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