@teamclaws/teamclaw 2026.8.1 → 2026.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +318 -17
- package/dist/index.js +54 -32
- package/dist/src/config.js +57 -2
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +814 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +338 -50
- package/dist/src/controller/controller-tools.js +14 -7
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +290 -6003
- package/dist/src/controller/kickoff-orchestrator.js +33 -43
- package/dist/src/controller/message-delivery.js +31 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +11 -93
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +309 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +19 -9
- package/dist/src/controller/provisioning/backend-contract.js +9 -0
- package/dist/src/controller/provisioning/container-shared.js +64 -0
- package/dist/src/controller/provisioning/docker.js +214 -0
- package/dist/src/controller/provisioning/kubernetes.js +244 -0
- package/dist/src/controller/provisioning/plugin-root.js +41 -0
- package/dist/src/controller/provisioning/process-supervisor.js +190 -0
- package/dist/src/controller/provisioning-config.js +239 -0
- package/dist/src/controller/repo-routes.js +129 -0
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/role-inference.js +231 -20
- package/dist/src/controller/route-table.js +375 -0
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +511 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +271 -0
- package/dist/src/controller/task-results.js +471 -0
- package/dist/src/controller/task-router.js +74 -4
- package/dist/src/controller/task-routes.js +703 -0
- package/dist/src/controller/teamauto-routes.js +124 -0
- package/dist/src/controller/tunnel-manager.js +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +6 -2
- package/dist/src/controller/webui-routes.js +49 -0
- package/dist/src/controller/worker-provisioning.js +69 -953
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/controller/workflow-routes.js +407 -0
- package/dist/src/controller/workspace-routes.js +200 -0
- package/dist/src/git-collaboration.js +4 -9
- package/dist/src/identity.js +15 -3
- package/dist/src/interaction-contracts.js +7 -7
- package/dist/src/openclaw-workspace.js +40 -18
- package/dist/src/profile-loader.js +604 -0
- package/dist/src/profiles/banking.json +202 -0
- package/dist/src/profiles/crossborder-ecom.json +253 -0
- package/dist/src/profiles/insurance.json +157 -0
- package/dist/src/profiles/knowledge/hs-structure.md +97 -0
- package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/dist/src/profiles/knowledge/vat-principles.md +85 -0
- package/dist/src/profiles/schema.json +281 -0
- package/dist/src/profiles/securities.json +137 -0
- package/dist/src/profiles/software-rd.json +264 -0
- package/dist/src/profiles/trading-co.json +200 -0
- package/dist/src/prompt-policy.js +42 -17
- package/dist/src/protocol.js +66 -3
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +54 -13
- package/dist/src/session-roles.js +14 -0
- package/dist/src/shared/clarification-schema.js +65 -0
- package/dist/src/shared/github-auth.js +15 -0
- package/dist/src/shared/kickoff-prompt.js +37 -0
- package/dist/src/shared/utils.js +47 -0
- package/dist/src/state.js +275 -11
- package/dist/src/task-executor.js +7 -17
- package/dist/src/teamauto/github-client.js +18 -0
- package/dist/src/teamauto/repo-sync.js +228 -6
- package/dist/src/teamauto/scanner.js +40 -12
- package/dist/src/teamauto/scheduler.js +231 -12
- package/dist/src/types.js +77 -16
- package/dist/src/ui/app.js +1434 -82
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +144 -45
- package/dist/src/ui/style.css +194 -0
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/prompt-injector.js +44 -8
- package/dist/src/worker/skill-installer.js +6 -10
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +93 -7
- package/index.ts +61 -32
- package/openclaw.plugin.json +50 -2
- package/package.json +3 -2
- package/src/config.ts +57 -2
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1037 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +422 -50
- package/src/controller/controller-tools.ts +16 -9
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +336 -6964
- package/src/controller/kickoff-orchestrator.ts +69 -45
- package/src/controller/message-delivery.ts +52 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +14 -100
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +396 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/provisioning/backend-contract.ts +51 -0
- package/src/controller/provisioning/container-shared.ts +84 -0
- package/src/controller/provisioning/docker.ts +260 -0
- package/src/controller/provisioning/kubernetes.ts +263 -0
- package/src/controller/provisioning/plugin-root.ts +42 -0
- package/src/controller/provisioning/process-supervisor.ts +214 -0
- package/src/controller/provisioning-config.ts +289 -0
- package/src/controller/repo-routes.ts +163 -0
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +597 -0
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +622 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +399 -0
- package/src/controller/task-results.ts +556 -0
- package/src/controller/task-router.ts +98 -6
- package/src/controller/task-routes.ts +812 -0
- package/src/controller/teamauto-routes.ts +121 -0
- package/src/controller/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +32 -4
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +83 -1121
- package/src/controller/worker-routes.ts +241 -0
- package/src/controller/workflow-routes.ts +498 -0
- package/src/controller/workspace-routes.ts +222 -0
- package/src/git-collaboration.ts +4 -9
- package/src/identity.ts +16 -3
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +816 -0
- package/src/profiles/banking.json +202 -0
- package/src/profiles/crossborder-ecom.json +253 -0
- package/src/profiles/insurance.json +157 -0
- package/src/profiles/knowledge/hs-structure.md +97 -0
- package/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/src/profiles/knowledge/vat-principles.md +85 -0
- package/src/profiles/schema.json +281 -0
- package/src/profiles/securities.json +137 -0
- package/src/profiles/software-rd.json +264 -0
- package/src/profiles/trading-co.json +200 -0
- package/src/prompt-policy.ts +44 -17
- package/src/protocol.ts +72 -2
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/shared/clarification-schema.ts +81 -0
- package/src/shared/github-auth.ts +92 -0
- package/src/shared/kickoff-prompt.ts +47 -0
- package/src/shared/utils.ts +51 -0
- package/src/state.ts +326 -10
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +23 -1
- package/src/teamauto/repo-sync.ts +248 -7
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +261 -17
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +263 -17
- package/src/ui/app.js +1434 -82
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +144 -45
- package/src/ui/style.css +194 -0
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +6 -10
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +101 -7
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
// Design 2.4 workflows backend (vertical-team-profiles-design.md section
|
|
2
|
+
// 2.4): declarative workflow templates with conclusion branches, consumed
|
|
3
|
+
// end to end from this module.
|
|
4
|
+
//
|
|
5
|
+
// - POST /api/v1/workflows/{id}/start (registered in route-table.ts):
|
|
6
|
+
// creates the FIRST step task of the named template (the UI wave renders
|
|
7
|
+
// the profile's workflows as a quick-action button group and posts here
|
|
8
|
+
// with optional initial context).
|
|
9
|
+
// - continueWorkflowAfterTaskCompletion: the task-completion hook that
|
|
10
|
+
// task-results.ts applyTaskResult invokes for tasks carrying
|
|
11
|
+
// TaskInfo.workflow. It parses the completed step's conclusion phrase
|
|
12
|
+
// from the result text (includes match, longest phrase wins) and routes
|
|
13
|
+
// per the step's `on` map - RUNTIME-DYNAMIC routing, the design's
|
|
14
|
+
// "controller 按 conclusion 路由" realized WITHOUT a controller LLM pass:
|
|
15
|
+
// the conclusion enum values are concrete phrases (e.g. 「通过」/
|
|
16
|
+
// 「退回补充材料」) the step's task description instructs the worker to
|
|
17
|
+
// end its deliverable with, so deterministic keyword matching suffices.
|
|
18
|
+
//
|
|
19
|
+
// The task chain IS the run state (per design: no separate registry): every
|
|
20
|
+
// step task carries TaskWorkflowContext {workflowId, runId, stepKey,
|
|
21
|
+
// visitCounts, routed* latch}, persists with TeamState, serializes through
|
|
22
|
+
// serializeTask, and the routed* latch makes routing exactly-once per step
|
|
23
|
+
// task. Workflow tasks are createdBy "workflow", so the generic controller
|
|
24
|
+
// LLM follow-up (continueControllerWorkflow) never fires for them - the
|
|
25
|
+
// declarative template replaces the LLM's free-form follow-up planning.
|
|
26
|
+
//
|
|
27
|
+
// Module-home rule mirrors the other route modules: TYPE-ONLY import of
|
|
28
|
+
// route-table.js (RouteContext); no runtime import of http-server.
|
|
29
|
+
|
|
30
|
+
import type { RoleId, TaskInfo, TaskWorkflowContext } from "../types.js";
|
|
31
|
+
import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
|
|
32
|
+
import { getActiveWorkflows, type TeamProfileWorkflow, type TeamProfileWorkflowStep } from "../profile-loader.js";
|
|
33
|
+
import { recordTaskExecutionEvent, serializeTask } from "./task-execution.js";
|
|
34
|
+
import { createControllerManagedTask } from "./controller-planning.js";
|
|
35
|
+
import { SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS } from "./controller-routes.js";
|
|
36
|
+
import type { ControllerTaskDomainDeps } from "./task-execution.js";
|
|
37
|
+
import type { RouteContext } from "./route-table.js";
|
|
38
|
+
|
|
39
|
+
/** createdBy stamp for workflow-engine tasks (skips the controller LLM follow-up path). */
|
|
40
|
+
const WORKFLOW_TASK_CREATED_BY = "workflow";
|
|
41
|
+
|
|
42
|
+
/** Return-edge loop guard: a step may be (re)entered at most this many times per run. */
|
|
43
|
+
export const MAX_WORKFLOW_STEP_VISITS = 3;
|
|
44
|
+
|
|
45
|
+
/** Upstream result excerpt cap when embedding outputs into a step description. */
|
|
46
|
+
const UPSTREAM_RESULT_EXCERPT_CHARS = 4000;
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
// Template helpers.
|
|
50
|
+
// ---------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
function stepKeyOf(stepId: number | string): string {
|
|
53
|
+
return String(stepId);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isBranchStep(step: TeamProfileWorkflowStep): boolean {
|
|
57
|
+
return typeof step.id === "string";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function findStep(workflow: TeamProfileWorkflow, stepKey: string): TeamProfileWorkflowStep | undefined {
|
|
61
|
+
return workflow.steps.find((step) => stepKeyOf(step.id) === stepKey);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Default "next" resolution (design 2.4: on-values may be "next" or a step
|
|
66
|
+
* id; conclusions without an explicit on-mapping fall through to next):
|
|
67
|
+
* advance along the NUMERIC spine to the smallest numeric step id greater
|
|
68
|
+
* than the current one. Branch steps (string ids like "committee") are never
|
|
69
|
+
* a default next - they are reachable only through an explicit on jump, so
|
|
70
|
+
* e.g. the within-mandate approval (step 2) ends the run instead of leaking
|
|
71
|
+
* into the committee step declared after it.
|
|
72
|
+
*/
|
|
73
|
+
function defaultNextStep(workflow: TeamProfileWorkflow, current: TeamProfileWorkflowStep): TeamProfileWorkflowStep | undefined {
|
|
74
|
+
if (isBranchStep(current)) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
return workflow.steps
|
|
78
|
+
.filter((step) => !isBranchStep(step) && (step.id as number) > (current.id as number))
|
|
79
|
+
.sort((a, b) => (a.id as number) - (b.id as number))[0];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Longest-phrase-wins includes match of the step's conclusion enum against
|
|
84
|
+
* the completed task's evidence text (result + result contract summary /
|
|
85
|
+
* key points / notes). Longest-first prevents a prefix phrase (「通过」 inside
|
|
86
|
+
* 「未通过」-style collisions, 「补充材料」 inside 「退回补充材料」) from
|
|
87
|
+
* shadowing the specific phrase.
|
|
88
|
+
*/
|
|
89
|
+
export function matchStepConclusion(step: TeamProfileWorkflowStep, evidenceText: string): string | undefined {
|
|
90
|
+
const conclusions = step.conclusion ?? [];
|
|
91
|
+
if (conclusions.length === 0 || !evidenceText) {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
return [...conclusions].sort((a, b) => b.length - a.length).find((phrase) => evidenceText.includes(phrase));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function collectResultEvidence(task: TaskInfo): string {
|
|
98
|
+
const contract = task.resultContract;
|
|
99
|
+
return [
|
|
100
|
+
task.result ?? "",
|
|
101
|
+
contract?.summary ?? "",
|
|
102
|
+
contract?.notes ?? "",
|
|
103
|
+
...(contract?.keyPoints ?? []),
|
|
104
|
+
].join("\n");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Task description assembly.
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
function conclusionInstruction(step: TeamProfileWorkflowStep): string {
|
|
112
|
+
const conclusions = step.conclusion ?? [];
|
|
113
|
+
if (conclusions.length === 0) {
|
|
114
|
+
return "";
|
|
115
|
+
}
|
|
116
|
+
return `结论要求:请在交付物结尾单独一行明确给出以下结论短语之一(工作流引擎按该短语路由下一步):${conclusions.map((phrase) => `「${phrase}」`).join(" / ")}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function truncateExcerpt(text: string, limit = UPSTREAM_RESULT_EXCERPT_CHARS): string {
|
|
120
|
+
const normalized = text.trim();
|
|
121
|
+
if (normalized.length <= limit) {
|
|
122
|
+
return normalized;
|
|
123
|
+
}
|
|
124
|
+
return `${normalized.slice(0, limit).trimEnd()}\n…(上游结果过长,已截断,完整内容见原任务)`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Design 2.4 outputKey passing: for every inputs[] key of the target step,
|
|
129
|
+
* embed the latest completed result of the step that declares that output.
|
|
130
|
+
*/
|
|
131
|
+
function buildUpstreamInputsSection(
|
|
132
|
+
targetStep: TeamProfileWorkflowStep,
|
|
133
|
+
workflow: TeamProfileWorkflow,
|
|
134
|
+
completedTasks: TaskInfo[],
|
|
135
|
+
): string {
|
|
136
|
+
const inputKeys = targetStep.inputs ?? [];
|
|
137
|
+
if (inputKeys.length === 0) {
|
|
138
|
+
return "";
|
|
139
|
+
}
|
|
140
|
+
const lines: string[] = [];
|
|
141
|
+
for (const inputKey of inputKeys) {
|
|
142
|
+
const declaringStep = workflow.steps.find((step) => (step.outputs ?? []).some((output) => output.key === inputKey));
|
|
143
|
+
if (!declaringStep) {
|
|
144
|
+
continue; // impossible after load validation (dangling input is fatal); belt-and-braces
|
|
145
|
+
}
|
|
146
|
+
const output = (declaringStep.outputs ?? []).find((entry) => entry.key === inputKey)!;
|
|
147
|
+
const sourceTask = completedTasks
|
|
148
|
+
.filter((task) => task.workflow?.stepKey === stepKeyOf(declaringStep.id))
|
|
149
|
+
.sort((a, b) => (b.completedAt ?? b.updatedAt) - (a.completedAt ?? a.updatedAt))[0];
|
|
150
|
+
if (sourceTask) {
|
|
151
|
+
lines.push(
|
|
152
|
+
`【上游产出 ${output.key}(${output.name},来自任务 ${sourceTask.id}:${declaringStep.title})】`,
|
|
153
|
+
truncateExcerpt(sourceTask.result ?? sourceTask.resultContract?.summary ?? "(上游任务未记录文本结果)"),
|
|
154
|
+
"",
|
|
155
|
+
);
|
|
156
|
+
} else {
|
|
157
|
+
lines.push(`【上游产出 ${output.key}(${output.name})】尚未生成:请先向 controller 申请 ${declaringStep.title} 的产出。`, "");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return lines.join("\n").trim();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function buildReturnReasonSection(returningTask: TaskInfo): string {
|
|
164
|
+
return [
|
|
165
|
+
`【退回意见(来自 ${returningTask.title},任务 ${returningTask.id} 的结论与要点)】`,
|
|
166
|
+
truncateExcerpt(collectResultEvidence(returningTask)),
|
|
167
|
+
].join("\n");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
// Run helpers.
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
function tasksOfWorkflowRun(state: { tasks: Record<string, TaskInfo> }, runId: string): TaskInfo[] {
|
|
175
|
+
return Object.values(state.tasks).filter((task) => task.workflow?.runId === runId);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function visitCountsIncluding(context: TaskWorkflowContext, stepKey: string): Record<string, number> {
|
|
179
|
+
const counts = { ...(context.visitCounts ?? {}) };
|
|
180
|
+
counts[stepKey] = (counts[stepKey] ?? 0) + 1;
|
|
181
|
+
return counts;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function createWorkflowStepTask(
|
|
185
|
+
input: {
|
|
186
|
+
workflow: TeamProfileWorkflow;
|
|
187
|
+
step: TeamProfileWorkflowStep;
|
|
188
|
+
runId: string;
|
|
189
|
+
description: string;
|
|
190
|
+
visitCounts: Record<string, number>;
|
|
191
|
+
},
|
|
192
|
+
deps: ControllerTaskDomainDeps,
|
|
193
|
+
): Promise<TaskInfo | undefined> {
|
|
194
|
+
const { workflow, step } = input;
|
|
195
|
+
const workflowContext: TaskWorkflowContext = {
|
|
196
|
+
workflowId: workflow.id,
|
|
197
|
+
runId: input.runId,
|
|
198
|
+
stepKey: stepKeyOf(step.id),
|
|
199
|
+
visitCounts: input.visitCounts,
|
|
200
|
+
};
|
|
201
|
+
return createControllerManagedTask({
|
|
202
|
+
title: step.title,
|
|
203
|
+
description: input.description,
|
|
204
|
+
assignedRole: step.role as RoleId,
|
|
205
|
+
createdBy: WORKFLOW_TASK_CREATED_BY,
|
|
206
|
+
projectName: `workflow-${workflow.id}`,
|
|
207
|
+
recommendedSkills: [],
|
|
208
|
+
workflow: workflowContext,
|
|
209
|
+
}, deps);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function buildStepDescription(
|
|
213
|
+
input: {
|
|
214
|
+
workflow: TeamProfileWorkflow;
|
|
215
|
+
step: TeamProfileWorkflowStep;
|
|
216
|
+
initialContext?: string;
|
|
217
|
+
upstreamSection?: string;
|
|
218
|
+
returnSection?: string;
|
|
219
|
+
},
|
|
220
|
+
): string {
|
|
221
|
+
const { workflow, step } = input;
|
|
222
|
+
const parts: string[] = [
|
|
223
|
+
`【工作流】${workflow.name}(workflow id: ${workflow.id})— 当前步骤:${step.title}`,
|
|
224
|
+
step.description ?? "",
|
|
225
|
+
];
|
|
226
|
+
if (input.initialContext?.trim()) {
|
|
227
|
+
parts.push(`【业务背景 / 初始材料】\n${input.initialContext.trim()}`);
|
|
228
|
+
}
|
|
229
|
+
if (input.returnSection) {
|
|
230
|
+
parts.push(input.returnSection);
|
|
231
|
+
}
|
|
232
|
+
if (input.upstreamSection) {
|
|
233
|
+
parts.push(`【上游交付(本步骤的输入)】\n${input.upstreamSection}`);
|
|
234
|
+
}
|
|
235
|
+
const instruction = conclusionInstruction(step);
|
|
236
|
+
if (instruction) {
|
|
237
|
+
parts.push(instruction);
|
|
238
|
+
}
|
|
239
|
+
return parts.filter((entry) => entry.trim().length > 0).join("\n\n");
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------------------------------------------------------------------------
|
|
243
|
+
// Completion routing (the design's "controller 按 conclusion 路由", minimal
|
|
244
|
+
// viable: deterministic phrase matching on the result evidence, no LLM pass).
|
|
245
|
+
// ---------------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
export async function continueWorkflowAfterTaskCompletion(
|
|
248
|
+
completedTask: TaskInfo,
|
|
249
|
+
deps: ControllerTaskDomainDeps,
|
|
250
|
+
): Promise<TaskInfo | undefined> {
|
|
251
|
+
const context = completedTask.workflow;
|
|
252
|
+
if (!context) {
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
const { logger } = deps;
|
|
256
|
+
const state = deps.getTeamState();
|
|
257
|
+
if (!state || !state.tasks[completedTask.id]) {
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const workflow = getActiveWorkflows().find((entry) => entry.id === context.workflowId);
|
|
262
|
+
if (!workflow) {
|
|
263
|
+
logger.warn(
|
|
264
|
+
`Workflow: task ${completedTask.id} references workflow "${context.workflowId}" which the active profile does not carry - chain stops`,
|
|
265
|
+
);
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
const currentStep = findStep(workflow, context.stepKey);
|
|
269
|
+
if (!currentStep) {
|
|
270
|
+
logger.warn(
|
|
271
|
+
`Workflow: task ${completedTask.id} references step "${context.stepKey}" of "${workflow.id}" which no longer exists - chain stops`,
|
|
272
|
+
);
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// 1. Decide the next step from the conclusion evidence (pure, no state).
|
|
277
|
+
const evidence = collectResultEvidence(state.tasks[completedTask.id] ?? completedTask);
|
|
278
|
+
const conclusion = matchStepConclusion(currentStep, evidence);
|
|
279
|
+
const explicitTarget = conclusion !== undefined ? currentStep.on?.[conclusion] : undefined;
|
|
280
|
+
let nextStep: TeamProfileWorkflowStep | undefined;
|
|
281
|
+
if (explicitTarget !== undefined && explicitTarget !== "next") {
|
|
282
|
+
nextStep = findStep(workflow, stepKeyOf(explicitTarget));
|
|
283
|
+
} else {
|
|
284
|
+
// No conclusion enum, no matching phrase (documented fallback), or an
|
|
285
|
+
// explicit "next": advance along the numeric spine.
|
|
286
|
+
nextStep = defaultNextStep(workflow, currentStep);
|
|
287
|
+
}
|
|
288
|
+
const nextStepKey = nextStep ? stepKeyOf(nextStep.id) : "";
|
|
289
|
+
const isReturnEdge = typeof nextStep?.id === "number"
|
|
290
|
+
&& typeof currentStep.id === "number"
|
|
291
|
+
&& (nextStep.id as number) <= currentStep.id;
|
|
292
|
+
|
|
293
|
+
// 2. Once-only routing latch + loop guard, set atomically in one state
|
|
294
|
+
// mutation (no await between latch and task creation, so concurrent
|
|
295
|
+
// completions cannot double-spawn the follow-up task). routedToStepKey
|
|
296
|
+
// records where the chain ACTUALLY went: the follow-up step key, or ""
|
|
297
|
+
// when the run ends (leaf completion or the guard refusing a return edge).
|
|
298
|
+
let alreadyRouted = false;
|
|
299
|
+
let loopGuardTripped = false;
|
|
300
|
+
let visitCounts = context.visitCounts ?? {};
|
|
301
|
+
deps.updateTeamState((s) => {
|
|
302
|
+
const task = s.tasks[completedTask.id];
|
|
303
|
+
if (!task?.workflow) {
|
|
304
|
+
alreadyRouted = true;
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (task.workflow.routedToStepKey !== undefined) {
|
|
308
|
+
alreadyRouted = true;
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (nextStep && (context.visitCounts?.[nextStepKey] ?? 0) + 1 > MAX_WORKFLOW_STEP_VISITS) {
|
|
312
|
+
loopGuardTripped = true;
|
|
313
|
+
}
|
|
314
|
+
task.workflow.routedToStepKey = loopGuardTripped ? "" : nextStepKey;
|
|
315
|
+
task.workflow.routedAt = Date.now();
|
|
316
|
+
task.workflow.routedConclusion = conclusion;
|
|
317
|
+
if (!loopGuardTripped) {
|
|
318
|
+
task.workflow.visitCounts = visitCountsIncluding(context, nextStepKey);
|
|
319
|
+
visitCounts = task.workflow.visitCounts;
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
if (alreadyRouted) {
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (loopGuardTripped) {
|
|
327
|
+
recordWorkflowRoutingEvent(completedTask.id, deps, currentStep,
|
|
328
|
+
`workflow "${workflow.id}" stopped: step "${nextStepKey}" would exceed ${MAX_WORKFLOW_STEP_VISITS} visits (return-edge loop guard)`);
|
|
329
|
+
logger.warn(
|
|
330
|
+
`Workflow: run ${context.runId} of "${workflow.id}" stopped at step ${context.stepKey} - step "${nextStepKey}" exceeded the ${MAX_WORKFLOW_STEP_VISITS}-visit loop guard`,
|
|
331
|
+
);
|
|
332
|
+
return undefined;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (conclusion === undefined && (currentStep.conclusion ?? []).length > 0) {
|
|
336
|
+
logger.warn(
|
|
337
|
+
`Workflow: task ${completedTask.id} (step ${context.stepKey} of "${workflow.id}") stated none of the step's conclusion phrases; falling back to default next-step routing`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
recordWorkflowRoutingEvent(completedTask.id, deps, currentStep,
|
|
342
|
+
`workflow "${workflow.id}" step ${context.stepKey} completed${conclusion ? ` with conclusion 「${conclusion}」` : ""} -> ${
|
|
343
|
+
nextStep ? `step ${nextStepKey} (${nextStep.title}, role ${nextStep.role})` : "chain end"}`);
|
|
344
|
+
|
|
345
|
+
if (!nextStep) {
|
|
346
|
+
logger.info(`Workflow: run ${context.runId} of "${workflow.id}" completed (no next step after ${context.stepKey})`);
|
|
347
|
+
return undefined;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 3. Create the follow-up step task with upstream outputs + return reason.
|
|
351
|
+
const runTasks = tasksOfWorkflowRun(deps.getTeamState() ?? state, context.runId);
|
|
352
|
+
const completedRunTasks = runTasks.filter((task) => task.status === "completed" || task.id === completedTask.id);
|
|
353
|
+
const description = buildStepDescription({
|
|
354
|
+
workflow,
|
|
355
|
+
step: nextStep,
|
|
356
|
+
upstreamSection: buildUpstreamInputsSection(nextStep, workflow, completedRunTasks),
|
|
357
|
+
returnSection: isReturnEdge ? buildReturnReasonSection(state.tasks[completedTask.id] ?? completedTask) : undefined,
|
|
358
|
+
});
|
|
359
|
+
const nextTask = await createWorkflowStepTask({
|
|
360
|
+
workflow,
|
|
361
|
+
step: nextStep,
|
|
362
|
+
runId: context.runId,
|
|
363
|
+
description,
|
|
364
|
+
visitCounts,
|
|
365
|
+
}, deps);
|
|
366
|
+
if (!nextTask) {
|
|
367
|
+
logger.error(`Workflow: failed to create follow-up task for run ${context.runId} of "${workflow.id}" (step ${nextStepKey})`);
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
logger.info(
|
|
371
|
+
`Workflow: run ${context.runId} of "${workflow.id}" routed step ${context.stepKey} -> ${nextStepKey} as task ${nextTask.id}`,
|
|
372
|
+
);
|
|
373
|
+
return nextTask;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function recordWorkflowRoutingEvent(
|
|
377
|
+
taskId: string,
|
|
378
|
+
deps: ControllerTaskDomainDeps,
|
|
379
|
+
step: TeamProfileWorkflowStep,
|
|
380
|
+
message: string,
|
|
381
|
+
): void {
|
|
382
|
+
recordTaskExecutionEvent(taskId, {
|
|
383
|
+
type: "lifecycle",
|
|
384
|
+
phase: "workflow_step_routed",
|
|
385
|
+
source: "controller",
|
|
386
|
+
status: "running",
|
|
387
|
+
message,
|
|
388
|
+
role: step.role,
|
|
389
|
+
}, deps);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
// POST /api/v1/workflows/{id}/start - kick off a workflow run.
|
|
394
|
+
// ---------------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Extracts the workflow id from /api/v1/workflows/{id}/start. Returns ""
|
|
398
|
+
* for a malformed id (the route regex already guarantees the segment shape;
|
|
399
|
+
* percent-decode failures degrade to "" -> the 404 path, never a 500).
|
|
400
|
+
*/
|
|
401
|
+
function workflowIdFromPathname(pathname: string): string {
|
|
402
|
+
const match = pathname.match(/^\/api\/v1\/workflows\/([^/]+)\/start$/);
|
|
403
|
+
const raw = match?.[1];
|
|
404
|
+
if (!raw) {
|
|
405
|
+
return "";
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
return decodeURIComponent(raw);
|
|
409
|
+
} catch {
|
|
410
|
+
return "";
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export async function workflowStartRoute(ctx: RouteContext): Promise<void> {
|
|
415
|
+
const { req, res, deps, pathname, currentState } = ctx;
|
|
416
|
+
const { logger } = deps;
|
|
417
|
+
|
|
418
|
+
// Transition matrix (design 2.3): starting a workflow spawns new work for
|
|
419
|
+
// the outgoing team, same as POST /api/v1/tasks. The dispatch-layer gate
|
|
420
|
+
// in http-server.ts enumerates the historical task-submission paths, so
|
|
421
|
+
// this handler enforces the same 503 + Retry-After contract for its own
|
|
422
|
+
// route (handler-level enforcement keeps the gate list untouched).
|
|
423
|
+
if (currentState?.transition) {
|
|
424
|
+
res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
|
|
425
|
+
sendJson(res, 503, {
|
|
426
|
+
error: `Team profile switch to "${currentState.transition.targetProfileId}" is in progress (phase: ${currentState.transition.phase}); workflow start is temporarily unavailable - retry after the switch completes`,
|
|
427
|
+
retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
|
|
428
|
+
transition: { phase: currentState.transition.phase, targetProfileId: currentState.transition.targetProfileId },
|
|
429
|
+
});
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const workflowId = workflowIdFromPathname(pathname);
|
|
434
|
+
const workflows = getActiveWorkflows();
|
|
435
|
+
const workflow = workflows.find((entry) => entry.id === workflowId);
|
|
436
|
+
if (!workflow) {
|
|
437
|
+
sendError(
|
|
438
|
+
res,
|
|
439
|
+
404,
|
|
440
|
+
`unknown workflow "${workflowId || "<empty>"}" for the active profile (available: ${
|
|
441
|
+
workflows.map((entry) => entry.id).sort().join(", ") || "none"
|
|
442
|
+
})`,
|
|
443
|
+
);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (!deps.getTeamState()) {
|
|
448
|
+
sendError(res, 503, "Team state not loaded");
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
let body: Record<string, unknown>;
|
|
453
|
+
try {
|
|
454
|
+
body = await parseJsonBody(req);
|
|
455
|
+
} catch (error) {
|
|
456
|
+
// #251 L6: a malformed request body is a client error (400), not a
|
|
457
|
+
// top-level 500 - parseJsonBody throws "Invalid JSON body: ...".
|
|
458
|
+
sendError(res, 400, error instanceof Error ? error.message : "invalid JSON body");
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (body.context !== undefined && typeof body.context !== "string") {
|
|
462
|
+
sendError(res, 400, "body field \"context\" must be a string when provided (initial business context for the first step)");
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const initialContext = typeof body.context === "string" ? body.context.trim() : "";
|
|
466
|
+
|
|
467
|
+
// Design 2.4 "按 steps 建任务链": the run starts at the FIRST declared
|
|
468
|
+
// step (the numeric spine root), not at the lowest id - template order is
|
|
469
|
+
// authoritative and load validation guarantees a non-empty steps array.
|
|
470
|
+
const firstStep = workflow.steps[0]!;
|
|
471
|
+
const runId = generateId();
|
|
472
|
+
const description = buildStepDescription({
|
|
473
|
+
workflow,
|
|
474
|
+
step: firstStep,
|
|
475
|
+
initialContext: initialContext || undefined,
|
|
476
|
+
upstreamSection: buildUpstreamInputsSection(firstStep, workflow, []),
|
|
477
|
+
});
|
|
478
|
+
const task = await createWorkflowStepTask({
|
|
479
|
+
workflow,
|
|
480
|
+
step: firstStep,
|
|
481
|
+
runId,
|
|
482
|
+
description,
|
|
483
|
+
visitCounts: { [stepKeyOf(firstStep.id)]: 1 },
|
|
484
|
+
}, deps);
|
|
485
|
+
if (!task) {
|
|
486
|
+
sendError(res, 500, `failed to create the first task of workflow "${workflowId}"`);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
logger.info(`Workflow: started run ${runId} of "${workflow.id}" at step ${stepKeyOf(firstStep.id)} (task ${task.id})`);
|
|
490
|
+
sendJson(res, 201, {
|
|
491
|
+
workflowId: workflow.id,
|
|
492
|
+
workflowName: workflow.name,
|
|
493
|
+
runId,
|
|
494
|
+
stepCount: workflow.steps.length,
|
|
495
|
+
step: { id: firstStep.id, role: firstStep.role, title: firstStep.title },
|
|
496
|
+
task: serializeTask(task),
|
|
497
|
+
});
|
|
498
|
+
}
|