@lmctl-ai/lmctl 0.2.382 → 0.2.384

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/build-info.json CHANGED
@@ -1 +1 @@
1
- {"sha": "e290adb20c9c8300c3e9002bf71a955c65cebf88", "dirty": false, "builtAt": "2026-10-22T17:43:43.000Z"}
1
+ {"sha": "fd0412193a72860a98f24a9acde30853f5eeede3", "dirty": false, "builtAt": "2026-10-22T18:34:02.000Z"}
package/dist/cli/index.js CHANGED
@@ -2627,15 +2627,15 @@ With a teamfile and an alias: single-member deep view (session detail, token
2627
2627
  breakdown, liveness with terminal-lock/in-flight holder info).
2628
2628
 
2629
2629
  --json emits { schema_version: 2, scope: 'self'|'db'|'team'|'member', ... }.
2630
- `,O_=2,Dd=5,AX=24*60*60*1e3,k_=72,yN=80;RX={name:"status",allowsBareTeamfile:!0,supportsRaw:!1};AN=new WeakMap});import{isAbsolute as sq,resolve as LN,join as CN}from"node:path";function DN(t){let e=ON.get(t);if(!e)throw Error("Unknown context");return e.dal()}function $N(t){return t!==null&&typeof t=="object"&&MN.has(t)}function PN(t){try{if(!t||typeof t!="object"||Array.isArray(t))return gt("invalid_argument","Context needs an explicit options map");let e={...t},n=["pid","env","cwd","dbPath","dal","onProgress","onWarning","clock","interactive"];if(Object.keys(e).some(_=>!n.includes(_)))return gt("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!sq(e.cwd))return gt("invalid_argument","Context needs an explicit env and absolute cwd");let r=Object.freeze({...e.env});if(Object.values(r).some(_=>_!==void 0&&typeof _!="string"))return gt("invalid_argument","Environment values must be strings or undefined");for(let _ of["onProgress","onWarning","clock"])if(e[_]!==void 0&&typeof e[_]!="function")return gt("invalid_argument",_+" must be a function");if(e.interactive!==void 0&&typeof e.interactive!="boolean")return gt("invalid_argument","interactive must be a boolean");if(e.dbPath!==void 0&&(typeof e.dbPath!="string"||!e.dbPath))return gt("invalid_argument","dbPath must be a nonempty string");if(e.pid!==void 0&&(!Number.isInteger(e.pid)||e.pid<=0))return gt("invalid_argument","pid must be a positive integer");let s=LN(e.cwd),o=r.LMCTL_HOME||(r.HOME?CN(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(o?CN(o,"state.db"):void 0)))return gt("invalid_argument","Context needs dbPath, LMCTL_DB, LMCTL_HOME or HOME");let a=!1,l,c,d,u=new AbortController,f=new Set,m=_=>{if(l){try{l.close()}catch(h){_.push(Ir(h))}l=void 0}},p=Object.freeze({status:"ok",error:null,pid:e.pid,signal:u.signal,env:r,cwd:s,dbPath:LN(s,Ke(e.dbPath,r)),dal:e.dal,interactive:e.interactive??r.LMCTL_NON_INTERACTIVE!=="1",onProgress:e.onProgress??(()=>{}),onWarning:e.onWarning??(()=>{}),clock:e.clock??Date.now,get closed(){return a},close(){if(c)return c;let _;return c=new Promise(h=>{_=h}),a=!0,u.abort(),(async()=>{let h=[],g=0;for(let E of[...f])try{await E.close(),g++,f.delete(E)}catch(y){h.push(Ir(y))}h.length||m(h),_({released:g,errors:h})})(),c},finalizeSync(_){if(d)return d;a=!0;let h=[],g={released:0,errors:h};d=g,c??=Promise.resolve(g);let E=[];for(let y of[...f])try{let w=y.finalizeSync(_);w instanceof Promise?E.push(w.then(()=>{g.released++,f.delete(y)}).catch(T=>{h.push(Ir(T))})):(g.released++,f.delete(y))}catch(w){h.push(Ir(w))}return u.abort(_),E.length?c=Promise.all(E).then(()=>(h.length||m(h),g)):h.length||m(h),g}});return ON.set(p,{resources:f,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=Fe({path:p.dbPath})}}),MN.add(p),oq.set(p,{activeAgents:new WeakSet,activeSessions:new Set,handoffSessions:new Set,reservations:new Map}),p}catch(e){return gt("invalid_argument","Invalid context: "+Ir(e))}}var ON,oq,MN,Pd=C(()=>{"use strict";bt();On();Qc();ON=new WeakMap;oq=new WeakMap,MN=new WeakSet});var Cr,BN,Ose,Dse,Mse,$se,Pse,se,M_,Tn,Ud,Lr,Fd,Wd,xo,UN,FN,jN,Lo,jd,iq,WN,HN,XN,$_=C(()=>{"use strict";Cr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Cr(e);Object.freeze(t)}return t},BN=Cr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),Ose=Cr({status:"string",error:"string|null",code:"ErrorCode?"}),Dse=Cr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Mse=Cr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),$se=Cr(["Provider1","Provider2","Provider3"]),Pse=Cr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),se={name:"ctx",type:"context"},M_={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},Tn={name:"teamfile",type:"string"},Ud={name:"alias",type:"string"},Lr={name:"prompt",type:"string"},Fd={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},Wd=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],xo={name:"options",type:"map",optional:!0,keys:Wd},UN={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},FN={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},jN={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Lo={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},jd={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},iq=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"},{name:"reconcile",type:"boolean"}],WN={name:"options",type:"map",optional:!0,keys:iq},HN={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},XN=Cr([{name:"resolveProfilePath",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"classifyFailure",implemented:!0,params:[{name:"text",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"model",type:"string"},{name:"status",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null",class:"string",rule:"string|null"},effects:[],summary:"Classify a recorded provider failure text by the one classifier; text no rule recognises is `unknown`, never the nearest class.",scriptBinding:{name:"lm_classify_failure",params:[{name:"text",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"model",type:"string"},{name:"status",type:"string"}]}]}},{name:"readPrompts",implemented:!0,params:[se,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[se,Tn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[Tn]}},{name:"resolveMember",implemented:!0,params:[se,Tn,Ud],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[Tn,Ud]}},{name:"lintTeam",implemented:!0,params:[se,Tn],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[Tn]}},{name:"seedTeam",implemented:!0,params:[se,Tn,UN],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[Tn,UN]}},{name:"promptAgent",implemented:!0,params:[se,Fd,Lr,xo],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...HN,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Fd,Lr,xo]}},{name:"promptMember",implemented:!0,params:[se,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...Wd]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",errorKind:"cycle|provider|target?",code:"ErrorCode?",errorClass:"string|null",usage:"map|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[Tn,Ud,Lr,{name:"options",type:"map",optional:!0,keys:[...Wd,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[se,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[se,Lo,jN],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[Fd,{...jN,optional:!0}]}},{name:"getSession",implemented:!0,params:[se,Lo],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages.",scriptBinding:{name:"lm_session_get",params:[Lo]}},{name:"reserveSession",implemented:!0,params:[se,Lo],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[se,Lo,{name:"reservation",type:"SessionReservation",optional:!0}],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission; an optional capability makes owned cleanup idempotent and replacement-safe."},{name:"openTeamBatch",returnsResource:!0,implemented:!0,params:[se,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...Wd]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[se,{name:"batch",type:"BatchRef"},Lr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[se,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[se,FN],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[FN]}},{name:"openTerminal",implemented:!0,params:[se,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[Tn,Ud]}},{name:"sessionAdmission",implemented:!0,params:[se,Lo],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[se,{name:"reservation",type:"SessionReservation"},Fd,Lr,xo],statuses:["ok","busy","stalled","empty","error"],results:{...HN,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[se,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Synchronously release one batch on a close deadline without cancelling unrelated batches."},{name:"inspectBatch",implemented:!0,params:[se,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"openNativeSession",returnsResource:!0,implemented:!0,params:[se,{name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},xo],statuses:["ok","busy","error"],results:{error:"string|null",session:"opaque context-bound NativeSessionRef"},effects:["provider","db","file-read"],summary:"Open a script-owned native conversation with existing receiver admission."},{name:"nativeSessionTurn",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"},Lr],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Record one unframed conversational turn through the existing recorder."},{name:"closeNativeSession",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close a script-owned native conversation and release its lease."},{name:"finalizeNativeSessionSync",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Critical synchronous native conversation lease release."},{name:"nativeSessionRequest",implemented:!0,params:[se,jd,Lr,xo],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Send a stateless native-id turn to a qualified conversation in the configured running lmbee service.",scriptBinding:{name:"lm_session_turn",params:[jd,Lr,xo]}},{name:"nativeSessionClose",implemented:!0,params:[se,jd],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Close an idle service-hosted native conversation; an absent entry is already closed.",scriptBinding:{name:"lm_session_close",params:[jd]}},{name:"loadProperties",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."},{name:"listRunning",implemented:!0,params:[se,WN],statuses:["ok","error"],results:{error:"string|null",running:"RunningRow[]",dead:"DeadRow[]",idle:"IdleRow[]"},effects:["db"],summary:"DB-wide view of tracked invocation activity. Read-only unless reconcile:true, which also aborts rows whose holder is confirmed dead. Dispatch and branch on status busy, never gate on this.",scriptBinding:{name:"lm_running",params:[WN]}}])});function qN(t){if(!$N(t))return gt("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return gt("cancelled","Context is closed")}function GN(t){return XN.find(e=>e.name===t)?.params.find(e=>e.name==="options")?.keys?.map(e=>e.name)??[]}var VN=C(()=>{"use strict";$_();Pd();Qc()});import{isAbsolute as aq,resolve as lq}from"node:path";function Bd(t){return Number.isFinite(t)&&Math.abs(t)<=cq}function dq(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(BN.includes(e))return e;if(e==="SQLITE_BUSY"||e==="SQLITE_LOCKED")return"busy";if(e==="SQLITE_READONLY"||e.startsWith("SQLITE_READONLY")||e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT"||e==="SQLITE_CANTOPEN")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}let n=t.message;if(typeof n=="string"){if(n.includes("readonly database")||n.includes("SQLITE_READONLY"))return"read";if(n.includes("database is locked")||n.includes("SQLITE_BUSY"))return"busy"}}return"internal"}function F_(t,e=Date.now()){if(t===void 0)return{windowMs:JN};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let o=Number(n[1]),i=n[2],l=(i==="s"?o:i==="m"?o*60:i==="h"?o*3600:o*86400)*1e3;return!Number.isFinite(l)||l<0||!Bd(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Bd(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Bd(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Hd(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function U_(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return P_;let s=e.get(n);if(s===void 0){try{s=Ie(n)}catch{s=null}e.set(n,s)}return s===null?P_:Nl(s,r)?.model??P_}async function KN(t,e={}){let n=qN(t);if(n)return{status:"error",error:n.error,code:n.code,running:[],dead:[],idle:[]};if(e!=null){if(typeof e!="object"||Array.isArray(e))return{status:"error",error:"Options must be a map",code:"invalid_argument",running:[],dead:[],idle:[]};let o=GN("listRunning");if(o.length>0){for(let i of Object.keys(e))if(!o.includes(i))return{status:"error",error:`Unknown option: ${i}`,code:"invalid_argument",running:[],dead:[],idle:[]}}if(e.teamfile!==void 0&&(typeof e.teamfile!="string"||!e.teamfile.trim()))return{status:"error",error:"teamfile must be a nonempty string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.member!==void 0&&typeof e.member!="string")return{status:"error",error:"member must be a string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.reconcile!==void 0&&typeof e.reconcile!="boolean")return{status:"error",error:"reconcile must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.tree!==void 0&&typeof e.tree!="boolean")return{status:"error",error:"tree must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]}}let r=t.clock(),s=JN;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Bd(r-e.since))return{status:"error",error:"since must be a non-negative number of milliseconds within representable date range",code:"invalid_argument",running:[],dead:[],idle:[]};s=e.since}else if(typeof e.since=="string"){let o=F_(e.since,r);if("error"in o)return{status:"error",error:o.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=o.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let o=DN(t),i=e?.teamfile!==void 0?aq(e.teamfile)?e.teamfile:lq(t.cwd,e.teamfile):void 0,a=i!==void 0?Ne(i,o):void 0,l=e?.member!==void 0?e.member.toLowerCase():void 0,c=y=>!(a!==void 0&&y.target_teamfile!==a||l!==void 0&&(y.target_alias??"").toLowerCase()!==l),d=o.listAllRunningTrackedInvocations().filter(c),u=new Map,f=[],m=[];for(let y of d){let w=ar(y),T=r-new Date(y.started_at).getTime(),S={id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:Hd(y),model:U_(y,u),started_at:y.started_at,parent_invocation_id:y.parent_invocation_id};if(w==="dead"){if(e?.reconcile===!0&&Lf(o,y)!==null)continue;m.push({...S,stale_for_ms:T})}else f.push({...S,running_for_ms:T,holder_liveness:w??"unknown"})}let p=new Set(d.map(Hd).filter(y=>y!==null)),_=new Date(r-s).toISOString(),h=o.listRecentlyFinishedTrackedInvocations(_).filter(c),g=new Set,E=[];for(let y of h){let w=Hd(y);w===null||p.has(w)||g.has(w)||(g.add(w),E.push({id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:w,model:U_(y,u),status:y.status,started_at:y.started_at,ended_at:y.ended_at,idle_ms:r-new Date(y.ended_at).getTime(),ran_ms:new Date(y.ended_at).getTime()-new Date(y.started_at).getTime(),error:y.error,parent_invocation_id:y.parent_invocation_id}))}if(e?.tree===!0){let y=new Set([...f.map(T=>T.id),...m.map(T=>T.id),...E.map(T=>T.id)]),w=[...y];for(;w.length>0;){let T=o.listFinishedTrackedInvocationChildren(w,_).filter(S=>!y.has(S.id)&&c(S));if(T.length===0)break;w=[];for(let S of T){y.add(S.id),w.push(S.id);let k=Hd(S);E.push({id:S.id,kind:S.kind,origin:S.origin,from_identity:S.from_identity,target:k,model:U_(S,u),status:S.status,started_at:S.started_at,ended_at:S.ended_at,idle_ms:r-new Date(S.ended_at).getTime(),ran_ms:new Date(S.ended_at).getTime()-new Date(S.started_at).getTime(),error:S.error,parent_invocation_id:S.parent_invocation_id})}}}return{status:"ok",error:null,running:f,dead:m,idle:E}}catch(o){return{status:"error",error:o instanceof Error?o.message:String(o),code:dq(o),running:[],dead:[],idle:[]}}}var JN,cq,P_,YN=C(()=>{"use strict";Pd();VN();$_();Wt();Ul();ze();on();JN=24*60*60*1e3,cq=864e13;P_="default"});var n0={};me(n0,{_setRunningWatchMaxTicksForTests:()=>mq,runRunning:()=>vq});import{resolve as uq}from"node:path";function mq(t){W_=t??void 0}function hq(t){let e=t.split(`
2631
- `,1)[0];return e.length<=H_?e:`${e.slice(0,H_)}\u2026`}function B_(t){return t.target!==null?wn(t.target):t.from_identity}function QN(t){return[(0,Pt.escapeCell)(B_(t)),t.kind,"running",t.holder_liveness,(0,Pt.escapeCell)(t.model),ka(t.started_at)]}function ZN(t){return[(0,Pt.escapeCell)(B_(t)),t.kind,"DEAD","",(0,Pt.escapeCell)(t.model),`stale ${ka(t.started_at)}, holder process confirmed dead`]}function e0(t){let e=`ran ${$d(t.ran_ms)}, idle ${ka(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,Pt.escapeCell)(El(t.error,H_)??hq(t.error))}`),[(0,Pt.escapeCell)(B_(t)),t.kind,t.status,"",(0,Pt.escapeCell)(t.model),e]}function j_(t){return t.filter(e=>e!=="").join(" ")}function t0(t){let e=new Map(t.map(o=>[o.id,o])),n=new Map,r=[];for(let o of t){let i=o.parent_invocation_id;if(i!==null&&e.has(i)){let a=n.get(i)??[];a.push(o),n.set(i,a)}else r.push(o)}let s=(o,i)=>i.started_at.localeCompare(o.started_at);r.sort(s);for(let o of n.values())o.sort(s);return{roots:r,childrenByParent:n}}function gq(t){let{roots:e,childrenByParent:n}=t0(t),r=[],s=(o,i)=>{r.push(`${" ".repeat(i+1)}${o.line}`);for(let a of n.get(o.id)??[])s(a,i+1)};for(let o of e)s(o,0);return r}function yq(t,e,n){let r=[...t.map(a=>({state:"running",...a})),...e.map(a=>({state:"dead",...a})),...n.map(a=>({state:"idle",...a}))],{roots:s,childrenByParent:o}=t0(r),i=a=>({...a,children:(o.get(a.id)??[]).map(i)});return s.map(i)}function Eq(t,e){return e?{schema_version:zN,tree:yq(t.running,t.dead,t.idle)}:{schema_version:zN,running:t.running,dead:t.dead,idle:t.idle}}function wq(t){let e=[...t.running.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(QN(r))})),...t.dead.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(ZN(r))})),...t.idle.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(e0(r))}))],n=gq(e);return`${n.length>0?n.join(`
2630
+ `,O_=2,Dd=5,AX=24*60*60*1e3,k_=72,yN=80;RX={name:"status",allowsBareTeamfile:!0,supportsRaw:!1};AN=new WeakMap});import{isAbsolute as sq,resolve as LN,join as CN}from"node:path";function DN(t){let e=ON.get(t);if(!e)throw Error("Unknown context");return e.dal()}function $N(t){return t!==null&&typeof t=="object"&&MN.has(t)}function PN(t){try{if(!t||typeof t!="object"||Array.isArray(t))return gt("invalid_argument","Context needs an explicit options map");let e={...t},n=["pid","env","cwd","dbPath","dal","onProgress","onWarning","clock","interactive"];if(Object.keys(e).some(_=>!n.includes(_)))return gt("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!sq(e.cwd))return gt("invalid_argument","Context needs an explicit env and absolute cwd");let r=Object.freeze({...e.env});if(Object.values(r).some(_=>_!==void 0&&typeof _!="string"))return gt("invalid_argument","Environment values must be strings or undefined");for(let _ of["onProgress","onWarning","clock"])if(e[_]!==void 0&&typeof e[_]!="function")return gt("invalid_argument",_+" must be a function");if(e.interactive!==void 0&&typeof e.interactive!="boolean")return gt("invalid_argument","interactive must be a boolean");if(e.dbPath!==void 0&&(typeof e.dbPath!="string"||!e.dbPath))return gt("invalid_argument","dbPath must be a nonempty string");if(e.pid!==void 0&&(!Number.isInteger(e.pid)||e.pid<=0))return gt("invalid_argument","pid must be a positive integer");let s=LN(e.cwd),o=r.LMCTL_HOME||(r.HOME?CN(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(o?CN(o,"state.db"):void 0)))return gt("invalid_argument","Context needs dbPath, LMCTL_DB, LMCTL_HOME or HOME");let a=!1,l,c,d,u=new AbortController,f=new Set,m=_=>{if(l){try{l.close()}catch(h){_.push(Ir(h))}l=void 0}},p=Object.freeze({status:"ok",error:null,pid:e.pid,signal:u.signal,env:r,cwd:s,dbPath:LN(s,Ke(e.dbPath,r)),dal:e.dal,interactive:e.interactive??r.LMCTL_NON_INTERACTIVE!=="1",onProgress:e.onProgress??(()=>{}),onWarning:e.onWarning??(()=>{}),clock:e.clock??Date.now,get closed(){return a},close(){if(c)return c;let _;return c=new Promise(h=>{_=h}),a=!0,u.abort(),(async()=>{let h=[],g=0;for(let E of[...f])try{await E.close(),g++,f.delete(E)}catch(y){h.push(Ir(y))}h.length||m(h),_({released:g,errors:h})})(),c},finalizeSync(_){if(d)return d;a=!0;let h=[],g={released:0,errors:h};d=g,c??=Promise.resolve(g);let E=[];for(let y of[...f])try{let w=y.finalizeSync(_);w instanceof Promise?E.push(w.then(()=>{g.released++,f.delete(y)}).catch(T=>{h.push(Ir(T))})):(g.released++,f.delete(y))}catch(w){h.push(Ir(w))}return u.abort(_),E.length?c=Promise.all(E).then(()=>(h.length||m(h),g)):h.length||m(h),g}});return ON.set(p,{resources:f,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=Fe({path:p.dbPath})}}),MN.add(p),oq.set(p,{activeAgents:new WeakSet,activeSessions:new Set,handoffSessions:new Set,reservations:new Map}),p}catch(e){return gt("invalid_argument","Invalid context: "+Ir(e))}}var ON,oq,MN,Pd=C(()=>{"use strict";bt();On();Qc();ON=new WeakMap;oq=new WeakMap,MN=new WeakSet});var Cr,BN,Ose,Dse,Mse,$se,Pse,se,M_,Tn,Ud,Lr,Fd,Wd,xo,UN,FN,jN,Lo,jd,iq,WN,HN,XN,$_=C(()=>{"use strict";Cr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Cr(e);Object.freeze(t)}return t},BN=Cr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),Ose=Cr({status:"string",error:"string|null",code:"ErrorCode?"}),Dse=Cr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Mse=Cr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),$se=Cr(["Provider1","Provider2","Provider3"]),Pse=Cr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),se={name:"ctx",type:"context"},M_={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},Tn={name:"teamfile",type:"string"},Ud={name:"alias",type:"string"},Lr={name:"prompt",type:"string"},Fd={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},Wd=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],xo={name:"options",type:"map",optional:!0,keys:Wd},UN={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},FN={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},jN={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Lo={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},jd={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},iq=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"},{name:"reconcile",type:"boolean"}],WN={name:"options",type:"map",optional:!0,keys:iq},HN={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},XN=Cr([{name:"resolveProfilePath",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"classifyFailure",implemented:!0,params:[{name:"text",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"model",type:"string"},{name:"status",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null",class:"string",rule:"string|null"},effects:[],summary:"Classify a recorded provider failure text by the one classifier; text no rule recognises is `unknown`, never the nearest class.",scriptBinding:{name:"lm_classify_failure",params:[{name:"text",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"model",type:"string"},{name:"status",type:"string"}]}]}},{name:"readPrompts",implemented:!0,params:[se,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[se,Tn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[Tn]}},{name:"resolveMember",implemented:!0,params:[se,Tn,Ud],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[Tn,Ud]}},{name:"lintTeam",implemented:!0,params:[se,Tn],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[Tn]}},{name:"seedTeam",implemented:!0,params:[se,Tn,UN],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[Tn,UN]}},{name:"promptAgent",implemented:!0,params:[se,Fd,Lr,xo],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...HN,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Fd,Lr,xo]}},{name:"promptMember",implemented:!0,params:[se,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...Wd]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",errorKind:"cycle|provider|target?",code:"ErrorCode?",errorClass:"string|null",usage:"map|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[Tn,Ud,Lr,{name:"options",type:"map",optional:!0,keys:[...Wd,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[se,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[se,Lo,jN],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[Fd,{...jN,optional:!0}]}},{name:"getSession",implemented:!0,params:[se,Lo],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages.",scriptBinding:{name:"lm_session_get",params:[Lo]}},{name:"reserveSession",implemented:!0,params:[se,Lo],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[se,Lo,{name:"reservation",type:"SessionReservation",optional:!0}],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission; an optional capability makes owned cleanup idempotent and replacement-safe."},{name:"openTeamBatch",returnsResource:!0,implemented:!0,params:[se,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...Wd]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[se,{name:"batch",type:"BatchRef"},Lr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[se,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[se,FN],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[FN]}},{name:"openTerminal",implemented:!0,params:[se,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[Tn,Ud]}},{name:"sessionAdmission",implemented:!0,params:[se,Lo],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[se,{name:"reservation",type:"SessionReservation"},Fd,Lr,xo],statuses:["ok","busy","stalled","empty","error"],results:{...HN,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[se,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Synchronously release one batch on a close deadline without cancelling unrelated batches."},{name:"inspectBatch",implemented:!0,params:[se,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"openNativeSession",returnsResource:!0,implemented:!0,params:[se,{name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},xo],statuses:["ok","busy","error"],results:{error:"string|null",session:"opaque context-bound NativeSessionRef"},effects:["provider","db","file-read"],summary:"Open a script-owned native conversation with existing receiver admission."},{name:"nativeSessionTurn",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"},Lr],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Record one unframed conversational turn through the existing recorder."},{name:"closeNativeSession",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close a script-owned native conversation and release its lease."},{name:"finalizeNativeSessionSync",implemented:!0,params:[se,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Critical synchronous native conversation lease release."},{name:"nativeSessionRequest",implemented:!0,params:[se,jd,Lr,xo],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Send a stateless native-id turn to a qualified conversation in the configured running lmbee service.",scriptBinding:{name:"lm_session_turn",params:[jd,Lr,xo]}},{name:"nativeSessionClose",implemented:!0,params:[se,jd],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Close an idle service-hosted native conversation; an absent entry is already closed.",scriptBinding:{name:"lm_session_close",params:[jd]}},{name:"loadProperties",implemented:!0,params:[se,M_],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."},{name:"listRunning",implemented:!0,params:[se,WN],statuses:["ok","error"],results:{error:"string|null",running:"RunningRow[]",dead:"DeadRow[]",idle:"IdleRow[]"},effects:["db"],summary:"DB-wide view of tracked invocation activity. Read-only unless reconcile:true, which also aborts rows whose holder is confirmed dead. Dispatch and branch on status busy, never gate on this.",scriptBinding:{name:"lm_running",params:[WN]}}])});function qN(t){if(!$N(t))return gt("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return gt("cancelled","Context is closed")}function GN(t){return XN.find(e=>e.name===t)?.params.find(e=>e.name==="options")?.keys?.map(e=>e.name)??[]}var VN=C(()=>{"use strict";$_();Pd();Qc()});import{isAbsolute as aq,resolve as lq}from"node:path";function Bd(t){return Number.isFinite(t)&&Math.abs(t)<=cq}function dq(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(BN.includes(e))return e;if(e==="SQLITE_BUSY"||e==="SQLITE_LOCKED")return"busy";if(e==="SQLITE_READONLY"||e.startsWith("SQLITE_READONLY")||e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT"||e==="SQLITE_CANTOPEN")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}let n=t.message;if(typeof n=="string"){if(n.includes("readonly database")||n.includes("SQLITE_READONLY"))return"read";if(n.includes("database is locked")||n.includes("SQLITE_BUSY"))return"busy"}}return"internal"}function F_(t,e=Date.now()){if(t===void 0)return{windowMs:JN};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let o=Number(n[1]),i=n[2],l=(i==="s"?o:i==="m"?o*60:i==="h"?o*3600:o*86400)*1e3;return!Number.isFinite(l)||l<0||!Bd(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Bd(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Bd(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Hd(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function U_(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return P_;let s=e.get(n);if(s===void 0){try{s=Ie(n)}catch{s=null}e.set(n,s)}return s===null?P_:Nl(s,r)?.model??P_}async function KN(t,e={}){let n=qN(t);if(n)return{status:"error",error:n.error,code:n.code,running:[],dead:[],idle:[]};if(e!=null){if(typeof e!="object"||Array.isArray(e))return{status:"error",error:"Options must be a map",code:"invalid_argument",running:[],dead:[],idle:[]};let o=GN("listRunning");if(o.length>0){for(let i of Object.keys(e))if(!o.includes(i))return{status:"error",error:`Unknown option: ${i}`,code:"invalid_argument",running:[],dead:[],idle:[]}}if(e.teamfile!==void 0&&(typeof e.teamfile!="string"||!e.teamfile.trim()))return{status:"error",error:"teamfile must be a nonempty string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.member!==void 0&&typeof e.member!="string")return{status:"error",error:"member must be a string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.reconcile!==void 0&&typeof e.reconcile!="boolean")return{status:"error",error:"reconcile must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.tree!==void 0&&typeof e.tree!="boolean")return{status:"error",error:"tree must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]}}let r=t.clock(),s=JN;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Bd(r-e.since))return{status:"error",error:"since must be a non-negative number of milliseconds within representable date range",code:"invalid_argument",running:[],dead:[],idle:[]};s=e.since}else if(typeof e.since=="string"){let o=F_(e.since,r);if("error"in o)return{status:"error",error:o.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=o.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let o=DN(t),i=e?.teamfile!==void 0?aq(e.teamfile)?e.teamfile:lq(t.cwd,e.teamfile):void 0,a=i!==void 0?Ne(i,o):void 0,l=e?.member!==void 0?e.member.toLowerCase():void 0,c=y=>!(a!==void 0&&y.target_teamfile!==a||l!==void 0&&(y.target_alias??"").toLowerCase()!==l),d=o.listAllRunningTrackedInvocations().filter(c),u=new Map,f=[],m=[];for(let y of d){let w=ar(y),T=r-new Date(y.started_at).getTime(),S={id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:Hd(y),model:U_(y,u),started_at:y.started_at,parent_invocation_id:y.parent_invocation_id};if(w==="dead"){if(e?.reconcile===!0&&Lf(o,y)!==null)continue;m.push({...S,age_ms:T})}else f.push({...S,running_for_ms:T,holder_liveness:w??"unknown"})}let p=new Set(d.map(Hd).filter(y=>y!==null)),_=new Date(r-s).toISOString(),h=o.listRecentlyFinishedTrackedInvocations(_).filter(c),g=new Set,E=[];for(let y of h){let w=Hd(y);w===null||p.has(w)||g.has(w)||(g.add(w),E.push({id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:w,model:U_(y,u),status:y.status,started_at:y.started_at,ended_at:y.ended_at,idle_ms:r-new Date(y.ended_at).getTime(),ran_ms:new Date(y.ended_at).getTime()-new Date(y.started_at).getTime(),error:y.error,parent_invocation_id:y.parent_invocation_id}))}if(e?.tree===!0){let y=new Set([...f.map(T=>T.id),...m.map(T=>T.id),...E.map(T=>T.id)]),w=[...y];for(;w.length>0;){let T=o.listFinishedTrackedInvocationChildren(w,_).filter(S=>!y.has(S.id)&&c(S));if(T.length===0)break;w=[];for(let S of T){y.add(S.id),w.push(S.id);let k=Hd(S);E.push({id:S.id,kind:S.kind,origin:S.origin,from_identity:S.from_identity,target:k,model:U_(S,u),status:S.status,started_at:S.started_at,ended_at:S.ended_at,idle_ms:r-new Date(S.ended_at).getTime(),ran_ms:new Date(S.ended_at).getTime()-new Date(S.started_at).getTime(),error:S.error,parent_invocation_id:S.parent_invocation_id})}}}return{status:"ok",error:null,running:f,dead:m,idle:E}}catch(o){return{status:"error",error:o instanceof Error?o.message:String(o),code:dq(o),running:[],dead:[],idle:[]}}}var JN,cq,P_,YN=C(()=>{"use strict";Pd();VN();$_();Wt();Ul();ze();on();JN=24*60*60*1e3,cq=864e13;P_="default"});var n0={};me(n0,{_setRunningWatchMaxTicksForTests:()=>mq,runRunning:()=>vq});import{resolve as uq}from"node:path";function mq(t){W_=t??void 0}function hq(t){let e=t.split(`
2631
+ `,1)[0];return e.length<=H_?e:`${e.slice(0,H_)}\u2026`}function B_(t){return t.target!==null?wn(t.target):t.from_identity}function QN(t){return[(0,Pt.escapeCell)(B_(t)),t.kind,"running",t.holder_liveness,(0,Pt.escapeCell)(t.model),ka(t.started_at)]}function ZN(t){return[(0,Pt.escapeCell)(B_(t)),t.kind,"DEAD","",(0,Pt.escapeCell)(t.model),`started ${ka(t.started_at)}, holder process confirmed dead`]}function e0(t){let e=`ran ${$d(t.ran_ms)}, idle ${ka(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,Pt.escapeCell)(El(t.error,H_)??hq(t.error))}`),[(0,Pt.escapeCell)(B_(t)),t.kind,t.status,"",(0,Pt.escapeCell)(t.model),e]}function j_(t){return t.filter(e=>e!=="").join(" ")}function t0(t){let e=new Map(t.map(o=>[o.id,o])),n=new Map,r=[];for(let o of t){let i=o.parent_invocation_id;if(i!==null&&e.has(i)){let a=n.get(i)??[];a.push(o),n.set(i,a)}else r.push(o)}let s=(o,i)=>i.started_at.localeCompare(o.started_at);r.sort(s);for(let o of n.values())o.sort(s);return{roots:r,childrenByParent:n}}function gq(t){let{roots:e,childrenByParent:n}=t0(t),r=[],s=(o,i)=>{r.push(`${" ".repeat(i+1)}${o.line}`);for(let a of n.get(o.id)??[])s(a,i+1)};for(let o of e)s(o,0);return r}function yq(t,e,n){let r=[...t.map(a=>({state:"running",...a})),...e.map(a=>({state:"dead",...a})),...n.map(a=>({state:"idle",...a}))],{roots:s,childrenByParent:o}=t0(r),i=a=>({...a,children:(o.get(a.id)??[]).map(i)});return s.map(i)}function Eq(t,e){return e?{schema_version:zN,tree:yq(t.running,t.dead,t.idle)}:{schema_version:zN,running:t.running,dead:t.dead,idle:t.idle}}function wq(t){let e=[...t.running.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(QN(r))})),...t.dead.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(ZN(r))})),...t.idle.map(r=>({id:r.id,parent_invocation_id:r.parent_invocation_id,started_at:r.started_at,line:j_(e0(r))}))],n=gq(e);return`${n.length>0?n.join(`
2632
2632
  `):" none"}
2633
2633
  `}function Tq(t,e){let n=[{title:`Running (${t.running.length}):`,rows:t.running.map(QN)},{title:`Dead (reclaimable) (${t.dead.length}):`,rows:t.dead.map(ZN)},{title:`Idle, finished in the last ${$d(e)} (${t.idle.length}):`,rows:t.idle.map(e0)}],r=["MEMBER","KIND","STATE","LIVENESS","MODEL","TIMING"],s=(0,Pt.measureColumns)([{rows:[],headers:r},...n.map(a=>a.rows)],{max:_q}),o=!1,i=[];return n.forEach((a,l)=>{if(l>0&&i.push(""),i.push(a.title),a.rows.length===0){i.push(" none");return}let c=!o;o=!0,i.push((0,Pt.renderGrid)(a.rows,{widths:s,margin:2,...c?{headers:r}:{}}))}),`${i.join(`
2634
2634
  `)}
2635
2635
  `}async function vq(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${pq}
2636
2636
  `),0;let n=ae(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch","--reconcile"]);if(n.error!==void 0)return D(e,n.error);let r=Y(n,"--json"),s=Y(n,"--tree"),o=Y(n,"--watch"),i=V(n,"--team"),a=V(n,"--member"),l=F_(V(n,"--since"));if("error"in l)return D(e,l.error);let c=V(n,"--watch-interval"),d=c===void 0?fq:Number.parseInt(c.replace(/s$/,""),10);if(!Number.isFinite(d)||d<1)return D(e,`invalid --watch-interval "${c}" (expected <N>s, N\u22651)`);let u=()=>W(e,async f=>{let m=PN({cwd:uq(e.cwd??process.cwd()),env:e.env??process.env,dal:f,dbPath:Ce(e)});if(m.status!=="ok")return D(e,m.error);let p=await KN(m,{teamfile:i,member:a,since:V(n,"--since"),tree:s,reconcile:Y(n,"--reconcile")});if(p.status!=="ok")return D(e,p.error??"listRunning failed");if(r){let _=Eq(p,s);return o?e.stdout.write(`${JSON.stringify(_)}
2637
2637
  `):Z(e,_),0}return e.stdout.write(s?wq(p):Tq(p,l.windowMs)),0});return o?await new Promise(f=>{let m=0,p=!1,_=E=>{clearInterval(E),f(0)},h=async E=>{if(!p){p=!0;try{await u()}catch(y){e.stderr.write(`running: ${y instanceof Error?y.message:String(y)}
2638
- `)}finally{p=!1}m+=1,W_!==void 0&&m>=W_&&_(E)}},g=setInterval(()=>{h(g)},d*1e3);h(g),process.once("SIGINT",()=>_(g)),process.once("SIGTERM",()=>_(g))}):u()}var Pt,zN,fq,W_,pq,H_,_q,r0=C(()=>{"use strict";Pt=Ft(Ct(),1);Pd();YN();le();D_();It();zN=3,fq=2;pq=["usage: lmctl running [--team <file>] [--member <alias>] [--since <duration|ISO8601>]"," [--tree] [--reconcile] [--watch] [--watch-interval Ns] [--json]","","Shows tracked_invocation activity DB-wide across the whole fleet, split","into three sections (flat mode, the default):",' - Running: status="running" with a live (or unverifiable cross-host)'," holder -- genuinely in-flight work.",' - Dead (reclaimable): status="running" but the holder process is'," confirmed dead -- an orphaned record, not active work. Its elapsed",' time is reported as staleness, not as "running", so a dead worker'," is never mistaken for one that is genuinely still building."," - Idle: targets with nothing running or dead, showing their most"," recent finish from the last 24 hours and how long they've been"," idle since.",' A finish that failed ends with " \u2014 " and one line of the failure:'," for a provider failure the end of the provider's own output, for"," any other error its first line. It is a pointer, not the full"," error: --json has the complete text.","","--team <file> narrows the view to one teamfile (path is canonicalized","before matching); --member <alias> narrows it to one member alias","(case-insensitive; combinable with --team). --since sets the lookback","window for the Idle section -- a relative duration (<n>s|m|h|d, e.g. 7d)","or an absolute ISO8601 timestamp (default 24h). Running and Dead are","point-in-time current state and are not time-filtered.","","Looking is read-only: a dead holder is listed under Dead and left as it is.","Dispatch reconciles dead holders for its receiver. Scheduled lmbee maintenance","explicitly opts into --reconcile, which aborts confirmed-dead rows and","terminalizes their linked messages. Ordinary reads do not reconcile them.","","--watch re-renders the full snapshot every --watch-interval (default 2s)","until interrupted (SIGINT/SIGTERM). With --json, each snapshot is emitted","as ONE compact JSON object per line (NDJSON).","","--tree shows the same rows as one hierarchical dispatch-lineage view","instead: no section headers (each row already carries its own status),","indented under the session that dispatched it (who woke whom), sorted","by the most recent root session first. A node is a specific turn at a","specific time, not a team:alias identity -- the same member can appear","as multiple nodes for its different turns. Lineage is only known for","turns dispatched by a NESTED `lmctl prompt`/`lmctl terminal` call made","from within another turn's own tool calls; anything else (a human's","direct dispatch, or a turn from before this feature existed) has no","recorded parent and shows as its own root. Unlike the flat Idle section,","--tree does NOT collapse finished rows to one per target: every finished","descendant of a node in view (within the --since window) is rendered, so","a `lmctl batch` run shows as its batch root with ALL of its per-prompt","turns nested underneath.","","Every row also carries `model`: the target member's declared `model=`",'read straight from its teamfile (no session/provider query) -- "default"',"when the teamfile has no model= attribute, the alias/file can't be","resolved, or there is no target at all. This is the DECLARED value only,","not necessarily what actually ran (see the MODEL column in `lmctl status","<teamfile> --details`).","","--json emits { schema_version, running, dead, idle } (flat, one array","per section, matching the three flat-mode sections -- each row carries","its own status/timing/error fields). --tree --json instead emits","{ schema_version, tree } -- an array of root nodes, each row's full",'fields plus a "state" discriminant ("running"/"dead"/"idle") and a','"children" array of the same shape, nested per the dispatch lineage.',"","Queries lmctl's own database only -- never touches native provider","session files."].join(`
2638
+ `)}finally{p=!1}m+=1,W_!==void 0&&m>=W_&&_(E)}},g=setInterval(()=>{h(g)},d*1e3);h(g),process.once("SIGINT",()=>_(g)),process.once("SIGTERM",()=>_(g))}):u()}var Pt,zN,fq,W_,pq,H_,_q,r0=C(()=>{"use strict";Pt=Ft(Ct(),1);Pd();YN();le();D_();It();zN=4,fq=2;pq=["usage: lmctl running [--team <file>] [--member <alias>] [--since <duration|ISO8601>]"," [--tree] [--reconcile] [--watch] [--watch-interval Ns] [--json]","","Shows tracked_invocation activity DB-wide across the whole fleet, split","into three sections (flat mode, the default):",' - Running: status="running" with a live (or unverifiable cross-host)'," holder -- genuinely in-flight work.",' - Dead (reclaimable): status="running" but the holder process is'," confirmed dead -- an orphaned record, not active work. Its age (time"," since it started; the moment the holder died is not recorded) is",' reported as "age_ms", not as "running", so a dead worker is never'," mistaken for one that is genuinely still building."," - Idle: targets with nothing running or dead, showing their most"," recent finish from the last 24 hours and how long they've been"," idle since.",' A finish that failed ends with " \u2014 " and one line of the failure:'," for a provider failure the end of the provider's own output, for"," any other error its first line. It is a pointer, not the full"," error: --json has the complete text.","","--team <file> narrows the view to one teamfile (path is canonicalized","before matching); --member <alias> narrows it to one member alias","(case-insensitive; combinable with --team). --since sets the lookback","window for the Idle section -- a relative duration (<n>s|m|h|d, e.g. 7d)","or an absolute ISO8601 timestamp (default 24h). Running and Dead are","point-in-time current state and are not time-filtered.","","Looking is read-only: a dead holder is listed under Dead and left as it is.","Dispatch reconciles dead holders for its receiver. Scheduled lmbee maintenance","explicitly opts into --reconcile, which aborts confirmed-dead rows and","terminalizes their linked messages. Ordinary reads do not reconcile them.","","--watch re-renders the full snapshot every --watch-interval (default 2s)","until interrupted (SIGINT/SIGTERM). With --json, each snapshot is emitted","as ONE compact JSON object per line (NDJSON).","","--tree shows the same rows as one hierarchical dispatch-lineage view","instead: no section headers (each row already carries its own status),","indented under the session that dispatched it (who woke whom), sorted","by the most recent root session first. A node is a specific turn at a","specific time, not a team:alias identity -- the same member can appear","as multiple nodes for its different turns. Lineage is only known for","turns dispatched by a NESTED `lmctl prompt`/`lmctl terminal` call made","from within another turn's own tool calls; anything else (a human's","direct dispatch, or a turn from before this feature existed) has no","recorded parent and shows as its own root. Unlike the flat Idle section,","--tree does NOT collapse finished rows to one per target: every finished","descendant of a node in view (within the --since window) is rendered, so","a `lmctl batch` run shows as its batch root with ALL of its per-prompt","turns nested underneath.","","Every row also carries `model`: the target member's declared `model=`",'read straight from its teamfile (no session/provider query) -- "default"',"when the teamfile has no model= attribute, the alias/file can't be","resolved, or there is no target at all. This is the DECLARED value only,","not necessarily what actually ran (see the MODEL column in `lmctl status","<teamfile> --details`).","","--json emits { schema_version, running, dead, idle } (flat, one array","per section, matching the three flat-mode sections -- each row carries","its own status/timing/error fields). --tree --json instead emits","{ schema_version, tree } -- an array of root nodes, each row's full",'fields plus a "state" discriminant ("running"/"dead"/"idle") and a','"children" array of the same shape, nested per the dispatch lineage.',"","Queries lmctl's own database only -- never touches native provider","session files."].join(`
2639
2639
  `),H_=120;_q=[26,void 0,void 0,void 0,24,void 0]});var i0={};me(i0,{runPrices:()=>kq});import{existsSync as Sq}from"node:fs";import{resolve as s0}from"node:path";function Xd(t,e,n="price snapshot unavailable"){return e?Z(t,{schema_version:1,status:"unavailable",reason:n}):t.stdout.write(`unavailable: ${n}
2640
2640
  `),0}function bq(t){let e=t?.code;return typeof e=="string"&&/SQLITE_(BUSY|LOCKED|READONLY|CANTOPEN)/.test(e)}function o0(t){return t.dal!==void 0?{db:t.dal,owned:!1}:{db:Fe({path:Ce(t),recover:!1}),owned:!0}}function Iq(t){if(t.owned)try{t.db.close()}catch{}}async function kq(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(qd),0;let n=t[0];return n!=="update"&&n!=="show"?(e.stderr.write(`error: expected update or show
2641
2641
  ${qd}`),2):n==="update"?Aq(t.slice(1),e):Nq(t.slice(1),e)}async function Aq(t,e){let n=ae(t,["--aliases"],["--json"]);if(n.error||n.positionals.length>1)return e.stderr.write(`error: ${n.error??"update accepts at most one FILE"}