@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.
@@ -0,0 +1,164 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonEntry, AxonStimulusEntry, CognetWake } from "@arcforge/types"
3
+ import { ENTRY_EVENT_PREFIXES } from "@arcforge/types"
4
+ import type { KernelBus } from "../contracts"
5
+ import type { AxonSessionT } from "@arcforge/session"
6
+ import type { KernelCognet } from "../contracts"
7
+
8
+ type WakeOpts = {
9
+ cognet: KernelCognet
10
+ stimuli: AxonStimulusEntry[]
11
+ bus: KernelBus
12
+ session: AxonSessionT
13
+ abort: AbortController
14
+ }
15
+
16
+ /** Entry vocabulary — the families are defined WITH AxonEntryEvent, never duplicated here. */
17
+ function isEntry(event: unknown): event is AxonEntry {
18
+ if (typeof event !== "object" || event === null) return false
19
+ const e = event as { type?: string; id?: string }
20
+ if (typeof e.type !== "string" || typeof e.id !== "string") return false
21
+ return ENTRY_EVENT_PREFIXES.some(prefix => (e.type as string).startsWith(prefix))
22
+ }
23
+
24
+ /**
25
+ * One execution of one wake: fires cognet.wake() exactly once and owns
26
+ * everything around it — the run record (kernel:run:start/complete/failed/
27
+ * interrupted) and the wire. Mode-agnostic — invocation.ts and continuous.ts
28
+ * both invoke through this unchanged; neither trigger source is visible
29
+ * here.
30
+ *
31
+ * The wire carries entries, full stop — forwarded from the bus (the commit
32
+ * pipeline announces every commit after it's on disk); cognets are never
33
+ * responsible for wire correctness of what they commit. There is no
34
+ * transient/delta current anymore: a temporally-extended emission is
35
+ * ordinary chunked entries (AxonChunk standard), so liveness rides the
36
+ * same pipeline as durability.
37
+ */
38
+ export function Wake(opts: WakeOpts) {
39
+ const runId = Bun.randomUUIDv7()
40
+ const abort = opts.abort
41
+ const channel = Channel<AxonEntry>()
42
+ const sessionCtx = { runId }
43
+
44
+ // every durable commit reaches the wire, no cognet cooperation needed —
45
+ // no thread to filter by, one session is always one continuous stream
46
+ const unsubscribe = opts.bus.onAny((_type, payload) => {
47
+ if (isEntry(payload)) channel.push(payload)
48
+ })
49
+
50
+ async function execute(): Promise<void> {
51
+ const started = Date.now()
52
+
53
+ // The outer try is the wire's terminal guarantee: no matter what
54
+ // throws — including the run-record commits themselves (disk gone) —
55
+ // the channel terminates and the bus subscription drops. Without it,
56
+ // a failed commit escapes void execute() as an unhandled rejection
57
+ // and the consumer's yield* hangs forever with the scheduler locked.
58
+ try {
59
+ await opts.session.commit("kernel:run:start", {}, sessionCtx)
60
+
61
+ const wake: CognetWake = {
62
+ stimuli: opts.stimuli,
63
+ signal: abort.signal,
64
+ }
65
+
66
+ try {
67
+ await opts.cognet.wake(wake)
68
+
69
+ // cognets return early on abort; engines may also throw on it — both land as an interrupt
70
+ if (abort.signal.aborted) {
71
+ await interrupted()
72
+ } else {
73
+ await opts.session.commit("kernel:run:complete", { durationMs: Date.now() - started }, sessionCtx)
74
+ }
75
+ channel.close()
76
+ } catch (cause) {
77
+ if (abort.signal.aborted) {
78
+ await interrupted()
79
+ channel.close()
80
+ return
81
+ }
82
+ // err() already emitted this at its throw site (disk + live
83
+ // sink → session's canonical "error" event) unless cause was
84
+ // a raw, unwrapped throw — err(cause) covers that case too,
85
+ // constructing+emitting for the first time. Either way this
86
+ // commit is pure run-accounting, no error payload of its own.
87
+ const failure = err(cause)
88
+ opts.session.reportError(failure)
89
+ await opts.session.commit("kernel:run:failed", {}, sessionCtx)
90
+ channel.fail(failure)
91
+ }
92
+ } catch (cause) {
93
+ channel.fail(err(cause))
94
+ } finally {
95
+ unsubscribe()
96
+ }
97
+ }
98
+
99
+ async function interrupted(): Promise<void> {
100
+ const reason = (abort.signal.reason ?? "user") as "user" | "shutdown"
101
+ await opts.session.commitEntry("axon:interrupt", { reason }, { runId })
102
+ await opts.session.commit("kernel:run:interrupted", { reason }, sessionCtx)
103
+ }
104
+
105
+ return {
106
+ runId,
107
+ abort,
108
+
109
+ /** the wake's wire: durable entries, in commit order */
110
+ async *stream(): AsyncGenerator<AxonEntry> {
111
+ void execute() // failures surface through channel.fail → thrown at the consumer
112
+ yield* channel
113
+ },
114
+ }
115
+ }
116
+
117
+ export type WakeT = ReturnType<typeof Wake>
118
+
119
+ // ── Channel ───────────────────────────────────────────────────────────────────
120
+
121
+ /**
122
+ * Bridges the wake (which cannot yield) to the caller's async iterator.
123
+ * push() during execution, close() on clean stop, fail() rethrows at the
124
+ * consumer.
125
+ */
126
+ function Channel<T>() {
127
+ const buffer: T[] = []
128
+ let notify: (() => void) | null = null
129
+ let done = false
130
+ let failed = false
131
+ let failure: unknown = null
132
+
133
+ function wakeConsumer() {
134
+ notify?.()
135
+ notify = null
136
+ }
137
+
138
+ return {
139
+ push(value: T) {
140
+ buffer.push(value)
141
+ wakeConsumer()
142
+ },
143
+ close() {
144
+ done = true
145
+ wakeConsumer()
146
+ },
147
+ fail(cause: unknown) {
148
+ failed = true
149
+ failure = cause
150
+ done = true
151
+ wakeConsumer()
152
+ },
153
+ async *[Symbol.asyncIterator](): AsyncGenerator<T> {
154
+ while (true) {
155
+ while (buffer.length > 0) yield buffer.shift()!
156
+ if (done) {
157
+ if (failed) throw failure
158
+ return
159
+ }
160
+ await new Promise<void>((resolve) => { notify = resolve })
161
+ }
162
+ },
163
+ }
164
+ }
@@ -0,0 +1,76 @@
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 two must never disagree about WHAT is in scope. They cannot,
13
+ * because neither decides it — toScope() does, once, and both render its
14
+ * result. This file only chooses how to spell it for `tsc`:
15
+ *
16
+ * flat module → each member declared directly (a top-level global)
17
+ * namespaced module → `namespace <name> { ... }`
18
+ *
19
+ * No `declare` prefix on members: everything inside `declare global { }` is
20
+ * already ambient, and TS1038 rejects a nested `declare` there.
21
+ */
22
+ export function scopeToDts(scope: AxonScope): string {
23
+ const modules = scope.modules.filter(module => module.members.length > 0)
24
+
25
+ const lines: string[] = [
26
+ "// tool-globals.d.ts — generated by axon prepare, do not edit",
27
+ "// Every tool the capsule can call, declared as it is callable.",
28
+ "// Mirrors the <scope> block the model receives — same source, same members.",
29
+ "",
30
+ "declare global {",
31
+ ]
32
+
33
+ // Ambient types first and deduped by exact text: a member declaration
34
+ // referencing Promise<DeployStatus> is unresolvable without it, in an
35
+ // editor exactly as in the model's context.
36
+ for (const ambient of new Set(modules.flatMap(module => module.ambientTypes ?? []))) {
37
+ lines.push(indent(ambient), "")
38
+ }
39
+
40
+ for (const module of modules) {
41
+ if (module.description) lines.push(indent(jsdocBlock(module.description)))
42
+
43
+ if (module.flat) {
44
+ for (const member of module.members) {
45
+ if (member.jsdoc) lines.push(indent(jsdocBlock(member.jsdoc)))
46
+ lines.push(indent(member.declaration))
47
+ }
48
+ continue
49
+ }
50
+
51
+ const body: string[] = []
52
+ for (const member of module.members) {
53
+ if (member.jsdoc) body.push(jsdocBlock(member.jsdoc))
54
+ body.push(member.declaration)
55
+ }
56
+ lines.push(indent(`namespace ${module.name} {\n${indent(body.join("\n"))}\n}`))
57
+ }
58
+
59
+ lines.push("}", "", "export {}", "")
60
+ return lines.join("\n")
61
+ }
62
+
63
+ /** How many callable members this scope declares — the caller's "did anything land" signal. */
64
+ export function scopeMemberCount(scope: AxonScope): number {
65
+ return scope.modules.reduce((total, module) => total + module.members.length, 0)
66
+ }
67
+
68
+ function indent(text: string): string {
69
+ return text.split("\n").map(line => (line ? ` ${line}` : line)).join("\n")
70
+ }
71
+
72
+ function jsdocBlock(text: string): string {
73
+ const lines = text.split("\n")
74
+ if (lines.length === 1) return `/** ${text} */`
75
+ return `/**\n${lines.map(l => ` * ${l}`.trimEnd()).join("\n")}\n */`
76
+ }
package/src/scope.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { AxonBlueprint, AxonScope, AxonScopeModule, AxonTool } from "@arcforge/types"
2
+
3
+ /**
4
+ * scope — the ONE decision about what is in an agent's executable scope.
5
+ *
6
+ * The capsule is a separate OS process. Something is in scope only if that
7
+ * process can actually load and call it, which means exactly one rule:
8
+ *
9
+ * a tool is in scope when it has a real entry file (or inline source).
10
+ *
11
+ * Everything the model is told it can call, and everything an editor is
12
+ * told exists, is derived from the AxonScope this produces. Two renderers
13
+ * consume it — renderScope() for the model, scopeToDts() for TypeScript —
14
+ * and they can differ only in SPELLING, never in membership, because
15
+ * membership is settled here before either runs.
16
+ *
17
+ * That property is the point. Previously the capsule filtered for
18
+ * loadability while the .d.ts generator rendered every scanned tool, so
19
+ * the file claimed to describe the model's scope and described something
20
+ * else entirely: an agent's npm dependencies, whose declarations had been
21
+ * introspected and hoisted in as callable globals.
22
+ *
23
+ * An npm dependency is NOT a tool. It is available to the agent project's
24
+ * SOURCE — importable by the author's own code — which is a bundler
25
+ * concern. A tool is available to the AGENT, across a process boundary,
26
+ * which is an execution concern. To turn a package into a tool, an author
27
+ * re-exports it from src/tools/ deliberately.
28
+ */
29
+
30
+ /** A tool the capsule can genuinely load — the only kind that may enter scope. */
31
+ export function isLoadable(tool: AxonTool): boolean {
32
+ return Boolean(tool.entryPath) || tool.source !== undefined
33
+ }
34
+
35
+ /** One tool's contribution to the executable scope. */
36
+ export function toScopeModule(tool: AxonTool): AxonScopeModule {
37
+ return {
38
+ name: tool.name,
39
+ ...(tool.description ? { description: tool.description } : {}),
40
+ members: tool.fns,
41
+ ...(tool.flat ? { flat: true } : {}),
42
+ ...(tool.ambientTypes ? { ambientTypes: tool.ambientTypes } : {}),
43
+ }
44
+ }
45
+
46
+ /**
47
+ * The blueprint's executable scope. Tools with no loadable entry are
48
+ * excluded — declaring something the capsule cannot call would tell the
49
+ * model to invoke a function that does not exist there.
50
+ */
51
+ export function toScope(blueprint: AxonBlueprint): AxonScope {
52
+ return { modules: blueprint.tools.filter(isLoadable).map(toScopeModule) }
53
+ }
@@ -0,0 +1 @@
1
+ export { Store } from "./store"
@@ -0,0 +1,54 @@
1
+ import type { KernelStore } from "@arcforge/types"
2
+ import type { AxonBlueprint } from "@arcforge/types"
3
+ import type { AxonSessionT } from "@arcforge/session"
4
+ import { home } from "@arcforge/session"
5
+ import path from "node:path"
6
+
7
+ type StoreOpts = {
8
+ blueprint: AxonBlueprint
9
+ /** The cognet this store belongs to — its private namespace on disk. */
10
+ cognet: { readonly name: string }
11
+ /** Environmental, same handle the kernel mediates output()/run() through. */
12
+ session: AxonSessionT
13
+ }
14
+
15
+ /**
16
+ * Store — the cognet's persistence resource, one door with two rooms and
17
+ * two ownership regimes (see KernelStore in @arcforge/types for the doctrine):
18
+ *
19
+ * - `session` — READ-ONLY view of the session's entry log, the kernel's
20
+ * live in-memory projection. Entries only, by construction: it reads
21
+ * session.entries (already classified by type namespace), so kernel
22
+ * telemetry and error machinery are unreachable from ring 3. This is
23
+ * how a cognet rehydrates at boot without anything being passed in.
24
+ * - the kv — the cognet's private consolidated state, whole-value JSON
25
+ * under data/state/<cognet-name>/, path authority in home.ts. Engine
26
+ * invisible on purpose: the contract is get/set, not files — a db can
27
+ * move in behind this door without any cognet noticing.
28
+ *
29
+ * Typed against CognetStoreSchema (declaration merging) at the ABI seam;
30
+ * this implementation is honest about what it really moves: unknown JSON.
31
+ */
32
+ export function Store(opts: StoreOpts): KernelStore {
33
+ const root = path.resolve(opts.blueprint.paths.root, opts.blueprint.paths.data)
34
+
35
+ return {
36
+ session: {
37
+ get(getOpts?: { after?: number }) {
38
+ const entries = opts.session.entries
39
+ if (getOpts?.after === undefined) return entries
40
+ return entries.filter(entry => entry.time.seq > getOpts.after!)
41
+ },
42
+ },
43
+
44
+ async get(key) {
45
+ return (await home.data.state.read(root, opts.cognet.name, key as string)) as CognetStoreSchema[typeof key] | null
46
+ },
47
+
48
+ async set(key, value) {
49
+ await home.data.state.write(root, opts.cognet.name, key as string, value)
50
+ },
51
+ }
52
+ }
53
+
54
+ export type StoreT = ReturnType<typeof Store>