@arcforge/kernel 2.0.115 → 2.0.117

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.115",
3
+ "version": "2.0.117",
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.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"
18
+ "@arcforge/air": "2.0.117",
19
+ "@arcforge/engines": "2.0.117",
20
+ "@arcforge/err": "2.0.117",
21
+ "@arcforge/session": "2.0.117",
22
+ "@arcforge/types": "2.0.117",
23
+ "@arclabs/cloud": "2.0.117",
24
+ "@axon/capsule": "2.0.117"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/bun": "latest",
package/src/engine.ts CHANGED
@@ -9,7 +9,8 @@ import type {
9
9
  EngineCloud,
10
10
  } from "@arcforge/types"
11
11
  import { asEngineFault, EngineFailure, resolveEngine } from "@arcforge/engines"
12
- import { Air, type AirBlockEvent, type AirT } from "@arcforge/cognet/air"
12
+ import { Air, type AirBlockEvent, type AirT } from "@arcforge/air"
13
+ import type { OutputDiagnostic } from "@arcforge/air/output"
13
14
  import type { AxonSessionT } from "@arcforge/session"
14
15
 
15
16
  type EngineOpts = {
@@ -17,6 +18,8 @@ type EngineOpts = {
17
18
  session: AxonSessionT
18
19
  /** The runtime's cloud client — handed to drivers at create(); engines call what they need. */
19
20
  cloud: EngineCloud
21
+ /** Commit a format violation the model must read and correct. */
22
+ fault(input: { code: string; message: string; excerpt?: string }): Promise<void>
20
23
  }
21
24
 
22
25
  type EngineContext = {
@@ -26,6 +29,25 @@ type EngineContext = {
26
29
  const MAX_ATTEMPTS = 3
27
30
  const RETRY_DELAYS_MS = [100, 300] as const
28
31
 
32
+ /**
33
+ * Attempts allowed after a response fails its declared output shape.
34
+ *
35
+ * Three model calls total is enough for a model to read a type error and fix
36
+ * it — a shape it cannot correct twice is usually one it cannot satisfy at
37
+ * all, and burning more calls on it just costs the caller money.
38
+ */
39
+ const DEFAULT_OUTPUT_RETRIES = 2
40
+
41
+ /** Type errors as the model reads them — its own line numbers, its own code. */
42
+ function describeViolations(problems: readonly OutputDiagnostic[]): string {
43
+ const lines = problems.map(p => (p.line ? `line ${p.line}: ${p.message}` : p.message))
44
+ return [
45
+ "Your <script> does not produce the required `result` shape:",
46
+ ...lines.map(l => ` ${l}`),
47
+ "Fix the script so `result` matches the declared type, then reply again.",
48
+ ].join("\n")
49
+ }
50
+
29
51
  /**
30
52
  * Engine — the inference layer of the runtime. Drivers are raw token pipes;
31
53
  * this manager owns AIR parsing, bounded pre-output retries, and the durable
@@ -63,10 +85,24 @@ export function Engine(opts: EngineOpts) {
63
85
  return { driver: def.create({ env: blueprint.env, cloud: opts.cloud }), name: def.name }
64
86
  }
65
87
 
66
- async function* stream(call: AxonEngineCall, context: EngineContext): AsyncGenerator<AxonEngineEvent> {
88
+ /**
89
+ * One logical call, as AIR BLOCKS — the raw half.
90
+ *
91
+ * Owns everything about talking to a driver: transport retries,
92
+ * reconciling the authoritative final text against what actually
93
+ * streamed, and the durable accounting span. It knows the grammar only
94
+ * well enough to parse it, and nothing about what the blocks MEAN.
95
+ *
96
+ * The response half (running scripts, rendering templates, enforcing an
97
+ * output shape) wraps this — see stream() below.
98
+ */
99
+ async function* blocks(
100
+ call: AxonEngineCall,
101
+ context: EngineContext,
102
+ ): AsyncGenerator<AirBlockEvent, AxonEngineResponse> {
67
103
  // Protocol is the manager's concern, never the driver's — drivers are
68
104
  // token pipes and must not receive a field they'd have to ignore.
69
- const { protocol, ...req } = call
105
+ const { protocol, output: _output, retries: _retries, ...req } = call
70
106
  const air = airFor(protocol)
71
107
  const span = { ...context, spanId: Bun.randomUUIDv7() }
72
108
  // The whole logical call, retries and AIR parsing included — distinct
@@ -131,10 +167,7 @@ export function Engine(opts: EngineOpts) {
131
167
  // (extend) from a full re-feed (which would
132
168
  // double-fire every already-streamed block).
133
169
  streamedText += raw.content
134
- for (const block of parser.feed(raw.content)) {
135
- const event = toBlockEvent(block)
136
- if (event) yield event
137
- }
170
+ yield* parser.feed(raw.content)
138
171
  break
139
172
 
140
173
  case "thinking:delta":
@@ -169,17 +202,9 @@ export function Engine(opts: EngineOpts) {
169
202
  // than risk reconciling against the wrong content.
170
203
  if (extendsStreamedText(streamedText, raw.response.text)) {
171
204
  const missing = raw.response.text.slice(streamedText.length)
172
- if (missing.length > 0) {
173
- for (const block of parser.feed(missing)) {
174
- const event = toBlockEvent(block)
175
- if (event) yield event
176
- }
177
- }
178
- }
179
- for (const block of parser.flush()) {
180
- const event = toBlockEvent(block)
181
- if (event) yield event
205
+ if (missing.length > 0) yield* parser.feed(missing)
182
206
  }
207
+ yield* parser.flush()
183
208
 
184
209
  const meta = {
185
210
  ...raw.response.meta,
@@ -197,8 +222,7 @@ export function Engine(opts: EngineOpts) {
197
222
  meta,
198
223
  durationMs: Date.now() - callStarted,
199
224
  }, span)
200
- yield { type: "engine:done", response }
201
- return
225
+ return response
202
226
  }
203
227
  }
204
228
  }
@@ -262,6 +286,138 @@ export function Engine(opts: EngineOpts) {
262
286
  })
263
287
  }
264
288
  }
289
+
290
+ // The loop either returns on `done` or throws; exhausting every
291
+ // attempt without either is unreachable, but TS needs the return type
292
+ // satisfied on this path.
293
+ throw err("ENGINE_NO_DONE")
294
+ }
295
+
296
+ /**
297
+ * One logical call, as engine events.
298
+ *
299
+ * Maps parsed blocks onto the wire vocabulary and enforces a declared
300
+ * output shape, retrying a response that misses it. What it does NOT do
301
+ * is act: a script is reported, never run. Running code is an act, and
302
+ * acts belong to the brain — the kernel is the authority on HOW code
303
+ * runs (policy, capsule, commit), never on WHETHER this particular reply
304
+ * should have run any.
305
+ *
306
+ * That line is what keeps the service general. A cognet may call a model
307
+ * to classify a stimulus, rank an inference, or plan; if the kernel ran
308
+ * whatever came back, every one of those would touch the world unasked.
309
+ */
310
+ async function* stream(call: AxonEngineCall, context: EngineContext): AsyncGenerator<AxonEngineEvent> {
311
+ const output = call.output
312
+ // Attempts AFTER the first, so `retries: 0` means one shot. Only a
313
+ // declared output contract can fail this way; without one there is
314
+ // nothing for a response to violate.
315
+ const budget = output ? (call.retries ?? DEFAULT_OUTPUT_RETRIES) : 0
316
+ let lastFault: string | undefined
317
+
318
+ yield { type: "engine:start" }
319
+
320
+ for (let attempt = 0; attempt <= budget; attempt++) {
321
+ const raw = blocks(call, context)
322
+ let violations: readonly OutputDiagnostic[] = []
323
+ let spoke = false
324
+ let acted = false
325
+ let yielded = false
326
+ let lang: "md" | "json" = "md"
327
+ let group: string | null = null
328
+ let pending: string | null = null
329
+
330
+ // Held rather than emitted: the parser follows every delta with a
331
+ // `done` carrying the whole block, so the LAST chunk is only
332
+ // knowable in arrears. Emitting eagerly would force an empty
333
+ // terminal chunk to close the group, turning a one-line reply
334
+ // into two entries on the record.
335
+ const events: AxonEngineEvent[] = []
336
+
337
+ let step = await raw.next()
338
+ while (!step.done) {
339
+ const block = step.value
340
+ switch (block.type) {
341
+ case "template:open":
342
+ lang = block.lang
343
+ break
344
+
345
+ case "template:delta":
346
+ if (pending !== null) {
347
+ group ??= crypto.randomUUID()
348
+ spoke = true
349
+ events.push({ type: "engine:text", content: pending, lang, chunk: { of: group } })
350
+ }
351
+ pending = block.content
352
+ break
353
+
354
+ case "template:done": {
355
+ if (block.incomplete) break
356
+ const last = pending ?? block.content
357
+ pending = null
358
+ if (!last) break
359
+ spoke = true
360
+ events.push(group
361
+ ? { type: "engine:text", content: last, lang, chunk: { of: group, final: true } }
362
+ : { type: "engine:text", content: last, lang })
363
+ group = null
364
+ break
365
+ }
366
+
367
+ case "script:done": {
368
+ if (block.incomplete) break
369
+ // Checked BEFORE it is reported, so a script that
370
+ // cannot satisfy the contract is never handed to a
371
+ // cognet that would run it.
372
+ if (output) {
373
+ const problems = output.check(block.content)
374
+ if (problems.length > 0) {
375
+ violations = problems
376
+ break
377
+ }
378
+ }
379
+ acted = true
380
+ events.push({ type: "engine:script", id: crypto.randomUUID(), content: block.content })
381
+ break
382
+ }
383
+
384
+ case "done":
385
+ yielded = true
386
+ break
387
+
388
+ // Thinking never crosses the boundary.
389
+ case "thinking:delta":
390
+ case "thinking:done":
391
+ break
392
+ }
393
+ step = await raw.next()
394
+ }
395
+
396
+ if (violations.length === 0) {
397
+ for (const event of events) yield event
398
+ yield { type: "engine:done", response: step.value, spoke, acted, yielded }
399
+ return
400
+ }
401
+
402
+ // Nothing this attempt produced is emitted: a response that
403
+ // failed its contract is not a partial answer, it is a discarded
404
+ // one. The diagnostic is committed so the next attempt's context
405
+ // carries it, and the model rewrites against its own error.
406
+ lastFault = describeViolations(violations)
407
+ await opts.fault({ code: "OUTPUT_TYPE_ERROR", message: lastFault })
408
+ }
409
+
410
+ // Budget exhausted. Loud, never a degraded return: a caller that
411
+ // asked for a shape gets that shape or an error explaining why it
412
+ // could not be produced, never an unchecked value it would treat as
413
+ // validated.
414
+ yield {
415
+ type: "engine:failure",
416
+ error: err("OUTPUT_UNSATISFIED", {
417
+ detail: `the model could not produce the required output shape after ${budget + 1} attempts. `
418
+ + `Last errors: ${lastFault ?? "(none recorded)"}`,
419
+ }),
420
+ }
265
421
  }
266
422
 
267
423
  return {
@@ -274,6 +430,7 @@ export function Engine(opts: EngineOpts) {
274
430
  async request(req: AxonEngineCall, context: EngineContext): Promise<AxonEngineResponse> {
275
431
  for await (const event of stream(req, context)) {
276
432
  if (event.type === "engine:done") return event.response
433
+ if (event.type === "engine:failure") throw event.error
277
434
  }
278
435
  throw err("ENGINE_NO_DONE")
279
436
  },
@@ -290,6 +447,8 @@ export function Engine(opts: EngineOpts) {
290
447
 
291
448
  export type AxonEngineT = ReturnType<typeof Engine>
292
449
 
450
+
451
+
293
452
  /** True when `final` is `streamed` plus a non-empty trailing suffix — never a divergence, only a possibly-truncated stream catching up to the provider's authoritative text. */
294
453
  function extendsStreamedText(streamed: string, final: string): boolean {
295
454
  return final.length > streamed.length && final.startsWith(streamed)
@@ -324,48 +483,3 @@ function delay(ms: number, signal?: AbortSignal): Promise<void> {
324
483
  function abortError(signal?: AbortSignal): DOMException {
325
484
  return new DOMException(signal?.reason ? String(signal.reason) : "engine request aborted", "AbortError")
326
485
  }
327
-
328
- function toBlockEvent(block: AirBlockEvent): AxonEngineEvent | null {
329
- switch (block.type) {
330
- case "text:delta":
331
- return { type: "engine:text:delta", content: block.content }
332
- case "thinking:delta":
333
- return null // dropped — thinking never crosses the wire
334
-
335
- case "text:done":
336
- if (block.incomplete) return incomplete("text", block.content)
337
- return { type: "engine:text", content: block.content }
338
- case "thinking:done":
339
- return null // dropped — thinking never crosses the wire
340
- case "typescript:done":
341
- if (block.incomplete) return incomplete("typescript", block.content)
342
- return { type: "engine:typescript", id: Bun.randomUUIDv7(), content: block.content }
343
-
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 }
358
-
359
- case "done":
360
- return { type: "engine:stop" }
361
- }
362
- }
363
-
364
- function incomplete(tag: string, content: string): AxonEngineEvent {
365
- return {
366
- type: "engine:output:error",
367
- code: "INCOMPLETE_BLOCK",
368
- message: `stream ended inside an unclosed <${tag}> block`,
369
- excerpt: content.slice(0, 200),
370
- }
371
- }
package/src/index.ts CHANGED
@@ -13,8 +13,8 @@
13
13
  export { Kernel, type AxonKernelT } from "./kernel"
14
14
  export type { KernelBus, KernelCognet } from "./contracts"
15
15
 
16
- // The capsule's executable surface, and its rendering as TypeScript
17
- // declarations — the kernel reports executable reality, callers decide how it
18
- // enters model context.
16
+ // The capsule's executable surface — the kernel reports executable reality,
17
+ // callers decide how it enters model context. How that surface is SPELLED
18
+ // (for a model, for tsc, as an output contract) belongs to @arcforge/air:
19
+ // the kernel owns what is callable, never how it is written down.
19
20
  export { toScope, toScopeModule, isLoadable } from "./scope"
20
- export { scopeToDts, scopeMemberCount } from "./scope-dts"
package/src/kernel.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { err } from "@arcforge/err"
2
- import type { AxonBlueprint, AxonEngineEvent, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
2
+ import type { AxonBlueprint, AxonEngineCall, AxonEngineEvent, AxonEntry, AxonEntryEvent, AxonEventMap, AxonRunResult, KernelAbi } from "@arcforge/types"
3
3
  import { EMPTY_CAPSULE_SCOPE } from "@arcforge/types"
4
4
  import type { AxonCloudClient } from "@arclabs/cloud"
5
5
  import type { KernelBus } from "./contracts"
@@ -51,6 +51,15 @@ type KernelOpts = {
51
51
  type KernelInput = {
52
52
  /** User message committed before the wake starts. */
53
53
  content?: string | string[]
54
+ /**
55
+ * The structured shape this invocation must produce, already compiled by
56
+ * the caller (Axon's handle) so a bad type throws at the call site,
57
+ * before a wake is ever scheduled. Enforced by the engine; invisible to
58
+ * the cognet.
59
+ */
60
+ output?: AxonEngineCall["output"]
61
+ /** Attempts after a response fails `output`. Ignored without one. */
62
+ retries?: number
54
63
  }
55
64
 
56
65
  const COGNET_EVENT_PREFIX = "cognet:"
@@ -164,6 +173,11 @@ export async function Kernel(opts: KernelOpts) {
164
173
  blueprint: opts.blueprint,
165
174
  session,
166
175
  cloud: opts.cloud,
176
+ // Reporting a format violation is the kernel's to commit — the
177
+ // engine describes the fault, the session records it. Injected
178
+ // rather than reached for, so the engine never learns what a session
179
+ // is. Hoisted declaration; live before the first call.
180
+ fault: input => recordFault(input, scheduler.active()).then(() => {}),
167
181
  })
168
182
 
169
183
  const store = Store({
@@ -239,16 +253,80 @@ export async function Kernel(opts: KernelOpts) {
239
253
  }, run)
240
254
  }
241
255
 
256
+ /**
257
+ * The cognet's engine calls, with the invocation's output contract folded
258
+ * in.
259
+ *
260
+ * A caller that declared `output` on request() demanded a shape of THIS
261
+ * invocation, and the engine is what enforces it — so the contract is
262
+ * attached here rather than passed through cognition, which has no
263
+ * business knowing a shape was asked for. A cognet renders context and
264
+ * reads facts; it never carries the caller's requirements.
265
+ */
242
266
  async function* streamAndRecord(req: Parameters<typeof engine.stream>[0]): AsyncGenerator<AxonEngineEvent> {
243
267
  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)
268
+ // The wake's cancellation is applied here, not passed in: an
269
+ // inference call is a mediated resource like the capsule, and a
270
+ // program that forgot to thread a signal made one unkillable.
271
+ const call = { ...req, ...activeContract, signal: run.signal }
272
+
273
+ for await (const event of engine.stream(call, run)) {
274
+ // A call that could not produce a usable response THROWS rather
275
+ // than arriving as an event a cognet might ignore. Yielding it
276
+ // and trusting every loop to check would make "the model never
277
+ // satisfied its contract" look identical to a completed wake —
278
+ // exactly the silent degradation the caller asked for a shape to
279
+ // avoid. The event is still yielded first so a consumer watching
280
+ // the stream sees the cause before the throw.
281
+ if (event.type === "engine:failure") {
282
+ yield event
283
+ throw event.error
247
284
  }
248
285
  yield event
249
286
  }
250
287
  }
251
288
 
289
+ /**
290
+ * The output contract for the wake currently running, if any.
291
+ *
292
+ * Wake-scoped, not kernel-scoped: it belongs to ONE invocation, and a
293
+ * value that outlived its wake would silently impose the previous
294
+ * caller's shape on the next request. Never reaches the ABI — the cognet
295
+ * has no idea a shape was demanded, which is the whole point.
296
+ */
297
+ let activeContract: { output: NonNullable<KernelInput["output"]>; retries?: number } | null = null
298
+
299
+ /**
300
+ * One wake, with its output contract live for exactly the wire's
301
+ * lifetime.
302
+ *
303
+ * Both public verbs route through here — `request()` is `stream()`
304
+ * drained — so a contract can never be installed for one and skipped for
305
+ * the other. Wrapping the wire rather than setting the contract beside
306
+ * the call makes teardown total: a normal end, a throw, an interrupt, or
307
+ * a consumer that abandons the stream all run the generator's finally.
308
+ */
309
+ function streamWithContract(input: KernelInput = {}) {
310
+ const run = scheduler.stream(input)
311
+ if (!input.output) return run
312
+
313
+ activeContract = {
314
+ output: input.output,
315
+ ...(input.retries === undefined ? {} : { retries: input.retries }),
316
+ }
317
+ const inner = run.stream
318
+ return {
319
+ ...run,
320
+ stream: (async function* () {
321
+ try {
322
+ yield* inner
323
+ } finally {
324
+ activeContract = null
325
+ }
326
+ })(),
327
+ }
328
+ }
329
+
252
330
  // ── the ABI — the syscall table, bound once to the kernel's organs ──────
253
331
  // Process-lifetime object: nothing on it carries per-wake state beyond
254
332
  // what scheduler.active() resolves internally. This is the only thing
@@ -275,13 +353,22 @@ export async function Kernel(opts: KernelOpts) {
275
353
  */
276
354
  fault: (input) => recordFault(input, scheduler.active()).then(() => {}),
277
355
 
278
- // capsule surface — self-committing (see runAndCommit above)
279
- run: ((code: string | string[], runOpts?: { signal?: AbortSignal }) => {
280
- if (Array.isArray(code)) return Promise.all(code.map(c => runAndCommit(c, runOpts)))
281
- return runAndCommit(code, runOpts)
356
+ /**
357
+ * capsule surface — self-committing (see runAndCommit above).
358
+ *
359
+ * The wake's cancellation is applied HERE, resolved from the run this
360
+ * syscall belongs to. A program never passes a signal and so can
361
+ * never omit one: a kill is authoritative, not something cognition
362
+ * opts into per call.
363
+ */
364
+ run: ((code: string | string[]) => {
365
+ const { signal } = scheduler.active() // throws SYSCALL_OUTSIDE_RUN if no wake is running
366
+ if (Array.isArray(code)) return Promise.all(code.map(c => runAndCommit(c, { signal })))
367
+ return runAndCommit(code, { signal })
282
368
  }) as KernelAbi["run"],
283
369
  scope: () => capsule.current.scope,
284
370
 
371
+
285
372
  // environment surface
286
373
  base: opts.base,
287
374
 
@@ -369,15 +456,31 @@ export async function Kernel(opts: KernelOpts) {
369
456
  return scheduler.loaded
370
457
  },
371
458
 
459
+ /**
460
+ * The capsule's executable scope, as the ABI reports it to a cognet.
461
+ *
462
+ * On the public surface because an output type is typechecked
463
+ * against it: a caller declaring `{ files: FileEntry[] }` may name a
464
+ * type the agent's own tools declare, and checking against anything
465
+ * other than the scope the MODEL is shown would accept types the
466
+ * model cannot see or reject ones it can.
467
+ */
468
+ scope: () => capsule.current.scope,
469
+
372
470
  /** Invoke on a stimulus arrival — invocation-mode cognets only; throws for continuous-mode. */
373
- stream(input: KernelInput = {}) {
374
- return scheduler.stream(input)
375
- },
471
+ stream: streamWithContract,
376
472
 
377
- /** Collect a full wake: every durable entry, in commit order. */
473
+ /**
474
+ * Collect a full wake: every durable entry, in commit order.
475
+ *
476
+ * Goes through THIS handle's stream(), not the scheduler's, so an
477
+ * output contract is installed and torn down identically for both
478
+ * verbs — reaching past it would have made `request({ contract })`
479
+ * silently unenforced.
480
+ */
378
481
  async request(input: KernelInput = {}): Promise<{ ok: true; entries: AxonEntry[] }> {
379
482
  const entries: AxonEntry[] = []
380
- for await (const entry of scheduler.stream(input).stream) {
483
+ for await (const entry of streamWithContract(input).stream) {
381
484
  entries.push(entry) // the wire carries entries, full stop — chunks included
382
485
  }
383
486
  return { ok: true, entries }
@@ -54,7 +54,7 @@ type InvokeInput = {
54
54
  * AsyncLocalStorage binds it to the wake that started the work, so a syscall
55
55
  * resolves correctly no matter how the awaits interleave.
56
56
  */
57
- const runStorage = new AsyncLocalStorage<{ runId: string }>()
57
+ const runStorage = new AsyncLocalStorage<{ runId: string; signal: AbortSignal }>()
58
58
 
59
59
  export function Scheduler(opts: SchedulerOpts) {
60
60
  let cognet: KernelCognet | null = null
@@ -117,7 +117,11 @@ export function Scheduler(opts: SchedulerOpts) {
117
117
  session: opts.session,
118
118
  abort: reserved.abort,
119
119
  })
120
- const run = { runId: wake.runId }
120
+ // The signal rides WITH the run, so a mediated syscall resolves its
121
+ // own wake's cancellation rather than being handed one. A cognet
122
+ // that forgot to thread it used to make an operation unkillable;
123
+ // there is now nothing to forget.
124
+ const run = { runId: wake.runId, signal: reserved.abort.signal }
121
125
 
122
126
  return (async function* () {
123
127
  try {
package/src/scope-dts.ts DELETED
@@ -1,82 +0,0 @@
1
- import type { AxonScope } from "@arcforge/types"
2
-
3
- /**
4
- * scopeToDts — the agent's executable scope, spelled as TypeScript.
5
- *
6
- * The sibling spelling of renderScope(): same AxonScope in, same members
7
- * out, different audience. renderScope() writes the <scope> block the model
8
- * reads; this writes the ambient declarations an editor reads, so tool
9
- * calls in the author's own src/tools, src/scripts, hooks, and routes
10
- * typecheck against exactly what the capsule will provide.
11
- *
12
- * These globals are real in host-side code, not only inside the capsule:
13
- * Inject().runtime() binds each one to the matching axon.tools.* proxy when
14
- * the runtime comes up (see core/src/platform/inject.ts). That is what makes
15
- * this file honest — for a while it declared globals a script could not
16
- * actually call, so `kanban.list()` typechecked and then threw at runtime.
17
- *
18
- * These two must never disagree about WHAT is in scope. They cannot,
19
- * because neither decides it — toScope() does, once, and both render its
20
- * result. This file only chooses how to spell it for `tsc`:
21
- *
22
- * flat module → each member declared directly (a top-level global)
23
- * namespaced module → `namespace <name> { ... }`
24
- *
25
- * No `declare` prefix on members: everything inside `declare global { }` is
26
- * already ambient, and TS1038 rejects a nested `declare` there.
27
- */
28
- export function scopeToDts(scope: AxonScope): string {
29
- const modules = scope.modules.filter(module => module.members.length > 0)
30
-
31
- const lines: string[] = [
32
- "// tool-globals.d.ts — generated by axon prepare, do not edit",
33
- "// Every tool the capsule can call, declared as it is callable.",
34
- "// Mirrors the <scope> block the model receives — same source, same members.",
35
- "",
36
- "declare global {",
37
- ]
38
-
39
- // Ambient types first and deduped by exact text: a member declaration
40
- // referencing Promise<DeployStatus> is unresolvable without it, in an
41
- // editor exactly as in the model's context.
42
- for (const ambient of new Set(modules.flatMap(module => module.ambientTypes ?? []))) {
43
- lines.push(indent(ambient), "")
44
- }
45
-
46
- for (const module of modules) {
47
- if (module.description) lines.push(indent(jsdocBlock(module.description)))
48
-
49
- if (module.flat) {
50
- for (const member of module.members) {
51
- if (member.jsdoc) lines.push(indent(jsdocBlock(member.jsdoc)))
52
- lines.push(indent(member.declaration))
53
- }
54
- continue
55
- }
56
-
57
- const body: string[] = []
58
- for (const member of module.members) {
59
- if (member.jsdoc) body.push(jsdocBlock(member.jsdoc))
60
- body.push(member.declaration)
61
- }
62
- lines.push(indent(`namespace ${module.name} {\n${indent(body.join("\n"))}\n}`))
63
- }
64
-
65
- lines.push("}", "", "export {}", "")
66
- return lines.join("\n")
67
- }
68
-
69
- /** How many callable members this scope declares — the caller's "did anything land" signal. */
70
- export function scopeMemberCount(scope: AxonScope): number {
71
- return scope.modules.reduce((total, module) => total + module.members.length, 0)
72
- }
73
-
74
- function indent(text: string): string {
75
- return text.split("\n").map(line => (line ? ` ${line}` : line)).join("\n")
76
- }
77
-
78
- function jsdocBlock(text: string): string {
79
- const lines = text.split("\n")
80
- if (lines.length === 1) return `/** ${text} */`
81
- return `/**\n${lines.map(l => ` * ${l}`.trimEnd()).join("\n")}\n */`
82
- }