@arcforge/kernel 2.0.100

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/src/kernel.ts ADDED
@@ -0,0 +1,330 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonBlueprint, AxonEntry, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
3
+ import type { AxonCloudClient } from "@arclabs/cloud"
4
+ import type { KernelBus } from "./contracts"
5
+ import { Engine } from "./engine"
6
+ import type { AxonSessionT } from "@arcforge/session"
7
+ import { AxonCapsule, type AxonCapsuleT } from "./capsule"
8
+ import { Scheduler } from "./scheduler"
9
+ import type { KernelCognet } from "./contracts"
10
+ import { Store } from "./store"
11
+ import type { AxonHost } from "@arcforge/types"
12
+
13
+ type KernelOpts = {
14
+ blueprint: AxonBlueprint
15
+ /** Immutable host invocation directory for this runtime's userland. */
16
+ cwd: string
17
+ bus: KernelBus
18
+ /** The runtime's cloud client — engines resolve vault-backed provider tokens through it. */
19
+ cloud: AxonCloudClient
20
+ /** The brain — the runtime's handle over the blueprint-carried cognet artifact. Always present. */
21
+ cognet: KernelCognet
22
+ /**
23
+ * The session is environmental — constructed once at the Axon() seam,
24
+ * alongside bus/cloud, and handed to every consumer that needs it
25
+ * (Kernel, AxonRuntime, AxonHandle). Kernel does not own it and does
26
+ * not close it; it only reaches session through the ABI's output()/
27
+ * run(), which is the one real privilege boundary this file enforces
28
+ * (the untrusted cognet may only emit/request, never read or write the
29
+ * log directly). No thread concept: one cognet instance is always
30
+ * exactly one continuous stream.
31
+ */
32
+ session: AxonSessionT
33
+ /**
34
+ * The agent's base identity text, rendered fresh per call — backs the
35
+ * ABI's base(). Injected because rendering it is a PRESENTATION concern
36
+ * (boot.vue, the vstr renderer, the prompt context) that ring 0 has no
37
+ * business owning: the kernel guards the user's identity contract, it
38
+ * does not decide how that identity is produced.
39
+ */
40
+ base: () => Promise<string>
41
+ /**
42
+ * Re-render base() against a new blueprint on reload. Paired with `base`:
43
+ * whoever owns producing the identity text owns refreshing it, so ring 0
44
+ * fans the blueprint out without knowing what produces it.
45
+ */
46
+ onUpdate?: (blueprint: AxonBlueprint) => void
47
+ host?: AxonHost
48
+ }
49
+
50
+ type KernelInput = {
51
+ /** User message committed before the wake starts. */
52
+ content?: string | string[]
53
+ }
54
+
55
+ const COGNET_EVENT_PREFIX = "cognet:"
56
+
57
+ /** Render a run's completion value for the visible tool-call log. Strings pass through; everything else is JSON. */
58
+ function formatValue(value: unknown): string {
59
+ if (value === undefined) return ""
60
+ if (typeof value === "string") return value
61
+ try {
62
+ return JSON.stringify(value, null, 2) ?? ""
63
+ } catch {
64
+ return String(value)
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Run one block against the capsule and normalize the outcome — the ABI
70
+ * boundary this seam exists for. Exec() below (capsule's own contract)
71
+ * still rejects; a program should never have to catch three different
72
+ * shapes (AbortError, timeout Error, plain Error) to know what happened,
73
+ * so this is the one place that catch lives. Console output is captured
74
+ * here too (via the capsule's own onConsole, never exposed past this
75
+ * function) and returned inline — the kernel already auto-forwards the
76
+ * capsule's full event stream to the bus untranslated, so a program that
77
+ * wants live output subscribes to that; a program that wants ITS OWN run's
78
+ * output back as part of the result reads `stdout` here, no callback wired
79
+ * by hand.
80
+ */
81
+ async function runOne(capsule: AxonCapsuleT, code: string, opts?: { signal?: AbortSignal; id?: string }): Promise<AxonRunResult> {
82
+ const stdout: string[] = []
83
+ const onConsole = (level: string, args: unknown[]) => {
84
+ const line = args.map(a => (typeof a === "string" ? a : JSON.stringify(a))).join(" ")
85
+ stdout.push(level === "log" || level === "info" ? line : `[${level}] ${line}`)
86
+ }
87
+
88
+ try {
89
+ const value = await capsule.current.run(code, { onConsole, signal: opts?.signal, id: opts?.id })
90
+ return { ok: true, value, stdout }
91
+ } catch (cause) {
92
+ const interrupted = opts?.signal?.aborted || (cause instanceof Error && cause.name === "AbortError")
93
+ const timedOut = cause instanceof Error && /timed out/.test(cause.message)
94
+ return {
95
+ ok: false,
96
+ stdout,
97
+ error: {
98
+ kind: interrupted ? "interrupt" : timedOut ? "timeout" : "exception",
99
+ message: cause instanceof Error ? cause.message : String(cause),
100
+ },
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Kernel — the agent's OS. Owns resources and execution, never cognition.
107
+ *
108
+ * Ring 0: the trusted machinery — engine (inference), scheduler (process
109
+ * management), the capsule's constructor. Ring 3: the capsule — the
110
+ * unprivileged userland every agent-emitted effect runs in; the kernel is
111
+ * its ONLY constructor, and security is enforced at that process boundary
112
+ * alone.
113
+ *
114
+ * Session is NOT kernel-owned — it's environmental, constructed once at
115
+ * the Axon() seam and handed in here like bus/cloud. The kernel's only
116
+ * relationship to it is mediating the cognet's access: the ABI's output()
117
+ * and run() are the only doors, and both commit on the cognet's behalf —
118
+ * it never touches session.commit directly. Every other consumer (Axon(),
119
+ * AxonRuntime, AxonHandle) reaches session directly — going through the
120
+ * kernel to commit a runtime event was the original design mistake this
121
+ * replaces.
122
+ *
123
+ * Cognition lives in the COGNET — a versioned artifact carried in on the
124
+ * blueprint, exec'd here once, and woken per stimulus (or per tick, for a
125
+ * continuous-mode cognet — see scheduler/). The cognet touches nothing but
126
+ * the ABI built here; the kernel never learns what the model sees or how
127
+ * the brain thinks. Grammar, rendering, strategy: all above this line's
128
+ * pay grade. No thread concept anywhere in this file: one cognet instance
129
+ * is always exactly one continuous stream against the session's one log;
130
+ * multiple independent conversations are multiple Axon() instances, a
131
+ * host-level (TUI) concern this file has no opinion on.
132
+ *
133
+ * The kernel exists to protect user resources from the cognet. The cognet
134
+ * is the unprivileged brain that uses the user's resources as per policy.
135
+ */
136
+ export async function Kernel(opts: KernelOpts) {
137
+ const cognet = opts.cognet
138
+ const session = opts.session
139
+
140
+ const scheduler = Scheduler({
141
+ bus: opts.bus,
142
+ session: session,
143
+ })
144
+
145
+ const capsule = await AxonCapsule({
146
+ boot: true,
147
+ blueprint: opts.blueprint,
148
+ bus: opts.bus,
149
+ session: session,
150
+ run: () => scheduler.current(),
151
+ cwd: opts.cwd,
152
+ ...(opts.host ? { host: opts.host } : {}),
153
+ })
154
+
155
+ const engine = Engine({
156
+ blueprint: opts.blueprint,
157
+ session,
158
+ cloud: opts.cloud,
159
+ })
160
+
161
+ const store = Store({
162
+ blueprint: opts.blueprint,
163
+ cognet: cognet,
164
+ session: session,
165
+ })
166
+
167
+ /** One block or many (concurrent, Promise.all-shaped) — always resolves. */
168
+ function run(code: string, runOpts?: { signal?: AbortSignal }): Promise<AxonRunResult>
169
+ function run(code: string[], runOpts?: { signal?: AbortSignal }): Promise<AxonRunResult[]>
170
+ function run(code: string | string[], runOpts?: { signal?: AbortSignal }): Promise<AxonRunResult> | Promise<AxonRunResult[]> {
171
+ if (Array.isArray(code)) return Promise.all(code.map(c => runOne(capsule, c, runOpts)))
172
+ return runOne(capsule, code, runOpts)
173
+ }
174
+
175
+ /**
176
+ * The ABI's own run() — same normalized result as the script-facing
177
+ * run() above, plus one more step: durably commits cognet:action:typescript
178
+ * (the code) and cognet:action:result (the outcome) to the session's one log,
179
+ * the moment each block settles. This is the platform-owned half of
180
+ * the two-verb rule — the cognet never calls session.commit itself; it
181
+ * just reads the returned result for its own control flow.
182
+ */
183
+ async function runAndCommit(code: string, runOpts?: { signal?: AbortSignal }): Promise<AxonRunResult> {
184
+ const run = scheduler.active() // throws SYSCALL_OUTSIDE_RUN if no wake is running
185
+ const id = Bun.randomUUIDv7()
186
+ await session.commitEntry("cognet:action:typescript", { id, content: code }, run)
187
+ // The entry id IS the capsule command id — one id for one execution,
188
+ // so capsule:cmd/fn/activity spans join the visible tool call directly.
189
+ const result = await runOne(capsule, code, { ...runOpts, id })
190
+ await session.commitEntry("cognet:action:result", {
191
+ for: id,
192
+ ok: result.ok,
193
+ content: [...result.stdout, result.ok ? formatValue(result.value) : ""].filter(s => s.length > 0).join("\n"),
194
+ ...(result.error ? { error: result.error } : {}),
195
+ }, run)
196
+ return result
197
+ }
198
+
199
+ // ── the ABI — the syscall table, bound once to the kernel's organs ──────
200
+ // Process-lifetime object: nothing on it carries per-wake state beyond
201
+ // what scheduler.active() resolves internally. This is the only thing
202
+ // a program ever holds.
203
+ const abi: KernelAbi = {
204
+ /** unmediated — commits directly to the session's one log, never refuses */
205
+ output: (type, data) => {
206
+ const run = scheduler.active() // throws SYSCALL_OUTSIDE_RUN if no wake is running
207
+ // Same TS limitation as emit() below: AxonEntryEvent is an
208
+ // intersection containing AxonOutputEvent — TS can't distribute
209
+ // an indexed access over it for a generic key, but the payload
210
+ // type is identical for every K. Not a shape mismatch.
211
+ return session.commitEntry(type as never, data as never, run).then(() => {})
212
+ },
213
+
214
+ // llm surface
215
+ stream: (req) => engine.stream(req, scheduler.active()),
216
+
217
+ // capsule surface — self-committing (see runAndCommit above)
218
+ run: ((code: string | string[], runOpts?: { signal?: AbortSignal }) => {
219
+ if (Array.isArray(code)) return Promise.all(code.map(c => runAndCommit(c, runOpts)))
220
+ return runAndCommit(code, runOpts)
221
+ }) as KernelAbi["run"],
222
+ scope: () => capsule.current.scope,
223
+
224
+ // environment surface
225
+ base: opts.base,
226
+
227
+ /**
228
+ * Cognet telemetry — enforced at the call site, not just the type:
229
+ * the cognet's own `emit<K extends keyof CognetEventMap>` signature
230
+ * already prevents a well-typed call from naming anything outside
231
+ * cognet:*, but nothing stopped a raw/untyped call from reaching the
232
+ * write path under any string. Refusing loudly here closes that gap —
233
+ * a cognet can narrate its own world, never forge kernel machinery.
234
+ *
235
+ * Durable: commits to the session's log (which forwards to the bus
236
+ * after the append lands), same pipeline as every other event — the
237
+ * cognet's telemetry is debugging record, and a log it never reaches
238
+ * is a log that can't debug it. Fire-and-forget for the cognet
239
+ * (emit stays sync/void); a continuous-mode cognet ticking fast will
240
+ * make this chatty — the known cost, gate at the write if it bites.
241
+ */
242
+ emit: (type, data) => {
243
+ if (!(type as string).startsWith(COGNET_EVENT_PREFIX)) {
244
+ throw err("COGNET_EMIT_FORBIDDEN", { detail: `cognet may only emit cognet:* events, got "${type as string}"`, context: { type: type as string } })
245
+ }
246
+ // runId when a wake is running, bare outside one (load/unload
247
+ // narration is legal) — current() never throws, unlike active().
248
+ void session.commit(type, data as AxonEventMap[typeof type], scheduler.current() ?? undefined)
249
+ },
250
+
251
+ // persistence surface — private cognitive state + read-only episodic
252
+ // access, one mediated door like stream/run (see Store())
253
+ store: store,
254
+ }
255
+
256
+ // exec(): the kernel is the only loader. ABI compatibility is checked
257
+ // inside the handle; a mismatched artifact never half-loads.
258
+ await cognet.load(abi)
259
+ scheduler.attach(cognet)
260
+
261
+ return {
262
+ /** Invoke on a stimulus arrival — invocation-mode cognets only; throws for continuous-mode. */
263
+ stream(input: KernelInput = {}) {
264
+ return scheduler.stream(input)
265
+ },
266
+
267
+ /** Collect a full wake: every durable entry, in commit order. */
268
+ async request(input: KernelInput = {}): Promise<{ ok: true; entries: AxonEntry[] }> {
269
+ const entries: AxonEntry[] = []
270
+ for await (const entry of scheduler.stream(input).stream) {
271
+ entries.push(entry) // the wire carries entries, full stop — chunks included
272
+ }
273
+ return { ok: true, entries }
274
+ },
275
+
276
+ /** Abort the active wake, if any. Safe to call when idle. */
277
+ interrupt(reason: "user" | "shutdown" = "user") {
278
+ scheduler.interrupt(reason)
279
+ },
280
+
281
+ /**
282
+ * Execute code in the capsule directly — the same conversation an
283
+ * agent-generated <typescript> block gets, mediated by the same
284
+ * policy and the same normalized result. Backs axon.tools.* proxy
285
+ * calls from script-land; the kernel is the only capsule
286
+ * constructor, so callers reach it here, never by holding the
287
+ * capsule handle themselves.
288
+ */
289
+ run,
290
+
291
+ /**
292
+ * The capsule's process tree, live: `main` is the sandboxed TS
293
+ * runtime itself, `processes` its managed children (everything the
294
+ * agent has spawned). Read/observe surface for clients (the TUI's
295
+ * capsule tree); the kernel remains the only constructor.
296
+ */
297
+ get userland() {
298
+ return {
299
+ main: capsule.current.main,
300
+ processes: capsule.current.process.list(),
301
+ }
302
+ },
303
+
304
+ /**
305
+ * The agent changed: one entry point, fanned out to the organs.
306
+ * Receives the full re-normalized blueprint from the runtime.
307
+ */
308
+ async update(next: AxonBlueprint) {
309
+ engine.update(next)
310
+ opts.onUpdate?.(next)
311
+ await cognet.update(next)
312
+ await capsule.update(next) // new policy → rebuilt sandbox, live before old drops
313
+ },
314
+
315
+ /**
316
+ * Drain the mind: abort any wake, stop the scheduler's clock (if
317
+ * continuous), unload the brain, kill the userland. Session is not
318
+ * kernel's to close — AxonRuntime.shutdown() ends it after this
319
+ * resolves, so a failure here never skips flushing the log.
320
+ */
321
+ async shutdown() {
322
+ scheduler.interrupt("shutdown")
323
+ scheduler.stop()
324
+ await cognet.unload()
325
+ await capsule.shutdown()
326
+ },
327
+ }
328
+ }
329
+
330
+ export type AxonKernelT = Awaited<ReturnType<typeof Kernel>>
@@ -0,0 +1,44 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonEntry, AxonStimulusEntry } from "@arcforge/types"
3
+ import type { AxonSessionT } from "@arcforge/session"
4
+
5
+ type ContinuousOpts = {
6
+ session: AxonSessionT
7
+ reserve: () => string
8
+ release: (id?: string) => void
9
+ runWake: (reservationId: string, input: { stimuli: AxonStimulusEntry[] }) => AsyncGenerator<AxonEntry>
10
+ }
11
+
12
+ /**
13
+ * Continuous trigger: invoked on a fixed clock regardless of whether
14
+ * anything arrived — an empty stimuli diff is the ordinary steady state,
15
+ * not an edge case a cognet needs to special-case.
16
+ *
17
+ * STUBBED. Landing the shape (type, wiring, start/stop lifecycle) now
18
+ * without guessing at tick semantics — no real continuous cognet exists
19
+ * yet to validate wake-overlap policy against (does a slow tick skip the
20
+ * next one, queue, or run concurrently?). Answering this without a real
21
+ * workload would be exactly the kind of premature generalization this
22
+ * whole redesign was trying to avoid. (The removal of "thread" as a
23
+ * concept actually simplifies what's left to design here — there's no
24
+ * longer a question of which of several conversations a tick addresses;
25
+ * one cognet instance is always exactly one continuous stream.)
26
+ */
27
+ export function Continuous(_opts: ContinuousOpts) {
28
+ let timer: ReturnType<typeof setInterval> | null = null
29
+
30
+ return {
31
+ start(_tickMs: number) {
32
+ throw err("SCHEDULER_CONTINUOUS_NOT_IMPLEMENTED", {
33
+ detail: "continuous mode is a declared, stubbed shape — no cognet may select it yet",
34
+ })
35
+ },
36
+
37
+ stop() {
38
+ if (timer) clearInterval(timer)
39
+ timer = null
40
+ },
41
+ }
42
+ }
43
+
44
+ export type ContinuousT = ReturnType<typeof Continuous>
@@ -0,0 +1,2 @@
1
+ export { Scheduler } from "./scheduler"
2
+ export type { SchedulerT } from "./scheduler"
@@ -0,0 +1,59 @@
1
+ import type { AxonEntry, AxonStimulusEntry } from "@arcforge/types"
2
+ import type { AxonSessionT } from "@arcforge/session"
3
+
4
+ type InvocationOpts = {
5
+ session: AxonSessionT
6
+ reserve: () => string
7
+ release: (id?: string) => void
8
+ runWake: (reservationId: string, input: { stimuli: AxonStimulusEntry[] }) => AsyncGenerator<AxonEntry>
9
+ interrupt: (reason: "user" | "shutdown", reservationId?: string) => void
10
+ }
11
+
12
+ type StreamInput = {
13
+ content?: string | string[]
14
+ }
15
+
16
+ /**
17
+ * Invocation trigger: one wake per admitted stimulus. The caller (kernel's
18
+ * public stream()/request()) supplies the thing that just happened —
19
+ * usually a user message — which gets committed as the FIRST stimulus, then
20
+ * the scheduler drains whatever else has accumulated on the buffer since the
21
+ * last invoke (stimuli.ts's own design: several may have queued while the
22
+ * previous wake was still running) and hands the cognet the whole diff in
23
+ * one call.
24
+ */
25
+ export function Invocation(opts: InvocationOpts) {
26
+ function stream(input: StreamInput = {}) {
27
+ const reservationId = opts.reserve()
28
+
29
+ const wire = (async function* () {
30
+ try {
31
+ const contents = input.content === undefined
32
+ ? []
33
+ : Array.isArray(input.content) ? input.content : [input.content]
34
+ for (const content of contents) {
35
+ const entry = await opts.session.stimuli.ingest("cognet:stimulus:text", {
36
+ source: { channel: "user" },
37
+ content,
38
+ })
39
+ yield entry
40
+ }
41
+
42
+ const stimuli = opts.session.stimuli.drain()
43
+ yield* opts.runWake(reservationId, { stimuli })
44
+ } catch (cause) {
45
+ opts.release(reservationId)
46
+ throw cause
47
+ }
48
+ })()
49
+
50
+ return {
51
+ stream: wire,
52
+ interrupt: () => opts.interrupt("user", reservationId),
53
+ }
54
+ }
55
+
56
+ return { stream }
57
+ }
58
+
59
+ export type InvocationT = ReturnType<typeof Invocation>
@@ -0,0 +1,153 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonEntry, AxonStimulusEntry } from "@arcforge/types"
3
+ import type { KernelBus } from "../contracts"
4
+ import type { AxonSessionT } from "@arcforge/session"
5
+ import type { KernelCognet } from "../contracts"
6
+ import { Wake } from "./wake"
7
+ import { Invocation } from "./invocation"
8
+ import { Continuous } from "./continuous"
9
+
10
+ type SchedulerOpts = {
11
+ bus: KernelBus
12
+ session: AxonSessionT
13
+ }
14
+
15
+ type InvokeInput = {
16
+ /** User message committed before the invoke starts. */
17
+ content?: string | string[]
18
+ }
19
+
20
+ /**
21
+ * Scheduler — the kernel's process manager. Decides WHEN cognet.wake() is
22
+ * called and WHAT diff it's handed; owns nothing about HOW a wake executes
23
+ * once started (that's wake.ts, unchanged regardless of trigger source).
24
+ *
25
+ * Two trigger sources, one mechanism: invocation.ts fires on an admitted
26
+ * stimulus, continuous.ts fires on a clock — both call the same internal
27
+ * runWake(), which drains session.stimuli and hands the diff to Wake().
28
+ * Neither trigger source knows the other exists; the cognet's declared
29
+ * `mode` picks which one is wired up.
30
+ *
31
+ * SCHEDULING POLICY (policy, not physics — revisit without contract change):
32
+ * one wake at a time, globally. A concurrent invoke throws RUN_IN_PROGRESS.
33
+ */
34
+ export function Scheduler(opts: SchedulerOpts) {
35
+ let cognet: KernelCognet | null = null
36
+ let active: { runId: string } | null = null
37
+ let reservation: { id: string; abort: AbortController } | null = null
38
+
39
+ /**
40
+ * Reserve the scheduler SYNCHRONOUSLY, at the true call boundary — an
41
+ * async generator's body doesn't run until iterated, so locking inside
42
+ * would leave a window where two callers both mint a wire.
43
+ */
44
+ function reserve(): string {
45
+ if (reservation) throw err("RUN_IN_PROGRESS")
46
+ const id = Bun.randomUUIDv7()
47
+ reservation = { id, abort: new AbortController() }
48
+ return id
49
+ }
50
+
51
+ function release(id?: string): void {
52
+ if (id !== undefined && reservation?.id !== id) return
53
+ active = null
54
+ reservation = null
55
+ }
56
+
57
+ /**
58
+ * Run one wake as an already-reserved execution, handed a stimuli diff.
59
+ * Both trigger sources call this identically — it has no idea whether a
60
+ * stimulus or a clock caused it to be called.
61
+ */
62
+ function runWake(reservationId: string, input: { stimuli: AxonStimulusEntry[] }): AsyncGenerator<AxonEntry> {
63
+ if (reservation?.id !== reservationId) throw err("RUN_RESERVATION_EXPIRED")
64
+ if (!cognet) {
65
+ release(reservationId)
66
+ throw err("NO_COGNET_LOADED")
67
+ }
68
+
69
+ const wake = Wake({
70
+ cognet,
71
+ stimuli: input.stimuli,
72
+ bus: opts.bus,
73
+ session: opts.session,
74
+ abort: reservation.abort,
75
+ })
76
+ active = { runId: wake.runId }
77
+
78
+ return (async function* () {
79
+ try {
80
+ // Every pull re-enters the wake body under the session's
81
+ // error scope: an async generator resumes in its CALLER's
82
+ // async context (the host consuming the stream), not its
83
+ // creation context, so wrapping creation alone would leak
84
+ // wake-time err() calls out of attribution. Scoping each
85
+ // next() means everything the wake executes — cognet code,
86
+ // engine calls, ABI syscalls — attributes to this session.
87
+ const inner = wake.stream()
88
+ while (true) {
89
+ const result = await opts.session.scope(() => inner.next())
90
+ if (result.done) return
91
+ yield result.value
92
+ }
93
+ } finally {
94
+ release(reservationId)
95
+ }
96
+ })()
97
+ }
98
+
99
+ /** abort the active wake, if any — safe to call when idle */
100
+ function interrupt(reason: "user" | "shutdown" = "user", reservationId?: string) {
101
+ if (reservationId !== undefined && reservation?.id !== reservationId) return
102
+ reservation?.abort.abort(reason)
103
+ }
104
+
105
+ const invocation = Invocation({ session: opts.session, reserve, release, runWake, interrupt })
106
+ const continuous = Continuous({ session: opts.session, reserve, release, runWake })
107
+
108
+ return {
109
+ get loaded() {
110
+ return cognet !== null
111
+ },
112
+
113
+ /** register the loaded cognet — the kernel runs load(abi) first */
114
+ attach(next: KernelCognet) {
115
+ cognet = next
116
+ if (next.mode.kind === "continuous") continuous.start(next.mode.tickMs)
117
+ },
118
+
119
+ /** Invoke on a stimulus admission (invocation mode) — no-op shape for continuous cognets, which never call this. */
120
+ stream(input: InvokeInput = {}) {
121
+ if (!cognet) throw err("NO_COGNET_LOADED")
122
+ if (cognet.mode.kind === "continuous") {
123
+ throw err("SCHEDULER_MODE_MISMATCH", { detail: "continuous cognets are invoked by the scheduler's own clock, never by stream()" })
124
+ }
125
+ return invocation.stream(input)
126
+ },
127
+
128
+ /**
129
+ * The currently running wake's correlation — run addressing is
130
+ * ambient, resolved here rather than passed by the cognet (there's
131
+ * no session/thread on the ABI for it to address by hand). Every
132
+ * syscall the ABI exposes (output, run, stream) reads this.
133
+ */
134
+ active() {
135
+ if (!active) throw err("SYSCALL_OUTSIDE_RUN")
136
+ return active
137
+ },
138
+
139
+ /** Like active(), but null outside a wake instead of throwing — for emitters (cognet telemetry) that legally fire during load/unload. */
140
+ current() {
141
+ return active
142
+ },
143
+
144
+ interrupt,
145
+
146
+ /** stop the continuous clock, if running — called on kernel shutdown/reload */
147
+ stop() {
148
+ continuous.stop()
149
+ },
150
+ }
151
+ }
152
+
153
+ export type SchedulerT = ReturnType<typeof Scheduler>