@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,1113 @@
|
|
|
1
|
+
// PR-C of issue #204 (http-server monolith split): the controller intake
|
|
2
|
+
// orchestration - the serialized, retrying runControllerIntake funnel with
|
|
3
|
+
// its session-progress streaming, rate-limit/inactivity probes, the
|
|
4
|
+
// ControllerIntakeSwitchInProgressError entry gate, workflow continuation,
|
|
5
|
+
// and the controller-run clarification sync/reconcile - extracted verbatim
|
|
6
|
+
// from controller/http-server.ts. Zero behavior change. This module must
|
|
7
|
+
// NEVER import http-server (the reverse edge exists:
|
|
8
|
+
// http-server -> controller-intake); the planning helpers arrive from
|
|
9
|
+
// ./controller-planning.js and the kickoff handler stays late-bound through
|
|
10
|
+
// the deps slice.
|
|
11
|
+
import { normalizeSessionRole } from "../session-roles.js";
|
|
12
|
+
import type {
|
|
13
|
+
ClarificationRequest,
|
|
14
|
+
ControllerOrchestrationManifest,
|
|
15
|
+
ControllerRunInfo,
|
|
16
|
+
ControllerRunSource,
|
|
17
|
+
TaskInfo,
|
|
18
|
+
TeamState,
|
|
19
|
+
TeamSwitchTransition,
|
|
20
|
+
} from "../types.js";
|
|
21
|
+
import { generateId } from "../protocol.js";
|
|
22
|
+
import { createControllerPromptInjector } from "./prompt-injector.js";
|
|
23
|
+
import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
|
|
24
|
+
import {
|
|
25
|
+
appendControllerRunEvent,
|
|
26
|
+
createControllerRun,
|
|
27
|
+
recordControllerRunEvent,
|
|
28
|
+
updateControllerRun,
|
|
29
|
+
} from "./controller-runs.js";
|
|
30
|
+
import {
|
|
31
|
+
buildControllerFollowUpMessage,
|
|
32
|
+
buildControllerManifestReply,
|
|
33
|
+
collectTaskIds,
|
|
34
|
+
ensureControllerManifest,
|
|
35
|
+
maybeBackfillExecutionReadyTask,
|
|
36
|
+
maybeConvertControllerClarificationToExecutionTask,
|
|
37
|
+
reconcileControllerManifestTaskBindings,
|
|
38
|
+
resolveControllerWorkflowSessionKey,
|
|
39
|
+
tagControllerCreatedTasks,
|
|
40
|
+
} from "./controller-planning.js";
|
|
41
|
+
import { pruneStaleControllerRuns } from "./task-cleanup.js";
|
|
42
|
+
import type { ControllerTaskDomainDeps } from "./task-execution.js";
|
|
43
|
+
|
|
44
|
+
const CONTROLLER_RUN_WAIT_SLICE_MS = 30_000;
|
|
45
|
+
const CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT = 200;
|
|
46
|
+
const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
|
|
47
|
+
const TOOL_CALL_BLOCK_TYPES = new Set(["tool_use", "toolcall", "tool_call"]);
|
|
48
|
+
const TOOL_RESULT_BLOCK_TYPES = new Set(["tool_result", "tool_result_error"]);
|
|
49
|
+
|
|
50
|
+
const CONTROLLER_RATE_LIMIT_STALL_PROBE_MS = 5 * 60 * 1000;
|
|
51
|
+
const CONTROLLER_RATE_LIMIT_PROBE_TIMEOUT_MS = 60_000;
|
|
52
|
+
const CONTROLLER_INACTIVITY_PROBE_TIMEOUT_MS = 60_000;
|
|
53
|
+
const CONTROLLER_RATE_LIMIT_WAITING_SENTINEL = "TEAMCLAW_STILL_WAITING";
|
|
54
|
+
const CONTROLLER_INTAKE_MAX_RETRIES = 2;
|
|
55
|
+
const CONTROLLER_INTAKE_RETRY_DELAY_MS = 3_000;
|
|
56
|
+
const CONTROLLER_INTAKE_RETRYABLE_ERROR_PATTERN = /(500|502|503|server error|internal error|overloaded|unavailable)/i;
|
|
57
|
+
const controllerIntakeQueue = new Map<string, Promise<void>>();
|
|
58
|
+
|
|
59
|
+
export function buildControllerIntakeSystemPrompt(
|
|
60
|
+
deps: Pick<ControllerTaskDomainDeps, "config" | "getTeamState">,
|
|
61
|
+
): string {
|
|
62
|
+
const injector = createControllerPromptInjector({
|
|
63
|
+
config: deps.config,
|
|
64
|
+
getTeamState: deps.getTeamState,
|
|
65
|
+
});
|
|
66
|
+
return injector()?.prependSystemContext ?? "";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function extractLastAssistantText(messages: unknown[]): string {
|
|
70
|
+
const assistantMessages = messages.filter((message): message is { role?: unknown; content?: unknown } => {
|
|
71
|
+
if (!message || typeof message !== "object") {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
return (message as { role?: unknown }).role === "assistant";
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const lastAssistant = assistantMessages[assistantMessages.length - 1];
|
|
78
|
+
if (!lastAssistant) {
|
|
79
|
+
return "";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (typeof lastAssistant.content === "string") {
|
|
83
|
+
return lastAssistant.content;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (Array.isArray(lastAssistant.content)) {
|
|
87
|
+
const textBlocks = lastAssistant.content
|
|
88
|
+
.filter((block): block is { type?: unknown; text?: unknown } => {
|
|
89
|
+
return !!block && typeof block === "object" && (block as { type?: unknown }).type === "text";
|
|
90
|
+
})
|
|
91
|
+
.map((block) => (typeof block.text === "string" ? block.text : ""))
|
|
92
|
+
.filter(Boolean);
|
|
93
|
+
if (textBlocks.length > 0) {
|
|
94
|
+
return textBlocks.join("\n");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return JSON.stringify(lastAssistant);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
type SessionProgressEntry = {
|
|
102
|
+
fingerprint: string;
|
|
103
|
+
message: string;
|
|
104
|
+
phase: string;
|
|
105
|
+
stream: string;
|
|
106
|
+
isRateLimit: boolean;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export function normalizeBlockType(value: unknown): string {
|
|
110
|
+
if (typeof value !== "string") {
|
|
111
|
+
return "";
|
|
112
|
+
}
|
|
113
|
+
return value.trim().toLowerCase();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function truncateProgressMessage(value: string): string {
|
|
117
|
+
const trimmed = value.trim();
|
|
118
|
+
if (!trimmed) {
|
|
119
|
+
return "";
|
|
120
|
+
}
|
|
121
|
+
if (trimmed.length <= MAX_SESSION_PROGRESS_MESSAGE_CHARS) {
|
|
122
|
+
return trimmed;
|
|
123
|
+
}
|
|
124
|
+
return `${trimmed.slice(0, MAX_SESSION_PROGRESS_MESSAGE_CHARS)}\n… (truncated)`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function normalizeProgressComparableText(value: string): string {
|
|
128
|
+
return value.trim().replace(/\r\n/g, "\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function safeJsonStringify(value: unknown): string {
|
|
132
|
+
try {
|
|
133
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
134
|
+
} catch (_err) {
|
|
135
|
+
return String(value);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function renderSessionMessage(message: Record<string, unknown>, role: string): { message: string; stream: string } {
|
|
140
|
+
const content = message.content;
|
|
141
|
+
if (typeof content === "string") {
|
|
142
|
+
return {
|
|
143
|
+
message: truncateProgressMessage(content),
|
|
144
|
+
stream: role,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (Array.isArray(content)) {
|
|
149
|
+
const textParts: string[] = [];
|
|
150
|
+
const toolCalls: string[] = [];
|
|
151
|
+
let toolResultCount = 0;
|
|
152
|
+
let toolResultErrors = 0;
|
|
153
|
+
|
|
154
|
+
for (const entry of content) {
|
|
155
|
+
if (!entry || typeof entry !== "object") {
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const block = entry as Record<string, unknown>;
|
|
160
|
+
const type = normalizeBlockType(block.type);
|
|
161
|
+
if (type === "text") {
|
|
162
|
+
const text = typeof block.text === "string" ? block.text.trim() : "";
|
|
163
|
+
if (text) {
|
|
164
|
+
textParts.push(text);
|
|
165
|
+
}
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (TOOL_CALL_BLOCK_TYPES.has(type)) {
|
|
170
|
+
const name = typeof block.name === "string" ? block.name.trim() : "";
|
|
171
|
+
if (name) {
|
|
172
|
+
toolCalls.push(name);
|
|
173
|
+
}
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (TOOL_RESULT_BLOCK_TYPES.has(type)) {
|
|
178
|
+
toolResultCount += 1;
|
|
179
|
+
if (block.is_error === true) {
|
|
180
|
+
toolResultErrors += 1;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const parts: string[] = [];
|
|
186
|
+
if (textParts.length > 0) {
|
|
187
|
+
parts.push(textParts.join("\n"));
|
|
188
|
+
}
|
|
189
|
+
if (toolCalls.length > 0) {
|
|
190
|
+
parts.push(`[tool call] ${toolCalls.join(", ")}`);
|
|
191
|
+
}
|
|
192
|
+
if (toolResultCount > 0) {
|
|
193
|
+
parts.push(`[tool result] ${toolResultCount}${toolResultErrors > 0 ? ` (${toolResultErrors} error)` : ""}`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (parts.length > 0) {
|
|
197
|
+
return {
|
|
198
|
+
message: truncateProgressMessage(parts.join("\n")),
|
|
199
|
+
stream: textParts.length > 0 ? role : "tool",
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const fallbackToolName = typeof message.toolName === "string"
|
|
205
|
+
? message.toolName.trim()
|
|
206
|
+
: (typeof message.tool_name === "string" ? message.tool_name.trim() : "");
|
|
207
|
+
if (fallbackToolName) {
|
|
208
|
+
return {
|
|
209
|
+
message: `[tool call] ${fallbackToolName}`,
|
|
210
|
+
stream: "tool",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
message: truncateProgressMessage(safeJsonStringify(message)),
|
|
216
|
+
stream: role || "session",
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function buildSessionProgressEntries(messages: unknown[], controllerMessage: string): SessionProgressEntry[] {
|
|
221
|
+
const entries: SessionProgressEntry[] = [];
|
|
222
|
+
const normalizedControllerMessage = normalizeProgressComparableText(controllerMessage);
|
|
223
|
+
|
|
224
|
+
for (const rawMessage of messages) {
|
|
225
|
+
if (!rawMessage || typeof rawMessage !== "object") {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const message = rawMessage as Record<string, unknown>;
|
|
230
|
+
const role = normalizeSessionRole(message.role);
|
|
231
|
+
if (!role) {
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const rendered = renderSessionMessage(message, role);
|
|
236
|
+
if (!rendered.message) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const comparableMessage = normalizeProgressComparableText(rendered.message);
|
|
241
|
+
if (role === "user" && normalizedControllerMessage && comparableMessage.includes(normalizedControllerMessage)) {
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
entries.push({
|
|
246
|
+
fingerprint: `${rendered.stream}:${comparableMessage}`,
|
|
247
|
+
message: rendered.message,
|
|
248
|
+
phase: rendered.stream,
|
|
249
|
+
stream: rendered.stream,
|
|
250
|
+
isRateLimit: isRateLimitMessage(rendered.message),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return entries;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function getNewSessionProgressEntries(
|
|
258
|
+
entries: SessionProgressEntry[],
|
|
259
|
+
previousFingerprints: string[],
|
|
260
|
+
): SessionProgressEntry[] {
|
|
261
|
+
if (entries.length === 0) {
|
|
262
|
+
return [];
|
|
263
|
+
}
|
|
264
|
+
if (previousFingerprints.length === 0) {
|
|
265
|
+
return entries;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const currentFingerprints = entries.map((entry) => entry.fingerprint);
|
|
269
|
+
const maxOverlap = Math.min(previousFingerprints.length, currentFingerprints.length);
|
|
270
|
+
let overlap = 0;
|
|
271
|
+
|
|
272
|
+
for (let size = maxOverlap; size > 0; size -= 1) {
|
|
273
|
+
let matches = true;
|
|
274
|
+
for (let index = 0; index < size; index += 1) {
|
|
275
|
+
if (previousFingerprints[previousFingerprints.length - size + index] !== currentFingerprints[index]) {
|
|
276
|
+
matches = false;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (matches) {
|
|
281
|
+
overlap = size;
|
|
282
|
+
break;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return entries.slice(overlap);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function formatDuration(timeoutMs: number): string {
|
|
290
|
+
const totalSeconds = Math.ceil(timeoutMs / 1000);
|
|
291
|
+
if (totalSeconds % 3600 === 0) {
|
|
292
|
+
const hours = totalSeconds / 3600;
|
|
293
|
+
return `${hours} hour${hours === 1 ? "" : "s"}`;
|
|
294
|
+
}
|
|
295
|
+
if (totalSeconds % 60 === 0) {
|
|
296
|
+
const minutes = totalSeconds / 60;
|
|
297
|
+
return `${minutes} minute${minutes === 1 ? "" : "s"}`;
|
|
298
|
+
}
|
|
299
|
+
return `${totalSeconds} second${totalSeconds === 1 ? "" : "s"}`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function isRateLimitMessage(value: string): boolean {
|
|
303
|
+
return /(rate[_ ]limit|too many requests|429\b|resource has been exhausted|tokens per day|quota|throttl)/i.test(
|
|
304
|
+
String(value || ""),
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function isStillWaitingResponse(value: string): boolean {
|
|
309
|
+
return value.replace(/\s+/g, " ").trim() === CONTROLLER_RATE_LIMIT_WAITING_SENTINEL;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export async function withSerializedControllerIntake<T>(
|
|
313
|
+
sessionKey: string,
|
|
314
|
+
fn: () => Promise<T>,
|
|
315
|
+
): Promise<T> {
|
|
316
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
|
|
317
|
+
const previous = controllerIntakeQueue.get(normalizedSessionKey) ?? Promise.resolve();
|
|
318
|
+
let releaseCurrent!: () => void;
|
|
319
|
+
const current = new Promise<void>((resolve) => {
|
|
320
|
+
releaseCurrent = resolve;
|
|
321
|
+
});
|
|
322
|
+
controllerIntakeQueue.set(normalizedSessionKey, current);
|
|
323
|
+
try {
|
|
324
|
+
await previous;
|
|
325
|
+
return await fn();
|
|
326
|
+
} finally {
|
|
327
|
+
releaseCurrent();
|
|
328
|
+
if (controllerIntakeQueue.get(normalizedSessionKey) === current) {
|
|
329
|
+
controllerIntakeQueue.delete(normalizedSessionKey);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function normalizeComparableText(value: string): string {
|
|
335
|
+
return value
|
|
336
|
+
.toLowerCase()
|
|
337
|
+
.replace(/\s+/g, " ")
|
|
338
|
+
.trim();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function buildManifestClarificationEntries(
|
|
342
|
+
manifest: ControllerOrchestrationManifest,
|
|
343
|
+
): Array<{ question: string; questionSchema?: ClarificationRequest["questionSchema"] }> {
|
|
344
|
+
const opportunities = Array.isArray(manifest.completionOpportunities)
|
|
345
|
+
? manifest.completionOpportunities.filter((entry) => entry.title && entry.value && entry.summary)
|
|
346
|
+
: [];
|
|
347
|
+
const completionEntries = manifest.requirementFullyComplete && opportunities.length > 0
|
|
348
|
+
? [{
|
|
349
|
+
question: "Would you like TeamClaw to continue with one of these adjacent next steps?",
|
|
350
|
+
questionSchema: {
|
|
351
|
+
kind: "single-select" as const,
|
|
352
|
+
title: "What should TeamClaw do next?",
|
|
353
|
+
description: opportunities.map((entry) => `- ${entry.title}: ${entry.summary}`).join("\n"),
|
|
354
|
+
required: false,
|
|
355
|
+
options: opportunities.map((entry) => ({
|
|
356
|
+
value: entry.value,
|
|
357
|
+
label: entry.title,
|
|
358
|
+
hint: entry.summary,
|
|
359
|
+
})),
|
|
360
|
+
allowOther: true,
|
|
361
|
+
},
|
|
362
|
+
}]
|
|
363
|
+
: [];
|
|
364
|
+
const normalizedQuestions = manifest.clarificationQuestions
|
|
365
|
+
.map((entry) => String(entry || "").trim())
|
|
366
|
+
.filter(Boolean);
|
|
367
|
+
const schemas = Array.isArray(manifest.clarificationSchemas) ? manifest.clarificationSchemas : [];
|
|
368
|
+
if (schemas.length > 0) {
|
|
369
|
+
return [
|
|
370
|
+
...schemas.map((schema, index) => ({
|
|
371
|
+
question: normalizedQuestions[index] || schema.title,
|
|
372
|
+
questionSchema: schema,
|
|
373
|
+
})),
|
|
374
|
+
...completionEntries,
|
|
375
|
+
];
|
|
376
|
+
}
|
|
377
|
+
return [
|
|
378
|
+
...normalizedQuestions.map((question) => ({ question })),
|
|
379
|
+
...completionEntries,
|
|
380
|
+
];
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function syncControllerRunClarifications(
|
|
384
|
+
controllerRunId: string,
|
|
385
|
+
sessionKey: string,
|
|
386
|
+
manifest: ControllerOrchestrationManifest,
|
|
387
|
+
deps: ControllerTaskDomainDeps,
|
|
388
|
+
): ClarificationRequest[] {
|
|
389
|
+
const entries = buildManifestClarificationEntries(manifest);
|
|
390
|
+
const created: ClarificationRequest[] = [];
|
|
391
|
+
const superseded: ClarificationRequest[] = [];
|
|
392
|
+
const now = Date.now();
|
|
393
|
+
deps.updateTeamState((state) => {
|
|
394
|
+
const desiredQuestionKeys = new Set(
|
|
395
|
+
entries.map((entry) => normalizeComparableText(entry.question)),
|
|
396
|
+
);
|
|
397
|
+
const existingQuestions = new Map(
|
|
398
|
+
Object.values(state.clarifications)
|
|
399
|
+
.filter((item) => item.controllerRunId === controllerRunId)
|
|
400
|
+
.map((item) => [normalizeComparableText(item.question), item]),
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
for (const [key, clarification] of existingQuestions.entries()) {
|
|
404
|
+
if (
|
|
405
|
+
clarification.status === "pending"
|
|
406
|
+
&& !desiredQuestionKeys.has(key)
|
|
407
|
+
) {
|
|
408
|
+
clarification.status = "answered";
|
|
409
|
+
clarification.answer = "Automatically superseded by the latest controller clarification set.";
|
|
410
|
+
clarification.answeredBy = "system";
|
|
411
|
+
clarification.answeredAt = now;
|
|
412
|
+
clarification.updatedAt = now;
|
|
413
|
+
superseded.push({ ...clarification });
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
for (const entry of entries) {
|
|
418
|
+
const key = normalizeComparableText(entry.question);
|
|
419
|
+
if (existingQuestions.has(key)) {
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
const clarification: ClarificationRequest = {
|
|
423
|
+
id: generateId(),
|
|
424
|
+
taskId: "",
|
|
425
|
+
controllerRunId,
|
|
426
|
+
controllerSessionKey: sessionKey,
|
|
427
|
+
requestedBy: "controller",
|
|
428
|
+
question: entry.question,
|
|
429
|
+
questionSchema: entry.questionSchema,
|
|
430
|
+
blockingReason: "The controller needs this information before it can confidently continue planning and downstream task creation.",
|
|
431
|
+
context: manifest.requirementSummary,
|
|
432
|
+
status: "pending",
|
|
433
|
+
createdAt: now,
|
|
434
|
+
updatedAt: now,
|
|
435
|
+
};
|
|
436
|
+
state.clarifications[clarification.id] = clarification;
|
|
437
|
+
created.push(clarification);
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
for (const clarification of created) {
|
|
442
|
+
deps.wsServer.broadcastUpdate({ type: "clarification:requested", data: clarification });
|
|
443
|
+
}
|
|
444
|
+
for (const clarification of superseded) {
|
|
445
|
+
deps.wsServer.broadcastUpdate({ type: "clarification:answered", data: clarification });
|
|
446
|
+
}
|
|
447
|
+
return created;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function reconcileControllerClarifications(deps: ControllerTaskDomainDeps): TeamState | null {
|
|
451
|
+
const state = deps.getTeamState();
|
|
452
|
+
if (!state) {
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const superseded: ClarificationRequest[] = [];
|
|
457
|
+
deps.updateTeamState((draft) => {
|
|
458
|
+
const runsBySession = new Map<string, ControllerRunInfo[]>();
|
|
459
|
+
for (const run of Object.values(draft.controllerRuns)) {
|
|
460
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(run.sessionKey);
|
|
461
|
+
const bucket = runsBySession.get(normalizedSessionKey) ?? [];
|
|
462
|
+
bucket.push(run);
|
|
463
|
+
runsBySession.set(normalizedSessionKey, bucket);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
for (const clar of Object.values(draft.clarifications)) {
|
|
467
|
+
if (clar.status !== "pending" || clar.requestedBy !== "controller" || clar.taskId) {
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(clar.controllerSessionKey);
|
|
471
|
+
const sessionRuns = runsBySession.get(normalizedSessionKey) ?? [];
|
|
472
|
+
const supersedingRun = sessionRuns.find((run) =>
|
|
473
|
+
run.updatedAt > clar.updatedAt
|
|
474
|
+
&& (
|
|
475
|
+
run.manifest?.createdTasks.length
|
|
476
|
+
|| run.manifest?.requirementFullyComplete
|
|
477
|
+
),
|
|
478
|
+
);
|
|
479
|
+
if (!supersedingRun) {
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
clar.status = "answered";
|
|
483
|
+
clar.answer = "Automatically superseded by later controller progress.";
|
|
484
|
+
clar.answeredBy = "system";
|
|
485
|
+
clar.answeredAt = supersedingRun.updatedAt;
|
|
486
|
+
clar.updatedAt = supersedingRun.updatedAt;
|
|
487
|
+
superseded.push({ ...clar });
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
for (const clarification of superseded) {
|
|
492
|
+
deps.wsServer.broadcastUpdate({ type: "clarification:answered", data: clarification });
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
for (const run of Object.values(state.controllerRuns)) {
|
|
496
|
+
if (!run.manifest?.clarificationsNeeded) {
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
syncControllerRunClarifications(run.id, run.sessionKey, run.manifest, deps);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
return deps.getTeamState();
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export function buildControllerRateLimitProbeMessage(
|
|
506
|
+
sourceTaskId?: string,
|
|
507
|
+
sourceTaskTitle?: string,
|
|
508
|
+
): string {
|
|
509
|
+
const workflowLabel = sourceTaskTitle
|
|
510
|
+
? `${sourceTaskTitle}${sourceTaskId ? ` (${sourceTaskId})` : ""}`
|
|
511
|
+
: (sourceTaskId ? `task ${sourceTaskId}` : "this controller workflow");
|
|
512
|
+
return [
|
|
513
|
+
`This is a follow-up check for ${workflowLabel}.`,
|
|
514
|
+
"The earlier controller run appears to be delayed by upstream model rate limiting.",
|
|
515
|
+
"Do not restart the workflow from scratch.",
|
|
516
|
+
"Do not duplicate tasks that already exist, are active, or are completed.",
|
|
517
|
+
"If the earlier controller follow-up is fully complete now, immediately submit the required structured manifest for that same workflow step and provide the final orchestration reply.",
|
|
518
|
+
`If the earlier controller follow-up is not complete yet, reply with exactly ${CONTROLLER_RATE_LIMIT_WAITING_SENTINEL}.`,
|
|
519
|
+
].join("\n");
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export function buildControllerInactivityProbeMessage(
|
|
523
|
+
inactivityMs: number,
|
|
524
|
+
sourceTaskId?: string,
|
|
525
|
+
sourceTaskTitle?: string,
|
|
526
|
+
): string {
|
|
527
|
+
const workflowLabel = sourceTaskTitle
|
|
528
|
+
? `${sourceTaskTitle}${sourceTaskId ? ` (${sourceTaskId})` : ""}`
|
|
529
|
+
: (sourceTaskId ? `task ${sourceTaskId}` : "this controller workflow");
|
|
530
|
+
return [
|
|
531
|
+
`This is a follow-up check for ${workflowLabel}.`,
|
|
532
|
+
`There has been no new visible controller workflow progress for over ${formatDuration(inactivityMs)}.`,
|
|
533
|
+
"Do not restart the workflow from scratch.",
|
|
534
|
+
"Do not duplicate tasks that already exist, are active, or are completed.",
|
|
535
|
+
"If the earlier controller follow-up is fully complete now, immediately submit the required structured manifest for that same workflow step and provide the final orchestration reply.",
|
|
536
|
+
`If the earlier controller follow-up is not complete yet, reply with exactly ${CONTROLLER_RATE_LIMIT_WAITING_SENTINEL}.`,
|
|
537
|
+
].join("\n");
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export async function continueControllerWorkflow(task: TaskInfo, deps: ControllerTaskDomainDeps): Promise<void> {
|
|
541
|
+
if (task.createdBy !== "controller") {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
const sessionKey = resolveControllerWorkflowSessionKey(task, deps.getTeamState());
|
|
545
|
+
if (!sessionKey) {
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (task.controllerSessionKey !== sessionKey) {
|
|
549
|
+
deps.updateTeamState((state) => {
|
|
550
|
+
const currentTask = state.tasks[task.id];
|
|
551
|
+
if (currentTask) {
|
|
552
|
+
currentTask.controllerSessionKey = sessionKey;
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
await runControllerIntake(buildControllerFollowUpMessage(task, deps.getTeamState()), sessionKey, deps, {
|
|
557
|
+
source: "task_follow_up",
|
|
558
|
+
sourceTaskId: task.id,
|
|
559
|
+
sourceTaskTitle: task.title,
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Phase 2.1 review fix (design 2.3 concurrency matrix): intake runs create
|
|
565
|
+
* tasks and burn a controller LLM pass, so they are refused while a profile
|
|
566
|
+
* switch transition is in flight - at the runControllerIntake ENTRY, which is
|
|
567
|
+
* the single funnel for URL submissions AND internal callers (task-completion
|
|
568
|
+
* follow-ups, parallel-help, clarification resumes) that bypass the URL-level
|
|
569
|
+
* 503 gate. The message deliberately avoids every token of
|
|
570
|
+
* CONTROLLER_INTAKE_RETRYABLE_ERROR_PATTERN: a transition rejection must fail
|
|
571
|
+
* fast, never retry its way into the switched team.
|
|
572
|
+
*/
|
|
573
|
+
export class ControllerIntakeSwitchInProgressError extends Error {
|
|
574
|
+
readonly transition: TeamSwitchTransition;
|
|
575
|
+
|
|
576
|
+
constructor(transition: TeamSwitchTransition) {
|
|
577
|
+
super(
|
|
578
|
+
`Controller intake rejected: a team profile switch to "${transition.targetProfileId}" is in progress (phase: ${transition.phase}) - retry after the switch completes`,
|
|
579
|
+
);
|
|
580
|
+
this.name = "ControllerIntakeSwitchInProgressError";
|
|
581
|
+
this.transition = transition;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
export async function runControllerIntake(
|
|
586
|
+
message: string,
|
|
587
|
+
sessionKey: string,
|
|
588
|
+
deps: ControllerTaskDomainDeps,
|
|
589
|
+
options?: {
|
|
590
|
+
source?: ControllerRunSource;
|
|
591
|
+
sourceTaskId?: string;
|
|
592
|
+
sourceTaskTitle?: string;
|
|
593
|
+
},
|
|
594
|
+
): Promise<{ sessionKey: string; runId: string; reply: string; controllerRunId: string }> {
|
|
595
|
+
const activeTransition = deps.getTeamState()?.transition;
|
|
596
|
+
if (activeTransition) {
|
|
597
|
+
throw new ControllerIntakeSwitchInProgressError(activeTransition);
|
|
598
|
+
}
|
|
599
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
|
|
600
|
+
return withSerializedControllerIntake(normalizedSessionKey, async () => {
|
|
601
|
+
let lastError: Error | null = null;
|
|
602
|
+
for (let attempt = 0; attempt <= CONTROLLER_INTAKE_MAX_RETRIES; attempt++) {
|
|
603
|
+
try {
|
|
604
|
+
return await runControllerIntakeUnlocked(message, normalizedSessionKey, deps, options);
|
|
605
|
+
} catch (err) {
|
|
606
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
607
|
+
const errorText = lastError.message;
|
|
608
|
+
// Only retry on transient server errors (500/502/503), not on client errors,
|
|
609
|
+
// timeouts, or other failures that retrying won't fix.
|
|
610
|
+
if (
|
|
611
|
+
attempt === CONTROLLER_INTAKE_MAX_RETRIES
|
|
612
|
+
|| !CONTROLLER_INTAKE_RETRYABLE_ERROR_PATTERN.test(errorText)
|
|
613
|
+
|| errorText.includes("timed out")
|
|
614
|
+
) {
|
|
615
|
+
throw lastError;
|
|
616
|
+
}
|
|
617
|
+
// Record a visible retry event so the human can see what happened.
|
|
618
|
+
deps.logger.warn(
|
|
619
|
+
`Controller: intake attempt ${attempt + 1} failed with transient error: ${errorText.slice(0, 200)}. Retrying in ${CONTROLLER_INTAKE_RETRY_DELAY_MS * (attempt + 1) / 1000}s...`,
|
|
620
|
+
);
|
|
621
|
+
await new Promise<void>((resolve) => setTimeout(resolve, CONTROLLER_INTAKE_RETRY_DELAY_MS * (attempt + 1)));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
throw lastError!;
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export async function runControllerIntakeUnlocked(
|
|
629
|
+
message: string,
|
|
630
|
+
sessionKey: string,
|
|
631
|
+
deps: ControllerTaskDomainDeps,
|
|
632
|
+
options?: {
|
|
633
|
+
source?: ControllerRunSource;
|
|
634
|
+
sourceTaskId?: string;
|
|
635
|
+
sourceTaskTitle?: string;
|
|
636
|
+
},
|
|
637
|
+
): Promise<{ sessionKey: string; runId: string; reply: string; controllerRunId: string }> {
|
|
638
|
+
const taskIdsBeforeRun = collectTaskIds(deps.getTeamState());
|
|
639
|
+
const controllerRun = createControllerRun(message, sessionKey, deps, options);
|
|
640
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
641
|
+
type: "lifecycle",
|
|
642
|
+
phase: "queued",
|
|
643
|
+
source: "controller",
|
|
644
|
+
status: "pending",
|
|
645
|
+
sessionKey,
|
|
646
|
+
message: "Controller intake queued.",
|
|
647
|
+
}, deps);
|
|
648
|
+
|
|
649
|
+
const runResult = await deps.runtime.subagent.run({
|
|
650
|
+
sessionKey,
|
|
651
|
+
message,
|
|
652
|
+
extraSystemPrompt: buildControllerIntakeSystemPrompt(deps),
|
|
653
|
+
idempotencyKey: `controller-intake-${generateId()}`,
|
|
654
|
+
});
|
|
655
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
656
|
+
type: "lifecycle",
|
|
657
|
+
phase: "run_started",
|
|
658
|
+
source: "controller",
|
|
659
|
+
status: "running",
|
|
660
|
+
sessionKey,
|
|
661
|
+
runId: runResult.runId,
|
|
662
|
+
message: `Controller intake started (${runResult.runId}).`,
|
|
663
|
+
}, deps);
|
|
664
|
+
|
|
665
|
+
const rateLimitState: {
|
|
666
|
+
active: boolean;
|
|
667
|
+
visibleAt?: number;
|
|
668
|
+
nextProbeAt?: number;
|
|
669
|
+
probeCount: number;
|
|
670
|
+
} = {
|
|
671
|
+
active: false,
|
|
672
|
+
probeCount: 0,
|
|
673
|
+
};
|
|
674
|
+
const inactivityState: {
|
|
675
|
+
active: boolean;
|
|
676
|
+
visibleAt?: number;
|
|
677
|
+
nextProbeAt?: number;
|
|
678
|
+
probeCount: number;
|
|
679
|
+
} = {
|
|
680
|
+
active: false,
|
|
681
|
+
nextProbeAt: Date.now() + deps.config.taskTimeoutMs,
|
|
682
|
+
probeCount: 0,
|
|
683
|
+
};
|
|
684
|
+
const progressSnapshot: {
|
|
685
|
+
fingerprints: string[];
|
|
686
|
+
latestMessages: unknown[];
|
|
687
|
+
lastActivityAt: number;
|
|
688
|
+
} = {
|
|
689
|
+
fingerprints: [],
|
|
690
|
+
latestMessages: [],
|
|
691
|
+
lastActivityAt: Date.now(),
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
const markRateLimitWaiting = async (): Promise<void> => {
|
|
695
|
+
if (rateLimitState.active) {
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const now = Date.now();
|
|
699
|
+
rateLimitState.active = true;
|
|
700
|
+
rateLimitState.visibleAt = now;
|
|
701
|
+
rateLimitState.nextProbeAt = now + CONTROLLER_RATE_LIMIT_STALL_PROBE_MS;
|
|
702
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
703
|
+
type: "progress",
|
|
704
|
+
phase: "model_rate_limit_waiting",
|
|
705
|
+
source: "controller",
|
|
706
|
+
status: "running",
|
|
707
|
+
sessionKey,
|
|
708
|
+
runId: runResult.runId,
|
|
709
|
+
message: "Model rate limit reached. OpenClaw is retrying upstream; TeamClaw will keep waiting for the controller workflow to continue.",
|
|
710
|
+
}, deps);
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
const clearRateLimitWaiting = (): void => {
|
|
714
|
+
rateLimitState.active = false;
|
|
715
|
+
rateLimitState.visibleAt = undefined;
|
|
716
|
+
rateLimitState.nextProbeAt = undefined;
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
const noteObservedControllerActivity = (): void => {
|
|
720
|
+
progressSnapshot.lastActivityAt = Date.now();
|
|
721
|
+
inactivityState.active = false;
|
|
722
|
+
inactivityState.visibleAt = undefined;
|
|
723
|
+
inactivityState.nextProbeAt = Date.now() + deps.config.taskTimeoutMs;
|
|
724
|
+
};
|
|
725
|
+
|
|
726
|
+
const syncControllerSessionProgress = async (): Promise<void> => {
|
|
727
|
+
const sessionMessages = await deps.runtime.subagent.getSessionMessages({
|
|
728
|
+
sessionKey,
|
|
729
|
+
limit: CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT,
|
|
730
|
+
});
|
|
731
|
+
progressSnapshot.latestMessages = Array.isArray(sessionMessages.messages) ? sessionMessages.messages : [];
|
|
732
|
+
const entries = buildSessionProgressEntries(progressSnapshot.latestMessages, message);
|
|
733
|
+
const newEntries = getNewSessionProgressEntries(entries, progressSnapshot.fingerprints);
|
|
734
|
+
progressSnapshot.fingerprints = entries.map((entry) => entry.fingerprint);
|
|
735
|
+
if (newEntries.length > 0) {
|
|
736
|
+
noteObservedControllerActivity();
|
|
737
|
+
}
|
|
738
|
+
for (const entry of newEntries) {
|
|
739
|
+
if (entry.isRateLimit) {
|
|
740
|
+
await markRateLimitWaiting();
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
if (rateLimitState.active && isStillWaitingResponse(entry.message)) {
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (rateLimitState.active) {
|
|
747
|
+
clearRateLimitWaiting();
|
|
748
|
+
}
|
|
749
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
750
|
+
type: "progress",
|
|
751
|
+
phase: entry.phase,
|
|
752
|
+
source: "subagent",
|
|
753
|
+
stream: entry.stream,
|
|
754
|
+
status: "running",
|
|
755
|
+
sessionKey,
|
|
756
|
+
runId: runResult.runId,
|
|
757
|
+
message: entry.message,
|
|
758
|
+
}, deps);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
const extractSessionAssistantReply = async (): Promise<string> => {
|
|
763
|
+
const sessionMessages = await deps.runtime.subagent.getSessionMessages({
|
|
764
|
+
sessionKey,
|
|
765
|
+
limit: 100,
|
|
766
|
+
});
|
|
767
|
+
return extractLastAssistantText(sessionMessages.messages);
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
const probeRateLimitedControllerCompletion = async (): Promise<string | null> => {
|
|
771
|
+
rateLimitState.probeCount += 1;
|
|
772
|
+
const now = Date.now();
|
|
773
|
+
rateLimitState.visibleAt = now;
|
|
774
|
+
rateLimitState.nextProbeAt = now + CONTROLLER_RATE_LIMIT_STALL_PROBE_MS;
|
|
775
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
776
|
+
type: "progress",
|
|
777
|
+
phase: "model_rate_limit_probe",
|
|
778
|
+
source: "controller",
|
|
779
|
+
status: "running",
|
|
780
|
+
sessionKey,
|
|
781
|
+
runId: runResult.runId,
|
|
782
|
+
message: `Model rate limit has delayed controller orchestration for over ${formatDuration(CONTROLLER_RATE_LIMIT_STALL_PROBE_MS)}. Re-checking whether this workflow step has already completed.`,
|
|
783
|
+
}, deps);
|
|
784
|
+
|
|
785
|
+
const probeRun = await deps.runtime.subagent.run({
|
|
786
|
+
sessionKey,
|
|
787
|
+
message: buildControllerRateLimitProbeMessage(options?.sourceTaskId, options?.sourceTaskTitle),
|
|
788
|
+
extraSystemPrompt: buildControllerIntakeSystemPrompt(deps),
|
|
789
|
+
idempotencyKey: `${runResult.runId}:rate-limit-probe:${rateLimitState.probeCount}`,
|
|
790
|
+
});
|
|
791
|
+
const probeWait = await deps.runtime.subagent.waitForRun({
|
|
792
|
+
runId: probeRun.runId,
|
|
793
|
+
timeoutMs: CONTROLLER_RATE_LIMIT_PROBE_TIMEOUT_MS,
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
if (probeWait.status !== "ok") {
|
|
797
|
+
return null;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
const probeReply = await extractSessionAssistantReply();
|
|
801
|
+
if (!probeReply || isRateLimitMessage(probeReply) || isStillWaitingResponse(probeReply)) {
|
|
802
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
803
|
+
type: "progress",
|
|
804
|
+
phase: "model_rate_limit_still_waiting",
|
|
805
|
+
source: "controller",
|
|
806
|
+
status: "running",
|
|
807
|
+
sessionKey,
|
|
808
|
+
runId: runResult.runId,
|
|
809
|
+
message: "The controller workflow is still waiting on model availability. TeamClaw will continue waiting.",
|
|
810
|
+
}, deps);
|
|
811
|
+
return null;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
clearRateLimitWaiting();
|
|
815
|
+
noteObservedControllerActivity();
|
|
816
|
+
return probeReply;
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
const probeInactiveControllerCompletion = async (): Promise<string | null> => {
|
|
820
|
+
inactivityState.probeCount += 1;
|
|
821
|
+
const now = Date.now();
|
|
822
|
+
inactivityState.active = true;
|
|
823
|
+
inactivityState.visibleAt = now;
|
|
824
|
+
inactivityState.nextProbeAt = now + deps.config.taskTimeoutMs;
|
|
825
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
826
|
+
type: "progress",
|
|
827
|
+
phase: "inactivity_probe",
|
|
828
|
+
source: "controller",
|
|
829
|
+
status: "running",
|
|
830
|
+
sessionKey,
|
|
831
|
+
runId: runResult.runId,
|
|
832
|
+
message: `No new controller workflow output has appeared for over ${formatDuration(deps.config.taskTimeoutMs)}. Re-checking whether this orchestration step is complete or still running.`,
|
|
833
|
+
}, deps);
|
|
834
|
+
|
|
835
|
+
const probeRun = await deps.runtime.subagent.run({
|
|
836
|
+
sessionKey,
|
|
837
|
+
message: buildControllerInactivityProbeMessage(
|
|
838
|
+
deps.config.taskTimeoutMs,
|
|
839
|
+
options?.sourceTaskId,
|
|
840
|
+
options?.sourceTaskTitle,
|
|
841
|
+
),
|
|
842
|
+
extraSystemPrompt: buildControllerIntakeSystemPrompt(deps),
|
|
843
|
+
idempotencyKey: `${runResult.runId}:inactivity-probe:${inactivityState.probeCount}`,
|
|
844
|
+
});
|
|
845
|
+
const probeWait = await deps.runtime.subagent.waitForRun({
|
|
846
|
+
runId: probeRun.runId,
|
|
847
|
+
timeoutMs: CONTROLLER_INACTIVITY_PROBE_TIMEOUT_MS,
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
if (probeWait.status === "error" && isRateLimitMessage(probeWait.error || "")) {
|
|
851
|
+
await markRateLimitWaiting();
|
|
852
|
+
return null;
|
|
853
|
+
}
|
|
854
|
+
if (probeWait.status !== "ok") {
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const probeReply = await extractSessionAssistantReply();
|
|
859
|
+
if (!probeReply || isRateLimitMessage(probeReply) || isStillWaitingResponse(probeReply)) {
|
|
860
|
+
inactivityState.active = false;
|
|
861
|
+
inactivityState.visibleAt = undefined;
|
|
862
|
+
inactivityState.nextProbeAt = Date.now() + deps.config.taskTimeoutMs;
|
|
863
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
864
|
+
type: "progress",
|
|
865
|
+
phase: "inactivity_still_waiting",
|
|
866
|
+
source: "controller",
|
|
867
|
+
status: "running",
|
|
868
|
+
sessionKey,
|
|
869
|
+
runId: runResult.runId,
|
|
870
|
+
message: "The controller workflow is still running without a final result yet. TeamClaw will keep waiting instead of failing the run.",
|
|
871
|
+
}, deps);
|
|
872
|
+
return null;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
if (rateLimitState.active) {
|
|
876
|
+
clearRateLimitWaiting();
|
|
877
|
+
}
|
|
878
|
+
noteObservedControllerActivity();
|
|
879
|
+
return probeReply;
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
let waitResult: Awaited<ReturnType<typeof deps.runtime.subagent.waitForRun>> = { status: "timeout" };
|
|
883
|
+
let completionOverride: string | null = null;
|
|
884
|
+
while (true) {
|
|
885
|
+
if (rateLimitState.active && (rateLimitState.nextProbeAt ?? Number.POSITIVE_INFINITY) <= Date.now()) {
|
|
886
|
+
completionOverride = await probeRateLimitedControllerCompletion();
|
|
887
|
+
if (completionOverride) {
|
|
888
|
+
waitResult = { status: "ok" };
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (!rateLimitState.active && (inactivityState.nextProbeAt ?? Number.POSITIVE_INFINITY) <= Date.now()) {
|
|
894
|
+
completionOverride = await probeInactiveControllerCompletion();
|
|
895
|
+
if (completionOverride) {
|
|
896
|
+
waitResult = { status: "ok" };
|
|
897
|
+
break;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
waitResult = await deps.runtime.subagent.waitForRun({
|
|
902
|
+
runId: runResult.runId,
|
|
903
|
+
timeoutMs: CONTROLLER_RUN_WAIT_SLICE_MS,
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
try {
|
|
907
|
+
await syncControllerSessionProgress();
|
|
908
|
+
} catch (err) {
|
|
909
|
+
deps.logger.debug?.(`Controller: failed to sync planning session progress for ${controllerRun.id}: ${String(err)}`);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
if (waitResult.status === "ok") {
|
|
913
|
+
clearRateLimitWaiting();
|
|
914
|
+
noteObservedControllerActivity();
|
|
915
|
+
break;
|
|
916
|
+
}
|
|
917
|
+
if (waitResult.status === "error") {
|
|
918
|
+
if (isRateLimitMessage(waitResult.error || "")) {
|
|
919
|
+
await markRateLimitWaiting();
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
break;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
if (waitResult.status !== "ok") {
|
|
926
|
+
const errorMessage = waitResult.error || "Controller intake failed";
|
|
927
|
+
const createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
|
|
928
|
+
updateControllerRun(controllerRun.id, deps, (run) => {
|
|
929
|
+
run.createdTaskIds = createdTaskIds;
|
|
930
|
+
run.error = errorMessage;
|
|
931
|
+
appendControllerRunEvent(run, {
|
|
932
|
+
type: "error",
|
|
933
|
+
phase: "run_failed",
|
|
934
|
+
source: "controller",
|
|
935
|
+
status: "failed",
|
|
936
|
+
sessionKey,
|
|
937
|
+
runId: runResult.runId,
|
|
938
|
+
message: errorMessage,
|
|
939
|
+
});
|
|
940
|
+
});
|
|
941
|
+
throw new Error(errorMessage);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
let createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
|
|
945
|
+
|
|
946
|
+
try {
|
|
947
|
+
await syncControllerSessionProgress();
|
|
948
|
+
} catch (err) {
|
|
949
|
+
deps.logger.debug?.(`Controller: failed final planning session sync for ${controllerRun.id}: ${String(err)}`);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const rawReply = completionOverride || await extractSessionAssistantReply()
|
|
953
|
+
|| "Controller completed the intake run but did not return any text.";
|
|
954
|
+
const recordedManifest = ensureControllerManifest(
|
|
955
|
+
controllerRun.id,
|
|
956
|
+
sessionKey,
|
|
957
|
+
message,
|
|
958
|
+
rawReply,
|
|
959
|
+
createdTaskIds,
|
|
960
|
+
deps,
|
|
961
|
+
);
|
|
962
|
+
const fallbackTaskIds = await maybeBackfillExecutionReadyTask(
|
|
963
|
+
controllerRun.id,
|
|
964
|
+
sessionKey,
|
|
965
|
+
message,
|
|
966
|
+
recordedManifest,
|
|
967
|
+
deps,
|
|
968
|
+
{ source: options?.source },
|
|
969
|
+
);
|
|
970
|
+
if (fallbackTaskIds.length > 0) {
|
|
971
|
+
createdTaskIds = Array.from(new Set([...createdTaskIds, ...fallbackTaskIds]));
|
|
972
|
+
}
|
|
973
|
+
const convertedClarificationTaskIds = await maybeConvertControllerClarificationToExecutionTask(
|
|
974
|
+
controllerRun.id,
|
|
975
|
+
sessionKey,
|
|
976
|
+
recordedManifest,
|
|
977
|
+
deps,
|
|
978
|
+
);
|
|
979
|
+
if (convertedClarificationTaskIds.length > 0) {
|
|
980
|
+
createdTaskIds = Array.from(new Set([...createdTaskIds, ...convertedClarificationTaskIds]));
|
|
981
|
+
}
|
|
982
|
+
syncControllerRunClarifications(controllerRun.id, sessionKey, recordedManifest, deps);
|
|
983
|
+
const reconciledTasks = reconcileControllerManifestTaskBindings(sessionKey, createdTaskIds, recordedManifest, controllerRun.id, deps);
|
|
984
|
+
|
|
985
|
+
// ── Automatic Team Kickoff ────────────────────────────────────────────
|
|
986
|
+
// For complex projects (3+ roles), automatically run a kickoff meeting
|
|
987
|
+
// so every candidate role can assess the requirement collaboratively.
|
|
988
|
+
// This happens AFTER the initial LLM pass so we know which roles are
|
|
989
|
+
// needed, but we store the assessments for visibility and future
|
|
990
|
+
// refinement passes.
|
|
991
|
+
const AUTO_KICKOFF_ROLE_THRESHOLD = 3;
|
|
992
|
+
const isFollowUp = options?.source === "task_follow_up";
|
|
993
|
+
const kickoffHandler = deps.getKickoffHandler?.();
|
|
994
|
+
if (
|
|
995
|
+
!isFollowUp
|
|
996
|
+
&& kickoffHandler
|
|
997
|
+
&& recordedManifest.requiredRoles.length >= AUTO_KICKOFF_ROLE_THRESHOLD
|
|
998
|
+
&& !recordedManifest.clarificationsNeeded
|
|
999
|
+
) {
|
|
1000
|
+
deps.logger.info(
|
|
1001
|
+
`Controller: auto-kickoff triggered for ${recordedManifest.requiredRoles.length} roles: ${recordedManifest.requiredRoles.join(", ")}`,
|
|
1002
|
+
);
|
|
1003
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
1004
|
+
type: "lifecycle",
|
|
1005
|
+
phase: "kickoff_started",
|
|
1006
|
+
source: "controller",
|
|
1007
|
+
status: "running",
|
|
1008
|
+
sessionKey,
|
|
1009
|
+
message: `Auto-kickoff: provisioning ${recordedManifest.requiredRoles.length} candidate roles for team assessment.`,
|
|
1010
|
+
}, deps);
|
|
1011
|
+
try {
|
|
1012
|
+
const kickoffResult = await kickoffHandler(
|
|
1013
|
+
recordedManifest.requiredRoles,
|
|
1014
|
+
recordedManifest.requiredRoles.length >= 5 ? "complex" : "medium",
|
|
1015
|
+
message,
|
|
1016
|
+
);
|
|
1017
|
+
// Store kickoff assessments on the manifest for UI/API visibility
|
|
1018
|
+
recordedManifest.kickoffPlan = {
|
|
1019
|
+
complexity: recordedManifest.requiredRoles.length >= 5 ? "complex" : "medium",
|
|
1020
|
+
candidateRoles: recordedManifest.requiredRoles,
|
|
1021
|
+
completed: true,
|
|
1022
|
+
assessments: kickoffResult.assessments,
|
|
1023
|
+
summary: kickoffResult.summary,
|
|
1024
|
+
triggeredAt: Date.now(),
|
|
1025
|
+
};
|
|
1026
|
+
updateControllerRun(controllerRun.id, deps, (run) => {
|
|
1027
|
+
if (run.manifest) {
|
|
1028
|
+
run.manifest.kickoffPlan = recordedManifest.kickoffPlan;
|
|
1029
|
+
}
|
|
1030
|
+
appendControllerRunEvent(run, {
|
|
1031
|
+
type: "lifecycle",
|
|
1032
|
+
phase: "kickoff_completed",
|
|
1033
|
+
source: "controller",
|
|
1034
|
+
status: "running",
|
|
1035
|
+
sessionKey,
|
|
1036
|
+
message: `Team kickoff completed: ${kickoffResult.assessments.length} assessments collected. ${kickoffResult.summary.slice(0, 200)}`,
|
|
1037
|
+
});
|
|
1038
|
+
});
|
|
1039
|
+
deps.logger.info(
|
|
1040
|
+
`Controller: auto-kickoff completed with ${kickoffResult.assessments.length} assessments`,
|
|
1041
|
+
);
|
|
1042
|
+
} catch (err) {
|
|
1043
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
1044
|
+
deps.logger.warn(`Controller: auto-kickoff failed: ${errMsg}`);
|
|
1045
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
1046
|
+
type: "lifecycle",
|
|
1047
|
+
phase: "kickoff_failed",
|
|
1048
|
+
source: "controller",
|
|
1049
|
+
status: "running",
|
|
1050
|
+
sessionKey,
|
|
1051
|
+
message: `Auto-kickoff failed: ${errMsg}. Proceeding with controller-only planning.`,
|
|
1052
|
+
}, deps);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
const latestTeamState = deps.getTeamState();
|
|
1057
|
+
const reply = buildControllerManifestReply(recordedManifest, reconciledTasks.taskIds, latestTeamState, rawReply);
|
|
1058
|
+
|
|
1059
|
+
updateControllerRun(controllerRun.id, deps, (run) => {
|
|
1060
|
+
run.reply = reply;
|
|
1061
|
+
run.error = undefined;
|
|
1062
|
+
run.createdTaskIds = reconciledTasks.taskIds;
|
|
1063
|
+
appendControllerRunEvent(run, {
|
|
1064
|
+
type: "output",
|
|
1065
|
+
phase: "final_reply",
|
|
1066
|
+
source: "subagent",
|
|
1067
|
+
status: "running",
|
|
1068
|
+
sessionKey,
|
|
1069
|
+
runId: runResult.runId,
|
|
1070
|
+
message: reply,
|
|
1071
|
+
});
|
|
1072
|
+
if (reconciledTasks.linkedTaskIds.length > 0) {
|
|
1073
|
+
appendControllerRunEvent(run, {
|
|
1074
|
+
type: "lifecycle",
|
|
1075
|
+
phase: "tasks_linked",
|
|
1076
|
+
source: "controller",
|
|
1077
|
+
status: "running",
|
|
1078
|
+
sessionKey,
|
|
1079
|
+
runId: runResult.runId,
|
|
1080
|
+
message: `Controller linked ${reconciledTasks.linkedTaskIds.length} existing task(s) into this workflow: ${reconciledTasks.linkedTaskIds.join(", ")}`,
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
if (reconciledTasks.taskIds.length > 0) {
|
|
1084
|
+
appendControllerRunEvent(run, {
|
|
1085
|
+
type: "lifecycle",
|
|
1086
|
+
phase: "tasks_created",
|
|
1087
|
+
source: "controller",
|
|
1088
|
+
status: "running",
|
|
1089
|
+
sessionKey,
|
|
1090
|
+
runId: runResult.runId,
|
|
1091
|
+
message: `Controller activated ${reconciledTasks.taskIds.length} execution-ready task(s): ${reconciledTasks.taskIds.join(", ")}`,
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
appendControllerRunEvent(run, {
|
|
1095
|
+
type: "lifecycle",
|
|
1096
|
+
phase: "run_completed",
|
|
1097
|
+
source: "controller",
|
|
1098
|
+
status: "completed",
|
|
1099
|
+
sessionKey,
|
|
1100
|
+
runId: runResult.runId,
|
|
1101
|
+
message: "Controller intake completed.",
|
|
1102
|
+
});
|
|
1103
|
+
});
|
|
1104
|
+
|
|
1105
|
+
await pruneStaleControllerRuns(deps, { excludeRunId: controllerRun.id });
|
|
1106
|
+
|
|
1107
|
+
return {
|
|
1108
|
+
sessionKey,
|
|
1109
|
+
runId: runResult.runId,
|
|
1110
|
+
reply,
|
|
1111
|
+
controllerRunId: controllerRun.id,
|
|
1112
|
+
};
|
|
1113
|
+
}
|