@misakacloud/opencode-mux 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # OpenCode Mux
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenCode V2 插件:在独立的 tmux/psmux pane 中运行构建、测试和后台服务。人和模型可以查看同一个 pane;命令退出或工具等待超时后,仍可查看日志或重启任务。
4
+
5
+ ## 安装
6
+
7
+ 1. 安装 `tmux`(Linux/macOS)或 `psmux`(Windows),确保可执行文件在 OpenCode 的 `PATH` 上。
8
+ 2. 在项目或全局的 `opencode.jsonc` 中配置插件,再重启 OpenCode:
9
+
10
+ ```jsonc
11
+ {
12
+ "plugins": ["@misakacloud/opencode-mux"]
13
+ }
14
+ ```
15
+
16
+ 插件从 `ctx.options` 读取配置,无需另建 `mux.jsonc`。需要自定义时使用:
17
+
18
+ ```jsonc
19
+ {
20
+ "plugins": [
21
+ {
22
+ "package": "@misakacloud/opencode-mux",
23
+ "options": {
24
+ "preferred": "tmux",
25
+ "socketName": "opencode",
26
+ "stateDir": "/path/to/mux-state",
27
+ "defaultTimeoutMs": 120000,
28
+ "defaultTailLines": 50,
29
+ "statusTheme": "powerline"
30
+ }
31
+ }
32
+ ]
33
+ }
34
+ ```
35
+
36
+ 选项均可省略。`preferred` 指定优先探测的后端,不可用时会回退(Windows 默认优先 `psmux`,其他平台默认优先 `tmux`)。`socketName` 为复用器 socket 名;`stateDir` 为任务记录目录,相对路径以项目目录为基准。未指定时,优先使用 `OPENCODE_MUX_STATE_DIR`,否则用 `$XDG_STATE_HOME/opencode-mux` 或 `~/.local/state/opencode-mux`。`defaultTimeoutMs` 覆盖构建等待和服务停止的默认时限(分别为 120 秒和 2 秒),`defaultTailLines` 覆盖构建、服务和重启的默认尾部日志行数(分别为 80、30、30;设为 `0` 可禁用)。单次工具入参优先于全局默认值。
37
+
38
+ | 选项 | 默认值 | 用途 |
39
+ | --- | --- | --- |
40
+ | `statusTheme` | `powerline`(Windows/psmux 自动用 `ascii`) | `powerline` 为分段彩色底栏;`ascii` 使用纯文本分隔;`off` 不写入主题设置。 |
41
+
42
+ ## 工具
43
+
44
+ | 工具 | 用途 |
45
+ | --- | --- |
46
+ | `mux_run_build` | 传入 `name`、`command` 运行构建或测试。默认等待结束并返回状态、退出码和日志;设 `wait: false` 可立即返回。 |
47
+ | `mux_service` | 按 `name` 和 `cwd` 管理服务:`start`、`restart`、`stop`、`status`、`remove`。新服务需要 `command`;`stop` 默认发送中断,设 `force: true` 可在停止超时后关闭 pane。 |
48
+ | `mux_restart` | 通过 `id` 或名称重启构建或服务,可传入 `command` 替换原命令。 |
49
+ | `mux_logs` | 读取最近的日志,默认 `100` 行,可用 `lines` 覆盖。 |
50
+ | `mux_input` | 向仍活着的 pane 发送文本,包括驻留的 shell。默认追加回车;`enter: false` 只发送文本。 |
51
+ | `mux_remove` | 移除单个构建或服务。设 `session: true` 可关闭整个项目会话。 |
52
+ | `mux_list` | 默认只列出当前项目的任务。用 `all: true` 查看所有项目,或用 `cwd`、`role`、`status` 筛选。`pruneGone: true` 会先清理目录和角色范围内已丢失 pane 的记录,不受 `status` 筛选影响。 |
53
+
54
+ 运行构建和管理服务时,省略 `cwd` 使用当前项目目录。对于重启、日志和输入,`id` 最准确;仅提供 `name` 时会搜索所有目录,出现同名任务时会列出候选项,可追加 `role`、`cwd` 或改用 `id`。
55
+
56
+ ### 移除任务或关闭会话
57
+
58
+ - `mux_remove({ id: "<任务 ID>" })`:只移除指定的构建或服务;若 pane 已不存在,仍会清理任务记录。也可用 `name` 配合 `role`、`cwd` 定位。
59
+ - `mux_remove({ session: true, cwd: "." })`:关闭当前项目的整个会话,终止会话中的所有任务、断开已附加的终端,并清理该会话的全部任务记录。省略 `cwd` 时也使用当前项目。
60
+
61
+ ## 接手与排查
62
+
63
+ 1. 用 `mux_run_build` 运行例如 `bun run test`,或用 `mux_service` 的 `start` 启动开发服务器。
64
+ 2. 在普通终端运行结果里的 `attachCommand`,进入对应的 tmux/psmux 会话。按 `Ctrl-b` 然后 `d` 可解除附加,不会停止任务(使用默认键位时)。
65
+ 3. 构建失败时查看退出码和尾部日志;构建等待超时并不终止 pane。可用 `mux_logs` 继续查看或用 `mux_restart` 重试。服务不再需要时可先 `stop`;确认不要保留 pane 和记录后再 `remove`。
66
+
67
+ ### tmux 键位与人工接手
68
+
69
+ 在本机使用默认 socket 时,`byobu attach -t =<会话名>` 和 `tmux attach -t =<会话名>` 都能连接。mux 会话默认使用 Byobu 风格键位:F2 新建窗口,F3/F4 切换到上一个/下一个窗口,F6 脱离,F7 回看滚动历史,F8 重命名窗口;Alt+←/→ 也可以切换窗口。键位不影响其他会话。
70
+
71
+ 命令退出后,pane 默认保留交互式 shell;`mux_list` 用 `shell: true` 标记,任务状态和退出码仍反映原命令结果。AI 可以用 `mux_input` 设置 `enter: false` 预填命令,由人在终端检查后按回车。可在插件配置的 `options` 中分别关闭这两个功能;Windows/psmux 沿用原行为。
72
+
73
+ ```jsonc
74
+ "options": {
75
+ "keepShellOnExit": false,
76
+ "byobuKeys": false
77
+ }
78
+ ```
79
+
80
+ ### 退出与脱离
81
+
82
+ - 按 **F6** 只脱离会话,后台任务继续运行,驻留 shell 和日志也会保留。想稍后接着操作,就先按 F6,不要退出 shell。
83
+ - 在驻留 shell 中按 **Ctrl+D** 或执行 `exit`,tmux 会自动清理该 pane。窗口里的最后一个 pane 退出时,窗口也会关闭;最后一个窗口退出时,会话随之结束。
84
+ - 要主动关闭整个项目会话,可使用 OpenChamber 面板的关闭会话操作,或调用 `mux_remove({ session: true })`。这会终止会话中的任务,不只是脱离。
85
+
86
+ ### 会话外观
87
+
88
+ 主题只应用于 mux 项目会话:底栏左侧显示 `mux`,中间是窗口标签并高亮当前窗口,右侧显示会话名、日期和每秒更新的时钟。按 F2 新开的窗口也会套用主题。主题启用鼠标,可点击标签切换窗口、滚轮回看、拖动窗格边框。
89
+
90
+ `powerline` 适合支持彩色状态栏的 tmux 终端。`ascii` 保留窗口高亮,改用 `序号:名称` 和 `+` 分隔,不依赖特殊字体,适合 Windows/psmux 或偏好纯文本标签的终端。设 `statusTheme: "off"` 可保留终端复用器的外观配置;不会撤销已在旧会话上应用的主题。
package/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { default } from "./src/index"
2
+ export * from "./src/index"
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package.json",
2
3
  "name": "@misakacloud/opencode-mux",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "0.1.0",
5
+ "description": "OpenCode V2 plugin for running builds and background services in tmux/psmux",
6
+ "type": "module",
7
+ "main": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "index.ts",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "vitest run",
19
+ "build": "tsc --noEmit"
20
+ },
21
+ "keywords": [
22
+ "opencode",
23
+ "opencode-plugin",
24
+ "tmux",
25
+ "psmux",
26
+ "mux"
27
+ ],
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/chisaato/opencode-plugins.git",
31
+ "directory": "packages/mux"
32
+ },
33
+ "author": "chisaato",
34
+ "license": "MIT",
35
+ "dependencies": {
36
+ "@misakacloud/opencode-mux-core": "^0.1.0"
37
+ },
38
+ "peerDependencies": {
39
+ "@opencode/plugin": "^2.0.31"
40
+ },
41
+ "devDependencies": {
42
+ "@opencode/plugin": "2.0.31",
43
+ "@types/bun": "latest",
44
+ "@types/node": "^25.6.0",
45
+ "typescript": "^6.0.3",
46
+ "vitest": "^4.1.5"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ }
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { resolve } from "node:path"
2
+ import type { Plugin } from "@opencode/plugin"
3
+ import { createMuxManager, type MuxManagerOptions } from "@misakacloud/opencode-mux-core"
4
+ import { createMuxTools, MAX_MUX_INTEGER, type MuxToolDefaults } from "./tools"
5
+
6
+ export { createMuxTools } from "./tools"
7
+ export type { MuxToolDefaults } from "./tools"
8
+
9
+ type MuxPluginOptions = Pick<MuxManagerOptions,
10
+ "preferred" | "socketName" | "stateDir" | "keepShellOnExit" | "byobuKeys" | "statusTheme"> & MuxToolDefaults
11
+ type MuxPluginContext = {
12
+ tool: Pick<Plugin.Context["tool"], "transform">
13
+ location?: { directory?: string }
14
+ options?: unknown
15
+ }
16
+
17
+ function nonEmptyString(value: unknown): string | undefined {
18
+ return typeof value === "string" && value.trim() !== "" && !value.includes("\0") ? value : undefined
19
+ }
20
+
21
+ function nonNegativeInteger(value: unknown): number | undefined {
22
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= MAX_MUX_INTEGER
23
+ ? value : undefined
24
+ }
25
+
26
+ /** 读取内联选项;忽略未知字段与无效值,由工具或核心层提供默认值。 */
27
+ export function parseMuxOptions(options: unknown): MuxPluginOptions {
28
+ const values = options && typeof options === "object" ? options as Record<string, unknown> : {}
29
+ return {
30
+ preferred: values.preferred === "tmux" || values.preferred === "psmux" ? values.preferred : undefined,
31
+ socketName: nonEmptyString(values.socketName),
32
+ stateDir: nonEmptyString(values.stateDir),
33
+ keepShellOnExit: typeof values.keepShellOnExit === "boolean" ? values.keepShellOnExit : undefined,
34
+ byobuKeys: typeof values.byobuKeys === "boolean" ? values.byobuKeys : undefined,
35
+ statusTheme: values.statusTheme === "powerline" || values.statusTheme === "ascii" || values.statusTheme === "off"
36
+ ? values.statusTheme : undefined,
37
+ defaultTimeoutMs: nonNegativeInteger(values.defaultTimeoutMs),
38
+ defaultTailLines: nonNegativeInteger(values.defaultTailLines),
39
+ }
40
+ }
41
+
42
+ /** 注册工具时不启动复用器;首次执行工具时由核心层探测可用后端。 */
43
+ export const MuxPlugin = {
44
+ id: "opencode-mux",
45
+ async setup(ctx: MuxPluginContext) {
46
+ const cwd = resolve(ctx.location?.directory ?? process.cwd())
47
+ const { preferred, socketName, stateDir, keepShellOnExit, byobuKeys, statusTheme, ...defaults } = parseMuxOptions(ctx.options)
48
+ const manager = createMuxManager({
49
+ preferred, socketName, stateDir: stateDir && resolve(cwd, stateDir), keepShellOnExit, byobuKeys, statusTheme,
50
+ })
51
+ const tools = createMuxTools(manager, cwd, defaults)
52
+
53
+ await ctx.tool.transform((editor) => {
54
+ for (const tool of tools) {
55
+ if (!editor.list().some((entry) => entry.name === tool.name)) editor.add(tool)
56
+ }
57
+ })
58
+ },
59
+ } satisfies Plugin.Plugin
60
+
61
+ export default MuxPlugin
package/src/tools.ts ADDED
@@ -0,0 +1,220 @@
1
+ import { resolve } from "node:path"
2
+ import type {
3
+ ManagedTask, MuxManager, RunBuildOptions, ServiceActionOptions, ServiceActionResult,
4
+ TaskFilter, TaskRole, TaskStatus,
5
+ } from "@misakacloud/opencode-mux-core"
6
+
7
+ export const MAX_MUX_INTEGER = 2_147_483_647
8
+ const ROLES = ["build", "service"]
9
+ const STATUSES = ["running", "succeeded", "failed", "stopped", "gone"]
10
+ const ACTIONS = ["start", "restart", "stop", "status", "remove"]
11
+
12
+ export interface MuxToolDefaults {
13
+ defaultTimeoutMs?: number
14
+ defaultTailLines?: number
15
+ }
16
+
17
+ type ToolManager = Pick<MuxManager,
18
+ "runBuild" | "serviceAction" | "restartTask" | "removeTask" | "closeSession" | "captureLogs" | "sendInput"
19
+ | "listTasks" | "pruneGone" | "attachCommand">
20
+ type ToolContext = { sessionID?: string }
21
+ type Selector = { id?: string; name?: string; role?: TaskRole; cwd?: string }
22
+ type BuildInput = Omit<RunBuildOptions, "cwd" | "source" | "sessionId"> & { cwd?: string }
23
+ type ServiceInput = Omit<ServiceActionOptions, "cwd" | "source" | "sessionId"> & { cwd?: string; tailLines?: number }
24
+ type ListInput = { cwd?: string; all?: boolean; role?: TaskRole; status?: TaskStatus; pruneGone?: boolean }
25
+
26
+ const str = (description: string) => ({ type: "string", description })
27
+ const bool = (description: string) => ({ type: "boolean", description })
28
+ const integer = (description: string) => ({ type: "integer", minimum: 0, maximum: MAX_MUX_INTEGER, description })
29
+ const choices = (values: string[], description: string) => ({ type: "string", enum: values, description })
30
+ const name = str("任务名称。")
31
+ const cwd = str("工作目录;相对路径以当前项目目录为基准。")
32
+ const command = str("在独立终端 pane 中执行的命令。")
33
+ const role = choices(ROLES, "任务类型。")
34
+ const timeoutMs = integer("等待时限(毫秒);超时不会自动终止任务。")
35
+ const tailLines = integer("返回最近的日志行数;0 不抓取日志。")
36
+ const selector = { id: str("唯一任务 ID;提供后优先于名称。"), name, role, cwd }
37
+
38
+ type InputSchema = {
39
+ type: "object"
40
+ properties: Record<string, unknown>
41
+ required?: string[]
42
+ additionalProperties: false
43
+ }
44
+
45
+ function schema(properties: Record<string, unknown>, required?: string[]): InputSchema {
46
+ return { type: "object", properties, ...(required && { required }), additionalProperties: false }
47
+ }
48
+
49
+ function report(text: string, metadata: Record<string, unknown>) {
50
+ return { content: [{ type: "text" as const, text }], metadata }
51
+ }
52
+
53
+ function tool<T>(
54
+ name: string, description: string, input: InputSchema,
55
+ execute: (input: T, context?: ToolContext) => Promise<ReturnType<typeof report>>,
56
+ ) {
57
+ return { name, description, input, execute: (args: unknown, context?: ToolContext) => execute((args ?? {}) as T, context) }
58
+ }
59
+
60
+ function taskSummary(task: ManagedTask) {
61
+ const { id, name, role, cwd, status, exitCode, restartCount, muxSession, paneId, shell } = task
62
+ return { id, name, role, cwd, status, exitCode: exitCode ?? null, restartCount, muxSession, paneId, ...(shell && { shell }) }
63
+ }
64
+
65
+ type AttachedTask = ReturnType<typeof taskSummary> & { attachCommand: string }
66
+
67
+ function taskText(task: AttachedTask) {
68
+ const exit = task.exitCode === null ? "" : ` exitCode=${task.exitCode}`
69
+ return `[${task.status}] ${task.role} ${task.name} id=${task.id}${exit}${task.shell ? " shell=驻留" : ""} restartCount=${task.restartCount}`
70
+ + `\n cwd=${task.cwd} muxSession=${task.muxSession} paneId=${task.paneId}\n attach: ${task.attachCommand}`
71
+ }
72
+
73
+ /** 创建 V2 工具;宿主负责按 JSON Schema 校验入参。 */
74
+ export function createMuxTools(manager: ToolManager, projectDirectory: string, defaults: MuxToolDefaults = {}) {
75
+ const workingDirectory = (directory?: string) => resolve(projectDirectory, directory ?? ".")
76
+ const origin = (context?: ToolContext) => ({ source: "ai" as const, sessionId: context?.sessionID })
77
+ const attach = async (task: ManagedTask): Promise<AttachedTask> => ({
78
+ ...taskSummary(task), attachCommand: await manager.attachCommand(task),
79
+ })
80
+
81
+ // 名称可能横跨多个目录或角色,绝不猜测要操作哪个任务。
82
+ async function resolveTask({ id, name, role, cwd }: Selector) {
83
+ if (!id && !name) {
84
+ return { error: report("请提供任务 id 或 name。可先调用 mux_list 查找任务。", {
85
+ ok: false, error: "missing_selector",
86
+ }) }
87
+ }
88
+ const matches = id
89
+ ? (await manager.listTasks()).filter((task) => task.id === id)
90
+ : await manager.listTasks({ name, role, cwd: cwd === undefined ? undefined : workingDirectory(cwd) })
91
+ if (matches.length === 0) {
92
+ return { error: report(`未找到任务 ${id ?? name}。可调用 mux_list 核对任务。`, {
93
+ ok: false, error: "task_not_found",
94
+ }) }
95
+ }
96
+ if (matches.length > 1) {
97
+ const candidates = matches.map(taskSummary)
98
+ return { error: report(
99
+ `任务名称 ${name} 不唯一。请指定 id,或补充 role/cwd:\n`
100
+ + candidates.map((t) => `- id=${t.id} role=${t.role} cwd=${t.cwd} status=${t.status}`).join("\n"),
101
+ { ok: false, error: "ambiguous_task", candidates },
102
+ ) }
103
+ }
104
+ return { task: matches[0] }
105
+ }
106
+
107
+ async function actionReport(label: string, result: ServiceActionResult, lines: number, removed = false) {
108
+ const { ok, task, timedOut = false } = result
109
+ if (!task) return report(`${label}:未找到任务。`, { ok, status: "not_found", timedOut, tail: "" })
110
+
111
+ let tail = ""
112
+ let tailError: string | undefined
113
+ // 可选尾部日志不应让已完成的操作失败,例如读日志前 pane 被人工关闭。
114
+ if (!removed && task.status !== "gone" && !task.forceStopped && lines !== 0) {
115
+ try {
116
+ tail = await manager.captureLogs(task.id, lines)
117
+ } catch (error) {
118
+ tailError = error instanceof Error ? error.message : String(error)
119
+ }
120
+ }
121
+ const info = await attach(task)
122
+ const status = removed && ok ? "removed" : info.status
123
+ return report([
124
+ `${label}:${status}(ok=${ok})`,
125
+ taskText(info),
126
+ timedOut && "等待停止超时;pane 仍可附加,也可以重试停止。",
127
+ tailError && `未能获取尾部日志:${tailError}`,
128
+ tail && `日志尾部:\n${tail}`,
129
+ ].filter(Boolean).join("\n"), {
130
+ ...info, ok, status, timedOut, tail, ...(tailError ? { tailError } : {}),
131
+ })
132
+ }
133
+
134
+ return [
135
+ tool<BuildInput>("mux_run_build", "运行构建或测试;返回退出状态与日志,保留 pane 供人工查看或重试。",
136
+ schema({ name, command, cwd, wait: bool("是否等待命令退出;默认 true。"), timeoutMs, tailLines }, ["name", "command"]),
137
+ async ({ cwd, timeoutMs, tailLines, ...input }, context) => {
138
+ const result = await manager.runBuild({
139
+ ...input, cwd: workingDirectory(cwd), ...origin(context),
140
+ timeoutMs: timeoutMs ?? defaults.defaultTimeoutMs,
141
+ tailLines: tailLines ?? defaults.defaultTailLines,
142
+ })
143
+ const info = await attach(result.task)
144
+ return report([
145
+ taskText(info),
146
+ `exitCode=${info.exitCode ?? "未取得"} timedOut=${result.timedOut}`,
147
+ result.timedOut && "等待构建超时;pane 不会被终止,可人工附加查看或重试。",
148
+ result.tail && `日志尾部:\n${result.tail}`,
149
+ ].filter(Boolean).join("\n"), { ...info, ok: result.ok, timedOut: result.timedOut, tail: result.tail })
150
+ }),
151
+ tool<ServiceInput>("mux_service", "启动、重启、停止、查询或移除项目后台服务。",
152
+ schema({
153
+ action: choices(ACTIONS, "服务操作;remove 会移除 pane 和任务记录。"), name, command, cwd,
154
+ restartIfRunning: bool("start 时若已运行,是否重启;默认 false。"),
155
+ force: bool("stop 等待超时后是否强制关闭 pane;默认 false。"), timeoutMs, tailLines,
156
+ }, ["action", "name"]),
157
+ async ({ action, cwd, timeoutMs, tailLines, ...input }, context) => {
158
+ const result = await manager.serviceAction({
159
+ ...input, action, cwd: workingDirectory(cwd), ...origin(context),
160
+ timeoutMs: timeoutMs ?? defaults.defaultTimeoutMs,
161
+ })
162
+ return actionReport(`服务 ${action}`, result, tailLines ?? defaults.defaultTailLines ?? 30, action === "remove" && result.ok)
163
+ }),
164
+ tool<Selector & { command?: string; tailLines?: number }>("mux_restart", "按 ID 或无歧义的名称重启已有构建或服务,可替换命令。",
165
+ schema({ ...selector, command, tailLines }),
166
+ async ({ command, tailLines, ...selector }, context) => {
167
+ const found = await resolveTask(selector)
168
+ if (found.error) return found.error
169
+ const result = await manager.restartTask(found.task.id, { command, ...origin(context) })
170
+ return actionReport("重启任务", result, tailLines ?? defaults.defaultTailLines ?? 30)
171
+ }),
172
+ tool<Selector & { lines?: number }>("mux_logs", "按 ID 或无歧义的名称抓取任务日志。",
173
+ schema({ ...selector, lines: integer("返回最近的日志行数;默认 100。") }),
174
+ async ({ lines = 100, ...selector }) => {
175
+ const found = await resolveTask(selector)
176
+ if (found.error) return found.error
177
+ const logs = await manager.captureLogs(found.task.id, lines)
178
+ const info = await attach(found.task)
179
+ return report(`${taskText(info)}\n日志:\n${logs}`, { ...info, ok: true, logs })
180
+ }),
181
+ tool<Selector & { input: string; enter?: boolean }>("mux_input", "向仍活着的终端 pane 发送字面文本,包括任务退出后驻留的 shell。设 enter: false 可由 AI 输入,人在终端确认后手动按回车。",
182
+ schema({ ...selector, input: str("发送的文本。可为空,仅发送回车。"), enter: bool("是否发送回车;默认 true。") }, ["input"]),
183
+ async ({ input, enter = true, ...selector }) => {
184
+ const found = await resolveTask(selector)
185
+ if (found.error) return found.error
186
+ await manager.sendInput(found.task.id, input, { enter })
187
+ return report(`已向任务 ${found.task.id} 发送输入(enter=${enter})。`,
188
+ { ...taskSummary(found.task), ok: true, enter })
189
+ }),
190
+ tool<Selector & { session?: boolean }>("mux_remove", "移除单个构建或服务任务,关闭其 pane 并删除记录。危险:session: true 会关闭 cwd 对应的整个 mux 会话,终止会话中的所有任务并使已附加的终端脱离。",
191
+ schema({ ...selector, session: bool("关闭整个项目会话;仅使用 cwd 定位,省略 cwd 时使用当前项目。") }),
192
+ async ({ session, ...selector }) => {
193
+ if (session) {
194
+ const result = await manager.closeSession({ cwd: workingDirectory(selector.cwd) })
195
+ return report(`已关闭会话 ${result.sessionName},清理 ${result.removed} 条任务记录。`, result)
196
+ }
197
+ const found = await resolveTask(selector)
198
+ if (found.error) return found.error
199
+ const { ok, task } = await manager.removeTask(found.task.id)
200
+ if (!ok || !task) return report(`未找到任务 ${found.task.id}。`, { ok: false, error: "task_not_found" })
201
+ return report(`已移除任务 ${task.id}。`, { ...taskSummary(task), ok, status: "removed" })
202
+ }),
203
+ tool<ListInput>("mux_list", "列出受管任务,默认仅当前项目;可清理已丢失 pane 的记录。",
204
+ schema({
205
+ cwd, all: bool("未指定 cwd 时,是否查看所有项目。"), role, status: choices(STATUSES, "筛选任务状态。"),
206
+ pruneGone: bool("先清理目录和角色范围内的 gone 记录,不受 status 筛选影响。"),
207
+ }),
208
+ async ({ cwd, all, role, status, pruneGone }) => {
209
+ const filter: TaskFilter = {
210
+ cwd: cwd === undefined && all ? undefined : workingDirectory(cwd), role,
211
+ }
212
+ const pruned = pruneGone ? await manager.pruneGone(filter) : []
213
+ const tasks = await Promise.all((await manager.listTasks({ ...filter, status })).map(attach))
214
+ return report([
215
+ `任务范围:${filter.cwd ?? "所有项目"};共 ${tasks.length} 个任务${pruneGone ? `,清理 ${pruned.length} 条记录` : ""}。`,
216
+ ...tasks.map(taskText),
217
+ ].join("\n"), { ok: true, cwd: filter.cwd ?? null, total: tasks.length, tasks, pruned: pruned.map(taskSummary) })
218
+ }),
219
+ ]
220
+ }