@arcforge/kernel 2.0.219 → 2.0.245
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/package.json +15 -10
- package/src/body.ts +49 -0
- package/src/engine.ts +3 -2
- package/src/kernel.ts +73 -7
- package/src/mediation.ts +12 -9
- package/src/memory/index.ts +1 -0
- package/src/memory/memory.ts +36 -0
- package/src/scheduler/ask.ts +76 -0
- package/src/scheduler/channel.ts +45 -0
- package/src/scheduler/continuous.ts +2 -2
- package/src/scheduler/entry.ts +19 -0
- package/src/scheduler/scheduler.ts +17 -7
- package/src/scheduler/wake.ts +2 -64
- package/src/services/handles.ts +70 -0
- package/src/services/index.ts +3 -0
- package/src/services/services.ts +170 -0
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcforge/kernel",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.245",
|
|
4
|
+
"license": "Apache-2.0",
|
|
4
5
|
"description": "The Axon kernel — ring 0. Owns resources and execution, enforces policy, and is the only constructor of the unprivileged capsule.",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"private": false,
|
|
@@ -12,16 +13,20 @@
|
|
|
12
13
|
"src"
|
|
13
14
|
],
|
|
14
15
|
"scripts": {
|
|
15
|
-
"deploy": "echo \"This package is published ONLY by apps/tui/scripts/release.ts, which pins workspace:* deps to concrete versions first. Publishing it directly ships an unresolvable dependency.\" && exit 1"
|
|
16
|
+
"deploy": "echo \"This package is published ONLY by apps/tui/scripts/release.ts, which pins workspace:* deps to concrete versions first. Publishing it directly ships an unresolvable dependency.\" && exit 1",
|
|
17
|
+
"test": "bun run test:full",
|
|
18
|
+
"test:hot": "bun test tests/hot",
|
|
19
|
+
"test:full": "bun test tests/hot"
|
|
16
20
|
},
|
|
17
21
|
"dependencies": {
|
|
18
|
-
"@arcforge/air": "2.0.
|
|
19
|
-
"@arcforge/
|
|
20
|
-
"@arcforge/
|
|
21
|
-
"@arcforge/
|
|
22
|
-
"@arcforge/
|
|
23
|
-
"@arcforge/
|
|
24
|
-
"@arcforge/
|
|
22
|
+
"@arcforge/air": "2.0.245",
|
|
23
|
+
"@arcforge/body": "2.0.245",
|
|
24
|
+
"@arcforge/capsule": "2.0.245",
|
|
25
|
+
"@arcforge/cloud": "2.0.245",
|
|
26
|
+
"@arcforge/engines": "2.0.245",
|
|
27
|
+
"@arcforge/err": "2.0.245",
|
|
28
|
+
"@arcforge/session": "2.0.245",
|
|
29
|
+
"@arcforge/types": "2.0.245"
|
|
25
30
|
},
|
|
26
31
|
"devDependencies": {
|
|
27
32
|
"@types/bun": "latest",
|
|
@@ -46,5 +51,5 @@
|
|
|
46
51
|
"agent-runtime",
|
|
47
52
|
"typescript"
|
|
48
53
|
],
|
|
49
|
-
"axonRevision": "
|
|
54
|
+
"axonRevision": "8a325713ddc9cebf3898fb9060dbe4fb72242b96"
|
|
50
55
|
}
|
package/src/body.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { manifest } from "@arcforge/body"
|
|
2
|
+
import type { body } from "@arcforge/types"
|
|
3
|
+
import type { AxonSessionT } from "@arcforge/session"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The body this agent wears, as the kernel knows it: whatever connects the
|
|
7
|
+
* agent to a body (the body module) tells it here, and a cognet reads it as
|
|
8
|
+
* `kernel.body()`.
|
|
9
|
+
*
|
|
10
|
+
* A manifest is checked as it arrives — the boundary where a body's word
|
|
11
|
+
* becomes the mind's — and recorded in the session before anything reads it,
|
|
12
|
+
* so every reading after it in the log means something in its terms.
|
|
13
|
+
*/
|
|
14
|
+
export function Body(opts: { session: AxonSessionT }) {
|
|
15
|
+
let worn: body.Manifest | null = null
|
|
16
|
+
let presence: Present | null = null
|
|
17
|
+
|
|
18
|
+
return {
|
|
19
|
+
current(): body.Manifest | null {
|
|
20
|
+
return worn
|
|
21
|
+
},
|
|
22
|
+
presence(): Present | null {
|
|
23
|
+
return presence
|
|
24
|
+
},
|
|
25
|
+
/** Whether the worn body is the mind's to move now; a body that is detached has left, by `leave`. */
|
|
26
|
+
async present(said: Present): Promise<void> {
|
|
27
|
+
if (worn === null) throw new Error(`the body said it is ${said.state}, but none is worn`)
|
|
28
|
+
await opts.session.commit("axon:body:presence", said.state === "embodied" ? { state: said.state } : { state: said.state, why: said.why })
|
|
29
|
+
presence = said
|
|
30
|
+
},
|
|
31
|
+
async wear(described: unknown): Promise<body.Manifest> {
|
|
32
|
+
const checked = manifest.check(described)
|
|
33
|
+
await opts.session.commit("axon:body:worn", { manifest: checked })
|
|
34
|
+
worn = checked
|
|
35
|
+
return checked
|
|
36
|
+
},
|
|
37
|
+
async leave(why: string): Promise<void> {
|
|
38
|
+
if (worn === null) return
|
|
39
|
+
worn = null
|
|
40
|
+
presence = null
|
|
41
|
+
await opts.session.commit("axon:body:left", { why: why })
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A body's presence while worn: anything but detached, which is leaving. */
|
|
47
|
+
type Present = Exclude<body.Presence, { state: "detached" }>
|
|
48
|
+
|
|
49
|
+
export type BodyT = ReturnType<typeof Body>
|
package/src/engine.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
AxonEngineFaultCode,
|
|
10
10
|
AxonEngineResponse,
|
|
11
11
|
EngineCloud,
|
|
12
|
+
RemoteEngines,
|
|
12
13
|
} from "@arcforge/types"
|
|
13
14
|
import { asEngineFault, EngineFailure } from "@arcforge/engines"
|
|
14
15
|
import type { AxonErrorCode } from "@arcforge/err"
|
|
@@ -61,7 +62,7 @@ type EngineOpts = {
|
|
|
61
62
|
* idle-stall guard — stays here and cannot tell the tokens crossed a
|
|
62
63
|
* process boundary to arrive.
|
|
63
64
|
*/
|
|
64
|
-
remote?:
|
|
65
|
+
remote?: RemoteEngines
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
type EngineContext = {
|
|
@@ -442,7 +443,7 @@ export function Engine(opts: EngineOpts) {
|
|
|
442
443
|
// with. Checked before `engines` so a runtime that happens to carry
|
|
443
444
|
// both cannot silently prefer the in-process path and pull a key
|
|
444
445
|
// inside the boundary.
|
|
445
|
-
if (opts.remote) return { driver: opts.remote(role), name: "supervisor" }
|
|
446
|
+
if (opts.remote) return { driver: opts.remote.generate(role), name: "supervisor" }
|
|
446
447
|
|
|
447
448
|
if (!opts.engines) return null
|
|
448
449
|
const bound = opts.engines.get(role)
|
package/src/kernel.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { err } from "@arcforge/err"
|
|
2
|
-
import type { AxonBlueprint, AxonDriver, AxonEngineCall, AxonEngineDriver, CapsulePolicy, ResolvedCapsulePolicy, AxonEngineEvent, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, CapsuleCommandOrigin, EngineSession, KernelAbi, TransformOptions, AxonStimulusInput } from "@arcforge/types"
|
|
2
|
+
import type { AxonBlueprint, AxonDriver, AxonEngineCall, AxonEngineDriver, RemoteEngines, CapsulePolicy, ResolvedCapsulePolicy, AxonEngineEvent, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, CapsuleCommandOrigin, EngineSession, KernelAbi, TransformOptions, AxonStimulusInput, ServiceGrants } from "@arcforge/types"
|
|
3
3
|
import { EMPTY_CAPSULE_SCOPE } from "@arcforge/types"
|
|
4
4
|
import type { AxonCloudClient } from "@arcforge/cloud"
|
|
5
5
|
import type { KernelBus } from "./contracts"
|
|
@@ -12,7 +12,10 @@ import { Scheduler } from "./scheduler"
|
|
|
12
12
|
import type { KernelCognet } from "./contracts"
|
|
13
13
|
import { Mediation } from "./mediation"
|
|
14
14
|
import { Store } from "./store"
|
|
15
|
+
import { Memory } from "./memory"
|
|
15
16
|
import { Knowledge } from "./knowledge"
|
|
17
|
+
import { Body } from "./body"
|
|
18
|
+
import { Services } from "./services"
|
|
16
19
|
import type { AxonEscalate, AxonHost } from "@arcforge/types"
|
|
17
20
|
|
|
18
21
|
type KernelOpts = {
|
|
@@ -42,7 +45,7 @@ type KernelOpts = {
|
|
|
42
45
|
* whether it is confined. Ring 0 asks for a driver by role and gets one;
|
|
43
46
|
* where that driver's tokens come from is the boundary's business.
|
|
44
47
|
*/
|
|
45
|
-
remote?:
|
|
48
|
+
remote?: RemoteEngines
|
|
46
49
|
/**
|
|
47
50
|
* The agent's base identity text, rendered fresh per call — backs the
|
|
48
51
|
* ABI's base(). Injected because rendering it is a PRESENTATION concern
|
|
@@ -78,6 +81,13 @@ type KernelOpts = {
|
|
|
78
81
|
* Absent for a cognet on the single-`engine:` path.
|
|
79
82
|
*/
|
|
80
83
|
engines?: EnginesT
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What the agent granted each use the cognet declared. Built at the
|
|
87
|
+
* Axon() seam with the agent's providers — the kernel serves calls
|
|
88
|
+
* through it and never learns how a provider was chosen.
|
|
89
|
+
*/
|
|
90
|
+
grants: ServiceGrants
|
|
81
91
|
}
|
|
82
92
|
|
|
83
93
|
type KernelInput = {
|
|
@@ -408,6 +418,8 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
408
418
|
let live = opts.blueprint
|
|
409
419
|
const blueprintNow = () => live
|
|
410
420
|
|
|
421
|
+
// The body the agent wears, told by whatever connects it to one; the cognet reads it as body().
|
|
422
|
+
const body = Body({ session: session })
|
|
411
423
|
const scheduler = Scheduler({
|
|
412
424
|
bus: opts.bus,
|
|
413
425
|
session: session,
|
|
@@ -465,6 +477,11 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
465
477
|
session: session,
|
|
466
478
|
})
|
|
467
479
|
|
|
480
|
+
const memory = Memory({
|
|
481
|
+
blueprint: opts.blueprint,
|
|
482
|
+
cognet: cognet,
|
|
483
|
+
})
|
|
484
|
+
|
|
468
485
|
/**
|
|
469
486
|
* Long-term knowledge — the agent's own data/knowledge/ plus every
|
|
470
487
|
* module's, discovered by the build and carried on the blueprint.
|
|
@@ -702,6 +719,18 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
702
719
|
return cognet.engines?.[role]
|
|
703
720
|
}
|
|
704
721
|
|
|
722
|
+
/**
|
|
723
|
+
* Whether a declared role was filled, for a confined agent. A REQUIRED
|
|
724
|
+
* role always was — an unfillable one fails the supervisor's resolution
|
|
725
|
+
* before this process exists. An OPTIONAL one may legitimately be empty,
|
|
726
|
+
* and only the supervisor's resolved facts can say; without them it is
|
|
727
|
+
* treated as empty, so a brain degrades instead of calling into nothing.
|
|
728
|
+
*/
|
|
729
|
+
function filled(role: string): boolean {
|
|
730
|
+
if (!declaredRole(role)?.optional) return true
|
|
731
|
+
return live.cognet.resolvedEngines?.[role] !== undefined
|
|
732
|
+
}
|
|
733
|
+
|
|
705
734
|
/**
|
|
706
735
|
* A declared requirement, as the ABI's EngineFacts.
|
|
707
736
|
*
|
|
@@ -732,7 +761,7 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
732
761
|
// The role's existence is settled by the cognet's own declaration;
|
|
733
762
|
// what fills it was settled by the supervisor before this process
|
|
734
763
|
// started.
|
|
735
|
-
if (!bound && !(opts.remote && declared)) {
|
|
764
|
+
if (!bound && !(opts.remote && declared && filled(role))) {
|
|
736
765
|
throw err("ENGINE_ROLE_UNBOUND", {
|
|
737
766
|
detail: `no engine bound to "${role}" — declare it in engines: and check kernel.engine.has() for optional roles`,
|
|
738
767
|
})
|
|
@@ -802,7 +831,7 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
802
831
|
// was ever spawned.
|
|
803
832
|
has: (role: string): boolean =>
|
|
804
833
|
(opts.engines?.resolution.bound.some(entry => entry.role === role) ?? false)
|
|
805
|
-
|| Boolean(opts.remote && declaredRole(role)),
|
|
834
|
+
|| Boolean(opts.remote && declaredRole(role) && filled(role)),
|
|
806
835
|
},
|
|
807
836
|
)
|
|
808
837
|
|
|
@@ -814,6 +843,15 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
814
843
|
* capability it was handed — a wiring fault, and loud rather than coerced.
|
|
815
844
|
*/
|
|
816
845
|
function driverFor<K extends "transform" | "stream">(role: string, kind: K) {
|
|
846
|
+
// Confined: the engine is on the supervisor's side of the link, and
|
|
847
|
+
// resolution happened there. Nothing is bound in this heap to check.
|
|
848
|
+
if (opts.remote) {
|
|
849
|
+
if (kind === "transform") return { driver: opts.remote.transform(role) as Extract<AxonDriver, { kind: K }>, bound: undefined }
|
|
850
|
+
throw err("ENGINE_ROLE_UNBOUND", {
|
|
851
|
+
detail: `role "${role}" is a stream engine, and stream engines are not wired across the confinement boundary yet`,
|
|
852
|
+
context: { role, kind },
|
|
853
|
+
})
|
|
854
|
+
}
|
|
817
855
|
const bound = opts.engines?.resolution.bound.find(entry => entry.role === role)
|
|
818
856
|
const driver = opts.engines?.get(role).driver
|
|
819
857
|
if (!driver || driver.kind !== kind) {
|
|
@@ -845,13 +883,13 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
845
883
|
|
|
846
884
|
const correlation = {
|
|
847
885
|
role,
|
|
848
|
-
provider: bound?.capability.provider ?? "unknown",
|
|
886
|
+
provider: bound?.capability.provider ?? (opts.remote ? "supervisor" : "unknown"),
|
|
849
887
|
...(bound?.capability.id ? { model: bound.capability.id } : {}),
|
|
850
888
|
}
|
|
851
889
|
await session.commit("kernel:transform:start", correlation, span)
|
|
852
890
|
|
|
853
891
|
try {
|
|
854
|
-
const result = await driver.transform(input, transformOpts)
|
|
892
|
+
const result = await driver.transform(input, { ...transformOpts, signal: run.signal })
|
|
855
893
|
await session.commit("kernel:transform:complete", { role, durationMs: Date.now() - started }, span)
|
|
856
894
|
return result
|
|
857
895
|
} catch (cause) {
|
|
@@ -977,6 +1015,13 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
977
1015
|
}
|
|
978
1016
|
}
|
|
979
1017
|
|
|
1018
|
+
const services = Services({
|
|
1019
|
+
uses: () => blueprintNow().cognet?.uses ?? {},
|
|
1020
|
+
grants: opts.grants,
|
|
1021
|
+
active: () => scheduler.active(),
|
|
1022
|
+
record: (type, data, span) => session.commit(type, data as never, span).then(() => {}),
|
|
1023
|
+
})
|
|
1024
|
+
|
|
980
1025
|
// ── the ABI — the syscall table, bound once to the kernel's organs ──────
|
|
981
1026
|
// Process-lifetime object: nothing on it carries per-wake state beyond
|
|
982
1027
|
// what scheduler.active() resolves internally. This is the only thing
|
|
@@ -997,6 +1042,9 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
997
1042
|
// llm surface — by role, resolved at boot against the user's providers
|
|
998
1043
|
engine: engineAbi,
|
|
999
1044
|
|
|
1045
|
+
// what the cognet uses, by its own names — served by whatever the agent granted
|
|
1046
|
+
services: services,
|
|
1047
|
+
|
|
1000
1048
|
/**
|
|
1001
1049
|
* A format violation the COGNET detected while rendering the model's
|
|
1002
1050
|
* output — the kernel writes the system fact the cognet may not forge.
|
|
@@ -1017,6 +1065,8 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
1017
1065
|
return runAndCommit(code, { signal })
|
|
1018
1066
|
}) as KernelAbi["run"],
|
|
1019
1067
|
scope: () => capsule.current.scope,
|
|
1068
|
+
body: body.current,
|
|
1069
|
+
presence: body.presence,
|
|
1020
1070
|
|
|
1021
1071
|
|
|
1022
1072
|
// environment surface
|
|
@@ -1053,6 +1103,8 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
1053
1103
|
void session
|
|
1054
1104
|
.commit(type, data as AxonEventMap[typeof type], scheduler.current() ?? undefined)
|
|
1055
1105
|
.catch(() => {})
|
|
1106
|
+
// The one cognet event the kernel acts on: the mind saying it is done with a request's message.
|
|
1107
|
+
if (type === "cognet:settled") scheduler.settled((data as { seqs: number[] }).seqs)
|
|
1056
1108
|
},
|
|
1057
1109
|
|
|
1058
1110
|
// persistence surface — private cognitive state + read-only episodic
|
|
@@ -1064,6 +1116,10 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
1064
1116
|
// path), different doctrine: this is the record, not a cache.
|
|
1065
1117
|
knowledge: knowledge,
|
|
1066
1118
|
|
|
1119
|
+
// long-term memory — where the cognet's own databases live. The
|
|
1120
|
+
// kernel owns the place; the cognet's engine owns everything else.
|
|
1121
|
+
memory: memory,
|
|
1122
|
+
|
|
1067
1123
|
// The brain's own rhythm. Called from a cognet plugin, never from the
|
|
1068
1124
|
// body — see KernelAbi.wake for why the body must not drive this.
|
|
1069
1125
|
// Deliberately NOT awaited into the wake: admission is the contract,
|
|
@@ -1084,19 +1140,29 @@ export async function Kernel(opts: KernelOpts) {
|
|
|
1084
1140
|
// The kernel owns this bracket rather than the cognet: exec'ing an
|
|
1085
1141
|
// untrusted artifact is boot's most failure-prone step, and a brain that
|
|
1086
1142
|
// dies inside load() could never close a bracket it opened itself.
|
|
1143
|
+
//
|
|
1144
|
+
// Attached BEFORE load(), the boot-side mirror of shutdown's detach-after-
|
|
1145
|
+
// unload: a continuous brain starts its own clock inside load(), and that
|
|
1146
|
+
// clock may fire before load() — or the commit after it — resolves. If
|
|
1147
|
+
// the scheduler did not hold the cognet yet, those ticks threw
|
|
1148
|
+
// NO_COGNET_LOADED into the brain's interval.
|
|
1087
1149
|
const loadStarted = Date.now()
|
|
1088
1150
|
await session.commit("cognet:load:start", { name: cognet.name })
|
|
1151
|
+
scheduler.attach(cognet)
|
|
1089
1152
|
try {
|
|
1090
1153
|
await cognet.load(abi)
|
|
1091
1154
|
} catch (cause) {
|
|
1155
|
+
scheduler.detach()
|
|
1092
1156
|
const failure = err(cause)
|
|
1093
1157
|
await session.commit("cognet:load:failed", { name: cognet.name, error: failure, durationMs: Date.now() - loadStarted })
|
|
1094
1158
|
throw failure
|
|
1095
1159
|
}
|
|
1096
1160
|
await session.commit("cognet:load:complete", { name: cognet.name, durationMs: Date.now() - loadStarted })
|
|
1097
|
-
scheduler.attach(cognet)
|
|
1098
1161
|
|
|
1099
1162
|
return {
|
|
1163
|
+
/** The body the agent wears: told here by whatever connects it to one, read by the cognet as `body()`. */
|
|
1164
|
+
body: { wear: body.wear, present: body.present, leave: body.leave },
|
|
1165
|
+
|
|
1100
1166
|
/**
|
|
1101
1167
|
* Whether a cognet is loaded and able to wake.
|
|
1102
1168
|
*
|
package/src/mediation.ts
CHANGED
|
@@ -210,9 +210,9 @@ export function Mediation(opts: MediationOpts) {
|
|
|
210
210
|
})
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
-
function span() {
|
|
213
|
+
function span(spanId?: string) {
|
|
214
214
|
const active = opts.run?.()
|
|
215
|
-
return active ? { runId: active.runId, spanId: Bun.randomUUIDv7() } : undefined
|
|
215
|
+
return active ? { runId: active.runId, spanId: spanId ?? Bun.randomUUIDv7() } : undefined
|
|
216
216
|
}
|
|
217
217
|
|
|
218
218
|
/**
|
|
@@ -278,20 +278,23 @@ export function Mediation(opts: MediationOpts) {
|
|
|
278
278
|
* silently stops pairing brackets.
|
|
279
279
|
*/
|
|
280
280
|
emit: {
|
|
281
|
-
start(input: { module: string; fn: string; args: unknown[] }) {
|
|
282
|
-
|
|
281
|
+
async start(input: { module: string; fn: string; args: unknown[] }) {
|
|
282
|
+
const spanId = Bun.randomUUIDv7()
|
|
283
|
+
await opts.session.commit("process:fn:start", { commandId: commandId(), ...input }, span(spanId))
|
|
284
|
+
return spanId
|
|
283
285
|
},
|
|
284
|
-
complete(input: { module: string; fn: string; result: unknown; durationMs: number }) {
|
|
285
|
-
|
|
286
|
+
async complete(input: { module: string; fn: string; result: unknown; durationMs: number; spanId: string }) {
|
|
287
|
+
const { spanId, ...data } = input
|
|
288
|
+
await opts.session.commit("process:fn:complete", { commandId: commandId(), ...data }, span(spanId))
|
|
286
289
|
},
|
|
287
|
-
failed(input: { module: string; fn: string; error: unknown; durationMs: number }) {
|
|
288
|
-
|
|
290
|
+
async failed(input: { module: string; fn: string; error: unknown; durationMs: number; spanId: string }) {
|
|
291
|
+
await opts.session.commit("process:fn:failed", {
|
|
289
292
|
commandId: commandId(),
|
|
290
293
|
module: input.module,
|
|
291
294
|
fn: input.fn,
|
|
292
295
|
error: input.error as never,
|
|
293
296
|
durationMs: input.durationMs,
|
|
294
|
-
}, span())
|
|
297
|
+
}, span(input.spanId))
|
|
295
298
|
},
|
|
296
299
|
},
|
|
297
300
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Memory } from "./memory"
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AxonBlueprint, KernelMemory, MemoryConnection } from "@arcforge/types"
|
|
2
|
+
import { home } from "@arcforge/session"
|
|
3
|
+
import { err } from "@arcforge/err"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
|
|
6
|
+
type MemoryOpts = {
|
|
7
|
+
blueprint: AxonBlueprint
|
|
8
|
+
/** The cognet whose memory this is — its own namespace on disk. */
|
|
9
|
+
cognet: { readonly name: string }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A database name: one lowercase identifier. Nothing in it can be read as a path. */
|
|
13
|
+
const NAME = /^[a-z][a-z0-9-]*$/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Memory — where a cognet's long-term databases live (see KernelMemory in
|
|
17
|
+
* @arcforge/types for the doctrine).
|
|
18
|
+
*
|
|
19
|
+
* The kernel says where; the cognet's own engine opens it. Today every
|
|
20
|
+
* database is a sqlite file in the agent's data. A hosted agent would
|
|
21
|
+
* answer `remote`, and no cognet would notice.
|
|
22
|
+
*/
|
|
23
|
+
export function Memory(opts: MemoryOpts): KernelMemory {
|
|
24
|
+
const root = path.resolve(opts.blueprint.paths.root, opts.blueprint.paths.data)
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
connect(name: string): MemoryConnection {
|
|
28
|
+
if (!NAME.test(name)) {
|
|
29
|
+
throw err("MEMORY_NAME_INVALID", { detail: `"${name}" is not a database name — one lowercase identifier: a letter, then letters, digits or dashes`, context: { name: name } })
|
|
30
|
+
}
|
|
31
|
+
return { type: "sqlite", path: home.data.memory.path(root, opts.cognet.name, name) }
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type MemoryT = ReturnType<typeof Memory>
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { addressedTo, type AxonEntry, type AxonStimulusInput } from "@arcforge/types"
|
|
2
|
+
import type { AxonSessionT } from "@arcforge/session"
|
|
3
|
+
import type { KernelBus } from "../contracts"
|
|
4
|
+
import { Channel } from "./channel"
|
|
5
|
+
import { isEntry } from "./entry"
|
|
6
|
+
|
|
7
|
+
type AskInput = {
|
|
8
|
+
content?: string | string[]
|
|
9
|
+
stimuli?: AxonStimulusInput[]
|
|
10
|
+
/** The surface the message arrived on — the address the mind answers to. */
|
|
11
|
+
channel?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Ask — a request, made of a mind that has no requests.
|
|
16
|
+
*
|
|
17
|
+
* A continuous mind runs on its own clock and hears whatever it is sent, so
|
|
18
|
+
* nothing about it begins or ends with a message. A caller that wants an
|
|
19
|
+
* answer — `axon -p`, an API, another agent — still gets one: the message is
|
|
20
|
+
* admitted, the entries the mind commits for this caller's channel (or for
|
|
21
|
+
* no one) stream back as they land, and the stream ends when the mind has
|
|
22
|
+
* SETTLED the message — every system that reads stimuli has taken it, and
|
|
23
|
+
* every run that took it, and whatever that run started, has ended. The mind
|
|
24
|
+
* says so itself (`cognet:settled`), by the seq it received each stimulus at.
|
|
25
|
+
*
|
|
26
|
+
* Nothing is reserved, and nothing is locked: the mind keeps ticking, other
|
|
27
|
+
* clients keep talking, and a caller that walks away leaves nothing held.
|
|
28
|
+
*/
|
|
29
|
+
export function Ask(opts: { session: AxonSessionT; bus: KernelBus; interrupt: (reason: "user") => void }) {
|
|
30
|
+
/** Callers waiting on a stimulus, by the seq the mind received it at. */
|
|
31
|
+
const waiting = new Map<number, () => void>()
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
/** The mind is done with these stimuli. */
|
|
35
|
+
settled(seqs: readonly number[]): void {
|
|
36
|
+
for (const seq of seqs) {
|
|
37
|
+
waiting.get(seq)?.()
|
|
38
|
+
waiting.delete(seq)
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
stream(input: AskInput) {
|
|
43
|
+
const channel = input.channel ?? "terminal"
|
|
44
|
+
const asked: number[] = []
|
|
45
|
+
|
|
46
|
+
const wire = (async function* () {
|
|
47
|
+
const out = Channel<AxonEntry>()
|
|
48
|
+
const unsubscribe = opts.bus.onAny((_type, payload) => {
|
|
49
|
+
if (!isEntry(payload)) return
|
|
50
|
+
if (!addressedTo(payload.data, channel)) return
|
|
51
|
+
out.push(payload)
|
|
52
|
+
})
|
|
53
|
+
try {
|
|
54
|
+
// Each waited on the moment it is admitted: the mind may settle the first while a later one is still going in.
|
|
55
|
+
const settling: Array<Promise<void>> = []
|
|
56
|
+
const admitted = (seq: number) => {
|
|
57
|
+
asked.push(seq)
|
|
58
|
+
settling.push(new Promise<void>(resolve => waiting.set(seq, resolve)))
|
|
59
|
+
}
|
|
60
|
+
const contents = input.content === undefined ? [] : Array.isArray(input.content) ? input.content : [input.content]
|
|
61
|
+
for (const content of contents) admitted((await opts.session.stimuli.ingest("cognet:stimulus:text", { channel: channel, content: content })).time.seq)
|
|
62
|
+
for (const stimulus of input.stimuli ?? []) admitted((await opts.session.stimuli.ingest(stimulus.type, stimulus.data as never)).time.seq)
|
|
63
|
+
void Promise.all(settling).then(() => out.close())
|
|
64
|
+
yield* out
|
|
65
|
+
} finally {
|
|
66
|
+
unsubscribe()
|
|
67
|
+
for (const seq of asked) waiting.delete(seq)
|
|
68
|
+
}
|
|
69
|
+
})()
|
|
70
|
+
|
|
71
|
+
return { stream: wire, interrupt: () => opts.interrupt("user") }
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type AskT = ReturnType<typeof Ask>
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridges something that cannot yield — a wake, or a mind answering a
|
|
3
|
+
* request — to the caller's async iterator.
|
|
4
|
+
* push() during execution, close() on clean stop, fail() rethrows at the
|
|
5
|
+
* consumer.
|
|
6
|
+
*/
|
|
7
|
+
export function Channel<T>() {
|
|
8
|
+
const buffer: T[] = []
|
|
9
|
+
let notify: (() => void) | null = null
|
|
10
|
+
let done = false
|
|
11
|
+
let failed = false
|
|
12
|
+
let failure: unknown = null
|
|
13
|
+
|
|
14
|
+
function wakeConsumer() {
|
|
15
|
+
notify?.()
|
|
16
|
+
notify = null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
push(value: T) {
|
|
21
|
+
buffer.push(value)
|
|
22
|
+
wakeConsumer()
|
|
23
|
+
},
|
|
24
|
+
close() {
|
|
25
|
+
done = true
|
|
26
|
+
wakeConsumer()
|
|
27
|
+
},
|
|
28
|
+
fail(cause: unknown) {
|
|
29
|
+
failed = true
|
|
30
|
+
failure = cause
|
|
31
|
+
done = true
|
|
32
|
+
wakeConsumer()
|
|
33
|
+
},
|
|
34
|
+
async *[Symbol.asyncIterator](): AsyncGenerator<T> {
|
|
35
|
+
while (true) {
|
|
36
|
+
while (buffer.length > 0) yield buffer.shift()!
|
|
37
|
+
if (done) {
|
|
38
|
+
if (failed) throw failure
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
await new Promise<void>((resolve) => { notify = resolve })
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -22,8 +22,8 @@ type ContinuousOpts = {
|
|
|
22
22
|
*
|
|
23
23
|
* The resolution is that these are different quantities. How fast frames
|
|
24
24
|
* arrive is the body's. How often it is worth thinking about them is the
|
|
25
|
-
* mind's. So
|
|
26
|
-
* emits stimuli.
|
|
25
|
+
* mind's. So the brain declares `mode.hz` in its own config, its host drives
|
|
26
|
+
* `kernel.wake()` at that rate, and the body only ever emits stimuli.
|
|
27
27
|
*
|
|
28
28
|
* OVERLAP POLICY: wakes overlap. Every wake starts, always, however long the
|
|
29
29
|
* last one is still taking.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AxonEntry } from "@arcforge/types"
|
|
2
|
+
import { ENTRY_EVENT_PREFIXES } from "@arcforge/types"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Entry vocabulary — the families are defined WITH AxonEntryEvent, never
|
|
6
|
+
* duplicated here.
|
|
7
|
+
*
|
|
8
|
+
* Shape-checked on `type` and `time.seq`, which is every enveloped event's
|
|
9
|
+
* identity (see AxonEvent). This used to require a string `id`; when that
|
|
10
|
+
* field was removed from the envelope the predicate rejected every entry
|
|
11
|
+
* ever emitted, and a wake produced no output at all — a reminder that a
|
|
12
|
+
* structural guard is only as correct as the shape it was written against.
|
|
13
|
+
*/
|
|
14
|
+
export function isEntry(event: unknown): event is AxonEntry {
|
|
15
|
+
if (typeof event !== "object" || event === null) return false
|
|
16
|
+
const e = event as { type?: string; time?: { seq?: number } }
|
|
17
|
+
if (typeof e.type !== "string" || typeof e.time?.seq !== "number") return false
|
|
18
|
+
return ENTRY_EVENT_PREFIXES.some(prefix => (e.type as string).startsWith(prefix))
|
|
19
|
+
}
|
|
@@ -6,6 +6,7 @@ import type { AxonSessionT } from "@arcforge/session"
|
|
|
6
6
|
import type { KernelCognet } from "../contracts"
|
|
7
7
|
import { Wake } from "./wake"
|
|
8
8
|
import { Invocation } from "./invocation"
|
|
9
|
+
import { Ask } from "./ask"
|
|
9
10
|
import { Continuous } from "./continuous"
|
|
10
11
|
|
|
11
12
|
type SchedulerOpts = {
|
|
@@ -17,6 +18,8 @@ type InvokeInput = {
|
|
|
17
18
|
/** User message committed before the invoke starts. */
|
|
18
19
|
content?: string | string[]
|
|
19
20
|
stimuli?: AxonStimulusInput[]
|
|
21
|
+
/** The surface the message arrived on — the address the answer goes back to. */
|
|
22
|
+
channel?: string
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
/**
|
|
@@ -169,6 +172,7 @@ export function Scheduler(opts: SchedulerOpts) {
|
|
|
169
172
|
|
|
170
173
|
const invocation = Invocation({ session: opts.session, reserve, release, runWake, interrupt })
|
|
171
174
|
const continuous = Continuous({ session: opts.session, reserve, release, runWake })
|
|
175
|
+
const ask = Ask({ session: opts.session, bus: opts.bus, interrupt: interrupt })
|
|
172
176
|
|
|
173
177
|
/**
|
|
174
178
|
* Wake an invocation cognet when the WORLD reaches it — the trigger that
|
|
@@ -182,7 +186,7 @@ export function Scheduler(opts: SchedulerOpts) {
|
|
|
182
186
|
*
|
|
183
187
|
* Three gates, and each rejects for its own reason:
|
|
184
188
|
*
|
|
185
|
-
* MODE — continuous cognets own their clock (
|
|
189
|
+
* MODE — continuous cognets own their clock (their host drives
|
|
186
190
|
* kernel.wake()); waking them here would be the runtime asserting a
|
|
187
191
|
* rhythm it cannot know, which continuous.ts exists to prevent.
|
|
188
192
|
*
|
|
@@ -271,8 +275,8 @@ export function Scheduler(opts: SchedulerOpts) {
|
|
|
271
275
|
|
|
272
276
|
/**
|
|
273
277
|
* Advance a continuous cognet by one wake. The clock belongs to the
|
|
274
|
-
* BRAIN —
|
|
275
|
-
* scheduler and never to the body. See KernelAbi.wake.
|
|
278
|
+
* BRAIN — its host driving `kernel.wake()` at `mode.hz` — never to
|
|
279
|
+
* this scheduler and never to the body. See KernelAbi.wake.
|
|
276
280
|
*
|
|
277
281
|
* Resolves with the wake's ordinal on admission, not completion.
|
|
278
282
|
*/
|
|
@@ -289,15 +293,21 @@ export function Scheduler(opts: SchedulerOpts) {
|
|
|
289
293
|
return { wakes: continuous.wakes }
|
|
290
294
|
},
|
|
291
295
|
|
|
292
|
-
/**
|
|
296
|
+
/**
|
|
297
|
+
* A request: the message in, the answer streamed back, ended when the
|
|
298
|
+
* answer is over. An invocation mind wakes for it, and the wake ending
|
|
299
|
+
* ends it; a continuous mind keeps its own clock, and the request ends
|
|
300
|
+
* when the mind has settled the message — see Ask.
|
|
301
|
+
*/
|
|
293
302
|
stream(input: InvokeInput = {}) {
|
|
294
303
|
if (!cognet) throw err("NO_COGNET_LOADED")
|
|
295
|
-
if (cognet.mode.kind === "continuous")
|
|
296
|
-
throw err("SCHEDULER_MODE_MISMATCH", { detail: "continuous cognets are invoked by the scheduler's own clock, never by stream()" })
|
|
297
|
-
}
|
|
304
|
+
if (cognet.mode.kind === "continuous") return ask.stream(input)
|
|
298
305
|
return invocation.stream(input)
|
|
299
306
|
},
|
|
300
307
|
|
|
308
|
+
/** The mind is done with these stimuli — what ends a request to a continuous mind. */
|
|
309
|
+
settled: ask.settled,
|
|
310
|
+
|
|
301
311
|
/**
|
|
302
312
|
* The currently running wake's correlation — run addressing is
|
|
303
313
|
* ambient, resolved here rather than passed by the cognet (there's
|
package/src/scheduler/wake.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { err } from "@arcforge/err"
|
|
2
2
|
import type { AxonEntry, AxonStimulusEntry, CognetWake } from "@arcforge/types"
|
|
3
|
-
import { ENTRY_EVENT_PREFIXES } from "@arcforge/types"
|
|
4
3
|
import type { KernelBus } from "../contracts"
|
|
4
|
+
import { Channel } from "./channel"
|
|
5
|
+
import { isEntry } from "./entry"
|
|
5
6
|
import type { AxonSessionT } from "@arcforge/session"
|
|
6
7
|
import type { KernelCognet } from "../contracts"
|
|
7
8
|
|
|
@@ -13,22 +14,6 @@ type WakeOpts = {
|
|
|
13
14
|
abort: AbortController
|
|
14
15
|
}
|
|
15
16
|
|
|
16
|
-
/**
|
|
17
|
-
* Entry vocabulary — the families are defined WITH AxonEntryEvent, never
|
|
18
|
-
* duplicated here.
|
|
19
|
-
*
|
|
20
|
-
* Shape-checked on `type` and `time.seq`, which is every enveloped event's
|
|
21
|
-
* identity (see AxonEvent). This used to require a string `id`; when that
|
|
22
|
-
* field was removed from the envelope the predicate rejected every entry
|
|
23
|
-
* ever emitted, and a wake produced no output at all — a reminder that a
|
|
24
|
-
* structural guard is only as correct as the shape it was written against.
|
|
25
|
-
*/
|
|
26
|
-
function isEntry(event: unknown): event is AxonEntry {
|
|
27
|
-
if (typeof event !== "object" || event === null) return false
|
|
28
|
-
const e = event as { type?: string; time?: { seq?: number } }
|
|
29
|
-
if (typeof e.type !== "string" || typeof e.time?.seq !== "number") return false
|
|
30
|
-
return ENTRY_EVENT_PREFIXES.some(prefix => (e.type as string).startsWith(prefix))
|
|
31
|
-
}
|
|
32
17
|
|
|
33
18
|
/**
|
|
34
19
|
* One execution of one wake: fires cognet.wake() exactly once and owns
|
|
@@ -124,50 +109,3 @@ export function Wake(opts: WakeOpts) {
|
|
|
124
109
|
}
|
|
125
110
|
|
|
126
111
|
export type WakeT = ReturnType<typeof Wake>
|
|
127
|
-
|
|
128
|
-
// ── Channel ───────────────────────────────────────────────────────────────────
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Bridges the wake (which cannot yield) to the caller's async iterator.
|
|
132
|
-
* push() during execution, close() on clean stop, fail() rethrows at the
|
|
133
|
-
* consumer.
|
|
134
|
-
*/
|
|
135
|
-
function Channel<T>() {
|
|
136
|
-
const buffer: T[] = []
|
|
137
|
-
let notify: (() => void) | null = null
|
|
138
|
-
let done = false
|
|
139
|
-
let failed = false
|
|
140
|
-
let failure: unknown = null
|
|
141
|
-
|
|
142
|
-
function wakeConsumer() {
|
|
143
|
-
notify?.()
|
|
144
|
-
notify = null
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
return {
|
|
148
|
-
push(value: T) {
|
|
149
|
-
buffer.push(value)
|
|
150
|
-
wakeConsumer()
|
|
151
|
-
},
|
|
152
|
-
close() {
|
|
153
|
-
done = true
|
|
154
|
-
wakeConsumer()
|
|
155
|
-
},
|
|
156
|
-
fail(cause: unknown) {
|
|
157
|
-
failed = true
|
|
158
|
-
failure = cause
|
|
159
|
-
done = true
|
|
160
|
-
wakeConsumer()
|
|
161
|
-
},
|
|
162
|
-
async *[Symbol.asyncIterator](): AsyncGenerator<T> {
|
|
163
|
-
while (true) {
|
|
164
|
-
while (buffer.length > 0) yield buffer.shift()!
|
|
165
|
-
if (done) {
|
|
166
|
-
if (failed) throw failure
|
|
167
|
-
return
|
|
168
|
-
}
|
|
169
|
-
await new Promise<void>((resolve) => { notify = resolve })
|
|
170
|
-
}
|
|
171
|
-
},
|
|
172
|
-
}
|
|
173
|
-
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { err } from "@arcforge/err"
|
|
2
|
+
import type { ServiceProvider } from "@arcforge/types"
|
|
3
|
+
|
|
4
|
+
/** One handle, as the kernel holds it: the use that made it, the provider that keeps it, and that provider's own id. */
|
|
5
|
+
type Held = { use: string; provider: ServiceProvider; id: string }
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Handles — every handle a provider keeps for the cognet, behind an id of the
|
|
9
|
+
* kernel's own.
|
|
10
|
+
*
|
|
11
|
+
* A provider names what it keeps however it likes; the cognet is given a
|
|
12
|
+
* kernel id for it instead. That id is valid only for the use that made it
|
|
13
|
+
* and only while that use's provider is the one that made it — so a handle
|
|
14
|
+
* passed to another use, or used after its provider changed, ends loudly
|
|
15
|
+
* rather than quietly reaching something else.
|
|
16
|
+
*/
|
|
17
|
+
export function Handles() {
|
|
18
|
+
const held = new Map<string, Held>()
|
|
19
|
+
|
|
20
|
+
return {
|
|
21
|
+
/** `value` as the cognet is given it: every handle in it renamed to a kernel id. */
|
|
22
|
+
given(use: string, provider: ServiceProvider, value: unknown): unknown {
|
|
23
|
+
return walk(value, handle => {
|
|
24
|
+
const id = `${use}:${Bun.randomUUIDv7()}`
|
|
25
|
+
held.set(id, { use: use, provider: provider, id: handle.id })
|
|
26
|
+
return { handle: handle.handle, id: id }
|
|
27
|
+
})
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
/** `value` as the provider is handed it: every handle in it back to the provider's own id. */
|
|
31
|
+
taken(use: string, provider: ServiceProvider, value: unknown): unknown {
|
|
32
|
+
return walk(value, handle => ({ handle: handle.handle, id: holding(handle.id, use, provider).id }))
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
/** Lets one go: told to the provider that keeps it, and forgotten. */
|
|
36
|
+
async release(id: string, current: (use: string) => ServiceProvider | null): Promise<void> {
|
|
37
|
+
const handle = held.get(id)
|
|
38
|
+
if (!handle) throw ended(id, "it was released, or never made")
|
|
39
|
+
held.delete(id)
|
|
40
|
+
// Its provider has changed: what it kept went with it, and there is nothing left to tell.
|
|
41
|
+
if (current(handle.use) !== handle.provider) return
|
|
42
|
+
await handle.provider.release(handle.id)
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function holding(id: string, use: string, provider: ServiceProvider): Held {
|
|
47
|
+
const handle = held.get(id)
|
|
48
|
+
if (!handle) throw ended(id, "it was released, or never made")
|
|
49
|
+
if (handle.use !== use) throw ended(id, `it was made by ${handle.use}, not ${use}`)
|
|
50
|
+
if (handle.provider !== provider) throw ended(id, `the provider behind ${use} has changed since it was made`)
|
|
51
|
+
return handle
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type HandlesT = ReturnType<typeof Handles>
|
|
56
|
+
|
|
57
|
+
/** Every `{ handle, id }` in a value, replaced; typed arrays and other memory pass through untouched. */
|
|
58
|
+
function walk(value: unknown, replace: (handle: { handle: string; id: string }) => unknown): unknown {
|
|
59
|
+
if (value === null || typeof value !== "object" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return value
|
|
60
|
+
if (Array.isArray(value)) return value.map(item => walk(item, replace))
|
|
61
|
+
const entries = Object.entries(value)
|
|
62
|
+
if (entries.length === 2 && typeof (value as { handle?: unknown }).handle === "string" && typeof (value as { id?: unknown }).id === "string") {
|
|
63
|
+
return replace(value as { handle: string; id: string })
|
|
64
|
+
}
|
|
65
|
+
return Object.fromEntries(entries.map(([key, item]) => [key, walk(item, replace)]))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function ended(id: string, why: string) {
|
|
69
|
+
return err("SERVICE_HANDLE_ENDED", { detail: `handle ${id} has ended: ${why}`, context: { handle: id } })
|
|
70
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { err, isAxonError } from "@arcforge/err"
|
|
2
|
+
import type { AxonError } from "@arcforge/err"
|
|
3
|
+
import type { CognetUse, KernelServices, ProviderSession, ServiceGrants, ServiceProvider, ServiceState } from "@arcforge/types"
|
|
4
|
+
import { Handles } from "./handles"
|
|
5
|
+
|
|
6
|
+
/** The span of one service call, as the session records it. */
|
|
7
|
+
type Span = { runId: string; spanId: string }
|
|
8
|
+
|
|
9
|
+
type ServicesOpts = {
|
|
10
|
+
/** What the cognet declared in `uses:`, each with its interface as compiled — read per call: a reload can change it. */
|
|
11
|
+
uses(): Readonly<Record<string, CognetUse>>
|
|
12
|
+
/** What the agent granted — read per call, so a provider that comes or goes is seen at once. */
|
|
13
|
+
grants: ServiceGrants
|
|
14
|
+
/** The wake a call is made in: its run, and its cancellation. */
|
|
15
|
+
active(): { runId: string; signal: AbortSignal }
|
|
16
|
+
/** Records one event of a call's span in the agent's session. */
|
|
17
|
+
record(type: `kernel:service:${"start" | "complete" | "failed" | "interrupted"}`, data: Record<string, unknown>, span: Span): Promise<void>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An open session: which use, which provider, and the span its lifetime is recorded as. */
|
|
21
|
+
type Open = { use: string; method: string; provider: ServiceProvider; session: ProviderSession; span: Span; opened: number }
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Services — the cognet's uses, served by whatever the agent granted.
|
|
25
|
+
*
|
|
26
|
+
* Every call is checked against the use's interface (a declared use, a method
|
|
27
|
+
* it has, called as its kind), reaches the provider granted NOW, and is
|
|
28
|
+
* recorded in the agent's session with the provider that answered. The
|
|
29
|
+
* cognet is handed the interface's answer and nothing else: never which
|
|
30
|
+
* provider, never what it cost. Handles are renamed on the way out and back
|
|
31
|
+
* (see Handles), and sessions are held by an id of the kernel's.
|
|
32
|
+
*/
|
|
33
|
+
export function Services(opts: ServicesOpts) {
|
|
34
|
+
const handles = Handles()
|
|
35
|
+
const sessions = new Map<string, Open>()
|
|
36
|
+
const granted = (use: string) => opts.grants.granted(use)
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
state(): Record<string, ServiceState> {
|
|
40
|
+
return Object.fromEntries(Object.keys(opts.uses()).map(use => {
|
|
41
|
+
const provider = granted(use)
|
|
42
|
+
return [use, { available: provider !== null, describe: provider ? provider.describe() : null }]
|
|
43
|
+
}))
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
async call(use: string, method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal) {
|
|
47
|
+
const provider = serving(use, method, "call")
|
|
48
|
+
const run = opts.active()
|
|
49
|
+
return traced({ use: use, method: method, kind: "call", provider: provider, run: run }, async () => {
|
|
50
|
+
const answer = await provider.call(method, taken(use, provider, args), signal ? AbortSignal.any([signal, run.signal]) : run.signal)
|
|
51
|
+
return handles.given(use, provider, answer)
|
|
52
|
+
})
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
stream(use: string, method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal) {
|
|
56
|
+
const provider = serving(use, method, "stream")
|
|
57
|
+
const run = opts.active()
|
|
58
|
+
return streamed({ use: use, method: method, provider: provider, run: run }, provider.stream(method, taken(use, provider, args), signal ? AbortSignal.any([signal, run.signal]) : run.signal))
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
async open(use, method) {
|
|
62
|
+
const provider = serving(use, method, "session")
|
|
63
|
+
const span = { runId: opts.active().runId, spanId: Bun.randomUUIDv7() }
|
|
64
|
+
await opts.record("kernel:service:start", { use: use, method: method, kind: "session", provider: provider.name }, span)
|
|
65
|
+
let session: ProviderSession
|
|
66
|
+
try {
|
|
67
|
+
session = await provider.open(method)
|
|
68
|
+
} catch (cause) {
|
|
69
|
+
const failure = refused(cause, use, method)
|
|
70
|
+
await opts.record("kernel:service:failed", { use: use, method: method, error: failure }, span)
|
|
71
|
+
throw failure
|
|
72
|
+
}
|
|
73
|
+
const id = `${use}:${Bun.randomUUIDv7()}`
|
|
74
|
+
sessions.set(id, { use: use, method: method, provider: provider, session: session, span: span, opened: Date.now() })
|
|
75
|
+
return id
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
async push(id, value) {
|
|
79
|
+
const open = opened(id)
|
|
80
|
+
try {
|
|
81
|
+
return handles.given(open.use, open.provider, await open.session.push(taken(open.use, open.provider, value)))
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
throw refused(cause, open.use, open.method)
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
async reset(id) {
|
|
88
|
+
await opened(id).session.reset()
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
async close(id) {
|
|
92
|
+
const open = opened(id)
|
|
93
|
+
sessions.delete(id)
|
|
94
|
+
await open.session.close()
|
|
95
|
+
await opts.record("kernel:service:complete", { use: open.use, method: open.method }, open.span)
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
release(id) {
|
|
99
|
+
return handles.release(id, granted)
|
|
100
|
+
},
|
|
101
|
+
} satisfies KernelServices
|
|
102
|
+
|
|
103
|
+
/** The provider granted to `use` now, after checking the call is one its interface makes. */
|
|
104
|
+
function serving(use: string, method: string, kind: "call" | "stream" | "session"): ServiceProvider {
|
|
105
|
+
const declared = opts.uses()[use]
|
|
106
|
+
if (!declared) throw err("SERVICE_INVALID", { detail: `${use} is no use this cognet declares in uses`, context: { use: use } })
|
|
107
|
+
const found = declared.methods[method]
|
|
108
|
+
if (!found) throw err("SERVICE_INVALID", { detail: `${declared.named} has no method ${method}`, context: { use: use, method: method } })
|
|
109
|
+
if (found.kind !== kind) throw err("SERVICE_INVALID", { detail: `${declared.named}'s ${method} is a ${found.kind}, not a ${kind}`, context: { use: use, method: method } })
|
|
110
|
+
const provider = granted(use)
|
|
111
|
+
if (!provider) throw err("SERVICE_UNAVAILABLE", { detail: `${use} is not available — nothing fills it; ask \`available\` first`, context: { use: use } })
|
|
112
|
+
return provider
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function taken(use: string, provider: ServiceProvider, args: unknown): Record<string, unknown> {
|
|
116
|
+
return handles.taken(use, provider, args) as Record<string, unknown>
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function opened(id: string): Open {
|
|
120
|
+
const open = sessions.get(id)
|
|
121
|
+
if (!open) throw err("SERVICE_INVALID", { detail: `session ${id} is not open`, context: { session: id } })
|
|
122
|
+
return open
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function traced<T>(call: { use: string; method: string; kind: "call"; provider: ServiceProvider; run: { runId: string } }, answer: () => Promise<T>): Promise<T> {
|
|
126
|
+
const span = { runId: call.run.runId, spanId: Bun.randomUUIDv7() }
|
|
127
|
+
await opts.record("kernel:service:start", { use: call.use, method: call.method, kind: call.kind, provider: call.provider.name }, span)
|
|
128
|
+
try {
|
|
129
|
+
const value = await answer()
|
|
130
|
+
await opts.record("kernel:service:complete", { use: call.use, method: call.method }, span)
|
|
131
|
+
return value
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
const failure = refused(cause, call.use, call.method)
|
|
134
|
+
await opts.record("kernel:service:failed", { use: call.use, method: call.method, error: failure }, span)
|
|
135
|
+
throw failure
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A stream's answers, its span open to its end — interrupted when its reader leaves before it. */
|
|
140
|
+
async function* streamed(call: { use: string; method: string; provider: ServiceProvider; run: { runId: string } }, answers: AsyncIterable<unknown>): AsyncIterable<unknown> {
|
|
141
|
+
const span = { runId: call.run.runId, spanId: Bun.randomUUIDv7() }
|
|
142
|
+
await opts.record("kernel:service:start", { use: call.use, method: call.method, kind: "stream", provider: call.provider.name }, span)
|
|
143
|
+
let events = 0
|
|
144
|
+
let ended = false
|
|
145
|
+
try {
|
|
146
|
+
for await (const answer of answers) {
|
|
147
|
+
events++
|
|
148
|
+
yield handles.given(call.use, call.provider, answer)
|
|
149
|
+
}
|
|
150
|
+
ended = true
|
|
151
|
+
await opts.record("kernel:service:complete", { use: call.use, method: call.method, events: events }, span)
|
|
152
|
+
} catch (cause) {
|
|
153
|
+
ended = true
|
|
154
|
+
const failure = refused(cause, call.use, call.method)
|
|
155
|
+
await opts.record("kernel:service:failed", { use: call.use, method: call.method, error: failure }, span)
|
|
156
|
+
throw failure
|
|
157
|
+
} finally {
|
|
158
|
+
// Its reader stopped before the end: a settled outcome, not a failure.
|
|
159
|
+
if (!ended) await opts.record("kernel:service:interrupted", { use: call.use, method: call.method, events: events }, span)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export type ServicesT = ReturnType<typeof Services>
|
|
165
|
+
|
|
166
|
+
/** A provider's failure as the cognet sees it: its own code when it has one, SERVICE_FAILED when it does not. */
|
|
167
|
+
function refused(cause: unknown, use: string, method: string): AxonError {
|
|
168
|
+
if (isAxonError(cause)) return cause
|
|
169
|
+
return err("SERVICE_FAILED", { detail: `${use}.${method}: ${cause instanceof Error ? cause.message : String(cause)}`, cause: cause, context: { use: use, method: method } })
|
|
170
|
+
}
|