@counterfact-labs/cli 0.2.5 → 0.2.7

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.
Files changed (82) hide show
  1. package/README.md +20 -0
  2. package/bundle/client-release.json +1 -1
  3. package/dist/adapters/completion-lock.js +95 -0
  4. package/dist/adapters/completion.js +132 -17
  5. package/dist/adapters/entry-files.js +126 -0
  6. package/dist/adapters/entry-selection.js +45 -0
  7. package/dist/adapters/files.js +2 -1
  8. package/dist/adapters/results.js +10 -2
  9. package/dist/adapters/selection.js +104 -0
  10. package/dist/adapters/settings.js +29 -2
  11. package/dist/analysis-core/analysis/schemas.js +1 -1
  12. package/dist/analysis-core/chunks/2PZF54KH.js +10 -0
  13. package/dist/analysis-core/chunks/{OPMA32A6.js → 6RWEWBHK.js} +1 -1
  14. package/dist/analysis-core/chunks/{PECX3OXB.js → 7NEWZ74F.js} +1 -1
  15. package/dist/analysis-core/chunks/{6QY5BV5B.js → CGCJN73D.js} +1 -1
  16. package/dist/analysis-core/chunks/CWYVUGG4.js +1 -0
  17. package/dist/analysis-core/chunks/{3JWEFCTJ.js → FBTOOUPL.js} +1 -1
  18. package/dist/analysis-core/chunks/GOQVKWP3.js +32 -0
  19. package/dist/analysis-core/chunks/IHAVDX4L.js +66 -0
  20. package/dist/analysis-core/chunks/IVULXWQN.js +21 -0
  21. package/dist/analysis-core/chunks/K5FUABWW.js +1 -0
  22. package/dist/analysis-core/chunks/KGQYR62R.js +7 -0
  23. package/dist/analysis-core/chunks/PY5M22CL.js +1 -0
  24. package/dist/analysis-core/chunks/{YDBO7P4X.js → RNTMH4MU.js} +1 -1
  25. package/dist/analysis-core/chunks/RUVMFAST.js +1 -0
  26. package/dist/analysis-core/chunks/S27VIQMZ.js +1 -0
  27. package/dist/analysis-core/chunks/{5DGPLXYB.js → SLJ6CW7W.js} +1 -1
  28. package/dist/analysis-core/chunks/{STI4JE7L.js → UEORNVQB.js} +1 -1
  29. package/dist/analysis-core/chunks/{X7WZAA7S.js → WYLIV2P2.js} +1 -1
  30. package/dist/analysis-core/contracts/analysis-selection.js +1 -0
  31. package/dist/analysis-core/contracts/module-resolution.js +1 -0
  32. package/dist/analysis-core/contracts/relay-analysis.js +1 -1
  33. package/dist/analysis-core/contracts/requests.js +1 -1
  34. package/dist/analysis-core/contracts/selection-paths.js +1 -0
  35. package/dist/analysis-core/conventions/analysis-fit.js +1 -1
  36. package/dist/analysis-core/conventions/file-admission.js +1 -1
  37. package/dist/analysis-core/import/calls/modules.js +1 -0
  38. package/dist/analysis-core/import/outside-loader-sources.js +1 -1
  39. package/dist/analysis-core/index.js +3 -3
  40. package/dist/analysis-core/requests/local-plan.js +1 -1
  41. package/dist/analysis-core/requests/registry.js +1 -1
  42. package/dist/analysis-core/requests/template-version.js +1 -1
  43. package/dist/analysis-core/requests/tools.js +1 -1
  44. package/dist/analysis-core/settings.js +1 -1
  45. package/dist/analysis-core/stages/engine-entry.js +1 -1
  46. package/dist/cli/agent-folder.js +3 -3
  47. package/dist/cli/analysis-selection.js +91 -0
  48. package/dist/cli/commands/analyze.js +34 -8
  49. package/dist/cli/commands/balance.js +6 -3
  50. package/dist/cli/completion-delivery.js +63 -0
  51. package/dist/cli/completion-recovery.js +68 -14
  52. package/dist/cli/context.js +4 -1
  53. package/dist/cli/main.js +21 -9
  54. package/dist/cli/mcp-failure.js +8 -0
  55. package/dist/cli/mcp.js +130 -30
  56. package/dist/cli/prior-completion.js +35 -0
  57. package/dist/cli/relay-check.js +163 -97
  58. package/dist/cli/relay-failure.js +32 -0
  59. package/dist/cli/relay-preparation.js +24 -11
  60. package/dist/cli/results-upload.js +131 -0
  61. package/dist/cli/scope-choices.js +57 -0
  62. package/dist/cli/sign-in.js +61 -2
  63. package/dist/contract/cli-api-messages.js +2 -0
  64. package/dist/contract/cli-refusals.js +74 -1
  65. package/dist/contract/cli-version.js +1 -1
  66. package/dist/contract/console.js +7 -2
  67. package/dist/contract/email-sign-in-messages.js +4 -0
  68. package/dist/contract/scope-choice.js +78 -0
  69. package/dist/contract/selection-metadata.js +9 -0
  70. package/dist/contract/selection-offer.js +43 -0
  71. package/dist/gatekeeper/cli-api.js +16 -7
  72. package/dist/gatekeeper/connection-exchange.js +1 -0
  73. package/dist/gatekeeper/console.js +61 -36
  74. package/package.json +2 -2
  75. package/dist/analysis-core/chunks/377MLK4M.js +0 -21
  76. package/dist/analysis-core/chunks/DLPVYWHZ.js +0 -1
  77. package/dist/analysis-core/chunks/FOKDE64Y.js +0 -1
  78. package/dist/analysis-core/chunks/KTNA2KTN.js +0 -7
  79. package/dist/analysis-core/chunks/NIOS7U6C.js +0 -41
  80. package/dist/analysis-core/chunks/QFY6A3MS.js +0 -66
  81. package/dist/analysis-core/chunks/SVMEWGD3.js +0 -1
  82. package/dist/analysis-core/chunks/ZTOVBAG7.js +0 -1
@@ -0,0 +1,104 @@
1
+ import { createHash } from "node:crypto";
2
+ import { join, relative, sep } from "node:path";
3
+ import { analysisSelectionRequestSchema, analysisSelectionResultSchema } from "../analysis-core/contracts/analysis-selection.js";
4
+ import { INVALID_SCOPE_MESSAGE, INVALID_SELECTION_MESSAGE, SCOPE_PROPOSAL_CONFLICT_MESSAGE, STALE_SCOPE_MESSAGE } from "../contract/scope-choice.js";
5
+ import { assessAnalysisSize, measureAnalysisSize } from "../analysis-core/conventions/analysis-fit.js";
6
+ import { ScopeChoiceError, selectionScopeChoices } from "../contract/selection-offer.js";
7
+ import { readLocalFolder } from "./files.js";
8
+ import { scopeChoicesEnabled, selectionModeEnabled } from "./settings.js";
9
+ import { entrySelectionProvider } from "./entry-selection.js";
10
+ const samePaths = (left, right) => left.length === right.length
11
+ && new Set(left).size === left.length && left.every(path => right.includes(path));
12
+ const importsKey = (imports) => JSON.stringify(imports === "none" ? [] : Array.isArray(imports) ? [...imports].sort() : imports);
13
+ const sameScope = (left, right) => left.snapshot === right.snapshot && left.entry === right.entry
14
+ && importsKey(left.imports) === importsKey(right.imports);
15
+ function selectionRequest(selection) {
16
+ const parsed = analysisSelectionRequestSchema.safeParse(selection.request);
17
+ if (!parsed.success)
18
+ throw new Error(INVALID_SELECTION_MESSAGE);
19
+ const request = parsed.data;
20
+ const path = request.kind === "file" ? request.entry : request.folder;
21
+ if (request.launchRoot !== selection.launchRoot || request.kind !== selection.kind
22
+ || join(request.launchRoot, path) !== selection.path
23
+ || request.kind === "file" && request.entry !== selection.entryPath)
24
+ throw new Error(INVALID_SELECTION_MESSAGE);
25
+ return request;
26
+ }
27
+ /** The provider owns membership and admission; this boundary only verifies its captured answer. */
28
+ export async function readAnalysisSelection(settings, selection, options = {}) {
29
+ options.signal?.throwIfAborted();
30
+ const request = selectionRequest(selection);
31
+ const { source, membership: rawMembership } = await (options.provider ?? entrySelectionProvider)(settings, request, {
32
+ proposal: options.proposal, admission: options.admission, signal: options.signal,
33
+ });
34
+ options.signal?.throwIfAborted();
35
+ const parsed = analysisSelectionResultSchema.safeParse(rawMembership);
36
+ if (!parsed.success)
37
+ throw new Error(INVALID_SELECTION_MESSAGE);
38
+ const membership = parsed.data;
39
+ if (membership.launchRoot !== request.launchRoot || membership.kind !== request.kind
40
+ || request.kind === "file" && (membership.kind !== "file" || membership.entry !== request.entry)
41
+ || request.kind === "folder" && (membership.kind !== "folder" || membership.folder !== request.folder))
42
+ throw new Error(INVALID_SELECTION_MESSAGE);
43
+ let paths = membership.files.map(file => file.path);
44
+ if (request.kind === "file" && request.scope) {
45
+ if (request.scope.snapshot !== membership.snapshot)
46
+ throw new Error(STALE_SCOPE_MESSAGE);
47
+ const choice = membership.choices.find(choice => sameScope(choice.scope, request.scope));
48
+ if (!choice)
49
+ throw new Error(INVALID_SCOPE_MESSAGE);
50
+ paths = choice.includes;
51
+ }
52
+ if (options.proposal?.files.some(file => !paths.includes(file.path)))
53
+ throw new Error(SCOPE_PROPOSAL_CONFLICT_MESSAGE);
54
+ if (!samePaths(Object.keys(source.files), paths) || !source.snapshot || !samePaths(Object.keys(source.snapshot), paths)
55
+ || source.sourceBase !== undefined && source.sourceBase !== request.launchRoot
56
+ || source.root !== undefined && source.root !== ".")
57
+ throw new Error(INVALID_SELECTION_MESSAGE);
58
+ const snapshot = Object.create(null);
59
+ for (const path of paths) {
60
+ const file = membership.files.find(file => file.path === path);
61
+ const bytes = source.snapshot[path];
62
+ // Decode the capture itself: a clipped string or replacement character cannot prove complete evidence.
63
+ let text;
64
+ try {
65
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
66
+ }
67
+ catch {
68
+ throw new Error(INVALID_SELECTION_MESSAGE);
69
+ }
70
+ if (!Buffer.isBuffer(bytes) || bytes.length !== file.size || text !== source.files[path]
71
+ || createHash("sha256").update(bytes).digest("hex") !== file.hash)
72
+ throw new Error(INVALID_SELECTION_MESSAGE);
73
+ snapshot[path] = Buffer.from(bytes);
74
+ }
75
+ if (!samePaths(source.selection.selected.map(file => file.path), paths)
76
+ || source.selection.selected.some(file => file.size !== membership.files.find(member => member.path === file.path)?.size))
77
+ throw new Error(INVALID_SELECTION_MESSAGE);
78
+ // All downstream paths use launch-relative coordinates, including imported files outside the entry's parent.
79
+ const selectedPath = relative(request.launchRoot, selection.path).split(sep).join("/");
80
+ if (selectedPath === ".." || selectedPath.startsWith("../"))
81
+ throw new Error(INVALID_SELECTION_MESSAGE);
82
+ return { source: { ...source, sourceBase: request.launchRoot, files: Object.freeze({ ...source.files }), snapshot }, membership };
83
+ }
84
+ /** Local byte admission can prove an entry too large, but cannot prove that a smaller plan fits. */
85
+ export function selectionSizeOffer(settings, membership, source) {
86
+ if (source.analysisFit?.fits !== false)
87
+ return undefined;
88
+ const oversizedPaths = membership.files.filter(file => file.role === "entry"
89
+ && !assessAnalysisSize(measureAnalysisSize(settings, [file])).fits).map(file => file.path);
90
+ return selectionScopeChoices(membership, { currentPaths: Object.keys(source.files), oversizedPaths });
91
+ }
92
+ /** Both execution paths use this owner to select the reader and stop before a nonfitting run. */
93
+ export async function readAnalysisSource(settings, folder, options = {}) {
94
+ const selection = selectionModeEnabled(settings) ? options.selection : undefined;
95
+ const selected = selection && (selection.kind === "file" || options.provider && scopeChoicesEnabled(settings))
96
+ ? await readAnalysisSelection(settings, selection, options) : undefined;
97
+ const source = selected?.source ?? await (options.readFolder?.() ?? readLocalFolder(settings, folder, options.admission));
98
+ if (selected && scopeChoicesEnabled(settings)) {
99
+ const offer = selectionSizeOffer(settings, selected.membership, source);
100
+ if (offer)
101
+ throw new ScopeChoiceError(offer);
102
+ }
103
+ return { source, ...(selected ? { membership: selected.membership } : {}) };
104
+ }
@@ -1,4 +1,5 @@
1
1
  import { snapshotSettings } from "../analysis-core/settings.js";
2
+ export { fileScopeEnabled } from "../analysis-core/settings.js";
2
3
  // Local startup and retention checks share this profile; snapshots never fill it implicitly.
3
4
  export const importerCoverageDefaults = Object.freeze({
4
5
  CF_IMPORT_COVERAGE: "1", CF_IMPORT_LAYOUTS: "1", CF_IMPORT_MANIFEST: "1", CF_IMPORT_SCOPED_SCAN: "1",
@@ -9,9 +10,21 @@ export const importerCoverageDefaults = Object.freeze({
9
10
  export function readJobSettings(env = process.env) {
10
11
  return snapshotSettings(env);
11
12
  }
13
+ /** Tool discovery captures selection switches without starting analysis validation. */
14
+ export function readSelectionSettings(env = process.env, options = {}) {
15
+ const localImportResolution = env.CF_LOCAL_IMPORT_RESOLUTION;
16
+ const saved = Object.freeze({ CF_FILE_SCOPE: env.CF_FILE_SCOPE ?? (localImportResolution === "0" ? "0" : "1"), CF_SCOPE_CHOICES: env.CF_SCOPE_CHOICES ?? "1",
17
+ CF_LOCAL_IMPORT_RESOLUTION: localImportResolution });
18
+ if (options.validate !== false)
19
+ for (const [name, value] of Object.entries(saved)) {
20
+ if (value !== undefined && value !== "0" && value !== "1")
21
+ throw new Error(`${name} must be 0 or 1.`);
22
+ }
23
+ return saved;
24
+ }
12
25
  export function readTransportSettings(env = process.env) {
13
26
  return Object.freeze({ CF_LOCAL_RELAY: env.CF_LOCAL_RELAY, CF_RELAY_DEV: env.CF_RELAY_DEV, ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY,
14
- ...Object.fromEntries(["CF_RELAY_URL", "CF_CONSOLE_URL", "CF_CONSOLE_TOKEN", "CF_RELAY_DEV_TRUST", "CF_RELAY_DEV_BUNDLE", "CF_RELAY_DEV_RELEASE"].filter(key => env[key] !== undefined).map(key => [key, env[key]])) });
27
+ ...Object.fromEntries(["CF_LOCAL_RESULTS_RETRY", "CF_RELAY_URL", "CF_CONSOLE_URL", "CF_CONSOLE_TOKEN", "CF_RELAY_DEV_TRUST", "CF_RELAY_DEV_BUNDLE", "CF_RELAY_DEV_RELEASE"].filter(key => env[key] !== undefined).map(key => [key, env[key]])) });
15
28
  }
16
29
  /** Only creation fills defaults; continuation consumes its saved snapshot unchanged. */
17
30
  export function newRunSettings(caller, env = process.env) {
@@ -25,6 +38,9 @@ export function newRunSettings(caller, env = process.env) {
25
38
  const gitignoreOutput = caller?.CF_LOCAL_GITIGNORE_OUTPUT ?? env.CF_LOCAL_GITIGNORE_OUTPUT;
26
39
  const chooseAgent = caller?.CF_CHOOSE_AGENT ?? env.CF_CHOOSE_AGENT;
27
40
  const findingAudience = caller?.CF_FINDING_AUDIENCE ?? env.CF_FINDING_AUDIENCE;
41
+ const selection = readSelectionSettings({ CF_FILE_SCOPE: caller?.CF_FILE_SCOPE ?? env.CF_FILE_SCOPE,
42
+ CF_SCOPE_CHOICES: caller?.CF_SCOPE_CHOICES ?? env.CF_SCOPE_CHOICES,
43
+ CF_LOCAL_IMPORT_RESOLUTION: caller?.CF_LOCAL_IMPORT_RESOLUTION ?? env.CF_LOCAL_IMPORT_RESOLUTION });
28
44
  for (const [name, value] of Object.entries({ CF_LOCAL_COMMITTED_ONLY: committedOnly,
29
45
  CF_LOCAL_GITIGNORE_OUTPUT: gitignoreOutput, CF_CHOOSE_AGENT: chooseAgent, CF_FINDING_AUDIENCE: findingAudience })) {
30
46
  if (value !== undefined && value !== "0" && value !== "1")
@@ -39,7 +55,8 @@ export function newRunSettings(caller, env = process.env) {
39
55
  ...(committedOnly === undefined ? {} : { CF_LOCAL_COMMITTED_ONLY: committedOnly }),
40
56
  ...(gitignoreOutput === undefined ? {} : { CF_LOCAL_GITIGNORE_OUTPUT: gitignoreOutput }),
41
57
  ...(chooseAgent === undefined ? {} : { CF_CHOOSE_AGENT: chooseAgent }),
42
- ...(findingAudience === undefined ? {} : { CF_FINDING_AUDIENCE: findingAudience }) });
58
+ ...(findingAudience === undefined ? {} : { CF_FINDING_AUDIENCE: findingAudience }),
59
+ ...selection });
43
60
  }
44
61
  /** The installed command selects the relay; source-only switches remain on the development runner. */
45
62
  export function readCliSettings(env = process.env, emailSignIn) {
@@ -49,3 +66,13 @@ export function readCliSettings(env = process.env, emailSignIn) {
49
66
  export function readEmailSignIn(env = process.env) {
50
67
  return env.CF_EMAIL_SIGN_IN !== "0";
51
68
  }
69
+ export function fileScopeRequested(settings) {
70
+ return settings.CF_FILE_SCOPE === "1";
71
+ }
72
+ export function scopeChoicesEnabled(settings) {
73
+ return fileScopeRequested(settings) && settings.CF_SCOPE_CHOICES === "1";
74
+ }
75
+ /** Requested file mode enters selection so unavailable mode is refused before reading paths. */
76
+ export function selectionModeEnabled(settings) {
77
+ return fileScopeRequested(settings);
78
+ }
@@ -1 +1 @@
1
- import{Fb as g,Gb as h,Hb as i,Ib as j,Pb as k,Rb as l,Sb as m,Tb as n,Ub as o,Vb as p,Wb as q}from"../chunks/NIOS7U6C.js";import"../chunks/74FPPPIG.js";import"../chunks/5TATKWLG.js";import"../chunks/724WZMYW.js";import"../chunks/YUY436SM.js";import"../chunks/C6X5GDG4.js";import{c as b,d as c,e as d,f as e,g as f}from"../chunks/6B2HILSY.js";import"../chunks/JKWTHRUR.js";import"../chunks/SKVEBOGA.js";import"../chunks/3GUKUEEJ.js";import{a}from"../chunks/A7WJJMRY.js";import"../chunks/FSLWD2PE.js";export{l as MAX_FINDINGS,i as attachFiles,m as cleanFindings,o as cleanFixDelta,h as cleanFragment,a as findingAudienceEnabled,e as findingsSchema,f as findingsSchemaFor,p as fingerprintOf,n as fixFingerprintOf,k as groupByAudience,b as inspectFixSchema,j as mergeGraphs,g as normaliseBrand,q as numberLines,c as otherSiteSchema,d as rawFindingSchema};
1
+ import{Eb as g,Fb as h,Gb as i,Hb as j,Ob as k,Qb as l,Rb as m,Sb as n,Tb as o,Ub as p,Vb as q}from"../chunks/GOQVKWP3.js";import"../chunks/74FPPPIG.js";import"../chunks/5TATKWLG.js";import"../chunks/2PZF54KH.js";import{c as b,d as c,e as d,f as e,g as f}from"../chunks/6B2HILSY.js";import"../chunks/JKWTHRUR.js";import"../chunks/SKVEBOGA.js";import"../chunks/3GUKUEEJ.js";import"../chunks/724WZMYW.js";import{a}from"../chunks/A7WJJMRY.js";import"../chunks/FSLWD2PE.js";import"../chunks/YUY436SM.js";import"../chunks/C6X5GDG4.js";import"../chunks/RUVMFAST.js";import"../chunks/S27VIQMZ.js";export{l as MAX_FINDINGS,i as attachFiles,m as cleanFindings,o as cleanFixDelta,h as cleanFragment,a as findingAudienceEnabled,e as findingsSchema,f as findingsSchemaFor,p as fingerprintOf,n as fixFingerprintOf,k as groupByAudience,b as inspectFixSchema,j as mergeGraphs,g as normaliseBrand,q as numberLines,c as otherSiteSchema,d as rawFindingSchema};
@@ -0,0 +1,10 @@
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 +1 @@
1
- import{a as S}from"./STI4JE7L.js";import{d as i,e as n,f as c,g as l,h as a,i as u,j as f,k as h,m as d}from"./6QY5BV5B.js";import{d as s}from"./3MTXB4MK.js";import{z as y}from"zod";function Q(e){let t=d(e),m=h(e);return{...t,headlinePlan(o){let r=t.analysisRequest(o),p=m.headlineFallbackQuestion();return{inputBytes:t.callInputBytes(r),fallbackQuestion:p,identity:{system:r.system,data:r.prompt,schema:y.toJSONSchema(r.schema),fallbackQuestion:p}}},modelReaderPrompt:()=>e.bundleText("model-reader-runtime-prompt"),validateShapeInput:o=>{a(e).shapeInputs(o)},...u(e),...n(e),...i(e),...s(e),...c(e),...l(e),...a(e),...f(e),...m,...S(e)}}export{Q as a};
1
+ import{d as i,e as n,f as c,g as l,h as a,i as u,j as f,k as h,m as d}from"./CGCJN73D.js";import{d as s}from"./3MTXB4MK.js";import{a as S}from"./UEORNVQB.js";import{z as y}from"zod";function Q(e){let t=d(e),m=h(e);return{...t,headlinePlan(o){let r=t.analysisRequest(o),p=m.headlineFallbackQuestion();return{inputBytes:t.callInputBytes(r),fallbackQuestion:p,identity:{system:r.system,data:r.prompt,schema:y.toJSONSchema(r.schema),fallbackQuestion:p}}},modelReaderPrompt:()=>e.bundleText("model-reader-runtime-prompt"),validateShapeInput:o=>{a(e).shapeInputs(o)},...u(e),...n(e),...i(e),...s(e),...c(e),...l(e),...a(e),...f(e),...m,...S(e)}}export{Q as a};
@@ -1 +1 @@
1
- import{a as p}from"./SVMEWGD3.js";import{A as y}from"./NIOS7U6C.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
+ 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,4 +1,4 @@
1
- import{a as A}from"./Y7JGSUOA.js";import{d as M}from"./3MTXB4MK.js";import{j as U}from"./K2GNDX3W.js";import{a as P}from"./HTLIRVP7.js";import{a as K}from"./QDYMR6KS.js";import{b}from"./E7TFIHC5.js";import{d as S}from"./ZTOVBAG7.js";import{a as C}from"./74FPPPIG.js";import{d as L,e as N,f as v,g as D,h as $}from"./5DGPLXYB.js";import{a as w,b as E}from"./MJGB25S5.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(`
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
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
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
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(`
@@ -0,0 +1 @@
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 +1 @@
1
- import{I as O}from"./377MLK4M.js";import{a as N}from"./326F4XNG.js";import{b as F}from"./2PSNOSJ2.js";import{A as x}from"./NIOS7U6C.js";import{e as P}from"./C6X5GDG4.js";async function H(S,t){let a={entriesVisited:0,filesRead:0,bytesRead:0,truncated:!1},d=[],R=()=>({files:t.selected.files,selection:t.selection,skippedFiles:F(d),search:a});if(O(S,{selected:t.selected,codeAgentsFound:t.codeAgentsFound}).kind==="none")return R();let h=await t.port.context();if(!h)return R();let E=[];try{let r=e=>P(e,h.selectedRoot),L=e=>Object.fromEntries(Object.entries(e).map(([c,I])=>[r(c),I])),A={...t.selected,files:L(t.selected.files),root:h.selectedRoot,...t.selected.listedPaths?{listedPaths:t.selected.listedPaths.map(r)}:{},...t.selected.pointerFiles?{pointerFiles:L(t.selected.pointerFiles)}:{},...typeof t.selected.explicitPrompt=="string"?{explicitPrompt:r(t.selected.explicitPrompt)}:{}},l=await t.port.list();a.entriesVisited=l.entriesVisited,a.truncated=l.truncated;let w=new Map(l.entries.map(e=>[e.path,e])),u=new Set,p={},m=x.codeScan,b=()=>O(S,{selected:A,codeAgentsFound:t.codeAgentsFound,entries:l.entries,bodies:p,attemptedPaths:[...u],completeListing:!l.truncated}),n=b();for(;n.kind==="search"&&n.paths.length;){let e=[],c=0;for(let s of n.paths){let i=w.get(s);if(i.size>m.fileBytes){d.push({path:s,reason:"too-large"}),u.add(s);continue}let o=i.size+1;if(e.length>=4||a.filesRead+e.length>=m.files||a.bytesRead+c+o>m.bytes)break;e.push({entry:i,allowance:o}),c+=o}if(!e.length){if(n=b(),n.kind==="none"||!n.paths.length)break;a.truncated=!0,d.push(...n.paths.map(s=>({path:s,reason:"scan-limit"})));break}(await N(e,4,async({entry:s,allowance:i})=>{u.add(s.path),a.filesRead++;try{return await t.port.read(s,i)}catch(o){if(o instanceof Error&&o.name==="AbortError")throw o;return{text:null,bytesRead:i,refusal:"unreadable"}}},{settleStartedOnError:!0})).forEach((s,i)=>{let{entry:o,allowance:k}=e[i],z=Number.isSafeInteger(s.bytesRead)&&s.bytesRead>=0&&s.bytesRead<=k;a.bytesRead+=z?s.bytesRead:k,z&&s.text!==null&&!s.refusal&&s.bytesRead<=m.fileBytes&&s.bytesRead<k&&Buffer.byteLength(s.text)===s.bytesRead?p[o.path]=s.text:d.push({path:o.path,reason:s.refusal??"unreadable"})}),n=b()}let g=b();if(g.kind==="none"||!g.ownedPaths.length)return R();let f={...A.files};for(let e of g.ownedPaths)Object.hasOwn(p,e)&&(f[e]=p[e]);let v=e=>({...e,path:r(e.path),...e.ref===e.path?{ref:r(e.ref)}:{}}),B=t.selection.selected.map(v),M=new Set(B.map(e=>e.path)),j=g.ownedPaths.filter(e=>!M.has(e)&&Object.hasOwn(f,e)).map(e=>({...w.get(e),path:e,size:Buffer.byteLength(f[e]),ref:w.get(e)?.ref??e})),y=t.selection.readingNotes,V={files:f,root:h.selectedRoot,search:a,skippedFiles:F(d),selection:{...t.selection,selected:[...B,...j],totalBytes:t.selection.totalBytes+j.reduce((e,c)=>e+c.size,0),refused:t.selection.refused.map(e=>({...e,path:r(e.path)})),...y?{readingNotes:{instruction:y.instruction.map(r),code:y.code.map(r),agents:y.agents.map(r)}}:{}}};return E=Object.keys(f),V}finally{t.port.finish?.(E)}}export{H as a};
1
+ import{S as O}from"./IVULXWQN.js";import{a as N}from"./326F4XNG.js";import{b as F}from"./2PSNOSJ2.js";import{z as x}from"./GOQVKWP3.js";import{e as P}from"./C6X5GDG4.js";async function H(S,t){let a={entriesVisited:0,filesRead:0,bytesRead:0,truncated:!1},d=[],R=()=>({files:t.selected.files,selection:t.selection,skippedFiles:F(d),search:a});if(O(S,{selected:t.selected,codeAgentsFound:t.codeAgentsFound}).kind==="none")return R();let h=await t.port.context();if(!h)return R();let E=[];try{let r=e=>P(e,h.selectedRoot),L=e=>Object.fromEntries(Object.entries(e).map(([c,I])=>[r(c),I])),A={...t.selected,files:L(t.selected.files),root:h.selectedRoot,...t.selected.listedPaths?{listedPaths:t.selected.listedPaths.map(r)}:{},...t.selected.pointerFiles?{pointerFiles:L(t.selected.pointerFiles)}:{},...typeof t.selected.explicitPrompt=="string"?{explicitPrompt:r(t.selected.explicitPrompt)}:{}},l=await t.port.list();a.entriesVisited=l.entriesVisited,a.truncated=l.truncated;let w=new Map(l.entries.map(e=>[e.path,e])),u=new Set,p={},m=x.codeScan,b=()=>O(S,{selected:A,codeAgentsFound:t.codeAgentsFound,entries:l.entries,bodies:p,attemptedPaths:[...u],completeListing:!l.truncated}),n=b();for(;n.kind==="search"&&n.paths.length;){let e=[],c=0;for(let s of n.paths){let i=w.get(s);if(i.size>m.fileBytes){d.push({path:s,reason:"too-large"}),u.add(s);continue}let o=i.size+1;if(e.length>=4||a.filesRead+e.length>=m.files||a.bytesRead+c+o>m.bytes)break;e.push({entry:i,allowance:o}),c+=o}if(!e.length){if(n=b(),n.kind==="none"||!n.paths.length)break;a.truncated=!0,d.push(...n.paths.map(s=>({path:s,reason:"scan-limit"})));break}(await N(e,4,async({entry:s,allowance:i})=>{u.add(s.path),a.filesRead++;try{return await t.port.read(s,i)}catch(o){if(o instanceof Error&&o.name==="AbortError")throw o;return{text:null,bytesRead:i,refusal:"unreadable"}}},{settleStartedOnError:!0})).forEach((s,i)=>{let{entry:o,allowance:k}=e[i],z=Number.isSafeInteger(s.bytesRead)&&s.bytesRead>=0&&s.bytesRead<=k;a.bytesRead+=z?s.bytesRead:k,z&&s.text!==null&&!s.refusal&&s.bytesRead<=m.fileBytes&&s.bytesRead<k&&Buffer.byteLength(s.text)===s.bytesRead?p[o.path]=s.text:d.push({path:o.path,reason:s.refusal??"unreadable"})}),n=b()}let g=b();if(g.kind==="none"||!g.ownedPaths.length)return R();let f={...A.files};for(let e of g.ownedPaths)Object.hasOwn(p,e)&&(f[e]=p[e]);let v=e=>({...e,path:r(e.path),...e.ref===e.path?{ref:r(e.ref)}:{}}),B=t.selection.selected.map(v),M=new Set(B.map(e=>e.path)),j=g.ownedPaths.filter(e=>!M.has(e)&&Object.hasOwn(f,e)).map(e=>({...w.get(e),path:e,size:Buffer.byteLength(f[e]),ref:w.get(e)?.ref??e})),y=t.selection.readingNotes,V={files:f,root:h.selectedRoot,search:a,skippedFiles:F(d),selection:{...t.selection,selected:[...B,...j],totalBytes:t.selection.totalBytes+j.reduce((e,c)=>e+c.size,0),refused:t.selection.refused.map(e=>({...e,path:r(e.path)})),...y?{readingNotes:{instruction:y.instruction.map(r),code:y.code.map(r),agents:y.agents.map(r)}}:{}}};return E=Object.keys(f),V}finally{t.port.finish?.(E)}}export{H as a};