@clearideas/agent-runtime-server 0.0.0-stage → 0.9.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,1139 @@
1
+ /**
2
+ * The OpenAI-compatible agent service: transport-neutral request handling
3
+ * over served agent manifests. `http.ts` adapts it to node:http and to
4
+ * fetch-style handlers.
5
+ */
6
+ import { randomUUID } from "node:crypto";
7
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import path from "node:path";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ import { loadAgentRuntimeConfig, } from "@clearideas/agent-runtime-config";
12
+ import { AgentRuntime, conversationTurns, declaresMessages, defaultManifestHasher, isRunInterruptedError, isRunSuspendedError, resolveAgentVariables, RunInterruptedError, } from "@clearideas/agent-runtime-core";
13
+ import { JexlConditionEvaluator } from "@clearideas/agent-runtime-condition-jexl";
14
+ import { FileAgentManifestSource, FileArtifactStore, MemoryRunStore, } from "@clearideas/agent-runtime-store-local";
15
+ import { AdmissionController } from "./admission.js";
16
+ import { canStreamLive, observeStepStarts, planAnswer, } from "./answer.js";
17
+ import { Authenticator, principalCanUse, } from "./auth.js";
18
+ import { normalizeInputMapping, } from "./config.js";
19
+ import { convertChatMessages, mapInputVariables, splitNewTurn, } from "./convert.js";
20
+ import { fromRunError, invalidRequest, ServerError } from "./errors.js";
21
+ import { composeHostRuntime, hostRuntimeDependencies, loadHostRunStore, loadHostRuntime, resolveAgentRuntimeConfig, } from "./host.js";
22
+ import { MemoryKeyValueStore, openKeyValueStore, } from "./kv.js";
23
+ import { ConversationLedger } from "./ledger.js";
24
+ import { MediaIngestor } from "./media.js";
25
+ import { chatCompletion, hasClientTools, modelObject, parseChatCompletionRequest, toOpenAiUsage, } from "./openai.js";
26
+ import { ChatStream, stepLabels } from "./stream.js";
27
+ export const jsonLogger = (write = (line) => process.stderr.write(line)) => {
28
+ const log = (level) => (record) => write(`${JSON.stringify({ time: new Date().toISOString(), level, ...record })}\n`);
29
+ return { info: log("info"), warn: log("warn"), error: log("error") };
30
+ };
31
+ export const silentLogger = {
32
+ info: () => undefined,
33
+ warn: () => undefined,
34
+ error: () => undefined,
35
+ };
36
+ const RETENTION_NAMESPACE = "retention:v1";
37
+ const packageVersion = async () => {
38
+ try {
39
+ const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../package.json");
40
+ return JSON.parse(await readFile(file, "utf8"))
41
+ .version;
42
+ }
43
+ catch {
44
+ return "unknown";
45
+ }
46
+ };
47
+ /**
48
+ * A tool adapter for startup checks that defers discovery to the first
49
+ * request: tool names are reported as not yet checked rather than unknown.
50
+ */
51
+ const deferredTools = () => ({
52
+ listTools: async () => [],
53
+ executeTool: async () => {
54
+ throw new Error("Tools are not available during startup checks.");
55
+ },
56
+ unavailableToolReason: () => "checked when a request runs",
57
+ });
58
+ const isLoopback = (host) => host === "127.0.0.1" ||
59
+ host === "::1" ||
60
+ host === "localhost" ||
61
+ host.startsWith("127.");
62
+ export class AgentServer {
63
+ config;
64
+ version;
65
+ #loaded;
66
+ #options;
67
+ #logger;
68
+ #models;
69
+ #runtimeConfig;
70
+ #auth;
71
+ #admission;
72
+ #runStore;
73
+ #artifacts;
74
+ #stores;
75
+ #ledger;
76
+ #media;
77
+ /** Runs awaiting deletion. Never evicted, or a run would be kept forever. */
78
+ #retention;
79
+ #active = new Map();
80
+ #settled = new Set();
81
+ #cleanup;
82
+ #retentionTimer;
83
+ #draining = false;
84
+ constructor(init) {
85
+ this.#loaded = init.loaded;
86
+ this.config = init.loaded.config;
87
+ this.#options = init.options;
88
+ this.#logger = init.logger;
89
+ this.#models = init.models;
90
+ this.#runtimeConfig = init.runtimeConfig;
91
+ this.#auth = init.auth;
92
+ this.#runStore = init.runStore;
93
+ this.#artifacts = init.artifacts;
94
+ this.#stores = init.stores;
95
+ this.version = init.version;
96
+ this.#cleanup = init.cleanup;
97
+ const server = this.config.server;
98
+ this.#admission = new AdmissionController({
99
+ maxConcurrentRuns: server.maxConcurrentRuns,
100
+ maxQueuedRequests: server.maxQueuedRequests,
101
+ queueTimeoutMs: server.queueTimeoutMs,
102
+ });
103
+ const conversations = this.config.conversations;
104
+ const ledgerStore = this.#store(conversations.ledger.store);
105
+ this.#ledger = new ConversationLedger(ledgerStore, {
106
+ ttlMs: conversations.ledger.ttl,
107
+ match: conversations.match,
108
+ });
109
+ this.#retention =
110
+ this.config.stores.default?.driver === "sqlite"
111
+ ? this.#store("default")
112
+ : new MemoryKeyValueStore({ maxEntries: Number.MAX_SAFE_INTEGER });
113
+ this.#media = new MediaIngestor(ledgerStore, {
114
+ maxInlineBytes: this.#runtimeConfig.messages?.media?.maxInlineBytes ?? 10 * 1024 * 1024,
115
+ urls: conversations.media.urls,
116
+ allowOrigins: conversations.media.allowOrigins,
117
+ ttlMs: conversations.ledger.ttl,
118
+ });
119
+ this.#retentionTimer = setInterval(() => {
120
+ void this.sweepRetention().catch((error) => this.#logger.warn({
121
+ event: "retention.failed",
122
+ error: error instanceof Error ? error.message : String(error),
123
+ }));
124
+ }, 60_000);
125
+ this.#retentionTimer.unref?.();
126
+ }
127
+ /**
128
+ * Load the runtime configuration and every served manifest, validate
129
+ * them, and run preflight. Any problem stops startup.
130
+ */
131
+ static async create(options) {
132
+ const { loaded } = options;
133
+ const config = loaded.config;
134
+ const logger = options.logger ?? jsonLogger();
135
+ const cleanup = [];
136
+ try {
137
+ const runtimeConfig = config.runtimeConfig
138
+ ? await loadAgentRuntimeConfig(config.runtimeConfig)
139
+ : await resolveAgentRuntimeConfig(undefined, loaded.baseDirectory);
140
+ const stores = new Map();
141
+ for (const [name, storeConfig] of Object.entries(config.stores)) {
142
+ const store = await openKeyValueStore(storeConfig);
143
+ stores.set(name, store);
144
+ cleanup.push(() => store.close?.());
145
+ }
146
+ if (!stores.has("default")) {
147
+ const store = await openKeyValueStore({
148
+ driver: "memory",
149
+ maxEntries: 100_000,
150
+ });
151
+ stores.set("default", store);
152
+ }
153
+ const storeDirectory = config.store.path
154
+ ? path.dirname(config.store.path)
155
+ : loaded.baseDirectory;
156
+ let runStore;
157
+ if (config.store.driver === "sqlite") {
158
+ const { SqliteRunStore } = await import("@clearideas/agent-runtime-store-sqlite");
159
+ const sqlite = new SqliteRunStore(config.store.path);
160
+ runStore = sqlite;
161
+ cleanup.push(() => sqlite.close());
162
+ }
163
+ else if (config.store.driver === "module") {
164
+ const moduleStore = await loadHostRunStore(config.runtimeModule, {
165
+ storeDirectory,
166
+ storeDriver: "module",
167
+ });
168
+ if (!moduleStore)
169
+ throw new Error("store.driver: module requires a runtime module that exports runStore or createRunStore.");
170
+ runStore = moduleStore;
171
+ }
172
+ else {
173
+ runStore = new MemoryRunStore();
174
+ }
175
+ let artifactDirectory = config.artifacts.path;
176
+ if (!artifactDirectory) {
177
+ // Without a configured location, artifacts live for the process.
178
+ const temporary = await mkdtemp(path.join(tmpdir(), "agent-runtime-serve-"));
179
+ cleanup.push(() => rm(temporary, { recursive: true, force: true }));
180
+ artifactDirectory = temporary;
181
+ }
182
+ const artifacts = new FileArtifactStore(artifactDirectory);
183
+ const moduleHook = config.runtimeModule
184
+ ? await loadAuthenticateHook(config.runtimeModule)
185
+ : undefined;
186
+ const hook = options.authenticate ?? moduleHook;
187
+ const auth = new Authenticator({
188
+ keys: config.auth.apiKeys,
189
+ ...(options.environment ? { environment: options.environment } : {}),
190
+ ...(hook ? { hook } : {}),
191
+ allowAnonymous: true,
192
+ });
193
+ if (auth.anonymous &&
194
+ !isLoopback(config.server.host) &&
195
+ !config.server.allowUnauthenticated) {
196
+ throw new Error(`Refusing to serve without authentication on ${config.server.host}. Configure API keys (auth.apiKeys or --api-key-env), bind to 127.0.0.1, or set allowUnauthenticated.`);
197
+ }
198
+ const created = Math.floor(Date.now() / 1000);
199
+ const models = new Map();
200
+ for (const modelConfig of config.models) {
201
+ models.set(modelConfig.name, await loadServedModel({
202
+ modelConfig,
203
+ config,
204
+ runtimeConfig,
205
+ storeDirectory,
206
+ artifacts,
207
+ created,
208
+ ...(options.runtime ? { programmatic: options.runtime } : {}),
209
+ warmup: options.warmup === true,
210
+ }));
211
+ }
212
+ return new AgentServer({
213
+ loaded,
214
+ options,
215
+ logger,
216
+ models,
217
+ runtimeConfig,
218
+ auth,
219
+ runStore,
220
+ artifacts,
221
+ stores,
222
+ version: await packageVersion(),
223
+ cleanup,
224
+ });
225
+ }
226
+ catch (error) {
227
+ for (const close of cleanup.reverse())
228
+ await close();
229
+ throw error;
230
+ }
231
+ }
232
+ #store(name) {
233
+ const store = this.#stores.get(name);
234
+ if (!store)
235
+ throw new Error(`Unknown store ${name}.`);
236
+ return store;
237
+ }
238
+ get ready() {
239
+ return !this.#draining;
240
+ }
241
+ get authenticated() {
242
+ return !this.#auth.anonymous;
243
+ }
244
+ get models() {
245
+ return [...this.#models.values()];
246
+ }
247
+ // ─── Request handling ────────────────────────────────────────────────────
248
+ async handle(request) {
249
+ const started = Date.now();
250
+ const requestId = requestIdFrom(request.headers);
251
+ const log = {
252
+ event: "request",
253
+ requestId,
254
+ method: request.method,
255
+ path: request.path,
256
+ };
257
+ const cors = this.#cors(request.headers);
258
+ const finish = (response) => {
259
+ const headers = {
260
+ ...cors,
261
+ "x-request-id": requestId,
262
+ ...response.headers,
263
+ };
264
+ const done = () => this.#logger.info({
265
+ ...log,
266
+ status: response.status,
267
+ durationMs: Date.now() - started,
268
+ });
269
+ if (response.body && typeof response.body !== "string") {
270
+ return { ...response, headers, body: logOnEnd(response.body, done) };
271
+ }
272
+ done();
273
+ return { ...response, headers };
274
+ };
275
+ try {
276
+ if (request.method === "OPTIONS") {
277
+ return finish({ status: 204, headers: {} });
278
+ }
279
+ return finish(await this.#route(request, log));
280
+ }
281
+ catch (caught) {
282
+ const error = caught instanceof ServerError
283
+ ? caught
284
+ : fromRunError(caught, {
285
+ exposeErrors: this.config.server.exposeErrors,
286
+ });
287
+ if (error.status >= 500) {
288
+ log.errorCode = error.code;
289
+ log.cause =
290
+ caught instanceof Error && this.config.server.exposeErrors
291
+ ? caught.message
292
+ : undefined;
293
+ }
294
+ return finish(errorResponse(error));
295
+ }
296
+ }
297
+ #cors(headers) {
298
+ const origin = header(headers, "origin");
299
+ const allowed = this.config.server.cors.origins;
300
+ if (!origin || !(allowed.includes("*") || allowed.includes(origin)))
301
+ return {};
302
+ return {
303
+ "access-control-allow-origin": allowed.includes("*") ? "*" : origin,
304
+ "access-control-allow-methods": "GET, POST, OPTIONS",
305
+ "access-control-allow-headers": "authorization, content-type, x-request-id",
306
+ "access-control-max-age": "600",
307
+ vary: "origin",
308
+ };
309
+ }
310
+ async #route(request, log) {
311
+ const { method } = request;
312
+ const route = request.path.replace(/\/+$/u, "") || "/";
313
+ if (route === "/health" && method === "GET")
314
+ return json(200, { status: "ok" });
315
+ if (route === "/ready" && method === "GET")
316
+ return this.ready
317
+ ? json(200, { status: "ready" })
318
+ : json(503, { status: "draining" });
319
+ if (route === "/version" && method === "GET")
320
+ return json(200, { version: this.version });
321
+ if (!route.startsWith("/v1/"))
322
+ throw new ServerError(404, "not_found", `No route for ${method} ${route}.`);
323
+ const principal = await this.#auth.authenticate({
324
+ method,
325
+ path: route,
326
+ headers: request.headers,
327
+ });
328
+ log.principal = principal.id;
329
+ if (route === "/v1/models" && method === "GET") {
330
+ return json(200, {
331
+ object: "list",
332
+ data: this.models
333
+ .filter((model) => principalCanUse(principal, model.name))
334
+ .map((model) => modelObject(model.name, model.created, model.description)),
335
+ });
336
+ }
337
+ if (route.startsWith("/v1/models/") && method === "GET") {
338
+ const name = decodeURIComponent(route.slice("/v1/models/".length));
339
+ const model = this.#models.get(name);
340
+ if (!model || !principalCanUse(principal, name))
341
+ throw modelNotFound(name);
342
+ return json(200, modelObject(model.name, model.created, model.description));
343
+ }
344
+ if (route === "/v1/chat/completions" && method === "POST") {
345
+ return this.#chatCompletion(request, principal, log);
346
+ }
347
+ throw new ServerError(404, "not_found", `No route for ${method} ${route}.`);
348
+ }
349
+ // ─── Chat completions ────────────────────────────────────────────────────
350
+ async #chatCompletion(request, principal, log) {
351
+ if (this.#draining)
352
+ throw new ServerError(503, "service_unavailable", "The server is shutting down.");
353
+ const server = this.config.server;
354
+ const runId = `run_${randomUUID()}`;
355
+ const controller = new AbortController();
356
+ let model;
357
+ const onDisconnect = () => {
358
+ if (model?.config.onDisconnect !== "continue" &&
359
+ !controller.signal.aborted)
360
+ controller.abort(new ServerError(499, "client_closed_request", "The client disconnected."));
361
+ };
362
+ request.signal.addEventListener("abort", onDisconnect, { once: true });
363
+ if (request.signal.aborted)
364
+ onDisconnect();
365
+ const timer = setTimeout(() => {
366
+ controller.abort(new ServerError(504, "timeout", "The request timed out."));
367
+ }, server.requestTimeoutMs);
368
+ timer.unref?.();
369
+ // Track the entire request, including body ingestion, queueing and setup.
370
+ let settle;
371
+ const tracked = new Promise((resolve) => {
372
+ settle = resolve;
373
+ });
374
+ this.#settled.add(tracked);
375
+ this.#active.set(runId, controller);
376
+ let release;
377
+ let cleaned = false;
378
+ let executing = false;
379
+ let prepared;
380
+ const cleanup = () => {
381
+ if (cleaned)
382
+ return;
383
+ cleaned = true;
384
+ clearTimeout(timer);
385
+ request.signal.removeEventListener("abort", onDisconnect);
386
+ this.#active.delete(runId);
387
+ release?.();
388
+ this.#settled.delete(tracked);
389
+ settle();
390
+ };
391
+ try {
392
+ const body = await abortable(request.readBody(server.maxRequestBytes, controller.signal), controller.signal);
393
+ let parsedBody;
394
+ try {
395
+ parsedBody = JSON.parse(body.toString("utf8"));
396
+ }
397
+ catch {
398
+ throw invalidRequest("The request body must be JSON.");
399
+ }
400
+ const requested = modelName(parsedBody);
401
+ model = requested ? this.#models.get(requested) : undefined;
402
+ const chat = parseChatCompletionRequest(parsedBody, model?.config.clientTools ?? "reject");
403
+ if (!model || !principalCanUse(principal, chat.model))
404
+ throw modelNotFound(chat.model);
405
+ log.model = model.name;
406
+ if (hasClientTools(chat))
407
+ log.clientTools = "ignored";
408
+ checkResponseFormat(model, chat);
409
+ if (this.#draining)
410
+ throw new ServerError(503, "service_unavailable", "The server is shutting down.");
411
+ log.runId = runId;
412
+ const stream = chat.stream === true;
413
+ log.stream = stream;
414
+ const identity = {
415
+ id: `chatcmpl-${runId}`,
416
+ created: Math.floor(Date.now() / 1000),
417
+ model: model.name,
418
+ systemFingerprint: `ar_${this.version}_${model.manifestHash.replace(/^[^:]*:/u, "").slice(0, 12)}`,
419
+ };
420
+ release = await this.#admission.acquire(principal.id, principal.maxConcurrentRuns, controller.signal);
421
+ controller.signal.throwIfAborted();
422
+ prepared = await this.#prepareRun({
423
+ model,
424
+ chat,
425
+ principal,
426
+ runId,
427
+ log,
428
+ signal: controller.signal,
429
+ });
430
+ controller.signal.throwIfAborted();
431
+ const execution = this.#execute({
432
+ model,
433
+ prepared,
434
+ runId,
435
+ signal: controller.signal,
436
+ stream: stream
437
+ ? new ChatStream({
438
+ identity,
439
+ includeUsage: chat.stream_options?.include_usage === true,
440
+ progress: model.config.stream.progress,
441
+ reasoning: model.config.stream.reasoning,
442
+ progressField: model.config.stream.progressField,
443
+ heartbeatMs: server.heartbeatMs,
444
+ stepLabels: model.labels,
445
+ onCancel: onDisconnect,
446
+ onError: (error) => controller.abort(error),
447
+ })
448
+ : undefined,
449
+ log,
450
+ });
451
+ executing = true;
452
+ void execution.done.then(cleanup, cleanup);
453
+ if (!stream) {
454
+ const outcome = await execution.done;
455
+ return json(200, chatCompletion(identity, outcome.reply, outcome.finishReason, toOpenAiUsage(outcome.result?.usage)), outcome.headers);
456
+ }
457
+ // Streamed: respond once the run has started, so errors found while
458
+ // creating the run (invalid history, signatures) keep their status.
459
+ const startedStream = await execution.started;
460
+ return {
461
+ status: 200,
462
+ headers: {
463
+ "content-type": "text/event-stream; charset=utf-8",
464
+ "cache-control": "no-cache",
465
+ connection: "keep-alive",
466
+ "x-accel-buffering": "no",
467
+ ...startedStream.headers,
468
+ },
469
+ body: startedStream.body,
470
+ };
471
+ }
472
+ catch (error) {
473
+ if (!executing) {
474
+ try {
475
+ await prepared?.moduleRuntime.shutdown?.();
476
+ }
477
+ finally {
478
+ cleanup();
479
+ }
480
+ }
481
+ throw abortError(controller.signal) ?? error;
482
+ }
483
+ }
484
+ /** Build the run input: history or variables, scope, budget. */
485
+ async #prepareRun(input) {
486
+ const { model, chat, principal } = input;
487
+ const conversations = this.config.conversations;
488
+ const scope = principal.scope ??
489
+ `key:${principal.id}${conversations.scope.includeUser && chat.user ? `/user:${chat.user}` : ""}`;
490
+ const moduleContext = {
491
+ manifest: model.manifest,
492
+ runId: input.runId,
493
+ storeDirectory: this.config.store.path
494
+ ? path.dirname(this.config.store.path)
495
+ : this.#loaded.baseDirectory,
496
+ storeDriver: this.config.store.driver,
497
+ ...(this.config.store.path
498
+ ? { storeLocation: this.config.store.path }
499
+ : {}),
500
+ };
501
+ // The runtime module is loaded for every request, as the CLI loads it
502
+ // for every run; the server owns the run store.
503
+ const moduleRuntime = await abortable(loadHostRuntime(this.config.runtimeModule, moduleContext, {
504
+ createRunStore: false,
505
+ }), input.signal, (late) => late.shutdown?.());
506
+ try {
507
+ const moduleAuthorize = moduleRuntime.messages?.authorizeArtifact;
508
+ const overlay = modelOverlay(model.config, this.#options.runtime, {
509
+ authorizeArtifact: async (ref, context) => (await this.#media.authorize(ref, context.scope)) ||
510
+ (moduleAuthorize
511
+ ? (await moduleAuthorize(ref, context)) === true
512
+ : false),
513
+ });
514
+ const runtime = composeHostRuntime(model.manifest, this.#runtimeConfig, [
515
+ moduleRuntime,
516
+ overlay,
517
+ ]);
518
+ const artifacts = runtime.artifactStore ?? this.#artifacts;
519
+ const converted = await abortable(convertChatMessages(chat.messages, {
520
+ allowMedia: model.mode === "conversation",
521
+ clientTools: model.config.clientTools,
522
+ media: this.#media,
523
+ scope,
524
+ artifacts,
525
+ }), input.signal);
526
+ const variables = mapInputVariables({
527
+ mappings: model.input,
528
+ chat: converted,
529
+ request: chat,
530
+ });
531
+ if (model.instructionsVariable && converted.instructions) {
532
+ variables.push({
533
+ key: model.instructionsVariable,
534
+ value: converted.instructions,
535
+ });
536
+ }
537
+ try {
538
+ resolveAgentVariables(model.manifest, variables);
539
+ }
540
+ catch (error) {
541
+ throw invalidRequest(error instanceof Error ? error.message : String(error), "messages");
542
+ }
543
+ let history = {
544
+ ledger: "not-applicable",
545
+ };
546
+ if (model.mode === "conversation") {
547
+ history = await abortable(this.#resolveHistory(model, converted, scope), input.signal);
548
+ input.log.ledger = history.ledger;
549
+ }
550
+ const budget = runBudget(model, chat, principal);
551
+ return {
552
+ runtime,
553
+ moduleRuntime,
554
+ artifacts,
555
+ scope,
556
+ converted,
557
+ variables,
558
+ ...history,
559
+ ...(budget ? { budget } : {}),
560
+ };
561
+ }
562
+ catch (error) {
563
+ await moduleRuntime.shutdown?.();
564
+ throw error;
565
+ }
566
+ }
567
+ /** Continue from the runtime's own history when the ledger recognizes the conversation. */
568
+ async #resolveHistory(model, converted, scope) {
569
+ const { prefix, newTurn } = splitNewTurn(converted.messages);
570
+ if (prefix.length === 0)
571
+ return { messages: converted.messages, ledger: "first-turn" };
572
+ const entry = await this.#ledger.lookup({
573
+ scope,
574
+ model: model.name,
575
+ messages: prefix,
576
+ });
577
+ if (entry) {
578
+ if (entry.manifestHash !== model.manifestHash &&
579
+ this.config.conversations.onManifestChange === "restart") {
580
+ return { messages: newTurn, ledger: "restarted" };
581
+ }
582
+ return {
583
+ messages: [...entry.history, ...newTurn],
584
+ ...(entry.signature ? { signature: entry.signature } : {}),
585
+ ledger: "hit",
586
+ };
587
+ }
588
+ switch (model.onUnrecognized) {
589
+ case "reject":
590
+ throw new ServerError(409, "conversation_not_recognized", "This conversation was not issued by this server or has changed. Start a new conversation.", { type: "invalid_request_error", param: "messages" });
591
+ case "restart":
592
+ return { messages: newTurn, ledger: "restarted" };
593
+ default:
594
+ return { messages: converted.messages, ledger: "unsigned" };
595
+ }
596
+ }
597
+ /**
598
+ * Execute a prepared run. `started` resolves when the run has been created
599
+ * (streaming responses start then); `done` settles with the outcome.
600
+ */
601
+ #execute(input) {
602
+ const { model, prepared, runId, stream } = input;
603
+ const headers = {
604
+ "x-agent-runtime-run-id": runId,
605
+ ...(prepared.messages
606
+ ? {
607
+ "x-agent-runtime-turn": String(conversationTurns(prepared.messages).currentTurn),
608
+ }
609
+ : {}),
610
+ ...(prepared.ledger === "restarted"
611
+ ? { "x-agent-runtime-conversation": "restarted" }
612
+ : {}),
613
+ };
614
+ let resolveStarted;
615
+ let rejectStarted;
616
+ const started = new Promise((resolve, reject) => {
617
+ resolveStarted = resolve;
618
+ rejectStarted = reject;
619
+ });
620
+ void started.catch(() => undefined);
621
+ let runStarted = false;
622
+ const completedCandidates = new Set();
623
+ const candidateIds = new Set(model.answer.candidates.map((candidate) => candidate.stepId));
624
+ const evaluator = new JexlConditionEvaluator();
625
+ const requestSink = {
626
+ emit: (event) => {
627
+ if (event.type === "run.started" && !runStarted) {
628
+ runStarted = true;
629
+ if (stream) {
630
+ stream.start();
631
+ resolveStarted({ body: stream.body, headers });
632
+ }
633
+ }
634
+ if (event.type === "step.completed" &&
635
+ event.stepId &&
636
+ candidateIds.has(event.stepId) &&
637
+ (event.stepPath === undefined || event.stepPath === event.stepId)) {
638
+ completedCandidates.add(event.stepId);
639
+ }
640
+ if (event.type === "context.reduced" &&
641
+ event.data?.scope === "messages")
642
+ input.log.compacted = true;
643
+ },
644
+ };
645
+ const dependencies = hostRuntimeDependencies(prepared.runtime, {
646
+ trust: "untrusted-request",
647
+ runStore: this.#runStore,
648
+ artifacts: prepared.artifacts,
649
+ eventSinks: [requestSink, ...(stream ? [stream.sink] : [])],
650
+ });
651
+ dependencies.stepExecutors = [...dependencies.stepExecutors].map((executor) => executor.type !== "prompt" || !stream
652
+ ? executor
653
+ : observeStepStarts(executor, async (step, variables) => {
654
+ if (!candidateIds.has(step.id) ||
655
+ model.config.output.from !== "final")
656
+ return;
657
+ if (await canStreamLive({
658
+ manifest: model.manifest,
659
+ plan: model.answer,
660
+ mode: model.config.stream.mode,
661
+ step,
662
+ variables,
663
+ completedCandidates,
664
+ evaluator,
665
+ })) {
666
+ stream.setLiveStep(step.id);
667
+ input.log.live = step.id;
668
+ }
669
+ }));
670
+ const agentRuntime = new AgentRuntime(dependencies);
671
+ const done = (async () => {
672
+ try {
673
+ let result;
674
+ let finishReason = "stop";
675
+ try {
676
+ result = await agentRuntime.run({
677
+ manifest: model.manifest,
678
+ runId,
679
+ ...(prepared.variables.length > 0
680
+ ? { variables: prepared.variables }
681
+ : {}),
682
+ ...(model.config.execution
683
+ ? { execution: model.config.execution }
684
+ : {}),
685
+ ...(prepared.budget ? { budget: prepared.budget } : {}),
686
+ ...(prepared.messages ? { messages: prepared.messages } : {}),
687
+ ...(prepared.signature
688
+ ? { messagesSignature: prepared.signature }
689
+ : {}),
690
+ ...(model.mode === "conversation"
691
+ ? { messagesScope: prepared.scope }
692
+ : {}),
693
+ signal: input.signal,
694
+ });
695
+ }
696
+ catch (error) {
697
+ if (!(isRunSuspendedError(error) && error.reason === "token-budget"))
698
+ throw error;
699
+ finishReason = "length";
700
+ }
701
+ finally {
702
+ // Requests refused before the run was created leave nothing to keep.
703
+ if (runStarted)
704
+ await this.#scheduleRetention(runId, result ? "completed" : "failed");
705
+ }
706
+ let reply = "";
707
+ if (result) {
708
+ reply = replyText(model, result);
709
+ if (model.mode === "conversation") {
710
+ await this.#recordConversation(model, prepared, result, reply, runId);
711
+ }
712
+ }
713
+ else if (stream) {
714
+ reply = stream.forwarded;
715
+ }
716
+ if (result?.usage) {
717
+ input.log.tokens =
718
+ result.usage.totalTokens ??
719
+ (result.usage.inputTokens ?? 0) + (result.usage.outputTokens ?? 0);
720
+ }
721
+ if (stream) {
722
+ stream.finish({
723
+ reply,
724
+ finishReason,
725
+ usage: toOpenAiUsage(result?.usage),
726
+ });
727
+ if (stream.diverged) {
728
+ input.log.diverged = true;
729
+ this.#logger.warn({ event: "stream.diverged", runId });
730
+ }
731
+ if (!runStarted)
732
+ resolveStarted({ body: stream.body, headers });
733
+ }
734
+ return {
735
+ reply,
736
+ finishReason,
737
+ ...(result ? { result } : {}),
738
+ headers,
739
+ };
740
+ }
741
+ catch (caught) {
742
+ const error = abortError(input.signal) ??
743
+ fromRunError(caught, {
744
+ exposeErrors: this.config.server.exposeErrors,
745
+ });
746
+ input.log.errorCode = error.code;
747
+ if (stream && runStarted) {
748
+ stream.fail(error);
749
+ return { reply: "", finishReason: "stop", headers, failed: error };
750
+ }
751
+ rejectStarted(error);
752
+ throw error;
753
+ }
754
+ finally {
755
+ await prepared.moduleRuntime.shutdown?.();
756
+ }
757
+ })();
758
+ void done.catch(() => undefined);
759
+ return { started, done };
760
+ }
761
+ async #recordConversation(model, prepared, result, reply, runId) {
762
+ if (!result.messages)
763
+ return;
764
+ const entry = {
765
+ history: result.messages,
766
+ ...(result.messagesSignature
767
+ ? { signature: result.messagesSignature }
768
+ : {}),
769
+ scope: prepared.scope,
770
+ runId,
771
+ model: model.name,
772
+ manifestHash: model.manifestHash,
773
+ createdAt: new Date().toISOString(),
774
+ };
775
+ try {
776
+ await this.#ledger.record({
777
+ messages: [
778
+ ...prepared.converted.messages,
779
+ { role: "assistant", content: [{ type: "text", text: reply }] },
780
+ ],
781
+ entry,
782
+ });
783
+ }
784
+ catch (error) {
785
+ // The reply is still delivered; the next turn is handled by
786
+ // onUnrecognized.
787
+ this.#logger.warn({
788
+ event: "ledger.record-failed",
789
+ runId,
790
+ error: error instanceof Error ? error.message : String(error),
791
+ });
792
+ }
793
+ }
794
+ // ─── Retention ───────────────────────────────────────────────────────────
795
+ async #scheduleRetention(runId, outcome) {
796
+ const retention = this.config.store.retention;
797
+ await this.#retention.set(RETENTION_NAMESPACE, runId, outcome, outcome === "completed" ? retention.completed : retention.failed);
798
+ }
799
+ /** Delete runs whose retention period has passed. */
800
+ async sweepRetention() {
801
+ await this.#ledger.sweepExpired();
802
+ await this.#media.sweepExpired();
803
+ if (!this.#runStore.deleteRun)
804
+ return 0;
805
+ let deleted = 0;
806
+ while (true) {
807
+ const due = await this.#retention.takeExpired(RETENTION_NAMESPACE, 100);
808
+ for (const { key } of due) {
809
+ try {
810
+ if (await this.#runStore.deleteRun(key))
811
+ deleted += 1;
812
+ }
813
+ catch {
814
+ // Still running (a resumed run): look again later.
815
+ await this.#retention.set(RETENTION_NAMESPACE, key, "retry", 3_600_000);
816
+ }
817
+ }
818
+ if (due.length < 100)
819
+ return deleted;
820
+ }
821
+ }
822
+ // ─── Shutdown ────────────────────────────────────────────────────────────
823
+ /**
824
+ * Stop admitting requests, let runs finish within the grace period, then
825
+ * interrupt the rest (they stay resumable), and release resources.
826
+ */
827
+ async shutdown(graceMs = this.config.server.shutdownGraceMs) {
828
+ if (this.#draining)
829
+ return;
830
+ this.#draining = true;
831
+ if (this.#retentionTimer)
832
+ clearInterval(this.#retentionTimer);
833
+ const pending = Promise.allSettled([...this.#settled]);
834
+ const graceful = await Promise.race([
835
+ pending.then(() => true),
836
+ new Promise((resolve) => {
837
+ const timer = setTimeout(() => resolve(false), graceMs);
838
+ timer.unref?.();
839
+ }),
840
+ ]);
841
+ if (!graceful) {
842
+ for (const controller of this.#active.values()) {
843
+ controller.abort(new RunInterruptedError("server shutdown"));
844
+ }
845
+ await Promise.allSettled([...this.#settled]);
846
+ }
847
+ for (const close of this.#cleanup.reverse()) {
848
+ try {
849
+ await close();
850
+ }
851
+ catch (error) {
852
+ this.#logger.warn({
853
+ event: "shutdown.cleanup-failed",
854
+ error: error instanceof Error ? error.message : String(error),
855
+ });
856
+ }
857
+ }
858
+ }
859
+ }
860
+ const header = (headers, name) => {
861
+ const value = headers[name];
862
+ return Array.isArray(value) ? value[0] : value;
863
+ };
864
+ const requestIdFrom = (headers) => {
865
+ const supplied = header(headers, "x-request-id");
866
+ return supplied && /^[A-Za-z0-9._:-]{1,128}$/u.test(supplied)
867
+ ? supplied
868
+ : `req_${randomUUID()}`;
869
+ };
870
+ const json = (status, value, headers = {}) => ({
871
+ status,
872
+ headers: {
873
+ "content-type": "application/json; charset=utf-8",
874
+ "cache-control": "no-store",
875
+ ...headers,
876
+ },
877
+ body: JSON.stringify(value),
878
+ });
879
+ const errorResponse = (error) => json(error.status, error.toBody(), error.retryAfter !== undefined
880
+ ? { "retry-after": String(error.retryAfter) }
881
+ : {});
882
+ /** The error an aborted run reports: timeout, disconnect, or shutdown. */
883
+ const abortError = (signal) => {
884
+ if (!signal.aborted)
885
+ return undefined;
886
+ if (signal.reason instanceof ServerError)
887
+ return signal.reason;
888
+ if (isRunInterruptedError(signal.reason))
889
+ return new ServerError(503, "service_unavailable", "The server is shutting down; retry the request.", { retryAfter: 5 });
890
+ return undefined;
891
+ };
892
+ /** The requested model name, read before full validation selects its policy. */
893
+ const modelName = (body) => body != null &&
894
+ typeof body === "object" &&
895
+ typeof body.model === "string"
896
+ ? body.model
897
+ : undefined;
898
+ const modelNotFound = (name) => new ServerError(404, "model_not_found", `The model ${JSON.stringify(name)} does not exist or you do not have access to it.`, { type: "invalid_request_error", param: "model" });
899
+ async function* logOnEnd(body, done) {
900
+ try {
901
+ yield* body;
902
+ }
903
+ finally {
904
+ done();
905
+ }
906
+ }
907
+ /** The reply text: the appended history message, or the selected output. */
908
+ const replyText = (model, result) => {
909
+ if (model.mode === "conversation") {
910
+ if (result.output === undefined) {
911
+ throw new ServerError(500, "agent_no_reply", "The agent completed without a reply.");
912
+ }
913
+ const last = result.messages?.at(-1);
914
+ const text = last?.role === "assistant"
915
+ ? last.content
916
+ .map((part) => (part.type === "text" ? part.text : ""))
917
+ .join("")
918
+ : undefined;
919
+ return text ?? stringify(result.output);
920
+ }
921
+ const from = model.config.output.from;
922
+ const value = from.startsWith("step:")
923
+ ? result.stepResults.find((entry) => entry.stepId === from.slice(5))?.output
924
+ : from.startsWith("variable:")
925
+ ? result.state[from.slice(9)]
926
+ : result.output;
927
+ return value === undefined ? "" : stringify(value);
928
+ };
929
+ const stringify = (value) => typeof value === "string" ? value : JSON.stringify(value);
930
+ const runBudget = (model, chat, principal) => {
931
+ const limits = [
932
+ model.config.budget?.maxTotalTokens,
933
+ principal.maxTotalTokensPerRequest,
934
+ model.config.maxTokens === "budget"
935
+ ? (chat.max_completion_tokens ?? chat.max_tokens ?? undefined)
936
+ : undefined,
937
+ ].filter((value) => typeof value === "number");
938
+ return limits.length > 0
939
+ ? { maxTotalTokens: Math.min(...limits) }
940
+ : undefined;
941
+ };
942
+ const checkResponseFormat = (model, chat) => {
943
+ const format = chat.response_format;
944
+ if (!format || format.type === "text")
945
+ return;
946
+ const steps = model.answer.candidates.map((candidate) => model.manifest.steps[candidate.index]);
947
+ const schemas = steps.map((step) => step.type === "prompt" ? step.outputSchema : undefined);
948
+ const structured = schemas.length > 0 && schemas.every(Boolean);
949
+ if (format.type === "json_object" && structured)
950
+ return;
951
+ if (format.type === "json_schema" &&
952
+ structured &&
953
+ schemas.every((schema) => JSON.stringify(schema) ===
954
+ JSON.stringify(format.json_schema.schema)))
955
+ return;
956
+ throw invalidRequest("response_format is fixed by the served agent's manifest and does not match this request.", "response_format");
957
+ };
958
+ /** Server-configured and programmatic adapters, applied over the runtime module. */
959
+ const modelOverlay = (config, programmatic, messages) => ({
960
+ ...programmatic,
961
+ ...(config.policies ? { policies: config.policies } : {}),
962
+ ...(config.enforcedPolicies
963
+ ? { enforcedPolicies: config.enforcedPolicies }
964
+ : {}),
965
+ messages: { ...programmatic?.messages, ...messages },
966
+ });
967
+ const loadAuthenticateHook = async (modulePath) => {
968
+ const imported = (await import(pathToFileURL(path.resolve(modulePath)).href));
969
+ const hook = imported.authenticate ?? imported.default?.authenticate;
970
+ if (hook === undefined)
971
+ return undefined;
972
+ if (typeof hook !== "function")
973
+ throw new Error("The runtime module's authenticate export must be a function.");
974
+ return hook;
975
+ };
976
+ /** Load, validate, and preflight one served manifest. */
977
+ const loadServedModel = async (options) => {
978
+ const { modelConfig, config } = options;
979
+ const prefix = `Served model ${modelConfig.name}`;
980
+ const manifestFile = modelConfig.manifest;
981
+ let manifest;
982
+ try {
983
+ manifest = await new FileAgentManifestSource(path.dirname(manifestFile), path.basename(manifestFile)).loadManifest();
984
+ }
985
+ catch (error) {
986
+ throw new Error(`${prefix}: ${error instanceof Error ? error.message : String(error)}`);
987
+ }
988
+ const declared = new Map((manifest.variables ?? []).map((variable) => [variable.key, variable]));
989
+ const mode = declaresMessages(manifest) ? "conversation" : "variable";
990
+ // Input mappings: explicit, or inferred for a single required string variable.
991
+ let mappings;
992
+ if (modelConfig.input) {
993
+ mappings = Object.entries(modelConfig.input).map(([variable, source]) => normalizeInputMapping(variable, source));
994
+ }
995
+ else if (mode === "conversation") {
996
+ mappings = [];
997
+ }
998
+ else {
999
+ const required = [...declared.values()].filter((variable) => variable.requiresOverride === true);
1000
+ const only = required[0];
1001
+ if (required.length === 1 && only?.type === "string") {
1002
+ mappings = [{ variable: only.key, source: "last-user" }];
1003
+ }
1004
+ else {
1005
+ const names = [...declared.keys()];
1006
+ throw new Error(`${prefix}: cannot tell which variable receives the chat. The manifest does not declare messages, and ${required.length === 0
1007
+ ? "declares no required string variable"
1008
+ : `requires ${required.map((variable) => variable.key).join(", ")}`}. Map inputs explicitly, for example --input ${names[0] ?? "question"}=last-user (sources: last-user, transcript, system, json, client).`);
1009
+ }
1010
+ }
1011
+ for (const mapping of mappings) {
1012
+ const variable = declared.get(mapping.variable);
1013
+ if (!variable) {
1014
+ throw new Error(`${prefix}: input maps undeclared variable ${mapping.variable}. Declared: ${[...declared.keys()].join(", ") || "none"}.`);
1015
+ }
1016
+ if ((mapping.source === "last-user" ||
1017
+ mapping.source === "transcript" ||
1018
+ mapping.source === "system") &&
1019
+ variable.type !== "string") {
1020
+ throw new Error(`${prefix}: variable ${mapping.variable} has type ${variable.type}; source ${mapping.source} supplies a string.`);
1021
+ }
1022
+ }
1023
+ const instructionsVariable = modelConfig.clientInstructions.startsWith("variable:")
1024
+ ? modelConfig.clientInstructions.slice("variable:".length)
1025
+ : undefined;
1026
+ if (instructionsVariable &&
1027
+ declared.get(instructionsVariable)?.type !== "string") {
1028
+ throw new Error(`${prefix}: clientInstructions names ${instructionsVariable}, which must be a declared string variable.`);
1029
+ }
1030
+ const supplied = new Set([
1031
+ ...mappings.map((mapping) => mapping.variable),
1032
+ ...(instructionsVariable ? [instructionsVariable] : []),
1033
+ ]);
1034
+ const unmapped = [...declared.values()].filter((variable) => variable.requiresOverride === true && !supplied.has(variable.key));
1035
+ if (unmapped.length > 0) {
1036
+ throw new Error(`${prefix}: required variables ${unmapped.map((variable) => variable.key).join(", ")} are not mapped from the request.`);
1037
+ }
1038
+ if (mode === "conversation" && modelConfig.output.from !== "final") {
1039
+ throw new Error(`${prefix}: the manifest declares messages, so its reply is the run's final output; output.from cannot be changed.`);
1040
+ }
1041
+ if (modelConfig.output.from.startsWith("step:")) {
1042
+ const stepId = modelConfig.output.from.slice(5);
1043
+ if (!manifest.steps.some((step) => step.id === stepId))
1044
+ throw new Error(`${prefix}: output.from names unknown step ${stepId}.`);
1045
+ }
1046
+ // Compose once and preflight, with the same composition requests use.
1047
+ const moduleRuntime = await loadHostRuntime(config.runtimeModule, {
1048
+ manifest,
1049
+ storeDirectory: options.storeDirectory,
1050
+ storeDriver: config.store.driver,
1051
+ }, { createRunStore: false });
1052
+ let signaturesRequired = manifest.messages?.requireSignature === true;
1053
+ try {
1054
+ let runtime;
1055
+ try {
1056
+ runtime = composeHostRuntime(manifest, options.runtimeConfig, [
1057
+ moduleRuntime,
1058
+ modelOverlay(modelConfig, options.programmatic, {
1059
+ authorizeArtifact: () => false,
1060
+ }),
1061
+ ]);
1062
+ }
1063
+ catch (error) {
1064
+ throw new Error(`${prefix}: ${error instanceof Error ? error.message : String(error)}`);
1065
+ }
1066
+ signaturesRequired ||= runtime.messages?.requireSignature === true;
1067
+ const dependencies = hostRuntimeDependencies(runtime, {
1068
+ trust: "untrusted-request",
1069
+ runStore: new MemoryRunStore(),
1070
+ artifacts: runtime.artifactStore ?? options.artifacts,
1071
+ });
1072
+ if (!options.warmup && dependencies.tools)
1073
+ dependencies.tools = deferredTools();
1074
+ try {
1075
+ await new AgentRuntime(dependencies).preflight(manifest);
1076
+ }
1077
+ catch (error) {
1078
+ const message = error instanceof Error ? error.message : String(error);
1079
+ const webhookHint = /no webhook step executor/u.test(message)
1080
+ ? " Webhook steps need a WebhookStepExecutor with authorizeDestination from the runtime module's stepExecutors."
1081
+ : "";
1082
+ throw new Error(`${prefix}: ${message}${webhookHint}`);
1083
+ }
1084
+ }
1085
+ finally {
1086
+ await moduleRuntime.shutdown?.();
1087
+ }
1088
+ const configured = config.conversations.onUnrecognized;
1089
+ if (mode === "conversation" &&
1090
+ signaturesRequired &&
1091
+ configured === "unsigned") {
1092
+ throw new Error(`${prefix}: conversations.onUnrecognized is unsigned, but signatures are required; use reject or restart.`);
1093
+ }
1094
+ const manifestHash = await defaultManifestHasher.hash(manifest);
1095
+ return {
1096
+ name: modelConfig.name,
1097
+ ...((modelConfig.description ?? manifest.description)
1098
+ ? { description: modelConfig.description ?? manifest.description }
1099
+ : {}),
1100
+ config: modelConfig,
1101
+ manifestFile,
1102
+ manifest,
1103
+ manifestHash,
1104
+ created: options.created,
1105
+ mode,
1106
+ input: mappings,
1107
+ instructionsVariable,
1108
+ answer: planAnswer(manifest),
1109
+ labels: stepLabels(manifest.steps),
1110
+ signaturesRequired,
1111
+ onUnrecognized: configured ?? (signaturesRequired ? "reject" : "unsigned"),
1112
+ };
1113
+ };
1114
+ /** Bound a host operation and clean up resources returned after cancellation. */
1115
+ const abortable = (operation, signal, disposeLate) => new Promise((resolve, reject) => {
1116
+ let aborted = signal.aborted;
1117
+ const onAbort = () => {
1118
+ aborted = true;
1119
+ signal.removeEventListener("abort", onAbort);
1120
+ reject(signal.reason);
1121
+ };
1122
+ if (aborted)
1123
+ onAbort();
1124
+ else
1125
+ signal.addEventListener("abort", onAbort, { once: true });
1126
+ void operation.then((value) => {
1127
+ signal.removeEventListener("abort", onAbort);
1128
+ if (aborted) {
1129
+ void Promise.resolve()
1130
+ .then(() => disposeLate?.(value))
1131
+ .catch(() => undefined);
1132
+ }
1133
+ else
1134
+ resolve(value);
1135
+ }, (error) => {
1136
+ signal.removeEventListener("abort", onAbort);
1137
+ reject(error);
1138
+ });
1139
+ });