@teamclaws/teamclaw 2026.11.0 → 2026.11.2

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 (128) hide show
  1. package/cli.mjs +368 -13
  2. package/dist/index.js +61 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/config-routes.js +138 -0
  7. package/dist/src/controller/controller-planning.js +1 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-service.js +67 -10
  10. package/dist/src/controller/controller-tools.js +3 -1
  11. package/dist/src/controller/github-auth.js +2 -1
  12. package/dist/src/controller/http-server.js +51 -16
  13. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  14. package/dist/src/controller/message-delivery.js +4 -1
  15. package/dist/src/controller/orchestration-manifest.js +5 -65
  16. package/dist/src/controller/preview-manager.js +51 -3
  17. package/dist/src/controller/profile-switch.js +42 -22
  18. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  19. package/dist/src/controller/provisioning/container-shared.js +64 -0
  20. package/dist/src/controller/provisioning/docker.js +214 -0
  21. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  22. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  23. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  24. package/dist/src/controller/provisioning-config.js +239 -0
  25. package/dist/src/controller/repo-routes.js +70 -4
  26. package/dist/src/controller/report-routes.js +56 -0
  27. package/dist/src/controller/route-table.js +73 -1045
  28. package/dist/src/controller/security.js +775 -0
  29. package/dist/src/controller/status-routes.js +287 -0
  30. package/dist/src/controller/task-assignment.js +5 -2
  31. package/dist/src/controller/task-execution.js +31 -0
  32. package/dist/src/controller/task-results.js +10 -0
  33. package/dist/src/controller/tunnel-manager.js +41 -8
  34. package/dist/src/controller/tunnel-routes.js +225 -0
  35. package/dist/src/controller/websocket.js +6 -2
  36. package/dist/src/controller/webui-routes.js +49 -0
  37. package/dist/src/controller/worker-provisioning.js +39 -949
  38. package/dist/src/controller/workflow-routes.js +407 -0
  39. package/dist/src/controller/workspace-routes.js +200 -0
  40. package/dist/src/git-collaboration.js +4 -9
  41. package/dist/src/identity.js +12 -1
  42. package/dist/src/openclaw-workspace.js +36 -0
  43. package/dist/src/profile-loader.js +119 -1
  44. package/dist/src/profiles/banking.json +26 -2
  45. package/dist/src/profiles/schema.json +82 -2
  46. package/dist/src/prompt-policy.js +18 -6
  47. package/dist/src/protocol.js +66 -3
  48. package/dist/src/shared/clarification-schema.js +65 -0
  49. package/dist/src/shared/github-auth.js +15 -0
  50. package/dist/src/shared/kickoff-prompt.js +37 -0
  51. package/dist/src/shared/utils.js +47 -0
  52. package/dist/src/state.js +89 -3
  53. package/dist/src/teamauto/scanner.js +21 -2
  54. package/dist/src/teamauto/scheduler.js +9 -2
  55. package/dist/src/types.js +15 -1
  56. package/dist/src/ui/app.js +990 -73
  57. package/dist/src/ui/github-login.html +1 -0
  58. package/dist/src/ui/index.html +125 -36
  59. package/dist/src/worker/http-handler.js +59 -0
  60. package/dist/src/worker/skill-installer.js +3 -9
  61. package/dist/src/worker/tools.js +20 -10
  62. package/dist/src/worker/worker-service.js +17 -4
  63. package/index.ts +69 -32
  64. package/openclaw.plugin.json +23 -2
  65. package/package.json +1 -1
  66. package/src/config.ts +24 -0
  67. package/src/controller/auth-routes.ts +157 -0
  68. package/src/controller/clarification-routes.ts +1 -1
  69. package/src/controller/config-routes.ts +152 -0
  70. package/src/controller/controller-planning.ts +8 -0
  71. package/src/controller/controller-routes.ts +237 -0
  72. package/src/controller/controller-service.ts +128 -10
  73. package/src/controller/controller-tools.ts +5 -2
  74. package/src/controller/github-auth.ts +28 -63
  75. package/src/controller/http-server.ts +66 -17
  76. package/src/controller/kickoff-orchestrator.ts +3 -42
  77. package/src/controller/message-delivery.ts +4 -1
  78. package/src/controller/orchestration-manifest.ts +8 -71
  79. package/src/controller/preview-manager.ts +53 -3
  80. package/src/controller/profile-switch.ts +53 -23
  81. package/src/controller/provisioning/backend-contract.ts +51 -0
  82. package/src/controller/provisioning/container-shared.ts +84 -0
  83. package/src/controller/provisioning/docker.ts +260 -0
  84. package/src/controller/provisioning/kubernetes.ts +263 -0
  85. package/src/controller/provisioning/plugin-root.ts +42 -0
  86. package/src/controller/provisioning/process-supervisor.ts +214 -0
  87. package/src/controller/provisioning-config.ts +289 -0
  88. package/src/controller/repo-routes.ts +84 -12
  89. package/src/controller/report-routes.ts +64 -0
  90. package/src/controller/route-table.ts +139 -1152
  91. package/src/controller/security.ts +899 -0
  92. package/src/controller/status-routes.ts +354 -0
  93. package/src/controller/task-assignment.ts +5 -1
  94. package/src/controller/task-execution.ts +43 -0
  95. package/src/controller/task-results.ts +12 -0
  96. package/src/controller/tunnel-manager.ts +45 -8
  97. package/src/controller/tunnel-routes.ts +231 -0
  98. package/src/controller/websocket.ts +20 -3
  99. package/src/controller/webui-routes.ts +55 -0
  100. package/src/controller/worker-provisioning.ts +51 -1117
  101. package/src/controller/workflow-routes.ts +498 -0
  102. package/src/controller/workspace-routes.ts +222 -0
  103. package/src/git-collaboration.ts +4 -9
  104. package/src/identity.ts +13 -1
  105. package/src/openclaw-workspace.ts +47 -0
  106. package/src/profile-loader.ts +167 -1
  107. package/src/profiles/banking.json +26 -2
  108. package/src/profiles/schema.json +82 -2
  109. package/src/prompt-policy.ts +19 -6
  110. package/src/protocol.ts +72 -2
  111. package/src/shared/clarification-schema.ts +81 -0
  112. package/src/shared/github-auth.ts +92 -0
  113. package/src/shared/kickoff-prompt.ts +47 -0
  114. package/src/shared/utils.ts +51 -0
  115. package/src/state.ts +92 -3
  116. package/src/teamauto/github-client.ts +2 -1
  117. package/src/teamauto/repo-sync.ts +2 -1
  118. package/src/teamauto/scanner.ts +22 -3
  119. package/src/teamauto/scheduler.ts +11 -3
  120. package/src/teamauto/store.ts +5 -0
  121. package/src/types.ts +130 -1
  122. package/src/ui/app.js +990 -73
  123. package/src/ui/github-login.html +1 -0
  124. package/src/ui/index.html +125 -36
  125. package/src/worker/http-handler.ts +64 -1
  126. package/src/worker/skill-installer.ts +3 -9
  127. package/src/worker/tools.ts +21 -10
  128. package/src/worker/worker-service.ts +18 -4
@@ -0,0 +1,407 @@
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
+ import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
30
+ import { getActiveWorkflows } from "../profile-loader.js";
31
+ import { recordTaskExecutionEvent, serializeTask } from "./task-execution.js";
32
+ import { createControllerManagedTask } from "./controller-planning.js";
33
+ import { SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS } from "./controller-routes.js";
34
+ /** createdBy stamp for workflow-engine tasks (skips the controller LLM follow-up path). */
35
+ const WORKFLOW_TASK_CREATED_BY = "workflow";
36
+ /** Return-edge loop guard: a step may be (re)entered at most this many times per run. */
37
+ export const MAX_WORKFLOW_STEP_VISITS = 3;
38
+ /** Upstream result excerpt cap when embedding outputs into a step description. */
39
+ const UPSTREAM_RESULT_EXCERPT_CHARS = 4000;
40
+ // ---------------------------------------------------------------------------
41
+ // Template helpers.
42
+ // ---------------------------------------------------------------------------
43
+ function stepKeyOf(stepId) {
44
+ return String(stepId);
45
+ }
46
+ function isBranchStep(step) {
47
+ return typeof step.id === "string";
48
+ }
49
+ function findStep(workflow, stepKey) {
50
+ return workflow.steps.find((step) => stepKeyOf(step.id) === stepKey);
51
+ }
52
+ /**
53
+ * Default "next" resolution (design 2.4: on-values may be "next" or a step
54
+ * id; conclusions without an explicit on-mapping fall through to next):
55
+ * advance along the NUMERIC spine to the smallest numeric step id greater
56
+ * than the current one. Branch steps (string ids like "committee") are never
57
+ * a default next - they are reachable only through an explicit on jump, so
58
+ * e.g. the within-mandate approval (step 2) ends the run instead of leaking
59
+ * into the committee step declared after it.
60
+ */
61
+ function defaultNextStep(workflow, current) {
62
+ if (isBranchStep(current)) {
63
+ return undefined;
64
+ }
65
+ return workflow.steps
66
+ .filter((step) => !isBranchStep(step) && step.id > current.id)
67
+ .sort((a, b) => a.id - b.id)[0];
68
+ }
69
+ /**
70
+ * Longest-phrase-wins includes match of the step's conclusion enum against
71
+ * the completed task's evidence text (result + result contract summary /
72
+ * key points / notes). Longest-first prevents a prefix phrase (「通过」 inside
73
+ * 「未通过」-style collisions, 「补充材料」 inside 「退回补充材料」) from
74
+ * shadowing the specific phrase.
75
+ */
76
+ export function matchStepConclusion(step, evidenceText) {
77
+ const conclusions = step.conclusion ?? [];
78
+ if (conclusions.length === 0 || !evidenceText) {
79
+ return undefined;
80
+ }
81
+ return [...conclusions].sort((a, b) => b.length - a.length).find((phrase) => evidenceText.includes(phrase));
82
+ }
83
+ function collectResultEvidence(task) {
84
+ const contract = task.resultContract;
85
+ return [
86
+ task.result ?? "",
87
+ contract?.summary ?? "",
88
+ contract?.notes ?? "",
89
+ ...(contract?.keyPoints ?? []),
90
+ ].join("\n");
91
+ }
92
+ // ---------------------------------------------------------------------------
93
+ // Task description assembly.
94
+ // ---------------------------------------------------------------------------
95
+ function conclusionInstruction(step) {
96
+ const conclusions = step.conclusion ?? [];
97
+ if (conclusions.length === 0) {
98
+ return "";
99
+ }
100
+ return `结论要求:请在交付物结尾单独一行明确给出以下结论短语之一(工作流引擎按该短语路由下一步):${conclusions.map((phrase) => `「${phrase}」`).join(" / ")}`;
101
+ }
102
+ function truncateExcerpt(text, limit = UPSTREAM_RESULT_EXCERPT_CHARS) {
103
+ const normalized = text.trim();
104
+ if (normalized.length <= limit) {
105
+ return normalized;
106
+ }
107
+ return `${normalized.slice(0, limit).trimEnd()}\n…(上游结果过长,已截断,完整内容见原任务)`;
108
+ }
109
+ /**
110
+ * Design 2.4 outputKey passing: for every inputs[] key of the target step,
111
+ * embed the latest completed result of the step that declares that output.
112
+ */
113
+ function buildUpstreamInputsSection(targetStep, workflow, completedTasks) {
114
+ const inputKeys = targetStep.inputs ?? [];
115
+ if (inputKeys.length === 0) {
116
+ return "";
117
+ }
118
+ const lines = [];
119
+ for (const inputKey of inputKeys) {
120
+ const declaringStep = workflow.steps.find((step) => (step.outputs ?? []).some((output) => output.key === inputKey));
121
+ if (!declaringStep) {
122
+ continue; // impossible after load validation (dangling input is fatal); belt-and-braces
123
+ }
124
+ const output = (declaringStep.outputs ?? []).find((entry) => entry.key === inputKey);
125
+ const sourceTask = completedTasks
126
+ .filter((task) => task.workflow?.stepKey === stepKeyOf(declaringStep.id))
127
+ .sort((a, b) => (b.completedAt ?? b.updatedAt) - (a.completedAt ?? a.updatedAt))[0];
128
+ if (sourceTask) {
129
+ lines.push(`【上游产出 ${output.key}(${output.name},来自任务 ${sourceTask.id}:${declaringStep.title})】`, truncateExcerpt(sourceTask.result ?? sourceTask.resultContract?.summary ?? "(上游任务未记录文本结果)"), "");
130
+ }
131
+ else {
132
+ lines.push(`【上游产出 ${output.key}(${output.name})】尚未生成:请先向 controller 申请 ${declaringStep.title} 的产出。`, "");
133
+ }
134
+ }
135
+ return lines.join("\n").trim();
136
+ }
137
+ function buildReturnReasonSection(returningTask) {
138
+ return [
139
+ `【退回意见(来自 ${returningTask.title},任务 ${returningTask.id} 的结论与要点)】`,
140
+ truncateExcerpt(collectResultEvidence(returningTask)),
141
+ ].join("\n");
142
+ }
143
+ // ---------------------------------------------------------------------------
144
+ // Run helpers.
145
+ // ---------------------------------------------------------------------------
146
+ function tasksOfWorkflowRun(state, runId) {
147
+ return Object.values(state.tasks).filter((task) => task.workflow?.runId === runId);
148
+ }
149
+ function visitCountsIncluding(context, stepKey) {
150
+ const counts = { ...(context.visitCounts ?? {}) };
151
+ counts[stepKey] = (counts[stepKey] ?? 0) + 1;
152
+ return counts;
153
+ }
154
+ async function createWorkflowStepTask(input, deps) {
155
+ const { workflow, step } = input;
156
+ const workflowContext = {
157
+ workflowId: workflow.id,
158
+ runId: input.runId,
159
+ stepKey: stepKeyOf(step.id),
160
+ visitCounts: input.visitCounts,
161
+ };
162
+ return createControllerManagedTask({
163
+ title: step.title,
164
+ description: input.description,
165
+ assignedRole: step.role,
166
+ createdBy: WORKFLOW_TASK_CREATED_BY,
167
+ projectName: `workflow-${workflow.id}`,
168
+ recommendedSkills: [],
169
+ workflow: workflowContext,
170
+ }, deps);
171
+ }
172
+ function buildStepDescription(input) {
173
+ const { workflow, step } = input;
174
+ const parts = [
175
+ `【工作流】${workflow.name}(workflow id: ${workflow.id})— 当前步骤:${step.title}`,
176
+ step.description ?? "",
177
+ ];
178
+ if (input.initialContext?.trim()) {
179
+ parts.push(`【业务背景 / 初始材料】\n${input.initialContext.trim()}`);
180
+ }
181
+ if (input.returnSection) {
182
+ parts.push(input.returnSection);
183
+ }
184
+ if (input.upstreamSection) {
185
+ parts.push(`【上游交付(本步骤的输入)】\n${input.upstreamSection}`);
186
+ }
187
+ const instruction = conclusionInstruction(step);
188
+ if (instruction) {
189
+ parts.push(instruction);
190
+ }
191
+ return parts.filter((entry) => entry.trim().length > 0).join("\n\n");
192
+ }
193
+ // ---------------------------------------------------------------------------
194
+ // Completion routing (the design's "controller 按 conclusion 路由", minimal
195
+ // viable: deterministic phrase matching on the result evidence, no LLM pass).
196
+ // ---------------------------------------------------------------------------
197
+ export async function continueWorkflowAfterTaskCompletion(completedTask, deps) {
198
+ const context = completedTask.workflow;
199
+ if (!context) {
200
+ return undefined;
201
+ }
202
+ const { logger } = deps;
203
+ const state = deps.getTeamState();
204
+ if (!state || !state.tasks[completedTask.id]) {
205
+ return undefined;
206
+ }
207
+ const workflow = getActiveWorkflows().find((entry) => entry.id === context.workflowId);
208
+ if (!workflow) {
209
+ logger.warn(`Workflow: task ${completedTask.id} references workflow "${context.workflowId}" which the active profile does not carry - chain stops`);
210
+ return undefined;
211
+ }
212
+ const currentStep = findStep(workflow, context.stepKey);
213
+ if (!currentStep) {
214
+ logger.warn(`Workflow: task ${completedTask.id} references step "${context.stepKey}" of "${workflow.id}" which no longer exists - chain stops`);
215
+ return undefined;
216
+ }
217
+ // 1. Decide the next step from the conclusion evidence (pure, no state).
218
+ const evidence = collectResultEvidence(state.tasks[completedTask.id] ?? completedTask);
219
+ const conclusion = matchStepConclusion(currentStep, evidence);
220
+ const explicitTarget = conclusion !== undefined ? currentStep.on?.[conclusion] : undefined;
221
+ let nextStep;
222
+ if (explicitTarget !== undefined && explicitTarget !== "next") {
223
+ nextStep = findStep(workflow, stepKeyOf(explicitTarget));
224
+ }
225
+ else {
226
+ // No conclusion enum, no matching phrase (documented fallback), or an
227
+ // explicit "next": advance along the numeric spine.
228
+ nextStep = defaultNextStep(workflow, currentStep);
229
+ }
230
+ const nextStepKey = nextStep ? stepKeyOf(nextStep.id) : "";
231
+ const isReturnEdge = typeof nextStep?.id === "number"
232
+ && typeof currentStep.id === "number"
233
+ && nextStep.id <= currentStep.id;
234
+ // 2. Once-only routing latch + loop guard, set atomically in one state
235
+ // mutation (no await between latch and task creation, so concurrent
236
+ // completions cannot double-spawn the follow-up task). routedToStepKey
237
+ // records where the chain ACTUALLY went: the follow-up step key, or ""
238
+ // when the run ends (leaf completion or the guard refusing a return edge).
239
+ let alreadyRouted = false;
240
+ let loopGuardTripped = false;
241
+ let visitCounts = context.visitCounts ?? {};
242
+ deps.updateTeamState((s) => {
243
+ const task = s.tasks[completedTask.id];
244
+ if (!task?.workflow) {
245
+ alreadyRouted = true;
246
+ return;
247
+ }
248
+ if (task.workflow.routedToStepKey !== undefined) {
249
+ alreadyRouted = true;
250
+ return;
251
+ }
252
+ if (nextStep && (context.visitCounts?.[nextStepKey] ?? 0) + 1 > MAX_WORKFLOW_STEP_VISITS) {
253
+ loopGuardTripped = true;
254
+ }
255
+ task.workflow.routedToStepKey = loopGuardTripped ? "" : nextStepKey;
256
+ task.workflow.routedAt = Date.now();
257
+ task.workflow.routedConclusion = conclusion;
258
+ if (!loopGuardTripped) {
259
+ task.workflow.visitCounts = visitCountsIncluding(context, nextStepKey);
260
+ visitCounts = task.workflow.visitCounts;
261
+ }
262
+ });
263
+ if (alreadyRouted) {
264
+ return undefined;
265
+ }
266
+ if (loopGuardTripped) {
267
+ recordWorkflowRoutingEvent(completedTask.id, deps, currentStep, `workflow "${workflow.id}" stopped: step "${nextStepKey}" would exceed ${MAX_WORKFLOW_STEP_VISITS} visits (return-edge loop guard)`);
268
+ logger.warn(`Workflow: run ${context.runId} of "${workflow.id}" stopped at step ${context.stepKey} - step "${nextStepKey}" exceeded the ${MAX_WORKFLOW_STEP_VISITS}-visit loop guard`);
269
+ return undefined;
270
+ }
271
+ if (conclusion === undefined && (currentStep.conclusion ?? []).length > 0) {
272
+ logger.warn(`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`);
273
+ }
274
+ recordWorkflowRoutingEvent(completedTask.id, deps, currentStep, `workflow "${workflow.id}" step ${context.stepKey} completed${conclusion ? ` with conclusion 「${conclusion}」` : ""} -> ${nextStep ? `step ${nextStepKey} (${nextStep.title}, role ${nextStep.role})` : "chain end"}`);
275
+ if (!nextStep) {
276
+ logger.info(`Workflow: run ${context.runId} of "${workflow.id}" completed (no next step after ${context.stepKey})`);
277
+ return undefined;
278
+ }
279
+ // 3. Create the follow-up step task with upstream outputs + return reason.
280
+ const runTasks = tasksOfWorkflowRun(deps.getTeamState() ?? state, context.runId);
281
+ const completedRunTasks = runTasks.filter((task) => task.status === "completed" || task.id === completedTask.id);
282
+ const description = buildStepDescription({
283
+ workflow,
284
+ step: nextStep,
285
+ upstreamSection: buildUpstreamInputsSection(nextStep, workflow, completedRunTasks),
286
+ returnSection: isReturnEdge ? buildReturnReasonSection(state.tasks[completedTask.id] ?? completedTask) : undefined,
287
+ });
288
+ const nextTask = await createWorkflowStepTask({
289
+ workflow,
290
+ step: nextStep,
291
+ runId: context.runId,
292
+ description,
293
+ visitCounts,
294
+ }, deps);
295
+ if (!nextTask) {
296
+ logger.error(`Workflow: failed to create follow-up task for run ${context.runId} of "${workflow.id}" (step ${nextStepKey})`);
297
+ return undefined;
298
+ }
299
+ logger.info(`Workflow: run ${context.runId} of "${workflow.id}" routed step ${context.stepKey} -> ${nextStepKey} as task ${nextTask.id}`);
300
+ return nextTask;
301
+ }
302
+ function recordWorkflowRoutingEvent(taskId, deps, step, message) {
303
+ recordTaskExecutionEvent(taskId, {
304
+ type: "lifecycle",
305
+ phase: "workflow_step_routed",
306
+ source: "controller",
307
+ status: "running",
308
+ message,
309
+ role: step.role,
310
+ }, deps);
311
+ }
312
+ // ---------------------------------------------------------------------------
313
+ // POST /api/v1/workflows/{id}/start - kick off a workflow run.
314
+ // ---------------------------------------------------------------------------
315
+ /**
316
+ * Extracts the workflow id from /api/v1/workflows/{id}/start. Returns ""
317
+ * for a malformed id (the route regex already guarantees the segment shape;
318
+ * percent-decode failures degrade to "" -> the 404 path, never a 500).
319
+ */
320
+ function workflowIdFromPathname(pathname) {
321
+ const match = pathname.match(/^\/api\/v1\/workflows\/([^/]+)\/start$/);
322
+ const raw = match?.[1];
323
+ if (!raw) {
324
+ return "";
325
+ }
326
+ try {
327
+ return decodeURIComponent(raw);
328
+ }
329
+ catch {
330
+ return "";
331
+ }
332
+ }
333
+ export async function workflowStartRoute(ctx) {
334
+ const { req, res, deps, pathname, currentState } = ctx;
335
+ const { logger } = deps;
336
+ // Transition matrix (design 2.3): starting a workflow spawns new work for
337
+ // the outgoing team, same as POST /api/v1/tasks. The dispatch-layer gate
338
+ // in http-server.ts enumerates the historical task-submission paths, so
339
+ // this handler enforces the same 503 + Retry-After contract for its own
340
+ // route (handler-level enforcement keeps the gate list untouched).
341
+ if (currentState?.transition) {
342
+ res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
343
+ sendJson(res, 503, {
344
+ 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`,
345
+ retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
346
+ transition: { phase: currentState.transition.phase, targetProfileId: currentState.transition.targetProfileId },
347
+ });
348
+ return;
349
+ }
350
+ const workflowId = workflowIdFromPathname(pathname);
351
+ const workflows = getActiveWorkflows();
352
+ const workflow = workflows.find((entry) => entry.id === workflowId);
353
+ if (!workflow) {
354
+ sendError(res, 404, `unknown workflow "${workflowId || "<empty>"}" for the active profile (available: ${workflows.map((entry) => entry.id).sort().join(", ") || "none"})`);
355
+ return;
356
+ }
357
+ if (!deps.getTeamState()) {
358
+ sendError(res, 503, "Team state not loaded");
359
+ return;
360
+ }
361
+ let body;
362
+ try {
363
+ body = await parseJsonBody(req);
364
+ }
365
+ catch (error) {
366
+ // #251 L6: a malformed request body is a client error (400), not a
367
+ // top-level 500 - parseJsonBody throws "Invalid JSON body: ...".
368
+ sendError(res, 400, error instanceof Error ? error.message : "invalid JSON body");
369
+ return;
370
+ }
371
+ if (body.context !== undefined && typeof body.context !== "string") {
372
+ sendError(res, 400, "body field \"context\" must be a string when provided (initial business context for the first step)");
373
+ return;
374
+ }
375
+ const initialContext = typeof body.context === "string" ? body.context.trim() : "";
376
+ // Design 2.4 "按 steps 建任务链": the run starts at the FIRST declared
377
+ // step (the numeric spine root), not at the lowest id - template order is
378
+ // authoritative and load validation guarantees a non-empty steps array.
379
+ const firstStep = workflow.steps[0];
380
+ const runId = generateId();
381
+ const description = buildStepDescription({
382
+ workflow,
383
+ step: firstStep,
384
+ initialContext: initialContext || undefined,
385
+ upstreamSection: buildUpstreamInputsSection(firstStep, workflow, []),
386
+ });
387
+ const task = await createWorkflowStepTask({
388
+ workflow,
389
+ step: firstStep,
390
+ runId,
391
+ description,
392
+ visitCounts: { [stepKeyOf(firstStep.id)]: 1 },
393
+ }, deps);
394
+ if (!task) {
395
+ sendError(res, 500, `failed to create the first task of workflow "${workflowId}"`);
396
+ return;
397
+ }
398
+ logger.info(`Workflow: started run ${runId} of "${workflow.id}" at step ${stepKeyOf(firstStep.id)} (task ${task.id})`);
399
+ sendJson(res, 201, {
400
+ workflowId: workflow.id,
401
+ workflowName: workflow.name,
402
+ runId,
403
+ stepCount: workflow.steps.length,
404
+ step: { id: firstStep.id, role: firstStep.role, title: firstStep.title },
405
+ task: serializeTask(task),
406
+ });
407
+ }
@@ -0,0 +1,200 @@
1
+ // Issue #226 W2 (route-table carve-up): the workspace browser + model-config
2
+ // route handlers (plus their private error-mapping helpers) moved verbatim
3
+ // from route-table.ts (PR-D had moved them verbatim from http-server.ts
4
+ // before that) - bodies byte-identical, only the module home changed.
5
+ // route-table.ts keeps the table entries that bind these handlers. Like
6
+ // security.ts, this module imports route-table.js as TYPE ONLY
7
+ // (RouteContext), so the module graph stays acyclic.
8
+ import fs from "node:fs";
9
+ import { parseJsonBody, sendJson, sendError, pinnedCorsAllowOrigin } from "../protocol.js";
10
+ import { listWorkspaceTree, listWorkspaceSubtree, readWorkspaceFile, readWorkspaceRawFile } from "../workspace-browser.js";
11
+ import { teamClawWorkspaceIsDefault, updateTeamClawWorkspaceDir, getTeamClawModelCatalog, updateTeamClawModelConfig, resolveTeamClawWorkspaceDir, } from "../openclaw-workspace.js";
12
+ import { resolveSafeProjectDirectory } from "./task-cleanup.js";
13
+ function workspaceRequestErrorStatus(err) {
14
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
15
+ return 404;
16
+ }
17
+ return 400;
18
+ }
19
+ function workspaceRequestErrorMessage(err) {
20
+ return err instanceof Error ? err.message : "Workspace request failed";
21
+ }
22
+ function workspaceStatusRoute(ctx) {
23
+ const { res } = ctx;
24
+ sendJson(res, 200, {
25
+ workspaceDir: resolveTeamClawWorkspaceDir(),
26
+ isDefault: teamClawWorkspaceIsDefault(),
27
+ });
28
+ }
29
+ async function workspaceChangeDirRoute(ctx) {
30
+ const { req, res, deps } = ctx;
31
+ let body;
32
+ try {
33
+ body = await parseJsonBody(req);
34
+ }
35
+ catch {
36
+ sendError(res, 400, "invalid JSON body");
37
+ return;
38
+ }
39
+ const workspaceDir = typeof body?.workspaceDir === "string"
40
+ ? body.workspaceDir
41
+ : "";
42
+ if (!workspaceDir.trim()) {
43
+ sendError(res, 400, "workspaceDir is required");
44
+ return;
45
+ }
46
+ try {
47
+ const result = await updateTeamClawWorkspaceDir(workspaceDir, {
48
+ warn: (message) => deps.logger.info(message),
49
+ });
50
+ sendJson(res, 200, {
51
+ ok: true,
52
+ workspaceDir: result.agentEntryPath,
53
+ configPath: result.configPath,
54
+ restartRequired: true,
55
+ });
56
+ }
57
+ catch (err) {
58
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update workspace directory");
59
+ }
60
+ }
61
+ // GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
62
+ async function modelsConfigGetRoute(ctx) {
63
+ const { res } = ctx;
64
+ try {
65
+ sendJson(res, 200, await getTeamClawModelCatalog());
66
+ }
67
+ catch (err) {
68
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read model configuration");
69
+ }
70
+ }
71
+ // PUT /api/v1/models/config - persist default and per-role model selection
72
+ async function modelsConfigPutRoute(ctx) {
73
+ const { req, res, deps } = ctx;
74
+ let body = null;
75
+ try {
76
+ body = await parseJsonBody(req);
77
+ }
78
+ catch {
79
+ sendError(res, 400, "invalid JSON body");
80
+ return;
81
+ }
82
+ const update = {};
83
+ if (typeof body?.defaultModel === "string") {
84
+ update.defaultModel = body.defaultModel.trim();
85
+ }
86
+ if (body?.roleModelOverrides && typeof body.roleModelOverrides === "object" && !Array.isArray(body.roleModelOverrides)) {
87
+ const overrides = {};
88
+ for (const [role, value] of Object.entries(body.roleModelOverrides)) {
89
+ if (typeof value === "string" && value.trim()) {
90
+ overrides[role] = value.trim();
91
+ }
92
+ }
93
+ update.roleModelOverrides = overrides;
94
+ }
95
+ if (update.defaultModel === undefined && update.roleModelOverrides === undefined) {
96
+ sendError(res, 400, "defaultModel or roleModelOverrides is required");
97
+ return;
98
+ }
99
+ try {
100
+ await updateTeamClawModelConfig(update, {
101
+ warn: (message) => deps.logger.info(message),
102
+ });
103
+ sendJson(res, 200, {
104
+ ok: true,
105
+ restartNote: "Config changes hot-reload; restart the gateway (openclaw gateway restart) if a change does not take effect.",
106
+ catalog: await getTeamClawModelCatalog(),
107
+ });
108
+ }
109
+ catch (err) {
110
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update model configuration");
111
+ }
112
+ }
113
+ async function workspaceTreeRoute(ctx) {
114
+ const { res, requestUrl } = ctx;
115
+ try {
116
+ // depth=N limits tree expansion (default 1 for lazy loading)
117
+ const depthParam = requestUrl.searchParams.get("depth");
118
+ const maxDepth = depthParam !== null ? Math.max(0, Math.min(parseInt(depthParam, 10) || 1, 8)) : 1;
119
+ sendJson(res, 200, await listWorkspaceTree(maxDepth));
120
+ }
121
+ catch (err) {
122
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
123
+ }
124
+ }
125
+ async function workspaceSubtreeRoute(ctx) {
126
+ const { res, requestUrl } = ctx;
127
+ const dirPath = requestUrl.searchParams.get("path") ?? "";
128
+ if (!dirPath) {
129
+ sendError(res, 400, "path is required");
130
+ return;
131
+ }
132
+ try {
133
+ sendJson(res, 200, { entries: await listWorkspaceSubtree(dirPath) });
134
+ }
135
+ catch (err) {
136
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
137
+ }
138
+ }
139
+ async function workspaceFileRoute(ctx) {
140
+ const { res, requestUrl } = ctx;
141
+ const relativePath = requestUrl.searchParams.get("path") ?? "";
142
+ if (!relativePath) {
143
+ sendError(res, 400, "path is required");
144
+ return;
145
+ }
146
+ try {
147
+ sendJson(res, 200, { file: await readWorkspaceFile(relativePath) });
148
+ }
149
+ catch (err) {
150
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
151
+ }
152
+ }
153
+ async function workspaceProjectPathRoute(ctx) {
154
+ const { res, requestUrl } = ctx;
155
+ const projectDir = requestUrl.searchParams.get("projectDir") ?? "";
156
+ if (!projectDir) {
157
+ sendError(res, 400, "projectDir is required");
158
+ return;
159
+ }
160
+ const absolutePath = resolveSafeProjectDirectory(projectDir);
161
+ if (!absolutePath) {
162
+ sendError(res, 400, "Invalid projectDir");
163
+ return;
164
+ }
165
+ if (!fs.existsSync(absolutePath)) {
166
+ sendError(res, 404, "Project directory not found");
167
+ return;
168
+ }
169
+ sendJson(res, 200, {
170
+ projectDir,
171
+ absolutePath,
172
+ });
173
+ }
174
+ async function workspaceRawFileRoute(ctx) {
175
+ const { res, pathname } = ctx;
176
+ const rawPathname = pathname.slice("/api/v1/workspace/raw/".length);
177
+ if (!rawPathname) {
178
+ sendError(res, 400, "path is required");
179
+ return;
180
+ }
181
+ try {
182
+ const relativePath = decodeURIComponent(rawPathname);
183
+ const file = await readWorkspaceRawFile(relativePath);
184
+ res.writeHead(200, {
185
+ "Content-Type": file.contentType,
186
+ "Cache-Control": "no-store",
187
+ // Issue #23 security review follow-up: honor a CORS origin the
188
+ // security gate pinned (device protection on) instead of hardcoding
189
+ // the wildcard, which silently widened it; unpinned keeps the
190
+ // historical "*" byte for byte (shared helper, see protocol.ts).
191
+ "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
192
+ "X-Content-Type-Options": "nosniff",
193
+ });
194
+ res.end(file.content);
195
+ }
196
+ catch (err) {
197
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
198
+ }
199
+ }
200
+ export { workspaceStatusRoute, workspaceChangeDirRoute, modelsConfigGetRoute, modelsConfigPutRoute, workspaceTreeRoute, workspaceSubtreeRoute, workspaceFileRoute, workspaceProjectPathRoute, workspaceRawFileRoute, };
@@ -3,6 +3,10 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { resolveTeamClawWorkspaceDir } from "./openclaw-workspace.js";
6
+ // W6 of issue #226: the local swallowing pathExists copy was removed; the
7
+ // alias keeps every call site byte-identical while the shared copy pins the
8
+ // exact original semantics (any fs.access error resolves false).
9
+ import { pathExistsTolerant as pathExists } from "./shared/utils.js";
6
10
  const TEAMCLAW_IMPORT_REF_PREFIX = "refs/teamclaw/imports";
7
11
  const BUNDLE_IMPORT_MAX_RETRIES = 3;
8
12
  const BUNDLE_IMPORT_RETRY_DELAY_MS = 2_000;
@@ -613,15 +617,6 @@ async function tryRebaseWorkerOntoController(workspaceDir, repoInfo, controllerU
613
617
  logger.warn(`Worker: rebase onto controller failed: ${err instanceof Error ? err.message : String(err)}; will retry bundle as-is.`);
614
618
  }
615
619
  }
616
- async function pathExists(filePath) {
617
- try {
618
- await fs.access(filePath);
619
- return true;
620
- }
621
- catch {
622
- return false;
623
- }
624
- }
625
620
  async function runGit(args, options) {
626
621
  const result = await runCommand("git", args, options);
627
622
  if (result.exitCode !== 0) {
@@ -4,6 +4,16 @@ import { generateId, createRegistrationRequest } from "./protocol.js";
4
4
  import { getActiveRole } from "./profile-loader.js";
5
5
  import { loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity } from "./state.js";
6
6
  import { MDnsBrowser } from "./discovery.js";
7
+ /**
8
+ * Issue #23 (client wave): headers for worker -> controller calls. While a
9
+ * paired device token is configured it rides the X-TeamClaw-Token header the
10
+ * controller's device gate accepts; without one the headers pass through
11
+ * unchanged (L0). The token value itself is never logged.
12
+ */
13
+ function withDeviceToken(config, headers) {
14
+ const token = config.securityToken?.trim();
15
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
16
+ }
7
17
  function getLocalIp(targetHost) {
8
18
  if (!targetHost || targetHost === "localhost" || targetHost === "127.0.0.1") {
9
19
  return "localhost";
@@ -90,7 +100,7 @@ export class IdentityManager {
90
100
  try {
91
101
  const res = await fetch(`${controllerUrl}/api/v1/workers/register`, {
92
102
  method: "POST",
93
- headers: { "Content-Type": "application/json" },
103
+ headers: withDeviceToken(this.config, { "Content-Type": "application/json" }),
94
104
  body: JSON.stringify(registration),
95
105
  });
96
106
  if (!res.ok) {
@@ -119,6 +129,7 @@ export class IdentityManager {
119
129
  try {
120
130
  await fetch(`${this.identity.controllerUrl}/api/v1/workers/${this.identity.workerId}`, {
121
131
  method: "DELETE",
132
+ headers: withDeviceToken(this.config, {}),
122
133
  });
123
134
  }
124
135
  catch {