@sedum-dev/core 0.1.0-alpha.22 → 0.1.0-alpha.23

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/dist/index.d.ts CHANGED
@@ -2063,6 +2063,12 @@ interface RelevanceProvider {
2063
2063
  readonly chunkCount?: number;
2064
2064
  /** Indexes of tests too large to score; the caller runs them. */
2065
2065
  readonly oversized?: readonly number[];
2066
+ /** Indexes of tests a failed or unsent call left unscored; the caller runs them. */
2067
+ readonly unscored?: readonly number[];
2068
+ /** Why no test could be scored, such as a diff past the request cap; the caller runs every test. */
2069
+ readonly skipped?: string;
2070
+ /** The first failed call's message, when some calls failed. */
2071
+ readonly failure?: string;
2066
2072
  }>;
2067
2073
  }
2068
2074
  interface ResolverDecision {
@@ -2588,21 +2594,64 @@ declare function relevanceQuestion(test: RelevanceTest): {
2588
2594
  };
2589
2595
  };
2590
2596
  type Question = ReturnType<typeof relevanceQuestion>;
2591
- declare function buildRelevanceBatches<Request>(diff: string, tests: readonly RelevanceTest[], makeRequest: (diff: string, questions: Record<string, Question>) => Request, limits: {
2592
- pair: number;
2593
- batch: number;
2594
- questions: number;
2595
- /** Pair bytes a test must leave for the diff, its metadata and markers. */
2596
- minDiff: number;
2597
- }): {
2598
- batches: {
2597
+ /**
2598
+ * Upper bound on the tokens Jev and Clef count for `text`. Their tokenizers
2599
+ * are not published; this was checked against live counts for code, YAML,
2600
+ * lockfiles, minified JS, hex, base64, CJK, Cyrillic and emoji (1.1 to 4 times
2601
+ * the real count). Dense content, such as hashes, costs about one token per
2602
+ * byte, so a plain byte budget cannot be both safe and roomy for code.
2603
+ */
2604
+ declare function estimateTokens(text: string): number;
2605
+ /** The requests that score a selection, and the tests they leave unscored. */
2606
+ interface RelevancePlan<Request> {
2607
+ readonly batches: {
2599
2608
  request: Request;
2600
2609
  indexes: number[];
2601
2610
  chunkIndex: number;
2602
2611
  }[];
2603
2612
  /** Tests too large to score; callers run them rather than truncate them. */
2604
- oversized: number[];
2605
- };
2613
+ readonly oversized: number[];
2614
+ /** Why no test can be scored, such as a diff past the request cap; callers run every test. */
2615
+ readonly skipped?: string;
2616
+ }
2617
+ /**
2618
+ * Limits are in estimated tokens. Costs add up per part: `makeRequest` must
2619
+ * put the diff in the request as a JSON string, and splitting serialized JSON
2620
+ * at string and object boundaries never lowers the estimate.
2621
+ */
2622
+ declare function buildRelevanceBatches<Request>(diff: string, tests: readonly RelevanceTest[], makeRequest: (diff: string, questions: Record<string, Question>) => Request, limits: {
2623
+ pair: number;
2624
+ batch: number;
2625
+ questions: number;
2626
+ /** Pair tokens a test must leave for the diff, its metadata and markers. */
2627
+ minDiff: number;
2628
+ }): RelevancePlan<Request>;
2629
+
2630
+ /** Most scoring calls in flight at once; give the provider's gate as many. */
2631
+ declare const RELEVANCE_CONCURRENCY = 8;
2632
+ /** What scoring a plan found; see `RelevanceProvider.scoreRelevance`. */
2633
+ interface RelevanceScores {
2634
+ readonly probabilities: number[];
2635
+ readonly calls: ProviderCall[];
2636
+ readonly chunkCount: number;
2637
+ readonly oversized: number[];
2638
+ readonly unscored: number[];
2639
+ readonly skipped?: string;
2640
+ readonly failure?: string;
2641
+ }
2642
+ /**
2643
+ * Sends a plan's requests, `RELEVANCE_CONCURRENCY` at a time, and keeps each test's
2644
+ * highest score. A failed call leaves its tests unscored, so they run; after
2645
+ * `MAX_FAILURES` failures, or one every later call would hit too, no more
2646
+ * start and the tests of unsent requests are unscored as well. A rejected key
2647
+ * or configuration, and cancellation, still fail selection: running every
2648
+ * test would hide a setup the user has to fix.
2649
+ */
2650
+ declare function scoreRelevancePlan<Request>(plan: RelevancePlan<Request>, testCount: number, ask: Ask<Request>, options?: ProviderCallOptions): Promise<RelevanceScores>;
2651
+ type Ask<Request> = (request: Request, indexes: readonly number[]) => Promise<{
2652
+ call: ProviderCall;
2653
+ scores: readonly number[];
2654
+ }>;
2606
2655
 
2607
2656
  interface VisionObservation {
2608
2657
  readonly instruction: string;
@@ -4224,4 +4273,4 @@ interface ActionRequest {
4224
4273
  readonly description: string;
4225
4274
  }
4226
4275
 
4227
- export { ACCEPTANCE_POLICY_VERSION, type ActionRequest, AiValues, type Aim, type AimResult, type AllowRule, AssertionEngineError, type AssertionEngineErrorCode, type AssertionOptions, type AttemptDependencies, type AttemptReport, BACKOFF_JITTER, type BrowserContextOptions, type BrowserContextSession, type BrowserDriver, BrowserDriverError, type BrowserDriverErrorCode, type BrowserInstallResult, type BrowserKind, type BrowserLaunchOptions, type BrowserPage, type BrowserSession, type BrowserSignal, type BrowserSignalSource, BugDetector, type BugDetectorOptions, CACHE_FORMAT, CANDIDATE_LIMIT, CLASSIFICATION_PROMPT_VERSION, type CacheEntry, type CacheLookup, type CacheMissReason, type CacheStore, type CachedClassification, type Candidate, type CandidatePage, type ChoiceWhy, ClassificationBatchError, type ClassificationCache, type ClassificationDiagnostic, type ClassificationDiagnosticCode, type ClassificationInput, type ClassificationMetrics, type ClassificationOptions, type ClassificationProvider, type ClassificationResult, type ClassifiedFlowDefinition, type ClassifiedFlowSentence, type ClassifiedFlowStep, type ClassifiedModuleStep, type ClassifiedStep, type ClassifyFlowOptions, type ClickOptions, type ClickResult, type ControlStateResult, DEFAULT_ALLOW, DEFAULT_BAND, DEFAULT_CONTRADICTION_CUTOFF, DEFAULT_MAX_SEVERAL, DEFAULT_MIN_P, DEFAULT_PROVIDER_CONCURRENCY, DEFAULT_SEMANTIC_THRESHOLDS, DEFAULT_TUNING, DIGEST_LIMIT, DataResolutionError, DeclaredDataValue, type Detection, type DetectionCheck, type DetectorCall, type DigestResult, type DiscoveryProblem, type DiscoveryProblemCode, type EmittedStep, type EmittedTest, type ExplorationAdvisor, type ExploreAction, type ExploreActionKind, type ExploreAdvice, type ExploreAdviceRequest, type ExploreDecision, type ExploreDecisionRequest, type ExploreFailure, type ExploreFinding, type ExploreMode, type ExploreOptions, type ExploreResult, type ExploreRunMeta, type ExploreRunResult, type ExploreSafety, type ExploreStepView, type ExploreTuning, FileClassificationCache, type FillResult, type FillTarget, type FindingTest, type FlowClassificationDiagnostic, type FlowClassificationResult, FlowDefinition, FlowDiagnostic, type FlowRunResult, type FlowRunnerDependencies, FlowScalar, FlowSource, FlowToken, FlowValidationResult, type FrameBox, type FreshPage, FullValidationCoverage, GOAL_NO_MATCH, GateAborted, GateWaitExceeded, type GoalAction, type GoalChoice, type GoalDecision, type GoalOptions, type GoalPlanner, type GoalResult, type GoalState, type GoalValueState, type HelperCall, type HistoryMove, INSPECTED_PAGE_LIMITS, type ImportBinding, type InputSource, type InspectedPage, type InvalidListEntry, type ItemVerdict, type Judge, type JudgeDecision, type JudgePageDigest, type LineRange, type ListedDiagnostic, type ListedTest, type LoadedScriptFile, LocatorCacheConflict, type LocatorCacheDiagnostic, type LocatorCacheLookup, type LocatorCacheSeed, type LocatorDiagnostic, type LocatorFailure, type LocatorOptionDiagnostic, type LocatorOptions, type LocatorResult, MATCHER_VERSION, MAX_COOLDOWN_MS, MAX_PROVIDER_CONCURRENCY, MIN_MODEL_MARGIN, MIN_MODEL_PROBABILITY, MODEL_CHOICES, type MatchResult, type MeasureResult, type ModelChoice, type ModelClassification, type ModelDecision, ModuleBinding, ModuleBindingResolutionError, ModuleStep, NAME_LIMIT, NOT_CHECKED_OFFLINE_CODE, NO_PAGE_FINDINGS, type NavigationOptions, type NavigationResult, NoopCacheStore, NoopClassificationCache, OPERATIONS, OPERATION_SET_VERSION, type Operation, type OracleEvent, type OracleOptions, PAGE_KINDS, PAGE_PROTOCOL, PEER_LIMIT, type PageBridge, type PageCheck, PageChecks, type PageChecksOptions, type PageFindings, type PageInspection, type PageInspector, PageScriptError, PageSignalCollector, type PageVersion, type ParseFlowOptions, ParsedFlowResult, ParsedModuleResult, PlaywrightBrowserDriver, type PlaywrightBrowserDriverOptions, type ProjectFileValidation, type ProjectFiles, type ProjectValidationCounts, type ProjectValidationOptions, type ProjectValidationResult, type ProviderCall, type ProviderCallOptions, ProviderError, type ProviderErrorCode, ProviderGate, type ProviderGateOptions, type ProviderRate, type ProviderTokenUsage, RATE_LIMIT_BUDGET_MS, type ReadTargetResult, type RejectionOwner, RejectionRouter, type RelevanceProvider, type RelevanceTest, type RepeatedMemberPolicy, type ReportPrivacy, type ResolveFlowModulesOptions, type ResolvedDataEntry, type ResolvedFlowResult, ResolvedModuleCall, ResolvedStepTarget, type Resolver, type ResolverCandidate, type ResolverCandidates, type ResolverDecision, type ResolverItem, type ResolverOption, type ResultAttempt, ResultAttemptSchema, type ResultCall, ResultCallSchema, type ResultDetection, ResultDetectionSchema, ResultErrorSchema, type ResultExecution, ResultExecutionSchema, type ResultFrame, ResultFrameSchema, ResultJudgementSchema, ResultLocatorSchema, ResultObservationSchema, type ResultPage, ResultPageSchema, type ResultProblem, ResultProblemSchema, type ResultSink, ResultSourceSchema, type ResultStep, ResultStepSchema, type ResultTest, ResultTestSchema, ResultTotalsSchema, ReusableBrowserDriver, RunRecorder, type RunResult, RunResultSchema, type RunningTest, RuntimeUrl, RuntimeValue, SCRIPT_TEST_SUFFIX, SEMANTIC_CHECKS, ScriptRegistration, type ScriptSentence, type ScriptSentenceScan, type ScriptTest, ScriptUsageError, SeededRandom, type SemanticCheck, type SemanticThresholds, type SentenceClassification, type SentencePresentation, SentenceStep, type SettleOptions, type SettleResult, type ShrinkResult, type SignalSettleOptions, type StateInspection, type StepCommand, StepExecutionError, type StepExecutionOptions, type StepExecutionResult, type StepFailureCode, type StepFailurePhase, type StepFrames, type StepInspection, type StepOperation, type StepOperationKind, type StepOutcome, type StepSource, type StepTokenization, type StrayReason, TEST_SUFFIXES, type TargetCheckDecision, type TargetCheckInput, type TargetCheckOptions, type TargetChecker, type TargetIdentity, TestBody, type TestListing, TestRecording, type TestStartInput, type TraceEntry, type UnattributedRejection, ValidationInput, type VerifyDecision, type VerifyFlag, type VerifyOptions, type VerifyPolicy, type VerifyResult, type VisionFailure, type VisionObservation, type VisionResolver, WAIT_UNTIL, type WriteRecord, allowed, attributeRejection, backoffDelay, buildExploreRunResult, buildRelevanceBatches, callExtent, canonicalSentence, captureVisionObservation, checkRegistrations, classificationKey, classifyParsedFlow, classifySentenceSteps, classifySteps, clearPageRefs, clickTarget, closeQuietly, codePoints, collectCandidates, compareDiagnostics, controlState, cooldownDelay, dedupeDiagnostics, describeAction, describeRejection, discoverFlowFiles, discoverProjectFiles, displayPath, emitTest, evaluateModelAnswer, evaluateVerifyScores, executeSentence, executeStep, explore, findBrowserExecutable, findIdentityCollisions, firstDiagnostic, goalChoiceAccepted, goalFailureArtifacts, goalOperations, inlineValues, installChromium, isBlocking, isClaimSentence, isFlowScalar, isPageInspector, isRunWideProviderError, isSafeRole, isScriptTestFile, isStaticHoldsClaim, isWeakPeer, keyedDigest, listTests, liveCandidates, loadFlowFile, loadListingEntries, loadScriptFile, looksDestructive, matchEntry, matchLiveEntry, measure, navigationWhy, nextConcurrency, nonBlockingFailure, normalizeSignal, opaqueMatches, pageDigest, pageKey, pageVersion, parseAllowRule, parseDataTemplate, parseFlow, parseModule, parseRetryAfter, patternOperation, preflightSentence, projectCandidates, projectDigest, quietPage, readTarget, recordGoalAction, redactOpaqueText, relevanceQuestion, replay, reportPage, resolveData, resolveEntryUrl, resolveFlowModules, resolveModuleBindings, resolveTarget, resolveTypeOperand, resultCall, resultTotals, runFlow, runGoal, runResultJsonSchema, runScriptTest, runtimeFailure, safeSource, safeText, safeUrl, sameVisualVersion, scanImportBindings, scanLocalImports, scanScriptSentences, scriptListingEntries, semanticDetections, shrink, signalDetection, stageEntry, stateDetections, targetVariants, textDetections, tokenize, tokenizeStep, uniqueDetections, unknownCostCall, validateFlows, validateOperand, validateProject, validateRunResult, validateTypeOperand, valueEntries, verify, visibleText, visualCandidates, walkSuiteFiles };
4276
+ export { ACCEPTANCE_POLICY_VERSION, type ActionRequest, AiValues, type Aim, type AimResult, type AllowRule, AssertionEngineError, type AssertionEngineErrorCode, type AssertionOptions, type AttemptDependencies, type AttemptReport, BACKOFF_JITTER, type BrowserContextOptions, type BrowserContextSession, type BrowserDriver, BrowserDriverError, type BrowserDriverErrorCode, type BrowserInstallResult, type BrowserKind, type BrowserLaunchOptions, type BrowserPage, type BrowserSession, type BrowserSignal, type BrowserSignalSource, BugDetector, type BugDetectorOptions, CACHE_FORMAT, CANDIDATE_LIMIT, CLASSIFICATION_PROMPT_VERSION, type CacheEntry, type CacheLookup, type CacheMissReason, type CacheStore, type CachedClassification, type Candidate, type CandidatePage, type ChoiceWhy, ClassificationBatchError, type ClassificationCache, type ClassificationDiagnostic, type ClassificationDiagnosticCode, type ClassificationInput, type ClassificationMetrics, type ClassificationOptions, type ClassificationProvider, type ClassificationResult, type ClassifiedFlowDefinition, type ClassifiedFlowSentence, type ClassifiedFlowStep, type ClassifiedModuleStep, type ClassifiedStep, type ClassifyFlowOptions, type ClickOptions, type ClickResult, type ControlStateResult, DEFAULT_ALLOW, DEFAULT_BAND, DEFAULT_CONTRADICTION_CUTOFF, DEFAULT_MAX_SEVERAL, DEFAULT_MIN_P, DEFAULT_PROVIDER_CONCURRENCY, DEFAULT_SEMANTIC_THRESHOLDS, DEFAULT_TUNING, DIGEST_LIMIT, DataResolutionError, DeclaredDataValue, type Detection, type DetectionCheck, type DetectorCall, type DigestResult, type DiscoveryProblem, type DiscoveryProblemCode, type EmittedStep, type EmittedTest, type ExplorationAdvisor, type ExploreAction, type ExploreActionKind, type ExploreAdvice, type ExploreAdviceRequest, type ExploreDecision, type ExploreDecisionRequest, type ExploreFailure, type ExploreFinding, type ExploreMode, type ExploreOptions, type ExploreResult, type ExploreRunMeta, type ExploreRunResult, type ExploreSafety, type ExploreStepView, type ExploreTuning, FileClassificationCache, type FillResult, type FillTarget, type FindingTest, type FlowClassificationDiagnostic, type FlowClassificationResult, FlowDefinition, FlowDiagnostic, type FlowRunResult, type FlowRunnerDependencies, FlowScalar, FlowSource, FlowToken, FlowValidationResult, type FrameBox, type FreshPage, FullValidationCoverage, GOAL_NO_MATCH, GateAborted, GateWaitExceeded, type GoalAction, type GoalChoice, type GoalDecision, type GoalOptions, type GoalPlanner, type GoalResult, type GoalState, type GoalValueState, type HelperCall, type HistoryMove, INSPECTED_PAGE_LIMITS, type ImportBinding, type InputSource, type InspectedPage, type InvalidListEntry, type ItemVerdict, type Judge, type JudgeDecision, type JudgePageDigest, type LineRange, type ListedDiagnostic, type ListedTest, type LoadedScriptFile, LocatorCacheConflict, type LocatorCacheDiagnostic, type LocatorCacheLookup, type LocatorCacheSeed, type LocatorDiagnostic, type LocatorFailure, type LocatorOptionDiagnostic, type LocatorOptions, type LocatorResult, MATCHER_VERSION, MAX_COOLDOWN_MS, MAX_PROVIDER_CONCURRENCY, MIN_MODEL_MARGIN, MIN_MODEL_PROBABILITY, MODEL_CHOICES, type MatchResult, type MeasureResult, type ModelChoice, type ModelClassification, type ModelDecision, ModuleBinding, ModuleBindingResolutionError, ModuleStep, NAME_LIMIT, NOT_CHECKED_OFFLINE_CODE, NO_PAGE_FINDINGS, type NavigationOptions, type NavigationResult, NoopCacheStore, NoopClassificationCache, OPERATIONS, OPERATION_SET_VERSION, type Operation, type OracleEvent, type OracleOptions, PAGE_KINDS, PAGE_PROTOCOL, PEER_LIMIT, type PageBridge, type PageCheck, PageChecks, type PageChecksOptions, type PageFindings, type PageInspection, type PageInspector, PageScriptError, PageSignalCollector, type PageVersion, type ParseFlowOptions, ParsedFlowResult, ParsedModuleResult, PlaywrightBrowserDriver, type PlaywrightBrowserDriverOptions, type ProjectFileValidation, type ProjectFiles, type ProjectValidationCounts, type ProjectValidationOptions, type ProjectValidationResult, type ProviderCall, type ProviderCallOptions, ProviderError, type ProviderErrorCode, ProviderGate, type ProviderGateOptions, type ProviderRate, type ProviderTokenUsage, RATE_LIMIT_BUDGET_MS, RELEVANCE_CONCURRENCY, type ReadTargetResult, type RejectionOwner, RejectionRouter, type RelevancePlan, type RelevanceProvider, type RelevanceScores, type RelevanceTest, type RepeatedMemberPolicy, type ReportPrivacy, type ResolveFlowModulesOptions, type ResolvedDataEntry, type ResolvedFlowResult, ResolvedModuleCall, ResolvedStepTarget, type Resolver, type ResolverCandidate, type ResolverCandidates, type ResolverDecision, type ResolverItem, type ResolverOption, type ResultAttempt, ResultAttemptSchema, type ResultCall, ResultCallSchema, type ResultDetection, ResultDetectionSchema, ResultErrorSchema, type ResultExecution, ResultExecutionSchema, type ResultFrame, ResultFrameSchema, ResultJudgementSchema, ResultLocatorSchema, ResultObservationSchema, type ResultPage, ResultPageSchema, type ResultProblem, ResultProblemSchema, type ResultSink, ResultSourceSchema, type ResultStep, ResultStepSchema, type ResultTest, ResultTestSchema, ResultTotalsSchema, ReusableBrowserDriver, RunRecorder, type RunResult, RunResultSchema, type RunningTest, RuntimeUrl, RuntimeValue, SCRIPT_TEST_SUFFIX, SEMANTIC_CHECKS, ScriptRegistration, type ScriptSentence, type ScriptSentenceScan, type ScriptTest, ScriptUsageError, SeededRandom, type SemanticCheck, type SemanticThresholds, type SentenceClassification, type SentencePresentation, SentenceStep, type SettleOptions, type SettleResult, type ShrinkResult, type SignalSettleOptions, type StateInspection, type StepCommand, StepExecutionError, type StepExecutionOptions, type StepExecutionResult, type StepFailureCode, type StepFailurePhase, type StepFrames, type StepInspection, type StepOperation, type StepOperationKind, type StepOutcome, type StepSource, type StepTokenization, type StrayReason, TEST_SUFFIXES, type TargetCheckDecision, type TargetCheckInput, type TargetCheckOptions, type TargetChecker, type TargetIdentity, TestBody, type TestListing, TestRecording, type TestStartInput, type TraceEntry, type UnattributedRejection, ValidationInput, type VerifyDecision, type VerifyFlag, type VerifyOptions, type VerifyPolicy, type VerifyResult, type VisionFailure, type VisionObservation, type VisionResolver, WAIT_UNTIL, type WriteRecord, allowed, attributeRejection, backoffDelay, buildExploreRunResult, buildRelevanceBatches, callExtent, canonicalSentence, captureVisionObservation, checkRegistrations, classificationKey, classifyParsedFlow, classifySentenceSteps, classifySteps, clearPageRefs, clickTarget, closeQuietly, codePoints, collectCandidates, compareDiagnostics, controlState, cooldownDelay, dedupeDiagnostics, describeAction, describeRejection, discoverFlowFiles, discoverProjectFiles, displayPath, emitTest, estimateTokens, evaluateModelAnswer, evaluateVerifyScores, executeSentence, executeStep, explore, findBrowserExecutable, findIdentityCollisions, firstDiagnostic, goalChoiceAccepted, goalFailureArtifacts, goalOperations, inlineValues, installChromium, isBlocking, isClaimSentence, isFlowScalar, isPageInspector, isRunWideProviderError, isSafeRole, isScriptTestFile, isStaticHoldsClaim, isWeakPeer, keyedDigest, listTests, liveCandidates, loadFlowFile, loadListingEntries, loadScriptFile, looksDestructive, matchEntry, matchLiveEntry, measure, navigationWhy, nextConcurrency, nonBlockingFailure, normalizeSignal, opaqueMatches, pageDigest, pageKey, pageVersion, parseAllowRule, parseDataTemplate, parseFlow, parseModule, parseRetryAfter, patternOperation, preflightSentence, projectCandidates, projectDigest, quietPage, readTarget, recordGoalAction, redactOpaqueText, relevanceQuestion, replay, reportPage, resolveData, resolveEntryUrl, resolveFlowModules, resolveModuleBindings, resolveTarget, resolveTypeOperand, resultCall, resultTotals, runFlow, runGoal, runResultJsonSchema, runScriptTest, runtimeFailure, safeSource, safeText, safeUrl, sameVisualVersion, scanImportBindings, scanLocalImports, scanScriptSentences, scoreRelevancePlan, scriptListingEntries, semanticDetections, shrink, signalDetection, stageEntry, stateDetections, targetVariants, textDetections, tokenize, tokenizeStep, uniqueDetections, unknownCostCall, validateFlows, validateOperand, validateProject, validateRunResult, validateTypeOperand, valueEntries, verify, visibleText, visualCandidates, walkSuiteFiles };
package/dist/index.js CHANGED
@@ -3513,6 +3513,9 @@ var ProviderGate = class {
3513
3513
  };
3514
3514
 
3515
3515
  // src/relevance.ts
3516
+ var MAX_REQUESTS = 256;
3517
+ var Unplannable = class extends Error {
3518
+ };
3516
3519
  function relevanceQuestion(test2) {
3517
3520
  return {
3518
3521
  type: "noul",
@@ -3578,9 +3581,8 @@ function* splitLine(part, fits) {
3578
3581
  else high = middle - 1;
3579
3582
  }
3580
3583
  if (!low)
3581
- throw new ProviderError(
3582
- "invalid-input",
3583
- "Diff metadata plus a test exceeds the relevance context budget; input was not truncated. Run the full suite."
3584
+ throw new Unplannable(
3585
+ "diff metadata leaves no room for the diff next to the largest test"
3584
3586
  );
3585
3587
  yield context + points.slice(offset, offset + low).join("");
3586
3588
  offset += low;
@@ -3590,11 +3592,7 @@ function partition(diff, fits) {
3590
3592
  const output = [];
3591
3593
  const push = (text) => {
3592
3594
  output.push(text);
3593
- if (output.length > 256)
3594
- throw new ProviderError(
3595
- "invalid-input",
3596
- "Relevance selection exceeds the 256-request guard; input was not truncated. Run the full suite."
3597
- );
3595
+ if (output.length > MAX_REQUESTS) throw tooManyRequests();
3598
3596
  };
3599
3597
  let current = "";
3600
3598
  function append(part) {
@@ -3622,20 +3620,43 @@ function partition(diff, fits) {
3622
3620
  if (current) push(current);
3623
3621
  return output;
3624
3622
  }
3623
+ function estimateTokens(text) {
3624
+ let tokens = 0;
3625
+ for (const [run] of text.matchAll(
3626
+ /[A-Za-z0-9_]+|\s+|[\x21-\x2f\x3a-\x40\x5b-\x5e\x60\x7b-\x7e]+|\P{ASCII}/gu
3627
+ )) {
3628
+ if (/^\w/u.test(run))
3629
+ tokens += run.length <= 24 && /^[A-Za-z_]*[0-9]{0,3}$/u.test(run) ? Math.ceil(run.length / 4) : run.length;
3630
+ else if (/^\s/u.test(run)) tokens += Math.ceil(run.length / 8);
3631
+ else if (run.codePointAt(0) > 127) tokens += Buffer.byteLength(run) - 1;
3632
+ else tokens += Math.ceil(run.length / 2);
3633
+ }
3634
+ return tokens;
3635
+ }
3636
+ function tooManyRequests() {
3637
+ return new Unplannable(
3638
+ `the diff needs more than ${MAX_REQUESTS} requests to score`
3639
+ );
3640
+ }
3625
3641
  function buildRelevanceBatches(diff, tests, makeRequest, limits) {
3626
3642
  const questions = tests.map(relevanceQuestion);
3627
- const bytes = (request) => Buffer.byteLength(JSON.stringify(request));
3628
- const pair = (text, index) => makeRequest(text, { [`test${index}`]: questions[index] });
3629
- const oversized = [];
3630
- const scored = [];
3631
- for (const index of tests.keys())
3632
- (bytes(pair("", index)) > limits.pair - limits.minDiff ? oversized : scored).push(index);
3633
- const output = [];
3634
- if (!scored.length || !diff) return { batches: output, oversized };
3635
- const fits = (text) => scored.every((index) => bytes(pair(text, index)) <= limits.pair);
3636
- const diffs = fits(diff) ? [diff] : partition(diff, fits);
3637
- const push = (text, indexes, chunkIndex) => {
3638
- output.push({
3643
+ const cost = (value) => estimateTokens(JSON.stringify(value));
3644
+ const overhead = cost(makeRequest("", {}));
3645
+ const question = questions.map(
3646
+ (value, index) => cost({ [`test${index}`]: value })
3647
+ );
3648
+ const { oversized, scored, largest } = sizeTests(question, overhead, limits);
3649
+ if (!scored.length || !diff) return { batches: [], oversized };
3650
+ const fits = (text) => overhead + cost(text) + largest <= limits.pair;
3651
+ try {
3652
+ const diffs = partition(diff, fits);
3653
+ const groups = diffs.flatMap(
3654
+ (text, chunkIndex) => groupQuestions(scored, question, overhead + cost(text), limits).map(
3655
+ (indexes) => ({ text, indexes, chunkIndex })
3656
+ )
3657
+ );
3658
+ if (groups.length > MAX_REQUESTS) throw tooManyRequests();
3659
+ const batches2 = groups.map(({ text, indexes, chunkIndex }) => ({
3639
3660
  request: makeRequest(
3640
3661
  text,
3641
3662
  Object.fromEntries(
@@ -3644,29 +3665,108 @@ function buildRelevanceBatches(diff, tests, makeRequest, limits) {
3644
3665
  ),
3645
3666
  indexes,
3646
3667
  chunkIndex
3647
- });
3648
- if (output.length > 256)
3649
- throw new ProviderError(
3650
- "invalid-input",
3651
- "Relevance selection exceeds the 256-request guard; input was not truncated. Run the full suite."
3652
- );
3668
+ }));
3669
+ return { batches: batches2, oversized };
3670
+ } catch (error2) {
3671
+ if (!(error2 instanceof Unplannable)) throw error2;
3672
+ return { batches: [], oversized, skipped: error2.message };
3673
+ }
3674
+ }
3675
+ function sizeTests(question, overhead, limits) {
3676
+ const tooLarge = (index) => overhead + question[index] > limits.pair - limits.minDiff;
3677
+ const scored = [...question.keys()].filter((index) => !tooLarge(index));
3678
+ return {
3679
+ oversized: [...question.keys()].filter(tooLarge),
3680
+ scored,
3681
+ largest: Math.max(...scored.map((index) => question[index]))
3653
3682
  };
3654
- for (const [chunkIndex, text] of diffs.entries()) {
3655
- let indexes = [];
3656
- for (const index of scored) {
3657
- const candidate = [...indexes, index];
3658
- const request = makeRequest(
3659
- text,
3660
- Object.fromEntries(candidate.map((i) => [`test${i}`, questions[i]]))
3661
- );
3662
- if (candidate.length > limits.questions || bytes(request) > limits.batch) {
3663
- push(text, indexes, chunkIndex);
3664
- indexes = [index];
3665
- } else indexes = candidate;
3683
+ }
3684
+ function groupQuestions(scored, question, base3, limits) {
3685
+ const groups = [];
3686
+ let indexes = [];
3687
+ let total = base3;
3688
+ for (const index of scored) {
3689
+ if (indexes.length + 1 > limits.questions || total + question[index] > limits.batch) {
3690
+ groups.push(indexes);
3691
+ indexes = [];
3692
+ total = base3;
3693
+ }
3694
+ indexes.push(index);
3695
+ total += question[index];
3696
+ }
3697
+ if (indexes.length) groups.push(indexes);
3698
+ return groups;
3699
+ }
3700
+
3701
+ // src/relevance-scoring.ts
3702
+ var RELEVANCE_CONCURRENCY = 8;
3703
+ var MAX_FAILURES = 3;
3704
+ async function scoreRelevancePlan(plan, testCount, ask, options) {
3705
+ const progress = {
3706
+ probabilities: Array.from({ length: testCount }, () => 0),
3707
+ calls: [],
3708
+ unscored: /* @__PURE__ */ new Set(),
3709
+ failures: [],
3710
+ next: 0
3711
+ };
3712
+ const workers = Math.min(RELEVANCE_CONCURRENCY, plan.batches.length);
3713
+ await Promise.all(
3714
+ Array.from(
3715
+ { length: workers },
3716
+ () => work(plan, ask, progress, options?.signal)
3717
+ )
3718
+ );
3719
+ if (progress.fatal) throw progress.fatal.error;
3720
+ options?.signal?.throwIfAborted();
3721
+ return scoresOf(plan, progress);
3722
+ }
3723
+ function scoresOf(plan, progress) {
3724
+ for (const { indexes } of plan.batches.slice(progress.next))
3725
+ for (const index of indexes) progress.unscored.add(index);
3726
+ const failure = progress.failures[0];
3727
+ return {
3728
+ probabilities: progress.probabilities,
3729
+ // Receipts in plan order, whatever order the calls finished in.
3730
+ calls: progress.calls.filter((call2) => call2 !== void 0),
3731
+ chunkCount: new Set(
3732
+ plan.batches.slice(0, progress.next).map((batch) => batch.chunkIndex)
3733
+ ).size,
3734
+ oversized: plan.oversized,
3735
+ unscored: [...progress.unscored].sort((a, b) => a - b),
3736
+ ...plan.skipped ? { skipped: plan.skipped } : {},
3737
+ ...failure === void 0 ? {} : { failure: firstLine(failure) }
3738
+ };
3739
+ }
3740
+ function stopped(progress, signal) {
3741
+ return signal?.aborted === true || progress.fatal !== void 0 || progress.failures.length >= MAX_FAILURES || progress.failures.some(isRunWideProviderError);
3742
+ }
3743
+ async function work(plan, ask, progress, signal) {
3744
+ while (!stopped(progress, signal) && progress.next < plan.batches.length) {
3745
+ const batch = progress.next++;
3746
+ const { request, indexes } = plan.batches[batch];
3747
+ try {
3748
+ const { call: call2, scores } = await ask(request, indexes);
3749
+ progress.calls[batch] = call2;
3750
+ indexes.forEach((index, position) => {
3751
+ progress.probabilities[index] = Math.max(
3752
+ progress.probabilities[index],
3753
+ scores[position]
3754
+ );
3755
+ });
3756
+ } catch (error2) {
3757
+ progress.calls[batch] = unknownCostCall(error2);
3758
+ if (failsSelection(error2, signal)) progress.fatal ??= { error: error2 };
3759
+ else progress.failures.push(error2);
3760
+ for (const index of indexes) progress.unscored.add(index);
3666
3761
  }
3667
- if (indexes.length) push(text, indexes, chunkIndex);
3668
3762
  }
3669
- return { batches: output, oversized };
3763
+ }
3764
+ function failsSelection(error2, signal) {
3765
+ return signal?.aborted === true || !(error2 instanceof ProviderError) || error2.code === "authentication" || error2.code === "configuration";
3766
+ }
3767
+ function firstLine(error2) {
3768
+ const text = error2 instanceof Error ? error2.message : String(error2);
3769
+ return text.split("\n").find((line) => line.trim())?.trim() ?? "unknown error";
3670
3770
  }
3671
3771
 
3672
3772
  // src/vision.ts
@@ -13584,7 +13684,7 @@ async function runScriptTest(file, identity2, runDependencies) {
13584
13684
  message: error2.message,
13585
13685
  fix: error2.fix
13586
13686
  });
13587
- const exclusive = async (source2, work) => {
13687
+ const exclusive = async (source2, work2) => {
13588
13688
  if (finished)
13589
13689
  usage(
13590
13690
  new ScriptUsageError(
@@ -13611,7 +13711,7 @@ async function runScriptTest(file, identity2, runDependencies) {
13611
13711
  source: source2,
13612
13712
  message: "The run was interrupted."
13613
13713
  });
13614
- const running = work();
13714
+ const running = work2();
13615
13715
  inFlight2 = running;
13616
13716
  try {
13617
13717
  return await running;
@@ -13751,9 +13851,9 @@ async function runScriptTest(file, identity2, runDependencies) {
13751
13851
  // `verify` would turn an action into a claim and make it look read-only.
13752
13852
  exclusive(source2, () => sentence(claim2, values, source2, true))
13753
13853
  );
13754
- const track = (work) => {
13854
+ const track = (work2) => {
13755
13855
  const step = new StepPromise(
13756
- (resolve, reject) => work.then(resolve, reject)
13856
+ (resolve, reject) => work2.then(resolve, reject)
13757
13857
  );
13758
13858
  outstanding.add(step);
13759
13859
  Promise.prototype.then.call(
@@ -14141,7 +14241,7 @@ async function recordCodeFailure(page, dependencies, source, error2, group) {
14141
14241
  const id = `${attempt.id}:step:${index}`;
14142
14242
  const message = error2 instanceof Error ? error2.message : typeof error2 === "string" ? error2 : "The test body threw a non-Error value.";
14143
14243
  const expectation = error2 instanceof Error && "matcherResult" in error2 ? "expect_failed" : "code_error";
14144
- const firstLine = message.split("\n").find((line) => line.trim()) ?? message;
14244
+ const firstLine2 = message.split("\n").find((line) => line.trim()) ?? message;
14145
14245
  let evidence = !report.evidenceEnabled ? { status: "omitted", reason: "disabled" } : page.closed ? { status: "unavailable", reason: "page_closed" } : !page.captureFrame ? { status: "unavailable", reason: "capture_unavailable" } : { status: "unavailable", reason: "capture_failed" };
14146
14246
  if (report.evidenceEnabled && page.captureFrame && !page.closed)
14147
14247
  try {
@@ -14159,7 +14259,7 @@ async function recordCodeFailure(page, dependencies, source, error2, group) {
14159
14259
  kind: "verify",
14160
14260
  operation: "code",
14161
14261
  phase: "steps",
14162
- sentence: safeText(firstLine.trim(), privacy, 512),
14262
+ sentence: safeText(firstLine2.trim(), privacy, 512),
14163
14263
  detail: safeText(
14164
14264
  error2 instanceof Error ? `${error2.name} thrown by the test code.` : "",
14165
14265
  privacy,
@@ -16315,12 +16415,12 @@ var StepTimeout = class extends Error {
16315
16415
  this.name = "StepTimeout";
16316
16416
  }
16317
16417
  };
16318
- function withDeadline(work, ms) {
16418
+ function withDeadline(work2, ms) {
16319
16419
  let timer;
16320
16420
  const deadline = new Promise((_, reject) => {
16321
16421
  timer = setTimeout(() => reject(new StepTimeout(ms)), ms);
16322
16422
  });
16323
- return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
16423
+ return Promise.race([work2, deadline]).finally(() => clearTimeout(timer));
16324
16424
  }
16325
16425
  var FORM_KINDS = /* @__PURE__ */ new Set(["form", "search", "auth"]);
16326
16426
  var PAGE_TEXT_LIMIT2 = 3e3;
@@ -17480,6 +17580,7 @@ export {
17480
17580
  ProviderError,
17481
17581
  ProviderGate,
17482
17582
  RATE_LIMIT_BUDGET_MS,
17583
+ RELEVANCE_CONCURRENCY,
17483
17584
  RejectionRouter,
17484
17585
  ResolvedStepTarget,
17485
17586
  ResultAttemptSchema,
@@ -17538,6 +17639,7 @@ export {
17538
17639
  discoverProjectFiles,
17539
17640
  displayPath,
17540
17641
  emitTest,
17642
+ estimateTokens,
17541
17643
  evaluateModelAnswer,
17542
17644
  evaluateVerifyScores,
17543
17645
  executeSentence,
@@ -17621,6 +17723,7 @@ export {
17621
17723
  scanImportBindings,
17622
17724
  scanLocalImports,
17623
17725
  scanScriptSentences,
17726
+ scoreRelevancePlan,
17624
17727
  scriptListingEntries,
17625
17728
  scriptRegistry,
17626
17729
  secret,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sedum-dev/core",
3
- "version": "0.1.0-alpha.22",
3
+ "version": "0.1.0-alpha.23",
4
4
  "repository": "https://github.com/sedum-dev/sedum",
5
5
  "publishConfig": {
6
6
  "access": "public"