@tansr/cli 0.10.2 → 0.11.0
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/package.json +1 -1
- package/tansr-artifacts.json +1222 -830
- package/tansr-bg-A35DNHK2.mjs +5 -0
- package/tansr-chunk-2CIB4KCJ.mjs +5 -0
- package/{tansr-chunk-XXBNISJJ.mjs → tansr-chunk-2HZJSKHM.mjs} +2 -2
- package/{tansr-chunk-E67N3BDI.mjs → tansr-chunk-2PB54HDR.mjs} +2 -2
- package/tansr-chunk-33QZBUL6.mjs +6 -0
- package/tansr-chunk-3YSQG6KY.mjs +5 -0
- package/tansr-chunk-4DAH4AIH.mjs +7 -0
- package/{tansr-chunk-S77B4PI7.mjs → tansr-chunk-4IWNKAT5.mjs} +2 -2
- package/tansr-chunk-4YAEV3T6.mjs +9 -0
- package/tansr-chunk-546BDI3V.mjs +7 -0
- package/tansr-chunk-6N333TUL.mjs +241 -0
- package/{tansr-chunk-ZY3IR67Q.mjs → tansr-chunk-6QKU3GNA.mjs} +2 -2
- package/tansr-chunk-AHUB2IHT.mjs +5 -0
- package/tansr-chunk-AOH7YPF3.mjs +8 -0
- package/{tansr-chunk-C6COFFZK.mjs → tansr-chunk-B2O4DB4K.mjs} +2 -2
- package/tansr-chunk-C2NTVBEY.mjs +5 -0
- package/{tansr-chunk-UCG4D6ER.mjs → tansr-chunk-C75DEEUJ.mjs} +2 -2
- package/tansr-chunk-ECYZ457U.mjs +5 -0
- package/tansr-chunk-EFN24XG3.mjs +25 -0
- package/tansr-chunk-ENRIN7EG.mjs +7 -0
- package/{tansr-chunk-RVSBSUXE.mjs → tansr-chunk-ITZBYACC.mjs} +2 -2
- package/{tansr-chunk-J72JGEKH.mjs → tansr-chunk-IZZYKHSW.mjs} +3 -3
- package/tansr-chunk-JIC3VWLQ.mjs +252 -0
- package/tansr-chunk-JTGWG4BG.mjs +32 -0
- package/tansr-chunk-LA3LGOYQ.mjs +11 -0
- package/tansr-chunk-MAMODDQN.mjs +5 -0
- package/tansr-chunk-N644DEOO.mjs +5 -0
- package/tansr-chunk-NQOYEFEE.mjs +5 -0
- package/tansr-chunk-O7P4OFK7.mjs +7 -0
- package/tansr-chunk-OEHA7T4Q.mjs +26 -0
- package/{tansr-chunk-CI7LFRTK.mjs → tansr-chunk-OKNSOZDU.mjs} +7 -7
- package/tansr-chunk-OT4KIQLR.mjs +9 -0
- package/tansr-chunk-OUOTEH4A.mjs +5 -0
- package/tansr-chunk-Q3XDAUKT.mjs +65 -0
- package/tansr-chunk-RFH7OCN6.mjs +5 -0
- package/tansr-chunk-RUYIVG72.mjs +12 -0
- package/tansr-chunk-SCFXBKV6.mjs +8 -0
- package/tansr-chunk-SHLU4JN2.mjs +5 -0
- package/{tansr-chunk-M774GK3P.mjs → tansr-chunk-SIV2666W.mjs} +2 -2
- package/tansr-chunk-SX3XZNN6.mjs +6 -0
- package/tansr-chunk-SXNTYWJY.mjs +8 -0
- package/tansr-chunk-UVL2XWKL.mjs +5 -0
- package/tansr-chunk-V4HGMAJS.mjs +375 -0
- package/{tansr-chunk-OB47UYHK.mjs → tansr-chunk-W2WIN3M2.mjs} +2 -2
- package/tansr-chunk-WAYVH5ON.mjs +5 -0
- package/tansr-chunk-WPKFARCU.mjs +11 -0
- package/{tansr-chunk-726Y5F3M.mjs → tansr-chunk-YEYFEVYF.mjs} +2 -2
- package/tansr-chunk-YK3CE3JM.mjs +5 -0
- package/tansr-chunk-YOSRXZWY.mjs +5 -0
- package/tansr-compaction-history-LZXZTWBV.mjs +5 -0
- package/tansr-compaction-log-H2SPLK24.mjs +5 -0
- package/tansr-indexed-CPYJVPFI.mjs +5 -0
- package/tansr-lock-XWDVZMLY.mjs +5 -0
- package/tansr-main-6GDLXIRQ.mjs +7 -0
- package/tansr-render-SVMDLHLN.mjs +6 -0
- package/tansr-restore-7PS7WCJR.mjs +5 -0
- package/tansr-run-acp-entry-EQGUKZ5R.mjs +68 -0
- package/tansr-run-approvals-entry-SEYBHLS2.mjs +12 -0
- package/{tansr-run-auth-entry-X3SXNPOI.mjs → tansr-run-auth-entry-R3GKGKWX.mjs} +2 -2
- package/tansr-run-doctor-B3XK72DW.mjs +11 -0
- package/tansr-run-headless-entry-4XTAVPTW.mjs +84 -0
- package/tansr-run-init-entry-GH2KDGI6.mjs +5 -0
- package/tansr-run-logout-entry-PLGYDEOB.mjs +5 -0
- package/tansr-run-mcp-serve-entry-UHK4WSKL.mjs +14 -0
- package/tansr-run-orchestrate-entry-M7R3433X.mjs +11 -0
- package/tansr-run-org-entry-UONLGJIJ.mjs +17 -0
- package/tansr-run-policy-entry-NNQCV5WS.mjs +16 -0
- package/tansr-run-profile-entry-PV6OO7FV.mjs +14 -0
- package/tansr-run-serve-entry-GWZQZ37P.mjs +16 -0
- package/tansr-run-sessions-entry-WL7YLRJL.mjs +25 -0
- package/tansr-run-update-entry-YI47IPCC.mjs +5 -0
- package/tansr-spill-YVUTIFOS.mjs +5 -0
- package/tansr-src-LPMSGRKO.mjs +5 -0
- package/{tansr-src-JAODAP53.mjs → tansr-src-RQJPOVDN.mjs} +50 -50
- package/tansr-startup-account-MYFJ3NOL.mjs +7 -0
- package/{tansr-startup-model-SREG5HNN.mjs → tansr-startup-model-BCGEYUM4.mjs} +3 -3
- package/tansr-storage-journal-4E274MUA.mjs +5 -0
- package/tansr-todos-replay-TVQKP7OD.mjs +5 -0
- package/tansr-tui-3Q7Z3ALV.mjs +73 -0
- package/tansr.mjs +1 -1
- package/tansrd.mjs +444 -265
- package/tansr-bg-QY4G2SNZ.mjs +0 -5
- package/tansr-chunk-2C6JKHKM.mjs +0 -25
- package/tansr-chunk-53SL6W6G.mjs +0 -6
- package/tansr-chunk-5T7X32UX.mjs +0 -6
- package/tansr-chunk-6OXR4F5Y.mjs +0 -67
- package/tansr-chunk-BCOFZJWA.mjs +0 -279
- package/tansr-chunk-BX7CF5RQ.mjs +0 -25
- package/tansr-chunk-F7C6ITED.mjs +0 -5
- package/tansr-chunk-H6JYYWPW.mjs +0 -35
- package/tansr-chunk-HRKJLVKC.mjs +0 -7
- package/tansr-chunk-I3TOVAA6.mjs +0 -5
- package/tansr-chunk-J2ED6CI4.mjs +0 -5
- package/tansr-chunk-KSBP64Q5.mjs +0 -12
- package/tansr-chunk-LSYPDTQG.mjs +0 -22
- package/tansr-chunk-MWHLITGY.mjs +0 -11
- package/tansr-chunk-NA22YT73.mjs +0 -5
- package/tansr-chunk-NCIMR6LB.mjs +0 -5
- package/tansr-chunk-OSK64SU3.mjs +0 -5
- package/tansr-chunk-Q6MUMULP.mjs +0 -5
- package/tansr-chunk-QEKVLX7W.mjs +0 -5
- package/tansr-chunk-QHEQQ2JB.mjs +0 -9
- package/tansr-chunk-QNHXB55W.mjs +0 -11
- package/tansr-chunk-QWGSXFEJ.mjs +0 -7
- package/tansr-chunk-SJFDQLLC.mjs +0 -5
- package/tansr-chunk-TYJWMSVW.mjs +0 -5
- package/tansr-chunk-TZJHQ3TT.mjs +0 -38
- package/tansr-chunk-UAEARRRH.mjs +0 -8
- package/tansr-chunk-WGXWBU37.mjs +0 -8
- package/tansr-chunk-ZQ3ZK7IL.mjs +0 -37
- package/tansr-main-5V46X7QH.mjs +0 -7
- package/tansr-render-PUEISX75.mjs +0 -6
- package/tansr-run-acp-entry-ANNUR7IB.mjs +0 -63
- package/tansr-run-approvals-entry-SLLTFTSX.mjs +0 -12
- package/tansr-run-doctor-RYIQQOOK.mjs +0 -10
- package/tansr-run-headless-entry-I53HJDNX.mjs +0 -78
- package/tansr-run-init-entry-USPWKDRI.mjs +0 -5
- package/tansr-run-logout-entry-KO7ZL2M5.mjs +0 -5
- package/tansr-run-mcp-serve-entry-YMQH7WSF.mjs +0 -14
- package/tansr-run-orchestrate-entry-YN3M6BWY.mjs +0 -11
- package/tansr-run-org-entry-STRRZVI4.mjs +0 -17
- package/tansr-run-policy-entry-4ENHRAMQ.mjs +0 -16
- package/tansr-run-profile-entry-THJMZ7ZA.mjs +0 -14
- package/tansr-run-serve-entry-N5PK7ACI.mjs +0 -99
- package/tansr-run-sessions-entry-KIT7PALM.mjs +0 -23
- package/tansr-run-update-entry-HYSKHBB6.mjs +0 -5
- package/tansr-sqlite-event-store-UQLSSZKP.mjs +0 -26
- package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +0 -29
- package/tansr-src-KOEPYVXX.mjs +0 -5
- package/tansr-startup-account-QUJKOV6V.mjs +0 -7
- package/tansr-tui-DXGFMSII.mjs +0 -75
package/tansr-tui-DXGFMSII.mjs
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import"./tansr-chunk-5VWLEU5D.mjs";import{a as Tt,b as vn}from"./tansr-chunk-E67N3BDI.mjs";import{a as Rc}from"./tansr-chunk-UCG4D6ER.mjs";import{a as Sc,c as kc,d as bc,f as He,g as wc,h as xc}from"./tansr-chunk-53SL6W6G.mjs";import{a as Oc,b as jc,c as Lc,d as Kc,e as Hc,f as Qc,g as Yc}from"./tansr-chunk-QNHXB55W.mjs";import{a as ce,b as Fc,c as Uc,d as Bc,e as Wc,f as Gc,g as $c,i as qc}from"./tansr-chunk-UAEARRRH.mjs";import{a as fo,b as go}from"./tansr-chunk-KSBP64Q5.mjs";import"./tansr-chunk-WW5ZPL6Q.mjs";import{v as zc,z as Vc}from"./tansr-chunk-OB47UYHK.mjs";import"./tansr-chunk-XAQNKJIC.mjs";import{a as f,b as mu}from"./tansr-chunk-RVSBSUXE.mjs";import{a as _t}from"./tansr-chunk-S3KHAGOR.mjs";import{$ as dt,D as Fi,H as Br,I as Et,J as Ui,V as Bi,X as Wi,Y as an,_ as Ke,b as de,fa as Gi,j as Fr,k as ji,l as Ur,q as Li,qa as dn,sa as cn,ua as Ki,x as Rt,y as qe}from"./tansr-chunk-CI7LFRTK.mjs";import{a as io,b as so,c as ao,d as co,e as lo,f as uo,g as mo,h as po}from"./tansr-chunk-J72JGEKH.mjs";import"./tansr-chunk-M774GK3P.mjs";import{$ as Qr,$a as ud,$b as eo,Ab as Nd,Bb as Od,D as sa,Da as za,Db as Ud,E as aa,Ea as Va,F as da,Fa as Ja,Fb as Zr,G as ca,Ga as Xa,Gb as Bd,H as la,Ha as Za,Hb as Wd,I as kn,Ia as ed,J as ua,Ja as td,Jb as _n,K as ma,Ka as nd,Kb as Gd,L as Ne,La as Rn,Lb as $d,M as pa,Ma as rd,Mb as qd,N as fa,Na as Mt,Nb as Kd,O as ga,Oa as od,P as ya,Pb as Hd,Qb as Qd,Rb as Yd,Sa as id,Sb as zd,T as bn,Ta as sd,Tb as Vd,U as ha,Ua as ad,Ub as Jd,V as va,Vb as Xd,W as Sa,Wa as dd,Wb as Zd,X as ka,Xb as ec,Y as ba,Yb as B,Z as wa,Za as cd,Zb as tc,_a as ld,a as Ks,aa as Ra,ab as zr,ac as nc,ba as Ea,ca as Ia,cc as An,d as Hs,da as Ta,db as md,dc as to,ea as Yr,eb as pd,ec as no,f as Qs,fa as Ca,fb as fd,fc as rc,g as Hr,ga as xa,gb as Vr,gc as oc,h as Js,ha as Ma,hb as gd,hc as ic,ia as _a,ib as yd,ic as Pn,ja as Aa,jb as Id,jc as sc,k as Xs,ka as La,kc as ac,lc as dc,m as Zs,ma as Fa,mb as Td,mc as cc,n as ea,na as Ua,nb as Jr,nc as lc,oa as Ba,ob as Cd,oc as uc,p as ta,pa as Wa,pc as mc,q as na,qa as Ga,qb as In,qc as yc,r as ra,ra as $a,rb as xd,rc as ro,sa as qa,sc as oo,t as oa,ta as Ka,tb as _d,tc as hc,u as ia,ua as Ha,vc,xa as Qa,xb as Ad,ya as Ya,yb as Pd,zb as Dd}from"./tansr-chunk-6OXR4F5Y.mjs";import{c as on,e as Ai,f as Pi,g as Di}from"./tansr-chunk-PIET7WB3.mjs";import{a as Pa,c as Da,d as Na,f as wn,g as Oa,j as ja}from"./tansr-chunk-S77B4PI7.mjs";import{e as hd,f as vd,g as Sd,k as kd,l as En,m as bd,n as wd,o as Rd,q as Ed}from"./tansr-chunk-NCIMR6LB.mjs";import{a as Sn,c as Ys}from"./tansr-chunk-Q6MUMULP.mjs";import"./tansr-chunk-QEKVLX7W.mjs";import{a as Mc,b as _c,c as Ac,d as Pc,e as Dc}from"./tansr-chunk-ZY3IR67Q.mjs";import{a as lt,d as Nc}from"./tansr-chunk-C6COFFZK.mjs";import"./tansr-chunk-NROI7AG5.mjs";import{l as Ec,m as Ic,n as Tc,o as Cc}from"./tansr-chunk-H6JYYWPW.mjs";import{a as U}from"./tansr-chunk-AMMPDY4V.mjs";import"./tansr-chunk-5T7X32UX.mjs";import"./tansr-chunk-726Y5F3M.mjs";import{a as Ct,h as Vs,j as xt,r as Cn,s as xn,t as jd,u as Ld,v as Xr,w as Fd,x as Mn}from"./tansr-chunk-WGXWBU37.mjs";import"./tansr-chunk-XXBNISJJ.mjs";import"./tansr-chunk-F5STVU7J.mjs";import{a as Tn}from"./tansr-chunk-2QKLANZQ.mjs";import{a as Gs,b as $s,c as fn,d as qs,e as gn,f as It,g as yn,h as hn,i as pc,k as fc,l as gc}from"./tansr-chunk-J2ED6CI4.mjs";import{D as Md,E as ct,x as zs}from"./tansr-chunk-LSYPDTQG.mjs";import{j as at,p as sn,s as Ni,v as Oi}from"./tansr-chunk-HRKJLVKC.mjs";import{$ as Ji,$a as ls,B as Hi,Ea as ns,Ee as _s,Fa as Wr,Fc as ks,Fe as As,Gd as Es,Ge as Ps,La as rs,M as Qi,Ne as Ds,Oa as os,Pa as is,Qe as Ns,Ra as Gr,Se as Os,Ub as fs,Va as ss,Xa as as,Xd as Is,Ya as ds,_ as Vi,_a as cs,aa as Xi,bf as js,ca as ln,cb as us,cc as gs,cd as bs,cf as G,da as Zi,db as ms,de as Ts,df as De,ef as Dn,hb as ps,ia as es,ja as un,jc as ys,jd as ws,kc as hs,kd as Rs,la as ts,lc as vs,ld as $r,qe as Cs,sc as Ss,se as xs,t as ve,te as Ms,ue as qr,xe as mn}from"./tansr-chunk-BCOFZJWA.mjs";import{a as Mi,b as _i}from"./tansr-chunk-C7GGA5ID.mjs";import{B as Bs,C as Kr,M as Ws,b as Ls,w as Fs,x as pn,y as Us}from"./tansr-chunk-2C6JKHKM.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-OSK64SU3.mjs";import{D as Yi,Ma as zi}from"./tansr-chunk-ZQ3ZK7IL.mjs";import"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import{d as nn,e as rn}from"./tansr-chunk-DIT3PBNB.mjs";import{e as _e,j as Ae,k as Pe,l as en,m as s,n as tn,o as wt}from"./tansr-chunk-NA22YT73.mjs";import{Fb as $i,Ib as qi}from"./tansr-chunk-QWGSXFEJ.mjs";import"./tansr-chunk-RRAMVVYF.mjs";import{randomUUID as bu}from"node:crypto";import{readFileSync as tl,statSync as wu}from"node:fs";import Ru from"node:os";import sl from"node:path";import{mkdirSync as pu,writeFileSync as fu}from"node:fs";import ho from"node:path";var yo=Ss,At=20,gu=[1,.7,.5,.35,.25];async function yu(){try{let t=await import("sharp"),r=t.default??t;return typeof r=="function"?r:null}catch{return null}}function hu(n=process.env){return ho.join(Sn(n),"image-cache")}var Nn=class{#r;#m;#o;#f=null;#i=0;#s=!1;constructor(t){let r=t.cacheRoot??hu();this.#r=ho.join(r,t.sessionId),this.#m=t.loadSharpImpl??yu,this.#o=t.onSharpMissing}get count(){return this.#i}async ingest(t,r){let i=Ur(t);if(i===null)return{ok:!1,error:"probe-failed",message:s(de.imageRejectedUnreadable,{path:r})};let a=t;if(a.length>yo){let l=await this.#P(a,i);if(l===null)return{ok:!1,error:"too-large",message:s(de.imageRejectedTooLarge,{size:_e(a.length),cap:_e(yo)})};if(a=l,i=Ur(a),i===null)return{ok:!1,error:"probe-failed",message:s(de.imageRejectedUnreadable,{path:r})}}this.#i+=1;let u=this.#i,d=ho.join(this.#r,`${u}.${ji(i.mime)}`);return this.#s||(pu(this.#r,{recursive:!0}),this.#s=!0),fu(d,a),{ok:!0,image:{id:u,mime:i.mime,width:i.width,height:i.height,bytes:a.length,cachePath:d,base64:a.toString("base64")}}}async#P(t,r){this.#f??=this.#m();let i=await this.#f;if(i===null)return this.#o?.(),null;for(let a of gu)try{let u=await i(t).resize({width:Math.max(1,Math.round(r.width*a)),height:Math.max(1,Math.round(r.height*a)),fit:"inside",withoutEnlargement:!0}).jpeg({quality:80}).toBuffer();if(u.length<=yo)return u}catch{return null}return null}};var Jc={phase:"idle",generation:0,turns:0};function ut(n){return n.phase==="closed"?n.inner:n}function Pt(n){return n.phase==="closed"?`closed(${n.inner.phase})`:n.phase}function vu(n){return n.kind==="reject"?`reject:${n.reason}`:n.kind==="carry"?`carry:${n.mode}${n.startTurn?"+start":""}`:n.kind}function Su(n,t){return t.effects.some(r=>r.kind==="reject")?"reject":t.effects.length===0&&t.next===n?"ignore":"transition"}var vo=n=>n.map(t=>({kind:t}));function Xc(n,t){let r=n.phase==="closed",i=r?n.inner:n,a=i.phase==="streaming"||i.phase==="aborting"||i.phase==="finishing",u=i.phase==="compacting"||i.phase==="compact_aborting",d={generation:i.generation,turns:i.turns},l={next:n,effects:[]},y=(...E)=>({next:n,effects:vo(E)}),c=(E,...R)=>({next:r?{phase:"closed",inner:E}:E,effects:vo(R)}),v=E=>({next:n,effects:[{kind:"reject",reason:E}]}),S={phase:"idle",...d},T={phase:"streaming",...d,turns:i.turns+1,turnGeneration:i.generation};switch(t.type){case"send":return r?l:i.phase==="finishing"?y("defer_send"):a?y("inject_user"):u?y("buffer_send"):c(T,"start_turn");case"agent_notification":return!r&&a?y("inject_agent"):!r&&i.phase==="idle"&&t.wakeIfIdle?c(T,"stash_agent","start_turn"):y("stash_agent");case"interrupt":return i.phase==="streaming"?c({...i,phase:"aborting"},"abort_turn"):a?y("abort_turn"):i.phase==="compacting"?c({phase:"compact_aborting",...d},"abort_compact"):u?y("abort_compact"):l;case"compact":return a?t.delegable?y("delegate_compact"):v("not_configured"):u?y("join_compact"):t.configured?t.historyEmpty?v("empty_history"):c({phase:"compacting",...d},"start_compact"):v("not_configured");case"replace_history":{let E=i.generation+1;return a?c({...i,phase:i.phase==="streaming"?"aborting":i.phase,generation:E},"abort_turn"):u?c({phase:"compact_aborting",...d,generation:E},"abort_compact"):c({phase:"idle",...d,generation:E})}case"close":{let E=i.phase==="streaming"?{...i,phase:"aborting"}:i.phase==="compacting"?{phase:"compact_aborting",...d}:i,R=[];return a&&R.push("abort_turn"),u&&R.push("abort_compact"),R.push("end_queue"),{next:{phase:"closed",inner:E},effects:vo(R)}}case"idle_op":return i.phase==="idle"?y("proceed"):v("turn_running");case"emergency_commit":return i.phase==="streaming"||i.phase==="aborting"?y("seal_turn"):l;case"turn_settled":return i.phase!=="streaming"&&i.phase!=="aborting"||i.turns!==t.turn?l:c({...i,phase:"finishing"},i.turnGeneration===i.generation&&!t.promptBlocked?"commit_turn":"discard_turn");case"turn_drained":{if(i.phase!=="finishing"||i.turns!==t.turn)return l;let E=i.turnGeneration===i.generation,R={kind:"carry",mode:E?"legacy":"crossed",startTurn:!r&&(E?t.allowLegacyCarry:!0)};return{next:r?{phase:"closed",inner:S}:S,effects:[{kind:"clear_turn"},R,{kind:"flush_deferred"}]}}case"turn_failed":return!a||i.turns!==t.turn?l:c(S,"clear_turn");case"compact_settled":return u?c(S,r?"drop_buffered":"flush_buffered"):l}}function Zc(n,t,r){return{from:Pt(n),input:t.type,to:Pt(r.next),effects:r.effects.map(vu),verdict:Su(n,r)}}function el(n){let t=`phase=${n.state} generation=${n.generation} turns=${n.turns}`;if(n.recentTransitions.length===0)return`${t}; transitions: none`;let r=n.recentTransitions.map(i=>`${i.input}:${i.from}>${i.to}[${i.effects.join(",")}]`).join(" ");return`${t}; transitions: ${r}`}var nl=64*1024,Eu=24,rl=/(^|\s)@([^\s@]+)/g,Iu=/[.,;:!?)"'\]]+$/,Dt=class{#r=dn();#m;#o;#f;#i;#s;#P;#G;#w;#g;#$;#q;#K;#S;#H;#l=Jc;#D=[];#C="";#N=null;#a;#Q;#Y;#O;#z;#x;#j;#V;#J;#X;#Z;#L;#ee;#ve;#k;#te;#R;#y;#F;#d;#p;#ne;#n;#u=null;#e=[];#h=[];#U=[];#Se=[];#re=[];#oe=!1;#ie=null;#E=new ds;#M=new Set;#v=null;#se=[];#B=[];#ae;#de;#ce;#le;#ke=null;#ue=new Map;#be=0;#we=0;#me=!1;constructor(t){this.#F=t.client,this.#m=t.executor,this.#o=t.cwd??process.cwd(),this.#f=t.rebindCwd,this.#i=t.system,this.#s=t.tools,this.#d=t.model,this.#p=t.contextWindowTokens,this.#ne=t.maxOutputTokens,this.#P=t.maxTokens??ln,this.#G=t.thinking,this.#w=t.sessionId??bu(),this.#g=new ls(this.#w),this.#$=t.onInputsConsumed,this.#q=t.maxTurnsPerQuery,this.#K=t.onEvent,this.#S=t.onHistoryCommit,this.#H=t.onEmergencyCommit,this.#a=t.compaction,this.#Q=t.compactionManagerOptions,this.#Y=t.transcriptHint,this.#O=t.reminders,this.#z=t.budget,this.#x=t.toolResultBudget,this.#j=t.queryHooks,this.#V=t.onTurnStart,this.#J=t.requestMeasurement,this.#X=t.onModelRequest,this.#Z=t.onTurnEnd,this.#L=t.onUserInput,this.#ee=t.onAgentInputsConsumed,this.#ve=t.runQueryImpl??as,this.#k=t.sessionCapture,this.#te=t.contextMaterials,this.#ae=t.imageInputModeResolver,this.#de=t.platformImageGate,this.#ce=t.imageCacheRoot,this.#le=t.loadSharpImpl,this.#R=t.sessionEvents,this.#y=t.checkpoints,this.#n=this.#Re()}#c(t){let r=Xc(this.#l,t);return this.#D.push(Zc(this.#l,t,r)),this.#D.length>Eu&&this.#D.shift(),this.#l=r.next,r.effects}#t(){return ut(this.#l).generation}#I(){return this.#l.phase==="closed"}#pe(t){for(let r of t)r.kind==="abort_turn"?this.#u?.abort():r.kind==="abort_compact"?this.#v?.ac.abort():r.kind==="end_queue"&&this.#r.end()}stateDiagnostics(){let t=ut(this.#l);return{state:Pt(this.#l),generation:t.generation,turns:t.turns,recentTransitions:[...this.#D]}}#Re(){if(this.#a===void 0||this.#p===void 0)return;let{manager:t,...r}=this.#a,i=cs({...r,observer:this.#Pe(r.observer)},this.#Q,{client:this.#F,contextWindowTokens:this.#p,...this.#Y!==void 0?{transcriptHint:this.#Y}:{}}),a=Ji(this.#O);return a!==void 0&&i.registerPostCompactInvalidation(a),i}#fe(t){let r=this.#n;this.#n=this.#Re(),!(r===void 0||this.#n===void 0)&&(t.carryAnchors&&this.#n.importAnchors(r.exportAnchors()),t.carryCalibration&&this.#n.importCalibration(r.exportCalibration()))}switchScheme(t,r){this.#a=t,this.#Q=r,this.#fe({carryAnchors:!0,carryCalibration:!0})}get events(){return this.#r.iterable}get sessionId(){return this.#w}send(t){this.sendWith(t)}getInputTarget(){return this.#g.getInputTarget()}inputCapabilities(){return this.#g.inputCapabilities()}getInputStatus(t,r){return this.#g.getInputStatus(t,r)}submitInput(t){let r=this.#g.submitInput(t);return r.then(i=>{i.outcome==="accepted"&&this.#b("onUserInput",()=>this.#L?.())},()=>{}),r}sendWith(t,r={}){this.#I()||(this.#L?.(),this.#Ee(t,r))}#Ee(t,r){let i=this.#Oe(t);if(i.length>0){this.#je(t,r,i);return}this.#_(this.#Me(t),r)}#_(t,r){this.#ge([t],r)}#ge(t,r){for(let i of this.#c({type:"send"}))switch(i.kind){case"defer_send":for(let a of t)this.#B.push({prompt:a,options:r,generation:this.#t()});break;case"inject_user":for(let a of t){let u=typeof a=="string"?a:a.text;this.#h.push({text:u,agent:!1,generation:this.#t()}),this.#u?.enqueueUserInput(u)}break;case"buffer_send":for(let a of t)this.#se.push({prompt:a,options:r,generation:this.#t()});break;case"start_turn":this.#Ne(t,r);break;default:break}}imageInputMode(){if(this.#ae!==void 0)return this.#ae(this.#d);let t=Fs(this.#d.provider,this.#d.model);return t===void 0?"unknown":pn(t.capability)}async ingestImage(t){if(this.imageInputMode()!=="supported")return{ok:!1,error:"unsupported",detail:s(de.imageRejectedUnsupported,{model:this.#d.model})};let r=await this.#xe(t);if(!r.ok)return{ok:!1,error:r.error,detail:r.message};this.#ue.set(r.image.id,r.image);let{base64:i,...a}=r.image;return{ok:!0,attachment:a}}sendWithImages(t){if(this.#I())return;this.#L?.();let r=this.#ue;this.#ue=new Map;let i=this.imageInputMode()==="supported",a=t.reduce((c,v)=>v.t==="image"&&r.get(v.id)!==void 0?c+1:c,0);if(i&&a>At){this.#Ce(a);return}let u=[],d=[],l=0;for(let c of t){if(c.t==="text"){if(c.text==="")continue;u.push({t:"text",text:c.text}),d.push(c.text);continue}let v=r.get(c.id);v!==void 0&&i&&(l+=1,u.push({t:"image",mime:v.mime,data:v.base64}),d.push(`
|
|
5
|
-
[image #${v.id}: ${sl.basename(v.cachePath)}]
|
|
6
|
-
`))}!i&&t.some(c=>c.t==="image")&&this.notify(s(de.imageRejectedUnsupported,{model:this.#d.model}));let y=d.join("");if(l===0){this.#Ee(y,{});return}this.#Ie(()=>{let c=this.#_e(y),v=c.length>0?`
|
|
7
|
-
|
|
8
|
-
${c.join(`
|
|
9
|
-
|
|
10
|
-
`)}`:"";v!==""&&u.push({t:"text",text:v}),this.#_({text:y+v,blocks:u},{})})}#Oe(t){let r=[],i=new Set;for(let a of t.matchAll(rl)){let u=a[2],d=il(u);if(d===void 0||!Fr.test(d.path))continue;let l=process.platform==="win32"?d.path.toLowerCase():d.path;i.has(l)||(i.add(l),r.push({token:u,path:d.path}))}return r}async#je(t,r,i){let a=[];if(this.imageInputMode()!=="supported")this.notify(s(de.imageRejectedUnsupported,{model:this.#d.model}));else if(i.length>At){this.#Ce(i.length);return}else for(let d of i){let l=await this.#xe(d.path);l.ok?a.push({t:"image",mime:l.image.mime,data:l.image.base64}):this.notify(l.message)}let u=this.#Me(t);if(a.length===0){this.#_(u,r);return}this.#Ie(()=>{this.#_({text:u,blocks:[{t:"text",text:u},...a]},r)})}#Ie(t){if(this.#u!==null||this.#de===void 0){t();return}let r;try{r=this.#de()}catch{r="unknown"}if(typeof r=="string"){r==="ok"?t():this.#Te(r);return}let i=this.#t();r.then(a=>a,()=>"unknown").then(a=>{this.#I()||i!==this.#t()||(a==="ok"?t():this.#Te(a))})}#Te(t){this.notify(s(t==="unavailable"?de.imageRejectedFeatureUnavailable:de.imageRejectedFeatureUnknown),"error"),this.#R?.record({kind:"image_feature_missing",origin:"platform",scope:"platform image-input",severity:"error",detail:t==="unavailable"?"platform features do not include image-input; send rejected as a whole":"platform image-input capability unknown (handshake pending/timed out); send rejected as a whole"})}#Ce(t){this.notify(s(de.imageRejectedTooMany,{count:t,max:At}),"error"),this.#R?.record({kind:"image_cap_exceeded",origin:"tui",scope:"image-input",detail:`${t} images in one message exceed cap ${At}; send rejected as a whole`})}async#xe(t){let r;try{r=tl(t)}catch{return{ok:!1,error:"read-failed",message:s(de.imageRejectedUnreadable,{path:t})}}return this.#ke??=new Nn({sessionId:this.#w,...this.#ce!==void 0?{cacheRoot:this.#ce}:{},...this.#le!==void 0?{loadSharpImpl:this.#le}:{},onSharpMissing:()=>{this.#R?.enter({kind:"degraded_mode",origin:"tui",scope:"image-downsample",detail:"sharp unavailable; oversized images are rejected instead of downscaled"})}}),this.#ke.ingest(r,t)}#Me(t){let r=this.#_e(t);return r.length>0?`${t}
|
|
11
|
-
|
|
12
|
-
${r.join(`
|
|
13
|
-
|
|
14
|
-
`)}`:t}#_e(t){let r=this.#n;if(r===void 0)return[];let i=new Set,a=[];for(let u of t.matchAll(rl)){let d=u[2],l=il(d);if(l===void 0||Fr.test(l.path))continue;let y=process.platform==="win32"?l.path.toLowerCase():l.path;if(i.has(y))continue;i.add(y);let c=r.attachmentStats.budgetBytes;if(l.size>c){this.notify(s(f.attachmentRejectedBudget,{path:d,used:_e(r.attachmentStats.injectedBytes),budget:_e(c)}));continue}let v;try{v=tl(l.path,"utf8")}catch{continue}if(v.includes("\0"))continue;let S=r.ingestAttachment({type:"file",sourceIdentity:l.path,content:v});S.kind==="inject"?a.push(Qi({type:"file",sourceIdentity:l.path,content:v})):S.kind==="reference"?a.push(S.referenceText):this.notify(s(f.attachmentRejectedBudget,{path:d,used:_e(S.usedBytes),budget:_e(S.budgetBytes)}))}return a}interrupt(){this.#pe(this.#c({type:"interrupt"}))}injectAgentNotification(t,r){let i="pending";for(let a of this.#c({type:"agent_notification",wakeIfIdle:r}))switch(a.kind){case"inject_agent":this.#h.push({text:t,agent:!0,generation:this.#t()}),this.#u?.enqueueUserInput(t),i="barrier";break;case"stash_agent":this.#U.push(t);break;case"start_turn":this.#Ne([]),i="wake";break;default:break}return i}setModel(t,r,i,a,u){this.#F=t,this.#d=r,this.#p=i,this.#ne=u,a!==void 0&&(this.#a=a),this.#fe({carryAnchors:!0,carryCalibration:!1})}setSystem(t){this.#i=t}currentModel(){return{...this.#d}}turns(){return ut(this.#l).turns}running(){let{phase:t}=ut(this.#l);return t==="streaming"||t==="aborting"||t==="finishing"}history(){return structuredClone(this.#e)}async emergencyCommit(t){let r=this.#u,i=this.#c({type:"emergency_commit"}).some(l=>l.kind==="seal_turn");if(r===null||!i)return{status:"idle"};let a={generation:this.#t(),turn:this.turns()};if(this.#N!==null&&this.#N.generation===a.generation&&this.#N.turn===a.turn)return{status:"already_sealed"};if(this.#H===void 0)return{status:"unwired"};this.#N=a;let u=Object.freeze(r.messages()),d={reason:t.reason,...t.reason==="signal"?{signal:t.signal}:{},at:new Date().toISOString(),turn:a.turn,...this.#C.length>0?{partialText:this.#C}:{}};try{return await this.#H(u,d),{status:"committed",turn:a.turn}}catch(l){return{status:"failed",error:l}}}#Le(t){if(t.length===0)return;let r=this.#C+t;this.#C=r.length>nl?r.slice(r.length-nl):r}#A(){return Object.freeze([...this.#e])}canReportContext(){return this.#n!==void 0}effectiveWindowTokens(){return this.#n?.thresholds.effectiveWindow}contextReport(){let t=this.#n;return t===void 0?void 0:{...t.assess({system:this.#i,messages:this.#e,tools:this.#s}),attachments:t.attachmentStats}}#ye(){return this.#a?.anchorLayer?.enabled===!0&&this.#n!==void 0}pinAnchor(t){if(!this.#ye())return{status:"disabled"};let r=this.#n.pinAnchor(t);return r===null?{status:"empty"}:{status:"pinned",entry:r.entry,duplicate:r.duplicate}}unpinAnchor(t){return this.#ye()?this.#n.unpinAnchor(t)?"removed":"not_found":"disabled"}listAnchors(){return this.#ye()?this.#n.anchors():"disabled"}preloadHistory(t){this.#e=t.map(i=>structuredClone(i));let r=this.#c({type:"replace_history"});this.#g.reset(),this.#pe(r),this.#fe({carryAnchors:!1,carryCalibration:!1})}resetHistory(){let t=this.#y;if(t!==void 0&&t.autoCheckpoint&&this.#e.length>0){let r=this.#e;t.write({trigger:"pre_clear",messages:r}).then(i=>this.#W(i)).catch(i=>{this.notify(s(f.checkpointAutoFailed,{trigger:"pre_clear",message:i instanceof Error?i.message:String(i)}),"error")})}this.preloadHistory([]),this.#S?.([],{rewritten:!1})}async compactNow(t){let r=this.#u,i=this.#a,a=this.#n,u=this.#c({type:"compact",delegable:r?.compactNow!==void 0,configured:i!==void 0&&a!==void 0,historyEmpty:this.#e.length===0});for(let d of u)switch(d.kind){case"delegate_compact":return r.compactNow(t);case"join_compact":return this.#v.promise;case"reject":if(d.reason!=="turn_running")return{status:"rejected",reason:d.reason};break;case"start_compact":return this.#Fe(i,a,t);default:break}throw new Error(`session-driver: compact_transition_no_outcome state=${Pt(this.#l)}`)}#Fe(t,r,i){this.pushEvent(Br({trigger:"manual"})),this.notify(s(f.compactStarted));let a=new AbortController,u=Date.now(),d=this.#E.register(r),l=this.#Ue(a,t,r,i).finally(()=>{d();let y=this.#c({type:"compact_settled"});this.#v=null,Date.now()-u>=3e4&&process.stdout.isTTY===!0&&process.env.TANSR_NO_BELL!=="1"&&process.stdout.write("\x07");let v=this.#se;if(this.#se=[],y.some(S=>S.kind==="flush_buffered")&&v.length>0){let S=v.filter(E=>E.generation===this.#t()),T=v.length-S.length;T>0&&this.notify(s(f.compactBufferedDropped,{count:T})),S.length>0&&this.#ge(S.map(E=>E.prompt),S[0]?.options??{})}});return this.#v={promise:l,ac:a},this.#E.track(l.then(()=>{})),l}async#Ue(t,r,i,a){let u=this.#t(),d=this.#k,l=this.#p,y=this.#e,c=()=>u===this.#t()&&!this.#I()&&!t.signal.aborted&&i===this.#n&&y===this.#e,v,S,T=!1,E=r.model??this.#d,R=d===void 0?void 0:i.assess({system:this.#i,messages:y,tools:this.#s});try{let h=this.#j?.([]),I=[];if(h?.preCompact!==void 0)try{let O=await h.preCompact({signal:t.signal,trigger:"manual",...a?.instructions!==void 0?{customInstructions:a.instructions}:{}});if(O.blocked===!0)return this.pushEvent({type:"turn.error",scope:"hooks",message:s(f.compactHookBlocked,{reason:O.blockReason??"-"}),recoverable:!0}),{status:"rejected",reason:"hook_blocked"};I=O.additionalContexts??[]}catch(O){this.pushEvent({type:"turn.error",scope:"hooks",message:O instanceof Error?O.message:String(O),recoverable:!0})}if(u!==this.#t())return this.pushEvent(Et({trigger:"manual"})),{status:"rejected",reason:"turn_ended"};let M=[...a?.instructions!==void 0?[a.instructions]:[],...I].filter(O=>O.trim().length>0),x=M.length>0?M.join(`
|
|
15
|
-
|
|
16
|
-
`):void 0;E=r.model??this.#d,d!==void 0&&(await d.awaitReady(t.signal),v=await zi({capture:d,messages:y,signal:t.signal,isCurrent:c,onPending:O=>this.#E.track(O.then(()=>{},()=>{}))}),v.assertSourceCurrent());let L=await i.compact({...v!==void 0?{publication:v,onUsage:O=>{S=O}}:{},view:{system:this.#i,messages:this.#e,tools:this.#s},model:E,trigger:"manual",signal:t.signal,...this.#y!==void 0&&a?.checkpoint!==!1?{beforeCompact:O=>this.#Ae(O,{trigger:"manual",...a?.checkpoint!==void 0?{checkpoint:a.checkpoint}:{}})}:{},maxTokens:Math.min(r.maxOutputTokens??2e4,i.thresholds.compactOutputBudget),...x!==void 0?{instructions:x}:{},...this.#x?.spill!==void 0?{spill:this.#x.spill}:{}});if(u!==this.#t()||d!==void 0&&!c()||!L.ok){let O=L.ok?L.compactionUsage:L.usage;for(let ne of un({messages:[],transform:{ops:[],...O!==void 0?{usage:O}:{}},usageAttribution:{model:E,contextWindowTokens:d===void 0?this.#p:l}}).events)this.pushEvent(ne);T=!0}if(u!==this.#t()||d!==void 0&&!c())return this.pushEvent(Et({trigger:"manual"})),{status:"rejected",reason:"turn_ended"};if(!L.ok)return this.pushEvent({type:"turn.error",scope:"compaction",message:L.message,recoverable:!0}),{status:"failed",outcome:L};let q=[...this.#e],pe=i.compactionObserver,Oe={messages:q,transform:{ops:[ts(L,this.#e)],...L.compactionUsage!==void 0?{usage:L.compactionUsage}:{},outcome:L,invalidations:"strategy"},usageAttribution:{model:E,...this.#p!==void 0?{contextWindowTokens:this.#p}:{}},...pe!==void 0?{observation:{observer:pe,trigger:"manual"}}:{}},je=v,Le;if(je===void 0)Le=un(Oe),this.#e=q.map(O=>structuredClone(O));else{let O=es({...Oe,afterPublishBeforeNotifications:()=>{this.#e=ne,je.accept()}}),ne=structuredClone([...O.nextMessages]);Le=O.commit(()=>(je.assertSourceCurrent(),c()))}T=!0;for(let O of Le.events)this.pushEvent(O);if(d===void 0?this.#S?.(this.#A(),{rewritten:!0}):this.#b("onHistoryCommit",()=>this.#S?.(this.#A(),{rewritten:!0})),h?.postCompact!==void 0)try{await h.postCompact({signal:t.signal,trigger:"manual",summaryText:L.summaryText,removedCount:L.removedIndices.length})}catch(O){this.pushEvent({type:"turn.error",scope:"hooks",message:O instanceof Error?O.message:String(O),recoverable:!0})}let K=L.removedIndices.length;return this.notify(s(f.compactBrief,{removed:K})),{status:"compacted",outcome:L,...L.checkpointId!==void 0?{checkpointId:L.checkpointId}:{}}}catch(h){if(d===void 0)throw h;if(!T&&S!==void 0)for(let M of un({messages:[],transform:{ops:[],usage:S},usageAttribution:{model:E,contextWindowTokens:d===void 0?this.#p:l}}).events)this.pushEvent(M);if(this.pushEvent(Et({trigger:"manual"})),!c())return{status:"rejected",reason:"turn_ended"};let I=h instanceof Error?h.message:String(h);return this.pushEvent({type:"turn.error",scope:"compaction",message:I,recoverable:!0}),{status:"failed",outcome:{ok:!1,reason:"before_compact_failed",message:I,trigger:"manual",measurementBefore:R.measurement,consecutiveAutoCompactFailures:R.consecutiveAutoCompactFailures,billingStatus:S===void 0?"not_sent":"reported",...S!==void 0?{usage:S}:{}}}}}#T(){return!this.#c({type:"idle_op"}).some(t=>t.kind==="proceed")}#W(t){this.pushEvent({type:"session.checkpointed",checkpointId:t.checkpointId,trigger:t.trigger,...t.label!==void 0?{label:t.label}:{},messageCount:t.messageCount})}async#Ae(t,r){let i=this.#y;if(i===void 0)return;let a=r.checkpoint;if(a===!1||a===void 0&&!i.autoCheckpoint)return;let u=typeof a=="object"?a.label:void 0,d=await i.write({trigger:"pre_compaction",...u!==void 0?{label:u}:{},messages:t.messages});return this.#W(d),{checkpointId:d.checkpointId}}async checkpoint(t={}){let r=this.#y;if(r===void 0)return{status:"rejected",reason:"not_configured"};if(this.#T())return{status:"rejected",reason:"turn_running"};if(this.#e.length===0)return{status:"rejected",reason:"empty_history"};try{let i=await r.write({trigger:"manual",...t.label!==void 0?{label:t.label}:{},messages:this.#e});return this.#W(i),{status:"saved",meta:i}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}async listCheckpoints(){return this.#y===void 0?[]:this.#y.list()}async restore(t){let r=this.#y;if(r===void 0)return{status:"rejected",reason:"not_configured"};if(this.#T())return{status:"rejected",reason:"turn_running"};let i;try{i=await r.read(t)}catch(y){return{status:"failed",message:y instanceof Error?y.message:String(y)}}if(i===null)return{status:"rejected",reason:"not_found"};if(this.#T())return{status:"rejected",reason:"turn_running"};let a=this.#e.length,u;if(r.autoCheckpoint&&a>0){try{let y=await r.write({trigger:"pre_restore",messages:this.#e});this.#W(y),u=y.checkpointId}catch(y){return{status:"failed",message:y instanceof Error?y.message:String(y)}}if(this.#T())return{status:"rejected",reason:"turn_running"}}let d=i.checkpoint.messages;this.preloadHistory(d),this.#S?.(this.#A(),{rewritten:!0}),this.pushEvent({type:"session.restored",checkpointId:t,fromMessages:a,toMessages:d.length});let l=i.checkpoint.cwd!==this.#o?{expected:i.checkpoint.cwd,actual:this.#o}:void 0;return{status:"restored",checkpointId:t,fromMessages:a,toMessages:d.length,...u!==void 0?{preRestoreCheckpointId:u}:{},...l!==void 0?{cwdMismatch:l}:{}}}cwd(){return this.#o}async setCwd(t){if(this.#T())return{status:"rejected",reason:"turn_running"};let r=this.#f;if(r===void 0)return{status:"rejected",reason:"not_configured"};let i=this.#o,a=await vn({requested:t,fallback:i,homedir:Ru.homedir()});if(!a.ok)return{status:"rejected",reason:a.reason};if(this.#T())return{status:"rejected",reason:"turn_running"};let u=a.cwd;return u===i?{status:"changed",from:i,to:u}:(this.#m=r(u,this.#m),this.#o=u,this.pushEvent({type:"session.cwd_changed",from:i,to:u}),{status:"changed",from:i,to:u})}async idle(){for(;;){let t=this.#ie??this.#v?.promise??null;if(t===null||(await t,(this.#ie??this.#v?.promise??null)===t))return}}async settleResources(){for(;this.#M.size>0||this.#v!==null;)await Promise.allSettled([...this.#M,...this.#v===null?[]:[this.#v.promise]]);this.#k!==void 0&&await this.#k.settle(),await this.#E.settle()}notify(t,r="info"){let i=r==="error"?"assembly":"assembly.notice";this.pushEvent({type:"turn.error",scope:i,message:t,recoverable:!0},"cli")}#Pe(t){return{onCompactionStarted:r=>{t?.onCompactionStarted?.(r),this.pushEvent(Br({trigger:r.trigger}))},onCompactionFinished:r=>{t?.onCompactionFinished?.(r),this.pushEvent(Et({trigger:r.trigger}))},...t?.onCompactionDeferred!==void 0?{onCompactionDeferred:r=>t.onCompactionDeferred?.(r)}:{},...t?.onMicrocompactApplied!==void 0?{onMicrocompactApplied:r=>t.onMicrocompactApplied?.(r)}:{},...t?.onToolResultsClamped!==void 0?{onToolResultsClamped:r=>t.onToolResultsClamped?.(r)}:{},...t?.onRequestMeasured!==void 0?{onRequestMeasured:r=>t.onRequestMeasured?.(r)}:{}}}pushEvent(t,r="cli"){let i={...t,sessionId:this.#w,seq:this.#be,ts:Date.now(),v:"v0",source:r};this.#be+=1,this.#De(i)}get callbackErrors(){return this.#we}#De(t){let r;if(this.#K!==void 0)try{this.#K(t)}catch(i){r={err:i}}this.#r.push(t),r!==void 0&&this.#he("onEvent",r.err)}#he(t,r){if(this.#we+=1,!(this.#me||this.#I())){this.#me=!0;try{this.pushEvent({type:"turn.error",scope:"assembly",message:s(f.driverCallbackFailed,{callback:t,message:ol(r)}),recoverable:!0,errorKind:"callback_error"},"cli")}finally{this.#me=!1}}}#b(t,r){try{r()}catch(i){this.#he(t,i)}}#Be(t){if(this.#j!==void 0)try{return this.#j(t)}catch(r){this.#he("queryHooks",r);return}}#We(t,r,i){this.#g.finish(t),this.#I()||this.pushEvent({type:"turn.error",scope:"assembly",message:s(f.driverPumpFailed,{message:ol(i)}),recoverable:!1,errorKind:"internal_error"},"cli");for(let a of this.#c({type:"turn_failed",turn:r}))a.kind==="clear_turn"&&this.#u===t&&(this.#u=null,this.#h=[],this.#B=[])}close(){this.#pe(this.#c({type:"close"}))}#Ne(t,r={}){let i=this.turns(),a=this.#t(),u=this.#U;this.#U=[],this.#Se=u;let d=t.map(M=>typeof M=="string"?M:M.text),l=this.#k===void 0?void 0:this.#e.length,y=[...this.#e,...t.map(M=>typeof M=="string"?{role:"user",blocks:[{t:"text",text:M}]}:{role:"user",blocks:M.blocks}),...u.map(M=>({role:"user",blocks:[{t:"text",text:M}]}))];if(this.#h=[],this.#re=[],this.#oe=!1,this.#C="",this.#V!==void 0){let M=this.#V;this.#b("onTurnStart",()=>M(i,d))}let c=r.model!==void 0?r.contextWindowTokens:this.#p,v=r.model!==void 0?r.maxOutputTokens:this.#ne,S=this.#Be(d),T=0,E=this.#t(),R=this.#ve({...this.#k!==void 0?{sessionCapture:this.#k,sessionCaptureInputStart:l}:{},...this.#te!==void 0?{contextMaterials:this.#te}:{},...this.#$===void 0?{}:{onInputsConsumed:M=>{if(E!==this.#t())return;let x=M.filter(L=>L.source==="strict"||this.#h[T++]?.agent===!1).map(L=>L.text);x.length>0&&this.#b("onInputsConsumed",()=>this.#$(x))}},client:r.client??this.#F,executor:this.#m,system:this.#i,tools:this.#s,model:r.model??this.#d,maxTokens:this.#P,...v!==void 0?{maxOutputTokens:v}:{},maxTokensEscalation:{ceilingTokens:Zi},...this.#G!==void 0?{thinking:this.#G}:{},sessionId:this.#w,initialMessages:y,...c!==void 0?{contextWindowTokens:c}:{},...this.#a!==void 0&&c!==void 0?{compaction:{...r.model===void 0&&this.#n!==void 0?{...this.#a,manager:this.#n}:{...this.#a,observer:this.#Pe(this.#a.observer)},...this.#y!==void 0&&this.#a.beforeCompact===void 0?{beforeCompact:(M,x)=>this.#Ae(M,x)}:{}}}:{},...this.#q!==void 0?{maxTurns:this.#q}:{},...this.#O!==void 0?{reminders:this.#O}:{},...this.#R!==void 0?{sessionEvents:this.#R}:{},...this.#z!==void 0?{budget:this.#z}:{},...this.#x!==void 0?{toolResultBudget:this.#x}:{},...S!==void 0?{hooks:S}:{},...this.#J!==void 0?{requestMeasurement:this.#J}:{},...this.#X!==void 0?{onModelRequest:this.#X}:{}});this.#u=R;for(let M of this.#h)R.enqueueUserInput(M.text);ut(this.#l).phase==="aborting"&&R.abort(),this.#g.bind(R);let h=this.#E.register(R),I=this.#Ge(R,a,i).catch(M=>this.#We(R,i,M)).finally(h);this.#ie=I,this.#E.track(I),this.#M.add(I),I.then(()=>{this.#M.delete(I)},()=>{this.#M.delete(I)})}async#Ge(t,r,i){let a=!0,u=!1,d=!1;try{for await(let l of t.events)(l.type==="turn.completed"||l.type==="turn.aborted")&&(a=l.reason==="completed"||l.reason==="structured_output"),l.type==="session.compacted"&&(u=!0),l.type==="turn.aborted"&&l.reason==="hook_stopped"&&(d=t.counters().modelTurns===0),l.type==="tool.proposed"&&this.#re.push(l.name),l.type==="turn.aborted"&&(this.#oe=!0),l.type==="msg.text.delta"&&this.#Le(l.text),this.#De(l)}finally{let l=this.#c({type:"turn_settled",turn:i,promptBlocked:d});this.#g.finish(t);let y=t.counters().queueInjections,c=this.#h.slice(0,y),v=this.#h.slice(y);if(l.some(S=>S.kind==="commit_turn")){if(this.#e=t.messages(),this.#S!==void 0){let T=this.#S;this.#b("onHistoryCommit",()=>T(this.#A(),{rewritten:u}))}let S=[...this.#Se,...c.filter(T=>T.agent).map(T=>T.text)];if(r===this.#t()&&S.length>0&&this.#ee!==void 0){let T=this.#ee;this.#b("onAgentInputsConsumed",()=>T(S))}if(r===this.#t()&&this.#Z!==void 0){let T=this.#Z,E={turn:i,history:this.#A(),toolNames:[...this.#re],aborted:this.#oe,system:this.#i};this.#b("onTurnEnd",()=>T(E))}}for(let S of this.#c({type:"turn_drained",turn:i,allowLegacyCarry:a}))switch(S.kind){case"clear_turn":this.#u===t&&(this.#u=null,this.#h=[]);break;case"carry":{let T=S.mode==="legacy"?v:v.filter(h=>h.generation>r),E=T.filter(h=>h.agent).map(h=>h.text),R=T.filter(h=>!h.agent).map(h=>h.text);E.length>0&&this.#U.unshift(...E),R.length>0&&S.startTurn&&this.#ge(R,{});break}case"flush_deferred":{let T=this.#B;this.#B=[];for(let E of T)E.generation===this.#t()&&this.#_(E.prompt,E.options);break}default:break}}}};function ol(n){let t=n instanceof Error?n.message:String(n);return $i(t).slice(0,400)}function il(n){let t=n.replace(Iu,""),r=t!==n&&t.length>0?[n,t]:[n];for(let i of r){let a=sl.resolve(i);try{let u=wu(a);if(u.isFile())return{path:a,size:u.size}}catch{}}}import{spawn as bm}from"node:child_process";import{randomUUID as wm}from"node:crypto";import{readFileSync as Rm}from"node:fs";import Al from"node:os";import Pl from"node:path";var Tu=1e4,Cu=Ic,xu=5e3;function al(n){let t=n.exit??(I=>{process.exit(I)}),r=!1,i=()=>{if(!r){r=!0;try{n.resetTerminal()}catch{}}},a=I=>{i(),t(I)},u=I=>{try{n.stderr.write(I.endsWith(`
|
|
17
|
-
`)?I:I+`
|
|
18
|
-
`)}catch{}},d=n.logger??{info:u,error:u,log:(I,M,x)=>{u(JSON.stringify({level:I,event:M,...x}))}},l={info:I=>{d.info(I)},error:I=>{i(),d.error(I)},...d.log!==void 0?{log:(I,M,x)=>{M.startsWith("process.")&&i(),d.log?.(I,M,x)}}:{}},y=()=>{},c=new Promise(I=>{y=I}),v=null,S=!1,T=I=>(I.reason==="fatal"&&(S=!0),v!==null||(v=(async()=>{try{await n.driver.emergencyCommit(I)}catch{}try{n.unmount()}catch{}await n.waitForShutdown()})().finally(y)),v),E=Cc(n.stderr,{log:(I,M)=>{i(),d.log!==void 0?d.log("warn",I,M):d.error(JSON.stringify({event:I,...M}))}}),R=Tc({hardExitAfterMs:n.hardExitAfterMs??Tu,hangupBudgetMs:n.hangupBudgetMs??Cu,...n.timers!==void 0?{timers:n.timers}:{},...n.now!==void 0?{now:n.now}:{},...n.signalSource!==void 0?{signalSource:n.signalSource}:{},drain:I=>T({reason:"signal",signal:I.signal}),exitCode:U.aborted,exit:a,onSecondSignal:I=>{i(),E.onSecondSignal(I)},onHardExit:E.onHardExit}),h=Ec({logger:l,onFatal:"drain-exit",drain:()=>T({reason:"fatal"}),drainTimeoutMs:n.fatalDrainTimeoutMs??xu,exit:a,...n.guardTarget!==void 0?{target:n.guardTarget}:{}});return{get signal(){return R.signal},settled:c,exitCode(I){return S?U.modelError:R.signal!==null?U.aborted:I},dispose(){R.dispose(),h()}}}function dl(n){let t=n.save??ga,r=n.initial,i=n.initial.status==="untrusted",a=()=>{i=!0,n.setMode(ma)},u=()=>s(Ne.untrustedBanner,{path:r.path}),d=async y=>{if(r.sessionOnly)return!1;try{return await t(n.storePath,n.cwd,y),!0}catch{return n.notify(s(Ne.storeWriteFailed,{path:r.path}),"error"),!1}},l=(y,c)=>{r={status:y?"trusted":"untrusted",path:r.path,sessionOnly:r.sessionOnly,...c?{source:r.path}:{}},n.emitEvent?.({trusted:y,persisted:c})};return{isUntrusted:()=>i,current:()=>r,needsDialog:()=>n.initial.status==="unknown",applyStartup(){n.initial.status==="untrusted"&&a()},bannerMessage:()=>i?u():null,async runDialog(y){let c=await y({path:r.path});if(c.decision==="trust"){let S=await d(!0);l(!0,S);return}a();let v=c.cancelled!==!0?await d(!1):!1;l(!1,v),n.notify(u())},async handleIntent(y){if(y==="status"){let v=Ne;r.status==="trusted"?n.notify(s(v.statusTrusted,{path:r.path,source:r.source??""})):r.status==="untrusted"?n.notify(s(v.statusUntrusted,{path:r.path})):n.notify(s(v.statusUnknown,{path:r.path}));return}if(y==="grant"){let v=await d(!0);l(!0,v),i=!1,n.setMode(n.configuredMode()),n.notify(s(v?Ne.granted:Ne.grantedSessionOnly,{path:r.path}));return}a();let c=await d(!1);l(!1,c),n.notify(s(c?Ne.revoked:Ne.revokedSessionOnly,{path:r.path}))}}}var Mu=3;function _u(n){if(n.channel==="report"){let t=n.wake===!0?' wake="true"':"";return[`<agent-notification channel="report" agent-id="${n.agentId}" notification-id="${n.notificationId}"${t}>`,n.message??"","</agent-notification>"].join(`
|
|
19
|
-
`)}return[`<agent-notification channel="settled" agent-id="${n.agentId}" notification-id="${n.notificationId}" outcome="${n.outcome??""}">`,n.summary??"","</agent-notification>"].join(`
|
|
20
|
-
`)}var On=class{#r;#m;#o=new Map;#f=0;constructor(t){this.#r=t,this.#m=t.maxConsecutiveWakes??Mu}async deliver(t){let r=Fc(t);await this.#r.sink.appendQueueEnqueue(r),this.#i(r)}redeliver(t){for(let r of t)this.#s(r.payload,!1);t.length>0&&this.#r.notify(s(f.agentNotificationsRedelivered,{count:t.length}))}noteUserInput(){this.#f=0}acknowledgeConsumed(t){for(let r of t){let i=this.#o.get(r);i!==void 0&&(this.#o.delete(r),this.#r.sink.appendQueueAck(i))}}pendingAckCount(){return this.#o.size}#i(t){if(!(t.channel==="report"&&t.wake===!0)||!this.#r.idleWakeEnabled()){this.#s(t,!1);return}if(this.#f>=this.#m){this.#s(t,!1)==="pending"&&this.#r.notify(s(f.agentWakeSuppressed,{agentId:t.agentId}));return}this.#s(t,!0)==="wake"&&(this.#f+=1)}#s(t,r){let i=_u(t);return this.#o.set(i,Uc(t)),this.#r.inject(i,r)}};import Pu from"node:os";import{readFileSync as Au}from"node:fs";function cl(n){let t=n.windowTokens!==void 0?`${n.name} (${qe(n.windowTokens)})`:n.name;return n.source!==void 0&&n.source!==""?`${t} [src:${n.source}]`:t}function jn(n){let t=f,r=` ${Li().sep} `,i=[];n.escapeLocal===!0?i.push(s(t.summaryLocalMode)):(n.identityLabel!==void 0&&n.identityLabel!==""&&i.push(s(t.summaryIdentity,{label:n.identityLabel})),n.identityOrg!==void 0&&n.identityOrg!==""&&i.push(s(t.summaryOrg,{org:n.identityOrg})),n.endpoint!==void 0&&n.endpoint!==""&&i.push(s(t.summaryEndpoint,{url:n.endpoint})));let a=[];n.mainModel!==void 0&&a.push(s(t.summaryModelMain,{model:cl(n.mainModel)})),n.fastModel!==void 0&&a.push(s(t.summaryModelFast,{model:cl(n.fastModel)}));let u=[];if(n.schemeName!==void 0&&n.schemeName!==""&&u.push(s(t.summaryScheme,{name:n.schemeName})),n.balance!==void 0){let d=n.balance.currency!==void 0&&n.balance.currency!==""?`${n.balance.amount} ${n.balance.currency}`:n.balance.amount;u.push(s(t.summaryBalance,{balance:d}))}return[i,a,u].filter(d=>d.length>0).map(d=>d.join(r))}function ll(n,t){let r=t!==void 0?at(n,t):at(n);if(r===null)return null;let i;try{i=JSON.parse(Au(r.whoamiFile,"utf8"))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let a=i,u=a.user,l=(Array.isArray(a.orgs)?a.orgs:[])[0],y=typeof l=="object"&&l!==null?l.name:void 0,c=typeof y=="string"&&y!==""?y:void 0;if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let v=u,S=typeof v.name=="string"&&v.name!==""?v.name:typeof v.email=="string"&&v.email!==""?v.email:typeof v.id=="string"&&v.id!==""?v.id:null;return S===null?null:c!==void 0?{label:S,org:c}:{label:S}}return c!==void 0?{label:c}:null}async function Ln(n){let t=lt,{env:r,notify:i}=n,a=process.platform,u=a==="win32"?Tn():void 0,d=sn(a),l=await Oi(Ni(r),{...u!==void 0?{cipher:u}:{},secretStore:d}),y=l.status==="ok"&&l.version===3?l.credentials:null,c=await n.askQuestion({prompt:y!==null?s(t.tuiReuseQuestion,{fingerprint:_c(y.pat)}):s(t.tuiPatQuestion),options:[{id:"web",label:s(t.tuiWebOption)},...y!==null?[{id:"reuse",label:s(t.tuiReuseOption)}]:[],{id:"new",label:s(t.tuiNewOption),textEntry:!0},{id:"cancel",label:s(t.tuiCancelOption)}],index:1,total:1});if(c.kind!=="answered"||c.selectedOptionIds.includes("cancel"))return i(s(t.cancelled)),!1;let v=c.freeText?.trim()??"",S,T=y?.derivedApp??null;if(v!=="")S=v;else if(c.selectedOptionIds.includes("web")){let I=await(n.webLoginImpl??Nc)({api:{baseUrl:ct(r)},env:r,clientName:`${Md} @ ${Pu.hostname()}`,notify:i});if(!I.ok)return!1;S=I.pat}else if(y!==null&&c.selectedOptionIds.includes("reuse"))S=y.pat;else return i(s(t.tuiPatEmpty),"error"),!1;if(!S.startsWith(Mc))return i(s(t.badPatShape),"error"),!1;i(s(t.tuiRunning));let E=await(n.performInitImpl??Pc)({pat:S,env:r,...u!==void 0?{cipher:u}:{},secretStore:d,platform:a,existingDerived:T,freezeIdentity:n.mode==="first-init"});if(!E.ok){let h=Ac(E.failure,r);return i(s(h.key,h.params),"error"),!1}i(Dc(E.summary,r).join(`
|
|
21
|
-
`));let R=jn({identityLabel:E.summary.ownerLabel,endpoint:rn(r),...E.summary.balance!==null?{balance:{amount:E.summary.balance,...E.summary.currency!==null?{currency:E.summary.currency}:{}}}:{}});return R.length>0&&i(R.join(`
|
|
22
|
-
`)),i(s(n.mode==="first-init"?t.doneAdopting:t.doneRestart)),!0}async function ul(n){let t=_t,{env:r,notify:i}=n,a=await n.askQuestion({prompt:s(t.tuiConfirmQuestion),options:[{id:"confirm",label:s(t.tuiConfirmOption)},{id:"cancel",label:s(t.tuiCancelOption)}],index:1,total:1});if(a.kind!=="answered"||!a.selectedOptionIds.includes("confirm"))return i(s(t.tuiCancelled)),!1;i(s(t.tuiRunning));let u=process.platform,d=u==="win32"?Tn():void 0,l=sn(u),y;try{y=await(n.performLogoutImpl??fo)({env:r,...d!==void 0?{cipher:d}:{},secretStore:l,onStep:c=>{c==="revoke"&&i(s(t.stepRevoke))}})}catch(c){let v=c.code??"unknown";return i(s(t.failLocalClear,{code:v}),"error"),!1}return y.existed?(i(go(y.summary,r).join(`
|
|
23
|
-
`)),i(s(t.tuiDoneRestart)),!0):(i(s(t.notLoggedIn)),!1)}import{mkdirSync as Du,readFileSync as Nu,writeFileSync as Ou}from"node:fs";import ju from"node:os";import So from"node:path";function me(n,t=ju.homedir()){let r=n.TANSR_CONFIG_DIR?.trim(),i=r!==void 0&&r!==""?r:So.join(t,_i);return So.join(i,Mi)}function Fn(n,t){let r={},i=null;try{i=Nu(n,"utf8")}catch{}if(i!==null)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))return"skipped_jsonc";r=d}catch{return"skipped_jsonc"}let a=r.ui,u=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};r.ui={...u,theme:t};try{return Du(So.dirname(n),{recursive:!0}),Ou(n,`${JSON.stringify(r,null,2)}
|
|
24
|
-
`,"utf8"),"persisted"}catch{return"failed"}}var Lu="uninitialized";function ml(n){return n.env.TANSR_STARTUP_PROBE!=="1"&&n.stdinIsTty&&n.stdoutIsTty&&!n.gate.escape&&!n.remoteEnabled}function pl(n){return{deferred:n.filter(t=>t.key===Xr.pruned),immediate:n.filter(t=>t.key!==Xr.pruned)}}function Fu(n){let{env:t,runtime:r,themeStore:i}=n,a=f,u=nn(t),d=dn(),l=0,y=(R,h="info")=>{d.push({type:"turn.error",scope:h==="error"?"assembly":"assembly.notice",message:R,recoverable:!0,sessionId:Lu,seq:l,ts:Date.now(),v:"v0",source:"cli"}),l+=1},c={send:()=>{y(s(a.uninitChatBlocked,{url:u}),"error")},interrupt:()=>{},events:d.iterable},v={sessionInfo:()=>({cwd:n.cwd}),availableLocales:()=>Ae(),themeInfo:()=>({current:i.current,available:Ke}),doctorChecks:()=>{let[R=0,h=0]=process.versions.node.split(".").map(Number),I=r.sources.filter(x=>x.status==="skipped"),M=r.diagnostics.filter(x=>x.severity==="error");return[{id:"node_version",ok:R>22||R===22&&h>=19,detail:`${process.version} (baseline >=22.19)`},{id:"config_sources",ok:I.length===0,detail:I.length===0?r.sources.map(x=>`${x.layer}=${x.status}`).join(" "):`skipped: ${I.map(x=>x.path??x.layer).join(", ")}`},{id:"config_diagnostics",ok:M.length===0,detail:r.diagnostics.length===0?"clean":`${M.length} error(s) / ${r.diagnostics.length} total`},{id:"platform_init",ok:!1,detail:`uninitialized origin=${r.providerOrigin} pruned=${r.localProviders.pruned??"none"} fix=/init`}]}},S=!1,T=async()=>{if(!S){S=!0;try{let R=n.initFlowImpl??Ln,h=!1;try{h=await R({env:t,askQuestion:n.askQuestion,notify:y,mode:"first-init"})}catch(I){y(s(lt.failNetwork,{code:I instanceof Error?I.name:"unknown"}),"error");return}h&&n.onInitialized()}finally{S=!1}}};return{driver:c,commandDeps:v,onCommandIntent:R=>{switch(R.type){case"init":{T();return}case"switch_theme":{let h=dt(R.theme);if(h===null){y(s(a.unknownTheme,{theme:R.theme,available:Ke.join(", ")}),"error");return}i.set(h);let I=Fn(me(t),h);y(I==="persisted"?s(a.themeSwitched,{theme:h}):s(a.themeSwitchedSessionOnly,{theme:h}));return}case"switch_locale":{let h=tn(R.locale);h!==void 0&&Ae().includes(h)?(h!==en()&&Pe(h),y(s(a.localeSwitched,{locale:h}))):y(s(a.unknownLocale,{locale:R.locale,available:Ae().join(", ")}),"error");return}default:y(s(a.uninitCommandUnavailable),"error")}},pushStartupGuidance:()=>{for(let R of n.startupNotices)y(s(R.key,R.params));y([s(a.uninitCardHeader),s(a.uninitCardInit,{url:u}),s(a.uninitCardEscape)].join(`
|
|
25
|
-
`))},close:()=>{d.end()}}}async function fl(n){let{runTui:t}=await import("./tansr-src-JAODAP53.mjs"),r=cn(),i=!1,a=null,u=Fu({env:n.env,cwd:n.cwd,themeStore:n.themeStore,runtime:n.runtime,startupNotices:n.startupNotices,askQuestion:l=>r.askQuestion(l),onInitialized:()=>{i=!0,a?.()}});u.pushStartupGuidance();let d=t({driver:u.driver,cwd:n.cwd,slashCommands:Rt,commandDeps:u.commandDeps,onCommandIntent:u.onCommandIntent,dialogs:r,theme:n.themeStore,renderOptions:{incremental:n.incremental},bannerLoginHint:!1,onQuit:()=>{u.close()}});return d.ok?(a=d.unmount,await d.waitUntilExit(),u.close(),i?{kind:"initialized"}:{kind:"quit"}):(u.close(),{kind:"mount_failed",message:d.error.message})}var gl="reset",Uu="keep";function yl(n){return async t=>{let r=s(t.kind==="total"?G.classifierBreakerTotal:G.classifierBreakerConsecutive),i=await n.askQuestion({prompt:`${r}
|
|
26
|
-
${s(f.breakerRecoveryQuestion)}`,options:[{id:gl,label:s(f.breakerRecoveryApprove)},{id:Uu,label:s(f.breakerRecoveryKeep)}],index:1,total:1});if(!(i.kind==="answered"&&i.selectedOptionIds.includes(gl))){n.notify(s(f.breakerRecoveryKept));return}let u=n.engine.getClassifierBreakerState();n.engine.resetClassifierBreaker();let d=n.auditTarget(),l=Zd({sessionId:d.sessionId,sessionDir:d.sessionDir,trip:t.kind,before:u,...n.now!==void 0?{now:n.now}:{}});n.notify(s(f.breakerResetDone)),l||n.notify(s(f.breakerAuditWriteFailed))}}import{mkdirSync as Bu,readFileSync as Wu,writeFileSync as Gu}from"node:fs";import $u from"node:path";function ko(n){let t=null;try{t=Wu(n,"utf8")}catch{return{}}try{let r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)?null:r}catch{return null}}function Nt(n,t){let r=n[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{}}function bo(n,t){try{return Bu($u.dirname(n),{recursive:!0}),Gu(n,`${JSON.stringify(t,null,2)}
|
|
27
|
-
`,"utf8"),"persisted"}catch{return"failed"}}function hl(n,t){let r=ko(n);return r===null?"skipped_jsonc":(r.context={...Nt(r,"context"),activeScheme:t},bo(n,r))}function vl(n,t,r){let i=ko(n);if(i===null)return"skipped_jsonc";let a=Nt(i,"context");return i.context={...a,schemes:{...Nt(a,"schemes"),[t]:r}},bo(n,i)}function Sl(n,t){let r=ko(n);if(r===null)return"skipped_jsonc";let i=Nt(r,"context"),a=Nt(i,"schemes");if(!(t in a))return"not_in_user_file";let{[t]:u,...d}=a;return r.context={...i,schemes:d},bo(n,r)}var qu=/^[A-Za-z][A-Za-z0-9_-]*$/,kl=new Set($s.map(n=>n.id));function Ku(n){if(n==="true")return!0;if(n==="false")return!1;let t=Number(n);return n.trim()!==""&&Number.isFinite(t)?t:n}function bl(n){let t=f,r=structuredClone(n.settings??{}),i=n.remote??null,a=()=>fn({settings:r,...i!==null?{remote:i}:{}}),u=a(),d=n.initialActive,l=n.notify,y=()=>{u=a()},c=()=>u.list().map(S=>S.id).join(", "),v=S=>{l(s(t.schemeUnknown,{id:S,available:c()}),"error")};return{list:()=>u.list().map(S=>({id:S.id,...S.displayName!==S.id?{displayName:S.displayName}:{},strategyId:S.strategyId,stage:S.stage,fingerprint:S.fingerprint,active:S.id===d.id,builtin:kl.has(S.id),...S.parentId!==void 0?{parentId:S.parentId}:{}})),active:()=>d,warning:()=>d.stage==="production"?null:{id:d.id,stage:d.stage},use(S){if(u.remoteSchemeLocked&&u.remoteSchemeId!==null&&S!==u.remoteSchemeId){l(s(t.schemeUseLockedRejected,{requested:S,id:u.remoteSchemeId}),"error");return}let T=u.get(S);if(T===void 0){v(S);return}if(T.id===d.id){l(s(t.schemeAlreadyActive,{id:S}));return}n.applyScheme(T),d=T;let E=hl(n.settingsPath,S);l(E==="persisted"?s(t.schemeSwitched,{id:S,fingerprint:T.fingerprint}):s(t.schemeSwitchedSessionOnly,{id:S}));let R=It(T);R!==null&&l(s(R.key,R.params))},add(S){let{id:T}=S;if(!qu.test(T)){l(s(t.schemeAddInvalidId,{id:T}),"error");return}if(u.has(T)){l(s(t.schemeAddExists,{id:T}),"error");return}let E=S.base??d.id,R=u.get(E);if(R===void 0){v(E);return}if(S.strategy!==void 0){if(hs(S.strategy)===void 0){l(s(t.schemeAddUnknownStrategy,{strategy:S.strategy,available:vs().join(", ")}),"error");return}if(S.strategy!==R.strategyId){l(s(t.schemeAddStrategyMismatch,{strategy:S.strategy,base:R.strategyId}),"error");return}}let h={};for(let[pe,Oe]of Object.entries(S.params))h[pe]=Ku(Oe);let I={...R.params,...h},M=Gs.safeParse(I);if(!M.success){let pe=M.error.issues[0];l(s(t.schemeAddInvalidParams,{id:T,reason:`${pe?.path.join(".")??""}: ${pe?.message??"invalid"}`}),"error");return}let x={stage:"experimental",origin:`derived:${R.id}`,parentId:R.id,params:M.data};r={...r,schemes:{...r.schemes??{},[T]:x}},y();let L=u.get(T),q=vl(n.settingsPath,T,x);l(q==="persisted"?s(t.schemeAdded,{id:T,fingerprint:L?.fingerprint??""}):s(t.schemeAddedSessionOnly,{id:T}))},remove(S){if(u.get(S)===void 0){v(S);return}if(kl.has(S)){l(s(t.schemeRemoveBuiltin,{id:S}),"error");return}if(S===u.remoteSchemeId){l(s(t.schemeRemoveRemote,{id:S}),"error");return}if(S===d.id){l(s(t.schemeRemoveActive,{id:S}),"error");return}let{[S]:E,...R}=r.schemes??{};r={...r,schemes:R},y();let h=Sl(n.settingsPath,S);l(h==="persisted"?s(t.schemeRemoved,{id:S}):s(t.schemeRemovedSessionOnly,{id:S}))},refreshRemote(S){let T=u.remoteSchemeId;i=S,y();let E=u.remoteSchemeId,R=E!==null?u.get(E):void 0;if(R===void 0)return;let h=T!==null&&d.id===T;if(!(d.id!==R.id||d.fingerprint!==R.fingerprint)){d=R;return}if(h||u.remoteSchemeLocked){let M=h?null:d.id;n.applyScheme(R),d=R,M!==null&&l(s(De.schemeOverrideRejected,{requested:M,id:R.id}),"error");let x=It(R);x!==null&&l(s(x.key,x.params))}}}}import{execFile as Hu}from"node:child_process";var Qu=5e3,Yu=4*1024*1024,zu=40;function wl(n,t){return new Promise((r,i)=>{Hu("git",[...t],{cwd:n,timeout:Qu,windowsHide:!0,maxBuffer:Yu},(a,u,d)=>{if(a!==null){let l=d.trim();i(new Error(l!==""?l.split(`
|
|
28
|
-
`)[0]??l:a.message));return}r(u)})})}function Vu(n,t){let r=n.split(`
|
|
29
|
-
`).map(u=>u.trimEnd()).filter(u=>u!=="");if(r.length===0)return[s(f.diffEmpty)];let i=[s(f.diffHeader)],a=r.slice(0,zu);return i.push(...a.map(u=>` ${u}`)),r.length>a.length&&i.push(s(f.diffTruncated,{shown:a.length,total:r.length})),t!==null&&t!==""&&i.push(` ${t}`),i}async function Rl(n){let t=await wl(n,["-c","core.quotepath=false","status","--porcelain"]),r=null;try{r=(await wl(n,["-c","core.quotepath=false","diff","--stat","HEAD","--"])).split(`
|
|
30
|
-
`).map(u=>u.trim()).filter(u=>u!=="").at(-1)??null}catch{}return Vu(t,r)}import{randomUUID as Ju}from"node:crypto";function Xu(n){return{sessionId:n.sessionId,updatedAt:n.updatedAt,cwd:n.cwd,...n.title!==void 0?{title:n.title}:{},...n.firstUserMessage!==void 0?{firstUserMessage:n.firstUserMessage}:{},...n.model!==void 0?{model:n.model}:{}}}async function wo(n,t){let r=t;if(r===void 0){let d=await Ys(n.storageRoot,{cwd:n.cwd,excludeSessionId:n.sink.currentSessionId()});if(d.length===0)return n.notify(s(ce.resumeNone)),!1;let l=await n.pickSession(d.map(Xu));if(l.kind!=="selected")return!1;r=l.session.sessionId}if(r===n.sink.currentSessionId())return n.notify(s(ce.resumeAlreadyCurrent,{sessionId:r})),!1;let i=await qc(n.storageRoot,r);if(!i.ok)return i.reason==="not_found"?n.notify(s(ce.resumeNotFound,{sessionId:r}),"error"):n.notify(s(ce.resumeFailed,{sessionId:r,message:i.detail}),"error"),!1;let a=n.todoStore!==void 0?await Kc(n.storageRoot,{messages:i.messages,...i.compactBoundary!==void 0?{compactBoundary:i.compactBoundary}:{}}):null,u=n.compactionLog!==void 0?await Bc(n.storageRoot,{attempts:i.compactionAttempts,...i.compactBoundary!==void 0?{compactBoundary:i.compactBoundary}:{}}):null;if(n.driver.preloadHistory(i.messages),n.replayTranscript?.(i.messages),n.todoStore?.replace(a??[]),u!==null&&n.compactionLog?.restore(u),i.continuable&&i.lock!==void 0)await n.sink.adoptSession({sessionId:i.sessionId,lock:i.lock,persistedCount:i.journalMessageCount,lastEventId:i.lastEventId,lastSeq:i.lastSeq,cursor:i.cursor}),n.onRestored?.(i.meta),n.notify(s(ce.resumeRestored,{sessionId:i.sessionId,count:i.messages.length}));else{let d=Ju();await n.sink.adoptFresh(d),n.onRestored?.(i.meta),n.notify(s(ce.resumeForked,{sessionId:d,count:i.messages.length}))}if(n.emitResumed?.({sessionId:i.sessionId,fromSeq:i.lastSeq}),n.sessionGrants!==void 0){let d=n.sessionGrants,l=Wc(i.sessionGrants,{...d.now!==void 0?{now:d.now}:{}});if(l.entries.length>0){for(let y of l.entries)d.record(y.rule,y.behavior);n.sink.appendPermissionRuntime(bd({entries:l.entries,skipped:l.skipped,...d.now!==void 0?{now:d.now}:{}})),n.notify(s(ce.resumeGrantsRestored,{count:l.entries.length,rules:Gc(l.entries)}))}}return n.sessionEvents!==void 0&&i.sessionEventConditions.length>0&&n.sessionEvents.restoreActiveConditions(i.sessionEventConditions),n.sessionEvents?.restoreModelProvenance?.(i.lastEffectiveModel),n.usageSnapshot!==void 0&&i.usageSnapshot!==void 0&&(n.usageSnapshot.adopt(i.usageSnapshot.payload.snapshot),i.usageSnapshot.staleMessages>0&&n.notify(s(ce.resumeUsageStale,{count:i.usageSnapshot.staleMessages}))),n.agentNotifications!==void 0&&i.pendingAgentNotifications.length>0&&n.agentNotifications.redeliver(i.pendingAgentNotifications),!0}function Zu(n){return{turn:n.turn,fileCount:n.files.length,capturedAt:n.capturedAt,...n.label!==void 0?{label:n.label}:{}}}function em(n){let t=[s(f.rewindDone,{turn:n.turn,restored:n.restored.length,deleted:n.deleted.length,skipped:n.skipped.length+n.failed.length})];for(let r of n.restored)t.push(s(f.rewindFileRestored,{path:r}));for(let r of n.deleted)t.push(s(f.rewindFileDeleted,{path:r}));for(let r of n.skipped)t.push(s(f.rewindFileSkipped,{path:r.path}));for(let r of n.failed)t.push(s(f.rewindFileFailed,{path:r.path,message:r.message}));return t}async function El(n){if(n.running())return n.notify(s(f.rewindBusy)),!1;let t=n.checkpoints.listRewindPoints();if(t.length===0)return n.notify(s(f.rewindNone)),!1;let r=await n.pickRewindPoint(t.map(Zu));if(r.kind!=="selected"||!(await n.confirmRewind({point:r.point,files:n.checkpoints.affectedFiles(r.point.turn)})).confirmed)return!1;if(n.running())return n.notify(s(f.rewindBusy)),!1;let a=await n.checkpoints.restoreToTurn(r.point.turn);return n.notify(em(a).join(`
|
|
31
|
-
`),a.failed.length>0?"error":"info"),a.failed.length===0}function Il(n){let t=n.ledger;if(t===void 0)return{wired:!1,commandDeps:()=>({}),statusSource:()=>({getSessionEventStickies:()=>[],getSessionEventInfo:()=>null}),restoreActiveConditions:()=>{},restoreModelProvenance:()=>{}};let r=Ki({emitNotice:(u,d)=>{n.pushEvent(Ui({level:u,text:d}))},...n.now!==void 0?{now:n.now}:{}}),i=n.journal,a=0;return t.setOnRecord((u,d)=>{if(i!==void 0&&a<512)try{let l=$c(u,d,n.wallClock);l!==null&&(a+=1,i.appendSessionEvent(l))}catch{}try{r.onRecord(u,d)}catch{}}),{wired:!0,commandDeps:()=>({sessionEvents:()=>t.snapshot()}),statusSource:()=>({getSessionEventStickies:()=>t.snapshot().activeConditions.map(u=>Fi(u.kind,u.scope)),getSessionEventInfo:()=>r.statusInfo()}),restoreActiveConditions:u=>{for(let d of u)t.enter({kind:d.kind,origin:d.origin,detail:"restored",...d.scope!==""?{scope:d.scope}:{}})},restoreModelProvenance:u=>{if(u===void 0||n.currentModel===void 0)return;let d=Ka(u,n.currentModel());d!==null&&t.record(d)}}}var Tl={action:"decline"};function nm(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(t.type!==void 0&&t.type!=="object")return null;let r=t.properties;if(typeof r!="object"||r===null||Array.isArray(r))return null;let i=Array.isArray(t.required)?new Set(t.required.filter(u=>typeof u=="string")):new Set,a=[];for(let[u,d]of Object.entries(r)){if(typeof d!="object"||d===null||Array.isArray(d))return null;let l=d,y=l.enum,c;if(Array.isArray(y)){if(y.length===0||!y.every(S=>typeof S=="string"))return null;c="enum"}else if(l.type==="string")c="string";else if(l.type==="number"||l.type==="integer")c="number";else if(l.type==="boolean")c="boolean";else return null;let v=l.default;a.push({name:u,fieldType:c,...typeof l.title=="string"?{title:l.title}:{},...typeof l.description=="string"?{description:l.description}:{},...i.has(u)?{required:!0}:{},...c==="enum"?{enumValues:y}:{},...typeof v=="string"||typeof v=="number"||typeof v=="boolean"?{defaultValue:v}:{}})}return a}function rm(n){if(n.mode==="url")return typeof n.url!="string"||n.url===""?null:{mode:"url",serverName:n.server,message:n.message,url:n.url};let t=nm(n.requestedSchema);return t===null?null:{mode:"form",serverName:n.server,message:n.message,fields:t}}function Ro(n){return async t=>{let r=rm(t);if(r===null)return Tl;let i=await n.requestElicitation(r);switch(i.kind){case"accepted":return{action:"accept",content:{...i.content}};case"declined":return Tl;case"cancelled":return{action:"cancel"}}}}import{mkdirSync as om,readFileSync as im,writeFileSync as sm}from"node:fs";import am from"node:path";function Eo(n,t,r,i){let a={},u=null;try{u=im(n,"utf8")}catch{}if(u!==null)try{let v=JSON.parse(u);if(typeof v!="object"||v===null||Array.isArray(v))return{outcome:"skipped_jsonc"};a=v}catch{return{outcome:"skipped_jsonc"}}let d=a.permissions,l=typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},y=l[t],c=Array.isArray(y)?y.filter(v=>typeof v=="string"):[];if(i==="add"){if(c.includes(r))return{outcome:"persisted",changed:!1};c.push(r)}else{let v=c.indexOf(r);if(v===-1)return{outcome:"persisted",changed:!1};c.splice(v,1)}a.permissions={...l,[t]:c};try{return om(am.dirname(n),{recursive:!0}),sm(n,`${JSON.stringify(a,null,2)}
|
|
32
|
-
`,"utf8"),{outcome:"persisted",changed:!0}}catch(v){return{outcome:"failed",message:v instanceof Error?v.message:String(v)}}}import{mkdirSync as dm,readFileSync as cm,writeFileSync as lm}from"node:fs";import um from"node:path";function Cl(n,t){let r={},i=null;try{i=cm(n,"utf8")}catch{}if(i!==null)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))return"skipped_jsonc";r=d}catch{return"skipped_jsonc"}let a=r.memory,u=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};r.memory={...u,autoMemory:t};try{return dm(um.dirname(n),{recursive:!0}),lm(n,`${JSON.stringify(r,null,2)}
|
|
33
|
-
`,"utf8"),"persisted"}catch{return"failed"}}import{mkdirSync as mm,readFileSync as pm,writeFileSync as fm}from"node:fs";import gm from"node:path";function Un(n,t,r){let i=n.find(u=>u.layer==="projectLocal");if(i?.path!==void 0)return{filePath:i.path,layer:"projectLocal"};let a=r!==void 0?at(t,r):at(t);return a!==null?{filePath:a.configFile,layer:"identity"}:{filePath:r!==void 0?me(t,r):me(t),layer:"user"}}function Io(n,t){let r={},i=null;try{i=pm(n,"utf8")}catch{}if(i!==null)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))return"skipped_jsonc";r=d}catch{return"skipped_jsonc"}let a=r.model,u=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};r.model={...u,selected:t};try{return mm(gm.dirname(n),{recursive:!0}),fm(n,`${JSON.stringify(r,null,2)}
|
|
34
|
-
`,"utf8"),"persisted"}catch{return"failed"}}import{mkdirSync as ym,readFileSync as hm,writeFileSync as vm}from"node:fs";import Sm from"node:path";var Qe={switchPersisted:"cli.window.switch.persisted",switchAlready:"cli.window.switch.already",switchJsonc:"cli.window.switch.jsonc",switchFailed:"cli.window.switch.failed",switchInvalid:"cli.window.switch.invalid",switchSingle:"cli.window.status.single",clampNotice:"cli.window.clamp.notice"};function km(n,t){let r=n.trim().toLowerCase();if(r==="")return;if(r==="max")return t[t.length-1];let i=/^(\d+(?:\.\d+)?)([km])?$/.exec(r);if(i===null)return;let a=Number(i[1]),u=i[2]==="m"?1e6:i[2]==="k"?1e3:1,d=a*u;if(!(!Number.isInteger(d)||d<=0)){for(let l of t)if(l===d)return l}}function Ml(n,t,r="CNY"){return n===void 0||!(n.inputPerMillion>0)?void 0:`≈${(t/1e6*n.inputPerMillion).toFixed(2)} ${r}`}function xl(n,t,r){let i={},a=null;try{a=hm(n,"utf8")}catch{}if(a!==null)try{let c=JSON.parse(a);if(typeof c!="object"||c===null||Array.isArray(c))return"skipped_jsonc";i=c}catch{return"skipped_jsonc"}let u=i.window,d=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},l=d.byModel,y=typeof l=="object"&&l!==null&&!Array.isArray(l)?l:{};i.window={...d,byModel:{...y,[t]:r}};try{return ym(Sm.dirname(n),{recursive:!0}),vm(n,`${JSON.stringify(i,null,2)}
|
|
35
|
-
`,"utf8"),"persisted"}catch{return"failed"}}function _l(n){let t={...n.initialByModel??{}},r=new Set,i=d=>{let l=Vr(d.capability.maxContext),y=t[d.modelName],c=gd(y,l);return{tiers:l,current:c.tier,source:c.source,preferred:c.source==="clamped"?y:void 0,effectiveCap:td(d.capability)}},a=(d,l)=>l.tiers.map((y,c)=>{let v=n.costText?.(d.modelName,y);return{tokens:y,isDefault:c===0,isCurrent:y===l.current,...v!==void 0?{costText:v}:{}}}),u=(d,l)=>{let y=qe(l);if(t[d]===l){n.notify(s(Qe.switchAlready,{model:d,tier:y}),"info");return}let c=xl(n.settingsFilePath,d,l);if(c==="failed"){n.notify(s(Qe.switchFailed,{path:n.settingsFilePath}),"error");return}if(t[d]=l,c==="skipped_jsonc"){n.notify(s(Qe.switchJsonc,{model:d,tokens:l,path:n.settingsFilePath}),"warning");return}n.notify(s(Qe.switchPersisted,{model:d,tier:y}),"info")};return{status(){let d=n.currentModel(),l=i(d);return{...d.alias!==void 0?{alias:d.alias}:{},model:d.modelName,current:l.current,source:l.source,...l.preferred!==void 0?{preferred:l.preferred}:{},declaredMax:d.capability.maxContext,effectiveCap:l.effectiveCap,tiers:a(d,l)}},select(d){let l=n.currentModel(),y=Vr(l.capability.maxContext);if(y.length===1){n.notify(s(Qe.switchSingle),"info");return}let c=km(d,y);if(c===void 0){n.notify(s(Qe.switchInvalid,{value:d,available:y.map(qe).join(" | ")}),"warning");return}u(l.modelName,c)},applyPickedTier(d,l){u(d,l)},announceClampOnce(){let d=n.currentModel();if(r.has(d.modelName))return;let l=i(d);if(l.source!=="clamped"||l.preferred===void 0)return;r.add(d.modelName),n.notify(s(Qe.clampNotice,{model:d.modelName,preferred:qe(l.preferred),tier:qe(l.current)}),"warning"),xl(n.settingsFilePath,d.modelName,l.current)==="persisted"&&(t[d.modelName]=l.current)},decorateModelChoices(d,l){return d.map(y=>{let c=l(y.target??y.alias);if(c===void 0)return y;let v=i(c);return{...y,window:{tiers:v.tiers.map(S=>{let T=n.costText?.(c.modelName,S);return{tokens:S,...T!==void 0?{costText:T}:{}}}),current:v.current,declaredMax:c.capability.maxContext}}})}}}var Em=200,Ot=ln;function Dl(n){let t={incremental:!1};for(let r=0;r<n.length;r++){let i=n[r],a=i,u,d=i.indexOf("=");if(i.startsWith("--")&&d!==-1&&(a=i.slice(0,d),u=i.slice(d+1)),a==="--incremental"){t.incremental=!0;continue}if(a==="--no-incremental"){t.incremental=!1;continue}if(a==="--resume"){if(u!==void 0){t.resume={sessionId:u};continue}let l=n[r+1];l!==void 0&&!l.startsWith("-")?(t.resume={sessionId:l},r++):t.resume={};continue}if(a==="--model"||a==="--lang"||a==="--theme"||a==="--context-scheme"||a==="--sessions-dir"||a==="--checkpoints-dir"||a==="--cwd"){let l;if(u!==void 0)l=u;else{let y=n[r+1];if(y===void 0||y.startsWith("-")&&y!=="-")return{ok:!1,key:Dn.missingValue,params:{flag:a}};l=y,r++}a==="--model"?t.model=l:a==="--theme"?t.theme=l:a==="--context-scheme"?t.contextScheme=l:a==="--sessions-dir"?t.sessionsDir=l:a==="--checkpoints-dir"?t.checkpointsDir=l:a==="--cwd"?t.cwd=l:t.lang=l;continue}return i.startsWith("-")?{ok:!1,key:Dn.unknownFlag,params:{flag:a}}:{ok:!1,key:Dn.unexpectedArg,params:{arg:i}}}return{ok:!0,args:t}}function Im(n){if(n.name!=="Write"&&n.name!=="Edit")return;let t=n.args,r=typeof t?.file_path=="string"?t.file_path:void 0;if(r!==void 0)try{return{exists:!0,currentText:Rm(r,"utf8")}}catch{return{exists:!1}}}function Tm(n,t){if(t.error!==void 0||t.notice!==void 0&&[De.defaultFallback,De.selectionInvalid,De.selectionPruned].includes(t.notice.key))return!0;try{return Kr(n,t.alias),!1}catch{return!0}}function Cm(n,t){if(n===void 0)return{ok:!0,themeName:t??an};let r=dt(n);return r===null?{ok:!1,theme:n}:{ok:!0,themeName:r}}function xm(n,t=setImmediate){t(()=>{n().catch(()=>{})})}async function Mm(n,t){let r=Dl(n);if(!r.ok)return process.stderr.write(s(r.key,r.params)+`
|
|
36
|
-
`),U.usage;let i=t??import("./tansr-src-JAODAP53.mjs").then(e=>({ok:!0,runtime:e}),e=>({ok:!1,error:e})),a=process.env,u=await vn({requested:r.args.cwd,fallback:process.cwd(),homedir:Al.homedir()});if(!u.ok)return Pe(wt({cliLang:r.args.lang,env:a})),process.stderr.write(s(u.key,u.params)+`
|
|
37
|
-
`),U.usage;let d=u.cwd,l=eo(d),y={lang:r.args.lang,theme:r.args.theme,model:r.args.model,contextScheme:r.args.contextScheme},c=await Mn({cwd:d,env:a,flagOverrides:Cn(y)}),v=xn(c.remoteSettings,y);Pe(wt({cliLang:v.lang,configLocale:c.loaded.locale,env:a}));let S=Cm(v.theme,c.loaded.ui?.theme);if(!S.ok)return process.stderr.write(s(f.unknownTheme,{theme:S.theme,available:Ke.join(", ")})+`
|
|
38
|
-
`),U.usage;let T=S.themeName,E=Gi(T),R=Ga(a),h=await Zr({env:a,sessionEvents:R,...c.loaded.network?.twpIdleTimeoutMs!==void 0?{twpIdleTimeoutMs:c.loaded.network.twpIdleTimeoutMs}:{}}),I=h.applyTo(c.registryConfig);if(I===null&&ml({env:a,gate:c.localProviders,remoteEnabled:h.enabled,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0})){let e=await fl({env:a,cwd:d,themeStore:E,runtime:c,startupNotices:h.notices,incremental:r.args.incremental});if(e.kind==="mount_failed")return process.stderr.write(e.message+`
|
|
39
|
-
`),U.usage;if(e.kind==="quit")return U.ok;l=eo(d),c=await Mn({cwd:d,env:a,flagOverrides:Cn(y)}),v=xn(c.remoteSettings,y),Pe(wt({cliLang:v.lang,configLocale:c.loaded.locale,env:a})),h=await Zr({env:a,sessionEvents:R,...c.loaded.network?.twpIdleTimeoutMs!==void 0?{twpIdleTimeoutMs:c.loaded.network.twpIdleTimeoutMs}:{}}),I=h.applyTo(c.registryConfig)}if(I===null){for(let o of h.notices)process.stderr.write(s(o.key,o.params)+`
|
|
40
|
-
`);let e=Fd({gate:c.localProviders,remoteEnabled:h.enabled,env:a});return process.stderr.write(s(e.key,e.params)+`
|
|
41
|
-
`),U.usage}let M=_n(I,h.governance),x=M.config,L=()=>Gd({...v.model!==void 0?{flag:v.model}:{},...c.modelSelection.selected!==void 0?{persisted:c.modelSelection.selected}:{},...c.modelSelection.layer!==void 0?{persistedLayer:c.modelSelection.layer}:{},projectPinnedMain:c.modelSelection.projectPinnedMain,config:x,review:M}),q=L(),pe=!1,Oe=()=>c.remoteSettings?.locks.some(e=>e==="model"||e==="model.selected")===!0,je=!1;if(v.model!==void 0)try{Kr(x,v.model)}catch{je=!0}if(h.enabled&&a.TANSR_STARTUP_PROBE!=="1"&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&Tm(x,q)){let{authorizedStartupChoices:e,runStartupModelTui:o}=await import("./tansr-startup-model-SREG5HNN.mjs"),{loadStartupAccount:p,runStartupAccountAction:g}=await import("./tansr-startup-account-QUJKOV6V.mjs"),b=await p({env:a,keyId:h.keyId}),k=()=>({account:b,choices:e(To(x,h.governance.models),x,M.authorizedHandles,Oe()?c.modelSelection.selected??"":void 0),notices:[...h.notices,...q.error!==void 0?[q.error]:q.notice!==void 0?[q.notice]:[],...je?[{key:G.unknownModel,params:{model:v.model??""}}]:[]]}),w=await o({env:a,cwd:d,themeStore:E,incremental:r.args.incremental,initial:k(),refresh:async P=>{if(await h.refreshStartup?.(P)!==!0||P.aborted)throw new Error("configuration_refresh_failed");if(c=await Mn({cwd:d,env:a,flagOverrides:Cn(y),remoteSettingsOverride:h.startupSettings?.()??null}),h.notices.push(...jd()),P.aborted)throw new Error("configuration_refresh_cancelled");if(v=xn(c.remoteSettings,y),Pe(wt({cliLang:v.lang,configLocale:c.loaded.locale,env:a})),E.set(dt(v.theme??c.loaded.ui?.theme??an)??an),I=h.applyTo(c.registryConfig),I===null)throw new Error("configuration_unavailable");return M=_n(I,h.governance),x=M.config,q=L(),je=!1,b=await p({env:a,keyId:h.keyId}),k()}}).catch(P=>{throw h.dispose?.(),P});if(w.kind==="quit")return h.dispose?.(),U.ok;if(w.kind==="mount_failed")return h.dispose?.(),process.stderr.write(w.message+`
|
|
42
|
-
`),U.usage;if(w.kind==="account")return g(w.action,{env:a,cwd:d,keyId:h.keyId,dispose:()=>h.dispose?.()});q={alias:w.alias},pe=!0}if(q.error!==void 0){h.dispose?.();for(let e of h.notices)process.stderr.write(s(e.key,e.params)+`
|
|
43
|
-
`);return process.stderr.write(s(q.error.key,q.error.params)+`
|
|
44
|
-
`),U.usage}let Le;try{Le=Hs({flags:{...r.args.sessionsDir!==void 0?{sessionsDir:r.args.sessionsDir}:{},...r.args.checkpointsDir!==void 0?{checkpointsDir:r.args.checkpointsDir}:{}},env:a,settings:c.loaded.storage,homedir:Al.homedir(),cwd:d})}catch(e){if(e instanceof Ks)return process.stderr.write(e.message+`
|
|
45
|
-
`),U.usage;throw e}let K=Qs(Le.sessionsDir),O=pl(h.notices);for(let e of O.immediate)process.stderr.write(s(e.key,e.params)+`
|
|
46
|
-
`);for(let e of M.notices)process.stderr.write(s(e.key,e.params)+`
|
|
47
|
-
`);let ne={...h.providerEnv!==null?{env:h.providerEnv}:{},...h.fetchImpl!==null?{fetchImpl:h.fetchImpl}:{},...h.twp!==null?{twp:h.twp}:{}},A=null,Wn=e=>{let o=Ws(e);o!==null&&A?.pushEvent(o,"provider");let p=qa(e);p!==null&&R.record(p)},Co=null,xo=null,Gn=Vd(),mt=Xd(),Se=Ls({onAttempt:e=>{mt.note(e),Co?.(e)}}).observer,$n=$d({notice:q.notice,modelSelection:c.modelSelection,config:x,sources:c.sources,env:a});$n!==void 0&&process.stderr.write(s($n.key,$n.params)+`
|
|
48
|
-
`);let Ye=q.alias,ke,_,ze;try{({client:ke,resolved:_,registry:ze}=xt(x,Ye,{onProviderSelected:Wn,attemptObserver:Se,...ne}))}catch(e){if(e instanceof Bs)return process.stderr.write(s(G.missingApiKey,{env:e.envVar??s(G.authEnvUnset)})+`
|
|
49
|
-
`),U.usage;if(e instanceof Us)return process.stderr.write(s(G.unknownModel,{model:Ye})+`
|
|
50
|
-
`),U.usage;throw e}if(pe&&!Oe()){let e=Un(c.sources,a);Io(e.filePath,Ye)!=="persisted"&&process.stderr.write(s(f.modelSelectionSessionOnly,{target:Ye})+`
|
|
51
|
-
`)}let H=yd(c.loaded.window?.byModel),qn=()=>h.enabled?{fastStrategy:{fallbackRefs:h.governance.fastFallbackGroup.map(e=>`tansr/${e}`)}}:{},z=Rn(x,_,{mainAlias:Ye,attemptObserver:Se,mainRunWindow:H(_.capability,_.modelName),...qn(),...ne}),Mo=e=>{let o=xt(x,e,{attemptObserver:Se,...ne});return{client:o.client,model:{provider:o.resolved.providerId,model:o.resolved.modelName}}},pt=fn({...c.loaded.context!==void 0?{settings:c.loaded.context}:{},...h.governance.contextScheme!==null?{remote:h.governance.contextScheme}:{}}),Fe=qs({registry:pt,...v.contextScheme!==void 0?{flagId:v.contextScheme}:{},...pt.remoteSchemeId!==null?{remoteId:pt.remoteSchemeId}:{},remoteLocked:pt.remoteSchemeLocked,...c.loaded.context!==void 0?{settings:c.loaded.context}:{}});if(!Fe.ok)return process.stderr.write(s(Fe.key,Fe.params)+`
|
|
52
|
-
`),U.usage;let V=Fe.scheme,be=gn(V,z.compaction),Nl=wn({env:a,policy:c.loaded.policy}),N=await dd({enabled:sd({settingValue:c.loaded.memory.autoMemory,scheme:V}),cwd:d,env:a});for(let e of N.warnings)process.stderr.write(s(e.key,e.params)+`
|
|
53
|
-
`);let he=wm(),Ve=Ye,D=_,Kn=ke,ee=z,re=await Nl,Hn={env:a,...c.loaded.permissions.classifierEnabled!==void 0?{configEnabled:c.loaded.permissions.classifierEnabled}:{},configGovernance:Cd(c.loaded.permissions),...z.fast!==void 0?{fast:z.fast}:{},stage2:{client:ke,model:{provider:_.providerId,model:_.modelName},..._.capability.sampling?.temperatureFixed!==void 0?{temperatureFixed:_.capability.sampling.temperatureFixed}:{}},liveStages:()=>({...ee.fast!==void 0?{fast:ee.fast}:{},stage2:{client:Kn,model:{provider:D.providerId,model:D.modelName},...D.capability.sampling?.temperatureFixed!==void 0?{temperatureFixed:D.capability.sampling.temperatureFixed}:{}}})},Je,ft,_o=re.anchor,Ol=xd({env:a,...re.anchor?.qualificationRemote!==void 0?{anchor:re.anchor.qualificationRemote}:{},...re.trustedKeys!==void 0?{trustedKeys:re.trustedKeys}:{}}),jl=_d({env:a,...re.anchor?.adjudicatorPool!==void 0?{anchor:re.anchor.adjudicatorPool}:{},...re.trustedKeys!==void 0?{trustedKeys:re.trustedKeys}:{}}),Ll=Pd({env:a}),[Ao,we,Po]=await Promise.all([Ol,jl,Ll]);h.setAdjudicatorPool(we.governance);let Do=Hr({adjudicator:h.governance.adjudicator,buildClient:Mo,pricing:h.pricingUpdates,platformHandles:h.governance.models.map(e=>e.handle),remoteAliases:h.governance.remoteAliases,...we.governance!==null?{pool:we.governance.entries}:{}});for(let e of Do.notices)process.stderr.write(s(e.key,e.params)+`
|
|
54
|
-
`);let jt=Do.remote,Qn=zs(),Lt=null,Fl={onRequestMeasured:e=>{Lt?.onRequestMeasured(e)}},{tierResolver:Ue,config:No,appointment:Re,evidence:Ee}=Ad({...Hn,remoteQualification:Ao,...we.governance!==null?{pool:we.governance.entries}:{},...Po!==void 0?{evaluationLedger:Po}:{},managedCeiling:()=>_o?.autoTierCeiling,override:()=>Je,requestMeasurement:Fl}),Yn=null,Be=No===void 0?void 0:{...No,rejectEffect:Id(!0),transcript:()=>Qn.transcript(),onBreakerTrip:e=>{if(Yn!==null){Yn(e);return}A?.notify(s(e.kind==="total"?G.classifierBreakerTotal:G.classifierBreakerConsecutive))},onBudgetExhausted:()=>A?.notify(s(G.classifierBudgetExhausted))},Ul=Be===void 0&&Jr(Hn),Ft=Da(c.loaded.permissions.defaultMode,re.anchor),Ut=Ft.mode,Oo=za({mode:Ut,env:a});if(Oo.kind==="refused")return process.stderr.write(s(G.bypassRootRefused)+`
|
|
55
|
-
`),U.usage;let jo=Va(a),Lo=Ut==="bypassPermissions"&&!await Ja(jo),Fo=lc({env:a,...c.loaded.audit!==void 0?{auditConfig:c.loaded.audit}:{}}),F=new ps({...Ut!==void 0&&!Lo?{mode:Ut}:{},layers:c.loaded.permissions.layers,baseline:{enabled:c.loaded.permissions.disableBaselineProtection!==!0},...Be!==void 0?{classifier:Be}:{},...Fo!==void 0?{hardSafety:Fo}:{},...N.setup!==null?{memoryWriteCarveOut:{dirs:[N.setup.dir]}}:{}}),zn=F.getMode(),oe=tc(a),ie=await l,J=[],Uo=null,Bo=(e,o,p)=>{e!==o&&Uo?.(kd({from:e,to:o,trigger:p}))},Wo=pa(a),se=dl({cwd:d,storePath:Wo,initial:ya(d,await fa(Wo)),configuredMode:()=>zn,setMode:e=>{let o=F.getMode();F.setMode(e),Bo(o,e,"workspace_trust")},notify:(e,o)=>A?.notify(e,o),emitEvent:({trusted:e,persisted:o})=>A?.pushEvent({type:"session.workspace_trust.changed",trusted:e,persisted:o},"trust")});se.applyStartup();let Bt=await ja(F,{env:a,trust:re,...c.loaded.permissions.recommendedRules!==void 0?{recommendedRules:c.loaded.permissions.recommendedRules}:{}});if(Bt.refuseLaunch){for(let e of Bt.notices)process.stderr.write(e.message+`
|
|
56
|
-
`);return process.stderr.write(s(Pa.refuseLaunch)+`
|
|
57
|
-
`),U.usage}let Bl=Ft.lockedMode!==void 0?[Na(Ft.lockedMode),...Bt.notices]:Bt.notices,gt=Sn(a),Go=Oa(re),$o=Ia(gt),ae=await Ma({cwd:d,env:a,reservedMcpNames:new Set(c.loaded.mcpServers.map(e=>e.name)),...Go!==void 0?{verify:Go}:{},projectTrust:{projectPath:d,records:await Ca($o)}}),Vn=js(c.loaded.hooks,ae.hooks),qo=()=>Ai(se.current(),{env:a}).enabled,Wt=Pi(qo);Wt.exempt(ae.hooks);let Jn=null,Ko=e=>{process.stderr.write(e+`
|
|
58
|
-
`)},Xn=()=>({id:V.id,fingerprint:V.fingerprint}),Zn=null,yt=Vs(h.pricingUpdates),er,Ho=c.loaded.usageReporting?.enabled!==!1,C=new Lc({storageRoot:K,sessionId:he,cwd:d,model:{provider:_.providerId,model:_.modelName},currentModel:()=>({provider:D.providerId,model:D.modelName}),startedAt:new Date().toISOString(),outputStyle:()=>er,platformSessionId:()=>h.platformSessionId(),...Ho?{}:{usageReportingDisabled:!0},onError:e=>A?.notify(e,"error"),...c.loaded.storage?.segmentation!==void 0?{segmentation:c.loaded.storage.segmentation}:{}});Uo=e=>C.appendPermissionRuntime(e);let tr=Ed(),Ie=La({surface:"tui",sessionId:he,currentSessionId:()=>C.currentSessionId(),cwd:d,sessionsRoot:K,env:a,loaded:c.loaded,engine:F,hooks:{config:Vn,trust:Wt,rebound:()=>Jn?.hookEngine()},budget:{section:c.loaded.budget,...yt!==void 0?{pricing:yt}:{},resolveProvider:()=>D.providerId,resolveReasoningTokens:ia(ze)},spill:!0,checkpoints:{paths:Le,volumeIds:()=>C.volumeIds(),cwd:()=>Jn?.cwd()??d,model:()=>({provider:D.providerId,model:D.modelName})},contextEvents:{scheme:()=>Xn(),mcp:()=>Zn?.meter()},decisions:{askTiming:e=>tr.consume(e)}},{emit:(e,o)=>A?.pushEvent(e,o),notify:e=>Ko(e)}),{audit:Gt,tracker:ht,budget:Qo,checkpoints:nr,toolResultBudget:rr,spill:Wl}=Ie,Gl=Ie.hooks.build,Yo=Ie.hooks.engine,$t=Ie.hooks.wiring,or=Di({wiring:$t,gate:Wt,projectEnabled:qo}),$l=qd({cwd:d,env:a,extraDirs:ae.skillDirs}),ql=ea({cwd:d,env:a,extraDirs:ae.agentDirs}),Kl=rs(d,on(a),{userDir:Wr(on(a),a),...N.setup!==null?{autoMemory:{dir:N.setup.readDir}}:{}}),Hl=yc({cwd:d,env:a}),[ir,Te,le,vt]=await Promise.all([$l,Kl,Hl,ql]);N.setup!==null&&ld(Te,N.setup);let zo=[...vc(le.diagnostics)],Ce=hc({env:a,...c.loaded.outputStyle!==void 0?{configName:c.loaded.outputStyle}:{},styles:le.styles}),fe=Ce.ok&&Ce.selection!==void 0?Ce.selection.style:le.styles[0];Ce.ok||zo.push({message:s(Ce.channel==="config"?G.unknownOutputStyleConfig:G.unknownOutputStyleEnv,{value:Ce.requested,expected:oo(le.styles)}),level:"error"});let sr=null,qt=e=>{let o=e.body!==void 0?{name:e.name,body:e.body}:void 0,p=Od(d,{memory:Te.segments,...N.setup!==null?{autoMemoryWriteGuidance:!0}:{},...N.setup!==null?{memoryInviteGuidance:!0}:{},skillsIndex:ir.indexSegment,...c.loaded.verify!==void 0?{verify:c.loaded.verify}:{},...o!==void 0?{outputStyle:o}:{}});return sr!==null&&p.push(sr),da(p)},te=qt(fe),ar=new Vi({onChange:e=>A?.pushEvent({type:"plan.todo.updated",items:e},"tool")}),$=cn(),dr=Qa({env:a,cwd:d,...c.loaded.sandbox!==void 0?{section:c.loaded.sandbox}:{}}),Vo=ks(a,c.loaded.semanticIndex),We=fd({autoMemory:N.setup,env:a,semanticIndex:c.loaded.semanticIndex,storageRoot:K,cwd:d,enabled:()=>od()!=="deny",currentSessionId:()=>C.currentSessionId()}),Jo=Bd({env:a,apiBaseUrl:ct(a),fetchImpl:h.fetchImpl,governance:h.governance}),Ql=Xs({env:a,apiBaseUrl:ct(a),fetchImpl:h.fetchImpl,governance:h.governance}),Yl=Wd({cwd:d,sessionId:()=>C.currentSessionId()}),Q=Zs({store:ar,channel:ed($),extraTools:[ir.tool,...Vo!==null?[Vo]:[],...We!==null?[We.tool]:[]],...dr!==void 0?{sandbox:dr.config}:{},...Jo!==void 0?{searchProvider:Jo}:{},mediaProviders:Ql,artifactSink:Yl,imageInput:()=>pn(D.capability),...Ts(c.loaded.http)}),zl=Ie.sessionArtifactWhitelist,cr=d,Xo=(e,o)=>Wa(F,Q.registry,{cwd:e,hooks:o,onNotice:p=>A?.notify(p),sessionEvents:R,sessionArtifactWhitelist:zl,...We!==null?{memorySearchRead:We.readPermission}:{},...N.setup!==null?{memoryReadWhitelist:Ha({dirs:cd(N.setup)})}:{}}),Ge=Xo(d,Yo),lr=async(e,o,p)=>{let g=Im(e),b=Date.now();tr.markRequested(e.id,b),C.appendPermissionRuntime(wd({callId:e.id,toolName:e.name}));let k=await $.requestPermission({toolCallId:e.id,toolName:e.name,args:e.args,cwd:cr,redactForDisplay:qi,...g!==void 0?{fileContext:g}:{},...p?.matchedRule!==void 0?{matchedRule:p.matchedRule}:{},...p?.sourceLayer!==void 0?{ruleSourceLayer:p.sourceLayer}:{},...p?.source==="classifier"&&p.reason!==void 0?{classifierReason:p.reason}:{},...p?.source==="builtin"&&p.reason!==void 0&&p.matchedRule?.startsWith(ms)===!0?{safetyReason:p.reason}:{},...p?.adjudication!==void 0?{adjudication:{...p.adjudication,...(()=>{let w=jt?.pool;return w!==void 0?{adjudicatorStatus:{evaluation:w.evaluation.status,origin:w.origin,tier:w.tier}}:{}})()}}:{}},o);if(tr.markDecided(e.id,Date.now()),C.appendPermissionRuntime(Rd({callId:e.id,toolName:e.name,decision:k.decision,scope:k.scope,...k.cancelled===!0?{cancelled:!0}:{},requestedAtMs:b})),(k.scope==="session"||k.scope==="repo")&&k.rules!==void 0){for(let w of k.rules)F.recordUserDecision(w,k.decision,cr);if(C.appendPermissionRuntime(En({rules:k.rules,behavior:k.decision,origin:"ask_dialog",scope:k.scope,toolName:e.name})),k.scope==="repo"&&k.decision==="allow")try{let w=await ac({file:oe,records:J,identity:ie,toolName:e.name,rules:k.rules});J=w.records,w.added>0&&A?.notify(s(B.recorded,{count:w.added}))}catch{A?.notify(s(B.writeFailed,{path:oe}),"error")}}return k.decision},Zo=null,ur=e=>Zo?.capture(e),Xe=cc(a,c.loaded.permissions.projectAskBudget),Ze=Xe.kind==="enabled"?new os({maxPrompts:Xe.maxPrompts,onExhausted:e=>A?.notify(s(f.projectAskBudgetExhausted,{count:e.promptCount}))}):void 0,et=Ie.decisions.onDecision,ei=null,ti=N.setup!==null?{dirs:[N.setup.dir],onWrite:e=>ei?.(e)}:void 0,ni=null,ri=null,tt=N.setup!==null?gs({dir:N.setup.readDir,roots:[d,N.setup.canonicalRoot],onRecall:e=>ni?.(e),onAdmission:e=>ri?.(e)}):void 0,oi=new ss({registry:Q.registry,cwd:d,permissionGate:Ge,askUser:lr,...Ze!==void 0?{projectAskBudget:Ze}:{},onDecision:et,captureFileCheckpoints:ur,...ti!==void 0?{memoryWrite:ti}:{},...tt!==void 0?{onFilesTouched:e=>tt.observeTouched(e)}:{}}),mr=Ya({cwd:d,hookEngine:Yo,gate:Ge,executor:oi},{buildHookEngine:Gl,buildGate:Xo,sandbox:dr});Jn=mr;let Vl=(e,o)=>{let p=mr.rebind(e,o);return cr=e,p.executor},ii=(e,o)=>{try{let p=ze.resolveAlias(e);return{provider:p.providerId,model:p.modelName}}catch{return o}},Kt=rd({env:a,models:()=>h.governance.models,registry:ze,crossProviderClient:{config:x,clientOptions:{attemptObserver:Se,...ne}}}),si=e=>{try{let o=ze.resolveAlias(`${e.provider}/${e.model}`);return H(o.capability,o.modelName)}catch{return}},ai={...be.query,...be.manager?.timeoutMs!==void 0?{timeoutMs:be.manager.timeoutMs}:{},restoreFileReader:Mt(),endpointHealthProbe:mt.probeFor(z.compactionBaseUrl),observer:{onCompactionStarted:e=>Me.onCompactionStarted?.(e),onCompactionFinished:e=>Me.onCompactionFinished?.(e),onMicrocompactApplied:e=>Me.onMicrocompactApplied?.(e),onToolResultsClamped:e=>Me.onToolResultsClamped?.(e),onRequestMeasured:e=>Me.onRequestMeasured?.(e)}},di=oa(c.loaded.budget,()=>ht.snapshot()),nt=Js({engine:F,env:a,askUser:lr,remote:()=>jt}),Ht=Fa(V),Jl=Ua(V),ci=()=>V,pr=()=>na(ci()),fr=null,ue=Ht?new bs({emit:e=>A?.pushEvent(e,"agent"),onNotification:async e=>{if(fr===null)throw new Error("agent notifications bridge unavailable before TUI assembly (ordering bug)");await fr(e)}}):void 0,gr=e=>{let o=Zn?.discoverToolFactory;if(o===void 0)throw new Error("McpDiscover subagent factory unavailable before MCP assembly (ordering bug)");return o(e)};ra(Q,{client:ke,system:()=>te,parentModel:{provider:_.providerId,model:_.modelName},maxTokens:Ot,sessionId:he,permissionGate:mr.forwardingGate,resolveModel:ii,...Kt!==void 0?{dispatchPolicy:Kt}:{},captureFileCheckpoints:ur,onDecision:et,mcpDiscover:gr,...nt!==void 0?{adjudication:nt}:{},compaction:ai,resolveContextWindow:si,toolResultBudget:rr,...Ht?{excludedTools:$r}:{},...ue!==void 0?{background:{runner:ue}}:{},concurrency:pr},vt);let li=[],Qt,Xl=e=>{(e.type==="turn.completed"||e.type==="turn.aborted")&&Gn.noteTurnFinal();let o=ht.consume(e);Gt?.consume(e),Qt?.noteEvent(e),e.type==="plan.todo.updated"&&(li=e.items);let p=Sc(o);p!==null&&A?.pushEvent(p,"cost")},rt=Ho&&h.enabled&&h.fetchImpl!==null?xc({env:a,apiBaseUrl:ct(a),fetchImpl:h.fetchImpl,directEndpoints:h.governance.directEndpoints,sessionId:()=>h.platformSessionId()??void 0,...h.keyId!==null?{profileKeyId:h.keyId}:{}}):null,W=Ie.contextEvents.writerFor;Co=e=>{W(C.currentSessionId()).observer.onProviderAttempt?.(e);let o=zd(e,Gn.current());o!==null&&C.appendRetryLedger(o),xo?.onAttempt(e)},Qt=Qd({env:a,schemeId:V.id})?Yd({sessionDir:()=>ve(K,C.currentSessionId()),onOutcome:e=>{e.kind==="mismatch"&&(A?.pushEvent({type:"turn.error",scope:Hd,message:s(f.contextAssertionMismatch,{index:e.diff.messageIndex,expected:e.diff.expected,actual:e.diff.actual}),recoverable:!0},"cli"),W(C.currentSessionId()).contextAssertion({outcome:"mismatch",messageIndex:e.diff.messageIndex,diffReason:e.diff.reason,expected:e.diff.expected,actual:e.diff.actual,comparedMessages:e.comparedMessages,rebuiltMessages:e.rebuiltMessages,actualMessages:e.actualMessages}))}}):void 0;let St=()=>{let e=ee.fast;return e!==void 0?{client:e.client,model:e.model,...e.thinkingOff===!0?{thinkingOff:!0}:{},...e.source!==void 0?{modelSource:e.source}:{}}:{client:Kn,model:{provider:D.providerId,model:D.modelName},modelSource:"main"}},ge=N.setup!==null?Rc({memoryDir:N.setup.dir,modelTier:St,engine:F,tools:Q.toolDefs,registry:Q.registry,permissionGate:Ge,sessionId:()=>C.currentSessionId(),cwd:d,balance:()=>h.balance(),tuning:{inviteGate:xs({section:c.loaded.memory,env:a}).mode,backpressureInterval:Ms(c.loaded.memory),extractionTruncation:qr(c.loaded.memory).enabled,truncationRecentRounds:qr(c.loaded.memory).recentRounds},onDecision:et,contextEvents:()=>W(C.currentSessionId()),mainModel:()=>{let e=A?.currentModel();return e!==void 0?`${e.provider}/${e.model}`:`${_.providerId}/${_.modelName}`},emitUsage:e=>A?.pushEvent(e,"cost"),onRequestMeasured:e=>Lt?.onRequestMeasured(e),notifyWriteBlocked:e=>{A!==null?A.notify(e):process.stderr.write(e+`
|
|
59
|
-
`)},notifySaved:e=>A?.notify(s(f.memoryExtractSaved,{count:e}))}):void 0,Yt=N.setup!==null?md({memoryDir:N.setup.dir,interactive:!0,modelTier:St,tools:Q.toolDefs,registry:Q.registry,permissionGate:Ge,sessionId:he,cwd:d,system:()=>te,balance:()=>h.balance(),onDecision:et,collectDecisionPatterns:()=>pd({storageRoot:K,cwd:d}),probeWrite:e=>W(C.currentSessionId()).memoryWrite({...e,source:"consolidate"}),onUsage:e=>{A?.pushEvent(mn(e),"cost")},requestMeasurement:{onRequestMeasured:e=>{Lt?.onRequestMeasured(e)}},notifyConsolidated:e=>A?.notify(s(f.memoryConsolidated,{count:e}))}):void 0,kt=N.setup!==null?_s({memoryDir:N.setup.readDir,projectAgentsPath:Pl.join(N.setup.canonicalRoot,"AGENTS.md"),userAgentsPath:Pl.join(Wr(on(a),a),"AGENTS.md"),modelTier:St,tools:Q.toolDefs,registry:Q.registry,permissionGate:Ge,askUser:lr,sessionId:he,cwd:d,system:()=>te,history:()=>A?.history()??[],onDecision:et,notifyReport:e=>A?.notify(e),onUsage:e=>{A?.pushEvent(mn(e),"cost")},probePromotion:e=>W(C.currentSessionId()).memoryPromotion(e),onOutcome:e=>{e.kind==="completed"?A?.notify(e.result.landedPaths.length>0?s(f.rememberDone,{count:e.result.landedPaths.length}):s(f.rememberNone)):e.kind==="failed"?A?.notify(s(f.rememberFailed,{reason:e.result.terminalReason}),"error"):e.kind==="crashed"&&A?.notify(s(f.rememberFailed,{reason:e.message}),"error")}}):void 0;ei=e=>{W(C.currentSessionId()).memoryWrite({...e,source:"main"}),ge?.noteMainMemoryWrite(),We?.noteMemoryFileWrite(e.path)},ni=e=>{W(C.currentSessionId()).memoryRecall(e)},ri=e=>{W(C.currentSessionId()).memoryRecallAdmission?.(e)};let yr=ad({autoMemoryEnabled:N.setup!==null,scheme:V}),xe=N.setup!==null&&yr!==null?ys({dir:N.setup.readDir,modelTier:St,budgets:yr,excludeFiles:[...id],onSelection:e=>W(C.currentSessionId()).memorySelection(e),onAdmission:e=>W(C.currentSessionId()).memoryRecallAdmission?.(e),onRecall:e=>W(C.currentSessionId()).memoryRecall({...e,source:"selector"}),onUsage:(e,o)=>{A?.pushEvent(mn({model:o.model,provider:o.provider,usage:e}),"cost")}}):void 0;if(N.setup!==null){let e=Te.segments.find(o=>o.scope==="auto-memory");W(C.currentSessionId()).memoryInjected({indexPath:N.setup.indexPath,present:e!==void 0,bytes:e!==void 0?Buffer.byteLength(e.content,"utf8"):0,lines:e!==void 0?e.content.split(`
|
|
60
|
-
`).length:0,truncated:Te.warnings.some(o=>o.startsWith("auto_memory_truncated"))})}let hr=()=>{try{return Xn()}catch{return}},vr=hd({scheme:()=>hr()}),Sr,Me={onCompactionStarted:e=>{W(C.currentSessionId()).observer.onCompactionStarted?.(e),C.appendCompactionAttempt(vd(e,hr()))},onCompactionFinished:e=>{let o=e.outcome;e.agentId===void 0&&e.mechanism===void 0&&o?.ok===!0&&(ge?.noteCompactionSummary(o.summaryText),We?.noteCompactionSummary({sessionId:C.currentSessionId(),compactionId:e.compactionId,summaryText:o.summaryText})),(o!==void 0?o.ok:e.foldedRemovedCount!==void 0)&&e.agentId===void 0&&(Sr={compactionId:e.compactionId,trigger:e.trigger,...o!==void 0&&o.ok?{beforeTokens:o.measurementBefore.contextTokens,afterTokens:o.measurementAfter.contextTokens}:{},...o!==void 0&&o.checkpointId!==void 0?{checkpointId:o.checkpointId}:{}}),W(C.currentSessionId()).observer.onCompactionFinished?.(e),C.appendCompactionAttempt(Sd(e,hr())),vr.observer.onCompactionFinished?.(e)},onMicrocompactApplied:e=>{W(C.currentSessionId()).observer.onMicrocompactApplied?.(e)},onToolResultsClamped:e=>{W(C.currentSessionId()).observer.onToolResultsClamped?.(e)},onRequestMeasured:e=>{W(C.currentSessionId()).observer.onRequestMeasured?.(e),rt?.onRequestMeasured(e)}},kr={onRequestMeasured:e=>{W(C.currentSessionId()).observer.onRequestMeasured?.(e),rt?.onRequestMeasured(e)}};Lt=kr,Yn=yl({engine:F,askQuestion:e=>$.askQuestion(e),notify:e=>A?.notify(e),auditTarget:()=>{let e=C.currentSessionId();return{sessionId:e,sessionDir:ve(K,e)}}});let br=new Hc({storageRoot:gt,appendRecord:e=>C.appendFileCheckpoint(e),currentTurn:()=>A?.turns()??0,onError:e=>A?.notify(e,"error")});Zo=br;let wr=Yc({storageRoot:K,currentSessionId:()=>C.currentSessionId(),modelTier:()=>ee.fast,onUsage:(e,o)=>{A?.pushEvent(Qc(o,e),"cost")},requestMeasurement:kr}),zt=fc({env:a,...c.loaded.effort!==void 0?{configLevel:c.loaded.effort}:{}}),Rr=zt.selection!==void 0?gc(zt.selection,Ot,{..._.capability.thinking.budgetMaxTokens!==void 0?{thinkingBudgetMaxTokens:_.capability.thinking.budgetMaxTokens}:{}}):void 0,bt,ye,m=new Dt({client:ke,executor:oi,system:te,tools:Q.toolDefs,model:{provider:_.providerId,model:_.modelName},contextWindowTokens:H(_.capability,_.modelName),..._.capability.maxOutput!==void 0?{maxOutputTokens:_.capability.maxOutput}:{},maxTokens:Rr?.maxTokens??Ot,...Rr?.thinking!==void 0?{thinking:Rr.thinking}:{},sessionId:he,maxTurnsPerQuery:Em,platformImageGate:()=>D.providerProfile.protocol==="twp"?h.imageFeatureVerdict():"ok",sessionEvents:R,checkpoints:nr,cwd:d,rebindCwd:Vl,onEvent:Xl,onHistoryCommit:(e,o)=>{let p=o.rewritten?Sr:void 0;Sr=void 0,!o.rewritten&&e.length===0&&xe?.resetEpoch(),C.commitHistory(e,{...o,...p!==void 0?{compaction:p}:{}});let g=di.takePayload();g!==void 0&&C.appendUsageSnapshot(g),wr.maybeGenerate(e)},onEmergencyCommit:(e,o)=>C.commitEmergency(e,o),compaction:{...be.query,observer:Me,restoreFileReader:Mt(),endpointHealthProbe:mt.probeFor(z.compactionBaseUrl)},...be.manager!==void 0?{compactionManagerOptions:be.manager}:{},transcriptHint:()=>ve(K,C.currentSessionId()),reminders:Xi({todoStore:ar,memoryPaths:ud(Te),...tt!==void 0?{drainMemoryRecalls:()=>tt.drainReminderEntries?.()??tt.drainReminders()}:{},...xe!==void 0?{drainMemorySelections:()=>xe.drainReminderEntries?.()??xe.drainReminders()}:{}}),...Qo!==void 0?{budget:Qo}:{},toolResultBudget:rr,queryHooks:$t.queryHooks,onInputsConsumed:e=>{Qn.noteInput(e),xe?.supplement?.(e.join(`
|
|
61
|
-
|
|
62
|
-
`))},onTurnStart:(e,o)=>{Gn.noteTurnStart(e),br.noteTurn(e,o[0]),Qn.noteTurn(o),ge?.noteTurnStart(),xe?.prefetch(o.join(`
|
|
63
|
-
|
|
64
|
-
`))},requestMeasurement:kr,...Qt!==void 0?{onModelRequest:e=>{Qt?.observeRequest(e.messages)}}:{},...ge!==void 0?{onTurnEnd:e=>{ge.noteInviteParse(As(Ps(e.history)),e.turn),ge.handleTurnEnd(e)}}:{},...Ht?{onUserInput:()=>bt?.noteUserInput(),onAgentInputsConsumed:e=>bt?.acknowledgeConsumed(e)}:{}});if(A=m,Ko=e=>m.notify(e),xo=Jd({pushEvent:e=>m.pushEvent(e)}),Ht){let e=new On({sink:C,inject:(p,g)=>m.injectAgentNotification(p,g),notify:(p,g)=>m.notify(p,g),idleWakeEnabled:()=>Jl});bt=e,fr=p=>e.deliver(p);let o=new Rs({client:ke,model:{provider:_.providerId,model:_.modelName},maxTokens:Ot,sessionId:he,permissionGate:Ge,cwd:d,contextWindowTokens:H(_.capability,_.modelName),emit:p=>m.pushEvent(p,"agent"),onNotification:p=>e.deliver(p),spill:Wl});ye=o,Ba(Q,{manager:o,client:ke,parentModel:{provider:_.providerId,model:_.modelName},system:()=>te,agents:vt.agents,mcpDiscover:gr,...nt!==void 0?{adjudication:nt}:{},nestedTask:{client:ke,system:()=>te,parentModel:{provider:_.providerId,model:_.modelName},maxTokens:Ot,sessionId:he,permissionGate:Ge,cwd:d,resolveModel:ii,...Kt!==void 0?{dispatchPolicy:Kt}:{},captureFileCheckpoints:ur,onDecision:et,mcpDiscover:gr,...nt!==void 0?{adjudication:nt}:{},compaction:ai,resolveContextWindow:si,toolResultBudget:rr,agents:vt.agents,excludedTools:$r}})}Yt?.start(),We?.syncStartup();for(let e of O.deferred)m.notify(s(e.key,e.params));for(let e of[...Bl,...ta(vt.diagnostics),...ae.notices,...zo])m.notify(e.message,e.level);h.setWarningListener(e=>{m.notify(s(e.key,e.params)),e.key===De.platformWarning&&e.params?.code==="balance_low"&&(ge?.noteBalanceLow(),Yt?.noteBalanceLow())});let ui=se.bannerMessage();ui!==null&&m.notify(ui),zt.invalidEnvValue!==void 0&&m.notify(s(G.invalidEffortEnv,{value:zt.invalidEnvValue,expected:pc.join("|")})),Ul&&m.notify(s(G.classifierFastMissing));for(let e of pt.diagnostics)m.notify(s(e.key,e.params));Fe.notice!==void 0&&m.notify(s(Fe.notice.key,Fe.notice.params));let Er=It(V);Er!==null&&m.notify(s(Er.key,Er.params)),z.fast!==void 0&&nd(z,{provider:_.providerId,model:_.modelName})&&m.notify(s(G.compactionOnMainModel,{fast:`${z.fast.model.provider}/${z.fast.model.model}`,main:`${_.providerId}/${_.modelName}`}));let Ir=yn(V,be.query,H(_.capability,_.modelName));Ir!==null&&m.notify(s(Ir.key,Ir.params));let Tr=hn(V,be.query,H(_.capability,_.modelName));Tr!==null&&m.notify(s(Tr.key,Tr.params));let Zl=e=>{let o=Rn(x,D,{mainAlias:Ve,attemptObserver:Se,mainRunWindow:H(D.capability,D.modelName),...qn(),...ne});ee=o;let p=gn(e,o.compaction);m.switchScheme({...p.query,observer:Me,restoreFileReader:Mt(),endpointHealthProbe:mt.probeFor(o.compactionBaseUrl)},p.manager);let g=yn(e,p.query,H(D.capability,D.modelName));g!==null&&m.notify(s(g.key,g.params));let b=hn(e,p.query,H(D.capability,D.modelName));b!==null&&m.notify(s(b.key,b.params))},X=bl({...c.loaded.context!==void 0?{settings:c.loaded.context}:{},initialActive:V,settingsPath:me(a),applyScheme:Zl,notify:(e,o)=>m.notify(e,o),...h.governance.contextScheme!==null?{remote:h.governance.contextScheme}:{}});Xn=()=>{let e=X.active();return{id:e.id,fingerprint:e.fingerprint}},ci=()=>X.active();let Cr=pr();h.setGovernanceRefreshListener(e=>{for(let b of e.diagnostics)m.notify(s(b.key,b.params));let o=Hr({adjudicator:e.governance.adjudicator,buildClient:Mo,pricing:e.pricingUpdates,platformHandles:e.governance.models.map(b=>b.handle),remoteAliases:e.governance.remoteAliases,...we.governance!==null?{pool:we.governance.entries}:{}});for(let b of o.notices)m.notify(s(b.key,b.params));jt=o.remote;let p=h.applyTo(c.registryConfig);if(p!==null){let b=_n(p,e.governance);for(let k of b.notices)m.notify(s(k.key,k.params));x=b.config}X.refreshRemote(e.governance.contextScheme);let g=pr();g!==Cr&&(m.notify(s(De.taskConcurrencyUpdated,{from:Cr,to:g})),Cr=g)});for(let e of Ao.notices)m.notify(e.message,e.level==="error"?"error":void 0);for(let e of we.notices)m.notify(e.message,e.level==="error"?"error":void 0);let xr=Dd({appointment:Re,evidence:Ee});xr!==void 0&&m.notify(s(xr.key,xr.params));let Mr=Nd({pool:jt?.pool,profileId:h.governance.adjudicator?.profileId});Mr!==void 0&&m.notify(s(Mr.key,Mr.params)),Oo.kind==="overridden"&&m.notify(s(G.bypassRootOverridden),"error");let eu=new Set(["permission_mode_layer_ignored","permission_setting_layer_ignored"]);for(let e of c.diagnostics)eu.has(e.code)&&m.notify(s(`config.diagnostic.${e.code}`,{layer:e.layer,...e.path!==void 0?{path:e.path}:{},...e.file!==void 0?{file:e.file}:{},...e.params}));(async()=>{let e=await nc(oe);J=e.records,e.corrupted&&A?.notify(s(B.storeCorrupted,{path:oe}),"error");let o=sc(J,ie);o.length>0&&(Pn(F,o,d),A?.notify(s(B.restoredAsk,{count:o.length})));let p=c.loaded.permissions.frozenProjectAllow??[];if(p.length===0)return;let{granted:g,pending:b}=ic(p,J,ie);g.length>0&&(Pn(F,g,d),A?.notify(s(B.restored,{count:g.length})));for(let k of b){let w=await $.requestCommandTrust({commandName:k.layer,rules:k.rules,...k.file!==void 0?{file:k.file}:{},variant:"projectAllow"});if(w.decision==="allow"&&(Pn(F,k.rules.map(P=>({rule:P})),d),w.scope==="repo"))try{J=await no(oe,J,k.rules.map(P=>to(ie,P,k.layer))),A?.notify(s(B.recorded,{count:k.rules.length}))}catch{A?.notify(s(B.writeFailed,{path:oe}),"error")}}})();let mi=e=>{let o=uc(e);switch(o!==null&&A?.pushEvent(o,"mcp"),e.type){case"mcp.closed":e.reason!=="closed"&&A?.notify(s("kernel.mcp.event.closed",{server:e.server,reason:e.reason}),"error");return;case"mcp.elicitation_declined":A?.notify(s("kernel.mcp.event.elicitation_declined",{server:e.server,mode:e.mode}));return;case"mcp.tool_skipped":A?.notify(s(`kernel.mcp.event.tool_skipped.${e.reason}`,{server:e.server,tool:e.tool}));return;case"mcp.reconnecting":case"mcp.reconnected":case"mcp.reconnect_exhausted":{let p=mc(e);p!==null&&A?.notify(p.message,p.level);return}default:return}},_r=ha(gt),Ar=ca(gt),pi=await ka(_r),fi=Qr(await Ar.load(),c.loaded.mcpServers),ot=wa(c.loaded.mcpServers,a,{projectPath:d,records:pi,toolsFingerprints:fi});for(let e of ot.deniedPersisted)m.notify(s(bn.deniedPersisted,{server:e.name}));let $e={current:null},Pr=e=>{e.status==="connected"?m.notify(s("kernel.mcp.attach.connected",{server:e.name,transport:e.transport,version:e.protocolVersion??"",count:e.tools.length})):e.status==="disabled"?m.notify(s("kernel.mcp.attach.disabled",{server:e.name})):m.notify(s("kernel.mcp.attach.failed",{server:e.name,code:e.error?.code??"unknown",message:e.error?.message??""}),"error")},Z=await la(Q,[...ot.allowed,...ae.mcpServers],{catalogStore:Ar,onEvent:mi,onElicitation:Ro($)}).catch(e=>bc(e,process.stderr));Zn=Z,sr=Z.segment,Z.segment!==null&&(te=qt(fe),m.setSystem(te));for(let e of kn(Z.manager.snapshot()))m.notify(e.message,e.level);if(Z.fold!==null){let e=ua(Z.fold);e!==null&&m.notify(e.message,e.level)}await Ra({storePath:_r,projectPath:d,records:pi,servers:ot.allowed,toolsFingerprints:Qr(await Ar.load(),ot.allowed)});let tu=async e=>{let o=await Is(Q,e,{onEvent:mi,onElicitation:Ro($)});$e.current=o;for(let p of o.attachments)Pr(p);return o},nu=ot.pending.length>0||ae.pendingTrust.length>0,Dr=Promise.resolve(),gi=!1,yi=[],Vt=wc({resources:()=>[Z,$e.current,...yi],before:async()=>{gi=!0,await kc([Dr,m.settleResources(),He(ue),He(ye),He(ge),He(Yt),He(kt),He(xe)],"TUI/shutdown")}}),Jt=aa({scheme:V,windowTokens:H(_.capability,_.modelName),system:te,memorySegments:Te.segments,toolDefs:Q.toolDefs,registry:Q.registry,recallBudgets:yr,writeGuidance:N.setup!==null,inviteGuidance:N.setup!==null});if(Jt!==null){Jt.toolState==="short"&&sa(Q.toolDefs,Q.registry),W(C.currentSessionId()).assemblyBudget(Jt.probe);for(let e of Jt.warnings)m.notify(s(e.key,e.params))}let hi=await Os({cwd:d,env:a,extraDirs:ae.commandDirs}),Nr=Kd(hi.commands,new Set(Rt.map(e=>e.name))),ru=[...Rt,...Nr.specs],Or=e=>{try{let o=ze.resolveAlias(e);return{alias:e,modelName:o.modelName,capability:o.capability}}catch{return}},it=_l({currentModel:()=>Or(Ve)??{modelName:D.modelName,capability:D.capability},settingsFilePath:Un(c.sources,a).filePath,...c.loaded.window?.byModel!==void 0?{initialByModel:c.loaded.window.byModel}:{},costText:(e,o)=>{if(yt===void 0)return;let p=e.indexOf("/"),g=p>0?yt.lookup(e.slice(0,p),e.slice(p+1)):yt.lookup(D.providerId,e);return g===void 0?void 0:Ml(g.pricing,o,g.currency)},notify:(e,o)=>m.notify(e,o==="error"?"error":"info")}),jr=Il({ledger:R,pushEvent:e=>m.pushEvent(e),journal:C,currentModel:()=>({provider:D.providerId,model:D.modelName})}),ou={...jr.commandDeps(),costSnapshot:()=>ht.snapshot(),cacheSaved:()=>h.cacheSaved(),platformCacheZeroRead:()=>h.platformCacheZeroRead(),windowStatus:()=>it.status(),get contextReport(){if(m.canReportContext())return()=>{let e=m.contextReport(),o=vr.snapshot(),p=_m(W(C.currentSessionId()).latestManifest()),g=(()=>{let b=N.setup;if(b===null)return;let k=zr(b.readDir),w=tt?.stats();return{indexBytes:k.indexBytes,indexMaxBytes:ns,fileCount:k.files,...w!==void 0?{recallTopics:w.topicsWithPaths,recalledCount:w.recalled}:{},...Ns(b.dir)}})();return{...e,...o!==void 0?{compactions:o}:{},...p!==void 0?{manifest:p}:{},...g!==void 0?{memory:g}:{}}}},contextSchemes:()=>X.list(),currentModel:()=>{let e=`${D.providerId}/${D.modelName}`,o=ee.fast,p=o!==void 0?`${o.model.provider}/${o.model.model}${o.thinkingOff===!0?"(thinking-off)":""}`:void 0,g=(()=>{if(o===void 0)return"main";switch(o.source){case"derived-main":case"group":return o.source;case"alias":return`alias:${h.governance.aliasOrigins?.fast??"unknown"}`;default:return"unknown"}})(),b=ee.compaction.model===void 0||ee.compaction.model.provider===D.providerId&&ee.compaction.model.model===D.modelName?"main":g,k=St(),w=D.providerId===Ct?h.governance.models.find(P=>P.handle===D.modelName):void 0;return{current:{alias:Ve,provider:D.providerId,model:D.modelName,...w!==void 0&&w.displayName!==w.handle?{displayName:w.displayName}:{}},...w?.pricing!=null?{pricing:{currency:w.pricing.currency,inPerMillion:w.pricing.inPerMillion,outPerMillion:w.pricing.outPerMillion,cacheReadPerMillion:w.pricing.cacheReadPerMillion,cacheWritePerMillion:w.pricing.cacheWritePerMillion}}:{},aliases:Bn(x.modelAliases),available:Am(x),roles:[{role:"title",target:p??e,source:g},{role:"classifier",target:`${p??e} · ${e}`,source:g},{role:"compaction",target:ee.compaction.model!==void 0?`${ee.compaction.model.provider}/${ee.compaction.model.model}`:e,source:b},{role:"memory",target:`${k.model.provider}/${k.model.model}`,source:o!==void 0?g:"main"}]}},sessionInfo:()=>({sessionId:he,cwd:d,turns:m.turns()}),availableLocales:()=>Ae(),themeInfo:()=>({current:E.current,available:[...Ke]}),outputStyles:()=>({current:fe.name,available:le.styles.map(e=>({name:e.name,source:e.source,...e.description!==void 0?{description:e.description}:{}}))}),configSummary:()=>({aliases:Bn(x.modelAliases),providers:Object.entries(x.providers).map(([e,o])=>({id:e,protocol:o.protocol,baseUrl:o.baseUrl,modelCount:Object.keys(o.models??{}).length})),...c.loaded.locale!==void 0?{locale:c.loaded.locale}:{},sources:c.sources.map(e=>({layer:e.layer,...e.path!==void 0?{path:e.path}:{},status:e.status})),diagnosticsCount:c.diagnostics.length}),permissionsReport:()=>dc({engine:F,layers:c.loaded.permissions.layers,frozenProjectAllow:c.loaded.permissions.frozenProjectAllow,modeLocked:Ft.lockedMode!==void 0,configuredMode:c.loaded.permissions.defaultMode,effectiveConfiguredMode:zn,classifier:{enabled:Jr(Hn),active:Be!==void 0,...Be!==void 0?{tier:Ue.snapshot()}:{},...Be!==void 0&&Re!==void 0?{appointment:{tier:Re.tier,source:Re.source,...Re.poolEntry!==void 0?{profileId:Re.poolEntry.profileId,name:Re.poolEntry.name,origin:Re.poolEntry.origin}:{}}}:{},...Be!==void 0&&Ee!==void 0?{evidence:{status:Ee.status,source:Ee.source,...Ee.reportRef!==void 0?{reportRef:Ee.reportRef}:{},...Ee.evaluatedAt!==void 0?{evaluatedAt:Ee.evaluatedAt}:{}}}:{}},...Ze!==void 0&&Xe.kind==="enabled"?{askBudget:{maxPrompts:Xe.maxPrompts,summary:Ze.summary}}:{},grants:{records:J,identity:ie}}),permissionTier:()=>Ue.snapshot(),explainDecisions:e=>ec(ve(K,C.currentSessionId()),e),hooks:()=>Object.entries(Vn.byEvent).flatMap(([e,o])=>(o??[]).map(p=>({id:p.id,event:e,kind:p.executor.type}))),skills:()=>ir.entries.map(e=>({name:e.name,source:e.source,description:e.description})),agents:()=>Cs(vt.agents),...ye!==void 0?{continuableAgents:()=>ye?.list()??[]}:{},...ue!==void 0?{taskBackgroundAgents:()=>ue.list().map(e=>({agentId:e.agentId,description:e.description,startedAt:new Date(e.startedAtMs).toISOString(),status:e.status}))}:{},mcpServers:()=>[...Z.manager.snapshot().map(e=>({name:e.name,transport:e.transport,status:e.state,toolCount:e.loadedToolCount,loadMode:e.loadMode,catalogToolCount:e.catalogToolCount,...e.catalogSource!==void 0?{catalogSource:e.catalogSource}:{},skippedCount:e.skippedTools.length,...e.error!==void 0?{errorCode:e.error.code,errorMessage:e.error.message}:{},...e.connections!==void 0?{connections:e.connections}:{},...e.reconnect!==void 0?{reconnect:e.reconnect}:{}})),...($e.current?.attachments??[]).map(e=>({name:e.name,transport:e.transport,status:e.status,toolCount:e.tools.length}))],plugins:()=>ae.items,todos:()=>li,doctorChecks:()=>{let[e=0,o=0]=process.versions.node.split(".").map(Number),p=c.sources.filter(j=>j.status==="skipped"),g=c.diagnostics.filter(j=>j.severity==="error"),b=hi.sources.filter(j=>j.status==="skipped"),k=Z.manager.snapshot(),w=$e.current?.attachments??[],P=k.length+w.length,Y=[...k.filter(j=>j.state!=="idle"&&j.state!=="ready"),...w.filter(j=>j.status!=="connected")];return[{id:"node_version",ok:e>22||e===22&&o>=19,detail:`${process.version} (baseline >=22.19)`},{id:"config_sources",ok:p.length===0,detail:p.length===0?c.sources.map(j=>`${j.layer}=${j.status}`).join(" "):`skipped: ${p.map(j=>j.path??j.layer).join(", ")}`},{id:"config_diagnostics",ok:g.length===0,detail:c.diagnostics.length===0?"clean":`${g.length} error(s) / ${c.diagnostics.length} total: ${[...new Set(c.diagnostics.slice(0,5).map(j=>j.code))].join(", ")}`},{id:"model_resolution",ok:!0,detail:`${Ve} -> ${D.providerId}/${D.modelName}`},{id:"context_window",ok:m.canReportContext(),detail:m.canReportContext()?s(f.doctorWindowKnown):s(f.doctorWindowUnknown)},{id:"context_scheme",ok:X.active().stage==="production",detail:`${X.active().id}@${X.active().fingerprint} stage=${X.active().stage}`},{id:"custom_commands",ok:b.length===0,detail:b.length===0?`${Nr.specs.length} loaded`:`skipped: ${b.map(j=>j.path??j.source).join(", ")}`},{id:"mcp_connections",ok:Y.length===0,detail:P===0?s(f.doctorMcpNone):`${P-Y.length}/${P} healthy${Y.length>0?`; failed: ${Y.map(j=>j.name).join(", ")}`:""}`},{id:"terminal",ok:process.stdout.isTTY===!0,detail:process.stdout.isTTY?`tty ${process.stdout.columns??"?"}x${process.stdout.rows??"?"}`:"not a tty"},{id:"workspace_trust",ok:!se.isUntrusted(),detail:`${se.current().status}${se.current().source!==void 0?` <- ${se.current().source}`:""}`},{id:"output_style",ok:!le.diagnostics.some(j=>j.severity==="error"),detail:`${fe.name} (${fe.source})${le.diagnostics.length>0?`; ${le.diagnostics.length} diagnostic(s)`:""}`},{id:"session_driver_state",ok:!0,detail:el(m.stateDiagnostics())}]},memorySummary:()=>({segments:Te.segments.map(e=>({scope:e.scope,path:e.path,bytes:Buffer.byteLength(e.content,"utf8")})),totalBytes:Te.segments.reduce((e,o)=>e+Buffer.byteLength(o.content,"utf8"),0),auto:{enabled:N.setup!==null,...(()=>{let e=N.setup;if(e===null)return{};let o=zr(e.readDir);return{dir:e.readDir,indexBytes:o.indexBytes,fileCount:o.files}})()}}),bgTasks:()=>zc(gt).map(e=>({id:e.id,status:Vc(e),startedAt:e.startedAt,...e.promptSummary!==""?{promptSummary:e.promptSummary}:{},logPath:e.logPath,...e.worktreePath!==void 0?{worktreePath:e.worktreePath}:{}}))},iu=async(e,o)=>{let p=o?.allowedTools??[];if(o!==void 0&&p.length>0)if(o.source==="project"){let g=`command:${o.name}`;if(p.every(k=>J.some(w=>An(w,ie,k,g))))for(let k of p)F.recordUserDecision(k,"allow",d);else{let k=await $.requestCommandTrust({commandName:o.name,rules:p,...o.file!==void 0?{file:o.file}:{}});if(k.decision==="allow"){for(let w of p)F.recordUserDecision(w,"allow",d);if(C.appendPermissionRuntime(En({rules:p,behavior:"allow",origin:`command_trust:${o.name}`,...k.scope!==void 0?{scope:k.scope}:{}})),k.scope==="repo")try{J=await no(oe,J,p.map(w=>to(ie,w,g))),m.notify(s(B.recorded,{count:p.length}))}catch{m.notify(s(B.writeFailed,{path:oe}),"error")}}}}else for(let g of p)F.recordUserDecision(g,"allow",d);if(o?.model!==void 0)try{let g=xt(x,o.model,{onProviderSelected:Wn,attemptObserver:Se,...ne});m.sendWith(e.prompt,{client:g.client,model:{provider:g.resolved.providerId,model:g.resolved.modelName},contextWindowTokens:H(g.resolved.capability,g.resolved.modelName),...g.resolved.capability.maxOutput!==void 0?{maxOutputTokens:g.resolved.capability.maxOutput}:{}});return}catch{m.notify(s(f.customModelFailed,{name:e.name,model:o.model}),"error")}m.send(e.prompt)},vi=e=>{let o={provider:D.providerId,model:D.modelName};try{let p=xt(x,e,{onProviderSelected:Wn,attemptObserver:Se,...ne}),g=Rn(x,p.resolved,{mainAlias:e,attemptObserver:Se,mainRunWindow:H(p.resolved.capability,p.resolved.modelName),...qn(),...ne}),b=gn(X.active(),g.compaction);m.setModel(p.client,{provider:p.resolved.providerId,model:p.resolved.modelName},H(p.resolved.capability,p.resolved.modelName),{...b.query,observer:Me,restoreFileReader:Mt(),endpointHealthProbe:mt.probeFor(g.compactionBaseUrl)},p.resolved.capability.maxOutput);{let Y=yn(X.active(),b.query,H(p.resolved.capability,p.resolved.modelName));Y!==null&&m.notify(s(Y.key,Y.params));let j=hn(X.active(),b.query,H(p.resolved.capability,p.resolved.modelName));j!==null&&m.notify(s(j.key,j.params))}Ve=e,D=p.resolved,Kn=p.client,ee=g;let k=$a(o,{provider:p.resolved.providerId,model:p.resolved.modelName});k!==null&&R.record(k);let w=Un(c.sources,a);Io(w.filePath,e)!=="persisted"&&m.notify(s(f.modelSelectionSessionOnly,{target:e})),m.notify(s(f.modelSwitched,{provider:p.resolved.providerId,model:p.resolved.modelName})),it.announceClampOnce()}catch{m.notify(s(f.switchModelFailed,{model:e}),"error")}},Si=Wi(),ki=e=>{wo({storageRoot:K,cwd:d,driver:m,sink:C,pickSession:o=>$.pickSession(o),notify:(o,p)=>m.notify(o,p),replayTranscript:o=>Si.replay(Bi(o).items),todoStore:ar,compactionLog:vr,...bt!==void 0?{agentNotifications:{redeliver:o=>bt?.redeliver(o)}}:{},sessionGrants:{record:(o,p)=>F.recordUserDecision(o,p,d)},sessionEvents:jr,emitResumed:({fromSeq:o})=>m.pushEvent({type:"session.resumed",fromSeq:o},"cli"),usageSnapshot:{adopt:o=>{ht.adoptSnapshot(o),di.sync()}},onRestored:o=>{let p=o?.outputStyle;if(p===void 0||Ce.ok&&Ce.selection?.source==="env")return;let g=ro(le.styles,p);if(g===void 0){m.notify(s(ce.resumeStyleUnknown,{style:p}),"error");return}if(er=g.name,g.name===fe.name)return;let b=fe.name;fe=g,te=qt(g),m.setSystem(te),m.pushEvent({type:"session.output_style.changed",style:g.name,previous:b},"cli"),m.notify(s(f.outputStyleRestored,{style:g.name}))}},e).then(o=>{o&&wr.suppress()}).catch(o=>{m.notify(s(ce.resumeFailed,{sessionId:e??"-",message:o instanceof Error?o.message:String(o)}),"error")})},Lr=()=>{ft!==void 0&&(clearTimeout(ft),ft=void 0)},su=(e,o)=>{Lr();let p=setTimeout(()=>{if(ft=void 0,Je!==e)return;let g=Ue.snapshot(),b=Gr(Gr(g.entry,g.ceiling),e.tier);Je=void 0,In({sessionId:C.currentSessionId(),sessionDir:ve(K,C.currentSessionId()),action:"expire",from:b,to:g.effective,actor:"system",reason:"ttl_expired"}),A?.notify(s(f.tierExpired,{effective:g.effective}))},Math.max(0,o-Date.now()));p.unref?.(),ft=p},bi=(e,o,p)=>{if(ye===void 0){m.notify(s(f.agentsContinuableDisabled));return}try{o(ye),m.notify(s(p,{agentId:e}))}catch(g){if(g instanceof ws){m.notify(g.code==="unknown_agent"?s(f.agentUnknown,{agentId:e}):s(f.agentManagerClosed),"error");return}throw g}},wi=null,au=e=>{switch(e.type){case"run_custom_command":{iu(e,Nr.byName.get(e.name));return}case"agent_followup":{bi(e.agentId,o=>{o.followup(e.agentId,e.message)},f.agentFollowupQueued);return}case"agent_interrupt":{bi(e.agentId,o=>o.interrupt(e.agentId,"user"),f.agentInterruptRequested);return}case"agent_kill":{if(ue===void 0){m.notify(s(f.agentsContinuableDisabled));return}m.notify(s(ue.kill(e.agentId)?f.agentKillRequested:f.agentBackgroundUnknown,{agentId:e.agentId}));return}case"switch_model":{vi(e.target);return}case"window_tier":{it.select(e.raw);return}case"pick_model":{$.pickModel(it.decorateModelChoices(To(x,h.governance.models),Or),Ve).then(o=>{if(o.kind==="selected"&&(vi(o.model.alias),o.windowTier!==void 0)){let p=Or(o.model.target??o.model.alias);p!==void 0&&it.applyPickedTier(p.modelName,o.windowTier)}});return}case"resume":{ki(e.sessionId);return}case"compact":{m.compactNow({...e.instructions!==void 0?{instructions:e.instructions}:{},checkpoint:nr.autoCheckpoint}).then(o=>{o.status==="rejected"&&m.notify(s(f.compactRejected,{reason:o.reason}))});return}case"checkpoint_save":{m.checkpoint(e.label!==void 0?{label:e.label}:{}).then(o=>{m.notify(o.status==="saved"?s(f.checkpointSaved,{id:o.meta.checkpointId,count:o.meta.messageCount}):o.status==="failed"?s(f.checkpointFailed,{message:o.message}):s(o.reason==="turn_running"?f.checkpointRejectedRunning:o.reason==="empty_history"?f.checkpointRejectedEmpty:f.checkpointNotConfigured),o.status==="failed"?"error":"info")});return}case"checkpoint_list":{m.listCheckpoints().then(o=>{if(o.length===0){m.notify(s(f.checkpointsEmpty));return}let p=o.map(g=>s(f.checkpointsLine,{id:g.checkpointId,time:g.createdAt,trigger:g.trigger,label:g.label??"-",count:g.messageCount}));m.notify(`${s(f.checkpointsHeader,{count:o.length})}
|
|
65
|
-
${p.join(`
|
|
66
|
-
`)}`)}).catch(o=>{m.notify(s(f.checkpointFailed,{message:o instanceof Error?o.message:String(o)}),"error")});return}case"checkpoint_restore":{m.restore(e.checkpointId).then(o=>{if(o.status==="restored"){m.notify(s(f.restoreDone,{id:o.checkpointId,from:o.fromMessages,to:o.toMessages})),o.preRestoreCheckpointId!==void 0&&m.notify(s(f.restorePreCheckpoint,{id:o.preRestoreCheckpointId})),o.cwdMismatch!==void 0&&m.notify(s(f.restoreCwdMismatch,{expected:o.cwdMismatch.expected,actual:o.cwdMismatch.actual}));return}if(o.status==="failed"){m.notify(s(f.checkpointFailed,{message:o.message}),"error");return}m.notify(o.reason==="not_found"?s(f.restoreNotFound,{id:e.checkpointId}):o.reason==="turn_running"?s(f.checkpointRejectedRunning):s(f.checkpointNotConfigured))});return}case"cwd_change":{m.setCwd(e.dir).then(o=>{if(o.status==="changed"){m.notify(s(f.cdChanged,{from:o.from,to:o.to}));return}if(o.reason==="turn_running"){m.notify(s(f.cdRejectedRunning));return}if(o.reason==="not_configured"){m.notify(s(f.cdNotConfigured),"error");return}m.notify(s(o.reason==="not_absolute"?Tt.notAbsolute:o.reason==="not_found"?Tt.notFound:o.reason==="not_directory"?Tt.notDirectory:Tt.notAllowed,{path:e.dir}),"error")});return}case"checkpoint_fork":{(async()=>{let o=await nr.read(e.checkpointId);if(o===null){m.notify(s(f.restoreNotFound,{id:e.checkpointId}));return}let{checkpoint:p}=o,g=Oc(p.messages),b=jc(p.messages),k=await fs({storageRoot:K,sourceSessionId:o.volumeId,checkpoint:p,cwd:m.cwd(),producer:"cli",extra:{model:D.modelName,provider:D.providerId,...g!==void 0?{title:g}:{},...b!==void 0?{firstUserMessage:b}:{}}});m.notify(s(f.forkDone,{id:k.sessionId}))})().catch(o=>{m.notify(s(f.forkFailed,{message:o instanceof Error?o.message:String(o)}),"error")});return}case"anchor_pin":{if(e.text===void 0){let p=m.listAnchors();if(p==="disabled")m.notify(s(f.anchorsDisabled));else if(p.length===0)m.notify(s(f.anchorsEmpty));else{let g=p.map(b=>s(f.anchorListLine,{id:b.id,source:b.source,text:b.text}));m.notify(`${s(f.anchorListHeader,{count:p.length})}
|
|
67
|
-
${g.join(`
|
|
68
|
-
`)}`)}return}let o=m.pinAnchor(e.text);m.notify(o.status==="disabled"?s(f.anchorsDisabled):o.status==="empty"?s(f.anchorPinEmpty):s(o.duplicate?f.anchorPinnedDuplicate:f.anchorPinned,{id:o.entry.id,text:o.entry.text}));return}case"anchor_unpin":{let o=m.unpinAnchor(e.id);m.notify(o==="disabled"?s(f.anchorsDisabled):o==="removed"?s(f.anchorUnpinned,{id:e.id}):s(f.anchorUnpinNotFound,{id:e.id}));return}case"switch_theme":{let o=dt(e.theme);if(o===null){m.notify(s(f.unknownTheme,{theme:e.theme,available:Ke.join(", ")}),"error");return}E.set(o);let p=Fn(me(a),o);m.notify(p==="persisted"?s(f.themeSwitched,{theme:o}):s(f.themeSwitchedSessionOnly,{theme:o}));return}case"context_scheme":{e.action==="use"?X.use(e.id):X.remove(e.id);return}case"context_scheme_add":{X.add(e);return}case"switch_output_style":{let o=ro(le.styles,e.style);if(o===void 0){m.notify(s(f.unknownOutputStyle,{style:e.style,available:oo(le.styles)}),"error");return}let p=fe.name;fe=o,te=qt(o),m.setSystem(te),er=o.name,Hi(ve(K,C.currentSessionId()),o.name).catch(()=>{}),o.name!==p&&m.pushEvent({type:"session.output_style.changed",style:o.name,previous:p},"cli"),m.notify(s(f.outputStyleSwitched,{style:o.name}));return}case"switch_locale":{let o=tn(e.locale);if(o!==void 0&&Ae().includes(o)){let p=en();Pe(o),o!==p&&m.pushEvent({type:"session.locale.changed",locale:o,previous:p},"cli"),m.notify(s(f.localeSwitched,{locale:o}))}else m.notify(s(f.unknownLocale,{locale:e.locale,available:Ae().join(", ")}),"error");return}case"init":{Ln({env:a,askQuestion:o=>$.askQuestion(o),notify:(o,p)=>m.notify(o,p),mode:"reinit"}).catch(o=>{m.notify(s(lt.failNetwork,{code:o instanceof Error?o.name:"unknown"}),"error")});return}case"logout":{ul({env:a,askQuestion:o=>$.askQuestion(o),notify:(o,p)=>m.notify(o,p)}).then(o=>{o&&wi?.()}).catch(o=>{m.notify(s(_t.failLocalClear,{code:o instanceof Error?o.name:"unknown"}),"error")});return}case"show_diff":{Rl(d).then(o=>{m.notify(o.join(`
|
|
69
|
-
`))}).catch(o=>{m.notify(s(f.diffFailed,{message:o instanceof Error?o.message:String(o)}),"error")});return}case"check_update":{(async()=>{let o=await wn({env:a,policy:c.loaded.policy});for(let P of o.notices)P.level==="error"&&m.notify(P.message,"error");let p=io(o.verify),g=await co({env:a,...c.loaded.update!==void 0?{config:c.loaded.update}:{},trust:p}),b=g.available;if(b===void 0||!mo(b)){m.notify(g.notice.message,g.notice.level);return}for(let P of ao(b))m.notify(P);if(m.notify(uo(lo(b,p),b.currentVersion).join(`
|
|
70
|
-
`)),!(await $.confirmUpdate({currentVersion:b.currentVersion,latestVersion:b.latestVersion,channel:b.channel,source:b.source,install:b.install})).confirmed){m.notify(s(f.updateInstallCancelled));return}m.notify(s(so.installing,{current:b.currentVersion,latest:b.latestVersion,channel:b.channel}));let w=await po(b,{env:a,trust:p});m.notify(w.message,w.level)})();return}case"workspace_trust":{se.handleIntent(e.action).then(()=>or.release());return}case"memory_toggle":{let o=e.enabled?"on":"off",p=Cl(me(a),e.enabled);p==="persisted"?m.notify(s(f.memoryTogglePersisted,{state:o})):p==="skipped_jsonc"?m.notify(s(f.memoryToggleSessionOnly,{state:o})):m.notify(s(f.memoryToggleFailed,{state:o,detail:"write"}),"error");return}case"memory_remember":{if(kt===void 0){m.notify(s(f.rememberUnavailable),"error");return}if(kt.promotionInFlight()){m.notify(s(f.rememberBusy));return}m.notify(s(f.rememberStarted)),kt.run();return}case"open_memory_dir":{let o=N.setup?.readDir;if(o===void 0){m.notify(s(f.memoryOpenUnavailable),"error");return}let p=process.platform==="win32"?"explorer":process.platform==="darwin"?"open":"xdg-open";try{bm(p,[o],{detached:!0,stdio:"ignore"}).unref(),m.notify(s(f.memoryOpened,{dir:o}))}catch(g){let b=g instanceof Error?g.message:String(g);m.notify(s(f.memoryOpenFailed,{dir:o,detail:b}),"error")}return}case"mcp_reconnect":{(async()=>{let o=$e.current,p=Z.manager.snapshot().map(w=>w.name),g=o?.attachments.map(w=>w.name)??[],b=[...p,...g];if(b.length===0){m.notify(s(f.mcpReconnectUnavailable),"error");return}let k;if(e.server!==void 0){if(!b.includes(e.server)){m.notify(s(f.mcpReconnectUnknown,{server:e.server,available:b.join(", ")}),"error");return}k=[e.server]}else if(k=[...Z.manager.snapshot().filter(w=>w.state==="failed").map(w=>w.name),...(o?.attachments??[]).filter(w=>w.status==="failed").map(w=>w.name)],k.length===0){m.notify(s(f.mcpReconnectNone));return}for(let w of k)if(p.includes(w)){let P=await Z.manager.reconnect(w);if(P!==null)for(let Y of kn([P]))m.notify(Y.message,Y.level)}else if(o!==null){let P=await o.reconnect(w);P!==null&&Pr(P)}})();return}case"mcp_connect":{(async()=>{let o=$e.current,p=Z.manager.snapshot(),g=p.find(k=>k.name===e.server),b=o?.attachments.find(k=>k.name===e.server);if(p.length===0&&(o?.attachments.length??0)===0){m.notify(s(f.mcpConnectUnavailable),"error");return}if(g===void 0&&b===void 0){let k=[...p.map(w=>w.name),...o?.attachments.map(w=>w.name)??[]];m.notify(s(f.mcpConnectUnknown,{server:e.server,available:k.join(", ")}),"error");return}if(g!==void 0){if(g.state==="ready"){m.notify(s(f.mcpConnectAlready,{server:e.server}));return}await Z.manager.ensureConnected(e.server);let k=Z.manager.snapshot().find(w=>w.name===e.server);if(k!==void 0)for(let w of kn([k]))m.notify(w.message,w.level);return}if(b!==void 0&&o!==null){if(b.status==="connected"){m.notify(s(f.mcpConnectAlready,{server:e.server}));return}let k=await o.reconnect(e.server);k!==null&&Pr(k)}})();return}case"permission_rules":{let o=e.rule,p=is(o);if(p===null){m.notify(s(f.permRuleInvalid,{rule:o}),"error");return}if(e.behavior==="allow"&&us(p)){m.notify(s(f.permRuleBroadAllow,{rule:o}),"error");return}let g=me(a),b=c.loaded.permissions.layers.user;if(e.action==="add"){F.recordUserDecision(o,e.behavior,d),C.appendPermissionRuntime(En({rules:[o],behavior:e.behavior,origin:"permission_rules"}));let w=Eo(g,e.behavior,o,"add");w.outcome==="persisted"?m.notify(w.changed?s(f.permRuleAdded,{behavior:e.behavior,rule:o}):s(f.permRuleExists,{behavior:e.behavior,rule:o})):w.outcome==="skipped_jsonc"?m.notify(s(f.permRuleSessionOnly,{path:g}),"error"):m.notify(s(f.permRuleAddFailed,{message:w.message}),"error");return}let k=Eo(g,e.behavior,o,"remove");if(k.outcome==="persisted"&&k.changed){e.behavior==="allow"&&F.revokeUserDecision(o);let w=(b?.[e.behavior]??[]).includes(o),P=e.behavior==="allow"&&!w;m.notify(P?s(f.permRuleRemoved,{behavior:e.behavior,rule:o}):s(f.permRuleRemovedNextSession,{behavior:e.behavior,rule:o}))}else if(k.outcome==="persisted"){let w=c.loaded.permissions.layers,P=["policy","projectLocal","projectShared"].find(Y=>(w[Y]?.[e.behavior]??[]).includes(o));m.notify(P!==void 0?s(f.permRuleOtherLayer,{rule:o,layer:P}):s(f.permRuleNotFound,{behavior:e.behavior,rule:o}),"error")}else k.outcome==="skipped_jsonc"?m.notify(s(f.permRuleRemoveJsonc,{path:g}),"error"):m.notify(s(f.permRuleRemoveFailed,{message:k.message}),"error");return}case"permission_tier":{if(e.action==="clear"){if(Je===void 0){m.notify(s(f.tierClearNone));return}let p=Ue.snapshot();Lr(),Je=void 0;let g=Ue.snapshot();In({sessionId:C.currentSessionId(),sessionDir:ve(K,C.currentSessionId()),action:"clear",from:p.effective,to:g.effective,actor:"user",reason:"override_clear"}),m.notify(s(f.tierCleared,{effective:g.effective}));return}let o=e.tier;if(o===void 0)return;(async()=>{_o=(await wn({env:a,policy:c.loaded.policy})).anchor;let g=Date.now(),b=Ue.snapshot(),k=Td({snapshot:b,target:o,...e.forRaw!==void 0?{forRaw:e.forRaw}:{},now:g});if(k.kind==="rejected"){for(let Y of k.blockers)m.notify(Y==="entry"?s(f.tierSetNoEntry,{target:o,entry:b.entry}):s(f.tierSetAboveCeiling,{target:o,ceiling:b.ceiling}),"error");return}if(k.kind==="rejected_ttl"){m.notify(k.reason==="downgrade_ttl"?s(f.tierDowngradeTtl):k.reason==="too_long"?s(f.tierTtlTooLong,{value:e.forRaw??""}):s(f.tierTtlInvalid,{value:e.forRaw??""}),"error");return}Lr(),Je=k.override;let w=k.override.expiresAtMs;w!==void 0&&su(k.override,w);let P=Ue.snapshot();In({sessionId:C.currentSessionId(),sessionDir:ve(K,C.currentSessionId()),action:"set",from:b.effective,to:P.effective,actor:"user",reason:"override_set",...w!==void 0?{ttlMs:w-g}:{}}),m.notify(w!==void 0?s(f.tierSetUpgrade,{tier:o,effective:P.effective,minutes:Math.max(1,Math.ceil((w-g)/6e4))}):s(f.tierSetSticky,{tier:o,effective:P.effective}))})();return}case"grants":{(async()=>{let o=J.filter(g=>g.repo===ie.repo);if(e.action==="revoke"&&e.target!==void 0){let g=Number(e.target);if(!Number.isInteger(g)||g<1||g>o.length){m.notify(s(B.invalidIndex,{value:e.target,count:o.length}),"error");return}let b=o[g-1];if(b.status==="revoked"){m.notify(s(B.alreadyRevoked,{rule:b.rule}));return}try{let{records:k,revoked:w}=await oc(oe,b);if(J=k,w===0){m.notify(s(B.alreadyRevoked,{rule:b.rule}));return}An(b,ie,b.rule,b.origin)&&F.revokeUserDecision(b.rule),m.notify(s(B.revokedOne,{rule:b.rule}))}catch{m.notify(s(B.writeFailed,{path:oe}),"error")}return}if(e.action==="revoke"){try{let{records:g,revoked:b,revokedRules:k}=await rc(oe,J,ie.repo);J=g;for(let w of k)F.revokeUserDecision(w);m.notify(b>0?s(B.revoked,{count:b}):s(B.revokeNone))}catch{m.notify(s(B.writeFailed,{path:oe}),"error")}return}if(o.length===0){m.notify(s(B.none));return}let p=o.map((g,b)=>{let k=g.status==="revoked"?"revoked":An(g,ie,g.rule,g.origin)?"active":"stale";return s(B.statusLine,{index:b+1,rule:g.rule,origin:g.origin,status:k})});m.notify([s(B.statusHeader,{repo:ie.repo,count:o.length}),...p].join(`
|
|
71
|
-
`))})();return}case"rewind":{Ri();return}}};function Ri(){El({checkpoints:br,running:()=>m.running(),pickRewindPoint:e=>$.pickRewindPoint(e),confirmRewind:e=>$.confirmRewind(e),notify:(e,o)=>m.notify(e,o)})}let du={contextWindowTokens:H(_.capability,_.modelName),getEffectiveWindowTokens:()=>m.effectiveWindowTokens(),getCostSnapshot:()=>Ud(h.serverCost(),{totals:{cost:ht.snapshot().totals.cost}}),isWorkspaceUntrusted:()=>se.isUntrusted(),getContextSchemeWarning:()=>X.warning(),getBalance:()=>h.balance()??void 0,getBalanceCurrency:()=>h.balanceCurrency()??void 0,getOrgBadge:()=>{let e=h.governance.org;return e!==null?{name:e.org.name!==""?e.org.name:e.org.id,softLock:e.softLock}:void 0},...jr.statusSource()},Xt=await i;if(!Xt.ok){let e=[];for(let o of[()=>m.close(),()=>Gt?.close("exit"),()=>ye?.drain(),()=>ue?.drain(),()=>C.close(),()=>rt?.close(),()=>Vt.observe({stderr:process.stderr})])try{await o()}catch(p){e.push(p)}if(e.length>0)try{process.stderr.write(`${JSON.stringify({event:"tui.cleanup_failed",failureCount:e.length,message:s("cli.cleanup.failed",{scope:"TUI/render-load"})})}
|
|
72
|
-
`)}catch{}throw Xt.error}let{runTui:cu}=Xt.runtime;if(a.TANSR_STARTUP_PROBE==="1"){process.stdout.write(`${JSON.stringify({probe:"tui_ready",ms:Math.round(performance.now())})}
|
|
73
|
-
`),m.close();try{await ye?.drain(),await ue?.drain(),await C.close(),await rt?.close()}finally{await Vt.observe({stderr:process.stderr})}return U.ok}or.start(r.args.resume!==void 0?"resume":"startup"),it.announceClampOnce();let Ei=Ld(a),Zt=Ei?null:ll(a),Ii=h.balance(),Ti=h.balanceCurrency(),lu=jn({...Ei?{escapeLocal:!0}:{},...Zt!==null?{identityLabel:Zt.label,...Zt.org!==void 0?{identityOrg:Zt.org}:{}}:{},...h.enabled?{endpoint:rn(a)}:{},mainModel:{name:_.modelName,windowTokens:H(_.capability,_.modelName)},...z.fast!==void 0?{fastModel:{name:z.fast.model.model,...z.fast.contextWindowTokens!==void 0?{windowTokens:z.fast.contextWindowTokens}:{},source:z.fast.source==="alias"?`alias:${h.governance.aliasOrigins?.fast??"unknown"}`:z.fast.source??"unknown"}}:{},schemeName:V.displayName,...Ii!==null?{balance:{amount:Ii,...Ti!==null?{currency:Ti}:{}}}:{}}),st=cu({driver:m,cwd:d,slashCommands:ru,commandDeps:ou,onCommandIntent:au,dialogs:$,statusSource:du,theme:E,transcriptReplay:Si,renderOptions:{incremental:r.args.incremental},onQuit:()=>m.close(),onDoubleEsc:()=>Ri(),bannerLoginHint:!h.enabled,bannerPortalUrl:nn(process.env),bannerSummaryLines:lu});if(!st.ok){process.stderr.write(st.error.message+`
|
|
74
|
-
`),m.close();try{await $t.sessionEnd("exit"),Gt?.close("exit"),await ye?.drain(),await ue?.drain(),await C.close(),await rt?.close()}finally{await Vt.observe({stderr:process.stderr})}return U.usage}xm(Xt.runtime.warmMarkdownLexer),wi=st.unmount;let Ci=()=>{},uu=new Promise(e=>{Ci=e}),xi=al({driver:m,unmount:st.unmount,resetTerminal:st.resetTerminal,waitForShutdown:()=>uu,stderr:process.stderr});se.needsDialog()&&se.runDialog(e=>$.requestWorkspaceTrust(e)).then(()=>or.release()),Lo&&Za({request:()=>$.confirmBypassAck(),isRestricted:()=>se.isUntrusted(),setEngineMode:e=>{let o=F.getMode();F.setMode(e),Bo(o,e,"bypass_ack")},onAccepted:()=>{zn="bypassPermissions"},persist:()=>Xa(jo),notifyDeclined:()=>m.notify(s(G.bypassAckDeclined)),notifyPersistFailed:()=>m.notify(s(G.bypassAckPersistFailed),"error")}),nu&&(Dr=(async()=>{let e=[];for(let g of ae.pendingTrust){let b=g.plugin,k=await $.requestPluginTrust({pluginName:b.name,version:b.version,hooksCount:b.contents.counts.hooks,mcpServerNames:Object.keys(b.contents.mcpServers??{}).map(P=>P.slice(0,80)),projectPath:d}),w=async P=>{try{if(g.fingerprint===null)throw new Error("fingerprint unavailable");await xa($o,Ta(d,b.name),{decision:P,fingerprint:g.fingerprint})}catch{m.notify(s(Yr.storeWriteFailed,{plugin:b.name}),"error")}};k.decision==="allow_once"?e.push(b):k.decision==="allow_always"?(e.push(b),await w("allow")):(k.cancelled!==!0&&await w("deny"),m.notify(s(Yr.deniedSession,{plugin:b.name})))}let o=[];if(e.length>0){let g=_a(e,{reservedMcpNames:new Set([...c.loaded.mcpServers.map(k=>k.name),...ae.mcpServers.map(k=>k.name)])});Wt.exempt(g.hooks),Aa(Vn,g.hooks),o.push(...g.mcpServers);for(let k of g.notices)m.notify(k.message,k.level);let b=new Set(e.map(k=>k.name));for(let k of ae.items)b.has(k.name)&&(k.trusted=!0)}let p=[];for(let g of ot.pending){let b=Ea(g),k=await $.requestMcpTrust({serverName:g.name,transport:b.transport,summary:b.summary,projectPath:d}),w=fi.get(g.name),P=async Y=>{try{await ba(_r,va(d,g.name),{decision:Y,fingerprint:Sa(g.config),...w!==void 0?{toolsFingerprint:w}:{}})}catch{m.notify(s(bn.storeWriteFailed,{server:g.name}),"error")}};k.decision==="allow_once"?p.push(g):k.decision==="allow_always"?(p.push(g),await P("allow")):(k.cancelled!==!0&&await P("deny"),m.notify(s(bn.deniedSession,{server:g.name})))}gi||($e.current=await tu([...p,...o]))})(),Dr.catch(e=>{e instanceof Es&&yi.push({closeAll:()=>e.cleanup.settleClose(),settleClose:()=>e.cleanup.settleClose()})})),r.args.resume!==void 0&&ki(r.args.resume.sessionId);try{await st.waitUntilExit()}finally{m.close();try{wr.abort(),xe?.dispose(),await m.idle(),await ye?.drain(),await ue?.drain(),ge?.handleSessionClose(),await Promise.all([ge?.drain(),Yt?.drain(),kt?.drain()]),await Ds(N.setup,()=>m.listAnchors()),await $t.sessionEnd("exit"),Gt?.close("exit"),Ie.decisions.writeMetrics(Ze!==void 0&&Xe.kind==="enabled"?{projectAskBudget:{maxPrompts:Xe.maxPrompts,summary:Ze.summary}}:{}),await C.close(),await rt?.close()}finally{try{await Vt.observe({stderr:process.stderr})}finally{xi.dispose(),Ci()}}}return xi.exitCode(U.ok)}function _m(n){if(n===void 0)return;let t=n.manifest.segments;return{segments:Yi.map(r=>({id:r,bytes:t[r].bytes,estimatedTokens:t[r].estimatedTokens})),estimatedTokens:n.estimatedTokens,prefixFingerprint:n.manifest.prefix.fingerprint,prefixBytes:n.manifest.prefix.bytes,...n.cacheAttribution!==void 0?{cacheAttribution:n.cacheAttribution}:{},...n.usage!==void 0?{usage:{input:n.usage.inputTokens,output:n.usage.outputTokens,cacheRead:n.usage.cacheReadInputTokens??0,cacheWrite:n.usage.cacheCreationInputTokens??0}}:{}}}function Bn(n){let t={};for(let r of["main","fast","reasoning"]){let i=n[r];i!==void 0&&(t[r]=i)}return t}function Am(n){let t=Object.keys(Bn(n.modelAliases));for(let[r,i]of Object.entries(n.providers))for(let a of Object.keys(i.models??{}))t.push(`${r}/${a}`);return t}function To(n,t=[]){let r=new Map(t.map(a=>[a.handle,a])),i=[];for(let[a,u]of Object.entries(Bn(n.modelAliases))){let d=u.startsWith(`${Ct}/`)?u.slice(Ct.length+1):u,l=r.get(d);i.push({alias:a,target:u,pinned:!0,...l!==void 0&&l.displayName!==l.handle?{description:l.displayName}:{}})}for(let[a,u]of Object.entries(n.providers))for(let[d,l]of Object.entries(u.models??{})){let y=a===Ct?r.get(d):void 0;i.push({alias:`${a}/${d}`,target:`${a}/${l}`,...y!==void 0?{displayName:y.displayName,...y.kind!==null?{kind:y.kind}:{},...y.family!==null?{family:y.family}:{},...y.manufacturer!==null?{manufacturer:y.manufacturer}:{},...y.tags.length>0?{tags:y.tags}:{}}:{}})}return i}export{Dt as KernelSessionDriver,f as TUI_ENTRY_MESSAGE_KEY,mu as TUI_ENTRY_MESSAGE_KEYS,To as buildModelChoices,Dl as parseTuiArgs,wo as runResumeFlow,Mm as runTuiEntry};
|
|
75
|
-
//# sourceMappingURL=tansr-tui-DXGFMSII.mjs.map
|