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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,251 @@
1
+ //#region src/internal/json.ts
2
+ const invalidJsonValue = Symbol("invalid-json-value");
3
+ function normalizeJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
4
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
5
+ if (typeof value === "number") return Number.isFinite(value) ? value : invalidJsonValue;
6
+ if (Array.isArray(value)) {
7
+ const normalized = [];
8
+ for (const item of value) {
9
+ const normalizedItem = normalizeJsonValue(item, seen);
10
+ if (normalizedItem === invalidJsonValue) return invalidJsonValue;
11
+ normalized.push(normalizedItem);
12
+ }
13
+ return normalized;
14
+ }
15
+ if (typeof value !== "object" || value === void 0) return invalidJsonValue;
16
+ const prototype = Object.getPrototypeOf(value);
17
+ if (prototype !== null && prototype !== Object.prototype) return invalidJsonValue;
18
+ if (seen.has(value)) return invalidJsonValue;
19
+ seen.add(value);
20
+ const normalized = {};
21
+ for (const [key, item] of Object.entries(value)) {
22
+ if (item === void 0) continue;
23
+ const normalizedItem = normalizeJsonValue(item, seen);
24
+ if (normalizedItem === invalidJsonValue) return invalidJsonValue;
25
+ Object.defineProperty(normalized, key, {
26
+ value: normalizedItem,
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true
30
+ });
31
+ }
32
+ seen.delete(value);
33
+ return normalized;
34
+ }
35
+ function toJsonValue(value, errorMessage) {
36
+ let normalized;
37
+ try {
38
+ normalized = normalizeJsonValue(value);
39
+ } catch {
40
+ throw new TypeError(errorMessage);
41
+ }
42
+ if (normalized === invalidJsonValue) throw new TypeError(errorMessage);
43
+ return normalized;
44
+ }
45
+ function serializeJsonValue(value) {
46
+ return typeof value === "string" ? value : JSON.stringify(value);
47
+ }
48
+ function serializeValue(value, errorMessage) {
49
+ return serializeJsonValue(toJsonValue(value, errorMessage));
50
+ }
51
+ //#endregion
52
+ //#region src/internal/run-support.ts
53
+ function toErrorMessage(error) {
54
+ if (error instanceof Error) return error.message;
55
+ if (typeof error === "string") return error;
56
+ try {
57
+ return JSON.stringify(error) ?? String(error);
58
+ } catch {
59
+ return String(error);
60
+ }
61
+ }
62
+ async function abortable(operation, signal) {
63
+ signal?.throwIfAborted();
64
+ if (!signal) return await operation();
65
+ const result = await new Promise((resolve, reject) => {
66
+ let settled = false;
67
+ const finish = (callback) => {
68
+ if (settled) return;
69
+ settled = true;
70
+ signal.removeEventListener("abort", onAbort);
71
+ callback();
72
+ };
73
+ const onAbort = () => finish(() => reject(signal.reason));
74
+ signal.addEventListener("abort", onAbort, { once: true });
75
+ if (signal.aborted) {
76
+ onAbort();
77
+ return;
78
+ }
79
+ Promise.resolve().then(() => {
80
+ signal.throwIfAborted();
81
+ return operation();
82
+ }).then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
83
+ });
84
+ signal.throwIfAborted();
85
+ return result;
86
+ }
87
+ function cancellationReason(signal) {
88
+ return signal.reason instanceof Error && signal.reason.name === "TimeoutError" ? "timeout" : "aborted";
89
+ }
90
+ function addUsage(first, second) {
91
+ if (!first) return second;
92
+ if (!second) return first;
93
+ const inputTokens = first.inputTokens === void 0 && second.inputTokens === void 0 ? void 0 : (first.inputTokens ?? 0) + (second.inputTokens ?? 0);
94
+ const outputTokens = first.outputTokens === void 0 && second.outputTokens === void 0 ? void 0 : (first.outputTokens ?? 0) + (second.outputTokens ?? 0);
95
+ const totalTokens = first.totalTokens === void 0 && second.totalTokens === void 0 ? void 0 : (first.totalTokens ?? 0) + (second.totalTokens ?? 0);
96
+ return {
97
+ ...inputTokens !== void 0 ? { inputTokens } : {},
98
+ ...outputTokens !== void 0 ? { outputTokens } : {},
99
+ ...totalTokens !== void 0 ? { totalTokens } : {}
100
+ };
101
+ }
102
+ function assertTokenBudget(agentName, limitName, usageName, limit, stepUsage, totalUsage) {
103
+ if (limit === void 0 || limit === false) return;
104
+ const stepTokens = stepUsage?.[usageName];
105
+ if (stepTokens === void 0 || !Number.isFinite(stepTokens) || stepTokens < 0) throw new Error(`Agent "${agentName}" cannot enforce ${limitName}: model usage.${usageName} is missing or invalid`);
106
+ if ((totalUsage?.[usageName] ?? 0) > limit) throw new Error(`Agent "${agentName}" exceeded ${limitName} limit of ${limit}`);
107
+ }
108
+ function assertContinuationBudget(agentName, limitName, usageName, limit, totalUsage) {
109
+ if (limit !== void 0 && limit !== false && (totalUsage?.[usageName] ?? 0) >= limit) throw new Error(`Agent "${agentName}" exhausted ${limitName} limit of ${limit} before completing`);
110
+ }
111
+ function remainingOutputTokens(limit, usage) {
112
+ if (limit === void 0 || limit === false) return void 0;
113
+ return limit - (usage?.outputTokens ?? 0);
114
+ }
115
+ function eventUsage(usage) {
116
+ if (usage === void 0) return void 0;
117
+ const value = toJsonValue(usage, "Model usage must be JSON-serializable");
118
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("Model usage must be a JSON object");
119
+ return value;
120
+ }
121
+ //#endregion
122
+ //#region src/internal/model-stream.ts
123
+ const MAX_DELTA_CHARS = 512;
124
+ const MAX_DELTA_DELAY_MS = 32;
125
+ function isRecord(value) {
126
+ return typeof value === "object" && value !== null && !Array.isArray(value);
127
+ }
128
+ function canonicalJson(value) {
129
+ if (Array.isArray(value)) return value.map(canonicalJson);
130
+ if (!isRecord(value)) return value;
131
+ const prototype = Object.getPrototypeOf(value);
132
+ if (prototype !== Object.prototype && prototype !== null) return value;
133
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalJson(item)]));
134
+ }
135
+ function assertConsistentOutput(result, outputText) {
136
+ if (result.output === void 0) {
137
+ if (outputText) throw new TypeError("Model stream emitted output without a final output");
138
+ return;
139
+ }
140
+ if (typeof result.output === "string") {
141
+ if (result.output !== outputText) throw new TypeError("Model stream deltas do not match the final output");
142
+ return;
143
+ }
144
+ if (!outputText) throw new TypeError("Model stream returned JSON output without output deltas");
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(outputText);
148
+ } catch (error) {
149
+ throw new TypeError("Model stream output deltas are not valid JSON", { cause: error });
150
+ }
151
+ if (JSON.stringify(canonicalJson(parsed)) !== JSON.stringify(canonicalJson(result.output))) throw new TypeError("Model stream deltas do not match the final JSON output");
152
+ }
153
+ function assertStreamEvent(value) {
154
+ if (!isRecord(value)) throw new TypeError("ModelGateway stream event must be an object");
155
+ if (value.type === "output.delta") {
156
+ if (typeof value.delta !== "string") throw new TypeError("ModelGateway output.delta must contain a string delta");
157
+ return;
158
+ }
159
+ if (value.type === "completed") {
160
+ if (!isRecord(value.result)) throw new TypeError("ModelGateway completed event must contain a result");
161
+ return;
162
+ }
163
+ throw new TypeError("ModelGateway returned an unknown stream event");
164
+ }
165
+ function takeCharacters(value, count) {
166
+ const characters = Array.from(value);
167
+ return [characters.slice(0, count).join(""), characters.slice(count).join("")];
168
+ }
169
+ async function* readModelStream(model, input) {
170
+ input.signal?.throwIfAborted();
171
+ const stream = model.stream(input);
172
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") throw new TypeError("ModelGateway.stream must return an AsyncIterable");
173
+ const iterator = stream[Symbol.asyncIterator]();
174
+ let pending;
175
+ let completed;
176
+ let outputText = "";
177
+ let buffer = "";
178
+ let firstDelta = true;
179
+ let bufferedAt = 0;
180
+ const next = () => {
181
+ const promise = abortable(() => iterator.next(), input.signal);
182
+ promise.catch(() => {});
183
+ return promise;
184
+ };
185
+ try {
186
+ while (true) {
187
+ if (buffer && Array.from(buffer).length >= MAX_DELTA_CHARS) {
188
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
189
+ buffer = rest;
190
+ bufferedAt = performance.now();
191
+ yield chunk;
192
+ continue;
193
+ }
194
+ pending ??= next();
195
+ let item;
196
+ if (buffer) {
197
+ const remaining = Math.max(0, MAX_DELTA_DELAY_MS - (performance.now() - bufferedAt));
198
+ const raced = await Promise.race([pending.then((value) => ({
199
+ type: "item",
200
+ value
201
+ })), new Promise((resolve) => {
202
+ setTimeout(() => resolve({ type: "flush" }), remaining);
203
+ })]);
204
+ if (raced.type === "flush") {
205
+ const chunk = buffer;
206
+ buffer = "";
207
+ bufferedAt = 0;
208
+ yield chunk;
209
+ continue;
210
+ }
211
+ item = raced.value;
212
+ } else item = await pending;
213
+ pending = void 0;
214
+ if (item.done) {
215
+ if (!completed) throw new TypeError("ModelGateway stream ended without completed");
216
+ assertConsistentOutput(completed, outputText);
217
+ return completed;
218
+ }
219
+ assertStreamEvent(item.value);
220
+ if (completed) throw new TypeError("ModelGateway stream emitted an event after completed");
221
+ if (item.value.type === "completed") {
222
+ completed = item.value.result;
223
+ if (buffer) {
224
+ const chunk = buffer;
225
+ buffer = "";
226
+ bufferedAt = 0;
227
+ yield chunk;
228
+ }
229
+ continue;
230
+ }
231
+ if (!item.value.delta) continue;
232
+ outputText += item.value.delta;
233
+ buffer += item.value.delta;
234
+ if (firstDelta) {
235
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
236
+ firstDelta = false;
237
+ buffer = rest;
238
+ bufferedAt = performance.now();
239
+ yield chunk;
240
+ } else if (!bufferedAt) bufferedAt = performance.now();
241
+ }
242
+ } catch (error) {
243
+ if (buffer) yield buffer;
244
+ throw error;
245
+ } finally {
246
+ if (pending) pending.catch(() => {});
247
+ if (iterator.return) Promise.resolve(iterator.return()).catch(() => {});
248
+ }
249
+ }
250
+ //#endregion
251
+ export { assertTokenBudget as a, remainingOutputTokens as c, serializeValue as d, toJsonValue as f, assertContinuationBudget as i, toErrorMessage as l, abortable as n, cancellationReason as o, addUsage as r, eventUsage as s, readModelStream as t, serializeJsonValue as u };
@@ -1,4 +1,4 @@
1
- import { d as ToolCall, f as ToolSpec, o as JsonObject, r as AgentMessage } from "../index-D_RBJmVt.mjs";
1
+ import { h as ToolSpec, i as AgentMessage, l as JsonValue, m as ToolCall, s as JsonObject } from "../index-C_Zpr13f.mjs";
2
2
  //#region src/models/index.d.ts
3
3
  type ReasoningEffort = 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high';
4
4
  interface ModelUsage {
@@ -6,22 +6,41 @@ interface ModelUsage {
6
6
  outputTokens?: number;
7
7
  totalTokens?: number;
8
8
  }
9
- interface ModelGenerateInput {
9
+ interface ModelInput {
10
10
  messages: AgentMessage[];
11
11
  tools?: ToolSpec[];
12
12
  reasoning?: ReasoningEffort;
13
13
  modelOptions?: Record<string, unknown>;
14
14
  outputSchema?: JsonObject;
15
+ maxOutputTokens?: number;
16
+ providerState?: unknown;
15
17
  signal?: AbortSignal;
16
18
  }
17
- interface ModelGenerateResult<TOutput = unknown> {
19
+ interface ModelResult<TOutput = unknown> {
18
20
  output?: TOutput;
19
21
  toolCalls?: ToolCall[];
20
22
  usage?: ModelUsage;
23
+ providerState?: unknown;
24
+ }
25
+ interface ModelMetadata {
26
+ provider?: string;
27
+ model?: string;
21
28
  }
22
29
  interface ModelGateway {
23
- generate(input: ModelGenerateInput): Promise<ModelGenerateResult>;
30
+ stream(input: ModelInput): AsyncIterable<ModelStreamEvent>;
31
+ metadata?: ModelMetadata;
32
+ stateCodec?: {
33
+ serialize(state: unknown): JsonValue;
34
+ restore(state: JsonValue): unknown;
35
+ };
24
36
  }
37
+ type ModelStreamEvent<TOutput = unknown> = {
38
+ type: 'output.delta';
39
+ delta: string;
40
+ } | {
41
+ type: 'completed';
42
+ result: ModelResult<TOutput>;
43
+ };
25
44
  type ModelRef = string | ModelGateway;
26
45
  //#endregion
27
- export { ModelGateway, ModelGenerateInput, ModelGenerateResult, ModelRef, ModelUsage, ReasoningEffort };
46
+ export { ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, ReasoningEffort };
@@ -0,0 +1,2 @@
1
+ import { a as TraceAnnotation, c as TraceContentPolicy, d as TraceRedactor, f as TraceRedactorInput, h as TraceStatus, i as RunTrace, l as TraceCost, m as TraceSpanKind, n as CostCalculatorInput, o as TraceContent, p as TraceSpan, r as ObservabilityOptions, s as TraceContentKind, t as CostCalculator, u as TraceExporter } from "../index-ojCY3lwm.mjs";
2
+ export { CostCalculator, CostCalculatorInput, ObservabilityOptions, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExporter, TraceRedactor, TraceRedactorInput, 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-QTkd6a7C.mjs";
2
+ export { PolicyAuthorization, PolicyDecision, PolicyDefinition, definePolicy };
@@ -0,0 +1,6 @@
1
+ //#region src/policies/index.ts
2
+ function definePolicy(policy) {
3
+ return policy;
4
+ }
5
+ //#endregion
6
+ export { definePolicy };
@@ -1,17 +1,2 @@
1
- import { a as ExecutionContext, t as AgentEvent } from "../index-D_RBJmVt.mjs";
2
- import { ModelUsage } from "../models/index.mjs";
3
- import { StandardSchemaV1 } from "@standard-schema/spec";
4
- //#region src/runtime/index.d.ts
5
- interface RunRequest<TInput = unknown, TOutput = unknown> {
6
- input: TInput;
7
- context?: ExecutionContext;
8
- outputSchema?: StandardSchemaV1<unknown, TOutput>;
9
- signal?: AbortSignal;
10
- }
11
- interface RunResult<TOutput = unknown> {
12
- output: TOutput;
13
- events?: AgentEvent[];
14
- usage?: ModelUsage;
15
- }
16
- //#endregion
17
- export { RunRequest, RunResult };
1
+ import { C as isDurableRunStore, S as ToolExecutionStatus, _ as RunStore, a as DurableRunStore, b as ToolExecutionRecord, c as ListEventsOptions, d as RunCheckpoint, f as RunLease, g as RunStatus, h as RunResult, i as CredentialStore, l as PendingToolExecution, m as RunRequest, n as ApprovalRequest, o as ExecutionCommit, p as RunPause, r as ApprovalResolution, s as InMemoryRunStore, t as AgentRun, u as ResumeRunResolution, v as Session, x as ToolExecutionResolution, y as SessionId } from "../index-DGWOGXzc.mjs";
2
+ export { AgentRun, ApprovalRequest, ApprovalResolution, CredentialStore, DurableRunStore, ExecutionCommit, InMemoryRunStore, ListEventsOptions, PendingToolExecution, ResumeRunResolution, RunCheckpoint, RunLease, RunPause, RunRequest, RunResult, RunStatus, RunStore, Session, SessionId, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, isDurableRunStore };
@@ -1 +1,92 @@
1
- export {};
1
+ //#region src/runtime/index.ts
2
+ function isDurableRunStore(store) {
3
+ const value = store;
4
+ return [
5
+ value.getCheckpoint,
6
+ value.getToolExecution,
7
+ value.commitExecution,
8
+ value.acquireLease,
9
+ value.renewLease,
10
+ value.releaseLease
11
+ ].every((method) => typeof method === "function");
12
+ }
13
+ var InMemoryRunStore = class {
14
+ #runs = /* @__PURE__ */ new Map();
15
+ #sessions = /* @__PURE__ */ new Map();
16
+ #events = /* @__PURE__ */ new Map();
17
+ #checkpoints = /* @__PURE__ */ new Map();
18
+ #toolExecutions = /* @__PURE__ */ new Map();
19
+ #leases = /* @__PURE__ */ new Map();
20
+ async getRun(runId) {
21
+ const run = this.#runs.get(runId);
22
+ return run === void 0 ? void 0 : structuredClone(run);
23
+ }
24
+ async saveRun(run) {
25
+ this.#runs.set(run.id, structuredClone(run));
26
+ if (!this.#events.has(run.id)) this.#events.set(run.id, []);
27
+ }
28
+ async getSession(sessionId) {
29
+ const session = this.#sessions.get(sessionId);
30
+ return session === void 0 ? void 0 : structuredClone(session);
31
+ }
32
+ async saveSession(session) {
33
+ this.#sessions.set(session.id, structuredClone(session));
34
+ }
35
+ async appendEvent(event) {
36
+ const events = this.#events.get(event.runId);
37
+ if (!events) throw new Error(`Run "${event.runId}" does not exist`);
38
+ events.push(structuredClone(event));
39
+ }
40
+ async listEvents(runId, options = {}) {
41
+ const events = this.#events.get(runId);
42
+ if (!events) throw new Error(`Run "${runId}" does not exist`);
43
+ let start = 0;
44
+ if (options.after !== void 0) {
45
+ const cursor = events.findIndex(({ id }) => id === options.after);
46
+ if (cursor < 0) throw new Error(`Event cursor "${options.after}" does not exist in run "${runId}"`);
47
+ start = cursor + 1;
48
+ }
49
+ return structuredClone(events.slice(start).sort((a, b) => a.sequence - b.sequence));
50
+ }
51
+ async getCheckpoint(runId) {
52
+ const checkpoint = this.#checkpoints.get(runId);
53
+ return checkpoint === void 0 ? void 0 : structuredClone(checkpoint);
54
+ }
55
+ async getToolExecution(runId, toolCallId) {
56
+ const execution = this.#toolExecutions.get(`${runId}:${toolCallId}`);
57
+ return execution === void 0 ? void 0 : structuredClone(execution);
58
+ }
59
+ async commitExecution(commit) {
60
+ const current = this.#runs.get(commit.run.id);
61
+ if (!current || current.revision !== commit.expectedRevision) return false;
62
+ const run = structuredClone(commit.run);
63
+ run.revision = commit.expectedRevision + 1;
64
+ this.#runs.set(run.id, run);
65
+ commit.run.revision = run.revision;
66
+ if (commit.session) this.#sessions.set(commit.session.id, structuredClone(commit.session));
67
+ if (commit.checkpoint === null) this.#checkpoints.delete(run.id);
68
+ else if (commit.checkpoint) this.#checkpoints.set(run.id, structuredClone(commit.checkpoint));
69
+ if (commit.toolExecution) this.#toolExecutions.set(`${run.id}:${commit.toolExecution.toolCallId}`, structuredClone(commit.toolExecution));
70
+ const events = this.#events.get(run.id);
71
+ if (!events) throw new Error(`Run "${run.id}" does not exist`);
72
+ for (const event of commit.events ?? []) events.push(structuredClone(event));
73
+ return true;
74
+ }
75
+ async acquireLease(lease) {
76
+ const current = this.#leases.get(lease.runId);
77
+ if (current && current.ownerId !== lease.ownerId && Date.parse(current.expiresAt) > Date.now()) return false;
78
+ this.#leases.set(lease.runId, structuredClone(lease));
79
+ return true;
80
+ }
81
+ async renewLease(lease) {
82
+ const current = this.#leases.get(lease.runId);
83
+ if (!current || current.ownerId !== lease.ownerId) return false;
84
+ this.#leases.set(lease.runId, structuredClone(lease));
85
+ return true;
86
+ }
87
+ async releaseLease(runId, ownerId) {
88
+ if (this.#leases.get(runId)?.ownerId === ownerId) this.#leases.delete(runId);
89
+ }
90
+ };
91
+ //#endregion
92
+ export { InMemoryRunStore, isDurableRunStore };
@@ -1,10 +1,11 @@
1
- import { d as ToolCall } from "../index-D_RBJmVt.mjs";
2
- import { ModelGateway, ModelGenerateInput, ModelGenerateResult } from "../models/index.mjs";
1
+ import { m as ToolCall } from "../index-C_Zpr13f.mjs";
2
+ import { ModelGateway, ModelInput, ModelResult } from "../models/index.mjs";
3
+ import { a as DurableRunStore } from "../index-DGWOGXzc.mjs";
3
4
  //#region src/testing/index.d.ts
4
5
  interface FakeModel extends ModelGateway {
5
- readonly calls: readonly ModelGenerateInput[];
6
+ readonly calls: readonly ModelInput[];
6
7
  }
7
- declare function fakeModel(...responses: ModelGenerateResult[]): FakeModel;
8
+ declare function fakeModel(...responses: ModelResult[]): FakeModel;
8
9
  interface ModelGatewayContract {
9
10
  output?: unknown;
10
11
  toolCall?: ToolCall;
@@ -12,5 +13,6 @@ interface ModelGatewayContract {
12
13
  error?: Error;
13
14
  }
14
15
  declare function testModelGateway(model: ModelGateway, contract?: ModelGatewayContract): Promise<void>;
16
+ declare function testRunStore(store: DurableRunStore): Promise<void>;
15
17
  //#endregion
16
- export { FakeModel, ModelGatewayContract, fakeModel, testModelGateway };
18
+ export { FakeModel, ModelGatewayContract, fakeModel, testModelGateway, testRunStore };