@arcforge/types 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.
package/src/inference.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { EngineEffort } from "./engine"
2
+
1
3
  /**
2
4
  * Inference requirements and supply — the contract between what a cognet
3
5
  * NEEDS and what a user HAS.
@@ -43,19 +45,127 @@ export type EngineType = "generate" | "transform" | "stream"
43
45
  * here only has to be specific enough for a resolver to tell two models
44
46
  * apart.
45
47
  *
46
- * "score", "vector" and "depth" are output shapes rather than modalities in
47
- * the strict sense. They earn their place because a cognet asking for a VAD
48
- * and a cognet asking for speech-to-text both say `in: "audio"`, and the
49
- * output is the only thing that separates them.
48
+ * "score", "vector", "depth" and "detections" are output shapes rather than
49
+ * modalities in the strict sense. They earn their place because a cognet
50
+ * asking for a VAD and a cognet asking for speech-to-text both say
51
+ * `in: "audio"`, and the output is the only thing that separates them — and
52
+ * an image encoder and an object detector both take `in: "image"`.
53
+ */
54
+ export const MODALITIES = [
55
+ "text",
56
+ "image",
57
+ "audio",
58
+ "video",
59
+ "vector",
60
+ "score",
61
+ "depth",
62
+ /** Located things: a box, a label and a confidence each. */
63
+ "detections",
64
+ /**
65
+ * A descriptor per patch of an image, on the grid the encoder tiles it
66
+ * with — not one pooled `vector`. What a perception stack stacks with its
67
+ * other fields; an encoder that can only pool cannot fill a role asking
68
+ * for this.
69
+ */
70
+ "features",
71
+ /** Regions of an image, one per prompt point, each with how sure the model is of it. */
72
+ "masks",
73
+ ] as const
74
+
75
+ /**
76
+ * One member of `MODALITIES`. The list is a value so that anything checking
77
+ * stored or declared metadata checks against THIS list — a second copy is
78
+ * how a new modality ends up refused as invalid by a reader nobody updated.
79
+ */
80
+ export type Modality = typeof MODALITIES[number]
81
+
82
+ /**
83
+ * An image, as it crosses to an engine.
84
+ *
85
+ * Raw pixels rather than an encoded file, because what a perception stack
86
+ * holds is pixels — it decoded the frame to look at it — and a crop of one is
87
+ * pixels too. Re-encoding a crop to JPEG to hand it to a model would spend
88
+ * time to lose information.
89
+ *
90
+ * `data` is base64 because the call crosses a JSON socket, where a typed
91
+ * array arrives as an index-keyed object nine hundred entries long.
92
+ */
93
+ export type ImageInput = {
94
+ kind: "image"
95
+ width: number
96
+ height: number
97
+ /** RGB only. A channel count is stated rather than inferred so a mismatch fails at the seam. */
98
+ channels: 3
99
+ /** Row-major RGB bytes, base64. */
100
+ data: string
101
+ }
102
+
103
+ /**
104
+ * A tensor, as it comes back from an engine.
105
+ *
106
+ * Binary, base64, for the reason `ImageInput` is: a feature grid is ~900k
107
+ * numbers, which as a JSON array is ~9MB of text to write and parse per call
108
+ * and as float32 bytes is 3.5MB. Little-endian, row-major, `dims` outermost
109
+ * first.
110
+ */
111
+ export type TensorOutput = {
112
+ kind: "tensor"
113
+ dims: number[]
114
+ dtype: "float32" | "uint8"
115
+ /** Row-major bytes, little-endian, base64. */
116
+ data: string
117
+ }
118
+
119
+ /**
120
+ * What a `features` engine returns for an `ImageInput`: one descriptor per
121
+ * patch, `[rows, cols, dim]`, at the image's OWN size — never resized or
122
+ * cropped to what the encoder was trained at. The caller chose the size
123
+ * because the grid it gets back has to line up with everything else it
124
+ * measures; an adapter that cropped to 224px would hand back descriptors of
125
+ * a picture nobody asked about.
126
+ *
127
+ * `patch` is how many image pixels one cell covers, so the caller can place
128
+ * the grid without knowing which model filled the role. The image's sides
129
+ * must be multiples of it; an image that is not is refused, not padded.
130
+ */
131
+ export type FeatureGrid = {
132
+ kind: "features"
133
+ patch: number
134
+ grid: TensorOutput
135
+ }
136
+
137
+ /** What a `masks` engine takes: an image, and the points to find a region at. */
138
+ export type SegmentInput = {
139
+ kind: "segment"
140
+ image: ImageInput
141
+ /** In the image's own pixels. Each yields one mask. */
142
+ points: Array<{ x: number; y: number }>
143
+ }
144
+
145
+ /**
146
+ * What a `masks` engine returns: one region per point, in point order. Each
147
+ * mask is `[rows, cols]` of 0/1 covering the WHOLE image (coarser than it —
148
+ * scale by width/cols), with `score` the model's own estimate of its
149
+ * quality, 0..1.
150
+ */
151
+ export type Masks = {
152
+ kind: "masks"
153
+ masks: Array<{ mask: TensorOutput; score: number }>
154
+ }
155
+
156
+ /**
157
+ * What a `depth` engine returns for an `ImageInput`: how near each part of
158
+ * the picture is, `[rows, cols]` float32 covering the WHOLE image (coarser
159
+ * than it — scale by width/cols).
160
+ *
161
+ * RELATIVE and INVERSE, as a monocular model gives it: a larger number is
162
+ * nearer, there is no unit, and the scale of one answer says nothing about
163
+ * the scale of the next. Ordering within one answer is all it claims.
50
164
  */
51
- export type Modality =
52
- | "text"
53
- | "image"
54
- | "audio"
55
- | "video"
56
- | "vector"
57
- | "score"
58
- | "depth"
165
+ export type DepthMap = {
166
+ kind: "depth"
167
+ depth: TensorOutput
168
+ }
59
169
 
60
170
  /**
61
171
  * One named engine a cognet requires, as declared in `cognet.config.ts`.
@@ -98,6 +208,13 @@ export type EngineRequirement = {
98
208
  */
99
209
  context?: number
100
210
 
211
+ /**
212
+ * The models that may fill it, by registry id, in order of preference —
213
+ * the first one the catalogue offers wins. Absent: any model that fits.
214
+ * Matched against a capability's own id, exactly, on any route.
215
+ */
216
+ model?: readonly string[]
217
+
101
218
  /** The reply must be parseable as structured output (AIR blocks, JSON mode). */
102
219
  structured?: boolean
103
220
 
@@ -220,6 +337,8 @@ export type ResolvedEngineFacts = {
220
337
  }
221
338
 
222
339
  export type EngineBinding = {
340
+ /** Reasoning effort reported by the live driver; absent when unknown or inapplicable. */
341
+ effort?: EngineEffort
223
342
  role: string
224
343
  requirement: EngineRequirement
225
344
  capability: EngineCapability
@@ -264,3 +383,65 @@ export type EngineResolution = {
264
383
  /** Unfilled roles that were NOT optional — non-empty means the agent cannot run. */
265
384
  missing: EngineUnmet[]
266
385
  }
386
+
387
+ /** What a model takes in, gives back, and how it is called — read off its task. */
388
+ export type ModelShape = {
389
+ type: EngineType
390
+ in: Modality[]
391
+ out: Modality[]
392
+ }
393
+
394
+ const TEXT_GENERATION: ModelShape = { type: "generate", in: ["text"], out: ["text"] }
395
+
396
+ /**
397
+ * Hugging Face task tags → model shape. THE one table.
398
+ *
399
+ * It lived twice — an exact-match table in @arcforge/engines and a substring
400
+ * matcher in axond's catalogue — and the two disagreed: the substring version
401
+ * read `image-feature-extraction` as `feature-extraction` and advertised
402
+ * DINOv2 as a TEXT encoder, so no role asking for image → vector could ever
403
+ * resolve to it. Two places that interpret a vocabulary are two chances to
404
+ * interpret it differently.
405
+ *
406
+ * Exact match on purpose. An unknown tag has NO shape — never a guess — so a
407
+ * reader can tell "nobody wrote this down" from a confident lie.
408
+ */
409
+ const PIPELINE_TAGS: Record<string, ModelShape> = {
410
+ "text-generation": TEXT_GENERATION,
411
+ "text2text-generation": TEXT_GENERATION,
412
+ "image-text-to-text": { type: "generate", in: ["text", "image"], out: ["text"] },
413
+ "audio-text-to-text": { type: "generate", in: ["text", "audio"], out: ["text"] },
414
+ "text-to-speech": { type: "generate", in: ["text"], out: ["audio"] },
415
+ "text-to-audio": { type: "generate", in: ["text"], out: ["audio"] },
416
+ "text-to-image": { type: "transform", in: ["text"], out: ["image"] },
417
+ "text-to-video": { type: "transform", in: ["text"], out: ["video"] },
418
+ "automatic-speech-recognition": { type: "transform", in: ["audio"], out: ["text"] },
419
+ "image-to-text": { type: "transform", in: ["image"], out: ["text"] },
420
+ "feature-extraction": { type: "transform", in: ["text"], out: ["vector"] },
421
+ "sentence-similarity": { type: "transform", in: ["text"], out: ["vector"] },
422
+ "image-feature-extraction": { type: "transform", in: ["image"], out: ["vector"] },
423
+ "depth-estimation": { type: "transform", in: ["image"], out: ["depth"] },
424
+ "image-classification": { type: "transform", in: ["image"], out: ["text"] },
425
+ "object-detection": { type: "transform", in: ["image"], out: ["detections"] },
426
+ "zero-shot-object-detection": { type: "transform", in: ["image", "text"], out: ["detections"] },
427
+ "image-segmentation": { type: "transform", in: ["image"], out: ["image"] },
428
+ "text-classification": { type: "transform", in: ["text"], out: ["text"] },
429
+ "token-classification": { type: "transform", in: ["text"], out: ["text"] },
430
+ "audio-classification": { type: "transform", in: ["audio"], out: ["text"] },
431
+ "voice-activity-detection": { type: "stream", in: ["audio"], out: ["score"] },
432
+ }
433
+
434
+ /** A task tag's shape, or null for a tag nobody has described. */
435
+ export function shapeOfPipelineTag(tag: string | undefined): ModelShape | null {
436
+ if (!tag) return null
437
+ return PIPELINE_TAGS[tag.toLowerCase()] ?? null
438
+ }
439
+
440
+ /** Supervisor-side model selection; inventory may change while an agent runs. */
441
+ export type EngineSelection = {
442
+ readonly primary: string | null
443
+ has(role: string): boolean
444
+ get(role: string): { binding: EngineBinding }
445
+ refresh(provider: string): Promise<void>
446
+ select(model: string): EngineCapability | null | Promise<EngineCapability | null>
447
+ }
package/src/kernel/abi.ts CHANGED
@@ -7,6 +7,7 @@ import type { CognetEventMap } from "../session/events/cognet"
7
7
  import type { AxonScope } from "../scope"
8
8
  import type { EngineRequirements, EngineType, Modality } from "../inference"
9
9
  import type { CapsuleScope } from "../capsule-scope"
10
+ import type { Manifest, Presence } from "../body/body"
10
11
 
11
12
  /**
12
13
  * The current kernel ABI contract version. Program definitions declare the
@@ -210,6 +211,46 @@ export type KernelKnowledge = {
210
211
  remove(name: string): Promise<void>
211
212
  }
212
213
 
214
+ /**
215
+ * Where one of the cognet's databases lives — handed to the database's
216
+ * opener untouched.
217
+ *
218
+ * A union so each place carries exactly what reaching it needs. `sqlite` is
219
+ * a file in the agent's data; `memory` holds nothing past the process;
220
+ * `remote` is a service the brain reaches over the network.
221
+ */
222
+ export type MemoryConnection =
223
+ | { type: "memory" }
224
+ | { type: "sqlite"; path: string }
225
+ | { type: "remote"; url: string; token?: string }
226
+
227
+ /**
228
+ * Long-term memory — the cognet's own databases. They are durable, and the
229
+ * mind is the only thing that can read them.
230
+ *
231
+ * A peer of `store` and `knowledge`, under a third doctrine:
232
+ * - `store`'s kv is a CACHE over the log: deleting it is always safe.
233
+ * - `knowledge` is human-readable material, published with the agent.
234
+ * - `memory` is what the mind has learned. It is not rebuildable from any
235
+ * log, so losing it is losing what was learned, and it is never published.
236
+ *
237
+ * The kernel says WHERE a database lives and nothing else. Its format, its
238
+ * queries, and when it is read or written are memory policy, which belongs to
239
+ * the cognet (see RETRIEVAL IS COGNITION, on KernelKnowledge). That is why
240
+ * this hands over a connection rather than a database: the cognet bundles its
241
+ * own engine and opens it there.
242
+ */
243
+ export type KernelMemory = {
244
+ /**
245
+ * Where the database `name` lives, for this cognet. One name, one
246
+ * database. A NAME, never a path: it is a single lowercase identifier,
247
+ * and anything else throws MEMORY_NAME_INVALID.
248
+ *
249
+ * Synchronous and does no IO: it resolves a place. The opener creates it.
250
+ */
251
+ connect(name: string): MemoryConnection
252
+ }
253
+
213
254
  /**
214
255
  * The outcome of one capsule run — success and failure are both ordinary
215
256
  * values here, never a rejection. `stdout` is every console.* call this
@@ -440,6 +481,46 @@ export type KernelEngines<Requirements extends EngineRequirements = EngineRequir
440
481
  has(role: string): boolean
441
482
  }
442
483
 
484
+ /** One use, as it stands: whether something fills it, and what that reports of itself. */
485
+ export type ServiceState = {
486
+ available: boolean
487
+ /** What the granted provider's `describe()` reports — null while unavailable. */
488
+ describe: Readonly<Record<string, unknown>> | null
489
+ }
490
+
491
+ /**
492
+ * The services a cognet uses, by the names it gave them in `uses:`.
493
+ *
494
+ * Addressed by name, never by provider: the cognet asks a use for a method of
495
+ * its interface, and the agent — on its own side of the boundary — decides
496
+ * what answers, what it costs and what it may reach. Nothing here names a
497
+ * provider, a credential or a model.
498
+ *
499
+ * Every call carries its arguments as one object, keyed by the method's
500
+ * parameter names — the same shape in every language. A session is addressed
501
+ * by the id `open` answers with, and a handle by its own id, so every verb
502
+ * here is a value in and a value out: what lets the same surface cross to a
503
+ * Rust or Python system unchanged.
504
+ */
505
+ export type KernelServices = {
506
+ /** Every declared use, as it stands now. */
507
+ state(): Readonly<Record<string, ServiceState>>
508
+ /** A call: one answer. Throws SERVICE_UNAVAILABLE when nothing fills the use. */
509
+ call(use: string, method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal): Promise<unknown>
510
+ /** A stream: answers as they come, until it ends or `signal` stops it. */
511
+ stream(use: string, method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal): AsyncIterable<unknown>
512
+ /** Opens a session; answers with its id. */
513
+ open(use: string, method: string): Promise<string>
514
+ /** One push into an open session, answered in order. */
515
+ push(session: string, value: unknown): Promise<unknown>
516
+ /** Starts a session again, as if just opened. */
517
+ reset(session: string): Promise<void>
518
+ /** Ends a session. */
519
+ close(session: string): Promise<void>
520
+ /** Lets go of a handle a provider keeps. */
521
+ release(handle: string): Promise<void>
522
+ }
523
+
443
524
  export type KernelAbi<Requirements extends EngineRequirements = EngineRequirements> = {
444
525
  /**
445
526
  * Emit a fact to the world — text, audio, visual, or a declared field
@@ -502,6 +583,25 @@ export type KernelAbi<Requirements extends EngineRequirements = EngineRequiremen
502
583
  */
503
584
  scope(): AxonScope
504
585
 
586
+ /**
587
+ * The body this agent wears, as the body described itself — its frames,
588
+ * senses, controls and skills (`body/body.ts`) — or null while it wears
589
+ * none. The kernel reports what the body said; the cognet decides what to
590
+ * make of it. Read it whenever it matters: a body that changes (a limb
591
+ * lost, a tool picked up) describes itself again, and this is always the
592
+ * newest.
593
+ */
594
+ body(): Manifest | null
595
+
596
+ /**
597
+ * Whether the worn body is this mind's to move now: `embodied`, or
598
+ * `held` — an emergency stop, a safe mode, a rover asleep — or
599
+ * `overridden`, someone else driving it, each with why. Senses go on
600
+ * either way; commands are not applied. Null while it wears none, or
601
+ * before the body has said.
602
+ */
603
+ presence(): Exclude<Presence, { state: "detached" }> | null
604
+
505
605
 
506
606
  /**
507
607
  * The agent's base context, rendered — boot.md / boot.vue. Kernel-
@@ -565,6 +665,19 @@ export type KernelAbi<Requirements extends EngineRequirements = EngineRequiremen
565
665
  */
566
666
  knowledge: KernelKnowledge
567
667
 
668
+ /**
669
+ * Long-term memory — where the cognet's own databases live. See
670
+ * KernelMemory. Mediated like store and knowledge: the cognet names a
671
+ * database, the kernel owns the place.
672
+ */
673
+ memory: KernelMemory
674
+
675
+ /**
676
+ * The services this cognet declared in `uses:` — each filled, or not, by
677
+ * whatever the agent granted. See KernelServices.
678
+ */
679
+ services: KernelServices
680
+
568
681
  /**
569
682
  * Wake the brain — the mind's own rhythm, driven from inside it.
570
683
  *
@@ -579,16 +692,9 @@ export type KernelAbi<Requirements extends EngineRequirements = EngineRequiremen
579
692
  * and 60Hz cannot both be "the" tick rate.
580
693
  *
581
694
  * So the body only ever emits stimuli, and the brain decides when to
582
- * look. A cognet plugin owns the clock:
583
- *
584
- * ```ts
585
- * // plugins/clock.ts
586
- * export default definePlugin(({ hooks }) => {
587
- * hooks.on("boot", () => {
588
- * setInterval(() => void kernel.wake(), 1000 / 30)
589
- * })
590
- * })
591
- * ```
695
+ * look. The brain declares its rate — `mode: { kind: "continuous", hz }`
696
+ * in its own config — and the cognet host calls this at that rate. A
697
+ * brain with an irregular rhythm can still call it from a plugin.
592
698
  *
593
699
  * Resolves with this wake's ordinal AS SOON AS IT IS ADMITTED — never
594
700
  * when it completes. A driver that awaited completion would serialise the
@@ -667,4 +773,20 @@ export type CognetWake = {
667
773
  * is cooperative and always will be. Check it between units and return.
668
774
  */
669
775
  signal: AbortSignal
776
+ /**
777
+ * The moment this wake stands for, epoch ms. The kernel never sets it: a
778
+ * live wake is now. A replay sets the time it is replaying, so the mind's
779
+ * clock, its systems' `now` and its world's write times, follow the
780
+ * recording rather than the machine running it.
781
+ */
782
+ at?: number
783
+ /**
784
+ * The async systems whose runs land in this wake's tick, as they landed
785
+ * when it ran live. The kernel never sets it. A replay running a
786
+ * session tick for tick as it ran does: an async run lands when the
787
+ * machine finishes it, which a replay on another machine, at another
788
+ * speed, could not reproduce otherwise. Present, exactly these land —
789
+ * waited for if still running — and every other settled run waits.
790
+ */
791
+ lands?: readonly string[]
670
792
  }
@@ -1,3 +1,3 @@
1
1
  export { KERNEL_ABI_VERSION } from "./abi"
2
- export type { KernelAbi, CognetWake, CognetEngineCall, AxonRunResult, KernelStore, KernelClock, KernelKnowledge, KnowledgeEntry, KernelEngine, KernelEngines, GenerateEngine, TransformEngine, StreamEngine, EngineSession, TransformOptions } from "./abi"
2
+ export type { KernelAbi, CognetWake, CognetEngineCall, AxonRunResult, KernelStore, KernelClock, KernelKnowledge, KnowledgeEntry, KernelMemory, MemoryConnection, KernelServices, ServiceState, KernelEngine, KernelEngines, GenerateEngine, TransformEngine, StreamEngine, EngineSession, TransformOptions } from "./abi"
3
3
 
package/src/machine.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The machine network's enrollment contract, shared by the daemon that signs
3
+ * and the backend that verifies — one definition, so the two can never sign
4
+ * and check different bytes.
5
+ */
6
+
7
+ /** Which network a machine belongs to: installed Axon and a source build are kept apart. */
8
+ export type MachineDistribution = "production" | "development"
9
+
10
+ /**
11
+ * What a daemon signs to enroll its key: the key, bound to the account, the
12
+ * network and a moment. Binding the account stops a signature seen in transit
13
+ * from enrolling someone's key into another account; the moment bounds replay.
14
+ */
15
+ export function machineStatement(input: { userId: string; key: string; distribution: MachineDistribution; at: string }): string {
16
+ return `axon-machine-enroll\n${input.userId}\n${input.key}\n${input.distribution}\n${input.at}`
17
+ }
@@ -0,0 +1,63 @@
1
+ import { isConnectionProvider, type ConnectionProvider } from "./connections"
2
+
3
+ export type ProviderUsageRecord = {
4
+ id: string
5
+ provider: ConnectionProvider
6
+ source: "account" | "explicit"
7
+ model: string
8
+ outcome: "completed" | "failed" | "cancelled"
9
+ durationMs: number
10
+ tokens?: { in: number; out: number }
11
+ }
12
+ export type ProviderUsageCount = { requests: number; completed: number; failed: number; cancelled: number; inputTokens: number; outputTokens: number; measured: number }
13
+ export type ProviderUsageSummary = {
14
+ provider: ConnectionProvider
15
+ days: number
16
+ source: "account" | "explicit" | "all"
17
+ totals: ProviderUsageCount
18
+ daily: Array<ProviderUsageCount & { date: string }>
19
+ models: Array<ProviderUsageCount & { model: string; lastUsedAt: string }>
20
+ }
21
+
22
+ /** Validates the metadata-only reporting contract at external boundaries. */
23
+ export function ProviderUsageWire() {
24
+ function object(raw: unknown): Record<string, unknown> {
25
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("PROVIDER_USAGE_INVALID: expected an object")
26
+ return Object.fromEntries(Object.entries(raw))
27
+ }
28
+ function text(raw: unknown, max: number): string {
29
+ if (typeof raw !== "string" || !raw || raw.length > max) throw new Error("PROVIDER_USAGE_INVALID: invalid text")
30
+ return raw
31
+ }
32
+ function number(raw: unknown): number {
33
+ if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) throw new Error("PROVIDER_USAGE_INVALID: invalid count")
34
+ return raw
35
+ }
36
+ function count(raw: unknown): ProviderUsageCount {
37
+ const value = object(raw)
38
+ return { requests: number(value.requests), completed: number(value.completed), failed: number(value.failed), cancelled: number(value.cancelled),
39
+ inputTokens: number(value.inputTokens), outputTokens: number(value.outputTokens), measured: number(value.measured) }
40
+ }
41
+ const values = { object: object, text: text, number: number, count: count }
42
+ function record(raw: unknown): ProviderUsageRecord {
43
+ const value = values.object(raw)
44
+ const id = values.text(value.id, 36)
45
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("PROVIDER_USAGE_INVALID: invalid identifier")
46
+ if (typeof value.provider !== "string" || !isConnectionProvider(value.provider)) throw new Error("PROVIDER_USAGE_INVALID: unknown provider")
47
+ if (value.source !== "account" && value.source !== "explicit") throw new Error("PROVIDER_USAGE_INVALID: invalid credential source")
48
+ if (value.outcome !== "completed" && value.outcome !== "failed" && value.outcome !== "cancelled") throw new Error("PROVIDER_USAGE_INVALID: invalid outcome")
49
+ const tokens = value.tokens === undefined ? undefined : values.object(value.tokens)
50
+ return { id: id, provider: value.provider, source: value.source, model: values.text(value.model, 200), outcome: value.outcome,
51
+ durationMs: values.number(value.durationMs), ...(tokens ? { tokens: { in: values.number(tokens.in), out: values.number(tokens.out) } } : {}) }
52
+ }
53
+ function summary(raw: unknown): ProviderUsageSummary {
54
+ const value = values.object(raw)
55
+ if (typeof value.provider !== "string" || !isConnectionProvider(value.provider)) throw new Error("PROVIDER_USAGE_INVALID: unknown provider")
56
+ if (value.source !== "account" && value.source !== "explicit" && value.source !== "all") throw new Error("PROVIDER_USAGE_INVALID: invalid source")
57
+ if (!Array.isArray(value.daily) || !Array.isArray(value.models)) throw new Error("PROVIDER_USAGE_INVALID: missing series")
58
+ return { provider: value.provider, source: value.source, days: values.number(value.days), totals: values.count(value.totals),
59
+ daily: value.daily.map(raw => { const item = values.object(raw); return { ...values.count(item), date: values.text(item.date, 10) } }),
60
+ models: value.models.map(raw => { const item = values.object(raw); return { ...values.count(item), model: values.text(item.model, 200), lastUsedAt: values.text(item.lastUsedAt, 40) } }) }
61
+ }
62
+ return { record: record, summary: summary }
63
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The agent's side of a service: what fills a use a cognet declared.
3
+ *
4
+ * A provider is anything that implements an interface — a model on this
5
+ * machine, a hosted API, a ROS service, another agent. The KERNEL holds it,
6
+ * on the agent's side of the boundary; the cognet only ever sees the
7
+ * interface (see `KernelServices`). Its `name` is recorded in the agent's
8
+ * session with every call it answers, and never crosses to the cognet.
9
+ *
10
+ * Arguments arrive as one object keyed by the method's parameter names, and
11
+ * answers leave as plain values. A handle a provider keeps crosses as
12
+ * `{ handle, id }` with an id of the provider's own choosing; the kernel
13
+ * gives the cognet its own id for it, so a handle can never be passed to a
14
+ * use or a provider that did not make it.
15
+ */
16
+ export type ServiceProvider = {
17
+ /** Which provider this is — for the agent's record, never shown to the cognet. */
18
+ readonly name: string
19
+ /** What it reports of itself, as its interface defines. */
20
+ describe(): Readonly<Record<string, unknown>>
21
+ call(method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal): Promise<unknown>
22
+ stream(method: string, args: Readonly<Record<string, unknown>>, signal?: AbortSignal): AsyncIterable<unknown>
23
+ open(method: string): Promise<ProviderSession>
24
+ /** Lets go of a handle it keeps, by its own id. */
25
+ release(handle: string): Promise<void>
26
+ }
27
+
28
+ /** One open session of a provider's. */
29
+ export type ProviderSession = {
30
+ push(value: unknown): Promise<unknown>
31
+ reset(): Promise<void>
32
+ close(): Promise<void>
33
+ }
34
+
35
+ /**
36
+ * What the agent granted, by use — a manager whose answer can change while the
37
+ * mind runs: a provider goes down, a GPU frees up. Null is a use nothing fills.
38
+ */
39
+ export type ServiceGrants = {
40
+ granted(use: string): ServiceProvider | null
41
+ }
42
+
43
+ /**
44
+ * What the agent grants one use, in `axon.config.ts`'s `services:`.
45
+ *
46
+ * - a provider: `"anthropic:claude-sonnet-5-5"` — a route the agent's
47
+ * inference sources supply — or `"./providers/features"`, one of its own;
48
+ * - `"auto"`: the best this machine offers that implements the interface and
49
+ * meets the use's `requires` — what an absent grant means;
50
+ * - `"off"`: nothing — an optional use goes unavailable, a required one
51
+ * stops the agent from starting;
52
+ * - an object, to grant a provider (or `"auto"`) within a limit.
53
+ */
54
+ export type ServiceGrant = string | { provider?: string; limit?: ServiceLimit }
55
+
56
+ /** What a use may cost, and how often — past it, calls are refused with SERVICE_LIMIT. */
57
+ export type ServiceLimit = {
58
+ /** Calls allowed in each `per`. */
59
+ calls?: number
60
+ /** Money allowed in each `per`. */
61
+ usd?: number
62
+ per: "second" | "minute" | "hour" | "day"
63
+ }
64
+
65
+ /**
66
+ * A provider the agent writes itself — `providers/<name>.provider.ts`, its
67
+ * default export. It implements one interface: `describe()`, and each of the
68
+ * interface's methods, taking their arguments as the interface writes them.
69
+ * It runs on the agent's side of the boundary, with the machine the agent
70
+ * owns; the cognet never sees which provider answered.
71
+ */
72
+ export type ProviderDefinition = {
73
+ /** The interface it implements: `depth-relative@1`, or a cognet's own — `@cody/terry/features@1`. */
74
+ implements: string
75
+ describe(): Readonly<Record<string, unknown>>
76
+ /** Lets go of a handle it keeps, by its own id. Required of a provider whose interface returns handles. */
77
+ release?(handle: string): Promise<void>
78
+ readonly [method: string]: unknown
79
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether an entry is for a client on `channel`: addressed to it, or to no
3
+ * one. An entry addressed to another channel is another conversation — the
4
+ * telegram user's reply, a voice speaking to itself — and not this client's
5
+ * to show.
6
+ *
7
+ * The ONE rule: every client that hears a mind (a request, a connection,
8
+ * `axon -p`) answers it the same way, or two of them disagree about what the
9
+ * agent said.
10
+ */
11
+ export function addressedTo(data: unknown, channel: string): boolean {
12
+ if (!data || typeof data !== "object" || !("channel" in data)) return true
13
+ const to = data.channel
14
+ return typeof to !== "string" || to === "" || to === channel
15
+ }
@@ -47,6 +47,15 @@ export type AxonEventContext = {
47
47
  * pointer would encode information the log already contains.
48
48
  */
49
49
  spanId?: string
50
+ /**
51
+ * The seq this entry's PRODUCER stamped it with, when it was relayed from
52
+ * another process's session — an agent in a subprocess, whose supervisor
53
+ * re-stamps everything it records. The mind addressed the entry by that
54
+ * seq (a text span names one), so that is how it is found again. Entries
55
+ * only: telemetry is never addressed by seq, and this field costs bytes on
56
+ * every line that carries it.
57
+ */
58
+ origin?: number
50
59
  }
51
60
 
52
61
  /**
@@ -62,7 +71,7 @@ export type AxonEventContext = {
62
71
  * part of the wire contract is a context that gets dropped at the boundary.
63
72
  * That is not hypothetical — it is the bug this type exists to prevent.
64
73
  */
65
- export type AxonCommitContext = Partial<Pick<AxonEventContext, "runId" | "spanId">>
74
+ export type AxonCommitContext = Partial<Pick<AxonEventContext, "runId" | "spanId" | "origin">>
66
75
 
67
76
  /**
68
77
  * The envelope. `M` is a registry map (event name → payload shape);
@@ -32,7 +32,15 @@ export type ActivityPayloads = {
32
32
  "file:delete": { path: string }
33
33
  "file:move": { from: string; to: string }
34
34
  "file:search": { query: string; scope?: string; matches?: number }
35
- "proc:exec": { command: string; cwd?: string; exitCode?: number }
35
+ "file:list": { path: string; entries?: number }
36
+ "vcs:status": { cwd?: string }
37
+ "vcs:diff": { args?: string }
38
+ "vcs:log": { args?: string }
39
+ "vcs:show": { args?: string }
40
+ "process:chdir": { cwd: string }
41
+ "proc:spawn": { command: string; procId?: string; pid?: number; exitCode?: number; stopped?: boolean; startedAt?: number; outputBytes?: number }
42
+ "proc:kill": { procId: string; command?: string }
43
+ "proc:exec": { command: string; cwd?: string; exitCode?: number; startedAt?: number; outputBytes?: number }
36
44
  "http": { method: string; url: string; status?: number }
37
45
  "speech": { text: string }
38
46
  /** Escape hatch — a plain sentence for anything outside the vocabulary. */
@@ -72,6 +80,10 @@ export type AxonAmbient = {
72
80
  }
73
81
 
74
82
  export type ActivityHandle<T extends ActivityType = ActivityType> = {
83
+ /** Amend an open activity without changing its lifecycle phase. */
84
+ update(data: Partial<ActivityPayloads[T]>): void
75
85
  /** Settle the activity with the rest of its payload. Idempotent. */
76
86
  done(data?: Partial<ActivityPayloads[T]>): void
87
+ /** Settle the activity as failed with the boundary's reason. */
88
+ fail(data: Partial<ActivityPayloads[T]>, error: string): void
77
89
  }