aimc-protocol 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alkapa.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # aimc-protocol
2
+
3
+ The messages between an aimc server and its host agents ([aimc-host](https://www.npmjs.com/package/aimc-host)),
4
+ as [zod](https://zod.dev) schemas. Both sides validate everything they receive with them.
5
+
6
+ ```ts
7
+ import { helloRequest, parseStreamEvent, PROTOCOL_VERSION } from "aimc-protocol/agent";
8
+ import { encodeSseData, readSseData } from "aimc-protocol/sse";
9
+ ```
10
+
11
+ ESM only, Node 22.12 or newer, TypeScript types included.
12
+
13
+ ## The API (version 1)
14
+
15
+ | Call | Direction | Body |
16
+ |---|---|---|
17
+ | `GET /api/agent/v1/config` (no auth) | agent → server | `agentConfigResponse`: where to sign in (OpenID Connect device flow) |
18
+ | `POST /api/agent/v1/hosts` | agent → server | `registerHostRequest` → `registerHostResponse` |
19
+ | `POST /api/agent/v1/hosts/{id}/hello` | agent → server | `helloRequest` → `helloResponse` |
20
+ | `GET /api/agent/v1/hosts/{id}/stream` | server → agent (SSE) | `streamEvent`: `job`, `cancel`, `config`, `ping` |
21
+ | `POST /api/agent/v1/hosts/{id}/jobs/{jobId}/events` | agent → server | `jobEventsRequest` → `jobEventsResponse` |
22
+ | `POST /api/agent/v1/hosts/{id}/heartbeat` | agent → server | `heartbeatRequest` → `heartbeatResponse` |
23
+
24
+ Every non-2xx answer is `agentApiError`: `{ error: { code, message } }`, the message written for
25
+ the host's owner.
26
+
27
+ ## Compatibility
28
+
29
+ `PROTOCOL_VERSION` is 1, and version 1 only grows:
30
+ - new fields are optional; unknown fields are stripped, so older peers ignore them;
31
+ - new stream events are ignored by older agents (`parseStreamEvent` returns null);
32
+ - new error codes are added, never renamed or removed.
33
+
34
+ Package versions follow that: additions are minor releases (1.x). A breaking change would be
35
+ protocol version 2, released as 2.0.0.
36
+
37
+ ## License
38
+
39
+ MIT
@@ -0,0 +1,280 @@
1
+ import { z } from "zod";
2
+ export declare const PROTOCOL_VERSION = 1;
3
+ /** The scope an agent asks for: "host" carries the host API audience; offline_access a long-lived refresh token. */
4
+ export declare const AGENT_SCOPE = "openid offline_access host";
5
+ export declare const HEARTBEAT_INTERVAL_MS = 15000;
6
+ export declare const agentConfigResponse: z.ZodObject<{
7
+ issuer: z.ZodURL;
8
+ clientId: z.ZodString;
9
+ scope: z.ZodString;
10
+ protocolVersion: z.ZodNumber;
11
+ }, z.core.$strip>;
12
+ export type AgentConfigResponse = z.infer<typeof agentConfigResponse>;
13
+ export declare const HOST_NAME: RegExp;
14
+ export declare const registerHostRequest: z.ZodObject<{
15
+ name: z.ZodString;
16
+ }, z.core.$strip>;
17
+ export type RegisterHostRequest = z.infer<typeof registerHostRequest>;
18
+ export declare const registerHostResponse: z.ZodObject<{
19
+ hostId: z.ZodUUID;
20
+ status: z.ZodLiteral<"pending_approval">;
21
+ }, z.core.$strip>;
22
+ export type RegisterHostResponse = z.infer<typeof registerHostResponse>;
23
+ export declare const helloRequest: z.ZodObject<{
24
+ protocolVersion: z.ZodNumber;
25
+ agentVersion: z.ZodString;
26
+ offeredModels: z.ZodArray<z.ZodString>;
27
+ maxConcurrent: z.ZodDefault<z.ZodNumber>;
28
+ hardware: z.ZodDefault<z.ZodObject<{
29
+ gpuName: z.ZodOptional<z.ZodString>;
30
+ vramMb: z.ZodOptional<z.ZodNumber>;
31
+ }, z.core.$strip>>;
32
+ ollamaVersion: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$strip>;
34
+ export type HelloRequest = z.input<typeof helloRequest>;
35
+ export declare const helloResponse: z.ZodObject<{
36
+ status: z.ZodEnum<{
37
+ pending_approval: "pending_approval";
38
+ active: "active";
39
+ paused: "paused";
40
+ }>;
41
+ maxConcurrent: z.ZodNumber;
42
+ heartbeatIntervalMs: z.ZodNumber;
43
+ latestAgentVersion: z.ZodOptional<z.ZodString>;
44
+ minAgentVersion: z.ZodOptional<z.ZodString>;
45
+ }, z.core.$strip>;
46
+ export type HelloResponse = z.infer<typeof helloResponse>;
47
+ export declare const jobMessage: z.ZodObject<{
48
+ role: z.ZodEnum<{
49
+ system: "system";
50
+ user: "user";
51
+ assistant: "assistant";
52
+ }>;
53
+ content: z.ZodString;
54
+ images: z.ZodOptional<z.ZodArray<z.ZodString>>;
55
+ }, z.core.$strip>;
56
+ export declare const jobOptions: z.ZodObject<{
57
+ numPredict: z.ZodNumber;
58
+ temperature: z.ZodOptional<z.ZodNumber>;
59
+ topP: z.ZodOptional<z.ZodNumber>;
60
+ stop: z.ZodOptional<z.ZodArray<z.ZodString>>;
61
+ seed: z.ZodOptional<z.ZodNumber>;
62
+ format: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"json">, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
63
+ think: z.ZodOptional<z.ZodBoolean>;
64
+ numCtx: z.ZodOptional<z.ZodNumber>;
65
+ }, z.core.$strip>;
66
+ export type JobOptions = z.infer<typeof jobOptions>;
67
+ export declare const jobEvent: z.ZodObject<{
68
+ type: z.ZodLiteral<"job">;
69
+ jobId: z.ZodUUID;
70
+ model: z.ZodString;
71
+ messages: z.ZodArray<z.ZodObject<{
72
+ role: z.ZodEnum<{
73
+ system: "system";
74
+ user: "user";
75
+ assistant: "assistant";
76
+ }>;
77
+ content: z.ZodString;
78
+ images: z.ZodOptional<z.ZodArray<z.ZodString>>;
79
+ }, z.core.$strip>>;
80
+ options: z.ZodObject<{
81
+ numPredict: z.ZodNumber;
82
+ temperature: z.ZodOptional<z.ZodNumber>;
83
+ topP: z.ZodOptional<z.ZodNumber>;
84
+ stop: z.ZodOptional<z.ZodArray<z.ZodString>>;
85
+ seed: z.ZodOptional<z.ZodNumber>;
86
+ format: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"json">, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
87
+ think: z.ZodOptional<z.ZodBoolean>;
88
+ numCtx: z.ZodOptional<z.ZodNumber>;
89
+ }, z.core.$strip>;
90
+ deadlineMs: z.ZodNumber;
91
+ }, z.core.$strip>;
92
+ export type JobEvent = z.infer<typeof jobEvent>;
93
+ export declare const cancelEvent: z.ZodObject<{
94
+ type: z.ZodLiteral<"cancel">;
95
+ jobId: z.ZodUUID;
96
+ }, z.core.$strip>;
97
+ export declare const configEvent: z.ZodObject<{
98
+ type: z.ZodLiteral<"config">;
99
+ maxConcurrent: z.ZodNumber;
100
+ }, z.core.$strip>;
101
+ export declare const pingEvent: z.ZodObject<{
102
+ type: z.ZodLiteral<"ping">;
103
+ }, z.core.$strip>;
104
+ export declare const streamEvent: z.ZodDiscriminatedUnion<[z.ZodObject<{
105
+ type: z.ZodLiteral<"job">;
106
+ jobId: z.ZodUUID;
107
+ model: z.ZodString;
108
+ messages: z.ZodArray<z.ZodObject<{
109
+ role: z.ZodEnum<{
110
+ system: "system";
111
+ user: "user";
112
+ assistant: "assistant";
113
+ }>;
114
+ content: z.ZodString;
115
+ images: z.ZodOptional<z.ZodArray<z.ZodString>>;
116
+ }, z.core.$strip>>;
117
+ options: z.ZodObject<{
118
+ numPredict: z.ZodNumber;
119
+ temperature: z.ZodOptional<z.ZodNumber>;
120
+ topP: z.ZodOptional<z.ZodNumber>;
121
+ stop: z.ZodOptional<z.ZodArray<z.ZodString>>;
122
+ seed: z.ZodOptional<z.ZodNumber>;
123
+ format: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"json">, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
124
+ think: z.ZodOptional<z.ZodBoolean>;
125
+ numCtx: z.ZodOptional<z.ZodNumber>;
126
+ }, z.core.$strip>;
127
+ deadlineMs: z.ZodNumber;
128
+ }, z.core.$strip>, z.ZodObject<{
129
+ type: z.ZodLiteral<"cancel">;
130
+ jobId: z.ZodUUID;
131
+ }, z.core.$strip>, z.ZodObject<{
132
+ type: z.ZodLiteral<"config">;
133
+ maxConcurrent: z.ZodNumber;
134
+ }, z.core.$strip>, z.ZodObject<{
135
+ type: z.ZodLiteral<"ping">;
136
+ }, z.core.$strip>], "type">;
137
+ export type StreamEvent = z.infer<typeof streamEvent>;
138
+ /** Parses one event from the stream; null for unknown or broken events (ignored, never fatal). */
139
+ export declare function parseStreamEvent(data: unknown): StreamEvent | null;
140
+ export declare const deltaJobEvent: z.ZodObject<{
141
+ type: z.ZodLiteral<"delta">;
142
+ text: z.ZodString;
143
+ }, z.core.$strip>;
144
+ export declare const doneJobEvent: z.ZodObject<{
145
+ type: z.ZodLiteral<"done">;
146
+ finishReason: z.ZodEnum<{
147
+ stop: "stop";
148
+ length: "length";
149
+ }>;
150
+ usage: z.ZodOptional<z.ZodObject<{
151
+ promptTokens: z.ZodNumber;
152
+ completionTokens: z.ZodNumber;
153
+ }, z.core.$strip>>;
154
+ timings: z.ZodOptional<z.ZodObject<{
155
+ loadMs: z.ZodOptional<z.ZodNumber>;
156
+ promptEvalMs: z.ZodOptional<z.ZodNumber>;
157
+ evalMs: z.ZodOptional<z.ZodNumber>;
158
+ }, z.core.$strip>>;
159
+ }, z.core.$strip>;
160
+ /**
161
+ * Codes an agent reports. "thinking_not_supported" / "images_not_supported": Ollama refused think
162
+ * or images for this model (another host would refuse too). retryable = the server may try
163
+ * another host if nothing was sent yet. New codes are only ever added, never renamed.
164
+ */
165
+ export declare const AGENT_ERROR_CODES: readonly ["model_not_offered", "ollama_unreachable", "ollama_error", "thinking_not_supported", "images_not_supported", "deadline_exceeded", "busy", "internal"];
166
+ export declare const errorJobEvent: z.ZodObject<{
167
+ type: z.ZodLiteral<"error">;
168
+ code: z.ZodEnum<{
169
+ model_not_offered: "model_not_offered";
170
+ ollama_unreachable: "ollama_unreachable";
171
+ ollama_error: "ollama_error";
172
+ thinking_not_supported: "thinking_not_supported";
173
+ images_not_supported: "images_not_supported";
174
+ deadline_exceeded: "deadline_exceeded";
175
+ busy: "busy";
176
+ internal: "internal";
177
+ }>;
178
+ retryable: z.ZodBoolean;
179
+ }, z.core.$strip>;
180
+ export declare const agentJobEvent: z.ZodDiscriminatedUnion<[z.ZodObject<{
181
+ type: z.ZodLiteral<"delta">;
182
+ text: z.ZodString;
183
+ }, z.core.$strip>, z.ZodObject<{
184
+ type: z.ZodLiteral<"done">;
185
+ finishReason: z.ZodEnum<{
186
+ stop: "stop";
187
+ length: "length";
188
+ }>;
189
+ usage: z.ZodOptional<z.ZodObject<{
190
+ promptTokens: z.ZodNumber;
191
+ completionTokens: z.ZodNumber;
192
+ }, z.core.$strip>>;
193
+ timings: z.ZodOptional<z.ZodObject<{
194
+ loadMs: z.ZodOptional<z.ZodNumber>;
195
+ promptEvalMs: z.ZodOptional<z.ZodNumber>;
196
+ evalMs: z.ZodOptional<z.ZodNumber>;
197
+ }, z.core.$strip>>;
198
+ }, z.core.$strip>, z.ZodObject<{
199
+ type: z.ZodLiteral<"error">;
200
+ code: z.ZodEnum<{
201
+ model_not_offered: "model_not_offered";
202
+ ollama_unreachable: "ollama_unreachable";
203
+ ollama_error: "ollama_error";
204
+ thinking_not_supported: "thinking_not_supported";
205
+ images_not_supported: "images_not_supported";
206
+ deadline_exceeded: "deadline_exceeded";
207
+ busy: "busy";
208
+ internal: "internal";
209
+ }>;
210
+ retryable: z.ZodBoolean;
211
+ }, z.core.$strip>], "type">;
212
+ export type AgentJobEvent = z.infer<typeof agentJobEvent>;
213
+ export declare const jobEventsRequest: z.ZodObject<{
214
+ seq: z.ZodNumber;
215
+ events: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
216
+ type: z.ZodLiteral<"delta">;
217
+ text: z.ZodString;
218
+ }, z.core.$strip>, z.ZodObject<{
219
+ type: z.ZodLiteral<"done">;
220
+ finishReason: z.ZodEnum<{
221
+ stop: "stop";
222
+ length: "length";
223
+ }>;
224
+ usage: z.ZodOptional<z.ZodObject<{
225
+ promptTokens: z.ZodNumber;
226
+ completionTokens: z.ZodNumber;
227
+ }, z.core.$strip>>;
228
+ timings: z.ZodOptional<z.ZodObject<{
229
+ loadMs: z.ZodOptional<z.ZodNumber>;
230
+ promptEvalMs: z.ZodOptional<z.ZodNumber>;
231
+ evalMs: z.ZodOptional<z.ZodNumber>;
232
+ }, z.core.$strip>>;
233
+ }, z.core.$strip>, z.ZodObject<{
234
+ type: z.ZodLiteral<"error">;
235
+ code: z.ZodEnum<{
236
+ model_not_offered: "model_not_offered";
237
+ ollama_unreachable: "ollama_unreachable";
238
+ ollama_error: "ollama_error";
239
+ thinking_not_supported: "thinking_not_supported";
240
+ images_not_supported: "images_not_supported";
241
+ deadline_exceeded: "deadline_exceeded";
242
+ busy: "busy";
243
+ internal: "internal";
244
+ }>;
245
+ retryable: z.ZodBoolean;
246
+ }, z.core.$strip>], "type">>;
247
+ }, z.core.$strip>;
248
+ export type JobEventsRequest = z.infer<typeof jobEventsRequest>;
249
+ export declare const jobEventsResponse: z.ZodObject<{
250
+ cancelled: z.ZodBoolean;
251
+ }, z.core.$strip>;
252
+ export type JobEventsResponse = z.infer<typeof jobEventsResponse>;
253
+ export declare const heartbeatRequest: z.ZodObject<{
254
+ gpu: z.ZodOptional<z.ZodObject<{
255
+ name: z.ZodString;
256
+ vramTotalMb: z.ZodNumber;
257
+ vramUsedMb: z.ZodNumber;
258
+ utilizationPct: z.ZodNumber;
259
+ temperatureC: z.ZodNumber;
260
+ }, z.core.$strip>>;
261
+ loadedModels: z.ZodArray<z.ZodObject<{
262
+ name: z.ZodString;
263
+ vramMb: z.ZodNumber;
264
+ expiresAt: z.ZodOptional<z.ZodString>;
265
+ }, z.core.$strip>>;
266
+ ollamaVersion: z.ZodOptional<z.ZodString>;
267
+ }, z.core.$strip>;
268
+ export type HeartbeatRequest = z.infer<typeof heartbeatRequest>;
269
+ export declare const heartbeatResponse: z.ZodObject<{
270
+ ok: z.ZodLiteral<true>;
271
+ }, z.core.$strip>;
272
+ /** Every non-2xx answer of the agent API: a fixed code and a message for the owner. */
273
+ export declare const agentApiError: z.ZodObject<{
274
+ error: z.ZodObject<{
275
+ code: z.ZodString;
276
+ message: z.ZodString;
277
+ }, z.core.$strip>;
278
+ }, z.core.$strip>;
279
+ export type AgentApiError = z.infer<typeof agentApiError>;
280
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAmBxB,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAClC,oHAAoH;AACpH,eAAO,MAAM,WAAW,+BAA+B,CAAC;AACxD,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAU5C,eAAO,MAAM,mBAAmB;;;;;iBAK9B,CAAC;AACH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAA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W,GAAG,IAAI,CAGlE;AAID,eAAO,MAAM,aAAa;;;iBAAwE,CAAC;AACnG,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;iBAKvB,CAAC;AACH;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,iKASpB,CAAC;AACX,eAAO,MAAM,aAAa;;;;;;;;;;;;;iBAIxB,CAAC;AAEH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAA6E,CAAC;AACxG,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAE1D,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAI3B,CAAC;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEhE,eAAO,MAAM,iBAAiB;;iBAAuC,CAAC;AACtE,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAIlE,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;iBAc3B,CAAC;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEhE,eAAO,MAAM,iBAAiB;;iBAAoC,CAAC;AAInE,uFAAuF;AACvF,eAAO,MAAM,aAAa;;;;;iBAA2E,CAAC;AACtG,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC"}
package/dist/agent.js ADDED
@@ -0,0 +1,156 @@
1
+ import { z } from "zod";
2
+ // The agent protocol, version 1: every message between an aimc server and a host agent.
3
+ // Both sides validate everything they receive with these schemas. Unknown stream event types are
4
+ // ignored (a newer server may send events an older agent doesn't know), unknown fields stripped.
5
+ //
6
+ // Compatibility: version 1 only ever grows. New fields are optional, new events and error codes
7
+ // are added, nothing is renamed or removed. A breaking change would be version 2, in a new
8
+ // major release of this package.
9
+ //
10
+ // GET /api/agent/v1/config no auth: where to sign in
11
+ // POST /api/agent/v1/hosts register a host (pending approval)
12
+ // POST /api/agent/v1/hosts/{id}/hello versions, offered models, hardware
13
+ // GET /api/agent/v1/hosts/{id}/stream SSE, server -> agent: job, cancel, config, ping
14
+ // POST /api/agent/v1/hosts/{id}/jobs/{jobId}/events agent -> server: deltas, done or error
15
+ // POST /api/agent/v1/hosts/{id}/heartbeat telemetry every 15 s
16
+ //
17
+ // Every non-2xx answer is { error: { code, message } } (agentApiError below).
18
+ export const PROTOCOL_VERSION = 1;
19
+ /** The scope an agent asks for: "host" carries the host API audience; offline_access a long-lived refresh token. */
20
+ export const AGENT_SCOPE = "openid offline_access host";
21
+ export const HEARTBEAT_INTERVAL_MS = 15_000;
22
+ /** Ollama-style model names, e.g. "qwen3-vl:8b-instruct" or "library/model:tag". */
23
+ const modelName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/);
24
+ const shortText = (max) => z.string().max(max);
25
+ const count = z.number().int().min(0).max(10_000_000);
26
+ const ms = z.number().int().min(0).max(24 * 3600 * 1000);
27
+ // ---- config ------------------------------------------------------------------------------
28
+ export const agentConfigResponse = z.object({
29
+ issuer: z.url(),
30
+ clientId: z.string().min(1),
31
+ scope: z.string().min(1),
32
+ protocolVersion: z.number().int(),
33
+ });
34
+ // ---- register ----------------------------------------------------------------------------
35
+ export const HOST_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,59}$/;
36
+ export const registerHostRequest = z.object({ name: z.string().trim().regex(HOST_NAME) });
37
+ export const registerHostResponse = z.object({ hostId: z.uuid(), status: z.literal("pending_approval") });
38
+ // ---- hello -------------------------------------------------------------------------------
39
+ export const helloRequest = z.object({
40
+ protocolVersion: z.number().int(),
41
+ agentVersion: shortText(40),
42
+ /** The local Ollama models the owner offers (only these are ever run). */
43
+ offeredModels: z.array(modelName).max(50),
44
+ /** The owner's own limit for jobs at once; the server uses the smaller of this and the admin's. */
45
+ maxConcurrent: z.number().int().min(1).max(32).default(1),
46
+ hardware: z
47
+ .object({ gpuName: shortText(100).optional(), vramMb: z.number().int().min(0).max(1_000_000).optional() })
48
+ .default({}),
49
+ ollamaVersion: shortText(40).optional(),
50
+ });
51
+ export const helloResponse = z.object({
52
+ status: z.enum(["pending_approval", "active", "paused"]),
53
+ /** Jobs at once this host gets (the smaller of the owner's and the admin's limit). */
54
+ maxConcurrent: z.number().int().min(1),
55
+ heartbeatIntervalMs: z.number().int().min(1000),
56
+ /** The newest host agent version the server recommends; an older agent tells its owner to update. */
57
+ latestAgentVersion: shortText(40).optional(),
58
+ /** The oldest host agent version the server accepts; older agents are refused (426 agent_outdated). */
59
+ minAgentVersion: shortText(40).optional(),
60
+ });
61
+ // ---- the job stream (server -> agent) ----------------------------------------------------
62
+ export const jobMessage = z.object({
63
+ role: z.enum(["system", "user", "assistant"]),
64
+ content: z.string(),
65
+ /** Base64 image data without the data: prefix, already validated by the server. */
66
+ images: z.array(z.string()).max(16).optional(),
67
+ });
68
+ export const jobOptions = z.object({
69
+ /** Ollama's num_predict: the most tokens to generate (already capped by the server). */
70
+ numPredict: z.number().int().min(1).max(1_000_000),
71
+ temperature: z.number().min(0).max(2).optional(),
72
+ topP: z.number().min(0).max(1).optional(),
73
+ stop: z.array(z.string().max(200)).max(4).optional(),
74
+ seed: z.number().int().optional(),
75
+ /** Ollama's format: "json" for any JSON object, or a JSON Schema the answer must match. */
76
+ format: z.union([z.literal("json"), z.record(z.string(), z.unknown())]).optional(),
77
+ /** Ollama's think switch; missing = the model's default. */
78
+ think: z.boolean().optional(),
79
+ /** Ollama's num_ctx: the context size the server wants for this model; missing = Ollama's default. */
80
+ numCtx: z.number().int().min(512).max(1_048_576).optional(),
81
+ });
82
+ export const jobEvent = z.object({
83
+ type: z.literal("job"),
84
+ jobId: z.uuid(),
85
+ /** The model's name in the agent's Ollama (one of its offered models). */
86
+ model: modelName,
87
+ messages: z.array(jobMessage).min(1),
88
+ options: jobOptions,
89
+ /** Stop and report an error if the job isn't finished after this many milliseconds. */
90
+ deadlineMs: ms,
91
+ });
92
+ export const cancelEvent = z.object({ type: z.literal("cancel"), jobId: z.uuid() });
93
+ export const configEvent = z.object({ type: z.literal("config"), maxConcurrent: z.number().int().min(1) });
94
+ export const pingEvent = z.object({ type: z.literal("ping") });
95
+ export const streamEvent = z.discriminatedUnion("type", [jobEvent, cancelEvent, configEvent, pingEvent]);
96
+ /** Parses one event from the stream; null for unknown or broken events (ignored, never fatal). */
97
+ export function parseStreamEvent(data) {
98
+ const result = streamEvent.safeParse(data);
99
+ return result.success ? result.data : null;
100
+ }
101
+ // ---- job events (agent -> server) --------------------------------------------------------
102
+ export const deltaJobEvent = z.object({ type: z.literal("delta"), text: z.string().max(100_000) });
103
+ export const doneJobEvent = z.object({
104
+ type: z.literal("done"),
105
+ finishReason: z.enum(["stop", "length"]),
106
+ usage: z.object({ promptTokens: count, completionTokens: count }).optional(),
107
+ timings: z.object({ loadMs: ms.optional(), promptEvalMs: ms.optional(), evalMs: ms.optional() }).optional(),
108
+ });
109
+ /**
110
+ * Codes an agent reports. "thinking_not_supported" / "images_not_supported": Ollama refused think
111
+ * or images for this model (another host would refuse too). retryable = the server may try
112
+ * another host if nothing was sent yet. New codes are only ever added, never renamed.
113
+ */
114
+ export const AGENT_ERROR_CODES = [
115
+ "model_not_offered",
116
+ "ollama_unreachable",
117
+ "ollama_error",
118
+ "thinking_not_supported",
119
+ "images_not_supported",
120
+ "deadline_exceeded",
121
+ "busy",
122
+ "internal",
123
+ ];
124
+ export const errorJobEvent = z.object({
125
+ type: z.literal("error"),
126
+ code: z.enum(AGENT_ERROR_CODES),
127
+ retryable: z.boolean(),
128
+ });
129
+ export const agentJobEvent = z.discriminatedUnion("type", [deltaJobEvent, doneJobEvent, errorJobEvent]);
130
+ export const jobEventsRequest = z.object({
131
+ /** 0, 1, 2… per job: lets the server drop a batch it already got (the agent retried). */
132
+ seq: z.number().int().min(0).max(1_000_000),
133
+ events: z.array(agentJobEvent).min(1).max(500),
134
+ });
135
+ export const jobEventsResponse = z.object({ cancelled: z.boolean() });
136
+ // ---- heartbeat ---------------------------------------------------------------------------
137
+ export const heartbeatRequest = z.object({
138
+ gpu: z
139
+ .object({
140
+ name: shortText(100),
141
+ vramTotalMb: z.number().int().min(0).max(1_000_000),
142
+ vramUsedMb: z.number().int().min(0).max(1_000_000),
143
+ utilizationPct: z.number().min(0).max(100),
144
+ temperatureC: z.number().min(-50).max(150),
145
+ })
146
+ .optional(),
147
+ loadedModels: z
148
+ .array(z.object({ name: modelName, vramMb: z.number().int().min(0).max(1_000_000), expiresAt: shortText(40).optional() }))
149
+ .max(20),
150
+ ollamaVersion: shortText(40).optional(),
151
+ });
152
+ export const heartbeatResponse = z.object({ ok: z.literal(true) });
153
+ // ---- errors ------------------------------------------------------------------------------
154
+ /** Every non-2xx answer of the agent API: a fixed code and a message for the owner. */
155
+ export const agentApiError = z.object({ error: z.object({ code: z.string(), message: z.string() }) });
156
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,wFAAwF;AACxF,iGAAiG;AACjG,iGAAiG;AACjG,EAAE;AACF,gGAAgG;AAChG,2FAA2F;AAC3F,iCAAiC;AACjC,EAAE;AACF,iFAAiF;AACjF,0FAA0F;AAC1F,0FAA0F;AAC1F,uGAAuG;AACvG,8FAA8F;AAC9F,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAE9E,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAClC,oHAAoH;AACpH,MAAM,CAAC,MAAM,WAAW,GAAG,4BAA4B,CAAC;AACxD,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAE5C,oFAAoF;AACpF,MAAM,SAAS,GAAG,CAAC,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+ /**
4
+ * Reads a stream of SSE events and yields each event's data, parsed as JSON. Network packets can
5
+ * cut an event anywhere, so it buffers until a full event (ending in an empty line) has arrived.
6
+ * Comments and events whose data isn't JSON are skipped.
7
+ */
8
+ export declare function readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown>;
9
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAMA,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,CAExD;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAEzD;AAED;;;;GAIG;AACH,wBAAuB,WAAW,CAAC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,OAAO,CAAC,CA8B5F"}
package/dist/sse.js ADDED
@@ -0,0 +1,52 @@
1
+ // Server-Sent Events, the small subset both sides use: every event is one `data:` line with a
2
+ // JSON object, then an empty line. Lines starting with ":" are comments (keep-alives).
3
+ // Shared by the server (writes the agent's job stream) and the host agent (reads it).
4
+ const encoder = new TextEncoder();
5
+ export function encodeSseData(value) {
6
+ return encoder.encode(`data: ${JSON.stringify(value)}\n\n`);
7
+ }
8
+ export function encodeSseComment(text) {
9
+ return encoder.encode(`: ${text.replace(/[\r\n]/g, " ")}\n\n`);
10
+ }
11
+ /**
12
+ * Reads a stream of SSE events and yields each event's data, parsed as JSON. Network packets can
13
+ * cut an event anywhere, so it buffers until a full event (ending in an empty line) has arrived.
14
+ * Comments and events whose data isn't JSON are skipped.
15
+ */
16
+ export async function* readSseData(body) {
17
+ const reader = body.getReader();
18
+ const decoder = new TextDecoder();
19
+ let buffer = "";
20
+ try {
21
+ for (;;) {
22
+ const { value, done } = await reader.read();
23
+ if (done)
24
+ break;
25
+ buffer += decoder.decode(value, { stream: true });
26
+ for (;;) {
27
+ const match = /\r?\n\r?\n/.exec(buffer);
28
+ if (!match)
29
+ break;
30
+ const block = buffer.slice(0, match.index);
31
+ buffer = buffer.slice(match.index + match[0].length);
32
+ const data = block
33
+ .split(/\r?\n/)
34
+ .filter((line) => line.startsWith("data:"))
35
+ .map((line) => line.slice(5).replace(/^ /, ""))
36
+ .join("\n");
37
+ if (!data)
38
+ continue;
39
+ try {
40
+ yield JSON.parse(data);
41
+ }
42
+ catch {
43
+ // not JSON: ignore, like an unknown event type
44
+ }
45
+ }
46
+ }
47
+ }
48
+ finally {
49
+ reader.releaseLock();
50
+ }
51
+ }
52
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,uFAAuF;AACvF,sFAAsF;AAEtF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,CAAC,MAAM,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAC3C,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AACjE,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,WAAW,CAAC,IAAgC;IACjE,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAChC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,CAAC;QACH,SAAS,CAAC;YACR,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,IAAI;gBAAE,MAAM;YAChB,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;YAClD,SAAS,CAAC;gBACR,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBACxC,IAAI,CAAC,KAAK;oBAAE,MAAM;gBAClB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;gBAC3C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;gBACrD,MAAM,IAAI,GAAG,KAAK;qBACf,KAAK,CAAC,OAAO,CAAC;qBACd,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;qBAC1C,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;qBAC9C,IAAI,CAAC,IAAI,CAAC,CAAC;gBACd,IAAI,CAAC,IAAI;oBAAE,SAAS;gBACpB,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;gBACpC,CAAC;gBAAC,MAAM,CAAC;oBACP,+CAA+C;gBACjD,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "aimc-protocol",
3
+ "version": "1.0.0",
4
+ "description": "The aimc host agent protocol (version 1): every message between a server and a host agent, as zod schemas",
5
+ "keywords": [
6
+ "ollama",
7
+ "gpu",
8
+ "protocol",
9
+ "zod",
10
+ "sse"
11
+ ],
12
+ "license": "MIT",
13
+ "homepage": "https://github.com/alkapa-com/aimc-host/tree/main/packages/protocol#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/alkapa-com/aimc-host.git",
17
+ "directory": "packages/protocol"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/alkapa-com/aimc-host/issues"
21
+ },
22
+ "author": "alkapa.com <info@alkapa.com>",
23
+ "type": "module",
24
+ "engines": {
25
+ "node": ">=22.12"
26
+ },
27
+ "exports": {
28
+ "./agent": {
29
+ "aimc-source": "./src/agent.ts",
30
+ "types": "./dist/agent.d.ts",
31
+ "default": "./dist/agent.js"
32
+ },
33
+ "./sse": {
34
+ "aimc-source": "./src/sse.ts",
35
+ "types": "./dist/sse.d.ts",
36
+ "default": "./dist/sse.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "files": [
41
+ "dist",
42
+ "src",
43
+ "!src/**/*.test.ts"
44
+ ],
45
+ "scripts": {
46
+ "build": "node ../../scripts/clean.mjs dist && tsc -p tsconfig.build.json",
47
+ "prepack": "npm run build"
48
+ },
49
+ "dependencies": {
50
+ "zod": "4.6.7"
51
+ }
52
+ }
package/src/agent.ts ADDED
@@ -0,0 +1,197 @@
1
+ import { z } from "zod";
2
+
3
+ // The agent protocol, version 1: every message between an aimc server and a host agent.
4
+ // Both sides validate everything they receive with these schemas. Unknown stream event types are
5
+ // ignored (a newer server may send events an older agent doesn't know), unknown fields stripped.
6
+ //
7
+ // Compatibility: version 1 only ever grows. New fields are optional, new events and error codes
8
+ // are added, nothing is renamed or removed. A breaking change would be version 2, in a new
9
+ // major release of this package.
10
+ //
11
+ // GET /api/agent/v1/config no auth: where to sign in
12
+ // POST /api/agent/v1/hosts register a host (pending approval)
13
+ // POST /api/agent/v1/hosts/{id}/hello versions, offered models, hardware
14
+ // GET /api/agent/v1/hosts/{id}/stream SSE, server -> agent: job, cancel, config, ping
15
+ // POST /api/agent/v1/hosts/{id}/jobs/{jobId}/events agent -> server: deltas, done or error
16
+ // POST /api/agent/v1/hosts/{id}/heartbeat telemetry every 15 s
17
+ //
18
+ // Every non-2xx answer is { error: { code, message } } (agentApiError below).
19
+
20
+ export const PROTOCOL_VERSION = 1;
21
+ /** The scope an agent asks for: "host" carries the host API audience; offline_access a long-lived refresh token. */
22
+ export const AGENT_SCOPE = "openid offline_access host";
23
+ export const HEARTBEAT_INTERVAL_MS = 15_000;
24
+
25
+ /** Ollama-style model names, e.g. "qwen3-vl:8b-instruct" or "library/model:tag". */
26
+ const modelName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/);
27
+ const shortText = (max: number) => z.string().max(max);
28
+ const count = z.number().int().min(0).max(10_000_000);
29
+ const ms = z.number().int().min(0).max(24 * 3600 * 1000);
30
+
31
+ // ---- config ------------------------------------------------------------------------------
32
+
33
+ export const agentConfigResponse = z.object({
34
+ issuer: z.url(),
35
+ clientId: z.string().min(1),
36
+ scope: z.string().min(1),
37
+ protocolVersion: z.number().int(),
38
+ });
39
+ export type AgentConfigResponse = z.infer<typeof agentConfigResponse>;
40
+
41
+ // ---- register ----------------------------------------------------------------------------
42
+
43
+ export const HOST_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,59}$/;
44
+
45
+ export const registerHostRequest = z.object({ name: z.string().trim().regex(HOST_NAME) });
46
+ export type RegisterHostRequest = z.infer<typeof registerHostRequest>;
47
+
48
+ export const registerHostResponse = z.object({ hostId: z.uuid(), status: z.literal("pending_approval") });
49
+ export type RegisterHostResponse = z.infer<typeof registerHostResponse>;
50
+
51
+ // ---- hello -------------------------------------------------------------------------------
52
+
53
+ export const helloRequest = z.object({
54
+ protocolVersion: z.number().int(),
55
+ agentVersion: shortText(40),
56
+ /** The local Ollama models the owner offers (only these are ever run). */
57
+ offeredModels: z.array(modelName).max(50),
58
+ /** The owner's own limit for jobs at once; the server uses the smaller of this and the admin's. */
59
+ maxConcurrent: z.number().int().min(1).max(32).default(1),
60
+ hardware: z
61
+ .object({ gpuName: shortText(100).optional(), vramMb: z.number().int().min(0).max(1_000_000).optional() })
62
+ .default({}),
63
+ ollamaVersion: shortText(40).optional(),
64
+ });
65
+ export type HelloRequest = z.input<typeof helloRequest>;
66
+
67
+ export const helloResponse = z.object({
68
+ status: z.enum(["pending_approval", "active", "paused"]),
69
+ /** Jobs at once this host gets (the smaller of the owner's and the admin's limit). */
70
+ maxConcurrent: z.number().int().min(1),
71
+ heartbeatIntervalMs: z.number().int().min(1000),
72
+ /** The newest host agent version the server recommends; an older agent tells its owner to update. */
73
+ latestAgentVersion: shortText(40).optional(),
74
+ /** The oldest host agent version the server accepts; older agents are refused (426 agent_outdated). */
75
+ minAgentVersion: shortText(40).optional(),
76
+ });
77
+ export type HelloResponse = z.infer<typeof helloResponse>;
78
+
79
+ // ---- the job stream (server -> agent) ----------------------------------------------------
80
+
81
+ export const jobMessage = z.object({
82
+ role: z.enum(["system", "user", "assistant"]),
83
+ content: z.string(),
84
+ /** Base64 image data without the data: prefix, already validated by the server. */
85
+ images: z.array(z.string()).max(16).optional(),
86
+ });
87
+
88
+ export const jobOptions = z.object({
89
+ /** Ollama's num_predict: the most tokens to generate (already capped by the server). */
90
+ numPredict: z.number().int().min(1).max(1_000_000),
91
+ temperature: z.number().min(0).max(2).optional(),
92
+ topP: z.number().min(0).max(1).optional(),
93
+ stop: z.array(z.string().max(200)).max(4).optional(),
94
+ seed: z.number().int().optional(),
95
+ /** Ollama's format: "json" for any JSON object, or a JSON Schema the answer must match. */
96
+ format: z.union([z.literal("json"), z.record(z.string(), z.unknown())]).optional(),
97
+ /** Ollama's think switch; missing = the model's default. */
98
+ think: z.boolean().optional(),
99
+ /** Ollama's num_ctx: the context size the server wants for this model; missing = Ollama's default. */
100
+ numCtx: z.number().int().min(512).max(1_048_576).optional(),
101
+ });
102
+ export type JobOptions = z.infer<typeof jobOptions>;
103
+
104
+ export const jobEvent = z.object({
105
+ type: z.literal("job"),
106
+ jobId: z.uuid(),
107
+ /** The model's name in the agent's Ollama (one of its offered models). */
108
+ model: modelName,
109
+ messages: z.array(jobMessage).min(1),
110
+ options: jobOptions,
111
+ /** Stop and report an error if the job isn't finished after this many milliseconds. */
112
+ deadlineMs: ms,
113
+ });
114
+ export type JobEvent = z.infer<typeof jobEvent>;
115
+
116
+ export const cancelEvent = z.object({ type: z.literal("cancel"), jobId: z.uuid() });
117
+ export const configEvent = z.object({ type: z.literal("config"), maxConcurrent: z.number().int().min(1) });
118
+ export const pingEvent = z.object({ type: z.literal("ping") });
119
+
120
+ export const streamEvent = z.discriminatedUnion("type", [jobEvent, cancelEvent, configEvent, pingEvent]);
121
+ export type StreamEvent = z.infer<typeof streamEvent>;
122
+
123
+ /** Parses one event from the stream; null for unknown or broken events (ignored, never fatal). */
124
+ export function parseStreamEvent(data: unknown): StreamEvent | null {
125
+ const result = streamEvent.safeParse(data);
126
+ return result.success ? result.data : null;
127
+ }
128
+
129
+ // ---- job events (agent -> server) --------------------------------------------------------
130
+
131
+ export const deltaJobEvent = z.object({ type: z.literal("delta"), text: z.string().max(100_000) });
132
+ export const doneJobEvent = z.object({
133
+ type: z.literal("done"),
134
+ finishReason: z.enum(["stop", "length"]),
135
+ usage: z.object({ promptTokens: count, completionTokens: count }).optional(),
136
+ timings: z.object({ loadMs: ms.optional(), promptEvalMs: ms.optional(), evalMs: ms.optional() }).optional(),
137
+ });
138
+ /**
139
+ * Codes an agent reports. "thinking_not_supported" / "images_not_supported": Ollama refused think
140
+ * or images for this model (another host would refuse too). retryable = the server may try
141
+ * another host if nothing was sent yet. New codes are only ever added, never renamed.
142
+ */
143
+ export const AGENT_ERROR_CODES = [
144
+ "model_not_offered",
145
+ "ollama_unreachable",
146
+ "ollama_error",
147
+ "thinking_not_supported",
148
+ "images_not_supported",
149
+ "deadline_exceeded",
150
+ "busy",
151
+ "internal",
152
+ ] as const;
153
+ export const errorJobEvent = z.object({
154
+ type: z.literal("error"),
155
+ code: z.enum(AGENT_ERROR_CODES),
156
+ retryable: z.boolean(),
157
+ });
158
+
159
+ export const agentJobEvent = z.discriminatedUnion("type", [deltaJobEvent, doneJobEvent, errorJobEvent]);
160
+ export type AgentJobEvent = z.infer<typeof agentJobEvent>;
161
+
162
+ export const jobEventsRequest = z.object({
163
+ /** 0, 1, 2… per job: lets the server drop a batch it already got (the agent retried). */
164
+ seq: z.number().int().min(0).max(1_000_000),
165
+ events: z.array(agentJobEvent).min(1).max(500),
166
+ });
167
+ export type JobEventsRequest = z.infer<typeof jobEventsRequest>;
168
+
169
+ export const jobEventsResponse = z.object({ cancelled: z.boolean() });
170
+ export type JobEventsResponse = z.infer<typeof jobEventsResponse>;
171
+
172
+ // ---- heartbeat ---------------------------------------------------------------------------
173
+
174
+ export const heartbeatRequest = z.object({
175
+ gpu: z
176
+ .object({
177
+ name: shortText(100),
178
+ vramTotalMb: z.number().int().min(0).max(1_000_000),
179
+ vramUsedMb: z.number().int().min(0).max(1_000_000),
180
+ utilizationPct: z.number().min(0).max(100),
181
+ temperatureC: z.number().min(-50).max(150),
182
+ })
183
+ .optional(),
184
+ loadedModels: z
185
+ .array(z.object({ name: modelName, vramMb: z.number().int().min(0).max(1_000_000), expiresAt: shortText(40).optional() }))
186
+ .max(20),
187
+ ollamaVersion: shortText(40).optional(),
188
+ });
189
+ export type HeartbeatRequest = z.infer<typeof heartbeatRequest>;
190
+
191
+ export const heartbeatResponse = z.object({ ok: z.literal(true) });
192
+
193
+ // ---- errors ------------------------------------------------------------------------------
194
+
195
+ /** Every non-2xx answer of the agent API: a fixed code and a message for the owner. */
196
+ export const agentApiError = z.object({ error: z.object({ code: z.string(), message: z.string() }) });
197
+ export type AgentApiError = z.infer<typeof agentApiError>;
package/src/sse.ts ADDED
@@ -0,0 +1,50 @@
1
+ // Server-Sent Events, the small subset both sides use: every event is one `data:` line with a
2
+ // JSON object, then an empty line. Lines starting with ":" are comments (keep-alives).
3
+ // Shared by the server (writes the agent's job stream) and the host agent (reads it).
4
+
5
+ const encoder = new TextEncoder();
6
+
7
+ export function encodeSseData(value: unknown): Uint8Array {
8
+ return encoder.encode(`data: ${JSON.stringify(value)}\n\n`);
9
+ }
10
+
11
+ export function encodeSseComment(text: string): Uint8Array {
12
+ return encoder.encode(`: ${text.replace(/[\r\n]/g, " ")}\n\n`);
13
+ }
14
+
15
+ /**
16
+ * Reads a stream of SSE events and yields each event's data, parsed as JSON. Network packets can
17
+ * cut an event anywhere, so it buffers until a full event (ending in an empty line) has arrived.
18
+ * Comments and events whose data isn't JSON are skipped.
19
+ */
20
+ export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown> {
21
+ const reader = body.getReader();
22
+ const decoder = new TextDecoder();
23
+ let buffer = "";
24
+ try {
25
+ for (;;) {
26
+ const { value, done } = await reader.read();
27
+ if (done) break;
28
+ buffer += decoder.decode(value, { stream: true });
29
+ for (;;) {
30
+ const match = /\r?\n\r?\n/.exec(buffer);
31
+ if (!match) break;
32
+ const block = buffer.slice(0, match.index);
33
+ buffer = buffer.slice(match.index + match[0].length);
34
+ const data = block
35
+ .split(/\r?\n/)
36
+ .filter((line) => line.startsWith("data:"))
37
+ .map((line) => line.slice(5).replace(/^ /, ""))
38
+ .join("\n");
39
+ if (!data) continue;
40
+ try {
41
+ yield JSON.parse(data) as unknown;
42
+ } catch {
43
+ // not JSON: ignore, like an unknown event type
44
+ }
45
+ }
46
+ }
47
+ } finally {
48
+ reader.releaseLock();
49
+ }
50
+ }