@lmctl-ai/lmctl 0.2.128 → 0.2.129
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/CHANGELOG.md +2 -0
- package/build-info.json +1 -1
- package/dist/cli/lmscript.js +5 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,8 @@ All notable public-preview changes for `@lmctl-ai/lmctl` are recorded here.
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
- Resource help and executed examples now describe lexical batch ownership, id-only handles, runtime escape refusal, async acquisition and signal/lease limits. Terminal, operator-prompt and one-shot prompt ownership stays internal.
|
|
8
|
+
|
|
7
9
|
- GraphQL literal docs/help now describe raw executable strings, ten schema-free preflight rules, fragment-only composition and gh variables. Examples and exact rejection diagnostics run on both lmscript and lmctl script; field/argument/type/enum schema validation remains a future library hook.
|
|
8
10
|
- Admitted team seed dispatches now record private usage rows with team/alias and copied prices. Chat/history/backfill exclude these non-event rows. Pre-dispatch refusals create no row; unavailable evidence stays unknown; accounting failures never change seed results. Additive v65 preserves the reader floor and historical rows.
|
|
9
11
|
|
package/build-info.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"sha": "
|
|
1
|
+
{"sha": "3eb85e69accb80e4e4ae0df047138f51f2890d9e", "dirty": false, "builtAt": "2026-10-07T12:19:32.000Z"}
|
package/dist/cli/lmscript.js
CHANGED
|
@@ -410,13 +410,15 @@ assert(json_stringify(args) == '["program","a= ","b=adsfa"]');
|
|
|
410
410
|
Fields \${value} insert opaque strings/numbers; a whole-word list field splices arguments. Quotes/escapes protect literal punctuation. Word-start # comments and backslash-newline continuation are supported; // is text.
|
|
411
411
|
No shell pipes, redirects, globbing, bare dollar variables or substitutions. Use system(argv, timeoutMs) for options; system(string) is refused. Default timeout 60000 ms, 0 disables it; nonzero process exits are data.
|
|
412
412
|
cmd_render(argv, dialect) outputs posix/windows/powershell text; never pass rendered text to system. Default windows on win32, otherwise posix. Windows encoding is CRT argument-tail syntax, not cmd.exe; on win32, .cmd/.bat shims are refused. PowerShell output needs & and 7.3+ native argument mode when executed.
|
|
413
|
+
`;if(n==="resources")return["Topic: Automatic resource closing","lm_batch_open is the only returned production resource; acquisition is async-only. CLI is async; sync SDK refuses before calling a factory.","The first receiving binding owns the handle in its lexical block/iteration/function/root/task; aliases and arguments borrow, with no reference counting.","Only read-only id is public. Returning/storing/coercing a handle fails at runtime; ids do not transfer authority to another run or expired owner.","Owners close in reverse acquisition order on normal exit or unwind; explicit lm_batch_close joins that idempotent close. Failed close stays recorded/unresolved.","SIGINT/SIGTERM critical release precedes exit 130/143. A busy writer can prevent release; report the failure. SIGKILL, remote cancellation and blocking callbacks have no strict cleanup guarantee.","Do not pass a handle directly to require; use require(handle != null, message). Identity/null tests and if(handle) are allowed.","SDK dryRun/dryRunAsync skip resource acquisition with null; a null guard can stop with needs-real-result/0. CLI check/dry-run is validation-only.","Batch close has one 5000 ms budget. Terminal/prompt_human/lm_prompt resources stay INTERNAL; their returned values remain ordinary data.","Examples: examples/resource_batch.lms TEAMFILE [fail|exit]; examples/resource_escape.lms TEAMFILE; examples/resource_signal.lms TEAMFILE.","These may run provider turns. See the language reference for expected outputs and signal procedure; check/dry-run opens nothing."].join(`
|
|
414
|
+
`)+`
|
|
413
415
|
`;if(n==="conditional")return`condition ? trueExpr : falseExpr
|
|
414
416
|
Precedence below || and above assignment; only the selected arm is evaluated.
|
|
415
417
|
`;if(n==="graphql")return["Topic: GraphQL literals","graphql"+'"'.repeat(3)+"..."+'"'.repeat(3)+" or graphql"+"'".repeat(3)+"..."+"'".repeat(3),"Raw lowercase triple strings: no interpolation, decoding or dedent; CRLF becomes LF. The first unescaped outer delimiter closes the literal, even in a GraphQL comment/block string; use opposite outer quotes.","Executable October 2021 syntax is checked in run preflight, --check and --dry-run before effects; failures exit 2 with error:FILE:LINE:COLUMN: GraphQL: MESSAGE.","Schema-free rules: Undefined fragment; Fragment cycle; Undefined variable; Unused variable; Unused fragment; Duplicate operation; Duplicate fragment; Duplicate variable; Duplicate argument; Anonymous operation must be alone.","Variable usage includes transitive fragments, directives and nested values; argument uniqueness is per field/directive list.","Fragment-only documents skip unused-fragment/operation-variable checks, retaining spread/cycle/duplicate checks. Plain/runtime-built strings and concatenation are unlinted; each constituent graphql literal is still checked independently.","No field/argument/type/enum validation, subscription root cardinality, input-object field/directive uniqueness, schema selector or execution. Domain checks are a future library hook; parameter tags are deferred.","Use GraphQL variables and a separate map; modules/gh.lms exposes gh.gh_graphql(query, vars) and owns tool/response failures.","Example:","q = graphql"+'"'.repeat(3)+"{ viewer { login } }"+'"'.repeat(3)+";","println(q);"].join(`
|
|
416
418
|
`)+`
|
|
417
419
|
`;if(n==="recover")return["Topic: Recover blocks and resume points","recover { resumepoint NAME: statements ... }","--resumepoint NAME(.NAME)* goes before FILE, -, or -e CODE.","The first entered recover consumes a segment; earlier points are skipped and later points fall through. Prelude code still runs.","One block scope; nested paths are dotted. RESUMEPOINT is read-only, null outside points; helpers inherit the active path.","No saved state, catching or automatic retry. Reload needed state; recover cannot enter in a parallel task or reenter in one run.","A nonzero run reports its first failure point after diagnostics. An earlier failure outside points suppresses the hint; final exit 0 and check errors have no hint.","Example: lmscript --resumepoint b -e 'recover { resumepoint a: println(RESUMEPOINT); resumepoint b: println(RESUMEPOINT); }'"].join(`
|
|
418
420
|
`)+`
|
|
419
|
-
`;if(n==="topics")return`Topics: conditional, regex, graphql, cmd, recover
|
|
421
|
+
`;if(n==="topics")return`Topics: conditional, regex, graphql, cmd, recover, resources
|
|
420
422
|
`;if(n==="regex")return`Topic: Regular expressions
|
|
421
423
|
JavaScript RegExp patterns; use regex_test, regex_match, regex_find_all, regex_replace and split_regex.
|
|
422
424
|
Use raw strings for backslashes; g means global matching; y is rejected by matching helpers.
|
|
@@ -437,9 +439,9 @@ ${l.parameters?.length?`Parameters:
|
|
|
437
439
|
`;let c=o.filter(u=>(u.module??"core")===l);for(let u of[...new Set(c.map(d=>d.category))].sort()){a+=" "+u+`:
|
|
438
440
|
`;for(let d of c.filter(m=>m.category===u).sort((m,p)=>m.name.localeCompare(p.name)))a+=" "+(d.signature??d.name)+`
|
|
439
441
|
`}}return a+`
|
|
440
|
-
Topics: conditional, regex, graphql, cmd, recover
|
|
442
|
+
Topics: conditional, regex, graphql, cmd, recover, resources
|
|
441
443
|
Use help <function|built-in|topic> for details.
|
|
442
|
-
`}var Qg=O(()=>{"use strict";Jo()});var bB,Mn,AI,CI,NI,fu,gu,hu,we,mu,Ht,Vo,ri,Ko,zo,pu,Zg,eh,th,si,nh,nt,Dn=O(()=>{"use strict";bB=1,Mn=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Mn(e);Object.freeze(t)}return t},AI=Mn(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal"]),CI=Mn({status:"string",error:"string|null",code:"ErrorCode?"}),NI=Mn(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),fu=Mn(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),gu=Mn(["Provider1","Provider2","Provider3"]),hu=Mn({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),we={name:"ctx",type:"context"},mu={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},Ht={name:"teamfile",type:"string"},Vo={name:"alias",type:"string"},ri={name:"prompt",type:"string"},Ko={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"}]},zo=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],pu={name:"options",type:"map",optional:!0,keys:zo},Zg={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},eh={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},th={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},si={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},nh={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},nt=Mn([{name:"resolveProfilePath",implemented:!0,params:[we,mu],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[we,mu],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:"readPrompts",implemented:!0,params:[we,{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:[we,Ht],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[Ht]}},{name:"resolveMember",implemented:!0,params:[we,Ht,Vo],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:[Ht,Vo]}},{name:"lintTeam",implemented:!0,params:[we,Ht],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:[Ht]}},{name:"seedTeam",implemented:!0,params:[we,Ht,Zg],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:[Ht,Zg]}},{name:"promptAgent",implemented:!0,params:[we,Ko,ri,pu],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...nh,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Ko,ri,pu]}},{name:"promptMember",implemented:!0,params:[we,{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"},...zo]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[Ht,Vo,ri,{name:"options",type:"map",optional:!0,keys:[...zo,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[we,{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:[we,si,th],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:[Ko,{...th,optional:!0}]}},{name:"getSession",implemented:!0,params:[we,si],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages."},{name:"reserveSession",implemented:!0,params:[we,si],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:[we,si,{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:[we,{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"},...zo]}],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:[we,{name:"batch",type:"BatchRef"},ri,{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:[we,{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:[we,eh],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:[eh]}},{name:"openTerminal",implemented:!0,params:[we,{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:[Ht,Vo]}},{name:"sessionAdmission",implemented:!0,params:[we,si],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:[we,{name:"reservation",type:"SessionReservation"},Ko,ri,pu],statuses:["ok","busy","stalled","empty","error"],results:{...nh,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[we,{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:[we,{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:"loadProperties",implemented:!0,params:[we,mu],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."}])});var rh,sh=O(()=>{"use strict";rh=[{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 a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",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:"map",description:"Batch handle object or null on error"},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:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'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 session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{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 the reply.",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, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{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_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:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{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_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" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},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 terminal lock and tracked invocation are released by the host on completion, failure, cancellation or signal; 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, code } after the TUI exits"},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", 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", 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:"string[]",description:"List of prompt strings"},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:"string[]",description:"List of paragraph strings"},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:"List of member records { 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|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},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 me(t){return{...t,status:"ok",error:null}}function B(t,e,n){return{...n,status:"error",code:t,error:e}}var rt=O(()=>{"use strict"});function oh(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?ii:ih}var ih,ii,_u=O(()=>{"use strict";ih="root_teamfile <> '(direct)'",ii=ih+" AND COALESCE(accounting_only,0)=0"});import{existsSync as OI}from"node:fs";import{createRequire as LI}from"node:module";function PI(){return yu===null&&(yu=LI(import.meta.url)("node:sqlite").DatabaseSync),yu}function FI(t){let e=DI[t];if(e!==void 0)return e;let n=MI[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function _r(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=FI(t.errcode)),t}function jI(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function UI(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function Eu(t){return t.length===1&&$I(t[0])?[t[0]]:t}function $I(t){if(!vu(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function vu(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var yu,MI,DI,bu,zr,wu,Yo=O(()=>{"use strict";yu=null;MI={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"},DI={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"};bu=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!OI(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(PI())(e,{readOnly:n.readonly===!0})}catch(r){_r(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new wu(this.handle.prepare(e))}catch(n){_r(n)}}exec(e){try{this.handle.exec(e)}catch(n){_r(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){_r(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(!jI(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(!UI(o))throw o}throw i}}};zr=bu,wu=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...Eu(e));return this.normalizeRow(n)}catch(n){_r(n)}}all(...e){try{return this.handle.all(...Eu(e)).map(n=>this.normalizeRow(n))}catch(n){_r(n)}}run(...e){try{let n=this.handle.run(...Eu(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){_r(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&vu(e)?Object.values(e):vu(e)?{...e}:e}}});function Tu(t){return new zr(t,{readonly:!0,fileMustExist:!0})}var ah=O(()=>{"use strict";Yo()});import{createHash as BI}from"node:crypto";import{lstat as HI,readFile as WI,realpath as lh,stat as ch}from"node:fs/promises";import{isAbsolute as uh,relative as qI,resolve as XI,sep as GI}from"node:path";function G(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function Q(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function oi(t){return Q(t)}function Et(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function se(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 pe(t,e){return t<e?-1:t>e?1:0}function Ve(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 Wt(t,e,n){let r={},s=oi(t.cacheWrite5m),i=oi(t.cacheWrite1h),o=oi(t.reasoning),a=oi(t.webSearch),l=oi(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 Fn(t){return typeof t=="string"&&VI.has(t.toLowerCase())}function Re(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 Yr(t){let e=G(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function De(t,e){if(!uh(t))return null;let n=await HI(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await lh(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await lh(s).catch(()=>XI(s)),o=qI(i,r);if(o===""||!o.startsWith(`..${GI}`)&&o!==".."&&!uh(o))return r}return null}async function it(t,e){se(e);let n=await ch(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await WI(t,{signal:e.signal});e.signal.throwIfAborted();let s=await ch(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${ai}:sha256:${BI("sha256").update(r).digest("hex")}`,data:r}}function Qo(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(`
|
|
444
|
+
`}var Qg=O(()=>{"use strict";Jo()});var bB,Mn,AI,CI,NI,fu,gu,hu,we,mu,Ht,Vo,ri,Ko,zo,pu,Zg,eh,th,si,nh,nt,Dn=O(()=>{"use strict";bB=1,Mn=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Mn(e);Object.freeze(t)}return t},AI=Mn(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal"]),CI=Mn({status:"string",error:"string|null",code:"ErrorCode?"}),NI=Mn(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),fu=Mn(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),gu=Mn(["Provider1","Provider2","Provider3"]),hu=Mn({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),we={name:"ctx",type:"context"},mu={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},Ht={name:"teamfile",type:"string"},Vo={name:"alias",type:"string"},ri={name:"prompt",type:"string"},Ko={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"}]},zo=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],pu={name:"options",type:"map",optional:!0,keys:zo},Zg={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},eh={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},th={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},si={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},nh={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},nt=Mn([{name:"resolveProfilePath",implemented:!0,params:[we,mu],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[we,mu],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:"readPrompts",implemented:!0,params:[we,{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:[we,Ht],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[Ht]}},{name:"resolveMember",implemented:!0,params:[we,Ht,Vo],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:[Ht,Vo]}},{name:"lintTeam",implemented:!0,params:[we,Ht],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:[Ht]}},{name:"seedTeam",implemented:!0,params:[we,Ht,Zg],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:[Ht,Zg]}},{name:"promptAgent",implemented:!0,params:[we,Ko,ri,pu],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...nh,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Ko,ri,pu]}},{name:"promptMember",implemented:!0,params:[we,{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"},...zo]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[Ht,Vo,ri,{name:"options",type:"map",optional:!0,keys:[...zo,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[we,{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:[we,si,th],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:[Ko,{...th,optional:!0}]}},{name:"getSession",implemented:!0,params:[we,si],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages."},{name:"reserveSession",implemented:!0,params:[we,si],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:[we,si,{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:[we,{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"},...zo]}],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:[we,{name:"batch",type:"BatchRef"},ri,{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:[we,{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:[we,eh],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:[eh]}},{name:"openTerminal",implemented:!0,params:[we,{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:[Ht,Vo]}},{name:"sessionAdmission",implemented:!0,params:[we,si],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:[we,{name:"reservation",type:"SessionReservation"},Ko,ri,pu],statuses:["ok","busy","stalled","empty","error"],results:{...nh,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[we,{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:[we,{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:"loadProperties",implemented:!0,params:[we,mu],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."}])});var rh,sh=O(()=>{"use strict";rh=[{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; member-map batches retain session identity without team leases, bundle optimization or team tracking.",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:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",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:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'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 session and finalizes tracked invocations and bundle leases.",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, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{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_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:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{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_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" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},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, code } after the TUI exits"},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", 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", 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:"string[]",description:"List of prompt strings"},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:"string[]",description:"List of paragraph strings"},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:"List of member records { 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|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},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 me(t){return{...t,status:"ok",error:null}}function B(t,e,n){return{...n,status:"error",code:t,error:e}}var rt=O(()=>{"use strict"});function oh(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?ii:ih}var ih,ii,_u=O(()=>{"use strict";ih="root_teamfile <> '(direct)'",ii=ih+" AND COALESCE(accounting_only,0)=0"});import{existsSync as OI}from"node:fs";import{createRequire as LI}from"node:module";function PI(){return yu===null&&(yu=LI(import.meta.url)("node:sqlite").DatabaseSync),yu}function FI(t){let e=DI[t];if(e!==void 0)return e;let n=MI[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function _r(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=FI(t.errcode)),t}function jI(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function UI(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function Eu(t){return t.length===1&&$I(t[0])?[t[0]]:t}function $I(t){if(!vu(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function vu(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var yu,MI,DI,bu,zr,wu,Yo=O(()=>{"use strict";yu=null;MI={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"},DI={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"};bu=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!OI(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(PI())(e,{readOnly:n.readonly===!0})}catch(r){_r(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new wu(this.handle.prepare(e))}catch(n){_r(n)}}exec(e){try{this.handle.exec(e)}catch(n){_r(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){_r(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(!jI(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(!UI(o))throw o}throw i}}};zr=bu,wu=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...Eu(e));return this.normalizeRow(n)}catch(n){_r(n)}}all(...e){try{return this.handle.all(...Eu(e)).map(n=>this.normalizeRow(n))}catch(n){_r(n)}}run(...e){try{let n=this.handle.run(...Eu(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){_r(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&vu(e)?Object.values(e):vu(e)?{...e}:e}}});function Tu(t){return new zr(t,{readonly:!0,fileMustExist:!0})}var ah=O(()=>{"use strict";Yo()});import{createHash as BI}from"node:crypto";import{lstat as HI,readFile as WI,realpath as lh,stat as ch}from"node:fs/promises";import{isAbsolute as uh,relative as qI,resolve as XI,sep as GI}from"node:path";function G(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function Q(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function oi(t){return Q(t)}function Et(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function se(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 pe(t,e){return t<e?-1:t>e?1:0}function Ve(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 Wt(t,e,n){let r={},s=oi(t.cacheWrite5m),i=oi(t.cacheWrite1h),o=oi(t.reasoning),a=oi(t.webSearch),l=oi(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 Fn(t){return typeof t=="string"&&VI.has(t.toLowerCase())}function Re(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 Yr(t){let e=G(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function De(t,e){if(!uh(t))return null;let n=await HI(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await lh(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await lh(s).catch(()=>XI(s)),o=qI(i,r);if(o===""||!o.startsWith(`..${GI}`)&&o!==".."&&!uh(o))return r}return null}async function it(t,e){se(e);let n=await ch(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await WI(t,{signal:e.signal});e.signal.throwIfAborted();let s=await ch(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${ai}:sha256:${BI("sha256").update(r).digest("hex")}`,data:r}}function Qo(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(`
|
|
443
445
|
`),s=[];for(let i of r)if(e.signal.throwIfAborted(),!!i.trim())try{let o=G(JSON.parse(i));if(!o)return null;s.push(o)}catch{return null}return s}var ai,st,_t,JI,yt,VI,dn=O(()=>{"use strict";ai="bx3",st={input_uncached:null,input_cached:null,input_cache_write:null,output:null};_t=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}},JI=0,yt=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${JI++}`,this.map.has(n)||this.map.set(n,e)}entries(){return[...this.map.values()]}};VI=new Set(["schedulewakeup","taskcreate","taskupdate","taskoutput","taskstop","todowrite","todoread","croncreate","crondelete","cronlist","monitor","listagents","toolsearch","askuserquestion","exitplanmode","agent","skill","job"])});import{readdir as KI}from"node:fs/promises";import{join as dh,sep as mh}from"node:path";var Qr,Su=O(()=>{"use strict";dn();Qr=class{constructor(e){this.format=e}async discover(e,n,r){se(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 KI(l,{withFileTypes:!0}).catch(m=>(m.code!=="ENOENT"&&(o=!0),[])),d=m=>dh(l,m.name)+(m.isDirectory()?mh:"");for(let m of u.sort((p,f)=>pe(d(p),d(f)))){e.signal.throwIfAborted();let p=dh(l,m.name),f=m.isDirectory()&&r?.startsWith(p+mh);if(!(r&&!f&&pe(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)=>pe(l.source_id,c.source_id)),{sources:s.slice(0,n),truncated:o||s.length>n}}async bytes(e,n){if(se(n),e.provider!==this.format.provider||this.format.sessionId(e.source_id)!==e.sessionid)return null;let r=await De(e.source_id,[this.format.root]);if(!r)return null;let s=await it(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 Zr(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 Zo=O(()=>{"use strict"});import{createReadStream as ph}from"node:fs";import{createInterface as fh}from"node:readline";import{stat as zI}from"node:fs/promises";import{homedir as YI}from"node:os";function gh(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*ve(t,e){let n=ph(t,{encoding:"utf-8"}),r=fh({input:n,crlfDelay:1/0});try{for await(let s of r){let i=s.trim();if(!i)continue;let o=gh(i);o!==void 0?yield o:e?.()}}finally{n.destroy()}}async function bt(t,e){let n=[],r=ph(t,{encoding:"utf-8"}),s=fh({input:r,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=gh(o);if(a!==void 0&&n.push(a),n.length>=e)break}}finally{s.close(),r.destroy()}return n}async function xe(t){let e=await zI(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function ge(t){return t.replace(/\\n/g,`
|
|
444
446
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function V(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ct(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ee,Le=O(()=>{"use strict";ee=YI()});import{readdir as QI}from"node:fs/promises";import{join as es,resolve as ZI}from"node:path";function ta(t){return ZI(t||process.env.XDG_DATA_HOME||es(ee,".local","share"))}function ex(t){return es(ta(t),"muse","sessions")}function tx(t,e,n,r){let s=r?.input_uncached_tokens,i=r?.cache_read_tokens??r?.input_cache_read_tokens,o=r?.cache_write_tokens??r?.input_cache_write_tokens;return{response_id:t,timestamp:e.toISOString(),model:typeof n=="string"&&n.length>0?n:null,tokens:{input_uncached:typeof s=="number"?s:null,input_cached:typeof i=="number"?i:null,input_cache_write:typeof o=="number"?o:null,output:typeof r?.output_tokens=="number"?r.output_tokens:null},files_read:null,files_written:null}}function yh(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 b=l.get(_);return b||(b={id:_,turn:{id:_,status:"unknown"},responseIds:[]},l.set(_,b)),b},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 b=_.payload?.source_run_record_id;for(let T of[_.id,b])if(!(typeof T!="string"||T.length===0)&&u.has(T))return;for(let T of[_.id,b])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 E=_.payload;if(_.payload_type==="runtime.session.metadata"&&(typeof E?.record?.workspace_root=="string"&&(n=E.record.workspace_root),typeof E?.record?.model_id=="string"&&(r=E.record.model_id)),_.payload_type!=="runtime.session"||E?.kind!=="run")return;let w=E.event,S=f(E.run_id);if(!w||!y||!S){w||p();return}if(w.kind==="started"&&typeof w.prompt=="string")a.push({role:"user",content:w.prompt,timestamp:y}),S.turn.startedAt=y,S.turn.prompt=w.prompt,S.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")S.turn.completedAt=y,S.turn.status=w.terminal==="completed"?"complete":"aborted",o=S.turn.status;else if(w.kind==="model_completed"){typeof w.model=="string"&&w.model.length>0&&(r=w.model,S.turn.model=w.model);let T=typeof b=="string"&&b.length>0?b:typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(!T)p();else{S.responseIds.push(T);let I={};if(w.usage&&typeof w.usage=="object")for(let A 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"]){let N=w.usage[A];typeof N=="number"&&Number.isSafeInteger(N)&&N>=0&&(I[A]=N)}Object.keys(I).length>0&&(S.turn.rawUsage=[...S.turn.rawUsage??[],{responseId:T,values:I}]),c.set(T,tx(T,y,w.model,I))}if(!w.usage)return;let x={},C=w.usage.input_uncached_tokens,L=w.usage.cache_read_tokens??w.usage.input_cache_read_tokens,k=w.usage.cache_write_tokens??w.usage.input_cache_write_tokens,v=w.usage.output_tokens,R=w.usage.reasoning_tokens;typeof C=="number"&&Number.isSafeInteger(C)&&C>=0&&(x.inputTokens=C),typeof L=="number"&&Number.isSafeInteger(L)&&L>=0&&(x.cachedInputTokens=L),typeof k=="number"&&Number.isSafeInteger(k)&&k>=0&&(x.cacheWriteInputTokens=k),typeof v=="number"&&Number.isSafeInteger(v)&&v>=0&&(x.outputTokens=v),typeof R=="number"&&Number.isSafeInteger(R)&&R>=0&&(x.reasoningOutputTokens=R),d=x}};return{visit:h,finish:()=>{if(!n||!s||!i)return null;let _=a.filter(w=>w.role==="user").map(w=>w.content),b=[...l.values()].map(w=>({...w.turn,...w.responseIds.length>0?{responseIds:[...w.responseIds]}:{}})),y=[...c.values()],E=Zr(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:E.input_uncached??void 0,totalCachedInputTokens:E.input_cached??void 0,totalCacheWriteInputTokens:E.input_cache_write??void 0,totalOutputTokens:E.output??void 0,lastTokenUsage:d,turns:b,responses:y,...m?{captureStatus:m}:{}}},markPartial:p}}function nx(t,e,n){let r=yh(e,n);for(let s of t)r.visit(s);return r.finish()}function rx(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=nx(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function Eh(t){return{provider:"muse",root:ex(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:rx}}async function _h(t,e){let n=yh(t,e);for await(let r of ve(e,n.markPartial))n.visit(r);return n.finish()}var hh,ea,ku=O(()=>{"use strict";Zo();Le();hh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ea=class{name="muse";dataHome;constructor(e={}){this.dataHome=ta(e.museDataHome)}get root(){return es(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await QI(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(es(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(es(e,i.name),n+1));return s}async resolveSessionPath(e){return hh.test(e)?(await this.files()).find(n=>n.endsWith(es(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?_h(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!hh.test(r))continue;let s=await _h(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as bh,readdir as sx,rm as ix,stat as wh}from"node:fs/promises";import{basename as ox,join as ts,resolve as ax}from"node:path";function sa(t){return ax(t||process.env.MINIPLAYER_HOME||ts(process.env.XDG_DATA_HOME||ts(ee,".local","share"),"miniplayer"))}function na(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Ru(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function vh(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Th(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Sh(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 kh(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))Q(c)!==null&&(n[l]=c);let r=Q(e.inputTokens),s=Q(e.cachedInputTokens),i=Q(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=Q(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&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:n,pricingFacts:Q(e.reasoningTokens)===null?null:{reasoning_output_tokens:Q(e.reasoningTokens)}}}function Ih(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),b=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 E=g.status==="complete"?"complete":g.status==="running"?"in_progress":g.status==="failed"?"failed":g.status==="aborted"?"aborted":"unknown";d=E==="failed"||E==="unknown"?"aborted":E,(E!=="complete"||g.partial===!0)&&(u=!0);let w=Array.isArray(g.modelResponses),S=w?g.modelResponses:[],T=[];l.push({id:g.responseId,startedAt:_,completedAt:b,model:y,prompt:g.input.text,status:E,responseIds:T}),a.push({role:"user",timestamp:_,content:g.input.text});let x=Array.isArray(g.toolEvents)&&g.toolEvents.length>0;if(!w&&!x){let R=g.usage??{},I=kh({...g,usage:R});Object.keys(I.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:g.responseId,values:I.rawUsage}]),T.push(g.responseId),c.push({response_id:g.responseId,timestamp:(b??_).toISOString(),model:y??null,model_provider:typeof g.provider=="string"?g.provider:null,tokens:I.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:I.pricingFacts}),E!=="complete"&&!g.usage&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??_,content:g.output.text,model:y});continue}let C=new Map,L=new Map,k=new Set,v=[];for(let R of S){if(!R||typeof R!="object"||typeof R.responseId!="string"||!R.responseId){u=!0;continue}if(T.includes(R.responseId)){u=!0;continue}let I=R,A=v.length;v.push({response:I,index:A,filesRead:[],filesWritten:[],io:[]}),T.push(R.responseId),h.has(R.responseId)&&(u=!0),h.add(R.responseId),I.toolCalls!==void 0&&!Array.isArray(I.toolCalls)&&(u=!0,v[A].io.push({direction:"read",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"}));for(let N of Array.isArray(I.toolCalls)?I.toolCalls:[]){let D=vh(N),j=Ru(N);if(D)C.set(D,A),L.set(D,j);else{u=!0;let K=j==="list_directory"||j==="read_file"||j==="webget"||j==="shell"||j==="tool",U=j==="write_file"||j==="shell"||j==="tool";K&&v[A].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),U&&v[A].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}T.length===0&&S.length>0&&(u=!0);for(let R of Array.isArray(g.toolEvents)?g.toolEvents:[]){let I=R&&typeof R=="object"?R:{},A=vh(I),N=A?C.get(A):void 0,D=Ru(I),j=Th(I.result),K=I.status==="failed"||I.error!==void 0;if(I.type==="tool_call"?a.push({role:"tool_use",timestamp:s(I?.timestamp)??_,content:na(I?.input??I?.args),toolName:D,toolInput:na(I?.input??I?.args),toolInputData:Th(I?.input??I?.args)??void 0,...A?{toolCallId:A}:{}}):a.push({role:"tool_result",timestamp:s(I?.timestamp)??b??_,content:na(K?I?.error:I?.result),toolName:D,...A?{toolCallId:A}:{}}),N===void 0){u=!0;continue}let U=v[N];(I.type==="tool_result"||K||I.result!==void 0)&&k.add(A);let re=j?.path,W=Q(j?.bytesRead??j?.bytesWritten);I.type!=="tool_call"&&(D==="read_file"&&!K&&typeof re=="string"&&W!==null?U.filesRead.push({path:re,bytes:W}):D==="write_file"&&!K&&typeof re=="string"&&W!==null?U.filesWritten.push({path:re,bytes:W}):D==="webget"&&!K&&W!==null?U.io.push({direction:"read",kind:"web",id:A,ref:Sh(j?.finalUrl??j?.url),bytes:W,basis:"certified_counter"}):D==="shell"||K?(D!=="write_file"&&U.io.push({direction:"read",kind:"unattributed",id:A,ref:null,bytes:null,basis:"unknown"}),(D==="shell"||D==="write_file")&&U.io.push({direction:"write",kind:"unattributed",id:A,ref:null,bytes:null,basis:"unknown"})):D==="list_directory"||D==="read_file"||D==="webget"?U.io.push({direction:"read",kind:D==="webget"?"web":"unattributed",id:A,ref:D==="webget"?Sh(j?.finalUrl??j?.url):null,bytes:null,basis:"unknown"}):D==="write_file"?U.io.push({direction:"write",kind:"unattributed",id:A,ref:null,bytes:null,basis:"unknown"}):U.io.push({direction:"read",kind:"unattributed",id:A,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:A,ref:null,bytes:null,basis:"unknown"}))}for(let[R,I]of L)if(!k.has(R)){let A=v[C.get(R)],N=I==="list_directory"||I==="read_file"||I==="webget"||I==="shell",D=I==="write_file"||I==="shell";N&&A.io.push({direction:"read",kind:"unattributed",id:R,ref:null,bytes:null,basis:"unknown"}),D&&A.io.push({direction:"write",kind:"unattributed",id:R,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let R of v){let I=R.response,A=kh(I),N=s(I.completedAt??I.startedAt)??b??_;new Set((Array.isArray(I.toolCalls)?I.toolCalls:[]).map(U=>Ru(U))).has("shell")&&!R.io.some(U=>U.kind==="unattributed"&&U.direction==="read")&&R.io.push({direction:"read",kind:"unattributed",id:I.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:I.responseId,ref:null,bytes:null,basis:"unknown"}),R.index===0&&R.io.unshift({direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"});let j=R.io.some(U=>U.direction==="read"&&U.bytes===null),K=R.io.some(U=>U.direction==="write"&&U.bytes===null);if(c.push({response_id:I.responseId,timestamp:N.toISOString(),model:typeof I.model=="string"?I.model:null,model_provider:typeof I.provider=="string"?I.provider:typeof g.provider=="string"?g.provider:null,tokens:A.tokens,files_read:j?null:R.filesRead,files_written:K?null:R.filesWritten,read_bytes:j?null:R.filesRead.reduce((U,re)=>U+(re.bytes??0),0)+R.io.filter(U=>U.direction==="read").reduce((U,re)=>U+(re.bytes??0),0),write_bytes:K?null:R.filesWritten.reduce((U,re)=>U+(re.bytes??0),0)+R.io.filter(U=>U.direction==="write").reduce((U,re)=>U+(re.bytes??0),0),external_io:R.io,pricing_facts:A.pricingFacts}),Object.keys(A.rawUsage).length){let U=l.at(-1);U.rawUsage=[...U.rawUsage??[],{responseId:I.responseId,values:A.rawUsage}]}}l.at(-1).responseIds=T,T.length!==S.length&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??_,content:g.output.text,model:y})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Zr(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 ia(t){return{provider:"miniplayer",root:ts(sa(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=ox(e,".json");return e.endsWith(".json")&&Rh.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:Ih(i,n,r)}catch{return null}}}}var Rh,ra,oa=O(()=>{"use strict";Zo();Le();dn();Rh=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;ra=class{name="miniplayer";home;constructor(e={}){this.home=sa(e.miniplayerHome)}getWatchPaths(){return[{directory:ts(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await sx(ts(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(!Rh.test(e))return null;let n=ts(this.home,"sessions",`${e}.json`);try{return(await wh(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=Ih(JSON.parse(await bh(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await bh(`${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 wh(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await ix(n),!0}}});import{createHash as lx}from"node:crypto";import{createRequire as cx}from"node:module";import{readdir as ux,realpath as dx}from"node:fs/promises";import{basename as xh,dirname as mx,join as Ah,resolve as Ch}from"node:path";function fx(){return px("node:sqlite").DatabaseSync}function gx(){return process.env.HOME||process.env.USERPROFILE||""}function yr(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 qt(t,e){return t.find(n=>n.field===e)}function hx(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=yr(n.bytes),s=qt(r,1)?.bytes,i=qt(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 _x(t){let e=qt(yr(t),5)?.bytes;if(e===void 0)return null;let n=qt(yr(e),1)?.bytes;if(n===void 0)return null;let r=yr(n),s=qt(r,1)?.varint;if(s===void 0)return null;let i=qt(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function yx(t){let e=qt(t,4)?.bytes,n=e!==void 0?yr(e):[],r=s=>{let i=qt(n,s)?.varint;return i===void 0?null:Q(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function Ex(t){let e=qt(yr(t),1)?.bytes;if(e===void 0)return null;let n=yr(e),r=hx(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=qt(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}=yx(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function Nh(t,e){se(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=Q(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=lx("sha256");i.update("rev:").update(aa).update(`
|
|
445
447
|
`);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(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.129",
|
|
4
4
|
"description": "A provider-agnostic control plane for teams of AI coding agents — across providers, with independent review and durable memory.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"homepage": "https://lmctl.com",
|