@buddysh/buddy 0.11.0 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/README.md +54 -43
- package/bin/cli.ts +282 -135
- package/dist/bin/cli.d.ts +5 -1
- package/dist/bin/cli.js +84 -91
- package/dist/chunk-05me15qw.js +2 -0
- package/dist/{chunk-bxfc4g2x.js → chunk-08x5b93v.js} +2 -13
- package/dist/chunk-0eg3kxb5.js +5 -0
- package/dist/chunk-0hc97k0t.js +44 -0
- package/dist/chunk-0paakbpj.js +2 -0
- package/dist/{chunk-hfvezfxh.js → chunk-0scz1dv5.js} +1 -1
- package/dist/{chunk-sp818c27.js → chunk-0w695m54.js} +5 -5
- package/dist/{chunk-vyapg8ca.js → chunk-11hdrnf6.js} +3 -3
- package/dist/{chunk-1stt2whn.js → chunk-15r904nz.js} +2 -2
- package/dist/{chunk-5k40mwd4.js → chunk-193abzy6.js} +1 -1
- package/dist/chunk-19zyq15p.js +2 -0
- package/dist/chunk-1c4690h9.js +79 -0
- package/dist/{chunk-q9n79dd3.js → chunk-1cpdz49v.js} +1 -1
- package/dist/{chunk-thaxgm5p.js → chunk-1qgr52wx.js} +1 -1
- package/dist/chunk-24c2ab29.js +2 -0
- package/dist/chunk-25sz1y7j.js +16 -0
- package/dist/chunk-2et8yavs.js +3 -0
- package/dist/chunk-2wj5xtdn.js +2 -0
- package/dist/{chunk-7mgec8kb.js → chunk-3901s7h9.js} +1 -1
- package/dist/{chunk-xvptf9jy.js → chunk-3cvng2nz.js} +2 -2
- package/dist/chunk-3fzbvs2p.js +2 -0
- package/dist/chunk-3pqra420.js +2 -0
- package/dist/{chunk-yk23nc4t.js → chunk-40znfg3x.js} +1 -1
- package/dist/chunk-428c5652.js +2 -0
- package/dist/chunk-49znmbh8.js +2 -0
- package/dist/chunk-5044y9en.js +5 -0
- package/dist/chunk-5yfaptmp.js +7 -0
- package/dist/{chunk-h7hs95wn.js → chunk-61xecp1z.js} +2 -2
- package/dist/{chunk-x0ya2r4r.js → chunk-657nbbp7.js} +2 -2
- package/dist/chunk-68fw3ma0.js +2 -0
- package/dist/{chunk-9h04nskh.js → chunk-69qyr9ef.js} +1 -1
- package/dist/chunk-6bd8ghkz.js +27 -0
- package/dist/{chunk-vh504tcv.js → chunk-6p4qz8qv.js} +2 -2
- package/dist/chunk-847g7jde.js +2 -0
- package/dist/{chunk-r3zyw8x0.js → chunk-8fw0v7bv.js} +2 -2
- package/dist/chunk-8hjvthz4.js +92 -0
- package/dist/chunk-90zmqn5k.js +2 -0
- package/dist/{chunk-3zdcekfj.js → chunk-929h6hhp.js} +2 -2
- package/dist/chunk-96ht6hwd.js +4 -0
- package/dist/chunk-97qf7mdt.js +2 -0
- package/dist/chunk-a4hzzn28.js +2 -0
- package/dist/chunk-aa277p5r.js +2 -0
- package/dist/chunk-b357cgb0.js +2 -0
- package/dist/chunk-b9escac0.js +4 -0
- package/dist/{chunk-56q4pwb5.js → chunk-be629jhq.js} +2 -2
- package/dist/chunk-bffxf4xy.js +2 -0
- package/dist/chunk-brfyymhf.js +2 -0
- package/dist/{chunk-zs3jaj0g.js → chunk-bymwaezh.js} +165 -119
- package/dist/chunk-c3es7pgf.js +2 -0
- package/dist/{chunk-9750tenz.js → chunk-c8rzx3a1.js} +1 -1
- package/dist/{chunk-tzs22es2.js → chunk-cgvt98pd.js} +1 -1
- package/dist/chunk-cwfkm7h9.js +3 -0
- package/dist/chunk-cwqhxqv7.js +2 -0
- package/dist/chunk-dgfb8k0h.js +2 -0
- package/dist/chunk-dqbk3kcj.js +104 -0
- package/dist/chunk-ds4stft2.js +2 -0
- package/dist/{chunk-1h3ey7k5.js → chunk-e68nf7cm.js} +1 -1
- package/dist/chunk-emyvrx5t.js +2 -0
- package/dist/{chunk-16yqbccr.js → chunk-eseshkd0.js} +1 -1
- package/dist/chunk-f53y8ans.js +3 -0
- package/dist/chunk-fjp3a7hp.js +26 -0
- package/dist/chunk-fpnjpgrb.js +2 -0
- package/dist/chunk-fr5c326k.js +2 -0
- package/dist/chunk-g24hav8e.js +370 -0
- package/dist/{chunk-6md7qf2g.js → chunk-g30dr44w.js} +2 -2
- package/dist/chunk-gkpd5nw2.js +2 -0
- package/dist/chunk-hbhmns7s.js +2 -0
- package/dist/chunk-hd5j9e3c.js +2 -0
- package/dist/{chunk-akffynkc.js → chunk-hfjywbbc.js} +1 -1
- package/dist/chunk-hmskwy76.js +2 -0
- package/dist/chunk-hns85dqw.js +2 -0
- package/dist/{chunk-wtjhehz9.js → chunk-hptfq3rg.js} +1 -1
- package/dist/{chunk-54sc18p8.js → chunk-hsa07n7c.js} +1 -1
- package/dist/chunk-hwxmhkxp.js +2 -0
- package/dist/{chunk-52x8mvh4.js → chunk-jnb80k2x.js} +2 -2
- package/dist/chunk-jtxcr5yw.js +4 -0
- package/dist/{chunk-tn8prpny.js → chunk-k26wnmzk.js} +7 -7
- package/dist/{chunk-2bp7tqca.js → chunk-kprtsn8c.js} +1 -1
- package/dist/chunk-m4p7cnvk.js +2 -0
- package/dist/chunk-mcwxpdg9.js +2 -0
- package/dist/chunk-mkzmjg3f.js +4 -0
- package/dist/chunk-ncrq3fvv.js +2 -0
- package/dist/chunk-ng7px8gx.js +2 -0
- package/dist/{chunk-vagxqhef.js → chunk-nrr8z2z7.js} +2 -2
- package/dist/{chunk-g0w8n555.js → chunk-p6qbqsyp.js} +2 -2
- package/dist/chunk-p8tmms5h.js +3 -0
- package/dist/{chunk-hw70wbzg.js → chunk-phfmnnne.js} +2 -2
- package/dist/{chunk-tb5y0350.js → chunk-pkr6905p.js} +1 -1
- package/dist/chunk-ppmabn5h.js +2 -0
- package/dist/chunk-pskqrv5r.js +2 -0
- package/dist/{chunk-4xsq18p3.js → chunk-q2tjkhez.js} +1 -1
- package/dist/{chunk-6g1y9yqh.js → chunk-q4t568hv.js} +1 -1
- package/dist/chunk-qd2s51gc.js +2 -0
- package/dist/chunk-r763e19p.js +6 -0
- package/dist/{chunk-74pxb991.js → chunk-rc2mk5x6.js} +2 -2
- package/dist/{chunk-zb62jhwm.js → chunk-s4zb0fcj.js} +13 -9
- package/dist/chunk-s6z3gm2s.js +5 -0
- package/dist/chunk-sc7emb71.js +2 -0
- package/dist/chunk-sw2538r0.js +49 -0
- package/dist/chunk-t25apff9.js +2 -0
- package/dist/{chunk-p4zwy518.js → chunk-tjc2vgwn.js} +2 -2
- package/dist/{chunk-gngwjf70.js → chunk-tw047td6.js} +2 -2
- package/dist/chunk-tws3npt7.js +38 -0
- package/dist/{chunk-6d9hmjt8.js → chunk-txtrpypt.js} +2 -2
- package/dist/chunk-v1wfa758.js +2 -0
- package/dist/{chunk-dfesffnr.js → chunk-vckhctmr.js} +1 -1
- package/dist/chunk-vdd1cghr.js +2 -0
- package/dist/{chunk-fvpr07dn.js → chunk-vgtmrd4c.js} +1 -1
- package/dist/chunk-vj1sdxpp.js +2 -0
- package/dist/{chunk-fm8ckj9b.js → chunk-vqa6vte3.js} +1 -1
- package/dist/{chunk-82dv4p13.js → chunk-wn6pbyzn.js} +1 -1
- package/dist/chunk-x23a6szw.js +2 -0
- package/dist/{chunk-xqx460y2.js → chunk-xs12dtf1.js} +1 -1
- package/dist/chunk-xznnmhyt.js +2 -0
- package/dist/chunk-y3dd8v85.js +2 -0
- package/dist/chunk-yk183r6z.js +2 -0
- package/dist/{chunk-1c1gznm9.js → chunk-yngahb11.js} +2 -2
- package/dist/{chunk-qyf90zz3.js → chunk-yp1tgdh3.js} +1 -1
- package/dist/chunk-ys1qqcpp.js +2 -0
- package/dist/{chunk-8rc6042h.js → chunk-ytmxd5fk.js} +2 -2
- package/dist/chunk-zgkrhymn.js +2 -0
- package/dist/chunk-zxgkp71x.js +2 -0
- package/dist/src/agent/index.d.ts +6 -1
- package/dist/src/agent/modes.d.ts +0 -8
- package/dist/src/agent/plan.d.ts +28 -0
- package/dist/src/agent/tasks.d.ts +20 -0
- package/dist/src/agent/tools/issue.d.ts +19 -0
- package/dist/src/ci/attempts.d.ts +36 -0
- package/dist/src/ci/base.d.ts +55 -0
- package/dist/src/ci/fix.d.ts +27 -18
- package/dist/src/ci/index.d.ts +5 -1
- package/dist/src/ci/run.d.ts +28 -0
- package/dist/src/commands/handlers.d.ts +3 -0
- package/dist/src/dashboard/dashboard-generator.d.ts +4 -0
- package/dist/src/events/index.d.ts +12 -0
- package/dist/src/gates/checks.d.ts +10 -0
- package/dist/src/gates/index.d.ts +1 -0
- package/dist/src/gates/post-merge.d.ts +13 -1
- package/dist/src/git/github-provider.d.ts +5 -1
- package/dist/src/git/gitlab-provider.d.ts +5 -1
- package/dist/src/git/provider.d.ts +40 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +1 -1
- package/dist/src/registry/registry-client.d.ts +1 -1
- package/dist/src/reports/index.d.ts +1 -0
- package/dist/src/reports/publish-gate.d.ts +22 -0
- package/dist/src/review/filters.d.ts +36 -0
- package/dist/src/review/index.d.ts +4 -1
- package/dist/src/review/marker.d.ts +18 -0
- package/dist/src/review/poster.d.ts +11 -1
- package/dist/src/review/resolve.d.ts +20 -0
- package/dist/src/review/run.d.ts +35 -0
- package/dist/src/rules/engine.d.ts +19 -0
- package/dist/src/scanner/package-json-extras.d.ts +34 -1
- package/dist/src/setup.d.ts +49 -17
- package/dist/src/setup.js +1 -1
- package/dist/src/templates/github-actions.d.ts +2 -0
- package/dist/src/types.d.ts +4 -1
- package/dist/src/upgrades/migrate.d.ts +3 -0
- package/dist/src/upgrades/report.d.ts +1 -0
- package/dist/src/utils/dockerfile-parser.d.ts +2 -2
- package/dist/src/utils/helpers.d.ts +10 -1
- package/dist/src/version/version-resolver.d.ts +1 -0
- package/package.json +12 -10
- package/dist/chunk-0j7z87kh.js +0 -3
- package/dist/chunk-0r8zt3d7.js +0 -2
- package/dist/chunk-1a53wj0h.js +0 -1
- package/dist/chunk-1wjnd24b.js +0 -24
- package/dist/chunk-1xe07hzm.js +0 -2
- package/dist/chunk-2dbkpfy9.js +0 -2
- package/dist/chunk-3q6czqs4.js +0 -6
- package/dist/chunk-49ey79p0.js +0 -5
- package/dist/chunk-4c9m61yd.js +0 -5
- package/dist/chunk-4efbxdjr.js +0 -4
- package/dist/chunk-4f7panqj.js +0 -21
- package/dist/chunk-4hd3rre0.js +0 -2
- package/dist/chunk-5c3qf34r.js +0 -2
- package/dist/chunk-5kt03hx5.js +0 -2
- package/dist/chunk-63ept76v.js +0 -2
- package/dist/chunk-65b3vq52.js +0 -2
- package/dist/chunk-6k653r8w.js +0 -2
- package/dist/chunk-6patq6bw.js +0 -2
- package/dist/chunk-6sgh49z1.js +0 -2
- package/dist/chunk-7tfrww3v.js +0 -2
- package/dist/chunk-7xk28xrv.js +0 -2
- package/dist/chunk-8661pvb8.js +0 -3
- package/dist/chunk-887s0w81.js +0 -2
- package/dist/chunk-978wtejw.js +0 -44
- package/dist/chunk-9eqpaxfz.js +0 -2
- package/dist/chunk-9p1xkmjy.js +0 -2
- package/dist/chunk-agdesgzv.js +0 -2
- package/dist/chunk-ar01x04a.js +0 -2
- package/dist/chunk-ay43f085.js +0 -2
- package/dist/chunk-bk9bqd5j.js +0 -2
- package/dist/chunk-bm8d40j0.js +0 -69
- package/dist/chunk-c3fczawt.js +0 -2
- package/dist/chunk-c9r9nd4t.js +0 -1
- package/dist/chunk-ctsz0ynx.js +0 -3
- package/dist/chunk-czremqk7.js +0 -2
- package/dist/chunk-da3wbh04.js +0 -2
- package/dist/chunk-dat582cg.js +0 -2
- package/dist/chunk-djntbp7a.js +0 -105
- package/dist/chunk-eagjp0dh.js +0 -3
- package/dist/chunk-eht72nnj.js +0 -2
- package/dist/chunk-f4nv5x3z.js +0 -2
- package/dist/chunk-fdfk918n.js +0 -2
- package/dist/chunk-fdj0tewy.js +0 -20
- package/dist/chunk-fqj7e6xa.js +0 -2
- package/dist/chunk-frm8zz31.js +0 -2
- package/dist/chunk-g0nv8psv.js +0 -2
- package/dist/chunk-gkmvxjbe.js +0 -2
- package/dist/chunk-j8asz4hb.js +0 -15
- package/dist/chunk-k62w2v03.js +0 -2
- package/dist/chunk-mcrfxphm.js +0 -5
- package/dist/chunk-mh3x7j6h.js +0 -2
- package/dist/chunk-naq32yx3.js +0 -86
- package/dist/chunk-nsmcjkas.js +0 -2
- package/dist/chunk-p1xm1jvz.js +0 -2
- package/dist/chunk-p3wsm8kz.js +0 -2
- package/dist/chunk-p7zgy37f.js +0 -2
- package/dist/chunk-ph1b3vbp.js +0 -315
- package/dist/chunk-pkjm2r0a.js +0 -2
- package/dist/chunk-pkkwb0n0.js +0 -4
- package/dist/chunk-pnpx1kqn.js +0 -6
- package/dist/chunk-qpz9k66h.js +0 -2
- package/dist/chunk-qvn1rtgp.js +0 -2
- package/dist/chunk-r06ce5g6.js +0 -2
- package/dist/chunk-r2sbprdb.js +0 -49
- package/dist/chunk-rqdep14r.js +0 -2
- package/dist/chunk-s1km8cyq.js +0 -2
- package/dist/chunk-s4ms8zag.js +0 -2
- package/dist/chunk-ts35hc5t.js +0 -3
- package/dist/chunk-vkctfqpm.js +0 -3
- package/dist/chunk-wdwvt7gb.js +0 -43
- package/dist/chunk-x3kragh9.js +0 -12
- package/dist/chunk-x9ctz1qc.js +0 -1
- package/dist/chunk-xakpdqaq.js +0 -3
- package/dist/chunk-yncea6ty.js +0 -2
- package/dist/chunk-yq0gxtzv.js +0 -2
- package/dist/chunk-yqhs08ky.js +0 -2
- package/dist/chunk-zve5d96e.js +0 -2
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Mb as g,Nb as r,Ob as e,Pb as jj}from"./chunk-5yfaptmp.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-rc2mk5x6.js";import{fc as s}from"./chunk-tjc2vgwn.js";import{$d as i}from"./chunk-nrr8z2z7.js";import{me as S}from"./chunk-p8tmms5h.js";import{Jf as b,Kf as m}from"./chunk-1cpdz49v.js";import{Fh as Y}from"./chunk-hfjywbbc.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
|
|
3
|
+
|
|
4
|
+
Report only defects you can point at in the diff. A review that invents
|
|
5
|
+
findings to look thorough is worse than one that reports nothing, so say
|
|
6
|
+
plainly when a change looks fine.
|
|
7
|
+
|
|
8
|
+
Every finding must name a file and a line number that appears in the diff you
|
|
9
|
+
were given. Do not report findings about code you cannot see.
|
|
10
|
+
|
|
11
|
+
Only include a suggestion when the fix is mechanical and you can write the
|
|
12
|
+
replacement exactly. Omit it for anything requiring judgement.`,Zj={chill:`Report only findings you are confident are real defects: correctness
|
|
13
|
+
bugs, security problems, and changes that break existing behaviour. Skip style
|
|
14
|
+
preferences, naming opinions, and speculative concerns.`,assertive:`Report correctness, security, performance, and maintainability
|
|
15
|
+
findings, including ones you are less certain about. Mark uncertain findings
|
|
16
|
+
as minor or nit so they can be filtered downstream, and still skip pure style
|
|
17
|
+
preferences.`};async function h(J,j){let Q=j.logger??Y(),Z=j.profile??"chill",$=_(j.diff),X=b(j.pathFilters),x=j.includePath??((O)=>xj(O)&&X.matches(O)),K=y($,{include:x});if(K.files.length===0)return Q.info("\uD83D\uDD0D Nothing to review after filtering generated and lock files"),{summary:"No reviewable changes.",walkthrough:[],findings:[],effort:1,omittedFiles:K.omitted};Q.info(`\uD83D\uDD0D Reviewing ${K.files.length} file(s), ${$.changedLines} changed line(s)`);let z=[...new Set(K.files.flatMap((O)=>m(O.path,j.pathInstructions)))],B=[Qj,Zj[Z],j.summaryOnly?"Return an empty findings array; only the summary and walkthrough are wanted.":"",j.instructions?`Repository-specific guidance:
|
|
18
|
+
${j.instructions}`:"",z.length>0?`Guidance for the files under review:
|
|
19
|
+
${z.join(`
|
|
20
|
+
`)}`:"",j.learnings?.trim()??""].filter(Boolean).join(`
|
|
21
|
+
|
|
22
|
+
`),P=[j.context?`Context:
|
|
23
|
+
${j.context}
|
|
24
|
+
`:"",`Diff:
|
|
25
|
+
`,K.text].join(""),H=(await J.complete({system:B,messages:[{role:"user",content:P}],jsonSchema:w})).json??{},q=$j($),M=Array.isArray(H.findings)?H.findings:[],{valid:V,dropped:G}=N(M,q);if(G.length>0)Q.debug(`\uD83D\uDD0D Dropped ${G.length} finding(s) that did not anchor to a changed line`);let{valid:L}=N(j.analyzerFindings??[],q),U=v([...L,...V],new Set(j.seenFingerprints??[]));if(U.length<V.length)Q.debug(`\uD83D\uDD0D Skipped ${V.length-U.length} finding(s) already reported`);return{summary:typeof H.summary==="string"?H.summary:"",walkthrough:Array.isArray(H.walkthrough)?H.walkthrough:[],findings:j.summaryOnly?[]:U,effort:Kj(H.effort),omittedFiles:K.omitted}}function $j(J){return new Map(J.files.map((j)=>[j.path,j.commentableLines]))}function xj(J){return!Jj.some((j)=>j.test(J))}function Kj(J){let j=Number(J);if(!Number.isFinite(j))return 3;return Math.min(5,Math.max(1,Math.round(j)))}var Xj=["CLAUDE.md","AGENTS.md",".cursorrules",".github/copilot-instructions.md","CONTRIBUTING.md"],zj=20000;async function c(J,j,Q=Xj,Z=Y()){if(Q===!1)return"";let $=[],X=0;for(let x of Q){let K=null;try{K=await J(x,j)}catch(P){Z.debug(`Could not read ${x} at ${j}: ${P}`);continue}if(!K?.trim())continue;let z=zj-X;if(z<=0){Z.debug(`Guideline budget exhausted before reading ${x}`);break}let B=K.length>z?`${K.slice(0,z)}
|
|
26
|
+
\u2026 [truncated]`:K;$.push(`--- ${x} ---
|
|
27
|
+
${B}`),X+=B.length}if($.length===0)return"";return Z.debug(`Loaded ${$.length} guideline file(s), ${X} characters`),$.join(`
|
|
28
|
+
|
|
29
|
+
`)}function f(J){let j=[];if(J.global?.trim())j.push(J.global.trim());if(J.pathInstructions?.length)j.push(`Path-specific guidance:
|
|
30
|
+
${J.pathInstructions.join(`
|
|
31
|
+
`)}`);if(J.guidelines?.trim())j.push(`Repository conventions, from its own documentation:
|
|
32
|
+
${J.guidelines.trim()}`);return j.join(`
|
|
33
|
+
|
|
34
|
+
`)}function u(J,j,Q){let Z=J.ai?.review;if(Z?.enabled===!1)return"AI review is disabled for this repository (`ai.review.enabled` is false).";if(Q==="requested")return null;if(Z?.autoReview===!1)return"Automatic review is off (`ai.review.autoReview` is false). Ask for one with `@buddy review`.";if(j.draft&&Z?.drafts!==!0)return"This pull request is a draft. Set `ai.review.drafts` to true, or ask with `@buddy review`.";let $=Hj(j.title,Z?.ignoreTitleKeywords);if($)return`The title contains \`${$}\` (\`ai.review.ignoreTitleKeywords\`).`;if(Oj(j.author,Z?.ignoreUsernames))return`Pull requests from \`${j.author}\` are ignored (\`ai.review.ignoreUsernames\`).`;return null}function Hj(J,j){if(!j?.length)return null;let Q=J.toLowerCase();return j.find((Z)=>Z.trim()&&Q.includes(Z.toLowerCase().trim()))??null}function Oj(J,j){if(!j?.length)return!1;let Q=J.toLowerCase();return j.some((Z)=>Z.toLowerCase().trim()===Q)}var l={critical:"\uD83D\uDD34 critical",major:"\uD83D\uDFE0 major",minor:"\uD83D\uDFE1 minor",nit:"\u26AA nit"};function Wj(J,j){let Q=J.tool?` \`[${J.tool}]\``:"",Z=`**${l[J.severity]}** \xB7 \`${J.category}\`${Q}
|
|
35
|
+
|
|
36
|
+
${J.message}`;if(J.suggestion)Z+=j?.suggestions===!1?`
|
|
37
|
+
|
|
38
|
+
Suggested replacement:
|
|
39
|
+
|
|
40
|
+
\`\`\`
|
|
41
|
+
${J.suggestion}
|
|
42
|
+
\`\`\``:`
|
|
43
|
+
|
|
44
|
+
\`\`\`suggestion
|
|
45
|
+
${J.suggestion}
|
|
46
|
+
\`\`\``;return Z}function k(J,j){let Q=J.findings.map((x)=>({path:x.path,line:x.line,side:"RIGHT",body:Wj(x,{suggestions:j.suggestions!==!1})})),Z=Bj(J.findings),$=Z.critical>0,X=[...new Set([...j.seenFingerprints??[],...J.findings.map(I)])];return{body:Mj(J,Z,j.headSha,X),comments:Q,event:j.requestChangesOn==="critical"&&$?"REQUEST_CHANGES":"COMMENT",state:{reviewedSha:j.headSha,fingerprints:X,reviewedAt:new Date().toISOString()}}}function Mj(J,j,Q,Z){let $=`## \uD83D\uDD0D Review
|
|
47
|
+
|
|
48
|
+
${J.summary||"_No summary produced._"}
|
|
49
|
+
|
|
50
|
+
`,X=J.findings.length,x="\u25CF".repeat(J.effort)+"\u25CB".repeat(5-J.effort);if($+=`**Review effort:** ${x} (${J.effort}/5)
|
|
51
|
+
|
|
52
|
+
`,X===0)$+=`**Findings:** none.
|
|
53
|
+
|
|
54
|
+
`;else{let K=Object.keys(l).filter((z)=>j[z]>0).map((z)=>`${j[z]} ${z}`);$+=`**Findings:** ${X} (${K.join(", ")}) \u2014 see the inline comments.
|
|
55
|
+
|
|
56
|
+
`}if(J.walkthrough.length>0){$+=`<details><summary>Walkthrough</summary>
|
|
57
|
+
|
|
58
|
+
| File | Change |
|
|
59
|
+
|---|---|
|
|
60
|
+
`;for(let K of J.walkthrough)$+=`| \`${D(K.path)}\` | ${D(K.description)} |
|
|
61
|
+
`;$+=`
|
|
62
|
+
</details>
|
|
63
|
+
|
|
64
|
+
`}if(J.omittedFiles.length>0)$+=`<details><summary>${J.omittedFiles.length} file(s) not reviewed</summary>
|
|
65
|
+
|
|
66
|
+
`,$+=`${J.omittedFiles.map((K)=>`- \`${D(K)}\``).join(`
|
|
67
|
+
`)}
|
|
68
|
+
|
|
69
|
+
</details>
|
|
70
|
+
|
|
71
|
+
`;return $+=`---
|
|
72
|
+
|
|
73
|
+
Reply to any comment to discuss it, or comment \`@buddy pause\` to stop reviewing this PR.
|
|
74
|
+
`,$+=g({reviewedSha:Q,fingerprints:Z,reviewedAt:new Date().toISOString()}),$}function Bj(J){let j={critical:0,major:0,minor:0,nit:0};for(let Q of J)j[Q.severity]++;return j}function D(J){return J.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/#(\d)/g,"#\u200B$1")}async function Vj(J){let j=J.logger??Y(),{config:Q,provider:Z,prNumber:$}=J,x=(await Z.getPullRequests("open")).find((W)=>W.number===$);if(!x)return{status:`Could not find open pull request #${$}.`};let K=u(Q,x,J.trigger??"requested");if(K)return j.info(`\uD83D\uDD0D Skipping PR #${$}: ${K}`),{status:K};let z=r(x.body);if(z?.paused&&!J.full)return{status:"Reviews are paused on this pull request. Say `@buddy resume` to restart them."};let B=await Z.getPullRequestDiff($);if(!B.trim())return{status:"There are no changes to review."};let A=_(B).files.map((W)=>W.path),H=await Z.getPullRequestHeadSha($);if(J.skipIfReviewed&&!jj(z,H))return j.info(`\uD83D\uDD0D PR #${$} already reviewed at ${H}`),{status:"Already reviewed at this commit."};let q=J.ai===void 0?s(Q,j):J.ai,M=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await i({files:A,root:process.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:j});if(M.skipped.length>0)j.info(`\u23ED\uFE0F Skipped ${M.skipped.length} analyzer(s): ${M.skipped.map((W)=>W.name).join(", ")}`);if(!q){if(M.findings.length===0)return{status:"No AI provider configured and static analysis found nothing to report."};let W=k({summary:"Static analysis only \u2014 no AI provider is configured.",walkthrough:[],findings:M.findings,effort:1,omittedFiles:[]},{headSha:H,requestChangesOn:Q.ai?.review?.requestChangesOn,suggestions:Z.capabilities().reviewSuggestions}),T={summary:"Static analysis only \u2014 no AI provider is configured.",walkthrough:[],findings:M.findings,effort:1,omittedFiles:[]};if(J.dryRun)return p(W,j),{status:`Would post ${M.findings.length} static-analysis finding(s).`,result:T};S(Z,"inlineReviewComments","createReview","posting a review");let R=await Z.createReview($,W);if(!R.posted)return{status:"The review could not be posted.",result:T};return await a(Z,$,x.body,W.state,z?.paused,j),{status:`Posted ${M.findings.length} static-analysis finding(s).${d(R,W,j)}`,result:T}}let V=x.base||Q.repository?.baseBranch||"main",G=(W,T)=>Z.getFileContent(W,T),[L,U]=await Promise.all([c(G,V,Q.ai?.review?.guidelineFiles,j),t(G,V,void 0,j)]),O=await h(q,{diff:B,profile:J.profile??Q.ai?.review?.profile,summaryOnly:J.summaryOnly??Q.ai?.review?.summaryOnly,instructions:f({global:Q.ai?.review?.instructions,guidelines:L}),learnings:o(n(U,A)),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,analyzerFindings:M.findings,seenFingerprints:J.full?[]:z?.fingerprints??[],logger:j}),F=k(O,{headSha:H,requestChangesOn:Q.ai?.review?.requestChangesOn,seenFingerprints:J.full?[]:z?.fingerprints??[],suggestions:Z.capabilities().reviewSuggestions});if(J.dryRun)return p(F,j),{status:`Would post ${O.findings.length} finding(s).`,result:O};S(Z,"inlineReviewComments","createReview","posting a review");let E=await Z.createReview($,F);if(!E.posted)return{status:"The review could not be posted.",result:O};return await a(Z,$,x.body,F.state,z?.paused,j),{status:O.findings.length===0?"Reviewed \u2014 nothing to report.":`Reviewed \u2014 ${O.findings.length} finding(s) posted.${d(E,F,j)}`,result:O}}function d(J,j,Q){let Z=j.comments.length-J.inlineComments;if(Z<=0)return"";return Q.warn(`\u26A0\uFE0F ${Z} of ${j.comments.length} inline comment(s) could not be placed on the diff`),` ${Z} of ${j.comments.length} inline comment(s) could not be placed on the diff.`}async function yj(J){return(await Vj(J)).status}function p(J,j){j.info(`
|
|
75
|
+
${J.body}
|
|
76
|
+
`);for(let Q of J.comments)j.info(`${Q.path}:${Q.line}
|
|
77
|
+
${Q.body}
|
|
78
|
+
`)}async function a(J,j,Q,Z,$,X){try{await J.updatePullRequest(j,{body:e(Q,{...Z,...$?{paused:!0}:{}})})}catch(x){X.warn(`Could not record review state on PR #${j}: ${x instanceof Error?x.message:String(x)}`)}}
|
|
79
|
+
export{C as nb,w as ob,I as pb,N as qb,v as rb,Jj as sb,h as tb,$j as ub,xj as vb,Xj as wb,zj as xb,c as yb,f as zb,Wj as Ab,k as Bb,Vj as Cb,yj as Db};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var{Glob:F}=globalThis.Bun;function K(k){if(!k||k.length===0)return{matches:()=>!0};let q=k.map((j)=>{let B=j.startsWith("!"),C=B?j.slice(1):j;return{negated:B,glob:new F(C),pattern:C}}),D=q.some((j)=>!j.negated);return{matches(j){let B=j.replace(/^\.\//,""),C=!D;for(let E of q){if(!H(E.glob,B))continue;C=!E.negated}return C}}}function L(k,q){if(!q?.length)return[];let D=k.replace(/^\.\//,"");return q.filter((j)=>H(new F(j.path),D)).sort((j,B)=>j.path.length-B.path.length).map((j)=>j.instructions)}function H(k,q){try{return k.match(q)}catch{return!1}}
|
|
3
|
-
export{K as
|
|
3
|
+
export{K as Jf,L as Kf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{oh as M}from"./chunk-193abzy6.js";import{zh as K}from"./chunk-e68nf7cm.js";import{Fh as J}from"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";function Q(j){let q=j.match(/github\.com\/([^/]+)\/([^/]+)\/(?:archive|releases\/download)\/(?:refs\/tags\/)?v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i);if(!q)return null;return{owner:q[1],repo:q[2].replace(/\.git$/,""),version:q[3],hasVPrefix:/\/v\d/.test(j)}}async function S(j,q){let y=J();try{let B={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"};if(q)B.Authorization=`Bearer ${q}`;let E=await K(`${M()}/repos/${j.owner}/${j.repo}/releases/latest`,{headers:B});if(!E.ok)return y.debug(`No latest release for ${j.owner}/${j.repo}: ${E.status}`),null;let F=await E.json();if(!F.tag_name)return null;let I=F.tag_name.replace(/^v/,"");return/^\d+\.\d+\.\d+/.test(I)?I:null}catch(B){return y.debug(`Failed to fetch latest Zig version for ${j.owner}/${j.repo}: ${B}`),null}}function X(j,q){return j.replace(/\/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i,(y)=>y.startsWith("/v")?`/v${q}`:`/${q}`)}async function Y(){try{return await Bun.spawn(["zig","version"],{stdout:"pipe",stderr:"pipe"}).exited===0}catch{return!1}}async function _(j){let q=J();try{let y=Bun.spawn(["zig","fetch",j],{stdout:"pipe",stderr:"pipe"}),[B,E]=await Promise.all([new Response(y.stdout).text(),y.exited]);if(E!==0){let I=await new Response(y.stderr).text();return q.warn(`\u26A0\uFE0F zig fetch failed for ${j}: ${I.trim()}`),null}let F=B.trim();return F.length>0?F:null}catch(y){return q.warn(`\u26A0\uFE0F Could not run zig fetch for ${j}: ${y}`),null}}export{X as zigUrlForVersion,Q as parseZigSource,Y as isZigAvailable,_ as fetchZigHash,S as fetchLatestZigVersion};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{A as V0,B as z0,C as EQ,a as N,b as X,c as R,r as dQ,s as $0,t as HQ,x as F,y as U,z as AQ}from"./chunk-sw2538r0.js";import"./chunk-q4t568hv.js";import*as O from"fs/promises";import*as XQ from"fs";import*as T from"path";import*as FQ from"child_process";import*as M0 from"crypto";import*as A0 from"readline";function S(V){if(V.inputSchema.type!=="object")throw Error(`JSON schema for tool "${V.name}" must be an object, but got ${V.inputSchema.type}`);return{type:"custom",name:V.name,input_schema:V.inputSchema,description:V.description,run:V.run,parse:(Q)=>Q,...V.close?{close:V.close}:{}}}import*as b from"fs/promises";import*as C from"path";import{randomUUID as L0}from"crypto";var e=493,T0=420;function YQ(V,Q){let $=C.relative(V,Q);return $===""||!$.startsWith(".."+C.sep)&&$!==".."&&!C.isAbsolute($)}async function OQ(V,Q){for(let $ of V)if(YQ(await r(C.resolve($)),Q))return $;return}var y0=40;function QQ(V){let Q=V?.code;return typeof Q==="string"?Q:void 0}async function r(V){let Q=[],$=V,z=0;for(;;){let K;try{K=await b.realpath($)}catch(Z){let q;try{q=(await b.lstat($)).isSymbolicLink()}catch(Y){let W=QQ(Y);if(W!=="ENOENT"&&W!=="ENOTDIR")throw Y;let J=C.dirname($);if(J===$)throw Y;Q.push(C.basename($)),$=J;continue}if(!q)throw Z;if(++z>y0)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});$=C.resolve(C.dirname($),await b.readlink($));continue}return Q.length?C.join(K,...Q.reverse()):K}}async function fQ(V,Q,$){let z=$?.allowedRoots??[],K=await r(C.resolve(V)),Z;try{Z=await r(C.resolve(K,Q))}catch(Y){throw new U(n(Y,`path ${JSON.stringify(Q)}`))}if(YQ(K,Z)||await OQ(z,Z)!==void 0)return Z;let q=z.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new U(`path ${JSON.stringify(Q)} is outside ${q}`)}async function RQ(V,Q){let $=C.dirname(V),z=C.join($,`.tmp-${process.pid}-${L0()}`),K;try{K=await b.open(z,"wx",T0),await K.writeFile(Q,"utf-8"),await K.sync(),await K.close(),K=void 0,await b.rename(z,V)}catch(Z){if(K)await K.close().catch(()=>{});throw await b.unlink(z).catch(()=>{}),Z}}function n(V,Q){let $=QQ(V);switch($){case"ENOENT":return`${Q}: no such file or directory`;case"EACCES":case"EPERM":return`${Q}: permission denied`;case"ENOTDIR":return`${Q}: not a directory`;case"EISDIR":return`${Q}: is a directory`;case"ELOOP":return`${Q}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${Q}: file name too long`;case"ENOSPC":return`${Q}: no space left on device`;case"EMFILE":case"ENFILE":return`${Q}: too many open files`;default:return`${Q}: ${$!==void 0?`i/o error (${$})`:"i/o error"}`}}import*as G from"fs/promises";import*as uQ from"fs";import*as w from"path";import{execFile as b0}from"child_process";import{promisify as x0}from"util";import{Readable as v0}from"stream";import{pipeline as P0}from"stream/promises";var E0=x0(b0);async function F0(V){let{client:Q,sessionId:$}=V;if(!Q)return async()=>{};let z=HQ(Q),K=V.session;if(!K){if($===void 0)return async()=>{};z.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),K=await Q.beta.sessions.retrieve($)}let Z=w.resolve(V.workdir,"skills"),q=[];for(let Y of K.agent.skills)try{let W=await Q.beta.skills.versions.retrieve(Y.version,{skill_id:Y.skill_id}),J=w.basename(W.name.trim());if(J===""||J==="."||J==="..")J=Y.skill_id;let H=w.resolve(Z,J);if(H!==Z&&!H.startsWith(Z+w.sep)){z.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:W.name});continue}let M=await Q.beta.skills.versions.download(W.id,{skill_id:Y.skill_id});await G.rm(H,{recursive:!0,force:!0}),await G.mkdir(H,{recursive:!0,mode:e}),q.push(H),await mQ(M,H),z.info("downloaded skill",{component:"agent-tool-context",skill_id:Y.skill_id,version:W.id,dest:H})}catch(W){z.warn("failed to download skill",{component:"agent-tool-context",skill_id:Y.skill_id,error:String(W)})}return async()=>{for(let Y of q)await G.rm(Y,{recursive:!0,force:!0}).catch((W)=>{z.warn("failed to clean up skill",{component:"agent-tool-context",dest:Y,error:String(W)})})}}function f0(V){for(let Q of V){let $=Q.trim();if(!$)continue;if(w.isAbsolute($)||$.split(/[\\/]/).includes(".."))throw new R(`refusing to extract unsafe archive member: ${$}`)}}var LQ="skill archive listing is inconsistent; refusing to extract",g0={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function gQ(V){let Q=V.split(`
|
|
3
|
+
`);if(Q[Q.length-1]==="")Q.pop();return Q}function u0(V,Q){return/^[\x20-\x7E]+$/.test(Q)&&!/[\\^#]/.test(Q)&&!(V==="unzip"&&Q.startsWith("-"))}function S0(V,Q,$){let z=gQ(Q),K=gQ($);if(z.length!==K.length)throw new R(LQ);let Z=[],q=[];return z.forEach((Y,W)=>{if(g0[V].has(K[W].charAt(0))){Z.push(Y);return}if(!u0(V,Y))throw new R(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(Y)}`);q.push(Y)}),{plain:Z,special:q}}async function SQ(V){for(let Q of await G.readdir(V,{withFileTypes:!0}))if(Q.isDirectory())await SQ(w.join(V,Q.name));else if(!Q.isFile())throw new R(LQ)}async function jQ(V,Q){try{let{stdout:$}=await E0(V,Q);return $}catch($){if(QQ($)==="ENOENT")throw new R(`skill extraction requires the \`${V}\` command, but it was not found on PATH`);throw $}}function m0(V){let Q,$=!1;for(let z of V){let K=z.trim().split("/").filter((q)=>q!==""&&q!==".");if(K.length===0)continue;let Z=K[0];if(Q===void 0)Q=Z;else if(Z!==Q)return"";if(K.length>1)$=!0}return Q!==void 0&&$?Q:""}async function mQ(V,Q){let $=w.join(Q,`.skill-archive-${process.pid}-${Date.now()}`);if(!V.body)throw new R("skill download response had no body");await P0(v0.fromWeb(V.body),uQ.createWriteStream($));let z=w.join(w.dirname(Q),`.skill-stage-${process.pid}-${Date.now()}`),K=w.join(w.dirname(Q),`.skill-exclude-${process.pid}-${Date.now()}`);try{let Z=await _0($,4),q=Z.length>=4&&Z[0]===80&&Z[1]===75&&Z[2]===3&&Z[3]===4,Y=q?"unzip":"tar",W=await jQ(Y,q?["-Z1",$]:["-tf",$]),J=await jQ(Y,q?["-Z","--h","--t",$]:["-tvf",$]),{plain:H,special:M}=S0(Y,W,J);f0([...H,...M]);let j=m0(H);if(await G.mkdir(z,{recursive:!0,mode:e}),H.length>0)await jQ(Y,await p0(Y,$,z,M,K));await SQ(z);let v=j?w.join(z,j):z,P=await G.readdir(v).catch((E)=>{throw QQ(E)==="ENOENT"?new R(LQ):E});for(let E of P)await G.rename(w.join(v,E),w.join(Q,E))}finally{await G.rm($,{force:!0}),await G.rm(K,{force:!0}),await G.rm(z,{recursive:!0,force:!0})}}async function p0(V,Q,$,z,K){let Z=z.map((q)=>q.replace(/[*?[\\]/g,"\\$&"));if(V==="unzip")return["-oq",Q,"-d",$,...Z.length>0?["-x",...Z]:[]];if(Z.length===0)return["-xf",Q,"-C",$];return await G.writeFile(K,Z.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{flag:"wx",mode:384}),["-xf",Q,"-C",$,"-X",K]}async function _0(V,Q){let $=await G.open(V,"r");try{let z=Buffer.alloc(Q),{bytesRead:K}=await $.read(z,0,Q,0);return z.subarray(0,K)}finally{await $.close()}}import*as q0 from"path";import{createHash as V1}from"crypto";import*as A from"fs/promises";import*as k from"path";import{constants as i}from"fs";import{createHash as h0,randomBytes as d0}from"crypto";var cQ=448,c0=384,n0=448,TQ=i.O_NOFOLLOW??0,i0=i.O_NONBLOCK??0;class D extends Error{constructor(V,Q){super(`path ${JSON.stringify(Q)} ${V}`);this.name="FileStoreError",this.reason=V,this.relPath=Q}}D.ESCAPES_ROOT="escapes the store root";D.IS_A_SYMLINK="is a symlink";D.NOT_A_FILE="is not a regular file";D.NOT_A_DIRECTORY="is not a directory";D.NOT_UTF8="is not valid utf-8";D.MOVE_DESTINATION_EXISTS="already exists";function yQ(V){return V.startsWith("/")&&!V.split("/").includes("..")}class l{constructor(V,Q,$=!1){this.hashes=new Map,this.rootPath=V,this.removedOnDispose=Q,this.decoder=$?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(V,Q){if(!l0())throw Error("FileStore requires O_NOFOLLOW support on this platform");let $=!1;try{await A.lstat(V)}catch(z){if(z.code!=="ENOENT")throw z;$=!0}return new l(k.resolve(V),$,Q?.utf8??!1)}async createRoot(){await a0(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await A.rm(this.rootPath,{recursive:!0,force:!0})}async put(V,Q,$){let z=V.replace(/\\/g,"/");if(z.endsWith("/")||z.endsWith("/.")||z===""||z===".")throw new D(D.NOT_A_FILE,V);let K=this.resolveUnderRoot(V),Z=typeof Q==="string"?dQ(Q):Q;this.requireUtf8(V,Z),await pQ(this.rootPath,k.dirname(K)),await o0(K,Z,$?.executable??!1)}async get(V){let Q=this.resolveUnderRoot(V),$;try{$=await nQ(V,Q)}catch(K){if(K.code==="ENOENT")return null;throw K}let z;try{let K=await $.readFile();z=new Uint8Array(K.buffer,K.byteOffset,K.byteLength)}finally{await $.close()}return this.requireUtf8(V,z),z}async ls(V="/"){let Q=this.resolveUnderRoot(V);return new Set((await _Q(this.rootPath,V,Q)).map(([$])=>$))}async findSymlinks(V="/"){let Q=this.resolveUnderRoot(V);return t0(this.rootPath,V,Q)}async hashtree(V="/"){let Q=this.resolveUnderRoot(V),$=JQ.nowNs(),z=Object.create(null);for(let[K,Z]of await _Q(this.rootPath,V,Q)){let q=await this.hashViaCache(K,Z,$);if(q!==null)z[K]=q}return z}async hashFile(V){let Q=this.resolveUnderRoot(V),$;try{$=await A.lstat(Q,{bigint:!0})}catch(K){if(K.code==="ENOENT")return null;throw K}if($.isSymbolicLink())throw new D(D.IS_A_SYMLINK,V);if(!$.isFile())throw new D(D.NOT_A_FILE,V);let z=k.relative(this.rootPath,Q).split(k.sep).join("/");return this.hashViaCache(z,Q,JQ.nowNs())}async move(V,Q){let $=this.resolveUnderRoot(V),z=this.resolveUnderRoot(Q);if($===this.rootPath||z===this.rootPath)return;if(await A.stat(z).then(()=>!0,()=>!1))throw new D(D.MOVE_DESTINATION_EXISTS,Q);await pQ(this.rootPath,k.dirname(z)),await A.rename($,z)}async remove(V){let Q=this.resolveUnderRoot(V);if(Q===this.rootPath)return;let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){if(z.code==="ENOENT")return;throw z}if($.isDirectory())await A.rm(Q,{recursive:!0,force:!0});else try{await A.unlink(Q)}catch(z){if(z.code!=="ENOENT")throw z}}resolveUnderRoot(V){let Q=V.replace(/\\/g,"/").replace(/^\/+/,""),$=Q.split("/").filter((z)=>z!==""&&z!==".");if(k.posix.isAbsolute(Q)||$.includes(".."))throw new D(D.ESCAPES_ROOT,V);return $.length===0?this.rootPath:k.join(this.rootPath,...$)}requireUtf8(V,Q){if(!this.decoder)return;try{this.decoder.decode(Q)}catch{throw new D(D.NOT_UTF8,V)}}async hashViaCache(V,Q,$){let z;try{z=await A.lstat(Q,{bigint:!0})}catch(q){if(q.code==="ENOENT")return null;throw q}if(!z.isFile())return null;let K=this.hashes.get(V),Z;if(K!==void 0&&e0(K,z))Z=K.sha;else try{Z=await JQ.hashFile(Q)}catch(q){let Y=q.code;if(Y==="ENOENT"||q instanceof D)return null;if(Y==="ELOOP"||Y==="EMLINK")return null;throw q}if(Q1(z,$))this.hashes.set(V,{mtimeNs:z.mtimeNs,ctimeNs:z.ctimeNs,size:z.size,sha:Z});return Z}}l.isPathLegal=yQ;function l0(){return TQ!==0}async function a0(V){let Q=[],$=V;for(;;){try{await A.stat($);break}catch(K){let Z=K.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR"&&Z!=="ELOOP")throw K}Q.push($);let z=k.dirname($);if(z===$)break;$=z}for(let z of Q.reverse())try{await A.mkdir(z,{mode:cQ})}catch(K){if(K.code!=="EEXIST")throw K}}async function pQ(V,Q){let $=k.relative(V,Q);if($==="")return;let z=V;for(let K of $.split(k.sep)){z=k.join(z,K);try{await A.mkdir(z,{mode:cQ})}catch(Z){if(Z.code!=="EEXIST")throw Z}}}async function o0(V,Q,$){let z=$?n0:c0,K=k.join(k.dirname(V),`.fs-${d0(8).toString("hex")}.tmp`),Z;try{Z=await A.open(K,i.O_WRONLY|i.O_CREAT|i.O_EXCL|TQ,z),await Z.writeFile(Q),await Z.close(),Z=void 0,await A.rename(K,V)}catch(q){if(Z)await Z.close().catch(()=>{});throw await A.unlink(K).catch(()=>{}),q}}async function nQ(V,Q){let $;try{$=await A.open(Q,i.O_RDONLY|TQ|i0)}catch(z){let K=z.code;if(K==="ELOOP"||K==="EMLINK")throw new D(D.IS_A_SYMLINK,V);throw z}try{if(!(await $.stat()).isFile())throw new D(D.NOT_A_FILE,V)}catch(z){throw await $.close().catch(()=>{}),z}return $}async function s0(V){let Q=h0("sha256"),$=await nQ(k.basename(V),V),z=new Uint8Array(1048576);try{for(;;){let{bytesRead:K}=await $.read(z,0,z.length);if(K===0)break;Q.update(z.subarray(0,K))}}finally{await $.close()}return Q.digest("hex")}async function _Q(V,Q,$){if(!await r0(Q,$))return[];let z=[];return await iQ($,(K,Z)=>{if(Z.isFile())z.push([k.relative(V,K).split(k.sep).join("/"),K])}),z.sort(),z}async function t0(V,Q,$){let z=(q)=>k.relative(V,q).split(k.sep).join("/"),K;try{K=await A.lstat($,{bigint:!0})}catch(q){let Y=q.code;if(Y==="ENOENT"||Y==="ENOTDIR")return new Set;throw q}if(K.isSymbolicLink())return new Set([z($)]);if(!K.isDirectory())throw new D(D.NOT_A_DIRECTORY,Q);let Z=new Set;return await iQ($,(q,Y)=>{if(Y.isSymbolicLink())Z.add(z(q))}),Z}async function r0(V,Q){let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){let K=z.code;if(K==="ENOENT"||K==="ENOTDIR")return!1;throw z}if(!$.isDirectory())throw new D(D.NOT_A_DIRECTORY,V);return!0}async function iQ(V,Q){let $=[V];while($.length){let z=$.pop(),K;try{K=await A.readdir(z,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")continue;throw Z}for(let Z of K){let q=k.join(z,Z.name);if(Q(q,Z),Z.isDirectory()&&!Z.isSymbolicLink())$.push(q)}}}function e0(V,Q){return Q.mtimeNs===V.mtimeNs&&Q.ctimeNs===V.ctimeNs&&Q.size===V.size}function Q1(V,Q){return(V.mtimeNs>V.ctimeNs?V.mtimeNs:V.ctimeNs)<Q-JQ.timestampTrustMarginNs}var $1=2000000000n,JQ={hashFile:s0,timestampTrustMarginNs:$1,nowNs:()=>BigInt(Date.now())*1000000n},lQ=l,hQ=Symbol.asyncDispose;if(hQ)Object.defineProperty(l.prototype,hQ,{value:l.prototype.dispose,configurable:!0,writable:!0});var I,g,BQ,$Q,MQ,B,a,DQ,f,K0,NQ,Z0,X0,bQ,vQ,aQ,oQ,xQ,sQ,tQ,WQ,UQ,rQ,eQ,z1=30000,o=".anthropic-memory-store",Y0=1;function Q0(V){return V1("sha256").update(`version ${Y0}
|
|
6
|
+
${V}`,"utf-8").digest("hex")}var K1=30000,Z1=100,X1=20,q1=16,Y1=32,H1=8,J1=50;class m extends R{constructor(V,Q){super(V);if(this.name="SessionMemoryError",Q!==void 0)this.cause=Q}}class H0{constructor(V,Q,$){this.mode=V,this.cap=Q,this.waiveWindow=$,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}class J0{constructor(V,Q){I.add(this),g.set(this,void 0),BQ.set(this,void 0),$Q.set(this,void 0),MQ.set(this,void 0),B.set(this,void 0),a.set(this,void 0),DQ.set(this,!1),f.set(this,[]),N(this,g,V,"f"),N(this,BQ,Q.workdir,"f"),N(this,$Q,Q.syncIntervalMs??AQ,"f"),z0(X(this,$Q,"f"),"syncIntervalMs"),N(this,MQ,Q.syncDeletions??"enabled","f"),N(this,B,HQ(V),"f"),N(this,a,Date.now(),"f")}get roots(){return X(this,f,"f").map((V)=>V.files.root().path)}get readOnlyRoots(){return X(this,f,"f").filter((V)=>V.readOnly).map((V)=>V.files.root().path)}async download(V){for(let Q of V.resources){if(Q.type!=="memory_store")continue;let $=X(this,I,"m",K0).call(this,Q),z;try{if(z={memoryStoreId:Q.memory_store_id,files:await lQ.open($,{utf8:!0}),readOnly:Q.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!z.files.root().removedOnDispose)throw new m(`something already exists at the memory store's path: ${$} (memory_store_id=${Q.memory_store_id}); it must not exist when the session starts`);try{await z.files.createRoot()}catch(K){if(!s(K))throw K;throw new m(`cannot create the memory store's folder: ${$} (memory_store_id=${Q.memory_store_id}): ${K}; the worker host must make this mount path writable`,K)}await X(this,I,"m",vQ).call(this,z),X(this,B,"f").info("downloaded memories",{count:z.baseline.size,memory_store_id:z.memoryStoreId,dest:z.files.root().path}),X(this,f,"f").push(z)}catch(K){if(z)await z.files.dispose().catch(()=>{});if(K instanceof m)throw K;throw new m(`failed to download memory store memory_store_id=${Q.memory_store_id}: ${K}`,K)}}N(this,a,Date.now(),"f")}async finish(){if(X(this,DQ,"f"))throw new R("finish() was already called: it is the session's last sync and runs once");N(this,DQ,!0,"f"),await this.syncAll(!0)}async syncAll(V){await Promise.all(X(this,f,"f").map((Q)=>X(this,I,"m",Z0).call(this,Q,V))),N(this,a,Date.now(),"f")}async syncIfDue(){if(Date.now()-X(this,a,"f")<X(this,$Q,"f"))return;await this.syncAll(!1)}async flushWrites(V){await Promise.all(X(this,f,"f").map((Q)=>X(this,I,"m",X0).call(this,Q,V)))}async dispose(){for(let V of X(this,f,"f")){let Q=V.files.root();try{let $=await X(this,I,"m",NQ).call(this,V);if(!$.markerOk&&Object.keys($.files).length>0){X(this,B,"f").warn(`${$.distrustReason}; leaving the memory store folder on disk`,{root:Q.path,memory_store_id:V.memoryStoreId});continue}await V.files.dispose()}catch($){if(!($ instanceof D)&&!s($))throw $;X(this,B,"f").warn("failed to remove the memory store folder",{root:V.files.root().path,memory_store_id:V.memoryStoreId,error:String($)});continue}if(Q.removedOnDispose)X(this,B,"f").info("removed memory store dir",{dest:Q.path,memory_store_id:V.memoryStoreId})}}}g=new WeakMap,BQ=new WeakMap,$Q=new WeakMap,MQ=new WeakMap,B=new WeakMap,a=new WeakMap,DQ=new WeakMap,f=new WeakMap,I=new WeakSet,K0=function(Q){if(Q.mount_path){if(!yQ(Q.mount_path))throw new m(`memory store mount_path is not a clean absolute path: ${JSON.stringify(Q.mount_path)} (memory_store_id=${Q.memory_store_id})`);return Q.mount_path}return q0.join(X(this,BQ,"f"),"memory",Q.name||Q.memory_store_id)},NQ=async function(Q){let $=await Q.files.hashtree(),z=$[o];if(delete $[o],z===Q0(Q.memoryStoreId))return{files:$,markerOk:!0,distrustReason:null};return{files:$,markerOk:!1,distrustReason:z!==void 0?"the marker file does not match this store":"the marker file is gone"}},Z0=async function(Q,$){try{let z=await X(this,I,"m",NQ).call(this,Q),K=z.files;if(!z.markerOk){if(Object.keys(K).length>0){X(this,B,"f").warn(`${z.distrustReason}; leaving the memory store folder as found and not syncing`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId});return}await X(this,I,"m",bQ).call(this,Q,"the folder or its marker is gone");return}if(Object.keys(K).length===0&&Q.baseline.size>1){await X(this,I,"m",bQ).call(this,Q,"every memory file is gone at once");return}let Z=new Map;for await(let[H,M]of X(this,I,"m",WQ).call(this,Q.memoryStoreId))Z.set(H,M);let q=new H0(X(this,MQ,"f"),Math.max(H1,Math.min(J1,Math.floor(Q.baseline.size/4))),$),Y=[],W=new Map,J=[...new Set([...Z.keys(),...Object.keys(K),...Q.baseline.keys()])].sort();for(let H of J){let M=Z.get(H),j=K[H],v=Q.baseline.get(H),P;if(j===void 0&&v!==void 0&&M!==void 0&&M.content_sha256===v&&!Q.readOnly)P=await X(this,I,"m",rQ).call(this,Q,H,M,v,q);else P=await X(this,I,"m",aQ).call(this,Q,H,M,j,Y);if(P!==void 0)W.set(H,P)}if(Q.baseline=W,await X(this,I,"m",sQ).call(this,Q,Y),q.suppressed>0)X(this,B,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:q.suppressed,memory_store_id:Q.memoryStoreId});if(q.capped>0)X(this,B,"f").warn(`delete cap reached: ${q.mode==="log_only"?"would send":"sent"} ${q.attempted} deletes, held ${q.capped} for later syncs`,{memory_store_id:Q.memoryStoreId})}catch(z){X(this,B,"f").warn("memory sync failed",{memory_store_id:Q.memoryStoreId,error:String(z)})}},X0=async function(Q,$){let z=new Map,K=new Set,Z=async()=>{if(Q.readOnly)return;let q=await X(this,I,"m",NQ).call(this,Q);if(!q.markerOk){X(this,B,"f").warn(`${q.distrustReason}; not uploading anything from the memory store folder`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId});return}for(let[J,H]of Object.entries(q.files))if(H!==Q.baseline.get(J)&&Q.refusedShas.get(J)!==H)z.set(J,H),K.add(J);if(z.size===0||$?.aborted)return;let Y=new Map;for await(let[J,H]of X(this,I,"m",WQ).call(this,Q.memoryStoreId)){if($?.aborted)return;Y.set(J,H)}let W=[];for(let J of[...z.keys()].sort()){let H=z.get(J),M=Q.baseline.get(J),j=Y.get(J);if(j!==void 0&&j.content_sha256===H){Q.baseline.set(J,j.content_sha256),K.delete(J);continue}if(j!==void 0&&j.content_sha256!==M){X(this,B,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:J,memory_store_id:Q.memoryStoreId}),K.delete(J);continue}W.push([J,H,j])}await X(this,I,"m",tQ).call(this,Q,W,K,$)};try{if(await W1(Z(),$),$?.aborted&&K.size>0)X(this,B,"f").warn(`memory flush cut off part-way; ${K.size} of ${z.size} changed files had not finished uploading`,{memory_store_id:Q.memoryStoreId})}catch(q){X(this,B,"f").warn("memory flush failed",{memory_store_id:Q.memoryStoreId,error:String(q)})}},bQ=async function(Q,$){X(this,B,"f").warn(`${$}; re-downloading the memory store folder instead of syncing`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId}),await Q.files.createRoot(),await X(this,I,"m",vQ).call(this,Q)},vQ=async function(Q){Q.baseline=new Map,Q.pendingDeletes.clear(),await Q.files.put(o,`version ${Y0}
|
|
7
|
+
${Q.memoryStoreId}`);for await(let[$,z]of X(this,I,"m",WQ).call(this,Q.memoryStoreId,"full"))if(await X(this,I,"m",xQ).call(this,Q,$,z.content??""))Q.baseline.set($,z.content_sha256)},aQ=async function(Q,$,z,K,Z){let q=Q.baseline.get($);if(K!==void 0)Q.pendingDeletes.delete($);if(!z){if(K===void 0){Q.pendingDeletes.delete($);return}if(q!==void 0){if(K===q){let M=await X(this,I,"m",oQ).call(this,Q,$,q);if(M===void 0)return;if(M===q)return q;K=M}if(Q.readOnly)X(this,B,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:$,memory_store_id:Q.memoryStoreId});else if(Q.refusedShas.get($)!==K)X(this,B,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:$,memory_store_id:Q.memoryStoreId})}if(Q.readOnly)return;if(Q.refusedShas.get($)===K)return;return await X(this,I,"m",UQ).call(this,Q,$,K,void 0)}let Y=z.content_sha256,W=Y!==q,J=K!==void 0&&K!==q&&K!==Y,H=!Q.readOnly&&J;if(K===void 0&&q!==void 0){if(W)X(this,B,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:$,memory_store_id:Q.memoryStoreId}),Q.pendingDeletes.delete($),Z.push([$,z]);return q}if(W){if(K===Y)return Y;if(J)X(this,B,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:$,memory_store_id:Q.memoryStoreId});return Z.push([$,z]),q}if(H){if(Q.refusedShas.get($)===K)return Y;return await X(this,I,"m",UQ).call(this,Q,$,K,z)??Y}return Y},oQ=async function(Q,$,z){let K;try{K=await Q.files.hashFile($)}catch(Z){if(!(Z instanceof D)&&!s(Z))throw Z;return z}if(K===null)return;if(K!==z)return K;try{await Q.files.remove($)}catch(Z){if(!(Z instanceof D)&&!s(Z))throw Z;return X(this,B,"f").warn("failed to remove memory deleted remotely",{path:$,memory_store_id:Q.memoryStoreId,error:String(Z)}),z}return},xQ=async function(Q,$,z){try{await Q.files.put($,z)}catch(K){if(!(K instanceof D)&&!s(K))throw K;return X(this,B,"f").warn("failed to write memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(K)}),!1}return!0},sQ=async function(Q,$){if($.length===0)return;let z=async(q,Y)=>{let W;try{W=await X(this,g,"f").beta.memoryStores.memories.retrieve(Y.id,{memory_store_id:Q.memoryStoreId,view:"full"})}catch(J){if(F(J,404))return;X(this,B,"f").warn("failed to fetch memory content",{path:q,memory_store_id:Q.memoryStoreId,error:String(J)});return}if(await X(this,I,"m",xQ).call(this,Q,q,W.content??""))Q.baseline.set(q,W.content_sha256)},K=$[Symbol.iterator](),Z=async()=>{for(let[q,Y]of K)await z(q,Y)};await Promise.all(Array.from({length:Math.min(q1,$.length)},Z))},tQ=async function(Q,$,z,K){let Z=$[Symbol.iterator](),q=async()=>{for(let[Y,W,J]of Z){if(K?.aborted)return;let H=await X(this,I,"m",UQ).call(this,Q,Y,W,J);if(z.delete(Y),H!==void 0)Q.baseline.set(Y,H)}};await Promise.all(Array.from({length:Math.min(Y1,$.length)},q))},WQ=async function*(Q,$="basic"){let z=$==="basic"?Z1:X1;for await(let K of X(this,g,"f").beta.memoryStores.memories.list(Q,{view:$,limit:z})){if(K.type!=="memory")continue;let Z=K.path.replace(/^\/+/,"");if(Z===o){X(this,B,"f").warn("the server listed the reserved marker path; skipping",{path:K.path,memory_store_id:Q});continue}yield[Z,K]}},UQ=async function V(Q,$,z,K){try{let Z=await Q.files.get($);if(Z===null)return;let q=$0(Z),Y=K?await X(this,g,"f").beta.memoryStores.memories.update(K.id,{memory_store_id:Q.memoryStoreId,content:q,precondition:{type:"content_sha256",content_sha256:K.content_sha256}}):await X(this,g,"f").beta.memoryStores.memories.create(Q.memoryStoreId,{path:"/"+$,content:q});return Q.refusedShas.delete($),Y.content_sha256}catch(Z){if(K&&F(Z,404))return await X(this,I,"m",V).call(this,Q,$,z,void 0);let q=Z instanceof D||F(Z,400)||F(Z,413);if(K&&F(Z,409))X(this,B,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:$,memory_store_id:Q.memoryStoreId});else if(q&&z!==void 0)Q.refusedShas.set($,z),X(this,B,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:$,memory_store_id:Q.memoryStoreId,rejection:String(Z)});else X(this,B,"f").warn("failed to upload memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(Z)});return}},rQ=async function(Q,$,z,K,Z){if(Z.mode==="disabled")return Z.suppressed++,K;let q=Q.pendingDeletes.get($);if(q===void 0)q=Date.now(),Q.pendingDeletes.set($,q);if(!Z.waiveWindow&&Date.now()-q<K1)return K;let Y,W;try{Y=await Q.files.hashFile(o)===Q0(Q.memoryStoreId),W=await Q.files.hashFile($)===null}catch(H){if(!(H instanceof D)&&!s(H))throw H;Y=W=!1}if(!Y)return K;if(!W)return Q.pendingDeletes.delete($),K;if(!Z.takeSlot())return K;if(Z.mode==="log_only")return X(this,B,"f").info("log-only: sync would delete this memory on the server",{path:$,memory_store_id:Q.memoryStoreId}),K;let J=await X(this,I,"m",eQ).call(this,Q,$,z,K);if(J===void 0)Q.pendingDeletes.delete($);return J},eQ=async function(Q,$,z,K){try{await X(this,g,"f").beta.memoryStores.memories.delete(z.id,{memory_store_id:Q.memoryStoreId,expected_content_sha256:K})}catch(Z){if(F(Z,404))return;if(F(Z,409)||F(Z,412))X(this,B,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:$,memory_store_id:Q.memoryStoreId});else X(this,B,"f").warn("failed to delete memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(Z)});return K}X(this,B,"f").info("propagated local deletion",{path:$,memory_store_id:Q.memoryStoreId});return};function s(V){return typeof V==="object"&&V!==null&&typeof V.code==="string"}async function W1(V,Q){if(!Q){await V;return}let $,z=new Promise((K)=>{if($=K,Q.aborted)K()});Q.addEventListener("abort",$,{once:!0});try{await Promise.race([V,z])}finally{Q.removeEventListener("abort",$)}}var IQ,L,y,VQ,p,x,PQ,kQ,zQ,CQ,wQ,h,d,t,_,KQ,u,B0,W0,U0=102400,I0=120000,U1=262144,D1=65536,D0=Buffer.from(`
|
|
8
|
+
`),ZQ=102400,N1=2000,B1=200;class k0 extends R{constructor(V){super(`bash command timed out after ${V}ms`);this.name="BashTimeoutError",this.timeoutMs=V}}var M1=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,A1=O.glob;function C0(V){return V===void 0?U1:V}function c(V){if(V===void 0)return;throw new R("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function M2(V){return[k1(V),C1(V),G1(V),O1(V),j1(V),L1(V)]}async function qQ(V,Q){return c(V.unrestrictedPaths),fQ(V.workdir,Q,{allowedRoots:V.allowedRoots??[]})}function w0(V,Q){return OQ(V.readOnlyRoots??[],Q)}function I1(){let V={};for(let[Q,$]of Object.entries(process.env)){if(Q.startsWith("ANTHROPIC_"))continue;V[Q]=$}return V}class G0{constructor(V,Q=I1()){IQ.add(this),L.set(this,void 0),y.set(this,""),VQ.set(this,!1),p.set(this,!1),x.set(this,null),N(this,L,FQ.spawn("/bin/bash",["--noprofile","--norc"],{cwd:V,env:{...Q,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),X(this,L,"f").stdout.setEncoding("utf8"),X(this,L,"f").stderr.setEncoding("utf8"),X(this,L,"f").stdout.on("data",($)=>X(this,IQ,"m",PQ).call(this,$)),X(this,L,"f").stderr.on("data",($)=>X(this,IQ,"m",PQ).call(this,$)),X(this,L,"f").once("close",()=>{N(this,p,!0,"f");let $=X(this,x,"f");N(this,x,null,"f"),$?.resolve()})}get closed(){return X(this,p,"f")}async exec(V,Q={}){if(X(this,p,"f"))throw new R("bash session terminated");let $=Q.timeoutMs??I0,z=Q.signal;z?.throwIfAborted(),N(this,y,"","f"),N(this,VQ,!1,"f");let K=`__ANT_CMD_${M0.randomUUID()}_DONE__`,Z=`${K.slice(0,8)}''${K.slice(8)}`,q=`{ ${V}
|
|
9
|
+
} </dev/null 2>&1; printf '\\n${Z}%d\\n' $?
|
|
10
|
+
`;if(X(this,L,"f").stdin.write(q),X(this,y,"f").indexOf(K)<0){let{promise:j,resolve:v}=EQ();N(this,x,{sentinel:K,resolve:v},"f");let P,E;try{await Promise.race([j,new Promise((j0,GQ)=>{P=setTimeout(()=>GQ(new k0($)),$)}),new Promise((j0,GQ)=>{if(!z)return;E=()=>GQ(z.reason),z.addEventListener("abort",E,{once:!0})})])}finally{if(P)clearTimeout(P);if(E&&z)z.removeEventListener("abort",E);N(this,x,null,"f")}}let Y=X(this,y,"f").indexOf(K);if(Y<0)throw new R("bash session terminated");let J=X(this,y,"f").slice(Y+K.length).match(/^(-?\d+)/),H=J?parseInt(J[1],10):-1,M=X(this,y,"f").slice(0,Y).replace(M1,"").replace(/\n+$/,"");if(X(this,VQ,"f"))M=`[output truncated]
|
|
11
|
+
${M}`;return{output:M,exitCode:H}}close(){if(X(this,p,"f"))return;N(this,p,!0,"f");let V=X(this,x,"f");N(this,x,null,"f"),V?.resolve(),X(this,L,"f").stdout.destroy(),X(this,L,"f").stderr.destroy(),X(this,L,"f").stdin.destroy();try{process.kill(-X(this,L,"f").pid,"SIGKILL")}catch{X(this,L,"f").kill("SIGKILL")}X(this,L,"f").unref()}}L=new WeakMap,y=new WeakMap,VQ=new WeakMap,p=new WeakMap,x=new WeakMap,IQ=new WeakSet,PQ=function(Q){if(N(this,y,X(this,y,"f")+Q,"f"),X(this,y,"f").length>U0)N(this,y,X(this,y,"f").slice(X(this,y,"f").length-U0),"f"),N(this,VQ,!0,"f");if(X(this,x,"f")&&X(this,y,"f").indexOf(X(this,x,"f").sentinel)>=0){let $=X(this,x,"f");N(this,x,null,"f"),$.resolve()}};function k1(V){c(V.unrestrictedPaths);let Q,$=Promise.resolve();return S({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:z,restart:K,timeout_ms:Z},q)=>{let Y=$,W=EQ();$=W.promise;try{await Y}catch{}try{if(K)Q?.close(),Q=void 0;if(!z){if(K)return"bash session restarted";throw new U("bash: command is required")}Q??(Q=new G0(V.workdir,V.env));try{let{output:J,exitCode:H}=await Q.exec(z,{timeoutMs:Z??I0,signal:q?.signal});if(H!==0)throw new U(J||`exit ${H}`);return J}catch(J){if(J instanceof U)throw J;throw Q.close(),Q=void 0,new U(`bash: ${J instanceof Error?J.message:String(J)}`)}}finally{W.resolve()}},close:()=>{Q?.close(),Q=void 0}})}function C1(V){return c(V.unrestrictedPaths),S({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:Q,view_range:$})=>{if(!Q)throw new U("read: file_path is required");let z=await qQ(V,Q);if($?.length&&$.length!==2)throw new U("read: view_range must be [start_line, end_line]");let K;try{let H=await O.stat(z);if(!H.isFile())throw new U(`read: ${Q} is not a regular file`);let M=C0(V.maxFileBytes);if(M!==null&&H.size>M){if(!$?.length)throw new U(`read: ${Q} is ${H.size} bytes, exceeds ${M}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[j,v]=$;return await w1(z,Q,j,v,M)}K=await O.readFile(z,"utf8")}catch(H){if(H instanceof U)throw H;throw new U(`read: ${n(H,Q)}`)}if(!$?.length)return K;let[Z,q]=$,Y=K.split(`
|
|
12
|
+
`),W=Math.max(0,Z-1),J=q>0?q:Y.length;return Y.slice(W,J).join(`
|
|
13
|
+
`)}})}async function w1(V,Q,$,z,K){let Z=new O0(Q,$,z,K);if(Z.rangeIsEmpty())return"";let q=XQ.createReadStream(V,{highWaterMark:D1});try{for await(let Y of q)if(Z.collectFrom(Y),Z.rangeIsCollected())break}finally{q.destroy()}return Z.text()}class O0{constructor(V,Q,$,z){kQ.add(this),zQ.set(this,void 0),CQ.set(this,void 0),wQ.set(this,void 0),h.set(this,void 0),d.set(this,void 0),t.set(this,void 0),_.set(this,0),KQ.set(this,[]),u.set(this,0),N(this,zQ,V,"f"),N(this,CQ,Q,"f"),N(this,wQ,$,"f"),N(this,h,Math.max(0,Q-1),"f"),N(this,d,$>0?$:1/0,"f"),N(this,t,z,"f")}rangeIsEmpty(){return X(this,d,"f")<=X(this,h,"f")}rangeIsCollected(){return X(this,_,"f")>=X(this,d,"f")}collectFrom(V){var Q;let $=0;while($<V.length&&!this.rangeIsCollected()){let z=V.indexOf(10,$),K=z<0?V.length:z;if(X(this,_,"f")>=X(this,h,"f"))X(this,kQ,"m",B0).call(this,V.subarray($,K),z>=0);if(z<0)break;N(this,_,(Q=X(this,_,"f"),Q++,Q),"f"),$=z+1}}text(){return Buffer.concat(X(this,KQ,"f"),X(this,u,"f")).toString("utf8")}}zQ=new WeakMap,CQ=new WeakMap,wQ=new WeakMap,h=new WeakMap,d=new WeakMap,t=new WeakMap,_=new WeakMap,KQ=new WeakMap,u=new WeakMap,kQ=new WeakSet,B0=function(Q,$){if(X(this,KQ,"f").push(Q),N(this,u,X(this,u,"f")+Q.length,"f"),$&&X(this,_,"f")+1<X(this,d,"f"))X(this,KQ,"f").push(D0),N(this,u,X(this,u,"f")+D0.length,"f");if(X(this,u,"f")>X(this,t,"f"))throw X(this,kQ,"m",W0).call(this)},W0=function(){if(X(this,d,"f")-X(this,h,"f")===1)return new U(`read: line ${X(this,h,"f")+1} of ${X(this,zQ,"f")} alone exceeds ${X(this,t,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new U(`read: view_range [${X(this,CQ,"f")}, ${X(this,wQ,"f")}] of ${X(this,zQ,"f")} exceeds ${X(this,t,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)};function G1(V){return c(V.unrestrictedPaths),S({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:Q,content:$})=>{if(!Q)throw new U("write: file_path is required");let z=await qQ(V,Q),K=await w0(V,z);if(K!==void 0)throw new U(`write: ${Q} is inside read-only directory ${K}`);try{await O.mkdir(T.dirname(z),{recursive:!0,mode:e}),await RQ(z,$??"")}catch(Z){throw new U(`write: ${n(Z,Q)}`)}return`wrote ${Buffer.byteLength($??"")} bytes to ${Q}`}})}function O1(V){return c(V.unrestrictedPaths),S({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:Q,old_string:$,new_string:z,replace_all:K})=>{if(!Q)throw new U("edit: file_path is required");if(!$)throw new U("edit: old_string is required");let Z=await qQ(V,Q),q=await w0(V,Z);if(q!==void 0)throw new U(`edit: ${Q} is inside read-only directory ${q}`);let Y;try{let H=await O.stat(Z);if(!H.isFile())throw new U(`edit: ${Q} is not a regular file`);let M=C0(V.maxFileBytes);if(M!==null&&H.size>M)throw new U(`edit: ${Q} is ${H.size} bytes, exceeds ${M}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);Y=await O.readFile(Z,"utf8")}catch(H){if(H instanceof U)throw H;throw new U(`edit: ${n(H,Q)}`)}let W=Y.split($).length-1;if(W===0)throw new U(`edit: old_string not found in ${Q}`);let J;if(K)J=Y.split($).join(z);else{if(W>1)throw new U(`edit: old_string appears ${W} times in ${Q} (must be unique)`);J=Y.replace($,()=>z)}try{await RQ(Z,J)}catch(H){throw new U(`edit: write: ${n(H,Q)}`)}return`edited ${Q} (${K?W:1} replacement(s))`}})}function R1(V){return V.split(/[\\/{},]/).includes("..")}function j1(V){return c(V.unrestrictedPaths),S({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:Q,path:$})=>{if(!Q)throw new U("glob: pattern is required");if(T.isAbsolute(Q))throw new U("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(R1(Q))throw new U('glob: ".." is not permitted in the pattern');let z=$?await qQ(V,$):T.resolve(V.workdir),K=$?z:await r(z),Z=[],q=R0;try{for await(let Y of A1(Q,{cwd:z,withFileTypes:!0,exclude:(W)=>W.name===".git"||W.name==="node_modules"})){if(q--<=0)break;if(!Y.isFile())continue;let W=T.join(Y.parentPath,Y.name),J;try{J=await O.realpath(W)}catch{continue}if(!YQ(K,J))continue;let H=0;try{H=(await O.stat(W)).mtimeMs}catch{}Z.push({path:W,mtime:H})}}catch(Y){throw new U(`glob: ${Y instanceof Error?Y.message:String(Y)}`)}if(Z.length===0)return"no matches";return Z.sort((Y,W)=>W.mtime-Y.mtime),Z.slice(0,B1).map((Y)=>Y.path).join(`
|
|
14
|
+
`)}})}function L1(V){return c(V.unrestrictedPaths),S({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:Q,path:$},z)=>{if(!Q)throw new U("grep: pattern is required");let K=T.resolve(V.workdir);if($)K=await qQ(V,$);let Z=await v1();return Z?T1(Z,Q,K,z?.signal):y1(Q,K,z?.signal)}})}function T1(V,Q,$,z){return new Promise((K,Z)=>{let q=FQ.spawn(V,["-n","--no-heading","-e",Q,"--",$],{...z?{signal:z}:{}}),Y="",W="",J=!1;q.stdout.on("data",(H)=>{if(J)return;if(Y+=H,Y.length>ZQ)J=!0,Y=Y.slice(0,ZQ),q.kill("SIGKILL")}),q.stderr.on("data",(H)=>W+=H),q.on("close",(H)=>{if(z?.aborted)return Z(new U("grep: aborted"));if(J)return K(Y+`
|
|
15
|
+
[output truncated at ${ZQ} bytes]`);if(H===0)return K(Y);if(H===1)return K("no matches");Z(new U(`grep: rg failed: ${W||`exit ${H}`}`))}),q.on("error",(H)=>{if(z?.aborted)return Z(new U("grep: aborted"));Z(new U(`grep: rg failed: ${H.message}`))})})}async function y1(V,Q,$){let z;try{z=new RegExp(V)}catch(W){throw new U(`grep: invalid regex: ${W instanceof Error?W.message:String(W)}`)}let K=[],Z=ZQ,q=(W)=>{if(Z-=W.length+1,Z<0)return K.push(`[output truncated at ${ZQ} bytes]`),!1;return K.push(W),!0};if((await O.stat(Q).catch(()=>null))?.isFile())await N0(Q,z,q);else await x1(Q,"",(W)=>N0(T.join(Q,W),z,q),$);if($?.aborted)throw new U("grep: aborted");if(K.length===0)return"no matches";return K.join(`
|
|
16
|
+
`)}async function N0(V,Q,$){let z=XQ.createReadStream(V,{encoding:"utf8"}),K=A0.createInterface({input:z,crlfDelay:1/0}),Z=0;try{for await(let q of K){if(Z++,q.length>N1)continue;if(Q.test(q)&&!$(`${V}:${Z}:${q}`))return!1}}catch{}finally{z.destroy()}return!0}var b1=40,R0=50000;async function x1(V,Q,$,z){let K=R0;async function Z(q,Y){if(Y>b1)return!0;if(z?.aborted)return!1;let W;try{W=await O.readdir(T.join(V,q),{withFileTypes:!0})}catch{return!0}for(let J of W){if(J.name===".git"||J.name==="node_modules")continue;if(K--<=0)return!1;if(z?.aborted)return!1;let H=q?T.join(q,J.name):J.name;if(J.isDirectory()){if(!await Z(H,Y+1))return!1}else if(J.isFile()){if(await $(H)===!1)return!1}}return!0}await Z(Q,0)}async function v1(){let V=(process.env.PATH??"").split(T.delimiter);for(let Q of V){let $=T.join(Q,"rg");try{return await O.access($,XQ.constants.X_OK),$}catch{}}return null}export{F0 as setupSkills,qQ as resolvePath,mQ as extractSkillArchive,G1 as betaWriteTool,C1 as betaReadTool,L1 as betaGrepTool,j1 as betaGlobTool,O1 as betaEditTool,k1 as betaBashTool,M2 as betaAgentToolset20260401,J0 as SessionMemoryStores,m as SessionMemoryError,V0 as MIN_MEMORY_SYNC_INTERVAL_MS,z1 as MEMORY_FLUSH_TIMEOUT_MS,o as MARKER_PATH,AQ as DEFAULT_MEMORY_SYNC_INTERVAL_MS,k0 as BashTimeoutError,G0 as BashSession};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var Y={node:{registry:"github",source:"nodejs/node"},bun:{registry:"npm",source:"bun"},npm:{registry:"npm",source:"npm"},pnpm:{registry:"npm",source:"pnpm"},yarn:{registry:"npm",source:"yarn"},deno:{registry:"github",source:"denoland/deno"}};function Z(A,F){if(typeof A!=="object"||A===null||Array.isArray(A))return[];let z=[];for(let[B,J]of Object.entries(A)){if(typeof J!=="string"||!J.trim())continue;if(!Y[B])continue;z.push({name:B,currentVersion:J.trim(),type:"engines",file:F,metadata:{engine:"true",source:Y[B].source}})}return z}function $(A){if(typeof A!=="object"||A===null)return[];let F=A,z=[],B=(J,L)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return;for(let[U,H]of Object.entries(J)){if(typeof H==="string"&&H.trim()){z.push({name:U,version:H.trim(),field:L});continue}if(typeof H==="object"&&H!==null){let M=H;if(typeof M["."]==="string")z.push({name:U,version:M["."].trim(),field:L});B(H,L)}}};return B(F.overrides,"overrides"),B(F.resolutions,"resolutions"),B(F.pnpm?.overrides,"pnpm.overrides"),z}function q(A,F){let z=A.version.trim();try{if(/^[\^~><=]/.test(z))return!Bun.semver.satisfies(F,z)}catch{return!0}return z!==F}async function C(A,F){let z=Y[A];if(!z)return null;let B=z.registry==="npm"?await F.npm(z.source):await F.github(z.source);return B?B.replace(/^v/,""):null}function R(A,F){let z=/^\s*(>=|\^|~|>|=)?\s*v?(\d+(?:\.\d+)*)\s*$/.exec(A);if(!z)return null;let[,B="",J]=z,L=J.split(".").map(Number),H=F.split(".").map(Number).slice(0,L.length),M=!1;for(let Q=0;Q<H.length;Q++){let X=H[Q]-(L[Q]??0);if(X!==0){M=X>0;break}}if(!M)return null;return`${B}${H.join(".")}`}function T(A,F){let z=(L)=>(/(\d+(?:\.\d+)*)/.exec(L)?.[1]??"0").split(".").map(Number),B=z(A),J=z(F);if((J[0]??0)!==(B[0]??0))return"major";if((J[1]??0)!==(B[1]??0))return"minor";return"patch"}function P(A,F){let z=/("engines"\s*:\s*\{)([\s\S]*?)(\})/.exec(A);if(!z)return A;let[B,J,L,U]=z,H=L;for(let M of F){if(M.dependencyType!=="engines")continue;let Q=M.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=M.currentVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");H=H.replace(new RegExp(`("${Q}"\\s*:\\s*")${X}(")`),`$1${M.newVersion}$2`)}return H===L?A:A.replace(B,`${J}${H}${U}`)}
|
|
3
|
+
export{Y as Ke,Z as Le,$ as Me,q as Ne,C as Oe,R as Pe,T as Qe,P as Re};
|
|
@@ -4,4 +4,4 @@ var A=1,F=30000,K=/<!--\s*buddy:manifest\s+v(\d+)\s*([\s\S]*?)-->/;function Y(j)
|
|
|
4
4
|
<!-- buddy:manifest v1
|
|
5
5
|
${JSON.stringify(j)}
|
|
6
6
|
-->`}function G(j,q={}){return L(j.updates,{group:j.name,...q})}function Z(j){if(!j)return null;let q=j.match(K);if(!q)return null;try{let w=JSON.parse(q[2].trim());if(!D(w))return null;return{...w,schemaVersion:Number(w.schemaVersion)||Number(q[1])||1,updates:w.updates.filter(z)}}catch{return null}}function I(j){return Z(j)!==null}function $(j){return j.replace(K,"").trimEnd()}function N(j,q,w={}){return $(j)+L(q,w)}function P(j){return j.updates.map((q)=>({name:q.name,currentVersion:q.current,newVersion:q.target}))}function R(j){return[...new Set(j.updates.map((q)=>q.file).filter(Boolean))]}function D(j){if(typeof j!=="object"||j===null)return!1;return Array.isArray(j.updates)}function z(j){if(typeof j!=="object"||j===null)return!1;let q=j;return typeof q.name==="string"&&typeof q.current==="string"&&typeof q.target==="string"}
|
|
7
|
-
export{A as
|
|
7
|
+
export{A as gg,F as hg,L as ig,G as jg,Z as kg,I as lg,$ as mg,N as ng,P as og,R as pg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{V as
|
|
2
|
+
import{zh as X}from"./chunk-e68nf7cm.js";import{Fh as Z}from"./chunk-hfjywbbc.js";var V={node:"nodejs","library/node":"nodejs",python:"python","library/python":"python",debian:"debian","library/debian":"debian",ubuntu:"ubuntu","library/ubuntu":"ubuntu",alpine:"alpine","library/alpine":"alpine",php:"php","library/php":"php",ruby:"ruby","library/ruby":"ruby",golang:"go","library/golang":"go",postgres:"postgresql","library/postgres":"postgresql",mysql:"mysql","library/mysql":"mysql",redis:"redis","library/redis":"redis",nginx:"nginx","library/nginx":"nginx"};function q(j){let x=j.replace(/^(?:docker\.io|registry-1\.docker\.io)\//,"");return V[x]??V[x.split("/").pop()??""]??null}function G(j,x){let z=/^v?(\d+(?:\.\d+)*)/.exec(j.trim());if(!z)return null;let H=z[1].split(".");for(let k=H.length;k>=1;k--){let K=H.slice(0,k).join("."),B=x.find((J)=>J.cycle===K);if(B)return B}return null}async function F(j,x,z={}){let H=z.logger??Z(),k=q(j);if(!k)return null;let K=z.baseUrl??"https://endoflife.date",B=await X(`${K}/api/${k}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!B?.ok)return H.debug(`Could not read the support window for ${k}`),null;let J=await B.json().catch(()=>null);if(!Array.isArray(J))return null;let v=G(x,J);if(!v)return null;if(v.eol===!1)return{product:k,cycle:v.cycle,eol:!1};if(v.eol===!0)return{product:k,cycle:v.cycle,eol:!0};let M=new Date(v.eol);if(Number.isNaN(M.getTime()))return{product:k,cycle:v.cycle,eol:!1};let $=z.now??new Date,Q=Math.round((M.getTime()-$.getTime())/86400000);return{product:k,cycle:v.cycle,eol:Q<0,date:v.eol,daysRemaining:Q}}var I=90;function N(j){if(!j)return"";if(j.eol)return j.date?`\`${j.product} ${j.cycle}\` reached end of life on ${j.date} and no longer receives security fixes.`:`\`${j.product} ${j.cycle}\` has reached end of life and no longer receives security fixes.`;if(j.daysRemaining!==void 0&&j.daysRemaining<=I)return`\`${j.product} ${j.cycle}\` reaches end of life in ${j.daysRemaining} day(s), on ${j.date}.`;return""}
|
|
3
|
+
export{V as xa,q as ya,G as za,F as Aa,I as Ba,N as Ca};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{bi as a,ci as e,di as o,ei as s,fi as t,gi as i,hi as c,ii as r,ji as n,ki as g,li as m,mi as u,ni as P,oi as l,pi as h}from"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{n as toPropertyKey,e as shouldProceedWithGitHubRequest,a as saveRateLimitInfo,s as saveGitHubPackageCache,u as resolvePackageDomain,i as logPkgxProjects,l as isKnownAlias,m as guessOriginalDomain,P as getPackageAliases,o as getGitHubPackageCache,h as getCanonicalDomain,c as formatObjectWithoutQuotedKeys,t as fetchPackageListFromGitHub,r as convertDomainToVarName,g as convertDomainToFileName};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{D as s,E as t,F as u,G as v,H as w,c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,u as p,v as q,w as r}from"./chunk-
|
|
2
|
+
import{D as s,E as t,F as u,G as v,H as w,c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,u as p,v as q,w as r}from"./chunk-sw2538r0.js";import"./chunk-q4t568hv.js";export{r as toFile,v as default,w as betaRefusalFallbackMiddleware,l as UnprocessableEntityError,f as RetryableError,m as RateLimitError,i as PermissionDeniedError,q as PagePromise,j as NotFoundError,n as InternalServerError,s as HUMAN_PROMPT,k as ConflictError,o as BetaFallbackState,u as BaseAnthropic,g as BadRequestError,h as AuthenticationError,a as AnthropicError,v as Anthropic,c as APIUserAbortError,p as APIPromise,b as APIError,e as APIConnectionTimeoutError,d as APIConnectionError,t as AI_PROMPT};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{jf as a,kf as b,lf as c,mf as d,nf as e,of as f,pf as g}from"./chunk-yngahb11.js";import"./chunk-1cpdz49v.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{f as strategyAllows,b as ruleMatches,c as resolveRuleEffects,e as mergeGroupEffects,g as groupsToRules,a as ecosystemOf,d as applyRules};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{zh as P}from"./chunk-e68nf7cm.js";import{Ch as M,Fh as Q}from"./chunk-hfjywbbc.js";function V(z){if(z==="running")return"in_progress";if(z==="success"||z==="failed"||z==="canceled"||z==="skipped"||z==="manual")return"completed";return"queued"}function X(z){switch(z){case"success":return"success";case"failed":return"failure";case"canceled":return"cancelled";case"skipped":case"manual":return"skipped";default:return null}}class Y{token;apiUrl;logger;projectId;constructor(z,A,F,G,H){this.token=z;this.apiUrl=(G??"https://gitlab.com/api/v4").replace(/\/+$/,""),this.logger=H??Q(),this.projectId=encodeURIComponent(`${A}/${F}`)}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!1,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}async request(z,A,F,G={}){let H=await P(`${this.apiUrl}${A}`,{method:z,headers:{"PRIVATE-TOKEN":this.token,Accept:G.raw?"text/plain":"application/json","User-Agent":"buddy",...F?{"Content-Type":"application/json"}:{}},...F?{body:JSON.stringify(F)}:{}});if(!H.ok){let K=await H.text().catch(()=>"");throw Error(`GitLab ${z} ${A} failed: ${H.status} ${K.slice(0,200)}`)}let J=await H.text();if(G.raw)return J;return J.trim()?JSON.parse(J):void 0}async optional(z,A,F={}){try{return await this.request(z,A,void 0,F)}catch(G){if(String(G).includes("404"))return null;throw G}}async branchExists(z){return await this.optional("GET",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)!==null}async createBranch(z,A){await this.request("POST",`/projects/${this.projectId}/repository/branches`,{branch:z,ref:A})}async deleteBranch(z){await this.request("DELETE",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)}async commitChanges(z,A,F,G="main"){if(F.length===0)return;if(await this.branchExists(z))await this.deleteBranch(z);await this.createBranch(z,G);let J=await Promise.all(F.map(async(K)=>{if(K.type==="delete")return{action:"delete",file_path:K.path};return{action:await this.getFileContent(K.path,G)!==null?"update":"create",file_path:K.path,content:K.content}}));await this.request("POST",`/projects/${this.projectId}/repository/commits`,{branch:z,commit_message:A,actions:J})}async getFileContent(z,A){let F=await this.optional("GET",`/projects/${this.projectId}/repository/files/${encodeURIComponent(z)}?ref=${encodeURIComponent(A)}`);if(!F?.content)return null;return F.encoding==="base64"?Buffer.from(F.content,"base64").toString("utf-8"):F.content}async createPullRequest(z){let A=await this.request("POST",`/projects/${this.projectId}/merge_requests`,{source_branch:z.head,target_branch:z.base,title:z.draft?`Draft: ${z.title}`:z.title,description:z.body,...z.labels?.length?{labels:z.labels.join(",")}:{},remove_source_branch:!0});return await this.assignPeople(A.iid,z),this.toPullRequest(A)}async assignPeople(z,A){let F=async(J=[])=>{return(await Promise.all(J.map(async(O)=>{return(await this.optional("GET",`/users?username=${encodeURIComponent(O)}`))?.[0]?.id??null}))).filter((O)=>O!==null)},[G,H]=await Promise.all([F(A.reviewers),F(A.assignees)]);if(G.length===0&&H.length===0)return;try{await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...G.length?{reviewer_ids:G}:{},...H.length?{assignee_ids:H}:{}})}catch(J){this.logger.warn(`\u26A0\uFE0F Could not assign reviewers on !${z}: ${M(J)}`)}}async getPullRequests(z="open"){let A=z==="all"?"state=all":z==="open"?"state=opened":"state=all",G=(await this.request("GET",`/projects/${this.projectId}/merge_requests?${A}&per_page=100`)).map((H)=>this.toPullRequest(H));return z==="closed"?G.filter((H)=>H.state!=="open"):G}async updatePullRequest(z,A){let F=await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...A.title!==void 0?{title:A.draft?`Draft: ${A.title}`:A.title}:{},...A.body!==void 0?{description:A.body}:{},...A.base!==void 0?{target_branch:A.base}:{},...A.labels!==void 0?{labels:A.labels.join(",")}:{}});return this.toPullRequest(F)}async closePullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"close"})}async reopenPullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"reopen"})}async mergePullRequest(z,A="squash"){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/merge`,{squash:A==="squash",should_remove_source_branch:!0})}async getPullRequestDiff(z){return((await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}/changes`)).changes??[]).map((F)=>[`diff --git a/${F.old_path} b/${F.new_path}`,`--- a/${F.old_path}`,`+++ b/${F.new_path}`,F.diff.replace(/\n$/,"")].join(`
|
|
3
|
+
`)).join(`
|
|
4
|
+
`)}async getPullRequestHeadSha(z){return(await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}`)).sha??""}async createComment(z,A){try{await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/notes`,{body:A})}catch(F){if(!String(F).includes("404"))throw F;await this.request("POST",`/projects/${this.projectId}/issues/${z}/notes`,{body:A})}}async createIssue(z){let A=await this.request("POST",`/projects/${this.projectId}/issues`,{title:z.title,description:z.body,...z.labels?.length?{labels:z.labels.join(",")}:{}});return this.toIssue(A)}async getIssues(z="open"){let A=z==="all"?"state=all":`state=${z==="open"?"opened":"closed"}`;return(await this.request("GET",`/projects/${this.projectId}/issues?${A}&per_page=100`)).map((G)=>this.toIssue(G))}async updateIssue(z,A){let F=await this.request("PUT",`/projects/${this.projectId}/issues/${z}`,{...A.title!==void 0?{title:A.title}:{},...A.body!==void 0?{description:A.body}:{},...A.labels!==void 0?{labels:A.labels.join(",")}:{}});return this.toIssue(F)}async closeIssue(z){await this.request("PUT",`/projects/${this.projectId}/issues/${z}`,{state_event:"close"})}async unpinIssue(z){return!1}async enableAutoMerge(z,A="squash"){try{return await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/merge`,{merge_when_pipeline_succeeds:!0,squash:A==="squash",should_remove_source_branch:!0}),!0}catch(F){return this.logger.debug(`Could not queue !${z} for auto-merge: ${M(F)}`),!1}}async getPullRequestChecksState(z){let F=(await this.optional("GET",`/projects/${this.projectId}/merge_requests/${z}/pipelines`))?.[0]?.status;if(!F)return"none";if(F==="success")return"success";if(["failed","canceled"].includes(F))return"failure";if(["running","pending","created","waiting_for_resource","preparing","scheduled"].includes(F))return"pending";return"none"}async createReview(z,A){if(await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/notes`,{body:A.body}),!A.comments?.length)return{posted:!0,inlineComments:0};let G=(await this.optional("GET",`/projects/${this.projectId}/merge_requests/${z}/versions`))?.[0];if(!G)return this.logger.warn("\u26A0\uFE0F Could not resolve diff positions; inline comments were not posted"),{posted:!0,inlineComments:0};let H=0;for(let J of A.comments)try{await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/discussions`,{body:J.body,position:{position_type:"text",base_sha:G.base_commit_sha,start_sha:G.start_commit_sha,head_sha:G.head_commit_sha,new_path:J.path,old_path:J.path,...J.side==="RIGHT"?{new_line:J.line}:{old_line:J.line}}}),H++}catch(K){this.logger.debug(`Could not place a comment on ${J.path}:${J.line}: ${M(K)}`)}return{posted:!0,inlineComments:H}}async createCheckRun(z,A,F){try{await this.request("POST",`/projects/${this.projectId}/statuses/${A}`,{state:F.conclusion==="failure"?"failed":"success",name:z,description:F.title.slice(0,140)})}catch(G){this.logger.warn(`\u26A0\uFE0F Could not report status ${z}: ${M(G)}`)}}async reactToComment(z,A){let F={eyes:"eyes","+1":"thumbsup","-1":"thumbsdown",rocket:"rocket",confused:"confused"};try{await this.request("POST",`/projects/${this.projectId}/notes/${z}/award_emoji`,{name:F[A]??"eyes"})}catch(G){this.logger.debug(`Could not react to note ${z}: ${M(G)}`)}}async hasWriteAccess(z){return(await this.optional("GET",`/projects/${this.projectId}/members/all?query=${encodeURIComponent(z)}`)??[]).some((F)=>F.username===z&&F.access_level>=30)}async getWorkflowRunLogs(z){return this.optional("GET",`/projects/${this.projectId}/jobs/${z}/trace`,{raw:!0}).catch((A)=>{return this.logger.debug(`Could not read the trace for job ${z}: ${M(A)}`),null})}async listWorkflowRuns(z,A={}){let F=A.limit??20;try{return(await this.request("GET",`/projects/${this.projectId}/jobs?per_page=${Math.min(F*5,100)}`)??[]).filter((H)=>H.ref===z).map((H)=>({id:H.id,name:H.name??"",headSha:H.commit?.id??"",headBranch:H.ref??z,status:V(H.status),conclusion:X(H.status),createdAt:new Date(H.created_at??new Date().toISOString())})).filter((H)=>!A.status||H.status===A.status).slice(0,F)}catch(G){return this.logger.debug(`Could not list CI jobs for ${z}: ${M(G)}`),[]}}async rerunWorkflowRun(z){try{return await this.request("POST",`/projects/${this.projectId}/jobs/${z}/retry`),!0}catch(A){return this.logger.warn(`Could not retry job ${z}: ${M(A)}`),!1}}async listReviewThreads(z){try{return(await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}/discussions?per_page=100`)??[]).filter((F)=>(F.notes??[]).some((G)=>G.resolvable)).map((F)=>({id:F.id,isResolved:(F.notes??[]).every((G)=>!G.resolvable||G.resolved),...F.notes?.[0]?.position?.new_path?{path:F.notes[0].position.new_path}:{},authorLogins:(F.notes??[]).map((G)=>G.author?.username).filter((G)=>typeof G==="string")}))}catch(A){return this.logger.debug(`Could not read discussions on !${z}: ${M(A)}`),[]}}async resolveReviewThread(z,A){try{return await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/discussions/${encodeURIComponent(A)}`,{resolved:!0}),!0}catch(F){return this.logger.warn(`Could not resolve discussion ${A}: ${M(F)}`),!1}}async getBuddyBranches(){return(await this.request("GET",`/projects/${this.projectId}/repository/branches?search=buddy&per_page=100`)).filter((A)=>A.name.startsWith("buddy/")).map((A)=>({name:A.name,sha:A.commit?.id??"",lastCommitDate:A.commit?.committed_date?new Date(A.commit.committed_date):new Date(0)}))}async getOrphanedBuddyBranches(){let[z,A]=await Promise.all([this.getBuddyBranches(),this.getPullRequests("open")]),F=new Set(A.map((G)=>G.head));return z.filter((G)=>!F.has(G.name))}async cleanupStaleBranches(z=7,A=!1){let F=new Date(Date.now()-z*24*60*60*1000),G=(await this.getOrphanedBuddyBranches()).filter((K)=>K.lastCommitDate<F);if(A)return{deleted:G.map((K)=>K.name),failed:[]};let H=[],J=[];for(let K of G)try{await this.deleteBranch(K.name),H.push(K.name)}catch{J.push(K.name)}return{deleted:H,failed:J}}toPullRequest(z){let A=Boolean(z.draft??z.work_in_progress)||/^(?:draft|wip):/i.test(z.title);return{number:z.iid,title:z.title.replace(/^(?:draft|wip):\s*/i,""),body:z.description??"",head:z.source_branch,base:z.target_branch,state:z.state==="merged"?"merged":z.state==="opened"?"open":"closed",url:z.web_url,createdAt:new Date(z.created_at),updatedAt:new Date(z.updated_at),...z.merged_at?{mergedAt:new Date(z.merged_at)}:{},author:z.author?.username??"",reviewers:(z.reviewers??[]).map((F)=>F.username),assignees:(z.assignees??[]).map((F)=>F.username),labels:z.labels??[],draft:A}}toIssue(z){return{number:z.iid,title:z.title,body:z.description??"",state:z.state==="closed"?"closed":"open",url:z.web_url,createdAt:new Date(z.created_at),updatedAt:new Date(z.updated_at),...z.closed_at?{closedAt:new Date(z.closed_at)}:{},author:z.author?.username??"",assignees:(z.assignees??[]).map((A)=>A.username),labels:z.labels??[]}}}
|
|
5
|
+
export{Y as th};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var B=/<!--\s*buddy:review\s+v(\d+)\s*([\s\S]*?)-->/,H=1;function F(j){let x={schemaVersion:1,...j};return`<!-- buddy:review v1
|
|
3
|
+
${JSON.stringify(x)}
|
|
4
|
+
-->`}function I(j){if(!j)return null;let x=j.match(B);if(!x)return null;try{let k=JSON.parse(x[2].trim());if(typeof k.reviewedSha!=="string")return null;return{schemaVersion:Number(k.schemaVersion)||1,reviewedSha:k.reviewedSha,fingerprints:Array.isArray(k.fingerprints)?k.fingerprints.filter((D)=>typeof D==="string"):[],reviewedAt:typeof k.reviewedAt==="string"?k.reviewedAt:new Date(0).toISOString(),...k.paused?{paused:!0}:{}}}catch{return null}}function J(j,x){return`${(j??"").replace(B,"").trimEnd()}
|
|
5
|
+
|
|
6
|
+
${F(x)}`}function L(j,x){if(j?.paused)return!1;return j?.reviewedSha!==x}
|
|
7
|
+
export{H as Lb,F as Mb,I as Nb,J as Ob,L as Pb};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Fh as V}from"./chunk-hfjywbbc.js";import{join as R}from"path";var K=/^catalog:(.*)$/;function N(X){let J;try{J=Bun.YAML.parse(X)}catch{return{entries:[],hasCatalogs:!1}}if(typeof J!=="object"||J===null)return{entries:[],hasCatalogs:!1};let B=J,z=[],$=!1,H=(M,j)=>{if(typeof M!=="object"||M===null||Array.isArray(M))return;$=!0;for(let[U,q]of Object.entries(M))if(typeof q==="string"&&q.trim())z.push({name:U,version:q.trim(),catalog:j})};if(H(B.catalog,"default"),typeof B.catalogs==="object"&&B.catalogs!==null)for(let[M,j]of Object.entries(B.catalogs))H(j,M);return{entries:z,hasCatalogs:$}}function k(X,J,B){let z=K.exec(X.trim());if(!z)return null;let $=z[1].trim()||"default";return J.find((H)=>H.name===B&&H.catalog===$)?.version??null}function w(X){return K.test(X.trim())}function S(X,J,B){let z=X.split(`
|
|
3
3
|
`),$=/^(\s*)(["']?)([^"':]+)\2(\s*:\s*)(["']?)(.+?)\5(\s*(?:#.*)?)$/,H=null,M=!1,j=0;for(let U=0;U<z.length;U++){let q=z[U],Y=q.length-q.trimStart().length,Z=q.trim();if(/^catalog\s*:\s*$/.test(Z)){H="default",M=!1;continue}if(/^catalogs\s*:\s*$/.test(Z)){M=!0,j=Y,H=null;continue}if(M&&Y>j&&/^[\w@./-]+\s*:\s*$/.test(Z)){H=Z.replace(/\s*:\s*$/,"");continue}if(M&&Z&&Y<=j)M=!1,H=null;if(H!==J.catalog)continue;let D=$.exec(q);if(!D||D[3].trim()!==J.name||D[6].trim()!==J.version)continue;let[,x,F,E,P,G,,Q]=D;return z[U]=`${x}${F}${E}${F}${P}${G}${B}${G}${Q}`,z.join(`
|
|
4
4
|
`)}return X}var W="pnpm-workspace.yaml",I="pnpm-workspace.yml";async function h(X,J,B={}){let z=B.logger??V(),$=new Set(B.ignore??[]);for(let H of[W,I]){let M=Bun.file(R(X,H));if(!await M.exists())continue;let{entries:j,hasCatalogs:U}=N(await M.text());if(!U)return{updates:[],entries:[],file:H};return z.debug(`\uD83D\uDCE6 ${H}: ${j.length} catalog entr(ies)`),{updates:(await Promise.all(j.map(async(Y)=>{if($.has(Y.name))return null;try{let Z=await J(Y.name);if(!Z)return null;let D=Y.version.replace(/^[\^~>=<\s]+/,"").trim();if(!D||D===Z)return null;return{name:Y.name,currentVersion:Y.version,newVersion:_(Y.version,Z),updateType:A(D,Z),dependencyType:"catalog",file:H,resolved:{catalog:Y.catalog}}}catch(Z){return z.debug(`Could not resolve catalog entry ${Y.name}: ${Z}`),null}}))).filter((Y)=>Y!==null),entries:j,file:H}}return{updates:[],entries:[]}}function _(X,J){return`${/^([\^~]|>=|<=|>|<)?/.exec(X.trim())?.[1]??""}${J}`}function A(X,J){let B=(H)=>H.split(".").map((M)=>Number.parseInt(M,10)||0),z=B(X),$=B(J);if((z[0]??0)!==($[0]??0))return"major";if((z[1]??0)!==($[1]??0))return"minor";return"patch"}function v(X,J){let B=X;for(let z of J){if(z.dependencyType!=="catalog")continue;B=S(B,{name:z.name,version:z.currentVersion,catalog:z.resolved?.catalog??"default"},z.newVersion)}return B}
|
|
5
|
-
export{N as
|
|
5
|
+
export{N as gc,k as hc,w as ic,S as jc,W as kc,I as lc,h as mc,v as nc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{L as
|
|
2
|
+
import{_c as Z}from"./chunk-dqbk3kcj.js";import{Dh as _}from"./chunk-hfjywbbc.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
|
|
3
|
+
export{L as Da};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$a as e,Xa as a,Ya as b,Za as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,gb as l}from"./chunk-s4zb0fcj.js";import"./chunk-08x5b93v.js";import"./chunk-q4t568hv.js";export{k as withTouchOffer,b as unitTestsTouch,d as simplifyTouch,i as renderTouchOffer,e as planTouch,l as parseTouchSelections,j as hasTouchOffer,g as getFinishingTouch,a as docstringsTouch,c as autofixTouch,h as TOUCH_OFFER_MARKER,f as FINISHING_TOUCHES};
|
|
@@ -5,4 +5,4 @@ function J(L,q){if(!L.trim())return[];let D=L.toLowerCase(),Q=[];for(let B of q)
|
|
|
5
5
|
|---|---|---|---|
|
|
6
6
|
`;for(let Q of q){let B=[];if(Q.vulnerable)B.push("\u26A0\uFE0F known advisory");if(Q.deprecated)B.push("\uD83D\uDEAB deprecated");if(Q.openPRs?.length)B.push(`open PR ${Q.openPRs.map((F)=>`#${F}`).join(", ")}`);D+=`| \`${Q.name}\` | ${Q.declaredVersion??"\u2014"} | ${Q.latestVersion??"\u2014"} | ${B.join(", ")||"\u2014"} |
|
|
7
7
|
`}return D}function Z(L,q){let D=new Map(q.map((F)=>[F.toLowerCase(),F])),Q=[],B=[];for(let F of L){let G=D.get(F.trim().toLowerCase());if(G&&!Q.includes(G))Q.push(G);else if(!G)B.push(F)}return{apply:Q,rejected:B}}function X(L,q){let D=V(L),Q=V(q);if(D.size===0||Q.size===0)return 0;let B=0;for(let F of D)if(Q.has(F))B++;return B/Math.min(D.size,Q.size)}function $(L,q,D=0.6){return q.map((Q)=>({number:Q.number,score:X(L,Q.text)})).filter((Q)=>Q.score>=D).sort((Q,B)=>B.score-Q.score)}var A=new Set(["the","a","an","is","are","was","were","to","of","in","on","for","and","or","but","with","this","that","it","be","has","have","not","when","then","i","we","you","my","our"]);function V(L){return new Set(L.toLowerCase().split(/[^\w.-]+/).filter((q)=>q.length>2&&!A.has(q)))}function H(L){return L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Y="<!-- buddy:quick-links -->",S=[{id:"plan",label:"Make a plan",description:"Read the issue and the relevant code, then post an implementation plan. Changes nothing."},{id:"build",label:"Build this",description:"Open a draft pull request implementing the issue."}],U=/- \[x\]\s*<!--\s*quick-action=([\w-]+)\s*-->/gi;function j(L){if(!L)return{actions:[]};let q=[];for(let D of L.matchAll(U)){let Q=D[1].trim();if(S.some((B)=>B.id===Q)&&!q.includes(Q))q.push(Q)}return{actions:q}}function v(L){return L.replace(/- \[x\](\s*<!--\s*quick-action=[\w-]+\s*-->)/gi,"- [ ]$1")}function w(L={}){let q=[Y,"","### Buddy","","Tick a box to have Buddy pick this up:",""];for(let Q of S)q.push(`- [ ] <!-- quick-action=${Q.id} -->**${Q.label}** \u2014 ${Q.description}`);let D=L.packages?.length&&L.body?J(L.body,L.packages.map((Q)=>Q.name)):[];if(D.length>0){let Q=L.packages.filter((B)=>D.includes(B.name));q.push("",M(Q))}return q.join(`
|
|
8
|
-
`)}export{J as
|
|
8
|
+
`)}export{J as aa,M as ba,Z as ca,X as da,$ as ea,Y as fa,S as ga,j as ha,v as ia,w as ja};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{od as A}from"./chunk-cwfkm7h9.js";import{le as G,me as q}from"./chunk-p8tmms5h.js";import{sf as T}from"./chunk-08x5b93v.js";import{If as S}from"./chunk-p6qbqsyp.js";import{Ch as K,Fh as O}from"./chunk-hfjywbbc.js";import{Wk as I}from"./chunk-q4t568hv.js";var w=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
|
|
3
|
+
`);for(let z of w){let J=[];for(let V of H)if(z.patterns.some((Q)=>Q.test(V))){if(J.push(V.trim()),J.length>=5)break}if(J.length>0)return{kind:z.kind,mechanical:z.mechanical,evidence:J}}return{kind:"unknown",mechanical:!1,evidence:P(H)}}function P(x,H=40){let z=x.filter((J)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(J)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(J));return(z.length>0?z:x.slice(-H)).slice(-H).map((J)=>J.trim()).filter(Boolean)}function X(x){switch(x.kind){case"lockfile-drift":return"The lock file is out of step with its manifest.";case"flake":return"A network or runner problem, unrelated to the change.";case"install":return"Dependencies could not be resolved.";case"type-error":return"The change does not type-check.";case"test-failure":return"One or more tests failed.";case"lint":return"Lint or formatting checks failed.";default:return"The failure could not be classified automatically."}}var b=3;async function _(x,H,z,J){let V=J??O();try{let Q=await x.listWorkflowRuns(H,{status:"completed",limit:20});for(let Y of F(Q).slice(0,b)){let Z=await x.getWorkflowRunLogs(Y.id);if(!Z)continue;if(N(Z).kind===z)return V.info(`\uD83E\uDDED ${H} already fails the same way (run ${Y.id}) \u2014 not this pull request's to fix`),!0}return!1}catch(Q){return V.debug(`Could not check ${H} for a pre-existing failure: ${K(Q)}`),!1}}function F(x){let H=new Map;for(let z of x)if(!H.has(z.name))H.set(z.name,z);return[...H.values()].filter((z)=>z.conclusion==="failure")}function h(x,H){if(!x)return"Tried to regenerate the lock file, but the install did not succeed.";if(!H)return"Regenerated the lock file, but could not push it to the branch. The change is in the workspace only, so the run will still be red until someone commits it.";return"Regenerated the lock file and pushed the result. No model was needed."}function m(x){let H="Repairs run on the pull request's branch, and answering a comment runs on the default branch, so anything I changed here would land on the wrong tree. ";if(x.kind==="lockfile-drift")return`Regenerating the lock file would fix this, and no model would be needed. ${H}The \`fix-ci\` job will do it on the next failing run, or you can run \`buddy fix-ci --run-id <id> --pr <number>\` yourself.`;return`${H}The \`fix-ci\` job runs on the failing run itself and can repair this; this reply is the diagnosis it would start from.`}async function M(x){let H=x.logger??O(),z=N(x.log),J=x.maxAttempts??3;if(H.info(`\uD83E\uDE7A CI failure classified as ${z.kind}`),x.failsOnBase??(x.checkBase?await x.checkBase(z.kind):!1))return{failure:z,action:"skipped",fixed:!1,report:$(z,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((x.priorAttempts??0)>=J)return{failure:z,action:"skipped",fixed:!1,report:$(z,`Already attempted ${x.priorAttempts} time(s); stopping rather than looping.`)};if(x.analysisOnly&&z.kind!=="flake")return{failure:z,action:"reported",fixed:!1,report:$(z,m(z))};if(z.kind==="lockfile-drift"&&x.regenerateLockfile){if(x.dryRun)return{failure:z,action:"mechanical-fix",fixed:!1,report:$(z,"Regenerating the lock file would fix this. No model would be needed. Nothing was changed, because this was a dry run.")};H.info("\uD83D\uDD27 Regenerating the lock file");let{regenerated:Y,pushed:Z}=await x.regenerateLockfile();return{failure:z,action:"mechanical-fix",fixed:Z,report:$(z,h(Y,Z))}}if(z.kind==="flake"){if(x.dryRun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient, and re-running the failed jobs would likely clear it. Nothing was changed, because this was a dry run.")};if(!x.rerun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient. Re-running the failed job is likely to clear it.")};H.info("\uD83D\uDD01 Re-running the failed jobs");let Y=await x.rerun();return{failure:z,action:"retry",fixed:!1,report:$(z,Y?"This looks transient, so I re-ran the failed jobs. No model was needed.":"This looks transient, but I could not re-run the failed jobs \u2014 `actions: write` is the usual reason. "+"Re-running them from the Actions tab is likely to clear it.")}}if(!x.ai)return{failure:z,action:"reported",fixed:!1,report:$(z,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let Q=await S(x.ai,{mode:T,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${z.kind} \u2014 ${X(z)}`,"","Relevant log lines:",z.evidence.join(`
|
|
4
|
+
`),"","Verify your fix by running the project's tests or build before reporting it done.","If the fix is not clear, explain what you found rather than guessing."].join(`
|
|
5
|
+
`),context:{workspace:x.workspace,baseBranch:x.baseBranch,...x.branch?{branch:x.branch}:{}},logger:H});return{failure:z,action:"agent-fix",fixed:Q.stopReason==="completed",report:$(z,Q.output||"The repair run ended without a conclusion.")}}function $(x,H){let z=`## \uD83E\uDE7A CI failure analysis
|
|
6
|
+
|
|
7
|
+
**Diagnosis:** ${X(x)}
|
|
8
|
+
|
|
9
|
+
${H}
|
|
10
|
+
`;if(x.evidence.length>0)z+=`
|
|
11
|
+
<details><summary>Relevant log lines</summary>
|
|
12
|
+
|
|
13
|
+
\`\`\`
|
|
14
|
+
${x.evidence.slice(0,20).join(`
|
|
15
|
+
`)}
|
|
16
|
+
\`\`\`
|
|
17
|
+
|
|
18
|
+
</details>
|
|
19
|
+
`;return z}var L=/<!--\s*buddy:fix-ci\s+v(\d+)\s*([\s\S]*?)-->/;function B(x){if(!x)return null;let H=x.match(L);if(!H)return null;try{let z=JSON.parse(H[2].trim()),J=Number(z.attempts);if(!Number.isFinite(J)||J<0)return null;return{attempts:Math.floor(J),lastAttemptAt:typeof z.lastAttemptAt==="string"?z.lastAttemptAt:new Date(0).toISOString()}}catch{return null}}function E(x,H,z=new Date){let J={attempts:H,lastAttemptAt:z.toISOString()},V=`<!-- buddy:fix-ci v1
|
|
20
|
+
${JSON.stringify(J)}
|
|
21
|
+
-->`;return`${(x??"").replace(L,"").trimEnd()}
|
|
22
|
+
|
|
23
|
+
${V}`}async function f(x,H,z){if(!G(x,"ciRuns","listWorkflowRuns"))return null;try{let J=await x.getPullRequestHeadSha(H.number),V=await x.listWorkflowRuns(H.head,{status:"completed",limit:30}),Q=J?V.filter((Y)=>Y.headSha===J):V;return F(Q)[0]?.id??null}catch(J){return z.debug(`Could not resolve the failing run for #${H.number}: ${K(J)}`),null}}async function c(x){let H=x.logger??O(),{config:z,provider:J}=x,V=x.workspace??process.cwd();q(J,"ciLogs","getWorkflowRunLogs","reading CI logs");let Q;if(x.prNumber){if(Q=(await J.getPullRequests("open")).find((W)=>W.number===x.prNumber),!Q)return`Could not find open pull request #${x.prNumber}.`}let Y=x.runId??(Q?await f(J,Q,H):null);if(!Y)return Q?"Nothing is failing at the head of this pull request, so there is nothing to diagnose.":"No run to diagnose. Pass --run-id, or --pr so I can find the failing run myself.";let Z=await J.getWorkflowRunLogs(Y);if(!Z)return H.warn(`\u26A0\uFE0F Could not read the logs for run ${Y}; nothing to diagnose`),`Could not read the logs for run ${Y}. They may have expired.`;let j=B(Q?.body)?.attempts??0,U=z.repository?.baseBranch??"main",R=G(J,"ciRuns","listWorkflowRuns"),y=G(J,"ciRuns","rerunWorkflowRun"),{createAiClient:k}=await import("./chunk-hsa07n7c.js"),C=await M({log:Z,priorAttempts:j,workspace:V,baseBranch:U,ai:x.analysisOnly?null:k(z,H),logger:H,dryRun:Boolean(x.dryRun),analysisOnly:Boolean(x.analysisOnly),...R?{checkBase:(D)=>_({listWorkflowRuns:(W,v)=>J.listWorkflowRuns(W,v),getWorkflowRunLogs:(W)=>J.getWorkflowRunLogs(W)},U,D,H)}:{},...y?{rerun:()=>J.rerunWorkflowRun(Y)}:{},...x.analysisOnly?{}:{regenerateLockfile:()=>g(V,H)}});if(H.info(`
|
|
24
|
+
${C.report}
|
|
25
|
+
`),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:E(Q.body,j+1)})}catch(D){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(D)}`)}}return await A(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V}=await import("./chunk-ng7px8gx.js"),{commitAndPush:Q}=await import("./chunk-aa277p5r.js"),Y=J(["package.json","composer.json"]),Z=!1;for(let j of Y){let U=await z(j,x);if(U.success)Z=!0;else H.warn(`\u26A0\uFE0F ${U.message}`)}if(!Z)return{regenerated:!1,pushed:!1};try{return{regenerated:!0,pushed:await Q(V(),`fix(deps): regenerate the lock file
|
|
26
|
+
|
|
27
|
+
The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ea,P as Fa,X as Ga,_ as Ha,F as Ia,M as Ja,c as Ka};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{zh as U}from"./chunk-e68nf7cm.js";import{Fh as f}from"./chunk-hfjywbbc.js";var{Glob:u}=globalThis.Bun;import{readdir as m}from"fs/promises";import{join as P,relative as l}from"path";import O from"process";var c=new Set(["node_modules","vendor","target",".git",".venv","venv","dist","build","__pycache__",".next",".cache"]);function W(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function L(z,H,$=4){let X=H.map((K)=>new u(K)),Z=[];async function J(K,G){if(G>$)return;let V=await m(K,{withFileTypes:!0}).catch(()=>[]);for(let Q of V){let j=P(K,Q.name);if(Q.isDirectory()){if(!c.has(Q.name)&&!Q.name.startsWith("."))await J(j,G+1);continue}let q=l(z,j);if(X.some((Y)=>Y.match(Q.name)||Y.match(q)))Z.push(q)}}return await J(z,0),Z.sort()}async function M(z,H){let $=[],X=[];for(let Z of H){if(!await Bun.file(P(z,Z.lockfile)).exists())continue;let[J]=Z.command;if(!await E(J)){X.push(`${Z.lockfile} (needs \`${Z.command.join(" ")}\`)`);continue}if(await Bun.spawn(Z.command,{cwd:z,stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??"",HOME:O.env.HOME??""}}).exited===0)$.push(Z.lockfile);else X.push(`${Z.lockfile} (\`${Z.command.join(" ")}\` failed)`)}return{regenerated:$,...X.length>0?{note:`These lockfiles were not regenerated and need updating locally: ${X.join(", ")}.`}:{}}}async function E(z){try{return await Bun.spawn(["which",z],{stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??""}}).exited===0}catch{return!1}}function B(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);for(let J=0;J<Math.max(X.length,Z.length);J++){let K=(X[J]??0)-(Z[J]??0);if(K!==0)return K}return 0}function C(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);if((X[0]??0)!==(Z[0]??0))return"major";if((X[1]??0)!==(Z[1]??0))return"minor";return"patch"}var p=/^\s*(?:require\s+)?([\w.~-]+(?:\.[\w.~-]+)*\/[^\s]+)\s+(v[\w.+-]+)\s*(\/\/.*)?$/,R=/^v\d+\.\d+\.\d+-\d{14}-[a-f0-9]{12}$/,I={name:"go",manifestPatterns:["go.mod"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[],X=!1;for(let Z of H.split(`
|
|
3
3
|
`)){let J=Z.trim();if(/^require\s*\($/.test(J)){X=!0;continue}if(X&&J===")"){X=!1;continue}if(!X&&!J.startsWith("require "))continue;let K=p.exec(Z);if(!K)continue;let[,G,V,Q]=K;if(Q?.includes("indirect"))continue;if(R.test(V))continue;$.push({name:G,currentVersion:V,section:"require",file:z})}return $},async latest(z,H={}){let $=H.registryUrl??"https://proxy.golang.org",X=z.name.replace(/[A-Z]/g,(K)=>`!${K.toLowerCase()}`),Z=await U(`${$}/${X}/@latest`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!Z?.ok)return null;let J=await Z.json().catch(()=>null);if(!J?.Version)return null;if(R.test(J.Version))return null;return{latest:J.Version,...J.Time?{publishedAt:new Date(J.Time)}:{},releaseNotesUrl:`https://pkg.go.dev/${z.name}@${J.Version}`,homepage:`https://pkg.go.dev/${z.name}`}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion);return z.replace(new RegExp(`^(\\s*(?:require\\s+)?${$}\\s+)${X}(\\s|$)`,"gm"),`$1${H.newVersion}$2`)},async postWrite(z){return M(z,[{lockfile:"go.sum",command:["go","mod","tidy"]}])},osvEcosystem:"Go",compareVersions:B,updateType:C};var s=/^\s*v?(?:(\d+)!)?(\d+(?:\.\d+)*)((?:[-_.]?(?:a|b|c|rc|alpha|beta|pre|preview)[-_.]?\d*)?)((?:[-_.]?(?:post|rev|r)[-_.]?\d*|-\d+)?)((?:[-_.]?dev[-_.]?\d*)?)(?:\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?\s*$/i,i={a:"a",alpha:"a",b:"b",beta:"b",c:"rc",rc:"rc",pre:"rc",preview:"rc"},v={a:0,b:1,rc:2};function S(z){let H=s.exec(z);if(!H)return null;let[,$,X,Z,J,K,G]=H,V={epoch:$?Number($):0,release:X.split(".").map(Number)};if(Z){let Q=/([a-z]+)[-_.]?(\d*)/i.exec(Z);if(Q){let j=i[Q[1].toLowerCase()];if(j)V.pre=[j,Q[2]?Number(Q[2]):0]}}if(J){let Q=/(\d+)/.exec(J);V.post=Q?Number(Q[1]):0}if(K){let Q=/(\d+)/.exec(K);V.dev=Q?Number(Q[1]):0}if(G)V.local=G.toLowerCase();return V}function d(z,H){for(let $=0;$<Math.max(z.length,H.length);$++){let X=(z[$]??0)-(H[$]??0);if(X!==0)return X}return 0}function A(z,H){let $=S(z),X=S(H);if(!$||!X)return z===H?0:z<H?-1:1;if($.epoch!==X.epoch)return $.epoch-X.epoch;let Z=d($.release,X.release);if(Z!==0)return Z;let J=(Q)=>{if(Q.dev!==void 0&&Q.pre===void 0&&Q.post===void 0)return 0;if(Q.pre!==void 0)return 1;if(Q.post!==void 0)return 3;return 2},K=J($)-J(X);if(K!==0)return K;if($.pre&&X.pre){let Q=v[$.pre[0]]-v[X.pre[0]];if(Q!==0)return Q;if($.pre[1]!==X.pre[1])return $.pre[1]-X.pre[1]}if(($.post??0)!==(X.post??0))return($.post??0)-(X.post??0);let G=$.dev??Number.POSITIVE_INFINITY,V=X.dev??Number.POSITIVE_INFINITY;if(G!==V)return G<V?-1:1;return 0}function g(z){let H=S(z);return Boolean(H&&(H.pre!==void 0||H.dev!==void 0))}function D(z,H){let $=S(z),X=S(H);if(!$||!X)return"patch";if($.epoch!==X.epoch||($.release[0]??0)!==(X.release[0]??0))return"major";if(($.release[1]??0)!==(X.release[1]??0))return"minor";return"patch"}function N(z){let H=/^\s*(~=|===|==|!=|<=|>=|<|>|\^)?\s*(.*)$/.exec(z.trim());if(!H)return{operator:"",version:z.trim()};return{operator:H[1]??"",version:H[2].trim()}}var b=/^\s*([A-Z0-9][\w.-]*)\s*(\[[^\]]*\])?\s*([<>=!~^].*?)?\s*(?:;.*)?$/i,o=/^\s*(?:-|#|$)/;function r(z,H){let $=[];return H.split(`
|
|
4
4
|
`).forEach((X)=>{let Z=X.split("#")[0];if(o.test(Z))return;let J=b.exec(Z);if(!J?.[1]||!J[3])return;$.push({name:J[1],currentVersion:J[3].trim(),section:"dependencies",file:z,...J[2]?{metadata:{extras:J[2]}}:{}})}),$}var a=[[/^\s*dependencies\s*=\s*\[/m,"dependencies"],[/^\s*(?:dev-dependencies|dev)\s*=\s*\[/m,"devDependencies"]];function n(z,H){let $=[],X=new Set,Z=(K,G,V)=>{let Q=`${V}:${K}`;if(!G.trim()||G.trim()==="*"||X.has(Q))return;X.add(Q),$.push({name:K,currentVersion:G.trim(),section:V,file:z})};for(let[K,G]of a){let V=K.exec(H);if(!V)continue;let Q=V.index+V[0].length,j=H.indexOf("]",Q);if(j===-1)continue;for(let q of H.slice(Q,j).matchAll(/["']([^"']+)["']/g)){let Y=b.exec(q[1]);if(Y?.[1]&&Y[3])Z(Y[1],Y[3],G)}}let J=H.matchAll(/\[tool\.poetry\.(?:group\.[\w-]+\.)?(dependencies|dev-dependencies)\]([\s\S]*?)(?=\n\[|$)/g);for(let K of J){let G=K[1]==="dependencies"?"dependencies":"devDependencies";for(let V of K[2].matchAll(/^\s*([A-Z0-9][\w.-]*)\s*=\s*(.+)$/gim)){let Q=V[1];if(Q.toLowerCase()==="python")continue;let j=V[2].trim(),q=/version\s*=\s*["']([^"']+)["']/.exec(j),Y=/^["']([^"']+)["']/.exec(j),F=q?.[1]??Y?.[1];if(F)Z(Q,F,G)}}return $}var w={name:"python",manifestPatterns:["pyproject.toml","requirements.txt","requirements-*.txt","requirements/*.txt"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){return z.endsWith(".toml")?n(z,H):r(z,H)},async latest(z,H={}){let $=H.registryUrl??"https://pypi.org",X=await U(`${$}/pypi/${encodeURIComponent(z.name)}/json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Z?.info?.version)return null;let J=Z.info.version;if(H.includePrerelease&&Z.releases){let V=Object.keys(Z.releases).filter((Q)=>!Z.releases[Q]?.every((j)=>j.yanked)).sort(A);J=V[V.length-1]??J}let G=Z.releases?.[J]?.find((V)=>V.upload_time_iso_8601)?.upload_time_iso_8601;return{latest:J,...G?{publishedAt:new Date(G)}:{},...Z.info.yanked?{deprecated:!0}:{},...Z.info.project_urls?.Changelog?{releaseNotesUrl:Z.info.project_urls.Changelog}:{},...Z.info.home_page?{homepage:Z.info.home_page}:{}}},applyUpdate(z,H){let{operator:$}=N(H.currentVersion),X=W(H.name),Z=W(H.currentVersion),J=N(H.newVersion).version,K=$?`${$}${J}`:J;return z.replace(new RegExp(`(^|["'\\s])(${X})(\\[[^\\]]*\\])?\\s*${Z}`,"gim"),(G,V,Q,j)=>`${V}${Q}${j??""}${K}`).replace(new RegExp(`^(\\s*${X}\\s*=\\s*["'])${Z}(["'])`,"gim"),`$1${K}$2`).replace(new RegExp(`^(\\s*${X}\\s*=\\s*\\{[^}]*version\\s*=\\s*["'])${Z}(["'])`,"gim"),`$1${K}$2`)},async postWrite(z){return M(z,[{lockfile:"uv.lock",command:["uv","lock"]},{lockfile:"poetry.lock",command:["poetry","lock","--no-update"]}])},osvEcosystem:"PyPI",compareVersions:A,updateType:D};var t=/^\s*gem\s+["']([\w-]+)["']\s*(?:,\s*["']([^"']+)["'])?/,e=/^\s*group\s+(.+?)\s+do\s*$/,zz=/^\s*end\s*$/,x={name:"ruby",manifestPatterns:["Gemfile","*.gemspec"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[],X=[];for(let Z of H.split(`
|
|
5
5
|
`)){let J=Z.replace(/#.*$/,""),K=e.exec(J);if(K){X.push(K[1].replace(/[:'",\s]/g,"")||"default");continue}if(zz.test(J)){X.pop();continue}let G=t.exec(J);if(!G?.[1])continue;if(!G[2])continue;if(/\b(?:path|git|github|branch):/.test(J))continue;$.push({name:G[1],currentVersion:G[2],section:X.length>0?X[X.length-1]:"dependencies",file:z})}return $},async latest(z,H={}){let $=H.registryUrl??"https://rubygems.org",X=await U(`${$}/api/v1/versions/${encodeURIComponent(z.name)}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Array.isArray(Z)||Z.length===0)return null;let J=Z.filter((G)=>G.number&&!G.yanked).filter((G)=>H.includePrerelease?!0:!G.prerelease).sort((G,V)=>B(G.number,V.number)),K=J[J.length-1];if(!K?.number)return null;return{latest:K.number,...K.created_at?{publishedAt:new Date(K.created_at)}:{},homepage:`${$}/gems/${z.name}`}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion),Z=/^\s*(~>|>=|<=|>|<|=)?\s*/.exec(H.currentVersion)?.[1]??"",J=Z?`${Z} ${H.newVersion}`:H.newVersion;return z.replace(new RegExp(`^(\\s*gem\\s+["']${$}["']\\s*,\\s*["'])${X}(["'])`,"gm"),`$1${J}$2`)},async postWrite(z){return M(z,[{lockfile:"Gemfile.lock",command:["bundle","lock","--update"]}])},osvEcosystem:"RubyGems",compareVersions:B,updateType:C};var Hz=[[/^\[dependencies\]/m,"dependencies"],[/^\[dev-dependencies\]/m,"devDependencies"],[/^\[build-dependencies\]/m,"buildDependencies"],[/^\[workspace\.dependencies\]/m,"workspaceDependencies"]],T={name:"rust",manifestPatterns:["Cargo.toml"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[];for(let[X,Z]of Hz){let J=X.exec(H);if(!J)continue;let K=J.index+J[0].length,G=H.slice(K).search(/\n\[/),V=G===-1?H.slice(K):H.slice(K,K+G);for(let Q of V.matchAll(/^\s*([\w-]+)\s*=\s*(.+)$/gm)){let j=Q[1],q=Q[2].trim(),Y=/version\s*=\s*["']([^"']+)["']/.exec(q),F=/^["']([^"']+)["']/.exec(q),_=Y?.[1]??F?.[1];if(!_||/\b(?:path|git)\s*=/.test(q))continue;$.push({name:j,currentVersion:_,section:Z,file:z})}}return $},async latest(z,H={}){let $=H.registryUrl??"https://crates.io",X=await U(`${$}/api/v1/crates/${encodeURIComponent(z.name)}`,{headers:{"User-Agent":"buddy (https://buddy.sh)",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Z?.crate)return null;let J=H.includePrerelease?Z.crate.newest_version??Z.crate.max_stable_version:Z.crate.max_stable_version??Z.crate.newest_version;if(!J)return null;let K=Z.versions?.find((G)=>G.num===J);if(K?.yanked)return null;return{latest:J,...K?.created_at?{publishedAt:new Date(K.created_at)}:{},...Z.crate.repository?{releaseNotesUrl:`${Z.crate.repository}/releases`}:{},...Z.crate.homepage?{homepage:Z.crate.homepage}:{}}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion);return z.replace(new RegExp(`^(\\s*${$}\\s*=\\s*["'])${X}(["'])`,"gm"),`$1${H.newVersion}$2`).replace(new RegExp(`^(\\s*${$}\\s*=\\s*\\{[^}]*?version\\s*=\\s*["'])${X}(["'])`,"gm"),`$1${H.newVersion}$2`)},async postWrite(z){return M(z,[{lockfile:"Cargo.lock",command:["cargo","update","--workspace"]}])},osvEcosystem:"crates.io",compareVersions:B,updateType:C};import{join as Xz}from"path";async function Zz(z){let H=z.logger??f(),$=z.adapters??k,X=new Set(z.ignore??[]),Z=[],J={},K=[];return await Promise.all($.map(async(G)=>{let V;try{V=await G.detect(z.dir)}catch(Q){H.warn(`\u26A0\uFE0F ${G.name}: could not look for manifests: ${Q}`);return}if(V.length===0)return;K.push({ecosystem:G.name,files:V}),H.debug(`\uD83D\uDCE6 ${G.name}: ${V.length} manifest(s)`);for(let Q of V){let j;try{j=await G.parse(Q,await Bun.file(Xz(z.dir,Q)).text())}catch(Y){H.warn(`\u26A0\uFE0F ${G.name}: could not parse ${Q}: ${Y}`);continue}J[G.name]=(J[G.name]??0)+j.length;let q=await Promise.all(j.map(async(Y)=>{if(X.has(Y.name))return null;try{let F=await G.latest(Y,{...z.includePrerelease!==void 0?{includePrerelease:z.includePrerelease}:{},logger:H});if(!F)return null;let _=y(Y.currentVersion);if(G.compareVersions(F.latest,_)<=0)return null;return{name:Y.name,currentVersion:Y.currentVersion,newVersion:F.latest,updateType:G.updateType(_,F.latest),dependencyType:G.name,file:Q,...F.releaseNotesUrl?{releaseNotesUrl:F.releaseNotesUrl}:{},...F.homepage?{homepage:F.homepage}:{}}}catch(F){return H.debug(`${G.name}: could not resolve ${Y.name}: ${F}`),null}}));Z.push(...q.filter((Y)=>Y!==null))}})),{updates:Z,dependenciesByEcosystem:J,manifests:K}}function y(z){let H=/(\d[\w.!+-]*)/.exec(z);return H?H[1]:z.trim()}async function $z(z,H,$=k){let X=[],Z=[];for(let J of $){if(!H.includes(J.name)||!J.postWrite)continue;let K=await J.postWrite(z).catch(()=>({regenerated:[],note:void 0}));if(X.push(...K.regenerated),K.note)Z.push(K.note)}return{regenerated:X,notes:Z}}var k=[w,T,I,x];function Ez(z,H=k){let $=z.split("/").pop()??z;for(let X of H)if(X.manifestPatterns.some((Z)=>h($,Z)||h(z,Z)))return X;return null}function h(z,H){if(!H.includes("*"))return z===H;let $=H.split("*").map((X)=>X.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join("[^/]*");return new RegExp(`^${$}$`).test(z)}function Rz(z,H=k){return H.find(($)=>$.name===z)??null}
|
|
6
|
-
export{W as
|
|
6
|
+
export{W as oc,L as pc,M as qc,E as rc,B as sc,C as tc,I as uc,S as vc,A as wc,g as xc,D as yc,N as zc,w as Ac,x as Bc,T as Cc,k as Dc,Ez as Ec,Rz as Fc,Zz as Gc,y as Hc,$z as Ic};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{_c as a}from"./chunk-dqbk3kcj.js";import"./chunk-phfmnnne.js";import"./chunk-r763e19p.js";import"./chunk-be629jhq.js";import"./chunk-pkr6905p.js";import"./chunk-eseshkd0.js";import"./chunk-11hdrnf6.js";import"./chunk-mkzmjg3f.js";import"./chunk-p8tmms5h.js";import"./chunk-ytmxd5fk.js";import"./chunk-b9escac0.js";import"./chunk-g30dr44w.js";import"./chunk-2et8yavs.js";import"./chunk-txtrpypt.js";import"./chunk-8hjvthz4.js";import"./chunk-yngahb11.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as Buddy};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{C as
|
|
2
|
+
import{Wf as T}from"./chunk-0hc97k0t.js";import{Fh as B}from"./chunk-hfjywbbc.js";import{Wk as W}from"./chunk-q4t568hv.js";import{spawn as X}from"child_process";import{existsSync as J}from"fs";import U from"process";function C(){return["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","pantry.lock"]}function Y(b){switch(b){case"bun":return{command:"bun",args:["install"]};case"npm":return{command:"npm",args:["install"]};case"yarn":return{command:"yarn",args:["install"]};case"pnpm":return{command:"pnpm",args:["install"]};case"composer":return{command:"composer",args:["update","--lock"]}}}async function F(b,q,z=300000){let{command:E,args:K}=Y(b);return B().info(`\uD83D\uDD04 Regenerating lock file with ${b} (${E} ${K.join(" ")})...`),new Promise((H)=>{let G=X(E,K,{cwd:q,stdio:"pipe",env:{...U.env,CI:"true"}}),V="",O="",Q=!1,R=setTimeout(()=>{Q=!0,B().warn(`\u26A0\uFE0F ${b} install timed out after ${z/1000}s, sending SIGTERM...`),G.kill("SIGTERM"),setTimeout(()=>{if(!G.killed)B().warn(`\u26A0\uFE0F ${b} install did not exit after SIGTERM, sending SIGKILL...`),G.kill("SIGKILL")},1e4)},z);G.stdout?.on("data",(A)=>{V+=A.toString()}),G.stderr?.on("data",(A)=>{O+=A.toString()}),G.on("close",(A)=>{if(clearTimeout(R),Q){H({success:!1,packageManager:b,message:`Lock file regeneration timed out after ${z/1000}s`});return}if(A===0)B().info(`\u2705 Lock file regenerated successfully with ${b}`),H({success:!0,packageManager:b,message:"Lock file regenerated successfully"});else{if(B().warn(`\u26A0\uFE0F ${b} install exited with code ${A}`),O)B().warn(` stderr: ${O.slice(0,500)}`);H({success:!1,packageManager:b,message:`Install exited with code ${A}: ${O.slice(0,200)}`})}}),G.on("error",(A)=>{clearTimeout(R),B().warn(`\u26A0\uFE0F Failed to run ${E}: ${A.message}`),H({success:!1,packageManager:b,message:`Failed to run ${E}: ${A.message}`})})})}function N(b){let q=new Set;for(let z of b){let E=z.split("/").pop()||"";if(E==="package.json"){let K=U.cwd(),H=T(K);q.add(H)}if(E==="composer.json")q.add("composer")}return Array.from(q)}function P(b,q){let z=W("path");switch(b){case"bun":return J(z.join(q,"bun.lock"))||J(z.join(q,"bun.lockb"));case"npm":return J(z.join(q,"package-lock.json"));case"yarn":return J(z.join(q,"yarn.lock"));case"pnpm":return J(z.join(q,"pnpm-lock.yaml"));case"composer":return J(z.join(q,"composer.lock"))}}
|
|
3
|
+
export{C as Kc,F as Lc,N as Mc,P as Nc};
|