Repository navigation
Expand file tree
/
Copy pathlocal-agent.ts
More file actions
8502 lines (6802 loc) · 320 KB
/
Copy pathlocal-agent.ts
File metadata and controls
8502 lines (6802 loc) · 320 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 { isDeepStrictEqual } from 'node:util';
import { promisify } from 'node:util';
import fse from 'fs-extra';
import { z } from 'zod';
import { log } from './utils/logger.js';
import { detachChild } from './utils/exec.js';
import { parseFrontmatter } from './utils/frontmatter.js';
import {
ensureDir,
errnoCode,
fileHash,
listDirs,
listFilesRecursive,
pruneEmptyDirs,
pathExists,
readFileSafe,
readFileIfExists,
readJson,
remove,
writeFile,
writeFileAtomic,
writeJson,
writeJsonAtomic,
} from './utils/fs.js';
import { RulesHandler, SkillsHandler } from './resources/index.js';
import { isBridgedTeamHookTool } from './bridged-team-hooks.js';
import { injectHooksToAllTools, applyAgentHook, applyBridgedAgentHook, hasBridgedAgentHook, removeAgentHook, removeBridgedAgentHook, 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 { getsRulesFromExtension, getsRulesFromSessionHook, ruleStemFromFilename } from './resources/rule-format.js';
import { inlineRulesLocationOf, unreadableConfigOf } from './resources/rules.js';
import { resolveTeamaiEntryScript } from './builtin-hooks.js';
import { assertSafeResourceName } from './utils/path-safety.js';
import {
supportsTransport,
renderJsonEntry,
renderCodexBlock,
entryHash,
museEntryHash,
serverNameProblem,
type McpJsonEntry,
} from './resources/mcp-format.js';
import {
readJsonDoc,
isTeamaiBareCopy,
ownsJsonMcpEntry,
writeJsonDoc,
restoreMcpDoc,
writeCodexAtomic,
spliceCodexBlock,
codexServerNames,
codexBlockIn,
recordedFileOf,
sameMcpFile,
claimedByOtherTools,
adoptMcpEntriesForOwners,
deleteEmptiedMcpFile,
describeMcpLocation,
loadMcpManifest,
mcpKeyOf,
mcpOwnersOf,
recordedMcpTarget,
sameMcpPlace,
logLeftMcpFiles,
mcpManifestKey,
mcpRelocated,
projectMcpLocations,
resolveMcpTargets,
saveMcpManifest,
type McpKey,
type McpOwners,
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,
scopedToolPaths,
applyToolRoots,
getDataHome,
isGitExcludeEnabled,
isUnmigratedDataHome,
resolveGitExclude,
resolveToolRootDir,
CLAUDE_TOOL_ID,
DEFAULT_CLAUDE_ROOT,
getTokenPath,
TEAMAI_CLAUDEMD_START,
TEAMAI_CLAUDEMD_END,
TEAMAI_RULES_START,
TEAMAI_RULES_END,
TEAMAI_TEAM_RULES_START,
TEAMAI_TEAM_RULES_END,
TeamaiConfigSchema,
managedMcpManifestPath,
managedMcpManifestKey,
managedMcpWorkspaceId,
type DashboardEvent,
type DeliveryTarget,
JsonValueSchema,
type JsonValue,
type LocalConfig,
type ManagedMcpManifest,
type ManagedMcpRecord,
type McpServerDef,
type McpTransport,
type ResourceItem,
type TeamaiConfig,
} from './types.js';
import { getUserHome } from './utils/home.js';
import { checkoutForRepoAnchor, 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 { hookSettingsFile, installOf, locate, ownOf, writable, type FilePlace, type Install } from './locate.js';
import { DELIVERED_MODEL_TOOLS, mcpFormatOf, mcpScopeFor, type DeliveredModelTool } from './tool-registry.js';
import { acquireLock, releaseLock } from './update.js';
import { isJsonObject, JsonObjectSchema, type JsonObject } from './types.js';
import { editJsonText, parseJson, parseJsonAs } from './utils/json.js';
import { parseYaml } from './utils/yaml.js';
import { resolveOpenclawConfigPath } from './openclaw-home.js';
import { realHost, toolHome } from './tool-home.js';
import YAML from 'yaml';
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;
}
/**
* projectName of a workspace that is enrolled (`teamai bind-project` ran in it)
* but has no ClawPro project yet. Like `__skipped__` it reports project_id 0;
* only this state prompts for a project. A workspace with no binding entry at
* all is not enrolled: the local agent does not sync there, and only says so
* once (see unenrolledNotice).
*/
const PENDING_BINDING_NAME = '__pending__';
export interface LocalAgentConfig {
endpoint: string;
/** Token for an agent with no entry in `agentTokens` (one set before per-agent tokens). */
token?: string;
/**
* The backend binds an agent access token (`sk-`) to the first agent instance
* that reports with it, and an instance is one agent type on one machine. So
* each agent needs its own token: keyed by normalized agent type.
*/
agentTokens?: Record<string, 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;
/** When `teamai local-agent` first set this up; a hand-written file may leave it out. */
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[];
};
}
type ModelConfigTool = DeliveredModelTool;
// SAFETY: DELIVERED_MODEL_TOOLS holds exactly the DeliveredModelTool ids; zod only needs the non-empty tuple type.
const ModelConfigToolSchema = z.enum(DELIVERED_MODEL_TOOLS as [ModelConfigTool, ...ModelConfigTool[]]);
/** The provider container every delivered candidate shares, checked before use. */
const MANAGED_PROVIDER = 'teamai';
/** The DSH credential-store reference the managed provider names. */
const DSH_CREDENTIAL_REF = 'TEAMAI_MODEL_API_KEY';
export type ModelDeliveryCommit = (record: ModelDeliveryRecord) => Promise<void>;
type FileRecord = ModelDeliveryRecord['files'][string];
type EntryRecord = FileRecord['entries'];
type CredentialRecord = NonNullable<ModelDeliveryRecord['credentials']>[string];
const DSH_LLM_ROW_ID = 'llm-pi-ai';
const DSH_LLM_ROW_NAME = '@deepseek-ai/dsh-llm-pi-ai';
const DSH_BASE_BUNDLE = '@deepseek-ai/dsh-base';
/** The provider fields teamai authors; any other provider key is the member's. */
const OPENCLAW_CONTAINER_KEYS = ['api', 'apiKey', 'baseUrl'];
const HERMES_CONTAINER_KEYS = ['api', 'api_key', 'discover_models', 'transport'];
const DSH_CONTAINER_KEYS = ['api', 'apiKeyEnv', 'baseURL'];
const ModelDeliveryEntryRecordSchema = z.object({
provider: z.string().min(1),
name: z.string().optional(),
hash: z.string().min(1),
}).catchall(JsonValueSchema);
const ModelDeliveryFileRecordSchema = z.object({
agent: ModelConfigToolSchema,
provider: z.string().min(1),
entries: z.record(z.string(), ModelDeliveryEntryRecordSchema),
/** Hash of the provider fields teamai authored, excluding models; absence means unproven ownership. */
containerHash: z.string().min(1).optional(),
/** The DSH llm-pi-ai row did not exist before teamai wrote it. */
rowCreated: z.boolean().optional(),
/** The DSH llm-pi-ai row already carried a config before teamai wrote it. */
rowHadConfig: z.boolean().optional(),
}).catchall(JsonValueSchema);
const ModelDeliveryCredentialRecordSchema = z.object({
ref: z.string().min(1),
hash: z.string().min(1),
created: z.boolean().optional(),
/** False when the same-named reference already existed, so cleanup leaves it alone. */
refOwned: z.boolean().optional(),
}).catchall(JsonValueSchema);
/** teamai's record of the delivered model files it wrote; no secret is stored here. */
export const ModelDeliveryRecordSchema = z.object({
version: z.literal(1),
files: z.record(z.string(), ModelDeliveryFileRecordSchema),
credentials: z.record(z.string(), ModelDeliveryCredentialRecordSchema).optional(),
}).catchall(JsonValueSchema);
export type ModelDeliveryRecord = z.infer<typeof ModelDeliveryRecordSchema>;
export interface DeliveredModel {
provider: string;
model_id: string;
name: string;
base_url: string;
api_key: string;
max_tokens?: number;
context_window?: number;
input_types?: string[];
}
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>;
deliveredModels?: Partial<Record<ModelConfigTool, ModelDeliveryRecord>>;
}
const ManagedModelIdsSchema = z.record(z.string(), z.string());
const BuddyModelManifestSchema = z.looseObject({
codebuddy: ManagedModelIdsSchema.optional(),
workbuddy: ManagedModelIdsSchema.optional(),
providersByAgent: z.record(z.string(), ManagedModelIdsSchema).optional(),
createdModelsFile: z.boolean().optional(),
});
/** teamai's model record, `model-manifest.json`; unknown keys are kept for a newer version. */
const ModelConfigManifestSchema = BuddyModelManifestSchema.extend({
claudeEnv: ManagedModelIdsSchema.optional(),
providers: ManagedModelIdsSchema.optional(),
workspaceModels: z.record(z.string(), BuddyModelManifestSchema).optional(),
deliveredModels: z.partialRecord(ModelConfigToolSchema, ModelDeliveryRecordSchema).optional(),
}) satisfies z.ZodType<ModelConfigManifest>;
type ModelAgentKind = 'codebuddy' | 'workbuddy' | 'claude' | ModelConfigTool;
type BuddyAgentKind = 'codebuddy' | 'workbuddy';
/** A string field of a file another tool owns, absent when it holds anything else. */
const OptionalText = z.string().optional().catch(undefined);
/** The SKILL.md frontmatter fields the local agent reads. */
const SkillFrontmatterSchema = z.object({ name: OptionalText, version: JsonValueSchema.optional().catch(undefined) });
/** The fields of a failed `execFile` the local agent reports; each is absent when it holds something else. */
const ExecFailureSchema = z.object({
stderr: OptionalText,
message: OptionalText,
killed: z.boolean().optional().catch(undefined),
code: OptionalText,
});
/** The message of a caught error; a thrown non-Error reads as its string form. */
function messageOf(cause: unknown): string {
return cause instanceof Error ? cause.message : String(cause);
}
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';
if (normalized === 'openclaw' || normalized === 'hermes' || normalized === 'dsh') return normalized;
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.flatMap((content) => {
const trimmed = content.trim();
return trimmed ? [trimmed] : [];
});
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 convention — `~/.<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: {} };
}
/** A manifest scope as a JSON object; a hand edit can leave one null. */
const ManifestScopeObjectSchema = z.looseObject({});
async function loadManifest(): Promise<LocalAgentManifest> {
const manifest = await readJson<LocalAgentManifest>(getManifestPath());
if (!manifest) return { scopes: {} };
// A scope that is not an object records nothing to update or remove; the others stay as written.
const scopes = Object.entries(manifest.scopes ?? {}).filter(([, scope]) => ManifestScopeObjectSchema.safeParse(scope).success);
return { ...manifest, scopes: Object.fromEntries(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());
// A file that holds no JSON object or array reads as empty, as it always has.
return data instanceof 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, in its home a
* recorded or env move relocates, then the project-scope path that versions
* before #1220 wrote under $HOME, and the default home's file, when they
* differ. 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;
const home = getUserHome();
return [...new Set([hookSettingsFile(tool, home, settings), ...[settings, legacy ?? settings].map((rel) => path.join(home, rel))])];
}
async function memberCodexTrust(): Promise<CodexTrustPolicy> {
const { loadLocalConfig, loadMemberSettings } = await import('./config.js');
// oxlint-disable-next-line teamai/config-load-options -- Codex trust reconciliation retains normal config migration and has no preview option
const local = await loadLocalConfig();
const settings = local?.scope === 'user' ? local : { ...(await loadMemberSettings()), ...local };
return codexTrustPolicy(settings);
}
/** The member turned off teamai's Codex trust writes (`codexTrustEnabled: false`). */
async function codexTrustDisabled(): Promise<boolean> {
const { loadLocalConfig, loadMemberSettings } = await import('./config.js');
// oxlint-disable-next-line teamai/config-load-options -- Codex trust reconciliation retains normal config migration and has no preview option
const local = await loadLocalConfig();
const settings = local?.scope === 'user' ? local : { ...(await loadMemberSettings()), ...local };
return settings.codexTrustEnabled === false;
}
function agentHookCodexTrust(disabled: boolean, settingsPath: string): CodexTrustPolicy {
return disabled ? { kind: 'disabled' } : { kind: 'enabled', codexHome: path.dirname(settingsPath) };
}
/**
* Remove an installed agent hook from where its tool keeps it, and from the
* file an earlier release generated for an adapter tool (a Hermes entry, an
* OpenClaw-family hook, an OpenCode plugin, a Pi extension).
*/
async function removeInstalledAgentHook(config: LocalAgentConfig | null, slug: string, rec: AgentHookRecord): Promise<void> {
if (isBridgedTeamHookTool(rec.tool)) await removeBridgedAgentHook(rec.tool, slug);
else if (!OPENCLAW_TOOLS.has(rec.tool)) await removeSettingsAgentHook(config, rec.tool, { slug, command: rec.command });
if (rec.tool === 'hermes') {
const { removeHermesAgentHook } = await import('./hermes-hooks.js');
await removeHermesAgentHook({ slug, event: rec.event, command: rec.command });
} else if (OPENCLAW_TOOLS.has(rec.tool)) {
const { removeOpenClawAgentHook } = await import('./openclaw-hooks.js');
await removeOpenClawAgentHook({ slug, tool: rec.tool });
} else if (rec.tool === 'opencode') {
const { removeOpencodeAgentHook } = await import('./opencode-hooks.js');
await removeOpencodeAgentHook({ slug, baseDir: getUserHome(), scope: 'user' });
} else if (rec.tool === 'pi') {
const { removePiAgentHook } = await import('./pi-hooks.js');
await removePiAgentHook(slug);
}
}
/** Remove a settings-file agent hook from every file it can sit in. */
/**
* Move each agent hook an earlier release wrote in a bridged tool's own format
* (a Hermes config entry, an OpenClaw handler, an OpenCode plugin, a Pi
* extension) into the tool's bridged file, where it blocks and matches as in
* Claude Code. The server sends no install again for a hook already in place.
*/
async function moveAgentHooksToBridge(config: LocalAgentConfig): Promise<void> {
for (const [slug, rec] of Object.entries(await loadAgentHookManifest())) {
if (!isBridgedTeamHookTool(rec.tool) || await hasBridgedAgentHook(rec.tool, slug)) continue;
try {
await removeInstalledAgentHook(config, slug, rec);
await applyBridgedAgentHook(rec.tool, { slug, event: rec.event, command: rec.command, matcher: rec.matcher, timeout: rec.timeout ?? 10 });
} catch (e) {
log.warn(`Could not move agent hook ${slug} for ${rec.tool} to teamai's hook bridge: ${e instanceof Error ? e.message : String(e)}. The next session tries again.`);
}
}
}
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 instanceof Error && 'code' in e && e.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;
}
/** A string map of config.json: an entry that is not text is left out. */
const TextMapSchema = z.record(z.string(), JsonValueSchema).transform((map) => Object.fromEntries(
Object.entries(map).flatMap(([key, value]): Array<[string, string]> => {
const text = z.string().safeParse(value);
return text.success ? [[key, text.data]] : [];
})));
/**
* config.json as teamai reads it. A person edits it too (`routes` is set by
* hand only), so a field of another type reads as absent and a map entry that
* is not text is left out; the workspace bindings stay as written for the load
* to read one by one. Unknown keys are kept for the write back, after the
* known ones, which are listed in the order teamai writes them.
*/
const StoredLocalAgentConfigSchema = z.looseObject({
endpoint: z.string(),
token: OptionalText,
agentTokens: TextMapSchema.optional().catch(undefined),
localAgentId: OptionalText,
createdAt: OptionalText,
workspaceBindings: z.record(z.string(), JsonValueSchema).catch({}),
userGroupId: z.number().optional().catch(undefined),
userGroupName: OptionalText,
routes: TextMapSchema.optional().catch(undefined),
});
/** A workspace binding of config.json; one whose projectId is not a number binds nothing. */
const WorkspaceBindingSchema = z.looseObject({
projectId: z.number(),
projectName: OptionalText,
boundAt: z.string().catch(''),
ideType: OptionalText,
});
/**
* The config a config.json value stores, or null when it names no endpoint,
* with the paths of the legacy group-based bindings (groupId without
* projectId) it leaves out.
*/
function storedLocalAgentConfig(json: JsonValue | undefined): { config: LocalAgentConfig; removedLegacyPaths: string[] } | null {
const stored = StoredLocalAgentConfigSchema.safeParse(json);
if (!stored.success || !stored.data.endpoint) return null;
const removedLegacyPaths: string[] = [];
const workspaceBindings: Record<string, WorkspaceBinding> = {};
for (const [wsPath, raw] of Object.entries(stored.data.workspaceBindings)) {
const binding = WorkspaceBindingSchema.safeParse(raw);
if (binding.success) {
workspaceBindings[wsPath] = binding.data;
} else if (isJsonObject(raw) && 'groupId' in raw && !('projectId' in raw)) {
removedLegacyPaths.push(wsPath);
}
}