@teamclaws/teamclaw 2026.11.1 → 2026.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/cli.mjs +96 -11
  2. package/dist/index.js +7 -0
  3. package/dist/src/controller/config-routes.js +138 -0
  4. package/dist/src/controller/http-server.js +18 -0
  5. package/dist/src/controller/journal.js +68 -0
  6. package/dist/src/controller/provisioning/process-supervisor.js +58 -2
  7. package/dist/src/controller/provisioning-config.js +53 -0
  8. package/dist/src/controller/route-table.js +11 -0
  9. package/dist/src/controller/security.js +39 -0
  10. package/dist/src/controller/teamauto-routes.js +12 -0
  11. package/dist/src/controller/tunnel-manager.js +33 -1
  12. package/dist/src/controller/tunnel-routes.js +17 -1
  13. package/dist/src/controller/websocket.js +4 -0
  14. package/dist/src/controller/worker-provisioning.js +36 -0
  15. package/dist/src/openclaw-workspace.js +36 -0
  16. package/dist/src/state.js +77 -1
  17. package/dist/src/teamauto/github-client.js +33 -0
  18. package/dist/src/teamauto/scanner.js +30 -3
  19. package/dist/src/teamauto/scheduler.js +300 -18
  20. package/dist/src/teamauto/store.js +9 -0
  21. package/dist/src/ui/app.js +188 -11
  22. package/dist/src/ui/index.html +38 -0
  23. package/index.ts +8 -0
  24. package/openclaw.plugin.json +1 -1
  25. package/package.json +1 -1
  26. package/src/controller/config-routes.ts +152 -0
  27. package/src/controller/http-server.ts +18 -0
  28. package/src/controller/journal.ts +89 -0
  29. package/src/controller/provisioning/process-supervisor.ts +56 -2
  30. package/src/controller/provisioning-config.ts +54 -0
  31. package/src/controller/route-table.ts +11 -0
  32. package/src/controller/security.ts +40 -0
  33. package/src/controller/teamauto-routes.ts +12 -0
  34. package/src/controller/tunnel-manager.ts +34 -1
  35. package/src/controller/tunnel-routes.ts +18 -1
  36. package/src/controller/websocket.ts +6 -0
  37. package/src/controller/worker-provisioning.ts +34 -0
  38. package/src/openclaw-workspace.ts +47 -0
  39. package/src/state.ts +73 -2
  40. package/src/teamauto/github-client.ts +36 -0
  41. package/src/teamauto/scanner.ts +31 -4
  42. package/src/teamauto/scheduler.ts +303 -18
  43. package/src/teamauto/store.ts +36 -1
  44. package/src/ui/app.js +188 -11
  45. package/src/ui/index.html +38 -0
package/cli.mjs CHANGED
@@ -20,6 +20,7 @@ const PACKAGE_INSTALL_SPEC = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;
20
20
  const PLUGIN_ID = "teamclaw";
21
21
  const DANGEROUS_INSTALL_FLAG = "--dangerously-force-unsafe-install";
22
22
  const CAPABILITY_CONSENT_FLAG = "--accept-capabilities";
23
+ const FORCE_INSTALL_FLAG = "--force";
23
24
 
24
25
  /**
25
26
  * OpenClaw 2026.10+ replaced the legacy break-glass install flag (now a
@@ -32,6 +33,19 @@ const CAPABILITY_CONSENT_FLAG = "--accept-capabilities";
32
33
  function isCapabilityConsentRequired(output) {
33
34
  return /accept-capabilities|capability[\s-]?consent|CapabilityConsentRequired/i.test(String(output || ""));
34
35
  }
36
+
37
+ /**
38
+ * openclaw 2026.10+ retired the legacy break-glass install flag (now a
39
+ * deprecated no-op) and cancels any install from a source outside ClawHub
40
+ * review/trust metadata — local package directories and npm-registry packages
41
+ * alike — asking the operator to rerun with --force after reviewing the
42
+ * source. This source gate cancels before the capability-consent check, so
43
+ * the capability error never surfaces on its own and both consents must be
44
+ * appended on the retry (issue #261).
45
+ */
46
+ function isSourceTrustGateCancel(output) {
47
+ return /rerun with --force|outside ClawHub review/i.test(String(output || ""));
48
+ }
35
49
  const DEFAULT_TEAMCLAW_IMAGE = "ghcr.io/topcheer/teamclaw-openclaw:latest";
36
50
  const DEFAULT_CONTROLLER_PORT = 9527;
37
51
  const DEFAULT_WORKER_PORT = 9528;
@@ -44,6 +58,16 @@ const TEAMCLAW_AGENT_ID = "teamclaw";
44
58
  const TEAMCLAW_RECOMMENDED_EXEC_SECURITY = "full";
45
59
  const TEAMCLAW_RECOMMENDED_EXEC_ASK = "off";
46
60
  const TEAMCLAW_RECOMMENDED_COMMAND_MODE = "auto";
61
+ /**
62
+ * The installer historically wrote commands.ownerDisplay="raw" as a host
63
+ * default. openclaw 2026.11 renders owner ids raw when the key is absent and
64
+ * its doctor now removes the key outright, while openclaw 2026.10.x config
65
+ * validation rejects the key as unrecognized — poisoning every later host CLI
66
+ * invocation after an install (issue #261). This value is what the installer
67
+ * used to write and what it now prunes; explicit non-default user choices are
68
+ * preserved.
69
+ */
70
+ const TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT = "raw";
47
71
  const AGENT_MODE_OPTIONS = [
48
72
  {
49
73
  value: "independent",
@@ -67,8 +91,27 @@ let ROLE_OPTIONS = [];
67
91
  let DEFAULT_WORKER_ROLE = "";
68
92
 
69
93
  async function loadRoleOptions() {
94
+ // #253 layout-adaptive loading via VARIABLE specifiers: bundlers and the
95
+ // image's dist-import checker treat a LITERAL dynamic import whose target
96
+ // does not exist in the current layout (./dist/src/roles.js is a phantom
97
+ // under the image's flat bundle; ./index.js does not exist in the npm
98
+ // tarball) as an unresolved edge and fail the build. A runtime variable
99
+ // defeats static resolution on purpose: whichever layout this file ships
100
+ // in resolves exactly one of the candidates.
101
+ const ROLE_MODULE_CANDIDATES = ["./dist/src/roles.js", "./index.js"];
102
+ let rolesModule = null;
103
+ for (const candidate of ROLE_MODULE_CANDIDATES) {
104
+ try {
105
+ rolesModule = await import(candidate);
106
+ break;
107
+ } catch {
108
+ // try the next layout
109
+ }
110
+ }
70
111
  try {
71
- const rolesModule = await import("./dist/src/roles.js");
112
+ if (!rolesModule) {
113
+ throw new Error("no role registry module found in any known layout");
114
+ }
72
115
  const roles = Array.isArray(rolesModule.ROLES) ? rolesModule.ROLES : [];
73
116
  ROLE_OPTIONS = roles
74
117
  .filter((role) => role && typeof role.id === "string" && role.id.trim())
@@ -81,9 +124,9 @@ async function loadRoleOptions() {
81
124
  ? registryDefault
82
125
  : "";
83
126
  } catch {
84
- // dist not built yet (dev checkout). Keep the registry empty so callers
85
- // fail with the actionable guidance in ensureRoleOptionsLoaded instead
86
- // of presenting a stale role list.
127
+ // Neither layout resolvable (pre-build dev checkout). Keep the registry
128
+ // empty so callers fail with the actionable guidance in
129
+ // ensureRoleOptionsLoaded instead of presenting a stale role list.
87
130
  ROLE_OPTIONS = [];
88
131
  DEFAULT_WORKER_ROLE = "";
89
132
  }
@@ -92,7 +135,7 @@ async function loadRoleOptions() {
92
135
  function ensureRoleOptionsLoaded() {
93
136
  if (ROLE_OPTIONS.length === 0) {
94
137
  throw new Error(
95
- "TeamClaw role registry unavailable (./dist/src/roles.js). Run `npm --prefix src run build` in the repository, or reinstall the @teamclaws/teamclaw package, then retry.",
138
+ "TeamClaw role registry unavailable (tried ./dist/src/roles.js and ./index.js). Run `npm --prefix src run build` in the repository, or reinstall the @teamclaws/teamclaw package, then retry.",
96
139
  );
97
140
  }
98
141
  }
@@ -655,6 +698,36 @@ async function writeConfig(configPath, config) {
655
698
  await fs.writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
656
699
  }
657
700
 
701
+ /**
702
+ * openclaw 2026.10.x config validation rejects the retired commands.ownerDisplay
703
+ * key ("Unrecognized key"), so a config still carrying the value written by an
704
+ * earlier installer deadlocks every host CLI invocation — including the plugin
705
+ * install this run is about to attempt (issue #261). Prune the
706
+ * installer-written "raw" default before any host command runs: the value is
707
+ * openclaw 2026.11's built-in default, and explicit non-default user choices
708
+ * are left untouched.
709
+ */
710
+ async function pruneInstallerWrittenOwnerDisplay(configPath) {
711
+ let config;
712
+ try {
713
+ config = await readOpenClawConfig(configPath);
714
+ } catch {
715
+ // Unparseable config: leave it alone; the host CLI and the existing
716
+ // config-parse error path will surface the problem.
717
+ return false;
718
+ }
719
+ const commands = isRecord(config.commands) ? config.commands : null;
720
+ if (!commands || commands.ownerDisplay !== TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT) {
721
+ return false;
722
+ }
723
+ delete commands.ownerDisplay;
724
+ await writeConfig(configPath, config);
725
+ console.log(
726
+ `Removed commands.ownerDisplay from ${configPath}: the key is retired, openclaw 2026.10.x rejects it as unrecognized (which blocks every OpenClaw command), and openclaw renders owner ids raw by default.`,
727
+ );
728
+ return true;
729
+ }
730
+
658
731
  function getExistingTeamClawConfig(config) {
659
732
  if (!isRecord(config)) {
660
733
  return {};
@@ -1334,7 +1407,7 @@ function attemptPluginInstall({ configPath }) {
1334
1407
  }
1335
1408
  }
1336
1409
  console.log(
1337
- `\nTeamClaw uses host-level orchestration capabilities, so OpenClaw requires an install consent flag during plugin installation (legacy: ${DANGEROUS_INSTALL_FLAG}; OpenClaw 2026.10+: ${CAPABILITY_CONSENT_FLAG}).`,
1410
+ `\nTeamClaw uses host-level orchestration capabilities, so OpenClaw requires install consent flags during plugin installation (legacy: ${DANGEROUS_INSTALL_FLAG}; OpenClaw 2026.10+: ${FORCE_INSTALL_FLAG} ${CAPABILITY_CONSENT_FLAG}).`,
1338
1411
  );
1339
1412
  const candidates = [
1340
1413
  {
@@ -1389,12 +1462,14 @@ function attemptPluginInstall({ configPath }) {
1389
1462
  if (
1390
1463
  result.status !== 0 &&
1391
1464
  !candidate.args.includes(CAPABILITY_CONSENT_FLAG) &&
1392
- isCapabilityConsentRequired(result.output)
1465
+ (isCapabilityConsentRequired(result.output) || isSourceTrustGateCancel(result.output))
1393
1466
  ) {
1394
- console.log("OpenClaw requires capability consent; retrying with --accept-capabilities...");
1467
+ console.log(
1468
+ `OpenClaw requires install consent; retrying with ${FORCE_INSTALL_FLAG} and ${CAPABILITY_CONSENT_FLAG}...`,
1469
+ );
1395
1470
  result = installPluginWithCommand(
1396
1471
  candidate.command,
1397
- [...candidate.args, CAPABILITY_CONSENT_FLAG],
1472
+ [...candidate.args, FORCE_INSTALL_FLAG, CAPABILITY_CONSENT_FLAG],
1398
1473
  env,
1399
1474
  );
1400
1475
  }
@@ -1879,8 +1954,12 @@ function applyTeamClawHostRuntimeDefaults(next) {
1879
1954
  if (typeof commands.restart !== "boolean") {
1880
1955
  commands.restart = true;
1881
1956
  }
1882
- if (typeof commands.ownerDisplay !== "string" || !commands.ownerDisplay.trim()) {
1883
- commands.ownerDisplay = "raw";
1957
+ if (commands.ownerDisplay === TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT) {
1958
+ // openclaw 2026.10.x rejects this retired key ("Unrecognized key"), which
1959
+ // deadlocks every later host CLI invocation; openclaw 2026.11 renders
1960
+ // owner ids raw by default anyway. Prune the installer-written default
1961
+ // and keep explicit non-default user choices (issue #261).
1962
+ delete commands.ownerDisplay;
1884
1963
  }
1885
1964
 
1886
1965
  const tools = ensureRecord(next, "tools");
@@ -2254,6 +2333,12 @@ async function runInstall(options) {
2254
2333
  : `Created ${configPath}`);
2255
2334
  }
2256
2335
 
2336
+ if (!options.dryRun) {
2337
+ // Heal configs poisoned by earlier installers before any host OpenClaw
2338
+ // command runs (issue #261).
2339
+ await pruneInstallerWrittenOwnerDisplay(configPath);
2340
+ }
2341
+
2257
2342
  let pluginInstallStatus = "skipped";
2258
2343
  let pluginInstallMethod = "";
2259
2344
  let pluginInstallError = "";
package/dist/index.js CHANGED
@@ -18,6 +18,13 @@ import { installRecommendedSkills } from "./src/worker/skill-installer.js";
18
18
  // W6 of issue #226: local swallowing pathExists copy replaced by the shared
19
19
  // one (identical semantics; alias keeps the call site byte-identical).
20
20
  import { pathExistsTolerant as pathExists } from "./src/shared/utils.js";
21
+ // #253: the image build compiles this plugin into a flat rolldown bundle
22
+ // (dist/extensions/teamclaw/index.js) with NO nested dist/src tree, while the
23
+ // npm tarball layout ships dist/src/roles.js and no top-level index.js. The
24
+ // installer CLI (cli.mjs) reads the role registry through whichever layout it
25
+ // lands in, so the registry must be reachable from this entry as a named
26
+ // export for the bundled layout to resolve it.
27
+ export { ROLES, DEFAULT_ROLE } from "./src/roles.js";
21
28
  export default definePluginEntry({
22
29
  id: "teamclaw",
23
30
  name: "TeamClaw",
@@ -0,0 +1,138 @@
1
+ // Hot-reloadable worker-provisioning configuration routes (runtime scaling).
2
+ //
3
+ // GET /api/v1/team/config -> read-only snapshot of the hot-reloadable fields
4
+ // PATCH /api/v1/team/config -> whitelist-only update that
5
+ // 1. mutates deps.config IN MEMORY (the provisioner reads these fields on
6
+ // every computeRoleDemand pass, so the change applies on the next
7
+ // reconcile tick — no restart),
8
+ // 2. persists to the host openclaw.json plugins.entries.teamclaw.config
9
+ // (same read-modify-write pattern as updateTeamClawModelConfig), and
10
+ // 3. pokes the provisioner via requestReconcile + broadcasts a
11
+ // team:config_updated WS event so desktop/web UIs refresh.
12
+ //
13
+ // Deployment-shape behavior (issue context: all deployment forms):
14
+ // - process / managed-gateway / desktop-private / tunnel: memory + host-config
15
+ // persistence (resolveDefaultOpenClawConfigPath honors OPENCLAW_HOME /
16
+ // OPENCLAW_CONFIG_PATH, so sandboxed instances persist into their own home).
17
+ // - docker (controller on host): same as process — host config is writable.
18
+ // - docker/k8s (controller itself containerized): container FS is ephemeral,
19
+ // so persistence degrades to memory-only and the response carries
20
+ // persistenceMode: "memory-only" + a restart note (declared behavior, not
21
+ // a silent drop). k8s deployments should source config from ConfigMap and
22
+ // treat this API as runtime-only scaling.
23
+ // Scale-down semantics: lowering maxPerRole never kills active workers; idle
24
+ // workers drain via workerProvisioningIdleTtlMs and the cap stops refills.
25
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
26
+ import { updateTeamClawProvisioningConfig } from "../openclaw-workspace.js";
27
+ /** Fields a PATCH may touch. Everything else in PluginConfig is rejected. */
28
+ const HOT_CONFIG_FIELDS = [
29
+ "workerProvisioningMaxPerRole",
30
+ "workerProvisioningMinPerRole",
31
+ "workerProvisioningIdleTtlMs",
32
+ ];
33
+ const BOUNDS = {
34
+ workerProvisioningMaxPerRole: { min: 1, max: 50 },
35
+ workerProvisioningMinPerRole: { min: 0, max: 50 },
36
+ // 1s floor keeps the idle reaper from churn-looping; 24h ceiling is generous.
37
+ workerProvisioningIdleTtlMs: { min: 1_000, max: 86_400_000 },
38
+ };
39
+ function teamConfigGetRoute(ctx) {
40
+ const { res, deps } = ctx;
41
+ const c = deps.config;
42
+ sendJson(res, 200, {
43
+ workerProvisioningType: c.workerProvisioningType,
44
+ workerProvisioningDisabled: c.workerProvisioningDisabled,
45
+ workerProvisioningMinPerRole: c.workerProvisioningMinPerRole,
46
+ workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
47
+ workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
48
+ // k8s controllers run on ephemeral container FS: declare it up front.
49
+ persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
50
+ });
51
+ }
52
+ async function teamConfigPatchRoute(ctx) {
53
+ const { req, res, deps } = ctx;
54
+ let body = null;
55
+ try {
56
+ body = (await parseJsonBody(req));
57
+ }
58
+ catch {
59
+ sendError(res, 400, "invalid JSON body");
60
+ return;
61
+ }
62
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
63
+ sendError(res, 400, "JSON object body required");
64
+ return;
65
+ }
66
+ const unknown = Object.keys(body).filter((k) => !HOT_CONFIG_FIELDS.includes(k));
67
+ if (unknown.length > 0) {
68
+ sendError(res, 400, `unknown or non-hot-reloadable field(s): ${unknown.join(", ")}`);
69
+ return;
70
+ }
71
+ const update = {};
72
+ for (const field of HOT_CONFIG_FIELDS) {
73
+ if (body[field] === undefined)
74
+ continue;
75
+ const raw = body[field];
76
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
77
+ sendError(res, 400, `${field} must be a finite number`);
78
+ return;
79
+ }
80
+ const { min, max } = BOUNDS[field];
81
+ update[field] = Math.max(min, Math.min(max, Math.floor(raw)));
82
+ }
83
+ if (Object.keys(update).length === 0) {
84
+ sendError(res, 400, `at least one of ${HOT_CONFIG_FIELDS.join(", ")} is required`);
85
+ return;
86
+ }
87
+ // 1) In-memory hot apply (deps.config is a live reference the provisioner
88
+ // reads on every demand computation — no restart needed).
89
+ const applied = {};
90
+ for (const [field, value] of Object.entries(update)) {
91
+ deps.config[field] = value;
92
+ applied[field] = value;
93
+ }
94
+ // Keep the min<=max invariant types.ts enforces at parse time.
95
+ const minR = update.workerProvisioningMinPerRole ?? deps.config.workerProvisioningMinPerRole;
96
+ if (deps.config.workerProvisioningMaxPerRole < minR) {
97
+ deps.config.workerProvisioningMaxPerRole = minR;
98
+ applied.workerProvisioningMaxPerRole = minR;
99
+ }
100
+ // 2) Persist (host config) unless the controller itself runs on an
101
+ // ephemeral container FS.
102
+ const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
103
+ let persisted = false;
104
+ if (!memoryOnly) {
105
+ try {
106
+ await updateTeamClawProvisioningConfig(applied, {
107
+ warn: (message) => deps.logger.info(message),
108
+ });
109
+ persisted = true;
110
+ }
111
+ catch (err) {
112
+ // Memory already applied — report partial success honestly.
113
+ deps.logger.warn(`TeamClaw: hot config applied in memory but host-config persist failed: ${err instanceof Error ? err.message : String(err)}`);
114
+ }
115
+ }
116
+ // 3) Poke the provisioner so the new caps apply immediately instead of
117
+ // waiting for the next periodic reconcile tick, then tell UIs.
118
+ try {
119
+ await deps.workerProvisioningManager?.requestReconcile("team-config-hot-update");
120
+ }
121
+ catch (err) {
122
+ deps.logger.warn(`TeamClaw: config hot-update reconcile poke failed: ${err instanceof Error ? err.message : String(err)}`);
123
+ }
124
+ deps.wsServer.broadcastUpdate({ type: "team:config_updated", data: { ...applied, persisted } });
125
+ deps.logger.info(`TeamClaw: worker provisioning config hot-updated: ${JSON.stringify(applied)} (persisted=${persisted})`);
126
+ sendJson(res, 200, {
127
+ ok: true,
128
+ applied,
129
+ persisted,
130
+ persistenceMode: persisted ? "host-config" : "memory-only",
131
+ ...(persisted
132
+ ? {}
133
+ : {
134
+ restartNote: "Applied in memory only; this deployment shape does not persist to a durable host config — after a gateway restart the config reverts to its persisted source.",
135
+ }),
136
+ });
137
+ }
138
+ export { teamConfigGetRoute, teamConfigPatchRoute };
@@ -212,6 +212,7 @@ export function createControllerHttpServer(deps) {
212
212
  verifyUpgrade: createWebSocketUpgradeGuard({
213
213
  ...deps,
214
214
  isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
215
+ gateAllows: (req) => tunnelManagerSingleton?.gateAllows(req) ?? false,
215
216
  }),
216
217
  });
217
218
  // Plugin shutdown: kill the local connector and tear down the remote
@@ -227,6 +228,23 @@ export function createControllerHttpServer(deps) {
227
228
  void tunnelManagerSingleton.recover().catch((err) => {
228
229
  logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
229
230
  });
231
+ // Shutdown counterpart of the boot recover above: when the gateway process
232
+ // stops (SIGTERM/SIGINT - e.g. a config change restarting the plugin, or
233
+ // launchctl kickstart), detach() kills ONLY the local connector and keeps
234
+ // both tunnel-state.json and the remote relay tunnel alive, so the next
235
+ // boot's recover() reconnects the SAME tunnel. Without this, the
236
+ // connector's exit handler ran mid-shutdown, cleared the state file and
237
+ // DELETEd the relay tunnel - after which nothing could recover and the
238
+ // hostname served 530 (issue timeline: 2026-11-12, two consecutive
239
+ // restarts). Idempotent and safe to register repeatedly per http server.
240
+ for (const signal of ["SIGTERM", "SIGINT"]) {
241
+ process.on(signal, () => {
242
+ try {
243
+ tunnelManagerSingleton?.detach();
244
+ }
245
+ catch { /* best effort during shutdown */ }
246
+ });
247
+ }
230
248
  setTimeout(() => {
231
249
  const state = deps.getTeamState();
232
250
  const pendingCount = state
@@ -0,0 +1,68 @@
1
+ // Controller activity journal (#ui-blindness): an in-memory ring of recent
2
+ // controller-side events, plus a tail reader for the teamclaw-relevant slice
3
+ // of the host gateway log. The web UI's Activity tab polls the journal and
4
+ // follows the log tail so operators can SEE provisioning, sweeps, task
5
+ // routing and tunnel lifecycle without ssh-ing into logs.
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { sendJson } from "../protocol.js";
10
+ const RING_LIMIT = 400;
11
+ const ring = [];
12
+ /** Record a controller event into the ring (callers also broadcast it). */
13
+ export function journalRecord(source, type, summary) {
14
+ ring.push({ at: Date.now(), source, type, summary: summary.slice(0, 240) });
15
+ if (ring.length > RING_LIMIT)
16
+ ring.splice(0, ring.length - RING_LIMIT);
17
+ }
18
+ /** Summarize a broadcast WS event into the journal (best effort, never throws). */
19
+ export function journalFromWsEvent(event) {
20
+ try {
21
+ const t = String(event.type ?? "unknown");
22
+ if (t === "task:created" || t === "task:completed" || t === "task:updated" || t === "worker:online" || t === "worker:offline" || t === "team:config_updated" || t === "controller:run") {
23
+ journalRecord("ws", t, JSON.stringify(event.data ?? {}).slice(0, 200));
24
+ }
25
+ }
26
+ catch { /* journal must never break broadcasting */ }
27
+ }
28
+ export function journalSnapshot(limit = 200) {
29
+ return ring.slice(-Math.min(limit, RING_LIMIT));
30
+ }
31
+ // ---------------------------------------------------------------------------
32
+ // Host gateway log tail (read-only). The teamclaw plugin logs land in the
33
+ // openclaw gateway log; filter to the teamclaw-relevant lines.
34
+ // ---------------------------------------------------------------------------
35
+ const TEAMCLAW_LOG_FILTER = /TeamClaw|TeamAuto|Provisioner|ProvisionedWorker|TaskRouter|tunnel|Controller:/i;
36
+ function gatewayLogCandidates() {
37
+ const home = process.env.OPENCLAW_HOME || path.join(os.homedir(), ".openclaw");
38
+ return [
39
+ process.env.TEAMCLAW_GATEWAY_LOG,
40
+ path.join(home, "logs", "gateway.log"),
41
+ path.join(process.env.HOME ?? "", "Library", "Logs", "openclaw", "gateway.log"),
42
+ ].filter((p) => Boolean(p));
43
+ }
44
+ export function readGatewayLogTail(lines = 200, filter = true) {
45
+ for (const candidate of gatewayLogCandidates()) {
46
+ try {
47
+ const raw = fs.readFileSync(candidate, "utf8");
48
+ const all = raw.split("\n").filter((l) => l.trim().length > 0);
49
+ const picked = filter ? all.filter((l) => TEAMCLAW_LOG_FILTER.test(l)) : all;
50
+ return { path: candidate, lines: picked.slice(-lines) };
51
+ }
52
+ catch {
53
+ // try next candidate
54
+ }
55
+ }
56
+ return { path: null, lines: [] };
57
+ }
58
+ // Route handlers (bound in route-table.ts, appended at the table tail on the
59
+ // append-only precedent; both read-only GETs).
60
+ export function controllerJournalRoute({ res, requestUrl }) {
61
+ const limit = Math.min(Math.max(parseInt(requestUrl.searchParams.get("limit") ?? "200", 10) || 200, 1), 400);
62
+ sendJson(res, 200, { events: journalSnapshot(limit) });
63
+ }
64
+ export function controllerLogTailRoute({ res, requestUrl }) {
65
+ const lines = Math.min(Math.max(parseInt(requestUrl.searchParams.get("lines") ?? "200", 10) || 200, 1), 1000);
66
+ const unfiltered = requestUrl.searchParams.get("all") === "1";
67
+ sendJson(res, 200, readGatewayLogTail(lines, !unfiltered));
68
+ }
@@ -8,6 +8,7 @@ import fs from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import readline from "node:readline";
10
10
  import { spawn } from "node:child_process";
11
+ import { resolveControllerTeamclawEntryPath } from "../provisioning-config.js";
11
12
  import { resolveDefaultOpenClawConfigPath, resolveDefaultTeamClawRuntimeRootDir, } from "../../openclaw-workspace.js";
12
13
  import { pathExists, sanitizePathSegment } from "../../shared/utils.js";
13
14
  import { copyControllerAuthProfiles } from "../provisioning-config.js";
@@ -17,15 +18,39 @@ export class ProcessProvisioner {
17
18
  type = "process";
18
19
  logger;
19
20
  processByWorkerId = new Map();
20
- baseDirPromise;
21
+ baseDirPromise; // mutable: ensureBaseDir self-heal swaps it
21
22
  constructor(logger) {
22
23
  this.logger = logger;
23
24
  const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
24
25
  this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
25
26
  .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
26
27
  }
28
+ /**
29
+ * #watchdog (observer-found 2026-11-13, workers starved 2.3h+): the
30
+ * session baseDir is created ONCE in the constructor and cached - if an
31
+ * external cleanup removes it (gateway restarts / culling sweeps), every
32
+ * later launch's mkdtemp hits ENOENT (mkdtemp never creates parents),
33
+ * the provisioner cools down, and pending tasks starve until process
34
+ * restart. Self-heal: verify the cached dir still exists on every
35
+ * launch; on ENOENT, rebuild it and swap the cached promise.
36
+ */
37
+ async ensureBaseDir() {
38
+ const dir = await this.baseDirPromise;
39
+ try {
40
+ await fs.stat(dir);
41
+ return dir;
42
+ }
43
+ catch {
44
+ const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
45
+ const fresh = fs.mkdir(provisionedRoot, { recursive: true })
46
+ .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
47
+ this.baseDirPromise = fresh;
48
+ this.logger.warn?.(`TeamClaw: provisioner session dir vanished (${dir}) - rebuilt`);
49
+ return fresh;
50
+ }
51
+ }
27
52
  async launch(spec) {
28
- const baseDir = await this.baseDirPromise;
53
+ const baseDir = await this.ensureBaseDir();
29
54
  const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
30
55
  const stateDir = path.join(runtimeHomeDir, ".openclaw");
31
56
  const configPath = path.join(stateDir, "openclaw.json");
@@ -48,6 +73,37 @@ export class ProcessProvisioner {
48
73
  throw err;
49
74
  });
50
75
  await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
76
+ // #task-stuck (13th layer, physical half): the worker sandbox has no
77
+ // teamclaw installation of its own, and entries.enabled does not resolve
78
+ // the plugin. Symlink the controller's teamclaw package into the
79
+ // sandbox's extensions/ dir - the host auto-discovers extensions/ - and
80
+ // mirror it into the config's plugins.load.paths so discovery sees the
81
+ // same physical path. Idempotent; failures are non-fatal (worker still
82
+ // boots, just without the plugin).
83
+ try {
84
+ const controllerEntry = resolveControllerTeamclawEntryPath();
85
+ if (controllerEntry) {
86
+ const pkgDir = path.dirname(path.dirname(controllerEntry)); // dist/index.js -> package root
87
+ const extDir = path.join(stateDir, "extensions");
88
+ await fs.mkdir(extDir, { recursive: true });
89
+ const linkPath = path.join(extDir, "teamclaw");
90
+ await fs.rm(linkPath, { force: true }).catch(() => undefined);
91
+ await fs.symlink(pkgDir, linkPath, "dir");
92
+ // Mirror into the written config (configJson was already serialized).
93
+ try {
94
+ const cfg = JSON.parse(await fs.readFile(configPath, "utf8"));
95
+ const plugins = (cfg.plugins ??= {});
96
+ const load = (plugins.load ??= { paths: [] });
97
+ if (Array.isArray(load.paths) && !load.paths.includes(linkPath))
98
+ load.paths.push(linkPath);
99
+ await fs.writeFile(configPath, JSON.stringify(cfg, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
100
+ }
101
+ catch { /* config mirror best-effort */ }
102
+ }
103
+ }
104
+ catch (e) {
105
+ this.logger.warn?.(`TeamClaw: could not link teamclaw into worker extensions: ${e instanceof Error ? e.message : String(e)}`);
106
+ }
51
107
  const gatewayEntrypoint = resolveGatewayEntrypoint();
52
108
  const child = spawn(process.execPath, [
53
109
  gatewayEntrypoint,
@@ -9,6 +9,39 @@ import path from "node:path";
9
9
  import JSON5 from "json5";
10
10
  import { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
11
11
  import { cloneJson, pathExists, sanitizePathSegment } from "../shared/utils.js";
12
+ import os from "node:os";
13
+ import fsSync from "node:fs";
14
+ /**
15
+ * #task-stuck (13th layer): resolve the teamclaw entry the CONTROLLER is
16
+ * actually loading, so process workers can plugins.load the same physical
17
+ * path. Discovery order: openclaw npm projects generation dirs (newest
18
+ * mtime wins - that is what the host loaded), then the global node_modules
19
+ * install. Returns undefined when nothing resolvable exists.
20
+ */
21
+ export function resolveControllerTeamclawEntryPath() {
22
+ const candidates = [];
23
+ const home = process.env.OPENCLAW_HOME?.trim() || process.env.HOME?.trim() || os.homedir();
24
+ const projectsDir = path.join(home, ".openclaw", "npm", "projects");
25
+ try {
26
+ for (const proj of fsSync.readdirSync(projectsDir)) {
27
+ if (!proj.startsWith("teamclaws-teamclaw"))
28
+ continue;
29
+ candidates.push(path.join(projectsDir, proj, "node_modules", "@teamclaws", "teamclaw"));
30
+ }
31
+ }
32
+ catch { /* no projects dir */ }
33
+ candidates.push("/opt/homebrew/lib/node_modules/@teamclaws/teamclaw/dist/index.js", "/usr/local/lib/node_modules/@teamclaws/teamclaw/dist/index.js");
34
+ let best;
35
+ for (const p of candidates) {
36
+ try {
37
+ const m = fsSync.statSync(p).mtimeMs;
38
+ if (!best || m > best.m)
39
+ best = { p, m };
40
+ }
41
+ catch { /* candidate absent */ }
42
+ }
43
+ return best?.p;
44
+ }
12
45
  export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec) {
13
46
  const config = cloneJson(baseConfig);
14
47
  delete config.channels;
@@ -84,6 +117,26 @@ export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec)
84
117
  if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
85
118
  delete plugins.load;
86
119
  }
120
+ // #task-stuck (2026-11-13, 13th layer): a PROCESS worker sandbox has NO
121
+ // local teamclaw installation (no extensions dir, no npm registration),
122
+ // and entries.enabled alone does not make the host resolve the plugin -
123
+ // the worker gateway booted as bare openclaw (plugins: anthropic,
124
+ // memory-core) and never registered with the controller, so pending
125
+ // tasks sat unclaimed forever. Point plugins.load at the CONTROLLER's
126
+ // teamclaw entry (the npm project dir the controller itself loads from).
127
+ if (controllerConfig.workerProvisioningType === "process" || !controllerConfig.workerProvisioningType) {
128
+ const controllerEntryPath = resolveControllerTeamclawEntryPath();
129
+ if (controllerEntryPath) {
130
+ // Host schema: plugins.load = { paths: string[] } (object, not array).
131
+ const loadObj = ensureRecord(plugins).load;
132
+ const existing = ensureRecord(loadObj && typeof loadObj === "object" ? loadObj : {});
133
+ const paths = Array.isArray(existing.paths) ? existing.paths.filter((p) => typeof p === "string") : [];
134
+ if (!paths.includes(controllerEntryPath))
135
+ paths.push(controllerEntryPath);
136
+ existing.paths = paths;
137
+ plugins.load = existing;
138
+ }
139
+ }
87
140
  const entries = ensureRecord(plugins.entries);
88
141
  const teamclawEntry = ensureRecord(entries.teamclaw);
89
142
  teamclawEntry.enabled = true;
@@ -3,6 +3,8 @@ import { githubAuthStatusRoute, githubAuthLoginRoute, githubAuthCallbackRoute, g
3
3
  import { workspaceStatusRoute, workspaceChangeDirRoute, modelsConfigGetRoute, modelsConfigPutRoute, workspaceTreeRoute, workspaceSubtreeRoute, workspaceFileRoute, workspaceProjectPathRoute, workspaceRawFileRoute, } from "./workspace-routes.js";
4
4
  import { controllerManifestRoute, controllerRunsListRoute, projectDeleteRoute, controllerRunDeleteRoute, controllerIntakeRoute, } from "./controller-routes.js";
5
5
  import { teamStatsRoute, teamStatusRoute, teamRolesRoute, teamProfilesListRoute, teamProfileGetRoute, teamProfileSwitchRoute, archivedTeamsRoute, } from "./status-routes.js";
6
+ import { teamConfigGetRoute, teamConfigPatchRoute } from "./config-routes.js";
7
+ import * as journalRoutes from "./journal.js";
6
8
  import { reportsListRoute, reportsSessionRoute, healthRoute, } from "./report-routes.js";
7
9
  import { handleTeamAutoActivityRequest, handleTeamAutoReposListRequest, handleTeamAutoRepoCandidatesRequest, handleTeamAutoRepoBindRequest, handleTeamAutoRepoItemRequest, } from "./teamauto-routes.js";
8
10
  import { handleRepoStatusRequest, handleRepoBundleRequest, repoImportRoute, } from "./repo-routes.js";
@@ -372,4 +374,13 @@ export const controllerRouteTable = [
372
374
  // { context } (initial business context). The handler enforces the
373
375
  // transition-matrix 503 itself (see workflow-routes.ts).
374
376
  { method: "POST", path: /^\/api\/v1\/workflows\/[^/]+\/start$/, handler: workflowStartRoute },
377
+ // Hot worker-provisioning config (#hot-config): GET snapshot + PATCH
378
+ // hot-apply. Appended at the table tail on the same append-only precedent
379
+ // (no path overlap with any earlier route).
380
+ { method: "GET", path: "/api/v1/team/config", handler: teamConfigGetRoute },
381
+ { method: "PATCH", path: "/api/v1/team/config", handler: teamConfigPatchRoute },
382
+ // Controller observability (#ui-blindness): event journal + gateway log
383
+ // tail for the web UI's Activity tab. Appended on the same precedent.
384
+ { method: "GET", path: "/api/v1/controller/journal", handler: journalRoutes.controllerJournalRoute },
385
+ { method: "GET", path: "/api/v1/controller/log-tail", handler: journalRoutes.controllerLogTailRoute },
375
386
  ];