pi-web-ui 0.111.0 → 0.113.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -2
- package/bin/frp-manager.mjs +9 -2
- package/bin/pi-web-ui.mjs +325 -45
- package/dist/server/agent-service-daemon.js +29 -4
- package/dist/server/agent-service.js +1527 -510
- package/dist/server/approval-audit.js +119 -0
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/approval-rules.js +42 -17
- package/dist/server/attachment-store.js +8 -8
- package/dist/server/canvas/canvas-agent-tool.js +8 -0
- package/dist/server/canvas/canvas-orchestrator.js +128 -22
- package/dist/server/canvas/pstack-skills-data.js +498 -0
- package/dist/server/client-state.js +28 -0
- package/dist/server/delegate-mode.js +6 -3
- package/dist/server/delegate-task.js +18 -3
- package/dist/server/dispatch-domain-handlers.js +39 -11
- package/dist/server/dsh/dsh-agent-service.js +294 -15
- package/dist/server/dsh/dsh-serialize.js +1 -1
- package/dist/server/durable/durable-driver.js +112 -107
- package/dist/server/durable/durable-event-projector.js +253 -0
- package/dist/server/durable/durable-loader.js +1 -14
- package/dist/server/durable/durable-models.js +107 -0
- package/dist/server/durable/index.js +0 -4
- package/dist/server/engine-probe.js +111 -48
- package/dist/server/eval-tool.js +28 -3
- package/dist/server/goal-service.js +7 -0
- package/dist/server/index.js +371 -57
- package/dist/server/json-utils.js +57 -0
- package/dist/server/marker-service.js +8 -0
- package/dist/server/message-window.js +43 -10
- package/dist/server/model-admin.js +247 -163
- package/dist/server/model-resolver.js +66 -44
- package/dist/server/plan-manager.js +3 -6
- package/dist/server/plugin-api-catalog.js +1 -0
- package/dist/server/plugin-assets.js +238 -0
- package/dist/server/plugin-facilities.js +22 -0
- package/dist/server/plugin-ui-slots.js +1 -0
- package/dist/server/plugins.js +209 -11
- package/dist/server/preset-fields.js +25 -1
- package/dist/server/preset-share.js +5 -2
- package/dist/server/prompt-assembler.js +2 -1
- package/dist/server/prompt-composer.js +18 -8
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-utils.js +156 -0
- package/dist/server/remote-ssh-service.js +110 -12
- package/dist/server/sdk-builtin-extensions.js +85 -0
- package/dist/server/serialize.js +1 -1
- package/dist/server/server-config.js +66 -0
- package/dist/server/session-parser.js +49 -13
- package/dist/server/session-search.js +4 -3
- package/dist/server/settings-service.js +74 -53
- package/dist/server/setup-page.js +632 -0
- package/dist/server/skill-discovery.js +361 -59
- package/dist/server/skill-maintenance.js +231 -0
- package/dist/server/skill-tool.js +32 -3
- package/dist/server/soft-cap.js +30 -6
- package/dist/server/subagent-helpers.js +22 -1
- package/dist/server/subagent-notify.js +93 -0
- package/dist/server/subagent-security-gate.js +282 -0
- package/dist/server/subagent-templates.js +8 -0
- package/dist/server/subagents.js +390 -48
- package/dist/server/terminals.js +196 -8
- package/dist/server/text-quote.js +61 -0
- package/dist/server/tool-approval.js +63 -4
- package/dist/server/tool-guards.js +208 -0
- package/dist/server/tool-host-factories.js +48 -10
- package/dist/server/tool-manager.js +106 -28
- package/dist/server/tool-overrides.js +21 -11
- package/dist/server/universal/driver-base.js +8 -0
- package/dist/server/universal/drivers/claude-code.js +116 -7
- package/dist/server/universal/drivers/dsh-driver.js +3 -0
- package/dist/server/universal/index.js +0 -1
- package/dist/server/universal/universal-session.js +106 -10
- package/dist/server/worktree-service.js +189 -1
- package/docs/dsh-engine.md +1 -5
- package/package.json +1 -1
- package/plugin-sdk/client-utils.mjs +192 -5
- package/plugin-sdk/index.d.ts +63 -1
- package/plugin-sdk/index.mjs +94 -0
- package/plugin-sdk/package.json +5 -1
- package/plugins/catalog.json +21 -0
- package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
- package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
- package/web/dist/assets/index-BwL7qBh6.css +1 -0
- package/web/dist/index.html +11 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B0ajS__T.js +0 -697
- package/web/dist/assets/index-BHik5WGG.css +0 -1
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* server/approval-audit.ts
|
|
3
|
+
*
|
|
4
|
+
* 审批决策与安全拦截审计日志(Append-Only Structured Audit Trail,Issue #722)。
|
|
5
|
+
*
|
|
6
|
+
* 记录每一个高危操作与自定义规则的安全事件:
|
|
7
|
+
* - 规则直接阻断(rule_denied)
|
|
8
|
+
* - 弹窗审批答复(user_approved / user_denied / user_edited)
|
|
9
|
+
* - 策略静默放行(suppressed_category / suppressed_all / suppressed_disabled)
|
|
10
|
+
* - 批量自动放行(batch_approved_policy / batch_approved_disabled)
|
|
11
|
+
*
|
|
12
|
+
* 存储路径:<dataDir>/audit/approvals.jsonl
|
|
13
|
+
* 轮转规则:单文件达到 10MB 自动轮转,最多保留 3 份归档。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, statSync, renameSync, unlinkSync, appendFileSync, readFileSync } from "node:fs";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
const MAX_AUDIT_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
|
18
|
+
const MAX_BACKUP_FILES = 3;
|
|
19
|
+
/** 参数摘录与截断(单个字段最长 1024 字符,防止长文本撑爆审计日志)。 */
|
|
20
|
+
export function sanitizeAuditParams(params) {
|
|
21
|
+
if (params === null || params === undefined)
|
|
22
|
+
return params;
|
|
23
|
+
if (typeof params === "string") {
|
|
24
|
+
return params.length > 1024 ? `${params.slice(0, 1024)}... [truncated ${params.length} chars]` : params;
|
|
25
|
+
}
|
|
26
|
+
if (typeof params !== "object")
|
|
27
|
+
return params;
|
|
28
|
+
if (Array.isArray(params)) {
|
|
29
|
+
return params.slice(0, 20).map(sanitizeAuditParams);
|
|
30
|
+
}
|
|
31
|
+
const obj = params;
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
34
|
+
out[k] = sanitizeAuditParams(v);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
export class ApprovalAuditLogger {
|
|
39
|
+
logPath;
|
|
40
|
+
seq = 0;
|
|
41
|
+
constructor(dataDir) {
|
|
42
|
+
this.logPath = join(dataDir, "audit", "approvals.jsonl");
|
|
43
|
+
}
|
|
44
|
+
getFilePath() {
|
|
45
|
+
return this.logPath;
|
|
46
|
+
}
|
|
47
|
+
/** 记录一条审批/安全决策。 */
|
|
48
|
+
record(entry) {
|
|
49
|
+
try {
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const fullEntry = {
|
|
52
|
+
id: `audit-${now}-${++this.seq}`,
|
|
53
|
+
timestamp: now,
|
|
54
|
+
isoTime: new Date(now).toISOString(),
|
|
55
|
+
...entry,
|
|
56
|
+
params: sanitizeAuditParams(entry.params),
|
|
57
|
+
};
|
|
58
|
+
this.rotateIfNeeded();
|
|
59
|
+
const dir = dirname(this.logPath);
|
|
60
|
+
if (!existsSync(dir)) {
|
|
61
|
+
mkdirSync(dir, { recursive: true });
|
|
62
|
+
}
|
|
63
|
+
appendFileSync(this.logPath, JSON.stringify(fullEntry) + "\n", "utf8");
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
// 审计日志写入为旁路监控,绝不中断正常业务流,仅记录调试警告
|
|
67
|
+
console.warn("[approval-audit] Failed to write audit log:", err);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** 检查文件大小并按需轮转。 */
|
|
71
|
+
rotateIfNeeded() {
|
|
72
|
+
if (!existsSync(this.logPath))
|
|
73
|
+
return;
|
|
74
|
+
try {
|
|
75
|
+
const stat = statSync(this.logPath);
|
|
76
|
+
if (stat.size < MAX_AUDIT_FILE_SIZE)
|
|
77
|
+
return;
|
|
78
|
+
for (let i = MAX_BACKUP_FILES - 1; i >= 1; i--) {
|
|
79
|
+
const src = this.logPath.replace(/\.jsonl$/, `.${i}.jsonl`);
|
|
80
|
+
const dst = this.logPath.replace(/\.jsonl$/, `.${i + 1}.jsonl`);
|
|
81
|
+
if (existsSync(src)) {
|
|
82
|
+
if (i === MAX_BACKUP_FILES - 1 && existsSync(dst)) {
|
|
83
|
+
unlinkSync(dst);
|
|
84
|
+
}
|
|
85
|
+
renameSync(src, dst);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const firstBackup = this.logPath.replace(/\.jsonl$/, ".1.jsonl");
|
|
89
|
+
if (existsSync(firstBackup))
|
|
90
|
+
unlinkSync(firstBackup);
|
|
91
|
+
renameSync(this.logPath, firstBackup);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
console.warn("[approval-audit] Log rotation failed:", err);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** 读取最近 N 条审计记录(主要供单测和审计查看)。 */
|
|
98
|
+
readRecentEntries(limit = 100) {
|
|
99
|
+
if (!existsSync(this.logPath))
|
|
100
|
+
return [];
|
|
101
|
+
try {
|
|
102
|
+
const content = readFileSync(this.logPath, "utf8");
|
|
103
|
+
const lines = content.trim().split("\n").filter(Boolean);
|
|
104
|
+
const out = [];
|
|
105
|
+
for (let i = Math.max(0, lines.length - limit); i < lines.length; i++) {
|
|
106
|
+
try {
|
|
107
|
+
out.push(JSON.parse(lines[i]));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// 忽略单行解析异常
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return [];
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -113,7 +113,7 @@ export const DEFAULT_APPROVAL_RULES = [
|
|
|
113
113
|
{
|
|
114
114
|
id: "builtin.file.sensitive.env",
|
|
115
115
|
enabled: true,
|
|
116
|
-
tools: ["write", "edit", "edit_soft"],
|
|
116
|
+
tools: ["write", "edit", "edit_soft", "patch"],
|
|
117
117
|
field: "path",
|
|
118
118
|
match: "regex",
|
|
119
119
|
value: "(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$",
|
|
@@ -128,7 +128,7 @@ export const DEFAULT_APPROVAL_RULES = [
|
|
|
128
128
|
{
|
|
129
129
|
id: "builtin.file.sensitive.ssh",
|
|
130
130
|
enabled: true,
|
|
131
|
-
tools: ["write", "edit", "edit_soft"],
|
|
131
|
+
tools: ["write", "edit", "edit_soft", "patch"],
|
|
132
132
|
field: "path",
|
|
133
133
|
match: "regex",
|
|
134
134
|
value: "(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$",
|
|
@@ -143,7 +143,7 @@ export const DEFAULT_APPROVAL_RULES = [
|
|
|
143
143
|
{
|
|
144
144
|
id: "builtin.file.sensitive.shell",
|
|
145
145
|
enabled: true,
|
|
146
|
-
tools: ["write", "edit", "edit_soft"],
|
|
146
|
+
tools: ["write", "edit", "edit_soft", "patch"],
|
|
147
147
|
field: "path",
|
|
148
148
|
match: "regex",
|
|
149
149
|
value: "(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$",
|
|
@@ -158,7 +158,7 @@ export const DEFAULT_APPROVAL_RULES = [
|
|
|
158
158
|
{
|
|
159
159
|
id: "builtin.file.outside-workspace",
|
|
160
160
|
enabled: true,
|
|
161
|
-
tools: ["write", "edit", "edit_soft"],
|
|
161
|
+
tools: ["write", "edit", "edit_soft", "patch"],
|
|
162
162
|
field: "path",
|
|
163
163
|
match: "outside_workspace",
|
|
164
164
|
value: "",
|
|
@@ -30,23 +30,30 @@
|
|
|
30
30
|
* - 内存缓存 + 文件 mtime 感知,支持直接编辑 JSON 文件热生效。
|
|
31
31
|
*/
|
|
32
32
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
33
|
-
import { resolve, sep } from "node:path";
|
|
33
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
34
34
|
import { writeJsonAtomicSync } from "./atomic-file.js";
|
|
35
35
|
import { DEFAULT_APPROVAL_RULES } from "./approval-default-rules.js";
|
|
36
36
|
export { DEFAULT_APPROVAL_RULES };
|
|
37
|
+
/**
|
|
38
|
+
* 检测命令字符串中是否包含 Shell 复合操作符或子命令执行结构(分号、逻辑与/或、管道、反引号、换行、$())。
|
|
39
|
+
* 用于白名单(allow)规则防止借由安全前缀在复合命令中夹带高危操作(Issue #722)。
|
|
40
|
+
*/
|
|
41
|
+
export const SHELL_COMPOUND_OPERATOR_RE = /(?:[;&|`\n]|\$\()/;
|
|
42
|
+
export function hasShellCompoundOperator(command) {
|
|
43
|
+
return SHELL_COMPOUND_OPERATOR_RE.test(command);
|
|
44
|
+
}
|
|
37
45
|
/**
|
|
38
46
|
* 跨平台判定 target 路径是否严格位于 root 目录内部或就是 root 本身。
|
|
39
47
|
* 针对 Windows 盘符大小写不敏感及正反斜杠统一进行规范化,防止 .. 路径穿越逃逸。
|
|
40
48
|
*/
|
|
41
49
|
export function isPathInsideRoot(target, root) {
|
|
42
|
-
const
|
|
43
|
-
const
|
|
44
|
-
if (
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
return
|
|
48
|
-
}
|
|
49
|
-
return normTarget === normRoot || normTarget.startsWith(normRoot + sep);
|
|
50
|
+
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
51
|
+
const rel = relative(fold(resolve(root)), fold(resolve(target)));
|
|
52
|
+
if (rel === "")
|
|
53
|
+
return true;
|
|
54
|
+
if (isAbsolute(rel))
|
|
55
|
+
return false;
|
|
56
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`) && !rel.startsWith("../");
|
|
50
57
|
}
|
|
51
58
|
/**
|
|
52
59
|
* 极简 glob 转 RegExp(只支持 * 单段、? 单字符、** 跨段)。
|
|
@@ -139,6 +146,10 @@ export function matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceR
|
|
|
139
146
|
const fieldValue = extractRuleFieldValue(rule.field, toolName, params);
|
|
140
147
|
if (!fieldValue)
|
|
141
148
|
return [];
|
|
149
|
+
if (rule.action === "allow" && rule.field === "command" && hasShellCompoundOperator(fieldValue)) {
|
|
150
|
+
const single = matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots);
|
|
151
|
+
return single ? [single] : [];
|
|
152
|
+
}
|
|
142
153
|
let re;
|
|
143
154
|
try {
|
|
144
155
|
re = new RegExp(rule.value, "gi");
|
|
@@ -186,61 +197,75 @@ export function matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRo
|
|
|
186
197
|
if (!fieldValue)
|
|
187
198
|
return null;
|
|
188
199
|
// 4. 按 match kind 进行文本判定并提取命中区间
|
|
200
|
+
let matched = null;
|
|
189
201
|
switch (rule.match) {
|
|
190
202
|
case "regex": {
|
|
191
203
|
try {
|
|
192
204
|
const re = new RegExp(rule.value, "i");
|
|
193
205
|
const m = re.exec(fieldValue);
|
|
194
206
|
if (m) {
|
|
195
|
-
|
|
207
|
+
matched = {
|
|
196
208
|
index: m.index,
|
|
197
209
|
length: m[0].length,
|
|
198
210
|
text: m[0],
|
|
199
211
|
};
|
|
200
212
|
}
|
|
201
|
-
return null;
|
|
202
213
|
}
|
|
203
214
|
catch {
|
|
204
215
|
return null;
|
|
205
216
|
}
|
|
217
|
+
break;
|
|
206
218
|
}
|
|
207
219
|
case "glob": {
|
|
208
220
|
try {
|
|
209
221
|
const re = globToRegex(rule.value);
|
|
210
222
|
const normalized = fieldValue.replace(/\\/g, "/");
|
|
211
223
|
if (re.test(normalized)) {
|
|
212
|
-
|
|
224
|
+
matched = { index: 0, length: fieldValue.length, text: fieldValue };
|
|
213
225
|
}
|
|
214
|
-
return null;
|
|
215
226
|
}
|
|
216
227
|
catch {
|
|
217
228
|
return null;
|
|
218
229
|
}
|
|
230
|
+
break;
|
|
219
231
|
}
|
|
220
232
|
case "contains": {
|
|
221
233
|
const idx = fieldValue.toLowerCase().indexOf(rule.value.toLowerCase());
|
|
222
234
|
if (idx >= 0) {
|
|
223
|
-
|
|
235
|
+
matched = {
|
|
224
236
|
index: idx,
|
|
225
237
|
length: rule.value.length,
|
|
226
238
|
text: fieldValue.slice(idx, idx + rule.value.length),
|
|
227
239
|
};
|
|
228
240
|
}
|
|
229
|
-
|
|
241
|
+
break;
|
|
230
242
|
}
|
|
231
243
|
case "prefix": {
|
|
232
244
|
if (fieldValue.toLowerCase().startsWith(rule.value.toLowerCase())) {
|
|
233
|
-
|
|
245
|
+
matched = {
|
|
234
246
|
index: 0,
|
|
235
247
|
length: rule.value.length,
|
|
236
248
|
text: fieldValue.slice(0, rule.value.length),
|
|
237
249
|
};
|
|
238
250
|
}
|
|
239
|
-
|
|
251
|
+
break;
|
|
240
252
|
}
|
|
241
253
|
default:
|
|
242
254
|
return null;
|
|
243
255
|
}
|
|
256
|
+
if (!matched)
|
|
257
|
+
return null;
|
|
258
|
+
// 复合命令白名单防逃逸(Issue #722):
|
|
259
|
+
// 当动作为 allow(免审放行)且字段为 command 时,如果整段命令包含复合操作符(; && || | \n $() `),
|
|
260
|
+
// 且该白名单匹配未完全覆盖整条命令输入,禁止仅凭前缀、子串或通配符放行整条复合命令,
|
|
261
|
+
// 防止如 `git status && rm -rf /` 借由安全前缀绕过后续的高危规则拦截。
|
|
262
|
+
if (rule.action === "allow" &&
|
|
263
|
+
rule.field === "command" &&
|
|
264
|
+
hasShellCompoundOperator(fieldValue) &&
|
|
265
|
+
matched.text.trim().length < fieldValue.trim().length) {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
return matched;
|
|
244
269
|
}
|
|
245
270
|
/**
|
|
246
271
|
* 单条规则针对具体工具调用的匹配判定(纯函数)。
|
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
* - 避免快照和消息列表随会话进行出现数兆字节 base64 的膨胀。
|
|
9
9
|
*/
|
|
10
10
|
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
-
import { mkdirSync, existsSync, readdirSync
|
|
11
|
+
import { mkdirSync, existsSync, readdirSync } from "node:fs";
|
|
12
12
|
import { readFile, rename, rm, writeFile, stat } from "node:fs/promises";
|
|
13
13
|
import { join, extname } from "node:path";
|
|
14
|
+
import { writeAtomicSync } from "./atomic-file.js";
|
|
14
15
|
let storeDir = "";
|
|
15
16
|
/** 初始化附件存储目录(服务启动时调用)。 */
|
|
16
17
|
export function initAttachmentStore(dataDir) {
|
|
@@ -92,16 +93,10 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
|
|
|
92
93
|
const fileName = `${hash}${ext}`;
|
|
93
94
|
const filePath = join(storeDir, fileName);
|
|
94
95
|
if (!existsSync(filePath)) {
|
|
95
|
-
const tmpPath = `${filePath}.${randomUUID()}.tmp`;
|
|
96
96
|
try {
|
|
97
|
-
|
|
98
|
-
renameSync(tmpPath, filePath);
|
|
97
|
+
writeAtomicSync(filePath, buffer);
|
|
99
98
|
}
|
|
100
99
|
catch (err) {
|
|
101
|
-
try {
|
|
102
|
-
rmSync(tmpPath, { force: true });
|
|
103
|
-
}
|
|
104
|
-
catch { }
|
|
105
100
|
const code = err.code;
|
|
106
101
|
if (code === "EEXIST") {
|
|
107
102
|
// 并发写同哈希:目标已在,按「已存在」成功路径返回
|
|
@@ -115,6 +110,11 @@ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream"
|
|
|
115
110
|
throw err;
|
|
116
111
|
}
|
|
117
112
|
}
|
|
113
|
+
if (!existsSync(filePath)) {
|
|
114
|
+
const err = new Error(`EPERM: target file does not exist after write ${filePath}`);
|
|
115
|
+
err.code = "EPERM";
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
118
|
}
|
|
119
119
|
return {
|
|
120
120
|
hash,
|
|
@@ -84,6 +84,8 @@ const VALID_ROLES = new Set([
|
|
|
84
84
|
"api",
|
|
85
85
|
"memory",
|
|
86
86
|
"end",
|
|
87
|
+
"pstack",
|
|
88
|
+
"skill",
|
|
87
89
|
]);
|
|
88
90
|
const canvasSchema = Type.Object({
|
|
89
91
|
action: Type.Union([
|
|
@@ -379,9 +381,15 @@ export function makeCanvasTool(host, lang) {
|
|
|
379
381
|
if (action === "add_edge") {
|
|
380
382
|
const s = p.sourceNodeId;
|
|
381
383
|
const t = p.targetNodeId;
|
|
384
|
+
if (s === t) {
|
|
385
|
+
return text(pick(getLang(), "不能连接自环边(源与目标相同)。", "Self-loop edges are not allowed (source equals target).", "canvas.edge.self", {}), { ok: false });
|
|
386
|
+
}
|
|
382
387
|
if (!graph.nodes.some((x) => x.id === s) || !graph.nodes.some((x) => x.id === t)) {
|
|
383
388
|
return text(pick(getLang(), "边的端点节点不存在,先 get 确认 id。", "Edge endpoint not found; get the graph first.", "canvas.edge.missing", {}), { ok: false });
|
|
384
389
|
}
|
|
390
|
+
if (graph.edges.some((e) => e.sourceNodeId === s && e.targetNodeId === t)) {
|
|
391
|
+
return text(pick(getLang(), `两节点间已存在连接(${s} → ${t})。`, `Edge already exists between ${s} and ${t}.`, "canvas.edge.duplicate", {}), { ok: false });
|
|
392
|
+
}
|
|
385
393
|
const edge = {
|
|
386
394
|
id: `e_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
|
|
387
395
|
sourceNodeId: s,
|
|
@@ -13,10 +13,12 @@ import { isAbsolute, resolve, sep } from "node:path";
|
|
|
13
13
|
import { isRemoteWorkspaceUri } from "../remote-ssh-service.js";
|
|
14
14
|
import { existsSync as fsExistsSync, mkdirSync as fsMkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
15
15
|
import { join as pathJoin } from "node:path";
|
|
16
|
-
import { saveCanvasRuntimeState, loadCanvasGraph, isSafeGraphId } from "./canvas-store.js";
|
|
16
|
+
import { saveCanvasRuntimeState, loadCanvasGraph, saveCanvasGraph, isSafeGraphId } from "./canvas-store.js";
|
|
17
17
|
import { isInsideGitRepo, normalizeWirePath } from "../worktree-service.js";
|
|
18
18
|
import { execFile } from "node:child_process";
|
|
19
19
|
import { promisify } from "node:util";
|
|
20
|
+
import { PSTACK_SKILLS_MAP } from "./pstack-skills-data.js";
|
|
21
|
+
import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
|
|
20
22
|
const exec = promisify(execFile);
|
|
21
23
|
export class CanvasOrchestrator {
|
|
22
24
|
dataDir;
|
|
@@ -151,19 +153,26 @@ export class CanvasOrchestrator {
|
|
|
151
153
|
});
|
|
152
154
|
}
|
|
153
155
|
/** 确保该节点所需的真实工作目录(支持 Worktree 隔离) */
|
|
154
|
-
/** 有效运行基准:显式 runBase
|
|
156
|
+
/** 有效运行基准:显式 runBase(本地绝对路径或远程 SSH URI)优先,否则服务启动目录 */
|
|
155
157
|
pickRunBase(runBase) {
|
|
156
158
|
const r = (runBase ?? "").trim();
|
|
157
|
-
if (r &&
|
|
158
|
-
return resolve(r);
|
|
159
|
+
if (r && (isRemoteWorkspaceUri(r) || isAbsolute(r)))
|
|
160
|
+
return isRemoteWorkspaceUri(r) ? r : resolve(r);
|
|
159
161
|
return resolve(this.baseCwd);
|
|
160
162
|
}
|
|
161
163
|
async resolveNodeCwd(node, runBase) {
|
|
162
164
|
// node.id 用于 worktree 目录名与 git 分支名;node.cwd 允许工作区外任意绝对路径。
|
|
163
165
|
if (!isSafeGraphId(node.id))
|
|
164
166
|
throw new Error(`Invalid canvas node id: ${JSON.stringify(node.id)}`);
|
|
165
|
-
const base = this.pickRunBase(runBase);
|
|
166
167
|
const raw = (node.cwd ?? "").trim();
|
|
168
|
+
// 远程 SSH 工作区路径(如 ssh://user@host:22/path)原生透传给引擎,不走本地目录与 worktree
|
|
169
|
+
if (isRemoteWorkspaceUri(raw)) {
|
|
170
|
+
return raw;
|
|
171
|
+
}
|
|
172
|
+
const base = this.pickRunBase(runBase);
|
|
173
|
+
if (isRemoteWorkspaceUri(base)) {
|
|
174
|
+
return !raw || raw === "." ? base : `${base.replace(/\/+$/, "")}/${raw.replace(/^\/+/, "")}`;
|
|
175
|
+
}
|
|
167
176
|
// 空 = 运行基准;相对路径 = 相对运行基准(默认服务工作区,运行时可被当前项目覆盖);绝对路径 = 原样使用(不再拦截越出工作区)。
|
|
168
177
|
const targetDir = !raw ? base : isAbsolute(raw) ? resolve(raw) : resolve(base, raw);
|
|
169
178
|
if (!node.useWorktree) {
|
|
@@ -236,7 +245,12 @@ export class CanvasOrchestrator {
|
|
|
236
245
|
this.activeExecutions.delete(execKey);
|
|
237
246
|
return;
|
|
238
247
|
}
|
|
239
|
-
|
|
248
|
+
const roleDetail = node.role === "pstack"
|
|
249
|
+
? `pstack: ${String(node.config?.skill || "poteto-mode")}`
|
|
250
|
+
: node.role === "skill"
|
|
251
|
+
? `skill: ${String(node.config?.skillName || node.config?.skill || "soul")}`
|
|
252
|
+
: node.role;
|
|
253
|
+
node.currentAction = `[${node.engine.toUpperCase()}] 启动 ${node.model} 执行中 (${roleDetail})...`;
|
|
240
254
|
this.broadcast({
|
|
241
255
|
type: "canvas_node_event",
|
|
242
256
|
graphId: graph.id,
|
|
@@ -280,7 +294,44 @@ export class CanvasOrchestrator {
|
|
|
280
294
|
let prompt = isInputOnly
|
|
281
295
|
? `${contractContext}${configContext ? `\n${configContext}` : ""}`
|
|
282
296
|
: `${expandedInstruction || "按照你的角色职责进行开发"}\n${configContext}${contractContext}`;
|
|
283
|
-
|
|
297
|
+
if (!contractContext.trim() &&
|
|
298
|
+
!initialPrompt?.trim() &&
|
|
299
|
+
!node.instruction?.trim() &&
|
|
300
|
+
!isCanvasPassthroughRole(node.role)) {
|
|
301
|
+
prompt += `\n\n【首节点启动指引】: 当前为流水线首节点。请结合当前工作区代码库现状,排查梳理项目架构规范与待实现的核心任务,输出明确的分工契约交由下游节点接力执行。`;
|
|
302
|
+
}
|
|
303
|
+
if (node.role === "pstack") {
|
|
304
|
+
const skillKey = String(node.config?.skill ?? "poteto-mode").trim();
|
|
305
|
+
const item = PSTACK_SKILLS_MAP[skillKey] || PSTACK_SKILLS_MAP["poteto-mode"];
|
|
306
|
+
const skillTitle = item ? `${item.icon} ${item.nameZh} (${item.id})` : skillKey;
|
|
307
|
+
const skillDoc = item?.content ? item.content.slice(0, 4500) : "";
|
|
308
|
+
prompt = `【Pstack 严谨工程专项工作依据 · ${skillTitle}】\n${skillDoc}\n\n【Pstack 执行守则】\n1. 深入优先、拒绝 AI 废话(Unslop):严禁生成无实质意义的虚浮描述和表面修补代码;\n2. 拿实证说话:完成修改后必须提供可复现的验证依据(测试输出、运行诊断或精确行为证据);\n3. 遵循所选 Skill(${skillKey})的全部非妥协原则(Non-negotiables)开展本节点任务。\n\n【本节点任务与上下文】\n${prompt}`;
|
|
309
|
+
}
|
|
310
|
+
else if (node.role === "skill") {
|
|
311
|
+
const targetSkillName = String(node.config?.skillName ?? node.config?.skill ?? "").trim();
|
|
312
|
+
let skillInstruction = "";
|
|
313
|
+
let foundSkillTitle = targetSkillName || "未指定技能";
|
|
314
|
+
if (targetSkillName) {
|
|
315
|
+
const diskSkills = discoverDiskSkills({
|
|
316
|
+
cwd: resolvedCwd || this.baseCwd,
|
|
317
|
+
dataDir: this.dataDir,
|
|
318
|
+
scanAncestors: true,
|
|
319
|
+
});
|
|
320
|
+
const matched = diskSkills.find((s) => s.name.toLowerCase() === targetSkillName.toLowerCase());
|
|
321
|
+
if (matched) {
|
|
322
|
+
skillInstruction = readSkillInstruction(matched.filePath);
|
|
323
|
+
foundSkillTitle = matched.name;
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
const pstackItem = PSTACK_SKILLS_MAP[targetSkillName.toLowerCase()];
|
|
327
|
+
if (pstackItem) {
|
|
328
|
+
skillInstruction = pstackItem.content;
|
|
329
|
+
foundSkillTitle = `${pstackItem.icon} ${pstackItem.nameZh} (${pstackItem.id})`;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
prompt = `【技能之魂 (Soul of Skill) · ${foundSkillTitle}】\n${skillInstruction ? `你当前以此 Skill 的规约与方法论作为你的核心灵魂与行动指南:\n${skillInstruction.slice(0, 4500)}` : `以「${foundSkillTitle}」技能要求为核心灵魂与行为准则。`}\n\n【执行契约】\n必须完全以该 Skill 的专业角色与标准推进工作,结合上游交付物严谨执行。\n\n【本节点任务与上下文】\n${prompt}`;
|
|
334
|
+
}
|
|
284
335
|
let outputSummary = "";
|
|
285
336
|
// AI 条件裁决(config.aiJudge=true):条件节点走一次轻量问答做语义判定,
|
|
286
337
|
// 只能回“结论:通过/不通过”,下游按它分流;失败回落关键词。未开启还是零 token 透传。
|
|
@@ -304,6 +355,13 @@ export class CanvasOrchestrator {
|
|
|
304
355
|
: node.model;
|
|
305
356
|
this.appendLog(graph.id, nodeId, "system", `AI 裁决启动(${node.engine}/${judgeModel}):${judgeAsk.slice(0, 200)}`);
|
|
306
357
|
}
|
|
358
|
+
else if (!isCanvasPassthroughRole(node.role) && node.role !== "transform") {
|
|
359
|
+
prompt += `\n\n【流水线自动化执行安全公约】:
|
|
360
|
+
1. 自治推进:这是无人值守的自动化协同流水线,严禁停留在向用户提问或等待人工决策阶段;遇分支情况请按最佳工程实践自主裁决并推进;
|
|
361
|
+
2. 避免前台阻塞:如需启动服务或验证测试,严禁启动阻塞终端的前台长进程;遇到端口占用(如 3000/3001 等)先检测并释放,验证完成后务必确保退出并清理所有后台子进程;
|
|
362
|
+
3. 交付明确:完成时请提供清晰的修改摘要、接口契约与当前状态,供下游节点或审查门禁接力。`;
|
|
363
|
+
}
|
|
364
|
+
this.appendLog(graph.id, nodeId, "prompt", prompt.slice(0, 2000));
|
|
307
365
|
// 纯透传控制节点(条件/循环/人工/汇聚/记忆/结束):不启动 LLM 会话,直接透传摘要。人工审批节点停留在 waiting_approval 等待抽屉批准,不自动向下游流转。
|
|
308
366
|
if (node.role === "transform") {
|
|
309
367
|
const transformed = executeTransformNode(graph, node);
|
|
@@ -528,6 +586,7 @@ export class CanvasOrchestrator {
|
|
|
528
586
|
});
|
|
529
587
|
continue;
|
|
530
588
|
}
|
|
589
|
+
edge.currentLoopCount = current + 1;
|
|
531
590
|
}
|
|
532
591
|
// 触发下游目标节点
|
|
533
592
|
const targetNode = graph.nodes.find((n) => n.id === edge.targetNodeId);
|
|
@@ -646,7 +705,7 @@ export class CanvasOrchestrator {
|
|
|
646
705
|
return graph;
|
|
647
706
|
}
|
|
648
707
|
/** 向节点插话干预 (Steer) */
|
|
649
|
-
steerNode(graphId, nodeId, message) {
|
|
708
|
+
async steerNode(graphId, nodeId, message) {
|
|
650
709
|
let graph = this.runningGraphs.get(graphId);
|
|
651
710
|
if (!graph) {
|
|
652
711
|
try {
|
|
@@ -670,6 +729,27 @@ export class CanvasOrchestrator {
|
|
|
670
729
|
event: "action",
|
|
671
730
|
currentAction: node.currentAction,
|
|
672
731
|
});
|
|
732
|
+
// 真正投递给底层会话(若节点正在执行)
|
|
733
|
+
const execKey = `${graphId}:${nodeId}`;
|
|
734
|
+
const execution = this.activeExecutions.get(execKey);
|
|
735
|
+
if (execution?.session && typeof execution.session.prompt === "function") {
|
|
736
|
+
try {
|
|
737
|
+
await execution.session.prompt(message);
|
|
738
|
+
this.appendLog(graphId, nodeId, "system", "已将插话实时投递进正在运行的智能体会话。");
|
|
739
|
+
}
|
|
740
|
+
catch (err) {
|
|
741
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
742
|
+
this.appendLog(graphId, nodeId, "error", `插话投递底层会话失败: ${errMsg}`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
else if (node.status !== "running") {
|
|
746
|
+
const cleanMsg = message.trim();
|
|
747
|
+
if (cleanMsg) {
|
|
748
|
+
node.instruction = node.instruction ? `${node.instruction}\n\n[人工指导补充]: ${cleanMsg}` : cleanMsg;
|
|
749
|
+
saveCanvasGraph(this.dataDir, graph);
|
|
750
|
+
this.appendLog(graphId, nodeId, "system", "节点未在运行,指导意见已暂存为该节点下一次执行指令。");
|
|
751
|
+
}
|
|
752
|
+
}
|
|
673
753
|
}
|
|
674
754
|
/** 重置全图节点状态为 idle */
|
|
675
755
|
resetStatus(graph) {
|
|
@@ -715,7 +795,11 @@ export class CanvasOrchestrator {
|
|
|
715
795
|
if (!this.engineGetter) {
|
|
716
796
|
throw new Error("引擎服务提供者未注入");
|
|
717
797
|
}
|
|
718
|
-
|
|
798
|
+
let engineSvc = this.engineGetter(node.engine);
|
|
799
|
+
if (!engineSvc && node.engine !== "pi") {
|
|
800
|
+
engineSvc = this.engineGetter("pi");
|
|
801
|
+
this.appendLog(graph.id, node.id, "system", `引擎 ${node.engine} 不可用,已自动切换为 Pi 原生引擎。`);
|
|
802
|
+
}
|
|
719
803
|
if (!engineSvc) {
|
|
720
804
|
throw new Error(`找不到智能体引擎:${node.engine}`);
|
|
721
805
|
}
|
|
@@ -768,6 +852,11 @@ export class CanvasOrchestrator {
|
|
|
768
852
|
}
|
|
769
853
|
};
|
|
770
854
|
const cs = await engineSvc.attach(clientId, sink);
|
|
855
|
+
const execKey = `${graph.id}:${node.id}`;
|
|
856
|
+
const execution = this.activeExecutions.get(execKey);
|
|
857
|
+
if (execution) {
|
|
858
|
+
execution.session = cs;
|
|
859
|
+
}
|
|
771
860
|
try {
|
|
772
861
|
if (cs.cwd !== resolvedCwd) {
|
|
773
862
|
await cs.setCwd(resolvedCwd);
|
|
@@ -779,7 +868,19 @@ export class CanvasOrchestrator {
|
|
|
779
868
|
await cs.switchModelOrThrow(normalizeCanvasModelId(node.model));
|
|
780
869
|
}
|
|
781
870
|
catch (err) {
|
|
782
|
-
|
|
871
|
+
// 尝试安全回退到当前引擎默认可用模型,避免特定模型未配置导致整张画布崩溃
|
|
872
|
+
let fallbackOk = false;
|
|
873
|
+
if (typeof cs.switchModel === "function") {
|
|
874
|
+
try {
|
|
875
|
+
await cs.switchModel("");
|
|
876
|
+
fallbackOk = true;
|
|
877
|
+
this.appendLog(graph.id, node.id, "system", `指定模型 [${node.model}] 不可用,已自动回落至引擎默认模型。`);
|
|
878
|
+
}
|
|
879
|
+
catch { }
|
|
880
|
+
}
|
|
881
|
+
if (!fallbackOk) {
|
|
882
|
+
throw new Error(`模型未配置或不可用 [${node.model}]: ${err.message}`);
|
|
883
|
+
}
|
|
783
884
|
}
|
|
784
885
|
}
|
|
785
886
|
// 真实应用思考强度
|
|
@@ -831,16 +932,18 @@ export class CanvasOrchestrator {
|
|
|
831
932
|
throw new Error("任务执行超时 (15分钟)");
|
|
832
933
|
}
|
|
833
934
|
}
|
|
834
|
-
//
|
|
935
|
+
// 真实检测代码变更统计(仅本地项目支持本地 git diff)
|
|
835
936
|
let diffSummary = "";
|
|
836
937
|
try {
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
938
|
+
if (!isRemoteWorkspaceUri(resolvedCwd)) {
|
|
939
|
+
const { stdout: diffStat } = await exec("git", ["diff", "--stat"], {
|
|
940
|
+
cwd: resolvedCwd,
|
|
941
|
+
timeout: 5000,
|
|
942
|
+
windowsHide: true,
|
|
943
|
+
});
|
|
944
|
+
if (diffStat.trim()) {
|
|
945
|
+
diffSummary = `\n【代码变更统计】:\n${diffStat.trim()}`;
|
|
946
|
+
}
|
|
844
947
|
}
|
|
845
948
|
}
|
|
846
949
|
catch { }
|
|
@@ -853,6 +956,9 @@ export class CanvasOrchestrator {
|
|
|
853
956
|
return `[${node.title}] 交付完成${diffSummary || "(未产生文件修改)"}`;
|
|
854
957
|
}
|
|
855
958
|
finally {
|
|
959
|
+
if (execution) {
|
|
960
|
+
execution.session = undefined;
|
|
961
|
+
}
|
|
856
962
|
engineSvc.detach(clientId, sink);
|
|
857
963
|
}
|
|
858
964
|
}
|
|
@@ -996,15 +1102,15 @@ function buildPassthroughSummary(node, contractContext, initialPrompt) {
|
|
|
996
1102
|
return `【人工审批 ${node.title}】${cfgText ? `审批提示:${cfgText}` : ""}\n待人工在抽屉中批准/驳回。上游产物:\n${contract}`;
|
|
997
1103
|
case "trigger": {
|
|
998
1104
|
const popup = (initialPrompt ?? "").trim();
|
|
999
|
-
const payload = popup || String(cfg["payload"] ?? "").trim();
|
|
1105
|
+
const payload = popup || String(cfg["payload"] ?? "").trim() || String(node.instruction ?? "").trim();
|
|
1000
1106
|
const extra = contractContext ? contractContext.slice(0, 1000) : "";
|
|
1001
1107
|
if (payload)
|
|
1002
|
-
return ("【手动触发 " +
|
|
1108
|
+
return ("【手动触发 · 业务需求输入 " +
|
|
1003
1109
|
node.title +
|
|
1004
|
-
"
|
|
1110
|
+
"】任务内容:\n" +
|
|
1005
1111
|
payload.slice(0, 1500) +
|
|
1006
1112
|
(extra ? "\n上游输入:\n" + extra : ""));
|
|
1007
|
-
return "【手动触发 " + node.title + "】" + (extra ? "上游输入:\n" + extra : "(无载荷,直接启动)");
|
|
1113
|
+
return ("【手动触发 · 业务需求输入 " + node.title + "】" + (extra ? "上游输入:\n" + extra : "(无载荷,直接启动)"));
|
|
1008
1114
|
}
|
|
1009
1115
|
case "cron":
|
|
1010
1116
|
return ("【定时触发 " +
|