@zhushanwen/subagent-core 0.2.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 +114 -0
- package/dist/chunk-3VOERJPJ.js +22 -0
- package/dist/chunk-A4IVZWVX.js +31 -0
- package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
- package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
- package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
- package/dist/execution/engine/engines/zcode/constants.js +22 -0
- package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
- package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
- package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
- package/dist/execution/engine/engines/zcode/reader.js +239 -0
- package/dist/execution/engine/paths.cjs +55 -0
- package/dist/execution/engine/paths.d.cts +8 -0
- package/dist/execution/engine/paths.d.ts +8 -0
- package/dist/execution/engine/paths.js +26 -0
- package/dist/execution/relay-env.cjs +62 -0
- package/dist/execution/relay-env.d.cts +33 -0
- package/dist/execution/relay-env.d.ts +33 -0
- package/dist/execution/relay-env.js +20 -0
- package/dist/index.cjs +1852 -0
- package/dist/index.d.cts +1184 -0
- package/dist/index.d.ts +1184 -0
- package/dist/index.js +1810 -0
- package/dist/types-BxyAidGf.d.cts +875 -0
- package/dist/types-BxyAidGf.d.ts +875 -0
- package/package.json +99 -0
- package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
- package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
- package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
- package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
- package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
- package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
- package/src/__tests__/m2-append-content-probe.test.ts +73 -0
- package/src/__tests__/manifest-store.test.ts +368 -0
- package/src/__tests__/record-store-cache.test.ts +335 -0
- package/src/__tests__/record-store-index.test.ts +560 -0
- package/src/__tests__/record-store-last-line.test.ts +129 -0
- package/src/__tests__/review-fix-loop-script.test.ts +288 -0
- package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
- package/src/__tests__/robustness-low-batch1.test.ts +286 -0
- package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
- package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
- package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
- package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
- package/src/__tests__/session-runner.test.ts +69 -0
- package/src/__tests__/smoke.test.ts +9 -0
- package/src/__tests__/stream-sink.test.ts +203 -0
- package/src/core/__tests__/host-services.test.ts +144 -0
- package/src/core/__tests__/logger.test.ts +78 -0
- package/src/core/__tests__/notify-ports.test.ts +104 -0
- package/src/core/host-services.ts +97 -0
- package/src/core/logger.ts +47 -0
- package/src/core/notify-ports.ts +126 -0
- package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
- package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
- package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
- package/src/execution/__tests__/alive-store.test.ts +147 -0
- package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
- package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
- package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
- package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
- package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
- package/src/execution/__tests__/config.test.ts +302 -0
- package/src/execution/__tests__/delivery-methods.test.ts +424 -0
- package/src/execution/__tests__/dialog-queue.test.ts +299 -0
- package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
- package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
- package/src/execution/__tests__/execute-nesting.test.ts +323 -0
- package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
- package/src/execution/__tests__/execution-record.test.ts +1394 -0
- package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
- package/src/execution/__tests__/finalize-record.test.ts +367 -0
- package/src/execution/__tests__/finalized-marker.test.ts +104 -0
- package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
- 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/mock-extension-api.ts +30 -0
- package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
- package/src/execution/__tests__/host-mode.test.ts +87 -0
- package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
- package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
- package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
- package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
- package/src/execution/__tests__/model-resolver.test.ts +465 -0
- 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__/output-collector.test.ts +358 -0
- package/src/execution/__tests__/path-encoding.test.ts +104 -0
- package/src/execution/__tests__/pi-invocation.test.ts +134 -0
- package/src/execution/__tests__/record-store.test.ts +1057 -0
- package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
- package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
- package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
- package/src/execution/__tests__/relay-env.test.ts +42 -0
- package/src/execution/__tests__/resource-policy.test.ts +109 -0
- package/src/execution/__tests__/rpc-mode.test.ts +89 -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 +687 -0
- package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
- package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
- package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
- package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
- package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
- package/src/execution/__tests__/session-file-gc.test.ts +293 -0
- package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
- package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
- package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
- package/src/execution/__tests__/spawn-args.test.ts +445 -0
- package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
- package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
- package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
- package/src/execution/__tests__/spawned-children.test.ts +92 -0
- package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
- package/src/execution/__tests__/stdin-writer.test.ts +462 -0
- package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
- package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
- package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
- package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
- package/src/execution/__tests__/subagent-service.test.ts +788 -0
- package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
- package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
- package/src/execution/__tests__/temp-prompt.test.ts +53 -0
- package/src/execution/__tests__/timeout-integration.test.ts +615 -0
- package/src/execution/__tests__/tombstone-store.test.ts +73 -0
- package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
- package/src/execution/__tests__/turn-limiter.test.ts +65 -0
- package/src/execution/__tests__/ui-channels.test.ts +187 -0
- package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
- package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
- package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
- package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
- package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
- package/src/execution/__tests__/worktree-manager.test.ts +633 -0
- package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
- package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
- package/src/execution/__tests__/worktree-registry.test.ts +199 -0
- package/src/execution/agent-registry.ts +199 -0
- package/src/execution/agent-result-mapper.ts +90 -0
- package/src/execution/alive-store.ts +119 -0
- package/src/execution/argv-mirror.ts +113 -0
- package/src/execution/best-effort.ts +38 -0
- package/src/execution/channel-registry-access.ts +144 -0
- package/src/execution/concurrency-pool.ts +116 -0
- package/src/execution/config.ts +165 -0
- package/src/execution/dialog-queue.ts +330 -0
- package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
- package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
- package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
- package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
- package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
- package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
- package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
- package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
- package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
- package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
- package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
- package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
- package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
- package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
- package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
- package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
- package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
- package/src/execution/engine/__tests__/paths.test.ts +39 -0
- package/src/execution/engine/__tests__/registry.test.ts +120 -0
- package/src/execution/engine/__tests__/routing.test.ts +231 -0
- package/src/execution/engine/common/data-dir.ts +66 -0
- package/src/execution/engine/common/errors.ts +183 -0
- package/src/execution/engine/common/event-journal.ts +254 -0
- package/src/execution/engine/common/journal-replay.ts +62 -0
- package/src/execution/engine/common/kill-chain.ts +221 -0
- package/src/execution/engine/common/nesting-guard.ts +50 -0
- package/src/execution/engine/common/persona-router.ts +108 -0
- package/src/execution/engine/common/pool-manager.ts +226 -0
- package/src/execution/engine/common/schema-emulation.ts +189 -0
- package/src/execution/engine/common/session-view-projection.ts +51 -0
- package/src/execution/engine/engine-discovery.ts +65 -0
- package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
- package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
- package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
- package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
- package/src/execution/engine/engines/pi/reader.ts +48 -0
- package/src/execution/engine/engines/pi/registration.ts +35 -0
- package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
- package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
- package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
- package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
- package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
- package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
- package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
- package/src/execution/engine/engines/zcode/constants.ts +43 -0
- package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
- package/src/execution/engine/engines/zcode/launcher.ts +161 -0
- package/src/execution/engine/engines/zcode/parser.ts +436 -0
- package/src/execution/engine/engines/zcode/preparer.ts +363 -0
- package/src/execution/engine/engines/zcode/reader.ts +381 -0
- package/src/execution/engine/engines/zcode/registration.ts +37 -0
- package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
- package/src/execution/engine/host-task-spec.ts +47 -0
- package/src/execution/engine/model-prompt.ts +158 -0
- package/src/execution/engine/paths.ts +42 -0
- package/src/execution/engine/port.ts +153 -0
- package/src/execution/engine/registry.ts +133 -0
- package/src/execution/engine/routing.ts +218 -0
- package/src/execution/engine/types.ts +309 -0
- package/src/execution/execute-options-mapper.ts +115 -0
- package/src/execution/execution-record.ts +984 -0
- package/src/execution/finalize-record.ts +254 -0
- package/src/execution/finalized-marker.ts +70 -0
- package/src/execution/get-state-handshake.ts +104 -0
- package/src/execution/host-mode.ts +56 -0
- package/src/execution/idle-gc.ts +47 -0
- package/src/execution/lifecycle-manager.ts +513 -0
- package/src/execution/lifecycle-predicates.ts +65 -0
- package/src/execution/manifest-store.ts +256 -0
- package/src/execution/model-config-service.ts +250 -0
- package/src/execution/model-resolver.ts +248 -0
- package/src/execution/notifier.ts +372 -0
- package/src/execution/notify-ledger.ts +580 -0
- package/src/execution/output-collector.ts +228 -0
- package/src/execution/path-encoding.ts +60 -0
- package/src/execution/pi-invocation.ts +120 -0
- package/src/execution/record-entry.ts +132 -0
- package/src/execution/record-store.ts +1265 -0
- package/src/execution/relay-env.ts +37 -0
- package/src/execution/session-context-resolver.ts +64 -0
- package/src/execution/session-file-gc.ts +120 -0
- package/src/execution/session-pending.ts +170 -0
- package/src/execution/session-reconstructor.ts +678 -0
- package/src/execution/session-runner.ts +1789 -0
- package/src/execution/sessions-index.ts +304 -0
- package/src/execution/spawn-event-adapter.ts +363 -0
- package/src/execution/stdin-writer.ts +198 -0
- package/src/execution/stream-sink.ts +126 -0
- package/src/execution/subagent-service.ts +2268 -0
- package/src/execution/subprocess-agent-runner.ts +317 -0
- package/src/execution/temp-prompt.ts +62 -0
- package/src/execution/tombstone-store.ts +72 -0
- package/src/execution/turn-limiter.ts +102 -0
- package/src/execution/types.ts +1023 -0
- package/src/execution/ui-channels.ts +216 -0
- package/src/execution/ui-interaction-model.ts +48 -0
- package/src/execution/ui-request-handler-factory.ts +243 -0
- package/src/execution/ui-request-observability.ts +81 -0
- package/src/execution/ui-request-queue.ts +184 -0
- package/src/execution/worktree-manager.ts +688 -0
- package/src/execution/worktree-registry.ts +279 -0
- package/src/index.ts +87 -0
- package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
- package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
- package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
- package/src/orchestration/__tests__/args-validator.test.ts +143 -0
- package/src/orchestration/__tests__/config-loader.test.ts +503 -0
- package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
- package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
- package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
- package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
- package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
- package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
- package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
- package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
- package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
- package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
- package/src/orchestration/__tests__/script-lint.test.ts +831 -0
- package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
- package/src/orchestration/__tests__/test-mocks.ts +197 -0
- package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
- package/src/orchestration/__tests__/worker-host.test.ts +120 -0
- package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
- package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
- package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
- package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
- package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
- package/src/orchestration/agent-opts-resolver.ts +174 -0
- package/src/orchestration/args-validator.ts +127 -0
- package/src/orchestration/config-loader.ts +316 -0
- package/src/orchestration/error-recovery.ts +1018 -0
- package/src/orchestration/execute-agent-call.ts +256 -0
- package/src/orchestration/launcher.ts +455 -0
- package/src/orchestration/lifecycle.ts +399 -0
- package/src/orchestration/models/__tests__/budget.test.ts +307 -0
- package/src/orchestration/models/agent-call.ts +83 -0
- package/src/orchestration/models/budget.ts +118 -0
- package/src/orchestration/models/ports.ts +164 -0
- package/src/orchestration/models/run-runtime.ts +104 -0
- package/src/orchestration/models/run-spec.ts +83 -0
- package/src/orchestration/models/run-state.ts +44 -0
- package/src/orchestration/models/trace.ts +183 -0
- package/src/orchestration/models/types.ts +301 -0
- package/src/orchestration/models/workflow-run.ts +254 -0
- package/src/orchestration/models/workflow-script-registry.ts +35 -0
- package/src/orchestration/models/workflow-script.ts +117 -0
- package/src/orchestration/script-lint.ts +766 -0
- package/src/orchestration/skill-discovery.ts +135 -0
- package/src/orchestration/worker-handle.ts +115 -0
- package/src/orchestration/worker-host.ts +98 -0
- package/src/orchestration/worker-script-builder.ts +421 -0
- package/src/orchestration/workflow-files.ts +85 -0
- package/src/orchestration/workflow-script-registry-impl.ts +133 -0
- package/src/shared/__tests__/agent-ref.test.ts +34 -0
- package/src/shared/__tests__/meta-parser.test.ts +304 -0
- package/src/shared/__tests__/model-ref.test.ts +306 -0
- package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
- package/src/shared/__tests__/resource-discovery.test.ts +749 -0
- package/src/shared/__tests__/resource-meta.test.ts +51 -0
- package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
- package/src/shared/__tests__/timer-delay.test.ts +61 -0
- package/src/shared/agent-event.ts +13 -0
- package/src/shared/agent-ref.ts +57 -0
- package/src/shared/meta-parser.ts +261 -0
- package/src/shared/model-ref.ts +286 -0
- package/src/shared/resource-discovery.ts +835 -0
- package/src/shared/resource-meta.ts +65 -0
- package/src/shared/schema-env.ts +44 -0
- package/src/shared/schema-jsonify.ts +58 -0
- package/src/shared/timer-delay.ts +54 -0
- package/src/shared/xml-injection.ts +35 -0
- package/workflows/README.md +81 -0
- package/workflows/_shared/agent-refs.cjs +40 -0
- package/workflows/chain.js +137 -0
- package/workflows/map-reduce.js +180 -0
- package/workflows/parallel.js +154 -0
- package/workflows/review-fix-loop-utils.cjs +1542 -0
- package/workflows/review-fix-loop.js +1605 -0
- package/workflows/scatter-gather.js +184 -0
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* workflow() 嵌套调用 — E2E 集成测试。
|
|
3
|
+
*
|
|
4
|
+
* 从 handleWorkerMessage 入口(发 workflow-call 消息)出发,走完完整链路:
|
|
5
|
+
* handleWorkerMessage → dispatchWorkflowCall → deps.onWorkflowCall(executeNestedWorkflow)
|
|
6
|
+
* → runWorkflow(mock) → pollRunToResult → postMessage(workflow-result)。
|
|
7
|
+
*
|
|
8
|
+
* 验证 Wave 1(协议层 dispatchWorkflowCall)与 Wave 2(实现 executeNestedWorkflow)
|
|
9
|
+
* 的端到端对接正确。
|
|
10
|
+
*
|
|
11
|
+
* Mock 策略:
|
|
12
|
+
* - vi.mock("../lifecycle.ts") 控制 runWorkflow:返回固定 runId + 把预构造的 child run
|
|
13
|
+
* 注入 deps.runs(使 pollRunToResult 首轮命中 done)
|
|
14
|
+
* - deps.registry.get 返回预定义 WorkflowScript
|
|
15
|
+
* - parent runtime.worker.postMessage 捕获 workflow-result 消息
|
|
16
|
+
* - deps.onWorkflowCall 用真实的 executeNestedWorkflow 注入(模拟 Interface 层 makeDeps)
|
|
17
|
+
*/
|
|
18
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
19
|
+
|
|
20
|
+
// vi.mock 必须在 import 之前(hoisting 保证拿到 mock 版本)
|
|
21
|
+
vi.mock("../lifecycle.ts", () => ({
|
|
22
|
+
runWorkflow: vi.fn(),
|
|
23
|
+
abortRun: vi.fn(async () => {}),
|
|
24
|
+
scheduleTimeBudget: vi.fn(() => undefined),
|
|
25
|
+
}));
|
|
26
|
+
|
|
27
|
+
import { handleWorkerMessage } from "../error-recovery.ts";
|
|
28
|
+
import { executeNestedWorkflow, type LauncherDeps } from "../launcher.ts";
|
|
29
|
+
import { runWorkflow } from "../lifecycle.ts";
|
|
30
|
+
import { Budget } from "../models/budget.ts";
|
|
31
|
+
import type { RunSpec } from "../models/run-spec.ts";
|
|
32
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
33
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
34
|
+
import type { WorkflowScript } from "../models/workflow-script.ts";
|
|
35
|
+
import type { LintResult } from "../script-lint.ts";
|
|
36
|
+
|
|
37
|
+
const MOCK_RUN_ID = "wf-e2e-child";
|
|
38
|
+
|
|
39
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
/** flush microtask 队列,让 void .then().catch() 异步链路跑完。 */
|
|
42
|
+
async function flushMicrotasks(): Promise<void> {
|
|
43
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 构造 mock WorkflowScript(validate / toExecutable 可控)。 */
|
|
47
|
+
function makeScript(opts: { valid?: boolean; lintErrorMsg?: string } = {}): WorkflowScript {
|
|
48
|
+
const valid = opts.valid ?? true;
|
|
49
|
+
return {
|
|
50
|
+
name: "child-wf",
|
|
51
|
+
path: "/fake/child-wf.js",
|
|
52
|
+
meta: { name: "child-wf", description: "child workflow", phases: [] },
|
|
53
|
+
toExecutable: () => "const meta = {}; execute() {}",
|
|
54
|
+
validate: (): LintResult => ({
|
|
55
|
+
valid,
|
|
56
|
+
findings: valid
|
|
57
|
+
? []
|
|
58
|
+
: [
|
|
59
|
+
{
|
|
60
|
+
severity: "error",
|
|
61
|
+
line: 3,
|
|
62
|
+
message: opts.lintErrorMsg ?? "lint boom",
|
|
63
|
+
suggestion: "fix it",
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
}),
|
|
67
|
+
} as unknown as WorkflowScript;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 构造 mock parent WorkflowRun(status="running",有 postMessage + controller)。
|
|
72
|
+
*
|
|
73
|
+
* 同时满足 handleWorkerMessage(需 status + runtime.worker)和 executeNestedWorkflow
|
|
74
|
+
* (需 spec.scriptName/chain + runtime.controller.signal + state.budget)的要求。
|
|
75
|
+
*/
|
|
76
|
+
function makeParentRun(opts: {
|
|
77
|
+
scriptName?: string;
|
|
78
|
+
parentWorkflowChain?: readonly string[];
|
|
79
|
+
budget?: Budget;
|
|
80
|
+
postMessage?: ReturnType<typeof vi.fn>;
|
|
81
|
+
} = {}): WorkflowRun {
|
|
82
|
+
const controller = new AbortController();
|
|
83
|
+
const postMessage = opts.postMessage ?? vi.fn();
|
|
84
|
+
return {
|
|
85
|
+
spec: {
|
|
86
|
+
scriptName: opts.scriptName ?? "parent-wf",
|
|
87
|
+
parentWorkflowChain: opts.parentWorkflowChain,
|
|
88
|
+
},
|
|
89
|
+
state: {
|
|
90
|
+
status: "running",
|
|
91
|
+
budget: opts.budget ?? new Budget({ maxTokens: 10000 }),
|
|
92
|
+
},
|
|
93
|
+
runtime: { controller, worker: { postMessage } },
|
|
94
|
+
} as unknown as WorkflowRun;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 构造 mock child WorkflowRun(done 终态,pollRunToResult 首轮命中)。 */
|
|
98
|
+
function makeDoneChildRun(opts: {
|
|
99
|
+
reason?: "completed" | "failed" | "aborted";
|
|
100
|
+
scriptResult?: unknown;
|
|
101
|
+
error?: string;
|
|
102
|
+
usedTokens?: number;
|
|
103
|
+
usedCost?: number;
|
|
104
|
+
}): WorkflowRun {
|
|
105
|
+
const reason = opts.reason ?? "completed";
|
|
106
|
+
return {
|
|
107
|
+
runId: MOCK_RUN_ID,
|
|
108
|
+
spec: { scriptName: "child-wf" },
|
|
109
|
+
state: {
|
|
110
|
+
status: "done",
|
|
111
|
+
reason,
|
|
112
|
+
scriptResult: opts.scriptResult,
|
|
113
|
+
error: opts.error,
|
|
114
|
+
budget: { usedTokens: opts.usedTokens ?? 0, usedCost: opts.usedCost ?? 0 },
|
|
115
|
+
},
|
|
116
|
+
} as unknown as WorkflowRun;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 构造 LauncherDeps mock:registry + runs(Map)+ 占位 port。 */
|
|
120
|
+
function makeDeps(opts: {
|
|
121
|
+
script?: WorkflowScript;
|
|
122
|
+
childRun?: WorkflowRun;
|
|
123
|
+
registry?: { getPath: ReturnType<typeof vi.fn> };
|
|
124
|
+
} = {}): LauncherDeps {
|
|
125
|
+
const runs = new Map<string, WorkflowRun>();
|
|
126
|
+
if (opts.childRun) runs.set(MOCK_RUN_ID, opts.childRun);
|
|
127
|
+
const registry = opts.registry ?? {
|
|
128
|
+
getPath: vi.fn(async () => opts.script),
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
registry,
|
|
132
|
+
runs,
|
|
133
|
+
store: { save: vi.fn(async () => {}), loadAll: vi.fn(async () => []) },
|
|
134
|
+
workerHost: { start: vi.fn(() => ({ postMessage: vi.fn() })) },
|
|
135
|
+
runner: { run: vi.fn(async () => ({})) },
|
|
136
|
+
log: vi.fn(),
|
|
137
|
+
eventBus: { emit: vi.fn() },
|
|
138
|
+
} as unknown as LauncherDeps;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 配置 runWorkflow mock:把 childRun 注入 deps.runs 并返回 MOCK_RUN_ID。 */
|
|
142
|
+
function setupRunWorkflow(childRun: WorkflowRun): void {
|
|
143
|
+
vi.mocked(runWorkflow).mockImplementation(async (_spec, deps) => {
|
|
144
|
+
deps.runs.set(MOCK_RUN_ID, childRun);
|
|
145
|
+
return MOCK_RUN_ID;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** WorkerHandlers 占位(workflow-call 路径不触发 handler 回调)。 */
|
|
150
|
+
function makeHandlers(): WorkerHandlers {
|
|
151
|
+
return {
|
|
152
|
+
onMessage: vi.fn(async () => {}),
|
|
153
|
+
onError: vi.fn(async () => {}),
|
|
154
|
+
onExit: vi.fn(async () => {}),
|
|
155
|
+
} as unknown as WorkerHandlers;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface PostedMsg {
|
|
159
|
+
type: string;
|
|
160
|
+
callId: number;
|
|
161
|
+
result: { content: string; parsedOutput?: unknown; error?: string };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 从 postMessage mock 取第 0 次调用的第 0 参,类型安全窄化。 */
|
|
165
|
+
function firstPosted(postMessage: ReturnType<typeof vi.fn>): PostedMsg {
|
|
166
|
+
return postMessage.mock.calls[0]![0] as PostedMsg;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 把 executeNestedWorkflow 绑定为 deps.onWorkflowCall(模拟 Interface 层 makeDeps)。
|
|
171
|
+
*
|
|
172
|
+
* 闭包引用 deps——与 index.ts makeDeps 的模式一致。
|
|
173
|
+
*/
|
|
174
|
+
function wireOnWorkflowCall(deps: LauncherDeps): void {
|
|
175
|
+
(deps as LifecycleDeps).onWorkflowCall = (name, args, parentRun) =>
|
|
176
|
+
executeNestedWorkflow(name, args, parentRun, deps);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
beforeEach(() => {
|
|
180
|
+
vi.clearAllMocks();
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// ── tests ────────────────────────────────────────────────────
|
|
184
|
+
|
|
185
|
+
describe("workflow() nesting end-to-end", () => {
|
|
186
|
+
it("end-to-end: workflow-call → executeNestedWorkflow → workflow-result posted back", async () => {
|
|
187
|
+
const postMessage = vi.fn();
|
|
188
|
+
const parent = makeParentRun({ postMessage });
|
|
189
|
+
const childRun = makeDoneChildRun({
|
|
190
|
+
reason: "completed",
|
|
191
|
+
scriptResult: { data: "test" },
|
|
192
|
+
});
|
|
193
|
+
const deps = makeDeps({ script: makeScript(), childRun });
|
|
194
|
+
setupRunWorkflow(childRun);
|
|
195
|
+
wireOnWorkflowCall(deps);
|
|
196
|
+
|
|
197
|
+
await handleWorkerMessage(
|
|
198
|
+
parent,
|
|
199
|
+
{ type: "workflow-call", callId: 1, name: "child", args: {} },
|
|
200
|
+
deps,
|
|
201
|
+
makeHandlers(),
|
|
202
|
+
);
|
|
203
|
+
await flushMicrotasks();
|
|
204
|
+
|
|
205
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
206
|
+
const sent = firstPosted(postMessage);
|
|
207
|
+
expect(sent.type).toBe("workflow-result");
|
|
208
|
+
expect(sent.callId).toBe(1);
|
|
209
|
+
expect(sent.result.content).toBe(JSON.stringify({ data: "test" }));
|
|
210
|
+
expect(sent.result.parsedOutput).toEqual({ data: "test" });
|
|
211
|
+
expect(sent.result.error).toBeUndefined();
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("end-to-end: circular call returns error result", async () => {
|
|
215
|
+
const postMessage = vi.fn();
|
|
216
|
+
// parent chain ["a"], scriptName "b" → target "a" 触发 a→b→a 循环
|
|
217
|
+
const parent = makeParentRun({
|
|
218
|
+
scriptName: "b",
|
|
219
|
+
parentWorkflowChain: ["a"],
|
|
220
|
+
postMessage,
|
|
221
|
+
});
|
|
222
|
+
const deps = makeDeps({ script: makeScript() });
|
|
223
|
+
wireOnWorkflowCall(deps);
|
|
224
|
+
|
|
225
|
+
await handleWorkerMessage(
|
|
226
|
+
parent,
|
|
227
|
+
{ type: "workflow-call", callId: 2, name: "a", args: {} },
|
|
228
|
+
deps,
|
|
229
|
+
makeHandlers(),
|
|
230
|
+
);
|
|
231
|
+
await flushMicrotasks();
|
|
232
|
+
|
|
233
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
234
|
+
const sent = firstPosted(postMessage);
|
|
235
|
+
expect(sent.result.error).toContain("Circular workflow call detected");
|
|
236
|
+
expect(sent.result.content).toBe("");
|
|
237
|
+
expect(runWorkflow).not.toHaveBeenCalled();
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("end-to-end: workflow not found returns error result", async () => {
|
|
241
|
+
const postMessage = vi.fn();
|
|
242
|
+
const parent = makeParentRun({ postMessage });
|
|
243
|
+
const deps = makeDeps({ script: undefined });
|
|
244
|
+
wireOnWorkflowCall(deps);
|
|
245
|
+
|
|
246
|
+
await handleWorkerMessage(
|
|
247
|
+
parent,
|
|
248
|
+
{ type: "workflow-call", callId: 3, name: "missing", args: {} },
|
|
249
|
+
deps,
|
|
250
|
+
makeHandlers(),
|
|
251
|
+
);
|
|
252
|
+
await flushMicrotasks();
|
|
253
|
+
|
|
254
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
255
|
+
const sent = firstPosted(postMessage);
|
|
256
|
+
expect(sent.result.error).toContain("not found");
|
|
257
|
+
expect(sent.result.content).toBe("");
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("end-to-end: child workflow failure propagates error", async () => {
|
|
261
|
+
const postMessage = vi.fn();
|
|
262
|
+
const parent = makeParentRun({ postMessage });
|
|
263
|
+
const childRun = makeDoneChildRun({
|
|
264
|
+
reason: "failed",
|
|
265
|
+
error: "agent crashed",
|
|
266
|
+
});
|
|
267
|
+
const deps = makeDeps({ script: makeScript(), childRun });
|
|
268
|
+
setupRunWorkflow(childRun);
|
|
269
|
+
wireOnWorkflowCall(deps);
|
|
270
|
+
|
|
271
|
+
await handleWorkerMessage(
|
|
272
|
+
parent,
|
|
273
|
+
{ type: "workflow-call", callId: 4, name: "child", args: {} },
|
|
274
|
+
deps,
|
|
275
|
+
makeHandlers(),
|
|
276
|
+
);
|
|
277
|
+
await flushMicrotasks();
|
|
278
|
+
|
|
279
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
280
|
+
const sent = firstPosted(postMessage);
|
|
281
|
+
expect(sent.result.error).toBe("agent crashed");
|
|
282
|
+
expect(sent.result.content).toBe("");
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("end-to-end: child shares parent budget reference (no sync-back)", async () => {
|
|
286
|
+
const postMessage = vi.fn();
|
|
287
|
+
const parentBudget = new Budget({ maxTokens: 10000 });
|
|
288
|
+
parentBudget.usedTokens = 100;
|
|
289
|
+
const parent = makeParentRun({ budget: parentBudget, postMessage });
|
|
290
|
+
const childRun = makeDoneChildRun({
|
|
291
|
+
reason: "completed",
|
|
292
|
+
scriptResult: "ok",
|
|
293
|
+
});
|
|
294
|
+
const deps = makeDeps({ script: makeScript(), childRun });
|
|
295
|
+
|
|
296
|
+
// 捕获传给 runWorkflow 的 spec——验证 budgetRef 共享父 Budget 引用
|
|
297
|
+
let capturedSpec: RunSpec | undefined;
|
|
298
|
+
vi.mocked(runWorkflow).mockImplementation(async (spec, d) => {
|
|
299
|
+
capturedSpec = spec;
|
|
300
|
+
d.runs.set(MOCK_RUN_ID, childRun);
|
|
301
|
+
return MOCK_RUN_ID;
|
|
302
|
+
});
|
|
303
|
+
wireOnWorkflowCall(deps);
|
|
304
|
+
|
|
305
|
+
await handleWorkerMessage(
|
|
306
|
+
parent,
|
|
307
|
+
{ type: "workflow-call", callId: 5, name: "child", args: {} },
|
|
308
|
+
deps,
|
|
309
|
+
makeHandlers(),
|
|
310
|
+
);
|
|
311
|
+
await flushMicrotasks();
|
|
312
|
+
|
|
313
|
+
// 子 run 直接复用父 Budget 引用(budgetRef),无需 sync-back
|
|
314
|
+
expect(capturedSpec?.budgetRef).toBe(parentBudget);
|
|
315
|
+
expect(parent.state.budget.usedTokens).toBe(100);
|
|
316
|
+
});
|
|
317
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WorkflowScript.validate lint memo(IF9/#15,TC9/DM2)— 引用相等键缓存测试。
|
|
3
|
+
*
|
|
4
|
+
* vi.mock script-lint 模块统计 lintScript 调用次数(design IF9 测试面):
|
|
5
|
+
* - 同 path + sourceCode 相等(含等值异字面量)→ 二次 validate 只 1 次 lint 调用
|
|
6
|
+
* - 【设计修正】design 原文「异引用等值 miss」在 JS 不可构造:字符串 === 是值相等
|
|
7
|
+
* (实测等值异字面量命中)。lintScript 是纯函数,值相等 ⟹ 结果相同,值键 memo
|
|
8
|
+
* 语义严格正确且是引用键意图的超集(registry 等值重建实例同样命中)。
|
|
9
|
+
* - 同 path 新内容(值不等)→ 重 lint 并更新条目
|
|
10
|
+
* - clearLintMemo → 重 lint(config-loader.invalidateCache 挂载点)
|
|
11
|
+
*/
|
|
12
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
13
|
+
|
|
14
|
+
const lintCalls = vi.hoisted(() => ({ count: 0 }));
|
|
15
|
+
|
|
16
|
+
vi.mock("../script-lint.ts", async (importOriginal) => {
|
|
17
|
+
const actual = await importOriginal<typeof import("../script-lint.ts")>();
|
|
18
|
+
const realLintScript = actual.lintScript;
|
|
19
|
+
const countingLintScript = ((source: string) => {
|
|
20
|
+
lintCalls.count++;
|
|
21
|
+
return realLintScript(source);
|
|
22
|
+
}) as typeof actual.lintScript;
|
|
23
|
+
return { ...actual, lintScript: countingLintScript };
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
import { WorkflowScript, clearLintMemo, type WorkflowMeta } from "../models/workflow-script.ts";
|
|
27
|
+
|
|
28
|
+
const meta: WorkflowMeta = {
|
|
29
|
+
kind: "workflow",
|
|
30
|
+
name: "w",
|
|
31
|
+
description: "",
|
|
32
|
+
phases: [],
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
function makeScript(path: string, sourceCode: string): WorkflowScript {
|
|
36
|
+
return new WorkflowScript({
|
|
37
|
+
name: "w",
|
|
38
|
+
source: "saved",
|
|
39
|
+
path,
|
|
40
|
+
sourceCode,
|
|
41
|
+
meta,
|
|
42
|
+
available: true,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const VALID = '/* @pi-meta name: w */\nagent({ prompt: "x" });\n';
|
|
47
|
+
|
|
48
|
+
beforeEach(() => {
|
|
49
|
+
clearLintMemo();
|
|
50
|
+
lintCalls.count = 0;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe("WorkflowScript.validate — lintMemo(IF9)", () => {
|
|
54
|
+
it("同 sourceCode 引用:二次 validate 只 1 次 lint 调用", () => {
|
|
55
|
+
const src = VALID;
|
|
56
|
+
const a = makeScript("/ws/.pi/workflows/w.js", src);
|
|
57
|
+
const b = makeScript("/ws/.pi/workflows/w.js", src); // registry 重建实例场景
|
|
58
|
+
|
|
59
|
+
const ra = a.validate();
|
|
60
|
+
const rb = b.validate();
|
|
61
|
+
|
|
62
|
+
expect(lintCalls.count).toBe(1);
|
|
63
|
+
expect(rb).toEqual(ra); // 缓存返回同一 lint 结果
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("等值异字面量同样命中(JS === 值相等;lintScript 纯函数 ⟹ 值键 memo 正确)", () => {
|
|
67
|
+
const a = makeScript("/ws/.pi/workflows/w.js", VALID);
|
|
68
|
+
const b = makeScript("/ws/.pi/workflows/w.js", `/* @pi-meta name: w */\nagent({ prompt: "x" });\n`);
|
|
69
|
+
|
|
70
|
+
a.validate();
|
|
71
|
+
b.validate();
|
|
72
|
+
|
|
73
|
+
// 设计原文预期「异引用 miss → 2 次」,但字符串 === 是值相等,等值必命中;
|
|
74
|
+
// lintScript(source) 纯函数,同值同结果,缓存正确性不受影响(实测锚定)。
|
|
75
|
+
expect(lintCalls.count).toBe(1);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("同 path 新内容(值不等):重 lint 并更新条目", () => {
|
|
79
|
+
const path = "/ws/.pi/workflows/w.js";
|
|
80
|
+
const old = makeScript(path, VALID);
|
|
81
|
+
old.validate();
|
|
82
|
+
expect(lintCalls.count).toBe(1);
|
|
83
|
+
|
|
84
|
+
const edited = makeScript(path, '/* @pi-meta name: w */\nagent({ prompt: "y", outputSchema: {} });\n');
|
|
85
|
+
edited.validate();
|
|
86
|
+
expect(lintCalls.count).toBe(2); // 新引用 → miss → 重 lint
|
|
87
|
+
|
|
88
|
+
// 新条目已覆写:再以 edited 同引用 validate 命中缓存
|
|
89
|
+
const replay = makeScript(path, edited.sourceCode);
|
|
90
|
+
replay.validate();
|
|
91
|
+
expect(lintCalls.count).toBe(2);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("clearLintMemo 后重 lint(invalidateCache 挂载点)", () => {
|
|
95
|
+
const a = makeScript("/ws/.pi/workflows/w.js", VALID);
|
|
96
|
+
a.validate();
|
|
97
|
+
expect(lintCalls.count).toBe(1);
|
|
98
|
+
|
|
99
|
+
clearLintMemo();
|
|
100
|
+
a.validate();
|
|
101
|
+
expect(lintCalls.count).toBe(2);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("不同 path 互不共享条目", () => {
|
|
105
|
+
const src = VALID;
|
|
106
|
+
makeScript("/ws/.pi/workflows/a.js", src).validate();
|
|
107
|
+
makeScript("/ws/.pi/workflows/b.js", src).validate();
|
|
108
|
+
expect(lintCalls.count).toBe(2);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent options resolver — resolves skill / schema to append-system-prompt
|
|
3
|
+
* content + env vars on every dispatch (BL-1).
|
|
4
|
+
*
|
|
5
|
+
* BL-1:解析 workflow 脚本里 `agent({skill,schema})` 的 inline override,
|
|
6
|
+
* 否则 pi 子进程只收到原始 prompt,没有 --append-system-prompt /
|
|
7
|
+
* --skill / PI_WORKFLOW_SCHEMA。
|
|
8
|
+
*
|
|
9
|
+
* 职责范围(M2 修正):仅处理 schema SO 指令(内容直传 appendSystemPrompt)+ skill。
|
|
10
|
+
* agent ref 处理(systemPrompt/model/thinkingLevel)已移交 resolveIdentity(execution 层,
|
|
11
|
+
* 经 getAgentConfig + resolveModel 完整覆盖),消除双重注入与 model 层级混乱。
|
|
12
|
+
*
|
|
13
|
+
* 调用方:engine/error-recovery.ts dispatchAgentCall(每次 agent-call 消息)。
|
|
14
|
+
* - skill → resolveSkillPath → skillPath(--skill)
|
|
15
|
+
* - schema → 结构化输出指令内容直传 appendSystemPrompt(--append-system-prompt)+ schemaEnv(PI_WORKFLOW_SCHEMA)
|
|
16
|
+
*
|
|
17
|
+
* M2 bug 修正:旧实现把 schema 指令写成临时文件、push 文件路径(而非内容)给下游,
|
|
18
|
+
* 下游 mapper/session-runner 把路径当文本拼进最终 append 文件,导致 schema 指令从未
|
|
19
|
+
* 进入子进程。改为指令内容直传(不写盘、无临时文件)。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { AgentCallOpts } from "./models/types.ts";
|
|
23
|
+
import { resolveSkillPath } from "./skill-discovery.ts";
|
|
24
|
+
import { stringifySchemaCached } from "../shared/schema-jsonify.ts";
|
|
25
|
+
|
|
26
|
+
export interface ResolveResult {
|
|
27
|
+
opts: AgentCallOpts;
|
|
28
|
+
error?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ── 根类型判定(与 structured-output 同源,本地副本) ──────────────
|
|
32
|
+
|
|
33
|
+
/** plain object 判定(isPlainObject,与 @zhushanwen/pi-structured-output schema-guards.ts 同语义)。 */
|
|
34
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
35
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* [U3 本地副本·同源锚定] 判定权威 schema 的根数据形态是否为 object。
|
|
40
|
+
*
|
|
41
|
+
* 与 @zhushanwen/pi-structured-output `src/execute.ts` 的 `isObjectRootSchema`
|
|
42
|
+
* 逐语义一致(该函数是 structured-output 工具 parameters {value} 包装/解包的唯一
|
|
43
|
+
* 判定源)。两包是独立 npm 包不能直接 import——optional peer 依赖在独立安装场景
|
|
44
|
+
* (pi 用户单独装本包)不保证存在,顶层值 import 会让整个 extension 加载崩溃;
|
|
45
|
+
* 且 builtin esbuild bundle 会把 import 的包内联成双实例(先例:session-runner.ts
|
|
46
|
+
* 的 PI_WORKFLOW_SCHEMA env 契约注释)。故本地复制,任一端改动判定逻辑必须同步
|
|
47
|
+
* 另一端(两端 docstring 互相锚定)。
|
|
48
|
+
*
|
|
49
|
+
* draft-07 语义:无 type 时类型关键字按值形态适用——properties/required 等
|
|
50
|
+
* object 特有关键字的存在意味着作者在描述 object 输出,算 object 根;组合根
|
|
51
|
+
* (anyOf/oneOf/allOf/$ref/enum)可能接受非 object 值,保真起见一律按非 object
|
|
52
|
+
* ({value} 包装可容纳任意成员类型)。
|
|
53
|
+
*/
|
|
54
|
+
function isObjectRootSchema(schema: unknown): schema is Record<string, unknown> {
|
|
55
|
+
if (!isPlainObject(schema)) return false;
|
|
56
|
+
if (schema.type === "object") return true;
|
|
57
|
+
if (Array.isArray(schema.type) && schema.type.includes("object")) return true;
|
|
58
|
+
const OBJECT_ONLY_KEYS = [
|
|
59
|
+
"properties",
|
|
60
|
+
"required",
|
|
61
|
+
"patternProperties",
|
|
62
|
+
"additionalProperties",
|
|
63
|
+
"minProperties",
|
|
64
|
+
"maxProperties",
|
|
65
|
+
"dependencies",
|
|
66
|
+
"dependentRequired",
|
|
67
|
+
"propertyNames",
|
|
68
|
+
];
|
|
69
|
+
return OBJECT_ONLY_KEYS.some((k) => k in schema);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 构造 schema structured-output 指令——resolver 单点注入的唯一文案源。
|
|
74
|
+
*
|
|
75
|
+
* [审查项#2] 消费链:resolveAgentOpts → appendSystemPrompt(ASP 稳定前缀区)。
|
|
76
|
+
* 此前 session-runner 有一份措辞相近的同名函数并把指令拼进 task 末尾,形成
|
|
77
|
+
* ASP + task 双重静态注入;task 后缀已删(task 每 agent 变化不可缓存,工具
|
|
78
|
+
* parameters 是 pi 必然注入的权威展示——注册工具 schema 随每次请求下发进
|
|
79
|
+
* provider 请求体,机制登记 PS-21:pi-ai dist/api/anthropic-messages.js
|
|
80
|
+
* convertTools :1000/:1008 → :1017 input_schema、openai-completions.js :1099
|
|
81
|
+
* parameters——schema 全文不必在 task 重复,文本重复浪费 ~730 tokens/子进程)。
|
|
82
|
+
*
|
|
83
|
+
* [审查项#4] AP 告知:注入侧校验用 additionalProperties:false 收窄后的
|
|
84
|
+
* parameters,模型自带 schema 外字段会被拒——不前置告知,拒绝显得凭空。
|
|
85
|
+
*
|
|
86
|
+
* JSON 序列化用 compact(stringifySchemaCached),与 schemaEnv 复用同串(IF7 #13)。
|
|
87
|
+
*/
|
|
88
|
+
export function formatSchemaInstruction(schema: Record<string, unknown>): string {
|
|
89
|
+
const schemaJson = stringifySchemaCached(schema, "compact");
|
|
90
|
+
// [U3] 根类型条件化:判定与 structured-output 的工具 parameters {value} 包装/解包
|
|
91
|
+
// 同源(上方 isObjectRootSchema 本地副本)。object 根 arguments 即 data;非 object
|
|
92
|
+
// 根参数层实为 {value} 包装——ASP 文案必须与工具 description 同语汇告知包装契约
|
|
93
|
+
// ({value: <data>} + value. 错误路径前缀),否则模型直传裸值必首调失败。
|
|
94
|
+
const isObjectRoot = isObjectRootSchema(schema);
|
|
95
|
+
const argsContractLine = isObjectRoot
|
|
96
|
+
? "Your call arguments ARE the result data itself — the tool's parameter schema IS the required shape of your result."
|
|
97
|
+
: "The tool's single argument must be an object `{value: <data>}` — put the result itself in `value`, and it must conform to the schema below. " +
|
|
98
|
+
"Validation errors may reference paths starting with `value.` (e.g. `value.0`, `value.name`): " +
|
|
99
|
+
"that prefix addresses the wrapper, not your data.";
|
|
100
|
+
const rulesCallLine = isObjectRoot
|
|
101
|
+
? "- Call the structured-output tool with your result data as its arguments. The system validates them against the schema above automatically."
|
|
102
|
+
: "- Call the structured-output tool with `{value: <your result data>}`. The system validates the `value` field against the schema above automatically.";
|
|
103
|
+
// [AP 告知条件化] 根级 additionalProperties 未声明时 D4 注入 false(见
|
|
104
|
+
// structured-output tool-definition)——额外字段恒拒绝,强承诺成立;作者显式声明
|
|
105
|
+
// true / 子 schema 时 injection 侧尊重不动,额外字段按作者声明放行,无条件
|
|
106
|
+
// 「一律拒绝」文案与参数层行为不符(保守方向误导:模型不敢传合法字段)。
|
|
107
|
+
const apLine = schema.additionalProperties === undefined
|
|
108
|
+
? "- Fields not defined in this schema are rejected — do not add extra fields."
|
|
109
|
+
: "- Extra fields follow this schema's own additionalProperties declaration.";
|
|
110
|
+
return [
|
|
111
|
+
"## MANDATORY: Structured Output Requirement",
|
|
112
|
+
"",
|
|
113
|
+
"This task requires structured output.",
|
|
114
|
+
"Your FINAL action must be calling the `structured-output` tool.",
|
|
115
|
+
"",
|
|
116
|
+
argsContractLine,
|
|
117
|
+
`Your result must conform to this schema:`,
|
|
118
|
+
"```json",
|
|
119
|
+
schemaJson,
|
|
120
|
+
"```",
|
|
121
|
+
"",
|
|
122
|
+
"Rules:",
|
|
123
|
+
rulesCallLine,
|
|
124
|
+
"- Do NOT output JSON in your text response — use the structured-output tool.",
|
|
125
|
+
"- Do NOT skip this step. The structured-output call IS your result.",
|
|
126
|
+
"- Complete all other work FIRST, then call structured-output as the last action.",
|
|
127
|
+
apLine,
|
|
128
|
+
].join("\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Resolve skill and schema into appendSystemPrompt (content array) + skillPath + schemaEnv.
|
|
133
|
+
*
|
|
134
|
+
* - Skill name -> resolved SKILL.md dir path via --skill
|
|
135
|
+
* - Schema JSON -> structured-output instruction string pushed into appendSystemPrompt
|
|
136
|
+
* (content, not file path) + PI_WORKFLOW_SCHEMA env
|
|
137
|
+
*
|
|
138
|
+
* Agent ref is intentionally NOT handled here — resolveIdentity (execution layer)
|
|
139
|
+
* covers it via getAgentConfig + resolveModel. Handling agent here would cause
|
|
140
|
+
* double-injection (agentConfig.systemPrompt at session-runner + appendSystemPrompt)
|
|
141
|
+
* and model-tier confusion.
|
|
142
|
+
*
|
|
143
|
+
* Returns the enriched opts.
|
|
144
|
+
*/
|
|
145
|
+
export function resolveAgentOpts(opts: AgentCallOpts): ResolveResult {
|
|
146
|
+
const appendSystemPrompt: string[] = [];
|
|
147
|
+
|
|
148
|
+
// Resolve skill name to SKILL.md path
|
|
149
|
+
if (opts.skill) {
|
|
150
|
+
const skillPath = resolveSkillPath(opts.skill);
|
|
151
|
+
if (!skillPath) {
|
|
152
|
+
return { opts, error: `Skill not found: ${opts.skill}. Searched .agents/skills/ and ~/.pi/agent/skills/` };
|
|
153
|
+
}
|
|
154
|
+
opts = { ...opts, skillPath };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Inject schema as structured-output instruction into appendSystemPrompt (content,
|
|
158
|
+
// not temp file) and set environment variable for conditional tool + hook activation.
|
|
159
|
+
// M2 fix: previously wrote the instruction to a temp file and pushed the FILE PATH,
|
|
160
|
+
// which got concatenated into the final append file as path garbage — the SO instruction
|
|
161
|
+
// never reached the subprocess. Now the instruction content is pushed directly.
|
|
162
|
+
if (opts.schema) {
|
|
163
|
+
// IF7(#13):formatSchemaInstruction 与 schemaEnv 对同一 schema 对象引用共享
|
|
164
|
+
// WeakMap 缓存条目(compact stringify 整个 dispatch 只发生一次)
|
|
165
|
+
appendSystemPrompt.push(formatSchemaInstruction(opts.schema));
|
|
166
|
+
|
|
167
|
+
// Set env var for structured-output extension to activate tool + hook
|
|
168
|
+
opts = { ...opts, schemaEnv: stringifySchemaCached(opts.schema, "compact") };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
opts: { ...opts, ...(appendSystemPrompt.length > 0 ? { appendSystemPrompt } : {}) },
|
|
173
|
+
};
|
|
174
|
+
}
|