@clearideas/agent-runtime-server 0.0.0-stage → 0.10.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/dist/host.js ADDED
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Host composition shared by every Agent Runtime host: the CLI's `run` and
3
+ * `worker` commands and the OpenAI-compatible server.
4
+ *
5
+ * This module decides what a manifest may use. It loads a trusted runtime
6
+ * module, validates the adapters it supplies, composes the runtime
7
+ * configuration, merges the two with host-supplied adapters, selects step
8
+ * executors for a trust mode, and assembles `AgentRuntime` dependencies. Keep
9
+ * it the only place that does so, so the host boundary is reviewed once.
10
+ */
11
+ import { access } from "node:fs/promises";
12
+ import path from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import { JexlConditionEvaluator } from "@clearideas/agent-runtime-condition-jexl";
15
+ import { composeRuntime, emptyAgentRuntimeConfig, loadAgentRuntimeConfig, } from "@clearideas/agent-runtime-config";
16
+ import { executionPoliciesSchema, runLimitsSchema, } from "@clearideas/agent-runtime-contracts";
17
+ import { LoopStepExecutor } from "@clearideas/agent-runtime-step-loop";
18
+ import { PromptMessageHistoryCompactor, PromptStepExecutor, } from "@clearideas/agent-runtime-step-prompt";
19
+ import { ApprovalStepExecutor, CodeStepExecutor, SubRunStepExecutor, WebhookStepExecutor, } from "@clearideas/agent-runtime-step-standard";
20
+ const adapterMethod = (value, name) => value != null &&
21
+ typeof value === "object" &&
22
+ typeof value[name] === "function";
23
+ /** Reject adapters that do not implement their port. */
24
+ export const validateHostRuntime = (runtime) => {
25
+ if (runtime.shutdown !== undefined && typeof runtime.shutdown !== "function")
26
+ throw new Error("Runtime shutdown must be a function.");
27
+ if (runtime.runStore &&
28
+ (!adapterMethod(runtime.runStore, "createRun") ||
29
+ !adapterMethod(runtime.runStore, "loadRun") ||
30
+ !adapterMethod(runtime.runStore, "saveCheckpoint"))) {
31
+ throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
32
+ }
33
+ if (runtime.artifactStore &&
34
+ (!adapterMethod(runtime.artifactStore, "put") ||
35
+ !adapterMethod(runtime.artifactStore, "get"))) {
36
+ throw new Error("Runtime artifactStore must implement ArtifactStore.put() and get().");
37
+ }
38
+ if (runtime.model && !adapterMethod(runtime.model, "generate"))
39
+ throw new Error("Runtime model must implement ModelAdapter.generate().");
40
+ if (runtime.tools &&
41
+ (!adapterMethod(runtime.tools, "listTools") ||
42
+ !adapterMethod(runtime.tools, "executeTool"))) {
43
+ throw new Error("Runtime tools must implement ToolAdapter.listTools() and executeTool().");
44
+ }
45
+ if (runtime.connectionCredentials &&
46
+ !adapterMethod(runtime.connectionCredentials, "getCredential")) {
47
+ throw new Error("Runtime connectionCredentials must implement ConnectionCredentialProvider.getCredential().");
48
+ }
49
+ if (runtime.approvals && !adapterMethod(runtime.approvals, "requestApproval"))
50
+ throw new Error("Runtime approvals must implement ApprovalAdapter.requestApproval().");
51
+ if (runtime.sandbox && !adapterMethod(runtime.sandbox, "execute"))
52
+ throw new Error("Runtime sandbox must implement SandboxAdapter.execute().");
53
+ if (runtime.subRuns && !adapterMethod(runtime.subRuns, "execute"))
54
+ throw new Error("Runtime subRuns must implement SubRunAdapter.execute().");
55
+ if (runtime.summarizer && !adapterMethod(runtime.summarizer, "summarize"))
56
+ throw new Error("Runtime summarizer must implement ContextSummarizerAdapter.summarize().");
57
+ if (runtime.workspaces &&
58
+ !adapterMethod(runtime.workspaces, "resolveWorkspace")) {
59
+ throw new Error("Runtime workspaces must implement WorkspaceProvider.resolveWorkspace().");
60
+ }
61
+ if (runtime.runSandbox &&
62
+ (!adapterMethod(runtime.runSandbox, "open") ||
63
+ !adapterMethod(runtime.runSandbox, "validate") ||
64
+ !adapterMethod(runtime.runSandbox, "tools"))) {
65
+ throw new Error("Runtime runSandbox must implement RunSandboxProvider.tools(), validate(), and open().");
66
+ }
67
+ if (runtime.sandboxProvider &&
68
+ (!adapterMethod(runtime.sandboxProvider, "create") ||
69
+ !adapterMethod(runtime.sandboxProvider, "execute") ||
70
+ !adapterMethod(runtime.sandboxProvider, "terminate"))) {
71
+ throw new Error("Runtime sandboxProvider must implement the SandboxProvider lifecycle methods.");
72
+ }
73
+ if (runtime.eventSinks &&
74
+ (!Array.isArray(runtime.eventSinks) ||
75
+ runtime.eventSinks.some((sink) => !adapterMethod(sink, "emit")))) {
76
+ throw new Error("Runtime eventSinks must be an array of EventSink values.");
77
+ }
78
+ if (runtime.stepExecutors &&
79
+ (!Array.isArray(runtime.stepExecutors) ||
80
+ runtime.stepExecutors.some((executor) => !executor ||
81
+ typeof executor !== "object" ||
82
+ typeof executor.type !== "string" ||
83
+ !adapterMethod(executor, "execute")))) {
84
+ throw new Error("Runtime stepExecutors must implement StepExecutor.");
85
+ }
86
+ return runtime;
87
+ };
88
+ /** Resolve the accepted export aliases of a static runtime module. */
89
+ const normalizeRuntime = (runtime) => ({
90
+ ...(runtime.shutdown ? { shutdown: runtime.shutdown } : {}),
91
+ ...((runtime.runStore ?? runtime.store)
92
+ ? { runStore: runtime.runStore ?? runtime.store }
93
+ : {}),
94
+ ...((runtime.artifactStore ?? runtime.artifacts)
95
+ ? { artifactStore: runtime.artifactStore ?? runtime.artifacts }
96
+ : {}),
97
+ ...((runtime.model ?? runtime.modelAdapter)
98
+ ? { model: runtime.model ?? runtime.modelAdapter }
99
+ : {}),
100
+ ...((runtime.tools ?? runtime.toolAdapter)
101
+ ? { tools: runtime.tools ?? runtime.toolAdapter }
102
+ : {}),
103
+ ...((runtime.connectionCredentials ?? runtime.credentialProvider)
104
+ ? {
105
+ connectionCredentials: runtime.connectionCredentials ?? runtime.credentialProvider,
106
+ }
107
+ : {}),
108
+ ...((runtime.approvals ?? runtime.approvalAdapter)
109
+ ? { approvals: runtime.approvals ?? runtime.approvalAdapter }
110
+ : {}),
111
+ ...((runtime.sandbox ?? runtime.sandboxAdapter)
112
+ ? { sandbox: runtime.sandbox ?? runtime.sandboxAdapter }
113
+ : {}),
114
+ ...((runtime.subRuns ?? runtime.subRunAdapter)
115
+ ? { subRuns: runtime.subRuns ?? runtime.subRunAdapter }
116
+ : {}),
117
+ ...((runtime.workspaces ?? runtime.workspaceProvider)
118
+ ? { workspaces: runtime.workspaces ?? runtime.workspaceProvider }
119
+ : {}),
120
+ ...((runtime.runSandbox ?? runtime.runSandboxProvider)
121
+ ? { runSandbox: runtime.runSandbox ?? runtime.runSandboxProvider }
122
+ : {}),
123
+ ...(runtime.sandboxProvider
124
+ ? { sandboxProvider: runtime.sandboxProvider }
125
+ : {}),
126
+ ...(runtime.policies
127
+ ? { policies: executionPoliciesSchema.parse(runtime.policies) }
128
+ : {}),
129
+ ...(runtime.enforcedPolicies
130
+ ? {
131
+ enforcedPolicies: executionPoliciesSchema.parse(runtime.enforcedPolicies),
132
+ }
133
+ : {}),
134
+ ...(runtime.limits ? { limits: runLimitsSchema.parse(runtime.limits) } : {}),
135
+ ...(runtime.enforcedLimits
136
+ ? { enforcedLimits: runLimitsSchema.parse(runtime.enforcedLimits) }
137
+ : {}),
138
+ ...(runtime.summarizer ? { summarizer: runtime.summarizer } : {}),
139
+ ...(runtime.messages ? { messages: runtime.messages } : {}),
140
+ ...((runtime.eventSinks?.length ?? 0) > 0 || runtime.eventSink
141
+ ? {
142
+ eventSinks: [
143
+ ...(runtime.eventSinks ?? []),
144
+ ...(runtime.eventSink ? [runtime.eventSink] : []),
145
+ ],
146
+ }
147
+ : {}),
148
+ ...((runtime.stepExecutors?.length ?? 0) > 0 ||
149
+ (runtime.executors?.length ?? 0) > 0
150
+ ? { stepExecutors: runtime.stepExecutors ?? runtime.executors }
151
+ : {}),
152
+ });
153
+ const defaultStepExecutors = (trust) => [
154
+ new PromptStepExecutor(),
155
+ new LoopStepExecutor(),
156
+ // Only a local operator's own manifests may reach arbitrary webhook
157
+ // destinations. Other hosts supply a WebhookStepExecutor with
158
+ // authorizeDestination through the runtime module's stepExecutors.
159
+ ...(trust === "local-operator"
160
+ ? [new WebhookStepExecutor({ allowUnsafeDestinations: true })]
161
+ : []),
162
+ new ApprovalStepExecutor(),
163
+ new CodeStepExecutor(),
164
+ new SubRunStepExecutor(),
165
+ ];
166
+ /**
167
+ * The step executors for a trust mode. Executors supplied by the runtime
168
+ * replace the default for their step type.
169
+ */
170
+ export const resolveHostStepExecutors = (runtime, trust) => {
171
+ const byType = new Map(defaultStepExecutors(trust).map((executor) => [executor.type, executor]));
172
+ for (const executor of runtime.stepExecutors ?? [])
173
+ byType.set(executor.type, executor);
174
+ return [...byType.values()];
175
+ };
176
+ const importRuntimeModule = async (modulePath) => {
177
+ const absolutePath = path.resolve(modulePath);
178
+ try {
179
+ return {
180
+ absolutePath,
181
+ imported: (await import(pathToFileURL(absolutePath).href)),
182
+ };
183
+ }
184
+ catch (error) {
185
+ throw new Error(`Could not load runtime module ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
186
+ }
187
+ };
188
+ /**
189
+ * Load a trusted local ESM runtime module and return its validated
190
+ * adapters. A module exports adapters directly, as `default` or `runtime`,
191
+ * or through `createRuntime(context)`. Without a path, returns no adapters.
192
+ * A host that manages its own run store passes `createRunStore: false`, so a
193
+ * module's `createRunStore` is not called for every run.
194
+ */
195
+ export const loadHostRuntime = async (modulePath, context, options = {}) => {
196
+ if (!modulePath)
197
+ return {};
198
+ const { absolutePath, imported } = await importRuntimeModule(modulePath);
199
+ const staticRuntime = imported.default ?? imported.runtime ?? imported;
200
+ const composedRuntime = imported.createRuntime
201
+ ? await imported.createRuntime(context)
202
+ : normalizeRuntime(staticRuntime);
203
+ if (!composedRuntime || typeof composedRuntime !== "object") {
204
+ throw new Error(`Runtime module ${absolutePath} did not export a runtime object.`);
205
+ }
206
+ const runtime = !composedRuntime.runStore &&
207
+ imported.createRunStore &&
208
+ options.createRunStore !== false
209
+ ? { ...composedRuntime, runStore: await imported.createRunStore(context) }
210
+ : composedRuntime;
211
+ return validateHostRuntime(runtime);
212
+ };
213
+ /** Load only a runtime module's run store, for commands that need no manifest. */
214
+ export const loadHostRunStore = async (modulePath, context) => {
215
+ if (!modulePath)
216
+ return undefined;
217
+ const { imported } = await importRuntimeModule(modulePath);
218
+ const staticRuntime = imported.default ?? imported.runtime ?? imported;
219
+ const store = imported.createRunStore
220
+ ? await imported.createRunStore(context)
221
+ : (staticRuntime.runStore ?? staticRuntime.store);
222
+ if (store &&
223
+ (!adapterMethod(store, "createRun") ||
224
+ !adapterMethod(store, "loadRun") ||
225
+ !adapterMethod(store, "saveCheckpoint"))) {
226
+ throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
227
+ }
228
+ return store;
229
+ };
230
+ /** Runtime configuration files discovered beside a manifest, in order. */
231
+ export const RUNTIME_CONFIG_FILE_NAMES = [
232
+ "agent-runtime.config.yaml",
233
+ "agent-runtime.config.yml",
234
+ "agent-runtime.config.json",
235
+ ];
236
+ /**
237
+ * Load the requested runtime configuration, or the first discovered
238
+ * `agent-runtime.config.*` in `searchDirectory`, or an empty configuration.
239
+ */
240
+ export const resolveAgentRuntimeConfig = async (requested, searchDirectory = process.cwd()) => {
241
+ if (requested)
242
+ return loadAgentRuntimeConfig(requested);
243
+ for (const candidate of RUNTIME_CONFIG_FILE_NAMES) {
244
+ const absolute = path.resolve(searchDirectory, candidate);
245
+ try {
246
+ await access(absolute);
247
+ return await loadAgentRuntimeConfig(absolute);
248
+ }
249
+ catch (error) {
250
+ if (error.code !== "ENOENT")
251
+ throw error;
252
+ }
253
+ }
254
+ return emptyAgentRuntimeConfig();
255
+ };
256
+ /**
257
+ * Workspace and sandbox adapters from runtimes, highest precedence first.
258
+ * Host-supplied adapters take precedence over the configuration.
259
+ */
260
+ export const hostWorkspaceCompositionOptions = (...runtimes) => {
261
+ const options = {};
262
+ for (const runtime of runtimes) {
263
+ if (runtime.workspaces && !options.provider)
264
+ options.provider = runtime.workspaces;
265
+ if (runtime.runSandbox && !options.runSandbox)
266
+ options.runSandbox = runtime.runSandbox;
267
+ if (runtime.sandboxProvider && !options.sandboxProvider)
268
+ options.sandboxProvider = runtime.sandboxProvider;
269
+ }
270
+ return options;
271
+ };
272
+ /** Overlay a runtime on another; message options and event sinks combine. */
273
+ export const mergeHostRuntimes = (base, overlay) => validateHostRuntime({
274
+ ...base,
275
+ ...overlay,
276
+ ...(base.messages || overlay.messages
277
+ ? { messages: { ...base.messages, ...overlay.messages } }
278
+ : {}),
279
+ ...((base.eventSinks?.length ?? 0) > 0 ||
280
+ (overlay.eventSinks?.length ?? 0) > 0
281
+ ? {
282
+ eventSinks: [
283
+ ...(base.eventSinks ?? []),
284
+ ...(overlay.eventSinks ?? []),
285
+ ],
286
+ }
287
+ : {}),
288
+ });
289
+ /**
290
+ * Compose a manifest's runtime: adapters from the configuration, overlaid by
291
+ * supplied runtimes in increasing precedence (for example, the runtime
292
+ * module, then adapters an embedding host passes in code). A supplied model
293
+ * or tool adapter replaces the configured one.
294
+ */
295
+ export const composeHostRuntime = (manifest, config, supplied, options = {}) => {
296
+ const highestFirst = [...supplied].reverse();
297
+ const credentialProvider = highestFirst.find((runtime) => runtime.connectionCredentials)?.connectionCredentials;
298
+ const configured = composeRuntime(manifest, config, options.environment ? { environment: options.environment } : {}, {
299
+ model: !supplied.some((runtime) => runtime.model),
300
+ tools: !supplied.some((runtime) => runtime.tools),
301
+ workspaceOptions: {
302
+ ...options.workspaceOptions,
303
+ ...hostWorkspaceCompositionOptions(...highestFirst),
304
+ },
305
+ ...(options.modelPolicy ? { modelPolicy: options.modelPolicy } : {}),
306
+ ...(options.toolOptions || credentialProvider
307
+ ? {
308
+ toolOptions: {
309
+ ...options.toolOptions,
310
+ ...(credentialProvider ? { credentialProvider } : {}),
311
+ },
312
+ }
313
+ : {}),
314
+ });
315
+ return supplied.reduce((merged, runtime) => mergeHostRuntimes(merged, runtime), validateHostRuntime(configured));
316
+ };
317
+ /**
318
+ * A runtime's message options with the prompt package's history compactor,
319
+ * so summarizing history policies pass preflight.
320
+ */
321
+ export const withHistoryCompactor = (options) => ({
322
+ compactor: new PromptMessageHistoryCompactor(),
323
+ ...options,
324
+ });
325
+ /** `AgentRuntime` dependencies for a composed host runtime. */
326
+ export const hostRuntimeDependencies = (runtime, options) => ({
327
+ ...(options.onEventSinkError
328
+ ? { onEventSinkError: options.onEventSinkError }
329
+ : {}),
330
+ runStore: options.runStore,
331
+ ...(options.agentManifestSource
332
+ ? { agentManifestSource: options.agentManifestSource }
333
+ : {}),
334
+ stepExecutors: resolveHostStepExecutors(runtime, options.trust),
335
+ conditionEvaluator: new JexlConditionEvaluator(),
336
+ eventSinks: [...(options.eventSinks ?? []), ...(runtime.eventSinks ?? [])],
337
+ ...(runtime.model ? { model: runtime.model } : {}),
338
+ ...(runtime.tools ? { tools: runtime.tools } : {}),
339
+ ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
340
+ ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
341
+ ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
342
+ ...(runtime.workspaces ? { workspaces: runtime.workspaces } : {}),
343
+ ...(runtime.runSandbox ? { runSandbox: runtime.runSandbox } : {}),
344
+ ...(runtime.policies ? { policies: runtime.policies } : {}),
345
+ ...(runtime.enforcedPolicies
346
+ ? { enforcedPolicies: runtime.enforcedPolicies }
347
+ : {}),
348
+ ...(runtime.limits ? { limits: runtime.limits } : {}),
349
+ ...(runtime.enforcedLimits ? { enforcedLimits: runtime.enforcedLimits } : {}),
350
+ ...(runtime.summarizer ? { summarizer: runtime.summarizer } : {}),
351
+ messages: withHistoryCompactor(runtime.messages),
352
+ ...(options.artifacts ? { artifacts: options.artifacts } : {}),
353
+ ...(options.maxParallelSteps
354
+ ? { maxParallelSteps: options.maxParallelSteps }
355
+ : {}),
356
+ ...(options.eventSinkFailurePolicy
357
+ ? { eventSinkFailurePolicy: options.eventSinkFailurePolicy }
358
+ : {}),
359
+ });
package/dist/http.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Transport adapters for the agent service: a node:http request listener and
3
+ * server, and a fetch-style handler for hosts built on Request/Response.
4
+ */
5
+ import { type IncomingMessage, type Server, type ServerResponse } from "node:http";
6
+ import type { AddressInfo } from "node:net";
7
+ import type { AgentServer } from "./service.js";
8
+ /** A node:http request listener for the service. */
9
+ export declare const createRequestListener: (server: AgentServer) => (request: IncomingMessage, response: ServerResponse) => void;
10
+ export interface ListeningServer {
11
+ /** Base URL, for example http://127.0.0.1:8000 */
12
+ url: string;
13
+ address: AddressInfo;
14
+ http: Server;
15
+ /** Stop accepting connections, drain runs, and release resources. */
16
+ close(graceMs?: number): Promise<void>;
17
+ }
18
+ /** Listen on the configured host and port. */
19
+ export declare const listen: (server: AgentServer, options?: {
20
+ host?: string;
21
+ port?: number;
22
+ }) => Promise<ListeningServer>;
23
+ /**
24
+ * A fetch-style handler, for hosts built on the Request/Response API. Mount
25
+ * it under a path prefix by passing `basePath`.
26
+ */
27
+ export declare const createFetchHandler: (server: AgentServer, options?: {
28
+ basePath?: string;
29
+ }) => (request: Request) => Promise<Response>;
package/dist/http.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Transport adapters for the agent service: a node:http request listener and
3
+ * server, and a fetch-style handler for hosts built on Request/Response.
4
+ */
5
+ import { createServer, } from "node:http";
6
+ import { ServerError } from "./errors.js";
7
+ const readNodeBody = (request, limit, signal) => new Promise((resolve, reject) => {
8
+ const chunks = [];
9
+ let size = 0;
10
+ const cleanup = () => {
11
+ request.off("data", onData);
12
+ request.off("end", onEnd);
13
+ request.off("error", onError);
14
+ signal?.removeEventListener("abort", onAbort);
15
+ };
16
+ const onError = (error) => {
17
+ cleanup();
18
+ request.pause();
19
+ reject(error);
20
+ };
21
+ const onAbort = () => onError(signal?.reason);
22
+ const onData = (chunk) => {
23
+ size += chunk.byteLength;
24
+ if (size > limit)
25
+ onError(tooLarge(limit));
26
+ else
27
+ chunks.push(chunk);
28
+ };
29
+ const onEnd = () => {
30
+ cleanup();
31
+ resolve(Buffer.concat(chunks, size));
32
+ };
33
+ if (signal?.aborted) {
34
+ onAbort();
35
+ return;
36
+ }
37
+ const declared = Number(request.headers["content-length"]);
38
+ if (Number.isFinite(declared) && declared > limit) {
39
+ onError(tooLarge(limit));
40
+ return;
41
+ }
42
+ signal?.addEventListener("abort", onAbort, { once: true });
43
+ request.on("data", onData);
44
+ request.on("end", onEnd);
45
+ request.on("error", onError);
46
+ });
47
+ const tooLarge = (limit) => new ServerError(413, "request_too_large", `The request body exceeds ${limit} bytes.`);
48
+ const writeBody = async (response, body) => {
49
+ response.flushHeaders();
50
+ for await (const chunk of body) {
51
+ if (response.destroyed)
52
+ break;
53
+ if (!response.write(chunk)) {
54
+ await new Promise((resolve) => {
55
+ const done = () => {
56
+ response.off("drain", done);
57
+ response.off("close", done);
58
+ resolve();
59
+ };
60
+ response.on("drain", done);
61
+ response.on("close", done);
62
+ });
63
+ }
64
+ }
65
+ };
66
+ /** A node:http request listener for the service. */
67
+ export const createRequestListener = (server) => (request, response) => {
68
+ const disconnected = new AbortController();
69
+ // A closed socket before the response finished is a client disconnect.
70
+ response.on("close", () => {
71
+ if (!response.writableFinished)
72
+ disconnected.abort();
73
+ });
74
+ let url;
75
+ try {
76
+ url = new URL(request.url ?? "/", "http://localhost");
77
+ }
78
+ catch {
79
+ response.writeHead(400, { "content-type": "application/json" });
80
+ response.end(JSON.stringify({
81
+ error: {
82
+ message: "Invalid request target.",
83
+ type: "invalid_request_error",
84
+ param: null,
85
+ code: "invalid_request",
86
+ },
87
+ }));
88
+ return;
89
+ }
90
+ const serviceRequest = {
91
+ method: request.method ?? "GET",
92
+ path: url.pathname,
93
+ headers: request.headers,
94
+ readBody: (limit, signal) => readNodeBody(request, limit, signal),
95
+ signal: disconnected.signal,
96
+ };
97
+ void server
98
+ .handle(serviceRequest)
99
+ .then(async (result) => {
100
+ if (response.destroyed)
101
+ return;
102
+ // Finish an error response before closing an unfinished upload.
103
+ if (!request.complete)
104
+ result.headers.connection = "close";
105
+ response.writeHead(result.status, result.headers);
106
+ if (result.body === undefined)
107
+ response.end();
108
+ else if (typeof result.body === "string")
109
+ response.end(result.body);
110
+ else {
111
+ const iterator = result.body[Symbol.asyncIterator]();
112
+ const closeIterator = () => {
113
+ void iterator.return?.();
114
+ };
115
+ response.once("close", closeIterator);
116
+ await writeBody(response, { [Symbol.asyncIterator]: () => iterator });
117
+ response.off("close", closeIterator);
118
+ response.end();
119
+ }
120
+ })
121
+ .catch(() => {
122
+ if (!response.headersSent) {
123
+ response.writeHead(500, { "content-type": "application/json" });
124
+ response.end(JSON.stringify({
125
+ error: {
126
+ message: "Internal server error.",
127
+ type: "server_error",
128
+ param: null,
129
+ code: "internal_error",
130
+ },
131
+ }));
132
+ }
133
+ else
134
+ response.destroy();
135
+ });
136
+ };
137
+ /** Listen on the configured host and port. */
138
+ export const listen = async (server, options = {}) => {
139
+ const host = options.host ?? server.config.server.host;
140
+ const port = options.port ?? server.config.server.port;
141
+ const http = createServer({
142
+ // Keep idle connections longer than common load balancer timeouts.
143
+ keepAliveTimeout: 65_000,
144
+ headersTimeout: 66_000,
145
+ // Runs are bounded by requestTimeoutMs, not the socket.
146
+ requestTimeout: 0,
147
+ }, createRequestListener(server));
148
+ await new Promise((resolve, reject) => {
149
+ http.once("error", reject);
150
+ http.listen(port, host, () => {
151
+ http.off("error", reject);
152
+ resolve();
153
+ });
154
+ });
155
+ const address = http.address();
156
+ const displayHost = address.family === "IPv6" ? `[${address.address}]` : address.address;
157
+ return {
158
+ url: `http://${displayHost}:${address.port}`,
159
+ address,
160
+ http,
161
+ close: async (graceMs) => {
162
+ const closed = new Promise((resolve) => http.close(() => resolve()));
163
+ http.closeIdleConnections();
164
+ await server.shutdown(graceMs);
165
+ http.closeAllConnections();
166
+ await closed;
167
+ },
168
+ };
169
+ };
170
+ /**
171
+ * A fetch-style handler, for hosts built on the Request/Response API. Mount
172
+ * it under a path prefix by passing `basePath`.
173
+ */
174
+ export const createFetchHandler = (server, options = {}) => async (request) => {
175
+ const url = new URL(request.url);
176
+ const basePath = options.basePath?.replace(/\/+$/u, "") ?? "";
177
+ const pathname = basePath && url.pathname.startsWith(basePath)
178
+ ? url.pathname.slice(basePath.length) || "/"
179
+ : url.pathname;
180
+ const headers = {};
181
+ request.headers.forEach((value, key) => {
182
+ headers[key] = value;
183
+ });
184
+ const result = await server.handle({
185
+ method: request.method,
186
+ path: pathname,
187
+ headers,
188
+ readBody: async (limit, signal) => {
189
+ if (!request.body)
190
+ return Buffer.alloc(0);
191
+ const reader = request.body.getReader();
192
+ const chunks = [];
193
+ let size = 0;
194
+ const cancel = () => {
195
+ void reader.cancel().catch(() => undefined);
196
+ };
197
+ signal?.addEventListener("abort", cancel, { once: true });
198
+ try {
199
+ if (signal?.aborted) {
200
+ cancel();
201
+ signal.throwIfAborted();
202
+ }
203
+ while (true) {
204
+ const { done, value } = await reader.read();
205
+ signal?.throwIfAborted();
206
+ if (done)
207
+ return Buffer.concat(chunks, size);
208
+ size += value.byteLength;
209
+ if (size > limit) {
210
+ cancel();
211
+ throw tooLarge(limit);
212
+ }
213
+ chunks.push(Buffer.from(value));
214
+ }
215
+ }
216
+ finally {
217
+ signal?.removeEventListener("abort", cancel);
218
+ reader.releaseLock();
219
+ }
220
+ },
221
+ signal: request.signal,
222
+ });
223
+ if (result.body === undefined || typeof result.body === "string") {
224
+ return new Response(result.body ?? null, {
225
+ status: result.status,
226
+ headers: result.headers,
227
+ });
228
+ }
229
+ const iterator = result.body[Symbol.asyncIterator]();
230
+ const encoder = new TextEncoder();
231
+ return new Response(new ReadableStream({
232
+ async pull(controller) {
233
+ const next = await iterator.next();
234
+ if (next.done)
235
+ controller.close();
236
+ else
237
+ controller.enqueue(encoder.encode(next.value));
238
+ },
239
+ async cancel() {
240
+ await iterator.return?.();
241
+ },
242
+ }), { status: result.status, headers: result.headers });
243
+ };
@@ -0,0 +1,9 @@
1
+ export * from "./host.js";
2
+ export { defaultServedModelName, discoverServerConfigFile, loadServerConfig, parseDuration, parseServerConfig, SERVER_CONFIG_FILE_NAMES, SERVER_CONFIG_SCHEMA_VERSION, serverConfigSchema, singleManifestServerConfig, type ApiKeyConfig, type InputSourceConfig, type KeyValueStoreConfig, type LoadedServerConfig, type ServedModelConfig, type ServerConfig, type ServerConfigInput, type SingleManifestOptions, } from "./config.js";
3
+ export { ANONYMOUS_PRINCIPAL, type AuthenticateHook, type AuthenticationRequest, type HostPrincipal, type Principal, } from "./auth.js";
4
+ export { ServerError, type OpenAiErrorBody } from "./errors.js";
5
+ export { MemoryKeyValueStore, SqliteKeyValueStore, type KeyValueStore, } from "./kv.js";
6
+ export { ConversationLedger, ledgerKey, projectConversation, type LedgerEntry, type LedgerMatch, } from "./ledger.js";
7
+ export { AgentServer, jsonLogger, silentLogger, type AgentServerOptions, type ServedModel, type ServerLogger, type ServiceRequest, type ServiceResponse, } from "./service.js";
8
+ export { createFetchHandler, createRequestListener, listen, type ListeningServer, } from "./http.js";
9
+ export { DEFAULT_API_KEY_ENV, resolveServeConfig, runServe, type RunServeHooks, type RunServeIo, type ServeOptions, } from "./serve.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./host.js";
2
+ export { defaultServedModelName, discoverServerConfigFile, loadServerConfig, parseDuration, parseServerConfig, SERVER_CONFIG_FILE_NAMES, SERVER_CONFIG_SCHEMA_VERSION, serverConfigSchema, singleManifestServerConfig, } from "./config.js";
3
+ export { ANONYMOUS_PRINCIPAL, } from "./auth.js";
4
+ export { ServerError } from "./errors.js";
5
+ export { MemoryKeyValueStore, SqliteKeyValueStore, } from "./kv.js";
6
+ export { ConversationLedger, ledgerKey, projectConversation, } from "./ledger.js";
7
+ export { AgentServer, jsonLogger, silentLogger, } from "./service.js";
8
+ export { createFetchHandler, createRequestListener, listen, } from "./http.js";
9
+ export { DEFAULT_API_KEY_ENV, resolveServeConfig, runServe, } from "./serve.js";