blade-code 0.10.70 → 0.10.71
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-31k6x4kn.js → chunk-0tm20v38.js} +2 -2
- package/dist/{chunk-728anavt.js → chunk-0vrgrw71.js} +1 -1
- package/dist/{chunk-p9vaaayr.js → chunk-1je1xw6v.js} +1 -1
- package/dist/{chunk-g28pgqyn.js → chunk-1pjkgfez.js} +1 -1
- package/dist/{chunk-qstf0gpe.js → chunk-1w83z8j0.js} +1 -1
- package/dist/{chunk-r9n8y8m1.js → chunk-2428hhvj.js} +1 -1
- package/dist/{chunk-0p0e70cy.js → chunk-2px6hzdc.js} +1 -1
- package/dist/chunk-3as0bkqy.js +1 -0
- package/dist/{chunk-bkajr86v.js → chunk-3hy06st1.js} +1 -1
- package/dist/{chunk-qm5c9wew.js → chunk-4ke8k0xw.js} +2 -2
- package/dist/{chunk-ffym3kf3.js → chunk-4pexpa3h.js} +1 -1
- package/dist/{chunk-63121s4r.js → chunk-5te2jqt3.js} +1 -1
- package/dist/{chunk-b39p4f5r.js → chunk-82htkvz8.js} +1 -1
- package/dist/chunk-8j568nm6.js +1 -0
- package/dist/{chunk-wepvrnmh.js → chunk-92x15fzx.js} +1 -1
- package/dist/{chunk-4aam3qhk.js → chunk-93tvxmqg.js} +1 -1
- package/dist/{chunk-1z9k5dmz.js → chunk-97aywyzn.js} +1 -1
- package/dist/{chunk-ypgjqg23.js → chunk-9hchc346.js} +1 -1
- package/dist/{chunk-8wea3qty.js → chunk-9q852bsc.js} +2 -2
- package/dist/{chunk-w2gr97qt.js → chunk-ahg9vjb6.js} +1 -1
- package/dist/{chunk-wahhwjp9.js → chunk-axtzde5k.js} +1 -1
- package/dist/{chunk-y9d9nqnn.js → chunk-azw0jckv.js} +1 -1
- package/dist/{chunk-sch01e04.js → chunk-be30r8an.js} +1 -1
- package/dist/{chunk-d2vrbbvd.js → chunk-byqxaa9v.js} +1 -1
- package/dist/{chunk-7b5s752s.js → chunk-cff9gphh.js} +1 -1
- package/dist/{chunk-5wnx38ze.js → chunk-ckqpt15b.js} +1 -1
- package/dist/{chunk-0kmrvxsz.js → chunk-d3ttqmyt.js} +3 -3
- package/dist/{chunk-pw87f92g.js → chunk-dwb2nmms.js} +1 -1
- package/dist/{chunk-brdxkp0y.js → chunk-fcmgwzrj.js} +1 -1
- package/dist/{chunk-832va1mp.js → chunk-fcv8b6ny.js} +1 -1
- package/dist/{chunk-z77c18j5.js → chunk-gtcxybv5.js} +1 -1
- package/dist/chunk-gvbx0t4j.js +1 -0
- package/dist/{chunk-ysmqje92.js → chunk-j0p54tqt.js} +1 -1
- package/dist/{chunk-20vj0npz.js → chunk-j9q1wyxg.js} +1 -1
- package/dist/chunk-jzntxp7f.js +3 -0
- package/dist/{chunk-f7yfcw8s.js → chunk-mtphps19.js} +1 -1
- package/dist/chunk-n827nys9.js +1 -0
- package/dist/{chunk-cmpj3a5a.js → chunk-nwzpnx7m.js} +1 -1
- package/dist/{chunk-wkpacysr.js → chunk-nx31fkkf.js} +2 -2
- package/dist/{chunk-83b4vfjs.js → chunk-qgrq04hb.js} +1 -1
- package/dist/chunk-qnsvae10.js +1 -0
- package/dist/chunk-r9d4mjxj.js +2 -0
- package/dist/{chunk-b2p4kd07.js → chunk-rm9hbew3.js} +1 -1
- package/dist/{chunk-smjkx71w.js → chunk-s77sbxr7.js} +1 -1
- package/dist/chunk-sp3bn8qh.js +1 -0
- package/dist/{chunk-d808m826.js → chunk-t2wgf9tq.js} +1 -1
- package/dist/{chunk-1bcp0qc4.js → chunk-trn6r1g3.js} +1 -1
- package/dist/{chunk-0p95nha3.js → chunk-v7p533ff.js} +1 -1
- package/dist/{chunk-h94vfh7s.js → chunk-vthgpdbd.js} +1 -1
- package/dist/{chunk-k6shq7rk.js → chunk-wfy851et.js} +1 -1
- package/dist/chunk-wneeq8cr.js +1 -0
- package/dist/{chunk-4md4sd4j.js → chunk-wrfay5r3.js} +1 -1
- package/dist/{chunk-sh17gjxv.js → chunk-x9tvjkjv.js} +1 -1
- package/dist/{chunk-rpfa4a56.js → chunk-xdz5zrjt.js} +1 -1
- package/dist/chunk-xzz69esf.js +1 -0
- package/dist/{chunk-q919ypcz.js → chunk-zdnk7qtn.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2z75emht.js +0 -1
- package/dist/chunk-3j413cgh.js +0 -1
- package/dist/chunk-8bsyhr4v.js +0 -1
- package/dist/chunk-c0qm0wwk.js +0 -1
- package/dist/chunk-cx5s0rf3.js +0 -1
- package/dist/chunk-e3asq942.js +0 -1
- package/dist/chunk-jrr361h1.js +0 -2
- package/dist/chunk-nea4rcdf.js +0 -1
- package/dist/chunk-v3kkv21n.js +0 -1
- package/dist/chunk-wj6t3tv2.js +0 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Hb as Xt,Ib as fn,Jb as yn,Kb as En}from"./chunk-th4jjfgm.js";import{$e as Bt}from"./chunk-
|
|
1
|
+
import{Hb as Xt,Ib as fn,Jb as yn,Kb as En}from"./chunk-th4jjfgm.js";import{$e as Bt}from"./chunk-4ke8k0xw.js";import{Bf as wn,Cf as Gt,Df as Ut,Ef as h,Ff as Ht,ef as gt,ff as vi,gf as sn,hf as zt,if as U,jf as en,kf as xt,lf as mt,nf as rn,of as Tn,pf as B,qf as dn,rf as on,sf as pn,tf as lt,uf as cn,vf as un,wf as Mn,yf as S}from"./chunk-82htkvz8.js";import{kg as X,mg as g}from"./chunk-v0rsz1rt.js";import{wg as It}from"./chunk-k0pa8874.js";import{jh as tn,kh as nn}from"./chunk-azw0jckv.js";import{Dh as ns}from"./chunk-wfy851et.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as a,g as i,h as l,i as m}from"./chunk-93tvxmqg.js";import"./chunk-9hchc346.js";import"./chunk-rm9hbew3.js";import"./chunk-s77sbxr7.js";import"./chunk-ahg9vjb6.js";import"./chunk-byqxaa9v.js";import"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{qd as n}from"./chunk-0vrgrw71.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
+
export{N as rh,S as sh};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Ah as
|
|
1
|
+
import{Ah as $,Bh as F}from"./chunk-9q852bsc.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as l};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Rf as H,Sf as I}from"./chunk-
|
|
1
|
+
import{Rf as H,Sf as I}from"./chunk-82htkvz8.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jd as a,kd as b}from"./chunk-3hy06st1.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Bh as j}from"./chunk-9q852bsc.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
|
|
2
2
|
`)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
|
|
3
3
|
export{m as Ug,I as Vg,M as Wg,V as Xg,h as Yg};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-be30r8an.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j}from"./chunk-
|
|
1
|
+
import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j}from"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-
|
|
1
|
+
import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as a}from"node:module";var c=a(import.meta.url);
|
|
2
|
-
export{c as
|
|
2
|
+
export{c as Dh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ee as a}from"./chunk-zdnk7qtn.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{je as B}from"./chunk-yn51162x.js";import{bh as Y}from"./chunk-
|
|
1
|
+
import{je as B}from"./chunk-yn51162x.js";import{bh as Y}from"./chunk-2px6hzdc.js";import{eh as Z,hh as $}from"./chunk-t8xmh4w2.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,z,x){if(z.api!=="anthropic-messages"||x.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,z){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((x)=>{let J=(z.models??[]).filter((G)=>G.provider===x.provider&&G.model===x.model),w=x.configId?(z.models??[]).find((G)=>G.id===x.configId):J.length===1?J[0]:void 0;if(x.configId&&!w)throw Error(`Unknown fallback model config ID: ${x.configId}`);if(w&&(w.provider!==x.provider||w.model!==x.model))throw Error(`Fallback model config ${w.id} does not match ${x.provider}/${x.model}`);if(!x.configId&&J.length>1)throw Error(`Fallback model ${x.provider}/${x.model} is ambiguous; set configId`);if(!w)return x;let Q=w.provider===q.provider;return{...x,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??z.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??z.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,z,x,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,x),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??z.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??z.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,z),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:z.providerCircuitBreakerOpenMs,providerRequestConcurrency:z.providerRequestConcurrency,providerRequestAdmissionMs:z.providerRequestAdmissionMs,providerRequestPendingBytes:z.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
|
|
2
2
|
export{D as fe,h as ge,j as he};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-z77c18j5.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-d2vrbbvd.js";import{N as jH,P as xH,Q as UH,S as VH,V as _H}from"./chunk-0kmrvxsz.js";import"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import{db as s,pb as LH,yb as WH}from"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import{Cc as O,Nc as a,nc as QH,rc as DH}from"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{jd as PH}from"./chunk-bkajr86v.js";import{ld as FH,md as EH,nd as zH}from"./chunk-r9n8y8m1.js";import{od as GH}from"./chunk-s7jsadnc.js";import"./chunk-bjqjdw34.js";import{Od as NH}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-b39p4f5r.js";import{ig as YH}from"./chunk-h0ft81a3.js";import{kg as BH,mg as H,ng as KH,pg as N}from"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as g}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),aH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=D({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(aH)}),oH=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:N(["local","acp"])}),rH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(oH)}),nH=D({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())}),tH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["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())}),JJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["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())}),KJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["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())}),VJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["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())}),ZJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["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()}),YJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"}))}),DJ=D({type:H.Literal("subagent"),state:N(["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(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),LJ=D({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:N(["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())}),WJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["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(N(["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(N(["attempt_limit","recovery_budget"]))}),xJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["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}))}),UJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["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}))}),_J=D({type:H.Literal("provider_stall"),phase:N(["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()}),GJ=D({type:H.Literal("action_stationarity"),phase:N(["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()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),EJ=D({type:H.Literal("task_admission"),state:N(["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})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function SJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var TJ=N(["text","jsonl"]),bJ=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(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(YH)),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(N(["local","worktree"])),outputFormat:H.Optional(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.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(V)=>{if(!V.headless)return;let Q=await mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as MH,n as fH,o as yH,p as SH,q as TH,r as bH}from"./chunk-gtcxybv5.js";import{A as JH,v as AH,w as t,x as e,y as HH,z as d}from"./chunk-byqxaa9v.js";import{N as jH,P as xH,Q as UH,S as VH,V as _H}from"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import{db as s,pb as LH,yb as WH}from"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import{Cc as O,Nc as a,nc as QH,rc as DH}from"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{jd as PH}from"./chunk-3hy06st1.js";import{ld as FH,md as EH,nd as zH}from"./chunk-2428hhvj.js";import{od as GH}from"./chunk-s7jsadnc.js";import"./chunk-bjqjdw34.js";import{Od as NH}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import{ig as YH}from"./chunk-h0ft81a3.js";import{kg as BH,mg as H,ng as KH,pg as N}from"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as g}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import MJ from"yargs";import{hideBin as fJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function wH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function mH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await wH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>mH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var ZH=1;function D(K){return H.Object({event_version:H.Literal(ZH),...K})}var cH=D({type:H.Literal("content_delta"),delta:H.String()}),uH=D({type:H.Literal("thinking_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking"),content:H.String()}),pH=D({type:H.Literal("stream_end")}),vH=D({type:H.Literal("content"),content:H.String()}),lH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),aH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),sH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),iH=D({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(aH)}),oH=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:N(["local","acp"])}),rH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(oH)}),nH=D({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())}),tH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),HJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["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())}),JJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["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())}),KJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["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())}),VJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["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())}),ZJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),$J=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),qJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),XJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["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()}),YJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),BJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),NJ=D({type:H.Literal("task_update"),tasks:H.Array(VH)}),QJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"}))}),DJ=D({type:H.Literal("subagent"),state:N(["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(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),LJ=D({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:N(["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())}),WJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),jJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["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(N(["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(N(["attempt_limit","recovery_budget"]))}),xJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["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}))}),UJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["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}))}),_J=D({type:H.Literal("provider_stall"),phase:N(["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()}),GJ=D({type:H.Literal("action_stationarity"),phase:N(["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()}),PJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),FJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),EJ=D({type:H.Literal("task_admission"),state:N(["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})}),zJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),AJ=D({type:H.Literal("error"),message:H.String()}),aJ=KH(H.Union([cH,uH,dH,pH,vH,lH,sH,iH,rH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,xJ,UJ,jJ,_J,GJ,PJ,FJ,EJ,zJ,AJ]));function $H(K,V){return{event_version:ZH,type:K,...V}}function yJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function SJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var TJ=N(["text","jsonl"]),bJ=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(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(YH)),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(N(["local","worktree"])),outputFormat:H.Optional(TJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class RH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function RJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IJ(K){let V=BH(bJ,K);if(!V.success)throw Error(`Invalid headless options: ${RJ(V.error)}`);return V.data}function gJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.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(V)=>{if(!V.headless)return;let Q=await mJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function CJ(K){return`[task] [${K.status}] ${K.subject}`}function kJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function hJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function OJ(K){return K==="jsonl"?"jsonl":"text"}function qH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){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 wJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function XH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify($H(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Gd as a,Hd as b,Id as c,Jd as d,Kd as e,Ld as f,Md as g,Nd as h,Od as i,Pd as j,Qd as k,Rd as l,Sd as m,Td as n,Ud as o,Vd as p,Wd as q}from"./chunk-
|
|
1
|
+
import{Gd as a,Hd as b,Id as c,Jd as d,Kd as e,Ld as f,Md as g,Nd as h,Od as i,Pd as j,Qd as k,Rd as l,Sd as m,Td as n,Ud as o,Vd as p,Wd as q}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-82htkvz8.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fe as a,ge as b,he as c}from"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ag as TE,Bg as gf,Cg as lf,Dg as xE,Eg as Wf,Gg as $f,Ig as Kf,Jg as If,Kg as uf,Lg as Cf,Ng as Df,Og as Ff,Qg as s}from"./chunk-6pyktfa4.js";import{Xg as g}from"./chunk-
|
|
1
|
+
import{Ag as TE,Bg as gf,Cg as lf,Dg as xE,Eg as Wf,Gg as $f,Ig as Kf,Jg as If,Kg as uf,Lg as Cf,Ng as Df,Og as Ff,Qg as s}from"./chunk-6pyktfa4.js";import{Xg as g}from"./chunk-t2wgf9tq.js";import{$g as P_,bh as Xf}from"./chunk-2px6hzdc.js";import{eh as e_}from"./chunk-t8xmh4w2.js";var YE={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},T_=(f)=>YE[f]||{};var cE=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Vf(f){return typeof f==="string"&&cE.has(f)}function Xh(f){if(!f.aborted)return;if(Vf(f.reason))return f.reason;return"user-cancel"}function Wh(f){if(Vf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function x_(...f){let _=f.filter(Boolean);if(_.length===0)return new AbortController().signal;if(_.length===1)return _[0];let E=AbortSignal;if(typeof E.any==="function")return E.any(_);for(let x of _)if(x.aborted)return x;let h=new AbortController,T=new Map;for(let x of _){let S=()=>{h.abort(x.reason);for(let[P,t]of T)P.removeEventListener("abort",t)};T.set(x,S)}for(let[x,S]of T)x.addEventListener("abort",S,{once:!0});return h.signal}function i(f,_,E){let h=E?.throwOnAbort??!1;if(_?.aborted){if(h)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,x)=>{let S,P=setTimeout(()=>{if(_&&S)_.removeEventListener("abort",S);T()},f);if(_)S=()=>{if(clearTimeout(P),h)x(new DOMException("Aborted","AbortError"));else T()},_.addEventListener("abort",S,{once:!0})})}var bE=g("Chat"),OE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function jf(f){if(typeof f==="string")return f;return f.filter((_)=>_.type==="text").map((_)=>_.text).join(`
|
|
2
2
|
`)}function BE(f){if(!f)return{};try{let _=JSON.parse(f);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return bE.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function VE(f){let _=f.match(/^data:([^;,]+);base64,(.+)$/s);return _?{mimeType:_[1],data:_[2]}:void 0}async function jE(f,_){let E=VE(f);if(E)return{type:"image",...E};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let h=await fetch(f,{signal:_});if(!h.ok)throw Error(`Failed to load image ${f}: HTTP ${h.status}`);return{type:"image",mimeType:h.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await h.arrayBuffer()).toString("base64")}}async function M_(f,_,E,h,T){let x=f.filter((t)=>t.role==="system").map((t)=>jf(t.content)).filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`),S=[];for(let t of f){if(t.role==="system")continue;if(t.role==="user"){let N=_.input.includes("image"),M=typeof t.content==="string"?t.content:await Promise.all(t.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):N?jE(R.image_url.url,h):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));S.push({role:"user",content:M,timestamp:Date.now()});continue}if(t.role==="assistant"){let N=[];if(t.reasoningContent?.trim())N.push({type:"thinking",thinking:t.reasoningContent});let M=jf(t.content);if(M)N.push({type:"text",text:M});for(let R of t.tool_calls??[]){if(!("function"in R))continue;N.push({type:"toolCall",id:R.id,name:R.function.name,arguments:BE(R.function.arguments)})}S.push({role:"assistant",content:N,api:_.api,provider:_.provider,model:_.id,usage:OE,stopReason:t.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}S.push({role:"toolResult",toolCallId:t.tool_call_id??"",toolName:t.name??"unknown",content:[{type:"text",text:jf(t.content)}],isError:!1,timestamp:Date.now()})}let P=E?.filter((t)=>!T||t.name===T).map((t)=>({name:t.name,description:t.description,parameters:t.parameters,constrainedSampling:t.constrainedSampling})).sort((t,N)=>t.name<N.name?-1:t.name>N.name?1:0);return{...x?{systemPrompt:x}:{},messages:S,...P?.length?{tools:P}:{}}}function R_(f){let _=[];for(let E=0;E<f.length;E++){let h=f[E];if(h.role==="tool")continue;let T=h.role==="assistant"&&h.tool_calls?.length?h.tool_calls:void 0;if(!T){_.push(h);continue}let x=[],S=E+1;while(S<f.length&&f[S].role==="tool")x.push(f[S++]);let P=new Set(T.map((M)=>M.id)),t=x.filter((M)=>M.tool_call_id&&P.has(M.tool_call_id)),N=new Set(t.map((M)=>M.tool_call_id));if(P.size===T.length&&t.length===P.size&&N.size===P.size)_.push(h,...t);E=S-1}return _}function A_(f){return f.some((_)=>_.role==="assistant"&&Boolean(_.tool_calls?.length)&&!_.reasoningContent?.trim())}function S_(f,_){return{...f,..._.baseUrl?{baseUrl:P_(f.api,_.baseUrl)}:{},..._.maxOutputTokens?{maxTokens:_.maxOutputTokens}:{}}}function zf(f){let _=f.modelCatalog??Xf();return{models:_.models,model:S_(_.getModel(f.provider,f.model),f)}}function N_(f,_){let E=f.modelCatalog??Xf();return S_(E.getModel(_.provider,_.model),f)}import{createHash as XE}from"node:crypto";var zE=32,JE=1000,WE=512,$E=2000,kE=0.1,LE=0.05,GE=0.9,ZE=300000,QE=3600000;class Jf{sessions=new Map;observe(f){if(f.retention==="none"){this.sessions.delete(f.sessionId);return}let _=f.now??Date.now(),E=KE(f,_),h=this.sessions.get(f.sessionId);if(E.callCount=(h?.callCount??0)+1,this.touch(f.sessionId,E),h&&E.contextEpoch!==h.contextEpoch)return;if(!h||h.cacheReadTokens<JE)return;let T=h.cacheReadTokens-E.cacheReadTokens,x=Math.min($E,Math.max(WE,h.cacheReadTokens*kE));if(T<x||E.cacheReadTokens>=h.cacheReadTokens*(1-LE))return;let S=E.modelIdentity!==h.modelIdentity,P=E.systemHash!==h.systemHash,t=E.toolsHash!==h.toolsHash,N=E.policyHash!==h.policyHash;if(!(S||P||t||N)&&E.promptTokens<h.promptTokens*GE)return;let R=Math.max(0,_-h.recordedAt),u=h.retention==="long"?QE:ZE,Y=S?"model_changed":P?"system_prompt_changed":t?"tools_changed":N?"request_policy_changed":R>=u?"ttl_expired":"server_side",$=CE(h,E);return{reason:Y,previousCacheReadTokens:h.cacheReadTokens,cacheReadTokens:E.cacheReadTokens,cacheWriteTokens:Math.max(0,f.usage.cacheCreationInputTokens??0),tokenDrop:T,elapsedMs:R,callNumber:E.callCount,systemPromptChanged:P,systemCharDelta:E.systemChars-h.systemChars,toolsChanged:t,addedToolCount:$.added,removedToolCount:$.removed,changedToolCount:$.changed,modelChanged:S,requestPolicyChanged:N}}clear(f){if(f)this.sessions.delete(f);else this.sessions.clear()}statsForTests(){return{sessions:this.sessions.size}}touch(f,_){this.sessions.delete(f),this.sessions.set(f,_);while(this.sessions.size>zE){let E=this.sessions.keys().next().value;if(E===void 0)break;this.sessions.delete(E)}}}function KE(f,_){let E=[...f.tools??f.context.tools??[]].map((h)=>({identityHash:ff(h.name),contractHash:ff(_f(h))})).sort((h,T)=>h.identityHash<T.identityHash?-1:h.identityHash>T.identityHash?1:0);return{modelIdentity:f.modelIdentity,systemHash:ff(f.context.systemPrompt??""),systemChars:f.context.systemPrompt?.length??0,toolsHash:ff(_f(E)),toolFingerprints:E,policyHash:ff(_f(f.policy)),contextEpoch:f.contextEpoch??"",retention:f.retention,promptTokens:Number.isFinite(f.usage.promptTokens)?Math.max(0,f.usage.promptTokens):0,cacheReadTokens:Math.max(0,f.usage.cacheReadInputTokens??0),recordedAt:_,callCount:1}}function CE(f,_){let E=new Map(f.toolFingerprints.map((T)=>[T.identityHash,T.contractHash])),h=new Map(_.toolFingerprints.map((T)=>[T.identityHash,T.contractHash]));return{added:[...h.keys()].filter((T)=>!E.has(T)).length,removed:[...E.keys()].filter((T)=>!h.has(T)).length,changed:[...h].filter(([T,x])=>E.has(T)&&E.get(T)!==x).length}}function _f(f){if(f===null||typeof f!=="object")return JSON.stringify(f)??"undefined";if(Array.isArray(f))return`[${f.map(_f).join(",")}]`;let _=f;return`{${Object.keys(_).sort().map((E)=>`${JSON.stringify(E)}:${_f(_[E])}`).join(",")}}`}function ff(f){return XE("sha256").update(f).digest("hex")}import{randomBytes as vE}from"node:crypto";import{createHmac as FE}from"node:crypto";function oE(f){try{let _=new URL(f);if(_.hash="",_.hostname=_.hostname.toLowerCase(),_.searchParams.sort(),_.pathname!=="/")_.pathname=_.pathname.replace(/\/+$/,"");return _.toString()}catch{return f.trim().replace(/\/+$/,"")}}function sE(f){if(!f)return[];return Object.entries(f).map(([_,E])=>[_.trim().toLowerCase(),E.trim()]).sort(([_],[E])=>_.localeCompare(E))}function Pf(f,_,E){let h=JSON.stringify([f.provider.trim(),String(f.api).trim(),oE(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",sE(f.customHeaders),E]);return FE("sha256",Buffer.from(_)).update(h).digest("hex")}var wE=60000,pE=4,mE=0.8;var Nf=300000,kf=600000;var I_=128,u_=256,qE=1800000,Sf=50;class hf extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Lf(f){return f instanceof hf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function l(f,_){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:_}function gE(f,_){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:_}function lE(f,_){return Pf(f,_,{providerCircuitOpenDurationMs:f.openDurationMs})}function Ef(f){let _=0;for(let E of f)if(E.failure)_++;return _}function D_(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function H_(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),$f)}class Y_{#x=new Map;#t=new WeakMap;#f;#E;#T;#h;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):vE(32),this.#E=f.now??(()=>performance.now()),this.#T=f.wallNow??f.now??Date.now,this.#h={maxEntries:Math.min(l(f.maxEntries,I_),I_),maxWindowEntries:Math.min(l(f.maxWindowEntries,u_),u_),windowMs:l(f.windowMs,wE),minSamples:l(f.minSamples,pE),errorRateThreshold:gE(f.errorRateThreshold,mE),idleTtlMs:l(f.idleTtlMs,qE)}}get size(){return this.#x.size}get(f){if(f.openDurationMs===0)return this.#R();let _=this.#E();this.#c(_);let E=lE(f,this.#f),h=this.#x.get(E);if(h)return h.lastTouchedAt=_,this.#_(h,f.probeLeaseMs);if(this.#x.size>=this.#h.maxEntries)this.#D();if(this.#x.size>=this.#h.maxEntries)return this.#R();let T={key:E,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:_,detached:!1};return this.#x.set(E,T),this.#_(T,f.probeLeaseMs)}#_(f,_){let E=this,h=Math.max(Nf,Math.min(l(_,Nf),kf));return{preflight:()=>E.#A(f),check:()=>E.#b(f,h),recordSuccess:(T)=>E.#M(T,"success"),recordFailure:(T,x)=>E.#M(T,"failure",x),recordNeutral:(T)=>E.#M(T,"neutral"),abandon:(T)=>E.#N(T),snapshot:()=>E.#j(f)}}#R(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let _=Object.freeze({kind:"noop"});return f.#t.set(_,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:_}},recordSuccess:(_)=>f.#S(_),recordFailure:(_)=>f.#S(_),recordNeutral:(_)=>f.#S(_),abandon:(_)=>f.#N(_),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#S(f){let _=this.#t.get(f);if(_?.kind==="noop")_.settled=!0;return}#A(f){let _=this.#E();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=_,this.#I(f,_),f.state==="closed")return{eligible:!0};if(f.state==="open"){let h=f.nextProbeAt??_;return _<h?this.#U(f,h-_):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return{eligible:!0};let E=Math.max(1,(f.probeLeaseExpiresAt??_+Sf)-_);return this.#U(f,Math.min(Sf,E))}#U(f,_){let{allowed:E,...h}=this.#P(f,_);return{eligible:!1,...h}}#b(f,_){let E=this.#E();if(f.detached)return this.#R().check();if(f.lastTouchedAt=E,this.#I(f,E),f.state==="closed")return this.#Y(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??E;if(E<T)return this.#P(f,T-E);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&E>=f.probeLeaseExpiresAt)return this.#O(f,E,_);let h=Math.max(1,(f.probeLeaseExpiresAt??E+Sf)-E);return this.#P(f,Math.min(Sf,h))}#Y(f,_,E){let h=Object.freeze({kind:_});return this.#t.set(h,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:_,...E!==void 0?{probeLeaseId:E}:{},settled:!1}),{allowed:!0,probe:_==="probe",token:h}}#O(f,_,E){let h=f.nextProbeLeaseId++;f.probeLeaseId=h,f.probeLeaseExpiresAt=_+E,f.lastTouchedAt=_;let T=this.#Y(f,"probe",h),x=f.lastFailure??{reason:"server_error"};return{...T,reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#P(f,_){let E=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:E.reason,...E.statusCode!==void 0?{statusCode:E.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(_)),nextProbeAt:this.#T()+Math.max(0,Math.ceil(_)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#M(f,_,E){let h=this.#t.get(f);if(!h||h.settled)return;if(h.settled=!0,h.kind==="noop"||!h.entry)return;let T=h.entry;if(T.detached||h.generation!==T.generation||h.kind==="regular"&&T.state!=="closed"||h.kind==="probe"&&(T.state!=="half_open"||h.probeLeaseId!==T.probeLeaseId))return;let x=this.#E();if(T.lastTouchedAt=x,h.kind==="probe"){if(_==="failure"&&E)return this.#u(T,E,x,"reopened");return this.#B(T)}if(_==="neutral")return;if(this.#V(T,_==="failure",x),_!=="failure"||!E)return;let S=Ef(T.samples),P=T.samples.length===0?0:S/T.samples.length;if(T.samples.length>=this.#h.minSamples&&P>=this.#h.errorRateThreshold)return this.#u(T,E,x,"opened");return}#u(f,_,E,h){let T={reason:_.reason,...D_(_.statusCode)!==void 0?{statusCode:D_(_.statusCode)}:{},...H_(_.retryAfterMs)!==void 0?{retryAfterMs:H_(_.retryAfterMs)}:{}},x=T.retryAfterMs??0,S=Math.max(f.configuredOpenDurationMs,x);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=S,f.nextProbeAt=E+S,f.lastFailure=T,{phase:h,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:S,nextProbeAt:this.#T()+S,openDurationMs:S,sampleCount:f.samples.length,failureCount:Ef(f.samples)}}#B(f){let _=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#N(f){let _=this.#t.get(f);if(!_||_.settled)return!1;if(_.settled=!0,_.kind==="noop")return!0;let E=_.entry;if(!E||E.detached||_.kind!=="probe"||_.generation!==E.generation||_.probeLeaseId!==E.probeLeaseId)return!1;return E.probeLeaseId=void 0,E.probeLeaseExpiresAt=void 0,E.lastTouchedAt=this.#E(),!0}#V(f,_,E){if(this.#I(f,E),f.samples.length>=this.#h.maxWindowEntries)f.samples.shift();f.samples.push({at:E,failure:_})}#I(f,_){let E=_-this.#h.windowMs,h=0;while(h<f.samples.length&&f.samples[h].at<E)h++;if(h>0)f.samples.splice(0,h)}#j(f){if(!f.detached)this.#I(f,this.#E());return{state:f.state,sampleCount:f.samples.length,failureCount:Ef(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#c(f){for(let[_,E]of this.#x)if(E.state==="closed"&&f-E.lastTouchedAt>this.#h.idleTtlMs)this.#H(_,E)}#D(){let f;for(let _ of this.#x.values())if(_.state==="closed"&&(!f||_.lastTouchedAt<f.lastTouchedAt))f=_;if(f)this.#H(f.key,f)}#H(f,_){_.detached=!0,this.#x.delete(f)}}var U_;function c_(){return U_??=new Y_,U_}import{randomBytes as aE}from"node:crypto";var b_=16,O_=128,B_=32,V_=3,j_=16,X_=96,z_=24,J_=12,W_=16,$_=4,k_=4,L_=67108864,G_=33554432,Z_=12,Q_=2,K_=2,C_=1,w_=15000,F_=30000;function Gf(){return{foreground:0,background:0,internal:0}}function Zf(){return{inFlight:Gf(),queued:Gf(),pendingBytes:Gf()}}function U(f){return f.foreground+f.background+f.internal}function W(f){return f.background+f.internal}function o_(f){return f.inFlight.foreground===0&&f.inFlight.background===0&&f.inFlight.internal===0&&f.queued.foreground===0&&f.queued.background===0&&f.queued.internal===0&&f.pendingBytes.foreground===0&&f.pendingBytes.background===0&&f.pendingBytes.internal===0}class Tf extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,_,E,h,T,x,S,P){super(f==="queue_full"?`Provider request admission ${_} ${h} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${_} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=_;this.requestClass=E;this.resource=h;this.inFlight=T;this.limit=x;this.queued=S;this.maxWaitMs=P;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function xf(f){return f instanceof Tf||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function z(f,_,E){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return _;return Math.min(f,E)}function yE(f){let _=z(f.globalMaxInFlight,b_,b_),E=z(f.globalMaxPending,O_,O_),h=z(f.domainMaxPending,B_,B_),T=Math.min(z(f.ownerMaxInFlight,V_,V_),_),x=Math.min(z(f.ownerMaxPending,j_,j_),E),S=Math.min(z(f.nonForegroundGlobalMaxPending,Math.min(X_,Math.max(1,Math.floor(E*3/4))),X_),E),P=Math.min(z(f.nonForegroundDomainMaxPending,Math.min(z_,Math.max(1,Math.floor(h*3/4))),z_),h),t=Math.min(z(f.nonForegroundOwnerMaxPending,Math.min(J_,Math.max(1,Math.floor(x*3/4))),J_),x),N=Math.min(z(f.internalGlobalMaxPending,Math.min(W_,Math.max(1,Math.floor(E/8))),W_),S),M=Math.min(z(f.internalDomainMaxPending,Math.min($_,Math.max(1,Math.floor(h/8))),$_),P),R=Math.min(z(f.internalOwnerMaxPending,Math.min(k_,Math.max(1,Math.floor(x/4))),k_),t),u=z(f.globalMaxPendingBytes,s,s),Y=Math.min(z(f.domainMaxPendingBytes,L_,L_),u),$=Math.min(z(f.ownerMaxPendingBytes,G_,G_),u),Q=Math.min(z(f.nonForegroundGlobalMaxInFlight,Math.min(Z_,_),Z_),_),K=Math.min(z(f.nonForegroundOwnerMaxInFlight,Math.min(Q_,T),Q_),T),o=Math.min(z(f.internalGlobalMaxInFlight,Math.min(K_,_),K_),_),Uf=z(f.internalDomainMaxInFlight,C_,C_),tf=z(f.agingMs,F_,F_);return{globalMaxInFlight:_,globalMaxPending:E,domainMaxPending:h,ownerMaxInFlight:T,ownerMaxPending:x,nonForegroundGlobalMaxPending:S,nonForegroundDomainMaxPending:P,nonForegroundOwnerMaxPending:t,internalGlobalMaxPending:N,internalDomainMaxPending:M,internalOwnerMaxPending:R,globalMaxPendingBytes:u,domainMaxPendingBytes:Y,ownerMaxPendingBytes:$,nonForegroundGlobalMaxInFlight:Q,nonForegroundOwnerMaxInFlight:K,internalGlobalMaxInFlight:o,internalDomainMaxInFlight:Uf,agingMs:tf}}function s_(f,_){if(!f.trim())throw Error(`${_} must not be blank`)}function dE(f){if(s_(f.sessionId,"sessionId"),s_(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<If||f.scope.maxConcurrent>uf)throw Error(`maxConcurrent must be between ${If} and ${uf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>s)throw Error(`maxPendingBytes must be between 1 and ${s}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>s+1)throw Error(`pendingBytes must be between 1 and ${s+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Qf(f,_){if(_!==void 0)return _;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function eE(f,_){return Pf(f,_,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class p_{#x;#t;#f;#E=[];#T=new Map;#h=new Map;#_=Zf();#R=1;#S=0;#A=!1;constructor(f={}){this.#x=f.processSecret?new Uint8Array(f.processSecret):aE(32),this.#t=f.now??(()=>performance.now()),this.#f=yE(f)}admit(f){if(dE(f),this.#A)throw this.#X("closed",f,{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight},this.#E.length);if(f.signal?.aborted)throw Qf(f.signal);let _=eE(f.scope,this.#x),E=this.#T.get(_),h=this.#h.get(f.ownerId),T=E??this.#Y(f.scope.maxConcurrent),x=h??this.#O();if(this.#E.length===0&&this.#P(T,x,f.requestClass)){if(!E)this.#T.set(_,T);if(!h)this.#h.set(f.ownerId,x),this.#R++;let u=this.#u(_,f.ownerId,f.requestClass),Y=this.#k(f,0);return{ready:Promise.resolve(u),getSnapshot:()=>({...Y}),cancel:()=>{Y={...Y}}}}let S=this.#U(f,T,x);if(S)throw this.#X("queue_full",f,S,this.#E.length);let P=this.#M(T,x,f.requestClass);if(f.maxWaitMs===0)throw this.#X("wait_timeout",f,P,this.#E.length);if(!E)this.#T.set(_,T);if(!h)this.#h.set(f.ownerId,x),this.#R++;let t,N,M=new Promise((u,Y)=>{t=u,N=Y});M.catch(()=>{return});let R={domainKey:_,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#t(),signal:f.signal,resolve:t,reject:N,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#c(R,Qf(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#j(R),f.maxWaitMs),R.timer.unref?.(),this.#E.push(R),this.#b(T,x,R),this.#N(),{ready:M,getSnapshot:()=>this.#$(R),cancel:(u)=>this.#c(R,Qf(f.signal,u))}}close(){if(this.#A)return;this.#A=!0;for(let f of[...this.#E]){let _=this.#T.get(f.domainKey),E=this.#h.get(f.ownerId),h=_&&E?this.#M(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new Tf("closed",h.scope,f.requestClass,h.resource,h.inFlight,h.limit,this.#E.length,f.maxWaitMs))}}getStats(){return{inFlight:U(this.#_.inFlight),queued:this.#E.length,pendingBytes:U(this.#_.pendingBytes),nonForegroundInFlight:W(this.#_.inFlight),internalInFlight:this.#_.inFlight.internal,nonForegroundQueued:W(this.#_.queued),internalQueued:this.#_.queued.internal,nonForegroundPendingBytes:W(this.#_.pendingBytes),internalPendingBytes:this.#_.pendingBytes.internal,domainCount:this.#T.size,ownerCount:this.#h.size,closed:this.#A}}#U(f,_,E){let h=(M,R,u)=>R>=u?{scope:M,resource:"pending_count",inFlight:R,limit:u}:void 0;if(f.requestClass==="internal"){let M=h("class",this.#_.queued.internal,this.#f.internalGlobalMaxPending)??h("class",E.counters.queued.internal,this.#f.internalOwnerMaxPending)??h("class",_.counters.queued.internal,this.#f.internalDomainMaxPending);if(M)return M}if(f.requestClass!=="foreground"){let M=h("class",W(this.#_.queued),this.#f.nonForegroundGlobalMaxPending)??h("class",W(E.counters.queued),this.#f.nonForegroundOwnerMaxPending)??h("class",W(_.counters.queued),this.#f.nonForegroundDomainMaxPending);if(M)return M}let T=h("global",this.#E.length,this.#f.globalMaxPending)??h("owner",U(E.counters.queued),this.#f.ownerMaxPending)??h("domain",U(_.counters.queued),this.#f.domainMaxPending);if(T)return T;let x=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),S=Math.min(x,this.#f.domainMaxPendingBytes),P=Math.min(x,this.#f.ownerMaxPendingBytes),t=(M,R)=>f.pendingBytes>R-M,N=(M)=>{if(M==="owner")return{scope:M,resource:"pending_bytes",inFlight:U(E.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(M==="domain")return{scope:M,resource:"pending_bytes",inFlight:U(_.counters.inFlight),limit:_.maxConcurrent};return{scope:M,resource:"pending_bytes",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let M=Math.max(1,Math.floor(x/8)),R=Math.max(1,Math.floor(S/4)),u=Math.max(1,Math.floor(P/4));if(t(this.#_.pendingBytes.internal,M)||t(E.counters.pendingBytes.internal,u)||t(_.counters.pendingBytes.internal,R))return N("class")}if(f.requestClass!=="foreground"){let M=Math.max(1,Math.floor(x*3/4)),R=Math.max(1,Math.floor(S*3/4)),u=Math.max(1,Math.floor(P/2));if(t(W(this.#_.pendingBytes),M)||t(W(E.counters.pendingBytes),u)||t(W(_.counters.pendingBytes),R))return N("class")}if(t(U(this.#_.pendingBytes),x))return N("global");if(t(U(E.counters.pendingBytes),P))return N("owner");if(t(U(_.counters.pendingBytes),S))return N("domain");return}#b(f,_,E){let{requestClass:h,pendingBytes:T}=E;this.#_.queued[h]++,f.counters.queued[h]++,_.counters.queued[h]++,this.#_.pendingBytes[h]+=T,f.counters.pendingBytes[h]+=T,_.counters.pendingBytes[h]+=T}#Y(f){return{maxConcurrent:f,counters:Zf()}}#O(){return{order:this.#R,counters:Zf()}}#P(f,_,E){if(U(this.#_.inFlight)>=this.#f.globalMaxInFlight)return!1;if(U(f.counters.inFlight)>=f.maxConcurrent)return!1;if(U(_.counters.inFlight)>=this.#f.ownerMaxInFlight)return!1;if(E==="foreground")return!0;if(W(this.#_.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(W(_.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let h=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=h)return!1;if(E!=="internal")return!0;return this.#_.inFlight.internal<this.#f.internalGlobalMaxInFlight&&f.counters.inFlight.internal<this.#f.internalDomainMaxInFlight}#M(f,_,E){if(U(_.counters.inFlight)>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:U(_.counters.inFlight),limit:this.#f.ownerMaxInFlight};if(E!=="foreground"&&W(_.counters.inFlight)>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(_.counters.inFlight),limit:this.#f.nonForegroundOwnerMaxInFlight};if(U(f.counters.inFlight)>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent};if(E!=="foreground"){let h=Math.max(1,f.maxConcurrent-1);if(W(f.counters.inFlight)>=h)return{scope:"class",resource:"stream",inFlight:W(f.counters.inFlight),limit:h}}if(E==="internal"&&f.counters.inFlight.internal>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.counters.inFlight.internal,limit:this.#f.internalDomainMaxInFlight};if(U(this.#_.inFlight)>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};if(E!=="foreground"&&W(this.#_.inFlight)>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:W(this.#_.inFlight),limit:this.#f.nonForegroundGlobalMaxInFlight};if(E==="internal"&&this.#_.inFlight.internal>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#_.inFlight.internal,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:U(f.counters.inFlight),limit:f.maxConcurrent}}#u(f,_,E){let h=this.#T.get(f),T=this.#h.get(_);if(!h||!T)throw Error("Provider admission accounting state is unavailable");this.#_.inFlight[E]++,h.counters.inFlight[E]++,T.counters.inFlight[E]++;let x=!1;return{release:()=>{if(x)return;x=!0,this.#B(f,_,E)}}}#B(f,_,E){let h=this.#T.get(f),T=this.#h.get(_);if(this.#_.inFlight[E]--,h)h.counters.inFlight[E]--;if(T)T.counters.inFlight[E]--;this.#z(f,_),this.#N()}#N(){if(this.#A)return;while(this.#E.length>0){let f=this.#t(),_=new Map;for(let[P,t]of this.#E.entries()){let N=this.#T.get(t.domainKey),M=this.#h.get(t.ownerId);if(N===void 0||M===void 0||!this.#P(N,M,t.requestClass))continue;let R=this.#V(t,f),u=_.get(t.ownerId);if(!u||R<u.rank||R===u.rank&&P<u.index)_.set(t.ownerId,{pending:t,rank:R,index:P})}let E=[..._.values()].filter(({pending:P})=>{let t=this.#T.get(P.domainKey),N=this.#h.get(P.ownerId);return t!==void 0&&N!==void 0&&this.#P(t,N,P.requestClass)}).map(({pending:P,rank:t})=>({pending:P,rank:t,order:this.#h.get(P.ownerId).order}));if(E.length===0)return;let h=Math.min(...E.map((P)=>P.rank)),T=E.filter((P)=>P.rank===h),S=T.filter((P)=>P.order>this.#S).sort((P,t)=>P.order-t.order)[0]??T.sort((P,t)=>P.order-t.order)[0];this.#I(S.pending,S.order)}}#V(f,_){let E=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,h=Math.floor(Math.max(0,_-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,E-h)}#I(f,_){if(!this.#H(f,!1))return;f.settled=!0,f.admitted=!0,this.#S=_;let E=this.#u(f.domainKey,f.ownerId,f.requestClass);f.permit=E,f.resolve(E)}#j(f){let _=this.#T.get(f.domainKey),E=this.#h.get(f.ownerId),h=_&&E?this.#M(_,E,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};this.#D(f,new Tf("wait_timeout",h.scope,f.requestClass,h.resource,h.inFlight,h.limit,this.#E.length,f.maxWaitMs))}#c(f,_){this.#D(f,_)}#D(f,_){if(!this.#H(f))return;f.settled=!0,f.reject(_),this.#N()}#H(f,_=!0){if(f.settled||f.admitted)return!1;let E=this.#E.indexOf(f);if(E<0)return!1;this.#E.splice(E,1);let h=this.#T.get(f.domainKey),T=this.#h.get(f.ownerId);if(h&&T)this.#J(h,T,f);if(this.#W(f),_)this.#z(f.domainKey,f.ownerId);return!0}#J(f,_,E){let{requestClass:h,pendingBytes:T}=E;this.#_.queued[h]--,f.counters.queued[h]--,_.counters.queued[h]--,this.#_.pendingBytes[h]-=T,f.counters.pendingBytes[h]-=T,_.counters.pendingBytes[h]-=T}#W(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#z(f,_){let E=this.#T.get(f);if(E&&o_(E.counters))this.#T.delete(f);let h=this.#h.get(_);if(h&&o_(h.counters))this.#h.delete(_)}#$(f){let _=Math.max(0,Math.floor(this.#t()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#E.length,inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs};let E=this.#T.get(f.domainKey),h=this.#h.get(f.ownerId),T=E&&h?this.#M(E,h,f.requestClass):{scope:"global",resource:"stream",inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:T.resource,scope:T.scope,reason:"capacity",queuePosition:this.#L(f,T.scope),queueDepth:this.#E.length,inFlight:T.inFlight,limit:T.limit,waitMs:_,maxWaitMs:f.maxWaitMs}}#k(f,_){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#E.length,inFlight:U(this.#_.inFlight),limit:this.#f.globalMaxInFlight,waitMs:_,maxWaitMs:f.maxWaitMs}}#L(f,_){let E=this.#E.filter((h)=>{switch(_){case"owner":return h.ownerId===f.ownerId;case"domain":return h.domainKey===f.domainKey;case"class":return h.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,E.indexOf(f)+1)}#X(f,_,E,h){return new Tf(f,E.scope,_.requestClass,E.resource,E.inFlight,E.limit,h,_.maxWaitMs)}}var v_;function m_(){return v_??=new p_,v_}function q_(f,_={}){let E=_.maxBytes??134217728,h=_.maxNodes??1e5;if(!Number.isSafeInteger(E)||E<=0||E>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(h)||h<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,x=0,S=0,P=!1,t=(M)=>{if(P||M<=0)return;if(!Number.isSafeInteger(M)||M>E-x){x=E+1,P=!0;return}x+=M},N=(M)=>{if(P)return;if(S+=1,S>h){t(E+1);return}if(M===null){t(4);return}switch(typeof M){case"string":t(Buffer.byteLength(M,"utf8"));return;case"number":case"bigint":t(8);return;case"boolean":t(4);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(M))return;if(T.add(M),ArrayBuffer.isView(M)){t(32+M.byteLength);return}if(M instanceof ArrayBuffer){t(32+M.byteLength);return}if(M instanceof Date){t(40);return}if(M instanceof RegExp){t(32+Buffer.byteLength(M.source,"utf8"));return}if(M instanceof Map){t(32);for(let[R,u]of M)if(N(R),N(u),P)return;return}if(M instanceof Set){t(32);for(let R of M)if(N(R),P)return;return}if(M instanceof WeakMap||M instanceof WeakSet){t(32);return}if(Array.isArray(M)){t(16);for(let R of M)if(N(R),P)return;return}t(32);for(let R of Reflect.ownKeys(M)){if(typeof R!=="string")continue;let u=Object.getOwnPropertyDescriptor(M,R);if(!u?.enumerable||!("value"in u))continue;if(t(8+Buffer.byteLength(R,"utf8")),N(u.value),P)return}};return N(f),x}function g_(f){return q_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:s})}var l_=new WeakSet;class a extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,_){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=_;this.name="ProviderRecoveryBudgetExceededError"}}class of extends Error{timeoutMs;code="PROVIDER_REQUEST_DEADLINE_EXCEEDED";constructor(f){super(`Provider request deadline exceeded after ${f}ms`);this.timeoutMs=f;this.name="ProviderRequestDeadlineExceededError"}}var nE=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],rE=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],iE=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function a_(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function fh(f){let _=a_(f);return rE.some((E)=>_.includes(E))}function sf(f){if(f!==null&&typeof f==="object")l_.add(f)}function RT(f){return f!==null&&typeof f==="object"&&l_.has(f)}function _h(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function Eh(f){if(f===null||typeof f!=="object")return;let _=f;for(let E of["status","statusCode"]){let h=_[E];if(typeof h==="number"&&Number.isInteger(h))return h}return}function hh(f){let _=f.match(/^(?:error:\s*)?(\d{3})\b/),E=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),h=Number(_?.[1]??E?.[1]);return Number.isInteger(h)?h:void 0}function y(f,_){let E=a_(f),h=_h(f);if(h==="STREAM_IDLE_TIMEOUT"||h==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||E.includes("request aborted")||E==="aborted")return{retryable:!1};if(nE.some((x)=>E.includes(x))||fh(f))return{retryable:!1};if(_?.shouldRetry==="false")return{retryable:!1,statusCode:_.statusCode};if(h==="PROVIDER_REQUEST_DEADLINE_EXCEEDED")return{retryable:!0,reason:"timeout"};let T=_?.statusCode??Eh(f)??hh(E);if(_?.shouldRetry==="true")return{retryable:!0,reason:T===429?"rate_limit":T===408||T===409?"timeout":"server_error",statusCode:T};if(T===429)return{retryable:!0,reason:"rate_limit",statusCode:T};if(T===408||T===409)return{retryable:!0,reason:"timeout",statusCode:T};if(T!==void 0&&T>=500&&T<=599)return{retryable:!0,reason:"server_error",statusCode:T};if(h==="PROVIDER_STREAM_CLOSED"||E.includes("stream closed before completion")||E.includes("ended without")||E.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(iE.some((x)=>E.includes(x)))return{retryable:!0,reason:"transport",statusCode:T};if(E.includes("timeout")||E.includes("timed out")||E.includes("temporarily unavailable")||E.includes("upstream_error")||E.includes("overloaded")||E.includes("rate limit")||E.includes("too many requests")||E.includes("service unavailable")||E.includes("server error")||E.includes("internal error")||E.includes("please retry")||E.includes("try your request again"))return{retryable:!0,reason:E.includes("rate")||E.includes("too many")?"rate_limit":E.includes("timeout")||E.includes("timed out")?"timeout":"server_error",statusCode:T};return{retryable:!1,statusCode:T}}function vf(f,_){if(!f)return;if(f.retryAfterMs!==void 0){let T=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(T))return Math.max(0,T)}if(f.retryAfter===void 0)return;let E=Number.parseFloat(f.retryAfter);if(Number.isFinite(E))return Math.max(0,E*1000);let h=Date.parse(f.retryAfter);return Number.isFinite(h)?Math.max(0,h-_):void 0}function y_(f,_,E={}){let h=E.now??Date.now(),T=E.maxDelayMs??60000,x=vf(_,h);if(x!==void 0)return Math.min(Math.ceil(x),T);let S=Math.max(0,f-1),P=E.maxExponentialDelayMs??8000,t=Math.min(500*2**S,P),N=Math.max(0,Math.min(1,E.random??Math.random())),M=t*(0.75+N*0.25);return Math.min(Math.round(M),T)}function n_(f,_){let E=f.onPayload;f.onPayload=async(h,T)=>{let x=E?await E(h,T):h;return _(x===void 0?h:x,T)}}function Th(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function wf(f,_,E){if(!f.enablePromptCaching)return"none";if(E&&_.api==="openai-completions"&&!_.baseUrl.includes("api.openai.com"))return"long";return"short"}function xh(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function th(f,_,E,h){let T=h?void 0:Th(E);if(!T){if(_.api==="anthropic-messages")f.thinkingEnabled=!1;if(_.api==="google-generative-ai"||_.api==="google-vertex")f.thinking={enabled:!1};return}switch(_.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:xh(T)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=T;break;default:f.reasoningEffort=T}}function Mh(f,_,E){if(!E)return;switch(_){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:E};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:E}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:E};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function Rh(f,_,E){let h=E.serviceTier;if(!h)return;if(_.api==="openai-responses"||_.api==="openai-codex-responses"||_.api==="azure-openai-responses"){f.serviceTier=h;return}if(_.api!=="openai-completions"&&!(_.api==="anthropic-messages"&&h==="fast"))return;n_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return _.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:h}})}function Ah(f,_,E){let h=E.responseVerbosity;if(!h)return;if(e_(_,h),_.api==="openai-codex-responses"){f.textVerbosity=h;return}n_(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(_.api==="openai-completions")return{...T,verbosity:h};let x="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...x,verbosity:h}}})}function r_(f,_,E,h,T=!1){let x={apiKey:f.apiKey,headers:f.customHeaders,signal:E,temperature:h?.temperature??f.temperature??0,maxTokens:h?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:wf(f,_,h?.providerSessionId),sessionId:h?.providerSessionId};if(th(x,_,f,T),Mh(x,_.api,h?.toolChoice?.toolName),Rh(x,_,f),Ah(x,_,f),_.api==="azure-openai-responses")x.azureBaseUrl=f.baseUrl,x.azureApiVersion=f.apiVersion,x.azureDeploymentName=_.id;return x}function d_(f,_){let E=_.get("x-should-retry");return{statusCode:f,..._.get("retry-after")!==null?{retryAfter:_.get("retry-after")??void 0}:{},..._.get("retry-after-ms")!==null?{retryAfterMs:_.get("retry-after-ms")??void 0}:{},...E==="true"||E==="false"?{shouldRetry:E}:{}}}var Ph=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function i_(f,_,E){let h=f.onResponse;if(f.onResponse=async(x,S)=>{let P=new Headers(x.headers);E(d_(x.status,P)),await h?.(x,S)},!Ph.has(_.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(x,S)=>{let P=await T(x,S);return E(d_(P.status,P.headers)),P}}function fE(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Hf=300000,Sh=30000;class _E extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class EE extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function pf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function Nh(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Hf}function Ih(f,_){if(_===0)return;let E=_!==void 0&&_>0?_:Sh;return Math.max(1,Math.min(E,Math.floor(f/2)))}function uh(f,_,E){if(E?.aborted)return Promise.reject(pf(E));return new Promise((h,T)=>{let x=!1,S=()=>{clearTimeout(M),E?.removeEventListener("abort",N)},P=(R)=>{if(x)return;x=!0,S(),h(R)},t=(R)=>{if(x)return;x=!0,S(),T(R instanceof Error?R:Error(String(R)))},N=()=>{if(E)t(pf(E))},M=setTimeout(()=>P({kind:"timer"}),Math.max(0,_));if(E?.addEventListener("abort",N,{once:!0}),E?.aborted){N();return}f.then((R)=>P({kind:"next",result:R}),t)})}async function*Dh(f,_,E){let h=Nh(_),T=Ih(h,_.stallWarningMs);if(_.signal?.aborted)throw pf(_.signal);let x=Date.now(),S=Promise.resolve().then(()=>f.next()),P;for(;;){let N=await uh(S,(P?h:T??h)-(Date.now()-x),_.signal);if(N.kind==="next"){if(P)yield{...P,phase:"recovered",durationMs:Math.max(P.durationMs,Date.now()-x)};return N.result}if(!P&&T!==void 0){E.stallCount++,P={phase:"detected",stallCount:E.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:h,outputStarted:E.outputStarted},yield P;continue}let M=new _E(h);throw _.abort?.(M),M}}async function*hE(f,_,E,h,T={}){let S=f.stream(_,E,h)[Symbol.asyncIterator](),P=0,t=!1,N={stallCount:0,outputStarted:!1};try{while(!0){let M=Dh(S,T,N),R=await M.next();while(!R.done)yield{providerStall:R.value},R=await M.next();let u=R.value;if(u.done)throw new EE;let Y=u.value;switch(Y.type){case"text_delta":N.outputStarted=!0,yield{content:Y.delta};break;case"thinking_delta":N.outputStarted=!0,yield{reasoningContent:Y.delta};break;case"toolcall_end":N.outputStarted=!0,yield{toolCalls:[{index:P++,id:Y.toolCall.id,type:"function",function:{name:Y.toolCall.name,arguments:JSON.stringify(Y.toolCall.arguments)}}]};break;case"done":t=!0,yield{finishReason:Y.reason,usage:fE(Y.message.usage)};return;case"error":throw Error(Y.error.errorMessage??`Request ${Y.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!t)Promise.resolve(S.return?.()).catch(()=>{return})}}var mf=g("Chat"),Hh=1;function Uh(f,_){let E=_.provider===f.provider,h=E&&_.channel===void 0,T=_.channel;return{...f,provider:_.provider,model:_.model,apiKey:T?.apiKey??(h?f.apiKey:void 0),baseUrl:T?.baseUrl??(h?f.baseUrl:void 0),temperature:T?.temperature??f.temperature,maxOutputTokens:T?.maxOutputTokens??(h?f.maxOutputTokens:void 0),timeout:T?.timeout??f.timeout,streamIdleTimeout:T?.streamIdleTimeout??f.streamIdleTimeout,apiVersion:T?.apiVersion??(h?f.apiVersion:void 0),customHeaders:T?.customHeaders??(h?f.customHeaders:void 0),enablePromptCaching:T?.enablePromptCaching??(h?f.enablePromptCaching:void 0),serviceTier:E?f.serviceTier:void 0,responseVerbosity:E?f.responseVerbosity:void 0,fallbackModels:void 0}}function Yh(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((_)=>_.type==="image_url"))}function ch(f){let E=f.findLast((h)=>{let T=h.metadata;return T!==null&&typeof T==="object"&&!Array.isArray(T)&&T.isCompactSummary===!0})?.metadata;return E!==null&&typeof E==="object"&&!Array.isArray(E)&&typeof E.parentId==="string"?E.parentId:""}function bh(f,_){let E=y(f,_);if(!E.retryable||!E.reason)return;let h=E.statusCode;switch(E.reason){case"rate_limit":if(h!==429)return;break;case"server_error":if(h===void 0||h<500||h>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=vf(_,Date.now());return{reason:E.reason,...h!==void 0?{statusCode:h}:{},...T!==void 0?{retryAfterMs:T}:{}}}function qf(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class af{config;models;model;promptCacheBreakMonitor=new Jf;admissionFallbackOwnerId=`pi-service-${process.pid}-${Hh++}`;constructor(f){let _=zf(f);this.config={...f,maxContextTokens:_.model.contextWindow,maxOutputTokens:f.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model,mf.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,_,E,h){let T="",x="",S=[],P,t;for await(let N of this.streamChat(f,_,E,h)){T+=N.content??"",x+=N.reasoningContent??"";for(let M of N.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)S.push(M);P=N.usage??P,t=N.finishReason??t}return{content:T,...x?{reasoningContent:x}:{},...S.length>0?{toolCalls:S}:{},usage:P,finishReason:t}}async*streamChat(f,_,E,h){let T=h?.toolChoice?.toolName;if(T&&!_?.some((A)=>A.name===T))throw Error(`Required tool is unavailable: ${T}`);let x=R_(f);if(x.some((A)=>Yh(A))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let S=Boolean(T)||A_(x),P=await M_(x,this.model,_,E,T),t=(A,I)=>{let B=h?.providerSessionId;if(!B||!A.usage)return A;if(!this.config.enablePromptCaching)return this.promptCacheBreakMonitor.clear(B),A;let c=wf(this.config,I,B),H=this.promptCacheBreakMonitor.observe({sessionId:B,modelIdentity:`${I.provider}\x00${I.api}\x00${I.id}`,context:P,retention:c,contextEpoch:ch(x),policy:{baseUrl:I.baseUrl??this.config.baseUrl??"",retention:c,requiredTool:T??"",reasoningEnabled:this.config.reasoningEnabled??!1,reasoningEffort:this.config.reasoningEffort??this.config.reasoningLevel??"",serviceTier:this.config.serviceTier??"",responseVerbosity:this.config.responseVerbosity??"",temperature:h?.temperature??this.config.temperature??0,maxOutputTokens:h?.maxOutputTokens??this.config.maxOutputTokens??0,customHeaders:this.config.customHeaders??{}},usage:A.usage});if(!H)return A;return mf.warn("[PiAIChatService] Prompt cache break detected",{reason:H.reason,previousCacheReadTokens:H.previousCacheReadTokens,cacheReadTokens:H.cacheReadTokens,tokenDrop:H.tokenDrop,callNumber:H.callNumber}),{...A,usage:{...A.usage,promptCacheBreak:H}}},N=g_({messages:x,context:P,tools:_,requestOptions:h}),M=h?.providerRecovery;if(M&&!xE(M.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let R=M?.mode==="bounded_foreground"&&M.budgetMs>0?{budgetMs:M.budgetMs,startedAt:void 0}:void 0,u=R?"bounded_foreground":"standard",Y=this.config.maxRetries??2,$=this.config.maxRetries??(R?TE:2),Q=R!==void 0&&this.config.maxRetries===void 0,K=0,o,Uf=this.config.providerCircuitRegistry??c_(),tf=this.config.providerCircuitBreakerOpenMs??Wf,tE=Math.max(Nf,Math.min(this.config.streamIdleTimeout??Hf,kf)),ME=this.config.providerRequestAdmissionScheduler??m_(),RE=this.config.providerRequestConcurrency??Kf,yf=this.config.providerRequestAdmissionMs??Cf,AE=this.config.providerRequestPendingBytes??Ff,Yf=h?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},PE=(A,I)=>Uf.get({provider:A.provider,api:A.api,baseUrl:A.baseUrl??I.baseUrl??"",model:A.id,serviceTier:I.serviceTier,apiVersion:I.apiVersion,apiKey:I.apiKey,customHeaders:I.customHeaders,openDurationMs:tf,probeLeaseMs:tE}),SE=(A,I)=>({provider:A.provider,api:A.api,baseUrl:A.baseUrl??I.baseUrl??"",model:A.id,serviceTier:I.serviceTier,apiVersion:I.apiVersion,apiKey:I.apiKey,customHeaders:I.customHeaders,maxConcurrent:RE,maxPendingBytes:AE}),j=(A=Date.now())=>{if(!R)return;let I=R.startedAt===void 0?0:Math.min(R.budgetMs,Math.max(0,A-R.startedAt));return{recoveryBudgetMs:R.budgetMs,recoveryElapsedMs:I,recoveryRemainingMs:Math.max(0,R.budgetMs-I)}},v=()=>({mode:u,...j()??{}}),df=()=>{if(R&&R.startedAt===void 0)R.startedAt=Date.now()},w=()=>{let A=j();return new a(R?.budgetMs??0,A?.recoveryElapsedMs??0)},d=()=>!Q||K<$+1,cf=(A,I)=>{let{state:B,...c}=I;return{phase:A,...c,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}},ef=(A)=>({phase:"rejected",requestClass:A.requestClass,resource:A.resource,scope:A.scope,reason:A.reason,queuePosition:0,queueDepth:Math.max(0,A.queued),inFlight:Math.max(0,A.inFlight),limit:Math.max(0,A.limit),waitMs:A.reason==="wait_timeout"?A.maxWaitMs:0,maxWaitMs:A.maxWaitMs,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),NE=async function*(A,I){let B=j()?.recoveryRemainingMs,c=B!==void 0&&R?.startedAt!==void 0?Math.min(yf,B):yf,H;try{H=ME.admit({scope:SE(A,I),sessionId:Yf.sessionId,ownerId:Yf.ownerId,requestClass:Yf.requestClass,maxWaitMs:c,pendingBytes:N,signal:E})}catch(b){if(xf(b)){if(b.reason==="wait_timeout"&&R?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(b)}}throw b}let L=H.getSnapshot();if(L.state==="admitted")return await H.ready;yield{providerAdmission:cf("queued",L)};let F=H.ready.then((b)=>({kind:"ready",permit:b}),(b)=>({kind:"error",error:b}));while(!0){let b=H.getSnapshot(),O=Math.max(1,Math.min(w_,Math.max(1,c-b.waitMs))),J,X=new Promise((p)=>{J=setTimeout(()=>p({kind:"heartbeat"}),O),J.unref?.()}),G=await Promise.race([F,X]);if(J)clearTimeout(J);if(G.kind==="heartbeat"){yield{providerAdmission:cf("queued",H.getSnapshot())};continue}if(G.kind==="error"){if(xf(G.error)){if(G.error.reason==="wait_timeout"&&R?.startedAt!==void 0&&(j()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:ef(G.error)}}throw G.error}return yield{providerAdmission:cf("admitted",H.getSnapshot())},G.permit}},IE=(A,I)=>{if(!d())throw w();if(Q)K++;o=void 0;let B=new AbortController,c=E?x_(E,B.signal):B.signal,H=typeof I.timeout==="number"&&Number.isFinite(I.timeout)&&I.timeout>0?Math.max(1,Math.floor(I.timeout)):void 0,L;if(R?.startedAt!==void 0){let O=j()?.recoveryRemainingMs??0;if(O<=0)throw w();L={remainingMs:O,error:new a(R.budgetMs,R.budgetMs)}}let F=r_(I,A,c,h,S);i_(F,A,(O)=>{o=O});let b=hE(this.models,A,P,F,{idleTimeoutMs:I.streamIdleTimeout??Hf,signal:c,abort:(O)=>B.abort(O)});return async function*(){let O,J;try{if(H!==void 0&&(L===void 0||H<L.remainingMs)){let X=new of(H);O=setTimeout(()=>B.abort(X),H),O.unref?.()}if(L){let X=L;J=setTimeout(()=>B.abort(X.error),X.remainingMs),J.unref?.()}yield*b}finally{if(O)clearTimeout(O);if(J)clearTimeout(J)}}()},nf=this,q=(A)=>({phase:A.phase,reason:A.reason,...A.statusCode!==void 0?{statusCode:A.statusCode}:{},...A.retryAfterMs!==void 0?{retryAfterMs:A.retryAfterMs}:{},...A.nextProbeAt!==void 0?{nextProbeAt:A.nextProbeAt}:{},openDurationMs:A.openDurationMs,sampleCount:A.sampleCount,failureCount:A.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),rf=(A,I)=>({phase:A,reason:I.reason,...I.statusCode!==void 0?{statusCode:I.statusCode}:{},retryAfterMs:I.retryAfterMs,...I.nextProbeAt!==void 0?{nextProbeAt:I.nextProbeAt}:{},openDurationMs:I.openDurationMs,sampleCount:I.sampleCount,failureCount:I.failureCount,...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),uE=(A)=>({phase:"probe",reason:A.reason??"server_error",...A.statusCode!==void 0?{statusCode:A.statusCode}:{},openDurationMs:A.openDurationMs??tf,...A.sampleCount!==void 0?{sampleCount:A.sampleCount}:{},...A.failureCount!==void 0?{failureCount:A.failureCount}:{},...j()?{recoveryRemainingMs:j()?.recoveryRemainingMs}:{}}),bf=(A,I,B)=>({providerRetry:{phase:"exhausted",attempt:A,maxRetries:$,reason:I,...B!==void 0?{statusCode:B}:{},...v(),exhaustedBy:"recovery_budget"}}),f_=async function*(A,I,B,c,H){let L,F=!1,b,O,J=PE(A,I);for(let X=0;X<=c;X++){if(!d())break;let G,p;while(!G){let D=J.preflight();while(!D.eligible){if(b=D.reason,O=D.statusCode,!R||!H){let C=rf("rejected",D);throw yield{providerCircuit:C},new hf(C)}df();let V=j()?.recoveryRemainingMs??0;if(V<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}yield{providerCircuit:rf("waiting",D)};let m=Math.min(Math.max(1,D.retryAfterMs),gf,V);if(await i(m,E,{throwOnAbort:!0}),(j()?.recoveryRemainingMs??0)<=0){let C=w();throw yield bf(Q?Math.max(0,K-1):X,D.reason,D.statusCode),C}D=J.preflight()}try{p=yield*NE(A,I)}catch(Z){if(Z instanceof a)yield bf(Q?Math.max(0,K-1):X,b??"timeout",O);throw Z}let k=J.check();if(k.allowed)G=k;else p.release(),p=void 0}let e=G.token;if(G.probe)yield{providerCircuit:uE(G)};try{let D=!1,k=!1;for await(let Z of IE(A,I)){if(Z.providerStall){yield Z;continue}let V=Q?K-1:X;if(V>0&&b&&!D)D=!0,yield{providerRetry:{phase:"recovered",attempt:V,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};if(!k){k=!0;let m=J.recordSuccess(e);if(m)yield{providerCircuit:q(m)}}F=!0,B(),yield t(Z,A)}if(!k){let Z=J.recordSuccess(e);if(Z)yield{providerCircuit:q(Z)}}return}catch(D){if(p?.release(),L=D,nf.logIdleTimeout(D,F,A),await nf.handleAbort(E),D instanceof a){if(F)throw sf(D),D;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b??"timeout",...O!==void 0?{statusCode:O}:{},...v(),exhaustedBy:"recovery_budget"}},D}let k=y(D,o);if(F)throw sf(D),D;let Z=bh(D,o),V=Z?J.recordFailure(e,Z):o&&!qf(D)?J.recordNeutral(e):void 0;if(V)yield{providerCircuit:q(V)};if(!k.retryable||!k.reason){if(X>0&&b)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:b,...O!==void 0?{statusCode:O}:{},...v()}};throw D}b=k.reason,O=k.statusCode;let m=X<c&&d();if(V&&V.phase!=="closed"&&m&&(!R||!H)){let C={...q(V),phase:"rejected"};throw yield{providerCircuit:C},new hf(C)}if(m){df();let C=Q?K:X+1,HE=y_(C,o,R?{maxDelayMs:lf,maxExponentialDelayMs:lf}:void 0),E_=V&&V.phase!=="closed"?V.retryAfterMs??0:0;if(R&&E_>0&&V)yield{providerCircuit:{...q(V),phase:"waiting"}};let UE=j(),Bf=Math.max(HE,E_),n=R?Math.min(Bf,UE?.recoveryRemainingMs??Bf):Bf,Rf={attempt:C,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Rf,delayMs:n,nextRetryAt:Date.now()+n,...v()}},R){let r=n;while(r>0){let h_=Math.min(r,gf);if(await i(h_,E,{throwOnAbort:!0}),r-=h_,(j()?.recoveryRemainingMs??0)<=0){let Af=w();throw yield{providerRetry:{phase:"exhausted",...Rf,...v(),exhaustedBy:"recovery_budget"}},Af}if(r>0){if(V&&V.phase!=="closed"&&V.nextProbeAt!==void 0){let Af=Math.max(0,V.nextProbeAt-Date.now());if(Af>0)yield{providerCircuit:{...q(V),phase:"waiting",retryAfterMs:Af}}}yield{providerRetry:{phase:"waiting",...Rf,delayMs:n,nextRetryAt:Date.now()+r,...v()}}}}}else await i(n,E,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Rf,...v()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,K-1):X,maxRetries:$,reason:k.reason,...k.statusCode!==void 0?{statusCode:k.statusCode}:{},...v(),...R&&(H||!d())?{exhaustedBy:"attempt_limit"}:{}}}}finally{J.abandon(e),p?.release()}}throw L},Of,__=!1,Mf=this.config.fallbackModels??[],DE=R&&Mf.length>0?Math.min(Y,$):$;try{for await(let A of f_(this.model,this.config,()=>{__=!0},DE,Mf.length===0))yield A;return}catch(A){if(Of=A,__||!xf(A)&&!Lf(A)&&!qf(A)&&!y(A,o).retryable)throw A}for(let[A,I]of Mf.entries()){if(!d())break;yield{modelFallback:!0};let B=!1;try{let c=Uh(this.config,I),H=N_(c,I),L=A===Mf.length-1,F=R&&!L?Math.min(Y,$):$;for await(let b of f_(H,c,()=>{B=!0},F,L))yield b;return}catch(c){if(Of=c,B||!xf(c)&&!Lf(c)&&!qf(c)&&!y(c,o).retryable)throw c}}throw Of}async handleAbort(f){if(f?.aborted)await i(0,f,{throwOnAbort:!0})}logIdleTimeout(f,_,E){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;mf.warn("[PiAIChatService] Provider stream idle timeout",{provider:E.provider,model:E.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:_})}getConfig(){return{...this.config}}updateConfig(f){let _={...this.config,...f},E=zf(_);this.config={..._,maxContextTokens:E.model.contextWindow,maxOutputTokens:_.maxOutputTokens??E.model.maxTokens},this.models=E.models,this.model=E.model}}var Oh=g("Service");async function GT(f){let _=f;if(_.provider){let E=T_(_.provider);if(Object.keys(E).length>0)_={..._,customHeaders:{...E,..._.customHeaders}},Oh.debug(`Injected ${_.provider} specific headers:`,Object.keys(E))}return Bh(_)}function Bh(f){return new af(f)}
|
package/package.json
CHANGED
package/dist/chunk-2z75emht.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ee as a}from"./chunk-q919ypcz.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{a as createChatServiceAsync};
|
package/dist/chunk-3j413cgh.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{fe as a,ge as b,he as c}from"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
package/dist/chunk-8bsyhr4v.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jd as a,kd as b}from"./chunk-bkajr86v.js";import"./chunk-y9d9nqnn.js";import"./chunk-k6shq7rk.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-c0qm0wwk.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-sch01e04.js";import"./chunk-y9d9nqnn.js";import"./chunk-k6shq7rk.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-cx5s0rf3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as a,g as i,h as l,i as m}from"./chunk-4aam3qhk.js";import"./chunk-ypgjqg23.js";import"./chunk-b2p4kd07.js";import"./chunk-smjkx71w.js";import"./chunk-w2gr97qt.js";import"./chunk-d2vrbbvd.js";import"./chunk-0kmrvxsz.js";import"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{qd as n}from"./chunk-728anavt.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
package/dist/chunk-e3asq942.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ke as a,le as b,me as c}from"./chunk-832va1mp.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
package/dist/chunk-jrr361h1.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{promises as A}from"node:fs";import q from"node:path";var J=new Map;async function L(B){let b=B;while(!0){try{return await A.lstat(q.join(b,".git")),b}catch(H){if(H.code!=="ENOENT")return}let E=q.dirname(b);if(E===b)return;b=E}}async function M(B){let b=q.join(B,".git"),E=await A.lstat(b);if(E.isDirectory())return B;if(!E.isFile())return;let H=await A.readFile(b,"utf8"),F=/^gitdir:\s*(.+)\s*$/im.exec(H);if(!F)return;let z=await A.realpath(q.isAbsolute(F[1])?F[1]:q.resolve(B,F[1])),I=z;try{let x=(await A.readFile(q.join(z,"commondir"),"utf8")).trim();if(x)I=await A.realpath(q.resolve(z,x))}catch(x){if(x.code!=="ENOENT")throw x}return q.basename(I)===".git"?A.realpath(q.dirname(I)):void 0}async function S(B){if(!q.isAbsolute(B))throw Error("Workspace path must be absolute");let b=await A.realpath(B),E=J.get(b);if(E)return E;let H=b;try{let z=await L(b);if(z){let I=await M(z),x=q.relative(z,b);if(I&&(x===""||!x.startsWith(`..${q.sep}`)&&x!==".."&&!q.isAbsolute(x))){let K=q.resolve(I,x);H=await A.realpath(K).catch(()=>K)}}}catch{}let F={projectPath:b,trustRoot:H};if(J.size>=512){let z=J.keys().next().value;if(z)J.delete(z)}return J.set(b,F),F}
|
|
2
|
-
export{S as rh};
|
package/dist/chunk-nea4rcdf.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ld as a,md as b,nd as c}from"./chunk-r9n8y8m1.js";import"./chunk-s7jsadnc.js";import"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-v3kkv21n.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{oh as a,ph as b,qh as c}from"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
package/dist/chunk-wj6t3tv2.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{rh as X}from"./chunk-jrr361h1.js";import{Ah as T}from"./chunk-8wea3qty.js";import{createHash as _}from"node:crypto";import{constants as N,promises as B}from"node:fs";import A from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import j from"write-file-atomic";var O=1,S=65536,D=1048576,U=100,R=64;function r(q){return q.state==="trusted"||q.state==="not_required"}function b(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function C(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 C(`${Q.origin}${Q.pathname}`)}catch{return C(q)}}function I(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=I($.args),L=H==="stdio"?C([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function E(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.command==="string"?C($.command):void 0,G=b($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function g(q){if(!Array.isArray(q))return[];return q.slice(0,U).flatMap((Q)=>{if(!b(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=b(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function P(q){if(!b(q))return[];return Object.entries(q).slice(0,U).map(([Q,Z])=>{let $=b(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function y(q){if(!b(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of I(q[Z]).slice(0,U))Q.push({kind:"permission",name:`${Z}: ${C($,512)}`});return Q}function f(q){let Q=[...m(q.mcpServers),...E(q.lspServers),...g(q.models),...P(q.modelProviders),...y(q.permissions)];if(b(q.env))for(let Z of Object.keys(q.env).slice(0,U))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function h(q){return q!=="hooks"&&q!=="disableAllHooks"}function v(q){return _("sha256").update(q).digest("hex")}function l(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(T(),"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 X(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let V={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,V),V}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 V={...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,V),V}let H=$.filter((Y)=>l(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),z=J[0],K=z?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:z?K?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!K&&z?.path?{inheritedFrom:z.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()=>{let Z=await X(q);await this.assertSafeTrustRoot(Z);let $={version:O,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(A.homedir()).catch(()=>F.resolve(A.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>D)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(!b($)||!b($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,U);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(K){if(K.code==="ENOENT")return;throw K}if(!H.isFile())return;if(H.size>D)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(!b(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(h).sort();if(J.length===0)return;let L=f(G),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let K of J)if(!z.has(K))L.push({kind:"configuration",name:K});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,U);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,N.O_RDONLY|N.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>S)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(!b($)||$.version!==O||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:O,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${v(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 j(Q,`${JSON.stringify(q,null,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 oh,r as ph,x as qh};
|