@counterfact-labs/cli 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/bundle/client-release.json +1 -1
  2. package/dist/adapters/analysis-results.js +87 -0
  3. package/dist/adapters/combined-results.js +27 -0
  4. package/dist/adapters/entry-files.js +5 -2
  5. package/dist/adapters/entry-packing.js +161 -0
  6. package/dist/adapters/entry-selection.js +13 -1
  7. package/dist/adapters/files.js +110 -5
  8. package/dist/adapters/git.js +10 -1
  9. package/dist/adapters/relay-plan.js +5 -7
  10. package/dist/adapters/release.js +4 -1
  11. package/dist/adapters/results.js +9 -2
  12. package/dist/adapters/selection.js +19 -9
  13. package/dist/adapters/settings.js +37 -6
  14. package/dist/adapters/source-relay-plan.js +7 -0
  15. package/dist/analysis-core/analysis/code-agents/skipped-files.js +1 -1
  16. package/dist/analysis-core/analysis/file-analysis-plan.js +1 -0
  17. package/dist/analysis-core/analysis/file-dependencies.js +1 -0
  18. package/dist/analysis-core/analysis/finding-activity-switch.js +1 -0
  19. package/dist/analysis-core/analysis/finding-identity.js +1 -0
  20. package/dist/analysis-core/analysis/finding-quality/policy.js +1 -0
  21. package/dist/analysis-core/analysis/folder-analysis-plan.js +1 -0
  22. package/dist/analysis-core/analysis/passes/full-file-passes.js +1 -0
  23. package/dist/analysis-core/analysis/project-architecture.js +1 -0
  24. package/dist/analysis-core/analysis/schemas.js +1 -1
  25. package/dist/analysis-core/chunks/2AASSZRO.js +35 -0
  26. package/dist/analysis-core/chunks/2YREYGOG.js +1 -0
  27. package/dist/analysis-core/chunks/33HRXJ5Q.js +1 -0
  28. package/dist/analysis-core/chunks/33IGHOYT.js +1 -0
  29. package/dist/analysis-core/chunks/4PT5C4IT.js +7 -0
  30. package/dist/analysis-core/chunks/4RXRAB5S.js +1 -0
  31. package/dist/analysis-core/chunks/4UDQBDDE.js +1 -0
  32. package/dist/analysis-core/chunks/{6RWEWBHK.js → 5B5UCWD3.js} +1 -1
  33. package/dist/analysis-core/chunks/6YCABS5T.js +1 -0
  34. package/dist/analysis-core/chunks/CQQ4TTXE.js +1 -0
  35. package/dist/analysis-core/chunks/CTLHKFPH.js +19 -0
  36. package/dist/analysis-core/chunks/F54DOWKN.js +6 -0
  37. package/dist/analysis-core/chunks/FRXOQ2M6.js +3 -0
  38. package/dist/analysis-core/chunks/HCPO6QPU.js +1 -0
  39. package/dist/analysis-core/chunks/HHFDNY6V.js +14 -0
  40. package/dist/analysis-core/chunks/{FBTOOUPL.js → HVQJKPQ4.js} +1 -1
  41. package/dist/analysis-core/chunks/INVTU73D.js +1 -0
  42. package/dist/analysis-core/chunks/JEWBPIQI.js +1 -0
  43. package/dist/analysis-core/chunks/JGK37AWN.js +1 -0
  44. package/dist/analysis-core/chunks/LFYTD7JF.js +1 -0
  45. package/dist/analysis-core/chunks/LMUXOKIM.js +1 -0
  46. package/dist/analysis-core/chunks/LOBIDUCA.js +1 -0
  47. package/dist/analysis-core/chunks/M5YWJY7P.js +1 -0
  48. package/dist/analysis-core/chunks/MGVIKA74.js +1 -0
  49. package/dist/analysis-core/chunks/MKYLK6DB.js +1 -0
  50. package/dist/analysis-core/chunks/MZOKZ3N6.js +1 -0
  51. package/dist/analysis-core/chunks/NXHVBJL4.js +1 -0
  52. package/dist/analysis-core/chunks/OKBK3JL3.js +1 -0
  53. package/dist/analysis-core/chunks/PBHHWFR6.js +1 -0
  54. package/dist/analysis-core/chunks/Q5WR6B2H.js +2 -0
  55. package/dist/analysis-core/chunks/QVXARKP7.js +1 -0
  56. package/dist/analysis-core/chunks/RQTNTIR4.js +1 -0
  57. package/dist/analysis-core/chunks/{RNTMH4MU.js → S27Y2TP5.js} +1 -1
  58. package/dist/analysis-core/chunks/SJESFYBA.js +10 -0
  59. package/dist/analysis-core/chunks/SP6XFHNH.js +1 -0
  60. package/dist/analysis-core/chunks/VDUFPTDD.js +1 -0
  61. package/dist/analysis-core/chunks/W24SFYZM.js +67 -0
  62. package/dist/analysis-core/chunks/YTHF2E2S.js +1 -0
  63. package/dist/analysis-core/chunks/YWL52FVW.js +2 -0
  64. package/dist/analysis-core/contracts/analysis-selection.js +1 -1
  65. package/dist/analysis-core/contracts/analysis-size.js +1 -0
  66. package/dist/analysis-core/contracts/execution-request.js +1 -0
  67. package/dist/analysis-core/contracts/intake-finding.js +1 -0
  68. package/dist/analysis-core/contracts/model-call-identity.js +1 -0
  69. package/dist/analysis-core/contracts/relay-analysis.js +1 -1
  70. package/dist/analysis-core/contracts/requests.js +1 -1
  71. package/dist/analysis-core/conventions/analysis-fit.js +1 -1
  72. package/dist/analysis-core/conventions/file-admission.js +1 -1
  73. package/dist/analysis-core/conventions/read-limits.js +1 -0
  74. package/dist/analysis-core/import/calls/modules.js +1 -1
  75. package/dist/analysis-core/import/entry-selection.js +1 -0
  76. package/dist/analysis-core/import/outside-loader-sources.js +1 -1
  77. package/dist/analysis-core/index.js +3 -3
  78. package/dist/analysis-core/requests/answer-formats.js +1 -1
  79. package/dist/analysis-core/requests/local-plan.js +1 -1
  80. package/dist/analysis-core/requests/planned-limits.js +1 -0
  81. package/dist/analysis-core/requests/registry.js +1 -1
  82. package/dist/analysis-core/requests/template-version.js +1 -1
  83. package/dist/analysis-core/requests/tools.js +1 -1
  84. package/dist/analysis-core/settings.js +1 -1
  85. package/dist/analysis-core/stages/engine-entry.js +1 -1
  86. package/dist/bundle/seal/engine.js +1 -1
  87. package/dist/cli/analysis-selection.js +47 -5
  88. package/dist/cli/api.js +1 -1
  89. package/dist/cli/commands/analyze.js +58 -15
  90. package/dist/cli/commands/skipped.js +65 -0
  91. package/dist/cli/context.js +2 -1
  92. package/dist/cli/finding-display.js +102 -7
  93. package/dist/cli/finding-settings.js +3 -1
  94. package/dist/cli/intake-payload.js +26 -2
  95. package/dist/cli/main.js +21 -7
  96. package/dist/cli/mcp-failure.js +6 -5
  97. package/dist/cli/mcp.js +134 -28
  98. package/dist/cli/relay-check.js +107 -23
  99. package/dist/cli/relay-failure.js +4 -4
  100. package/dist/cli/relay-preparation.js +50 -12
  101. package/dist/cli/result-check.js +31 -12
  102. package/dist/cli/saved-results.js +10 -0
  103. package/dist/cli/scope-choices.js +3 -3
  104. package/dist/cli/sign-in.js +2 -2
  105. package/dist/cli/skipped-files.js +22 -0
  106. package/dist/cli/summary.js +15 -1
  107. package/dist/contract/agent-choice.js +25 -2
  108. package/dist/contract/cli-api-messages.js +3 -0
  109. package/dist/contract/cli-refusals.js +31 -5
  110. package/dist/contract/cli-version.js +1 -1
  111. package/dist/contract/console-url.js +3 -0
  112. package/dist/contract/console.js +17 -38
  113. package/dist/contract/engine.js +1 -1
  114. package/dist/contract/messages.js +4 -3
  115. package/dist/contract/project-architecture.js +1 -0
  116. package/dist/contract/scope-choice.js +31 -11
  117. package/dist/contract/selection-offer.js +5 -8
  118. package/dist/gatekeeper/cli-api.js +70 -4
  119. package/dist/gatekeeper/console.js +19 -3
  120. package/dist/gatekeeper/model.js +5 -23
  121. package/dist/gatekeeper/trust/policy.js +2 -1
  122. package/package.json +4 -2
  123. package/dist/analysis-core/analysis/source-notes/types.js +0 -1
  124. package/dist/analysis-core/chunks/2PSNOSJ2.js +0 -1
  125. package/dist/analysis-core/chunks/2PZF54KH.js +0 -10
  126. package/dist/analysis-core/chunks/6B2HILSY.js +0 -1
  127. package/dist/analysis-core/chunks/6U2IR4XB.js +0 -1
  128. package/dist/analysis-core/chunks/7NEWZ74F.js +0 -1
  129. package/dist/analysis-core/chunks/CGCJN73D.js +0 -14
  130. package/dist/analysis-core/chunks/CWYVUGG4.js +0 -1
  131. package/dist/analysis-core/chunks/FSLWD2PE.js +0 -1
  132. package/dist/analysis-core/chunks/GOQVKWP3.js +0 -32
  133. package/dist/analysis-core/chunks/IHAVDX4L.js +0 -66
  134. package/dist/analysis-core/chunks/IVULXWQN.js +0 -21
  135. package/dist/analysis-core/chunks/K2GNDX3W.js +0 -1
  136. package/dist/analysis-core/chunks/K5FUABWW.js +0 -1
  137. package/dist/analysis-core/chunks/KGQYR62R.js +0 -7
  138. package/dist/analysis-core/chunks/KWECQJ6X.js +0 -1
  139. package/dist/analysis-core/chunks/PY5M22CL.js +0 -1
  140. package/dist/analysis-core/chunks/PYKAERZZ.js +0 -1
  141. package/dist/analysis-core/chunks/SKVEBOGA.js +0 -1
  142. package/dist/analysis-core/chunks/SLJ6CW7W.js +0 -1
  143. package/dist/analysis-core/chunks/UEORNVQB.js +0 -1
  144. package/dist/analysis-core/chunks/WYLIV2P2.js +0 -1
  145. package/dist/analysis-core/data/finding-types.js +0 -1
@@ -1 +0,0 @@
1
- import{A as Z,B as st,C as at,D as rt,E as it,F as E,G as lt,H as dt,I as pt,J as ct,P as ft,R as mt,V as ht,W as ut,a as ae,b as De,c as Ge,d as We,e as $e,f as V,g as re,h as _,i as Ye,ia as gt,j,k as z,ka as Pt,l as Je,la as wt,m as Ve,ma as kt,n as Qe,na as St,o as K,p as Xe,q as Ze,r as ie,s as Q,t as et,u as tt,v as I,w as le,x as X,y as ot,z as nt}from"./IHAVDX4L.js";import{a as qe}from"./6RWEWBHK.js";import{a as J}from"./QDYMR6KS.js";import{a as Ue}from"./4H23CSUM.js";import{i as He}from"./K2GNDX3W.js";import{a as Ne}from"./FBTOOUPL.js";import{J as Ke,M as T,e as xe,f as A,g as Be,h as Ie,i as Le,m as Te,o as M,p as _e,q as je,v as Y,x as ze}from"./IVULXWQN.js";import{d as Me,f as Ae}from"./K5FUABWW.js";import{a as B}from"./326F4XNG.js";import{c as se}from"./MJGB25S5.js";import{n as $}from"./KGQYR62R.js";import{b as L,c as U}from"./2PSNOSJ2.js";import{Fb as Ce,I as ne,Ta as W,U as D,X as Re,Y as Ee,aa as G,e as Se,n as x,qa as k,sb as Oe,va as ye,z as Fe}from"./GOQVKWP3.js";import{a as ve}from"./2PZF54KH.js";import{f as oe,i as ge,j as Pe,m as we,n as ke}from"./JKWTHRUR.js";import{b as ue}from"./724WZMYW.js";import{c as be,e as O}from"./C6X5GDG4.js";import{posix as Kt}from"node:path";function bt(n,e,s){let a=new Set(e.entries.map(i=>i.path)),t=new Set(D(n,[...a])),f=Object.fromEntries(Object.entries(e.files).filter(([i])=>e.selected.some(o=>o.path===i&&o.readBytes===void 0))),r=new Set(Ee(n,[...a],f)),c=[],d=new Set;return{read:async i=>{if(r.has(i.path)||e.managedReadPaths?.includes(i.path)&&e.files[i.path]===void 0)return e.refused.push({path:i.path,reason:"unreadable"}),null;c.push(i);try{let o=await s(i);if(o!==null){if(d.has(i.path)){let l=k(n,{path:i.path,size:Buffer.byteLength(o),text:o},{...e.admission,purpose:"skill",route:"github",root:e.root,listing:a,managedFiles:e.files});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}if(x(n)||ue(n)){let l=k(n,{path:i.path,text:o},{...e.admission,purpose:"override",route:"github",root:e.root,listing:a,managedFiles:e.files});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}if(e.phase==="manifest"){let l=k(n,{path:i.path,size:Buffer.byteLength(o)},{...e.admission,purpose:"pointer",route:"github",root:e.root});if(!l.admitted)return e.refused.push({path:i.path,reason:l.reason}),null}return o}}catch(o){if(o instanceof G&&(o.reason==="secret-content"||x(n)||d.has(i.path)||t.has(i.path)))return e.refused.push({path:i.path,reason:o.reason}),null;if(e.profile==="hosted-import"&&!d.has(i.path)&&!t.has(i.path))throw o}return e.refused.push({path:i.path,reason:"unreadable"}),null},requestedReads:c,skillReads:d}}import{createHash as zt}from"node:crypto";function de(n){return zt("sha256").update(JSON.stringify(n.map(({path:e,ref:s,size:a})=>({path:e,ref:s,size:a})))).digest("hex")}function vt(n,e,s){return T(n)?{settings:Ae(n),commit:s??de(e),revisionKind:s===void 0?"listing":"commit",completed:[]}:void 0}function Ft(n,e,s){let a=n.agentPages;if(!a)return;let t=s??a.listingEntries??n.entries,f=a.revisionKind??(a.commit===de(a.listingEntries??n.entries)?"listing":"commit");if(f==="commit"&&e!==void 0&&a.commit!==e||f==="listing"&&a.commit!==de(t))throw new Error("stale-agent-page");return a.commit}function Rt(n,e,s){e.ranked??=Q(n,e.scan,new Map);let a=new Map([...ie(e.scan.plan),...Object.entries(e.agentPages?.actualSizes??{})]),t=ae(n,e.ranked,a,new Map,{files:{},...e.agentPages?{page:{commit:e.agentPages.commit,scope:e.root,continuation:s}}:{}});t.page&&(e.ranked={...e.ranked,agentPage:t.page,strong:t.strong,possible:t.window,notRead:t.notRead,notReadMore:t.notReadMore});let f=[...t.refused,...e.ranked.skippedFiles??[]];if(e.requestedPaths.push(...f.map(r=>r.path)),e.refused.push(...f),e.profile==="hosted-import"&&t.paths.length||t.page){let r=tt(n,[],t.paths,e.scan.plan);e.refused.push(...r.refused),e.profile==="hosted-import"?at(e,r.selected):(nt(n,e),Z(e,r.selected))}else X(n,e,t.paths,e.scan.plan);e.phase=e.selected.length?"files":"done"}function Et(n,e,s,a){let t={...e.agentPages.actualSizes};s.forEach((o,l)=>{a[l]!==null&&(t[o.path]=Buffer.byteLength(a[l]))}),e.agentPages={...e.agentPages,actualSizes:t};let f=new Map([...ie(e.scan.plan),...Object.entries(t)]),r=new Map(Object.entries(e.files).map(([o,l])=>[o,Buffer.byteLength(l)])),c=new Set(e.skillReferencePaths),d=new Set([...e.conventionPaths,...st(e),...c,...e.markerPath?[e.markerPath]:[]]);for(let o of s)if(d.has(o.path)&&t[o.path]!==void 0){let l=k(n,{path:o.path,size:t[o.path]},{purpose:c.has(o.path)?"skill":"pointer",route:"github",root:e.root,listing:new Set(e.entries.map(u=>u.path)),managedFiles:e.files}),p=ze(r).left+(r.get(o.path)??0);l.admitted&&t[o.path]<=p?r.set(o.path,t[o.path]):e.refused.push({path:o.path,reason:l.admitted?"total":l.reason})}let m=ae(n,e.ranked,f,r),i=new Set(m.paths);s.forEach((o,l)=>{a[l]!==null&&(i.has(o.path)||d.has(o.path)&&r.has(o.path)?e.files[o.path]=a[l]:e.refused.push(m.refused.find(p=>p.path===o.path)??m.skippedFiles?.find(p=>p.path===o.path)??{path:o.path,reason:"total"}))}),e.ranked={...e.ranked,agentPage:m.page,strong:m.strong,possible:m.window}}function pe(n){let e=n.ranked,s=e?.agentPage;if(!s||n.phase!=="done")return;let a=[...e.agentInventory.strong,...e.agentInventory.possible],t=new Set(s.selected),f=new Set(s.refusals.map(d=>d.id)),r=a.filter(d=>t.has(W(d.prompt))&&!f.has(W(d.prompt))&&n.files[d.prompt.path]===void 0),c=[...s.refusals,...r.map(d=>({id:W(d.prompt),reason:n.refused.find(m=>m.path===d.prompt.path)?.reason??"missing"}))];n.ranked={...e,strong:e.strong.filter(d=>n.files[d.prompt.path]!==void 0),possible:e.possible.filter(d=>n.files[d.prompt.path]!==void 0),agentPage:{...s,refusals:c,partial:c.length>0,estimatedInputBytes:Object.values(n.files).reduce((d,m)=>d+Buffer.byteLength(m),0)}}}async function yt(n,e,s){if(!x(n))return!1;let a=Re(n,e.entries.map(o=>o.path));if(!a.length)return!1;let t=new Set(a.flatMap(o=>o.agents)),f=new Map(e.selected.map(o=>[o.path,o])),r=new Set(e.selected.filter(o=>o.readBytes===void 0&&e.files[o.path]!==void 0).map(o=>o.path));e.managedReadPaths||(e.managedReadPaths=[],(e.scan||e.ranked)&&(delete e.scan,delete e.ranked,delete e.manifestReadPaths,e.phase!=="marker"&&(e.phase="scan")));let c=new Set([...e.managedReadPaths,...r]),d=e.entries.filter(o=>t.has(o.path)&&f.has(o.path)&&!c.has(o.path)),m=d.slice(0,I);if(!m.length)return!1;let i=await B(m,4,async o=>{let l=k(n,o,{...e.admission,purpose:"pointer",route:"github",root:e.root});return l.admitted?s(o):(e.refused.push({path:o.path,reason:l.reason}),null)});if(m.forEach((o,l)=>{i[l]!==null&&(e.files[o.path]=i[l],e.selected=e.selected.map(p=>p.path===o.path?o:p))}),e.managedReadPaths.push(...m.map(o=>o.path)),d.length>m.length){for(let o of Object.keys(e.files))!t.has(o)&&a.some(l=>be(o,l.folder)!==null)&&delete e.files[o];e.cursor=0,(e.phase==="done"||e.phase==="manifest")&&(e.phase="files")}return!0}async function Ot(n,e,s){if(e.marketplacePlanned)return!1;let a=new Set(D(n,e.entries.map(o=>o.path)));if(!e.selected.some(o=>a.has(o.path)))return!1;let t=new Set(e.marketplaceReadPaths),r=e.selected.filter(o=>a.has(o.path)&&!t.has(o.path)).slice(0,I),c=await B(r,4,async o=>{let l=k(n,o,{...e.admission,purpose:"definition",route:"github",root:e.root});if(!l.admitted)return e.refused.push({path:o.path,reason:l.reason}),null;let u=(o.readBytes===void 0?e.files[o.path]:void 0)??await s({path:o.path,size:o.size,ref:o.ref});if(u===null)return null;let g=k(n,{path:o.path,size:Buffer.byteLength(u),text:u},{...e.admission,purpose:"definition",route:"github",root:e.root});return g.admitted?u:(e.refused.push({path:o.path,reason:g.reason}),null)});r.forEach((o,l)=>{c[l]!==null?e.files[o.path]=c[l]:delete e.files[o.path]}),e.marketplaceReadPaths=[...t,...r.map(o=>o.path)];let d=new Map(r.flatMap((o,l)=>c[l]===null?[]:[[o.path,Buffer.byteLength(c[l])]]));e.agentPages&&d.size&&(e.agentPages={...e.agentPages,listingEntries:e.agentPages.listingEntries??e.entries}),e.entries=e.entries.map(o=>d.has(o.path)?{...o,size:d.get(o.path)}:o);let m,i=e.marketplaceSelection?new Set(e.marketplaceSelection):void 0;do{let o=new Set(e.marketplaceReadPaths.filter(h=>e.files[h]===void 0)),l=e.entries.filter(h=>!o.has(h.path)&&(!i||i.has(h.path))),p=e.profile==="local-analysis"?Be(n,l,e.root,{files:e.files}):_e(n,l,e.root,{files:e.files,mode:e.marketplaceMode}),u="selected"in p?p.selected.map(h=>h.path):p.selectedPaths,g=new Set(u),P=new Map(l.map(h=>[h.path,h]));e.selected=u.map(h=>P.get(h)),e.selectionRefused=p.refused,e.hosted&&"selectedPaths"in p&&(e.hosted.fallback=p,e.hosted.codeMode||(e.hosted.needsExtraction=p.needsExtraction)),m=Object.keys(e.files).filter(h=>a.has(h)&&!g.has(h));for(let h of m)e.refused.push(p.refused.find(w=>w.path===h)??{path:h,reason:"total"});for(let h of Object.keys(e.files))g.has(h)||delete e.files[h]}while(m.length);return e.conventionPaths=$(n,e.entries.filter(o=>!a.has(o.path)||e.files[o.path]!==void 0).map(o=>o.path),e.root,{files:e.files}).files.filter(o=>o.role!=="reference").map(o=>o.path),e.cursor=0,e.marketplacePlanned=!e.selected.some(o=>a.has(o.path)&&!e.marketplaceReadPaths.includes(o.path)),r.length>0||!e.marketplacePlanned}function ce(n,e){let{plan:s,entries:a}=e,t=s.profile==="local-analysis"?s.context.dir??"":e.root??"",f=s.readers.find(i=>i.id==="marker")?.claim.wants[0],r=s.readers.some(i=>i.id==="code-scan"),c=new Map(a.map(i=>[i.path,i])),d=s.profile==="local-analysis"?s.selection.selected:s.selection.selectedPaths.flatMap(i=>c.has(i)?[c.get(i)]:[]),m=Te(n)?M(n,{phase:"start",root:t,paths:a.map(i=>i.path),scanFlag:!!f||r}):void 0;return{...T(n)?{agentPages:vt(n,a,e.commit)}:{},version:1,profile:s.profile,root:t,entries:a,selected:[...d],..."mode"in s?{marketplaceMode:s.mode}:{},..."selectionPaths"in s?{marketplaceSelection:s.selectionPaths}:{},conventionPaths:s.profile==="hosted-import"||T(n)?$(n,a.map(i=>i.path),t).files.filter(i=>i.role!=="reference").map(i=>i.path):[],...e.admission?{admission:e.admission}:{},selectionRefused:s.selection.refused,requestedPaths:[],refused:[],files:{},cursor:0,treeTruncated:e.treeTruncated??!1,...s.profile==="hosted-import"?{hosted:{fallback:structuredClone(s.selection),weakCodeFallback:n.CF_IMPORT_WEAK_CODE_FALLBACK!=="0",codeMode:!1,needsExtraction:s.selection.needsExtraction}}:{},decision:m??(f?{kind:"marker",markerPath:f,scanIfBare:r}:{kind:"settled",markerPath:null,markerKind:null,scan:r}),phase:f?"marker":r?"scan":"files"}}async function Ct(n,e,s){if(e.version!==1)throw new Error("unsupported-import-checkpoint");e.agentPages&&(n=e.agentPages.settings,Ft(e,s.commit));let a=le(n,e.profile),t={...e,selected:[...e.selected],files:{...e.files},requestedPaths:[...e.requestedPaths],refused:[...e.refused],...e.hosted?{hosted:{...e.hosted}}:{},...e.managedReadPaths?{managedReadPaths:[...e.managedReadPaths]}:{}},{read:f,requestedReads:r,skillReads:c}=bt(a,t,o=>s.read(o));if(await Ot(a,t,f))return E(a,t,r);if(await yt(a,t,f))return E(a,t,r);if(it(a,t),t.phase==="done")return s.resolvedCode&&rt(t,s.resolvedCode),E(a,t,r);if(t.phase==="manifest")return await lt(a,t,f),pe(t),E(a,t,r);if(t.phase==="marker"&&t.decision.kind==="marker"){let o=t.decision,l=o.markerPath,p=t.entries.find(g=>g.path===l);if(t.profile==="hosted-import"){let g=k(a,p,{purpose:"pointer",route:"github",root:t.root});if(!g.admitted)return t.refused.push({path:l,reason:g.reason}),t.decision={kind:"settled",markerPath:null,markerKind:null,scan:o.scanIfBare},t.phase=o.scanIfBare?"scan":"files",E(a,t,r)}X(a,t,[l],t.entries);let u=await f(p);if(u!==null&&(t.files[l]=u),t.decision=M(a,{phase:"read",pending:o,text:u}),t.markerPath=l,t.markerKind=t.decision.markerKind,t.markerKind!=="bare"){let g=t.profile==="hosted-import"?await s.listing():{entries:t.entries,truncated:!1};t.treeTruncated||=g.truncated;let P=await dt(a,{config:Le(u).config,markerDir:l.split("/").slice(0,-1).join("/"),selected:t.profile==="hosted-import"?[]:t.selected,admission:{...t.admission,root:t.root||void 0},modelReader:!1,priorRefused:t.refused,refusalMode:"append",requestedMode:"kept-and-refused",listing:async()=>g.entries});if(t.requestedPaths.push(...P.requestedPaths),t.refused=P.refused,t.agentPages&&P.selected){let h=new Set(P.requestedPaths);t.conventionPaths=[...new Set([...t.conventionPaths,...P.selected.filter(w=>h.has(w.path)).map(w=>w.path)])]}t.profile==="hosted-import"?Z(t,P.selected??[]):P.selected&&(t.selected=P.selected)}if(t.phase=t.decision.scan?"scan":"files",t.profile!=="hosted-import"||t.markerKind!=="bare"||t.decision.scan)return E(a,t,r)}if(t.phase==="scan"){if(!t.scan){let o=Qe(a,t.entries,t.root,!0,t.decision.kind==="settled"?t.decision.scanPaths:void 0);t.scan=o.state,t.refused.push(...o.refused)}if(!K(t.scan)){let o=await et(a,t.scan,f,{modelReader:!1,alreadyRead:new Map,size:{batch:Je,parallel:4}});t.scan=o.scan,o.selection&&(t.ranked=o.selection.ranked)}return K(t.scan)&&Rt(a,t),E(a,t,r)}if(ne(a))for(let o of t.skillReferencePaths??[])c.add(o);let d=t.selected.slice(t.cursor,t.cursor+I),m=d.filter(o=>t.files[o.path]===void 0),i=await B(m,4,f);if(t.agentPages&&t.ranked&&t.scan?Et(a,t,m,i):m.forEach((o,l)=>{i[l]!==null&&(t.files[o.path]=i[l])}),t.cursor+=d.length,ne(a)){let o=Object.fromEntries(Object.entries(t.files).filter(([h])=>t.selected.some(w=>w.path===h&&w.readBytes===void 0))),l=je(a,{entries:t.entries,selected:t.selected,files:o,root:t.root,admission:t.admission,referencePaths:t.skillReferencePaths});t.refused=L(t.refused,l.refused);for(let h of l.refused)c.has(h.path)&&delete t.files[h.path];if(t.cursor<t.selected.length)return E(a,t,r);let p=new Map(t.selected.map(h=>[h.path,h])),u=l.paths.filter(h=>!p.has(h)||p.get(h).readBytes!==void 0),g=new Set(u.filter(h=>p.has(h)));t.cursor-=t.selected.slice(0,t.cursor).filter(h=>g.has(h.path)).length,t.selected=t.selected.filter(h=>!g.has(h.path));for(let h of g)delete t.files[h];t.requestedPaths.push(...u),u.length&&(t.skillReferencePaths=[...t.skillReferencePaths??[],...u]);let P=new Map(t.entries.map(h=>[h.path,h]));t.selected.push(...u.map(h=>{let w=P.get(h);return{path:h,size:w.size,ref:w.ref}})),ot(t,u,"fallback")}return t.cursor>=t.selected.length&&(t.phase=xe(a)&&t.ranked||x(a)?"manifest":"done"),pe(t),E(a,t,r)}async function ee(n,e){let s=ce(n,e),a;do a=await Ct(n,s,{listing:async()=>({entries:e.entries,truncated:!1}),read:e.read}),s=a.state;while(s.phase!=="done");let t={};return s.markerPath!==void 0&&(t.markerPath=s.markerPath,t.markerKind=s.markerKind),s.ranked!==void 0&&(t.ranked=s.ranked,t.scan=s.scan),{files:a.files,settled:a.settled,skippedFiles:a.refused,...t}}function Nt(n){return n.CF_IMPORT_PROPOSAL!=="0"}var Ht=new Set(["secret","secret-content","out-of-scope"]);async function qt(n,e,s,a,t,f,r){let c={...e.admission,purpose:"proposal",route:"local-folder"},d=k(n,a??{path:s},c);if(!d.admitted)return{reason:d.reason};if(!a)return{reason:r??"missing"};if(a.size>f)return{reason:"allowance"};try{let m=t??await(e.proposalRead??e.read)({...a,readBytes:void 0});if(m===null)return{reason:r??"unreadable"};let i=Buffer.byteLength(m),o=k(n,{path:s,size:i,text:m},c);return o.admitted?i>f?{reason:"allowance"}:{text:m}:{reason:o.reason}}catch(m){return m instanceof G?{reason:m.reason,invalidates:Ht.has(m.reason)}:{reason:"unreadable"}}}async function Ut(n,e,s,a,t){let f=new Set(a.map(p=>p.path)),r=new Set(t.map(p=>p.path)),c=new Map(e.entries.map(p=>[p.path,p])),d=a.map(p=>({...c.get(p.path),readBytes:void 0})),m=p=>!f.has(p.path)&&!r.has(p.path),i=[...e.selection.selected.filter(m),...d],o=a.length||t.length?{...e.selection,selected:i,totalBytes:i.reduce((p,u)=>p+(u.readBytes??u.size),0),refused:e.selection.refused.filter(p=>!f.has(p.path))}:e.selection,l=e.evidence??{};if(t.length){let p=e.entries.filter(w=>!r.has(w.path)),{ranked:u,scan:g,markerPath:P,markerKind:h}=await ee(n,{entries:p,admission:e.admission,read:async w=>Object.hasOwn(s,w.path)?s[w.path]:null,plan:Y(n,{profile:"local-analysis",listing:p,selection:o})});l={ranked:u,scan:g,markerPath:P,markerKind:h}}return{...l,files:s,selection:o,settled:[...e.settled.filter(m),...d],skippedFiles:(e.skippedFiles??[]).filter(p=>!f.has(p.path)),...t.length?{invalidated:t}:{}}}async function xt(n,e){if(!Nt(n)||!e.proposal)return;let s={...e.files},a=new Map(e.entries.map(o=>[o.path,o])),t=new Map(e.unavailable?.map(o=>[o.path,o.reason])),f={},r=[],c=[],d=new Set,m=new Set(e.settled.filter(o=>o.readBytes===void 0).map(o=>o.path)),i=Object.values(s).reduce((o,l)=>o+Buffer.byteLength(l),0);for(let o of e.proposal.files){let l=Kt.normalize(o.path.replace(/\\/g,"/")),p=Object.hasOwn(s,l)?Buffer.byteLength(s[l]):0,u=!e.proposalRead&&m.has(l)&&Object.hasOwn(s,l)?s[l]:void 0,g=d.has(l)?{reason:"duplicate"}:await qt(n,e,l,a.get(l),u,Fe.codeAgent.importBytes-i+p,t.get(l));if(d.add(l),"text"in g)i+=Buffer.byteLength(g.text)-p,s={...s,[l]:g.text},c.push({...o,path:l});else{let P=g.reason==="wrong-type"?"coding-guide":g.reason;f[P]=(f[P]??0)+1,g.invalidates&&Object.hasOwn(s,l)&&(i-=p,delete s[l],r.push({path:l,reason:g.reason}))}}return{...await Ut(n,e,s,c,r),proposal:{...e.proposal,files:c},rejectedByReason:f}}import{posix as fe}from"node:path";function Dt(n,e={}){return(n.CF_CHOOSE_AGENT??e.CF_CHOOSE_AGENT)!=="0"}function At(n,{codeAgents:e,conventions:s,root:a,selection:t}){if(t?.kind==="file"||Se(n)||!Dt(n))return;let f=new Set(e.map(i=>i.prompt.path)),r=new Map(s.agentScopes?.map(i=>[i.key,i.folder])),c=Gt(e);if(c.push(...s.agents.flatMap(i=>Ke(i)?(i.definitionPaths??[]).filter(o=>i.key===null||!f.has(o)).map(o=>({folder:Wt(i,o,r,a),reason:o})):[])),c.some(i=>c.every(o=>Mt(i.folder,o.folder))))return;let m=c.filter((i,o)=>!c.some((l,p)=>p!==o&&Mt(l.folder,i.folder)&&(l.folder!==i.folder||p<o)));return{kind:m.length?"choose_agent":"no_agent",candidates:m}}function Mt(n,e){return n==="."||e===n||e.startsWith(`${n}/`)}function te(n){let e=fe.dirname(n[0]);for(let s of n.slice(1))for(;e!=="."&&s!==e&&!s.startsWith(`${e}/`);)e=fe.dirname(e);return e}function Gt(n){let e=n.map(()=>new Set),s=new Map(n.map((r,c)=>[r.unitKey,c])),a=new Map,t=(r,c)=>{c!==void 0&&(e[r].add(c),e[c].add(r))};n.forEach((r,c)=>{t(c,a.get(r.prompt.path)),a.set(r.prompt.path,c);for(let d of r.links??[])t(c,s.get(d.to))});let f=new Set;return n.flatMap((r,c)=>{if(f.has(c))return[];let d=[c],m=[];for(;d.length;){let i=d.pop();f.has(i)||(f.add(i),m.push(n[i].prompt.path,...n[i].ownFiles.map(o=>o.path)),d.push(...e[i]))}return[{folder:te(m),reason:r.prompt.path}]})}function Wt(n,e,s,a){return n.key!==null?s.get(n.key)||fe.dirname(e):(s.get(null)??a)||"."}function Bt(n,e=[],s){return e.find(a=>Ge(a.key,s)===n.id)?.folder??te(n.files.length?n.files.map(a=>a.path):[n.sourceRef?.path??"."])}function $t(n,e,s,a){let t=new Set(n.flatMap(c=>c.files.map(d=>d.path))),f=new Set(e.flatMap(c=>c.files.map(d=>d.path))),r=e.map(c=>Bt(c,s,a));return c=>f.has(c)||!t.has(c)&&r.some(d=>d==="."||d===""||c.startsWith(`${d}/`))}function Yt(n,e,s){let a=Object.fromEntries(Object.entries(e.files).filter(([o])=>s(o))),t=e.selection.selected.filter(o=>Object.hasOwn(a,o.path)),f=e.settled.filter(o=>s(o.path)),r=e.selection.refused.filter(o=>s(o.path)),c=e.selection.readingNotes,d=c?{instruction:c.instruction.filter(s),code:c.code.filter(s),agents:c.agents.filter(s)}:void 0,m=A(n,d??{instruction:[],code:[],agents:[]},f),i={...e.selection,selected:t,refused:r,readingNotes:d,skippedNote:m,totalBytes:t.reduce((o,l)=>o+(l.readBytes??l.size),0)};return{files:a,selection:i,settled:f,skippedFiles:e.skippedFiles.filter(o=>s(o.path)),invalidated:e.invalidated?.filter(o=>s(o.path))}}function Jt(n,e,s,a=[],t){let f=s??te([...e]),r=n.filter(i=>i.kind==="agent").map(i=>{let o=Bt(i,a,t),l=o==="."||o===""||f===o||f.startsWith(`${o}/`);return{node:i,overlap:new Set(i.files.filter(p=>e.has(p.path)).map(p=>p.path)).size,containment:l?o.split("/").filter(p=>p&&p!==".").length+1:0}}).filter(i=>i.overlap||i.containment);r.sort((i,o)=>o.overlap-i.overlap||o.containment-i.containment);let[c,d]=r,m=!!c&&c.overlap===d?.overlap&&c.containment===d?.containment;return{target:m?void 0:c?.node,overlapping:r.filter(i=>i.overlap).map(i=>i.node),tied:m?r.filter(i=>i.overlap===c.overlap&&i.containment===c.containment).map(i=>i.node):[]}}function Vt(n,e,s){let a=new Set(n.map(r=>r.path)),t=!!s&&!n.some(r=>r.path===s.path&&r.role==="system prompt"),f=t?n.filter(r=>r.path!==s.path).map(r=>r.role==="system prompt"||r.role==="soul"?{...r,role:"reference"}:r):[...n];return f.push(...e.filter(r=>!a.has(r.path)&&r.path!==s?.path).map(r=>({path:r.path,role:r.role==="tools"||r.role==="config"?r.role:"reference",label:null}))),t&&f.unshift({path:s.path,role:"system prompt",label:null}),{files:f,promptChanged:t}}function Qt(n,e){let s=new Map(n.map(a=>[a.label,a]));for(let a of e)s.has(a.label)||s.set(a.label,a);return[...s.values()]}function Xt(n,e,s,a,t){return a.filter(f=>f.role==="tools"&&(/\.json$/i.test(f.path)||ve(f.path)==="js")).flatMap(f=>Oe(n,e,s.files,{toolsPath:/\.json$/i.test(f.path)?f.path:null,toolsTsPath:/\.json$/i.test(f.path)?null:f.path,cliPath:null,mcpPath:null},t))}function Zt(n,e,s,a,t,f){let r=Vt(a?.files??[],s,t),d={...a??{id:De("",e.ruleResult.fragment.nodes.map(m=>m.id),()=>{})("agent"),kind:"agent",desc:re(null,r.files,!1),meta:null,tools:[],sourceRef:null},label:e.proposalSources.proposal.agentName,files:r.files,tools:Qt(a?.tools??[],Xt(n,e.repoKey,e.proposalSources,s,f))};return r.promptChanged&&t&&(d.desc=re(t.path,r.files,!1),d.sourceRef={path:t.path,line:null}),{agent:d,promptChanged:r.promptChanged}}function eo(n,e,s,a,t){let{target:f,overlapping:r,tied:c}=s,{fragment:d}=n,m=new Set([e.id,...(t?[...r,...c]:d.nodes).map(p=>p.id)]);for(let p=-1;p!==m.size;){p=m.size;for(let u of d.edges)m.has(u.from)&&m.add(u.to)}let i=d.nodes.filter(p=>m.has(p.id)).map(p=>p===f?e:p);f||i.push(e);let o=d.edges.filter(p=>m.has(p.from)&&m.has(p.to)),l=n.codeAgents?.filter(p=>m.has(p.unitKey)).flatMap(p=>p.unitKey!==f?.id?[p]:a?[]:[{...p,name:e.label,ownFiles:e.files}]);return{fragment:{...d,nodes:i,edges:o},...l?{codeAgents:l}:{}}}function to(n,e,s){let a=new Set(e.map(r=>r.path)),t=new Set([...n.flatMap(r=>r.files.map(c=>c.path)),...a]),f=a.size;return{fromProposal:f,fromRulesOnly:t.size-f,rejected:Object.values(s).reduce((r,c)=>r+c,0),rejectedByReason:s}}function It(n){return n.files.some(e=>e.role==="system prompt"||e.role==="soul")}function oo(n,e,s){if(e.some(t=>t.kind==="agent"&&!It(t)))return new Set;let a=new Set([V({code:"no-prompt",detail:"no-conventions"},n),V({code:"no-prompt"},n),V({code:"no-prompt",folderAgentsFound:!0},n)]);return s!==void 0&&a.add($e(n,{scanned:s})),a}function Lt(n,e){let{ruleResult:s,proposalSources:a,root:t,repoKey:f,scopes:r,scanned:c,agentChoice:d}=e,m=s,{files:i,selection:o,settled:l,skippedFiles:p,invalidated:u}=a,g=[...s.warnings],P=a.proposal.files.map(b=>({...b,path:O(b.path,t)})),h=P.find(b=>b.role==="prompt"),w=!1;if(P.length){let b=Jt(m.fragment.nodes,new Set(P.map(y=>y.path)),h?.path,r,t);if(b.target||h){let{agent:y,promptChanged:R}=Zt(n,e,P,b.target,h,g),N=d?.kind==="choose_agent";m={...m,...eo(s,y,b,R,N)},N&&({files:i,selection:o,settled:l,skippedFiles:p,invalidated:u}=Yt(n,a,$t(s.fragment.nodes,m.fragment.nodes,r,t))),w=It(y);let H=oo(f,m.fragment.nodes,c);g=g.filter(q=>!H.has(q))}}return{...m,files:i,selection:o,settled:l,skippedFiles:p,invalidated:u,...d&&!w?{agentChoice:d}:{},warnings:g,proposalCounts:to(m.fragment.nodes,P,a.rejectedByReason)}}function Yn(n){let e=[],s=!1,a=Promise.resolve();return t=>new Promise((f,r)=>{e.push({entry:t,resolve:f,reject:r}),!s&&(s=!0,queueMicrotask(()=>{let c=e;e=[],s=!1,a=a.then(async()=>{try{let d=await n(c.map(m=>m.entry));if(d.length!==c.length)throw new Error("bad_request");c.forEach((m,i)=>m.resolve(d[i]))}catch(d){c.forEach(m=>m.reject(d))}})}))})}async function Jn(n,e){let s=v=>e.localListing?v.filter(C=>k(n,C,{purpose:"listing",route:"local-folder",...e.admission}).admitted):v,a=s(e.entries),t=Y(n,{profile:"local-analysis",listing:a,selection:e.selection}),f=await ee(n,{entries:a,read:e.read,admission:e.admission,plan:t}),{files:r,settled:c,skippedFiles:d,...m}=f,i=await xt(n,{proposal:e.proposal,entries:a,read:e.read,proposalRead:e.proposalRead,admission:e.admission,files:r,settled:c,skippedFiles:d,selection:t.selection,unavailable:e.proposalRefusals,evidence:m}),{files:o,settled:l,skippedFiles:p}=i??f,u=_({...i??m,key:e.repoKey,files:o},t.context.flags,void 0,{markerPolicy:"any-read"}),g=i?.selection??t.selection,P;if(Me(n)&&e.repository){let v=e.repository,C=await Ne(n,{selected:{files:o,listedPaths:a.map(S=>S.path),fallbackName:Ye(e),skills:!0},selection:g,codeAgentsFound:We(n,u?.resolved,o),port:e.localListing?{context:()=>v.context(),read:(S,F)=>v.read(S,F),finish:S=>v.finish?.(S),list:async()=>{let S=await v.list();return{...S,entries:s(S.entries)}}}:v}),jt=new Set(Object.keys(o).map(S=>O(S,C.root)));if(o=C.files,g=C.selection,P=C.root,P!==void 0){p=p.map(F=>({...F,path:O(F.path,P)})),l=l.map(F=>({...F,path:O(F.path,P)}));let S=new Set(l.map(F=>F.path));l.push(...g.selected.filter(F=>!S.has(F.path)&&Object.hasOwn(o,F.path)))}p=L(p,C.skippedFiles).filter(S=>jt.has(S.path)||!Object.hasOwn(o,S.path))}let h={repoKey:e.repoKey,files:o,listedPaths:a.map(v=>O(v.path,P)),...P!==void 0?{root:P}:{},forLocal:!0,code:u},w=j(n,h),b=z(n,w),y=At(n,{codeAgents:b.codeAgents??[],conventions:w.conventions,root:P,selection:e.membership}),R=i?Lt(n,{ruleResult:b,proposalSources:{...i,files:o,selection:g,settled:l,skippedFiles:p,invalidated:i.invalidated?.map(v=>({...v,path:O(v.path,P)}))},root:P,repoKey:e.repoKey,scopes:w.conventions.agentScopes,scanned:u?.resolved?.scanned,agentChoice:y}):void 0,{settled:N,invalidated:H,...q}=R??{...b,settled:l,invalidated:void 0};R&&(o=R.files,g=R.selection,l=N,p=R.skippedFiles);let me=g.readingNotes?A(n,g.readingNotes,l):g.skippedNote,he=R?R.agentChoice:y;return{...q,...he?{agentChoice:he}:{},files:o,...P!==void 0?{root:P}:{},skippedFiles:H?.length?L(p,H):p,...R?{proposalCounts:R.proposalCounts}:{},warnings:[...new Set([...q.warnings,...me?[me]:[],...U(p)])],selection:g}}var no=new Set(pt);function Xn(n,e){for(let a of[...Object.keys(e.set),...e.clear])if(!no.has(a))throw new Error(`Unknown analysis field: ${a}`);let s={...n,...e.set};for(let a of e.clear)s[a]=void 0;return s}async function so(n,e,s){let a=Object.entries(e).map(([f,r])=>({path:f,size:Buffer.byteLength(r),ref:f})),t=Ve(n,a,s.root,!1,s.scanPaths);for(;!K(t);)t=await Xe(t,async f=>e[f.path]??null);return{scan:Q(n,t),summary:Ze(t)}}async function Tt(n,e,s){let{repoKey:a,root:t,agentConfigurations:f,codingGuides:r,forLocal:c}=s,d=s.flags??Ie(n),m=Object.keys(e),i=M(n,{phase:"start",paths:m,root:t,scanFlag:d.scan}),o=i.kind==="marker"?M(n,{phase:"read",pending:i,text:e[i.markerPath]??null}):i,l=o.kind==="off"?null:o.markerPath,p=o.kind==="off"?null:o.markerKind;if(o.kind==="off"||!o.scan){let b=_({key:a,files:e,markerPath:l,markerKind:p},d,void 0,{markerPolicy:"any-read"});return{...z(n,j(n,{repoKey:a,files:e,root:t,agentConfigurations:f,codingGuides:r,forLocal:c,code:b})),scanned:!1,resolved:null}}let{scan:u,summary:g}=await so(n,e,{repoKey:a,root:t,scanPaths:o.scanPaths}),P=_({key:a,files:e,ranked:u,scan:g,markerPath:l,markerKind:p},d,void 0,{markerPolicy:"any-read"});return{...z(n,j(n,{repoKey:a,files:e,root:t,agentConfigurations:f,codingGuides:r,forLocal:c,code:P})),scanned:!0,resolved:P.resolved}}async function _t(n,e){let{state:s,settings:a}=n;if(!ft(a,s).splitCheck||!s.splitEstimateBase)return{next:"inspecting",set:{repoCursor:0},clear:[]};let f=n.execution.preparation?.capUsd??s.splitEstimateBase.capUsd,r={...s.splitEstimateBase,capUsd:f};ke(r,e.progress.log);let c=gt(a,s),d={next:"inspecting",set:{repoCursor:0,splitCheckPriced:!0,splitFindingsPriced:!0},clear:["splitEstimateBase"]};if(!c.length)return d;let m=qe(J(await e.instructions())),i=c.reduce((g,{inventory:P})=>g+oe(Buffer.byteLength(wt({tools:m},{...P,findings:[]}).prompt))+oe(m.SHAPE_FINDINGS_INPUT_BYTES),0),o=r.lines.find(g=>g.label==="Scope check"),l=se(a,{template:"scope-findings"},"Scope check",Ue.mechanical,(o?.inputTokens??0)+c.length*St,(o?.outputTokens??0)+c.length*kt),p=r.lines.map(g=>g.label==="Scope check"?l:g);o||p.push(l),p.push(se(a,{template:"derive-shape"},"Split check",Pt,i,c.length*He));let u=ge(p,f);return Pe(u)?(d.estimate=r,d.clear.push("splitCheckPriced","splitFindingsPriced"),delete d.set.splitCheckPriced,delete d.set.splitFindingsPriced,e.progress.log({level:"warn",code:"analysis.split_check_over_cap",counts:{totalUsd:u.totalUsd,capUsd:u.capUsd}}),d.set.warnings=[...s.warnings??[],we]):d.estimate=u,d}var Os=async(n,e)=>{e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let{state:s,settings:a}=n,t=s.repos??[];await ye(a,s,e.readers);let f=s.repoCursor??0;if(f>=t.length)return _t(n,e);let r=t[f],c=n.execution.forLocal,d=c?s.mapped?.[f]?{fragment:ct(s,f),warnings:[]}:await Tt(a,r.files??{},{repoKey:r.key,root:r.root,agentConfigurations:r.agentConfigurations??{},forLocal:!0}):void 0,m=d?(()=>{let u=Ce(d.fragment,r.key);return{...u,warnings:[...d.warnings,...u.warnings]}})():ut(a,r,mt(a,s),s.modelReader??!1,s.projectAgents,J(await e.instructions()).bundleText("model-reader-runtime-prompt")),i=!c&&r.sourceReadNotes?A(a,r.sourceReadNotes,r.selected??[],r.root):void 0,o=c?[]:U((r.refused??[]).filter(u=>u.reason==="secret-content")),l="virtualFiles"in m?m.virtualFiles:void 0,p=[...s.mapped??[]];return p[f]=m.fragment,{next:"mapping",clear:[],set:{...l?{repos:t.map((u,g)=>g===f?{...u,files:{...u.files,...l}}:u)}:{},mapped:p,warnings:[...s.warnings??[],...i?[`${r.key}: ${i}`]:[],...o,...m.warnings,...ht(r)],repoCursor:f+1}}};export{Nt as a,Yn as b,Jn as c,Xn as d,Os as e};
@@ -1 +0,0 @@
1
- var r=t=>t.CF_UNTRUSTED_CONTENT_CHECK!=="0";function n(t){return t.CF_FINDING_BETTER_AS_CODE==="1"}var o=["contradiction","ambiguity","bypassable_requirement","stale_fact","description_mismatch","ungoverned_tool","untrusted_instructions","better_as_code"];function i(t){return o.filter(e=>(e!=="untrusted_instructions"||r(t))&&(e!=="better_as_code"||n(t)))}function _(t){return!n(t)&&r(t)}var p={contradiction:"Contradiction",ambiguity:"Ambiguity",bypassable_requirement:"Bypassable requirement",stale_fact:"Stale fact",description_mismatch:"Description mismatch",ungoverned_tool:"Ungoverned tool",untrusted_instructions:"Untrusted instructions",better_as_code:"Better as code",structure:"Structure",prompt_quality:"Prompt quality"};function l(t){return["contradiction","bypassable_requirement","stale_fact","description_mismatch","ungoverned_tool","untrusted_instructions"].includes(t)?2:1}function s(t){return typeof t=="string"&&o.includes(t)}function m(t,e){return s(t)&&i(e).includes(t)}export{r as a,n as b,i as c,_ as d,p as e,l as f,s as g,m as h};
@@ -1,32 +0,0 @@
1
- import{b as pn}from"./74FPPPIG.js";import{d as Oo,e as bt}from"./5TATKWLG.js";import{a as W,b as _t,d as Rt,e as Lo,f as pe}from"./2PZF54KH.js";import{d as cn}from"./6B2HILSY.js";import{f as Ro}from"./JKWTHRUR.js";import{b as _o,d as ln,e as Eo}from"./SKVEBOGA.js";import{a as wo,b as rn,c as bo}from"./724WZMYW.js";import{a as sn}from"./A7WJJMRY.js";import{b as an}from"./FSLWD2PE.js";import{c as un,d as fn,e as Et,g as Io}from"./YUY436SM.js";import{a as Te,c as B,d as vo,e as Fe}from"./C6X5GDG4.js";import{relative as Pa,sep as $a}from"node:path";var Ao=/(^|\/)(?:(?:\.cursor|\.windsurf|\.claude|\.roo)\/rules\/|\.clinerules\/|\.junie\/guidelines\.md$|\.kiro\/steering\/|\.github\/instructions\/.*\.instructions\.md$)/;function ye(e){let t=e.toLowerCase(),n=t.split("/").pop();return["claude.md","agents.md","gemini.md",".cursorrules",".windsurfrules",".clinerules","copilot-instructions.md"].includes(n)||/^(claude|agents|gemini)\.(local|override)\.md$/.test(n)||Ao.test(t)}function Za(e){let t=e.toLowerCase();return t.includes("/")?t===".github/copilot-instructions.md"||Ao.exec(t)?.index===0:ye(t)}function Qa(e,t){return+(e.toLowerCase()==="agents.md")-+(t.toLowerCase()==="agents.md")||e.localeCompare(t)}var Qe=["claude.md","agents.md"];function Fs(e){return!De(e)&&e.CF_CONFIGURATION_GUIDE_PROMPT!=="0"}function De(e){return e.CF_IMPORT_GUIDES_AS_PROMPT==="1"}function Po(e,t,n=!1){return n||De(e)||!ye(t)}function $o(e,t){return De(e)?Qe.includes(t.toLowerCase()):ye(t)}function Mo({codeAgentsFound:e,folderAgentsFound:t=!1,otherDefinitions:n,agentConfiguration:o=!1,usage:r="import"},s){return De(s)?t?"background":r==="scan"?n?"prompt":"background":r==="map"?e?"background":"prompt":e&&!n?"background":"prompt":Fs(s)&&o&&!e&&!t?"prompt":"background"}function ne(e,t){return e.CF_IMPORT_COVERAGE==="1"&&(t===void 0||e[t]==="1")}function X(e){return ne(e,"CF_IMPORT_LAYOUTS")}function J(e,t,n){let o=_t(t,n).filter(r=>r.kind!=="comment");return{path:e,text:t,lang:n,toks:o}}function d(e,t){return e?.kind==="punct"&&e.text===t}function y(e,t){return e?.kind==="ident"&&(t===void 0||e.text===t)}function K(e){return e?.kind==="string"||e?.kind==="template"}function Be(e){let t=/^[A-Za-z]*/.exec(e.text)[0],n=e.text.slice(t.length),o=n[0]??"",r=n.startsWith(o.repeat(3))&&n.length>=6?3:1,s=n.length>=2*r&&n.endsWith(o.repeat(r));if(s){let i=0;for(let l=n.length-r-1;l>=0&&n[l]==="\\";l--)i++;s=i%2===0}return{prefix:t,width:r,inner:n.slice(r,s?n.length-r:void 0),closed:s}}function T(e,t){return d(e[t],"=")&&!d(e[t+1],"=")&&!d(e[t+1],">")}var de=["function","def","class"],me=12;function V(e,t){return t===0||e[t].line>e[t-1].endLine}function Se(e,t){return t.start-(e.lastIndexOf(`
2
- `,t.start-1)+1)}function A(e,t){let n=0;for(let o=t;o<e.length;o++)if(e[o].kind==="punct"){if("([{".includes(e[o].text))n++;else if(")]}".includes(e[o].text)&&--n===0)return o}return e.length}function j(e,t){let n=A(e,t),o=[],r=t+1,s=0;for(let i=t+1;i<n;i++){let l=e[i];l.kind==="punct"&&"([{".includes(l.text)?s++:l.kind==="punct"&&")]}".includes(l.text)?s--:s===0&&d(l,",")&&(o.push({from:r,to:i}),r=i+1)}return r<n&&o.push({from:r,to:n}),o}function vt(e,t,n){let o=A(e,t),r=[],s=t+1,i=0,l=!1,a=0;for(let c=t+1;c<o;c++){let f=e[c];if(f.kind==="punct")if("([{".includes(f.text))i++;else if(")]}".includes(f.text))i--;else{if(i!==0)continue;f.text===","&&a===0?(r.push({from:s,to:c}),s=c+1,l=!1):f.text===":"&&!l?l=!0:l&&(n==="js"&&f.text==="<"?a++:n==="js"&&f.text===">"&&a>0&&!d(e[c-1],"=")?a--:a===0&&T(e,c)&&(l=!1))}}return s<o&&r.push({from:s,to:o}),r}var Ds=100;function ke(e){return e.replace(/\s+/g," ").trim().slice(0,Ds)}function q(e,t={}){return e.lang==="py"?Xs(e,t.namespaceBindings===!0,t.bindingPositions===!0):Gs(e,t.bindingPositions===!0,t.completeImports===!0)}var Bs=new Set(["@anthropic-ai/sdk","anthropic","openai","ai","@anthropic-ai/claude-agent-sdk","claude_agent_sdk","@openai/agents"]);function Ot(e,t,n={},o){let r=t==="py"?e.split(".")[0]:e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0];return r==="@openai/agents"?n.layouts===!0:t==="py"&&r==="agents"?n.layouts===!0&&(n.openaiAgents===!0||!!o&&Ws(o)):Bs.has(r)||r.startsWith("@ai-sdk/")||r.startsWith("@langchain/")||r.startsWith("langchain")}function Ws({toks:e}){let t=(n,o=!1)=>e.some((r,s)=>y(r,n)&&!de.includes(e[s-1]?.text??"")&&(d(e[s+1],"(")||o&&d(e[s+1],".")));return t("Agent")&&t("Runner",!0)}var Ks=[".","/","@/","~/"];function le(e,t){return e.filter(n=>t==="py"||Ks.some(o=>n.source.startsWith(o))).flatMap(n=>n.names.map(o=>({name:o,imported:n.renamed?.[o]??o,source:n.source,line:n.line})))}function Gs(e,t,n){let{toks:o}=e,r=[];for(let s=0;s<o.length;s++)if(y(o[s],"import")&&!d(o[s-1],".")){let i=d(o[s+1],"(")?Us(e,s+1):Js(e,s,n);i&&r.push({...i,...t?{bindingAt:s}:{}})}else y(o[s],"require")&&d(o[s+1],"(")&&K(o[s+2])&&d(o[s+3],")")&&r.push({source:o[s+2].value,line:o[s].line,...qs(e,s),...t?{bindingAt:s}:{}});return r}function Us(e,t){let n=e.toks[t+1];return K(n)&&d(e.toks[t+2],")")?{source:n.value,line:n.line,names:[]}:null}var zs=80;function Js(e,t,n){let{toks:o}=e,r=n?o.length:Math.min(o.length,t+zs);for(let s=t+1;s<r;s++){let i=o[s];if(K(i))return s!==t+1&&!y(o[s-1],"from")?null:{source:i.value,line:o[t].line,...Vs(e,t+1,s)};if(d(i,";")||y(i,"import"))return null}return null}function Vs(e,t,n){let{toks:o}=e,r=[],s={},i=y(o[t],"type")&&Co(o[t+1])?t+1:t,l=y(o[i])?o[i].text:void 0;for(let a=t;a<n;a++){let c=o[a];if(!(!y(c)||c.text==="from"))if(c.text==="as")y(o[a+1])&&(r.push(o[++a].text),y(o[a-2])&&(s[o[a].text]=o[a-2].text));else{if(y(o[a+1],"as"))continue;(c.text!=="type"||!Co(o[a+1]))&&r.push(c.text)}}return{names:r,renamed:s,...l?{defaultName:l}:{}}}function Co(e){return d(e,"{")||y(e)&&e?.text!=="from"}function qs(e,t){let{toks:n}=e,o={names:[],renamed:{}};if(!d(n[t-1],"="))return o;if(y(n[t-2]))return{names:[n[t-2].text],renamed:{}};if(!d(n[t-2],"}"))return o;let r=t-2;for(;r>0&&!d(n[r],"{");)r--;let s=[],i={};for(let l=r+1;l<t-2;l++)!y(n[l])||d(n[l+1],":")||(s.push(n[l].text),d(n[l-1],":")&&y(n[l-2])&&(i[n[l].text]=n[l-2].text));return{names:s,renamed:i}}function Xs(e,t,n){let{toks:o}=e,r=[];for(let s=0;s<o.length;s++)if(V(o,s)){if(y(o[s],"import"))r.push(...Hs(e,s+1,t).map(i=>({...i,...n?{bindingAt:s}:{}})));else if(y(o[s],"from")){let i=jo(e,s+1);i.next>s+1&&y(e.toks[i.next],"import")&&r.push({source:i.text,line:o[s].line,...Ys(e,i.next+1),...n?{bindingAt:s}:{}})}}return r}function jo(e,t){let{toks:n}=e,o=t,r=!1;for(;;){if(d(n[o],"."))r=!1;else if(y(n[o])&&!r&&n[o].text!=="import")r=!0;else break;o++}return{text:n.slice(t,o).map(s=>s.text).join(""),next:o}}function Hs(e,t,n){let{toks:o}=e,r=[],s=t;for(;;){let i=jo(e,s);if(i.next===s)break;let l=y(o[i.next],"as")?o[i.next+1]?.text:void 0,a=l??i.text.split(".")[0];if(r.push({source:i.text,line:o[t].line,names:n?[a]:[],...n?{namespaceNames:[a],...l?{renamed:{[l]:i.text}}:{}}:{}}),s=i.next,y(o[s],"as")&&(s+=2),!d(o[s],","))break;s++}return r}function Ys(e,t){let{toks:n}=e,o=d(n[t],"("),r=o?A(n,t):n.length,s=[],i={};for(let l=o?t+1:t;l<r&&!(!o&&(V(n,l)||d(n[l],";")));l++)y(n[l])&&(y(n[l+1],"as")&&y(n[l+2])?(s.push(n[l+2].text),i[n[l+2].text]=n[l].text,l+=2):s.push(n[l].text));return{names:s,renamed:i}}var It=["eval","evals"],Zs=new RegExp(`(^|/)(${[...It,"evaluations?","bench(?:mark)?s?"].join("|")})/`,"i"),Qs=/^(evals?|bench(?:mark)?s?)[_-].+|.+[._-](evals?|bench(?:mark)?s?)[._-]/i;function No(e,t){if(Zs.test(e))return!0;let n=W(e);if((n||/\.(json|ya?ml|toml)$/i.test(e))&&Qs.test(e.split("/").at(-1)))return!0;if(!n||t===void 0||!/(^|\/)scripts\//i.test(e))return!1;let o=J(e,t,n),{toks:r}=o;if(r.some((p,g)=>y(p,"export")||y(p,"exports")||n==="py"&&y(p,"def")||y(p,"module")&&d(r[g+1],".")&&y(r[g+2],"exports"))||!r.some(p=>y(p)&&/^(expected|dataset|fixtures|cases)$/i.test(p.text)))return!1;let s=r.flatMap((p,g)=>y(p)&&d(r[g+1],"(")&&!["for","if","while","switch","catch"].includes(p.text)&&!["function","def","class"].includes(r[g-1]?.text)?[g]:[]),l=q(o).filter(p=>p.names.some(g=>s.some(m=>y(r[m],g)&&!d(r[m-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)),f=[...c,...l.filter(p=>a.test(p.source))],u=new Set(f.flatMap(p=>p.names));return s.some(p=>d(r[p-1],".")?!(y(r[p-2],"console")&&["log","table"].includes(r[p].text)):y(r[p],"require")&&r[p+2]?.kind==="string"&&f.some(g=>g.source===r[p+2].value)?!1:!u.has(r[p].text)&&!(n==="py"&&y(r[p],"print")))?!1:l.some(p=>a.test(p.source))&&c.some(p=>!a.test(p.source))}function Lt(e){return e.CF_IMPORT_CALLS==="1"}var We={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 Ke(e){return e.CF_IMPORT_LAYOUTS==="1"}var Do=/(^|\/)(__tests__|__snapshots__)\/|\.(test|spec)\.[jt]sx?$|_test\.(go|py)$/i,dn=new Set(["test","tests","__tests__","spec","specs","testdata","test-data","test_data","test-support","mocks","fixtures","fixture","__fixtures__","__mocks__","__snapshots__"]),Bo=/^(examples?|samples?)(?:[-_].+)?$|^.+[-_](examples?|samples?)$/i,Wo=/\.(test|spec)\..+|^test_.*\.py$|_test\.(py|go)$|_spec\.rb$|^conftest\.py$/i,ei=new Set([...dn].filter(e=>!["test","tests","__tests__","spec","specs"].includes(e))),ti=new Set([".github","cassettes"]),ni=new Set,To=new WeakMap;function Ko(e){if(!ne(e))return[];let t=To.get(e);if(t)return t;let n=[];try{let o=JSON.parse(e.CF_IMPORT_SCOPES??"[]");Array.isArray(o)&&o.every(r=>{if(!r||typeof r!="object"||!["runtime","example","evaluator"].includes(r.kind)||typeof r.path!="string")return!1;let s=r.path.endsWith("/**"),i=s?r.path.slice(0,-3):r.path;return!!i&&!/[\\\0:*?]/.test(i)&&!i.split("/").some(l=>!l||l==="."||l==="..")&&!(r.kind==="evaluator"&&s)})&&new Set(o.map(r=>r.path)).size===o.length&&(n=Object.freeze(o.map(({path:r,kind:s})=>Object.freeze({path:r,kind:s}))))}catch{}return To.set(e,n),n}function we(e,t,n){let o=B(t,n);if(o===null)return;let r=Ko(e).filter(l=>l.path.endsWith("/**")?t.startsWith(l.path.slice(0,-2)):t===l.path).sort((l,a)=>a.path.replace(/\/\*\*$/,"").length-l.path.replace(/\/\*\*$/,"").length)[0];if(!r||r.kind==="runtime")return;let s=o.split("/"),i=s.pop();if(!(s.some(l=>ei.has(l.toLowerCase())||ti.has(l.toLowerCase()))||/^conftest\.py$/i.test(i))&&!(r.kind==="example"&&(Wo.test(i)||s.some(l=>dn.has(l.toLowerCase())))))return r}function mn(e,t,n={}){return!Ko(e).some(r=>r.kind!=="runtime"&&(B(r.path,n.root)!==null||r.path.endsWith("/**")&&B(`${Te(n.root)}/`,r.path.slice(0,-3))!==null))||we(e,t,n.root)?!1:At(t,{root:n.root??void 0,listing:n.listing??ni})!==null}var oi=new Set(["example-agents","examples","example","fixtures","__fixtures__","testdata","test","tests","__tests__","demo","demos"]),ri=/^examples?[-_]/i;function Go(e,t,n){if(e.CF_IMPORT_INCLUDE_EXAMPLES==="1"||we(e,t,n))return!1;let o=ne(e),r=i=>oi.has(i.toLowerCase())||ri.test(i)||o&&(i.toLowerCase()==="fixture"||Bo.test(i));if(Te(n).split("/").some(r))return!1;let s=B(t,n);return s!==null&&s.split("/").slice(0,-1).some(r)}var Fo=new WeakMap;function si(e){let t=Fo.get(e);if(t)return t;let n={exact:new Set,foldedNames:new Set};for(let o of e.keys()){let r=0;for(let s=o.indexOf("/");s!==-1;s=o.indexOf("/",r))n.exact.add(o.slice(0,s)),n.foldedNames.add(o.slice(0,r)+o.slice(r,s).toLowerCase()),r=s+1}return Fo.set(e,n),n}function ii(e,t,n){let o=e.some(r=>At(t(r),n)===null);return r=>{if(n.settings&&we(n.settings,r,n.root))return!1;if(n.settings&&mn(n.settings,r,n))return!0;let s=At(r,n);return s==="test"||s==="example"&&o}}function Uo(e,t,n){let o=ii(e,t,n),r=[],s=[];for(let i of e)(o(t(i))?s:r).push(i);return{kept:r,skipped:s}}function gn(e,t){return At(e,t)!==null}function At(e,t){let n=B(e,t.root);return n?li(e,n,t):null}function li(e,t,n){let o=si(n.listing),r=e.endsWith("/")||o.exact.has(e),s=t.split("/").filter(Boolean),i=r?"":s.pop()??"";return Wo.test(i)||s.some(a=>dn.has(a.toLowerCase()))?"test":s.some((a,c)=>{let f=a.toLowerCase();if(Bo.test(f))return!0;if(f!=="before"&&f!=="after")return!1;let u=Te(Fe(s.slice(0,c).join("/"),n.root)),p=u?`${u}/`:"",g=f==="before"?"after":"before";return o.foldedNames.has(p+g)})?"example":null}var ai=new Set,zo=new WeakMap;function Jo(e,t){let n={root:t.root,listing:t.listing??ai};if(!gn(e,n))return!1;let o=t.listing;if(!o?.has(e))return!0;let r=zo.get(o);r||zo.set(o,r=new WeakMap);let s=r.get(t.settings);s||r.set(t.settings,s=new Map);let i=s.get(t.key);if(!i){let l=[...o.keys()].filter(a=>gn(a,n)||t.readable(a,"get"in o?o.get(a):void 0));i=new Set(Uo(l,a=>a,n).skipped),s.set(t.key,i)}return i.has(e)}function Vo(e){return e.CF_IMPORT_EXAMPLE_FILTER!=="0"}import{posix as hn}from"node:path";var xn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function ae(e,t={}){let n=`(?:${et.map(xn).join("|")})`,o=`(?:${Pt.map(xn).join("|")})`,s=new RegExp(`^(${t.nested?"(?:.*?/)??":""}(?:(${n}/[^/]+)/${be}|${o})/([^/]+))/(.+)$`,t.caseSensitive?"":"i").exec(e);if(!s)return null;let i=t.caseSensitive?s[4]:s[4].toLowerCase(),l=t.caseSensitive?F.skill:F.skill.toLowerCase();return{folder:s[1],name:s[3],definition:i===l,reference:i.startsWith("references/"),...s[2]?{ownerPath:s[1].replace(/\/skills\/[^/]+$/i,".md")}:{}}}function yn(e){return ae(e)?.reference??!1}function ci(e){return ne(e,"CF_DISCOVERY_SKILLS")}function ui(e){return!/[\\:\0]/.test(e)&&e.split("/").every(t=>t&&t!=="."&&t!=="..")}function fi(e){let t=[],n;for(let[o,r]of e.split(/\r?\n/).entries()){let s=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(r);if(n){if(s&&s[1][0]===n.marker[0]&&s[1].length>=n.marker.length&&!s[2].trim()){n=void 0;continue}if(!n.shell||!/^\s*(?:\$\s+)?(?:cat|less|more|head|tail)\s+/.test(r))continue}if(!n&&s){n={marker:s[1],shell:/^(?:sh|bash|shell|console)?$/i.test(s[2].trim())};continue}let i=/!?\[[^\]\n]*\]\(\s*(?:<([^>\n]+)>|([^\s)\n]+))(?:\s+["'][^"'\n]*["'])?\s*\)|^\s*\[[^\]]+\]:\s*(?:<([^>]+)>|(\S+))|`([^`\n]+)`|([^\s`<>"'()[\],;]+)/g;for(let l of r.matchAll(i)){let a=l.slice(1,5).some(g=>g!==void 0),c=l[1]??l[2]??l[3]??l[4]??l[5]??l[6],f=a?c:c.replace(/[.,;:]+$/,""),u=/^[^.\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(f.split(/[/\\]/).at(-1)??""),p=l[5]!==void 0&&/[/\\]/.test(f)||/^\.{1,2}[/\\]/.test(f);f.startsWith("#")||!a&&(/\s/.test(f)||!(p||u))||t.push({target:f,span:{from:o+1,to:o+1}})}}return t}function _c(e,t){let n={references:[],cycles:[],unresolved:[]};if(!ci(e))return n;let o=[...new Set(t.paths)].filter(s=>ui(s)&&B(s,t.root)!==null).sort(),r=new Set(o);for(let s of[...new Set(t.skillPaths)].sort()){if(!r.has(s)||!ae(s,{nested:!0})?.definition)continue;let i=new Set,l=new Set,a=c=>{if(!(i.has(c)||!Object.hasOwn(t.files,c))){i.add(c),l.add(c);for(let{target:f,span:u}of fi(t.files[c])){let p=k=>n.unresolved.push({ownerPath:s,fromPath:c,target:f,span:u,reason:k}),g=f.split("#")[0];if(!g||/[\\:\0*?[\]$]/.test(g)||g.startsWith("/")||/[{}]/.test(g.replace(/(?:^|\/)\{lang\}(?=\/)/g,""))){p("unsupported");continue}let m=hn.normalize(hn.join(hn.dirname(c),g));if(m===".."||m.startsWith("../")||B(m,t.root)===null){p("out-of-scope");continue}let x=new RegExp(`^${m.split("/").map(k=>k==="{lang}"?"[^/]+":xn(k)).join("/")}$`),h=m.includes("{lang}")?o.filter(k=>x.test(k)):r.has(m)?[m]:[];if(!h.length){p("missing");continue}for(let k of h){let w={ownerPath:s,fromPath:c,path:k,span:u};l.has(k)?n.cycles.push(w):(n.references.push(w),a(k))}}l.delete(c)}};a(s)}return n}var kn="readme";function Ac(e){let t=e.toLowerCase();return t.startsWith(kn)?0:t===F.agentGuide?1:t.endsWith(".md")&&e.split("/").length<=2?2:qo.test(e)?3:null}var F={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:`${kn}.md`,agentGuide:"agents.md"},tt=[F.systemPrompt,F.hyphenatedPrompt,F.system,F.prompt],wn=F.promptFallback,pi=[...tt,wn].map(e=>e.toLowerCase()),$t=[".mcp.json","mcp.json"],di=[F.toolsSource,F.cli],Ee=".claude",nt="agents",be="skills",et=[`${Ee}/${nt}`,nt],Pc=/^(?:\.claude\/)?(skills|commands)\//i,Pt=[be,`${Ee}/${be}`],mi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),gi=e=>e.map(mi).join("|"),hi=`(?:${gi(et)})`,bn=new RegExp(`^${hi}/[^/]+\\.md$`,"i"),xi=/^templates\/.+/i;function $c(e,t){return ae(e,t)?.definition??!1}function _e(e){return e.CF_DISCOVERY_SKILLS!=="0"}var _n=new Map([...tt.map(e=>[e,{role:"prompt",kind:"dedicated"}]),[wn.toLowerCase(),{role:"prompt",kind:"fallback"}],[F.soul,{role:"soul"}],[F.knowledge,{role:"knowledge"}],[F.config,{role:"marker"}],[F.tools,{role:"tool file",kind:"json"}],[F.toolsSource,{role:"tool file",kind:"sdk"}],[F.cli,{role:"tool file",kind:"cli"}],...$t.map(e=>[e,{role:"MCP config"}])]),yi=[..._n.keys()];function Sn(e){let t=_n.get(e.toLowerCase());if(t)return t;if(bn.test(e))return{role:"sub-agent"};let n=ae(e),o=n?.ownerPath?{ownerPath:n.ownerPath}:{};return n?.definition?{role:"skill",name:n.name,...o}:n?.reference?{role:"reference",kind:"skill",name:n.name,...o}:xi.test(e)?{role:"reference",kind:"template"}:null}function Si(e){let t=Sn(e);return!!t&&t.role!=="skill"&&t.role!=="reference"}var ki=["package.json","pyproject.toml","go.mod","cargo.toml"],wi=[...yi.filter(e=>!di.includes(e)),...ki],bi=new RegExp(`^${kn}[^/]*$`,"i");function Mt(e,t,n){let o=Ke(e)?n?.ownerOf(t):void 0;return o?B(t,o.folder)??t:t}function En(e,t,n){if(Ke(e)&&n?.files?.some(l=>l.path===t&&l.kind==="entry"))return!0;t=Mt(e,t,n);let o=t.split("/").pop()??"",r=ae(t),s=r?.definition&&(_e(e)||!r.ownerPath&&!r.folder.startsWith(`${Ee}/`)),i=r?.reference&&r.ownerPath&&_e(e);return wi.includes(o.toLowerCase())||bi.test(o)||Si(t)||!!s||!!i}var Mc=[...tt,wn].join(", "),Cc=`${F.config}, a system prompt file, ${F.tools}, an MCP config, ${F.soul}, ${F.knowledge}, ${nt}/*.md and ${be}/*/${F.skill}`,jc=/(agent|tool|prompt|llm|model|chain|graph|pipeline|workflow|handler|route|server|main|index|app|orchestr)/i,Nc=/(^|\/)prompts?\/.*\.(md|txt|prompt)$/i;function Tc(e,t,n={}){let o=t.flatMap(m=>{let x=B(m,n.root);return x===null?[]:[{path:m,relativePath:x}]}),r=o.filter(({path:m})=>Ge(e,{path:m},{purpose:"override",route:"github"}).admitted),s=new Map(r.map(m=>[m.relativePath.toLowerCase(),m.path])),i=tt.map(m=>s.get(m)).find(Boolean),l=$t.map(m=>s.get(m)).find(Boolean),a=m=>$o(e,m),c=Mo({codeAgentsFound:n.codeAgentsFound??!1,folderAgentsFound:n.folderAgentsFound,agentConfiguration:n.agentConfiguration,otherDefinitions:r.some(({relativePath:m})=>{let x=Sn(m);return!a(m)&&!!x&&x.role!=="reference"})},e),f=n.agentConfiguration&&c==="prompt",u=f?Qe.map(m=>s.get(m)).find(Boolean):void 0,p=!f&&s.has(F.soul)&&!(De(e)?pi:tt).some(m=>s.has(m)),g=[];for(let m of r){let x=a(m.relativePath)&&(c==="background"||f&&!Qe.includes(m.relativePath.toLowerCase())),h=f&&Qe.includes(m.relativePath.toLowerCase())?{role:"prompt",kind:"fallback"}:x?{role:"knowledge",kind:"background"}:Sn(m.relativePath);if(!h||n.mode==="core"&&(h.role==="skill"||h.role==="reference"))continue;let k;x?k=m.path===s.get(m.relativePath.toLowerCase()):f&&h.role==="prompt"&&h.kind==="fallback"?k=m.path===u:h.role==="prompt"&&h.kind==="dedicated"?k=m.path===i:h.role==="MCP config"?k=m.path===l:_n.has(m.relativePath.toLowerCase())&&(k=m.path===s.get(m.relativePath.toLowerCase()));let w=h.ownerPath?{ownerPath:s.get(h.ownerPath.toLowerCase())??null}:{};g.push({...m,...h,...w,...k===void 0?{}:{preferred:k}})}return{files:g,scoped:o,registry:p}}var Re=/\.(?:md|txt|j2|hbs|mustache|prompt)$/i,Xo=/(?:^|[/\\])(?:prompts?|templates?|instructions)(?=$|[/\\])/i,_i=/prompt|instructions|system/i,Ei=200;function Ct(e){if(!Re.test(e))return!1;let t=e.split("/"),n=t[t.length-1];return t.slice(0,-1).some(r=>r.toLowerCase()==="prompts")||_i.test(n)}function Ho(e,t){return!Ct(e)||Buffer.byteLength(t)<Ei?null:Ri(e,t)}function Ri(e,t){let n=Buffer.byteLength(t),o=t.split(`
3
- `).length;return{kind:"file",named:!1,prose:!1,path:e,start:0,line:1,endLine:o,span:{from:1,to:o},symbol:null,chars:n,excerpt:ke(t),enclosing:null}}function Wc(e,t){let n=e.toks[t.from];return t.to!==t.from+1||n?.kind!=="string"||!Be(n).closed?null:{kind:"named",named:!0,prose:!1,path:e.path,start:n.start,line:n.line,endLine:n.endLine,span:{from:n.line,to:n.endLine},symbol:null,chars:n.value.length,excerpt:ke(n.value),enclosing:null}}function Rn(e){return/(?:^|\/)(?:pyproject\.toml|requirements\.txt)$/i.test(e)}function Gc(e,t){if(!Rn(e))return!1;let n=t.split(/\r?\n/).map(s=>s.replace(/("(?:\\.|[^"\\])*"|'[^']*')|#.*/g,(i,l)=>l??""));if(/(?:^|\/)requirements\.txt$/i.test(e))return n.some(s=>/^\s*openai[-_.]agents(?:\[[^\]]*\])?(?=\s*(?:$|[<>=!~;@#]))/i.test(s));let o="",r=new Map;for(let s of n){let i=/^\s*\[([^\]]+)\]/.exec(s);i?o=i[1]:(r.has(o)||r.set(o,[]),r.get(o).push(s))}for(let[s,i]of r){let l=i.join(`
4
- `);if(/^tool\.poetry(?:\.group\.[^.]+)?\.dependencies$/.test(s)){if(/^\s*["']?openai[-_.]agents["']?\s*=/im.test(l))return!0}else if(["project","project.optional-dependencies","dependency-groups"].includes(s)){let a=/^\s*([\w."'-]+)\s*=\s*\[((?:"(?:\\.|[^"\\])*"|'[^']*'|[^\]"'])*)\]/gm;for(let c of l.matchAll(a))if(!(s==="project"&&c[1].replace(/["']/g,"")!=="dependencies")&&/["']openai[-_.]agents(?=["'[<>=!~ ;@])/i.test(c[2]))return!0}}return!1}function Yo(e){return/\.json$/i.test(e)?"json":/\.ya?ml$/i.test(e)?"yaml":W(e)||/\.(cs|go|rb|java)$/i.test(e)?"code":/\.(md|markdown)$/i.test(e)?"markdown":"text"}function Zo(e){return{salesforce:"Salesforce",slack:"Slack",s3:"S3",anthropic:"Anthropic","http-client":"HTTP client"}[e.toLowerCase()]??e}function Qo(e){let t=new Map;for(let n of e)!n.unitKey||!n.scope||(t.has(n.scope)||t.set(n.scope,new Map),t.get(n.scope).set(n.unitKey,n.id));return e.flatMap(n=>!n.unitKey||!n.scope?[]:(n.links??[]).flatMap(o=>{let r=t.get(n.scope)?.get(o.to);return r?[{from:n.id,to:r,kind:"invokes",label:o.kind,sourceRef:o.source??null}]:[]}))}function er(e,t,n){let o;try{let r=JSON.parse(e),s=r?.mcpServers??r?.servers;o=s&&typeof s=="object"?Object.keys(s):[]}catch{return{servers:[],warnings:[`${t} is not valid JSON; ignored`]}}return{servers:o,warnings:!n&&o.length?[`found MCP config (servers: ${o.join(", ")}) but no ${F.tools}; tool schemas are discovered from a running server and were not extracted`]:[]}}import{z as ve}from"zod";var vi=ve.object({name:ve.string().min(1,"tool name is required"),description:ve.string().optional(),input_schema:ve.record(ve.string(),ve.unknown()).optional()}),Oi=ve.array(vi);function tr(e){let t=[];if(e==null)return{tools:[],warnings:t};let n=e;if(typeof e=="string"){let r=e.trim();if(r==="")return{tools:[],warnings:t};try{n=JSON.parse(r)}catch(s){throw new Error(`tools is not valid JSON: ${s.message}`)}}let o=Oi.safeParse(n);if(!o.success)throw new Error(`tools do not match the expected shape (an array of {name, description?, input_schema?}): ${o.error.issues.map(r=>`${r.path.join(".")||"(root)"}: ${r.message}`).join("; ")}`);return o.data.length===0&&t.push("no tools were provided"),{tools:o.data,warnings:t}}import{posix as vn}from"node:path";var Q=e=>`${e.path}:${e.kind}:${e.start}`;function ot(e){return e.slice(e.lastIndexOf("/")+1)}function rt(e,t){let n=t.replace(/\\/g,"/").replace(/^(\.\/)+/,""),o=e.filter(r=>r.path===n||r.path.endsWith(`/${n}`));return o.length>0?o:e.filter(r=>ot(r.path)===ot(n))}function Oe(e,t,n){let o=Q(t);e.set(o,[...e.get(o)??[],n])}function Ii(e,t,n){let o=r=>r.replace(/\.(tsx?|jsx?|mjs|cjs|py)$/,"").replace(/\/(?:index|__init__)$/,"");if(t.startsWith(".")){let r=e.endsWith(".py"),s=r?/^\.+/.exec(t)?.[0].length??0:0,i=r?"../".repeat(Math.max(0,s-1))+t.slice(s).replace(/\./g,"/"):t,l=o(vn.normalize(vn.join(vn.dirname(e),i)));return n.filter(a=>o(a)===l)}return n.filter(r=>Rt(r,t))}function nr(e,t,n){if(!(!e.moduleResolver||e.moduleResolver.legacy))return new Set(e.moduleResolver.bindings(t.path,n.source,[n.imported]).flatMap(o=>o.status==="resolved"?[o.path]:[]))}function Ue(e,t,n){let o=nr(e,t,n)??new Set(Ii(t.path,n.source,e.files.map(r=>r.path)));return e.files.filter(r=>o.has(r.path))}function On(e,t,n,o,r=!1){let s=nr(e,t,n);if(s)return o.filter(a=>s.has(a.path));let i=r?[n.source,`${n.source}.${n.imported}`]:[n.source],l=o.filter(a=>i.some(c=>Rt(a.path,c)));return l.length?l:o}function Ie(e,t,n,o){let r=(o.get(n)??[]).filter(c=>c.path===t.path);if(r.length)return r;let[s,i]=n.split("."),l=t.imports.find(c=>c.name===s);if(!l)return[];let a=new Set(Ue(e,t,l).map(c=>c.path));return(o.get(i??l.imported)??[]).filter(c=>a.has(c.path))}import{posix as Bt}from"node:path";var jt=/^(claude-[a-z0-9.-]+|gpt-[a-z0-9.-]+|o[1-9](-[a-z0-9-]+)?|gemini-[a-z0-9.-]+)$/,Li=/^\S+\.(?:md|txt|j2|hbs|mustache|prompt)$/i,st=50,or=200;function rr(e){let t=[],n=[],o=[];for(let[r,s]of e.toks.entries()){if(!K(s))continue;s.kind==="string"&&jt.test(s.value)&&t.length<st&&t.push({value:s.value,path:e.path,line:s.line});let i=s.value.length<=or&&Li.test(s.value),l=e.toks[r-2],a=d(e.toks[r-1],":")&&l&&/^(?:system_prompt|user_prompt|prompt|template)$/i.test(l.kind==="string"?l.value:l.text);if(i){let c={value:s.value,path:e.path,line:s.line};n.length<st&&n.push(c),a&&o.length<st&&o.push(c)}}return{modelIds:t,fileRefs:n,promptFileRefs:o}}function sr(e){let{toks:t}=e,n=[];for(let o=0;o<t.length&&n.length<st;o++)if(!(!y(t[o])||!T(t,o+1)||!d(t[o+2],"{"))&&!(e.lang==="js"&&!y(t[o-1],"const")))for(let{from:r,to:s}of j(t,o+2)){let i=t[r],l=t[r+2];if(!(s!==r+3||!d(t[r+1],":")||l?.kind!=="string"||l.value.length>or||!jt.test(l.value))&&!(!y(i)&&i?.kind!=="string")&&(n.push({object:t[o].text,member:i.kind==="string"?i.value:i.text,value:l.value,path:e.path,line:l.line}),n.length===st))break}return n}import{posix as Dt}from"node:path";import{posix as lt}from"node:path";var Ai=new Set(["string","unknown","any","object","never","boolean","number","undefined","null","void"]),Pi=new Set(["if","for","while","switch","catch","with"]),$i=24;function ir(e){return Ai.has(e)}function G(e,t){let n=0;for(let o=t-1;o>=0;o--){let r=e.toks[o];if(r.kind==="punct"){if(")]}".includes(r.text))n++;else if("([{".includes(r.text)&&n--===0)return o}}return-1}function In(e,t){let{toks:n}=e;if(!d(n[t],"("))return!1;let o=n[t-1];if(o&&y(o)&&Pi.has(o.text))return!1;let r=A(n,t),s=n[r+1];return d(s,"{")||d(s,"=")&&d(n[r+2],">")?!0:d(s,":")&&y(n[t-2],"function")}function lr(e,t){let{toks:n}=e;if(!d(n[t],"{"))return!1;for(let r=t-1;r>=0&&r>=t-$i;r--){let s=n[r];if(d(s,";")||d(s,"{")||d(s,"}"))break;if(y(s,"interface")||y(s,"type")&&y(n[r+1])&&(d(n[r+2],"=")||d(n[r+2],"<")))return!0}if(!d(n[t-1],":"))return!1;let o=G(e,t);return o>=0&&(lr(e,o)||In(e,o))}function Ln(e,t){let n=G(e,t);if(n<0)return!1;if(In(e,n)||lr(e,n))return!0;let o=d(e.toks[n],"{")?G(e,n):-1;return o>=0&&In(e,o)}var Mi=new Set(["if","for","while","switch","catch","return","function","def","class","elif","with","await","typeof"]),An={js:new Set(["if","for","while","switch","catch","with"]),py:new Set(["if","elif","for","while","with","except"])},Ci={js:new Set([...An.js,"return","yield","throw","await","typeof","void","delete","new","in","instanceof","case","else","do","default","extends"]),py:new Set([...An.py,"return","yield","await","not","and","or","is","in","assert","raise","else","lambda","del"])};function H(e,t,n){if(!n)return y(e[t])&&!Mi.has(e[t].text)&&d(e[t+1],"(");let o=t+1;if(!d(e[o],"("))return!1;let r=t,s=n.lang==="py"&&d(e[r],"\\");if(s&&r--,n.lang==="py"&&e[r]?.endLine<e[o].line&&!s&&G(n,o)<0)return!1;if(n.lang==="js"&&d(e[r],".")&&d(e[r-1],"?")&&(r-=2),n.lang==="js"&&d(e[r],">")){if(!/\.[cm]?tsx?$/.test(n.path))return!1;let i=0;do{if(d(e[r],";")||d(e[r],"="))return!1;d(e[r],">")?i++:d(e[r],"<")&&i--,r--}while(r>=0&&i>0);if(i!==0)return!1}for(;d(e[r],"]");)r=G(n,r)-1;if(d(e[r],")")){let i=e[G(n,r)-1];return!y(i)||!An[n.lang].has(i.text)}return!y(e[r])||de.some(i=>y(e[r-1],i))||n.lang==="py"&&["match","case"].includes(e[r].text)&&V(e,r)&&d(e[A(e,o)+1],":")?!1:d(e[r-1],".")||!Ci[n.lang].has(e[r].text)}function U(e,t={}){let n=e.lang==="py"?Ji(e,!!t.includeMembers,!!t.promptFunctions):Fi(e,!!t.includeMembers,!!t.typedReturns,!!t.declarationPositions);if(!t.includeMembers)return n;for(let o=0;o<e.toks.length;o++){if(!d(e.toks[o],"["))continue;let r=e.toks[o-1];if(o===0||y(r,"return")||r?.kind==="punct"&&"=:(,[>".includes(r.text))for(let[i,l]of j(e.toks,o).entries())n.push({name:`[${i}]`,line:e.toks[l.from].line,from:l.from-1,to:l.to,params:null,kind:"index"})}return n.map(o=>({...o,kind:o.kind??(o.params===null?"value":"function")}))}function oe(e,t){return Pn(e,t).at(-1)?.name??null}function Pn(e,t){return e.filter(n=>n.from<t&&t<n.to).sort((n,o)=>n.from-o.from)}var ji="=+-*/,([{:?.&|<>!%",Ni=".+-*/?:,|&)]}";function ze(e,t,n){let{toks:o}=e,r=0;for(let s=t;s<o.length;s++){n?.(1);let i=o[s];if(i.kind==="punct"&&"([{".includes(i.text))r++;else{if(i.kind==="punct"&&")]}".includes(i.text)&&--r<0)return s;if(r===0&&d(i,";")&&e.lang==="js")return s+1}if(r===0&&s>t&&V(o,s)&&Ti(e,s))return s}return o.length}function Ti(e,t){if(e.lang==="py")return!0;let n=e.toks[t-1],o=e.toks[t],r=n.kind==="punct"&&ji.includes(n.text),s=o.kind==="punct"&&Ni.includes(o.text);return!r&&!s}function it(e,t,n){let{toks:o}=e,r=[];for(let{from:s,to:i}of vt(o,t,n)){let l=s;for(;l<i&&o[l].kind==="punct"&&(o[l].text==="*"||o[l].text===".");)l++;i-s===1&&o[s].kind==="punct"&&["*","/"].includes(o[s].text)||r.push(l<i&&y(o[l])?o[l].text:null)}return n==="py"&&(r[0]==="self"||r[0]==="cls")&&r.shift(),r}function Fi(e,t,n,o){let{toks:r}=e,s=[],i=0;for(let l=0;l<r.length;l++){let a=r[l];if(d(a,"{"))i++;else if(d(a,"}"))i--;else if(y(a,"function")&&!d(r[l-1],".")){let c=Ki(e,l,n);c&&s.push(c)}else if(["const","let","var"].includes(a.text)&&a.kind==="ident"&&y(r[l+1])){let c=Ui(e,l,i===0||t);c&&s.push(c)}else if(t&&y(a,"class")&&y(r[l+1])){let c=r.findIndex((f,u)=>u>l+1&&d(f,"{"));c>=0&&s.push({name:r[l+1].text,line:a.line,from:l,to:A(r,c)+1,params:null,kind:"class"})}else if(t&&y(a)){let c=Wi(e,l,s,o);c&&s.push(c)}}return s}var Di=["public","private","protected","static","readonly","async","get","set"],Bi=["if","for","while","switch","catch","with"];function Wi(e,t,n,o){let{toks:r}=e,s=t;for(d(r[s-1],".")&&y(r[s-2],"this")&&(s-=2);y(r[s-1])&&Di.includes(r[s-1].text);)s--;let i=["{","}",",",";"].some(g=>d(r[s-1],g));if(!V(r,s)&&!i||Bi.includes(r[t].text))return null;let l=t+1;if(d(r[l],"(")){let g=A(r,l)+1;if(d(r[g],":"))for(;g<r.length&&!d(r[g],"{")&&!d(r[g],";");)g++;if(!d(r[g],"{"))return null;if(o&&!i){let m=Pn(n,t).at(-1),x=G(e,t);if(m?.kind!=="class"||x<0||A(r,x)+1!==m.to)return null}return{name:r[t].text,line:r[t].line,from:t,to:A(r,g)+1,params:it(e,l,"js"),kind:"method"}}if(!T(r,l)&&!d(r[l],":"))return null;let c=Pn(n,t).at(-1)?.kind==="class"?ar(e,l,ze(e,l+1)):T(r,l)?l:null,f=c===null?l+1:c+1,u=ze(e,f),p=0;for(let g=f;g<u;g++){if(d(r[g],",")&&p===0){u=g;break}r[g].kind==="punct"&&("([{".includes(r[g].text)?p++:")]}".includes(r[g].text)&&p--)}return{name:r[t].text,line:r[t].line,from:t,to:u,params:null,kind:c===null?"property":"value"}}function Ki(e,t,n){let{toks:o}=e,r=t+1;if(d(o[r],"*")&&r++,!y(o[r]))return null;let s=o[r];if(r++,d(o[r],"<")&&(r=Gi(e,r)),!d(o[r],"("))return null;let i=it(e,r,"js"),l=A(o,r)+1;n&&d(o[l],":")&&d(o[l+1],"{")&&(l=A(o,l+1)+1);for(let a=l;a<o.length&&!d(o[a],";");a++)if(d(o[a],"{"))return{name:s.text,line:o[t].line,from:t,to:A(o,a)+1,params:i};return null}function Gi(e,t){let n=0;for(let o=t;o<e.toks.length;o++)if(d(e.toks[o],"<"))n++;else if(d(e.toks[o],">")&&--n===0)return o+1;return e.toks.length}function Ui(e,t,n){let{toks:o}=e,r=ar(e,t+2);if(r===null)return null;let s=ze(e,r+1),i=zi(e,r+1,s);return!i&&!n?null:{name:o[t+1].text,line:o[t].line,from:t,to:s,params:i}}function ar(e,t,n=e.toks.length){let o=t;if(d(e.toks[o],":")){let r=o+me;for(;o<r&&o<n&&!T(e.toks,o);)o++}return o<n&&T(e.toks,o)?o:null}function zi(e,t,n){let{toks:o}=e,r=y(o[t],"async")?t+1:t;if(y(o[r],"function"))return r++,d(o[r],"*")&&r++,y(o[r])&&r++,d(o[r],"(")?it(e,r,"js"):null;let s=i=>d(o[i],"=")&&d(o[i+1],">");if(y(o[r])&&s(r+1))return[o[r].text];if(!d(o[r],"("))return null;for(let i=A(o,r)+1;i<n;i++)if(s(i))return it(e,r,"js");return null}function Ji(e,t,n){let{toks:o,text:r}=e,s=[];for(let i=0;i<o.length;i++){let l=o[i],a=y(l,"def")&&y(o[i+1])&&d(o[i+2],"("),c=t&&y(l,"class")&&y(o[i+1]);if(a||c){let f=qi(e,a||d(o[i+2],"(")?A(o,i+2)+1:i+2),u=(t||n)&&y(o[i-1],"async")&&o[i-1].line===l.line?o[i-1]:l,p=Se(r,u),g=f+1;for(;g<o.length&&!(V(o,g)&&Se(r,o[g])<=p);)g++;s.push({name:o[i+1].text,line:l.line,from:i,to:g,params:a?it(e,i+2,"py"):null,...c?{kind:"class"}:{}})}else y(l)&&V(o,i)&&(t||Se(r,l)===0)&&Vi(e,i+1)&&s.push({name:l.text,line:l.line,from:i,to:ze(e,i+1),params:null})}return s}function Vi(e,t){let{toks:n}=e;return T(n,t)||d(n[t],":")}function qi(e,t){let n=t;for(;n<e.toks.length&&!d(e.toks[n],":");)n++;return n}function Je(e,t){return e.filter(n=>n.from<t&&t<n.to).at(-1)??null}function Ve(e){let{toks:t}=e,n=[];for(let o=0;o<t.length;o++){if(!y(t[o])||!H(t,o,e))continue;let r=o;for(;d(t[r-1],".")&&y(t[r-2]);)r-=2;if(d(t[r-1],".")&&d(t[r-2],")")){let a=G(e,r-2);r=n.find(f=>f.open===a)?.from??a}let s=A(t,o+1);if(s===t.length)continue;let i=d(t[o-1],".")&&d(t[o-2],")")?o:r,l=t.slice(i,o+1).map(a=>a.text).join("");n.push({from:r,to:s+1,open:o+1,callee:l,args:j(t,o+1)})}return n}function ce(e,t,n){let o=ze(e,t,n);return d(e.toks[o-1],";")?o-1:o}function Nt(e){let{toks:t}=e,n=[];for(let o=0;o<t.length;o++){if(!y(t[o])||d(t[o-1],"."))continue;let r=o+1;if(d(t[r],":")){if(!(e.lang==="js"?["const","let","var"].includes(t[o-1]?.text):V(t,o)))continue;for(;r<o+me&&r<t.length&&!T(t,r)&&![";","{","}"].some(a=>d(t[r],a));)r++}let s=d(t[r],"+");if(s&&r++,!T(t,r))continue;let i=G(e,o);e.lang==="py"&&d(t[i],"(")||(n.push({at:o,name:t[o].text,append:s,from:r+1,to:ce(e,r+1)}),o=r)}return n}function cr(e,t,n=Ve(e)){let{toks:o}=e,{assignments:r,functions:s,owner:i,binding:l,inBlock:a,lexical:c,declarations:f}=t,u=q(e),p=U(e,{includeMembers:!0}),g=p.filter(S=>S.params!==null),m=S=>p.filter(_=>(_.params!==null||_.kind==="class")&&_.from<S&&S<_.to).sort((_,E)=>E.from-_.from)[0]??null,x=(S,_)=>{let E=m(S.from);return a(S.from,_)&&(E===null||E.from<_&&_<E.to)},h=q(e,{namespaceBindings:!0,bindingPositions:!0}).map(S=>{let _=S.bindingAt,E=S.names.map(v=>({local:v,name:S.renamed?.[v]??v,namespace:S.namespaceNames?.includes(v)===!0||e.lang==="js"&&(y(o[_],"require")&&!d(o[_-2],"}")||d(o[_+1],"*"))}));return{module:S,at:_,names:E}}),k=(S,_,E=!1)=>{if(E){if(i(_)?.params?.includes(S)||l(S,_)||s.some(I=>I.name===S))return null;let R=u.filter(I=>I.names.includes(S));return R.length===1?{module:R[0],name:R[0].renamed?.[S]??S,namespace:!1}:null}let v=m(_),O=[...v?.kind==="class"?[v]:[],...g.filter(R=>R.from<_&&_<R.to).sort((R,I)=>I.from-R.from),null];for(let R of O){let I=h.filter(P=>m(P.at)===R&&a(P.at,_)&&P.names.some(M=>M.local===S)),L=r.filter(P=>P.name===S&&m(P.at)===R&&(!c(f.get(P)??P)||a(P.at,_))&&!I.some(M=>y(o[M.at],"require")&&P.from<=M.at&&M.at<P.to)),$=p.filter(P=>P.name===S&&(P.params!==null||P.kind==="class")&&m(P.from)===R&&x(P,_));if(R?.params?.includes(S)||L.length||$.length)return null;if(!I.length)continue;if(I.length!==1||I[0].at>=_&&!(e.lang==="js"&&y(o[I[0].at],"import")))return null;let C=I[0],N=C.names.find(P=>P.local===S);return{module:C.module,name:N.name,namespace:N.namespace}}return null};return{importBinding:k,hasImport:(S,_)=>_?u.some(E=>E.names.includes(S)):h.some(E=>E.names.some(v=>v.local===S)),loaderImport:(S,_)=>{let E=S.callee.split(".")[0];if(_){let O=k(E,S.from);return O?le([O.module],e.lang).find(R=>R.name===E)??null:null}let v=le(u,e.lang).filter(O=>O.name===E);return v.length!==1||i(n.find(O=>O.callee===S.callee)?.open??0)?.params?.includes(E)?null:v[0]}}}function ur(e,t,n={}){let{toks:o}=e,r=Nt(e),s=t.filter(_=>_.params!==null),i=_=>Je(s,_),l=(_,E)=>{let v=i(E);return r.findLast(O=>O.at<E&&O.name===_&&i(O.at)===v)??(v?.params?.includes(_)?void 0:r.findLast(O=>O.at<E&&O.name===_&&i(O.at)===null))},a=[],c=[];for(let _=0;_<o.length;_++)a.push([...c]),d(o[_],"{")?c.push(_):d(o[_],"}")&&c.pop();let f=(_,E)=>a[_].every((v,O)=>a[E]?.[O]===v),u=_=>["const","let"].includes(o[_.at-1]?.text),p=_=>u(_)||y(o[_.at-1],"var"),g=new Map;for(let _ of r)g.set(_,p(_)?_:r.findLast(E=>E.at<_.at&&E.name===_.name&&i(E.at)===i(_.at)&&p(E)&&(!u(E)||f(E.at,_.at))));let m=(_,E,v)=>r.some(O=>O.name===_&&i(O.at)!==E&&v(O.at)&&!g.get(O)&&!i(O.at)?.params?.includes(_)),x=(_,E)=>{let v=i(E);return!m(_,v,O=>v!==null&&v.from<O&&O<v.to)},h=_=>{let E=i(_.at);if(!E?.params?.includes(_.name))return!1;let v=o.findIndex((O,R)=>E.from<R&&R<_.at&&d(O,"("));return v>=0&&_.at<A(o,v)},k=(_,E)=>{let v=i(_.from);return f(_.from,E)&&(v===null||(n.enclosingBindings?v.from<E&&E<v.to:v===i(E)))},w=_=>{for(let E=_.at-1;E>=0&&![";","{","}"].includes(o[E].text);E--){if([")","]"].includes(o[E].text)){E=G(e,E);continue}if(["if","else","for","while","case","and","or"].includes(o[E].text)||["?","&","|"].includes(o[E].text))return!0}return!1};return{assignments:r,functions:s,owner:i,legacyBinding:l,inBlock:f,lexical:u,declarations:g,parameterIsCertain:x,parameterDefault:h,functionVisible:k,bindingIsCertain:(_,E)=>_.at<E&&f(_.at,E)&&(!n.enclosingBindings||!w(_))&&!m(_.name,i(_.at),v=>f(_.at,v)&&(!n.enclosingBindings||i(_.at)===null||i(_.at).from<v&&v<i(_.at).to)),binding:(_,E)=>{let v=i(E),O=r.filter(P=>{if(P.name!==_)return!1;let M=g.get(P);return!M||!u(M)||f(M.at,E)}),R=[...s.filter(P=>P.from<E&&E<P.to).sort((P,M)=>M.from-P.from),null],I=n.enclosingBindings?R.find(P=>P?.params?.includes(_)||O.some(M=>i(M.at)===P)||s.some(M=>M.name===_&&i(M.from)===P&&k(M,E))):void 0,L=O.filter(P=>n.enclosingBindings?i(P.at)===I:i(P.at)===v||!v?.params?.includes(_)&&i(P.at)===null),$=P=>{let M=g.get(P);return M&&u(M)?a[M.at].length:0},C=Math.max(-1,...L.map($)),N=L.filter(P=>$(P)===C);return N.findLast(P=>P.at<E)??N[0]}}}function re(e,t,n={}){let{toks:o}=e,r=Ve(e),s=ur(e,t,n),{assignments:i,functions:l,owner:a,legacyBinding:c,binding:f,bindingIsCertain:u,parameterIsCertain:p,parameterDefault:g,functionVisible:m}=s,{importBinding:x,hasImport:h,loaderImport:k}=cr(e,s,r),w=(E,v=new Set)=>o.slice(E.from,E.to).flatMap((O,R)=>{let I=c(O.text,E.from+R);return O.kind!=="ident"||!I||I.append||v.has(I.at)?[O]:w(I,new Set([...v,I.at]))}),b=E=>{let v=o[E.open-1].text;if(["readFileSync","readFile"].includes(v))return E.args[0]??null;if(!d(o[E.open-2],"."))return null;let O=E.open-3;if(v==="read_text"&&y(o[O]))return{from:E.from,to:O+1};if(!d(o[O],")"))return null;let R=G(e,O),I=r.find(L=>L.open===R);return v==="read_text"?I?.callee==="Path"?I.args[0]??null:{from:R+1,to:O}:v==="read"&&I?.callee==="open"||v==="text"&&I?.callee==="Bun.file"?I?.args[0]??null:null},S=E=>{let[v,...O]=E.callee.split("."),R=x(v,E.open,!n.enclosingBindings);if(R){let L=R.module,$=O.at(-1)??R.name;return(/^(?:node:)?fs(?:\/promises)?$/.test(L.source)?["readFile","readFileSync","readdir","readdirSync"]:/^(?:node:)?path$/.test(L.source)?["join","resolve"]:/^(?:node:)?url$/.test(L.source)?["fileURLToPath"]:L.source==="pathlib"?["Path"]:[]).includes($)?$:null}return(n.enclosingBindings?l.some(L=>L.from<E.open&&E.open<L.to&&L.params?.includes(v)):a(E.open)?.params?.includes(v))||f(v,E.open)||l.some(L=>L.name===v)||h(v,!n.enclosingBindings)||O.length&&!["fs","path","Bun"].includes(v)?null:O.at(-1)??v},_=r.flatMap(E=>{let v=b(E)??(["readFileSync","readFile"].includes(S(E)??"")?E.args[0]:null);return v?[{sourcePath:e.path,line:o[E.open-1].line,call:E,path:v,tokens:w(v)}]:[]});return{source:e,calls:r,assignments:i,functions:l,owner:a,binding:f,bindingIsCertain:u,parameterIsCertain:p,parameterDefault:g,functionVisible:m,pathTokens:w,importBinding:x,loaderImport:k,builtin:S,operations:_}}function ue({source:{toks:e}},t){let{from:n,to:o}=t;for(y(e[n],"await")&&n++;d(e[n],"(")&&A(e,n)===o-1;)n++,o--;return{from:n,to:o}}function ee(e,t){let{from:n,to:o}=ue(e,t);return e.calls.findLast(r=>r.to===o&&(r.from===n||y(e.source.toks[n],"new")&&r.from===n+1))}function $n(e,t){let{toks:n}=e.source,{from:o}=t,r=o+1;if(d(n[o],"(")&&(r=A(n,o)+1,o++),!y(n[o])||!d(n[r],"=")||!d(n[r+1],">"))return null;let s=r+2;return d(n[s],"{")?y(n[s+1],"return")?(s+=2,{name:n[o].text,body:{from:s,to:ce(e.source,s)}}):null:{name:n[o].text,body:{from:s,to:t.to}}}function Y(e,t,n=new Map,o=new Set){let{source:{toks:r,path:s},binding:i,builtin:l}=e,a=ue(e,t),{from:c,to:f}=a;if(c>=f||!r[c])return null;let u=r.slice(c,f).map(b=>b.text).join(""),p=b=>{let S=i(b,c);return!S||e.parameterDefault(S)&&n.has(b)&&n.get(b)!==void 0?e.parameterIsCertain(b,c)?n.get(b)??null:null:e.bindingIsCertain(S,c)&&!S.append&&!o.has(S.at)?Y(e,S,n,new Set([...o,S.at])):null},g=b=>Y(e,b,n,o);if(f===c+1){let b=r[c];if(e.source.lang==="py"&&b.formatted&&b.value.includes("{"))return null;if(b.kind==="string"||b.kind==="template"&&!b.value.includes("${"))return/^(?:[a-z]+:|[/\\])/i.test(b.value)?null:b.value;if(b.kind==="template"){let S=!1,_=b.value.replace(/\$\{([^}]*)\}/g,(E,v)=>{if(!/^[A-Za-z_$][\w$]*$/.test(v))return S=!0,"";let O=p(v);return O==null&&(S=!0),O??""});return S||/^(?:[a-z]+:|[/\\])/i.test(_)?null:_}if(y(b,"__dirname")&&!i(b.text,c)&&!e.owner(c)?.params?.includes(b.text))return`/repository/${lt.dirname(s)}`;if(y(b))return p(b.text)}let m=[];for(let b=c;b<f;b++){if(["(","[","{"].some(S=>d(r[b],S))){b=A(r,b);continue}m.push(b)}let x=m.find(b=>d(r[b],"?")&&d(r[b+1],"?"));if(x!==void 0){let b=g({from:c,to:x});if(b!==null)return b;let S=x===c+1&&y(r[c])&&!i(r[c].text,c)?r[c].text:null;return S&&e.owner(c)?.params?.includes(S)&&e.parameterIsCertain(S,c)&&(!n.has(S)||n.get(S)===void 0)?g({from:x+2,to:f}):null}let h=m.find(b=>d(r[b],"+"));if(h!==void 0){let b=g({from:c,to:h}),S=g({from:h+1,to:f});return b===null||S===null?null:b+S}if(u==="import.meta.url")return`/repository/${s}`;let k=ee(e,a);if(!k)return null;let w=l(k);if(w==="URL"&&k.args.length===2){let b=r.slice(k.args[1].from,k.args[1].to).map(_=>_.text).join(""),S=g(k.args[0]);return b==="import.meta.url"&&S!==null&&!/^(?:[a-z]+:|[/\\])/i.test(S)?lt.join("/repository",lt.dirname(s),S):null}if(w==="fileURLToPath"||w==="Path")return k.args.length===1?g(k.args[0]):null;if(w==="join"||w==="resolve"){let b=k.args.map(g);return b.length&&b.every(S=>S!==null)&&b.every(S=>S.startsWith("/repository/")||!/^(?:[a-z]+:|[/\\])/i.test(S))?w==="resolve"?lt.resolve("/repository",...b):lt.join(...b):null}return null}function fr(e,t){let n=ue(e,t),o=e.source.toks[n.from],r=y(o,"null")||y(o,"undefined")&&!e.binding(o.text,n.from)&&!e.owner(n.from)?.params?.includes(o.text);return n.to===n.from+1&&r?void 0:Y(e,n)}import{posix as Tt}from"node:path";function ge(e,t){if(e===null)return null;let n=e.startsWith("/repository/")?e.slice(12):e.startsWith(".")?Tt.join(Tt.dirname(t),e):e,o=Tt.normalize(n.replace(/\\/g,"/")).replace(/\/$/,"");return o===".."||o.startsWith("../")||/^(?:[a-z]+:|\/)/i.test(o)?null:o}function pr(e,t){return{from:t.from,to:t.open-2}}function Mn(e,t,n,o=new Set){let r=ue(e,t),{source:{toks:s},binding:i}=e;if(r.to===r.from+1&&y(s[r.from])){let p=i(s[r.from].text,r.from);return p&&e.bindingIsCertain(p,r.from)&&!p.append&&!o.has(p.at)?Mn(e,p,n,new Set([...o,p.at])):null}let l=ee(e,r);if(!l)return null;if(["readdirSync","readdir"].includes(e.builtin(l)??"")&&l.args[0]){let p=ge(Y(e,l.args[0],n),e.source.path);return p===null?null:{path:p}}if(s[l.open-1].text!=="filter"||l.args.length!==1)return null;let a=$n(e,l.args[0]),c=a&&ee(e,a.body),f=c?.args[0]&&Y(e,c.args[0]);if(!a||c?.callee!==`${a.name}.endsWith`||!f||!Re.test(`template${f}`))return null;let u=Mn(e,pr(e,l),n,o);return u?{...u,extension:f}:null}function dr(e,t,n,o){let{source:{toks:r}}=e;for(let s of e.calls){if(r[s.open-1].text!=="map"||s.args.length!==1)continue;let i=$n(e,s.args[0]);if(!i||!(i.body.from<=t.from&&t.to<=i.body.to))continue;let l=Mn(e,pr(e,s),o);if(!l?.extension||e.owner(t.open)!==e.owner(s.open)||r.slice(i.body.from,t.from).some((u,p)=>{let g=i.body.from+p;return y(u,"function")||d(u,"=")&&d(r[g+1],">")}))continue;let c=new Map(o).set(i.name,"__template_entry__");if(ge(Y(e,n,c),e.source.path)===Tt.join(l.path,"__template_entry__"))return{kind:"directory",path:l.path,extension:l.extension}}return null}function mr(e,t){let n=e.owner(t.open),o=new Set(e.assignments.filter(r=>e.owner(r.at)===n&&r.from<=t.from&&t.to<=r.to));for(let r of e.assignments)e.owner(r.at)!==n||r.from<=t.from||Ft(e,r,o)&&o.add(r);return o}function Ft(e,t,n){return e.source.toks.slice(t.from,t.to).some((o,r)=>{let s=t.from+r;if(d(e.source.toks[s-1],".")||d(e.source.toks[s+1],":"))return!1;let i=y(o)&&e.binding(o.text,s);return i&&n.has(i)})}function gr(e,t,n,o){if(!t)return!1;let{toks:r}=e.source;for(let i=t.from;i<t.to;i++){if(!y(r[i],"return")||e.owner(i)!==t)continue;let l={from:i+1,to:ce(e.source,i+1)};if(l.from<=n.from&&n.to<=l.to||Ft(e,l,o))return!0}let s=r.findIndex((i,l)=>t.from<l&&l<n.from&&d(i,"=")&&d(r[l+1],">"));return s>=0&&!d(r[s+2],"{")}function Cn(e,t,n,o=!1){let r=(o?n.replace(Re,""):n).replace(/\\/g,"/"),s=c=>o?c.path.replace(Re,""):c.path,i=Dt.dirname(t);for(;;){let c=Dt.normalize(Dt.join(i,r)),f=e.filter(u=>s(u)===c);if(f.length)return f.length===1?f:[];if(i==="."||i==="/")break;i=Dt.dirname(i)}if(r.includes("/"))return[];let l=o?e.filter(c=>s(c)===r||s(c).endsWith(`/${r}`)):rt([...e],r),a=l.length||!o?l:e.filter(c=>ot(s(c))===ot(r));return a.length===1?a:[]}function hr(e){return e.filter(({call:t})=>{let n=t.callee.split(".").at(-1);return n==="readFile"||n==="readFileSync"||["read_text","read","text"].includes(n??"")&&t.from<t.open-1})}function qe(e){return e.filter(t=>Re.test(t))}function xr(e,t,n){let{tokens:o}=e,r=o.filter(a=>a.kind==="string"||a.kind==="template").filter(a=>a.value.length<=200).map(a=>a.value),s=r.map(a=>{let c=Xo.exec(a);return c?a.slice(0,c.index+c[0].length).replace(/\\/g,"/"):null}).find(a=>a!==null)??null,i=qe(r)[0]?.match(/\.[^./\\]+$/)?.[0]??null;if(s===null&&i===null)return null;let l=t.params.findIndex(a=>a!==null&&o.some((c,f)=>y(c,a)&&!d(o[f-1],".")?!0:c.kind!=="template"&&!c.formatted?!1:(c.value.match(/\$?\{[^}]*\}/g)??[]).some(u=>{let p=_t(u.replace(/^\$?\{|\}$/g,""),n);return p.some((g,m)=>y(g,a)&&!d(p[m-1],"."))})));return l<0?null:{folder:s,ext:i,paramIndex:l}}function Xi(e,t,n,o){let r=t.loaderImport(n,X(e));if(!r)return null;let s=Ue({files:o.map(i=>({path:i.source.path}))},{path:t.source.path},r).map(i=>i.path);return{binding:r,paths:s}}function at(e,t){let n=e.builtin(t);if(["readFileSync","readFile"].includes(n??""))return!0;if(!["read_text","read","text"].includes(n??""))return!1;let o=n==="read_text"?"Path":n==="read"?"open":"file";return e.calls.some(r=>r.from===t.from&&r.to<t.to&&e.builtin(r)===o)}function yr(e,t,n,o="anchored"){let r=Object.entries(t).flatMap(([u,p])=>{if(n?.source.path===u)return[re(n.source,n.scopes)];let g=W(u);if(!g)return[];let m=J(u,p,g);return[re(m,U(m))]});n&&!r.some(u=>u.source===n.source)&&r.push(re(n.source,n.scopes));let s=r.flatMap(u=>u.operations);if(o==="operations")return{operations:s,reads:[],dependencies:[]};let i=r.flatMap(u=>u.functions.map(p=>({syntax:u,scope:p}))),l=new Map,a=new Set,c=(u,p)=>{let g=p.callee.split(".")[0];if(u.owner(p.open)?.params?.includes(g))return[];let m=u.binding(g,p.open),x=i.filter(w=>w.syntax===u&&w.scope.name===p.callee&&u.functionVisible(w.scope,p.open));if(x.length)return x.filter(w=>!m||m.at===w.scope.from+1);if(m)return[];let h=Xi(e,u,p,r);if(!h)return[];if(!h.paths.length)for(let w of Lo(u.source.path,h.binding.source,[h.binding.imported],u.source.lang,!0))a.add(w);let k=p.callee.split(".")[1]??h.binding.imported;return i.filter(w=>h.paths.includes(w.syntax.source.path)&&w.scope.name===k&&w.syntax.owner(w.scope.from)===null)};for(let u of r)for(let p of u.calls){let g=c(u,p);for(let m of g){let x=new Map((m.scope.params??[]).flatMap((k,w)=>k===null?[]:[[k,g.length!==1?null:p.args[w]?fr(u,p.args[w]):void 0]])),h=l.get(m.scope)??[];h.push({parameters:x,...g.length===1&&m.syntax!==u?{consumer:u.source.path}:{}}),l.set(m.scope,h)}}let f=[];for(let u of r)for(let p of u.operations){if(!at(u,p.call))continue;let g=u.owner(p.call.open),m=g?l.get(g)??[{parameters:new Map}]:[{parameters:new Map}];for(let x of m){let h=ge(Y(u,p.path,x.parameters),u.source.path),k=h===null?dr(u,p.call,p.path,x.parameters):{kind:"file",path:h};if(!k)continue;let w=mr(u,p.call),b=new Set(x.consumer&&gr(u,g,p.call,w)?[x.consumer]:[]);for(let E of u.calls){if(u.owner(E.open)!==g||!E.args.some(O=>Ft(u,O,w)))continue;let v=c(u,E);v.length===1&&v[0].syntax!==u&&b.add(v[0].syntax.source.path)}let S=f.find(E=>E.sourcePath===p.sourcePath&&E.line===p.line&&JSON.stringify(E.target)===JSON.stringify(k)),_=[...b].sort();S?S.consumerPaths=[...new Set([...S.consumerPaths,..._])].sort():f.push({sourcePath:p.sourcePath,line:p.line,target:k,consumerPaths:_})}}return{operations:s,reads:f,dependencies:[...a].sort()}}var Hi=30;function Sr(e,t){let n=(e?.modelIds??[]).filter(o=>Math.abs(o.line-t)<=Hi);return n.sort((o,r)=>Math.abs(o.line-t)-Math.abs(r.line-t)||o.line-r.line),n[0]??null}function ct(e,t,n,o){let r=Sr(e.byPath.get(t),n);return r||!o?r:Sr(e.byPath.get(o.path),o.line)}function Yi(e,t,n){let o=n.model;if(o?.kind==="literal"&&jt.test(o.text))return t.modelIds.find(p=>p.value===o.text&&p.line>=n.line)??{value:o.text,path:t.path,line:n.line};if(o?.kind!=="member")return null;let[r,s,i]=o.text.split(".");if(!s||i)return null;let l=new Map;for(let p of e.files)for(let g of p.modelMembers??[])l.set(g.object,[...l.get(g.object)??[],g]);let a=Ie(e,t,r,l).filter(p=>p.member===s);if(a.length!==1)return null;let{value:c,path:f,line:u}=a[0];return{value:c,path:f,line:u}}function Zi(e,t,n){if(!n.shape)return;let o=t.imports.find(s=>s.name===n.shape),r=o?Ue(e,t,o):[];return{name:n.shape,path:r.length===1?r[0].path:t.path,line:o?.line??n.line}}function jn(e,t){let n=new Map,o=new Map;for(let i of e.files){for(let l of i.loaders??[])n.set(l.name,[...n.get(l.name)??[],l]);for(let l of i.promptReturns??[])o.set(l.fn,[...o.get(l.fn)??[],l])}let r=e.files.flatMap(i=>i.sites.filter(l=>l.kind==="file")),s=(i,l,a,c=new Set)=>{let f=`${i.path}:${JSON.stringify(l)}`;if(c.has(f)||c.size>=50)return[];let u=new Set([...c,f]);if(l.kind==="site")return i.sites.filter(h=>h.start===l.siteStart).map(h=>({site:h,sdk:i.sdk}));if(l.kind==="symbol"||l.kind==="module-member"){let[h,k]=l.callee.split("."),w=h.replace(/\(\)$/,""),b=(i.promptBindings??[]).filter(R=>R.name===l.callee.replace("().","."));if(!l.importBinding&&b.length)return b.flatMap(R=>R.loads.flatMap(I=>s(i,I,a,u)));let S=l.importBinding?[l.importBinding]:i.imports.filter(R=>R.name===w);if(S.length!==1)return[];let _=S[0],E=Ue(e,i,_);if(E.length!==1)return[];let v=E[0],O=l.kind==="module-member"?k:k?`${_.imported}.${k}`:_.imported;return O?s(v,{kind:"symbol",callee:O,literals:[]},a,u):[]}if(l.kind==="bound-file"||l.kind==="chainlite")return l.literals.flatMap(h=>{let k=l.kind==="bound-file"?[h]:[Bt.join(Bt.dirname(i.path),h),Bt.join(Bt.dirname(i.path),"prompts",h)],w=r.filter(b=>k.includes(b.path));return w.length===1?w.map(b=>({site:b,sdk:l.kind==="chainlite"||i.sdk})):[]});let p=l.kind==="loader"||l.kind==="return",g=p?Ie(e,i,l.callee,n):[];if(g.length)return g.flatMap(h=>l.literals.flatMap(k=>{let w=h.ext&&!k.endsWith(h.ext)?k+h.ext:k,b=h.folder?`${h.folder}/${w}`:w;return Cn(r,h.path,b,!h.ext).map(_=>({site:_,sdk:e.byPath.get(h.path)?.sdk??!1}))}));let m=p&&a?Ie(e,i,l.callee,o):[];return m.length?m.flatMap(h=>h.loads.flatMap(k=>s(e.byPath.get(h.path),k,!1,u))):l.kind==="read"||l.kind==="file-key"?qe(l.literals).flatMap(h=>Cn(r,i.path,h).map(k=>({site:k,sdk:i.sdk}))):[]};for(let i of e.files){if(i.sdk||i.callSites.some(a=>a.kind==="system-arg"))for(let a of i.loadedPromptRefs??[])for(let c of r.filter(f=>f.path===a.value))Oe(t,c,{kind:"L3",callPath:i.path,callLine:a.line,callExcerpt:a.value,wrapper:null,shortLabel:null,sdk:i.sdk,modelId:ct(e,i.path,a.line,null)});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(m=>m.model)?.model??null,shape:a.find(m=>m.shape)?.shape??null},f=a.flatMap(m=>m.loads.flatMap(x=>s(i,x,!0))),u=[...new Map(f.map(m=>[Q(m.site),m.site])).values()];if(!u.length)continue;let p=u.slice(1).map(m=>m.path),g=Zi(e,i,c);Oe(t,u[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||f.some(m=>m.sdk),modelId:Yi(e,i,c),...p.length?{alsoLoads:p}:{},...g?{shape:g}:{}})}}}function wr(e,t,n,o,r=!1){let s=e.files.filter(i=>i.path!==t.path).flatMap(i=>i.sites.filter(l=>l.symbol===n));return On(e,t,o,s,r)}function br(e,t,n){let o=t.sites.filter(s=>s.symbol===n);if(o.length>0)return o;let r=t.imports.find(s=>s.name===n);return r?wr(e,t,r.imported,r):[]}function Qi(e,t,n,o){return wr(e,t,o,n,!0)}function el(e,t,n){let o=(e.wrappers.get(n)??[]).filter(i=>i.path===t.path);if(o.length>0)return o;let r=t.imports.find(i=>i.name===n);if(!r)return[];let s=e.wrappers.get(r.imported)??[];return On(e,t,r,s)}function tl(e,t,n,o){if(n.kind!=="system-arg"||!n.value)return!1;let r=_r(e,t,n.value);for(let s of r)Oe(o,s,{kind:"L1",callPath:t.path,callLine:n.line,callExcerpt:`system prompt ${n.value.text}`,wrapper:null,shortLabel:n.shortLabel??null,sdk:t.sdk,modelId:ct(e,t.path,n.line,null)});return r.length>0}function nl(e,t){return e.args.find(n=>n.name===t.paramName)??e.args.filter(n=>n.name===null)[t.paramIndex]}function _r(e,t,n){return n.kind==="literal"&&n.siteStart!==null?t.sites.filter(o=>o.start===n.siteStart):n.kind==="identifier"?br(e,t,n.text):n.kind==="member"?ol(e,t,n.text):[]}function ol(e,t,n){let o=/^(\w+)\.(\w+)$/.exec(n);if(!o)return[];let r=t.imports.find(s=>s.name===o[1]);return r?Qi(e,t,r,o[2]):/^(?:self|cls|this|[A-Z]\w*)$/.test(o[1])?br(e,t,o[2]):[]}function rl(e,t,n){for(let o of t.wrapperCalls)for(let r of el(e,t,o.name)){let s=nl(o,r);if(s)for(let i of _r(e,t,s))Oe(n,i,{kind:"L2",callPath:t.path,callLine:o.line,callExcerpt:`${o.name}(\u2026)`,wrapper:r,shortLabel:o.shortLiterals.length===1?o.shortLiterals[0]:null,sdk:t.sdk||(e.byPath.get(r.path)?.sdk??!1),modelId:ct(e,t.path,o.line,r)})}}function Nn(e,t=!1){return e.filter(n=>n.sdk||n.callSites.some(o=>o.kind==="system-arg")).flatMap(n=>t?n.priorFileRefs??[]:n.fileRefs)}function uf(e,t){let n=e.flatMap(o=>rt(t,o.value).map(r=>({promptPath:r.path,readerPath:o.path})));return[...new Map(n.map(o=>[JSON.stringify(o),o])).values()]}function kr(e,t){let n=e.files.flatMap(o=>o.sites.filter(r=>r.kind==="file"));if(n.length!==0)for(let o of Nn(e.files)){let r=e.byPath.get(o.path);for(let s of rt(n,o.value))Oe(t,s,{kind:"L3",callPath:r.path,callLine:o.line,callExcerpt:o.value,wrapper:null,shortLabel:null,sdk:r.sdk,modelId:ct(e,r.path,o.line,null)})}}function Er(e,t={}){let n=new Map;for(let a of e.flatMap(c=>c.wrappers))n.set(a.name,[...n.get(a.name)??[],a]);let o={byPath:new Map(e.map(a=>[a.path,a])),files:e,wrappers:n,moduleResolver:t.moduleResolver},r=new Map,s=[];for(let a of e){for(let c of a.callSites)c.kind!=="system-arg"||tl(o,a,c,r)||c.value&&c.value.kind!=="literal"&&s.push({path:a.path,line:c.line});rl(o,a,r)}let i;if(t.includePrior&&e.some(a=>a.priorDeliveries!==void 0)){let a=e.map(f=>f.priorDeliveries===void 0?f:{...f,deliveries:f.priorDeliveries,fileRefs:f.priorFileRefs??f.fileRefs,promptBindings:void 0,loadedPromptRefs:void 0}),c={...o,files:a,byPath:new Map(a.map(f=>[f.path,f]))};i=new Map(r),kr(c,i),jn(c,i)}kr(o,r),jn(o,r);let l=new Set([...r.values()].flat().filter(a=>a.kind==="L4").map(a=>`${a.callPath}:${a.callLine}`));return{links:r,...i?{priorLinks:i}:{},callsWithoutPrompt:s.filter(a=>!l.has(`${a.path}:${a.line}`))}}var ut={named:3,prose:2,file:3,link:4,sdk:1},sl=6,il=3,Rr={L1:0,L2:1,L4:1.5,L3:2};function ft(e,t){return e<t?-1:e>t?1:0}function ll(e){return[...e].sort((n,o)=>Rr[n.kind]-Rr[o.kind]||Number(o.sdk)-Number(n.sdk)||ft(n.callPath,o.callPath)||n.callLine-o.callLine)[0]??null}function al(e){return(e.named?ut.named:0)+(e.prose?ut.prose:0)+(e.kind==="file"?ut.file:0)}function Tn(e,t,n){let o=ll(t),r=n||t.some(i=>i.sdk),s=al(e)+(o?ut.link:0)+(r?ut.sdk:0);return s<il?null:{tier:s>=sl?"strong":"possible",score:s,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:r,modelId:o?.modelId??null,...o?.alsoLoads?.length?{alsoLoads:o.alsoLoads}:{},...o?.shape?{shape:o.shape}:{}}}function Wt(e,t){return(t.selectionScore??t.score)-(e.selectionScore??e.score)||ft(e.prompt.path,t.prompt.path)||e.prompt.line-t.prompt.line}function Or(e,t){let n={files:e},o=new Map(e.map(a=>[a.path,a])),r=t.flatMap(a=>{let c=a.link;if(c?.kind!=="L4")return[];let f=o.get(c.callPath),u=f?.deliveries?.find(g=>g.line===c.callLine&&`${g.callee}(\u2026)`===c.callExcerpt&&(c.callStart===void 0||g.callStart===c.callStart));if(!u)return[];let p=f?.stepCalls?.find(g=>g.callStart===u.callStart&&g.line===u.line);return[{path:c.callPath,candidate:a,delivery:u,enclosingStart:p?.enclosingStart}]}),s=new Map;for(let a of r){let c=a.delivery.enclosing;c&&s.set(c,[...s.get(c)??[],a])}let i=new Map,l=(a,c,f)=>{let u=Q(a.candidate.prompt),p=Q(c.candidate.prompt);if(u===p)return;let g=i.get(u)??[];g.some(m=>m.to===p&&m.kind===f)||g.push({to:p,kind:f}),i.set(u,g)};for(let a of e){let c=r.filter(p=>p.path===a.path),f=[...a.stepCalls??[]];for(let{delivery:p}of c)f.some(g=>vr(g,p))||f.push({callee:p.callee,line:p.line,callStart:p.callStart,enclosing:p.enclosing,resultVar:p.resultVar,argNames:[]});f.sort((p,g)=>p.line-g.line||(p.callStart??0)-(g.callStart??0));let u=new Map;for(let p of f){let g=p.localTarget===null?[]:Ie(n,a,p.callee,s).filter(k=>p.localTarget===void 0||k.enclosingStart===p.localTarget),m=c.filter(k=>k.delivery.enclosing!==null&&k.delivery.enclosing===p.enclosing&&(k.enclosingStart===void 0||p.enclosingStart===void 0||k.enclosingStart===p.enclosingStart));for(let k of m)for(let w of g)l(k,w,"calls");let x=`${p.enclosing??""}:${p.enclosingStart??""}`,h=u.get(x)??new Map;for(let k of p.argNames){let w=h.get(k);if(!(!w||p.argCalls&&Object.hasOwn(p.argCalls,k)&&p.argCalls[k]!==w.callStart))for(let b of w.steps)for(let S of g)l(b,S,"feeds")}p.resultVar&&h.set(p.resultVar,{steps:[...g,...c.filter(k=>vr(p,k.delivery))],callStart:p.callStart}),u.set(x,h)}}return i}function vr(e,t){return e.line===t.line&&e.callee===t.callee&&(t.callStart===void 0||e.callStart===t.callStart)}function Fn(e){let{links:t,callsWithoutPrompt:n,priorLinks:o}=Er(e,{includePrior:!0}),r=new Set([...t.values()].flatMap(f=>f.flatMap(u=>u.alsoLoads??[]))),s=[];for(let f of e)for(let u of f.sites){if(r.has(u.path)&&!(t.get(Q(u))??[]).some(g=>g.kind!=="L3"))continue;let p=Tn(u,t.get(Q(u))??[],f.sdk);if(p&&o){let g=Tn(u,o.get(Q(u))??[],f.sdk);g?.score!==p.score&&(p.selectionScore=g?.score??0)}p&&s.push(p)}s.sort(Wt);let i=Or(e,s);for(let f of s){let u=i.get(Q(f.prompt));u?.length&&(f.links=u)}let l=e.flatMap(f=>f.modelIds).sort((f,u)=>ft(f.path,u.path)||f.line-u.line),a=Nn(e,!0),c=e.flatMap(f=>f.snippets??[]).map(f=>{let u=Fn([f.hits]),p={path:f.hits.path,span:f.span,imports:f.hits.imports,status:"unresolved"};return{...u,strong:u.strong.map(g=>({...g,documentation:p})),possible:u.possible.map(g=>({...g,documentation:p})),documentation:p}});return{...a.length?{filenameReferences:a}:{},strong:[...s.filter(f=>f.tier==="strong"),...c.flatMap(f=>f.strong)].sort(Wt),possible:[...s.filter(f=>f.tier==="possible"),...c.flatMap(f=>f.possible)].sort(Wt),callsWithoutPrompt:[...n,...c.flatMap(f=>f.callsWithoutPrompt)].sort((f,u)=>ft(f.path,u.path)||f.line-u.line),repoModelIds:l,...c.length?{documentedImports:c.map(f=>f.documentation)}:{},scanned:e.length}}import{posix as gt}from"node:path";var cl=40,ul=new Set(["const","let","var","function","class","default","async","interface","enum"]);function fl(e,t){let{toks:n}=e,o=[];for(let r=0;r<n.length;r++){if(!y(n[r],"export"))continue;let s=0,i=t?n.length:Math.min(n.length,r+cl);for(let l=r+1;l<i&&(d(n[l],"{")&&s++,d(n[l],"}")&&s--,!(d(n[l],";")||(!t||s===0)&&y(n[l])&&ul.has(n[l].text)));l++)if((!t||s===0)&&y(n[l],"from")&&K(n[l+1])){o.push(n[l+1].value);break}}return o}function Kt(e,t,n,o=!1){let r=typeof o=="boolean"?o:o.allReexports===!0,s=typeof o=="object"&&o.completeImports===!0,i=J(e,t,n),l=q(i,{bindingPositions:s,namespaceBindings:s,completeImports:s});if(n==="py"){if(!s)return l;let p=l.flatMap(h=>h.namespaceNames?[{...h,names:[]}]:h.names.length?h.names.map(k=>({...h,names:[h.renamed?.[k]??k]})):[h]),g=new Set(["importlib",...l.filter(h=>h.source==="importlib").flatMap(h=>h.namespaceNames??[])]),m=new Set(l.filter(h=>h.source==="importlib"&&!h.namespaceNames).flatMap(h=>h.names.filter(k=>(h.renamed?.[k]??k)==="import_module"))),{toks:x}=i;for(let h=0;h<x.length;h++){let k=y(x[h],"__import__")&&!d(x[h-1],".")&&!y(x[h-1],"def"),w=y(x[h],"import_module")&&d(x[h-1],".")&&y(x[h-2])&&g.has(x[h-2].text)&&!d(x[h-3],".")||y(x[h])&&m.has(x[h].text)&&!d(x[h-1],".")&&!y(x[h-1],"def");if(!k&&!w||!d(x[h+1],"("))continue;let b=x[h+2],S=b?.kind==="string"&&!/^f/i.test(b.text)&&d(x[h+3],")");p.push({source:S?b.value:"?",names:[],line:x[h].line,bindingAt:h,...S?{}:{dynamic:!0}})}return p}let a=[],{toks:c}=i,f=new Set(s?U(i,{includeMembers:!0,typedReturns:!0,declarationPositions:!0}).filter(p=>p.kind==="method").map(p=>p.from):[]);if(s)for(let p=0;p<c.length;p++){if(!y(c[p],"import")&&!y(c[p],"require")||d(c[p-1],".")||!H(c,p,i)||f.has(p))continue;let g=c[p+2];(!K(g)||!d(c[p+3],")")||g.kind==="template"&&g.value.includes("${"))&&a.push({source:"?",names:[],line:c[p].line,bindingAt:p,dynamic:!0})}let u=new Set(a.map(p=>p.bindingAt));return[...l.filter(p=>!u.has(p.bindingAt)),...fl(i,r).map(p=>({source:p,names:[]})),...a]}function pt(e,t){let{toks:n}=e;if(d(n[t],"(")){let o=Dn(e,t+1);return o&&d(n[o.next],")")?{...o,next:o.next+1}:null}return d(n[t],"[")?dl(e,t):Dn(e,t)}function Dn(e,t){let{toks:n}=e,o=[],r=t;for(;K(n[r]);)o.push(n[r]),r++,d(n[r],"+")&&K(n[r+1])&&r++;return o.length===0?null:{start:o[0].start,line:o[0].line,endLine:o[o.length-1].endLine,text:o.map(s=>s.value).join(""),partStarts:o.map(s=>s.start),next:r,...o.some(Bn)?{filledAtRunTime:!0}:{}}}function Bn(e){return!!e.formatted&&(e.kind==="template"||pl(e.value))}function pl(e){for(let t=0;t<e.length;t++)if(e[t]==="{"){if(e[t+1]==="{"){t++;continue}return e.indexOf("}",t+1)>=0}return!1}function dt(e,t,n=e.toks.length){let{toks:o}=e;if(e.lang==="py")for(;t<n&&d(o[t],"(");)t++;if(e.lang==="py"&&y(o[t],"lambda")){for(let r=t+1;r<n;r++){if(d(o[r],":"))return r+1;["(","[","{"].some(s=>d(o[r],s))&&(r=A(o,r))}return null}if(e.lang!=="js")return null;for(;t<n;){let r=y(o[t],"async")?t+1:t,s=d(o[r],"(")?A(o,r):-1,i=s>=0?s+1:y(o[r])?r+1:-1;if(d(o[i],":")){let l=Math.min(n,i+me);for(;i<l&&!d(o[i],"=");)i++}if(i>=0&&i+2<n&&d(o[i],"=")&&d(o[i+1],">"))return i+2;if(s<0)return null;t=r+1,n=Math.min(n,s)}return null}function dl(e,t){let{toks:n}=e,o=t+1;if(!d(n[o],"{"))return null;let r=A(n,o),s=d(n[r+1],",")?r+2:r+1;if(!d(n[s],"]"))return null;for(let i=o+1;i<r;i++){let l=n[i];if((y(l)&&l.text==="text"||l.kind==="string"&&l.value==="text")&&d(n[i+1],":")){let c=Dn(e,i+2);return c&&{...c,next:s+1}}}return null}var Wn={kind:"other",text:"",siteLine:null,siteStart:null};function te(e,t,n,o=e.toks.length,r=!1){let{toks:s}=e,i=r?dt(e,n,o):null,l=pt(e,i??n);if(i!==null&&(!l||!t.has(l.start)))return Wn;if(l&&l.next<=o){let f=t.get(l.start)??null;return{kind:"literal",text:ke(l.text),siteLine:f,siteStart:f===null?null:l.start}}if(!y(s[n]))return Wn;let a=n+1,c=!1;for(;;){let f=d(s[a],"?")&&d(s[a+1],".")?a+1:a;if(!d(s[f],".")||!y(s[f+1]))break;a=f+2,c=!0}return a<o&&!ml(s[a],V(s,a))?Wn:{kind:c?"member":"identifier",text:e.text.slice(s[n].start,s[a-1].end),siteLine:null,siteStart:null}}function ml(e,t){return t||e.kind==="punct"&&",)}];".includes(e.text)}var Ir=new Set(["system","systemPrompt","system_prompt","instructions"]);function Kn(e,t){let n=Le(e.toks[t-2]);if(n===null||!Ir.has(n)||Lr(e,t-2)!==t)return!1;let o=G(e,t-2);if(e.lang==="py"&&e.toks[t-2].kind==="ident")return H(e.toks,o-1,e)&&!d(e.toks[t-3],".");if(!d(e.toks[o],"{"))return!1;let r=G(e,o);if(!H(e.toks,r-1,e))return!1;let s=o-1;return e.lang==="py"&&(d(e.toks[s],"*")&&d(e.toks[s-1],"*")||d(e.toks[s],"=")&&y(e.toks[s-1]))&&(s-=2),s===r||d(e.toks[s],",")}function he(e,t,n,o=!1,r=!1){let s=[];return e.toks.forEach((i,l)=>{let a=Lr(e,l);if(a===null)return;let c=gl(e,n,a,r&&Kn(e,a)),f=o?hl(e,l):null;s.push({valueAt:a,site:{kind:"system-arg",path:e.path,line:i.line,value:c,enclosing:oe(t,l),...f?{shortLabel:f}:{}}})}),s}function gl(e,t,n,o){let{toks:r}=e,s=te(e,t,n,r.length,o);if(s.kind!=="other")return s;if(d(r[n],"[")){let l=A(r,n);for(let a=n+1;a<l;a++)if(Le(r[a])==="text"&&d(r[a+1],":"))return te(e,t,a+2)}let i=d(r[n+1],"?")&&d(r[n+2],"?")||d(r[n+1],"|")&&d(r[n+2],"|");return y(r[n])&&i?te(e,t,n,n+1):s}var Le=e=>e?.kind==="string"?e.value:e?.kind==="ident"?e.text:null;function hl(e,t){let{toks:n}=e,o=0;for(let r=t-1;r>=0;r--){let s=n[r];if(s.kind==="punct"){if(")]}".includes(s.text))o++;else if("([{".includes(s.text)){if(o>0){o--;continue}let i=e.lang==="js"&&d(s,"{")?r-1:r;return!d(n[i],"(")||!xl(e,i-1)||e.lang==="js"&&i===r?null:yl(e,r)}}}return null}function xl(e,t){let{toks:n}=e;if(e.lang==="js"&&d(n[t],">")){let o=0;do d(n[t],">")&&!d(n[t-1],"=")?o++:d(n[t],"<")&&o--,t--;while(t>=0&&o>0)}return y(n[t],"Agent")}function yl(e,t){let{toks:n}=e;for(let{from:o,to:r}of j(n,t).reverse()){let s=n[o],i=(y(s,"get")||y(s,"set"))&&(Le(n[o+1])==="name"||d(n[o+1],"["));if(d(s,".")||d(s,"[")||d(s,"*")||i)return null;if(Le(s)!=="name")continue;let l=e.lang==="py"?T(n,o+1):d(n[o+1],":"),a=n[o+2];if(!l||r!==o+3||a?.kind!=="string")return null;let{prefix:c,closed:f}=Be(a);return f&&!/[fb]/i.test(c)&&a.value.trim()||null}return null}function Lr(e,t){let{toks:n}=e,o=n[t],r=Le(o),s=l=>T(n,l),i=l=>d(n[l],":")||e.lang==="py"&&s(l);return r!==null&&Ir.has(r)?(e.lang==="py"&&o.kind==="ident"?s(t+1):i(t+1))?e.lang==="js"&&kl(e,t)?null:t+2:e.lang==="js"&&o.kind==="ident"&&(d(n[t-1],"{")||d(n[t-1],","))&&(d(n[t+1],",")||d(n[t+1],"}"))&&!Ln(e,t)?t:null:r==="role"&&i(t+1)&&n[t+2]?.kind==="string"&&n[t+2].value==="system"?Sl(e,t+3):(d(o,"(")||d(o,"["))&&n[t+1]?.kind==="string"&&n[t+1].value==="system"&&d(n[t+2],",")?t+3:y(o,"SystemMessage")&&d(n[t+1],"(")?Le(n[t+2])==="content"&&i(t+3)?t+4:t+2:null}function Sl(e,t){let{toks:n}=e;if(!d(n[t],",")||Le(n[t+1])!=="content")return null;let o=n[t+2];return d(o,":")||d(o,"=")?t+3:null}function kl(e,t){let n=e.toks[t+2];return y(n)&&ir(n.text)||Ln(e,t)}function Ar(e,t,n,o,r={}){let s=W(e);if(!s)return[];let i=J(e,t,s),{toks:l}=i,a=q(i),c=U(i,{includeMembers:!0}),f=mt(i,"default");f?.name==="default"&&c.push(f),c.sort((x,h)=>x.from-h.from||h.to-x.to);let u=[],p=El(i),g=_l(i,o),m=x=>c.filter(h=>h.params!==null&&h.from<x&&x<h.to).at(-1)?.name??null;for(let x of Kt(e,t,s,!0)){let h=a.find(S=>S.source===x.source&&S.names.join("\0")===x.names.join("\0")),k=h?.names.map(S=>({name:S,imported:h.defaultName===S?"default":h.renamed?.[S]??S}))??bl(i,x.source),w=h?.line??l.find(S=>S.kind==="string"&&S.value===x.source)?.line??1,b=wl(i,w);for(let{name:S,imported:_}of k){let E=pe(e,x.source,[_],s,n,!0)??null,v={from:e,to:E,symbol:S,imported:_,source:x.source,...E?{}:{reason:x.source.startsWith(".")?"missing":"external"}},O=l.some((L,$)=>$>b&&y(L,S)&&T(l,$+1))||c.some(L=>L.name===S&&L.from>b&&!c.some($=>$.from<L.from&&L.from<$.to&&($.params!==null||$.kind==="class")));if(O)continue;let R=Pr(i,S);for(let L of R)u.push({...v,symbol:L,kind:"import",usage:"reexport",within:null,span:{from:w,to:w}});let I=h?l.flatMap((L,$)=>!O&&y(L,S)&&$>b&&!["def","function","class"].includes(l[$-1]?.text??"")&&(!d(l[$-1],".")||d(l[$-2],".")&&d(l[$-3],"."))&&!c.some(C=>C.from<$&&$<C.to&&C.params?.includes(S))?[$]:[]):[];if(!I.length&&!R.length){let L=ne(r,"CF_IMPORT_LEXICAL_FACTS")?m(l.findIndex($=>$.line===w)):null;u.push({...v,kind:"import",usage:L?"reference":"reexport",within:L,span:{from:w,to:w}})}for(let L of I){let $=p.find(M=>M.from<=L&&L<M.to),C=!g||g.from<=($?.at??L)&&($?.at??L)<g.to,N=$&&!C&&($.kind!=="tool-registration"||g?.to===0),P=$&&(C||N)?$.kind:"import";u.push({...v,...N?{reason:"unlinked"}:{},kind:P,usage:H(l,L,i)?"call":"reference",within:m(L),span:{from:Math.min(l[$?.at??L].line,l[L].line),to:Math.max(l[$?.at??L].endLine,l[L].endLine)}})}}if(!k.length){let S=pe(e,x.source,[],s,n,!0)??null;u.push({from:e,to:S,kind:"import",symbol:"*",imported:"*",source:x.source,usage:"reexport",within:null,span:{from:w,to:w},...S?{}:{reason:x.source.startsWith(".")?"missing":"external"}})}}for(let x=0;x<l.length;x++)!y(l[x])||!["import","import_module","require"].includes(l[x].text)||!d(l[x+1],"(")||l[x+2]?.kind==="string"&&d(l[x+3],")")||u.push({from:e,to:null,kind:"import",symbol:"*",imported:"*",source:"",usage:"call",within:m(x),reason:"dynamic",span:{from:l[x].line,to:l[x].endLine}});return u.filter((x,h)=>u.findIndex(k=>JSON.stringify(k)===JSON.stringify(x))===h)}function wl(e,t){let{toks:n}=e,o=n.findIndex(r=>r.line===t);for(let r=o;r<n.length;r++){if(e.lang==="py"&&n[r].line>t)return r-1;if(d(n[r],";")||e.lang==="js"&&n[r].kind==="string")return r}return n.length-1}function bl(e,t){let{toks:n}=e,o=[];for(let r=0;r<n.length;r++){if(!y(n[r],"export"))continue;let s=r+1;if(!d(n[s],"{"))continue;let i=A(n,s);!y(n[i+1],"from")||n[i+2]?.value!==t||o.push(...j(n,s).flatMap(l=>y(n[l.from])?[{name:n[l.to-1].text,imported:n[l.from].text}]:[]))}return o}function Pr(e,t){let{toks:n}=e,o=[];for(let r=0;r<n.length;r++)if(!(!y(n[r],"export")||!d(n[r+1],"{"))&&!y(n[A(n,r+1)+1],"from"))for(let s of j(n,r+1))y(n[s.from],t)&&o.push(n[s.to-1].text);return o}function mt(e,t){let n=U(e),{toks:o}=e;if(t==="default"){let s=o.findIndex((i,l)=>y(i,"default")&&y(o[l-1],"export"));if(s>=0){let i=s+1;y(o[i],"async")&&i++;let l=y(o[i],"function"),a=l?i+1:i;if(y(o[a])&&(t=o[a].text),d(o[a],"(")){let c=A(o,a),f=l?c+1:c+3;if(l||d(o[c+1],"=")&&d(o[c+2],">")){let u=d(o[f],"{")?A(o,f)+1:o.findIndex((p,g)=>g>=f&&d(p,";"));return{name:"default",line:o[i].line,from:i,to:u<0?o.length:u,params:j(o,a).map(p=>y(o[p.from])?o[p.from].text:null),kind:"function"}}}}}let r=n.find(s=>s.name===t);if(r)return r;for(let s of n)if(Pr(e,s.name).includes(t))return s;return null}function _l(e,t){if(!t||t.path!==e.path)return null;let{toks:n}=e,o=new Set([t.symbol]);for(let a of q(e))for(let c of a.names)(a.renamed?.[c]??c)===t.symbol&&o.add(c);let r=new Map;t.promptPath===e.path&&t.promptStart!==void 0&&r.set(t.promptStart,t.line??1);let s=he(e,[],r).filter(({site:a})=>(t.line===void 0||a.line===t.line)&&(a.value?.kind==="identifier"&&o.has(a.value.text)||a.value?.siteStart!=null&&a.value.siteStart===t.promptStart)),i=s.length===1?s[0].valueAt:void 0,l=[];for(let a=0;a<n.length;a++){if(!H(n,a,e))continue;let c=A(n,a+1);(t.callStart!==void 0?n[a].start===t.callStart:i!==void 0?a<i&&i<c:t.line!==void 0&&n[a].line<=t.line&&(n[c]?.endLine??0)>=t.line)&&l.push({from:a,to:c+1})}return i!==void 0||t.callStart!==void 0?l.at(-1)??{from:0,to:0}:l.length===1?l[0]:{from:0,to:0}}function El(e){let{toks:t}=e,n=[],o=(r,s,i)=>{if(s&&(n.push({...s,at:r,kind:i}),s.to===s.from+1&&y(t[s.from]))){let l=t.flatMap((a,c)=>y(a,t[s.from].text)&&d(t[c+1],"=")?[c+2]:[]);l.length===1&&d(t[l[0]],"[")&&n.push({from:l[0],to:A(t,l[0])+1,at:r,kind:i})}};for(let r=0;r<t.length;r++){let s=t[r].kind==="string"?t[r].value:t[r].text;if(["tools","state_schema","context_schema","config_schema","model_config","llm_config"].includes(s)&&(d(t[r+1],"=")||d(t[r+1],":"))){let l=r+2,a=d(t[l],"[")?A(t,l)+1:l+1;o(r,{from:l,to:a},s==="tools"?"tool-registration":"config")}if(!d(t[r+1],"("))continue;let i=j(t,r+1);["add_node","addNode"].includes(s)&&o(r,i[1],"graph-node"),["StateGraph"].includes(s)&&o(r,i[0],"config"),["bind_tools","bindTools","ToolNode"].includes(s)&&o(r,i[0],"tool-registration")}return n}function Qf(e){return[...e].filter(t=>gt.basename(t)==="langgraph.json")}function Mr(e,t,n,o={}){if(gt.basename(e)==="langgraph.json")return Rl(e,t,n,o.root);if(W(e)!=="py")return[];let r=J(e,t,"py"),{toks:s}=r,i=U(r),l=re(r,i,{enclosingBindings:!0}),a=o.root?`${o.root}/llm_config.yaml`:"llm_config.yaml",c=[],f=new Map;for(let u of l.calls){if(u.callee.includes("."))continue;let p=l.importBinding(u.callee,u.from);p?.module.source!=="chainlite"||p.name!=="llm_generation_chain"||s.some((g,m)=>y(g,u.callee)&&g.line!==p.module.line&&!d(s[m+1],"(")&&l.importBinding(u.callee,m)?.module===p.module)||s.some((g,m)=>y(g,"import")&&d(s[m+1],"*"))||f.set(u.callee,[...f.get(u.callee)??[],u.from])}for(let[u,p]of f){let g=o.call?.path===e?o.call:void 0,m=p.filter(x=>g?.callStart!==void 0?s[x].start===g.callStart:g?.line===void 0||s[x].line===g.line);for(let x of p){let h=A(s,x+1),k=i.filter(w=>w.params!==null&&w.from<x&&x<w.to).at(-1)?.name??null;c.push({from:e,to:n.has(a)?a:null,kind:"config",symbol:u,imported:"*",source:a,usage:"call",within:k,span:{from:s[x].line,to:s[Math.min(h,s.length-1)].endLine},...n.has(a)?g&&(m.length!==1||m[0]!==x)?{reason:"unlinked"}:{}:{reason:"missing"}})}}return c}function Rl(e,t,n,o){let r=()=>[{from:e,to:null,kind:"graph-node",symbol:"graphs",imported:"*",source:"",usage:"reference",within:null,span:{from:1,to:Math.max(1,t.split(`
5
- `).length)},reason:"dynamic"}],s;try{s=JSON.parse(t)}catch{return r()}if(!$r(s)||!$r(s.graphs))return[];let i=s.graphs,l=J(e,t,"js"),{toks:a}=l,c=j(a,0).filter(u=>a[u.from]?.value==="graphs");if(c.length!==1)return r();let f=j(a,c[0].from+2);return f.map(u=>{let p=a[u.from].value,g=i[p],m=f.filter(w=>a[w.from].value===p).length!==1,x=typeof g=="string"?/^(.+):([A-Za-z_$][\w$]*)$/.exec(g):null,h=null,k;if(m||!x)k="dynamic";else if(/^[a-z][a-z\d+.-]*:\/\//i.test(x[1])||!x[1].includes("/")&&!W(x[1]))k="external";else{let w=gt.normalize(gt.join(gt.dirname(e),x[1]));!x[1].startsWith("/")&&!x[1].includes("\\")&&!/^[A-Za-z]:/.test(x[1])&&w!==".."&&!w.startsWith("../")&&B(w,o)!==null&&W(w)&&n.has(w)?h=w:k="missing"}return{from:e,to:h,kind:"graph-node",symbol:p,imported:x?.[2]??"*",source:typeof g=="string"?g:"",usage:"reference",within:p,span:{from:a[u.from].line,to:a[u.to-1].endLine},...k?{reason:k}:{}}})}function ep(e,t,n,o,r={}){let s=W(e);if(!s)return[];let i=J(e,t,s),{toks:l}=i,a=mt(i,n);if(!a||a.params!==null)return[];let c=l.findIndex((w,b)=>b>=a.from&&b<a.to&&T(l,b));if(c<0)return[];let f=y(l[c+1])&&d(l[c+2],".")&&y(l[c+3],"compile"),u=f?l[c+1].text:n,p=f?mt(i,u):a;if(!p||!l.slice(p.from,p.to).some(w=>y(w,"StateGraph")))return[];if([n,u].some(w=>l.filter((b,S)=>y(b,w)&&T(l,S+1)).length!==1))return[];let g=U(i),m=w=>g.filter(b=>b.params!==null&&b.from<w&&w<b.to).map(b=>b.from).join(","),x=[{from:p.from,to:p.to}];for(let w=0;w<l.length;w++)y(l[w],u)&&d(l[w+1],".")&&["add_node","addNode"].includes(l[w+2]?.text)&&d(l[w+3],"(")&&m(w)===m(p.from)&&x.push({from:w,to:A(l,w+3)+1});let h=[];for(let w of x)for(let b=w.from;b<w.to;b++){if(!["add_node","addNode"].includes(l[b]?.text)||!d(l[b+1],"(")||m(b)!==m(p.from))continue;let S=j(l,b+1)[1];if(!S||S.to!==S.from+1||!y(l[S.from]))continue;let _=l[S.from].text;!Cr(i,_)||l.some((v,O)=>y(v,_)&&T(l,O+1))||h.push({from:e,to:e,kind:"graph-node",symbol:_,imported:_,source:_,usage:"reference",within:null,span:{from:l[b].line,to:l[S.from].endLine}})}return[...Ar(e,t,o,void 0,r).filter(w=>(w.kind==="config"||w.kind==="graph-node")&&x.some(b=>l.slice(b.from,b.to).some(S=>y(S,w.symbol)&&S.line>=w.span.from&&S.line<=w.span.to))),...h].filter((w,b,S)=>S.findIndex(_=>JSON.stringify(_)===JSON.stringify(w))===b)}function tp(e,t,n,o){let r=W(e);if(!r||o?.path!==e)return!1;let s=J(e,t,r),i=Cr(s,n);if(!i)return!1;let l=(a,c)=>o.callStart!==void 0?s.toks[a].start<=o.callStart&&s.toks[c-1].end>o.callStart:o.line!==void 0&&s.toks[a].line<=o.line&&s.toks[c-1].endLine>=o.line;return l(i.from,i.to)&&(o.callStart!==void 0||U(s).filter(a=>a.params!==null&&l(a.from,a.to)).length===1)}function Cr(e,t){let n=mt(e,t);return n&&n.params!==null&&U(e).filter(o=>o.name===n.name).length===1?n:null}function $r(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Xe=50,vl=new Set(["replace","replaceAll","format","format_messages","formatMessages"]),Ol=new Set(["withStructuredOutput","with_structured_output","bind","bind_tools","bindTools"]);function jr(e,t){let n=e.source,{toks:o}=n,r=(p,g)=>{let m=e.importBinding(p,g),x=m&&le([m.module],n.lang).find(h=>h.name===p);return x?{namespace:m.namespace,importBinding:x}:null},s=p=>[...new Map(p.map(g=>[JSON.stringify(g),g])).values()].slice(0,Xe),i=p=>{let g=j(o,p),m=g.map(h=>o[h.from]);return!g.every(h=>(y(o[h.from])||o[h.from].kind==="string")&&(d(o[h.from+1],":")||y(o[h.from])&&h.to===h.from+1))||new Set(m.map(h=>h.value||h.text)).size!==m.length?null:g},l=(p,g)=>e.functions.some(m=>m.from<g&&g<m.to&&m.params?.includes(p)),a=(p,g)=>{let m=/^([A-Za-z_$][\w$]*)(\(\))?(?:\.([A-Za-z_$][\w$]*))?$/.exec(p.trim()),x=m&&r(m[1],g);return!m||!x?[]:[{kind:x.namespace&&m[3]&&!m[2]?"module-member":"symbol",callee:`${m[1]}${m[2]&&m[3]?"()":""}${m[3]?`.${m[3]}`:""}`,literals:[],importBinding:x.importBinding}]},c=(p,g,m)=>{let x=r(p,g);if(x)return[{kind:"symbol",callee:p,literals:[],importBinding:x.importBinding}];let h=e.binding(p,g);return h&&e.bindingIsCertain(h,g)&&!h.append&&!m.has(h.at)&&(!l(p,g)||e.owner(h.at)===e.owner(g))?f(h,new Set([...m,h.at])):[]},f=(p,g=new Set)=>{let m=ue(e,p),{from:x,to:h}=m;if(x>=h||!o[x])return[];let k=t.find(b=>b.start===o[x].start);if(K(o[x])&&h===x+1){let b=k?[{kind:"site",callee:"",literals:[],siteStart:k.start}]:[];if(h===x+1&&o[x].kind==="template")for(let S of o[x].value.matchAll(/\$\{([^{}]*)\}/g))b.push(...a(S[1],x));return s(b)}if(h===x+1&&y(o[x]))return c(o[x].text,x,g);let w=ee(e,m);if(w){let b=o[w.open-1].text;if(vl.has(b)&&d(o[w.open-2],"."))return f({from:w.from,to:w.open-2},g);let S=e.operations.find(_=>_.call.from===w.from&&_.call.to===w.to);if(S&&at(e,w)){let _=ge(Y(e,S.path),n.path);return _?[{kind:"bound-file",callee:w.callee,literals:[_]}]:[]}if(!w.args.length)return a(w.callee,x)}if(d(o[x],"[")&&A(o,x)===h-1)return s(j(o,x).flatMap(b=>f(b,g)));if(d(o[x],"{")&&A(o,x)===h-1){let b=i(x);if(!b)return[];let S=v=>b.find(O=>(y(o[O.from],v)||o[O.from]?.value===v)&&d(o[O.from+1],":")),_=S("role"),E=S("content");return _&&E&&["system","user"].includes(o[_.from+2]?.value)?f({from:E.from+2,to:E.to},g):[]}if(h===x+3&&y(o[x])&&d(o[x+1],".")&&y(o[x+2]))return a(`${o[x].text}.${o[x+2].text}`,x);if(d(o[h-2],".")&&y(o[h-1])){let b=ee(e,{from:x,to:h-2});if(b&&!b.args.length)return a(`${b.callee}().${o[h-1].text}`,x)}return[]},u=(p,g=new Set)=>{let m=ue(e,p),{from:x,to:h}=m;if(h===x+1&&y(o[x])){let E=o[x].text,v=e.binding(E,x);return!!v&&e.bindingIsCertain(v,x)&&!v.append&&!g.has(v.at)&&(!l(E,x)||e.owner(v.at)===e.owner(x))&&u(v,new Set([...g,v.at]))}let k=ee(e,m);if(!k)return!1;let w=o[k.open-1].text;if(Ol.has(w))return u({from:k.from,to:k.open-2},g);let b=k.callee.split(".")[0],S=e.importBinding(b,x),_=k.callee.includes(".")?k.callee.split(".").at(-1):S?.name??b;return!!S&&Ot(S.module.source,n.lang)&&/^(?:Chat(?!Prompt|Message|History)|AzureChat|BaseChat|LLM)/.test(_)};return{values:f,modelValue:u,objectFields:i,unique:s}}var Il=new Set(["invoke","ainvoke","batch","abatch","stream","astream"]);function Nr(e,t,n){let o=re(e,t,{enclosingBindings:!0}),{toks:r}=e,{values:s,modelValue:i,objectFields:l,unique:a}=jr(o,n),c=o.assignments.filter(m=>o.owner(m.at)===null).filter(m=>o.assignments.filter(x=>x.name===m.name&&o.owner(x.at)===null).length===1).filter(m=>o.bindingIsCertain(m,r.length)).map(m=>({name:m.name,loads:s(m,new Set([m.at]))})).filter(m=>m.loads.length).slice(0,Xe),f=[],u=Mr(e.path,e.text,new Set),p=(m,x,h=null)=>{if(!x.length||f.length===Xe)return;let k=o.assignments.find(w=>ee(o,w)===m);f.push({path:e.path,line:r[m.from].line,callStart:r[m.from].start,callee:m.callee,key:null,loads:a(x),model:h,shape:null,enclosing:o.owner(m.from)?.name??null,resultVar:k?.name??null})};for(let m of o.calls){if(u.some(x=>x.symbol===m.callee&&x.span.from===r[m.from].line)){let x=m.args[0],h=x&&Y(o,x),k=m.args.find(w=>y(r[w.from],"engine")&&d(r[w.from+1],"="));h&&p(m,[{kind:"chainlite",callee:m.callee,literals:[h]}],k?te(e,new Map,k.from+2,k.to):null);continue}Il.has(r[m.open-1].text)&&d(r[m.open-2],".")&&i({from:m.from,to:m.open-2})&&m.args[0]&&p(m,s(m.args[0]))}for(let m=0;m<r.length&&c.length<Xe;m++){let x=y(r[m],"return")?o.owner(m):null;if(!x||o.owner(x.from)!==null||o.functions.filter(k=>k.name===x.name).length!==1||o.assignments.some(k=>k.name===x.name)||r.filter((k,w)=>y(k,"return")&&o.owner(w)===x).length!==1||r.slice(x.from,m).some(k=>k.kind==="ident"&&["if","for","while","switch","try","catch"].includes(k.text)))continue;if(d(r[m+1],"{")){let k=l(m+1);if(!k)continue;for(let w of k){let b=r[w.from];if(!y(b)&&b.kind!=="string")continue;let S=d(r[w.from+1],":")?w.from+2:w.from,_=s({from:S,to:w.to});_.length&&c.length<Xe&&c.push({name:`${x.name}.${b.value||b.text}`,loads:_})}continue}let h=s({from:m+1,to:ce(e,m+1)});h.length&&c.push({name:x.name,loads:h})}let g=o.operations.flatMap(m=>{if(!at(o,m.call))return[];let x=ge(Y(o,m.path),e.path);return x?[{value:x,path:e.path,line:m.line}]:[]});return{bindings:c,deliveries:f,loadedRefs:g}}function Gt(e,t,n){let o=e.split(`
6
- `),r=Math.min(Math.max(t-1-3,0),o.length-1),s=0;for(let i=0;i<r;i++)s+=o[i].length+1;return{text:e.slice(s,s+n),fromLine:r+1}}var Ll=new Map([["python","py"],["py","py"],["javascript","js"],["js","js"]]);function Tr(e,t,n){return t.filter(o=>/\.md$/i.test(o)&&Po(e,o)&&we(e,o,n)?.kind==="example")}function Ut(e,t){if(!/\.md$/i.test(e))return[];let n=[],o,r=0,s=t.split(`
7
- `);for(let i=0;i<s.length;i++){let l=s[i].replace(/\r$/,""),a=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(l);if(a){let c=a[1][0],f=a[1].length,u=a[2].trim();o?c===o.marker&&f>=o.width&&!u&&(o.lang&&r>o.start&&n.push({path:e,lang:o.lang,start:o.start,end:r,span:{from:o.line,to:i}}),o=void 0):(c!=="`"||!u.includes("`"))&&(o={marker:c,width:f,lang:Ll.get(u.split(/\s+/)[0].toLowerCase()),start:r+s[i].length+1,line:i+2})}r+=s[i].length+1}return n}function Ep(e,t,n){let o=new Set(Tr(e,Object.keys(t)));if(!o.size)return t;let r=n.nodes.flatMap(s=>s.files??[]).filter(s=>s.role==="system prompt"&&s.span);return Object.fromEntries(Object.entries(t).map(([s,i])=>{if(!o.has(s))return[s,i];let l=r.filter(c=>c.path===s).map(c=>c.span),a=Ut(s,i).filter(c=>l.some(f=>c.span.from<=f.from&&f.to<=c.span.to));return a.length?[s,i.split(`
8
- `).map((c,f)=>a.some(u=>u.span.from<=f+1&&f+1<=u.span.to)?c:"").join(`
9
- `)]:[s,i]}))}function Fr(e,t,n,o,r){if(!o||!Tr(e,[t]).length)return null;let s=Ut(t,n).find(l=>l.span.from<=o.from&&o.to<=l.span.to);if(!s)return null;let i=Gt(n.slice(s.start,s.end),o.from-s.span.from+1,r);return{text:i.text,fromLine:s.span.from+i.fromLine-1}}function Rp(e,t){return e.split("").map((n,o)=>/[\r\n]/.test(n)||t.some(r=>r.start<=o&&o<r.end)?n:" ").join("")}var Dr=200,Br=300,Un=/SYSTEM|PROMPT|INSTRUCTION/i,Al=/^\s*You(?:['’]re)?(?![\w'’])/;function Wr(e,t,n={}){let o=n.minChars!==void 0,r=n.promptFunctions!==!1,s=[],i=new Map,l=new Set,a=(c,f)=>{l.has(c)||(l.add(c),s.push(f),i.set(c,f.span.from))};for(let c=0;c<e.toks.length;c++){let f=Pl(e,c,o||r);if(!f)continue;let u=r?dt(e,f.valueAt):null,p=pt(e,u??f.valueAt);!p||p.text.length<(n.minChars??Dr)||!o&&!Un.test(e.toks[f.nameAt].text)&&!(u!==null&&zt(p.text,!!p.filledAtRunTime))||(a(p.start,Gn(e,p,{named:!0,prose:zt(p.text,r&&!!p.filledAtRunTime),line:e.toks[f.nameAt].line,symbol:e.toks[f.nameAt].text,enclosing:oe(t,f.declAt)},r&&!!p.filledAtRunTime)),p.partStarts.forEach(g=>l.add(g)))}return r&&e.toks.forEach((c,f)=>{let u=y(c,"return")?t.filter(k=>k.params!==null&&k.from<f&&f<k.to).sort((k,w)=>w.from-k.from)[0]:void 0,p=Kn(e,f);if(!u&&!p)return;let g=u?f+1:f,m=p?dt(e,g):null,x=pt(e,m??g);if(!x||x.text.length<(n.minChars??Dr))return;let h=zt(x.text,!!x.filledAtRunTime);u&&!o&&!Un.test(u.name)&&!h||(a(x.start,Gn(e,x,{named:!!u||!h,prose:h,line:u?.line??x.line,symbol:u?.name??null,enclosing:u?.name??oe(t,f)},!!x.filledAtRunTime)),x.partStarts.forEach(k=>l.add(k)))}),e.toks.forEach((c,f)=>{if(!K(c)||l.has(c.start)||c.value.length<(n.minChars??Br))return;let u=r&&Bn(c),p=zt(c.value,u);if(!o&&!p)return;let g={start:c.start,line:c.line,endLine:c.endLine,text:c.value,partStarts:[c.start],next:f+1};a(c.start,Gn(e,g,{named:!1,prose:p,line:c.line,symbol:null,enclosing:oe(t,f)},u))}),s.sort((c,f)=>c.line-f.line),{sites:s,siteLineByStart:i}}function zt(e,t=!1){let n=t?e.replace(/^(?:\s*\$?\{[^{}]*\})+\s*/,""):e;return e.length>=Br&&Al.test(n)}function Gn(e,t,n,o=!1){return{kind:n.named?"named":"prose",...n,path:e.path,endLine:t.endLine,span:{from:t.line,to:t.endLine},start:t.start,chars:t.text.length,excerpt:ke(t.text),...o?{filledAtRunTime:!0}:{}}}function Pl(e,t,n){let{toks:o}=e,r=e.lang==="js";if(r&&!(y(o[t])&&["const","let","var"].includes(o[t].text)))return null;let s=r?t+1:t;if(!y(o[s])||!n&&!Un.test(o[s].text)||!r&&!(V(o,t)&&$l(e,t)))return null;let i=s+1;if(d(o[i],":")){let l=i+me;for(;i<l&&i<o.length&&!T(o,i);)i++}return T(o,i)?{declAt:t,nameAt:s,valueAt:i+1}:null}function $l(e,t){let n=Se(e.text,e.toks[t]);if(n===0)return!0;for(let o=t-1;o>=0;o--)if(!(!V(e.toks,o)||Se(e.text,e.toks[o])>=n))return y(e.toks[o],"class");return!1}var Ml=20,Cl=/^(?:messages\.(?:create|stream)|chat\.completions\.create|responses\.create|generateText|streamText|Runner\.run)\(/,jl=/\/v1\/(?:messages|chat\/completions)$/;function Jt(e,t,n,o={}){let{toks:r}=e,s=n.filter(a=>Ot(a.source,e.lang,o,e)),i=s.length>0,l=s.map(a=>({line:a.line,at:null}));return r.forEach((a,c)=>{if(K(a)){jl.test(a.value)&&l.push({line:a.line,at:c});return}if(!y(a))return;let f=r.slice(c,c+7).map(m=>m.text).join(""),u=de.includes(r[c-1]?.text??""),p=i&&a.text==="query"&&r[c+1]?.text==="("&&r[c-1]?.text!==".";(Cl.test(f)&&(a.text!=="Runner"||o.layouts===!0&&i)&&!u||p&&!u)&&l.push({line:a.line,at:c})}),l.sort((a,c)=>a.line-c.line),l.slice(0,Ml).map(({line:a,at:c})=>({kind:"sdk",path:e.path,line:a,value:null,enclosing:c===null?null:oe(t,c)}))}function Vt(e,t,n){let o=[];for(let r of t){let{params:s}=r;if(s)for(let{site:i,valueAt:l}of n){if(i.value?.kind!=="identifier"||l<=r.from||l>=r.to)continue;let a=s.indexOf(i.value.text),c=o.some(f=>f.name===r.name&&f.paramIndex===a);a>=0&&!c&&o.push({name:r.name,paramIndex:a,paramName:i.value.text,path:e.path,line:r.line})}}return o}var Nl=200,Tl=40;function Kr(e,t,n,o){let{toks:r}=e,s=[];for(let i=0;i<r.length&&s.length<Nl;i++){let l=r[i];if(!H(r,i)||d(r[i-1],".")||de.includes(r[i-1]?.text??""))continue;let a=j(r,i+1).map(f=>Fl(e,n,f));a.some(f=>f.kind==="literal"&&f.siteLine!==null||f.kind==="identifier"&&o.has(f.text))&&s.push({name:l.text,path:e.path,line:l.line,args:a,shortLiterals:a.filter(f=>f.kind==="literal"&&f.siteLine===null&&f.text.length>0&&f.text.length<=Tl).map(f=>f.text),enclosing:oe(t,i)})}return s}function Fl(e,t,n){let{toks:o}=e,r=e.lang==="py"&&y(o[n.from])&&T(o,n.from+1),s=r?n.from+2:n.from;return{...te(e,t,s,n.to),name:r?o[n.from].text:null}}var Gr=50;function qt(e,t,n,o,r,s){let{toks:i}=e,l=new Set(t.map(u=>u.name)),a=u=>Je(t,u),c=new Map(n.map(u=>[u.from,u])),f=new Set(s.map(u=>u.callStart));return n.filter(u=>l.has(u.callee)||r.has(u.callee.split(".")[0])||f.has(i[u.from].start)).slice(0,Gr).map(u=>{let p=a(u.from),g=[...new Set(u.args.flatMap(O=>{let{from:R,to:I}=O;for(e.lang==="py"&&y(i[R])&&T(i,R+1)&&(R+=2);d(i[R],"(")&&A(i,R)===I-1;)R++,I--;if(!y(i[R]))return[];for(let L=R+1;L<I;L+=2)if(!d(i[L],".")||!y(i[L+1]))return[];return[i[R].text]}))].slice(0,Gr),m=O=>o.findLast(R=>R.name===O&&R.at<u.from&&a(R.at)===p&&!(R.from<=u.from&&u.from<R.to)),x=O=>{let R=y(i[O.from],"await")?O.from+1:O.from,I=c.get(R);return!O.append&&I?.to===O.to?I:null},h=Object.fromEntries(g.flatMap(O=>{let R=m(O);if(!R)return[];let I=x(R);return[[O,I?i[I.from].start:null]]})),k=o.find(O=>x(O)===u),w=t.filter(O=>O.from<u.from&&u.from<O.to),b=t.filter(O=>O.name===u.callee&&(!a(O.from)||w.includes(a(O.from)))).sort((O,R)=>(a(R.from)?.from??-1)-(a(O.from)?.from??-1))[0],S=u.callee.split(".")[0],_=w.findLast(O=>O.params?.includes(S)||o.some(R=>R.name===S&&R.at<u.from&&a(R.at)===O)),E=_&&(!b||(a(b.from)?.from??-1)<_.from),v=E?null:b?i[b.from].start:null;return{callee:u.callee,resultVar:k?.name??null,argNames:g,enclosing:p?.name??null,line:i[u.from].line,callStart:i[u.from].start,...p?{enclosingStart:i[p.from].start}:{},...b||E||l.has(u.callee)?{localTarget:v}:{},...Object.keys(h).length?{argCalls:h}:{}}})}var Ae=50,Dl=200,Ur=new Set(["system","systemPrompt","system_prompt","instructions","prompt","template","template_file"]),Bl=new Set(["model","engine","schema","response_format","output_type","outputSchema","tools","messages","max_tokens","maxTokens"]),Wl=new Set(["schema","response_format","output_type","outputSchema"]),zr=/(?:template|template_file|prompt_file)$/;function Jr(e,t){let{toks:n}=e,o=t.filter(R=>R.params!==null),r=R=>Je(o,R),s=Ve(e),i=new Map(s.map(R=>[R.from,R])),l=q(e),a=new Set(le(l,e.lang).map(R=>R.name)),c=Jt(e,t,l).length>0,f=Vt(e,t,he(e,t,new Map)),u=new Map(s.flatMap(R=>{let I=Kl(e,R),L=f.find(C=>C.name===R.callee),$=I.filter(C=>c||L||I.some(N=>N.object===C.object&&Bl.has(N.key)));return c||L||$.length?[[R,{fields:$,wrapper:L}]]:[]})),p=Nt(e),g=new Map(p.map(R=>[R.at,R])),m=new Map(p.filter(R=>!R.append).map(R=>[y(n[R.from],"await")?R.from+1:R.from,R.name])),x=yr({},{[e.path]:e.text},{source:e,scopes:t},"operations"),h=hr(x.operations),k=new Map(h.map(R=>[R.call.from,R.path])),w=[];for(let R of o){for(let I of h){if(r(I.call.from)!==R)continue;let L=xr(I,R,e.lang);if(!(!L||w.some($=>$.name===R.name&&$.line===R.line))&&(w.push({name:R.name,paramIndex:L.paramIndex,folder:L.folder,ext:L.ext,path:e.path,line:R.line}),w.length===Ae))break}if(w.length===Ae)break}let b=new Set(w.map(R=>R.name)),S=new Map,_=R=>[...new Map(R.map(I=>[JSON.stringify(I),I])).values()].slice(0,Ae),E=R=>n.slice(R.from,R.to).filter(K).filter(I=>I.value.length<=Dl).map(I=>I.value).slice(0,Ae),v=[];for(let R=0;R<2;R++){let I=new Map;v=[];let L=($,C)=>{let{from:N,to:P}=$;for(y(n[N],"await")&&N++;d(n[N],"(")&&A(n,N)===P-1;)N++,P--;if(P===N+1&&y(n[N]))return I.get(C)?.get(n[N].text)??[];let M=i.get(N);if(M&&M.to===P){let Me=k.get(N);if(Me){let z=E(Me);return qe(z).length>0?[{kind:"read",callee:M.callee,literals:z}]:[]}if(u.get(M)?.fields.some(z=>Ur.has(z.key)||z.key==="messages"))return[];let Ce=M.args[0]?E(M.args[0]):[],je=a.has(M.callee.split(".")[0]),D=[...S.keys()].some(z=>z.name===M.callee);if(D||(b.has(M.callee)||je)&&(Ce.length>0||je&&M.args.length===0))return[{kind:D?"return":"loader",callee:M.callee,literals:Ce}]}return[]};for(let $=0;$<n.length;$++){let C=r($),N=g.get($);if(N){let{name:D,append:z}=N,fe=I.get(C)??new Map;fe.set(D,_([...z?fe.get(D)??[]:[],...L(N,C)])),I.set(C,fe)}if(y(n[$],"return")&&C&&!w.some(D=>D.name===C.name&&D.line===C.line)){let D=L({from:$+1,to:ce(e,$+1)},C);D.length&&(S.has(C)||S.size<Ae)&&S.set(C,{fn:C.name,loads:_([...S.get(C)?.loads??[],...D]),path:e.path,line:C.line})}let P=i.get($);if(!P||v.length===Ae)continue;let M=u.get(P);if(!M)continue;let{fields:Me,wrapper:Ce}=M,je=(D,z,fe=!1)=>{let se=L(D,C);if(!se.length&&fe){let ie=E(D);qe(ie).length>0&&(se=[{kind:"file-key",callee:P.callee,literals:ie}])}if(!se.length||v.length===Ae)return;let Ne=Me.filter(ie=>D.object===void 0||ie.object===D.object),xe=Ne.find(ie=>ie.key==="model"||ie.key==="engine"),on=Ne.find(ie=>Wl.has(ie.key)),js=xe?te(e,new Map,xe.from,xe.to):null,ko=on?te(e,new Map,on.from,on.to):null,Ns=ko?.kind==="identifier"?ko.text:null,Ts=m.get(P.from)??null;v.push({path:e.path,line:n[P.from].line,callStart:n[P.from].start,callee:P.callee,key:z,loads:se,model:js,shape:Ns,enclosing:C?.name??null,resultVar:Ts})};for(let D of Me)if((Ur.has(D.key)||zr.test(D.key))&&je(D,D.key,e.lang==="py"&&zr.test(D.key)),D.key==="messages")for(let z=D.from;z<D.to;z++){if(!d(n[z],"{"))continue;let fe=zn(e,z),se=fe.find(xe=>xe.key==="role");if(!se||n[se.from]?.kind!=="string"||!["system","user"].includes(n[se.from].value))continue;let Ne=fe.find(xe=>xe.key==="content");Ne&&se.from<Ne.from&&je({...Ne,object:D.object},"content"),z=A(n,z)}Ce&&P.args[Ce.paramIndex]&&!Me.length&&je(P.args[Ce.paramIndex],null)}}let O=qt(e,o,s,p,a,v);return{loaders:w,promptReturns:[...S.values()],deliveries:v,stepCalls:O}}function zn(e,t){let{toks:n}=e;return j(n,t).flatMap(({from:o,to:r})=>{let s=y(n[o])?n[o].text:n[o]?.kind==="string"?n[o].value:null;return s?d(n[o+1],":")||e.lang==="py"&&T(n,o+1)?[{key:s,from:o+2,to:r,object:t}]:r===o+1?[{key:s,from:o,to:r,object:t}]:[]:[]})}function Kl(e,t){return e.lang==="py"?zn(e,t.open):t.args.flatMap(n=>d(e.toks[n.from],"{")?zn(e,n.from):[])}function Jn(e){return{path:e,sites:[],callSites:[],sdk:!1,sdkLine:null,wrappers:[],wrapperCalls:[],imports:[],modelIds:[],fileRefs:[]}}function qr(e,t,n={}){try{if(n.coverageLinks===!0&&n.documented===!0&&/\.md$/i.test(e)){let o=Ut(e,t).map(r=>({span:r.span,hits:Vr(e,t.slice(0,r.start).replace(/[^\r\n]/g," ")+t.slice(r.start,r.end),n,r.lang)}));return{...Jn(e),snippets:o}}return Vr(e,t,n)}catch{return Jn(e)}}function Vr(e,t,n,o=W(e)){if(!o){let S=Ho(e,t);return{...Jn(e),sites:S?[S]:[]}}let r=J(e,t,o),s=U(r,{promptFunctions:n.promptFunctions!==!1}),i=q(r),l=le(i,o),{sites:a,siteLineByStart:c}=Wr(r,s,n),f=Jt(r,s,i,n.sdk),u=he(r,s,c,n.sdk?.layouts===!0&&f.length>0,n.promptFunctions!==!1),p=new Set([...a.flatMap(S=>S.symbol?[S.symbol]:[]),...l.map(S=>S.name)]),g=n.promptLoaders!==!1?Jr(r,s):null,m=n.coverageLinks===!0&&g?Nr(r,s,a):null,x=[...g?.deliveries??[],...m?.deliveries??[]],h=m?re(r,s):null,k=h?qt(r,h.functions,h.calls,h.assignments,new Set(l.map(S=>S.name)),x):g?.stepCalls,w=rr(r),b=n.promptLoaders!==!1?sr(r):[];return{path:e,sites:a,callSites:[...u.map(S=>S.site),...f].sort((S,_)=>S.line-_.line),sdk:f.length>0,sdkLine:f.length>0?f[0].line:null,wrappers:Vt(r,s,u),wrapperCalls:Kr(r,s,c,p),imports:l,modelIds:w.modelIds,fileRefs:m?w.promptFileRefs:w.fileRefs,...g?.loaders.length?{loaders:g.loaders}:{},...g?.promptReturns.length?{promptReturns:g.promptReturns}:{},...x.length?{deliveries:x}:{},...m?{priorDeliveries:g?.deliveries??[],priorFileRefs:w.fileRefs}:{},...k?.length?{stepCalls:k}:{},...m?.bindings.length?{promptBindings:m.bindings}:{},...m?.loadedRefs.length?{loadedPromptRefs:m.loadedRefs}:{},...b.length?{modelMembers:b}:{}}}var Xr=e=>e.CF_CODE_PROMPT_FUNCTIONS!=="0";var Gl=20;function Xt(e,t){let n=new Set(t),o=new Set;for(let[r,s]of Object.entries(e)){let i=W(r);if(i)for(let l of Kt(r,s,i)){let a=pe(r,l.source,l.names,i,n);a!==void 0&&o.add(a)}}return[...o].sort()}function Ed(e,t,n){return Xt(e,t).filter(o=>!vo(o,n)).slice(0,Gl)}function Ul(e,t){let n=Te(e),o=n?n.split("/"):[],r=t.split("/").slice(0,-1),s=0;for(;s<o.length&&s<r.length&&o[s]===r[s];)s++;return o.slice(0,s).join("/")}function Rd(e,t,n){let o=Xr(n),r=Fn(Object.entries(t).map(([l,a])=>qr(l,a,{promptFunctions:o}))),s=r.strong[0]??r.possible[0];if(!s)return null;let i=s.prompt.path;return{suggestedDir:Ul(e,i),file:i,symbol:s.prompt.symbol}}function vd(e,t){let n=t.suggestedDir||"the repository root";return`no agent prompt in ${e}; its code imports ${t.file}, which defines ${t.symbol??"a prompt"} \u2014 import ${n} to include it`}function Vn(e,t){if(!t||!d(e[t.from],"{")||A(e,t.from)!==t.to-1)return null;let n=new Map;for(let o of j(e,t.from)){let r=e[o.from];if(!(y(r)||r?.kind==="string")||!d(e[o.from+1],":"))return null;let s=r.kind==="string"?r.value:r.text;if(n.has(s))return null;n.set(s,{from:o.from+2,to:o.to})}return n}function Pe(e,t,n=0){if(!t||n>32)return;let{from:o,to:r}=t,s=e[o];if(s?.kind==="string"&&Be(s).closed){if(r===o+1)return s.value;if(d(e[o+1],"+")){let a=Pe(e,{from:o+2,to:r},n+1);if(typeof a=="string")return s.value+a}}if(r===o+1){if(s?.kind==="number"){let a=Number(s.text.replace(/_/g,""));return Number.isFinite(a)?a:void 0}if(y(s,"true"))return!0;if(y(s,"false"))return!1;if(y(s,"null"))return null}if(d(s,"[")&&A(e,o)===r-1){let a=j(e,o).map(c=>Pe(e,c,n+1));return a.includes(void 0)?void 0:a}let i=Vn(e,t);if(!i)return;let l=[...i].map(([a,c])=>[a,Pe(e,c,n+1)]);return l.some(([,a])=>a===void 0)?void 0:Object.fromEntries(l)}function Hr(e,t){let n=Vn(e,t);if(!n)return null;let o=Pe(e,n.get("type"));if(o==="function"&&n.has("function")&&(n=Vn(e,n.get("function"))),!n)return null;let r=n.get("input_schema")??(o==="function"?n.get("parameters"):void 0);if(!r)return null;let s=Pe(e,n.get("name")),i=Pe(e,n.get("description"));if(typeof s!="string"||!s.trim()||typeof i!="string")return{tools:[],warnings:["Some tools couldn't be read from code"]};let l=Pe(e,r),a=l!==null&&typeof l=="object"&&!Array.isArray(l);return{tools:[{name:s,description:i,...a?{input_schema:l}:{}}],warnings:a?[]:[`${s}'s arguments couldn't be read from code`]}}function Hn(e,t){y(e[t],"as")&&y(e[t+1],"const")&&(t+=2);let n=e[t];return n===void 0||n.kind==="punct"&&",;)}]".includes(n.text)||y(n)&&n.line>(e[t-1]?.endLine??n.line)&&!["as","satisfies"].includes(n.text)}function qn(e,t,n){for(;d(e[t],".");)t++;return y(e[t])?[e[t].text]:!d(e[t],"{")&&!d(e[t],"[")?[]:j(e,t).filter(o=>o.from<o.to&&o.to<=n).flatMap(o=>{let r=o.from;return d(e[t],"{")&&d(e[r+1],":")&&(r+=2),qn(e,r,o.to)})}function Xn(e,t){let{toks:n}=e,o=new Map,r=new Map,s=new Map,i=[];for(let l=0;l<n.length;l++){if(d(n[l],"{")?i.push(l):d(n[l],"}")&&i.pop(),!y(n[l])||!["const","let","var"].includes(n[l].text))continue;let a=i.at(-1);if(t!==void 0&&a!==void 0&&(t<a||t>A(n,a)))continue;let c=y(n[l+1])?l+2:A(n,l+1)+1,f=qn(n,l+1,c).filter(p=>t===void 0||(r.get(p)??-1)<=i.length);for(let p of f)o.set(p,null),r.set(p,i.length),s.set(p,l);if(!y(n[l],"const")||!y(n[l+1])||!f.length)continue;let u=n[l+1].text;for(let p=l+2;p<Math.min(n.length,l+40)&&!d(n[p],";");p++)if(d(n[p],"=")){o.set(u,null),r.set(u,i.length),d(n[p+1],"[")&&Hn(n,A(n,p+1)+1)&&(o.set(u,p+1),r.set(u,i.length));break}}if(t!==void 0)for(let l of U(e)){if(l.params===null||t<=l.from||t>=l.to)continue;let a=l.params.filter(c=>c!==null);if(l.params.includes(null)){let c=n.findIndex((f,u)=>u>l.from&&u<t&&d(f,"("));c>=0&&a.push(...vt(n,c,"js").flatMap(({from:f,to:u})=>qn(n,f,u)))}for(let c of a)(s.get(c)??-1)<=l.from&&o.set(c,null)}return o}function zl(e){let{toks:t}=e,n=new Map;for(let o=0;o<t.length;o++){if(!y(t[o],"export"))continue;let r=Xn(e,o);if(y(t[o+1],"const")){let s=t[o+2]?.text,i=r.get(s);i!=null&&n.set(s,i)}else if(y(t[o+1],"default")){let s=d(t[o+2],"[")?o+2:r.get(t[o+2]?.text),i=d(t[o+2],"[")?A(t,o+2)+1:o+3;s!=null&&Hn(t,i)&&n.set("default",s)}else if(d(t[o+1],"{"))for(let s of j(t,o+1)){let i=r.get(t[s.from]?.text);i!=null&&n.set(t[s.to-1].text,i)}}return n}function Yr(e,t,n){return n.has(e[t.from]?.start)&&d(e[t.from+1],"(")&&A(e,t.from+1)===t.to-1}function Jl(e,t){let n=t?.call;if(!n)return;let{toks:o}=e;if(n.loadedPrompt&&n.callStart!==void 0){let u=o.findIndex(p=>p.start===n.callStart);if(u<0)return;for(;d(o[u+1],".")&&y(o[u+2]);)u+=2;return H(o,u,e)?{from:u+1,to:A(o,u+1)+1}:void 0}let r=new Set([n.symbol]),s=new Set(Object.keys(t.imports));for(let u of q(e)){let p=pe(e.path,u.source,u.names,"js",s);if(!(n.promptPath&&p!==n.promptPath))for(let g of u.names)((u.renamed?.[g]??g)===n.symbol||p===n.promptPath&&g===u.defaultName)&&r.add(g)}let i=n.promptPath===e.path&&n.promptStart!==void 0?new Map([[n.promptStart,n.line??1]]):new Map,l=he(e,[],i).filter(({site:u})=>n.line===void 0||u.line===n.line),a=(l.find(({site:u})=>u.value?.siteStart!=null&&u.value.siteStart===n.promptStart)??l.find(({site:u})=>u.value&&r.has(u.value.text))??l[0])?.valueAt;if(a===void 0)return;let c,f;for(let u=0;u<a;u++){if(!d(o[u],"(")&&!d(o[u],"{"))continue;let p=A(o,u)+1;p<=a||(d(o[u],"{")?c={from:u,to:p}:f={from:u,to:p})}return f??c}function Zr(e,t,n,o){let r=J(t?.path??"tools.ts",e,"js"),{toks:s}=r,i=t?.call?.loadedPrompt?new Set(U(r).filter(S=>S.params!==null).map(S=>S.name)):new Set,l=Xn(r),a=new Map,c=t?.imports??{},f=new Set(Object.keys(c));for(let S of q(r)){let _=pe(r.path,S.source,S.names,"js",f);if(_===void 0)continue;let E=J(_,c[_],"js"),v=o(c[_]);for(let[O,R]of zl(E))for(let I of S.names)(S.defaultName===I?"default":S.renamed?.[I]??I)===O&&a.set(I,{toks:E.toks,open:R,path:_,calls:v})}let u=new Set,p=new Set,g=[],m="Some tools couldn't be read from code",x=Jl(r,t),h=!1;for(let S=0;S<s.length;S++){if(x&&(S<x.from||S>=x.to))continue;let _=s[S];if(["input_schema","parameters"].includes(_.kind==="string"?_.value:_.text)&&d(s[S+1],":")&&d(s[S+2],"{")){S=A(s,S+2);continue}if((y(_,"tools")||_.kind==="string"&&_.value==="tools")&&d(s[S+1],":")){h=!0;let E=s[S+2],v=Xn(r,S),O=d(E,"[")?S+2:y(E)?v.get(E.text):void 0,R=d(E,"[")?A(s,S+2)+1:S+3;if(!Hn(s,R)){g.push(m);continue}O==null?y(E)&&!v.has(E.text)&&a.has(E.text)?p.add(E.text):g.push(m):u.add(O)}}if(!h)for(let S of l.values())S!==null&&j(s,S).some(_=>Hr(s,_)||Yr(s,_,n))&&u.add(S);let k=[],w=new Map,b=[...u].map(S=>({toks:s,open:S,calls:n,path:null}));b.push(...[...p].map(S=>a.get(S)));for(let{toks:S,open:_,calls:E,path:v}of b){let O=I=>g.push(v?`${v}: ${I}`:I),R=A(S,_);if(!d(S[R],"]")){O(m);continue}for(let I of j(S,_)){let L=Hr(S,I),$=Yr(S,I,E),C=I.to===I.from+1&&y(S[I.from])?S[I.from].text:null,N=h&&v===null&&C&&i.has(C)?{name:C,description:""}:null;if(!L&&!$&&!N)O(m);else{let P=L?L.tools:N?[N]:h&&$?[E.get(S[I.from].start)]:[];for(let M of P)w.has(M.name)||w.set(M.name,v??r.path);k.push(...P),L?.warnings.forEach(O)}}}return{tools:k,warnings:g,selected:h,from:Object.fromEntries(w)}}var ht=String.raw`(?:"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')`,Vl=new RegExp(String.raw`(${ht}|`+"`(?:[^`\\\\]|\\\\.)*`)"+String.raw`|\/\/[^\n]*|\/\*[\s\S]*?\*\/`,"g"),ql=/(?<![\w$])tool\s*(<[^()]*>)?\(/g,Xl=new RegExp(`^${ht}$`),Hl=new RegExp(`^${ht}(?:\\s*\\+\\s*${ht})*$`),Yl={n:`
10
- `,t:" ",r:"\r"};function Qr(e){return e.slice(1,-1).replace(/\\(.)/g,(t,n)=>Yl[n]??n)}function Zl(e){return e.replace(Vl,(t,n)=>n?n[0]+"_".repeat(n.length-2)+n[n.length-1]:" ".repeat(t.length))}function es(e,t){let n=0;for(let o=t;o<e.length;o++){let r=e[o];if("([{".includes(r))n++;else if(")]}".includes(r)){if(n===0)return o;n--}else if(r===","&&n===0)return o}return e.length}function ts(e){let t=Zl(e),n=[],o=[],r=new Map,s="a tool( call in tools.ts was skipped: its name and description are not plain text";for(let i of t.matchAll(ql)){let l=t.slice(Math.max(0,i.index-40),i.index).trimEnd();if(l.endsWith(".")&&!l.endsWith("...")||i[1]){o.push(s);continue}let c=es(t,i.index+i[0].length),f=c+1,u=es(t,f),p=e.slice(i.index+i[0].length,c).trim(),g=e.slice(f,u).trim();if(t[c]!==","||!Xl.test(p)||!Hl.test(g)){o.push(s);continue}let m=g.match(new RegExp(ht,"g")),x={name:Qr(p),description:m.map(Qr).join("")};n.push(x),r.set(i.index,x)}return{tools:n,warnings:o,readCalls:r}}function ns(e,t){let{tools:n,warnings:o}=os(e,t);return{tools:n,warnings:o}}function os(e,t){let{tools:n,warnings:o,readCalls:r}=ts(e),s=new Map(n.map(({name:l})=>[l,t?.path??"tools.ts"])),i=Zr(e,t,r,l=>ts(l).readCalls);if(i.selected)return i;n.push(...i.tools),o.push(...i.warnings);for(let[l,a]of Object.entries(i.from))s.has(l)||s.set(l,a);return{tools:n,warnings:o,from:Object.fromEntries(s),selected:!1}}function Fd(e,t,n){let o=Object.fromEntries(e.filter(u=>W(u)==="js"&&t[u]!==void 0).map(u=>[u,t[u]])),r=Xt(o,Object.keys(t)),s=u=>{let p=Object.fromEntries(Xt({[u]:t[u]},Object.keys(t)).filter(m=>r.includes(m)).map(m=>[m,t[m]])),g=os(t[u],{path:u,imports:p,...n?.path===u?{call:n}:{}});return{...g,warnings:g.warnings.map(m=>`${u}: ${m}`)}},i=Object.keys(o).map(s),l=i.filter((u,p)=>u.selected&&(!n||Object.keys(o)[p]===n.path)),a=l.length?l:[...i,...r.filter(u=>!o[u]).map(s)],c=new Map;return{tools:a.flatMap(u=>u.tools.filter(p=>c.has(p.name)?!1:(c.set(p.name,u.from[p.name]),!0))),from:Object.fromEntries(c),warnings:[...new Set(a.flatMap(u=>u.warnings))]}}function rs(e){let t;try{t=JSON.parse(e)}catch{return{tools:[],warnings:[".cli.json is not valid JSON; ignored"]}}let n=t?.clis;return!n||typeof n!="object"||Array.isArray(n)?{tools:[],warnings:[]}:{tools:Object.entries(n).map(([r,s])=>{let i=s?.description;return{name:r,description:typeof i=="string"?i:""}}),warnings:[]}}var Ql=/\.(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,ea=/\.(md|mdx|txt|json|ya?ml)$/i,ta=/^(licen[cs]e.*|copying|notice|authors|codeowners|readme|changelog|\.gitignore|\.gitattributes|\.editorconfig|\.gitkeep|\.nvmrc|\.python-version|\.tool-versions|\.prettierrc|\.npmignore|\.dockerignore)$/i;function Yn(e){return Ql.test(e.trim())}function Wd(e){return!Yn(e)&&ea.test(e.trim())}function Kd(e){let t=e.trim();return!ye(t)&&!ta.test(t.split("/").at(-1))&&!/\.(md|mdx|txt|text|jsonl?|ndjson|csv|tsv|pdf|rst|adoc|ini|cfg|ya?ml|toml|lock|png|jpe?g|gif|svg|ico|webp|avif|bmp|tiff?)$/i.test(t)}var na=["stripe","slack","postgresql","datadog","pagerduty","jira","googlecalendar"],oa=new Set(na);function Yt(e){if(!e)return null;let t=e.trim().toLowerCase();return oa.has(t)?t:null}function ra(e,t){let n=[...e.warnings],o=new Set(e.nodes.map(l=>l.id)),r=new Set,s=e.nodes.map(l=>{let a=[],c=new Set;for(let f of l.tools??[]){let u=f.label.trim();if(!u){n.push(`${t}: dropped a tool with no name on ${l.id}`);continue}let p=`${f.source??"tool"}:${u}`;if(c.has(p)){n.push(`${t}: ${l.id} lists ${u} twice \u2014 kept one`);continue}c.add(p);let g=Yt(f.brand);f.brand&&!g&&!r.has(f.brand)&&(r.add(f.brand),n.push(`${t}: "${f.brand}" is not a provider mark we can draw \u2014 those tools render without one`)),a.push({label:u,brand:g,...f.source?{source:f.source}:{}})}return{...l,tools:a}}),i=e.edges.filter(l=>{let a=o.has(l.from)&&o.has(l.to);return a||n.push(`${t}: dropped edge ${l.from} \u2192 ${l.to} (unknown endpoint)`),a});return e.nodes.some(l=>l.kind==="agent")||n.push(`${t}: the mapping found no agent node \u2014 the graph may be incomplete`),{fragment:{...e,nodes:s,edges:i,warnings:[]},warnings:n}}var Ht=2e4;function ss(e){return e.trim().replace(/^(?:\.?\/)+/,"")}function sa(e,t,n,o={}){let r=[],s=new Map;for(let c of Object.keys(t))s.set(ss(c),c);let i={},l=Zn(e),a=e.nodes.map(c=>{let f=[],u=[];for(let p of c.files??[]){let g=p.path.trim();if(!g)continue;let m=s.get(ss(g));if(m===void 0){r.push(`${n}: node ${c.id} lists ${g} as a definition file, which the analysis never read \u2014 dropped`);continue}let x=t[m],h=x.length>Ht,k=(p.role==="system prompt"?Fr(o,m,x,p.span,Ht):null)??(h&&p.span&&p.role==="system prompt"&&Yn(m)?Gt(x,p.span.from,Ht):null),w=k?k.text:h?x.slice(0,Ht):x;h&&!Qn(m,l)&&r.push(`${n}: node ${c.id}'s ${p.role} file (${m}) is ${x.length} characters \u2014 stored truncated at ${w.length}`),f.push({role:p.role,label:p.label??null,path:m,...p.span?{span:p.span}:{},...p.filledAtRunTime?{filledAtRunTime:!0}:{}}),u.push({...p.filledAtRunTime?{filledAtRunTime:!0}:{},role:p.role,...p.label?{label:p.label}:{},path:m,tokens:Ro(x.length),text:w,...h?{truncated:!0,storedChars:w.length}:{},...p.span?{span:p.span}:{},...k?{fromLine:k.fromLine}:{}})}return u.length&&(i[c.id]=u),{...c,files:f}});return{fragment:{...e,nodes:a},nodes:i,warnings:r}}function ia(e){let t=[],n=[];for(let{repoKey:o,fragment:r,files:s}of e){let i=l=>`${o}#${l}`;for(let l of r.nodes){let a=s?.[l.id],c=(l.tools??[]).map(f=>({label:f.label,...f.brand?{brand:f.brand}:{},...f.source?{source:f.source}:{}}));t.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 r.edges)n.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:t,edges:n}}var la={critical:0,high:1,medium:2,low:3};function eo(e){return la[e]}function is(e){let t=e?.trim();return t&&t.length<=280?t:null}var aa=2,to=4,no=120,ls="Which should the agent do?",ca="asked to pose a question, answered with one fix";function as(e){if(!pn(e.category))return{question:null,fixes:e.fixes,warnings:[]};let t=`finding "${e.title}"`;if(e.fixes.length<aa)return{question:null,fixes:e.fixes,warnings:[`${t}: ${ca}`]};let n=[],o=e.fixes;o.length>to&&(n.push(`${t}: ${o.length} options proposed; keeping the first ${to}`),o=o.slice(0,to));let r=(e.question??"").trim();return r?r.length>no&&(n.push(`${t}: the question is longer than ${no} characters; cut`),r=`${r.slice(0,no-1).trimEnd()}\u2026`):(n.push(`${t}: no question with ${o.length} options; asking "${ls}"`),r=ls),{question:r,fixes:o,warnings:n}}function ro(e){let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return[e.kind,e.siteRepo??"-",e.site?.path??"-",t].join("|")}var $e=e=>e.legacyFingerprint??e.fingerprint,He=e=>e.replace(/\s+/g," ").trim(),ua=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(" ")),xt=new Set(["before","after","instead","from","to","than"]),fs=new Set([...xt,"no","not","never","cannot","without"]),fa=/^(?: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)?)$/,so=e=>e.split(/[.!?;,\n]+|\b(?:and|but|while)\b/);function Ye(e){return fa.test(e)?e==="sent"?"send":e.replace(/(?:ing|ped|ed|es|s)$/,"").replace(/^skipp$/,"skip").replace(/^(delet|revok|rout|writ|charg)$/,"$1e"):null}function Ze(e){let t=(e.toLowerCase().replaceAll("can't","cannot").match(/[a-z0-9_]+/g)??[]).filter(n=>!ua.has(n)||xt.has(n)).map(n=>Ye(n)??n);return t.map((n,o)=>["not","never","cannot"].includes(n)&&Ye(t[o+1]??"")!==null?"skip":n)}function oo(e){return new Set(Ze(e))}function pa(e){return[...oo(e)].filter(t=>Ye(t)!==null).sort()}function da(e){return so(e).filter(t=>Ze(t).some(n=>xt.has(n))).map(t=>Ze(t).join(" ")).sort()}function ma(e,t){let n=o=>o!=="refund"&&Ye(o)!==null;return so(e).flatMap(o=>{let r=Ze(o);return r.flatMap((s,i)=>{if(!n(s))return[];let l=r.slice(i+1),a=l.findIndex(x=>n(x)||fs.has(x)),c=l.slice(0,a<0?l.length:a).filter(x=>t.has(x)),f=["skip","no","not","never","cannot","without"].includes(r[i-1]??""),u=a<0?[]:l.slice(a),p=u.findIndex(x=>n(x)),g=u.slice(0,p<0?u.length:p),m=g.flatMap((x,h)=>{if(!xt.has(x))return[];let k=g.slice(h+1),w=k.findIndex(b=>xt.has(b));return[JSON.stringify([x,k.slice(0,w<0?k.length:w).filter(b=>t.has(b))])]});return c.length?[{action:s,objects:c,denied:f,relations:m}]:[]})}).sort((o,r)=>JSON.stringify(o).localeCompare(JSON.stringify(r)))}function ga(e){let t=Ze(e);return["before","after","instead"].filter(n=>t.includes(n)).concat(t.some((n,o)=>["no","not","never","cannot","without"].includes(n)||n==="skip"&&Ye(t[o+1]??"")!==null)?["negative"]:[])}function Zt(e){let t=He(e.cause??"").toLowerCase(),n=[...new Set(e.sites.map(s=>He(s.quote).toLowerCase()))].sort((s,i)=>i.length-s.length||s.localeCompare(i));for(let s of n)t=t.replaceAll(s,"");let o=oo(t),r=oo(e.sites.map(s=>s.quote).join(" "));return{text:t,terms:o,operators:t.match(/!==|===|!=|==|<=|>=|<|>/g)??[],actions:pa(t),direction:ga(t),relations:da(t),anchors:[...o].filter(s=>r.has(s)).sort(),numbers:[...o].filter(s=>/^\d+$/.test(s)).sort(),objects:so(t).map(s=>Ze(s).filter(i=>r.has(i)&&Ye(i)===null&&!fs.has(i)).join(" ")).filter(Boolean).sort(),bindings:ma(t,r)}}function ps(e,t){let[n,o]=[Zt(e),Zt(t)];if(Math.min(n.terms.size,o.terms.size)<3||!n.anchors.length)return!1;for(let s of["operators","actions","direction","relations","anchors","numbers","objects","bindings"])if(JSON.stringify(n[s])!==JSON.stringify(o[s]))return!1;let r=[...n.terms].filter(s=>o.terms.has(s));return n.text===o.text||r.length>=4&&r.length/Math.max(n.terms.size,o.terms.size)>=.7}function ha(e){return[...new Set(e.map(t=>JSON.stringify([t.repoKey,t.path,He(t.quote)])))].sort()}function Qt(e){return e.omittedSites||!e.sites.length||e.sites.some(t=>t.verified===!1||!t.path||!He(t.quote)||!Number.isInteger(t.startLine)||t.startLine<1||!Number.isInteger(t.endLine)||t.endLine<t.startLine)?null:ha(e.sites)}function xa(e,t){if(!e.kind||e.kind!==t.kind||!e.category||e.category!==t.category||(e.agentId??null)!==(t.agentId??null))return!1;let[n,o]=[Qt(e),Qt(t)];return n!==null&&o!==null&&JSON.stringify(n)===JSON.stringify(o)&&ps(e,t)}function ya(e,t){if(e.kind!==t.kind||e.category!==t.category||(e.agentId??null)!==(t.agentId??null))return!0;let[n,o]=[Qt(e),Qt(t)];return n!==null&&o!==null&&JSON.stringify(n)!==JSON.stringify(o)?!0:n===null||o===null?!1:ds(e,t)}function ds(e,t){let[n,o]=[Zt(e),Zt(t)],r=(i,l)=>i.some(a=>!l.includes(a))&&l.some(a=>!i.includes(a));for(let i of["actions","anchors","numbers","operators"])if(r(n[i],o[i]))return!0;for(let i of n.actions.filter(l=>o.actions.includes(l))){let l=n.bindings.filter(c=>c.action===i),a=o.bindings.filter(c=>c.action===i);if(l.length&&a.length&&l.every(c=>a.every(f=>r(c.objects,f.objects)||c.denied!==f.denied||r(c.relations,f.relations))))return!0}for(let i of new Set(n.bindings.map(l=>JSON.stringify(l.objects)))){let l=a=>a.bindings.filter(c=>JSON.stringify(c.objects)===i).map(c=>c.action);if(r(l(n),l(o)))return!0}let s=i=>i.direction.filter(l=>l!=="negative");return!!r(s(n),s(o))}function sm(e){for(let f of[e.previous,e.current])if(f.some(u=>!u.id||!u.fingerprint)||new Set(f.map(u=>u.id)).size!==f.length)throw new Error("Missing or duplicate finding identities.");let t=e.previous.flatMap(f=>e.current.flatMap(u=>($e(f)===$e(u)?!e.enabled||!ya(f,u):e.enabled&&xa(f,u))?[{previous:f,current:u}]:[])),n=[],o=new Set,r=new Set,s=(f,u)=>{for(let p of f)f.filter(g=>g.previous.id===p.previous.id).length!==1||f.filter(g=>g.current.id===p.current.id).length!==1||(n.push({previousId:p.previous.id,currentId:p.current.id,fingerprint:e.enabled?p.previous.fingerprint:$e(p.previous),reason:u}),o.add(p.previous.id),r.add(p.current.id))};s(t.filter(f=>$e(f.previous)===$e(f.current)),"legacy");let i=t.filter(f=>!o.has(f.previous.id)&&!r.has(f.current.id));e.enabled&&s(i,"meaning");let l=i.filter(f=>!o.has(f.previous.id)&&!r.has(f.current.id)),a=new Map;for(let f of l){let u=l.filter(m=>m.current.id===f.current.id).map(m=>m.previous.id).sort(),p=l.filter(m=>m.previous.id===f.previous.id).map(m=>m.current.id).sort(),g={reason:"ambiguous",previousIds:u,currentIds:p};a.set(JSON.stringify(g),g)}n.sort((f,u)=>f.previousId.localeCompare(u.previousId)||f.currentId.localeCompare(u.currentId));let c=new Map(n.map(f=>[f.currentId,f]));return{matches:n,unmatchedPrevious:e.previous.filter(f=>!o.has(f.id)),unmatchedCurrent:e.current.filter(f=>!r.has(f.id)),currentIdentities:e.current.map(f=>({currentId:f.id,legacyFingerprint:$e(f),matchedFingerprint:c.get(f.id)?.fingerprint??$e(f),matchedId:c.get(f.id)?.previousId??f.id})),diagnostics:[...a.entries()].sort(([f],[u])=>f.localeCompare(u)).map(([,f])=>f)}}var ms=e=>[...e.site?[{...e.site,excerpt:e.excerpt}]:[],...e.otherSites??[]];function cs(e){let t=ms(e),n=new Map;for(let o of t){let r=JSON.stringify([o.path,o.line??null]);(!n.has(r)||(o.line??0)>0&&o.excerpt?.trim())&&n.set(r,o)}return[...n.values()].sort((o,r)=>o.path.localeCompare(r.path)||(o.line??-1)-(r.line??-1))}function im(e,t){if(e.category!==t.category)return!1;let[n,o]=[cs(e),cs(t)];return n.length===o.length&&n.every((r,s)=>r.path===o[s].path&&(r.line==null||o[s].line==null?r.line==o[s].line:Math.abs(r.line-o[s].line)<=3))}function lm(e,t){let[n,o]=[us(e,"a"),us(t,"b")];if((n.agentId??null)!==(o.agentId??null)||ds(n,o))return!1;let r=(f,u)=>f.omittedSites&&!!u.excerpt?.trim()||f.sites.some(p=>!!p.quote.trim()&&(!p.path||!Number.isInteger(p.startLine)||p.startLine<1||p.verified===!1));if(r(n,e)||r(o,t))return!1;let s=f=>{let u=new Map;for(let p of f.sites){if(!p.quote.trim())continue;let g=JSON.stringify([p.repoKey,p.path,p.startLine]);(!u.has(g)||u.get(g).endLine<p.endLine)&&u.set(g,p)}return[...u.values()]},[i,l]=[s(n),s(o)].sort((f,u)=>f.length-u.length);if(!i.length||e.category!==t.category&&i.length<2||i.length===1&&He(e.cause).toLowerCase()!==He(t.cause).toLowerCase()&&!ps(n,o))return!1;let a=(f,u)=>f.repoKey===u.repoKey&&f.path===u.path&&f.startLine<=u.endLine&&u.startLine<=f.endLine,c=(f,u)=>f===i.length||l.some((p,g)=>u.has(g)||!a(i[f],p)?!1:c(f+1,new Set([...u,g])));return c(0,new Set)}function us(e,t){return{id:t,fingerprint:ro(e),kind:e.kind,title:e.title,category:e.category,cause:e.cause,agentId:e.agentId,omittedSites:+!e.site,sites:ms(e).map(n=>({repoKey:n.repo??e.siteRepo??"",path:n.path,startLine:n.line??0,endLine:(n.line??0)+(n.excerpt?.split(`
11
- `).length??1)-1,quote:n.excerpt??"",...n.verified!==void 0?{verified:n.verified}:{}}))}}var Sa="users";function gs(e){let t=_o.safeParse(e);return t.success?t.data:Sa}function hs(e,t){if(sn(t))return gs(e)}function ka(e){let t={users:[],team:[]};for(let n of e)t[gs(n.audience)].push(n);return t}function fm(e){if(!e.every(t=>t===void 0))return e.every(t=>t==="team")?"team":"users"}function io(e,t,n,o,r){if(t===null)return null;let s=e.safeParse(t);return s.success?s.data:(r.push(`${o}: ${n} "${t}" is not one of ${Object.values(e.enum).join(", ")} \u2014 dropped`),null)}var ao=12,xs=3,lo=3;function ys(e,t){return Object.keys(e).find(n=>e[n].has(t))}function wa(e,t,n=ao,o={}){let r=[],s=e;if(an(o)){let c=e.filter(f=>f.category==="better_as_code");if(c.length>xs){let f=c.sort((p,g)=>eo(p.severity)-eo(g.severity)).slice(0,xs),u=0;s=e.flatMap(p=>p.category!=="better_as_code"?[p]:u<f.length?[f[u++]]:[])}}let i=s.slice(0,n);s.length>n&&!(an(o)&&n>ao)&&r.push(`the model proposed ${s.length} findings; keeping the first ${n}`);let l=c=>{let f=(c.otherSites??[]).flatMap(g=>{let m=cn.safeParse(g);return m.success?[m.data]:(r.push(`finding "${c.title}" listed an other site in a shape we could not read \u2014 dropped`),[])});f.length>lo&&r.push(`finding "${c.title}" quoted ${f.length} other sites; keeping the first ${lo}`);let u=f.slice(0,lo).flatMap(g=>{let m=ys(t,g.path);return m?[{...g,repo:m}]:(r.push(`finding "${c.title}" also cited ${g.path}, which the analysis never read \u2014 that site dropped`),[])});if(!c.site)return{...c,siteRepo:null,otherSites:u};let p=ys(t,c.site.path);return p?{...c,siteRepo:p,otherSites:u}:(r.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:u})};return{findings:i.map(c=>{let{audience:f,...u}=l(c),p=hs(f,o),g=as(u);return r.push(...g.warnings),{...u,...p===void 0?{}:{audience:p},summary:is(u.summary),fixes:g.fixes,question:g.question}}),warnings:r}}function ba(e){let t=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),n=[...new Set(e.targetFiles.map(o=>o.path.trim().replace(/^(\.\/)+/,"")))].sort().join(`
12
- `);return[e.kind,t,n].join("|")}function _a(e,t,n){if(!e)return{delta:null,warnings:[]};let o=[],r=[];for(let l of e.nodes){let a=io(ln,l.change,`delta node ${l.id} change`,n,o);if(a){if(a!=="added"&&!t.has(l.id)){o.push(`${n}: dropped delta node ${l.id} (not in the architecture)`);continue}r.push({id:l.id,change:a,label:l.label})}}let s=new Set([...t,...r.map(l=>l.id)]),i=[];for(let l of e.edges){let a=`${l.from} \u2192 ${l.to}`,c=io(ln,l.change,`delta edge ${a} change`,n,o),f=io(Eo,l.kind,`delta edge ${a} kind`,n,o);if(!(!c||!f)){if(!s.has(l.from)||!s.has(l.to)){o.push(`${n}: dropped delta edge ${a} (unknown node)`);continue}i.push({from:l.from,to:l.to,kind:f,change:c,detail:l.detail})}}return r.length===0&&i.length===0?{delta:null,warnings:o}:{delta:{nodes:r,edges:i},warnings:o}}function Ea(e){return ro(e)}function Ra(e){let t=e.split(`
13
- `);return t.length>1&&t[t.length-1]===""&&t.pop(),t.map((n,o)=>`${o+1} ${n}`).join(`
14
- `)}function en(e){return{label:e,brand:Yt(e)}}function Fm(e,t,n,o,r){let s=[],i=a=>{s.push(...a.tools.map(c=>c.name)),r.push(...a.warnings.map(c=>`${t}: ${c}`))};if(o.toolsPath)try{s.push(...tr(n[o.toolsPath]).tools.map(a=>a.name))}catch{r.push(`${t}: tools.json is not a valid tool list; ignored`)}o.toolsTsPath&&i(ns(n[o.toolsTsPath])),o.cliPath&&i(rs(n[o.cliPath]));let l=[];if(o.mcpPath){let a=er(n[o.mcpPath],o.mcpPath,o.toolsPath!==null);l.push(...a.servers),r.push(...a.warnings.map(c=>`${t}: ${c}`))}return[...new Set(s)].map(en).concat(l.map(a=>({...en(a),source:"mcp"})))}function Ss(e){let t=e.sourceRef?.repo?`${e.sourceRef.repo}#`:null;return e.unitKey??(t&&e.id.startsWith(t)?e.id.slice(t.length):e.id.startsWith("model:")?e.id:e.id.slice(e.id.indexOf("#")+1))}function ks(e){return Ss(e).startsWith("model:")}function Zn(e){return new Set(e.nodes.filter(ks).flatMap(t=>[...(t.files??[]).map(n=>n.path),...t.sourceRef?[t.sourceRef.path]:[]]))}function Qn(e,t){let n=e.trim().replace(/^(\.\/)+/,"");if(!t)return n.includes(" \u203A ")&&n.slice(n.lastIndexOf(" \u203A ")+3).includes("/");if(t.has(n))return!0;for(let o of t){let r=o.indexOf(" \u203A ");if(r>=0&&n.startsWith(o.slice(0,r+3)))return!0}return!1}async function Vm(e,t,n,o,r=!1,s){if(t)return t;let i={enabled:o??e.CF_ANALYSIS_IMPORTED_AGENTS!=="0",byRepo:{}};if(!i.enabled)return i;Lt(e)&&(i.grouped=!0);let l=await n?.()??[];r&&(i.agentRows=structuredClone(s?.length?[...s]: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:")&&(!r||!a.codeInputsJson))continue;let c=Oo(a.repoPath);if(!c)continue;let f=a.unitKey.startsWith("model:")?i.byRepo:i.codeByRepo??={};(f[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 bs(e,t){let n=e.slice(6).split("#")[0];return va(n,t)}function va(e,t){return t?B(e,bt(t))??e:e}function ws(e){return`${bs(e.unitKey)} \u203A ${e.name}`}function co(e,t,n=""){let o=e?.enabled?e.byRepo[t]??[]:[],r=o.map(ws),s=new Set(Object.entries(e?.enabled?e.byRepo:{}).filter(([a])=>a!==t).flatMap(([,a])=>a.map(ws))),i=o.map((a,c)=>{let f=r.filter(h=>h===r[c]).length>1?`${r[c]} (${a.unitKey.split("#").slice(1).join("#")})`:r[c],u=s.has(r[c])?`${t} \u203A ${f}`:f,p=`${u}/system_prompt.md`,g={[p]:a.systemPrompt??n},m=[{role:"system prompt",label:null,path:p}];if(a.toolsJson?.length){let h=`${u}/tools.json`;g[h]=JSON.stringify(a.toolsJson,null,2),m.push({role:"tools",label:null,path:h})}if(a.services?.length){let h=`${u}/context.md`,k=a.services.map(({name:w,kind:b})=>`${Zo(w)}${b===w?"":` (${b})`}`);g[h]=`This agent's code (not the model) reads from or writes to: ${k.join(", ")}.`,m.push({role:"reference",label:"Context",path:h})}return{node:{id:a.unitKey,label:a.name,kind:"agent",desc:"",meta:a.model,sourceRef:{path:p,line:1},files:m,tools:(a.toolsJson??[]).map(h=>en(h.name))},files:g,keys:[a.unitKey],sourcePath:bs(a.unitKey,t),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 f=o[c].groupKey?`group:${o[c].groupKey}`:`step:${c}`,u=l.get(f)??[];u.push(a),l.set(f,u)}),[...l.values()].map(a=>{let c=a[0],f=o.find(u=>u.unitKey===c.node.id);return{...c,steps:a,keys:a.flatMap(u=>u.keys),files:Object.assign({},...a.map(u=>u.files)),node:{...c.node,label:f.groupName??f.name,sourcePaths:[...new Set(a.map(u=>u.sourcePath))],files:a.flatMap(u=>u.node.files),tools:[...new Map(a.flatMap(u=>u.node.tools).map(u=>[u.label,u])).values()]}}})}function _s(e,t){return co(e,t).flatMap(({steps:n})=>n.flatMap(({files:o,sourcePath:r,agentKey:s})=>Object.entries(o).map(([i,l])=>({path:i,text:l,sourcePath:r,agentKey:s,role:i.slice(i.lastIndexOf("/")+1)}))))}function qm(e,t,n,o=""){let r=new Set(n.nodes.filter(f=>f.kind==="agent").map(f=>f.id)),s=[],i={},l=co(e,t,o);for(let f of l)r.has(f.node.id)||(r.add(f.node.id),s.push(f.node),Object.assign(i,f.files));let a=new Map(l.flatMap(f=>f.keys.map(u=>[u,f.node.id]))),c=Qo((e?.enabled?e.byRepo[t]??[]:[]).filter(f=>r.has(a.get(f.unitKey)??f.unitKey)).map(f=>{let u=a.get(f.unitKey)??f.unitKey;return{...f,id:u,scope:t,links:f.links?.map(p=>({...p,to:a.get(p.to)??p.to})).filter(p=>!e?.grouped||p.to!==u),unitKey:u}}));return{nodes:s,files:i,edges:c}}function Xm(e,t,n){return n.length?t.filter(o=>!o.startsWith(`${e}: no agent found \u2014`)&&!o.startsWith(`${e}: no agent conventions found (`)):t}function Hm(e,t,n){let o=new Set(co(e,t).flatMap(r=>Object.keys(r.files)));return o.size?Object.fromEntries(Object.entries(n).filter(([r])=>!o.has(r))):n}import{posix as Z}from"node:path";function Es(e,t){if(t==="markdown"){let l=e.startsWith("---")?e.indexOf(`
15
- ---`,3):-1;return l<0?null:{start:3,end:l+1,bodyStart:l+4,newline:`
16
- `,raw:e.slice(3,l).split(`
17
- `)}}if(t==="outline"){let l=e.split(`
18
- `),a=l[0]==="---"?l.indexOf("---",1):-1;if(a<0)return null;let c=l.slice(0,a).join(`
19
- `).length+1;return{start:4,end:c,bodyStart:Math.min(e.length,c+4),newline:`
20
- `,raw:l.slice(1,a)}}let n=/^\uFEFF?---(\r?\n)/.exec(e);if(!n)return null;let o=e.slice(n[0].length),r=/^---(?:\r?\n|$)/m.exec(o);if(!r)return null;let s=o.slice(0,r.index),i=n[0].length+r.index;return{start:n[0].length,end:i,bodyStart:i+r[0].length,newline:n[1],raw:s?s.slice(0,-1).split(`
21
- `):[]}}function vs(e){return(e.startsWith('"')?e.match(/^"((?:\\.|[^"\\])*)"\s*(?:#.*)?$/):e.match(/^'((?:''|[^'])*)'\s*(?:#.*)?$/))?.[1]??null}function Rs(e,t=!1){if(!e||e.startsWith("#"))return null;if(e.startsWith('"')||e.startsWith("'"))return vs(e);let n=e.replace(/\s+#.*$/,"");if(t&&/:\s*$/.test(n))return null;let o=t?n.trimEnd():n;return/^[[\]{}&*!?@`%|>]|^-(?:\s|$)|:\s/.test(o)||/^(?:[-+]?\d|[-+]?\.\d|[-+]?\.(?:inf|nan)$|null$|~$|true$|false$|yes$|no$|on$|off$|y$|n$)/i.test(o)?null:n}function Oa(e,t=!1,n=!1){let o=[],r=new Map,s=null;return e.map(i=>{let l=i.replace(/\r$/,""),a=l.length-l.trimStart().length,c=()=>o.map(({key:x})=>x).join(".")||null;if(s&&(!l.trim()||a>s.indent))return l.trim()&&(s.contentIndent??=a),{location:c(),text:l.slice(s.contentIndent??a),keys:s.keys};if(s=null,!l.trim()||l.trimStart().startsWith("#"))return{location:c()};for(;o.length&&o.at(-1).indent>=a;)o.pop();if(n&&/^\s*-\s/.test(l)){let x=o.map(({key:w})=>w),h=JSON.stringify(x),k=r.get(h)??0;return r.set(h,k+1),{location:c(),keys:[...x,k]}}let f=l.match(/^\s*([\w.-]+):(?:\s+(.*))?$/);if(!f)return{location:c()};let u=f[2]??"",p=[...o.map(({key:x})=>x),f[1]];if(!u||u.startsWith("#"))return o.push({indent:a,key:f[1]}),{location:c(),...n?{keys:p}:{}};if(/^[|>][+-]?\s*(?:#.*)?$/.test(u))return s={indent:a,keys:p},{location:c()};let g=u.match(/^(["'])(.*)\1\s*(?:#.*)?$/),m=t?vs(u)??u.replace(/\s+#.*$/,""):g?g[2]:u.replace(/\s+#.*$/,"");return{location:c(),text:m,keys:p}})}function uo(e,t={}){let n=e.split(`
22
- `).map(i=>i.replace(/\r$/,"")),o=Oa(n,!0),r={},s=[{indent:-1,value:r}];for(let i=0;i<n.length;i++){let l=n[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+(.*))?$/),f=l.match(/^\s*-(?:\s+(.*))?$/);if(!c&&!f)return null;for(;s.at(-1).indent>=a;)s.pop();let u=s.at(-1);if(u.childIndent??=a,u.childIndent!==a||u.indent===-1&&a!==0)return null;if(f){if(!t.lists)return null;let m=Rs(f[1]??"",!0);if(m===null||s.length===1)return null;if(!Array.isArray(u.value)){if(Object.keys(u.value).length)return null;u.value=[],Object.defineProperty(s.at(-2).value,u.key,{value:u.value,enumerable:!0,writable:!0})}u.value.push(m);continue}if(!c||Array.isArray(u.value)||Object.hasOwn(u.value,c[1]))return null;let p=c[2]??"";if(!p||p.startsWith("#")){let m={};Object.defineProperty(u.value,c[1],{value:m,enumerable:!0,writable:!0}),s.push({indent:a,key:c[1],value:m});continue}let g;if(/^[|>][+-]?\s*(?:#.*)?$/.test(p)){let m=i+1,x;for(;i+1<n.length;){let k=n[i+1],w=k.length-k.trimStart().length;if(k.trim()&&w<=a)break;if(k.includes(" ")||k.trim()&&(x??=w,w<x))return null;i++}let h=i;g=o.slice(m,h+1).flatMap(({text:k})=>k===void 0?[]:[k]).join(`
23
- `)}else{let m=Rs(p);if(m===null)return null;g=m}Object.defineProperty(u.value,c[1],{value:g,enumerable:!0,writable:!0})}return r}function eg(e){let t=uo(e,{lists:!0});return t?fo(e,{legacyBoundaries:!0}).map(n=>({key:n.key,value:t[n.key],span:n.span})):null}function fo(e,t={}){let n=e.split(`
24
- `),o=n.flatMap((r,s)=>(t.legacyBoundaries?r.trim()&&!/^\s|^#/.test(r):/^[\w.-]+:(?:\s|$)/.test(r))?[s]:[]);return o.map((r,s)=>{let i=n[r].slice(0,n[r].indexOf(":")),l=o[s+1]??n.length;for(;l>o[s]+1&&!n[l-1].trim();)l--;return{key:i,span:{from:r+1,to:l}}})}function po(e){let t=e.split(/^---(?:\s+#.*)?\s*$/m);if(t.length>1)return[...new Set(t.flatMap(po))];let n=e.split(`
25
- `).filter(i=>i.trim()&&!/^\s*(?:#|---\s*$|\.\.\.\s*$|%[A-Z])/.test(i)),o=n.join(`
26
- `).trimStart().replace(/^(?:(?:&[\w.-]+|!<[^>]+>|![\w:/.!-]+)\s+)+/,"");if(o.startsWith("{"))return Ia(o);let r=i=>i.length-i.trimStart().length,s=n.reduce((i,l)=>Math.min(i,r(l)),1/0);return n.flatMap(i=>{let l=/^["']?([\w.-]+)["']?\s*:/.exec(i.trimStart());return r(i)===s&&l?[l[1]]:[]})}function Ia(e){let t=[],n=[],o="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(o){i==="\\"&&o==='"'?s++:i===o&&(o==="'"&&e[s+1]==="'"?s++:o="");continue}if(i==="#"&&/\s/.test(e[s-1]??" ")){for(;s<e.length&&e[s]!==`
27
- `;)s++;continue}if(r&&n.length===1&&!/\s/.test(i)&&i!=="}"&&i!=="?"){let l=/^(?:"((?:\\.|[^"\\])*)"|'((?:''|[^'])*)'|([\w.-]+))\s*:/.exec(e.slice(s));if(!l)return[];try{t.push(l[1]!==void 0?JSON.parse(`"${l[1]}"`):l[2]?.replace(/''/g,"'")??l[3])}catch{return[]}s+=l[0].length-1,r=!1;continue}if(i==='"'||i==="'")o=i;else if(i==="{"||i==="[")n.push(i),n.length===1&&(r=!0);else if(i==="}"||i==="]"){if(n.pop()!==(i==="}"?"{":"["))return[];if(!n.length)return t}else i===","&&n.length===1&&(r=!0)}return[]}function yt(e,t){return X(e)?[...new Set(t)].filter(n=>Is(n)&&/(?:^|\/)\.claude-plugin\/(?:plugin|marketplace)\.json$/i.test(n)).sort():[]}function sg(e,t,n={}){return yt(e,t).flatMap(o=>{let r=/^(?:(.*)\/)?\.claude-plugin\/plugin\.json$/i.exec(o);if(r)return[{folder:r[1]??"",path:o}];let s=o.split("/").slice(0,-2).join("/");try{let i=JSON.parse(n[o]);return!i||typeof i!="object"||!("plugins"in i)||!Array.isArray(i.plugins)?[]:[...new Set(i.plugins.flatMap(l=>{if(!l||typeof l!="object"||typeof l.source!="string")return[];let a=l.source.replace(/^\.\//,"");return Is(a)?[Fe(a,s)]:[]}))].map(l=>({folder:l,path:o}))}catch{return[]}})}function Is(e){return!/[\\:\0?*#%]/.test(e)&&!e.split("/").some(t=>!t||t==="."||t==="..")}function ig(e,t,n){let o=t.split("/");for(let r=0;r<o.length-2;r++)if(!(o[r].toLowerCase()!=="plugins"||!o[r+1])&&Os(e,o.slice(r+2).join("/")))return o.slice(0,r+2).join("/");for(let r of[...n].sort((s,i)=>i.folder.length-s.folder.length)){let s=B(t,r.folder);if(s!==null&&Os(e,s))return r.folder}return null}function Os(e,t){return t.toLowerCase().startsWith(`${nt}/`)&&bn.test(t)||!!(_e(e)&&t.toLowerCase().startsWith(`${be}/`)&&ae(t)?.definition)}function mo(e,t,n={}){if(!X(e))return[];let o=[...new Set(t)].filter(s=>!/[\\:\0]/.test(s)&&s.split("/").every(i=>i&&i!=="."&&i!=="..")).sort(),r=new Map;for(let s of o){let i=/^(?:(.*)\/)?environments\/[^/]+\.ya?ml$/i.exec(s),l=/^(?:(.*)\/)?agents\/[^/]+\/environment\.ya?ml$/i.exec(s),a=i?.[1]??l?.[1]??(i||l?"":null);if(a===null||r.has(a))continue;let c=p=>B(p,a),f=o.filter(p=>/^agents\/(?:[^/]+\.md|[^/]+\/agent\.md)$/i.test(c(p)??""));if(!f.length)continue;let u=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)??""));r.set(a,{folder:a,agents:f,configs:u})}for(let s of r.values())for(let i of s.agents){if(n[i]===void 0)continue;let l=La(i,n[i],s,o);for(let a of l.configPaths)s.configs.includes(a)||s.configs.push(a);for(let a of l.relationships)a.kind==="config"&&n[a.path]!==void 0&&Aa(n[a.path])&&!s.configs.includes(a.path)&&s.configs.push(a.path)}return[...r.values()].sort((s,i)=>s.folder<i.folder?-1:s.folder>i.folder?1:0)}function gg(e,t,n){let o=mo(e,t,n).filter(s=>s.agents.some(i=>n[i]===void 0)),r=new Set(yt(e,t));return t.filter(s=>!r.has(s)&&/\.(?:ya?ml|json|md)$/i.test(s)&&o.some(i=>B(s,i.folder)!==null&&!i.agents.includes(s)&&!i.configs.includes(s)))}function La(e,t,n,o){let r=Es(t),s=r?.raw.join(`
28
- `)??"",i=new Map(fo(s).map(h=>[h.key,s.split(`
29
- `).slice(h.span.from-1,h.span.to).join(`
30
- `)])),l=h=>i.has(h)?uo(i.get(h),{lists:!0})?.[h]:void 0,a=h=>typeof l(h)=="string"?l(h):null,c={path:e,name:a("name")??Z.basename(e,".md"),model:a("model"),description:a("description"),prompt:r?t.slice(r.bodyStart).trim():t.trim(),relationships:[],refused:[],configPaths:[]};r||c.refused.push({path:e,reason:"invalid"});let f=(h,k,w=!1)=>{if(/[\\:\0${}*]/.test(h)||h.startsWith("/")){c.refused.push({path:e,reason:"dynamic"});return}let b=Z.normalize(Z.join(Z.dirname(e),h));if(B(b,n.folder)===null||b===".."||b.startsWith("../")){c.refused.push({path:b,reason:"out-of-scope"});return}if(!o.includes(b)){c.refused.push({path:b,reason:"missing"});return}if(k==="agent"&&!n.agents.includes(b)){c.refused.push({path:b,reason:"out-of-scope"});return}c.relationships.some(S=>S.path===b&&S.kind===k)||c.relationships.push({path:b,kind:k}),w&&!c.configPaths.includes(b)&&c.configPaths.push(b)},u=(h,k)=>{let w=l(h);if(w===void 0&&!i.has(h))return;let b=typeof w=="string"?[w]:Array.isArray(w)?w:[];if(!b.length||b.some(S=>typeof S!="string")){c.refused.push({path:e,reason:"dynamic"});return}for(let S of b)f(S,k,k==="config")};for(let h of["environment","policy","vault","vault_schema"])u(h,"config");u("skills","skill");let p=l("multiagent");if(p&&typeof p=="object"&&"agents"in p&&Array.isArray(p.agents))for(let h of p.agents)typeof h=="string"?f(h,"agent"):c.refused.push({path:e,reason:"dynamic"});else i.has("multiagent")&&c.refused.push({path:e,reason:"dynamic"});let g=Z.basename(e,".md"),m=g.toLowerCase()==="agent",x=m?n.configs.filter(h=>Z.dirname(h)===Z.dirname(e)&&/\/environment\.ya?ml$/i.test(h)):n.configs.filter(h=>B(h,n.folder)?.match(/^environments\/([^/]+)\.ya?ml$/i)?.[1]===g);if(!i.has("environment")){let h=n.agents.length===1?n.configs.filter(k=>/^environments\/[^/]+\.ya?ml$/i.test(B(k,n.folder))):[];for(let k of x.length?x:h.length===1?h:[])f(Z.relative(Z.dirname(e),k),"config")}if(!i.has("policy")&&(m||n.agents.length===1))for(let h of n.configs.filter(k=>/(?:^|\/)policy\.ya?ml$/i.test(k)&&Z.dirname(k)===(m?Z.dirname(e):n.folder)))f(Z.relative(Z.dirname(e),h),"config");for(let h of c.prompt.matchAll(/(?:\]\(|[`\s])((?:\.\.?\/)[^\s`"'()]+\.(?:ya?ml|json|md))(?:[)`\s]|$)/g))f(h[1],/\/SKILL\.md$/i.test(h[1])?"skill":"config");return c}function Aa(e){let t=/^(?:config|networking|filesystem_policy|network_policies|policy|permissions|auth|injection_location|secret_name)$/;return po(e).some(n=>t.test(n))}function zg(e){return e==="skill"?"skill":"definition"}var ho=class extends Error{reason;constructor(t,n){super(t==="secret"?Et(n):t==="secret-content"?bo(n):`File was not read: ${t}.`),this.reason=t}},yo=["html"],Ps=["md","json","yaml","yml",...yo],So=e=>new RegExp(`\\.(?:${e.join("|")})$`,"i"),Ma=So(Ps),Ca=So(yo),ja=So(["ts","tsx","js","jsx","py","go","rb","java","rs","toml",...Ps.filter(e=>!yo.includes(e))]);function $s(e,t,n){return t=Mt(e,t,n),yn(t)&&Ca.test(t)}function Na(e,t,n){return t=Mt(e,t,n),yn(t)&&Ma.test(t)&&(_e(e)||!$s(e,t))}function Ta(e,t,n){return ja.test(t)||Na(e,t,n)||ne(e)&&Ct(t)}function Fa(e,t,n=[]){if(!Ke(e)||!t.toLowerCase().endsWith(".md"))return!1;let o=t.split("/");return o.some((r,s)=>r.toLowerCase()==="commands"&&s<o.length-1&&(o[s-1]?.toLowerCase()===Ee||n.includes(o.slice(0,s).join("/"))))}function Ms(e,t,n=!1){if(!fn(t,n)||Fa(e,t))return!1;let o=[Ee,...$t.filter(s=>s.startsWith(".")),F.cli],r="";for(let s of t.toLowerCase().split("/")){let i=r?`${r}/${s}`:s,l=yt(e,[i]).length>0,a=X(e)&&(s===".claude-plugin"||l);if(s.startsWith(".")&&!o.includes(s)&&!a||r.split("/").at(-1)===".claude-plugin"&&!l||r===Ee&&!et.includes(`${r}/${s}`)&&!(Pt.includes(`${r}/${s}`)&&_e(e)))return!1;r=r?`${r}/${s}`:s}return!0}var qo=/(prompt|tool|agent|config|instruction)/i,Ls=/\.(md|json|ts|js|py|yaml|yml|txt)$/i,kt=/(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock|go\.sum)$|\.lock$/i,Da=/(^|\/)(node_modules|dist|build|out|vendor|target|__pycache__|coverage)\//i,wt=new RegExp(`${Da.source}|\\.min\\.|\\.(png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|pdf|zip|gz|jar|bin|map)$`,"i"),St=new RegExp(`${wt.source}|${Do.source}|${kt.source}|${un.source}`,"i"),Ba=/\.(ts|tsx|js|jsx|mjs|cjs|py)$/i,Cs=new RegExp(`(^|/)(${It.join("|")}|cassettes|docs|\\.github)/`,"i"),Wa=/(^|\/)([^/]*\.stories\.[^/]*|[^/]*\.d\.ts)$/i,Ka=new RegExp(`(^|/)(${["test","tests","__tests__","test-support","testdata","fixtures","__fixtures__",...It,"cassettes","mocks","__mocks__","examples","docs","\\.github"].join("|")})/`,"i"),Ga=/(^|\/)([^/]*fixture[^/]*|[^/]*\.stories\.[^/]*|test_[^/]*\.py|conftest\.py|[^/]*\.d\.ts)$/i,tn=/(^|\/)\.git\//i,go=(e,t,n)=>n==="github"?We.conventionImport.fileBytes:void 0,nn=()=>We.codeScan.fileBytes,Ua={entry:{hidden:!0,excluded:[wt,kt,tn]},archive:{hidden:!1,discovery:!0,excluded:[wt,kt,tn]},listing:{hidden:!0},definition:{hidden:!0,discovery:!0,limit:go},skill:{hidden:!0,discovery:!0,limit:go},extraction:{hidden:!0,discovery:!0,accepts:(e,t)=>Ls.test(t),limit:go},source:{hidden:!0,discovery:!0,excluded:[St],empty:!0,accepts:(e,t,n)=>En(e,t,n)||Ta(e,t,n),limit:(e,t,n,o)=>En(e,t,o)?void 0:$s(e,t,o)?We.sourceFetch.htmlReferenceBytes:We.sourceFetch.codeFileBytes},"code-scan":{hidden:!0,discovery:!0,excluded:[St,Cs,Wa],relativeExclusions:!0,excludeExamples:!0,accepts:(e,t)=>Ba.test(t)||Ct(t)||Ke(e)&&Rn(t)&&Ms(e,t),limit:nn},"code-support":{hidden:!0,excluded:[St],accepts:(e,t)=>W(t)!==null,limit:nn},pointer:{hidden:!1,limit:nn},proposal:{hidden:!0,excluded:[wt,kt,tn],empty:!0,limit:nn},survey:{hidden:!0,discovery:!0,excluded:[St,tn],relativeExclusions:!0,accepts:(e,t)=>Ls.test(t)||Yo(t)==="code",limit:()=>We.survey.fileBytes},override:{hidden:!1}};function Ge(e,t,n){return xo(e,t,n,!0)}var za=/(?:^|\/)(?:vault\.ya?ml|(?:vaults?|auth)\/(?:credentials?|values?|tokens?)(?:\.[^/]+)?)$/i;function Ja(e){let t=e.path.replace(/\\/g,"/");if(e.text===void 0||!/\.(?:ya?ml|json|md)$/i.test(t))return!1;let n=e.text,o=/(?:^|[\n{,])\s*(?:-\s*)?["']?(?:secret(?:_value)?|api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|client[_-]?secret|private[_-]?key|credentials?)["']?\s*:/gim,r=/(?:^|[\n{,])\s*(?:-\s*)?["']?[A-Z][A-Z0-9_]*(?:_KEY|_TOKEN|_PASSWORD|_SECRET)["']?\s*:/gm;return[...n.matchAll(o),...n.matchAll(r)].some(i=>!/^\s*(["']?)(?:\$\{[A-Z_][A-Z0-9_]*\}|\$[A-Z_][A-Z0-9_]*)\1[^\S\n]*(?:#[^\n]*)?(?:[,}\r\n]|$)/.test(n.slice(i.index+i[0].length)))||/["']?auth["']?\s*:/.test(n)&&/(?:^|[\n{,])\s*["']?value["']?\s*:/m.test(n)||/-----BEGIN (?:[A-Z ]*PRIVATE KEY|CERTIFICATE)-----/.test(n)}function xo(e,t,n,o){let r=Io(e,t,{...n,allowSelectedFile:n.purpose==="override",requireLocalTarget:n.purpose==="proposal"});if(!r.admitted)return r;let s=B(t.path,n.root);if(X(e)&&za.test(t.path.replace(/\\/g,"/")))return{admitted:!1,reason:"secret"};if(X(e)&&Ja(t)&&(!n.listing||mo(e,[...n.listing.keys()],t.text===void 0?n.managedFiles:{...n.managedFiles,[t.path]:t.text}).some(u=>u.configs.includes(t.path)&&!/\/SKILL\.md$/i.test(t.path))))return{admitted:!1,reason:"secret"};if(n.route==="local-folder"&&(n.purpose==="proposal"||n.purpose==="entry")&&n.localTarget){let u=Pa(n.localTarget.root,n.localTarget.path).split($a).join("/"),p=xo(e,{...t,path:u},{...n,root:void 0,localTarget:void 0,gitIgnored:n.purpose==="entry"?n.gitIgnored:void 0},o);if(!p.admitted)return p}let i=Ua[n.purpose];if(n.purpose==="proposal"&&ye(s))return{admitted:!1,reason:"wrong-type"};if(i.discovery&&Go(e,t.path,n.root))return{admitted:!1,reason:"excluded"};if(i.hidden&&n.route!=="github"&&!Ms(e,t.path,t.directory))return{admitted:!1,reason:"hidden"};if(i.hidden&&n.route==="local-folder"&&t.path.split("/").includes("node_modules"))return{admitted:!1,reason:"excluded"};let l=i.relativeExclusions?s:t.path,a=we(e,t.path,n.root);if(!["listing","pointer","override"].includes(n.purpose)&&mn(e,t.path,n))return{admitted:!1,reason:"excluded"};if(i.excluded?.some(u=>a&&u===Cs?!1:a&&u===St?wt.test(l)||kt.test(l):u.test(l)))return{admitted:!1,reason:"excluded"};if(n.purpose==="archive"&&Lt(e)&&No(s,t.text)&&!a)return{admitted:!1,reason:"excluded"};if(i.excludeExamples&&!a){if(Vo(e)){if(o&&Jo(t.path,{root:n.root??void 0,listing:n.listing,settings:e,key:JSON.stringify([n.root??"",n.route,...n.exclusions?.length?[n.exclusions]:[]]),readable:(u,p)=>xo(e,{path:u,size:p},{...n,localTarget:void 0},!1).admitted}))return{admitted:!1,reason:"excluded"}}else if(Ka.test(l)||Ga.test(l))return{admitted:!1,reason:"excluded"}}if(i.empty&&t.size!==void 0&&t.size<=0)return{admitted:!1,reason:"empty"};if(i.accepts&&!(a?.kind==="example"&&n.purpose==="code-scan"&&/\.md$/i.test(s))&&!i.accepts(e,s,n.scopes))return{admitted:!1,reason:"wrong-type"};let c=i.limit?.(e,s,n.route,n.scopes);if(c!==void 0&&t.size!==void 0&&t.size>c)return{admitted:!1,reason:"too-large"};let f=wo(e,t.text);return f?{admitted:!1,reason:f}:{admitted:!0}}var Va=`
31
- [The rest of this file was not read.]
32
- `;async function qa(e,t,n,o={}){let r=Ge(e,t,{purpose:"override",route:"github",...o});if(!r.admitted)throw new Error(r.reason==="secret"?Et(t.path):`File was not read: ${r.reason}.`);let s=await n(),i=Ge(e,{path:t.path,text:s},{purpose:"override",route:"github",...o});if(!i.admitted)throw new ho(i.reason,t.path);if(t.readBytes===void 0)return s;let l=Buffer.from(s,"utf8");if(l.length<=t.readBytes)return s;let a=Math.min(t.readBytes,l.length);for(;a>0&&(l[a]&192)===128;)a--;return l.subarray(0,a).toString("utf8")+Va}var Xa=4096;function Ha(e,t,n,o={}){let r=rn(e),s=r&&t.readBytes!==void 0?t.readBytes+Xa:void 0;return qa(e,r?t:{path:t.path},async()=>{let i=await n(s===void 0?t:{...t,readBytes:s});if(i===null)throw new Error("File is unavailable.");return s===void 0?i:Buffer.from(i.slice(0,s),"utf8").subarray(0,s).toString("utf8")},o)}var As=new WeakMap;function Ya(e,t){let n=As.get(t);if(n?.settings===e)return t;t=n?.source??t;let o=t.admission;if(!o?.exclusions?.length&&!rn(e))return t;let r,s=()=>r??=(t.listAll?t.listAll():t.list()).then(a=>new Set(a.map(c=>c.path))),i=async a=>{let c=await(a&&t.listAll?t.listAll():t.list());return o?.exclusions?.length?c.filter(f=>Ge(e,f,{purpose:"override",route:"github",...o}).admitted):c},l={repoKey:t.repoKey,root:t.root,source:t.source,admission:o,head:()=>t.head(),linkFor:(...a)=>t.linkFor(...a),list:()=>i(!1),...t.listAll?{listAll:()=>i(!0)}:{},read:async a=>Ha(e,a,c=>t.read(c),{...o,...X(e)?{listing:await s()}:{}})};return As.set(l,{source:t,settings:e}),l}async function Jg(e,t,n){for(let o of n){if(!o.admission?.exclusions?.length)continue;let r=t.repos?.find(c=>c.key===o.repoKey);if(!r)continue;let s=new Map(_s(t.projectAgents,r.key).map(c=>[c.path,Fe(c.sourcePath,bt(r.key))])),i=[...Object.keys(r.files??{}).map(c=>s.get(c)??c),...s.values(),...(r.selected??[]).map(c=>c.path),...(r.scan?.plan??[]).map(c=>c.path)];if(!i.length)continue;let l=Ya(e,o),a=new Set((await(l.listAll?l.listAll():l.list())).map(c=>c.path));for(let c of i)if(!Ge(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{Za as a,Qa as b,Qe as c,Fs as d,De as e,Po as f,Mo as g,Yn as h,Wd as i,Kd as j,Lt as k,Ke as l,ne as m,X as n,J as o,d as p,y as q,Be as r,V as s,Se as t,A as u,j as v,q as w,Ot as x,No as y,We as z,Ko as A,we as B,mn as C,Go as D,ii as E,gn as F,Vo as G,ae as H,ci as I,_c as J,Xo as K,Ct as L,Ri as M,Wc as N,Rn as O,Gc as P,Es as Q,uo as R,eg as S,fo as T,yt as U,sg as V,ig as W,mo as X,gg as Y,La as Z,Aa as _,zg as $,ho as aa,Ps as ba,$s as ca,Na as da,Ta as ea,Fa as fa,Ms as ga,qo as ha,Ls as ia,kt as ja,Da as ka,wt as la,St as ma,Ba as na,Cs as oa,tn as pa,Ge as qa,Va as ra,qa as sa,Ha as ta,Ya as ua,Jg as va,Ac as wa,F as xa,tt as ya,wn as za,pi as Aa,Ee as Ba,nt as Ca,et as Da,Pc as Ea,Pt as Fa,bn as Ga,$c as Ha,_e as Ia,Si as Ja,bi as Ka,Mt as La,En as Ma,Mc as Na,Cc as Oa,jc as Pa,Nc as Qa,Tc as Ra,tr as Sa,Q as Ta,U as Ua,re as Va,yr as Wa,uf as Xa,Fn as Ya,Kt as Za,Ar as _a,mt as $a,Qf as ab,Mr as bb,ep as cb,tp as db,Tr as eb,Ut as fb,Ep as gb,Rp as hb,qr as ib,Xr as jb,Xt as kb,Ed as lb,Rd as mb,vd as nb,ns as ob,Fd as pb,rs as qb,en as rb,Fm as sb,Ss as tb,ks as ub,Zn as vb,Qn as wb,Vm as xb,bs as yb,va as zb,co as Ab,qm as Bb,Xm as Cb,Hm as Db,Yt as Eb,ra as Fb,sa as Gb,ia as Hb,ro as Ib,sm as Jb,cs as Kb,im as Lb,lm as Mb,us as Nb,ka as Ob,fm as Pb,ao as Qb,wa as Rb,ba as Sb,_a as Tb,Ea as Ub,Ra as Vb};