forked from paperclipai/paperclip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilt-in-agents.ts
More file actions
1969 lines (1854 loc) · 76.4 KB
/
Copy pathbuilt-in-agents.ts
File metadata and controls
1969 lines (1854 loc) · 76.4 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 { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { readPaperclipSkillSyncPreference, writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import { and, desc, eq, ne } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, builtInManagedResources, companies, issueThreadInteractions, issues, routines, routineTriggers } from "@paperclipai/db";
import { syncRoutineVariablesWithTemplate } from "@paperclipai/shared";
import type { Agent, Approval, CompanySkill, PermissionKey, Routine, RoutineTrigger, RoutineVariable } from "@paperclipai/shared";
import { conflict, HttpError, notFound, unprocessable } from "../errors.js";
import { logActivity } from "./activity-log.js";
import { adapterConfigHasSecretRef, inheritCompanyCredentialEnv } from "./agent-credential-inheritance.js";
import { agentInstructionsService } from "./agent-instructions.js";
import { agentService } from "./agents.js";
import { approvalService } from "./approvals.js";
import {
readBuiltInAgentMarker,
withBuiltInAgentMarker,
} from "./built-in-agent-metadata.js";
import { companySkillService } from "./company-skills.js";
import { routineService } from "./routines.js";
import { accessService } from "./access.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { listAdapterModels } from "../adapters/registry.js";
export type BuiltInAgentStatus = "not_provisioned" | "pending_approval" | "needs_setup" | "ready" | "paused";
export interface BuiltInAgentDefinition {
key: string;
displayName: string;
featureKeys: string[];
shortPurpose: string;
defaultInstructions: string;
defaultRole: string;
defaultTitle?: string | null;
defaultIcon?: string | null;
defaultPermissions?: Record<string, unknown>;
defaultStatus?: "idle" | "paused";
defaultManager?: "single_root_agent" | null;
allowedAdapterTypes?: string[];
defaultAdapterType?: string;
defaultAdapterConfig?: Record<string, unknown>;
defaultBudgetMonthlyCents?: number;
defaultRuntimeConfig?: Record<string, unknown>;
bundle?: BuiltInAgentBundleDefinition;
}
export interface BuiltInAgentState {
definition: BuiltInAgentDefinition;
status: BuiltInAgentStatus;
agentId: string | null;
agent: Agent | null;
pauseReason: string | null;
resources: BuiltInManagedResourceState[];
approval?: Approval | null;
}
export interface BuiltInAgentProvisionInput {
adapterType?: string;
adapterConfig?: Record<string, unknown>;
budgetMonthlyCents?: number;
}
export interface BuiltInAgentProvisionActor {
requestedByAgentId?: string | null;
requestedByUserId?: string | null;
}
export interface BuiltInAgentProvisionResult {
state: BuiltInAgentState;
approval: Approval | null;
}
export type BuiltInManagedResourceKind = "instructions" | "skill" | "routine";
export type BuiltInManagedResourceStockStatus =
| "missing"
| "stock_current"
| "stock_update_available"
| "operator_modified";
export interface BuiltInManagedResourceState {
resourceKind: BuiltInManagedResourceKind;
resourceKey: string;
resourceId: string | null;
stockVersion: string;
stockHash: string;
currentHash: string | null;
stockStatus: BuiltInManagedResourceStockStatus;
updateAvailable: boolean;
resetAvailable: boolean;
changedFiles?: string[];
scheduleEnabled?: boolean;
pendingUpdateInteractionId?: string | null;
pendingUpdateIssueId?: string | null;
pendingUpdateIssueIdentifier?: string | null;
}
export interface BuiltInAgentBundleDefinition {
stockVersion: string;
instructions: {
entryFile: string;
files: Record<string, string>;
};
skill: {
skillKey: string;
displayName: string;
slug: string;
canonicalKey: string;
files: Record<string, string>;
};
routine: {
routineKey: string;
title: string;
description: string;
status: "active" | "paused";
priority: "critical" | "high" | "medium" | "low";
concurrencyPolicy: "always_enqueue" | "coalesce_if_active" | "skip_if_active";
catchUpPolicy: "enqueue_missed_with_cap" | "skip_missed";
variables: RoutineVariable[];
triggers: Array<{
kind: "schedule";
label: string | null;
enabled: boolean;
cronExpression: string;
timezone: string;
}>;
};
}
export interface RequiredBuiltInAgentWarning {
code: "built_in_agent_paused";
key: string;
agentId: string;
message: string;
pauseReason: string | null;
}
export interface RequiredBuiltInAgent {
definition: BuiltInAgentDefinition;
agent: Agent;
warning: RequiredBuiltInAgentWarning | null;
}
const BUILT_IN_AGENT_KEY_PATTERN = /^[a-z][a-z0-9_-]*$/;
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const BUILT_INS_DIR = path.resolve(moduleDir, "../built-ins/agents");
const SOURCE_BUILT_INS_DIR = path.resolve(moduleDir, "../../src/built-ins/agents");
const FALLBACK_REFLECTION_COACH_INSTRUCTIONS = [
"# Reflection Coach",
"",
"You are Paperclip's built-in Reflection Coach.",
"Review recent agent execution records, identify evidence-backed improvement patterns, and propose the smallest durable instruction, skill, or tool-description change.",
"Do not apply changes in the same run. Present a reviewable diff and wait for the required Paperclip issue-thread approval before any follow-up applies it.",
"",
].join("\n");
const FALLBACK_REFLECTION_COACH_ROUTINE = [
"Review recent agent work for coaching opportunities.",
"",
"Select recent target agents, inspect their work history and current instructions, then propose small, review-gated improvements that would prevent repeated misses.",
"",
].join("\n");
const FALLBACK_REFLECTION_COACH_SKILL = [
"---",
"name: reflection-coach",
"description: Reflect on another agent's recent execution record and propose the smallest review-gated improvement.",
"key: paperclipai/bundled/paperclip-operations/reflection-coach",
"---",
"",
"# Reflection Coach",
"",
"Review another agent's recent execution record, name evidence-backed patterns, and propose the smallest durable improvement as a reviewable diff. Do not hot-swap instructions or skills in the same run.",
"",
].join("\n");
const FALLBACK_SUMMARIZER_INSTRUCTIONS = [
"You are Summarizer, a built-in reporting agent at Paperclip.",
"",
"Turn the current state of a Paperclip scope (project, workspaces overview, or a single project workspace) into a short, honest, human-readable Markdown summary and write it back to that scope's summary slot as a new revision. Use the `summarize-status` skill as your operating procedure.",
"",
"Read-and-report only: never change issues, workspaces, or code. Cite issue identifiers, never fabricate status, keep every read company-scoped, and run on the low-cost model profile lane by default.",
"",
].join("\n");
const FALLBACK_SUMMARIZER_ROUTINE = [
"Regenerate summary slots whose scope has changed since their last revision.",
"",
"Paused by default; spends no tokens until an operator enables the schedule or runs it manually. Read-and-report only — the only write is the summary revision.",
"",
].join("\n");
const FALLBACK_SUMMARIZER_SKILL = [
"---",
"name: summarize-status",
"description: Write a short, colloquial summary for a Paperclip summary slot: open with the one or two decisions the reader must make — or, when nothing needs deciding, what to review — each with a recommendation, close with one or two recent pieces of work and where they stand, streaming status as it works.",
"key: paperclipai/bundled/paperclip-operations/summarize-status",
"---",
"",
"# Summarize status",
"",
"Turn a Paperclip scope's current state into a short, colloquial Markdown summary — opening with a `**Decide:**` block of at most two bullets (each with the decision's context, a link, and an `**I suggest:**` recommendation), followed by plain prose on the one or two things that matter most, with at most three or four inline issue links and never a trailing link list — then write it back to the scope's summary slot. When nothing needs a decision, open with `**Nothing to decide right now.**` plus a `**Review:**` block (at most two bullets) triaging what is waiting on review — easy approves vs what needs the reader's eyes — each with a link and an `**I suggest:**` recommendation. End every summary with a `**Recent work:**` block: at most two bullets, one line each, naming a recent piece of work and where it stands. Post the first `STATUS:` line immediately from the first task in context and keep streaming `STATUS:` lines while working. Not a task list. Read-and-report only; never fabricate status.",
"",
].join("\n");
const warnedBuiltInTextFallbacks = new Set<string>();
const warnedBuiltInTextReadErrors = new Set<string>();
function resolvePackageRoot(packageName: string) {
try {
return path.dirname(require.resolve(`${packageName}/package.json`));
} catch {
return null;
}
}
export function readBuiltInTextWithFallback(
label: string,
candidatePaths: string[],
fallbackText: string,
) {
const attemptedPaths = candidatePaths.filter((candidatePath) => candidatePath.trim().length > 0);
for (const candidatePath of attemptedPaths) {
try {
return readFileSync(candidatePath, "utf8");
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
const codeLabel = code || String(error);
const warningKey = [label, candidatePath, codeLabel].join(":");
if (!warnedBuiltInTextReadErrors.has(warningKey)) {
warnedBuiltInTextReadErrors.add(warningKey);
console.warn(
"[paperclip] Built-in agent asset " + label + " read error on " + candidatePath + ": " + codeLabel,
);
}
}
// Try every known runtime/source path before falling back to compiled text.
}
}
if (!warnedBuiltInTextFallbacks.has(label)) {
warnedBuiltInTextFallbacks.add(label);
console.warn(
`[paperclip] Built-in agent asset ${label} was not readable; using bundled fallback text. `
+ `Checked: ${attemptedPaths.join(", ")}`,
);
}
return fallbackText;
}
function readBuiltInText(relativePath: string, fallbackText: string) {
return readBuiltInTextWithFallback(
relativePath,
[path.join(BUILT_INS_DIR, relativePath), path.join(SOURCE_BUILT_INS_DIR, relativePath)],
fallbackText,
);
}
const skillsCatalogRoot = resolvePackageRoot("@paperclipai/skills-catalog");
const REFLECTION_COACH_INSTRUCTIONS = readBuiltInText("reflection-coach/AGENTS.md", FALLBACK_REFLECTION_COACH_INSTRUCTIONS);
const REFLECTION_COACH_ROUTINE = readBuiltInText(
"reflection-coach/routines/recent-agent-reflection.md",
FALLBACK_REFLECTION_COACH_ROUTINE,
);
const REFLECTION_COACH_SKILL = readBuiltInTextWithFallback(
"reflection-coach/SKILL.md",
[
path.resolve(
moduleDir,
"../../../packages/skills-catalog/catalog/bundled/paperclip-operations/reflection-coach/SKILL.md",
),
...(skillsCatalogRoot
? [path.join(skillsCatalogRoot, "catalog/bundled/paperclip-operations/reflection-coach/SKILL.md")]
: []),
],
FALLBACK_REFLECTION_COACH_SKILL,
);
const SUMMARIZER_INSTRUCTIONS = readBuiltInText("summarizer/AGENTS.md", FALLBACK_SUMMARIZER_INSTRUCTIONS);
const SUMMARIZER_ROUTINE = readBuiltInText(
"summarizer/routines/refresh-stale-summaries.md",
FALLBACK_SUMMARIZER_ROUTINE,
);
const SUMMARIZER_SKILL = readBuiltInTextWithFallback(
"summarizer/SKILL.md",
[
path.resolve(
moduleDir,
"../../../packages/skills-catalog/catalog/bundled/paperclip-operations/summarize-status/SKILL.md",
),
...(skillsCatalogRoot
? [path.join(skillsCatalogRoot, "catalog/bundled/paperclip-operations/summarize-status/SKILL.md")]
: []),
],
FALLBACK_SUMMARIZER_SKILL,
);
const DEFINITIONS = validateBuiltInAgentDefinitions([
{
key: "briefs",
displayName: "Briefs Agent",
featureKeys: ["briefs"],
shortPurpose: "Prepares concise operational briefs for the board and agent company.",
defaultInstructions:
"You are Paperclip's built-in Briefs agent. Produce concise, sourced operational briefs that help the board understand current company work, risks, and next actions.",
defaultRole: "general",
allowedAdapterTypes: ["codex_local", "claude_local", "gemini_local", "opencode_local", "process"],
defaultBudgetMonthlyCents: 0,
},
{
key: "learning",
displayName: "Learning Agent",
featureKeys: ["learning"],
shortPurpose: "Maintains reusable company learning from completed work and recurring patterns.",
defaultInstructions:
"You are Paperclip's built-in Learning agent. Extract durable lessons from completed work, preserve useful patterns, and keep learning artifacts grounded in source context.",
defaultRole: "general",
allowedAdapterTypes: ["codex_local", "claude_local", "gemini_local", "opencode_local", "process"],
defaultBudgetMonthlyCents: 0,
},
{
key: "reflection-coach",
displayName: "Reflection Coach",
featureKeys: ["reflection-coach"],
shortPurpose:
"Runs evidence-backed reflection loops on recent agent work, proposes small instruction and skill improvements, and requests approval before changes are applied.",
defaultInstructions: REFLECTION_COACH_INSTRUCTIONS,
defaultRole: "general",
defaultTitle: "Reflection Coach",
defaultIcon: "eye",
defaultPermissions: {
canCreateAgents: false,
canCreateSkills: false,
builtInMutationPolicy: {
requiresDisplayedDiff: true,
requiresAcceptedTaskInteraction: true,
applyInSeparateFollowUpRun: true,
},
},
defaultStatus: "paused",
defaultManager: "single_root_agent",
allowedAdapterTypes: ["claude_local", "codex_local", "gemini_local", "opencode_local", "process"],
defaultBudgetMonthlyCents: 0,
bundle: {
stockVersion: "2026-07-08",
instructions: {
entryFile: "AGENTS.md",
files: {
"AGENTS.md": REFLECTION_COACH_INSTRUCTIONS,
},
},
skill: {
skillKey: "reflection-coach",
displayName: "Reflection Coach",
slug: "reflection-coach",
canonicalKey: "paperclipai/bundled/paperclip-operations/reflection-coach",
files: {
"reflection-coach/SKILL.md": REFLECTION_COACH_SKILL,
},
},
routine: {
routineKey: "recent-agent-reflection",
title: "Review recent agent trajectories for coaching proposals",
description: REFLECTION_COACH_ROUTINE,
status: "paused",
priority: "medium",
concurrencyPolicy: "coalesce_if_active",
catchUpPolicy: "skip_missed",
variables: [
{ name: "lookbackDays", label: "Lookback days", type: "number", defaultValue: 7, required: true, options: [] },
{ name: "maxTargetAgents", label: "Max target agents", type: "number", defaultValue: 8, required: true, options: [] },
{
name: "targetAgentMode",
label: "Target agent mode",
type: "select",
defaultValue: "recent_active",
required: true,
options: ["recent_active", "recent_blocked", "recent_completed"],
},
{ name: "excludeAgentIds", label: "Excluded agent ids", type: "text", defaultValue: "", required: false, options: [] },
],
triggers: [
{
kind: "schedule",
label: "Weekly reflection review",
enabled: false,
cronExpression: "0 9 * * 1",
timezone: "UTC",
},
],
},
},
},
{
key: "summarizer",
displayName: "Summarizer",
featureKeys: ["summarizer"],
shortPurpose:
"Writes short, human-readable Markdown status summaries into project, workspaces-overview, and project-workspace summary slots on demand.",
defaultInstructions: SUMMARIZER_INSTRUCTIONS,
defaultRole: "general",
defaultTitle: "Summarizer",
defaultIcon: "sparkles",
defaultPermissions: {
canCreateAgents: false,
canCreateSkills: false,
},
defaultStatus: "paused",
defaultManager: "single_root_agent",
allowedAdapterTypes: ["claude_local", "codex_local", "gemini_local", "opencode_local", "process"],
defaultAdapterType: "claude_local",
defaultAdapterConfig: {
model: "claude-haiku-4-5",
},
defaultBudgetMonthlyCents: 0,
bundle: {
stockVersion: "2026-07-15",
instructions: {
entryFile: "AGENTS.md",
files: {
"AGENTS.md": SUMMARIZER_INSTRUCTIONS,
},
},
skill: {
skillKey: "summarize-status",
displayName: "Summarize status",
slug: "summarize-status",
canonicalKey: "paperclipai/bundled/paperclip-operations/summarize-status",
files: {
"summarize-status/SKILL.md": SUMMARIZER_SKILL,
},
},
routine: {
routineKey: "refresh-stale-summaries",
title: "Refresh stale summary slots",
description: SUMMARIZER_ROUTINE,
status: "paused",
priority: "medium",
concurrencyPolicy: "coalesce_if_active",
catchUpPolicy: "skip_missed",
variables: [
{ name: "staleAfterHours", label: "Refresh slots older than (hours)", type: "number", defaultValue: 24, required: true, options: [] },
{ name: "maxSlots", label: "Max slots to refresh per run", type: "number", defaultValue: 10, required: true, options: [] },
{
name: "scopeKinds",
label: "Scope kinds to include",
type: "select",
defaultValue: "all",
required: true,
options: ["all", "project", "workspaces_overview", "project_workspace"],
},
],
triggers: [
{
kind: "schedule",
label: "Daily stale-summary refresh",
enabled: false,
cronExpression: "0 8 * * *",
timezone: "UTC",
},
],
},
},
},
]);
const DEFINITIONS_BY_KEY = new Map(DEFINITIONS.map((definition) => [definition.key, definition]));
const ROOT_AGENT_DEFAULT_CHANGE_GRANTS: PermissionKey[] = ["agents:configure", "skills:create"];
const BUILT_IN_AGENT_DEFAULT_GRANTS: Record<string, PermissionKey[]> = {
"reflection-coach": ["agents:suggest-changes", "skills:suggest-changes"],
};
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function nonEmptyString(value: unknown) {
return typeof value === "string" && value.trim().length > 0;
}
function uniqueNonEmptyStrings(values: string[]) {
const seen = new Set<string>();
const result: string[] = [];
for (const value of values) {
const normalized = value.trim();
if (!normalized || seen.has(normalized)) continue;
seen.add(normalized);
result.push(normalized);
}
return result;
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value && typeof value === "object") {
return `{${Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
function stockHash(value: unknown) {
return `sha256:${createHash("sha256").update(stableJson(value)).digest("hex")}`;
}
function changedFileList(currentFiles: Record<string, string | null>, stockFiles: Record<string, string>) {
const paths = new Set([...Object.keys(currentFiles), ...Object.keys(stockFiles)]);
return [...paths]
.filter((filePath) => (currentFiles[filePath] ?? null) !== (stockFiles[filePath] ?? null))
.sort((left, right) => left.localeCompare(right));
}
function resourceStatus(input: {
resourceId: string | null;
currentHash: string | null;
bindingStockHash: string | null;
latestStockHash: string;
}): BuiltInManagedResourceStockStatus {
if (!input.resourceId || !input.currentHash) return "missing";
if (input.currentHash === input.latestStockHash) return "stock_current";
if (input.bindingStockHash && input.currentHash === input.bindingStockHash) {
return "stock_update_available";
}
return "operator_modified";
}
function stockState(input: {
resourceKind: BuiltInManagedResourceKind;
resourceKey: string;
resourceId: string | null;
stockVersion: string;
latestStockHash: string;
currentHash: string | null;
bindingStockHash: string | null;
changedFiles?: string[];
scheduleEnabled?: boolean;
pendingUpdateInteractionId?: string | null;
pendingUpdateIssueId?: string | null;
pendingUpdateIssueIdentifier?: string | null;
}): BuiltInManagedResourceState {
const status = resourceStatus({
resourceId: input.resourceId,
currentHash: input.currentHash,
bindingStockHash: input.bindingStockHash,
latestStockHash: input.latestStockHash,
});
return {
resourceKind: input.resourceKind,
resourceKey: input.resourceKey,
resourceId: input.resourceId,
stockVersion: input.stockVersion,
stockHash: input.latestStockHash,
currentHash: input.currentHash,
stockStatus: status,
updateAvailable: status === "stock_update_available" || status === "operator_modified",
resetAvailable: status !== "stock_current",
...(input.changedFiles && input.changedFiles.length > 0 ? { changedFiles: input.changedFiles } : {}),
...(input.scheduleEnabled !== undefined ? { scheduleEnabled: input.scheduleEnabled } : {}),
...(input.pendingUpdateInteractionId !== undefined
? { pendingUpdateInteractionId: input.pendingUpdateInteractionId }
: {}),
...(input.pendingUpdateIssueId !== undefined ? { pendingUpdateIssueId: input.pendingUpdateIssueId } : {}),
...(input.pendingUpdateIssueIdentifier !== undefined
? { pendingUpdateIssueIdentifier: input.pendingUpdateIssueIdentifier }
: {}),
};
}
export function validateBuiltInAgentDefinitions(definitions: BuiltInAgentDefinition[]) {
const seenKeys = new Set<string>();
for (const definition of definitions) {
if (!BUILT_IN_AGENT_KEY_PATTERN.test(definition.key)) {
throw new Error(`Invalid built-in agent key: ${definition.key}`);
}
if (seenKeys.has(definition.key)) {
throw new Error(`Duplicate built-in agent key: ${definition.key}`);
}
seenKeys.add(definition.key);
if (!definition.displayName.trim()) {
throw new Error(`Built-in agent ${definition.key} requires a displayName`);
}
if (!definition.shortPurpose.trim()) {
throw new Error(`Built-in agent ${definition.key} requires a shortPurpose`);
}
if (!definition.defaultInstructions.trim()) {
throw new Error(`Built-in agent ${definition.key} requires defaultInstructions`);
}
if (!definition.defaultRole.trim()) {
throw new Error(`Built-in agent ${definition.key} requires a defaultRole`);
}
if (uniqueNonEmptyStrings(definition.featureKeys).length !== definition.featureKeys.length) {
throw new Error(`Built-in agent ${definition.key} featureKeys must be unique non-empty strings`);
}
if (definition.featureKeys.length === 0) {
throw new Error(`Built-in agent ${definition.key} requires at least one featureKey`);
}
if (
definition.allowedAdapterTypes
&& uniqueNonEmptyStrings(definition.allowedAdapterTypes).length !== definition.allowedAdapterTypes.length
) {
throw new Error(`Built-in agent ${definition.key} allowedAdapterTypes must be unique non-empty strings`);
}
if (
definition.defaultAdapterType
&& definition.allowedAdapterTypes
&& !definition.allowedAdapterTypes.includes(definition.defaultAdapterType)
) {
throw new Error(`Built-in agent ${definition.key} defaultAdapterType must be allowed`);
}
if (
definition.defaultBudgetMonthlyCents !== undefined
&& (!Number.isInteger(definition.defaultBudgetMonthlyCents) || definition.defaultBudgetMonthlyCents < 0)
) {
throw new Error(`Built-in agent ${definition.key} defaultBudgetMonthlyCents must be a non-negative integer`);
}
if (definition.bundle) {
if (!definition.bundle.stockVersion.trim()) {
throw new Error(`Built-in agent ${definition.key} bundle requires a stockVersion`);
}
if (!definition.bundle.instructions.files[definition.bundle.instructions.entryFile]) {
throw new Error(`Built-in agent ${definition.key} bundle instructions require the entry file`);
}
if (!definition.bundle.skill.files[`${definition.bundle.skill.slug}/SKILL.md`]) {
throw new Error(`Built-in agent ${definition.key} bundle skill requires SKILL.md`);
}
if (!definition.bundle.routine.description.trim()) {
throw new Error(`Built-in agent ${definition.key} bundle routine requires a description`);
}
}
}
return definitions.map((definition) => ({
...definition,
featureKeys: [...definition.featureKeys],
allowedAdapterTypes: definition.allowedAdapterTypes ? [...definition.allowedAdapterTypes] : undefined,
defaultAdapterConfig: definition.defaultAdapterConfig ? { ...definition.defaultAdapterConfig } : undefined,
bundle: definition.bundle ? {
...definition.bundle,
instructions: {
...definition.bundle.instructions,
files: { ...definition.bundle.instructions.files },
},
skill: {
...definition.bundle.skill,
files: { ...definition.bundle.skill.files },
},
routine: {
...definition.bundle.routine,
variables: definition.bundle.routine.variables.map((variable) => ({ ...variable, options: [...variable.options] })),
triggers: definition.bundle.routine.triggers.map((trigger) => ({ ...trigger })),
},
} : undefined,
}));
}
export function listBuiltInAgentDefinitions() {
return DEFINITIONS.map((definition) => ({
...definition,
featureKeys: [...definition.featureKeys],
allowedAdapterTypes: definition.allowedAdapterTypes ? [...definition.allowedAdapterTypes] : undefined,
defaultAdapterConfig: definition.defaultAdapterConfig ? { ...definition.defaultAdapterConfig } : undefined,
}));
}
export function getBuiltInAgentDefinition(key: string) {
return DEFINITIONS_BY_KEY.get(key) ?? null;
}
export function requireBuiltInAgentDefinition(key: string) {
const definition = getBuiltInAgentDefinition(key);
if (!definition) throw notFound(`Built-in agent definition not found: ${key}`);
return definition;
}
function defaultAdapterType(definition: BuiltInAgentDefinition) {
return definition.defaultAdapterType ?? definition.allowedAdapterTypes?.[0] ?? "process";
}
function normalizeAdapterType(value: unknown) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function selectPreferredAdapterType(
definition: BuiltInAgentDefinition,
usage: Array<{ adapterType: string; count: number }>,
) {
const fallback = defaultAdapterType(definition);
const preference = definition.allowedAdapterTypes ?? [];
if (preference.length === 0) return fallback;
const rank = new Map(preference.map((adapterType, index) => [adapterType, index]));
let selected: { adapterType: string; count: number; rank: number } | null = null;
for (const entry of usage) {
const adapterRank = rank.get(entry.adapterType);
if (adapterRank === undefined) continue;
if (!selected || entry.count > selected.count || (entry.count === selected.count && adapterRank < selected.rank)) {
selected = { ...entry, rank: adapterRank };
}
}
return selected?.adapterType ?? fallback;
}
function assertAdapterAllowed(definition: BuiltInAgentDefinition, adapterType: string) {
if (definition.allowedAdapterTypes && !definition.allowedAdapterTypes.includes(adapterType)) {
throw unprocessable(`Adapter type ${adapterType} is not allowed for built-in agent ${definition.key}`, {
code: "built_in_agent_adapter_not_allowed",
key: definition.key,
allowedAdapterTypes: definition.allowedAdapterTypes,
});
}
}
function hasCompleteAdapterConfig(adapterType: string, adapterConfig: unknown) {
if (!isPlainRecord(adapterConfig)) return false;
if (["process", "command"].includes(adapterType)) {
return nonEmptyString(adapterConfig.command) || nonEmptyString(adapterConfig.script);
}
if (adapterType === "http") {
return nonEmptyString(adapterConfig.url) || nonEmptyString(adapterConfig.endpoint) || nonEmptyString(adapterConfig.webhookUrl);
}
if (adapterType === "openclaw_gateway" || adapterType === "hermes_gateway") {
return nonEmptyString(adapterConfig.baseUrl) || nonEmptyString(adapterConfig.url);
}
return nonEmptyString(adapterConfig.model);
}
export function deriveBuiltInAgentStatus(agent: Pick<Agent, "adapterType" | "adapterConfig" | "status" | "pausedAt"> | null): BuiltInAgentStatus {
if (!agent) return "not_provisioned";
if (agent.status === "pending_approval") return "pending_approval";
if (agent.status === "paused" || agent.pausedAt) return "paused";
return hasCompleteAdapterConfig(agent.adapterType, agent.adapterConfig) ? "ready" : "needs_setup";
}
function builtInMetadata(definition: BuiltInAgentDefinition, existing?: Record<string, unknown> | null) {
return withBuiltInAgentMarker(existing, {
key: definition.key,
featureKeys: definition.featureKeys,
});
}
function definitionPatch(definition: BuiltInAgentDefinition, input: BuiltInAgentProvisionInput = {}) {
const adapterType = input.adapterType ?? defaultAdapterType(definition);
assertAdapterAllowed(definition, adapterType);
return {
name: definition.displayName,
role: definition.defaultRole,
title: definition.defaultTitle ?? null,
icon: definition.defaultIcon ?? null,
capabilities: definition.shortPurpose,
adapterType,
adapterConfig: input.adapterConfig ?? definition.defaultAdapterConfig ?? {},
permissions: definition.defaultPermissions ?? {},
budgetMonthlyCents: input.budgetMonthlyCents ?? definition.defaultBudgetMonthlyCents ?? 0,
};
}
async function assertKnownBuiltInAgentModel(
definition: BuiltInAgentDefinition,
input: BuiltInAgentProvisionInput,
) {
const adapterType = input.adapterType ?? defaultAdapterType(definition);
const adapterConfig = input.adapterConfig ?? definition.defaultAdapterConfig ?? {};
const model = typeof adapterConfig.model === "string" ? adapterConfig.model.trim() : "";
if (!model || !hasCompleteAdapterConfig(adapterType, adapterConfig)) return;
const models = await listAdapterModels(adapterType);
if (models.length === 0 || models.some((candidate) => candidate.id === model)) return;
throw unprocessable(`Model "${model}" is not available for adapter ${adapterType}.`, {
code: "built_in_agent_model_unknown",
key: definition.key,
adapterType,
model,
availableModelIds: models.map((candidate) => candidate.id),
});
}
function builtInAgentNotConfiguredError(state: BuiltInAgentState) {
return new HttpError(412, `Built-in agent is not configured: ${state.definition.key}`, {
code: "built_in_agent_not_configured",
key: state.definition.key,
status: state.status,
agentId: state.agentId,
featureKeys: state.definition.featureKeys,
});
}
function hasProvisionSetupInput(input: BuiltInAgentProvisionInput) {
return input.adapterType !== undefined || input.adapterConfig !== undefined || input.budgetMonthlyCents !== undefined;
}
function rowIsBuiltInAgent(row: typeof agents.$inferSelect, key: string) {
const marker = readBuiltInAgentMarker(row.metadata);
return marker?.key === key;
}
export function builtInAgentService(
db: Db,
options: { pluginWorkerManager?: PluginWorkerManager } = {},
) {
const agentSvc = agentService(db);
const accessSvc = accessService(db);
const approvalSvc = approvalService(db);
const instructionsSvc = agentInstructionsService();
const skillSvc = companySkillService(db);
// Routine runs dispatch heartbeat runs, which acquire sandbox leases. Without
// the worker manager the runtime cannot resolve a plugin-backed sandbox
// provider and every run fails setup.
const routineSvc = routineService(db, {
pluginWorkerManager: options.pluginWorkerManager,
});
async function findSingleRootManager(companyId: string) {
const roots = await db
.select()
.from(agents)
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
const nonBuiltInRoots = roots.filter((agent) => !readBuiltInAgentMarker(agent.metadata) && !agent.reportsTo);
return nonBuiltInRoots.length === 1 ? nonBuiltInRoots[0]!.id : null;
}
async function ensureAgentDefaultGrants(companyId: string, agentId: string, grantKeys: PermissionKey[]) {
if (grantKeys.length === 0) return 0;
await accessSvc.ensureMembership(companyId, "agent", agentId, "member", "active");
let ensured = 0;
for (const permissionKey of grantKeys) {
await accessSvc.setPrincipalPermission(companyId, "agent", agentId, permissionKey, true, null);
ensured += 1;
}
return ensured;
}
async function ensureBuiltInAgentDefaultGrants(agent: Agent, definition: BuiltInAgentDefinition) {
if (agent.status === "pending_approval" || agent.status === "terminated") return 0;
return ensureAgentDefaultGrants(
agent.companyId,
agent.id,
BUILT_IN_AGENT_DEFAULT_GRANTS[definition.key] ?? [],
);
}
async function ensureRootAgentDefaultChangeGrants(companyId: string) {
const rows = await db
.select()
.from(agents)
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
const rootCeoRows = rows.filter((agent) =>
!readBuiltInAgentMarker(agent.metadata) &&
!agent.reportsTo &&
agent.role.trim().toLowerCase() === "ceo" &&
agent.status !== "pending_approval"
);
if (rootCeoRows.length !== 1) return 0;
return ensureAgentDefaultGrants(companyId, rootCeoRows[0]!.id, ROOT_AGENT_DEFAULT_CHANGE_GRANTS);
}
async function ensureCompanyDefaultAgentGrants(companyId: string) {
let ensured = await ensureRootAgentDefaultChangeGrants(companyId);
for (const definition of DEFINITIONS) {
const agent = await findSingleAgent(companyId, definition);
if (!agent) continue;
ensured += await ensureBuiltInAgentDefaultGrants(agent as Agent, definition);
}
return ensured;
}
async function defaultProvisionInput(companyId: string, definition: BuiltInAgentDefinition, input: BuiltInAgentProvisionInput) {
if (input.adapterType || input.adapterConfig) return input;
if (definition.defaultAdapterType || definition.defaultAdapterConfig) {
return {
...input,
adapterType: definition.defaultAdapterType,
adapterConfig: definition.defaultAdapterConfig ? { ...definition.defaultAdapterConfig } : undefined,
};
}
if (!definition.bundle) return input;
const rows = await db
.select({
adapterType: agents.adapterType,
adapterConfig: agents.adapterConfig,
})
.from(agents)
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
const candidate = rows.find((row) =>
definition.allowedAdapterTypes?.includes(row.adapterType)
&& hasCompleteAdapterConfig(row.adapterType, row.adapterConfig)
);
if (!candidate) return input;
return {
...input,
adapterType: candidate.adapterType,
adapterConfig: {},
};
}
async function getManagedResourceBinding(
companyId: string,
bundleKey: string,
resourceKind: BuiltInManagedResourceKind,
resourceKey: string,
) {
return db
.select()
.from(builtInManagedResources)
.where(and(
eq(builtInManagedResources.companyId, companyId),
eq(builtInManagedResources.bundleKey, bundleKey),
eq(builtInManagedResources.resourceKind, resourceKind),
eq(builtInManagedResources.resourceKey, resourceKey),
))
.then((rows) => rows[0] ?? null);
}
async function upsertManagedResourceBinding(input: {
companyId: string;
bundleKey: string;
resourceKind: BuiltInManagedResourceKind;
resourceKey: string;
resourceId: string;
stockVersion: string;
stockHash: string;
defaultsJson: Record<string, unknown>;
}) {
const now = new Date();
return db
.insert(builtInManagedResources)
.values(input)
.onConflictDoUpdate({
target: [
builtInManagedResources.companyId,
builtInManagedResources.bundleKey,
builtInManagedResources.resourceKind,
builtInManagedResources.resourceKey,
],
set: {
resourceId: input.resourceId,
stockVersion: input.stockVersion,
stockHash: input.stockHash,
defaultsJson: input.defaultsJson,
updatedAt: now,
},
})
.returning()
.then((rows) => rows[0] ?? null);
}
async function currentInstructionFiles(agent: Agent, bundle: BuiltInAgentBundleDefinition) {
const currentFiles: Record<string, string | null> = {};
for (const filePath of Object.keys(bundle.instructions.files)) {
try {
currentFiles[filePath] = (await instructionsSvc.readFile(agent, filePath)).content;
} catch {
currentFiles[filePath] = null;
}
}
return currentFiles;
}
async function materializeInstructions(agent: Agent, definition: BuiltInAgentDefinition, mode: "reconcile" | "reset") {
const bundle = definition.bundle!;
const stock = stockHash(bundle.instructions.files);
const binding = await getManagedResourceBinding(agent.companyId, definition.key, "instructions", "AGENTS.md");
const currentFiles = await currentInstructionFiles(agent, bundle);
const currentHash = Object.values(currentFiles).some((value) => value === null) ? null : stockHash(currentFiles);
const currentState = stockState({
resourceKind: "instructions",
resourceKey: "AGENTS.md",
resourceId: agent.id,
stockVersion: bundle.stockVersion,
latestStockHash: stock,
currentHash,
bindingStockHash: binding?.stockHash ?? null,
changedFiles: changedFileList(currentFiles, bundle.instructions.files),
});
const shouldWrite =
mode === "reset"
|| currentState.stockStatus === "missing"
|| currentState.stockStatus === "stock_update_available";
if (!shouldWrite) {
if (!binding && currentHash === stock) {
await upsertManagedResourceBinding({
companyId: agent.companyId,
bundleKey: definition.key,
resourceKind: "instructions",
resourceKey: "AGENTS.md",
resourceId: agent.id,
stockVersion: bundle.stockVersion,
stockHash: stock,
defaultsJson: {
entryFile: bundle.instructions.entryFile,
files: Object.keys(bundle.instructions.files),