@counterfact-labs/cli 0.2.4 → 0.2.6

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 (153) hide show
  1. package/README.md +7 -1
  2. package/bundle/client-release.json +1 -1
  3. package/dist/adapters/anthropic.js +11 -2
  4. package/dist/adapters/completion.js +3 -0
  5. package/dist/adapters/durable-write.js +9 -2
  6. package/dist/adapters/files.js +25 -13
  7. package/dist/adapters/git-ignore.js +28 -14
  8. package/dist/adapters/git.js +1 -1
  9. package/dist/adapters/gitignore-output.js +41 -0
  10. package/dist/adapters/models.js +1 -6
  11. package/dist/adapters/output-paths.js +5 -2
  12. package/dist/adapters/public-instructions.js +1 -1
  13. package/dist/adapters/relay-plan.js +2 -5
  14. package/dist/adapters/release.js +2 -1
  15. package/dist/adapters/repository-files.js +164 -4
  16. package/dist/adapters/repository-root.js +18 -2
  17. package/dist/adapters/results.js +8 -4
  18. package/dist/adapters/settings.js +26 -1
  19. package/dist/adapters/snapshot.js +86 -15
  20. package/dist/analysis-core/analysis/finding-audience-switch.js +1 -0
  21. package/dist/analysis-core/analysis/schemas.js +1 -1
  22. package/dist/analysis-core/analysis/source-notes/types.js +1 -1
  23. package/dist/analysis-core/chunks/377MLK4M.js +21 -0
  24. package/dist/analysis-core/chunks/{D6AWHLRI.js → 3JWEFCTJ.js} +1 -1
  25. package/dist/analysis-core/chunks/{3227KXHF.js → 4H23CSUM.js} +1 -1
  26. package/dist/analysis-core/chunks/5DGPLXYB.js +1 -0
  27. package/dist/analysis-core/chunks/5TATKWLG.js +1 -0
  28. package/dist/analysis-core/chunks/{EH3QQ3T4.js → 6B2HILSY.js} +1 -1
  29. package/dist/analysis-core/chunks/6QY5BV5B.js +14 -0
  30. package/dist/analysis-core/chunks/6U2IR4XB.js +1 -0
  31. package/dist/analysis-core/chunks/A7WJJMRY.js +1 -0
  32. package/dist/analysis-core/chunks/C6X5GDG4.js +1 -0
  33. package/dist/analysis-core/chunks/DLPVYWHZ.js +1 -0
  34. package/dist/analysis-core/chunks/DZZBQDGO.js +1 -0
  35. package/dist/analysis-core/chunks/F3R4J3ND.js +1 -0
  36. package/dist/analysis-core/chunks/FOKDE64Y.js +1 -0
  37. package/dist/analysis-core/chunks/K2GNDX3W.js +1 -0
  38. package/dist/analysis-core/chunks/KTNA2KTN.js +7 -0
  39. package/dist/analysis-core/chunks/KWECQJ6X.js +1 -0
  40. package/dist/analysis-core/chunks/{SL27GMEN.js → M6HYSTQD.js} +1 -1
  41. package/dist/analysis-core/chunks/{ZAA44GPI.js → N7U5N42V.js} +1 -1
  42. package/dist/analysis-core/chunks/NIOS7U6C.js +41 -0
  43. package/dist/analysis-core/chunks/{QMIXCT62.js → OPMA32A6.js} +1 -1
  44. package/dist/analysis-core/chunks/PECX3OXB.js +1 -0
  45. package/dist/analysis-core/chunks/QFY6A3MS.js +66 -0
  46. package/dist/analysis-core/chunks/SKVEBOGA.js +1 -0
  47. package/dist/analysis-core/chunks/{T66VDFXF.js → STI4JE7L.js} +1 -1
  48. package/dist/analysis-core/chunks/SVMEWGD3.js +1 -0
  49. package/dist/analysis-core/chunks/X7WZAA7S.js +1 -0
  50. package/dist/analysis-core/chunks/YDBO7P4X.js +1 -0
  51. package/dist/analysis-core/chunks/YUY436SM.js +1 -0
  52. package/dist/analysis-core/chunks/ZTOVBAG7.js +1 -0
  53. package/dist/analysis-core/contracts/file-safety.js +1 -0
  54. package/dist/analysis-core/contracts/relay-analysis.js +1 -0
  55. package/dist/analysis-core/contracts/requests.js +1 -1
  56. package/dist/analysis-core/conventions/analysis-fit.js +1 -1
  57. package/dist/analysis-core/conventions/file-admission.js +1 -1
  58. package/dist/analysis-core/data/finding-types.js +1 -1
  59. package/dist/analysis-core/findings/sites.js +1 -0
  60. package/dist/analysis-core/github/repo-key.js +1 -1
  61. package/dist/analysis-core/import/outside-loader-sources.js +1 -1
  62. package/dist/analysis-core/index.js +3 -3
  63. package/dist/analysis-core/llm/output-limit.js +1 -1
  64. package/dist/analysis-core/llm/types.js +1 -0
  65. package/dist/analysis-core/requests/answer-formats.js +1 -1
  66. package/dist/analysis-core/requests/headline-request.js +1 -1
  67. package/dist/analysis-core/requests/local-plan.js +1 -1
  68. package/dist/analysis-core/requests/registry.js +1 -1
  69. package/dist/analysis-core/requests/template-version.js +1 -1
  70. package/dist/analysis-core/requests/tools.js +1 -1
  71. package/dist/analysis-core/settings.js +1 -1
  72. package/dist/analysis-core/stages/engine-entry.js +1 -0
  73. package/dist/analysis-core/stages/execution-ports.js +1 -0
  74. package/dist/bundle/seal/deserialise.js +9 -1
  75. package/dist/bundle/seal/engine.js +76 -0
  76. package/dist/bundle/seal/freeze.js +9 -0
  77. package/dist/bundle/seal/metadata.js +3 -0
  78. package/dist/bundle/seal/open-engine.js +26 -0
  79. package/dist/bundle/seal/open.js +2 -8
  80. package/dist/cli/agent-folder.js +3 -3
  81. package/dist/cli/commands/analyze.js +39 -6
  82. package/dist/cli/commands/balance.js +6 -3
  83. package/dist/cli/commands/finding.js +9 -3
  84. package/dist/cli/context.js +6 -1
  85. package/dist/cli/finding-display.js +39 -0
  86. package/dist/cli/finding-lookup.js +92 -0
  87. package/dist/cli/finding-settings.js +5 -0
  88. package/dist/cli/fix-requests.js +42 -0
  89. package/dist/cli/intake-payload.js +19 -11
  90. package/dist/cli/main.js +9 -4
  91. package/dist/cli/mcp-failure.js +8 -0
  92. package/dist/cli/mcp.js +125 -37
  93. package/dist/cli/relay-check.js +47 -14
  94. package/dist/cli/relay-preparation.js +28 -5
  95. package/dist/cli/result-check.js +68 -0
  96. package/dist/cli/sign-in.js +61 -2
  97. package/dist/cli/summary.js +10 -3
  98. package/dist/contract/agent-choice.js +15 -0
  99. package/dist/contract/agent-proposal.js +38 -0
  100. package/dist/contract/attestation.js +106 -0
  101. package/dist/contract/cli-api-messages.js +2 -0
  102. package/dist/contract/cli-refusals.js +69 -1
  103. package/dist/contract/cli-version.js +1 -1
  104. package/dist/contract/console.js +21 -16
  105. package/dist/contract/email-sign-in-messages.js +4 -0
  106. package/dist/contract/engine.js +44 -0
  107. package/dist/contract/findings.js +28 -0
  108. package/dist/contract/fix-requests.js +30 -0
  109. package/dist/contract/messages.js +6 -94
  110. package/dist/contract/public-report.js +1 -0
  111. package/dist/contract/runtime-environment.js +12 -1
  112. package/dist/core/analysis/run-to-end.js +7 -52
  113. package/dist/gatekeeper/attestation.js +1 -1
  114. package/dist/gatekeeper/channel-binding.js +15 -0
  115. package/dist/gatekeeper/cli-api.js +28 -9
  116. package/dist/gatekeeper/connection-exchange.js +17 -12
  117. package/dist/gatekeeper/console.js +31 -17
  118. package/dist/gatekeeper/model.js +2 -1
  119. package/dist/gatekeeper/production-attestation.js +23 -17
  120. package/dist/gatekeeper/trust/policy.js +4 -1
  121. package/dist/gatekeeper/trust/schema.js +4 -0
  122. package/dist/transport/kms.js +25 -0
  123. package/package.json +4 -3
  124. package/dist/adapters/quality.js +0 -6
  125. package/dist/adapters/report.js +0 -29
  126. package/dist/analysis-core/analysis/analysis-flags.js +0 -1
  127. package/dist/analysis-core/analysis/finding-quality/config.js +0 -1
  128. package/dist/analysis-core/analysis/finding-quality/policy.js +0 -1
  129. package/dist/analysis-core/analysis/headlines/attachment.js +0 -1
  130. package/dist/analysis-core/analysis/headlines/input.js +0 -1
  131. package/dist/analysis-core/chunks/3CKW5JIF.js +0 -1
  132. package/dist/analysis-core/chunks/6YCABS5T.js +0 -1
  133. package/dist/analysis-core/chunks/7OYIBWX3.js +0 -1
  134. package/dist/analysis-core/chunks/DRGDIIFA.js +0 -1
  135. package/dist/analysis-core/chunks/FTODBFQW.js +0 -1
  136. package/dist/analysis-core/chunks/HPIAEQHE.js +0 -37
  137. package/dist/analysis-core/chunks/IVDDV6CU.js +0 -14
  138. package/dist/analysis-core/chunks/JF4GYMOZ.js +0 -1
  139. package/dist/analysis-core/chunks/K5OTWBTT.js +0 -22
  140. package/dist/analysis-core/chunks/MXXNED6N.js +0 -7
  141. package/dist/analysis-core/chunks/NCWEOJVJ.js +0 -6
  142. package/dist/analysis-core/chunks/O652FQQH.js +0 -1
  143. package/dist/analysis-core/chunks/OFBJNHC6.js +0 -1
  144. package/dist/analysis-core/chunks/QV2EOS7U.js +0 -1
  145. package/dist/analysis-core/chunks/STZOC7LN.js +0 -1
  146. package/dist/analysis-core/chunks/T2SAP7OV.js +0 -60
  147. package/dist/analysis-core/chunks/T5TREZCQ.js +0 -1
  148. package/dist/analysis-core/chunks/TDNTU4TF.js +0 -1
  149. package/dist/analysis-core/chunks/U5HOEVPE.js +0 -1
  150. package/dist/analysis-core/chunks/UEWL3GMQ.js +0 -1
  151. package/dist/analysis-core/chunks/V7BFUTM7.js +0 -1
  152. package/dist/core/analysis/finding-quality/config.js +0 -4
  153. package/dist/core/analysis/structural-run.js +0 -16
@@ -1,6 +0,0 @@
1
- import { readFindingQualityConfig as readSharedConfig } from "../analysis-core/analysis/finding-quality/config.js";
2
- import { readableRequestTools } from "./instructions.js";
3
- // Local startup has one provider and has not approved recall or imported code evidence.
4
- export function readLocalQualityConfig(settings, tools = readableRequestTools()) {
5
- return readSharedConfig(settings, tools, { codeInputs: false, recall: false, secondOpinion: false });
6
- }
@@ -1,29 +0,0 @@
1
- import { rankFindings } from "../analysis-core/analysis/finding-quality/policy.js";
2
- import { attachHeadlineResults } from "../analysis-core/analysis/headlines/attachment.js";
3
- /** The local view keeps presentation ranking and reading diagnostics beside the shared result. */
4
- export function buildLocalReport(repoKey, result, state) {
5
- const quality = result.findingQuality;
6
- const checked = { ...(state.findingCheck?.state?.result ?? { kept: result.findings, dropped: [], warnings: [] }) };
7
- // Source explanations refresh the audit without changing the saved checker decision.
8
- if (quality?.assessments && checked.qualityAudit)
9
- checked.qualityAudit = {
10
- coverage: quality.coverage ?? [], verdicts: quality.verdicts ?? [], assessments: quality.assessments,
11
- ...(quality.shadow ? { shadow: quality.shadow } : {}),
12
- };
13
- const attached = attachHeadlineResults(result.findings, result.structures, result.findingHeadlines ?? [], result.findingHeadlineDiagnostics);
14
- const wording = new Map(attached.rows.filter(row => row.target === "finding")
15
- .map(row => [row.index, { headline: row.headline, ifLeft: row.ifLeft }]));
16
- const structureWording = new Map(attached.rows.filter(row => row.target === "structure")
17
- .map(row => [row.index, { headline: row.headline, ifLeft: row.ifLeft }]));
18
- const structures = structureWording.size ? result.structures.map((proposal, index) => structureWording.has(index)
19
- ? { ...proposal, ...structureWording.get(index) } : proposal) : result.structures;
20
- const findings = wording.size
21
- ? result.findings.map((finding, index) => wording.has(index) ? { ...finding, ...wording.get(index) } : finding)
22
- : result.findings;
23
- const ranked = state.findingQuality?.config.switches.ranking ? rankFindings(findings, quality?.assessments ?? []) : undefined;
24
- return { repoKey, findings: ranked?.ordered ?? findings, structures, graph: result.graph, warnings: result.warnings,
25
- ...(attached.diagnostics ? { findingHeadlineDiagnostics: attached.diagnostics } : {}),
26
- skippedFiles: state.inspectPlan?.skipped ?? [], passes: state.inspectPlan?.passes.length ?? 1, findingCheck: checked,
27
- ...(ranked ? { ranking: { defaultIds: ranked.defaultIds, hiddenIds: ranked.hiddenIds, emptyMessage: ranked.emptyMessage } } : {}),
28
- };
29
- }
@@ -1 +0,0 @@
1
- import{a,b,c}from"../chunks/OFBJNHC6.js";export{c as analysisFlagsOf,a as readAnalysisFlags,b as readParallelPassSettings};
@@ -1 +0,0 @@
1
- import{n as a,o as b,p as c,q as d,r as e,s as f}from"../../chunks/DRGDIIFA.js";import"../../chunks/6YCABS5T.js";import"../../chunks/SL27GMEN.js";import"../../chunks/3CKW5JIF.js";import"../../chunks/STZOC7LN.js";import"../../chunks/MJGB25S5.js";import"../../chunks/UEWL3GMQ.js";import"../../chunks/OFBJNHC6.js";import"../../chunks/3227KXHF.js";import"../../chunks/HPIAEQHE.js";import"../../chunks/74FPPPIG.js";import"../../chunks/EH3QQ3T4.js";import"../../chunks/JKWTHRUR.js";import"../../chunks/FSLWD2PE.js";import"../../chunks/JF4GYMOZ.js";import"../../chunks/3GUKUEEJ.js";import"../../chunks/T5TREZCQ.js";import"../../chunks/724WZMYW.js";export{f as assertFindingQualityPrompts,b as findingAnalysisTemplate,e as findingQualityConfigOf,a as findingQualityPromptNames,c as plannedFindingQualityCalls,d as readFindingQualityConfig};
@@ -1 +0,0 @@
1
- import{i as a,j as b}from"../../chunks/MXXNED6N.js";import"../../chunks/U5HOEVPE.js";import"../../chunks/HPIAEQHE.js";import"../../chunks/74FPPPIG.js";import"../../chunks/EH3QQ3T4.js";import"../../chunks/JKWTHRUR.js";import"../../chunks/FSLWD2PE.js";import"../../chunks/JF4GYMOZ.js";import"../../chunks/3GUKUEEJ.js";import"../../chunks/T5TREZCQ.js";import"../../chunks/724WZMYW.js";export{a as assessFindings,b as rankFindings};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"../../chunks/O652FQQH.js";import"../../chunks/57M4OQJM.js";import"../../chunks/IBCFGUHI.js";import"../../chunks/HPIAEQHE.js";import"../../chunks/74FPPPIG.js";import"../../chunks/EH3QQ3T4.js";import"../../chunks/JKWTHRUR.js";import"../../chunks/FSLWD2PE.js";import"../../chunks/JF4GYMOZ.js";import"../../chunks/3GUKUEEJ.js";import"../../chunks/T5TREZCQ.js";import"../../chunks/724WZMYW.js";export{d as attachHeadlineResults,c as attachHeadlineRows,a as headlineTargetFingerprint,b as headlineWordingAt};
@@ -1 +0,0 @@
1
- import{a as b,b as c}from"../../chunks/FTODBFQW.js";import{c as a}from"../../chunks/ZAA44GPI.js";import"../../chunks/3227KXHF.js";import"../../chunks/O652FQQH.js";import"../../chunks/57M4OQJM.js";import"../../chunks/IBCFGUHI.js";import"../../chunks/HPIAEQHE.js";import"../../chunks/74FPPPIG.js";import"../../chunks/EH3QQ3T4.js";import"../../chunks/JKWTHRUR.js";import"../../chunks/FSLWD2PE.js";import"../../chunks/JF4GYMOZ.js";import"../../chunks/3GUKUEEJ.js";import"../../chunks/T5TREZCQ.js";import"../../chunks/724WZMYW.js";export{b as buildHeadlineInput,c as headlineInputHash,a as headlineRequest};
@@ -1 +0,0 @@
1
- import{a as C,b as F}from"./STZOC7LN.js";import{a as c}from"./MJGB25S5.js";import{z as t}from"zod";var O=Object.freeze(["CF_MULTI_PASS","CF_SPLIT_CHECK","CF_FINDING_CHECK","CF_SOURCE_NOTES","CF_PARALLEL_PASSES","CF_PASS_CONCURRENCY","CF_PARALLEL_SCOPE_CHECK","CF_FINDING_QUALITY","CF_FINDING_FULL_CONTEXT","CF_FINDING_PRECISION_RULES","CF_PROMPT_AGREE","CF_FINDING_SECOND_OPINION","CF_FINDING_RANKING","CF_FINDING_SEMANTIC_MATCHING","CF_FINDING_CODE_INPUTS","CF_FINDING_RECALL","CF_FINDING_RECALL_VARIANT","CF_FINDING_SECOND_OPINION_MODEL","CF_FINDING_SECOND_OPINION_PROVIDER","CF_FIX_EXPECTED_OUTCOME","CF_UNTRUSTED_CONTENT_CHECK","CF_FINDING_BETTER_AS_CODE","CF_CODE_AGENTS","CF_CODE_AGENTS_MODEL","CF_FINDING_DEDUPE","CF_ANALYSIS_IMPORTED_AGENTS","CF_RECALL_SIGNALS","CF_READING_NOTE_AGENT_ONLY","CF_SPLIT_HELPER_TOOLS","CF_CODE_PROMPT_LOADERS","CF_CODE_PROMPT_FUNCTIONS","CF_READING_PRIORITY","CF_LOCAL_SYMLINK_GUARD","CF_IMPORT_EXAMPLE_FILTER","CF_IMPORT_OUTSIDE_LOADERS","CF_SECRET_SCAN","CF_RESPECT_GITIGNORE","CF_IMPORT_COVERAGE","CF_IMPORT_MANIFEST","CF_IMPORT_SCOPED_SCAN","CF_IMPORT_INCLUDE_EXAMPLES","CF_IMPORT_WEAK_CODE_FALLBACK","CF_REFUSE_TOO_LARGE","CF_FINDING_HEADLINES","CF_IMPORT_LAYOUTS","CF_DISCOVERY_SKILLS","CF_IMPORT_CALLS","CF_PROMPT_CACHE","CF_MODEL_READER","CF_LEGACY_TOOL_LISTS"]),a=O.filter(e=>e!=="CF_IMPORT_OUTSIDE_LOADERS"&&e!=="CF_SECRET_SCAN"&&e!=="CF_RESPECT_GITIGNORE"&&e!=="CF_IMPORT_COVERAGE"&&e!=="CF_IMPORT_MANIFEST"&&e!=="CF_IMPORT_SCOPED_SCAN"&&e!=="CF_IMPORT_INCLUDE_EXAMPLES"&&e!=="CF_IMPORT_WEAK_CODE_FALLBACK"&&e!=="CF_REFUSE_TOO_LARGE");function N(e,_="request"){return Object.freeze(Object.fromEntries((_==="saved"?O:a).filter(i=>Object.hasOwn(e,i)).map(i=>[i,e[i]])))}var p=t.partialRecord(t.enum(a),t.string()),E=t.lazy(()=>t.union([t.string(),t.number(),t.boolean(),t.null(),t.array(E),t.record(t.string(),E)])),l=t.object({data:t.record(t.string(),E),settings:p,maxInputBytes:t.number().int().positive().optional()}).strict(),S=t.string().min(1).max(128).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/),T=t.object({maxTokens:t.number().int().positive().optional(),effort:t.enum(["low","medium","high","max"]).optional(),thinking:t.literal("disabled").optional(),promptCache:t.boolean().optional()}).strict(),R=t.object({template:t.string().min(1),inputs:l,answerFormat:t.string().min(1),model:S,limits:T.optional()}).strict();function P(e,_={},o){let i={data:e.inputs,settings:N(_),...o===void 0?{}:{maxInputBytes:o}};return R.parse({...e,answerFormat:Object.hasOwn(r,e.template)?A(e.template,e.answerFormat,_):e.answerFormat,limits:{...e.limits,promptCache:c(_,{template:e.template},e.model).enabled},inputs:JSON.parse(JSON.stringify(i))})}var n=(e,..._)=>Object.freeze({role:e,answerFormats:Object.freeze(_)}),s=F().map(e=>e.name),r=Object.freeze({"derive-findings":n("required",...s),"derive-findings-legacy":n("required",...s),"derive-findings-no-outcome":n("required",...s),"derive-findings-legacy-no-outcome":n("required",...s),"benchmark-judge":n("required","judge"),"judge-code-prompt":n("optional","codeJudge"),"derive-structure":n("optional","structures"),"structure-recheck":n("optional","recheck"),"derive-shape":n("optional","shape"),"scope-items":n("optional","structureScope"),"scope-findings":n("optional","scope"),"check-findings":n("optional","check"),"check-findings-precision-v1":n("optional","check"),"second-opinion":n("optional","opinion"),"explain-sources":n("optional","sourceNotes"),"finding-headlines":n("optional","findingHeadlines")});function D(){return r}function f(e,_,o){let i=o??(e==="derive"?"derive-findings":"check-findings");if(!Object.keys(r).filter(I=>r[I].answerFormats.includes(e==="derive"?"findings":"check")).includes(i))throw new Error("Unknown analysis template");return e==="derive"&&!C(_).switches.expectedOutcome&&!i.endsWith("-no-outcome")?`${i}-no-outcome`:i}function A(e,_,o){let i=_==="findings"?C(o).name:_;if(!Object.hasOwn(r,e)||!r[e].answerFormats.includes(i))throw new Error("Unsupported template answer format");return i}function g(e,_,o){if(o(_),!Object.hasOwn(r,e)||r[e].role!=="optional")throw _}export{O as a,N as b,l as c,S as d,T as e,R as f,P as g,D as h,f as i,A as j,g as k};
@@ -1 +0,0 @@
1
- var n=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 c(e){if(!Object.hasOwn(n,e))throw new Error("Unknown analysis template");return n[e]}function s(e){return Object.fromEntries(Object.entries(e).map(([i,r])=>[i,{...r,route:c(i)}]))}export{c as a,s as b};
@@ -1 +0,0 @@
1
- import{h as G}from"./NCWEOJVJ.js";import{Aa as $,Ba as P,Ca as w,Fa as M,Ga as y,Ta as D,a as l,b as N,e as T,ga as E,o as C,qa as I,u as R,wa as F,za as _}from"./HPIAEQHE.js";import{a as b,c as x}from"./T5TREZCQ.js";var k="Some of this agent's files weren't read, so findings may be missing.";var B=r=>r.CF_READING_PRIORITY!=="0";var U=new Set(["system prompt","soul","knowledge","config","tools","mcp"]);function L(r){let t=new Set;for(let s of r.nodes)for(let f of s.files??[])U.has(f.role)&&t.add(f.path);let n=new Set(r.edges.filter(s=>s.kind==="delegates").map(s=>s.to));for(let s of r.nodes)n.has(s.id)&&s.sourceRef&&t.add(s.sourceRef.path);return t}function V(r){return new Set([...r.nodes,...r.edges].flatMap(t=>t.sourceRef?[t.sourceRef.path]:[]))}var p=6e4,j=r=>{if(r.length<=p)return r;let t=r.endsWith(E)?E:"";return(t?r.slice(0,-t.length):r).slice(0,p)+t};function Z(r,t){let n=[...r].filter(s=>t[s]!==void 0&&j(t[s])!==t[s]).sort();return n.length===0?null:`${n.length} core file${n.length===1?" was":"s were"} longer than ${p/1e3} KB, so only the first ${p/1e3} KB ${n.length===1?"was":"were"} read: ${n.join(", ")}`}var A=r=>r.split("/").slice(0,-1).join("/"),Y=/(agent|prompt|tool|llm|model)/i,z=2.5;function K(r,t){if(!B(r))return{enabled:!1,tierOf:()=>6};if(t.repos?.some(e=>e.kind==="github"&&b(e.root)))return v(r,t,t.repos);let n=t.scopes??(T(r)?G(r,t.paths):void 0),s=t.graph?L(t.graph):new Set,f=new Set(t.graph?.nodes.flatMap(e=>(e.files??[]).filter(o=>o.role==="code"&&l(o.path)).map(o=>o.path))??[]),i=new Set(t.graph?.nodes.flatMap(e=>(e.files??[]).filter(o=>o.role==="system prompt").map(o=>o.path))??[]),a=e=>N(e)&&(I.includes(e.split("/").pop().toLowerCase())||/(^|\/)system_prompt_[^/]+\.md$/i.test(e)||y.test(e)),c=e=>{if(s.has(e))return 1;if(f.has(e))return 2;let o=P(r,e,n),d=R(o,{nested:!0});if(d?.reference)return 5;if(d?.definition||F.test(o))return 4;if(d||/(^|\/)(docs?|references)\//i.test(o)||$.test(e.split("/").pop()))return 5;if(_(o)||w(r,e,n)&&_(e.split("/").pop())||a(e))return 1;if(l(e)){if(Y.test(e))return z;if(M.test(e))return 3}return 6};for(let e of t.paths)c(e)===1&&a(e)&&i.add(e);let m=[...i].flatMap(e=>{let o=A(e);return[o,...o?[A(o)]:[]]}),h=e=>l(e)&&m.some(o=>A(e)===o),u=new Map(t.paths.map(e=>{let o=c(e);return[e,o>2&&h(e)?2:o]})),g=[...u].filter(([e,o])=>o<=2&&l(e)).map(([e])=>e),O=D(Object.fromEntries(g.flatMap(e=>t.files?.[e]===void 0?[]:[[e,t.files[e]]])),t.paths);for(let e of O)l(e)&&!R(P(r,e,n),{nested:!0})&&(u.get(e)??6)>2&&u.set(e,2);return{enabled:!0,tierOf:e=>u.get(e)??c(e)}}function v(r,t,n){let s=new Map;for(let f of n){let i=f.kind==="github"?f.root:void 0,a=t.paths.filter(e=>f.files?.[e]!==void 0&&!s.has(e)),c=e=>x(e,i)??(f.files?.[e]!==void 0?e:null),m=e=>{let o=e?c(e.path):null;return o===null?null:{path:o}},h=t.graph&&{nodes:t.graph.nodes.map(e=>({...e,sourceRef:m(e.sourceRef),files:e.files?.flatMap(o=>{let d=c(o.path);return d===null?[]:[{...o,path:d}]})})),edges:t.graph.edges.map(e=>({...e,sourceRef:m(e.sourceRef)}))},u=a.flatMap(e=>{let o=c(e);return o===null?[]:[o]}),g=Object.fromEntries(a.flatMap(e=>{let o=c(e);return o===null||t.files?.[e]===void 0?[]:[[o,t.files[e]]]})),O=K(r,{paths:u,files:g,graph:h});for(let e of a)s.set(e,O.tierOf(c(e)??e))}return{enabled:!0,tierOf:f=>s.get(f)??6}}function H(r,t){return r.enabled?t.filter(n=>["too-large","total","allowance"].includes(n.reason)&&r.tierOf(n.path)<3).map(n=>n.path):[]}function W(r){return r.slice(0,3)}function q(r,t=!1){let n=W(r);if(!n.length)return;let s=t?". "+k:", so some findings may be missing";return`${n.join(", ")} ${n.length===1?"was":"were"} left out${s}`}function ue(r,t){return q(H(r,t))}function de(r,t){return r.enabled&&r.tierOf(t)<3}function me(r,t,n){let s=C.sourceFetch.codeFileBytes;return r.enabled&&r.tierOf(t)<3&&l(t)&&n>s?{size:s,readBytes:s}:{size:n}}function pe(r,t){return r.enabled&&r.tierOf(t)<3&&l(t)}function S(r){return r.split("/").length-1}function he(r,t,n){return w(r,t,n)?0:M.test(t)?1+Math.min(S(t),3)/10:S(t)<=2?2:S(t)<=4?3:4}function ge(r,t){return(r.tier??0)-(t.tier??0)||r.score-t.score||r.size-t.size}function Oe(r,t,n,s){return[...r].sort((f,i)=>(s?.enabled?s.tierOf(f)-s.tierOf(i):0)||Number(n.has(i))-Number(n.has(f))||t[f].length-t[i].length||(f<i?-1:1))}function Re(r,t,n,s){return[...r].sort((f,i)=>(s?.enabled?s.tierOf(f.path)-s.tierOf(i.path):0)||Number(t.has(i.path))-Number(t.has(f.path))||Number(n.has(i.path))-Number(n.has(f.path))||f.text.length-i.text.length)}export{B as a,L as b,V as c,j as d,Z as e,K as f,H as g,W as h,q as i,ue as j,de as k,me as l,pe as m,he as n,ge as o,Oe as p,Re as q};
@@ -1 +0,0 @@
1
- import{a as U}from"./6YCABS5T.js";import{c as V}from"./SL27GMEN.js";import{i as b,j as v}from"./3CKW5JIF.js";import{c as y}from"./MJGB25S5.js";import{a as K}from"./OFBJNHC6.js";import{a as u,b as w}from"./3227KXHF.js";import{ub as Y}from"./HPIAEQHE.js";import{c as k,f as M}from"./JKWTHRUR.js";var l=u.chat,s=8,I=1,W=40,N=6e4,S=16e3,Q=8e4,f=4e3,q=1536,R=8192,B=1024;function h(e){return R+e*q+B}function A(e,t="legacy"){return t==="whole-file"?N+Q+f*e+4e3*4:N+(S+f)*e+4e3*2}function pe(e,t,o,n,c="legacy"){if(!o||t===0)return null;let r=Math.ceil(t/s),i=1+I,p=h(t)+(R+B)*(r-1),_={template:n};if(c==="whole-file"){let F=Math.floor(t/s),d=t%s,a=M(A(s,c))*F+(d?M(A(d,c)):0);return y(e,_,"Double-check findings",l,a*i,p*i)}let C=N*r+(S+f)*t;return y(e,_,"Double-check findings",l,(M(C)+4e3*r)*i,p*i)}var Ce=8e5;function L(e,t,o,n,c,r,i){return{routeId:U(t),templateId:t,answerFormatId:v(t,o,e),model:n,calls:c,maxInputBytes:r,maxInputTokens:2e5,maxOutputTokens:i??V({model:n})}}function X(e,t){let o=e.CF_FINDING_QUALITY==="1",n=o&&e.CF_FINDING_FULL_CONTEXT==="1",c=o&&e.CF_FINDING_PRECISION_RULES==="1",r=t?.check.name??(c?"check-findings-precision-v1":"check-findings");return{enabled:o,fullContext:n,precisionRules:c,prompts:{derive:t?.derive.name??"derive-findings-legacy",check:r==="check-findings-legacy"?"check-findings":r}}}function $(e){return X({},e.prompts).prompts}function G(e,t,{enabled:o,prompts:n}){return b(e,t,o?n[e]:void 0)}function Ae(e,t,o){return G(e,t,{enabled:o?.switches.enabled??!1,prompts:X({},o?.prompts).prompts})}function Fe(e,t,o,n){let c=K(e),r=X(e),{fullContext:i}=r,p=G("derive",e,r),_=G("check",e,r),C=i?"whole-file":"legacy";return{findings:o,derive:L(e,p,"findings",u.generate,t,n),check:c.findingCheck?L(e,_,"check",l,Math.ceil(o/s)*(I+1),Math.max(n,A(s,C)),h(s)):null}}function g(e){if(e&&typeof e=="object"){for(let t of Object.values(e))g(t);Object.freeze(e)}return e}function ee(e,t,o={}){let{enabled:n,fullContext:c,precisionRules:r,prompts:i}=X(e),p=m=>n&&e[m]==="1",_=p("CF_FINDING_SECOND_OPINION"),C=p("CF_FINDING_RANKING"),F=n&&e.CF_FINDING_SEMANTIC_MATCHING!=="0",d=o.codeInputs!==!1&&n&&e.CF_FINDING_CODE_INPUTS!=="0",a=[],x=e.CF_FINDING_RECALL_VARIANT,D=o.recall!==!1&&p("CF_FINDING_RECALL")&&(x==="request-18"||x==="two-sweeps")?x:"off";o.recall!==!1&&p("CF_FINDING_RECALL")&&D==="off"&&a.push("Recall was skipped: no supported variant was selected.");let P=null,H=null;if(o.recall===!1&&e.CF_FINDING_RECALL==="1"&&a.push("Recall isn't available in local checks yet, so CF_FINDING_RECALL has no effect."),o.codeInputs===!1&&e.CF_FINDING_CODE_INPUTS==="1"&&a.push("Code evidence isn't available in local checks yet, so CF_FINDING_CODE_INPUTS has no effect."),_&&o.secondOpinion===!1&&a.push("Second opinion was skipped: local analysis supports Anthropic only."),_&&o.secondOpinion!==!1){let m=e.CF_FINDING_SECOND_OPINION_MODEL??"",E=Object.hasOwn(k,m)?k[m]:void 0,O=k[l];E&&E.provider===e.CF_FINDING_SECOND_OPINION_PROVIDER&&E.provider!==O.provider&&E.input<=O.input&&E.output<=O.output&&(E.input<O.input||E.output<O.output)?(P=m,H=E.provider):a.push("Second opinion was skipped: configure a priced, cheaper model from a different provider.")}return g({ruleVersion:n?"precision-v1":"legacy",switches:{enabled:n,fullContext:c,precisionRules:r,secondOpinion:_,ranking:C,semanticMatching:F,codeInputs:d,recall:D!=="off"},prompts:{derive:t.promptVersion(i.derive,e),check:t.promptVersion(i.check,e)},models:{derive:u.generate,check:l,scope:u.mechanical,secondOpinion:P},caps:{coreBytes:N,siteBytes:S,findingTextBytes:f,siteWindowLines:W,citedBatchBytes:c?8e4:0,passBytes:15e4,passContextBytes:6e4,maxPasses:4,passFindings:D==="request-18"?18:Y,totalFindings:24,deriveOutputTokens:w,checkBatchSize:s,checkOutputTokens:h(s),checkMaxRetries:I,checkOverheadTokens:4e3,secondOpinionBatchSize:4,secondOpinionInputBytes:A(4)+(c?8e4:0),secondOpinionOutputTokens:2048,secondOpinionMaxRetries:I},recallVariant:D,displayPolicyVersion:C?"support-v1":"legacy",meaningMatchingVersion:F?"meaning-v1":"legacy",codeInputScopeVersion:d?"owned-code-v1":"legacy",secondOpinionProvider:H,diagnostics:a})}function De(e,t){return t?g(structuredClone(t)):ee({},e)}function ke(e,t,o={}){let n=$(e);e.switches.enabled&&t.assertPromptVersions([{...e.prompts.derive,name:n.derive},{...e.prompts.check,name:n.check}],o)}export{l as a,s as b,I as c,W as d,N as e,S as f,Q as g,f as h,h as i,A as j,pe as k,Ce as l,L as m,$ as n,Ae as o,Fe as p,ee as q,De as r,ke as s};
@@ -1 +0,0 @@
1
- import{a as p}from"./O652FQQH.js";import{b as l}from"./57M4OQJM.js";import{createHash as d}from"node:crypto";function u({repo:o,body:r}){let[t,...i]=r.evidence,n=r.split,s=e=>e.map(a=>({path:a.path??null,startLine:a.startLine,endLine:a.endLine}));return{kind:"structure",impact:r.kind,cause:r.cause,category:null,question:null,fixSummaries:[],site:t?{repo:o,path:t.path,line:t.line}:null,excerpt:t?.excerpt??null,otherSites:i.map(e=>({repo:o,path:e.path,line:e.line,excerpt:e.excerpt})),structure:{title:r.title,subKind:r.subKind,files:r.files.map(e=>({path:e.path,action:e.action,role:e.role,unit:e.unit,loadMode:e.loadMode,loadVia:e.loadVia,purpose:e.purpose})),segments:r.segments.map(e=>({path:e.path,startLine:e.startLine,endLine:e.endLine,to:e.to,disposition:e.disposition,into:e.into?{path:e.into.path,line:e.into.line}:null,reason:e.reason})),reorder:r.reorder?{path:r.reorder.path,startLine:r.reorder.startLine,endLine:r.reorder.endLine,steps:r.reorder.steps.map(e=>({from:e.from,reason:e.reason}))}:null,toolMoves:r.toolMoves.map(e=>({tool:e.tool,fromUnit:e.fromUnit,toUnit:e.toUnit,reason:e.reason})),split:n?{frontDoor:{job:n.frontDoor.job,skills:[...n.frontDoor.skills]},subAgents:n.subAgents.map(e=>({job:e.job,description:e.description,path:e.path,handoff:e.handoff??null,skills:e.skills.map(a=>({from:a.from,to:a.to})),tools:[...e.tools],movedKnowledge:s(e.movedKnowledge),neededKnowledge:s(e.neededKnowledge)}))}:null}}}function x(o,r=[]){return{evidence:[...o.map((t,i)=>({key:`f${i}`,kind:"finding",impact:t.kind,structure:null,cause:t.cause,category:t.category??null,question:t.question,site:t.site?{repo:t.siteRepo,path:t.site.path,line:t.site.line}:null,excerpt:t.excerpt,otherSites:t.otherSites.map(n=>({repo:n.repo,path:n.path,line:n.line,excerpt:n.excerpt})),fixSummaries:t.fixes.flatMap(n=>typeof n.summary=="string"&&n.summary.trim()?[n.summary]:[])})),...r.map((t,i)=>({key:`s${i}`,...u(t)}))],positions:[...o.map((t,i)=>({key:`f${i}`,target:"finding",index:i,fingerprint:p("finding",t)})),...r.map((t,i)=>({key:`s${i}`,target:"structure",index:i,fingerprint:p("structure",t)}))]}}function L(o,r){return d("sha256").update(l({batch:o,requestIdentity:r})).digest("hex")}export{x as a,L as b};
@@ -1,37 +0,0 @@
1
- import{b as Gt}from"./74FPPPIG.js";import{d as Xt}from"./EH3QQ3T4.js";import{f as to}from"./JKWTHRUR.js";import{b as Jt}from"./FSLWD2PE.js";import{c as zt,d as no}from"./JF4GYMOZ.js";import{a as We,c as D,d as oo,e as ct,i as so,j as ut}from"./T5TREZCQ.js";import{a as Qn,b as Ut,c as eo}from"./724WZMYW.js";var Ee=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,o,s,r=!1){this.tokens.push({kind:n,text:this.text.slice(t,o),value:s??this.text.slice(t,o),start:t,end:o,line:this.lineAt(t),endLine:this.lineAt(o-1),...r?{formatted:!0}:{}})}lineAt(n){let t=0,o=this.lineStarts.length-1;for(;t<o;){let s=t+o+1>>1;this.lineStarts[s]<=n?t=s:o=s-1}return t+1}},Er=/[\p{L}_$]/u,br=/[\p{L}\p{N}_$]/u;function Ke(e){return Er.test(e)}function lo(e){return br.test(e)}function ee(e){return e>="0"&&e<="9"}function Be(e){return e===" "||e===" "||e===`
2
- `||e==="\r"||e==="\f"||e==="\v"}function be(e,n){return e[n+1]==="\r"&&e[n+2]===`
3
- `?3:2}function Ue(e,n){let t=n+1;for(;t<e.length&&lo(e[t]);)t++;return t}function ze(e,n){let t=n+1;for(;t<e.length&&(lo(e[t])||e[t]===".");)t++;return t}function Je(e,n){for(;n<e.length&&e[n]!==`
4
- `&&e[n]!=="\r";)n++;return n}var ro={n:`
5
- `,t:" ",r:"\r",b:"\b",f:"\f",v:"\v"},io=/^[0-9a-fA-F]+$/;function Or(e,n,t){let o=e[n+1];if(o==="\r"&&e[n+2]===`
6
- `)return["",n+3];if(o===`
7
- `||o==="\r")return["",n+2];if(o in ro)return[ro[o],n+2];let s=o==="x"?2:o==="u"?4:o==="U"&&t==="py"?8:0;if(s){let r=e.slice(n+2,n+2+s);if(r.length===s&&io.test(r)){let i=parseInt(r,16);if(i<=1114111)return[String.fromCodePoint(i),n+2+s]}}if(o==="u"&&t==="js"&&e[n+2]==="{"){let r=e.indexOf("}",n+3),i=r===-1?"":e.slice(n+3,r);if(io.test(i)&&parseInt(i,16)<=1114111)return[String.fromCodePoint(parseInt(i,16)),r+1]}if(t==="py"){if(o==="a")return["\x07",n+2];if(o>="0"&&o<="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(o==="N"&&e[n+2]==="{"){let r=e.indexOf("}",n+3);if(r!==-1)return[e.slice(n,r+1),r+1]}}return t==="js"&&o==="0"?["\0",n+2]:[o,n+2]}function Oe(e,n){let t="",o=0;for(;o<e.length;){if(e[o]!=="\\"||o+1>=e.length){t+=e[o++];continue}let[s,r]=Or(e,o,n);t+=s,o=r}return t}var Rr=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function ao(e,n){let t=e[n],o=n+1;for(;o<e.length;){let s=e[o];if(s==="\\")o+=be(e,o);else{if(s===t)return o+1;if(s===`
8
- `||s==="\r")return o;o++}}return e.length}function Ir(e,n,t=!1){let o=["t"],s=[],r=-1,i,l,a=(u,f,p)=>{l=i,i={kind:u,text:e.slice(f,p),start:f,end:p}},c=n+1;for(;c<e.length;){let u=o[o.length-1],f=e[c];if(u==="t")if(f==="\\")c+=be(e,c);else if(f==="`"){if(t&&a("template",c,c+1),c++,o.pop(),o.length===0)return{end:c,closed:!0,interpolations:s}}else f==="$"&&e[c+1]==="{"?(i=l=void 0,o.length===1&&(r=c),o.push(1),c+=2):c++;else if(f==="'"||f==='"'){let p=ao(e,c);t&&a("string",c,p),c=p}else if(f==="`")o.push("t"),c++;else if(f==="/"&&e[c+1]==="/")c=Je(e,c);else if(f==="/"&&e[c+1]==="*")c=co(e,c);else if(t&&f==="/"&&fo(i,l)){let p=uo(e,c);a("regex",c,p),c=p}else if(f==="{")t&&a("punct",c,c+1),o[o.length-1]=u+1,c++;else if(f==="}")t&&a("punct",c,c+1),c++,u===1?(o.pop(),o.length===1&&s.push([r,c])):o[o.length-1]=u-1;else if(t&&(Ke(f)||ee(f))){let p=ee(f)?ze(e,c):Ue(e,c);a(ee(f)?"number":"ident",c,p),c=p}else t&&!Be(f)&&a("punct",c,c+1),c++}return r!==-1&&o.length>1&&s.push([r,e.length]),{end:e.length,closed:!1,interpolations:s}}function $r(e,n,t){let o=t.closed?t.end-1:t.end,s="",r=n+1;for(let[i,l]of t.interpolations)s+=Oe(e.slice(r,i),"js")+e.slice(i,Math.min(l,o)),r=l;return s+Oe(e.slice(r,o),"js")}function co(e,n){let t=e.indexOf("*/",n+2);return t===-1?e.length:t+2}function uo(e,n){let t=n+1,o=!1;for(;t<e.length;){let s=e[t];if(s===`
9
- `||s==="\r")return t;if(s==="\\")t+=be(e,t);else if(s==="[")o=!0,t++;else if(s==="]")o=!1,t++;else if(s==="/"&&!o){t++;break}else t++}for(;t<e.length&&/[a-z]/i.test(e[t]);)t++;return Math.min(t,e.length)}function vr(e,n){return e.kind==="punct"&&(e.text==="+"||e.text==="-")&&n?.text===e.text&&n.end===e.start}function fo(e,n){if(!e)return!0;if(vr(e,n))return!1;switch(e.kind){case"ident":return Rr.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 po(e){let n=new Ee(e),t,o,s=(i,l,a,c,u=!1)=>{n.push(i,l,a,c,u),i!=="comment"&&(o=t,t=n.tokens[n.tokens.length-1])},r=0;for(;r<e.length;){let i=e[r],l=e[r+1];if(Be(i)){r++;continue}let a;if(i==="/"&&l==="/")a=Je(e,r),s("comment",r,a);else if(i==="/"&&l==="*")a=co(e,r),s("comment",r,a);else if(i==="'"||i==='"')a=ao(e,r),s("string",r,a,Oe(Lr(e,r,a,i),"js"));else if(i==="`"){let c=Ir(e,r);a=c.end,s("template",r,a,$r(e,r,c),c.interpolations.length>0)}else i==="/"&&fo(t,o)?(a=uo(e,r),s("regex",r,a)):ee(i)||i==="."&&ee(l??"")?(a=ze(e,r),s("number",r,a)):Ke(i)?(a=Ue(e,r),s("ident",r,a)):(a=r+1,s("punct",r,a));r=a}return n.tokens}function Lr(e,n,t,o){let s=0;for(let i=t-2;i>n&&e[i]==="\\";i--)s++;let r=t-n>1&&e[t-1]===o&&s%2===0;return e.slice(n+1,r?t-1:t)}var Ar=new Set(["r","b","f","u","rb","br","fr","rf"]);function go(e,n,t=!1,o){let s=e[n],r=e.startsWith(s.repeat(3),n),l=n+(r?3:1),a=l,c=0,u=[];for(;a<e.length;){let f=e[a];if(f==="\\")a+=be(e,a);else if(t&&f==="{"&&c===0&&e[a+1]==="{")a+=2;else if(t&&f==="{"){let p=u.at(-1);o&&(c===0||p?.format&&c===p.depth?u.push({start:a+1,depth:c+1,nesting:0,format:!1}):p&&!p.format&&p.nesting++),c++,a++}else if(t&&f==="}"&&c>0){let p=u.at(-1);p?.depth===c?(p.format||o?.push([p.start,a]),u.pop()):p&&!p.format&&p.nesting--,c--,a++}else if(o&&u.length&&!u.at(-1).format&&"()[]".includes(f))u.at(-1).nesting+="([".includes(f)?1:-1,a++;else if(o&&f===":"&&u.length&&!u.at(-1).format&&u.at(-1).nesting===0){let p=u.at(-1);o.push([p.start,a]),p.format=!0,a++}else if(c>0&&!u.at(-1)?.format&&(f==='"'||f==="'")&&!e.startsWith(f.repeat(3),a)&&mo(e,a)!==-1)a=mo(e,a);else{if(r&&e.startsWith(s.repeat(3),a))return{end:a+3,bodyStart:l,bodyEnd:a};if(!r&&f===s)return{end:a+1,bodyStart:l,bodyEnd:a};if(!r&&(f===`
10
- `||f==="\r"))return{end:a,bodyStart:l,bodyEnd:a};a++}}return{end:e.length,bodyStart:l,bodyEnd:e.length}}function mo(e,n){let t=go(e,n);return t.end>t.bodyEnd?t.end:-1}function xo(e){let n=new Ee(e),t=0;for(;t<e.length;){let o=e[t];if(Be(o)){t++;continue}if(o==="#"){let s=Je(e,t);n.push("comment",t,s),t=s}else if(o==='"'||o==="'")t=ho(n,t,t,"");else if(ee(o)||o==="."&&ee(e[t+1]??"")){let s=ze(e,t);n.push("number",t,s),t=s}else if(Ke(o)){let s=Ue(e,t),r=e.slice(t,s).toLowerCase();(e[s]==='"'||e[s]==="'")&&Ar.has(r)?t=ho(n,t,s,r):(n.push("ident",t,s),t=s)}else n.push("punct",t,t+1),t++}return n.tokens}function ho(e,n,t,o){let s=go(e.text,t,o.includes("f")),r=e.text.slice(s.bodyStart,s.bodyEnd);return e.push("string",n,s.end,o.includes("r")?r:Oe(r,"py"),o.includes("f")),s.end}var Pr={ts:"js",tsx:"js",js:"js",jsx:"js",mjs:"js",cjs:"js",mts:"js",cts:"js",py:"py"};function G(e){let n=e.slice(e.lastIndexOf("/")+1),t=n.lastIndexOf(".");return t===-1?null:Pr[n.slice(t+1).toLowerCase()]??null}function ft(e,n){return n==="py"?xo(e):po(e)}function V(e,n,t){let o=ft(n,t).filter(s=>s.kind!=="comment");return{path:e,text:n,lang:t,toks:o}}function d(e,n){return e?.kind==="punct"&&e.text===n}function h(e,n){return e?.kind==="ident"&&(n===void 0||e.text===n)}function B(e){return e?.kind==="string"||e?.kind==="template"}function pt(e){let n=/^[A-Za-z]*/.exec(e.text)[0],t=e.text.slice(n.length),o=t[0]??"",s=t.startsWith(o.repeat(3))&&t.length>=6?3:1,r=t.length>=2*s&&t.endsWith(o.repeat(s));if(r){let i=0;for(let l=t.length-s-1;l>=0&&t[l]==="\\";l--)i++;r=i%2===0}return{prefix:n,width:s,inner:t.slice(s,r?t.length-s:void 0),closed:r}}function N(e,n){return d(e[n],"=")&&!d(e[n+1],"=")&&!d(e[n+1],">")}var re=["function","def","class"],ie=12;function U(e,n){return n===0||e[n].line>e[n-1].endLine}function ae(e,n){return n.start-(e.lastIndexOf(`
11
- `,n.start-1)+1)}function $(e,n){let t=0;for(let o=n;o<e.length;o++)if(e[o].kind==="punct"){if("([{".includes(e[o].text))t++;else if(")]}".includes(e[o].text)&&--t===0)return o}return e.length}function W(e,n){let t=$(e,n),o=[],s=n+1,r=0;for(let i=n+1;i<t;i++){let l=e[i];l.kind==="punct"&&"([{".includes(l.text)?r++:l.kind==="punct"&&")]}".includes(l.text)?r--:r===0&&d(l,",")&&(o.push({from:s,to:i}),s=i+1)}return s<t&&o.push({from:s,to:t}),o}function dt(e,n,t){let o=$(e,n),s=[],r=n+1,i=0,l=!1,a=0;for(let c=n+1;c<o;c++){let u=e[c];if(u.kind==="punct")if("([{".includes(u.text))i++;else if(")]}".includes(u.text))i--;else{if(i!==0)continue;u.text===","&&a===0?(s.push({from:r,to:c}),r=c+1,l=!1):u.text===":"&&!l?l=!0:l&&(t==="js"&&u.text==="<"?a++:t==="js"&&u.text===">"&&a>0&&!d(e[c-1],"=")?a--:a===0&&N(e,c)&&(l=!1))}}return r<o&&s.push({from:r,to:o}),s}var jr=100;function Re(e){return e.replace(/\s+/g," ").trim().slice(0,jr)}function z(e){return e.lang==="py"?Ur(e):Nr(e)}var Mr=new Set(["@anthropic-ai/sdk","anthropic","openai","ai","@anthropic-ai/claude-agent-sdk","claude_agent_sdk","@openai/agents"]);function So(e,n,t={},o){let s=n==="py"?e.split(".")[0]:e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0];return s==="@openai/agents"?t.layouts===!0:n==="py"&&s==="agents"?t.layouts===!0&&(t.openaiAgents===!0||!!o&&Cr(o)):Mr.has(s)||s.startsWith("@ai-sdk/")||s.startsWith("@langchain/")||s.startsWith("langchain")}function Cr({toks:e}){let n=(t,o=!1)=>e.some((s,r)=>h(s,t)&&!re.includes(e[r-1]?.text??"")&&(d(e[r+1],"(")||o&&d(e[r+1],".")));return n("Agent")&&n("Runner",!0)}var Tr=[".","/","@/","~/"];function Ie(e,n){return e.filter(t=>n==="py"||Tr.some(o=>t.source.startsWith(o))).flatMap(t=>t.names.map(o=>({name:o,imported:t.renamed?.[o]??o,source:t.source,line:t.line})))}function Nr(e){let{toks:n}=e,t=[];for(let o=0;o<n.length;o++)if(h(n[o],"import")&&!d(n[o-1],".")){let s=d(n[o+1],"(")?Fr(e,o+1):Wr(e,o);s&&t.push(s)}else h(n[o],"require")&&d(n[o+1],"(")&&B(n[o+2])&&d(n[o+3],")")&&t.push({source:n[o+2].value,line:n[o].line,...Br(e,o)});return t}function Fr(e,n){let t=e.toks[n+1];return B(t)&&d(e.toks[n+2],")")?{source:t.value,line:t.line,names:[]}:null}var Dr=80;function Wr(e,n){let{toks:t}=e,o=Math.min(t.length,n+Dr);for(let s=n+1;s<o;s++){let r=t[s];if(B(r))return s!==n+1&&!h(t[s-1],"from")?null:{source:r.value,line:t[n].line,...Kr(e,n+1,s)};if(d(r,";")||h(r,"import"))return null}return null}function Kr(e,n,t){let{toks:o}=e,s=[],r={},i=h(o[n],"type")&&yo(o[n+1])?n+1:n,l=h(o[i])?o[i].text:void 0;for(let a=n;a<t;a++){let c=o[a];if(!(!h(c)||c.text==="from"))if(c.text==="as")h(o[a+1])&&(s.push(o[++a].text),h(o[a-2])&&(r[o[a].text]=o[a-2].text));else{if(h(o[a+1],"as"))continue;(c.text!=="type"||!yo(o[a+1]))&&s.push(c.text)}}return{names:s,renamed:r,...l?{defaultName:l}:{}}}function yo(e){return d(e,"{")||h(e)&&e?.text!=="from"}function Br(e,n){let{toks:t}=e,o={names:[],renamed:{}};if(!d(t[n-1],"="))return o;if(h(t[n-2]))return{names:[t[n-2].text],renamed:{}};if(!d(t[n-2],"}"))return o;let s=n-2;for(;s>0&&!d(t[s],"{");)s--;let r=[],i={};for(let l=s+1;l<n-2;l++)!h(t[l])||d(t[l+1],":")||(r.push(t[l].text),d(t[l-1],":")&&h(t[l-2])&&(i[t[l].text]=t[l-2].text));return{names:r,renamed:i}}function Ur(e){let{toks:n}=e,t=[];for(let o=0;o<n.length;o++)if(U(n,o)){if(h(n[o],"import"))t.push(...zr(e,o+1));else if(h(n[o],"from")){let s=wo(e,o+1);s.next>o+1&&h(e.toks[s.next],"import")&&t.push({source:s.text,line:n[o].line,...Jr(e,s.next+1)})}}return t}function wo(e,n){let{toks:t}=e,o=n,s=!1;for(;;){if(d(t[o],"."))s=!1;else if(h(t[o])&&!s&&t[o].text!=="import")s=!0;else break;o++}return{text:t.slice(n,o).map(r=>r.text).join(""),next:o}}function zr(e,n){let{toks:t}=e,o=[],s=n;for(;;){let r=wo(e,s);if(r.next===s||(o.push({source:r.text,line:t[n].line,names:[]}),s=r.next,h(t[s],"as")&&(s+=2),!d(t[s],",")))break;s++}return o}function Jr(e,n){let{toks:t}=e,o=d(t[n],"("),s=o?$(t,n):t.length,r=[],i={};for(let l=o?n+1:n;l<s&&!(!o&&(U(t,l)||d(t[l],";")));l++)h(t[l])&&(h(t[l+1],"as")&&h(t[l+2])?(r.push(t[l+2].text),i[t[l+2].text]=t[l].text,l+=2):r.push(t[l].text));return{names:r,renamed:i}}var mt=["eval","evals"],Xr=new RegExp(`(^|/)(${[...mt,"evaluations?","bench(?:mark)?s?"].join("|")})/`,"i"),Gr=/^(evals?|bench(?:mark)?s?)[_-].+|.+[._-](evals?|bench(?:mark)?s?)[._-]/i;function ko(e,n){if(Xr.test(e))return!0;let t=G(e);if((t||/\.(json|ya?ml|toml)$/i.test(e))&&Gr.test(e.split("/").at(-1)))return!0;if(!t||n===void 0||!/(^|\/)scripts\//i.test(e))return!1;let o=V(e,n,t),{toks:s}=o;if(s.some((p,m)=>h(p,"export")||h(p,"exports")||t==="py"&&h(p,"def")||h(p,"module")&&d(s[m+1],".")&&h(s[m+2],"exports"))||!s.some(p=>h(p)&&/^(expected|dataset|fixtures|cases)$/i.test(p.text)))return!1;let r=s.flatMap((p,m)=>h(p)&&d(s[m+1],"(")&&!["for","if","while","switch","catch"].includes(p.text)&&!["function","def","class"].includes(s[m-1]?.text)?[m]:[]),l=z(o).filter(p=>p.names.some(m=>r.some(x=>h(s[x],m)&&!d(s[x-1],".")))),a=/(^|[/._-])(scores?|scoring|graders?|grading|evals?|evaluators?|bench(?:mark)?s?)([/._-]|$)/i,c=l.filter(p=>p.source.startsWith(".")&&/(^|[/._-])(agents?|runners?)([/._-]|$)/i.test(p.source)),u=[...c,...l.filter(p=>a.test(p.source))],f=new Set(u.flatMap(p=>p.names));return r.some(p=>d(s[p-1],".")?!(h(s[p-2],"console")&&["log","table"].includes(s[p].text)):h(s[p],"require")&&s[p+2]?.kind==="string"&&u.some(m=>m.source===s[p+2].value)?!1:!f.has(s[p].text)&&!(t==="py"&&h(s[p],"print")))?!1:l.some(p=>a.test(p.source))&&c.some(p=>!a.test(p.source))}function ht(e){return e.CF_IMPORT_CALLS==="1"}var $e={archive:{bytes:6e7,files:2e4},conventionImport:{fileBytes:5e4,totalBytes:12e4,skillBytes:6e5,skillFiles:60,extractionFiles:25},sourceFetch:{instructionBytes:6e5,codeBytes:3e5,htmlReferenceBytes:3e4,codeFileBytes:6e4,codeFiles:60},codeScan:{files:400,bytes:3e6,fileBytes:2e5},candidateFetch:{check:12e4,pointers:12e4},codeAgent:{extraBytes:4e4,importBytes:2e6,toolCodeFiles:5},survey:{fileBytes:5e6,files:60},localCheck:{uploadBytes:18e5},verification:{sourceBytes:12e4}};function ve(e){return e.CF_IMPORT_LAYOUTS==="1"}var Eo=/(^|\/)(__tests__|__snapshots__)\/|\.(test|spec)\.[jt]sx?$|_test\.(go|py)$/i,qr=new Set(["test","tests","__tests__","spec","specs","testdata","test-data","test_data","test-support","mocks","fixtures","fixture","__fixtures__","__mocks__","__snapshots__"]),Vr=/^(examples?|samples?)(?:[-_].+)?$|^.+[-_](examples?|samples?)$/i,Hr=/\.(test|spec)\..+|^test_.*\.py$|_test\.(py|go)$|_spec\.rb$|^conftest\.py$/i,Yr=new Set(["example-agents","examples","example","fixtures","__fixtures__","testdata","test","tests","__tests__","demo","demos"]),Zr=/^examples?[-_]/i;function bo(e,n,t){if(e.CF_IMPORT_INCLUDE_EXAMPLES==="1")return!1;let o=r=>Yr.has(r.toLowerCase())||Zr.test(r);if(We(t).split("/").some(o))return!1;let s=D(n,t);return s!==null&&s.split("/").slice(0,-1).some(o)}var _o=new WeakMap;function Qr(e){let n=_o.get(e);if(n)return n;let t={exact:new Set,foldedNames:new Set};for(let o of e.keys()){let s=0;for(let r=o.indexOf("/");r!==-1;r=o.indexOf("/",s))t.exact.add(o.slice(0,r)),t.foldedNames.add(o.slice(0,s)+o.slice(s,r).toLowerCase()),s=r+1}return _o.set(e,t),t}function ei(e,n,t){let o=e.some(s=>qt(n(s),t)===null);return s=>{let r=qt(s,t);return r==="test"||r==="example"&&o}}function Oo(e,n,t){let o=ei(e,n,t),s=[],r=[];for(let i of e)(o(n(i))?r:s).push(i);return{kept:s,skipped:r}}function Vt(e,n){return qt(e,n)!==null}function qt(e,n){let t=D(e,n.root);return t?ti(e,t,n):null}function ti(e,n,t){let o=Qr(t.listing),s=e.endsWith("/")||o.exact.has(e),r=n.split("/").filter(Boolean),i=s?"":r.pop()??"";return Hr.test(i)||r.some(a=>qr.has(a.toLowerCase()))?"test":r.some((a,c)=>{let u=a.toLowerCase();if(Vr.test(u))return!0;if(u!=="before"&&u!=="after")return!1;let f=We(ct(r.slice(0,c).join("/"),t.root)),p=f?`${f}/`:"",m=u==="before"?"after":"before";return o.foldedNames.has(p+m)})?"example":null}var ni=new Set,Ro=new WeakMap;function Io(e,n){let t={root:n.root,listing:n.listing??ni};if(!Vt(e,t))return!1;let o=n.listing;if(!o?.has(e))return!0;let s=Ro.get(o);s||Ro.set(o,s=new WeakMap);let r=s.get(n.settings);r||s.set(n.settings,r=new Map);let i=r.get(n.key);if(!i){let l=[...o.keys()].filter(a=>Vt(a,t)||n.readable(a,"get"in o?o.get(a):void 0));i=new Set(Oo(l,a=>a,t).skipped),r.set(n.key,i)}return i.has(e)}function $o(e){return e.CF_IMPORT_EXAMPLE_FILTER!=="0"}function vo({codeAgentsFound:e,folderAgentsFound:n=!1,otherDefinitions:t,usage:o="import"}){return n?"background":o==="scan"?t?"prompt":"background":o==="map"?e?"background":"prompt":e&&!t?"background":"prompt"}function gt(e,n){return e.CF_IMPORT_COVERAGE==="1"&&(n===void 0||e[n]==="1")}import{posix as Ht}from"node:path";var Yt=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function ce(e,n={}){let t=`(?:${Ge.map(Yt).join("|")})`,o=`(?:${xt.map(Yt).join("|")})`,r=new RegExp(`^(${n.nested?"(?:.*?/)??":""}(?:(${t}/[^/]+)/${Xe}|${o})/([^/]+))/(.+)$`,n.caseSensitive?"":"i").exec(e);if(!r)return null;let i=n.caseSensitive?r[4]:r[4].toLowerCase(),l=n.caseSensitive?M.skill:M.skill.toLowerCase();return{folder:r[1],name:r[3],definition:i===l,reference:i.startsWith("references/"),...r[2]?{ownerPath:r[1].replace(/\/skills\/[^/]+$/i,".md")}:{}}}function Zt(e){return ce(e)?.reference??!1}function oi(e){return gt(e,"CF_DISCOVERY_SKILLS")}function si(e){return!/[\\:\0]/.test(e)&&e.split("/").every(n=>n&&n!=="."&&n!=="..")}function ri(e){let n=[],t;for(let[o,s]of e.split(/\r?\n/).entries()){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(t){if(r&&r[1][0]===t.marker[0]&&r[1].length>=t.marker.length&&!r[2].trim()){t=void 0;continue}if(!t.shell||!/^\s*(?:\$\s+)?(?:cat|less|more|head|tail)\s+/.test(s))continue}if(!t&&r){t={marker:r[1],shell:/^(?:sh|bash|shell|console)?$/i.test(r[2].trim())};continue}let i=/!?\[[^\]\n]*\]\(\s*(?:<([^>\n]+)>|([^\s)\n]+))(?:\s+["'][^"'\n]*["'])?\s*\)|^\s*\[[^\]]+\]:\s*(?:<([^>]+)>|(\S+))|`([^`\n]+)`|([^\s`<>"'()[\],;]+)/g;for(let l of s.matchAll(i)){let a=l.slice(1,5).some(m=>m!==void 0),c=l[1]??l[2]??l[3]??l[4]??l[5]??l[6],u=a?c:c.replace(/[.,;:]+$/,""),f=/^[^.\s][^\s]*\.(?:md|mdx|rst|txt|html?|json|ya?ml|toml|csv|ts|tsx|js|jsx|mjs|cjs|py|go|java|rb|rs|sh|prompt)(?:#.*)?$/i.test(u.split(/[/\\]/).at(-1)??""),p=l[5]!==void 0&&/[/\\]/.test(u)||/^\.{1,2}[/\\]/.test(u);u.startsWith("#")||!a&&(/\s/.test(u)||!(p||f))||n.push({target:u,span:{from:o+1,to:o+1}})}}return n}function Sc(e,n){let t={references:[],cycles:[],unresolved:[]};if(!oi(e))return t;let o=[...new Set(n.paths)].filter(r=>si(r)&&D(r,n.root)!==null).sort(),s=new Set(o);for(let r of[...new Set(n.skillPaths)].sort()){if(!s.has(r)||!ce(r,{nested:!0})?.definition)continue;let i=new Set,l=new Set,a=c=>{if(!(i.has(c)||!Object.hasOwn(n.files,c))){i.add(c),l.add(c);for(let{target:u,span:f}of ri(n.files[c])){let p=y=>t.unresolved.push({ownerPath:r,fromPath:c,target:u,span:f,reason:y}),m=u.split("#")[0];if(!m||/[\\:\0*?[\]$]/.test(m)||m.startsWith("/")||/[{}]/.test(m.replace(/(?:^|\/)\{lang\}(?=\/)/g,""))){p("unsupported");continue}let x=Ht.normalize(Ht.join(Ht.dirname(c),m));if(x===".."||x.startsWith("../")||D(x,n.root)===null){p("out-of-scope");continue}let w=new RegExp(`^${x.split("/").map(y=>y==="{lang}"?"[^/]+":Yt(y)).join("/")}$`),S=x.includes("{lang}")?o.filter(y=>w.test(y)):s.has(x)?[x]:[];if(!S.length){p("missing");continue}for(let y of S){let b={ownerPath:r,fromPath:c,path:y,span:f};l.has(y)?t.cycles.push(b):(t.references.push(b),a(y))}}l.delete(c)}};a(r)}return t}var tn="readme";function Rc(e){let n=e.toLowerCase();return n.startsWith(tn)?0:n===M.agentGuide?1:n.endsWith(".md")&&e.split("/").length<=2?2:Lo.test(e)?3:null}var M={systemPrompt:"system_prompt.md",hyphenatedPrompt:"system-prompt.md",unseparatedPrompt:"systemprompt.md",system:"system.md",prompt:"prompt.md",promptFallback:"CLAUDE.md",soul:"soul.md",knowledge:"knowledge.md",tools:"tools.json",toolsSource:"tools.ts",cli:".cli.json",config:"counterfact.json",skill:"SKILL.md",readme:`${tn}.md`,agentGuide:"agents.md"},yt=[M.systemPrompt,M.hyphenatedPrompt,M.system,M.prompt],St=M.promptFallback,ii=[...yt,St].map(e=>e.toLowerCase()),wt=[".mcp.json","mcp.json"],li=[M.toolsSource,M.cli],ue=".claude",Qt="agents",Xe="skills",Ge=[`${ue}/${Qt}`,Qt],xt=[Xe,`${ue}/${Xe}`],ai=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ci=e=>e.map(ai).join("|"),ui=`(?:${ci(Ge)})`,fi=new RegExp(`^${ui}/[^/]+\\.md$`,"i"),pi=/^templates\/.+/i;function Ic(e,n){return ce(e,n)?.definition??!1}function qe(e){return e.CF_DISCOVERY_SKILLS!=="0"}var nn=new Map([...yt.map(e=>[e,{role:"prompt",kind:"dedicated"}]),[St.toLowerCase(),{role:"prompt",kind:"fallback"}],[M.soul,{role:"soul"}],[M.knowledge,{role:"knowledge"}],[M.config,{role:"marker"}],[M.tools,{role:"tool file",kind:"json"}],[M.toolsSource,{role:"tool file",kind:"sdk"}],[M.cli,{role:"tool file",kind:"cli"}],...wt.map(e=>[e,{role:"MCP config"}])]),di=[...nn.keys()];function en(e){let n=nn.get(e.toLowerCase());if(n)return n;if(fi.test(e))return{role:"sub-agent"};let t=ce(e),o=t?.ownerPath?{ownerPath:t.ownerPath}:{};return t?.definition?{role:"skill",name:t.name,...o}:t?.reference?{role:"reference",kind:"skill",name:t.name,...o}:pi.test(e)?{role:"reference",kind:"template"}:null}function mi(e){let n=en(e);return!!n&&n.role!=="skill"&&n.role!=="reference"}var hi=["package.json","pyproject.toml","go.mod","cargo.toml"],gi=[...di.filter(e=>!li.includes(e)),...hi],xi=new RegExp(`^${tn}[^/]*$`,"i");function kt(e,n,t){let o=ve(e)?t?.ownerOf(n):void 0;return o?D(n,o.folder)??n:n}function on(e,n,t){if(ve(e)&&t?.files?.some(l=>l.path===n&&l.kind==="entry"))return!0;n=kt(e,n,t);let o=n.split("/").pop()??"",s=ce(n),r=s?.definition&&(qe(e)||!s.ownerPath&&!s.folder.startsWith(`${ue}/`)),i=s?.reference&&s.ownerPath&&qe(e);return gi.includes(o.toLowerCase())||xi.test(o)||mi(n)||!!r||!!i}var $c=[...yt,St].join(", "),vc=`${M.config}, a system prompt file, ${M.tools}, an MCP config, ${M.soul}, ${M.knowledge}, ${Qt}/*.md and ${Xe}/*/${M.skill}`,Lc=/(agent|tool|prompt|llm|model|chain|graph|pipeline|workflow|handler|route|server|main|index|app|orchestr)/i,Ac=/(^|\/)prompts?\/.*\.(md|txt|prompt)$/i;function Pc(e,n,t={}){let o=n.flatMap(p=>{let m=D(p,t.root);return m===null?[]:[{path:p,relativePath:m}]}),s=o.filter(({path:p})=>Le(e,{path:p},{purpose:"override",route:"github"}).admitted),r=new Map(s.map(p=>[p.relativePath.toLowerCase(),p.path])),i=yt.map(p=>r.get(p)).find(Boolean),l=wt.map(p=>r.get(p)).find(Boolean),a=r.has(M.soul)&&!ii.some(p=>r.has(p)),c=p=>[St.toLowerCase(),M.agentGuide].includes(p.toLowerCase()),u=vo({codeAgentsFound:t.codeAgentsFound??!1,folderAgentsFound:t.folderAgentsFound,otherDefinitions:s.some(({relativePath:p})=>{let m=en(p);return!c(p)&&!!m&&m.role!=="reference"})}),f=[];for(let p of s){let m=u==="background"&&c(p.relativePath),x=m?{role:"knowledge",kind:"background"}:en(p.relativePath);if(!x||t.mode==="core"&&(x.role==="skill"||x.role==="reference"))continue;let w;m?w=p.path===r.get(p.relativePath.toLowerCase()):x.role==="prompt"&&x.kind==="dedicated"?w=p.path===i:x.role==="MCP config"?w=p.path===l:nn.has(p.relativePath.toLowerCase())&&(w=p.path===r.get(p.relativePath.toLowerCase()));let S=x.ownerPath?{ownerPath:r.get(x.ownerPath.toLowerCase())??null}:{};f.push({...p,...x,...S,...w===void 0?{}:{preferred:w}})}return{files:f,scoped:o,registry:a}}var fe=/\.(?:md|txt|j2|hbs|mustache|prompt)$/i,Ao=/(?:^|[/\\])(?:prompts?|templates?|instructions)(?=$|[/\\])/i,yi=/prompt|instructions|system/i,Si=200;function sn(e){if(!fe.test(e))return!1;let n=e.split("/"),t=n[n.length-1];return n.slice(0,-1).some(s=>s.toLowerCase()==="prompts")||yi.test(t)}function Po(e,n){return!sn(e)||Buffer.byteLength(n)<Si?null:wi(e,n)}function wi(e,n){let t=Buffer.byteLength(n),o=n.split(`
12
- `).length;return{kind:"file",named:!1,prose:!1,path:e,start:0,line:1,endLine:o,span:{from:1,to:o},symbol:null,chars:t,excerpt:Re(n),enclosing:null}}function rn(e){return/(?:^|\/)(?:pyproject\.toml|requirements\.txt)$/i.test(e)}function Nc(e,n){if(!rn(e))return!1;let t=n.split(/\r?\n/).map(r=>r.replace(/("(?:\\.|[^"\\])*"|'[^']*')|#.*/g,(i,l)=>l??""));if(/(?:^|\/)requirements\.txt$/i.test(e))return t.some(r=>/^\s*openai[-_.]agents(?:\[[^\]]*\])?(?=\s*(?:$|[<>=!~;@#]))/i.test(r));let o="",s=new Map;for(let r of t){let i=/^\s*\[([^\]]+)\]/.exec(r);i?o=i[1]:(s.has(o)||s.set(o,[]),s.get(o).push(r))}for(let[r,i]of s){let l=i.join(`
13
- `);if(/^tool\.poetry(?:\.group\.[^.]+)?\.dependencies$/.test(r)){if(/^\s*["']?openai[-_.]agents["']?\s*=/im.test(l))return!0}else if(["project","project.optional-dependencies","dependency-groups"].includes(r)){let a=/^\s*([\w."'-]+)\s*=\s*\[((?:"(?:\\.|[^"\\])*"|'[^']*'|[^\]"'])*)\]/gm;for(let c of l.matchAll(a))if(!(r==="project"&&c[1].replace(/["']/g,"")!=="dependencies")&&/["']openai[-_.]agents(?=["'[<>=!~ ;@])/i.test(c[2]))return!0}}return!1}function jo(e){return/\.json$/i.test(e)?"json":/\.ya?ml$/i.test(e)?"yaml":G(e)||/\.(cs|go|rb|java)$/i.test(e)?"code":/\.(md|markdown)$/i.test(e)?"markdown":"text"}import{dirname as Sa,isAbsolute as wa,posix as at,relative as or,resolve as sr,sep as ka}from"node:path";function Mo(e){return{salesforce:"Salesforce",slack:"Slack",s3:"S3",anthropic:"Anthropic","http-client":"HTTP client"}[e.toLowerCase()]??e}function Co(e){let n=new Map;for(let t of e)!t.unitKey||!t.scope||(n.has(t.scope)||n.set(t.scope,new Map),n.get(t.scope).set(t.unitKey,t.id));return e.flatMap(t=>!t.unitKey||!t.scope?[]:(t.links??[]).flatMap(o=>{let s=n.get(t.scope)?.get(o.to);return s?[{from:t.id,to:s,kind:"invokes",label:o.kind,sourceRef:o.source??null}]:[]}))}function To(e,n,t){let o;try{let s=JSON.parse(e),r=s?.mcpServers??s?.servers;o=r&&typeof r=="object"?Object.keys(r):[]}catch{return{servers:[],warnings:[`${n} is not valid JSON; ignored`]}}return{servers:o,warnings:!t&&o.length?[`found MCP config (servers: ${o.join(", ")}) but no ${M.tools}; tool schemas are discovered from a running server and were not extracted`]:[]}}import{z as pe}from"zod";var ki=pe.object({name:pe.string().min(1,"tool name is required"),description:pe.string().optional(),input_schema:pe.record(pe.string(),pe.unknown()).optional()}),_i=pe.array(ki);function No(e){let n=[];if(e==null)return{tools:[],warnings:n};let t=e;if(typeof e=="string"){let s=e.trim();if(s==="")return{tools:[],warnings:n};try{t=JSON.parse(s)}catch(r){throw new Error(`tools is not valid JSON: ${r.message}`)}}let o=_i.safeParse(t);if(!o.success)throw new Error(`tools do not match the expected shape (an array of {name, description?, input_schema?}): ${o.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);return o.data.length===0&&n.push("no tools were provided"),{tools:o.data,warnings:n}}import{posix as ln}from"node:path";var H=e=>`${e.path}:${e.kind}:${e.start}`;function Ve(e){return e.slice(e.lastIndexOf("/")+1)}function Ei(e){return e.replace(/\.(tsx?|jsx?|mjs|cjs|py)$/,"").replace(/^(\.{1,2}\/)+/,"").replace(/^[@~]?\//,"").replace(/^\.+/,"").replace(/\./g,"/")}function _t(e,n){let t=Ei(n),o=e.replace(/\.[^./]+$/,"").replace(/\/index$/,"").replace(/\/__init__$/,"");return t.length>0&&(o===t||o.endsWith(`/${t}`))}function Et(e,n){let t=n.replace(/\\/g,"/").replace(/^(\.\/)+/,""),o=e.filter(s=>s.path===t||s.path.endsWith(`/${t}`));return o.length>0?o:e.filter(s=>Ve(s.path)===Ve(t))}function Ae(e,n,t){let o=H(n);e.set(o,[...e.get(o)??[],t])}function He(e,n,t){let o=t.source,s=r=>r.replace(/\.(tsx?|jsx?|mjs|cjs|py)$/,"").replace(/\/(?:index|__init__)$/,"");if(o.startsWith(".")){let r=n.path.endsWith(".py"),i=r?/^\.+/.exec(o)?.[0].length??0:0,l=r?"../".repeat(Math.max(0,i-1))+o.slice(i).replace(/\./g,"/"):o,a=s(ln.normalize(ln.join(ln.dirname(n.path),l)));return e.files.filter(c=>s(c.path)===a)}return e.files.filter(r=>_t(r.path,o))}function de(e,n,t,o){let s=(o.get(t)??[]).filter(c=>c.path===n.path);if(s.length)return s;let[r,i]=t.split("."),l=n.imports.find(c=>c.name===r);if(!l)return[];let a=new Set(He(e,n,l).map(c=>c.path));return(o.get(i??l.imported)??[]).filter(c=>a.has(c.path))}var Ot=/^(claude-[a-z0-9.-]+|gpt-[a-z0-9.-]+|o[1-9](-[a-z0-9-]+)?|gemini-[a-z0-9.-]+)$/,bi=/^\S+\.(?:md|txt|j2|hbs|mustache|prompt)$/i,bt=50,Fo=200;function Do(e){let n=[],t=[];for(let o of e.toks){if(!B(o))continue;o.kind==="string"&&Ot.test(o.value)&&n.length<bt&&n.push({value:o.value,path:e.path,line:o.line}),o.value.length<=Fo&&bi.test(o.value)&&t.length<bt&&t.push({value:o.value,path:e.path,line:o.line})}return{modelIds:n,fileRefs:t}}function Wo(e){let{toks:n}=e,t=[];for(let o=0;o<n.length&&t.length<bt;o++)if(!(!h(n[o])||!N(n,o+1)||!d(n[o+2],"{"))&&!(e.lang==="js"&&!h(n[o-1],"const")))for(let{from:s,to:r}of W(n,o+2)){let i=n[s],l=n[s+2];if(!(r!==s+3||!d(n[s+1],":")||l?.kind!=="string"||l.value.length>Fo||!Ot.test(l.value))&&!(!h(i)&&i?.kind!=="string")&&(t.push({object:n[o].text,member:i.kind==="string"?i.value:i.text,value:l.value,path:e.path,line:l.line}),t.length===bt))break}return t}import{posix as Pt}from"node:path";function Ko(e,n){let t=e?e.split("/"):[];for(let o of n.split("/"))if(!(o===""||o==="."))if(o===".."){if(t.pop()===void 0)return null}else t.push(o);return t.join("/")}function Oi(e,n=!1){let t=n?[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"]:[".ts",".tsx",".js"],o=e.replace(n?/\.(js|jsx|mjs|cjs)$/:/\.(js|jsx|mjs)$/,""),s=n&&e.endsWith(".mjs")?[".mts"]:n&&e.endsWith(".cjs")?[".cts"]:[".ts",".tsx"];return[e,...t.map(r=>e+r),...o===e?[]:s.map(r=>o+r),...t.map(r=>`${e}/index${r}`)]}function Ri(e,n,t){let o=n.length-n.replace(/^\.+/,"").length,s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r="../".repeat(o-1),i=n.slice(o).split(".").join("/"),l=Ko(s,r+i);return l===null?[]:i?[`${l}.py`,`${l}/__init__.py`]:[...t.map(a=>l?`${l}/${a}.py`:`${a}.py`),l?`${l}/__init__.py`:"__init__.py"]}function an(e,n,t,o,s=!1){if(!n.startsWith("."))return[];if(o==="py")return Ri(e,n,t);let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",i=Ko(r,n);return i===null?[]:Oi(i,s)}function Ye(e,n,t,o,s,r=!1){return an(e,n,t,o,r).find(i=>s.has(i))}import{posix as et}from"node:path";var Ii=new Set(["string","unknown","any","object","never","boolean","number","undefined","null","void"]),$i=new Set(["if","for","while","switch","catch","with"]),vi=24;function Bo(e){return Ii.has(e)}function J(e,n){let t=0;for(let o=n-1;o>=0;o--){let s=e.toks[o];if(s.kind==="punct"){if(")]}".includes(s.text))t++;else if("([{".includes(s.text)&&t--===0)return o}}return-1}function cn(e,n){let{toks:t}=e;if(!d(t[n],"("))return!1;let o=t[n-1];if(o&&h(o)&&$i.has(o.text))return!1;let s=$(t,n),r=t[s+1];return d(r,"{")||d(r,"=")&&d(t[s+2],">")?!0:d(r,":")&&h(t[n-2],"function")}function Uo(e,n){let{toks:t}=e;if(!d(t[n],"{"))return!1;for(let s=n-1;s>=0&&s>=n-vi;s--){let r=t[s];if(d(r,";")||d(r,"{")||d(r,"}"))break;if(h(r,"interface")||h(r,"type")&&h(t[s+1])&&(d(t[s+2],"=")||d(t[s+2],"<")))return!0}if(!d(t[n-1],":"))return!1;let o=J(e,n);return o>=0&&(Uo(e,o)||cn(e,o))}function un(e,n){let t=J(e,n);if(t<0)return!1;if(cn(e,t)||Uo(e,t))return!0;let o=d(e.toks[t],"{")?J(e,t):-1;return o>=0&&cn(e,o)}var Li=new Set(["if","for","while","switch","catch","return","function","def","class","elif","with","await","typeof"]),fn={js:new Set(["if","for","while","switch","catch","with"]),py:new Set(["if","elif","for","while","with","except"])},Ai={js:new Set([...fn.js,"return","yield","throw","await","typeof","void","delete","new","in","instanceof","case","else","do","default","extends"]),py:new Set([...fn.py,"return","yield","await","not","and","or","is","in","assert","raise","else","lambda","del"])};function te(e,n,t){if(!t)return h(e[n])&&!Li.has(e[n].text)&&d(e[n+1],"(");let o=n+1;if(!d(e[o],"("))return!1;let s=n,r=t.lang==="py"&&d(e[s],"\\");if(r&&s--,t.lang==="py"&&e[s]?.endLine<e[o].line&&!r&&J(t,o)<0)return!1;if(t.lang==="js"&&d(e[s],".")&&d(e[s-1],"?")&&(s-=2),t.lang==="js"&&d(e[s],">")){if(!/\.[cm]?tsx?$/.test(t.path))return!1;let i=0;do{if(d(e[s],";")||d(e[s],"="))return!1;d(e[s],">")?i++:d(e[s],"<")&&i--,s--}while(s>=0&&i>0);if(i!==0)return!1}for(;d(e[s],"]");)s=J(t,s)-1;if(d(e[s],")")){let i=e[J(t,s)-1];return!h(i)||!fn[t.lang].has(i.text)}return!h(e[s])||re.some(i=>h(e[s-1],i))||t.lang==="py"&&["match","case"].includes(e[s].text)&&U(e,s)&&d(e[$(e,o)+1],":")?!1:d(e[s-1],".")||!Ai[t.lang].has(e[s].text)}function me(e,n={}){let t=e.lang==="py"?Ui(e,!!n.includeMembers,!!n.promptFunctions):Ci(e,!!n.includeMembers,!!n.typedReturns);if(!n.includeMembers)return t;for(let o=0;o<e.toks.length;o++){if(!d(e.toks[o],"["))continue;let s=e.toks[o-1];if(o===0||h(s,"return")||s?.kind==="punct"&&"=:(,[>".includes(s.text))for(let[i,l]of W(e.toks,o).entries())t.push({name:`[${i}]`,line:e.toks[l.from].line,from:l.from-1,to:l.to,params:null,kind:"index"})}return t.map(o=>({...o,kind:o.kind??(o.params===null?"value":"function")}))}function Y(e,n){return zo(e,n).at(-1)?.name??null}function zo(e,n){return e.filter(t=>t.from<n&&n<t.to).sort((t,o)=>t.from-o.from)}var Pi="=+-*/,([{:?.&|<>!%",ji=".+-*/?:,|&)]}";function Pe(e,n,t){let{toks:o}=e,s=0;for(let r=n;r<o.length;r++){t?.(1);let i=o[r];if(i.kind==="punct"&&"([{".includes(i.text))s++;else{if(i.kind==="punct"&&")]}".includes(i.text)&&--s<0)return r;if(s===0&&d(i,";")&&e.lang==="js")return r+1}if(s===0&&r>n&&U(o,r)&&Mi(e,r))return r}return o.length}function Mi(e,n){if(e.lang==="py")return!0;let t=e.toks[n-1],o=e.toks[n],s=t.kind==="punct"&&Pi.includes(t.text),r=o.kind==="punct"&&ji.includes(o.text);return!s&&!r}function Ze(e,n,t){let{toks:o}=e,s=[];for(let{from:r,to:i}of dt(o,n,t)){let l=r;for(;l<i&&o[l].kind==="punct"&&(o[l].text==="*"||o[l].text===".");)l++;i-r===1&&o[r].kind==="punct"&&["*","/"].includes(o[r].text)||s.push(l<i&&h(o[l])?o[l].text:null)}return t==="py"&&(s[0]==="self"||s[0]==="cls")&&s.shift(),s}function Ci(e,n,t){let{toks:o}=e,s=[],r=0;for(let i=0;i<o.length;i++){let l=o[i];if(d(l,"{"))r++;else if(d(l,"}"))r--;else if(h(l,"function")&&!d(o[i-1],".")){let a=Di(e,i,t);a&&s.push(a)}else if(["const","let","var"].includes(l.text)&&l.kind==="ident"&&h(o[i+1])){let a=Ki(e,i,r===0||n);a&&s.push(a)}else if(n&&h(l,"class")&&h(o[i+1])){let a=o.findIndex((c,u)=>u>i+1&&d(c,"{"));a>=0&&s.push({name:o[i+1].text,line:l.line,from:i,to:$(o,a)+1,params:null,kind:"class"})}else if(n&&h(l)){let a=Fi(e,i,s);a&&s.push(a)}}return s}var Ti=["public","private","protected","static","readonly","async","get","set"],Ni=["if","for","while","switch","catch","with"];function Fi(e,n,t){let{toks:o}=e,s=n;for(d(o[s-1],".")&&h(o[s-2],"this")&&(s-=2);h(o[s-1])&&Ti.includes(o[s-1].text);)s--;if(!U(o,s)&&!["{","}",",",";"].some(f=>d(o[s-1],f))||Ni.includes(o[n].text))return null;let r=n+1;if(d(o[r],"(")){let f=$(o,r)+1;if(d(o[f],":"))for(;f<o.length&&!d(o[f],"{")&&!d(o[f],";");)f++;return d(o[f],"{")?{name:o[n].text,line:o[n].line,from:n,to:$(o,f)+1,params:Ze(e,r,"js"),kind:"method"}:null}if(!N(o,r)&&!d(o[r],":"))return null;let l=zo(t,n).at(-1)?.kind==="class"?Jo(e,r,Pe(e,r+1)):N(o,r)?r:null,a=l===null?r+1:l+1,c=Pe(e,a),u=0;for(let f=a;f<c;f++){if(d(o[f],",")&&u===0){c=f;break}o[f].kind==="punct"&&("([{".includes(o[f].text)?u++:")]}".includes(o[f].text)&&u--)}return{name:o[n].text,line:o[n].line,from:n,to:c,params:null,kind:l===null?"property":"value"}}function Di(e,n,t){let{toks:o}=e,s=n+1;if(d(o[s],"*")&&s++,!h(o[s]))return null;let r=o[s];if(s++,d(o[s],"<")&&(s=Wi(e,s)),!d(o[s],"("))return null;let i=Ze(e,s,"js"),l=$(o,s)+1;t&&d(o[l],":")&&d(o[l+1],"{")&&(l=$(o,l+1)+1);for(let a=l;a<o.length&&!d(o[a],";");a++)if(d(o[a],"{"))return{name:r.text,line:o[n].line,from:n,to:$(o,a)+1,params:i};return null}function Wi(e,n){let t=0;for(let o=n;o<e.toks.length;o++)if(d(e.toks[o],"<"))t++;else if(d(e.toks[o],">")&&--t===0)return o+1;return e.toks.length}function Ki(e,n,t){let{toks:o}=e,s=Jo(e,n+2);if(s===null)return null;let r=Pe(e,s+1),i=Bi(e,s+1,r);return!i&&!t?null:{name:o[n+1].text,line:o[n].line,from:n,to:r,params:i}}function Jo(e,n,t=e.toks.length){let o=n;if(d(e.toks[o],":")){let s=o+ie;for(;o<s&&o<t&&!N(e.toks,o);)o++}return o<t&&N(e.toks,o)?o:null}function Bi(e,n,t){let{toks:o}=e,s=h(o[n],"async")?n+1:n;if(h(o[s],"function"))return s++,d(o[s],"*")&&s++,h(o[s])&&s++,d(o[s],"(")?Ze(e,s,"js"):null;let r=i=>d(o[i],"=")&&d(o[i+1],">");if(h(o[s])&&r(s+1))return[o[s].text];if(!d(o[s],"("))return null;for(let i=$(o,s)+1;i<t;i++)if(r(i))return Ze(e,s,"js");return null}function Ui(e,n,t){let{toks:o,text:s}=e,r=[];for(let i=0;i<o.length;i++){let l=o[i],a=h(l,"def")&&h(o[i+1])&&d(o[i+2],"("),c=n&&h(l,"class")&&h(o[i+1]);if(a||c){let u=Ji(e,a||d(o[i+2],"(")?$(o,i+2)+1:i+2),f=(n||t)&&h(o[i-1],"async")&&o[i-1].line===l.line?o[i-1]:l,p=ae(s,f),m=u+1;for(;m<o.length&&!(U(o,m)&&ae(s,o[m])<=p);)m++;r.push({name:o[i+1].text,line:l.line,from:i,to:m,params:a?Ze(e,i+2,"py"):null,...c?{kind:"class"}:{}})}else h(l)&&U(o,i)&&(n||ae(s,l)===0)&&zi(e,i+1)&&r.push({name:l.text,line:l.line,from:i,to:Pe(e,i+1),params:null})}return r}function zi(e,n){let{toks:t}=e;return N(t,n)||d(t[n],":")}function Ji(e,n){let t=n;for(;t<e.toks.length&&!d(e.toks[t],":");)t++;return t}function je(e,n){return e.filter(t=>t.from<n&&n<t.to).at(-1)??null}function Rt(e){let{toks:n}=e,t=[];for(let o=0;o<n.length;o++){if(!h(n[o])||!te(n,o,e))continue;let s=o;for(;d(n[s-1],".")&&h(n[s-2]);)s-=2;if(d(n[s-1],".")&&d(n[s-2],")")){let a=J(e,s-2);s=t.find(u=>u.open===a)?.from??a}let r=$(n,o+1);if(r===n.length)continue;let i=d(n[o-1],".")&&d(n[o-2],")")?o:s,l=n.slice(i,o+1).map(a=>a.text).join("");t.push({from:s,to:r+1,open:o+1,callee:l,args:W(n,o+1)})}return t}function he(e,n,t){let o=Pe(e,n,t);return d(e.toks[o-1],";")?o-1:o}function It(e){let{toks:n}=e,t=[];for(let o=0;o<n.length;o++){if(!h(n[o])||d(n[o-1],"."))continue;let s=o+1;if(d(n[s],":")){if(!(e.lang==="js"?["const","let","var"].includes(n[o-1]?.text):U(n,o)))continue;for(;s<o+ie&&s<n.length&&!N(n,s)&&![";","{","}"].some(a=>d(n[s],a));)s++}let r=d(n[s],"+");if(r&&s++,!N(n,s))continue;let i=J(e,o);e.lang==="py"&&d(n[i],"(")||(t.push({at:o,name:n[o].text,append:r,from:s+1,to:he(e,s+1)}),o=s)}return t}function $t(e,n){let{toks:t}=e,o=Rt(e),s=It(e),r=n.filter(g=>g.params!==null),i=g=>je(r,g),l=z(e),a=(g,_)=>{let O=i(_);return s.findLast(R=>R.at<_&&R.name===g&&i(R.at)===O)??(O?.params?.includes(g)?void 0:s.findLast(R=>R.at<_&&R.name===g&&i(R.at)===null))},c=[],u=[];for(let g=0;g<t.length;g++)c.push([...u]),d(t[g],"{")?u.push(g):d(t[g],"}")&&u.pop();let f=(g,_)=>c[g].every((O,R)=>c[_]?.[R]===O),p=g=>["const","let"].includes(t[g.at-1]?.text),m=g=>p(g)||h(t[g.at-1],"var"),x=new Map;for(let g of s)x.set(g,m(g)?g:s.findLast(_=>_.at<g.at&&_.name===g.name&&i(_.at)===i(g.at)&&m(_)&&(!p(_)||f(_.at,g.at))));let w=(g,_,O)=>s.some(R=>R.name===g&&i(R.at)!==_&&O(R.at)&&!x.get(R)&&!i(R.at)?.params?.includes(g)),S=(g,_)=>{let O=i(_);return!w(g,O,R=>O!==null&&O.from<R&&R<O.to)},y=g=>{let _=i(g.at);if(!_?.params?.includes(g.name))return!1;let O=t.findIndex((R,I)=>_.from<I&&I<g.at&&d(R,"("));return O>=0&&g.at<$(t,O)},b=(g,_)=>f(g.from,_)&&(i(g.from)===i(_)||i(g.from)===null),E=(g,_)=>g.at<_&&f(g.at,_)&&!w(g.name,i(g.at),O=>f(g.at,O)),k=(g,_)=>{let O=i(_),R=s.filter(j=>{if(j.name!==g||!(i(j.at)===O||!O?.params?.includes(g)&&i(j.at)===null))return!1;let X=x.get(j);return!X||!p(X)||f(X.at,_)}),I=j=>{let X=x.get(j);return X&&p(X)?c[X.at].length:0},P=Math.max(-1,...R.map(I)),F=R.filter(j=>I(j)===P);return F.findLast(j=>j.at<_)??F[0]},L=(g,_=new Set)=>t.slice(g.from,g.to).flatMap((O,R)=>{let I=a(O.text,g.from+R);return O.kind!=="ident"||!I||I.append||_.has(I.at)?[O]:L(I,new Set([..._,I.at]))}),A=g=>{let _=t[g.open-1].text;if(["readFileSync","readFile"].includes(_))return g.args[0]??null;if(!d(t[g.open-2],"."))return null;let O=g.open-3;if(_==="read_text"&&h(t[O]))return{from:g.from,to:O+1};if(!d(t[O],")"))return null;let R=J(e,O),I=o.find(P=>P.open===R);return _==="read_text"?I?.callee==="Path"?I.args[0]??null:{from:R+1,to:O}:_==="read"&&I?.callee==="open"||_==="text"&&I?.callee==="Bun.file"?I?.args[0]??null:null},C=g=>{let[_,...O]=g.callee.split(".");if(i(g.open)?.params?.includes(_)||k(_,g.open)||r.some(I=>I.name===_))return null;let R=l.filter(I=>I.names.includes(_));if(R.length>1)return null;if(R.length){let I=R[0],P=O.at(-1)??I.renamed?.[_]??_;return(/^(?:node:)?fs(?:\/promises)?$/.test(I.source)?["readFile","readFileSync","readdir","readdirSync"]:/^(?:node:)?path$/.test(I.source)?["join","resolve"]:/^(?:node:)?url$/.test(I.source)?["fileURLToPath"]:I.source==="pathlib"?["Path"]:[]).includes(P)?P:null}return O.length&&!["fs","path","Bun"].includes(_)?null:O.at(-1)??_},v=o.flatMap(g=>{let _=A(g)??(["readFileSync","readFile"].includes(C(g)??"")?g.args[0]:null);return _?[{sourcePath:e.path,line:t[g.open-1].line,call:g,path:_,tokens:L(_)}]:[]});return{source:e,calls:o,assignments:s,functions:r,owner:i,binding:k,bindingIsCertain:E,parameterIsCertain:S,parameterDefault:y,functionVisible:b,pathTokens:L,builtin:C,operations:v}}function Me({source:{toks:e}},n){let{from:t,to:o}=n;for(h(e[t],"await")&&t++;d(e[t],"(")&&$(e,t)===o-1;)t++,o--;return{from:t,to:o}}function Qe(e,n){let{from:t,to:o}=Me(e,n);return e.calls.findLast(s=>s.to===o&&(s.from===t||h(e.source.toks[t],"new")&&s.from===t+1))}function pn(e,n){let{toks:t}=e.source,{from:o}=n,s=o+1;if(d(t[o],"(")&&(s=$(t,o)+1,o++),!h(t[o])||!d(t[s],"=")||!d(t[s+1],">"))return null;let r=s+2;return d(t[r],"{")?h(t[r+1],"return")?(r+=2,{name:t[o].text,body:{from:r,to:he(e.source,r)}}):null:{name:t[o].text,body:{from:r,to:n.to}}}function ne(e,n,t=new Map,o=new Set){let{source:{toks:s,path:r},binding:i,builtin:l}=e,a=Me(e,n),{from:c,to:u}=a;if(c>=u||!s[c])return null;let f=s.slice(c,u).map(E=>E.text).join(""),p=E=>{let k=i(E,c);return!k||e.parameterDefault(k)&&t.has(E)&&t.get(E)!==void 0?e.parameterIsCertain(E,c)?t.get(E)??null:null:e.bindingIsCertain(k,c)&&!k.append&&!o.has(k.at)?ne(e,k,t,new Set([...o,k.at])):null},m=E=>ne(e,E,t,o);if(u===c+1){let E=s[c];if(e.source.lang==="py"&&E.formatted&&E.value.includes("{"))return null;if(E.kind==="string"||E.kind==="template"&&!E.value.includes("${"))return/^(?:[a-z]+:|[/\\])/i.test(E.value)?null:E.value;if(E.kind==="template"){let k=!1,L=E.value.replace(/\$\{([^}]*)\}/g,(A,C)=>{if(!/^[A-Za-z_$][\w$]*$/.test(C))return k=!0,"";let v=p(C);return v==null&&(k=!0),v??""});return k||/^(?:[a-z]+:|[/\\])/i.test(L)?null:L}if(h(E,"__dirname")&&!i(E.text,c)&&!e.owner(c)?.params?.includes(E.text))return`/repository/${et.dirname(r)}`;if(h(E))return p(E.text)}let x=[];for(let E=c;E<u;E++){if(["(","[","{"].some(k=>d(s[E],k))){E=$(s,E);continue}x.push(E)}let w=x.find(E=>d(s[E],"?")&&d(s[E+1],"?"));if(w!==void 0){let E=m({from:c,to:w});if(E!==null)return E;let k=w===c+1&&h(s[c])&&!i(s[c].text,c)?s[c].text:null;return k&&e.owner(c)?.params?.includes(k)&&e.parameterIsCertain(k,c)&&(!t.has(k)||t.get(k)===void 0)?m({from:w+2,to:u}):null}let S=x.find(E=>d(s[E],"+"));if(S!==void 0){let E=m({from:c,to:S}),k=m({from:S+1,to:u});return E===null||k===null?null:E+k}if(f==="import.meta.url")return`/repository/${r}`;let y=Qe(e,a);if(!y)return null;let b=l(y);if(b==="URL"&&y.args.length===2){let E=s.slice(y.args[1].from,y.args[1].to).map(L=>L.text).join(""),k=m(y.args[0]);return E==="import.meta.url"&&k!==null&&!/^(?:[a-z]+:|[/\\])/i.test(k)?et.join("/repository",et.dirname(r),k):null}if(b==="fileURLToPath"||b==="Path")return y.args.length===1?m(y.args[0]):null;if(b==="join"||b==="resolve"){let E=y.args.map(m);return E.length&&E.every(k=>k!==null)&&E.every(k=>k.startsWith("/repository/")||!/^(?:[a-z]+:|[/\\])/i.test(k))?b==="resolve"?et.resolve("/repository",...E):et.join(...E):null}return null}function Xo(e,n){let t=Me(e,n),o=e.source.toks[t.from],s=h(o,"null")||h(o,"undefined")&&!e.binding(o.text,t.from)&&!e.owner(t.from)?.params?.includes(o.text);return t.to===t.from+1&&s?void 0:ne(e,t)}import{posix as vt}from"node:path";function Lt(e,n){if(e===null)return null;let t=e.startsWith("/repository/")?e.slice(12):e.startsWith(".")?vt.join(vt.dirname(n),e):e,o=vt.normalize(t.replace(/\\/g,"/")).replace(/\/$/,"");return o===".."||o.startsWith("../")||/^(?:[a-z]+:|\/)/i.test(o)?null:o}function Go(e,n){return{from:n.from,to:n.open-2}}function dn(e,n,t,o=new Set){let s=Me(e,n),{source:{toks:r},binding:i}=e;if(s.to===s.from+1&&h(r[s.from])){let p=i(r[s.from].text,s.from);return p&&e.bindingIsCertain(p,s.from)&&!p.append&&!o.has(p.at)?dn(e,p,t,new Set([...o,p.at])):null}let l=Qe(e,s);if(!l)return null;if(["readdirSync","readdir"].includes(e.builtin(l)??"")&&l.args[0]){let p=Lt(ne(e,l.args[0],t),e.source.path);return p===null?null:{path:p}}if(r[l.open-1].text!=="filter"||l.args.length!==1)return null;let a=pn(e,l.args[0]),c=a&&Qe(e,a.body),u=c?.args[0]&&ne(e,c.args[0]);if(!a||c?.callee!==`${a.name}.endsWith`||!u||!fe.test(`template${u}`))return null;let f=dn(e,Go(e,l),t,o);return f?{...f,extension:u}:null}function qo(e,n,t,o){let{source:{toks:s}}=e;for(let r of e.calls){if(s[r.open-1].text!=="map"||r.args.length!==1)continue;let i=pn(e,r.args[0]);if(!i||!(i.body.from<=n.from&&n.to<=i.body.to))continue;let l=dn(e,Go(e,r),o);if(!l?.extension||e.owner(n.open)!==e.owner(r.open)||s.slice(i.body.from,n.from).some((f,p)=>{let m=i.body.from+p;return h(f,"function")||d(f,"=")&&d(s[m+1],">")}))continue;let c=new Map(o).set(i.name,"__template_entry__");if(Lt(ne(e,t,c),e.source.path)===vt.join(l.path,"__template_entry__"))return{kind:"directory",path:l.path,extension:l.extension}}return null}function Vo(e,n){let t=e.owner(n.open),o=new Set(e.assignments.filter(s=>e.owner(s.at)===t&&s.from<=n.from&&n.to<=s.to));for(let s of e.assignments)e.owner(s.at)!==t||s.from<=n.from||At(e,s,o)&&o.add(s);return o}function At(e,n,t){return e.source.toks.slice(n.from,n.to).some((o,s)=>{let r=n.from+s;if(d(e.source.toks[r-1],".")||d(e.source.toks[r+1],":"))return!1;let i=h(o)&&e.binding(o.text,r);return i&&t.has(i)})}function Ho(e,n,t,o){if(!n)return!1;let{toks:s}=e.source;for(let i=n.from;i<n.to;i++){if(!h(s[i],"return")||e.owner(i)!==n)continue;let l={from:i+1,to:he(e.source,i+1)};if(l.from<=t.from&&t.to<=l.to||At(e,l,o))return!0}let r=s.findIndex((i,l)=>n.from<l&&l<t.from&&d(i,"=")&&d(s[l+1],">"));return r>=0&&!d(s[r+2],"{")}function mn(e,n,t,o=!1){let s=(o?t.replace(fe,""):t).replace(/\\/g,"/"),r=c=>o?c.path.replace(fe,""):c.path,i=Pt.dirname(n);for(;;){let c=Pt.normalize(Pt.join(i,s)),u=e.filter(f=>r(f)===c);if(u.length)return u.length===1?u:[];if(i==="."||i==="/")break;i=Pt.dirname(i)}if(s.includes("/"))return[];let l=o?e.filter(c=>r(c)===s||r(c).endsWith(`/${s}`)):Et([...e],s),a=l.length||!o?l:e.filter(c=>Ve(r(c))===Ve(s));return a.length===1?a:[]}function Yo(e){return e.filter(({call:n})=>{let t=n.callee.split(".").at(-1);return t==="readFile"||t==="readFileSync"||["read_text","read","text"].includes(t??"")&&n.from<n.open-1})}function Ce(e){return e.filter(n=>fe.test(n))}function Zo(e,n,t){let{tokens:o}=e,s=o.filter(a=>a.kind==="string"||a.kind==="template").filter(a=>a.value.length<=200).map(a=>a.value),r=s.map(a=>{let c=Ao.exec(a);return c?a.slice(0,c.index+c[0].length).replace(/\\/g,"/"):null}).find(a=>a!==null)??null,i=Ce(s)[0]?.match(/\.[^./\\]+$/)?.[0]??null;if(r===null&&i===null)return null;let l=n.params.findIndex(a=>a!==null&&o.some((c,u)=>h(c,a)&&!d(o[u-1],".")?!0:c.kind!=="template"&&!c.formatted?!1:(c.value.match(/\$?\{[^}]*\}/g)??[]).some(f=>{let p=ft(f.replace(/^\$?\{|\}$/g,""),t);return p.some((m,x)=>h(m,a)&&!d(p[x-1],"."))})));return l<0?null:{folder:r,ext:i,paramIndex:l}}function Xi(e,n,t){let[o]=n.split("."),s=Ie(z(e.source),e.source.lang).filter(l=>l.name===o);if(s.length!==1||e.owner(e.calls.find(l=>l.callee===n)?.open??0)?.params?.includes(o))return null;let r=s[0],i=He({files:t.map(l=>({path:l.source.path}))},{path:e.source.path},r).map(l=>l.path);return{binding:r,paths:i}}function Gi(e,n){let t=e.builtin(n);if(["readFileSync","readFile"].includes(t??""))return!0;if(!["read_text","read","text"].includes(t??""))return!1;let o=t==="read_text"?"Path":t==="read"?"open":"file";return e.calls.some(s=>s.from===n.from&&s.to<n.to&&e.builtin(s)===o)}function Qo(e,n,t="anchored"){let o=Object.entries(e).flatMap(([u,f])=>{if(n?.source.path===u)return[$t(n.source,n.scopes)];let p=G(u);if(!p)return[];let m=V(u,f,p);return[$t(m,me(m))]});n&&!o.some(u=>u.source===n.source)&&o.push($t(n.source,n.scopes));let s=o.flatMap(u=>u.operations);if(t==="operations")return{operations:s,reads:[],dependencies:[]};let r=o.flatMap(u=>u.functions.map(f=>({syntax:u,scope:f}))),i=new Map,l=new Set,a=(u,f)=>{let p=f.callee.split(".")[0];if(u.owner(f.open)?.params?.includes(p))return[];let m=u.binding(p,f.open),x=r.filter(y=>y.syntax===u&&y.scope.name===f.callee&&u.functionVisible(y.scope,f.open));if(x.length)return x.filter(y=>!m||m.at===y.scope.from+1);if(m)return[];let w=Xi(u,f.callee,o);if(!w)return[];if(!w.paths.length)for(let y of an(u.source.path,w.binding.source,[w.binding.imported],u.source.lang,!0))l.add(y);let S=f.callee.split(".")[1]??w.binding.imported;return r.filter(y=>w.paths.includes(y.syntax.source.path)&&y.scope.name===S&&y.syntax.owner(y.scope.from)===null)};for(let u of o)for(let f of u.calls){let p=a(u,f);for(let m of p){let x=new Map((m.scope.params??[]).flatMap((S,y)=>S===null?[]:[[S,p.length!==1?null:f.args[y]?Xo(u,f.args[y]):void 0]])),w=i.get(m.scope)??[];w.push({parameters:x,...p.length===1&&m.syntax!==u?{consumer:u.source.path}:{}}),i.set(m.scope,w)}}let c=[];for(let u of o)for(let f of u.operations){if(!Gi(u,f.call))continue;let p=u.owner(f.call.open),m=p?i.get(p)??[{parameters:new Map}]:[{parameters:new Map}];for(let x of m){let w=Lt(ne(u,f.path,x.parameters),u.source.path),S=w===null?qo(u,f.call,f.path,x.parameters):{kind:"file",path:w};if(!S)continue;let y=Vo(u,f.call),b=new Set(x.consumer&&Ho(u,p,f.call,y)?[x.consumer]:[]);for(let L of u.calls){if(u.owner(L.open)!==p||!L.args.some(C=>At(u,C,y)))continue;let A=a(u,L);A.length===1&&A[0].syntax!==u&&b.add(A[0].syntax.source.path)}let E=c.find(L=>L.sourcePath===f.sourcePath&&L.line===f.line&&JSON.stringify(L.target)===JSON.stringify(S)),k=[...b].sort();E?E.consumerPaths=[...new Set([...E.consumerPaths,...k])].sort():c.push({sourcePath:f.sourcePath,line:f.line,target:S,consumerPaths:k})}}return{operations:s,reads:c,dependencies:[...l].sort()}}function qi(e,n,t){let o=t.model;if(o?.kind==="literal"&&Ot.test(o.text))return n.modelIds.find(p=>p.value===o.text&&p.line>=t.line)??{value:o.text,path:n.path,line:t.line};if(o?.kind!=="member")return null;let[s,r,i]=o.text.split(".");if(!r||i)return null;let l=new Map;for(let p of e.files)for(let m of p.modelMembers??[])l.set(m.object,[...l.get(m.object)??[],m]);let a=de(e,n,s,l).filter(p=>p.member===r);if(a.length!==1)return null;let{value:c,path:u,line:f}=a[0];return{value:c,path:u,line:f}}function Vi(e,n,t){if(!t.shape)return;let o=n.imports.find(r=>r.name===t.shape),s=o?He(e,n,o):[];return{name:t.shape,path:s.length===1?s[0].path:n.path,line:o?.line??t.line}}function es(e,n){let t=new Map,o=new Map;for(let i of e.files){for(let l of i.loaders??[])t.set(l.name,[...t.get(l.name)??[],l]);for(let l of i.promptReturns??[])o.set(l.fn,[...o.get(l.fn)??[],l])}let s=e.files.flatMap(i=>i.sites.filter(l=>l.kind==="file")),r=(i,l,a)=>{let c=l.kind==="loader"||l.kind==="return",u=c?de(e,i,l.callee,t):[];if(u.length)return u.flatMap(m=>l.literals.flatMap(x=>{let w=m.ext&&!x.endsWith(m.ext)?x+m.ext:x,S=m.folder?`${m.folder}/${w}`:w;return mn(s,m.path,S,!m.ext).map(b=>({site:b,sdk:e.byPath.get(m.path)?.sdk??!1}))}));let f=c&&a?de(e,i,l.callee,o):[];return f.length?f.flatMap(m=>m.loads.flatMap(x=>r(e.byPath.get(m.path),x,!1))):l.kind==="read"||l.kind==="file-key"?Ce(l.literals).flatMap(m=>mn(s,i.path,m).map(x=>({site:x,sdk:i.sdk}))):[]};for(let i of e.files){let l=new Map;for(let a of i.deliveries??[]){let c=`${a.callStart??a.line}:${a.callee}`;l.set(c,[...l.get(c)??[],a])}for(let a of l.values()){let c={...a[0],model:a.find(x=>x.model)?.model??null,shape:a.find(x=>x.shape)?.shape??null},u=a.flatMap(x=>x.loads.flatMap(w=>r(i,w,!0))),f=[...new Map(u.map(x=>[H(x.site),x.site])).values()];if(!f.length)continue;let p=f.slice(1).map(x=>x.path),m=Vi(e,i,c);Ae(n,f[0],{kind:"L4",callPath:i.path,callLine:c.line,callExcerpt:`${c.callee}(\u2026)`,...c.callStart!==void 0?{callStart:c.callStart}:{},wrapper:null,shortLabel:null,sdk:i.sdk||u.some(x=>x.sdk),modelId:qi(e,i,c),...p.length?{alsoLoads:p}:{},...m?{shape:m}:{}})}}}var Hi=30;function ns(e,n,t,o){let s=e.files.filter(i=>i.path!==n.path).flatMap(i=>i.sites.filter(l=>l.symbol===t)),r=s.filter(i=>o.some(l=>_t(i.path,l)));return r.length>0?r:s}function os(e,n,t){let o=n.sites.filter(r=>r.symbol===t);if(o.length>0)return o;let s=n.imports.find(r=>r.name===t);return s?ns(e,n,s.imported,[s.source]):[]}function Yi(e,n,t,o){return ns(e,n,o,[t.source,`${t.source}.${t.imported}`])}function Zi(e,n,t){let o=(e.wrappers.get(t)??[]).filter(l=>l.path===n.path);if(o.length>0)return o;let s=n.imports.find(l=>l.name===t);if(!s)return[];let r=e.wrappers.get(s.imported)??[],i=r.filter(l=>_t(l.path,s.source));return i.length>0?i:r}function ts(e,n){let t=(e?.modelIds??[]).filter(o=>Math.abs(o.line-n)<=Hi);return t.sort((o,s)=>Math.abs(o.line-n)-Math.abs(s.line-n)||o.line-s.line),t[0]??null}function hn(e,n,t,o){let s=ts(e.byPath.get(n),t);return s||!o?s:ts(e.byPath.get(o.path),o.line)}function Qi(e,n,t,o){if(t.kind!=="system-arg"||!t.value)return!1;let s=ss(e,n,t.value);for(let r of s)Ae(o,r,{kind:"L1",callPath:n.path,callLine:t.line,callExcerpt:`system prompt ${t.value.text}`,wrapper:null,shortLabel:t.shortLabel??null,sdk:n.sdk,modelId:hn(e,n.path,t.line,null)});return s.length>0}function el(e,n){return e.args.find(t=>t.name===n.paramName)??e.args.filter(t=>t.name===null)[n.paramIndex]}function ss(e,n,t){return t.kind==="literal"&&t.siteStart!==null?n.sites.filter(o=>o.start===t.siteStart):t.kind==="identifier"?os(e,n,t.text):t.kind==="member"?tl(e,n,t.text):[]}function tl(e,n,t){let o=/^(\w+)\.(\w+)$/.exec(t);if(!o)return[];let s=n.imports.find(r=>r.name===o[1]);return s?Yi(e,n,s,o[2]):/^(?:self|cls|this|[A-Z]\w*)$/.test(o[1])?os(e,n,o[2]):[]}function nl(e,n,t){for(let o of n.wrapperCalls)for(let s of Zi(e,n,o.name)){let r=el(o,s);if(r)for(let i of ss(e,n,r))Ae(t,i,{kind:"L2",callPath:n.path,callLine:o.line,callExcerpt:`${o.name}(\u2026)`,wrapper:s,shortLabel:o.shortLiterals.length===1?o.shortLiterals[0]:null,sdk:n.sdk||(e.byPath.get(s.path)?.sdk??!1),modelId:hn(e,n.path,o.line,s)})}}function ol(e,n){let t=e.files.flatMap(o=>o.sites.filter(s=>s.kind==="file"));if(t.length!==0){for(let o of e.files)if(!(!o.sdk&&!o.callSites.some(s=>s.kind==="system-arg")))for(let s of o.fileRefs)for(let r of Et(t,s.value))Ae(n,r,{kind:"L3",callPath:o.path,callLine:s.line,callExcerpt:s.value,wrapper:null,shortLabel:null,sdk:o.sdk,modelId:hn(e,o.path,s.line,null)})}}function rs(e){let n=new Map;for(let i of e.flatMap(l=>l.wrappers))n.set(i.name,[...n.get(i.name)??[],i]);let t={byPath:new Map(e.map(i=>[i.path,i])),files:e,wrappers:n},o=new Map,s=[];for(let i of e){for(let l of i.callSites)l.kind!=="system-arg"||Qi(t,i,l,o)||l.value&&l.value.kind!=="literal"&&s.push({path:i.path,line:l.line});nl(t,i,o)}ol(t,o),es(t,o);let r=new Set([...o.values()].flat().filter(i=>i.kind==="L4").map(i=>`${i.callPath}:${i.callLine}`));return{links:o,callsWithoutPrompt:s.filter(i=>!r.has(`${i.path}:${i.line}`))}}var tt={named:3,prose:2,file:3,link:4,sdk:1},sl=6,rl=3,is={L1:0,L2:1,L4:1.5,L3:2};function nt(e,n){return e<n?-1:e>n?1:0}function il(e){return[...e].sort((t,o)=>is[t.kind]-is[o.kind]||Number(o.sdk)-Number(t.sdk)||nt(t.callPath,o.callPath)||t.callLine-o.callLine)[0]??null}function ll(e){return(e.named?tt.named:0)+(e.prose?tt.prose:0)+(e.kind==="file"?tt.file:0)}function ls(e,n,t){let o=il(n),s=t||n.some(i=>i.sdk),r=ll(e)+(o?tt.link:0)+(s?tt.sdk:0);return r<rl?null:{tier:r>=sl?"strong":"possible",score:r,prompt:e,link:o&&{kind:o.kind,callPath:o.callPath,callLine:o.callLine,callExcerpt:o.callExcerpt,...o.callStart!==void 0?{callStart:o.callStart}:{},wrapper:o.wrapper,shortLabel:o.shortLabel},sdk:s,modelId:o?.modelId??null,...o?.alsoLoads?.length?{alsoLoads:o.alsoLoads}:{},...o?.shape?{shape:o.shape}:{}}}function as(e,n){return n.score-e.score||nt(e.prompt.path,n.prompt.path)||e.prompt.line-n.prompt.line}function us(e,n){let t={files:e},o=new Map(e.map(a=>[a.path,a])),s=n.flatMap(a=>{let c=a.link;if(c?.kind!=="L4")return[];let u=o.get(c.callPath),f=u?.deliveries?.find(m=>m.line===c.callLine&&`${m.callee}(\u2026)`===c.callExcerpt&&(c.callStart===void 0||m.callStart===c.callStart));if(!f)return[];let p=u?.stepCalls?.find(m=>m.callStart===f.callStart&&m.line===f.line);return[{path:c.callPath,candidate:a,delivery:f,enclosingStart:p?.enclosingStart}]}),r=new Map;for(let a of s){let c=a.delivery.enclosing;c&&r.set(c,[...r.get(c)??[],a])}let i=new Map,l=(a,c,u)=>{let f=H(a.candidate.prompt),p=H(c.candidate.prompt);if(f===p)return;let m=i.get(f)??[];m.some(x=>x.to===p&&x.kind===u)||m.push({to:p,kind:u}),i.set(f,m)};for(let a of e){let c=s.filter(p=>p.path===a.path),u=[...a.stepCalls??[]];for(let{delivery:p}of c)u.some(m=>cs(m,p))||u.push({callee:p.callee,line:p.line,callStart:p.callStart,enclosing:p.enclosing,resultVar:p.resultVar,argNames:[]});u.sort((p,m)=>p.line-m.line||(p.callStart??0)-(m.callStart??0));let f=new Map;for(let p of u){let m=p.localTarget===null?[]:de(t,a,p.callee,r).filter(y=>p.localTarget===void 0||y.enclosingStart===p.localTarget),x=c.filter(y=>y.delivery.enclosing!==null&&y.delivery.enclosing===p.enclosing&&(y.enclosingStart===void 0||p.enclosingStart===void 0||y.enclosingStart===p.enclosingStart));for(let y of x)for(let b of m)l(y,b,"calls");let w=`${p.enclosing??""}:${p.enclosingStart??""}`,S=f.get(w)??new Map;for(let y of p.argNames){let b=S.get(y);if(!(!b||p.argCalls&&Object.hasOwn(p.argCalls,y)&&p.argCalls[y]!==b.callStart))for(let E of b.steps)for(let k of m)l(E,k,"feeds")}p.resultVar&&S.set(p.resultVar,{steps:[...m,...c.filter(y=>cs(p,y.delivery))],callStart:p.callStart}),f.set(w,S)}}return i}function cs(e,n){return e.line===n.line&&e.callee===n.callee&&(n.callStart===void 0||e.callStart===n.callStart)}function fs(e){let{links:n,callsWithoutPrompt:t}=rs(e),o=new Set([...n.values()].flatMap(l=>l.flatMap(a=>a.alsoLoads??[]))),s=[];for(let l of e)for(let a of l.sites){if(o.has(a.path)&&!(n.get(H(a))??[]).some(u=>u.kind!=="L3"))continue;let c=ls(a,n.get(H(a))??[],l.sdk);c&&s.push(c)}s.sort(as);let r=us(e,s);for(let l of s){let a=r.get(H(l.prompt));a?.length&&(l.links=a)}let i=e.flatMap(l=>l.modelIds).sort((l,a)=>nt(l.path,a.path)||l.line-a.line);return{strong:s.filter(l=>l.tier==="strong"),possible:s.filter(l=>l.tier==="possible"),callsWithoutPrompt:t.sort((l,a)=>nt(l.path,a.path)||l.line-a.line),repoModelIds:i,scanned:e.length}}function ot(e,n){let{toks:t}=e;if(d(t[n],"(")){let o=gn(e,n+1);return o&&d(t[o.next],")")?{...o,next:o.next+1}:null}return d(t[n],"[")?cl(e,n):gn(e,n)}function gn(e,n){let{toks:t}=e,o=[],s=n;for(;B(t[s]);)o.push(t[s]),s++,d(t[s],"+")&&B(t[s+1])&&s++;return o.length===0?null:{start:o[0].start,line:o[0].line,endLine:o[o.length-1].endLine,text:o.map(r=>r.value).join(""),partStarts:o.map(r=>r.start),next:s,...o.some(xn)?{filledAtRunTime:!0}:{}}}function xn(e){return!!e.formatted&&(e.kind==="template"||al(e.value))}function al(e){for(let n=0;n<e.length;n++)if(e[n]==="{"){if(e[n+1]==="{"){n++;continue}return e.indexOf("}",n+1)>=0}return!1}function st(e,n,t=e.toks.length){let{toks:o}=e;if(e.lang==="py")for(;n<t&&d(o[n],"(");)n++;if(e.lang==="py"&&h(o[n],"lambda")){for(let s=n+1;s<t;s++){if(d(o[s],":"))return s+1;["(","[","{"].some(r=>d(o[s],r))&&(s=$(o,s))}return null}if(e.lang!=="js")return null;for(;n<t;){let s=h(o[n],"async")?n+1:n,r=d(o[s],"(")?$(o,s):-1,i=r>=0?r+1:h(o[s])?s+1:-1;if(d(o[i],":")){let l=Math.min(t,i+ie);for(;i<l&&!d(o[i],"=");)i++}if(i>=0&&i+2<t&&d(o[i],"=")&&d(o[i+1],">"))return i+2;if(r<0)return null;n=s+1,t=Math.min(t,r)}return null}function cl(e,n){let{toks:t}=e,o=n+1;if(!d(t[o],"{"))return null;let s=$(t,o),r=d(t[s+1],",")?s+2:s+1;if(!d(t[r],"]"))return null;for(let i=o+1;i<s;i++){let l=t[i];if((h(l)&&l.text==="text"||l.kind==="string"&&l.value==="text")&&d(t[i+1],":")){let c=gn(e,i+2);return c&&{...c,next:r+1}}}return null}var yn={kind:"other",text:"",siteLine:null,siteStart:null};function oe(e,n,t,o=e.toks.length,s=!1){let{toks:r}=e,i=s?st(e,t,o):null,l=ot(e,i??t);if(i!==null&&(!l||!n.has(l.start)))return yn;if(l&&l.next<=o){let u=n.get(l.start)??null;return{kind:"literal",text:Re(l.text),siteLine:u,siteStart:u===null?null:l.start}}if(!h(r[t]))return yn;let a=t+1,c=!1;for(;;){let u=d(r[a],"?")&&d(r[a+1],".")?a+1:a;if(!d(r[u],".")||!h(r[u+1]))break;a=u+2,c=!0}return a<o&&!ul(r[a],U(r,a))?yn:{kind:c?"member":"identifier",text:e.text.slice(r[t].start,r[a-1].end),siteLine:null,siteStart:null}}function ul(e,n){return n||e.kind==="punct"&&",)}];".includes(e.text)}var ps=new Set(["system","systemPrompt","system_prompt","instructions"]);function Sn(e,n){let t=ge(e.toks[n-2]);if(t===null||!ps.has(t)||ds(e,n-2)!==n)return!1;let o=J(e,n-2);if(e.lang==="py"&&e.toks[n-2].kind==="ident")return te(e.toks,o-1,e)&&!d(e.toks[n-3],".");if(!d(e.toks[o],"{"))return!1;let s=J(e,o);if(!te(e.toks,s-1,e))return!1;let r=o-1;return e.lang==="py"&&(d(e.toks[r],"*")&&d(e.toks[r-1],"*")||d(e.toks[r],"=")&&h(e.toks[r-1]))&&(r-=2),r===s||d(e.toks[r],",")}function Te(e,n,t,o=!1,s=!1){let r=[];return e.toks.forEach((i,l)=>{let a=ds(e,l);if(a===null)return;let c=fl(e,t,a,s&&Sn(e,a)),u=o?pl(e,l):null;r.push({valueAt:a,site:{kind:"system-arg",path:e.path,line:i.line,value:c,enclosing:Y(n,l),...u?{shortLabel:u}:{}}})}),r}function fl(e,n,t,o){let{toks:s}=e,r=oe(e,n,t,s.length,o);if(r.kind!=="other")return r;if(d(s[t],"[")){let l=$(s,t);for(let a=t+1;a<l;a++)if(ge(s[a])==="text"&&d(s[a+1],":"))return oe(e,n,a+2)}let i=d(s[t+1],"?")&&d(s[t+2],"?")||d(s[t+1],"|")&&d(s[t+2],"|");return h(s[t])&&i?oe(e,n,t,t+1):r}var ge=e=>e?.kind==="string"?e.value:e?.kind==="ident"?e.text:null;function pl(e,n){let{toks:t}=e,o=0;for(let s=n-1;s>=0;s--){let r=t[s];if(r.kind==="punct"){if(")]}".includes(r.text))o++;else if("([{".includes(r.text)){if(o>0){o--;continue}let i=e.lang==="js"&&d(r,"{")?s-1:s;return!d(t[i],"(")||!dl(e,i-1)||e.lang==="js"&&i===s?null:ml(e,s)}}}return null}function dl(e,n){let{toks:t}=e;if(e.lang==="js"&&d(t[n],">")){let o=0;do d(t[n],">")&&!d(t[n-1],"=")?o++:d(t[n],"<")&&o--,n--;while(n>=0&&o>0)}return h(t[n],"Agent")}function ml(e,n){let{toks:t}=e;for(let{from:o,to:s}of W(t,n).reverse()){let r=t[o],i=(h(r,"get")||h(r,"set"))&&(ge(t[o+1])==="name"||d(t[o+1],"["));if(d(r,".")||d(r,"[")||d(r,"*")||i)return null;if(ge(r)!=="name")continue;let l=e.lang==="py"?N(t,o+1):d(t[o+1],":"),a=t[o+2];if(!l||s!==o+3||a?.kind!=="string")return null;let{prefix:c,closed:u}=pt(a);return u&&!/[fb]/i.test(c)&&a.value.trim()||null}return null}function ds(e,n){let{toks:t}=e,o=t[n],s=ge(o),r=l=>N(t,l),i=l=>d(t[l],":")||e.lang==="py"&&r(l);return s!==null&&ps.has(s)?(e.lang==="py"&&o.kind==="ident"?r(n+1):i(n+1))?e.lang==="js"&&gl(e,n)?null:n+2:e.lang==="js"&&o.kind==="ident"&&(d(t[n-1],"{")||d(t[n-1],","))&&(d(t[n+1],",")||d(t[n+1],"}"))&&!un(e,n)?n:null:s==="role"&&i(n+1)&&t[n+2]?.kind==="string"&&t[n+2].value==="system"?hl(e,n+3):(d(o,"(")||d(o,"["))&&t[n+1]?.kind==="string"&&t[n+1].value==="system"&&d(t[n+2],",")?n+3:h(o,"SystemMessage")&&d(t[n+1],"(")?ge(t[n+2])==="content"&&i(n+3)?n+4:n+2:null}function hl(e,n){let{toks:t}=e;if(!d(t[n],",")||ge(t[n+1])!=="content")return null;let o=t[n+2];return d(o,":")||d(o,"=")?n+3:null}function gl(e,n){let t=e.toks[n+2];return h(t)&&Bo(t.text)||un(e,n)}var ms=200,hs=300,kn=/SYSTEM|PROMPT|INSTRUCTION/i,xl=/^\s*You(?:['’]re)?(?![\w'’])/;function gs(e,n,t={}){let o=t.minChars!==void 0,s=t.promptFunctions!==!1,r=[],i=new Map,l=new Set,a=(c,u)=>{l.has(c)||(l.add(c),r.push(u),i.set(c,u.span.from))};for(let c=0;c<e.toks.length;c++){let u=yl(e,c,o||s);if(!u)continue;let f=s?st(e,u.valueAt):null,p=ot(e,f??u.valueAt);!p||p.text.length<(t.minChars??ms)||!o&&!kn.test(e.toks[u.nameAt].text)&&!(f!==null&&jt(p.text,!!p.filledAtRunTime))||(a(p.start,wn(e,p,{named:!0,prose:jt(p.text,s&&!!p.filledAtRunTime),line:e.toks[u.nameAt].line,symbol:e.toks[u.nameAt].text,enclosing:Y(n,u.declAt)},s&&!!p.filledAtRunTime)),p.partStarts.forEach(m=>l.add(m)))}return s&&e.toks.forEach((c,u)=>{let f=h(c,"return")?n.filter(y=>y.params!==null&&y.from<u&&u<y.to).sort((y,b)=>b.from-y.from)[0]:void 0,p=Sn(e,u);if(!f&&!p)return;let m=f?u+1:u,x=p?st(e,m):null,w=ot(e,x??m);if(!w||w.text.length<(t.minChars??ms))return;let S=jt(w.text,!!w.filledAtRunTime);f&&!o&&!kn.test(f.name)&&!S||(a(w.start,wn(e,w,{named:!!f||!S,prose:S,line:f?.line??w.line,symbol:f?.name??null,enclosing:f?.name??Y(n,u)},!!w.filledAtRunTime)),w.partStarts.forEach(y=>l.add(y)))}),e.toks.forEach((c,u)=>{if(!B(c)||l.has(c.start)||c.value.length<(t.minChars??hs))return;let f=s&&xn(c),p=jt(c.value,f);if(!o&&!p)return;let m={start:c.start,line:c.line,endLine:c.endLine,text:c.value,partStarts:[c.start],next:u+1};a(c.start,wn(e,m,{named:!1,prose:p,line:c.line,symbol:null,enclosing:Y(n,u)},f))}),r.sort((c,u)=>c.line-u.line),{sites:r,siteLineByStart:i}}function jt(e,n=!1){let t=n?e.replace(/^(?:\s*\$?\{[^{}]*\})+\s*/,""):e;return e.length>=hs&&xl.test(t)}function wn(e,n,t,o=!1){return{kind:t.named?"named":"prose",...t,path:e.path,endLine:n.endLine,span:{from:n.line,to:n.endLine},start:n.start,chars:n.text.length,excerpt:Re(n.text),...o?{filledAtRunTime:!0}:{}}}function yl(e,n,t){let{toks:o}=e,s=e.lang==="js";if(s&&!(h(o[n])&&["const","let","var"].includes(o[n].text)))return null;let r=s?n+1:n;if(!h(o[r])||!t&&!kn.test(o[r].text)||!s&&!(U(o,n)&&Sl(e,n)))return null;let i=r+1;if(d(o[i],":")){let l=i+ie;for(;i<l&&i<o.length&&!N(o,i);)i++}return N(o,i)?{declAt:n,nameAt:r,valueAt:i+1}:null}function Sl(e,n){let t=ae(e.text,e.toks[n]);if(t===0)return!0;for(let o=n-1;o>=0;o--)if(!(!U(e.toks,o)||ae(e.text,e.toks[o])>=t))return h(e.toks[o],"class");return!1}var wl=20,kl=/^(?:messages\.(?:create|stream)|chat\.completions\.create|responses\.create|generateText|streamText|Runner\.run)\(/,_l=/\/v1\/(?:messages|chat\/completions)$/;function Mt(e,n,t,o={}){let{toks:s}=e,r=t.filter(a=>So(a.source,e.lang,o,e)),i=r.length>0,l=r.map(a=>({line:a.line,at:null}));return s.forEach((a,c)=>{if(B(a)){_l.test(a.value)&&l.push({line:a.line,at:c});return}if(!h(a))return;let u=s.slice(c,c+7).map(x=>x.text).join(""),f=re.includes(s[c-1]?.text??""),p=i&&a.text==="query"&&s[c+1]?.text==="("&&s[c-1]?.text!==".";(kl.test(u)&&(a.text!=="Runner"||o.layouts===!0&&i)&&!f||p&&!f)&&l.push({line:a.line,at:c})}),l.sort((a,c)=>a.line-c.line),l.slice(0,wl).map(({line:a,at:c})=>({kind:"sdk",path:e.path,line:a,value:null,enclosing:c===null?null:Y(n,c)}))}function Ct(e,n,t){let o=[];for(let s of n){let{params:r}=s;if(r)for(let{site:i,valueAt:l}of t){if(i.value?.kind!=="identifier"||l<=s.from||l>=s.to)continue;let a=r.indexOf(i.value.text),c=o.some(u=>u.name===s.name&&u.paramIndex===a);a>=0&&!c&&o.push({name:s.name,paramIndex:a,paramName:i.value.text,path:e.path,line:s.line})}}return o}var El=200,bl=40;function xs(e,n,t,o){let{toks:s}=e,r=[];for(let i=0;i<s.length&&r.length<El;i++){let l=s[i];if(!te(s,i)||d(s[i-1],".")||re.includes(s[i-1]?.text??""))continue;let a=W(s,i+1).map(u=>Ol(e,t,u));a.some(u=>u.kind==="literal"&&u.siteLine!==null||u.kind==="identifier"&&o.has(u.text))&&r.push({name:l.text,path:e.path,line:l.line,args:a,shortLiterals:a.filter(u=>u.kind==="literal"&&u.siteLine===null&&u.text.length>0&&u.text.length<=bl).map(u=>u.text),enclosing:Y(n,i)})}return r}function Ol(e,n,t){let{toks:o}=e,s=e.lang==="py"&&h(o[t.from])&&N(o,t.from+1),r=s?t.from+2:t.from;return{...oe(e,n,r,t.to),name:s?o[t.from].text:null}}var ys=50;function Ss(e,n,t,o,s,r){let{toks:i}=e,l=new Set(n.map(f=>f.name)),a=f=>je(n,f),c=new Map(t.map(f=>[f.from,f])),u=new Set(r.map(f=>f.callStart));return t.filter(f=>l.has(f.callee)||s.has(f.callee.split(".")[0])||u.has(i[f.from].start)).slice(0,ys).map(f=>{let p=a(f.from),m=[...new Set(f.args.flatMap(v=>{let{from:g,to:_}=v;for(e.lang==="py"&&h(i[g])&&N(i,g+1)&&(g+=2);d(i[g],"(")&&$(i,g)===_-1;)g++,_--;if(!h(i[g]))return[];for(let O=g+1;O<_;O+=2)if(!d(i[O],".")||!h(i[O+1]))return[];return[i[g].text]}))].slice(0,ys),x=v=>o.findLast(g=>g.name===v&&g.at<f.from&&a(g.at)===p&&!(g.from<=f.from&&f.from<g.to)),w=v=>{let g=h(i[v.from],"await")?v.from+1:v.from,_=c.get(g);return!v.append&&_?.to===v.to?_:null},S=Object.fromEntries(m.flatMap(v=>{let g=x(v);if(!g)return[];let _=w(g);return[[v,_?i[_.from].start:null]]})),y=o.find(v=>w(v)===f),b=n.filter(v=>v.from<f.from&&f.from<v.to),E=n.filter(v=>v.name===f.callee&&(!a(v.from)||b.includes(a(v.from)))).sort((v,g)=>(a(g.from)?.from??-1)-(a(v.from)?.from??-1))[0],k=f.callee.split(".")[0],L=b.findLast(v=>v.params?.includes(k)||o.some(g=>g.name===k&&g.at<f.from&&a(g.at)===v)),A=L&&(!E||(a(E.from)?.from??-1)<L.from),C=A?null:E?i[E.from].start:null;return{callee:f.callee,resultVar:y?.name??null,argNames:m,enclosing:p?.name??null,line:i[f.from].line,callStart:i[f.from].start,...p?{enclosingStart:i[p.from].start}:{},...E||A||l.has(f.callee)?{localTarget:C}:{},...Object.keys(S).length?{argCalls:S}:{}}})}var xe=50,Rl=200,ws=new Set(["system","systemPrompt","system_prompt","instructions","prompt","template","template_file"]),Il=new Set(["model","engine","schema","response_format","output_type","outputSchema","tools","messages","max_tokens","maxTokens"]),$l=new Set(["schema","response_format","output_type","outputSchema"]),ks=/(?:template|template_file|prompt_file)$/;function _s(e,n){let{toks:t}=e,o=n.filter(g=>g.params!==null),s=g=>je(o,g),r=Rt(e),i=new Map(r.map(g=>[g.from,g])),l=z(e),a=new Set(Ie(l,e.lang).map(g=>g.name)),c=Mt(e,n,l).length>0,u=Ct(e,n,Te(e,n,new Map)),f=new Map(r.flatMap(g=>{let _=vl(e,g),O=u.find(I=>I.name===g.callee),R=_.filter(I=>c||O||_.some(P=>P.object===I.object&&Il.has(P.key)));return c||O||R.length?[[g,{fields:R,wrapper:O}]]:[]})),p=It(e),m=new Map(p.map(g=>[g.at,g])),x=new Map(p.filter(g=>!g.append).map(g=>[h(t[g.from],"await")?g.from+1:g.from,g.name])),w=Qo({[e.path]:e.text},{source:e,scopes:n},"operations"),S=Yo(w.operations),y=new Map(S.map(g=>[g.call.from,g.path])),b=[];for(let g of o){for(let _ of S){if(s(_.call.from)!==g)continue;let O=Zo(_,g,e.lang);if(!(!O||b.some(R=>R.name===g.name&&R.line===g.line))&&(b.push({name:g.name,paramIndex:O.paramIndex,folder:O.folder,ext:O.ext,path:e.path,line:g.line}),b.length===xe))break}if(b.length===xe)break}let E=new Set(b.map(g=>g.name)),k=new Map,L=g=>[...new Map(g.map(_=>[JSON.stringify(_),_])).values()].slice(0,xe),A=g=>t.slice(g.from,g.to).filter(B).filter(_=>_.value.length<=Rl).map(_=>_.value).slice(0,xe),C=[];for(let g=0;g<2;g++){let _=new Map;C=[];let O=(R,I)=>{let{from:P,to:F}=R;for(h(t[P],"await")&&P++;d(t[P],"(")&&$(t,P)===F-1;)P++,F--;if(F===P+1&&h(t[P]))return _.get(I)?.get(t[P].text)??[];let j=i.get(P);if(j&&j.to===F){let X=y.get(P);if(X){let K=A(X);return Ce(K).length>0?[{kind:"read",callee:j.callee,literals:K}]:[]}if(f.get(j)?.fields.some(K=>ws.has(K.key)||K.key==="messages"))return[];let we=j.args[0]?A(j.args[0]):[],ke=a.has(j.callee.split(".")[0]),T=[...k.keys()].some(K=>K.name===j.callee);if(T||(E.has(j.callee)||ke)&&(we.length>0||ke&&j.args.length===0))return[{kind:T?"return":"loader",callee:j.callee,literals:we}]}return[]};for(let R=0;R<t.length;R++){let I=s(R),P=m.get(R);if(P){let{name:T,append:K}=P,se=_.get(I)??new Map;se.set(T,L([...K?se.get(T)??[]:[],...O(P,I)])),_.set(I,se)}if(h(t[R],"return")&&I&&!b.some(T=>T.name===I.name&&T.line===I.line)){let T=O({from:R+1,to:he(e,R+1)},I);T.length&&(k.has(I)||k.size<xe)&&k.set(I,{fn:I.name,loads:L([...k.get(I)?.loads??[],...T]),path:e.path,line:I.line})}let F=i.get(R);if(!F||C.length===xe)continue;let j=f.get(F);if(!j)continue;let{fields:X,wrapper:we}=j,ke=(T,K,se=!1)=>{let Z=O(T,I);if(!Z.length&&se){let Q=A(T);Ce(Q).length>0&&(Z=[{kind:"file-key",callee:F.callee,literals:Q}])}if(!Z.length||C.length===xe)return;let _e=X.filter(Q=>T.object===void 0||Q.object===T.object),le=_e.find(Q=>Q.key==="model"||Q.key==="engine"),Bt=_e.find(Q=>$l.has(Q.key)),wr=le?oe(e,new Map,le.from,le.to):null,Zn=Bt?oe(e,new Map,Bt.from,Bt.to):null,kr=Zn?.kind==="identifier"?Zn.text:null,_r=x.get(F.from)??null;C.push({path:e.path,line:t[F.from].line,callStart:t[F.from].start,callee:F.callee,key:K,loads:Z,model:wr,shape:kr,enclosing:I?.name??null,resultVar:_r})};for(let T of X)if((ws.has(T.key)||ks.test(T.key))&&ke(T,T.key,e.lang==="py"&&ks.test(T.key)),T.key==="messages")for(let K=T.from;K<T.to;K++){if(!d(t[K],"{"))continue;let se=_n(e,K),Z=se.find(le=>le.key==="role");if(!Z||t[Z.from]?.kind!=="string"||!["system","user"].includes(t[Z.from].value))continue;let _e=se.find(le=>le.key==="content");_e&&Z.from<_e.from&&ke({..._e,object:T.object},"content"),K=$(t,K)}we&&F.args[we.paramIndex]&&!X.length&&ke(F.args[we.paramIndex],null)}}let v=Ss(e,o,r,p,a,C);return{loaders:b,promptReturns:[...k.values()],deliveries:C,stepCalls:v}}function _n(e,n){let{toks:t}=e;return W(t,n).flatMap(({from:o,to:s})=>{let r=h(t[o])?t[o].text:t[o]?.kind==="string"?t[o].value:null;return r?d(t[o+1],":")||e.lang==="py"&&N(t,o+1)?[{key:r,from:o+2,to:s,object:n}]:s===o+1?[{key:r,from:o,to:s,object:n}]:[]:[]})}function vl(e,n){return e.lang==="py"?_n(e,n.open):n.args.flatMap(t=>d(e.toks[t.from],"{")?_n(e,t.from):[])}function Es(e){return{path:e,sites:[],callSites:[],sdk:!1,sdkLine:null,wrappers:[],wrapperCalls:[],imports:[],modelIds:[],fileRefs:[]}}function bs(e,n,t={}){try{return Ll(e,n,t)}catch{return Es(e)}}function Ll(e,n,t){let o=G(e);if(!o){let w=Po(e,n);return{...Es(e),sites:w?[w]:[]}}let s=V(e,n,o),r=me(s,{promptFunctions:t.promptFunctions!==!1}),i=z(s),l=Ie(i,o),{sites:a,siteLineByStart:c}=gs(s,r,t),u=Mt(s,r,i,t.sdk),f=Te(s,r,c,t.sdk?.layouts===!0&&u.length>0,t.promptFunctions!==!1),p=new Set([...a.flatMap(w=>w.symbol?[w.symbol]:[]),...l.map(w=>w.name)]),m=t.promptLoaders!==!1?_s(s,r):null,x=t.promptLoaders!==!1?Wo(s):[];return{path:e,sites:a,callSites:[...f.map(w=>w.site),...u].sort((w,S)=>w.line-S.line),sdk:u.length>0,sdkLine:u.length>0?u[0].line:null,wrappers:Ct(s,r,f),wrapperCalls:xs(s,r,c,p),imports:l,...Do(s),...m?.loaders.length?{loaders:m.loaders}:{},...m?.promptReturns.length?{promptReturns:m.promptReturns}:{},...m?.deliveries.length?{deliveries:m.deliveries}:{},...m?.stepCalls.length?{stepCalls:m.stepCalls}:{},...x.length?{modelMembers:x}:{}}}var Os=e=>e.CF_CODE_PROMPT_FUNCTIONS!=="0";var Al=40,Pl=new Set(["const","let","var","function","class","default","async","interface","enum"]);function jl(e,n){let{toks:t}=e,o=[];for(let s=0;s<t.length;s++){if(!h(t[s],"export"))continue;let r=0,i=n?t.length:Math.min(t.length,s+Al);for(let l=s+1;l<i&&(d(t[l],"{")&&r++,d(t[l],"}")&&r--,!(d(t[l],";")||(!n||r===0)&&h(t[l])&&Pl.has(t[l].text)));l++)if((!n||r===0)&&h(t[l],"from")&&B(t[l+1])){o.push(t[l+1].value);break}}return o}function Rs(e,n,t,o=!1){let s=V(e,n,t),r=z(s);return t==="js"?[...r,...jl(s,o).map(i=>({source:i,names:[]}))]:r}var Ml=20;function Tt(e,n){let t=new Set(n),o=new Set;for(let[s,r]of Object.entries(e)){let i=G(s);if(i)for(let l of Rs(s,r,i)){let a=Ye(s,l.source,l.names,i,t);a!==void 0&&o.add(a)}}return[...o].sort()}function lp(e,n,t){return Tt(e,n).filter(o=>!oo(o,t)).slice(0,Ml)}function Cl(e,n){let t=We(e),o=t?t.split("/"):[],s=n.split("/").slice(0,-1),r=0;for(;r<o.length&&r<s.length&&o[r]===s[r];)r++;return o.slice(0,r).join("/")}function ap(e,n,t){let o=Os(t),s=fs(Object.entries(n).map(([l,a])=>bs(l,a,{promptFunctions:o}))),r=s.strong[0]??s.possible[0];if(!r)return null;let i=r.prompt.path;return{suggestedDir:Cl(e,i),file:i,symbol:r.prompt.symbol}}function cp(e,n){let t=n.suggestedDir||"the repository root";return`no agent prompt in ${e}; its code imports ${n.file}, which defines ${n.symbol??"a prompt"} \u2014 import ${t} to include it`}function En(e,n){if(!n||!d(e[n.from],"{")||$(e,n.from)!==n.to-1)return null;let t=new Map;for(let o of W(e,n.from)){let s=e[o.from];if(!(h(s)||s?.kind==="string")||!d(e[o.from+1],":"))return null;let r=s.kind==="string"?s.value:s.text;if(t.has(r))return null;t.set(r,{from:o.from+2,to:o.to})}return t}function ye(e,n,t=0){if(!n||t>32)return;let{from:o,to:s}=n,r=e[o];if(r?.kind==="string"&&pt(r).closed){if(s===o+1)return r.value;if(d(e[o+1],"+")){let a=ye(e,{from:o+2,to:s},t+1);if(typeof a=="string")return r.value+a}}if(s===o+1){if(r?.kind==="number"){let a=Number(r.text.replace(/_/g,""));return Number.isFinite(a)?a:void 0}if(h(r,"true"))return!0;if(h(r,"false"))return!1;if(h(r,"null"))return null}if(d(r,"[")&&$(e,o)===s-1){let a=W(e,o).map(c=>ye(e,c,t+1));return a.includes(void 0)?void 0:a}let i=En(e,n);if(!i)return;let l=[...i].map(([a,c])=>[a,ye(e,c,t+1)]);return l.some(([,a])=>a===void 0)?void 0:Object.fromEntries(l)}function Is(e,n){let t=En(e,n);if(!t)return null;let o=ye(e,t.get("type"));if(o==="function"&&t.has("function")&&(t=En(e,t.get("function"))),!t)return null;let s=t.get("input_schema")??(o==="function"?t.get("parameters"):void 0);if(!s)return null;let r=ye(e,t.get("name")),i=ye(e,t.get("description"));if(typeof r!="string"||!r.trim()||typeof i!="string")return{tools:[],warnings:["Some tools couldn't be read from code"]};let l=ye(e,s),a=l!==null&&typeof l=="object"&&!Array.isArray(l);return{tools:[{name:r,description:i,...a?{input_schema:l}:{}}],warnings:a?[]:[`${r}'s arguments couldn't be read from code`]}}function Rn(e,n){h(e[n],"as")&&h(e[n+1],"const")&&(n+=2);let t=e[n];return t===void 0||t.kind==="punct"&&",;)}]".includes(t.text)||h(t)&&t.line>(e[n-1]?.endLine??t.line)&&!["as","satisfies"].includes(t.text)}function bn(e,n,t){for(;d(e[n],".");)n++;return h(e[n])?[e[n].text]:!d(e[n],"{")&&!d(e[n],"[")?[]:W(e,n).filter(o=>o.from<o.to&&o.to<=t).flatMap(o=>{let s=o.from;return d(e[n],"{")&&d(e[s+1],":")&&(s+=2),bn(e,s,o.to)})}function On(e,n){let{toks:t}=e,o=new Map,s=new Map,r=new Map,i=[];for(let l=0;l<t.length;l++){if(d(t[l],"{")?i.push(l):d(t[l],"}")&&i.pop(),!h(t[l])||!["const","let","var"].includes(t[l].text))continue;let a=i.at(-1);if(n!==void 0&&a!==void 0&&(n<a||n>$(t,a)))continue;let c=h(t[l+1])?l+2:$(t,l+1)+1,u=bn(t,l+1,c).filter(p=>n===void 0||(s.get(p)??-1)<=i.length);for(let p of u)o.set(p,null),s.set(p,i.length),r.set(p,l);if(!h(t[l],"const")||!h(t[l+1])||!u.length)continue;let f=t[l+1].text;for(let p=l+2;p<Math.min(t.length,l+40)&&!d(t[p],";");p++)if(d(t[p],"=")){o.set(f,null),s.set(f,i.length),d(t[p+1],"[")&&Rn(t,$(t,p+1)+1)&&(o.set(f,p+1),s.set(f,i.length));break}}if(n!==void 0)for(let l of me(e)){if(l.params===null||n<=l.from||n>=l.to)continue;let a=l.params.filter(c=>c!==null);if(l.params.includes(null)){let c=t.findIndex((u,f)=>f>l.from&&f<n&&d(u,"("));c>=0&&a.push(...dt(t,c,"js").flatMap(({from:u,to:f})=>bn(t,u,f)))}for(let c of a)(r.get(c)??-1)<=l.from&&o.set(c,null)}return o}function Tl(e){let{toks:n}=e,t=new Map;for(let o=0;o<n.length;o++){if(!h(n[o],"export"))continue;let s=On(e,o);if(h(n[o+1],"const")){let r=n[o+2]?.text,i=s.get(r);i!=null&&t.set(r,i)}else if(h(n[o+1],"default")){let r=d(n[o+2],"[")?o+2:s.get(n[o+2]?.text),i=d(n[o+2],"[")?$(n,o+2)+1:o+3;r!=null&&Rn(n,i)&&t.set("default",r)}else if(d(n[o+1],"{"))for(let r of W(n,o+1)){let i=s.get(n[r.from]?.text);i!=null&&t.set(n[r.to-1].text,i)}}return t}function $s(e,n,t){return t.has(e[n.from]?.start)&&d(e[n.from+1],"(")&&$(e,n.from+1)===n.to-1}function Nl(e,n){let t=n?.call;if(!t)return;let{toks:o}=e;if(t.loadedPrompt&&t.callStart!==void 0){let f=o.findIndex(p=>p.start===t.callStart);if(f<0)return;for(;d(o[f+1],".")&&h(o[f+2]);)f+=2;return te(o,f,e)?{from:f+1,to:$(o,f+1)+1}:void 0}let s=new Set([t.symbol]),r=new Set(Object.keys(n.imports));for(let f of z(e)){let p=Ye(e.path,f.source,f.names,"js",r);if(!(t.promptPath&&p!==t.promptPath))for(let m of f.names)((f.renamed?.[m]??m)===t.symbol||p===t.promptPath&&m===f.defaultName)&&s.add(m)}let i=t.promptPath===e.path&&t.promptStart!==void 0?new Map([[t.promptStart,t.line??1]]):new Map,l=Te(e,[],i).filter(({site:f})=>t.line===void 0||f.line===t.line),a=(l.find(({site:f})=>f.value?.siteStart!=null&&f.value.siteStart===t.promptStart)??l.find(({site:f})=>f.value&&s.has(f.value.text))??l[0])?.valueAt;if(a===void 0)return;let c,u;for(let f=0;f<a;f++){if(!d(o[f],"(")&&!d(o[f],"{"))continue;let p=$(o,f)+1;p<=a||(d(o[f],"{")?c={from:f,to:p}:u={from:f,to:p})}return u??c}function vs(e,n,t,o){let s=V(n?.path??"tools.ts",e,"js"),{toks:r}=s,i=n?.call?.loadedPrompt?new Set(me(s).filter(k=>k.params!==null).map(k=>k.name)):new Set,l=On(s),a=new Map,c=n?.imports??{},u=new Set(Object.keys(c));for(let k of z(s)){let L=Ye(s.path,k.source,k.names,"js",u);if(L===void 0)continue;let A=V(L,c[L],"js"),C=o(c[L]);for(let[v,g]of Tl(A))for(let _ of k.names)(k.defaultName===_?"default":k.renamed?.[_]??_)===v&&a.set(_,{toks:A.toks,open:g,path:L,calls:C})}let f=new Set,p=new Set,m=[],x="Some tools couldn't be read from code",w=Nl(s,n),S=!1;for(let k=0;k<r.length;k++){if(w&&(k<w.from||k>=w.to))continue;let L=r[k];if(["input_schema","parameters"].includes(L.kind==="string"?L.value:L.text)&&d(r[k+1],":")&&d(r[k+2],"{")){k=$(r,k+2);continue}if((h(L,"tools")||L.kind==="string"&&L.value==="tools")&&d(r[k+1],":")){S=!0;let A=r[k+2],C=On(s,k),v=d(A,"[")?k+2:h(A)?C.get(A.text):void 0,g=d(A,"[")?$(r,k+2)+1:k+3;if(!Rn(r,g)){m.push(x);continue}v==null?h(A)&&!C.has(A.text)&&a.has(A.text)?p.add(A.text):m.push(x):f.add(v)}}if(!S)for(let k of l.values())k!==null&&W(r,k).some(L=>Is(r,L)||$s(r,L,t))&&f.add(k);let y=[],b=new Map,E=[...f].map(k=>({toks:r,open:k,calls:t,path:null}));E.push(...[...p].map(k=>a.get(k)));for(let{toks:k,open:L,calls:A,path:C}of E){let v=_=>m.push(C?`${C}: ${_}`:_),g=$(k,L);if(!d(k[g],"]")){v(x);continue}for(let _ of W(k,L)){let O=Is(k,_),R=$s(k,_,A),I=_.to===_.from+1&&h(k[_.from])?k[_.from].text:null,P=S&&C===null&&I&&i.has(I)?{name:I,description:""}:null;if(!O&&!R&&!P)v(x);else{let F=O?O.tools:P?[P]:S&&R?[A.get(k[_.from].start)]:[];for(let j of F)b.has(j.name)||b.set(j.name,C??s.path);y.push(...F),O?.warnings.forEach(v)}}}return{tools:y,warnings:m,selected:S,from:Object.fromEntries(b)}}var rt=String.raw`(?:"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')`,Fl=new RegExp(String.raw`(${rt}|`+"`(?:[^`\\\\]|\\\\.)*`)"+String.raw`|\/\/[^\n]*|\/\*[\s\S]*?\*\/`,"g"),Dl=/(?<![\w$])tool\s*(<[^()]*>)?\(/g,Wl=new RegExp(`^${rt}$`),Kl=new RegExp(`^${rt}(?:\\s*\\+\\s*${rt})*$`),Bl={n:`
14
- `,t:" ",r:"\r"};function Ls(e){return e.slice(1,-1).replace(/\\(.)/g,(n,t)=>Bl[t]??t)}function Ul(e){return e.replace(Fl,(n,t)=>t?t[0]+"_".repeat(t.length-2)+t[t.length-1]:" ".repeat(n.length))}function As(e,n){let t=0;for(let o=n;o<e.length;o++){let s=e[o];if("([{".includes(s))t++;else if(")]}".includes(s)){if(t===0)return o;t--}else if(s===","&&t===0)return o}return e.length}function Ps(e){let n=Ul(e),t=[],o=[],s=new Map,r="a tool( call in tools.ts was skipped: its name and description are not plain text";for(let i of n.matchAll(Dl)){let l=n.slice(Math.max(0,i.index-40),i.index).trimEnd();if(l.endsWith(".")&&!l.endsWith("...")||i[1]){o.push(r);continue}let c=As(n,i.index+i[0].length),u=c+1,f=As(n,u),p=e.slice(i.index+i[0].length,c).trim(),m=e.slice(u,f).trim();if(n[c]!==","||!Wl.test(p)||!Kl.test(m)){o.push(r);continue}let x=m.match(new RegExp(rt,"g")),w={name:Ls(p),description:x.map(Ls).join("")};t.push(w),s.set(i.index,w)}return{tools:t,warnings:o,readCalls:s}}function js(e,n){let{tools:t,warnings:o}=Ms(e,n);return{tools:t,warnings:o}}function Ms(e,n){let{tools:t,warnings:o,readCalls:s}=Ps(e),r=new Map(t.map(({name:l})=>[l,n?.path??"tools.ts"])),i=vs(e,n,s,l=>Ps(l).readCalls);if(i.selected)return i;t.push(...i.tools),o.push(...i.warnings);for(let[l,a]of Object.entries(i.from))r.has(l)||r.set(l,a);return{tools:t,warnings:o,from:Object.fromEntries(r),selected:!1}}function kp(e,n,t){let o=Object.fromEntries(e.filter(f=>G(f)==="js"&&n[f]!==void 0).map(f=>[f,n[f]])),s=Tt(o,Object.keys(n)),r=f=>{let p=Object.fromEntries(Tt({[f]:n[f]},Object.keys(n)).filter(x=>s.includes(x)).map(x=>[x,n[x]])),m=Ms(n[f],{path:f,imports:p,...t?.path===f?{call:t}:{}});return{...m,warnings:m.warnings.map(x=>`${f}: ${x}`)}},i=Object.keys(o).map(r),l=i.filter((f,p)=>f.selected&&(!t||Object.keys(o)[p]===t.path)),a=l.length?l:[...i,...s.filter(f=>!o[f]).map(r)],c=new Map;return{tools:a.flatMap(f=>f.tools.filter(p=>c.has(p.name)?!1:(c.set(p.name,f.from[p.name]),!0))),from:Object.fromEntries(c),warnings:[...new Set(a.flatMap(f=>f.warnings))]}}function Cs(e){let n;try{n=JSON.parse(e)}catch{return{tools:[],warnings:[".cli.json is not valid JSON; ignored"]}}let t=n?.clis;return!t||typeof t!="object"||Array.isArray(t)?{tools:[],warnings:[]}:{tools:Object.entries(t).map(([s,r])=>{let i=r?.description;return{name:s,description:typeof i=="string"?i:""}}),warnings:[]}}function Ts(e,n,t){let o=e.split(`
15
- `),s=Math.min(Math.max(n-1-3,0),o.length-1),r=0;for(let i=0;i<s;i++)r+=o[i].length+1;return{text:e.slice(r,r+t),fromLine:s+1}}var zl=/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|rb|java|kt|swift|c|cc|cpp|h|hpp|cs|php|sh|bash|zsh|ps1|sql|tf|hcl|lock|toml|gradle)$/i,Jl=/\.(md|mdx|txt|json|ya?ml)$/i;function In(e){return zl.test(e.trim())}function bp(e){return!In(e)&&Jl.test(e.trim())}var Xl=["stripe","slack","postgresql","datadog","pagerduty","jira","googlecalendar"],Gl=new Set(Xl);function Nt(e){if(!e)return null;let n=e.trim().toLowerCase();return Gl.has(n)?n:null}function ql(e,n){let t=[...e.warnings],o=new Set(e.nodes.map(l=>l.id)),s=new Set,r=e.nodes.map(l=>{let a=[],c=new Set;for(let u of l.tools??[]){let f=u.label.trim();if(!f){t.push(`${n}: dropped a tool with no name on ${l.id}`);continue}let p=`${u.source??"tool"}:${f}`;if(c.has(p)){t.push(`${n}: ${l.id} lists ${f} twice \u2014 kept one`);continue}c.add(p);let m=Nt(u.brand);u.brand&&!m&&!s.has(u.brand)&&(s.add(u.brand),t.push(`${n}: "${u.brand}" is not a provider mark we can draw \u2014 those tools render without one`)),a.push({label:f,brand:m,...u.source?{source:u.source}:{}})}return{...l,tools:a}}),i=e.edges.filter(l=>{let a=o.has(l.from)&&o.has(l.to);return a||t.push(`${n}: dropped edge ${l.from} \u2192 ${l.to} (unknown endpoint)`),a});return e.nodes.some(l=>l.kind==="agent")||t.push(`${n}: the mapping found no agent node \u2014 the graph may be incomplete`),{fragment:{...e,nodes:r,edges:i,warnings:[]},warnings:t}}var $n=2e4;function Ns(e){return e.trim().replace(/^(?:\.?\/)+/,"")}function Vl(e,n,t){let o=[],s=new Map;for(let a of Object.keys(n))s.set(Ns(a),a);let r={},i=vn(e),l=e.nodes.map(a=>{let c=[],u=[];for(let f of a.files??[]){let p=f.path.trim();if(!p)continue;let m=s.get(Ns(p));if(m===void 0){o.push(`${t}: node ${a.id} lists ${p} as a definition file, which the analysis never read \u2014 dropped`);continue}let x=n[m],w=x.length>$n,S=w&&f.span&&f.role==="system prompt"&&In(m)?Ts(x,f.span.from,$n):null,y=S?S.text:w?x.slice(0,$n):x;w&&!Ln(m,i)&&o.push(`${t}: node ${a.id}'s ${f.role} file (${m}) is ${x.length} characters \u2014 stored truncated at ${y.length}`),c.push({role:f.role,label:f.label??null,path:m,...f.span?{span:f.span}:{},...f.filledAtRunTime?{filledAtRunTime:!0}:{}}),u.push({...f.filledAtRunTime?{filledAtRunTime:!0}:{},role:f.role,...f.label?{label:f.label}:{},path:m,tokens:to(x.length),text:y,...w?{truncated:!0,storedChars:y.length}:{},...f.span?{span:f.span}:{},...S?{fromLine:S.fromLine}:{}})}return u.length&&(r[a.id]=u),{...a,files:c}});return{fragment:{...e,nodes:l},nodes:r,warnings:o}}function Hl(e){let n=[],t=[];for(let{repoKey:o,fragment:s,files:r}of e){let i=l=>`${o}#${l}`;for(let l of s.nodes){let a=r?.[l.id],c=(l.tools??[]).map(u=>({label:u.label,...u.brand?{brand:u.brand}:{},...u.source?{source:u.source}:{}}));n.push({id:i(l.id),label:l.label,kind:l.kind,desc:l.desc,meta:l.meta,...l.sourcePaths?{sourcePaths:l.sourcePaths}:{},sourceRef:l.sourceRef?{repo:o,path:l.sourceRef.path,line:l.sourceRef.line}:null,...a?.length?{files:a}:{},...c.length?{tools:c}:{}})}for(let l of s.edges)t.push({from:i(l.from),to:i(l.to),kind:l.kind,label:l.label,sourceRef:l.sourceRef?{repo:o,path:l.sourceRef.path,line:l.sourceRef.line}:null})}return{nodes:n,edges:t}}var Yl={critical:0,high:1,medium:2,low:3};function An(e){return Yl[e]}function Fs(e){let n=e?.trim();return n&&n.length<=280?n:null}var Zl=2,Pn=4,jn=120,Ds="Which should the agent do?",Ql="asked to pose a question, answered with one fix";function Ws(e){if(!Gt(e.category))return{question:null,fixes:e.fixes,warnings:[]};let n=`finding "${e.title}"`;if(e.fixes.length<Zl)return{question:null,fixes:e.fixes,warnings:[`${n}: ${Ql}`]};let t=[],o=e.fixes;o.length>Pn&&(t.push(`${n}: ${o.length} options proposed; keeping the first ${Pn}`),o=o.slice(0,Pn));let s=(e.question??"").trim();return s?s.length>jn&&(t.push(`${n}: the question is longer than ${jn} characters; cut`),s=`${s.slice(0,jn-1).trimEnd()}\u2026`):(t.push(`${n}: no question with ${o.length} options; asking "${Ds}"`),s=Ds),{question:s,fixes:o,warnings:t}}function Cn(e){let n=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return[e.kind,e.siteRepo??"-",e.site?.path??"-",n].join("|")}var Se=e=>e.legacyFingerprint??e.fingerprint,Ne=e=>e.replace(/\s+/g," ").trim(),ea=new Set("a an and are as at be been being but by can could do does for from has have in is it its of on or that the their them then there these they this those to until was were which while will with would".split(" ")),it=new Set(["before","after","instead","from","to","than"]),Us=new Set([...it,"no","not","never","cannot","without"]),ta=/^(?:send(?:s|ing)?|sent|delet(?:e[sd]?|ing)|refund(?:s|ed|ing)?|grant(?:s|ed|ing)?|revok(?:e[sd]?|ing)|return(?:s|ed|ing)?|rout(?:e[sd]?|ing)|read(?:s|ing)?|writ(?:e[sd]?|ing)|charg(?:e[sd]?|ing)|block(?:s|ed|ing)?|allow(?:s|ed|ing)?|skip(?:s|ped|ping)?|select(?:s|ed|ing)?|check(?:s|ed|ing)?|request(?:s|ed|ing)?)$/,Tn=e=>e.split(/[.!?;,\n]+|\b(?:and|but|while)\b/);function Fe(e){return ta.test(e)?e==="sent"?"send":e.replace(/(?:ing|ped|ed|es|s)$/,"").replace(/^skipp$/,"skip").replace(/^(delet|revok|rout|writ|charg)$/,"$1e"):null}function De(e){let n=(e.toLowerCase().replaceAll("can't","cannot").match(/[a-z0-9_]+/g)??[]).filter(t=>!ea.has(t)||it.has(t)).map(t=>Fe(t)??t);return n.map((t,o)=>["not","never","cannot"].includes(t)&&Fe(n[o+1]??"")!==null?"skip":t)}function Mn(e){return new Set(De(e))}function na(e){return[...Mn(e)].filter(n=>Fe(n)!==null).sort()}function oa(e){return Tn(e).filter(n=>De(n).some(t=>it.has(t))).map(n=>De(n).join(" ")).sort()}function sa(e,n){let t=o=>o!=="refund"&&Fe(o)!==null;return Tn(e).flatMap(o=>{let s=De(o);return s.flatMap((r,i)=>{if(!t(r))return[];let l=s.slice(i+1),a=l.findIndex(w=>t(w)||Us.has(w)),c=l.slice(0,a<0?l.length:a).filter(w=>n.has(w)),u=["skip","no","not","never","cannot","without"].includes(s[i-1]??""),f=a<0?[]:l.slice(a),p=f.findIndex(w=>t(w)),m=f.slice(0,p<0?f.length:p),x=m.flatMap((w,S)=>{if(!it.has(w))return[];let y=m.slice(S+1),b=y.findIndex(E=>it.has(E));return[JSON.stringify([w,y.slice(0,b<0?y.length:b).filter(E=>n.has(E))])]});return c.length?[{action:r,objects:c,denied:u,relations:x}]:[]})}).sort((o,s)=>JSON.stringify(o).localeCompare(JSON.stringify(s)))}function ra(e){let n=De(e);return["before","after","instead"].filter(t=>n.includes(t)).concat(n.some((t,o)=>["no","not","never","cannot","without"].includes(t)||t==="skip"&&Fe(n[o+1]??"")!==null)?["negative"]:[])}function Ft(e){let n=Ne(e.cause??"").toLowerCase(),t=[...new Set(e.sites.map(r=>Ne(r.quote).toLowerCase()))].sort((r,i)=>i.length-r.length||r.localeCompare(i));for(let r of t)n=n.replaceAll(r,"");let o=Mn(n),s=Mn(e.sites.map(r=>r.quote).join(" "));return{text:n,terms:o,operators:n.match(/!==|===|!=|==|<=|>=|<|>/g)??[],actions:na(n),direction:ra(n),relations:oa(n),anchors:[...o].filter(r=>s.has(r)).sort(),numbers:[...o].filter(r=>/^\d+$/.test(r)).sort(),objects:Tn(n).map(r=>De(r).filter(i=>s.has(i)&&Fe(i)===null&&!Us.has(i)).join(" ")).filter(Boolean).sort(),bindings:sa(n,s)}}function zs(e,n){let[t,o]=[Ft(e),Ft(n)];if(Math.min(t.terms.size,o.terms.size)<3||!t.anchors.length)return!1;for(let r of["operators","actions","direction","relations","anchors","numbers","objects","bindings"])if(JSON.stringify(t[r])!==JSON.stringify(o[r]))return!1;let s=[...t.terms].filter(r=>o.terms.has(r));return t.text===o.text||s.length>=4&&s.length/Math.max(t.terms.size,o.terms.size)>=.7}function ia(e){return[...new Set(e.map(n=>JSON.stringify([n.repoKey,n.path,Ne(n.quote)])))].sort()}function Dt(e){return e.omittedSites||!e.sites.length||e.sites.some(n=>n.verified===!1||!n.path||!Ne(n.quote)||!Number.isInteger(n.startLine)||n.startLine<1||!Number.isInteger(n.endLine)||n.endLine<n.startLine)?null:ia(e.sites)}function la(e,n){if(!e.kind||e.kind!==n.kind||!e.category||e.category!==n.category||(e.agentId??null)!==(n.agentId??null))return!1;let[t,o]=[Dt(e),Dt(n)];return t!==null&&o!==null&&JSON.stringify(t)===JSON.stringify(o)&&zs(e,n)}function aa(e,n){if(e.kind!==n.kind||e.category!==n.category||(e.agentId??null)!==(n.agentId??null))return!0;let[t,o]=[Dt(e),Dt(n)];return t!==null&&o!==null&&JSON.stringify(t)!==JSON.stringify(o)?!0:t===null||o===null?!1:Js(e,n)}function Js(e,n){let[t,o]=[Ft(e),Ft(n)],s=(i,l)=>i.some(a=>!l.includes(a))&&l.some(a=>!i.includes(a));for(let i of["actions","anchors","numbers","operators"])if(s(t[i],o[i]))return!0;for(let i of t.actions.filter(l=>o.actions.includes(l))){let l=t.bindings.filter(c=>c.action===i),a=o.bindings.filter(c=>c.action===i);if(l.length&&a.length&&l.every(c=>a.every(u=>s(c.objects,u.objects)||c.denied!==u.denied||s(c.relations,u.relations))))return!0}for(let i of new Set(t.bindings.map(l=>JSON.stringify(l.objects)))){let l=a=>a.bindings.filter(c=>JSON.stringify(c.objects)===i).map(c=>c.action);if(s(l(t),l(o)))return!0}let r=i=>i.direction.filter(l=>l!=="negative");return!!s(r(t),r(o))}function Wp(e){for(let u of[e.previous,e.current])if(u.some(f=>!f.id||!f.fingerprint)||new Set(u.map(f=>f.id)).size!==u.length)throw new Error("Missing or duplicate finding identities.");let n=e.previous.flatMap(u=>e.current.flatMap(f=>(Se(u)===Se(f)?!e.enabled||!aa(u,f):e.enabled&&la(u,f))?[{previous:u,current:f}]:[])),t=[],o=new Set,s=new Set,r=(u,f)=>{for(let p of u)u.filter(m=>m.previous.id===p.previous.id).length!==1||u.filter(m=>m.current.id===p.current.id).length!==1||(t.push({previousId:p.previous.id,currentId:p.current.id,fingerprint:e.enabled?p.previous.fingerprint:Se(p.previous),reason:f}),o.add(p.previous.id),s.add(p.current.id))};r(n.filter(u=>Se(u.previous)===Se(u.current)),"legacy");let i=n.filter(u=>!o.has(u.previous.id)&&!s.has(u.current.id));e.enabled&&r(i,"meaning");let l=i.filter(u=>!o.has(u.previous.id)&&!s.has(u.current.id)),a=new Map;for(let u of l){let f=l.filter(x=>x.current.id===u.current.id).map(x=>x.previous.id).sort(),p=l.filter(x=>x.previous.id===u.previous.id).map(x=>x.current.id).sort(),m={reason:"ambiguous",previousIds:f,currentIds:p};a.set(JSON.stringify(m),m)}t.sort((u,f)=>u.previousId.localeCompare(f.previousId)||u.currentId.localeCompare(f.currentId));let c=new Map(t.map(u=>[u.currentId,u]));return{matches:t,unmatchedPrevious:e.previous.filter(u=>!o.has(u.id)),unmatchedCurrent:e.current.filter(u=>!s.has(u.id)),currentIdentities:e.current.map(u=>({currentId:u.id,legacyFingerprint:Se(u),matchedFingerprint:c.get(u.id)?.fingerprint??Se(u),matchedId:c.get(u.id)?.previousId??u.id})),diagnostics:[...a.entries()].sort(([u],[f])=>u.localeCompare(f)).map(([,u])=>u)}}var Xs=e=>[...e.site?[{...e.site,excerpt:e.excerpt}]:[],...e.otherSites??[]];function Ks(e){let n=Xs(e),t=new Map;for(let o of n){let s=JSON.stringify([o.path,o.line??null]);(!t.has(s)||(o.line??0)>0&&o.excerpt?.trim())&&t.set(s,o)}return[...t.values()].sort((o,s)=>o.path.localeCompare(s.path)||(o.line??-1)-(s.line??-1))}function Kp(e,n){if(e.category!==n.category)return!1;let[t,o]=[Ks(e),Ks(n)];return t.length===o.length&&t.every((s,r)=>s.path===o[r].path&&(s.line==null||o[r].line==null?s.line==o[r].line:Math.abs(s.line-o[r].line)<=3))}function Bp(e,n){let[t,o]=[Bs(e,"a"),Bs(n,"b")];if((t.agentId??null)!==(o.agentId??null)||Js(t,o))return!1;let s=(u,f)=>u.omittedSites&&!!f.excerpt?.trim()||u.sites.some(p=>!!p.quote.trim()&&(!p.path||!Number.isInteger(p.startLine)||p.startLine<1||p.verified===!1));if(s(t,e)||s(o,n))return!1;let r=u=>{let f=new Map;for(let p of u.sites){if(!p.quote.trim())continue;let m=JSON.stringify([p.repoKey,p.path,p.startLine]);(!f.has(m)||f.get(m).endLine<p.endLine)&&f.set(m,p)}return[...f.values()]},[i,l]=[r(t),r(o)].sort((u,f)=>u.length-f.length);if(!i.length||e.category!==n.category&&i.length<2||i.length===1&&Ne(e.cause).toLowerCase()!==Ne(n.cause).toLowerCase()&&!zs(t,o))return!1;let a=(u,f)=>u.repoKey===f.repoKey&&u.path===f.path&&u.startLine<=f.endLine&&f.startLine<=u.endLine,c=(u,f)=>u===i.length||l.some((p,m)=>f.has(m)||!a(i[u],p)?!1:c(u+1,new Set([...f,m])));return c(0,new Set)}function Bs(e,n){return{id:n,fingerprint:Cn(e),kind:e.kind,title:e.title,category:e.category,cause:e.cause,agentId:e.agentId,omittedSites:+!e.site,sites:Xs(e).map(t=>({repoKey:t.repo??e.siteRepo??"",path:t.path,startLine:t.line??0,endLine:(t.line??0)+(t.excerpt?.split(`
16
- `).length??1)-1,quote:t.excerpt??"",...t.verified!==void 0?{verified:t.verified}:{}}))}}function Nn(e,n,t,o,s){if(n===null)return null;let r=e.safeParse(n);return r.success?r.data:(s.push(`${o}: ${t} "${n}" is not one of ${Object.values(e.enum).join(", ")} \u2014 dropped`),null)}var Dn=12,Gs=3,Fn=3;function qs(e,n){return Object.keys(e).find(t=>e[t].has(n))}function ca(e,n,t=Dn,o={}){let s=[],r=e;if(Jt(o)){let c=e.filter(u=>u.category==="better_as_code");if(c.length>Gs){let u=c.sort((p,m)=>An(p.severity)-An(m.severity)).slice(0,Gs),f=0;r=e.flatMap(p=>p.category!=="better_as_code"?[p]:f<u.length?[u[f++]]:[])}}let i=r.slice(0,t);r.length>t&&!(Jt(o)&&t>Dn)&&s.push(`the model proposed ${r.length} findings; keeping the first ${t}`);let l=c=>{let u=(c.otherSites??[]).flatMap(m=>{let x=Xt.safeParse(m);return x.success?[x.data]:(s.push(`finding "${c.title}" listed an other site in a shape we could not read \u2014 dropped`),[])});u.length>Fn&&s.push(`finding "${c.title}" quoted ${u.length} other sites; keeping the first ${Fn}`);let f=u.slice(0,Fn).flatMap(m=>{let x=qs(n,m.path);return x?[{...m,repo:x}]:(s.push(`finding "${c.title}" also cited ${m.path}, which the analysis never read \u2014 that site dropped`),[])});if(!c.site)return{...c,siteRepo:null,otherSites:f};let p=qs(n,c.site.path);return p?{...c,siteRepo:p,otherSites:f}:(s.push(`finding "${c.title}" cited ${c.site.path}, which the analysis never read \u2014 site dropped`),{...c,site:null,excerpt:c.excerpt,siteRepo:null,otherSites:f})};return{findings:i.map(c=>{let u=l(c),f=Ws(u);return s.push(...f.warnings),{...u,summary:Fs(u.summary),fixes:f.fixes,question:f.question}}),warnings:s}}function ua(e){let n=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=[...new Set(e.targetFiles.map(o=>o.path.trim().replace(/^(\.\/)+/,"")))].sort().join(`
17
- `);return[e.kind,n,t].join("|")}function fa(e,n,t){if(!e)return{delta:null,warnings:[]};let o=[],s=[];for(let l of e.nodes){let a=Nn(zt,l.change,`delta node ${l.id} change`,t,o);if(a){if(a!=="added"&&!n.has(l.id)){o.push(`${t}: dropped delta node ${l.id} (not in the architecture)`);continue}s.push({id:l.id,change:a,label:l.label})}}let r=new Set([...n,...s.map(l=>l.id)]),i=[];for(let l of e.edges){let a=`${l.from} \u2192 ${l.to}`,c=Nn(zt,l.change,`delta edge ${a} change`,t,o),u=Nn(no,l.kind,`delta edge ${a} kind`,t,o);if(!(!c||!u)){if(!r.has(l.from)||!r.has(l.to)){o.push(`${t}: dropped delta edge ${a} (unknown node)`);continue}i.push({from:l.from,to:l.to,kind:u,change:c,detail:l.detail})}}return s.length===0&&i.length===0?{delta:null,warnings:o}:{delta:{nodes:s,edges:i},warnings:o}}function pa(e){return Cn(e)}function da(e){let n=e.split(`
18
- `);return n.length>1&&n[n.length-1]===""&&n.pop(),n.map((t,o)=>`${o+1} ${t}`).join(`
19
- `)}function Wt(e){return{label:e,brand:Nt(e)}}function pd(e,n,t,o,s){let r=[],i=a=>{r.push(...a.tools.map(c=>c.name)),s.push(...a.warnings.map(c=>`${n}: ${c}`))};if(o.toolsPath)try{r.push(...No(t[o.toolsPath]).tools.map(a=>a.name))}catch{s.push(`${n}: tools.json is not a valid tool list; ignored`)}o.toolsTsPath&&i(js(t[o.toolsTsPath])),o.cliPath&&i(Cs(t[o.cliPath]));let l=[];if(o.mcpPath){let a=To(t[o.mcpPath],o.mcpPath,o.toolsPath!==null);l.push(...a.servers),s.push(...a.warnings.map(c=>`${n}: ${c}`))}return[...new Set(r)].map(Wt).concat(l.map(a=>({...Wt(a),source:"mcp"})))}function Vs(e){let n=e.sourceRef?.repo?`${e.sourceRef.repo}#`:null;return e.unitKey??(n&&e.id.startsWith(n)?e.id.slice(n.length):e.id.startsWith("model:")?e.id:e.id.slice(e.id.indexOf("#")+1))}function Hs(e){return Vs(e).startsWith("model:")}function vn(e){return new Set(e.nodes.filter(Hs).flatMap(n=>[...(n.files??[]).map(t=>t.path),...n.sourceRef?[n.sourceRef.path]:[]]))}function Ln(e,n){let t=e.trim().replace(/^(\.\/)+/,"");if(!n)return t.includes(" \u203A ")&&t.slice(t.lastIndexOf(" \u203A ")+3).includes("/");if(n.has(t))return!0;for(let o of n){let s=o.indexOf(" \u203A ");if(s>=0&&t.startsWith(o.slice(0,s+3)))return!0}return!1}async function kd(e,n,t,o,s=!1,r){if(n)return n;let i={enabled:o??e.CF_ANALYSIS_IMPORTED_AGENTS!=="0",byRepo:{}};if(!i.enabled)return i;ht(e)&&(i.grouped=!0);let l=await t?.()??[];s&&(i.agentRows=structuredClone(r?.length?[...r]:l.map((a,c)=>({id:a.id??String(c),repoPath:a.repoPath,unitKey:a.unitKey,notFoundAt:a.notFoundAt??null}))));for(let a of l){if(!a.unitKey||!a.repoPath||!a.unitKey.startsWith("model:")&&(!s||!a.codeInputsJson))continue;let c=so(a.repoPath);if(!c)continue;let u=a.unitKey.startsWith("model:")?i.byRepo:i.codeByRepo??={};(u[c]??=[]).push(structuredClone({unitKey:a.unitKey,name:a.name,...a.groupKey===void 0?{}:{groupKey:a.groupKey},...a.groupName===void 0?{}:{groupName:a.groupName},systemPrompt:a.systemPrompt,toolsJson:a.toolsJson,model:a.model,...a.codeInputsJson===void 0?{}:{codeInputsJson:a.codeInputsJson},...a.links===void 0?{}:{links:a.links},...a.services===void 0?{}:{services:a.services}}))}return i}function Zs(e,n){let t=e.slice(6).split("#")[0];return ma(t,n)}function ma(e,n){return n?D(e,ut(n))??e:e}function Ys(e){return`${Zs(e.unitKey)} \u203A ${e.name}`}function Wn(e,n,t=""){let o=e?.enabled?e.byRepo[n]??[]:[],s=o.map(Ys),r=new Set(Object.entries(e?.enabled?e.byRepo:{}).filter(([a])=>a!==n).flatMap(([,a])=>a.map(Ys))),i=o.map((a,c)=>{let u=s.filter(S=>S===s[c]).length>1?`${s[c]} (${a.unitKey.split("#").slice(1).join("#")})`:s[c],f=r.has(s[c])?`${n} \u203A ${u}`:u,p=`${f}/system_prompt.md`,m={[p]:a.systemPrompt??t},x=[{role:"system prompt",label:null,path:p}];if(a.toolsJson?.length){let S=`${f}/tools.json`;m[S]=JSON.stringify(a.toolsJson,null,2),x.push({role:"tools",label:null,path:S})}if(a.services?.length){let S=`${f}/context.md`,y=a.services.map(({name:b,kind:E})=>`${Mo(b)}${E===b?"":` (${E})`}`);m[S]=`This agent's code (not the model) reads from or writes to: ${y.join(", ")}.`,x.push({role:"reference",label:"Context",path:S})}return{node:{id:a.unitKey,label:a.name,kind:"agent",desc:"",meta:a.model,sourceRef:{path:p,line:1},files:x,tools:(a.toolsJson??[]).map(S=>Wt(S.name))},files:m,keys:[a.unitKey],sourcePath:Zs(a.unitKey,n),agentKey:a.unitKey.split("#").slice(1).join("#")}});if(!e?.grouped)return i.map(a=>({...a,steps:[a]}));let l=new Map;return i.forEach((a,c)=>{let u=o[c].groupKey?`group:${o[c].groupKey}`:`step:${c}`,f=l.get(u)??[];f.push(a),l.set(u,f)}),[...l.values()].map(a=>{let c=a[0],u=o.find(f=>f.unitKey===c.node.id);return{...c,steps:a,keys:a.flatMap(f=>f.keys),files:Object.assign({},...a.map(f=>f.files)),node:{...c.node,label:u.groupName??u.name,sourcePaths:[...new Set(a.map(f=>f.sourcePath))],files:a.flatMap(f=>f.node.files),tools:[...new Map(a.flatMap(f=>f.node.tools).map(f=>[f.label,f])).values()]}}})}function Qs(e,n){return Wn(e,n).flatMap(({steps:t})=>t.flatMap(({files:o,sourcePath:s,agentKey:r})=>Object.entries(o).map(([i,l])=>({path:i,text:l,sourcePath:s,agentKey:r,role:i.slice(i.lastIndexOf("/")+1)}))))}function _d(e,n,t,o=""){let s=new Set(t.nodes.filter(u=>u.kind==="agent").map(u=>u.id)),r=[],i={},l=Wn(e,n,o);for(let u of l)s.has(u.node.id)||(s.add(u.node.id),r.push(u.node),Object.assign(i,u.files));let a=new Map(l.flatMap(u=>u.keys.map(f=>[f,u.node.id]))),c=Co((e?.enabled?e.byRepo[n]??[]:[]).filter(u=>s.has(a.get(u.unitKey)??u.unitKey)).map(u=>{let f=a.get(u.unitKey)??u.unitKey;return{...u,id:f,scope:n,links:u.links?.map(p=>({...p,to:a.get(p.to)??p.to})).filter(p=>!e?.grouped||p.to!==f),unitKey:f}}));return{nodes:r,files:i,edges:c}}function Ed(e,n,t){return t.length?n.filter(o=>!o.startsWith(`${e}: no agent found \u2014`)&&!o.startsWith(`${e}: no agent conventions found (`)):n}function bd(e,n,t){let o=new Set(Wn(e,n).flatMap(s=>Object.keys(s.files)));return o.size?Object.fromEntries(Object.entries(t).filter(([s])=>!o.has(s))):t}import{posix as q}from"node:path";function er(e,n){if(n==="markdown"){let l=e.startsWith("---")?e.indexOf(`
20
- ---`,3):-1;return l<0?null:{start:3,end:l+1,bodyStart:l+4,newline:`
21
- `,raw:e.slice(3,l).split(`
22
- `)}}if(n==="outline"){let l=e.split(`
23
- `),a=l[0]==="---"?l.indexOf("---",1):-1;if(a<0)return null;let c=l.slice(0,a).join(`
24
- `).length+1;return{start:4,end:c,bodyStart:Math.min(e.length,c+4),newline:`
25
- `,raw:l.slice(1,a)}}let t=/^\uFEFF?---(\r?\n)/.exec(e);if(!t)return null;let o=e.slice(t[0].length),s=/^---(?:\r?\n|$)/m.exec(o);if(!s)return null;let r=o.slice(0,s.index),i=t[0].length+s.index;return{start:t[0].length,end:i,bodyStart:i+s[0].length,newline:t[1],raw:r?r.slice(0,-1).split(`
26
- `):[]}}function nr(e){return(e.startsWith('"')?e.match(/^"((?:\\.|[^"\\])*)"\s*(?:#.*)?$/):e.match(/^'((?:''|[^'])*)'\s*(?:#.*)?$/))?.[1]??null}function tr(e,n=!1){if(!e||e.startsWith("#"))return null;if(e.startsWith('"')||e.startsWith("'"))return nr(e);let t=e.replace(/\s+#.*$/,"");if(n&&/:\s*$/.test(t))return null;let o=n?t.trimEnd():t;return/^[[\]{}&*!?@`%|>]|^-(?:\s|$)|:\s/.test(o)||/^(?:[-+]?\d|[-+]?\.\d|[-+]?\.(?:inf|nan)$|null$|~$|true$|false$|yes$|no$|on$|off$|y$|n$)/i.test(o)?null:t}function ha(e,n=!1,t=!1){let o=[],s=new Map,r=null;return e.map(i=>{let l=i.replace(/\r$/,""),a=l.length-l.trimStart().length,c=()=>o.map(({key:w})=>w).join(".")||null;if(r&&(!l.trim()||a>r.indent))return l.trim()&&(r.contentIndent??=a),{location:c(),text:l.slice(r.contentIndent??a),keys:r.keys};if(r=null,!l.trim()||l.trimStart().startsWith("#"))return{location:c()};for(;o.length&&o.at(-1).indent>=a;)o.pop();if(t&&/^\s*-\s/.test(l)){let w=o.map(({key:b})=>b),S=JSON.stringify(w),y=s.get(S)??0;return s.set(S,y+1),{location:c(),keys:[...w,y]}}let u=l.match(/^\s*([\w.-]+):(?:\s+(.*))?$/);if(!u)return{location:c()};let f=u[2]??"",p=[...o.map(({key:w})=>w),u[1]];if(!f||f.startsWith("#"))return o.push({indent:a,key:u[1]}),{location:c(),...t?{keys:p}:{}};if(/^[|>][+-]?\s*(?:#.*)?$/.test(f))return r={indent:a,keys:p},{location:c()};let m=f.match(/^(["'])(.*)\1\s*(?:#.*)?$/),x=n?nr(f)??f.replace(/\s+#.*$/,""):m?m[2]:f.replace(/\s+#.*$/,"");return{location:c(),text:x,keys:p}})}function Kn(e,n={}){let t=e.split(`
27
- `).map(i=>i.replace(/\r$/,"")),o=ha(t,!0),s={},r=[{indent:-1,value:s}];for(let i=0;i<t.length;i++){let l=t[i];if(!l.trim()||l.trimStart().startsWith("#"))continue;if(l.includes(" "))return null;let a=l.length-l.trimStart().length,c=l.match(/^\s*([\w.-]+):(?:\s+(.*))?$/),u=l.match(/^\s*-(?:\s+(.*))?$/);if(!c&&!u)return null;for(;r.at(-1).indent>=a;)r.pop();let f=r.at(-1);if(f.childIndent??=a,f.childIndent!==a||f.indent===-1&&a!==0)return null;if(u){if(!n.lists)return null;let x=tr(u[1]??"",!0);if(x===null||r.length===1)return null;if(!Array.isArray(f.value)){if(Object.keys(f.value).length)return null;f.value=[],Object.defineProperty(r.at(-2).value,f.key,{value:f.value,enumerable:!0,writable:!0})}f.value.push(x);continue}if(!c||Array.isArray(f.value)||Object.hasOwn(f.value,c[1]))return null;let p=c[2]??"";if(!p||p.startsWith("#")){let x={};Object.defineProperty(f.value,c[1],{value:x,enumerable:!0,writable:!0}),r.push({indent:a,key:c[1],value:x});continue}let m;if(/^[|>][+-]?\s*(?:#.*)?$/.test(p)){let x=i+1,w;for(;i+1<t.length;){let y=t[i+1],b=y.length-y.trimStart().length;if(y.trim()&&b<=a)break;if(y.includes(" ")||y.trim()&&(w??=b,b<w))return null;i++}let S=i;m=o.slice(x,S+1).flatMap(({text:y})=>y===void 0?[]:[y]).join(`
28
- `)}else{let x=tr(p);if(x===null)return null;m=x}Object.defineProperty(f.value,c[1],{value:m,enumerable:!0,writable:!0})}return s}function $d(e){let n=Kn(e,{lists:!0});return n?Bn(e,{legacyBoundaries:!0}).map(t=>({key:t.key,value:n[t.key],span:t.span})):null}function Bn(e,n={}){let t=e.split(`
29
- `),o=t.flatMap((s,r)=>(n.legacyBoundaries?s.trim()&&!/^\s|^#/.test(s):/^[\w.-]+:(?:\s|$)/.test(s))?[r]:[]);return o.map((s,r)=>{let i=t[s].slice(0,t[s].indexOf(":")),l=o[r+1]??t.length;for(;l>o[r]+1&&!t[l-1].trim();)l--;return{key:i,span:{from:s+1,to:l}}})}function Un(e){let n=e.split(/^---(?:\s+#.*)?\s*$/m);if(n.length>1)return[...new Set(n.flatMap(Un))];let t=e.split(`
30
- `).filter(i=>i.trim()&&!/^\s*(?:#|---\s*$|\.\.\.\s*$|%[A-Z])/.test(i)),o=t.join(`
31
- `).trimStart().replace(/^(?:(?:&[\w.-]+|!<[^>]+>|![\w:/.!-]+)\s+)+/,"");if(o.startsWith("{"))return ga(o);let s=i=>i.length-i.trimStart().length,r=t.reduce((i,l)=>Math.min(i,s(l)),1/0);return t.flatMap(i=>{let l=/^["']?([\w.-]+)["']?\s*:/.exec(i.trimStart());return s(i)===r&&l?[l[1]]:[]})}function ga(e){let n=[],t=[],o="",s=!1;for(let r=0;r<e.length;r++){let i=e[r];if(o){i==="\\"&&o==='"'?r++:i===o&&(o==="'"&&e[r+1]==="'"?r++:o="");continue}if(i==="#"&&/\s/.test(e[r-1]??" ")){for(;r<e.length&&e[r]!==`
32
- `;)r++;continue}if(s&&t.length===1&&!/\s/.test(i)&&i!=="}"&&i!=="?"){let l=/^(?:"((?:\\.|[^"\\])*)"|'((?:''|[^'])*)'|([\w.-]+))\s*:/.exec(e.slice(r));if(!l)return[];try{n.push(l[1]!==void 0?JSON.parse(`"${l[1]}"`):l[2]?.replace(/''/g,"'")??l[3])}catch{return[]}r+=l[0].length-1,s=!1;continue}if(i==='"'||i==="'")o=i;else if(i==="{"||i==="[")t.push(i),t.length===1&&(s=!0);else if(i==="}"||i==="]"){if(t.pop()!==(i==="}"?"{":"["))return[];if(!t.length)return n}else i===","&&t.length===1&&(s=!0)}return[]}function lt(e){return gt(e,"CF_IMPORT_LAYOUTS")}function zn(e,n,t={}){if(!lt(e))return[];let o=[...new Set(n)].filter(r=>!/[\\:\0]/.test(r)&&r.split("/").every(i=>i&&i!=="."&&i!=="..")).sort(),s=new Map;for(let r of o){let i=/^(?:(.*)\/)?environments\/[^/]+\.ya?ml$/i.exec(r),l=/^(?:(.*)\/)?agents\/[^/]+\/environment\.ya?ml$/i.exec(r),a=i?.[1]??l?.[1]??(i||l?"":null);if(a===null||s.has(a))continue;let c=p=>D(p,a),u=o.filter(p=>/^agents\/(?:[^/]+\.md|[^/]+\/agent\.md)$/i.test(c(p)??""));if(!u.length)continue;let f=o.filter(p=>/^(?:environments\/[^/]+\.ya?ml|vaults\/[^/]+\.ya?ml|policy\.ya?ml|agents\/[^/]+\/(?:environment|policy|vault)\.ya?ml|skills\/[^/]+\/SKILL\.md)$/i.test(c(p)??""));s.set(a,{folder:a,agents:u,configs:f})}for(let r of s.values())for(let i of r.agents){if(t[i]===void 0)continue;let l=xa(i,t[i],r,o);for(let a of l.configPaths)r.configs.includes(a)||r.configs.push(a);for(let a of l.relationships)a.kind==="config"&&t[a.path]!==void 0&&ya(t[a.path])&&!r.configs.includes(a.path)&&r.configs.push(a.path)}return[...s.values()].sort((r,i)=>r.folder<i.folder?-1:r.folder>i.folder?1:0)}function Cd(e,n,t){let o=zn(e,n,t).filter(s=>s.agents.some(r=>t[r]===void 0));return n.filter(s=>/\.(?:ya?ml|json|md)$/i.test(s)&&o.some(r=>D(s,r.folder)!==null&&!r.agents.includes(s)&&!r.configs.includes(s)))}function xa(e,n,t,o){let s=er(n),r=s?.raw.join(`
33
- `)??"",i=new Map(Bn(r).map(S=>[S.key,r.split(`
34
- `).slice(S.span.from-1,S.span.to).join(`
35
- `)])),l=S=>i.has(S)?Kn(i.get(S),{lists:!0})?.[S]:void 0,a=S=>typeof l(S)=="string"?l(S):null,c={path:e,name:a("name")??q.basename(e,".md"),model:a("model"),description:a("description"),prompt:s?n.slice(s.bodyStart).trim():n.trim(),relationships:[],refused:[],configPaths:[]};s||c.refused.push({path:e,reason:"invalid"});let u=(S,y,b=!1)=>{if(/[\\:\0${}*]/.test(S)||S.startsWith("/")){c.refused.push({path:e,reason:"dynamic"});return}let E=q.normalize(q.join(q.dirname(e),S));if(D(E,t.folder)===null||E===".."||E.startsWith("../")){c.refused.push({path:E,reason:"out-of-scope"});return}if(!o.includes(E)){c.refused.push({path:E,reason:"missing"});return}if(y==="agent"&&!t.agents.includes(E)){c.refused.push({path:E,reason:"out-of-scope"});return}c.relationships.some(k=>k.path===E&&k.kind===y)||c.relationships.push({path:E,kind:y}),b&&!c.configPaths.includes(E)&&c.configPaths.push(E)},f=(S,y)=>{let b=l(S);if(b===void 0&&!i.has(S))return;let E=typeof b=="string"?[b]:Array.isArray(b)?b:[];if(!E.length||E.some(k=>typeof k!="string")){c.refused.push({path:e,reason:"dynamic"});return}for(let k of E)u(k,y,y==="config")};for(let S of["environment","policy","vault","vault_schema"])f(S,"config");f("skills","skill");let p=l("multiagent");if(p&&typeof p=="object"&&"agents"in p&&Array.isArray(p.agents))for(let S of p.agents)typeof S=="string"?u(S,"agent"):c.refused.push({path:e,reason:"dynamic"});else i.has("multiagent")&&c.refused.push({path:e,reason:"dynamic"});let m=q.basename(e,".md"),x=m.toLowerCase()==="agent",w=x?t.configs.filter(S=>q.dirname(S)===q.dirname(e)&&/\/environment\.ya?ml$/i.test(S)):t.configs.filter(S=>D(S,t.folder)?.match(/^environments\/([^/]+)\.ya?ml$/i)?.[1]===m);if(!i.has("environment")){let S=t.agents.length===1?t.configs.filter(y=>/^environments\/[^/]+\.ya?ml$/i.test(D(y,t.folder))):[];for(let y of w.length?w:S.length===1?S:[])u(q.relative(q.dirname(e),y),"config")}if(!i.has("policy")&&(x||t.agents.length===1))for(let S of t.configs.filter(y=>/(?:^|\/)policy\.ya?ml$/i.test(y)&&q.dirname(y)===(x?q.dirname(e):t.folder)))u(q.relative(q.dirname(e),S),"config");for(let S of c.prompt.matchAll(/(?:\]\(|[`\s])((?:\.\.?\/)[^\s`"'()]+\.(?:ya?ml|json|md))(?:[)`\s]|$)/g))u(S[1],/\/SKILL\.md$/i.test(S[1])?"skill":"config");return c}function ya(e){let n=/^(?:config|networking|filesystem_policy|network_policies|policy|permissions|auth|injection_location|secret_name)$/;return Un(e).some(t=>n.test(t))}function nm(e){return e==="skill"?"skill":"definition"}var Gn=class extends Error{reason;constructor(n,t){super(n==="secret"?Yn(t):n==="secret-content"?eo(t):`File was not read: ${n}.`),this.reason=n}};function _a(e){return e.CF_RESPECT_GITIGNORE!=="0"}function rr(e){return e.CF_LOCAL_SYMLINK_GUARD!=="0"}var Vn=["html"],ur=["md","json","yaml","yml",...Vn],Hn=e=>new RegExp(`\\.(?:${e.join("|")})$`,"i"),Ea=Hn(ur),ba=Hn(Vn),Oa=Hn(["ts","tsx","js","jsx","py","go","rb","java","rs","toml",...ur.filter(e=>!Vn.includes(e))]);function fr(e,n,t){return n=kt(e,n,t),Zt(n)&&ba.test(n)}function Ra(e,n,t){return n=kt(e,n,t),Zt(n)&&Ea.test(n)&&(qe(e)||!fr(e,n))}function Ia(e,n,t){return Oa.test(n)||Ra(e,n,t)}function $a(e,n,t=[]){if(!ve(e)||!n.toLowerCase().endsWith(".md"))return!1;let o=n.split("/");return o.some((s,r)=>s.toLowerCase()==="commands"&&r<o.length-1&&(o[r-1]?.toLowerCase()===ue||t.includes(o.slice(0,r).join("/"))))}function pr(e,n,t=!1){if(!qn(n,t)||$a(e,n))return!1;let o=[ue,...wt.filter(r=>r.startsWith(".")),M.cli],s="";for(let r of n.toLowerCase().split("/")){if(r.startsWith(".")&&!o.includes(r)||s===ue&&!Ge.includes(`${s}/${r}`)&&!(xt.includes(`${s}/${r}`)&&qe(e)))return!1;s=s?`${s}/${r}`:r}return!0}var Lo=/(prompt|tool|agent|config|instruction)/i,ir=/\.(md|json|ts|js|py|yaml|yml|txt)$/i,dr=/(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock|go\.sum)$|\.lock$/i,va=/(^|\/)\.?(?:credentials|secrets)$/i,mr=/(^|\/)(\.env(?:\.[^/]*)?|\.(?:npmrc|pypirc|netrc)|(?:secret|secrets|token|tokens)\.json|(?:credentials|secrets)\.(?:json|ya?ml)|secrets\.toml|[^/]+-credentials\.json|service-account[^/]*\.json|id_(?:rsa|dsa|ecdsa|ed25519)|[^/]+\.(?:pem|key|p12|pfx|tfvars|tfstate|ppk|jks|keystore))$/i,hr=new RegExp(`${mr.source}|${va.source}`,"i");function qn(e,n=!1){return!(n?mr:hr).test(e.replace(/\\/g,"/"))}function Yn(e){return`Secret file was not read: ${e}.`}function om(e,n){return n==="secret"?Yn(e):`File outside the folder was not read: ${e}.`}var gr=/(^|\/)(node_modules|dist|build|out|vendor|target|__pycache__|coverage)\/|\.min\.|\.(png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|pdf|zip|gz|jar|bin|map)$/i,Kt=new RegExp(`${gr.source}|${Eo.source}|${dr.source}|${hr.source}`,"i"),La=/\.(ts|tsx|js|jsx|mjs|cjs|py)$/i,Aa=new RegExp(`(^|/)(${mt.join("|")}|cassettes|docs|\\.github)/`,"i"),Pa=/(^|\/)([^/]*\.stories\.[^/]*|[^/]*\.d\.ts)$/i,ja=new RegExp(`(^|/)(${["test","tests","__tests__","test-support","testdata","fixtures","__fixtures__",...mt,"cassettes","mocks","__mocks__","examples","docs","\\.github"].join("|")})/`,"i"),Ma=/(^|\/)([^/]*fixture[^/]*|[^/]*\.stories\.[^/]*|test_[^/]*\.py|conftest\.py|[^/]*\.d\.ts)$/i,lr=/(^|\/)\.git\//i,Jn=(e,n,t)=>t==="github"?$e.conventionImport.fileBytes:void 0,Xn=()=>$e.codeScan.fileBytes,Ca={archive:{hidden:!1,discovery:!0,excluded:[gr,dr,lr]},listing:{hidden:!0},definition:{hidden:!0,discovery:!0,limit:Jn},skill:{hidden:!0,discovery:!0,limit:Jn},extraction:{hidden:!0,discovery:!0,accepts:(e,n)=>ir.test(n),limit:Jn},source:{hidden:!0,discovery:!0,excluded:[Kt],empty:!0,accepts:(e,n,t)=>on(e,n,t)||Ia(e,n,t),limit:(e,n,t,o)=>on(e,n,o)?void 0:fr(e,n,o)?$e.sourceFetch.htmlReferenceBytes:$e.sourceFetch.codeFileBytes},"code-scan":{hidden:!0,discovery:!0,excluded:[Kt,Aa,Pa],relativeExclusions:!0,excludeExamples:!0,accepts:(e,n)=>La.test(n)||sn(n)||ve(e)&&rn(n)&&pr(e,n),limit:Xn},"code-support":{hidden:!0,excluded:[Kt],accepts:(e,n)=>G(n)!==null,limit:Xn},pointer:{hidden:!1,limit:Xn},survey:{hidden:!0,discovery:!0,excluded:[Kt,lr],relativeExclusions:!0,accepts:(e,n)=>ir.test(n)||jo(n)==="code",limit:()=>$e.survey.fileBytes},override:{hidden:!1}};function Le(e,n,t){return xr(e,n,t,!0)}var Ta=/(?:^|\/)(?:vault\.ya?ml|(?:vaults?|auth)\/(?:credentials?|values?|tokens?)(?:\.[^/]+)?)$/i;function Na(e){let n=e.path.replace(/\\/g,"/");if(e.text===void 0||!/\.(?:ya?ml|json|md)$/i.test(n))return!1;let t=e.text,o=/(?:^|[\n{,])\s*(?:-\s*)?["']?(?:secret(?:_value)?|api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|client[_-]?secret|private[_-]?key|credentials?)["']?\s*:/gim,s=/(?:^|[\n{,])\s*(?:-\s*)?["']?[A-Z][A-Z0-9_]*(?:_KEY|_TOKEN|_PASSWORD|_SECRET)["']?\s*:/gm;return[...t.matchAll(o),...t.matchAll(s)].some(i=>!/^\s*(["']?)(?:\$\{[A-Z_][A-Z0-9_]*\}|\$[A-Z_][A-Z0-9_]*)\1[^\S\n]*(?:#[^\n]*)?(?:[,}\r\n]|$)/.test(t.slice(i.index+i[0].length)))||/["']?auth["']?\s*:/.test(t)&&/(?:^|[\n{,])\s*["']?value["']?\s*:/m.test(t)||/-----BEGIN (?:[A-Z ]*PRIVATE KEY|CERTIFICATE)-----/.test(t)}function xr(e,n,t,o){let s=D(n.path,t.root);if(s===null)return{admitted:!1,reason:"out-of-scope"};if(!qn(n.path,n.directory))return{admitted:!1,reason:"secret"};if(lt(e)&&Ta.test(n.path.replace(/\\/g,"/")))return{admitted:!1,reason:"secret"};if(lt(e)&&Na(n)&&(!t.listing||zn(e,[...t.listing.keys()],n.text===void 0?t.managedFiles:{...t.managedFiles,[n.path]:n.text}).some(u=>u.configs.includes(n.path)&&!/\/SKILL\.md$/i.test(n.path))))return{admitted:!1,reason:"secret"};let r=rr(e)&&t.gitIgnored!==void 0&&t.localTarget?.parent!==void 0&&t.localTarget.parent!==Sa(sr(t.localTarget.root,n.path));if(t.route==="local-folder"&&_a(e)&&(r||t.gitIgnored?.has(n.path)||t.localTarget&&(t.gitIgnored?.has(t.localTarget.path)||t.gitIgnored?.has(sr(t.localTarget.root,n.path)))))return{admitted:!1,reason:"excluded"};if(ar(n.path,t.exclusions)||t.route==="local-folder"&&t.localTarget&&(ar(or(t.localTarget.root,t.localTarget.path),t.exclusions)||t.localTarget.excludedTargets?.some(u=>Sr(t.localTarget.path,u))))return{admitted:!1,reason:"excluded"};if(t.exclusions?.length&&t.listing&&!t.listing.has(n.path))return{admitted:!1,reason:"excluded"};if(t.route==="local-folder"&&rr(e)&&t.localTarget){let u=or(t.localTarget.root,t.localTarget.path);if(!(t.purpose==="override"&&t.localTarget.path===t.localTarget.selectedPath)&&(u===".."||u.startsWith(`..${ka}`)||wa(u)))return{admitted:!1,reason:"out-of-scope"};if(!qn(u,n.directory))return{admitted:!1,reason:"secret"}}let i=Ca[t.purpose];if(i.discovery&&bo(e,n.path,t.root))return{admitted:!1,reason:"excluded"};if(i.hidden&&t.route!=="github"&&!pr(e,n.path,n.directory))return{admitted:!1,reason:"hidden"};if(i.hidden&&t.route==="local-folder"&&n.path.split("/").includes("node_modules"))return{admitted:!1,reason:"excluded"};let l=i.relativeExclusions?s:n.path;if(i.excluded?.some(u=>u.test(l)))return{admitted:!1,reason:"excluded"};if(t.purpose==="archive"&&ht(e)&&ko(s,n.text))return{admitted:!1,reason:"excluded"};if(i.excludeExamples){if($o(e)){if(o&&Io(n.path,{root:t.root??void 0,listing:t.listing,settings:e,key:JSON.stringify([t.root??"",t.route,...t.exclusions?.length?[t.exclusions]:[]]),readable:(u,f)=>xr(e,{path:u,size:f},{...t,localTarget:void 0},!1).admitted}))return{admitted:!1,reason:"excluded"}}else if(ja.test(l)||Ma.test(l))return{admitted:!1,reason:"excluded"}}if(i.empty&&n.size!==void 0&&n.size<=0)return{admitted:!1,reason:"empty"};if(i.accepts&&!i.accepts(e,s,t.scopes))return{admitted:!1,reason:"wrong-type"};let a=i.limit?.(e,s,t.route,t.scopes);if(a!==void 0&&n.size!==void 0&&n.size>a)return{admitted:!1,reason:"too-large"};let c=Qn(e,n.text);return c?{admitted:!1,reason:c}:{admitted:!0}}var Fa=`
36
- [The rest of this file was not read.]
37
- `;async function Da(e,n,t,o={}){let s=Le(e,n,{purpose:"override",route:"github",...o});if(!s.admitted)throw new Error(s.reason==="secret"?Yn(n.path):`File was not read: ${s.reason}.`);let r=await t(),i=Le(e,{path:n.path,text:r},{purpose:"override",route:"github",...o});if(!i.admitted)throw new Gn(i.reason,n.path);if(n.readBytes===void 0)return r;let l=Buffer.from(r,"utf8");if(l.length<=n.readBytes)return r;let a=Math.min(n.readBytes,l.length);for(;a>0&&(l[a]&192)===128;)a--;return l.subarray(0,a).toString("utf8")+Fa}var Wa=4096;function Ka(e,n,t,o={}){let s=Ut(e),r=s&&n.readBytes!==void 0?n.readBytes+Wa:void 0;return Da(e,s?n:{path:n.path},async()=>{let i=await t(r===void 0?n:{...n,readBytes:r});if(i===null)throw new Error("File is unavailable.");return r===void 0?i:Buffer.from(i.slice(0,r),"utf8").subarray(0,r).toString("utf8")},o)}function yr(e=[]){return e.map(n=>{let t=n.replace(/\\/g,"/"),o=t.endsWith("/**"),s=at.normalize(o?t.slice(0,-3):t);if(!t||s.includes("*")||s.includes("\0")||at.isAbsolute(s)||/^[A-Za-z]:/.test(s)||s===".."||s.startsWith("../"))throw new Error("Use repository-relative exclusion paths or directory trees ending in /**.");return{path:s,tree:o}})}function Sr(e,n){let t=at.normalize(e.replace(/\\/g,"/")),o=at.normalize(n.path.replace(/\\/g,"/"));return t===o||n.tree&&(o==="."?t!==".."&&!t.startsWith("../")&&!at.isAbsolute(t):t.startsWith(o.endsWith("/")?o:`${o}/`))}function ar(e,n=[]){return yr(n).some(t=>Sr(e,t))}async function sm(e,n){let t=[];for(let o of yr(e.exclusions)){let s=await n(o.path);s!==null&&t.push({...o,path:s})}return t}var cr=new WeakMap;function Ba(e,n){let t=cr.get(n);if(t?.settings===e)return n;n=t?.source??n;let o=n.admission;if(!o?.exclusions?.length&&!Ut(e))return n;let s,r=()=>s??=(n.listAll?n.listAll():n.list()).then(a=>new Set(a.map(c=>c.path))),i=async a=>{let c=await(a&&n.listAll?n.listAll():n.list());return o?.exclusions?.length?c.filter(u=>Le(e,u,{purpose:"override",route:"github",...o}).admitted):c},l={repoKey:n.repoKey,root:n.root,source:n.source,admission:o,head:()=>n.head(),linkFor:(...a)=>n.linkFor(...a),list:()=>i(!1),...n.listAll?{listAll:()=>i(!0)}:{},read:async a=>Ka(e,a,c=>n.read(c),{...o,...lt(e)?{listing:await r()}:{}})};return cr.set(l,{source:n,settings:e}),l}async function rm(e,n,t){for(let o of t){if(!o.admission?.exclusions?.length)continue;let s=n.repos?.find(c=>c.key===o.repoKey);if(!s)continue;let r=new Map(Qs(n.projectAgents,s.key).map(c=>[c.path,ct(c.sourcePath,ut(s.key))])),i=[...Object.keys(s.files??{}).map(c=>r.get(c)??c),...r.values(),...(s.selected??[]).map(c=>c.path),...(s.scan?.plan??[]).map(c=>c.path)];if(!i.length)continue;let l=Ba(e,o),a=new Set((await(l.listAll?l.listAll():l.list())).map(c=>c.path));for(let c of i)if(!Le(e,{path:c},{purpose:"override",route:"github",...o.admission,listing:a}).admitted)throw new Error("Saved files conflict with the current exclusions. Start a new analysis.")}}export{In as a,bp as b,ht as c,vo as d,ve as e,G as f,V as g,d as h,h as i,N as j,$ as k,W as l,z as m,So as n,$e as o,bo as p,ei as q,Vt as r,$o as s,gt as t,ce as u,oi as v,Sc as w,Ao as x,sn as y,wi as z,rn as A,Nc as B,er as C,Kn as D,$d as E,Bn as F,lt as G,zn as H,Cd as I,xa as J,ya as K,nm as L,Gn as M,_a as N,rr as O,ur as P,fr as Q,Ra as R,Ia as S,$a as T,pr as U,Lo as V,ir as W,dr as X,hr as Y,qn as Z,Yn as _,om as $,gr as aa,Kt as ba,La as ca,Aa as da,lr as ea,Le as fa,Fa as ga,Da as ha,Ka as ia,sm as ja,Ba as ka,rm as la,Rc as ma,M as na,yt as oa,St as pa,ii as qa,ue as ra,Qt as sa,Xe as ta,Ge as ua,xt as va,fi as wa,Ic as xa,qe as ya,mi as za,xi as Aa,kt as Ba,on as Ca,$c as Da,vc as Ea,Lc as Fa,Ac as Ga,Pc as Ha,No as Ia,H as Ja,Ye as Ka,te as La,me as Ma,Qo as Na,fs as Oa,Te as Pa,bs as Qa,Os as Ra,Rs as Sa,Tt as Ta,lp as Ua,ap as Va,cp as Wa,js as Xa,kp as Ya,Cs as Za,Wt as _a,pd as $a,Vs as ab,Hs as bb,vn as cb,Ln as db,kd as eb,Zs as fb,ma as gb,Wn as hb,_d as ib,Ed as jb,bd as kb,Nt as lb,ql as mb,Vl as nb,Hl as ob,Wp as pb,Ks as qb,Kp as rb,Bp as sb,Bs as tb,Dn as ub,ca as vb,ua as wb,fa as xb,pa as yb,da as zb};
@@ -1,14 +0,0 @@
1
- import{a as A}from"./Y7JGSUOA.js";import{d as J}from"./3MTXB4MK.js";import{j as U}from"./TDNTU4TF.js";import{a as M}from"./HTLIRVP7.js";import{a as K}from"./QDYMR6KS.js";import{b as v}from"./E7TFIHC5.js";import{c as T}from"./V7BFUTM7.js";import{b as P}from"./6YCABS5T.js";import{f as C,g as N,h as S,i as $,j as D}from"./3CKW5JIF.js";import{a as w,b as E}from"./MJGB25S5.js";import{a as L}from"./74FPPPIG.js";import{c as F}from"./FSLWD2PE.js";import{z as b}from"zod";function I(t,e){if(Buffer.byteLength(t)<=e)return t;let r=0,i=Math.min(t.length,e);for(;r<i;){let a=Math.ceil((r+i)/2);Buffer.byteLength(t.slice(0,a))<=e?r=a:i=a-1}return i>0&&/[\uD800-\uDBFF]/.test(t[i-1])&&i--,t.slice(0,i)}function G(t){let{bundleText:e}=t,r=s=>Buffer.byteLength(JSON.stringify(s));function i(s){let n=[];for(let o of s){if(r([...n,""])>4e3)break;let m=0,l=Buffer.byteLength(o);for(;m<l;){let d=Math.ceil((m+l)/2);r([...n,I(o,d)])<=4e3?m=d:l=d-1}n.push(I(o,m))}return n}function a(s,n=!1){return s.map(o=>typeof o!="string"&&o.kind==="no-core"&&n?e("analysis-check-input-1"):M([o])[0])}function p(s){let n=s.citedFiles===void 0?"":',"citedFiles":'+JSON.stringify(s.citedFiles),o=a(s.diagnostics,!0),m=s.citedFiles===void 0?o:i(o),l=[{text:'{"coreFiles":'+JSON.stringify(s.coreFiles)},{text:n+',"findings":'+JSON.stringify(s.findings)+',"diagnostics":'+JSON.stringify(m)+"}"}];return E(l,w({},{template:"check-findings"}).breakpoints)}function c(s){return Buffer.byteLength(p(s).map(n=>n.text).join(""))}return{checkDiagnosticsText:a,checkPromptBlocks:p,checkPayloadBytes:c}}function R(t,e={}){return t.length?t.map(r=>{let i=e.includeFiles===!1?"":`; files ${r.files.join(", ")||"none"}`;return`${r.ref} "${r.title}" (${r.subKind}): frozen ${r.frozen.join(", ")||"none"}; declined ${r.declined.join(", ")||"none"}${i}`}).join(`
2
- `):"none"}function O(t){let{bundleText:e}=t,r=e("analysis-scope-check-1"),i=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(o=>({unit:JSON.stringify(o.unitKey),kind:o.kind,name:JSON.stringify(o.name),location:JSON.stringify(`${o.sourcePath}:${o.sourceLine}${o.sourceEndLine?`\u2013${o.sourceEndLine}`:""}`)}))}function s(n){return e("code-finding-note",{codeSources:c(n)})}return{RULE:r,SPLIT_SCOPE_RULE:i,SUB_KIND_DEFS:a,STRUCTURE_SCOPE_RULE:p,codeSourceLabels:c,codeFindingNote:s}}import{posix as Q}from"node:path";function H(t){let{bundleText:e}=t,r=.25,i=4;function a(c){let s=new Set(c.map(l=>l.name)),n=new Map(c.map(l=>[l.name,new Set(l.skills.filter(d=>d!==l.name&&s.has(d)))])),o=new Map;for(let l of n.values())for(let d of l)o.set(d,(o.get(d)??0)+1);let m=Math.max(i,(c.length-1)*r);return c.map(l=>({name:l.name,linkedFrom:o.get(l.name)??0,linksTo:n.get(l.name).size})).filter(l=>l.linkedFrom>=m||l.linksTo>=m)}function p(c){let s=a(c);if(!s.length)return null;let n=s.map(o=>e("shape-shared-skill",o));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:r}=J(t),{sharedSkillsText:i}=H(t);function a(c){let s=new Map(c.map((n,o)=>[n.name,`s${o+1}`]));return e("shape-skills",{skills:c.map(n=>({...n,id:s.get(n.name),refs:n.references.map(o=>Q.relative(Q.dirname(n.path),o)).join(","),tools:n.tools.join(","),links:n.skills.map(o=>s.get(o)).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:i(c.skills),tools:c.tools.map(s=>({...s,skills:s.skills.join(", ")})),subAgents:c.subAgents.map(s=>({...s,tools:s.tools.join(", "),skills:a(s.skills)})),prompts:c.prompts,knowledge:c.knowledge.map(s=>({...s,headings:s.sections.map(n=>`${n.startLine}-${n.endLine} ${n.heading}`).join(`
5
- `)})),findings:r(c.findings)})}return{inventoryText:p}}function X(t){let{SPLIT_SCOPE_RULE:e}=O(t),{inventoryText:r}=W(t);function i(a){return{scopeRule:e,open:R(a.open),inventory:r(a)}}return{shapeInputs:i,SPLIT_SCOPE_RULE:e}}function j(t){let{bundleText:e}=t,r={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")}},i={untrusted_instructions:{derive:"analysis-categories-17",check:"analysis-categories-18"},better_as_code:{derive:"analysis-categories-19",check:"analysis-categories-20"}};function a(s){return F(s).map(n=>{let o=r[n];return e("category-entry",{category:n,definition:o.def,evidence:o.evidence})}).join(`
6
- `)}function p(s,n){return F(s).map(o=>{let m=i[o]?.[n];return m?`
7
-
8
- ${e(m,{promptAgreement:T(s)})}`:""}).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:r}=X(t),{templates:i}=t,{categoryBlock:a,categoryRules:p}=j(t);function c(s,n,o,m={}){if(s==="derive-shape")return{...n,...r(n.inventoryData)};if(s.startsWith("check-findings")||s==="second-opinion"){let l=e(n.checkInput),d=a(o),u=p(o,"check"),x=T(o),h={...n,promptAgreement:x,categories:d,categoryRules:u,core:l[0].text,claims:l[1].text};if(s!=="second-opinion")return h;let g;try{if(typeof n.checkTemplate!="string")throw new Error;g=$("check",o,n.checkTemplate)}catch{throw new Error("Unknown check template")}let y=typeof g=="string"&&Object.hasOwn(m,g)?m[g]:void 0;if(y?.route!=="finding_check"||y.system===void 0)throw new Error("Unknown check template");return{...h,checkSystem:v(y.system,{promptAgreement:x,categories:d,categoryRules:u},i)}}return n}return{stageInputs:c}}var V="<<<BEGIN REPOSITORY TEXT>>>",Z="<<<END REPOSITORY TEXT>>>";function B(t){let e=t;for(let r="";r!==e;)r=e,e=e.replaceAll(V,"").replaceAll(Z,"");return`${V}
10
- ${e.replaceAll("{{","{ {")}
11
- ${Z}`}function q(t,e){return{location:B(String(t.location)),text:B(String(t.text)),usage:B(t.usage===null?e.bundleText("code-check-no-usage"):String(t.usage))}}function ee(t){let{categoryBlock:e,categoryRules:r,impactBlock:i}=j(t),{codeSourceLabels:a,codeFindingNote:p,RULE:c,SPLIT_SCOPE_RULE:s,STRUCTURE_SCOPE_RULE:n,SUB_KIND_DEFS:o}=O(t),{bundleText:m}=t;function l(d,u,x){if(d==="finding-headlines")return{data:JSON.stringify(u.evidence),choiceCategories:L.join(", ")};if(d==="judge-code-prompt")return q(u,t);if(d.startsWith("derive-findings"))return{...u,promptAgreement:T(x),pass:u.pass??null,codeSources:a(u.codeSources??[]),categories:e(x),categoryRules:r(x,"derive"),impacts:i()};if(d==="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:o,scopeRule:n,open:R(g,{includeFiles:!1}),loadModes:h.map(f=>{let k=f.evidenceKind?m("load-evidence-skill-frontmatter"):f.evidence;return m("analysis-derive-structures-11",{v0:f.path,v1:f.mode,v2:f.unit??"no unit",v3:f.via,v4:k?` (${k})`:""})}).join(`
12
- `)}}if(d==="scope-items"){let h=u.scopeRuleId==="structure"?n:u.scopeRuleId==="split"?s:"";return{items:u.items??[],scopeRule:h}}if(d==="scope-findings"){let h=u.codeSources,g=u.codeFiles,y=p(h);return{...u,system:y?m("scope-system-code")+`
13
-
14
- `+y:c,code:g.length?m("code-evidence",{files:JSON.stringify(g)}):""}}return u}return{enrichRequestInputs:l,headlineFallbackQuestion:()=>t.description("finding-headlines-fallback-question")}}function te(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 r=e.templates[t.template],i=t.limits??{};if(i.maxTokens!==void 0&&(!Number.isSafeInteger(i.maxTokens)||i.maxTokens<=0))throw new Error("Invalid maxTokens");let a=v(r.prompt,t.inputs,e.includes),p=r.promptBlocks?.map(c=>({text:v(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:r.route??t.template,model:t.model,...r.system===void 0?{}:{system:v(r.system,t.inputs,e.includes)},prompt:a,...p?{promptBlocks:p}:{},schema:e.answerFormats[t.answerFormat],...i.maxTokens===void 0?{}:{maxTokens:i.maxTokens},...i.effort===void 0?{}:{effort:i.effort},...i.thinking===void 0?{}:{thinking:i.thinking}}}var _=class extends Error{name="InputBudgetError"};function Ze(t){let{templates:e,descriptions:r}=t,{withDescriptions:i}=A(t),a=U(i,t.description);function p(){let o={prompt:e["check-evidence"],promptBlocks:[{text:"{{core}}"},{text:"{{claims}}"}]},m=P({"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":{...o,system:e["check-findings"]},"check-findings-precision-v1":{...o,system:e["check-findings-precision-v1"]},"second-opinion":{...o,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(m).map(([l,d])=>[l,{...d,...d.promptBlocks?{promptBlocks:E(d.promptBlocks,w({},{template:l}).breakpoints)}:{}}]))}function c(){return{templates:p(),includes:e,answerFormats:a,descriptions:r,policy:S()}}function s(o,m={}){return oe(o,c(),m)}function n(o,m={}){let l=ne(N(o,m),c());return{...l,schema:l.schema}}return{instructionRegistry:c,analysisModelRequest:s,analysisRequest:n,buildAnalysisCall:o=>ne(o,c()),withDescriptions:i,callInputBytes:se}}function se(t){return Buffer.byteLength(t.prompt)+Buffer.byteLength(t.system??"")}function oe(t,e,r){let i=e.policy??S(),a=Object.hasOwn(S(),t.template)?D(t.template,t.answerFormat,r):t.answerFormat;if(!Object.hasOwn(i,t.template)||!i[t.template].answerFormats.includes(a))throw new Error("Unsupported template answer format");if(!Object.hasOwn(S(),t.template))return{...t,answerFormat:a,inputs:t.inputs};let p=K({templates:e.includes??{},descriptions:e.descriptions??{}}),{stageInputs:c}=Y(p),{enrichRequestInputs:s}=ee(p);return{...t,answerFormat:a,inputs:s(t.template,c(t.template,t.inputs,r,e.templates),r)}}function ne(t,e){let r=C.parse({template:t.template,inputs:t.inputs,answerFormat:t.answerFormat,model:t.model,...t.limits?{limits:t.limits}:{}}),{data:i,settings:a,maxInputBytes:p}=r.inputs,c=te(oe({...r,inputs:i},e,a),e);if(p!==void 0&&se(c)>p)throw new _("serialized evidence exceeds the priced input budget");let s=r.template==="judge-code-prompt"?b.object({path:b.string(),line:b.number()}).parse(i.at):r.template==="structure-recheck"?b.object({childId:b.string()}).parse(i):{};return{...c,...Object.hasOwn(S(),r.template)&&r.template!=="benchmark-judge"?{context:s}:{}}}export{te as a,I as b,G as c,O as d,H as e,W as f,X as g,j as h,Y as i,ee as j,_ as k,Ze as l,se as m,ne as n};
@@ -1 +0,0 @@
1
- import{z as e}from"zod";import{z as n}from"zod";var t=n.enum(["ready","needs_review","blocked"]);var i=e.enum(["high","medium","low"]),a=e.enum(["added","edited","removed"]),l=e.enum(["invokes","delegates","reads","writes","emits"]),r=e.object({nodes:e.array(e.object({id:e.string().min(1),change:a,label:e.string().nullable()})),edges:e.array(e.object({from:e.string().min(1),to:e.string().min(1),kind:l,change:a,detail:e.string().nullable()}))}),d=e.object({summary:e.string().nullable(),impact:e.string().nullable(),confidence:i.nullable(),objective:e.string().nullable(),status:t.nullable(),blockedBy:e.string().nullable(),alsoFixes:e.array(e.string()).default([]),delta:r.nullable()});export{t as a,i as b,a as c,l as d,r as e,d as f};