@teamclaws/teamclaw 2026.8.0 → 2026.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +46 -15
- package/dist/api.js +1 -0
- package/dist/index.js +325 -0
- package/dist/src/config.js +412 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-capacity.js +14 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +813 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +624 -0
- package/dist/src/controller/controller-tools.js +587 -0
- package/dist/src/controller/delivery-report.js +458 -0
- package/dist/src/controller/github-auth.js +564 -0
- package/dist/src/controller/http-server.js +284 -0
- package/dist/src/controller/kickoff-orchestrator.js +246 -0
- package/dist/src/controller/managed-gateway-process.js +286 -0
- package/dist/src/controller/message-delivery.js +28 -0
- package/dist/src/controller/message-router.js +38 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +151 -0
- package/dist/src/controller/preview-manager.js +586 -0
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +289 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +197 -0
- package/dist/src/controller/repo-routes.js +63 -0
- package/dist/src/controller/role-inference.js +246 -0
- package/dist/src/controller/route-table.js +1353 -0
- package/dist/src/controller/task-assignment.js +508 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +240 -0
- package/dist/src/controller/task-results.js +461 -0
- package/dist/src/controller/task-router.js +137 -0
- 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 +548 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +42 -0
- package/dist/src/controller/worker-provisioning.js +1674 -0
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/discovery.js +86 -0
- package/dist/src/git-collaboration.js +694 -0
- package/dist/src/identity.js +132 -0
- package/dist/src/install-defaults.js +1 -0
- package/dist/src/interaction-contracts.js +531 -0
- package/dist/src/networking.js +91 -0
- package/dist/src/openclaw-workspace.js +925 -0
- package/dist/src/profile-loader.js +486 -0
- package/dist/src/profiles/banking.json +178 -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 +201 -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 +386 -0
- package/dist/src/protocol.js +58 -0
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +390 -0
- package/dist/src/session-roles.js +14 -0
- package/dist/src/state.js +361 -0
- package/dist/src/task-executor.js +1023 -0
- package/dist/src/teamauto/github-client.js +210 -0
- package/dist/src/teamauto/norms.js +85 -0
- package/dist/src/teamauto/repo-sync.js +423 -0
- package/dist/src/teamauto/scanner.js +207 -0
- package/dist/src/teamauto/schedule.js +123 -0
- package/dist/src/teamauto/scheduler.js +907 -0
- package/dist/src/teamauto/store.js +133 -0
- package/dist/src/types.js +290 -0
- package/dist/src/ui/app.js +4860 -0
- package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
- package/dist/src/ui/github-login.html +296 -0
- package/dist/src/ui/index.html +447 -0
- package/dist/src/ui/style.css +2805 -0
- package/dist/src/worker/http-handler.js +146 -0
- package/dist/src/worker/message-queue.js +24 -0
- package/dist/src/worker/prompt-injector.js +78 -0
- package/dist/src/worker/skill-installer.js +255 -0
- package/dist/src/worker/tools.js +541 -0
- package/dist/src/worker/worker-service.js +307 -0
- package/dist/src/workspace-browser.js +269 -0
- package/openclaw.plugin.json +28 -1
- package/package.json +3 -2
- package/src/config.ts +33 -2
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1029 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +295 -41
- package/src/controller/controller-tools.ts +11 -7
- package/src/controller/http-server.ts +294 -6971
- package/src/controller/kickoff-orchestrator.ts +70 -7
- package/src/controller/message-delivery.ts +49 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +6 -29
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +366 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/repo-routes.ts +91 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +1616 -0
- package/src/controller/task-assignment.ts +618 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +356 -0
- package/src/controller/task-results.ts +544 -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/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +13 -1
- package/src/controller/worker-provisioning.ts +32 -4
- package/src/controller/worker-routes.ts +241 -0
- package/src/identity.ts +3 -2
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +650 -0
- package/src/profiles/banking.json +178 -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 +201 -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 +27 -13
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/state.ts +236 -9
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +21 -0
- package/src/teamauto/repo-sync.ts +246 -6
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +259 -16
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +133 -16
- package/src/ui/app.js +592 -24
- package/src/ui/index.html +44 -11
- package/src/ui/style.css +194 -0
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +3 -1
- package/src/worker/worker-service.ts +83 -3
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// ===========================================================================
|
|
2
|
+
// Controller HTTP server - COMPOSITION ROOT (issue #204 P0 split, PR-D).
|
|
3
|
+
//
|
|
4
|
+
// This file assembles the pieces and owns ONLY the dispatch-layer gates and
|
|
5
|
+
// the server lifecycle; request routing is declarative (see
|
|
6
|
+
// ./route-table.ts, PR-D) and every handler body lives in a domain module.
|
|
7
|
+
// Request pipeline, in order:
|
|
8
|
+
//
|
|
9
|
+
// 1. CORS preflight (OPTIONS short-circuit)
|
|
10
|
+
// 2. Tunnel gate (viaTunnel classification: gate page routes / gate
|
|
11
|
+
// cookie 403 / tunnel management API - tables in ./route-table.ts)
|
|
12
|
+
// 3. handleRequest gates (verbatim, NOT part of the route table):
|
|
13
|
+
// a. profile-switch transition matrix (409 worker re-register,
|
|
14
|
+
// 503+Retry-After task submission / repo import)
|
|
15
|
+
// b. capability 404 gates (steady-state existence gate, after (a) on
|
|
16
|
+
// purpose: transition semantics win over the 404)
|
|
17
|
+
// 4. declarative route table match (./route-table.ts, array order =
|
|
18
|
+
// the historical if/startsWith chain, one-to-one)
|
|
19
|
+
// 5. fall-through 404
|
|
20
|
+
//
|
|
21
|
+
// Domain module index (the 18 modules this root composes; none of them may
|
|
22
|
+
// import this file):
|
|
23
|
+
// PR-A: profile-switch.ts (six-step switch machine), ui-assets.ts
|
|
24
|
+
// PR-B: teamauto-routes.ts, repo-routes.ts, preview-proxy.ts
|
|
25
|
+
// PR-C: task-execution.ts, project-registry.ts, controller-runs.ts,
|
|
26
|
+
// task-cleanup.ts, task-assignment.ts, controller-intake.ts,
|
|
27
|
+
// controller-planning.ts, task-results.ts (via task-routes),
|
|
28
|
+
// worker-routes.ts, task-routes.ts, message-routes.ts,
|
|
29
|
+
// clarification-routes.ts
|
|
30
|
+
// PR-D: route-table.ts (declarative route table + dispatcher + the
|
|
31
|
+
// handlers that were inline here before the split)
|
|
32
|
+
// Pre-split peers that stayed: controller-service.ts (service lifecycle),
|
|
33
|
+
// websocket.ts, task-router.ts, message-router.ts, github-auth.ts,
|
|
34
|
+
// tunnel-manager.ts, delivery-report.ts, orchestration-manifest.ts,
|
|
35
|
+
// preview-manager.ts, worker-provisioning.ts, controller-capacity.ts,
|
|
36
|
+
// controller-tools.ts, kickoff-orchestrator.ts, prompt-injector.ts.
|
|
37
|
+
// ===========================================================================
|
|
38
|
+
import http from "node:http";
|
|
39
|
+
import { sendJson, sendError } from "../protocol.js";
|
|
40
|
+
import { getActiveProfile } from "../profile-loader.js";
|
|
41
|
+
import { autoAssignPendingTasks } from "./task-assignment.js";
|
|
42
|
+
import { createTunnelManager, gatePageHtml } from "./tunnel-manager.js";
|
|
43
|
+
// PR-D of issue #204: routing is declarative. route-table.ts owns the
|
|
44
|
+
// ordered controller route table, the tunnel-side tables, the dispatcher
|
|
45
|
+
// and every handler that used to be inline in this file's if/startsWith
|
|
46
|
+
// chain. This is the only runtime import direction between the two files
|
|
47
|
+
// (route-table imports this file as TYPE ONLY), so the module graph stays
|
|
48
|
+
// acyclic.
|
|
49
|
+
import { controllerRouteTable, createTunnelGateRoutes, createTunnelManagementRoutes, dispatchRoutes, SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS, } from "./route-table.js";
|
|
50
|
+
// ===========================================================================
|
|
51
|
+
// Team profile switch dispatch-layer constants (Phase 2.1,
|
|
52
|
+
// vertical-team-profiles-design.md 2.3). The six-step switch machine itself
|
|
53
|
+
// (drain -> archive -> rebuild -> warm -> settle) lives in
|
|
54
|
+
// ./profile-switch.ts since PR-A of issue #204; these constants below gate
|
|
55
|
+
// request dispatch while a transition is in flight and stay with the router.
|
|
56
|
+
// ===========================================================================
|
|
57
|
+
/** Advisory backoff hint carried in 409 bodies for worker register/heartbeat. */
|
|
58
|
+
const SWITCH_WORKER_BACKOFF_HINT_MS = 5000;
|
|
59
|
+
// SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS moved to ./route-table.ts with
|
|
60
|
+
// PR-D (the intake handler body carries it too); imported above.
|
|
61
|
+
/** New-work entry points gated with 503 + Retry-While during a transition. */
|
|
62
|
+
const TRANSITION_BLOCKED_TASK_POST_PATHS = new Set([
|
|
63
|
+
"/api/v1/tasks",
|
|
64
|
+
"/api/v1/controller/intake",
|
|
65
|
+
"/api/v1/controller/manifest",
|
|
66
|
+
]);
|
|
67
|
+
// Review fix: manual assign and parallel-help both spawn work for the
|
|
68
|
+
// outgoing team (parallel-help funnels into runControllerIntake, which also
|
|
69
|
+
// carries its own entry-level backstop); task handoff stays open - it is part
|
|
70
|
+
// of in-flight completion the drain waits on.
|
|
71
|
+
const TRANSITION_BLOCKED_TASK_POST_PATH_RES = [
|
|
72
|
+
/^\/api\/v1\/tasks\/[^/]+\/assign$/,
|
|
73
|
+
/^\/api\/v1\/tasks\/[^/]+\/parallel-help$/,
|
|
74
|
+
];
|
|
75
|
+
const WORKER_REGISTER_PATH = "/api/v1/workers/register";
|
|
76
|
+
const WORKER_HEARTBEAT_PATH_RE = /^\/api\/v1\/workers\/[^/]+\/heartbeat$/;
|
|
77
|
+
/**
|
|
78
|
+
* Route -> capability map. Prefix entries hide the whole route family;
|
|
79
|
+
* exact entries are method-bound single routes. Routes NOT listed here stay
|
|
80
|
+
* up for every profile: capability-agnostic reads, capability reads that
|
|
81
|
+
* degrade gracefully instead of disappearing (GET /api/v1/repo answers
|
|
82
|
+
* { enabled: false } so the UI can render an off state), and - deliberately
|
|
83
|
+
* - POST /api/v1/controller/manifest: that endpoint records the controller
|
|
84
|
+
* INTAKE orchestration manifest (controllerRuns/projects/task bindings,
|
|
85
|
+
* requirement:complete), it is not a delivery-report surface, and the
|
|
86
|
+
* controller prompt rules make teamclaw_submit_manifest mandatory on every
|
|
87
|
+
* reply (controller-tools POSTs this endpoint) - gating it under
|
|
88
|
+
* deliveryReview would 404 every intake manifest of a deliveryReview=false
|
|
89
|
+
* team and break the intake loop (cross-review fix).
|
|
90
|
+
*/
|
|
91
|
+
const CAPABILITY_GATE_PREFIXES = [
|
|
92
|
+
["/api/v1/teamauto", "teamauto"],
|
|
93
|
+
["/api/v1/previews/", "runnablePreview"],
|
|
94
|
+
["/api/v1/reports", "deliveryReview"],
|
|
95
|
+
];
|
|
96
|
+
const CAPABILITY_GATE_EXACT_PATHS = [
|
|
97
|
+
["POST", "/api/v1/repo/import", "git"],
|
|
98
|
+
["GET", "/api/v1/repo/bundle", "git"],
|
|
99
|
+
];
|
|
100
|
+
/**
|
|
101
|
+
* Returns the capability that owns `pathname` when the ACTIVE profile has it
|
|
102
|
+
* disabled, else null (route proceeds unchanged). Reads the active profile
|
|
103
|
+
* per request so the gates flip atomically with the switch's step-4 profile
|
|
104
|
+
* activation.
|
|
105
|
+
*/
|
|
106
|
+
function disabledCapabilityForPath(method, pathname) {
|
|
107
|
+
const { capabilities } = getActiveProfile();
|
|
108
|
+
for (const [prefix, capability] of CAPABILITY_GATE_PREFIXES) {
|
|
109
|
+
if (pathname.startsWith(prefix) && !capabilities[capability]) {
|
|
110
|
+
return capability;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (const [gatedMethod, gatedPath, capability] of CAPABILITY_GATE_EXACT_PATHS) {
|
|
114
|
+
if (method === gatedMethod && pathname === gatedPath && !capabilities[capability]) {
|
|
115
|
+
return capability;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
export function createControllerHttpServer(deps) {
|
|
121
|
+
const { logger, wsServer } = deps;
|
|
122
|
+
let tunnelManagerSingleton = null;
|
|
123
|
+
// Tunnel-side route tables are built once (lazily, next to the lazy
|
|
124
|
+
// tunnel manager singleton they close over) and reused for every request.
|
|
125
|
+
let tunnelRoutesSingleton = null;
|
|
126
|
+
const server = http.createServer(async (req, res) => {
|
|
127
|
+
// CORS preflight
|
|
128
|
+
if (req.method === "OPTIONS") {
|
|
129
|
+
res.writeHead(200, {
|
|
130
|
+
"Access-Control-Allow-Origin": "*",
|
|
131
|
+
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
|
|
132
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
133
|
+
});
|
|
134
|
+
res.end();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
138
|
+
const pathname = url.pathname;
|
|
139
|
+
// Tunnel sharing: every request arriving via <user>.apps.teamclaw.dev is
|
|
140
|
+
// gated behind the token the local web UI displays. The gate-page /
|
|
141
|
+
// management route bodies live in ./route-table.ts (PR-D); the branch
|
|
142
|
+
// structure below is unchanged from the pre-PR-D if/else chain.
|
|
143
|
+
let tunnelManager = tunnelManagerSingleton;
|
|
144
|
+
if (!tunnelManager) {
|
|
145
|
+
tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
|
|
146
|
+
}
|
|
147
|
+
if (!tunnelRoutesSingleton) {
|
|
148
|
+
tunnelRoutesSingleton = {
|
|
149
|
+
gate: createTunnelGateRoutes(tunnelManager),
|
|
150
|
+
management: createTunnelManagementRoutes(tunnelManager, deps),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const tunnelCtx = {
|
|
154
|
+
req, res, requestUrl: url, pathname, deps, currentState: null,
|
|
155
|
+
};
|
|
156
|
+
const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
|
|
157
|
+
if (viaTunnel) {
|
|
158
|
+
if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (!tunnelManager.gateAllows(req)) {
|
|
162
|
+
res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
|
|
163
|
+
res.end(gatePageHtml(String(req.headers.host), false));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
if (await dispatchRoutes(tunnelRoutesSingleton.management, tunnelCtx)) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
await handleRequest(req, res, pathname, deps);
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
logger.error(`Controller HTTP error: ${err instanceof Error ? err.message : String(err)}`);
|
|
177
|
+
sendError(res, 500, "Internal server error");
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
// Attach WebSocket
|
|
181
|
+
wsServer.attach(server);
|
|
182
|
+
// Plugin shutdown: kill the local connector and tear down the remote
|
|
183
|
+
// tunnel so gateway exits never leak orphan cloudflared processes.
|
|
184
|
+
server.on("close", () => {
|
|
185
|
+
void tunnelManagerSingleton?.stop().catch(() => undefined);
|
|
186
|
+
});
|
|
187
|
+
// Boot reconciliation: reconnect a share persisted by a previous run
|
|
188
|
+
// (gateway restart or kill -9) so the tunnel id and gate token survive.
|
|
189
|
+
if (!tunnelManagerSingleton) {
|
|
190
|
+
tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
|
|
191
|
+
}
|
|
192
|
+
void tunnelManagerSingleton.recover().catch((err) => {
|
|
193
|
+
logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
|
|
194
|
+
});
|
|
195
|
+
setTimeout(() => {
|
|
196
|
+
const state = deps.getTeamState();
|
|
197
|
+
const pendingCount = state
|
|
198
|
+
? Object.values(state.tasks).filter((t) => t.status === "pending" && !t.assignedWorkerId).length
|
|
199
|
+
: 0;
|
|
200
|
+
if (pendingCount > 0) {
|
|
201
|
+
logger.info(`Controller: startup reconciliation — ${pendingCount} pending tasks, triggering auto-assign`);
|
|
202
|
+
void autoAssignPendingTasks(deps).catch((err) => {
|
|
203
|
+
logger.warn(`Controller: startup auto-assign failed: ${String(err)}`);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}, 2000);
|
|
207
|
+
return server;
|
|
208
|
+
}
|
|
209
|
+
async function handleRequest(req, res, pathname, deps) {
|
|
210
|
+
const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
211
|
+
const currentState = deps.getTeamState();
|
|
212
|
+
// ==================== Profile switch concurrency matrix ====================
|
|
213
|
+
// Phase 2.1 (design 2.3): while a switch transition is in flight -
|
|
214
|
+
// - worker register/heartbeat -> 409 with an explicit backoff hint (the
|
|
215
|
+
// design contract for existing workers; they retry on their interval
|
|
216
|
+
// and re-register after team.switch_completed);
|
|
217
|
+
// - task submission POSTs -> 503 + Retry-After;
|
|
218
|
+
// - a second POST /api/v1/team/profile -> 409 (handled inside that
|
|
219
|
+
// endpoint, which owns the step-0 validation order);
|
|
220
|
+
// Worker result/progress endpoints intentionally stay open: the drain step
|
|
221
|
+
// waits for exactly those in-flight completions.
|
|
222
|
+
const activeTransition = currentState?.transition;
|
|
223
|
+
if (activeTransition) {
|
|
224
|
+
if (req.method === "POST" && (pathname === WORKER_REGISTER_PATH || WORKER_HEARTBEAT_PATH_RE.test(pathname))) {
|
|
225
|
+
sendJson(res, 409, {
|
|
226
|
+
error: `Team profile switch to "${activeTransition.targetProfileId}" is in progress (phase: ${activeTransition.phase}); worker registration and heartbeat are temporarily rejected - back off and retry`,
|
|
227
|
+
retryAfterMs: SWITCH_WORKER_BACKOFF_HINT_MS,
|
|
228
|
+
transition: { phase: activeTransition.phase, targetProfileId: activeTransition.targetProfileId },
|
|
229
|
+
});
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (req.method === "POST" &&
|
|
233
|
+
(TRANSITION_BLOCKED_TASK_POST_PATHS.has(pathname) || TRANSITION_BLOCKED_TASK_POST_PATH_RES.some((re) => re.test(pathname)))) {
|
|
234
|
+
res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
|
|
235
|
+
sendJson(res, 503, {
|
|
236
|
+
error: `Team profile switch to "${activeTransition.targetProfileId}" is in progress (phase: ${activeTransition.phase}); task submission is temporarily unavailable - retry after the switch completes`,
|
|
237
|
+
retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
|
|
238
|
+
transition: { phase: activeTransition.phase, targetProfileId: activeTransition.targetProfileId },
|
|
239
|
+
});
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
// Review fix: a bundle import during a transition would run after the
|
|
243
|
+
// step-4 flip and stamp a repo field onto the new team even for profiles
|
|
244
|
+
// with git disabled - the switch itself re-prepares repo state for
|
|
245
|
+
// git-capable targets, so imports wait it out.
|
|
246
|
+
if (req.method === "POST" && pathname === "/api/v1/repo/import") {
|
|
247
|
+
res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
|
|
248
|
+
sendJson(res, 503, {
|
|
249
|
+
error: `Team profile switch to "${activeTransition.targetProfileId}" is in progress (phase: ${activeTransition.phase}); repo import is temporarily unavailable - retry after the switch completes`,
|
|
250
|
+
retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
|
|
251
|
+
transition: { phase: activeTransition.phase, targetProfileId: activeTransition.targetProfileId },
|
|
252
|
+
});
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// ==================== Capability 404 gates (Phase 2.3) ====================
|
|
257
|
+
// Steady-state existence gate, placed AFTER the transition matrix on
|
|
258
|
+
// purpose: while a switch is in flight the 503/409 transition semantics
|
|
259
|
+
// win over the steady-state 404 (e.g. repo import towards a git-less
|
|
260
|
+
// target reports "retry later" during the switch, "does not exist" after
|
|
261
|
+
// it). software-rd has all capabilities on, so this never fires there.
|
|
262
|
+
const gatedCapability = disabledCapabilityForPath(req.method ?? "", pathname);
|
|
263
|
+
if (gatedCapability) {
|
|
264
|
+
const profile = getActiveProfile();
|
|
265
|
+
sendJson(res, 404, {
|
|
266
|
+
error: `Team profile "${profile.id}" has the "${gatedCapability}" capability disabled - this endpoint does not exist for this team`,
|
|
267
|
+
capability: gatedCapability,
|
|
268
|
+
profileId: profile.id,
|
|
269
|
+
});
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
// ==================== Declarative route table (PR-D) ====================
|
|
273
|
+
// Single ordered match over ./route-table.ts's controllerRouteTable
|
|
274
|
+
// (array order = the pre-PR-D if/startsWith chain, one-to-one; see the
|
|
275
|
+
// parity test tests/test-route-table.mjs). Handlers may decline (return
|
|
276
|
+
// false) to continue matching; an exhausted table falls through to the
|
|
277
|
+
// final 404 below - both semantics are preserved from the old chain.
|
|
278
|
+
const handled = await dispatchRoutes(controllerRouteTable, {
|
|
279
|
+
req, res, requestUrl, pathname, deps, currentState,
|
|
280
|
+
});
|
|
281
|
+
if (!handled) {
|
|
282
|
+
sendError(res, 404, "Not found");
|
|
283
|
+
}
|
|
284
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Team Kickoff Orchestrator
|
|
3
|
+
*
|
|
4
|
+
* Implements the "Team Kickoff Meeting" pattern: before committing to an execution
|
|
5
|
+
* plan, the controller provisions candidate-role workers and asks each for a
|
|
6
|
+
* structured assessment of the requirement from their professional perspective.
|
|
7
|
+
*
|
|
8
|
+
* Flow:
|
|
9
|
+
* 1. Controller's initial LLM pass identifies complexity + candidate roles
|
|
10
|
+
* 2. Controller calls `teamclaw_request_kickoff` tool
|
|
11
|
+
* 3. This module provisions workers for each candidate role
|
|
12
|
+
* 4. Each worker receives a kickoff assessment request (lightweight LLM call)
|
|
13
|
+
* 5. Assessments are collected and returned to the controller
|
|
14
|
+
* 6. Controller synthesizes team input into final execution plan
|
|
15
|
+
* 7. Unneeded workers are reclaimed by the idle TTL mechanism
|
|
16
|
+
*/
|
|
17
|
+
// Phase 1.3: role data comes from the active TeamProfile loader.
|
|
18
|
+
import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
|
|
19
|
+
import { inferTaskRoleWithConfidence } from "./role-inference.js";
|
|
20
|
+
// ── Constants ────────────────────────────────────────────────────────────────
|
|
21
|
+
/** Maximum time to wait for all workers to register after provisioning. */
|
|
22
|
+
const WORKER_PROVISION_TIMEOUT_MS = 90_000;
|
|
23
|
+
/** Maximum time to wait for a single worker's kickoff assessment. */
|
|
24
|
+
const ASSESSMENT_TIMEOUT_MS = 120_000;
|
|
25
|
+
/** Poll interval when waiting for workers to appear in state. */
|
|
26
|
+
const WORKER_POLL_INTERVAL_MS = 2_000;
|
|
27
|
+
// ── Public API ───────────────────────────────────────────────────────────────
|
|
28
|
+
export async function runKickoffMeeting(request, deps) {
|
|
29
|
+
const { logger } = deps;
|
|
30
|
+
const { requirement, candidateRoles, complexity } = request;
|
|
31
|
+
// Validate roles
|
|
32
|
+
// Resolved per call so the set always reflects the active profile.
|
|
33
|
+
const validRoles = candidateRoles.filter((r) => getActiveRoleIds().includes(r));
|
|
34
|
+
if (validRoles.length === 0) {
|
|
35
|
+
return buildEmptyResult(complexity, "No valid candidate roles provided.");
|
|
36
|
+
}
|
|
37
|
+
logger.info(`Kickoff: starting team meeting — complexity=${complexity}, candidates=[${validRoles.join(", ")}]`);
|
|
38
|
+
// Phase 1: Provision all candidate role workers in parallel
|
|
39
|
+
const provisionPromises = validRoles.map(async (role) => {
|
|
40
|
+
try {
|
|
41
|
+
await deps.ensureRoleProvisioned(role);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
logger.warn(`Kickoff: failed to provision ${role}: ${err instanceof Error ? err.message : String(err)}`);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
await Promise.all(provisionPromises);
|
|
48
|
+
// Phase 2: Wait for workers to appear in state
|
|
49
|
+
const availableWorkers = await waitForWorkers(validRoles, deps);
|
|
50
|
+
if (availableWorkers.size === 0) {
|
|
51
|
+
return buildEmptyResult(complexity, "No workers became available within the provisioning timeout.");
|
|
52
|
+
}
|
|
53
|
+
logger.info(`Kickoff: ${availableWorkers.size}/${validRoles.length} workers available — requesting assessments`);
|
|
54
|
+
// Phase 3: Send assessment requests to all available workers in parallel
|
|
55
|
+
const assessments = [];
|
|
56
|
+
const assessmentPromises = [...availableWorkers.entries()].map(async ([role, worker]) => {
|
|
57
|
+
try {
|
|
58
|
+
const assessment = await deps.requestWorkerAssessment(worker, requirement);
|
|
59
|
+
assessment.role = role; // ensure role is set correctly
|
|
60
|
+
assessments.push(assessment);
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
logger.warn(`Kickoff: assessment failed for ${role}: ${err instanceof Error ? err.message : String(err)}`);
|
|
64
|
+
// Record a failed assessment so the controller knows this role didn't respond
|
|
65
|
+
assessments.push({
|
|
66
|
+
role,
|
|
67
|
+
needed: false,
|
|
68
|
+
scope: `Assessment failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
69
|
+
suggestedTasks: [],
|
|
70
|
+
dependencies: [],
|
|
71
|
+
risks: [`Could not assess — ${err instanceof Error ? err.message : "unknown error"}`],
|
|
72
|
+
questions: [],
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
await Promise.all(assessmentPromises);
|
|
77
|
+
// Phase 4: Build the kickoff plan
|
|
78
|
+
const plan = {
|
|
79
|
+
complexity,
|
|
80
|
+
candidateRoles: validRoles,
|
|
81
|
+
assessments,
|
|
82
|
+
completed: true,
|
|
83
|
+
};
|
|
84
|
+
const summary = buildKickoffSummary(plan, requirement);
|
|
85
|
+
logger.info(`Kickoff: team meeting complete — ${assessments.filter((a) => a.needed).length}/${assessments.length} roles needed`);
|
|
86
|
+
return { plan, summary };
|
|
87
|
+
}
|
|
88
|
+
// ── Internal helpers ─────────────────────────────────────────────────────────
|
|
89
|
+
async function waitForWorkers(roles, deps) {
|
|
90
|
+
const deadline = Date.now() + WORKER_PROVISION_TIMEOUT_MS;
|
|
91
|
+
const result = new Map();
|
|
92
|
+
while (Date.now() < deadline) {
|
|
93
|
+
const state = deps.getTeamState();
|
|
94
|
+
if (state) {
|
|
95
|
+
for (const role of roles) {
|
|
96
|
+
if (result.has(role))
|
|
97
|
+
continue;
|
|
98
|
+
const worker = Object.values(state.workers).find((w) => w.role === role && (w.status === "idle" || w.status === "busy"));
|
|
99
|
+
if (worker) {
|
|
100
|
+
result.set(role, worker);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (result.size === roles.length) {
|
|
104
|
+
break; // all workers found
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
await sleep(WORKER_POLL_INTERVAL_MS);
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
function buildEmptyResult(complexity, reason) {
|
|
112
|
+
return {
|
|
113
|
+
plan: {
|
|
114
|
+
complexity,
|
|
115
|
+
candidateRoles: [],
|
|
116
|
+
assessments: [],
|
|
117
|
+
completed: true,
|
|
118
|
+
},
|
|
119
|
+
summary: `Team kickoff could not be completed: ${reason} Proceed with controller-only planning.`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function buildKickoffSummary(plan, _requirement) {
|
|
123
|
+
const parts = [];
|
|
124
|
+
parts.push(`## Team Kickoff Meeting Results (${plan.complexity} complexity)`);
|
|
125
|
+
parts.push("");
|
|
126
|
+
const needed = plan.assessments.filter((a) => a.needed);
|
|
127
|
+
const notNeeded = plan.assessments.filter((a) => !a.needed);
|
|
128
|
+
if (needed.length > 0) {
|
|
129
|
+
parts.push("### Roles Confirmed Needed");
|
|
130
|
+
for (const a of needed) {
|
|
131
|
+
const roleDef = getActiveRole(a.role);
|
|
132
|
+
const icon = roleDef?.icon ?? "•";
|
|
133
|
+
parts.push(`\n**${icon} ${roleDef?.label ?? a.role}**`);
|
|
134
|
+
parts.push(`- Scope: ${a.scope}`);
|
|
135
|
+
if (a.suggestedTasks.length > 0) {
|
|
136
|
+
parts.push(`- Suggested tasks: ${a.suggestedTasks.join("; ")}`);
|
|
137
|
+
}
|
|
138
|
+
if (a.dependencies.length > 0) {
|
|
139
|
+
parts.push(`- Dependencies: ${a.dependencies.join("; ")}`);
|
|
140
|
+
}
|
|
141
|
+
if (a.risks.length > 0) {
|
|
142
|
+
parts.push(`- Risks: ${a.risks.join("; ")}`);
|
|
143
|
+
}
|
|
144
|
+
if (a.questions.length > 0) {
|
|
145
|
+
parts.push(`- Questions: ${a.questions.join("; ")}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (notNeeded.length > 0) {
|
|
150
|
+
parts.push("");
|
|
151
|
+
parts.push("### Roles Not Needed");
|
|
152
|
+
for (const a of notNeeded) {
|
|
153
|
+
const roleDef = getActiveRole(a.role);
|
|
154
|
+
parts.push(`- ${roleDef?.icon ?? "•"} ${roleDef?.label ?? a.role}: ${a.scope}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
parts.push("");
|
|
158
|
+
parts.push("### Team Consensus");
|
|
159
|
+
parts.push(`- Required roles: ${needed.map((a) => a.role).join(", ") || "none identified"}`);
|
|
160
|
+
const allTasks = needed.flatMap((a) => a.suggestedTasks.map((t) => `[${a.role}] ${t}`));
|
|
161
|
+
if (allTasks.length > 0) {
|
|
162
|
+
parts.push("- Suggested task breakdown:");
|
|
163
|
+
for (const t of allTasks) {
|
|
164
|
+
parts.push(` - ${t}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const allDeps = needed.flatMap((a) => a.dependencies);
|
|
168
|
+
if (allDeps.length > 0) {
|
|
169
|
+
parts.push(`- Cross-role dependencies: ${[...new Set(allDeps)].join("; ")}`);
|
|
170
|
+
}
|
|
171
|
+
const allRisks = needed.flatMap((a) => a.risks);
|
|
172
|
+
if (allRisks.length > 0) {
|
|
173
|
+
parts.push(`- Team risks: ${[...new Set(allRisks)].join("; ")}`);
|
|
174
|
+
}
|
|
175
|
+
const allQuestions = needed.flatMap((a) => a.questions);
|
|
176
|
+
if (allQuestions.length > 0) {
|
|
177
|
+
parts.push(`- Unresolved questions: ${[...new Set(allQuestions)].join("; ")}`);
|
|
178
|
+
}
|
|
179
|
+
parts.push("");
|
|
180
|
+
parts.push("Use these team assessments to create the final execution plan. Only create tasks for roles that confirmed they are needed. Respect the dependency ordering suggested by the team.");
|
|
181
|
+
return parts.join("\n");
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Build the kickoff assessment prompt sent to a worker.
|
|
185
|
+
* The worker should respond with structured JSON matching KickoffAssessment.
|
|
186
|
+
*/
|
|
187
|
+
export function buildKickoffAssessmentPrompt(role, requirement) {
|
|
188
|
+
const roleDef = getActiveRole(role);
|
|
189
|
+
const roleLabel = roleDef?.label ?? role;
|
|
190
|
+
return [
|
|
191
|
+
`You are the ${roleLabel} in a virtual software team.`,
|
|
192
|
+
`Your team is conducting a kickoff meeting for a new requirement.`,
|
|
193
|
+
``,
|
|
194
|
+
`## Requirement`,
|
|
195
|
+
requirement,
|
|
196
|
+
``,
|
|
197
|
+
`## Your Task`,
|
|
198
|
+
`Evaluate this requirement from your professional perspective as ${roleLabel}.`,
|
|
199
|
+
`Respond with a JSON object (and nothing else) with these fields:`,
|
|
200
|
+
``,
|
|
201
|
+
`{`,
|
|
202
|
+
` "needed": boolean, // Is your role needed for this project?`,
|
|
203
|
+
` "scope": string, // What would you contribute? (1-2 sentences)`,
|
|
204
|
+
` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
|
|
205
|
+
` "dependencies": string[], // What you need from other roles before or during your work`,
|
|
206
|
+
` "risks": string[], // Concerns or risks from your perspective`,
|
|
207
|
+
` "questions": string[] // Clarifications you'd want before starting`,
|
|
208
|
+
`}`,
|
|
209
|
+
``,
|
|
210
|
+
`Guidelines:`,
|
|
211
|
+
`- Be honest about whether your role is truly needed. Don't inflate your importance.`,
|
|
212
|
+
`- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
|
|
213
|
+
`- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
|
|
214
|
+
`- Keep suggestedTasks concrete and actionable, not vague.`,
|
|
215
|
+
`- Only list dependencies on roles that are actually relevant.`,
|
|
216
|
+
`- Return ONLY the JSON object, no markdown fencing, no explanation.`,
|
|
217
|
+
].join("\n");
|
|
218
|
+
}
|
|
219
|
+
function sleep(ms) {
|
|
220
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
221
|
+
}
|
|
222
|
+
export async function resolveTaskRoleWithLlmFallback(task, deps = {}) {
|
|
223
|
+
const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
|
|
224
|
+
if (!verdict.needsLlmFallback) {
|
|
225
|
+
return verdict.role;
|
|
226
|
+
}
|
|
227
|
+
if (deps.llmRoleJudge) {
|
|
228
|
+
try {
|
|
229
|
+
const judged = await deps.llmRoleJudge({ task, verdict });
|
|
230
|
+
const validated = validateActiveRoleId(judged);
|
|
231
|
+
if (validated) {
|
|
232
|
+
deps.logger?.info(`RoleInference: LLM fallback judged role ${validated} (token fast path refused: ${verdict.reason})`);
|
|
233
|
+
return validated;
|
|
234
|
+
}
|
|
235
|
+
deps.logger?.warn(`RoleInference: LLM fallback returned ${JSON.stringify(judged)} which is not a role of the active profile; using defaultRole`);
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
deps.logger?.warn(`RoleInference: LLM fallback failed (${err instanceof Error ? err.message : String(err)}); using defaultRole`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
deps.logger?.info(`RoleInference: token fast path refused to decide (${verdict.reason}) and no LLM fallback is wired; using defaultRole`);
|
|
243
|
+
}
|
|
244
|
+
return getActiveDefaultRole();
|
|
245
|
+
}
|
|
246
|
+
export { ASSESSMENT_TIMEOUT_MS };
|