@hosty-sdk/app 0.47.0 → 0.48.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.
@@ -0,0 +1,78 @@
1
+ import { type AgentAttachment, type AgentAttachmentChunk, type AgentAttachmentChunkReceipt, type AgentAuthorizer, type AgentAuthorizationRequest, type AgentCancelInput, type AgentCapabilities, type AgentConfigurationCreate, type AgentConnectionPage, type AgentConnectionUsage, type AgentControlReceipt, type AgentEvent, type AgentModelCatalog, type AgentOperation, type AgentPreparedRequest, type AgentProviderRef, type AgentResponseInput, type AgentRunControlInput, type AgentRunInput, type AgentRunSnapshot, type AgentSession, type AgentSessionCreate, type AgentSessionPage, type AgentWatchItem } from "./agent.js";
2
+ export type AgentClientOptions = {
3
+ provider: AgentProviderRef;
4
+ authorize: AgentAuthorizer;
5
+ fetch?: typeof fetch;
6
+ requestTimeoutMs?: number;
7
+ };
8
+ export type AgentRequestOptions = {
9
+ signal?: AbortSignal;
10
+ };
11
+ export type AgentWatchOptions = AgentRequestOptions & {
12
+ cursor?: string;
13
+ maxReconnects?: number;
14
+ reconnectDelayMs?: number;
15
+ };
16
+ /** Preparing once lets an application persist exactly the bytes it must reuse after an uncertain delivery. */
17
+ export declare function prepareAgentRequest<T>(operation: AgentOperation, method: "PUT" | "POST", path: string, input: unknown, metadata?: Omit<AgentAuthorizationRequest, "operation" | "method" | "path" | "bodyHash">): AgentPreparedRequest<T>;
18
+ export declare const prepareAgentSessionCreate: (sessionId: string, input: AgentSessionCreate) => AgentPreparedRequest<AgentSession>;
19
+ export declare const prepareAgentConfiguration: (sessionId: string, configurationId: string, input: AgentConfigurationCreate) => AgentPreparedRequest<AgentSession>;
20
+ export declare const prepareAgentRun: (sessionId: string, runId: string, input: AgentRunInput) => AgentPreparedRequest<AgentRunSnapshot>;
21
+ export declare const prepareAgentResponse: (runId: string, input: AgentResponseInput) => AgentPreparedRequest<AgentControlReceipt>;
22
+ export declare const prepareAgentCancel: (runId: string, input: AgentCancelInput) => AgentPreparedRequest<AgentControlReceipt>;
23
+ export declare const prepareAgentControl: (runId: string, input: AgentRunControlInput) => AgentPreparedRequest<AgentControlReceipt>;
24
+ export declare const prepareAgentAttachmentChunk: (attachmentId: string, index: number, input: AgentAttachmentChunk) => AgentPreparedRequest<AgentAttachmentChunkReceipt>;
25
+ /** Backend-to-backend transport. The authorizer talks to Core; only its scoped token reaches the provider. */
26
+ export declare class AgentClient {
27
+ private readonly options;
28
+ private readonly fetcher;
29
+ private readonly timeout;
30
+ constructor(options: AgentClientOptions);
31
+ private response;
32
+ private json;
33
+ private get;
34
+ /** No transport retry can change a prepared body's identity or begin a second run. */
35
+ execute<T>(request: AgentPreparedRequest<T>, options?: AgentRequestOptions): Promise<T>;
36
+ capabilities(options?: AgentRequestOptions): Promise<AgentCapabilities>;
37
+ connections(query?: {
38
+ cursor?: string;
39
+ limit?: number;
40
+ }, options?: AgentRequestOptions): Promise<AgentConnectionPage>;
41
+ models(connectionId: string, options?: AgentRequestOptions): Promise<AgentModelCatalog>;
42
+ connectionUsage(connectionId: string, options?: AgentRequestOptions): Promise<AgentConnectionUsage>;
43
+ createSession(sessionId: string, input: AgentSessionCreate, options?: AgentRequestOptions): Promise<AgentSession>;
44
+ session(sessionId: string, options?: AgentRequestOptions): Promise<AgentSession>;
45
+ sessions(query?: {
46
+ cursor?: string;
47
+ limit?: number;
48
+ }, options?: AgentRequestOptions): Promise<AgentSessionPage>;
49
+ configureSession(sessionId: string, configurationId: string, input: AgentConfigurationCreate, options?: AgentRequestOptions): Promise<AgentSession>;
50
+ startRun(sessionId: string, runId: string, input: AgentRunInput, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
51
+ run(runId: string, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
52
+ respond(runId: string, input: AgentResponseInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
53
+ cancel(runId: string, input: AgentCancelInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
54
+ control(runId: string, requestId: string, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
55
+ runControl(runId: string, input: AgentRunControlInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
56
+ prepareAttachmentChunk(attachmentId: string, index: number, input: AgentAttachmentChunk): AgentPreparedRequest<AgentAttachmentChunkReceipt>;
57
+ uploadAttachment(attachmentId: string, input: Uint8Array, metadata: {
58
+ mediaType: string;
59
+ name?: string;
60
+ }, options?: AgentRequestOptions): Promise<AgentAttachment>;
61
+ private checkSnapshot;
62
+ private validateResponse;
63
+ /** One authenticated stream; watchRun adds reconnect and atomic snapshot recovery. */
64
+ events(runId: string, options?: AgentRequestOptions & {
65
+ cursor?: string;
66
+ }): AsyncGenerator<{
67
+ event: AgentEvent;
68
+ cursor: string;
69
+ }>;
70
+ /** Snapshot items replace consumer state; event items are new, deduplicated persisted events. */
71
+ watchRun(runId: string, options?: AgentWatchOptions): AsyncGenerator<AgentWatchItem>;
72
+ }
73
+ /** Streaming decoder handles split UTF-8, CR/LF framing, multi-line data and comment heartbeats. */
74
+ export declare function parseAgentSse(response: Pick<Response, "body">, maxBytes?: number): AsyncGenerator<{
75
+ id: string;
76
+ event: string;
77
+ data: string;
78
+ }>;
@@ -0,0 +1,367 @@
1
+ import { createHash } from "node:crypto";
2
+ import { AgentApiError, } from "./agent.js";
3
+ import { validateAgentEvent, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
4
+ const MAX_BYTES = 1024 * 1024;
5
+ const sha = (body) => createHash("sha256").update(body, "utf8").digest("hex");
6
+ const segment = (id) => {
7
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(id))
8
+ throw new AgentApiError("invalid_input", "A bounded opaque resource ID is required.", 400);
9
+ return encodeURIComponent(id);
10
+ };
11
+ const sameProvider = (a, b) => a.appId === b.appId && a.installationId === b.installationId && a.key === b.key;
12
+ /** Preparing once lets an application persist exactly the bytes it must reuse after an uncertain delivery. */
13
+ export function prepareAgentRequest(operation, method, path, input, metadata = {}) {
14
+ const body = JSON.stringify(input);
15
+ if (typeof body !== "string" || Buffer.byteLength(body) > MAX_BYTES)
16
+ throw new AgentApiError("payload_budget", "The agent command exceeds its byte allowance.", 413);
17
+ validateAgentRequest(method, path, body, operation);
18
+ return { ...JSON.parse(JSON.stringify(metadata)), operation, method, path, body, bodyHash: sha(body) };
19
+ }
20
+ export const prepareAgentSessionCreate = (sessionId, input) => prepareAgentRequest("sessions.create", "PUT", `/sessions/${segment(sessionId)}`, input, { sessionId });
21
+ export const prepareAgentConfiguration = (sessionId, configurationId, input) => prepareAgentRequest("sessions.configure", "PUT", `/sessions/${segment(sessionId)}/configurations/${segment(configurationId)}`, input, { sessionId });
22
+ export const prepareAgentRun = (sessionId, runId, input) => prepareAgentRequest("runs.start", "PUT", `/sessions/${segment(sessionId)}/runs/${segment(runId)}`, input, { sessionId, runId, resources: input.resources, ceiling: { mcp: input.mcp, resources: input.resources, configurationRevision: input.configurationRevision } });
23
+ export const prepareAgentResponse = (runId, input) => prepareAgentRequest("runs.respond", "POST", `/runs/${segment(runId)}/responses`, input, { runId });
24
+ export const prepareAgentCancel = (runId, input) => prepareAgentRequest("runs.cancel", "POST", `/runs/${segment(runId)}/cancel`, input, { runId, ...(input.fenceIfNotAdmitted ? { sessionId: input.fenceIfNotAdmitted.sessionId } : {}) });
25
+ export const prepareAgentControl = (runId, input) => prepareAgentRequest("runs.control", "POST", `/runs/${segment(runId)}/controls`, input, { runId });
26
+ export const prepareAgentAttachmentChunk = (attachmentId, index, input) => prepareAgentRequest("attachments.write", "PUT", `/attachments/${segment(attachmentId)}/chunks/${index}`, input);
27
+ /** Backend-to-backend transport. The authorizer talks to Core; only its scoped token reaches the provider. */
28
+ export class AgentClient {
29
+ options;
30
+ fetcher;
31
+ timeout;
32
+ constructor(options) {
33
+ this.options = options;
34
+ if (!options.provider?.appId || !options.provider.installationId || !options.provider.key)
35
+ throw new AgentApiError("provider_selection_required", "Select an installation-qualified agent provider.", 400);
36
+ this.fetcher = options.fetch ?? globalThis.fetch;
37
+ this.timeout = options.requestTimeoutMs ?? 15000;
38
+ }
39
+ async response(request, body, options, stream = false) {
40
+ options.signal?.throwIfAborted();
41
+ const signal = stream ? options.signal : options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(this.timeout)]) : AbortSignal.timeout(this.timeout);
42
+ for (let attempt = 0; attempt < 2; attempt++) {
43
+ const binding = await this.options.authorize(request, signal);
44
+ if (!sameProvider(this.options.provider, binding.provider))
45
+ throw new AgentApiError("provider_changed", "The selected provider installation changed.", 409);
46
+ const base = new URL(binding.baseUrl);
47
+ if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash || !binding.token
48
+ || !Number.isFinite(Date.parse(binding.expiresAt)) || Date.parse(binding.expiresAt) <= Date.now())
49
+ throw new AgentApiError("authorization_invalid", "Core returned an invalid current provider binding.", 401);
50
+ const headers = { authorization: `Bearer ${binding.token}`, accept: stream ? "text/event-stream" : "application/json" };
51
+ if (body !== undefined)
52
+ headers["content-type"] = "application/json";
53
+ if (binding.admissionRef)
54
+ headers["X-Hosty-Agent-Admission"] = binding.admissionRef;
55
+ const response = await this.fetcher(base.href.replace(/\/$/, "") + request.path, { method: request.method, headers, body, signal, redirect: "error", cache: "no-store" });
56
+ if (response.status === 401 && attempt === 0) {
57
+ await response.body?.cancel();
58
+ continue;
59
+ }
60
+ return response;
61
+ }
62
+ throw new AgentApiError("token_invalid", "Agent authorization expired.", 401);
63
+ }
64
+ async json(response) {
65
+ const raw = await boundedText(response, MAX_BYTES);
66
+ let value;
67
+ try {
68
+ value = JSON.parse(raw);
69
+ }
70
+ catch {
71
+ throw new AgentApiError("response_invalid", "The provider returned invalid JSON.", 502);
72
+ }
73
+ if (!response.ok) {
74
+ const error = value?.error;
75
+ throw new AgentApiError(error?.code ?? "provider_failed", error?.message ?? `Agent request failed (${response.status}).`, response.status, error?.retryable === true, error?.details, error?.requestId);
76
+ }
77
+ return value;
78
+ }
79
+ async get(operation, path, options = {}, metadata = {}) {
80
+ const request = { ...metadata, operation, method: "GET", path, bodyHash: sha("") };
81
+ validateAgentRequest("GET", path, "", operation);
82
+ const value = await this.json(await this.response(request, undefined, options));
83
+ this.validateResponse(request, value);
84
+ return value;
85
+ }
86
+ /** No transport retry can change a prepared body's identity or begin a second run. */
87
+ async execute(request, options = {}) {
88
+ if (request.bodyHash !== sha(request.body))
89
+ throw new AgentApiError("request_digest_mismatch", "The prepared command bytes changed.", 409);
90
+ validateAgentRequest(request.method, request.path, request.body, request.operation);
91
+ const { body, __result: _result, ...metadata } = request;
92
+ const value = await this.json(await this.response(metadata, body, options));
93
+ this.validateResponse(metadata, value);
94
+ return value;
95
+ }
96
+ capabilities(options) { return this.get("capabilities", "/capabilities", options); }
97
+ connections(query = {}, options) { return this.get("connections.list", "/connections" + queryString(query), options); }
98
+ models(connectionId, options) { return this.get("connections.models", `/connections/${segment(connectionId)}/models`, options); }
99
+ connectionUsage(connectionId, options) { return this.get("connections.usage", `/connections/${segment(connectionId)}/usage`, options); }
100
+ createSession(sessionId, input, options) { return this.execute(prepareAgentSessionCreate(sessionId, input), options); }
101
+ session(sessionId, options) { return this.get("sessions.read", `/sessions/${segment(sessionId)}`, options, { sessionId }); }
102
+ sessions(query = {}, options) { return this.get("sessions.list", "/sessions" + queryString(query), options); }
103
+ configureSession(sessionId, configurationId, input, options) { return this.execute(prepareAgentConfiguration(sessionId, configurationId, input), options); }
104
+ startRun(sessionId, runId, input, options) { return this.execute(prepareAgentRun(sessionId, runId, input), options); }
105
+ async run(runId, options) {
106
+ const value = await this.get("runs.read", `/runs/${segment(runId)}`, options, { runId });
107
+ this.checkSnapshot(value, runId);
108
+ return value;
109
+ }
110
+ respond(runId, input, options) { return this.execute(prepareAgentResponse(runId, input), options); }
111
+ cancel(runId, input, options) { return this.execute(prepareAgentCancel(runId, input), options); }
112
+ control(runId, requestId, options) { return this.get("runs.controls.read", `/runs/${segment(runId)}/controls/${segment(requestId)}`, options, { runId }); }
113
+ runControl(runId, input, options) { return this.execute(prepareAgentControl(runId, input), options); }
114
+ prepareAttachmentChunk(attachmentId, index, input) { return prepareAgentAttachmentChunk(attachmentId, index, input); }
115
+ async uploadAttachment(attachmentId, input, metadata, options) {
116
+ const bytes = Buffer.from(input), digest = createHash("sha256").update(bytes).digest("hex");
117
+ if (bytes.byteLength > 25 * 1024 * 1024)
118
+ throw new AgentApiError("payload_budget", "An attachment exceeds 25 MiB.", 413);
119
+ const count = Math.max(1, Math.ceil(bytes.byteLength / (512 * 1024)));
120
+ let completed = null;
121
+ for (let index = 0; index < count; index++) {
122
+ const receipt = await this.execute(prepareAgentAttachmentChunk(attachmentId, index, { digest, sizeBytes: bytes.byteLength, mediaType: metadata.mediaType, ...(metadata.name !== undefined ? { name: metadata.name } : {}), count, data: bytes.subarray(index * 512 * 1024, (index + 1) * 512 * 1024).toString("base64") }), options);
123
+ if (receipt.attachment)
124
+ completed = receipt.attachment;
125
+ }
126
+ if (!completed || completed.digest !== digest || completed.sizeBytes !== bytes.byteLength || completed.mediaType !== metadata.mediaType)
127
+ throw new AgentApiError("response_invalid", "The provider did not publish the intended immutable attachment.", 502);
128
+ return completed;
129
+ }
130
+ checkSnapshot(value, runId) {
131
+ validateAgentRunSnapshot(value);
132
+ if (value.ref.id !== runId || !sameProvider(this.options.provider, value.ref.provider))
133
+ throw new AgentApiError("response_invalid", "The snapshot belongs to another run or provider.", 502);
134
+ }
135
+ validateResponse(request, value) {
136
+ const invalid = () => { throw new AgentApiError("response_invalid", "The provider returned an invalid operation result.", 502); };
137
+ const record = value;
138
+ if (request.operation === "capabilities")
139
+ validateAgentCapabilities(value);
140
+ else if (["sessions.create", "sessions.configure", "sessions.read"].includes(request.operation)) {
141
+ validateAgentSession(value);
142
+ if (!sameProvider(this.options.provider, value.ref.provider) || value.ref.id !== request.sessionId)
143
+ invalid();
144
+ }
145
+ else if (request.operation === "sessions.list") {
146
+ const items = record?.sessions;
147
+ if (!Array.isArray(items) || items.length > 100 || !(record?.nextCursor === null || typeof record?.nextCursor === "string"))
148
+ invalid();
149
+ for (const session of items) {
150
+ validateAgentSession(session);
151
+ if (!sameProvider(this.options.provider, session.ref.provider))
152
+ invalid();
153
+ }
154
+ }
155
+ else if (request.operation === "runs.start" || request.operation === "runs.read") {
156
+ this.checkSnapshot(value, request.runId);
157
+ if (request.sessionId && value.sessionId !== request.sessionId)
158
+ invalid();
159
+ }
160
+ else if (["runs.respond", "runs.cancel", "runs.control", "runs.controls.read"].includes(request.operation)) {
161
+ validateAgentControlReceipt(value);
162
+ if (value.run.id !== request.runId || !sameProvider(this.options.provider, value.run.provider))
163
+ invalid();
164
+ if (request.operation === "runs.controls.read" && value.requestId !== request.path.split("/").at(-1))
165
+ invalid();
166
+ }
167
+ else if (request.operation === "connections.list") {
168
+ const items = record?.connections;
169
+ if (!Array.isArray(items) || items.length > 100 || !(record?.nextCursor === null || typeof record?.nextCursor === "string"))
170
+ invalid();
171
+ for (const connection of items)
172
+ if (!connection || typeof connection.id !== "string" || typeof connection.name !== "string" || typeof connection.ready !== "boolean" || typeof connection.revision !== "string" || !/^[1-9][0-9]*$/.test(connection.revision))
173
+ invalid();
174
+ }
175
+ else if (request.operation === "connections.models") {
176
+ if (!record || typeof record.revision !== "string" || !record.revision.length || record.revision.length > 256 || !Array.isArray(record.models) || record.models.length > 1000 || !(record.defaultModel === null || typeof record.defaultModel === "string"))
177
+ invalid();
178
+ for (const model of record.models)
179
+ if (!model || typeof model.id !== "string" || !Array.isArray(model.reasoningEfforts) || model.reasoningEfforts.some(v => v !== null && typeof v !== "string"))
180
+ invalid();
181
+ }
182
+ else if (request.operation === "attachments.write") {
183
+ if (!record || !Array.isArray(record.received) || record.received.length > 50 || record.received.some(i => !Number.isSafeInteger(i) || i < 0 || i >= 50) || new Set(record.received).size !== record.received.length)
184
+ invalid();
185
+ const attachment = record.attachment;
186
+ if (attachment !== null && (!attachment || !sameProvider(this.options.provider, attachment.owner) || typeof attachment.id !== "string" || !/^[a-f0-9]{64}$/.test(attachment.digest) || !Number.isSafeInteger(attachment.sizeBytes) || attachment.sizeBytes < 0 || typeof attachment.mediaType !== "string"))
187
+ invalid();
188
+ }
189
+ else if (request.operation === "connections.usage" && (!record || typeof record.available !== "boolean" || typeof record.observedAt !== "string" || !Number.isFinite(Date.parse(record.observedAt))))
190
+ invalid();
191
+ }
192
+ /** One authenticated stream; watchRun adds reconnect and atomic snapshot recovery. */
193
+ async *events(runId, options = {}) {
194
+ const path = `/runs/${segment(runId)}/events` + queryString({ after: options.cursor });
195
+ const response = await this.response({ operation: "runs.events", method: "GET", path, bodyHash: sha(""), runId }, undefined, options, true);
196
+ if (!response.ok) {
197
+ await this.json(response);
198
+ return;
199
+ }
200
+ if (!response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase().includes("text/event-stream"))
201
+ throw new AgentApiError("response_invalid", "The provider did not return an event stream.", 502);
202
+ for await (const frame of parseAgentSse(response, MAX_BYTES)) {
203
+ if (frame.event !== "agent")
204
+ continue;
205
+ let event;
206
+ try {
207
+ event = JSON.parse(frame.data);
208
+ }
209
+ catch {
210
+ throw new AgentApiError("event_invalid", "The provider returned an invalid event.", 502);
211
+ }
212
+ validateAgentEvent(event);
213
+ if (event.runId !== runId || !frame.id)
214
+ throw new AgentApiError("event_invalid", "The event does not identify this run and replay cursor.", 502);
215
+ if (event.type === "run.updated")
216
+ this.checkSnapshot(event.data.snapshot, runId);
217
+ yield { event, cursor: frame.id };
218
+ }
219
+ }
220
+ /** Snapshot items replace consumer state; event items are new, deduplicated persisted events. */
221
+ async *watchRun(runId, options = {}) {
222
+ let snapshot = await this.run(runId, options);
223
+ yield { kind: "snapshot", snapshot };
224
+ let cursor = snapshot.cursor, sequence = BigInt(snapshot.lastSequence), generation = snapshot.generation;
225
+ let retries = 0;
226
+ const max = options.maxReconnects ?? 5;
227
+ if (!Number.isSafeInteger(max) || max < 0 || max > 100 || options.reconnectDelayMs !== undefined && (!Number.isSafeInteger(options.reconnectDelayMs) || options.reconnectDelayMs < 0 || options.reconnectDelayMs > 60000))
228
+ throw new AgentApiError("invalid_input", "Invalid bounded reconnect policy.", 400);
229
+ while (!options.signal?.aborted) {
230
+ if (snapshot.stopConfirmed && ["succeeded", "failed", "cancelled"].includes(snapshot.state))
231
+ return;
232
+ try {
233
+ for await (const item of this.events(runId, { signal: options.signal, cursor })) {
234
+ if (item.event.generation !== generation)
235
+ throw new AgentApiError("event_generation_changed", "A run's durable generation changed.", 409);
236
+ const next = BigInt(item.event.sequence);
237
+ if (next <= sequence)
238
+ continue;
239
+ if (next !== sequence + 1n)
240
+ throw new AgentApiError("event_gap", "Resynchronize the run after a missing event.", 409, true);
241
+ sequence = next;
242
+ cursor = item.cursor;
243
+ retries = 0;
244
+ if (item.event.type === "run.updated")
245
+ snapshot = item.event.data.snapshot;
246
+ yield { kind: "event", ...item };
247
+ if (snapshot.stopConfirmed && ["succeeded", "failed", "cancelled"].includes(snapshot.state))
248
+ return;
249
+ }
250
+ if (++retries > max)
251
+ throw new AgentApiError("stream_closed", "The provider repeatedly closed its active stream.", 503, true);
252
+ }
253
+ catch (error) {
254
+ if (options.signal?.aborted)
255
+ throw options.signal.reason;
256
+ if (error instanceof AgentApiError && error.status !== 410 && error.code !== "event_gap" && !error.retryable && ![429, 503, 504].includes(error.status))
257
+ throw error;
258
+ if (error instanceof AgentApiError && error.code === "stream_closed" || ++retries > max)
259
+ throw error;
260
+ }
261
+ options.signal?.throwIfAborted();
262
+ snapshot = await this.run(runId, options);
263
+ if (snapshot.generation !== generation)
264
+ throw new AgentApiError("event_generation_changed", "A run's durable generation changed.", 409);
265
+ cursor = snapshot.cursor;
266
+ sequence = BigInt(snapshot.lastSequence);
267
+ generation = snapshot.generation;
268
+ yield { kind: "snapshot", snapshot };
269
+ if (!snapshot.stopConfirmed)
270
+ await pause(options.reconnectDelayMs ?? 250, options.signal);
271
+ }
272
+ options.signal?.throwIfAborted();
273
+ }
274
+ }
275
+ function queryString(value) {
276
+ const query = new URLSearchParams();
277
+ for (const [key, item] of Object.entries(value))
278
+ if (item !== undefined)
279
+ query.set(key, String(item));
280
+ return query.size ? "?" + query.toString() : "";
281
+ }
282
+ async function boundedText(response, max) {
283
+ const reader = response.body?.getReader();
284
+ if (!reader)
285
+ return "";
286
+ const chunks = [];
287
+ let size = 0;
288
+ try {
289
+ while (true) {
290
+ const item = await reader.read();
291
+ if (item.done)
292
+ break;
293
+ size += item.value.byteLength;
294
+ if (size > max)
295
+ throw new AgentApiError("response_budget", "The provider response exceeds its byte allowance.", 502);
296
+ chunks.push(item.value);
297
+ }
298
+ }
299
+ finally {
300
+ await reader.cancel().catch(() => { });
301
+ reader.releaseLock();
302
+ }
303
+ return Buffer.concat(chunks).toString("utf8");
304
+ }
305
+ /** Streaming decoder handles split UTF-8, CR/LF framing, multi-line data and comment heartbeats. */
306
+ export async function* parseAgentSse(response, maxBytes = MAX_BYTES) {
307
+ const reader = response.body?.getReader();
308
+ if (!reader)
309
+ throw new AgentApiError("event_invalid", "The event stream is empty.", 502);
310
+ const decoder = new TextDecoder("utf-8", { fatal: true });
311
+ let buffer = "", id = "", event = "message", data = [], bytes = 0;
312
+ try {
313
+ while (true) {
314
+ const chunk = await reader.read();
315
+ buffer += decoder.decode(chunk.value, { stream: !chunk.done });
316
+ let match;
317
+ while ((match = /\r\n|\r|\n/.exec(buffer))) {
318
+ // A CR at a chunk boundary may be the first half of CRLF.
319
+ if (!chunk.done && match[0] === "\r" && match.index === buffer.length - 1)
320
+ break;
321
+ const line = buffer.slice(0, match.index);
322
+ buffer = buffer.slice(match.index + match[0].length);
323
+ bytes += Buffer.byteLength(line) + 1;
324
+ if (bytes > maxBytes + 8192)
325
+ throw new AgentApiError("event_budget", "An event exceeds its byte allowance.", 502);
326
+ if (!line) {
327
+ if (data.length)
328
+ yield { id, event, data: data.join("\n") };
329
+ id = "";
330
+ event = "message";
331
+ data = [];
332
+ bytes = 0;
333
+ continue;
334
+ }
335
+ if (line.startsWith(":"))
336
+ continue;
337
+ const colon = line.indexOf(":"), field = colon < 0 ? line : line.slice(0, colon);
338
+ let value = colon < 0 ? "" : line.slice(colon + 1);
339
+ if (value.startsWith(" "))
340
+ value = value.slice(1);
341
+ if (field === "id" && !value.includes("\0"))
342
+ id = value;
343
+ else if (field === "event")
344
+ event = value;
345
+ else if (field === "data")
346
+ data.push(value);
347
+ }
348
+ if (Buffer.byteLength(buffer) + bytes > maxBytes + 8192)
349
+ throw new AgentApiError("event_budget", "An event exceeds its byte allowance.", 502);
350
+ if (chunk.done)
351
+ break; // An incomplete final frame is never acknowledged as a persisted event.
352
+ }
353
+ }
354
+ finally {
355
+ await reader.cancel().catch(() => { });
356
+ reader.releaseLock();
357
+ }
358
+ }
359
+ async function pause(ms, signal) {
360
+ signal?.throwIfAborted();
361
+ await new Promise((resolve, reject) => {
362
+ const done = () => { signal?.removeEventListener("abort", abort); resolve(); };
363
+ const timer = setTimeout(done, ms);
364
+ const abort = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); reject(signal?.reason); };
365
+ signal?.addEventListener("abort", abort, { once: true });
366
+ });
367
+ }
@@ -0,0 +1,6 @@
1
+ /** Machine-readable public contract. Payload-free Core admission is a separate platform API. */
2
+ type Schema = Record<string, unknown>;
3
+ export declare const AGENT_SCHEMAS: Record<string, Schema>;
4
+ export declare const AGENT_OPENAPI: Schema;
5
+ export declare const AGENT_EVENT_SCHEMA: Schema;
6
+ export {};
@@ -0,0 +1,138 @@
1
+ const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
2
+ const text = (maxLength = 256) => ({ type: "string", minLength: 1, maxLength });
3
+ const id = { type: "string", pattern: "^[A-Za-z0-9_-]{1,256}$" };
4
+ const uuid = { type: "string", format: "uuid" };
5
+ const revision = { type: "string", pattern: "^[1-9][0-9]{0,39}$" };
6
+ const sequence = { type: "string", pattern: "^(0|[1-9][0-9]{0,39})$" };
7
+ const digest = { type: "string", pattern: "^[a-f0-9]{64}$" };
8
+ const boolean = { type: "boolean" };
9
+ const positive = { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER };
10
+ const nullableText = { type: ["string", "null"], maxLength: 256 };
11
+ const list = (items, maxItems = 128) => ({ type: "array", maxItems, items });
12
+ const unique = (items, maxItems = 128) => ({ ...list(items, maxItems), uniqueItems: true });
13
+ const object = (properties, required = Object.keys(properties), additionalProperties = false) => ({ type: "object", properties, required, additionalProperties });
14
+ const capability = unique({ ...text(), pattern: "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)*$" }, 128);
15
+ const refProperties = { appId: text(), installationId: text(), key: text() };
16
+ const baseControl = { requestId: uuid, expectedGeneration: uuid, expectedRevision: revision };
17
+ const terminalStates = ["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"];
18
+ const phases = ["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"];
19
+ export const AGENT_SCHEMAS = {
20
+ ProviderRef: object(refProperties),
21
+ QualifiedRef: object({ provider: ref("ProviderRef"), id }),
22
+ Instruction: object({ id: text(128), text: { type: "string", maxLength: 262144 } }),
23
+ Skill: object({ skillId: digest, expectedDigest: digest }, ["skillId"]),
24
+ McpTarget: { oneOf: [object({ kind: { const: "core" } }), object({ kind: { const: "app" }, ...refProperties })] },
25
+ McpPolicy: object({ default: { enum: ["ask", "run"] }, autoAllowReadOnly: boolean, tools: { type: "object", maxProperties: 512, propertyNames: text(), additionalProperties: { oneOf: [object({ mode: { const: "run" }, definition: digest }), object({ mode: { enum: ["ask", "disabled"] } })] } } }, ["default"]),
26
+ McpSelection: object({ targets: list(object({ target: ref("McpTarget"), tools: unique(text(), 512), policy: ref("McpPolicy") }, ["target"]), 16), connections: list(object({ id, revision }), 16) }, []),
27
+ Configuration: object({ connection: object({ id, revision }), instructions: list(ref("Instruction"), 16),
28
+ systemPrompt: object({ mode: { const: "append" }, text: { type: "string", maxLength: 262144 } }), skills: list(ref("Skill"), 202),
29
+ nativeTools: { enum: ["provider_default", "none"] }, approvalMode: { enum: ["normal", "autonomous"] }, predictions: object({ enabled: boolean }), subagents: object({ enabled: boolean, maxConcurrency: { type: "integer", minimum: 1, maximum: 128 } }, ["enabled"]) }, ["connection"]),
30
+ SessionCreate: object({ configuration: ref("Configuration"), requiredCapabilities: capability,
31
+ correlation: object({ conversation: ref("QualifiedRef"), task: ref("QualifiedRef") }, []) }, ["configuration"]),
32
+ ConfigurationCreate: object({ requestId: uuid, expectedSessionRevision: revision, configuration: ref("Configuration"), requiredCapabilities: capability }, ["requestId", "expectedSessionRevision", "configuration"]),
33
+ Attachment: object({ owner: ref("ProviderRef"), id, digest, sizeBytes: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, mediaType: text(128), name: text() }, ["owner", "id", "digest", "sizeBytes", "mediaType"]),
34
+ AttachmentChunk: object({ digest, sizeBytes: { type: "integer", minimum: 0, maximum: 26214400 }, mediaType: text(128), name: text(), count: { type: "integer", minimum: 1, maximum: 50 }, data: { type: "string", maxLength: 699052, contentEncoding: "base64" } }, ["digest", "sizeBytes", "mediaType", "count", "data"]),
35
+ AttachmentChunkReceipt: object({ attachment: { oneOf: [ref("Attachment"), { type: "null" }] }, received: unique({ type: "integer", minimum: 0, maximum: 49 }, 50) }),
36
+ Resource: object({ kind: text(64), id, revision: text(), provider: ref("ProviderRef") }, ["kind", "id", "revision"]),
37
+ Selection: object({ model: nullableText, reasoningEffort: nullableText }),
38
+ RunInput: object({ expectedSessionRevision: revision, configurationRevision: revision, continuation: { enum: ["start", "resume"] },
39
+ input: { oneOf: [object({ text: text(1048576), attachments: list(ref("Attachment"), 20) }, ["text"]), object({ decisionResponseRef: object({ runId: id, requestId: uuid }) })] },
40
+ context: list(ref("Instruction"), 16), selection: ref("Selection"), resources: list(ref("Resource"), 16), mcp: ref("McpSelection"), requiredCapabilities: capability,
41
+ limits: object({ maxDurationMs: positive, maxOutputTokens: positive, maxToolCalls: positive }, []) }, ["expectedSessionRevision", "configurationRevision", "continuation", "input"]),
42
+ DecisionResponse: { oneOf: [object({ kind: { const: "approval" }, decision: { enum: ["allow", "deny"] }, message: { type: "string", maxLength: 65536 } }, ["kind", "decision"]),
43
+ object({ kind: { const: "question" }, answers: { type: "object", maxProperties: 128, propertyNames: id, additionalProperties: { oneOf: [{ type: "string", maxLength: 65536 }, list({ type: "string", maxLength: 65536 }, 128)] } } })] },
44
+ ResponseInput: object({ ...baseControl, decisionId: id, decisionRevision: revision, response: ref("DecisionResponse") }),
45
+ CancelInput: { oneOf: [object(baseControl), object({ requestId: uuid, fenceIfNotAdmitted: object({ sessionId: id, startDigest: digest }) })] },
46
+ ControlInput: { oneOf: [
47
+ object({ ...baseControl, command: { const: "park" }, decisionId: id, decisionRevision: revision, reason: text(8192) }, [...Object.keys(baseControl), "command", "decisionId", "decisionRevision"]),
48
+ object({ ...baseControl, command: { const: "barrier" }, barrierId: id, kind: { enum: ["task_adoption", "child_wait", "source_rebind", "limits", "human_input"] }, generation: revision, acknowledgedSequence: sequence, snapshot: text(8192) }, [...Object.keys(baseControl), "command", "barrierId", "kind", "generation", "acknowledgedSequence"]),
49
+ object({ ...baseControl, command: { const: "reconcile" }, stopped: { const: true }, evidence: text(8192) }, [...Object.keys(baseControl), "command", "stopped"]),
50
+ object({ ...baseControl, command: { const: "liveConfigure" }, mcp: ref("McpSelection") }),
51
+ object({ ...baseControl, command: { const: "mcpPolicy" }, mcp: ref("McpSelection") }),
52
+ object({ ...baseControl, command: { const: "predictions" }, enabled: boolean }),
53
+ ] },
54
+ Source: object({ agentId: id, parentAgentId: id, parentToolCallId: id }, ["agentId"]),
55
+ PendingDecision: object({ id, revision, kind: { enum: ["approval", "question"] }, delivery: { enum: ["continue_run", "next_turn"] }, source: ref("Source"), title: text(65536), toolCallId: id, toolName: text(), input: {},
56
+ questions: list(object({ id, text: text(65536), header: text(1024), allowText: boolean, multiple: boolean, required: boolean,
57
+ options: list(object({ id, label: text(8192), description: text(8192), preview: text(65536) }, ["id", "label"]), 128) }, ["id", "text"]), 128) }, ["id", "revision", "kind", "delivery"], true),
58
+ Result: object({ status: { enum: ["succeeded", "failed", "cancelled"] }, messageId: id, text: { type: "string", maxLength: 1048576 }, value: {}, schemaValid: boolean, error: ref("ErrorDetail") }, ["status"], true),
59
+ Message: object({ id, source: ref("Source"), role: { enum: ["assistant", "user", "system"] }, text: { type: "string", maxLength: 1048576 }, state: { enum: ["streaming", "complete", "interrupted"] } }, ["id", "role", "text", "state"], true),
60
+ Tool: object({ id, source: ref("Source"), name: text(), input: {}, output: { type: "string", maxLength: 1048576 }, state: { enum: ["running", "completed", "failed", "cancelled", "unknown"] }, truncated: boolean,
61
+ command: object({ status: { enum: ["completed", "failed", "cancelled", "unknown"] }, exitCode: { type: "integer" }, durationMs: { type: "integer", minimum: 0 }, summary: text(65536) }, ["status"]) }, ["id", "name", "state"], true),
62
+ RunSnapshot: object({ ref: ref("QualifiedRef"), sessionId: id, generation: uuid, revision: sequence,
63
+ state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, freshness: { enum: ["current", "last_known", "unavailable"] }, observedAt: { type: "string", format: "date-time" },
64
+ configurationRevision: revision, lastSequence: sequence, cursor: text(8192), pending: list(ref("PendingDecision"), 256),
65
+ effects: object({ certainty: { enum: ["known", "unknown"] }, unresolvedCallIds: unique(id, 1024) }), result: ref("Result"), messages: list(ref("Message"), 4096), tools: list(ref("Tool"), 4096),
66
+ agents: list(object({ agentId: id, parentAgentId: id, parentToolCallId: id, state: { enum: terminalStates }, stopConfirmed: boolean }, ["agentId", "state"], true), 1024),
67
+ selection: object({ requested: ref("Selection"), effective: ref("Selection") }), admissionRef: text(),
68
+ coverage: object({ messages: { enum: ["complete", "truncated"] }, tools: { enum: ["complete", "truncated"] }, decisions: { enum: ["complete", "truncated"] } }, ["messages", "tools"]),
69
+ executionUsage: object({ sequence, activeMs: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, unknown: boolean }),
70
+ latestContext: { ...object({ sequence: revision, usage: { type: ["object", "null"], additionalProperties: true } }),
71
+ description: "Latest root context.updated observation within the snapshot watermark; its canonical positive sequence is at most lastSequence. Null usage explicitly clears the observation. Absence means no retained observation. Payloads share the bounded snapshot/event JSON byte allowance." },
72
+ decisions: list(object({ decision: ref("PendingDecision"), state: { enum: ["pending", "resolved", "superseded", "unknown"] }, response: ref("DecisionResponse") }, ["decision", "state"]), 256),
73
+ pendingContinuations: list(object({ requestId: uuid, run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }), 256) }, ["ref", "sessionId", "generation", "revision", "state", "phase", "stopConfirmed", "freshness", "observedAt", "configurationRevision", "lastSequence", "cursor", "pending", "effects"], true),
74
+ Session: object({ ref: ref("QualifiedRef"), revision, configurationRevision: revision, configurationDigest: digest,
75
+ nativeState: { enum: ["not_created", "available", "missing", "unavailable", "unknown"] }, activeRun: { oneOf: [ref("QualifiedRef"), { type: "null" }] },
76
+ resolvedSkills: list(object({ skillId: digest, digest }), 202), configuration: ref("Configuration"), correlation: object({ conversation: ref("QualifiedRef"), task: ref("QualifiedRef") }, []) }, ["ref", "revision", "configurationRevision", "configurationDigest", "nativeState", "activeRun", "resolvedSkills"], true),
77
+ ControlReceipt: object({ requestId: uuid, state: { enum: ["accepted", "applied", "rejected", "superseded", "unknown"] }, run: ref("QualifiedRef"), revision: sequence, generation: uuid, error: ref("ErrorDetail"),
78
+ continuation: object({ run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }) }, ["requestId", "state", "run", "revision"], true),
79
+ ErrorDetail: object({ code: text(), message: { type: "string", maxLength: 8192 }, retryable: boolean, requestId: uuid, details: { type: "object", additionalProperties: true } }, ["code", "message", "retryable"], true),
80
+ Error: object({ error: ref("ErrorDetail") }),
81
+ Connection: object({ id, revision, name: text(), ready: boolean, reason: text(8192), capabilities: capability }, ["id", "revision", "name", "ready"], true),
82
+ ModelCatalog: object({ revision: text(256), models: list(object({ id: text(), name: text(), reasoningEfforts: list(nullableText), defaultReasoningEffort: nullableText, capabilities: capability, unavailableReason: text(8192) }, ["id", "reasoningEfforts"], true), 1000), defaultModel: nullableText, nextCursor: { type: ["string", "null"], maxLength: 8192 } }, ["revision", "models", "defaultModel"], true),
83
+ Capabilities: object({ version: { const: 1 }, eventVersions: unique(text(), 16), capabilities: capability,
84
+ limits: object({ maxCommandBytes: positive, maxEventBytes: positive, maxSnapshotBytes: positive, maxReplayBytes: positive, replayRetentionMs: positive, maxControls: positive, maxPageSize: positive, maxDurationMs: positive, maxSkillSnapshotBytes: positive, maxSkillSnapshotFiles: positive }, ["maxCommandBytes", "maxEventBytes", "maxSnapshotBytes", "maxReplayBytes", "replayRetentionMs", "maxControls", "maxPageSize"], true), configuration: object({ resumeCompatible: unique(text(), 32) }) }, ["version", "eventVersions", "capabilities", "limits", "configuration"], true),
85
+ };
86
+ const eventNames = ["run.updated", "session.bound", "selection.updated", "message.started", "message.delta", "message.completed", "tool.started", "tool.output", "tool.completed", "decision.requested", "decision.updated", "decision.resolved", "control.updated", "result.available", "usage.updated", "context.updated", "agent.updated", "warning", "extension"];
87
+ AGENT_SCHEMAS.Event = { ...object({ schemaVersion: { const: "agent-event.1" }, runId: id, generation: uuid, sequence: revision, revision: sequence,
88
+ occurredAt: { type: "string", format: "date-time" }, type: { enum: eventNames }, source: ref("Source"), data: { type: "object", additionalProperties: true } }),
89
+ allOf: eventNames.map(name => ({ if: { properties: { type: { const: name } } }, then: { properties: { data: name === "run.updated" ? object({ snapshot: ref("RunSnapshot") }, ["snapshot"], true)
90
+ : name.startsWith("message.") ? object({ messageId: id, text: { type: "string" } }, name === "message.delta" ? ["messageId", "text"] : ["messageId"], true)
91
+ : name.startsWith("tool.") ? object({ toolCallId: id, name: text(), output: { type: "string" } }, name === "tool.output" ? ["toolCallId", "output"] : ["toolCallId"], true)
92
+ : name.startsWith("decision.") ? object({ decisionId: id, decision: ref("PendingDecision") }, ["decisionId"], true)
93
+ : name === "control.updated" ? object({ requestId: uuid, receipt: ref("ControlReceipt") }, ["requestId"], true)
94
+ : name === "session.bound" ? object({ sessionId: id }, ["sessionId"], true)
95
+ : name === "context.updated" ? object({ usage: { type: ["object", "null"], additionalProperties: true } }, ["usage"], true)
96
+ : name === "extension" ? object({ namespace: text(), required: { const: false }, payload: {} }, ["namespace"], true)
97
+ : { type: "object", additionalProperties: true } } } })),
98
+ };
99
+ const page = (key, item) => object({ [key]: list(ref(item), 100), nextCursor: { type: ["string", "null"], maxLength: 8192 } });
100
+ AGENT_SCHEMAS.SessionPage = page("sessions", "Session");
101
+ AGENT_SCHEMAS.ConnectionPage = page("connections", "Connection");
102
+ AGENT_SCHEMAS.ConnectionUsage = object({ observedAt: { type: "string", format: "date-time" }, available: boolean, data: { type: "object", additionalProperties: true } }, ["observedAt", "available"], true);
103
+ const parameter = (name) => ({ name, in: "path", required: true, schema: id });
104
+ const errors = Object.fromEntries([400, 401, 403, 404, 409, 410, 413, 422, 429, 503].map(status => [String(status), { description: "Structured agent error; retryable never authorizes another mutation UUID.", content: { "application/json": { schema: ref("Error") } } }]));
105
+ function operation(operationId, response, input, pathParameters = [], statuses = [200]) {
106
+ return { operationId, security: [{ coreOperation: [] }], parameters: pathParameters.map(parameter), ...(input ? { requestBody: { required: true, content: { "application/json": { schema: ref(input) } } } } : {}),
107
+ responses: { ...errors, ...Object.fromEntries(statuses.map(status => [String(status), { description: "Authorized durable result.", headers: { "Cache-Control": { schema: { const: "no-store" } } }, content: { "application/json": { schema: ref(response) } } }])) } };
108
+ }
109
+ export const AGENT_OPENAPI = {
110
+ openapi: "3.1.0", info: { title: "Hosty Agent Execution API", version: "1.0.0", description: "Independent provider execution. Paths are relative to the current Core-declared interface base. Exact UTF-8 command bytes and stable mutation UUIDs are retained across retries. No Harness dependency or raw native session IDs." },
111
+ paths: {
112
+ "/capabilities": { get: operation("capabilities", "Capabilities") },
113
+ "/connections": { get: operation("connections.list", "ConnectionPage") },
114
+ "/connections/{connectionId}/models": { get: operation("connections.models", "ModelCatalog", undefined, ["connectionId"]) },
115
+ "/connections/{connectionId}/usage": { get: { ...operation("connections.usage", "ConnectionUsage", undefined, ["connectionId"]), description: "Optional connections.usage capability." } },
116
+ "/attachments/{attachmentId}/chunks/{index}": { put: { ...operation("attachments.write", "AttachmentChunkReceipt", "AttachmentChunk", ["attachmentId", "index"], [200, 201]), description: "Stable upload UUID, zero-based chunk index. At most 512 KiB decoded per chunk and 25 MiB/file; exact retries are actor scoped. Final completion publishes an immutable provider-owned attachment reference." } },
117
+ "/sessions": { get: operation("sessions.list", "SessionPage") },
118
+ "/sessions/{sessionId}": { get: operation("sessions.read", "Session", undefined, ["sessionId"]), put: operation("sessions.create", "Session", "SessionCreate", ["sessionId"], [200, 201]) },
119
+ "/sessions/{sessionId}/configurations/{configurationId}": { put: operation("sessions.configure", "Session", "ConfigurationCreate", ["sessionId", "configurationId"], [200, 201]) },
120
+ "/sessions/{sessionId}/runs/{runId}": { put: operation("runs.start", "RunSnapshot", "RunInput", ["sessionId", "runId"], [200, 202]) },
121
+ "/runs/{runId}": { get: operation("runs.read", "RunSnapshot", undefined, ["runId"]) },
122
+ "/runs/{runId}/events": { get: { operationId: "runs.events", security: [{ coreOperation: [] }], parameters: [parameter("runId"), { name: "after", in: "query", schema: text(8192) }, { name: "Last-Event-ID", in: "header", schema: text(8192) }],
123
+ description: "At-least-once SSE. after and Last-Event-ID must agree. Persisted Event envelopes use event: agent and an opaque id cursor. 410 replay_expired requires installing a fresh atomic snapshot before following its cursor. Disconnect never cancels execution.",
124
+ responses: { ...errors, "200": { description: "Persisted agent event stream.", content: { "text/event-stream": { schema: { type: "string" }, "x-event-schema": ref("Event") } } } } } },
125
+ "/runs/{runId}/responses": { post: operation("runs.respond", "ControlReceipt", "ResponseInput", ["runId"], [200, 202]) },
126
+ "/runs/{runId}/cancel": { post: operation("runs.cancel", "ControlReceipt", "CancelInput", ["runId"], [200, 202]) },
127
+ "/runs/{runId}/controls": { post: { ...operation("runs.control", "ControlReceipt", "ControlInput", ["runId"], [200, 202]), description: "Optional controls require their advertised capabilities. Reconcile input is an attestation, never proof of actual native exit." } },
128
+ "/runs/{runId}/controls/{requestId}": { get: operation("runs.controls.read", "ControlReceipt", undefined, ["runId", "requestId"]) },
129
+ }, components: { securitySchemes: { coreOperation: { type: "http", scheme: "bearer", description: "Fresh Core exact-operation credential, never the caller's service/user token." } }, schemas: AGENT_SCHEMAS },
130
+ };
131
+ function localRefs(value) {
132
+ if (Array.isArray(value))
133
+ return value.map(localRefs);
134
+ if (value && typeof value === "object")
135
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, key === "$ref" && typeof item === "string" ? item.replace("#/components/schemas/", "#/$defs/") : localRefs(item)]));
136
+ return value;
137
+ }
138
+ export const AGENT_EVENT_SCHEMA = { $schema: "https://json-schema.org/draft/2020-12/schema", $id: "urn:hosty:agent-event:1", $ref: "#/$defs/Event", $defs: localRefs(AGENT_SCHEMAS) };