@lmctl-ai/lmctl 0.2.353 → 0.2.355
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 +1 -1
- package/dist/cli/index.js +207 -207
- package/dist/cli/lmscript.js +2 -2
- package/dist/lmbee.js +3 -3
- package/package.json +1 -1
package/dist/cli/lmscript.js
CHANGED
|
@@ -514,7 +514,7 @@ Calls return {status:"ok", result} | {status:"error", error:{code, message}} | {
|
|
|
514
514
|
`).slice(-12).join(`
|
|
515
515
|
`)));return c.stdout},s=(c,u,d)=>rr(n(c,u,d),r),i=(c,u,d)=>rr(s(c,["rev-parse","--verify","--end-of-options",Bv(u,"revision")],d),uc),o=({r:c})=>c.code===1&&!c.stderr&&!c.signal&&!c.timed_out,a=(c,u)=>rr(n(c,["symbolic-ref","--quiet","--short","HEAD"],u),d=>o(d)?null:uc(r(d)));return{functions:{"git.status":(c,u)=>rr(s(c,["status","--porcelain=v2","-z","--branch","--ahead-behind","--untracked-files=all","--renames"],u),d=>{let m=Hv(d);return m.detached?rr(a(c,u),p=>(p!==null&&(m.branch=p,m.detached=!1),m)):m}),"git.branch":a,"git.rev_parse":i,"git.remotes":(c,u)=>rr(n(c,["config","--null","--get-regexp","^remote\\..*\\.url$"],u),d=>{if(o(d))return[];let p=r(d).split("\0");if(p.pop()!=="")throw Error("git: incomplete remote config");return p.map(f=>{let h=f.indexOf(`
|
|
516
516
|
`),g=f.slice(0,h).match(/^remote\.(.+)\.url$/);if(h<0||!g)throw Error("git: malformed remote config");return{name:g[1],url:f.slice(h+1)}})}),"git.log":(c,u,d)=>{if(typeof u!="number"||!Number.isInteger(u)||u<0||u>1e4)throw Error("git.log: n must be an integer from 0 to 10000");return rr(n(c,["rev-parse","--verify","--quiet","--end-of-options","HEAD"],d),m=>o(m)?[]:(r(m),u===0?[]:rr(s(c,["log","--no-show-signature","--encoding=UTF-8","-n",String(u),"--format=%H%x00%an%x00%aI%x00%B","-z","--"],d),Wv)))}},globals:{},dispose(){}}}var rr,uc,FM,Xv=L(()=>{"use strict";rr=(t,e)=>t instanceof Promise?t.then(e):e(t),uc=t=>t.endsWith(`
|
|
517
|
-
`)?t.slice(0,-1):t,FM=t=>t.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1<redacted>@").replace(/([?&](?:access_token|token|password|passwd|api_key)=)[^&\s"'<>]+/gi,"$1<redacted>")});var LK,Lr,ta,UM,BM,$p,HM,Up,be,jp,xn,dc,Or,mc,fc,ki,Gv,Jv,Vv,Ri,pc,WM,Kv,zv,wt,sr=L(()=>{"use strict";LK=1,Lr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Lr(e);Object.freeze(t)}return t},ta=Lr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),UM=Lr({status:"string",error:"string|null",code:"ErrorCode?"}),BM=Lr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),$p=Lr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),HM=Lr(["Provider1","Provider2","Provider3"]),Up=Lr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),be={name:"ctx",type:"context"},jp={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},xn={name:"teamfile",type:"string"},dc={name:"alias",type:"string"},Or={name:"prompt",type:"string"},mc={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"}]},fc=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],ki={name:"options",type:"map",optional:!0,keys:fc},Gv={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},Jv={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},Vv={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Ri={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},pc={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"}]},WM=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"}],Kv={name:"options",type:"map",optional:!0,keys:WM},zv={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},wt=Lr([{name:"resolveProfilePath",implemented:!0,params:[be,jp],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[be,jp],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:[be,{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:[be,xn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[xn]}},{name:"resolveMember",implemented:!0,params:[be,xn,dc],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:[xn,dc]}},{name:"lintTeam",implemented:!0,params:[be,xn],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:[xn]}},{name:"seedTeam",implemented:!0,params:[be,xn,Gv],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:[xn,Gv]}},{name:"promptAgent",implemented:!0,params:[be,mc,Or,ki],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...zv,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[mc,Or,ki]}},{name:"promptMember",implemented:!0,params:[be,{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"},...fc]}],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:[xn,dc,Or,{name:"options",type:"map",optional:!0,keys:[...fc,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[be,{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:[be,Ri,Vv],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:[mc,{...Vv,optional:!0}]}},{name:"getSession",implemented:!0,params:[be,Ri],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:[Ri]}},{name:"reserveSession",implemented:!0,params:[be,Ri],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:[be,Ri,{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:[be,{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"},...fc]}],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:[be,{name:"batch",type:"BatchRef"},Or,{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:[be,{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:[be,Jv],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:[Jv]}},{name:"openTerminal",implemented:!0,params:[be,{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:[xn,dc]}},{name:"sessionAdmission",implemented:!0,params:[be,Ri],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:[be,{name:"reservation",type:"SessionReservation"},mc,Or,ki],statuses:["ok","busy","stalled","empty","error"],results:{...zv,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[be,{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:[be,{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:[be,{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"}]},ki],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:[be,{name:"session",type:"NativeSessionRef"},Or],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:[be,{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:[be,{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:[be,pc,Or,ki],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:[pc,Or,ki]}},{name:"nativeSessionClose",implemented:!0,params:[be,pc],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:[pc]}},{name:"loadProperties",implemented:!0,params:[be,jp],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:[be,Kv],statuses:["ok","error"],results:{error:"string|null",running:"RunningRow[]",dead:"DeadRow[]",idle:"IdleRow[]"},effects:["db"],summary:"DB-wide view of tracked invocation activity. Observation only; dispatch and branch on status busy, never gate on this.",scriptBinding:{name:"lm_running",params:[Kv]}}])});var Yv,Qv=L(()=>{"use strict";Yv=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a service-hosted conversation addressed by provider and native sessionid. Qualified providers require the already-running lmbee endpoint in LMCTL_SERVICE_ENDPOINT. idleTimeoutMs controls idle retention (default 300000 ms; zero disables expiry). An accepted turn finishes and is recorded after the caller disconnects. World failures never throw. This is an effect and is skipped in dry-run with a map dummy; one-shot providers stay local.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid; optional sessiondir, model, effort"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode and idleTimeoutMs"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id, code?, outcome?, service_epoch?, connection_epoch?, connection_state? }"},example:'res = lm_session_turn({ provider: "kimi", sessionid: "native-1" }, "Continue");'},{name:"lm_session_close",category:"lmctl Automation",signature:"lm_session_close(member)",description:"Requests closure of the service-owned conversation addressed by provider and native sessionid. Idle conversations close, active conversations return busy, and an absent entry is already closed. World failures never throw; dry-run returns a map dummy.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid"}],returns:{type:"map",description:'{ status: "ok"|"busy"|"error", error: string|null, code?: string }'},example:'closed = lm_session_close({ provider: "kimi", sessionid: "native-1" });'},{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. A handoff reservation is host-owned and released on EOF, provider failure, cancellation, context finalization or signal; the returned outcome is an ordinary map. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens the only returned production resource: an async-only opaque read-only id handle. The first receiving lexical binding owns it until scope exit; aliases borrow, and returning/storing/coercing the handle is refused at runtime. Teamfile batches keep existing admission. A member map with provider and sessionid locks an existing native session: one known owner uses its teamfile and alias lease, otherwise the native address is the lease key. Native handles reuse one persistent conversation when supported, or one provider process per turn, and record each turn. A member map without sessionid retains the fresh-agent batch path. Dry-run simulates these resource operations without provider or lease activity.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"ResourceHandle|null",description:"Opaque id-only handle, or null on admission refusal; no mutable map or transferable authority"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index?, total?)",description:"Native handles accept handle and prompt only for dependent conversational turns; teamfile and fresh-member batches still require index and total. Each native turn uses the existing transcript and usage recorder.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Same-run live owner/borrower handle or authorized id reference"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"Teamfile or fresh-member form only: 1-based prompt index"},{name:"total",type:"number",description:"Teamfile or fresh-member form only: total prompts"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'empty'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch resource. Native handles close their conversation and release the owned lease; scope exit, script error, exit, and signals also close them. Teamfile batches retain tracked-invocation and bundle cleanup.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Authorized handle/id; repeat close joins the same operation"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns an ordinary result map. The host owns its pending per-turn lease and critical release; no returned resource or script closer.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, error_class, usage, message_id, team_chat_log_id, error_kind?, code? } - error_kind (cycle|provider|target) names the stage that failed and an internal fault stops the script instead of returning; error_class is null for a turn that did not fail, else one of quota_exhausted, binary_missing, auth_required, upstream_undisclosed, upstream_throttled, model_not_offered, stale_session, transport_interrupted, context_exhausted, receiver_busy, holder_died or unknown (decided by lmctl, never by the script), and usage is null or what the provider reported: { source, reason, inputUncached, cacheRead, cacheWrite, output, reasoning, modelReported, costUsd (an ESTIMATE at API reference rates, not a subscription charge), costReason, providerCostUsd }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent"); if (res.error_class != null) { println(res.error_class); }'},{name:"lm_classify_failure",category:"lmctl Automation",signature:"lm_classify_failure(text, options = {})",description:"Classifies a recorded provider failure text with the same classifier lm_prompt uses for live turns, so a script reading stored errors (for example tracked_invocation.error) never carries its own regex table. Pure: no database, provider or file access. Text no rule recognises is unknown, never the nearest class.",parameters:[{name:"text",type:"string",description:"The recorded provider error text"},{name:"options",type:"map",description:"(optional) model: the model the failed attempt requested (enables the retired-model tell: the provider listing its own models); status: the recorded status, so empty text with busy, empty or stalled still classifies"}],returns:{type:"map",description:"{ status, error, class, rule } where class is one of the lm_prompt error_class values and rule names the matching rule (null for unknown)"},example:'c = lm_classify_failure("spawn kimi ENOENT"); println(c.class);'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_agent_message",category:"lmctl Automation",signature:"lm_agent_message(member, prompt, options = {})",description:"Like lm_agent, and also returns the completed turn as lmctl stores and prices it: model, token buckets and the lmprice cost of that turn. Cost is null (with costUnavailableReason) when the provider does not record enough accounting.",parameters:[{name:"member",type:"map",description:"As for lm_agent"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) As for lm_agent"}],returns:{type:"map",description:"lm_agent's { status, reply, error, message_id, team_chat_log_id } plus message: null | { role, content, provider, sessionid, model, usage: { input, cachedInput, cacheWrite, output }, costUsd, costUnavailableReason, priceRoute, priceDataSource }"},example:'agent = { provider: "miniplayer", model: "deepseek/deepseek-flash" }; res = lm_agent_message(agent, "Say hi"); println(res.message.costUsd);'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, sessions: [{ provider, sessionid, sessiondir, modifiedAt }] }'},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_get",category:"lmctl Automation",signature:"lm_session_get(target)",description:"Reads native session messages. Returns messages in chronological order, or not_found if the session does not exist.",parameters:[{name:"target",type:"map",description:"Session target map with required provider and sessionid strings"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, messages?: [{ role: string, content: string }] }'},example:'session = lm_session_get({ provider: "codex", sessionid: "sess-123" }); if (session.status == "ok") { println(len(session.messages)); }'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_running",category:"lmctl Automation",signature:"lm_running(options = {})",description:'Returns active tracked-invocation snapshot. Options: since (e.g. "1h", "2d"). observation only; dispatch and branch on status busy, never gate on this.',parameters:[{name:"options",type:"map",description:'(optional) Query options: since (duration string like "1h", "2d")'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, running: map[], dead: map[], idle: map[] }'},example:'snapshot = lm_running(); if (snapshot.status == "ok") { println(len(snapshot.running)); }'},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, seeded: [{ alias, provider, sessionid, sessiondir, model }] }'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. The host attempts checked lock/invocation release on completion, failure, cancellation or signal and reports unresolved failures, including a busy database; the returned outcome is an ordinary map. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, exit_code: number, signal: string|null, code?: string }'},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", error: null, readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, members: [{ alias, provider, model, sessionid, sessiondir }] }'},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, member?: { alias, provider, model, sessionid, sessiondir }, isLead?: bool, teamfile?: string }'},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function z(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function he(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var ft=L(()=>{"use strict"});function ew(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?na:Zv}var Zv,na,Bp=L(()=>{"use strict";Zv="root_teamfile <> '(direct)'",na=Zv+" AND COALESCE(accounting_only,0)=0"});import{existsSync as qM}from"node:fs";import{createRequire as XM}from"node:module";function GM(){return Hp===null&&(Hp=XM(import.meta.url)("node:sqlite").DatabaseSync),Hp}function KM(t){let e=VM[t];if(e!==void 0)return e;let n=JM[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function Ls(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=KM(t.errcode)),t}function zM(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function YM(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function Wp(t){return t.length===1&&QM(t[0])?[t[0]]:t}function QM(t){if(!Gp(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Gp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Hp,JM,VM,qp,Ms,Xp,ra=L(()=>{"use strict";Hp=null;JM={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},VM={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};qp=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!qM(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(GM())(e,{readOnly:n.readonly===!0})}catch(r){Ls(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new Xp(this.handle.prepare(e))}catch(n){Ls(n)}}exec(e){try{this.handle.exec(e)}catch(n){Ls(n)}}pragma(e,n){let r=`PRAGMA ${e}`;if(e.includes("=")){this.exec(r);return}if(n?.simple===!0){let s=this.prepare(r).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(r).all()}transaction(e){let n=(...r)=>this.runTransaction("BEGIN",e,r);return n.immediate=(...r)=>this.runTransaction("BEGIN IMMEDIATE",e,r),n}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){Ls(e)}}runTransaction(e,n,r){if(!this.inTransaction){this.exec(e);try{let i=n(...r);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!zM(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=n(...r);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!YM(o))throw o}throw i}}};Ms=qp,Xp=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...Wp(e));return this.normalizeRow(n)}catch(n){Ls(n)}}all(...e){try{return this.handle.all(...Wp(e)).map(n=>this.normalizeRow(n))}catch(n){Ls(n)}}run(...e){try{let n=this.handle.run(...Wp(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){Ls(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Gp(e)?Object.values(e):Gp(e)?{...e}:e}}});function gc(t){return new Ms(t,{readonly:!0,fileMustExist:!0})}var Jp=L(()=>{"use strict";ra()});import{createHash as ZM}from"node:crypto";import{lstat as eP,readFile as tP,realpath as tw,stat as nw}from"node:fs/promises";import{isAbsolute as rw,relative as nP,resolve as rP,sep as sP}from"node:path";function Y(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function oe(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function sa(t){return oe(t)}function Gt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function we(t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t.maxRows)||t.maxRows<=0)throw new Error("maxRows must be a positive safe integer");t.signal.throwIfAborted()}function xe(t,e){return t<e?-1:t>e?1:0}function Et(t,e,n){if(t===null||e===null)return null;let r=n==="written"?"write":"read",s=0;for(let i of t){if(i.bytes===null)return null;s+=i.bytes}for(let i of e)if(i.direction===r){if(i.bytes===null)return null;s+=i.bytes}return s}function In(t,e,n){let r={},s=sa(t.cacheWrite5m),i=sa(t.cacheWrite1h),o=sa(t.reasoning),a=sa(t.webSearch),l=sa(t.webFetch);o!==null&&(e===null||o<=e)&&(r.reasoning_output_tokens=o);let c=(s??0)+(i??0),u=n===null||c<=n;return s!==null&&u&&(r.cache_write_5m_tokens=s),i!==null&&u&&(r.cache_write_1h_tokens=i),a!==null&&(r.web_search_requests=a),l!==null&&(r.web_fetch_requests=l),Object.keys(r).length>0?r:null}function Mr(t){return typeof t=="string"&&oP.has(t.toLowerCase())}function Be(t,e){t.record({direction:"read",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"}),t.record({direction:"write",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"})}function xi(t){let e=Y(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function tt(t,e){if(!rw(t))return null;let n=await eP(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await tw(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await tw(s).catch(()=>rP(s)),o=nP(i,r);if(o===""||!o.startsWith(`..${sP}`)&&o!==".."&&!rw(o))return r}return null}async function Ot(t,e){we(e);let n=await nw(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await tP(t,{signal:e.signal});e.signal.throwIfAborted();let s=await nw(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${ia}:sha256:${ZM("sha256").update(r).digest("hex")}`,data:r}}function hc(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=t.toString("utf8"),r=n.length===0?[]:n.slice(0,-1).split(`
|
|
517
|
+
`)?t.slice(0,-1):t,FM=t=>t.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1<redacted>@").replace(/([?&](?:access_token|token|password|passwd|api_key)=)[^&\s"'<>]+/gi,"$1<redacted>")});var LK,Lr,ta,UM,BM,$p,HM,Up,be,jp,xn,dc,Or,mc,fc,ki,Gv,Jv,Vv,Ri,pc,WM,Kv,zv,wt,sr=L(()=>{"use strict";LK=1,Lr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Lr(e);Object.freeze(t)}return t},ta=Lr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),UM=Lr({status:"string",error:"string|null",code:"ErrorCode?"}),BM=Lr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),$p=Lr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),HM=Lr(["Provider1","Provider2","Provider3"]),Up=Lr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),be={name:"ctx",type:"context"},jp={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},xn={name:"teamfile",type:"string"},dc={name:"alias",type:"string"},Or={name:"prompt",type:"string"},mc={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"}]},fc=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],ki={name:"options",type:"map",optional:!0,keys:fc},Gv={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},Jv={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},Vv={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Ri={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},pc={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"}]},WM=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"},{name:"reconcile",type:"boolean"}],Kv={name:"options",type:"map",optional:!0,keys:WM},zv={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},wt=Lr([{name:"resolveProfilePath",implemented:!0,params:[be,jp],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[be,jp],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:[be,{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:[be,xn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[xn]}},{name:"resolveMember",implemented:!0,params:[be,xn,dc],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:[xn,dc]}},{name:"lintTeam",implemented:!0,params:[be,xn],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:[xn]}},{name:"seedTeam",implemented:!0,params:[be,xn,Gv],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:[xn,Gv]}},{name:"promptAgent",implemented:!0,params:[be,mc,Or,ki],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...zv,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[mc,Or,ki]}},{name:"promptMember",implemented:!0,params:[be,{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"},...fc]}],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:[xn,dc,Or,{name:"options",type:"map",optional:!0,keys:[...fc,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[be,{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:[be,Ri,Vv],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:[mc,{...Vv,optional:!0}]}},{name:"getSession",implemented:!0,params:[be,Ri],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:[Ri]}},{name:"reserveSession",implemented:!0,params:[be,Ri],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:[be,Ri,{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:[be,{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"},...fc]}],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:[be,{name:"batch",type:"BatchRef"},Or,{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:[be,{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:[be,Jv],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:[Jv]}},{name:"openTerminal",implemented:!0,params:[be,{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:[xn,dc]}},{name:"sessionAdmission",implemented:!0,params:[be,Ri],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:[be,{name:"reservation",type:"SessionReservation"},mc,Or,ki],statuses:["ok","busy","stalled","empty","error"],results:{...zv,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[be,{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:[be,{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:[be,{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"}]},ki],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:[be,{name:"session",type:"NativeSessionRef"},Or],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:[be,{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:[be,{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:[be,pc,Or,ki],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:[pc,Or,ki]}},{name:"nativeSessionClose",implemented:!0,params:[be,pc],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:[pc]}},{name:"loadProperties",implemented:!0,params:[be,jp],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:[be,Kv],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:[Kv]}}])});var Yv,Qv=L(()=>{"use strict";Yv=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a service-hosted conversation addressed by provider and native sessionid. Qualified providers require the already-running lmbee endpoint in LMCTL_SERVICE_ENDPOINT. idleTimeoutMs controls idle retention (default 300000 ms; zero disables expiry). An accepted turn finishes and is recorded after the caller disconnects. World failures never throw. This is an effect and is skipped in dry-run with a map dummy; one-shot providers stay local.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid; optional sessiondir, model, effort"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode and idleTimeoutMs"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id, code?, outcome?, service_epoch?, connection_epoch?, connection_state? }"},example:'res = lm_session_turn({ provider: "kimi", sessionid: "native-1" }, "Continue");'},{name:"lm_session_close",category:"lmctl Automation",signature:"lm_session_close(member)",description:"Requests closure of the service-owned conversation addressed by provider and native sessionid. Idle conversations close, active conversations return busy, and an absent entry is already closed. World failures never throw; dry-run returns a map dummy.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid"}],returns:{type:"map",description:'{ status: "ok"|"busy"|"error", error: string|null, code?: string }'},example:'closed = lm_session_close({ provider: "kimi", sessionid: "native-1" });'},{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. A handoff reservation is host-owned and released on EOF, provider failure, cancellation, context finalization or signal; the returned outcome is an ordinary map. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens the only returned production resource: an async-only opaque read-only id handle. The first receiving lexical binding owns it until scope exit; aliases borrow, and returning/storing/coercing the handle is refused at runtime. Teamfile batches keep existing admission. A member map with provider and sessionid locks an existing native session: one known owner uses its teamfile and alias lease, otherwise the native address is the lease key. Native handles reuse one persistent conversation when supported, or one provider process per turn, and record each turn. A member map without sessionid retains the fresh-agent batch path. Dry-run simulates these resource operations without provider or lease activity.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"ResourceHandle|null",description:"Opaque id-only handle, or null on admission refusal; no mutable map or transferable authority"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index?, total?)",description:"Native handles accept handle and prompt only for dependent conversational turns; teamfile and fresh-member batches still require index and total. Each native turn uses the existing transcript and usage recorder.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Same-run live owner/borrower handle or authorized id reference"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"Teamfile or fresh-member form only: 1-based prompt index"},{name:"total",type:"number",description:"Teamfile or fresh-member form only: total prompts"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'empty'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch resource. Native handles close their conversation and release the owned lease; scope exit, script error, exit, and signals also close them. Teamfile batches retain tracked-invocation and bundle cleanup.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Authorized handle/id; repeat close joins the same operation"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns an ordinary result map. The host owns its pending per-turn lease and critical release; no returned resource or script closer.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, error_class, usage, message_id, team_chat_log_id, error_kind?, code? } - error_kind (cycle|provider|target) names the stage that failed and an internal fault stops the script instead of returning; error_class is null for a turn that did not fail, else one of quota_exhausted, binary_missing, auth_required, upstream_undisclosed, upstream_throttled, model_not_offered, stale_session, transport_interrupted, context_exhausted, receiver_busy, holder_died or unknown (decided by lmctl, never by the script), and usage is null or what the provider reported: { source, reason, inputUncached, cacheRead, cacheWrite, output, reasoning, modelReported, costUsd (an ESTIMATE at API reference rates, not a subscription charge), costReason, providerCostUsd }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent"); if (res.error_class != null) { println(res.error_class); }'},{name:"lm_classify_failure",category:"lmctl Automation",signature:"lm_classify_failure(text, options = {})",description:"Classifies a recorded provider failure text with the same classifier lm_prompt uses for live turns, so a script reading stored errors (for example tracked_invocation.error) never carries its own regex table. Pure: no database, provider or file access. Text no rule recognises is unknown, never the nearest class.",parameters:[{name:"text",type:"string",description:"The recorded provider error text"},{name:"options",type:"map",description:"(optional) model: the model the failed attempt requested (enables the retired-model tell: the provider listing its own models); status: the recorded status, so empty text with busy, empty or stalled still classifies"}],returns:{type:"map",description:"{ status, error, class, rule } where class is one of the lm_prompt error_class values and rule names the matching rule (null for unknown)"},example:'c = lm_classify_failure("spawn kimi ENOENT"); println(c.class);'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_agent_message",category:"lmctl Automation",signature:"lm_agent_message(member, prompt, options = {})",description:"Like lm_agent, and also returns the completed turn as lmctl stores and prices it: model, token buckets and the lmprice cost of that turn. Cost is null (with costUnavailableReason) when the provider does not record enough accounting.",parameters:[{name:"member",type:"map",description:"As for lm_agent"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) As for lm_agent"}],returns:{type:"map",description:"lm_agent's { status, reply, error, message_id, team_chat_log_id } plus message: null | { role, content, provider, sessionid, model, usage: { input, cachedInput, cacheWrite, output }, costUsd, costUnavailableReason, priceRoute, priceDataSource }"},example:'agent = { provider: "miniplayer", model: "deepseek/deepseek-flash" }; res = lm_agent_message(agent, "Say hi"); println(res.message.costUsd);'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, sessions: [{ provider, sessionid, sessiondir, modifiedAt }] }'},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_get",category:"lmctl Automation",signature:"lm_session_get(target)",description:"Reads native session messages. Returns messages in chronological order, or not_found if the session does not exist.",parameters:[{name:"target",type:"map",description:"Session target map with required provider and sessionid strings"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, messages?: [{ role: string, content: string }] }'},example:'session = lm_session_get({ provider: "codex", sessionid: "sess-123" }); if (session.status == "ok") { println(len(session.messages)); }'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_running",category:"lmctl Automation",signature:"lm_running(options = {})",description:'Returns active tracked-invocation snapshot. Options: since (e.g. "1h", "2d") and reconcile (boolean, default false). reconcile:true may mutate tracked invocations by reconciling verified dead holders; the default is read-only. Dispatch and branch on status busy, never gate on this.',parameters:[{name:"options",type:"map",description:'(optional) Query options: since (duration string like "1h", "2d"); reconcile (boolean, default false) opts into dead-holder reconciliation writes'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, running: map[], dead: map[], idle: map[] }'},example:'snapshot = lm_running(); if (snapshot.status == "ok") { println(len(snapshot.running)); }'},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, seeded: [{ alias, provider, sessionid, sessiondir, model }] }'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. The host attempts checked lock/invocation release on completion, failure, cancellation or signal and reports unresolved failures, including a busy database; the returned outcome is an ordinary map. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, exit_code: number, signal: string|null, code?: string }'},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", error: null, readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, members: [{ alias, provider, model, sessionid, sessiondir }] }'},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, member?: { alias, provider, model, sessionid, sessiondir }, isLead?: bool, teamfile?: string }'},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function z(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function he(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var ft=L(()=>{"use strict"});function ew(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?na:Zv}var Zv,na,Bp=L(()=>{"use strict";Zv="root_teamfile <> '(direct)'",na=Zv+" AND COALESCE(accounting_only,0)=0"});import{existsSync as qM}from"node:fs";import{createRequire as XM}from"node:module";function GM(){return Hp===null&&(Hp=XM(import.meta.url)("node:sqlite").DatabaseSync),Hp}function KM(t){let e=VM[t];if(e!==void 0)return e;let n=JM[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function Ls(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=KM(t.errcode)),t}function zM(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function YM(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function Wp(t){return t.length===1&&QM(t[0])?[t[0]]:t}function QM(t){if(!Gp(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Gp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Hp,JM,VM,qp,Ms,Xp,ra=L(()=>{"use strict";Hp=null;JM={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},VM={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};qp=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!qM(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(GM())(e,{readOnly:n.readonly===!0})}catch(r){Ls(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new Xp(this.handle.prepare(e))}catch(n){Ls(n)}}exec(e){try{this.handle.exec(e)}catch(n){Ls(n)}}pragma(e,n){let r=`PRAGMA ${e}`;if(e.includes("=")){this.exec(r);return}if(n?.simple===!0){let s=this.prepare(r).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(r).all()}transaction(e){let n=(...r)=>this.runTransaction("BEGIN",e,r);return n.immediate=(...r)=>this.runTransaction("BEGIN IMMEDIATE",e,r),n}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){Ls(e)}}runTransaction(e,n,r){if(!this.inTransaction){this.exec(e);try{let i=n(...r);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!zM(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=n(...r);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!YM(o))throw o}throw i}}};Ms=qp,Xp=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...Wp(e));return this.normalizeRow(n)}catch(n){Ls(n)}}all(...e){try{return this.handle.all(...Wp(e)).map(n=>this.normalizeRow(n))}catch(n){Ls(n)}}run(...e){try{let n=this.handle.run(...Wp(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){Ls(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Gp(e)?Object.values(e):Gp(e)?{...e}:e}}});function gc(t){return new Ms(t,{readonly:!0,fileMustExist:!0})}var Jp=L(()=>{"use strict";ra()});import{createHash as ZM}from"node:crypto";import{lstat as eP,readFile as tP,realpath as tw,stat as nw}from"node:fs/promises";import{isAbsolute as rw,relative as nP,resolve as rP,sep as sP}from"node:path";function Y(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function oe(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function sa(t){return oe(t)}function Gt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function we(t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t.maxRows)||t.maxRows<=0)throw new Error("maxRows must be a positive safe integer");t.signal.throwIfAborted()}function xe(t,e){return t<e?-1:t>e?1:0}function Et(t,e,n){if(t===null||e===null)return null;let r=n==="written"?"write":"read",s=0;for(let i of t){if(i.bytes===null)return null;s+=i.bytes}for(let i of e)if(i.direction===r){if(i.bytes===null)return null;s+=i.bytes}return s}function In(t,e,n){let r={},s=sa(t.cacheWrite5m),i=sa(t.cacheWrite1h),o=sa(t.reasoning),a=sa(t.webSearch),l=sa(t.webFetch);o!==null&&(e===null||o<=e)&&(r.reasoning_output_tokens=o);let c=(s??0)+(i??0),u=n===null||c<=n;return s!==null&&u&&(r.cache_write_5m_tokens=s),i!==null&&u&&(r.cache_write_1h_tokens=i),a!==null&&(r.web_search_requests=a),l!==null&&(r.web_fetch_requests=l),Object.keys(r).length>0?r:null}function Mr(t){return typeof t=="string"&&oP.has(t.toLowerCase())}function Be(t,e){t.record({direction:"read",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"}),t.record({direction:"write",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"})}function xi(t){let e=Y(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function tt(t,e){if(!rw(t))return null;let n=await eP(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await tw(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await tw(s).catch(()=>rP(s)),o=nP(i,r);if(o===""||!o.startsWith(`..${sP}`)&&o!==".."&&!rw(o))return r}return null}async function Ot(t,e){we(e);let n=await nw(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await tP(t,{signal:e.signal});e.signal.throwIfAborted();let s=await nw(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${ia}:sha256:${ZM("sha256").update(r).digest("hex")}`,data:r}}function hc(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=t.toString("utf8"),r=n.length===0?[]:n.slice(0,-1).split(`
|
|
518
518
|
`),s=[];for(let i of r)if(e.signal.throwIfAborted(),!!i.trim())try{let o=Y(JSON.parse(i));if(!o)return null;s.push(o)}catch{return null}return s}var ia,Nt,qt,iP,Xt,oP,ir=L(()=>{"use strict";ia="bx3",Nt={input_uncached:null,input_cached:null,input_cache_write:null,output:null};qt=class{map=new Map;record(e,n,r,s){if(typeof r!="string"||r.length===0||r.includes("\0"))return;let i=`${e}\0${n}\0${r}`;this.map.has(i)||this.map.set(i,{direction:n,path:r,bytes:s})}files(e){let n=[];for(let r of this.map.values())r.direction===e&&n.push({path:r.path,bytes:r.bytes});return n}},iP=0,Xt=class{map=new Map;record(e){let n;e.id!==null?n=`id\0${e.id}\0${e.direction}\0${e.kind}`:e.bytes===null?n=`mark\0${e.direction}\0${e.kind}\0${e.basis}\0${e.ref??""}`:n=`seq\0${iP++}`,this.map.has(n)||this.map.set(n,e)}entries(){return[...this.map.values()]}};oP=new Set(["schedulewakeup","taskcreate","taskupdate","taskoutput","taskstop","todowrite","todoread","croncreate","crondelete","cronlist","monitor","listagents","toolsearch","askuserquestion","exitplanmode","agent","skill","job"])});import{readdir as aP}from"node:fs/promises";import{join as sw,sep as iw}from"node:path";var Ii,Vp=L(()=>{"use strict";ir();Ii=class{constructor(e){this.format=e}async discover(e,n,r){we(e);let s=[],i=0,o=!1,a=async(l,c)=>{if(e.signal.throwIfAborted(),c>8||i>e.maxRows){o=!0;return}let u=await aP(l,{withFileTypes:!0}).catch(m=>(m.code!=="ENOENT"&&(o=!0),[])),d=m=>sw(l,m.name)+(m.isDirectory()?iw:"");for(let m of u.sort((p,f)=>xe(d(p),d(f)))){e.signal.throwIfAborted();let p=sw(l,m.name),f=m.isDirectory()&&r?.startsWith(p+iw);if(!(r&&!f&&xe(d(m),r)<=0)){if(!f&&++i>e.maxRows){o=!0;break}if(m.isDirectory())await a(p,c+1);else if(m.isFile()){let h=this.format.sessionId(p);h&&s.push({provider:this.format.provider,sessionid:h,source_id:p})}if(s.length>=n){o=!0;break}}}};return await a(this.format.root,0),s.sort((l,c)=>xe(l.source_id,c.source_id)),{sources:s.slice(0,n),truncated:o||s.length>n}}async bytes(e,n){if(we(n),e.provider!==this.format.provider||this.format.sessionId(e.source_id)!==e.sessionid)return null;let r=await tt(e.source_id,[this.format.root]);if(!r)return null;let s=await Ot(r,n).catch(()=>(n.signal.throwIfAborted(),null));return s&&{...s,revision:`${this.format.revision}:${s.revision}`}}async inspect(e,n){let r=await this.bytes(e,n);return r?{status:"ready",revision:r.revision}:{status:"partial"}}async read(e,n,r){let s=await this.bytes(e,r);if(!s||s.revision!==n)return{status:"partial"};let i=this.format.decode(s.data,e.sessionid,e.source_id,r);return!i||!i.responses?{status:"partial"}:{status:"complete",source:e,revision:n,checkpoint:null,responses:i.responses,...i.captureStatus?{capture_status:i.captureStatus}:{}}}}});function Pr(t,e=!0){let n={input_uncached:null,input_cached:null,input_cache_write:null,output:null};if(!e||!t.length||new Set(t.map(r=>r.response_id)).size!==t.length)return n;for(let r of Object.keys(n)){let s=t.map(o=>o.tokens[r]);if(s.some(o=>o===null||!Number.isSafeInteger(o)||o<0))continue;let i=s.reduce((o,a)=>o+a,0);Number.isSafeInteger(i)&&(n[r]=i)}return n}var oa=L(()=>{"use strict"});import{createReadStream as ow}from"node:fs";import{createInterface as aw}from"node:readline";import{stat as lP}from"node:fs/promises";import{homedir as cP}from"node:os";function lw(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*Le(t,e){let n=ow(t,{encoding:"utf-8"}),r=aw({input:n,crlfDelay:1/0});try{for await(let s of r){let i=s.trim();if(!i)continue;let o=lw(i);o!==void 0?yield o:e?.()}}finally{n.destroy()}}async function Jt(t,e){let n=[],r=ow(t,{encoding:"utf-8"}),s=aw({input:r,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=lw(o);if(a!==void 0&&n.push(a),n.length>=e)break}}finally{s.close(),r.destroy()}return n}async function He(t){let e=await lP(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function Ae(t){return t.replace(/\\n/g,`
|
|
519
519
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function ee(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function tn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ce,Ke=L(()=>{"use strict";ce=cP()});import{readdir as uP}from"node:fs/promises";import{join as Ai,resolve as dP}from"node:path";function _c(t){return dP(t||process.env.XDG_DATA_HOME||Ai(ce,".local","share"))}function mP(t){return Ai(_c(t),"muse","sessions")}function pP(t,e,n,r){let s=r?.input_tokens,i=r?.cache_read_tokens??r?.input_cache_read_tokens,o=r?.cache_write_tokens??r?.input_cache_write_tokens,a=typeof r?.promptTokens=="number"?r.promptTokens:typeof r?.prompt_tokens=="number"?r.prompt_tokens:void 0,l=typeof s=="number"&&typeof i=="number"&&i>s||typeof a=="number"&&typeof i=="number"&&i>a||typeof a=="number"&&typeof o=="number"&&o>a||typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&i+o>a,c=l?null:typeof i=="number"?i:null,u=l?null:typeof o=="number"?o:null,d=null;return l||(typeof r?.input_uncached_tokens=="number"?d=r.input_uncached_tokens:typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&a>=i+o&&(d=a-i-o)),{response_id:t,timestamp:e.toISOString(),model:typeof n=="string"&&n.length>0?n:null,tokens:{input_uncached:typeof d=="number"?d:null,input_cached:typeof c=="number"?c:null,input_cache_write:typeof u=="number"?u:null,output:typeof r?.output_tokens=="number"?r.output_tokens:null},files_read:null,files_written:null}}function dw(t,e){let n,r,s,i,o,a=[],l=new Map,c=new Map,u=new Set,d,m,p=()=>{m="partial"},f=_=>{if(typeof _!="string"||_.length===0){p();return}let v=l.get(_);return v||(v={id:_,turn:{id:_,status:"unknown"},responseIds:[]},l.set(_,v)),v},h=_=>{if(_.retained_frame&&Array.isArray(_.children)){for(let T of _.children)try{if(typeof T?.record_json!="string")throw new Error("missing record_json");h(JSON.parse(T.record_json))}catch{p()}return}if(_.stream?.kind!=="session"||_.stream?.id!==t)return;if(_.schema_version!==1){p();return}if(_.payload_type?.startsWith("runtime.session")&&_.payload_schema_version!==1){p();return}let v=_.payload?.source_run_record_id;for(let T of[_.id,v])if(!(typeof T!="string"||T.length===0)&&u.has(T))return;for(let T of[_.id,v])typeof T=="string"&&T.length>0&&u.add(T);let y=typeof _.recorded_at=="number"&&Number.isFinite(_.recorded_at)?new Date(_.recorded_at/1e3):void 0;if(_.recorded_at!==void 0&&(!y||!Number.isFinite(y.getTime()))){p();return}y&&Number.isFinite(y.getTime())&&((!s||y<s)&&(s=y),(!i||y>i)&&(i=y));let b=_.payload;if(_.payload_type==="runtime.session.metadata"&&(typeof b?.record?.workspace_root=="string"&&(n=b.record.workspace_root),typeof b?.record?.model_id=="string"&&(r=b.record.model_id)),_.payload_type!=="runtime.session"||b?.kind!=="run")return;let w=b.event,k=f(b.run_id);if(!w||!y||!k){w||p();return}if(w.kind==="started"&&typeof w.prompt=="string")a.push({role:"user",content:w.prompt,timestamp:y}),k.turn.startedAt=y,k.turn.prompt=w.prompt,k.turn.status="in_progress",o="in_progress";else if(w.kind==="assistant_message_committed"&&typeof w.text=="string")a.push({role:"assistant",content:w.text,timestamp:y});else if(w.kind==="terminal")k.turn.completedAt=y,k.turn.status=w.terminal==="completed"?"complete":"aborted",o=k.turn.status;else if(w.kind==="model_completed"){typeof w.model=="string"&&w.model.length>0&&(r=w.model,k.turn.model=w.model);let T=typeof v=="string"&&v.length>0?v:typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(!T)p();else{k.responseIds.push(T);let B={};if(w.usage&&typeof w.usage=="object")for(let $ of["input_tokens","output_tokens","cached_tokens","reasoning_tokens","input_uncached_tokens","cache_read_tokens","input_cache_read_tokens","cache_write_tokens","input_cache_write_tokens","promptTokens","prompt_tokens"]){let te=w.usage[$];typeof te=="number"&&Number.isSafeInteger(te)&&te>=0&&(B[$]=te)}Object.keys(B).length>0&&(k.turn.rawUsage=[...k.turn.rawUsage??[],{responseId:T,values:B}]),c.set(T,pP(T,y,w.model,B))}if(!w.usage)return;let R={},C=w.usage.input_tokens,N=w.usage.cache_read_tokens??w.usage.input_cache_read_tokens,A=w.usage.cache_write_tokens??w.usage.input_cache_write_tokens,E=typeof w.usage.promptTokens=="number"?w.usage.promptTokens:typeof w.usage.prompt_tokens=="number"?w.usage.prompt_tokens:void 0,S=typeof C=="number"&&typeof N=="number"&&N>C||typeof E=="number"&&typeof N=="number"&&N>E||typeof E=="number"&&typeof A=="number"&&A>E||typeof E=="number"&&typeof N=="number"&&typeof A=="number"&&N+A>E,x=S?void 0:typeof N=="number"?N:void 0,I=S?void 0:typeof A=="number"?A:void 0,O;S||(typeof w.usage.input_uncached_tokens=="number"?O=w.usage.input_uncached_tokens:typeof E=="number"&&typeof N=="number"&&typeof A=="number"&&E>=N+A&&(O=E-N-A)),O!==void 0&&O<0&&(O=void 0);let M=w.usage.output_tokens,D=w.usage.reasoning_tokens;typeof O=="number"&&Number.isSafeInteger(O)&&O>=0&&(R.inputTokens=O),typeof x=="number"&&Number.isSafeInteger(x)&&x>=0&&(R.cachedInputTokens=x),typeof I=="number"&&Number.isSafeInteger(I)&&I>=0&&(R.cacheWriteInputTokens=I),typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(R.outputTokens=M),typeof D=="number"&&Number.isSafeInteger(D)&&D>=0&&(R.reasoningOutputTokens=D),d=R}};return{visit:h,finish:()=>{if(!n||!s||!i)return null;let _=a.filter(w=>w.role==="user").map(w=>w.content),v=[...l.values()].map(w=>({...w.turn,...w.responseIds.length>0?{responseIds:[...w.responseIds]}:{}})),y=[...c.values()],b=Pr(y,m!=="partial");return{provider:"muse",sessionId:t,filePath:e,cwd:n,createdAt:s,modifiedAt:i,model:r,messages:a,messageCount:a.length,firstUserMessage:_[0],lastUserMessage:_.at(-1),userPrompts:_,turnStatus:o,totalInputTokens:b.input_uncached??void 0,totalCachedInputTokens:b.input_cached??void 0,totalCacheWriteInputTokens:b.input_cache_write??void 0,totalOutputTokens:b.output??void 0,lastTokenUsage:d,turns:v,responses:y,...m?{captureStatus:m}:{}}},markPartial:p}}function fP(t,e,n){let r=dw(e,n);for(let s of t)r.visit(s);return r.finish()}function gP(t,e,n,r){r.signal.throwIfAborted();let s=Math.max(0,r.maxBytes),i=t.length<=s?t:t.subarray(0,Math.max(0,t.subarray(0,s).lastIndexOf(10))),o=i.length!==t.length,a=[],l=o,c=0,u=m=>{if(!m||typeof m!="object"||Array.isArray(m)){l=!0;return}let p=m;if(p.retained_frame&&Array.isArray(p.children)){for(let f of p.children){if(c>=r.maxRows){l=!0;return}let h;try{if(typeof f?.record_json!="string")throw new Error("missing record_json");h=JSON.parse(f.record_json)}catch{l=!0;continue}u(h)}return}if(c>=r.maxRows){l=!0;return}a.push(p),c++};for(let m of i.toString("utf8").split(/\r?\n/u)){if(r.signal.throwIfAborted(),m.trim()==="")continue;let p;try{p=JSON.parse(m)}catch{l=!0;continue}u(p)}let d=fP(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function mw(t){return{provider:"muse",root:mP(t),revision:"muse-session-v2",sessionId:n=>n.replaceAll("\\","/").match(/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/session\.jsonl$/iu)?.[1]??null,decode:gP}}async function uw(t,e){let n=dw(t,e);for await(let r of Le(e,n.markPartial))n.visit(r);return n.finish()}var cw,yc,Kp=L(()=>{"use strict";oa();Ke();cw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;yc=class{name="muse";dataHome;constructor(e={}){this.dataHome=_c(e.museDataHome)}get root(){return Ai(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await uP(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(Ai(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(Ai(e,i.name),n+1));return s}async resolveSessionPath(e){return cw.test(e)?(await this.files()).find(n=>n.endsWith(Ai(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?uw(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!cw.test(r))continue;let s=await uw(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as pw,readdir as hP,rm as yP,stat as fw}from"node:fs/promises";import{basename as _P,join as Ci,resolve as bP}from"node:path";function wc(t){return bP(t||process.env.MINIPLAYER_HOME||Ci(process.env.XDG_DATA_HOME||Ci(ce,".local","share"),"miniplayer"))}function bc(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function zp(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function gw(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function hw(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function yw(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return null}}function _w(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))oe(c)!==null&&(n[l]=c);let r=oe(e.inputTokens),s=oe(e.cachedInputTokens),i=oe(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=oe(e.outputTokens),a=null;return t.usageConvention==="input-includes-cache"&&r!==null&&s!==null&&s<=r&&(a=r-s),t.usageConvention==="input-excludes-cache"&&r!==null&&i!==null&&(a=r+i),t.usageConvention==="synthetic"&&r===0&&s===0&&(i===0||i===null)&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:n,pricingFacts:oe(e.reasoningTokens)===null?null:{reasoning_output_tokens:oe(e.reasoningTokens)}}}function vw(t,e,n){if(!t||typeof t!="object")return null;let r=t;if(![1,2].includes(r.version)||r.id!==e||typeof r.cwd!="string")return null;let s=f=>{if(typeof f!="string")return;let h=new Date(f);return Number.isFinite(h.getTime())?h:void 0},i=s(r.createdAt),o=s(r.updatedAt);if(!i||!o)return null;let a=[],l=[],c=[],u=r.version===1,d="complete";if(r.version===1){if(!Array.isArray(r.messages))return null;for(let f of r.messages){if(!f||!["user","assistant"].includes(f.role)||typeof f.content!="string")return null;a.push({role:f.role,content:f.content,timestamp:s(f.timestamp)??o})}}else{if(!Array.isArray(r.turns))return null;let f=new Set,h=new Set;for(let g of r.turns){if(!g||typeof g.responseId!="string"||!g.responseId||typeof g.input?.text!="string")return null;if(f.has(g.responseId)){u=!0;continue}f.add(g.responseId);let _=s(g.startedAt),v=s(g.completedAt??g.endedAt);if(!_)return null;let y=typeof g.model=="string"?g.model:void 0;["complete","running","failed","aborted"].includes(g.status)||(u=!0);let b=g.status==="complete"?"complete":g.status==="running"?"in_progress":g.status==="failed"?"failed":g.status==="aborted"?"aborted":"unknown";d=b==="failed"||b==="unknown"?"aborted":b,(b!=="complete"||g.partial===!0)&&(u=!0);let w=Array.isArray(g.modelResponses),k=w?g.modelResponses:[],T=[];l.push({id:g.responseId,startedAt:_,completedAt:v,model:y,prompt:g.input.text,status:b,responseIds:T}),a.push({role:"user",timestamp:_,content:g.input.text});let R=Array.isArray(g.toolEvents)&&g.toolEvents.length>0;if(!w&&!R){let S=g.usage??{},x=_w({...g,usage:S});Object.keys(x.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:g.responseId,values:x.rawUsage}]),T.push(g.responseId),c.push({response_id:g.responseId,timestamp:(v??_).toISOString(),model:y??null,model_provider:typeof g.provider=="string"?g.provider:null,tokens:x.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(g.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"}],pricing_facts:x.pricingFacts}),b!=="complete"&&!g.usage&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:v??_,content:g.output.text,model:y});continue}let C=new Map,N=new Map,A=new Set,E=[];for(let S of k){if(!S||typeof S!="object"||typeof S.responseId!="string"||!S.responseId){u=!0;continue}if(T.includes(S.responseId)){u=!0;continue}let x=S,I=E.length;E.push({response:x,index:I,filesRead:[],filesWritten:[],io:[]}),T.push(S.responseId),h.has(S.responseId)&&(u=!0),h.add(S.responseId),x.toolCalls!==void 0&&!Array.isArray(x.toolCalls)&&(u=!0,E[I].io.push({direction:"read",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"}));for(let O of Array.isArray(x.toolCalls)?x.toolCalls:[]){let M=gw(O),D=zp(O);if(M)C.set(M,I),N.set(M,D);else{u=!0;let B=D==="list_directory"||D==="read_file"||D==="webget"||D==="shell"||D==="tool",$=D==="write_file"||D==="shell"||D==="tool";B&&E[I].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),$&&E[I].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}T.length===0&&k.length>0&&(u=!0);for(let S of Array.isArray(g.toolEvents)?g.toolEvents:[]){let x=S&&typeof S=="object"?S:{},I=gw(x),O=I?C.get(I):void 0,M=zp(x),D=hw(x.result),B=x.status==="failed"||x.error!==void 0;if(x.type==="tool_call"?a.push({role:"tool_use",timestamp:s(x?.timestamp)??_,content:bc(x?.input??x?.args),toolName:M,toolInput:bc(x?.input??x?.args),toolInputData:hw(x?.input??x?.args)??void 0,...I?{toolCallId:I}:{}}):a.push({role:"tool_result",timestamp:s(x?.timestamp)??v??_,content:bc(B?x?.error:x?.result),toolName:M,...I?{toolCallId:I}:{}}),O===void 0){u=!0;continue}let $=E[O];(x.type==="tool_result"||B||x.result!==void 0)&&A.add(I);let te=D?.path,X=oe(D?.bytesRead??D?.bytesWritten);x.type!=="tool_call"&&(M==="read_file"&&!B&&typeof te=="string"&&X!==null?$.filesRead.push({path:te,bytes:X}):M==="write_file"&&!B&&typeof te=="string"&&X!==null?$.filesWritten.push({path:te,bytes:X}):M==="webget"&&!B&&X!==null?$.io.push({direction:"read",kind:"web",id:I,ref:yw(D?.finalUrl??D?.url),bytes:X,basis:"certified_counter"}):M==="shell"||B?(M!=="write_file"&&$.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}),(M==="shell"||M==="write_file")&&$.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"})):M==="list_directory"||M==="read_file"||M==="webget"?$.io.push({direction:"read",kind:M==="webget"?"web":"unattributed",id:I,ref:M==="webget"?yw(D?.finalUrl??D?.url):null,bytes:null,basis:"unknown"}):M==="write_file"?$.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}):$.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}))}for(let[S,x]of N)if(!A.has(S)){let I=E[C.get(S)],O=x==="list_directory"||x==="read_file"||x==="webget"||x==="shell",M=x==="write_file"||x==="shell";O&&I.io.push({direction:"read",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),M&&I.io.push({direction:"write",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let S of E){let x=S.response,I=_w(x),O=s(x.completedAt??x.startedAt)??v??_;new Set((Array.isArray(x.toolCalls)?x.toolCalls:[]).map($=>zp($))).has("shell")&&!S.io.some($=>$.kind==="unattributed"&&$.direction==="read")&&S.io.push({direction:"read",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"}),S.index===0&&S.io.unshift({direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"});let D=S.io.some($=>$.direction==="read"&&$.bytes===null),B=S.io.some($=>$.direction==="write"&&$.bytes===null);if(c.push({response_id:x.responseId,timestamp:O.toISOString(),model:typeof x.model=="string"?x.model:null,model_provider:typeof x.provider=="string"?x.provider:typeof g.provider=="string"?g.provider:null,tokens:I.tokens,files_read:D?null:S.filesRead,files_written:B?null:S.filesWritten,read_bytes:D?null:S.filesRead.reduce(($,te)=>$+(te.bytes??0),0)+S.io.filter($=>$.direction==="read").reduce(($,te)=>$+(te.bytes??0),0),write_bytes:B?null:S.filesWritten.reduce(($,te)=>$+(te.bytes??0),0)+S.io.filter($=>$.direction==="write").reduce(($,te)=>$+(te.bytes??0),0),external_io:S.io,pricing_facts:I.pricingFacts}),Object.keys(I.rawUsage).length){let $=l.at(-1);$.rawUsage=[...$.rawUsage??[],{responseId:x.responseId,values:I.rawUsage}]}}l.at(-1).responseIds=T,T.length!==k.length&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:v??_,content:g.output.text,model:y})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Pr(c,!u);return{provider:"miniplayer",sessionId:e,cwd:r.cwd,filePath:n,createdAt:i,modifiedAt:o,model:typeof r.model=="string"?r.model:void 0,messages:a,messageCount:a.length,userPrompts:m,firstUserMessage:m[0],lastUserMessage:m.at(-1),turns:l,responses:c,turnStatus:d,...u?{captureStatus:"partial"}:{},totalInputTokens:p.input_uncached??void 0,totalCachedInputTokens:p.input_cached??void 0,totalCacheWriteInputTokens:p.input_cache_write??void 0,totalOutputTokens:p.output??void 0}}function Ec(t){return{provider:"miniplayer",root:Ci(wc(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=_P(e,".json");return e.endsWith(".json")&&bw.test(n)?n:null},decode(e,n,r,s){s.signal.throwIfAborted();try{let i=JSON.parse(e.toString("utf8"));return(Array.isArray(i.turns)?i.turns.reduce((a,l)=>a+1+(Array.isArray(l?.modelResponses)?l.modelResponses.length:0)+(Array.isArray(l?.toolEvents)?l.toolEvents.length:0),0):Array.isArray(i.messages)?i.messages.length:0)>s.maxRows?null:vw(i,n,r)}catch{return null}}}}var bw,vc,Tc=L(()=>{"use strict";oa();Ke();ir();bw=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;vc=class{name="miniplayer";home;constructor(e={}){this.home=wc(e.miniplayerHome)}getWatchPaths(){return[{directory:Ci(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await hP(Ci(this.home,"sessions"))}catch{return[]}return(await Promise.all(e.filter(r=>r.endsWith(".json")).map(r=>this.loadSession(r.slice(0,-5))))).filter(r=>r!==null)}async resolveSessionPath(e){if(!bw.test(e))return null;let n=Ci(this.home,"sessions",`${e}.json`);try{return(await fw(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=vw(JSON.parse(await pw(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await pw(`${n}.lock`,"utf8"));if(Number.isInteger(i.pid)&&i.pid>0)try{process.kill(i.pid,0),s="in_progress"}catch{s="aborted"}}catch{}return{...r,...s!=="complete"?{turnStatus:s}:{}}}catch{return null}}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;try{throw await fw(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await yP(n),!0}}});import{createHash as vP}from"node:crypto";import{createRequire as wP}from"node:module";import{readdir as EP,realpath as TP}from"node:fs/promises";import{basename as ww,dirname as SP,join as Ew,resolve as Tw}from"node:path";function RP(){return kP("node:sqlite").DatabaseSync}function xP(){return process.env.HOME||process.env.USERPROFILE||""}function Ps(t){let e=[],n=0,r=()=>{let s=0n,i=0n;for(;;){if(n>=t.length||i>63n)return null;let o=t[n++];if(s|=BigInt(o&127)<<i,i+=7n,!(o&128))break}return s<=BigInt(Number.MAX_SAFE_INTEGER)?Number(s):null};for(;n<t.length;){let s=r();if(s===null)return e;let i=s>>>3,o=s&7;if(i===0)return e;if(o===0){let a=r();if(a===null)return e;e.push({field:i,wire:o,varint:a})}else if(o===1){if(n+8>t.length)return e;n+=8,e.push({field:i,wire:o})}else if(o===5){if(n+4>t.length)return e;n+=4,e.push({field:i,wire:o})}else if(o===2){let a=r();if(a===null||n+a>t.length)return e;e.push({field:i,wire:o,bytes:t.subarray(n,n+a)}),n+=a}else return e}return e}function An(t,e){return t.find(n=>n.field===e)}function IP(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=Ps(n.bytes),s=An(r,1)?.bytes,i=An(r,2)?.bytes;if(s===void 0||i===void 0)continue;let o=s.toString("utf8");e.has(o)||e.set(o,i.toString("utf8"))}return e}function AP(t){let e=An(Ps(t),5)?.bytes;if(e===void 0)return null;let n=An(Ps(e),1)?.bytes;if(n===void 0)return null;let r=Ps(n),s=An(r,1)?.varint;if(s===void 0)return null;let i=An(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function CP(t){let e=An(t,4)?.bytes,n=e!==void 0?Ps(e):[],r=s=>{let i=An(n,s)?.varint;return i===void 0?null:oe(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function NP(t){let e=An(Ps(t),1)?.bytes;if(e===void 0)return null;let n=Ps(e),r=IP(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=An(n,19)?.bytes,o=i!==void 0&&i.length>0?i.toString("utf8"):null,a=r.get("last_step_index"),l=a===void 0?Number.NaN:Number(a),c=Number.isSafeInteger(l)&&l>=0?l:null,{tokens:u,thinkingOutputTokens:d}=CP(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function Sw(t,e){we(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=oe(n?.total);if(r===null||r>e.maxBytes)return null;let s=t.prepare("SELECT idx, data FROM gen_metadata ORDER BY idx LIMIT ?").all(e.maxRows+1);if(s.length>e.maxRows)return null;let i=vP("sha256");i.update("rev:").update(Sc).update(`
|
|
520
520
|
`);let o=[],a=[],l=0;for(let d of s){if(e.signal.throwIfAborted(),!(d.data instanceof Uint8Array))return null;let m=Buffer.from(d.data);if(l+=m.length,l>e.maxBytes)return null;i.update("g").update(String(d.idx)).update("\0").update(m).update(`
|
|
@@ -2420,7 +2420,7 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2420
2420
|
`),kt({event:"model_ignored",provider:f.provider,model:f.model,reason:f.reason}),n?.(f)}});if(l===null||l.length===0)return mr(t,`no resume incantation for provider "${s}"`);let c=Ge(r?.env??t.env??process.env,o,i,"terminal"),u=await hI(s,{binary:l[0],cwd:o,env:c,signal:r?.signal});if(r?.signal?.aborted){let f=r.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";return r.cancel?.(f),f==="SIGINT"?130:143}let[d,...m]=l,p=u.kind==="use-binary"?u.binary:d;return u.message&&t.stderr.write(u.message+`
|
|
2421
2421
|
`),await new Promise(f=>{if(r?.signal?.aborted){let R=r.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";return r.cancel?.(R),f(R==="SIGINT"?130:143)}let h=r?.streams,g=h?[h.stdin,h.stdout,h.stderr].map(R=>R.fd):void 0,_=g?.every(R=>typeof R=="number"),v=zG(p,m,{stdio:h?_?g:["pipe","pipe","pipe"]:"inherit",cwd:o,env:c}),y=h?.stdin?.readableFlowing;h&&!_&&(h.stdin.pipe(v.stdin),v.stdout?.pipe(h.stdout,{end:!1}),v.stderr?.pipe(h.stderr,{end:!1}));let b=!1,w=R=>{if(!b){b=!0;try{r?.cancel?.(R)}catch{}{try{v.kill(R)}catch{}Te(v,{stdinEnd:!1,softDelayMs:0,killDelayMs:100}).catch(()=>{})}}},k=()=>w(r?.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r&&(r.stop=w);let T=()=>{r?.signal?.removeEventListener("abort",k),h&&!_&&(h.stdin.unpipe(v.stdin),y||h.stdin.pause(),v.stdout?.unpipe(h.stdout),v.stderr?.unpipe(h.stderr))};r?.signal?.addEventListener("abort",k,{once:!0}),r?.signal?.aborted&&k(),v.stdin?.on("error",()=>{}),v.on("error",R=>{T(),f(mr(t,`failed to launch ${p}: ${R.message}`))}),v.on("exit",(R,C)=>{T(),r&&(r.signalObserved=C);let N=R??(C?128+(KG.signals[C]??1):1),A=yI(s);A&&N!==0&&N!==130&&N!==143&&!b&&!r?.signal?.aborted&&t.stderr.write(s+" exited with status "+N+". "+A+`
|
|
2422
2422
|
`),f(N)})})}var dN=L(()=>{"use strict";Zs();sn();go();pr();lN();Pn();Mn();yn();Nd();cr();Wd();yl();cN();Ce();Ks()});import{resolve as eJ}from"node:path";async function mN(t,e,n){let r=(l,c)=>({status:"error",error:l,errorCode:c,code:null,signal:null}),s,i=!1,o,a;try{let l=_e(t);if(l)return r(l.error,l.code);if(!t.interactive||t.env.LMCTL_NON_INTERACTIVE==="1")return r("terminal opens an interactive TUI; non-interactive mode is enabled","noninteractive");if(!e||typeof e.teamfile!="string"||typeof e.alias!="string"||!n||typeof n.stdin?.pipe!="function"||typeof n.stdout?.write!="function"||typeof n.stderr?.write!="function")return r("Terminal requires teamfile, alias and caller streams","invalid_argument");let c={...e};o={env:{...t.env,LMCTL_DB:t.dbPath},pid:t.pid,signal:t.signal,streams:n,onResource(f){a=f,t.closed&&f.finalizeSync("SIGTERM")}},s=Nn(t,{async close(){try{await a?.close()}catch(f){throw i=!0,f}},finalizeSync(f){try{a?.finalizeSync(f)}catch(h){throw i=!0,h}}});let u=[],d=yt(t,(f,h)=>{h==="stderr"&&f.startsWith("error:")&&u.push(f.replace(/^error:\s*/,"").trim())}),m=await uN({...d,stdin:n.stdin},eJ(t.cwd,c.teamfile),c.alias,gn(t),o);return o.cleanupError?.()&&(i=!0),{status:m.code===0&&!m.signal?"ok":"error",error:m.signal?`terminal terminated by ${m.signal}`:m.code===0?null:u.join(`
|
|
2423
|
-
`)||`terminal exited with code ${m.code}`,code:m.code,signal:m.signal}}catch(l){return o?.cleanupError?.()&&(i=!0),r(z(l),"provider")}finally{i||s?.()}}var pN=L(()=>{"use strict";dN();on();cn();ft()});import{isAbsolute as tJ,resolve as nJ}from"node:path";function lm(t){return Number.isFinite(t)&&Math.abs(t)<=rJ}function sJ(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ta.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 E_(t,e=Date.now()){if(t===void 0)return{windowMs:cm};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let i=Number(n[1]),o=n[2],l=(o==="s"?i:o==="m"?i*60:o==="h"?i*3600:i*86400)*1e3;return!Number.isFinite(l)||l<0||!lm(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!lm(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return lm(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function am(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function w_(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return v_;let s=e.get(n);if(s===void 0){try{s=Kt(n)}catch{s=null}e.set(n,s)}return s===null?v_:bu(s,r)?.model??v_}async function fN(t,e={}){let n=_e(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 i=kr("listRunning");if(i.length>0){for(let o of Object.keys(e))if(!i.includes(o))return{status:"error",error:`Unknown option: ${o}`,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.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=cm;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!lm(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 i=E_(e.since,r);if("error"in i)return{status:"error",error:i.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=i.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let i=gn(t),o=e?.teamfile!==void 0?tJ(e.teamfile)?e.teamfile:nJ(t.cwd,e.teamfile):void 0,a=o!==void 0?Dt(o,i):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),u=i.listAllRunningTrackedInvocations().filter(c),d=new Map,m=[],p=[];for(let y of u){let b=Zc(y),w=r-new Date(y.started_at).getTime(),k={id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:am(y),model:w_(y,d),started_at:y.started_at,parent_invocation_id:y.parent_invocation_id};if(b==="dead"){if(r_(i,y)!==null)continue;p.push({...k,stale_for_ms:w})}else m.push({...k,running_for_ms:w,holder_liveness:b??"unknown"})}let f=new Set(u.map(am).filter(y=>y!==null)),h=new Date(r-s).toISOString(),g=i.listRecentlyFinishedTrackedInvocations(h).filter(c),_=new Set,v=[];for(let y of g){let b=am(y);b===null||f.has(b)||_.has(b)||(_.add(b),v.push({id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:b,model:w_(y,d),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([...m.map(w=>w.id),...p.map(w=>w.id),...v.map(w=>w.id)]),b=[...y];for(;b.length>0;){let w=i.listFinishedTrackedInvocationChildren(b,h).filter(k=>!y.has(k.id)&&c(k));if(w.length===0)break;b=[];for(let k of w){y.add(k.id),b.push(k.id);let T=am(k);v.push({id:k.id,kind:k.kind,origin:k.origin,from_identity:k.from_identity,target:T,model:w_(k,d),status:k.status,started_at:k.started_at,ended_at:k.ended_at,idle_ms:r-new Date(k.ended_at).getTime(),ran_ms:new Date(k.ended_at).getTime()-new Date(k.started_at).getTime(),error:k.error,parent_invocation_id:k.parent_invocation_id})}}}return{status:"ok",error:null,running:m,dead:p,idle:v}}catch(i){return{status:"error",error:i instanceof Error?i.message:String(i),code:sJ(i),running:[],dead:[],idle:[]}}}var cm,rJ,v_,gN=L(()=>{"use strict";on();cn();sr();cr();Xd();Mn();Ys();cm=24*60*60*1e3,rJ=864e13;v_="default"});var hN={};Sn(hN,{DAY_MS:()=>cm,LMCTL_API_VERSION:()=>LK,LMCTL_ERROR_CODES:()=>ta,LMCTL_OPERATIONS:()=>wt,LMCTL_PROFILE_VALUE_NAMES:()=>BM,LMCTL_PROPERTY_KEYS:()=>$p,LMCTL_PROPERTY_TABLES:()=>HM,LMCTL_REMOVED_GLOBALS:()=>Up,LMCTL_RESULT_FIELDS:()=>UM,NativeSessionManager:()=>im,agentMessage:()=>cC,batchTurn:()=>VC,classifyFailure:()=>iC,closeBatch:()=>KC,closeNativeSession:()=>ci,createLmctlContext:()=>Hf,deleteSession:()=>iA,fail:()=>H,finalizeBatchSync:()=>XC,finalizeNativeSessionSync:()=>tN,getSession:()=>sA,inspectBatch:()=>GC,isLmctlContext:()=>Ji,lintTeam:()=>p2,listMembers:()=>d2,listRunning:()=>fN,listSessions:()=>rA,loadProfile:()=>k$,loadProperties:()=>R$,nativeSessionClose:()=>oN,nativeSessionRequest:()=>iN,nativeSessionTurn:()=>To,ok:()=>he,openNativeSession:()=>Eo,openTeamBatch:()=>JC,openTerminal:()=>mN,parseRunningSince:()=>E_,profileValues:()=>S$,promptAgent:()=>YI,promptMember:()=>FC,promptReservedAgent:()=>eA,readPrompts:()=>y2,readRatelimits:()=>FX,releaseSession:()=>nA,reserveSession:()=>tA,resolveMember:()=>m2,resolveProfilePath:()=>tg,seedErrorCollector:()=>XI,seedTeam:()=>f2,sessionAdmission:()=>ZI});var yN=L(()=>{"use strict";ft();on();ES();sr();GI();JI();oA();sC();oC();By();uC();jC();zC();sm();aN();pN();gN();__()});var wN={};Sn(wN,{createLmctlHostModule:()=>vN,default:()=>_J});import{AsyncLocalStorage as iJ}from"node:async_hooks";import{randomUUID as oJ}from"node:crypto";import{types as aJ}from"node:util";import{createInterface as lJ}from"node:readline";import{Writable as cJ}from"node:stream";import{readFileSync as uJ}from"node:fs";import{resolve as dJ}from"node:path";import{homedir as mJ}from"node:os";function _N(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ta.includes(e))return e;if(e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}}return"internal"}function hJ(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[T_,...t.params??[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]],readonly:t.name==="lm_error",dryControl:t.name==="lm_error"?"error":"output"};if(t.name==="lm_exit")return{...t,arity:{min:0,max:2},params:[{name:"code",type:"number",optional:!0},T_],readonly:!0};if(um.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"||t.name==="lm_agent_message"){let e=t.params??[{name:"file",type:"string"}],n=typeof t.arity=="number"?t.arity:t.arity.min;return{...t,arity:{min:n,max:e.length+1},params:[...e,T_],readonly:um.has(t.name)}}return t}function vN(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:yJ,async activate(r){let s=t.api??await Promise.resolve().then(()=>(yN(),hN)),i,o=new iJ,a=()=>o.getStore()??e,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new Map,m=new Map,p=!1,f=()=>{if(i)return i;let E={...r.env};!E.HOME&&!E.LMCTL_HOME&&!E.LMCTL_DB&&(E.HOME=mJ());let S=s.createLmctlContext({env:E,cwd:r.cwd,pid:process.pid,onProgress:(x,I)=>a()[I??"stderr"](x),onWarning:x=>a().stderr(x)});if(S.status!=="ok")throw Error(S.error);return i=S,t.onContext?.(i),i},h={},g=()=>{let E=s.loadProperties(f());if(E.status!=="ok")throw Error(E.error);return{path:E.path,properties:E.properties,hint:"Define it in "+E.path+" or run lmctl init"}},_=()=>i&&!i.closed&&i.finalizeSync(r.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r.signal?.addEventListener("abort",_,{once:!0}),r.signal?.aborted&&_();let v=async(E,S,x={},I)=>{let O=x&&typeof x=="object"&&!Array.isArray(x)?{permissionMode:x.permissionMode??"yolo",idleTimeoutMs:x.idleTimeoutMs??void 0}:x,M=I?await s.promptReservedAgent(f(),I,E,S,O):await s.promptAgent(f(),E,S,O);if(E&&typeof E=="object"&&M.sessionid&&M.status!=="busy"&&(E.sessionid=M.sessionid),E?.sessionid&&M.status!=="busy"){let D=JSON.stringify([E.provider,E.sessionid]),B=m.get(D)??{lines:[],options:{}};B.lines.push(`You: ${S}`),M.reply&&B.lines.push(`Agent: ${M.reply}`),M.error&&B.lines.push(`${M.status}: ${M.error}`),B.options={...x},m.set(D,B)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},y=(E,S)=>new Error(`${E}: ${S.error??"operation failed"}`),b=(E,S)=>{if(S.status!=="ok")throw y(E,S);return S},w=(E,S="lm_batch_turn",x=!1)=>{if(E!==null&&typeof E=="object"&&aJ.isProxy(E))throw Error("Resource batch id cannot be read from a proxy");let I=E!==null&&typeof E=="object"?Object.getOwnPropertyDescriptor(E,"id"):void 0;if(I&&!("value"in I))throw Error("Resource batch id must be an own data property, not an accessor");let O=typeof E=="string"?E:I?.value,M=typeof O=="string"?d.get(O):void 0,D=Zo();if(!M){if(typeof O=="string"&&/^run-[0-9]+-[0-9]+\//.test(O)&&D&&!O.startsWith(D.runtime.token+"/"))throw Error("Resource batch "+O+" belongs to another run: "+S);return}if(!D)throw Error("Resource batch "+O+" requires an authorized script invocation");return D.runtime.authorizeRaw(M,D.scope,S,x),M},k=E=>{let S=Zo();if(!S)throw Error("lm_batch_open requires an authorized script invocation");E.id=S.runtime.token+"/"+oJ(),E.kind="lmctl batch",E.closeDeadlineMs=5e3;let x;return E.close=(I={})=>{if(x)return x;let O,M;return x=new Promise((D,B)=>{O=D,M=B}),(async()=>{let D=l.get(E);if(D){b("lm_batch_close",await s.closeNativeSession(f(),D));return}let B=c.get(E);if(B){B.closed=!0;return}let $=I.explicit??[],te=I.reason==="cancelled"?"cancelled":$[0]??(E.observedError?"error":I.reason??"done");b("lm_batch_close",await s.closeBatch(f(),u.get(E),{status:te==="done"?"done":te==="cancelled"?"cancelled":"error",error:$[1]??I.error}))})().then(O,M),x},E.finalizeSync=()=>{let I=f();if(I.closed){let O=I.finalizeSync("SIGTERM");if(O.errors.length)throw Error(O.errors.join(`
|
|
2423
|
+
`)||`terminal exited with code ${m.code}`,code:m.code,signal:m.signal}}catch(l){return o?.cleanupError?.()&&(i=!0),r(z(l),"provider")}finally{i||s?.()}}var pN=L(()=>{"use strict";dN();on();cn();ft()});import{isAbsolute as tJ,resolve as nJ}from"node:path";function lm(t){return Number.isFinite(t)&&Math.abs(t)<=rJ}function sJ(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ta.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 E_(t,e=Date.now()){if(t===void 0)return{windowMs:cm};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let i=Number(n[1]),o=n[2],l=(o==="s"?i:o==="m"?i*60:o==="h"?i*3600:i*86400)*1e3;return!Number.isFinite(l)||l<0||!lm(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!lm(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return lm(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function am(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function w_(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return v_;let s=e.get(n);if(s===void 0){try{s=Kt(n)}catch{s=null}e.set(n,s)}return s===null?v_:bu(s,r)?.model??v_}async function fN(t,e={}){let n=_e(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 i=kr("listRunning");if(i.length>0){for(let o of Object.keys(e))if(!i.includes(o))return{status:"error",error:`Unknown option: ${o}`,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=cm;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!lm(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 i=E_(e.since,r);if("error"in i)return{status:"error",error:i.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=i.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let i=gn(t),o=e?.teamfile!==void 0?tJ(e.teamfile)?e.teamfile:nJ(t.cwd,e.teamfile):void 0,a=o!==void 0?Dt(o,i):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),u=i.listAllRunningTrackedInvocations().filter(c),d=new Map,m=[],p=[];for(let y of u){let b=Zc(y),w=r-new Date(y.started_at).getTime(),k={id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:am(y),model:w_(y,d),started_at:y.started_at,parent_invocation_id:y.parent_invocation_id};if(b==="dead"){if(e?.reconcile===!0&&r_(i,y)!==null)continue;p.push({...k,stale_for_ms:w})}else m.push({...k,running_for_ms:w,holder_liveness:b??"unknown"})}let f=new Set(u.map(am).filter(y=>y!==null)),h=new Date(r-s).toISOString(),g=i.listRecentlyFinishedTrackedInvocations(h).filter(c),_=new Set,v=[];for(let y of g){let b=am(y);b===null||f.has(b)||_.has(b)||(_.add(b),v.push({id:y.id,kind:y.kind,origin:y.origin,from_identity:y.from_identity,target:b,model:w_(y,d),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([...m.map(w=>w.id),...p.map(w=>w.id),...v.map(w=>w.id)]),b=[...y];for(;b.length>0;){let w=i.listFinishedTrackedInvocationChildren(b,h).filter(k=>!y.has(k.id)&&c(k));if(w.length===0)break;b=[];for(let k of w){y.add(k.id),b.push(k.id);let T=am(k);v.push({id:k.id,kind:k.kind,origin:k.origin,from_identity:k.from_identity,target:T,model:w_(k,d),status:k.status,started_at:k.started_at,ended_at:k.ended_at,idle_ms:r-new Date(k.ended_at).getTime(),ran_ms:new Date(k.ended_at).getTime()-new Date(k.started_at).getTime(),error:k.error,parent_invocation_id:k.parent_invocation_id})}}}return{status:"ok",error:null,running:m,dead:p,idle:v}}catch(i){return{status:"error",error:i instanceof Error?i.message:String(i),code:sJ(i),running:[],dead:[],idle:[]}}}var cm,rJ,v_,gN=L(()=>{"use strict";on();cn();sr();cr();Xd();Mn();Ys();cm=24*60*60*1e3,rJ=864e13;v_="default"});var hN={};Sn(hN,{DAY_MS:()=>cm,LMCTL_API_VERSION:()=>LK,LMCTL_ERROR_CODES:()=>ta,LMCTL_OPERATIONS:()=>wt,LMCTL_PROFILE_VALUE_NAMES:()=>BM,LMCTL_PROPERTY_KEYS:()=>$p,LMCTL_PROPERTY_TABLES:()=>HM,LMCTL_REMOVED_GLOBALS:()=>Up,LMCTL_RESULT_FIELDS:()=>UM,NativeSessionManager:()=>im,agentMessage:()=>cC,batchTurn:()=>VC,classifyFailure:()=>iC,closeBatch:()=>KC,closeNativeSession:()=>ci,createLmctlContext:()=>Hf,deleteSession:()=>iA,fail:()=>H,finalizeBatchSync:()=>XC,finalizeNativeSessionSync:()=>tN,getSession:()=>sA,inspectBatch:()=>GC,isLmctlContext:()=>Ji,lintTeam:()=>p2,listMembers:()=>d2,listRunning:()=>fN,listSessions:()=>rA,loadProfile:()=>k$,loadProperties:()=>R$,nativeSessionClose:()=>oN,nativeSessionRequest:()=>iN,nativeSessionTurn:()=>To,ok:()=>he,openNativeSession:()=>Eo,openTeamBatch:()=>JC,openTerminal:()=>mN,parseRunningSince:()=>E_,profileValues:()=>S$,promptAgent:()=>YI,promptMember:()=>FC,promptReservedAgent:()=>eA,readPrompts:()=>y2,readRatelimits:()=>FX,releaseSession:()=>nA,reserveSession:()=>tA,resolveMember:()=>m2,resolveProfilePath:()=>tg,seedErrorCollector:()=>XI,seedTeam:()=>f2,sessionAdmission:()=>ZI});var yN=L(()=>{"use strict";ft();on();ES();sr();GI();JI();oA();sC();oC();By();uC();jC();zC();sm();aN();pN();gN();__()});var wN={};Sn(wN,{createLmctlHostModule:()=>vN,default:()=>_J});import{AsyncLocalStorage as iJ}from"node:async_hooks";import{randomUUID as oJ}from"node:crypto";import{types as aJ}from"node:util";import{createInterface as lJ}from"node:readline";import{Writable as cJ}from"node:stream";import{readFileSync as uJ}from"node:fs";import{resolve as dJ}from"node:path";import{homedir as mJ}from"node:os";function _N(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ta.includes(e))return e;if(e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}}return"internal"}function hJ(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[T_,...t.params??[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]],readonly:t.name==="lm_error",dryControl:t.name==="lm_error"?"error":"output"};if(t.name==="lm_exit")return{...t,arity:{min:0,max:2},params:[{name:"code",type:"number",optional:!0},T_],readonly:!0};if(um.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"||t.name==="lm_agent_message"){let e=t.params??[{name:"file",type:"string"}],n=typeof t.arity=="number"?t.arity:t.arity.min;return{...t,arity:{min:n,max:e.length+1},params:[...e,T_],readonly:um.has(t.name)}}return t}function vN(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:yJ,async activate(r){let s=t.api??await Promise.resolve().then(()=>(yN(),hN)),i,o=new iJ,a=()=>o.getStore()??e,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new Map,m=new Map,p=!1,f=()=>{if(i)return i;let E={...r.env};!E.HOME&&!E.LMCTL_HOME&&!E.LMCTL_DB&&(E.HOME=mJ());let S=s.createLmctlContext({env:E,cwd:r.cwd,pid:process.pid,onProgress:(x,I)=>a()[I??"stderr"](x),onWarning:x=>a().stderr(x)});if(S.status!=="ok")throw Error(S.error);return i=S,t.onContext?.(i),i},h={},g=()=>{let E=s.loadProperties(f());if(E.status!=="ok")throw Error(E.error);return{path:E.path,properties:E.properties,hint:"Define it in "+E.path+" or run lmctl init"}},_=()=>i&&!i.closed&&i.finalizeSync(r.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r.signal?.addEventListener("abort",_,{once:!0}),r.signal?.aborted&&_();let v=async(E,S,x={},I)=>{let O=x&&typeof x=="object"&&!Array.isArray(x)?{permissionMode:x.permissionMode??"yolo",idleTimeoutMs:x.idleTimeoutMs??void 0}:x,M=I?await s.promptReservedAgent(f(),I,E,S,O):await s.promptAgent(f(),E,S,O);if(E&&typeof E=="object"&&M.sessionid&&M.status!=="busy"&&(E.sessionid=M.sessionid),E?.sessionid&&M.status!=="busy"){let D=JSON.stringify([E.provider,E.sessionid]),B=m.get(D)??{lines:[],options:{}};B.lines.push(`You: ${S}`),M.reply&&B.lines.push(`Agent: ${M.reply}`),M.error&&B.lines.push(`${M.status}: ${M.error}`),B.options={...x},m.set(D,B)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},y=(E,S)=>new Error(`${E}: ${S.error??"operation failed"}`),b=(E,S)=>{if(S.status!=="ok")throw y(E,S);return S},w=(E,S="lm_batch_turn",x=!1)=>{if(E!==null&&typeof E=="object"&&aJ.isProxy(E))throw Error("Resource batch id cannot be read from a proxy");let I=E!==null&&typeof E=="object"?Object.getOwnPropertyDescriptor(E,"id"):void 0;if(I&&!("value"in I))throw Error("Resource batch id must be an own data property, not an accessor");let O=typeof E=="string"?E:I?.value,M=typeof O=="string"?d.get(O):void 0,D=Zo();if(!M){if(typeof O=="string"&&/^run-[0-9]+-[0-9]+\//.test(O)&&D&&!O.startsWith(D.runtime.token+"/"))throw Error("Resource batch "+O+" belongs to another run: "+S);return}if(!D)throw Error("Resource batch "+O+" requires an authorized script invocation");return D.runtime.authorizeRaw(M,D.scope,S,x),M},k=E=>{let S=Zo();if(!S)throw Error("lm_batch_open requires an authorized script invocation");E.id=S.runtime.token+"/"+oJ(),E.kind="lmctl batch",E.closeDeadlineMs=5e3;let x;return E.close=(I={})=>{if(x)return x;let O,M;return x=new Promise((D,B)=>{O=D,M=B}),(async()=>{let D=l.get(E);if(D){b("lm_batch_close",await s.closeNativeSession(f(),D));return}let B=c.get(E);if(B){B.closed=!0;return}let $=I.explicit??[],te=I.reason==="cancelled"?"cancelled":$[0]??(E.observedError?"error":I.reason??"done");b("lm_batch_close",await s.closeBatch(f(),u.get(E),{status:te==="done"?"done":te==="cancelled"?"cancelled":"error",error:$[1]??I.error}))})().then(O,M),x},E.finalizeSync=()=>{let I=f();if(I.closed){let O=I.finalizeSync("SIGTERM");if(O.errors.length)throw Error(O.errors.join(`
|
|
2424
2424
|
`));return}if(l.has(E))b("lm_batch_close",s.finalizeNativeSessionSync(I,l.get(E)));else if(u.has(E))b("lm_batch_close",s.finalizeBatchSync(I,u.get(E)));else{let O=c.get(E);O&&(O.closed=!0)}},d.set(E.id,E),E},T=E=>E&&typeof E=="object"?u.get(E):void 0,R=E=>{let S=T(E);if(S){let x=b("lm_batch_open",s.inspectBatch(f(),S)),{status:I,error:O,...M}=x;Object.assign(E,{...M,id:E.close?E.id:M.id})}},N={lm_exit:(E=0)=>{let S=Number(E);throw new Wt(Number.isFinite(S)&&S>=0&&S<=255?Math.floor(S):1)},lm_log:(E,...S)=>{let x=bN(S);return a().stderr(x.endsWith(`
|
|
2425
2425
|
`)?x:x+`
|
|
2426
2426
|
`),x},lm_error:(E,...S)=>{let x=bN(S);return o.getStore()?.errors?.push(x),r.reportRecordedError(x),a().stderr("error: "+x+`
|