@imaegoo/dsh-llm-failure-command 0.0.0-stage → 1.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 iMaeGoo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # 模型调用失败恢复(llm-failure-command)
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
+ 当 DSH 的模型调用因为连接类错误失败时,自动执行一条可配置的命令,然后重试同一次请求。
4
+
5
+ 典型的用法是恢复 adb 端口转发:本机的模型代理监听 `33377` 端口,通过 adb forward 映射到手机上的服务。转发一旦断开,之后每一次模型调用都会失败,而修复动作就是重新执行一次 `adb forward`。这个插件把「重连 + 重试」做成自动的:
6
+
7
+ ```
8
+ 模型调用失败 → 执行命令 → 成功则重试请求 → 请求通过
9
+ ```
10
+
11
+ ## 安装
12
+
13
+ 在 DSH 的 **设置 → 插件 → 添加插件** 中填入包名:
14
+
15
+ ```
16
+ @imaegoo/dsh-llm-failure-command
17
+ ```
18
+
19
+ 装上后在 **设置 → 模型调用失败恢复** 里配置。
20
+
21
+ ## 设置
22
+
23
+ 打开 **设置 → 模型调用失败恢复**。所有字段修改后立即保存,没有「保存」按钮。
24
+
25
+ | 字段 | 默认值 | 说明 |
26
+ | --- | --- | --- |
27
+ | 启用 | 开 | 关闭后插件完全不介入,失败照常抛出 |
28
+ | 设备序列号 | 空 | `adb devices` 第一列的那个序列号;单台设备可留空,多台时必填 |
29
+ | 本地端口 | `33377` | 模型代理监听的端口,转发到的手机端口与之相同 |
30
+ | 要执行的命令 | 空 | 留空则用上面两项拼出 `adb [-s 序列号] forward tcp:<端口> tcp:<端口>`;填写则忽略上面两项,原样交给系统 shell 执行 |
31
+ | 命令超时 | 15000 ms | 超时后会连同子进程树一起结束 |
32
+ | 每次失败最多重试 | 1 | 同一个 step 内最多触发几次修复;`0` 等同于关闭 |
33
+
34
+ 序列号和端口是分开的字段,所以换手机或换端口时改一个字段就行,不用重写整条命令。需要做别的事情(重启服务、重连隧道等)时,把「要执行的命令」填上,它优先于序列号和端口。
35
+
36
+ 页面上的 **立即执行一次** 会真实跑一次命令并显示输出,方便先确认命令本身可用;**恢复默认** 把所有项还原。
37
+
38
+ 配置存放在 `~/.dsh/llm-failure-command.json`(可用 `DSH_HOME` 覆盖目录)。
39
+
40
+ > 序列号会进入 shell,所以只接受字母、数字、点、下划线、冒号和连字符。含引号或分号的值会被拒绝,而不是转义后拼进去。
41
+
42
+ ## 哪些失败会触发
43
+
44
+ 只有连接类错误才会触发,因为这些才是重跑命令能修好的:
45
+
46
+ `TRANSPORT`、`TIMEOUT`、`SERVER`、`RATE_LIMIT`、`UNKNOWN`、`PI_AI_ERROR`
47
+
48
+ **不会**触发的是配置类错误——`AUTH`、`INVALID_CREDENTIAL`、`CONTEXT_WINDOW_EXCEEDED`、`QUOTA`、`INVALID_REQUEST` 等。同一次请求再发一遍仍然会失败,执行命令只会白等。
49
+
50
+ ## 实现要点
51
+
52
+ - 挂的是 `agent/request-error` 瀑布钩子。返回 `{ kind: "retry" }` 会让 agent loop 重开 step、重新发起这次请求;返回 `undefined` 则保持失败终止。
53
+ - 用 `prepend: true` 注册。内置的 `@deepseek-ai/dsh-llm-retry` 也监听同一个钩子,而对 `TRANSPORT` 这类可重试错误码它**不会**先问下一个监听器,而是自己先退避重试 5 次(500ms→10s)。如果排在它后面,修复动作要等好几分钟才轮到。
54
+ - 命令失败时不声称修复成功,直接 `next()` 把决定权交回去,保留原本的失败信息。
55
+ - 每个 step 的尝试次数有上限,避免命令无效时无限重试;`session/event` 的 `step/start` 与 `turn/end` 会重置该 session 的计数。
56
+ - 命令用 `spawn(command, { shell: true })` 执行。这样 Windows 上走的是 `cmd.exe /d /s /c <命令>` 且不重新转义引号,命令行原样到达 shell;超时时用 `taskkill /T` 结束整个进程树。
57
+
58
+ ## 文件
59
+
60
+ | 文件 | 作用 |
61
+ | --- | --- |
62
+ | `lib/index.js` | 宿主插件:钩子、命令触发、设置 HTTP 接口 |
63
+ | `lib/config.js` | `~/.dsh/llm-failure-command.json` 的读写与校验 |
64
+ | `lib/run-command.js` | 带超时的单次命令执行 |
65
+ | `lib/client.js` | 设置页(`settings.section` 槽位) |
66
+ | `test/harness.mjs` | 离线单测:命令执行、配置、钩子决策、设置接口、客户端包 |
67
+ | `test/e2e-cordis.mjs` | 真实 Cordis 端到端:验证 `prepend` 顺序,以及「修复后请求成功」 |
68
+ | `test/render.mjs` | 用最小 React 替身渲染真实设置页,检查字段、开关、按钮与错误提示 |
69
+
70
+ ## 测试
71
+
72
+ ```bash
73
+ npm test # harness + render
74
+ ```
75
+
76
+ `test/e2e-cordis.mjs` 需要一份解包出来的 DSH 运行时,默认指向本机路径;改路径见文件开头的 `DSH_MODULES`:
77
+
78
+ ```bash
79
+ node test/e2e-cordis.mjs
80
+ ```
@@ -0,0 +1,15 @@
1
+ # llm-failure-command — one host row.
2
+ #
3
+ # The plugin watches the agent loop's `agent/request-error` waterfall and, when a
4
+ # model request fails with a connection-class error, runs the operator's repair
5
+ # command and asks the loop to retry the same request. The command, its timeout,
6
+ # and the retry budget live in the "模型调用失败恢复" settings section, which the
7
+ # browser half registers.
8
+ #
9
+ # Installing this package as a profile bundle adds this row; the package name is
10
+ # resolved by the Loader from the profile's node_modules.
11
+ # `name` is quoted because a leading `@` is a reserved YAML indicator: an
12
+ # unquoted value may not start with it.
13
+ - insert:
14
+ - id: llm-failure-command
15
+ name: '@imaegoo/dsh-llm-failure-command'
package/lib/client.js ADDED
@@ -0,0 +1,395 @@
1
+ /*
2
+ * The in-GUI settings section for the model-failure recovery plugin.
3
+ *
4
+ * Registers one page under Settings where the repair command, its switch, and
5
+ * its limits live, plus the outcome of the last run. Every field saves itself;
6
+ * the buttons are "run now" and "restore defaults". The page talks to
7
+ * `/llm-failure-command/api/state`, which the host half serves.
8
+ *
9
+ * React comes from the browser module table and the styling uses dsw theme
10
+ * tokens, so the page follows the harness light and dark themes.
11
+ *
12
+ * IMPORTANT — everything lives inside the factory below.
13
+ *
14
+ * The host concatenates several client bundles into ONE classic script. A
15
+ * top-level `const` here is therefore a global of that shared script, and a name
16
+ * another concatenated package also declares raises `Identifier 'X' has already
17
+ * been declared`. That SyntaxError stops the whole script, so every package in
18
+ * the batch fails to register — the failure reads as
19
+ * "loaded without registering ... via __ModuleLoader__.load".
20
+ */
21
+ (window.__ModuleLoader__)?.load({
22
+ id: "@imaegoo/dsh-llm-failure-command",
23
+ factory(require) {
24
+ const React = require("react");
25
+ const h = React.createElement;
26
+ const { useCallback, useEffect, useRef, useState } = React;
27
+
28
+ const CSS = `
29
+ .lfc { display: flex; flex-direction: column; gap: 14px; padding: 4px 0 24px; max-width: 620px; min-width: 0; }
30
+ .lfc, .lfc * { box-sizing: border-box; }
31
+ .lfc h3 { margin: 0; font-size: 15px; font-weight: 600; color: var(--dsw-alias-label-primary); }
32
+ .lfc p { margin: 0; font-size: 13px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }
33
+ .lfc-card { display: flex; flex-direction: column; gap: 10px; padding: 14px 16px; min-width: 0;
34
+ border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md);
35
+ background: var(--dsw-alias-bg-layer-1); }
36
+ .lfc-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;
37
+ font-size: 13px; min-width: 0; color: var(--dsw-alias-label-primary); }
38
+ .lfc-row > span:first-child { flex: none; }
39
+ .lfc-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
40
+ .lfc-field > span { font-size: 12.5px; color: var(--dsw-alias-label-secondary); }
41
+ .lfc-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
42
+ .lfc input[type=text], .lfc input[type=number] { width: 100%; height: 34px; padding: 0 10px; font: inherit; font-size: 13px; min-width: 0;
43
+ font-family: ui-monospace, Menlo, monospace;
44
+ color: var(--dsw-alias-label-primary); background: var(--dsw-specific-input-major, var(--dsw-alias-bg-layer-2));
45
+ border: 0.5px solid var(--dsw-alias-border-l4); border-radius: var(--dsw-radius-sm); outline: none; }
46
+ .lfc input[type=number] { font-family: inherit; }
47
+ .lfc input:focus { border-color: var(--dsw-alias-state-business-primary);
48
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--dsw-alias-state-business-primary) 18%, transparent); }
49
+ .lfc-toggle { display: inline-flex; align-items: center; flex: none; cursor: pointer; }
50
+ .lfc-toggle input { position: absolute; opacity: 0; width: 0; height: 0; }
51
+ .lfc-toggle i { width: 38px; height: 22px; border-radius: 999px; background: var(--dsw-alias-border-l4);
52
+ position: relative; transition: background .15s ease; }
53
+ .lfc-toggle i::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px;
54
+ border-radius: 50%; background: var(--dsw-alias-label-primary); transition: transform .15s ease; }
55
+ .lfc-toggle input:checked + i { background: var(--dsw-alias-state-business-primary); }
56
+ .lfc-toggle input:checked + i::after { transform: translateX(16px); background: var(--dsw-alias-label-primary-foreground, #fff); }
57
+ .lfc-toggle input:disabled + i { opacity: .5; cursor: default; }
58
+ .lfc-toggle input:focus-visible + i { outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-alias-state-business-primary); outline-offset: 2px; }
59
+ .lfc-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
60
+ .lfc button { height: 32px; padding: 0 14px; font: inherit; font-size: 13px; border-radius: var(--dsw-radius-sm);
61
+ cursor: pointer; border: 0.5px solid var(--dsw-alias-border-l4);
62
+ background: transparent; color: var(--dsw-alias-label-primary); }
63
+ .lfc button:disabled { opacity: .55; cursor: default; }
64
+ .lfc button.primary { color: var(--dsw-alias-label-primary-foreground, #fff); font-weight: 500; border-color: transparent;
65
+ background: var(--dsw-alias-state-business-primary); }
66
+ .lfc button.primary:hover:not(:disabled) { filter: brightness(1.08); }
67
+ .lfc-pill { display: inline-flex; align-items: center; gap: 6px; padding: 1px 10px; border-radius: 999px;
68
+ font-size: 12px; border: 0.5px solid var(--dsw-alias-border-l2); color: var(--dsw-alias-label-secondary); }
69
+ .lfc-pill.on { color: var(--dsw-alias-state-success-primary);
70
+ border-color: color-mix(in srgb, var(--dsw-alias-state-success-primary) 55%, transparent); }
71
+ .lfc-pill.bad { color: var(--dsw-alias-state-error-primary);
72
+ border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 55%, transparent); }
73
+ .lfc-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
74
+ .lfc-note { font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-tertiary); }
75
+ .lfc-err { font-size: 12.5px; line-height: 1.5; color: var(--dsw-alias-state-error-primary); }
76
+ .lfc-out { margin: 0; padding: 10px 12px; max-height: 180px; overflow: auto; min-width: 0;
77
+ font-family: ui-monospace, Menlo, monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap;
78
+ word-break: break-word; color: var(--dsw-alias-label-secondary);
79
+ background: var(--dsw-alias-bg-layer-2); border-radius: var(--dsw-radius-sm); }
80
+ .lfc-kv { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; font-size: 12.5px; min-width: 0; }
81
+ .lfc-kv > span:first-child { flex: none; color: var(--dsw-alias-label-secondary); }
82
+ .lfc-kv > span:last-child { font-family: ui-monospace, Menlo, monospace; word-break: break-all;
83
+ color: var(--dsw-alias-label-primary); }
84
+ @media (max-width: 560px) { .lfc-grid { grid-template-columns: 1fr; } }
85
+ `;
86
+
87
+ /** API endpoint, resolved against the document so a mounted GUI still works. */
88
+ function apiUrl() {
89
+ return new URL("llm-failure-command/api/state", document.baseURI).href;
90
+ }
91
+
92
+ /** Render a stored timestamp as a coarse "how long ago". */
93
+ function relativeTime(ms) {
94
+ if (!ms) return "";
95
+ const seconds = Math.max(0, Math.floor((Date.now() - ms) / 1000));
96
+ if (seconds < 60) return "刚刚";
97
+ if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`;
98
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时前`;
99
+ return `${Math.floor(seconds / 86400)} 天前`;
100
+ }
101
+
102
+ /** The settings page: the switch, the command, its limits, and the last run. */
103
+ function LlmFailureCommand() {
104
+ const [snapshot, setSnapshot] = useState(null);
105
+ const [draft, setDraft] = useState({
106
+ enabled: true, command: "", deviceSerial: "", port: "", timeoutMs: "", maxRetries: "",
107
+ });
108
+ const [busy, setBusy] = useState(false);
109
+ const [error, setError] = useState("");
110
+ const [notice, setNotice] = useState("");
111
+
112
+ /** Pending auto-save for the text fields. */
113
+ const saveTimer = useRef(undefined);
114
+ const draftRef = useRef(draft);
115
+ draftRef.current = draft;
116
+ /** True while the operator has edits that are not saved yet. */
117
+ const dirty = useRef(false);
118
+
119
+ /**
120
+ * Adopt a host snapshot.
121
+ *
122
+ * The form follows the host whenever the operator is not editing it, so
123
+ * reopening the page always shows the stored configuration.
124
+ */
125
+ const applySnapshot = useCallback((next) => {
126
+ setSnapshot(next);
127
+ if (dirty.current) return;
128
+ setDraft({
129
+ enabled: next.config.enabled,
130
+ command: next.config.command,
131
+ deviceSerial: next.config.deviceSerial,
132
+ port: String(next.config.port),
133
+ timeoutMs: String(next.config.timeoutMs),
134
+ maxRetries: String(next.config.maxRetries),
135
+ });
136
+ }, []);
137
+
138
+ const refresh = useCallback(async () => {
139
+ try {
140
+ const response = await fetch(apiUrl(), { headers: { accept: "application/json" } });
141
+ if (!response.ok) return;
142
+ applySnapshot(await response.json());
143
+ } catch {
144
+ // Keep the last known state; the next poll retries.
145
+ }
146
+ }, [applySnapshot]);
147
+
148
+ /** Send one patch. A rejected field leaves the draft for correction. */
149
+ const save = useCallback(async (patch, options = {}) => {
150
+ try {
151
+ const response = await fetch(apiUrl(), {
152
+ method: "POST",
153
+ headers: { "content-type": "application/json" },
154
+ body: JSON.stringify(patch),
155
+ });
156
+ const payload = await response.json();
157
+ if (!response.ok) {
158
+ setError(payload.error ?? "保存失败");
159
+ return null;
160
+ }
161
+ setError("");
162
+ if (options.announce === true) {
163
+ setNotice("已保存");
164
+ window.setTimeout(() => setNotice(""), 1600);
165
+ }
166
+ dirty.current = false;
167
+ applySnapshot(payload);
168
+ return payload;
169
+ } catch (err) {
170
+ setError(err?.message || "无法访问插件接口");
171
+ return null;
172
+ }
173
+ }, [applySnapshot]);
174
+
175
+ const scheduleSave = useCallback(() => {
176
+ if (saveTimer.current !== undefined) window.clearTimeout(saveTimer.current);
177
+ saveTimer.current = window.setTimeout(() => {
178
+ saveTimer.current = undefined;
179
+ const current = draftRef.current;
180
+ void save({
181
+ command: current.command,
182
+ deviceSerial: current.deviceSerial,
183
+ port: current.port,
184
+ timeoutMs: current.timeoutMs,
185
+ maxRetries: current.maxRetries,
186
+ });
187
+ }, 700);
188
+ }, [save]);
189
+
190
+ /** Run the command now, so the operator can verify it before relying on it. */
191
+ const runNow = useCallback(async () => {
192
+ setBusy(true);
193
+ setError("");
194
+ try {
195
+ await save({ action: "test" });
196
+ } finally {
197
+ setBusy(false);
198
+ }
199
+ }, [save]);
200
+
201
+ /** Restore the shipped defaults. */
202
+ const reset = useCallback(async () => {
203
+ setBusy(true);
204
+ setError("");
205
+ dirty.current = false;
206
+ try {
207
+ await save({ action: "reset" }, { announce: true });
208
+ } finally {
209
+ setBusy(false);
210
+ }
211
+ }, [save]);
212
+
213
+ /** The switch applies immediately: a disabled plugin needs no debounce. */
214
+ const toggle = useCallback((enabled) => {
215
+ dirty.current = true;
216
+ setDraft((current) => ({ ...current, enabled }));
217
+ void save({ enabled });
218
+ }, [save]);
219
+
220
+ const edit = (field, value) => {
221
+ dirty.current = true;
222
+ setDraft((current) => ({ ...current, [field]: value }));
223
+ scheduleSave();
224
+ };
225
+
226
+ useEffect(() => {
227
+ void refresh();
228
+ // A failed run's outcome is worth seeing without a manual reload.
229
+ const timer = window.setInterval(() => { void refresh(); }, 2500);
230
+ return () => window.clearInterval(timer);
231
+ }, [refresh]);
232
+
233
+ useEffect(() => () => {
234
+ if (saveTimer.current !== undefined) window.clearTimeout(saveTimer.current);
235
+ }, []);
236
+
237
+ if (snapshot === null) {
238
+ return h("div", { className: "lfc" }, h("style", null, CSS), h("p", null, "加载中…"));
239
+ }
240
+
241
+ const { runtime, status, limits } = snapshot;
242
+ const last = runtime.lastRun;
243
+ const running = runtime.running;
244
+
245
+ const statusCard = h("div", { className: "lfc-card" },
246
+ h("div", { className: "lfc-row" },
247
+ h("span", null, "状态"),
248
+ h("span", { className: "lfc-pill " + (snapshot.config.enabled ? "on" : "") },
249
+ h("span", { className: "lfc-dot" }),
250
+ snapshot.config.enabled ? "已启用" : "未启用")),
251
+ h("div", { className: "lfc-kv" },
252
+ h("span", null, "已触发"),
253
+ h("span", null, `${runtime.driven} 次`)),
254
+ h("div", { className: "lfc-kv" },
255
+ h("span", null, "成功重试"),
256
+ h("span", null, `${runtime.recovered} 次`)),
257
+ runtime.exhausted > 0
258
+ ? h("div", { className: "lfc-kv" },
259
+ h("span", null, "命令失败"),
260
+ h("span", null, `${runtime.exhausted} 次`))
261
+ : null,
262
+ runtime.recovered === 0 && runtime.driven === 0
263
+ ? h("p", { className: "lfc-note" }, "尚未触发过。模型调用失败时会自动执行下面的命令并重试请求。")
264
+ : null);
265
+
266
+ const form = h("div", { className: "lfc-card" },
267
+ h("label", { className: "lfc-row" },
268
+ h("span", null, "模型调用失败时自动执行命令"),
269
+ h("span", { className: "lfc-toggle" },
270
+ h("input", {
271
+ type: "checkbox",
272
+ checked: draft.enabled,
273
+ disabled: busy,
274
+ onChange: (event) => toggle(event.currentTarget.checked),
275
+ }),
276
+ h("i", null))),
277
+ h("div", { className: "lfc-grid" },
278
+ h("div", { className: "lfc-field" },
279
+ h("span", null, "设备序列号(可选)"),
280
+ h("input", {
281
+ type: "text",
282
+ value: draft.deviceSerial,
283
+ spellCheck: false,
284
+ autoComplete: "off",
285
+ placeholder: "留空表示当前唯一的设备",
286
+ onChange: (event) => edit("deviceSerial", event.currentTarget.value),
287
+ }),
288
+ h("span", { className: "lfc-note" },
289
+ "adb devices 里那一列。多台设备时必填,单台可留空。")),
290
+ h("div", { className: "lfc-field" },
291
+ h("span", null, "本地端口"),
292
+ h("input", {
293
+ type: "number",
294
+ value: draft.port,
295
+ min: limits.port.min,
296
+ max: limits.port.max,
297
+ step: 1,
298
+ disabled: busy,
299
+ onChange: (event) => edit("port", event.currentTarget.value),
300
+ }),
301
+ h("span", { className: "lfc-note" },
302
+ "模型代理监听的端口,转发到的手机端口与之相同。"))),
303
+ h("div", { className: "lfc-field" },
304
+ h("span", null, "要执行的命令"),
305
+ h("input", {
306
+ type: "text",
307
+ value: draft.command,
308
+ spellCheck: false,
309
+ autoComplete: "off",
310
+ placeholder: snapshot.effectiveCommand,
311
+ onChange: (event) => edit("command", event.currentTarget.value),
312
+ }),
313
+ h("span", { className: "lfc-note" },
314
+ draft.command.trim() === ""
315
+ ? `留空则按上面的序列号和端口拼出:${snapshot.effectiveCommand}`
316
+ : "已手动指定命令,上面的序列号与端口不再参与拼装。原样交给系统 shell 执行。")),
317
+ h("div", { className: "lfc-grid" },
318
+ h("div", { className: "lfc-field" },
319
+ h("span", null, "命令超时(毫秒)"),
320
+ h("input", {
321
+ type: "number",
322
+ value: draft.timeoutMs,
323
+ min: limits.timeoutMs.min,
324
+ max: limits.timeoutMs.max,
325
+ step: 500,
326
+ disabled: busy,
327
+ onChange: (event) => edit("timeoutMs", event.currentTarget.value),
328
+ })),
329
+ h("div", { className: "lfc-field" },
330
+ h("span", null, "每次失败最多重试"),
331
+ h("input", {
332
+ type: "number",
333
+ value: draft.maxRetries,
334
+ min: limits.maxRetries.min,
335
+ max: limits.maxRetries.max,
336
+ step: 1,
337
+ disabled: busy,
338
+ onChange: (event) => edit("maxRetries", event.currentTarget.value),
339
+ }))),
340
+ h("div", { className: "lfc-actions" },
341
+ h("button", {
342
+ type: "button",
343
+ className: "primary",
344
+ disabled: busy || running,
345
+ onClick: () => { void runNow(); },
346
+ }, running ? "执行中…" : "立即执行一次"),
347
+ h("button", {
348
+ type: "button",
349
+ disabled: busy || running,
350
+ onClick: () => { void reset(); },
351
+ }, "恢复默认"),
352
+ notice !== "" ? h("span", { className: "lfc-note" }, notice) : null),
353
+ error !== "" ? h("div", { className: "lfc-err" }, error) : null);
354
+
355
+ const lastCard = last === null
356
+ ? null
357
+ : h("div", { className: "lfc-card" },
358
+ h("div", { className: "lfc-row" },
359
+ h("span", null, "最近一次执行"),
360
+ h("span", { className: "lfc-pill " + (last.ok ? "on" : "bad") },
361
+ h("span", { className: "lfc-dot" }),
362
+ last.ok ? "成功" : last.timedOut ? "超时" : last.aborted ? "已取消" : `退出码 ${String(last.code)}`)),
363
+ h("div", { className: "lfc-kv" },
364
+ h("span", null, "时间"),
365
+ h("span", null, `${relativeTime(last.at)} · ${String(last.durationMs)}ms`)),
366
+ h("div", { className: "lfc-kv" },
367
+ h("span", null, "触发"),
368
+ h("span", null, last.reason === "manual" ? "手动执行" : last.reason)),
369
+ last.stdout !== "" ? h("pre", { className: "lfc-out" }, last.stdout) : null,
370
+ last.stderr !== "" ? h("pre", { className: "lfc-out" }, last.stderr) : null);
371
+
372
+ return h("div", { className: "lfc" },
373
+ h("style", null, CSS),
374
+ h("h3", null, "模型调用失败恢复"),
375
+ h("p", null,
376
+ "当模型调用因为连接类错误失败时,先执行下面这条命令,再重试同一次请求。适合用来恢复 adb 端口转发之类的外部依赖。"),
377
+ statusCard,
378
+ form,
379
+ lastCard,
380
+ h("p", { className: "lfc-note" }, `配置文件:${status.path}`));
381
+ }
382
+
383
+ return {
384
+ inject: ["slots"],
385
+ apply(ctx) {
386
+ ctx.slots.inject("settings.section", () => ctx.slots.register({
387
+ name: "settings.section",
388
+ id: "llm-failure-command",
389
+ order: 66,
390
+ label: "模型调用失败恢复",
391
+ }, LlmFailureCommand));
392
+ },
393
+ };
394
+ },
395
+ });
package/lib/config.js ADDED
@@ -0,0 +1,201 @@
1
+ /*
2
+ * Persistent configuration for the LLM-failure recovery plugin.
3
+ *
4
+ * Stored as JSON under the dsh home directory rather than in the profile's
5
+ * cordis patch: the host half then imports nothing but Node builtins, which is
6
+ * what lets the plugin live inside a profile whose node_modules cannot resolve
7
+ * any `@deepseek-ai/*` package.
8
+ */
9
+ import { randomBytes } from "node:crypto";
10
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { dirname, join } from "node:path";
13
+
14
+ /** ADB serial used when the operator has no strong preference. */
15
+ export const DEFAULT_SERIAL = "";
16
+
17
+ /** Default local port that the model proxy listens on. */
18
+ export const DEFAULT_PORT = 33377;
19
+
20
+ /** The command run when `command` is left empty: built from the serial and port. */
21
+ export function defaultCommand(serial, port) {
22
+ const target = serial.trim() === "" ? "" : `-s ${serial.trim()} `;
23
+ return `adb ${target}forward tcp:${String(port)} tcp:${String(port)}`;
24
+ }
25
+
26
+ /** Hard bounds applied to every stored value. */
27
+ export const LIMITS = Object.freeze({
28
+ timeoutMs: { min: 1000, max: 120_000 },
29
+ maxRetries: { min: 0, max: 10 },
30
+ port: { min: 1, max: 65_535 },
31
+ });
32
+
33
+ /** The serial the settings page offers as its placeholder. */
34
+ export const DEFAULTS = Object.freeze({
35
+ enabled: true,
36
+ command: "",
37
+ timeoutMs: 15_000,
38
+ maxRetries: 1,
39
+ deviceSerial: DEFAULT_SERIAL,
40
+ port: DEFAULT_PORT,
41
+ });
42
+
43
+ /** dsh home directory, matching where the harness keeps its own state. */
44
+ function dshHome() {
45
+ const explicit = process.env.DSH_HOME?.trim();
46
+ if (explicit) return explicit;
47
+ return join(homedir(), ".dsh");
48
+ }
49
+
50
+ /** Absolute path of the plugin's configuration file. */
51
+ export function configPath() {
52
+ return join(dshHome(), "llm-failure-command.json");
53
+ }
54
+
55
+ /**
56
+ * The command that will actually run.
57
+ *
58
+ * An explicit `command` always wins, so an operator can use any repair step at
59
+ * all. Left empty, the command is composed from the serial and port fields,
60
+ * which keeps the common case — one adb forward — editable field by field
61
+ * instead of as shell text.
62
+ * @param config - a complete configuration.
63
+ * @returns the command line handed to the shell.
64
+ */
65
+ export function resolveCommand(config) {
66
+ if (typeof config.command === "string" && config.command.trim() !== "") return config.command.trim();
67
+ return defaultCommand(config.deviceSerial, config.port);
68
+ }
69
+
70
+ /** Read the stored configuration, filling defaults for missing or invalid keys. */
71
+ export function readConfig() {
72
+ try {
73
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
74
+ return normalize(parsed);
75
+ } catch {
76
+ // A missing or unreadable file is a fresh install, not an error.
77
+ return { ...DEFAULTS };
78
+ }
79
+ }
80
+
81
+ /** Merge a patch into the stored configuration and return the result. */
82
+ export function writeConfig(patch) {
83
+ const next = normalize({ ...readConfig(), ...patch });
84
+ const file = configPath();
85
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
86
+ const tmp = `${file}.tmp`;
87
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
88
+ renameSync(tmp, file);
89
+ try {
90
+ chmodSync(file, 0o600);
91
+ } catch {
92
+ // Windows ignores POSIX modes; the file is already user-scoped.
93
+ }
94
+ return next;
95
+ }
96
+
97
+ /** The value a fresh install starts from, for a settings page's "reset" hint. */
98
+ export function defaultConfig() {
99
+ return { ...DEFAULTS };
100
+ }
101
+
102
+ /**
103
+ * Validate one incoming settings submission.
104
+ *
105
+ * Every field is optional so the page can save a single control. A rejected
106
+ * field names itself, so the page can show the message beside the form instead
107
+ * of silently keeping a stale value.
108
+ * @param input - the parsed request body.
109
+ * @returns the accepted patch.
110
+ * @throws {TypeError} naming the first rejected field.
111
+ */
112
+ export function validatePatch(input) {
113
+ const patch = {};
114
+
115
+ if (input.enabled !== undefined) {
116
+ if (typeof input.enabled !== "boolean") throw new TypeError("enabled 必须是布尔值");
117
+ patch.enabled = input.enabled;
118
+ }
119
+
120
+ if (input.command !== undefined) {
121
+ if (typeof input.command !== "string") throw new TypeError("command 必须是字符串");
122
+ const command = input.command.trim();
123
+ if (command.length > 4096) throw new TypeError("command 过长(最多 4096 字符)");
124
+ // An empty command is meaningful: it means "compose one from the fields".
125
+ patch.command = command;
126
+ }
127
+
128
+ if (input.deviceSerial !== undefined) {
129
+ if (typeof input.deviceSerial !== "string") throw new TypeError("deviceSerial 必须是字符串");
130
+ const serial = input.deviceSerial.trim();
131
+ if (serial.length > 256) throw new TypeError("deviceSerial 过长(最多 256 字符)");
132
+ // A serial reaches a shell, so anything outside ADB's own alphabet is
133
+ // refused rather than escaped: `adb -s` takes a host:port for TCP devices.
134
+ if (!/^[A-Za-z0-9._:-]*$/.test(serial)) {
135
+ throw new TypeError("deviceSerial 只能包含字母、数字、点、下划线、冒号和连字符");
136
+ }
137
+ patch.deviceSerial = serial;
138
+ }
139
+
140
+ if (input.port !== undefined) {
141
+ patch.port = readInteger(input.port, LIMITS.port, "port");
142
+ }
143
+
144
+ if (input.timeoutMs !== undefined) {
145
+ patch.timeoutMs = readInteger(input.timeoutMs, LIMITS.timeoutMs, "timeoutMs");
146
+ }
147
+
148
+ if (input.maxRetries !== undefined) {
149
+ patch.maxRetries = readInteger(input.maxRetries, LIMITS.maxRetries, "maxRetries");
150
+ }
151
+
152
+ const known = ["enabled", "command", "deviceSerial", "port", "timeoutMs", "maxRetries"];
153
+ const unknown = Object.keys(input).filter((key) => !known.includes(key));
154
+ if (unknown.length > 0) throw new TypeError(`未知字段:${unknown.join("、")}`);
155
+
156
+ return patch;
157
+ }
158
+
159
+ /** Coerce one bounded integer field, accepting the page's numeric strings. */
160
+ function readInteger(value, bounds, field) {
161
+ const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
162
+ if (typeof number !== "number" || !Number.isInteger(number)) {
163
+ throw new TypeError(`${field} 必须是整数`);
164
+ }
165
+ if (number < bounds.min || number > bounds.max) {
166
+ throw new TypeError(`${field} 必须在 ${bounds.min} 到 ${bounds.max} 之间`);
167
+ }
168
+ return number;
169
+ }
170
+
171
+ /** Coerce an arbitrary value into a complete, bounded configuration. */
172
+ function normalize(input) {
173
+ const source = typeof input === "object" && input !== null ? input : {};
174
+ const text = (value) => (typeof value === "string" ? value.trim() : "");
175
+
176
+ const command = text(source.command);
177
+ const deviceSerial = text(source.deviceSerial);
178
+ const port = Number(source.port);
179
+ const timeoutMs = Number(source.timeoutMs);
180
+ const maxRetries = Number(source.maxRetries);
181
+
182
+ return {
183
+ enabled: source.enabled !== false,
184
+ command: command.length > 4096 ? "" : command,
185
+ deviceSerial: deviceSerial.length > 256 ? DEFAULT_SERIAL : deviceSerial,
186
+ port: Number.isInteger(port) && port >= LIMITS.port.min && port <= LIMITS.port.max
187
+ ? port
188
+ : DEFAULTS.port,
189
+ timeoutMs: Number.isInteger(timeoutMs) && timeoutMs >= LIMITS.timeoutMs.min && timeoutMs <= LIMITS.timeoutMs.max
190
+ ? timeoutMs
191
+ : DEFAULTS.timeoutMs,
192
+ maxRetries: Number.isInteger(maxRetries) && maxRetries >= LIMITS.maxRetries.min && maxRetries <= LIMITS.maxRetries.max
193
+ ? maxRetries
194
+ : DEFAULTS.maxRetries,
195
+ };
196
+ }
197
+
198
+ /** A short random tag, so a settings write is attributable in logs. */
199
+ export function revision() {
200
+ return randomBytes(6).toString("base64url");
201
+ }
package/lib/index.js ADDED
@@ -0,0 +1,343 @@
1
+ /*
2
+ * LLM-failure recovery: run a command when a model call fails, then retry.
3
+ *
4
+ * The motivating case is a local model proxy that listens on a host port which
5
+ * an adb port forward maps onto a phone. When the forward is lost every model
6
+ * call fails with a transport error, and the fix is a single `adb forward`
7
+ * command: run it, then let the loop try the same request again.
8
+ *
9
+ * Wiring: `agent/request-error` is a waterfall dispatched by the agent loop
10
+ * after a model request produced a terminal error finish. A listener that
11
+ * returns `{ kind: "retry" }` makes the loop reopen the step and re-dispatch
12
+ * the request; `undefined` (or polling `next()`) leaves the failure terminal.
13
+ * The listener is registered with `prepend: true` because the built-in
14
+ * `llm-retry` policy also listens here and, for the codes this fails on
15
+ * (`TRANSPORT`, `TIMEOUT`, `SERVER`, `RATE_LIMIT`), does not poll `next()` until
16
+ * its own budget is exhausted — a repair that runs after five backoff attempts
17
+ * would arrive minutes late.
18
+ *
19
+ * This half imports nothing but Node builtins and the plugin's own modules: the
20
+ * profile's node_modules cannot resolve any `@deepseek-ai/*` package.
21
+ */
22
+ import { readConfig, resolveCommand, validatePatch, writeConfig, defaultConfig, LIMITS, configPath } from "./config.js";
23
+ import { runCommand } from "./run-command.js";
24
+
25
+ /** Stable Cordis plugin name. */
26
+ export const name = "llm-failure-command";
27
+
28
+ /** The settings page and its API vanish with the web server they extend. */
29
+ export const inject = ["webServer"];
30
+
31
+ /** Largest settings payload accepted from the browser. */
32
+ const MAX_BODY_BYTES = 64 * 1024;
33
+
34
+ /**
35
+ * Failure codes worth repairing. Anything else (a bad credential, an exceeded
36
+ * context window, a malformed request) is a configuration problem that the
37
+ * same request will reproduce, so running a command would only add latency.
38
+ * `UNKNOWN`/`PI_AI_ERROR` are included because an adapter that could not even
39
+ * classify a connection error reports one of them.
40
+ */
41
+ const REPAIRABLE_CODES = new Set([
42
+ "TRANSPORT",
43
+ "TIMEOUT",
44
+ "SERVER",
45
+ "RATE_LIMIT",
46
+ "UNKNOWN",
47
+ "PI_AI_ERROR",
48
+ ]);
49
+
50
+ /** How long a finished attempt record stays useful before it may be pruned. */
51
+ const ATTEMPT_STALE_MS = 30_000;
52
+
53
+ /** Bound on the per-step attempt ledger, so a long session cannot grow it. */
54
+ const ATTEMPT_LEDGER_LIMIT = 256;
55
+
56
+ /**
57
+ * Run a configured command after a failed model request and retry it.
58
+ *
59
+ * The plugin keeps no state that a restart must preserve beyond the settings
60
+ * file: the attempt ledger is per-step and self-expiring.
61
+ */
62
+ export function apply(ctx) {
63
+ const log = (message) => {
64
+ ctx.logger?.info?.(`llm-failure-command: ${message}`);
65
+ };
66
+ const warn = (message) => {
67
+ ctx.logger?.warn?.(`llm-failure-command: ${message}`);
68
+ };
69
+
70
+ /** Attempt counters keyed by agent/turn/step. */
71
+ const attempts = new Map();
72
+
73
+ /** How many repairs are in flight, so the page's "running" state survives overlap. */
74
+ let running = 0;
75
+
76
+ /** What the settings page renders: the stored configuration and what it has done. */
77
+ const runtime = {
78
+ lastRun: null,
79
+ driven: 0,
80
+ recovered: 0,
81
+ exhausted: 0,
82
+ };
83
+
84
+ /** Forget records that are stale, keeping the ledger bounded across a long session. */
85
+ function prune(now) {
86
+ if (attempts.size <= ATTEMPT_LEDGER_LIMIT) return;
87
+ for (const [key, entry] of attempts) {
88
+ if (now - entry.touchedAt > ATTEMPT_STALE_MS) attempts.delete(key);
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Run the stored command and record the outcome.
94
+ *
95
+ * @param options - `signal` cancels the run; `reason` labels the log line.
96
+ * @returns the run result, ready for the page.
97
+ */
98
+ async function repair(options = {}) {
99
+ const config = readConfig();
100
+ const command = resolveCommand(config);
101
+ const startedAt = Date.now();
102
+ running += 1;
103
+ try {
104
+ const result = await runCommand(command, {
105
+ timeoutMs: config.timeoutMs,
106
+ signal: options.signal,
107
+ });
108
+ const finishedAt = Date.now();
109
+ runtime.lastRun = {
110
+ at: finishedAt,
111
+ durationMs: finishedAt - startedAt,
112
+ command,
113
+ ok: result.ok,
114
+ code: result.code,
115
+ timedOut: result.timedOut,
116
+ aborted: result.aborted,
117
+ stdout: result.stdout,
118
+ stderr: result.stderr,
119
+ reason: options.reason ?? "manual",
120
+ };
121
+ if (result.ok) {
122
+ log(`${options.reason ?? "manual"}: rescued by \`${command}\` in ${String(finishedAt - startedAt)}ms`);
123
+ } else {
124
+ const detail = result.timedOut
125
+ ? `timed out after ${String(config.timeoutMs)}ms`
126
+ : result.aborted
127
+ ? "aborted"
128
+ : `exit ${String(result.code)}`;
129
+ warn(`${options.reason ?? "manual"}: \`${command}\` ${detail}`);
130
+ }
131
+ return runtime.lastRun;
132
+ } finally {
133
+ running -= 1;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Hand one failed request a repair and, when it worked, ask for a retry.
139
+ *
140
+ * A failed repair still polls `next()`: the built-in retry policy gets its
141
+ * turn, and the failure stays terminal when it declines.
142
+ */
143
+ ctx.on("agent/request-error", async (payload, next) => {
144
+ const { agent, turn, step, provider, failure, signal } = payload ?? {};
145
+ const config = readConfig();
146
+ if (!config.enabled || config.maxRetries === 0) return next();
147
+
148
+ const code = typeof failure?.code === "string" ? failure.code : "UNKNOWN";
149
+ if (!REPAIRABLE_CODES.has(code)) return next();
150
+ if (signal?.aborted) return next();
151
+
152
+ const agentId = typeof agent?.id === "string" ? agent.id : "unknown";
153
+ const key = `${agentId}:${String(turn)}:${String(step)}`;
154
+ const now = Date.now();
155
+ prune(now);
156
+
157
+ const used = attempts.get(key)?.count ?? 0;
158
+ if (used >= config.maxRetries) {
159
+ // This step has already spent its budget; a second repair is unlikely to
160
+ // help and would only stall the failure the operator needs to see.
161
+ return next();
162
+ }
163
+
164
+ attempts.set(key, { count: used + 1, touchedAt: now });
165
+
166
+ runtime.driven += 1;
167
+ warn(
168
+ `model call failed (provider=${String(provider)}, code=${code}, status=${String(failure?.status ?? "-")}); running repair command`,
169
+ );
170
+
171
+ const result = await repair({ signal, reason: `auto:${code}` });
172
+ if (signal?.aborted) return next();
173
+
174
+ if (!result.ok) {
175
+ runtime.exhausted += 1;
176
+ return next();
177
+ }
178
+
179
+ runtime.recovered += 1;
180
+ return { kind: "retry" };
181
+ }, { prepend: true });
182
+
183
+ /** A session's step boundary and its end both start a clean ledger for that session. */
184
+ ctx.on("session/event", (session, event) => {
185
+ if (event?.type !== "step/start" && event?.type !== "turn/end") return;
186
+ const sessionId = typeof session?.id === "string" ? session.id : undefined;
187
+ if (sessionId === undefined) return;
188
+ for (const key of attempts.keys()) {
189
+ if (key.startsWith(`${sessionId}:`)) attempts.delete(key);
190
+ }
191
+ });
192
+
193
+ /** The JSON the settings page renders from. */
194
+ function snapshot() {
195
+ const config = readConfig();
196
+ return {
197
+ config,
198
+ defaults: defaultConfig(),
199
+ limits: LIMITS,
200
+ // What an empty `command` will actually run, so the page can show it.
201
+ effectiveCommand: resolveCommand(config),
202
+ runtime: {
203
+ running: running > 0,
204
+ lastRun: runtime.lastRun,
205
+ driven: runtime.driven,
206
+ recovered: runtime.recovered,
207
+ exhausted: runtime.exhausted,
208
+ },
209
+ status: {
210
+ path: configPath(),
211
+ repairableCodes: [...REPAIRABLE_CODES],
212
+ },
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Apply one settings submission.
218
+ *
219
+ * Fields are saved as they arrive, so the page has no save button. The only
220
+ * actions apart from a plain save are `test` (run the command now) and
221
+ * `reset` (restore the shipped defaults).
222
+ */
223
+ async function applySettings(body) {
224
+ const { action, ...fields } = body;
225
+ if (action !== undefined && typeof action !== "string") {
226
+ throw new TypeError("action 必须是字符串");
227
+ }
228
+
229
+ let changed = false;
230
+ if (action === "reset") {
231
+ writeConfig(defaultConfig());
232
+ changed = true;
233
+ log("settings reset to defaults");
234
+ } else if (Object.keys(fields).length > 0) {
235
+ const patch = validatePatch(fields);
236
+ const before = readConfig();
237
+ const after = writeConfig(patch);
238
+ changed = JSON.stringify(before) !== JSON.stringify(after);
239
+ }
240
+
241
+ if (action === "test") {
242
+ await repair({ reason: "manual" });
243
+ }
244
+
245
+ return { ok: true, changed, ...snapshot() };
246
+ }
247
+
248
+ /** Guard against cross-origin writes: the page is same-origin with the API. */
249
+ function trusted(req) {
250
+ const origin = headerValue(req, "origin");
251
+ if (origin === undefined || origin === "") return true;
252
+ const host = headerValue(req, "host");
253
+ if (host === undefined) return false;
254
+ try {
255
+ return new URL(origin).host === host;
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+
261
+ async function handleState(req, res) {
262
+ if (!trusted(req)) {
263
+ writeJSON(res, 403, { error: "forbidden" });
264
+ return;
265
+ }
266
+ const method = (req.method ?? "GET").toUpperCase();
267
+ if (method === "GET") {
268
+ writeJSON(res, 200, snapshot());
269
+ return;
270
+ }
271
+ if (method !== "POST") {
272
+ writeJSON(res, 405, { error: "method not allowed" });
273
+ return;
274
+ }
275
+ try {
276
+ const body = await readJSON(req);
277
+ writeJSON(res, 200, await applySettings(body));
278
+ } catch (error) {
279
+ writeJSON(res, 400, { error: error instanceof Error ? error.message : String(error) });
280
+ }
281
+ }
282
+
283
+ ctx.effect(
284
+ () => ctx.webServer.register({ kind: "exact", path: "/llm-failure-command/api/state", handler: handleState }),
285
+ "llm-failure-command: settings api",
286
+ );
287
+
288
+ const initial = readConfig();
289
+ log(
290
+ `ready (enabled=${String(initial.enabled)}, maxRetries=${String(initial.maxRetries)}, command=${initial.command})`,
291
+ );
292
+ }
293
+
294
+ function headerValue(req, field) {
295
+ const raw = req.headers[field] ?? req.headers[field.toLowerCase()];
296
+ if (Array.isArray(raw)) return raw[0];
297
+ return typeof raw === "string" ? raw : undefined;
298
+ }
299
+
300
+ function writeJSON(res, status, body) {
301
+ res.writeHead(status, {
302
+ "content-type": "application/json; charset=utf-8",
303
+ "cache-control": "no-store",
304
+ });
305
+ res.end(JSON.stringify(body));
306
+ }
307
+
308
+ /** Read and parse a bounded JSON request body. */
309
+ function readJSON(req) {
310
+ return new Promise((resolve, reject) => {
311
+ const chunks = [];
312
+ let bytes = 0;
313
+ req.on("data", (chunk) => {
314
+ if (!Buffer.isBuffer(chunk)) return;
315
+ bytes += chunk.length;
316
+ if (bytes > MAX_BODY_BYTES) {
317
+ reject(new Error("请求体过大"));
318
+ return;
319
+ }
320
+ chunks.push(chunk);
321
+ });
322
+ req.on("end", () => {
323
+ const text = Buffer.concat(chunks).toString("utf8").trim();
324
+ if (text === "") {
325
+ resolve({});
326
+ return;
327
+ }
328
+ try {
329
+ const parsed = JSON.parse(text);
330
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
331
+ reject(new Error("请求体必须是 JSON 对象"));
332
+ return;
333
+ }
334
+ resolve(parsed);
335
+ } catch {
336
+ reject(new Error("请求体不是合法 JSON"));
337
+ }
338
+ });
339
+ req.on("error", () => {
340
+ reject(new Error("读取请求体失败"));
341
+ });
342
+ });
343
+ }
@@ -0,0 +1,163 @@
1
+ /*
2
+ * One-shot shell command execution for the recovery plugin.
3
+ *
4
+ * Node's own `child_process` is used rather than `ctx.shell`: that service is
5
+ * sandbox-confined, and a repair command must still run under the presets that
6
+ * deny writes. It is also not resolvable from a profile-installed package.
7
+ *
8
+ * The command runs through `shell: true`, which is the only portable way to
9
+ * hand a command LINE to a shell: on Windows that spawns
10
+ * `cmd.exe /d /s /c <command>` with `windowsVerbatimArguments` set, so the
11
+ * operator's own quoting reaches cmd unchanged instead of being re-escaped by
12
+ * Node's CRT rules.
13
+ */
14
+ import { spawn, spawnSync } from "node:child_process";
15
+
16
+ /** Bytes of each stream retained for the settings page; the rest is dropped. */
17
+ const STREAM_CAP_BYTES = 8192;
18
+
19
+ /**
20
+ * Run one shell command to completion with a hard timeout.
21
+ *
22
+ * Never rejects: an unusable command, a non-zero exit, and a timeout all
23
+ * resolve with a described result, because the caller is already handling a
24
+ * failure and must not be derailed by this one.
25
+ * @param command - the command line, run verbatim by the platform's shell.
26
+ * @param options - timeout, working directory, and an optional abort signal.
27
+ * @returns the exit status, whether it timed out, and captured output.
28
+ */
29
+ export function runCommand(command, options = {}) {
30
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15_000;
31
+ const signal = options.signal;
32
+
33
+ return new Promise((resolve) => {
34
+ if (signal?.aborted) {
35
+ resolve({
36
+ ok: false,
37
+ code: null,
38
+ signal: null,
39
+ timedOut: false,
40
+ aborted: true,
41
+ stdout: "",
42
+ stderr: "已取消",
43
+ });
44
+ return;
45
+ }
46
+
47
+ let stdout = "";
48
+ let stderr = "";
49
+ let timedOut = false;
50
+ let settled = false;
51
+ let timer;
52
+
53
+ /** Settle once, clearing the timer and the abort listener. */
54
+ const finish = (result) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ if (timer !== undefined) clearTimeout(timer);
58
+ signal?.removeEventListener?.("abort", onAbort);
59
+ resolve({
60
+ ok: result.ok === true,
61
+ code: result.code ?? null,
62
+ signal: result.signal ?? null,
63
+ timedOut: result.timedOut === true,
64
+ aborted: result.aborted === true,
65
+ stdout: result.stdout ?? "",
66
+ stderr: result.stderr ?? "",
67
+ });
68
+ };
69
+
70
+ /** Stop the command, taking its whole tree down on Windows. */
71
+ const stop = () => {
72
+ if (process.platform === "win32" && child?.pid !== undefined) {
73
+ // `cmd.exe` runs the real command as a grandchild, so killing the shell
74
+ // alone would leave the operator's process behind.
75
+ try {
76
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
77
+ windowsHide: true,
78
+ stdio: "ignore",
79
+ });
80
+ return;
81
+ } catch {
82
+ // Fall through to the direct kill below.
83
+ }
84
+ }
85
+ try {
86
+ child?.kill("SIGKILL");
87
+ } catch {
88
+ // The process is already gone; `close` settles the promise.
89
+ }
90
+ };
91
+
92
+ const onAbort = () => {
93
+ stop();
94
+ finish({ ok: false, code: null, timedOut: false, aborted: true, stdout, stderr });
95
+ };
96
+
97
+ let child;
98
+ try {
99
+ child = spawn(command, {
100
+ shell: true,
101
+ cwd: options.cwd,
102
+ windowsHide: true,
103
+ stdio: ["ignore", "pipe", "pipe"],
104
+ env: process.env,
105
+ });
106
+ } catch (error) {
107
+ finish({ ok: false, code: null, timedOut: false, aborted: false, stdout: "", stderr: describe(error) });
108
+ return;
109
+ }
110
+
111
+ timer = setTimeout(() => {
112
+ timedOut = true;
113
+ stop();
114
+ }, Math.max(1, timeoutMs));
115
+ timer.unref?.();
116
+
117
+ signal?.addEventListener?.("abort", onAbort, { once: true });
118
+
119
+ // Reading only what the page can show bounds memory if the command is chatty.
120
+ child.stdout?.on("data", (chunk) => {
121
+ stdout = append(stdout, chunk);
122
+ });
123
+ child.stderr?.on("data", (chunk) => {
124
+ stderr = append(stderr, chunk);
125
+ });
126
+ child.on("error", (error) => {
127
+ finish({
128
+ ok: false,
129
+ code: null,
130
+ timedOut,
131
+ aborted: false,
132
+ stdout,
133
+ stderr: append(stderr, Buffer.from(describe(error))),
134
+ });
135
+ });
136
+ child.on("close", (code, closeSignal) => {
137
+ finish({
138
+ ok: code === 0 && !timedOut,
139
+ code,
140
+ signal: closeSignal ?? null,
141
+ timedOut,
142
+ aborted: false,
143
+ stdout,
144
+ stderr,
145
+ });
146
+ });
147
+ });
148
+ }
149
+
150
+ /** Append a chunk, keeping at most {@link STREAM_CAP_BYTES} of decoded text. */
151
+ function append(text, chunk) {
152
+ if (text.length >= STREAM_CAP_BYTES) return text;
153
+ return (text + chunk.toString("utf8")).slice(0, STREAM_CAP_BYTES);
154
+ }
155
+
156
+ /** Render a thrown value without letting hostile coercion escape. */
157
+ function describe(value) {
158
+ try {
159
+ return value instanceof Error ? value.message : String(value);
160
+ } catch {
161
+ return "unknown error";
162
+ }
163
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@imaegoo/dsh-llm-failure-command",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.1",
4
+ "description": "Run a configurable shell command automatically when a model call fails, then retry the request (e.g. restore an adb port forward).",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "license": "MIT",
8
+ "author": "iMaeGoo",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+ssh://git@github.com/imaegoo/dsh-llm-failure-command.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/imaegoo/dsh-llm-failure-command/issues"
15
+ },
16
+ "homepage": "https://github.com/imaegoo/dsh-llm-failure-command#readme",
17
+ "exports": {
18
+ ".": "./lib/index.js",
19
+ "./client": "./lib/client.js",
20
+ "./package.json": "./package.json",
21
+ "./cordis.patch.yml": "./cordis.patch.yml"
22
+ },
23
+ "scripts": {
24
+ "test": "node test/patch.mjs && node test/harness.mjs && node test/render.mjs"
25
+ },
26
+ "devDependencies": {
27
+ "js-yaml": "^4.1.0"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "dsh": {
34
+ "bundle": {
35
+ "patch": "./cordis.patch.yml"
36
+ },
37
+ "client": {
38
+ "platform": "web",
39
+ "immediately": true
40
+ }
41
+ },
42
+ "files": [
43
+ "lib/**/*.js",
44
+ "cordis.patch.yml",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "engines": {
49
+ "node": ">=22.15"
50
+ },
51
+ "keywords": [
52
+ "dsh",
53
+ "dsh-plugin",
54
+ "deepseek-harness",
55
+ "cordis-plugin",
56
+ "adb",
57
+ "retry",
58
+ "recovery"
59
+ ]
60
+ }