@arcforge/kernel 2.0.101 → 2.0.103

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.101",
3
+ "version": "2.0.103",
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.101",
19
- "@arcforge/engines": "2.0.101",
20
- "@arcforge/err": "2.0.101",
21
- "@arcforge/session": "2.0.101",
22
- "@arcforge/types": "2.0.101",
23
- "@arclabs/cloud": "2.0.101",
24
- "@axon/capsule": "2.0.101"
18
+ "@arcforge/cognet": "2.0.103",
19
+ "@arcforge/engines": "2.0.103",
20
+ "@arcforge/err": "2.0.103",
21
+ "@arcforge/session": "2.0.103",
22
+ "@arcforge/types": "2.0.103",
23
+ "@arclabs/cloud": "2.0.103",
24
+ "@axon/capsule": "2.0.103"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/bun": "latest",
package/src/capsule.ts CHANGED
@@ -150,12 +150,23 @@ export async function AxonCapsule(opts: AxonCapsuleOpts) {
150
150
  async function boot(): Promise<CapsuleT> {
151
151
  const capsule = Capsule(config())
152
152
  capsule.onAny((event) => {
153
+ // The sandbox reports every cwd change as it happens, so the
154
+ // live location is always known without asking for it.
155
+ if (event.type === "capsule:cwd") liveCwd = event.cwd
153
156
  const { type, ...data } = event
157
+ // onAny is a synchronous listener on the capsule's own bus — it
158
+ // cannot await, so both writes below are fire-and-forget. The
159
+ // catches are load-bearing rather than defensive: every capsule
160
+ // event flows through here, and an unhandled rejection from a
161
+ // full disk or a throwing bus handler would take the whole
162
+ // process down for what is, at worst, one lost telemetry line.
154
163
  if (CAPSULE_TRANSIENT_EVENTS.has(type)) {
155
- void opts.bus.forward(event)
164
+ void opts.bus.forward(event).catch(() => {})
156
165
  return
157
166
  }
158
- void opts.session.commit(type, data as AxonEventMap[typeof type], opts.run?.() ?? undefined)
167
+ void opts.session
168
+ .commit(type, data as AxonEventMap[typeof type], opts.run?.() ?? undefined)
169
+ .catch(() => {})
159
170
  })
160
171
  await capsule.boot()
161
172
 
@@ -165,24 +176,6 @@ export async function AxonCapsule(opts: AxonCapsuleOpts) {
165
176
  return capsule
166
177
  }
167
178
 
168
- /**
169
- * The declared contract (see scope/declarations.ts) is "cwd changes
170
- * persist across blocks" — true within one capsule's lifetime, silently
171
- * false across a reload unless the incoming capsule inherits where the
172
- * outgoing one actually was. Best-effort: a query that fails (dead
173
- * incarnation, mid-crash) falls back to the last known liveCwd, not a
174
- * hard failure — reload must not abort because the outgoing capsule
175
- * can't answer one last question.
176
- */
177
- async function captureLiveCwd(capsule: CapsuleT): Promise<void> {
178
- try {
179
- const result = await capsule.run("process.cwd()", { timeout: 5_000 })
180
- if (typeof result === "string" && result.length > 0) liveCwd = result
181
- } catch {
182
- // Outgoing capsule couldn't answer — keep whatever liveCwd already holds.
183
- }
184
- }
185
-
186
179
  /**
187
180
  * Commit a detach for whatever capsule id is passed in — always the
188
181
  * OUTGOING one, captured by the caller before boot() overwrites
@@ -197,7 +190,10 @@ export async function AxonCapsule(opts: AxonCapsuleOpts) {
197
190
  async function reload() {
198
191
  const previous = current
199
192
  const previousId = currentId
200
- if (previous) await captureLiveCwd(previous)
193
+ // liveCwd is already current — the outgoing sandbox reported every
194
+ // move as it happened (capsule:cwd), so there is nothing to ask it
195
+ // for on the way out. This used to execute process.cwd() inside a
196
+ // dying incarnation and silently keep a stale value when that failed.
201
197
  current = await boot()
202
198
  await previous?.shutdown()
203
199
  if (previousId) await detach(previousId, "reload")
package/src/engine.ts CHANGED
@@ -47,6 +47,10 @@ export function Engine(opts: EngineOpts) {
47
47
 
48
48
  async function* stream(req: AxonEngineRequest, context: EngineContext): AsyncGenerator<AxonEngineEvent> {
49
49
  const span = { ...context, spanId: Bun.randomUUIDv7() }
50
+ // The whole logical call, retries and AIR parsing included — distinct
51
+ // from meta.durationMs, which is one attempt's provider latency. A
52
+ // call that succeeded on its third try shows both numbers honestly.
53
+ const callStarted = Date.now()
50
54
  if (!current) {
51
55
  const fault = {
52
56
  code: "INVALID_REQUEST" as const,
@@ -59,7 +63,7 @@ export function Engine(opts: EngineOpts) {
59
63
  messages: req.messages,
60
64
  bytes: new TextEncoder().encode(JSON.stringify(req.messages)).byteLength,
61
65
  }, span)
62
- await opts.session.commit("kernel:engine:failed", { attempts: 0, fault }, span)
66
+ await opts.session.commit("kernel:engine:failed", { attempts: 0, fault, durationMs: Date.now() - callStarted }, span)
63
67
  throw err("ENGINE_MISSING")
64
68
  }
65
69
 
@@ -169,6 +173,7 @@ export function Engine(opts: EngineOpts) {
169
173
  ...(response.thinking ? { thinking: response.thinking } : {}),
170
174
  stopReason: response.stopReason,
171
175
  meta,
176
+ durationMs: Date.now() - callStarted,
172
177
  }, span)
173
178
  yield { type: "engine:done", response }
174
179
  return
@@ -210,7 +215,7 @@ export function Engine(opts: EngineOpts) {
210
215
  if (req.signal?.aborted) throw abortError(req.signal)
211
216
 
212
217
  const abortFault = asEngineFault(delayError, correlation)
213
- await opts.session.commit("kernel:engine:failed", { attempts: attempt, fault: abortFault }, span)
218
+ await opts.session.commit("kernel:engine:failed", { attempts: attempt, fault: abortFault, durationMs: Date.now() - callStarted }, span)
214
219
  throw err("ENGINE_STREAM_FAILED", {
215
220
  detail: abortFault.message,
216
221
  context: { code: abortFault.code, provider: abortFault.provider, model: abortFault.model, retryable: abortFault.retryable, attempts: attempt },
@@ -220,7 +225,7 @@ export function Engine(opts: EngineOpts) {
220
225
  continue
221
226
  }
222
227
 
223
- await opts.session.commit("kernel:engine:failed", { attempts: attempt, fault }, span)
228
+ await opts.session.commit("kernel:engine:failed", { attempts: attempt, fault, durationMs: Date.now() - callStarted }, span)
224
229
  if (fault.code === "AUTH_NOT_CONNECTED" && fault.provider === "codex") {
225
230
  throw err("CODEX_NOT_CONNECTED", {
226
231
  detail: fault.message,
package/src/kernel.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { err } from "@arcforge/err"
2
- import type { AxonBlueprint, AxonEntry, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
2
+ import type { AxonBlueprint, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
3
3
  import type { AxonCloudClient } from "@arclabs/cloud"
4
4
  import type { KernelBus } from "./contracts"
5
5
  import { Engine } from "./engine"
@@ -204,11 +204,13 @@ export async function Kernel(opts: KernelOpts) {
204
204
  /** unmediated — commits directly to the session's one log, never refuses */
205
205
  output: (type, data) => {
206
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(() => {})
207
+ // AxonEntryEvent is an intersection that CONTAINS AxonOutputEvent,
208
+ // so for any output key the two payload types are the same type —
209
+ // TS can't prove it through the intersection for a generic K. The
210
+ // TYPE is now fully checked (it was `as never` before, checking
211
+ // nothing); only the payload's provenance needs asserting, and
212
+ // it's asserted at this one key, not across the union.
213
+ return session.commitEntry(type, data as AxonEntryEvent[typeof type], run).then(() => {})
212
214
  },
213
215
 
214
216
  // llm surface
@@ -245,7 +247,16 @@ export async function Kernel(opts: KernelOpts) {
245
247
  }
246
248
  // runId when a wake is running, bare outside one (load/unload
247
249
  // narration is legal) — current() never throws, unlike active().
248
- void session.commit(type, data as AxonEventMap[typeof type], scheduler.current() ?? undefined)
250
+ //
251
+ // The catch is required, not defensive: emit() is sync by
252
+ // contract (the cognet never awaits its own telemetry), so a
253
+ // rejected commit has nowhere to go. Without it a disk failure
254
+ // during a fast-ticking wake would surface as an unhandled
255
+ // rejection and kill the runtime — a telemetry write must never
256
+ // be able to take down the thing it is observing.
257
+ void session
258
+ .commit(type, data as AxonEventMap[typeof type], scheduler.current() ?? undefined)
259
+ .catch(() => {})
249
260
  },
250
261
 
251
262
  // persistence surface — private cognitive state + read-only episodic
@@ -255,7 +266,20 @@ export async function Kernel(opts: KernelOpts) {
255
266
 
256
267
  // exec(): the kernel is the only loader. ABI compatibility is checked
257
268
  // inside the handle; a mismatched artifact never half-loads.
258
- await cognet.load(abi)
269
+ //
270
+ // The kernel owns this bracket rather than the cognet: exec'ing an
271
+ // untrusted artifact is boot's most failure-prone step, and a brain that
272
+ // dies inside load() could never close a bracket it opened itself.
273
+ const loadStarted = Date.now()
274
+ await session.commit("cognet:load:start", { name: cognet.name })
275
+ try {
276
+ await cognet.load(abi)
277
+ } catch (cause) {
278
+ const failure = err(cause)
279
+ await session.commit("cognet:load:failed", { name: cognet.name, error: failure, durationMs: Date.now() - loadStarted })
280
+ throw failure
281
+ }
282
+ await session.commit("cognet:load:complete", { name: cognet.name, durationMs: Date.now() - loadStarted })
259
283
  scheduler.attach(cognet)
260
284
 
261
285
  return {
@@ -321,8 +345,24 @@ export async function Kernel(opts: KernelOpts) {
321
345
  async shutdown() {
322
346
  scheduler.interrupt("shutdown")
323
347
  scheduler.stop()
324
- await cognet.unload()
348
+
349
+ // A failed unload must never strand the userland: the capsule is
350
+ // a real OS process, and skipping its teardown leaks it for the
351
+ // life of the host. The brain's failure is recorded, then
352
+ // rethrown after the box is definitely gone.
353
+ const unloadStarted = Date.now()
354
+ await session.commit("cognet:unload:start", { name: cognet.name })
355
+ let failure: ReturnType<typeof err> | null = null
356
+ try {
357
+ await cognet.unload()
358
+ await session.commit("cognet:unload:complete", { name: cognet.name, durationMs: Date.now() - unloadStarted })
359
+ } catch (cause) {
360
+ failure = err(cause)
361
+ await session.commit("cognet:unload:failed", { name: cognet.name, error: failure, durationMs: Date.now() - unloadStarted })
362
+ }
363
+
325
364
  await capsule.shutdown()
365
+ if (failure) throw failure
326
366
  },
327
367
  }
328
368
  }
@@ -9,6 +9,15 @@ type InvocationOpts = {
9
9
  interrupt: (reason: "user" | "shutdown", reservationId?: string) => void
10
10
  }
11
11
 
12
+ /**
13
+ * How long a reserved-but-never-consumed wire holds the scheduler before the
14
+ * lock is dropped. Generous on purpose: a legitimate consumer starts pulling
15
+ * within microseconds, so anything at this scale is genuinely abandoned, and
16
+ * releasing early on a slow-but-real caller would be worse than the wedge
17
+ * this guards against.
18
+ */
19
+ const ABANDON_MS = 30_000
20
+
12
21
  type StreamInput = {
13
22
  content?: string | string[]
14
23
  }
@@ -26,7 +35,27 @@ export function Invocation(opts: InvocationOpts) {
26
35
  function stream(input: StreamInput = {}) {
27
36
  const reservationId = opts.reserve()
28
37
 
38
+ // reserve() is synchronous — it has to be, or two callers could both
39
+ // mint a wire before either locked (see Scheduler.reserve). But an
40
+ // async generator's body does not run until it is iterated, so
41
+ // between this call and the first pull the scheduler is LOCKED with
42
+ // nothing running and no release path: runWake's finally lives
43
+ // inside the generator.
44
+ //
45
+ // A caller that never consumes the wire therefore wedges the runtime
46
+ // permanently — every later request throws RUN_IN_PROGRESS until the
47
+ // process restarts. That is not hypothetical: /_axon/stream hands the
48
+ // wire to a ReadableStream whose start() only fires when the client
49
+ // reads, so a client disconnecting in that window would take the
50
+ // agent down remotely.
51
+ //
52
+ // The timer closes the window. It is cancelled the instant the body
53
+ // actually starts, so a consumed wire never sees it; only an
54
+ // abandoned one does.
55
+ const abandoned = setTimeout(() => opts.release(reservationId), ABANDON_MS)
56
+
29
57
  const wire = (async function* () {
58
+ clearTimeout(abandoned)
30
59
  try {
31
60
  const contents = input.content === undefined
32
61
  ? []
@@ -49,7 +78,17 @@ export function Invocation(opts: InvocationOpts) {
49
78
 
50
79
  return {
51
80
  stream: wire,
52
- interrupt: () => opts.interrupt("user", reservationId),
81
+ interrupt: () => {
82
+ // Abort first — it matches on the reservation id, so
83
+ // releasing ahead of it would make the abort a no-op against
84
+ // a wake that IS running. Then drop the reservation, which
85
+ // covers the other case: an interrupt arriving before the
86
+ // wire was ever pulled has no wake to abort, only a lock to
87
+ // free. Both paths are idempotent.
88
+ opts.interrupt("user", reservationId)
89
+ clearTimeout(abandoned)
90
+ opts.release(reservationId)
91
+ },
53
92
  }
54
93
  }
55
94
 
@@ -86,7 +86,7 @@ export function Wake(opts: WakeOpts) {
86
86
  // commit is pure run-accounting, no error payload of its own.
87
87
  const failure = err(cause)
88
88
  opts.session.reportError(failure)
89
- await opts.session.commit("kernel:run:failed", {}, sessionCtx)
89
+ await opts.session.commit("kernel:run:failed", { durationMs: Date.now() - started }, sessionCtx)
90
90
  channel.fail(failure)
91
91
  }
92
92
  } catch (cause) {