@fevex/core 0.1.0-alpha.7 → 0.1.0-alpha.9

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 (34) hide show
  1. package/README.md +49 -0
  2. package/dist/agents/index.d.mts +2 -2
  3. package/dist/artifacts/index.d.mts +1 -1
  4. package/dist/channels/index.d.mts +1 -1
  5. package/dist/evals/index.d.mts +4 -4
  6. package/dist/{fevex-CVMLnZsk.d.mts → fevex-WBvRWSpy.d.mts} +20 -10
  7. package/dist/http/index.d.mts +4 -4
  8. package/dist/{index-CzAi2Y_Z.d.mts → index-3bFNzCiY.d.mts} +154 -4
  9. package/dist/{index-CbACw6xZ.d.mts → index-BLgiXQK4.d.mts} +2 -2
  10. package/dist/{index-5p3q2yIp.d.mts → index-BbwT5XxQ.d.mts} +94 -4
  11. package/dist/{index-Df84VWmN.d.mts → index-CL7mu_x9.d.mts} +1 -1
  12. package/dist/{index-BTD1c4Ys.d.mts → index-CmFBB4Px.d.mts} +3 -3
  13. package/dist/{index-B0AdFbgr.d.mts → index-D4mWV2zG.d.mts} +2 -2
  14. package/dist/{index-CpLDt6Rw.d.mts → index-D7FoZ7aQ.d.mts} +3 -3
  15. package/dist/{index-BgKFd9yw.d.mts → index-D7r0puBi.d.mts} +15 -2
  16. package/dist/{index-1cHr7KB_.d.mts → index-D8lCFkc7.d.mts} +4 -4
  17. package/dist/{index-CseuTR-F.d.mts → index-DgSxJZo4.d.mts} +3 -3
  18. package/dist/index.d.mts +13 -13
  19. package/dist/index.mjs +655 -78
  20. package/dist/knowledge/index.d.mts +1 -1
  21. package/dist/models/index.d.mts +2 -2
  22. package/dist/observability/index.d.mts +1 -1
  23. package/dist/policies/index.d.mts +1 -1
  24. package/dist/runtime/index.d.mts +2 -2
  25. package/dist/runtime/index.mjs +172 -1
  26. package/dist/sandbox/index.d.mts +1 -1
  27. package/dist/teams/index.d.mts +1 -1
  28. package/dist/testing/index.d.mts +6 -6
  29. package/dist/tools/index.d.mts +3 -3
  30. package/dist/tools/index.mjs +221 -1
  31. package/dist/{types-B8laW1hM.d.mts → types-CckDlhYo.d.mts} +15 -1
  32. package/dist/workflows/index.d.mts +1 -1
  33. package/package.json +1 -1
  34. package/dist/exact-definition-NHBBFlFR.d.mts +0 -4
@@ -1,2 +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-B0AdFbgr.mjs";
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-D4mWV2zG.mjs";
2
2
  export { AgentsMdOptions, ContextBlock, ContextProvider, InMemoryMemoryStore, KnowledgeContext, LoadSkillFileOptions, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, ProgressiveSkillProvider, SkillDefinition, createAgentsMdContextProvider, createMemoryContextProvider, defineContextProvider, defineSkill, isProgressiveSkillProvider, loadSkillFile, loadSkillFiles };
@@ -1,2 +1,2 @@
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 } from "../index-BgKFd9yw.mjs";
2
- export { ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, ReasoningEffort, ToolChoice };
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 };
@@ -1,2 +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-CpLDt6Rw.mjs";
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-D7FoZ7aQ.mjs";
2
2
  export { CostCalculator, CostCalculatorInput, ObservabilityOptions, ObservabilityStats, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExportQueueOptions, TraceExporter, TraceRedactor, TraceRedactorInput, TraceRunKind, TraceSpan, TraceSpanKind, TraceStatus };
@@ -1,2 +1,2 @@
1
- import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-CbACw6xZ.mjs";
1
+ import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-BLgiXQK4.mjs";
2
2
  export { PolicyAuthorization, PolicyDecision, PolicyDefinition, definePolicy };
@@ -1,2 +1,2 @@
1
- import { $ as validateListEventsOptions, A as RunPause, B as TeamRun, C as PurgeRunsResult, D as RunCheckpoint, E as RetainableRunStore, F as RunStore, G as WorkflowBudgetUsage, H as ToolExecutionRecord, I as Session, J as WorkflowRun, K as WorkflowCheckpoint, L as SessionId, M as RunRequest, N as RunResult, O as RunCorrelation, P as RunStatus, Q as isRetainableRunStore, R as StoredRunCheckpoint, S as PurgeRunsOptions, T as RetainableRunStatus, U as ToolExecutionResolution, V as TimerResolution, W as ToolExecutionStatus, X as WorkflowWaitRecord, Y as WorkflowStepRecord, Z as isDurableRunStore, _ as EventResolution, a as AgentRun, b as ListEventsOptions, c as ApprovalRequest, d as CoordinatorRun, et as validatePurgeRunsOptions, f as CredentialStore, g as ElicitationResolution, h as ElicitationRequest, i as InMemoryRunStore, j as RunRecord, k as RunLease, l as ApprovalResolution, m as ElicitationMode, o as AgentRunPause, p as DurableRunStore, q as WorkflowCompensationRecord, s as ApprovalMode, u as CoordinatorCheckpoint, v as ExecutionCommit, w as ResumeRunResolution, x as PendingToolExecution, y as ExecutionCreate, z as TeamCheckpoint } from "../index-CzAi2Y_Z.mjs";
2
- export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, PendingToolExecution, PurgeRunsOptions, PurgeRunsResult, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunLease, RunPause, RunRecord, RunRequest, RunResult, RunStatus, RunStore, Session, SessionId, StoredRunCheckpoint, TeamCheckpoint, TeamRun, TimerResolution, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowRun, WorkflowStepRecord, WorkflowWaitRecord, isDurableRunStore, isRetainableRunStore, validateListEventsOptions, validatePurgeRunsOptions };
1
+ import { $ as SessionCompaction, A as ElicitationMode, B as ResumeRunResolution, C as ApprovalMode, D as CoordinatorRun, E as CoordinatorCheckpoint, F as ExecutionCreate, G as RunLease, H as RetainableRunStore, I as ListEventsOptions, J as RunRequest, K as RunPause, L as PendingToolExecution, M as ElicitationResolution, N as EventResolution, O as CredentialStore, P as ExecutionCommit, Q as Session, R as PurgeRunsOptions, S as AgentRunPause, T as ApprovalResolution, U as RunCheckpoint, V as RetainableRunStatus, W as RunCorrelation, X as RunStatus, Y as RunResult, Z as RunStore, _ as createDigestContextCompactor, _t as validatePurgeRunsOptions, at as ToolExecutionRecord, b as resolveContextBudget, c as InMemoryRunStore, ct as WorkflowBudgetUsage, d as ContextCompactionStats, dt as WorkflowRun, et as SessionId, f as ContextCompactor, ft as WorkflowStepRecord, g as ResolvedContextBudget, gt as validateListEventsOptions, h as ModelContextCompactorOptions, ht as isRetainableRunStore, it as TimerResolution, j as ElicitationRequest, k as DurableRunStore, l as ContextCompactionInput, lt as WorkflowCheckpoint, m as DigestContextCompactorOptions, mt as isDurableRunStore, nt as TeamCheckpoint, ot as ToolExecutionResolution, p as ContextTokenEstimator, pt as WorkflowWaitRecord, q as RunRecord, rt as TeamRun, st as ToolExecutionStatus, tt as StoredRunCheckpoint, u as ContextCompactionOptions, ut as WorkflowCompensationRecord, v as createModelContextCompactor, w as ApprovalRequest, x as AgentRun, y as estimateContextTokens, z as PurgeRunsResult } from "../index-3bFNzCiY.mjs";
2
+ export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, ContextCompactionInput, ContextCompactionOptions, ContextCompactionStats, ContextCompactor, ContextTokenEstimator, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DigestContextCompactorOptions, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, ModelContextCompactorOptions, PendingToolExecution, PurgeRunsOptions, PurgeRunsResult, ResolvedContextBudget, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunLease, RunPause, RunRecord, RunRequest, RunResult, RunStatus, RunStore, Session, SessionCompaction, SessionId, StoredRunCheckpoint, TeamCheckpoint, TeamRun, TimerResolution, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowRun, WorkflowStepRecord, WorkflowWaitRecord, createDigestContextCompactor, createModelContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
@@ -1,4 +1,175 @@
1
1
  import { t as FevexRunError } from "../run-error-Cr17wPGH.mjs";
2
+ //#region src/runtime/compaction.ts
3
+ /** Validates a context budget and fills in defaults. */
4
+ function resolveContextBudget(budget, label) {
5
+ if (budget === void 0) return void 0;
6
+ if (!isRecord(budget)) throw new TypeError(`${label} must be an object`);
7
+ const contextWindow = budget.contextWindow;
8
+ if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0) throw new TypeError(`${label}.contextWindow must be a positive safe integer`);
9
+ const reserveOutputTokens = budget.reserveOutputTokens ?? 0;
10
+ if (!Number.isSafeInteger(reserveOutputTokens) || reserveOutputTokens < 0 || reserveOutputTokens >= contextWindow) throw new TypeError(`${label}.reserveOutputTokens must be a non-negative safe integer below contextWindow`);
11
+ const usable = contextWindow - reserveOutputTokens;
12
+ const compactAt = budget.compactAt ?? .8;
13
+ if (typeof compactAt !== "number" || !Number.isFinite(compactAt) || compactAt <= 0 || compactAt > 1) throw new TypeError(`${label}.compactAt must be greater than 0 and at most 1`);
14
+ const targetTokens = budget.targetTokens ?? Math.max(1, Math.floor(usable * Math.min(.5, compactAt * .9)));
15
+ if (!Number.isSafeInteger(targetTokens) || targetTokens <= 0 || targetTokens >= usable) throw new TypeError(`${label}.targetTokens must be a positive safe integer below the usable window`);
16
+ if (targetTokens > Math.floor(usable * compactAt)) throw new TypeError(`${label}.targetTokens must not exceed the compaction threshold`);
17
+ const safetyFactor = budget.safetyFactor ?? 1.1;
18
+ if (typeof safetyFactor !== "number" || !Number.isFinite(safetyFactor) || safetyFactor < 1 || safetyFactor > 2) throw new TypeError(`${label}.safetyFactor must be between 1 and 2`);
19
+ return {
20
+ contextWindow,
21
+ reserveOutputTokens,
22
+ compactAt,
23
+ targetTokens,
24
+ safetyFactor
25
+ };
26
+ }
27
+ /**
28
+ * Rough provider-neutral estimate: about four characters per token plus
29
+ * message and tool framing. Hosts can inject a real tokenizer instead.
30
+ */
31
+ function estimateContextTokens(input) {
32
+ let characters = 0;
33
+ for (const message of input.messages) {
34
+ characters += message.role.length + message.content.length + 16;
35
+ if (message.name !== void 0) characters += message.name.length;
36
+ if (message.toolCallId !== void 0) characters += message.toolCallId.length;
37
+ if (message.toolCalls !== void 0) characters += JSON.stringify(message.toolCalls).length;
38
+ }
39
+ if (input.tools?.length) characters += JSON.stringify(input.tools).length;
40
+ return Math.max(1, Math.ceil(characters / 4));
41
+ }
42
+ const DEFAULT_COMPACTOR_PROMPT = "You compact conversation history for another agent. Preserve decisions, approvals, constraints, identifiers, tool results and open tasks. Return only the summary.";
43
+ /**
44
+ * Creates a semantic compactor backed by a model. Use a cheap, fast model and
45
+ * keep it separate from the agent model when possible. Large transcripts are
46
+ * summarized in chunks and then merged.
47
+ */
48
+ function createModelContextCompactor(options) {
49
+ const maxOutputTokens = options.maxOutputTokens ?? 1024;
50
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) throw new TypeError("Model compactor maxOutputTokens must be a positive safe integer");
51
+ const maxInputChars = options.maxInputChars ?? 12e4;
52
+ if (!Number.isSafeInteger(maxInputChars) || maxInputChars < 1e3) throw new TypeError("Model compactor maxInputChars must be a safe integer of at least 1,000");
53
+ const systemPrompt = options.systemPrompt ?? DEFAULT_COMPACTOR_PROMPT;
54
+ const summarize = async (text, instruction, signal) => {
55
+ const stream = options.model.stream({
56
+ messages: [{
57
+ role: "system",
58
+ content: systemPrompt
59
+ }, {
60
+ role: "user",
61
+ content: `${instruction}\n\n${text || "(empty)"}`
62
+ }],
63
+ maxOutputTokens,
64
+ ...signal === void 0 ? {} : { signal }
65
+ });
66
+ let deltas = "";
67
+ let output;
68
+ for await (const event of stream) if (event.type === "output.delta") deltas += event.delta;
69
+ else output = event.result.output;
70
+ const summary = typeof output === "string" ? output : deltas;
71
+ if (!summary.trim()) throw new Error("Model context compactor returned an empty summary");
72
+ return summary.trim();
73
+ };
74
+ return { async compact(input) {
75
+ let current = formatTranscript(input.messages);
76
+ let depth = 0;
77
+ while (current.length > maxInputChars && depth < 4) {
78
+ const summaries = [];
79
+ for (const chunk of splitText(current, maxInputChars)) summaries.push(await summarize(chunk, "Summarize this part of a longer conversation. Preserve decisions, constraints, identifiers, tool results and open tasks.", input.signal));
80
+ current = summaries.join("\n\n");
81
+ depth += 1;
82
+ }
83
+ if (current.length > maxInputChars) current = `${current.slice(0, maxInputChars - 1)}…`;
84
+ return [{
85
+ role: "system",
86
+ content: await summarize(current, `Merge the following into one summary in at most ${input.targetTokens} tokens.`, input.signal)
87
+ }];
88
+ } };
89
+ }
90
+ function formatTranscript(messages) {
91
+ return messages.map((message) => {
92
+ const toolCalls = message.toolCalls?.length ? `\nTool calls: ${message.toolCalls.map((call) => `${call.name}(${JSON.stringify(call.input)})`).join(", ")}` : "";
93
+ const name = message.name === void 0 ? "" : ` (${message.name})`;
94
+ return `${message.role}${name}: ${message.content}${toolCalls}`;
95
+ }).join("\n\n");
96
+ }
97
+ function splitText(text, maxChars) {
98
+ const chunks = [];
99
+ let rest = text;
100
+ while (rest.length > maxChars) {
101
+ let cut = rest.lastIndexOf("\n", maxChars);
102
+ if (cut < Math.floor(maxChars / 2)) cut = maxChars;
103
+ chunks.push(rest.slice(0, cut));
104
+ rest = rest.slice(cut).trimStart();
105
+ }
106
+ if (rest) chunks.push(rest);
107
+ return chunks;
108
+ }
109
+ /**
110
+ * Deterministic compactor used when the host does not inject one. It keeps
111
+ * role-aware excerpts of older messages and drops the oldest excerpts first.
112
+ * It never calls a model.
113
+ */
114
+ function createDigestContextCompactor(options = {}) {
115
+ const maxChars = options.maxCharsPerMessage ?? 400;
116
+ if (!Number.isSafeInteger(maxChars) || maxChars < 40) throw new TypeError("Digest compactor maxCharsPerMessage must be a safe integer of at least 40");
117
+ return { compact(input) {
118
+ if (input.messages.length === 0) return [{
119
+ role: "system",
120
+ content: "[Compacted earlier conversation]"
121
+ }];
122
+ let perMessage = maxChars;
123
+ let lines = input.messages.flatMap((message) => digestMessage(message, perMessage));
124
+ while (input.estimateTokens([{
125
+ role: "system",
126
+ content: digestContent(lines, input.messages.length)
127
+ }]) > input.targetTokens && perMessage > 40) {
128
+ perMessage = Math.max(40, Math.floor(perMessage * .7));
129
+ lines = input.messages.flatMap((message) => digestMessage(message, perMessage));
130
+ }
131
+ let selected = lines;
132
+ let content = digestContent(selected, input.messages.length);
133
+ while (input.estimateTokens([{
134
+ role: "system",
135
+ content
136
+ }]) > input.targetTokens && selected.length > 1) {
137
+ selected = selected.slice(1);
138
+ content = digestContent(selected, input.messages.length);
139
+ }
140
+ const limit = Math.max(80, input.targetTokens * 4);
141
+ if (content.length > limit) content = `${content.slice(0, Math.max(0, limit - 1))}…`;
142
+ return [{
143
+ role: "system",
144
+ content
145
+ }];
146
+ } };
147
+ }
148
+ function digestContent(lines, totalMessages) {
149
+ const omitted = Math.max(0, totalMessages - lines.length);
150
+ return [`[Compacted conversation: ${totalMessages} earlier messages${omitted ? `, ${omitted} omitted` : ""}]`, ...lines].join("\n");
151
+ }
152
+ function digestMessage(message, maxChars) {
153
+ const content = truncate(message.content, maxChars);
154
+ if (message.role === "user") return content ? [`User: ${content}`] : [];
155
+ if (message.role === "assistant") {
156
+ const lines = [];
157
+ if (content) lines.push(`Assistant: ${content}`);
158
+ for (const call of message.toolCalls ?? []) lines.push(`Tool call ${call.name}: ${truncate(JSON.stringify(call.input), Math.min(maxChars, 200))}`);
159
+ return lines;
160
+ }
161
+ if (message.role === "tool") return content ? [`Tool result${message.name === void 0 ? "" : ` (${message.name})`}: ${content}`] : [];
162
+ return content ? [`System: ${content}`] : [];
163
+ }
164
+ function truncate(value, maxChars) {
165
+ const normalized = value.replace(/\s+/g, " ").trim();
166
+ if (normalized.length <= maxChars) return normalized;
167
+ return `${normalized.slice(0, Math.max(0, maxChars - 1))}…`;
168
+ }
169
+ function isRecord(value) {
170
+ return typeof value === "object" && value !== null && !Array.isArray(value);
171
+ }
172
+ //#endregion
2
173
  //#region src/runtime/run-store.ts
3
174
  function validateListEventsOptions(options) {
4
175
  if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new TypeError("Event limit must be a positive safe integer");
@@ -180,4 +351,4 @@ var InMemoryRunStore = class {
180
351
  }
181
352
  };
182
353
  //#endregion
183
- export { InMemoryRunStore, isDurableRunStore, isRetainableRunStore, validateListEventsOptions, validatePurgeRunsOptions };
354
+ export { InMemoryRunStore, createDigestContextCompactor, createModelContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
@@ -1,2 +1,2 @@
1
- import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "../index-Df84VWmN.mjs";
1
+ import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "../index-CL7mu_x9.mjs";
2
2
  export { LocalSandboxOptions, Sandbox, SandboxCapabilities, SandboxError, SandboxRunRequest, SandboxRunResult, createLocalSandbox, sandboxResultToJson };
@@ -1,2 +1,2 @@
1
- import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "../index-1cHr7KB_.mjs";
1
+ import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "../index-D8lCFkc7.mjs";
2
2
  export { type TeamDefinition, type TeamDelegation, type TeamHandoff, type TeamLimits, type TeamMember, type TeamStep, type TeamTaskResult, defineTeam };
@@ -1,9 +1,9 @@
1
- import { m as ToolCall } from "../types-B8laW1hM.mjs";
2
- import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-BgKFd9yw.mjs";
3
- import { h as ElicitationRequest, p as DurableRunStore } from "../index-CzAi2Y_Z.mjs";
4
- import { f as MemoryStore } from "../index-B0AdFbgr.mjs";
5
- import { d as ToolProvider } from "../index-5p3q2yIp.mjs";
6
- import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-BTD1c4Ys.mjs";
1
+ import { E as ToolProvider } from "../index-BbwT5XxQ.mjs";
2
+ import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-D7r0puBi.mjs";
3
+ import { m as ToolCall } from "../types-CckDlhYo.mjs";
4
+ import { j as ElicitationRequest, k as DurableRunStore } from "../index-3bFNzCiY.mjs";
5
+ import { f as MemoryStore } from "../index-D4mWV2zG.mjs";
6
+ import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-CmFBB4Px.mjs";
7
7
  //#region src/testing/contracts.d.ts
8
8
  interface ModelGatewayContract {
9
9
  output?: unknown;
@@ -1,3 +1,3 @@
1
- import { g as ToolSpec, m as ToolCall } from "../types-B8laW1hM.mjs";
2
- import { C as toToolSpec, S as defineTool, _ as ToolExecutionContext, a as compileFevexJsonSchema, b as ToolRetryPolicy, c as ConnectionToolPolicy, d as ToolProvider, f as ToolProviderContext, g as ToolDefinition, h as ToolApproval, i as FevexJsonSchemaValidator, l as IntegrationError, m as defineConnection, n as FevexJsonSchemaProfileLimits, o as validateFevexJsonSchemaProfile, p as ToolProviderTool, r as FevexJsonSchemaProfileOptions, s as ConnectionDefinition, t as FEVEX_JSON_SCHEMA_PROFILE_VERSION, u as IntegrationErrorCategory, v as ToolIdempotency, x as ToolRisk, y as ToolResult } from "../index-5p3q2yIp.mjs";
3
- export { ConnectionDefinition, ConnectionToolPolicy, FEVEX_JSON_SCHEMA_PROFILE_VERSION, FevexJsonSchemaProfileLimits, FevexJsonSchemaProfileOptions, FevexJsonSchemaValidator, IntegrationError, IntegrationErrorCategory, ToolApproval, type ToolCall, ToolDefinition, ToolExecutionContext, ToolIdempotency, ToolProvider, ToolProviderContext, ToolProviderTool, ToolResult, ToolRetryPolicy, ToolRisk, type ToolSpec, compileFevexJsonSchema, defineConnection, defineTool, toToolSpec, validateFevexJsonSchemaProfile };
1
+ import { A as ToolApproval, C as ConnectionToolPolicy, D as ToolProviderContext, E as ToolProvider, F as ToolRetryPolicy, I as ToolRisk, L as defineTool, M as ToolExecutionContext, N as ToolIdempotency, O as ToolProviderTool, P as ToolResult, R as toToolSpec, S as ConnectionDefinition, T as IntegrationErrorCategory, _ as FevexJsonSchemaProfileLimits, a as InMemoryToolEmbeddingCacheOptions, b as compileFevexJsonSchema, c as ToolEmbeddingIndexEntry, d as cosineSimilarity, f as schemaKeywords, g as FEVEX_JSON_SCHEMA_PROFILE_VERSION, h as toolEmbeddingText, i as InMemoryToolEmbeddingCache, j as ToolDefinition, k as defineConnection, l as ToolEmbeddingMatch, m as toolEmbeddingKey, n as ToolSearchCandidate, o as ToolEmbeddingCache, p as searchToolEmbeddingIndex, r as BuildToolEmbeddingIndexOptions, s as ToolEmbeddingIndex, t as ToolReranker, u as buildToolEmbeddingIndex, v as FevexJsonSchemaProfileOptions, w as IntegrationError, x as validateFevexJsonSchemaProfile, y as FevexJsonSchemaValidator } from "../index-BbwT5XxQ.mjs";
2
+ import { g as ToolSpec, m as ToolCall } from "../types-CckDlhYo.mjs";
3
+ export { BuildToolEmbeddingIndexOptions, ConnectionDefinition, ConnectionToolPolicy, FEVEX_JSON_SCHEMA_PROFILE_VERSION, FevexJsonSchemaProfileLimits, FevexJsonSchemaProfileOptions, FevexJsonSchemaValidator, InMemoryToolEmbeddingCache, InMemoryToolEmbeddingCacheOptions, IntegrationError, IntegrationErrorCategory, ToolApproval, type ToolCall, ToolDefinition, ToolEmbeddingCache, ToolEmbeddingIndex, ToolEmbeddingIndexEntry, ToolEmbeddingMatch, ToolExecutionContext, ToolIdempotency, ToolProvider, ToolProviderContext, ToolProviderTool, ToolReranker, ToolResult, ToolRetryPolicy, ToolRisk, ToolSearchCandidate, type ToolSpec, buildToolEmbeddingIndex, compileFevexJsonSchema, cosineSimilarity, defineConnection, defineTool, schemaKeywords, searchToolEmbeddingIndex, toToolSpec, toolEmbeddingKey, toolEmbeddingText, validateFevexJsonSchemaProfile };
@@ -230,4 +230,224 @@ function toToolSpec(tool, inputSchema) {
230
230
  };
231
231
  }
232
232
  //#endregion
233
- export { FEVEX_JSON_SCHEMA_PROFILE_VERSION, IntegrationError, compileFevexJsonSchema, defineConnection, defineTool, toToolSpec, validateFevexJsonSchemaProfile };
233
+ //#region src/tools/tool-index.ts
234
+ /** Bounded LRU cache for tool embeddings. */
235
+ var InMemoryToolEmbeddingCache = class {
236
+ #entries = /* @__PURE__ */ new Map();
237
+ #maxEntries;
238
+ constructor(options = {}) {
239
+ const maxEntries = options.maxEntries ?? 1e3;
240
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) throw new TypeError("Tool embedding cache maxEntries must be a positive safe integer");
241
+ this.#maxEntries = maxEntries;
242
+ }
243
+ get size() {
244
+ return this.#entries.size;
245
+ }
246
+ get(key) {
247
+ assertKey(key);
248
+ const value = this.#entries.get(key);
249
+ if (value === void 0) return void 0;
250
+ this.#entries.delete(key);
251
+ this.#entries.set(key, value);
252
+ return [...value];
253
+ }
254
+ set(key, vector) {
255
+ assertKey(key);
256
+ assertVector(vector, "Tool embedding cache vector");
257
+ this.#entries.delete(key);
258
+ this.#entries.set(key, [...vector]);
259
+ while (this.#entries.size > this.#maxEntries) {
260
+ const oldest = this.#entries.keys().next().value;
261
+ if (oldest === void 0) break;
262
+ this.#entries.delete(oldest);
263
+ }
264
+ }
265
+ getMany(keys) {
266
+ return keys.map((key) => this.get(key));
267
+ }
268
+ setMany(entries) {
269
+ for (const entry of entries) this.set(entry.key, entry.vector);
270
+ }
271
+ };
272
+ /**
273
+ * Builds or refreshes a semantic index for a tool catalog. The content key is
274
+ * `sha256(embeddingModel.id + text)`, so changing the model or the tool text
275
+ * invalidates the cached vector.
276
+ */
277
+ async function buildToolEmbeddingIndex(options) {
278
+ assertEmbeddingModel(options.embeddings);
279
+ const batchSize = options.batchSize ?? 64;
280
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1) throw new TypeError("Tool embedding batchSize must be a positive safe integer");
281
+ const tools = options.tools;
282
+ const texts = tools.map(toolEmbeddingText);
283
+ const keys = await Promise.all(texts.map((text) => toolEmbeddingKey(options.embeddings.id, text)));
284
+ const vectors = /* @__PURE__ */ new Map();
285
+ const missing = /* @__PURE__ */ new Map();
286
+ const batchCached = await readCacheMany(options.cache, keys, options.embeddings.dimensions);
287
+ for (let index = 0; index < tools.length; index += 1) {
288
+ const key = keys[index];
289
+ const cached = batchCached === void 0 ? await readCache(options.cache, key, options.embeddings.dimensions) : batchCached[index];
290
+ if (cached !== void 0) {
291
+ vectors.set(key, cached);
292
+ continue;
293
+ }
294
+ if (!missing.has(key)) missing.set(key, texts[index]);
295
+ }
296
+ const pending = [...missing.entries()];
297
+ for (let offset = 0; offset < pending.length; offset += batchSize) {
298
+ options.signal?.throwIfAborted();
299
+ const batch = pending.slice(offset, offset + batchSize);
300
+ const embedded = await options.embeddings.embed({
301
+ texts: batch.map(([, text]) => text),
302
+ ...options.signal === void 0 ? {} : { signal: options.signal }
303
+ });
304
+ if (!Array.isArray(embedded) || embedded.length !== batch.length) throw new Error(`Embedding model "${options.embeddings.id}" returned ${embedded.length} vectors for ${batch.length} texts`);
305
+ const writes = [];
306
+ for (let index = 0; index < batch.length; index += 1) {
307
+ const vector = embedded[index];
308
+ assertVector(vector, `Embedding for "${batch[index][1]}"`);
309
+ vectors.set(batch[index][0], vector);
310
+ writes.push({
311
+ key: batch[index][0],
312
+ vector
313
+ });
314
+ }
315
+ if (options.cache?.setMany !== void 0) try {
316
+ await options.cache.setMany(writes);
317
+ } catch {}
318
+ else for (const write of writes) await writeCache(options.cache, write.key, write.vector);
319
+ }
320
+ const dimensions = options.embeddings.dimensions ?? vectors.values().next().value?.length ?? 0;
321
+ for (const vector of vectors.values()) if (vector.length !== dimensions) throw new Error(`Embedding model "${options.embeddings.id}" returned mixed dimensions: ${dimensions} and ${vector.length}`);
322
+ return {
323
+ modelId: options.embeddings.id,
324
+ dimensions,
325
+ entries: tools.map((tool, index) => ({
326
+ tool,
327
+ vector: [...vectors.get(keys[index])]
328
+ }))
329
+ };
330
+ }
331
+ /** Returns cosine matches above `minScore`, ordered by score. */
332
+ function searchToolEmbeddingIndex(index, query, limit, minScore = 0) {
333
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new TypeError("Tool embedding search limit must be a positive safe integer");
334
+ if (query.length !== index.dimensions) throw new TypeError(`Query embedding has ${query.length} dimensions; index expects ${index.dimensions}`);
335
+ assertVector([...query], "Query embedding");
336
+ if (typeof minScore !== "number" || !Number.isFinite(minScore)) throw new TypeError("Tool embedding minScore must be a finite number");
337
+ return index.entries.map((entry) => ({
338
+ tool: entry.tool,
339
+ score: cosineSimilarity(query, entry.vector)
340
+ })).filter(({ score }) => score >= minScore).sort((left, right) => right.score - left.score || left.tool.name.localeCompare(right.tool.name)).slice(0, limit);
341
+ }
342
+ /** Canonical text indexed for one tool: name, description and schema keywords. */
343
+ function toolEmbeddingText(tool) {
344
+ return [
345
+ tool.name,
346
+ tool.description ?? "",
347
+ schemaKeywords(tool.inputSchema)
348
+ ].filter(Boolean).join("\n");
349
+ }
350
+ /** Extracts property names, descriptions, titles, required fields and enum values. */
351
+ function schemaKeywords(schema) {
352
+ if (schema === void 0) return "";
353
+ const terms = /* @__PURE__ */ new Set();
354
+ const visit = (value, key) => {
355
+ if (typeof value === "string") {
356
+ if (key === "description" || key === "title" || key === "const") terms.add(value);
357
+ return;
358
+ }
359
+ if (Array.isArray(value)) {
360
+ for (const item of value) visit(item, key);
361
+ return;
362
+ }
363
+ if (value === null || typeof value !== "object") return;
364
+ for (const [childKey, child] of Object.entries(value)) {
365
+ if (childKey === "properties" && child !== null && typeof child === "object" && !Array.isArray(child)) {
366
+ for (const property of Object.keys(child)) terms.add(property);
367
+ visit(child, childKey);
368
+ continue;
369
+ }
370
+ if (childKey === "required" && Array.isArray(child)) {
371
+ for (const item of child) if (typeof item === "string") terms.add(item);
372
+ continue;
373
+ }
374
+ if (childKey === "enum" && Array.isArray(child)) {
375
+ for (const item of child) terms.add(String(item));
376
+ continue;
377
+ }
378
+ visit(child, childKey);
379
+ }
380
+ };
381
+ visit(schema);
382
+ return [...terms].join(" ");
383
+ }
384
+ /** Stable content key for one embedding model and tool text. */
385
+ async function toolEmbeddingKey(modelId, text) {
386
+ if (!modelId.trim()) throw new TypeError("Embedding model id cannot be empty");
387
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${modelId}\n${text}`));
388
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
389
+ }
390
+ function cosineSimilarity(left, right) {
391
+ assertVector(left, "Left cosine vector");
392
+ assertVector(right, "Right cosine vector");
393
+ if (left.length !== right.length) throw new TypeError(`Cosine vectors must have the same dimensions: ${left.length} and ${right.length}`);
394
+ let dot = 0;
395
+ let leftNorm = 0;
396
+ let rightNorm = 0;
397
+ for (let index = 0; index < left.length; index += 1) {
398
+ const a = left[index];
399
+ const b = right[index];
400
+ dot += a * b;
401
+ leftNorm += a * a;
402
+ rightNorm += b * b;
403
+ }
404
+ if (leftNorm === 0 || rightNorm === 0) return 0;
405
+ return dot / Math.sqrt(leftNorm * rightNorm);
406
+ }
407
+ function assertEmbeddingModel(model) {
408
+ if (typeof model.id !== "string" || !model.id.trim()) throw new TypeError("Embedding model id must be a non-empty string");
409
+ if (typeof model.embed !== "function") throw new TypeError("Embedding model must implement embed");
410
+ if (model.dimensions !== void 0 && (!Number.isSafeInteger(model.dimensions) || model.dimensions < 1)) throw new TypeError("Embedding model dimensions must be a positive safe integer");
411
+ }
412
+ function assertKey(key) {
413
+ if (typeof key !== "string" || !key.trim()) throw new TypeError("Tool embedding cache key must be a non-empty string");
414
+ }
415
+ function assertVector(vector, label) {
416
+ if (!Array.isArray(vector) || vector.length === 0 || vector.some((value) => typeof value !== "number" || !Number.isFinite(value))) throw new TypeError(`${label} must be a non-empty array of finite numbers`);
417
+ }
418
+ async function readCache(cache, key, dimensions) {
419
+ if (cache === void 0) return void 0;
420
+ try {
421
+ return normalizeCached(await cache.get(key), dimensions);
422
+ } catch {
423
+ return;
424
+ }
425
+ }
426
+ async function readCacheMany(cache, keys, dimensions) {
427
+ if (cache?.getMany === void 0) return void 0;
428
+ try {
429
+ const values = await cache.getMany(keys);
430
+ if (!Array.isArray(values) || values.length !== keys.length) return void 0;
431
+ return values.map((value) => normalizeCached(value, dimensions));
432
+ } catch {
433
+ return;
434
+ }
435
+ }
436
+ function normalizeCached(value, dimensions) {
437
+ if (value === void 0) return void 0;
438
+ try {
439
+ assertVector(value, "Cached tool embedding");
440
+ if (dimensions !== void 0 && value.length !== dimensions) return void 0;
441
+ return [...value];
442
+ } catch {
443
+ return;
444
+ }
445
+ }
446
+ async function writeCache(cache, key, vector) {
447
+ if (cache === void 0) return;
448
+ try {
449
+ await cache.set(key, [...vector]);
450
+ } catch {}
451
+ }
452
+ //#endregion
453
+ export { FEVEX_JSON_SCHEMA_PROFILE_VERSION, InMemoryToolEmbeddingCache, IntegrationError, buildToolEmbeddingIndex, compileFevexJsonSchema, cosineSimilarity, defineConnection, defineTool, schemaKeywords, searchToolEmbeddingIndex, toToolSpec, toolEmbeddingKey, toolEmbeddingText, validateFevexJsonSchemaProfile };
@@ -258,7 +258,7 @@ interface ToolEventSource {
258
258
  connectionName: string;
259
259
  remoteToolName: string;
260
260
  }
261
- type AgentEventType = 'run.started' | 'run.recovered' | 'run.paused' | 'run.resumed' | 'model.started' | 'model.output.delta' | 'model.completed' | 'tool.started' | 'tool.completed' | 'tool.failed' | 'tool.retrying' | 'tool.execution_unknown' | 'artifact.created' | 'elicitation.requested' | 'elicitation.resolved' | 'approval.requested' | 'approval.resolved' | 'run.completed' | 'run.failed' | 'run.cancelled' | 'workflow.run.started' | 'workflow.run.recovered' | 'workflow.step.started' | 'workflow.step.completed' | 'workflow.step.failed' | 'workflow.compensation.started' | 'workflow.compensation.completed' | 'workflow.compensation.failed' | 'workflow.wait.started' | 'workflow.wait.completed' | 'workflow.run.paused' | 'workflow.run.resumed' | 'workflow.run.completed' | 'workflow.run.failed' | 'workflow.run.cancelled' | 'team.run.started' | 'team.run.recovered' | 'team.agent.assigned' | 'team.handoff.created' | 'team.task.completed' | 'team.task.failed' | 'team.merge.started' | 'team.merge.completed' | 'team.merge.failed' | 'team.run.paused' | 'team.run.resumed' | 'team.run.completed' | 'team.run.failed' | 'team.run.cancelled';
261
+ type AgentEventType = 'run.started' | 'run.recovered' | 'run.paused' | 'run.resumed' | 'model.started' | 'model.output.delta' | 'model.completed' | 'context.compacted' | 'tool.started' | 'tool.completed' | 'tool.failed' | 'tool.retrying' | 'tool.execution_unknown' | 'artifact.created' | 'elicitation.requested' | 'elicitation.resolved' | 'approval.requested' | 'approval.resolved' | 'run.completed' | 'run.failed' | 'run.cancelled' | 'workflow.run.started' | 'workflow.run.recovered' | 'workflow.step.started' | 'workflow.step.completed' | 'workflow.step.failed' | 'workflow.compensation.started' | 'workflow.compensation.completed' | 'workflow.compensation.failed' | 'workflow.wait.started' | 'workflow.wait.completed' | 'workflow.run.paused' | 'workflow.run.resumed' | 'workflow.run.completed' | 'workflow.run.failed' | 'workflow.run.cancelled' | 'team.run.started' | 'team.run.recovered' | 'team.agent.assigned' | 'team.handoff.created' | 'team.task.completed' | 'team.task.failed' | 'team.merge.started' | 'team.merge.completed' | 'team.merge.failed' | 'team.run.paused' | 'team.run.resumed' | 'team.run.completed' | 'team.run.failed' | 'team.run.cancelled';
262
262
  interface AgentEventPayloads {
263
263
  'run.started': undefined;
264
264
  'run.recovered': {
@@ -292,6 +292,20 @@ interface AgentEventPayloads {
292
292
  teamDelegationId?: string;
293
293
  teamAgentName?: string;
294
294
  };
295
+ 'context.compacted': {
296
+ step: number;
297
+ removedMessages: number;
298
+ estimatedTokens: number;
299
+ compactedTokens: number;
300
+ targetTokens: number;
301
+ contextWindow: number;
302
+ summary: string;
303
+ summaryTruncated?: boolean;
304
+ workflowStepId?: string;
305
+ workflowAgentName?: string;
306
+ teamDelegationId?: string;
307
+ teamAgentName?: string;
308
+ };
295
309
  'tool.started': {
296
310
  step: number;
297
311
  toolCallId: string;
@@ -1,2 +1,2 @@
1
- import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "../index-CseuTR-F.mjs";
1
+ import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "../index-DgSxJZo4.mjs";
2
2
  export { WorkflowAgentResult, WorkflowDefinition, WorkflowEventDefinition, WorkflowEventResult, WorkflowStep, WorkflowStepContext, WorkflowStepOptions, defineWorkflow };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fevex/core",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "description": "Agent Engineering Framework for code-first, provider-neutral AI agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -1,4 +0,0 @@
1
- //#region src/internal/exact-definition.d.ts
2
- type ExactDefinition<TInput, TShape> = TInput & { readonly [TKey in Exclude<keyof TInput, keyof TShape>]: never; };
3
- //#endregion
4
- export { ExactDefinition as t };