@arcforge/platform 2.0.166

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 (207) hide show
  1. package/README.md +31 -0
  2. package/package.json +69 -0
  3. package/src/bin/supervisor.ts +102 -0
  4. package/src/bin/test-api.ts +30 -0
  5. package/src/bin/test-preload.ts +308 -0
  6. package/src/bin/update-helper.ts +32 -0
  7. package/src/build/bench/CLAUDE.md +106 -0
  8. package/src/build/bench/SPEC.md +209 -0
  9. package/src/build/bench/agents.ts +105 -0
  10. package/src/build/bench/axes.ts +84 -0
  11. package/src/build/bench/bench.ts +96 -0
  12. package/src/build/bench/discover.ts +147 -0
  13. package/src/build/bench/index.ts +7 -0
  14. package/src/build/bench/log.ts +47 -0
  15. package/src/build/bench/matrix.ts +23 -0
  16. package/src/build/bench/preload.ts +440 -0
  17. package/src/build/bench/prepare.ts +61 -0
  18. package/src/build/bench/projection.ts +112 -0
  19. package/src/build/bench/resolve.ts +54 -0
  20. package/src/build/bench/runner.ts +309 -0
  21. package/src/build/bench/schema/extract.ts +148 -0
  22. package/src/build/bench/schema/index.ts +2 -0
  23. package/src/build/bench/schema/schema.ts +95 -0
  24. package/src/build/bench/schema/worker.ts +30 -0
  25. package/src/build/bench/typegen.ts +119 -0
  26. package/src/build/bench/workspace/files.ts +139 -0
  27. package/src/build/bench/workspace/handle.ts +133 -0
  28. package/src/build/bench/workspace/index.ts +11 -0
  29. package/src/build/bench/workspace/workspace.ts +14 -0
  30. package/src/build/blueprint/blueprint.ts +398 -0
  31. package/src/build/blueprint/cognet/abi.ts +207 -0
  32. package/src/build/blueprint/cognet/bundle-worker.ts +93 -0
  33. package/src/build/blueprint/cognet/bundle.ts +664 -0
  34. package/src/build/blueprint/cognet/cognet.ts +249 -0
  35. package/src/build/blueprint/cognet/index.ts +10 -0
  36. package/src/build/blueprint/cognet/manifest.ts +38 -0
  37. package/src/build/blueprint/cognet/resolve.ts +113 -0
  38. package/src/build/blueprint/collisions.ts +51 -0
  39. package/src/build/blueprint/index.ts +29 -0
  40. package/src/build/blueprint/modules/entries.ts +117 -0
  41. package/src/build/blueprint/modules/index.ts +300 -0
  42. package/src/build/blueprint/modules/meta.ts +174 -0
  43. package/src/build/blueprint/scan/boot.ts +34 -0
  44. package/src/build/blueprint/scan/cognetImports.ts +56 -0
  45. package/src/build/blueprint/scan/components.ts +45 -0
  46. package/src/build/blueprint/scan/config.ts +234 -0
  47. package/src/build/blueprint/scan/configImports.ts +232 -0
  48. package/src/build/blueprint/scan/declare-worker.ts +61 -0
  49. package/src/build/blueprint/scan/declare.ts +393 -0
  50. package/src/build/blueprint/scan/h3-globals.ts +137 -0
  51. package/src/build/blueprint/scan/knowledge.ts +101 -0
  52. package/src/build/blueprint/scan/middleware.ts +110 -0
  53. package/src/build/blueprint/scan/moduleImports.ts +79 -0
  54. package/src/build/blueprint/scan/plugins.ts +93 -0
  55. package/src/build/blueprint/scan/promptPackages.ts +45 -0
  56. package/src/build/blueprint/scan/prompts.ts +164 -0
  57. package/src/build/blueprint/scan/published.ts +131 -0
  58. package/src/build/blueprint/scan/resolve.ts +398 -0
  59. package/src/build/blueprint/scan/routes.ts +109 -0
  60. package/src/build/blueprint/scan/scripts.ts +119 -0
  61. package/src/build/blueprint/scan/tool-bundle-worker.ts +69 -0
  62. package/src/build/blueprint/scan/tools.ts +610 -0
  63. package/src/build/blueprint/types.ts +28 -0
  64. package/src/build/extensions/config.ts +261 -0
  65. package/src/build/extensions/edit.ts +684 -0
  66. package/src/build/extensions/extensions.ts +731 -0
  67. package/src/build/extensions/index.ts +10 -0
  68. package/src/build/extensions/load.ts +350 -0
  69. package/src/build/extensions/registrations.ts +189 -0
  70. package/src/build/extensions/store.ts +200 -0
  71. package/src/build/frame/frame.ts +145 -0
  72. package/src/build/frame/index.ts +5 -0
  73. package/src/build/frame/migrate.ts +246 -0
  74. package/src/build/project/bundle/agent.ts +382 -0
  75. package/src/build/project/bundle/artifacts.ts +88 -0
  76. package/src/build/project/bundle/assets.ts +385 -0
  77. package/src/build/project/bundle/bundle.ts +160 -0
  78. package/src/build/project/bundle/imports.ts +102 -0
  79. package/src/build/project/bundle/index.ts +16 -0
  80. package/src/build/project/bundle/module.ts +130 -0
  81. package/src/build/project/bundle/source.ts +136 -0
  82. package/src/build/project/bundle/stage.ts +97 -0
  83. package/src/build/project/bundle/types.ts +111 -0
  84. package/src/build/project/cognet.ts +156 -0
  85. package/src/build/project/create/agent.ts +52 -0
  86. package/src/build/project/create/bench.ts +81 -0
  87. package/src/build/project/create/cognet.ts +102 -0
  88. package/src/build/project/create/extension.ts +63 -0
  89. package/src/build/project/create/module.ts +43 -0
  90. package/src/build/project/create/profile.ts +102 -0
  91. package/src/build/project/create/prompt.ts +68 -0
  92. package/src/build/project/create/templates.ts +88 -0
  93. package/src/build/project/deploy.ts +96 -0
  94. package/src/build/project/index.ts +40 -0
  95. package/src/build/project/installer.ts +616 -0
  96. package/src/build/project/kinds.ts +374 -0
  97. package/src/build/project/links.ts +33 -0
  98. package/src/build/project/manifest/bunfig.ts +139 -0
  99. package/src/build/project/manifest/config.ts +246 -0
  100. package/src/build/project/manifest/env.ts +184 -0
  101. package/src/build/project/manifest/index.ts +9 -0
  102. package/src/build/project/manifest/manifest.ts +49 -0
  103. package/src/build/project/manifest/model.ts +124 -0
  104. package/src/build/project/manifest/package.ts +386 -0
  105. package/src/build/project/manifest/text.ts +19 -0
  106. package/src/build/project/models/fetch.ts +123 -0
  107. package/src/build/project/models/index.ts +8 -0
  108. package/src/build/project/models/models.ts +111 -0
  109. package/src/build/project/models/specifier.ts +106 -0
  110. package/src/build/project/models/store.ts +202 -0
  111. package/src/build/project/modules/hash.ts +31 -0
  112. package/src/build/project/modules/index.ts +5 -0
  113. package/src/build/project/modules/lock.ts +78 -0
  114. package/src/build/project/modules/modules.ts +155 -0
  115. package/src/build/project/prepare.ts +709 -0
  116. package/src/build/project/project.ts +253 -0
  117. package/src/build/project/projects.ts +164 -0
  118. package/src/build/project/propagation.ts +120 -0
  119. package/src/build/project/publish/verify.ts +312 -0
  120. package/src/build/project/publish.ts +155 -0
  121. package/src/build/project/reconcile.ts +93 -0
  122. package/src/build/project/specifier.ts +42 -0
  123. package/src/build/project/tree.ts +615 -0
  124. package/src/build/project/treecache.ts +356 -0
  125. package/src/build/project/typegen/axon-dts.ts +362 -0
  126. package/src/build/project/typegen/cognet-dts.ts +91 -0
  127. package/src/build/project/typegen/components.ts +45 -0
  128. package/src/build/project/typegen/env.ts +59 -0
  129. package/src/build/project/typegen/generators.ts +108 -0
  130. package/src/build/project/typegen/hooks.ts +71 -0
  131. package/src/build/project/typegen/index.ts +137 -0
  132. package/src/build/project/typegen/prompt-dts.ts +40 -0
  133. package/src/build/project/typegen/prompts.ts +36 -0
  134. package/src/build/project/typegen/registry-dts.ts +109 -0
  135. package/src/build/project/typegen/scripts.ts +37 -0
  136. package/src/build/project/typegen/tools.ts +31 -0
  137. package/src/build/project/typegen/tsconfig.ts +243 -0
  138. package/src/build/project/typegen/tui-dts.ts +120 -0
  139. package/src/build/project/typegen/write.ts +40 -0
  140. package/src/build/project/verify.ts +268 -0
  141. package/src/build/project/watcher.ts +266 -0
  142. package/src/build/runtime/agent.ts +550 -0
  143. package/src/build/runtime/escalations.ts +159 -0
  144. package/src/build/runtime/index.ts +15 -0
  145. package/src/build/runtime/instances.ts +604 -0
  146. package/src/build/runtime/profile.ts +91 -0
  147. package/src/build/runtime/progress.ts +143 -0
  148. package/src/build/runtime/requests.ts +167 -0
  149. package/src/build/runtime/resolve.ts +159 -0
  150. package/src/build/runtime/runtime.ts +233 -0
  151. package/src/build/runtime/sessions/index.ts +5 -0
  152. package/src/build/runtime/sessions/record.ts +145 -0
  153. package/src/build/runtime/sessions/sessions.ts +240 -0
  154. package/src/build/runtime/zeno.ts +120 -0
  155. package/src/index.ts +11 -0
  156. package/src/link/agent-main.ts +395 -0
  157. package/src/link/index.ts +70 -0
  158. package/src/link/services.ts +120 -0
  159. package/src/platform.ts +293 -0
  160. package/src/procs/index.ts +15 -0
  161. package/src/procs/tree.ts +177 -0
  162. package/src/services/cloud.ts +419 -0
  163. package/src/services/control/client.ts +126 -0
  164. package/src/services/control/dispatch.ts +156 -0
  165. package/src/services/control/index.ts +17 -0
  166. package/src/services/control/protocol.ts +179 -0
  167. package/src/services/control/server.ts +241 -0
  168. package/src/services/deployments.ts +81 -0
  169. package/src/services/files.ts +329 -0
  170. package/src/services/index.ts +5 -0
  171. package/src/services/mic/capture.ts +248 -0
  172. package/src/services/mic/config.ts +109 -0
  173. package/src/services/mic/fft.ts +93 -0
  174. package/src/services/mic/index.ts +139 -0
  175. package/src/services/mic/visualizer.ts +46 -0
  176. package/src/services/ollama/catalog.ts +122 -0
  177. package/src/services/ollama/http.ts +124 -0
  178. package/src/services/ollama/index.ts +13 -0
  179. package/src/services/ollama/models.ts +153 -0
  180. package/src/services/ollama/ollama.ts +89 -0
  181. package/src/services/ollama/registry.ts +112 -0
  182. package/src/services/ollama/types.ts +72 -0
  183. package/src/services/prompts.ts +76 -0
  184. package/src/services/registry.ts +220 -0
  185. package/src/services/resources/hardware.ts +125 -0
  186. package/src/services/resources/index.ts +6 -0
  187. package/src/services/resources/reservations.ts +162 -0
  188. package/src/services/resources/resources.ts +156 -0
  189. package/src/services/running/index.ts +1 -0
  190. package/src/services/running/running.ts +200 -0
  191. package/src/services/store/disk.ts +97 -0
  192. package/src/services/store/index.ts +15 -0
  193. package/src/services/store/store.ts +729 -0
  194. package/src/services/store/types.ts +303 -0
  195. package/src/services/test/child.ts +150 -0
  196. package/src/services/test/events.ts +102 -0
  197. package/src/services/test/files.ts +26 -0
  198. package/src/services/test/frames.ts +39 -0
  199. package/src/services/test/index.ts +7 -0
  200. package/src/services/test/runner.ts +122 -0
  201. package/src/services/test/types.ts +26 -0
  202. package/src/services/update/contract.ts +77 -0
  203. package/src/services/update/index.ts +12 -0
  204. package/src/services/update/installer.ts +139 -0
  205. package/src/services/update/updates.ts +137 -0
  206. package/src/utils/fs.ts +148 -0
  207. package/src/utils/tsast.ts +102 -0
@@ -0,0 +1,109 @@
1
+ /**
2
+ * VisualizerConfig — every tunable knob for the mic's braille waveform,
3
+ * gathered in one file. Getting this to look/feel right is fiddly (window
4
+ * size, bucket count, smoothing, decay) — change values here, not in
5
+ * fft.ts or visualizer.ts, which are meant to stay pure functions of
6
+ * whatever config they're given.
7
+ */
8
+ export type VisualizerConfig = {
9
+ /** Must match capture.ts's sox invocation — samples/sec of the raw PCM stream. */
10
+ sampleRate: number
11
+ /** FFT window size in samples. Must be a power of two. Bigger = finer frequency resolution, slower to compute, more latency per frame. */
12
+ fftSize: number
13
+ /** How often (ms) a new frame is sampled, FFT'd, and rendered while the mic is active. */
14
+ tickMs: number
15
+ /** Number of frequency buckets, spaced log-scale across the audible range so bass/mid/treble get roughly even visual weight. Two buckets render per braille character (left/right dot columns are independent buckets) — keep this even. */
16
+ bucketCount: number
17
+ /** Lowest/highest frequency (Hz) folded into buckets — outside this range is discarded. */
18
+ minFreqHz: number
19
+ maxFreqHz: number
20
+ /**
21
+ * A single FFT frame's magnitude per bucket has real statistical
22
+ * variance — it's not a bug, it's how FFT-of-noise behaves — so raw
23
+ * per-tick dB is itself averaged (exponential moving average) BEFORE
24
+ * floor tracking or the gate ever see it. Without this, even the
25
+ * floor tracker chases per-frame noise instead of converging to a
26
+ * stable baseline, and no gate threshold can cleanly separate real
27
+ * quiet signal from noise jitter. 0 = no averaging (raw), 1 = frozen.
28
+ */
29
+ magnitudeSmoothing: number
30
+ /** Exponential smoothing between frames, 0 (no smoothing, raw/jittery) to 1 (frozen). Blends toward the new magnitude each tick. */
31
+ smoothing: number
32
+ /** How much a bucket's visual level falls per tick when input drops (e.g. between words) — keeps silence from cutting bars off instantly. 0 = no decay (instant drop), 1 = never falls on its own. */
33
+ decayPerTick: number
34
+ /**
35
+ * Dynamic range (dB) ABOVE each bucket's own live noise floor mapped to
36
+ * the visual 0..1 range — a bucket reading floor+headroomDb or louder
37
+ * shows full height. There is no fixed minDb: "silence" is whatever
38
+ * that bucket's floor currently is, tracked live (see floorRiseRate/
39
+ * floorFallRate) rather than a hardcoded number, because room noise/
40
+ * mic self-noise varies per machine and even per session (a fan
41
+ * kicking on, etc.) — the same reason real noise gates calibrate to
42
+ * the room instead of assuming a fixed silence level.
43
+ */
44
+ headroomDb: number
45
+ /**
46
+ * Per-bucket floor tracking rate, applied once per tick. The floor
47
+ * chases the current reading: FALLS fast when the signal drops below
48
+ * it (so "someone stopped talking" or "quieter background" is picked
49
+ * up quickly), RISES slowly when the signal sits above it (so a
50
+ * sustained loud moment doesn't get treated as "the new normal" too
51
+ * fast, which would numb the display to real loud speech). Both are
52
+ * 0..1 blend rates per tick, same shape as smoothing/decayPerTick.
53
+ */
54
+ floorFallRate: number
55
+ floorRiseRate: number
56
+ /**
57
+ * Gain compensation, in dB boost per octave above minFreqHz. Real audio
58
+ * (voice, music, nearly everything) carries far more energy in bass
59
+ * than treble — the spectral tilt is a physical property of sound, not
60
+ * a bug — so without this, low buckets visually dominate and the
61
+ * waveform reads as "bass-only" even when there's real energy higher
62
+ * up (the consonants/sibilance that actually carry speech). Each
63
+ * bucket gets +gainPerOctaveDb for every octave its center frequency
64
+ * sits above minFreqHz, applied before the floor-relative mapping.
65
+ */
66
+ gainPerOctaveDb: number
67
+ /**
68
+ * Noise gate — a real, always-jittery noise floor means individual
69
+ * buckets randomly poke a dot or two above 0 even in silence (that's
70
+ * normal FFT-of-noise behavior, not a bug in the floor tracker). Below
71
+ * gateThreshold, level snaps to exactly 0 — the same thing a hardware
72
+ * noise gate does. gateKneeWidth ramps smoothly from 0 up to the real
73
+ * value across [gateThreshold, gateThreshold+gateKneeWidth] instead of
74
+ * a hard on/off step, so a bucket hovering right at the line doesn't
75
+ * flicker between "nothing" and "some" every tick.
76
+ */
77
+ gateThreshold: number
78
+ gateKneeWidth: number
79
+ }
80
+
81
+ export const defaultVisualizerConfig: VisualizerConfig = {
82
+ sampleRate: 16_000,
83
+ fftSize: 1024,
84
+ // 16ms = 60fps — matches VTerm's real render rate. FFT cost is
85
+ // negligible (~0.1ms/call, ~270x headroom even at a much slower 30ms
86
+ // tick), so there's no reason to sample slower than the display can
87
+ // show; every redraw is a fresh sample, not an interpolated one.
88
+ tickMs: 16,
89
+ bucketCount: 112, // 56 rendered characters (2 buckets/char) — double the previous display width
90
+ minFreqHz: 80,
91
+ maxFreqHz: 6_000,
92
+ // ~3-4 ticks (at 16ms) to reach ~90% of a sudden loud onset — still
93
+ // well within "reacts within a syllable" while smoothing away most
94
+ // single-frame noise variance.
95
+ magnitudeSmoothing: 0.6,
96
+ // Low smoothing/decay = fast attack AND fast release — the bar should
97
+ // snap up and back down within a syllable (roughly 80-200ms), not
98
+ // linger across several. Tune by ear from here.
99
+ smoothing: 0.15,
100
+ decayPerTick: 0.5,
101
+ headroomDb: 24,
102
+ // Fall fast (react to quieter conditions quickly), rise slowly (don't
103
+ // let a sustained loud moment redefine "normal" too fast).
104
+ floorFallRate: 0.05,
105
+ floorRiseRate: 0.01,
106
+ gainPerOctaveDb: 6,
107
+ gateThreshold: 0.22,
108
+ gateKneeWidth: 0.1,
109
+ }
@@ -0,0 +1,93 @@
1
+ import FFT from "fft.js"
2
+ import { err } from "@arcforge/err"
3
+ import type { VisualizerConfig } from "./config"
4
+
5
+ /**
6
+ * fft — pure signal math, no process/state. Takes one window of PCM
7
+ * samples and a config, returns one magnitude (dB) per frequency bucket.
8
+ * Fully unit-testable without a real mic: feed it a synthetic sine wave
9
+ * and assert energy lands in the expected bucket.
10
+ */
11
+
12
+ /** Hann window — tapers the edges of the sample block so the FFT doesn't see a hard cut, which otherwise smears energy across every bucket (spectral leakage). */
13
+ function hannWindow(samples: Float32Array): Float32Array {
14
+ const n = samples.length
15
+ const windowed = new Float32Array(n)
16
+ for (let i = 0; i < n; i++) {
17
+ const w = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (n - 1)))
18
+ windowed[i] = samples[i]! * w
19
+ }
20
+ return windowed
21
+ }
22
+
23
+ /** Log-spaced bucket edges between minFreqHz/maxFreqHz — equal visual weight per octave, not per Hz. */
24
+ function bucketEdges(config: VisualizerConfig): number[] {
25
+ const { bucketCount, minFreqHz, maxFreqHz } = config
26
+ const logMin = Math.log2(minFreqHz)
27
+ const logMax = Math.log2(maxFreqHz)
28
+ const edges: number[] = []
29
+ for (let i = 0; i <= bucketCount; i++) {
30
+ edges.push(2 ** (logMin + ((logMax - logMin) * i) / bucketCount))
31
+ }
32
+ return edges
33
+ }
34
+
35
+ /**
36
+ * Runs one FFT over `samples` (must be exactly config.fftSize long — pad
37
+ * or trim before calling) and returns config.bucketCount magnitudes in dB,
38
+ * bucketed log-scale across [minFreqHz, maxFreqHz].
39
+ */
40
+ export function computeBuckets(samples: Float32Array, config: VisualizerConfig): number[] {
41
+ const { fftSize, sampleRate, bucketCount } = config
42
+ if (samples.length !== fftSize) {
43
+ throw err("MIC_FFT_SIZE_MISMATCH", { detail: `expected ${fftSize} samples, got ${samples.length}`, context: { expected: fftSize, actual: samples.length } })
44
+ }
45
+
46
+ const windowed = hannWindow(samples)
47
+ const fft = new FFT(fftSize)
48
+ const out = fft.createComplexArray()
49
+ fft.realTransform(out, Array.from(windowed))
50
+ fft.completeSpectrum(out)
51
+
52
+ // out is interleaved [re, im, re, im, ...]; only the first half is
53
+ // unique for a real input (the rest mirrors it) — bin i's frequency is i * sampleRate / fftSize.
54
+ const bins = fftSize / 2
55
+ const magnitudes = new Float32Array(bins)
56
+ for (let i = 0; i < bins; i++) {
57
+ const re = out[i * 2]!
58
+ const im = out[i * 2 + 1]!
59
+ magnitudes[i] = Math.sqrt(re * re + im * im)
60
+ }
61
+
62
+ const edges = bucketEdges(config)
63
+ const buckets = new Array<number>(bucketCount).fill(0)
64
+ const binHz = sampleRate / fftSize
65
+
66
+ for (let b = 0; b < bucketCount; b++) {
67
+ const loBin = Math.max(0, Math.floor(edges[b]! / binHz))
68
+ const hiBin = Math.min(bins - 1, Math.ceil(edges[b + 1]! / binHz))
69
+ let sum = 0
70
+ let count = 0
71
+ for (let i = loBin; i <= hiBin; i++) {
72
+ sum += magnitudes[i]!
73
+ count++
74
+ }
75
+ const avg = count > 0 ? sum / count : 0
76
+ // dBFS-ish: 20*log10(magnitude). A genuinely empty bin range (avg=0)
77
+ // would be -Infinity — floor it at a large-but-finite negative
78
+ // instead; the adaptive floor tracker (mic/index.ts) treats this
79
+ // the same as any other very quiet reading.
80
+ const db = avg > 0 ? 20 * Math.log10(avg) : -120
81
+
82
+ // Octave-tilt gain compensation: real audio carries far more energy
83
+ // in bass than treble (spectral tilt), so without this the low
84
+ // buckets visually dominate regardless of what's actually being
85
+ // said. Boost grows with how many octaves this bucket's center
86
+ // frequency sits above minFreqHz.
87
+ const center = (edges[b]! + edges[b + 1]!) / 2
88
+ const octavesAboveFloor = Math.max(0, Math.log2(center / config.minFreqHz))
89
+ buckets[b] = db + octavesAboveFloor * config.gainPerOctaveDb
90
+ }
91
+
92
+ return buckets
93
+ }
@@ -0,0 +1,139 @@
1
+ import { Capture } from "./capture"
2
+ import { computeBuckets } from "./fft"
3
+ import { renderBraille } from "./visualizer"
4
+ import { defaultVisualizerConfig, type VisualizerConfig } from "./config"
5
+
6
+ export type { VisualizerConfig } from "./config"
7
+ export { defaultVisualizerConfig } from "./config"
8
+
9
+ type MicOpts = {
10
+ config?: Partial<VisualizerConfig>
11
+ }
12
+
13
+ /** Noise gate with a smooth knee — see gateThreshold/gateKneeWidth in config.ts. */
14
+ function applyGate(level: number, config: VisualizerConfig): number {
15
+ const { gateThreshold, gateKneeWidth } = config
16
+ if (level <= gateThreshold) return 0
17
+ if (level >= gateThreshold + gateKneeWidth) return level
18
+ const t = (level - gateThreshold) / gateKneeWidth
19
+ return level * t
20
+ }
21
+
22
+ /**
23
+ * Mic — the mic capture + visualizer service. Owns its own tick loop
24
+ * (setInterval, framework-agnostic — runs the same whether or not any UI
25
+ * is mounted, usable from the CLI headless too), so useMic() only ever
26
+ * has to re-read a plain value on the same schedule the UI already
27
+ * re-renders on.
28
+ *
29
+ * Per-bucket noise floor tracking, level smoothing, and decay are all
30
+ * frame-to-frame state and live here — fft.ts and visualizer.ts stay pure
31
+ * functions of whatever they're given.
32
+ */
33
+ export function Mic(opts: MicOpts = {}) {
34
+ const config: VisualizerConfig = { ...defaultVisualizerConfig, ...opts.config }
35
+ const capture = Capture({ sampleRate: config.sampleRate, windowSamples: config.fftSize })
36
+
37
+ // Per-bucket adaptive noise floor (in dB) — "silence" for THIS bucket,
38
+ // on THIS machine, right now. Never a fixed number: room noise and mic
39
+ // self-noise vary per environment, and even within a session (a fan
40
+ // kicking on) — a real noise gate calibrates to the room, it doesn't
41
+ // assume one. Snapped directly to each bucket's first real reading
42
+ // (floorInitialized) rather than starting from an arbitrary guess —
43
+ // starting miles off (e.g. -100dB when real quiet signal reads -20dB)
44
+ // means the floor is playing catch-up for a long time, during which
45
+ // the display would read as maxed-out regardless of actual loudness.
46
+ // Raw per-tick dB, averaged (EMA) before floor tracking ever sees it —
47
+ // a single FFT frame has real statistical variance (that's how
48
+ // FFT-of-noise behaves, not a bug), so without this the floor tracker
49
+ // itself chases per-frame noise instead of converging to a stable
50
+ // baseline, and no gate threshold can then cleanly separate real quiet
51
+ // signal from noise jitter.
52
+ let dbAvg = new Array<number>(config.bucketCount).fill(0)
53
+ let dbAvgInitialized = new Array<boolean>(config.bucketCount).fill(false)
54
+ let floor = new Array<number>(config.bucketCount).fill(0)
55
+ let floorInitialized = new Array<boolean>(config.bucketCount).fill(false)
56
+ let levels = new Array<number>(config.bucketCount).fill(0)
57
+ let waveform = renderBraille(levels)
58
+ let timer: ReturnType<typeof setInterval> | null = null
59
+
60
+ function tick(): void {
61
+ const window = capture.currentWindow()
62
+ const raw = computeBuckets(window, config)
63
+
64
+ for (let i = 0; i < raw.length; i++) {
65
+ const rawDb = raw[i]!
66
+
67
+ if (!dbAvgInitialized[i]) {
68
+ dbAvg[i] = rawDb
69
+ dbAvgInitialized[i] = true
70
+ } else {
71
+ dbAvg[i] = dbAvg[i]! + (rawDb - dbAvg[i]!) * (1 - config.magnitudeSmoothing)
72
+ }
73
+ const db = dbAvg[i]!
74
+
75
+ if (!floorInitialized[i]) {
76
+ floor[i] = db
77
+ floorInitialized[i] = true
78
+ } else {
79
+ // Floor chases the current reading: falls fast (quieter
80
+ // conditions get picked up quickly), rises slowly (a
81
+ // sustained loud moment doesn't get treated as "the new
82
+ // normal" too fast, which would numb the display to
83
+ // genuinely loud speech).
84
+ const rate = db < floor[i]! ? config.floorFallRate : config.floorRiseRate
85
+ floor[i] = floor[i]! + (db - floor[i]!) * rate
86
+ }
87
+
88
+ const rawTarget = Math.min(1, Math.max(0, (db - floor[i]!) / config.headroomDb))
89
+ const target = applyGate(rawTarget, config)
90
+ const prev = levels[i]!
91
+
92
+ // Rise immediately toward louder input (smoothing blends in),
93
+ // decay only (never jump down faster than decayPerTick) when
94
+ // quieter — keeps trailing silence from cutting bars off
95
+ // instantly between words.
96
+ levels[i] = target >= prev
97
+ ? prev + (target - prev) * (1 - config.smoothing)
98
+ : Math.max(target, prev * config.decayPerTick)
99
+ }
100
+
101
+ waveform = renderBraille(levels)
102
+ }
103
+
104
+ return {
105
+ isActive(): boolean {
106
+ return capture.isCapturing()
107
+ },
108
+
109
+ /** Pre-rendered braille waveform, ready to display — recomputed every config.tickMs while active. */
110
+ waveform(): string {
111
+ return waveform
112
+ },
113
+
114
+ async start(): Promise<void> {
115
+ await capture.start()
116
+ dbAvg = new Array(config.bucketCount).fill(0)
117
+ dbAvgInitialized = new Array(config.bucketCount).fill(false)
118
+ floor = new Array(config.bucketCount).fill(0)
119
+ floorInitialized = new Array(config.bucketCount).fill(false)
120
+ levels = new Array(config.bucketCount).fill(0)
121
+ waveform = renderBraille(levels)
122
+ timer = setInterval(tick, config.tickMs)
123
+ },
124
+
125
+ /** Stops capture and returns the recorded audio, ready for cloud.client.stt.transcribe(). */
126
+ async stop(): Promise<Blob> {
127
+ if (timer) {
128
+ clearInterval(timer)
129
+ timer = null
130
+ }
131
+ const blob = await capture.stop()
132
+ levels = new Array(config.bucketCount).fill(0)
133
+ waveform = renderBraille(levels)
134
+ return blob
135
+ },
136
+ }
137
+ }
138
+
139
+ export type MicT = ReturnType<typeof Mic>
@@ -0,0 +1,46 @@
1
+ /**
2
+ * visualizer — pure rendering only. Takes bucket levels already resolved
3
+ * to 0..1 (see mic/index.ts, which owns dB->level mapping against the
4
+ * live adaptive noise floor) and returns the braille string to display.
5
+ * Smoothing/decay/floor-tracking are NOT done here — they're
6
+ * frame-to-frame state, owned by the ticker, not a stateless render fn.
7
+ *
8
+ * Freq = x-axis (one bucket per braille half-cell, left-to-right), amp =
9
+ * y-axis (bottom-anchored dot fill within that half). A braille cell is a
10
+ * 2x4 dot grid — treating its left and right columns as two INDEPENDENT
11
+ * buckets (not one glyph picked from a "looks denser" list) doubles
12
+ * horizontal resolution for the same character width and gives a real
13
+ * bottom-anchored bar per bucket, 4 height levels each.
14
+ *
15
+ * Unicode braille bit layout (0x2800 base):
16
+ * dot1 dot4 bit0 bit3
17
+ * dot2 dot5 bit1 bit4
18
+ * dot3 dot6 bit2 bit5
19
+ * dot7 dot8 bit6 bit7
20
+ * Bottom-anchored fill order, left column: dot7 -> dot3 -> dot2 -> dot1.
21
+ * Right column: dot8 -> dot6 -> dot5 -> dot4.
22
+ */
23
+ const BRAILLE_BASE = 0x2800
24
+ const LEFT_DOTS = [0b1000000, 0b0000100, 0b0000010, 0b0000001] // dot7, dot3, dot2, dot1 — bottom to top
25
+ const RIGHT_DOTS = [0b10000000, 0b00100000, 0b00010000, 0b00001000] // dot8, dot6, dot5, dot4 — bottom to top
26
+
27
+ /** 0..4 filled dots (bottom-up) for one column, from a clamped 0..1 amplitude level. */
28
+ function columnBits(level: number, dots: number[]): number {
29
+ const filled = Math.round(Math.min(1, Math.max(0, level)) * dots.length)
30
+ let bits = 0
31
+ for (let i = 0; i < filled; i++) bits |= dots[i]!
32
+ return bits
33
+ }
34
+
35
+ /** bucketLevels are already 0..1 (clamped), one entry per FFT bucket — see mic/index.ts's floor-relative mapping. */
36
+ export function renderBraille(bucketLevels: number[]): string {
37
+ let out = ""
38
+ for (let i = 0; i < bucketLevels.length; i += 2) {
39
+ const leftLevel = bucketLevels[i]!
40
+ const rightLevel = bucketLevels[i + 1] ?? 0
41
+
42
+ const bits = columnBits(leftLevel, LEFT_DOTS) | columnBits(rightLevel, RIGHT_DOTS)
43
+ out += String.fromCodePoint(BRAILLE_BASE + bits)
44
+ }
45
+ return out
46
+ }
@@ -0,0 +1,122 @@
1
+ import type { CatalogModel } from "./types"
2
+
3
+ /**
4
+ * The models Axon offers for local inference.
5
+ *
6
+ * Curated deliberately, because **Ollama has no search API**. There is no
7
+ * `/api/search`, the registry's `/v2/.../tags/list` catalog endpoints answer
8
+ * 404, and ollama.com serves HTML only. The alternatives were scraping a web
9
+ * page — a silent breakage the first time the markup moves — or offering
10
+ * nothing.
11
+ *
12
+ * So this is the shelf, and `Registry.resolve()` is the counter: any name a
13
+ * user types is verified against the live registry and pulled, listed here or
14
+ * not. A palette gets a real list; power users are not fenced in.
15
+ *
16
+ * Sizes are absent on purpose. What a variant IS belongs here; how many bytes
17
+ * that currently amounts to belongs to the registry, which is asked at display
18
+ * time. Recording a size here would be a number that silently goes stale.
19
+ */
20
+ export const CATALOG: CatalogModel[] = [
21
+ {
22
+ name: "gemma3:1b",
23
+ model: "gemma3",
24
+ tag: "1b",
25
+ description: "Google's smallest Gemma 3 — fast enough for a laptop CPU, capable enough for simple tasks.",
26
+ parameters: "1B",
27
+ capabilities: ["chat"],
28
+ },
29
+ {
30
+ name: "gemma3:4b",
31
+ model: "gemma3",
32
+ tag: "4b",
33
+ description: "Gemma 3 with vision. The best general default on consumer hardware.",
34
+ parameters: "4B",
35
+ capabilities: ["chat", "vision"],
36
+ },
37
+ {
38
+ name: "gemma3:12b",
39
+ model: "gemma3",
40
+ tag: "12b",
41
+ description: "Gemma 3 at a size that rewards a real GPU — noticeably stronger reasoning.",
42
+ parameters: "12B",
43
+ capabilities: ["chat", "vision"],
44
+ },
45
+ {
46
+ name: "qwen3:4b",
47
+ model: "qwen3",
48
+ tag: "4b",
49
+ description: "Qwen 3 with tool calling and thinking — the smallest model here that can drive an agent.",
50
+ parameters: "4B",
51
+ capabilities: ["chat", "tools", "thinking"],
52
+ },
53
+ {
54
+ name: "qwen3:8b",
55
+ model: "qwen3",
56
+ tag: "8b",
57
+ description: "Qwen 3 at 8B. Strong tool use for its size; a good agent default with a GPU.",
58
+ parameters: "8B",
59
+ capabilities: ["chat", "tools", "thinking"],
60
+ },
61
+ {
62
+ name: "qwen3:14b",
63
+ model: "qwen3",
64
+ tag: "14b",
65
+ description: "Qwen 3 at 14B — the most capable local agent model most machines can hold.",
66
+ parameters: "14B",
67
+ capabilities: ["chat", "tools", "thinking"],
68
+ },
69
+ {
70
+ name: "qwen2.5-coder:7b",
71
+ model: "qwen2.5-coder",
72
+ tag: "7b",
73
+ description: "Code-specialised Qwen 2.5. Fill-in-the-middle and repository-scale context.",
74
+ parameters: "7B",
75
+ capabilities: ["chat", "tools"],
76
+ },
77
+ {
78
+ name: "llama3.2:3b",
79
+ model: "llama3.2",
80
+ tag: "3b",
81
+ description: "Meta's compact Llama 3.2 — broad general knowledge at a small footprint.",
82
+ parameters: "3B",
83
+ capabilities: ["chat", "tools"],
84
+ },
85
+ {
86
+ name: "mistral:7b",
87
+ model: "mistral",
88
+ tag: "7b",
89
+ description: "Mistral 7B. A dependable general-purpose model with a permissive licence.",
90
+ parameters: "7B",
91
+ capabilities: ["chat", "tools"],
92
+ },
93
+ {
94
+ name: "phi4:14b",
95
+ model: "phi4",
96
+ tag: "14b",
97
+ description: "Microsoft's Phi-4 — punches well above its parameter count on reasoning.",
98
+ parameters: "14B",
99
+ capabilities: ["chat"],
100
+ },
101
+ {
102
+ name: "deepseek-r1:7b",
103
+ model: "deepseek-r1",
104
+ tag: "7b",
105
+ description: "Reasoning-first model that shows its working before answering.",
106
+ parameters: "7B",
107
+ capabilities: ["chat", "thinking"],
108
+ },
109
+ {
110
+ name: "nomic-embed-text:latest",
111
+ model: "nomic-embed-text",
112
+ tag: "latest",
113
+ description: "Embeddings only — for retrieval and memory, not conversation.",
114
+ parameters: "137M",
115
+ capabilities: ["embedding"],
116
+ },
117
+ ]
118
+
119
+ /** Every distinct model family on the shelf, in catalog order. */
120
+ export function families(): string[] {
121
+ return [...new Set(CATALOG.map(entry => entry.model))]
122
+ }
@@ -0,0 +1,124 @@
1
+ import { err } from "@arcforge/err"
2
+
3
+ type HttpOpts = {
4
+ /** Daemon base URL, e.g. http://localhost:11434. */
5
+ host: string
6
+ }
7
+
8
+ /**
9
+ * Http — every request to the local Ollama daemon.
10
+ *
11
+ * The daemon is optional infrastructure: a user who has never installed Ollama
12
+ * is in a perfectly ordinary state, so "not reachable" must arrive as a
13
+ * structured OLLAMA_UNAVAILABLE rather than a raw fetch TypeError that reads
14
+ * like a bug. Everything else — a 404 for an unknown model, a 500 — surfaces
15
+ * with the daemon's own message, because it is the daemon's answer and it is
16
+ * usually the right thing to show.
17
+ */
18
+ export function Http(opts: HttpOpts) {
19
+ const host = opts.host.replace(/\/+$/, "")
20
+
21
+ /**
22
+ * `body` is the VALUE to send, not an encoded string — this owns the
23
+ * JSON encoding so no caller can send an unencoded object by mistake.
24
+ * Its presence also selects the method: Ollama's read endpoints are GET,
25
+ * everything else POSTs a payload.
26
+ */
27
+ async function send(path: string, body?: unknown): Promise<Response> {
28
+ const url = `${host}${path}`
29
+
30
+ let response: Response
31
+ try {
32
+ response = await fetch(url, body === undefined
33
+ ? {}
34
+ : {
35
+ method: "POST",
36
+ body: JSON.stringify(body),
37
+ headers: { "content-type": "application/json" },
38
+ })
39
+ } catch (cause) {
40
+ // A connection that cannot be opened is the ONE failure that is not
41
+ // a fault: Ollama is not installed, or not running.
42
+ throw err("OLLAMA_UNAVAILABLE", {
43
+ detail: `no Ollama daemon at ${host} — start it with \`ollama serve\`, or install it from https://ollama.com`,
44
+ context: { host: host },
45
+ cause: cause,
46
+ })
47
+ }
48
+
49
+ if (!response.ok) {
50
+ const body = await response.text().catch(() => "")
51
+ const message = parseErrorBody(body) ?? `${response.status} ${response.statusText}`
52
+ throw err("OLLAMA_REQUEST_FAILED", {
53
+ detail: `${path}: ${message}`,
54
+ context: { host: host, path: path, status: response.status },
55
+ })
56
+ }
57
+
58
+ return response
59
+ }
60
+
61
+ return {
62
+ host: host,
63
+
64
+ /** A JSON request/response round trip. */
65
+ async json<T>(path: string, body?: unknown): Promise<T> {
66
+ const response = await send(path, body)
67
+ return await response.json() as T
68
+ },
69
+
70
+ /**
71
+ * An NDJSON stream — one JSON object per line, which is how Ollama
72
+ * reports long operations like a pull.
73
+ *
74
+ * Lines are reassembled across chunk boundaries: a 4 MB download emits
75
+ * progress faster than the reader drains it, so a naive split drops the
76
+ * partial line at the end of every chunk.
77
+ */
78
+ async *stream<T>(path: string, body: unknown): AsyncGenerator<T> {
79
+ const response = await send(path, body)
80
+ if (!response.body) {
81
+ throw err("OLLAMA_REQUEST_FAILED", { detail: `${path}: response carried no body`, context: { path: path } })
82
+ }
83
+
84
+ const reader = response.body.getReader()
85
+ const decoder = new TextDecoder()
86
+ let carry = ""
87
+
88
+ try {
89
+ while (true) {
90
+ const { value, done } = await reader.read()
91
+ if (done) break
92
+
93
+ carry += decoder.decode(value, { stream: true })
94
+ const lines = carry.split("\n")
95
+ carry = lines.pop() ?? ""
96
+
97
+ for (const line of lines) {
98
+ if (line.trim()) yield JSON.parse(line) as T
99
+ }
100
+ }
101
+ if (carry.trim()) yield JSON.parse(carry) as T
102
+ } finally {
103
+ // A consumer that breaks out of the loop early (a cancelled
104
+ // download) must not leave the socket held open.
105
+ await reader.cancel().catch(() => {})
106
+ }
107
+ },
108
+ }
109
+ }
110
+
111
+ export type HttpT = ReturnType<typeof Http>
112
+
113
+ /** Ollama reports failures as `{"error": "..."}` — prefer that over a bare status line. */
114
+ function parseErrorBody(body: string): string | null {
115
+ if (!body.trim()) return null
116
+ try {
117
+ const parsed = JSON.parse(body) as { error?: unknown }
118
+ return typeof parsed.error === "string" ? parsed.error : null
119
+ } catch {
120
+ // Not JSON — the raw body is still better than nothing, trimmed so a
121
+ // stray HTML error page cannot flood a terminal.
122
+ return body.trim().slice(0, 200)
123
+ }
124
+ }
@@ -0,0 +1,13 @@
1
+ // ollama — local models, programmatically.
2
+ // Ollama() is the module's single entry point.
3
+
4
+ export { Ollama, type OllamaT } from "./ollama"
5
+ export { CATALOG } from "./catalog"
6
+ export type {
7
+ Capability,
8
+ CatalogModel,
9
+ LocalModel,
10
+ OllamaStatus,
11
+ PullProgress,
12
+ RunningModel,
13
+ } from "./types"