@fevex/core 0.1.0-alpha.0 → 0.1.0-alpha.10

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.
Files changed (52) hide show
  1. package/README.md +1110 -52
  2. package/dist/agents/index.d.mts +2 -23
  3. package/dist/agents/index.mjs +1 -1
  4. package/dist/artifacts/index.d.mts +2 -0
  5. package/dist/artifacts/index.mjs +2 -0
  6. package/dist/artifacts-gUzemET7.mjs +440 -0
  7. package/dist/channels/index.d.mts +2 -0
  8. package/dist/channels/index.mjs +192 -0
  9. package/dist/evals/index.d.mts +153 -0
  10. package/dist/evals/index.mjs +422 -0
  11. package/dist/fevex-_KOsOsB8.d.mts +129 -0
  12. package/dist/http/index.d.mts +150 -0
  13. package/dist/http/index.mjs +692 -0
  14. package/dist/index-26ilbzAs.d.mts +50 -0
  15. package/dist/index-B8EcvWeN.d.mts +103 -0
  16. package/dist/index-BEqYWean.d.mts +118 -0
  17. package/dist/index-Btth7rdL.d.mts +58 -0
  18. package/dist/index-CFzrvDQ0.d.mts +21 -0
  19. package/dist/index-CIHWc5V1.d.mts +116 -0
  20. package/dist/index-D7r0puBi.d.mts +64 -0
  21. package/dist/index-DHcfIfh-.d.mts +224 -0
  22. package/dist/index-DUhNa7IR.d.mts +73 -0
  23. package/dist/index-lCCFokc6.d.mts +617 -0
  24. package/dist/index.d.mts +39 -15
  25. package/dist/index.mjs +4962 -208
  26. package/dist/knowledge/index.d.mts +2 -0
  27. package/dist/knowledge/index.mjs +289 -0
  28. package/dist/model-stream-JQdHDDcj.mjs +131 -0
  29. package/dist/models/index.d.mts +2 -27
  30. package/dist/observability/index.d.mts +2 -0
  31. package/dist/observability/index.mjs +1 -0
  32. package/dist/policies/index.d.mts +2 -0
  33. package/dist/policies/index.mjs +6 -0
  34. package/dist/run-error-Cr17wPGH.mjs +23 -0
  35. package/dist/run-support-CmZ6Xo6H.mjs +162 -0
  36. package/dist/runtime/index.d.mts +2 -17
  37. package/dist/runtime/index.mjs +354 -1
  38. package/dist/sandbox/index.d.mts +2 -0
  39. package/dist/sandbox/index.mjs +147 -0
  40. package/dist/teams/index.d.mts +2 -0
  41. package/dist/teams/index.mjs +2 -0
  42. package/dist/teams-Ctz676G4.mjs +82 -0
  43. package/dist/testing/index.d.mts +40 -8
  44. package/dist/testing/index.mjs +668 -23
  45. package/dist/tools/index.d.mts +3 -31
  46. package/dist/tools/index.mjs +442 -2
  47. package/dist/types-CckDlhYo.d.mts +575 -0
  48. package/dist/workflows/index.d.mts +2 -0
  49. package/dist/workflows/index.mjs +6 -0
  50. package/package.json +43 -3
  51. package/dist/exact-definition-NHBBFlFR.d.mts +0 -4
  52. package/dist/index-D_RBJmVt.d.mts +0 -44
@@ -0,0 +1,2 @@
1
+ import { _ as defineContextProvider, a as AgentsMdOptions, c as ContextProvider, d as MemoryRecord, f as MemoryStore, g as createMemoryContextProvider, h as SkillDefinition, i as InMemoryMemoryStore, l as KnowledgeContext, m as ProgressiveSkillProvider, n as loadSkillFile, o as createAgentsMdContextProvider, p as MemoryWrite, r as loadSkillFiles, s as ContextBlock, t as LoadSkillFileOptions, u as MemoryQuery, v as defineSkill, y as isProgressiveSkillProvider } from "../index-CIHWc5V1.mjs";
2
+ export { AgentsMdOptions, ContextBlock, ContextProvider, InMemoryMemoryStore, KnowledgeContext, LoadSkillFileOptions, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, ProgressiveSkillProvider, SkillDefinition, createAgentsMdContextProvider, createMemoryContextProvider, defineContextProvider, defineSkill, isProgressiveSkillProvider, loadSkillFile, loadSkillFiles };
@@ -0,0 +1,289 @@
1
+ import { readFile, readdir, realpath, stat } from "node:fs/promises";
2
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
3
+ //#region src/knowledge/knowledge.ts
4
+ function isProgressiveSkillProvider(provider) {
5
+ const candidate = provider;
6
+ return typeof candidate.load === "function" && typeof candidate.description === "string";
7
+ }
8
+ function defineContextProvider(provider) {
9
+ return provider;
10
+ }
11
+ function defineSkill(skill) {
12
+ return defineContextProvider({
13
+ name: skill.name,
14
+ async read() {
15
+ return [{
16
+ id: `${skill.name}:instructions`,
17
+ content: skill.instructions
18
+ }, ...(skill.resources ?? []).map((resource, index) => {
19
+ const normalized = isSkillResource(resource) ? resource : { content: resource };
20
+ return {
21
+ id: normalized.id ?? `${skill.name}:resource:${index + 1}`,
22
+ content: stringifyKnowledge(normalized.content),
23
+ ...normalized.metadata === void 0 ? {} : { metadata: normalized.metadata }
24
+ };
25
+ })];
26
+ }
27
+ });
28
+ }
29
+ function isSkillResource(value) {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value) && "content" in value && (value.id === void 0 || typeof value.id === "string");
31
+ }
32
+ function createMemoryContextProvider(options) {
33
+ return defineContextProvider({
34
+ name: options.name ?? "memory",
35
+ async read(context) {
36
+ return (await options.store.search({
37
+ query: context.input,
38
+ limit: options.limit,
39
+ agentName: context.agentName,
40
+ sessionId: context.sessionId,
41
+ namespace: context.context?.namespace,
42
+ actor: context.context?.actor
43
+ }, context)).map((record) => ({
44
+ id: record.id,
45
+ content: record.content,
46
+ metadata: {
47
+ ...record.metadata ?? {},
48
+ createdAt: record.createdAt,
49
+ ...record.agentName === void 0 ? {} : { agentName: record.agentName },
50
+ ...record.sessionId === void 0 ? {} : { sessionId: record.sessionId }
51
+ }
52
+ }));
53
+ }
54
+ });
55
+ }
56
+ function stringifyKnowledge(value) {
57
+ return typeof value === "string" ? value : JSON.stringify(value);
58
+ }
59
+ //#endregion
60
+ //#region src/knowledge/agents-md.ts
61
+ const DEFAULT_MAX_BYTES$1 = 256 * 1024;
62
+ /**
63
+ * Reads one explicit `AGENTS.md` file as context.
64
+ *
65
+ * Fevex never walks the filesystem looking for `AGENTS.md`; register one
66
+ * provider per file and reference its name from `agent.context`.
67
+ */
68
+ function createAgentsMdContextProvider(options) {
69
+ const path = typeof options === "string" ? options : options.path;
70
+ const name = ((typeof options === "string" ? void 0 : options.name) ?? "agents-md").trim();
71
+ const maxBytes = (typeof options === "string" ? void 0 : options.maxBytes) ?? DEFAULT_MAX_BYTES$1;
72
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new TypeError("AGENTS.md maxBytes must be a positive safe integer");
73
+ if (!name.trim()) throw new TypeError("AGENTS.md provider name cannot be empty");
74
+ return defineContextProvider({
75
+ name,
76
+ async read() {
77
+ if ((await stat(path)).size > maxBytes) throw new Error(`AGENTS.md file "${path}" exceeds ${maxBytes} bytes`);
78
+ const content = await readFile(path, "utf8");
79
+ if (Buffer.byteLength(content) > maxBytes) throw new Error(`AGENTS.md file "${path}" exceeds ${maxBytes} bytes`);
80
+ return content.trim() ? [{
81
+ id: "agents-md",
82
+ content
83
+ }] : [];
84
+ }
85
+ });
86
+ }
87
+ //#endregion
88
+ //#region src/knowledge/in-memory-memory-store.ts
89
+ /** Volatile keyword-search memory store for tests and local development. */
90
+ var InMemoryMemoryStore = class {
91
+ #records = /* @__PURE__ */ new Map();
92
+ async search(query, context) {
93
+ context.signal?.throwIfAborted();
94
+ const terms = query.query.toLowerCase().split(/\s+/).filter(Boolean);
95
+ const scored = [...this.#records.values()].filter((record) => matchesScope(record, query)).map((record) => ({
96
+ record,
97
+ score: score(record.content, terms)
98
+ })).filter(({ score }) => !terms.length || score > 0).sort((left, right) => right.score - left.score || right.record.createdAt.localeCompare(left.record.createdAt));
99
+ return scored.slice(0, query.limit ?? scored.length).map(({ record }) => structuredClone(record));
100
+ }
101
+ async write(record, context) {
102
+ context.signal?.throwIfAborted();
103
+ const saved = {
104
+ id: crypto.randomUUID(),
105
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
106
+ ...structuredClone(record)
107
+ };
108
+ this.#records.set(saved.id, saved);
109
+ return structuredClone(saved);
110
+ }
111
+ };
112
+ function matchesScope(record, query) {
113
+ return matches(record.agentName, query.agentName) && matches(record.sessionId, query.sessionId) && matches(record.namespace, query.namespace) && matches(record.actor?.id, query.actor?.id);
114
+ }
115
+ function matches(left, right) {
116
+ return right === void 0 || left === void 0 || left === right;
117
+ }
118
+ function score(content, terms) {
119
+ const text = content.toLowerCase();
120
+ return terms.reduce((total, term) => total + (text.includes(term) ? 1 : 0), 0);
121
+ }
122
+ //#endregion
123
+ //#region src/knowledge/skill-file.ts
124
+ const DEFAULT_MAX_BYTES = 256 * 1024;
125
+ const DEFAULT_MAX_RESOURCE_BYTES = 256 * 1024;
126
+ const MAX_RESOURCES = 200;
127
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
128
+ const RESOURCE_DIRECTORIES = [
129
+ "references",
130
+ "scripts",
131
+ "assets"
132
+ ];
133
+ /**
134
+ * Loads one explicit `SKILL.md` file.
135
+ *
136
+ * Only `name` and `description` are advertised up front. The body and any
137
+ * files under `references/`, `scripts/` or `assets/` load on demand.
138
+ */
139
+ async function loadSkillFile(path, options = {}) {
140
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
141
+ const maxResourceBytes = options.maxResourceBytes ?? DEFAULT_MAX_RESOURCE_BYTES;
142
+ assertPositiveInteger(maxBytes, "maxBytes");
143
+ assertPositiveInteger(maxResourceBytes, "maxResourceBytes");
144
+ const absolute = await realpath(resolve(path));
145
+ if ((await stat(absolute)).size > maxBytes) throw new Error(`Skill file "${path}" exceeds ${maxBytes} bytes`);
146
+ const source = (await readFile(absolute, "utf8")).replace(/^\uFEFF/, "");
147
+ if (Buffer.byteLength(source) > maxBytes) throw new Error(`Skill file "${path}" exceeds ${maxBytes} bytes`);
148
+ const skill = parseSkillFile(source, path);
149
+ const root = dirname(absolute);
150
+ return defineContextProvider({
151
+ name: skill.name,
152
+ description: skill.description,
153
+ async read() {
154
+ return [{
155
+ id: `${skill.name}:metadata`,
156
+ content: skill.description
157
+ }];
158
+ },
159
+ async load(_context, resource) {
160
+ if (resource !== void 0) return [{
161
+ id: `${skill.name}:resource:${resource}`,
162
+ content: await readResource(root, resource, maxResourceBytes)
163
+ }];
164
+ const blocks = [{
165
+ id: `${skill.name}:instructions`,
166
+ content: skill.instructions
167
+ }];
168
+ const resources = await listResources(root);
169
+ if (resources.length) blocks.push({
170
+ id: `${skill.name}:resources`,
171
+ content: [
172
+ "Resources:",
173
+ ...resources.map((item) => `- ${item.path} (${formatBytes(item.size)})`),
174
+ "Load one by passing its path as the resource argument.",
175
+ ...resources.some((item) => item.path.startsWith("scripts/")) ? ["Scripts are for reference only and are not executed by this runtime."] : []
176
+ ].join("\n")
177
+ });
178
+ return blocks;
179
+ }
180
+ });
181
+ }
182
+ /** Loads several explicit `SKILL.md` files; it never scans directories. */
183
+ function loadSkillFiles(paths, options = {}) {
184
+ return Promise.all(paths.map((path) => loadSkillFile(path, options)));
185
+ }
186
+ function parseSkillFile(source, path) {
187
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(source);
188
+ if (!match) throw new Error(`Skill file "${path}" must start with --- frontmatter`);
189
+ const fields = parseFrontmatter(match[1]);
190
+ const name = fields.name?.trim();
191
+ const description = fields.description?.trim();
192
+ const instructions = match[2].trim();
193
+ if (!name) throw new Error(`Skill file "${path}" must define a name`);
194
+ if (name.length > 64 || !SKILL_NAME.test(name) || name.startsWith("fevex__")) throw new Error(`Skill file "${path}" has an invalid name; use lowercase letters, numbers and hyphens, up to 64 characters`);
195
+ if (!description) throw new Error(`Skill file "${path}" must define a description`);
196
+ if (!instructions) throw new Error(`Skill file "${path}" must contain instructions`);
197
+ return {
198
+ name,
199
+ description,
200
+ instructions
201
+ };
202
+ }
203
+ function parseFrontmatter(source) {
204
+ const fields = {};
205
+ const lines = source.split(/\r?\n/);
206
+ for (let index = 0; index < lines.length; index += 1) {
207
+ const line = lines[index];
208
+ if (!line.trim() || line.trimStart().startsWith("#")) continue;
209
+ if (/^\s/.test(line)) continue;
210
+ const colon = line.indexOf(":");
211
+ if (colon <= 0) continue;
212
+ const key = line.slice(0, colon).trim();
213
+ let value = line.slice(colon + 1).trim();
214
+ if (value === "|" || value === ">" || value === "|-" || value === ">-") {
215
+ const block = [];
216
+ while (index + 1 < lines.length) {
217
+ const next = lines[index + 1];
218
+ if (next.trim() && !/^\s/.test(next)) break;
219
+ index += 1;
220
+ block.push(next.replace(/^\s+/, ""));
221
+ }
222
+ while (block.length && !block[block.length - 1]) block.pop();
223
+ value = value.startsWith(">") ? block.filter(Boolean).join(" ") : block.join("\n");
224
+ } else if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
225
+ fields[key] = value;
226
+ }
227
+ return fields;
228
+ }
229
+ async function listResources(root) {
230
+ const resources = [];
231
+ for (const directory of RESOURCE_DIRECTORIES) await walkResources(resolve(root, directory), root, resources);
232
+ return resources.sort((left, right) => left.path.localeCompare(right.path)).slice(0, MAX_RESOURCES);
233
+ }
234
+ async function walkResources(directory, root, resources) {
235
+ if (resources.length >= MAX_RESOURCES) return;
236
+ let entries;
237
+ try {
238
+ entries = await readdir(directory, { withFileTypes: true });
239
+ } catch (error) {
240
+ if (isMissing(error)) return;
241
+ throw error;
242
+ }
243
+ for (const entry of entries) {
244
+ if (resources.length >= MAX_RESOURCES) return;
245
+ if (entry.isSymbolicLink()) continue;
246
+ const target = resolve(directory, entry.name);
247
+ if (entry.isDirectory()) {
248
+ await walkResources(target, root, resources);
249
+ continue;
250
+ }
251
+ if (!entry.isFile()) continue;
252
+ const info = await stat(target);
253
+ resources.push({
254
+ path: relative(root, target).split("\\").join("/"),
255
+ size: info.size
256
+ });
257
+ }
258
+ }
259
+ async function readResource(root, resource, maxBytes) {
260
+ if (resource.includes("\0")) throw new Error("Skill resource path is invalid");
261
+ const requested = resolve(root, resource);
262
+ const requestedPath = relative(root, requested);
263
+ if (!requestedPath || requestedPath.startsWith("..") || isAbsolute(requestedPath)) throw new Error(`Skill resource "${resource}" is outside the skill directory`);
264
+ let target;
265
+ try {
266
+ target = await realpath(requested);
267
+ } catch {
268
+ throw new Error(`Skill resource "${resource}" was not found`);
269
+ }
270
+ const path = relative(root, target);
271
+ if (!path || path.startsWith("..") || isAbsolute(path)) throw new Error(`Skill resource "${resource}" is outside the skill directory`);
272
+ const info = await stat(target);
273
+ if (!info.isFile()) throw new Error(`Skill resource "${resource}" is not a file`);
274
+ if (info.size > maxBytes) throw new Error(`Skill resource "${resource}" exceeds ${maxBytes} bytes`);
275
+ const buffer = await readFile(target);
276
+ if (buffer.includes(0)) throw new Error(`Skill resource "${resource}" is not UTF-8 text`);
277
+ return buffer.toString("utf8");
278
+ }
279
+ function formatBytes(bytes) {
280
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
281
+ }
282
+ function assertPositiveInteger(value, name) {
283
+ if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`Skill ${name} must be a positive safe integer`);
284
+ }
285
+ function isMissing(error) {
286
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
287
+ }
288
+ //#endregion
289
+ export { InMemoryMemoryStore, createAgentsMdContextProvider, createMemoryContextProvider, defineContextProvider, defineSkill, isProgressiveSkillProvider, loadSkillFile, loadSkillFiles };
@@ -0,0 +1,131 @@
1
+ import { n as abortable } from "./run-support-CmZ6Xo6H.mjs";
2
+ //#region src/internal/model-stream.ts
3
+ const MAX_DELTA_CHARS = 512;
4
+ const MAX_DELTA_DELAY_MS = 32;
5
+ function isRecord(value) {
6
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7
+ }
8
+ function canonicalJson(value) {
9
+ if (Array.isArray(value)) return value.map(canonicalJson);
10
+ if (!isRecord(value)) return value;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ if (prototype !== Object.prototype && prototype !== null) return value;
13
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalJson(item)]));
14
+ }
15
+ function assertConsistentOutput(result, outputText) {
16
+ if (result.output === void 0) {
17
+ if (outputText) throw new TypeError("Model stream emitted output without a final output");
18
+ return;
19
+ }
20
+ if (typeof result.output === "string") {
21
+ if (result.output !== outputText) throw new TypeError("Model stream deltas do not match the final output");
22
+ return;
23
+ }
24
+ if (!outputText) throw new TypeError("Model stream returned JSON output without output deltas");
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(outputText);
28
+ } catch (error) {
29
+ throw new TypeError("Model stream output deltas are not valid JSON", { cause: error });
30
+ }
31
+ if (JSON.stringify(canonicalJson(parsed)) !== JSON.stringify(canonicalJson(result.output))) throw new TypeError("Model stream deltas do not match the final JSON output");
32
+ }
33
+ function assertStreamEvent(value) {
34
+ if (!isRecord(value)) throw new TypeError("ModelGateway stream event must be an object");
35
+ if (value.type === "output.delta") {
36
+ if (typeof value.delta !== "string") throw new TypeError("ModelGateway output.delta must contain a string delta");
37
+ return;
38
+ }
39
+ if (value.type === "completed") {
40
+ if (!isRecord(value.result)) throw new TypeError("ModelGateway completed event must contain a result");
41
+ return;
42
+ }
43
+ throw new TypeError("ModelGateway returned an unknown stream event");
44
+ }
45
+ function takeCharacters(value, count) {
46
+ const characters = Array.from(value);
47
+ return [characters.slice(0, count).join(""), characters.slice(count).join("")];
48
+ }
49
+ async function* readModelStream(model, input) {
50
+ input.signal?.throwIfAborted();
51
+ const stream = model.stream(input);
52
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") throw new TypeError("ModelGateway.stream must return an AsyncIterable");
53
+ const iterator = stream[Symbol.asyncIterator]();
54
+ let pending;
55
+ let completed;
56
+ let outputText = "";
57
+ let buffer = "";
58
+ let firstDelta = true;
59
+ let bufferedAt = 0;
60
+ const next = () => {
61
+ const promise = abortable(() => iterator.next(), input.signal);
62
+ promise.catch(() => {});
63
+ return promise;
64
+ };
65
+ try {
66
+ while (true) {
67
+ if (buffer && Array.from(buffer).length >= MAX_DELTA_CHARS) {
68
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
69
+ buffer = rest;
70
+ bufferedAt = performance.now();
71
+ yield chunk;
72
+ continue;
73
+ }
74
+ pending ??= next();
75
+ let item;
76
+ if (buffer) {
77
+ const remaining = Math.max(0, MAX_DELTA_DELAY_MS - (performance.now() - bufferedAt));
78
+ const raced = await Promise.race([pending.then((value) => ({
79
+ type: "item",
80
+ value
81
+ })), new Promise((resolve) => {
82
+ setTimeout(() => resolve({ type: "flush" }), remaining);
83
+ })]);
84
+ if (raced.type === "flush") {
85
+ const chunk = buffer;
86
+ buffer = "";
87
+ bufferedAt = 0;
88
+ yield chunk;
89
+ continue;
90
+ }
91
+ item = raced.value;
92
+ } else item = await pending;
93
+ pending = void 0;
94
+ if (item.done) {
95
+ if (!completed) throw new TypeError("ModelGateway stream ended without completed");
96
+ assertConsistentOutput(completed, outputText);
97
+ return completed;
98
+ }
99
+ assertStreamEvent(item.value);
100
+ if (completed) throw new TypeError("ModelGateway stream emitted an event after completed");
101
+ if (item.value.type === "completed") {
102
+ completed = item.value.result;
103
+ if (buffer) {
104
+ const chunk = buffer;
105
+ buffer = "";
106
+ bufferedAt = 0;
107
+ yield chunk;
108
+ }
109
+ continue;
110
+ }
111
+ if (!item.value.delta) continue;
112
+ outputText += item.value.delta;
113
+ buffer += item.value.delta;
114
+ if (firstDelta) {
115
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
116
+ firstDelta = false;
117
+ buffer = rest;
118
+ bufferedAt = performance.now();
119
+ yield chunk;
120
+ } else if (!bufferedAt) bufferedAt = performance.now();
121
+ }
122
+ } catch (error) {
123
+ if (buffer) yield buffer;
124
+ throw error;
125
+ } finally {
126
+ if (pending) pending.catch(() => {});
127
+ if (iterator.return) Promise.resolve(iterator.return()).catch(() => {});
128
+ }
129
+ }
130
+ //#endregion
131
+ export { readModelStream as t };
@@ -1,27 +1,2 @@
1
- import { d as ToolCall, f as ToolSpec, o as JsonObject, r as AgentMessage } from "../index-D_RBJmVt.mjs";
2
- //#region src/models/index.d.ts
3
- type ReasoningEffort = 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high';
4
- interface ModelUsage {
5
- inputTokens?: number;
6
- outputTokens?: number;
7
- totalTokens?: number;
8
- }
9
- interface ModelGenerateInput {
10
- messages: AgentMessage[];
11
- tools?: ToolSpec[];
12
- reasoning?: ReasoningEffort;
13
- modelOptions?: Record<string, unknown>;
14
- outputSchema?: JsonObject;
15
- signal?: AbortSignal;
16
- }
17
- interface ModelGenerateResult<TOutput = unknown> {
18
- output?: TOutput;
19
- toolCalls?: ToolCall[];
20
- usage?: ModelUsage;
21
- }
22
- interface ModelGateway {
23
- generate(input: ModelGenerateInput): Promise<ModelGenerateResult>;
24
- }
25
- type ModelRef = string | ModelGateway;
26
- //#endregion
27
- export { ModelGateway, ModelGenerateInput, ModelGenerateResult, ModelRef, ModelUsage, ReasoningEffort };
1
+ import { a as ModelResult, c as ReasoningEffort, i as ModelRef, l as ToolChoice, n as ModelInput, o as ModelStreamEvent, r as ModelMetadata, s as ModelUsage, t as ModelGateway, u as EmbeddingModel } from "../index-D7r0puBi.mjs";
2
+ export { EmbeddingModel, ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, ReasoningEffort, ToolChoice };
@@ -0,0 +1,2 @@
1
+ import { _ as TraceSpanKind, a as RunTrace, c as TraceContentKind, d as TraceExportQueueOptions, f as TraceExporter, g as TraceSpan, h as TraceRunKind, i as ObservabilityStats, l as TraceContentPolicy, m as TraceRedactorInput, n as CostCalculatorInput, o as TraceAnnotation, p as TraceRedactor, r as ObservabilityOptions, s as TraceContent, t as CostCalculator, u as TraceCost, v as TraceStatus } from "../index-BEqYWean.mjs";
2
+ export { CostCalculator, CostCalculatorInput, ObservabilityOptions, ObservabilityStats, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExportQueueOptions, TraceExporter, TraceRedactor, TraceRedactorInput, TraceRunKind, TraceSpan, TraceSpanKind, TraceStatus };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-CFzrvDQ0.mjs";
2
+ export { PolicyAuthorization, PolicyDecision, PolicyDefinition, definePolicy };
@@ -0,0 +1,6 @@
1
+ //#region src/policies/policy.ts
2
+ function definePolicy(policy) {
3
+ return policy;
4
+ }
5
+ //#endregion
6
+ export { definePolicy };
@@ -0,0 +1,23 @@
1
+ //#region src/run-error.ts
2
+ var FevexRunError = class extends Error {
3
+ code;
4
+ runId;
5
+ name = "FevexRunError";
6
+ constructor(code, message, runId, options) {
7
+ super(message, options);
8
+ this.code = code;
9
+ this.runId = runId;
10
+ }
11
+ };
12
+ var RunPausedError = class extends FevexRunError {
13
+ runId;
14
+ pause;
15
+ name = "RunPausedError";
16
+ constructor(runId, pause) {
17
+ super("RUN_PAUSED", `Run "${runId}" is paused`, runId);
18
+ this.runId = runId;
19
+ this.pause = pause;
20
+ }
21
+ };
22
+ //#endregion
23
+ export { RunPausedError as n, FevexRunError as t };
@@ -0,0 +1,162 @@
1
+ import { t as FevexRunError } from "./run-error-Cr17wPGH.mjs";
2
+ //#region src/internal/json.ts
3
+ const invalidJsonValue = Symbol("invalid-json-value");
4
+ function normalizeJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
5
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
6
+ if (typeof value === "number") return Number.isFinite(value) ? value : invalidJsonValue;
7
+ if (Array.isArray(value)) {
8
+ const normalized = [];
9
+ for (const item of value) {
10
+ const normalizedItem = normalizeJsonValue(item, seen);
11
+ if (normalizedItem === invalidJsonValue) return invalidJsonValue;
12
+ normalized.push(normalizedItem);
13
+ }
14
+ return normalized;
15
+ }
16
+ if (typeof value !== "object" || value === void 0) return invalidJsonValue;
17
+ const prototype = Object.getPrototypeOf(value);
18
+ if (prototype !== null && prototype !== Object.prototype) return invalidJsonValue;
19
+ if (seen.has(value)) return invalidJsonValue;
20
+ seen.add(value);
21
+ const normalized = {};
22
+ for (const [key, item] of Object.entries(value)) {
23
+ if (item === void 0) continue;
24
+ const normalizedItem = normalizeJsonValue(item, seen);
25
+ if (normalizedItem === invalidJsonValue) return invalidJsonValue;
26
+ Object.defineProperty(normalized, key, {
27
+ value: normalizedItem,
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true
31
+ });
32
+ }
33
+ seen.delete(value);
34
+ return normalized;
35
+ }
36
+ function toJsonValue(value, errorMessage) {
37
+ let normalized;
38
+ try {
39
+ normalized = normalizeJsonValue(value);
40
+ } catch {
41
+ throw new TypeError(errorMessage);
42
+ }
43
+ if (normalized === invalidJsonValue) throw new TypeError(errorMessage);
44
+ return normalized;
45
+ }
46
+ function serializeJsonValue(value) {
47
+ return typeof value === "string" ? value : JSON.stringify(value);
48
+ }
49
+ function serializeValue(value, errorMessage) {
50
+ return serializeJsonValue(toJsonValue(value, errorMessage));
51
+ }
52
+ //#endregion
53
+ //#region src/internal/run-support.ts
54
+ /** Largest delay accepted by Node and Bun timers. */
55
+ const MAX_DEADLINE_MS = 2147483647;
56
+ function deadlineAtFromMs(deadlineMs) {
57
+ if (deadlineMs === void 0) return void 0;
58
+ if (!Number.isSafeInteger(deadlineMs) || deadlineMs <= 0 || deadlineMs > 2147483647) throw new TypeError(`deadlineMs must be a positive safe integer up to ${MAX_DEADLINE_MS}`);
59
+ return new Date(Date.now() + deadlineMs).toISOString();
60
+ }
61
+ function runSignal(controller, request) {
62
+ const signals = [controller.signal];
63
+ if (request.signal) signals.push(request.signal);
64
+ if (request.deadlineMs !== void 0) {
65
+ deadlineAtFromMs(request.deadlineMs);
66
+ signals.push(AbortSignal.timeout(request.deadlineMs));
67
+ }
68
+ return AbortSignal.any(signals);
69
+ }
70
+ function resumeDeadlineSignal(deadlineAt, runId, code) {
71
+ if (deadlineAt === void 0) return void 0;
72
+ const expiresAt = Date.parse(deadlineAt);
73
+ if (!Number.isFinite(expiresAt)) throw new FevexRunError(code, `Run "${runId}" has an invalid deadline`, runId);
74
+ if (expiresAt <= Date.now()) throw new FevexRunError(code, `Run "${runId}" deadline has passed`, runId);
75
+ return AbortSignal.timeout(expiresAt - Date.now());
76
+ }
77
+ function remainingDeadlineMs(deadlineAt, runId) {
78
+ if (deadlineAt === void 0) return void 0;
79
+ const expiresAt = Date.parse(deadlineAt);
80
+ if (!Number.isFinite(expiresAt)) throw new FevexRunError("RUN_NOT_RESUMABLE", `Run "${runId}" has an invalid deadline`, runId);
81
+ const remaining = expiresAt - Date.now();
82
+ if (remaining <= 0) throw new FevexRunError("RUN_NOT_RESUMABLE", `Run "${runId}" deadline has passed`, runId);
83
+ return remaining;
84
+ }
85
+ function isTimeoutError(error) {
86
+ return typeof error === "object" && error !== null && error.name === "TimeoutError";
87
+ }
88
+ function minDeadline(first, second) {
89
+ if (first === void 0) return second;
90
+ if (second === void 0) return first;
91
+ return Math.min(first, second);
92
+ }
93
+ function toErrorMessage(error) {
94
+ if (error instanceof Error) return error.message;
95
+ if (typeof error === "string") return error;
96
+ try {
97
+ return JSON.stringify(error) ?? String(error);
98
+ } catch {
99
+ return String(error);
100
+ }
101
+ }
102
+ async function abortable(operation, signal) {
103
+ signal?.throwIfAborted();
104
+ if (!signal) return await operation();
105
+ const result = await new Promise((resolve, reject) => {
106
+ let settled = false;
107
+ const finish = (callback) => {
108
+ if (settled) return;
109
+ settled = true;
110
+ signal.removeEventListener("abort", onAbort);
111
+ callback();
112
+ };
113
+ const onAbort = () => finish(() => reject(signal.reason));
114
+ signal.addEventListener("abort", onAbort, { once: true });
115
+ if (signal.aborted) {
116
+ onAbort();
117
+ return;
118
+ }
119
+ Promise.resolve().then(() => {
120
+ signal.throwIfAborted();
121
+ return operation();
122
+ }).then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
123
+ });
124
+ signal.throwIfAborted();
125
+ return result;
126
+ }
127
+ function cancellationReason(signal) {
128
+ return signal.reason instanceof Error && signal.reason.name === "TimeoutError" ? "timeout" : "aborted";
129
+ }
130
+ function addUsage(first, second) {
131
+ if (!first) return second;
132
+ if (!second) return first;
133
+ const inputTokens = first.inputTokens === void 0 && second.inputTokens === void 0 ? void 0 : (first.inputTokens ?? 0) + (second.inputTokens ?? 0);
134
+ const outputTokens = first.outputTokens === void 0 && second.outputTokens === void 0 ? void 0 : (first.outputTokens ?? 0) + (second.outputTokens ?? 0);
135
+ const totalTokens = first.totalTokens === void 0 && second.totalTokens === void 0 ? void 0 : (first.totalTokens ?? 0) + (second.totalTokens ?? 0);
136
+ return {
137
+ ...inputTokens !== void 0 ? { inputTokens } : {},
138
+ ...outputTokens !== void 0 ? { outputTokens } : {},
139
+ ...totalTokens !== void 0 ? { totalTokens } : {}
140
+ };
141
+ }
142
+ function assertTokenBudget(agentName, limitName, usageName, limit, stepUsage, totalUsage) {
143
+ if (limit === void 0 || limit === false) return;
144
+ const stepTokens = stepUsage?.[usageName];
145
+ if (stepTokens === void 0 || !Number.isFinite(stepTokens) || stepTokens < 0) throw new Error(`Agent "${agentName}" cannot enforce ${limitName}: model usage.${usageName} is missing or invalid`);
146
+ if ((totalUsage?.[usageName] ?? 0) > limit) throw new Error(`Agent "${agentName}" exceeded ${limitName} limit of ${limit}`);
147
+ }
148
+ function assertContinuationBudget(agentName, limitName, usageName, limit, totalUsage) {
149
+ if (limit !== void 0 && limit !== false && (totalUsage?.[usageName] ?? 0) >= limit) throw new Error(`Agent "${agentName}" exhausted ${limitName} limit of ${limit} before completing`);
150
+ }
151
+ function remainingOutputTokens(limit, usage) {
152
+ if (limit === void 0 || limit === false) return void 0;
153
+ return limit - (usage?.outputTokens ?? 0);
154
+ }
155
+ function eventUsage(usage) {
156
+ if (usage === void 0) return void 0;
157
+ const value = toJsonValue(usage, "Model usage must be JSON-serializable");
158
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("Model usage must be a JSON object");
159
+ return value;
160
+ }
161
+ //#endregion
162
+ export { serializeValue as _, assertTokenBudget as a, eventUsage as c, remainingDeadlineMs as d, remainingOutputTokens as f, serializeJsonValue as g, toErrorMessage as h, assertContinuationBudget as i, isTimeoutError as l, runSignal as m, abortable as n, cancellationReason as o, resumeDeadlineSignal as p, addUsage as r, deadlineAtFromMs as s, MAX_DEADLINE_MS as t, minDeadline as u, toJsonValue as v };