@tangle-network/agent-knowledge 4.1.0 → 5.0.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.
@@ -1,7 +1,8 @@
1
- import { b as AgentMemoryAdapter, C as KnowledgeBenchmarkSpec, H as KnowledgeMemoryBenchmarkTaskKind, o as KnowledgeAnswerBenchmarkTaskKind, G as KnowledgeMemoryBenchmarkCase, q as KnowledgeBenchmarkCase, p as KnowledgeBenchmarkArtifact, ad as RunMemoryAdapterBenchmarkOptions, ae as RunMemoryAdapterBenchmarkResult, x as KnowledgeBenchmarkScenario, v as KnowledgeBenchmarkReport, B as BuildRetrievalBenchmarkCasesFromQrelsOptions, L as KnowledgeRetrievalBenchmarkCase, M as KnowledgeRetrievalBenchmarkQrel, t as KnowledgeBenchmarkEvaluation, D as KnowledgeBenchmarkSplit, ab as RunKnowledgeBenchmarkSuiteOptions, ac as RunKnowledgeBenchmarkSuiteResult } from '../types-DP38encz.js';
2
- export { K as KnowledgeAnswerBenchmarkCase, r as KnowledgeBenchmarkCaseBase, s as KnowledgeBenchmarkDistribution, u as KnowledgeBenchmarkFamily, w as KnowledgeBenchmarkResponder, y as KnowledgeBenchmarkSliceSummary, z as KnowledgeBenchmarkSource, E as KnowledgeBenchmarkTaskKind, F as KnowledgeClaimMatcher, I as KnowledgeMemoryEvent, J as KnowledgeMemoryFactMatcher, N as KnowledgeRetrievalBenchmarkQuery, O as MemoryAdapterBenchmarkCandidate, P as MemoryAdapterBenchmarkRankingRow } from '../types-DP38encz.js';
1
+ import { f as AgentMemoryAdapter, F as KnowledgeBenchmarkSpec, L as KnowledgeMemoryBenchmarkTaskKind, r as KnowledgeAnswerBenchmarkTaskKind, J as KnowledgeMemoryBenchmarkCase, t as KnowledgeBenchmarkCase, s as KnowledgeBenchmarkArtifact, aa as RunMemoryAdapterBenchmarkOptions, ab as RunMemoryAdapterBenchmarkResult, C as KnowledgeBenchmarkScenario, y as KnowledgeBenchmarkReport, B as BuildRetrievalBenchmarkCasesFromQrelsOptions, O as KnowledgeRetrievalBenchmarkCase, P as KnowledgeRetrievalBenchmarkQrel, w as KnowledgeBenchmarkEvaluation, G as KnowledgeBenchmarkSplit, a8 as RunKnowledgeBenchmarkSuiteOptions, a9 as RunKnowledgeBenchmarkSuiteResult } from '../types-BY-xLVw-.js';
2
+ export { K as KnowledgeAnswerBenchmarkCase, u as KnowledgeBenchmarkCaseBase, v as KnowledgeBenchmarkDistribution, x as KnowledgeBenchmarkFamily, z as KnowledgeBenchmarkResponder, D as KnowledgeBenchmarkSliceSummary, E as KnowledgeBenchmarkSource, H as KnowledgeBenchmarkTaskKind, I as KnowledgeClaimMatcher, M as KnowledgeMemoryEvent, N as KnowledgeMemoryFactMatcher, Q as KnowledgeRetrievalBenchmarkQuery, S as MemoryAdapterBenchmarkCandidate, T as MemoryAdapterBenchmarkRankingRow } from '../types-BY-xLVw-.js';
3
3
  import { CampaignResult, JudgeConfig } from '@tangle-network/agent-eval/campaign';
4
4
  import '../types-6x0OpfW6.js';
5
+ import '@tangle-network/agent-interface';
5
6
 
6
7
  declare function createNoopMemoryBenchmarkAdapter(id?: string): AgentMemoryAdapter;
7
8
  declare function createInMemoryBenchmarkAdapter(options?: {
@@ -20,7 +20,7 @@ import {
20
20
  scoreKnowledgeBenchmarkArtifact,
21
21
  scoreMemoryBenchmarkArtifact,
22
22
  summarizeKnowledgeBenchmarkCampaign
23
- } from "../chunk-BBCIB4UL.js";
23
+ } from "../chunk-EYIA5PLQ.js";
24
24
  import "../chunk-DQ3PDMDP.js";
25
25
  import "../chunk-YMKHCTS2.js";
26
26
  export {
@@ -926,9 +926,6 @@ function reconcileInterruptedMemoryPaidCalls(costLedger) {
926
926
  "external memory provider"
927
927
  );
928
928
  }
929
- function reconcileInterruptedRunPaidCalls(costLedger, label) {
930
- reconcileInterruptedPaidCallsAtMaximum(costLedger, () => true, label);
931
- }
932
929
  function reconcileInterruptedPaidCallsAtMaximum(costLedger, ownsActor, label) {
933
930
  if (costLedger.summary().unresolvedCalls === 0) return;
934
931
  const pending = requirePendingCostCallInspection(costLedger);
@@ -1025,7 +1022,6 @@ function reserveRecoveryAttempts(input) {
1025
1022
  path,
1026
1023
  label,
1027
1024
  event: {
1028
- schema: 1,
1029
1025
  attemptId,
1030
1026
  generation,
1031
1027
  recordedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
@@ -1102,7 +1098,7 @@ function readRecoveryAttemptGenerations(storage, path, label) {
1102
1098
  }
1103
1099
  function parseRecoveryAttemptEvent(value, path, line, label) {
1104
1100
  const event = value;
1105
- const valid = typeof event === "object" && event !== null && event.schema === 1 && typeof event.attemptId === "string" && event.attemptId.length > 0 && Number.isSafeInteger(event.generation) && event.generation > 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt));
1101
+ const valid = typeof event === "object" && event !== null && typeof event.attemptId === "string" && event.attemptId.length > 0 && Number.isSafeInteger(event.generation) && event.generation > 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt));
1106
1102
  if (!valid) throw new Error(`invalid ${label} '${path}' line ${line}`);
1107
1103
  return value;
1108
1104
  }
@@ -1111,9 +1107,7 @@ function isMissingPendingCostCall(error, callId) {
1111
1107
  }
1112
1108
  function requirePendingCostCallInspection(costLedger) {
1113
1109
  if (!costLedger.listPending) {
1114
- throw new Error(
1115
- "interrupted memory recovery requires CostLedger.listPending() from @tangle-network/agent-eval 0.122.8 or newer"
1116
- );
1110
+ throw new Error("interrupted memory recovery requires CostLedger.listPending() support");
1117
1111
  }
1118
1112
  return costLedger.listPending();
1119
1113
  }
@@ -1604,7 +1598,7 @@ function readActiveMemoryBenchmarkAttempts(storage, path) {
1604
1598
  }
1605
1599
  function parseMemoryBenchmarkAttemptEvent(value, path, line) {
1606
1600
  const event = value;
1607
- const valid = typeof event === "object" && event !== null && event.schema === 3 && (event.status === "started" || event.status === "cleaned") && isNonEmptyString(event.attemptId) && isNonEmptyString(event.candidateId) && isNonEmptyString(event.candidateRef) && isNonEmptyString(event.adapterId) && isNonEmptyString(event.caseId) && isNonEmptyString(event.cellId) && isAgentMemoryScope(event.scope) && typeof event.adapterCreationCostUsd === "number" && Number.isFinite(event.adapterCreationCostUsd) && event.adapterCreationCostUsd >= 0 && typeof event.costUsdPerCase === "number" && Number.isFinite(event.costUsdPerCase) && event.costUsdPerCase >= 0 && typeof event.recoveryCostUsdPerAttempt === "number" && Number.isFinite(event.recoveryCostUsdPerAttempt) && event.recoveryCostUsdPerAttempt >= 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt)) && typeof event.recovery === "boolean";
1601
+ const valid = typeof event === "object" && event !== null && (event.status === "started" || event.status === "cleaned") && isNonEmptyString(event.attemptId) && isNonEmptyString(event.candidateId) && isNonEmptyString(event.candidateRef) && isNonEmptyString(event.adapterId) && isNonEmptyString(event.caseId) && isNonEmptyString(event.cellId) && isAgentMemoryScope(event.scope) && typeof event.adapterCreationCostUsd === "number" && Number.isFinite(event.adapterCreationCostUsd) && event.adapterCreationCostUsd >= 0 && typeof event.costUsdPerCase === "number" && Number.isFinite(event.costUsdPerCase) && event.costUsdPerCase >= 0 && typeof event.recoveryCostUsdPerAttempt === "number" && Number.isFinite(event.recoveryCostUsdPerAttempt) && event.recoveryCostUsdPerAttempt >= 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt)) && typeof event.recovery === "boolean";
1608
1602
  if (!valid) {
1609
1603
  throw new Error(`invalid memory benchmark attempt event in '${path}' line ${line}`);
1610
1604
  }
@@ -1702,7 +1696,6 @@ function createMemoryAdapterBenchmarkResponder(options) {
1702
1696
  options.scope
1703
1697
  );
1704
1698
  const attempt = {
1705
- schema: 3,
1706
1699
  status: "started",
1707
1700
  attemptId,
1708
1701
  candidateId: options.candidateId,
@@ -2002,11 +1995,7 @@ function renderSliceTable(slices) {
2002
1995
  }
2003
1996
 
2004
1997
  // src/retrieval-eval.ts
2005
- import {
2006
- heldOutGate,
2007
- parameterSweepProposer,
2008
- runImprovementLoop
2009
- } from "@tangle-network/agent-eval/campaign";
1998
+ import { canonicalJson as canonicalJson2 } from "@tangle-network/agent-eval";
2010
1999
  function retrievalConfigSurface(config) {
2011
2000
  return canonicalJson2(config);
2012
2001
  }
@@ -2129,161 +2118,36 @@ function scoreRetrievalArtifact(artifact, scenario) {
2129
2118
  matchedTargetIds: [...matchedTargetIds].sort()
2130
2119
  };
2131
2120
  }
2132
- function buildRetrievalParameterCandidates(searchSpace, options = {}) {
2133
- const candidates = [];
2134
- for (const [path, values] of Object.entries(searchSpace).sort(([a], [b]) => a.localeCompare(b))) {
2135
- for (const value of values) {
2136
- if (options.baseline && canonicalJson2(getConfigPath(options.baseline, path)) === canonicalJson2(value)) {
2137
- continue;
2138
- }
2139
- candidates.push({
2140
- label: `${path}=${formatCandidateValue(value)}`,
2141
- rationale: `Set retrieval config ${path} to ${formatCandidateValue(value)}`,
2142
- changes: [{ path, value }]
2143
- });
2144
- }
2145
- }
2146
- return candidates;
2147
- }
2148
- function retrievalParameterSweepProposer(options) {
2149
- const candidates = options.candidates ?? (options.searchSpace ? buildRetrievalParameterCandidates(options.searchSpace, { baseline: options.baseline }) : []);
2150
- if (candidates.length === 0) {
2151
- throw new Error("retrievalParameterSweepProposer requires at least one candidate");
2152
- }
2153
- return parameterSweepProposer({ candidates });
2154
- }
2155
- async function runRetrievalImprovementLoop(options) {
2156
- const split = splitRetrievalScenarios(options);
2157
- const candidates = resolveRetrievalCandidates(options);
2158
- const populationSize = options.populationSize ?? Math.max(1, Math.min(4, candidates.length));
2159
- const maxGenerations = options.maxGenerations ?? Math.max(1, Math.ceil(candidates.length / populationSize));
2160
- const proposer = withTargetRecallStop(
2161
- retrievalParameterSweepProposer({ candidates }),
2162
- options.targetRecall
2163
- );
2164
- const gate = options.gate ?? heldOutGate({
2165
- scenarios: split.holdoutScenarios,
2166
- deltaThreshold: options.deltaThreshold ?? 0.02
2167
- });
2168
- const result = await runImprovementLoop({
2169
- baselineSurface: retrievalConfigSurface(options.baseline),
2170
- scenarios: split.trainScenarios,
2171
- holdoutScenarios: split.holdoutScenarios,
2172
- dispatchWithSurface: buildRetrievalEvalDispatch({
2173
- index: options.index,
2174
- defaultK: options.defaultK,
2175
- retrieve: options.retrieve
2176
- }),
2177
- judges: [...options.judges ?? [retrievalRecallJudge({ weights: options.metricWeights })]],
2178
- proposer,
2179
- gate,
2180
- autoOnPromote: "none",
2181
- runDir: options.runDir ?? ".agent-knowledge/retrieval-improvement",
2182
- seed: options.seed,
2183
- reps: options.reps,
2184
- resumable: options.resumable,
2185
- costCeiling: options.costCeiling,
2186
- maxConcurrency: options.maxConcurrency,
2187
- dispatchTimeoutMs: options.dispatchTimeoutMs,
2188
- expectUsage: options.expectUsage ?? "off",
2189
- tracing: options.tracing,
2190
- storage: options.storage,
2191
- populationSize,
2192
- maxGenerations,
2193
- promoteTopK: options.promoteTopK,
2194
- maxImprovementShots: options.maxImprovementShots,
2195
- report: options.report,
2196
- findings: options.findings,
2197
- now: options.now
2198
- });
2199
- return {
2200
- ...result,
2201
- baselineConfig: options.baseline,
2202
- winnerConfig: retrievalConfigFromSurface(result.winnerSurface),
2203
- trainScenarios: split.trainScenarios,
2204
- holdoutScenarios: split.holdoutScenarios,
2205
- candidates,
2206
- targetRecall: options.targetRecall
2207
- };
2208
- }
2209
- function splitRetrievalScenarios(options) {
2210
- const scenarios = [...options.scenarios];
2211
- if (scenarios.length === 0) {
2212
- throw new Error("runRetrievalImprovementLoop requires at least one training scenario");
2213
- }
2214
- if (options.holdoutScenarios) {
2215
- const holdoutScenarios = [...options.holdoutScenarios];
2216
- if (holdoutScenarios.length === 0) {
2217
- throw new Error("runRetrievalImprovementLoop holdoutScenarios must not be empty");
2218
- }
2219
- return { trainScenarios: scenarios, holdoutScenarios };
2220
- }
2221
- if (scenarios.length < 2) {
2121
+ function partitionRetrievalScenarios(scenarios, options = {}) {
2122
+ if (scenarios.length < 4) {
2222
2123
  throw new Error(
2223
- "runRetrievalImprovementLoop requires at least 2 scenarios when holdoutScenarios are not provided"
2124
+ "partitionRetrievalScenarios requires at least 4 scenarios for non-empty train and selection partitions plus 2 final scenarios"
2224
2125
  );
2225
2126
  }
2226
- const holdoutFraction = options.holdoutFraction ?? 0.3;
2227
- if (!Number.isFinite(holdoutFraction) || holdoutFraction <= 0 || holdoutFraction >= 1) {
2228
- throw new Error(
2229
- `runRetrievalImprovementLoop holdoutFraction must be > 0 and < 1, got ${String(holdoutFraction)}`
2230
- );
2231
- }
2232
- const shuffled = seededShuffle(scenarios, options.splitSeed ?? options.seed ?? 42);
2233
- const holdoutCount = Math.min(
2234
- shuffled.length - 1,
2235
- Math.max(1, Math.round(shuffled.length * holdoutFraction))
2236
- );
2237
- const splitIndex = shuffled.length - holdoutCount;
2238
- return {
2239
- trainScenarios: shuffled.slice(0, splitIndex),
2240
- holdoutScenarios: shuffled.slice(splitIndex)
2241
- };
2242
- }
2243
- function resolveRetrievalCandidates(options) {
2244
- const candidates = options.candidates ? [...options.candidates] : options.searchSpace ? buildRetrievalParameterCandidates(options.searchSpace, { baseline: options.baseline }) : [];
2245
- if (candidates.length === 0) {
2246
- throw new Error("runRetrievalImprovementLoop requires candidates or searchSpace");
2247
- }
2248
- return candidates;
2249
- }
2250
- function withTargetRecallStop(proposer, targetRecall) {
2251
- if (targetRecall === void 0) {
2252
- return proposer;
2127
+ const selectionFraction = options.selectionFraction ?? 0.2;
2128
+ const finalFraction = options.finalFraction ?? 0.2;
2129
+ assertPartitionFraction(selectionFraction, "selectionFraction");
2130
+ assertPartitionFraction(finalFraction, "finalFraction");
2131
+ if (selectionFraction + finalFraction >= 1) {
2132
+ throw new Error("selectionFraction + finalFraction must be less than 1");
2253
2133
  }
2254
- if (!Number.isFinite(targetRecall) || targetRecall < 0 || targetRecall > 1) {
2255
- throw new Error(`targetRecall must be between 0 and 1, got ${String(targetRecall)}`);
2134
+ const shuffled = seededShuffle(scenarios, options.seed ?? 42);
2135
+ const finalCount = Math.max(2, Math.round(shuffled.length * finalFraction));
2136
+ const selectionCount = Math.max(1, Math.round(shuffled.length * selectionFraction));
2137
+ if (finalCount + selectionCount >= shuffled.length) {
2138
+ throw new Error("retrieval scenario fractions leave no training scenarios");
2256
2139
  }
2140
+ const trainEnd = shuffled.length - selectionCount - finalCount;
2257
2141
  return {
2258
- kind: `${proposer.kind}:target-recall`,
2259
- propose: (context) => proposer.propose(context),
2260
- decide(args) {
2261
- const baseDecision = proposer.decide?.(args);
2262
- if (baseDecision?.stop) {
2263
- return baseDecision;
2264
- }
2265
- const bestRecall = bestObservedRecall(args.history);
2266
- if (bestRecall >= targetRecall) {
2267
- return {
2268
- stop: true,
2269
- reason: `target recall ${targetRecall} reached with train recall ${bestRecall}`
2270
- };
2271
- }
2272
- return { stop: false };
2273
- }
2142
+ trainScenarios: shuffled.slice(0, trainEnd),
2143
+ selectionScenarios: shuffled.slice(trainEnd, trainEnd + selectionCount),
2144
+ finalScenarios: shuffled.slice(trainEnd + selectionCount)
2274
2145
  };
2275
2146
  }
2276
- function bestObservedRecall(history) {
2277
- let best = Number.NEGATIVE_INFINITY;
2278
- for (const generation of history) {
2279
- for (const candidate of generation.candidates) {
2280
- const recall = candidate.dimensions.recall;
2281
- if (recall !== void 0 && Number.isFinite(recall) && recall > best) {
2282
- best = recall;
2283
- }
2284
- }
2147
+ function assertPartitionFraction(value, name) {
2148
+ if (!Number.isFinite(value) || value <= 0 || value >= 1) {
2149
+ throw new Error(`${name} must be greater than 0 and less than 1`);
2285
2150
  }
2286
- return best;
2287
2151
  }
2288
2152
  function retrievalK(config, scenario, defaultK) {
2289
2153
  const rawK = config.k ?? config.topK ?? scenario.k ?? defaultK;
@@ -2399,35 +2263,6 @@ function normalizeWeight(value) {
2399
2263
  }
2400
2264
  return value;
2401
2265
  }
2402
- function getConfigPath(config, path) {
2403
- let current = config;
2404
- for (const part of path.split(".")) {
2405
- if (!isJsonObject(current)) {
2406
- return void 0;
2407
- }
2408
- current = current[part];
2409
- }
2410
- return current;
2411
- }
2412
- function formatCandidateValue(value) {
2413
- if (typeof value === "string") {
2414
- return value;
2415
- }
2416
- return canonicalJson2(value);
2417
- }
2418
- function canonicalJson2(value) {
2419
- if (value === void 0) {
2420
- return "undefined";
2421
- }
2422
- if (Array.isArray(value)) {
2423
- return `[${value.map(canonicalJson2).join(",")}]`;
2424
- }
2425
- if (isJsonObject(value)) {
2426
- const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson2(child)}`);
2427
- return `{${entries.join(",")}}`;
2428
- }
2429
- return JSON.stringify(value);
2430
- }
2431
2266
  function isJsonObject(value) {
2432
2267
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2433
2268
  }
@@ -3272,9 +3107,7 @@ export {
3272
3107
  buildRetrievalEvalDispatch,
3273
3108
  retrievalRecallJudge,
3274
3109
  scoreRetrievalArtifact,
3275
- buildRetrievalParameterCandidates,
3276
- retrievalParameterSweepProposer,
3277
- runRetrievalImprovementLoop,
3110
+ partitionRetrievalScenarios,
3278
3111
  memoryHitToSourceRecord,
3279
3112
  memoryWriteResultToSourceRecord,
3280
3113
  createNoopMemoryBenchmarkAdapter,
@@ -3289,7 +3122,6 @@ export {
3289
3122
  buildFirstPartyMemoryLifecycleBenchmarkCases,
3290
3123
  DEFAULT_MEMORY_RECOVERY_RETRIES_PER_ATTEMPT,
3291
3124
  reconcileInterruptedMemoryPaidCalls,
3292
- reconcileInterruptedRunPaidCalls,
3293
3125
  assertNoInterruptedPaidCalls,
3294
3126
  hasSettledPaidCall,
3295
3127
  appendAttemptJournalEvent,
@@ -3318,4 +3150,4 @@ export {
3318
3150
  parseKnowledgeBenchmarkQrels,
3319
3151
  buildRetrievalBenchmarkCasesFromQrels
3320
3152
  };
3321
- //# sourceMappingURL=chunk-BBCIB4UL.js.map
3153
+ //# sourceMappingURL=chunk-EYIA5PLQ.js.map