Repository navigation
Expand file tree
/
Copy pathlocal-agent.ts
More file actions
5069 lines (4748 loc) · 221 KB
/
Copy pathlocal-agent.ts
File metadata and controls
5069 lines (4748 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import fse from 'fs-extra';
import { log } from './utils/logger.js';
import { detachChild } from './utils/exec.js';
import { parseFrontmatter } from './utils/frontmatter.js';
import {
ensureDir,
fileHash,
listDirs,
listFilesRecursive,
pruneEmptyDirs,
pathExists,
readFileSafe,
readFileIfExists,
readJson,
remove,
writeFile,
writeJson,
writeJsonAtomic,
} from './utils/fs.js';
import { RulesHandler, SkillsHandler } from './resources/index.js';
import { injectHooksToAllTools, applyAgentHook, removeAgentHook, isAgentHookSupportedTool, isAgentHookEvent, isCodexTrustGatedTool, trustCodexAgentHook, OPENCLAW_TOOLS, codexTrustPolicy, type CodexTrustPolicy } from './hooks.js';
import { parseHookEvent } from './dashboard-collector.js';
import { resolveHookCwd } from './utils/hook-cwd.js';
import { isInteractive } from './utils/prompt.js';
import { getAgentVersion } from './agent-version.js';
import { getMachineId, deriveLocalAgentId } from './machine-id.js';
import { EXCLUDED_RULE_NAMES } from './builtin-rules.js';
import { ruleStemFromFilename } from './resources/rule-format.js';
import { resolveTeamaiEntryScript } from './builtin-hooks.js';
import { resolveOpenclawWorkspaceDir } from './openclaw-hooks.js';
import { assertSafeResourceName } from './utils/path-safety.js';
import {
detectMcpFormat,
supportsTransport,
renderJsonEntry,
renderCodexBlock,
entryHash,
} from './resources/mcp-format.js';
import {
readJsonDoc,
isTeamaiBareCopy,
ownsJsonMcpEntry,
writeJsonDoc,
writeMcpJson,
writeCodexAtomic,
spliceCodexBlock,
codexServerNames,
recordedFileOf,
sameMcpFile,
claimedByOtherTools,
deleteEmptiedMcpFile,
describeMcpLocation,
loadMcpManifest,
mcpKeyOf,
recordedMcpTarget,
sameMcpPlace,
logLeftMcpFiles,
mcpManifestKey,
mcpRelocated,
projectMcpLocations,
resolveMcpTargets,
saveMcpManifest,
type McpKey,
type McpTarget,
} from './mcp-reconcile.js';
import { normalizeAgentType } from './utils/tool-names.js';
import { logHttpRequest, logHttpResponse } from './utils/http-log.js';
import {
applyInstructionPlan, channelReadiness, deliversInstructionsByHook, holdsInstructionBlocks, instructionHookText, instructionHookTextFor,
instructionTargetOf, planInstructionFiles, registerOpencodeContext, resolveInstructionTargets,
retiredFilesOfReached, nativeProjectInstructions,
} from './instruction-targets.js';
import { opencodeV1ClaudeFile } from './resources/opencode-config.js';
import { reconcilePlugins, teardownAllPlugins, parseGetConfig, substituteVars, unresolvedPlaceholders, type ReconcileDeps, type PluginState } from './plugin-lifecycle.js';
import {
resolveBaseDir,
resolveToolBaseDir,
scopedToolPaths,
applyToolRoots,
getDataHome,
isGitExcludeEnabled,
isUnmigratedDataHome,
resolveGitExclude,
resolveToolRootDir,
CLAUDE_TOOL_ID,
DEFAULT_CLAUDE_ROOT,
getTokenPath,
TEAMAI_CLAUDEMD_START,
TEAMAI_CLAUDEMD_END,
TeamaiConfigSchema,
managedMcpManifestPath,
managedMcpManifestKey,
managedMcpWorkspaceId,
type DashboardEvent,
type DeliveryTarget,
type LocalConfig,
type ManagedMcpManifest,
type ManagedMcpRecord,
type McpServerDef,
type McpTransport,
type ResourceItem,
type TeamaiConfig,
} from './types.js';
import { getUserHome } from './utils/home.js';
import { checkoutForProjectAnchor, gitCommonDir, isLiveCheckout, listWorktrees, resolveAnchors } from './utils/git.js';
import {
ensure as ensureGitExclude, gitExcludeFile, gitTracks, gitUntracked, remove as removeGitExclude, report as reportGitExclude, stateHomeRecord,
sync as syncGitExclude, type GitExcludeOwner,
} from './git-exclude.js';
import {
clearGitExcludeFailure, localAgentGitExcludeNotices, noticeGitExclude, recordGitExcludeFailure,
} from './git-exclude-notices.js';
import { blockingEntries, contentHash, deliveredSkillFiles, describeMembersDirLeft, isLink, keepsTrackedCopy, ownsSkillDir } from './resources/delivered-copies.js';
import { skillOrigin, withSkillFrontmatter } from './resources/skills.js';
import { installOf, locate, ownOf, writable, type FilePlace } from './locate.js';
import { acquireLock, releaseLock } from './update.js';
const execFileAsync = promisify(execFile);
const LOCAL_AGENT_DIR = 'local-agent';
const CONFIG_FILE = 'config.json';
const MANIFEST_FILE = 'manifest.json';
const MODEL_MANIFEST_FILE = 'model-manifest.json';
const REPORTER_ERROR_LOG = 'reporter/errors.jsonl';
/**
* Abort timeout for local-agent network calls.
*
* Prevents a fetch from hanging indefinitely when the endpoint is unreachable,
* which would otherwise keep a socket pending on the event loop and stall the
* hook subprocess until the host IDE's default hook timeout fires.
*/
const LOCAL_AGENT_FETCH_TIMEOUT_MS = 15_000;
/**
* Per-fetch timeout to use while running inside a *foreground* hook. Foreground
* hooks block the host IDE and must finish under its per-event hook timeout
* (UserPromptSubmit/PostToolUse = 10s). Kept under 5s — and safely below the
* foreground handler's dispatch budget (LOCAL_AGENT_FG_TIMEOUT_MS = 4.5s) — so a
* slow/unreachable endpoint fails fast and the whole handler returns before the
* host aborts it. Healthy endpoints answer in well under a second, so this is
* invisible in normal use and never degrades the experience.
*/
const LOCAL_AGENT_HOOK_FETCH_TIMEOUT_MS = 3_000;
/** Active per-fetch timeout; overridden to the hook value inside foreground hooks. */
let activeFetchTimeoutMs = LOCAL_AGENT_FETCH_TIMEOUT_MS;
type LocalAgentScope = 'instance' | 'user' | 'project';
type ResourceKind = 'skills' | 'rules' | 'claudemd';
type CommandResourceKind = 'skill' | 'rule' | 'claudemd';
// Command types recognized but not yet implemented by this reporter. Skipped
// silently (see isUnimplementedCommand) so the suffix logic in commandKind()
// cannot misfire (e.g. uninstall_hook_rule ends in _rule and would otherwise be
// treated as a destructive rule uninstall). uninstall_teamai is NOT here — it
// carries a `cmd` and is executed by runCmdCommand (see executeCommand), so the
// local agent actually uninstalls itself and acks.
// install_hook_rule / uninstall_hook_rule are now implemented (see runHookRuleCommand) and are NOT skipped.
const UNIMPLEMENTED_COMMAND_TYPES = new Set<string>([]);
/** Hook commands this reporter implements (see runHookRuleCommand). Excluded from
* the handle_type==='hook' skip so they dispatch instead of being silently dropped. */
const IMPLEMENTED_HOOK_COMMAND_TYPES = new Set<string>(['install_hook_rule', 'uninstall_hook_rule']);
interface WorkspaceBinding {
projectId: number;
projectName?: string;
boundAt: string;
/** Normalized owning tool (via normalizeAgentType). Optional for back-compat with existing config.json;
* absent means "not yet attributed". */
ideType?: string;
}
export interface LocalAgentConfig {
endpoint: string;
token?: string;
/**
* @deprecated No longer the id source. local_agent_id is now derived at
* runtime per detected tool via resolveLocalAgentId(). Kept optional so
* older config.json files still load without a rewrite.
*/
localAgentId?: string;
createdAt: string;
userGroupId?: number;
userGroupName?: string;
workspaceBindings: Record<string, WorkspaceBinding>;
/**
* Optional per-endpoint path overrides. Maps a logical route name to a custom
* path so a backend that does not use the default `/api/local-agent/*` layout
* can be pointed at its own routes. Unspecified routes fall back to DEFAULT_ROUTES.
* Example: { "getConfig": "/api/plugins/config", "sync": "/v2/agent/sync" }
*/
routes?: Partial<Record<RouteName, string>>;
}
/**
* Logical names for every backend endpoint the local agent talks to, mapped to
* their default paths. A deployment can override any of these via config.routes
* (see LocalAgentConfig.routes) without touching call sites.
*/
export const DEFAULT_ROUTES = {
projects: '/api/projects/mine',
report: '/api/local-agent/report',
sync: '/api/local-agent/sync',
ack: '/api/local-agent/commands/ack',
getConfig: '/api/local-agent/get-config',
} as const;
export type RouteName = keyof typeof DEFAULT_ROUTES;
interface LocalAgentProject {
id: number;
name: string;
description?: string;
}
interface ManifestResource {
slug: string;
version?: string;
display_name?: string;
source?: string;
installed_at: string;
/**
* Actual on-disk directory name for skills. Equals the SKILL.md `name:` when
* it differs from the server slug, else the slug. Used at uninstall time to
* locate the directory by slug (the manifest key stays the slug).
*/
dir_name?: string;
/**
* The tools this entry was written to (#915). An entry an older CLI wrote
* has none: it counts as recorded for a tool whose copy equals the installed
* version or sits under `dir_name`, and gains the field on its next install.
* For a claudemd entry, the tools the compiled block reached.
*/
tools?: string[];
}
interface ManifestScope {
skills: Record<string, ManifestResource>;
rules: Record<string, ManifestResource>;
claudemd: Record<string, ManifestResource>;
}
interface LocalAgentManifest {
scopes: Record<string, ManifestScope>;
}
interface LocalAgentCommand {
id: number;
type?: string;
scope?: string;
workspace_path?: string;
download_url?: string;
skill_slug?: string;
skill_version?: string;
rule_slug?: string;
rule_version?: string;
rule_type?: string;
handle_type?: string;
claudemd_slug?: string;
claudemd_version?: string;
resource_slug?: string;
resource_version?: string;
slug?: string;
name?: string;
version?: string;
display_name?: string;
cmd?: string;
event?: string;
matcher?: string;
timeout?: number;
mcp_config?: {
transport: string;
url?: string;
headers?: Record<string, string>;
command?: string;
args?: string[];
env?: Record<string, string>;
timeout?: number;
requires?: string[];
};
}
interface DeliveredModel {
provider: string;
model_id: string;
name: string;
base_url: string;
api_key: string;
max_tokens?: number;
context_window?: number;
}
interface BuddyModelManifest {
codebuddy?: Record<string, string>;
workbuddy?: Record<string, string>;
providersByAgent?: Record<string, Record<string, string>>;
/** Project scope: teamai created the project's models file, so it deletes it once nothing is left in it (#915). */
createdModelsFile?: boolean;
}
interface ModelConfigManifest extends BuddyModelManifest {
claudeEnv?: Record<string, string>;
/**
* model_id → provider for every model this reporter has applied. Claude
* stores its gateway as plain ANTHROPIC_* env vars that carry no provider,
* so this is the only way to report back the provider the server sent.
*/
providers?: Record<string, string>;
workspaceModels?: Record<string, BuddyModelManifest>;
}
type ModelAgentKind = 'codebuddy' | 'workbuddy' | 'claude';
type BuddyAgentKind = 'codebuddy' | 'workbuddy';
function modelAgentKind(tool: string | undefined): ModelAgentKind | undefined {
const normalized = normalizeAgentType(tool ?? '');
if (normalized === 'codebuddy' || normalized === 'codebuddy-internal') return 'codebuddy';
if (normalized === 'workbuddy') return 'workbuddy';
if (normalized === 'claude') return 'claude';
return undefined;
}
/**
* Whether a sync command is recognized-but-unimplemented and must be skipped
* before dispatch. Matches both the known unimplemented type strings and any
* hook command (handle_type === 'hook'), so a future hook `type` outside
* UNIMPLEMENTED_COMMAND_TYPES still skips silently instead of falling through
* to commandKind() and being acked as a failure.
*/
function isUnimplementedCommand(command: LocalAgentCommand): boolean {
const type = command.type ?? '';
if (IMPLEMENTED_HOOK_COMMAND_TYPES.has(type)) return false;
return UNIMPLEMENTED_COMMAND_TYPES.has(type) || command.handle_type === 'hook';
}
interface LocalAgentContext {
cwd?: string;
tool?: string;
status?: string;
event?: DashboardEvent;
}
function getTeamaiHomePath(): string {
return path.join(getUserHome(), '.teamai');
}
function getLocalAgentHome(): string {
return path.join(getTeamaiHomePath(), LOCAL_AGENT_DIR);
}
function localAgentLockPath(): string {
// Source cleanup removes the local-agent directory's contents, so keep its lock outside it.
return path.join(getTeamaiHomePath(), '.local-agent-sync-lock');
}
/** Set on a command a sync runs while it holds the lock: the pid of that sync. */
const LOCK_HOLDER_ENV = 'TEAMAI_LOCAL_AGENT_LOCK_HOLDER';
/** Whether this process runs as a command of the sync that holds the lock, so holds it too. */
async function holdsParentLocalAgentLock(): Promise<boolean> {
if (process.env[LOCK_HOLDER_ENV] !== String(process.ppid)) return false;
return (await readJson<{ pid?: number }>(localAgentLockPath()))?.pid === process.ppid;
}
async function acquireLocalAgentLock(waitMs = 0): Promise<boolean> {
if (await acquireLock(localAgentLockPath())) return true;
const deadline = Date.now() + waitMs;
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 100));
if (await acquireLock(localAgentLockPath())) return true;
}
return false;
}
function getConfigPath(): string {
return path.join(getLocalAgentHome(), CONFIG_FILE);
}
function getManifestPath(): string {
return path.join(getLocalAgentHome(), MANIFEST_FILE);
}
function getModelManifestPath(): string {
return path.join(getLocalAgentHome(), MODEL_MANIFEST_FILE);
}
function getErrorLogPath(): string {
return path.join(getTeamaiHomePath(), REPORTER_ERROR_LOG);
}
function compileClaudemdBlock(contents: string[]): string | null {
const parts = contents.map((content) => content.trim()).filter(Boolean);
if (parts.length === 0) return null;
return [
TEAMAI_CLAUDEMD_START,
'<!-- DO NOT EDIT: This section is auto-managed by teamai -->',
'',
parts.join('\n\n'),
'',
TEAMAI_CLAUDEMD_END,
].join('\n');
}
function normalizeEndpoint(endpoint: string): string {
return endpoint.trim().replace(/\/+$/, '');
}
/** Normalize a route override so it is a leading-slash path (endpoint has no trailing slash). */
function normalizeRoute(route: string): string {
const trimmed = route.trim();
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
}
/**
* Resolve a logical route name to its path, applying config.routes overrides
* over DEFAULT_ROUTES. A blank/whitespace override is ignored (falls back to default).
*/
export function resolveRoute(config: Pick<LocalAgentConfig, 'routes'>, name: RouteName): string {
const override = config.routes?.[name];
if (override && override.trim()) return normalizeRoute(override);
return DEFAULT_ROUTES[name];
}
/**
* Resolve the per-tool install directory that seeds the local_agent_id hash.
*
* This must match the historical status-report口径 — `~/.<tool>` — so that a
* machine upgrading from the status-report era keeps the same id instead of
* drifting. It is derived from the same toolPaths map buildReportPayload uses:
* `~/<dirname(skills)>` (e.g. `.codebuddy/skills` → `~/.codebuddy`). Unknown
* tools fall back to `~/.<tool>`, still deterministic and distinct per tool.
* Note: install_path only feeds the local hash — it never leaves the machine.
*/
function resolveAgentInstallPath(agentType: string): string {
const home = getUserHome();
const skillsRel = createLocalAgentTeamConfig('').toolPaths[agentType]?.skills;
const rel = skillsRel ? path.dirname(skillsRel) : `.${agentType}`;
return path.join(home, rel);
}
/**
* Resolve the local_agent_id for the current invocation.
*
* Deterministic per (detected tool + machine + install dir) — same tool on the
* same machine always yields the same id, so the backend sees a stable agent
* instead of a fresh random one every hook fire. The tool is auto-detected from
* the hook's --tool flag (context.tool); different tools (claude / codebuddy /
* workbuddy) get different ids because agent_type AND the per-tool install dir
* (~/.<tool>) both feed the hash. install_path uses the tool's own dir (not the
* teamai home) to stay byte-for-byte identical to the historical status-report
* derivation, avoiding an id change on upgrade. TEAMAI_LOCAL_AGENT_ID still
* overrides for explicit pinning.
*/
function resolveLocalAgentId(context: LocalAgentContext): string {
const envOverride = process.env.TEAMAI_LOCAL_AGENT_ID;
if (envOverride) return envOverride;
const agentType = context.tool ?? 'workbuddy';
return deriveLocalAgentId(agentType, getMachineId(), resolveAgentInstallPath(agentType));
}
/**
* Detect whether we are running inside a CloudStudio container sandbox.
*
* WorkBuddy can spawn a CloudStudio Linux container that runs its own teamai
* hooks. That container has a different machine_id than the macOS host, so it
* derives a second local_agent_id and reports a duplicate agent card. Both
* signals below are absent on a normal Linux user machine, so this never
* suppresses reporting for legitimate standalone Linux users.
*/
function isCloudStudioSandbox(): boolean {
if (process.env.X_IDE_IS_CLOUDSTUDIO === 'TRUE') return true;
try {
return fs.existsSync('/var/run/cloudstudio');
} catch {
return false;
}
}
/**
* Build the unified log tag for local-agent debug output: `[<id6>] [<tool>]` —
* the last 6 chars of the derived agent id plus the agent name (tool), so every
* line (HTTP request/response, report/sync, command ack) reads the same way.
*/
function localAgentTag(context: LocalAgentContext): string {
const tool = context.tool ?? 'workbuddy';
return `[${resolveLocalAgentId(context).slice(-6)}] [${tool}]`;
}
function scopeKey(scope: LocalAgentScope, workspacePath?: string): string {
return scope === 'project' ? `project:${workspacePath ?? ''}` : scope;
}
function emptyManifestScope(): ManifestScope {
return { skills: {}, rules: {}, claudemd: {} };
}
async function loadManifest(): Promise<LocalAgentManifest> {
const manifest = await readJson<LocalAgentManifest>(getManifestPath());
return manifest ?? { scopes: {} };
}
async function saveManifest(manifest: LocalAgentManifest): Promise<void> {
await writeJson(getManifestPath(), manifest);
}
/** One HTTP-source agent hook recorded locally so teardown can find & remove it
* across all formats (codex has no in-file marker, so its command is stored). */
interface AgentHookRecord {
tool: string;
event: string;
command: string;
matcher?: string;
timeout?: number;
}
/** slug → record. Kept separate from the resource manifest and from the team
* managed-hooks.json so a team pull never treats agent hooks as stale. */
type AgentHookManifest = Record<string, AgentHookRecord>;
function getAgentHookManifestPath(): string {
return path.join(getLocalAgentHome(), 'agent-hooks.json');
}
async function loadAgentHookManifest(): Promise<AgentHookManifest> {
const data = await readJson<AgentHookManifest>(getAgentHookManifestPath());
return data && typeof data === 'object' ? data : {};
}
async function saveAgentHookManifest(manifest: AgentHookManifest): Promise<void> {
await writeJsonAtomic(getAgentHookManifestPath(), manifest);
}
/**
* The member's per-machine tool roots, from the teamai config that governs this
* directory: the project one when there is one, else the user-scope one.
*
* The local agent carries no LocalConfig — it addresses tool roots under $HOME
* directly — but it writes the same files `teamai pull` does, so a root the
* member relocated (CLAUDE_CONFIG_DIR, recorded by `teamai init`) has to reach
* them too. No config, or no entry, leaves the paths exactly as they were.
*/
async function memberToolRoots(workspacePath?: string): Promise<Record<string, string> | undefined> {
const { resolveMemberToolRoots } = await import('./config.js');
return resolveMemberToolRoots(workspacePath ?? process.cwd());
}
/** Claude Code's user root on this machine, honoring a relocated CLAUDE_CONFIG_DIR. */
async function claudeUserRoot(): Promise<string> {
return resolveToolRootDir(CLAUDE_TOOL_ID, DEFAULT_CLAUDE_ROOT, await memberToolRoots());
}
/**
* The settings files an agent hook for `tool` can sit in, absolute: first the
* user-scope file `teamai pull` writes and the tool reads, then the
* project-scope path that versions before #1220 wrote under $HOME, when it
* differs. Installs write the first; removals clear them all.
*/
async function agentHookSettingsPaths(config: LocalAgentConfig | null, tool: string): Promise<string[]> {
// Hook cleanup also runs after the source configuration has been cleared.
const teamConfig = createLocalAgentTeamConfig(config?.endpoint ?? 'local-agent');
const toolRoots = await memberToolRoots();
const settings = scopedToolPaths(teamConfig, { scope: 'user', toolRoots })[tool]?.settings;
if (!settings) {
throw new Error(`unsupported tool: ${tool} (no settings path)`);
}
const legacy = applyToolRoots(teamConfig.toolPaths, toolRoots)[tool]?.settings;
return [...new Set([settings, legacy ?? settings])].map((rel) => path.join(getUserHome(), rel));
}
async function memberCodexTrust(): Promise<CodexTrustPolicy> {
const { loadLocalConfig } = await import('./config.js');
return codexTrustPolicy(await loadLocalConfig() ?? {});
}
/** The member turned off teamai's Codex trust writes (`codexTrustEnabled: false`). */
async function codexTrustDisabled(): Promise<boolean> {
const { loadLocalConfig } = await import('./config.js');
return (await loadLocalConfig())?.codexTrustEnabled === false;
}
function agentHookCodexTrust(disabled: boolean, settingsPath: string): CodexTrustPolicy {
return disabled ? { kind: 'disabled' } : { kind: 'enabled', codexHome: path.dirname(settingsPath) };
}
/** Remove a settings-file agent hook from every file it can sit in. */
async function removeSettingsAgentHook(
config: LocalAgentConfig | null,
tool: string,
opts: { slug: string; command?: string },
): Promise<void> {
const disabled = await codexTrustDisabled();
for (const settingsPath of await agentHookSettingsPaths(config, tool)) {
await removeAgentHook(settingsPath, tool, opts, agentHookCodexTrust(disabled, settingsPath));
}
}
function getPluginStatePath(): string {
return path.join(getLocalAgentHome(), 'plugins.json');
}
async function readPluginState(): Promise<Record<string, PluginState>> {
return (await readJson<Record<string, PluginState>>(getPluginStatePath())) ?? {};
}
/**
* Atomically mutate the plugin-state file under an exclusive lock. If the lock
* cannot be acquired within the timeout, throws (the caller skips this cycle
* rather than writing without the lock — reconcile is throttled, so skipping is safe).
*/
async function withPluginStateLock(mutate: (m: Record<string, PluginState>) => void): Promise<void> {
const statePath = getPluginStatePath();
const lockPath = `${statePath}.lock`;
await ensureDir(path.dirname(lockPath));
const deadline = Date.now() + 5000;
let acquired = false;
while (Date.now() <= deadline) {
try { const fd = await fs.promises.open(lockPath, 'wx'); await fd.close(); acquired = true; break; }
catch (e) {
if ((e as { code?: string }).code !== 'EEXIST') throw e;
try {
const st = await fs.promises.stat(lockPath);
if (Date.now() - st.mtimeMs > 30_000) { await fs.promises.rm(lockPath, { force: true }); continue; }
} catch { /* lock vanished */ }
await new Promise((r) => setTimeout(r, 50));
}
}
if (!acquired) throw new Error('could not acquire plugin-state lock');
try {
const m = await readPluginState();
mutate(m);
await writeJson(statePath, m);
} finally {
await fs.promises.rm(lockPath, { force: true });
}
}
function getManifestScope(
manifest: LocalAgentManifest,
scope: LocalAgentScope,
workspacePath?: string,
): ManifestScope {
const key = scopeKey(scope, workspacePath);
manifest.scopes[key] ??= emptyManifestScope();
return manifest.scopes[key];
}
/**
* Canonicalize a workspace path to its physical on-disk form via realpath.
* On case-insensitive filesystems (macOS) this collapses casing variants of the
* same physical directory to one identity; it also resolves symlinks. Falls back
* to the resolved absolute path when the target does not exist (dead binding) or
* realpath fails for any other reason.
*/
async function canonicalizeWorkspacePath(value: string): Promise<string> {
const absolute = path.resolve(value);
try {
return await fs.promises.realpath(absolute);
} catch {
return absolute;
}
}
function mergeWorkspaceBindings(
existing: WorkspaceBinding | undefined,
incoming: WorkspaceBinding,
canonicalKey: string,
): WorkspaceBinding {
if (!existing) return incoming;
// pick base = whichever has a non-zero projectId; prefer existing on tie
const existingReal = existing.projectId !== 0;
const incomingReal = incoming.projectId !== 0;
if (existingReal && incomingReal && existing.projectId !== incoming.projectId) {
log.warn(
`local-agent: workspace ${canonicalKey} has conflicting project bindings ` +
`(${existing.projectId} vs ${incoming.projectId}); keeping ${existing.projectId}`,
);
}
const base = existingReal || !incomingReal ? { ...existing } : { ...incoming };
// A physical workspace tracks one owning tool (same single-owner model as
// stampWorkspaceTool). Only backfill ideType when the base lacks one; if two
// aliases were stamped by different tools, the base's ideType wins — the
// other tool re-stamps itself on its next report from the canonical path.
if (!base.ideType) base.ideType = existing.ideType ?? incoming.ideType;
return base;
}
export async function loadLocalAgentConfig(options: { dryRun?: boolean } = {}): Promise<LocalAgentConfig | null> {
const fileConfig = await readJson<LocalAgentConfig | { disabled: true }>(getConfigPath());
// A removed source must not reconnect through legacy config or environment fallback.
if (fileConfig && 'disabled' in fileConfig && fileConfig.disabled === true) return null;
if (fileConfig && 'endpoint' in fileConfig && fileConfig.endpoint) {
const config = {
...fileConfig,
endpoint: normalizeEndpoint(fileConfig.endpoint),
workspaceBindings: fileConfig.workspaceBindings ?? {},
};
// Migrate: clear legacy group-based bindings (groupId without projectId)
const removedLegacyPaths: string[] = [];
for (const [wsPath, binding] of Object.entries(config.workspaceBindings)) {
if ('groupId' in binding && !('projectId' in (binding as Record<string, unknown>))) {
delete config.workspaceBindings[wsPath];
removedLegacyPaths.push(wsPath);
}
}
if (removedLegacyPaths.length > 0 && options.dryRun) {
log.info(`[dry-run] Would remove ${removedLegacyPaths.length} legacy group-based workspace binding(s).`);
} else if (removedLegacyPaths.length > 0) {
log.warn(
`Removed ${removedLegacyPaths.length} legacy group-based workspace binding(s); ` +
`you will be prompted to re-bind on the next session.`,
);
try {
await saveLocalAgentConfig(config);
} catch (e) {
log.debug(`local-agent: failed to persist binding cleanup: ${(e as Error).message}`);
}
}
// Migrate: canonicalize binding keys to their physical on-disk path so
// case-only / symlink aliases of the same workspace collapse to one entry.
const migrated: Record<string, WorkspaceBinding> = {};
let migrationChanged = false;
for (const [wsPath, binding] of Object.entries(config.workspaceBindings)) {
const canonicalKey = await canonicalizeWorkspacePath(wsPath);
if (canonicalKey !== wsPath) migrationChanged = true;
if (migrated[canonicalKey]) migrationChanged = true;
migrated[canonicalKey] = mergeWorkspaceBindings(migrated[canonicalKey], binding, canonicalKey);
}
config.workspaceBindings = migrated;
if (migrationChanged && !options.dryRun) {
await saveLocalAgentConfig(config);
}
return config;
}
// Backfill: if config.json is missing but a legacy ~/.teamai/config.yaml has
// an HTTP team repo, auto-create config.json so v0.17.x upgraders keep capability.
const { loadLocalConfig } = await import('./config.js');
const { resolveApiKey } = await import('./api-key.js');
// Under `dryRun` the migrations above and this backfill stay in memory: nothing is written.
const legacy = await loadLocalConfig(options);
if (legacy?.repo?.kind === 'http' && legacy.repo.url) {
const endpoint = normalizeEndpoint(legacy.repo.url);
const token = resolveApiKey() ?? undefined;
const backfilled: LocalAgentConfig = {
endpoint,
token,
createdAt: new Date().toISOString(),
workspaceBindings: {},
};
if (options.dryRun) return backfilled;
try {
await saveLocalAgentConfig(backfilled);
log.debug('local-agent: backfilled config.json from legacy ~/.teamai/config.yaml (http repo)');
} catch (e) {
log.debug(`local-agent: backfill persist failed, using in-memory config: ${(e as Error).message}`);
}
return backfilled;
}
const envEndpoint =
process.env.TEAMAI_HTTP_ENDPOINT ??
process.env.TEAMAI_ENDPOINT ??
process.env.TEAMAI_API_BASE_URL;
if (!envEndpoint) return null;
return {
endpoint: normalizeEndpoint(envEndpoint),
token: process.env.TEAMAI_API_TOKEN ?? process.env.TEAMAI_TOKEN,
createdAt: new Date().toISOString(),
workspaceBindings: {},
};
}
async function saveLocalAgentConfig(config: LocalAgentConfig): Promise<void> {
await writeJsonAtomic(getConfigPath(), {
...config,
endpoint: normalizeEndpoint(config.endpoint),
workspaceBindings: config.workspaceBindings ?? {},
});
}
function createLocalAgentTeamConfig(endpoint: string): TeamaiConfig {
return TeamaiConfigSchema.parse({
team: 'local-agent',
repo: endpoint,
description: 'HTTP local agent resource cache',
});
}
/**
* Whether the member keeps what teamai delivers into `workspacePath` out of
* git (#915): the resolved flag of the config governing it, its project's,
* else the user scope's. Unknown when that config, or the git-mode team's
* teamai.yaml with no override in the config, cannot be read: `cause` says
* which, `fix` what to do (`resolveGitExclude`).
*/
async function gitExcludeEnabledFor(workspacePath: string): Promise<boolean | { cause: string; fix: string }> {
const { loadTeamConfig, resolveConfigForDir } = await import('./config.js');
let unreadable: { cause: string; fix: string } | undefined;
const config = await resolveConfigForDir(workspacePath, (configPath, error) => {
unreadable = { cause: `teamai could not read ${configPath} (${error})`, fix: `Fix ${configPath}` };
});
if (unreadable) return unreadable;
if (!config) return false;
const enabled = resolveGitExclude(config, await loadTeamConfig(config.repo.localPath));
if (enabled !== undefined) return enabled;
const override = isUnmigratedDataHome(config) ? '' : `, or set \`gitExcludeEnabled\` in ${path.join(getDataHome(config), 'config.yaml')}`;
return {
cause: `teamai could not read sharing.gitExclude from the team's teamai.yaml (${path.join(config.repo.localPath, 'teamai.yaml')})`,
fix: `Fix or restore teamai.yaml in the team repository${override}`,
};
}
/**
* The resource cache's team config for one install, carrying the workspace's
* git exclude flag so every writer and the instruction targets read the same
* value (#915). While the flag is unknown nothing is written: either value
* could move a file the other placed. `change` names what was refused
* ("install <slug>", "uninstall <slug>").
*/
async function localAgentTeamConfig(endpoint: string, scope: LocalAgentScope, workspacePath: string | undefined, change: string): Promise<TeamaiConfig> {
const teamConfig = createLocalAgentTeamConfig(endpoint);
if (scope !== 'project' || !workspacePath) return teamConfig;
const enabled = await gitExcludeEnabledFor(workspacePath);
if (typeof enabled === 'object') {
throw new Error(`${enabled.cause}, so the local agent did not ${change} in ${workspacePath}: it wrote nothing there. ${enabled.fix}.`);
}
if (!enabled) return teamConfig;
return { ...teamConfig, sharing: { ...teamConfig.sharing, gitExclude: { enabled: true } } };
}
/** The block of the skills and rules this agent installs in projects, its exclude files recorded in its state home (#915). */
function localAgentGitExcludeOwner(): GitExcludeOwner {
return { name: 'local-agent', record: stateHomeRecord(getLocalAgentHome(), 'local-agent') };
}
/**
* Whether `entry` records `tool`'s copy at `dest` (#915): by its `tools`, or,
* for an entry an older CLI wrote without them, by its `dir_name` naming the
* path or by a copy equal to the installed version.
*/
async function recordsCopy(
entry: ManifestResource | undefined, tool: string, dest: string, equalsInstalled: () => Promise<boolean>,
): Promise<boolean> {
if (!entry) return false;
if (entry.tools) return entry.tools.includes(tool);
if (entry.dir_name !== undefined && path.basename(dest) === entry.dir_name) return true;
return equalsInstalled();
}
/** Why the local agent did not install `slug` at `dest`: the file there is the member's (#915). */
function keptMembersFile(dest: string, slug: string): string {
return `Kept ${dest}: it is not teamai's (not in the local agent's records). `
+ `Rename or delete it; the local agent installs ${slug} on its next sync.`;
}
/** The tools an older CLI's `entry` counts as written to, by `recordsCopy` (#915). */
async function legacyTools(
entry: ManifestResource,
fullTeamConfig: TeamaiConfig,
targetsFor: (teamConfig: TeamaiConfig) => Promise<DeliveryTarget[]>,
equalsInstalled: (target: DeliveryTarget) => Promise<boolean>,
): Promise<string[]> {
const tools: string[] = [];
for (const [tool, toolPath] of Object.entries(fullTeamConfig.toolPaths)) {
for (const target of await targetsFor({ ...fullTeamConfig, toolPaths: { [tool]: toolPath } })) {
if (await pathExists(target.dest) && await recordsCopy(entry, tool, target.dest, () => equalsInstalled(target))) {
tools.push(tool);
break;
}
}
}
return tools;
}
/** `tools`, with `tool` when every one of its `targets` is on disk after the write. */
async function withToolIfWritten(tools: string[], tool: string, targets: DeliveryTarget[]): Promise<string[]> {
const written = targets.length > 0 && (await Promise.all(targets.map(({ dest }) => pathExists(dest)))).every(Boolean);
return [...new Set(written ? [...tools, tool] : tools)].sort();
}
/**
* The first destination of `item` for the one tool of `teamConfig` that holds
* the member's rule (#915): a file that is neither the render of `item` nor
* recorded in `entry` (for a legacy entry, equal to the render of `installed`,
* the version in the cache).
*/
async function membersRuleCopy(
teamConfig: TeamaiConfig, localConfig: LocalConfig, item: ResourceItem, entry: ManifestResource | undefined,
tool: string, installed: ResourceItem | undefined,
): Promise<string | null> {
const handler = new RulesHandler();
for (const { dest, content } of await handler.deliveryTargets(teamConfig, localConfig, item)) {
const disk = await fileHash(dest);
if (disk === null || (content !== undefined && disk === contentHash(content))) continue;
const equalsInstalled = async (): Promise<boolean> => {
if (!installed || !await pathExists(installed.sourcePath)) return false;
const render = (await handler.deliveryTargets(teamConfig, localConfig, installed)).find((target) => target.dest === dest)?.content;
return render !== undefined && disk === contentHash(render);
};
if (await recordsCopy(entry, tool, dest, equalsInstalled)) continue;
return dest;
}
return null;
}
/**
* Which files of `dest`, a tool's copy of the local agent's skill or rule
* `name` (a skill: its directory name), are teamai's (#915). Null when no
* manifest entry records that copy for `tool`; an entry an older CLI wrote,
* without tools, counts for every tool. Otherwise `teamais` are the files
* equal to what the agent writes there today from its cached source, and
* `members` every other entry (a file the member added or edited, a link, a
* repository). Read-only; judge before the cache is deleted. `config`: the
* source's, when a teardown already disabled it.
*/
export async function localAgentCopyFiles(
kind: 'skill' | 'rule', name: string, tool: string, dest: string, config?: LocalAgentConfig,
): Promise<{ teamais: string[]; members: string[] } | null> {
config ??= await loadLocalAgentConfig({ dryRun: true }) ?? undefined;
if (!config) return null;
const fullTeamConfig = createLocalAgentTeamConfig(config.endpoint);
const toolPath = fullTeamConfig.toolPaths[tool];
if (!toolPath) return null;
const real = async (file: string): Promise<string> => fs.promises.realpath(file).catch(() => path.resolve(file));
const at = await real(dest);
for (const [key, scopeManifest] of Object.entries((await loadManifest()).scopes)) {
const entries = Object.entries((kind === 'skill' ? scopeManifest.skills : scopeManifest.rules) ?? {});
const entry = entries.find(([slug, e]) => (kind === 'skill' ? e.dir_name ?? slug : slug) === name)?.[1];
if (!entry || (entry.tools && !entry.tools.includes(tool))) continue;
const { scope, workspacePath } = parseScopeKey(key);
const repoPath = await getResourceRepoPath(scope, workspacePath);
const localConfig = await createResourceLocalConfig(config, scope, repoPath, workspacePath);
const teamConfig = { ...fullTeamConfig, toolPaths: { [tool]: toolPath } };
const sourcePath = path.join(repoPath, kind === 'skill' ? 'skills' : 'rules', kind === 'skill' ? name : `${name}.md`);
const item: ResourceItem = { name, type: kind === 'skill' ? 'skills' : 'rules', sourcePath, relativePath: path.relative(repoPath, sourcePath).split(path.sep).join('/') };
const handler = kind === 'skill' ? new SkillsHandler() : new RulesHandler();
let target: DeliveryTarget | undefined;
for (const candidate of await handler.deliveryTargets(teamConfig, localConfig, item)) {
if (await real(candidate.dest) === at) target = candidate;
}
if (!target) continue;
if (kind === 'rule') {
const disk = await fileHash(dest);
const teamais = disk !== null && ((target.content !== undefined && disk === contentHash(target.content)) || disk === await fileHash(sourcePath));
return teamais ? { teamais: [dest], members: [] } : { teamais: [], members: [dest] };
}
if (await isLink(dest)) return { teamais: [], members: [dest] };
// What the agent writes there today: each cached file, SKILL.md with its frontmatter repaired.
const expected = new Map<string, string>();
for (const rel of await pathExists(sourcePath) ? await listFilesRecursive(sourcePath) : []) {
const bytes = await fse.readFile(path.join(sourcePath, rel));
const text = bytes.toString('utf-8');
const written = rel === 'SKILL.md' ? withSkillFrontmatter(text, name) : text;
expected.set(rel.split(path.sep).join('/'), contentHash(written === text ? bytes : written));
}
const result = { teamais: [] as string[], members: [] as string[] };
const walk = async (dir: string, rel: string): Promise<void> => {
for (const entry of await fse.readdir(dir, { withFileTypes: true }).catch(() => [])) {
const file = path.join(dir, entry.name);
const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
if (entry.isDirectory()) await walk(file, entryRel);
else if (entry.isFile() && expected.get(entryRel) === await fileHash(file)) result.teamais.push(file);
else result.members.push(file);
}
};
await walk(dest, '');
return result;
}
return null;
}
async function createResourceLocalConfig(
config: LocalAgentConfig,
scope: LocalAgentScope,
repoPath: string,
workspacePath?: string,
): Promise<LocalConfig> {
const projectScope = scope === 'project';
return {
repo: { localPath: repoPath, remote: config.endpoint },
username: os.userInfo().username,
scope: projectScope ? 'project' : 'user',
projectRoot: projectScope ? workspacePath : undefined,
additionalRoles: [],
// User-scope paths resolve under $HOME here, so a tool the member relocated
// must be addressed at its recorded root — the same one `teamai pull` uses.
...(projectScope ? {} : { toolRoots: await memberToolRoots(workspacePath) }),
// State a sync records (OpenCode's instructions entry) goes to the
// project's data home, where uninstall reads it.
...(projectScope && workspacePath
? { dataHome: await (await import('./config.js')).resolveDataHomeForScope('project', workspacePath) }
: {}),