@fevex/core 0.1.0-alpha.8 → 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.
- package/README.md +30 -1
- package/dist/agents/index.d.mts +2 -2
- package/dist/channels/index.d.mts +1 -1
- package/dist/evals/index.d.mts +3 -3
- package/dist/{fevex-DB0-k1fb.d.mts → fevex-WBvRWSpy.d.mts} +14 -8
- package/dist/http/index.d.mts +3 -3
- package/dist/{index-B8molngu.d.mts → index-3bFNzCiY.d.mts} +64 -3
- package/dist/{index-Bl0hR7EC.d.mts → index-BLgiXQK4.d.mts} +1 -1
- package/dist/{index-DtMxzCqj.d.mts → index-BbwT5XxQ.d.mts} +92 -2
- package/dist/{index-CuaetTLQ.d.mts → index-CmFBB4Px.d.mts} +2 -2
- package/dist/{index-CAyAoOW0.d.mts → index-D4mWV2zG.d.mts} +1 -1
- package/dist/{index-CecXoEbs.d.mts → index-D7FoZ7aQ.d.mts} +2 -2
- package/dist/{index-BfYzemR8.d.mts → index-D7r0puBi.d.mts} +14 -1
- package/dist/{index-CODYPevS.d.mts → index-D8lCFkc7.d.mts} +3 -3
- package/dist/{index-RKE3-CKs.d.mts → index-DgSxJZo4.d.mts} +2 -2
- package/dist/index.d.mts +11 -11
- package/dist/index.mjs +456 -77
- package/dist/knowledge/index.d.mts +1 -1
- package/dist/models/index.d.mts +2 -2
- package/dist/observability/index.d.mts +1 -1
- package/dist/policies/index.d.mts +1 -1
- package/dist/runtime/index.d.mts +2 -2
- package/dist/runtime/index.mjs +68 -1
- package/dist/teams/index.d.mts +1 -1
- package/dist/testing/index.d.mts +5 -5
- package/dist/tools/index.d.mts +2 -2
- package/dist/tools/index.mjs +221 -1
- package/dist/workflows/index.d.mts +1 -1
- package/package.json +1 -1
- 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-
|
|
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 };
|
package/dist/models/index.d.mts
CHANGED
|
@@ -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-
|
|
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-
|
|
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-
|
|
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 };
|
package/dist/runtime/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, ContextCompactionInput, ContextCompactionOptions, ContextCompactor, ContextTokenEstimator, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DigestContextCompactorOptions, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, 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, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, 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 };
|
package/dist/runtime/index.mjs
CHANGED
|
@@ -39,6 +39,73 @@ function estimateContextTokens(input) {
|
|
|
39
39
|
if (input.tools?.length) characters += JSON.stringify(input.tools).length;
|
|
40
40
|
return Math.max(1, Math.ceil(characters / 4));
|
|
41
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
|
+
}
|
|
42
109
|
/**
|
|
43
110
|
* Deterministic compactor used when the host does not inject one. It keeps
|
|
44
111
|
* role-aware excerpts of older messages and drops the oldest excerpts first.
|
|
@@ -284,4 +351,4 @@ var InMemoryRunStore = class {
|
|
|
284
351
|
}
|
|
285
352
|
};
|
|
286
353
|
//#endregion
|
|
287
|
-
export { InMemoryRunStore, createDigestContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
|
|
354
|
+
export { InMemoryRunStore, createDigestContextCompactor, createModelContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
|
package/dist/teams/index.d.mts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/testing/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { E as ToolProvider } from "../index-BbwT5XxQ.mjs";
|
|
2
|
+
import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-D7r0puBi.mjs";
|
|
1
3
|
import { m as ToolCall } from "../types-CckDlhYo.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { f as
|
|
5
|
-
import { d as ToolProvider } from "../index-DtMxzCqj.mjs";
|
|
6
|
-
import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-CuaetTLQ.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;
|
package/dist/tools/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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";
|
|
1
2
|
import { g as ToolSpec, m as ToolCall } from "../types-CckDlhYo.mjs";
|
|
2
|
-
|
|
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 };
|
|
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 };
|
package/dist/tools/index.mjs
CHANGED
|
@@ -230,4 +230,224 @@ function toToolSpec(tool, inputSchema) {
|
|
|
230
230
|
};
|
|
231
231
|
}
|
|
232
232
|
//#endregion
|
|
233
|
-
|
|
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 };
|
|
@@ -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-
|
|
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