@linzumi/cli 1.0.140 → 1.0.142

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.
@@ -419,6 +419,6 @@ Tools:
419
419
  Auth:
420
420
  Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
421
421
  Hosted personal agents use --delegation-auth-file with a signed delegation grant.
422
- `}async function sE(e){let t=Cl(e);if(t.get("help")===!0){process.stdout.write(ev());return}let r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}),o=re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,s=Al(re(t,"mode")),i=tv(re(t,"tool-scope")),a=re(t,"cwd")??process.cwd(),c=re(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:s}),d=new bi({name:"linzumi",version:"0.1.0"});fE(d),aE(d,{client:u,toolScope:i,operatingMode:s,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,devServices:iE(process.env)}),await d.connect(new ki)}function iE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:O_(t),ownerPid:r}}function aE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:s,kandanUrl:i,defaultThreadId:a,ownerUsername:c,agentSession:u,devServices:d}=t,l=n==="all"||n==="coding";u&&(e.tool("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.",{body:m.string().min(1).describe("Plain-text reply body to post.")},async p=>E(await r.agentReply({body:p.body}))),e.tool("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()=>E(await r.agentListCodingJobs({}))),e.tool("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).",{channel:m.string().describe("Channel slug to host the job thread."),runner_key:m.string().describe("Runner (computer) to run the job on."),cwd:m.string().describe("Working directory on the runner."),work_description:m.string().min(1).describe("What the job should do - the initial instruction."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:m.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.")},async p=>E(await r.agentStartCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),mode:m.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>E(await r.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Send a message into a coding job thread as the asking user (the job processes it like any human follow-up).",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),body:m.string().min(1).describe("Message body to send.")},async p=>E(await r.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.agentReadCodingJobThread(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),source_seq:m.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:m.string().describe("The approval request id."),decision:m.enum(["approve","deny"]).describe("The asker's decision.")},async p=>E(await r.agentResolveJobApproval(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to archive.")},async p=>E(await r.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to unarchive.")},async p=>E(await r.agentUnarchiveCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID."),status:m.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>E(await r.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:m.string().min(1).describe("Channel name to create.")},async p=>E(await r.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:m.string().describe("Current channel slug to rename."),name:m.string().min(1).describe("New display name.")},async p=>E(await r.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:m.string().describe("Channel slug to archive.")},async p=>E(await r.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:m.string().describe("Channel slug to unarchive.")},async p=>E(await r.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to react to."),emoji:m.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>E(await r.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the reacted message."),emoji:m.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>E(await r.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to pin.")},async p=>E(await r.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the pinned message.")},async p=>E(await r.agentUnpinMessage(p)))),n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:m.union([m.string(),m.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:m.union([m.string(),m.number()]).optional().describe("Alias for message_id."),message_url:m.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:m.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:m.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async p=>E(await r.getMessage(p))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.getThread(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:m.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async p=>E(await r.getThreadTranscript(p))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:m.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:m.number().int().positive().optional().describe("Return messages before this channel seq.")},async p=>E(await r.getChannel(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:m.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:m.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:m.array(m.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:m.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:m.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:m.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:m.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async p=>E(await r.searchWorkspace(p))),e.tool("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.',{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:m.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:m.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:m.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async p=>E(await r.askWorkspace(p))),e.tool("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 p=>E(await r.aboutMe(p)))),l&&(e.tool("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.",{query:m.string().min(1).describe("Web search query (natural language or keywords)."),limit:m.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async p=>E(await r.webSearch(p))),e.tool("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.",{url:m.string().min(1).describe("Absolute public http(s) URL to fetch.")},async p=>E(await r.fetchUrl(p)))),n==="all"&&(e.tool("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()=>await X_(r.listUiTargets({}))),e.tool("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.",{kind:m.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:m.record(m.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>await X_(r.openUi(Pt(p,a))))),l&&(e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async p=>E(await r.getCodingJobMetadata(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:m.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async p=>E(await r.renameCodingJob(Pt(p,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")},async p=>E(await r.upsertCodingJobPlan(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:m.array(m.object({title:m.string().min(1).max(255),description:m.string().min(1).max(1e4),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional()})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async p=>E(await r.replaceCodingJobPlanSteps(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:m.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:m.number().int().positive().describe("Current step lock_version from metadata."),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")},async p=>E(await r.updateCodingJobPlanStep(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:m.string().min(1).max(255),github_repo_name:m.string().min(1).max(255),github_pr_number:m.number().int().positive(),github_pr_url:m.string().url(),title:m.string().min(1).max(255),body:m.string().min(1).max(1e5).optional(),head_branch:m.string().min(1).max(255),head_sha:m.string().min(7).max(64),base_branch:m.string().min(1).max(255),base_sha:m.string().min(7).max(64),state:m.enum(["draft","open","closed","merged"]).optional(),is_draft:m.boolean().optional(),review_status:m.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:m.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:m.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:m.enum(["unknown","clean","dirty"]).optional(),dirty_summary:m.string().min(1).max(2e3).optional()},async p=>E(await r.linkCodingJobPullRequest(Pt(p,a)))),e.tool("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(" "),{target:m.object({kind:m.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:m.union([m.string(),m.number()]).optional().describe("Required when kind is message_seq."),thread_id:m.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Do not guess; use new_message when there is no previous assistant message. 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:m.array(m.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden supported file types inside the approved workspace or Downloads."),body:m.string().min(1).max(2e4).optional().describe("Required for new_message. 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:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.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 h=W_(p.target,a);try{let f=await dE({client:r,cwd:s,kandanUrl:i,target:h,files:p.files,workspace:p.workspace,channel:p.channel,body:p.body});return E(G_(i,f))}catch(f){throw uE(f)}}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:m.object({message_seq:m.union([m.string(),m.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:m.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:m.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=>E(G_(i,await r.editMessage({...p,target:W_(p.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async p=>E(await r.listVaultSecrets(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.listProjects(p))),e.tool("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.`,{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async p=>E(await r.getProjectTasks(Pt(p,a)))),e.tool("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.',{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:m.string().min(1).describe("Task title."),kind:m.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:m.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:m.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:m.string().optional().describe("Username of a workspace member to assign."),position:m.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async p=>E(await r.createProjectTask(Pt(p,a)))),e.tool("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.',{task_id:m.string().describe("task_id of the group or issue to update."),title:m.string().min(1).optional().describe("New title."),description:m.string().nullable().optional().describe("New description. Pass null to clear it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:m.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:m.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:m.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:m.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:m.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:m.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:m.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async p=>E(await r.updateProjectTask(p))),e.tool("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.`,{task_id:m.string().describe("task_id of the group or issue to delete.")},async p=>E(await r.deleteProjectTask(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async p=>E(await r.addProjectTaskDependency(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async p=>E(await r.removeProjectTaskDependency(p))),e.tool("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).",{call_id:m.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 p=>E(await r.getCallTranscript(p))),u||e.tool("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).",{work_description:m.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:m.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."),channel:m.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:m.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:m.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")},async p=>E(await r.agentStartCodingJob(Pt(p,a))))),tE(n)&&(e.tool("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:.",{name:B_.describe("Custom emoji shortcode name, with or without surrounding colons."),file:m.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await lE({client:r,cwd:s,kandanUrl:i,name:p.name,file:p.file,workspace:p.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:m.union([m.string(),m.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:B_.describe("New shortcode name, with or without surrounding colons."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.renameCustomEmoji(p)))),e.tool("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()=>({content:[{type:"text",text:F_}]})),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:m.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:m.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:m.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async p=>E(await r.noteProjectDirectory(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:m.enum(["codex","claude_code"]).describe("Conversation source."),import_key:m.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:m.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:m.string().optional().describe("Short label for the discovered conversation."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async p=>E(await r.noteAgentConversation(p))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:m.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:m.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:m.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:m.string().optional().describe("Short user-facing status note."),current_place:m.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:m.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:m.string().optional().describe("Short failure detail when status is failed."),metadata:m.record(m.unknown()).optional().describe("Small structured status metadata.")},async p=>E(await r.noteOnboardingDiscoveryStatus(p))),n==="all"&&rE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:m.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify owner visibility."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>{let h=p.owner_username??c;if(h===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return E(await r.dmOwner({...p,owner_username:h}))}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:m.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 p=>E(await r.sendChannelMessage(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID."),body:m.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 p=>E(await r.sendThreadReply(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify target visibility."),username:m.string().describe("Visible Linzumi username to DM."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>E(await r.sendDm(p)))),n==="all"&&e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:m.array(m.string().regex(/^[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:m.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:m.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async p=>E(await r.getVaultValues(p))),n==="all"&&!u&&d!==void 0&&cE(e,s,d)}function H_(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath}}function cE(e,t,r){e.tool("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).",{name:m.string().regex(/^[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:m.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:m.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:m.array(m.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:m.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:m.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 o=await N_({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return E({ok:!1,error:o.error});let s=Date.now()+(n.wait_for_ports_ms??15e3),i=o.record.ports.length===0;for(;!i&&Date.now()<s;)i=(await Promise.all(o.record.ports.map(d=>El(d)))).every(d=>d),i||await new Promise(d=>setTimeout(d,250));let c=(await Il(r.scopeDir)).find(u=>u.record.name===o.record.name);return E({ok:!0,service:c===void 0?{name:o.record.name}:H_(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("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.",{name:m.string().min(1).describe("Service name to stop.")},async n=>{let o=await Ol({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("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()=>{let n=await Il(r.scopeDir);return E({services:n.map(o=>H_(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:m.string().min(1).describe("Service name."),max_bytes:m.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Z_(r.scopeDir,n.name,n.max_bytes??16384);return E(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("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.",{name:m.string().min(1).describe("Service name to remove.")},async n=>{let o=await D_({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function uE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function dE(e){let t=await Promise.all(e.files.map(i=>kl(e.cwd,i))),r=we(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(i=>({file_name:i.fileName,content_type:i.contentType,size_bytes:i.sizeBytes}))}),o=$i(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(i,a)=>{let c=zt(o[a]),u=we(c?.upload_url),d=we(c?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=await Y_(i.path),p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),h=await fetch(Ao(e.kandanUrl,u),{method:d,headers:{"content-type":i.contentType},body:p});if(!h.ok)throw new Error(`Linzumi upload failed for ${i.fileName}: ${h.status} ${h.statusText}`)}));let s=o.map(i=>{let a=we(zt(i)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:s})}async function lE(e){let t=await kl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=zt(r.upload),o=we(n?.upload_url),s=we(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let i=await Y_(t.path),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),c=await fetch(Ao(e.kandanUrl,o),{method:s,headers:{"content-type":t.contentType},body:a});if(!c.ok){let l=`${c.status} ${c.statusText}`,h=(await c.text()).trim(),f=h===""?l:(()=>{try{let g=JSON.parse(h);return ft(g)&&typeof g.error=="string"?g.error:h}catch{return h}})();throw new Error(`Linzumi custom emoji upload failed: ${f}`)}let u=await c.json();if(!ft(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let d=zt(u.custom_emoji);if(d===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:d,asset_id:we(u.asset_id),id:x_(d?.id),name:we(d?.name),shortcode:we(d?.shortcode),image_url:we(d?.image_url)}}function W_(e,t){if(we(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(we(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function Pt(e,t){return we(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Ao(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function G_(e,t){let r=zt(t.message),n=zt(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:K_(e,r)},...n===void 0?{}:{target_message:K_(e,n)}}}function K_(e,t){let r=$i(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>pE(e,n))}}function pE(e,t){let r=zt(t);if(r===void 0)return t;let n=we(r.url),o=zt(r.image_variants);return{...r,...n===void 0?{}:{url:Ao(e,n)},...o===void 0?{}:{image_variants:mE(e,o)}}}function mE(e,t){let r=we(t.inline_url),n=we(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Ao(e,r)},...n===void 0?{}:{carousel_url:Ao(e,n)}}}function fE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(tn,()=>({resources:[]})),e.server.setRequestHandler(rn,()=>({resourceTemplates:[]}))}async function hE(e){let t=Cl(e),r=Ml(t,"api-url"),n=re(t,"format")??"codex",o=Al(re(t,"mode")),s=t.get("include-token")===!0?(await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")})).accessToken:void 0,i=U_({command:re(t,"command"),kandanUrl:r,accessToken:s,delegationAuthFilePath:re(t,"delegation-auth-file"),ownerUsername:re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:tv(re(t,"tool-scope"))});switch(n){case"codex":process.stdout.write(J_(i));return;case"claude-code":process.stdout.write(q_(i));return;default:throw new Error("--format must be codex or claude-code")}}async function gE(e){let t=Cl(e),r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")});switch(n.mode){case"local-runner":{if(!await Vy({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:Al(re(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
422
+ `}async function sE(e){let t=Cl(e);if(t.get("help")===!0){process.stdout.write(ev());return}let r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}),o=re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,s=Al(re(t,"mode")),i=tv(re(t,"tool-scope")),a=re(t,"cwd")??process.cwd(),c=re(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:s}),d=new bi({name:"linzumi",version:"0.1.0"});fE(d),aE(d,{client:u,toolScope:i,operatingMode:s,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,devServices:iE(process.env)}),await d.connect(new ki)}function iE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:O_(t),ownerPid:r}}function aE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:s,kandanUrl:i,defaultThreadId:a,ownerUsername:c,agentSession:u,devServices:d}=t,l=n==="all"||n==="coding";u&&(e.tool("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.",{body:m.string().min(1).describe("Plain-text reply body to post.")},async p=>E(await r.agentReply({body:p.body}))),e.tool("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()=>E(await r.agentListCodingJobs({}))),e.tool("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).",{channel:m.string().describe("Channel slug to host the job thread."),runner_key:m.string().describe("Runner (computer) to run the job on."),cwd:m.string().describe("Working directory on the runner."),work_description:m.string().min(1).describe("What the job should do - the initial instruction."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:m.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.")},async p=>E(await r.agentStartCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),mode:m.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>E(await r.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Send a message into a coding job thread as the asking user (the job processes it like any human follow-up).",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),body:m.string().min(1).describe("Message body to send.")},async p=>E(await r.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.agentReadCodingJobThread(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),source_seq:m.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:m.string().describe("The approval request id."),decision:m.enum(["approve","deny"]).describe("The asker's decision.")},async p=>E(await r.agentResolveJobApproval(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to archive.")},async p=>E(await r.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to unarchive.")},async p=>E(await r.agentUnarchiveCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID."),status:m.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>E(await r.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:m.string().min(1).describe("Channel name to create.")},async p=>E(await r.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:m.string().describe("Current channel slug to rename."),name:m.string().min(1).describe("New display name.")},async p=>E(await r.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:m.string().describe("Channel slug to archive.")},async p=>E(await r.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:m.string().describe("Channel slug to unarchive.")},async p=>E(await r.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to react to."),emoji:m.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>E(await r.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the reacted message."),emoji:m.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>E(await r.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to pin.")},async p=>E(await r.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the pinned message.")},async p=>E(await r.agentUnpinMessage(p)))),n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:m.union([m.string(),m.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:m.union([m.string(),m.number()]).optional().describe("Alias for message_id."),message_url:m.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:m.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:m.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async p=>E(await r.getMessage(p))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.getThread(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:m.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async p=>E(await r.getThreadTranscript(p))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:m.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:m.number().int().positive().optional().describe("Return messages before this channel seq.")},async p=>E(await r.getChannel(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:m.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:m.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:m.array(m.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:m.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:m.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:m.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:m.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async p=>E(await r.searchWorkspace(p))),e.tool("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.',{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:m.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:m.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:m.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async p=>E(await r.askWorkspace(p))),e.tool("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 p=>E(await r.aboutMe(p)))),l&&(e.tool("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.",{query:m.string().min(1).describe("Web search query (natural language or keywords)."),limit:m.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async p=>E(await r.webSearch(p))),e.tool("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.",{url:m.string().min(1).describe("Absolute public http(s) URL to fetch.")},async p=>E(await r.fetchUrl(p)))),n==="all"&&(e.tool("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()=>await X_(r.listUiTargets({}))),e.tool("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.",{kind:m.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:m.record(m.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>await X_(r.openUi(Pt(p,a))))),l&&(e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async p=>E(await r.getCodingJobMetadata(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:m.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async p=>E(await r.renameCodingJob(Pt(p,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")},async p=>E(await r.upsertCodingJobPlan(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:m.array(m.object({title:m.string().min(1).max(255),description:m.string().min(1).max(1e4),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional()})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async p=>E(await r.replaceCodingJobPlanSteps(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:m.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:m.number().int().positive().describe("Current step lock_version from metadata."),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")},async p=>E(await r.updateCodingJobPlanStep(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:m.string().min(1).max(255),github_repo_name:m.string().min(1).max(255),github_pr_number:m.number().int().positive(),github_pr_url:m.string().url(),title:m.string().min(1).max(255),body:m.string().min(1).max(1e5).optional(),head_branch:m.string().min(1).max(255),head_sha:m.string().min(7).max(64),base_branch:m.string().min(1).max(255),base_sha:m.string().min(7).max(64),state:m.enum(["draft","open","closed","merged"]).optional(),is_draft:m.boolean().optional(),review_status:m.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:m.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:m.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:m.enum(["unknown","clean","dirty"]).optional(),dirty_summary:m.string().min(1).max(2e3).optional()},async p=>E(await r.linkCodingJobPullRequest(Pt(p,a)))),e.tool("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(" "),{target:m.object({kind:m.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:m.union([m.string(),m.number()]).optional().describe("Required when kind is message_seq."),thread_id:m.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Do not guess; use new_message when there is no previous assistant message. 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:m.array(m.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden supported file types inside the approved workspace or Downloads."),body:m.string().min(1).max(2e4).optional().describe("Required for new_message. 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:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.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 h=W_(p.target,a);try{let f=await dE({client:r,cwd:s,kandanUrl:i,target:h,files:p.files,workspace:p.workspace,channel:p.channel,body:p.body});return E(G_(i,f))}catch(f){throw uE(f)}}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:m.object({message_seq:m.union([m.string(),m.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:m.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:m.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=>E(G_(i,await r.editMessage({...p,target:W_(p.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async p=>E(await r.listVaultSecrets(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.listProjects(p))),e.tool("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.`,{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async p=>E(await r.getProjectTasks(Pt(p,a)))),e.tool("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.',{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:m.string().min(1).describe("Task title."),kind:m.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:m.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:m.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:m.string().optional().describe("Username of a workspace member to assign."),position:m.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async p=>E(await r.createProjectTask(Pt(p,a)))),e.tool("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.',{task_id:m.string().describe("task_id of the group or issue to update."),title:m.string().min(1).optional().describe("New title."),description:m.string().nullable().optional().describe("New description. Pass null to clear it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:m.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:m.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:m.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:m.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:m.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:m.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:m.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async p=>E(await r.updateProjectTask(p))),e.tool("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.`,{task_id:m.string().describe("task_id of the group or issue to delete.")},async p=>E(await r.deleteProjectTask(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async p=>E(await r.addProjectTaskDependency(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async p=>E(await r.removeProjectTaskDependency(p))),e.tool("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).",{call_id:m.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 p=>E(await r.getCallTranscript(p))),u||e.tool("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).",{work_description:m.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:m.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."),channel:m.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:m.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:m.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),agent_provider:m.string().optional().describe("Agent provider override, e.g. 'codex' (optional)."),reasoning_effort:m.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),approval_policy:m.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional)."),sandbox:m.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional)."),fast:m.boolean().optional().describe("Fast-mode override (optional)."),allow_port_forwarding_by_default:m.boolean().optional().describe("Default port-forwarding override (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),egress_mode:m.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")},async p=>E(await r.agentStartCodingJob(Pt(p,a))))),tE(n)&&(e.tool("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:.",{name:B_.describe("Custom emoji shortcode name, with or without surrounding colons."),file:m.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await lE({client:r,cwd:s,kandanUrl:i,name:p.name,file:p.file,workspace:p.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:m.union([m.string(),m.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:B_.describe("New shortcode name, with or without surrounding colons."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.renameCustomEmoji(p)))),e.tool("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()=>({content:[{type:"text",text:F_}]})),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:m.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:m.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:m.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async p=>E(await r.noteProjectDirectory(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:m.enum(["codex","claude_code"]).describe("Conversation source."),import_key:m.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:m.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:m.string().optional().describe("Short label for the discovered conversation."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async p=>E(await r.noteAgentConversation(p))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:m.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:m.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:m.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:m.string().optional().describe("Short user-facing status note."),current_place:m.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:m.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:m.string().optional().describe("Short failure detail when status is failed."),metadata:m.record(m.unknown()).optional().describe("Small structured status metadata.")},async p=>E(await r.noteOnboardingDiscoveryStatus(p))),n==="all"&&rE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:m.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify owner visibility."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>{let h=p.owner_username??c;if(h===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return E(await r.dmOwner({...p,owner_username:h}))}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:m.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 p=>E(await r.sendChannelMessage(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID."),body:m.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 p=>E(await r.sendThreadReply(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify target visibility."),username:m.string().describe("Visible Linzumi username to DM."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>E(await r.sendDm(p)))),n==="all"&&e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:m.array(m.string().regex(/^[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:m.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:m.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async p=>E(await r.getVaultValues(p))),n==="all"&&!u&&d!==void 0&&cE(e,s,d)}function H_(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath}}function cE(e,t,r){e.tool("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).",{name:m.string().regex(/^[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:m.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:m.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:m.array(m.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:m.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:m.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 o=await N_({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return E({ok:!1,error:o.error});let s=Date.now()+(n.wait_for_ports_ms??15e3),i=o.record.ports.length===0;for(;!i&&Date.now()<s;)i=(await Promise.all(o.record.ports.map(d=>El(d)))).every(d=>d),i||await new Promise(d=>setTimeout(d,250));let c=(await Il(r.scopeDir)).find(u=>u.record.name===o.record.name);return E({ok:!0,service:c===void 0?{name:o.record.name}:H_(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("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.",{name:m.string().min(1).describe("Service name to stop.")},async n=>{let o=await Ol({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("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()=>{let n=await Il(r.scopeDir);return E({services:n.map(o=>H_(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:m.string().min(1).describe("Service name."),max_bytes:m.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Z_(r.scopeDir,n.name,n.max_bytes??16384);return E(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("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.",{name:m.string().min(1).describe("Service name to remove.")},async n=>{let o=await D_({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function uE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function dE(e){let t=await Promise.all(e.files.map(i=>kl(e.cwd,i))),r=we(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(i=>({file_name:i.fileName,content_type:i.contentType,size_bytes:i.sizeBytes}))}),o=$i(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(i,a)=>{let c=zt(o[a]),u=we(c?.upload_url),d=we(c?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=await Y_(i.path),p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),h=await fetch(Ao(e.kandanUrl,u),{method:d,headers:{"content-type":i.contentType},body:p});if(!h.ok)throw new Error(`Linzumi upload failed for ${i.fileName}: ${h.status} ${h.statusText}`)}));let s=o.map(i=>{let a=we(zt(i)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:s})}async function lE(e){let t=await kl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=zt(r.upload),o=we(n?.upload_url),s=we(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let i=await Y_(t.path),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),c=await fetch(Ao(e.kandanUrl,o),{method:s,headers:{"content-type":t.contentType},body:a});if(!c.ok){let l=`${c.status} ${c.statusText}`,h=(await c.text()).trim(),f=h===""?l:(()=>{try{let g=JSON.parse(h);return ft(g)&&typeof g.error=="string"?g.error:h}catch{return h}})();throw new Error(`Linzumi custom emoji upload failed: ${f}`)}let u=await c.json();if(!ft(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let d=zt(u.custom_emoji);if(d===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:d,asset_id:we(u.asset_id),id:x_(d?.id),name:we(d?.name),shortcode:we(d?.shortcode),image_url:we(d?.image_url)}}function W_(e,t){if(we(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(we(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function Pt(e,t){return we(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Ao(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function G_(e,t){let r=zt(t.message),n=zt(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:K_(e,r)},...n===void 0?{}:{target_message:K_(e,n)}}}function K_(e,t){let r=$i(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>pE(e,n))}}function pE(e,t){let r=zt(t);if(r===void 0)return t;let n=we(r.url),o=zt(r.image_variants);return{...r,...n===void 0?{}:{url:Ao(e,n)},...o===void 0?{}:{image_variants:mE(e,o)}}}function mE(e,t){let r=we(t.inline_url),n=we(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Ao(e,r)},...n===void 0?{}:{carousel_url:Ao(e,n)}}}function fE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(tn,()=>({resources:[]})),e.server.setRequestHandler(rn,()=>({resourceTemplates:[]}))}async function hE(e){let t=Cl(e),r=Ml(t,"api-url"),n=re(t,"format")??"codex",o=Al(re(t,"mode")),s=t.get("include-token")===!0?(await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")})).accessToken:void 0,i=U_({command:re(t,"command"),kandanUrl:r,accessToken:s,delegationAuthFilePath:re(t,"delegation-auth-file"),ownerUsername:re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:tv(re(t,"tool-scope"))});switch(n){case"codex":process.stdout.write(J_(i));return;case"claude-code":process.stdout.write(q_(i));return;default:throw new Error("--format must be codex or claude-code")}}async function gE(e){let t=Cl(e),r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")});switch(n.mode){case"local-runner":{if(!await Vy({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:Al(re(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
423
423
  `)}async function jl(e){if(e.delegationAuthFilePath!==void 0){if(e.explicitToken!==void 0||e.authFilePath!==void 0)throw new Error("--delegation-auth-file cannot be combined with --token or --auth-file");return{accessToken:Ky(e.delegationAuthFilePath).accessToken,mode:"personal-agent-delegation"}}return{accessToken:await yE({kandanUrl:e.kandanUrl,explicitToken:e.explicitToken,authFilePath:e.authFilePath,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug}),mode:"local-runner"}}async function yE(e,t={readCachedToken:Si,validateTokenOutcome:Eo,resolveToken:k_}){let r=e.explicitToken??t.readCachedToken(e.kandanUrl,e.authFilePath)?.accessToken;if(r===void 0)throw new Error("missing Linzumi MCP token; run linzumi auth or pass --token");let n=await t.validateTokenOutcome({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug});if(n==="usable")return r;let o=n;try{return await t.resolveToken({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,authFilePath:e.authFilePath})}catch(s){throw new Error(`Linzumi MCP token was rejected by the server and re-mint failed: ${s instanceof Error?s.message:String(s)}`)}}function E(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}async function X_(e){try{return E(await e)}catch(t){let r=t instanceof Error?t.message:String(t),n=r.match(/failed: ([a-z0-9_]+)(?: detail=(.+))?$/);if(n===null)return E({error:r});let[,o,s]=n;return E(s===void 0?{error:o??r}:{error:o??r,detail:s})}}function Cl(e){let t=new Map;for(let r=0;r<e.length;r+=1){let n=e[r];if(n===void 0)continue;if(!n.startsWith("--"))throw new Error(`unexpected argument ${n}`);let o=n.slice(2),s=oE.get(o);if(s===void 0)throw new Error(`unsupported option --${o}`);if(s.kind==="boolean"){t.set(o,!0);continue}let i=e[r+1];if(i===void 0||i.startsWith("--"))throw new Error(`--${o} requires a value`);t.set(o,i),r+=1}return t}function re(e,t){let r=e.get(t);return typeof r=="string"&&r.trim()!==""?r:void 0}function Al(e){switch(e){case void 0:return"text";case"voice":case"text":return e;default:throw new Error("--mode must be voice or text")}}function tv(e){switch(e){case void 0:return"all";case"all":case"coding":case"onboarding-discovery":return e;default:throw new Error("--tool-scope must be all, coding, or onboarding-discovery")}}function Ml(e,t){let r=re(e,t);if(r===void 0)throw new Error(`--${t} is required`);return r}function vE(e){return e[0]==="mcp"?e.slice(1):e}async function bE(e){try{await Q_(vE(e))}catch(t){process.stderr.write(`linzumi mcp server failed: ${t instanceof Error?t.message:String(t)}
424
424
  `),process.exitCode=1}}var wE=process.argv[1]!==void 0&&import.meta.url===_E(process.argv[1]).href;wE&&bE(process.argv.slice(2));export{vE as mcpServerEntryArgs,bE as runMcpServerEntry};
@@ -419,6 +419,6 @@ Tools:
419
419
  Auth:
420
420
  Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
421
421
  Hosted personal agents use --delegation-auth-file with a signed delegation grant.
422
- `}async function sE(e){let t=Cl(e);if(t.get("help")===!0){process.stdout.write(ev());return}let r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}),o=re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,s=Al(re(t,"mode")),i=tv(re(t,"tool-scope")),a=re(t,"cwd")??process.cwd(),c=re(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:s}),d=new bi({name:"linzumi",version:"0.1.0"});fE(d),aE(d,{client:u,toolScope:i,operatingMode:s,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,devServices:iE(process.env)}),await d.connect(new ki)}function iE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:O_(t),ownerPid:r}}function aE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:s,kandanUrl:i,defaultThreadId:a,ownerUsername:c,agentSession:u,devServices:d}=t,l=n==="all"||n==="coding";u&&(e.tool("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.",{body:m.string().min(1).describe("Plain-text reply body to post.")},async p=>E(await r.agentReply({body:p.body}))),e.tool("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()=>E(await r.agentListCodingJobs({}))),e.tool("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).",{channel:m.string().describe("Channel slug to host the job thread."),runner_key:m.string().describe("Runner (computer) to run the job on."),cwd:m.string().describe("Working directory on the runner."),work_description:m.string().min(1).describe("What the job should do - the initial instruction."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:m.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.")},async p=>E(await r.agentStartCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),mode:m.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>E(await r.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Send a message into a coding job thread as the asking user (the job processes it like any human follow-up).",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),body:m.string().min(1).describe("Message body to send.")},async p=>E(await r.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.agentReadCodingJobThread(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),source_seq:m.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:m.string().describe("The approval request id."),decision:m.enum(["approve","deny"]).describe("The asker's decision.")},async p=>E(await r.agentResolveJobApproval(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to archive.")},async p=>E(await r.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to unarchive.")},async p=>E(await r.agentUnarchiveCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID."),status:m.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>E(await r.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:m.string().min(1).describe("Channel name to create.")},async p=>E(await r.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:m.string().describe("Current channel slug to rename."),name:m.string().min(1).describe("New display name.")},async p=>E(await r.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:m.string().describe("Channel slug to archive.")},async p=>E(await r.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:m.string().describe("Channel slug to unarchive.")},async p=>E(await r.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to react to."),emoji:m.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>E(await r.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the reacted message."),emoji:m.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>E(await r.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to pin.")},async p=>E(await r.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the pinned message.")},async p=>E(await r.agentUnpinMessage(p)))),n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:m.union([m.string(),m.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:m.union([m.string(),m.number()]).optional().describe("Alias for message_id."),message_url:m.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:m.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:m.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async p=>E(await r.getMessage(p))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.getThread(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:m.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async p=>E(await r.getThreadTranscript(p))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:m.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:m.number().int().positive().optional().describe("Return messages before this channel seq.")},async p=>E(await r.getChannel(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:m.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:m.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:m.array(m.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:m.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:m.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:m.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:m.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async p=>E(await r.searchWorkspace(p))),e.tool("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.',{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:m.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:m.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:m.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async p=>E(await r.askWorkspace(p))),e.tool("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 p=>E(await r.aboutMe(p)))),l&&(e.tool("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.",{query:m.string().min(1).describe("Web search query (natural language or keywords)."),limit:m.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async p=>E(await r.webSearch(p))),e.tool("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.",{url:m.string().min(1).describe("Absolute public http(s) URL to fetch.")},async p=>E(await r.fetchUrl(p)))),n==="all"&&(e.tool("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()=>await X_(r.listUiTargets({}))),e.tool("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.",{kind:m.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:m.record(m.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>await X_(r.openUi(Pt(p,a))))),l&&(e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async p=>E(await r.getCodingJobMetadata(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:m.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async p=>E(await r.renameCodingJob(Pt(p,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")},async p=>E(await r.upsertCodingJobPlan(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:m.array(m.object({title:m.string().min(1).max(255),description:m.string().min(1).max(1e4),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional()})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async p=>E(await r.replaceCodingJobPlanSteps(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:m.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:m.number().int().positive().describe("Current step lock_version from metadata."),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")},async p=>E(await r.updateCodingJobPlanStep(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:m.string().min(1).max(255),github_repo_name:m.string().min(1).max(255),github_pr_number:m.number().int().positive(),github_pr_url:m.string().url(),title:m.string().min(1).max(255),body:m.string().min(1).max(1e5).optional(),head_branch:m.string().min(1).max(255),head_sha:m.string().min(7).max(64),base_branch:m.string().min(1).max(255),base_sha:m.string().min(7).max(64),state:m.enum(["draft","open","closed","merged"]).optional(),is_draft:m.boolean().optional(),review_status:m.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:m.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:m.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:m.enum(["unknown","clean","dirty"]).optional(),dirty_summary:m.string().min(1).max(2e3).optional()},async p=>E(await r.linkCodingJobPullRequest(Pt(p,a)))),e.tool("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(" "),{target:m.object({kind:m.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:m.union([m.string(),m.number()]).optional().describe("Required when kind is message_seq."),thread_id:m.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Do not guess; use new_message when there is no previous assistant message. 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:m.array(m.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden supported file types inside the approved workspace or Downloads."),body:m.string().min(1).max(2e4).optional().describe("Required for new_message. 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:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.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 h=W_(p.target,a);try{let f=await dE({client:r,cwd:s,kandanUrl:i,target:h,files:p.files,workspace:p.workspace,channel:p.channel,body:p.body});return E(G_(i,f))}catch(f){throw uE(f)}}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:m.object({message_seq:m.union([m.string(),m.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:m.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:m.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=>E(G_(i,await r.editMessage({...p,target:W_(p.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async p=>E(await r.listVaultSecrets(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.listProjects(p))),e.tool("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.`,{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async p=>E(await r.getProjectTasks(Pt(p,a)))),e.tool("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.',{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:m.string().min(1).describe("Task title."),kind:m.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:m.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:m.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:m.string().optional().describe("Username of a workspace member to assign."),position:m.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async p=>E(await r.createProjectTask(Pt(p,a)))),e.tool("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.',{task_id:m.string().describe("task_id of the group or issue to update."),title:m.string().min(1).optional().describe("New title."),description:m.string().nullable().optional().describe("New description. Pass null to clear it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:m.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:m.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:m.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:m.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:m.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:m.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:m.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async p=>E(await r.updateProjectTask(p))),e.tool("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.`,{task_id:m.string().describe("task_id of the group or issue to delete.")},async p=>E(await r.deleteProjectTask(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async p=>E(await r.addProjectTaskDependency(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async p=>E(await r.removeProjectTaskDependency(p))),e.tool("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).",{call_id:m.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 p=>E(await r.getCallTranscript(p))),u||e.tool("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).",{work_description:m.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:m.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."),channel:m.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:m.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:m.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional).")},async p=>E(await r.agentStartCodingJob(Pt(p,a))))),tE(n)&&(e.tool("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:.",{name:B_.describe("Custom emoji shortcode name, with or without surrounding colons."),file:m.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await lE({client:r,cwd:s,kandanUrl:i,name:p.name,file:p.file,workspace:p.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:m.union([m.string(),m.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:B_.describe("New shortcode name, with or without surrounding colons."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.renameCustomEmoji(p)))),e.tool("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()=>({content:[{type:"text",text:F_}]})),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:m.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:m.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:m.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async p=>E(await r.noteProjectDirectory(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:m.enum(["codex","claude_code"]).describe("Conversation source."),import_key:m.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:m.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:m.string().optional().describe("Short label for the discovered conversation."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async p=>E(await r.noteAgentConversation(p))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:m.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:m.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:m.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:m.string().optional().describe("Short user-facing status note."),current_place:m.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:m.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:m.string().optional().describe("Short failure detail when status is failed."),metadata:m.record(m.unknown()).optional().describe("Small structured status metadata.")},async p=>E(await r.noteOnboardingDiscoveryStatus(p))),n==="all"&&rE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:m.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify owner visibility."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>{let h=p.owner_username??c;if(h===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return E(await r.dmOwner({...p,owner_username:h}))}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:m.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 p=>E(await r.sendChannelMessage(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID."),body:m.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 p=>E(await r.sendThreadReply(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify target visibility."),username:m.string().describe("Visible Linzumi username to DM."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>E(await r.sendDm(p)))),n==="all"&&e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:m.array(m.string().regex(/^[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:m.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:m.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async p=>E(await r.getVaultValues(p))),n==="all"&&!u&&d!==void 0&&cE(e,s,d)}function H_(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath}}function cE(e,t,r){e.tool("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).",{name:m.string().regex(/^[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:m.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:m.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:m.array(m.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:m.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:m.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 o=await N_({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return E({ok:!1,error:o.error});let s=Date.now()+(n.wait_for_ports_ms??15e3),i=o.record.ports.length===0;for(;!i&&Date.now()<s;)i=(await Promise.all(o.record.ports.map(d=>El(d)))).every(d=>d),i||await new Promise(d=>setTimeout(d,250));let c=(await Il(r.scopeDir)).find(u=>u.record.name===o.record.name);return E({ok:!0,service:c===void 0?{name:o.record.name}:H_(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("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.",{name:m.string().min(1).describe("Service name to stop.")},async n=>{let o=await Ol({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("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()=>{let n=await Il(r.scopeDir);return E({services:n.map(o=>H_(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:m.string().min(1).describe("Service name."),max_bytes:m.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Z_(r.scopeDir,n.name,n.max_bytes??16384);return E(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("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.",{name:m.string().min(1).describe("Service name to remove.")},async n=>{let o=await D_({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function uE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function dE(e){let t=await Promise.all(e.files.map(i=>kl(e.cwd,i))),r=we(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(i=>({file_name:i.fileName,content_type:i.contentType,size_bytes:i.sizeBytes}))}),o=$i(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(i,a)=>{let c=zt(o[a]),u=we(c?.upload_url),d=we(c?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=await Y_(i.path),p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),h=await fetch(Ao(e.kandanUrl,u),{method:d,headers:{"content-type":i.contentType},body:p});if(!h.ok)throw new Error(`Linzumi upload failed for ${i.fileName}: ${h.status} ${h.statusText}`)}));let s=o.map(i=>{let a=we(zt(i)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:s})}async function lE(e){let t=await kl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=zt(r.upload),o=we(n?.upload_url),s=we(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let i=await Y_(t.path),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),c=await fetch(Ao(e.kandanUrl,o),{method:s,headers:{"content-type":t.contentType},body:a});if(!c.ok){let l=`${c.status} ${c.statusText}`,h=(await c.text()).trim(),f=h===""?l:(()=>{try{let g=JSON.parse(h);return ft(g)&&typeof g.error=="string"?g.error:h}catch{return h}})();throw new Error(`Linzumi custom emoji upload failed: ${f}`)}let u=await c.json();if(!ft(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let d=zt(u.custom_emoji);if(d===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:d,asset_id:we(u.asset_id),id:x_(d?.id),name:we(d?.name),shortcode:we(d?.shortcode),image_url:we(d?.image_url)}}function W_(e,t){if(we(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(we(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function Pt(e,t){return we(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Ao(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function G_(e,t){let r=zt(t.message),n=zt(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:K_(e,r)},...n===void 0?{}:{target_message:K_(e,n)}}}function K_(e,t){let r=$i(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>pE(e,n))}}function pE(e,t){let r=zt(t);if(r===void 0)return t;let n=we(r.url),o=zt(r.image_variants);return{...r,...n===void 0?{}:{url:Ao(e,n)},...o===void 0?{}:{image_variants:mE(e,o)}}}function mE(e,t){let r=we(t.inline_url),n=we(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Ao(e,r)},...n===void 0?{}:{carousel_url:Ao(e,n)}}}function fE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(tn,()=>({resources:[]})),e.server.setRequestHandler(rn,()=>({resourceTemplates:[]}))}async function hE(e){let t=Cl(e),r=Ml(t,"api-url"),n=re(t,"format")??"codex",o=Al(re(t,"mode")),s=t.get("include-token")===!0?(await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")})).accessToken:void 0,i=U_({command:re(t,"command"),kandanUrl:r,accessToken:s,delegationAuthFilePath:re(t,"delegation-auth-file"),ownerUsername:re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:tv(re(t,"tool-scope"))});switch(n){case"codex":process.stdout.write(J_(i));return;case"claude-code":process.stdout.write(q_(i));return;default:throw new Error("--format must be codex or claude-code")}}async function gE(e){let t=Cl(e),r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")});switch(n.mode){case"local-runner":{if(!await Vy({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:Al(re(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
422
+ `}async function sE(e){let t=Cl(e);if(t.get("help")===!0){process.stdout.write(ev());return}let r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}),o=re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,s=Al(re(t,"mode")),i=tv(re(t,"tool-scope")),a=re(t,"cwd")??process.cwd(),c=re(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:s}),d=new bi({name:"linzumi",version:"0.1.0"});fE(d),aE(d,{client:u,toolScope:i,operatingMode:s,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,devServices:iE(process.env)}),await d.connect(new ki)}function iE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:O_(t),ownerPid:r}}function aE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:s,kandanUrl:i,defaultThreadId:a,ownerUsername:c,agentSession:u,devServices:d}=t,l=n==="all"||n==="coding";u&&(e.tool("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.",{body:m.string().min(1).describe("Plain-text reply body to post.")},async p=>E(await r.agentReply({body:p.body}))),e.tool("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()=>E(await r.agentListCodingJobs({}))),e.tool("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).",{channel:m.string().describe("Channel slug to host the job thread."),runner_key:m.string().describe("Runner (computer) to run the job on."),cwd:m.string().describe("Working directory on the runner."),work_description:m.string().min(1).describe("What the job should do - the initial instruction."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:m.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.")},async p=>E(await r.agentStartCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),mode:m.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>E(await r.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Send a message into a coding job thread as the asking user (the job processes it like any human follow-up).",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),body:m.string().min(1).describe("Message body to send.")},async p=>E(await r.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.agentReadCodingJobThread(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the job thread."),thread_id:m.string().uuid().describe("The job thread UUID."),source_seq:m.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:m.string().describe("The approval request id."),decision:m.enum(["approve","deny"]).describe("The asker's decision.")},async p=>E(await r.agentResolveJobApproval(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to archive.")},async p=>E(await r.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID to unarchive.")},async p=>E(await r.agentUnarchiveCodingJob(p))),e.tool("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.",{channel:m.string().describe("Channel slug hosting the thread."),thread_id:m.string().uuid().describe("The thread UUID."),status:m.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>E(await r.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:m.string().min(1).describe("Channel name to create.")},async p=>E(await r.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:m.string().describe("Current channel slug to rename."),name:m.string().min(1).describe("New display name.")},async p=>E(await r.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:m.string().describe("Channel slug to archive.")},async p=>E(await r.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:m.string().describe("Channel slug to unarchive.")},async p=>E(await r.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to react to."),emoji:m.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>E(await r.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the reacted message."),emoji:m.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>E(await r.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the message to pin.")},async p=>E(await r.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:m.string().describe("Channel slug containing the message."),message_seq:m.number().int().positive().describe("Channel seq of the pinned message.")},async p=>E(await r.agentUnpinMessage(p)))),n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:m.union([m.string(),m.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:m.union([m.string(),m.number()]).optional().describe("Alias for message_id."),message_url:m.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:m.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:m.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async p=>E(await r.getMessage(p))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:m.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>E(await r.getThread(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Linzumi thread UUID."),limit:m.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:m.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async p=>E(await r.getThreadTranscript(p))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:m.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:m.number().int().positive().optional().describe("Return messages before this channel seq.")},async p=>E(await r.getChannel(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:m.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:m.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:m.array(m.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:m.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:m.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:m.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:m.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async p=>E(await r.searchWorkspace(p))),e.tool("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.',{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:m.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:m.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:m.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async p=>E(await r.askWorkspace(p))),e.tool("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 p=>E(await r.aboutMe(p)))),l&&(e.tool("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.",{query:m.string().min(1).describe("Web search query (natural language or keywords)."),limit:m.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async p=>E(await r.webSearch(p))),e.tool("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.",{url:m.string().min(1).describe("Absolute public http(s) URL to fetch.")},async p=>E(await r.fetchUrl(p)))),n==="all"&&(e.tool("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()=>await X_(r.listUiTargets({}))),e.tool("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.",{kind:m.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:m.record(m.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>await X_(r.openUi(Pt(p,a))))),l&&(e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async p=>E(await r.getCodingJobMetadata(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:m.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async p=>E(await r.renameCodingJob(Pt(p,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job.")},async p=>E(await r.upsertCodingJobPlan(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:m.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:m.array(m.object({title:m.string().min(1).max(255),description:m.string().min(1).max(1e4),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional()})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async p=>E(await r.replaceCodingJobPlanSteps(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:m.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:m.number().int().positive().describe("Current step lock_version from metadata."),status:m.enum(["pending","active","completed","blocked","canceled"]),status_note:m.string().min(1).max(4e3).optional(),completed_debrief:m.string().min(1).max(2e4).optional().describe("Required when marking a step completed.")},async p=>E(await r.updateCodingJobPlanStep(Pt(p,a)))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:m.string().min(1).max(255),github_repo_name:m.string().min(1).max(255),github_pr_number:m.number().int().positive(),github_pr_url:m.string().url(),title:m.string().min(1).max(255),body:m.string().min(1).max(1e5).optional(),head_branch:m.string().min(1).max(255),head_sha:m.string().min(7).max(64),base_branch:m.string().min(1).max(255),base_sha:m.string().min(7).max(64),state:m.enum(["draft","open","closed","merged"]).optional(),is_draft:m.boolean().optional(),review_status:m.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:m.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:m.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:m.enum(["unknown","clean","dirty"]).optional(),dirty_summary:m.string().min(1).max(2e3).optional()},async p=>E(await r.linkCodingJobPullRequest(Pt(p,a)))),e.tool("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(" "),{target:m.object({kind:m.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:m.union([m.string(),m.number()]).optional().describe("Required when kind is message_seq."),thread_id:m.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Do not guess; use new_message when there is no previous assistant message. 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:m.array(m.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden supported file types inside the approved workspace or Downloads."),body:m.string().min(1).max(2e4).optional().describe("Required for new_message. 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:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.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 h=W_(p.target,a);try{let f=await dE({client:r,cwd:s,kandanUrl:i,target:h,files:p.files,workspace:p.workspace,channel:p.channel,body:p.body});return E(G_(i,f))}catch(f){throw uE(f)}}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:m.object({message_seq:m.union([m.string(),m.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:m.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:m.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=>E(G_(i,await r.editMessage({...p,target:W_(p.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async p=>E(await r.listVaultSecrets(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.listProjects(p))),e.tool("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.`,{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async p=>E(await r.getProjectTasks(Pt(p,a)))),e.tool("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.',{project_id:m.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:m.string().min(1).describe("Task title."),kind:m.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:m.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:m.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:m.string().optional().describe("Username of a workspace member to assign."),position:m.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async p=>E(await r.createProjectTask(Pt(p,a)))),e.tool("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.',{task_id:m.string().describe("task_id of the group or issue to update."),title:m.string().min(1).optional().describe("New title."),description:m.string().nullable().optional().describe("New description. Pass null to clear it."),status:m.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:m.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:m.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:m.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:m.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:m.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:m.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:m.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async p=>E(await r.updateProjectTask(p))),e.tool("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.`,{task_id:m.string().describe("task_id of the group or issue to delete.")},async p=>E(await r.deleteProjectTask(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async p=>E(await r.addProjectTaskDependency(p))),e.tool("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.',{task_id:m.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:m.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async p=>E(await r.removeProjectTaskDependency(p))),e.tool("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).",{call_id:m.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 p=>E(await r.getCallTranscript(p))),u||e.tool("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).",{work_description:m.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:m.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."),channel:m.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:m.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:m.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:m.string().optional().describe("Model override (optional)."),model_provider:m.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),agent_provider:m.string().optional().describe("Agent provider override, e.g. 'codex' (optional)."),reasoning_effort:m.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),approval_policy:m.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional)."),sandbox:m.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional)."),fast:m.boolean().optional().describe("Fast-mode override (optional)."),allow_port_forwarding_by_default:m.boolean().optional().describe("Default port-forwarding override (optional)."),execution_mode:m.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),egress_mode:m.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")},async p=>E(await r.agentStartCodingJob(Pt(p,a))))),tE(n)&&(e.tool("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:.",{name:B_.describe("Custom emoji shortcode name, with or without surrounding colons."),file:m.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await lE({client:r,cwd:s,kandanUrl:i,name:p.name,file:p.file,workspace:p.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:m.union([m.string(),m.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:B_.describe("New shortcode name, with or without surrounding colons."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async p=>E(await r.renameCustomEmoji(p)))),e.tool("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()=>({content:[{type:"text",text:F_}]})),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:m.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:m.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:m.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async p=>E(await r.noteProjectDirectory(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:m.enum(["codex","claude_code"]).describe("Conversation source."),import_key:m.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:m.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:m.string().optional().describe("Short label for the discovered conversation."),activity_at:m.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:m.record(m.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async p=>E(await r.noteAgentConversation(p))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:m.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:m.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:m.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:m.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:m.string().optional().describe("Short user-facing status note."),current_place:m.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:m.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:m.string().optional().describe("Short failure detail when status is failed."),metadata:m.record(m.unknown()).optional().describe("Small structured status metadata.")},async p=>E(await r.noteOnboardingDiscoveryStatus(p))),n==="all"&&rE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:m.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify owner visibility."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>{let h=p.owner_username??c;if(h===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return E(await r.dmOwner({...p,owner_username:h}))}),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:m.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 p=>E(await r.sendChannelMessage(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID."),body:m.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 p=>E(await r.sendThreadReply(p))),e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Source channel slug used to verify target visibility."),username:m.string().describe("Visible Linzumi username to DM."),body:m.string().min(1).max(2e4).describe("Plain-text message body to DM.")},async p=>E(await r.sendDm(p)))),n==="all"&&e.tool("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.",{workspace:m.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:m.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:m.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:m.array(m.string().regex(/^[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:m.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:m.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async p=>E(await r.getVaultValues(p))),n==="all"&&!u&&d!==void 0&&cE(e,s,d)}function H_(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath}}function cE(e,t,r){e.tool("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).",{name:m.string().regex(/^[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:m.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:m.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:m.array(m.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:m.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:m.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 o=await N_({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return E({ok:!1,error:o.error});let s=Date.now()+(n.wait_for_ports_ms??15e3),i=o.record.ports.length===0;for(;!i&&Date.now()<s;)i=(await Promise.all(o.record.ports.map(d=>El(d)))).every(d=>d),i||await new Promise(d=>setTimeout(d,250));let c=(await Il(r.scopeDir)).find(u=>u.record.name===o.record.name);return E({ok:!0,service:c===void 0?{name:o.record.name}:H_(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("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.",{name:m.string().min(1).describe("Service name to stop.")},async n=>{let o=await Ol({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("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()=>{let n=await Il(r.scopeDir);return E({services:n.map(o=>H_(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:m.string().min(1).describe("Service name."),max_bytes:m.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Z_(r.scopeDir,n.name,n.max_bytes??16384);return E(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("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.",{name:m.string().min(1).describe("Service name to remove.")},async n=>{let o=await D_({scopeDir:r.scopeDir,name:n.name});return E(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function uE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function dE(e){let t=await Promise.all(e.files.map(i=>kl(e.cwd,i))),r=we(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(i=>({file_name:i.fileName,content_type:i.contentType,size_bytes:i.sizeBytes}))}),o=$i(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(i,a)=>{let c=zt(o[a]),u=we(c?.upload_url),d=we(c?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=await Y_(i.path),p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),h=await fetch(Ao(e.kandanUrl,u),{method:d,headers:{"content-type":i.contentType},body:p});if(!h.ok)throw new Error(`Linzumi upload failed for ${i.fileName}: ${h.status} ${h.statusText}`)}));let s=o.map(i=>{let a=we(zt(i)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:s})}async function lE(e){let t=await kl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=zt(r.upload),o=we(n?.upload_url),s=we(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let i=await Y_(t.path),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),c=await fetch(Ao(e.kandanUrl,o),{method:s,headers:{"content-type":t.contentType},body:a});if(!c.ok){let l=`${c.status} ${c.statusText}`,h=(await c.text()).trim(),f=h===""?l:(()=>{try{let g=JSON.parse(h);return ft(g)&&typeof g.error=="string"?g.error:h}catch{return h}})();throw new Error(`Linzumi custom emoji upload failed: ${f}`)}let u=await c.json();if(!ft(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let d=zt(u.custom_emoji);if(d===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:d,asset_id:we(u.asset_id),id:x_(d?.id),name:we(d?.name),shortcode:we(d?.shortcode),image_url:we(d?.image_url)}}function W_(e,t){if(we(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(we(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function Pt(e,t){return we(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Ao(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function G_(e,t){let r=zt(t.message),n=zt(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:K_(e,r)},...n===void 0?{}:{target_message:K_(e,n)}}}function K_(e,t){let r=$i(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>pE(e,n))}}function pE(e,t){let r=zt(t);if(r===void 0)return t;let n=we(r.url),o=zt(r.image_variants);return{...r,...n===void 0?{}:{url:Ao(e,n)},...o===void 0?{}:{image_variants:mE(e,o)}}}function mE(e,t){let r=we(t.inline_url),n=we(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Ao(e,r)},...n===void 0?{}:{carousel_url:Ao(e,n)}}}function fE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(tn,()=>({resources:[]})),e.server.setRequestHandler(rn,()=>({resourceTemplates:[]}))}async function hE(e){let t=Cl(e),r=Ml(t,"api-url"),n=re(t,"format")??"codex",o=Al(re(t,"mode")),s=t.get("include-token")===!0?(await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")})).accessToken:void 0,i=U_({command:re(t,"command"),kandanUrl:r,accessToken:s,delegationAuthFilePath:re(t,"delegation-auth-file"),ownerUsername:re(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:tv(re(t,"tool-scope"))});switch(n){case"codex":process.stdout.write(J_(i));return;case"claude-code":process.stdout.write(q_(i));return;default:throw new Error("--format must be codex or claude-code")}}async function gE(e){let t=Cl(e),r=Ml(t,"api-url"),n=await jl({kandanUrl:r,explicitToken:re(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:re(t,"auth-file"),delegationAuthFilePath:re(t,"delegation-auth-file"),workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")});switch(n.mode){case"local-runner":{if(!await Vy({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:re(t,"workspace"),channelSlug:re(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await xl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:Al(re(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
423
423
  `)}async function jl(e){if(e.delegationAuthFilePath!==void 0){if(e.explicitToken!==void 0||e.authFilePath!==void 0)throw new Error("--delegation-auth-file cannot be combined with --token or --auth-file");return{accessToken:Ky(e.delegationAuthFilePath).accessToken,mode:"personal-agent-delegation"}}return{accessToken:await yE({kandanUrl:e.kandanUrl,explicitToken:e.explicitToken,authFilePath:e.authFilePath,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug}),mode:"local-runner"}}async function yE(e,t={readCachedToken:Si,validateTokenOutcome:Eo,resolveToken:k_}){let r=e.explicitToken??t.readCachedToken(e.kandanUrl,e.authFilePath)?.accessToken;if(r===void 0)throw new Error("missing Linzumi MCP token; run linzumi auth or pass --token");let n=await t.validateTokenOutcome({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug});if(n==="usable")return r;let o=n;try{return await t.resolveToken({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,authFilePath:e.authFilePath})}catch(s){throw new Error(`Linzumi MCP token was rejected by the server and re-mint failed: ${s instanceof Error?s.message:String(s)}`)}}function E(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}async function X_(e){try{return E(await e)}catch(t){let r=t instanceof Error?t.message:String(t),n=r.match(/failed: ([a-z0-9_]+)(?: detail=(.+))?$/);if(n===null)return E({error:r});let[,o,s]=n;return E(s===void 0?{error:o??r}:{error:o??r,detail:s})}}function Cl(e){let t=new Map;for(let r=0;r<e.length;r+=1){let n=e[r];if(n===void 0)continue;if(!n.startsWith("--"))throw new Error(`unexpected argument ${n}`);let o=n.slice(2),s=oE.get(o);if(s===void 0)throw new Error(`unsupported option --${o}`);if(s.kind==="boolean"){t.set(o,!0);continue}let i=e[r+1];if(i===void 0||i.startsWith("--"))throw new Error(`--${o} requires a value`);t.set(o,i),r+=1}return t}function re(e,t){let r=e.get(t);return typeof r=="string"&&r.trim()!==""?r:void 0}function Al(e){switch(e){case void 0:return"text";case"voice":case"text":return e;default:throw new Error("--mode must be voice or text")}}function tv(e){switch(e){case void 0:return"all";case"all":case"coding":case"onboarding-discovery":return e;default:throw new Error("--tool-scope must be all, coding, or onboarding-discovery")}}function Ml(e,t){let r=re(e,t);if(r===void 0)throw new Error(`--${t} is required`);return r}function vE(e){return e[0]==="mcp"?e.slice(1):e}async function bE(e){try{await Q_(vE(e))}catch(t){process.stderr.write(`linzumi mcp server failed: ${t instanceof Error?t.message:String(t)}
424
424
  `),process.exitCode=1}}var wE=process.argv[1]!==void 0&&import.meta.url===_E(process.argv[1]).href;wE&&bE(process.argv.slice(2));export{vE as mcpServerEntryArgs,bE as runMcpServerEntry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linzumi/cli",
3
- "version": "1.0.140",
3
+ "version": "1.0.142",
4
4
  "description": "Linzumi CLI \u2014 point a Codex agent at the real code on your laptop, with your team watching and steering from shared threads.",
5
5
  "type": "module",
6
6
  "bin": {