@counterfact-labs/cli 0.2.7 → 0.2.10
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/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/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/2CWULBP2.js +1 -0
- package/dist/analysis-core/chunks/2M55DR2J.js +35 -0
- package/dist/analysis-core/chunks/34NVU26H.js +1 -0
- package/dist/analysis-core/chunks/{RNTMH4MU.js → 5BTATES5.js} +1 -1
- package/dist/analysis-core/chunks/5UWDUYHF.js +1 -0
- package/dist/analysis-core/chunks/{6RWEWBHK.js → 5VQ4VYIP.js} +1 -1
- package/dist/analysis-core/chunks/66JRJPJC.js +1 -0
- package/dist/analysis-core/chunks/6JTHFDH3.js +1 -0
- package/dist/analysis-core/chunks/6VHZNBII.js +19 -0
- package/dist/analysis-core/chunks/6YCABS5T.js +1 -0
- package/dist/analysis-core/chunks/C77LGCKF.js +1 -0
- package/dist/analysis-core/chunks/CNQZLSAP.js +1 -0
- package/dist/analysis-core/chunks/DHVEGIU6.js +1 -0
- package/dist/analysis-core/chunks/HCPO6QPU.js +1 -0
- package/dist/analysis-core/chunks/I4F56VMG.js +1 -0
- package/dist/analysis-core/chunks/INVTU73D.js +1 -0
- package/dist/analysis-core/chunks/{6B2HILSY.js → JAPVLU4Z.js} +1 -1
- package/dist/analysis-core/chunks/KBTM5MBC.js +14 -0
- package/dist/analysis-core/chunks/LFJQ4YLP.js +3 -0
- package/dist/analysis-core/chunks/M5YWJY7P.js +1 -0
- package/dist/analysis-core/chunks/MKYLK6DB.js +1 -0
- package/dist/analysis-core/chunks/N2L4JMJE.js +1 -0
- package/dist/analysis-core/chunks/NCW5LJ5O.js +6 -0
- package/dist/analysis-core/chunks/P253B344.js +7 -0
- package/dist/analysis-core/chunks/PBHHWFR6.js +1 -0
- package/dist/analysis-core/chunks/Q5WR6B2H.js +2 -0
- package/dist/analysis-core/chunks/QPIBHTON.js +67 -0
- package/dist/analysis-core/chunks/QVXARKP7.js +1 -0
- package/dist/analysis-core/chunks/SJESFYBA.js +10 -0
- package/dist/analysis-core/chunks/SP6XFHNH.js +1 -0
- package/dist/analysis-core/chunks/TA2NIQAY.js +1 -0
- package/dist/analysis-core/chunks/UKX3A6AX.js +1 -0
- package/dist/analysis-core/chunks/VC3PYT2B.js +1 -0
- package/dist/analysis-core/chunks/VDUFPTDD.js +1 -0
- package/dist/analysis-core/chunks/VWRFSVLI.js +1 -0
- package/dist/analysis-core/chunks/VX6LYNXV.js +1 -0
- package/dist/analysis-core/chunks/W73WF226.js +1 -0
- package/dist/analysis-core/chunks/{FBTOOUPL.js → XVGLY4EO.js} +1 -1
- 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 +55 -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 +25 -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 +103 -23
- package/dist/cli/relay-failure.js +4 -4
- package/dist/cli/relay-preparation.js +47 -9
- 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 +8 -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/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/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
- /package/dist/analysis-core/chunks/{SKVEBOGA.js → 33EUZF25.js} +0 -0
|
@@ -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";
|
|
@@ -84,6 +85,10 @@ export class ConsoleClient {
|
|
|
84
85
|
}
|
|
85
86
|
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
87
|
}
|
|
88
|
+
async supportsSkippedFiles() {
|
|
89
|
+
const mode = await this.#send("/api/cli/checks/mode", {}, z.object({}), z.object({ skippedFiles: z.boolean().optional() }), 1024, { method: "GET", context: "start" });
|
|
90
|
+
return mode.skippedFiles === true;
|
|
91
|
+
}
|
|
87
92
|
create(input) {
|
|
88
93
|
return this.#lifecycle({ ...input, action: "create" }, consoleCreatedSchema);
|
|
89
94
|
}
|
|
@@ -140,9 +145,9 @@ export class ConsoleClient {
|
|
|
140
145
|
};
|
|
141
146
|
const destination = new URL(path, this.#url);
|
|
142
147
|
const request = (destination.protocol === "https:" ? httpsRequest : httpRequest)(destination, {
|
|
143
|
-
method: "POST", agent: false, rejectUnauthorized: true, maxHeaderSize: 16 * 1024,
|
|
148
|
+
method: options.method ?? "POST", agent: false, rejectUnauthorized: true, maxHeaderSize: 16 * 1024,
|
|
144
149
|
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",
|
|
150
|
+
"content-length": options.method === "GET" ? 0 : body.length, "accept-encoding": "identity",
|
|
146
151
|
...options.headers },
|
|
147
152
|
}, response => {
|
|
148
153
|
const status = response.statusCode ?? 0;
|
|
@@ -194,7 +199,7 @@ export class ConsoleClient {
|
|
|
194
199
|
// Use one wall-clock deadline: an idle timeout alone lets a trickling response run forever.
|
|
195
200
|
const timer = setTimeout(() => { finish(interrupted()); request.destroy(); }, this.#timeoutMs);
|
|
196
201
|
request.on("error", () => finish(interrupted()));
|
|
197
|
-
request.end(body);
|
|
202
|
+
request.end(options.method === "GET" ? undefined : body);
|
|
198
203
|
}).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
204
|
}
|
|
200
205
|
}
|
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.10",
|
|
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 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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as Z,B as st,C as at,D as rt,E as it,F as E,G as lt,H as dt,I as pt,J as ct,P as ft,R as mt,V as ht,W as ut,a as ae,b as De,c as Ge,d as We,e as $e,f as V,g as re,h as _,i as Ye,ia as gt,j,k as z,ka as Pt,l as Je,la as wt,m as Ve,ma as kt,n as Qe,na as St,o as K,p as Xe,q as Ze,r as ie,s as Q,t as et,u as tt,v as I,w as le,x as X,y as ot,z as nt}from"./IHAVDX4L.js";import{a as qe}from"./6RWEWBHK.js";import{a as J}from"./QDYMR6KS.js";import{a as Ue}from"./4H23CSUM.js";import{i as He}from"./K2GNDX3W.js";import{a as Ne}from"./FBTOOUPL.js";import{J as Ke,M as T,e as xe,f as A,g as Be,h as Ie,i as Le,m as Te,o as M,p as _e,q as je,v as Y,x as ze}from"./IVULXWQN.js";import{d as Me,f as Ae}from"./K5FUABWW.js";import{a as B}from"./326F4XNG.js";import{c as se}from"./MJGB25S5.js";import{n as $}from"./KGQYR62R.js";import{b as L,c as U}from"./2PSNOSJ2.js";import{Fb as Ce,I as ne,Ta as W,U as D,X as Re,Y as Ee,aa as G,e as Se,n as x,qa as k,sb as Oe,va as ye,z as Fe}from"./GOQVKWP3.js";import{a as ve}from"./2PZF54KH.js";import{f as oe,i as ge,j as Pe,m as we,n as ke}from"./JKWTHRUR.js";import{b as ue}from"./724WZMYW.js";import{c as be,e as O}from"./C6X5GDG4.js";import{posix as Kt}from"node:path";function bt(n,e,s){let a=new Set(e.entries.map(i=>i.path)),t=new Set(D(n,[...a])),f=Object.fromEntries(Object.entries(e.files).filter(([i])=>e.selected.some(o=>o.path===i&&o.readBytes===void 0))),r=new Set(Ee(n,[...a],f)),c=[],d=new Set;return{read:async i=>{if(r.has(i.path)||e.managedReadPaths?.includes(i.path)&&e.files[i.path]===void 0)return e.refused.push({path:i.path,reason:"unreadable"}),null;c.push(i);try{let o=await s(i);if(o!==null){if(d.has(i.path)){let l=k(n,{path:i.path,size:Buffer.byteLength(o),text:o},{...e.admission,purpose:"skill",route:"github",root:e.root,listing:a,managedFiles:e.files});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}if(x(n)||ue(n)){let l=k(n,{path:i.path,text:o},{...e.admission,purpose:"override",route:"github",root:e.root,listing:a,managedFiles:e.files});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}if(e.phase==="manifest"){let l=k(n,{path:i.path,size:Buffer.byteLength(o)},{...e.admission,purpose:"pointer",route:"github",root:e.root});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}return o}}catch(o){if(o instanceof G&&(o.reason==="secret-content"||x(n)||d.has(i.path)||t.has(i.path)))return e.refused.push({path:i.path,reason:o.reason}),null;if(e.profile==="hosted-import"&&!d.has(i.path)&&!t.has(i.path))throw o}return e.refused.push({path:i.path,reason:"unreadable"}),null},requestedReads:c,skillReads:d}}import{createHash as zt}from"node:crypto";function de(n){return zt("sha256").update(JSON.stringify(n.map(({path:e,ref:s,size:a})=>({path:e,ref:s,size:a})))).digest("hex")}function vt(n,e,s){return T(n)?{settings:Ae(n),commit:s??de(e),revisionKind:s===void 0?"listing":"commit",completed:[]}:void 0}function Ft(n,e,s){let a=n.agentPages;if(!a)return;let t=s??a.listingEntries??n.entries,f=a.revisionKind??(a.commit===de(a.listingEntries??n.entries)?"listing":"commit");if(f==="commit"&&e!==void 0&&a.commit!==e||f==="listing"&&a.commit!==de(t))throw new Error("stale-agent-page");return a.commit}function Rt(n,e,s){e.ranked??=Q(n,e.scan,new Map);let a=new Map([...ie(e.scan.plan),...Object.entries(e.agentPages?.actualSizes??{})]),t=ae(n,e.ranked,a,new Map,{files:{},...e.agentPages?{page:{commit:e.agentPages.commit,scope:e.root,continuation:s}}:{}});t.page&&(e.ranked={...e.ranked,agentPage:t.page,strong:t.strong,possible:t.window,notRead:t.notRead,notReadMore:t.notReadMore});let f=[...t.refused,...e.ranked.skippedFiles??[]];if(e.requestedPaths.push(...f.map(r=>r.path)),e.refused.push(...f),e.profile==="hosted-import"&&t.paths.length||t.page){let r=tt(n,[],t.paths,e.scan.plan);e.refused.push(...r.refused),e.profile==="hosted-import"?at(e,r.selected):(nt(n,e),Z(e,r.selected))}else X(n,e,t.paths,e.scan.plan);e.phase=e.selected.length?"files":"done"}function Et(n,e,s,a){let t={...e.agentPages.actualSizes};s.forEach((o,l)=>{a[l]!==null&&(t[o.path]=Buffer.byteLength(a[l]))}),e.agentPages={...e.agentPages,actualSizes:t};let f=new Map([...ie(e.scan.plan),...Object.entries(t)]),r=new Map(Object.entries(e.files).map(([o,l])=>[o,Buffer.byteLength(l)])),c=new Set(e.skillReferencePaths),d=new Set([...e.conventionPaths,...st(e),...c,...e.markerPath?[e.markerPath]:[]]);for(let o of s)if(d.has(o.path)&&t[o.path]!==void 0){let l=k(n,{path:o.path,size:t[o.path]},{purpose:c.has(o.path)?"skill":"pointer",route:"github",root:e.root,listing:new Set(e.entries.map(u=>u.path)),managedFiles:e.files}),p=ze(r).left+(r.get(o.path)??0);l.admitted&&t[o.path]<=p?r.set(o.path,t[o.path]):e.refused.push({path:o.path,reason:l.admitted?"total":l.reason})}let m=ae(n,e.ranked,f,r),i=new Set(m.paths);s.forEach((o,l)=>{a[l]!==null&&(i.has(o.path)||d.has(o.path)&&r.has(o.path)?e.files[o.path]=a[l]:e.refused.push(m.refused.find(p=>p.path===o.path)??m.skippedFiles?.find(p=>p.path===o.path)??{path:o.path,reason:"total"}))}),e.ranked={...e.ranked,agentPage:m.page,strong:m.strong,possible:m.window}}function pe(n){let e=n.ranked,s=e?.agentPage;if(!s||n.phase!=="done")return;let a=[...e.agentInventory.strong,...e.agentInventory.possible],t=new Set(s.selected),f=new Set(s.refusals.map(d=>d.id)),r=a.filter(d=>t.has(W(d.prompt))&&!f.has(W(d.prompt))&&n.files[d.prompt.path]===void 0),c=[...s.refusals,...r.map(d=>({id:W(d.prompt),reason:n.refused.find(m=>m.path===d.prompt.path)?.reason??"missing"}))];n.ranked={...e,strong:e.strong.filter(d=>n.files[d.prompt.path]!==void 0),possible:e.possible.filter(d=>n.files[d.prompt.path]!==void 0),agentPage:{...s,refusals:c,partial:c.length>0,estimatedInputBytes:Object.values(n.files).reduce((d,m)=>d+Buffer.byteLength(m),0)}}}async function yt(n,e,s){if(!x(n))return!1;let a=Re(n,e.entries.map(o=>o.path));if(!a.length)return!1;let t=new Set(a.flatMap(o=>o.agents)),f=new Map(e.selected.map(o=>[o.path,o])),r=new Set(e.selected.filter(o=>o.readBytes===void 0&&e.files[o.path]!==void 0).map(o=>o.path));e.managedReadPaths||(e.managedReadPaths=[],(e.scan||e.ranked)&&(delete e.scan,delete e.ranked,delete e.manifestReadPaths,e.phase!=="marker"&&(e.phase="scan")));let c=new Set([...e.managedReadPaths,...r]),d=e.entries.filter(o=>t.has(o.path)&&f.has(o.path)&&!c.has(o.path)),m=d.slice(0,I);if(!m.length)return!1;let i=await B(m,4,async o=>{let l=k(n,o,{...e.admission,purpose:"pointer",route:"github",root:e.root});return l.admitted?s(o):(e.refused.push({path:o.path,reason:l.reason}),null)});if(m.forEach((o,l)=>{i[l]!==null&&(e.files[o.path]=i[l],e.selected=e.selected.map(p=>p.path===o.path?o:p))}),e.managedReadPaths.push(...m.map(o=>o.path)),d.length>m.length){for(let o of Object.keys(e.files))!t.has(o)&&a.some(l=>be(o,l.folder)!==null)&&delete e.files[o];e.cursor=0,(e.phase==="done"||e.phase==="manifest")&&(e.phase="files")}return!0}async function Ot(n,e,s){if(e.marketplacePlanned)return!1;let a=new Set(D(n,e.entries.map(o=>o.path)));if(!e.selected.some(o=>a.has(o.path)))return!1;let t=new Set(e.marketplaceReadPaths),r=e.selected.filter(o=>a.has(o.path)&&!t.has(o.path)).slice(0,I),c=await B(r,4,async o=>{let l=k(n,o,{...e.admission,purpose:"definition",route:"github",root:e.root});if(!l.admitted)return e.refused.push({path:o.path,reason:l.reason}),null;let u=(o.readBytes===void 0?e.files[o.path]:void 0)??await s({path:o.path,size:o.size,ref:o.ref});if(u===null)return null;let g=k(n,{path:o.path,size:Buffer.byteLength(u),text:u},{...e.admission,purpose:"definition",route:"github",root:e.root});return g.admitted?u:(e.refused.push({path:o.path,reason:g.reason}),null)});r.forEach((o,l)=>{c[l]!==null?e.files[o.path]=c[l]:delete e.files[o.path]}),e.marketplaceReadPaths=[...t,...r.map(o=>o.path)];let d=new Map(r.flatMap((o,l)=>c[l]===null?[]:[[o.path,Buffer.byteLength(c[l])]]));e.agentPages&&d.size&&(e.agentPages={...e.agentPages,listingEntries:e.agentPages.listingEntries??e.entries}),e.entries=e.entries.map(o=>d.has(o.path)?{...o,size:d.get(o.path)}:o);let m,i=e.marketplaceSelection?new Set(e.marketplaceSelection):void 0;do{let o=new Set(e.marketplaceReadPaths.filter(h=>e.files[h]===void 0)),l=e.entries.filter(h=>!o.has(h.path)&&(!i||i.has(h.path))),p=e.profile==="local-analysis"?Be(n,l,e.root,{files:e.files}):_e(n,l,e.root,{files:e.files,mode:e.marketplaceMode}),u="selected"in p?p.selected.map(h=>h.path):p.selectedPaths,g=new Set(u),P=new Map(l.map(h=>[h.path,h]));e.selected=u.map(h=>P.get(h)),e.selectionRefused=p.refused,e.hosted&&"selectedPaths"in p&&(e.hosted.fallback=p,e.hosted.codeMode||(e.hosted.needsExtraction=p.needsExtraction)),m=Object.keys(e.files).filter(h=>a.has(h)&&!g.has(h));for(let h of m)e.refused.push(p.refused.find(w=>w.path===h)??{path:h,reason:"total"});for(let h of Object.keys(e.files))g.has(h)||delete e.files[h]}while(m.length);return e.conventionPaths=$(n,e.entries.filter(o=>!a.has(o.path)||e.files[o.path]!==void 0).map(o=>o.path),e.root,{files:e.files}).files.filter(o=>o.role!=="reference").map(o=>o.path),e.cursor=0,e.marketplacePlanned=!e.selected.some(o=>a.has(o.path)&&!e.marketplaceReadPaths.includes(o.path)),r.length>0||!e.marketplacePlanned}function ce(n,e){let{plan:s,entries:a}=e,t=s.profile==="local-analysis"?s.context.dir??"":e.root??"",f=s.readers.find(i=>i.id==="marker")?.claim.wants[0],r=s.readers.some(i=>i.id==="code-scan"),c=new Map(a.map(i=>[i.path,i])),d=s.profile==="local-analysis"?s.selection.selected:s.selection.selectedPaths.flatMap(i=>c.has(i)?[c.get(i)]:[]),m=Te(n)?M(n,{phase:"start",root:t,paths:a.map(i=>i.path),scanFlag:!!f||r}):void 0;return{...T(n)?{agentPages:vt(n,a,e.commit)}:{},version:1,profile:s.profile,root:t,entries:a,selected:[...d],..."mode"in s?{marketplaceMode:s.mode}:{},..."selectionPaths"in s?{marketplaceSelection:s.selectionPaths}:{},conventionPaths:s.profile==="hosted-import"||T(n)?$(n,a.map(i=>i.path),t).files.filter(i=>i.role!=="reference").map(i=>i.path):[],...e.admission?{admission:e.admission}:{},selectionRefused:s.selection.refused,requestedPaths:[],refused:[],files:{},cursor:0,treeTruncated:e.treeTruncated??!1,...s.profile==="hosted-import"?{hosted:{fallback:structuredClone(s.selection),weakCodeFallback:n.CF_IMPORT_WEAK_CODE_FALLBACK!=="0",codeMode:!1,needsExtraction:s.selection.needsExtraction}}:{},decision:m??(f?{kind:"marker",markerPath:f,scanIfBare:r}:{kind:"settled",markerPath:null,markerKind:null,scan:r}),phase:f?"marker":r?"scan":"files"}}async function Ct(n,e,s){if(e.version!==1)throw new Error("unsupported-import-checkpoint");e.agentPages&&(n=e.agentPages.settings,Ft(e,s.commit));let a=le(n,e.profile),t={...e,selected:[...e.selected],files:{...e.files},requestedPaths:[...e.requestedPaths],refused:[...e.refused],...e.hosted?{hosted:{...e.hosted}}:{},...e.managedReadPaths?{managedReadPaths:[...e.managedReadPaths]}:{}},{read:f,requestedReads:r,skillReads:c}=bt(a,t,o=>s.read(o));if(await Ot(a,t,f))return E(a,t,r);if(await yt(a,t,f))return E(a,t,r);if(it(a,t),t.phase==="done")return s.resolvedCode&&rt(t,s.resolvedCode),E(a,t,r);if(t.phase==="manifest")return await lt(a,t,f),pe(t),E(a,t,r);if(t.phase==="marker"&&t.decision.kind==="marker"){let o=t.decision,l=o.markerPath,p=t.entries.find(g=>g.path===l);if(t.profile==="hosted-import"){let g=k(a,p,{purpose:"pointer",route:"github",root:t.root});if(!g.admitted)return t.refused.push({path:l,reason:g.reason}),t.decision={kind:"settled",markerPath:null,markerKind:null,scan:o.scanIfBare},t.phase=o.scanIfBare?"scan":"files",E(a,t,r)}X(a,t,[l],t.entries);let u=await f(p);if(u!==null&&(t.files[l]=u),t.decision=M(a,{phase:"read",pending:o,text:u}),t.markerPath=l,t.markerKind=t.decision.markerKind,t.markerKind!=="bare"){let g=t.profile==="hosted-import"?await s.listing():{entries:t.entries,truncated:!1};t.treeTruncated||=g.truncated;let P=await dt(a,{config:Le(u).config,markerDir:l.split("/").slice(0,-1).join("/"),selected:t.profile==="hosted-import"?[]:t.selected,admission:{...t.admission,root:t.root||void 0},modelReader:!1,priorRefused:t.refused,refusalMode:"append",requestedMode:"kept-and-refused",listing:async()=>g.entries});if(t.requestedPaths.push(...P.requestedPaths),t.refused=P.refused,t.agentPages&&P.selected){let h=new Set(P.requestedPaths);t.conventionPaths=[...new Set([...t.conventionPaths,...P.selected.filter(w=>h.has(w.path)).map(w=>w.path)])]}t.profile==="hosted-import"?Z(t,P.selected??[]):P.selected&&(t.selected=P.selected)}if(t.phase=t.decision.scan?"scan":"files",t.profile!=="hosted-import"||t.markerKind!=="bare"||t.decision.scan)return E(a,t,r)}if(t.phase==="scan"){if(!t.scan){let o=Qe(a,t.entries,t.root,!0,t.decision.kind==="settled"?t.decision.scanPaths:void 0);t.scan=o.state,t.refused.push(...o.refused)}if(!K(t.scan)){let o=await et(a,t.scan,f,{modelReader:!1,alreadyRead:new Map,size:{batch:Je,parallel:4}});t.scan=o.scan,o.selection&&(t.ranked=o.selection.ranked)}return K(t.scan)&&Rt(a,t),E(a,t,r)}if(ne(a))for(let o of t.skillReferencePaths??[])c.add(o);let d=t.selected.slice(t.cursor,t.cursor+I),m=d.filter(o=>t.files[o.path]===void 0),i=await B(m,4,f);if(t.agentPages&&t.ranked&&t.scan?Et(a,t,m,i):m.forEach((o,l)=>{i[l]!==null&&(t.files[o.path]=i[l])}),t.cursor+=d.length,ne(a)){let o=Object.fromEntries(Object.entries(t.files).filter(([h])=>t.selected.some(w=>w.path===h&&w.readBytes===void 0))),l=je(a,{entries:t.entries,selected:t.selected,files:o,root:t.root,admission:t.admission,referencePaths:t.skillReferencePaths});t.refused=L(t.refused,l.refused);for(let h of l.refused)c.has(h.path)&&delete t.files[h.path];if(t.cursor<t.selected.length)return E(a,t,r);let p=new Map(t.selected.map(h=>[h.path,h])),u=l.paths.filter(h=>!p.has(h)||p.get(h).readBytes!==void 0),g=new Set(u.filter(h=>p.has(h)));t.cursor-=t.selected.slice(0,t.cursor).filter(h=>g.has(h.path)).length,t.selected=t.selected.filter(h=>!g.has(h.path));for(let h of g)delete t.files[h];t.requestedPaths.push(...u),u.length&&(t.skillReferencePaths=[...t.skillReferencePaths??[],...u]);let P=new Map(t.entries.map(h=>[h.path,h]));t.selected.push(...u.map(h=>{let w=P.get(h);return{path:h,size:w.size,ref:w.ref}})),ot(t,u,"fallback")}return t.cursor>=t.selected.length&&(t.phase=xe(a)&&t.ranked||x(a)?"manifest":"done"),pe(t),E(a,t,r)}async function ee(n,e){let s=ce(n,e),a;do a=await Ct(n,s,{listing:async()=>({entries:e.entries,truncated:!1}),read:e.read}),s=a.state;while(s.phase!=="done");let t={};return s.markerPath!==void 0&&(t.markerPath=s.markerPath,t.markerKind=s.markerKind),s.ranked!==void 0&&(t.ranked=s.ranked,t.scan=s.scan),{files:a.files,settled:a.settled,skippedFiles:a.refused,...t}}function Nt(n){return n.CF_IMPORT_PROPOSAL!=="0"}var Ht=new Set(["secret","secret-content","out-of-scope"]);async function qt(n,e,s,a,t,f,r){let c={...e.admission,purpose:"proposal",route:"local-folder"},d=k(n,a??{path:s},c);if(!d.admitted)return{reason:d.reason};if(!a)return{reason:r??"missing"};if(a.size>f)return{reason:"allowance"};try{let m=t??await(e.proposalRead??e.read)({...a,readBytes:void 0});if(m===null)return{reason:r??"unreadable"};let i=Buffer.byteLength(m),o=k(n,{path:s,size:i,text:m},c);return o.admitted?i>f?{reason:"allowance"}:{text:m}:{reason:o.reason}}catch(m){return m instanceof G?{reason:m.reason,invalidates:Ht.has(m.reason)}:{reason:"unreadable"}}}async function Ut(n,e,s,a,t){let f=new Set(a.map(p=>p.path)),r=new Set(t.map(p=>p.path)),c=new Map(e.entries.map(p=>[p.path,p])),d=a.map(p=>({...c.get(p.path),readBytes:void 0})),m=p=>!f.has(p.path)&&!r.has(p.path),i=[...e.selection.selected.filter(m),...d],o=a.length||t.length?{...e.selection,selected:i,totalBytes:i.reduce((p,u)=>p+(u.readBytes??u.size),0),refused:e.selection.refused.filter(p=>!f.has(p.path))}:e.selection,l=e.evidence??{};if(t.length){let p=e.entries.filter(w=>!r.has(w.path)),{ranked:u,scan:g,markerPath:P,markerKind:h}=await ee(n,{entries:p,admission:e.admission,read:async w=>Object.hasOwn(s,w.path)?s[w.path]:null,plan:Y(n,{profile:"local-analysis",listing:p,selection:o})});l={ranked:u,scan:g,markerPath:P,markerKind:h}}return{...l,files:s,selection:o,settled:[...e.settled.filter(m),...d],skippedFiles:(e.skippedFiles??[]).filter(p=>!f.has(p.path)),...t.length?{invalidated:t}:{}}}async function xt(n,e){if(!Nt(n)||!e.proposal)return;let s={...e.files},a=new Map(e.entries.map(o=>[o.path,o])),t=new Map(e.unavailable?.map(o=>[o.path,o.reason])),f={},r=[],c=[],d=new Set,m=new Set(e.settled.filter(o=>o.readBytes===void 0).map(o=>o.path)),i=Object.values(s).reduce((o,l)=>o+Buffer.byteLength(l),0);for(let o of e.proposal.files){let l=Kt.normalize(o.path.replace(/\\/g,"/")),p=Object.hasOwn(s,l)?Buffer.byteLength(s[l]):0,u=!e.proposalRead&&m.has(l)&&Object.hasOwn(s,l)?s[l]:void 0,g=d.has(l)?{reason:"duplicate"}:await qt(n,e,l,a.get(l),u,Fe.codeAgent.importBytes-i+p,t.get(l));if(d.add(l),"text"in g)i+=Buffer.byteLength(g.text)-p,s={...s,[l]:g.text},c.push({...o,path:l});else{let P=g.reason==="wrong-type"?"coding-guide":g.reason;f[P]=(f[P]??0)+1,g.invalidates&&Object.hasOwn(s,l)&&(i-=p,delete s[l],r.push({path:l,reason:g.reason}))}}return{...await Ut(n,e,s,c,r),proposal:{...e.proposal,files:c},rejectedByReason:f}}import{posix as fe}from"node:path";function Dt(n,e={}){return(n.CF_CHOOSE_AGENT??e.CF_CHOOSE_AGENT)!=="0"}function At(n,{codeAgents:e,conventions:s,root:a,selection:t}){if(t?.kind==="file"||Se(n)||!Dt(n))return;let f=new Set(e.map(i=>i.prompt.path)),r=new Map(s.agentScopes?.map(i=>[i.key,i.folder])),c=Gt(e);if(c.push(...s.agents.flatMap(i=>Ke(i)?(i.definitionPaths??[]).filter(o=>i.key===null||!f.has(o)).map(o=>({folder:Wt(i,o,r,a),reason:o})):[])),c.some(i=>c.every(o=>Mt(i.folder,o.folder))))return;let m=c.filter((i,o)=>!c.some((l,p)=>p!==o&&Mt(l.folder,i.folder)&&(l.folder!==i.folder||p<o)));return{kind:m.length?"choose_agent":"no_agent",candidates:m}}function Mt(n,e){return n==="."||e===n||e.startsWith(`${n}/`)}function te(n){let e=fe.dirname(n[0]);for(let s of n.slice(1))for(;e!=="."&&s!==e&&!s.startsWith(`${e}/`);)e=fe.dirname(e);return e}function Gt(n){let e=n.map(()=>new Set),s=new Map(n.map((r,c)=>[r.unitKey,c])),a=new Map,t=(r,c)=>{c!==void 0&&(e[r].add(c),e[c].add(r))};n.forEach((r,c)=>{t(c,a.get(r.prompt.path)),a.set(r.prompt.path,c);for(let d of r.links??[])t(c,s.get(d.to))});let f=new Set;return n.flatMap((r,c)=>{if(f.has(c))return[];let d=[c],m=[];for(;d.length;){let i=d.pop();f.has(i)||(f.add(i),m.push(n[i].prompt.path,...n[i].ownFiles.map(o=>o.path)),d.push(...e[i]))}return[{folder:te(m),reason:r.prompt.path}]})}function Wt(n,e,s,a){return n.key!==null?s.get(n.key)||fe.dirname(e):(s.get(null)??a)||"."}function Bt(n,e=[],s){return e.find(a=>Ge(a.key,s)===n.id)?.folder??te(n.files.length?n.files.map(a=>a.path):[n.sourceRef?.path??"."])}function $t(n,e,s,a){let t=new Set(n.flatMap(c=>c.files.map(d=>d.path))),f=new Set(e.flatMap(c=>c.files.map(d=>d.path))),r=e.map(c=>Bt(c,s,a));return c=>f.has(c)||!t.has(c)&&r.some(d=>d==="."||d===""||c.startsWith(`${d}/`))}function Yt(n,e,s){let a=Object.fromEntries(Object.entries(e.files).filter(([o])=>s(o))),t=e.selection.selected.filter(o=>Object.hasOwn(a,o.path)),f=e.settled.filter(o=>s(o.path)),r=e.selection.refused.filter(o=>s(o.path)),c=e.selection.readingNotes,d=c?{instruction:c.instruction.filter(s),code:c.code.filter(s),agents:c.agents.filter(s)}:void 0,m=A(n,d??{instruction:[],code:[],agents:[]},f),i={...e.selection,selected:t,refused:r,readingNotes:d,skippedNote:m,totalBytes:t.reduce((o,l)=>o+(l.readBytes??l.size),0)};return{files:a,selection:i,settled:f,skippedFiles:e.skippedFiles.filter(o=>s(o.path)),invalidated:e.invalidated?.filter(o=>s(o.path))}}function Jt(n,e,s,a=[],t){let f=s??te([...e]),r=n.filter(i=>i.kind==="agent").map(i=>{let o=Bt(i,a,t),l=o==="."||o===""||f===o||f.startsWith(`${o}/`);return{node:i,overlap:new Set(i.files.filter(p=>e.has(p.path)).map(p=>p.path)).size,containment:l?o.split("/").filter(p=>p&&p!==".").length+1:0}}).filter(i=>i.overlap||i.containment);r.sort((i,o)=>o.overlap-i.overlap||o.containment-i.containment);let[c,d]=r,m=!!c&&c.overlap===d?.overlap&&c.containment===d?.containment;return{target:m?void 0:c?.node,overlapping:r.filter(i=>i.overlap).map(i=>i.node),tied:m?r.filter(i=>i.overlap===c.overlap&&i.containment===c.containment).map(i=>i.node):[]}}function Vt(n,e,s){let a=new Set(n.map(r=>r.path)),t=!!s&&!n.some(r=>r.path===s.path&&r.role==="system prompt"),f=t?n.filter(r=>r.path!==s.path).map(r=>r.role==="system prompt"||r.role==="soul"?{...r,role:"reference"}:r):[...n];return f.push(...e.filter(r=>!a.has(r.path)&&r.path!==s?.path).map(r=>({path:r.path,role:r.role==="tools"||r.role==="config"?r.role:"reference",label:null}))),t&&f.unshift({path:s.path,role:"system prompt",label:null}),{files:f,promptChanged:t}}function Qt(n,e){let s=new Map(n.map(a=>[a.label,a]));for(let a of e)s.has(a.label)||s.set(a.label,a);return[...s.values()]}function Xt(n,e,s,a,t){return a.filter(f=>f.role==="tools"&&(/\.json$/i.test(f.path)||ve(f.path)==="js")).flatMap(f=>Oe(n,e,s.files,{toolsPath:/\.json$/i.test(f.path)?f.path:null,toolsTsPath:/\.json$/i.test(f.path)?null:f.path,cliPath:null,mcpPath:null},t))}function Zt(n,e,s,a,t,f){let r=Vt(a?.files??[],s,t),d={...a??{id:De("",e.ruleResult.fragment.nodes.map(m=>m.id),()=>{})("agent"),kind:"agent",desc:re(null,r.files,!1),meta:null,tools:[],sourceRef:null},label:e.proposalSources.proposal.agentName,files:r.files,tools:Qt(a?.tools??[],Xt(n,e.repoKey,e.proposalSources,s,f))};return r.promptChanged&&t&&(d.desc=re(t.path,r.files,!1),d.sourceRef={path:t.path,line:null}),{agent:d,promptChanged:r.promptChanged}}function eo(n,e,s,a,t){let{target:f,overlapping:r,tied:c}=s,{fragment:d}=n,m=new Set([e.id,...(t?[...r,...c]:d.nodes).map(p=>p.id)]);for(let p=-1;p!==m.size;){p=m.size;for(let u of d.edges)m.has(u.from)&&m.add(u.to)}let i=d.nodes.filter(p=>m.has(p.id)).map(p=>p===f?e:p);f||i.push(e);let o=d.edges.filter(p=>m.has(p.from)&&m.has(p.to)),l=n.codeAgents?.filter(p=>m.has(p.unitKey)).flatMap(p=>p.unitKey!==f?.id?[p]:a?[]:[{...p,name:e.label,ownFiles:e.files}]);return{fragment:{...d,nodes:i,edges:o},...l?{codeAgents:l}:{}}}function to(n,e,s){let a=new Set(e.map(r=>r.path)),t=new Set([...n.flatMap(r=>r.files.map(c=>c.path)),...a]),f=a.size;return{fromProposal:f,fromRulesOnly:t.size-f,rejected:Object.values(s).reduce((r,c)=>r+c,0),rejectedByReason:s}}function It(n){return n.files.some(e=>e.role==="system prompt"||e.role==="soul")}function oo(n,e,s){if(e.some(t=>t.kind==="agent"&&!It(t)))return new Set;let a=new Set([V({code:"no-prompt",detail:"no-conventions"},n),V({code:"no-prompt"},n),V({code:"no-prompt",folderAgentsFound:!0},n)]);return s!==void 0&&a.add($e(n,{scanned:s})),a}function Lt(n,e){let{ruleResult:s,proposalSources:a,root:t,repoKey:f,scopes:r,scanned:c,agentChoice:d}=e,m=s,{files:i,selection:o,settled:l,skippedFiles:p,invalidated:u}=a,g=[...s.warnings],P=a.proposal.files.map(b=>({...b,path:O(b.path,t)})),h=P.find(b=>b.role==="prompt"),w=!1;if(P.length){let b=Jt(m.fragment.nodes,new Set(P.map(y=>y.path)),h?.path,r,t);if(b.target||h){let{agent:y,promptChanged:R}=Zt(n,e,P,b.target,h,g),N=d?.kind==="choose_agent";m={...m,...eo(s,y,b,R,N)},N&&({files:i,selection:o,settled:l,skippedFiles:p,invalidated:u}=Yt(n,a,$t(s.fragment.nodes,m.fragment.nodes,r,t))),w=It(y);let H=oo(f,m.fragment.nodes,c);g=g.filter(q=>!H.has(q))}}return{...m,files:i,selection:o,settled:l,skippedFiles:p,invalidated:u,...d&&!w?{agentChoice:d}:{},warnings:g,proposalCounts:to(m.fragment.nodes,P,a.rejectedByReason)}}function Yn(n){let e=[],s=!1,a=Promise.resolve();return t=>new Promise((f,r)=>{e.push({entry:t,resolve:f,reject:r}),!s&&(s=!0,queueMicrotask(()=>{let c=e;e=[],s=!1,a=a.then(async()=>{try{let d=await n(c.map(m=>m.entry));if(d.length!==c.length)throw new Error("bad_request");c.forEach((m,i)=>m.resolve(d[i]))}catch(d){c.forEach(m=>m.reject(d))}})}))})}async function Jn(n,e){let s=v=>e.localListing?v.filter(C=>k(n,C,{purpose:"listing",route:"local-folder",...e.admission}).admitted):v,a=s(e.entries),t=Y(n,{profile:"local-analysis",listing:a,selection:e.selection}),f=await ee(n,{entries:a,read:e.read,admission:e.admission,plan:t}),{files:r,settled:c,skippedFiles:d,...m}=f,i=await xt(n,{proposal:e.proposal,entries:a,read:e.read,proposalRead:e.proposalRead,admission:e.admission,files:r,settled:c,skippedFiles:d,selection:t.selection,unavailable:e.proposalRefusals,evidence:m}),{files:o,settled:l,skippedFiles:p}=i??f,u=_({...i??m,key:e.repoKey,files:o},t.context.flags,void 0,{markerPolicy:"any-read"}),g=i?.selection??t.selection,P;if(Me(n)&&e.repository){let v=e.repository,C=await Ne(n,{selected:{files:o,listedPaths:a.map(S=>S.path),fallbackName:Ye(e),skills:!0},selection:g,codeAgentsFound:We(n,u?.resolved,o),port:e.localListing?{context:()=>v.context(),read:(S,F)=>v.read(S,F),finish:S=>v.finish?.(S),list:async()=>{let S=await v.list();return{...S,entries:s(S.entries)}}}:v}),jt=new Set(Object.keys(o).map(S=>O(S,C.root)));if(o=C.files,g=C.selection,P=C.root,P!==void 0){p=p.map(F=>({...F,path:O(F.path,P)})),l=l.map(F=>({...F,path:O(F.path,P)}));let S=new Set(l.map(F=>F.path));l.push(...g.selected.filter(F=>!S.has(F.path)&&Object.hasOwn(o,F.path)))}p=L(p,C.skippedFiles).filter(S=>jt.has(S.path)||!Object.hasOwn(o,S.path))}let h={repoKey:e.repoKey,files:o,listedPaths:a.map(v=>O(v.path,P)),...P!==void 0?{root:P}:{},forLocal:!0,code:u},w=j(n,h),b=z(n,w),y=At(n,{codeAgents:b.codeAgents??[],conventions:w.conventions,root:P,selection:e.membership}),R=i?Lt(n,{ruleResult:b,proposalSources:{...i,files:o,selection:g,settled:l,skippedFiles:p,invalidated:i.invalidated?.map(v=>({...v,path:O(v.path,P)}))},root:P,repoKey:e.repoKey,scopes:w.conventions.agentScopes,scanned:u?.resolved?.scanned,agentChoice:y}):void 0,{settled:N,invalidated:H,...q}=R??{...b,settled:l,invalidated:void 0};R&&(o=R.files,g=R.selection,l=N,p=R.skippedFiles);let me=g.readingNotes?A(n,g.readingNotes,l):g.skippedNote,he=R?R.agentChoice:y;return{...q,...he?{agentChoice:he}:{},files:o,...P!==void 0?{root:P}:{},skippedFiles:H?.length?L(p,H):p,...R?{proposalCounts:R.proposalCounts}:{},warnings:[...new Set([...q.warnings,...me?[me]:[],...U(p)])],selection:g}}var no=new Set(pt);function Xn(n,e){for(let a of[...Object.keys(e.set),...e.clear])if(!no.has(a))throw new Error(`Unknown analysis field: ${a}`);let s={...n,...e.set};for(let a of e.clear)s[a]=void 0;return s}async function so(n,e,s){let a=Object.entries(e).map(([f,r])=>({path:f,size:Buffer.byteLength(r),ref:f})),t=Ve(n,a,s.root,!1,s.scanPaths);for(;!K(t);)t=await Xe(t,async f=>e[f.path]??null);return{scan:Q(n,t),summary:Ze(t)}}async function Tt(n,e,s){let{repoKey:a,root:t,agentConfigurations:f,codingGuides:r,forLocal:c}=s,d=s.flags??Ie(n),m=Object.keys(e),i=M(n,{phase:"start",paths:m,root:t,scanFlag:d.scan}),o=i.kind==="marker"?M(n,{phase:"read",pending:i,text:e[i.markerPath]??null}):i,l=o.kind==="off"?null:o.markerPath,p=o.kind==="off"?null:o.markerKind;if(o.kind==="off"||!o.scan){let b=_({key:a,files:e,markerPath:l,markerKind:p},d,void 0,{markerPolicy:"any-read"});return{...z(n,j(n,{repoKey:a,files:e,root:t,agentConfigurations:f,codingGuides:r,forLocal:c,code:b})),scanned:!1,resolved:null}}let{scan:u,summary:g}=await so(n,e,{repoKey:a,root:t,scanPaths:o.scanPaths}),P=_({key:a,files:e,ranked:u,scan:g,markerPath:l,markerKind:p},d,void 0,{markerPolicy:"any-read"});return{...z(n,j(n,{repoKey:a,files:e,root:t,agentConfigurations:f,codingGuides:r,forLocal:c,code:P})),scanned:!0,resolved:P.resolved}}async function _t(n,e){let{state:s,settings:a}=n;if(!ft(a,s).splitCheck||!s.splitEstimateBase)return{next:"inspecting",set:{repoCursor:0},clear:[]};let f=n.execution.preparation?.capUsd??s.splitEstimateBase.capUsd,r={...s.splitEstimateBase,capUsd:f};ke(r,e.progress.log);let c=gt(a,s),d={next:"inspecting",set:{repoCursor:0,splitCheckPriced:!0,splitFindingsPriced:!0},clear:["splitEstimateBase"]};if(!c.length)return d;let m=qe(J(await e.instructions())),i=c.reduce((g,{inventory:P})=>g+oe(Buffer.byteLength(wt({tools:m},{...P,findings:[]}).prompt))+oe(m.SHAPE_FINDINGS_INPUT_BYTES),0),o=r.lines.find(g=>g.label==="Scope check"),l=se(a,{template:"scope-findings"},"Scope check",Ue.mechanical,(o?.inputTokens??0)+c.length*St,(o?.outputTokens??0)+c.length*kt),p=r.lines.map(g=>g.label==="Scope check"?l:g);o||p.push(l),p.push(se(a,{template:"derive-shape"},"Split check",Pt,i,c.length*He));let u=ge(p,f);return Pe(u)?(d.estimate=r,d.clear.push("splitCheckPriced","splitFindingsPriced"),delete d.set.splitCheckPriced,delete d.set.splitFindingsPriced,e.progress.log({level:"warn",code:"analysis.split_check_over_cap",counts:{totalUsd:u.totalUsd,capUsd:u.capUsd}}),d.set.warnings=[...s.warnings??[],we]):d.estimate=u,d}var Os=async(n,e)=>{e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let{state:s,settings:a}=n,t=s.repos??[];await ye(a,s,e.readers);let f=s.repoCursor??0;if(f>=t.length)return _t(n,e);let r=t[f],c=n.execution.forLocal,d=c?s.mapped?.[f]?{fragment:ct(s,f),warnings:[]}:await Tt(a,r.files??{},{repoKey:r.key,root:r.root,agentConfigurations:r.agentConfigurations??{},forLocal:!0}):void 0,m=d?(()=>{let u=Ce(d.fragment,r.key);return{...u,warnings:[...d.warnings,...u.warnings]}})():ut(a,r,mt(a,s),s.modelReader??!1,s.projectAgents,J(await e.instructions()).bundleText("model-reader-runtime-prompt")),i=!c&&r.sourceReadNotes?A(a,r.sourceReadNotes,r.selected??[],r.root):void 0,o=c?[]:U((r.refused??[]).filter(u=>u.reason==="secret-content")),l="virtualFiles"in m?m.virtualFiles:void 0,p=[...s.mapped??[]];return p[f]=m.fragment,{next:"mapping",clear:[],set:{...l?{repos:t.map((u,g)=>g===f?{...u,files:{...u.files,...l}}:u)}:{},mapped:p,warnings:[...s.warnings??[],...i?[`${r.key}: ${i}`]:[],...o,...m.warnings,...ht(r)],repoCursor:f+1}}};export{Nt as a,Yn as b,Jn as c,Xn as d,Os as e};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var r=t=>t.CF_UNTRUSTED_CONTENT_CHECK!=="0";function n(t){return t.CF_FINDING_BETTER_AS_CODE==="1"}var o=["contradiction","ambiguity","bypassable_requirement","stale_fact","description_mismatch","ungoverned_tool","untrusted_instructions","better_as_code"];function i(t){return o.filter(e=>(e!=="untrusted_instructions"||r(t))&&(e!=="better_as_code"||n(t)))}function _(t){return!n(t)&&r(t)}var p={contradiction:"Contradiction",ambiguity:"Ambiguity",bypassable_requirement:"Bypassable requirement",stale_fact:"Stale fact",description_mismatch:"Description mismatch",ungoverned_tool:"Ungoverned tool",untrusted_instructions:"Untrusted instructions",better_as_code:"Better as code",structure:"Structure",prompt_quality:"Prompt quality"};function l(t){return["contradiction","bypassable_requirement","stale_fact","description_mismatch","ungoverned_tool","untrusted_instructions"].includes(t)?2:1}function s(t){return typeof t=="string"&&o.includes(t)}function m(t,e){return s(t)&&i(e).includes(t)}export{r as a,n as b,i as c,_ as d,p as e,l as f,s as g,m as h};
|