create-windy 0.6.14 → 0.6.16

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.
Files changed (162) hide show
  1. package/dist/cli.js +1008 -61
  2. package/package.json +1 -1
  3. package/template/.agents/skills/windy-business-module/SKILL.md +58 -8
  4. package/template/.windy-template.json +2 -2
  5. package/template/apps/server/src/agent/client-session/attempt-authority.test.ts +162 -0
  6. package/template/apps/server/src/agent/client-session/attempt-authority.ts +191 -0
  7. package/template/apps/server/src/agent/client-session/bootstrap.ts +27 -11
  8. package/template/apps/server/src/agent/client-session/completion.ts +75 -24
  9. package/template/apps/server/src/agent/client-session/contracts.ts +23 -0
  10. package/template/apps/server/src/agent/client-session/creation.ts +103 -0
  11. package/template/apps/server/src/agent/client-session/digest.ts +11 -1
  12. package/template/apps/server/src/agent/client-session/drizzle-records.ts +150 -0
  13. package/template/apps/server/src/agent/client-session/drizzle-repository.integration.test.ts +30 -3
  14. package/template/apps/server/src/agent/client-session/drizzle-repository.ts +23 -132
  15. package/template/apps/server/src/agent/client-session/finalization.ts +99 -0
  16. package/template/apps/server/src/agent/client-session/host-auth.ts +22 -10
  17. package/template/apps/server/src/agent/client-session/host-revocation-composition.test.ts +77 -0
  18. package/template/apps/server/src/agent/client-session/host-revocation-composition.ts +28 -0
  19. package/template/apps/server/src/agent/client-session/launch-authority.contract.test.ts +21 -0
  20. package/template/apps/server/src/agent/client-session/manifest-admission.ts +11 -0
  21. package/template/apps/server/src/agent/client-session/service.test-support.ts +22 -0
  22. package/template/apps/server/src/agent/client-session/service.ts +104 -134
  23. package/template/apps/server/src/agent/client-session/terminal-digest.test.ts +23 -0
  24. package/template/apps/server/src/agent/client-workflow-artifact/active-blob-references.ts +8 -0
  25. package/template/apps/server/src/agent/client-workflow-artifact/artifact-builder.ts +60 -0
  26. package/template/apps/server/src/agent/client-workflow-artifact/authority-current.ts +59 -0
  27. package/template/apps/server/src/agent/client-workflow-artifact/binding-registry.test.ts +189 -0
  28. package/template/apps/server/src/agent/client-workflow-artifact/binding-registry.ts +153 -0
  29. package/template/apps/server/src/agent/client-workflow-artifact/bootstrap.ts +77 -0
  30. package/template/apps/server/src/agent/client-workflow-artifact/cancellation.ts +47 -0
  31. package/template/apps/server/src/agent/client-workflow-artifact/completed-recovery.ts +31 -0
  32. package/template/apps/server/src/agent/client-workflow-artifact/contracts.ts +104 -0
  33. package/template/apps/server/src/agent/client-workflow-artifact/drizzle-locks.ts +30 -0
  34. package/template/apps/server/src/agent/client-workflow-artifact/drizzle-mapper.ts +138 -0
  35. package/template/apps/server/src/agent/client-workflow-artifact/drizzle-repository.ts +346 -0
  36. package/template/apps/server/src/agent/client-workflow-artifact/error.ts +21 -0
  37. package/template/apps/server/src/agent/client-workflow-artifact/handler.ts +167 -0
  38. package/template/apps/server/src/agent/client-workflow-artifact/host-revocation.ts +29 -0
  39. package/template/apps/server/src/agent/client-workflow-artifact/in-memory-repository.ts +232 -0
  40. package/template/apps/server/src/agent/client-workflow-artifact/job-port.ts +101 -0
  41. package/template/apps/server/src/agent/client-workflow-artifact/presentation.ts +41 -0
  42. package/template/apps/server/src/agent/client-workflow-artifact/recovery.contract.test.ts +253 -0
  43. package/template/apps/server/src/agent/client-workflow-artifact/release-binding.ts +85 -0
  44. package/template/apps/server/src/agent/client-workflow-artifact/repository.test.ts +204 -0
  45. package/template/apps/server/src/agent/client-workflow-artifact/repository.ts +97 -0
  46. package/template/apps/server/src/agent/client-workflow-artifact/routes-handler.contract.test.ts +201 -0
  47. package/template/apps/server/src/agent/client-workflow-artifact/routes.ts +161 -0
  48. package/template/apps/server/src/agent/client-workflow-artifact/runtime-composition.ts +101 -0
  49. package/template/apps/server/src/agent/client-workflow-artifact/scope-authority.ts +39 -0
  50. package/template/apps/server/src/agent/client-workflow-artifact/service-authorization.ts +117 -0
  51. package/template/apps/server/src/agent/client-workflow-artifact/service-support.ts +28 -0
  52. package/template/apps/server/src/agent/client-workflow-artifact/service.contract.test.ts +345 -0
  53. package/template/apps/server/src/agent/client-workflow-artifact/service.ts +350 -0
  54. package/template/apps/server/src/agent/client-workflow-artifact/session-boundary.ts +39 -0
  55. package/template/apps/server/src/agent/client-workflow-artifact/source-access.contract.test.ts +98 -0
  56. package/template/apps/server/src/agent/client-workflow-artifact/source-access.ts +80 -0
  57. package/template/apps/server/src/agent/client-workflow-artifact/takeover.ts +122 -0
  58. package/template/apps/server/src/agent/client-workflow-artifact/task-authority.contract.test.ts +97 -0
  59. package/template/apps/server/src/agent/client-workflow-artifact/task-authority.ts +147 -0
  60. package/template/apps/server/src/agent/client-workflow-artifact/terminal-authority.contract.test.ts +100 -0
  61. package/template/apps/server/src/agent/client-workflow-artifact/terminal-replay.ts +31 -0
  62. package/template/apps/server/src/agent/client-workflow-artifact/terminal-seal.ts +211 -0
  63. package/template/apps/server/src/agent/client-workflow-artifact/workflow-artifact.test-support.ts +173 -0
  64. package/template/apps/server/src/agent/client-workflow-artifact/workflow-loader.contract.test.ts +254 -0
  65. package/template/apps/server/src/agent/client-workflow-artifact/workflow-loader.ts +285 -0
  66. package/template/apps/server/src/agent/run-facade.test-support.ts +17 -4
  67. package/template/apps/server/src/agent/run-facade.test.ts +16 -0
  68. package/template/apps/server/src/agent/run-session-authorization.ts +12 -10
  69. package/template/apps/server/src/agent/runtime-bootstrap-input.ts +5 -1
  70. package/template/apps/server/src/agent/runtime-bootstrap.ts +33 -33
  71. package/template/apps/server/src/agent/runtime-public-ports.ts +40 -0
  72. package/template/apps/server/src/agent/session-invalidation/contracts.ts +25 -26
  73. package/template/apps/server/src/agent/session-projection-access.ts +31 -19
  74. package/template/apps/server/src/agent/unavailable-routes.ts +21 -0
  75. package/template/apps/server/src/agent/workflow-runtime-bootstrap.ts +2 -0
  76. package/template/apps/server/src/agent-workflow/artifact-source-authorization.ts +12 -6
  77. package/template/apps/server/src/agent-workflow/command-facade.ts +70 -11
  78. package/template/apps/server/src/agent-workflow/drizzle-artifact-port.ts +9 -9
  79. package/template/apps/server/src/agent-workflow/drizzle-delegation-completion.ts +1 -1
  80. package/template/apps/server/src/agent-workflow/platform-node-adapters.ts +14 -6
  81. package/template/apps/server/src/agent-workflow/project-launch-authority.contract.test.ts +53 -0
  82. package/template/apps/server/src/agent-workflow/project-launch-authority.ts +92 -0
  83. package/template/apps/server/src/agent-workflow/runtime-composition.ts +30 -14
  84. package/template/apps/server/src/app/agent-runtime-composition.ts +6 -1
  85. package/template/apps/server/src/app/client-agent-workflow-artifact-binding.ts +14 -0
  86. package/template/apps/server/src/application-services.ts +6 -0
  87. package/template/apps/server/src/data-access/scope-containment.test.ts +31 -0
  88. package/template/apps/server/src/data-access/scope-containment.ts +48 -0
  89. package/template/apps/server/src/jobs/artifact-publication.test.ts +192 -0
  90. package/template/apps/server/src/jobs/artifact-publication.ts +56 -0
  91. package/template/apps/server/src/jobs/artifact-publisher.ts +101 -0
  92. package/template/apps/server/src/jobs/drizzle-artifact.ts +73 -1
  93. package/template/apps/server/src/jobs/drizzle-execution-repository.ts +14 -1
  94. package/template/apps/server/src/jobs/drizzle-execution.integration.test.ts +65 -0
  95. package/template/apps/server/src/jobs/drizzle-repository.integration.test.ts +1 -0
  96. package/template/apps/server/src/jobs/execution-repository.ts +28 -0
  97. package/template/apps/server/src/jobs/execution.test.ts +3 -1
  98. package/template/apps/server/src/jobs/in-memory-execution.ts +16 -0
  99. package/template/apps/server/src/jobs/in-memory-lease.ts +45 -1
  100. package/template/apps/server/src/jobs/legacy-adapter.integration.test.ts +2 -0
  101. package/template/apps/server/src/jobs/postgres-cleanup-contract.test.ts +58 -0
  102. package/template/apps/server/src/jobs/worker.ts +8 -14
  103. package/template/apps/server/src/module-host/background-ai-unavailable.ts +18 -0
  104. package/template/apps/server/src/module-host/durable-context.ts +19 -22
  105. package/template/apps/server/src/module-host/implementation-completeness.test.ts +80 -1
  106. package/template/apps/server/src/module-host/implementation-completeness.ts +28 -1
  107. package/template/apps/server/src/module-host/request-context.ts +32 -8
  108. package/template/apps/server/src/module-host/storage-port.ts +3 -0
  109. package/template/apps/server/src/module-host/workflow-input-artifact-port.test.ts +104 -0
  110. package/template/apps/server/src/module-host/workflow-input-artifact-port.ts +229 -0
  111. package/template/apps/server/src/module-host/workflow-input-materialization.test.ts +163 -0
  112. package/template/apps/server/src/module-host/workflow-input-materialization.ts +161 -0
  113. package/template/apps/server/src/workflow/drizzle-repository.integration.test.ts +1 -0
  114. package/template/apps/web/src/pages/system/components/ai-runtime/AiRuntimeFilters.vue +2 -1
  115. package/template/apps/web/src/pages/system/components/ai-runtime/AiRuntimeFilters.webtest.ts +16 -0
  116. package/template/docs/architecture/agent-workflow.md +13 -2
  117. package/template/docs/architecture/durable-jobs.md +7 -0
  118. package/template/docs/operations/agent-session-memory.md +2 -1
  119. package/template/docs/operations/agent-session-troubleshooting.md +87 -2
  120. package/template/docs/operations/agent-workflow-recovery.md +25 -14
  121. package/template/docs/platform/client-agent-session.md +148 -2
  122. package/template/packages/ai-client/package.json +2 -1
  123. package/template/packages/ai-client/src/client-agent/index.ts +1 -0
  124. package/template/packages/ai-client/src/client-agent/workflow-artifact/contracts.ts +85 -0
  125. package/template/packages/ai-client/src/client-agent/workflow-artifact/http.test.ts +49 -0
  126. package/template/packages/ai-client/src/client-agent/workflow-artifact/http.ts +82 -0
  127. package/template/packages/ai-client/src/client-agent/workflow-artifact/index.ts +3 -0
  128. package/template/packages/ai-client/src/client-agent/workflow-artifact/validation.test.ts +154 -0
  129. package/template/packages/ai-client/src/client-agent/workflow-artifact/validation.ts +332 -0
  130. package/template/packages/database/drizzle/0062_client_agent_workflow_artifact.sql +63 -0
  131. package/template/packages/database/drizzle/meta/0062_snapshot.json +14839 -0
  132. package/template/packages/database/drizzle/meta/_journal.json +7 -0
  133. package/template/packages/database/package.json +1 -1
  134. package/template/packages/database/src/agent-runtime-schema.test.ts +177 -0
  135. package/template/packages/database/src/schema/client-agent-workflow-artifact.ts +158 -0
  136. package/template/packages/database/src/schema/index.ts +1 -0
  137. package/template/packages/jobs/package.json +1 -1
  138. package/template/packages/jobs/src/handlers.test.ts +10 -0
  139. package/template/packages/jobs/src/handlers.ts +28 -11
  140. package/template/packages/modules/package.json +1 -1
  141. package/template/packages/modules/src/ai-client-execution-policy.ts +6 -0
  142. package/template/packages/modules/src/manifest.ts +2 -0
  143. package/template/packages/modules/src/system-agent-audit-actions.ts +3 -0
  144. package/template/packages/modules/src/system-ai-api-bindings.ts +15 -0
  145. package/template/packages/modules/src/system-audit-actions.ts +15 -0
  146. package/template/packages/server-sdk/index.ts +52 -0
  147. package/template/packages/server-sdk/package.json +5 -1
  148. package/template/packages/server-sdk/src/client-agent-session.ts +13 -1
  149. package/template/packages/server-sdk/src/client-agent-workflow-artifact.contract.test.ts +113 -0
  150. package/template/packages/server-sdk/src/client-agent-workflow-artifact.ts +183 -0
  151. package/template/packages/server-sdk/src/durable-handler.ts +7 -0
  152. package/template/packages/server-sdk/src/request-context.ts +7 -0
  153. package/template/packages/server-sdk/src/workflow-input-artifact-port.ts +104 -0
  154. package/template/packages/server-sdk/src/workflow-input-artifact-validation.contract.test.ts +124 -0
  155. package/template/packages/server-sdk/src/workflow-input-artifact-validation.ts +347 -0
  156. package/template/packages/server-sdk/src/workflow-input-materialization-handler.ts +43 -0
  157. package/template/packages/storage/package.json +1 -1
  158. package/template/packages/storage/src/blob-store-put-once.test.ts +70 -0
  159. package/template/packages/storage/src/blob-store.ts +9 -0
  160. package/template/packages/storage/src/local-file-blob-put-once.ts +120 -0
  161. package/template/packages/storage/src/local-file-blob-store.ts +53 -1
  162. package/template/packages/storage/src/memory-blob-store.ts +73 -33
@@ -0,0 +1,31 @@
1
+ import type { ModuleAiJsonValue } from "@southwind-ai/server-sdk";
2
+ import type { RequestGuardContext } from "../../guards.js";
3
+ import { clientSessionTerminalDigest } from "../client-session/digest.js";
4
+ import type { ClientAgentWorkflowArtifactRecord } from "./contracts.js";
5
+ import { clientWorkflowPublicView } from "./presentation.js";
6
+ import { requireTerminalClientWorkflowArtifact } from "./service-authorization.js";
7
+ import { workflowArtifactConflict } from "./service-support.js";
8
+ import type { ClientAgentWorkflowFactsLoader } from "./workflow-loader.js";
9
+
10
+ export async function replayCompletedClientWorkflowArtifact(input: {
11
+ record: ClientAgentWorkflowArtifactRecord;
12
+ receiptIds: readonly string[];
13
+ result?: ModuleAiJsonValue;
14
+ context: RequestGuardContext;
15
+ signal: AbortSignal;
16
+ loader: ClientAgentWorkflowFactsLoader;
17
+ }) {
18
+ const facts = await requireTerminalClientWorkflowArtifact({
19
+ record: input.record,
20
+ context: input.context,
21
+ signal: input.signal,
22
+ loader: input.loader,
23
+ });
24
+ if (
25
+ input.record.terminalRequestDigest !==
26
+ clientSessionTerminalDigest(input.receiptIds, input.result)
27
+ ) {
28
+ throw workflowArtifactConflict("终态请求摘要与首次完成不一致");
29
+ }
30
+ return clientWorkflowPublicView(input.record, facts.binding.artifact.kind);
31
+ }
@@ -0,0 +1,211 @@
1
+ import type { ModuleAiJsonValue } from "@southwind-ai/server-sdk";
2
+ import type { BlobStore } from "@southwind-ai/storage";
3
+ import type { ClientSessionRecord } from "../client-session/contracts.js";
4
+ import {
5
+ clientSessionTerminalDigest,
6
+ digestJson,
7
+ digestText,
8
+ } from "../client-session/digest.js";
9
+ import type { ClientSessionRepository } from "../client-session/repository.js";
10
+ import type { GovernedClientAgentSessionService } from "../client-session/service.js";
11
+ import { ClientAgentSessionError } from "../client-session/errors.js";
12
+ import {
13
+ clientWorkflowTerminalReceipt,
14
+ storeClientWorkflowArtifact,
15
+ } from "./artifact-builder.js";
16
+ import type { ClientAgentWorkflowArtifactRecord } from "./contracts.js";
17
+ import { clientWorkflowPayloadOf } from "./presentation.js";
18
+ import type { ClientAgentWorkflowArtifactRepository } from "./repository.js";
19
+ import {
20
+ workflowArtifactConflict as conflict,
21
+ workflowArtifactHidden as hidden,
22
+ } from "./service-support.js";
23
+ import { clientWorkflowSessionCall } from "./session-boundary.js";
24
+ import type { ClientAgentWorkflowFactsLoader } from "./workflow-loader.js";
25
+ import type { ClientAgentWorkflowTaskAuthority } from "./task-authority.js";
26
+
27
+ interface TerminalProjectionPorts {
28
+ signal: AbortSignal;
29
+ sessionRepository: ClientSessionRepository;
30
+ repository: ClientAgentWorkflowArtifactRepository;
31
+ loader: ClientAgentWorkflowFactsLoader;
32
+ blobs: BlobStore;
33
+ now: () => number;
34
+ }
35
+
36
+ export async function sealClientWorkflowArtifact(
37
+ input: TerminalProjectionPorts & {
38
+ current: ClientAgentWorkflowArtifactRecord;
39
+ claimToken: string;
40
+ receiptIds: readonly string[];
41
+ result?: ModuleAiJsonValue;
42
+ sessions: GovernedClientAgentSessionService;
43
+ tasks: ClientAgentWorkflowTaskAuthority;
44
+ },
45
+ ) {
46
+ const requestDigest = clientSessionTerminalDigest(
47
+ input.receiptIds,
48
+ input.result,
49
+ );
50
+ const currentFacts = await input.loader.loadTerminal({
51
+ record: input.current,
52
+ signal: input.signal,
53
+ });
54
+ const openedInputArtifacts = await input.tasks.openInputArtifacts({
55
+ artifacts: currentFacts.inputArtifacts,
56
+ actorId: input.current.actorId,
57
+ scopeDigest: input.current.scopeDigest,
58
+ signal: input.signal,
59
+ });
60
+ const completed = await clientWorkflowSessionCall(
61
+ input.sessions.finalizeWorkflow(
62
+ input.current.clientSessionId!,
63
+ {
64
+ actorId: input.current.actorId,
65
+ clientBindingDigest: input.current.clientBindingDigest!,
66
+ hostSessionDigest: input.current.hostSessionDigest!,
67
+ },
68
+ input.receiptIds,
69
+ input.result,
70
+ async (proposedResult) => {
71
+ try {
72
+ return await currentFacts.binding.terminalResultAuthority.canonicalize(
73
+ {
74
+ workflowInput: currentFacts.input,
75
+ inputArtifacts: openedInputArtifacts,
76
+ proposedResult,
77
+ actorId: input.current.actorId,
78
+ scopeDigest: input.current.scopeDigest,
79
+ signal: input.signal,
80
+ },
81
+ );
82
+ } catch {
83
+ throw new ClientAgentSessionError(
84
+ "INVALID_INPUT",
85
+ "Project terminal result authority 拒绝结果",
86
+ 400,
87
+ );
88
+ }
89
+ },
90
+ ),
91
+ "finalize",
92
+ );
93
+ if (completed.status !== "completed" || completed.result === undefined) {
94
+ throw conflict("Client Agent Session 尚未完成");
95
+ }
96
+ const session = await input.sessionRepository.find(
97
+ input.current.clientSessionId!,
98
+ );
99
+ if (!session || session.terminalDigest !== requestDigest) {
100
+ throw conflict("Client Agent Session 终态请求摘要冲突");
101
+ }
102
+ return sealCompletedClientWorkflowSession({
103
+ ...input,
104
+ session,
105
+ terminalRequestDigest: requestDigest,
106
+ claimTokenHash: digestText(input.claimToken),
107
+ });
108
+ }
109
+
110
+ export async function sealCompletedClientWorkflowSession(
111
+ input: TerminalProjectionPorts & {
112
+ current: ClientAgentWorkflowArtifactRecord;
113
+ session: ClientSessionRecord;
114
+ terminalRequestDigest: `sha256:${string}`;
115
+ claimTokenHash: `sha256:${string}`;
116
+ },
117
+ ) {
118
+ const { current, session } = input;
119
+ if (
120
+ session.status !== "completed" ||
121
+ !session.finalResult ||
122
+ session.terminalDigest !== input.terminalRequestDigest ||
123
+ session.sessionId !== current.clientSessionId ||
124
+ session.actorId !== current.actorId ||
125
+ session.operationKey !== current.operationKey ||
126
+ session.clientBindingDigest !== current.clientBindingDigest ||
127
+ session.hostSessionDigest !== current.hostSessionDigest ||
128
+ input.claimTokenHash !== current.claimTokenHash
129
+ ) {
130
+ throw hidden();
131
+ }
132
+ const history = [...session.receipts]
133
+ .sort((left, right) => left.attempt - right.attempt)
134
+ .map((receipt) => ({
135
+ receiptId: receipt.receiptId,
136
+ attempt: receipt.attempt,
137
+ requestDigest: receipt.requestDigest,
138
+ responseDigest: receipt.responseDigest,
139
+ deploymentDigest: receipt.deploymentDigest,
140
+ issuedAt: new Date(receipt.issuedAt).toISOString(),
141
+ }));
142
+ if (!history.length) throw hidden();
143
+ const historyHeadDigest = digestJson(history);
144
+ const terminalReceiptId = clientWorkflowTerminalReceipt(
145
+ current,
146
+ historyHeadDigest,
147
+ );
148
+ const terminalReceiptDigest = digestJson({
149
+ terminalReceiptId,
150
+ terminalRequestDigest: input.terminalRequestDigest,
151
+ workId: current.workId,
152
+ claimGeneration: current.claimGeneration,
153
+ clientRunId: session.clientRunId,
154
+ historyHeadDigest,
155
+ result: session.finalResult.result,
156
+ });
157
+ const terminalResult = {
158
+ schemaVersion: 1,
159
+ result: session.finalResult.result,
160
+ attestation: {
161
+ clientRunId: session.clientRunId,
162
+ terminalReceiptId,
163
+ terminalReceiptDigest,
164
+ historyLength: history.length,
165
+ historyHeadDigest,
166
+ providerAttested: session.finalResult.attestation.providerAttested,
167
+ },
168
+ provenance: {
169
+ workId: current.workId,
170
+ workflowRunId: current.runId,
171
+ claimGeneration: current.claimGeneration,
172
+ },
173
+ } as const satisfies ModuleAiJsonValue;
174
+ const facts = await input.loader.load({
175
+ jobId: current.durableJobId,
176
+ payload: clientWorkflowPayloadOf(current),
177
+ signal: input.signal,
178
+ });
179
+ const artifact = await storeClientWorkflowArtifact({
180
+ blobs: input.blobs,
181
+ result: terminalResult,
182
+ binding: facts.binding,
183
+ terminalReceiptDigest,
184
+ });
185
+ const terminal = await input.repository.complete({
186
+ workId: current.workId,
187
+ claimTokenHash: input.claimTokenHash,
188
+ terminal: {
189
+ claimGeneration: current.claimGeneration,
190
+ clientSessionId: current.clientSessionId!,
191
+ historySequence: history.length,
192
+ historyHeadDigest,
193
+ terminalReceiptId,
194
+ terminalReceiptDigest,
195
+ terminalRequestDigest: input.terminalRequestDigest,
196
+ terminalResult,
197
+ artifact,
198
+ now: input.now(),
199
+ },
200
+ });
201
+ if (terminal) return terminal;
202
+ const converged = await input.repository.find(current.workId);
203
+ if (
204
+ converged?.status === "completed" &&
205
+ converged.terminalReceiptDigest === terminalReceiptDigest &&
206
+ converged.terminalRequestDigest === input.terminalRequestDigest
207
+ ) {
208
+ return converged;
209
+ }
210
+ throw conflict("终态回执与当前领取代次冲突");
211
+ }
@@ -0,0 +1,173 @@
1
+ import type { ModuleClientAgentHostPrincipal } from "@southwind-ai/server-sdk";
2
+ import type { RequestGuardContext } from "../../guards.js";
3
+ import { buildScopeContext } from "../../data-access/context.js";
4
+ import { captureAuthorizationScope } from "../../data-access/scope-snapshot.js";
5
+ import { digestJson } from "../client-session/digest.js";
6
+ import type {
7
+ ClientAgentWorkflowArtifactBinding,
8
+ ClientAgentWorkflowArtifactRecord,
9
+ } from "./contracts.js";
10
+ import { clientWorkflowBindingCommitment } from "./binding-registry.js";
11
+ import type { ClientAgentWorkflowFactsLoader } from "./workflow-loader.js";
12
+
13
+ export const clientBindingDigest = `sha256:${"b".repeat(64)}` as const;
14
+ export const workflowInput = { question: "研判当前页面线索" } as const;
15
+
16
+ export const workflowBinding: ClientAgentWorkflowArtifactBinding = {
17
+ workflowKey: "case.full-analysis",
18
+ nodeId: "page-agent-artifact",
19
+ operationKey: "analysis.page-agent",
20
+ releaseDigest: `sha256:${"d".repeat(64)}`,
21
+ scopeContainmentContractVersion: 1,
22
+ terminalResultAuthority: {
23
+ version: "sharp.page-agent-result.v1",
24
+ digest: `sha256:${"e".repeat(64)}`,
25
+ async canonicalize({ proposedResult, inputArtifacts }) {
26
+ if (!Array.isArray(inputArtifacts)) {
27
+ throw new Error("terminal input artifacts missing");
28
+ }
29
+ return proposedResult;
30
+ },
31
+ },
32
+ clientTaskAuthority: {
33
+ version: "sharp.page-agent-task.v1",
34
+ digest: `sha256:${"f".repeat(64)}`,
35
+ async build({ workflowInput }) {
36
+ return { taskKey: "sharp.page-agent", input: workflowInput };
37
+ },
38
+ },
39
+ launchAuthority: {
40
+ version: "sharp.workflow-launch.v1",
41
+ digest: `sha256:${"a".repeat(64)}`,
42
+ async authorizeRelease() {},
43
+ async authorizeRun({ currentAuthorizationScope }) {
44
+ return {
45
+ authorizationScope: currentAuthorizationScope,
46
+ };
47
+ },
48
+ },
49
+ artifact: {
50
+ kind: "structured-data",
51
+ contentType: "application/json",
52
+ filename: "page-agent-result.json",
53
+ retentionPolicyKey: "case-analysis",
54
+ maxByteSize: 64 * 1024,
55
+ },
56
+ };
57
+
58
+ export const principal: ModuleClientAgentHostPrincipal = {
59
+ actorId: "actor-1",
60
+ installationId: "installation-1",
61
+ sessionId: "host-session-1",
62
+ };
63
+
64
+ const scopeContext = buildScopeContext(principal.actorId, undefined, [
65
+ {
66
+ id: "role-analyst",
67
+ code: "analyst",
68
+ dataScope: "self",
69
+ departmentIds: [],
70
+ },
71
+ ]);
72
+
73
+ export const guardContext: RequestGuardContext = {
74
+ requestId: "request-1",
75
+ actor: {
76
+ id: principal.actorId,
77
+ type: "user",
78
+ name: "研判员",
79
+ roleCodes: ["analyst"],
80
+ permissionKeys: ["system.agent-workflow.manage"],
81
+ dataAccess: scopeContext,
82
+ scopeContext,
83
+ },
84
+ startedAt: "2026-08-28T00:00:00.000Z",
85
+ };
86
+
87
+ export function workflowRecord(
88
+ patch: Partial<ClientAgentWorkflowArtifactRecord> = {},
89
+ ): ClientAgentWorkflowArtifactRecord {
90
+ const scope = captureAuthorizationScope(guardContext.actor.scopeContext);
91
+ return {
92
+ workId: "cawa_work-1",
93
+ commandId: "command-1",
94
+ durableJobId: "job-1",
95
+ runId: "run-1",
96
+ nodeRunId: "node-run-1",
97
+ effectKind: "job",
98
+ taskKey: "system.agent-workflow.client-agent-artifact",
99
+ operationKey: workflowBinding.operationKey,
100
+ bindingDigest: digestJson(clientWorkflowBindingCommitment(workflowBinding)),
101
+ actorId: principal.actorId,
102
+ scopeDigest: `sha256:${scope.hash}`,
103
+ authorizationSnapshotDigest: digestJson({ actorId: principal.actorId }),
104
+ runPolicyDigest: digestJson({ mode: "governed" }),
105
+ requestDigest: digestJson({ commandId: "command-1" }),
106
+ inputDigest: digestJson(workflowInput),
107
+ effectGeneration: 1,
108
+ effectFenceTokenDigest: digestJson({ fence: "fence-1" }),
109
+ status: "pending",
110
+ claimGeneration: 0,
111
+ historySequence: 0,
112
+ version: 1,
113
+ createdAt: 1_000,
114
+ updatedAt: 1_000,
115
+ ...patch,
116
+ };
117
+ }
118
+
119
+ export function workflowLoader(
120
+ input: {
121
+ record?: () => ClientAgentWorkflowArtifactRecord;
122
+ trace?: string[];
123
+ active?: () => boolean;
124
+ terminal?: () => boolean;
125
+ canonicalize?: typeof workflowBinding.terminalResultAuthority.canonicalize;
126
+ } = {},
127
+ ): ClientAgentWorkflowFactsLoader {
128
+ return {
129
+ load: async () => {
130
+ if (input.active?.() === false) throw new Error("ACTIVE_EFFECT_CLOSED");
131
+ input.trace?.push("authority-fence-current");
132
+ return {
133
+ record: structuredClone(input.record?.() ?? workflowRecord()),
134
+ input: structuredClone(workflowInput),
135
+ inputArtifacts: [],
136
+ frozenScope: captureAuthorizationScope(guardContext.actor.scopeContext)
137
+ .snapshot,
138
+ binding: cloneWorkflowBinding(input.canonicalize),
139
+ };
140
+ },
141
+ loadTerminal: async () => {
142
+ if (input.terminal?.() === false)
143
+ throw new Error("TERMINAL_AUTHORIZATION_STALE");
144
+ input.trace?.push("terminal-authority-current");
145
+ return {
146
+ binding: cloneWorkflowBinding(input.canonicalize),
147
+ input: structuredClone(workflowInput),
148
+ inputArtifacts: [],
149
+ frozenScope: captureAuthorizationScope(guardContext.actor.scopeContext)
150
+ .snapshot,
151
+ };
152
+ },
153
+ } as unknown as ClientAgentWorkflowFactsLoader;
154
+ }
155
+
156
+ function cloneWorkflowBinding(
157
+ canonicalize = workflowBinding.terminalResultAuthority.canonicalize,
158
+ ): ClientAgentWorkflowArtifactBinding {
159
+ return {
160
+ ...structuredClone(clientWorkflowBindingCommitment(workflowBinding)),
161
+ terminalResultAuthority: {
162
+ ...structuredClone(
163
+ clientWorkflowBindingCommitment(workflowBinding)
164
+ .terminalResultAuthority,
165
+ ),
166
+ canonicalize,
167
+ },
168
+ clientTaskAuthority: workflowBinding.clientTaskAuthority,
169
+ launchAuthority: workflowBinding.launchAuthority,
170
+ };
171
+ }
172
+
173
+ export const workflowSignal = new AbortController().signal;
@@ -0,0 +1,254 @@
1
+ import { expect, test } from "bun:test";
2
+ import type { DurableJobService } from "../../jobs/service.js";
3
+ import { buildScopeContext } from "../../data-access/context.js";
4
+ import { captureAuthorizationScope } from "../../data-access/scope-snapshot.js";
5
+ import type { DrizzleAgentWorkflowRepository } from "../../agent-workflow/drizzle-repository.js";
6
+ import { ClientAgentWorkflowArtifactBindingRegistry } from "./binding-registry.js";
7
+ import { ClientAgentWorkflowFactsLoader } from "./workflow-loader.js";
8
+ import {
9
+ workflowBinding,
10
+ workflowInput,
11
+ workflowSignal,
12
+ } from "./workflow-artifact.test-support.js";
13
+
14
+ test("loader pin Immutable Release 与唯一 job-artifact-final 拓扑", async () => {
15
+ const fixture = loaderFixture();
16
+ const facts = await fixture.loader.load({
17
+ jobId: "job-1",
18
+ payload: {
19
+ commandId: "command-1",
20
+ runId: "run-1",
21
+ nodeRunId: "node-run-1",
22
+ effectGeneration: 1,
23
+ requestDigest: fixture.command.requestDigest,
24
+ },
25
+ signal: workflowSignal,
26
+ });
27
+ expect(facts.binding.releaseDigest).toBe(workflowBinding.releaseDigest);
28
+
29
+ fixture.release.releaseDigest = `sha256:${"e".repeat(64)}`;
30
+ await expect(
31
+ fixture.loader.load({
32
+ jobId: "job-1",
33
+ payload: {
34
+ commandId: "command-1",
35
+ runId: "run-1",
36
+ nodeRunId: "node-run-1",
37
+ },
38
+ signal: workflowSignal,
39
+ }),
40
+ ).rejects.toThrow("CLIENT_AGENT_WORKFLOW_RELEASE_BINDING_INVALID");
41
+
42
+ fixture.release.releaseDigest = workflowBinding.releaseDigest;
43
+ fixture.release.definition.edges.push({
44
+ from: workflowBinding.nodeId,
45
+ to: "final",
46
+ });
47
+ await expect(
48
+ fixture.loader.load({
49
+ jobId: "job-1",
50
+ payload: {
51
+ commandId: "command-1",
52
+ runId: "run-1",
53
+ nodeRunId: "node-run-1",
54
+ },
55
+ signal: workflowSignal,
56
+ }),
57
+ ).rejects.toThrow("CLIENT_AGENT_WORKFLOW_RELEASE_BINDING_INVALID");
58
+
59
+ fixture.release.definition.edges.pop();
60
+ const fallbackPolicy = {
61
+ mode: "fallback",
62
+ nodeId: "final",
63
+ };
64
+ fixture.release.definition.nodes[0]!.failurePolicy = fallbackPolicy;
65
+ await expect(
66
+ fixture.loader.load({
67
+ jobId: "job-1",
68
+ payload: {
69
+ commandId: "command-1",
70
+ runId: "run-1",
71
+ nodeRunId: "node-run-1",
72
+ },
73
+ signal: workflowSignal,
74
+ }),
75
+ ).rejects.toThrow("CLIENT_AGENT_WORKFLOW_RELEASE_BINDING_INVALID");
76
+ });
77
+
78
+ test("terminal loader 接受 committed/completed immutable facts 并拒绝摘要漂移", async () => {
79
+ const fixture = loaderFixture();
80
+ const begun = await fixture.loader.load({
81
+ jobId: "job-1",
82
+ payload: {
83
+ commandId: "command-1",
84
+ runId: "run-1",
85
+ nodeRunId: "node-run-1",
86
+ },
87
+ signal: workflowSignal,
88
+ });
89
+ fixture.snapshot.run.status = "completed";
90
+ fixture.snapshot.nodeRuns[0]!.status = "completed";
91
+ fixture.command.status = "committed";
92
+ await expect(
93
+ fixture.loader.loadTerminal({
94
+ record: begun.record,
95
+ signal: workflowSignal,
96
+ }),
97
+ ).resolves.toMatchObject({ binding: workflowBinding });
98
+
99
+ fixture.command.requestDigest = `sha256:${"9".repeat(64)}`;
100
+ await expect(
101
+ fixture.loader.loadTerminal({
102
+ record: begun.record,
103
+ signal: workflowSignal,
104
+ }),
105
+ ).rejects.toThrow("WORKFLOW_TERMINAL_IDENTITY_INVALID");
106
+ });
107
+
108
+ function loaderFixture() {
109
+ const scope = captureAuthorizationScope(
110
+ buildScopeContext("actor-1", undefined, [
111
+ {
112
+ id: "role-analyst",
113
+ code: "analyst",
114
+ dataScope: "self",
115
+ departmentIds: [],
116
+ },
117
+ ]),
118
+ );
119
+ const release = {
120
+ releaseId: "workflow-release-1",
121
+ releaseDigest: workflowBinding.releaseDigest,
122
+ definitionId: "workflow-definition-1",
123
+ definitionDigest: `sha256:${"f".repeat(64)}`,
124
+ definition: {
125
+ schemaVersion: 1,
126
+ workflowKey: workflowBinding.workflowKey,
127
+ version: "1.0.0",
128
+ label: "全案线索研判",
129
+ entryNodeId: workflowBinding.nodeId,
130
+ nodes: [
131
+ {
132
+ id: workflowBinding.nodeId,
133
+ type: "job",
134
+ label: "PageAgent",
135
+ taskKey: "system.agent-workflow.client-agent-artifact",
136
+ failurePolicy: { mode: "fail-run" },
137
+ },
138
+ {
139
+ id: "page-agent-output",
140
+ type: "artifact",
141
+ label: "受治理产物",
142
+ policyKey: workflowBinding.artifact.retentionPolicyKey,
143
+ artifactKind: workflowBinding.artifact.kind,
144
+ failurePolicy: { mode: "fail-run" },
145
+ },
146
+ {
147
+ id: "final",
148
+ type: "final",
149
+ label: "完成",
150
+ outputSchemaKey: "analysis.result.v1",
151
+ failurePolicy: { mode: "fail-run" },
152
+ },
153
+ ],
154
+ edges: [
155
+ { from: workflowBinding.nodeId, to: "page-agent-output" },
156
+ { from: "page-agent-output", to: "final" },
157
+ ],
158
+ budget: budget(),
159
+ },
160
+ coordinates: {
161
+ runtimeVersion: "runtime-1",
162
+ routeVersion: "route-1",
163
+ promptVersion: "prompt-1",
164
+ toolSchemaVersion: "tool-schema-1",
165
+ manifestDigest: `sha256:${"a".repeat(64)}`,
166
+ },
167
+ publishedBy: "actor-1",
168
+ publishedAt: "2026-08-28T00:00:00.000Z",
169
+ };
170
+ const command = {
171
+ commandId: "command-1",
172
+ runId: "run-1",
173
+ nodeRunId: "node-run-1",
174
+ effectKind: "job",
175
+ effectKey: workflowBinding.nodeId,
176
+ adapter: { kind: "durable-job", coordinate: "job-idempotency:node-1" },
177
+ idempotencyKey: "job-command-1",
178
+ requestDigest: `sha256:${"1".repeat(64)}`,
179
+ generation: 1,
180
+ fenceTokenDigest: `sha256:${"2".repeat(64)}`,
181
+ authorizationSnapshotDigest: `sha256:${"3".repeat(64)}`,
182
+ runPolicyDigest: `sha256:${"4".repeat(64)}`,
183
+ status: "dispatched",
184
+ version: 2,
185
+ createdAt: "2026-08-28T00:00:00.000Z",
186
+ updatedAt: "2026-08-28T00:00:01.000Z",
187
+ };
188
+ const snapshot = {
189
+ run: {
190
+ runId: "run-1",
191
+ releaseId: release.releaseId,
192
+ actorId: "actor-1",
193
+ scopeDigest: `sha256:${scope.hash}`,
194
+ authorizationSnapshotDigest: command.authorizationSnapshotDigest,
195
+ executionPolicyDigest: command.runPolicyDigest,
196
+ status: "running",
197
+ inputReceipt: {
198
+ schemaKey: "analysis.input.v1",
199
+ value: workflowInput,
200
+ valueDigest: `sha256:${"5".repeat(64)}`,
201
+ recordedAt: "2026-08-28T00:00:00.000Z",
202
+ },
203
+ },
204
+ nodeRuns: [
205
+ {
206
+ nodeRunId: "node-run-1",
207
+ runId: "run-1",
208
+ nodeId: workflowBinding.nodeId,
209
+ nodeType: "job",
210
+ status: "running",
211
+ inputArtifacts: [],
212
+ outputArtifacts: [],
213
+ },
214
+ ],
215
+ sideEffects: [command],
216
+ };
217
+ const workflows = {
218
+ getSnapshot: async () => snapshot,
219
+ getRelease: async () => release,
220
+ } as unknown as DrizzleAgentWorkflowRepository;
221
+ const jobs = {
222
+ get: async () => ({
223
+ job: {
224
+ id: "job-1",
225
+ handlerKey: "system.agent-workflow.client-agent-artifact",
226
+ requestedBy: "actor-1",
227
+ authorizationScope: scope.snapshot,
228
+ },
229
+ }),
230
+ } as unknown as DurableJobService;
231
+ return {
232
+ loader: new ClientAgentWorkflowFactsLoader(
233
+ workflows,
234
+ jobs,
235
+ new ClientAgentWorkflowArtifactBindingRegistry([workflowBinding]),
236
+ ),
237
+ release,
238
+ command,
239
+ snapshot,
240
+ };
241
+ }
242
+
243
+ function budget() {
244
+ return {
245
+ maxDurationSeconds: 600,
246
+ maxModelAttempts: 1,
247
+ maxToolCalls: 0,
248
+ maxSubagents: 0,
249
+ maxParallelism: 1,
250
+ maxInputTokens: 1,
251
+ maxOutputTokens: 1,
252
+ maxCostMicros: 1,
253
+ };
254
+ }