@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,90 @@
1
+ import type { AxonBlueprint, ModuleSetupAxon } from "@arcforge/types"
2
+ import { err } from "@arcforge/err"
3
+ import type { AxonSessionT } from "@arcforge/session"
4
+ import type { AxonHooksT } from "../platform"
5
+
6
+ /**
7
+ * The narrow `axon` handle a module's `setup()` receives. Deliberately
8
+ * smaller than the full AxonHandle: a module registers boot-time wiring
9
+ * (hooks, policy) and may SENSE (`stim`) — it does not run conversations.
10
+ * `request`/`stream` are withheld on purpose; `stim` is not, because a
11
+ * channel module is a sense organ and sensing is not cognition. Everything
12
+ * here is a thin projection over pieces Axon() already built; the context
13
+ * owns no state.
14
+ *
15
+ * `server` and `tools` are declared by the type but throw loudly: no module
16
+ * consumes them yet, and wiring dynamic routes from setup() means teaching
17
+ * AxonServer about a second, runtime route source — a boundary decision to
18
+ * make when a real module needs it, not a silent stub that returns nothing.
19
+ */
20
+ export function ModuleContext(opts: {
21
+ blueprint: AxonBlueprint
22
+ hooks: AxonHooksT
23
+ /** Backs `stim()` — a channel module's wire into the session's sense pathway. */
24
+ session: AxonSessionT
25
+ /** Sink for teardown callbacks registered via ctx.onDispose(). Owned by the caller (runSetup), which runs them in reverse. */
26
+ onDispose: (fn: () => void | Promise<void>) => void
27
+ }): ModuleSetupAxon {
28
+ const { blueprint, hooks, session } = opts
29
+
30
+ // The narrow module handle intentionally exposes hooks with a loose
31
+ // (string, ...any[]) signature — a module registers against hook names by
32
+ // string, not against the runtime's internal typed AxonHooks map. Bridge
33
+ // the two at this one seam.
34
+ const hook: ModuleSetupAxon["hook"] = hooks.hook as ModuleSetupAxon["hook"]
35
+ const callHook: ModuleSetupAxon["callHook"] = hooks.callHook as ModuleSetupAxon["callHook"]
36
+
37
+ return {
38
+ hook,
39
+ callHook,
40
+ onDispose: opts.onDispose,
41
+
42
+ // Straight through to the session's sense pathway — the same door
43
+ // AxonHandle.stim uses. Granted to modules because sensing is not
44
+ // cognition: a channel module delivers what its transport received
45
+ // and never decides what was worth delivering.
46
+ stim: session.stimuli.ingest,
47
+
48
+ warn: async (message: string) => {
49
+ await session.commit("build:warning", { domain: "module", message })
50
+ },
51
+
52
+ env: {
53
+ get: key => blueprint.env[key],
54
+ require: key => {
55
+ const value = blueprint.env[key]
56
+ if (value === undefined || value === "") {
57
+ throw err("MODULE_ENV_REQUIRED", { detail: `module setup requires env var "${key}"`, context: { key } })
58
+ }
59
+ return value
60
+ },
61
+ },
62
+
63
+ policy: {
64
+ // Modules declare policy needs statically (ModulePolicyNeeds); the
65
+ // CLI reconciles them at install. Runtime mutation of the resolved
66
+ // policy from setup() is not a capability we grant — the resolved
67
+ // agent policy is authoritative and immutable at boot.
68
+ update: () => {
69
+ throw err("MODULE_POLICY_IMMUTABLE", {
70
+ detail: "policy.update() from setup() — declare policy needs statically in module.config.ts",
71
+ })
72
+ },
73
+ },
74
+
75
+ server: {
76
+ addRoute: () => {
77
+ throw err("MODULE_SERVER_NOT_WIRED", { detail: "ctx.server.addRoute — declare routes as server/api/ files in the module" })
78
+ },
79
+ addMiddleware: () => {
80
+ throw err("MODULE_SERVER_NOT_WIRED", { detail: "ctx.server.addMiddleware — not wired" })
81
+ },
82
+ },
83
+
84
+ tools: {
85
+ get: () => {
86
+ throw err("MODULE_SERVER_NOT_WIRED", { detail: "ctx.tools.get — not wired" })
87
+ },
88
+ },
89
+ }
90
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Modules — the agent's declared modules, executed at boot.
3
+ *
4
+ * Modules() is the boundary; loadModule/runSetup are its internals.
5
+ */
6
+ export { Modules, type ModulesT } from "./modules"
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto"
2
+ import { pathToFileURL } from "node:url"
3
+ import { readFile } from "node:fs/promises"
4
+ import type { AxonModule, ModuleConfig, ModuleOptionSchema } from "@arcforge/types"
5
+ import { err } from "@arcforge/err"
6
+
7
+ /** A module's config imported and validated, ready to run setup(). */
8
+ export type LoadedModule = {
9
+ module: AxonModule
10
+ config: ModuleConfig
11
+ /** SHA-256 of the config file bytes — the determinism fingerprint. */
12
+ configHash: string
13
+ /** Options validated against the module's schema, with defaults applied. */
14
+ options: Record<string, unknown>
15
+ }
16
+
17
+ /**
18
+ * Import a module's module.config.ts by its blueprint-resolved `configPath`
19
+ * and validate its declared options. A module that cannot import, or whose
20
+ * options violate its schema, fails the whole boot — the runtime never runs a
21
+ * partially-wired agent (Hard Invariant #1, #6).
22
+ *
23
+ * The config is re-imported per boot (cache-busted) so a hot-reload picks up
24
+ * edits; the content hash records exactly which bytes ran, so two boots of the
25
+ * same blueprint are provably the same wiring.
26
+ */
27
+ export async function loadModule(module: AxonModule): Promise<LoadedModule> {
28
+ const bytes = await readConfigBytes(module.configPath)
29
+ const configHash = createHash("sha256").update(bytes).digest("hex")
30
+
31
+ let config: ModuleConfig
32
+ try {
33
+ // Cache-bust so watch-mode reloads re-evaluate. randomUUID (not a
34
+ // timestamp) — repeated imports in one millisecond would otherwise
35
+ // share Bun's module cache and silently serve stale bytes.
36
+ //
37
+ // pathToFileURL FIRST. Appending a query to a bare filesystem path
38
+ // makes the runtime read the whole string as a URL, and a module
39
+ // imported by URL resolves its own bare specifiers against that URL
40
+ // rather than by walking node_modules from its directory. A module
41
+ // importing only relative paths survived that; one importing a real
42
+ // dependency (`discord.js`) failed with "Cannot find package" naming
43
+ // the cache-busted path — the query string was the tell.
44
+ const url = `${pathToFileURL(module.configPath).href}?t=${crypto.randomUUID()}`
45
+ const imported = (await import(url)) as { default?: ModuleConfig }
46
+ if (!imported.default || typeof imported.default !== "object") {
47
+ throw new Error("module.config.ts has no default export")
48
+ }
49
+ config = imported.default
50
+ } catch (cause) {
51
+ throw err("MODULE_CONFIG_LOAD_FAILED", {
52
+ detail: `${module.name} — ${cause instanceof Error ? cause.message : String(cause)}`,
53
+ context: { name: module.name, configPath: module.configPath },
54
+ cause,
55
+ })
56
+ }
57
+
58
+ const options = validateOptions(module)
59
+ return { module, config, configHash, options }
60
+ }
61
+
62
+ async function readConfigBytes(configPath: string): Promise<Buffer> {
63
+ try {
64
+ return await readFile(configPath)
65
+ } catch (cause) {
66
+ throw err("MODULE_CONFIG_LOAD_FAILED", {
67
+ detail: `cannot read ${configPath}`,
68
+ context: { configPath },
69
+ cause,
70
+ })
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Validate the agent-supplied options against the module's schema and apply
76
+ * declared defaults.
77
+ *
78
+ * Takes the blueprint's module entry alone, deliberately: the schema there
79
+ * was AST-scraped at scan time and is the validation authority. The imported
80
+ * config drives behaviour only and is never re-read for options, so the two
81
+ * cannot disagree about what a module accepts.
82
+ */
83
+ function validateOptions(module: AxonModule): Record<string, unknown> {
84
+ const supplied = module.options ?? {}
85
+ const schema = module.optionsSchema ?? {}
86
+ const resolved: Record<string, unknown> = {}
87
+
88
+ for (const [key, spec] of Object.entries(schema)) {
89
+ const value = supplied[key]
90
+
91
+ if (value === undefined) {
92
+ if (spec.default !== undefined) resolved[key] = spec.default
93
+ else if (spec.required) {
94
+ throw err("MODULE_OPTIONS_INVALID", {
95
+ detail: `module "${module.name}" requires option "${key}"`,
96
+ context: { name: module.name, option: key },
97
+ })
98
+ }
99
+ continue
100
+ }
101
+
102
+ if (!typeMatches(value, spec)) {
103
+ throw err("MODULE_OPTIONS_INVALID", {
104
+ detail: `module "${module.name}" option "${key}" expected ${spec.type}, got ${typeof value}`,
105
+ context: { name: module.name, option: key, expected: spec.type, actual: typeof value },
106
+ })
107
+ }
108
+ resolved[key] = value
109
+ }
110
+
111
+ return resolved
112
+ }
113
+
114
+ function typeMatches(value: unknown, spec: ModuleOptionSchema): boolean {
115
+ if (spec.type === "string") return typeof value === "string"
116
+ if (spec.type === "number") return typeof value === "number"
117
+ if (spec.type === "boolean") return typeof value === "boolean"
118
+ return false
119
+ }
@@ -0,0 +1,87 @@
1
+ import type { AxonBlueprint } from "@arcforge/types"
2
+ import type { AxonSessionT } from "@arcforge/session"
3
+ import type { AxonHooksT } from "../platform"
4
+ import { loadModule } from "./load"
5
+ import { runSetup, type LiveModule } from "./setup"
6
+
7
+ /**
8
+ * Modules — the boot-time executor for the agent's declared modules.
9
+ *
10
+ * For each module in the blueprint (in blueprint order — the flattened,
11
+ * declaration-ordered list the scanner produced), imports its module.config.ts
12
+ * by the statically-resolved `configPath`, validates options, and runs
13
+ * `setup(ctx)` against a narrow `axon` handle. Setup is SEQUENTIAL and total:
14
+ * a failure aborts the whole boot, so the only outcomes are "every module
15
+ * wired in order" or "boot failed at module K" — never a half-wired agent.
16
+ *
17
+ * The handle is a manager (Coding Standards): it owns the live module set as
18
+ * swappable `current` state. `reload()` disposes the current set in reverse
19
+ * order, then re-runs setup for the new blueprint — reload is exactly
20
+ * shutdown+boot, so a reloaded agent is identical to a freshly-booted one.
21
+ *
22
+ * Determinism: same blueprint (same modules, order, options, config bytes) ⇒
23
+ * same setup sequence ⇒ same wired state, or failure at the same point. The
24
+ * session log (module:setup:* / module:dispose:*) is the replayable proof.
25
+ */
26
+ export async function Modules(opts: {
27
+ blueprint: AxonBlueprint
28
+ hooks: AxonHooksT
29
+ session: AxonSessionT
30
+ }): Promise<ModulesT> {
31
+ const { hooks, session } = opts
32
+
33
+ let live: LiveModule[] = await setupAll(opts.blueprint)
34
+
35
+ async function setupAll(blueprint: AxonBlueprint): Promise<LiveModule[]> {
36
+ const result: LiveModule[] = []
37
+ // Sequential, blueprint order — the deterministic contract.
38
+ for (const module of blueprint.modules) {
39
+ const loaded = await loadModule(module)
40
+ result.push(await runSetup({ loaded, blueprint, hooks, session }))
41
+ }
42
+ return result
43
+ }
44
+
45
+ async function disposeAll(): Promise<void> {
46
+ // Reverse module order — a module tears down before the ones declared
47
+ // before it, which it may depend on. Errors are isolated per module.
48
+ const failures: unknown[] = []
49
+ for (const module of [...live].reverse()) {
50
+ try {
51
+ await module.dispose()
52
+ } catch (cause) {
53
+ failures.push(cause)
54
+ }
55
+ }
56
+ live = []
57
+ if (failures.length > 0) throw new AggregateError(failures, "module teardown completed with failures")
58
+ }
59
+
60
+ return {
61
+ get current() {
62
+ return live
63
+ },
64
+
65
+ /**
66
+ * Set up modules for a blueprint. Used on reload AFTER dispose() and
67
+ * the server rebuild, because AxonServer resets all hooks — a module's
68
+ * setup() hooks must re-register after that reset to survive. Boot
69
+ * calls setupAll directly; reload splits dispose/setup around the
70
+ * server rebuild, which is why these are two methods, not one reload().
71
+ */
72
+ async setup(blueprint: AxonBlueprint) {
73
+ live = await setupAll(blueprint)
74
+ },
75
+
76
+ /** Teardown: dispose every module in reverse order. Empties the live set. */
77
+ async dispose() {
78
+ await disposeAll()
79
+ },
80
+ }
81
+ }
82
+
83
+ export type ModulesT = {
84
+ readonly current: LiveModule[]
85
+ setup(blueprint: AxonBlueprint): Promise<void>
86
+ dispose(): Promise<void>
87
+ }
@@ -0,0 +1,91 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonBlueprint } from "@arcforge/types"
3
+ import type { AxonSessionT } from "@arcforge/session"
4
+ import type { AxonHooksT } from "../platform"
5
+ import { ModuleContext } from "./context"
6
+ import type { LoadedModule } from "./load"
7
+
8
+ /**
9
+ * One live module — the result of running a module's `setup()`. Holds the
10
+ * disposers it registered via `ctx.onDispose()` so its live resources can be
11
+ * released in reverse order on shutdown or reload.
12
+ */
13
+ export type LiveModule = {
14
+ name: string
15
+ dispose: () => Promise<void>
16
+ }
17
+
18
+ /**
19
+ * Run a single module's `setup(ctx)` and record the transaction to the session
20
+ * log. Emits module:setup:start (with the config hash — the determinism
21
+ * fingerprint) then :complete or :failed. A throwing setup fails loudly: the
22
+ * caller aborts the whole boot rather than continue with a half-wired agent.
23
+ *
24
+ * Disposers registered during setup are captured here and returned as one
25
+ * reverse-order teardown, wrapped in its own span bracket.
26
+ */
27
+ export async function runSetup(opts: {
28
+ loaded: LoadedModule
29
+ blueprint: AxonBlueprint
30
+ hooks: AxonHooksT
31
+ session: AxonSessionT
32
+ }): Promise<LiveModule> {
33
+ const { loaded, blueprint, hooks, session } = opts
34
+ const { module, config, configHash, options } = loaded
35
+
36
+ await session.commit("module:setup:start", { name: module.name, configHash, options })
37
+ const started = Date.now()
38
+
39
+ const disposers: Array<() => void | Promise<void>> = []
40
+ const axon = ModuleContext({ blueprint, hooks, session, onDispose: fn => disposers.push(fn) })
41
+
42
+ // A module with no setup() is legal — it contributes tools/prompts
43
+ // statically and needs no boot-time wiring.
44
+ if (config.setup) {
45
+ try {
46
+ // options was validated against module.optionsSchema in loadModule
47
+ // — it satisfies the module's typed option shape. The generic is
48
+ // erased on ModuleConfig here, so the runtime-validated bag is the
49
+ // honest input to the typed setup at this one seam.
50
+ await config.setup({ axon, options: options as Parameters<NonNullable<typeof config.setup>>[0]["options"] })
51
+ } catch (cause) {
52
+ const failure = err("MODULE_SETUP_FAILED", {
53
+ detail: `${module.name} — ${cause instanceof Error ? cause.message : String(cause)}`,
54
+ context: { name: module.name },
55
+ cause,
56
+ })
57
+ await session.commit("module:setup:failed", { name: module.name, error: failure, durationMs: Date.now() - started })
58
+ throw failure
59
+ }
60
+ }
61
+
62
+ await session.commit("module:setup:complete", { name: module.name, durationMs: Date.now() - started })
63
+
64
+ return {
65
+ name: module.name,
66
+ dispose: async () => {
67
+ const disposeStarted = Date.now()
68
+ await session.commit("module:dispose:start", { name: module.name })
69
+ // Reverse registration order within the module — later-acquired
70
+ // resources release before the earlier ones they may depend on.
71
+ const failures: unknown[] = []
72
+ for (const fn of [...disposers].reverse()) {
73
+ try {
74
+ await fn()
75
+ } catch (cause) {
76
+ failures.push(cause)
77
+ }
78
+ }
79
+ if (failures.length > 0) {
80
+ const failure = err("MODULE_SETUP_FAILED", {
81
+ detail: `${module.name} dispose failed`,
82
+ context: { name: module.name },
83
+ cause: new AggregateError(failures),
84
+ })
85
+ await session.commit("module:dispose:failed", { name: module.name, error: failure, durationMs: Date.now() - disposeStarted })
86
+ throw failure
87
+ }
88
+ await session.commit("module:dispose:complete", { name: module.name, durationMs: Date.now() - disposeStarted })
89
+ },
90
+ }
91
+ }
@@ -0,0 +1,201 @@
1
+ import { resolve } from "node:path"
2
+ import { err } from "@arcforge/err"
3
+ import type { AxonBlueprint as AxonBlueprintT, AxonConfig, AxonPartialBlueprint } from "@arcforge/types"
4
+
5
+ /**
6
+ * Config every agent starts from before its own axon.config.ts is merged in.
7
+ * Deliberately near-empty: an unset field means "the runtime decides", and the
8
+ * one entry here exists so `config.policy` is always an object to spread into
9
+ * rather than a null check at every read site.
10
+ */
11
+ const DEFAULT_CONFIG: Partial<AxonConfig> = {
12
+ policy: {},
13
+ }
14
+
15
+ /**
16
+ * Normalizes a partial blueprint from the CLI into the strict AxonBlueprint
17
+ * shape everything downstream trusts. This is the one seam where every field
18
+ * gets a default — nothing past this point should ever check `?? fallback`
19
+ * on a blueprint field. Agent identity (name/version/hash) defaults to an
20
+ * unnamed dev identity when the CLI hasn't resolved one yet (e.g. tests,
21
+ * ad-hoc `Axon()` calls) — it is not load-bearing for the runtime itself.
22
+ */
23
+ export function AxonBlueprint(input?: AxonPartialBlueprint): AxonBlueprintT {
24
+ const partial = input ?? {}
25
+
26
+ // Hard invariant: an agent without a brain does not work. The CLI (or
27
+ // test) must construct and pass the cognet definition — the runtime
28
+ // ships none and never defaults one.
29
+ if (!partial.cognet) {
30
+ throw err("NO_COGNET")
31
+ }
32
+
33
+ // NO process-global session handle: a process may host several Axon()
34
+ // runtimes at once, and any env var naming "the" session is clobbered
35
+ // by whichever booted last. Error attribution flows through err()'s
36
+ // AsyncLocalStorage scope (session.scope, established at the runtime's
37
+ // entry points); a failed boot's thrown error carries its own
38
+ // sessionId/sessionFile in context (see Axon.ts).
39
+ const sessionId = partial.session?.id ?? crypto.randomUUID()
40
+
41
+ const blueprint: AxonBlueprintT = {
42
+ session: {
43
+ id: sessionId,
44
+ },
45
+
46
+ agent: {
47
+ name: partial.agent?.name ?? "unnamed-agent",
48
+ version: partial.agent?.version ?? "0.0.0",
49
+ hash: partial.agent?.hash ?? { type: "sha256", value: "" },
50
+ },
51
+
52
+ config: {
53
+ ...DEFAULT_CONFIG,
54
+ ...partial.config,
55
+ },
56
+
57
+ // The machine-wide ceiling, carried through verbatim. Deliberately NOT
58
+ // defaulted: absent means "no profile governs this agent" — a
59
+ // deployment, or `axon run` outside one — which is a different fact
60
+ // from an empty ceiling and must stay distinguishable.
61
+ ...(partial.profilePolicy ? { profilePolicy: partial.profilePolicy } : {}),
62
+
63
+ // The user's declared inference sources, carried verbatim for the
64
+ // same reason and with the same distinction: absent means "no profile
65
+ // governs this agent", which is a deployment or `axon run` outside
66
+ // one, and is a different fact from a profile that declares none.
67
+ ...(partial.profileProviders ? { profileProviders: partial.profileProviders } : {}),
68
+
69
+ env: partial.env ?? {},
70
+
71
+ // the brain, constructed by the CLI (or a test) and carried in live.
72
+ // REQUIRED: an agent without a brain is not an agent — checked below.
73
+ cognet: partial.cognet,
74
+
75
+ tools: partial.tools ?? [],
76
+ prompts: partial.prompts ?? [],
77
+ scripts: partial.scripts ?? [],
78
+ knowledge: partial.knowledge ?? [],
79
+
80
+ server: {
81
+ middleware: partial.server?.middleware ?? [],
82
+ routes: partial.server?.routes ?? [],
83
+ plugins: partial.server?.plugins ?? [],
84
+ },
85
+
86
+ modules: partial.modules ?? [],
87
+ // Resolved supervisor-side and carried through: a confined agent
88
+ // cannot compute it (resolving needs the credential this side does
89
+ // not hold), so dropping it here is what left /_axon/health
90
+ // reporting `engine: null` on a working agent.
91
+ ...(partial.engine ? { engine: partial.engine } : {}),
92
+
93
+ paths: {
94
+ root: partial.paths?.root ?? process.cwd(),
95
+ // Runtime output — sessions, state, sensory — lives INSIDE the
96
+ // generated frame, because none of it is authored: it is what the
97
+ // agent produced, not what the user wrote. `data/knowledge` is the
98
+ // counterpart and deliberately stays at the project root, since it
99
+ // IS authored and gets committed. After this split, everything
100
+ // under .agent/ is disposable and everything outside it is source.
101
+ data: partial.paths?.data ?? ".agent/data",
102
+ },
103
+ }
104
+
105
+ if (partial.boot !== undefined) blueprint.boot = partial.boot
106
+ if (partial.bootFilePath !== undefined) blueprint.bootFilePath = partial.bootFilePath
107
+
108
+ // AXON_HOME is the agent's PROJECT ROOT, inherited by the capsule — the
109
+ // agent's own private subprocess reads it to reach its own folder.
110
+ //
111
+ // The root, not the data directory, which is what it used to be. The
112
+ // prose the model is given has always described it as the root ("an agent
113
+ // folder at AXON_HOME", then a tree with src/, .env and axon.config.ts
114
+ // under it), so the value and its documentation disagreed. Anchoring at
115
+ // the root makes the documented paths true and keeps `${AXON_HOME}/data/
116
+ // knowledge` correct now that runtime output has moved elsewhere.
117
+ //
118
+ // It survives the multi-instance model only because each capsule gets
119
+ // its own env at spawn; nothing in THIS process should read it back to
120
+ // locate a session (that's what error context / blueprint.paths are for).
121
+ process.env.AXON_HOME = resolve(blueprint.paths.root)
122
+
123
+ return blueprint
124
+ }
125
+
126
+ /**
127
+ * Overlays an update onto the current blueprint and re-normalizes through
128
+ * AxonBlueprint(), so an updated blueprint obeys the exact same contract as a
129
+ * boot-time one. Session and agent IDENTITY always come from the current
130
+ * blueprint — an update can never change who the agent is.
131
+ *
132
+ * Two update semantics, chosen by `mode`:
133
+ *
134
+ * - "merge" (default) — a partial programmatic update. Fields absent from the
135
+ * partial keep their current value (`update({ config: { policy } })` changes
136
+ * only the policy, the engine set at boot survives).
137
+ *
138
+ * - "replace" — a hot reload from the config file. The file IS the complete,
139
+ * authoritative declaration, so `config` (env/tools/etc.) is taken wholesale
140
+ * and a field the author DELETED (commenting out `policy`) actually
141
+ * disappears. Deep-merging a file reload silently kept a removed policy
142
+ * alive — a confined sandbox never relaxed until a full restart. Identity
143
+ * and runtime-owned paths still come from current.
144
+ *
145
+ * Normalization backfills defaults either way, so replace never leaves a
146
+ * required field unset.
147
+ */
148
+ export function mergeBlueprint(
149
+ current: AxonBlueprintT,
150
+ partial: AxonPartialBlueprint,
151
+ mode: "merge" | "replace" = "merge",
152
+ ): AxonBlueprintT {
153
+ if (mode === "replace") {
154
+ // Identity and runtime-owned fields never come from the config file, so
155
+ // they survive a replace regardless of the partial: session/agent (who
156
+ // the agent is), paths (where it lives), and cognet (the resolved brain,
157
+ // bundled separately from axon.config.ts). Everything the file DOES own
158
+ // — config, env, tools, prompts, scripts, modules, server — is taken
159
+ // from the partial as-is, so a deleted field is genuinely gone.
160
+ return AxonBlueprint({
161
+ ...partial,
162
+ session: current.session,
163
+ agent: current.agent,
164
+ paths: current.paths,
165
+ cognet: partial.cognet ?? current.cognet,
166
+ })
167
+ }
168
+
169
+ const merged: AxonPartialBlueprint = {
170
+ session: current.session,
171
+ agent: current.agent,
172
+ config: { ...current.config, ...partial.config },
173
+ // Survives a merge-mode update for the same reason config does: a
174
+ // programmatic change to one field must not silently drop the
175
+ // machine's ceiling.
176
+ ...(partial.profileProviders ?? current.profileProviders
177
+ ? { profileProviders: partial.profileProviders ?? current.profileProviders }
178
+ : {}),
179
+ ...(partial.profilePolicy ?? current.profilePolicy
180
+ ? { profilePolicy: partial.profilePolicy ?? current.profilePolicy }
181
+ : {}),
182
+ env: partial.env ?? current.env,
183
+ tools: partial.tools ?? current.tools,
184
+ prompts: partial.prompts ?? current.prompts,
185
+ scripts: partial.scripts ?? current.scripts,
186
+ knowledge: partial.knowledge ?? current.knowledge,
187
+ server: { ...current.server, ...partial.server },
188
+ modules: partial.modules ?? current.modules,
189
+ ...(partial.engine ?? current.engine ? { engine: partial.engine ?? current.engine } : {}),
190
+ cognet: partial.cognet ?? current.cognet,
191
+ paths: { ...current.paths, ...partial.paths },
192
+ }
193
+
194
+ const boot = partial.boot ?? current.boot
195
+ if (boot !== undefined) merged.boot = boot
196
+
197
+ const bootFilePath = partial.bootFilePath ?? current.bootFilePath
198
+ if (bootFilePath !== undefined) merged.bootFilePath = bootFilePath
199
+
200
+ return AxonBlueprint(merged)
201
+ }