blade-code 0.10.82 → 0.10.83
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-shq0pkxq.js → chunk-01zar8q6.js} +1 -1
- package/dist/{chunk-33bpwkyk.js → chunk-0q5bz3nm.js} +2 -2
- package/dist/{chunk-bpgyafzm.js → chunk-1htd858b.js} +2 -2
- package/dist/{chunk-zkhb55jz.js → chunk-272swnyr.js} +1 -1
- package/dist/chunk-2b7zryg3.js +118 -0
- package/dist/chunk-3p808rrt.js +1 -0
- package/dist/{chunk-mygw13zd.js → chunk-44dzrn0p.js} +1 -1
- package/dist/chunk-4pksah0q.js +1 -0
- package/dist/{chunk-3e0dry5e.js → chunk-4rq0jhf4.js} +3 -3
- package/dist/{chunk-n57jybv7.js → chunk-69rpb78b.js} +1 -1
- package/dist/{chunk-h0fh3j9w.js → chunk-6jsmac0q.js} +1 -1
- package/dist/{chunk-6at3v7hd.js → chunk-73j10ezs.js} +2 -2
- package/dist/chunk-7jp7e0zj.js +1 -0
- package/dist/{chunk-pfvgkexe.js → chunk-7m5q8vxf.js} +1 -1
- package/dist/{chunk-b9nhnzaj.js → chunk-7rfhmbqw.js} +1 -1
- package/dist/{chunk-qka2h00j.js → chunk-8215sm79.js} +12 -11
- package/dist/{chunk-sj0k8cdf.js → chunk-83caxxbt.js} +1 -1
- package/dist/{chunk-877traav.js → chunk-a14vnxrf.js} +1 -1
- package/dist/{chunk-bb1d4r3r.js → chunk-aqkexfag.js} +1 -1
- package/dist/{chunk-seamt0j3.js → chunk-b2p9qm6j.js} +2 -2
- package/dist/chunk-bd5e1n5z.js +1 -0
- package/dist/{chunk-6v2eawp6.js → chunk-cchk5xrs.js} +1 -1
- package/dist/{chunk-skw3b17a.js → chunk-d2pwwdab.js} +1 -1
- package/dist/chunk-d4k4v959.js +1 -0
- package/dist/{chunk-091qx62q.js → chunk-e1ry8aj5.js} +1 -1
- package/dist/{chunk-b9vm7gns.js → chunk-ffa6hhee.js} +2 -2
- package/dist/{chunk-8gfwva8m.js → chunk-fkwfymb6.js} +4 -4
- package/dist/{chunk-411ewxte.js → chunk-fs9j9gas.js} +2 -2
- package/dist/{chunk-jdb2mwbn.js → chunk-fv8b98tz.js} +2 -2
- package/dist/{chunk-e0ebj41c.js → chunk-g832dwdm.js} +2 -2
- package/dist/{chunk-c9e0fbyh.js → chunk-g9xjcfrf.js} +1 -1
- package/dist/{chunk-1mc7nfb4.js → chunk-gd2sw9zm.js} +1 -1
- package/dist/chunk-hg8d4vhj.js +2 -0
- package/dist/{chunk-eeb2945p.js → chunk-hjr9r44k.js} +1 -1
- package/dist/chunk-hqsqk5dp.js +1 -0
- package/dist/{chunk-fsm3fb2m.js → chunk-jf4bxxyf.js} +1 -1
- package/dist/{chunk-gre57x9m.js → chunk-jndq361v.js} +1 -1
- package/dist/chunk-js3j00ka.js +1 -0
- package/dist/{chunk-htsrecy5.js → chunk-k50z8903.js} +1 -1
- package/dist/{chunk-3kggy7we.js → chunk-m0a75642.js} +1 -1
- package/dist/{chunk-h6a0nct6.js → chunk-m5f934fh.js} +1 -1
- package/dist/chunk-mbt25rs5.js +1 -0
- package/dist/{chunk-5nfc0j4f.js → chunk-mgtcjwhy.js} +2 -2
- package/dist/{chunk-217cy9g5.js → chunk-mq2nx77s.js} +2 -2
- package/dist/{chunk-pajdvkxa.js → chunk-p9a3d507.js} +1 -1
- package/dist/{chunk-gdxm7yz5.js → chunk-q14mgye7.js} +2 -2
- package/dist/chunk-qb242y47.js +1 -0
- package/dist/{chunk-25yvyn7q.js → chunk-r4mjdkzv.js} +1 -1
- package/dist/{chunk-vpcpcwyq.js → chunk-r51ds5qw.js} +2 -2
- package/dist/{chunk-jwx10h5z.js → chunk-r77pcb0f.js} +2 -2
- package/dist/chunk-rmqksw1e.js +1 -0
- package/dist/{chunk-0a0sj79a.js → chunk-rwvaapta.js} +2 -2
- package/dist/{chunk-0141jad7.js → chunk-sb84vdcf.js} +1 -1
- package/dist/{chunk-0ra945vt.js → chunk-shr5cg46.js} +2 -2
- package/dist/{chunk-qxn5bg5k.js → chunk-sk8h4m9m.js} +1 -1
- package/dist/{chunk-h3w814js.js → chunk-skg520wq.js} +2 -2
- package/dist/{chunk-jzvbjn6e.js → chunk-sr4zv59p.js} +1 -1
- package/dist/{chunk-5nezhmnq.js → chunk-t1633e8m.js} +2 -2
- package/dist/{chunk-sghq0p21.js → chunk-t5ysd5z8.js} +1 -1
- package/dist/{chunk-cvy0pd00.js → chunk-t6phsb5h.js} +2 -2
- package/dist/{chunk-ky9q53m7.js → chunk-tpxs85cg.js} +1 -1
- package/dist/chunk-w2sb1hy9.js +1 -0
- package/dist/{chunk-7nx0pzfk.js → chunk-ww51801m.js} +1 -1
- package/dist/chunk-x2rraka3.js +1 -0
- package/dist/{chunk-n94a42wh.js → chunk-xepdd9yj.js} +1 -1
- package/dist/chunk-xj65p2sn.js +1 -0
- package/dist/chunk-xp3ad15c.js +10 -0
- package/dist/{chunk-rkp180w6.js → chunk-xy67pj74.js} +325 -320
- package/dist/{chunk-bhe154zk.js → chunk-xzgqyzmy.js} +52 -52
- package/dist/chunk-znhjr51w.js +1 -0
- package/dist/chunk-zp27f256.js +6 -0
- package/dist/web/assets/{ChatView-tu6nu0Yw.js → ChatView-DRn47Y3l.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-DFj0ZWq6.js → CodeBlockHighlighter-DxATdO6i.js} +1 -1
- package/dist/web/assets/{FilePreview-CLJNHlXO.js → FilePreview-D21mo4fn.js} +1 -1
- package/dist/web/assets/{KanbanBoard-B63UlcNr.js → KanbanBoard-DEUuLh0H.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-D7ap0LLK.js → MarkdownRenderer-BA9VgOyM.js} +3 -3
- package/dist/web/assets/{SettingsModal-B8Gp0bXw.js → SettingsModal-CXq3qDgQ.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-gxALR-zu.js → TaskSwitcher-CUcZEUQH.js} +1 -1
- package/dist/web/assets/{TerminalPanel-dnC4oh4w.js → TerminalPanel-CcC6f3H_.js} +1 -1
- package/dist/web/assets/{index-Dn4vZglG.js → index-CfVQVVVI.js} +3 -3
- package/dist/web/assets/{teamService-CoJLtqAq.js → teamService-BX1zdQBb.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-0wk1byp5.js +0 -1
- package/dist/chunk-3n08j1xh.js +0 -1
- package/dist/chunk-4mpwdcfd.js +0 -10
- package/dist/chunk-6adxyred.js +0 -1
- package/dist/chunk-7t41dza5.js +0 -1
- package/dist/chunk-c3vqqs0r.js +0 -1
- package/dist/chunk-gn6ftvjy.js +0 -1
- package/dist/chunk-gw1za0rb.js +0 -1
- package/dist/chunk-h9xayrwp.js +0 -1
- package/dist/chunk-jdzgkdse.js +0 -1
- package/dist/chunk-kpfbbh24.js +0 -1
- package/dist/chunk-m0dt3w7w.js +0 -112
- package/dist/chunk-ndnjmy45.js +0 -1
- package/dist/chunk-qky3qehm.js +0 -6
- package/dist/chunk-qvtstj28.js +0 -1
- package/dist/chunk-reakyamv.js +0 -2
- package/dist/chunk-rpbyc2k4.js +0 -1
- package/dist/chunk-xqnfzt9g.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as e,T as t,U as r,x as s,V as m}from"./index-
|
|
1
|
+
import{R as e,T as t,U as r,x as s,V as m}from"./index-CfVQVVVI.js";import"./vendor-react-DG5dkZ_t.js";import"./vendor-radix-DXRuAJHH.js";import"./vendor-icons-DovdPN7M.js";import"./session-events-Bgir_Gl_.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:r(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:r(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:r(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:r(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(r(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),b={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,a,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:a,message:g})})},delete:async(n,i)=>{const a=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${a.toString()}`,{method:"DELETE"}))}};export{b as teamService};
|
package/dist/web/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>BladeCode</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-CfVQVVVI.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-DG5dkZ_t.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/vendor-radix-DXRuAJHH.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/vendor-icons-DovdPN7M.js">
|
package/package.json
CHANGED
package/dist/chunk-0wk1byp5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g}from"./chunk-m0dt3w7w.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-mygw13zd.js";import"./chunk-7nx0pzfk.js";import"./chunk-zkhb55jz.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-b9vm7gns.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
package/dist/chunk-3n08j1xh.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Bh as a,Ch as b,Dh as c,Eh as d,Fh as e,Gh as f}from"./chunk-411ewxte.js";import"./chunk-h0fh3j9w.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
package/dist/chunk-4mpwdcfd.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{f as T,g as W,h as X,i as Y}from"./chunk-8gfwva8m.js";import"./chunk-1mc7nfb4.js";import"./chunk-shq0pkxq.js";import"./chunk-sghq0p21.js";import"./chunk-bb1d4r3r.js";import"./chunk-n57jybv7.js";import"./chunk-rkp180w6.js";import"./chunk-pajdvkxa.js";import"./chunk-ky9q53m7.js";import"./chunk-bhe154zk.js";import"./chunk-r8wbvxn7.js";import"./chunk-m0dt3w7w.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{yd as R}from"./chunk-vpcpcwyq.js";import"./chunk-h3w814js.js";import{Ud as Q}from"./chunk-gdxm7yz5.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-6at3v7hd.js";import"./chunk-e0ebj41c.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-3e0dry5e.js";import"./chunk-zkhb55jz.js";import"./chunk-cvy0pd00.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import{Ch as M}from"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-6adxyred.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Hh as a,Ih as b,Jh as c}from"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
package/dist/chunk-7t41dza5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$d as n,Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g,Vd as h,Wd as i,Xd as j,Yd as k,Zd as l,_d as m,ae as o,be as p,ce as q}from"./chunk-gdxm7yz5.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-cvy0pd00.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.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};
|
package/dist/chunk-c3vqqs0r.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-877traav.js";import"./chunk-411ewxte.js";import"./chunk-h0fh3j9w.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-gn6ftvjy.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{pe as a}from"./chunk-seamt0j3.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as createChatServiceAsync};
|
package/dist/chunk-gw1za0rb.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{td as a,ud as b,vd as c}from"./chunk-5nfc0j4f.js";import"./chunk-jdb2mwbn.js";import"./chunk-gdxm7yz5.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-b9nhnzaj.js";import"./chunk-cvy0pd00.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-h9xayrwp.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jd as a,kd as b,ld as c,md as d,nd as e,od as f,pd as g,qd as h}from"./chunk-jwx10h5z.js";import"./chunk-b9vm7gns.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
|
package/dist/chunk-jdzgkdse.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-bhe154zk.js";import"./chunk-r8wbvxn7.js";import"./chunk-m0dt3w7w.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-mygw13zd.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-3e0dry5e.js";import"./chunk-zkhb55jz.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
package/dist/chunk-kpfbbh24.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{rd as a,sd as b}from"./chunk-217cy9g5.js";import"./chunk-411ewxte.js";import"./chunk-h0fh3j9w.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-m0dt3w7w.js
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import{$c as I1,_c as u,ad as K$,bd as v1,cd as I,dd as T$,ed as u1,fd as x$,gd as P1,hd as N$,id as F$,kd as g0,nd as R$,od as h1}from"./chunk-jwx10h5z.js";import{te as O0}from"./chunk-mygw13zd.js";import{jf as W0}from"./chunk-7nx0pzfk.js";import{vf as V1}from"./chunk-zkhb55jz.js";import{Ig as j1,Jg as m1}from"./chunk-reakyamv.js";import{Og as v$}from"./chunk-0141jad7.js";import{oh as D0}from"./chunk-b9vm7gns.js";import{vh as Y0,yh as _0}from"./chunk-h6a0nct6.js";import{Ch as i}from"./chunk-411ewxte.js";import{Mh as k1,Nh as C0,Oh as S1,Ph as b,Qh as m,Sh as V0,Th as p,Uh as G0}from"./chunk-0ra945vt.js";import{readdir as O$,readFile as s,rm as q0,stat as y0}from"node:fs/promises";import*as O from"node:path";import{nanoid as j}from"nanoid";import{createHash as e1,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as N0 from"node:path";import{execFileSync as d1}from"node:child_process";import{createHash as r1}from"node:crypto";import{readFileSync as o1}from"node:fs";var t1=/^[a-f0-9]{64}$/;function k$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&t1.test(q.fingerprint)}var S$={readFile:($)=>o1($,"utf8"),execFile:($,q)=>d1($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},a1=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function l0($,q){return{platform:$,fingerprint:r1("sha256").update(`${$}\x00${q}`).digest("hex")}}function s1($,q){let f=q.readFile(`/proc/${$}/stat`).trim(),L=f.lastIndexOf(")");if(L<0)throw Error("Invalid /proc process stat");let C=f.slice(L+2).split(/\s+/)[19];if(!C||!/^\d+$/.test(C))throw Error("Missing process start ticks");return C}function T0($,q=process.platform,f=S$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return l0(q,s1($,f));if(q==="darwin"){let L=f.execFile("ps",["-o","lstart=","-p",String($)]).trim();return L?l0(q,L):void 0}if(q==="win32"){let L=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=f.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",L]).trim();return B?l0(q,B):void 0}}catch{return}return}function j$($,q){return T0($,q.platform)?.fingerprint===q.fingerprint}function wf($,q,f=S$,L=a1){if(!Number.isInteger($)||$<=1)return!1;let B=T0($,q.platform,f);if(B)return B.fingerprint===q.fingerprint;return!L($)}var u$=1;function qq($,q){let f=e1("sha256").update(q).digest("hex");return N0.join(C0($),".locks",`${f}.lock`)}function x0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function p0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==u$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!k$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function m$($){let q=await p0($);if(q)return q;return await new Promise((f)=>setTimeout(f,10)),p0($)}function fq($){try{return process.kill($,0),!0}catch(q){return x0(q,"EPERM")}}async function I$($,q){let f;try{return f=await v.open($,"wx",384),await f.writeFile(`${JSON.stringify(q)}
|
|
2
|
-
`,"utf8"),!0}catch(L){if(x0(L,"EEXIST"))return!1;if(f)await v.unlink($).catch(()=>{return});throw L}finally{await f?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class c{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=v$()){let f=qq(q,$),L={version:u$,sessionId:$,ownerId:$q(),pid:process.pid,processIdentity:T0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(N0.dirname(f),{recursive:!0,mode:448}),await I$(f,L))return new c(f,L);let B=await m$(f);if(B&&fq(B.pid)&&(!B.processIdentity||j$(B.pid,B.processIdentity)))throw new n(B.pid);if(await v.unlink(f).catch((C)=>{if(!x0(C,"ENOENT"))throw C}),await I$(f,L))return new c(f,L);throw new n((await m$(f))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await p0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((q)=>{if(!x0(q,"ENOENT"))throw q})}}var mf=1;function i0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Lq($){if(!i0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&i0($.image_url)&&typeof $.image_url.url==="string"}function Cq($){if(!i0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(Lq)}function P$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let f=JSON.parse(q);if(!Array.isArray(f)||!f.every(Cq))return;return f}function If($){let q=P$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function F0($){return P$($)}function Bq($,q){for(let f of $){if(f.type!=="part_created"||f.data.partType!=="tool_result")continue;let L=f.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let B=L;if(B.toolCallId===q||f.data.partId===q||f.data.messageId===q)return B}return}function h$($){let q=u($),f=new Map;for(let L of q){if(L.type==="interaction_requested"){f.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let B=f.get(L.data.requestId);if(B)B.response=L.data;continue}if(L.type==="interaction_recovered"){let B=f.get(L.data.requestId);if(B)B.recovery=L.data}}for(let L of f.values()){let B=Bq(q,L.request.toolCallId);L.hasToolResult=B!==void 0;let C=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;L.hasRecoveryToolResult=C?.interactionRecovery===!0&&C.requestId===L.request.requestId}return[...f.values()]}function n$($){return h$($).reverse().find((q)=>!q.response&&!q.recovery)}function Pf($){let q=new Map;for(let f of h$($))q.set(f.request.toolCallId,f);return[...q.values()].filter((f)=>f.response&&!f.recovery&&(!f.hasToolResult||f.hasRecoveryToolResult))}function c$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function R0($){let q=new Map,f=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))f.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let B=q.get(L.data.reviewId);if(B&&B.completion===void 0)B.completion=L.data}return f.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function nf($){return R0($).reverse().find((q)=>q.completion===void 0)}function d0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function l$($,q){let f=["## Code Review","",`Target: ${$.target.label}`,`Status: ${d0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)f.push("","No actionable findings.");else{f.push("","### Findings");for(let[L,B]of q.findings.entries()){let C=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;f.push("",`${L+1}. ${B.title}`,` ${B.codeLocation.path}:L${C} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(q.error)f.push("",`Error: ${q.error}`);return f.join(`
|
|
3
|
-
`)}function p$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((f)=>({title:f.title,body:f.body,priority:f.priority,confidenceScore:f.confidenceScore,codeLocation:{...f.codeLocation}})),...q.error?{error:q.error}:{}}}var a0=1;var r0=2000,Jq='<token-budget-handoff version="1">',pf="handoff-message-",Zq=128,Gq=["version","messageId","observedPromptTokens","availableForInput","handoffThreshold","compactionThreshold","createdAt"],Qq=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Vq=/(?:^|\n)Remaining prompt-token headroom before compaction: (\d+)\.$/;function P($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function s0($){return P($)&&$>0}function Xq($){for(let q=0;q<$.length;q+=1){let f=$.charCodeAt(q);if(f<=31||f===127)return!0}return!1}function i$($){return typeof $==="string"&&$.length>=1&&$.length<=Zq&&!Xq($)}function o0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let q=Object.getPrototypeOf($);return q===Object.prototype||q===null}function U0($,q){let f=Math.floor($/10),L=$%10;return f*q+Math.floor(L*q/10)}function Yq($){if(typeof $!=="string"||!Qq.test($))return!1;try{let q=new Date($);return Number.isFinite(q.getTime())&&q.toISOString()===$}catch{return!1}}function d$($){if(!P($))throw Error("Token budget handoff headroom must be a safe nonnegative integer");return[Jq,"Context rollover is approaching. Continue the user task from this state only.","Make objective, decisions, mutations, verification, background work, blockers, and the exact next action explicit.","For pending work, preserve exact commands, tool arguments, and required final-response constraints when they are known.","Do not claim success or completion unless it is already proven in the transcript.","Do not create bookkeeping files the user did not request.",`Remaining prompt-token headroom before compaction: ${$}.`].join(`
|
|
4
|
-
`)}function _q($){let q=d$($);if(new TextEncoder().encode(q).length>r0)throw Error(`Token budget handoff reminder exceeds ${r0} bytes`);return q}function t0($,q){let f=Object.keys($).sort(),L=[...q].sort();return f.length===L.length&&f.every((B,C)=>B===L[C])}function df($){let{maxContextTokens:q,maxOutputTokens:f,configuredMaxOutputTokens:L}=$,B=f??L??void 0;if(B!==void 0)return B;if(!s0(q))return;return Math.min(Math.max(Math.floor(q*0.1),8192),32768)}function rf($){let{contextTokens:q,tokenSource:f,estimatedPendingTokens:L,maxContextTokens:B,maxOutputTokens:C}=$;if(!s0(B)||!P(C)||C>=B)return{phase:"unknown"};let J=B-C;if(J<=0)return{phase:"unknown"};let Z=U0(J,7),Q=U0(J,8);if(!P(q))return{phase:"unknown",...f?{tokenSource:f}:{},...P(L)?{estimatedPendingTokens:L}:{},maxContextTokens:B,maxOutputTokens:C,availableForInput:J,handoffThreshold:Z,compactionThreshold:Q};let X={contextTokens:q,...f?{tokenSource:f}:{},...P(L)?{estimatedPendingTokens:L}:{},maxContextTokens:B,maxOutputTokens:C,availableForInput:J,handoffThreshold:Z,compactionThreshold:Q};if(q<Z)return{phase:"below_handoff",...X};if(q<Q)return{phase:"handoff_band",...X};return{phase:"compaction_due",...X}}function r$($){if($.type!=="token_budget_handoff_recorded"||!o0($.data))return;let q=$.data;if(!t0(q,Gq)||q.version!==a0||!i$(q.messageId)||!P(q.observedPromptTokens)||!s0(q.availableForInput)||!P(q.handoffThreshold)||!P(q.compactionThreshold)||!Yq(q.createdAt))return;let f=U0(q.availableForInput,7),L=U0(q.availableForInput,8);if(q.handoffThreshold!==f||q.compactionThreshold!==L||q.observedPromptTokens<q.handoffThreshold||q.observedPromptTokens>=q.compactionThreshold)return;return $}function Oq($){return $.type==="token_budget_handoff_recorded"}function o$($){let q=$.findLastIndex((C)=>{if(C.type!=="part_created"||C.data.partType!=="summary")return!1;let J=C.data.payload;return J!==null&&typeof J==="object"&&!Array.isArray(J)&&F0(J.replacementMessages)!==void 0}),f=$.slice(q+1).filter(Oq);if(f.length===0)return{kind:"none"};let L=f.at(-1);if(!L)return{kind:"none"};if(f.length!==1)return{kind:"suppressed",recordId:L.id};let B=r$(L);return B?{kind:"valid",event:B}:{kind:"suppressed",recordId:L.id}}function t$($){let q=r$($);if(!q)return;let f={clientVisible:!1,tokenBudgetHandoff:{version:a0,messageId:q.data.messageId}};return{id:q.data.messageId,role:"user",content:_q(Math.max(0,q.data.compactionThreshold-q.data.observedPromptTokens)),metadata:f}}function Wq($){if(typeof $.id!=="string"||$.role!=="user"||typeof $.content!=="string"||!o0($.metadata)||$.metadata.clientVisible!==!1)return!1;let q=$.metadata;if(!t0(q,["clientVisible","tokenBudgetHandoff"]))return!1;let f=q.tokenBudgetHandoff;if(!o0(f))return!1;if(!t0(f,["messageId","version"]))return!1;if(f.version!==a0||!i$(f.messageId)||f.messageId!==$.id)return!1;if(new TextEncoder().encode($.content).length>r0)return!1;let B=Vq.exec($.content);if(!B)return!1;let C=Number(B[1]);return P(C)&&$.content===d$(C)}function of($){return $.filter((q)=>!Wq(q))}var e0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},capacity:{message:"Task admission capacity is full. Retry after running tasks complete.",retryable:!0},runtime:{message:"Agent execution failed.",retryable:!0}};function Hq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Kq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";if(/\btask admission\b.*\b(capacity|queue)\b/.test(q))return"capacity";return"runtime"}function Tq($){try{if(!$||typeof $!=="object"||!("name"in $)||$.name!=="TaskAdmissionQueueFullError"&&$.name!=="SessionRuntimeCapacityError"||!("resource"in $))return;return $.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes"?$.resource:void 0}catch{return}}function a$($){return{code:$,...e0[$]}}function $$($){let q=Tq($);if(q)return{...a$("capacity"),resource:q};return a$(Kq(Hq($)))}function q$($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in e0))return!1;let f=e0[q.code],L=q.resource===void 0||q.resource==="pending_count"||q.resource==="pending_bytes"||q.resource==="resident_runtimes";return q.message===f.message&&q.retryable===f.retryable&&L&&(q.code==="capacity"||q.resource===void 0)}import{promises as B0,realpathSync as Nq}from"node:fs";import z0 from"node:path";import*as o from"fs/promises";import*as R from"path";var s$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class r extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class f${static normalize($,q){let f=R.isAbsolute($)?$:R.resolve(q,$),L=R.normalize(f),B=R.normalize(q);if(!this.isWithinWorkspace(L,B))throw new r(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(R.sep);for(let f of s$)if(q.includes(f))throw new r(`Access denied: "${f}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new r(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let f=this.normalize($,q);this.checkRestricted(f);try{await o.access(f)}catch(L){throw new r(`Path not found: ${$}`,"PATH_NOT_FOUND")}return f}static async resolveSymlink($,q){try{let f=await o.realpath($),L=await o.realpath(q);if(!this.isWithinWorkspace(f,L))throw new r(`Symlink points outside workspace: ${$} -> ${f}`,"SYMLINK_OUTSIDE_WORKSPACE");return f}catch(f){if(f instanceof r)throw f;return $}}static getRelativePath($,q){return R.relative(q,$)}static isWithinWorkspace($,q){let f=R.resolve($),L=R.resolve(q),B=R.relative(L,f);return B===""||B!==".."&&!B.startsWith(`..${R.sep}`)&&!R.isAbsolute(B)}static async isWithinWorkspaceResolved($,q){let f=R.resolve(q),L=R.isAbsolute($)?R.resolve($):R.resolve(f,$);if(!this.isWithinWorkspace(L,f))return!1;let B;try{B=await o.realpath(f)}catch{return!1}let C=L;while(!0){try{let Z=await o.realpath(C);return this.isWithinWorkspace(Z,B)}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")return!1}let J=R.dirname(C);if(J===C)return!1;C=J}}static isRestricted($){let q=$.split(R.sep);return s$.some((f)=>q.includes(f))}}var J0=D0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,q){try{let f=await B0.stat($),L={filePath:z0.resolve($),accessTime:Date.now(),mtime:f.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),J0.debug(`记录文件读取: ${$}`)}catch(f){J0.warn(`记录文件读取失败: ${$}`,f)}}async recordFileEdit($,q,f="edit"){try{let L=await B0.stat($),B={filePath:z0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:f};this.setRecord(B),await this.recordAliases($,B.filePath),J0.debug(`记录文件${f==="edit"?"编辑":"写入"}: ${$}`)}catch(L){J0.warn(`记录文件${f==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let f=this.accessedFiles.get(this.resolveTrackedPath($));if(!f)return!1;return q?f.has(q):f.size>0}async checkFileModification($,q){let f=this.getFileRecord($,q);if(!f)return{modified:!1,message:"文件未被跟踪"};try{let L=await B0.stat($);if(Math.abs(L.mtimeMs-f.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(f.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let B=L;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,q){let f=this.getFileRecord($,q);if(!f)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await B0.stat($);if(L.mtimeMs-f.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(f.accessTime).toISOString()} (${f.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let B=L;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return J0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,q){let f=this.accessedFiles.get(this.resolveTrackedPath($));if(!f)return;if(q)return f.get(q);return[...f.values()].sort((L,B)=>B.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let f=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(f),this.removeAliases(f);return}let L=this.accessedFiles.get(f);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(f),this.removeAliases(f)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[f,L]of this.accessedFiles.entries()){if(q&&!f$.isWithinWorkspace(f,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(f),this.removeAliases(f)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(z0.resolve($),q);let f=await B0.realpath($).catch(()=>{return});if(f)this.pathAliases.set(f,q)}resolveTrackedPath($){let q=z0.resolve($);if(this.accessedFiles.has(q))return q;let f=this.pathAliases.get(q);if(f)return f;try{let L=Nq.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,f]of this.pathAliases)if(f===$)this.pathAliases.delete(q)}}import*as Z0 from"node:crypto";import{promises as H}from"node:fs";import*as T from"node:path";import L$ from"write-file-atomic";var e$="missing";class A0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(b($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!T.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?T.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=G0();this.snapshotDir=T.join(q,"file-history",this.sessionId),this.manifestPath=T.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await H.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=G0(),q=await H.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),f=Z0.createHash("sha256").update(q).digest("hex").slice(0,24),L=T.join($,"file-history",this.sessionId),B=T.join($,"file-history","workspaces",f,this.sessionId),C=T.join(B,"manifest.json");try{await H.access(C)}catch{await this.migrateLegacySnapshotDir(L,B,q)}this.snapshotDir=B,this.manifestPath=C}async migrateLegacySnapshotDir($,q,f){let L;try{L=JSON.parse(await H.readFile(T.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,f)))return;await H.mkdir(T.dirname(q),{recursive:!0,mode:493});try{await H.rename($,q)}catch(B){let C=B.code;if(C!=="ENOENT"&&C!=="EEXIST"&&C!=="ENOTEMPTY")throw B}}isWithinWorkspace($,q){if(!T.isAbsolute($))return!1;let f=T.relative(q,T.resolve($));return f===""||f!==".."&&!f.startsWith(`..${T.sep}`)&&!T.isAbsolute(f)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let f=await this.resolveFileIdentity($),L=!0;try{await H.access(f)}catch{L=!1}let B=this.trackedFileBackups.get(f),C=B?B.version+1:1,J=this.generateFileHash(f,C),Z=this.getSnapshotPath(J,C),Q=new Date;if(L){let Y=await H.readFile(f);await H.writeFile(Z,Y)}let X={backupFileName:J,version:C,backupTime:Q};return this.trackedFileBackups.set(f,X),this.snapshots.push({messageId:q,backupFileName:J,timestamp:Q,filePath:f,version:C,existedBefore:L}),await this.cleanupOldSnapshots(f),await this.persistManifest(),X}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let f=await this.resolveFileIdentity($),L=this.snapshots.find((B)=>B.filePath===f&&B.backupFileName===q.backupFileName&&B.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${f}`);L.postEditHash=await this.hashFile(f),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let f=await this.resolveFileIdentity($),L=this.snapshots.find((B)=>B.filePath===f&&B.backupFileName===q.backupFileName&&B.version===q.version);if(!L)return;this.removeSnapshot(L),await H.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),f=this.snapshots.slice().reverse().find((C)=>C.filePath===q&&C.postEditHash!==void 0);if(!f?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==f.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let B=this.getSnapshotPath(f.backupFileName,f.version);if(f.existedBefore){let C=await H.readFile(B);await H.mkdir(T.dirname(q),{recursive:!0}),await H.writeFile(q,C)}else await H.rm(q,{force:!0});return this.removeSnapshot(f),await H.rm(B,{force:!0}),await this.persistManifest(),f}async restoreSnapshot($,q){let f=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((C)=>C.messageId===q&&C.filePath===f);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${f}`);let B=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let C=await H.readFile(B);await H.mkdir(T.dirname(f),{recursive:!0}),await H.writeFile(f,C)}else await H.rm(f,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((f)=>f.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((f)=>f.filePath),snapshotCount:q.reduce((f,L)=>f+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let f=new Map;for(let B of q){let C,J=!0;try{C=await H.readFile(B.filePath)}catch(Q){if(Q.code!=="ENOENT")throw Q;J=!1}if((C?Z0.createHash("sha256").update(C).digest("hex"):e$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(f.set(B.filePath,{existed:J,content:C}),B.target.existedBefore)await H.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let L=[...this.snapshots];try{for(let C of q)if(C.target.existedBefore){let J=await H.readFile(this.getSnapshotPath(C.target.backupFileName,C.target.version));await H.mkdir(T.dirname(C.filePath),{recursive:!0}),await L$(C.filePath,J)}else await H.rm(C.filePath,{force:!0});let B=new Set(q.flatMap((C)=>C.selected));this.snapshots=this.snapshots.filter((C)=>!B.has(C)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((C)=>H.rm(this.getSnapshotPath(C.backupFileName,C.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=L,this.rebuildTrackedFileBackups();let C=[];for(let[J,Z]of f)try{if(Z.existed&&Z.content)await L$(J,Z.content);else await H.rm(J,{force:!0})}catch(Q){C.push(Q)}if(C.length>0)throw AggregateError([B,...C],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:q.map((B)=>B.filePath),snapshotCount:q.reduce((B,C)=>B+C.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),f=new Set(q.flatMap((B)=>B.selected));if(f.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!f.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=L,this.rebuildTrackedFileBackups(),B}return await Promise.all([...f].map((B)=>H.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:q.map((B)=>B.filePath),snapshotCount:f.size}}buildRewindPlan($){let q=new Set($),f=this.snapshots.filter((C)=>C.postEditHash!==void 0),L=f.filter((C)=>q.has(C.messageId));return[...new Set(L.map((C)=>C.filePath))].sort().map((C)=>{let J=f.filter((Y)=>Y.filePath===C),Z=J.filter((Y)=>q.has(Y.messageId)),Q=J.indexOf(Z[0]),X=J.slice(Q);if(X.length!==Z.length||X.some((Y)=>!q.has(Y.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${C}`);return{filePath:C,selected:Z,target:Z[0],latest:Z.at(-1)}})}async loadManifest(){try{let $=await H.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(f)=>({...f,filePath:await this.resolveFileIdentity(f.filePath),timestamp:new Date(f.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await H.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await L$(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let f=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of f)await H.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,B)=>B.timestamp.getTime()-L.timestamp.getTime()),f=new Set(q.slice(0,$));for(let L of this.snapshots)if(!f.has(L))await H.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return T.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=T.resolve($),f=[],L=q;while(!0){try{let C=await H.realpath(L);return T.join(C,...f.reverse())}catch(C){let J=C.code;if(J!=="ENOENT"&&J!=="ENOTDIR")throw C}let B=T.dirname(L);if(B===L)return q;f.push(T.basename(L)),L=B}}async hashFile($){try{let q=await H.readFile($);return Z0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return e$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let f=Z0.createHash("md5");return f.update(`${$}:${q}`),f.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var VL=1200,XL=2000,YL=2000,_L=2000;function q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Fq($){if(typeof $==="string"&&$.length>0)return $;if(q1($)&&typeof $.message==="string")return $.message;return}function Rq($,q){if($===null||$===void 0)return q??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function f1($){let q=$.error!==null&&$.error!==void 0,f=q?Fq($.error)??"Tool execution failed":void 0,L=q1($.metadata)?$.metadata:void 0;return{success:!q,llmContent:Rq($.output,f),...f?{error:{type:"execution_error",message:f}}:{},...L?{metadata:L}:{}}}function B$($,q){if($.length<=q)return $;let f=Math.max(0,q);if(f>0&&f<$.length&&/[\uD800-\uDBFF]/.test($.charAt(f-1)))f-=1;return $.slice(0,f)}function $1($,q){if($.length<=q)return $;let f=Math.max(0,$.length-q);if(f<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(f)))f+=1;return $.slice(f)}function C$($,q){if($.length<=q)return $;if(q<=0)return"";let f=`
|
|
5
|
-
... (display clipped) ...
|
|
6
|
-
`,L=$.indexOf(`
|
|
7
|
-
`),B=L>=0&&/^(?:stdout|stderr):$/.test($.slice(0,L))?`${$.slice(0,L)}
|
|
8
|
-
`:"",C=B?$.slice(B.length):$,J=q-B.length-f.length;if(J<=0)return $1($,q);let Z=Math.min(Math.floor(J/3),C.length),Q=Math.max(0,J-Z);return B+B$(C,Z)+f+$1(C,Q)}function Uq($){let q=$.split(`
|
|
9
|
-
`),f=q.at(-1);if(!f?.startsWith("Output truncated"))return{body:$};return{body:q.slice(0,-1).join(`
|
|
10
|
-
`),suffix:f}}function zq($){let f=$.indexOf(`
|
|
11
|
-
stderr:
|
|
12
|
-
`);if(!$.startsWith(`stdout:
|
|
13
|
-
`)||f<0)return[$];return[$.slice(0,f),$.slice(f+1)]}function OL($,q){if(!Number.isSafeInteger(q)||q<=0)throw Error("maxChars must be a positive safe integer");if(!$.detail||$.detail.length<=q)return $;let{body:f,suffix:L}=Uq($.detail),B=L?`
|
|
14
|
-
${B$(L,q)}`:"",C=Math.max(0,q-B.length),J=zq(f),Z;if(J.length===2){let Y=Math.max(0,C-1),G=Math.floor(Y/2),V=Y-G;Z=`${C$(J[0],G)}
|
|
15
|
-
${C$(J[1],V)}`}else Z=C$(f,C);let Q=B$(`${Z}${B}`,q);return{...$,detail:Q}}var HL={clientVisible:!1};function L1($){if($.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)&&$.metadata.clientVisible===!1)return!1;return!($.role==="user"&&typeof $.content==="string"&&$.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&$.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{createHash as mq}from"node:crypto";import _1 from"node:path";import{StringDecoder as Mq}from"node:string_decoder";var TL=1048576;function J$($,q){let f=q;while(f<$.length&&($[f]&192)===128)f+=1;return f}class Z${maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,q.length>this.maxBytes){this.retainOversizedChunkTail(q);return}this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail($){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let q=J$($,$.length-this.maxBytes);if(this.omittedBytes+=q,q===$.length)return;let f=Buffer.from($.subarray(q));this.chunks.push(f),this.retainedBytes=f.length}trimToLimit(){let $=!1;while(this.retainedBytes>this.maxBytes){let q=this.chunks[0];if(!q)return;let f=this.retainedBytes-this.maxBytes;if(q.length<=f){this.chunks.shift(),this.retainedBytes-=q.length,this.omittedBytes+=q.length,$=!0;continue}let L=J$(q,f);this.chunks[0]=q.subarray(L),this.retainedBytes-=L,this.omittedBytes+=L,$=!0}if($)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let $=this.chunks[0];if($.length===0){this.chunks.shift();continue}let q=J$($,0);if(q===0)return;if(this.retainedBytes-=q,this.omittedBytes+=q,q===$.length)this.chunks.shift();else{this.chunks[0]=$.subarray(q);return}}}compactChunks(){if(this.chunks.length<=32)return;let $=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,$.length>0)this.chunks.push($)}}var M0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},t={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},C1={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Dq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Aq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:M0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:M0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:t,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:C1},{pattern:/^git\s+(status|branch|remote)/i,config:t},{pattern:/^git\s+(log|diff|show)/i,config:C1},{pattern:/^(ls|dir|tree)\s+/i,config:t,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:t,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:t,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:M0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:M0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:t,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:t,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];function B1($,q,f){let L=q,B=f??$.length;if(L>0){let C=$.charCodeAt(L);if(C>=56320&&C<=57343)L+=1}if(B<$.length){let C=$.charCodeAt(B-1);if(C>=55296&&C<=56319)B-=1}return $.slice(L,B)}class G${static getConfigForCommand($){for(let{pattern:q,config:f,summaryTemplate:L}of Aq)if(q.test($))return{config:f,summaryTemplate:L};return{config:Dq}}static truncate($,q){let{config:f,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,f,L)}static truncateWithConfig($,q,f){let L=$.length,B=$.split(`
|
|
16
|
-
`),C=B.length;if(C<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:C,originalChars:L};let J=B.slice(0,q.keepHead),Z=B.slice(-q.keepTail),Q=C-q.keepHead-q.keepTail,X=J.join(`
|
|
17
|
-
`);if(X+=`
|
|
18
|
-
|
|
19
|
-
... (${Q} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${C} total) ...
|
|
20
|
-
|
|
21
|
-
`,X+=Z.join(`
|
|
22
|
-
`),X.length>q.maxChars){let G=Math.floor(q.maxChars/2)-50,V=B1(X,0,G),_=B1(X,X.length-G);X=`${V}
|
|
23
|
-
|
|
24
|
-
... (content truncated to ${q.maxChars} chars) ...
|
|
25
|
-
|
|
26
|
-
${_}`}let Y=q.summarize&&f?f(C,L):void 0;if(Y)X+=`
|
|
27
|
-
|
|
28
|
-
[Summary: ${Y}]`;return{content:X,truncated:!0,originalLines:C,originalChars:L,summary:Y}}static truncateForLLM($,q,f){let L=this.truncate($,f),B=this.truncate(q,f),C;if(L.truncated||B.truncated){let J=[];if(L.truncated)J.push(`stdout: ${L.originalLines} lines -> ${L.content.split(`
|
|
29
|
-
`).length} lines`);if(B.truncated)J.push(`stderr: ${B.originalLines} lines -> ${B.content.split(`
|
|
30
|
-
`).length} lines`);C=`Output truncated: ${J.join(", ")}`}return{stdout:L.content,stderr:B.content,truncationInfo:C}}static shouldTruncate($,q){let{config:f}=this.getConfigForCommand(q);return $.split(`
|
|
31
|
-
`).length>f.maxLines||$.length>f.maxChars}static getStats($){return{lines:$.split(`
|
|
32
|
-
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var J1=32768,bq=1048576,wq=65536,Eq=3600000,Z1=4096,gq=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class Q${stream;executionId;onEvent;output=new Z$(bq/2);decoder=new Mq("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,f){this.stream=$;this.executionId=q;this.onEvent=f}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<Z1){let L=q.subarray(0,Math.min(q.length,Z1-this.sniffBytes));this.sniffChunks.push(L),this.sniffBytes+=L.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let f=G1(this.decoder.write(q));this.output.append(f),this.emit(f)}finish(){if(this.binary)return;let $=G1(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=wq-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let f=yq($,q);if(this.streamedBytes+=Buffer.byteLength(f),f.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:f,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function G1($){return $.replace(gq,"")}function yq($,q){let f=Buffer.from($);if(f.length<=q)return $;let L=q;while(L>0&&(f[L]&192)===128)L-=1;return f.subarray(0,L).toString("utf8")}function Q1($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function kq($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>J1)throw Error(`User shell command exceeds ${J1} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function Sq(){return{execute($,q){return new Promise((f)=>{let L=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",B=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:C,processTree:J}=V1(L,B,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Z="",Q="",X=!1,Y=!1,G=!1,V,_=()=>{return V??=J.terminate(),V},W=setTimeout(()=>{X=!0,_()},q.timeoutMs),N=()=>{Y=!0,_()};if(q.signal.addEventListener("abort",N,{once:!0}),q.signal.aborted)N();C.stdout?.on("data",(U)=>{q.onOutput?.("stdout",U)}),C.stderr?.on("data",(U)=>{q.onOutput?.("stderr",U)});let E=async(U)=>{if(G)return;if(G=!0,clearTimeout(W),q.signal.removeEventListener("abort",N),X||Y)await _();f({...U,stdout:"",stderr:"",timedOut:X,aborted:Y})};C.once("error",(U)=>{E({exitCode:null,error:U.message})}),C.once("close",(U)=>{E({exitCode:U})})})}}}async function DL($,q){let f=kq($),L=q.timeoutMs??Eq,B=new Q$("stdout",q.executionId,q.onEvent),C=new Q$("stderr",q.executionId,q.onEvent),J=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:f});let Z,Q=!1,X=!1;try{Z=await(q.executor??Sq()).execute(f,{cwd:q.cwd,env:q.env,timeoutMs:L,signal:q.signal,onOutput:(N,E)=>{if(N==="stdout")Q=!0;else X=!0;(N==="stdout"?B:C).append(E)}})}catch(N){Z={exitCode:null,stdout:"",stderr:"",error:N instanceof Error?N.message:String(N)}}if(!Q)B.append(Z.stdout);if(!X)C.append(Z.stderr);B.finish(),C.finish(),await Promise.all([B.flushEvents(),C.flushEvents()]);let Y=B.snapshot(),G=C.snapshot(),V=G$.truncateForLLM(Y.content.trim(),G.content.trim(),f),_=Z.aborted||q.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",W={version:1,command:f,status:_,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-J),stdout:V.stdout,stderr:Z.error?[V.stderr,Z.error].filter(Boolean).join(`
|
|
33
|
-
`):V.stderr,stdoutOmittedBytes:Y.omittedBytes,stderrOmittedBytes:G.omittedBytes,binaryOutput:Y.binary||G.binary,truncated:Boolean(V.truncationInfo)||Y.omittedBytes>0||G.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:W}),W}function AL($){let q=[$.stdout?`stdout:
|
|
34
|
-
${$.stdout}`:"",$.stderr?`stderr:
|
|
35
|
-
${$.stderr}`:""].filter(Boolean).join(`
|
|
36
|
-
`);return["<user_shell_command>",`<command>${Q1($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
37
|
-
${Q1(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
38
|
-
`)}function X1($){let q=[$.stdout,$.stderr?`stderr:
|
|
39
|
-
${$.stderr}`:""].filter(Boolean).join(`
|
|
40
|
-
`);return[`! ${$.command}`,q||"(no output)"].join(`
|
|
41
|
-
`)}function jq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function b0($){if(!$||typeof $!=="object"||Array.isArray($))return;return jq($.userShellCommand)}var w0=16777216,Y1=65536,yL=1048576,Iq=8,E0=200,vq=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,uq=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,Pq=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,hq=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),nq=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function y($,q){return $.count+=1,q}function cq($){return vq.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function lq($){return[...$].filter((q)=>{if(q===`
|
|
42
|
-
`||q==="\r"||q==="\t")return!0;let f=q.codePointAt(0)??0;if(f<32||f===127)return!1;if(f>=57344&&f<=63743)return!1;if(f>=983040&&f<=1048573)return!1;if(f>=1048576&&f<=1114109)return!1;if(f>=917504&&f<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function g($,q){let f=$.normalize("NFKC"),L=f.replace(hq,"");if(L!==f)q.count+=1;f=L,f=f.replace(nq,()=>y(q,"[redacted-private-key]")),f=f.replace(/\bBearer\s+[^\s"'`]+/gi,()=>y(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>y(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>y(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(C,J,Z)=>`${J}${Z}${y(q,"[redacted]")}`);let B=lq(f);if(B!==f)q.count+=1;return B.replace(/\r\n?/g,`
|
|
43
|
-
`)}function O1($,q,f){if(/^data:[^;,]+;base64,/i.test($))return y(f,"[binary omitted]");let L=g($,f),B=_1.resolve(q);for(let C of[B,B.startsWith("/private/")?B.slice(8):`/private${B}`])L=L.replaceAll(C,".");return L=L.replace(uq,(C)=>C.startsWith("./")?C:y(f,"[host-path]")),L=L.replace(Pq,()=>y(f,"[host-path]")),L=L.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(C)=>{try{let J=new URL(C);if(J.username||J.password||J.search||J.hash)f.count+=1;return J.username="",J.password="",J.search="",J.hash="",J.toString()}catch{return y(f,"[redacted-url]")}}),L}function Y$($,q,f,L=0,B){if(B&&cq(B))return y(f,"[redacted]");if(L>=Iq)return y(f,"[depth limit]");if(typeof $==="string")return O1($,q,f);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let C=$.slice(0,E0).map((J)=>Y$(J,q,f,L+1));if($.length>C.length)C.push(y(f,`[${$.length-C.length} items omitted]`));return C}if($&&typeof $==="object"){let C={},J=Object.entries($);for(let[Z,Q]of J.slice(0,E0))C[g(Z,f)]=Y$(Q,q,f,L+1,Z);if(J.length>E0)C["[entries omitted]"]=J.length-E0;return C}return String($)}function pq($,q){let f=Buffer.from($,"utf8");if(f.length<=q)return $;let L=f.subarray(0,q).toString("utf8");while(Buffer.byteLength(L,"utf8")>q)L=L.slice(0,-1);return L}function iq($,q,f){let L=JSON.stringify(Y$($,q,f),null,2);if(Buffer.byteLength(L,"utf8")<=Y1)return L;f.count+=1;let B=`
|
|
44
|
-
... [activity truncated]`;return pq(L,Y1-Buffer.byteLength(B))+B}function _$($,q=""){let f=Math.max(2,...[...$.matchAll(/`+/g)].map((B)=>B[0].length)),L="`".repeat(f+1);return`${L}${q}
|
|
45
|
-
${$}
|
|
46
|
-
${L}`}function V$($){return $.replace(/\s+/g," ").trim()}function dq($){let q=new Map,f=new Map,L=new Map,B=0;for(let C of u($)){if(C.type==="message_created"){let Y=f.get(C.data.messageId);if(Y)Y.role=C.data.role,Y.metadata=C.data.metadata,q.set(C.data.messageId,Y),f.delete(C.data.messageId);else if(!q.has(C.data.messageId))q.set(C.data.messageId,{order:B++,role:C.data.role,parts:[],metadata:C.data.metadata});continue}if(C.type!=="part_created"&&C.type!=="part_updated")continue;let J=q.get(C.data.messageId)??f.get(C.data.messageId);if(!J)J={order:B++,role:"activity",parts:[]},f.set(C.data.messageId,J);let Z=`${C.data.messageId}\x00${C.data.partType}\x00${C.data.partId}`,Q=L.get(Z);if(Q){Q.event=C;continue}let X={order:B++,event:C};L.set(Z,X),J.parts.push(X)}return[...q.values(),...f.values()].sort((C,J)=>C.order-J.order)}function X$($,q,f,L){return`## Activity: ${$}
|
|
47
|
-
|
|
48
|
-
${_$(iq(q,f.projectPath,L),"json")}`}function W1($,q,f={}){let L={count:0},B=f.includeReasoning===!0,C=[],J=0,Z=0,Q=0;for(let E of dq($)){let U=b0(E.metadata);if(U){let A=g(U.command,L),D=g([U.stdout,U.stderr?`stderr:
|
|
49
|
-
${U.stderr}`:""].filter(Boolean).join(`
|
|
50
|
-
`)||"(no output)",L);C.push(`## User shell command
|
|
51
|
-
|
|
52
|
-
${_$(`$ ${A}
|
|
53
|
-
${D}`,"console")}`),J+=1;continue}let e=[],$0=[],k=[],S=Number.POSITIVE_INFINITY;for(let A of E.parts.sort((D,w)=>D.order-w.order)){let{partType:D,payload:w}=A.event.data;if(D==="text"){let K=w.text;if(typeof K==="string"&&K.trim())e.push(g(K,L)),S=Math.min(S,A.order)}else if(D==="image"){let K=w.mimeType;$0.push(typeof K==="string"?`[Image: ${g(K,L)}]`:"[Image]"),S=Math.min(S,A.order)}else if(D==="reasoning"&&B){let K=w.text;if(typeof K==="string"&&K.trim())k.push({order:A.order,markdown:`## Reasoning
|
|
54
|
-
|
|
55
|
-
${g(K,L).trim()}`}),Q+=1}else if(D==="tool_call"){let K=w,M=typeof K.toolName==="string"?g(K.toolName,L):"unknown";k.push({order:A.order,markdown:X$(`${M} call`,K.input??{},q,L)}),Z+=1}else if(D==="tool_result"){let K=w,M=typeof K.toolName==="string"?g(K.toolName,L):"unknown";k.push({order:A.order,markdown:X$(`${M} result`,typeof K.error==="string"?{error:K.error}:{output:K.output??null},q,L)}),Z+=1}else if(D==="summary"){let K=w.text;if(typeof K==="string"&&K.trim())k.push({order:A.order,markdown:`## Summary
|
|
56
|
-
|
|
57
|
-
${g(K,L).trim()}`})}else if(D==="subtask_ref")k.push({order:A.order,markdown:X$("Subagent",w,q,L)}),Z+=1;else if(D==="diff"||D==="patch"){let K=typeof w==="string"?w:JSON.stringify(w,null,2);k.push({order:A.order,markdown:`## File changes
|
|
58
|
-
|
|
59
|
-
${_$(O1(K,q.projectPath,L),"diff")}`}),Z+=1}}if((E.role==="user"||E.role==="assistant")&&(e.length>0||$0.length>0))k.push({order:S,markdown:`## ${E.role==="user"?"User":"Assistant"}
|
|
60
|
-
|
|
61
|
-
${[...e,...$0].join(`
|
|
62
|
-
|
|
63
|
-
`).trim()}`}),J+=1;C.push(...k.sort((A,D)=>A.order-D.order).map((A)=>A.markdown))}if(C.length===0)throw Error("No conversation content to export");let X=`${C.join(`
|
|
64
|
-
|
|
65
|
-
`)}
|
|
66
|
-
`,Y=Buffer.byteLength(X,"utf8");if(Y>w0)throw Error(`Session export exceeds ${w0} bytes`);let G=mq("sha256").update(X).digest("hex"),V=_1.basename(q.taskSourceProjectPath??q.projectPath),_=q.selectedModelId??q.taskModelId,N=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${V$(g(q.title,L))}`]:[],`- Project: \`${V$(g(V,L))}\``,..._?[`- Model: \`${V$(g(_,L))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${B?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${G}\``,`- Content bytes: ${Y}`,`- Redactions: ${L.count}`,"","---",""].join(`
|
|
67
|
-
`)+`
|
|
68
|
-
`+X;if(Buffer.byteLength(N,"utf8")>w0)throw Error(`Session export exceeds ${w0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:N,contentSha256:G,contentBytes:Y,messageCount:J,activityCount:Z,reasoningIncluded:B,reasoningCount:Q,redactionCount:L.count}}import{createHash as rq}from"node:crypto";import oq from"ajv";var U1="StructuredOutput",H1=65536,K1=131072,mL=2,T1=20,x1=1000,N1=200;function a($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function F1($,q){if(!a($))throw Error(`${q} must be a JSON object`);let f;try{f=JSON.stringify($)}catch(B){throw Error(`${q} must be JSON-serializable`,{cause:B})}if(f===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(f);if(!a(L))throw Error(`${q} must be a JSON object`);return L}function tq($){let q=0,f=0,L=(B,C)=>{if(q++,q>x1)throw Error(`Output schema exceeds the ${x1} node complexity limit`);if(C>T1)throw Error(`Output schema exceeds the ${T1} level depth limit`);if(Array.isArray(B)){for(let J of B)L(J,C+1);return}if(!a(B))return;if("$ref"in B){let J=B.$ref;if(typeof J!=="string"||!(J==="#"||J.startsWith("#/$defs/")||J.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in B&&a(B.properties)){if(f+=Object.keys(B.properties).length,f>N1)throw Error(`Output schema exceeds the ${N1} property limit`)}for(let J of Object.values(B))L(J,C+1)};L($,0)}function aq($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function sq($){let q=new oq({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(f){throw Error(`Invalid output schema: ${f instanceof Error?f.message:String(f)}`)}}function z1($){let q=F1($,"Output schema"),f=JSON.stringify(q);if(Buffer.byteLength(f)>H1)throw Error(`Output schema exceeds ${H1} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');tq(q);let B=sq(q),C=rq("sha256").update(f).digest("hex");return{schema:q,schemaDigest:C,declaration:{name:U1,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(J){let Z;try{Z=F1(J,"Structured output")}catch(X){return{success:!1,message:X instanceof Error?X.message:String(X)}}let Q=JSON.stringify(Z);if(Buffer.byteLength(Q)>K1)return{success:!1,message:`Structured output exceeds ${K1} bytes`};if(!B(Z))return{success:!1,message:aq(B.errors)};return{success:!0,output:Z}}}}function R1($,q){if(!a($))return;let f=a($.structuredOutput)?$.structuredOutput:$;if(f.schemaDigest!==q.schemaDigest||!("output"in f))return;let L=q.validate(f.output);return L.success?L.output:void 0}function IL($,q){for(let f=$.length-1;f>=0;f--){let L=$[f];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let J=R1(L.metadata,q);if(J)return{output:J,completed:!0};continue}if(L.role!=="tool"||L.name!==U1)continue;let B=a(L.metadata)?L.metadata:void 0,C=R1(B?.metadata,q);if(C)return{output:C,completed:!1}}return}var Q0=D0("Service"),D1=new Set(["queued","running","completed","failed","cancelled","interrupted"]),U$=new Set(["local","worktree"]),S0=new Set(["high","medium","low"]),j0=new Set(["feature","bug","maintenance","research"]);function eq($,q,f,L){if($.taskStatuses){let B=$.taskStatuses.includes("interrupted")?[...new Set([...$.taskStatuses,"running"])]:$.taskStatuses;f.push(`${q}task_status IN (${B.map(()=>"?").join(", ")})`),L.push(...B)}if($.taskPriorities)f.push(`${q}task_priority IN (${$.taskPriorities.map(()=>"?").join(", ")})`),L.push(...$.taskPriorities);if($.taskDueAfter)f.push(`${q}task_due_at >= ?`),L.push($.taskDueAfter);if($.taskDueBefore)f.push(`${q}task_due_at <= ?`),L.push($.taskDueBefore)}function $f($,q){if(!n1($,q))return!1;if(q.taskPriorities&&($.taskPriority===void 0||!q.taskPriorities.includes($.taskPriority)))return!1;if(q.taskDueAfter&&($.taskDueAt===void 0||$.taskDueAt<q.taskDueAfter))return!1;if(q.taskDueBefore&&($.taskDueAt===void 0||$.taskDueAt>q.taskDueBefore))return!1;return!0}function n1($,q){return q.taskStatuses===void 0||q.taskStatuses.includes($.taskStatus)}var qf=new Set(["default","autoEdit","yolo","plan"]),ff=new Set(["applied","discarded","conflicted"]),Lf=86400000;class z$ extends Error{}function A1($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function M1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((L)=>typeof q[L]!=="string"||!q[L])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function b1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!ff.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function w1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((L)=>typeof q[L]!=="number"||!Number.isInteger(q[L])||q[L]<0))return;return q}function E1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$,f;if(q.outputSchema!==void 0)try{f=z1(q.outputSchema).schema}catch{return}if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!O.isAbsolute(q.sourceProjectPath)||!U$.has(q.isolation)||!k0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.taskPriority!==void 0&&!S0.has(q.taskPriority)||q.taskKind!==void 0&&!j0.has(q.taskKind)||q.taskDueAt!==void 0&&(typeof q.taskDueAt!=="string"||!Number.isFinite(Date.parse(q.taskDueAt)))||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!O0(q.reasoningEffort)||q.serviceTier!==void 0&&!_0(q.serviceTier)||q.responseVerbosity!==void 0&&!Y0(q.responseVerbosity)||q.communicationStyle!==void 0&&!W0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let L;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>j1)return;let B=0;for(let C of q.attachments){if(!C||typeof C!=="object"||Array.isArray(C))return;let J=C;if(!["file","image","url"].includes(String(J.type)))return;for(let Z of["path","url","content","mimeType","name"])if(J[Z]!==void 0&&typeof J[Z]!=="string")return;B+=typeof J.content==="string"?Buffer.byteLength(J.content):0}if(B>m1)return;L=q.attachments.map((C)=>{let J=C;return{type:J.type,...J.path!==void 0?{path:J.path}:{},...J.url!==void 0?{url:J.url}:{},...J.content!==void 0?{content:J.content}:{},...J.mimeType!==void 0?{mimeType:J.mimeType}:{},...J.name!==void 0?{name:J.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},...S0.has(q.taskPriority)?{taskPriority:q.taskPriority}:{},...j0.has(q.taskKind)?{taskKind:q.taskKind}:{},...typeof q.taskDueAt==="string"?{taskDueAt:new Date(q.taskDueAt).toISOString()}:{},sourceProjectPath:O.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...O0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},..._0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Y0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...W0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...L?{attachments:L}:{},...f?{outputSchema:f}:{}}}function k0($){return typeof $==="string"&&qf.has($)}function g1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!O.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:O.resolve(q.projectPath)}}var c1={stat($){return y0($,{bigint:!0})},readFile($){return s($,"utf-8")}},X0=c1;function Y2($){X0=$}function _2(){X0=c1}class l1 extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class f0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class h extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function W$($,q){return`${$}\x00${q}`}function Cf($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function p1($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function Bf($){let q=new Map($.map((f)=>[W$(f.projectPath,f.sessionId),f]));return $.map((f)=>{let L=f,B=new Set;while(L){let Q=W$(L.projectPath,L.sessionId);if(B.has(Q))break;if(B.add(Q),p1(L.archivedAt))return{...f,archivedAt:L.archivedAt,archivedBySessionId:L.sessionId};L=L.parentId?q.get(W$(L.projectPath,L.parentId)):void 0}let{archivedAt:C,archivedBySessionId:J,...Z}=f;return Z})}function H$($,q){let f=Bf($);if(q===null)return f;return f.filter((L)=>Boolean(L.archivedAt)===q)}class x{static toUISafeMessages($){let q=Date.now(),f=$.length,L=[];return $.forEach((B,C)=>{if(B.role!=="user"&&B.role!=="assistant"||!L1(B))return;let J;if(typeof B.content==="string")J=B.content;else if(Array.isArray(B.content))J=B.content.map((G)=>G.type==="text"?G.text:"[Image]").join("");else J="";let Z=J.trim();if(!Z)return;let Q=b0(B.metadata),X=Q?X1(Q):Z,Y=L[L.length-1];if(Y&&Y.role===B.role&&Y.content===X)return;L.push({id:`restored-${q}-${C}`,role:B.role,content:X,timestamp:q-(f-C)*1000,metadata:B.metadata&&typeof B.metadata==="object"?B.metadata:void 0})}),L}static async listSessionPage($={}){let q=x$($),f=await this.listSessionPageFromProjection(q);if(f)return f;let B=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(N$),C=F$(B,q);return{sessions:C.sessions.map((J)=>this.toPublicMetadata(J)),nextCursor:C.nextCursor}}static async listSessionPageFromProjection($){let q=u1($);try{let f=await g0();if(!f)return null;await R$(f,this.projectionDeriver(),$.cursor?5000:0);let L=[],B=[];if($.cwd)L.push("s.project_path = ?"),B.push($.cwd);if(!$.includeSubagents)L.push("s.is_subagent = 0");if(L.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){L.push(`(
|
|
69
|
-
s.last_message_time < ?
|
|
70
|
-
OR (
|
|
71
|
-
s.last_message_time = ?
|
|
72
|
-
AND (
|
|
73
|
-
s.project_sort_key > ?
|
|
74
|
-
OR (s.project_sort_key = ? AND s.session_sort_key > ?)
|
|
75
|
-
)
|
|
76
|
-
)
|
|
77
|
-
)`);let Q=T$(q.projectPath);B.push(q.lastMessageTime,q.lastMessageTime,Q,Q,T$(q.sessionId))}let C=f.prepare(`WITH RECURSIVE archive_members(
|
|
78
|
-
project_path, session_id, archive_root_id, effective_archived_at, depth
|
|
79
|
-
) AS (
|
|
80
|
-
SELECT project_path, session_id, session_id, archived_at, 0
|
|
81
|
-
FROM sessions
|
|
82
|
-
WHERE archived_at IS NOT NULL
|
|
83
|
-
UNION ALL
|
|
84
|
-
SELECT child.project_path, child.session_id, parent.archive_root_id,
|
|
85
|
-
parent.effective_archived_at, parent.depth + 1
|
|
86
|
-
FROM sessions child
|
|
87
|
-
JOIN archive_members parent
|
|
88
|
-
ON child.project_path = parent.project_path
|
|
89
|
-
AND child.parent_id = parent.session_id
|
|
90
|
-
WHERE parent.depth < 128
|
|
91
|
-
),
|
|
92
|
-
ranked_archive AS (
|
|
93
|
-
SELECT project_path, session_id, archive_root_id,
|
|
94
|
-
effective_archived_at,
|
|
95
|
-
ROW_NUMBER() OVER (
|
|
96
|
-
PARTITION BY project_path, session_id
|
|
97
|
-
ORDER BY depth ASC, archive_root_id ASC
|
|
98
|
-
) AS rank
|
|
99
|
-
FROM archive_members
|
|
100
|
-
)
|
|
101
|
-
SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
|
|
102
|
-
FROM sessions s
|
|
103
|
-
LEFT JOIN ranked_archive a
|
|
104
|
-
ON a.project_path = s.project_path
|
|
105
|
-
AND a.session_id = s.session_id
|
|
106
|
-
AND a.rank = 1
|
|
107
|
-
${L.length>0?`WHERE ${L.join(" AND ")}`:""}
|
|
108
|
-
ORDER BY s.last_message_time DESC,
|
|
109
|
-
s.project_sort_key ASC,
|
|
110
|
-
s.session_sort_key ASC
|
|
111
|
-
LIMIT ?`).all(...B,$.limit+1),J=await Promise.all(C.map(async(Q)=>{let X=JSON.parse(Q.metadata_json);if(Q.archive_root_id&&Q.effective_archived_at)return this.reconcileInterruptedTask({...X,archivedAt:Q.effective_archived_at,archivedBySessionId:Q.archive_root_id});let{archivedAt:Y,archivedBySessionId:G,...V}=X;return this.reconcileInterruptedTask(V)})),Z=F$(J,$);return{sessions:Z.sessions.map((Q)=>this.toPublicMetadata(Q)),nextCursor:Z.nextCursor}}catch{return null}}static async listSessions($={}){let q=x$($),f=P1($),L=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived,f),B=new Set;return L.sort(N$).flatMap((C)=>{let J=`${C.projectPath}\x00${C.sessionId}`;if(B.has(J))return[];return B.add(J),[this.toPublicMetadata(C)]})}static async collectStaleEmptySessions($={}){let q=$.now??Date.now(),f=$.olderThanMs??Lf;if(!Number.isFinite(f)||f<0)throw Error("Stale empty session age must be a non-negative number");let L=$.projectPath?[{storagePath:C0(this.resolveCatalogWorkspace($.projectPath)),projectPath:this.resolveCatalogWorkspace($.projectPath)}]:await this.listAllProjectStorageDirectories(),B=0;for(let C of L){let J;try{J=await O$(C.storagePath)}catch(Z){if(Z.code==="ENOENT")continue;throw Z}for(let Z of J){if(!Z.endsWith(".jsonl"))continue;let Q=Z.slice(0,-6);if(!S1(Q))continue;let X=O.join(C.storagePath,Z);try{let G=await y0(X);if(q-G.mtimeMs<f)continue;if(await Promise.all([y0(O.join(C.storagePath,`${Q}.inbox.json`)).then(()=>!0).catch(()=>!1),y0(V0(C.projectPath,Q)).then(()=>!0).catch(()=>!1)]).then((_)=>_.some(Boolean)))continue}catch(G){if(G.code==="ENOENT")continue;throw G}let Y;try{Y=await c.acquire(Q,C.projectPath)}catch(G){if(G instanceof n)continue;throw G}try{if(!await new I(X).deleteValidated((V)=>V.length===1&&V[0]?.type==="session_created"&&V[0].data.relationType!=="subagent"))continue;B++,await q0(O.join(C.storagePath,`${Q}.inbox.json`),{force:!0}),await q0(V0(C.projectPath,Q),{force:!0}),await this.removeFromProjection(Q,C.projectPath)}catch(G){Q0.warn(`[SessionService] Skipping stale empty session cleanup: ${Q}`,G)}finally{await Y.release()}}}return B}static async findSessionMetadata($,q){if(b($),q!==void 0){if(!O.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=O.resolve(q),B=this.getSessionFilePath(L,$);try{let C=await this.readStoredSessionMetadata(B,$,L);if(C.projectPath!==L)return;if(!C.parentId||C.archivedAt)return this.toPublicMetadata(H$([C],null)[0]??C);let J=await this.scanStoredSessions(L,!0,0,null);return this.toPublicMetadata(J.find((Z)=>Z.sessionId===$)??C)}catch(C){if(C.code==="ENOENT")return;throw C}}let f=(await this.scanStoredSessions(void 0,!0,0,null)).filter((L)=>L.sessionId===$);if(f.length===0)return;if(f.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(f[0])}static async loadSession($,q){try{if(q){if(!O.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=O.resolve(q),B=this.getSessionFilePath(L,$);try{return await this.loadSessionFromFile(B,$,L)}catch(C){if(C.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw C}}let f=(await this.scanStoredSessions(void 0,!0,0,null)).find((L)=>L.sessionId===$);if(!f)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(f.filePath,$)}catch(f){throw Q0.error(`[SessionService] 加载会话失败 (${$}):`,f),f}}static async loadSessionModelContext($,q){try{if(q){if(!O.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=O.resolve(q),B=this.getSessionFilePath(L,$);try{return await this.loadSessionModelContextFromFile(B,$,L)}catch(C){if(C.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw C}}let f=(await this.scanStoredSessions(void 0,!0,0,null)).find((L)=>L.sessionId===$);if(!f)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(f.filePath,$)}catch(f){throw Q0.error(`[SessionService] 加载模型上下文失败 (${$}):`,f),f}}static async exportSessionMarkdown($,q,f={}){b($);let L=this.resolveCatalogWorkspace(q),B=m(L,$),C;try{C=await this.readStableSessionSnapshot(B,$)}catch(Q){throw this.sanitizeStoredSessionError(Q,$)}let J=this.projectMetadataFromEntries(C,$,L,B);if(J.projectPath!==L)throw Error(`Session export workspace mismatch: ${$}`);let Z=J.archivedAt;if(!Z&&J.parentId)Z=(await this.findArchivedAncestor(J.parentId,L))?.archivedAt;return W1(C,{...J,archivedAt:Z},f)}static async listRewindCheckpoints($,q){b($);let f=this.resolveCatalogWorkspace(q),L=m(f,$),B=await this.readStableSessionSnapshot(L,$);this.validateSessionWorkspace(B,$,f);let C=new A0({sessionId:$,workspaceRoot:f});await C.initialize();let J=I1(B),Z=[];for(let Q of J){let X=K$(B,Q.messageId),Y=await C.previewRewind(X.snapshotMessageIds);Z.push({...Q,fileCount:Y.files.length})}return Z}static async rewindSession($,q,f){b($);let L=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,L);let B=m(L,$),C=new I(B),J;try{await C.appendValidatedAsync(async(Z)=>{this.validateSessionWorkspace(Z,$,L);let Q=K$(Z,f.targetMessageId),X=new A0({sessionId:$,workspaceRoot:L});await X.initialize();let Y=await X.previewRewind(Q.snapshotMessageIds),G=f.mode==="conversation"?await X.commitSnapshots(Q.snapshotMessageIds):await X.rewindSnapshots(Q.snapshotMessageIds),V=new Date().toISOString(),_={id:j(),sessionId:$,timestamp:V,type:"session_rewound",cwd:L,gitBranch:p(L),version:i(),data:{rewindId:j(),targetMessageId:f.targetMessageId,mode:f.mode,restoredFiles:f.mode==="conversation"?[]:G.files,createdAt:V}},W=u([...Z,_]);return J={checkpoint:{...Q.checkpoint,fileCount:Y.files.length},mode:f.mode,removedTurns:Q.removedTurns,restoredFiles:_.data.restoredFiles,messages:this.convertJSONLToMessages(W)},_})}catch(Z){throw this.sanitizeStoredSessionError(Z,$)}if(!J)throw Error(`Session rewind did not produce a result: ${$}`);for(let Z of J.restoredFiles)l.getInstance().clearFileRecord(Z);return J}static async forkSession($,q){b($);let f=q.newSessionId??`fork-${Date.now()}-${j(8)}`;b(f);let L=this.resolveForkWorkspace(q.sourceProjectPath),B=this.resolveForkWorkspace(q.targetProjectPath);if(L!==B)throw Error("Session forks must stay in the source workspace");let C=m(L,$),J=await this.readStableSessionSnapshot(C,$),Z=this.getSessionCreatedEntry(J,$);if(Z.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!O.isAbsolute(Z.cwd)||O.resolve(Z.cwd)!==L)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let Q=this.projectMetadataFromEntries(J,$,L,C);if(Q.archivedAt)throw new f0($,$);if(Q.parentId){let F=await this.findArchivedAncestor(Q.parentId,L);if(F)throw new f0($,F.sessionId)}let X=u(J),Y=new Date().toISOString(),G=Z.data.rootId||$,V=p(B),_=i(),{status:W,taskStatus:N,taskStatusReason:E,taskFailure:U,taskStartedAt:e,taskCompletedAt:$0,taskOwnerPid:k,taskPromptSummary:S,taskPriority:A,taskKind:D,taskDueAt:w,taskDispatch:K,taskModelId:M,taskRetriedFrom:D$,taskDelivery:A$,taskIsolation:M$,taskSourceProjectPath:m0,taskWorktree:b$,taskDiffStat:w$,taskQueuePosition:E$,taskQueueDepth:g$,taskConcurrencyLimit:y$,pendingInteraction:I0,...v0}=Z.data,u0={id:j(),sessionId:f,timestamp:Y,type:"session_created",cwd:B,gitBranch:V,version:_,data:{...v0,sessionId:f,rootId:G,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:Y,taskIsolation:"local",taskSourceProjectPath:B,createdAt:Y,updatedAt:Y}},P0=X.filter((F)=>F.type!=="session_created"&&F.type!=="token_budget_handoff_recorded"&&F.type!=="inbox_acknowledged"&&F.type!=="interaction_requested"&&F.type!=="interaction_responded"&&F.type!=="interaction_recovered"&&F.type!=="review_started"&&F.type!=="review_completed").map((F)=>{let d={...F,id:j(),sessionId:f,cwd:B,gitBranch:V,version:_};if(F.type==="session_updated"){let{status:K0,taskStatus:z,taskStatusReason:c0,taskFailure:Jf,taskStartedAt:Zf,taskCompletedAt:Gf,taskOwnerPid:Qf,taskPromptSummary:Vf,taskPriority:Xf,taskKind:Yf,taskDueAt:_f,taskDispatch:Of,taskModelId:Wf,taskRetriedFrom:Hf,taskDelivery:Kf,taskIsolation:Tf,taskSourceProjectPath:xf,taskWorktree:Nf,taskDiffStat:Ff,taskQueuePosition:Rf,taskQueueDepth:Uf,taskConcurrencyLimit:zf,pendingInteraction:Df,...i1}=F.data;return{...d,type:"session_updated",data:{...i1,sessionId:f,rootId:G,parentId:$,relationType:"fork"}}}if(F.type==="message_created"){let{inboxMessageId:K0,...z}=F.data;return{...d,type:"message_created",data:z}}return d}),h0={id:j(),sessionId:f,timestamp:Y,type:"session_updated",cwd:B,gitBranch:V,version:_,data:{sessionId:f,rootId:G,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:Y,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:B,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:Y}},L0=[u0,...P0,h0],H0=m(B,f);try{await new I(H0).createExclusive(L0)}catch(F){if(F.code==="EEXIST")throw Error(`Fork session already exists: ${f}`,{cause:F});throw F}let n0=this.projectMetadataFromEntries(L0,f,B,H0);return{sessionId:f,parentSessionId:$,projectPath:B,messages:this.convertJSONLToMessages(L0),metadata:this.toPublicMetadata(n0)}}static async deleteSession($,q){if(b($),q){if(!O.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=O.resolve(q),B=this.getSessionFilePath(L,$),C=new I(B),J;try{J=await C.deleteValidated((Z)=>{return this.projectMetadataFromEntries(Z,$,L,B).projectPath===L})}catch(Z){if(!this.isCorruptSessionJSONLError(Z))throw Z;J=await C.delete()}if(!J)return 0;return await q0(O.join(O.dirname(B),`${$}.inbox.json`),{force:!0}),await q0(V0(L,$),{force:!0}),await this.removeFromProjection($,L),1}let f=(await this.scanStoredSessions(void 0,!0)).filter((L)=>L.sessionId===$);if(f.length===0)return 0;return await Promise.all(f.map(async(L)=>{await new I(L.filePath).delete(),await q0(O.join(O.dirname(L.filePath),`${L.sessionId}.inbox.json`),{force:!0}),await q0(V0(L.projectPath,L.sessionId),{force:!0}),await this.removeFromProjection(L.sessionId,L.projectPath)})),f.length}static async removeFromProjection($,q){try{let f=await g0();if(f)h1(f,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskPriority!==void 0&&$.taskPriority!==null&&!S0.has($.taskPriority))throw Error("Invalid session task priority");if($.taskKind!==void 0&&$.taskKind!==null&&!j0.has($.taskKind))throw Error("Invalid session task kind");if($.taskDueAt!==void 0&&$.taskDueAt!==null&&!Number.isFinite(Date.parse($.taskDueAt)))throw Error("Invalid session task due date");if($.taskFailure!==void 0&&$.taskFailure!==null&&!q$($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!E1($.taskDispatch))throw Error("Invalid durable task dispatch");if($.taskModelId!==void 0&&$.taskModelId!==null&&(!$.taskModelId.trim()||$.taskModelId.length>500))throw Error("Invalid session task model ID");if($.selectedModelId!==void 0&&$.selectedModelId!==null&&(!$.selectedModelId.trim()||$.selectedModelId.length>500))throw Error("Invalid selected session model ID");if($.permissionMode!==void 0&&$.permissionMode!==null&&!k0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!O0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!_0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!Y0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!W0($.communicationStyle))throw Error("Invalid session communication style");if($.communicationStyleDigest!==void 0&&$.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))throw Error("Invalid session communication style digest");if($.projectInstructionsDigest!==void 0&&$.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if($.taskRetriedFrom!==void 0&&$.taskRetriedFrom!==null&&!g1($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!b1($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!U$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!O.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let f=M1($.taskWorktree);if(!f||f.sessionId!==q||![f.repositoryRoot,f.originalWorkspaceRoot,f.worktreeRoot,f.workspaceRoot].every((L)=>O.isAbsolute(L)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!w1($.taskDiffStat))throw Error("Invalid session task diff stat");if($.taskQueuePosition!==void 0&&$.taskQueuePosition!==null&&(!Number.isInteger($.taskQueuePosition)||$.taskQueuePosition<1))throw Error("Invalid session task queue position");if($.taskQueueDepth!==void 0&&$.taskQueueDepth!==null&&(!Number.isInteger($.taskQueueDepth)||$.taskQueueDepth<0))throw Error("Invalid session task queue depth");if($.taskConcurrencyLimit!==void 0&&$.taskConcurrencyLimit!==null&&(!Number.isInteger($.taskConcurrencyLimit)||$.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof $.taskQueuePosition==="number"&&typeof $.taskQueueDepth==="number"&&$.taskQueuePosition>$.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata($,q,f={}){b($),x.validateTaskMetadataUpdate(f,$);let L=x.resolveCatalogWorkspace(q);if(f.taskWorktree&&O.resolve(f.taskWorktree.workspaceRoot)!==L)throw Error("Session task worktree must match the catalog workspace");let B=new Date().toISOString(),C={id:j(),sessionId:$,timestamp:B,type:"session_created",cwd:L,gitBranch:p(L),version:i(),data:{sessionId:$,rootId:$,...f.title!==void 0?{title:f.title}:{},taskStatus:f.taskStatus??"queued",...f.taskPromptSummary!==void 0?{taskPromptSummary:f.taskPromptSummary}:{},...f.taskPriority!==void 0?{taskPriority:f.taskPriority}:{},...f.taskKind!==void 0?{taskKind:f.taskKind}:{},...typeof f.taskDueAt==="string"?{taskDueAt:new Date(f.taskDueAt).toISOString()}:{},...f.taskDispatch!==void 0?{taskDispatch:f.taskDispatch}:{},...f.taskModelId!==void 0?{taskModelId:f.taskModelId}:{},...f.taskRetriedFrom!==void 0?{taskRetriedFrom:f.taskRetriedFrom}:{},...f.taskIsolation!==void 0?{taskIsolation:f.taskIsolation}:{},...f.taskSourceProjectPath!==void 0?{taskSourceProjectPath:f.taskSourceProjectPath}:{},...f.taskWorktree!==void 0?{taskWorktree:f.taskWorktree}:{},...f.selectedModelId!==void 0?{selectedModelId:f.selectedModelId}:{},...f.permissionMode!==void 0?{permissionMode:f.permissionMode}:{},...f.reasoningEffort!==void 0?{reasoningEffort:f.reasoningEffort}:{},...f.serviceTier!==void 0?{serviceTier:f.serviceTier}:{},...f.responseVerbosity!==void 0?{responseVerbosity:f.responseVerbosity}:{},...f.communicationStyle!==void 0?{communicationStyle:f.communicationStyle}:{},...f.communicationStyleDigest!==void 0?{communicationStyleDigest:f.communicationStyleDigest}:{},...f.projectInstructionsDigest!==void 0?{projectInstructionsDigest:f.projectInstructionsDigest}:{},createdAt:B,updatedAt:B}},J=x.getSessionFilePath(L,$);return await new I(J).createExclusive([C]),x.toPublicMetadata(x.projectMetadataFromEntries([C],$,L,J))}static async assertSessionWritable($,q){let f=await this.findSessionMetadata($,q);if(!f)throw Error(`Session not found: ${$}`);if(f.archivedAt)throw new f0($,f.archivedBySessionId??$);return f}static async findArchivedAncestor($,q){let f=new Set,L=$;while(L){if(f.has(L))throw Error("Session lineage contains a cycle");f.add(L),b(L);let B=m(q,L),C;try{C=await s(B,"utf8")}catch(Z){if(Z.code==="ENOENT")return;throw Z}let J=this.projectMetadataFromEntries(this.parseStoredSession(C,L),L,q,B);if(J.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(J.archivedAt)return{sessionId:J.sessionId,archivedAt:J.archivedAt};L=J.parentId}return}static async listSessionArchiveMembers($,q){b($);let f=this.resolveCatalogWorkspace(q),L=await this.scanStoredSessions(f,!0,0,null);if(!L.some((J)=>J.sessionId===$))throw Error(`Session not found: ${$}`);let B=new Set([$]),C=!0;while(C){C=!1;for(let J of L)if(J.parentId&&B.has(J.parentId)&&!B.has(J.sessionId))B.add(J.sessionId),C=!0}return L.filter((J)=>B.has(J.sessionId)).sort((J,Z)=>J.sessionId.localeCompare(Z.sessionId)).map((J)=>this.toPublicMetadata(J))}static async archiveSession($,q){b($);let f=this.resolveCatalogWorkspace(q),L=await this.findSessionMetadata($,f);if(!L)throw Error(`Session not found: ${$}`);if(L.archivedAt)return L;let B=await this.listSessionArchiveMembers($,f),C=B.find((Z)=>Z.taskStatus==="queued"||Z.taskStatus==="running");if(C)throw new h(`Stop session ${C.sessionId} before archiving this session tree`);let J=[];try{for(let Y of B)J.push(await c.acquire(Y.sessionId,f));let Z=m(f,$),Q=new I(Z),X=[];return await Q.appendValidated((Y)=>{let G=this.projectMetadataFromEntries(Y,$,f,Z);if(G.archivedAt)throw new h(`Session archive state changed concurrently: ${$}`);if(G.taskStatus==="queued"||G.taskStatus==="running")throw new h(`Stop session ${$} before archiving it`);let V=new Date().toISOString(),_={id:j(),sessionId:$,timestamp:V,type:"session_updated",cwd:f,gitBranch:p(f),version:i(),data:{sessionId:$,archivedAt:V,updatedAt:V}};return X=[...Y,_],_}),this.toPublicMetadata({...this.projectMetadataFromEntries(X,$,f,Z),archivedBySessionId:$})}catch(Z){if(Z instanceof h)throw Z;if(Z instanceof n)throw new h(Z.message);throw this.sanitizeStoredSessionError(Z,$)}finally{for(let Z of J.reverse())await Z.release()}}static async unarchiveSession($,q){b($);let f=this.resolveCatalogWorkspace(q),L=await this.findSessionMetadata($,f);if(!L)throw Error(`Session not found: ${$}`);if(!L.archivedAt)return L;if(L.archivedBySessionId&&L.archivedBySessionId!==$)throw new h(`Unarchive ancestor ${L.archivedBySessionId} to restore session ${$}`);let B;try{B=await c.acquire($,f);let C=m(f,$),J=new I(C),Z=[];return await J.appendValidated((Q)=>{if(!this.projectMetadataFromEntries(Q,$,f,C).archivedAt)throw new h(`Session archive state changed concurrently: ${$}`);let Y=new Date().toISOString(),G={id:j(),sessionId:$,timestamp:Y,type:"session_updated",cwd:f,gitBranch:p(f),version:i(),data:{sessionId:$,archivedAt:null,updatedAt:Y}};return Z=[...Q,G],G}),this.toPublicMetadata(this.projectMetadataFromEntries(Z,$,f,C))}catch(C){if(C instanceof h)throw C;if(C instanceof n)throw new h(C.message);throw this.sanitizeStoredSessionError(C,$)}finally{await B?.release()}}static async updateSessionMetadata($,q,f){if(b($),x.validateTaskMetadataUpdate(f,$),f.taskStatus!==void 0&&!D1.has(f.taskStatus))throw Error(`Invalid session task status: ${String(f.taskStatus)}`);if(f.taskOwnerPid!==void 0&&f.taskOwnerPid!==null&&(!Number.isInteger(f.taskOwnerPid)||f.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let L=x.resolveCatalogWorkspace(q);if(f.taskWorktree&&O.resolve(f.taskWorktree.workspaceRoot)!==L)throw Error("Session task worktree must match the catalog workspace");let B=x.getSessionFilePath(L,$),C=new I(B),J=[];try{await C.appendValidatedAsync(async(Z)=>{let Q=x.getSessionCreatedEntry(Z,$);if(Q.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!O.isAbsolute(Q.cwd)||O.resolve(Q.cwd)!==L)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let X=x.projectMetadataFromEntries(Z,$,L,B);if(X.archivedAt)throw new f0($,$);if(X.parentId){let V=await x.findArchivedAncestor(X.parentId,L);if(V)throw new f0($,V.sessionId)}let Y=new Date().toISOString(),G={id:j(),sessionId:$,timestamp:Y,type:"session_updated",cwd:L,gitBranch:p(L),version:i(),data:{sessionId:$,...f.title!==void 0?{title:f.title}:{},...f.taskStatus!==void 0?{taskStatus:f.taskStatus}:{},...f.taskStatusReason!==void 0?{taskStatusReason:f.taskStatusReason}:{},...f.taskFailure!==void 0?{taskFailure:f.taskFailure}:{},...f.taskStartedAt!==void 0?{taskStartedAt:f.taskStartedAt}:{},...f.taskCompletedAt!==void 0?{taskCompletedAt:f.taskCompletedAt}:{},...f.taskOwnerPid!==void 0?{taskOwnerPid:f.taskOwnerPid}:{},...f.taskPromptSummary!==void 0?{taskPromptSummary:f.taskPromptSummary}:{},...f.taskPriority!==void 0?{taskPriority:f.taskPriority}:{},...f.taskKind!==void 0?{taskKind:f.taskKind}:{},...f.taskDueAt!==void 0?{taskDueAt:f.taskDueAt===null?null:new Date(f.taskDueAt).toISOString()}:{},...f.taskDispatch!==void 0?{taskDispatch:f.taskDispatch}:{},...f.taskModelId!==void 0?{taskModelId:f.taskModelId}:{},...f.taskRetriedFrom!==void 0?{taskRetriedFrom:f.taskRetriedFrom}:{},...f.taskDelivery!==void 0?{taskDelivery:f.taskDelivery}:{},...f.taskIsolation!==void 0?{taskIsolation:f.taskIsolation}:{},...f.taskSourceProjectPath!==void 0?{taskSourceProjectPath:f.taskSourceProjectPath}:{},...f.taskWorktree!==void 0?{taskWorktree:f.taskWorktree}:{},...f.taskDiffStat!==void 0?{taskDiffStat:f.taskDiffStat}:{},...f.taskQueuePosition!==void 0?{taskQueuePosition:f.taskQueuePosition}:{},...f.taskQueueDepth!==void 0?{taskQueueDepth:f.taskQueueDepth}:{},...f.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:f.taskConcurrencyLimit}:{},...f.selectedModelId!==void 0?{selectedModelId:f.selectedModelId}:{},...f.permissionMode!==void 0?{permissionMode:f.permissionMode}:{},...f.reasoningEffort!==void 0?{reasoningEffort:f.reasoningEffort}:{},...f.serviceTier!==void 0?{serviceTier:f.serviceTier}:{},...f.responseVerbosity!==void 0?{responseVerbosity:f.responseVerbosity}:{},...f.communicationStyle!==void 0?{communicationStyle:f.communicationStyle}:{},...f.communicationStyleDigest!==void 0?{communicationStyleDigest:f.communicationStyleDigest}:{},...f.projectInstructionsDigest!==void 0?{projectInstructionsDigest:f.projectInstructionsDigest}:{},updatedAt:Y}};return J=[...Z,G],G})}catch(Z){throw x.sanitizeStoredSessionError(Z,$)}return x.toPublicMetadata(x.projectMetadataFromEntries(J,$,L,B))}static async setSessionPermissionMode($,q,f){if(b($),!k0(f))throw Error("Invalid session permission mode");let L=x.resolveCatalogWorkspace(q),B=await x.findSessionMetadata($,L);if(B?.permissionMode===f)return B;if(B)return x.updateSessionMetadata($,L,{permissionMode:f});try{return await x.createSessionMetadata($,L,{taskStatus:"completed",permissionMode:f})}catch(C){if(C.code!=="EEXIST")throw C;return x.updateSessionMetadata($,L,{permissionMode:f})}}static async findSessionTaskWorktree($,q){b($);let f=x.resolveCatalogWorkspace(q),L=x.getSessionFilePath(f,$);try{return(await x.readStoredSessionMetadata(L,$,f)).taskWorktree}catch(B){if(B.code==="ENOENT")return;throw x.sanitizeStoredSessionError(B,$)}}static async findSessionTaskDispatch($,q){b($);let f=x.resolveCatalogWorkspace(q),L=x.getSessionFilePath(f,$);try{return(await x.readStoredSessionMetadata(L,$,f)).taskDispatch}catch(B){if(B.code==="ENOENT")return;throw x.sanitizeStoredSessionError(B,$)}}static async loadSessionFromFile($,q,f){let L=await s($,"utf-8"),B=this.parseStoredSession(L,q);if(f!==void 0){if(this.projectMetadataFromEntries(B,q,f,$).projectPath!==f)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(B)}static async loadSessionModelContextFromFile($,q,f){let L=await s($,"utf-8"),B=this.parseStoredSession(L,q);if(f!==void 0){if(this.projectMetadataFromEntries(B,q,f,$).projectPath!==f)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToModelContext(B)}static convertJSONLToModelContext($){let q=u($),f=-1,L;for(let C=0;C<q.length;C++){let J=q[C];if(J?.type!=="part_created"||J.data.partType!=="summary")continue;let Z=J.data.payload;if(f=C,L=F0(Z.replacementMessages),!L)L=[{role:"user",content:Z.text??"",metadata:J.data.payload}]}if(f<0||!L)return this.convertJSONLToMessages(q,{includeTokenBudgetHandoffs:!0});let B=this.convertJSONLToMessages(q.slice(f+1),{includeTokenBudgetHandoffs:!0});return[...L,...B]}static convertJSONLToMessages($,q={}){let f=[],L=new Map,B=new Map,C=new Map,J=new Map,Z=new Map,Q=u($),X=q.includeTokenBudgetHandoffs?o$(Q):{kind:"none"},Y=new Set;for(let G of Q){if(G.type==="token_budget_handoff_recorded"){if(X.kind==="valid"&&X.event.id===G.id){let V=t$(G);if(V)f.push(V)}continue}if(G.type==="message_created"){let V=G.data.metadata&&typeof G.data.metadata==="object"&&!Array.isArray(G.data.metadata)?G.data.metadata:void 0,_=V?.codeReview&&typeof V.codeReview==="object"&&!Array.isArray(V.codeReview)?V.codeReview:void 0;if(_?.phase==="completed"&&typeof _.reviewId==="string")Y.add(_.reviewId);let W=G.data.role==="assistant"&&G.data.parentMessageId?C.get(G.data.parentMessageId):void 0,N=W??{role:G.data.role,content:"",...G.data.metadata||G.data.inboxMessageId?{metadata:{...G.data.metadata&&typeof G.data.metadata==="object"&&!Array.isArray(G.data.metadata)?G.data.metadata:{},...G.data.inboxMessageId?{inboxMessageId:G.data.inboxMessageId}:{}}}:{}};if(L.set(G.data.messageId,N),B.set(G.data.messageId,[]),!W)f.push(N)}if(G.type==="part_created"){if(G.data.partType==="reasoning"){let V=L.get(G.data.messageId);if(V){let _=G.data.payload;V.reasoningContent=(V.reasoningContent??"")+(_.text??"")}}if(G.data.partType==="text"){let V=L.get(G.data.messageId);if(V){let _=G.data.payload,W=B.get(G.data.messageId);if(W)W.push({type:"text",text:_.text??""}),V.content=y1(W);else V.content=_.text??""}}if(G.data.partType==="image"){let V=L.get(G.data.messageId);if(V){let _=G.data.payload,W=B.get(G.data.messageId);if(W&&_.dataUrl)W.push({type:"image_url",image_url:{url:_.dataUrl}}),V.content=y1(W)}}if(G.data.partType==="tool_call"){let V=L.get(G.data.messageId);if(V?.role!=="assistant"){if(V=C.get(G.data.messageId),!V)V={role:"assistant",content:"",tool_calls:[]},C.set(G.data.messageId,V),f.push(V)}if(V.role==="assistant"){let _=G.data.payload,W=_.toolCallId??G.data.partId;J.set(G.data.partId,W),Z.set(W,V),V.tool_calls??=[],V.tool_calls.push({id:W,type:"function",function:{name:_.toolName??"unknown",arguments:JSON.stringify(_.input??{})}})}}if(G.data.partType==="tool_result"){let V=G.data.payload,_=f1(V),W=_.error?`Error: ${_.error.message}`:typeof _.llmContent==="string"?_.llmContent:JSON.stringify(_.llmContent),N=V;f.push({role:"tool",content:W,tool_call_id:J.get(G.data.messageId)??V.toolCallId,name:V.toolName,metadata:N})}if(G.data.partType==="summary"){let V=G.data.payload,_=G.data.payload;f.push({role:"system",content:V.text??"",metadata:_})}if(G.data.partType==="subtask_ref"){let V=L.get(G.data.messageId)??Z.get(G.data.messageId);if(V){let _=G.data.payload,W=V.metadata??{};V.metadata={...W,subtaskRef:_}}}}}for(let G of R0(Q)){if(G.completion===void 0||Y.has(G.start.reviewId))continue;f.push({role:"assistant",content:l$(G.start,G.completion),metadata:{codeReview:{...p$(G.start,G.completion),synthetic:!0}}})}return f}static projectionDeriver(){return($,q,f)=>{try{let L=m(f,q);return this.projectMetadataFromEntries($,q,f,L)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,f=0,L=!1,B={}){try{let C=await g0();if(!C)return null;await R$(C,this.projectionDeriver(),f);let J=[],Z=[];if($!==void 0)J.push("project_path=?"),Z.push($);eq(B,"",J,Z);let Q=J.length>0?` WHERE ${J.join(" AND ")}`:"",X=C.prepare(`SELECT metadata_json, is_subagent FROM sessions${Q}`).all(...Z),Y=[];for(let V of X){if(!q&&V.is_subagent===1)continue;try{let _=JSON.parse(V.metadata_json);if($!==void 0&&_.projectPath!==$)continue;Y.push(_)}catch{}}let G=await Promise.all(Y.map((V)=>this.reconcileInterruptedTask(V)));return H$(G.filter((V)=>n1(V,B)),L)}catch{return null}}static async scanStoredSessions($,q=!1,f=0,L=!1,B={}){let C=$?O.resolve($):void 0,J=await this.scanStoredSessionsFromProjection(C,q,f,L,B);if(J)return J;let Z=C?[{storagePath:C0(C),projectPath:C}]:await this.listAllProjectStorageDirectories(),Q=[];for(let X of Z){let Y;try{Y=await O$(X.storagePath)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of Y){if(!G.endsWith(".jsonl"))continue;let V=G.slice(0,-6),_=O.join(X.storagePath,G);try{let W=await this.readStoredSessionMetadata(_,V,X.projectPath);if(C!==void 0&&W.projectPath!==C){Q0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!q&&W.relationType==="subagent")continue;if(!$f(W,B))continue;Q.push(W)}catch(W){let N=W.code;if(N==="ENOENT")continue;if(N)throw W;Q0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return H$(Q,L)}static async listAllProjectStorageDirectories(){let $=O.join(G0(),"projects"),q;try{q=await O$($,{withFileTypes:!0,encoding:"utf8"})}catch(f){if(f.code==="ENOENT")return[];throw f}return q.filter((f)=>f.isDirectory()).map((f)=>({storagePath:O.join($,f.name),projectPath:k1(f.name)}))}static async readStoredSessionMetadata($,q,f){let L=await s($,"utf-8"),B=this.parseStoredSession(L,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(B,q,f,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||A1(q))return $;let f;try{f=await c.acquire($.sessionId,$.projectPath)}catch(C){if(!(C instanceof n))throw C;let J=await s($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(J,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let L=new I($.filePath),B;try{try{await L.appendValidated((C)=>{let J=this.projectMetadataFromEntries(C,$.sessionId,$.projectPath,$.filePath);if(J.taskStatus!=="running"||J.taskOwnerPid!==q||A1(q))throw new z$;let Z=new Date().toISOString(),Q={id:j(),sessionId:$.sessionId,timestamp:Z,type:"session_updated",cwd:$.projectPath,gitBranch:p($.projectPath),version:i(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Z,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Z}};return B=[...C,Q],Q})}catch(C){if(!(C instanceof z$))throw C}if(!B){let C=await s($.filePath,"utf-8");B=this.parseStoredSession(C,$.sessionId)}return this.projectMetadataFromEntries(B,$.sessionId,$.projectPath,$.filePath)}finally{await f.release()}}static projectMetadataFromEntries($,q,f,L){if($.length===0)throw Error(`Empty session transcript: ${q}`);let B=this.getSessionCreatedEntry($,q),C=$.reduce((z,c0)=>c0.type==="session_updated"?{...z,...c0.data}:z,{...B.data}),J=u($),Z=c$(n$(J)),X=R0(J).at(-1),Y=J.findLastIndex((z)=>z.type==="review_started"&&z.data.reviewId===X?.start.reviewId||z.type==="review_completed"&&z.data.reviewId===X?.start.reviewId),G=J.findLastIndex((z)=>(z.type==="session_created"||z.type==="session_updated")&&Object.hasOwn(z.data,"taskStatus")),V=X!==void 0&&Y>G,_=V?X.completion===void 0?"running":X.completion.status==="completed"||X.completion.status==="stale"?"completed":X.completion.status==="aborted"?"cancelled":X.completion.status==="interrupted"?"interrupted":"failed":void 0,W=J.filter((z)=>z.type==="message_created"&&["user","assistant"].includes(z.data.role)).length,N=J.some((z)=>z.type==="part_created"&&z.data.partType==="tool_result"&&typeof z.data.payload.error==="string"),E=D1.has(C.taskStatus)?C.taskStatus:void 0,U=_??E??(N?"failed":"completed"),e=typeof C.taskOwnerPid==="number"&&Number.isInteger(C.taskOwnerPid)&&C.taskOwnerPid>0?C.taskOwnerPid:void 0,$0=U$.has(C.taskIsolation)?C.taskIsolation:void 0,k=typeof C.taskSourceProjectPath==="string"&&O.isAbsolute(C.taskSourceProjectPath)?O.resolve(C.taskSourceProjectPath):void 0,S=B.cwd;if(S!==void 0&&!O.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${q}`);let A=S===void 0?f:O.resolve(S),D=M1(C.taskWorktree),w=D?.sessionId===q&&O.resolve(D.workspaceRoot)===A?D:void 0,K=w1(C.taskDiffStat),M=E1(C.taskDispatch),D$=S0.has(C.taskPriority)?C.taskPriority:M?.taskPriority,A$=j0.has(C.taskKind)?C.taskKind:M?.taskKind,M$=typeof C.taskDueAt==="string"&&Number.isFinite(Date.parse(C.taskDueAt))?new Date(C.taskDueAt).toISOString():M?.taskDueAt,m0=typeof C.taskModelId==="string"&&C.taskModelId.trim()?C.taskModelId:M?.modelId,b$=typeof C.selectedModelId==="string"&&C.selectedModelId.trim()?C.selectedModelId:m0,w$=k0(C.permissionMode)?C.permissionMode:M?.permissionMode,E$=O0(C.reasoningEffort)?C.reasoningEffort:M?.reasoningEffort,g$=_0(C.serviceTier)?C.serviceTier:M?.serviceTier,y$=Y0(C.responseVerbosity)?C.responseVerbosity:M?.responseVerbosity,I0=W0(C.communicationStyle)?C.communicationStyle:M?.communicationStyle,v0=Object.hasOwn(C,"communicationStyleDigest")?typeof C.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(C.communicationStyleDigest)?C.communicationStyleDigest:void 0:I0===M?.communicationStyle?M?.communicationStyleDigest:void 0,u0=Object.hasOwn(C,"projectInstructionsDigest")?typeof C.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(C.projectInstructionsDigest)?C.projectInstructionsDigest:void 0:M?.projectInstructionsDigest,P0=p1(C.archivedAt)?C.archivedAt:void 0,h0=g1(C.taskRetriedFrom),L0=b1(C.taskDelivery),H0=typeof C.taskQueuePosition==="number"&&Number.isInteger(C.taskQueuePosition)&&C.taskQueuePosition>0?C.taskQueuePosition:void 0,n0=typeof C.taskQueueDepth==="number"&&Number.isInteger(C.taskQueueDepth)&&C.taskQueueDepth>=0?C.taskQueueDepth:void 0,F=typeof C.taskConcurrencyLimit==="number"&&Number.isInteger(C.taskConcurrencyLimit)&&C.taskConcurrencyLimit>0?C.taskConcurrencyLimit:void 0,d=V?X?.completion?X.completion.status==="completed"?void 0:`Code review ${d0(X.completion.status)}`:`Reviewing ${X?.start.target.label??"changes"}`:void 0,K0=V?U==="failed"&&d?$$(d):void 0:q$(C.taskFailure)?C.taskFailure:U==="failed"&&typeof C.taskStatusReason==="string"?$$(C.taskStatusReason):void 0;return{sessionId:q,projectPath:A,gitBranch:B.gitBranch,rootId:C.rootId||q,parentId:C.parentId,relationType:C.relationType,resumedFrom:C.resumedFrom,rootAgentId:C.rootAgentId,resumeDepth:C.resumeDepth,title:C.title,agentType:C.agentType,model:C.model,selectedModelId:b$,permissionMode:w$,reasoningEffort:E$,serviceTier:g$,responseVerbosity:y$,communicationStyle:I0,communicationStyleDigest:v0,projectInstructionsDigest:u0,pendingInteraction:Z,taskStatus:U,taskStatusReason:K0?.message??d??(typeof C.taskStatusReason==="string"?C.taskStatusReason:void 0),taskFailure:K0,taskStartedAt:V?X?.start.startedAt:typeof C.taskStartedAt==="string"?C.taskStartedAt:void 0,taskCompletedAt:V?X?.completion?.completedAt:typeof C.taskCompletedAt==="string"?C.taskCompletedAt:void 0,taskPromptSummary:V?X?Cf(X.start.target):"/review uncommitted":typeof C.taskPromptSummary==="string"?C.taskPromptSummary:void 0,taskPriority:D$,taskKind:A$,taskDueAt:M$,taskModelId:m0,taskRetryAvailable:M!==void 0,taskRetriedFrom:h0,taskDelivery:L0,taskIsolation:$0,taskSourceProjectPath:k,taskWorktreePath:w?.worktreeRoot,taskWorktreeBranch:w?.branch,taskBaseCommit:w?.baseCommit,taskDiffStat:K,taskQueuePosition:H0,taskQueueDepth:n0,taskConcurrencyLimit:F,archivedAt:P0,taskOwnerPid:V?void 0:e,taskWorktree:w,taskDispatch:M,messageCount:W,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:N||U==="failed",filePath:L}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:f,taskWorktree:L,taskDispatch:B,...C}=$;return C}static getSessionFilePath($,q){return m($,q)}static getSessionCreatedEntry($,q){let f=$.find((L)=>L.type==="session_created");if(!f)throw new l1(q);return f}static resolveCatalogWorkspace($){if(!O.isAbsolute($))throw Error("Session catalog cwd must be absolute");return O.resolve($)}static validateSessionWorkspace($,q,f){let L=this.getSessionCreatedEntry($,q);if(L.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!O.isAbsolute(L.cwd)||O.resolve(L.cwd)!==f)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!O.isAbsolute($))throw Error("Fork workspace paths must be absolute");return O.resolve($)}static parseStoredSession($,q){return v1($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let f=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${f?` at line ${f}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,f=3){for(let L=0;L<f;L+=1){let B=await X0.stat($),C=await X0.readFile($),J=this.parseStoredSession(C,q),Z=await X0.stat($);if(B.size===Z.size&&B.mtimeNs===Z.mtimeNs&&B.dev===Z.dev&&B.ino===Z.ino)return J}throw Error("Session changed while creating fork; retry the operation")}}function y1($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
112
|
-
export{f$ as Ub,k$ as Vb,T0 as Wb,j$ as Xb,wf as Yb,n as Zb,c as _b,mf as $b,If as ac,n$ as bc,Pf as cc,R0 as dc,nf as ec,d0 as fc,l$ as gc,p$ as hc,pf as ic,df as jc,rf as kc,Oq as lc,o$ as mc,t$ as nc,Wq as oc,of as pc,a$ as qc,$$ as rc,l as sc,A0 as tc,VL as uc,XL as vc,YL as wc,_L as xc,f1 as yc,OL as zc,HL as Ac,L1 as Bc,TL as Cc,Z$ as Dc,G$ as Ec,DL as Fc,AL as Gc,X1 as Hc,b0 as Ic,yL as Jc,U1 as Kc,H1 as Lc,mL as Mc,z1 as Nc,IL as Oc,Lf as Pc,Y2 as Qc,_2 as Rc,l1 as Sc,f0 as Tc,h as Uc,x as Vc};
|
package/dist/chunk-ndnjmy45.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as a,g as i,h as l,i as m}from"./chunk-8gfwva8m.js";import"./chunk-1mc7nfb4.js";import"./chunk-shq0pkxq.js";import"./chunk-sghq0p21.js";import"./chunk-bb1d4r3r.js";import"./chunk-n57jybv7.js";import"./chunk-rkp180w6.js";import"./chunk-pajdvkxa.js";import"./chunk-ky9q53m7.js";import"./chunk-bhe154zk.js";import"./chunk-r8wbvxn7.js";import"./chunk-m0dt3w7w.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{yd as n}from"./chunk-vpcpcwyq.js";import"./chunk-h3w814js.js";import{Ud as s}from"./chunk-gdxm7yz5.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-6at3v7hd.js";import"./chunk-e0ebj41c.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-3e0dry5e.js";import"./chunk-zkhb55jz.js";import"./chunk-cvy0pd00.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.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-qky3qehm.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{m as fH,n as yH,o as SH,p as TH,q as bH,r as RH}from"./chunk-3kggy7we.js";import{A as JH,v as MH,w as t,x as e,y as HH,z as d}from"./chunk-n57jybv7.js";import{Q as xH,S as UH,T as _H,V as ZH,Y as GH}from"./chunk-rkp180w6.js";import"./chunk-pajdvkxa.js";import"./chunk-ky9q53m7.js";import{Eb as jH,jb as s,vb as WH}from"./chunk-bhe154zk.js";import"./chunk-r8wbvxn7.js";import{Kc as O,Vc as a,vc as DH,zc as LH}from"./chunk-m0dt3w7w.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{rd as FH}from"./chunk-217cy9g5.js";import{td as EH,ud as zH,vd as AH}from"./chunk-5nfc0j4f.js";import{wd as PH}from"./chunk-jdb2mwbn.js";import"./chunk-h3w814js.js";import{Wd as QH}from"./chunk-gdxm7yz5.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-6at3v7hd.js";import"./chunk-e0ebj41c.js";import{hf as VH}from"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-3e0dry5e.js";import"./chunk-zkhb55jz.js";import"./chunk-cvy0pd00.js";import{Ag as BH}from"./chunk-pfvgkexe.js";import{Cg as NH,Eg as H,Fg as KH,Hg as N}from"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as g}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import fJ from"yargs";import{hideBin as yJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function mH(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 cH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await mH(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)=>cH(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 $H=1;function D(K){return H.Object({event_version:H.Literal($H),...K})}var uH=D({type:H.Literal("content_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking_delta"),delta:H.String()}),pH=D({type:H.Literal("thinking"),content:H.String()}),vH=D({type:H.Literal("stream_end")}),lH=D({type:H.Literal("content"),content:H.String()}),aH=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"]),sH=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})}),iH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),oH=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(sH)}),rH=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"])}),nH=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(rH)}),tH=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())}),eH=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())}),HJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),JJ=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())}),KJ=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())}),VJ=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())}),ZJ=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())}),$J=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()}),qJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),XJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),YJ=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()}),BJ=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())}),NJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),QJ=D({type:H.Literal("task_update"),tasks:H.Array(ZH)}),DJ=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}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(VH)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),LJ=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}))}),WJ=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())}),jJ=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})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),xJ=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"]))}),UJ=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}))}),_J=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}))}),GJ=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()}),PJ=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()}),FJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),EJ=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())}),zJ=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})}),AJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),MJ=D({type:H.Literal("error"),message:H.String()}),iJ=KH(H.Union([uH,dH,pH,vH,lH,aH,iH,oH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,UJ,_J,xJ,GJ,PJ,FJ,EJ,zJ,AJ,MJ]));function qH(K,V){return{event_version:$H,type:K,...V}}function SJ(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 TJ(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 bJ=N(["text","jsonl"]),RJ=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(BH)),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(bJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class IH{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 IJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function gJ(K){let V=NH(RJ,K);if(!V.success)throw Error(`Invalid headless options: ${IJ(V.error)}`);return V.data}function CJ(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 cJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
|
-
`)}function kJ(K){return`[task] [${K.status}] ${K.subject}`}function hJ(){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 OJ(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 wJ(K){return K==="jsonl"?"jsonl":"text"}function XH(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 mJ(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 YH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(qH(J,Z))}
|
|
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
|
-
`);if(J)K.stdout.write(`
|
|
5
|
-
`)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,kJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function cJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new IH,Z={targetLocked:!1},W,x,j,G=TJ(Q),f=!1,F=new v(V,{signal:G.signal,onFailure:(Y)=>{f=!0,G.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=YH(w,q),m=async()=>{try{return await F.flush(),!f}catch{return!1}},y=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=gJ(K);q=wJ(Y.outputFormat);let S=await bH(Y);B=YH(w,q,Boolean(S)),await fH();let i=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await SH({message:Y.message,_:Y._,stdin:Q?.stdin}):await yH({...Y,stdin:Q?.stdin}),R=i===void 0,P=R?{mode:"agent",content:""}:await TH(i);if(P.mode==="output"){if(P.content)B.output(P.content,P.exitCode??0);return await y(P.exitCode??0)}let C=P.content.trimStart().startsWith("!")?P.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&S)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:_,messages:o,metadata:r}=await RH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),I=Y.permissionMode??r?.permissionMode??"yolo",n=Y.model&&Y.model!=="inherit"?Y.model:QH()?.id,U=Y.taskIsolation?await MH.createSessionTask({sessionId:_,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:I,...n?{modelId:n}:{},...S?{outputSchema:S}:{}}}):void 0,E=U?.metadata.projectPath??r?.projectPath??g();if(j=s.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==_||X.projectPath!==E)return;let $=X.properties,z=["queued","admitted","rejected"],A=["foreground","background","internal"],M=["stream","pending_count","pending_bytes"],b=["global","domain","owner","class"],wH=["capacity","queue_full","wait_timeout","closed"];if(!z.includes($.phase)||!A.includes($.requestClass)||!M.includes($.resource)||!b.includes($.scope)||$.reason!==void 0&&!wH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await a.setSessionPermissionMode(_,E,I);let gH=U?!1:await jH.cancelPendingNonInteractive(E,_);if(U)B.taskSession({sessionId:_,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=s.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==_||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let CH={messages:gH?await a.loadSessionModelContext(_,E):[...o],userId:"cli-user",sessionId:_,workspaceRoot:E,permissionMode:I,signal:G.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:hJ()};W=await xH.create({sessionId:_,workspaceRoot:E,modelId:Y.model,permissionMode:I,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?PH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...o.length>0?{sessionStart:{isResume:!0,resumeSessionId:_}}:{}});let k=R&&W.getPendingSteeringCount()>0,h=R&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",T=R&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(R&&!k&&!c){if(!T)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(T.structuredOutput&&T.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:T.structuredOutput,schemaDigest:T.structuredOutputSchemaDigest});else B.content(T.content);return B.phase("completed","done","Recovered headless run completed"),await y(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:G.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await y(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kH=Y.maxTurns??W.getConfig().maxTurns,hH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,OH=await GH.createWithRuntime(W,{sessionId:_,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:I,toolWhitelist:Y.allowedTools,toolBlacklist:hH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await WH(OH.chatStream(P.content,CH,{stream:!0,signal:G.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:S,pendingInputOnly:k,goalContinuationOnly:c,...kH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!S||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let z=JSON.parse($.function.arguments),A=UH($.function.name,z),M=XH($.function.name,z),b=mJ($.function.name,A,M,Z);if(b.shouldLockTarget)Z.targetLocked=!0;B.phase(b.phase,b.status,b.message,{toolName:$.function.name,target:M}),B.toolStart($.function.name,A,M,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let z;try{let M=JSON.parse($.function.arguments);z=XH($.function.name,M)}catch{z=void 0}let A=LH(_H($.function.name,X.result),DH);if(B.toolResult($.function.name,A.summary,z,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:SJ(X.result.metadata)}),A.detail)B.toolDetail($.function.name,A.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await y(1);return B.phase("completed","done","Headless run completed"),await y(0)}catch(Y){if(!f){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
|
|
6
|
-
`);B.error(`Error: ${OJ(Y)}`)}return await y(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),G.dispose()}}}async function PK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=FH,j=fJ(yJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([zH,EH,AH]);return CJ(j),await j.parse(),!0}export{cJ as runHeadless,PK as handleHeadlessMode,RJ as HeadlessOptionsSchema};
|
package/dist/chunk-qvtstj28.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Qe as a,Re as b,Se as c,Te as d,Ue as e,Ve as f,We as g,Xe as h,Ye as i,Ze as j}from"./chunk-e0ebj41c.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-3e0dry5e.js";import"./chunk-zkhb55jz.js";import"./chunk-cvy0pd00.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-411ewxte.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.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};
|
package/dist/chunk-reakyamv.js
DELETED
package/dist/chunk-rpbyc2k4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{qe as a,re as b,se as c}from"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|