@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.
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +44 -2
- package/dist/admission.d.ts +19 -0
- package/dist/admission.js +106 -0
- package/dist/answer.d.ts +51 -0
- package/dist/answer.js +100 -0
- package/dist/auth.d.ts +49 -0
- package/dist/auth.js +89 -0
- package/dist/config.d.ts +346 -0
- package/dist/config.js +540 -0
- package/dist/convert.d.ts +46 -0
- package/dist/convert.js +180 -0
- package/dist/errors.d.ts +36 -0
- package/dist/errors.js +93 -0
- package/dist/host.d.ts +143 -0
- package/dist/host.js +353 -0
- package/dist/http.d.ts +29 -0
- package/dist/http.js +243 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/kv.d.ts +51 -0
- package/dist/kv.js +144 -0
- package/dist/ledger.d.ts +59 -0
- package/dist/ledger.js +94 -0
- package/dist/media.d.ts +37 -0
- package/dist/media.js +136 -0
- package/dist/openai.d.ts +180 -0
- package/dist/openai.js +172 -0
- package/dist/serve.d.ts +61 -0
- package/dist/serve.js +201 -0
- package/dist/service.d.ts +85 -0
- package/dist/service.js +1139 -0
- package/dist/stream.d.ts +62 -0
- package/dist/stream.js +255 -0
- package/package.json +71 -4
package/dist/openai.d.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The supported subset of the OpenAI Chat Completions API: request
|
|
3
|
+
* validation and response construction. Unknown request fields are accepted
|
|
4
|
+
* and ignored, as OpenAI-compatible servers conventionally do; fields that
|
|
5
|
+
* would change what a run may do are refused.
|
|
6
|
+
*/
|
|
7
|
+
import type { ModelUsage } from "@clearideas/agent-runtime-contracts";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
declare const textPartSchema: z.ZodObject<{
|
|
10
|
+
type: z.ZodLiteral<"text">;
|
|
11
|
+
text: z.ZodString;
|
|
12
|
+
}, z.core.$loose>;
|
|
13
|
+
declare const imagePartSchema: z.ZodObject<{
|
|
14
|
+
type: z.ZodLiteral<"image_url">;
|
|
15
|
+
image_url: z.ZodObject<{
|
|
16
|
+
url: z.ZodString;
|
|
17
|
+
}, z.core.$loose>;
|
|
18
|
+
}, z.core.$loose>;
|
|
19
|
+
declare const filePartSchema: z.ZodObject<{
|
|
20
|
+
type: z.ZodLiteral<"file">;
|
|
21
|
+
file: z.ZodObject<{
|
|
22
|
+
file_data: z.ZodOptional<z.ZodString>;
|
|
23
|
+
file_id: z.ZodOptional<z.ZodString>;
|
|
24
|
+
filename: z.ZodOptional<z.ZodString>;
|
|
25
|
+
}, z.core.$loose>;
|
|
26
|
+
}, z.core.$loose>;
|
|
27
|
+
declare const refusalPartSchema: z.ZodObject<{
|
|
28
|
+
type: z.ZodLiteral<"refusal">;
|
|
29
|
+
refusal: z.ZodString;
|
|
30
|
+
}, z.core.$loose>;
|
|
31
|
+
declare const otherPartSchema: z.ZodObject<{
|
|
32
|
+
type: z.ZodString;
|
|
33
|
+
}, z.core.$loose>;
|
|
34
|
+
export type OpenAiContentPart = z.infer<typeof textPartSchema> | z.infer<typeof imagePartSchema> | z.infer<typeof filePartSchema> | z.infer<typeof refusalPartSchema> | z.infer<typeof otherPartSchema>;
|
|
35
|
+
export declare const chatMessageSchema: z.ZodObject<{
|
|
36
|
+
role: z.ZodEnum<{
|
|
37
|
+
assistant: "assistant";
|
|
38
|
+
developer: "developer";
|
|
39
|
+
function: "function";
|
|
40
|
+
system: "system";
|
|
41
|
+
tool: "tool";
|
|
42
|
+
user: "user";
|
|
43
|
+
}>;
|
|
44
|
+
content: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodType<OpenAiContentPart, unknown, z.core.$ZodTypeInternals<OpenAiContentPart, unknown>>>, z.ZodNull]>>;
|
|
45
|
+
name: z.ZodOptional<z.ZodString>;
|
|
46
|
+
refusal: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
47
|
+
tool_calls: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnknown>>>;
|
|
48
|
+
function_call: z.ZodOptional<z.ZodUnknown>;
|
|
49
|
+
tool_call_id: z.ZodOptional<z.ZodString>;
|
|
50
|
+
}, z.core.$loose>;
|
|
51
|
+
export type ChatMessage = z.infer<typeof chatMessageSchema>;
|
|
52
|
+
export declare const chatCompletionRequestSchema: z.ZodObject<{
|
|
53
|
+
model: z.ZodString;
|
|
54
|
+
messages: z.ZodArray<z.ZodObject<{
|
|
55
|
+
role: z.ZodEnum<{
|
|
56
|
+
assistant: "assistant";
|
|
57
|
+
developer: "developer";
|
|
58
|
+
function: "function";
|
|
59
|
+
system: "system";
|
|
60
|
+
tool: "tool";
|
|
61
|
+
user: "user";
|
|
62
|
+
}>;
|
|
63
|
+
content: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodType<OpenAiContentPart, unknown, z.core.$ZodTypeInternals<OpenAiContentPart, unknown>>>, z.ZodNull]>>;
|
|
64
|
+
name: z.ZodOptional<z.ZodString>;
|
|
65
|
+
refusal: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
66
|
+
tool_calls: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnknown>>>;
|
|
67
|
+
function_call: z.ZodOptional<z.ZodUnknown>;
|
|
68
|
+
tool_call_id: z.ZodOptional<z.ZodString>;
|
|
69
|
+
}, z.core.$loose>>;
|
|
70
|
+
stream: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
|
|
71
|
+
stream_options: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
72
|
+
include_usage: z.ZodOptional<z.ZodBoolean>;
|
|
73
|
+
}, z.core.$loose>>>;
|
|
74
|
+
user: z.ZodOptional<z.ZodString>;
|
|
75
|
+
max_tokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
76
|
+
max_completion_tokens: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
77
|
+
response_format: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodObject<{
|
|
78
|
+
type: z.ZodLiteral<"text">;
|
|
79
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
80
|
+
type: z.ZodLiteral<"json_object">;
|
|
81
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
82
|
+
type: z.ZodLiteral<"json_schema">;
|
|
83
|
+
json_schema: z.ZodObject<{
|
|
84
|
+
name: z.ZodOptional<z.ZodString>;
|
|
85
|
+
schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
86
|
+
}, z.core.$loose>;
|
|
87
|
+
}, z.core.$loose>]>>>;
|
|
88
|
+
n: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
89
|
+
tools: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnknown>>>;
|
|
90
|
+
functions: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodUnknown>>>;
|
|
91
|
+
tool_choice: z.ZodOptional<z.ZodUnknown>;
|
|
92
|
+
logprobs: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
|
|
93
|
+
top_logprobs: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
94
|
+
audio: z.ZodOptional<z.ZodUnknown>;
|
|
95
|
+
modalities: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
|
|
96
|
+
variables: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
|
|
97
|
+
}, z.core.$loose>;
|
|
98
|
+
export type ChatCompletionRequest = z.infer<typeof chatCompletionRequestSchema>;
|
|
99
|
+
/**
|
|
100
|
+
* Validate a request body and refuse parameters the server does not honor.
|
|
101
|
+
* Client tools are never used: with `ignore` they are dropped, with `reject`
|
|
102
|
+
* they are refused.
|
|
103
|
+
*/
|
|
104
|
+
export declare const parseChatCompletionRequest: (body: unknown, clientTools?: "ignore" | "reject") => ChatCompletionRequest;
|
|
105
|
+
/** True when the request carries client tool definitions. */
|
|
106
|
+
export declare const hasClientTools: (request: ChatCompletionRequest) => boolean;
|
|
107
|
+
/** OpenAI usage, from the run's aggregated model usage. */
|
|
108
|
+
export interface OpenAiUsage {
|
|
109
|
+
prompt_tokens: number;
|
|
110
|
+
completion_tokens: number;
|
|
111
|
+
total_tokens: number;
|
|
112
|
+
prompt_tokens_details?: {
|
|
113
|
+
cached_tokens: number;
|
|
114
|
+
};
|
|
115
|
+
completion_tokens_details?: {
|
|
116
|
+
reasoning_tokens: number;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export declare const toOpenAiUsage: (usage: ModelUsage | undefined) => OpenAiUsage;
|
|
120
|
+
export type FinishReason = "stop" | "length";
|
|
121
|
+
export interface CompletionIdentity {
|
|
122
|
+
id: string;
|
|
123
|
+
created: number;
|
|
124
|
+
model: string;
|
|
125
|
+
systemFingerprint: string;
|
|
126
|
+
}
|
|
127
|
+
export declare const chatCompletion: (identity: CompletionIdentity, content: string, finishReason: FinishReason, usage: OpenAiUsage) => {
|
|
128
|
+
id: string;
|
|
129
|
+
object: "chat.completion";
|
|
130
|
+
created: number;
|
|
131
|
+
model: string;
|
|
132
|
+
system_fingerprint: string;
|
|
133
|
+
choices: {
|
|
134
|
+
index: number;
|
|
135
|
+
message: {
|
|
136
|
+
role: "assistant";
|
|
137
|
+
content: string;
|
|
138
|
+
refusal: null;
|
|
139
|
+
};
|
|
140
|
+
logprobs: null;
|
|
141
|
+
finish_reason: FinishReason;
|
|
142
|
+
}[];
|
|
143
|
+
usage: OpenAiUsage;
|
|
144
|
+
};
|
|
145
|
+
export interface ChunkDelta {
|
|
146
|
+
role?: "assistant";
|
|
147
|
+
content?: string;
|
|
148
|
+
reasoning_content?: string;
|
|
149
|
+
reasoning?: string;
|
|
150
|
+
}
|
|
151
|
+
export declare const chatCompletionChunk: (identity: CompletionIdentity, delta: ChunkDelta, finishReason?: FinishReason | null) => {
|
|
152
|
+
id: string;
|
|
153
|
+
object: "chat.completion.chunk";
|
|
154
|
+
created: number;
|
|
155
|
+
model: string;
|
|
156
|
+
system_fingerprint: string;
|
|
157
|
+
choices: {
|
|
158
|
+
index: number;
|
|
159
|
+
delta: ChunkDelta;
|
|
160
|
+
logprobs: null;
|
|
161
|
+
finish_reason: FinishReason | null;
|
|
162
|
+
}[];
|
|
163
|
+
};
|
|
164
|
+
export declare const usageChunk: (identity: CompletionIdentity, usage: OpenAiUsage) => {
|
|
165
|
+
id: string;
|
|
166
|
+
object: "chat.completion.chunk";
|
|
167
|
+
created: number;
|
|
168
|
+
model: string;
|
|
169
|
+
system_fingerprint: string;
|
|
170
|
+
choices: never[];
|
|
171
|
+
usage: OpenAiUsage;
|
|
172
|
+
};
|
|
173
|
+
export declare const modelObject: (name: string, created: number, description?: string) => {
|
|
174
|
+
id: string;
|
|
175
|
+
object: "model";
|
|
176
|
+
created: number;
|
|
177
|
+
owned_by: string;
|
|
178
|
+
description?: string;
|
|
179
|
+
};
|
|
180
|
+
export {};
|
package/dist/openai.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { invalidRequest } from "./errors.js";
|
|
3
|
+
const textPartSchema = z.looseObject({
|
|
4
|
+
type: z.literal("text"),
|
|
5
|
+
text: z.string(),
|
|
6
|
+
});
|
|
7
|
+
const imagePartSchema = z.looseObject({
|
|
8
|
+
type: z.literal("image_url"),
|
|
9
|
+
image_url: z.looseObject({ url: z.string().min(1) }),
|
|
10
|
+
});
|
|
11
|
+
const filePartSchema = z.looseObject({
|
|
12
|
+
type: z.literal("file"),
|
|
13
|
+
file: z.looseObject({
|
|
14
|
+
file_data: z.string().min(1).optional(),
|
|
15
|
+
file_id: z.string().min(1).optional(),
|
|
16
|
+
filename: z.string().min(1).optional(),
|
|
17
|
+
}),
|
|
18
|
+
});
|
|
19
|
+
const refusalPartSchema = z.looseObject({
|
|
20
|
+
type: z.literal("refusal"),
|
|
21
|
+
refusal: z.string(),
|
|
22
|
+
});
|
|
23
|
+
const otherPartSchema = z.looseObject({ type: z.string() });
|
|
24
|
+
const contentPartSchema = z.union([
|
|
25
|
+
textPartSchema,
|
|
26
|
+
imagePartSchema,
|
|
27
|
+
filePartSchema,
|
|
28
|
+
refusalPartSchema,
|
|
29
|
+
otherPartSchema,
|
|
30
|
+
]);
|
|
31
|
+
export const chatMessageSchema = z.looseObject({
|
|
32
|
+
role: z.enum([
|
|
33
|
+
"system",
|
|
34
|
+
"developer",
|
|
35
|
+
"user",
|
|
36
|
+
"assistant",
|
|
37
|
+
"tool",
|
|
38
|
+
"function",
|
|
39
|
+
]),
|
|
40
|
+
content: z
|
|
41
|
+
.union([z.string(), z.array(contentPartSchema), z.null()])
|
|
42
|
+
.optional(),
|
|
43
|
+
name: z.string().optional(),
|
|
44
|
+
refusal: z.string().nullable().optional(),
|
|
45
|
+
tool_calls: z.array(z.unknown()).nullable().optional(),
|
|
46
|
+
function_call: z.unknown().optional(),
|
|
47
|
+
tool_call_id: z.string().optional(),
|
|
48
|
+
});
|
|
49
|
+
const responseFormatSchema = z.union([
|
|
50
|
+
z.looseObject({ type: z.literal("text") }),
|
|
51
|
+
z.looseObject({ type: z.literal("json_object") }),
|
|
52
|
+
z.looseObject({
|
|
53
|
+
type: z.literal("json_schema"),
|
|
54
|
+
json_schema: z.looseObject({
|
|
55
|
+
name: z.string().optional(),
|
|
56
|
+
schema: z.record(z.string(), z.unknown()).optional(),
|
|
57
|
+
}),
|
|
58
|
+
}),
|
|
59
|
+
]);
|
|
60
|
+
export const chatCompletionRequestSchema = z.looseObject({
|
|
61
|
+
model: z.string().min(1),
|
|
62
|
+
messages: z.array(chatMessageSchema).min(1),
|
|
63
|
+
stream: z.boolean().nullable().optional(),
|
|
64
|
+
stream_options: z
|
|
65
|
+
.looseObject({ include_usage: z.boolean().optional() })
|
|
66
|
+
.nullable()
|
|
67
|
+
.optional(),
|
|
68
|
+
user: z.string().max(256).optional(),
|
|
69
|
+
max_tokens: z.number().int().positive().nullable().optional(),
|
|
70
|
+
max_completion_tokens: z.number().int().positive().nullable().optional(),
|
|
71
|
+
response_format: responseFormatSchema.nullable().optional(),
|
|
72
|
+
n: z.number().int().positive().nullable().optional(),
|
|
73
|
+
tools: z.array(z.unknown()).nullable().optional(),
|
|
74
|
+
functions: z.array(z.unknown()).nullable().optional(),
|
|
75
|
+
tool_choice: z.unknown().optional(),
|
|
76
|
+
logprobs: z.boolean().nullable().optional(),
|
|
77
|
+
top_logprobs: z.number().int().nullable().optional(),
|
|
78
|
+
audio: z.unknown().optional(),
|
|
79
|
+
modalities: z.array(z.string()).nullable().optional(),
|
|
80
|
+
/** Extension: values for variables the operator mapped with source `client`. */
|
|
81
|
+
variables: z.record(z.string(), z.unknown()).nullable().optional(),
|
|
82
|
+
});
|
|
83
|
+
/**
|
|
84
|
+
* Validate a request body and refuse parameters the server does not honor.
|
|
85
|
+
* Client tools are never used: with `ignore` they are dropped, with `reject`
|
|
86
|
+
* they are refused.
|
|
87
|
+
*/
|
|
88
|
+
export const parseChatCompletionRequest = (body, clientTools = "reject") => {
|
|
89
|
+
const parsed = chatCompletionRequestSchema.safeParse(body);
|
|
90
|
+
if (!parsed.success) {
|
|
91
|
+
const issue = parsed.error.issues[0];
|
|
92
|
+
throw invalidRequest(`Invalid request: ${issue ? `${issue.path.join(".") || "body"}: ${issue.message}` : "malformed body"}.`, issue?.path.length ? String(issue.path[0]) : undefined);
|
|
93
|
+
}
|
|
94
|
+
const request = parsed.data;
|
|
95
|
+
if (clientTools === "reject") {
|
|
96
|
+
if ((request.tools?.length ?? 0) > 0 ||
|
|
97
|
+
(request.functions?.length ?? 0) > 0)
|
|
98
|
+
throw invalidRequest("Client-defined tools are not supported. The served agent's tools are configured by the host.", request.tools?.length ? "tools" : "functions");
|
|
99
|
+
if (request.tool_choice != null &&
|
|
100
|
+
request.tool_choice !== "none" &&
|
|
101
|
+
request.tool_choice !== "auto")
|
|
102
|
+
throw invalidRequest("tool_choice is not supported: the served agent's tools are configured by the host.", "tool_choice");
|
|
103
|
+
}
|
|
104
|
+
if ((request.n ?? 1) > 1)
|
|
105
|
+
throw invalidRequest("Only n = 1 is supported.", "n");
|
|
106
|
+
if (request.logprobs === true)
|
|
107
|
+
throw invalidRequest("logprobs are not supported.", "logprobs");
|
|
108
|
+
if (request.audio != null || request.modalities?.includes("audio"))
|
|
109
|
+
throw invalidRequest("Audio output is not supported.", "modalities");
|
|
110
|
+
return request;
|
|
111
|
+
};
|
|
112
|
+
/** True when the request carries client tool definitions. */
|
|
113
|
+
export const hasClientTools = (request) => (request.tools?.length ?? 0) > 0 || (request.functions?.length ?? 0) > 0;
|
|
114
|
+
export const toOpenAiUsage = (usage) => {
|
|
115
|
+
const prompt = usage?.inputTokens ?? 0;
|
|
116
|
+
const completion = usage?.outputTokens ?? 0;
|
|
117
|
+
return {
|
|
118
|
+
prompt_tokens: prompt,
|
|
119
|
+
completion_tokens: completion,
|
|
120
|
+
total_tokens: usage?.totalTokens ?? prompt + completion,
|
|
121
|
+
...(usage?.cachedInputTokens != null
|
|
122
|
+
? { prompt_tokens_details: { cached_tokens: usage.cachedInputTokens } }
|
|
123
|
+
: {}),
|
|
124
|
+
...(usage?.reasoningTokens != null
|
|
125
|
+
? {
|
|
126
|
+
completion_tokens_details: {
|
|
127
|
+
reasoning_tokens: usage.reasoningTokens,
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
: {}),
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
export const chatCompletion = (identity, content, finishReason, usage) => ({
|
|
134
|
+
id: identity.id,
|
|
135
|
+
object: "chat.completion",
|
|
136
|
+
created: identity.created,
|
|
137
|
+
model: identity.model,
|
|
138
|
+
system_fingerprint: identity.systemFingerprint,
|
|
139
|
+
choices: [
|
|
140
|
+
{
|
|
141
|
+
index: 0,
|
|
142
|
+
message: { role: "assistant", content, refusal: null },
|
|
143
|
+
logprobs: null,
|
|
144
|
+
finish_reason: finishReason,
|
|
145
|
+
},
|
|
146
|
+
],
|
|
147
|
+
usage,
|
|
148
|
+
});
|
|
149
|
+
export const chatCompletionChunk = (identity, delta, finishReason = null) => ({
|
|
150
|
+
id: identity.id,
|
|
151
|
+
object: "chat.completion.chunk",
|
|
152
|
+
created: identity.created,
|
|
153
|
+
model: identity.model,
|
|
154
|
+
system_fingerprint: identity.systemFingerprint,
|
|
155
|
+
choices: [{ index: 0, delta, logprobs: null, finish_reason: finishReason }],
|
|
156
|
+
});
|
|
157
|
+
export const usageChunk = (identity, usage) => ({
|
|
158
|
+
id: identity.id,
|
|
159
|
+
object: "chat.completion.chunk",
|
|
160
|
+
created: identity.created,
|
|
161
|
+
model: identity.model,
|
|
162
|
+
system_fingerprint: identity.systemFingerprint,
|
|
163
|
+
choices: [],
|
|
164
|
+
usage,
|
|
165
|
+
});
|
|
166
|
+
export const modelObject = (name, created, description) => ({
|
|
167
|
+
id: name,
|
|
168
|
+
object: "model",
|
|
169
|
+
created,
|
|
170
|
+
owned_by: "agent-runtime",
|
|
171
|
+
...(description ? { description } : {}),
|
|
172
|
+
});
|
package/dist/serve.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type InputSourceConfig, type LoadedServerConfig } from "./config.js";
|
|
2
|
+
import type { HostRuntime } from "./host.js";
|
|
3
|
+
import { type ServerLogger } from "./service.js";
|
|
4
|
+
export interface ServeOptions {
|
|
5
|
+
/** Serve one manifest. Mutually exclusive with `serverConfig`. */
|
|
6
|
+
manifest?: string;
|
|
7
|
+
/** Server configuration file. Without it, one is discovered in `cwd`. */
|
|
8
|
+
serverConfig?: string;
|
|
9
|
+
/** Do not look for a server configuration file (single-manifest mode). */
|
|
10
|
+
noServerConfig?: boolean;
|
|
11
|
+
cwd?: string;
|
|
12
|
+
host?: string;
|
|
13
|
+
port?: number;
|
|
14
|
+
/** Environment variable holding an API key that may use every model. */
|
|
15
|
+
apiKeyEnv?: string;
|
|
16
|
+
allowUnauthenticated?: boolean;
|
|
17
|
+
servedModelName?: string;
|
|
18
|
+
runtimeConfig?: string;
|
|
19
|
+
runtimeModule?: string;
|
|
20
|
+
input?: Record<string, InputSourceConfig>;
|
|
21
|
+
output?: string;
|
|
22
|
+
streamMode?: "auto" | "live" | "committed";
|
|
23
|
+
progress?: "none" | "status";
|
|
24
|
+
storeDriver?: "memory" | "sqlite";
|
|
25
|
+
store?: string;
|
|
26
|
+
ledger?: string;
|
|
27
|
+
onUnrecognized?: "unsigned" | "reject" | "restart";
|
|
28
|
+
clientTools?: "ignore" | "reject";
|
|
29
|
+
maxConcurrentRuns?: number;
|
|
30
|
+
requestTimeoutMs?: number;
|
|
31
|
+
warmup?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** The environment variable read for an API key when none is named. */
|
|
34
|
+
export declare const DEFAULT_API_KEY_ENV = "AGENT_RUNTIME_API_KEY";
|
|
35
|
+
/**
|
|
36
|
+
* Resolve the configuration `serve` would use, and notes worth telling the
|
|
37
|
+
* operator. An explicit argument always beats a discovered file.
|
|
38
|
+
*/
|
|
39
|
+
export declare const resolveServeConfig: (options: ServeOptions, environment?: Readonly<Record<string, string | undefined>>) => Promise<{
|
|
40
|
+
loaded: LoadedServerConfig;
|
|
41
|
+
notes: string[];
|
|
42
|
+
}>;
|
|
43
|
+
export interface RunServeIo {
|
|
44
|
+
stdout(text: string): void;
|
|
45
|
+
stderr(text: string): void;
|
|
46
|
+
}
|
|
47
|
+
export interface RunServeHooks {
|
|
48
|
+
/** Adapters supplied in code (embedding, tests). */
|
|
49
|
+
runtime?: HostRuntime;
|
|
50
|
+
logger?: ServerLogger;
|
|
51
|
+
environment?: Readonly<Record<string, string | undefined>>;
|
|
52
|
+
/** Called once listening, with the base URL. */
|
|
53
|
+
onListening?(url: string): void;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Start serving and return when `signal` aborts, after a graceful shutdown.
|
|
57
|
+
* With `check`, validate everything, print a summary, and return.
|
|
58
|
+
*/
|
|
59
|
+
export declare const runServe: (options: ServeOptions & {
|
|
60
|
+
check?: boolean;
|
|
61
|
+
}, io: RunServeIo, signal: AbortSignal | undefined, hooks?: RunServeHooks) => Promise<void>;
|
package/dist/serve.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-runtime serve`: resolve the server configuration from a file, a
|
|
3
|
+
* discovered file, or command-line options; start; and stop on a signal.
|
|
4
|
+
*/
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { FileAgentManifestSource } from "@clearideas/agent-runtime-store-local";
|
|
7
|
+
import { defaultServedModelName, discoverServerConfigFile, loadServerConfig, SERVER_CONFIG_FILE_NAMES, singleManifestServerConfig, } from "./config.js";
|
|
8
|
+
import { listen } from "./http.js";
|
|
9
|
+
import { AgentServer, jsonLogger } from "./service.js";
|
|
10
|
+
/** The environment variable read for an API key when none is named. */
|
|
11
|
+
export const DEFAULT_API_KEY_ENV = "AGENT_RUNTIME_API_KEY";
|
|
12
|
+
/**
|
|
13
|
+
* Resolve the configuration `serve` would use, and notes worth telling the
|
|
14
|
+
* operator. An explicit argument always beats a discovered file.
|
|
15
|
+
*/
|
|
16
|
+
export const resolveServeConfig = async (options, environment = process.env) => {
|
|
17
|
+
const cwd = options.cwd ?? process.cwd();
|
|
18
|
+
const notes = [];
|
|
19
|
+
if (options.manifest && options.serverConfig) {
|
|
20
|
+
throw new Error("Serve either one manifest or a server configuration, not both.");
|
|
21
|
+
}
|
|
22
|
+
let loaded;
|
|
23
|
+
if (options.serverConfig) {
|
|
24
|
+
loaded = await loadServerConfig(path.resolve(cwd, options.serverConfig));
|
|
25
|
+
}
|
|
26
|
+
else if (options.manifest) {
|
|
27
|
+
if (!options.noServerConfig) {
|
|
28
|
+
const discovered = await discoverServerConfigFile(cwd);
|
|
29
|
+
if (discovered) {
|
|
30
|
+
notes.push(`Ignoring ${path.basename(discovered)}: a manifest argument selects single-manifest mode.`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const manifestFile = path.resolve(cwd, options.manifest);
|
|
34
|
+
const manifest = await new FileAgentManifestSource(path.dirname(manifestFile), path.basename(manifestFile)).loadManifest();
|
|
35
|
+
const ledger = options.ledger
|
|
36
|
+
? parseLedgerOption(options.ledger, cwd)
|
|
37
|
+
: undefined;
|
|
38
|
+
loaded = singleManifestServerConfig({
|
|
39
|
+
manifest: manifestFile,
|
|
40
|
+
servedModelName: options.servedModelName ??
|
|
41
|
+
defaultServedModelName(manifestFile, manifest.id),
|
|
42
|
+
...(options.runtimeConfig
|
|
43
|
+
? { runtimeConfig: path.resolve(cwd, options.runtimeConfig) }
|
|
44
|
+
: {}),
|
|
45
|
+
...(options.runtimeModule
|
|
46
|
+
? { runtimeModule: path.resolve(cwd, options.runtimeModule) }
|
|
47
|
+
: {}),
|
|
48
|
+
...(options.input ? { input: options.input } : {}),
|
|
49
|
+
...(options.output ? { output: options.output } : {}),
|
|
50
|
+
...(options.streamMode ? { streamMode: options.streamMode } : {}),
|
|
51
|
+
...(options.progress ? { progress: options.progress } : {}),
|
|
52
|
+
...(options.storeDriver
|
|
53
|
+
? {
|
|
54
|
+
store: {
|
|
55
|
+
driver: options.storeDriver,
|
|
56
|
+
...(options.store
|
|
57
|
+
? { path: path.resolve(cwd, options.store) }
|
|
58
|
+
: {}),
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
: {}),
|
|
62
|
+
...(ledger ? { ledger } : {}),
|
|
63
|
+
...(options.onUnrecognized
|
|
64
|
+
? { onUnrecognized: options.onUnrecognized }
|
|
65
|
+
: {}),
|
|
66
|
+
...(options.clientTools ? { clientTools: options.clientTools } : {}),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
const discovered = await discoverServerConfigFile(cwd);
|
|
71
|
+
if (!discovered) {
|
|
72
|
+
throw new Error(`No server configuration found. Looked for ${SERVER_CONFIG_FILE_NAMES.join(", ")} in ${cwd}. Pass --server-config <file>, or serve one manifest: agent-runtime serve ./agent.yaml`);
|
|
73
|
+
}
|
|
74
|
+
loaded = await loadServerConfig(discovered);
|
|
75
|
+
notes.push(`Using ${discovered}.`);
|
|
76
|
+
}
|
|
77
|
+
if (options.manifest === undefined &&
|
|
78
|
+
(options.servedModelName ||
|
|
79
|
+
options.input ||
|
|
80
|
+
options.output ||
|
|
81
|
+
options.streamMode ||
|
|
82
|
+
options.progress ||
|
|
83
|
+
options.storeDriver ||
|
|
84
|
+
options.ledger ||
|
|
85
|
+
options.onUnrecognized ||
|
|
86
|
+
options.clientTools)) {
|
|
87
|
+
throw new Error("Model, store, and ledger options apply to single-manifest mode; set them in the server configuration file instead.");
|
|
88
|
+
}
|
|
89
|
+
// Command-line overrides of the server section.
|
|
90
|
+
const server = {
|
|
91
|
+
...loaded.config.server,
|
|
92
|
+
...(options.host ? { host: options.host } : {}),
|
|
93
|
+
...(options.port !== undefined ? { port: options.port } : {}),
|
|
94
|
+
...(options.maxConcurrentRuns
|
|
95
|
+
? { maxConcurrentRuns: options.maxConcurrentRuns }
|
|
96
|
+
: {}),
|
|
97
|
+
...(options.requestTimeoutMs
|
|
98
|
+
? { requestTimeoutMs: options.requestTimeoutMs }
|
|
99
|
+
: {}),
|
|
100
|
+
...(options.allowUnauthenticated ? { allowUnauthenticated: true } : {}),
|
|
101
|
+
};
|
|
102
|
+
// An API key from the environment: always when named, otherwise only when
|
|
103
|
+
// the configuration defines no keys.
|
|
104
|
+
let apiKeys = loaded.config.auth.apiKeys;
|
|
105
|
+
const keyEnv = options.apiKeyEnv ?? DEFAULT_API_KEY_ENV;
|
|
106
|
+
if (options.apiKeyEnv && !environment[options.apiKeyEnv]) {
|
|
107
|
+
throw new Error(`--api-key-env names ${options.apiKeyEnv}, which is not set.`);
|
|
108
|
+
}
|
|
109
|
+
if (environment[keyEnv] &&
|
|
110
|
+
(options.apiKeyEnv !== undefined || apiKeys.length === 0)) {
|
|
111
|
+
if (apiKeys.some((key) => key.id === "default")) {
|
|
112
|
+
throw new Error(`The configuration already defines an API key with id "default"; remove it or omit --api-key-env.`);
|
|
113
|
+
}
|
|
114
|
+
apiKeys = [
|
|
115
|
+
...apiKeys,
|
|
116
|
+
{ id: "default", key: { env: keyEnv }, models: "*" },
|
|
117
|
+
];
|
|
118
|
+
notes.push(`Requiring the API key in ${keyEnv}.`);
|
|
119
|
+
}
|
|
120
|
+
// Host-level overrides that apply to a configuration file as well.
|
|
121
|
+
const runtimeOverrides = options.manifest === undefined
|
|
122
|
+
? {
|
|
123
|
+
...(options.runtimeConfig
|
|
124
|
+
? { runtimeConfig: path.resolve(cwd, options.runtimeConfig) }
|
|
125
|
+
: {}),
|
|
126
|
+
...(options.runtimeModule
|
|
127
|
+
? { runtimeModule: path.resolve(cwd, options.runtimeModule) }
|
|
128
|
+
: {}),
|
|
129
|
+
}
|
|
130
|
+
: {};
|
|
131
|
+
const config = {
|
|
132
|
+
...loaded.config,
|
|
133
|
+
...runtimeOverrides,
|
|
134
|
+
server,
|
|
135
|
+
auth: { ...loaded.config.auth, apiKeys },
|
|
136
|
+
};
|
|
137
|
+
return { loaded: { ...loaded, config }, notes };
|
|
138
|
+
};
|
|
139
|
+
const parseLedgerOption = (value, cwd) => {
|
|
140
|
+
if (value === "memory")
|
|
141
|
+
return { driver: "memory" };
|
|
142
|
+
if (value.startsWith("sqlite:") && value.length > "sqlite:".length)
|
|
143
|
+
return { driver: "sqlite", path: path.resolve(cwd, value.slice(7)) };
|
|
144
|
+
throw new Error("--ledger must be memory or sqlite:<path>.");
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Start serving and return when `signal` aborts, after a graceful shutdown.
|
|
148
|
+
* With `check`, validate everything, print a summary, and return.
|
|
149
|
+
*/
|
|
150
|
+
export const runServe = async (options, io, signal, hooks = {}) => {
|
|
151
|
+
const environment = hooks.environment ?? process.env;
|
|
152
|
+
const { loaded, notes } = await resolveServeConfig(options, environment);
|
|
153
|
+
for (const note of notes)
|
|
154
|
+
io.stderr(`${note}\n`);
|
|
155
|
+
const server = await AgentServer.create({
|
|
156
|
+
loaded,
|
|
157
|
+
environment,
|
|
158
|
+
logger: hooks.logger ?? jsonLogger((line) => io.stderr(line)),
|
|
159
|
+
...(hooks.runtime ? { runtime: hooks.runtime } : {}),
|
|
160
|
+
...(options.warmup ? { warmup: true } : {}),
|
|
161
|
+
});
|
|
162
|
+
const summary = {
|
|
163
|
+
models: server.models.map((model) => ({
|
|
164
|
+
name: model.name,
|
|
165
|
+
mode: model.mode,
|
|
166
|
+
manifest: model.manifestFile,
|
|
167
|
+
...(model.mode === "conversation"
|
|
168
|
+
? {
|
|
169
|
+
signaturesRequired: model.signaturesRequired,
|
|
170
|
+
onUnrecognized: model.onUnrecognized,
|
|
171
|
+
}
|
|
172
|
+
: {
|
|
173
|
+
input: model.input.map((entry) => `${entry.variable}=${entry.source}`),
|
|
174
|
+
}),
|
|
175
|
+
})),
|
|
176
|
+
authentication: server.authenticated ? "required" : "none",
|
|
177
|
+
};
|
|
178
|
+
if (options.check) {
|
|
179
|
+
await server.shutdown(0);
|
|
180
|
+
io.stdout(`${JSON.stringify({ valid: true, ...summary }, null, 2)}\n`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (signal?.aborted) {
|
|
184
|
+
await server.shutdown(0);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const listening = await listen(server);
|
|
188
|
+
io.stderr(`Agent Runtime server listening on ${listening.url}/v1 (${summary.models
|
|
189
|
+
.map((model) => model.name)
|
|
190
|
+
.join(", ")}; authentication ${summary.authentication})\n`);
|
|
191
|
+
hooks.onListening?.(listening.url);
|
|
192
|
+
await new Promise((resolve) => {
|
|
193
|
+
if (!signal)
|
|
194
|
+
return;
|
|
195
|
+
if (signal.aborted)
|
|
196
|
+
resolve();
|
|
197
|
+
signal.addEventListener("abort", () => resolve(), { once: true });
|
|
198
|
+
});
|
|
199
|
+
io.stderr("Shutting down: finishing active runs.\n");
|
|
200
|
+
await listening.close();
|
|
201
|
+
};
|