@zhushanwen/pi-subagent-workflow 7.3.4 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -12
- package/agents/analyst.md +61 -0
- package/agents/coder.md +70 -0
- package/agents/debugger.md +67 -0
- package/agents/doc-reviewer.md +3 -3
- package/agents/explorer.md +50 -18
- package/agents/general-purpose.md +19 -8
- package/agents/orchestrator.md +37 -32
- package/agents/planner.md +45 -11
- package/agents/researcher.md +53 -11
- package/agents/reviewer.md +74 -0
- package/package.json +1 -1
- package/skills/workflow-script-format/SKILL.md +1 -1
- package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
- package/src/execution/__tests__/agent-registry.test.ts +13 -11
- package/src/execution/__tests__/ask-user-transit-e2e.test.ts +10 -4
- package/src/execution/__tests__/before-agent-start-injection.test.ts +132 -0
- package/src/execution/__tests__/bg-notify-render.test.ts +15 -15
- package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +365 -0
- package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
- package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +215 -0
- package/src/execution/__tests__/conversation-wiring.test.ts +198 -0
- package/src/execution/__tests__/crash-recovery.test.ts +8 -2
- package/src/execution/__tests__/delivery-methods.test.ts +385 -0
- package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
- package/src/execution/__tests__/execute-and-await-worktree.test.ts +49 -2
- package/src/execution/__tests__/execute-nesting.test.ts +20 -72
- package/src/execution/__tests__/execution-record.test.ts +199 -0
- package/src/execution/__tests__/finalize-record.test.ts +170 -14
- package/src/execution/__tests__/format.test.ts +131 -7
- package/src/execution/__tests__/gc-timer.test.ts +184 -0
- package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
- package/src/execution/__tests__/helpers/spawn-mock.ts +25 -7
- package/src/execution/__tests__/index-session-start-identity.test.ts +371 -0
- package/src/execution/__tests__/index-session-start.test.ts +257 -5
- package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
- package/src/execution/__tests__/lifecycle-manager.test.ts +337 -0
- package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
- package/src/execution/__tests__/list-component.test.ts +59 -5
- package/src/execution/__tests__/list-fields.test.ts +109 -0
- package/src/execution/__tests__/model-resolver.test.ts +38 -1
- package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
- package/src/execution/__tests__/nested-visibility.test.ts +325 -0
- package/src/execution/__tests__/notifier-flush.test.ts +209 -7
- package/src/execution/__tests__/one-shot-upgrade.test.ts +205 -0
- package/src/execution/__tests__/parent-child-matrix.test.ts +336 -0
- package/src/execution/__tests__/record-store.test.ts +158 -52
- package/src/execution/__tests__/recursive-visibility-baseline.test.ts +11 -12
- package/src/execution/__tests__/recursive-visibility-env.test.ts +18 -20
- package/src/execution/__tests__/resource-policy.test.ts +109 -0
- package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
- package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
- package/src/execution/__tests__/run-spawn-edges.test.ts +18 -25
- package/src/execution/__tests__/run-spawn-integration.test.ts +29 -25
- package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
- package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +14 -11
- package/src/execution/__tests__/session-pending.test.ts +61 -2
- package/src/execution/__tests__/session-reconstructor.test.ts +4 -4
- package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
- package/src/execution/__tests__/session-runner-schema-env.test.ts +15 -21
- package/src/execution/__tests__/session-start-reaper.test.ts +10 -8
- package/src/execution/__tests__/spawn-args.test.ts +127 -49
- package/src/execution/__tests__/spawn-worktree-guidance.test.ts +1 -0
- package/src/execution/__tests__/spawned-children.test.ts +92 -0
- package/src/execution/__tests__/status-refactor.test.ts +345 -0
- package/src/execution/__tests__/stdin-writer.test.ts +97 -0
- package/src/execution/__tests__/subagent-service-message-close.test.ts +598 -0
- package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
- package/src/execution/__tests__/subagent-service.test.ts +49 -11
- package/src/execution/__tests__/timeout-integration.test.ts +27 -13
- package/src/execution/__tests__/tool-action.test.ts +12 -10
- package/src/execution/__tests__/truncline-snapshot.test.ts +81 -0
- package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
- package/src/execution/__tests__/worktree-manager.test.ts +292 -89
- package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +13 -12
- package/src/execution/argv-mirror.ts +21 -2
- package/src/execution/execution-record.ts +126 -9
- package/src/execution/finalize-record.ts +90 -13
- package/src/execution/host-mode.ts +1 -1
- package/src/execution/lifecycle-manager.ts +484 -0
- package/src/execution/lifecycle-predicates.ts +65 -0
- package/src/execution/manifest-store.ts +61 -16
- package/src/execution/model-resolver.ts +26 -5
- package/src/execution/notifier.ts +69 -12
- package/src/execution/pi-invocation.ts +21 -1
- package/src/execution/record-store.ts +554 -107
- package/src/execution/session-pending.ts +116 -45
- package/src/execution/session-reconstructor.ts +224 -7
- package/src/execution/session-runner.ts +290 -75
- package/src/execution/sessions-index.ts +304 -0
- package/src/execution/stdin-writer.ts +93 -7
- package/src/execution/stream-sink.ts +20 -3
- package/src/execution/subagent-service.ts +867 -138
- package/src/execution/turn-limiter.ts +14 -0
- package/src/execution/types.ts +204 -22
- package/src/execution/worktree-manager.ts +128 -49
- package/src/execution/worktree-registry.ts +13 -2
- package/src/index.ts +277 -19
- package/src/injectors/subagent-list-injector.ts +26 -8
- package/src/injectors/workflow-list-injector.ts +25 -8
- package/src/interface/__tests__/subagent-tool-prompt.test.ts +18 -5
- package/src/interface/__tests__/tool-render.test.ts +15 -13
- package/src/interface/bg-notify-render.ts +32 -8
- package/src/interface/command-actions.ts +26 -7
- package/src/interface/commands.ts +21 -22
- package/src/interface/format.ts +44 -17
- package/src/interface/gui-mappers.ts +6 -8
- package/src/interface/helpers.ts +170 -10
- package/src/interface/list-component.ts +53 -14
- package/src/interface/subagent-actions.ts +235 -17
- package/src/interface/subagent-tool.ts +82 -17
- package/src/interface/subagents.ts +2 -1
- package/src/interface/tool-render.ts +11 -24
- package/src/interface/tool-workflow.ts +20 -35
- package/src/interface/views/WorkflowsView.ts +89 -32
- package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +264 -0
- package/src/interface/views/__tests__/detail-content-session-file.test.ts +1 -1
- package/src/interface/views/format.ts +3 -3
- package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +325 -0
- package/src/orchestration/__tests__/args-validator.test.ts +1 -1
- package/src/orchestration/__tests__/config-loader.test.ts +38 -0
- package/src/orchestration/__tests__/error-recovery-handlers.test.ts +394 -4
- package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +4 -4
- package/src/orchestration/__tests__/execute-agent-call.test.ts +95 -0
- package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +657 -18
- package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -2
- package/src/orchestration/__tests__/lifecycle.test.ts +332 -149
- package/src/orchestration/__tests__/skill-discovery.test.ts +157 -0
- package/src/orchestration/__tests__/test-mocks.ts +191 -0
- package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +98 -0
- package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -2
- package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
- package/src/orchestration/__tests__/workflows-e2e.test.ts +1 -1
- package/src/orchestration/agent-opts-resolver.ts +4 -1
- package/src/orchestration/args-validator.ts +2 -2
- package/src/orchestration/config-loader.ts +30 -1
- package/src/orchestration/error-recovery.ts +133 -29
- package/src/orchestration/execute-agent-call.ts +31 -7
- package/src/orchestration/jsonl-run-store.ts +287 -40
- package/src/orchestration/launcher.ts +7 -1
- package/src/orchestration/lifecycle.ts +135 -132
- package/src/orchestration/models/__tests__/trace.test.ts +408 -0
- package/src/orchestration/models/budget.ts +1 -1
- package/src/orchestration/models/run-runtime.ts +15 -17
- package/src/orchestration/models/run-spec.ts +2 -2
- package/src/orchestration/models/run-state.ts +3 -3
- package/src/orchestration/models/trace.ts +95 -15
- package/src/orchestration/models/types.ts +8 -9
- package/src/orchestration/models/workflow-run.ts +50 -71
- package/src/orchestration/models/workflow-script.ts +32 -1
- package/src/orchestration/skill-discovery.ts +30 -0
- package/src/orchestration/worker-handle.ts +1 -1
- package/src/orchestration/worker-host.ts +1 -1
- package/src/orchestration/worker-script-builder.ts +29 -10
- package/src/shared/__tests__/agent-ref.test.ts +34 -0
- package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +280 -0
- package/src/shared/__tests__/resource-discovery.test.ts +55 -0
- package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
- package/src/shared/agent-ref.ts +16 -0
- package/src/shared/resource-discovery.ts +147 -58
- package/src/shared/schema-jsonify.ts +53 -0
- package/workflows/README.md +4 -4
- package/agents/code-reviewer.md +0 -47
- package/agents/context-builder.md +0 -21
- package/agents/oracle.md +0 -34
- package/agents/worker.md +0 -20
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Module-scope helpers: accessible to BOTH the IIFE body AND the outer
|
|
3
|
+
// .then()/.catch() handlers (which run outside the IIFE). _workerLogs/
|
|
4
|
+
// _pushWorkerLog/_safePost + the parentPort/workerData handles must all live
|
|
5
|
+
// here — a previous version declared _safePost inside the IIFE, so the
|
|
6
|
+
// .then()/.catch() return/error handlers threw ReferenceError: _safePost is
|
|
7
|
+
// not defined, crashing the Worker on EVERY script return (exit code 1) and
|
|
8
|
+
// losing all diagnostics. require() is cached, so destructuring once at module
|
|
9
|
+
// load and reusing everywhere avoids the redundant require calls that used to
|
|
10
|
+
// appear in the IIFE and the outer .then/.catch.
|
|
11
|
+
const { parentPort: _parentPort, workerData: _workerData } = require("node:worker_threads");
|
|
12
|
+
const _workerLogs = [];
|
|
13
|
+
// IF6(#12): known agent() fields — hoisted to module scope, built once per worker
|
|
14
|
+
// (was rebuilt inside agent() on every call; field set is call-invariant).
|
|
15
|
+
const _KNOWN_FIELDS = new Set(["prompt", "description", "schema", "model", "scene", "label", "task", "agent", "phase", "skill", "timeoutMs", "cwd", "fork", "worktree", "returnMeta", "thinkingLevel"]);
|
|
16
|
+
function _pushWorkerLog(level, args) {
|
|
17
|
+
try { _workerLogs.push({ level, message: args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ") }); } catch (e) { /* swallow */ }
|
|
18
|
+
}
|
|
19
|
+
// ── safePostMessage wrapper: 统一 postMessage 防御(DataCloneError 等)──
|
|
20
|
+
// Module-scope so the outer .then/.catch return/error handlers can use it.
|
|
21
|
+
// context 取值约定(诊断标识):固定为消息类型字面量——
|
|
22
|
+
// "agent-call" / "workflow-call" / "return" / "error",调用方据此在日志里
|
|
23
|
+
// 一眼定位是哪类 postMessage 失败。新增调用点必须传对应 context。
|
|
24
|
+
function _safePost(msg, context) {
|
|
25
|
+
try { _parentPort.postMessage(msg); return true; }
|
|
26
|
+
catch (e) {
|
|
27
|
+
const errMsg = e && e.message ? e.message : String(e);
|
|
28
|
+
const stack = e && e.stack ? e.stack : "";
|
|
29
|
+
_pushWorkerLog("error", ["[postMessage failed:" + context + "]", errMsg, stack]);
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
(async () => {
|
|
34
|
+
const parentPort = _parentPort;
|
|
35
|
+
const workerData = _workerData;
|
|
36
|
+
|
|
37
|
+
if (!parentPort) {
|
|
38
|
+
throw new Error("Workflow worker: parentPort is null — not running in a Worker thread");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ── Intercept console.* to avoid leaking worker diagnostics into the input area ──
|
|
42
|
+
console.log = function (...args) { _pushWorkerLog("log", args); };
|
|
43
|
+
console.warn = function (...args) { _pushWorkerLog("warn", args); };
|
|
44
|
+
console.error = function (...args) { _pushWorkerLog("error", args); };
|
|
45
|
+
console.info = function (...args) { _pushWorkerLog("info", args); };
|
|
46
|
+
|
|
47
|
+
// ── Internal state ──
|
|
48
|
+
let _callIdCounter = 0;
|
|
49
|
+
let _agentCallCount = 0;
|
|
50
|
+
const _pendingCalls = new Map();
|
|
51
|
+
const _callCache = workerData.callCache instanceof Map
|
|
52
|
+
? workerData.callCache
|
|
53
|
+
: new Map(Object.entries(workerData.callCache || {}).map(([k, v]) => [Number(k), v]));
|
|
54
|
+
|
|
55
|
+
// ── Injected globals ──
|
|
56
|
+
const $ARGS = (workerData.args && typeof workerData.args === "object") ? workerData.args : {};
|
|
57
|
+
const args = $ARGS;
|
|
58
|
+
const $WORKSPACE = typeof workerData.workspace === "string" ? workerData.workspace : "";
|
|
59
|
+
const _budgetData = {
|
|
60
|
+
total: (workerData.budget && workerData.budget.maxTokens) || 0,
|
|
61
|
+
_spentTokens: (workerData.budget && workerData.budget.usedTokens) ?? 0,
|
|
62
|
+
_spentCost: (workerData.budget && workerData.budget.usedCost) ?? 0,
|
|
63
|
+
};
|
|
64
|
+
const $BUDGET = {
|
|
65
|
+
get total() { return _budgetData.total; },
|
|
66
|
+
spent() { return _budgetData._spentTokens; },
|
|
67
|
+
remaining() { return Math.max(0, _budgetData.total - _budgetData._spentTokens); },
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// ── Run-level model/thinkingLevel override (Option B symmetric single-path) ──
|
|
71
|
+
// Injected from workerData (set by workerHost from RunSpec.model/thinkingLevel).
|
|
72
|
+
// agent() reads these as run-level defaults; per-call explicit opts still win.
|
|
73
|
+
const $MODEL = (workerData.model && typeof workerData.model === "string") ? workerData.model : undefined;
|
|
74
|
+
const $THINKING_LEVEL = (workerData.thinkingLevel && typeof workerData.thinkingLevel === "string") ? workerData.thinkingLevel : undefined;
|
|
75
|
+
|
|
76
|
+
// ── WorkflowAbortedError ──
|
|
77
|
+
class WorkflowAbortedError extends Error {
|
|
78
|
+
constructor(reason) {
|
|
79
|
+
super("Workflow aborted: " + (reason || "No reason"));
|
|
80
|
+
this.name = "WorkflowAbortedError";
|
|
81
|
+
this.reason = reason || "";
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── Message handler (main thread → worker) ──
|
|
86
|
+
parentPort.on("message", (msg) => {
|
|
87
|
+
if (msg.type === "agent-result") {
|
|
88
|
+
const pending = _pendingCalls.get(msg.callId);
|
|
89
|
+
if (pending) {
|
|
90
|
+
_pendingCalls.delete(msg.callId);
|
|
91
|
+
if (typeof msg.result !== "undefined") {
|
|
92
|
+
_callCache.set(msg.callId, msg.result);
|
|
93
|
+
}
|
|
94
|
+
// 失败不传播到 agent 外部:resolve 而非 reject。
|
|
95
|
+
// 旧实现在 result.error 时 reject,单 agent 失败会冒到 worker 顶层 .catch()
|
|
96
|
+
// → 发 type:"error" → handleScriptError → rebuildRuntime → SIGKILL 同伴进程,
|
|
97
|
+
// 把单点失败放大成整批崩溃。改为始终 resolve(错误时回退到 content 文本),
|
|
98
|
+
// 让 parallel() 下的脚本容错循环(parseResult → null → skip)自然接管。
|
|
99
|
+
// 错误原因已由主线程 executeAgentCall → trace.update(result.error) 保留在 trace/TUI,
|
|
100
|
+
// 不丢失。失败 resolve 为空字符串是既定容错策略。
|
|
101
|
+
// parsedOutput: validated data object from structured-output execute().
|
|
102
|
+
// Fallback to content (raw text) when no schema was requested or on error.
|
|
103
|
+
// W2 改动 9(b):returnMeta===true 时 resolve {value,sessionFile,worktreePath,error}(对称缓存重放 9c);否则单值。
|
|
104
|
+
const _value = msg.result.parsedOutput ?? msg.result.content;
|
|
105
|
+
if (pending.returnMeta) {
|
|
106
|
+
pending.resolve({
|
|
107
|
+
value: _value,
|
|
108
|
+
sessionFile: msg.result.sessionFile,
|
|
109
|
+
worktreePath: msg.result.worktreePath,
|
|
110
|
+
error: msg.result.error,
|
|
111
|
+
});
|
|
112
|
+
} else {
|
|
113
|
+
pending.resolve(_value);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} else if (msg.type === "workflow-result") {
|
|
117
|
+
const pending = _pendingCalls.get(msg.callId);
|
|
118
|
+
if (pending) {
|
|
119
|
+
_pendingCalls.delete(msg.callId);
|
|
120
|
+
pending.resolve(msg.result);
|
|
121
|
+
}
|
|
122
|
+
} else if (msg.type === "abort") {
|
|
123
|
+
const err = new WorkflowAbortedError(msg.reason);
|
|
124
|
+
_pendingCalls.forEach((p) => { p.reject(err); });
|
|
125
|
+
_pendingCalls.clear();
|
|
126
|
+
} else if (msg.type === "budget-update" && msg.budget) {
|
|
127
|
+
_budgetData._spentTokens = msg.budget.usedTokens ?? _budgetData._spentTokens;
|
|
128
|
+
_budgetData._spentCost = msg.budget.usedCost ?? _budgetData._spentCost;
|
|
129
|
+
}
|
|
130
|
+
// "budget-warning" is informational; no required handling
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
let _currentPhase = "";
|
|
134
|
+
function phase(name) { _currentPhase = String(name); }
|
|
135
|
+
|
|
136
|
+
function log(msg) {
|
|
137
|
+
try { parentPort.postMessage({ type: "log", phase: _currentPhase, message: String(msg) }); } catch(e) { /* swallow */ }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function agent(firstArg, secondArg) {
|
|
141
|
+
let opts;
|
|
142
|
+
if (typeof firstArg === "string") {
|
|
143
|
+
opts = {
|
|
144
|
+
prompt: firstArg,
|
|
145
|
+
description: (secondArg && typeof secondArg === "object" && secondArg.label) || undefined,
|
|
146
|
+
schema: (secondArg && typeof secondArg === "object" && secondArg.schema) || undefined,
|
|
147
|
+
model: (secondArg && typeof secondArg === "object" && secondArg.model) || $MODEL,
|
|
148
|
+
scene: (secondArg && typeof secondArg === "object" && secondArg.scene) || undefined,
|
|
149
|
+
phase: (secondArg && typeof secondArg === "object" && secondArg.phase) || undefined,
|
|
150
|
+
thinkingLevel: (secondArg && typeof secondArg === "object" && secondArg.thinkingLevel) || $THINKING_LEVEL,
|
|
151
|
+
};
|
|
152
|
+
} else if (typeof firstArg === "object" && firstArg !== null) {
|
|
153
|
+
if (firstArg.prompt) {
|
|
154
|
+
opts = firstArg;
|
|
155
|
+
} else if (firstArg.task || firstArg.agent) {
|
|
156
|
+
// fork/worktree/returnMeta forwarded here (parity with agent({prompt,...}) and direct-pass
|
|
157
|
+
// branches). Previously this shortcut dropped them (w1 only noted, not wired).
|
|
158
|
+
opts = {
|
|
159
|
+
prompt: firstArg.task || firstArg.prompt || "",
|
|
160
|
+
description: firstArg.label || firstArg.description,
|
|
161
|
+
agent: firstArg.agent,
|
|
162
|
+
schema: firstArg.schema,
|
|
163
|
+
model: firstArg.model || $MODEL,
|
|
164
|
+
scene: firstArg.scene,
|
|
165
|
+
skill: firstArg.skill,
|
|
166
|
+
timeoutMs: firstArg.timeoutMs,
|
|
167
|
+
cwd: firstArg.cwd,
|
|
168
|
+
fork: firstArg.fork,
|
|
169
|
+
worktree: firstArg.worktree,
|
|
170
|
+
returnMeta: firstArg.returnMeta,
|
|
171
|
+
thinkingLevel: firstArg.thinkingLevel || $THINKING_LEVEL,
|
|
172
|
+
};
|
|
173
|
+
} else {
|
|
174
|
+
opts = firstArg;
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
throw new Error("agent() requires a prompt string or options object as first argument");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Run-level fallback for object branches (opts = firstArg direct assign).
|
|
181
|
+
// Priority: agent() explicit > $MODEL global (set from workerData.model).
|
|
182
|
+
if (!opts.model && $MODEL) opts.model = $MODEL;
|
|
183
|
+
if (!opts.thinkingLevel && $THINKING_LEVEL) opts.thinkingLevel = $THINKING_LEVEL;
|
|
184
|
+
|
|
185
|
+
// Validate known agent() fields to catch API misuse early (_KNOWN_FIELDS at module scope)
|
|
186
|
+
const _unknownFields = Object.keys(opts).filter((k) => !_KNOWN_FIELDS.has(k));
|
|
187
|
+
if (_unknownFields.length > 0) {
|
|
188
|
+
_pushWorkerLog("warn", ["[workflow] agent() received unknown fields: " + _unknownFields.join(", ") + ". Known fields: prompt, description, schema, model, scene, label, task, agent, phase, skill, timeoutMs, cwd, fork, worktree, returnMeta, thinkingLevel"]);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const callId = _callIdCounter;
|
|
192
|
+
_callIdCounter++;
|
|
193
|
+
_agentCallCount++;
|
|
194
|
+
if (_callCache.has(callId)) {
|
|
195
|
+
const cached = _callCache.get(callId);
|
|
196
|
+
// 与 live handler 对齐:失败也 resolve(回退 content),不 throw。
|
|
197
|
+
// 见 agent-result 消息处理的注释:拒绝传播失败到 agent 外部。
|
|
198
|
+
// W2 改动 9(c):returnMeta 分支(对称 handler 9b),opts 仍在闭包作用域。
|
|
199
|
+
if (!cached) return undefined;
|
|
200
|
+
const _cachedValue = cached.parsedOutput ?? cached.content;
|
|
201
|
+
if (opts.returnMeta === true) {
|
|
202
|
+
return {
|
|
203
|
+
value: _cachedValue,
|
|
204
|
+
sessionFile: cached.sessionFile,
|
|
205
|
+
worktreePath: cached.worktreePath,
|
|
206
|
+
error: cached.error,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return _cachedValue;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const _effectivePhase = opts.phase || _currentPhase;
|
|
213
|
+
delete opts.phase;
|
|
214
|
+
|
|
215
|
+
if (!_safePost({ type: "agent-call", callId, opts, phase: _effectivePhase }, "agent-call")) {
|
|
216
|
+
return Promise.reject(new Error("postMessage failed for agent-call (callId=" + callId + "): see workerLogs"));
|
|
217
|
+
}
|
|
218
|
+
return new Promise((resolve, reject) => {
|
|
219
|
+
_pendingCalls.set(callId, { resolve, reject, returnMeta: opts.returnMeta === true });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function parallel(calls) {
|
|
224
|
+
if (typeof calls === "function") { return calls(); }
|
|
225
|
+
const settled = await Promise.allSettled(calls.map((c) => {
|
|
226
|
+
if (c && typeof c.then === "function") { return c; }
|
|
227
|
+
if (typeof c === "function") { return c(); }
|
|
228
|
+
if (typeof c === "object" && c !== null && (c.task || c.agent)) { return agent(c); }
|
|
229
|
+
return agent(c);
|
|
230
|
+
}));
|
|
231
|
+
return settled.map((r) => {
|
|
232
|
+
if (r.status === "fulfilled") {
|
|
233
|
+
const v = r.value;
|
|
234
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
235
|
+
// 主线程 fallback(postAgentResult/postResult serialization failed)回发的对象含 error 字段
|
|
236
|
+
// → 归一化为 failed 形状,与脚本侧 r.status === "failed" 检查统一
|
|
237
|
+
if (typeof v.error === "string" && v.error.length > 0) return { status: "failed", error: v.error };
|
|
238
|
+
return v;
|
|
239
|
+
}
|
|
240
|
+
return { status: "failed", error: "agent returned non-object result (type=" + typeof v + ")" };
|
|
241
|
+
}
|
|
242
|
+
const reason = r.reason;
|
|
243
|
+
const errMsg = reason instanceof Error ? reason.message : String(reason);
|
|
244
|
+
return { status: "failed", error: errMsg };
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function pipeline(firstArg, ...restStages) {
|
|
249
|
+
// Single-arg mode: pipeline([stage1, stage2, ...])
|
|
250
|
+
if (Array.isArray(firstArg) && restStages.length === 0) {
|
|
251
|
+
let result;
|
|
252
|
+
for (let i = 0; i < firstArg.length; i++) {
|
|
253
|
+
try { result = await firstArg[i](result); }
|
|
254
|
+
catch (e) {
|
|
255
|
+
const msg = e && e.message ? e.message : String(e);
|
|
256
|
+
_pushWorkerLog("error", ["[pipeline stage " + i + " failed]", msg]);
|
|
257
|
+
throw e;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
// Cartesian product mode: pipeline([items], stage1, stage2, ...)
|
|
263
|
+
if (Array.isArray(firstArg) && restStages.length > 0 && typeof restStages[0] === "function") {
|
|
264
|
+
const results = [];
|
|
265
|
+
for (let idx = 0; idx < firstArg.length; idx++) {
|
|
266
|
+
const item = firstArg[idx];
|
|
267
|
+
let val = item;
|
|
268
|
+
let failed = false;
|
|
269
|
+
for (const stage of restStages) {
|
|
270
|
+
if (failed) break;
|
|
271
|
+
try { val = await stage(val); }
|
|
272
|
+
catch (e) {
|
|
273
|
+
const msg = e && e.message ? e.message : String(e);
|
|
274
|
+
_pushWorkerLog("error", ["[pipeline cartesian stage failed for item " + (idx + 1) + "]", msg]);
|
|
275
|
+
val = null; failed = true;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
results.push(val);
|
|
279
|
+
}
|
|
280
|
+
return results;
|
|
281
|
+
}
|
|
282
|
+
throw new Error("pipeline() expects pipeline([stage1, ...]) or pipeline([items], stage1, ...)");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ── workflow global — nested workflow invocation ──
|
|
286
|
+
async function workflow(name, args) {
|
|
287
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
288
|
+
throw new Error("workflow() requires a workflow name string as first argument");
|
|
289
|
+
}
|
|
290
|
+
const workflowArgs = (typeof args === "object" && args !== null) ? args : {};
|
|
291
|
+
const callId = _callIdCounter;
|
|
292
|
+
_callIdCounter++;
|
|
293
|
+
if (!_safePost({ type: "workflow-call", callId, name, args: workflowArgs }, "workflow-call")) {
|
|
294
|
+
return Promise.reject(new Error("postMessage failed for workflow-call (name=" + name + "): see workerLogs"));
|
|
295
|
+
}
|
|
296
|
+
return new Promise((resolve, reject) => {
|
|
297
|
+
_pendingCalls.set(callId, { resolve, reject });
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ── User workflow script ──
|
|
302
|
+
// sample exercising template features
|
|
303
|
+
const name = $ARGS.name ?? "default";
|
|
304
|
+
phase("build");
|
|
305
|
+
const spec = await agent("build it", { label: "builder", schema: { type: "object" } });
|
|
306
|
+
const results = await parallel([
|
|
307
|
+
agent({ task: "unit tests", agent: "./tester.md" }),
|
|
308
|
+
agent({ task: "lint", agent: "./linter.md", skill: "lint-skill" }),
|
|
309
|
+
]);
|
|
310
|
+
await pipeline([(x) => x, (x) => x]);
|
|
311
|
+
await workflow("deploy", { env: "prod" });
|
|
312
|
+
log("done " + name + " " + $WORKSPACE + " " + $BUDGET.remaining());
|
|
313
|
+
module.exports = { execute: async (ctx) => ctx.agent("finalize") };
|
|
314
|
+
|
|
315
|
+
// ── Auto-invoke execute() for module.exports pattern ──
|
|
316
|
+
if (typeof module !== "undefined" && module.exports && typeof module.exports.execute === "function") {
|
|
317
|
+
return await module.exports.execute({ agent, parallel, pipeline, phase, log, workflow, $ARGS, $WORKSPACE, $BUDGET });
|
|
318
|
+
}
|
|
319
|
+
})().then((result) => {
|
|
320
|
+
const runId = (_workerData.args && typeof _workerData.args === "object" && _workerData.args._runId) || "";
|
|
321
|
+
_safePost({ type: "return", runId, result, workerLogs: _workerLogs }, "return");
|
|
322
|
+
}).catch((err) => {
|
|
323
|
+
const runId = (_workerData.args && typeof _workerData.args === "object" && _workerData.args._runId) || "";
|
|
324
|
+
_safePost({ type: "error", runId, error: err.message || String(err), workerLogs: _workerLogs }, "error");
|
|
325
|
+
});
|
|
@@ -93,7 +93,7 @@ describe("validateRunArgs — 校验语义", () => {
|
|
|
93
93
|
const args = { targetType: "git-diff", target: "main", autoCommit: "false", maxRounds: "10" };
|
|
94
94
|
const spec = makeSpec(reviewFixLoopParameters(), args);
|
|
95
95
|
expect(() => validateRunArgs(spec)).not.toThrow();
|
|
96
|
-
expect(spec.args).toBe(args); // 原地 mutate,引用不变(worker
|
|
96
|
+
expect(spec.args).toBe(args); // 原地 mutate,引用不变(worker 启动/崩溃重跑同一对象)
|
|
97
97
|
expect(spec.args.autoCommit).toBe(false);
|
|
98
98
|
expect(spec.args.maxRounds).toBe(10);
|
|
99
99
|
});
|
|
@@ -446,6 +446,44 @@ describe("getWorkflowByPath — 按绝对路径加载(S2 路径统一核心新
|
|
|
446
446
|
expect(meta!.phases).toEqual([]);
|
|
447
447
|
expect(meta!.path).toBe("/nonexistent/ghost.js");
|
|
448
448
|
});
|
|
449
|
+
|
|
450
|
+
// ── IF4(外部 #5 残留):source 按路径推导(.tmp → tmp) ──
|
|
451
|
+
// 修复前:任意路径硬编码 "user-pi" → .tmp 下脚本按路径加载被错标 saved,
|
|
452
|
+
// 与 discoverWorkflows 对 project-pi-tmp 源的正确映射矛盾。
|
|
453
|
+
|
|
454
|
+
it("IF4: workspaceRoot/.pi/workflows/.tmp 下的脚本按路径加载 source = tmp", async () => {
|
|
455
|
+
// findWorkspaceRoot 指向临时工作区 → tmp 前缀判定生效
|
|
456
|
+
mockedFindWorkspaceRoot.mockReturnValue(ws.root);
|
|
457
|
+
const tmpScriptPath = await writeScript(ws.tmpDir, "adhoc.js", validScript("adhoc"));
|
|
458
|
+
|
|
459
|
+
const meta = await getWorkflowByPath(tmpScriptPath);
|
|
460
|
+
|
|
461
|
+
expect(meta).toBeDefined();
|
|
462
|
+
expect(meta!.available).toBe(true);
|
|
463
|
+
expect(meta!.source).toBe("tmp");
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
it("IF4: 非 .tmp 路径按路径加载 source = saved(输出不变,DS4)", async () => {
|
|
467
|
+
mockedFindWorkspaceRoot.mockReturnValue(ws.root);
|
|
468
|
+
const savedPath = await writeScript(ws.projectDir, "byfile.js", validScript("byfile"));
|
|
469
|
+
|
|
470
|
+
const meta = await getWorkflowByPath(savedPath);
|
|
471
|
+
|
|
472
|
+
expect(meta).toBeDefined();
|
|
473
|
+
expect(meta!.available).toBe(true);
|
|
474
|
+
expect(meta!.source).toBe("saved");
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
it("IF4: tmp 前缀判定不误伤同名前缀目录(.tmp-other/ 非 .tmp/)", async () => {
|
|
478
|
+
mockedFindWorkspaceRoot.mockReturnValue(ws.root);
|
|
479
|
+
const siblingDir = join(ws.projectDir, ".tmp-other");
|
|
480
|
+
await mkdir(siblingDir, { recursive: true });
|
|
481
|
+
const siblingPath = await writeScript(siblingDir, "sib.js", validScript("sib"));
|
|
482
|
+
|
|
483
|
+
const meta = await getWorkflowByPath(siblingPath);
|
|
484
|
+
|
|
485
|
+
expect(meta!.source).toBe("saved");
|
|
486
|
+
});
|
|
449
487
|
});
|
|
450
488
|
|
|
451
489
|
describe("WorkflowScanConfig 类型接口", () => {
|