blade-code 0.10.139 → 0.10.140
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/dist/blade.js +2 -2
- package/dist/{chunk-6qhbdcse.js → chunk-08z32sky.js} +2 -2
- package/dist/{chunk-mec8yedz.js → chunk-0c2y17xy.js} +1 -1
- package/dist/{chunk-x3c718v5.js → chunk-0kghtvxj.js} +2 -2
- package/dist/{chunk-3eskgvpy.js → chunk-0sx7ak0b.js} +1 -1
- package/dist/{chunk-sj4gz23a.js → chunk-15fpc0qg.js} +1 -1
- package/dist/{chunk-mtfjwsn2.js → chunk-19zsecpx.js} +2 -2
- package/dist/{chunk-7pg5y3pg.js → chunk-1myft5nb.js} +1 -1
- package/dist/chunk-1nreg14s.js +1 -0
- package/dist/{chunk-z9qv0d6k.js → chunk-2d3zksr0.js} +1 -1
- package/dist/{chunk-sdhdn0yx.js → chunk-2ff55pvt.js} +3 -3
- package/dist/{chunk-65c3vjwm.js → chunk-2g8avyq6.js} +1 -1
- package/dist/chunk-3kvt23m3.js +1 -0
- package/dist/chunk-4rh40xhc.js +1 -0
- package/dist/chunk-4xr4hz19.js +2 -0
- package/dist/{chunk-zz5n2qxk.js → chunk-50m1czz9.js} +1 -1
- package/dist/{chunk-earhezc8.js → chunk-5cw3bevx.js} +1 -1
- package/dist/{chunk-9m7d3ajv.js → chunk-5jq1mrqd.js} +1 -1
- package/dist/chunk-61yd46c0.js +1 -0
- package/dist/{chunk-8py443a5.js → chunk-6zxm9pen.js} +1 -1
- package/dist/{chunk-25r1v5rn.js → chunk-7eepxhcp.js} +34 -34
- package/dist/{chunk-jy7k2dwm.js → chunk-85b3kacc.js} +2 -2
- package/dist/chunk-8774agqd.js +1 -0
- package/dist/chunk-8brb7c6j.js +6 -0
- package/dist/{chunk-hrcz179j.js → chunk-8fx20am1.js} +2 -2
- package/dist/{chunk-16648v5c.js → chunk-8vqhcx3s.js} +1 -1
- package/dist/{chunk-6ezffjq1.js → chunk-9ced7jf0.js} +1 -1
- package/dist/chunk-abpmpyqa.js +1 -0
- package/dist/{chunk-yvmexv2c.js → chunk-ascjys4e.js} +1 -1
- package/dist/chunk-bb0z7c3g.js +1 -0
- package/dist/{chunk-5j68055h.js → chunk-c562kd2m.js} +1 -1
- package/dist/{chunk-bgzj85za.js → chunk-cf3dvysj.js} +1 -1
- package/dist/{chunk-bq6d0v5b.js → chunk-cww9pp1q.js} +2 -2
- package/dist/{chunk-7j4s1nrc.js → chunk-d1qe06f0.js} +1 -1
- package/dist/{chunk-40pd090k.js → chunk-e6j4vzta.js} +2 -2
- package/dist/{chunk-3ekz3zms.js → chunk-eh901zhx.js} +2 -2
- package/dist/{chunk-5w8pmsqe.js → chunk-eqe3smcg.js} +2 -2
- package/dist/{chunk-a5hkv8er.js → chunk-es0cbtx1.js} +2 -2
- package/dist/{chunk-gc4kj295.js → chunk-ffkzessq.js} +1 -1
- package/dist/{chunk-dv2m2xe5.js → chunk-g38d2ezm.js} +1 -1
- package/dist/{chunk-v2fewxvw.js → chunk-g4kydkyz.js} +2 -2
- package/dist/{chunk-qrv72yy6.js → chunk-g5scqxq3.js} +2 -2
- package/dist/{chunk-8rccn1y2.js → chunk-gq727fet.js} +1 -1
- package/dist/{chunk-5qwpdx3n.js → chunk-hj1yrssp.js} +1 -1
- package/dist/{chunk-d64b7wta.js → chunk-hvmrcd84.js} +1 -1
- package/dist/{chunk-zx78c1an.js → chunk-kmg8ad2j.js} +1 -1
- package/dist/{chunk-04t21rey.js → chunk-kxwc5wrx.js} +1 -1
- package/dist/chunk-m9dv5177.js +10 -0
- package/dist/{chunk-az08pq83.js → chunk-ma1mn6hn.js} +1 -1
- package/dist/{chunk-t88sfhjj.js → chunk-mnk0b4nz.js} +1 -1
- package/dist/chunk-mwgx87vw.js +1 -0
- package/dist/{chunk-cefmcwyv.js → chunk-n6tvswa8.js} +2 -2
- package/dist/{chunk-fbrdcveb.js → chunk-n8qg68y2.js} +1 -1
- package/dist/chunk-ntq4h4jh.js +1 -0
- package/dist/{chunk-1bqatrxs.js → chunk-nxsarfy6.js} +1 -1
- package/dist/{chunk-ft1bdqbs.js → chunk-pg7cgvs8.js} +2 -2
- package/dist/{chunk-1h3736q2.js → chunk-ppmy3n74.js} +219 -218
- package/dist/{chunk-grx6fv9w.js → chunk-pw9axk0e.js} +2 -2
- package/dist/{chunk-2jq9ed09.js → chunk-pwct7cj7.js} +1 -1
- package/dist/{chunk-esff371k.js → chunk-q9qts6bq.js} +2 -2
- package/dist/chunk-r324qme7.js +1 -0
- package/dist/{chunk-rhwkvx96.js → chunk-r4q06wbs.js} +1 -1
- package/dist/chunk-ra6ksfdy.js +1 -0
- package/dist/{chunk-dw0mewc2.js → chunk-rrtptbzv.js} +2 -2
- package/dist/{chunk-jb4hmk56.js → chunk-svsgtj41.js} +2 -2
- package/dist/{chunk-6j5v5emj.js → chunk-tagzy876.js} +6 -6
- package/dist/{chunk-516adpx6.js → chunk-tecbx0ek.js} +1 -1
- package/dist/chunk-tnts2de5.js +1 -0
- package/dist/chunk-w0710yj4.js +1 -0
- package/dist/{chunk-npc7jt96.js → chunk-w2m4yczv.js} +1 -1
- package/dist/{chunk-mh3ne2sf.js → chunk-w5057h27.js} +2 -2
- package/dist/chunk-we13xwds.js +180 -0
- package/dist/{chunk-f4cn6v8t.js → chunk-xagh2qb6.js} +2 -2
- package/dist/{chunk-05cv54r8.js → chunk-y5bqd8gh.js} +1 -1
- package/dist/{chunk-awheqy52.js → chunk-zfaenqqx.js} +2 -2
- package/dist/chunk-zp5097qk.js +2 -0
- package/dist/web/assets/ChatView-BlAGPVC-.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-CYhxXWvb.js → CodeBlockHighlighter-BM1MZv6w.js} +1 -1
- package/dist/web/assets/{FilePreview-ByTaE1GR.js → FilePreview-P77KS9tr.js} +1 -1
- package/dist/web/assets/{KanbanBoard-KMmGvNPc.js → KanbanBoard-B0c7sE2y.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C6lKOJaG.js → MarkdownRenderer-DHa0FqU0.js} +3 -3
- package/dist/web/assets/{ScrollArea-Bo6cZ3PH.js → ScrollArea-C6yf2fqq.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-Cymc4xw0.js → SessionHistorySurface-CXYBWqlN.js} +1 -1
- package/dist/web/assets/{SettingsModal-D36xhHwa.js → SettingsModal-BVjVlENY.js} +1 -1
- package/dist/web/assets/{Sidebar-DEGQINYb.js → Sidebar-DDW9Xs6e.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BEISb7-8.js → TaskSwitcher-D74_5q1F.js} +1 -1
- package/dist/web/assets/{TerminalPanel-B7PXaRGh.js → TerminalPanel-DNEKapEi.js} +1 -1
- package/dist/web/assets/{archive-Dyn5Oz68.js → archive-Ao0WD7pU.js} +1 -1
- package/dist/web/assets/{arrow-left-mWU3P1zb.js → arrow-left-a5_iLemp.js} +1 -1
- package/dist/web/assets/{calendar-clock-B6b0Cb3d.js → calendar-clock-BKbdz6Cu.js} +1 -1
- package/dist/web/assets/{chevron-right-Cl6g5_0e.js → chevron-right-8qYRfCj4.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-FKryGzO4.js → chevrons-up-down-BXNG4GvK.js} +1 -1
- package/dist/web/assets/{clock-3-CfVjvMmA.js → clock-3-DEL1ixyh.js} +1 -1
- package/dist/web/assets/{copy-CIYuf7du.js → copy-Bd5v-KkM.js} +1 -1
- package/dist/web/assets/{download-DecDFX8n.js → download-CIKvpDBW.js} +1 -1
- package/dist/web/assets/{external-link-DaSwvjf7.js → external-link-B33h3DQN.js} +1 -1
- package/dist/web/assets/{folder-DZtlKvFm.js → folder-lOczceoh.js} +1 -1
- package/dist/web/assets/index-hZ37pkxs.js +203 -0
- package/dist/web/assets/{pause-Bd-STGLc.js → pause-nnvVbgsj.js} +1 -1
- package/dist/web/assets/{pencil-BoTIqqxX.js → pencil-_yfoOmUq.js} +1 -1
- package/dist/web/assets/{play-C4ctis0t.js → play-BilJ7SDs.js} +1 -1
- package/dist/web/assets/{plus-D08TlGJu.js → plus-BqqpYKaK.js} +1 -1
- package/dist/web/assets/{session-events-DKjIMNKI.js → session-events-FPOvcMBw.js} +19 -19
- package/dist/web/assets/{settings-BGRhMFaU.js → settings-CmJXtYTH.js} +1 -1
- package/dist/web/assets/{team-CPme0l2K.js → team-Bb04o2Tb.js} +1 -1
- package/dist/web/assets/{teamService-CVCtTVfY.js → teamService-B5w9cpsa.js} +1 -1
- package/dist/web/assets/{terminal-D7GsyYki.js → terminal-DOjdChj0.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2agbk8ef.js +0 -1
- package/dist/chunk-2bty4510.js +0 -6
- package/dist/chunk-2f7nr9hh.js +0 -1
- package/dist/chunk-2t9vtt75.js +0 -1
- package/dist/chunk-3aaehgva.js +0 -1
- package/dist/chunk-3t5r41yh.js +0 -1
- package/dist/chunk-5xgyx25z.js +0 -2
- package/dist/chunk-gjc1hhhv.js +0 -1
- package/dist/chunk-gx4seq5c.js +0 -10
- package/dist/chunk-h2gp7smy.js +0 -1
- package/dist/chunk-mc2mr1kn.js +0 -2
- package/dist/chunk-mkckss82.js +0 -1
- package/dist/chunk-ntpwqfy3.js +0 -1
- package/dist/chunk-q82ntq7t.js +0 -1
- package/dist/chunk-recafw5r.js +0 -171
- package/dist/chunk-smjfqtws.js +0 -1
- package/dist/chunk-wazhd8bm.js +0 -1
- package/dist/chunk-wf4s1hp2.js +0 -1
- package/dist/web/assets/ChatView-CQnuGDqk.js +0 -63
- package/dist/web/assets/index-DQaqO-lw.js +0 -203
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Xj as C,Yj as I}from"./chunk-earhezc8.js";import{Zj as _}from"./chunk-t88sfhjj.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
1
|
+
import{$j as I,_j as C}from"./chunk-5cw3bevx.js";import{ak as _}from"./chunk-mnk0b4nz.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
|
|
2
2
|
`,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
|
|
3
|
-
export{R as
|
|
3
|
+
export{R as Xj,t as Yj,x as Zj};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{of as a,pf as b}from"./chunk-rrtptbzv.js";import"./chunk-19zsecpx.js";import"./chunk-tecbx0ek.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{p as RH,q as gH,r as kH,s as CH,t as hH,u as OH}from"./chunk-y5bqd8gh.js";import{B as IH,C as VH,D as ZH,E as $H,F as l,G as qH}from"./chunk-15fpc0qg.js";import{H as BH,ca as EH,ea as MH,fa as zH,ja as fH}from"./chunk-ppmy3n74.js";import"./chunk-8vqhcx3s.js";import"./chunk-pwct7cj7.js";import{$a as NH}from"./chunk-4xr4hz19.js";import{Kb as t,Wb as PH,ec as FH}from"./chunk-we13xwds.js";import"./chunk-0sx7ak0b.js";import{Pd as _H,Td as GH,Vd as u,ee as n}from"./chunk-n6tvswa8.js";import"./chunk-kmg8ad2j.js";import"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import{of as SH}from"./chunk-rrtptbzv.js";import{qf as TH,rf as yH,sf as bH}from"./chunk-w5057h27.js";import{tf as AH}from"./chunk-g4kydkyz.js";import"./chunk-08z32sky.js";import{Tf as UH}from"./chunk-0kghtvxj.js";import"./chunk-v508x7cg.js";import"./chunk-c562kd2m.js";import"./chunk-pw9axk0e.js";import"./chunk-cww9pp1q.js";import"./chunk-8fx20am1.js";import"./chunk-hvmrcd84.js";import"./chunk-eqe3smcg.js";import"./chunk-xagh2qb6.js";import{ih as YH}from"./chunk-ascjys4e.js";import"./chunk-r4q06wbs.js";import"./chunk-ma1mn6hn.js";import"./chunk-2ff55pvt.js";import"./chunk-nxsarfy6.js";import"./chunk-e6j4vzta.js";import{Oi as jH}from"./chunk-w2m4yczv.js";import{Ti as s,Ui as r}from"./chunk-zp5097qk.js";import{Yi as C}from"./chunk-g38d2ezm.js";import"./chunk-n8qg68y2.js";import{Aj as xH,Cj as H,Dj as XH,Fj as Y}from"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import"./chunk-2g8avyq6.js";import"./chunk-19zsecpx.js";import"./chunk-85b3kacc.js";import"./chunk-5cw3bevx.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";import cJ from"yargs";import{hideBin as uJ}from"yargs/helpers";function a(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function lH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{a(V,"drain",x),a(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function aH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await lH(V,Q)}class i{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new l("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new qH({maxPendingItems:Z.maxPendingItems??VH,maxPendingBytes:Z.maxPendingBytes??ZH,writeTimeoutMs:Z.writeTimeoutMs??$H,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>aH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new l("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))a(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var iH=L({type:H.Literal("content_delta"),delta:H.String()}),oH=L({type:H.Literal("thinking_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking"),content:H.String()}),rH=L({type:H.Literal("stream_end")}),nH=L({type:H.Literal("content"),content:H.String()}),tH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),o=Y(["readonly","write","execute"]),eH=H.Object({kind:o,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),HJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o)}),JJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(eH)}),KJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),VJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(KJ)}),ZJ=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),$J=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),XJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),YJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),BJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),QJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),DJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),LJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),WJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),jJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),xJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),UJ=L({type:H.Literal("task_update"),tasks:H.Array(BH)}),_J=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),GJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(YH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),FJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),EJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(NH)}),MJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),zJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),fJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),c=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),QH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),SJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:QH},{additionalProperties:!1}))},{additionalProperties:!1}),TJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([SJ,H.Null()])},{additionalProperties:!1}),yJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),bJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(yJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),IJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([bJ,H.Null()])},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:QH},{additionalProperties:!1}),gJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),kJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),CJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),hJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),OJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),wJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),mJ=L({type:H.Literal("error"),message:H.String()}),BK=XH(H.Union([iH,oH,sH,rH,nH,tH,HJ,JJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,zJ,fJ,MJ,AJ,TJ,IJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ]));function DH(V,Z){return{event_version:k,type:V,...Z}}function dJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function pJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var vJ=Y(["text","jsonl"]),lJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(jH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(vJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class wH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function aJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function iJ(V){let Z=xH(lJ,V);if(!Z.success)throw Error(`Invalid headless options: ${aJ(Z.error)}`);return Z.data}function oJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await HK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
|
|
2
|
+
`)}function sJ(V){return`[task] [${V.status}] ${V.subject}`}function rJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function nJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function tJ(V){return V==="jsonl"?"jsonl":"text"}function LH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function eJ(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function WH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(DH(J,K))}
|
|
3
|
+
`)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
|
|
4
|
+
`);if(J)V.stdout.write(`
|
|
5
|
+
`)},content(J){if(Z==="jsonl"){q("content",{content:J});return}W(V.stdout,J)},structuredOutput(J){if(Z==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}W(V.stdout,JSON.stringify(J.output))},toolStart(J,K,D,x){if(Z==="jsonl"){q("tool_start",{tool_name:J,summary:K,target:D,tool_kind:x});return}W(V.stderr,`[tool:start] ${K}`)},toolProgress(J,K,D,x,j){if(Z==="jsonl"){q("tool_progress",{tool_name:J,message:K,progress:D,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}W(V.stderr,`[tool:progress] ${J}: ${K}`)},toolResult(J,K,D,x,j){if(Z==="jsonl"){q("tool_result",{tool_name:J,summary:K,target:D,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}W(V.stderr,`[tool:result] ${K}`)},mcpCatalogChanged(J){if(Z==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(Z==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(Z==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}W(V.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(Z==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}W(V.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(Z==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}W(V.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(Z==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}W(V.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(Z==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}W(V.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(Z==="jsonl"){q("project_rules_loaded",{files:J.files.map((K)=>({id:K.id,relative_path:K.relativePath,source:K.source,conditional:K.conditional,content_sha256:K.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}W(V.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,K,D){if(Z==="jsonl"){q("user_shell_started",{execution_id:J,command:K,auxiliary:D});return}W(V.stderr,`[user-shell:start] ${K}`)},userShellOutput(J,K,D,x){if(Z==="jsonl"){q("user_shell_output",{execution_id:J,stream:K,chunk:D,stream_truncated:x});return}(K==="stderr"?V.stderr:V.stdout).write(D)},userShellCompleted(J){if(Z==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}W(V.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,K,D,x={}){if(Z==="jsonl"){q("phase",{phase:J,status:K,message:D,turn:x.turn,tool_name:x.toolName,target:x.target});return}W(V.stderr,`[phase:${J}] ${D}`)},toolDetail(J,K){if(Z==="jsonl"){q("tool_detail",{tool_name:J,detail:K});return}W(V.stderr,K)},taskUpdate(J){if(Z==="jsonl"){q("task_update",{tasks:J});return}for(let K of J)W(V.stderr,sJ(K))},goalFrontier(J){if(Z==="jsonl"){q("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let K=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";W(V.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${K}`)},turnRecovery(J){let K=J.assessment;if(Z==="jsonl"){q("turn_recovery",{state:K.state,turn_id:K.turnId,input_message_count:K.inputMessageCount,reason:K.state==="requires_attention"?K.reason:void 0});return}W(V.stderr,`[turn-recovery:${K.state}] ${K.turnId}`)},goal(J){if(Z==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount});return}if(J.goal)W(V.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else W(V.stderr,"[goal:cleared]")},subagent(J){let K=J.kind==="subagent_spawned";if(Z==="jsonl"){q("subagent",{state:K?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:K?void 0:J.success,summary:K?void 0:J.summary,verification_verdict:K?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}W(V.stderr,`[subagent:${K?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(Z==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}W(V.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let K=J.phase==="start";if(Z==="jsonl"){q("compacting",{state:K?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason,memory:J.memory});return}W(V.stderr,K?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}${J.memory?.outcome==="written"?`; saved ${J.memory.entries} project memories`:""}`)},providerAdmission(J){if(Z==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}W(V.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(Z==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let K=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";W(V.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${K}`)},providerCircuit(J){if(Z==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let K=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";W(V.stderr,`[provider-circuit:${J.phase}] ${J.reason}${K}`)},providerStall(J){if(Z==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}W(V.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},providerRecovery(J){let K=J.recovery.snapshot;if(Z==="jsonl"){q("provider_recovery",{generation:J.recovery.generation,revision:J.recovery.revision,snapshot:K?{activity:K.activity,reason:K.reason,updated_at:K.updatedAt,next_action_at:K.nextActionAt,retry:K.retry?{attempt:K.retry.attempt,max_retries:K.retry.maxRetries,status_code:K.retry.statusCode,delay_ms:K.retry.delayMs,recovery_budget_ms:K.retry.recoveryBudgetMs,recovery_elapsed_ms:K.retry.recoveryElapsedMs,recovery_remaining_ms:K.retry.recoveryRemainingMs}:void 0,admission:K.admission?{request_class:K.admission.requestClass,scope:K.admission.scope,resource:K.admission.resource,queue_position:K.admission.queuePosition,queue_depth:K.admission.queueDepth,in_flight:K.admission.inFlight,limit:K.admission.limit,wait_ms:K.admission.waitMs,max_wait_ms:K.admission.maxWaitMs,recovery_remaining_ms:K.admission.recoveryRemainingMs}:void 0,circuit:K.circuit?{phase:K.circuit.phase,status_code:K.circuit.statusCode,retry_after_ms:K.circuit.retryAfterMs,next_probe_at:K.circuit.nextProbeAt,open_duration_ms:K.circuit.openDurationMs,sample_count:K.circuit.sampleCount,failure_count:K.circuit.failureCount,recovery_remaining_ms:K.circuit.recoveryRemainingMs}:void 0,stall:K.stall?{stall_count:K.stall.stallCount,duration_ms:K.stall.durationMs,warning_after_ms:K.stall.warningAfterMs,timeout_ms:K.stall.timeoutMs,output_started:K.stall.outputStarted}:void 0,fallback:K.fallback?{from:K.fallback.from,to:K.fallback.to,candidate:K.fallback.candidate,candidate_count:K.fallback.candidateCount,trigger:K.fallback.trigger.source==="retry"||K.fallback.trigger.source==="circuit"?{source:K.fallback.trigger.source,reason:K.fallback.trigger.reason,status_code:K.fallback.trigger.statusCode}:K.fallback.trigger}:void 0}:null});return}W(V.stderr,K?`[provider-recovery:${K.activity}] ${K.reason}`:"[provider-recovery:clear]")},turnActivity(J){if(Z!=="jsonl")return;let K=J.activity.snapshot;q("turn_activity",{generation:J.activity.generation,revision:J.activity.revision,snapshot:K?{phase:K.phase,started_at:K.startedAt,updated_at:K.updatedAt,turn:K.turn,max_turns:K.maxTurns,output_started:K.outputStarted,tool_calls_started:K.toolCallsStarted,tool_calls_completed:K.toolCallsCompleted,active_tools:K.activeTools.map((D)=>({name:D.name,kind:D.kind,started_at:D.startedAt,progress:D.progress,total:D.total})),active_tool_overflow:K.activeToolOverflow}:null})},modelFallback(J){let K=J.trigger.source==="retry"||J.trigger.source==="circuit"?{source:J.trigger.source,reason:J.trigger.reason,status_code:J.trigger.statusCode}:J.trigger;if(Z==="jsonl"){q("model_fallback",{from:J.from,to:J.to,candidate:J.candidate,candidate_count:J.candidateCount,trigger:K});return}W(V.stderr,`[provider-fallback] ${J.from.model} -> ${J.to.model}`)},actionStationarity(J){if(Z==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}W(V.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(Z==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}W(V.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(Z==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}W(V.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(Z==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}W(V.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,K=0){if(Z==="jsonl"){q("output",{content:J,exit_code:K});return}W(K===0?V.stdout:V.stderr,J)},error(J){if(Z==="jsonl"){q("error",{message:J});return}W(V.stderr,J)}}}async function HK(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new wH,K={targetLocked:!1},D,x,j,P=pJ(Q),T=!1,F=new i(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),d={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=WH(d,q),p=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await p()?N:1};try{let N=iJ(V);q=tJ(N.outputFormat);let y=await hH(N);B=WH(d,q,Boolean(y)),await RH();let e=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await kH({message:N.message,_:N._,stdin:Q?.stdin}):await gH({...N,stdin:Q?.stdin}),M=e===void 0,_=M?{mode:"agent",content:""}:await CH(e);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>s)throw Error(`User prompt exceeds the ${s}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>r)throw Error(`User prompt exceeds the ${r}-byte durable input limit`);let h=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(h!==void 0&&N.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(h!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(N.taskIsolation&&(N.continue||N.resume||N.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:HH,metadata:JH}=await OH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??JH?.permissionMode??"yolo",KH=N.model&&N.model!=="inherit"?N.model:UH()?.id,U=N.taskIsolation?await IH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...KH?{modelId:KH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??JH?.projectPath??C();if(j=t.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let X=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],vH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(X.phase)||!A.includes(X.requestClass)||!S.includes(X.resource)||!I.includes(X.scope)||X.reason!==void 0&&!vH.includes(X.reason)||typeof X.queuePosition!=="number"||typeof X.queueDepth!=="number"||typeof X.inFlight!=="number"||typeof X.limit!=="number"||typeof X.waitMs!=="number"||typeof X.maxWaitMs!=="number"||X.recoveryRemainingMs!==void 0&&typeof X.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,...X.reason!==void 0?{reason:X.reason}:{},queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,...X.recoveryRemainingMs!==void 0?{recoveryRemainingMs:X.recoveryRemainingMs}:{}})}),!U)await n.setSessionPermissionMode(G,z,R);let mH=U?!1:await FH.cancelPendingNonInteractive(z,G);if(U)B.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??C(),isolation:N.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=t.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let cH={messages:mH?await n.loadSessionModelContext(G,z):[...HH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:rJ()};D=await EH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?AH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...HH.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&D.getPendingSteeringCount()>0,O=M&&!g?await D.getGoal():null,w=O?.status==="active"||O?.status==="verifying",v=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&v.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:v}),B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!w?await D.getRecoveredFinalResponse():void 0;if(M&&!g&&!w){if(!b)throw Error("No unfinished turn or active goal to resume");let $=v;if($.state!=="none")B.turnRecovery({kind:"turn_recovery",assessment:$});if(O)B.goal({kind:"goal_updated",goal:O});if(b.structuredOutput&&b.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else B.content(b.content);return B.phase("completed","done","Recovered headless run completed"),await E(0)}if(h!==void 0){let $=await D.executeUserShellCommand(h,{signal:P.signal,onEvent:async(X)=>{if(X.type==="started")B.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")B.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated);await p()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let uH=N.maxTurns??D.getConfig().maxTurns,dH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,pH=await fH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:dH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await PH(pH.chatStream(_.content,cH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...uH===-1?{onTurnLimitReached:async($)=>{return B.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||q==="jsonl")J.markAssistantContent();B.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let X=J.completeStream();B.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=MH(X.function.name,f),S=LH(X.function.name,f),I=eJ(X.function.name,A,S,K);if(I.shouldLockTarget)K.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:X.function.name,target:S}),B.toolStart(X.function.name,A,S,$.toolKind)}catch{B.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),B.toolStart(X.function.name,X.function.name,void 0,$.toolKind)}break}case"tool_progress":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;B.toolProgress(X.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;let f;try{let S=JSON.parse(X.function.arguments);f=LH(X.function.name,S)}catch{f=void 0}let A=GH(zH(X.function.name,$.result),_H);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:dJ($.result.metadata)}),A.detail)B.toolDetail(X.function.name,A.detail);break}case"token_usage":B.tokenUsage($.usage);break;case"compaction":B.compacting($);break;case"task_update":B.taskUpdate($.tasks);break;case"goal_frontier_updated":B.goalFrontier($);break;case"turn_recovery":B.turnRecovery($);break;case"structured_output":B.structuredOutput($);break;case"mcp_catalog_changed":B.mcpCatalogChanged($);break;case"mcp_content_changed":B.mcpContentChanged($);break;case"mcp_resource_updated":B.mcpResourceUpdated($);break;case"mcp_connection_changed":B.mcpConnectionChanged($);break;case"mcp_log":B.mcpLog($);break;case"mcp_instructions_changed":B.mcpInstructionsChanged($);break;case"mcp_task_changed":B.mcpTaskChanged($);break;case"project_rules_loaded":B.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":B.goal($);break;case"subagent_spawned":case"subagent_completed":B.subagent($);break;case"model_fallback":B.modelFallback($);break;case"provider_admission":B.providerAdmission($);break;case"provider_retry":B.providerRetry($);break;case"provider_circuit":B.providerCircuit($);break;case"provider_stall":B.providerStall($);break;case"provider_recovery":B.providerRecovery($);break;case"turn_activity":B.turnActivity($);break;case"action_stationarity":B.actionStationarity($);break;case"turn_start":if($.turn===1)K.targetLocked=!1;B.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let X=$}}await p()});if(m.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(m.metadata?.recoveryAttention)return B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!m.success)return B.error(`Error: ${m.error?.message??"Agent execution failed"}`),await E(1);return B.phase("completed","done","Headless run completed"),await E(0)}catch(N){if(!T){if(J.hasOpenThinking()&&q==="text")d.stderr.write(`
|
|
6
|
+
`);B.error(`Error: ${nJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function hK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":K,"max-turns":D,...x}=SH,j=cJ(uJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([yH,TH,bH]);return oJ(j),await j.parse(),!0}export{HK as runHeadless,hK as handleHeadlessMode,lJ as HeadlessOptionsSchema};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{D as
|
|
1
|
+
import{tg as B}from"./chunk-hvmrcd84.js";import{Kj as Y}from"./chunk-svsgtj41.js";import{Nj as Z,Qj as $}from"./chunk-2g8avyq6.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
|
+
export{D as pg,h as qg,j as rg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Hk as K}from"./chunk-tecbx0ek.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
|
|
2
2
|
export{P as Ea,V as Fa,R as Ga,N as Ha};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ea as h,Ga as f,Ha as k}from"./chunk-
|
|
1
|
+
import{Ea as h,Ga as f,Ha as k}from"./chunk-8vqhcx3s.js";import"./chunk-tecbx0ek.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-kxwc5wrx.js";import"./chunk-19zsecpx.js";import"./chunk-tecbx0ek.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var n="verification",r="goal-verification",o="review";function e(t){return t==="verification"||t==="goal-verification"}function i(t){return e(t)||t==="review"}var s=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],c=["pending","pass","fail","partial"],l=4000,p=3,S=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],u=3,_=["waiting_dependency","same_task_no_effect","repeated_deferral"],d=3;
|
|
2
|
-
export{n as
|
|
2
|
+
export{n as $g,r as ah,o as bh,e as ch,i as dh,s as eh,c as fh,l as gh,p as hh,S as ih,u as jh,_ as kh,d as lh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mg as a}from"./chunk-pw9axk0e.js";import"./chunk-cww9pp1q.js";import"./chunk-n8qg68y2.js";import"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import"./chunk-2g8avyq6.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
|
|
2
|
-
export{B as
|
|
2
|
+
export{B as ag};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{da as p}from"./chunk-
|
|
1
|
+
import{da as p}from"./chunk-ppmy3n74.js";import{Mb as _}from"./chunk-we13xwds.js";import{Ad as z,Ld as q,ee as O,wd as N,xd as U,yd as I,zd as A}from"./chunk-n6tvswa8.js";import{qe as o}from"./chunk-es0cbtx1.js";import{ag as P}from"./chunk-c562kd2m.js";import{Bg as e}from"./chunk-xagh2qb6.js";import{xk as j}from"./chunk-mnk0b4nz.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
|
|
3
3
|
`).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
|
|
4
4
|
`)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{N as
|
|
1
|
+
import{Cj as b,Dj as K,Fj as j}from"./chunk-pg7cgvs8.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
|
|
2
|
+
export{N as ng,V as og};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as i}from"./chunk-
|
|
1
|
+
import{j as i}from"./chunk-5jq1mrqd.js";import{Yi as s}from"./chunk-g38d2ezm.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Pi as K}from"./chunk-w2m4yczv.js";import{Qi as wt,Ri as ft}from"./chunk-zp5097qk.js";import{Yi as I}from"./chunk-g38d2ezm.js";import{$i as Bt,Zi as tt,_i as Dt,dj as Gt,ej as et,fj as Kt,gj as Ht,hj as Yt,ij as cn,jj as Ft,kj as qt,lj as Mt,mj as Vt,nj as Jt,oj as _t,pj as Qt,qj as jt,rj as Wt,sj as Zt,tj as kt,uj as yt}from"./chunk-n8qg68y2.js";import{Aj as bn,Bj as _n,Cj as T,yj as Un}from"./chunk-pg7cgvs8.js";import{Hj as zt,Kj as v}from"./chunk-svsgtj41.js";import{Sj as xn,Tj as Cn}from"./chunk-19zsecpx.js";import{Zj as a}from"./chunk-85b3kacc.js";import{ak as Ln}from"./chunk-mnk0b4nz.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${e.map((M)=>` - ${M}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
-
export{B as
|
|
44
|
+
export{B as zh,nn as Ah,f as Bh,En as Ch,hn as Dh,C as Eh,ot as Fh,VM as Gh,W as Hh,jM as Ih,WM as Jh,ZM as Kh,ct as Lh,Ce as Mh,kM as Nh,he as Oh,yM as Ph,Pt as Qh,n_ as Rh,t_ as Sh,M_ as Th,__ as Uh,r_ as Vh,Ct as Wh,S_ as Xh,E_ as Yh,u_ as Zh,o_ as _h,Y as $h,Rn as ai,F as bi,q as ci,Xn as di,V as ei,TM as fi,sM as gi,J as hi,Q as ii,h as ji,xM as ki,zn as li,Dn as mi,hM as ni,Bn as oi,Gn as pi,Kn as qi,Hn as ri,Yn as si,Fn as ti,XM as ui,qn as vi,Vn as wi,Jn as xi,Qn as yi,jn as zi,Wn as Ai,Zn as Bi,kn as Ci,yn as Di,ln as Ei,vn as Fi,nt as Gi,s as Hi,d as Ii,Le as Ji,z as Ki,l as Li,X as Mi,W_ as Ni};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mf as N}from"./chunk-0kghtvxj.js";import{uh as $}from"./chunk-2ff55pvt.js";import{Yi as _}from"./chunk-g38d2ezm.js";import{wj as Y,yj as Z}from"./chunk-pg7cgvs8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
|
-
export{O as
|
|
4
|
+
export{O as uf,y as vf,j as wf,C as xf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{D as
|
|
1
|
+
import{Mi as I}from"./chunk-e6j4vzta.js";import{Jj as G,Kj as H}from"./chunk-svsgtj41.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
|
|
2
|
+
export{D as ug,Q as vg,T as wg,U as xg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ef as w0,ff as hT}from"./chunk-zfaenqqx.js";import{yh as MT}from"./chunk-nxsarfy6.js";import{yj as yT}from"./chunk-pg7cgvs8.js";import{Gk as RT,ak as X0,ik as E,kk as D,lk as i,nk as c,ok as j0,pk as bT,qk as ST,rk as fT,vk as k,xk as D0,yk as a}from"./chunk-mnk0b4nz.js";import{Hk as Z0}from"./chunk-tecbx0ek.js";import{createHash as F_}from"node:crypto";import{readdir as k0,stat as A0}from"node:fs/promises";import G0 from"node:path";import{createHash as oT,randomBytes as u0}from"node:crypto";import{chmod as p0,link as rT,lstat as p,mkdir as eT,open as l,readdir as l0,realpath as v0,unlink as U0}from"node:fs/promises";import K from"node:path";function dT(){return typeof globalThis.Bun<"u"}function sT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.prepare($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>T.pragma($,{simple:!0}),close:()=>T.close()}}function aT(T){return{exec:($)=>T.exec($),prepare:($)=>{let _=T.query($);return{run:(...G)=>{_.run(...G)},get:(...G)=>_.get(...G),all:(...G)=>_.all(...G)}},transaction:($)=>T.transaction($)(),pragma:($)=>{let _=T.query(`PRAGMA ${$}`).get();if(!_)return;let G=Object.values(_);return G.length===1?G[0]:_},close:()=>T.close()}}function tT(T){return[`PRAGMA busy_timeout=${T};`,"PRAGMA journal_mode=WAL;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
|
|
2
2
|
`)}async function t(T,$={}){let _=$.busyTimeoutMs??5000;if(!Number.isSafeInteger(_)||_<0)return null;let G=null;try{if(dT()){let{Database:Y}=await import("bun:sqlite");G=aT(new Y(T))}else{let Q=(await import("better-sqlite3")).default;G=sT(new Q(T))}return G.exec(tT(_)),G}catch{try{G?.close()}catch{}return null}}var T$="surface-workspaces-v1",n0=/^[a-f0-9]{64}$/,$$=/^acp-remote-workspace:[A-Za-z0-9_-]{43}$/,_$=1024,G$=".surface-workspaces-v1.capacity.sqlite",i0=/^\.tmp-acp-remote-workspace-([1-9][0-9]*)-[a-f0-9]{32}\.pending$/;class H extends Error{name="AcpRemoteWorkspaceReferenceError";code;retryable;constructor(T){let $=T==="session_surface_not_found"?{message:"Session surface was not found",retryable:!1}:T==="session_surface_capacity"?{message:"Session surface capacity is exhausted",retryable:!0}:{message:"Session surface state is invalid",retryable:!1};super($.message);this.code=T,this.retryable=$.retryable,Object.setPrototypeOf(this,new.target.prototype)}}var P,o=new Map;function c0(T){return K.join(String(T),T$)}async function d0(T,$){let _=D($);if(i(_.collisionIdentity)!==String(T))throw new H("session_surface_state_invalid");let G=a0(_.exactIdentity),X=c0(T);return await Y$(T,X),X$(X,()=>Q$(X,async()=>{await B$(X);let Y=await s0(T,X,!0),Q=Y.recordsByDigest.get(G);if(Q)return Q.workspaceRef;if(Y.recordsByDigest.size>=_$)throw new H("session_surface_capacity");let Z=K.join(X,`${G}.json`),U=new Set(Y.workspaceRefToDigest.keys());for(let V=0;V<32;V+=1){let g=M$();if(U.has(g))continue;return J$(T,X,Z,_,{version:1,exactIdentityDigest:G,workspaceRef:g})}throw new H("session_surface_state_invalid")}))}async function X$(T,$){let _=o.get(T)??Promise.resolve(),G=()=>{return},X=new Promise((Q)=>{G=Q}),Y=_.catch(()=>{return}).then(()=>X);o.set(T,Y),await _.catch(()=>{return});try{return await $()}finally{if(G(),o.get(T)===Y)o.delete(T)}}async function Y$(T,$){try{await V0($,String(T))}catch(_){if(x(_)!=="ENOENT"){if(_ instanceof H)throw _;throw new H("session_surface_state_invalid")}try{await eT($,{recursive:!1,mode:448})}catch(G){if(x(G)!=="EEXIST")throw new H("session_surface_state_invalid")}await V0($,String(T)),await h(String(T))}}async function Q$(T,$){await P?.beforeCapacityLockAttempt?.();let _=await Z$(T),G=!1,X,Y,Q;try{_.database.exec("BEGIN IMMEDIATE;"),G=!0,await P?.afterCapacityLockAcquired?.(),Q={value:await $()}}catch(Z){X=Z}if(G)try{await U$(_),_.database.exec("ROLLBACK;")}catch(Z){Y=Z}try{_.database.close()}catch(Z){if(!G)Y=Z}if(await _.identityHandle.close().catch(()=>{return}),Y!==void 0)throw new H("session_surface_state_invalid");if(X instanceof H)throw X;if(X!==void 0||!Q)throw new H("session_surface_state_invalid");return Q.value}async function Z$(T){let $=K.join(T,G$),_=null,G;try{let X=!1;try{let Q=await l($,"wx",384);X=!0,await Q.sync(),await Q.close()}catch(Q){if(x(Q)!=="EEXIST")throw Q}if(await m($,T),X)await h(T);G=await l($,"r"),await n(G,$,T);let Y=await G.stat({bigint:!0});if(_=await t($,{busyTimeoutMs:30000}),!_)throw new H("session_surface_state_invalid");if(_.exec("PRAGMA locking_mode=NORMAL;"),_.exec("PRAGMA synchronous=FULL;"),_.exec("PRAGMA busy_timeout=30000;"),process.platform!=="win32")await p0($,384);return await n(G,$,T),await V$($,T),{database:_,identity:Y,identityHandle:G,path:$}}catch(X){await G?.close().catch(()=>{return});try{_?.close()}catch{}if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}async function U$(T){await n(T.identityHandle,T.path,K.dirname(T.path));let $=await T.identityHandle.stat({bigint:!0});if(!B0(T.identity,$))throw new H("session_surface_state_invalid")}async function V$(T,$){for(let _ of["-journal","-shm","-wal"]){let G=`${T}${_}`;try{if(process.platform!=="win32")await p0(G,384);await m(G,$)}catch(X){if(x(X)!=="ENOENT"){if(X instanceof H)throw X;throw new H("session_surface_state_invalid")}}}}async function B$(T){let $=await l0(T,{withFileTypes:!0}),_=!1;for(let G of $){if(!i0.test(G.name))continue;let X=K.join(T,G.name);await m(X,T),await U0(X),_=!0}if(_)await h(T)}async function s0(T,$,_){try{await V0($,String(T))}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};if(Q instanceof H)throw Q;throw new H("session_surface_state_invalid")}let G;try{G=await l0($,{withFileTypes:!0})}catch(Q){if(!_&&x(Q)==="ENOENT")return{recordsByDigest:new Map,workspaceRefToDigest:new Map};throw new H("session_surface_state_invalid")}let X=new Map,Y=new Map;for(let Q of G){if(i0.test(Q.name)){await m(K.join($,Q.name),$);continue}if(!Q.name.endsWith(".json"))continue;let Z=K.basename(Q.name,".json");if(!n0.test(Z))throw new H("session_surface_state_invalid");let U=K.join($,Q.name),V=await g$(U,$);if(V.exactIdentityDigest!==Z)throw new H("session_surface_state_invalid");if(X.has(Z))throw new H("session_surface_state_invalid");let g=Y.get(V.workspaceRef);if(g&&g!==Z)throw new H("session_surface_state_invalid");X.set(Z,V),Y.set(V.workspaceRef,Z)}return{recordsByDigest:X,workspaceRefToDigest:Y}}async function g$(T,$){let _;try{await m(T,$),_=await l(T,"r"),await n(_,T,$);let G=await _.readFile({encoding:"utf8"});return H$(G)}catch(G){if(G instanceof H&&G.code==="session_surface_not_found")throw G;if(x(G)==="ENOENT")throw new H("session_surface_not_found");throw new H("session_surface_state_invalid")}finally{await _?.close()}}function H$(T){let $;try{$=JSON.parse(T)}catch{throw new H("session_surface_state_invalid")}if(!O$($))throw new H("session_surface_state_invalid");return $}function O$(T){if(!T||typeof T!=="object"||Array.isArray(T))return!1;let $=T,_=Object.keys($).sort();if(_.length!==3||_[0]!=="exactIdentityDigest"||_[1]!=="version"||_[2]!=="workspaceRef")return!1;return $.version===1&&typeof $.exactIdentityDigest==="string"&&n0.test($.exactIdentityDigest)&&typeof $.workspaceRef==="string"&&$$.test($.workspaceRef)}function a0(T){return oT("sha256").update(`acp-remote-workspace-exact-identity\x00${T}`).digest("hex")}function M$(){return`acp-remote-workspace:${u0(32).toString("base64url")}`}function C$(){return`.tmp-acp-remote-workspace-${process.pid}-${u0(16).toString("hex")}.pending`}async function V0(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isDirectory())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==448)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function m(T,$){if(K.dirname(T)!==$)throw new H("session_surface_state_invalid");let _=await p(T);if(_.isSymbolicLink()||!_.isFile())throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&_.uid!==process.getuid())throw new H("session_surface_state_invalid");let G=t0(_.mode);if(process.platform!=="win32"&&G!==384)throw new H("session_surface_state_invalid");await g0(T,$,K.basename(T))}async function n(T,$,_){let[G,X]=await Promise.all([T.stat({bigint:!0}),p($,{bigint:!0})]);if(K.dirname($)!==_||X.isSymbolicLink()||!X.isFile()||!G.isFile()||X.dev!==G.dev||X.ino!==G.ino)throw new H("session_surface_state_invalid");if(typeof process.getuid==="function"&&(Number(X.uid)!==process.getuid()||Number(G.uid)!==process.getuid()))throw new H("session_surface_state_invalid");let Y=Number(X.mode&BigInt(511)),Q=Number(G.mode&BigInt(511));if(process.platform!=="win32"&&(Y!==384||Q!==384))throw new H("session_surface_state_invalid");await g0($,_,K.basename($))}async function g0(T,$,_){let G=await v0(T),X=await v0($);if(G!==K.join(X,_))throw new H("session_surface_state_invalid")}async function h(T){if(!F$(process.platform))return;try{if(P?.syncDirectory){await P.syncDirectory(T);return}await L$(T)}catch{throw new H("session_surface_state_invalid")}}function F$(T){return T!=="win32"}async function L$(T){let $=await l(T,"r");try{await $.sync()}finally{await $.close()}}async function J$(T,$,_,G,X){let Y=K.join($,C$()),Q,Z,U=!1,V=!1,g,O;try{Q=await l(Y,"wx",384),await Q.writeFile(JSON.stringify(X),"utf8"),await Q.sync(),await n(Q,Y,$),Z=await Q.stat({bigint:!0}),await Q.close(),Q=void 0,await P?.beforePublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y});try{await rT(Y,_),U=!0}catch(M){if(x(M)!=="EEXIST")throw M;g=await N$(T,G)}if(U){let M=await p(_,{bigint:!0});if(!Z||!B0(Z,M))throw new H("session_surface_state_invalid");await m(_,$),await h($),V=!0,g=X.workspaceRef;try{await P?.afterPublish?.({finalPath:_,referenceDirectoryPath:$,tempPath:Y})}catch{}}}catch(M){O=M}finally{await Q?.close().catch(()=>{return})}if(O!==void 0&&U&&!V&&Z)try{let M=await p(_,{bigint:!0});if(B0(Z,M))await U0(_),await h($)}catch{}try{if(await U0(Y),!V)await h($)}catch(M){if(x(M)!=="ENOENT"&&O===void 0&&!V)O=M}if(O instanceof H)throw O;if(O!==void 0||g===void 0)throw new H("session_surface_state_invalid");return g}async function N$(T,$){let _=c0(T),G=await s0(T,_,!0),X=a0(D($).exactIdentity),Y=G.recordsByDigest.get(X);if(!Y)throw new H("session_surface_state_invalid");return Y.workspaceRef}function B0(T,$){return BigInt(T.dev)===BigInt($.dev)&&BigInt(T.ino)===BigInt($.ino)}function x(T){return T!==null&&typeof T==="object"&&"code"in T&&typeof T.code==="string"?T.code:void 0}function t0(T){return typeof T==="bigint"?Number(T&BigInt(511)):T&511}import*as f from"node:path";var $T=50,_T=100,z$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),I$=new Set(["high","medium","low"]),GT=/^[A-Za-z0-9_-]+$/,K$=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/,W$=/^acp-remote-exact-path:[a-f0-9]{64}$/;function XT(T){return typeof T==="string"&&K$.test(T)&&Number.isFinite(Date.parse(T))}function o0(T){return typeof T==="string"&&f.isAbsolute(T)}function r0(T){return typeof T==="string"&&W$.test(T)}function j$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function k$(T){return Buffer.from(JSON.stringify(T),"utf8").toString("base64url")}function A$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($);if(_.version!==1||_.kind!==void 0&&_.kind!=="local"||typeof _.includeSubagents!=="boolean"||_.archived!==void 0&&typeof _.archived!=="boolean"||!(_.cwd===null||o0(_.cwd))||!XT(_.lastMessageTime)||!o0(_.projectPath)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"local",cwd:_.cwd===null?null:f.resolve(_.cwd),includeSubagents:_.includeSubagents,archived:_.archived??!1,lastMessageTime:_.lastMessageTime,projectPath:f.resolve(_.projectPath),sessionId:_.sessionId}}catch{throw Error("Invalid session cursor")}}function x$(T){try{if(!GT.test(T))throw Error("invalid");let $=Buffer.from(T,"base64url").toString("utf8");if(Buffer.from($,"utf8").toString("base64url")!==T)throw Error("invalid");let _=JSON.parse($),G=Object.keys(_),X=new Set(["version","kind","exactIdentity","includeSubagents","archived","lastMessageTime","workspaceIdentity","sessionId"]);if(G.some((Y)=>!X.has(Y))||_.version!==1||_.kind!=="remote"||typeof _.includeSubagents!=="boolean"||typeof _.archived!=="boolean"||!(_.exactIdentity===null||r0(_.exactIdentity))||!XT(_.lastMessageTime)||!r0(_.workspaceIdentity)||!k(_.sessionId))throw Error("invalid");return{version:1,kind:"remote",exactIdentity:_.exactIdentity??null,includeSubagents:_.includeSubagents,archived:_.archived,lastMessageTime:_.lastMessageTime,workspaceIdentity:_.workspaceIdentity,sessionId:_.sessionId}}catch{throw Error("Invalid remote session cursor")}}function v(T){let $="";for(let _=0;_<T.length;_+=1)$+=T.charCodeAt(_).toString(16).padStart(4,"0");return $}function E$(T){if(!T.cursor)return;let $=A$(T.cursor);if($.cwd!==T.cwd||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Session cursor scope does not match this query");return $}function q$(T){if(!T.cursor)return;let $=x$(T.cursor);if($.exactIdentity!==T.exactIdentity||T.exactIdentity!==null&&$.workspaceIdentity!==T.exactIdentity||$.includeSubagents!==T.includeSubagents||($.archived??!1)!==T.archived)throw Error("Remote session cursor scope does not match this query");return $}function n_(T={}){let{cwd:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T;if($!==void 0&&!f.isAbsolute($))throw Error("Session catalog cwd must be absolute");let Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:$===void 0?null:f.resolve($),cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function i_(T={}){let{descriptor:$,cursor:_,limit:G,includeSubagents:X=!1,archived:Y=!1}=T,Q=G===void 0?$T:G;if(!Number.isInteger(Q)||Q<1||Q>_T)throw Error("Session catalog limit must be an integer from 1 to 100");return{descriptor:$,exactIdentity:$?.exactIdentity??null,cursor:_??void 0,limit:Q,includeSubagents:X,archived:Y}}function c_(T={}){let $=e0(T.taskStatus,z$,"task status"),_=e0(T.taskPriority,I$,"task priority"),G=TT(T.taskDueAfter,"taskDueAfter"),X=TT(T.taskDueBefore,"taskDueBefore");return D$(G,X),{...$?{taskStatuses:$}:{},..._?{taskPriorities:_}:{},...G?{taskDueAfter:G}:{},...X?{taskDueBefore:X}:{}}}function e0(T,$,_){if(T===void 0)return;let G=Array.isArray(T)?T:[T];if(G.length===0)return;let X=new Set;for(let Y of G){if(typeof Y!=="string"||!$.has(Y))throw Error(`Invalid session ${_} filter`);X.add(Y)}return[...X].sort()}function TT(T,$){if(T===void 0)return;if(typeof T!=="string"||!Number.isFinite(Date.parse(T)))throw Error(`Invalid session ${$} filter`);return new Date(T).toISOString()}function D$(T,$){if(T!==void 0&&$!==void 0&&T>$)throw Error("Session task due range is inverted")}function w$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.projectPath<$.projectPath)return-1;if(T.projectPath>$.projectPath)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function b$(T,$){if(T.lastMessageTime>$.lastMessageTime)return-1;if(T.lastMessageTime<$.lastMessageTime)return 1;if(T.workspaceIdentity<$.workspaceIdentity)return-1;if(T.workspaceIdentity>$.workspaceIdentity)return 1;if(T.sessionId<$.sessionId)return-1;if(T.sessionId>$.sessionId)return 1;return 0}function d_(T,$){let _=[...T],G=E$($);if(G)_=_.filter((Q)=>w$(Q,{sessionId:G.sessionId,projectPath:G.projectPath,lastMessageTime:G.lastMessageTime})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:j$({version:1,kind:"local",cwd:$.cwd,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,projectPath:Y.projectPath,sessionId:Y.sessionId})}}function s_(T,$){let _=[...T],G=q$($);if(G)_=_.filter((Q)=>b$(Q,{sessionId:G.sessionId,projectPath:Q.projectPath,lastMessageTime:G.lastMessageTime,workspaceIdentity:G.workspaceIdentity})>0);let X=_.slice(0,$.limit);if(X.length===0||_.length<=X.length)return{sessions:X};let Y=X[X.length-1];return{sessions:X,nextCursor:k$({version:1,kind:"remote",exactIdentity:$.exactIdentity,includeSubagents:$.includeSubagents,archived:$.archived,lastMessageTime:Y.lastMessageTime,workspaceIdentity:Y.workspaceIdentity,sessionId:Y.sessionId})}}function S$(T){return T.type==="message_created"||T.type==="token_budget_handoff_recorded"||T.type==="part_created"||T.type==="part_updated"||T.type==="turn_started"||T.type==="turn_completed"||T.type==="turn_aborted"||T.type==="turn_recovery_acknowledged"||T.type==="interaction_requested"||T.type==="interaction_responded"||T.type==="interaction_recovered"||T.type==="review_started"||T.type==="review_completed"}function H0(T){return T.type==="message_created"&&T.data.role==="user"&&(T.data.inboxMessageId!==void 0||T.data.parentMessageId===void 0)}function O0(T,$){let _=T.find((G)=>H0(G)&&G.data.messageId===$);if(!_)throw Error(`Rewind checkpoint not found: ${$}`);return{messageId:$,preview:YT(T,$),createdAt:_.data.createdAt}}function YT(T,$){let _=T.flatMap((G)=>{if(G.type!=="part_created"||G.data.messageId!==$)return[];if(G.data.partType==="text"){let X=G.data.payload;return typeof X.text==="string"?[X.text]:[]}if(G.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(_.length<=160)return _;return`${_.slice(0,160)}...`}function QT(T,$){O0(T,$);let _=T.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),G=T[_],X=G?.type==="message_created"?G.data.inboxMessageId:void 0,Y=new Set(T.flatMap((Q)=>Q.type==="turn_started"&&X&&Q.data.inputMessageIds?.includes(X)?[Q.data.turnId]:[]));return T.filter((Q,Z)=>{if((Q.type==="turn_started"||Q.type==="turn_completed"||Q.type==="turn_aborted"||Q.type==="turn_recovery_acknowledged")&&Y.has(Q.data.turnId))return!1;return Z<_||!S$(Q)})}function u(T){let $=[];for(let _ of T){if(_.type!=="session_rewound"){$.push(_);continue}if(O0($,_.data.targetMessageId),_.data.mode!=="code")$=QT($,_.data.targetMessageId)}return $}function t_(T){let $=u(T);return $.filter(H0).map((_)=>({messageId:_.data.messageId,preview:YT($,_.data.messageId),createdAt:_.data.createdAt})).reverse()}function o_(T,$){let _=u(T),G=O0(_,$),X=_.findIndex((Q)=>Q.type==="message_created"&&Q.data.messageId===$),Y=_.slice(X);return{checkpoint:G,projectedEntries:QT(_,$),removedTurns:Y.filter(H0).length,snapshotMessageIds:Y.flatMap((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_call"?[Q.data.partId]:[])}}import{createHash as i$}from"node:crypto";var e_={clientVisible:!1};function ZT(T){if(T.metadata&&typeof T.metadata==="object"&&!Array.isArray(T.metadata)&&T.metadata.clientVisible===!1)return!1;return!(T.role==="user"&&typeof T.content==="string"&&T.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&T.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{StringDecoder as y$}from"node:string_decoder";var $1=1048576;function M0(T,$){let _=$;while(_<T.length&&(T[_]&192)===128)_+=1;return _}class C0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(T=1048576){this.maxBytes=T;if(!Number.isSafeInteger(T)||T<=0)throw Error("maxBytes must be a positive safe integer")}append(T){let $=Buffer.isBuffer(T)?T:Buffer.from(T);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let T=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,T}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(T){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=M0(T,T.length-this.maxBytes);if(this.omittedBytes+=$,$===T.length)return;let _=Buffer.from(T.subarray($));this.chunks.push(_),this.retainedBytes=_.length}trimToLimit(){let T=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let _=this.retainedBytes-this.maxBytes;if($.length<=_){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,T=!0;continue}let G=M0($,_);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G,T=!0}if(T)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let T=this.chunks[0];if(T.length===0){this.chunks.shift();continue}let $=M0(T,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===T.length)this.chunks.shift();else{this.chunks[0]=T.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let T=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,T.length>0)this.chunks.push(T)}}var r={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},R={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},UT={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},f$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},R$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:r,summaryTemplate:(T)=>`Successfully processed ${T} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:r,summaryTemplate:(T)=>`Package operation completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:R,summaryTemplate:(T)=>`Build completed (${T} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:UT},{pattern:/^git\s+(status|branch|remote)/i,config:R},{pattern:/^git\s+(log|diff|show)/i,config:UT},{pattern:/^(ls|dir|tree)\s+/i,config:R,summaryTemplate:(T)=>`Listed ${T} items`},{pattern:/^find\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:R,summaryTemplate:(T)=>`Found ${T} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:r,summaryTemplate:(T)=>`Docker operation completed (${T} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:r,summaryTemplate:(T)=>`Python package operation completed (${T} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:R,summaryTemplate:(T)=>`Rust operation completed (${T} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:R,summaryTemplate:(T)=>`Go operation completed (${T} lines)`}];function VT(T,$,_){let G=$,X=_??T.length;if(G>0){let Y=T.charCodeAt(G);if(Y>=56320&&Y<=57343)G+=1}if(X<T.length){let Y=T.charCodeAt(X-1);if(Y>=55296&&Y<=56319)X-=1}return T.slice(G,X)}class F0{static getConfigForCommand(T){for(let{pattern:$,config:_,summaryTemplate:G}of R$)if($.test(T))return{config:_,summaryTemplate:G};return{config:f$}}static truncate(T,$){let{config:_,summaryTemplate:G}=this.getConfigForCommand($);return this.truncateWithConfig(T,_,G)}static truncateWithConfig(T,$,_){let G=T.length,X=T.split(`
|
|
3
3
|
`),Y=X.length;if(Y<=$.maxLines&&G<=$.maxChars)return{content:T,truncated:!1,originalLines:Y,originalChars:G};let Q=X.slice(0,$.keepHead),Z=X.slice(-$.keepTail),U=Y-$.keepHead-$.keepTail,V=Q.join(`
|
|
4
4
|
`);if(V+=`
|
|
@@ -335,4 +335,4 @@ ranked_archive AS (
|
|
|
335
335
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
336
336
|
WHERE parts_fts MATCH ? AND source_kind = 'local'
|
|
337
337
|
ORDER BY timestamp DESC LIMIT ?`,Z=T.prepare(Q);return _?Z.all(Y,_,G):Z.all(Y,G)}
|
|
338
|
-
export{d0 as
|
|
338
|
+
export{d0 as le,u as me,t_ as ne,o_ as oe,d as pe,j as qe,v as re,E$ as se,q$ as te,n_ as ue,i_ as ve,c_ as we,w$ as xe,b$ as ye,d_ as ze,s_ as Ae,e_ as Be,ZT as Ce,$1 as De,C0 as Ee,F0 as Fe,U1 as Ge,V1 as He,B1 as Ie,CT as Je,FT as Ke,J0 as Le,KT as Me,y1 as Ne,h1 as Oe,P1 as Pe,vT as Qe,K_ as Re,W_ as Se,pT as Te,DT as Ue,w_ as Ve,m1 as We,b_ as Xe,v1 as Ye,u1 as Ze,p1 as _e,f_ as $e,l1 as af,n1 as bf,i1 as cf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-
|
|
1
|
+
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-y5bqd8gh.js";import{ca as O,ja as S}from"./chunk-ppmy3n74.js";import"./chunk-8vqhcx3s.js";import"./chunk-pwct7cj7.js";import"./chunk-4xr4hz19.js";import{Wb as M,ec as E}from"./chunk-we13xwds.js";import"./chunk-0sx7ak0b.js";import{ee as f}from"./chunk-n6tvswa8.js";import"./chunk-kmg8ad2j.js";import{Je as h}from"./chunk-es0cbtx1.js";import"./chunk-zfaenqqx.js";import{of as I}from"./chunk-rrtptbzv.js";import{qf as y,rf as R,sf as g}from"./chunk-w5057h27.js";import{tf as C}from"./chunk-g4kydkyz.js";import"./chunk-08z32sky.js";import{Qf as w}from"./chunk-0kghtvxj.js";import"./chunk-v508x7cg.js";import"./chunk-c562kd2m.js";import"./chunk-pw9axk0e.js";import"./chunk-cww9pp1q.js";import"./chunk-8fx20am1.js";import"./chunk-hvmrcd84.js";import"./chunk-eqe3smcg.js";import"./chunk-xagh2qb6.js";import"./chunk-ascjys4e.js";import"./chunk-r4q06wbs.js";import"./chunk-ma1mn6hn.js";import"./chunk-2ff55pvt.js";import"./chunk-nxsarfy6.js";import"./chunk-e6j4vzta.js";import{Oi as A}from"./chunk-w2m4yczv.js";import"./chunk-zp5097qk.js";import{Yi as P}from"./chunk-g38d2ezm.js";import"./chunk-n8qg68y2.js";import"./chunk-pg7cgvs8.js";import"./chunk-svsgtj41.js";import"./chunk-2g8avyq6.js";import"./chunk-19zsecpx.js";import"./chunk-85b3kacc.js";import"./chunk-5cw3bevx.js";import"./chunk-mnk0b4nz.js";import"./chunk-tecbx0ek.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Vi,D as Wi,P as Xi,V as Yi};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{rh as Q}from"./chunk-ma1mn6hn.js";import{Aj as F,Cj as k,Fj as G}from"./chunk-pg7cgvs8.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as tf};
|