@arcforge/platform 2.0.219 → 2.0.244

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.
Files changed (127) hide show
  1. package/package.json +27 -19
  2. package/src/build/blueprint/blueprint.ts +48 -64
  3. package/src/build/blueprint/cognet/abi.ts +3 -257
  4. package/src/build/blueprint/cognet/bundle-worker.ts +11 -0
  5. package/src/build/blueprint/cognet/bundle.ts +294 -89
  6. package/src/build/blueprint/cognet/cognet.ts +8 -7
  7. package/src/build/blueprint/cognet/config/config.ts +52 -0
  8. package/src/build/blueprint/cognet/config/index.ts +4 -0
  9. package/src/build/blueprint/cognet/config/literal.ts +83 -0
  10. package/src/build/blueprint/cognet/config/provider.ts +43 -0
  11. package/src/build/blueprint/cognet/config/shape.ts +183 -0
  12. package/src/build/blueprint/cognet/index.ts +4 -2
  13. package/src/build/blueprint/cognet/native/cargo.ts +31 -0
  14. package/src/build/blueprint/cognet/native/crate.ts +126 -0
  15. package/src/build/blueprint/cognet/native/index.ts +2 -0
  16. package/src/build/blueprint/cognet/native/library.ts +125 -0
  17. package/src/build/blueprint/cognet/native/manifest.ts +137 -0
  18. package/src/build/blueprint/cognet/python/index.ts +1 -0
  19. package/src/build/blueprint/cognet/python/project.ts +119 -0
  20. package/src/build/blueprint/cognet/schema/arrays.ts +23 -0
  21. package/src/build/blueprint/cognet/schema/authored.ts +273 -0
  22. package/src/build/blueprint/cognet/schema/compile.ts +78 -0
  23. package/src/build/blueprint/cognet/schema/components/external.ts +15 -0
  24. package/src/build/blueprint/cognet/schema/components/index.ts +3 -0
  25. package/src/build/blueprint/cognet/schema/components/lock.ts +58 -0
  26. package/src/build/blueprint/cognet/schema/components/model.ts +34 -0
  27. package/src/build/blueprint/cognet/schema/components/python.ts +15 -0
  28. package/src/build/blueprint/cognet/schema/components/python_source.py +69 -0
  29. package/src/build/blueprint/cognet/schema/components/rust.ts +33 -0
  30. package/src/build/blueprint/cognet/schema/components/rust_source/Cargo.lock +117 -0
  31. package/src/build/blueprint/cognet/schema/components/rust_source/Cargo.toml +11 -0
  32. package/src/build/blueprint/cognet/schema/components/rust_source/src/main.rs +104 -0
  33. package/src/build/blueprint/cognet/schema/components/source.ts +220 -0
  34. package/src/build/blueprint/cognet/schema/components/tags.ts +66 -0
  35. package/src/build/blueprint/cognet/schema/components/typescript.ts +157 -0
  36. package/src/build/blueprint/cognet/schema/index.ts +5 -0
  37. package/src/build/blueprint/cognet/schema/interfaces/index.ts +3 -0
  38. package/src/build/blueprint/cognet/schema/interfaces/source.ts +218 -0
  39. package/src/build/blueprint/cognet/schema/python.ts +260 -0
  40. package/src/build/blueprint/cognet/schema/rust.ts +316 -0
  41. package/src/build/blueprint/cognet/schema/schema.ts +248 -0
  42. package/src/build/blueprint/cognet/schema/typescript.ts +352 -0
  43. package/src/build/blueprint/index.ts +1 -1
  44. package/src/build/blueprint/modules/index.ts +7 -5
  45. package/src/build/blueprint/modules/meta.ts +47 -3
  46. package/src/build/blueprint/scan/config.ts +22 -16
  47. package/src/build/blueprint/scan/provider-globals.ts +46 -0
  48. package/src/build/blueprint/scan/providers.ts +25 -0
  49. package/src/build/blueprint/scan/tools.ts +21 -15
  50. package/src/build/extensions/edit.ts +66 -2
  51. package/src/build/extensions/extensions.ts +16 -3
  52. package/src/build/extensions/index.ts +1 -1
  53. package/src/build/project/bundle/agent.ts +26 -17
  54. package/src/build/project/bundle/source.ts +2 -2
  55. package/src/build/project/create/cognet.ts +84 -33
  56. package/src/build/project/create/profile.ts +13 -3
  57. package/src/build/project/index.ts +1 -1
  58. package/src/build/project/installer.ts +6 -5
  59. package/src/build/project/kinds.ts +4 -0
  60. package/src/build/project/manifest/env.ts +10 -0
  61. package/src/build/project/models/blobs/blobs.ts +57 -0
  62. package/src/build/project/models/blobs/index.ts +1 -0
  63. package/src/build/project/models/fetch.ts +46 -51
  64. package/src/build/project/models/index.ts +2 -1
  65. package/src/build/project/models/models.ts +12 -38
  66. package/src/build/project/models/onnx.ts +82 -0
  67. package/src/build/project/models/specifier.ts +9 -3
  68. package/src/build/project/models/storage/index-store.ts +27 -0
  69. package/src/build/project/models/storage/index.ts +1 -0
  70. package/src/build/project/models/store.ts +21 -16
  71. package/src/build/project/prepare.ts +82 -27
  72. package/src/build/project/project.ts +8 -14
  73. package/src/build/project/projects.ts +12 -1
  74. package/src/build/project/tree.ts +13 -3
  75. package/src/build/project/treecache.ts +8 -4
  76. package/src/build/project/typegen/axon-dts.ts +18 -0
  77. package/src/build/project/typegen/cognet-dts.ts +248 -59
  78. package/src/build/project/typegen/prompt-dts.ts +2 -3
  79. package/src/build/project/typegen/registry-dts.ts +2 -2
  80. package/src/build/project/typegen/tsconfig.ts +13 -13
  81. package/src/build/project/typegen/tui-dts.ts +3 -4
  82. package/src/build/project/typegen/workspace-scripts.ts +8 -7
  83. package/src/build/project/typegen/write.ts +15 -2
  84. package/src/build/project/watcher.ts +27 -0
  85. package/src/build/runtime/agent.ts +102 -63
  86. package/src/build/runtime/conformance.ts +25 -0
  87. package/src/build/runtime/escalations.ts +3 -8
  88. package/src/build/runtime/index.ts +2 -0
  89. package/src/build/runtime/instances.ts +7 -4
  90. package/src/build/runtime/progress.ts +6 -2
  91. package/src/build/runtime/reload-watch.ts +11 -8
  92. package/src/debug/README.md +398 -0
  93. package/src/debug/debug.ts +101 -0
  94. package/src/debug/events.ts +156 -0
  95. package/src/debug/graph.ts +94 -0
  96. package/src/debug/index.ts +5 -0
  97. package/src/debug/indexer.ts +286 -0
  98. package/src/debug/inference.ts +53 -0
  99. package/src/debug/log.ts +68 -0
  100. package/src/debug/overview.ts +78 -0
  101. package/src/debug/perf.ts +75 -0
  102. package/src/debug/resources.ts +125 -0
  103. package/src/debug/ring.ts +31 -0
  104. package/src/debug/sessions.ts +90 -0
  105. package/src/debug/signs.ts +119 -0
  106. package/src/debug/tally.ts +44 -0
  107. package/src/debug/types.ts +146 -0
  108. package/src/index.ts +9 -0
  109. package/src/link/agent-main.ts +36 -10
  110. package/src/link/index.ts +1 -1
  111. package/src/link/services.ts +88 -57
  112. package/src/platform.ts +17 -25
  113. package/src/services/cloud.ts +1 -4
  114. package/src/services/control/client.ts +1 -1
  115. package/src/services/control/server.ts +1 -1
  116. package/src/services/index.ts +1 -0
  117. package/src/services/ollama/daemon.ts +23 -0
  118. package/src/services/ollama/http.ts +7 -1
  119. package/src/services/ollama/ollama.ts +8 -14
  120. package/src/services/probe/ask.ts +139 -0
  121. package/src/services/probe/index.ts +3 -0
  122. package/src/services/providers.ts +18 -0
  123. package/src/services/resources/hardware.ts +15 -18
  124. package/src/services/resources/resources.ts +4 -5
  125. package/src/services/store/types.ts +3 -0
  126. package/src/services/running/index.ts +0 -1
  127. package/src/services/running/running.ts +0 -216
@@ -161,16 +161,19 @@ function DeclareServer() {
161
161
  async function send(payload: string): Promise<DeclareWorkerResult> {
162
162
  if (!proc || proc.killed) spawn()
163
163
 
164
- const writer = (proc!.stdin as { write(chunk: string): void; flush?(): void })
164
+ const current = proc
165
+ const currentLines = lines
166
+ if (!current || !currentLines) throw new Error("declare-worker did not start")
167
+ const writer = (current.stdin as { write(chunk: string): void; flush?(): void })
165
168
  writer.write(`${payload}\n`)
166
169
  writer.flush?.()
167
170
 
168
- const next = await lines!.next()
171
+ const next = await currentLines.next()
169
172
  if (next.done) {
170
173
  // The worker exited rather than answering. Drop the handle so the
171
174
  // next call starts a fresh one instead of writing into a dead pipe.
172
- const stderr = await new Response(proc!.stderr as ReadableStream<Uint8Array>).text().catch(() => "")
173
- stop()
175
+ const stderr = await new Response(current.stderr as ReadableStream<Uint8Array>).text()
176
+ if (proc === current) stop()
174
177
  return { ok: false, message: `declare-worker exited without answering${stderr ? `\n${stderr}` : ""}` }
175
178
  }
176
179
 
@@ -181,17 +184,20 @@ function DeclareServer() {
181
184
 
182
185
  return {
183
186
  request(payload: string): Promise<DeclareWorkerResult> {
184
- const result = queue.then(() =>
185
- Promise.race([
186
- send(payload),
187
- new Promise<DeclareWorkerResult>(resolve =>
188
- setTimeout(() => {
189
- stop()
190
- resolve({ ok: false, message: `declare-worker timed out after ${REQUEST_TIMEOUT_MS}ms` })
191
- }, REQUEST_TIMEOUT_MS),
192
- ),
193
- ]),
194
- )
187
+ const result = queue.then(async () => {
188
+ let timer: ReturnType<typeof setTimeout> | undefined
189
+ try {
190
+ return await Promise.race([
191
+ send(payload),
192
+ new Promise<DeclareWorkerResult>(resolve => {
193
+ timer = setTimeout(() => {
194
+ stop()
195
+ resolve({ ok: false, message: `declare-worker timed out after ${REQUEST_TIMEOUT_MS}ms` })
196
+ }, REQUEST_TIMEOUT_MS)
197
+ }),
198
+ ])
199
+ } finally { if (timer) clearTimeout(timer) }
200
+ })
195
201
  // The chain must survive a rejection, or one failure wedges every
196
202
  // later request behind it forever.
197
203
  queue = result.catch(() => { })
@@ -31,6 +31,7 @@ import { readFile, writeFile } from "node:fs/promises"
31
31
  import { readFileSync } from "node:fs"
32
32
  import { join } from "node:path"
33
33
  import { err } from "@arcforge/err"
34
+ import type { ProfilePermissions } from "@arcforge/types"
34
35
  import { fsx } from "../../utils/fs"
35
36
  import { tsast } from "../../utils/tsast"
36
37
  import { parseRef } from "./store"
@@ -422,6 +423,68 @@ export async function readPolicy(profileRoot: string): Promise<Record<string, un
422
423
  return literalOf(value) as Record<string, unknown>
423
424
  }
424
425
 
426
+ /** The profile-wide command mediation preset. */
427
+ export async function readPermissions(profileRoot: string): Promise<ProfilePermissions> {
428
+ const path = configPath(profileRoot)
429
+ if (!fsx.exists(path)) return "normal"
430
+ const located = locateConfig(path, await readFile(path, "utf-8"))
431
+ if (!located) return "normal"
432
+
433
+ const value = tsast.prop(located.object, "permissions")
434
+ if (!value) return "normal"
435
+ if (!tsc().isStringLiteralLike(value) || !["normal", "allow", "ask"].includes(value.text)) {
436
+ throw err("PROFILE_CONFIG_UNEDITABLE", {
437
+ detail: `permissions must be \"normal\", \"allow\", or \"ask\" in ${path}`,
438
+ context: { path },
439
+ })
440
+ }
441
+ return value.text as ProfilePermissions
442
+ }
443
+
444
+ /** Write the profile-wide permission preset without rewriting the user's file. */
445
+ export async function setPermissions(profileRoot: string, permissions: ProfilePermissions): Promise<EditResult> {
446
+ const path = configPath(profileRoot)
447
+ if (!fsx.exists(path)) throw err("PROFILE_CONFIG_MISSING", { detail: path, context: { path } })
448
+
449
+ const text = await readFile(path, "utf-8")
450
+ const located = locateConfig(path, text)
451
+ if (!located) {
452
+ throw err("PROFILE_CONFIG_UNEDITABLE", {
453
+ detail: `could not find a defineProfile({ ... }) call in ${path}`,
454
+ context: { path },
455
+ })
456
+ }
457
+
458
+ const existing = located.object.properties.find(
459
+ prop => tsc().isPropertyAssignment(prop) && nameOf(prop.name) === "permissions",
460
+ )
461
+ if (existing && tsc().isPropertyAssignment(existing)) {
462
+ if (tsc().isStringLiteralLike(existing.initializer) && existing.initializer.text === permissions) return { changed: false }
463
+ const next = text.slice(0, existing.initializer.getStart(located.source))
464
+ + render(permissions, indentOf(text, existing.getStart(located.source)))
465
+ + text.slice(existing.initializer.getEnd())
466
+ await writeFile(path, verified(next, path))
467
+ return { changed: true }
468
+ }
469
+
470
+ const props = located.object.properties
471
+ const last = props[props.length - 1]
472
+ const indent = " ".repeat(last ? indentOf(text, last.getStart(located.source)) : 4)
473
+ const entry = `\n\n${indent}permissions: ${render(permissions, indent.length)},`
474
+ if (last) {
475
+ const trailing = text.slice(last.getEnd()).match(/^\s*,/)
476
+ const insertAt = last.getEnd() + (trailing ? trailing[0].length : 0)
477
+ const next = text.slice(0, insertAt) + `${trailing ? "" : ","}` + entry + text.slice(insertAt)
478
+ await writeFile(path, verified(next, path))
479
+ return { changed: true }
480
+ }
481
+
482
+ const open = located.object.getStart(located.source) + 1
483
+ const next = text.slice(0, open) + entry + "\n" + text.slice(open)
484
+ await writeFile(path, verified(next, path))
485
+ return { changed: true }
486
+ }
487
+
425
488
  /**
426
489
  * Set one key on `settings`, creating the block if it is absent.
427
490
  *
@@ -646,7 +709,7 @@ export async function readProviders(profileRoot: string): Promise<string[]> {
646
709
  * profile that never named a provider works rather than throwing about a
647
710
  * missing array.
648
711
  */
649
- export async function addProvider(profileRoot: string, factory: string): Promise<EditResult> {
712
+ export async function addProvider(profileRoot: string, factory: string, opts?: { initial?: readonly string[] }): Promise<EditResult> {
650
713
  const path = configPath(profileRoot)
651
714
  if (!fsx.exists(path)) {
652
715
  throw err("PROFILE_CONFIG_MISSING", { detail: path, context: { path } })
@@ -693,7 +756,8 @@ export async function addProvider(profileRoot: string, factory: string): Promise
693
756
  const first = object.object.properties[0]
694
757
  const insertAt = first ? first.getStart(object.source) : object.object.getStart(object.source) + 1
695
758
  const indent = first ? " ".repeat(indentOf(text, insertAt)) : " "
696
- const field = `providers: [${factory}()],`
759
+ const factories = [...new Set([...(opts?.initial ?? []), factory])]
760
+ const field = `providers: [${factories.map(name => `${name}()`).join(", ")}],`
697
761
  const next = first
698
762
  ? text.slice(0, insertAt) + `${field}\n\n${indent}` + text.slice(insertAt)
699
763
  : text.slice(0, insertAt) + `\n${indent}${field}\n` + text.slice(insertAt)
@@ -1,11 +1,12 @@
1
1
  import { mkdir, rename, rm } from "node:fs/promises"
2
2
  import { dirname, join } from "node:path"
3
3
  import { err } from "@arcforge/err"
4
+ import type { ProfilePermissions } from "@arcforge/types"
4
5
  import { gt, valid } from "semver"
5
6
  import { fsx } from "../../utils/fs"
6
7
  import { Watcher } from "../project"
7
8
  import { ProfileConfigFile, resolveEntry, type ResolvedEntry } from "./config"
8
- import { addEntry, addProvider, readEntries, readProviders, readSettings, removeEntry, removeProvider, setSetting } from "./edit"
9
+ import { addEntry, addProvider, readEntries, readProviders, readSettings, removeEntry, removeProvider, setPermissions, setSetting } from "./edit"
9
10
  import { ExtensionStore, formatRef, parseRef, type ExtensionStoreT } from "./store"
10
11
  import { DisposerSink, disposeSource, loadSource, RELOAD_PREFIX, type LoadedSource } from "./load"
11
12
 
@@ -294,6 +295,18 @@ export function Extensions(opts: ExtensionsOpts) {
294
295
  return suppress ? suppress(write) : write()
295
296
  },
296
297
 
298
+ /**
299
+ * Set command mediation for every agent in this profile.
300
+ *
301
+ * Deliberately NOT watcher-suppressed. A visual setting is already
302
+ * applied by its caller, but this setting becomes capsule policy at
303
+ * boot; suppressing the config change would leave the running agent
304
+ * under its old permission posture until an unrelated reload.
305
+ */
306
+ async setPermissions(permissions: ProfilePermissions): Promise<{ changed: boolean }> {
307
+ return setPermissions(opts.root(), permissions)
308
+ },
309
+
297
310
  /**
298
311
  * The provider factories this profile declares.
299
312
  *
@@ -312,9 +325,9 @@ export function Extensions(opts: ExtensionsOpts) {
312
325
  * not fire the watcher's reload, or connecting a provider would
313
326
  * restart every extension as a side effect.
314
327
  */
315
- async addProvider(factory: string): Promise<{ changed: boolean }> {
328
+ async addProvider(factory: string, options?: { initial?: readonly string[] }): Promise<{ changed: boolean }> {
316
329
  const root = opts.root()
317
- const write = () => addProvider(root, factory)
330
+ const write = () => addProvider(root, factory, options)
318
331
  return suppress ? suppress(write) : write()
319
332
  },
320
333
 
@@ -5,6 +5,6 @@
5
5
 
6
6
  export { Extensions, type ExtensionsT, type ExtensionsResult, type ExtensionUpdate } from "./extensions"
7
7
  export { ProfileConfigFile, resolveEntry, type ResolvedEntry, type ProfileConfigResult } from "./config"
8
- export { addEntry, addProvider, readEntries, readPolicy, readProviders, readSettings, readSettingsSync, removeEntry, removeProvider, setSetting, type EditResult } from "./edit"
8
+ export { addEntry, addProvider, readEntries, readPermissions, readPolicy, readProviders, readSettings, readSettingsSync, removeEntry, removeProvider, setPermissions, setSetting, type EditResult } from "./edit"
9
9
  export { DisposerSink, type LoadedSource, type LoadedFile } from "./load"
10
10
  export { ExtensionStore, formatRef, parseRef, type ExtensionStoreT, type StoredExtension } from "./store"
@@ -1,5 +1,6 @@
1
1
  import { dirname, join, relative, resolve, sep } from "node:path"
2
- import { cp, mkdir, rm } from "node:fs/promises"
2
+ import { existsSync } from "node:fs"
3
+ import { cp, mkdir, readdir, rm } from "node:fs/promises"
3
4
  import { axonBaseRef, type AxonConfig } from "@arcforge/types"
4
5
  import { err } from "@arcforge/err"
5
6
  import { Config, flatten } from "../../blueprint"
@@ -134,7 +135,7 @@ export function Agent(opts: AgentOpts) {
134
135
  // state — neither belongs to anyone but this one installation.
135
136
  // The published-files table in the docs has always said
136
137
  // `data/knowledge/ ✓ included`; this is what makes that true.
137
- const entries = ["src", "server", "modules", INLINE_COGNET_DIR, join("data", "knowledge")]
138
+ const entries = ["src", "server", "modules", "providers", INLINE_COGNET_DIR, join("data", "knowledge")]
138
139
  .filter(dir => fsx.exists(join(stageDir, dir)))
139
140
  // Tarball-relative, matching what stageCognet() laid down.
140
141
  entries.push(
@@ -223,7 +224,8 @@ async function copyTree(root: string, stageDir: string, target: BundleTarget): P
223
224
  // registry's source view and uneditable by anyone who clones it. An agent
224
225
  // with a registry cognet simply has no such directory, so this is a
225
226
  // no-op there.
226
- for (const dir of ["src", "server", "modules", INLINE_COGNET_DIR]) {
227
+ // `providers` is the agent's own code too — what fills the uses its grants name.
228
+ for (const dir of ["src", "server", "modules", "providers", INLINE_COGNET_DIR]) {
227
229
  const source = join(root, dir)
228
230
  if (fsx.exists(source)) await cp(source, join(stageDir, dir), { recursive: true })
229
231
  }
@@ -326,23 +328,30 @@ async function stageCognet(frame: FrameT, bundleDir: string, stageDir: string):
326
328
  const target = join(shipped, BUNDLE_COGNET_DIR)
327
329
  await cp(frame.path("cognet"), target, { recursive: true })
328
330
 
329
- // Strip everything the compile step scratches into the cognet dir.
331
+ // Ship what runs, and nothing the compile step scratches beside it.
330
332
  //
331
- // `.build` is the bundler's own workspace. `.instances` is per-RUNTIME
332
- // scratch: core copies the compiled cognet to a unique physical path per
333
- // booted agent (module scope is one brain's resident RAM, so two runtimes
334
- // must not share a module instance) and removes it on dispose. A `kill -9`
335
- // skips that dispose, so a developer's crashed local runs leave copies
336
- // behind — and they were being published.
337
- //
338
- // Shipping them is not cosmetic: each is a multi-hundred-KB duplicate of a
339
- // file already in the tarball, named with a hash and a UUID from the
340
- // publisher's machine, and long enough (130 chars) that GNU tar emits a
341
- // `@LongLink` pseudo-entry for it — which is what surfaced in the
342
- // registry's file tree as unexplained `@LongLink` rows.
343
- for (const scratch of [".build", ".instances"]) {
333
+ // `.build` and `.schema` are the bundler's and the schema compiler's
334
+ // workspaces; `schema/` is the TypeScript generated from the cognet's
335
+ // schemas, already compiled into the bundle; `native/` holds the Rust
336
+ // crate the build generates — its sources and a `target/` of hundreds of
337
+ // MB — beside the one content-named `.node` the bundle loads, which is all
338
+ // of it that ships. A `cognet.<hash>.mjs` is a hot reload's copy a crashed
339
+ // process left. (`.instances` is where older runtimes copied the bundle per
340
+ // boot; one still lying in a developer's frame must not be published —
341
+ // each is a multi-hundred-KB duplicate whose 130-char name made GNU tar
342
+ // emit the `@LongLink` rows seen in the registry's file tree.)
343
+ for (const scratch of [".build", ".schema", "schema", ".instances"]) {
344
344
  await rm(join(target, scratch), { recursive: true, force: true })
345
345
  }
346
+ for (const entry of await readdir(target)) {
347
+ if (/^cognet\.[0-9a-f]+\.mjs$/.test(entry)) await rm(join(target, entry), { force: true })
348
+ }
349
+ const native = join(target, "native")
350
+ if (existsSync(native)) {
351
+ for (const entry of await readdir(native)) {
352
+ if (!entry.endsWith(".node")) await rm(join(native, entry), { recursive: true, force: true })
353
+ }
354
+ }
346
355
 
347
356
  // The brain's path AS THE DEPLOYED CONTAINER WILL SEE IT — built from the
348
357
  // same two values that placed the file above, so the manifest cannot
@@ -1,6 +1,6 @@
1
1
  import { join } from "node:path"
2
2
  import { err } from "@arcforge/err"
3
- import { readCognetAbi } from "../../blueprint"
3
+ import { CognetConfigFile } from "../../blueprint"
4
4
  import { fsx } from "../../../utils/fs"
5
5
  import { KINDS } from "../kinds"
6
6
  import { Frame } from "../../frame"
@@ -82,7 +82,7 @@ export function Source(opts: SourceOpts) {
82
82
  // neither declares a kernel contract, and the field is omitted for
83
83
  // both, so the registry row stays NULL rather than carrying a
84
84
  // number nobody asserted.
85
- const abi = kind === "cognet" ? await readCognetAbi(root) : null
85
+ const abi = kind === "cognet" ? CognetConfigFile({ sourceDir: root }).read()?.abi ?? null : null
86
86
 
87
87
  const image: SourceImage = {
88
88
  kind,
@@ -7,44 +7,86 @@ import { bareName, type ScaffoldOpts } from "../kinds"
7
7
 
8
8
  const CONFIG_TEMPLATE = (name: string) => `// ${name} — what this brain declares.
9
9
  //
10
- // Identity comes from package.json and behavior from src/main.ts; the compile
11
- // step composes the three. The kernel ABI is stamped in at compile time, so
10
+ // Identity comes from package.json; behaviour from its systems — every
11
+ // *.system.ts under src/. The kernel ABI is stamped in at compile time, so
12
12
  // there is nothing to pin unless you want this brain to REFUSE a kernel it
13
13
  // has not been validated against.
14
14
  export default defineCognet({
15
+ // Wakes when a stimulus arrives. A mind that must keep acting whether or
16
+ // not the world spoke declares { kind: "continuous", hz } instead.
15
17
  mode: { kind: "invocation" },
16
18
  })
17
19
  `
18
20
 
19
- const MAIN_TEMPLATE = (name: string) => `// ${name} — a raw script: this file IS the brain.
20
- //
21
- // Runs once at load(), with the ambient globals live (kernel, loop, phase,
22
- // system, blueprint — typed by the generated frame, run \`axon prepare\`).
23
- // Module scope is resident RAM: alive across wakes, rebuildable from the
24
- // log, gone without loss on kill -9 — never authoritative.
25
-
26
- loop(async ({ stimuli, signal, stop }) => {
27
- await phase("sense", async () => {
28
- // one deterministic fold: new entries → your own resident model.
29
- // kernel.store.session.get({ after: seq }) is the same door for
30
- // cold-boot hydration and steady-state diffs — the equivalence
31
- // that makes kill -9 free.
32
- })
33
-
34
- await phase("think", async () => {
35
- // strategy. yours. the kernel has no opinion past this comment.
36
- // const messages = ...render from your model...
37
- // for await (const event of kernel.stream({ messages, signal })) { ... }
38
- })
39
-
40
- await phase("act", async () => {
41
- // effects leave ONLY through the two verbs:
42
- // kernel.output(type, data) — unmediated emission (chunk: {of, final} to stream)
43
- // kernel.run(code) — mediated capsule execution, committed for you
44
- })
45
-
46
- // quiescent? nothing pending → this wake is over. the brain stays warm.
47
- stop()
21
+ const SCHEMA_TEMPLATE = (name: string) => `// What ${name} believes about the room. Components are declared here, in no
22
+ // language: \`axon prepare\` generates the TypeScript (and Rust) types and
23
+ // handles, imported as #schema/sense/sense.
24
+ syntax = "proto3";
25
+
26
+ package ${protoPackage(name)}.sense;
27
+
28
+ import "cognet/cognet.proto";
29
+
30
+ // A temperature, and when it was felt.
31
+ message Reading {
32
+ double celsius = 1;
33
+ double at = 2;
34
+ }
35
+
36
+ message Components {
37
+ option (cognet.components) = true;
38
+
39
+ // The newest temperature the room reported. act/ reads it.
40
+ Reading temperature = 1;
41
+ }
42
+ `
43
+
44
+ const FEEL_TEMPLATE = `import { temperature } from "#schema/sense/sense"
45
+
46
+ /**
47
+ * Feel — the newest temperature the body reported, as a belief.
48
+ *
49
+ * Reads stimuli: every one since this system last ran, so nothing that
50
+ * arrived is missed. Writes the belief only; deciding what to do about it is
51
+ * another system's.
52
+ */
53
+ export default defineSystem({
54
+ reads: [stimuli],
55
+ writes: [temperature],
56
+
57
+ run({ stimuli }) {
58
+ for (const stimulus of stimuli) {
59
+ if (stimulus.type !== "cognet:stimulus:vector" || stimulus.data.channel !== "/temperature") continue
60
+ ecs.set({
61
+ id: "room",
62
+ components: { temperature: { celsius: stimulus.data.values[0]!, at: stimulus.time.ms } },
63
+ })
64
+ }
65
+ },
66
+ })
67
+ `
68
+
69
+ const HEAT_TEMPLATE = `import { temperature } from "#schema/sense/sense"
70
+
71
+ const SETTINGS = { target: 21 }
72
+
73
+ /**
74
+ * Heat — turn the heater on below the target, off above it.
75
+ *
76
+ * Runs after feel, and only when the temperature changed: it reads what feel
77
+ * writes, and the schedule derives both from that alone.
78
+ */
79
+ export default defineSystem({
80
+ reads: [temperature],
81
+
82
+ async run() {
83
+ const [room] = ecs.query({ components: ["temperature"] })
84
+ if (!room) return
85
+ await kernel.output("cognet:output:vector", {
86
+ channel: "/heater",
87
+ values: [room.temperature.celsius < SETTINGS.target ? 1 : 0],
88
+ })
89
+ },
48
90
  })
49
91
  `
50
92
 
@@ -73,11 +115,14 @@ export async function scaffoldCognet(opts: ScaffoldOpts): Promise<string> {
73
115
  throw err("PROJECT_EXISTS", { detail: `${root} already exists`, context: { root } })
74
116
  }
75
117
 
76
- await mkdir(join(root, "src"), { recursive: true })
118
+ await mkdir(join(root, "src", "sense"), { recursive: true })
119
+ await mkdir(join(root, "src", "act"), { recursive: true })
77
120
 
78
121
  const files: Promise<unknown>[] = [
79
122
  writeFile(join(root, "cognet.config.ts"), CONFIG_TEMPLATE(opts.name)),
80
- writeFile(join(root, "src", "main.ts"), MAIN_TEMPLATE(opts.name)),
123
+ writeFile(join(root, "src", "sense", "sense.proto"), SCHEMA_TEMPLATE(opts.name)),
124
+ writeFile(join(root, "src", "sense", "feel.system.ts"), FEEL_TEMPLATE),
125
+ writeFile(join(root, "src", "act", "heat.system.ts"), HEAT_TEMPLATE),
81
126
  ]
82
127
 
83
128
  // A standalone cognet is a package: it has an identity to publish, its own
@@ -100,3 +145,9 @@ export async function scaffoldCognet(opts: ScaffoldOpts): Promise<string> {
100
145
 
101
146
  return root
102
147
  }
148
+
149
+ /** A cognet name as a proto package segment: lowercase letters, digits and underscores, starting with a letter. */
150
+ function protoPackage(name: string): string {
151
+ const bare = bareName(name).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")
152
+ return /^[a-z]/.test(bare) ? bare : `cognet_${bare}`
153
+ }
@@ -58,10 +58,20 @@ commands.register("hello", {
58
58
  })
59
59
  `
60
60
 
61
+ const DEFAULT_EXTENSIONS = [
62
+ "@axon/ember-theme",
63
+ "@axon/gruvbox-theme",
64
+ "@axon/mocha-theme",
65
+ "@axon/nord",
66
+ "@axon/rose-pine",
67
+ "@axon/tokyo-night",
68
+ ]
69
+
61
70
  const CONFIG_TEMPLATE = `export default defineProfile({
62
- // Extensions load in this order. A registry name ("@axon/vim") is fetched
63
- // and installed; a path ("./extensions/mine") is used where it sits.
64
- extensions: [],
71
+ // Axon's built-in theme collection. Add registry names or local paths here.
72
+ extensions: [
73
+ ${DEFAULT_EXTENSIONS.map(name => ` "${name}",`).join("\n")}
74
+ ],
65
75
  })
66
76
  `
67
77
 
@@ -35,6 +35,6 @@ export { Frame, type FrameT, type FrameArea } from "../frame"
35
35
 
36
36
  // Model weights — declared by a cognet, fetched and verified here, handed to
37
37
  // the brain as absolute paths. An asset store that happens to be used for ML.
38
- export { Models, ModelStore, parseModel, parseModels, downloadUrl, basenameOf, fetchModel } from "./models"
38
+ export { Models, ModelStore, parseModel, parseModels, downloadUrl, basenameOf, Fetch, onnx } from "./models"
39
39
  export type { ModelsT, ResolveResult, ModelStoreT, StoredModel, ParsedModel } from "./models"
40
40
  export { parseSpecifier } from "./specifier"
@@ -247,11 +247,12 @@ export function Installer(opts: InstallerOpts) {
247
247
  additions[name] = range
248
248
  repaired.push({ name, from: existing, to: range, origin })
249
249
  }
250
- } catch {
251
- // Unresolvable here too. Left alone deliberately: the
252
- // install that follows fails with the package manager's own
253
- // message, which is more specific than anything this could
254
- // invent about a package it could not reach.
250
+ } catch (cause) {
251
+ // This is the boundary that discovered the incompatible
252
+ // registry state. Continuing would make Bun fail later
253
+ // with a manifest-wide error that hides which tracked
254
+ // range became invalid.
255
+ throw cause
255
256
  }
256
257
  }
257
258
 
@@ -170,6 +170,7 @@ export const KINDS: Record<Kind, KindSpec> = {
170
170
  "src/**/*.vue",
171
171
  "scripts/**/*.ts",
172
172
  "server/**/*.ts",
173
+ "providers/**/*.ts",
173
174
  "modules/**/*.ts",
174
175
  "modules/**/*.vue",
175
176
  ],
@@ -214,6 +215,9 @@ export const KINDS: Record<Kind, KindSpec> = {
214
215
  "./**/*.d.ts",
215
216
  "*.ts",
216
217
  "src/**/*.ts",
218
+ "types/**/*.ts",
219
+ "interfaces/**/*.ts",
220
+ "library/**/*.ts",
217
221
  "plugins/**/*.ts",
218
222
  "tests/**/*.ts",
219
223
  ],
@@ -65,6 +65,16 @@ export function Env(opts: EnvOpts) {
65
65
  return values
66
66
  },
67
67
 
68
+ /**
69
+ * The variables this agent's .env sets, as the runtime reads them —
70
+ * comments, quotes and `export` handled by the one parser. Unvalidated:
71
+ * a running agent takes what the file says; `production()` is the gate.
72
+ */
73
+ async values(): Promise<Record<string, string>> {
74
+ const content = await fsx.readText(path)
75
+ return content ? parse(content) : {}
76
+ },
77
+
68
78
  /**
69
79
  * The variable names this agent's .env defines. Names only — a caller
70
80
  * listing keys must never be handed the secrets to render.
@@ -0,0 +1,57 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { mkdir, open, rename, rm } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { err } from "@arcforge/err"
5
+ import type { StoredModel } from "../store"
6
+
7
+ /** Stream verified bytes into the content-addressed store with bounded memory. */
8
+ export function Blobs(opts: { root: string }) {
9
+ async function receive(input: {
10
+ filename: string
11
+ body: ReadableStream<Uint8Array>
12
+ expected?: string
13
+ signal?: AbortSignal
14
+ progress?(received: number): void
15
+ }): Promise<StoredModel> {
16
+ await mkdir(opts.root, { recursive: true })
17
+ const temporary = join(opts.root, `.incoming-${randomUUID()}`)
18
+ const file = await open(temporary, "wx")
19
+ const reader = input.body.getReader()
20
+ const hash = createHash("sha256")
21
+ let bytes = 0
22
+ try {
23
+ while (true) {
24
+ input.signal?.throwIfAborted()
25
+ const chunk = await reader.read()
26
+ if (chunk.done) break
27
+ hash.update(chunk.value)
28
+ let offset = 0
29
+ while (offset < chunk.value.length) {
30
+ const result = await file.write(chunk.value, offset, chunk.value.length - offset)
31
+ if (result.bytesWritten <= 0) throw err("MODEL_FETCH_FAILED", { detail: "model file write made no progress" })
32
+ offset += result.bytesWritten
33
+ }
34
+ bytes += chunk.value.length
35
+ input.progress?.(bytes)
36
+ }
37
+ input.signal?.throwIfAborted()
38
+ const sha256 = hash.digest("hex")
39
+ if (input.expected && input.expected !== sha256) throw err("MODEL_HASH_MISMATCH", { detail: `${input.filename}: expected ${input.expected}, received ${sha256}` })
40
+ const directory = join(opts.root, sha256)
41
+ await mkdir(directory, { recursive: true })
42
+ await file.sync()
43
+ await file.close()
44
+ const path = join(directory, input.filename)
45
+ input.signal?.throwIfAborted()
46
+ await rename(temporary, path)
47
+ return { path: path, sha256: sha256, bytes: bytes }
48
+ } finally {
49
+ try { await reader.cancel() } finally {
50
+ reader.releaseLock()
51
+ await file.close()
52
+ await rm(temporary, { force: true })
53
+ }
54
+ }
55
+ }
56
+ return { receive: receive }
57
+ }
@@ -0,0 +1 @@
1
+ export { Blobs } from "./blobs"