@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.
- package/README.md +31 -0
- package/package.json +37 -0
- package/src/Axon.ts +260 -0
- package/src/cognet/cognet.ts +318 -0
- package/src/cognet/index.ts +4 -0
- package/src/index.ts +11 -0
- package/src/modules/context.ts +90 -0
- package/src/modules/index.ts +6 -0
- package/src/modules/load.ts +119 -0
- package/src/modules/modules.ts +87 -0
- package/src/modules/setup.ts +91 -0
- package/src/platform/blueprint.ts +201 -0
- package/src/platform/boot.ts +160 -0
- package/src/platform/bus.ts +207 -0
- package/src/platform/hooks.ts +30 -0
- package/src/platform/index.ts +18 -0
- package/src/platform/inject.ts +236 -0
- package/src/runtime/handle.ts +283 -0
- package/src/runtime/index.ts +2 -0
- package/src/runtime/inference.ts +221 -0
- package/src/runtime/runtime.ts +207 -0
- package/src/runtime/server/connect-auth.ts +123 -0
- package/src/runtime/server/endpoints.ts +257 -0
- package/src/runtime/server/h3.ts +33 -0
- package/src/runtime/server/index.ts +8 -0
- package/src/runtime/server/middleware.ts +59 -0
- package/src/runtime/server/plugins.ts +23 -0
- package/src/runtime/server/routes.ts +33 -0
- package/src/runtime/server/server.ts +138 -0
- package/src/runtime/server/session-view.ts +100 -0
- package/src/runtime/server/sse.ts +45 -0
- package/src/runtime/server/streams.ts +186 -0
- package/src/runtime/source/context.ts +67 -0
- package/src/runtime/source/render.ts +90 -0
- package/src/runtime/source/scripts.ts +55 -0
- package/src/tools/index.ts +11 -0
- package/src/tools/load.ts +119 -0
- package/src/tools/mediate.ts +92 -0
- package/src/tools/tools.ts +88 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import type { vstr as Vstr } from "@arcforge/vstr"
|
|
2
|
+
import { err } from "@arcforge/err"
|
|
3
|
+
import { promptContext } from "../runtime/source/context"
|
|
4
|
+
import type { AxonBlueprint } from "@arcforge/types"
|
|
5
|
+
import type { AxonSessionT } from "@arcforge/session"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `@arcforge/vstr` carries the whole Vue toolchain (@vue/compiler-sfc,
|
|
9
|
+
* runtime-core, server-renderer, turndown) — ~280ms of module evaluation, paid
|
|
10
|
+
* at IMPORT time by anything that reached the runtime. Only .vue prompts need
|
|
11
|
+
* it, so an agent with none, and every request that renders a static prompt,
|
|
12
|
+
* was paying for a compiler it never called.
|
|
13
|
+
*
|
|
14
|
+
* Loaded on first render and memoised: the cost moves to the first .vue
|
|
15
|
+
* render and is never paid twice.
|
|
16
|
+
*/
|
|
17
|
+
let vstrModule: Promise<{ vstr: typeof Vstr }> | null = null
|
|
18
|
+
function loadVstr(): Promise<{ vstr: typeof Vstr }> {
|
|
19
|
+
vstrModule ??= import("@arcforge/vstr")
|
|
20
|
+
return vstrModule
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
type BootOpts = {
|
|
25
|
+
blueprint: AxonBlueprint
|
|
26
|
+
/** Where captured console output from boot.vue's script gets committed. */
|
|
27
|
+
session: AxonSessionT
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const LOG_LEVELS = ["info", "warning", "error"] as const
|
|
31
|
+
type LogLevel = (typeof LOG_LEVELS)[number]
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Boot — the agent's base context. Static `boot.md` is a plain string,
|
|
35
|
+
* read once by the CLI. Dynamic `boot.vue` is a runtime concern: rendered
|
|
36
|
+
* fresh on every tick, with the real `axon` global in scope (read lazily
|
|
37
|
+
* off globalThis — Boot() is constructed before Axon() finishes wiring the
|
|
38
|
+
* handle, so it can never hold a direct reference; by the time render() is
|
|
39
|
+
* actually called, inject.runtime() has already fired).
|
|
40
|
+
*
|
|
41
|
+
* noCache is deliberate — a script-setup call to axon.tools.* must reflect
|
|
42
|
+
* current data on every tick, not a snapshot from the first render.
|
|
43
|
+
*
|
|
44
|
+
* boot.vue's `<script setup>` runs plain console.log/warn/error like any
|
|
45
|
+
* other userland code — those calls must show up as axon:log:* events in
|
|
46
|
+
* the session so the debugger sees them, without losing the real stdout
|
|
47
|
+
* write (a script author tailing their own terminal should still see it).
|
|
48
|
+
* Console is swapped for the duration of this render call only, restored
|
|
49
|
+
* in a finally — same scoped-swap-with-restore shape as the config
|
|
50
|
+
* loader's global patching, never a process-wide patch.
|
|
51
|
+
*/
|
|
52
|
+
export function Boot(opts: BootOpts) {
|
|
53
|
+
let blueprint = opts.blueprint
|
|
54
|
+
const session = opts.session
|
|
55
|
+
|
|
56
|
+
function captureConsole() {
|
|
57
|
+
const original = { log: console.log, warn: console.warn, error: console.error }
|
|
58
|
+
|
|
59
|
+
function wrap(level: LogLevel, original_: (...args: unknown[]) => void) {
|
|
60
|
+
return (...args: unknown[]) => {
|
|
61
|
+
original_(...args) // real stdout/stderr write is never blocked
|
|
62
|
+
// console.log cannot be async, so the commit is deliberately
|
|
63
|
+
// fire-and-forget. The catch is not optional: commit() rejects
|
|
64
|
+
// on a disk failure, and without it a full disk turns every
|
|
65
|
+
// console.log in boot.vue into an unhandled rejection that
|
|
66
|
+
// crashes the process. Losing one captured log line is the
|
|
67
|
+
// right trade against that — the real stdout write above
|
|
68
|
+
// already happened.
|
|
69
|
+
void session.commit(`axon:log:${level}`, { value: args.length === 1 ? args[0] : args })
|
|
70
|
+
.catch(() => {})
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
console.log = wrap("info", original.log)
|
|
75
|
+
console.warn = wrap("warning", original.warn)
|
|
76
|
+
console.error = wrap("error", original.error)
|
|
77
|
+
|
|
78
|
+
return () => {
|
|
79
|
+
console.log = original.log
|
|
80
|
+
console.warn = original.warn
|
|
81
|
+
console.error = original.error
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The last render that succeeded, for a boot.vue that has since broken.
|
|
87
|
+
*
|
|
88
|
+
* Null until one has. See render() for why this exists at all.
|
|
89
|
+
*/
|
|
90
|
+
let lastGood: string | null = null
|
|
91
|
+
|
|
92
|
+
async function render(): Promise<string | undefined> {
|
|
93
|
+
if (blueprint.boot !== undefined) return blueprint.boot
|
|
94
|
+
if (blueprint.bootFilePath === undefined) return undefined
|
|
95
|
+
|
|
96
|
+
const restore = captureConsole()
|
|
97
|
+
try {
|
|
98
|
+
const rendered = await (await loadVstr()).vstr(blueprint.bootFilePath, {
|
|
99
|
+
context: promptContext(),
|
|
100
|
+
noCache: true,
|
|
101
|
+
}).render()
|
|
102
|
+
lastGood = rendered
|
|
103
|
+
return rendered
|
|
104
|
+
} catch (cause) {
|
|
105
|
+
// vstr (generic tool, no @axon/err) throws plain on a malformed
|
|
106
|
+
// boot.vue — wrap at the boundary into the structured code.
|
|
107
|
+
const failure = err("BOOT_SCRIPT_INVALID", { cause, context: { path: blueprint.bootFilePath } })
|
|
108
|
+
|
|
109
|
+
// ── Never throw from here ───────────────────────────────────────
|
|
110
|
+
//
|
|
111
|
+
// render() is called by kernel.base() on EVERY tick, inside the
|
|
112
|
+
// cognet's render phase. A throw does not merely fail the boot: it
|
|
113
|
+
// kills the wake, so a typo saved mid-session stops the agent
|
|
114
|
+
// answering at all — while the user is editing the very file they
|
|
115
|
+
// would use it to fix.
|
|
116
|
+
//
|
|
117
|
+
// Falling back to the last good render is strictly better than
|
|
118
|
+
// empty: the agent keeps the identity and instructions it had a
|
|
119
|
+
// moment ago, which is almost always still what its author meant.
|
|
120
|
+
if (lastGood !== null) {
|
|
121
|
+
return `${lastGood}\n\n${degradedNote(failure.message, true)}`
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Nothing to fall back to — a boot.vue broken before it ever
|
|
125
|
+
// rendered. The agent runs WITHOUT its identity, which is a real
|
|
126
|
+
// loss and must not be silent: an agent with empty context answers
|
|
127
|
+
// confidently as a generic assistant, and the user cannot tell
|
|
128
|
+
// why it stopped sounding like theirs.
|
|
129
|
+
return degradedNote(failure.message, false)
|
|
130
|
+
} finally {
|
|
131
|
+
restore()
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* What the model is told when boot.vue would not render.
|
|
137
|
+
*
|
|
138
|
+
* Written to the MODEL, not the user — the user sees the structured error
|
|
139
|
+
* card. This is the sentence that stops the agent behaving as though
|
|
140
|
+
* nothing happened, and it says which of the two situations it is in
|
|
141
|
+
* because they call for different behaviour: stale instructions are worth
|
|
142
|
+
* following, no instructions are worth admitting to.
|
|
143
|
+
*/
|
|
144
|
+
function degradedNote(reason: string, stale: boolean): string {
|
|
145
|
+
return stale
|
|
146
|
+
? `<system-note>Your boot context failed to reload and the text above is the last version that worked. It may be out of date. Reason: ${reason}</system-note>`
|
|
147
|
+
: `<system-note>Your boot context could not be loaded, so you are running without the identity and instructions its author wrote. Say so if asked who you are or what you are for. Reason: ${reason}</system-note>`
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
render,
|
|
152
|
+
|
|
153
|
+
/** the agent changed: adopt the new blueprint — next render, never mid-render */
|
|
154
|
+
update(next: AxonBlueprint) {
|
|
155
|
+
blueprint = next
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export type AxonBootT = ReturnType<typeof Boot>
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { err } from "@arcforge/err"
|
|
2
|
+
import type { AxonEventMap } from "@arcforge/types"
|
|
3
|
+
|
|
4
|
+
// ── Types ─────────────────────────────────────────────────────────────────────
|
|
5
|
+
|
|
6
|
+
export type EventHandler<T> = (payload: T) => void | Promise<void>
|
|
7
|
+
|
|
8
|
+
export type BusHistoryEntry = {
|
|
9
|
+
event: string
|
|
10
|
+
payload: unknown
|
|
11
|
+
ts: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* AxonBus — the central observable event channel for the Axon runtime.
|
|
16
|
+
*
|
|
17
|
+
* Carries everything in AxonEventMap — runtime lifecycle (axon:boot:*,
|
|
18
|
+
* axon:shutdown:*, axon:reload:*), kernel and cognet telemetry, capsule
|
|
19
|
+
* events, and the session's entries. The session commit pipeline forwards
|
|
20
|
+
* each event here AFTER it is durable, so a bus subscriber never sees
|
|
21
|
+
* something that failed to persist.
|
|
22
|
+
*
|
|
23
|
+
* NOT the durable record — that is the session log. This is live
|
|
24
|
+
* notification: the server bridges it to SSE (/_axon/events), the TUI
|
|
25
|
+
* subscribes for live rendering, and tests assert against history(). An
|
|
26
|
+
* event that only reaches the bus is gone when the process ends.
|
|
27
|
+
*
|
|
28
|
+
* Distinct from Hooks(): this is many-to-many fire-and-forget notification;
|
|
29
|
+
* hooks are call-and-await-to-completion at a fixed runtime call point.
|
|
30
|
+
*
|
|
31
|
+
* Generic EventMap lets user-defined events be typed alongside built-ins.
|
|
32
|
+
*/
|
|
33
|
+
export type AxonBusT<EventMap extends Record<string, unknown> = AxonEventMap> = {
|
|
34
|
+
/**
|
|
35
|
+
* Emit an event. Awaits all registered handlers before resolving.
|
|
36
|
+
* Errors in handlers are caught and re-emitted as "axon:bus:error" (non-fatal).
|
|
37
|
+
*/
|
|
38
|
+
emit<K extends keyof (AxonEventMap & EventMap)>(
|
|
39
|
+
event: K,
|
|
40
|
+
payload: (AxonEventMap & EventMap)[K],
|
|
41
|
+
): Promise<void>
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Subscribe to an event. Returns an unsubscribe function.
|
|
45
|
+
* Handlers are called in registration order (use priority via hooks for ordering).
|
|
46
|
+
*/
|
|
47
|
+
on<K extends keyof (AxonEventMap & EventMap)>(
|
|
48
|
+
event: K,
|
|
49
|
+
handler: EventHandler<(AxonEventMap & EventMap)[K]>,
|
|
50
|
+
): () => void
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Subscribe to an event exactly once. Auto-unsubscribes after first call.
|
|
54
|
+
*/
|
|
55
|
+
once<K extends keyof (AxonEventMap & EventMap)>(
|
|
56
|
+
event: K,
|
|
57
|
+
handler: EventHandler<(AxonEventMap & EventMap)[K]>,
|
|
58
|
+
): () => void
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Unsubscribe a specific handler from an event.
|
|
62
|
+
*/
|
|
63
|
+
off(event: string, handler: EventHandler<unknown>): void
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* All events emitted since the bus was created, in order.
|
|
67
|
+
* Useful for test assertions and debugging.
|
|
68
|
+
* Optionally filter by event name or limit to last N entries.
|
|
69
|
+
*/
|
|
70
|
+
history(opts?: { limit?: number; event?: string }): BusHistoryEntry[]
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Clear the history buffer (e.g. between test cases).
|
|
74
|
+
*/
|
|
75
|
+
clearHistory(): void
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Subscribe to ALL events. Handler receives the event name and payload.
|
|
79
|
+
* Used by the WebSocket bus relay to forward events to connected TUI clients.
|
|
80
|
+
* Returns an unsubscribe function.
|
|
81
|
+
*/
|
|
82
|
+
onAny(handler: (event: string, payload: unknown) => void): () => void
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Relay an externally-typed event onto the bus without static payload
|
|
86
|
+
* checking — for boundaries that forward another system's event stream
|
|
87
|
+
* (capsule, Cognos). The event's own `type` field is the bus event name.
|
|
88
|
+
*/
|
|
89
|
+
forward(event: { type: string }): Promise<void>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ── Implementation ────────────────────────────────────────────────────────────
|
|
93
|
+
|
|
94
|
+
export function AxonBus<EventMap extends Record<string, unknown> = AxonEventMap>(opts?: { maxHistory?: number }): AxonBusT<EventMap> {
|
|
95
|
+
const maxHistory = opts?.maxHistory ?? 1000
|
|
96
|
+
type FullMap = AxonEventMap & EventMap
|
|
97
|
+
|
|
98
|
+
// handler map: event name → ordered list of handlers
|
|
99
|
+
const handlers = new Map<string, Array<EventHandler<unknown>>>()
|
|
100
|
+
|
|
101
|
+
// wildcard handlers — called for every emitted event
|
|
102
|
+
const anyHandlers = new Set<(event: string, payload: unknown) => void>()
|
|
103
|
+
|
|
104
|
+
// history ring — all emitted events, in order
|
|
105
|
+
const _history: BusHistoryEntry[] = []
|
|
106
|
+
|
|
107
|
+
function getHandlers(event: string): Array<EventHandler<unknown>> {
|
|
108
|
+
if (!handlers.has(event)) handlers.set(event, [])
|
|
109
|
+
return handlers.get(event)!
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function on(event: string, handler: EventHandler<unknown>): () => void {
|
|
113
|
+
getHandlers(event).push(handler)
|
|
114
|
+
return () => off(event, handler)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function once(event: string, handler: EventHandler<unknown>): () => void {
|
|
118
|
+
const wrapper: EventHandler<unknown> = async (payload) => {
|
|
119
|
+
off(event, wrapper)
|
|
120
|
+
await handler(payload)
|
|
121
|
+
}
|
|
122
|
+
return on(event, wrapper)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function off(event: string, handler: EventHandler<unknown>): void {
|
|
126
|
+
const list = handlers.get(event)
|
|
127
|
+
if (!list) return
|
|
128
|
+
const idx = list.indexOf(handler)
|
|
129
|
+
if (idx !== -1) list.splice(idx, 1)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Strip non-serialisable fields (functions) from a payload before storing in history. */
|
|
133
|
+
function sanitiseForHistory(payload: unknown): unknown {
|
|
134
|
+
if (payload === null || typeof payload !== "object") return payload
|
|
135
|
+
const result: Record<string, unknown> = {}
|
|
136
|
+
for (const [k, v] of Object.entries(payload as Record<string, unknown>)) {
|
|
137
|
+
if (typeof v !== "function") result[k] = v
|
|
138
|
+
}
|
|
139
|
+
return result
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function emit(event: string, payload: unknown): Promise<void> {
|
|
143
|
+
if (_history.length >= maxHistory) {
|
|
144
|
+
_history.shift()
|
|
145
|
+
}
|
|
146
|
+
_history.push({ event, payload: sanitiseForHistory(payload), ts: Date.now() })
|
|
147
|
+
|
|
148
|
+
const list = getHandlers(event).slice() // snapshot — handlers may mutate during iteration
|
|
149
|
+
for (const handler of list) {
|
|
150
|
+
try {
|
|
151
|
+
await handler(payload)
|
|
152
|
+
} catch (cause) {
|
|
153
|
+
// A handler failure is a real failure — plugins and modules
|
|
154
|
+
// register handlers, so a silently-broken one is invisible
|
|
155
|
+
// rot. Constructing it through err() delivers it to the
|
|
156
|
+
// session's error sink (errScope), which is what makes it
|
|
157
|
+
// durable; previously this only reached the in-memory
|
|
158
|
+
// history ring and stderr, so nothing about a failing
|
|
159
|
+
// plugin handler ever survived the process.
|
|
160
|
+
const failure = err("BUS_HANDLER_FAILED", {
|
|
161
|
+
detail: `handler for "${event}" threw`,
|
|
162
|
+
context: { event },
|
|
163
|
+
cause,
|
|
164
|
+
})
|
|
165
|
+
// Recursion guard: a failing axon:bus:error handler must not
|
|
166
|
+
// re-enter this path forever. Its own failure is already
|
|
167
|
+
// recorded by err() above.
|
|
168
|
+
if (event !== "axon:bus:error") {
|
|
169
|
+
await emit("axon:bus:error", { event, error: failure })
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Wildcard handlers are non-fatal, but failures are surfaced.
|
|
175
|
+
for (const handler of anyHandlers) {
|
|
176
|
+
try {
|
|
177
|
+
handler(event, payload)
|
|
178
|
+
} catch (anyHandlerError) {
|
|
179
|
+
console.warn(`[axon:bus] wildcard handler error on "${event}":`, anyHandlerError)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
emit: emit as AxonBusT<EventMap>["emit"],
|
|
186
|
+
on: on as AxonBusT<EventMap>["on"],
|
|
187
|
+
once: once as AxonBusT<EventMap>["once"],
|
|
188
|
+
off: off as AxonBusT<EventMap>["off"],
|
|
189
|
+
history(opts?: { limit?: number; event?: string }): BusHistoryEntry[] {
|
|
190
|
+
let result = opts?.event
|
|
191
|
+
? _history.filter(e => e.event === opts.event)
|
|
192
|
+
: [..._history]
|
|
193
|
+
if (opts?.limit !== undefined) {
|
|
194
|
+
result = result.slice(-opts.limit)
|
|
195
|
+
}
|
|
196
|
+
return result
|
|
197
|
+
},
|
|
198
|
+
clearHistory(): void { _history.length = 0 },
|
|
199
|
+
onAny(handler: (event: string, payload: unknown) => void): () => void {
|
|
200
|
+
anyHandlers.add(handler)
|
|
201
|
+
return () => { anyHandlers.delete(handler) }
|
|
202
|
+
},
|
|
203
|
+
forward(event: { type: string }): Promise<void> {
|
|
204
|
+
return emit(event.type, event)
|
|
205
|
+
},
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Hookable } from "hookable"
|
|
2
|
+
import type { AxonHooks } from "@arcforge/types"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Thin wrapper over Hookable, typed against the `AxonHooks` contract in
|
|
6
|
+
* @arcforge/types. One instance per runtime, constructed before Plugins() runs
|
|
7
|
+
* so `axon.hooks.hook(...)` registrations land before any call point fires.
|
|
8
|
+
*
|
|
9
|
+
* Distinct from AxonBus: this is call-and-await-to-completion at a fixed
|
|
10
|
+
* runtime call point, not many-to-many fire-and-forget notification.
|
|
11
|
+
*/
|
|
12
|
+
export function Hooks() {
|
|
13
|
+
const hookable = new Hookable<AxonHooks>()
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
hook: hookable.hook.bind(hookable),
|
|
17
|
+
callHook: hookable.callHook.bind(hookable),
|
|
18
|
+
removeHook: hookable.removeHook.bind(hookable),
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Clears every registration. AxonServer() rebuilds from scratch on
|
|
22
|
+
* every reload and reruns Plugins() in full — without this, a
|
|
23
|
+
* plugin's hook.hook() calls would accumulate one extra registration
|
|
24
|
+
* per reload, firing handlers multiple times for a single event.
|
|
25
|
+
*/
|
|
26
|
+
reset: hookable.removeAllHooks.bind(hookable),
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type AxonHooksT = ReturnType<typeof Hooks>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Platform — the runtime's shared infrastructure.
|
|
3
|
+
*
|
|
4
|
+
* Everything here is constructed once at the Axon() seam and handed to
|
|
5
|
+
* whoever needs it: the event bus, the lifecycle hooks, the blueprint
|
|
6
|
+
* normalizer, the global injector, boot-time identity rendering. None of it
|
|
7
|
+
* knows about cognition, execution, or HTTP — those layers depend on this
|
|
8
|
+
* one, never the reverse.
|
|
9
|
+
*
|
|
10
|
+
* This index IS the boundary. Import from `../platform`, never from
|
|
11
|
+
* `../platform/bus` or any other file inside: reaching past it means either
|
|
12
|
+
* the thing belongs in this list or it should not be reached at all.
|
|
13
|
+
*/
|
|
14
|
+
export { AxonBus, type AxonBusT, type BusHistoryEntry, type EventHandler } from "./bus"
|
|
15
|
+
export { Hooks, type AxonHooksT } from "./hooks"
|
|
16
|
+
export { AxonBlueprint, mergeBlueprint } from "./blueprint"
|
|
17
|
+
export { Inject } from "./inject"
|
|
18
|
+
export { Boot } from "./boot"
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
2
|
+
import { err } from "@arcforge/err"
|
|
3
|
+
import { defineArgs, defineAxonPlugin, defineMiddleware, defineModule, defineProps, definePrompt } from "@arcforge/types"
|
|
4
|
+
import type { AxonBlueprint, AxonHandle } from "@arcforge/types"
|
|
5
|
+
|
|
6
|
+
const argsStorage = new AsyncLocalStorage<Record<string, unknown>>()
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Args for the one place ALS cannot reach: a dynamic `import()`'s module
|
|
10
|
+
* evaluation.
|
|
11
|
+
*
|
|
12
|
+
* Scripts are invoked by importing them, and ALS context does NOT propagate
|
|
13
|
+
* across that boundary in Bun — neither into the synchronous top-level body
|
|
14
|
+
* nor after an `await` inside it, so `args` read at a script's top level saw
|
|
15
|
+
* an empty object no matter what was passed.
|
|
16
|
+
*
|
|
17
|
+
* Keyed by RUN ID, not a single serialized slot. The slot version was a real
|
|
18
|
+
* race: `withArgs` saved the previous value and restored it in a `finally`,
|
|
19
|
+
* so two overlapping invocations interleaved on one variable — A sets, B sets,
|
|
20
|
+
* A reads B's args. Reproduced deterministically (A in flight reading
|
|
21
|
+
* `{who:"B"}`), and it surfaced as non-deterministic failures in
|
|
22
|
+
* tests/integration/handle/scripts.test.ts the moment the suite ran with
|
|
23
|
+
* --parallel. Nothing threw; a script simply ran against another call's args.
|
|
24
|
+
*
|
|
25
|
+
* The run ID is the cache-bust token the script specifier already carries
|
|
26
|
+
* (see runtime/source/scripts.ts), so the script reads its args back through
|
|
27
|
+
* `args` with no ambiguity about which invocation it belongs to, however many
|
|
28
|
+
* are in flight.
|
|
29
|
+
*/
|
|
30
|
+
const runArgs = new Map<string, Record<string, unknown>>()
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the args for whichever run is asking.
|
|
34
|
+
*
|
|
35
|
+
* There is deliberately NO "current run" variable. Any single slot — however
|
|
36
|
+
* carefully saved and restored — is a race the moment two invocations overlap,
|
|
37
|
+
* which is exactly the bug this replaced. Instead the caller is identified from
|
|
38
|
+
* the stack: a script's frames carry its own specifier, and that specifier
|
|
39
|
+
* carries the run id (`...?run=<uuid>`), so each concurrent script resolves to
|
|
40
|
+
* its own entry with nothing shared between them.
|
|
41
|
+
*
|
|
42
|
+
* Falls back to the sole in-flight run when the stack carries no run id. That
|
|
43
|
+
* covers an `args` read from a helper the script imported (a separate module,
|
|
44
|
+
* its own frames) while keeping the ambiguous case honest: with more than one
|
|
45
|
+
* run in flight there is no defensible answer, so it yields `{}` rather than
|
|
46
|
+
* guessing and handing a script another call's args.
|
|
47
|
+
*/
|
|
48
|
+
function argsForCaller(): Record<string, unknown> | undefined {
|
|
49
|
+
const stack = new Error().stack ?? ""
|
|
50
|
+
for (const [runId, args] of runArgs) {
|
|
51
|
+
if (stack.includes(`run=${runId}`)) return args
|
|
52
|
+
}
|
|
53
|
+
return runArgs.size === 1 ? runArgs.values().next().value : undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Owns every global mutation in the runtime. All globalThis writes live
|
|
58
|
+
* here, nowhere else — this is the one place to audit for it.
|
|
59
|
+
*
|
|
60
|
+
* Two phases, same pattern as the old inject.ts:
|
|
61
|
+
* macros() — noop globals, safe to import before the runtime exists.
|
|
62
|
+
* Any call throws INJECT_OUTSIDE_RUNTIME.
|
|
63
|
+
* runtime() — swaps in the live handle once Axon() has fully built it.
|
|
64
|
+
*
|
|
65
|
+
* `args` is scoped per-invocation: AsyncLocalStorage wherever context
|
|
66
|
+
* propagates, and a run-id-keyed map for the dynamic-import window where it
|
|
67
|
+
* does not (see runArgs above). Two concurrent script/tool calls each get
|
|
68
|
+
* their own args regardless of interleaving.
|
|
69
|
+
*/
|
|
70
|
+
export function Inject() {
|
|
71
|
+
function outsideRuntime(): never {
|
|
72
|
+
throw err("INJECT_OUTSIDE_RUNTIME")
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const inject = {
|
|
76
|
+
macros() {
|
|
77
|
+
const g = globalThis as Record<string, unknown>
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The AUTHORING globals a config file calls at module scope.
|
|
81
|
+
*
|
|
82
|
+
* `module.config.ts` starts with `export default defineModule({…})`,
|
|
83
|
+
* so importing one needs `defineModule` to already exist. The
|
|
84
|
+
* platform's blueprint scanner installs these during the build —
|
|
85
|
+
* which is fine while the build and the runtime share a process,
|
|
86
|
+
* and wrong the moment they do not: a confined agent imports its
|
|
87
|
+
* modules in its OWN process, where nothing had installed them, and
|
|
88
|
+
* boot died with "defineModule is not defined".
|
|
89
|
+
*
|
|
90
|
+
* Installed here because this is the one place that owns globalThis
|
|
91
|
+
* writes, and `??=` so the scanner's copies win where both run —
|
|
92
|
+
* they are the same identity functions either way.
|
|
93
|
+
*/
|
|
94
|
+
g.defineModule ??= defineModule
|
|
95
|
+
g.definePrompt ??= definePrompt
|
|
96
|
+
g.defineArgs ??= defineArgs
|
|
97
|
+
g.defineProps ??= defineProps
|
|
98
|
+
g.defineMiddleware ??= defineMiddleware
|
|
99
|
+
g.defineAxonPlugin ??= defineAxonPlugin
|
|
100
|
+
|
|
101
|
+
g.axon = new Proxy({}, {
|
|
102
|
+
get: outsideRuntime,
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
Object.defineProperty(g, "args", {
|
|
106
|
+
configurable: true,
|
|
107
|
+
get: outsideRuntime,
|
|
108
|
+
})
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* `loaded` is a THUNK returning the live tool scope, not a value: a
|
|
113
|
+
* hot reload rebuilds that scope, and a captured map would keep
|
|
114
|
+
* serving the tool the author just deleted.
|
|
115
|
+
*/
|
|
116
|
+
runtime(axon: AxonHandle, blueprint?: AxonBlueprint, loaded?: () => Record<string, unknown>) {
|
|
117
|
+
const g = globalThis as Record<string, unknown>
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* `globalThis.axon` serves TWO audiences that used to live in
|
|
121
|
+
* different processes.
|
|
122
|
+
*
|
|
123
|
+
* Script-land sees the AxonHandle — `axon.request()`,
|
|
124
|
+
* `axon.tools.*`, the curated surface agent-authored code is
|
|
125
|
+
* written against. TOOL code sees the capsule's ambient, whose
|
|
126
|
+
* only member is `activity()`: write-only telemetry that grants
|
|
127
|
+
* nothing, which a tool calls as `globalThis.axon?.activity(...)`.
|
|
128
|
+
*
|
|
129
|
+
* Two objects, one name, and it never mattered while the capsule
|
|
130
|
+
* had its own global object. In one heap whichever installs last
|
|
131
|
+
* wins — and the runtime installs after the capsule, so every tool
|
|
132
|
+
* calling `activity()` hit "not a function" on a handle that had
|
|
133
|
+
* no such member.
|
|
134
|
+
*
|
|
135
|
+
* Merged rather than ordered: an install order that happens to
|
|
136
|
+
* work is not a contract, and a tool has no way to reach a
|
|
137
|
+
* different global. The ambient's members are carried forward, so
|
|
138
|
+
* both audiences find what they were promised on the one name they
|
|
139
|
+
* both use.
|
|
140
|
+
*/
|
|
141
|
+
const ambient = g.axon as { activity?: unknown } | undefined
|
|
142
|
+
g.axon = ambient?.activity
|
|
143
|
+
// A PROXY, not a spread: the handle exposes `tools` and
|
|
144
|
+
// `ready` as GETTERS that a reload replaces, and copying them
|
|
145
|
+
// would freeze both at their boot values — a script would keep
|
|
146
|
+
// calling the tool map from before the author's edit. Every
|
|
147
|
+
// miss forwards to the live handle; `activity` is the one own
|
|
148
|
+
// member.
|
|
149
|
+
? new Proxy(axon as object, {
|
|
150
|
+
get: (target, key, receiver) => key === "activity"
|
|
151
|
+
? ambient.activity
|
|
152
|
+
: Reflect.get(target, key, target),
|
|
153
|
+
has: (target, key) => key === "activity" || Reflect.has(target, key),
|
|
154
|
+
}) as AxonHandle
|
|
155
|
+
: axon
|
|
156
|
+
|
|
157
|
+
Object.defineProperty(g, "args", {
|
|
158
|
+
configurable: true,
|
|
159
|
+
get: () => argsStorage.getStore() ?? argsForCaller() ?? {},
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
installToolGlobals(g, loaded?.() ?? {})
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Run fn with `args` scoped to this call only — safe under concurrency.
|
|
167
|
+
*
|
|
168
|
+
* `runId` must uniquely identify this invocation; callers importing a
|
|
169
|
+
* script pass the same token they cache-bust the specifier with, so a
|
|
170
|
+
* top-level read inside that module resolves to these args and no
|
|
171
|
+
* other in-flight call's.
|
|
172
|
+
*/
|
|
173
|
+
async withArgs<T>(runId: string, args: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {
|
|
174
|
+
runArgs.set(runId, args)
|
|
175
|
+
try {
|
|
176
|
+
return await argsStorage.run(args, fn)
|
|
177
|
+
} finally {
|
|
178
|
+
runArgs.delete(runId)
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return inject
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Tool globals installed by the last runtime() call, so a reinstall can retract them. */
|
|
187
|
+
let installedToolGlobals: string[] = []
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Tool exports as globals — the agent's whole scope, in one heap.
|
|
191
|
+
*
|
|
192
|
+
* Everything exported from `src/tools/*.ts` (a module's included) lands here
|
|
193
|
+
* under its OWN export name, unaugmented. Filenames group; they do not
|
|
194
|
+
* namespace. `export function add()` is `add()`; `export const fs = {...}`
|
|
195
|
+
* is `fs.read()`. That is the entire rule, and it is the same one the
|
|
196
|
+
* generated `.agent/tool-globals.d.ts` declares.
|
|
197
|
+
*
|
|
198
|
+
* ONE INSTALLER, ONE SOURCE. These come from the loaded tool scope — the
|
|
199
|
+
* same `scope.globals()` the model's own code executes against — so
|
|
200
|
+
* script-land, prompts, routes, hooks and model-emitted code cannot see
|
|
201
|
+
* different shapes of the same tool. There used to be a second installer
|
|
202
|
+
* here projecting `axon.tools.<file>.<export>`, which double-wrapped a
|
|
203
|
+
* module exporting one object (`fs` became `{ fs: {...} }`) and silently
|
|
204
|
+
* clobbered the correct binding. Both the projection and the surface it
|
|
205
|
+
* read are gone.
|
|
206
|
+
*
|
|
207
|
+
* The values are ALREADY MEDIATED — the loader wraps every export before it
|
|
208
|
+
* reaches this scope — so policy, tracing and escalation are enforced by
|
|
209
|
+
* calling them, not by any wrapping done here.
|
|
210
|
+
*
|
|
211
|
+
* Binding is to the runtime that owns this process — one agent, one global
|
|
212
|
+
* scope. Cross-agent tool calls are deliberately not a thing: a second
|
|
213
|
+
* agent is a second process, and a global that could mean either agent's
|
|
214
|
+
* tool is a footgun rather than a feature.
|
|
215
|
+
*/
|
|
216
|
+
function installToolGlobals(g: Record<string, unknown>, loaded: Record<string, unknown>): void {
|
|
217
|
+
// A reload rebuilds the scope. Retract the previous set first so a tool
|
|
218
|
+
// the author deleted does not linger as a callable global.
|
|
219
|
+
for (const name of installedToolGlobals) delete g[name]
|
|
220
|
+
installedToolGlobals = []
|
|
221
|
+
|
|
222
|
+
for (const [name, value] of Object.entries(loaded)) {
|
|
223
|
+
// Tool vs tool is fatal: two files exporting the same name give the
|
|
224
|
+
// author no way to say which they meant, and last-one-wins picks
|
|
225
|
+
// silently. Tool vs HOST BUILTIN is not a collision — `@axon/fs`
|
|
226
|
+
// exporting `fs` is the author's explicit declaration and the whole
|
|
227
|
+
// point of installing it, so the tool takes the name. The builtin
|
|
228
|
+
// stays reachable the correct way, by importing `node:fs`.
|
|
229
|
+
if (installedToolGlobals.includes(name)) {
|
|
230
|
+
throw err("TOOL_GLOBAL_COLLISION", { context: { name } })
|
|
231
|
+
}
|
|
232
|
+
g[name] = value
|
|
233
|
+
installedToolGlobals.push(name)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|