@counterfact-labs/cli 0.1.3 → 0.2.3

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 (181) hide show
  1. package/README.md +176 -42
  2. package/bundle/client-release.json +7 -0
  3. package/bundle/sealed.json +908 -0
  4. package/dist/adapters/anthropic.js +151 -0
  5. package/dist/adapters/completion.js +112 -0
  6. package/dist/adapters/durable-write.js +34 -0
  7. package/dist/adapters/files.js +140 -0
  8. package/dist/adapters/folder-path.js +6 -0
  9. package/dist/adapters/git-ignore.js +49 -0
  10. package/dist/adapters/git.js +44 -0
  11. package/dist/adapters/ignored-files.js +36 -0
  12. package/dist/adapters/instructions.js +35 -0
  13. package/dist/adapters/models.js +51 -0
  14. package/dist/adapters/output-paths.js +92 -0
  15. package/dist/adapters/prompt-cache.js +28 -0
  16. package/dist/adapters/public-instructions.js +36 -0
  17. package/dist/adapters/quality.js +6 -0
  18. package/dist/adapters/relay-plan.js +15 -0
  19. package/dist/adapters/release.js +57 -0
  20. package/dist/adapters/report.js +29 -0
  21. package/dist/adapters/repository-files.js +199 -0
  22. package/dist/adapters/repository-root.js +120 -0
  23. package/dist/adapters/results.js +9 -0
  24. package/dist/adapters/settings.js +25 -0
  25. package/dist/adapters/snapshot.js +68 -0
  26. package/dist/analysis-core/analysis/analysis-flags.js +1 -0
  27. package/dist/analysis-core/analysis/code-agents/skipped-files.js +1 -0
  28. package/dist/analysis-core/analysis/finding-quality/config.js +1 -0
  29. package/dist/analysis-core/analysis/finding-quality/policy.js +1 -0
  30. package/dist/analysis-core/analysis/headlines/attachment.js +1 -0
  31. package/dist/analysis-core/analysis/headlines/input.js +1 -0
  32. package/dist/analysis-core/analysis/headlines/types.js +1 -0
  33. package/dist/analysis-core/analysis/schemas.js +1 -0
  34. package/dist/analysis-core/analysis/source-notes/types.js +1 -0
  35. package/dist/analysis-core/chunks/2PSNOSJ2.js +1 -0
  36. package/dist/analysis-core/chunks/3227KXHF.js +1 -0
  37. package/dist/analysis-core/chunks/326F4XNG.js +1 -0
  38. package/dist/analysis-core/chunks/3MTXB4MK.js +6 -0
  39. package/dist/analysis-core/chunks/4F6ZIHXU.js +1 -0
  40. package/dist/analysis-core/chunks/57M4OQJM.js +1 -0
  41. package/dist/analysis-core/chunks/6YCABS5T.js +1 -0
  42. package/dist/analysis-core/chunks/724WZMYW.js +2 -0
  43. package/dist/analysis-core/chunks/74FPPPIG.js +1 -0
  44. package/dist/analysis-core/chunks/7QDOHWSY.js +27 -0
  45. package/dist/analysis-core/chunks/BZNHHLNP.js +1 -0
  46. package/dist/analysis-core/chunks/DTMHXKP6.js +7 -0
  47. package/dist/analysis-core/chunks/E7TFIHC5.js +1 -0
  48. package/dist/analysis-core/chunks/EH3QQ3T4.js +1 -0
  49. package/dist/analysis-core/chunks/EQTIRIMU.js +37 -0
  50. package/dist/analysis-core/chunks/FSLWD2PE.js +1 -0
  51. package/dist/analysis-core/chunks/G322LST6.js +1 -0
  52. package/dist/analysis-core/chunks/HTLIRVP7.js +1 -0
  53. package/dist/analysis-core/chunks/IBCFGUHI.js +1 -0
  54. package/dist/analysis-core/chunks/IL2KRP3T.js +1 -0
  55. package/dist/analysis-core/chunks/J4AXGE5W.js +1 -0
  56. package/dist/analysis-core/chunks/JF4GYMOZ.js +1 -0
  57. package/dist/analysis-core/chunks/KEKTZDIK.js +1 -0
  58. package/dist/analysis-core/chunks/KU5DINLW.js +1 -0
  59. package/dist/analysis-core/chunks/M7MMAUAK.js +1 -0
  60. package/dist/analysis-core/chunks/OFBJNHC6.js +1 -0
  61. package/dist/analysis-core/chunks/ORCYIIHB.js +60 -0
  62. package/dist/analysis-core/chunks/PVPEY7NF.js +1 -0
  63. package/dist/analysis-core/chunks/PYKAERZZ.js +1 -0
  64. package/dist/analysis-core/chunks/QDYMR6KS.js +1 -0
  65. package/dist/analysis-core/chunks/QPXNXMLC.js +1 -0
  66. package/dist/analysis-core/chunks/SL27GMEN.js +1 -0
  67. package/dist/analysis-core/chunks/STZOC7LN.js +1 -0
  68. package/dist/analysis-core/chunks/T5TREZCQ.js +1 -0
  69. package/dist/analysis-core/chunks/TDNTU4TF.js +1 -0
  70. package/dist/analysis-core/chunks/U5HOEVPE.js +1 -0
  71. package/dist/analysis-core/chunks/UEWL3GMQ.js +1 -0
  72. package/dist/analysis-core/chunks/VER355VN.js +1 -0
  73. package/dist/analysis-core/chunks/VFENG4MR.js +1 -0
  74. package/dist/analysis-core/chunks/VGYWI4X2.js +1 -0
  75. package/dist/analysis-core/chunks/Y5AUKKYG.js +1 -0
  76. package/dist/analysis-core/chunks/Y7JGSUOA.js +1 -0
  77. package/dist/analysis-core/chunks/YVDCJN7D.js +14 -0
  78. package/dist/analysis-core/chunks/ZAA44GPI.js +1 -0
  79. package/dist/analysis-core/chunks/ZMUBMYWN.js +1 -0
  80. package/dist/analysis-core/contracts/requests.js +1 -0
  81. package/dist/analysis-core/conventions/file-admission.js +1 -0
  82. package/dist/analysis-core/data/finding-types.js +1 -0
  83. package/dist/analysis-core/errors.js +1 -0
  84. package/dist/analysis-core/findings/presentation.js +1 -0
  85. package/dist/analysis-core/github/repo-key.js +1 -0
  86. package/dist/analysis-core/import/outside-loader-sources.js +1 -0
  87. package/dist/analysis-core/index.js +6 -0
  88. package/dist/analysis-core/llm/cache-policy.js +1 -0
  89. package/dist/analysis-core/llm/cost.js +1 -0
  90. package/dist/analysis-core/llm/execution.js +1 -0
  91. package/dist/analysis-core/llm/output-limit.js +1 -0
  92. package/dist/analysis-core/llm/slots.js +1 -0
  93. package/dist/analysis-core/llm/stable-json.js +1 -0
  94. package/dist/analysis-core/llm/structured-output-error.js +1 -0
  95. package/dist/analysis-core/map-limit.js +1 -0
  96. package/dist/analysis-core/requests/answer-formats.js +1 -0
  97. package/dist/analysis-core/requests/check-diagnostics.js +1 -0
  98. package/dist/analysis-core/requests/headline-request.js +1 -0
  99. package/dist/analysis-core/requests/instruction-text.js +1 -0
  100. package/dist/analysis-core/requests/local-plan.js +1 -0
  101. package/dist/analysis-core/requests/registry.js +1 -0
  102. package/dist/analysis-core/requests/schema-descriptions.js +1 -0
  103. package/dist/analysis-core/requests/shape-finding-input.js +1 -0
  104. package/dist/analysis-core/requests/template-version.js +1 -0
  105. package/dist/analysis-core/requests/tools.js +1 -0
  106. package/dist/analysis-core/settings.js +1 -0
  107. package/dist/bundle/seal/deserialise.js +75 -0
  108. package/dist/bundle/seal/encryption.js +25 -0
  109. package/dist/bundle/seal/metadata.js +69 -0
  110. package/dist/bundle/seal/open.js +38 -0
  111. package/dist/bundle/seal/planned-calls.js +20 -0
  112. package/dist/bundle/seal/signature.js +51 -0
  113. package/dist/cli/agent-folder.js +17 -0
  114. package/dist/cli/api-types.js +2 -0
  115. package/dist/cli/api.js +1 -0
  116. package/dist/{claude-code-permission.js → cli/claude-code-permission.js} +4 -3
  117. package/dist/cli/commands/analyze.js +73 -0
  118. package/dist/cli/commands/login.js +51 -0
  119. package/dist/cli/completion-recovery.js +18 -0
  120. package/dist/{context.js → cli/context.js} +8 -14
  121. package/dist/cli/email-sign-in.js +56 -0
  122. package/dist/{git.js → cli/git.js} +12 -8
  123. package/dist/cli/intake-payload.js +18 -0
  124. package/dist/{main.js → cli/main.js} +23 -12
  125. package/dist/{mcp.js → cli/mcp.js} +109 -40
  126. package/dist/cli/output.js +10 -0
  127. package/dist/cli/relay-check.js +239 -0
  128. package/dist/cli/relay-preparation.js +31 -0
  129. package/dist/cli/sign-in-input.js +97 -0
  130. package/dist/{sign-in.js → cli/sign-in.js} +2 -1
  131. package/dist/cli/suggested-email.js +10 -0
  132. package/dist/cli/summary.js +30 -0
  133. package/dist/contract/cli-api-messages.js +5 -0
  134. package/dist/contract/cli-refusals.js +22 -0
  135. package/dist/contract/cli-version.js +1 -0
  136. package/dist/contract/console-url.js +8 -0
  137. package/dist/contract/console.js +111 -0
  138. package/dist/contract/email-sign-in-messages.js +18 -0
  139. package/dist/contract/messages.js +252 -0
  140. package/dist/contract/release-key.js +2 -0
  141. package/dist/contract/runtime-environment.js +37 -0
  142. package/dist/core/analysis/finding-quality/config.js +4 -0
  143. package/dist/core/analysis/run-to-end.js +55 -0
  144. package/dist/core/analysis/structural-run.js +16 -0
  145. package/dist/gatekeeper/attestation.js +67 -0
  146. package/dist/gatekeeper/certificate-algorithms.js +18 -0
  147. package/dist/gatekeeper/certificate-path.js +99 -0
  148. package/dist/gatekeeper/cli-api.js +174 -0
  149. package/dist/gatekeeper/client.js +76 -0
  150. package/dist/gatekeeper/connection-exchange.js +60 -0
  151. package/dist/gatekeeper/connection.js +140 -0
  152. package/dist/gatekeeper/console.js +168 -0
  153. package/dist/gatekeeper/loopback.js +5 -0
  154. package/dist/gatekeeper/model.js +70 -0
  155. package/dist/gatekeeper/production-attestation.js +149 -0
  156. package/dist/gatekeeper/trust/hardware.js +21 -0
  157. package/dist/gatekeeper/trust/policy.js +42 -0
  158. package/dist/gatekeeper/trust/production.json +25 -0
  159. package/dist/setup-pings/client.js +31 -0
  160. package/dist/setup-pings/contract.js +2 -0
  161. package/dist/setup-pings/policy.js +3 -0
  162. package/dist/setup-pings/state.js +261 -0
  163. package/dist/setup-pings/worker.js +95 -0
  164. package/dist/transport/base64url.js +9 -0
  165. package/dist/transport/http-response.js +89 -0
  166. package/dist/transport/tls-exporter.js +5 -0
  167. package/package.json +57 -11
  168. package/LICENSE +0 -1
  169. package/dist/api-types.js +0 -2
  170. package/dist/api.js +0 -97
  171. package/dist/commands/check.js +0 -104
  172. package/dist/commands/login.js +0 -9
  173. package/dist/files.js +0 -99
  174. package/dist/gitignore.js +0 -70
  175. package/dist/output.js +0 -23
  176. package/dist/secret-files.js +0 -5
  177. /package/dist/{browser.js → cli/browser.js} +0 -0
  178. /package/dist/{commands → cli/commands}/balance.js +0 -0
  179. /package/dist/{commands → cli/commands}/finding.js +0 -0
  180. /package/dist/{commands → cli/commands}/logout.js +0 -0
  181. /package/dist/{credentials.js → cli/credentials.js} +0 -0
@@ -0,0 +1,14 @@
1
+ import{d as J}from"./3MTXB4MK.js";import{j as U}from"./TDNTU4TF.js";import{a as M}from"./HTLIRVP7.js";import{a as K}from"./QDYMR6KS.js";import{b as v}from"./E7TFIHC5.js";import{a as A}from"./Y7JGSUOA.js";import{c as T}from"./IL2KRP3T.js";import{b as P}from"./6YCABS5T.js";import{f as C,g as N,h as S,i as $,j as D}from"./PVPEY7NF.js";import{a as w,b as E}from"./VFENG4MR.js";import{a as L}from"./74FPPPIG.js";import{c as F}from"./FSLWD2PE.js";import{z as b}from"zod";function I(t,e){if(Buffer.byteLength(t)<=e)return t;let r=0,i=Math.min(t.length,e);for(;r<i;){let a=Math.ceil((r+i)/2);Buffer.byteLength(t.slice(0,a))<=e?r=a:i=a-1}return i>0&&/[\uD800-\uDBFF]/.test(t[i-1])&&i--,t.slice(0,i)}function G(t){let{bundleText:e}=t,r=s=>Buffer.byteLength(JSON.stringify(s));function i(s){let n=[];for(let o of s){if(r([...n,""])>4e3)break;let m=0,l=Buffer.byteLength(o);for(;m<l;){let d=Math.ceil((m+l)/2);r([...n,I(o,d)])<=4e3?m=d:l=d-1}n.push(I(o,m))}return n}function a(s,n=!1){return s.map(o=>typeof o!="string"&&o.kind==="no-core"&&n?e("analysis-check-input-1"):M([o])[0])}function p(s){let n=s.citedFiles===void 0?"":',"citedFiles":'+JSON.stringify(s.citedFiles),o=a(s.diagnostics,!0),m=s.citedFiles===void 0?o:i(o),l=[{text:'{"coreFiles":'+JSON.stringify(s.coreFiles)},{text:n+',"findings":'+JSON.stringify(s.findings)+',"diagnostics":'+JSON.stringify(m)+"}"}];return E(l,w({},{template:"check-findings"}).breakpoints)}function c(s){return Buffer.byteLength(p(s).map(n=>n.text).join(""))}return{checkDiagnosticsText:a,checkPromptBlocks:p,checkPayloadBytes:c}}function R(t,e={}){return t.length?t.map(r=>{let i=e.includeFiles===!1?"":`; files ${r.files.join(", ")||"none"}`;return`${r.ref} "${r.title}" (${r.subKind}): frozen ${r.frozen.join(", ")||"none"}; declined ${r.declined.join(", ")||"none"}${i}`}).join(`
2
+ `):"none"}function O(t){let{bundleText:e}=t,r=e("analysis-scope-check-1"),i=e("analysis-split-check-scope-rule-1"),a=[e("analysis-derive-structures-1"),e("analysis-derive-structures-2"),e("analysis-derive-structures-3"),e("analysis-derive-structures-4"),e("analysis-derive-structures-5"),e("analysis-derive-structures-6"),e("analysis-derive-structures-7"),e("analysis-derive-structures-8")].join(`
3
+ `),p=e("analysis-derive-structures-10");function c(n){return n.map(o=>({unit:JSON.stringify(o.unitKey),kind:o.kind,name:JSON.stringify(o.name),location:JSON.stringify(`${o.sourcePath}:${o.sourceLine}${o.sourceEndLine?`\u2013${o.sourceEndLine}`:""}`)}))}function s(n){return e("code-finding-note",{codeSources:c(n)})}return{RULE:r,SPLIT_SCOPE_RULE:i,SUB_KIND_DEFS:a,STRUCTURE_SCOPE_RULE:p,codeSourceLabels:c,codeFindingNote:s}}import{posix as Q}from"node:path";function H(t){let{bundleText:e}=t,r=.25,i=4;function a(c){let s=new Set(c.map(l=>l.name)),n=new Map(c.map(l=>[l.name,new Set(l.skills.filter(d=>d!==l.name&&s.has(d)))])),o=new Map;for(let l of n.values())for(let d of l)o.set(d,(o.get(d)??0)+1);let m=Math.max(i,(c.length-1)*r);return c.map(l=>({name:l.name,linkedFrom:o.get(l.name)??0,linksTo:n.get(l.name).size})).filter(l=>l.linkedFrom>=m||l.linksTo>=m)}function p(c){let s=a(c);if(!s.length)return null;let n=s.map(o=>e("shape-shared-skill",o));return e("analysis-split-check-shared-skills-1",{v0:n.join(`
4
+ `)})}return{sharedSkillsOf:a,sharedSkillsText:p}}function W(t){let{bundleText:e}=t,{shapeFindingsText:r}=J(t),{sharedSkillsText:i}=H(t);function a(c){let s=new Map(c.map((n,o)=>[n.name,`s${o+1}`]));return e("shape-skills",{skills:c.map(n=>({...n,id:s.get(n.name),refs:n.references.map(o=>Q.relative(Q.dirname(n.path),o)).join(","),tools:n.tools.join(","),links:n.skills.map(o=>s.get(o)).join(","),hasRefs:n.references.length>0,hasTools:n.tools.length>0,hasLinks:n.skills.length>0,hasDetails:n.references.length>0||n.tools.length>0||n.skills.length>0}))})}function p(c){return e("shape-inventory",{agent:c.agent,v0:a(c.skills),shared:i(c.skills),tools:c.tools.map(s=>({...s,skills:s.skills.join(", ")})),subAgents:c.subAgents.map(s=>({...s,tools:s.tools.join(", "),skills:a(s.skills)})),prompts:c.prompts,knowledge:c.knowledge.map(s=>({...s,headings:s.sections.map(n=>`${n.startLine}-${n.endLine} ${n.heading}`).join(`
5
+ `)})),findings:r(c.findings)})}return{inventoryText:p}}function X(t){let{SPLIT_SCOPE_RULE:e}=O(t),{inventoryText:r}=W(t);function i(a){return{scopeRule:e,open:R(a.open),inventory:r(a)}}return{shapeInputs:i,SPLIT_SCOPE_RULE:e}}function j(t){let{bundleText:e}=t,r={contradiction:{def:e("analysis-categories-1"),evidence:e("analysis-categories-2")},ambiguity:{def:e("analysis-categories-3"),evidence:e("analysis-categories-4")},bypassable_requirement:{def:e("analysis-categories-5"),evidence:e("analysis-categories-6")},stale_fact:{def:e("analysis-categories-7"),evidence:e("analysis-categories-8")},description_mismatch:{def:e("analysis-categories-9"),evidence:e("analysis-categories-10")},ungoverned_tool:{def:e("analysis-categories-11"),evidence:e("analysis-categories-12")},untrusted_instructions:{def:e("analysis-categories-13"),evidence:e("analysis-categories-14")},better_as_code:{def:e("analysis-categories-15"),evidence:e("analysis-categories-16")}},i={untrusted_instructions:{derive:"analysis-categories-17",check:"analysis-categories-18"},better_as_code:{derive:"analysis-categories-19",check:"analysis-categories-20"}};function a(s){return F(s).map(n=>{let o=r[n];return e("category-entry",{category:n,definition:o.def,evidence:o.evidence})}).join(`
6
+ `)}function p(s,n){return F(s).map(o=>{let m=i[o]?.[n];return m?`
7
+
8
+ ${e(m,{promptAgreement:T(s)})}`:""}).join("")}function c(){return[e("analysis-categories-21"),e("analysis-categories-22"),e("analysis-categories-23"),e("analysis-categories-24"),e("analysis-categories-25"),e("analysis-categories-26")].join(`
9
+ `)}return{categoryBlock:a,categoryRules:p,impactBlock:c}}function Y(t){let{checkPromptBlocks:e}=G(t),{shapeInputs:r}=X(t),{templates:i}=t,{categoryBlock:a,categoryRules:p}=j(t);function c(s,n,o,m={}){if(s==="derive-shape")return{...n,...r(n.inventoryData)};if(s.startsWith("check-findings")||s==="second-opinion"){let l=e(n.checkInput),d=a(o),u=p(o,"check"),x=T(o),h={...n,promptAgreement:x,categories:d,categoryRules:u,core:l[0].text,claims:l[1].text};if(s!=="second-opinion")return h;let g;try{if(typeof n.checkTemplate!="string")throw new Error;g=$("check",o,n.checkTemplate)}catch{throw new Error("Unknown check template")}let y=typeof g=="string"&&Object.hasOwn(m,g)?m[g]:void 0;if(y?.route!=="finding_check"||y.system===void 0)throw new Error("Unknown check template");return{...h,checkSystem:v(y.system,{promptAgreement:x,categories:d,categoryRules:u},i)}}return n}return{stageInputs:c}}var V="<<<BEGIN REPOSITORY TEXT>>>",Z="<<<END REPOSITORY TEXT>>>";function B(t){let e=t;for(let r="";r!==e;)r=e,e=e.replaceAll(V,"").replaceAll(Z,"");return`${V}
10
+ ${e.replaceAll("{{","{ {")}
11
+ ${Z}`}function q(t,e){return{location:B(String(t.location)),text:B(String(t.text)),usage:B(t.usage===null?e.bundleText("code-check-no-usage"):String(t.usage))}}function ee(t){let{categoryBlock:e,categoryRules:r,impactBlock:i}=j(t),{codeSourceLabels:a,codeFindingNote:p,RULE:c,SPLIT_SCOPE_RULE:s,STRUCTURE_SCOPE_RULE:n,SUB_KIND_DEFS:o}=O(t),{bundleText:m}=t;function l(d,u,x){if(d==="finding-headlines")return{data:JSON.stringify(u.evidence),choiceCategories:L.join(", ")};if(d==="judge-code-prompt")return q(u,t);if(d.startsWith("derive-findings"))return{...u,promptAgreement:T(x),pass:u.pass??null,codeSources:a(u.codeSources??[]),categories:e(x),categoryRules:r(x,"derive"),impacts:i()};if(d==="derive-structure"){let h=u.loadModesData,g=u.openStructuresData,y=u.findingsData;return{...u,findings:(y??[]).map(f=>({...f,category:f.category??"\u2014",excerpt:f.excerpt??"",site:f.site?{...f.site,line:f.site.line??"?"}:null,otherSites:(f.otherSites??[]).map(k=>({...k,line:k.line??"?",excerpt:k.excerpt??""})),question:f.question??"",options:f.fixes.map(k=>k.title)})),subKinds:o,scopeRule:n,open:R(g,{includeFiles:!1}),loadModes:h.map(f=>{let k=f.evidenceKind?m("load-evidence-skill-frontmatter"):f.evidence;return m("analysis-derive-structures-11",{v0:f.path,v1:f.mode,v2:f.unit??"no unit",v3:f.via,v4:k?` (${k})`:""})}).join(`
12
+ `)}}if(d==="scope-items"){let h=u.scopeRuleId==="structure"?n:u.scopeRuleId==="split"?s:"";return{items:u.items??[],scopeRule:h}}if(d==="scope-findings"){let h=u.codeSources,g=u.codeFiles,y=p(h);return{...u,system:y?m("scope-system-code")+`
13
+
14
+ `+y:c,code:g.length?m("code-evidence",{files:JSON.stringify(g)}):""}}return u}return{enrichRequestInputs:l,headlineFallbackQuestion:()=>t.description("finding-headlines-fallback-question")}}function te(t,e){if(!Object.hasOwn(e.templates,t.template))throw new Error(`Unknown template: ${t.template}`);if(!Object.hasOwn(e.answerFormats,t.answerFormat))throw new Error(`Unknown answer format: ${t.answerFormat}`);let r=e.templates[t.template],i=t.limits??{};if(i.maxTokens!==void 0&&(!Number.isSafeInteger(i.maxTokens)||i.maxTokens<=0))throw new Error("Invalid maxTokens");let a=v(r.prompt,t.inputs,e.includes),p=r.promptBlocks?.map(c=>({text:v(c.text,t.inputs,e.includes),...c.cache?{cache:!0}:{}}));if(p&&p.map(c=>c.text).join("")!==a)throw new Error("Registered blocks must match the prompt");return{route:r.route??t.template,model:t.model,...r.system===void 0?{}:{system:v(r.system,t.inputs,e.includes)},prompt:a,...p?{promptBlocks:p}:{},schema:e.answerFormats[t.answerFormat],...i.maxTokens===void 0?{}:{maxTokens:i.maxTokens},...i.effort===void 0?{}:{effort:i.effort},...i.thinking===void 0?{}:{thinking:i.thinking}}}var _=class extends Error{name="InputBudgetError"};function Ze(t){let{templates:e,descriptions:r}=t,{withDescriptions:i}=A(t),a=U(i,t.description);function p(){let o={prompt:e["check-evidence"],promptBlocks:[{text:"{{core}}"},{text:"{{claims}}"}]},m=P({"benchmark-judge":{system:e["benchmark-judge"],prompt:"{{data}}"},"judge-code-prompt":{prompt:e["judge-code-prompt"]},"derive-findings":{prompt:e["derive-findings"]},"derive-findings-legacy":{prompt:e["derive-findings-legacy"]},"derive-findings-no-outcome":{prompt:e["derive-findings-no-outcome"]},"derive-findings-legacy-no-outcome":{prompt:e["derive-findings-legacy-no-outcome"]},"derive-structure":{prompt:e["derive-structure"]},"structure-recheck":{system:e["structure-recheck-system"],prompt:e["structure-recheck"]},"derive-shape":{prompt:e["derive-shape"]},"scope-items":{prompt:e["scope-items"],system:e["scope-system"]},"scope-findings":{prompt:e["scope-findings"],system:"{{system}}"},"check-findings":{...o,system:e["check-findings"]},"check-findings-precision-v1":{...o,system:e["check-findings-precision-v1"]},"second-opinion":{...o,system:e["opinion-system"]},"explain-sources":{prompt:e["source-evidence"],system:e["explain-sources"]},"finding-headlines":{system:e["finding-headlines"],prompt:"{{data}}"}});return Object.fromEntries(Object.entries(m).map(([l,d])=>[l,{...d,...d.promptBlocks?{promptBlocks:E(d.promptBlocks,w({},{template:l}).breakpoints)}:{}}]))}function c(){return{templates:p(),includes:e,answerFormats:a,descriptions:r,policy:S()}}function s(o,m={}){return oe(o,c(),m)}function n(o,m={}){let l=ne(N(o,m),c());return{...l,schema:l.schema}}return{instructionRegistry:c,analysisModelRequest:s,analysisRequest:n,buildAnalysisCall:o=>ne(o,c()),withDescriptions:i,callInputBytes:se}}function se(t){return Buffer.byteLength(t.prompt)+Buffer.byteLength(t.system??"")}function oe(t,e,r){let i=e.policy??S(),a=Object.hasOwn(S(),t.template)?D(t.template,t.answerFormat,r):t.answerFormat;if(!Object.hasOwn(i,t.template)||!i[t.template].answerFormats.includes(a))throw new Error("Unsupported template answer format");if(!Object.hasOwn(S(),t.template))return{...t,answerFormat:a,inputs:t.inputs};let p=K({templates:e.includes??{},descriptions:e.descriptions??{}}),{stageInputs:c}=Y(p),{enrichRequestInputs:s}=ee(p);return{...t,answerFormat:a,inputs:s(t.template,c(t.template,t.inputs,r,e.templates),r)}}function ne(t,e){let r=C.parse({template:t.template,inputs:t.inputs,answerFormat:t.answerFormat,model:t.model,...t.limits?{limits:t.limits}:{}}),{data:i,settings:a,maxInputBytes:p}=r.inputs,c=te(oe({...r,inputs:i},e,a),e);if(p!==void 0&&se(c)>p)throw new _("serialized evidence exceeds the priced input budget");let s=r.template==="judge-code-prompt"?b.object({path:b.string(),line:b.number()}).parse(i.at):r.template==="structure-recheck"?b.object({childId:b.string()}).parse(i):{};return{...c,...Object.hasOwn(S(),r.template)&&r.template!=="benchmark-judge"?{context:s}:{}}}export{te as a,I as b,G as c,O as d,H as e,W as f,X as g,j as h,Y as i,ee as j,_ as k,Ze as l,se as m,ne as n};
@@ -0,0 +1 @@
1
+ import{a as e}from"./3227KXHF.js";var t=e.mechanical,i=4096;function a(n){return{template:"finding-headlines",answerFormat:"findingHeadlines",model:t,limits:{maxTokens:i},inputs:{evidence:n}}}export{t as a,i as b,a as c};
@@ -0,0 +1 @@
1
+ import{a as p}from"./M7MMAUAK.js";import{b as l}from"./57M4OQJM.js";import{createHash as d}from"node:crypto";function u({repo:o,body:r}){let[t,...i]=r.evidence,n=r.split,s=e=>e.map(a=>({path:a.path??null,startLine:a.startLine,endLine:a.endLine}));return{kind:"structure",impact:r.kind,cause:r.cause,category:null,question:null,fixSummaries:[],site:t?{repo:o,path:t.path,line:t.line}:null,excerpt:t?.excerpt??null,otherSites:i.map(e=>({repo:o,path:e.path,line:e.line,excerpt:e.excerpt})),structure:{title:r.title,subKind:r.subKind,files:r.files.map(e=>({path:e.path,action:e.action,role:e.role,unit:e.unit,loadMode:e.loadMode,loadVia:e.loadVia,purpose:e.purpose})),segments:r.segments.map(e=>({path:e.path,startLine:e.startLine,endLine:e.endLine,to:e.to,disposition:e.disposition,into:e.into?{path:e.into.path,line:e.into.line}:null,reason:e.reason})),reorder:r.reorder?{path:r.reorder.path,startLine:r.reorder.startLine,endLine:r.reorder.endLine,steps:r.reorder.steps.map(e=>({from:e.from,reason:e.reason}))}:null,toolMoves:r.toolMoves.map(e=>({tool:e.tool,fromUnit:e.fromUnit,toUnit:e.toUnit,reason:e.reason})),split:n?{frontDoor:{job:n.frontDoor.job,skills:[...n.frontDoor.skills]},subAgents:n.subAgents.map(e=>({job:e.job,description:e.description,path:e.path,handoff:e.handoff??null,skills:e.skills.map(a=>({from:a.from,to:a.to})),tools:[...e.tools],movedKnowledge:s(e.movedKnowledge),neededKnowledge:s(e.neededKnowledge)}))}:null}}}function x(o,r=[]){return{evidence:[...o.map((t,i)=>({key:`f${i}`,kind:"finding",impact:t.kind,structure:null,cause:t.cause,category:t.category??null,question:t.question,site:t.site?{repo:t.siteRepo,path:t.site.path,line:t.site.line}:null,excerpt:t.excerpt,otherSites:t.otherSites.map(n=>({repo:n.repo,path:n.path,line:n.line,excerpt:n.excerpt})),fixSummaries:t.fixes.flatMap(n=>typeof n.summary=="string"&&n.summary.trim()?[n.summary]:[])})),...r.map((t,i)=>({key:`s${i}`,...u(t)}))],positions:[...o.map((t,i)=>({key:`f${i}`,target:"finding",index:i,fingerprint:p("finding",t)})),...r.map((t,i)=>({key:`s${i}`,target:"structure",index:i,fingerprint:p("structure",t)}))]}}function L(o,r){return d("sha256").update(l({batch:o,requestIdentity:r})).digest("hex")}export{x as a,L as b};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as ANALYSIS_SETTING_NAMES,g as analysisExecutionRequest,c as executionInputs,f as executionRequest,b as filterAnalysisSettings,d as modelName,k as recoverRequestFailure,e as requestLimits,h as requestPolicy,i as selectAnalysisTemplate,j as selectAnswerFormat};
@@ -0,0 +1 @@
1
+ import{$ as o,N as a,O as b,P as c,Q as d,R as e,S as f,T as g,U as h,V as i,W as j,X as k,Y as l,Z as m,_ as n,aa as p,ba as q,ca as r,da as s,ea as t,fa as u,ga as v,ha as w,ia as x,ja as y,ka as z,la as A,ma as B}from"../chunks/EQTIRIMU.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";import"../chunks/T5TREZCQ.js";import"../chunks/724WZMYW.js";export{s as CODE_EXT_RE,j as EXTRACTION_CANDIDATE_RE,k as EXTRACTION_EXT_RE,a as FileReadRefusal,u as GIT_DIR_RE,l as LOCK_FILE_RE,t as NON_SOURCE_FOLDER_RE,d as REFERENCE_FILE_EXTENSIONS,m as SECRET_FILE_RE,w as SOURCE_CUT_MARKER,r as SOURCE_EXCLUDE_RE,q as SOURCE_NON_LOCK_EXCLUDE_RE,v as admitFile,A as admittedFileAccess,B as assertSnapshotAdmission,p as fileRefusalWarning,f as isFetchableReferencePath,g as isFetchableSourcePath,e as isHtmlReferencePath,i as isReadableLocalPath,n as isReadableRepoPath,h as isUnreadCommandPath,c as localSymlinkGuardEnabled,y as readAdmittedSource,x as readRepoFile,z as resolveLocalExclusions,b as respectGitignore,o as secretFileWarning};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"../chunks/JF4GYMOZ.js";export{b as fixConfidenceSchema,c as fixDeltaChangeSchema,d as fixDeltaEdgeKindSchema,e as fixDeltaSchema,f as fixFactsSchema,a as fixStatusSchema};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunks/BZNHHLNP.js";export{a as JobError,b as throwIfOrgSpendReached};
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunks/IBCFGUHI.js";export{b as findingPresentation,a as findingWording};
@@ -0,0 +1 @@
1
+ import{f as a,g as b,h as c,i as d,j as e}from"../chunks/T5TREZCQ.js";export{e as folderOfRepoKey,b as localRepoKeyFor,a as repoKeyFor,c as repoKeyOfRepoPath,d as savedRepoKeyOf};
@@ -0,0 +1 @@
1
+ import{a as c}from"../chunks/Y5AUKKYG.js";import"../chunks/7QDOHWSY.js";import"../chunks/326F4XNG.js";import"../chunks/IL2KRP3T.js";import"../chunks/2PSNOSJ2.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import{q as b}from"../chunks/EQTIRIMU.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";import{e as a}from"../chunks/T5TREZCQ.js";import"../chunks/724WZMYW.js";export{b as READ_LIMITS,c as readOutsideLoaderSources,a as repoPathFrom};
@@ -0,0 +1,6 @@
1
+ import{$ as Wt,A as Tt,B as _t,C as ge,D as Lt,E as ke,F as Nt,G as Ae,H as Me,I as Fr,J as Rr,K as vr,L as Cr,M as we,N as V,O as jt,P as Kt,Q as Se,R as Ht,S as Pe,T as zt,U as Be,V as Dt,W as Ut,X as qt,Y as $t,Z as Vt,_ as Gt,a as kt,aa as Or,b as Y,ba as Xt,c as wt,ca as Jt,d as he,da as Yt,e as $,ea as Qt,f as St,g as Q,ga as Ir,h as Pt,i as Z,ia as Ar,j as ee,ja as Mr,k as bt,l as yt,la as Br,m as xt,n as Et,na as Tr,o as Ft,p as Rt,q as vt,r as Ct,s as Ot,t as ue,u as te,v as It,w as At,x as Mt,y as re,z as Bt}from"./chunks/ORCYIIHB.js";import{a as J}from"./chunks/QPXNXMLC.js";import"./chunks/VER355VN.js";import{a as yr,d as gt,k as xr,l as Er}from"./chunks/YVDCJN7D.js";import"./chunks/3MTXB4MK.js";import{i as ut}from"./chunks/TDNTU4TF.js";import"./chunks/HTLIRVP7.js";import{a as U}from"./chunks/QDYMR6KS.js";import{b as br}from"./chunks/E7TFIHC5.js";import"./chunks/Y7JGSUOA.js";import"./chunks/4F6ZIHXU.js";import"./chunks/VGYWI4X2.js";import"./chunks/J4AXGE5W.js";import"./chunks/PYKAERZZ.js";import{a as ht}from"./chunks/Y5AUKKYG.js";import{H as mt,I as Pr,h as D,i as me,j as dt,k as lt,y as ft}from"./chunks/7QDOHWSY.js";import{a as L}from"./chunks/326F4XNG.js";import{a as Ie,b as pt,d as Sr}from"./chunks/IL2KRP3T.js";import{b as B,c as ie}from"./chunks/2PSNOSJ2.js";import{b as Ue,c as qe,k as ct,o as Oe,q as wr}from"./chunks/G322LST6.js";import"./chunks/6YCABS5T.js";import"./chunks/SL27GMEN.js";import"./chunks/PVPEY7NF.js";import"./chunks/STZOC7LN.js";import{c as A}from"./chunks/VFENG4MR.js";import"./chunks/UEWL3GMQ.js";import{a as He,c as ne}from"./chunks/OFBJNHC6.js";import"./chunks/DTMHXKP6.js";import"./chunks/U5HOEVPE.js";import"./chunks/ZMUBMYWN.js";import"./chunks/ZAA44GPI.js";import{a as M,b as De}from"./chunks/3227KXHF.js";import"./chunks/M7MMAUAK.js";import"./chunks/57M4OQJM.js";import"./chunks/IBCFGUHI.js";import"./chunks/KU5DINLW.js";import{Ab as it,I as _,J as Je,K as fe,Ka as rt,N as Ye,S as Qe,b as $e,d as le,e as pe,fb as ot,g as X,ga as R,ja as Ze,jb as st,la as q,ma as z,na as et,nb as nt,q as C,r as Ge,t as We,vb as at,w as Xe,x as Ce,za as tt}from"./chunks/EQTIRIMU.js";import"./chunks/74FPPPIG.js";import"./chunks/EH3QQ3T4.js";import{f as K,i as ce,j as ze,k as ve,l as de}from"./chunks/KEKTZDIK.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import{a as Re}from"./chunks/BZNHHLNP.js";import{a as Ve,c as v,e as H}from"./chunks/T5TREZCQ.js";import{b as ae}from"./chunks/724WZMYW.js";function G(r,e,o,s){let t=new Set(o.map(c=>v(c.path,s))),n=r.CF_READING_NOTE_AGENT_ONLY!=="0"&&bt(r),d=new Set(e.agents),h=c=>!t.has(c)&&(!n||d.has(c)),u=e.instruction.filter(h),k=e.code.filter(h),l=e.agents.filter(c=>!t.has(c)),f=new Set(Ft(l)),b=[...u,...k].every(c=>f.has(c)),P=u.length,i=k.length,p=[!b&&P>0&&`${P} instruction file${P===1?"":"s"} left out by the ${Math.round(C.sourceFetch.instructionBytes/1e3)}KB instruction budget`,!b&&i>0&&`${i} analyzable file${i===1?"":"s"} left out by the ${Math.round(C.sourceFetch.codeBytes/1e3)}KB/${C.sourceFetch.codeFiles}-file code budget \u2014 the analysis reads the most agent-shaped files first`,Rt(l,n)].filter(Boolean),a=o.filter(c=>c.readBytes!==void 0).map(c=>v(c.path,s));return a.length&&p.push(`${a.join(", ")}: only the first ${C.sourceFetch.codeFileBytes/1e3} KB was read`),p.length?p.map((c,m)=>m<p.length-1?String(c).replace(/\.$/,""):c).join("; "):void 0}function be(r,e,o){let s=e.filter(g=>{let x=R(r,g,{purpose:"source",route:"github",root:o});return x.admitted||x.reason==="wrong-type"||x.reason==="too-large"}),t=X(r)?D(r,s.map(g=>g.path),o):void 0,n=new Set(t?.pluginDeclarations?.map(g=>g.path)),d=t?{files:t.files.map(g=>({...g,path:v(g.path,o)})),ownerOf:g=>{let x=t.ownerOf(H(g,o));return x?{...x,folder:x.key===null?"":v(x.folder,o)}:null}}:void 0,h=new Set(t?.ignoredPaths),u=xt(r,{paths:s.map(g=>v(g.path,o)),scopes:d}),k=[],l=e.flatMap(g=>{if(h.has(g.path))return[];let x=v(g.path,o),w=x===null?{size:g.size}:vt(u,x,g.size),E=R(r,{...g,size:w.size},{purpose:"source",route:"github",root:o,scopes:d});return E.admitted?[{entry:{...g,...w},rel:x,score:Ot(r,x,d),size:w.size,...u.enabled?{tier:u.tierOf(x)}:{}}]:(k.push({path:g.path,reason:E.reason}),[])}),f=l.filter(({score:g})=>g===0).sort(ue),b=l.filter(({score:g})=>g>0).sort(ue),P=[],i={instruction:0,code:0},p={instruction:[],code:[]},a=0,c=(u.enabled?[...l].sort(ue):[...f,...b]).sort((g,x)=>Number(n.has(x.entry.path))-Number(n.has(g.entry.path)));for(let{entry:g,rel:x,score:w}of c){let E=!n.has(g.path)&&!Ct(u,x)&&($e(g.path)||Qe(r,x,d)||w===0)?"instruction":"code",F=E==="instruction"?C.sourceFetch.instructionBytes:C.sourceFetch.codeBytes;if(i[E]+g.size>F||E==="code"&&a>=C.sourceFetch.codeFiles){p[E].push(x),k.push({path:g.path,reason:i[E]+g.size>F?"total":"allowance"});continue}P.push(g),i[E]+=g.size,E==="code"&&(a+=1)}let m=Et(u,k.flatMap(g=>{let x=v(g.path,o);return x===null?[]:[{...g,path:x}]})),S={...p,agents:m},y=G(r,S,P,o);return{selected:P,totalBytes:i.instruction+i.code,refused:k,...y?{skippedNote:y}:{},...u.enabled&&y?{readingNotes:S}:{}}}var Zt=(r,e)=>{let{markerToRead:o}=he(e.settings,{paths:r.map(({path:s})=>s),root:e.dir??void 0,scanFlag:e.flags.scan,marker:null});return o?{strength:"partial",wants:[o]}:null};function er(r,e,o="bare"){let{scan:s}=he(e.settings,{paths:r.map(({path:t})=>t),root:e.dir??void 0,scanFlag:e.flags.scan,marker:o});return s?{strength:"partial",wants:[]}:null}var _r=2e3;function tr(r,e,o,s={}){let t=e.filter(w=>v(w.path,o)!=null),n={},d=[],h=new Map,u=s.mode!=="core"&&tt(r),k=D(r,t.map(w=>w.path),o,{mode:u?"all":"core"}),l=new Set([...k.ignoredPaths,...k.ignoredImportPaths]),f=new Map(k.files.filter(w=>w.role!=="reference").map(w=>[w.path,w])),b=new Map(k.scopes.map(w=>[w.key,C.conventionImport.totalBytes])),P=C.conventionImport.skillBytes,i=X(r)?C.codeAgent.importBytes:1/0,p=0,a=w=>v(w.path,k.ownerOf(w.path).folder)??w.path,c=(w,E)=>{h.set(w.path,{path:w.path,reason:E})},m=(w,E)=>{let F=R(r,w,{purpose:E,route:"github",root:o});return F.admitted?!0:(c(w,F.reason),!1)},S=w=>{if(n[w.path])return;let E=u&&f.get(w.path)?.role==="skill"?"skill":"core",F=k.ownerOf(w.path),I=E==="skill"?P:b.get(F.key),T=w.size??0;if(E==="skill"&&p>=C.conventionImport.skillFiles){c(w,"allowance");return}if(T>I||T>i){c(w,"total");return}n[w.path]=w.ref,d.push(w.path),i-=T,E==="skill"?(P-=T,p++):b.set(F.key,I-T)},y=t.filter(w=>f.has(w.path));for(let w of y)m(w,f.get(w.path)?.role==="skill"?"skill":"definition")&&S(w);let g=0;if(me(r))for(let w of dt(new Set(t.map(E=>E.path)))){let E=t.find(F=>F.path===w);if(g>=C.conventionImport.extractionFiles){c(E,"allowance");continue}if(m(E,"source")&&m(E,"definition")){let F=d.length;S(E),d.length>F&&g++}}let x=k.needsExtraction;if(x){let w=t.flatMap(F=>{if(l.has(F.path)||n[F.path]||u&&Xe(a(F)))return[];if(!m(F,"extraction"))return[];let I=et(a(F));return I===null?[]:[{entry:F,rank:I}]}).sort((F,I)=>F.rank-I.rank||(F.entry.size??0)-(I.entry.size??0)),E=g;for(let{entry:F}of w){if(E>=C.conventionImport.extractionFiles){c(F,"allowance");continue}let I=d.length;S(F),d.length>I&&E++}}if(u&&s.files){let w=Te(r,{entries:e,selected:t.filter(E=>Object.hasOwn(n,E.path)),files:s.files,root:o});for(let E of w.paths)Object.hasOwn(n,E)||(d.push(E),n[E]=t.find(F=>F.path===E).ref);for(let E of w.refused)h.set(E.path,E)}return{...X(r)&&y.some(w=>!Object.hasOwn(n,w.path))?{definitionsOmitted:!0}:{},selectedPaths:d,shaByPath:n,treeListing:t.slice(0,_r).map(w=>w.path),needsExtraction:x,refused:[...h.values()]}}function Te(r,e){let o=new Set(e.selected.map(n=>n.path)),s=D(r,e.entries.map(n=>n.path),e.root).files.filter(n=>n.role==="skill"&&o.has(n.path)).map(n=>n.path),t=lt(r,{skillPaths:s,paths:e.entries.map(n=>n.path),files:e.files,sizes:new Map(e.entries.map(n=>[n.path,n.size])),selected:e.selected,root:e.root,admission:e.admission,referencePaths:e.referencePaths});return{paths:[...new Set(t?.flatMap(n=>n.files.map(d=>d.path))??[])],refused:t?.flatMap(n=>n.refused)??[]}}var rr=(r,e)=>{let o=tr(e.settings,r,e.dir??void 0,{mode:e.mode});return{strength:"partial",wants:o.selectedPaths,state:{needsExtraction:o.needsExtraction,treeListing:o.treeListing,shaByPath:o.shaByPath,refused:o.refused,...o.definitionsOmitted?{definitionsOmitted:!0}:{}}}};var or=["marker","code-scan","conventions"];var Lr={marker:Zt,"code-scan":er,conventions:rr};function ye(r,e,o,s,t=Lr){let n={...o,settings:r},d={readers:[]};for(let h of or)if(!(s&&!s.includes(h)))try{let u=t[h]?.(e,n);u&&d.readers.push({id:h,claim:u,done:!1})}catch{}return d}function Nr(r){return{readers:r.readers.map(({id:e,done:o})=>({id:e,done:o}))}}function _e(r){let e=r.readers.find(({id:o})=>o==="conventions").claim;return{selectedPaths:e.wants,...e.state}}function Le(r,e){let o={dir:e.root??null,mode:e.profile==="hosted-import"?e.mode??"all":"all",flags:e.profile==="hosted-import"?e.flags??te(r):te(r)};if(e.profile==="hosted-import"){let n=ye(r,e.listing,o);return{profile:e.profile,...n,selection:_e(n)}}let s=e.listing.filter(n=>R(r,n,{purpose:"pointer",route:"github",root:e.root}).admitted),t=ye(r,s,o,["marker","code-scan"]);return{profile:e.profile,...t,listing:s,selection:e.selection??be(r,e.listing,e.root),context:o}}var W=20;function oe(r,e,o,s){e.requestedPaths.push(...o);let t=ke(r,e.selected,o,s);e.selected=t.selected,e.refused.push(...t.refused)}function xe(r,e,o){let s=r.hosted;if(!s)return;let t=new Set(e),n=r.selected.filter(d=>t.has(d.path));o==="code"?s.codePaths&&(s.codePaths=[...new Set([...s.codePaths,...n.map(d=>d.path)])]):s.weakCodeFallback&&(r.conventionPaths=[...new Set([...r.conventionPaths,...n.map(d=>d.path)])],s.fallback={...s.fallback,selectedPaths:[...new Set([...s.fallback.selectedPaths,...n.map(d=>d.path)])],shaByPath:{...s.fallback.shaByPath,...Object.fromEntries(n.map(d=>[d.path,d.ref]))}})}function Ee(r,e){let o=new Set(r.conventionPaths);if(r.decision.kind==="settled"&&r.decision.scanPaths&&r.markerKind&&r.markerKind!=="bare")for(let t of r.selected)o.add(t.path);let s=new Map(e.map(t=>[t.path,t]));for(let t of r.selected)o.has(t.path)&&!s.has(t.path)&&s.set(t.path,t);r.selected=[...s.values()],r.cursor=0,r.hosted&&(r.hosted.codeMode=!0,r.hosted.needsExtraction=!1)}function sr(r,e=St(r.ranked,r.scan)){return e.agents.length>0}function nr(r,e){if(r.hosted&&(r.hosted.codePaths=e.map(s=>s.path)),!r.hosted?.weakCodeFallback||r.hosted.codeMode||sr(r)){Ee(r,e);return}let o=new Map(r.selected.map(s=>[s.path,s]));for(let s of e)o.has(s.path)||o.set(s.path,s);r.selected=[...o.values()],r.cursor=0}function ar(r,e){let o=r.hosted;if(!o?.weakCodeFallback||!o.codePaths||r.markerKind&&r.markerKind!=="bare")return;let s=new Map([...r.entries,...r.selected].map(n=>[n.path,n]));sr(r,e)?Ee(r,o.codePaths.map(n=>s.get(n))):(r.selected=o.fallback.selectedPaths.map(n=>s.get(n)),r.cursor=0,o.codeMode=!1,o.needsExtraction=o.fallback.needsExtraction);let t=new Set(r.selected.map(n=>n.path));r.files=Object.fromEntries(Object.entries(r.files).filter(([n])=>t.has(n)))}function Ne(r,e){if(!_(r))return;let o=new Set(e.entries.map(n=>n.path)),s=Object.fromEntries(Object.entries(e.files).filter(([n])=>e.selected.some(d=>d.path===n&&d.readBytes===void 0))),t=new Set(fe(r,[...o],s));for(let[n,d]of Object.entries(e.files)){let h=R(r,{path:n,text:d},{...e.admission,purpose:"override",route:"github",root:e.root,listing:o,managedFiles:e.files});(!h.admitted||t.has(n))&&(delete e.files[n],e.refused.push({path:n,reason:h.admitted?"unreadable":h.reason}))}}function N(r,e,o){Ne(r,e);let s=e.selected.filter(h=>e.files[h.path]!==void 0),t=new Set(s.filter(h=>h.readBytes===void 0).map(h=>h.path)),n=new Set(e.requestedPaths),d=B(e.selectionRefused.filter(h=>!n.has(h.path)),e.refused).filter(h=>!t.has(h.path));return{state:e,requestedReads:o,files:e.files,settled:s,refused:d,treeTruncated:e.treeTruncated}}async function ir(r,e,o){e.manifestReadPaths??=e.selected.slice(0,e.cursor).filter(a=>a.readBytes===void 0).map(a=>a.path);let s=new Set(e.selected.filter(a=>a.readBytes===void 0).map(a=>a.path)),t=Object.fromEntries(Object.entries(e.files).filter(([a])=>s.has(a))),n=new Map(e.entries.map(a=>[a.path,a.size])),d=new Map(Object.entries(e.files).map(([a,c])=>[a,Buffer.byteLength(c)]));for(let[a,c]of Object.entries(t))n.set(a,Buffer.byteLength(c));let h=Y(r,e.ranked,n,!1,d,e.codeImportV2,{files:t,root:e.root}),u=new Set(e.manifestReadPaths),k=h.paths.filter(a=>t[a]===void 0&&!u.has(a)),l=new Map(e.selected.filter(a=>a.readBytes!==void 0).map(a=>[a.path,a]));e.requestedPaths.push(...k.filter(a=>l.has(a))),oe(r,e,k.filter(a=>!l.has(a)),e.entries);let f=new Set(k),b=new Map(e.entries.map(a=>[a.path,a])),P=e.selected.filter(a=>f.has(a.path)).map(a=>l.has(a.path)?b.get(a.path):a).slice(0,W);if(P.length){let a=await L(P,4,async g=>{let x=R(r,g,{...e.admission,purpose:"pointer",route:"github",root:e.root});return x.admitted?o(g):(e.refused.push({path:g.path,reason:x.reason}),null)});e.manifestReadPaths=[...e.manifestReadPaths,...P.map(g=>g.path)];let c=new Map(n);P.forEach((g,x)=>{a[x]!==null&&c.set(g.path,Buffer.byteLength(a[x]))});let m=new Map(P.filter((g,x)=>l.has(g.path)&&a[x]!==null).map(g=>[g.path,d.get(g.path)])),S=Y(r,e.ranked,c,!1,d,e.codeImportV2,{files:t,root:e.root,replacementBytes:m}),y=new Set(S.paths);P.forEach((g,x)=>{a[x]!==null&&(y.has(g.path)?(e.files[g.path]=a[x],e.selected=e.selected.map(w=>w.path===g.path?g:w)):e.refused.push(S.refused.find(w=>w.path===g.path)??{path:g.path,reason:"total"}))});return}let i=new Map((h.manifests??[]).map(a=>{let m=a.files.filter(S=>t[S.path]===void 0).map(S=>e.refused.find(y=>y.path===S.path)??{path:S.path,reason:"missing"});return[a.agentId,{...a,files:a.files.filter(S=>t[S.path]!==void 0),refused:[...a.refused,...m]}]})),p=a=>{let c=i.get(rt(a.prompt));return c?{...a,manifest:c}:a};e.ranked={...e.ranked,strong:e.ranked.strong.map(p),possible:e.ranked.possible.map(p)},xe(e,[...i.values()].flatMap(a=>a.files.map(c=>c.path)),"code"),e.refused.push(...[...i.values()].flatMap(kt)),e.phase="done"}async function cr(r,e,o){if(!_(r))return!1;let s=Je(r,e.entries.map(f=>f.path));if(!s.length)return!1;let t=new Set(s.flatMap(f=>f.agents)),n=new Map(e.selected.map(f=>[f.path,f])),d=new Set(e.selected.filter(f=>f.readBytes===void 0&&e.files[f.path]!==void 0).map(f=>f.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 h=new Set([...e.managedReadPaths,...d]),u=e.entries.filter(f=>t.has(f.path)&&n.has(f.path)&&!h.has(f.path)),k=u.slice(0,W);if(!k.length)return!1;let l=await L(k,4,async f=>{let b=R(r,f,{...e.admission,purpose:"pointer",route:"github",root:e.root});return b.admitted?o(f):(e.refused.push({path:f.path,reason:b.reason}),null)});if(k.forEach((f,b)=>{l[b]!==null&&(e.files[f.path]=l[b],e.selected=e.selected.map(P=>P.path===f.path?f:P))}),e.managedReadPaths.push(...k.map(f=>f.path)),u.length>k.length){for(let f of Object.keys(e.files))!t.has(f)&&s.some(b=>v(f,b.folder)!==null)&&delete e.files[f];e.cursor=0,(e.phase==="done"||e.phase==="manifest")&&(e.phase="files")}return!0}function dr(r,e){let{plan:o,entries:s}=e,t=o.profile==="local-analysis"?o.context.dir??"":e.root??"",n=o.readers.find(l=>l.id==="marker")?.claim.wants[0],d=o.readers.some(l=>l.id==="code-scan"),h=new Map(s.map(l=>[l.path,l])),u=o.profile==="local-analysis"?o.selection.selected:o.selection.selectedPaths.flatMap(l=>h.has(l)?[h.get(l)]:[]),k=wt(r)?$(r,{phase:"start",root:t,paths:s.map(l=>l.path),scanFlag:!!n||d}):void 0;return{version:1,profile:o.profile,root:t,entries:s,selected:[...u],conventionPaths:o.profile==="hosted-import"?D(r,s.map(l=>l.path),t).files.filter(l=>l.role!=="reference").map(l=>l.path):[],...e.admission?{admission:e.admission}:{},selectionRefused:o.selection.refused,requestedPaths:[],refused:[],files:{},cursor:0,treeTruncated:e.treeTruncated??!1,codeImportV2:o.profile==="local-analysis"&&le(r),...o.profile==="hosted-import"?{hosted:{fallback:structuredClone(o.selection),weakCodeFallback:r.CF_IMPORT_WEAK_CODE_FALLBACK!=="0",codeMode:!1,needsExtraction:o.selection.needsExtraction}}:{},decision:k??(n?{kind:"marker",markerPath:n,scanIfBare:d}:{kind:"settled",markerPath:null,markerKind:null,scan:d}),phase:n?"marker":d?"scan":"files"}}function jr(r,e){e.ranked??=ge(r,e.scan,!1,new Map,e.codeImportV2);let o=Y(r,e.ranked,_t(e.scan.plan),!1,new Map,e.codeImportV2),s=[...o.refused,...e.ranked.skippedFiles??[]];if(e.requestedPaths.push(...s.map(t=>t.path)),e.refused.push(...s),e.profile==="hosted-import"&&o.paths.length){let t=ke(r,[],o.paths,e.scan.plan);e.refused.push(...t.refused),nr(e,t.selected)}else oe(r,e,o.paths,e.scan.plan);e.phase=e.selected.length?"files":"done"}async function lr(r,e,o){if(e.version!==1)throw new Error("unsupported-import-checkpoint");let s=e.profile==="hosted-import"?{...r,CF_IMPORT_CALLS:"0"}:r,t={...e,selected:[...e.selected],files:{...e.files},requestedPaths:[...e.requestedPaths],refused:[...e.refused],...e.hosted?{hosted:{...e.hosted}}:{},...e.managedReadPaths?{managedReadPaths:[...e.managedReadPaths]}:{}},n=new Set(t.entries.map(i=>i.path)),d=Object.fromEntries(Object.entries(t.files).filter(([i])=>t.selected.some(p=>p.path===i&&p.readBytes===void 0))),h=new Set(fe(s,[...n],d)),u=[],k=new Set,l=async i=>{if(h.has(i.path)||t.managedReadPaths?.includes(i.path)&&t.files[i.path]===void 0)return t.refused.push({path:i.path,reason:"unreadable"}),null;u.push(i);try{let p=await o.read(i);if(p!==null){if(k.has(i.path)){let a=R(s,{path:i.path,size:Buffer.byteLength(p),text:p},{...t.admission,purpose:"skill",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(_(s)||ae(s)){let a=R(s,{path:i.path,text:p},{...t.admission,purpose:"override",route:"github",root:t.root,listing:n,managedFiles:t.files});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}if(t.phase==="manifest"){let a=R(s,{path:i.path,size:Buffer.byteLength(p)},{...t.admission,purpose:"pointer",route:"github",root:t.root});if(!a.admitted)return t.refused.push({path:i.path,reason:a.reason}),null}return p}}catch(p){if(p instanceof Ye&&(p.reason==="secret-content"||_(s)||k.has(i.path)))return t.refused.push({path:i.path,reason:p.reason}),null;if(t.profile==="hosted-import"&&!k.has(i.path))throw p}return t.refused.push({path:i.path,reason:"unreadable"}),null};if(await cr(s,t,l))return N(s,t,u);if(Ne(s,t),t.phase==="done")return o.resolvedCode&&ar(t,o.resolvedCode),N(s,t,u);if(t.phase==="manifest")return await ir(s,t,l),N(s,t,u);if(t.phase==="marker"&&t.decision.kind==="marker"){let i=t.decision,p=i.markerPath,a=t.entries.find(m=>m.path===p);if(t.profile==="hosted-import"){let m=R(s,a,{purpose:"pointer",route:"github",root:t.root});if(!m.admitted)return t.refused.push({path:p,reason:m.reason}),t.decision={kind:"settled",markerPath:null,markerKind:null,scan:i.scanIfBare},t.phase=i.scanIfBare?"scan":"files",N(s,t,u)}oe(s,t,[p],t.entries);let c=await l(a);if(c!==null&&(t.files[p]=c),t.decision=$(s,{phase:"read",pending:i,text:c}),t.markerPath=p,t.markerKind=t.decision.markerKind,t.markerKind!=="bare"){let m=t.profile==="hosted-import"?await o.listing():{entries:t.entries,truncated:!1};t.treeTruncated||=m.truncated;let S=await Nt(s,{config:ft(c).config,markerDir:p.split("/").slice(0,-1).join("/"),selected:t.profile==="hosted-import"?[]:t.selected,admission:{...t.admission,root:t.root||void 0},modelReader:!1,codeImportV2:t.codeImportV2,priorRefused:t.refused,refusalMode:"append",requestedMode:"kept-and-refused",listing:async()=>m.entries});t.requestedPaths.push(...S.requestedPaths),t.refused=S.refused,t.profile==="hosted-import"?Ee(t,S.selected??[]):S.selected&&(t.selected=S.selected)}if(t.phase=t.decision.scan?"scan":"files",t.profile!=="hosted-import"||t.markerKind!=="bare"||t.decision.scan)return N(s,t,u)}if(t.phase==="scan"){if(!t.scan){let i=Mt(s,t.entries,t.root,!0,t.decision.kind==="settled"?t.decision.scanPaths:void 0);t.scan=i.state,t.refused.push(...i.refused)}if(!re(t.scan)){let i=await Lt(s,t.scan,l,{modelReader:!1,alreadyRead:new Map,codeImportV2:t.codeImportV2,size:{batch:It,parallel:4}});t.scan=i.scan,i.selection&&(t.ranked=i.selection.ranked)}return re(t.scan)&&jr(s,t),N(s,t,u)}Ce(s)&&(k=new Set(t.skillReferencePaths));let f=t.selected.slice(t.cursor,t.cursor+W),b=f.filter(i=>t.files[i.path]===void 0),P=await L(b,4,l);if(b.forEach((i,p)=>{P[p]!==null&&(t.files[i.path]=P[p])}),t.cursor+=f.length,Ce(s)){let i=Object.fromEntries(Object.entries(t.files).filter(([y])=>t.selected.some(g=>g.path===y&&g.readBytes===void 0))),p=Te(s,{entries:t.entries,selected:t.selected,files:i,root:t.root,admission:t.admission,referencePaths:t.skillReferencePaths});t.refused=B(t.refused,p.refused);for(let y of p.refused)k.has(y.path)&&delete t.files[y.path];if(t.cursor<t.selected.length)return N(s,t,u);let a=new Map(t.selected.map(y=>[y.path,y])),c=p.paths.filter(y=>!a.has(y)||a.get(y).readBytes!==void 0),m=new Set(c.filter(y=>a.has(y)));t.cursor-=t.selected.slice(0,t.cursor).filter(y=>m.has(y.path)).length,t.selected=t.selected.filter(y=>!m.has(y.path));for(let y of m)delete t.files[y];t.requestedPaths.push(...c),c.length&&(t.skillReferencePaths=[...t.skillReferencePaths??[],...c]);let S=new Map(t.entries.map(y=>[y.path,y]));t.selected.push(...c.map(y=>{let g=S.get(y);return{path:y,size:g.size,ref:g.ref}})),xe(t,c,"fallback")}return t.cursor>=t.selected.length&&(t.phase=me(s)&&t.ranked?"manifest":"done"),N(s,t,u)}async function pr(r,e){let o=dr(r,e),s;do s=await lr(r,o,{listing:async()=>({entries:e.entries,truncated:!1}),read:e.read}),o=s.state;while(o.phase!=="done");let t={};return o.markerPath!==void 0&&(t.markerPath=o.markerPath,t.markerKind=o.markerKind),o.ranked!==void 0&&(t.ranked=o.ranked,t.scan=o.scan),{files:s.files,settled:s.settled,skippedFiles:s.refused,...t}}async function je(r,e){let o=Le(r,{profile:"local-analysis",listing:e.entries,selection:e.selection}),{files:s,settled:t,skippedFiles:n,...d}=await pr(r,{entries:e.entries,read:e.read,admission:e.admission,plan:o}),h=s,u=t,k=n,l=Q({key:e.repoKey,files:h,...d},o.context.flags,void 0,{markerPolicy:"any-read"}),{selection:f}=o,b;if(pt(r)&&e.repository){let a=await ht(r,{selected:{files:h,listedPaths:e.entries.map(m=>m.path),fallbackName:Pt(e),skills:!0},selection:f,codeAgentsFound:(l?.resolved?.agents.length??0)>0,port:e.repository}),c=new Set(Object.keys(h).map(m=>H(m,a.root)));if(h=a.files,f=a.selection,b=a.root,b!==void 0){k=k.map(S=>({...S,path:H(S.path,b)})),u=u.map(S=>({...S,path:H(S.path,b)}));let m=new Set(u.map(S=>S.path));u.push(...f.selected.filter(S=>!m.has(S.path)&&Object.hasOwn(h,S.path)))}k=B(k,a.skippedFiles).filter(m=>c.has(m.path)||!Object.hasOwn(h,m.path))}let P={repoKey:e.repoKey,files:h,listedPaths:e.entries.map(a=>H(a.path,b)),...b!==void 0?{root:b}:{},forLocal:!0,code:l},i=ee(r,Z(r,P)),p=f.readingNotes?G(r,f.readingNotes,u):f.skippedNote;return{...i,files:h,...b!==void 0?{root:b}:{},skippedFiles:k,warnings:[...new Set([...i.warnings,...p?[p]:[],...ie(k)])],selection:f}}var Kr=new Set;function Hr(r,e={}){let o=Ve(e.dir),s=e.limits??C.archive,t=e.listing??Kr,n={commit:null,files:new Map,skipped:[]},d=new Set,h=0,u=0;function k(i){let p=i.replace(/\/$/,"").split("/");return!i.startsWith("/")&&!i.includes("\\")&&!/^[a-z]:/i.test(i)&&!p.some(a=>a===".."||a==="."||!a)}function l(i,p,a,c=t){if(!a||!k(i)||!Number.isSafeInteger(p)||p<0)return"refused";let m=R(r,{path:i,size:p},{purpose:"archive",route:"github",root:o});return m.admitted?e.exampleFolders?.some(S=>i.startsWith(S))||We(i,{root:o,listing:c})?"example":null:m.reason==="excluded"&&Ge(r,i,o)?"example":m.reason==="excluded"||m.reason==="wrong-type"?"excluded":"refused"}function f(i,p){d.has(i)||(d.add(i),n.skipped.push({path:i,reason:p}))}function b(i,p=t){let a=i.split("/");for(let c=1;c<=a.length;c++){let m=a.slice(0,c).join("/");if(m===o||o.startsWith(`${m}/`))continue;if(v(m,o)===null)return!1;let S=l(`${m}/`,0,!0,p);if(S)return f(`${m}/`,S),!1}return!0}function P(i,p,a=!0){if(v(i,o)===null)return!1;if(!k(i))return f(i,"refused"),!1;let c=i.split("/");if(c.length>1&&!b(c.slice(0,-1).join("/")))return!1;let m=l(i,p,a);return m?(f(i,m),!1):u>=s.files||p>s.bytes-h?(f(i,"over-limit"),!1):(h+=p,u++,!0)}return{result:n,accept:P,enterFolder:b}}var zr=new Set(Ae);function Dr(r,e){for(let s of[...Object.keys(e.set),...e.clear])if(!zr.has(s))throw new Error(`Unknown analysis field: ${s}`);let o={...r,...e.set};for(let s of e.clear)o[s]=void 0;return o}async function Ur(r,e,o,s){o=q(r,o);let t=structuredClone(e);for(t.files??={},t.cursor=0;;){let n=await Se(r,t,o,s);if(n){t=n;continue}let d=t.selected??[];if((t.cursor??0)>=d.length)return t;let h=d.slice(t.cursor).filter(l=>!Object.hasOwn(t.files,l.path)),u=[],k=await L(h,4,async l=>{try{return{path:l.path,text:await we(l,f=>o.read(f),u,t.refused)}}catch(f){return{error:f}}});for(let l of k){if("error"in l)throw l.error;l.text!==null&&(t.files[l.path]=l.text)}u.length&&(t.refused=B(t.refused,u)),t.cursor=d.length}}async function fr(r,e,o,s){let{codeFindingNote:t}=gt(s),n={deriveBytes:0,codeEvidence:[]};if(!e.findingQuality?.config.switches.codeInputs||!e.projectAgents?.enabled)return n;let d=e.projectAgents,h=(e.repos??[]).filter(c=>[...d.byRepo[c.key]??[],...d.codeByRepo?.[c.key]??[]].some(m=>m.codeInputsJson&&(m.codeInputsJson.tools.length||m.codeInputsJson.contextInputs.length))),k=(await L(h,1,async c=>{try{let m=o.find(S=>S.repoKey===c.key);if(!m)throw new Error("Source reader is missing.");return{repo:await Ur(r,c,m,e.modelReader??!1)}}catch(m){return{error:m}}})).map(c=>{if("error"in c)throw c.error;return c.repo}),l=k.map(c=>{let m=Pe(r,c,V(r,e),e.modelReader,d);return Object.assign(c.files,m.virtualFiles),m.fragment}),f=Object.fromEntries(k.map(c=>[c.key,c.files??{}])),P=zt({...e,repos:k,mapped:l}).findingQuality?.codeEvidence?.filter(c=>Object.keys(c.input.files).length)??[];if(!P.length)return n;let i=P.map(c=>({repo:c.repo,unitKey:c.unitKey,enabled:!0,inputs:[c.input],files:f[c.repo]}));return{deriveBytes:[...new Map(P.flatMap(c=>Object.entries(c.input.files).map(([m,S])=>[JSON.stringify([c.repo,m]),{path:m,text:S}]))).values()].reduce((c,{path:m,text:S})=>c+Buffer.byteLength(`### ${m}
2
+ \`\`\`
3
+ ${it(S)}
4
+ \`\`\`
5
+
6
+ `),0)+Buffer.byteLength(t(P.flatMap(c=>c.input.sources))),codeEvidence:i}}function ur(r,e,o,s,t){let n=e.analysisFlags,d=[],h=new Set,u=0,k=0;for(let m of e.repos??[]){k+=(m.selected??[]).reduce((y,g)=>y+(g.readBytes??g.size),0),d.push(...(m.selected??[]).map(y=>({path:v(y.path,m.root)??y.path,size:y.size})));let S=st(e.projectAgents,m.key,{nodes:[],edges:[],warnings:[]},t);for(let[y,g]of Object.entries(S.files)){let x=yt(g).length;u+=x,d.push({path:y,size:x}),h.add(y)}}u+=k;let l=$t(d,n.multiPass,h),f=l>1?24:at,b=(h.size?u:Math.min(u,15e4))+s.deriveBytes,P=Oe("derive",r,o),i=Array.from({length:l},(m,S)=>A(r,{template:P},l>1?`Derive findings (part ${S+1} of ${l})`:"Derive findings",M.generate,K(b+Vt(u,l))+4e3,De)),p=n.multiPass&&h.size?k:Math.min(k,15e4);i.push(A(r,{template:"derive-structure"},"Structural pass",M.generate,K(p)+4e3,12e3));let a=Math.ceil(f/Ue)*(1+qe);i.push(A(r,{template:"scope-findings"},"Scope check",o.switches.enabled?o.models.scope:M.mechanical,a*(4e3+K(s.scopeBytes)),a*1e3));let c=ct(r,f,n.findingCheck??!0,Oe("check",r,o),o.switches.fullContext?"whole-file":"legacy");return c&&i.push(c),(n.sourceNotes??!0)&&i.push(A(r,{template:"explain-sources"},"Explain sources",Dt,K(qt)*f,Ut*f)),e.codeAgents?.model&&e.repos?.some(m=>m.scanNeeded)&&i.push(A(r,{template:"judge-code-prompt"},"Check possible agents in code",M.mechanical,6*3e3,1200)),i.push(...Gt(Ie(r),r)),i}var Gr=async(r,e)=>{if(e.progress.assertHeld(),e.progress.signal?.throwIfAborted(),!e.model)throw new Re("llm","Analysis needs a live model; no provider key is configured.");if(!e.readers.length)throw new Re("not_found","This project has no analyzable repository.");let o=r.execution.preparation;if(!o)throw new Error("Preparation options are required for estimation.");let{state:s,settings:t}=r;await z(t,s,e.readers),await e.context.refreshStructureParts?.().catch(()=>{});let n=U(await e.instructions()),d=J(n),h=n.bundleText("model-reader-runtime-prompt"),u=[...s.warnings??[]],k=V(t,s),l=s.modelReader??mt(t),f=s.codeImportV2??le(t),b=s.analysisFlags?ne(t,s):He(t),P=s.findingQuality??{config:o.qualityConfig},i=await ot(t,s.projectAgents,e.context.loadProjectAgents,void 0,P.config.switches.codeInputs),p=[],a=[],c=e.readers.map(O=>q(t,O));for(let O of c){e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let se=await O.head(),Ke=await O.list(),j=be(t,Ke,O.root);!j.readingNotes&&j.skippedNote&&u.push(`${O.repoKey}: ${j.skippedNote}`),a.push({key:O.repoKey,kind:"github",root:O.root,selected:j.selected}),p.push({key:O.repoKey,...O.source??{kind:O.repoKey.startsWith("local:")?"fs":"github"},headSha:se.sha,branch:se.branch,selected:j.selected,...j.readingNotes?{sourceReadNotes:j.readingNotes}:{},cursor:0,files:{},...O.root?{root:O.root}:{},...jt(t,Ke,j.selected,O.root,k,l,f)})}let m={...s,repos:p,projectAgents:i,codeAgents:k,modelReader:l,codeImportV2:f,analysisFlags:b,findingQuality:P};await z(t,m,c);let S=await fr(t,m,c,n),{sources:y,files:g}=Be({qualityConfig:P.config,codeEvidence:S.codeEvidence}),x=d.enrichRequestInputs("scope-findings",{codeSources:y,codeFiles:g},t),w=Buffer.byteLength(String(x.code))+Math.max(0,Buffer.byteLength(String(x.system))-Buffer.byteLength(d.RULE)),E=[...o.uploadReadingAllowance?[o.uploadReadingAllowance]:[],...ur(t,{...m,repos:a},P.config,{deriveBytes:S.deriveBytes,scopeBytes:w},h)],F=await e.context.loadOpenStructures?.()??[],I=(await e.context.loadPendingRechecks?.().catch(()=>[])??[]).reduce((O,se)=>O+se.children.length,0);I&&E.push(A(t,{template:"structure-recheck"},"Post-merge re-check",M.mechanical,I*3e3,I*300));let T=await e.context.chatFindingCount?.().catch(()=>(e.progress.log({level:"warn",code:"chat.count_failed"}),0))??0;T&&E.push(A(t,{},"Re-check chat findings",M.mechanical,T*3e3,T*300));let Fe=ce(E,o.capUsd);return de(Fe),{next:o.confirmPrice?"awaiting_confirm":"fetching_files",clear:[],estimate:Fe,set:{repos:p,warnings:u,openStructures:F,codeAgents:k,modelReader:l,codeImportV2:f,analysisFlags:b,projectAgents:i,findingQuality:P,...b.splitCheck?{splitEstimateBase:Fe}:{}}}};var Wr=async({state:r,settings:e},o)=>{o.progress.assertHeld(),o.progress.signal?.throwIfAborted();let s=[...r.repos??[]];await z(e,r,o.readers);let t=r.repoCursor??0;if(t>=s.length)return{next:"mapping",set:{repoCursor:0},clear:[]};let n=structuredClone(s[t]),d=o.readers.find(a=>a.repoKey===n.key);if(!d)throw new Error(`no reader for ${n.key}`);let h=q(e,d),u=pe(r).remapping,k=await Se(e,n,h,r.modelReader??!1,u);if(k)return s[t]=k,{next:"fetching_files",set:{repos:s},clear:[]};let l=n.selected??[],f=n.cursor??0,b=l.slice(f,f+20),P={...n.files??{}},i=[];for(let a of b){if(o.progress.assertHeld(),o.progress.signal?.throwIfAborted(),P[a.path]!==void 0)continue;let c=await we(a,m=>h.read(m),i,n.refused);c!==null&&(P[a.path]=c)}i.length&&(n.refused=B(n.refused,i)),n.files=P,n.cursor=f+b.length,s[t]=n;let p=n.cursor>=l.length&&!Kt(n);return{next:"fetching_files",set:{repos:s,repoCursor:p?t+1:t},clear:[]}};async function Xr(r,e){let o=e.admission?.exclusions?.length?e.entries.filter(n=>R(r,n,{purpose:"override",route:"github",...e.admission}).admitted):e.entries,s=_(r)?new Set(o.map(n=>n.path)):void 0,t=!e.admission?.exclusions?.length&&!ae(r)?e.read:n=>Ze(r,n,e.read,{...e.admission,...s?{listing:s}:{}});return je(r,{...e,entries:o,read:t})}async function Jr(r,e,o){let s=Object.entries(e).map(([n,d])=>({path:n,size:Buffer.byteLength(d),ref:n})),t=At(r,s,o.root,!1,o.scanPaths);for(;!re(t);)t=await Bt(t,async n=>e[n.path]??null);return{scan:ge(r,t),summary:Tt(t)}}async function gr(r,e,o){let{repoKey:s,root:t,codingGuides:n,forLocal:d}=o,h=o.flags??te(r),u=Object.keys(e),k=$(r,{phase:"start",paths:u,root:t,scanFlag:h.scan}),l=k.kind==="marker"?$(r,{phase:"read",pending:k,text:e[k.markerPath]??null}):k,f=l.kind==="off"?null:l.markerPath,b=l.kind==="off"?null:l.markerKind;if(l.kind==="off"||!l.scan){let m=Q({key:s,files:e,markerPath:f,markerKind:b},h,void 0,{markerPolicy:"any-read"});return{...ee(r,Z(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:d,code:m})),scanned:!1,resolved:null}}let{scan:P,summary:i}=await Jr(r,e,{repoKey:s,root:t,scanPaths:l.scanPaths}),p=Q({key:s,files:e,ranked:P,scan:i,markerPath:f,markerKind:b},h,void 0,{markerPolicy:"any-read"});return{...ee(r,Z(r,{repoKey:s,files:e,root:t,codingGuides:n,forLocal:d,code:p})),scanned:!0,resolved:p.resolved}}async function kr(r,e){let{state:o,settings:s}=r;if(!ne(s,o).splitCheck||!o.splitEstimateBase)return{next:"inspecting",set:{repoCursor:0},clear:[]};let n=r.execution.preparation?.capUsd??o.splitEstimateBase.capUsd,d={...o.splitEstimateBase,capUsd:n};de(d);let h=Wt(s,o),u={next:"inspecting",set:{repoCursor:0,splitCheckPriced:!0,splitFindingsPriced:!0},clear:["splitEstimateBase"]};if(!h.length)return u;let k=J(U(await e.instructions())),l=h.reduce((p,{inventory:a})=>p+K(Buffer.byteLength(Jt({tools:k},{...a,findings:[]}).prompt))+K(k.SHAPE_FINDINGS_INPUT_BYTES),0),f=d.lines.find(p=>p.label==="Scope check"),b=A(s,{template:"scope-findings"},"Scope check",M.mechanical,(f?.inputTokens??0)+h.length*Qt,(f?.outputTokens??0)+h.length*Yt),P=d.lines.map(p=>p.label==="Scope check"?b:p);f||P.push(b),P.push(A(s,{template:"derive-shape"},"Split check",Xt,l,h.length*ut));let i=ce(P,n);return ze(i)?(u.estimate=d,u.clear.push("splitCheckPriced","splitFindingsPriced"),delete u.set.splitCheckPriced,delete u.set.splitFindingsPriced,u.set.warnings=[...o.warnings??[],`The split check was skipped because its estimate (${ve(i.totalUsd)}) exceeds the ${ve(i.capUsd)} cap. The rest of the analysis continues.`]):u.estimate=i,u}var Yr=async(r,e)=>{e.progress.assertHeld(),e.progress.signal?.throwIfAborted();let{state:o,settings:s}=r,t=o.repos??[];await z(s,o,e.readers);let n=o.repoCursor??0;if(n>=t.length)return kr(r,e);let d=t[n],h=r.execution.forLocal,u=h?o.mapped?.[n]?{fragment:Me(o,n),warnings:[]}:await gr(s,d.files??{},{repoKey:d.key,root:d.root,forLocal:!0}):void 0,k=pe(o).remapping,l=u?(()=>{let p=nt(u.fragment,d.key);return{...p,warnings:[...u.warnings,...p.warnings]}})():Pe(s,d,V(s,o),o.modelReader??!1,o.projectAgents,k,U(await e.instructions()).bundleText("model-reader-runtime-prompt")),f=!h&&d.sourceReadNotes?G(s,d.sourceReadNotes,d.selected??[],d.root):void 0,b=h?[]:ie((d.refused??[]).filter(p=>p.reason==="secret-content")),P="virtualFiles"in l?l.virtualFiles:void 0,i=[...o.mapped??[]];return i[n]=l.fragment,{next:"mapping",clear:[],set:{...P?{repos:t.map((p,a)=>a===n?{...p,files:{...p.files,...P}}:p)}:{},mapped:i,warnings:[...o.warnings??[],...f?[`${d.key}: ${f}`]:[],...b,...l.warnings,...Ht(d)],repoCursor:n+1}}};function Qr(r,e){let o=e?.findingHeadlineDiagnostics??(r.findingHeadlines?.version===2?r.findingHeadlines.diagnostics:r.findingHeadlineDiagnostics);return{set:{...o?{findingHeadlineDiagnostics:o}:{},repos:(r.repos??[]).map(s=>({...s,files:{},selected:[],scan:void 0,ranked:void 0})),...r.projectAgents?{projectAgents:{enabled:r.projectAgents.enabled,byRepo:{}}}:{}},clear:["passResults","sourceNotes","findingHeadlines","findingsRaw","structuresRaw","loadModes","rechecks","recheckedChangeIds","readPaths","inspectPlan","passFindings","codeChecks","newVerdicts",...r.shapeFindings?["shapeFindings"]:[]]}}export{Ae as ANALYSIS_FIELDS,xr as InputBudgetError,M as MODELS,R as admitFile,Cr as analysisFieldsOf,Or as analysisRuntime,Dr as applyAnalysisDelta,Mr as buildAnalysisResult,yr as buildRequest,U as createInstructionText,Er as createRequestRegistry,J as createRequestTools,je as discoverLocalSources,ye as discoverReaders,Gr as estimateStage,Xr as fetchLocalSources,Wr as fetchStage,vr as fetchedPathsOf,Ie as findingHeadlinesEnabled,Qr as finishAnalysis,Br as headlinesStage,Ir as inspectStage,Yr as mapStage,Nr as planForJob,Le as planImport,wr as readFindingQualityConfig,br as render,Hr as repoCollector,Pr as resolveAgents,Me as savedFragmentAt,Rr as savedFragmentsOf,Be as scopeCodeContext,_e as selectionOfPlan,Sr as snapshotSettings,Ar as sourceNotesStage,Tr as structureStage,Fr as trySavedFragmentAt};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"../chunks/VFENG4MR.js";import"../chunks/KEKTZDIK.js";import"../chunks/BZNHHLNP.js";export{b as applyCacheBreakpoints,d as captureAllowanceMultiplier,e as promptCacheEnabled,c as promptCacheEstimateLine,a as promptCachePolicy};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"../chunks/KEKTZDIK.js";import"../chunks/BZNHHLNP.js";export{a as ANTHROPIC_CACHE_READ_RATE,b as CACHE_WRITE_MULTIPLIERS,d as FALLBACK_MODEL,c as PRICE_PER_MTOK,l as assertEstimateWithinCap,e as cacheWriteMultiplier,f as estimateTokensFromBytes,g as estimateUsd,k as formatUsd,h as line,j as overCap,i as sumEstimate};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/4F6ZIHXU.js";export{a as executeStructuredRequest};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"../chunks/SL27GMEN.js";import"../chunks/3227KXHF.js";export{a as NONSTREAM_MAX_TOKENS,c as anthropicStructuredLimit,b as supportsReasoningControls};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/VGYWI4X2.js";export{a as retryCalls};
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunks/57M4OQJM.js";export{a as stableClone,b as stableStringify};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/J4AXGE5W.js";export{a as StructuredOutputError};
@@ -0,0 +1 @@
1
+ import{a}from"./chunks/326F4XNG.js";export{a as mapLimit};
@@ -0,0 +1 @@
1
+ import{j as a}from"../chunks/TDNTU4TF.js";import"../chunks/STZOC7LN.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/EH3QQ3T4.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";export{a as answerFormats};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/HTLIRVP7.js";export{a as checkDiagnosticsText};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"../chunks/ZAA44GPI.js";import"../chunks/3227KXHF.js";export{a as FINDING_HEADLINES_MODEL,b as FINDING_HEADLINES_OUTPUT_TOKENS,c as headlineRequest};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";export{a as createInstructionText};
@@ -0,0 +1 @@
1
+ import{fa as o,ha as p,ka as e,ma as m}from"../chunks/ORCYIIHB.js";import"../chunks/QPXNXMLC.js";import"../chunks/VER355VN.js";import"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/4F6ZIHXU.js";import"../chunks/VGYWI4X2.js";import"../chunks/J4AXGE5W.js";import"../chunks/PYKAERZZ.js";import"../chunks/7QDOHWSY.js";import"../chunks/326F4XNG.js";import"../chunks/IL2KRP3T.js";import"../chunks/2PSNOSJ2.js";import"../chunks/G322LST6.js";import"../chunks/6YCABS5T.js";import"../chunks/SL27GMEN.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/OFBJNHC6.js";import"../chunks/DTMHXKP6.js";import"../chunks/U5HOEVPE.js";import"../chunks/ZMUBMYWN.js";import"../chunks/ZAA44GPI.js";import"../chunks/3227KXHF.js";import"../chunks/M7MMAUAK.js";import"../chunks/57M4OQJM.js";import"../chunks/IBCFGUHI.js";import"../chunks/KU5DINLW.js";import"../chunks/EQTIRIMU.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";import"../chunks/T5TREZCQ.js";import"../chunks/724WZMYW.js";function i(l,r,a={}){let n=o(l,r,a.structureState);return[...n.calls,...p(l,n.findings),...m(l,r,a),...e(l)]}export{i as localCallPlan};
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d}from"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/IL2KRP3T.js";import"../chunks/6YCABS5T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as InputBudgetError,d as buildAnalysisCall,c as callInputBytes,b as createRequestRegistry};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/Y7JGSUOA.js";export{a as createSchemaDescriptions};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"../chunks/3MTXB4MK.js";export{a as SHAPE_FINDINGS_INPUT_BYTES,c as assertShapeFindingBytes,d as createShapeFindingInput,b as shapeFindingData};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/VER355VN.js";import"../chunks/E7TFIHC5.js";import"../chunks/IL2KRP3T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as createTemplateVersion};
@@ -0,0 +1 @@
1
+ import{a}from"../chunks/QPXNXMLC.js";import"../chunks/VER355VN.js";import"../chunks/YVDCJN7D.js";import"../chunks/3MTXB4MK.js";import"../chunks/TDNTU4TF.js";import"../chunks/HTLIRVP7.js";import"../chunks/QDYMR6KS.js";import"../chunks/E7TFIHC5.js";import"../chunks/Y7JGSUOA.js";import"../chunks/IL2KRP3T.js";import"../chunks/6YCABS5T.js";import"../chunks/PVPEY7NF.js";import"../chunks/STZOC7LN.js";import"../chunks/VFENG4MR.js";import"../chunks/UEWL3GMQ.js";import"../chunks/U5HOEVPE.js";import"../chunks/74FPPPIG.js";import"../chunks/EH3QQ3T4.js";import"../chunks/KEKTZDIK.js";import"../chunks/FSLWD2PE.js";import"../chunks/JF4GYMOZ.js";import"../chunks/BZNHHLNP.js";export{a as createRequestTools};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunks/IL2KRP3T.js";import"./chunks/PVPEY7NF.js";import"./chunks/STZOC7LN.js";import"./chunks/VFENG4MR.js";import"./chunks/UEWL3GMQ.js";import"./chunks/EH3QQ3T4.js";import"./chunks/KEKTZDIK.js";import"./chunks/FSLWD2PE.js";import"./chunks/JF4GYMOZ.js";import"./chunks/BZNHHLNP.js";export{a as findingHeadlinesEnabled,b as outsideLoadersEnabled,c as promptAgreementEnabled,d as snapshotSettings};
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
3
+ import { answerFormats } from "../../analysis-core/requests/answer-formats.js";
4
+ import { createInstructionText } from "../../analysis-core/requests/instruction-text.js";
5
+ import { createSchemaDescriptions } from "../../analysis-core/requests/schema-descriptions.js";
6
+ const registryPayload = z.object({
7
+ templates: z.record(z.string(), z.object({
8
+ prompt: z.string(), system: z.string().optional(), route: z.string().optional(),
9
+ promptBlocks: z.array(z.object({ text: z.string(), cache: z.literal(true).optional() }).strict()).optional(),
10
+ }).strict()),
11
+ includes: z.record(z.string(), z.string()),
12
+ answerFormats: z.record(z.string(), z.object({ schema: z.string(), source: z.string() }).strict()),
13
+ descriptions: z.record(z.string(), z.string()),
14
+ }).strict();
15
+ function restoreFormat(saved, local) {
16
+ const source = z.record(z.string(), z.unknown()).parse(JSON.parse(saved.source));
17
+ // Validate the provider shape while leaving defaults, catches and cleanup to the local core.
18
+ const provider = z.record(z.string(), z.unknown()).parse(JSON.parse(saved.schema));
19
+ const validator = z.fromJSONSchema(provider);
20
+ const constraints = local ?? z.fromJSONSchema(source);
21
+ // A fresh root keeps Zod's refinement parent metadata out of the schema hook.
22
+ const format = z.unknown().pipe(z.json().superRefine((value, context) => {
23
+ if (!validator.safeParse(value).success || !constraints.safeParse(value).success) {
24
+ context.addIssue({ code: "custom", message: "Invalid answer format" });
25
+ }
26
+ }));
27
+ // Zod's schema hook preserves the compiler input without rebuilding a stricter validator.
28
+ format._zod.toJSONSchema = () => structuredClone(source);
29
+ if (JSON.stringify(zodOutputFormat(format).schema) !== saved.schema)
30
+ throw new Error("Incompatible answer format");
31
+ return format;
32
+ }
33
+ export function deserialiseRegistry(bytes) {
34
+ try {
35
+ const payload = registryPayload.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
36
+ const text = createInstructionText({
37
+ templates: payload.includes, descriptions: payload.descriptions,
38
+ });
39
+ const formats = answerFormats(undefined, name => Object.hasOwn(payload.descriptions, name) ? text.description(name) : undefined);
40
+ const { withDescriptions } = createSchemaDescriptions(text);
41
+ return { ...payload, answerFormats: Object.fromEntries(Object.entries(payload.answerFormats).map(([name, schema]) => {
42
+ let format;
43
+ if (Object.hasOwn(formats, name)) {
44
+ // Decrypted wording hydrates the same enumeration used by the source registry.
45
+ format = withDescriptions(formats[name]);
46
+ if (JSON.stringify(z.toJSONSchema(format, { reused: "ref" })) !== schema.source)
47
+ throw new Error();
48
+ }
49
+ return [name, restoreFormat(schema, format)];
50
+ })) };
51
+ }
52
+ catch {
53
+ // JSON and schema errors can quote decrypted instructions; callers only need the failure category.
54
+ throw new Error("Invalid registry payload");
55
+ }
56
+ }
57
+ const sealedRegistryPayload = z.object({
58
+ registry: registryPayload,
59
+ fingerprintKey: z.string(),
60
+ policy: z.record(z.string(), z.object({
61
+ role: z.enum(["required", "optional"]), answerFormats: z.array(z.string().min(1)).min(1),
62
+ }).strict()),
63
+ }).strict();
64
+ export function deserialiseSealedRegistry(bytes) {
65
+ try {
66
+ const payload = sealedRegistryPayload.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
67
+ const fingerprintKey = Buffer.from(payload.fingerprintKey, "base64");
68
+ if (fingerprintKey.length !== 32 || fingerprintKey.toString("base64") !== payload.fingerprintKey)
69
+ throw new Error();
70
+ return { registry: deserialiseRegistry(Buffer.from(JSON.stringify(payload.registry))), fingerprintKey, policy: payload.policy };
71
+ }
72
+ catch {
73
+ throw new Error("Invalid registry payload");
74
+ }
75
+ }
@@ -0,0 +1,25 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ function decode(value) {
3
+ const bytes = Buffer.from(value, "base64");
4
+ if (bytes.toString("base64") !== value)
5
+ throw new Error("Invalid base64 encoding");
6
+ return bytes;
7
+ }
8
+ export function encrypt(plaintext, key) {
9
+ const iv = randomBytes(12);
10
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
11
+ // The contract has no separate tag field; keep the tag with the ciphertext it authenticates.
12
+ const sealed = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
13
+ return { sealed: sealed.toString("base64"), iv: iv.toString("base64") };
14
+ }
15
+ export function decrypt(sealed, iv, key) {
16
+ const bytes = decode(sealed);
17
+ const nonce = decode(iv);
18
+ if (nonce.length !== 12 || bytes.length < 16)
19
+ throw new Error("Invalid encrypted payload");
20
+ // The payload length check and subarray(-16) enforce a 16-byte authentication tag.
21
+ // nosemgrep: javascript.node-crypto.security.gcm-no-tag-length.gcm-no-tag-length
22
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
23
+ decipher.setAuthTag(bytes.subarray(-16));
24
+ return Buffer.concat([decipher.update(bytes.subarray(0, -16)), decipher.final()]);
25
+ }
@@ -0,0 +1,69 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { stableStringify } from "../../analysis-core/llm/stable-json.js";
3
+ import { createInstructionText } from "../../analysis-core/requests/instruction-text.js";
4
+ import { requestPolicy } from "../../analysis-core/contracts/requests.js";
5
+ import { bundleMetadata } from "../../contract/messages.js";
6
+ import { buildAnalysisCall, callInputBytes } from "../../analysis-core/requests/registry.js";
7
+ import { headlineRequest } from "../../analysis-core/requests/headline-request.js";
8
+ import { HEADLINE_RESULT_VERSION } from "../../analysis-core/analysis/headlines/types.js";
9
+ import { z } from "zod";
10
+ import { createRequestTools } from "../../analysis-core/requests/tools.js";
11
+ export function sameNames(names, values) {
12
+ const actual = Object.keys(values).sort();
13
+ return names.length === actual.length && [...names].sort().every((name, index) => name === actual[index]);
14
+ }
15
+ export function createBundleMetadata(registry, key, policy) {
16
+ if (key.byteLength !== 32 || !sameNames(Object.keys(policy), registry.templates))
17
+ throw new Error("Invalid bundle policy");
18
+ function asset(kind, name, value) {
19
+ return { size: Buffer.byteLength(value), fingerprint: createHmac("sha256", key)
20
+ .update(stableStringify([kind, name, value])).digest("hex") };
21
+ }
22
+ const known = requestPolicy();
23
+ const text = createInstructionText({ templates: registry.includes ?? {}, descriptions: registry.descriptions });
24
+ let headlinePlan;
25
+ if (Object.hasOwn(registry.templates, "finding-headlines")) {
26
+ const request = headlineRequest([]);
27
+ const call = buildAnalysisCall({ ...request, inputs: { data: request.inputs, settings: {} } }, registry);
28
+ const probe = headlineRequest([{ key: "f0", kind: "finding", impact: "correctness", structure: null,
29
+ cause: "", category: null, question: null, site: null, excerpt: null, otherSites: [], fixSummaries: [] }]);
30
+ const probeCall = buildAnalysisCall({ ...probe, inputs: { data: probe.inputs, settings: {} } }, registry);
31
+ // Evidence enters the renderer as one JSON scalar. Measure its copies through the renderer, including includes.
32
+ const evidenceCopies = (callInputBytes(probeCall) - callInputBytes(call)) / (Buffer.byteLength(JSON.stringify(probe.inputs.evidence)) - 2);
33
+ const inputOverheadBytes = callInputBytes(call) - evidenceCopies * 2;
34
+ if (!Number.isSafeInteger(evidenceCopies) || evidenceCopies < 0 || inputOverheadBytes < 0)
35
+ throw new Error("Invalid bundle policy");
36
+ headlinePlan = { ...asset("headline-plan", "finding-headlines", stableStringify({ system: call.system, prompt: call.prompt,
37
+ schema: z.toJSONSchema(call.schema, { reused: "ref" }), fallbackQuestion: createRequestTools(text).headlineFallbackQuestion() })),
38
+ inputOverheadBytes, evidenceCopies, resultVersion: HEADLINE_RESULT_VERSION };
39
+ }
40
+ return bundleMetadata.parse({
41
+ templates: Object.fromEntries(Object.entries(registry.templates).map(([name, template]) => {
42
+ const item = policy[name];
43
+ if (Object.hasOwn(known, name) && stableStringify(item) !== stableStringify(known[name]))
44
+ throw new Error("Invalid bundle policy");
45
+ if (!item || new Set(item.answerFormats).size !== item.answerFormats.length ||
46
+ item.answerFormats.some(format => !Object.hasOwn(registry.answerFormats, format)))
47
+ throw new Error("Invalid bundle policy");
48
+ return [name, { ...asset("template", name, stableStringify(template)), role: item.role, answerFormats: [...item.answerFormats].sort() }];
49
+ })),
50
+ includes: Object.fromEntries(Object.entries(registry.includes ?? {}).map(([name, value]) => {
51
+ const expanded = asset("expanded-include", name, text.templateText(name));
52
+ return [name, { ...asset("include", name, value), expandedSize: expanded.size, expandedFingerprint: expanded.fingerprint }];
53
+ })),
54
+ descriptions: Object.fromEntries(Object.entries(registry.descriptions).map(([name, value]) => [name, asset("description", name, value)])),
55
+ ...(headlinePlan ? { headlinePlan } : {}),
56
+ });
57
+ }
58
+ export function verifyBundleMetadata(metadata, registry, key, policy) {
59
+ const supplied = bundleMetadata.parse(metadata);
60
+ const expected = createBundleMetadata(registry, key, policy);
61
+ // Older releases remain readable; their metadata cannot enable sealed headline planning.
62
+ if (!supplied.headlinePlan)
63
+ delete expected.headlinePlan;
64
+ else if (supplied.headlinePlan.resultVersion === undefined && expected.headlinePlan)
65
+ delete expected.headlinePlan.resultVersion;
66
+ if (stableStringify(supplied) !== stableStringify(expected)) {
67
+ throw new Error("Invalid bundle metadata");
68
+ }
69
+ }
@@ -0,0 +1,38 @@
1
+ import { sealedBundle } from "../../contract/messages.js";
2
+ import { decrypt } from "./encryption.js";
3
+ import { deserialiseSealedRegistry } from "./deserialise.js";
4
+ import { sameNames, verifyBundleMetadata } from "./metadata.js";
5
+ import { verifyCompatibleRelease } from "./signature.js";
6
+ const authenticated = new WeakSet();
7
+ export function isOpenedBundle(registry) { return authenticated.has(registry); }
8
+ function freezeData(data) {
9
+ if (data && typeof data === "object") {
10
+ for (const child of Object.values(data))
11
+ freezeData(child);
12
+ Object.freeze(data);
13
+ }
14
+ return data;
15
+ }
16
+ export async function openBundle(value, options) {
17
+ const parsed = sealedBundle.safeParse(value);
18
+ if (!parsed.success)
19
+ throw new Error("Invalid sealed bundle");
20
+ const bundle = parsed.data;
21
+ verifyCompatibleRelease(bundle, options.verificationKey, options.relayVersion);
22
+ try {
23
+ const key = await options.keyService.unwrapKey(bundle.wrappedKey);
24
+ const { registry, fingerprintKey, policy } = deserialiseSealedRegistry(decrypt(bundle.sealed, bundle.iv, key));
25
+ if (Buffer.from(key).equals(fingerprintKey) || !sameNames(bundle.templates, registry.templates) || !sameNames(bundle.answerFormats, registry.answerFormats)) {
26
+ throw new Error();
27
+ }
28
+ verifyBundleMetadata(bundle.metadata, registry, fingerprintKey, policy);
29
+ const opened = Object.freeze({ ...registry, templates: freezeData(registry.templates), includes: freezeData(registry.includes),
30
+ descriptions: freezeData(registry.descriptions), answerFormats: Object.freeze(registry.answerFormats),
31
+ policy: freezeData(policy), bundleMetadata: freezeData(bundle) });
32
+ authenticated.add(opened);
33
+ return opened;
34
+ }
35
+ catch {
36
+ throw new Error("Unable to open bundle");
37
+ }
38
+ }
@@ -0,0 +1,20 @@
1
+ import { stableStringify } from "../../analysis-core/llm/stable-json.js";
2
+ import { id } from "../../contract/console.js";
3
+ /** Authenticated bundle metadata owns which planned templates and formats are available. */
4
+ export function checkPlannedCallsAgainstBundle(bundle, calls, policy) {
5
+ for (const { templateId, answerFormatId } of calls) {
6
+ id.parse(templateId);
7
+ id.parse(answerFormatId);
8
+ const template = Object.hasOwn(bundle.metadata.templates, templateId) ? bundle.metadata.templates[templateId] : undefined;
9
+ if (!bundle.templates.includes(templateId) || !bundle.answerFormats.includes(answerFormatId)
10
+ || !template?.answerFormats.includes(answerFormatId))
11
+ throw new Error("Unsupported planned template or format");
12
+ if (policy !== undefined) {
13
+ const rule = Object.hasOwn(policy, templateId) ? policy[templateId] : undefined;
14
+ if (!rule || rule.role !== template.role || !rule.answerFormats.includes(answerFormatId)
15
+ || stableStringify([...new Set(rule.answerFormats)].sort()) !== stableStringify([...new Set(template.answerFormats)].sort())) {
16
+ throw new Error("Runtime and sealed policy differ");
17
+ }
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,51 @@
1
+ import { createHash, createPublicKey, sign, verify } from "node:crypto";
2
+ import { stableStringify } from "../../analysis-core/llm/stable-json.js";
3
+ export const RELEASE_SIGNING_INPUT_LIMIT = 64 * 1024;
4
+ /** Billing identifies the encrypted payload; publication receipts separately identify the full JSON file. */
5
+ export function sealedBundleHash(bundle) {
6
+ return createHash("sha256").update(Buffer.from(bundle.sealed, "base64")).digest("hex");
7
+ }
8
+ function signingBytes(bundle) {
9
+ // One encoding serves both release tooling and the relay, independent of JSON key order on disk.
10
+ const fields = Object.fromEntries(Object.entries(bundle).filter(([name]) => name !== "signature"));
11
+ // The release key signs a fixed-size fingerprint, because the production key service signs at most 64 KiB
12
+ // and a sealed bundle is larger. The label keeps these signatures from being valid for anything else.
13
+ return createHash("sha256").update("counterfact sealed release v1\n").update(stableStringify(fields), "utf8").digest();
14
+ }
15
+ function checkKey(key) {
16
+ if (key.asymmetricKeyType !== "ed25519")
17
+ throw new Error("Expected an Ed25519 release key");
18
+ }
19
+ export function signRelease(bundle, key) {
20
+ checkKey(key);
21
+ return sign(null, signingBytes(bundle), key).toString("base64");
22
+ }
23
+ export function localReleaseSigner(key) {
24
+ checkKey(key);
25
+ return { publicKey: createPublicKey(key), async sign(bytes) { return sign(null, bytes, key); } };
26
+ }
27
+ export async function signReleaseWithSigner(release, signer) {
28
+ checkKey(signer.publicKey);
29
+ // Strict console metadata JSON cannot be a 32-byte bundle fingerprint, so the two formats cannot share a signature.
30
+ const bytes = Buffer.isBuffer(release) ? Buffer.from(release) : signingBytes(release);
31
+ if (bytes.byteLength > RELEASE_SIGNING_INPUT_LIMIT)
32
+ throw new Error("Release signing input exceeds 64 KiB");
33
+ const signature = await signer.sign(Buffer.from(bytes));
34
+ // A remote key reference can point at a different release key; catch that before publishing a bundle.
35
+ if (signature.byteLength !== 64 || !verify(null, bytes, signer.publicKey, signature))
36
+ throw new Error("Invalid release signature");
37
+ return signature.toString("base64");
38
+ }
39
+ export function verifyRelease(bundle, key) {
40
+ checkKey(key);
41
+ const signature = Buffer.from(bundle.signature, "base64");
42
+ if (signature.toString("base64") !== bundle.signature || !verify(null, signingBytes(bundle), key, signature)) {
43
+ throw new Error("Invalid bundle signature");
44
+ }
45
+ }
46
+ export function verifyCompatibleRelease(bundle, key, relayVersion) {
47
+ // Authenticate the advertised compatibility list before any caller relies on it or releases a key.
48
+ verifyRelease(bundle, key);
49
+ if (!bundle.relayVersions.includes(relayVersion))
50
+ throw new Error("Unsupported relay version");
51
+ }
@@ -0,0 +1,17 @@
1
+ import { resolveFolderPath } from "../adapters/folder-path.js";
2
+ import { START_FAILURE_MESSAGE } from "../contract/cli-refusals.js";
3
+ import { isAbsolute, parse, relative, resolve, sep } from "node:path";
4
+ export function resolveAgentFolder(path, cwd) {
5
+ return resolve(cwd ?? process.cwd(), path);
6
+ }
7
+ /** The MCP launch tree is the user's boundary for unattended paid work. */
8
+ export async function resolveMcpAgentFolder(path, cwd, homeDir) {
9
+ const [folder, launch, home] = await Promise.all([
10
+ resolveFolderPath(resolveAgentFolder(path, cwd)), resolveFolderPath(cwd), resolveFolderPath(homeDir),
11
+ ]).catch(() => { throw new Error(START_FAILURE_MESSAGE); });
12
+ const rel = relative(launch, folder);
13
+ if (folder === parse(folder).root || folder === home || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
14
+ throw new Error(START_FAILURE_MESSAGE);
15
+ }
16
+ return folder;
17
+ }
@@ -0,0 +1,2 @@
1
+ // Keep the copied command API contract self-contained.
2
+ export const CLI_BODY_LIMIT = 2 * 1024 * 1024;
@@ -0,0 +1 @@
1
+ export { ApiClient, ApiError, DEFAULT_URL, errorCode, errorText } from "../gatekeeper/cli-api.js";
@@ -1,9 +1,10 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  const servers = ["mcp__plugin_counterfact_counterfact", "mcp__counterfact"];
4
- export const CHECK_TOOL_RULE = `${servers[0]}__check_agent`;
5
- const allowedRules = new Set(servers.flatMap(server => [server, `${server}__*`, `${server}__check_agent`]));
6
- export async function checkToolAllowed(homeDir, cwd) {
4
+ export const ANALYZE_TOOL_NAME = "analyze_agent";
5
+ export const ANALYZE_TOOL_RULE = `${servers[0]}__${ANALYZE_TOOL_NAME}`;
6
+ const allowedRules = new Set(servers.flatMap(server => [server, `${server}__*`, `${server}__${ANALYZE_TOOL_NAME}`]));
7
+ export async function analyzeToolAllowed(homeDir, cwd) {
7
8
  const paths = [join(homeDir, ".claude/settings.json"), join(cwd, ".claude/settings.json"), join(cwd, ".claude/settings.local.json")];
8
9
  const matches = await Promise.all(paths.map(async (path) => {
9
10
  try {