@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/config.js ADDED
@@ -0,0 +1,543 @@
1
+ /**
2
+ * Server configuration: the operator-trusted description of what the server
3
+ * exposes, to whom, and with which limits. Nothing here is ever read from a
4
+ * request.
5
+ */
6
+ import { access, readFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { agentRunExecutionSchema, executionPoliciesSchema, runLimitsSchema, } from "@clearideas/agent-runtime-contracts";
9
+ import { parse as parseYaml } from "yaml";
10
+ import { z } from "zod";
11
+ export const SERVER_CONFIG_SCHEMA_VERSION = "1.0";
12
+ /** Server configuration files discovered in the working directory, in order. */
13
+ export const SERVER_CONFIG_FILE_NAMES = [
14
+ "agent-runtime.server.yaml",
15
+ "agent-runtime.server.yml",
16
+ "agent-runtime.server.json",
17
+ ];
18
+ const DURATION_UNITS = {
19
+ ms: 1,
20
+ s: 1_000,
21
+ m: 60_000,
22
+ h: 3_600_000,
23
+ d: 86_400_000,
24
+ };
25
+ /** Parse `250ms`, `15s`, `5m`, `1h`, `7d`, or a number of milliseconds. */
26
+ export const parseDuration = (value) => {
27
+ if (typeof value === "number") {
28
+ if (!Number.isSafeInteger(value) || value <= 0)
29
+ throw new Error(`Duration must be a positive integer of milliseconds.`);
30
+ return value;
31
+ }
32
+ const match = /^(\d+)(ms|s|m|h|d)$/u.exec(value.trim());
33
+ if (!match) {
34
+ throw new Error(`Invalid duration "${value}"; use a number of milliseconds or a value such as 500ms, 15s, 5m, 1h, or 7d.`);
35
+ }
36
+ const milliseconds = Number(match[1]) * DURATION_UNITS[match[2]];
37
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0)
38
+ throw new Error(`Duration "${value}" is out of range.`);
39
+ return milliseconds;
40
+ };
41
+ const durationSchema = z
42
+ .union([z.number(), z.string()])
43
+ .transform((value, context) => {
44
+ try {
45
+ return parseDuration(value);
46
+ }
47
+ catch (error) {
48
+ context.addIssue({
49
+ code: "custom",
50
+ message: error instanceof Error ? error.message : String(error),
51
+ });
52
+ return z.NEVER;
53
+ }
54
+ });
55
+ const positiveInteger = z.number().int().positive().safe();
56
+ const environmentName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
57
+ const storeName = z.string().regex(/^[a-z][a-z0-9-]*$/u);
58
+ const variableKey = z.string().min(1).max(100);
59
+ /** An OpenAI model id: letters, digits, and `.`, `_`, `-`, `:`, `/`. */
60
+ export const servedModelNameSchema = z
61
+ .string()
62
+ .min(1)
63
+ .max(200)
64
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u, "Model names may contain letters, digits, and . _ - : / characters.");
65
+ const keyValueStoreSchema = z.discriminatedUnion("driver", [
66
+ z.strictObject({
67
+ driver: z.literal("memory"),
68
+ /** Upper bound on entries; the least recently used are evicted. */
69
+ maxEntries: positiveInteger.default(100_000),
70
+ }),
71
+ z.strictObject({
72
+ driver: z.literal("sqlite"),
73
+ path: z.string().min(1),
74
+ }),
75
+ ]);
76
+ /** Where one variable of a run gets its value from a chat request. */
77
+ const inputSourceSchema = z.union([
78
+ z.enum(["last-user", "transcript", "system", "json", "client"]),
79
+ z.strictObject({
80
+ source: z.literal("last-user"),
81
+ }),
82
+ z.strictObject({
83
+ source: z.literal("transcript"),
84
+ /** Only the newest earlier messages. */
85
+ maxMessages: positiveInteger.optional(),
86
+ }),
87
+ z.strictObject({
88
+ source: z.literal("system"),
89
+ }),
90
+ z.strictObject({
91
+ source: z.literal("json"),
92
+ /** Field of the JSON object in the newest user message. Defaults to the variable's key. */
93
+ key: z.string().min(1).optional(),
94
+ }),
95
+ z.strictObject({
96
+ source: z.literal("client"),
97
+ /** Field of the request's `variables` object. Defaults to the variable's key. */
98
+ key: z.string().min(1).optional(),
99
+ }),
100
+ ]);
101
+ export const normalizeInputMapping = (variable, source) => {
102
+ const value = typeof source === "string" ? { source } : source;
103
+ switch (value.source) {
104
+ case "json":
105
+ case "client":
106
+ return {
107
+ variable,
108
+ source: value.source,
109
+ key: ("key" in value ? value.key : undefined) ?? variable,
110
+ };
111
+ case "transcript":
112
+ return {
113
+ variable,
114
+ source: "transcript",
115
+ ...("maxMessages" in value && value.maxMessages != null
116
+ ? { maxMessages: value.maxMessages }
117
+ : {}),
118
+ };
119
+ default:
120
+ return { variable, source: value.source };
121
+ }
122
+ };
123
+ const outputSchema = z.strictObject({
124
+ /** `final`, `step:<id>`, or `variable:<name>`. Variable mode only. */
125
+ from: z
126
+ .string()
127
+ .regex(/^(final|step:.+|variable:.+)$/u, "output.from must be final, step:<id>, or variable:<name>.")
128
+ .default("final"),
129
+ });
130
+ const streamSchema = z.strictObject({
131
+ mode: z.enum(["auto", "live", "committed"]).default("auto"),
132
+ progress: z.enum(["none", "status"]).default("none"),
133
+ reasoning: z.enum(["none", "answer-step"]).default("none"),
134
+ progressField: z
135
+ .enum(["reasoning_content", "reasoning"])
136
+ .default("reasoning_content"),
137
+ });
138
+ export const servedModelConfigSchema = z.strictObject({
139
+ name: servedModelNameSchema,
140
+ /** Path to the agent manifest, relative to the configuration file. */
141
+ manifest: z.string().min(1),
142
+ description: z.string().optional(),
143
+ /** What happens to client system and developer messages. */
144
+ clientInstructions: z
145
+ .string()
146
+ .regex(/^(drop|variable:.+)$/u, "clientInstructions must be drop or variable:<name>.")
147
+ .default("drop"),
148
+ /** Run variables filled from the request, by variable key. */
149
+ input: z.record(variableKey, inputSourceSchema).optional(),
150
+ output: outputSchema.default({ from: "final" }),
151
+ stream: streamSchema.default({
152
+ mode: "auto",
153
+ progress: "none",
154
+ reasoning: "none",
155
+ progressField: "reasoning_content",
156
+ }),
157
+ budget: z.strictObject({ maxTotalTokens: positiveInteger }).optional(),
158
+ execution: agentRunExecutionSchema.optional(),
159
+ policies: executionPoliciesSchema.optional(),
160
+ enforcedPolicies: executionPoliciesSchema.optional(),
161
+ /** Default run limits for this model's runs, and ceilings on them. */
162
+ limits: runLimitsSchema.optional(),
163
+ enforcedLimits: runLimitsSchema.optional(),
164
+ /** What a client disconnect does to its run. */
165
+ onDisconnect: z.enum(["cancel", "continue"]).default("cancel"),
166
+ /** `budget` maps max_tokens to the run's token budget, capped by the host. */
167
+ maxTokens: z.enum(["ignore", "budget"]).default("ignore"),
168
+ /**
169
+ * Client-defined tools are never exposed or executed. `ignore` drops them,
170
+ * and client tool history, from the request (chat front ends such as Open
171
+ * WebUI attach their own tools to every request); `reject` refuses them.
172
+ */
173
+ clientTools: z.enum(["ignore", "reject"]).default("ignore"),
174
+ });
175
+ const apiKeySchema = z.strictObject({
176
+ /** Stable identifier used in logs, metrics, and the conversation scope. */
177
+ id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u),
178
+ key: z.union([
179
+ z.strictObject({ env: environmentName }),
180
+ z.strictObject({
181
+ sha256: z
182
+ .string()
183
+ .regex(/^[0-9a-f]{64}$/u, "sha256 must be 64 lowercase hex digits."),
184
+ }),
185
+ ]),
186
+ /** Served model names this key may use, or `"*"` for all. */
187
+ models: z.union([z.literal("*"), z.array(servedModelNameSchema).min(1)]),
188
+ maxConcurrentRuns: positiveInteger.optional(),
189
+ maxTotalTokensPerRequest: positiveInteger.optional(),
190
+ });
191
+ const serverSectionDefaults = {
192
+ host: "127.0.0.1",
193
+ port: 8000,
194
+ maxRequestBytes: 20 * 1024 * 1024,
195
+ requestTimeoutMs: 600_000,
196
+ shutdownGraceMs: 30_000,
197
+ heartbeatMs: 15_000,
198
+ maxConcurrentRuns: 32,
199
+ maxQueuedRequests: 64,
200
+ queueTimeoutMs: 30_000,
201
+ cors: { origins: [] },
202
+ exposeErrors: false,
203
+ allowUnauthenticated: false,
204
+ };
205
+ export const serverConfigSchema = z
206
+ .strictObject({
207
+ version: z.literal(SERVER_CONFIG_SCHEMA_VERSION),
208
+ server: z
209
+ .strictObject({
210
+ host: z.string().min(1).default(serverSectionDefaults.host),
211
+ port: z
212
+ .number()
213
+ .int()
214
+ .min(0)
215
+ .max(65_535)
216
+ .default(serverSectionDefaults.port),
217
+ maxRequestBytes: positiveInteger.default(serverSectionDefaults.maxRequestBytes),
218
+ requestTimeoutMs: durationSchema.default(serverSectionDefaults.requestTimeoutMs),
219
+ shutdownGraceMs: durationSchema.default(serverSectionDefaults.shutdownGraceMs),
220
+ heartbeatMs: durationSchema.default(serverSectionDefaults.heartbeatMs),
221
+ maxConcurrentRuns: positiveInteger.default(serverSectionDefaults.maxConcurrentRuns),
222
+ maxQueuedRequests: z
223
+ .number()
224
+ .int()
225
+ .nonnegative()
226
+ .default(serverSectionDefaults.maxQueuedRequests),
227
+ queueTimeoutMs: durationSchema.default(serverSectionDefaults.queueTimeoutMs),
228
+ cors: z
229
+ .strictObject({ origins: z.array(z.string().min(1)).default([]) })
230
+ .default({ origins: [] }),
231
+ exposeErrors: z.boolean().default(false),
232
+ /** Required to serve without authentication on a non-loopback address. */
233
+ allowUnauthenticated: z.boolean().default(false),
234
+ })
235
+ .default(serverSectionDefaults),
236
+ /** Runtime configuration: providers, models, connections, workspaces, sandbox, messages. */
237
+ runtimeConfig: z.string().min(1).optional(),
238
+ /** Trusted runtime module supplying adapters and hooks. */
239
+ runtimeModule: z.string().min(1).optional(),
240
+ store: z
241
+ .strictObject({
242
+ driver: z.enum(["memory", "sqlite", "module"]).default("memory"),
243
+ path: z.string().min(1).optional(),
244
+ retention: z
245
+ .strictObject({
246
+ completed: durationSchema.default(86_400_000),
247
+ failed: durationSchema.default(604_800_000),
248
+ })
249
+ .default({ completed: 86_400_000, failed: 604_800_000 }),
250
+ })
251
+ .default({
252
+ driver: "memory",
253
+ retention: { completed: 86_400_000, failed: 604_800_000 },
254
+ }),
255
+ artifacts: z
256
+ .strictObject({ path: z.string().min(1).optional() })
257
+ .default({}),
258
+ /** Named key-value stores for server state. `default` is used unless another is named. */
259
+ stores: z.record(storeName, keyValueStoreSchema).default({}),
260
+ conversations: z
261
+ .strictObject({
262
+ ledger: z
263
+ .strictObject({
264
+ store: storeName.default("default"),
265
+ ttl: durationSchema.default(2_592_000_000),
266
+ })
267
+ .default({ store: "default", ttl: 2_592_000_000 }),
268
+ scope: z
269
+ .strictObject({ includeUser: z.boolean().default(false) })
270
+ .default({ includeUser: false }),
271
+ match: z.enum(["exact", "user-turns"]).default("exact"),
272
+ /** Defaults to `reject` when signatures are required, otherwise `unsigned`. */
273
+ onUnrecognized: z.enum(["unsigned", "reject", "restart"]).optional(),
274
+ onManifestChange: z.enum(["continue", "restart"]).default("continue"),
275
+ media: z
276
+ .strictObject({
277
+ urls: z.enum(["reject", "allow"]).default("reject"),
278
+ allowOrigins: z.array(z.url()).default([]),
279
+ })
280
+ .default({ urls: "reject", allowOrigins: [] }),
281
+ })
282
+ .default({
283
+ ledger: { store: "default", ttl: 2_592_000_000 },
284
+ scope: { includeUser: false },
285
+ match: "exact",
286
+ onManifestChange: "continue",
287
+ media: { urls: "reject", allowOrigins: [] },
288
+ }),
289
+ auth: z
290
+ .strictObject({ apiKeys: z.array(apiKeySchema).default([]) })
291
+ .default({ apiKeys: [] }),
292
+ models: z.array(servedModelConfigSchema).min(1),
293
+ })
294
+ .superRefine((config, context) => {
295
+ const names = new Set();
296
+ config.models.forEach((model, index) => {
297
+ if (names.has(model.name)) {
298
+ context.addIssue({
299
+ code: "custom",
300
+ message: `Duplicate served model name: ${model.name}`,
301
+ path: ["models", index, "name"],
302
+ });
303
+ }
304
+ names.add(model.name);
305
+ });
306
+ const ids = new Set();
307
+ config.auth.apiKeys.forEach((key, index) => {
308
+ if (ids.has(key.id)) {
309
+ context.addIssue({
310
+ code: "custom",
311
+ message: `Duplicate API key id: ${key.id}`,
312
+ path: ["auth", "apiKeys", index, "id"],
313
+ });
314
+ }
315
+ ids.add(key.id);
316
+ if (key.models !== "*") {
317
+ key.models.forEach((model, modelIndex) => {
318
+ if (!names.has(model)) {
319
+ context.addIssue({
320
+ code: "custom",
321
+ message: `API key ${key.id} names unknown model ${model}.`,
322
+ path: ["auth", "apiKeys", index, "models", modelIndex],
323
+ });
324
+ }
325
+ });
326
+ }
327
+ });
328
+ if (config.store.driver === "sqlite" && !config.store.path) {
329
+ context.addIssue({
330
+ code: "custom",
331
+ message: "store.path is required for the sqlite store driver.",
332
+ path: ["store", "path"],
333
+ });
334
+ }
335
+ if (config.conversations.ledger.store !== "default" &&
336
+ !config.stores[config.conversations.ledger.store]) {
337
+ context.addIssue({
338
+ code: "custom",
339
+ message: `conversations.ledger.store names unknown store "${config.conversations.ledger.store}".`,
340
+ path: ["conversations", "ledger", "store"],
341
+ });
342
+ }
343
+ if (config.conversations.media.urls === "allow" &&
344
+ config.conversations.media.allowOrigins.length === 0) {
345
+ context.addIssue({
346
+ code: "custom",
347
+ message: "conversations.media.urls: allow requires at least one allowOrigins entry.",
348
+ path: ["conversations", "media", "allowOrigins"],
349
+ });
350
+ }
351
+ });
352
+ export const parseServerConfig = (input) => serverConfigSchema.parse(input);
353
+ const formatIssues = (error) => error.issues
354
+ .map((issue) => issue.path.length > 0
355
+ ? `${issue.path.join(".")}: ${issue.message}`
356
+ : issue.message)
357
+ .join("; ");
358
+ /**
359
+ * Resolve paths in a configuration against the directory it was loaded
360
+ * from, so a server file works wherever the server is started.
361
+ */
362
+ export const resolveServerConfigPaths = (config, baseDirectory) => {
363
+ const resolve = (value) => path.resolve(baseDirectory, value);
364
+ return {
365
+ ...config,
366
+ ...(config.runtimeConfig
367
+ ? { runtimeConfig: resolve(config.runtimeConfig) }
368
+ : {}),
369
+ ...(config.runtimeModule
370
+ ? { runtimeModule: resolve(config.runtimeModule) }
371
+ : {}),
372
+ store: {
373
+ ...config.store,
374
+ ...(config.store.path ? { path: resolve(config.store.path) } : {}),
375
+ },
376
+ artifacts: {
377
+ ...(config.artifacts.path
378
+ ? { path: resolve(config.artifacts.path) }
379
+ : {}),
380
+ },
381
+ stores: Object.fromEntries(Object.entries(config.stores).map(([name, store]) => [
382
+ name,
383
+ store.driver === "sqlite"
384
+ ? { ...store, path: resolve(store.path) }
385
+ : store,
386
+ ])),
387
+ models: config.models.map((model) => ({
388
+ ...model,
389
+ manifest: resolve(model.manifest),
390
+ })),
391
+ };
392
+ };
393
+ /** Where a configuration file keeps durable state unless it says otherwise. */
394
+ export const SERVER_STATE_DIRECTORY = ".agent-runtime/serve";
395
+ const isObject = (value) => value != null && typeof value === "object" && !Array.isArray(value);
396
+ /**
397
+ * A configuration file describes a deployment, so what it leaves out is
398
+ * durable: runs and server state (the conversation ledger and media index)
399
+ * in SQLite, and stored media in a directory, all under
400
+ * `.agent-runtime/serve` beside the file. Conversations and the media they
401
+ * reference therefore survive restarts together.
402
+ */
403
+ const withDurableDefaults = (input) => {
404
+ if (!isObject(input))
405
+ return input;
406
+ const store = isObject(input.store) ? input.store : {};
407
+ const stores = isObject(input.stores) ? input.stores : {};
408
+ const artifacts = isObject(input.artifacts) ? input.artifacts : {};
409
+ return {
410
+ ...input,
411
+ store: store.driver === undefined
412
+ ? {
413
+ ...store,
414
+ driver: "sqlite",
415
+ path: store.path ?? `${SERVER_STATE_DIRECTORY}/runs.sqlite`,
416
+ }
417
+ : store,
418
+ stores: {
419
+ ...stores,
420
+ default: stores.default ?? {
421
+ driver: "sqlite",
422
+ path: `${SERVER_STATE_DIRECTORY}/state.sqlite`,
423
+ },
424
+ },
425
+ artifacts: {
426
+ ...artifacts,
427
+ path: artifacts.path ?? `${SERVER_STATE_DIRECTORY}/artifacts`,
428
+ },
429
+ };
430
+ };
431
+ /** Load and validate a server configuration file (YAML or JSON). */
432
+ export const loadServerConfig = async (file) => {
433
+ const absolute = path.resolve(file);
434
+ let source;
435
+ try {
436
+ source = await readFile(absolute, "utf8");
437
+ }
438
+ catch (error) {
439
+ if (error.code === "ENOENT")
440
+ throw new Error(`Server configuration not found: ${absolute}`);
441
+ throw error;
442
+ }
443
+ let parsed;
444
+ try {
445
+ parsed = absolute.endsWith(".json")
446
+ ? JSON.parse(source)
447
+ : parseYaml(source);
448
+ }
449
+ catch (error) {
450
+ throw new Error(`Could not parse server configuration ${absolute}: ${error instanceof Error ? error.message : String(error)}`);
451
+ }
452
+ const result = serverConfigSchema.safeParse(withDurableDefaults(parsed));
453
+ if (!result.success) {
454
+ throw new Error(`Invalid server configuration ${absolute}: ${formatIssues(result.error)}`);
455
+ }
456
+ const baseDirectory = path.dirname(absolute);
457
+ return {
458
+ config: resolveServerConfigPaths(result.data, baseDirectory),
459
+ file: absolute,
460
+ baseDirectory,
461
+ };
462
+ };
463
+ /** The first discovered server configuration file in a directory, if any. */
464
+ export const discoverServerConfigFile = async (directory) => {
465
+ for (const name of SERVER_CONFIG_FILE_NAMES) {
466
+ const candidate = path.resolve(directory, name);
467
+ try {
468
+ await access(candidate);
469
+ return candidate;
470
+ }
471
+ catch (error) {
472
+ if (error.code !== "ENOENT")
473
+ throw error;
474
+ }
475
+ }
476
+ return undefined;
477
+ };
478
+ /** The served model name a manifest gets when none is given: its id, else the file name. */
479
+ export const defaultServedModelName = (manifestFile, manifestId) => {
480
+ if (manifestId && servedModelNameSchema.safeParse(manifestId).success)
481
+ return manifestId;
482
+ const base = path
483
+ .basename(manifestFile)
484
+ .replace(/\.(agent\.)?(ya?ml|json)$/iu, "")
485
+ .replace(/[^A-Za-z0-9._:/-]+/gu, "-")
486
+ .replace(/^[^A-Za-z0-9]+/u, "");
487
+ return base || "agent";
488
+ };
489
+ /**
490
+ * Build a one-model configuration from command-line options. Single-manifest
491
+ * mode keeps runs, the ledger, and stored media for the life of the process
492
+ * unless told otherwise; a SQLite ledger keeps stored media beside it, so
493
+ * conversations and their media survive restarts together.
494
+ */
495
+ export const singleManifestServerConfig = (options) => {
496
+ const manifest = path.resolve(options.manifest);
497
+ const baseDirectory = path.dirname(manifest);
498
+ const ledgerStore = options.ledger?.driver === "sqlite"
499
+ ? { driver: "sqlite", path: path.resolve(options.ledger.path) }
500
+ : { driver: "memory", maxEntries: 100_000 };
501
+ const config = parseServerConfig({
502
+ version: SERVER_CONFIG_SCHEMA_VERSION,
503
+ ...(options.runtimeConfig
504
+ ? { runtimeConfig: path.resolve(options.runtimeConfig) }
505
+ : {}),
506
+ ...(options.runtimeModule
507
+ ? { runtimeModule: path.resolve(options.runtimeModule) }
508
+ : {}),
509
+ store: {
510
+ driver: options.store?.driver ?? "memory",
511
+ ...(options.store?.path
512
+ ? { path: path.resolve(options.store.path) }
513
+ : {}),
514
+ },
515
+ stores: { default: ledgerStore },
516
+ ...(ledgerStore.driver === "sqlite"
517
+ ? {
518
+ artifacts: {
519
+ path: path.join(path.dirname(ledgerStore.path), "artifacts"),
520
+ },
521
+ }
522
+ : {}),
523
+ conversations: {
524
+ ...(options.onUnrecognized
525
+ ? { onUnrecognized: options.onUnrecognized }
526
+ : {}),
527
+ },
528
+ models: [
529
+ {
530
+ name: options.servedModelName,
531
+ manifest,
532
+ ...(options.input ? { input: options.input } : {}),
533
+ ...(options.output ? { output: { from: options.output } } : {}),
534
+ stream: {
535
+ ...(options.streamMode ? { mode: options.streamMode } : {}),
536
+ ...(options.progress ? { progress: options.progress } : {}),
537
+ },
538
+ ...(options.clientTools ? { clientTools: options.clientTools } : {}),
539
+ },
540
+ ],
541
+ });
542
+ return { config, baseDirectory };
543
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Chat request → run input. Conversation manifests receive the chat as
3
+ * conversation messages; variable manifests receive operator-mapped
4
+ * variables. Nothing else from a request reaches a run.
5
+ */
6
+ import type { AgentVariableOverride, ConversationMessage } from "@clearideas/agent-runtime-contracts";
7
+ import type { ArtifactStore } from "@clearideas/agent-runtime-core";
8
+ import type { InputMapping } from "./config.js";
9
+ import type { MediaIngestor } from "./media.js";
10
+ import type { ChatCompletionRequest, ChatMessage } from "./openai.js";
11
+ export interface ConvertedChat {
12
+ /** Text of the client's system and developer messages. */
13
+ instructions: string;
14
+ /** User and assistant messages, in order, with media as artifact references. */
15
+ messages: ConversationMessage[];
16
+ }
17
+ export interface ConvertOptions {
18
+ /** Conversation mode accepts media; variable mode accepts text only. */
19
+ allowMedia: boolean;
20
+ /** `ignore` drops client tool messages and tool calls; `reject` refuses them. */
21
+ clientTools: "ignore" | "reject";
22
+ media: MediaIngestor;
23
+ scope: string;
24
+ artifacts: ArtifactStore;
25
+ }
26
+ /**
27
+ * Convert chat messages. Client system and developer messages become
28
+ * `instructions`; tool messages and tool calls are dropped or refused, per
29
+ * the `clientTools` policy; audio and file ids are refused; an assistant
30
+ * message with no text is omitted. The request must end with a user message.
31
+ */
32
+ export declare const convertChatMessages: (messages: readonly ChatMessage[], options: ConvertOptions) => Promise<ConvertedChat>;
33
+ /** Messages up to and including the last assistant message, and the new turn after it. */
34
+ export declare const splitNewTurn: (messages: readonly ConversationMessage[]) => {
35
+ prefix: ConversationMessage[];
36
+ newTurn: ConversationMessage[];
37
+ };
38
+ /**
39
+ * Variable overrides for operator-mapped inputs. Values are validated by the
40
+ * runtime against the manifest's declarations before a run is created.
41
+ */
42
+ export declare const mapInputVariables: (input: {
43
+ mappings: readonly InputMapping[];
44
+ chat: ConvertedChat;
45
+ request: ChatCompletionRequest;
46
+ }) => AgentVariableOverride[];