pi-web-ui 0.113.1 → 0.114.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/CHANGELOG.md +71 -1
- package/README.md +187 -316
- package/README.zh-CN.md +227 -299
- package/README.zh-TW.md +227 -299
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +4081 -4041
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2419 -1174
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +69 -13
- package/dist/server/canvas/canvas-agent-tool.js +68 -18
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +519 -202
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +110 -24
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +351 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +830 -0
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +529 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +996 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +84 -27
- package/dist/server/dsh/dsh-agent-service.js +282 -159
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/eval-tool.js +135 -135
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +38 -26
- package/dist/server/global-loader.js +40 -2
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +285 -255
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/patch-bash-process.js +125 -0
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/persona-chain.js +8 -8
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +288 -94
- package/dist/server/preset-fields.js +56 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +113 -72
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +199 -106
- package/dist/server/request-context.js +164 -0
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/schedule-agent-tool.js +39 -21
- package/dist/server/scheduler-tasks.js +106 -55
- package/dist/server/scm-commitmsg.js +10 -10
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +273 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/setup-page.js +620 -620
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/text-quote.js +9 -0
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +48 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +357 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/vision-bridge.js +18 -18
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +148 -0
- package/docs/device-desktop.md +48 -0
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +5 -2
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -676
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +11 -1
- package/themes/aetheris.css +501 -607
- package/themes/ayu-light.css +116 -140
- package/themes/bases/flow-base.css +1357 -1363
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +688 -687
- package/themes/bases/zhupi-base.css +660 -659
- package/themes/catppuccin-latte.css +119 -142
- package/themes/catppuccin.css +116 -147
- package/themes/claude-code-dark.css +147 -146
- package/themes/codex.css +114 -138
- package/themes/cyberpunk.css +50 -108
- package/themes/dark-teal.css +264 -265
- package/themes/dazzle.css +38 -108
- package/themes/everforest-light.css +115 -138
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -138
- package/themes/gruvbox-light.css +115 -138
- package/themes/kanagawa-lotus.css +115 -138
- package/themes/md-preview.css +24 -234
- package/themes/mist.css +166 -186
- package/themes/nord.css +107 -138
- package/themes/one-dark.css +106 -139
- package/themes/paper.css +174 -186
- package/themes/rose-pine-dawn.css +114 -138
- package/themes/sakura.css +166 -186
- package/themes/solarized-light.css +114 -137
- package/themes/tokyo-night.css +115 -146
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -186
- package/themes/zhujian-dark.css +115 -114
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -114
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
- package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
- package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
- package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
- package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
- package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
- package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
- package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
- package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
- package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
- package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
- package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
- package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
- package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
- package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
- package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
- package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
- package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/desktop-YguLbrX1.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-BPvpea8t.js +85 -0
- package/web/dist/assets/index-D6u8xH0o.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +42 -35
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
- package/web/dist/assets/index-ByiO9f-N.js +0 -2008
- package/web/dist/assets/index-ycGLh4a4.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -1,3 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* message-window — 历史消息的服务端「按需加载」(尾部窗口 + 往前翻页)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么在传输层做:四个引擎(pi / DSH / claude / durable)各有一条发快照的
|
|
5
|
+
* 路径,各自实现窗口化必然三处改动、以后新引擎还会漏。这里挂在 `server/index.ts`
|
|
6
|
+
* 每个连接唯一的 `send` 漏斗上,引擎侧零改动,所有引擎(含第三方扩展)口径一致。
|
|
7
|
+
*
|
|
8
|
+
* 只做三件事:
|
|
9
|
+
* 1. `snapshot`:把 `state.messages`(全量)裁成尾部窗口,回填
|
|
10
|
+
* `historyStart`(窗口首条在全量里的下标)、`historyTotal` 与 `historyGeneration`;
|
|
11
|
+
* 2. `snapshot_delta`:把新追加的消息并入缓存,并回填同样的窗口元数据;
|
|
12
|
+
* 3. `load_earlier_messages`:把窗口往前扩一页,回 `earlier_messages`。
|
|
13
|
+
*
|
|
14
|
+
* 刻意**不碰** `rev` / `baseRev`:各引擎的增量语义(DSH 的 baseRev 算法、
|
|
15
|
+
* durable 的消息结构)完全不同,一旦在这里改写版本号就会把它们的自愈逻辑搞坏。
|
|
16
|
+
* 往前翻页只是给客户端「补齐更早的一段」,不影响任何 rev 链。
|
|
17
|
+
*
|
|
18
|
+
* 窗口元数据可选以兼容旧端;新前端对带代次的分页同时校验代次与接缝,
|
|
19
|
+
* 服务端发现失效代次或锚点时回 resyncRequired,由前端 get_state 重建基线。
|
|
20
|
+
*/
|
|
21
|
+
import { randomUUID } from "node:crypto";
|
|
1
22
|
/** 尾部窗口条数(缺省 300 条)。 */
|
|
2
23
|
export const DEFAULT_HISTORY_WINDOW = 300;
|
|
3
24
|
/** 尾部窗口字符预算(缺省 150 万字符 ≈ 3MB JSON)。
|
|
@@ -113,12 +134,7 @@ export class MessageWindowTap {
|
|
|
113
134
|
const state = msg.state;
|
|
114
135
|
const full = state.messages;
|
|
115
136
|
const entry = this.entry(state.conversationId);
|
|
116
|
-
entry
|
|
117
|
-
// 首次按「条数 + 字符预算」算;之后只允许单调不增(已翻过的页不能被全量快照推回去)。
|
|
118
|
-
entry.start =
|
|
119
|
-
entry.start < 0
|
|
120
|
-
? pickWindowStart(full, this.cfg)
|
|
121
|
-
: computeWindowStart(entry.start, full.length, this.cfg.windowSize);
|
|
137
|
+
this.updateBaseline(entry, full);
|
|
122
138
|
this.lastConversationId = state.conversationId;
|
|
123
139
|
this.send({
|
|
124
140
|
...msg,
|
|
@@ -127,6 +143,7 @@ export class MessageWindowTap {
|
|
|
127
143
|
messages: entry.start > 0 ? full.slice(entry.start) : full,
|
|
128
144
|
historyStart: entry.start,
|
|
129
145
|
historyTotal: full.length,
|
|
146
|
+
historyGeneration: entry.generation,
|
|
130
147
|
},
|
|
131
148
|
});
|
|
132
149
|
return;
|
|
@@ -140,11 +157,17 @@ export class MessageWindowTap {
|
|
|
140
157
|
}
|
|
141
158
|
if (msg.appended.length > 0) {
|
|
142
159
|
entry.full = entry.full.concat(msg.appended);
|
|
160
|
+
entry.ids.push(...msg.appended.map((m) => m.id));
|
|
143
161
|
}
|
|
144
162
|
this.lastConversationId = msg.conversationId;
|
|
145
163
|
this.send({
|
|
146
164
|
...msg,
|
|
147
|
-
state: {
|
|
165
|
+
state: {
|
|
166
|
+
...msg.state,
|
|
167
|
+
historyStart: entry.start,
|
|
168
|
+
historyTotal: entry.full.length,
|
|
169
|
+
historyGeneration: entry.generation,
|
|
170
|
+
},
|
|
148
171
|
});
|
|
149
172
|
return;
|
|
150
173
|
}
|
|
@@ -156,13 +179,13 @@ export class MessageWindowTap {
|
|
|
156
179
|
*/
|
|
157
180
|
rehydrate(convId, full, start) {
|
|
158
181
|
const entry = this.entry(convId);
|
|
159
|
-
entry.
|
|
160
|
-
|
|
182
|
+
const fresh = entry.start < 0;
|
|
183
|
+
this.updateBaseline(entry, full);
|
|
184
|
+
// Legacy clients may restore a numeric cursor on a fresh cache. Modern
|
|
185
|
+
// clients must first obtain its new generation through get_state.
|
|
186
|
+
if (fresh && start !== undefined && Number.isFinite(start) && start >= 0) {
|
|
161
187
|
entry.start = Math.min(full.length, start);
|
|
162
188
|
}
|
|
163
|
-
else if (entry.start < 0) {
|
|
164
|
-
entry.start = pickWindowStart(full, this.cfg);
|
|
165
|
-
}
|
|
166
189
|
}
|
|
167
190
|
/** 客户端往上翻页:把窗口起点往前扩 `count` 条(`all` = 一路拉到最早)。
|
|
168
191
|
* - `conversationId`: 会话 ID(缺省回退最近一次快照会话);
|
|
@@ -178,16 +201,32 @@ export class MessageWindowTap {
|
|
|
178
201
|
if (!entry || !convId)
|
|
179
202
|
return false;
|
|
180
203
|
const total = entry.full.length;
|
|
204
|
+
const anchor = opts.beforeId === undefined ? undefined : entry.full.findIndex((m) => m.id === opts.beforeId);
|
|
205
|
+
const invalid = (opts.historyGeneration !== undefined && opts.historyGeneration !== entry.generation) ||
|
|
206
|
+
anchor === -1 ||
|
|
207
|
+
(opts.before !== undefined && (!Number.isInteger(opts.before) || opts.before < 0 || opts.before > total)) ||
|
|
208
|
+
(anchor !== undefined && opts.before !== undefined && anchor !== opts.before);
|
|
209
|
+
if (invalid) {
|
|
210
|
+
this.send({
|
|
211
|
+
type: "earlier_messages",
|
|
212
|
+
conversationId: convId,
|
|
213
|
+
messages: [],
|
|
214
|
+
historyStart: entry.start,
|
|
215
|
+
historyTotal: total,
|
|
216
|
+
historyGeneration: entry.generation,
|
|
217
|
+
beforeId: opts.beforeId,
|
|
218
|
+
before: opts.before,
|
|
219
|
+
resyncRequired: true,
|
|
220
|
+
});
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
181
223
|
// 确定翻页右边界(end):
|
|
182
|
-
// 1.
|
|
183
|
-
// 2.
|
|
224
|
+
// 1. 使用已校验的消息 ID beforeId 定位(失效锚点已在上方拒绝);
|
|
225
|
+
// 2. 未提供锚点时兼容客户端自描述下标 before;
|
|
184
226
|
// 3. 最后回退服务端自身记录的 entry.start(若小于 0 则说明未初始化,回退 total)。
|
|
185
227
|
let end = entry.start >= 0 ? entry.start : total;
|
|
186
|
-
if (
|
|
187
|
-
|
|
188
|
-
if (idx >= 0) {
|
|
189
|
-
end = idx;
|
|
190
|
-
}
|
|
228
|
+
if (anchor !== undefined) {
|
|
229
|
+
end = anchor;
|
|
191
230
|
}
|
|
192
231
|
else if (typeof opts.before === "number" && Number.isFinite(opts.before) && opts.before >= 0) {
|
|
193
232
|
end = Math.min(total, opts.before);
|
|
@@ -195,16 +234,30 @@ export class MessageWindowTap {
|
|
|
195
234
|
const page = opts.all ? end : Math.min(MAX_PAGE, Math.max(1, Math.floor(opts.count ?? this.cfg.pageSize) || 1));
|
|
196
235
|
const start = opts.all ? 0 : Math.max(0, end - page);
|
|
197
236
|
const messages = start < end ? entry.full.slice(start, end) : [];
|
|
198
|
-
entry.start = start;
|
|
237
|
+
entry.start = Math.min(entry.start, start);
|
|
199
238
|
this.send({
|
|
200
239
|
type: "earlier_messages",
|
|
201
240
|
conversationId: convId,
|
|
202
241
|
messages,
|
|
203
242
|
historyStart: start,
|
|
204
243
|
historyTotal: total,
|
|
244
|
+
historyGeneration: entry.generation,
|
|
245
|
+
beforeId: entry.full[end]?.id,
|
|
246
|
+
before: end,
|
|
205
247
|
});
|
|
206
248
|
return true;
|
|
207
249
|
}
|
|
250
|
+
updateBaseline(entry, full) {
|
|
251
|
+
const rewritten = entry.ids.length > full.length || entry.ids.some((id, i) => full[i]?.id !== id);
|
|
252
|
+
if (rewritten)
|
|
253
|
+
entry.generation = randomUUID();
|
|
254
|
+
// Appends and repeated snapshots must not re-expand a character-limited
|
|
255
|
+
// baseline. Only explicit pagination expands it; rewrites start afresh.
|
|
256
|
+
if (entry.start < 0 || rewritten)
|
|
257
|
+
entry.start = pickWindowStart(full, this.cfg);
|
|
258
|
+
entry.full = full;
|
|
259
|
+
entry.ids = full.map((m) => m.id);
|
|
260
|
+
}
|
|
208
261
|
/** 取(或建)对话窗口;LRU 超限时淘汰最久未用的那个。 */
|
|
209
262
|
entry(convId) {
|
|
210
263
|
const hit = this.convs.get(convId);
|
|
@@ -213,7 +266,7 @@ export class MessageWindowTap {
|
|
|
213
266
|
this.convs.set(convId, hit);
|
|
214
267
|
return hit;
|
|
215
268
|
}
|
|
216
|
-
const created = { full: [], start: -1 };
|
|
269
|
+
const created = { full: [], start: -1, generation: randomUUID(), ids: [] };
|
|
217
270
|
this.convs.set(convId, created);
|
|
218
271
|
while (this.convs.size > MAX_CACHED_CONVERSATIONS) {
|
|
219
272
|
const oldest = this.convs.keys().next();
|
package/dist/server/net-guard.js
CHANGED
|
@@ -19,11 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import { lookup as dnsLookup } from "node:dns/promises";
|
|
21
21
|
import { isIP } from "node:net";
|
|
22
|
-
|
|
23
|
-
/** 判断全局 fetch 是否仍为进程启动时的原生 fetch(未被 vi.stubGlobal 替换)。 */
|
|
24
|
-
export function isNativeGlobalFetch() {
|
|
25
|
-
return globalThis.fetch === initialGlobalFetch;
|
|
26
|
-
}
|
|
22
|
+
import { Agent, buildConnector, fetch as undiciFetch } from "undici";
|
|
27
23
|
const defaultLookupAll = async (hostname) => {
|
|
28
24
|
return await dnsLookup(hostname, { all: true, verbatim: true });
|
|
29
25
|
};
|
|
@@ -224,7 +220,7 @@ export async function resolveAndValidateUrl(raw, opts = {}) {
|
|
|
224
220
|
const addresses = [];
|
|
225
221
|
for (const rec of records) {
|
|
226
222
|
const addr = typeof rec?.address === "string" ? rec.address.trim() : "";
|
|
227
|
-
if (!addr || isBlockedHost(addr)) {
|
|
223
|
+
if (!isIP(addr) || isBlockedHost(addr)) {
|
|
228
224
|
return { ok: false, reason: "host" };
|
|
229
225
|
}
|
|
230
226
|
addresses.push(addr);
|
|
@@ -239,23 +235,106 @@ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
|
239
235
|
/**
|
|
240
236
|
* 带 SSRF 收口(URL 校验 + DNS 解析后 IP 校验 + 重定向逐跳校验)的安全 fetch 封装。
|
|
241
237
|
*/
|
|
238
|
+
export class FetchUrlError extends Error {
|
|
239
|
+
reason;
|
|
240
|
+
constructor(reason, url) {
|
|
241
|
+
super(reason === "scheme" ? `Blocked URL scheme: ${url}` : `Blocked private or internal host: ${url}`);
|
|
242
|
+
this.reason = reason;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** Abort also bounds DNS and injected transports that do not implement signals. */
|
|
246
|
+
export function readBeforeAbort(work, signal) {
|
|
247
|
+
return new Promise((resolve, reject) => {
|
|
248
|
+
const abort = () => {
|
|
249
|
+
signal.removeEventListener("abort", abort);
|
|
250
|
+
reject(signal.reason);
|
|
251
|
+
};
|
|
252
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
253
|
+
if (signal.aborted)
|
|
254
|
+
abort();
|
|
255
|
+
else
|
|
256
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
async function resolveWithoutDns(raw) {
|
|
260
|
+
const check = validateFetchUrl(raw);
|
|
261
|
+
return check.ok ? { ...check, addresses: [] } : check;
|
|
262
|
+
}
|
|
263
|
+
async function pinnedFetch(url, init, addresses) {
|
|
264
|
+
const hostname = new URL(url).hostname.replace(/^\[|\]$/g, "");
|
|
265
|
+
const connect = buildConnector({
|
|
266
|
+
lookup: (_host, options, callback) => {
|
|
267
|
+
const family = typeof options === "number" ? options : options.family;
|
|
268
|
+
const records = addresses
|
|
269
|
+
.map((address) => ({ address, family: isIP(address) }))
|
|
270
|
+
.filter((record) => !family || record.family === Number(family));
|
|
271
|
+
if (!records.length)
|
|
272
|
+
return callback(new Error("No validated address for requested family"), "", 0);
|
|
273
|
+
if (typeof options === "object" && options.all)
|
|
274
|
+
callback(null, records);
|
|
275
|
+
else
|
|
276
|
+
callback(null, records[0].address, records[0].family);
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
// A private dispatcher prevents proxy/global-dispatcher DNS resolution and cross-hop pooling.
|
|
280
|
+
// Keep the original hostname in the URL and connector for Host, SNI and certificate checks.
|
|
281
|
+
const dispatcher = new Agent({
|
|
282
|
+
connect: (options, callback) => {
|
|
283
|
+
if (options.hostname.replace(/^\[|\]$/g, "") !== hostname) {
|
|
284
|
+
callback(new Error("Unexpected connection hostname"), null);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
connect(options, callback);
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
const signal = init.signal;
|
|
291
|
+
const destroy = () => {
|
|
292
|
+
void dispatcher.destroy().catch(() => { });
|
|
293
|
+
};
|
|
294
|
+
signal.addEventListener("abort", destroy, { once: true });
|
|
295
|
+
try {
|
|
296
|
+
signal.throwIfAborted();
|
|
297
|
+
const headers = new Headers(init.headers);
|
|
298
|
+
headers.delete("host");
|
|
299
|
+
const response = await undiciFetch(url, {
|
|
300
|
+
...init,
|
|
301
|
+
headers: Array.from(headers.entries()),
|
|
302
|
+
dispatcher,
|
|
303
|
+
});
|
|
304
|
+
// Graceful close waits for the response stream; abort/cancel still destroys the connection.
|
|
305
|
+
void dispatcher
|
|
306
|
+
.close()
|
|
307
|
+
.catch(() => dispatcher.destroy())
|
|
308
|
+
.catch(() => { })
|
|
309
|
+
.finally(() => {
|
|
310
|
+
signal.removeEventListener("abort", destroy);
|
|
311
|
+
});
|
|
312
|
+
return response;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
signal.removeEventListener("abort", destroy);
|
|
316
|
+
await dispatcher.destroy().catch(() => { });
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
242
320
|
export async function safeFetch(url, init = {}, opts = {}) {
|
|
243
|
-
const
|
|
244
|
-
const
|
|
321
|
+
const useDns = !opts.fetcher || !!opts.lookup || opts.skipDnsLookup === false;
|
|
322
|
+
const deadline = AbortSignal.timeout(opts.timeoutMs ?? 10_000);
|
|
323
|
+
const signal = init.signal ? AbortSignal.any([init.signal, deadline]) : deadline;
|
|
245
324
|
const maxRedirects = opts.maxRedirects ?? 5;
|
|
246
325
|
let currentUrl = url;
|
|
247
|
-
let currentInit = { ...init, redirect: "manual" };
|
|
326
|
+
let currentInit = { ...init, signal, redirect: "manual" };
|
|
248
327
|
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
328
|
+
signal.throwIfAborted();
|
|
249
329
|
const check = useDns
|
|
250
|
-
? await resolveAndValidateUrl(currentUrl, { lookup: opts.lookup })
|
|
251
|
-
:
|
|
252
|
-
if (!check.ok)
|
|
253
|
-
throw new
|
|
254
|
-
? `Blocked URL scheme: ${currentUrl}`
|
|
255
|
-
: `Blocked private or internal host: ${currentUrl}`);
|
|
256
|
-
}
|
|
330
|
+
? await readBeforeAbort(resolveAndValidateUrl(currentUrl, { lookup: opts.lookup }), signal)
|
|
331
|
+
: await resolveWithoutDns(currentUrl);
|
|
332
|
+
if (!check.ok)
|
|
333
|
+
throw new FetchUrlError(check.reason, currentUrl);
|
|
257
334
|
currentUrl = check.url;
|
|
258
|
-
const res =
|
|
335
|
+
const res = opts.fetcher
|
|
336
|
+
? await readBeforeAbort(opts.fetcher(currentUrl, currentInit), signal)
|
|
337
|
+
: await pinnedFetch(currentUrl, currentInit, check.addresses);
|
|
259
338
|
if (!REDIRECT_STATUSES.has(res.status)) {
|
|
260
339
|
return res;
|
|
261
340
|
}
|
|
@@ -263,13 +342,36 @@ export async function safeFetch(url, init = {}, opts = {}) {
|
|
|
263
342
|
if (!location) {
|
|
264
343
|
return res;
|
|
265
344
|
}
|
|
345
|
+
if (res.body)
|
|
346
|
+
await readBeforeAbort(res.body.getReader().cancel(), signal);
|
|
266
347
|
if (hop === maxRedirects) {
|
|
267
348
|
throw new Error(`Too many redirects (> ${maxRedirects})`);
|
|
268
349
|
}
|
|
269
|
-
|
|
350
|
+
let nextUrl;
|
|
351
|
+
try {
|
|
352
|
+
nextUrl = new URL(location, currentUrl).toString();
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
throw new FetchUrlError("scheme", location);
|
|
356
|
+
}
|
|
357
|
+
if (new URL(nextUrl).origin !== new URL(currentUrl).origin) {
|
|
358
|
+
const headers = new Headers(currentInit.headers);
|
|
359
|
+
for (const name of ["authorization", "cookie", "proxy-authorization", "host"])
|
|
360
|
+
headers.delete(name);
|
|
361
|
+
currentInit = { ...currentInit, headers };
|
|
362
|
+
}
|
|
270
363
|
// 303 或 301/302 POST 重定向按规范退化为 GET
|
|
271
|
-
if (res.status === 303 ||
|
|
272
|
-
|
|
364
|
+
if (res.status === 303 ||
|
|
365
|
+
((res.status === 301 || res.status === 302) && currentInit.method?.toUpperCase() === "POST")) {
|
|
366
|
+
const headers = new Headers(currentInit.headers);
|
|
367
|
+
headers.delete("content-length");
|
|
368
|
+
headers.delete("content-type");
|
|
369
|
+
currentInit = {
|
|
370
|
+
...currentInit,
|
|
371
|
+
method: currentInit.method?.toUpperCase() === "HEAD" ? "HEAD" : "GET",
|
|
372
|
+
body: undefined,
|
|
373
|
+
headers,
|
|
374
|
+
};
|
|
273
375
|
}
|
|
274
376
|
currentUrl = nextUrl;
|
|
275
377
|
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/** Bound native shell output draining without changing shell selection (issue #794). */
|
|
2
|
+
import { registerHooks } from "node:module";
|
|
3
|
+
export const SENTINEL = "// pi-web-ui #794: bounded shell lifecycle v1";
|
|
4
|
+
// Kept as JavaScript source because this compatibility patch runs inside the SDK.
|
|
5
|
+
// The SDK still owns shell discovery, environment, process groups and tree killing.
|
|
6
|
+
export const SHELL_WAIT_SOURCE = `function waitForShellLifecycle(child, { onData, signal, timeout, timeoutMs, kill }) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
let settled = false;
|
|
9
|
+
let exited = false;
|
|
10
|
+
let exitCode = null;
|
|
11
|
+
let stopError;
|
|
12
|
+
let executionTimer;
|
|
13
|
+
let drainTimer;
|
|
14
|
+
let idleTimer;
|
|
15
|
+
let stopTimer;
|
|
16
|
+
const cleanup = () => {
|
|
17
|
+
clearTimeout(executionTimer);
|
|
18
|
+
clearTimeout(drainTimer);
|
|
19
|
+
clearTimeout(idleTimer);
|
|
20
|
+
clearTimeout(stopTimer);
|
|
21
|
+
signal?.removeEventListener("abort", onAbort);
|
|
22
|
+
child.removeListener("exit", onExit);
|
|
23
|
+
child.removeListener("close", onClose);
|
|
24
|
+
child.removeListener("error", onError);
|
|
25
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
26
|
+
stream?.removeListener("data", onOutput);
|
|
27
|
+
stream?.destroy();
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const finish = (error) => {
|
|
31
|
+
if (settled) return;
|
|
32
|
+
settled = true;
|
|
33
|
+
cleanup();
|
|
34
|
+
if (error) reject(error);
|
|
35
|
+
else resolve(exitCode);
|
|
36
|
+
};
|
|
37
|
+
const stop = (error) => {
|
|
38
|
+
if (settled || stopError) return;
|
|
39
|
+
stopError = error;
|
|
40
|
+
clearTimeout(executionTimer);
|
|
41
|
+
clearTimeout(drainTimer);
|
|
42
|
+
clearTimeout(idleTimer);
|
|
43
|
+
// Killing is best effort; inherited handles must never prevent settlement.
|
|
44
|
+
stopTimer = setTimeout(() => finish(stopError), 1000);
|
|
45
|
+
try { kill(); } catch { /* preserve the original timeout/cancellation */ }
|
|
46
|
+
};
|
|
47
|
+
const onAbort = () => stop(new Error("aborted"));
|
|
48
|
+
const armIdle = () => {
|
|
49
|
+
clearTimeout(idleTimer);
|
|
50
|
+
idleTimer = setTimeout(() => finish(stopError), 100);
|
|
51
|
+
};
|
|
52
|
+
const onOutput = (data) => {
|
|
53
|
+
if (settled || stopError) return;
|
|
54
|
+
try { onData(data); } catch (error) { stop(error); return; }
|
|
55
|
+
if (exited) armIdle();
|
|
56
|
+
};
|
|
57
|
+
const onExit = (code) => {
|
|
58
|
+
exited = true;
|
|
59
|
+
exitCode = code;
|
|
60
|
+
clearTimeout(executionTimer);
|
|
61
|
+
if (stopError) { finish(stopError); return; }
|
|
62
|
+
// Preserve the SDK's quiet-period drain, but never extend this hard cap.
|
|
63
|
+
drainTimer = setTimeout(() => {
|
|
64
|
+
try { onData(Buffer.from("\\n[Output collection stopped: inherited pipes remained open after the shell exited.]\\n")); }
|
|
65
|
+
catch (error) { finish(error); return; }
|
|
66
|
+
finish();
|
|
67
|
+
}, 1000);
|
|
68
|
+
armIdle();
|
|
69
|
+
};
|
|
70
|
+
const onClose = (code) => {
|
|
71
|
+
exitCode = code;
|
|
72
|
+
finish(stopError);
|
|
73
|
+
};
|
|
74
|
+
const onError = (error) => finish(stopError ?? error);
|
|
75
|
+
child.once("exit", onExit);
|
|
76
|
+
child.once("close", onClose);
|
|
77
|
+
child.once("error", onError);
|
|
78
|
+
child.stdout?.on("data", onOutput);
|
|
79
|
+
child.stderr?.on("data", onOutput);
|
|
80
|
+
if (timeoutMs !== undefined) {
|
|
81
|
+
executionTimer = setTimeout(() => stop(new Error("timeout:" + timeout)), timeoutMs);
|
|
82
|
+
}
|
|
83
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
84
|
+
if (signal?.aborted) onAbort();
|
|
85
|
+
});
|
|
86
|
+
}`;
|
|
87
|
+
const OLD_LIFECYCLE = / let timedOut = false;\r?\n[\s\S]*? finally \{[\s\S]*?signal\.removeEventListener\("abort", onAbort\);\r?\n \}/;
|
|
88
|
+
const REPLACEMENT = ` try {
|
|
89
|
+
const exitCode = await waitForShellLifecycle(child, {
|
|
90
|
+
onData, signal, timeout, timeoutMs,
|
|
91
|
+
kill: () => { if (child.pid) killProcessTree(child.pid); },
|
|
92
|
+
});
|
|
93
|
+
const signalCode = child.signalCode;
|
|
94
|
+
return { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };
|
|
95
|
+
} finally {
|
|
96
|
+
if (child.pid) untrackDetachedChildPid(child.pid);
|
|
97
|
+
}`;
|
|
98
|
+
export function patchBashProcessSource(source) {
|
|
99
|
+
if (source.includes(SENTINEL))
|
|
100
|
+
return { code: source, status: "already" };
|
|
101
|
+
if (!source.includes('from "../../utils/child-process.js"') || !OLD_LIFECYCLE.test(source)) {
|
|
102
|
+
return { code: source, status: "unsupported" };
|
|
103
|
+
}
|
|
104
|
+
const code = source
|
|
105
|
+
.replace(/import \{ waitForChildProcess \} from "\.\.\/\.\.\/utils\/child-process\.js";\r?\n/, "")
|
|
106
|
+
.replace(OLD_LIFECYCLE, REPLACEMENT);
|
|
107
|
+
return { code: `${code}\n${SENTINEL}\n${SHELL_WAIT_SOURCE}\n`, status: "patched" };
|
|
108
|
+
}
|
|
109
|
+
/* SDK sources are transformed in memory before compilation, never on disk. */
|
|
110
|
+
export function registerBashProcessPatch() {
|
|
111
|
+
registerHooks({
|
|
112
|
+
load(url, context, nextLoad) {
|
|
113
|
+
const loaded = nextLoad(url, context);
|
|
114
|
+
if (!url.replaceAll("\\\\", "/").endsWith("/@earendil-works/pi-coding-agent/dist/core/tools/bash.js"))
|
|
115
|
+
return loaded;
|
|
116
|
+
if (loaded.source == null)
|
|
117
|
+
return loaded;
|
|
118
|
+
const source = typeof loaded.source === "string" ? loaded.source : new TextDecoder().decode(loaded.source);
|
|
119
|
+
const result = patchBashProcessSource(source);
|
|
120
|
+
if (result.status === "unsupported")
|
|
121
|
+
console.warn(`[bash-process] SDK lifecycle patch not applied (unrecognized source): ${url}`);
|
|
122
|
+
return { ...loaded, source: result.code };
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
@@ -22,15 +22,15 @@ export function makePatchTool(options) {
|
|
|
22
22
|
name: PATCH_TOOL_NAME,
|
|
23
23
|
promptSnippet: "apply content-hashed, line-anchored patches to files",
|
|
24
24
|
label: "Apply Hashline patch",
|
|
25
|
-
description: `Apply content-hashed, line-anchored patches to workspace files — prevents stale edits, line drift, and indentation hallucination.
|
|
26
|
-
Each file section starts with \`[path#TAG]\` (or \`[path]\` if the hash is unknown yet). Operations:
|
|
27
|
-
- \`PUT N.=M:\` replace lines N..M (inclusive) with the following \`+TEXT\` lines.
|
|
28
|
-
- \`PUT N*:\` replace the syntactic block starting at line N (closing brace/indent auto-resolved).
|
|
29
|
-
- \`PUT <N:\` / \`PUT >N:\` insert before / after line N (\`<1\` = head, \`>$\` = end).
|
|
30
|
-
- \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines into a register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
|
|
31
|
-
- \`REM\` delete file; \`MV dest/path\` move/rename.
|
|
32
|
-
- Create a file: bare \`[path]\` header (no tag) on a nonexistent path + \`PUT <1:\` / \`PUT >$:\` \`+TEXT\` content.
|
|
33
|
-
- Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line). Divergence triggers a 3-way merge.
|
|
25
|
+
description: `Apply content-hashed, line-anchored patches to workspace files — prevents stale edits, line drift, and indentation hallucination.
|
|
26
|
+
Each file section starts with \`[path#TAG]\` (or \`[path]\` if the hash is unknown yet). Operations:
|
|
27
|
+
- \`PUT N.=M:\` replace lines N..M (inclusive) with the following \`+TEXT\` lines.
|
|
28
|
+
- \`PUT N*:\` replace the syntactic block starting at line N (closing brace/indent auto-resolved).
|
|
29
|
+
- \`PUT <N:\` / \`PUT >N:\` insert before / after line N (\`<1\` = head, \`>$\` = end).
|
|
30
|
+
- \`CUT N.=M [@name]\` / \`CUT N* [@name]\` delete lines into a register; \`PUT <N @name\` / \`PUT >N @name\` paste it.
|
|
31
|
+
- \`REM\` delete file; \`MV dest/path\` move/rename.
|
|
32
|
+
- Create a file: bare \`[path]\` header (no tag) on a nonexistent path + \`PUT <1:\` / \`PUT >$:\` \`+TEXT\` content.
|
|
33
|
+
- Body rows under \`:\` headers MUST start with \`+\` (\`+\` alone = blank line). Divergence triggers a 3-way merge.
|
|
34
34
|
Success returns the next anchor tag and live LSP diagnostics.`,
|
|
35
35
|
parameters: Type.Object({
|
|
36
36
|
patch: Type.String({
|
|
@@ -20,9 +20,9 @@ import { fileURLToPath } from "node:url";
|
|
|
20
20
|
import { sdkCopies } from "./sdk-origin.js";
|
|
21
21
|
export const TARGET_PATTERN = /if\s*\(!messageEntryId\)\s*\{\s*this\._extensionRunner\.emitError\(\{\s*extensionPath:\s*"<boundary>",\s*event:\s*"turn_end",\s*error:\s*"turn_end could not resolve the persisted assistant entry ID",\s*\}\);\s*return false;\s*\}/;
|
|
22
22
|
export const PATCHED_SENTINEL = "// pi-web-ui patch (issue #411: silent turn_end on aborted turns)";
|
|
23
|
-
export const REPLACEMENT = `if (!messageEntryId) {
|
|
24
|
-
${PATCHED_SENTINEL}
|
|
25
|
-
return false;
|
|
23
|
+
export const REPLACEMENT = `if (!messageEntryId) {
|
|
24
|
+
${PATCHED_SENTINEL}
|
|
25
|
+
return false;
|
|
26
26
|
}`;
|
|
27
27
|
/**
|
|
28
28
|
* 纯函数:给定 agent-session.js 内容,返回打补丁后的内容。
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Shared upload and WebSocket limits. Keep this module free of runtime dependencies. */
|
|
2
|
+
export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
3
|
+
export function normalizeUploadMaxMb(value, fallback) {
|
|
4
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.min(100, Math.floor(value))) : fallback;
|
|
5
|
+
}
|
|
6
|
+
export function uploadLimitBytes(settings, kind) {
|
|
7
|
+
const defaults = { chat: 20, workspace: 100, folder: 32 };
|
|
8
|
+
return normalizeUploadMaxMb(settings[`${kind}UploadMaxMb`], defaults[kind]) * 1024 * 1024;
|
|
9
|
+
}
|
|
10
|
+
/** Base64 expands each group of up to three bytes into four characters. */
|
|
11
|
+
export const MAX_UPLOAD_BASE64_CHARS = Math.ceil(MAX_UPLOAD_BYTES / 3) * 4;
|
|
12
|
+
/** Base64 payload plus 1MiB for the JSON envelope (paths, names and attachment metadata). */
|
|
13
|
+
export const WS_MAX_PAYLOAD_BYTES = MAX_UPLOAD_BASE64_CHARS + 1024 * 1024;
|
|
14
|
+
/** Reject definitely oversized base64 text before allocating a decoded Buffer. */
|
|
15
|
+
export function isUploadDataTooLong(dataLength, capBytes = MAX_UPLOAD_BYTES) {
|
|
16
|
+
return dataLength > Math.ceil(capBytes / 3) * 4;
|
|
17
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
/** A request owns its clock and cancellation; holders may change during takeover. */
|
|
3
|
+
export class PendingQuestion {
|
|
4
|
+
questions;
|
|
5
|
+
id = `q-${randomUUID()}`;
|
|
6
|
+
createdAt = Date.now();
|
|
7
|
+
deadline;
|
|
8
|
+
promise;
|
|
9
|
+
conversationId;
|
|
10
|
+
audience;
|
|
11
|
+
settled = false;
|
|
12
|
+
onSettled;
|
|
13
|
+
finish;
|
|
14
|
+
timer;
|
|
15
|
+
removeAbort;
|
|
16
|
+
settledListeners = new Set();
|
|
17
|
+
constructor(questions, conversationId, audience, timeoutSeconds, signal) {
|
|
18
|
+
this.questions = questions;
|
|
19
|
+
this.conversationId = conversationId;
|
|
20
|
+
this.audience = audience;
|
|
21
|
+
this.promise = new Promise((resolve) => {
|
|
22
|
+
this.finish = resolve;
|
|
23
|
+
});
|
|
24
|
+
if (timeoutSeconds > 0) {
|
|
25
|
+
this.deadline = this.createdAt + timeoutSeconds * 1000;
|
|
26
|
+
this.timer = setTimeout(() => this.resolve({ status: "timed_out", timed_out: true }), timeoutSeconds * 1000);
|
|
27
|
+
this.timer.unref?.();
|
|
28
|
+
}
|
|
29
|
+
if (signal) {
|
|
30
|
+
const abort = () => this.resolve(null);
|
|
31
|
+
this.removeAbort = () => signal.removeEventListener?.("abort", abort);
|
|
32
|
+
signal.addEventListener?.("abort", abort, { once: true });
|
|
33
|
+
if (signal.aborted)
|
|
34
|
+
abort();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Independent of legacy onSettled, so holder migration cannot erase other owners' cleanup.
|
|
38
|
+
* Late subscribers run immediately. Returned cleanup only unsubscribes this listener. */
|
|
39
|
+
subscribeSettled(listener) {
|
|
40
|
+
if (this.settled) {
|
|
41
|
+
listener();
|
|
42
|
+
return () => { };
|
|
43
|
+
}
|
|
44
|
+
this.settledListeners.add(listener);
|
|
45
|
+
return () => {
|
|
46
|
+
this.settledListeners.delete(listener);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Compatibility alias for integrations using listener naming. */
|
|
50
|
+
addSettledListener(listener) {
|
|
51
|
+
return this.subscribeSettled(listener);
|
|
52
|
+
}
|
|
53
|
+
resolve = (result) => {
|
|
54
|
+
if (this.settled)
|
|
55
|
+
return;
|
|
56
|
+
this.settled = true;
|
|
57
|
+
clearTimeout(this.timer);
|
|
58
|
+
this.removeAbort?.();
|
|
59
|
+
this.removeAbort = undefined;
|
|
60
|
+
this.finish(result);
|
|
61
|
+
const onSettled = this.onSettled;
|
|
62
|
+
this.onSettled = undefined;
|
|
63
|
+
const listeners = [...this.settledListeners];
|
|
64
|
+
this.settledListeners.clear();
|
|
65
|
+
// Every owner gets cleanup even if another subscriber throws. Preserve the first error.
|
|
66
|
+
let firstError;
|
|
67
|
+
let failed = false;
|
|
68
|
+
for (const listener of [...listeners, ...(onSettled ? [onSettled] : [])]) {
|
|
69
|
+
try {
|
|
70
|
+
listener();
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (!failed) {
|
|
74
|
+
failed = true;
|
|
75
|
+
firstError = error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (failed)
|
|
80
|
+
throw firstError;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -52,12 +52,12 @@ export const PI_DOC_PATHS = (() => {
|
|
|
52
52
|
* programs wait for input that never comes. Legacy Chinese files are often
|
|
53
53
|
* GBK/GB2312 — read them with the right encoding, never paste mojibake into
|
|
54
54
|
* reasoning/answers. */
|
|
55
|
-
export const WINDOWS_PERSONA = `You are a coding agent running on Windows. The bash tool runs Git Bash (bash.exe), not PowerShell. Follow these rules to avoid hanging the session:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
- ALWAYS pass a timeout parameter to the bash tool (in seconds). There is NO default timeout — a command that never finishes (servers, watchers, infinite loops, slow downloads/installs) will hang the entire conversation indefinitely. Pick a generous timeout for long-running work, but never omit it.
|
|
60
|
-
- NEVER run interactive or foreground long-running commands through the bash tool (vi, less, top, python -, node -, npm run dev, sleep 10000). For servers/daemons use background execution with output redirected to a log file, then poll the log; stop them when done.
|
|
61
|
-
- In the interactive terminal (TTY) — which is Git Bash too, not PowerShell — NEVER use heredocs (<<'EOF' ... EOF) or here-strings, and NEVER start interactive programs (vi, less, python -, node -, npm init): they wait for keyboard input that never arrives and hang the terminal forever. Prefer writing a temp script file (e.g. .pi-tmp.sh) and running it non-interactively. ALWAYS pass a timeout to long-running commands (e.g. \`timeout 120 npm run dev\`).
|
|
62
|
-
|
|
55
|
+
export const WINDOWS_PERSONA = `You are a coding agent running on Windows. The bash tool runs Git Bash (bash.exe), not PowerShell. Follow these rules to avoid hanging the session:
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
- ALWAYS pass a timeout parameter to the bash tool (in seconds). There is NO default timeout — a command that never finishes (servers, watchers, infinite loops, slow downloads/installs) will hang the entire conversation indefinitely. Pick a generous timeout for long-running work, but never omit it.
|
|
60
|
+
- NEVER run interactive or foreground long-running commands through the bash tool (vi, less, top, python -, node -, npm run dev, sleep 10000). For servers/daemons use background execution with output redirected to a log file, then poll the log; stop them when done.
|
|
61
|
+
- In the interactive terminal (TTY) — which is Git Bash too, not PowerShell — NEVER use heredocs (<<'EOF' ... EOF) or here-strings, and NEVER start interactive programs (vi, less, python -, node -, npm init): they wait for keyboard input that never arrives and hang the terminal forever. Prefer writing a temp script file (e.g. .pi-tmp.sh) and running it non-interactively. ALWAYS pass a timeout to long-running commands (e.g. \`timeout 120 npm run dev\`).
|
|
62
|
+
|
|
63
63
|
Many legacy Chinese text files (.html/.txt/.md/.log, exported documents) are GBK/GB2312 encoded: the read tool decodes UTF-8 only and will show mojibake (乱码) for them. If a file's content looks garbled, read it through the terminal instead: in Git Bash use \`cat file | iconv -f GBK -t UTF-8\` (or \`iconv -f GBK -t UTF-8 file\`); in cmd use \`chcp 65001 && type file\`; in PowerShell use \`Get-Content -Encoding Default file\`. Never paste mojibake into your reasoning or answer — describe the decoded content instead.`;
|