@linzumi/cli 1.0.196 → 1.0.197
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/dist/impl-res/index.js
CHANGED
|
@@ -286,7 +286,7 @@ Keep "src" required, all other fields optional, and never exceed 10 embeds in on
|
|
|
286
286
|
`;return"[mcp_servers."+e.name+`]
|
|
287
287
|
command = `+Fu(e.command)+`
|
|
288
288
|
args = `+uO(e.args)+`
|
|
289
|
-
`+t}var hO="Other",_O="linzumi_ask_user_question",gU="plan_mode_native_interview_tool",yU="no_active_turn";function Du(e){return JSON.stringify(e)}function bU(e){let t=e.trim().toLowerCase();switch(t){case"other":case"something else":case"something else...":return!0;default:return t.includes("other")?!0:t.includes("something else")}}function SU(e){let t=In(e),r=Gu(t!==void 0?t.questions:void 0);if(r===void 0)return{TAG:"Invalid",_0:"questions: expected an array"};let n=r.length;if(n===0)return{TAG:"Invalid",_0:"questions: min 1, got 0"};if(n>4)return{TAG:"Invalid",_0:"questions: max 4, got "+n.toString()};let i={contents:void 0},o=[],a=new Set;r.forEach((l,d)=>{if(i.contents!==void 0)return;let c=d.toString(),m=In(l);if(m===void 0){i.contents="questions["+c+"]: expected an object";return}let _=nn(m.question);if(_===void 0){i.contents="questions["+c+"].question: must be a non-empty string";return}if(a.has(_)){i.contents="questions: duplicate question text "+Du(_);return}let h=nn(m.header);if(h===void 0){i.contents="questions["+c+"].header: must be a non-empty string";return}if(h.length>12){i.contents="questions["+c+"].header: max 12 chars, got "+h.length.toString();return}let f=m.multiSelect;if(f!==void 0){let E=0;if(typeof f!="boolean"&&(E=2),E===2){i.contents="questions["+c+"].multiSelect: must be a boolean";return}}let p=Gu(m.options);if(p===void 0){i.contents="questions["+c+"].options: expected an array";return}let g=p.length;if(g<2){i.contents="questions["+c+"].options: min 2, got "+g.toString();return}if(g>4){i.contents="questions["+c+"].options: max 4, got "+g.toString();return}let b=[],y=new Set;if(p.forEach((E,G)=>{if(i.contents!==void 0)return;let Q=G.toString(),$=In(E),F=$!==void 0?nn($.label):void 0;if($!==void 0&&F!==void 0){let oe=$.description,W=0;if(oe!==void 0){let ae=0;if(typeof oe=="string"?W=2:ae=3,ae===3){i.contents="questions["+c+"].options["+Q+"].description: must be a string";return}}else W=2;if(W===2){if(bU(F)){i.contents="questions["+c+"].options["+Q+"].label: "+Du(F)+" is reserved for the built-in Other option";return}if(y.has(F)){i.contents="questions["+c+"].options: duplicate label "+Du(F);return}y.add(F);let ae=$.description,je;je=typeof ae=="string"?ae:"",b.push({label:F,description:je});return}}i.contents="questions["+c+"].options["+Q+"].label: must be a non-empty string"}),i.contents!==void 0)return;a.add(_);let w=m.multiSelect,C;C=w===!0,o.push({question:_,header:h,options:b,multiSelect:C})});let s=i.contents;return s!==void 0?{TAG:"Invalid",_0:s}:{TAG:"Parsed",_0:{questions:o}}}function vU(e){let t={};e.questions.forEach(s=>{let l={};l.type="string",l.description=s.header,t[s.question]=l});let r={};r.type="object",r.properties=t,r.required=e.questions.map(s=>s.question);let n=e.questions.map(s=>{let l={};return l.question=s.question,l.header=s.header,l.multiSelect=s.multiSelect,l.options=s.options.map(d=>{let u={};return u.label=d.label,u.description=d.description,u}),l}),i={};i.version=1,i.questions=n;let o={};o[_O]=i;let a={};return a.message="Linzumi interview: the user is being asked in the Linzumi thread.",a.requestedSchema=r,a._meta=o,a}function wU(e,t){let r=In(t);if(r===void 0)return{TAG:"AnswersInvalid",_0:"the runner accepted the interview but returned no answers; it may predate linzumi_ask_user_question support"};let n={contents:void 0},i={};e.questions.forEach(a=>{if(n.contents!==void 0)return;let l=r[a.question];if(typeof l=="string"){let d=0,u;try{u=JSON.parse(l),d=2}catch{n.contents="the runner returned an undecodable answer for question "+Du(a.question);return}if(d===2){i[a.question]=u;return}}n.contents="the runner returned no answer for question "+Du(a.question)});let o=n.contents;return o!==void 0?{TAG:"AnswersInvalid",_0:o}:{TAG:"Answers",_0:i}}function kU(e){let t=In(e);if(t===void 0)return;let r=In(t[_O]);return nn(r!==void 0?r.reason:void 0)}function ra(e){let t={};t.type="text",t.text=e;let r={};return r.content=[t],r.isError=!0,r}function TU(e){if(e===void 0)return"undefined";if(e===null)return"null";switch(typeof e){case"string":return e;case"number":return e.toString();default:return JSON.stringify(e)}}async function gO(e,t){let r=SU(t);if(r.TAG!=="Parsed")return ra(r._0);let n=r._0,i=0,o;try{o=await e(vU(n),2147483647),i=1}catch(a){let s=U(a);return ra("the interview could not be delivered to the user: "+$i(s))}if(i===1){let a=In(o),s=a!==void 0?a:{},l=s.action,d=0;if(typeof l=="string")switch(l){case"accept":let u=wU(n,s.content);if(u.TAG!=="Answers")return ra(u._0);let c={};return c.answers=u._0,Un(c);case"cancel":return ra("the user dismissed the question without answering");case"decline":let m=kU(s._meta);return ra(m!==void 0?m===gU?"linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead":m===yU?"the interview was declined: no active turn is bound to this session":"the interview request was declined by the runner":"the interview request was declined by the runner");default:d=2}else d=2;if(d===2)return ra("the interview returned an unknown action: "+TU(l))}}var yO="linzumi_ask_user_question",ny=4,iy=12,oy=2,ay=4;function AU(e){switch(e){case"All":return!0;case"Coding":case"OnboardingDiscovery":return!1}}function OU(e){return e==="Voice"}function CU(e){return e.trim().replace(new RegExp("^:+"),"").replace(new RegExp(":+$"),"").toLowerCase()}function bO(){return x.string().min(1).refine(e=>CU(e).length<=64,{message:"Custom emoji shortcode name must be at most 64 characters after trimming surrounding colons."})}function Mr(){return x.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")}function xi(){return x.string().optional().describe("Channel slug. Omit to use the authenticated token scope.")}function Ai(e){if(typeof e=="string")return e}function SO(e,t,r){let n=In(e[t]);return n!==void 0?n:Kr(r+" "+t+" must be an object")}function EU(e){return e!==void 0?Array.isArray(e)?Ye(e,t=>{if(typeof t=="string")return t}):[]:[]}function PU(e){return e!==void 0?Array.isArray(e)?Ye(e,t=>{if(typeof t=="number")return t}):[]:[]}function vO(e){if(typeof e=="number")return e}function wO(e){let t={};t.name=e.record.name,t.command=e.record.command,t.cwd=e.record.cwd,t.ports=e.record.ports.map(o=>o),t.restart_on_branch_change=e.record.restartOnBranchChange,t.desired_state=Zg(e.record.desiredState),t.liveness=XA(e.liveness),t.port_health=e.portProbes.map(o=>{let a={};return a.port=o.port,a.listening=o.listening,a});let r=e.record.startedAtMs;t.started_at_ms=r!==void 0?r:null;let n=e.lastExit,i;if(n!==void 0){let o={},a=n.code;o.code=a!==void 0?a:null;let s=n.signal;o.signal=s!==void 0?s:null,o.at_ms=n.atMs,i=o}else i=null;return t.last_exit=i,t.log_path=e.record.logPath,t}function RU(e,t,r){e.registerTool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",Object.fromEntries([["name",x.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service.")],["command",x.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell.")],["cwd",x.string().optional().describe("Working directory for the service. Defaults to the session cwd.")],["ports",x.array(x.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility.")],["restart_on_branch_change",x.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts).")],["wait_for_ports_ms",x.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=Ai(n.command),s=a!==void 0?a:"",l=Ai(n.cwd),d=await iO({scopeDir:r.scopeDir,definition:{name:o,command:s,cwd:l!==void 0?l:t,ports:PU(n.ports),restartOnBranchChange:me(n.restart_on_branch_change,!0)},ownerPid:r.ownerPid});if(d.TAG==="Ok"){let c=d._0,m=vO(n.wait_for_ports_ms),_=Date.now()+(m!==void 0?m:15e3),h=c.ports.length===0;for(;!h&&Date.now()<_;)h=(await Promise.all(c.ports.map(S=>Yg(S|0)))).every(S=>S),h||await Uf(250);let p=(await Xg(r.scopeDir)).find(y=>y.record.name===c.name),g={};g.ok=!0;let b;if(p!==void 0)b=wO(p);else{let y={};y.name=c.name,b=y}return g.service=b,p!==void 0&&p.liveness!=="Running"&&(g.hint="The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."),Un(g)}let u={};return u.ok=!1,u.error=d._0,Un(u)}),e.registerTool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",Object.fromEntries([["name",x.string().min(1).describe("Service name to stop.")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=await ey(r.scopeDir,o,void 0),s={};return a.TAG==="Ok"?(s.ok=!0,s.name=a._0.name,s.desired_state="stopped"):(s.ok=!1,s.error=a._0),Un(s)}),e.registerTool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / stopped), per-port health probes, and last exit. Live state - always check this before concluding a dev server is up or down.",{},async n=>{let i=await Xg(r.scopeDir),o={};return o.services=i.map(a=>wO(a)),Un(o)}),e.registerTool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",Object.fromEntries([["name",x.string().min(1).describe("Service name.")],["max_bytes",x.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=vO(n.max_bytes),s=aO(r.scopeDir,o,a!==void 0?a:16384),l={};return s!==void 0?(l.ok=!0,l.name=o,l.log_tail=s):(l.ok=!1,l.error="no log for service: "+o),Un(l)}),e.registerTool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",Object.fromEntries([["name",x.string().min(1).describe("Service name to remove.")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=await oO(r.scopeDir,o),s={};return a.TAG==="Ok"?(s.ok=!0,s.name=a._0.name,s.removed=!0):(s.ok=!1,s.error=a._0),Un(s)})}function kO(e,t){let r=t.devServices,n=t.agentSession,i=t.ownerUsername,o=t.defaultThreadId,a=t.serviceUrl,s=t.cwd,l=t.toolScope,d=t.client,u;switch(l){case"All":case"Coding":u=!0;break;case"OnboardingDiscovery":u=!1;break}let c=async f=>Un(await f),m=async(f,p)=>(p.tool=f,await c(d.agentDocumentTool(p))),_=t.documentSurfaces;_!==void 0&&_&&(e.registerTool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",Object.fromEntries([["query",x.string().min(1).describe("Document title or content search query.")]]),async f=>await m("lookup_documents",f)),e.registerTool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",Object.fromEntries([["document_id",x.string().uuid().describe("Document UUID.")]]),async f=>await m("read_document",f)),e.registerTool("linzumi_propose_document_patch","Create an agent-attributed structural patch proposal. This never directly mutates document content; per-document auto-apply is resolved server-side after proposal persistence.",Object.fromEntries([["document_id",x.string().uuid().describe("Document UUID.")],["patch",x.record(x.unknown()).describe("Revisioned structural document patch.")],["rationale",x.string().min(1).describe("Why this change is proposed.")]]),async f=>await m("propose_document_patch",f)),e.registerTool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",Object.fromEntries([["title",x.string().min(1).describe("Document title.")],["initial_patch",x.record(x.unknown()).describe("Bootstrap structural patch.")],["folder_id",x.string().uuid().optional().describe("Destination folder UUID.")]]),async f=>await m("create_document",f)));let h=t.askUserQuestion;switch(h!==void 0&&e.registerTool(yO,"Ask the user up to "+ny.toString()+" structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max "+iy.toString()+" chars) and "+oy.toString()+"-"+ay.toString()+' options {label, description}; a built-in "'+hO+'" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.',Object.fromEntries([["questions",x.array(x.object(Object.fromEntries([["question",x.string().describe("The question to ask the user.")],["header",x.string().describe("Short category header shown above the question (max "+iy.toString()+' chars, e.g. "Auth", "Scope").')],["options",x.array(x.object(Object.fromEntries([["label",x.string().describe("Option label the user taps.")],["description",x.string().optional().describe("One-line explanation of the option.")]]))).describe(oy.toString()+"-"+ay.toString()+" options for this question.")],["multiSelect",x.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")]]))).describe("1-"+ny.toString()+" questions to ask atomically.")]]),async f=>await gO(h,f)),n&&(e.registerTool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",Object.fromEntries([["body",x.string().min(1).describe("Plain-text reply body to post.")]]),async f=>{let p={},g=f.body;return p.body=g!==void 0?g:void 0,await c(d.agentReply(p))}),e.registerTool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async f=>await c(d.agentListCodingJobs({}))),e.registerTool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["channel",x.string().describe("Channel slug to host the job thread.")],["runner_key",x.string().describe("Runner (computer) to run the job on.")],["cwd",x.string().describe("Working directory on the runner.")],["work_description",x.string().min(1).describe("What the job should do - the initial instruction.")],["model",x.string().optional().describe("Model override (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["execution_mode",x.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["project_task_id",x.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")]]),async f=>await c(d.agentStartCodingJob(f))),e.registerTool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["mode",x.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")]]),async f=>await c(d.agentInterruptCodingJob(f))),e.registerTool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",x.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set.")],["thread_id",x.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set.")],["to_user",x.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",x.string().min(1).describe("Message body to send.")],["delivery",x.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async f=>await c(d.agentSendCodingJobMessage(f))),e.registerTool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["limit",x.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",x.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await c(d.agentReadCodingJobThread(f))),e.registerTool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["source_seq",x.number().int().positive().describe("Channel seq of the message the approval request rides on.")],["request_id",x.string().describe("The approval request id.")],["decision",x.enum(["approve","deny"]).describe("The asker's decision.")]]),async f=>await c(d.agentResolveJobApproval(f))),e.registerTool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID to archive.")]]),async f=>await c(d.agentArchiveCodingJob(f))),e.registerTool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID to unarchive.")]]),async f=>await c(d.agentUnarchiveCodingJob(f))),e.registerTool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID.")],["status",x.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")]]),async f=>await c(d.agentSetThreadStatus(f))),e.registerTool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",Object.fromEntries([["name",x.string().min(1).describe("Channel name to create.")]]),async f=>await c(d.agentCreateChannel(f))),e.registerTool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",Object.fromEntries([["channel",x.string().describe("Current channel slug to rename.")],["name",x.string().min(1).describe("New display name.")]]),async f=>await c(d.agentRenameChannel(f))),e.registerTool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",Object.fromEntries([["channel",x.string().describe("Channel slug to archive.")]]),async f=>await c(d.agentArchiveChannel(f))),e.registerTool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",Object.fromEntries([["channel",x.string().describe("Channel slug to unarchive.")]]),async f=>await c(d.agentUnarchiveChannel(f))),e.registerTool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the message to react to.")],["emoji",x.string().min(1).describe("Emoji to add (unicode or :shortcode:).")]]),async f=>await c(d.agentAddReaction(f))),e.registerTool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the reacted message.")],["emoji",x.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")]]),async f=>await c(d.agentRemoveReaction(f))),e.registerTool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the message to pin.")]]),async f=>await c(d.agentPinMessage(f))),e.registerTool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the pinned message.")]]),async f=>await c(d.agentUnpinMessage(f)))),l){case"All":e.registerTool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["message_id",x.union([x.string(),x.number()]).optional().describe("Message seq inside the scoped channel.")],["message_seq",x.union([x.string(),x.number()]).optional().describe("Alias for message_id.")],["message_url",x.string().optional().describe("Full Linzumi message URL with #message-<seq>.")],["before",x.number().int().min(0).max(100).optional().describe("Number of visible messages before the target.")],["after",x.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")]]),async f=>await c(d.getMessage(f))),e.registerTool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Linzumi thread UUID.")],["limit",x.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",x.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await c(d.getThread(f))),e.registerTool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Linzumi thread UUID.")],["limit",x.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200).")],["cursor",x.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")]]),async f=>await c(d.getThreadTranscript(f))),e.registerTool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["limit",x.number().int().min(1).max(100).optional().describe("Maximum messages to return.")],["before_seq",x.number().int().positive().optional().describe("Return messages before this channel seq.")]]),async f=>await c(d.getChannel(f))),e.registerTool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",Object.fromEntries([["workspace",Mr()],["query",x.string().min(1).describe("Natural-language or keyword query to retrieve against.")],["limit",x.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped).")],["source_types",x.array(x.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all.")],["authored_after",x.string().optional().describe("ISO8601 instant; only content authored at or after this time.")],["authored_before",x.string().optional().describe("ISO8601 instant; only content authored at or before this time.")],["repo",x.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name).")],["check_status",x.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")]]),async f=>await c(d.searchWorkspace(f))),e.registerTool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',Object.fromEntries([["workspace",Mr()],["question",x.string().min(1).max(2e3).describe("Natural-language question to answer with citations.")],["channel",x.string().optional().describe("Optional channel slug providing conversational context; never widens access.")],["allow_cached",x.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")]]),async f=>await c(d.askWorkspace(f))),e.registerTool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>await c(d.aboutMe(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(u&&(e.registerTool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",Object.fromEntries([["query",x.string().min(1).describe("Web search query (natural language or keywords).")],["limit",x.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")]]),async f=>await c(d.webSearch(f))),e.registerTool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",Object.fromEntries([["url",x.string().min(1).describe("Absolute public http(s) URL to fetch.")]]),async f=>await c(d.fetchUrl(f)))),l){case"All":e.registerTool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async f=>await Dg(d.listUiTargets({}))),e.registerTool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",Object.fromEntries([["kind",x.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout).")],["args",x.record(x.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path).")],["workspace",Mr()]]),async f=>await Dg(d.openUi(Fi(f,o))));break;case"Coding":case"OnboardingDiscovery":break}if(u){let f=()=>x.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.");e.registerTool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()]]),async p=>await c(d.getCodingJobMetadata(Fi(p,o)))),e.registerTool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["title",x.string().min(1).max(100).describe("Concise user-visible title for this coding job.")]]),async p=>await c(d.renameCodingJob(Fi(p,o)))),e.registerTool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["goal",x.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")]]),async p=>await c(d.upsertCodingJobPlan(Fi(p,o)))),e.registerTool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["goal",x.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal.")],["steps",x.array(x.object(Object.fromEntries([["title",x.string().min(1).max(255)],["description",x.string().min(1).max(1e4)],["status",x.enum(["pending","active","completed","blocked","canceled"])],["status_note",x.string().min(1).max(4e3).optional()],["completed_debrief",x.string().min(1).max(2e4).optional()]]))).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")]]),async p=>await c(d.replaceCodingJobPlanSteps(Fi(p,o)))),e.registerTool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["step_id",x.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata.")],["lock_version",x.number().int().positive().describe("Current step lock_version from metadata.")],["status",x.enum(["pending","active","completed","blocked","canceled"])],["status_note",x.string().min(1).max(4e3).optional()],["completed_debrief",x.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")]]),async p=>await c(d.updateCodingJobPlanStep(Fi(p,o)))),e.registerTool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["github_repo_owner",x.string().min(1).max(255)],["github_repo_name",x.string().min(1).max(255)],["github_pr_number",x.number().int().positive()],["github_pr_url",x.string().url()],["title",x.string().min(1).max(255)],["body",x.string().min(1).max(1e5).optional()],["head_branch",x.string().min(1).max(255)],["head_sha",x.string().min(7).max(64)],["base_branch",x.string().min(1).max(255)],["base_sha",x.string().min(7).max(64)],["state",x.enum(["draft","open","closed","merged"]).optional()],["is_draft",x.boolean().optional()],["review_status",x.enum(["unknown","review_required","approved","changes_requested"]).optional()],["source_remote_url",x.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet.")],["runtime_worktree_root",x.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet.")],["dirty_status",x.enum(["unknown","clean","dirty"]).optional()],["dirty_summary",x.string().min(1).max(2e3).optional()]]),async p=>await c(d.linkCodingJobPullRequest(Fi(p,o)))),e.registerTool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),Object.fromEntries([["target",x.object(Object.fromEntries([["kind",x.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel.")],["message_seq",x.union([x.string(),x.number()]).optional().describe("Required when kind is message_seq.")],["thread_id",x.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")]])).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit.")],["files",x.array(x.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types.")],["body",x.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool.")],["workspace",Mr()],["channel",x.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")]]),async p=>{let g=Lg(SO(p,"target","linzumi_upload_files"),o),b;try{b=await ZA({client:d,cwd:s,serviceUrl:a,target:g,files:EU(p.files),workspace:Ai(p.workspace),channel:Ai(p.channel),body:Ai(p.body)})}catch(y){return WA(U(y))}return Un(Ug(a,b))}),e.registerTool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["target",x.object(Object.fromEntries([["message_seq",x.union([x.string(),x.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here.")],["thread_id",x.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")]])).describe("Exact message target for the body edit.")],["body",x.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")]]),async p=>{let g=ta(p);return g.target=Lg(SO(p,"target","linzumi_edit_message"),o),Un(Ug(a,await d.editMessage(g)))})}switch(l){case"All":if(e.registerTool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>await c(d.listVaultSecrets(f))),e.registerTool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",Object.fromEntries([["workspace",Mr()]]),async f=>await c(d.listProjects(f))),e.registerTool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,Object.fromEntries([["project_id",x.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")]]),async f=>await c(d.getProjectTasks(Fi(f,o)))),e.registerTool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',Object.fromEntries([["project_id",x.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")],["title",x.string().min(1).describe("Task title.")],["kind",x.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).')],["description",x.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it.")],["status",x.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".')],["parent_id",x.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent.")],["assignee",x.string().optional().describe("Username of a workspace member to assign.")],["position",x.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")]]),async f=>await c(d.createProjectTask(Fi(f,o)))),e.registerTool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',Object.fromEntries([["task_id",x.string().describe("task_id of the group or issue to update.")],["title",x.string().min(1).optional().describe("New title.")],["description",x.string().nullable().optional().describe("New description. Pass null to clear it.")],["status",x.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.')],["status_note",x.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it.")],["position",x.number().int().min(0).optional().describe("New sort position among siblings.")],["parent_id",x.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent.")],["clear_parent",x.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id.")],["assignee",x.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee.")],["clear_assignee",x.boolean().optional().describe("true removes the assignee. Do not combine with assignee.")],["lock_version",x.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")]]),async f=>await c(d.updateProjectTask(f))),e.registerTool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,Object.fromEntries([["task_id",x.string().describe("task_id of the group or issue to delete.")]]),async f=>await c(d.deleteProjectTask(f))),e.registerTool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',Object.fromEntries([["task_id",x.string().describe("task_id of the DEPENDENT issue (the one that must wait).")],["depends_on_task_id",x.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")]]),async f=>await c(d.addProjectTaskDependency(f))),e.registerTool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',Object.fromEntries([["task_id",x.string().describe("task_id of the DEPENDENT issue.")],["depends_on_task_id",x.string().describe("task_id of the PREREQUISITE issue the edge points at.")]]),async f=>await c(d.removeProjectTaskDependency(f))),e.registerTool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",Object.fromEntries([["call_id",x.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")]]),async f=>await c(d.getCallTranscript(f))),!n){e.registerTool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job - only start tasks whose work_state is ready, and ONLY after the user explicitly accepts your offer to start them. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",x.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description.")],["project_task_id",x.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")],["channel",x.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel.")],["runner_key",x.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer.")],["cwd",x.string().optional().describe("Working directory on the runner. Omit to use this job's own folder.")],["model",x.string().optional().describe("Model override (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["agent_provider",x.string().optional().describe("Agent provider override, e.g. 'codex' (optional).")],["reasoning_effort",x.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["approval_policy",x.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional).")],["sandbox",x.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional).")],["fast",x.boolean().optional().describe("Fast-mode override (optional).")],["allow_port_forwarding_by_default",x.boolean().optional().describe("Default port-forwarding override (optional).")],["execution_mode",x.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["egress_mode",x.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")]]),async p=>await c(d.agentStartCodingJob(Fi(p,o))));let f=t.multiAgentJobs;f!==void 0&&f&&(e.registerTool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",x.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone.")],["agent_provider",x.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job.")],["model",x.string().optional().describe("Model override for the child (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["reasoning_effort",x.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["project_task_id",x.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")]]),async p=>await c(d.agentSpawnChildJob(Fi(p,o)))),e.registerTool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",Object.fromEntries([["query",x.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")]]),async p=>{let g={};return Object.entries(p).forEach(b=>{g[b[0]]=b[1]}),g.source_thread_id=qg(z(o,b=>b)),await c(d.agentDiscoverCodingJobs(g))}),e.registerTool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",x.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set.")],["thread_id",x.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set.")],["to_user",x.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",x.string().min(1).describe("Coordination message to send.")],["delivery",x.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async p=>{let g={};return Object.entries(p).forEach(b=>{g[b[0]]=b[1]}),g.source_thread_id=qg(z(o,b=>b)),await c(d.agentSendCodingJobMessage(g))}))}break;case"Coding":case"OnboardingDiscovery":break}switch(AU(l)&&(e.registerTool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",Object.fromEntries([["name",bO().describe("Custom emoji shortcode name, with or without surrounding colons.")],["file",x.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji.")],["workspace",Mr()]]),async f=>{let p=Ai(f.name),g=Ai(f.file);return Un(await BA({client:d,cwd:s,serviceUrl:a,name:p!==void 0?p:"",file:g!==void 0?g:"",workspace:Ai(f.workspace)}))}),e.registerTool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",Object.fromEntries([["emoji_id",x.union([x.string(),x.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings.")],["name",bO().describe("New shortcode name, with or without surrounding colons.")],["workspace",Mr()]]),async f=>await c(d.renameCustomEmoji(f)))),e.registerTool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async f=>{let p={};p.type="text",p.text=dO;let g={};return g.content=[p],g}),e.registerTool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["path",x.string().min(1).describe("Absolute local path to the repository worktree root.")],["display_name",x.string().optional().describe("Short project label. Defaults to the path basename.")],["activity_at",x.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["import_key",x.string().optional().describe("Stable dedupe key. Defaults to path.")],["metadata",x.record(x.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")]]),async f=>await c(d.noteProjectDirectory(f))),e.registerTool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["source",x.enum(["codex","claude_code"]).describe("Conversation source.")],["import_key",x.string().min(1).describe("Stable dedupe key, such as a session id or file path.")],["path",x.string().optional().describe("Absolute local path to the conversation file or directory.")],["display_name",x.string().optional().describe("Short label for the discovered conversation.")],["activity_at",x.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["metadata",x.record(x.unknown()).optional().describe("Small structured metadata such as session id or project path.")]]),async f=>await c(d.noteAgentConversation(f))),e.registerTool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["phase",x.enum(["projects","conversations"]).describe("Discovery phase being reported.")],["status",x.enum(["starting","running","completed","failed"]).describe("Current phase status.")],["places_searched",x.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far.")],["message",x.string().optional().describe("Short user-facing status note.")],["current_place",x.string().optional().describe("Current folder, file, Git command target, or known location being checked.")],["current_source",x.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code.")],["last_error",x.string().optional().describe("Short failure detail when status is failed.")],["metadata",x.record(x.unknown()).optional().describe("Small structured status metadata.")]]),async f=>await c(d.noteOnboardingDiscoveryStatus(f))),l==="All"&&OU(t.operatingMode)&&(e.registerTool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",Object.fromEntries([["owner_username",x.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username.")],["workspace",Mr()],["channel",x.string().optional().describe("Source channel slug used to verify owner visibility.")],["body",x.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>{let p=Ai(f.owner_username),g=p!==void 0?p:i;if(g===void 0)return Kr("owner_username is required for linzumi_dm_owner");let b=ta(f);return b.owner_username=g,await c(d.dmOwner(b))}),e.registerTool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["body",x.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await c(d.sendChannelMessage(f))),e.registerTool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Existing Linzumi thread UUID.")],["body",x.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await c(d.sendThreadReply(f))),e.registerTool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",Object.fromEntries([["workspace",Mr()],["channel",x.string().optional().describe("Source channel slug used to verify target visibility.")],["username",x.string().describe("Visible Linzumi username to DM.")],["body",x.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>await c(d.sendDm(f)))),l){case"All":e.registerTool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",Object.fromEntries([["workspace",Mr()],["channel",x.string().optional().describe("Channel slug used to disambiguate the approval thread when needed.")],["thread_id",x.string().uuid().describe("Existing Linzumi thread UUID for the inline approval.")],["env_var_names",x.array(x.string().regex(new RegExp("^[A-Z][A-Z0-9_]{0,127}$"))).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys.")],["description",x.string().min(1).max(500).describe("Human-readable reason shown in the approval request.")],["justification",x.string().min(10).max(1e3).describe("Agent justification shown to the approver.")]]),async f=>await c(d.getVaultValues(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(l){case"All":return n||r===void 0?void 0:RU(e,s,r);case"Coding":case"OnboardingDiscovery":return}}function TO(e){if(typeof e=="number"&&e%1===0)return e}function MU(e){if(typeof e=="string")return e}function $U(e){let t=e.replaceAll("-","+").replaceAll("_","/");switch(t.length&3){case 2:return t+"==";case 3:return t+"=";default:return t}}function ly(e){let t=e.split(".")[1];if(t===void 0)return;let r=Buffer.from($U(t),"base64").toString("utf8"),n;try{n=JSON.parse(r)}catch{n=void 0}if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}function Lu(e){let t=ly(e);if(t===void 0)return{actorUserId:void 0,actorUsername:void 0};let r=TO(t.actor_id);return{actorUserId:r!==void 0?r:TO(t.sub),actorUsername:MU(t.actor_username)}}function xO(e){let t=k(ly(e),n=>n.workspace_scope),r=t!==void 0?Array.isArray(t)?Ye(t,n=>{if(typeof n=="string"&&n.trim()!=="")return n}):[]:[];if(r.length===1)return r[0]}var sy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AO(e){let t=ly(e);if(t===void 0)return!1;let n=t.document_surfaces===!0,i=t.linzumi_agent_session,o=typeof i=="string"?sy.test(i):!1,a=t.coding_job_id,s=t.coding_job_thread_id,l=typeof a=="string"&&typeof s=="string"?sy.test(a)&&sy.test(s):!1;return n?o?!0:l:!1}function jU(e){return typeof e==="undefined"?!0:e===null}function dy(e){let t=Yn(e.serviceUrl);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=e.fetchImpl,i=n!==void 0?n:Lf,o=e.authMode,a=o!==void 0&&o!=="LocalRunner"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",s=e.operatingMode,l=s!==void 0?ry(s):"text",d=async(u,c,m)=>{let _=Lo(c,r),h;h=_.TAG==="Ok"?_._0:Kr(_._0);let f={};Object.entries(m).forEach(E=>{f[E[0]]=E[1]}),f.operating_mode=l;let p={};p.authorization="Bearer "+e.accessToken;let g;if(u==="Get"){let E=h.searchParams;Object.entries(f).forEach(G=>{let j=G[1];if(!jU(j)){E.set(G[0],String(j));return}}),g=await i.json(h.toString(),{method:"GET",headers:p})}else p["content-type"]="application/json",g=await i.json(h.toString(),{method:"POST",headers:p,body:JSON.stringify(f)});let b=await g.json(),y;if(y=typeof b=="object"&&b!==null&&!Array.isArray(b)?b:void 0,y===void 0)return Kr("Linzumi MCP API returned non-object JSON from "+c);let S=g.ok,w=me(y.ok,!0),C=0;if(S){if(w)return y;C=1}else C=1;if(C===1){let E=y.error,G,j=0;typeof E=="string"?G=E:j=2,j===2&&(G="HTTP "+g.status.toString());let Q=y.detail,$=typeof Q=="string"?" detail="+Q:"";return Kr("Linzumi MCP API "+c+" failed: "+G+$)}};return{TAG:"Ok",_0:{validateAuth:()=>d("Get",a+"/validate",{}),issueOnboardingDiscoveryToken:u=>d("Post",a+"/onboarding-discovery-token",u),getMessage:u=>d("Get",a+"/message",u),getThread:u=>d("Get",a+"/thread",u),getThreadTranscript:u=>d("Get",a+"/thread-transcript",u),getChannel:u=>d("Get",a+"/channel",u),searchWorkspace:u=>d("Get",a+"/search",u),askWorkspace:u=>d("Post",a+"/ask",u),aboutMe:u=>d("Get",a+"/about-me",u),webSearch:u=>d("Get",a+"/web-search",u),fetchUrl:u=>d("Get",a+"/fetch-url",u),listUiTargets:u=>d("Get",a+"/ui-targets",u),openUi:u=>d("Post",a+"/open-ui",u),getCodingJobMetadata:u=>d("Get",a+"/coding-job-metadata",u),listProjects:u=>d("Get",a+"/projects",u),getProjectTasks:u=>d("Get",a+"/project-tasks",u),createProjectTask:u=>d("Post",a+"/project-tasks/create",u),updateProjectTask:u=>d("Post",a+"/project-tasks/update",u),deleteProjectTask:u=>d("Post",a+"/project-tasks/delete",u),addProjectTaskDependency:u=>d("Post",a+"/project-tasks/add-dependency",u),removeProjectTaskDependency:u=>d("Post",a+"/project-tasks/remove-dependency",u),getCallTranscript:u=>d("Get",a+"/call-transcript",u),renameCodingJob:u=>d("Post",a+"/coding-job-title",u),upsertCodingJobPlan:u=>d("Post",a+"/coding-job-plan",u),replaceCodingJobPlanSteps:u=>d("Post",a+"/coding-job-plan/steps",u),updateCodingJobPlanStep:u=>d("Post",a+"/coding-job-plan/step",u),linkCodingJobPullRequest:u=>d("Post",a+"/coding-job-primary-pr",u),listVaultSecrets:u=>d("Get",a+"/vault-secrets",u),noteProjectDirectory:u=>d("Post",a+"/discovered-project",u),noteAgentConversation:u=>d("Post",a+"/discovered-conversation",u),noteOnboardingDiscoveryStatus:u=>d("Post",a+"/discovery-status",u),sendChannelMessage:u=>d("Post",a+"/channel-message",u),editMessage:u=>d("Post",a+"/message/edit",u),agentReply:u=>d("Post",a+"/agent-reply",u),agentTurnProgress:u=>d("Post",a+"/agent-turn-progress",u),agentDocumentTool:u=>d("Post",a+"/agent/document-tool",u),agentListCodingJobs:u=>d("Get",a+"/agent/coding-jobs",u),agentStartCodingJob:u=>d("Post",a+"/agent/start-coding-job",u),agentSpawnChildJob:u=>d("Post",a+"/agent/spawn-child-job",u),agentInterruptCodingJob:u=>d("Post",a+"/agent/interrupt-coding-job",u),agentSendCodingJobMessage:u=>d("Post",a+"/agent/send-coding-job-message",u),agentDiscoverCodingJobs:u=>d("Get",a+"/agent/discover-coding-jobs",u),agentReadCodingJobThread:u=>d("Get",a+"/agent/coding-job-thread",u),agentResolveJobApproval:u=>d("Post",a+"/agent/resolve-job-approval",u),agentArchiveCodingJob:u=>d("Post",a+"/agent/archive-coding-job",u),agentUnarchiveCodingJob:u=>d("Post",a+"/agent/unarchive-coding-job",u),agentSetThreadStatus:u=>d("Post",a+"/agent/set-thread-status",u),agentCreateChannel:u=>d("Post",a+"/agent/create-channel",u),agentRenameChannel:u=>d("Post",a+"/agent/rename-channel",u),agentArchiveChannel:u=>d("Post",a+"/agent/archive-channel",u),agentUnarchiveChannel:u=>d("Post",a+"/agent/unarchive-channel",u),agentAddReaction:u=>d("Post",a+"/agent/add-reaction",u),agentRemoveReaction:u=>d("Post",a+"/agent/remove-reaction",u),agentPinMessage:u=>d("Post",a+"/agent/pin-message",u),agentUnpinMessage:u=>d("Post",a+"/agent/unpin-message",u),prepareMessageUploads:u=>d("Post",a+"/message-uploads/prepare",u),attachMessageFiles:u=>d("Post",a+"/message-files/attach",u),prepareCustomEmoji:u=>d("Post",a+"/custom-emoji/prepare",u),renameCustomEmoji:u=>d("Post",a+"/custom-emoji/rename",u),sendThreadReply:u=>d("Post",a+"/thread-reply",u),sendDm:u=>d("Post",a+"/dm",u),dmOwner:u=>d("Post",a+"/dm-owner",u),getVaultValues:u=>d("Post",a+"/vault-values",u)}}}var zU=Object.freeze({status:"aborted"});function V(e,t,r){function n(s,l){var d;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(d=s._zod).traits??(d.traits=new Set),s._zod.traits.add(e),t(s,l);for(let u in a.prototype)u in s||Object.defineProperty(s,u,{value:a.prototype[u].bind(s)});s._zod.constr=a,s._zod.def=l}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function a(s){var l;let d=r?.Parent?new o:this;n(d,s),(l=d._zod).deferred??(l.deferred=[]);for(let u of d._zod.deferred)u();return d}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var na=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Cm={};function Oi(e){return e&&Object.assign(Cm,e),Cm}var Ut={};q_(Ut,{BIGINT_FORMAT_RANGES:()=>CO,Class:()=>cy,NUMBER_FORMAT_RANGES:()=>yy,aborted:()=>Ds,allowsEval:()=>hy,assert:()=>LU,assertEqual:()=>NU,assertIs:()=>qU,assertNever:()=>DU,assertNotEqual:()=>FU,assignProp:()=>py,cached:()=>Vu,captureStackTrace:()=>Pm,cleanEnum:()=>t2,cleanRegex:()=>Zu,clone:()=>Ci,createTransparentProxy:()=>BU,defineLazy:()=>$r,esc:()=>qs,escapeRegex:()=>Ia,extend:()=>QU,finalizeIssue:()=>io,floatSafeRemainder:()=>my,getElementAtPath:()=>UU,getEnumValues:()=>Wu,getLengthableOrigin:()=>Bu,getParsedType:()=>ZU,getSizableOrigin:()=>EO,isObject:()=>od,isPlainObject:()=>ad,issue:()=>by,joinValues:()=>Em,jsonStringifyReplacer:()=>fy,merge:()=>YU,normalizeParams:()=>ft,nullish:()=>Hu,numKeys:()=>HU,omit:()=>KU,optionalKeys:()=>gy,partial:()=>XU,pick:()=>JU,prefixIssues:()=>Oo,primitiveTypes:()=>OO,promiseAllObject:()=>WU,propertyKeyTypes:()=>_y,randomString:()=>VU,required:()=>e2,stringifyPrimitive:()=>Rm,unwrapMessage:()=>Uu});function NU(e){return e}function FU(e){return e}function qU(e){}function DU(e){throw new Error}function LU(e){}function Wu(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Em(e,t="|"){return e.map(r=>Rm(r)).join(t)}function fy(e,t){return typeof t=="bigint"?t.toString():t}function Vu(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Hu(e){return e==null}function Zu(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function my(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}function $r(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function py(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UU(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function WU(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=n[o];return i})}function VU(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function qs(e){return JSON.stringify(e)}var Pm=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function od(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var hy=Vu(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function ad(e){if(od(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(od(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function HU(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ZU=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},_y=new Set(["string","number","symbol"]),OO=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ia(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ci(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ft(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function BU(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,o){return t??(t=e()),Reflect.set(t,n,i,o)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function Rm(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function gy(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var yy={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},CO={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function JU(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Ci(e,{...e._zod.def,shape:r,checks:[]})}function KU(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Ci(e,{...e._zod.def,shape:r,checks:[]})}function QU(e,t){if(!ad(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return py(this,"shape",n),n},checks:[]};return Ci(e,r)}function YU(e,t){return Ci(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return py(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function XU(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=e?new e({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)i[o]=e?new e({type:"optional",innerType:n[o]}):n[o];return Ci(t,{...t._zod.def,shape:i,checks:[]})}function e2(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=new e({type:"nonoptional",innerType:n[o]}))}else for(let o in n)i[o]=new e({type:"nonoptional",innerType:n[o]});return Ci(t,{...t._zod.def,shape:i,checks:[]})}function Ds(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Oo(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Uu(e){return typeof e=="string"?e:e?.message}function io(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=Uu(e.inst?._zod.def?.error?.(e))??Uu(t?.error?.(e))??Uu(r.customError?.(e))??Uu(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function EO(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Bu(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function by(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function t2(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var cy=class{constructor(...t){}};var PO=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,fy,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Im=V("$ZodError",PO),Ju=V("$ZodError",PO,{Parent:Error});function Sy(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function vy(e,t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>i({issues:s}));else if(a.code==="invalid_key")i({issues:a.issues});else if(a.code==="invalid_element")i({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let s=n,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(s[d]=s[d]||{_errors:[]},s[d]._errors.push(r(a))):s[d]=s[d]||{_errors:[]},s=s[d],l++}}};return i(e),n}var wy=e=>(t,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new na;if(a.issues.length){let s=new(i?.Err??e)(a.issues.map(l=>io(l,o,Oi())));throw Pm(s,i?.callee),s}return a.value},ky=wy(Ju),Ty=e=>async(t,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(i?.Err??e)(a.issues.map(l=>io(l,o,Oi())));throw Pm(s,i?.callee),s}return a.value},xy=Ty(Ju),Ay=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new na;return o.issues.length?{success:!1,error:new(e??Im)(o.issues.map(a=>io(a,i,Oi())))}:{success:!0,data:o.value}},Ls=Ay(Ju),Oy=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>io(a,i,Oi())))}:{success:!0,data:o.value}},Us=Oy(Ju);var RO=/^[cC][^\s-]{8,}$/,IO=/^[0-9a-z]+$/,MO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$O=/^[0-9a-vA-V]{20}$/,jO=/^[A-Za-z0-9]{27}$/,GO=/^[a-zA-Z0-9_-]{21}$/,zO=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var NO=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cy=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var FO=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var n2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function qO(){return new RegExp(n2,"u")}var DO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,LO=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,UO=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,WO=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,VO=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ey=/^[A-Za-z0-9_-]*$/,HO=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var ZO=/^\+(?:[0-9]){6,14}[0-9]$/,BO="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",JO=new RegExp(`^${BO}$`);function KO(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function QO(e){return new RegExp(`^${KO(e)}$`)}function YO(e){let t=KO({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${BO}T(?:${n})$`)}var XO=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var eC=/^\d+$/,tC=/^-?\d+(?:\.\d+)?/i,rC=/true|false/i,nC=/null/i;var iC=/^[^A-Z]*$/,oC=/^[^a-z]*$/;var Mn=V("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),aC={number:"number",bigint:"bigint",object:"date"},Py=V("$ZodCheckLessThan",(e,t)=>{Mn.init(e,t);let r=aC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ry=V("$ZodCheckGreaterThan",(e,t)=>{Mn.init(e,t);let r=aC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sC=V("$ZodCheckMultipleOf",(e,t)=>{Mn.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):my(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),lC=V("$ZodCheckNumberFormat",(e,t)=>{Mn.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,o]=yy[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=i,s.maximum=o,r&&(s.pattern=eC)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}});var dC=V("$ZodCheckMaxLength",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let a=Bu(i);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),uC=V("$ZodCheckMinLength",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let a=Bu(i);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),cC=V("$ZodCheckLengthEquals",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,o=i.length;if(o===t.length)return;let a=Bu(i),s=o>t.length;n.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ku=V("$ZodCheckStringFormat",(e,t)=>{var r,n;Mn.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),fC=V("$ZodCheckRegex",(e,t)=>{Ku.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),mC=V("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=iC),Ku.init(e,t)}),pC=V("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=oC),Ku.init(e,t)}),hC=V("$ZodCheckIncludes",(e,t)=>{Mn.init(e,t);let r=Ia(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),_C=V("$ZodCheckStartsWith",(e,t)=>{Mn.init(e,t);let r=new RegExp(`^${Ia(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),gC=V("$ZodCheckEndsWith",(e,t)=>{Mn.init(e,t);let r=new RegExp(`.*${Ia(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var yC=V("$ZodCheckOverwrite",(e,t)=>{Mn.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var $m=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
289
|
+
`+t}var hO="Other",_O="linzumi_ask_user_question",gU="plan_mode_native_interview_tool",yU="no_active_turn";function Du(e){return JSON.stringify(e)}function bU(e){let t=e.trim().toLowerCase();switch(t){case"other":case"something else":case"something else...":return!0;default:return t.includes("other")?!0:t.includes("something else")}}function SU(e){let t=In(e),r=Gu(t!==void 0?t.questions:void 0);if(r===void 0)return{TAG:"Invalid",_0:"questions: expected an array"};let n=r.length;if(n===0)return{TAG:"Invalid",_0:"questions: min 1, got 0"};if(n>4)return{TAG:"Invalid",_0:"questions: max 4, got "+n.toString()};let i={contents:void 0},o=[],a=new Set;r.forEach((l,d)=>{if(i.contents!==void 0)return;let c=d.toString(),m=In(l);if(m===void 0){i.contents="questions["+c+"]: expected an object";return}let _=nn(m.question);if(_===void 0){i.contents="questions["+c+"].question: must be a non-empty string";return}if(a.has(_)){i.contents="questions: duplicate question text "+Du(_);return}let h=nn(m.header);if(h===void 0){i.contents="questions["+c+"].header: must be a non-empty string";return}if(h.length>12){i.contents="questions["+c+"].header: max 12 chars, got "+h.length.toString();return}let f=m.multiSelect;if(f!==void 0){let E=0;if(typeof f!="boolean"&&(E=2),E===2){i.contents="questions["+c+"].multiSelect: must be a boolean";return}}let p=Gu(m.options);if(p===void 0){i.contents="questions["+c+"].options: expected an array";return}let g=p.length;if(g<2){i.contents="questions["+c+"].options: min 2, got "+g.toString();return}if(g>4){i.contents="questions["+c+"].options: max 4, got "+g.toString();return}let b=[],y=new Set;if(p.forEach((E,G)=>{if(i.contents!==void 0)return;let Q=G.toString(),$=In(E),F=$!==void 0?nn($.label):void 0;if($!==void 0&&F!==void 0){let oe=$.description,W=0;if(oe!==void 0){let ae=0;if(typeof oe=="string"?W=2:ae=3,ae===3){i.contents="questions["+c+"].options["+Q+"].description: must be a string";return}}else W=2;if(W===2){if(bU(F)){i.contents="questions["+c+"].options["+Q+"].label: "+Du(F)+" is reserved for the built-in Other option";return}if(y.has(F)){i.contents="questions["+c+"].options: duplicate label "+Du(F);return}y.add(F);let ae=$.description,je;je=typeof ae=="string"?ae:"",b.push({label:F,description:je});return}}i.contents="questions["+c+"].options["+Q+"].label: must be a non-empty string"}),i.contents!==void 0)return;a.add(_);let w=m.multiSelect,C;C=w===!0,o.push({question:_,header:h,options:b,multiSelect:C})});let s=i.contents;return s!==void 0?{TAG:"Invalid",_0:s}:{TAG:"Parsed",_0:{questions:o}}}function vU(e){let t={};e.questions.forEach(s=>{let l={};l.type="string",l.description=s.header,t[s.question]=l});let r={};r.type="object",r.properties=t,r.required=e.questions.map(s=>s.question);let n=e.questions.map(s=>{let l={};return l.question=s.question,l.header=s.header,l.multiSelect=s.multiSelect,l.options=s.options.map(d=>{let u={};return u.label=d.label,u.description=d.description,u}),l}),i={};i.version=1,i.questions=n;let o={};o[_O]=i;let a={};return a.message="Linzumi interview: the user is being asked in the Linzumi thread.",a.requestedSchema=r,a._meta=o,a}function wU(e,t){let r=In(t);if(r===void 0)return{TAG:"AnswersInvalid",_0:"the runner accepted the interview but returned no answers; it may predate linzumi_ask_user_question support"};let n={contents:void 0},i={};e.questions.forEach(a=>{if(n.contents!==void 0)return;let l=r[a.question];if(typeof l=="string"){let d=0,u;try{u=JSON.parse(l),d=2}catch{n.contents="the runner returned an undecodable answer for question "+Du(a.question);return}if(d===2){i[a.question]=u;return}}n.contents="the runner returned no answer for question "+Du(a.question)});let o=n.contents;return o!==void 0?{TAG:"AnswersInvalid",_0:o}:{TAG:"Answers",_0:i}}function kU(e){let t=In(e);if(t===void 0)return;let r=In(t[_O]);return nn(r!==void 0?r.reason:void 0)}function ra(e){let t={};t.type="text",t.text=e;let r={};return r.content=[t],r.isError=!0,r}function TU(e){if(e===void 0)return"undefined";if(e===null)return"null";switch(typeof e){case"string":return e;case"number":return e.toString();default:return JSON.stringify(e)}}async function gO(e,t){let r=SU(t);if(r.TAG!=="Parsed")return ra(r._0);let n=r._0,i=0,o;try{o=await e(vU(n),2147483647),i=1}catch(a){let s=U(a);return ra("the interview could not be delivered to the user: "+$i(s))}if(i===1){let a=In(o),s=a!==void 0?a:{},l=s.action,d=0;if(typeof l=="string")switch(l){case"accept":let u=wU(n,s.content);if(u.TAG!=="Answers")return ra(u._0);let c={};return c.answers=u._0,Un(c);case"cancel":return ra("the user dismissed the question without answering");case"decline":let m=kU(s._meta);return ra(m!==void 0?m===gU?"linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead":m===yU?"the interview was declined: no active turn is bound to this session":"the interview request was declined by the runner":"the interview request was declined by the runner");default:d=2}else d=2;if(d===2)return ra("the interview returned an unknown action: "+TU(l))}}var yO="linzumi_ask_user_question",ny=4,iy=12,oy=2,ay=4;function AU(e){switch(e){case"All":return!0;case"Coding":case"OnboardingDiscovery":return!1}}function OU(e){return e==="Voice"}function CU(e){return e.trim().replace(new RegExp("^:+"),"").replace(new RegExp(":+$"),"").toLowerCase()}function bO(){return x.string().min(1).refine(e=>CU(e).length<=64,{message:"Custom emoji shortcode name must be at most 64 characters after trimming surrounding colons."})}function Mr(){return x.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")}function xi(){return x.string().optional().describe("Channel slug. Omit to use the authenticated token scope.")}function Ai(e){if(typeof e=="string")return e}function SO(e,t,r){let n=In(e[t]);return n!==void 0?n:Kr(r+" "+t+" must be an object")}function EU(e){return e!==void 0?Array.isArray(e)?Ye(e,t=>{if(typeof t=="string")return t}):[]:[]}function PU(e){return e!==void 0?Array.isArray(e)?Ye(e,t=>{if(typeof t=="number")return t}):[]:[]}function vO(e){if(typeof e=="number")return e}function wO(e){let t={};t.name=e.record.name,t.command=e.record.command,t.cwd=e.record.cwd,t.ports=e.record.ports.map(o=>o),t.restart_on_branch_change=e.record.restartOnBranchChange,t.desired_state=Zg(e.record.desiredState),t.liveness=XA(e.liveness),t.port_health=e.portProbes.map(o=>{let a={};return a.port=o.port,a.listening=o.listening,a});let r=e.record.startedAtMs;t.started_at_ms=r!==void 0?r:null;let n=e.lastExit,i;if(n!==void 0){let o={},a=n.code;o.code=a!==void 0?a:null;let s=n.signal;o.signal=s!==void 0?s:null,o.at_ms=n.atMs,i=o}else i=null;return t.last_exit=i,t.log_path=e.record.logPath,t}function RU(e,t,r){e.registerTool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",Object.fromEntries([["name",x.string().regex(new RegExp("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service.")],["command",x.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell.")],["cwd",x.string().optional().describe("Working directory for the service. Defaults to the session cwd.")],["ports",x.array(x.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility.")],["restart_on_branch_change",x.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts).")],["wait_for_ports_ms",x.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=Ai(n.command),s=a!==void 0?a:"",l=Ai(n.cwd),d=await iO({scopeDir:r.scopeDir,definition:{name:o,command:s,cwd:l!==void 0?l:t,ports:PU(n.ports),restartOnBranchChange:me(n.restart_on_branch_change,!0)},ownerPid:r.ownerPid});if(d.TAG==="Ok"){let c=d._0,m=vO(n.wait_for_ports_ms),_=Date.now()+(m!==void 0?m:15e3),h=c.ports.length===0;for(;!h&&Date.now()<_;)h=(await Promise.all(c.ports.map(S=>Yg(S|0)))).every(S=>S),h||await Uf(250);let p=(await Xg(r.scopeDir)).find(y=>y.record.name===c.name),g={};g.ok=!0;let b;if(p!==void 0)b=wO(p);else{let y={};y.name=c.name,b=y}return g.service=b,p!==void 0&&p.liveness!=="Running"&&(g.hint="The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."),Un(g)}let u={};return u.ok=!1,u.error=d._0,Un(u)}),e.registerTool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",Object.fromEntries([["name",x.string().min(1).describe("Service name to stop.")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=await ey(r.scopeDir,o,void 0),s={};return a.TAG==="Ok"?(s.ok=!0,s.name=a._0.name,s.desired_state="stopped"):(s.ok=!1,s.error=a._0),Un(s)}),e.registerTool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / stopped), per-port health probes, and last exit. Live state - always check this before concluding a dev server is up or down.",{},async n=>{let i=await Xg(r.scopeDir),o={};return o.services=i.map(a=>wO(a)),Un(o)}),e.registerTool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",Object.fromEntries([["name",x.string().min(1).describe("Service name.")],["max_bytes",x.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=vO(n.max_bytes),s=aO(r.scopeDir,o,a!==void 0?a:16384),l={};return s!==void 0?(l.ok=!0,l.name=o,l.log_tail=s):(l.ok=!1,l.error="no log for service: "+o),Un(l)}),e.registerTool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",Object.fromEntries([["name",x.string().min(1).describe("Service name to remove.")]]),async n=>{let i=Ai(n.name),o=i!==void 0?i:"",a=await oO(r.scopeDir,o),s={};return a.TAG==="Ok"?(s.ok=!0,s.name=a._0.name,s.removed=!0):(s.ok=!1,s.error=a._0),Un(s)})}function kO(e,t){let r=t.devServices,n=t.agentSession,i=t.ownerUsername,o=t.defaultThreadId,a=t.serviceUrl,s=t.cwd,l=t.toolScope,d=t.client,u;switch(l){case"All":case"Coding":u=!0;break;case"OnboardingDiscovery":u=!1;break}let c=async f=>Un(await f),m=async(f,p)=>(p.tool=f,await c(d.agentDocumentTool(p))),_=t.documentSurfaces;_!==void 0&&_&&(e.registerTool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",Object.fromEntries([["query",x.string().min(1).describe("Document title or content search query.")]]),async f=>await m("lookup_documents",f)),e.registerTool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",Object.fromEntries([["document_id",x.string().uuid().describe("Document UUID.")]]),async f=>await m("read_document",f)),e.registerTool("linzumi_propose_document_patch","Use this tool for any explicit instruction to edit, add, rewrite, update, or fix document content, including parent-delegated work. After resolving exactly one patch target document and reading its current revision, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Every change is proposal-always: the server persists an agent-attributed structural patch proposal first, leaves it pending in hold mode, and resolves per-document auto-apply server-side only after persistence and authorization.",Object.fromEntries([["document_id",x.string().uuid().describe("Document UUID.")],["patch",x.record(x.unknown()).describe("Revisioned structural document patch.")],["rationale",x.string().min(1).describe("Why this change is proposed.")]]),async f=>await m("propose_document_patch",f)),e.registerTool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",Object.fromEntries([["title",x.string().min(1).describe("Document title.")],["initial_patch",x.record(x.unknown()).describe("Bootstrap structural patch.")],["folder_id",x.string().uuid().optional().describe("Destination folder UUID.")]]),async f=>await m("create_document",f)));let h=t.askUserQuestion;switch(h!==void 0&&e.registerTool(yO,"Ask the user up to "+ny.toString()+" structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max "+iy.toString()+" chars) and "+oy.toString()+"-"+ay.toString()+' options {label, description}; a built-in "'+hO+'" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.',Object.fromEntries([["questions",x.array(x.object(Object.fromEntries([["question",x.string().describe("The question to ask the user.")],["header",x.string().describe("Short category header shown above the question (max "+iy.toString()+' chars, e.g. "Auth", "Scope").')],["options",x.array(x.object(Object.fromEntries([["label",x.string().describe("Option label the user taps.")],["description",x.string().optional().describe("One-line explanation of the option.")]]))).describe(oy.toString()+"-"+ay.toString()+" options for this question.")],["multiSelect",x.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")]]))).describe("1-"+ny.toString()+" questions to ask atomically.")]]),async f=>await gO(h,f)),n&&(e.registerTool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",Object.fromEntries([["body",x.string().min(1).describe("Plain-text reply body to post.")]]),async f=>{let p={},g=f.body;return p.body=g!==void 0?g:void 0,await c(d.agentReply(p))}),e.registerTool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async f=>await c(d.agentListCodingJobs({}))),e.registerTool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["channel",x.string().describe("Channel slug to host the job thread.")],["runner_key",x.string().describe("Runner (computer) to run the job on.")],["cwd",x.string().describe("Working directory on the runner.")],["work_description",x.string().min(1).describe("What the job should do - the initial instruction.")],["model",x.string().optional().describe("Model override (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["execution_mode",x.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["project_task_id",x.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")]]),async f=>await c(d.agentStartCodingJob(f))),e.registerTool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["mode",x.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")]]),async f=>await c(d.agentInterruptCodingJob(f))),e.registerTool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",x.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set.")],["thread_id",x.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set.")],["to_user",x.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",x.string().min(1).describe("Message body to send.")],["delivery",x.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async f=>await c(d.agentSendCodingJobMessage(f))),e.registerTool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["limit",x.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",x.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await c(d.agentReadCodingJobThread(f))),e.registerTool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the job thread.")],["thread_id",x.string().uuid().describe("The job thread UUID.")],["source_seq",x.number().int().positive().describe("Channel seq of the message the approval request rides on.")],["request_id",x.string().describe("The approval request id.")],["decision",x.enum(["approve","deny"]).describe("The asker's decision.")]]),async f=>await c(d.agentResolveJobApproval(f))),e.registerTool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID to archive.")]]),async f=>await c(d.agentArchiveCodingJob(f))),e.registerTool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID to unarchive.")]]),async f=>await c(d.agentUnarchiveCodingJob(f))),e.registerTool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",Object.fromEntries([["channel",x.string().describe("Channel slug hosting the thread.")],["thread_id",x.string().uuid().describe("The thread UUID.")],["status",x.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")]]),async f=>await c(d.agentSetThreadStatus(f))),e.registerTool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",Object.fromEntries([["name",x.string().min(1).describe("Channel name to create.")]]),async f=>await c(d.agentCreateChannel(f))),e.registerTool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",Object.fromEntries([["channel",x.string().describe("Current channel slug to rename.")],["name",x.string().min(1).describe("New display name.")]]),async f=>await c(d.agentRenameChannel(f))),e.registerTool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",Object.fromEntries([["channel",x.string().describe("Channel slug to archive.")]]),async f=>await c(d.agentArchiveChannel(f))),e.registerTool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",Object.fromEntries([["channel",x.string().describe("Channel slug to unarchive.")]]),async f=>await c(d.agentUnarchiveChannel(f))),e.registerTool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the message to react to.")],["emoji",x.string().min(1).describe("Emoji to add (unicode or :shortcode:).")]]),async f=>await c(d.agentAddReaction(f))),e.registerTool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the reacted message.")],["emoji",x.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")]]),async f=>await c(d.agentRemoveReaction(f))),e.registerTool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the message to pin.")]]),async f=>await c(d.agentPinMessage(f))),e.registerTool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",Object.fromEntries([["channel",x.string().describe("Channel slug containing the message.")],["message_seq",x.number().int().positive().describe("Channel seq of the pinned message.")]]),async f=>await c(d.agentUnpinMessage(f)))),l){case"All":e.registerTool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["message_id",x.union([x.string(),x.number()]).optional().describe("Message seq inside the scoped channel.")],["message_seq",x.union([x.string(),x.number()]).optional().describe("Alias for message_id.")],["message_url",x.string().optional().describe("Full Linzumi message URL with #message-<seq>.")],["before",x.number().int().min(0).max(100).optional().describe("Number of visible messages before the target.")],["after",x.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")]]),async f=>await c(d.getMessage(f))),e.registerTool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Linzumi thread UUID.")],["limit",x.number().int().min(1).max(100).optional().describe("Maximum replies to return.")],["before_seq",x.number().int().positive().optional().describe("Return replies before this channel seq.")]]),async f=>await c(d.getThread(f))),e.registerTool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Linzumi thread UUID.")],["limit",x.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200).")],["cursor",x.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")]]),async f=>await c(d.getThreadTranscript(f))),e.registerTool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["limit",x.number().int().min(1).max(100).optional().describe("Maximum messages to return.")],["before_seq",x.number().int().positive().optional().describe("Return messages before this channel seq.")]]),async f=>await c(d.getChannel(f))),e.registerTool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",Object.fromEntries([["workspace",Mr()],["query",x.string().min(1).describe("Natural-language or keyword query to retrieve against.")],["limit",x.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped).")],["source_types",x.array(x.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all.")],["authored_after",x.string().optional().describe("ISO8601 instant; only content authored at or after this time.")],["authored_before",x.string().optional().describe("ISO8601 instant; only content authored at or before this time.")],["repo",x.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name).")],["check_status",x.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")]]),async f=>await c(d.searchWorkspace(f))),e.registerTool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',Object.fromEntries([["workspace",Mr()],["question",x.string().min(1).max(2e3).describe("Natural-language question to answer with citations.")],["channel",x.string().optional().describe("Optional channel slug providing conversational context; never widens access.")],["allow_cached",x.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")]]),async f=>await c(d.askWorkspace(f))),e.registerTool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>await c(d.aboutMe(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(u&&(e.registerTool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",Object.fromEntries([["query",x.string().min(1).describe("Web search query (natural language or keywords).")],["limit",x.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")]]),async f=>await c(d.webSearch(f))),e.registerTool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",Object.fromEntries([["url",x.string().min(1).describe("Absolute public http(s) URL to fetch.")]]),async f=>await c(d.fetchUrl(f)))),l){case"All":e.registerTool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async f=>await Dg(d.listUiTargets({}))),e.registerTool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",Object.fromEntries([["kind",x.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout).")],["args",x.record(x.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path).")],["workspace",Mr()]]),async f=>await Dg(d.openUi(Fi(f,o))));break;case"Coding":case"OnboardingDiscovery":break}if(u){let f=()=>x.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.");e.registerTool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()]]),async p=>await c(d.getCodingJobMetadata(Fi(p,o)))),e.registerTool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["title",x.string().min(1).max(100).describe("Concise user-visible title for this coding job.")]]),async p=>await c(d.renameCodingJob(Fi(p,o)))),e.registerTool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["goal",x.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")]]),async p=>await c(d.upsertCodingJobPlan(Fi(p,o)))),e.registerTool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["goal",x.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal.")],["steps",x.array(x.object(Object.fromEntries([["title",x.string().min(1).max(255)],["description",x.string().min(1).max(1e4)],["status",x.enum(["pending","active","completed","blocked","canceled"])],["status_note",x.string().min(1).max(4e3).optional()],["completed_debrief",x.string().min(1).max(2e4).optional()]]))).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")]]),async p=>await c(d.replaceCodingJobPlanSteps(Fi(p,o)))),e.registerTool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["step_id",x.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata.")],["lock_version",x.number().int().positive().describe("Current step lock_version from metadata.")],["status",x.enum(["pending","active","completed","blocked","canceled"])],["status_note",x.string().min(1).max(4e3).optional()],["completed_debrief",x.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")]]),async p=>await c(d.updateCodingJobPlanStep(Fi(p,o)))),e.registerTool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",f()],["github_repo_owner",x.string().min(1).max(255)],["github_repo_name",x.string().min(1).max(255)],["github_pr_number",x.number().int().positive()],["github_pr_url",x.string().url()],["title",x.string().min(1).max(255)],["body",x.string().min(1).max(1e5).optional()],["head_branch",x.string().min(1).max(255)],["head_sha",x.string().min(7).max(64)],["base_branch",x.string().min(1).max(255)],["base_sha",x.string().min(7).max(64)],["state",x.enum(["draft","open","closed","merged"]).optional()],["is_draft",x.boolean().optional()],["review_status",x.enum(["unknown","review_required","approved","changes_requested"]).optional()],["source_remote_url",x.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet.")],["runtime_worktree_root",x.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet.")],["dirty_status",x.enum(["unknown","clean","dirty"]).optional()],["dirty_summary",x.string().min(1).max(2e3).optional()]]),async p=>await c(d.linkCodingJobPullRequest(Fi(p,o)))),e.registerTool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),Object.fromEntries([["target",x.object(Object.fromEntries([["kind",x.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel.")],["message_seq",x.union([x.string(),x.number()]).optional().describe("Required when kind is message_seq.")],["thread_id",x.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")]])).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit.")],["files",x.array(x.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types.")],["body",x.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool.")],["workspace",Mr()],["channel",x.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")]]),async p=>{let g=Lg(SO(p,"target","linzumi_upload_files"),o),b;try{b=await ZA({client:d,cwd:s,serviceUrl:a,target:g,files:EU(p.files),workspace:Ai(p.workspace),channel:Ai(p.channel),body:Ai(p.body)})}catch(y){return WA(U(y))}return Un(Ug(a,b))}),e.registerTool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["target",x.object(Object.fromEntries([["message_seq",x.union([x.string(),x.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here.")],["thread_id",x.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")]])).describe("Exact message target for the body edit.")],["body",x.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")]]),async p=>{let g=ta(p);return g.target=Lg(SO(p,"target","linzumi_edit_message"),o),Un(Ug(a,await d.editMessage(g)))})}switch(l){case"All":if(e.registerTool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>await c(d.listVaultSecrets(f))),e.registerTool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",Object.fromEntries([["workspace",Mr()]]),async f=>await c(d.listProjects(f))),e.registerTool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,Object.fromEntries([["project_id",x.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")]]),async f=>await c(d.getProjectTasks(Fi(f,o)))),e.registerTool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',Object.fromEntries([["project_id",x.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")],["title",x.string().min(1).describe("Task title.")],["kind",x.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).')],["description",x.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it.")],["status",x.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".')],["parent_id",x.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent.")],["assignee",x.string().optional().describe("Username of a workspace member to assign.")],["position",x.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")]]),async f=>await c(d.createProjectTask(Fi(f,o)))),e.registerTool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',Object.fromEntries([["task_id",x.string().describe("task_id of the group or issue to update.")],["title",x.string().min(1).optional().describe("New title.")],["description",x.string().nullable().optional().describe("New description. Pass null to clear it.")],["status",x.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.')],["status_note",x.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it.")],["position",x.number().int().min(0).optional().describe("New sort position among siblings.")],["parent_id",x.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent.")],["clear_parent",x.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id.")],["assignee",x.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee.")],["clear_assignee",x.boolean().optional().describe("true removes the assignee. Do not combine with assignee.")],["lock_version",x.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")]]),async f=>await c(d.updateProjectTask(f))),e.registerTool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,Object.fromEntries([["task_id",x.string().describe("task_id of the group or issue to delete.")]]),async f=>await c(d.deleteProjectTask(f))),e.registerTool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',Object.fromEntries([["task_id",x.string().describe("task_id of the DEPENDENT issue (the one that must wait).")],["depends_on_task_id",x.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")]]),async f=>await c(d.addProjectTaskDependency(f))),e.registerTool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',Object.fromEntries([["task_id",x.string().describe("task_id of the DEPENDENT issue.")],["depends_on_task_id",x.string().describe("task_id of the PREREQUISITE issue the edge points at.")]]),async f=>await c(d.removeProjectTaskDependency(f))),e.registerTool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",Object.fromEntries([["call_id",x.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")]]),async f=>await c(d.getCallTranscript(f))),!n){e.registerTool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job - only start tasks whose work_state is ready, and ONLY after the user explicitly accepts your offer to start them. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",x.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description.")],["project_task_id",x.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")],["channel",x.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel.")],["runner_key",x.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer.")],["cwd",x.string().optional().describe("Working directory on the runner. Omit to use this job's own folder.")],["model",x.string().optional().describe("Model override (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["agent_provider",x.string().optional().describe("Agent provider override, e.g. 'codex' (optional).")],["reasoning_effort",x.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["approval_policy",x.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional).")],["sandbox",x.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional).")],["fast",x.boolean().optional().describe("Fast-mode override (optional).")],["allow_port_forwarding_by_default",x.boolean().optional().describe("Default port-forwarding override (optional).")],["execution_mode",x.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")],["egress_mode",x.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")]]),async p=>await c(d.agentStartCodingJob(Fi(p,o))));let f=t.multiAgentJobs;f!==void 0&&f&&(e.registerTool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",Object.fromEntries([["work_description",x.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone.")],["agent_provider",x.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job.")],["model",x.string().optional().describe("Model override for the child (optional).")],["model_provider",x.string().optional().describe("Model provider override, e.g. 'wafer' (optional).")],["reasoning_effort",x.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional).")],["project_task_id",x.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job.")],["visibility",x.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")]]),async p=>await c(d.agentSpawnChildJob(Fi(p,o)))),e.registerTool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",Object.fromEntries([["query",x.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")]]),async p=>{let g={};return Object.entries(p).forEach(b=>{g[b[0]]=b[1]}),g.source_thread_id=qg(z(o,b=>b)),await c(d.agentDiscoverCodingJobs(g))}),e.registerTool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",Object.fromEntries([["channel",x.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set.")],["thread_id",x.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set.")],["to_user",x.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox.")],["body",x.string().min(1).describe("Coordination message to send.")],["delivery",x.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")]]),async p=>{let g={};return Object.entries(p).forEach(b=>{g[b[0]]=b[1]}),g.source_thread_id=qg(z(o,b=>b)),await c(d.agentSendCodingJobMessage(g))}))}break;case"Coding":case"OnboardingDiscovery":break}switch(AU(l)&&(e.registerTool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",Object.fromEntries([["name",bO().describe("Custom emoji shortcode name, with or without surrounding colons.")],["file",x.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji.")],["workspace",Mr()]]),async f=>{let p=Ai(f.name),g=Ai(f.file);return Un(await BA({client:d,cwd:s,serviceUrl:a,name:p!==void 0?p:"",file:g!==void 0?g:"",workspace:Ai(f.workspace)}))}),e.registerTool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",Object.fromEntries([["emoji_id",x.union([x.string(),x.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings.")],["name",bO().describe("New shortcode name, with or without surrounding colons.")],["workspace",Mr()]]),async f=>await c(d.renameCustomEmoji(f)))),e.registerTool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async f=>{let p={};p.type="text",p.text=dO;let g={};return g.content=[p],g}),e.registerTool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["path",x.string().min(1).describe("Absolute local path to the repository worktree root.")],["display_name",x.string().optional().describe("Short project label. Defaults to the path basename.")],["activity_at",x.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["import_key",x.string().optional().describe("Stable dedupe key. Defaults to path.")],["metadata",x.record(x.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")]]),async f=>await c(d.noteProjectDirectory(f))),e.registerTool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["source",x.enum(["codex","claude_code"]).describe("Conversation source.")],["import_key",x.string().min(1).describe("Stable dedupe key, such as a session id or file path.")],["path",x.string().optional().describe("Absolute local path to the conversation file or directory.")],["display_name",x.string().optional().describe("Short label for the discovered conversation.")],["activity_at",x.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp.")],["metadata",x.record(x.unknown()).optional().describe("Small structured metadata such as session id or project path.")]]),async f=>await c(d.noteAgentConversation(f))),e.registerTool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",Object.fromEntries([["workspace",Mr()],["runner_id",x.string().min(1).describe("Local runner/computer id provided in the discovery prompt.")],["phase",x.enum(["projects","conversations"]).describe("Discovery phase being reported.")],["status",x.enum(["starting","running","completed","failed"]).describe("Current phase status.")],["places_searched",x.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far.")],["message",x.string().optional().describe("Short user-facing status note.")],["current_place",x.string().optional().describe("Current folder, file, Git command target, or known location being checked.")],["current_source",x.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code.")],["last_error",x.string().optional().describe("Short failure detail when status is failed.")],["metadata",x.record(x.unknown()).optional().describe("Small structured status metadata.")]]),async f=>await c(d.noteOnboardingDiscoveryStatus(f))),l==="All"&&OU(t.operatingMode)&&(e.registerTool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",Object.fromEntries([["owner_username",x.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username.")],["workspace",Mr()],["channel",x.string().optional().describe("Source channel slug used to verify owner visibility.")],["body",x.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>{let p=Ai(f.owner_username),g=p!==void 0?p:i;if(g===void 0)return Kr("owner_username is required for linzumi_dm_owner");let b=ta(f);return b.owner_username=g,await c(d.dmOwner(b))}),e.registerTool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["body",x.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await c(d.sendChannelMessage(f))),e.registerTool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",Object.fromEntries([["workspace",Mr()],["channel",xi()],["thread_id",x.string().uuid().describe("Existing Linzumi thread UUID.")],["body",x.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths.")]]),async f=>await c(d.sendThreadReply(f))),e.registerTool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",Object.fromEntries([["workspace",Mr()],["channel",x.string().optional().describe("Source channel slug used to verify target visibility.")],["username",x.string().describe("Visible Linzumi username to DM.")],["body",x.string().min(1).max(2e4).describe("Plain-text message body to DM.")]]),async f=>await c(d.sendDm(f)))),l){case"All":e.registerTool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",Object.fromEntries([["workspace",Mr()],["channel",x.string().optional().describe("Channel slug used to disambiguate the approval thread when needed.")],["thread_id",x.string().uuid().describe("Existing Linzumi thread UUID for the inline approval.")],["env_var_names",x.array(x.string().regex(new RegExp("^[A-Z][A-Z0-9_]{0,127}$"))).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys.")],["description",x.string().min(1).max(500).describe("Human-readable reason shown in the approval request.")],["justification",x.string().min(10).max(1e3).describe("Agent justification shown to the approver.")]]),async f=>await c(d.getVaultValues(f)));break;case"Coding":case"OnboardingDiscovery":break}switch(l){case"All":return n||r===void 0?void 0:RU(e,s,r);case"Coding":case"OnboardingDiscovery":return}}function TO(e){if(typeof e=="number"&&e%1===0)return e}function MU(e){if(typeof e=="string")return e}function $U(e){let t=e.replaceAll("-","+").replaceAll("_","/");switch(t.length&3){case 2:return t+"==";case 3:return t+"=";default:return t}}function ly(e){let t=e.split(".")[1];if(t===void 0)return;let r=Buffer.from($U(t),"base64").toString("utf8"),n;try{n=JSON.parse(r)}catch{n=void 0}if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}function Lu(e){let t=ly(e);if(t===void 0)return{actorUserId:void 0,actorUsername:void 0};let r=TO(t.actor_id);return{actorUserId:r!==void 0?r:TO(t.sub),actorUsername:MU(t.actor_username)}}function xO(e){let t=k(ly(e),n=>n.workspace_scope),r=t!==void 0?Array.isArray(t)?Ye(t,n=>{if(typeof n=="string"&&n.trim()!=="")return n}):[]:[];if(r.length===1)return r[0]}var sy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AO(e){let t=ly(e);if(t===void 0)return!1;let n=t.document_surfaces===!0,i=t.linzumi_agent_session,o=typeof i=="string"?sy.test(i):!1,a=t.coding_job_id,s=t.coding_job_thread_id,l=typeof a=="string"&&typeof s=="string"?sy.test(a)&&sy.test(s):!1;return n?o?!0:l:!1}function jU(e){return typeof e==="undefined"?!0:e===null}function dy(e){let t=Yn(e.serviceUrl);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=e.fetchImpl,i=n!==void 0?n:Lf,o=e.authMode,a=o!==void 0&&o!=="LocalRunner"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",s=e.operatingMode,l=s!==void 0?ry(s):"text",d=async(u,c,m)=>{let _=Lo(c,r),h;h=_.TAG==="Ok"?_._0:Kr(_._0);let f={};Object.entries(m).forEach(E=>{f[E[0]]=E[1]}),f.operating_mode=l;let p={};p.authorization="Bearer "+e.accessToken;let g;if(u==="Get"){let E=h.searchParams;Object.entries(f).forEach(G=>{let j=G[1];if(!jU(j)){E.set(G[0],String(j));return}}),g=await i.json(h.toString(),{method:"GET",headers:p})}else p["content-type"]="application/json",g=await i.json(h.toString(),{method:"POST",headers:p,body:JSON.stringify(f)});let b=await g.json(),y;if(y=typeof b=="object"&&b!==null&&!Array.isArray(b)?b:void 0,y===void 0)return Kr("Linzumi MCP API returned non-object JSON from "+c);let S=g.ok,w=me(y.ok,!0),C=0;if(S){if(w)return y;C=1}else C=1;if(C===1){let E=y.error,G,j=0;typeof E=="string"?G=E:j=2,j===2&&(G="HTTP "+g.status.toString());let Q=y.detail,$=typeof Q=="string"?" detail="+Q:"";return Kr("Linzumi MCP API "+c+" failed: "+G+$)}};return{TAG:"Ok",_0:{validateAuth:()=>d("Get",a+"/validate",{}),issueOnboardingDiscoveryToken:u=>d("Post",a+"/onboarding-discovery-token",u),getMessage:u=>d("Get",a+"/message",u),getThread:u=>d("Get",a+"/thread",u),getThreadTranscript:u=>d("Get",a+"/thread-transcript",u),getChannel:u=>d("Get",a+"/channel",u),searchWorkspace:u=>d("Get",a+"/search",u),askWorkspace:u=>d("Post",a+"/ask",u),aboutMe:u=>d("Get",a+"/about-me",u),webSearch:u=>d("Get",a+"/web-search",u),fetchUrl:u=>d("Get",a+"/fetch-url",u),listUiTargets:u=>d("Get",a+"/ui-targets",u),openUi:u=>d("Post",a+"/open-ui",u),getCodingJobMetadata:u=>d("Get",a+"/coding-job-metadata",u),listProjects:u=>d("Get",a+"/projects",u),getProjectTasks:u=>d("Get",a+"/project-tasks",u),createProjectTask:u=>d("Post",a+"/project-tasks/create",u),updateProjectTask:u=>d("Post",a+"/project-tasks/update",u),deleteProjectTask:u=>d("Post",a+"/project-tasks/delete",u),addProjectTaskDependency:u=>d("Post",a+"/project-tasks/add-dependency",u),removeProjectTaskDependency:u=>d("Post",a+"/project-tasks/remove-dependency",u),getCallTranscript:u=>d("Get",a+"/call-transcript",u),renameCodingJob:u=>d("Post",a+"/coding-job-title",u),upsertCodingJobPlan:u=>d("Post",a+"/coding-job-plan",u),replaceCodingJobPlanSteps:u=>d("Post",a+"/coding-job-plan/steps",u),updateCodingJobPlanStep:u=>d("Post",a+"/coding-job-plan/step",u),linkCodingJobPullRequest:u=>d("Post",a+"/coding-job-primary-pr",u),listVaultSecrets:u=>d("Get",a+"/vault-secrets",u),noteProjectDirectory:u=>d("Post",a+"/discovered-project",u),noteAgentConversation:u=>d("Post",a+"/discovered-conversation",u),noteOnboardingDiscoveryStatus:u=>d("Post",a+"/discovery-status",u),sendChannelMessage:u=>d("Post",a+"/channel-message",u),editMessage:u=>d("Post",a+"/message/edit",u),agentReply:u=>d("Post",a+"/agent-reply",u),agentTurnProgress:u=>d("Post",a+"/agent-turn-progress",u),agentDocumentTool:u=>d("Post",a+"/agent/document-tool",u),agentListCodingJobs:u=>d("Get",a+"/agent/coding-jobs",u),agentStartCodingJob:u=>d("Post",a+"/agent/start-coding-job",u),agentSpawnChildJob:u=>d("Post",a+"/agent/spawn-child-job",u),agentInterruptCodingJob:u=>d("Post",a+"/agent/interrupt-coding-job",u),agentSendCodingJobMessage:u=>d("Post",a+"/agent/send-coding-job-message",u),agentDiscoverCodingJobs:u=>d("Get",a+"/agent/discover-coding-jobs",u),agentReadCodingJobThread:u=>d("Get",a+"/agent/coding-job-thread",u),agentResolveJobApproval:u=>d("Post",a+"/agent/resolve-job-approval",u),agentArchiveCodingJob:u=>d("Post",a+"/agent/archive-coding-job",u),agentUnarchiveCodingJob:u=>d("Post",a+"/agent/unarchive-coding-job",u),agentSetThreadStatus:u=>d("Post",a+"/agent/set-thread-status",u),agentCreateChannel:u=>d("Post",a+"/agent/create-channel",u),agentRenameChannel:u=>d("Post",a+"/agent/rename-channel",u),agentArchiveChannel:u=>d("Post",a+"/agent/archive-channel",u),agentUnarchiveChannel:u=>d("Post",a+"/agent/unarchive-channel",u),agentAddReaction:u=>d("Post",a+"/agent/add-reaction",u),agentRemoveReaction:u=>d("Post",a+"/agent/remove-reaction",u),agentPinMessage:u=>d("Post",a+"/agent/pin-message",u),agentUnpinMessage:u=>d("Post",a+"/agent/unpin-message",u),prepareMessageUploads:u=>d("Post",a+"/message-uploads/prepare",u),attachMessageFiles:u=>d("Post",a+"/message-files/attach",u),prepareCustomEmoji:u=>d("Post",a+"/custom-emoji/prepare",u),renameCustomEmoji:u=>d("Post",a+"/custom-emoji/rename",u),sendThreadReply:u=>d("Post",a+"/thread-reply",u),sendDm:u=>d("Post",a+"/dm",u),dmOwner:u=>d("Post",a+"/dm-owner",u),getVaultValues:u=>d("Post",a+"/vault-values",u)}}}var zU=Object.freeze({status:"aborted"});function V(e,t,r){function n(s,l){var d;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(d=s._zod).traits??(d.traits=new Set),s._zod.traits.add(e),t(s,l);for(let u in a.prototype)u in s||Object.defineProperty(s,u,{value:a.prototype[u].bind(s)});s._zod.constr=a,s._zod.def=l}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function a(s){var l;let d=r?.Parent?new o:this;n(d,s),(l=d._zod).deferred??(l.deferred=[]);for(let u of d._zod.deferred)u();return d}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var na=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Cm={};function Oi(e){return e&&Object.assign(Cm,e),Cm}var Ut={};q_(Ut,{BIGINT_FORMAT_RANGES:()=>CO,Class:()=>cy,NUMBER_FORMAT_RANGES:()=>yy,aborted:()=>Ds,allowsEval:()=>hy,assert:()=>LU,assertEqual:()=>NU,assertIs:()=>qU,assertNever:()=>DU,assertNotEqual:()=>FU,assignProp:()=>py,cached:()=>Vu,captureStackTrace:()=>Pm,cleanEnum:()=>t2,cleanRegex:()=>Zu,clone:()=>Ci,createTransparentProxy:()=>BU,defineLazy:()=>$r,esc:()=>qs,escapeRegex:()=>Ia,extend:()=>QU,finalizeIssue:()=>io,floatSafeRemainder:()=>my,getElementAtPath:()=>UU,getEnumValues:()=>Wu,getLengthableOrigin:()=>Bu,getParsedType:()=>ZU,getSizableOrigin:()=>EO,isObject:()=>od,isPlainObject:()=>ad,issue:()=>by,joinValues:()=>Em,jsonStringifyReplacer:()=>fy,merge:()=>YU,normalizeParams:()=>ft,nullish:()=>Hu,numKeys:()=>HU,omit:()=>KU,optionalKeys:()=>gy,partial:()=>XU,pick:()=>JU,prefixIssues:()=>Oo,primitiveTypes:()=>OO,promiseAllObject:()=>WU,propertyKeyTypes:()=>_y,randomString:()=>VU,required:()=>e2,stringifyPrimitive:()=>Rm,unwrapMessage:()=>Uu});function NU(e){return e}function FU(e){return e}function qU(e){}function DU(e){throw new Error}function LU(e){}function Wu(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function Em(e,t="|"){return e.map(r=>Rm(r)).join(t)}function fy(e,t){return typeof t=="bigint"?t.toString():t}function Vu(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Hu(e){return e==null}function Zu(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function my(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}function $r(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function py(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UU(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function WU(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=n[o];return i})}function VU(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function qs(e){return JSON.stringify(e)}var Pm=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function od(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var hy=Vu(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function ad(e){if(od(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(od(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function HU(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ZU=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},_y=new Set(["string","number","symbol"]),OO=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ia(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ci(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ft(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function BU(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,o){return t??(t=e()),Reflect.set(t,n,i,o)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function Rm(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function gy(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var yy={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},CO={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function JU(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Ci(e,{...e._zod.def,shape:r,checks:[]})}function KU(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Ci(e,{...e._zod.def,shape:r,checks:[]})}function QU(e,t){if(!ad(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return py(this,"shape",n),n},checks:[]};return Ci(e,r)}function YU(e,t){return Ci(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return py(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function XU(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=e?new e({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)i[o]=e?new e({type:"optional",innerType:n[o]}):n[o];return Ci(t,{...t._zod.def,shape:i,checks:[]})}function e2(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(i[o]=new e({type:"nonoptional",innerType:n[o]}))}else for(let o in n)i[o]=new e({type:"nonoptional",innerType:n[o]});return Ci(t,{...t._zod.def,shape:i,checks:[]})}function Ds(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Oo(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Uu(e){return typeof e=="string"?e:e?.message}function io(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=Uu(e.inst?._zod.def?.error?.(e))??Uu(t?.error?.(e))??Uu(r.customError?.(e))??Uu(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function EO(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Bu(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function by(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function t2(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var cy=class{constructor(...t){}};var PO=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,fy,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Im=V("$ZodError",PO),Ju=V("$ZodError",PO,{Parent:Error});function Sy(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function vy(e,t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>i({issues:s}));else if(a.code==="invalid_key")i({issues:a.issues});else if(a.code==="invalid_element")i({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let s=n,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(s[d]=s[d]||{_errors:[]},s[d]._errors.push(r(a))):s[d]=s[d]||{_errors:[]},s=s[d],l++}}};return i(e),n}var wy=e=>(t,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new na;if(a.issues.length){let s=new(i?.Err??e)(a.issues.map(l=>io(l,o,Oi())));throw Pm(s,i?.callee),s}return a.value},ky=wy(Ju),Ty=e=>async(t,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(i?.Err??e)(a.issues.map(l=>io(l,o,Oi())));throw Pm(s,i?.callee),s}return a.value},xy=Ty(Ju),Ay=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new na;return o.issues.length?{success:!1,error:new(e??Im)(o.issues.map(a=>io(a,i,Oi())))}:{success:!0,data:o.value}},Ls=Ay(Ju),Oy=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>io(a,i,Oi())))}:{success:!0,data:o.value}},Us=Oy(Ju);var RO=/^[cC][^\s-]{8,}$/,IO=/^[0-9a-z]+$/,MO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$O=/^[0-9a-vA-V]{20}$/,jO=/^[A-Za-z0-9]{27}$/,GO=/^[a-zA-Z0-9_-]{21}$/,zO=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var NO=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cy=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var FO=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var n2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function qO(){return new RegExp(n2,"u")}var DO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,LO=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,UO=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,WO=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,VO=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ey=/^[A-Za-z0-9_-]*$/,HO=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var ZO=/^\+(?:[0-9]){6,14}[0-9]$/,BO="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",JO=new RegExp(`^${BO}$`);function KO(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function QO(e){return new RegExp(`^${KO(e)}$`)}function YO(e){let t=KO({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${BO}T(?:${n})$`)}var XO=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var eC=/^\d+$/,tC=/^-?\d+(?:\.\d+)?/i,rC=/true|false/i,nC=/null/i;var iC=/^[^A-Z]*$/,oC=/^[^a-z]*$/;var Mn=V("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),aC={number:"number",bigint:"bigint",object:"date"},Py=V("$ZodCheckLessThan",(e,t)=>{Mn.init(e,t);let r=aC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ry=V("$ZodCheckGreaterThan",(e,t)=>{Mn.init(e,t);let r=aC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sC=V("$ZodCheckMultipleOf",(e,t)=>{Mn.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):my(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),lC=V("$ZodCheckNumberFormat",(e,t)=>{Mn.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,o]=yy[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=i,s.maximum=o,r&&(s.pattern=eC)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}});var dC=V("$ZodCheckMaxLength",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let a=Bu(i);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),uC=V("$ZodCheckMinLength",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let a=Bu(i);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),cC=V("$ZodCheckLengthEquals",(e,t)=>{var r;Mn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Hu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,o=i.length;if(o===t.length)return;let a=Bu(i),s=o>t.length;n.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ku=V("$ZodCheckStringFormat",(e,t)=>{var r,n;Mn.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),fC=V("$ZodCheckRegex",(e,t)=>{Ku.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),mC=V("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=iC),Ku.init(e,t)}),pC=V("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=oC),Ku.init(e,t)}),hC=V("$ZodCheckIncludes",(e,t)=>{Mn.init(e,t);let r=Ia(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),_C=V("$ZodCheckStartsWith",(e,t)=>{Mn.init(e,t);let r=new RegExp(`^${Ia(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),gC=V("$ZodCheckEndsWith",(e,t)=>{Mn.init(e,t);let r=new RegExp(`.*${Ia(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var yC=V("$ZodCheckOverwrite",(e,t)=>{Mn.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var $m=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
290
290
|
`).filter(a=>a),i=Math.min(...n.map(a=>a.length-a.trimStart().length)),o=n.map(a=>a.slice(i)).map(a=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...r,i.join(`
|
|
291
291
|
`))}};var SC={major:4,minor:0,patch:0};var Ar=V("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=SC;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(o,a,s)=>{let l=Ds(o),d;for(let u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(l)continue;let c=o.issues.length,m=u._zod.check(o);if(m instanceof Promise&&s?.async===!1)throw new na;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,o.issues.length!==c&&(l||(l=Ds(o,c)))});else{if(o.issues.length===c)continue;l||(l=Ds(o,c))}}return d?d.then(()=>o):o};e._zod.run=(o,a)=>{let s=e._zod.parse(o,a);if(s instanceof Promise){if(a.async===!1)throw new na;return s.then(l=>i(l,n,a))}return i(s,n,a)}}e["~standard"]={validate:i=>{try{let o=Ls(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Us(e,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Qu=V("$ZodString",(e,t)=>{Ar.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??XO(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),jr=V("$ZodStringFormat",(e,t)=>{Ku.init(e,t),Qu.init(e,t)}),My=V("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=NO),jr.init(e,t)}),$y=V("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Cy(n))}else t.pattern??(t.pattern=Cy());jr.init(e,t)}),jy=V("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=FO),jr.init(e,t)}),Gy=V("$ZodURL",(e,t)=>{jr.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),o=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:HO.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),zy=V("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=qO()),jr.init(e,t)}),Ny=V("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=GO),jr.init(e,t)}),Fy=V("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=RO),jr.init(e,t)}),qy=V("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=IO),jr.init(e,t)}),Dy=V("$ZodULID",(e,t)=>{t.pattern??(t.pattern=MO),jr.init(e,t)}),Ly=V("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$O),jr.init(e,t)}),Uy=V("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=jO),jr.init(e,t)}),PC=V("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=YO(t)),jr.init(e,t)}),RC=V("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=JO),jr.init(e,t)}),IC=V("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=QO(t)),jr.init(e,t)}),MC=V("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=zO),jr.init(e,t)}),Wy=V("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=DO),jr.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Vy=V("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=LO),jr.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Hy=V("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=UO),jr.init(e,t)}),Zy=V("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=WO),jr.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function $C(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var By=V("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=VO),jr.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{$C(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function i2(e){if(!Ey.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return $C(r)}var Jy=V("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ey),jr.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{i2(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ky=V("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ZO),jr.init(e,t)});function o2(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var Qy=V("$ZodJWT",(e,t)=>{jr.init(e,t),e._zod.check=r=>{o2(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Gm=V("$ZodNumber",(e,t)=>{Ar.init(e,t),e._zod.pattern=e._zod.bag.pattern??tC,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),Yy=V("$ZodNumber",(e,t)=>{lC.init(e,t),Gm.init(e,t)}),Xy=V("$ZodBoolean",(e,t)=>{Ar.init(e,t),e._zod.pattern=rC,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});var eb=V("$ZodNull",(e,t)=>{Ar.init(e,t),e._zod.pattern=nC,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}});var tb=V("$ZodUnknown",(e,t)=>{Ar.init(e,t),e._zod.parse=r=>r}),rb=V("$ZodNever",(e,t)=>{Ar.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function vC(e,t,r){e.issues.length&&t.issues.push(...Oo(r,e.issues)),t.value[r]=e.value}var nb=V("$ZodArray",(e,t)=>{Ar.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let o=[];for(let a=0;a<i.length;a++){let s=i[a],l=t.element._zod.run({value:s,issues:[]},n);l instanceof Promise?o.push(l.then(d=>vC(d,r,a))):vC(l,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function jm(e,t,r){e.issues.length&&t.issues.push(...Oo(r,e.issues)),t.value[r]=e.value}function wC(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Oo(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var zm=V("$ZodObject",(e,t)=>{Ar.init(e,t);let r=Vu(()=>{let c=Object.keys(t.shape);for(let _ of c)if(!(t.shape[_]instanceof Ar))throw new Error(`Invalid element at key "${_}": expected a Zod schema`);let m=gy(t.shape);return{shape:t.shape,keys:c,keySet:new Set(c),numKeys:c.length,optionalKeys:new Set(m)}});$r(e._zod,"propValues",()=>{let c=t.shape,m={};for(let _ in c){let h=c[_]._zod;if(h.values){m[_]??(m[_]=new Set);for(let f of h.values)m[_].add(f)}}return m});let n=c=>{let m=new $m(["shape","payload","ctx"]),_=r.value,h=b=>{let y=qs(b);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let f=Object.create(null),p=0;for(let b of _.keys)f[b]=`key_${p++}`;m.write("const newResult = {}");for(let b of _.keys)if(_.optionalKeys.has(b)){let y=f[b];m.write(`const ${y} = ${h(b)};`);let S=qs(b);m.write(`
|
|
292
292
|
if (${y}.issues.length) {
|
|
@@ -321,7 +321,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
321
321
|
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),vK(r)}clear(){this._buffer=void 0}};function vK(e){return bE.parse(JSON.parse(e))}function sM(e){return JSON.stringify(e)+`
|
|
322
322
|
`}var dh=class{constructor(t=lM.stdin,r=lM.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new lh,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=sM(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function kK(e){let t={};t.listChanged=!1;let r={};r.resources=t,e.server.registerCapabilities(r),e.server.setRequestHandler(cd,()=>{let n={};return n.resources=[],n}),e.server.setRequestHandler(fd,()=>{let n={};return n.resourceTemplates=[],n})}function TK(e){return{registerTool:(t,r,n,i)=>{e.tool(t,r,n,i)}}}function xK(e){return(t,r)=>e.server.elicitInput(t,{timeout:r})}async function jw(e){let t=e.delegationAuthFilePath;if(t!==void 0){let n=e.explicitToken,i=e.authFilePath;if(n!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};if(i!==void 0)return{TAG:"Error",_0:"--delegation-auth-file cannot be combined with --token or --auth-file"};let o=tA(t,Date.now());return o.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:o._0.accessToken,mode:"PersonalAgentDelegation"}}:{TAG:"Error",_0:o._0.summary}}let r=await TA(e.serviceUrl,e.explicitToken,e.authFilePath,e.workspaceSlug,e.channelSlug,void 0);return r.TAG==="Ok"?{TAG:"Ok",_0:{accessToken:r._0,mode:"LocalRunner"}}:{TAG:"Error",_0:r._0.summary}}function Gw(e,t){let r=tn(e,"token");return{serviceUrl:t,explicitToken:r!==void 0?r:process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:tn(e,"auth-file"),delegationAuthFilePath:tn(e,"delegation-auth-file"),workspaceSlug:tn(e,"workspace"),channelSlug:tn(e,"channel")}}async function AK(e){let t=Nf(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0;if(El(r,"help"))return ms(Df()),{TAG:"Ok",_0:void 0};let n=Ff(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await jw(Gw(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let a=o._0,s=qf(tn(r,"mode")),l=Z_(tn(r,"tool-scope"));if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let d=s._0;if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let u=tn(r,"owner-username"),c=u!==void 0?u:process.env.LINZUMI_MCP_OWNER_USERNAME,m=tn(r,"cwd"),_=m!==void 0?m:process.cwd(),h=tn(r,"thread-id"),f=h!==void 0?h:process.env[FA],p=dy({serviceUrl:i,accessToken:a.accessToken,authMode:a.mode,operatingMode:d});if(p.TAG!=="Ok")return{TAG:"Error",_0:p._0};let g=new sh({name:"linzumi",version:"0.1.0"});return kK(g),kO(TK(g),{client:p._0,toolScope:l._0,operatingMode:d,cwd:_,serviceUrl:i,defaultThreadId:f,ownerUsername:c,agentSession:El(r,"agent-session"),documentSurfaces:AO(a.accessToken),multiAgentJobs:El(r,"multi-agent-jobs"),devServices:sO(process.env),askUserQuestion:El(r,"ask-user-question-tool")?xK(g):void 0}),await g.connect(new dh),{TAG:"Ok",_0:void 0}}async function OK(e){let t=Nf(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=Ff(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=tn(r,"format"),a=o!==void 0?o:"codex",s=qf(tn(r,"mode"));if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let l;if(El(r,"include-token")){let m=await jw(Gw(r,i));l=m.TAG==="Ok"?{TAG:"Ok",_0:m._0.accessToken}:{TAG:"Error",_0:m._0}}else l={TAG:"Ok",_0:void 0};if(l.TAG!=="Ok")return{TAG:"Error",_0:l._0};let d=Z_(tn(r,"tool-scope"));if(d.TAG!=="Ok")return{TAG:"Error",_0:d._0};let u=tn(r,"owner-username"),c=id({command:tn(r,"command"),serviceUrl:i,accessToken:l._0,delegationAuthFilePath:tn(r,"delegation-auth-file"),ownerUsername:u!==void 0?u:process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:s._0,toolScope:d._0});switch(a){case"claude-code":return ms(mO(c)),{TAG:"Ok",_0:void 0};case"codex":return ms(pO(c)),{TAG:"Ok",_0:void 0};default:return{TAG:"Error",_0:"--format must be codex or claude-code"}}}async function CK(e){let t=Nf(e);if(t.TAG!=="Ok")return{TAG:"Error",_0:t._0};let r=t._0,n=Ff(r,"api-url");if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let i=n._0,o=await jw(Gw(r,i));if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let a=o._0,s=a.mode,l;if(s==="LocalRunner"){let d=await Vl(i,a.accessToken,tn(r,"workspace"),tn(r,"channel"),void 0);if(d.TAG==="Ok")switch(d._0){case"Usable":l={TAG:"Ok",_0:void 0};break;case"Rejected":case"NotFound":l={TAG:"Error",_0:"Linzumi MCP auth validation failed"};break}else l={TAG:"Error",_0:d._0.summary}}else{let d=qf(tn(r,"mode"));if(d.TAG==="Ok"){let u=dy({serviceUrl:i,accessToken:a.accessToken,authMode:a.mode,operatingMode:d._0});if(u.TAG==="Ok")try{await u._0.validateAuth(),l={TAG:"Ok",_0:void 0}}catch(c){let m=U(c);l={TAG:"Error",_0:$i(m)}}else l={TAG:"Error",_0:u._0}}else l={TAG:"Error",_0:d._0}}return l.TAG!=="Ok"?{TAG:"Error",_0:l._0}:(ms(`Linzumi MCP auth OK
|
|
323
323
|
`),{TAG:"Ok",_0:void 0})}async function dM(e){let t=e.slice(1),r=e[0];if(r!==void 0)switch(r){case"--help":case"-h":return ms(Df()),{TAG:"Ok",_0:void 0};case"config":return await OK(t);case"doctor":return await CK(t);case"server":return await AK(t);default:return{TAG:"Error",_0:"unknown linzumi mcp command: "+r}}else return ms(Df()),{TAG:"Ok",_0:void 0}}import*as fM from"node:fs";import*as mM from"node:url";import*as ni from"node:path";import*as pM from"node:module";var PK=[["linux","x64",{triple:"x86_64-unknown-linux-musl",packageName:"@openai/codex-linux-x64"}],["linux","arm64",{triple:"aarch64-unknown-linux-musl",packageName:"@openai/codex-linux-arm64"}],["android","x64",{triple:"x86_64-unknown-linux-musl",packageName:"@openai/codex-linux-x64"}],["android","arm64",{triple:"aarch64-unknown-linux-musl",packageName:"@openai/codex-linux-arm64"}],["darwin","x64",{triple:"x86_64-apple-darwin",packageName:"@openai/codex-darwin-x64"}],["darwin","arm64",{triple:"aarch64-apple-darwin",packageName:"@openai/codex-darwin-arm64"}],["win32","x64",{triple:"x86_64-pc-windows-msvc",packageName:"@openai/codex-win32-x64"}],["win32","arm64",{triple:"aarch64-pc-windows-msvc",packageName:"@openai/codex-win32-arm64"}]];function hM(e,t){return z(PK.find(r=>r[0]===e?r[1]===t:!1),r=>r[2])}function RK(e){try{return pM.createRequire(import.meta.url).resolve(e)}catch{return}}function IK(e){let t=Cl(e);return t.TAG==="Ok"?t._0:[]}function uh(){return{platform:process.platform,arch:process.arch,fileExists:e=>fM.existsSync(e),listDirectory:IK,resolveModulePath:RK,moduleDir:ni.dirname(mM.fileURLToPath(import.meta.url))}}function _M(e,t,r){let n=t;for(;;){let i=n,o=ni.join(...[i,"node_modules"].concat(e.split("/")));if(r(ni.join(o,"package.json")))return o;let a=ni.dirname(i);if(a===i)return;n=a}}function zw(e,t){let r=t.resolveModulePath(e+"/package.json");return r!==void 0?ni.dirname(r):_M(e,t.moduleDir,t.fileExists)}function MK(e,t,r){let i=r.platform==="win32"?"codex.exe":"codex",o=ni.join(e,t),s=[ni.join(o,"codex",i),ni.join(o,"bin",i),ni.join(o,i)].find(l=>r.fileExists(l));return s!==void 0?s:r.listDirectory(o).map(l=>ni.join(o,l,i)).find(l=>r.fileExists(l))}function $K(e){let t=hM(e.platform,e.arch);if(t===void 0)return;let r=[],n=zw(t.packageName,e);n!==void 0&&r.push(ni.join(n,"vendor"));let i=zw("@openai/codex",e);return i!==void 0&&r.push(ni.join(i,"vendor")),Le(r,void 0,(o,a)=>o!==void 0?o:MK(a,t.triple,e))}function jK(e){let t=zw("@openai/codex",e);if(t===void 0)return;let r=ir(ni.join(t,"package.json"));if(r.TAG!=="Ok")return;let n;try{n=JSON.parse(r._0)}catch{n=void 0}if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let i=n.version;if(i!==void 0&&typeof i=="string"&&i.trim()!=="")return i.trim()}var GK=new RegExp("(\\d+\\.\\d+\\.\\d+)");function ch(e){let t=ya(e,["--version"],1e4,1048576);if(t.TAG!=="Ok")return;let r=GK.exec(t._0);if(r!=null)return k(r.slice(1)[0],n=>n)}function zK(e,t){return e!==void 0&&t!==void 0?e===t?{TAG:"Match",version:e}:{TAG:"Mismatch",pathVersion:e,pinnedVersion:t}:{TAG:"Unverified",pathVersion:e,pinnedVersion:t}}function NK(e){switch(e.TAG){case"Match":return"match";case"Mismatch":return"mismatch";case"Unverified":return"unverified"}}var Nw="LINZUMI_ALLOW_HARNESS_MISMATCH",uM={contents:!1};var FK="Warning: the Codex engine bundled with @linzumi/cli could not be located in its install (@openai/codex platform binary missing). Falling back to `codex` from PATH - the engine version may not match this CLI release. Pass --codex-bin <path> to pin an engine explicitly.\n";function qK(e){if(!uM.contents)return uM.contents=!0,e(FK)}function cM(e,t){return"the codex engine bundled with @linzumi/cli is missing from this install and the `codex` on PATH is version "+e+", but this CLI release pins engine "+t+". "+("Running a mismatched engine breaks the wire protocol (codex "+t+" vocabulary), so refusing to start. ")+("Fix: reinstall the CLI (a fresh `npx -y @linzumi/cli@latest` restores the bundled engine), pass --codex-bin <path> to pin an engine deliberately, or set "+Nw+"=1 to accept the skew.")}function DK(e,t){return"Warning: proceeding with the PATH codex "+e+" despite the CLI pinning engine "+t+" ("+Nw+`=1). Engine/CLI version skew can break the wire protocol.
|
|
324
|
-
`}function LK(e,t){}function fh(e,t,r,n,i,o){let a=o!==void 0?o:LK;if(e!==void 0)return{TAG:"Ok",_0:{codexBin:e,source:"ExplicitFlag"}};let s=$K(t);if(s!==void 0){let m={};return m.codex_bin_path=s,m.codex_bin_source="bundled",a("codex.binary.resolved",m),{TAG:"Ok",_0:{codexBin:s,source:"Bundled"}}}qK(r);let l=jK(t),d=l!==void 0?n("codex"):void 0,u=zK(d,l),c={};switch(c.codex_bin_path="codex",c.codex_bin_source="path-fallback",c.harness_version_check=NK(u),u.TAG){case"Match":c.harness_version=u.version;break;case"Mismatch":c.path_harness_version=u.pathVersion,c.pinned_harness_version=u.pinnedVersion;break;case"Unverified":c.path_harness_version=Pr(u.pathVersion,null,m=>m),c.pinned_harness_version=Pr(u.pinnedVersion,null,m=>m);break}switch(a("codex.binary.resolved",c),u.TAG){case"Mismatch":let m=u.pinnedVersion,_=u.pathVersion,h=i[Nw];return h===void 0?{TAG:"Error",_0:cM(_,m)}:h!=="1"?{TAG:"Error",_0:cM(_,m)}:(r(DK(_,m)),{TAG:"Ok",_0:{codexBin:"codex",source:"PathFallback"}});case"Match":case"Unverified":return{TAG:"Ok",_0:{codexBin:"codex",source:"PathFallback"}}}}var qw=[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_fresh_session_resume","harness.mid_stream_stall_fresh_session_resume"],["codex.mid_stream_stall_fresh_session_resume_failed","harness.mid_stream_stall_fresh_session_resume_failed"],["codex.mid_stream_stall_fresh_session_resume_flagged","harness.mid_stream_stall_fresh_session_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_demoted_late_upstream_error","job.turn_demoted_late_upstream_error"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.child_thread_event_failed","linzumi.child_thread_event_failed"],["kandan.child_thread_event_skipped_missing_thread_binding","linzumi.child_thread_event_skipped_missing_thread_binding"],["kandan.child_thread_upsert_failed","linzumi.child_thread_upsert_failed"],["kandan.child_thread_upsert_skipped_missing_thread_binding","linzumi.child_thread_upsert_skipped_missing_thread_binding"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],gM=[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],mh=[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],Dw=[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]];function Wc(){return v("1.0.196","0.0.0-unbundled")}function Uw(){return"linzumi "+v("1.0.196","0.0.0-unbundled")}function Id(e,t){let r=e.indexOf(t);if(r!==-1)return r}function Ww(){let e=process.env.LINZUMI_NAMING_DUAL_EMIT;if(e===void 0)return!0;let t=e.trim().toLowerCase();return t!=="0"?t!=="false":!1}function Vw(e){let t={};return e.forEach(r=>{t[r[0]]=r[1]}),t}function UK(e){let t={};return e.forEach(r=>{t[r[1]]=r[0]}),t}var SM=Vw(gM),vM=Vw(mh),WK=Vw(Dw),VK=UK(Dw);function HK(e){return e.endsWith("_canonical")?!0:e.endsWith("_legacy")}function wM(e,t){return t>=32?e:Array.isArray(e)?e.map(r=>wM(r,t+1|0)):e===null?e:typeof e==="object"?kM(e,t):e}function kM(e,t){let r=Object.keys(e),n={};return r.forEach(i=>{let o=e[i];if(o!==void 0){n[i]=wM(o,t+1|0);return}}),r.forEach(i=>{if(HK(i))return;let o=n[i];if(o===void 0)return;let a=SM[i];if(a!==void 0)n[a]=o;else{let c=vM[i];c!==void 0&&(n[c]!==void 0||(n[c]=o))}let s=n[i];if(s===void 0||typeof s!="string")return;let l=WK[s];if(l!==void 0){if(n[i+"_canonical"]!==void 0)return;n[i+"_canonical"]=l;return}let d=VK[s];if(!(d===void 0||n[i+"_legacy"]!==void 0)){n[i+"_legacy"]=d;return}}),n}function ph(e){return Ww()?kM(e,0):e}function TM(e){let t=e.slice();return e.forEach(r=>{let n=SM[r];n!==void 0&&!t.includes(n)&&t.push(n);let i=vM[r];if(i!==void 0&&!t.includes(i)){t.push(i);return}}),t}var Md="<SENSITIVE_DATA>",ZK=TM(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"]),BK=["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"],JK=new RegExp("^(authorization|cookie|set-cookie|password)$","i"),KK=new RegExp("(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$","i"),QK=new RegExp("\\beyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b","g");function YK(e){return e!==void 0?JK.test(e)?!0:KK.test(e):!1}function xM(e){let t={contents:!1};return JT(e).forEach(r=>{if(ZK.includes(r.toLowerCase())){e.set(r,Md),t.contents=!0;return}}),t.contents}function XK(e){let t=Id(e,"?"),r=Id(e,"#");if(t===void 0||r!==void 0&&r<t)return e;let n=e.slice(0,t),i=r!==void 0?e.slice(t+1|0,r):e.slice(t+1|0),o=r!==void 0?e.slice(r):"",a=new URLSearchParams(i);return xM(a)?n+"?"+a.toString()+o:e}function e9(e){let t=Mi(e);if(t===void 0)return XK(e);let r=ge(t);return xM(r.searchParams),r.toString()}function da(e){return e9(e).replace(QK,Md)}function t9(e){let t=Id(e,"=");return t!==void 0?[e.slice(0,t),e.slice(t+1|0)]:[e,void 0]}function Zw(e,t){if(YK(t))return Md;if(Array.isArray(e))return t==="args"?r9(e):e.map(r=>Zw(r,void 0));if(e===null)return e;switch(typeof e){case"string":return da(e);case"object":return AM(e);default:return e}}function r9(e){let t={contents:!1};return e.map(r=>{if(typeof r=="string"){if(t.contents)return t.contents=!1,Md;let n=t9(r),i=n[0];return BK.includes(i)?n[1]!==void 0?i+"="+Md:(t.contents=!0,r):da(r)}return t.contents=!1,Zw(r,void 0)})}function AM(e){let t=e.name,r=typeof t=="string"?t.toLowerCase():void 0,n;if(r!==void 0)switch(r){case"authorization":case"cookie":case"set-cookie":n=!0;break;default:n=!1}else n=!1;let i={};return Object.entries(e).forEach(o=>{let a=o[0];if(a!=="runner_console"){i[a]=n&&a==="value"?Md:Zw(o[1],a);return}}),i}var $d=AM;import*as wi from"node:os";import*as _o from"node:path";function _h(e){return e!==void 0?ge(e):null}import*as pT from"node:crypto";function CM(e){return"local_runner:"+e}var n9="kandan-local-codex-runner",i9="rescript";function EM(e){let t={};t.clientName=n9,t.clientId=e.clientId;let r=e.machineFingerprint;t.machineFingerprint=r!==void 0?r:null,Object.entries(bA(e.machineFingerprintV2)).forEach(a=>{t[a[0]]=a[1]}),t.runnerPid=e.runnerPid,t.version=e.version,t.hostname=e.hostname,t.cwd=e.cwd;let n=e.workspace;t.workspace=n!==void 0?n:null;let i=e.channel;t.channel=i!==void 0?i:null,t.capabilities=e.capabilities;let o=e.generationOverlapEpoch;if(o!==void 0){let a={};a.epoch=o,a.overlap=!0,t.generation=a}return t.commander_impl=i9,t}function PM(e,t,r){let n={};return n.last_seq=r,t!==void 0&&(n.runner_id=e,n.thread_id=t),n}function An(e,t){return e.catch(r=>t(U(r)))}function IM(){let e=[],t=[],r={contents:!1},n=()=>{let a=e.shift();return a!==void 0?Promise.resolve({done:!1,value:a}):r.contents?Promise.resolve({done:!0}):new Promise((s,l)=>{t.push(s)})},i=()=>(r.contents=!0,Promise.resolve({done:!0})),o={};return o[Symbol.asyncIterator]=()=>({next:n,return:i}),{iterable:o,push:a=>{if(r.contents)return!1;let s=t.shift();return s!==void 0?(s({done:!1,value:a}),!0):(e.push(a),!0)},close:()=>{r.contents=!0,(()=>{for(;;){let s=t.shift();if(s===void 0)return;s({done:!0})}})()}}}function Bw(e){return import(e)}var MM="@anthropic-ai/claude-agent-sdk";function $M(e){return IM()}function a9(e){return{next:()=>e.next(),close:()=>{e.close()},interrupt:()=>e.interrupt(),setModel:t=>e.setModel(t),setPermissionMode:t=>e.setPermissionMode(t),applyFlagSettings:t=>e.applyFlagSettings(t),supportedCommands:()=>e.supportedCommands()}}async function jM(){let e=await Bw(MM);return{query:t=>a9(e.query(t)),getSessionInfo:(t,r)=>e.getSessionInfo(t,r),listSessions:t=>e.listSessions(t),getSessionMessages:(t,r)=>e.getSessionMessages(t,r)}}async function s9(e,t){try{let r=await e();return t(r),{TAG:"Ok",_0:void 0}}catch(r){let n=U(r);return{TAG:"Error",_0:v(k(fr(n),mr),"unknown Claude authentication probe failure")}}}async function GM(e){return await s9(async()=>await(await Bw(MM)).startup({options:{cwd:e,persistSession:!1,settingSources:["user","project","local"],tools:[]},initializeTimeoutMs:15e3}),t=>{t.close()})}var Jw=["codex","claude-code","pi","opencode"];function nl(e){return e}function gh(e){switch(e.TAG){case"SessionStarted":return"session_started";case"TurnStarted":return"turn_started";case"ItemStarted":return"item_started";case"ItemDelta":return"item_delta";case"ItemCompleted":return"item_completed";case"ApprovalRequested":return"approval_requested";case"UsageUpdated":return"usage_updated";case"RateLimitUpdated":return"rate_limit_updated";case"ActivityPulse":return"activity_pulse";case"TurnCompleted":return"turn_completed";case"TurnFailed":return"turn_failed";case"TurnInterrupted":return"turn_interrupted";case"HarnessDied":return"harness_died"}}function Yw(e){switch(e){case"BindingNotObject":return"binding_not_object";case"SessionIdInvalid":return"session_id_invalid";case"LeaseEpochInvalid":return"lease_epoch_invalid";case"NextFrameIndexInvalid":return"next_frame_index_invalid";case"CheckpointConfigMissing":return"checkpoint_config_missing";case"CheckpointConfigInvalid":return"checkpoint_config_invalid";case"SourceSeqInvalid":return"source_seq_invalid"}}function Kw(e){return"adt_stream_v1 dispatch refused: "+Yw(e)+"; the commander refuses to stream unconfigured (no baked fallback thresholds exist by law - plan doc 2.4/MF9)"}function FM(e){switch(e){case"Checkpoint":return"checkpoint";case"Delta":return"delta";case"Terminal":return"terminal"}}function bh(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function il(e){if(e!==void 0&&typeof e=="number"&&e>=1&&Math.trunc(e)===e)return e}function l9(e){let t=bh(e);if(t===void 0)return;let r=il(t.version),n=k(t.thresholds,bh);if(r===void 0||n===void 0)return;let i=il(n.max_bytes),o=il(n.max_deltas),a=il(n.max_interval_ms);if(i!==void 0&&o!==void 0&&a!==void 0)return{version:r,thresholds:{maxBytes:i,maxDeltas:o,maxIntervalMs:a}}}function d9(e){let t=bh(e);if(t===void 0)return{TAG:"ParseRefused",_0:"BindingNotObject"};let r=il(t.session_id);if(r===void 0)return{TAG:"ParseRefused",_0:"SessionIdInvalid"};let n=il(t.lease_epoch);if(n===void 0)return{TAG:"ParseRefused",_0:"LeaseEpochInvalid"};let i=il(t.next_frame_index);if(i===void 0)return{TAG:"ParseRefused",_0:"NextFrameIndexInvalid"};let o=t.checkpoint_config;if(o===void 0)return{TAG:"ParseRefused",_0:"CheckpointConfigMissing"};let a=l9(o);return a!==void 0?{TAG:"Parsed",_0:{sessionId:r,leaseEpoch:n,nextFrameIndex:i,checkpointConfig:a}}:{TAG:"ParseRefused",_0:"CheckpointConfigInvalid"}}function u9(e){return Kn(FM(e.frameKind)+`
|
|
324
|
+
`}function LK(e,t){}function fh(e,t,r,n,i,o){let a=o!==void 0?o:LK;if(e!==void 0)return{TAG:"Ok",_0:{codexBin:e,source:"ExplicitFlag"}};let s=$K(t);if(s!==void 0){let m={};return m.codex_bin_path=s,m.codex_bin_source="bundled",a("codex.binary.resolved",m),{TAG:"Ok",_0:{codexBin:s,source:"Bundled"}}}qK(r);let l=jK(t),d=l!==void 0?n("codex"):void 0,u=zK(d,l),c={};switch(c.codex_bin_path="codex",c.codex_bin_source="path-fallback",c.harness_version_check=NK(u),u.TAG){case"Match":c.harness_version=u.version;break;case"Mismatch":c.path_harness_version=u.pathVersion,c.pinned_harness_version=u.pinnedVersion;break;case"Unverified":c.path_harness_version=Pr(u.pathVersion,null,m=>m),c.pinned_harness_version=Pr(u.pinnedVersion,null,m=>m);break}switch(a("codex.binary.resolved",c),u.TAG){case"Mismatch":let m=u.pinnedVersion,_=u.pathVersion,h=i[Nw];return h===void 0?{TAG:"Error",_0:cM(_,m)}:h!=="1"?{TAG:"Error",_0:cM(_,m)}:(r(DK(_,m)),{TAG:"Ok",_0:{codexBin:"codex",source:"PathFallback"}});case"Match":case"Unverified":return{TAG:"Ok",_0:{codexBin:"codex",source:"PathFallback"}}}}var qw=[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_fresh_session_resume","harness.mid_stream_stall_fresh_session_resume"],["codex.mid_stream_stall_fresh_session_resume_failed","harness.mid_stream_stall_fresh_session_resume_failed"],["codex.mid_stream_stall_fresh_session_resume_flagged","harness.mid_stream_stall_fresh_session_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_demoted_late_upstream_error","job.turn_demoted_late_upstream_error"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.child_thread_event_failed","linzumi.child_thread_event_failed"],["kandan.child_thread_event_skipped_missing_thread_binding","linzumi.child_thread_event_skipped_missing_thread_binding"],["kandan.child_thread_upsert_failed","linzumi.child_thread_upsert_failed"],["kandan.child_thread_upsert_skipped_missing_thread_binding","linzumi.child_thread_upsert_skipped_missing_thread_binding"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],gM=[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],mh=[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],Dw=[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]];function Wc(){return v("1.0.197","0.0.0-unbundled")}function Uw(){return"linzumi "+v("1.0.197","0.0.0-unbundled")}function Id(e,t){let r=e.indexOf(t);if(r!==-1)return r}function Ww(){let e=process.env.LINZUMI_NAMING_DUAL_EMIT;if(e===void 0)return!0;let t=e.trim().toLowerCase();return t!=="0"?t!=="false":!1}function Vw(e){let t={};return e.forEach(r=>{t[r[0]]=r[1]}),t}function UK(e){let t={};return e.forEach(r=>{t[r[1]]=r[0]}),t}var SM=Vw(gM),vM=Vw(mh),WK=Vw(Dw),VK=UK(Dw);function HK(e){return e.endsWith("_canonical")?!0:e.endsWith("_legacy")}function wM(e,t){return t>=32?e:Array.isArray(e)?e.map(r=>wM(r,t+1|0)):e===null?e:typeof e==="object"?kM(e,t):e}function kM(e,t){let r=Object.keys(e),n={};return r.forEach(i=>{let o=e[i];if(o!==void 0){n[i]=wM(o,t+1|0);return}}),r.forEach(i=>{if(HK(i))return;let o=n[i];if(o===void 0)return;let a=SM[i];if(a!==void 0)n[a]=o;else{let c=vM[i];c!==void 0&&(n[c]!==void 0||(n[c]=o))}let s=n[i];if(s===void 0||typeof s!="string")return;let l=WK[s];if(l!==void 0){if(n[i+"_canonical"]!==void 0)return;n[i+"_canonical"]=l;return}let d=VK[s];if(!(d===void 0||n[i+"_legacy"]!==void 0)){n[i+"_legacy"]=d;return}}),n}function ph(e){return Ww()?kM(e,0):e}function TM(e){let t=e.slice();return e.forEach(r=>{let n=SM[r];n!==void 0&&!t.includes(n)&&t.push(n);let i=vM[r];if(i!==void 0&&!t.includes(i)){t.push(i);return}}),t}var Md="<SENSITIVE_DATA>",ZK=TM(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"]),BK=["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"],JK=new RegExp("^(authorization|cookie|set-cookie|password)$","i"),KK=new RegExp("(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$","i"),QK=new RegExp("\\beyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b","g");function YK(e){return e!==void 0?JK.test(e)?!0:KK.test(e):!1}function xM(e){let t={contents:!1};return JT(e).forEach(r=>{if(ZK.includes(r.toLowerCase())){e.set(r,Md),t.contents=!0;return}}),t.contents}function XK(e){let t=Id(e,"?"),r=Id(e,"#");if(t===void 0||r!==void 0&&r<t)return e;let n=e.slice(0,t),i=r!==void 0?e.slice(t+1|0,r):e.slice(t+1|0),o=r!==void 0?e.slice(r):"",a=new URLSearchParams(i);return xM(a)?n+"?"+a.toString()+o:e}function e9(e){let t=Mi(e);if(t===void 0)return XK(e);let r=ge(t);return xM(r.searchParams),r.toString()}function da(e){return e9(e).replace(QK,Md)}function t9(e){let t=Id(e,"=");return t!==void 0?[e.slice(0,t),e.slice(t+1|0)]:[e,void 0]}function Zw(e,t){if(YK(t))return Md;if(Array.isArray(e))return t==="args"?r9(e):e.map(r=>Zw(r,void 0));if(e===null)return e;switch(typeof e){case"string":return da(e);case"object":return AM(e);default:return e}}function r9(e){let t={contents:!1};return e.map(r=>{if(typeof r=="string"){if(t.contents)return t.contents=!1,Md;let n=t9(r),i=n[0];return BK.includes(i)?n[1]!==void 0?i+"="+Md:(t.contents=!0,r):da(r)}return t.contents=!1,Zw(r,void 0)})}function AM(e){let t=e.name,r=typeof t=="string"?t.toLowerCase():void 0,n;if(r!==void 0)switch(r){case"authorization":case"cookie":case"set-cookie":n=!0;break;default:n=!1}else n=!1;let i={};return Object.entries(e).forEach(o=>{let a=o[0];if(a!=="runner_console"){i[a]=n&&a==="value"?Md:Zw(o[1],a);return}}),i}var $d=AM;import*as wi from"node:os";import*as _o from"node:path";function _h(e){return e!==void 0?ge(e):null}import*as pT from"node:crypto";function CM(e){return"local_runner:"+e}var n9="kandan-local-codex-runner",i9="rescript";function EM(e){let t={};t.clientName=n9,t.clientId=e.clientId;let r=e.machineFingerprint;t.machineFingerprint=r!==void 0?r:null,Object.entries(bA(e.machineFingerprintV2)).forEach(a=>{t[a[0]]=a[1]}),t.runnerPid=e.runnerPid,t.version=e.version,t.hostname=e.hostname,t.cwd=e.cwd;let n=e.workspace;t.workspace=n!==void 0?n:null;let i=e.channel;t.channel=i!==void 0?i:null,t.capabilities=e.capabilities;let o=e.generationOverlapEpoch;if(o!==void 0){let a={};a.epoch=o,a.overlap=!0,t.generation=a}return t.commander_impl=i9,t}function PM(e,t,r){let n={};return n.last_seq=r,t!==void 0&&(n.runner_id=e,n.thread_id=t),n}function An(e,t){return e.catch(r=>t(U(r)))}function IM(){let e=[],t=[],r={contents:!1},n=()=>{let a=e.shift();return a!==void 0?Promise.resolve({done:!1,value:a}):r.contents?Promise.resolve({done:!0}):new Promise((s,l)=>{t.push(s)})},i=()=>(r.contents=!0,Promise.resolve({done:!0})),o={};return o[Symbol.asyncIterator]=()=>({next:n,return:i}),{iterable:o,push:a=>{if(r.contents)return!1;let s=t.shift();return s!==void 0?(s({done:!1,value:a}),!0):(e.push(a),!0)},close:()=>{r.contents=!0,(()=>{for(;;){let s=t.shift();if(s===void 0)return;s({done:!0})}})()}}}function Bw(e){return import(e)}var MM="@anthropic-ai/claude-agent-sdk";function $M(e){return IM()}function a9(e){return{next:()=>e.next(),close:()=>{e.close()},interrupt:()=>e.interrupt(),setModel:t=>e.setModel(t),setPermissionMode:t=>e.setPermissionMode(t),applyFlagSettings:t=>e.applyFlagSettings(t),supportedCommands:()=>e.supportedCommands()}}async function jM(){let e=await Bw(MM);return{query:t=>a9(e.query(t)),getSessionInfo:(t,r)=>e.getSessionInfo(t,r),listSessions:t=>e.listSessions(t),getSessionMessages:(t,r)=>e.getSessionMessages(t,r)}}async function s9(e,t){try{let r=await e();return t(r),{TAG:"Ok",_0:void 0}}catch(r){let n=U(r);return{TAG:"Error",_0:v(k(fr(n),mr),"unknown Claude authentication probe failure")}}}async function GM(e){return await s9(async()=>await(await Bw(MM)).startup({options:{cwd:e,persistSession:!1,settingSources:["user","project","local"],tools:[]},initializeTimeoutMs:15e3}),t=>{t.close()})}var Jw=["codex","claude-code","pi","opencode"];function nl(e){return e}function gh(e){switch(e.TAG){case"SessionStarted":return"session_started";case"TurnStarted":return"turn_started";case"ItemStarted":return"item_started";case"ItemDelta":return"item_delta";case"ItemCompleted":return"item_completed";case"ApprovalRequested":return"approval_requested";case"UsageUpdated":return"usage_updated";case"RateLimitUpdated":return"rate_limit_updated";case"ActivityPulse":return"activity_pulse";case"TurnCompleted":return"turn_completed";case"TurnFailed":return"turn_failed";case"TurnInterrupted":return"turn_interrupted";case"HarnessDied":return"harness_died"}}function Yw(e){switch(e){case"BindingNotObject":return"binding_not_object";case"SessionIdInvalid":return"session_id_invalid";case"LeaseEpochInvalid":return"lease_epoch_invalid";case"NextFrameIndexInvalid":return"next_frame_index_invalid";case"CheckpointConfigMissing":return"checkpoint_config_missing";case"CheckpointConfigInvalid":return"checkpoint_config_invalid";case"SourceSeqInvalid":return"source_seq_invalid"}}function Kw(e){return"adt_stream_v1 dispatch refused: "+Yw(e)+"; the commander refuses to stream unconfigured (no baked fallback thresholds exist by law - plan doc 2.4/MF9)"}function FM(e){switch(e){case"Checkpoint":return"checkpoint";case"Delta":return"delta";case"Terminal":return"terminal"}}function bh(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function il(e){if(e!==void 0&&typeof e=="number"&&e>=1&&Math.trunc(e)===e)return e}function l9(e){let t=bh(e);if(t===void 0)return;let r=il(t.version),n=k(t.thresholds,bh);if(r===void 0||n===void 0)return;let i=il(n.max_bytes),o=il(n.max_deltas),a=il(n.max_interval_ms);if(i!==void 0&&o!==void 0&&a!==void 0)return{version:r,thresholds:{maxBytes:i,maxDeltas:o,maxIntervalMs:a}}}function d9(e){let t=bh(e);if(t===void 0)return{TAG:"ParseRefused",_0:"BindingNotObject"};let r=il(t.session_id);if(r===void 0)return{TAG:"ParseRefused",_0:"SessionIdInvalid"};let n=il(t.lease_epoch);if(n===void 0)return{TAG:"ParseRefused",_0:"LeaseEpochInvalid"};let i=il(t.next_frame_index);if(i===void 0)return{TAG:"ParseRefused",_0:"NextFrameIndexInvalid"};let o=t.checkpoint_config;if(o===void 0)return{TAG:"ParseRefused",_0:"CheckpointConfigMissing"};let a=l9(o);return a!==void 0?{TAG:"Parsed",_0:{sessionId:r,leaseEpoch:n,nextFrameIndex:i,checkpointConfig:a}}:{TAG:"ParseRefused",_0:"CheckpointConfigInvalid"}}function u9(e){return Kn(FM(e.frameKind)+`
|
|
325
325
|
`+e.body).slice(0,16)}function c9(e){let t={};return t.session_id=e.sessionId,t.lease_epoch=e.leaseEpoch,t.frame_index=e.frameIndex,t.frame_kind=FM(e.frameKind),t.body=e.body,t.byte_len=e.byteLen,t}function qM(e){let t=c9(e);return t.digest=u9(e),t}function Xw(e){switch(e){case"StaleEpoch":return"stale_epoch";case"PostSettle":return"post_settle";case"PostTerminal":return"post_terminal";case"FrameIndexReuse":return"frame_index_reuse";case"UnknownRejection":return"unknown"}}function DM(e){if(e===void 0||typeof e!="string")return"UnknownRejection";switch(e){case"frame_index_reuse":return"FrameIndexReuse";case"post_settle":return"PostSettle";case"post_terminal":return"PostTerminal";case"stale_epoch":return"StaleEpoch";default:return"UnknownRejection"}}function f9(e,t){return{binding:e,cumulative:"",pendingBody:"",pendingBytes:0,pendingDeltas:0,lastFrameAtMs:t,nextFrameIndex:e.nextFrameIndex,emittedFrameCount:0,checkpointPending:!1,terminalEmitted:!1,fenced:!1}}function e0(e,t,r){let n;switch(t){case"Delta":n=e.pendingBody;break;case"Checkpoint":case"Terminal":n=e.cumulative;break}let i=e.binding.sessionId,o=e.binding.leaseEpoch,a=e.nextFrameIndex,s=Buffer.byteLength(n,"utf8"),l={sessionId:i,leaseEpoch:o,frameIndex:a,frameKind:t,body:n,byteLen:s};switch(e.nextFrameIndex=e.nextFrameIndex+1,e.emittedFrameCount=e.emittedFrameCount+1|0,e.pendingBody="",e.pendingBytes=0,e.pendingDeltas=0,e.lastFrameAtMs=r,t){case"Delta":break;case"Checkpoint":case"Terminal":e.checkpointPending=!1;break}return l}function m9(e,t){let r=e.binding.checkpointConfig.thresholds;return e.pendingDeltas>0?e.pendingBytes>=r.maxBytes||e.pendingDeltas>=r.maxDeltas?!0:t-e.lastFrameAtMs>=r.maxIntervalMs:!1}function LM(e){let t=e.emittedFrameCount,r=e.checkpointPending;return t!==0&&!r?"Delta":"Checkpoint"}function p9(e,t,r){if(!(e.fenced||e.terminalEmitted||t===""))return e.cumulative=e.cumulative+t,e.pendingBody=e.pendingBody+t,e.pendingBytes=e.pendingBytes+Buffer.byteLength(t,"utf8")|0,e.pendingDeltas=e.pendingDeltas+1|0,m9(e,r)?e0(e,LM(e),r):void 0}function h9(e,t){if(!(e.fenced||e.terminalEmitted||e.pendingBody===""))return e0(e,LM(e),t)}function _9(e,t){if(!(e.fenced||e.terminalEmitted))return e.terminalEmitted=!0,e0(e,"Terminal",t)}function g9(e){if(!(e.fenced||e.terminalEmitted)){e.cumulative="",e.pendingBody="",e.pendingBytes=0,e.pendingDeltas=0,e.checkpointPending=!0;return}}function UM(e){e.fenced=!0}function y9(e){switch(e){case"failed":case"ignored":case"interrupted":case"processed":return!0;default:return!1}}function WM(e,t,r){if(e===void 0||e===null)return"Absent";let n=d9(e);if(n.TAG==="Parsed"){let o=n._0;if(t===void 0)return{TAG:"Refused",reason:"SourceSeqInvalid",message:Kw("SourceSeqInvalid")};if(!(t>=1&&Math.trunc(t)===t))return{TAG:"Refused",reason:"SourceSeqInvalid",message:Kw("SourceSeqInvalid")};let a={};return a.session_id=o.sessionId,a.lease_epoch=o.leaseEpoch,a.checkpoint_config_version=o.checkpointConfig.version,{TAG:"Accepted",session:{binding:o,sourceSeq:t,emitter:f9(o,r),trackedItemKey:void 0,trackedItemRank:0,itemFirstSeenOrdinals:{},lastBody:"",done:!1},ackPayload:a}}let i=n._0;return{TAG:"Refused",reason:i,message:Kw(i)}}function Vc(e,t){let r=e[t];if(typeof r=="string")return r}function NM(e,t){let r=e[t];if(r!==void 0&&typeof r=="number"&&Math.trunc(r)===r)return r}function b9(e){return k(k(e.structured,bh),r=>Vc(r,"phase"))==="final_answer"?1:0}function VM(e,t,r,n,i){if(e.done||e.emitter.fenced)return[];if(t===i.messageState){let p=NM(r,"seq"),g=Vc(r,"status");if(p===void 0)return[];if(g===void 0)return[];if(!(p===e.sourceSeq&&y9(g)))return[];let b=h9(e.emitter,n),y=_9(e.emitter,n);e.done=!0;let S=[];return b!==void 0&&S.push(b),y!==void 0&&S.push(y),S}let a=(t===i.postStreamedRow||t===i.streamSnapshot||t===i.finalizeRow||t===i.postCompletedRow)&&me(Vc(r,"stream_kind"),"assistant")&&me(NM(r,"source_seq"),e.sourceSeq),s=Vc(r,"item_key");if(!a)return[];if(s===void 0)return[];let l=b9(r),d=e.itemFirstSeenOrdinals[s],u;if(d!==void 0)u=d;else{let p=Object.keys(e.itemFirstSeenOrdinals).length;e.itemFirstSeenOrdinals[s]=p,u=p}let c=e.trackedItemKey,m;if(c!==void 0)if(c===s)e.trackedItemRank=l,m=!0;else{let p=v(e.itemFirstSeenOrdinals[c],-1);l>e.trackedItemRank||l===e.trackedItemRank&&u>p?(e.trackedItemKey=s,e.trackedItemRank=l,e.lastBody="",g9(e.emitter),m=!0):m=!1}else e.trackedItemKey=s,e.trackedItemRank=l,m=!0;if(!m)return[];let _=v(Vc(r,"body"),""),h=_.startsWith(e.lastBody)?_.slice(e.lastBody.length,_.length):_;e.lastBody=_;let f=p9(e.emitter,h,n);return f!==void 0?[f]:[]}var Hc={},yh={},Qw=[];function HM(e,t){Hc[e]=t}function t0(e){return Hc[e]}function ZM(e,t){let r=Hc[e];if(r!==void 0&&r.binding.sessionId===t.binding.sessionId&&r.binding.leaseEpoch===t.binding.leaseEpoch)return Ir(Hc,e)}function BM(e){let t=e.toString();if(yh[t]===void 0)for(yh[t]=!0,Qw.push(t);Qw.length>256;){let n=Qw.shift();n!==void 0&&Ir(yh,n)}}function r0(e){return v(yh[e.toString()],!1)}function JM(){return Object.entries(Hc).filter(e=>{let t=e[1];return t.done?!1:!r0(t.binding.sessionId)})}function KM(e,t){let r={};return r.session_id=e.binding.sessionId,r.lease_epoch=e.binding.leaseEpoch,r.harness_alive=t,r}var QM="adt_frame",YM="adt_binding_ack",XM="adt_stall_heartbeat",n0="adt.frame";function S9(e){switch(e){case"SocketOpen":return"open";case"SocketMessage":return"message";case"SocketClose":return"close";case"SocketError":return"error"}}function v9(e){let t=e.data,r;r=t==null||typeof t!="string"?void 0:t;let n=e.code,i;i=n==null||typeof n!="number"||(n|0)!==n?void 0:n|0;let o=e.reason,a;return a=o==null||typeof o!="string"?void 0:o,{data:r,code:i,reason:a}}function w9(e){return{readyState:()=>e.readyState,send:t=>{e.send(t)},close:()=>{e.close()},on:(t,r)=>{e.addEventListener(S9(t),n=>r(v9(n)),{})}}}function Sh(e,t){return w9(new WebSocket(e,t))}var t$=0,ol=1;var i0="file",o0=["mcp_oauth_credentials_store","cli_auth_credentials_store"],k9=o0.flatMap(e=>["-c",e+'="'+i0+'"']),T9=["-c","features.apps=false"];function mo(e){return JSON.stringify(e)}function x9(e){let t=(r,n)=>r!==void 0?Object.entries(r).flatMap(i=>["-c","model_providers."+e.id+"."+n+"."+i[0]+"="+mo(i[1])]):[];return[["-c","model_providers."+e.id+".name="+mo(e.name),"-c","model_providers."+e.id+".base_url="+mo(e.baseUrl),"-c","model_providers."+e.id+".env_key="+mo(e.envKey),"-c","model_providers."+e.id+".wire_api="+mo(e.wireApi)],t(e.httpHeaders,"http_headers"),t(e.envHttpHeaders,"env_http_headers"),["-c","model_provider="+mo(e.id)]].flat()}var A9=["-c","model_providers.openai-linzumi.name="+mo("OpenAI"),"-c","model_providers.openai-linzumi.wire_api="+mo("responses"),"-c","model_providers.openai-linzumi.requires_openai_auth=true","-c","model_providers.openai-linzumi.supports_websockets=true"];function O9(e){let t=e.model,r=e.reasoningEffort,n=e.modelProvider;return[T9,k9,t!==void 0?["-c","model="+mo(t)]:[],r!==void 0?["-c","model_reasoning_effort="+mo(r)]:[],e.fast?["-c","service_tier="+mo("fast")]:[],e.mcpConfigArgs.flat(),n!==void 0?x9(n):A9].flat()}function n$(e,t){return[["app-server"],O9(t),["--listen",e]].flat()}var C9=["LINZUMI_MCP_ACCESS_TOKEN","LINZUMI_MCP_OWNER_USERNAME"];function i$(e,t,r){let n=r?Object.fromEntries(Object.entries(e)):{};return C9.forEach(i=>Ir(n,i)),t.forEach(i=>{let o=i[1],a=i[0];if(o!==void 0){n[a]=o;return}else return Ir(n,a)}),n}var o$=["ignore","pipe","pipe"];function a$(e){let t=e.length;return t>12e3?e.slice(t-12e3|0,t):e}function s$(e,t,r){return r<3&&e.includes("codex app-server exited before readyz")&&t.includes("EADDRINUSE")?t.includes("listen"):!1}function l$(e){let t=Mi(e);if(t===void 0)return;let r=ge(t),i=r.protocol==="wss:"?"https:":"http:";return r.protocol=i,r.pathname="/readyz",r.search="",r.hash="",r.toString()}var E9="kandan-local-codex-runner",P9="0.0.1";function d$(){return Object.fromEntries([["clientInfo",Object.fromEntries([["name",E9],["version",P9]])],["capabilities",Object.fromEntries([["experimentalApi",!0]])]])}var R9=new RegExp("\\bsession\\b.+\\bis archived\\b","i");function u$(e){return R9.test(e)}var I9=new RegExp("^thread not found(?:\\s*:|\\b)","i");function c$(e){return I9.test(e.trim())}var f$=2e3;function M9(e){try{e.unref();return}catch{return}}var m$="codex app-server websocket closed",$9="codex app-server websocket is not open";function j9(e){let t=e.method;if(typeof t=="string")return t}function a0(e){let t=e.error;if(t===void 0)return{TAG:"ResultReply",_0:v(e.result,null)};if(typeof t!="object"||t===null||Array.isArray(t))return{TAG:"ErrorReply",code:0,message:JSON.stringify(t)};let r=t.code,n=r!==void 0&&typeof r=="number"?r:0,i=t.message;return{TAG:"ErrorReply",code:n,message:typeof i=="string"?i:""}}function wh(e,t,r,n){let i=JSON.stringify(n);t(r,i);try{return e.socket.send(i),{TAG:"Ok",_0:void 0}}catch(o){let a=U(o);return{TAG:"Error",_0:Te(a).message}}}function g$(e,t,r){try{return t(r)}catch(n){let i=U(n);return e("codex.notification_callback_failed",Object.fromEntries([["purpose","codex.app_server"],["method",r.method],["message",Te(i).message]]))}}function p$(e,t,r){try{return t(r)}catch(n){let i=U(n);return e("codex.close_callback_failed",Object.fromEntries([["purpose","codex.app_server"],["message",Te(i).message]]))}}function G9(e,t){let r;if(t.TAG==="Ok")r=[["jsonrpc","2.0"],["id",e],["result",t._0]];else{let n=t._0;r=[["jsonrpc","2.0"],["id",e],["error",Object.fromEntries([["code",n[0]],["message",n[1]]])]]}return Object.fromEntries(r)}async function z9(e,t,r,n){let i={TAG:"Error",_0:[-32601,"unhandled Codex app-server request: "+n.method]},o=e.requestCallbacks.slice(),a,s=0;for(;Fn(a)&&s<o.length;){let d=o[s];if(d!==void 0){let u=0,c;try{c=await d(n),u=1}catch(m){let _=U(m);a={TAG:"Error",_0:[-32e3,Te(_).message]}}u===1&&c!==void 0&&(a={TAG:"Ok",_0:c})}s=s+1|0}let l=v(a,i);wh(t,r,"outgoing",G9(n.id,l))}function N9(e,t,r,n,i){let o;try{o=JSON.parse(i)}catch(_){let h=U(_);r("codex.app_server_frame_malformed",Object.fromEntries([["purpose","codex.app_server"],["message",Te(h).message],["payload",i.slice(0,512)],["payloadChars",i.length]])),o=void 0}let a;if(o!==void 0){let _=0;typeof o=="object"&&o!==null&&!Array.isArray(o)?a=o:_=1,_===1&&(r("codex.app_server_frame_malformed",Object.fromEntries([["purpose","codex.app_server"],["message","codex app-server sent non-object JSON-RPC message"],["payload",i.slice(0,512)],["payloadChars",i.length]])),a=void 0)}else a=void 0;if(a===void 0)return;let s=Yt(a.id),l=s&&(Yt(a.result)||Yt(a.error)),d=j9(a);if(l){let _=v(a.id,null),h=JSON.stringify(_),f=e.pending[h];return f!==void 0?(Ir(e.pending,h),f.resolvePending({TAG:"Ok",_0:a0(a)})):void 0}if(s)if(d!==void 0){An(z9(e,t,n,{id:v(a.id,null),method:d,params:a.params}),_=>Promise.resolve());return}else return;if(d===void 0)return;let u=a.params,c={method:d,params:u};e.notificationCallbacks.length!==0?e.notificationCallbacks.forEach(_=>g$(r,_,c)):e.pendingNotifications.push(c)}function F9(e,t,r){return Object.fromEntries(r!==void 0?[["jsonrpc","2.0"],["id",e],["method",t],["params",r]]:[["jsonrpc","2.0"],["id",e],["method",t]])}function h$(e,t){return Object.fromEntries(t!==void 0?[["jsonrpc","2.0"],["method",e],["params",t]]:[["jsonrpc","2.0"],["method",e]])}function _$(e,t,r,n,i,o){return t.socket.readyState()===ol?new Promise((a,s)=>{e.pending[JSON.stringify(n)]={resolvePending:a};let l=wh(t,r,"request",F9(n,i,o));l.TAG!=="Ok"&&(Ir(e.pending,JSON.stringify(n)),a({TAG:"Error",_0:l._0}))}):Promise.resolve({TAG:"Error",_0:$9})}async function kh(e,t,r,n){let i=t!==void 0?t:u=>({socket:Sh(u,[]),ping:void 0}),o=r!==void 0?r:2e3,a=n!==void 0?n:()=>Date.now(),s=a()+o,l,d="websocket open failed";for(;Fn(l);){let u;try{u={TAG:"Ok",_0:i(e)}}catch(c){let m=U(c);u={TAG:"Error",_0:Te(m).message}}if(u.TAG==="Ok"){let c=u._0;if(await new Promise((m,_)=>{c.socket.on("SocketOpen",h=>m(!0)),c.socket.on("SocketError",h=>m(!1))}))l={TAG:"Ok",_0:c};else{try{c.socket.close()}catch{}a()>s&&(l={TAG:"Error",_0:d})}}else d=u._0,a()>s&&(l={TAG:"Error",_0:d})}return v(l,{TAG:"Error",_0:d})}async function Th(e,t){let r={pending:{},notificationCallbacks:[],requestCallbacks:[],pendingNotifications:[],closeCallbacks:[],nextId:1,closeError:void 0},n=t.audit,i=t.onWire,o=setInterval(()=>{let d=e.ping;if(d!==void 0&&e.socket.readyState()===ol)try{return d()}catch{return}},t.keepaliveIntervalMs);M9(o);let a=d=>{clearInterval(o);let u=Object.entries(r.pending);if(Object.entries(r.pending).forEach(_=>Ir(r.pending,_[0])),u.forEach(_=>_[1].resolvePending({TAG:"Error",_0:d})),r.closeError!==void 0)return;r.closeError=d;let m=r.closeCallbacks.slice();r.closeCallbacks.splice(0,r.closeCallbacks.length),m.forEach(_=>p$(n,_,d))};e.socket.on("SocketClose",d=>a(m$)),e.socket.on("SocketError",d=>a(m$)),e.socket.on("SocketMessage",d=>{let u=d.data;if(u!==void 0)return i("incoming",u),N9(r,e,n,i,u)});let s=await _$(r,e,i,"initialize","initialize",d$());if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let l=s._0;return l.TAG!=="ResultReply"?{TAG:"Error",_0:"codex initialize failed: "+l.message}:(wh(e,i,"outgoing",h$("initialized",void 0)),{TAG:"Ok",_0:{request:(d,u)=>{let c=r.nextId;return r.nextId=r.nextId+1|0,_$(r,e,i,c,d,u)},notify:(d,u)=>{wh(e,i,"outgoing",h$(d,u))},onNotification:d=>{r.notificationCallbacks.push(d);let u=r.pendingNotifications.slice();r.pendingNotifications.splice(0,r.pendingNotifications.length),u.forEach(c=>g$(n,d,c))},onRequest:d=>{r.requestCallbacks.push(d)},onClose:d=>{let u=r.closeError;if(u!==void 0)return p$(n,d,u);r.closeCallbacks.push(d)},isClosed:()=>Yt(r.closeError),close:()=>{clearInterval(o);try{return e.socket.close()}catch{return}}}})}import*as Nd from"node:fs";function zd(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}function $o(e){if(e!==void 0&&typeof e=="string"&&e.trim()!=="")return e.trim()}function Gd(e){if(e!==void 0&&typeof e=="number"&&Lt(e))return e}function y$(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}var b$="linzumi_thread_codex_worker_ready",S$="linzumi_thread_codex_worker_session_closed",v$="linzumi_thread_codex_worker_request",w$="linzumi_thread_codex_worker_notify",u0="linzumi_thread_codex_worker_response",k$="linzumi_thread_codex_worker_notification",T$="linzumi_thread_codex_worker_server_request",x$="linzumi_thread_codex_worker_server_request_response";function A$(e,t){let r={};return r.type=b$,r.kandanThreadId=e,r.commanderManagedPorts=t.map(n=>{let i={};i.port=n.port;let o=n.pid;o!==void 0&&(i.pid=o);let a=n.processName;a!==void 0&&(i.processName=a);let s=n.processIconKey;s!==void 0&&(i.processIconKey=s);let l=n.agentProvider;return l!==void 0&&(i.agentProvider=l),i}),r}function O$(e,t){let r={};return r.type=S$,r.kandanThreadId=e,r.reason=t,r}function q9(e,t,r){let n={};return n.type=v$,n.id=e,n.method=t,r!==void 0&&(n.params=r),n}function D9(e,t){let r={};return r.type=w$,r.method=e,t!==void 0&&(r.params=t),r}function L9(e,t){let r={};return r.type=u0,r.id=e,r.response=t,r}function U9(e,t){let r={};return r.type=u0,r.id=e,r.error=t,r}function W9(e){let t={};return t.type=k$,t.notification=e,t}function V9(e,t){let r={};return r.type=T$,r.id=e,r.request=t,r}function l0(e,t,r){let n={};return n.type=x$,n.id=e,t!==void 0&&(n.result=t),r!==void 0&&(n.error=r),n}function H9(e){if(e===void 0||typeof e!="object"||e===null||Array.isArray(e)||e.id===void 0)return;let r=e.result,n=e.error;if(r!==void 0||n!==void 0)return e}function Z9(e){if(e===void 0||typeof e!="object"||e===null||Array.isArray(e))return;let t=e.id,r=e.method;if(!(t!==void 0||typeof r!="string"))return e}function B9(e){if(e===void 0||typeof e!="object"||e===null||Array.isArray(e))return;let t=e.id,r=e.method;if(t!==void 0&&typeof r=="string")return e}function J9(e){let t=zd(e);if(t===void 0)return;let r=t.type;if(r===void 0||typeof r!="string")return;if(r===v$){let i=Gd(t.id),o=$o(t.method);return i!==void 0&&o!==void 0?{TAG:"ParentRequest",id:i,method_:o,params:y$(t.params)}:void 0}if(r===w$){let i=$o(t.method);return i!==void 0?{TAG:"ParentNotify",method_:i,params:y$(t.params)}:void 0}if(r!==x$)return;let n=Gd(t.id);if(n!==void 0)return{TAG:"ParentServerRequestResponse",id:n,result:t.result,error:$o(t.error)}}function K9(e){let t=zd(e);if(t===void 0)return;let r=t.type;if(r===void 0||typeof r!="string")return;if(r===u0){let o=Gd(t.id);return o!==void 0?{TAG:"ChildResponse",id:o,response:H9(t.response),error:$o(t.error)}:void 0}if(r===k$){let o=Z9(t.notification);return o!==void 0?{TAG:"ChildNotification",notification:o}:void 0}if(r!==T$)return;let n=Gd(t.id),i=B9(t.request);if(n!==void 0&&i!==void 0)return{TAG:"ChildServerRequest",id:n,request:i}}function C$(e){let t=zd(e);if(t===void 0)return;let r=t.type;if(typeof r=="string"&&r===S$)return[v($o(t.kandanThreadId),""),v($o(t.reason),"")]}var Q9="thread Codex worker reported invalid ready payload";function Y9(e){let t=$o(e);if(t!==void 0)switch(t){case"claude-code":return"claude-code";case"codex":return"codex";default:return}}function X9(e){return e!==void 0?Array.isArray(e)?Ye(e,t=>{let r=zd(t);if(r===void 0)return;let n=Gd(r.port);if(n!==void 0&&n>=1&&n<=65535)return{port:n,pid:Gd(r.pid),processName:$o(r.processName),processIconKey:$o(r.processIconKey),agentProvider:Y9(r.agentProvider)}}):[]:[]}function E$(e,t){let r=zd(e);if(r===void 0)return{TAG:"Ok",_0:void 0};let n=r.type;if(n===void 0)return{TAG:"Ok",_0:void 0};if(typeof n!="string")return{TAG:"Ok",_0:void 0};if(n!==b$)return{TAG:"Ok",_0:void 0};let i=$o(r.kandanThreadId);return i!==void 0&&i===t?{TAG:"Ok",_0:{kandanThreadId:i,commanderManagedPorts:X9(r.commanderManagedPorts)}}:{TAG:"Error",_0:Q9}}function P$(e,t){}var R$="linzumi.thread_runner",e6="thread Codex worker requires a codex client with onRequest",d0="thread Codex worker IPC channel closed";function I$(e,t,r){let n=r!==void 0?r:P$,i=e.onRequest;if(i===void 0)return{TAG:"Error",_0:e6};let o=new Map,a={contents:1},s={contents:!1},l=u=>{if(s.contents)return;s.contents=!0;let c={};c.purpose=R$,c.reason=u,n("thread_codex_worker.ipc_send_dropped",c)},d=u=>{let c=t.send,m=t.isConnected();if(c===void 0||!m)return l("ipc_channel_closed");let _=c(u);if(_.TAG!=="Ok")return l(_._0)};return t.onMessage(u=>{let c=J9(u);if(c!==void 0)switch(c.TAG){case"ParentRequest":let m=c.id;e.request(c.method_,c.params).then(p=>p.TAG==="Ok"?d(L9(m,p._0)):d(U9(m,p._0)));return;case"ParentNotify":return e.notify(c.method_,c.params);case"ParentServerRequestResponse":let _=c.error,h=c.id,f=o.get(h);return f!==void 0?(o.delete(h),f(_!==void 0?{TAG:"Error",_0:_}:{TAG:"Ok",_0:c.result})):void 0}}),e.onNotification(u=>d(W9(u))),i(u=>new Promise((c,m)=>{let _=a.contents;a.contents=_+1,o.set(_,c),d(V9(_,u))})),t.onceDisconnect(()=>{o.forEach(u=>u({TAG:"Error",_0:d0})),o.clear()}),{TAG:"Ok",_0:void 0}}var t6="thread Codex worker IPC client is closed",r6="thread Codex worker response missing body",n6="thread Codex worker IPC client closed";async function i6(e,t,r,n,i,o){let a=d=>{let u=e(d);if(u.TAG==="Ok")return;let c={};c.purpose=R$,c.requestMethod=n,c.message=u._0,o("thread_codex_worker.ipc_response_dropped",c)},s=!1,l=0;for(;!s&&l<i.length;){let d=i[l];if(d!==void 0){let u=await d(r);if(u.TAG==="Ok"){let c=u._0;c!==void 0&&(s=!0,a(l0(t,c,void 0)))}else s=!0,a(l0(t,void 0,u._0))}l=l+1|0}if(!s)return a(l0(t,void 0,"unhandled Codex app-server request: "+n))}function o6(e){let t=zd(e);if(t===void 0)return"";let r=t.method;return typeof r=="string"?r:""}function M$(e,t){let r=t!==void 0?t:P$,n=new Map,i=[],o=[],a=[],s={contents:1},l={contents:!1},d=p=>{n.forEach(g=>g({TAG:"Error",_0:p})),n.clear()},u=p=>{if(l.contents)return{TAG:"Error",_0:t6};let g=e.send,b=e.isConnected();return g!==void 0&&b?g(p):{TAG:"Error",_0:d0}},c=p=>{let g=K9(p);if(g!==void 0)switch(g.TAG){case"ChildResponse":let b=g.error,y=g.response,S=g.id,w=n.get(S);return w!==void 0?(n.delete(S),w(b!==void 0?{TAG:"Error",_0:b}:y!==void 0?{TAG:"Ok",_0:y}:{TAG:"Error",_0:r6})):void 0;case"ChildNotification":let C=g.notification;i.length!==0?i.forEach(j=>j(C)):a.push(C);return;case"ChildServerRequest":let G=g.request;i6(u,g.id,G,o6(G),o,r);return}},m=e.onMessage(c),_=()=>{l.contents=!0,d(d0)},h=e.onceExit(_),f=e.onceDisconnect(_);return{request:(p,g)=>new Promise((b,y)=>{let S=s.contents;s.contents=S+1,n.set(S,b);let w=u(q9(S,p,g));w.TAG!=="Ok"&&(n.delete(S),b({TAG:"Error",_0:w._0}))}),notify:(p,g)=>u(D9(p,g)),onNotification:p=>{i.push(p);let g=a.slice();a.splice(0,a.length),g.forEach(b=>p(b))},onRequest:p=>{o.push(p)},isClosed:()=>l.contents?!0:!e.isConnected(),close:()=>{l.contents=!0,m(),h(),f(),d(n6)}}}import*as Mh from"node:child_process";import*as j$ from"node:os";import*as G$ from"node:path";function Bi(e){let t=parseFloat(e);if(!Number.isNaN(t))return t}function z$(){return G$.join(j$.homedir(),".linzumi","protected-dev-listeners")}var a6=new RegExp("^(\\d+)\\s+(\\d+)$");function s6(e){return Ye(e.split(`
|
|
326
326
|
`),t=>{let r=a6.exec(t.trim());if(r==null)return;let n=r.slice(1);if(n.length!==2)return;let i=n[0];if(i===void 0)return;let o=n[1];if(o===void 0)return;let a=Bi(i),s=Bi(o);if(a!==void 0&&s!==void 0)return{pid:a,pgid:s}})}function l6(e){let t=ya("ps",["-axo","pid=,pgid="],5e3,16e6);if(t.TAG==="Ok")return s6(t._0).filter(r=>r.pgid===e).map(r=>r.pid)}function xh(e,t,r,n,i){let o=n!==void 0?n:l6,a;if(i.size>0){let l=o(e);if(l!==void 0){let d=l.filter(u=>i.has(u));if(d.length!==0){let u=[],c=new Set(l.filter(m=>!i.has(m)));c.add(e),Array.from(c).forEach(m=>{let _=r(m|0,t);if(_.TAG==="Ok")return;let h=_._0;if(!me(h.code,"ESRCH")){u.push({pid:m,code:h.code,message:h.message});return}}),a={mode:"IndividualSignals",sparedPids:d,failures:u,groupSignalError:void 0}}else a=void 0}else a=void 0}else a=void 0;if(a!==void 0)return a;let s=r(-e|0,t);return s.TAG==="Ok"?{mode:"GroupSignal",sparedPids:[],failures:[],groupSignalError:void 0}:{mode:"GroupSignal",sparedPids:[],failures:[],groupSignalError:s._0}}var q$={contents:(e,t)=>{}};var c0="SIGKILL",al={children:new Set,handlersInstalled:!1,removeHandlers:void 0};function Bc(e,t,r,n,i){let o=e.pid;q$.contents("process.reap_failed",Object.fromEntries([["purpose",e.kind],["pid",o!==void 0?o:null],["ownProcessGroup",e.ownProcessGroup],["reason",t],["stage",r],["code",n!==void 0?n:null],["message",i]]))}function d6(e,t,r,n){let i;try{e.stop(),i={TAG:"Ok",_0:void 0}}catch(l){i={TAG:"Error",_0:U(l)}}if(i.TAG!=="Ok"){let l=Te(i._0);Bc(e,n,"stop",l.code,l.message)}let o=e.pid;if(o===void 0)return;if(e.ownProcessGroup){let l=xh(o,c0,t,void 0,r);l.sparedPids.length!==0&&q$.contents("process.reap_spared_listeners",Object.fromEntries([["purpose",e.kind],["pid",o],["reason",n],["sparedPids",l.sparedPids.map(m=>m)]])),l.failures.forEach(m=>Bc(e,n,"member_kill:"+m.pid.toString(),m.code,m.message));let d=l.groupSignalError;if(d===void 0||me(d.code,"ESRCH"))return;Bc(e,n,"group_kill",d.code,d.message);let u=t(o,c0);if(u.TAG==="Ok")return;let c=u._0;return me(c.code,"ESRCH")?void 0:Bc(e,n,"pid_kill",c.code,c.message)}let a=t(o,c0);if(a.TAG==="Ok")return;let s=a._0;if(!me(s.code,"ESRCH"))return Bc(e,n,"pid_kill",s.code,s.message)}function f0(e,t,r){let n=e!==void 0?e:eo,i=t!==void 0?t:new Set,o=r!==void 0?r:"exit",a=Array.from(al.children);return al.children.clear(),a.forEach(s=>d6(s,n,i,o)),a.length}function F$(e,t){let r;return r=typeof t=="string"?t:JSON.stringify(t),"linzumi commander "+e+": "+r+`
|
|
327
327
|
`}function u6(){if(al.handlersInstalled)return;al.handlersInstalled=!0;let e=o=>{f0(void 0,void 0,"process_exit")};process.on("exit",e);let t=process.listenerCount("uncaughtException")===0,r=process.listenerCount("unhandledRejection")===0,n=o=>{f0(void 0,void 0,"uncaught_exception"),br(F$("uncaughtException",o)),process.exit(1)},i=o=>{f0(void 0,void 0,"unhandled_rejection"),br(F$("unhandledRejection",o)),process.exit(1)};t&&process.on("uncaughtException",n),r&&process.on("unhandledRejection",i),al.removeHandlers=()=>{if(process.off("exit",e),t&&process.off("uncaughtException",n),r){process.off("unhandledRejection",i);return}}}function Ah(e){return al.children.add(e),u6(),{unregister:()=>{al.children.delete(e)}}}import*as Za from"node:path";function m0(e){return e?"true":"false"}import*as L$ from"node:net";function sl(e,t){try{return e.kill(t)}catch{return!1}}function U$(){return new Promise((e,t)=>{let r=L$.createServer();r.on("error",n=>e({TAG:"Error",_0:n.message})),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n==null)return r.close(o=>{}),e({TAG:"Error",_0:"failed to allocate loopback port"});let i=n.port;r.close(o=>o==null?e({TAG:"Ok",_0:i}):e({TAG:"Error",_0:o.message}))})})}var que=new RegExp("[^0-9A-Za-z._-]","g");var Kue=new RegExp("[\\\\/]");var W$="cannot fork thread runner without current CLI script path";var Que=15*6e4,Yue=120*6e4,Xue=1440*6e4,ece=2*6e4;var p6="this computer is updating its Linzumi runner",tce=p6+" to a new version - nothing was started. Retry in a few minutes once the update finishes.";var rce=15*6e4;var V$="this computer restarted its Linzumi runner for an update",nce=V$+" after waiting for this job past the drain timeout - the job was interrupted. Send your message again to continue.",ice=V$+" while this job was waiting on your approval - the approval prompt was interrupted. Send your message again and answer the approval prompt to continue.";function H$(e,t,r){return e==="SIGTERM"&&t?r!=="win32":!1}var Z$="runner.thread_worker_sigterm_deferred_to_drain";function h6(e,t){}var h0="linzumi.thread_runner";function J$(e,t){return e!==void 0&&e.trim()!==""?{TAG:"Ok",_0:Za.isAbsolute(e)?e:Za.resolve(t,e)}:{TAG:"Error",_0:W$}}function _6(e){return["--require","-r","--import","--loader","--experimental-loader"].includes(e)}function g6(e){return["--require=","-r=","--import=","--loader=","--experimental-loader="].some(t=>e.startsWith(t))}function y6(e){let t=[],r=0;for(;r<e.length;){let n=e[r];if(n!==void 0){let i=_6(n),o=g6(n);if(i){let a=e[r+1|0];a!==void 0&&(t.push(n),t.push(a)),r=r+2|0}else o&&t.push(n),r=r+1|0}else r=r+1|0}return t}function _0(e,t,r){return y6(r).concat([e].concat(t))}function ii(e,t){return t!==void 0?t!==""?[e,t]:[]:[]}function K$(e){let t=e.codingJob;if(t===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let r=t.mcpToken;if(r===void 0||typeof r!="string")return;let n=r.trim();if(n!=="")return n}function Q$(e){let t=i=>{let o=i.join(",");if(o!=="")return o},r=e.codexModelProvider,n=e.runtimeDefaults;return[["--api-url",e.kandanUrl],["--cwd",e.cwd],["--codex-bin",e.codexBin],ii("--workspace",e.workspaceSlug),ii("--log-file",e.logFile),ii("--debug-trace-dir",z(e.debugTrace,i=>i.dir)),ii("--debug-trace-content",k(e.debugTrace,i=>i.contentMode)),e.fast?["--fast"]:[],ii("--allowed-cwd",t(e.allowedCwds)),ii("--forward-port",t(e.allowedForwardPorts.map(i=>i.toString()))),ii("--code-server-bin",e.codeServerBin),ii("--model",k(e.runtimeDefaults,i=>i.model)),ii("--reasoning-effort",k(e.runtimeDefaults,i=>i.reasoningEffort)),ii("--sandbox",k(e.runtimeDefaults,i=>i.sandbox)),ii("--approval-policy",k(e.runtimeDefaults,i=>i.approvalPolicy)),r!==void 0?["--model-provider",r.provider,"--llm-proxy-base-url",r.llmProxyBaseUrl]:[],e.vmExecution?["--vm-execution"]:[],ii("--execution-mode",e.executionMode),ii("--egress-mode",e.egressMode),ii("--project-public-id",e.projectPublicId),ii("--golden-image-id",e.goldenImagePublicId),["--multi-agent-jobs-eligible",m0(e.multiAgentJobsEligible)],["--multi-agent-jobs-enabled",m0(e.multiAgentJobs)],n!==void 0?n.allowPortForwardingByDefault?["--allow-port-forwarding-by-default"]:["--no-allow-port-forwarding-by-default"]:[]].flat()}function Y$(e){let t=[],r=0;for(;r<e.length;){let n=e[r];n!==void 0?n==="--token"?(t.push("--token"),t.push("<redacted>"),r=r+2|0):(t.push(n),r=r+1|0):r=r+1|0}return t}function X$(e,t,r){let n=[["LINZUMI_THREAD_RUNNER_ROLE","thread"],["LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID",e.kandanThreadId],["LINZUMI_THREAD_RUNNER_TOKEN",e.token],["LINZUMI_DEV_SERVICES_PARENT_PID",t.toString()]],i=e.codexModelProvider;return i!==void 0&&n.push(["LINZUMI_LLM_PROXY_TOKEN",i.llmProxyToken]),n.push(["LINZUMI_THREAD_RUNNER_AGENT_MCP_TOKEN",v(e.linzumiAgentMcpToken,"")]),n.push(["LINZUMI_THREAD_RUNNER_CODING_JOB_MCP_TOKEN",v(e.codingJobMcpToken,"")]),r!==void 0&&n.push(["OPENAI_API_KEY",r]),n}function ll(e){let t=e.length;return t>12e3?e.slice(t-12e3|0,t):e}function Oh(e){let t=Pr(e.code,"null",o=>o.toString()),r=v(e.signal,"null"),n="thread Codex worker exited before ready: code="+t+" signal="+r,i=e.capturedOutput.trim();return i===""?n:n+`
|