@arcforge/kernel 2.0.113 → 2.0.115

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcforge/kernel",
3
- "version": "2.0.113",
3
+ "version": "2.0.115",
4
4
  "description": "The Axon kernel — ring 0. Owns resources and execution, enforces policy, and is the only constructor of the unprivileged capsule.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -15,13 +15,13 @@
15
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
16
  },
17
17
  "dependencies": {
18
- "@arcforge/cognet": "2.0.113",
19
- "@arcforge/engines": "2.0.113",
20
- "@arcforge/err": "2.0.113",
21
- "@arcforge/session": "2.0.113",
22
- "@arcforge/types": "2.0.113",
23
- "@arclabs/cloud": "2.0.113",
24
- "@axon/capsule": "2.0.113"
18
+ "@arcforge/cognet": "2.0.115",
19
+ "@arcforge/engines": "2.0.115",
20
+ "@arcforge/err": "2.0.115",
21
+ "@arcforge/session": "2.0.115",
22
+ "@arcforge/types": "2.0.115",
23
+ "@arclabs/cloud": "2.0.115",
24
+ "@axon/capsule": "2.0.115"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/bun": "latest",
package/src/engine.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { err } from "@arcforge/err"
2
2
  import type {
3
+ AirProtocolName,
3
4
  AxonBlueprint,
5
+ AxonEngineCall,
4
6
  AxonEngineDriver,
5
7
  AxonEngineEvent,
6
- AxonEngineRequest,
7
8
  AxonEngineResponse,
8
9
  EngineCloud,
9
10
  } from "@arcforge/types"
10
11
  import { asEngineFault, EngineFailure, resolveEngine } from "@arcforge/engines"
11
- import { Air, type AirBlockEvent } from "@arcforge/cognet/air"
12
+ import { Air, type AirBlockEvent, type AirT } from "@arcforge/cognet/air"
12
13
  import type { AxonSessionT } from "@arcforge/session"
13
14
 
14
15
  type EngineOpts = {
@@ -35,7 +36,24 @@ const RETRY_DELAYS_MS = [100, 300] as const
35
36
  * retrying could duplicate semantic output, so that failure is terminal.
36
37
  */
37
38
  export function Engine(opts: EngineOpts) {
38
- const air = Air()
39
+ /**
40
+ * One Air per protocol, built on first use and reused.
41
+ *
42
+ * The grammar is resolved from the CALLER's protocol, not the runtime's:
43
+ * the cognet that rendered the context is the only thing that knows which
44
+ * contract the model was shown, and a parser accepting different tags
45
+ * than the contract declared would silently discard every block.
46
+ */
47
+ const airs = new Map<AirProtocolName, AirT>()
48
+ const airFor = (protocol: AirProtocolName = "classic"): AirT => {
49
+ let air = airs.get(protocol)
50
+ if (!air) {
51
+ air = Air({ protocol })
52
+ airs.set(protocol, air)
53
+ }
54
+ return air
55
+ }
56
+
39
57
  let blueprint = opts.blueprint
40
58
  let current = build(blueprint)
41
59
 
@@ -45,7 +63,11 @@ export function Engine(opts: EngineOpts) {
45
63
  return { driver: def.create({ env: blueprint.env, cloud: opts.cloud }), name: def.name }
46
64
  }
47
65
 
48
- async function* stream(req: AxonEngineRequest, context: EngineContext): AsyncGenerator<AxonEngineEvent> {
66
+ async function* stream(call: AxonEngineCall, context: EngineContext): AsyncGenerator<AxonEngineEvent> {
67
+ // Protocol is the manager's concern, never the driver's — drivers are
68
+ // token pipes and must not receive a field they'd have to ignore.
69
+ const { protocol, ...req } = call
70
+ const air = airFor(protocol)
49
71
  const span = { ...context, spanId: Bun.randomUUIDv7() }
50
72
  // The whole logical call, retries and AIR parsing included — distinct
51
73
  // from meta.durationMs, which is one attempt's provider latency. A
@@ -249,7 +271,7 @@ export function Engine(opts: EngineOpts) {
249
271
 
250
272
  stream: stream,
251
273
 
252
- async request(req: AxonEngineRequest, context: EngineContext): Promise<AxonEngineResponse> {
274
+ async request(req: AxonEngineCall, context: EngineContext): Promise<AxonEngineResponse> {
253
275
  for await (const event of stream(req, context)) {
254
276
  if (event.type === "engine:done") return event.response
255
277
  }
@@ -319,13 +341,20 @@ function toBlockEvent(block: AirBlockEvent): AxonEngineEvent | null {
319
341
  if (block.incomplete) return incomplete("typescript", block.content)
320
342
  return { type: "engine:typescript", id: Bun.randomUUIDv7(), content: block.content }
321
343
 
322
- case "shell:done":
323
- return {
324
- type: "engine:output:error",
325
- code: "UNSUPPORTED_BLOCK",
326
- message: "shell blocks are not executable in this runtime",
327
- excerpt: block.content.slice(0, 200),
328
- }
344
+ // ── sfc protocol ────────────────────────────────────────────────
345
+ case "script:done":
346
+ if (block.incomplete) return incomplete("script", block.content)
347
+ return { type: "engine:script", id: Bun.randomUUIDv7(), content: block.content }
348
+
349
+ case "template:open":
350
+ return { type: "engine:template:open", lang: block.lang }
351
+
352
+ case "template:delta":
353
+ return { type: "engine:template:delta", content: block.content }
354
+
355
+ case "template:done":
356
+ if (block.incomplete) return incomplete("template", block.content)
357
+ return { type: "engine:template", content: block.content }
329
358
 
330
359
  case "done":
331
360
  return { type: "engine:stop" }
package/src/kernel.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { err } from "@arcforge/err"
2
- import type { AxonBlueprint, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
2
+ import type { AxonBlueprint, AxonEngineEvent, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
3
+ import { EMPTY_CAPSULE_SCOPE } from "@arcforge/types"
3
4
  import type { AxonCloudClient } from "@arclabs/cloud"
4
5
  import type { KernelBus } from "./contracts"
5
6
  import { Engine } from "./engine"
@@ -86,14 +87,21 @@ async function runOne(capsule: AxonCapsuleT, code: string, opts?: { signal?: Abo
86
87
  }
87
88
 
88
89
  try {
89
- const value = await capsule.current.run(code, { onConsole, signal: opts?.signal, id: opts?.id })
90
- return { ok: true, value, stdout }
90
+ // exec() rather than run(): the bindings come back alongside the
91
+ // value, so a cognet rendering a template from the same turn has
92
+ // something to interpolate against.
93
+ const { value, scope } = await capsule.current.exec(code, { onConsole, signal: opts?.signal, id: opts?.id })
94
+ return { ok: true, value, stdout, scope }
91
95
  } catch (cause) {
92
96
  const interrupted = opts?.signal?.aborted || (cause instanceof Error && cause.name === "AbortError")
93
97
  const timedOut = cause instanceof Error && /timed out/.test(cause.message)
94
98
  return {
95
99
  ok: false,
96
100
  stdout,
101
+ // A block that threw declared nothing usable — an empty scope is
102
+ // the honest value, and keeps callers from having to test for
103
+ // absence before every interpolation.
104
+ scope: EMPTY_CAPSULE_SCOPE,
97
105
  error: {
98
106
  kind: interrupted ? "interrupt" : timedOut ? "timeout" : "exception",
99
107
  message: cause instanceof Error ? cause.message : String(cause),
@@ -196,6 +204,51 @@ export async function Kernel(opts: KernelOpts) {
196
204
  return result
197
205
  }
198
206
 
207
+ /**
208
+ * The engine stream, with format violations recorded as system facts.
209
+ *
210
+ * A violation is the KERNEL's observation, not the cognet's speech: the
211
+ * AIR parser detected it, and a cognet paraphrasing it through output()
212
+ * would put runtime diagnostics in the agent's own voice — indistinguishable
213
+ * from something the agent said, both to a reader and to the next render.
214
+ * Committing it here as axon:system:message keeps the provenance honest,
215
+ * renders it dimmed rather than as a message, and still puts it in front of
216
+ * the model next tick (AIR renders <system>), which is what makes the
217
+ * self-correction loop work.
218
+ *
219
+ * The event still reaches the cognet — a loop may want to react — but it
220
+ * no longer has to launder it to make it visible.
221
+ */
222
+ /**
223
+ * Record one format violation as a system fact.
224
+ *
225
+ * The single writer for both sources — the parser's own detections
226
+ * (an unclosed block) and a cognet's via fault() (an interpolation
227
+ * naming a binding that was never declared). One shape, one entry type,
228
+ * one thing for a host to recognise and hide.
229
+ */
230
+ function recordFault(
231
+ fault: { code: string; message: string; excerpt?: string },
232
+ run: { runId: string } | undefined,
233
+ ): Promise<unknown> {
234
+ return session.commitEntry("axon:system:message", {
235
+ type: "format-violation",
236
+ lang: "txt",
237
+ content: `${fault.code}: ${fault.message}`,
238
+ ...(fault.excerpt ? { attributes: { excerpt: fault.excerpt } } : {}),
239
+ }, run)
240
+ }
241
+
242
+ async function* streamAndRecord(req: Parameters<typeof engine.stream>[0]): AsyncGenerator<AxonEngineEvent> {
243
+ const run = scheduler.active()
244
+ for await (const event of engine.stream(req, run)) {
245
+ if (event.type === "engine:output:error") {
246
+ await recordFault(event, run)
247
+ }
248
+ yield event
249
+ }
250
+ }
251
+
199
252
  // ── the ABI — the syscall table, bound once to the kernel's organs ──────
200
253
  // Process-lifetime object: nothing on it carries per-wake state beyond
201
254
  // what scheduler.active() resolves internally. This is the only thing
@@ -214,7 +267,13 @@ export async function Kernel(opts: KernelOpts) {
214
267
  },
215
268
 
216
269
  // llm surface
217
- stream: (req) => engine.stream(req, scheduler.active()),
270
+ stream: (req) => streamAndRecord(req),
271
+
272
+ /**
273
+ * A format violation the COGNET detected while rendering the model's
274
+ * output — the kernel writes the system fact the cognet may not forge.
275
+ */
276
+ fault: (input) => recordFault(input, scheduler.active()).then(() => {}),
218
277
 
219
278
  // capsule surface — self-committing (see runAndCommit above)
220
279
  run: ((code: string | string[], runOpts?: { signal?: AbortSignal }) => {
@@ -374,9 +433,20 @@ export async function Kernel(opts: KernelOpts) {
374
433
  * ends it after this resolves, so a failure here never skips flushing
375
434
  * the log.
376
435
  *
377
- * No clock to stop: a continuous cognet is ticked by the body (a
378
- * plugin driving `axon.tick()`), which tears its own interval down on
379
- * `shutdown:before` — before this runs.
436
+ * THE BRAIN STOPS ITS OWN CLOCK, AND IT MUST STILL HAVE A KERNEL WHEN
437
+ * IT DOES. A continuous cognet is ticked by one of its own plugins
438
+ * driving kernel.wake() on an interval, and that interval is cleared
439
+ * by the plugin's own "shutdown" hook — which runs inside
440
+ * cognet.unload(). So unload() has to complete BEFORE anything the
441
+ * clock touches is torn down.
442
+ *
443
+ * This used to call scheduler.detach() first, on the reasoning that a
444
+ * brain being torn down can no longer wake. True, but it made wake()
445
+ * throw NO_COGNET_LOADED while a 30Hz interval was still firing into
446
+ * it — an unhandled rejection every ~33ms of teardown, from a plugin
447
+ * doing exactly what the authoring surface tells it to. Detaching
448
+ * after unload closes that window without weakening the guard: the
449
+ * clock is already stopped by then, so nothing is left to wake.
380
450
  */
381
451
  async shutdown() {
382
452
  scheduler.interrupt("shutdown")
@@ -387,10 +457,6 @@ export async function Kernel(opts: KernelOpts) {
387
457
  // rethrown after the box is definitely gone.
388
458
  const unloadStarted = Date.now()
389
459
  await session.commit("cognet:unload:start", { name: cognet.name })
390
- // Before the unload, not after: whether it succeeds or throws, a
391
- // brain being torn down can no longer wake, and readiness must
392
- // stop claiming otherwise the moment that becomes true.
393
- scheduler.detach()
394
460
  let failure: ReturnType<typeof err> | null = null
395
461
  try {
396
462
  await cognet.unload()
@@ -399,6 +465,10 @@ export async function Kernel(opts: KernelOpts) {
399
465
  failure = err(cause)
400
466
  await session.commit("cognet:unload:failed", { name: cognet.name, error: failure, durationMs: Date.now() - unloadStarted })
401
467
  }
468
+ // After the unload, whether it succeeded or threw: readiness must
469
+ // stop claiming a brain that is gone, and a cognet whose unload
470
+ // failed is no more wakeable than one whose unload worked.
471
+ scheduler.detach()
402
472
 
403
473
  await capsule.shutdown()
404
474
  if (failure) throw failure