@counterfact-labs/cli 0.2.7 → 0.2.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/bundle/client-release.json +1 -1
- package/dist/adapters/analysis-results.js +87 -0
- package/dist/adapters/combined-results.js +27 -0
- package/dist/adapters/entry-files.js +5 -2
- package/dist/adapters/entry-packing.js +161 -0
- package/dist/adapters/entry-selection.js +13 -1
- package/dist/adapters/files.js +110 -5
- package/dist/adapters/git.js +10 -1
- package/dist/adapters/relay-plan.js +5 -7
- package/dist/adapters/release.js +4 -1
- package/dist/adapters/results.js +9 -2
- package/dist/adapters/selection.js +19 -9
- package/dist/adapters/settings.js +37 -6
- package/dist/adapters/source-relay-plan.js +7 -0
- package/dist/analysis-core/analysis/code-agents/skipped-files.js +1 -1
- package/dist/analysis-core/analysis/file-analysis-plan.js +1 -0
- package/dist/analysis-core/analysis/file-dependencies.js +1 -0
- package/dist/analysis-core/analysis/finding-activity-switch.js +1 -0
- package/dist/analysis-core/analysis/finding-identity.js +1 -0
- package/dist/analysis-core/analysis/finding-quality/policy.js +1 -0
- package/dist/analysis-core/analysis/folder-analysis-plan.js +1 -0
- package/dist/analysis-core/analysis/passes/full-file-passes.js +1 -0
- package/dist/analysis-core/analysis/project-architecture.js +1 -0
- package/dist/analysis-core/analysis/schemas.js +1 -1
- package/dist/analysis-core/chunks/2AASSZRO.js +35 -0
- package/dist/analysis-core/chunks/2YREYGOG.js +1 -0
- package/dist/analysis-core/chunks/33HRXJ5Q.js +1 -0
- package/dist/analysis-core/chunks/33IGHOYT.js +1 -0
- package/dist/analysis-core/chunks/4PT5C4IT.js +7 -0
- package/dist/analysis-core/chunks/4RXRAB5S.js +1 -0
- package/dist/analysis-core/chunks/4UDQBDDE.js +1 -0
- package/dist/analysis-core/chunks/{6RWEWBHK.js → 5B5UCWD3.js} +1 -1
- package/dist/analysis-core/chunks/6YCABS5T.js +1 -0
- package/dist/analysis-core/chunks/CQQ4TTXE.js +1 -0
- package/dist/analysis-core/chunks/CTLHKFPH.js +19 -0
- package/dist/analysis-core/chunks/F54DOWKN.js +6 -0
- package/dist/analysis-core/chunks/FRXOQ2M6.js +3 -0
- package/dist/analysis-core/chunks/HCPO6QPU.js +1 -0
- package/dist/analysis-core/chunks/HHFDNY6V.js +14 -0
- package/dist/analysis-core/chunks/{FBTOOUPL.js → HVQJKPQ4.js} +1 -1
- package/dist/analysis-core/chunks/INVTU73D.js +1 -0
- package/dist/analysis-core/chunks/JEWBPIQI.js +1 -0
- package/dist/analysis-core/chunks/JGK37AWN.js +1 -0
- package/dist/analysis-core/chunks/LFYTD7JF.js +1 -0
- package/dist/analysis-core/chunks/LMUXOKIM.js +1 -0
- package/dist/analysis-core/chunks/LOBIDUCA.js +1 -0
- package/dist/analysis-core/chunks/M5YWJY7P.js +1 -0
- package/dist/analysis-core/chunks/MGVIKA74.js +1 -0
- package/dist/analysis-core/chunks/MKYLK6DB.js +1 -0
- package/dist/analysis-core/chunks/MZOKZ3N6.js +1 -0
- package/dist/analysis-core/chunks/NXHVBJL4.js +1 -0
- package/dist/analysis-core/chunks/OKBK3JL3.js +1 -0
- package/dist/analysis-core/chunks/PBHHWFR6.js +1 -0
- package/dist/analysis-core/chunks/Q5WR6B2H.js +2 -0
- package/dist/analysis-core/chunks/QVXARKP7.js +1 -0
- package/dist/analysis-core/chunks/RQTNTIR4.js +1 -0
- package/dist/analysis-core/chunks/{RNTMH4MU.js → S27Y2TP5.js} +1 -1
- package/dist/analysis-core/chunks/SJESFYBA.js +10 -0
- package/dist/analysis-core/chunks/SP6XFHNH.js +1 -0
- package/dist/analysis-core/chunks/VDUFPTDD.js +1 -0
- package/dist/analysis-core/chunks/W24SFYZM.js +67 -0
- package/dist/analysis-core/chunks/YTHF2E2S.js +1 -0
- package/dist/analysis-core/chunks/YWL52FVW.js +2 -0
- package/dist/analysis-core/contracts/analysis-selection.js +1 -1
- package/dist/analysis-core/contracts/analysis-size.js +1 -0
- package/dist/analysis-core/contracts/execution-request.js +1 -0
- package/dist/analysis-core/contracts/intake-finding.js +1 -0
- package/dist/analysis-core/contracts/model-call-identity.js +1 -0
- package/dist/analysis-core/contracts/relay-analysis.js +1 -1
- package/dist/analysis-core/contracts/requests.js +1 -1
- package/dist/analysis-core/conventions/analysis-fit.js +1 -1
- package/dist/analysis-core/conventions/file-admission.js +1 -1
- package/dist/analysis-core/conventions/read-limits.js +1 -0
- package/dist/analysis-core/import/calls/modules.js +1 -1
- package/dist/analysis-core/import/entry-selection.js +1 -0
- package/dist/analysis-core/import/outside-loader-sources.js +1 -1
- package/dist/analysis-core/index.js +3 -3
- package/dist/analysis-core/requests/answer-formats.js +1 -1
- package/dist/analysis-core/requests/local-plan.js +1 -1
- package/dist/analysis-core/requests/planned-limits.js +1 -0
- package/dist/analysis-core/requests/registry.js +1 -1
- package/dist/analysis-core/requests/template-version.js +1 -1
- package/dist/analysis-core/requests/tools.js +1 -1
- package/dist/analysis-core/settings.js +1 -1
- package/dist/analysis-core/stages/engine-entry.js +1 -1
- package/dist/bundle/seal/engine.js +1 -1
- package/dist/cli/analysis-selection.js +47 -5
- package/dist/cli/api.js +1 -1
- package/dist/cli/commands/analyze.js +58 -15
- package/dist/cli/commands/skipped.js +65 -0
- package/dist/cli/context.js +2 -1
- package/dist/cli/finding-display.js +102 -7
- package/dist/cli/finding-settings.js +3 -1
- package/dist/cli/intake-payload.js +26 -2
- package/dist/cli/main.js +21 -7
- package/dist/cli/mcp-failure.js +6 -5
- package/dist/cli/mcp.js +134 -28
- package/dist/cli/relay-check.js +107 -23
- package/dist/cli/relay-failure.js +4 -4
- package/dist/cli/relay-preparation.js +50 -12
- package/dist/cli/result-check.js +31 -12
- package/dist/cli/saved-results.js +10 -0
- package/dist/cli/scope-choices.js +3 -3
- package/dist/cli/sign-in.js +2 -2
- package/dist/cli/skipped-files.js +22 -0
- package/dist/cli/summary.js +15 -1
- package/dist/contract/agent-choice.js +25 -2
- package/dist/contract/cli-api-messages.js +3 -0
- package/dist/contract/cli-refusals.js +31 -5
- package/dist/contract/cli-version.js +1 -1
- package/dist/contract/console-url.js +3 -0
- package/dist/contract/console.js +17 -38
- package/dist/contract/engine.js +1 -1
- package/dist/contract/messages.js +4 -3
- package/dist/contract/project-architecture.js +1 -0
- package/dist/contract/scope-choice.js +31 -11
- package/dist/contract/selection-offer.js +5 -8
- package/dist/gatekeeper/cli-api.js +70 -4
- package/dist/gatekeeper/console.js +19 -3
- package/dist/gatekeeper/model.js +5 -23
- package/dist/gatekeeper/trust/policy.js +2 -1
- package/package.json +4 -2
- package/dist/analysis-core/analysis/source-notes/types.js +0 -1
- package/dist/analysis-core/chunks/2PSNOSJ2.js +0 -1
- package/dist/analysis-core/chunks/2PZF54KH.js +0 -10
- package/dist/analysis-core/chunks/6B2HILSY.js +0 -1
- package/dist/analysis-core/chunks/6U2IR4XB.js +0 -1
- package/dist/analysis-core/chunks/7NEWZ74F.js +0 -1
- package/dist/analysis-core/chunks/CGCJN73D.js +0 -14
- package/dist/analysis-core/chunks/CWYVUGG4.js +0 -1
- package/dist/analysis-core/chunks/FSLWD2PE.js +0 -1
- package/dist/analysis-core/chunks/GOQVKWP3.js +0 -32
- package/dist/analysis-core/chunks/IHAVDX4L.js +0 -66
- package/dist/analysis-core/chunks/IVULXWQN.js +0 -21
- package/dist/analysis-core/chunks/K2GNDX3W.js +0 -1
- package/dist/analysis-core/chunks/K5FUABWW.js +0 -1
- package/dist/analysis-core/chunks/KGQYR62R.js +0 -7
- package/dist/analysis-core/chunks/KWECQJ6X.js +0 -1
- package/dist/analysis-core/chunks/PY5M22CL.js +0 -1
- package/dist/analysis-core/chunks/PYKAERZZ.js +0 -1
- package/dist/analysis-core/chunks/SKVEBOGA.js +0 -1
- package/dist/analysis-core/chunks/SLJ6CW7W.js +0 -1
- package/dist/analysis-core/chunks/UEORNVQB.js +0 -1
- package/dist/analysis-core/chunks/WYLIV2P2.js +0 -1
- package/dist/analysis-core/data/finding-types.js +0 -1
|
@@ -4,16 +4,28 @@ import { refusedImportSchema } from "../analysis-core/contracts/module-resolutio
|
|
|
4
4
|
import { selectionPathSchema, snapshotIdSchema } from "../analysis-core/contracts/selection-paths.js";
|
|
5
5
|
import { FileReadRefusal } from "../analysis-core/conventions/file-admission.js";
|
|
6
6
|
export { analysisScopeSchema } from "../analysis-core/contracts/analysis-selection.js";
|
|
7
|
-
//
|
|
7
|
+
// Coverage wording stays here so the CLI and MCP cannot make different promises about coverage.
|
|
8
8
|
export const CHOOSE_SCOPE_MESSAGE = "This analysis is too large to run at once. Choose what Counterfact should read.";
|
|
9
|
+
export const MULTI_ENTRY_CHOOSE_SCOPE_MESSAGE = "These agent files are too many or too large for one analysis. Choose what Counterfact should read.";
|
|
9
10
|
export const ENTRY_ONLY_LABEL = "Only the selected file";
|
|
10
11
|
export const ENTRY_ONLY_DESCRIPTION = "Read {entry}. Leave its imports out of this analysis.";
|
|
11
12
|
export const SELECTED_IMPORTS_LABEL = "The selected file and some imports";
|
|
12
13
|
export const SELECTED_IMPORTS_DESCRIPTION = "Read {entry} and the imports listed below. Leave the other imports out of this analysis.";
|
|
13
14
|
export const ENTRY_IMPORTS_LABEL = "One agent file and its imports";
|
|
14
15
|
export const ENTRY_IMPORTS_DESCRIPTION = "Read {entry} and its project imports inside the launch folder.";
|
|
16
|
+
export const ENTRY_GROUP_LABEL = "Several agent files and their imports";
|
|
17
|
+
export const ENTRY_GROUP_DESCRIPTION = "Read the agent files and their project imports listed below. Leave the other selected files out of this analysis.";
|
|
15
18
|
export const SINGLE_FILE_TOO_LARGE_MESSAGE = "This file is too large to analyze on its own. Choose another agent file or split this file into smaller files.";
|
|
16
19
|
export const INVALID_SELECTION_MESSAGE = "Choose an agent file or folder inside the launch folder.";
|
|
20
|
+
export const ANALYSIS_TOO_LARGE_MESSAGE = "This analysis is too large to run at once. Choose one agent file or a smaller folder, such as one agent's folder.";
|
|
21
|
+
/** Recovery may offer a file only when this run accepts file selections. */
|
|
22
|
+
export function selectionRefusalMessage(message, fileMode) {
|
|
23
|
+
if (!fileMode && message === INVALID_SELECTION_MESSAGE)
|
|
24
|
+
return "Choose a folder inside this project, or start Claude Code or Codex in the folder you want to analyze.";
|
|
25
|
+
if (!fileMode && message === ANALYSIS_TOO_LARGE_MESSAGE)
|
|
26
|
+
return "This analysis is too large to run at once. Choose a smaller folder, such as one agent's folder.";
|
|
27
|
+
return message;
|
|
28
|
+
}
|
|
17
29
|
export const INVALID_SCOPE_MESSAGE = "This scope could not be used. Choose one of the returned scopes and try again.";
|
|
18
30
|
export const STALE_SCOPE_MESSAGE = "The selected files changed. Run the analysis again to get updated scope choices.";
|
|
19
31
|
export const SCOPE_PROPOSAL_CONFLICT_MESSAGE = "The selected scope and proposed files do not match. Keep the selected file and only its listed imports.";
|
|
@@ -27,6 +39,7 @@ export function isSelectionRefusal(error, fileMode) {
|
|
|
27
39
|
}
|
|
28
40
|
export const INCLUDED_FILES_CAPTION = "Included files:";
|
|
29
41
|
export const OMITTED_IMPORTS_CAPTION = "Imports left out:";
|
|
42
|
+
export const OMITTED_FILES_CAPTION = "Files left out:";
|
|
30
43
|
export const SCOPE_CHOICE_INSTRUCTION = "Choose a scope, then run the analysis again with that scope.";
|
|
31
44
|
export const INCOMPLETE_IMPORTS_MESSAGE = "Some imports could not be resolved. This analysis covers only the files listed below.";
|
|
32
45
|
export const IMPORT_DISCOVERY_LIMIT_MESSAGE = "Counterfact reached the import discovery limit. The list of imports is incomplete.";
|
|
@@ -43,22 +56,28 @@ export const SELECTION_COVERAGE_DESCRIPTION = "This analysis covers {entry} and
|
|
|
43
56
|
export const SCOPE_RETRY_TEMPLATE = "Run again: counterfact-labs analyze {quoted-entry} --scope {quoted-scope-file}";
|
|
44
57
|
export const FILE_SCOPE_PUBLIC_USAGE = "Usage: counterfact-labs analyze [path] [--proposal <json-file>] [--scope <json-file>]\n counterfact-labs finding <id>\n counterfact-labs balance | login | logout | mcp\n";
|
|
45
58
|
export const FILE_SCOPE_SOURCE_USAGE = "Usage: npx tsx cli/check.ts <path> [--output <directory>] [--scope <json-file>]\n";
|
|
59
|
+
export function scopeChoiceWording(choice, fits) {
|
|
60
|
+
const group = (choice.scope.entries ?? []).filter(entry => choice.includes.includes(entry)).length > 1;
|
|
61
|
+
const entryOnly = choice.scope.imports === "none" || Array.isArray(choice.scope.imports) && choice.scope.imports.length === 0;
|
|
62
|
+
const fullImports = choice.scope.imports === "all" || choice.coverage === "entry-imports";
|
|
63
|
+
return {
|
|
64
|
+
label: group ? ENTRY_GROUP_LABEL : entryOnly ? ENTRY_ONLY_LABEL : fullImports ? ENTRY_IMPORTS_LABEL : SELECTED_IMPORTS_LABEL,
|
|
65
|
+
description: entryOnly && fits === false ? SINGLE_FILE_TOO_LARGE_MESSAGE
|
|
66
|
+
: (group ? ENTRY_GROUP_DESCRIPTION : entryOnly ? ENTRY_ONLY_DESCRIPTION : fullImports ? ENTRY_IMPORTS_DESCRIPTION : SELECTED_IMPORTS_DESCRIPTION)
|
|
67
|
+
.replace("{entry}", () => choice.scope.entry),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
46
70
|
export const scopeChoiceSchema = provenScopeChoiceSchema.safeExtend({
|
|
47
|
-
label: z.enum([ENTRY_ONLY_LABEL, SELECTED_IMPORTS_LABEL, ENTRY_IMPORTS_LABEL]),
|
|
71
|
+
label: z.enum([ENTRY_ONLY_LABEL, SELECTED_IMPORTS_LABEL, ENTRY_IMPORTS_LABEL, ENTRY_GROUP_LABEL]),
|
|
48
72
|
description: z.string().min(1).max(8192),
|
|
49
|
-
//
|
|
73
|
+
// Local measurement can prove a group fits; ordinary run admission checks it again.
|
|
50
74
|
fits: z.union([z.boolean(), z.literal("unknown")]),
|
|
51
75
|
}).refine(choice => {
|
|
52
|
-
const
|
|
53
|
-
const entryOnly = imports === "none" || Array.isArray(imports) && imports.length === 0;
|
|
54
|
-
const label = entryOnly ? ENTRY_ONLY_LABEL : imports === "all" ? ENTRY_IMPORTS_LABEL : SELECTED_IMPORTS_LABEL;
|
|
55
|
-
const description = entryOnly && choice.fits === false ? SINGLE_FILE_TOO_LARGE_MESSAGE
|
|
56
|
-
: (entryOnly ? ENTRY_ONLY_DESCRIPTION : imports === "all" ? ENTRY_IMPORTS_DESCRIPTION : SELECTED_IMPORTS_DESCRIPTION)
|
|
57
|
-
.replace("{entry}", () => choice.scope.entry);
|
|
76
|
+
const { label, description } = scopeChoiceWording(choice, choice.fits);
|
|
58
77
|
return choice.label === label && choice.description === description;
|
|
59
78
|
});
|
|
60
79
|
export const chooseScopeResultSchema = z.strictObject({
|
|
61
|
-
kind: z.literal("choose_scope"), text: z.
|
|
80
|
+
kind: z.literal("choose_scope"), text: z.enum([CHOOSE_SCOPE_MESSAGE, MULTI_ENTRY_CHOOSE_SCOPE_MESSAGE]), snapshot: snapshotIdSchema,
|
|
62
81
|
entry: selectionPathSchema.nullable(), coverageComplete: z.boolean(),
|
|
63
82
|
frontierCount: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
64
83
|
choices: z.array(scopeChoiceSchema).min(1).max(ANALYSIS_SELECTION_LIMITS.choices),
|
|
@@ -72,7 +91,8 @@ export const chooseScopeResultSchema = z.strictObject({
|
|
|
72
91
|
&& value.choices.every(choice => choice.scope.snapshot === value.snapshot && (value.entry === null || choice.scope.entry === value.entry
|
|
73
92
|
&& (choice.scope.imports !== "all" || choice.omitted.length === 0))));
|
|
74
93
|
export const chooseScopeMcpResultSchema = z.strictObject({
|
|
75
|
-
content: z.tuple([z.strictObject({ type: z.literal("text"), text: z.string()
|
|
94
|
+
content: z.tuple([z.strictObject({ type: z.literal("text"), text: z.string()
|
|
95
|
+
.refine(text => [CHOOSE_SCOPE_MESSAGE, MULTI_ENTRY_CHOOSE_SCOPE_MESSAGE].some(message => text.startsWith(message))) })]),
|
|
76
96
|
isError: z.literal(false), structuredContent: chooseScopeResultSchema.safeExtend({ exitCode: z.literal(0) }),
|
|
77
97
|
});
|
|
78
98
|
export const SCOPE_CHOICE_EXIT_CODE = 3;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CHOOSE_SCOPE_MESSAGE,
|
|
1
|
+
import { CHOOSE_SCOPE_MESSAGE, MULTI_ENTRY_CHOOSE_SCOPE_MESSAGE, scopeChoiceWording, SINGLE_FILE_TOO_LARGE_MESSAGE } from "./scope-choice.js";
|
|
2
2
|
export class ScopeChoiceError extends Error {
|
|
3
3
|
choice;
|
|
4
4
|
constructor(choice) {
|
|
@@ -20,13 +20,10 @@ export function selectionScopeChoices(membership, options = {}) {
|
|
|
20
20
|
const knownOversized = entryOnly && oversized.has(choice.scope.entry);
|
|
21
21
|
const identical = choice.includes.length === current.size && choice.includes.every(path => current.has(path));
|
|
22
22
|
const key = JSON.stringify([...choice.includes].sort());
|
|
23
|
-
if (seen.has(key) || choice.includes.some(path => !current.has(path)) || identical && !knownOversized)
|
|
23
|
+
if (seen.has(key) || choice.includes.some(path => !current.has(path)) || identical && !knownOversized && !options.allowCurrent)
|
|
24
24
|
return [];
|
|
25
25
|
seen.add(key);
|
|
26
|
-
const label
|
|
27
|
-
const description = knownOversized ? SINGLE_FILE_TOO_LARGE_MESSAGE
|
|
28
|
-
: (entryOnly ? ENTRY_ONLY_DESCRIPTION : choice.scope.imports === "all" ? ENTRY_IMPORTS_DESCRIPTION : SELECTED_IMPORTS_DESCRIPTION)
|
|
29
|
-
.replace("{entry}", () => choice.scope.entry);
|
|
26
|
+
const { label, description } = scopeChoiceWording(choice, knownOversized ? false : "unknown");
|
|
30
27
|
return [{ ...choice, label, description, fits: knownOversized ? false : "unknown" }];
|
|
31
28
|
});
|
|
32
29
|
if (!choices.length)
|
|
@@ -37,7 +34,7 @@ export function selectionScopeChoices(membership, options = {}) {
|
|
|
37
34
|
const importedBy = [...new Set(membership.edges.filter(edge => edge.path === file.path).map(edge => edge.from))];
|
|
38
35
|
return importedBy.length ? [{ path: file.path, role: "imported-helper", importedBy }] : [];
|
|
39
36
|
});
|
|
40
|
-
return { kind: "choose_scope", text: CHOOSE_SCOPE_MESSAGE, snapshot: membership.snapshot,
|
|
41
|
-
entry: membership.kind === "file" ? membership.entry : null, coverageComplete: membership.completeness.complete,
|
|
37
|
+
return { kind: "choose_scope", text: membership.kind === "file" && membership.entries ? MULTI_ENTRY_CHOOSE_SCOPE_MESSAGE : CHOOSE_SCOPE_MESSAGE, snapshot: membership.snapshot,
|
|
38
|
+
entry: membership.kind === "file" && !membership.entries ? membership.entry : null, coverageComplete: membership.completeness.complete,
|
|
42
39
|
frontierCount: membership.completeness.frontierCount, choices, imports, refusedEdges: membership.refusedEdges };
|
|
43
40
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { cliRefusals, refusalExitCode } from "../contract/cli-refusals.js";
|
|
1
|
+
import { cliRefusals, localFailure, refusalExitCode } from "../contract/cli-refusals.js";
|
|
2
2
|
import { CLI_VERSION } from "../contract/cli-version.js";
|
|
3
3
|
import { consoleSchemeAllowed } from "../contract/console-url.js";
|
|
4
4
|
import { cliApiMessages } from "../contract/cli-api-messages.js";
|
|
5
|
+
import { selectionRefusalMessage } from "../contract/scope-choice.js";
|
|
5
6
|
import { emailSignInMessages } from "../contract/email-sign-in-messages.js";
|
|
6
7
|
import { CLI_BODY_LIMIT } from "../cli/api-types.js";
|
|
7
8
|
import { findingNumberParamsSchema } from "../contract/findings.js";
|
|
@@ -20,6 +21,9 @@ export class ApiError extends Error {
|
|
|
20
21
|
this.reason = reason;
|
|
21
22
|
}
|
|
22
23
|
}
|
|
24
|
+
export class SavedSignInError extends ApiError {
|
|
25
|
+
constructor() { super(0, "invalid_request", cliApiMessages.unreadable_sign_in_terminal, 0, "invalid_request"); }
|
|
26
|
+
}
|
|
23
27
|
const emailRoutes = {
|
|
24
28
|
"email/start": { fields: ["email"], successStatus: 202, failures: { invalid_email: 400 }, jsonCooldown: true },
|
|
25
29
|
"email/verify": { fields: ["email", "code", "clientName"], successStatus: 200,
|
|
@@ -27,6 +31,49 @@ const emailRoutes = {
|
|
|
27
31
|
};
|
|
28
32
|
// Longer cooldowns keep the server's delay but use the sentence without a duration.
|
|
29
33
|
const MAX_DISPLAYED_EMAIL_COOLDOWN_MS = 24 * 60 * 60 * 1000;
|
|
34
|
+
const transportErrorCodes = new Set([
|
|
35
|
+
"ECONNREFUSED", "ECONNRESET", "ECONNABORTED", "EPIPE", "ENETUNREACH", "ENETDOWN", "EHOSTUNREACH", "EHOSTDOWN",
|
|
36
|
+
"ENETRESET", "EADDRNOTAVAIL", "EPROTO", "ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "ETIMEDOUT", "ETIMEOUT", "ESERVFAIL", "ENODATA",
|
|
37
|
+
// Certificate verification can fail without an SSL or TLS prefix.
|
|
38
|
+
"UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_CRL", "UNABLE_TO_DECRYPT_CERT_SIGNATURE",
|
|
39
|
+
"UNABLE_TO_DECRYPT_CRL_SIGNATURE", "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY", "CERT_SIGNATURE_FAILURE",
|
|
40
|
+
"CRL_SIGNATURE_FAILURE", "CERT_NOT_YET_VALID", "CERT_HAS_EXPIRED", "CRL_NOT_YET_VALID", "CRL_HAS_EXPIRED",
|
|
41
|
+
"ERROR_IN_CERT_NOT_BEFORE_FIELD", "ERROR_IN_CERT_NOT_AFTER_FIELD", "ERROR_IN_CRL_LAST_UPDATE_FIELD",
|
|
42
|
+
"ERROR_IN_CRL_NEXT_UPDATE_FIELD", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN",
|
|
43
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "CERT_CHAIN_TOO_LONG", "CERT_REVOKED",
|
|
44
|
+
"NO_ISSUER_PUBLIC_KEY", "PATH_LENGTH_EXCEEDED", "INVALID_PURPOSE", "CERT_UNTRUSTED", "CERT_REJECTED",
|
|
45
|
+
"SUBJECT_ISSUER_MISMATCH", "AKID_SKID_MISMATCH", "AKID_ISSUER_SERIAL_MISMATCH", "KEYUSAGE_NO_CERTSIGN",
|
|
46
|
+
"UNABLE_TO_GET_CRL_ISSUER", "UNHANDLED_CRITICAL_EXTENSION", "KEYUSAGE_NO_CRL_SIGN",
|
|
47
|
+
"UNHANDLED_CRITICAL_CRL_EXTENSION", "INVALID_NON_CA", "PROXY_PATH_LENGTH_EXCEEDED",
|
|
48
|
+
"KEYUSAGE_NO_DIGITAL_SIGNATURE", "PROXY_CERTIFICATES_NOT_ALLOWED", "INVALID_EXTENSION",
|
|
49
|
+
"INVALID_POLICY_EXTENSION", "NO_EXPLICIT_POLICY", "DIFFERENT_CRL_SCOPE", "UNSUPPORTED_EXTENSION_FEATURE",
|
|
50
|
+
"UNNESTED_RESOURCE", "PERMITTED_VIOLATION", "EXCLUDED_VIOLATION", "SUBTREE_MINMAX", "APPLICATION_VERIFICATION",
|
|
51
|
+
"UNSUPPORTED_CONSTRAINT_TYPE", "UNSUPPORTED_CONSTRAINT_SYNTAX", "UNSUPPORTED_NAME_SYNTAX",
|
|
52
|
+
"CRL_PATH_VALIDATION_ERROR", "PATH_LOOP", "SUITE_B_INVALID_VERSION", "SUITE_B_INVALID_ALGORITHM",
|
|
53
|
+
"SUITE_B_INVALID_CURVE", "SUITE_B_INVALID_SIGNATURE_ALGORITHM", "SUITE_B_LOS_NOT_ALLOWED",
|
|
54
|
+
"SUITE_B_CANNOT_SIGN_P_384_WITH_P_256", "HOSTNAME_MISMATCH", "EMAIL_MISMATCH", "IP_ADDRESS_MISMATCH",
|
|
55
|
+
"DANE_NO_MATCH", "EE_KEY_TOO_SMALL", "CA_KEY_TOO_SMALL", "CA_MD_TOO_WEAK", "NO_VALID_SCTS",
|
|
56
|
+
"PROXY_SUBJECT_NAME_VIOLATION", "OCSP_VERIFY_NEEDED", "OCSP_VERIFY_FAILED", "OCSP_CERT_UNKNOWN",
|
|
57
|
+
"UNSUPPORTED_SIGNATURE_ALGORITHM", "SIGNATURE_ALGORITHM_MISMATCH", "SIGNATURE_ALGORITHM_INCONSISTENCY",
|
|
58
|
+
"INVALID_CA", "PATHLEN_INVALID_FOR_NON_CA", "PATHLEN_WITHOUT_KU_KEY_CERT_SIGN",
|
|
59
|
+
"KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA", "ISSUER_NAME_EMPTY", "SUBJECT_NAME_EMPTY",
|
|
60
|
+
"MISSING_AUTHORITY_KEY_IDENTIFIER", "MISSING_SUBJECT_KEY_IDENTIFIER", "EMPTY_SUBJECT_ALT_NAME",
|
|
61
|
+
"EMPTY_SUBJECT_SAN_NOT_CRITICAL", "CA_BCONS_NOT_CRITICAL", "AUTHORITY_KEY_IDENTIFIER_CRITICAL",
|
|
62
|
+
"SUBJECT_KEY_IDENTIFIER_CRITICAL", "CA_CERT_MISSING_KEY_USAGE", "EXTENSIONS_REQUIRE_VERSION_3",
|
|
63
|
+
"EC_KEY_EXPLICIT_PARAMS", "RPK_UNTRUSTED",
|
|
64
|
+
]);
|
|
65
|
+
function transportFailed(error, depth = 0) {
|
|
66
|
+
if (!(error instanceof Error) || depth > 4)
|
|
67
|
+
return false;
|
|
68
|
+
if ("code" in error && typeof error.code === "string") {
|
|
69
|
+
if (error.code === "ERR_INVALID_URL" || error.code === "UND_ERR_INVALID_ARG")
|
|
70
|
+
return false;
|
|
71
|
+
if (transportErrorCodes.has(error.code) || /^(?:UND_ERR_|ERR_SSL_|ERR_TLS_|EAI_|CERT_|CRL_)/.test(error.code))
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
return transportFailed(error.cause, depth + 1)
|
|
75
|
+
|| error instanceof AggregateError && error.errors.some((cause) => transportFailed(cause, depth + 1));
|
|
76
|
+
}
|
|
30
77
|
function retryAfterMs(value, rejectNegativeSeconds = false) {
|
|
31
78
|
if (!value)
|
|
32
79
|
return undefined;
|
|
@@ -97,11 +144,13 @@ export class ApiClient {
|
|
|
97
144
|
token;
|
|
98
145
|
fetcher;
|
|
99
146
|
signal;
|
|
147
|
+
classifyTransportErrors;
|
|
100
148
|
baseUrl;
|
|
101
|
-
constructor(baseUrl, token, fetcher = fetch, signal) {
|
|
149
|
+
constructor(baseUrl, token, fetcher = fetch, signal, classifyTransportErrors = true) {
|
|
102
150
|
this.token = token;
|
|
103
151
|
this.fetcher = fetcher;
|
|
104
152
|
this.signal = signal;
|
|
153
|
+
this.classifyTransportErrors = classifyTransportErrors;
|
|
105
154
|
let url;
|
|
106
155
|
try {
|
|
107
156
|
url = new URL(baseUrl);
|
|
@@ -132,6 +181,15 @@ export class ApiClient {
|
|
|
132
181
|
}
|
|
133
182
|
if (body !== undefined)
|
|
134
183
|
headers["content-type"] = "application/json";
|
|
184
|
+
// Fetch also validates headers locally. Keep that failure outside the transport catch.
|
|
185
|
+
if (this.classifyTransportErrors) {
|
|
186
|
+
try {
|
|
187
|
+
new Headers(headers);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
throw new SavedSignInError();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
135
193
|
const serialized = body === undefined ? undefined : JSON.stringify(safeBody);
|
|
136
194
|
if (serialized !== undefined && Buffer.byteLength(serialized, "utf8") > CLI_BODY_LIMIT) {
|
|
137
195
|
throw new ApiError(413, "body_too_large", cliRefusals.body_too_large);
|
|
@@ -151,8 +209,14 @@ export class ApiClient {
|
|
|
151
209
|
redirect: "error", signal: controller.signal,
|
|
152
210
|
});
|
|
153
211
|
}
|
|
154
|
-
catch {
|
|
212
|
+
catch (error) {
|
|
155
213
|
throwIfAborted();
|
|
214
|
+
// Fetch can refuse locally before creating a request, so rejection alone is not transport evidence.
|
|
215
|
+
if (this.classifyTransportErrors && !controller.signal.aborted && !transportFailed(error)) {
|
|
216
|
+
if (localFailure(error))
|
|
217
|
+
throw error;
|
|
218
|
+
throw new ApiError(0, "request_failed", cliApiMessages.request_failed);
|
|
219
|
+
}
|
|
156
220
|
throw new ApiError(0, "unreachable", cliApiMessages.unreachable, 0, "console_unreachable");
|
|
157
221
|
}
|
|
158
222
|
throwIfAborted();
|
|
@@ -190,4 +254,6 @@ export class ApiClient {
|
|
|
190
254
|
}
|
|
191
255
|
}
|
|
192
256
|
export function errorCode(error) { return refusalExitCode(error instanceof ApiError ? error.code : undefined); }
|
|
193
|
-
export function errorText(error
|
|
257
|
+
export function errorText(error, fileMode = true) {
|
|
258
|
+
return selectionRefusalMessage(localFailure(error)?.message ?? (error instanceof Error ? error.message : cliApiMessages.request_failed), fileMode);
|
|
259
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { consoleSchemeAllowed } from "../contract/console-url.js";
|
|
2
2
|
import { request as httpRequest } from "node:http";
|
|
3
3
|
import { request as httpsRequest } from "node:https";
|
|
4
|
+
import { z } from "zod";
|
|
4
5
|
import { CLI_VERSION } from "../contract/cli-version.js";
|
|
5
6
|
import { cliRefusals, NOT_ALLOWED_MESSAGE, SIGN_IN_EXPIRED_MESSAGE, CHECK_CONFLICT_MESSAGE, UNSAVED_RESULTS_MESSAGE, FINISH_FAILURE_MESSAGE, RESERVATION_EXPIRED_MESSAGE, RESULTS_TOO_LARGE_MESSAGE, START_FAILURE_MESSAGE } from "../contract/cli-refusals.js";
|
|
6
7
|
import { cliRelayReservationRequestSchema, consoleCreatedSchema, consoleIntakeResultSchema, consoleReservationSchema, consoleStatusSchema, LOCAL_FINDINGS_BODY_LIMIT, localFindingsPayloadSchema, LOCAL_START_BODY_LIMIT, LOCAL_START_EXECUTION_HEADER, localStartRequestSchema, localStartResponseSchema, serializeLocalStartMetadata } from "../contract/console.js";
|
|
@@ -49,6 +50,14 @@ export class ConsoleError extends Error {
|
|
|
49
50
|
}
|
|
50
51
|
}
|
|
51
52
|
export const isConsoleToken = (token) => /^[\x21-\x7e]{1,4096}$/.test(token);
|
|
53
|
+
/** Strict older consoles accept optional metadata only after explicitly advertising it. */
|
|
54
|
+
export function consoleCapabilities(mode) {
|
|
55
|
+
return {
|
|
56
|
+
skippedFiles: "skippedFiles" in mode && mode.skippedFiles === true,
|
|
57
|
+
findingActivity: "findingActivity" in mode && mode.findingActivity === true,
|
|
58
|
+
architecture: "architecture" in mode && mode.architecture === true,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
52
61
|
/** Only this client may send repository metadata, content-free lifecycle or findings-only intake payloads to the console. */
|
|
53
62
|
export class ConsoleClient {
|
|
54
63
|
#url;
|
|
@@ -84,6 +93,13 @@ export class ConsoleClient {
|
|
|
84
93
|
}
|
|
85
94
|
return this.#send("/api/cli/checks", input, localStartRequestSchema, localStartResponseSchema, LOCAL_START_BODY_LIMIT, { statuses: [201], headers: { ...headers, [LOCAL_START_EXECUTION_HEADER.name]: LOCAL_START_EXECUTION_HEADER.value }, context: "start" });
|
|
86
95
|
}
|
|
96
|
+
async capabilities() {
|
|
97
|
+
const mode = await this.#send("/api/cli/checks/mode", {}, z.object({}), z.object({ skippedFiles: z.boolean().optional() }).passthrough(), 1024, { method: "GET", context: "start" });
|
|
98
|
+
return consoleCapabilities(mode);
|
|
99
|
+
}
|
|
100
|
+
async supportsSkippedFiles() {
|
|
101
|
+
return (await this.capabilities()).skippedFiles;
|
|
102
|
+
}
|
|
87
103
|
create(input) {
|
|
88
104
|
return this.#lifecycle({ ...input, action: "create" }, consoleCreatedSchema);
|
|
89
105
|
}
|
|
@@ -140,9 +156,9 @@ export class ConsoleClient {
|
|
|
140
156
|
};
|
|
141
157
|
const destination = new URL(path, this.#url);
|
|
142
158
|
const request = (destination.protocol === "https:" ? httpsRequest : httpRequest)(destination, {
|
|
143
|
-
method: "POST", agent: false, rejectUnauthorized: true, maxHeaderSize: 16 * 1024,
|
|
159
|
+
method: options.method ?? "POST", agent: false, rejectUnauthorized: true, maxHeaderSize: 16 * 1024,
|
|
144
160
|
headers: { "x-counterfact-cli-version": CLI_VERSION, authorization: `Bearer ${this.#token}`, "content-type": "application/json", accept: "application/json",
|
|
145
|
-
"content-length": body.length, "accept-encoding": "identity",
|
|
161
|
+
"content-length": options.method === "GET" ? 0 : body.length, "accept-encoding": "identity",
|
|
146
162
|
...options.headers },
|
|
147
163
|
}, response => {
|
|
148
164
|
const status = response.statusCode ?? 0;
|
|
@@ -194,7 +210,7 @@ export class ConsoleClient {
|
|
|
194
210
|
// Use one wall-clock deadline: an idle timeout alone lets a trickling response run forever.
|
|
195
211
|
const timer = setTimeout(() => { finish(interrupted()); request.destroy(); }, this.#timeoutMs);
|
|
196
212
|
request.on("error", () => finish(interrupted()));
|
|
197
|
-
request.end(body);
|
|
213
|
+
request.end(options.method === "GET" ? undefined : body);
|
|
198
214
|
}).catch(error => { throw new ConsoleError(error instanceof ConsoleError ? error.code : "unavailable", options.context, error instanceof ConsoleError ? { localReason: error.localReason, responseCode: error.responseCode, httpStatus: error.httpStatus } : {}); });
|
|
199
215
|
}
|
|
200
216
|
}
|
package/dist/gatekeeper/model.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { unredactedAnswer } from "../contract/public-report.js";
|
|
3
|
-
import { executionRequest } from "../analysis-core/contracts/
|
|
3
|
+
import { executionRequest } from "../analysis-core/contracts/execution-request.js";
|
|
4
|
+
import { createModelCallIdentities } from "../analysis-core/contracts/model-call-identity.js";
|
|
4
5
|
export class ModelConfigurationError extends Error {
|
|
5
6
|
name = "ModelConfigurationError";
|
|
6
7
|
}
|
|
@@ -8,9 +9,7 @@ export function relayModel(options) {
|
|
|
8
9
|
const { client, bundleVersion, reservationId, reservationToken, onUsage } = options;
|
|
9
10
|
if (!bundleVersion.trim() || !reservationId.trim() || !reservationToken?.trim() || reservationToken.length > 256)
|
|
10
11
|
throw new ModelConfigurationError("Invalid relay configuration");
|
|
11
|
-
const identities =
|
|
12
|
-
const originals = new WeakMap();
|
|
13
|
-
let callCount = 0;
|
|
12
|
+
const identities = createModelCallIdentities({ mintId: options.mintId ?? randomUUID });
|
|
14
13
|
function view(retry) {
|
|
15
14
|
return {
|
|
16
15
|
settleStartedOnError: true,
|
|
@@ -29,24 +28,7 @@ export function relayModel(options) {
|
|
|
29
28
|
throw new Error("Invalid relay request data");
|
|
30
29
|
}
|
|
31
30
|
execution.onSend?.(inputBytes);
|
|
32
|
-
const
|
|
33
|
-
const matching = identities.get(key);
|
|
34
|
-
let identity;
|
|
35
|
-
if (retry > 0) {
|
|
36
|
-
const original = originals.get(request);
|
|
37
|
-
const candidates = original ? [...original].filter(id => matching?.has(id)) : [...matching ?? []];
|
|
38
|
-
if (candidates.length !== 1)
|
|
39
|
-
throw new Error("Ambiguous relay call identity");
|
|
40
|
-
identity = candidates[0];
|
|
41
|
-
}
|
|
42
|
-
else {
|
|
43
|
-
if (callCount >= 4096)
|
|
44
|
-
throw new Error("Relay call limit reached");
|
|
45
|
-
identity = randomUUID();
|
|
46
|
-
callCount++;
|
|
47
|
-
identities.set(key, new Set([...matching ?? [], identity]));
|
|
48
|
-
originals.set(request, new Set([...originals.get(request) ?? [], identity]));
|
|
49
|
-
}
|
|
31
|
+
const identity = identities.resolve({ snapshot, originalKey: request, retry });
|
|
50
32
|
let reply;
|
|
51
33
|
try {
|
|
52
34
|
const signals = [options.signal, execution.signal].filter((signal) => !!signal);
|
|
@@ -29,9 +29,10 @@ export const workloadPolicy = z.object({
|
|
|
29
29
|
.refine(subject => workloadZones.some(zone => subject.includes(`/zones/${zone}/`)))),
|
|
30
30
|
imageSigningKeyIds: values(z.string().regex(/^[0-9a-f]{64}$/)),
|
|
31
31
|
}).strict();
|
|
32
|
+
export const engineRelease = z.strictObject({ imageDigest: z.string().regex(/^sha256:[0-9a-f]{64}$/), engine: enginePin });
|
|
32
33
|
const productionTrust = workloadPolicy.extend({
|
|
33
34
|
imageDigests: z.array(z.string().regex(/^sha256:[0-9a-f]{64}$/)).min(1),
|
|
34
|
-
engineReleases: z.array(
|
|
35
|
+
engineReleases: z.array(engineRelease).min(1).optional(),
|
|
35
36
|
}).refine(value => !value.engineReleases || value.engineReleases.every(release => value.imageDigests.includes(release.imageDigest)) &&
|
|
36
37
|
new Set(value.engineReleases.map(release => release.imageDigest)).size === value.engineReleases.length, "Engine release image differs");
|
|
37
38
|
export function validateWorkloadPolicy(value) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@counterfact-labs/cli",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"homepage": "https://counterfactlabs.com",
|
|
5
5
|
"relaySource": "https://github.com/counterfact-labs/sealed-relay",
|
|
6
6
|
"type": "module",
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
"build:core": "npm run build --workspace @counterfact-labs/analysis-core",
|
|
25
25
|
"build:setup-pings": "npm run build --workspace @counterfact-labs/setup-pings",
|
|
26
26
|
"pretest": "npm run build:core && npm run build:setup-pings",
|
|
27
|
+
"pretest:integration": "npm run build:core && npm run build:setup-pings",
|
|
28
|
+
"test:integration": "tsx --import ./tests/integration/offline.mjs --test --test-concurrency=1 --test-timeout=240000 tests/integration/*.test.ts",
|
|
27
29
|
"release:core": "tsx scripts/release-core.ts",
|
|
28
30
|
"build:cli": "npm run build:setup-pings && tsx scripts/build-cli.ts",
|
|
29
31
|
"prepack": "npm run build:core && npm run build:cli",
|
|
@@ -45,7 +47,7 @@
|
|
|
45
47
|
"tsx": "4.23.15",
|
|
46
48
|
"typescript": "6.0.3",
|
|
47
49
|
"typescript-eslint": "8.64.0",
|
|
48
|
-
"@counterfact-labs/analysis-core": "0.8.
|
|
50
|
+
"@counterfact-labs/analysis-core": "0.8.3",
|
|
49
51
|
"@counterfact-labs/setup-pings": "0.1.0"
|
|
50
52
|
},
|
|
51
53
|
"workspaces": [
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c}from"../../chunks/PYKAERZZ.js";import{d as a,e as b}from"../../chunks/KWECQJ6X.js";import"../../chunks/FSLWD2PE.js";export{a as SOURCE_ROLES,c as rolesForCategory,b as sourceNotesSchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as f}from"./724WZMYW.js";function g(o){return o.skippedFiles??(o.notRead??[]).map(({path:t,kind:r})=>({path:t,reason:r==="prompt-too-large"?"too-large":"allowance"}))}function u(...o){let t={"secret-content":-7,secret:-6,hidden:-5,excluded:-4,"wrong-type":-3,empty:-2,"out-of-scope":-1,"too-large":0,allowance:1,"tool-limit":2,"scan-limit":3,total:4,unreadable:5,missing:6},r=new Map;for(let n of o)for(let e of n??[]){let s=r.get(e.path);(!s||t[e.reason]<t[s.reason])&&r.set(e.path,e)}return[...r.values()]}function d(o,t=0){let r=u(o),n=(...i)=>r.filter(({reason:p})=>i.includes(p)).length,e=r.filter(i=>i.reason==="secret-content").map(i=>f(i.path)),s=n("too-large"),a=n("allowance","tool-limit"),l=n("total","scan-limit"),c=n("missing","unreadable");return s&&e.push(`${s} ${s===1?"file was":"files were"} too big to read.`),a&&e.push(`${a} ${a===1?"file wasn't":"files weren't"} read because the file allowance was reached.`),l&&e.push(`${l} ${l===1?"file wasn't":"files weren't"} read because the repository is large.`),c&&e.push(`${c} ${c===1?"file couldn't":"files couldn't"} be read, so some tools may be missing.`),t>0&&e.push(`${t} more ${t===1?"file wasn't":"files weren't"} read.`),e}function w(o,t){return t?[...o.filter(n=>{let e=/^(\d+) more (?:file wasn't|files weren't) read\.$/.exec(n);return e?(t+=Number(e[1]),!1):!0}),...d([],t)]:[...o]}export{g as a,u as b,d as c,w as d};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{c as S}from"./RUVMFAST.js";import{a as N}from"./S27VIQMZ.js";import{posix as I}from"node:path";var b=class{text;tokens=[];lineStarts=[0];constructor(n){this.text=n;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&this.lineStarts.push(t+1)}push(n,t,s,i,r=!1){this.tokens.push({kind:n,text:this.text.slice(t,s),value:i??this.text.slice(t,s),start:t,end:s,line:this.lineAt(t),endLine:this.lineAt(s-1),...r?{formatted:!0}:{}})}lineAt(n){let t=0,s=this.lineStarts.length-1;for(;t<s;){let i=t+s+1>>1;this.lineStarts[i]<=n?t=i:s=i-1}return t+1}},ce=/[\p{L}_$]/u,ue=/[\p{L}\p{N}_$]/u;function w(e){return ce.test(e)}function D(e){return ue.test(e)}function m(e){return e>="0"&&e<="9"}function E(e){return e===" "||e===" "||e===`
|
|
2
|
-
`||e==="\r"||e==="\f"||e==="\v"}function k(e,n){return e[n+1]==="\r"&&e[n+2]===`
|
|
3
|
-
`?3:2}function $(e,n){let t=n+1;for(;t<e.length&&D(e[t]);)t++;return t}function v(e,n){let t=n+1;for(;t<e.length&&(D(e[t])||e[t]===".");)t++;return t}function O(e,n){for(;n<e.length&&e[n]!==`
|
|
4
|
-
`&&e[n]!=="\r";)n++;return n}var F={n:`
|
|
5
|
-
`,t:" ",r:"\r",b:"\b",f:"\f",v:"\v"},z=/^[0-9a-fA-F]+$/;function ae(e,n,t){let s=e[n+1];if(s==="\r"&&e[n+2]===`
|
|
6
|
-
`)return["",n+3];if(s===`
|
|
7
|
-
`||s==="\r")return["",n+2];if(s in F)return[F[s],n+2];let i=s==="x"?2:s==="u"?4:s==="U"&&t==="py"?8:0;if(i){let r=e.slice(n+2,n+2+i);if(r.length===i&&z.test(r)){let o=parseInt(r,16);if(o<=1114111)return[String.fromCodePoint(o),n+2+i]}}if(s==="u"&&t==="js"&&e[n+2]==="{"){let r=e.indexOf("}",n+3),o=r===-1?"":e.slice(n+3,r);if(z.test(o)&&parseInt(o,16)<=1114111)return[String.fromCodePoint(parseInt(o,16)),r+1]}if(t==="py"){if(s==="a")return["\x07",n+2];if(s>="0"&&s<="7"){let r=n+1;for(;r<n+4&&e[r]>="0"&&e[r]<="7";)r++;return[String.fromCharCode(parseInt(e.slice(n+1,r),8)),r]}if(s==="N"&&e[n+2]==="{"){let r=e.indexOf("}",n+3);if(r!==-1)return[e.slice(n,r+1),r+1]}}return t==="js"&&s==="0"?["\0",n+2]:[s,n+2]}function x(e,n){let t="",s=0;for(;s<e.length;){if(e[s]!=="\\"||s+1>=e.length){t+=e[s++];continue}let[i,r]=ae(e,s,n);t+=i,s=r}return t}var de=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Z(e,n){let t=e[n],s=n+1;for(;s<e.length;){let i=e[s];if(i==="\\")s+=k(e,s);else{if(i===t)return s+1;if(i===`
|
|
8
|
-
`||i==="\r")return s;s++}}return e.length}function pe(e,n,t=!1){let s=["t"],i=[],r=-1,o,c,l=(a,u,d)=>{c=o,o={kind:a,text:e.slice(u,d),start:u,end:d}},f=n+1;for(;f<e.length;){let a=s[s.length-1],u=e[f];if(a==="t")if(u==="\\")f+=k(e,f);else if(u==="`"){if(t&&l("template",f,f+1),f++,s.pop(),s.length===0)return{end:f,closed:!0,interpolations:i}}else u==="$"&&e[f+1]==="{"?(o=c=void 0,s.length===1&&(r=f),s.push(1),f+=2):f++;else if(u==="'"||u==='"'){let d=Z(e,f);t&&l("string",f,d),f=d}else if(u==="`")s.push("t"),f++;else if(u==="/"&&e[f+1]==="/")f=O(e,f);else if(u==="/"&&e[f+1]==="*")f=J(e,f);else if(t&&u==="/"&&q(o,c)){let d=X(e,f);l("regex",f,d),f=d}else if(u==="{")t&&l("punct",f,f+1),s[s.length-1]=a+1,f++;else if(u==="}")t&&l("punct",f,f+1),f++,a===1?(s.pop(),s.length===1&&i.push([r,f])):s[s.length-1]=a-1;else if(t&&(w(u)||m(u))){let d=m(u)?v(e,f):$(e,f);l(m(u)?"number":"ident",f,d),f=d}else t&&!E(u)&&l("punct",f,f+1),f++}return r!==-1&&s.length>1&&i.push([r,e.length]),{end:e.length,closed:!1,interpolations:i}}function he(e,n,t){let s=t.closed?t.end-1:t.end,i="",r=n+1;for(let[o,c]of t.interpolations)i+=x(e.slice(r,o),"js")+e.slice(o,Math.min(c,s)),r=c;return i+x(e.slice(r,s),"js")}function J(e,n){let t=e.indexOf("*/",n+2);return t===-1?e.length:t+2}function X(e,n){let t=n+1,s=!1;for(;t<e.length;){let i=e[t];if(i===`
|
|
9
|
-
`||i==="\r")return t;if(i==="\\")t+=k(e,t);else if(i==="[")s=!0,t++;else if(i==="]")s=!1,t++;else if(i==="/"&&!s){t++;break}else t++}for(;t<e.length&&/[a-z]/i.test(e[t]);)t++;return Math.min(t,e.length)}function ge(e,n){return e.kind==="punct"&&(e.text==="+"||e.text==="-")&&n?.text===e.text&&n.end===e.start}function q(e,n){if(!e)return!0;if(ge(e,n))return!1;switch(e.kind){case"ident":return de.has(e.text);case"number":case"string":case"template":case"regex":return!1;case"punct":return e.text!==")"&&e.text!=="]"&&e.text!=="}";default:return!0}}function B(e){let n=new b(e),t,s,i=(o,c,l,f,a=!1)=>{n.push(o,c,l,f,a),o!=="comment"&&(s=t,t=n.tokens[n.tokens.length-1])},r=0;for(;r<e.length;){let o=e[r],c=e[r+1];if(E(o)){r++;continue}let l;if(o==="/"&&c==="/")l=O(e,r),i("comment",r,l);else if(o==="/"&&c==="*")l=J(e,r),i("comment",r,l);else if(o==="'"||o==='"')l=Z(e,r),i("string",r,l,x(me(e,r,l,o),"js"));else if(o==="`"){let f=pe(e,r);l=f.end,i("template",r,l,he(e,r,f),f.interpolations.length>0)}else o==="/"&&q(t,s)?(l=X(e,r),i("regex",r,l)):m(o)||o==="."&&m(c??"")?(l=v(e,r),i("number",r,l)):w(o)?(l=$(e,r),i("ident",r,l)):(l=r+1,i("punct",r,l));r=l}return n.tokens}function me(e,n,t,s){let i=0;for(let o=t-2;o>n&&e[o]==="\\";o--)i++;let r=t-n>1&&e[t-1]===s&&i%2===0;return e.slice(n+1,r?t-1:t)}var ye=new Set(["r","b","f","u","rb","br","fr","rf"]);function V(e,n,t=!1,s){let i=e[n],r=e.startsWith(i.repeat(3),n),c=n+(r?3:1),l=c,f=0,a=[];for(;l<e.length;){let u=e[l];if(u==="\\")l+=k(e,l);else if(t&&u==="{"&&f===0&&e[l+1]==="{")l+=2;else if(t&&u==="{"){let d=a.at(-1);s&&(f===0||d?.format&&f===d.depth?a.push({start:l+1,depth:f+1,nesting:0,format:!1}):d&&!d.format&&d.nesting++),f++,l++}else if(t&&u==="}"&&f>0){let d=a.at(-1);d?.depth===f?(d.format||s?.push([d.start,l]),a.pop()):d&&!d.format&&d.nesting--,f--,l++}else if(s&&a.length&&!a.at(-1).format&&"()[]".includes(u))a.at(-1).nesting+="([".includes(u)?1:-1,l++;else if(s&&u===":"&&a.length&&!a.at(-1).format&&a.at(-1).nesting===0){let d=a.at(-1);s.push([d.start,l]),d.format=!0,l++}else if(f>0&&!a.at(-1)?.format&&(u==='"'||u==="'")&&!e.startsWith(u.repeat(3),l)&&G(e,l)!==-1)l=G(e,l);else{if(r&&e.startsWith(i.repeat(3),l))return{end:l+3,bodyStart:c,bodyEnd:l};if(!r&&u===i)return{end:l+1,bodyStart:c,bodyEnd:l};if(!r&&(u===`
|
|
10
|
-
`||u==="\r"))return{end:l,bodyStart:c,bodyEnd:l};l++}}return{end:e.length,bodyStart:c,bodyEnd:e.length}}function G(e,n){let t=V(e,n);return t.end>t.bodyEnd?t.end:-1}function Y(e){let n=new b(e),t=0;for(;t<e.length;){let s=e[t];if(E(s)){t++;continue}if(s==="#"){let i=O(e,t);n.push("comment",t,i),t=i}else if(s==='"'||s==="'")t=H(n,t,t,"");else if(m(s)||s==="."&&m(e[t+1]??"")){let i=v(e,t);n.push("number",t,i),t=i}else if(w(s)){let i=$(e,t),r=e.slice(t,i).toLowerCase();(e[i]==='"'||e[i]==="'")&&ye.has(r)?t=H(n,t,i,r):(n.push("ident",t,i),t=i)}else n.push("punct",t,t+1),t++}return n.tokens}function H(e,n,t,s){let i=V(e.text,t,s.includes("f")),r=e.text.slice(i.bodyStart,i.bodyEnd);return e.push("string",n,i.end,s.includes("r")?r:x(r,"py"),s.includes("f")),i.end}var je={ts:"js",tsx:"js",js:"js",jsx:"js",mjs:"js",cjs:"js",mts:"js",cts:"js",py:"py"};function L(e){let n=e.slice(e.lastIndexOf("/")+1),t=n.lastIndexOf(".");return t===-1?null:je[n.slice(t+1).toLowerCase()]??null}function K(e,n){return n==="py"?Y(e):B(e)}var p={inventoryEntries:1e4,metadataTextUnits:1e6,workspaceTextUnits:2e6,settingsFiles:128,settingsBytes:2e6,metadataDepth:32,workspacePatterns:128,patternTextUnits:512,patternSegments:64};function h(e){return N.safeParse(e).success&&!e.split("/").includes("node_modules")}function j(e,n){return/^(?:\/|[A-Za-z][A-Za-z\d+.-]*:)|[\\\p{C}]/u.test(n)?null:P(e==="."?"":e,n)}function P(e,n){let t=e?e.split("/"):[];for(let s of n.split("/"))if(!(s===""||s==="."))if(s===".."){if(t.pop()===void 0)return null}else t.push(s);return t.join("/")}var T=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Q(e){let n=K(e.replace(/^\uFEFF/,""),"js").filter(s=>s.kind!=="comment"),t=n.filter((s,i)=>s.text!==","||!["}","]"].includes(n[i+1]?.text)).map(s=>s.text).join(" ");try{let s=JSON.parse(t);return T(s)?s:null}catch{return null}}function ee(e,n){if(!n.startsWith(".")||n.split("/").includes("node_modules"))return[];let t=j(I.dirname(e),n);return t!==null&&h(t)?[t,`${t}.json`,`${t}/tsconfig.json`]:[]}function te(e,n){let t=I.dirname(e);for(;;){let s=I.join(t,"tsconfig.json");if(n.has(s)&&h(s))return s;if(t===".")return;t=I.dirname(t)}}var W=class{files;static settingsFiles(n,t,s){let i=[...new Set(s.filter(o=>L(o)==="js").flatMap(o=>te(o,n)??[]))],r=new Set(i);for(let o=0;o<i.length;o++){let c=i[o],l=t.get(c);if(l===void 0||l.length>p.metadataTextUnits)continue;let f=Q(l)?.extends;if(typeof f!="string")continue;let a=ee(c,f).find(u=>n.has(u));a&&!r.has(a)&&(r.add(a),i.splice(o+1,0,a))}return i}configs=new Map;constructor(n){this.files=n}config(n){let t=this.configs.get(n);if(t)return t;let s=this.readConfig(n);return this.configs.set(n,s),s}readConfig(n,t=new Set){if(t.has(n))return"invalid-config";if(t.size>=p.metadataDepth)return"over-limit";let s=this.files.get(n);if(s===void 0)return"invalid-config";if(s.length>p.metadataTextUnits)return"over-limit";let i=Q(s);if(!i)return"invalid-config";let r=I.dirname(n),o={base:r==="."?"":r,baseUrl:!1,paths:{}};if(i.extends!==void 0){if(typeof i.extends!="string"||!i.extends.startsWith("."))return"unsupported";if(i.extends.split("/").includes("node_modules"))return"excluded";let f=j(r,i.extends);if(f===null)return"out-of-scope";if(!h(f))return"excluded";let a=ee(n,i.extends).find(d=>this.files.has(d));if(!a)return"invalid-config";let u=this.readConfig(a,new Set([...t,n]));if(typeof u=="string")return u;o=u}let c=i.compilerOptions===void 0?{}:i.compilerOptions;if(!T(c)||c.paths!==void 0&&!T(c.paths)||c.baseUrl!==void 0&&typeof c.baseUrl!="string")return"invalid-config";if(typeof c.baseUrl=="string"&&c.baseUrl.split("/").includes("node_modules"))return"excluded";let l=typeof c.baseUrl=="string"?j(r,c.baseUrl):c.paths!==void 0&&!o.baseUrl?r==="."?"":r:o.base;return l===null?"out-of-scope":l&&!h(l)?"excluded":{base:l,baseUrl:c.baseUrl!==void 0||o.baseUrl,paths:c.paths??o.paths}}bases(n,t){let s=te(n,this.files);if(!s)return null;let i=this.config(s);if(typeof i=="string")return i;let r=Object.entries(i.paths).flatMap(([f,a])=>{let u=f.indexOf("*");if(u<0)return f===t?[{targets:a,capture:"",rank:1/0,suffix:0}]:[];let d=f.slice(0,u),g=f.slice(u+1);return t.length>=d.length+g.length&&t.startsWith(d)&&t.endsWith(g)?[{targets:a,capture:t.slice(d.length,t.length-g.length),rank:d.length,suffix:g.length}]:[]}).sort((f,a)=>a.rank-f.rank||a.suffix-f.suffix);if(r.length>1&&r[0].rank===r[1].rank&&r[0].suffix===r[1].suffix)return"ambiguous";let o=r[0];if(o&&(!Array.isArray(o.targets)||!o.targets.length||!o.targets.every(f=>typeof f=="string")))return"invalid-config";let c=o?o.targets:i.baseUrl?[t]:[];if(!c.length)return null;let l=[];for(let f of c){if((f.match(/\*/g)?.length??0)>1||o?.rank===1/0&&f.includes("*"))return"unsupported";let a=f.replace(/\*/,()=>o?.capture??"");if(a.split("/").includes("node_modules"))return"excluded";let u=j(i.base,a);if(u===null)return"out-of-scope";if(!h(u))return"excluded";l.push(u)}return{bases:l,fallback:!o}}};import{posix as ie}from"node:path";var C=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function re(e){try{let n=JSON.parse(e);return C(n)?n:null}catch{return null}}function be(e){let n=[],t=!1;for(let s of e.split(/\r?\n/)){if(/^packages:\s*(?:#.*)?$/.test(s)){t=!0;continue}if(!t||/^\s*(?:#.*)?$/.test(s))continue;if(/^\S/.test(s)){t=!1;continue}let i=/^\s+-\s+(?:'([^']*)'|"([^"]*)"|([^#\s]+))\s*(?:#.*)?$/.exec(s);if(!i)return null;n.push(i[1]??i[2]??i[3])}return t||n.length?n:null}function ke(e){if(!e||e.length>p.patternTextUnits||/[\\\p{C}{}[\]?]|^(?:\/|[A-Za-z]:)/u.test(e)||e.split("/").some(s=>s===".."||s==="node_modules"))return null;let n=e.replace(/^\.\//,"").replace(/\/$/,"").split("/");if(n.length>p.patternSegments||n.filter(s=>s==="**").length>1||n.some(s=>s!=="**"&&(s.match(/\*/g)?.length??0)>1))return null;let t=(s,i)=>{let r=s.indexOf("*");return r<0?s===i:i.length>=s.length-1&&i.startsWith(s.slice(0,r))&&i.endsWith(s.slice(r+1))};return s=>{let i=s.split("/"),r=n.indexOf("**");if(r<0)return i.length===n.length&&n.every((c,l)=>t(c,i[l]));let o=n.length-r-1;return i.length>=n.length-1&&n.slice(0,r).every((c,l)=>t(c,i[l]))&&n.slice(r+1).every((c,l)=>t(c,i[i.length-o+l]))}}function ne(e){let n=e.get("package.json"),t=e.get("pnpm-workspace.yaml");if((n?.length??0)>p.metadataTextUnits||(t?.length??0)>p.metadataTextUnits)return"over-limit";let s=n===void 0?{}:re(n);if(!s)return"invalid-config";let i=C(s.workspaces)?s.workspaces.packages:s.workspaces;if(i!==void 0&&(!Array.isArray(i)||!i.every(l=>typeof l=="string")))return"invalid-config";let r=t===void 0?[]:be(t);if(!r)return"unsupported";let o=[...i??[],...r];if(o.length>p.workspacePatterns)return"over-limit";let c=[];for(let l of o){let f=ke(l.replace(/^!/,""));if(!f)return"unsupported";c.push({excluded:l.startsWith("!"),matches:f})}return c}function se(e,n){if(e==="package.json"||!e.endsWith("/package.json")||!h(e))return!1;let t=ie.dirname(e);return n.some(s=>!s.excluded&&s.matches(t))&&!n.some(s=>s.excluded&&s.matches(t))}function oe(e,n=0){if(n>=p.metadataDepth)return{reason:"over-limit"};if(typeof e=="string")return{target:e};if(!C(e))return{reason:"unsupported"};for(let t of["source","import","default"])if(Object.hasOwn(e,t))return oe(e[t],n+1);return{reason:"unsupported"}}var A=class{files;static settingsFiles(n,t){let s=["package.json","pnpm-workspace.yaml"].filter(r=>n.has(r));if(s.some(r=>!t.has(r)))return s;let i=ne(t);return typeof i=="string"?s:[...s,...[...n].filter(r=>se(r,i))]}packages;constructor(n){this.files=n}inventory(){return this.packages??=this.readInventory()}readInventory(){let n=ne(this.files);if(typeof n=="string")return n;let t=[],s=(this.files.get("package.json")?.length??0)+(this.files.get("pnpm-workspace.yaml")?.length??0);for(let[i,r]of this.files){if(!se(i,n))continue;let o=ie.dirname(i);if(s+=r.length,r.length>p.metadataTextUnits||s>p.workspaceTextUnits)return"over-limit";let c=re(r);if(!c||typeof c.name!="string")return"invalid-config";t.push({root:o,data:c})}return t}bases(n){let t=/^(@[^/]+\/[^/]+|[^/@][^/]*)(?:\/(.+))?$/.exec(n);if(!t)return"unsupported";let s=this.inventory();if(typeof s=="string")return s;let i=s.filter(u=>u.data.name===t[1]);if(!i.length)return null;if(i.length>1)return"ambiguous";let r=i[0],o=t[2]?`./${t[2]}`:".",c;if(r.data.exports!==void 0){let u=r.data.exports;if(C(u)&&Object.keys(u).some(d=>d.includes("*")))return"unsupported";if(C(u)&&Object.keys(u).some(d=>d.startsWith("."))){if(Object.keys(u).some(d=>!d.startsWith(".")))return"ambiguous";c=u[o]}else o==="."&&(c=u);if(c===void 0)return"missing"}else c=o!=="."?o:r.data.source??r.data.module??r.data.main??"./index";let l=oe(c);if("reason"in l)return l.reason;let{target:f}=l;if(f.split("/").includes("node_modules"))return"excluded";if(/^(?:\/|[A-Za-z]:)|[\\\p{C}]/u.test(f)||r.data.exports!==void 0&&!f.startsWith("./"))return"out-of-scope";let a=j(r.root,f);return a===null||!a.startsWith(`${r.root}/`)?"out-of-scope":h(a)?{bases:[a]}:"excluded"}};function xe(e){return e.replace(/\.(tsx?|jsx?|mjs|cjs|py)$/,"").replace(/^(\.{1,2}\/)+/,"").replace(/^[@~]?\//,"").replace(/^\.+/,"").replace(/\./g,"/")}function _e(e,n){let t=xe(n),s=e.replace(/\.[^./]+$/,"").replace(/\/index$/,"").replace(/\/__init__$/,"");return t.length>0&&(s===t||s.endsWith(`/${t}`))}function le(e,n=!1){let t=n?[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"]:[".ts",".tsx",".js"],s=e.replace(n?/\.(js|jsx|mjs|cjs)$/:/\.(js|jsx|mjs)$/,""),i=n&&e.endsWith(".mjs")?[".mts"]:n&&e.endsWith(".cjs")?[".cts"]:[".ts",".tsx"];return[e,...t.map(r=>e+r),...s===e?[]:i.map(r=>s+r),...t.map(r=>`${e}/index${r}`)]}function Se(e,n,t){let s=n.length-n.replace(/^\.+/,"").length,i=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r="../".repeat(s-1),o=n.slice(s).split(".").join("/"),c=P(i,r+o);return c===null?[]:o?[`${c}.py`,`${c}/__init__.py`]:[...t.map(l=>c?`${c}/${l}.py`:`${l}.py`),c?`${c}/__init__.py`:"__init__.py"]}function R(e,n,t,s,i=!1){if(!n.startsWith("."))return[];if(s==="py")return Se(e,n,t);let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=P(r,n);return o===null?[]:le(o,i)}function we(e,n,t,s,i,r=!1){return R(e,n,t,s,r).find(o=>i.has(o))}function Ge(e,n,t,s={},i){return new M(t,s).resolve(e,n,i)}var M=class{repo;static settingsFiles(n,t,s){return[...W.settingsFiles(n,t,s),...s.some(i=>L(i)==="js")?A.settingsFiles(n,t):[]]}legacy;files;aliases;workspaces;pythonRoots=new Map;constructor(n,t={}){if(this.repo=n,this.legacy=t.CF_LOCAL_IMPORT_RESOLUTION==="0",this.files=n.files.size>p.inventoryEntries&&!this.legacy?new Map:new Map([...n.files].filter(([s])=>h(s))),this.aliases=new W(this.files),this.workspaces=new A(this.files),!this.legacy)for(let s of this.files.keys()){if(!s.endsWith(".py"))continue;let i=s.split("/");for(let r=0;r<i.length;r++){let o=i.slice(0,r).join("/"),c=r===i.length-1?i[r].slice(0,-3):i[r];this.pythonRoots.has(o)||this.pythonRoots.set(o,new Set),this.pythonRoots.get(o).add(c)}}}hasPythonRoot(n,t){let s=n.split("/");s.pop();for(let i=s.length;i>=0;i--){let r=s.slice(0,i).join("/");if(this.pythonRoots.get(r)?.has(t)||this.pythonRoots.get(r?`${r}/src`:"src")?.has(t))return!0}return!1}bindings(n,t,s){return!S.shape.from.safeParse(n).success||!S.shape.specifier.safeParse(t).success?[]:[this.resolve(n,t,s)]}resolve(n,t,s=[]){S.shape.from.parse(n),S.shape.specifier.parse(t);let i=n.endsWith(".py"),r=(a,u=null)=>({status:"refused",from:n,specifier:t,provenance:u,reason:a}),o=(a,u)=>({status:"resolved",from:n,specifier:t,provenance:u,path:a});if(this.legacy){let a=we(n,t,s,i?"py":"js",new Set(this.files.keys()));return a?o(a,"relative"):r(t.startsWith(".")?"missing":"external")}if(!h(n))return r("out-of-scope");if(/[\\\p{C}\p{Zl}\p{Zp}]/u.test(t))return r("unsupported");if(/^(?:\/|[A-Za-z]:)/.test(t))return r("out-of-scope");if(t.split("/").includes("node_modules"))return r("excluded");if(this.repo.files.size>p.inventoryEntries)return r("over-limit");if(i&&!/^\.*(?:[\p{L}_][\p{L}\p{N}_]*(?:\.[\p{L}_][\p{L}\p{N}_]*)*)?$/u.test(t)||i&&s.some(a=>!/^[\p{L}_][\p{L}\p{N}_]*$/u.test(a)))return r("unsupported");if(t.startsWith(".")||i){let a=i&&!t.startsWith(".")?`.${t}`:t,d=(i&&!t.startsWith(".")?["__root__.py",n]:[n]).map(y=>[...i?s.flatMap(_=>R(y,`${a}${a.endsWith(".")?"":"."}${_}`,[],"py",!0)):[],...R(y,a,s,i?"py":"js",!0)].map(_=>_.replace(/^\//,"")));if(d.every(y=>!y.length))return r("out-of-scope","relative");let g=new Set(d.map(y=>y.find(_=>this.files.has(_))).filter(y=>y!==void 0));if(g.size>1)return r("ambiguous","relative");let U=[...g][0],fe=i&&!t.startsWith(".")&&!this.hasPythonRoot(n,t.split(".")[0]);return U?o(U,"relative"):r(fe?"external":"missing","relative")}let c=(a,u)=>{if(a===null)return null;if(typeof a=="string")return r(a,u);for(let d of a.bases){let g=le(d,!0).find(U=>this.files.has(U));if(g)return o(g,u)}return r("missing",u)},l=this.aliases.bases(n,t),f=c(l,"alias");return f&&(f.status==="resolved"||typeof l=="string"||!l?.fallback)?f:c(this.workspaces.bases(t),"workspace")??r("external")}};export{L as a,K as b,p as c,_e as d,R as e,we as f,Ge as g,M as h};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c,c as l,d as s,e as m,g as i}from"./SKVEBOGA.js";import{c as u,d as p}from"./FSLWD2PE.js";function n(a,d={}){return JSON.stringify({bundleDescription:a,inputs:d})}import{z as e}from"zod";import{z as t}from"zod";var r=t.object({motivation:t.array(t.object({kind:t.string(),reason:t.string(),evidence:t.string()})),outcomes:t.array(t.object({improvement:t.string(),measurement:t.string()}))}),O=r.extend({motivation:r.shape.motivation.default([]),outcomes:r.shape.outcomes.default([])});var h=e.object({path:e.string().min(1),line:e.number().int().positive().nullable()}),f=e.object({label:e.string(),source:e.literal("mcp").optional(),brand:e.string().nullable().default(()=>null)}),x=["system prompt","soul","knowledge","skill","config","tools","mcp","template","reference","code"],y=e.object({filledAtRunTime:e.boolean().optional(),role:e.enum(x),label:e.string().nullable().default(()=>null),path:e.string().min(1),span:e.object({from:e.number().int(),to:e.number().int()}).optional()}),S=e.object({id:e.string().min(1),label:e.string().min(1),kind:e.enum(["entry","agent","tool","store","exit"]),desc:e.string(),meta:e.string().nullable(),sourceRef:h.nullable(),sourcePaths:e.array(e.string()).optional(),files:e.array(y).default(()=>[]),tools:e.array(f).default(()=>[])}),j=e.object({from:e.string().min(1),to:e.string().min(1),kind:e.enum(["invokes","delegates","reads","writes","emits"]),label:e.string().nullable(),sourceRef:h.nullable()}),_=e.object({nodes:e.array(S),edges:e.array(j),warnings:e.array(e.string())}),v=e.object({...r.shape,title:e.string().min(1).describe(n("analysis-wire-schemas-1")),approach:e.string().min(1).describe(n("analysis-wire-schemas-2")),kind:e.enum(["code","prompt"]),targetFiles:e.array(e.object({path:e.string().min(1),create:e.boolean().nullable()})),...i.shape});function o(a){return e.string().describe(n("analysis-wire-schemas-3",{v0:Object.values(a.enum).join(", ")}))}var w=e.object({nodes:e.array(e.object({id:e.string().min(1),change:o(s),label:e.string().nullable()})),edges:e.array(e.object({from:e.string().min(1),to:e.string().min(1),kind:o(m),change:o(s),detail:e.string().nullable()}))}),k=v.omit({motivation:!0,outcomes:!0}).extend({expectedOutcome:e.string().describe(n("analysis-wire-schemas-4")),summary:i.shape.summary.catch(null),impact:i.shape.impact.catch(null),objective:i.shape.objective.catch(null),blockedBy:i.shape.blockedBy.catch(null),confidence:o(l).nullable().catch(null),status:o(c).nullable().catch(null),alsoFixes:e.array(e.string()).nullable().default([]).catch(()=>[]),delta:w.nullable().catch(null)}),q=e.object({path:e.string().min(1),line:e.number().int().positive(),excerpt:e.string().trim().min(1)}),F=e.object({path:e.string(),line:e.number(),excerpt:e.string()}),b=a=>e.string().describe(n("analysis-wire-schemas-5",{v0:u(a).join(", ")})).nullable().catch(null),g=e.object({kind:e.enum(["ordering","reliability","coverage","cost","safety","correctness"]),severity:e.enum(["low","medium","high","critical"]),title:e.string().min(1).describe(n("analysis-wire-schemas-6")),cause:e.string().min(1),summary:e.string().describe(n("analysis-wire-schemas-7")).catch(""),site:e.object({path:e.string().min(1),line:e.number().int().positive().nullable()}).nullable(),excerpt:e.string().nullable(),category:b({}),otherSites:e.array(F).nullable().default([]).catch(()=>[]),question:e.string().describe(n("analysis-wire-schemas-8")).catch(""),fixes:e.array(k).min(1)}),E=e.object({findings:e.array(g)});function A(a){return p(a)?E:e.object({findings:e.array(g.extend({category:b(a)}))})}export{n as a,_ as b,k as c,q as d,g as e,E as f,A as g};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as f,c as r,e as m,g as p}from"./6B2HILSY.js";import{b as o}from"./SKVEBOGA.js";import{a as c}from"./A7WJJMRY.js";import{e as x}from"./KWECQJ6X.js";import{a as d,b as u}from"./FSLWD2PE.js";import{z as s}from"zod";var g={expectedOutcome:{setting:"CF_FIX_EXPECTED_OUTCOME",enabled:e=>e.CF_FIX_EXPECTED_OUTCOME!=="0",suffix:"-no-outcome",suffixWhen:!1},untrustedContent:{setting:"CF_UNTRUSTED_CONTENT_CHECK",enabled:d,suffix:"-no-untrusted",suffixWhen:!1},betterAsCode:{setting:"CF_FINDING_BETTER_AS_CODE",enabled:u,suffix:"-better-as-code",suffixWhen:!0},audience:{setting:"CF_FINDING_AUDIENCE",enabled:c,suffix:"-audience",suffixWhen:!0}};function h(e){let t=Object.entries(g).map(([n,i])=>({key:n,rule:i,enabled:i.enabled(e)}));return{name:`findings${t.map(({rule:n,enabled:i})=>i===n.suffixWhen?n.suffix:"").join("")}`,switches:Object.fromEntries(t.map(({key:n,enabled:i})=>[n,i])),settings:Object.fromEntries(t.map(({rule:n,enabled:i})=>[n.setting,i?"1":"0"]))}}function D(){let e=[{}];for(let{setting:t}of Object.values(g))e=e.flatMap(n=>["0","1"].map(i=>({...n,[t]:i})));return e.map(t=>({...h(t),schema:F(t)}))}function b(e){return s.object({findings:s.array(e.shape.findings.element.extend({fixes:s.array(r.omit({expectedOutcome:!0})).min(1)}))})}var E=r.extend({expectedOutcome:s.string().default("")}),C=s.array(m.extend({audience:o.optional().catch(void 0),fixes:s.array(E).min(1),sourceNotes:x.nullable().optional().catch(null)}));function F(e){let t=h(e),n=p(t.settings),a=(t.switches.expectedOutcome?n:b(n)).shape.findings.element,l=o.describe(f("finding-audience"));return s.object({findings:s.array(t.switches.audience?a.extend({audience:l.catch(void 0)}):a)})}function W(e){return O(e.findings)}function O(e){return C.parse(e)}export{h as a,D as b,F as c,W as d,O as e};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as p}from"./KGQYR62R.js";import{z as y}from"./GOQVKWP3.js";import{posix as B}from"node:path";var m=Object.freeze({totalLimitBytes:y.codeAgent.importBytes,instructionLimitBytes:y.sourceFetch.instructionBytes}),u=["totalBytes","instructionBytes","fileCount"],n=()=>new Error("Invalid analysis size"),l=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0;function z(t){if(!t||typeof t!="object"||Array.isArray(t)||Reflect.ownKeys(t).length!==u.length||u.some(a=>!Object.hasOwn(t,a)||!l(Reflect.get(t,a))))throw n();let{totalBytes:i,instructionBytes:c,fileCount:o}=t;if(c>i)throw n();return{totalBytes:i,instructionBytes:c,fileCount:o}}function A(t){let i=z(t);return i.totalBytes>m.totalLimitBytes?{fits:!1,measure:"total_text"}:i.instructionBytes>m.instructionLimitBytes?{fits:!1,measure:"instruction_text"}:{fits:!0,measure:null}}function d(t,i,c={}){let o=new Map;for(let e of i){if(!l(e.size)||typeof e.path!="string"||!e.path||e.path.includes("\0"))throw n();let s=B.normalize(e.path.replace(/\\/g,"/"));if(s==="."||s===".."||s.startsWith("../")||s.startsWith("/"))throw n();let f=o.get(s);if(f&&f.size!==e.size)throw n();o.set(s,{path:s,size:e.size,ref:s})}let a=[...o.values()],{descriptions:h}=p(t,a,c,{measureAnalysisSize:!0}),r={totalBytes:0,instructionBytes:0,fileCount:0};for(let e of h){if(!e.countsTowardAnalysisSize)continue;let{entry:s}=e;if(r.totalBytes+=s.size,e.analysisPool==="instruction"&&(r.instructionBytes+=s.size),r.fileCount+=1,!u.every(f=>l(r[f])))throw n()}return z(r)}export{m as a,z as b,A as c,d};
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import{a as K}from"./QDYMR6KS.js";import{a as A}from"./Y7JGSUOA.js";import{d as M}from"./3MTXB4MK.js";import{b}from"./E7TFIHC5.js";import{j as U}from"./K2GNDX3W.js";import{a as P}from"./HTLIRVP7.js";import{e as S}from"./K5FUABWW.js";import{d as L,e as N,f as v,g as D,h as $}from"./SLJ6CW7W.js";import{a as w,b as E}from"./MJGB25S5.js";import{a as C}from"./74FPPPIG.js";import{c as j}from"./FSLWD2PE.js";var J=Object.freeze({"benchmark-judge":"score_match","judge-code-prompt":"judge-code-prompt","derive-findings":"derive_findings","derive-findings-legacy":"derive_findings","derive-findings-no-outcome":"derive_findings","derive-findings-legacy-no-outcome":"derive_findings","derive-structure":"derive_structure","structure-recheck":"structure_recheck","derive-shape":"derive_shape","scope-items":"scope_check_structure","scope-findings":"scope_check","explain-sources":"explain_sources","finding-headlines":"finding_headlines","check-findings":"finding_check","check-findings-precision-v1":"finding_check","second-opinion":"finding_second_opinion"});function re(t){if(!Object.hasOwn(J,t))throw new Error("Unknown analysis template");return J[t]}function z(t){return Object.fromEntries(Object.entries(t).map(([e,o])=>[e,{...o,route:re(e)}]))}import{z as T}from"zod";function F(t,e){if(Buffer.byteLength(t)<=e)return t;let o=0,r=Math.min(t.length,e);for(;o<r;){let a=Math.ceil((o+r)/2);Buffer.byteLength(t.slice(0,a))<=e?o=a:r=a-1}return r>0&&/[\uD800-\uDBFF]/.test(t[r-1])&&r--,t.slice(0,r)}function G(t){let{bundleText:e}=t,o=i=>Buffer.byteLength(JSON.stringify(i));function r(i){let n=[];for(let s of i){if(o([...n,""])>4e3)break;let d=0,l=Buffer.byteLength(s);for(;d<l;){let m=Math.ceil((d+l)/2);o([...n,F(s,m)])<=4e3?d=m:l=m-1}n.push(F(s,d))}return n}function a(i,n=!1){return i.map(s=>typeof s!="string"&&s.kind==="no-core"&&n?e("analysis-check-input-1"):P([s])[0])}function p(i){let n=i.citedFiles===void 0?"":',"citedFiles":'+JSON.stringify(i.citedFiles),s=a(i.diagnostics,!0),d=i.citedFiles===void 0?s:r(s),l=[{text:'{"coreFiles":'+JSON.stringify(i.coreFiles)},{text:n+',"findings":'+JSON.stringify(i.findings)+',"diagnostics":'+JSON.stringify(d)+"}"}];return E(l,w({},{template:"check-findings"}).breakpoints)}function c(i){return Buffer.byteLength(p(i).map(n=>n.text).join(""))}return{checkDiagnosticsText:a,checkPromptBlocks:p,checkPayloadBytes:c}}function R(t,e={}){return t.length?t.map(o=>{let r=e.includeFiles===!1?"":`; files ${o.files.join(", ")||"none"}`;return`${o.ref} "${o.title}" (${o.subKind}): frozen ${o.frozen.join(", ")||"none"}; declined ${o.declined.join(", ")||"none"}${r}`}).join(`
|
|
2
|
-
`):"none"}function _(t){let{bundleText:e}=t,o=e("analysis-scope-check-1"),r=e("analysis-split-check-scope-rule-1"),a=[e("analysis-derive-structures-1"),e("analysis-derive-structures-2"),e("analysis-derive-structures-3"),e("analysis-derive-structures-4"),e("analysis-derive-structures-5"),e("analysis-derive-structures-6"),e("analysis-derive-structures-7"),e("analysis-derive-structures-8")].join(`
|
|
3
|
-
`),p=e("analysis-derive-structures-10");function c(n){return n.map(s=>({unit:JSON.stringify(s.unitKey),kind:s.kind,name:JSON.stringify(s.name),location:JSON.stringify(`${s.sourcePath}:${s.sourceLine}${s.sourceEndLine?`\u2013${s.sourceEndLine}`:""}`)}))}function i(n){return e("code-finding-note",{codeSources:c(n)})}return{RULE:o,SPLIT_SCOPE_RULE:r,SUB_KIND_DEFS:a,STRUCTURE_SCOPE_RULE:p,codeSourceLabels:c,codeFindingNote:i}}import{posix as V}from"node:path";function Q(t){let{bundleText:e}=t,o=.25,r=4;function a(c){let i=new Set(c.map(l=>l.name)),n=new Map(c.map(l=>[l.name,new Set(l.skills.filter(m=>m!==l.name&&i.has(m)))])),s=new Map;for(let l of n.values())for(let m of l)s.set(m,(s.get(m)??0)+1);let d=Math.max(r,(c.length-1)*o);return c.map(l=>({name:l.name,linkedFrom:s.get(l.name)??0,linksTo:n.get(l.name).size})).filter(l=>l.linkedFrom>=d||l.linksTo>=d)}function p(c){let i=a(c);if(!i.length)return null;let n=i.map(s=>e("shape-shared-skill",s));return e("analysis-split-check-shared-skills-1",{v0:n.join(`
|
|
4
|
-
`)})}return{sharedSkillsOf:a,sharedSkillsText:p}}function W(t){let{bundleText:e}=t,{shapeFindingsText:o}=M(t),{sharedSkillsText:r}=Q(t);function a(c){let i=new Map(c.map((n,s)=>[n.name,`s${s+1}`]));return e("shape-skills",{skills:c.map(n=>({...n,id:i.get(n.name),refs:n.references.map(s=>V.relative(V.dirname(n.path),s)).join(","),tools:n.tools.join(","),links:n.skills.map(s=>i.get(s)).join(","),hasRefs:n.references.length>0,hasTools:n.tools.length>0,hasLinks:n.skills.length>0,hasDetails:n.references.length>0||n.tools.length>0||n.skills.length>0}))})}function p(c){return e("shape-inventory",{agent:c.agent,v0:a(c.skills),shared:r(c.skills),tools:c.tools.map(i=>({...i,skills:i.skills.join(", ")})),subAgents:c.subAgents.map(i=>({...i,tools:i.tools.join(", "),skills:a(i.skills)})),prompts:c.prompts,knowledge:c.knowledge.map(i=>({...i,headings:i.sections.map(n=>`${n.startLine}-${n.endLine} ${n.heading}`).join(`
|
|
5
|
-
`)})),findings:o(c.findings)})}return{inventoryText:p}}function X(t){let{SPLIT_SCOPE_RULE:e}=_(t),{inventoryText:o}=W(t);function r(a){return{scopeRule:e,open:R(a.open),inventory:o(a)}}return{shapeInputs:r,SPLIT_SCOPE_RULE:e}}function O(t){let{bundleText:e}=t,o={contradiction:{def:e("analysis-categories-1"),evidence:e("analysis-categories-2")},ambiguity:{def:e("analysis-categories-3"),evidence:e("analysis-categories-4")},bypassable_requirement:{def:e("analysis-categories-5"),evidence:e("analysis-categories-6")},stale_fact:{def:e("analysis-categories-7"),evidence:e("analysis-categories-8")},description_mismatch:{def:e("analysis-categories-9"),evidence:e("analysis-categories-10")},ungoverned_tool:{def:e("analysis-categories-11"),evidence:e("analysis-categories-12")},untrusted_instructions:{def:e("analysis-categories-13"),evidence:e("analysis-categories-14")},better_as_code:{def:e("analysis-categories-15"),evidence:e("analysis-categories-16")}},r={untrusted_instructions:{derive:"analysis-categories-17",check:"analysis-categories-18"},better_as_code:{derive:"analysis-categories-19",check:"analysis-categories-20"}};function a(i){return j(i).map(n=>{let s=o[n];return e("category-entry",{category:n,definition:s.def,evidence:s.evidence})}).join(`
|
|
6
|
-
`)}function p(i,n){return j(i).map(s=>{let d=r[s]?.[n];return d?`
|
|
7
|
-
|
|
8
|
-
${e(d,{promptAgreement:S(i)})}`:""}).join("")}function c(){return[e("analysis-categories-21"),e("analysis-categories-22"),e("analysis-categories-23"),e("analysis-categories-24"),e("analysis-categories-25"),e("analysis-categories-26")].join(`
|
|
9
|
-
`)}return{categoryBlock:a,categoryRules:p,impactBlock:c}}function Y(t){let{checkPromptBlocks:e}=G(t),{shapeInputs:o}=X(t),{templates:r}=t,{categoryBlock:a,categoryRules:p}=O(t);function c(i,n,s,d={}){if(i==="derive-shape")return{...n,...o(n.inventoryData)};if(i.startsWith("check-findings")||i==="second-opinion"){let l=e(n.checkInput),m=a(s),u=p(s,"check"),x=S(s),h={...n,promptAgreement:x,categories:m,categoryRules:u,core:l[0].text,claims:l[1].text};if(i!=="second-opinion")return h;let g;try{if(typeof n.checkTemplate!="string")throw new Error;g=D("check",s,n.checkTemplate)}catch{throw new Error("Unknown check template")}let y=typeof g=="string"&&Object.hasOwn(d,g)?d[g]:void 0;if(y?.route!=="finding_check"||y.system===void 0)throw new Error("Unknown check template");return{...h,checkSystem:b(y.system,{promptAgreement:x,categories:m,categoryRules:u},r)}}return n}return{stageInputs:c}}var Z="<<<BEGIN REPOSITORY TEXT>>>",q="<<<END REPOSITORY TEXT>>>";function I(t){let e=t;for(let o="";o!==e;)o=e,e=e.replaceAll(Z,"").replaceAll(q,"");return`${Z}
|
|
10
|
-
${e.replaceAll("{{","{ {")}
|
|
11
|
-
${q}`}function ee(t,e){return{location:I(String(t.location)),text:I(String(t.text)),usage:I(t.usage===null?e.bundleText("code-check-no-usage"):String(t.usage))}}function te(t){let{categoryBlock:e,categoryRules:o,impactBlock:r}=O(t),{codeSourceLabels:a,codeFindingNote:p,RULE:c,SPLIT_SCOPE_RULE:i,STRUCTURE_SCOPE_RULE:n,SUB_KIND_DEFS:s}=_(t),{bundleText:d}=t;function l(m,u,x){if(m==="finding-headlines")return{data:JSON.stringify(u.evidence),choiceCategories:C.join(", ")};if(m==="judge-code-prompt")return ee(u,t);if(m.startsWith("derive-findings"))return{...u,promptAgreement:S(x),pass:u.pass??null,codeSources:a(u.codeSources??[]),categories:e(x),categoryRules:o(x,"derive"),impacts:r()};if(m==="derive-structure"){let h=u.loadModesData,g=u.openStructuresData,y=u.findingsData;return{...u,findings:(y??[]).map(f=>({...f,category:f.category??"\u2014",excerpt:f.excerpt??"",site:f.site?{...f.site,line:f.site.line??"?"}:null,otherSites:(f.otherSites??[]).map(k=>({...k,line:k.line??"?",excerpt:k.excerpt??""})),question:f.question??"",options:f.fixes.map(k=>k.title)})),subKinds:s,scopeRule:n,open:R(g,{includeFiles:!1}),loadModes:h.map(f=>{let k=f.evidenceKind?d("load-evidence-skill-frontmatter"):f.evidence;return d("analysis-derive-structures-11",{v0:f.path,v1:f.mode,v2:f.unit??"no unit",v3:f.via,v4:k?` (${k})`:""})}).join(`
|
|
12
|
-
`)}}if(m==="scope-items"){let h=u.scopeRuleId==="structure"?n:u.scopeRuleId==="split"?i:"";return{items:u.items??[],scopeRule:h}}if(m==="scope-findings"){let h=u.codeSources,g=u.codeFiles,y=p(h);return{...u,system:y?d("scope-system-code")+`
|
|
13
|
-
|
|
14
|
-
`+y:c,code:g.length?d("code-evidence",{files:JSON.stringify(g)}):""}}return u}return{enrichRequestInputs:l,headlineFallbackQuestion:()=>t.description("finding-headlines-fallback-question")}}function ne(t,e){if(!Object.hasOwn(e.templates,t.template))throw new Error(`Unknown template: ${t.template}`);if(!Object.hasOwn(e.answerFormats,t.answerFormat))throw new Error(`Unknown answer format: ${t.answerFormat}`);let o=e.templates[t.template],r=t.limits??{};if(r.maxTokens!==void 0&&(!Number.isSafeInteger(r.maxTokens)||r.maxTokens<=0))throw new Error("Invalid maxTokens");let a=b(o.prompt,t.inputs,e.includes),p=o.promptBlocks?.map(c=>({text:b(c.text,t.inputs,e.includes),...c.cache?{cache:!0}:{}}));if(p&&p.map(c=>c.text).join("")!==a)throw new Error("Registered blocks must match the prompt");return{route:o.route??t.template,model:t.model,...o.system===void 0?{}:{system:b(o.system,t.inputs,e.includes)},prompt:a,...p?{promptBlocks:p}:{},schema:e.answerFormats[t.answerFormat],...r.maxTokens===void 0?{}:{maxTokens:r.maxTokens},...r.effort===void 0?{}:{effort:r.effort},...r.thinking===void 0?{}:{thinking:r.thinking}}}var B=class extends Error{name="InputBudgetError"};function nt(t){let{templates:e,descriptions:o}=t,{withDescriptions:r}=A(t),a=U(r,t.description);function p(){let s={prompt:e["check-evidence"],promptBlocks:[{text:"{{core}}"},{text:"{{claims}}"}]},d=z({"benchmark-judge":{system:e["benchmark-judge"],prompt:"{{data}}"},"judge-code-prompt":{prompt:e["judge-code-prompt"]},"derive-findings":{prompt:e["derive-findings"]},"derive-findings-legacy":{prompt:e["derive-findings-legacy"]},"derive-findings-no-outcome":{prompt:e["derive-findings-no-outcome"]},"derive-findings-legacy-no-outcome":{prompt:e["derive-findings-legacy-no-outcome"]},"derive-structure":{prompt:e["derive-structure"]},"structure-recheck":{system:e["structure-recheck-system"],prompt:e["structure-recheck"]},"derive-shape":{prompt:e["derive-shape"]},"scope-items":{prompt:e["scope-items"],system:e["scope-system"]},"scope-findings":{prompt:e["scope-findings"],system:"{{system}}"},"check-findings":{...s,system:e["check-findings"]},"check-findings-precision-v1":{...s,system:e["check-findings-precision-v1"]},"second-opinion":{...s,system:e["opinion-system"]},"explain-sources":{prompt:e["source-evidence"],system:e["explain-sources"]},"finding-headlines":{system:e["finding-headlines"],prompt:"{{data}}"}});return Object.fromEntries(Object.entries(d).map(([l,m])=>[l,{...m,...m.promptBlocks?{promptBlocks:E(m.promptBlocks,w({},{template:l}).breakpoints)}:{}}]))}function c(){return{templates:p(),includes:e,answerFormats:a,descriptions:o,policy:v()}}function i(s,d={}){let l=Object.hasOwn(v(),s.template)?$(s.template,s.answerFormat,d):s.answerFormat;return ie({...s,answerFormat:l},c(),d)}function n(s,d={}){let l=se(N(s,d),c());return{...l,schema:l.schema}}return{instructionRegistry:c,analysisModelRequest:i,analysisRequest:n,buildAnalysisCall:s=>se(s,c()),withDescriptions:r,callInputBytes:oe}}function oe(t){return Buffer.byteLength(t.prompt)+Buffer.byteLength(t.system??"")}function ie(t,e,o){let r=e.policy??v();if(!Object.hasOwn(r,t.template)||!r[t.template].answerFormats.includes(t.answerFormat))throw new Error("Unsupported template answer format");if(!Object.hasOwn(v(),t.template))return{...t,inputs:t.inputs};let a=K({templates:e.includes??{},descriptions:e.descriptions??{}}),{stageInputs:p}=Y(a),{enrichRequestInputs:c}=te(a);return{...t,inputs:c(t.template,p(t.template,t.inputs,o,e.templates),o)}}function se(t,e){let o=L.parse({template:t.template,inputs:t.inputs,answerFormat:t.answerFormat,model:t.model,...t.limits?{limits:t.limits}:{}}),{data:r,settings:a,maxInputBytes:p}=o.inputs,c=ne(ie({...o,inputs:r},e,a),e);if(p!==void 0&&oe(c)>p)throw new B("serialized evidence exceeds the priced input budget");let i=o.template==="judge-code-prompt"?T.object({path:T.string(),line:T.number()}).parse(r.at):o.template==="structure-recheck"?T.object({childId:T.string()}).parse(r):{};return{...c,...Object.hasOwn(v(),o.template)&&o.template!=="benchmark-judge"?{context:i}:{}}}export{ne as a,re as b,F as c,G as d,_ as e,Q as f,W as g,X as h,O as i,Y as j,te as k,B as l,nt as m,oe as n,se as o};
|