@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
package/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# @arcforge/core
|
|
2
|
+
|
|
3
|
+
The agent runtime for [Axon](https://axon.arclabs.it).
|
|
4
|
+
|
|
5
|
+
`Axon()` composes a blueprint, a kernel, a cognet, modules and a server into one running
|
|
6
|
+
agent. It is the thing the TUI runs, the CLI spawns, the Fleet extension attaches to, and
|
|
7
|
+
a deployed container boots — all through the same entry point or the HTTP surface it
|
|
8
|
+
builds.
|
|
9
|
+
|
|
10
|
+
`Axon()` is wiring only. It normalises the blueprint at one seam and hands the strict
|
|
11
|
+
shape down, so nothing below has to re-derive what the agent is. What you get back is a
|
|
12
|
+
handle you talk to, not a config you look things up in.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @arcforge/core
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Most people never install this directly. It arrives as a dependency of the Axon
|
|
19
|
+
framework when you scaffold an agent with `axon init`.
|
|
20
|
+
|
|
21
|
+
## Documentation
|
|
22
|
+
|
|
23
|
+
Full documentation is at **[axon.arclabs.it/docs/v2](https://axon.arclabs.it/docs/v2)**.
|
|
24
|
+
|
|
25
|
+
- [What is Axon?](https://axon.arclabs.it/docs/v2)
|
|
26
|
+
- [The runtime loop](https://axon.arclabs.it/docs/v2/concepts/runtime-loop)
|
|
27
|
+
- [Managed runtime](https://axon.arclabs.it/docs/v2/concepts/managed-runtime)
|
|
28
|
+
|
|
29
|
+
## License
|
|
30
|
+
|
|
31
|
+
Proprietary. © ArcLabs
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@arcforge/core",
|
|
3
|
+
"version": "2.0.166",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./src/index.ts",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "bun test",
|
|
14
|
+
"test:coverage": "bun test --coverage"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@arcforge/air": "2.0.166",
|
|
18
|
+
"@arcforge/cognet": "2.0.166",
|
|
19
|
+
"@arcforge/engines": "2.0.166",
|
|
20
|
+
"@arcforge/err": "2.0.166",
|
|
21
|
+
"@arcforge/kernel": "2.0.166",
|
|
22
|
+
"@arcforge/session": "2.0.166",
|
|
23
|
+
"@arcforge/types": "2.0.166",
|
|
24
|
+
"@arcforge/cloud": "2.0.166",
|
|
25
|
+
"@arcforge/capsule": "2.0.166",
|
|
26
|
+
"@arcforge/vstr": "2.0.166",
|
|
27
|
+
"crossws": "^0.3.5",
|
|
28
|
+
"h3": "^1.13.0",
|
|
29
|
+
"hookable": "^5.5.3",
|
|
30
|
+
"jose": "^5.9.6"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@arclabs/repo": "1.0.0",
|
|
34
|
+
"@types/bun": "latest",
|
|
35
|
+
"typescript": "^5"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/Axon.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { AxonCloud } from "@arcforge/cloud"
|
|
2
|
+
import type { AxonCloudClient } from "@arcforge/cloud"
|
|
3
|
+
import type { AxonEngineDriver, AxonEscalate, AxonHost, AxonPartialBlueprint } from "@arcforge/types"
|
|
4
|
+
import { err } from "@arcforge/err"
|
|
5
|
+
import { AxonBlueprint } from "./platform"
|
|
6
|
+
import { Inject } from "./platform"
|
|
7
|
+
import { AxonBus } from "./platform"
|
|
8
|
+
import { Hooks } from "./platform"
|
|
9
|
+
import { Kernel } from "@arcforge/kernel"
|
|
10
|
+
import { Boot } from "./platform"
|
|
11
|
+
import { AxonSession, home } from "@arcforge/session"
|
|
12
|
+
|
|
13
|
+
import { AxonHandle } from "./runtime"
|
|
14
|
+
import { AxonRuntime } from "./runtime/runtime"
|
|
15
|
+
import { Inference } from "./runtime/inference"
|
|
16
|
+
import { Cognet } from "./cognet"
|
|
17
|
+
import { Modules } from "./modules"
|
|
18
|
+
import { Tools } from "./tools"
|
|
19
|
+
import { resolve } from "node:path"
|
|
20
|
+
|
|
21
|
+
type AxonOpts = {
|
|
22
|
+
blueprint: AxonPartialBlueprint
|
|
23
|
+
/** Host invocation directory inherited by the capsule. Not agent configuration. */
|
|
24
|
+
cwd?: string
|
|
25
|
+
/**
|
|
26
|
+
* The event bus this runtime announces on. Supply one to observe boot —
|
|
27
|
+
* anything constructed in here is subscribable only after boot is over.
|
|
28
|
+
*/
|
|
29
|
+
bus?: ReturnType<typeof AxonBus>
|
|
30
|
+
/**
|
|
31
|
+
* An already-authenticated cloud client — the host's identity. The TUI
|
|
32
|
+
* passes its logged-in profile client so the agent runs AS the user
|
|
33
|
+
* (vault connections, billing). Omitted (deployed runtime, tests), the
|
|
34
|
+
* runtime builds its own from the agent env's AXON_API_KEY.
|
|
35
|
+
*/
|
|
36
|
+
cloud?: AxonCloudClient
|
|
37
|
+
/** Trusted platform services available to capsule code through its Axon facade. */
|
|
38
|
+
host?: AxonHost
|
|
39
|
+
/**
|
|
40
|
+
* The platform's policy decider — consulted when a rule says "escalate".
|
|
41
|
+
*
|
|
42
|
+
* Separate from `host` on purpose: that is the GUEST's channel into the
|
|
43
|
+
* platform, and a sandboxed program able to reach the decider could raise
|
|
44
|
+
* or answer its own escalations. This is host code asking host code.
|
|
45
|
+
*
|
|
46
|
+
* Absent = no decider, which the capsule treats as deny. That is the
|
|
47
|
+
* honest state for `axon run` in a script and for any embedder that never
|
|
48
|
+
* wired a surface to ask.
|
|
49
|
+
*/
|
|
50
|
+
escalate?: AxonEscalate
|
|
51
|
+
/**
|
|
52
|
+
* Inference lives outside this process.
|
|
53
|
+
*
|
|
54
|
+
* Set by the agent entrypoint when this runtime is CONFINED: the provider
|
|
55
|
+
* credential is held by the supervisor and must never enter the box, so
|
|
56
|
+
* the agent asks for a role and receives tokens over the link. Absent
|
|
57
|
+
* everywhere else, where inference is resolved and performed in this heap.
|
|
58
|
+
*
|
|
59
|
+
* A driver, so nothing above it changes: the Engine manager keeps owning
|
|
60
|
+
* AIR, retries and the stall guard, and cannot tell the tokens crossed a
|
|
61
|
+
* process boundary.
|
|
62
|
+
*/
|
|
63
|
+
remote?: (role: string) => AxonEngineDriver
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type { AxonHost } from "@arcforge/types"
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Axon runtime factory.
|
|
70
|
+
*
|
|
71
|
+
* Pure composition — normalizes the blueprint at the one seam, builds each
|
|
72
|
+
* handle in dependency order, and hands the assembled set to AxonRuntime.
|
|
73
|
+
* No work happens here that isn't wiring.
|
|
74
|
+
*
|
|
75
|
+
* Session is constructed here, environmental like bus/cloud — not owned by
|
|
76
|
+
* the kernel. Every handle that needs to read or commit session facts
|
|
77
|
+
* (Kernel, AxonRuntime, AxonHandle) receives it directly; the kernel's own
|
|
78
|
+
* relationship to it is narrowed to mediating the untrusted cognet's access
|
|
79
|
+
* through the ABI (output()/run() only), never holding it as its own state.
|
|
80
|
+
* This is also the earliest point axon:boot:start can be durably recorded, and
|
|
81
|
+
* the outer try/catch is the one place axon:boot:failed can be recorded for any
|
|
82
|
+
* failure during the rest of construction.
|
|
83
|
+
*/
|
|
84
|
+
export async function Axon(opts?: AxonOpts) {
|
|
85
|
+
const bootStarted = Date.now()
|
|
86
|
+
const inject = Inject()
|
|
87
|
+
inject.macros()
|
|
88
|
+
|
|
89
|
+
const blueprint = AxonBlueprint(opts?.blueprint)
|
|
90
|
+
const cwd = resolve(opts?.cwd ?? process.cwd())
|
|
91
|
+
/**
|
|
92
|
+
* Environmental, like session and cloud — and ACCEPTED from a caller
|
|
93
|
+
* that needs to observe boot.
|
|
94
|
+
*
|
|
95
|
+
* A confined agent forwards every commit to its supervisor by
|
|
96
|
+
* subscribing to this bus. Constructed only in here, the earliest a
|
|
97
|
+
* caller could subscribe was after `Axon()` returned — by which point
|
|
98
|
+
* boot has already announced and passed. That was invisible while the
|
|
99
|
+
* agent also wrote its own log; once the supervisor became the only
|
|
100
|
+
* writer, every boot event simply vanished from the record.
|
|
101
|
+
*/
|
|
102
|
+
const bus = opts?.bus ?? AxonBus()
|
|
103
|
+
const hooks = Hooks()
|
|
104
|
+
|
|
105
|
+
const cloud = opts?.cloud ?? AxonCloud({
|
|
106
|
+
// The SUPERVISOR's credential, from hostEnv — never from `env`, which
|
|
107
|
+
// is the agent's own .env and crosses into the box. See AxonBlueprint.
|
|
108
|
+
key: blueprint.hostEnv?.AXON_API_KEY ?? blueprint.env.AXON_API_KEY,
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The agent's own session — in memory always, on disk only when nothing
|
|
113
|
+
* else owns the file.
|
|
114
|
+
*
|
|
115
|
+
* A CONFINED agent (`remote` set) commits, announces on its bus, and
|
|
116
|
+
* `agent-main` forwards each entry to the supervisor, which holds the
|
|
117
|
+
* durable record. Writing here as well put two AxonSessions over one
|
|
118
|
+
* path, each with its own seq counter: the log carried interleaved
|
|
119
|
+
* streams whose sequence numbers ran backwards, every entry appeared
|
|
120
|
+
* twice, and anything counting entries read double.
|
|
121
|
+
*
|
|
122
|
+
* The supervisor being the only writer is also the security property the
|
|
123
|
+
* boundary is for — the agent may APPEND to the record through the link
|
|
124
|
+
* and can never rewrite it.
|
|
125
|
+
*/
|
|
126
|
+
const session = await AxonSession({ blueprint, bus, persist: !opts?.remote })
|
|
127
|
+
|
|
128
|
+
// Everything from here runs under this session's error scope: any
|
|
129
|
+
// AxonError constructed during the rest of boot attributes to THIS
|
|
130
|
+
// session's log, never another instance's in the same process.
|
|
131
|
+
return await session.scope(async () => {
|
|
132
|
+
await session.commit("axon:boot:start", {
|
|
133
|
+
version: blueprint.agent.version,
|
|
134
|
+
agentRoot: blueprint.paths.root,
|
|
135
|
+
// an explicit cloud client means the TUI handed us the host's own
|
|
136
|
+
// logged-in identity (local dev); its absence means we built one
|
|
137
|
+
// from the deployed agent's own AXON_API_KEY (cloud runtime).
|
|
138
|
+
mode: opts?.cloud ? "local" : "cloud",
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
// Cognet resolution and role resolution are INDEPENDENT: one is a
|
|
143
|
+
// disk read plus a JS import, the other is network work against
|
|
144
|
+
// the user's providers. Run concurrently, the boot pays the
|
|
145
|
+
// slower of the two rather than their sum.
|
|
146
|
+
//
|
|
147
|
+
// Both still complete before the kernel, so the ordering
|
|
148
|
+
// guarantee below is unchanged — a required role that nothing can
|
|
149
|
+
// fill stops the boot before ring 0 exists, exactly as when these
|
|
150
|
+
// were sequential. What changed is only that the waiting overlaps.
|
|
151
|
+
//
|
|
152
|
+
// Started together and awaited together: a rejection in either is
|
|
153
|
+
// observed by the Promise.all, so neither can become an unhandled
|
|
154
|
+
// rejection while the other is still in flight.
|
|
155
|
+
// Role RESOLUTION is skipped entirely when inference is remote.
|
|
156
|
+
//
|
|
157
|
+
// Resolving a role means reaching the user's providers over the
|
|
158
|
+
// network and building a driver from a credential — which is the
|
|
159
|
+
// one thing a confined agent must never do. The supervisor already
|
|
160
|
+
// resolved these roles on its own side; the agent asks for a role
|
|
161
|
+
// by name and receives tokens.
|
|
162
|
+
//
|
|
163
|
+
// Skipped rather than resolved-and-ignored: a confined box has no
|
|
164
|
+
// credential to resolve WITH, so attempting it fails the boot with
|
|
165
|
+
// ENGINE_REQUIREMENTS_UNMET before the remote driver is ever
|
|
166
|
+
// consulted. It is also the wrong work to do twice.
|
|
167
|
+
const [cognet, engines] = await Promise.all([
|
|
168
|
+
Cognet({ blueprint, session }),
|
|
169
|
+
opts?.remote ? Promise.resolve(undefined) : Inference({ blueprint, cloud, session }),
|
|
170
|
+
])
|
|
171
|
+
|
|
172
|
+
// Boot renders the agent's identity (boot.md / boot.vue). It is a
|
|
173
|
+
// presentation concern, so it is built HERE and handed to the
|
|
174
|
+
// kernel as base() rather than living in ring 0.
|
|
175
|
+
const boot = Boot({ blueprint, session })
|
|
176
|
+
|
|
177
|
+
const kernel = await session.span("axon:kernel", {}, () => Kernel({
|
|
178
|
+
blueprint: blueprint,
|
|
179
|
+
...(opts?.remote ? { remote: opts.remote } : {}),
|
|
180
|
+
...(engines ? { engines } : {}),
|
|
181
|
+
bus: bus,
|
|
182
|
+
cloud: cloud,
|
|
183
|
+
cognet: cognet,
|
|
184
|
+
session: session,
|
|
185
|
+
base: async () => (await boot.render()) ?? "", // absent boot → "", never undefined
|
|
186
|
+
onUpdate: next => boot.update(next),
|
|
187
|
+
cwd,
|
|
188
|
+
...(opts?.host ? { host: opts.host } : {}),
|
|
189
|
+
...(opts?.escalate ? { escalate: opts.escalate } : {}),
|
|
190
|
+
}))
|
|
191
|
+
|
|
192
|
+
// Tools live IN THIS PROCESS — the only place they can.
|
|
193
|
+
//
|
|
194
|
+
// Loaded after the kernel exists (mediation needs its policy and
|
|
195
|
+
// its span stream) and before the handle, so every surface built
|
|
196
|
+
// on top of it sees the same set.
|
|
197
|
+
//
|
|
198
|
+
// Unconditional. This used to be gated on `remote`, which means
|
|
199
|
+
// "inference crosses the link" — an unrelated fact that happened
|
|
200
|
+
// to coincide with confinement. Anything booted without it loaded
|
|
201
|
+
// ZERO tools, so a script run that way failed with "fs is not
|
|
202
|
+
// defined" for a module its config plainly installed.
|
|
203
|
+
const tools = Tools({ mediation: kernel.mediation })
|
|
204
|
+
await tools.install(blueprint.tools)
|
|
205
|
+
|
|
206
|
+
// user facing handle
|
|
207
|
+
const axon = AxonHandle({
|
|
208
|
+
blueprint: blueprint,
|
|
209
|
+
kernel: kernel,
|
|
210
|
+
session: session,
|
|
211
|
+
hooks: hooks,
|
|
212
|
+
cloud: cloud,
|
|
213
|
+
inject: inject,
|
|
214
|
+
bus: bus,
|
|
215
|
+
// A thunk: a hot reload rebuilds the set, and a captured map
|
|
216
|
+
// would keep serving a tool the author deleted.
|
|
217
|
+
loaded: () => tools.globals(),
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
// inject before [middleware, plugins, hooks]. The blueprint rides
|
|
221
|
+
// along because tool globals follow its `flat` placement — the
|
|
222
|
+
// agent's own src/tools land as top-level globals, a module's under
|
|
223
|
+
// its namespace, exactly as the capsule installs them.
|
|
224
|
+
inject.runtime(axon, blueprint, () => tools.globals())
|
|
225
|
+
|
|
226
|
+
// Run declared modules' setup() against the live handle, in
|
|
227
|
+
// blueprint order, before the runtime finishes booting — so a
|
|
228
|
+
// module's hooks and live resources (Discord gateway, timers) are
|
|
229
|
+
// wired before the first request. A setup failure fails boot.
|
|
230
|
+
const modules = await Modules({ blueprint, hooks, session })
|
|
231
|
+
|
|
232
|
+
return await AxonRuntime({
|
|
233
|
+
blueprint: blueprint,
|
|
234
|
+
cloud: cloud,
|
|
235
|
+
axon: axon,
|
|
236
|
+
kernel: kernel,
|
|
237
|
+
session: session,
|
|
238
|
+
bus: bus,
|
|
239
|
+
hooks: hooks,
|
|
240
|
+
modules: modules,
|
|
241
|
+
bootStarted: bootStarted,
|
|
242
|
+
})
|
|
243
|
+
} catch (cause) {
|
|
244
|
+
const failure = err(cause)
|
|
245
|
+
// The thrown error names its own durable record — a host that
|
|
246
|
+
// never got a runtime handle (failed boot) reads the log the
|
|
247
|
+
// ERROR points at, not a process-global env var that another
|
|
248
|
+
// instance may have clobbered since.
|
|
249
|
+
failure.context = {
|
|
250
|
+
...failure.context,
|
|
251
|
+
sessionId: session.id,
|
|
252
|
+
sessionFile: home.data.sessions.path(resolve(blueprint.paths.root, blueprint.paths.data), session.id),
|
|
253
|
+
}
|
|
254
|
+
await session.commit("axon:boot:failed", { error: failure, durationMs: Date.now() - bootStarted })
|
|
255
|
+
throw failure
|
|
256
|
+
}
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export type AxonT = Awaited<ReturnType<typeof Axon>>
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { mkdir, readdir, rm, stat } from "node:fs/promises"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
import { pathToFileURL } from "node:url"
|
|
5
|
+
import { err } from "@arcforge/err"
|
|
6
|
+
import type { AxonBlueprint, AxonEventMap, AxonSpanName, CognetBlueprint, CognetDefinition, CognetWake, KernelAbi } from "@arcforge/types"
|
|
7
|
+
import { KERNEL_ABI_VERSION } from "@arcforge/types"
|
|
8
|
+
|
|
9
|
+
type CognetOpts = {
|
|
10
|
+
blueprint: AxonBlueprint
|
|
11
|
+
/**
|
|
12
|
+
* Where to report resolution cost. Optional: a reload resolves the same
|
|
13
|
+
* way with nobody watching, and tests construct a cognet with no session
|
|
14
|
+
* at all.
|
|
15
|
+
*/
|
|
16
|
+
session?: {
|
|
17
|
+
span<K extends AxonSpanName, T>(
|
|
18
|
+
name: K,
|
|
19
|
+
start: AxonEventMap[`${K}:start`],
|
|
20
|
+
run: () => Promise<T>,
|
|
21
|
+
complete?: (value: T) => Omit<AxonEventMap[`${K}:complete`], "durationMs">,
|
|
22
|
+
): Promise<T>
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Cognet — the runtime's handle over one cognition artifact.
|
|
28
|
+
*
|
|
29
|
+
* Orchestrator only: resolves the definition the blueprint carries (bundle
|
|
30
|
+
* on disk from the CLI, or a live object from tests) and manages it
|
|
31
|
+
* (manager pattern — `current` is swappable on reload, nobody downstream
|
|
32
|
+
* knows). The loop lives in the DEFINITION, built as its own project
|
|
33
|
+
* (cognets/*) and bundled by `axon prepare` into <agent>/.agent/cognet/ —
|
|
34
|
+
* this layer never implements cognition, and there is no other way to
|
|
35
|
+
* load a brain.
|
|
36
|
+
*
|
|
37
|
+
* Async factory deliberately: construction resolves the definition (a disk
|
|
38
|
+
* read + import for the CLI form), so the handle can never be observed
|
|
39
|
+
* half-built.
|
|
40
|
+
*
|
|
41
|
+
* Lifecycle contract with the kernel:
|
|
42
|
+
* Cognet({ blueprint }) → resolve + configure (definition sees its blueprint)
|
|
43
|
+
* kernel exec → load(abi): ABI checked, definition.load(abi) runs
|
|
44
|
+
* wakes → forwarded to the definition
|
|
45
|
+
* update(blueprint) → changed artifact (hash/ref) swaps the brain;
|
|
46
|
+
* same artifact re-fans config only
|
|
47
|
+
*/
|
|
48
|
+
export async function Cognet(opts: CognetOpts) {
|
|
49
|
+
let blueprint = opts.blueprint
|
|
50
|
+
const slot = blueprint.cognet
|
|
51
|
+
let resolved = opts.session
|
|
52
|
+
? await opts.session.span(
|
|
53
|
+
"axon:cognet",
|
|
54
|
+
{ specifier: "path" in slot ? slot.path : null } as never,
|
|
55
|
+
() => resolve(slot),
|
|
56
|
+
(value: ResolvedCognet) => ({
|
|
57
|
+
// `cognet`, not `name`: `data.name` is span-identity by
|
|
58
|
+
// convention (the ontology guard pairs brackets on it), and a
|
|
59
|
+
// payload field that only appears on the closing half would
|
|
60
|
+
// split this span into an orphaned open and close.
|
|
61
|
+
cognet: value.definition.name,
|
|
62
|
+
version: value.definition.version,
|
|
63
|
+
bytes: value.bytes ?? 0,
|
|
64
|
+
hashMs: value.hashMs ?? 0,
|
|
65
|
+
importMs: value.importMs ?? 0,
|
|
66
|
+
}) as never,
|
|
67
|
+
)
|
|
68
|
+
: await resolve(slot)
|
|
69
|
+
let current = resolved.definition
|
|
70
|
+
let disposeArtifact = resolved.dispose
|
|
71
|
+
let abi: KernelAbi | null = null
|
|
72
|
+
|
|
73
|
+
// configuration precedes exec — the definition sees its blueprint
|
|
74
|
+
// before load() and before every wake that follows a reload
|
|
75
|
+
current.update?.(blueprint)
|
|
76
|
+
|
|
77
|
+
/** exec(): ABI compatibility is checked HERE — a mismatched artifact never half-loads. */
|
|
78
|
+
async function exec(definition: CognetDefinition, kernel: KernelAbi) {
|
|
79
|
+
if (definition.abi !== KERNEL_ABI_VERSION) {
|
|
80
|
+
throw err("COGNET_ABI_MISMATCH", {
|
|
81
|
+
detail: `${definition.name}@${definition.version} targets ABI ${definition.abi}, kernel provides ${KERNEL_ABI_VERSION}`,
|
|
82
|
+
context: { name: definition.name, version: definition.version, targetAbi: definition.abi, kernelAbi: KERNEL_ABI_VERSION },
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
await definition.load(kernel)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function load(kernel: KernelAbi) {
|
|
89
|
+
try {
|
|
90
|
+
await exec(current, kernel)
|
|
91
|
+
abi = kernel
|
|
92
|
+
} catch (cause) {
|
|
93
|
+
await disposeArtifact?.()
|
|
94
|
+
throw cause
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
get name() { return current.name },
|
|
100
|
+
get version() { return current.version },
|
|
101
|
+
get abi() { return current.abi },
|
|
102
|
+
/**
|
|
103
|
+
* The inference roles this brain declared.
|
|
104
|
+
*
|
|
105
|
+
* Read live like every other field here, and read by the kernel only
|
|
106
|
+
* when inference is REMOTE — a confined agent has no local binding to
|
|
107
|
+
* take capability facts from, so the declaration is what the ABI
|
|
108
|
+
* reports for a role.
|
|
109
|
+
*/
|
|
110
|
+
get engines() { return current.engines },
|
|
111
|
+
/** How the scheduler should invoke this cognet — read live, so a reload that changes mode takes effect on the next attach. */
|
|
112
|
+
get mode() { return current.mode },
|
|
113
|
+
|
|
114
|
+
/** Which entry types wake this brain; absent = everything. Read live, same reason as mode. */
|
|
115
|
+
get wakeOn() { return current.wakeOn },
|
|
116
|
+
|
|
117
|
+
load: load,
|
|
118
|
+
|
|
119
|
+
wake(wake: CognetWake) {
|
|
120
|
+
return current.wake(wake)
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The agent changed. A reload that carries a NEW artifact (different
|
|
125
|
+
* bundle hash, or a different live definition) swaps the brain: new
|
|
126
|
+
* definition resolved, configured, and exec'd before the old one
|
|
127
|
+
* unloads — overlap, not gap. Same artifact = config re-fan only.
|
|
128
|
+
*/
|
|
129
|
+
async update(next: AxonBlueprint) {
|
|
130
|
+
const changed = artifactChanged(blueprint.cognet, next.cognet)
|
|
131
|
+
blueprint = next
|
|
132
|
+
|
|
133
|
+
if (changed) {
|
|
134
|
+
const previous = current
|
|
135
|
+
const previousDispose = disposeArtifact
|
|
136
|
+
const candidateResolved = await resolve(next.cognet)
|
|
137
|
+
const candidate = candidateResolved.definition
|
|
138
|
+
candidate.update?.(next)
|
|
139
|
+
// Transactional swap: a candidate that cannot exec never
|
|
140
|
+
// becomes current and never strands the known-good brain.
|
|
141
|
+
try {
|
|
142
|
+
if (abi) await exec(candidate, abi)
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
await candidateResolved.dispose?.()
|
|
145
|
+
throw cause
|
|
146
|
+
}
|
|
147
|
+
current = candidate
|
|
148
|
+
disposeArtifact = candidateResolved.dispose
|
|
149
|
+
await previous.unload?.()
|
|
150
|
+
await previousDispose?.()
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
current.update?.(next)
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
async unload() {
|
|
158
|
+
try {
|
|
159
|
+
await current.unload?.()
|
|
160
|
+
} finally {
|
|
161
|
+
await disposeArtifact?.()
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export type CognetT = Awaited<ReturnType<typeof Cognet>>
|
|
168
|
+
|
|
169
|
+
// ── Resolution ────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
function artifactChanged(before: CognetBlueprint, after: CognetBlueprint): boolean {
|
|
172
|
+
if ("definition" in before || "definition" in after) {
|
|
173
|
+
const a = "definition" in before ? before.definition : null
|
|
174
|
+
const b = "definition" in after ? after.definition : null
|
|
175
|
+
return a !== b
|
|
176
|
+
}
|
|
177
|
+
return before.hash !== after.hash
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Blueprint slot → live definition.
|
|
182
|
+
*
|
|
183
|
+
* CLI form: verify the bundle's sha256 against the blueprint BEFORE
|
|
184
|
+
* evaluating a single line of it, then import with the hash as a
|
|
185
|
+
* cache-buster (the ES module registry keys on URL — a rebuilt bundle at
|
|
186
|
+
* the same path must produce a FRESH module instance, whose module scope
|
|
187
|
+
* becomes the new brain's resident RAM). The stale module of a swapped-out
|
|
188
|
+
* brain cannot be evicted from the registry — one leaked scope per brain
|
|
189
|
+
* reload, the standard HMR trade.
|
|
190
|
+
*/
|
|
191
|
+
type ResolvedCognet = {
|
|
192
|
+
definition: CognetDefinition
|
|
193
|
+
/** Removes the per-runtime module copy once its owning kernel has stopped. */
|
|
194
|
+
dispose?: () => Promise<void>
|
|
195
|
+
/** Bundle size on disk. Absent for the live-definition form, which reads nothing. */
|
|
196
|
+
bytes?: number
|
|
197
|
+
/**
|
|
198
|
+
* Split because they grow for different reasons: hashing scales with
|
|
199
|
+
* bundle size, the import is JS compile time. A boot that got slower has
|
|
200
|
+
* to be able to say which.
|
|
201
|
+
*/
|
|
202
|
+
hashMs?: number
|
|
203
|
+
importMs?: number
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function resolve(slot: CognetBlueprint): Promise<ResolvedCognet> {
|
|
207
|
+
if ("definition" in slot) return { definition: validate(slot, slot.definition) }
|
|
208
|
+
|
|
209
|
+
const file = Bun.file(slot.path)
|
|
210
|
+
if (!(await file.exists())) {
|
|
211
|
+
throw err("COGNET_MISSING", { detail: `no bundle at ${slot.path} — run \`axon prepare\``, context: { path: slot.path } })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const hashBegan = Date.now()
|
|
215
|
+
const contents = await file.bytes()
|
|
216
|
+
const hash = createHash("sha256").update(contents).digest("hex")
|
|
217
|
+
const hashMs = Date.now() - hashBegan
|
|
218
|
+
if (hash !== slot.hash) {
|
|
219
|
+
throw err("COGNET_HASH_MISMATCH", {
|
|
220
|
+
detail: `${slot.path} does not match the blueprint (expected ${slot.hash.slice(0, 12)}…, found ${hash.slice(0, 12)}…) — stale or tampered bundle; run \`axon prepare\``,
|
|
221
|
+
context: { path: slot.path, expected: slot.hash, found: hash },
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Module scope is a brain's resident RAM, and one brain belongs to one
|
|
226
|
+
// kernel. Bun may reuse a file module even when only its query string
|
|
227
|
+
// differs, so query-based cache busting is not a reliable isolation
|
|
228
|
+
// boundary. Give every runtime a distinct physical entry instead.
|
|
229
|
+
//
|
|
230
|
+
// The copies live under .agent (already ignored by the project watcher)
|
|
231
|
+
// and are removed with the owning runtime. The compiled cognet is a
|
|
232
|
+
// self-contained ESM artifact, so no relative import graph needs copying.
|
|
233
|
+
const instanceDir = join(dirname(slot.path), ".instances")
|
|
234
|
+
const instancePath = join(instanceDir, `${slot.hash}.${crypto.randomUUID()}.mjs`)
|
|
235
|
+
await mkdir(instanceDir, { recursive: true })
|
|
236
|
+
await sweepStaleInstances(instanceDir)
|
|
237
|
+
await Bun.write(instancePath, contents)
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
const importBegan = Date.now()
|
|
241
|
+
const module = (await import(pathToFileURL(instancePath).href)) as { default?: unknown }
|
|
242
|
+
const importMs = Date.now() - importBegan
|
|
243
|
+
return {
|
|
244
|
+
definition: validate(slot, module.default),
|
|
245
|
+
dispose: async () => { await rm(instancePath, { force: true }) },
|
|
246
|
+
bytes: contents.byteLength,
|
|
247
|
+
hashMs: hashMs,
|
|
248
|
+
importMs: importMs,
|
|
249
|
+
}
|
|
250
|
+
} catch (cause) {
|
|
251
|
+
await rm(instancePath, { force: true })
|
|
252
|
+
throw cause
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* How long an instance copy must be untouched before a later boot may delete
|
|
258
|
+
* it. Comfortably longer than the window between `mkdir` and the `import` that
|
|
259
|
+
* pins the file, so a runtime booting concurrently can never have its own copy
|
|
260
|
+
* swept out from under it.
|
|
261
|
+
*/
|
|
262
|
+
const STALE_INSTANCE_MS = 60 * 60_000
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Remove instance copies orphaned by runtimes that never disposed.
|
|
266
|
+
*
|
|
267
|
+
* `dispose()` deletes the copy on clean shutdown, but a `kill -9` — or a crash,
|
|
268
|
+
* or a debugger stop — skips it, and nothing else ever did. Every such exit
|
|
269
|
+
* leaked a full copy of the compiled cognet: 21 files / 1.8MB in one local
|
|
270
|
+
* agent, growing without bound, and published into the release tarball.
|
|
271
|
+
*
|
|
272
|
+
* Age is the only safe signal, because a sibling runtime's copy is a live
|
|
273
|
+
* import that must not be touched. Sweeping on boot (rather than on dispose)
|
|
274
|
+
* is what makes it work at all — the process that leaked the file is by
|
|
275
|
+
* definition not around to clean it up.
|
|
276
|
+
*
|
|
277
|
+
* Best-effort: a failure here must never stop a brain from loading.
|
|
278
|
+
*/
|
|
279
|
+
async function sweepStaleInstances(instanceDir: string): Promise<void> {
|
|
280
|
+
try {
|
|
281
|
+
const cutoff = Date.now() - STALE_INSTANCE_MS
|
|
282
|
+
const entries = await readdir(instanceDir)
|
|
283
|
+
await Promise.all(entries.map(async entry => {
|
|
284
|
+
const path = join(instanceDir, entry)
|
|
285
|
+
try {
|
|
286
|
+
const info = await stat(path)
|
|
287
|
+
if (info.mtimeMs < cutoff) await rm(path, { force: true })
|
|
288
|
+
} catch {
|
|
289
|
+
// Raced with another runtime's dispose — already gone, fine.
|
|
290
|
+
}
|
|
291
|
+
}))
|
|
292
|
+
} catch {
|
|
293
|
+
// No directory yet, or an unreadable one. Not a reason to fail a boot.
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** The bundle's default export must be a definition, and must be who the blueprint says it is. */
|
|
298
|
+
function validate(slot: CognetBlueprint, candidate: unknown): CognetDefinition {
|
|
299
|
+
if (
|
|
300
|
+
typeof candidate !== "object" || candidate === null ||
|
|
301
|
+
typeof (candidate as CognetDefinition).load !== "function" ||
|
|
302
|
+
typeof (candidate as CognetDefinition).wake !== "function" ||
|
|
303
|
+
typeof (candidate as CognetDefinition).name !== "string" ||
|
|
304
|
+
typeof (candidate as CognetDefinition).abi !== "string"
|
|
305
|
+
) {
|
|
306
|
+
throw err("COGNET_INVALID", { detail: `${slot.name} did not yield a cognet definition (default export must be defineCognet(...))`, context: { name: slot.name } })
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const definition = candidate as CognetDefinition
|
|
310
|
+
if (definition.name !== slot.name) {
|
|
311
|
+
throw err("COGNET_IDENTITY_MISMATCH", {
|
|
312
|
+
detail: `blueprint says "${slot.name}", artifact says "${definition.name}"`,
|
|
313
|
+
context: { expected: slot.name, found: definition.name },
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return definition
|
|
318
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// The runtime's handle over a compiled cognet artifact — the LOADER, not the
|
|
2
|
+
// runtime. Everything that executes inside a brain (host, clock, ecs, air)
|
|
3
|
+
// lives in @arcforge/cognet, which is public; this side stays private.
|
|
4
|
+
export { Cognet, type CognetT } from "./cognet"
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { Axon } from "./Axon"
|
|
2
|
+
// Role resolution, exported for the SUPERVISOR: a confined agent must never
|
|
3
|
+
// resolve a role, because resolution means building a driver from a
|
|
4
|
+
// credential. The supervisor does it once on its own side and vends tokens.
|
|
5
|
+
export { Inference } from "./runtime/inference"
|
|
6
|
+
// The event bus, exported for the SUPERVISOR: a linked agent has no in-heap
|
|
7
|
+
// runtime to announce on, so its commits fan out through one of these instead.
|
|
8
|
+
export { AxonBus } from "./platform"
|
|
9
|
+
export type { AxonT, AxonHost } from "./Axon"
|
|
10
|
+
export { toScope, toScopeModule, isLoadable } from "@arcforge/kernel"
|
|
11
|
+
export { scopeToDts, scopeMemberCount } from "@arcforge/air"
|