@teamclaws/teamclaw 2026.4.3-2 → 2026.4.4

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.
@@ -1,4 +1,9 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
+ import { execFile } from "node:child_process";
3
+ import { createRequire } from "node:module";
4
+ import { promisify } from "node:util";
5
+
6
+ const execFileAsync = promisify(execFile);
2
7
  import fs from "node:fs/promises";
3
8
  import os from "node:os";
4
9
  import path from "node:path";
@@ -143,8 +148,15 @@ function resolveConfiguredAgentEntry(
143
148
  return null;
144
149
  }
145
150
  const agents = isRecord(parsed.agents) ? parsed.agents : null;
146
- const list = agents && Array.isArray(agents.list) ? agents.list : [];
147
151
  const normalizedAgentId = normalizeAgentId(agentId);
152
+ // OpenClaw 2026.10+ keyed agents.entries take precedence; legacy hosts
153
+ // (<2026.10) only have the array-shaped agents.list.
154
+ const entries = agents && isRecord(agents.entries) ? agents.entries : null;
155
+ const keyedEntry = entries ? entries[normalizedAgentId] : null;
156
+ if (isRecord(keyedEntry)) {
157
+ return keyedEntry;
158
+ }
159
+ const list = agents && Array.isArray(agents.list) ? agents.list : [];
148
160
  for (const entry of list) {
149
161
  if (!isRecord(entry)) {
150
162
  continue;
@@ -283,6 +295,35 @@ export type TeamClawModelReadiness = {
283
295
  message: string;
284
296
  };
285
297
 
298
+ /**
299
+ * OpenClaw 2026.10+ moved model-provider auth out of the legacy per-agent
300
+ * `auth-profiles.json` file and into the host config (models.providers[*]
301
+ * with apiKey/auth, optionally backed by the secrets store). Treat a host
302
+ * config with provider auth as ready so the readiness gate does not false-
303
+ * negative on current hosts.
304
+ */
305
+ function hostConfiguredProviderAuthExists(
306
+ env: NodeJS.ProcessEnv = process.env,
307
+ homedir: () => string = os.homedir,
308
+ ): boolean {
309
+ try {
310
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
311
+ const parsed = JSON.parse(readFileSync(configPath, "utf8")) as {
312
+ models?: { providers?: Record<string, unknown> };
313
+ providers?: Record<string, unknown>;
314
+ };
315
+ const providers = parsed.models?.providers ?? parsed.providers ?? {};
316
+ return Object.values(providers).some(
317
+ (value) =>
318
+ Boolean(value) &&
319
+ typeof value === "object" &&
320
+ ("apiKey" in (value as object) || "auth" in (value as object)),
321
+ );
322
+ } catch {
323
+ return false;
324
+ }
325
+ }
326
+
286
327
  export function getTeamClawModelReadiness(
287
328
  env: NodeJS.ProcessEnv = process.env,
288
329
  homedir: () => string = os.homedir,
@@ -299,20 +340,22 @@ export function getTeamClawModelReadiness(
299
340
  return false;
300
341
  }
301
342
  }) ?? authCandidates[0] ?? "";
302
- const hasConfiguredModel = Boolean(configuredModel);
303
343
  const hasAuthProfiles = Boolean(authPath) && existsSync(authPath);
304
- const status = hasConfiguredModel && hasAuthProfiles ? "ready" : "missing";
344
+ const hasHostProviderAuth = !hasAuthProfiles && hostConfiguredProviderAuthExists(env, homedir);
345
+ const authReady = hasAuthProfiles || hasHostProviderAuth;
346
+ const hasConfiguredModel = Boolean(configuredModel);
347
+ const status = hasConfiguredModel && authReady ? "ready" : "missing";
305
348
  const missingParts = [];
306
349
  if (!hasConfiguredModel) {
307
350
  missingParts.push("no model is configured");
308
351
  }
309
- if (!hasAuthProfiles) {
352
+ if (!authReady) {
310
353
  missingParts.push("no auth-profiles.json was found");
311
354
  }
312
355
  return {
313
356
  status,
314
357
  hasConfiguredModel,
315
- hasAuthProfiles,
358
+ hasAuthProfiles: authReady,
316
359
  configuredModel,
317
360
  authPath,
318
361
  message: status === "ready"
@@ -391,6 +434,353 @@ export function resolveTeamClawWorkspaceDir(
391
434
  return resolveTeamClawAgentWorkspaceRootDir(env, homedir);
392
435
  }
393
436
 
437
+ /**
438
+ * True when the teamclaw workspace is still the implicit default (nothing
439
+ * explicitly configured) - the UI uses this to offer a one-time workspace
440
+ * relocation prompt on first load.
441
+ */
442
+ export function teamClawWorkspaceIsDefault(
443
+ env: NodeJS.ProcessEnv = process.env,
444
+ homedir: () => string = os.homedir,
445
+ ): boolean {
446
+ if (resolveExplicitTeamClawWorkspaceDir(env, homedir)) {
447
+ return false;
448
+ }
449
+ const entry = resolveConfiguredAgentEntry(TEAMCLAW_AGENT_ID, env, homedir);
450
+ return typeof (entry as { workspace?: unknown } | null)?.workspace !== "string";
451
+ }
452
+
453
+ /**
454
+ * Persist a new teamclaw workspace path into the host config, writing the
455
+ * 2026.10 keyed agents.entries shape (legacy agents.list folded + removed,
456
+ * ownership=explicit for multi-agent rosters). Legacy list-only hosts keep
457
+ * the array shape.
458
+ */
459
+ export async function updateTeamClawWorkspaceDir(
460
+ workspaceDir: string,
461
+ logger?: { warn?: (message: string) => void },
462
+ env: NodeJS.ProcessEnv = process.env,
463
+ homedir: () => string = os.homedir,
464
+ ): Promise<{ configPath: string; agentEntryPath: string }> {
465
+ if (!workspaceDir.trim()) {
466
+ throw new Error("workspace path is required");
467
+ }
468
+ // Reject relative paths: path.resolve() would silently join them onto the
469
+ // gateway process cwd (which can be the workspace itself), producing a
470
+ // nested garbage path in the host config.
471
+ if (!workspaceDir.trim().startsWith("/") && !workspaceDir.trim().startsWith("~/") && workspaceDir.trim() !== "~") {
472
+ throw new Error("workspace path must be absolute (start with / or ~/)");
473
+ }
474
+ const normalized = path.resolve(expandUserPath(workspaceDir.trim(), homedir));
475
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
476
+ let parsed: Record<string, unknown>;
477
+ try {
478
+ parsed = JSON5.parse(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
479
+ if (!isRecord(parsed)) {
480
+ throw new Error("host config is not an object");
481
+ }
482
+ } catch (err) {
483
+ throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
484
+ }
485
+
486
+ const agents = isRecord(parsed.agents) ? parsed.agents : {};
487
+ const patch: Record<string, unknown> = { workspace: normalized };
488
+
489
+ const legacyList = Array.isArray(agents.list) ? agents.list.filter(isRecord) : [];
490
+ if (isRecord(agents.entries) || legacyList.length === 0) {
491
+ const entries = isRecord(agents.entries) ? agents.entries : {};
492
+ for (const legacyEntry of legacyList) {
493
+ const legacyId = typeof legacyEntry.id === "string" ? legacyEntry.id : "";
494
+ if (!legacyId || isRecord(entries[legacyId])) {
495
+ continue;
496
+ }
497
+ const migrated = cloneJsonValue(legacyEntry);
498
+ delete migrated.id;
499
+ entries[legacyId] = migrated;
500
+ }
501
+ const existing = isRecord(entries[TEAMCLAW_AGENT_ID]) ? entries[TEAMCLAW_AGENT_ID] : {};
502
+ entries[TEAMCLAW_AGENT_ID] = { ...cloneJsonValue(existing), ...patch };
503
+ agents.entries = entries;
504
+ delete agents.list;
505
+ if (Object.keys(entries).length > 1 && agents.ownership !== "explicit") {
506
+ agents.ownership = "explicit";
507
+ }
508
+ } else {
509
+ const nextList = [...legacyList];
510
+ const index = nextList.findIndex((entry) => entry.id === TEAMCLAW_AGENT_ID);
511
+ if (index >= 0) {
512
+ nextList[index] = { ...cloneJsonValue(nextList[index]), ...patch };
513
+ } else {
514
+ nextList.push({ id: TEAMCLAW_AGENT_ID, ...patch });
515
+ }
516
+ agents.list = nextList;
517
+ }
518
+ parsed.agents = agents;
519
+ await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
520
+ logger?.warn?.(`TeamClaw: workspace updated to ${normalized} (restart the gateway to apply)`);
521
+ return { configPath, agentEntryPath: normalized };
522
+ }
523
+
524
+ const TEAMCLAW_ROLE_CATALOG: ReadonlyArray<{ id: string; label: string }> = [
525
+ { id: "pm", label: "Project Manager" },
526
+ { id: "architect", label: "Architect" },
527
+ { id: "developer", label: "Developer" },
528
+ { id: "qa", label: "QA Engineer" },
529
+ { id: "release-engineer", label: "Release Engineer" },
530
+ { id: "infra-engineer", label: "Infra Engineer" },
531
+ { id: "devops", label: "DevOps Engineer" },
532
+ { id: "security-engineer", label: "Security Engineer" },
533
+ { id: "designer", label: "Designer" },
534
+ { id: "marketing", label: "Marketing" },
535
+ { id: "data-engineer", label: "Data Engineer" },
536
+ ];
537
+
538
+ export type TeamClawModelCatalog = {
539
+ defaultModel: string;
540
+ roleModelOverrides: Record<string, string>;
541
+ roles: ReadonlyArray<{ id: string; label: string }>;
542
+ providers: ReadonlyArray<{ id: string; models: string[] }>;
543
+ };
544
+
545
+ /**
546
+ * Model catalog for the UI settings dialog: provider/model ids from the host
547
+ * config (names only - never secrets), plus the current teamclaw default and
548
+ * per-role overrides.
549
+ */
550
+ /**
551
+ * Live host model catalog via `openclaw models list --json` (the gateway's
552
+ * own resolved catalog: provider plugins, dynamic entries, availability).
553
+ * Cached briefly because the CLI spawn costs ~seconds; falls back to the
554
+ * static config models when unavailable.
555
+ */
556
+ let liveCatalogCache: { at: number; providers: Array<{ id: string; models: string[] }> } | null = null;
557
+ let liveCatalogInFlight: Promise<Array<{ id: string; models: string[] }>> | null = null;
558
+ const LIVE_CATALOG_TTL_MS = 30_000;
559
+
560
+ /**
561
+ * Resolve how to invoke the openclaw CLI from inside the gateway process.
562
+ * LaunchAgent processes may lack /opt/homebrew/bin on PATH, so prefer
563
+ * node + the host package entry resolved through the plugin's node_modules
564
+ * link (the host links itself there at install time); fall back to the bare
565
+ * command name.
566
+ */
567
+ function resolveOpenClawCliInvocation(): { command: string; args: string[] } {
568
+ if (process.execPath) {
569
+ try {
570
+ const moduleRequire = createRequire(import.meta.url);
571
+ const hostPkgDir = path.dirname(moduleRequire.resolve("openclaw/package.json"));
572
+ const entry = path.join(hostPkgDir, "openclaw.mjs");
573
+ if (existsSync(entry)) {
574
+ return { command: process.execPath, args: [entry] };
575
+ }
576
+ } catch (resolveErr) {
577
+ // Resolution failure is expected on hosts without the node_modules link;
578
+ // fall through to the bare CLI name.
579
+ void resolveErr;
580
+ }
581
+ }
582
+ return { command: "openclaw", args: [] };
583
+ }
584
+
585
+ function buildCatalogCliEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
586
+ // The gateway LaunchAgent environment carries runtime variables (e.g.
587
+ // OPENCLAW_GATEWAY_PORT) that hijack the CLI's behavior, and may lack the
588
+ // package manager bin dirs. Pass a minimal, PATH-augmented env instead.
589
+ const clean: NodeJS.ProcessEnv = {
590
+ PATH: ["/opt/homebrew/bin", "/usr/local/bin", env.PATH || "/usr/bin:/bin"].join(path.delimiter),
591
+ };
592
+ for (const key of ["HOME", "USER", "LANG", "OPENCLAW_CONFIG_PATH", "OPENCLAW_STATE_DIR", "OPENCLAW_HOME"]) {
593
+ if (typeof env[key] === "string") {
594
+ clean[key] = env[key];
595
+ }
596
+ }
597
+ return clean;
598
+ }
599
+
600
+ async function readLiveModelCatalogProviders(env: NodeJS.ProcessEnv): Promise<Array<{ id: string; models: string[] }>> {
601
+ const now = Date.now();
602
+ if (liveCatalogCache && now - liveCatalogCache.at < LIVE_CATALOG_TTL_MS) {
603
+ return liveCatalogCache.providers;
604
+ }
605
+ if (liveCatalogInFlight) {
606
+ return liveCatalogInFlight;
607
+ }
608
+ liveCatalogInFlight = (async () => {
609
+ try {
610
+ const invocation = resolveOpenClawCliInvocation();
611
+ // IMPORTANT: `openclaw models list` is a gateway RPC client. Running it
612
+ // synchronously (spawnSync) from inside a gateway plugin service
613
+ // deadlocks: the CLI cannot reach the gateway whose event loop is
614
+ // blocked waiting on it. Async execFile keeps the loop free.
615
+ const { stdout } = await execFileAsync(
616
+ invocation.command,
617
+ [...invocation.args, "models", "list", "--json"],
618
+ {
619
+ timeout: 20_000,
620
+ maxBuffer: 8 * 1024 * 1024,
621
+ env: buildCatalogCliEnv(env),
622
+ },
623
+ );
624
+ const parsed = JSON.parse(stdout) as { models?: unknown };
625
+ const byProvider = new Map<string, Set<string>>();
626
+ if (Array.isArray(parsed.models)) {
627
+ for (const entry of parsed.models) {
628
+ const key = isRecord(entry) && typeof (entry as { key?: unknown }).key === "string"
629
+ ? (entry as { key: string }).key
630
+ : "";
631
+ if (!key || (entry as { available?: unknown }).available === false) {
632
+ continue;
633
+ }
634
+ const slash = key.indexOf("/");
635
+ const providerId = slash > 0 ? key.slice(0, slash) : key;
636
+ const modelId = slash > 0 ? key.slice(slash + 1) : "";
637
+ if (!modelId) {
638
+ continue;
639
+ }
640
+ if (!byProvider.has(providerId)) {
641
+ byProvider.set(providerId, new Set());
642
+ }
643
+ byProvider.get(providerId)!.add(modelId);
644
+ }
645
+ }
646
+ const providers = [...byProvider.entries()]
647
+ .map(([id, models]) => ({ id, models: [...models].sort() }))
648
+ .sort((left, right) => left.id.localeCompare(right.id));
649
+ liveCatalogCache = { at: now, providers };
650
+ return providers;
651
+ } catch (err) {
652
+ console.warn(`[teamclaw] live model catalog unavailable: ${err instanceof Error ? err.message : String(err)}`);
653
+ liveCatalogCache = { at: now, providers: [] };
654
+ return [];
655
+ } finally {
656
+ liveCatalogInFlight = null;
657
+ }
658
+ })();
659
+ return liveCatalogInFlight;
660
+ }
661
+
662
+ export async function getTeamClawModelCatalog(
663
+ env: NodeJS.ProcessEnv = process.env,
664
+ homedir: () => string = os.homedir,
665
+ ): Promise<TeamClawModelCatalog> {
666
+ const parsedConfig = loadOpenClawConfigRecord(env, homedir);
667
+ const staticProviders: Array<{ id: string; models: string[] }> = [];
668
+ const modelsSection = parsedConfig && isRecord(parsedConfig.models) ? parsedConfig.models : null;
669
+ const providerMap = modelsSection && isRecord((modelsSection as { providers?: unknown }).providers)
670
+ ? (modelsSection as { providers: Record<string, unknown> }).providers
671
+ : null;
672
+ if (providerMap) {
673
+ for (const [providerId, providerValue] of Object.entries(providerMap)) {
674
+ if (!isRecord(providerValue)) {
675
+ continue;
676
+ }
677
+ const rawModels = Array.isArray((providerValue as { models?: unknown }).models)
678
+ ? (providerValue as { models: unknown[] }).models
679
+ : [];
680
+ const models = rawModels
681
+ .map((entry) => {
682
+ if (typeof entry === "string") {
683
+ return entry;
684
+ }
685
+ const id = isRecord(entry) ? (entry as { id?: unknown }).id : undefined;
686
+ return typeof id === "string" ? id : "";
687
+ })
688
+ .filter(Boolean);
689
+ staticProviders.push({ id: providerId, models });
690
+ }
691
+ }
692
+
693
+ // Live catalog first; merge static config entries in (dedup) so models the
694
+ // user pinned in config but the live resolver has not surfaced still show.
695
+ const merged = new Map<string, Set<string>>();
696
+ for (const provider of [...(await readLiveModelCatalogProviders(env)), ...staticProviders]) {
697
+ if (!merged.has(provider.id)) {
698
+ merged.set(provider.id, new Set());
699
+ }
700
+ const target = merged.get(provider.id)!;
701
+ for (const model of provider.models) {
702
+ target.add(model);
703
+ }
704
+ }
705
+ const providers = [...merged.entries()]
706
+ .map(([id, models]) => ({ id, models: [...models].sort() }))
707
+ .sort((left, right) => left.id.localeCompare(right.id));
708
+
709
+ let roleModelOverrides: Record<string, string> = {};
710
+ const pluginsSection = parsedConfig && isRecord(parsedConfig.plugins) ? parsedConfig.plugins : null;
711
+ const pluginEntries = pluginsSection && isRecord((pluginsSection as { entries?: unknown }).entries)
712
+ ? (pluginsSection as { entries: Record<string, unknown> }).entries
713
+ : null;
714
+ const teamclawPlugin = pluginEntries ? pluginEntries[TEAMCLAW_AGENT_ID] : null;
715
+ const pluginConfig = isRecord(teamclawPlugin) ? (teamclawPlugin as { config?: unknown }).config : null;
716
+ const overrides = pluginConfig && isRecord(pluginConfig) ? (pluginConfig as { roleModelOverrides?: unknown }).roleModelOverrides : null;
717
+ if (overrides && isRecord(overrides)) {
718
+ roleModelOverrides = { ...(overrides as Record<string, string>) };
719
+ }
720
+
721
+ return {
722
+ defaultModel: resolveConfiguredTeamClawModelValue(env, homedir),
723
+ roleModelOverrides,
724
+ roles: TEAMCLAW_ROLE_CATALOG,
725
+ providers,
726
+ };
727
+ }
728
+
729
+ /**
730
+ * Persist model configuration: the teamclaw agent default model (host config
731
+ * agents.entries.teamclaw.model) and per-role overrides (plugin config
732
+ * roleModelOverrides). The gateway hot-reloads config changes; a restart is
733
+ * only needed if a change does not take effect.
734
+ */
735
+ export async function updateTeamClawModelConfig(
736
+ update: { defaultModel?: string; roleModelOverrides?: Record<string, string> },
737
+ logger?: { warn?: (message: string) => void },
738
+ env: NodeJS.ProcessEnv = process.env,
739
+ homedir: () => string = os.homedir,
740
+ ): Promise<{ configPath: string }> {
741
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
742
+ let parsed: Record<string, unknown>;
743
+ try {
744
+ parsed = JSON5.parse(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
745
+ if (!isRecord(parsed)) {
746
+ throw new Error("host config is not an object");
747
+ }
748
+ } catch (err) {
749
+ throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
750
+ }
751
+
752
+ if (typeof update.defaultModel === "string" && update.defaultModel.trim()) {
753
+ const agents = isRecord(parsed.agents) ? parsed.agents : {};
754
+ const entries = isRecord(agents.entries) ? agents.entries : {};
755
+ const teamclaw = isRecord(entries[TEAMCLAW_AGENT_ID]) ? entries[TEAMCLAW_AGENT_ID] : {};
756
+ entries[TEAMCLAW_AGENT_ID] = { ...teamclaw, model: update.defaultModel.trim() };
757
+ agents.entries = entries;
758
+ if (Object.keys(entries).length > 1 && agents.ownership !== "explicit") {
759
+ agents.ownership = "explicit";
760
+ }
761
+ parsed.agents = agents;
762
+ }
763
+
764
+ if (update.roleModelOverrides !== undefined && update.roleModelOverrides !== null) {
765
+ const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
766
+ const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
767
+ const teamclawPlugin = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : { enabled: true };
768
+ const pluginConfig = isRecord((teamclawPlugin as { config?: unknown }).config)
769
+ ? (teamclawPlugin as { config: Record<string, unknown> }).config
770
+ : {};
771
+ pluginEntries[TEAMCLAW_AGENT_ID] = {
772
+ ...teamclawPlugin,
773
+ config: { ...pluginConfig, roleModelOverrides: update.roleModelOverrides },
774
+ };
775
+ plugins.entries = pluginEntries;
776
+ parsed.plugins = plugins;
777
+ }
778
+
779
+ await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
780
+ logger?.warn?.("TeamClaw: model config updated (hot-reload applies; restart the gateway if a change does not take effect)");
781
+ return { configPath };
782
+ }
783
+
394
784
  /**
395
785
  * Resolve the `projects/` root inside the TeamClaw workspace.
396
786
  * Each orchestration run or ad-hoc task gets its own subdirectory here.
@@ -539,39 +929,59 @@ async function ensureTeamClawAgentConfigBootstrap(logger: PluginLogger): Promise
539
929
 
540
930
  const agents = isRecord(parsed.agents) ? parsed.agents : {};
541
931
  const defaults = isRecord(agents.defaults) ? agents.defaults : {};
542
- const nextList = Array.isArray(agents.list) ? [...agents.list] : [];
543
932
  const rootTools = isRecord(parsed.tools) ? parsed.tools : {};
544
933
  const rootExec = isRecord(rootTools.exec) ? rootTools.exec : {};
545
934
  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
546
- const entries = isRecord(plugins.entries) ? plugins.entries : {};
547
- const teamclawPluginEntry = isRecord(entries[TEAMCLAW_AGENT_ID]) ? entries[TEAMCLAW_AGENT_ID] : {};
935
+ const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
936
+ const teamclawPluginEntry = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : {};
548
937
  const existingPluginConfig = isRecord(teamclawPluginEntry.config) ? teamclawPluginEntry.config : {};
549
- const teamclawWorkspaceDir = path.join(resolveDefaultOpenClawStateDir(), `workspace-${TEAMCLAW_AGENT_ID}`);
550
938
  const teamclawAgentDir = path.join(resolveDefaultOpenClawStateDir(), "agents", TEAMCLAW_AGENT_ID, "agent");
551
- const existingIndex = nextList.findIndex((entry) => isRecord(entry) && normalizeAgentId(entry.id) === TEAMCLAW_AGENT_ID);
552
- const existingEntry = existingIndex >= 0 && isRecord(nextList[existingIndex]) ? nextList[existingIndex] : {};
939
+
940
+ // OpenClaw 2026.10+ rejects agents.list ("moved to keyed agents.entries")
941
+ // and rejects tools.exec objects mixing mode with security/ask. Write the
942
+ // keyed shape whenever the host already uses it, and never reintroduce the
943
+ // legacy list on modern hosts.
944
+ const agentEntries = isRecord(agents.entries) ? agents.entries : {};
945
+ const legacyList = Array.isArray(agents.list) ? agents.list.filter(isRecord) : [];
946
+ const modernSchema = isRecord(agents.entries) || legacyList.length === 0;
947
+
948
+ const findExistingAgentEntry = (): { entry: Record<string, unknown>; source: "entries" | "list" | "none" } => {
949
+ const keyed = agentEntries[TEAMCLAW_AGENT_ID];
950
+ if (isRecord(keyed)) {
951
+ return { entry: keyed, source: "entries" };
952
+ }
953
+ const fromList = legacyList.find((entry) => normalizeAgentId(entry.id) === TEAMCLAW_AGENT_ID);
954
+ if (fromList) {
955
+ return { entry: fromList, source: "list" };
956
+ }
957
+ return { entry: {}, source: "none" };
958
+ };
959
+ const existing = findExistingAgentEntry();
960
+ const existingEntry = existing.entry;
553
961
  const existingEntryTools = isRecord(existingEntry.tools) ? existingEntry.tools : {};
554
962
  const existingEntryExec = isRecord(existingEntryTools.exec) ? existingEntryTools.exec : {};
555
963
  const nextEntryExec: Record<string, unknown> = {
556
964
  ...cloneJsonValue(rootExec),
557
965
  ...cloneJsonValue(existingEntryExec),
558
966
  };
559
- if (typeof nextEntryExec.security !== "string" || !nextEntryExec.security.trim()) {
560
- nextEntryExec.security = typeof rootExec.security === "string" && rootExec.security.trim()
561
- ? rootExec.security.trim()
562
- : TEAMCLAW_RECOMMENDED_EXEC_SECURITY;
563
- }
564
- if (typeof nextEntryExec.ask !== "string" || !nextEntryExec.ask.trim()) {
565
- nextEntryExec.ask = typeof rootExec.ask === "string" && rootExec.ask.trim()
566
- ? rootExec.ask.trim()
567
- : TEAMCLAW_RECOMMENDED_EXEC_ASK;
967
+ if (typeof nextEntryExec.mode === "string" && nextEntryExec.mode.trim()) {
968
+ // Keyed-schema hosts forbid combining mode with security/ask.
969
+ delete nextEntryExec.security;
970
+ delete nextEntryExec.ask;
971
+ } else {
972
+ if (typeof nextEntryExec.security !== "string" || !nextEntryExec.security.trim()) {
973
+ nextEntryExec.security = typeof rootExec.security === "string" && rootExec.security.trim()
974
+ ? rootExec.security.trim()
975
+ : TEAMCLAW_RECOMMENDED_EXEC_SECURITY;
976
+ }
977
+ if (typeof nextEntryExec.ask !== "string" || !nextEntryExec.ask.trim()) {
978
+ nextEntryExec.ask = typeof rootExec.ask === "string" && rootExec.ask.trim()
979
+ ? rootExec.ask.trim()
980
+ : TEAMCLAW_RECOMMENDED_EXEC_ASK;
981
+ }
568
982
  }
569
983
  const nextEntry: Record<string, unknown> = {
570
- ...existingEntry,
571
- id: TEAMCLAW_AGENT_ID,
572
- workspace: typeof existingEntry.workspace === "string" && existingEntry.workspace.trim()
573
- ? existingEntry.workspace
574
- : teamclawWorkspaceDir,
984
+ ...cloneJsonValue(existingEntry),
575
985
  agentDir: typeof existingEntry.agentDir === "string" && existingEntry.agentDir.trim()
576
986
  ? existingEntry.agentDir
577
987
  : teamclawAgentDir,
@@ -580,6 +990,16 @@ async function ensureTeamClawAgentConfigBootstrap(logger: PluginLogger): Promise
580
990
  exec: nextEntryExec,
581
991
  },
582
992
  };
993
+ // Keep the workspace implicit when unset: materializing the default here
994
+ // would make "default" and "explicitly configured" indistinguishable, which
995
+ // the UI workspace-relocation prompt depends on. The runtime resolver falls
996
+ // back to <stateDir>/workspace-teamclaw either way.
997
+ if (typeof existingEntry.workspace === "string" && existingEntry.workspace.trim()) {
998
+ nextEntry.workspace = existingEntry.workspace;
999
+ }
1000
+ if (!modernSchema) {
1001
+ nextEntry.id = TEAMCLAW_AGENT_ID;
1002
+ }
583
1003
  if (nextEntry.model == null && defaults.model != null) {
584
1004
  nextEntry.model = cloneJsonValue(defaults.model);
585
1005
  }
@@ -596,23 +1016,48 @@ async function ensureTeamClawAgentConfigBootstrap(logger: PluginLogger): Promise
596
1016
  nextPluginConfig.workerProvisioningType = "process";
597
1017
  }
598
1018
 
599
- const entryChanged = JSON.stringify(existingEntry) !== JSON.stringify(nextEntry);
1019
+ const entryChanged = JSON.stringify(existingEntry) !== JSON.stringify(nextEntry)
1020
+ || (modernSchema && (legacyList.length > 0 || !isRecord(agentEntries[TEAMCLAW_AGENT_ID])));
600
1021
  const pluginConfigChanged = JSON.stringify(existingPluginConfig) !== JSON.stringify(nextPluginConfig);
601
1022
  if (!entryChanged && !pluginConfigChanged) {
602
1023
  return;
603
1024
  }
604
1025
 
605
- if (existingIndex >= 0) {
606
- nextList[existingIndex] = nextEntry;
1026
+ if (modernSchema) {
1027
+ // Fold any legacy list entries into the keyed map, then drop the list so
1028
+ // 2026.10 hosts stop rejecting the config.
1029
+ for (const legacyEntry of legacyList) {
1030
+ const legacyId = normalizeAgentId(legacyEntry.id);
1031
+ if (!legacyId || isRecord(agentEntries[legacyId])) {
1032
+ continue;
1033
+ }
1034
+ const migrated = cloneJsonValue(legacyEntry);
1035
+ delete migrated.id;
1036
+ agentEntries[legacyId] = migrated;
1037
+ }
1038
+ const keyedNextEntry = cloneJsonValue(nextEntry);
1039
+ delete keyedNextEntry.id;
1040
+ agentEntries[TEAMCLAW_AGENT_ID] = keyedNextEntry;
1041
+ agents.entries = agentEntries;
1042
+ delete agents.list;
1043
+ if (Object.keys(agentEntries).length > 1 && agents.ownership !== "explicit") {
1044
+ agents.ownership = "explicit";
1045
+ }
607
1046
  } else {
608
- nextList.push(nextEntry);
1047
+ const nextList = [...legacyList];
1048
+ const existingIndex = nextList.findIndex((entry) => isRecord(entry) && normalizeAgentId(entry.id) === TEAMCLAW_AGENT_ID);
1049
+ if (existingIndex >= 0) {
1050
+ nextList[existingIndex] = nextEntry;
1051
+ } else {
1052
+ nextList.push(nextEntry);
1053
+ }
1054
+ agents.list = nextList;
609
1055
  }
610
- agents.list = nextList;
611
1056
  parsed.agents = agents;
612
1057
  if (pluginConfigChanged) {
613
1058
  teamclawPluginEntry.config = nextPluginConfig;
614
- entries[TEAMCLAW_AGENT_ID] = teamclawPluginEntry;
615
- plugins.entries = entries;
1059
+ pluginEntries[TEAMCLAW_AGENT_ID] = teamclawPluginEntry;
1060
+ plugins.entries = pluginEntries;
616
1061
  parsed.plugins = plugins;
617
1062
  }
618
1063
  await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
@@ -12,6 +12,7 @@ export const TEAMCLAW_ROLE_IDS: RoleId[] = [
12
12
  "security-engineer",
13
13
  "designer",
14
14
  "marketing",
15
+ "data-engineer",
15
16
  ];
16
17
 
17
18
  export const TEAMCLAW_ROLE_IDS_TEXT = TEAMCLAW_ROLE_IDS.join(", ");
@@ -54,7 +55,7 @@ export function buildRoleOperatingRules(options: {
54
55
  "- Treat file paths from plans, docs, and teammate messages as hints, not facts. Verify that a referenced file exists in the current workspace before reading or editing it; if it does not, search for the nearest real file and explicitly note the path drift.",
55
56
  "- Treat other workers' OpenClaw sessions and session keys as unavailable; use the shared workspace, the current task context, and teammate messages instead of trying cross-session inspection.",
56
57
  "- Do not mark a task completed or failed via progress updates. Finish by returning the deliverable or raising the blocking error so TeamClaw can close the task correctly.",
57
- "- If only a commercial or proprietary option would unblock the task, ask the human for approval before assuming it is allowed.",
58
+ "- Do not infer ownership, license scope, or lack of user authorization from technical characteristics such as proprietary branding, bundled assets, binary files, minified code, or repository layout. Focus on technical feasibility and the user's explicit requirements.",
58
59
  `- Use exact TeamClaw role IDs when collaborating: ${TEAMCLAW_ROLE_IDS_TEXT}.`,
59
60
  `- If a true follow-up is required after your deliverable, prefer these exact next roles: ${suggestedRoles}.`,
60
61
  `- Default starter skills for this role: ${recommendedSkills}. If the task includes more specific recommended skills, prefer those.`,
@@ -109,10 +110,15 @@ export function buildTaskExecutionRules(rateLimitWaitingSentinel: string): strin
109
110
  "- Do NOT create additional tasks, task trees, or duplicate follow-up work.",
110
111
  "- Do NOT re-scope this into a multi-role coordination workflow.",
111
112
  "- Do NOT delegate the core work of this task away to another role.",
113
+ "- Default to completing implementation work in your current worker session. Do not hand the whole task to a helper coding agent just because delegation feels faster.",
114
+ "- Only use a helper coding agent when there is a concrete capability gap, a long-running specialist CLI workflow, or a sharply bounded subproblem that is genuinely narrower than the full task.",
115
+ "- If you use a helper coding agent, pass the full TeamClaw task context first: requirement summary, authoritative project path, upstream task outputs, active blockers, acceptance criteria, and the exact artifact you must return.",
116
+ "- Never ask a helper coding agent to take over the whole TeamClaw task. Helpers, if used at all, must stay narrow and subordinate to your task ownership.",
112
117
  "- If Task Context includes recent completed deliverables, treat them as upstream inputs and search the shared workspace for any referenced task IDs or filenames before requesting clarification.",
113
118
  "- Do NOT attempt to inspect or resolve another worker's OpenClaw session or session key; those sessions are isolated per worker.",
114
119
  "- If the task includes a Recommended Skills section, use those skills first and prefer the exact listed slugs when searching for additional help.",
115
120
  "- If this task has a project directory, treat files outside that directory as foreign unless the task explicitly says they are shared infrastructure inputs. Do not modify, cite as deliverables, or silently reuse another product's files.",
121
+ "- Do not infer that the user lacks rights to inspect, modify, port, rename, or rebrand code merely because a repository contains bundled, binary, generated, minified, or vendor-branded material. Treat authorization as outside your role unless the user explicitly states a restriction.",
116
122
  "- Do NOT mark the task completed or failed via progress tools. Return the final deliverable (or raise an error) and let TeamClaw close the task.",
117
123
  "- If critical information is missing and you cannot proceed safely, request clarification and wait instead of guessing.",
118
124
  "- If more work is needed, mention it briefly in your result or use a handoff/review tool on this same task.",
@@ -311,6 +317,7 @@ export function buildControllerStructuredContractRules(): string[] {
311
317
  "- Use deferredTasks for later-phase work that should not be created yet because prerequisites are not satisfied.",
312
318
  "- If the run is blocked and no tasks should be created yet, submit a manifest with createdTasks=[] and explain the blocker in clarificationQuestions and/or deferredTasks.",
313
319
  "- If you ask the human clarifying questions, still submit the manifest so the controller has machine-readable state for this run.",
320
+ "- When the requirement is truly complete, also include 1-3 completionOpportunities for adjacent, technically justified next steps TeamClaw could continue immediately if the human wants more. Keep them optional, concrete, and near the delivered scope.",
314
321
  ];
315
322
  }
316
323
 
@@ -333,6 +340,8 @@ export function buildControllerIntakeRules(): string[] {
333
340
  "- Human messages are the initial requirement, not an already-decomposed task tree.",
334
341
  "- Analyze the requirement briefly: desired outcome, scope, constraints.",
335
342
  "- BIAS TOWARD ACTION: if the requirement is clear enough for a competent developer/designer/etc. to start working, create the task immediately. Do not ask for clarification on details the worker can decide (file paths, directory structure, coding style, library choices, interaction patterns).",
343
+ "- Route repository analysis, architecture design, feasibility assessment, migration planning, and large rewrite decomposition to architect first. Do not default these pre-implementation tasks to developer just because code will eventually be written.",
344
+ "- Do not reject, moralize, or speculate about ownership merely because code appears bundled, binary-adjacent, generated, minified, vendor-branded, or otherwise unusual. Treat those as technical input characteristics only.",
336
345
  "- Only ask for clarification when a decision fundamentally changes the scope or architecture (e.g. 'build a web app' — do you want React, Vue, or plain HTML? Or 'integrate payments' — which provider?). Even then, limit to 1-2 truly blocking questions.",
337
346
  "- After the requirement is clear enough, translate it into the minimum explicit TeamClaw task packet needed for the team.",
338
347
  "- When creating a task, include a recommendedSkills array whenever you know a useful OpenClaw/ClawHub skill slug (or a short search query if you do not know the exact slug).",
@@ -369,6 +378,7 @@ export function buildControllerDisciplineRules(options: { canProvisionWithoutWor
369
378
  `- Use exact TeamClaw role IDs only: ${TEAMCLAW_ROLE_IDS_TEXT}.`,
370
379
  "- Never guess or summarize a worker's unfinished output as if it were a completed result. While work is still in flight, report only current status plus the next concrete step.",
371
380
  "- Never fabricate downstream readiness from intent alone. Downstream creation requires evidence: completed task state, a structured result contract, concrete deliverables, or an explicit handoff.",
381
+ "- Never ask the human to manually run an obvious machine step such as rebuild/retest/repro/verification (for example git pull, go build, npm test, rerun and report whether it still crashes) when TeamClaw can create an execution task and do that work itself.",
372
382
  ];
373
383
  }
374
384