@app-vitals/agent-admin 1.43.0 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.43.0",
3
+ "version": "1.44.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.135.0",
45
- "@app-vitals/agent-lib": "1.43.0",
45
+ "@app-vitals/agent-lib": "1.44.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -10,6 +10,7 @@
10
10
  import type { AgentCronJob, PrismaClient } from "../prisma/client/client.ts";
11
11
  import { type Clock, SystemClock } from "./clock.ts";
12
12
  import { NotFoundError, UnprocessableEntityError } from "./errors.ts";
13
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
13
14
  import type {
14
15
  SpecialtyDefaultCron,
15
16
  SpecialtyDefaultsResolver,
@@ -560,101 +561,117 @@ export class AgentCronJobService {
560
561
  where: { agentId, system: true },
561
562
  });
562
563
 
563
- // Build a map of name → existing cron
564
- const existingByName = new Map<string, AgentCronJob>();
565
- for (const cron of existingSystemCrons) {
566
- if (cron.name) {
567
- existingByName.set(cron.name, cron);
568
- }
569
- }
570
-
571
- // Build set of valid default cron names for orphan detection
572
- const systemCronNames = new Set(defaultCrons.map((c) => c.name));
573
-
574
- let created = 0;
575
- let updated = 0;
576
- let deleted = 0;
577
-
578
564
  // Wrap all mutations in a transaction so a crash mid-loop cannot leave
579
565
  // the agent missing required system crons (e.g. shipwright-dev-task).
580
- await this.prisma.$transaction(async (tx) => {
581
- // Pass 1: reconcile each default cron entry, recording name → row id.
582
- const idByName = new Map<string, string>();
583
- for (const systemCron of defaultCrons) {
584
- const existing = existingByName.get(systemCron.name);
585
-
586
- if (existing) {
587
- // Update in place — preserves id (and thus AgentCronRun history,
588
- // which cascade-deletes when its AgentCronJob is deleted) and the
589
- // existing enabled state.
590
- await tx.agentCronJob.update({
591
- where: { id: existing.id },
592
- data: {
593
- schedule: systemCron.schedule,
594
- prompt: systemCron.prompt,
595
- silent: systemCron.silent ?? false,
596
- preCheck: systemCron.preCheck ?? null,
597
- },
598
- });
599
- idByName.set(systemCron.name, existing.id);
600
- updated++;
601
- } else {
602
- const createdCron = await tx.agentCronJob.create({
603
- data: {
604
- agentId,
605
- name: systemCron.name,
606
- system: true,
607
- schedule: systemCron.schedule,
608
- prompt: systemCron.prompt,
609
- silent: systemCron.silent ?? false,
610
- preCheck: systemCron.preCheck ?? null,
611
- channel: null,
612
- user: null,
613
- enabled: systemCron.enabled ?? true,
614
- },
615
- });
616
- idByName.set(systemCron.name, createdCron.id);
617
- created++;
618
- }
619
- }
566
+ return this.prisma.$transaction((tx) =>
567
+ applySystemCronDefaults(tx, agentId, defaultCrons, existingSystemCrons),
568
+ );
569
+ }
570
+ }
620
571
 
621
- // Pass 2: link declared parent/child crons now that every row in this
622
- // reconcile has a known id, regardless of array order or first-boot.
623
- // Also clears parentCronId back to null when an entry no longer
624
- // declares a resolvable parentCron, so the link self-heals in both
625
- // directions rather than only null→set.
626
- for (const systemCron of defaultCrons) {
627
- const childId = idByName.get(systemCron.name);
628
- if (!childId) continue;
629
- const parentId = systemCron.parentCron
630
- ? idByName.get(systemCron.parentCron)
631
- : undefined;
632
-
633
- if (parentId) {
634
- await tx.agentCronJob.update({
635
- where: { id: childId },
636
- data: { parentCronId: parentId },
637
- });
638
- } else {
639
- const existing = existingByName.get(systemCron.name);
640
- if (existing && existing.parentCronId !== null) {
641
- await tx.agentCronJob.update({
642
- where: { id: childId },
643
- data: { parentCronId: null },
644
- });
645
- }
646
- }
647
- }
572
+ /**
573
+ * The mutation half of reconcileSystemCrons(), shared with the template
574
+ * reconcile (agent-template-reconcile.ts) so both run it inside their own
575
+ * transaction: pass 1 updates/creates each default cron by name, pass 2
576
+ * links parentCron, the orphan pass deletes system crons no longer listed.
577
+ * `existingSystemCrons` are the agent's rows with system=true.
578
+ */
579
+ export async function applySystemCronDefaults(
580
+ tx: Pick<PrismaTransactionClient, "agentCronJob">,
581
+ agentId: string,
582
+ defaultCrons: readonly SpecialtyDefaultCron[],
583
+ existingSystemCrons: readonly AgentCronJob[],
584
+ ): Promise<{ created: number; updated: number; deleted: number }> {
585
+ // Build a map of name → existing cron
586
+ const existingByName = new Map<string, AgentCronJob>();
587
+ for (const cron of existingSystemCrons) {
588
+ if (cron.name) {
589
+ existingByName.set(cron.name, cron);
590
+ }
591
+ }
648
592
 
649
- // Orphan pass: delete any system cron whose name is not in the defaults.
650
- for (const cron of existingSystemCrons) {
651
- if (!cron.name || !systemCronNames.has(cron.name)) {
652
- await tx.agentCronJob.delete({ where: { id: cron.id } });
653
- deleted++;
654
- }
593
+ // Build set of valid default cron names for orphan detection
594
+ const systemCronNames = new Set(defaultCrons.map((c) => c.name));
595
+
596
+ let created = 0;
597
+ let updated = 0;
598
+ let deleted = 0;
599
+
600
+ // Pass 1: reconcile each default cron entry, recording name → row id.
601
+ const idByName = new Map<string, string>();
602
+ for (const systemCron of defaultCrons) {
603
+ const existing = existingByName.get(systemCron.name);
604
+
605
+ if (existing) {
606
+ // Update in place — preserves id (and thus AgentCronRun history,
607
+ // which cascade-deletes when its AgentCronJob is deleted) and the
608
+ // existing enabled state.
609
+ await tx.agentCronJob.update({
610
+ where: { id: existing.id },
611
+ data: {
612
+ schedule: systemCron.schedule,
613
+ prompt: systemCron.prompt,
614
+ silent: systemCron.silent ?? false,
615
+ preCheck: systemCron.preCheck ?? null,
616
+ },
617
+ });
618
+ idByName.set(systemCron.name, existing.id);
619
+ updated++;
620
+ } else {
621
+ const createdCron = await tx.agentCronJob.create({
622
+ data: {
623
+ agentId,
624
+ name: systemCron.name,
625
+ system: true,
626
+ schedule: systemCron.schedule,
627
+ prompt: systemCron.prompt,
628
+ silent: systemCron.silent ?? false,
629
+ preCheck: systemCron.preCheck ?? null,
630
+ channel: null,
631
+ user: null,
632
+ enabled: systemCron.enabled ?? true,
633
+ },
634
+ });
635
+ idByName.set(systemCron.name, createdCron.id);
636
+ created++;
637
+ }
638
+ }
639
+
640
+ // Pass 2: link declared parent/child crons now that every row in this
641
+ // reconcile has a known id, regardless of array order or first-boot.
642
+ // Also clears parentCronId back to null when an entry no longer
643
+ // declares a resolvable parentCron, so the link self-heals in both
644
+ // directions rather than only null→set.
645
+ for (const systemCron of defaultCrons) {
646
+ const childId = idByName.get(systemCron.name);
647
+ if (!childId) continue;
648
+ const parentId = systemCron.parentCron
649
+ ? idByName.get(systemCron.parentCron)
650
+ : undefined;
651
+
652
+ if (parentId) {
653
+ await tx.agentCronJob.update({
654
+ where: { id: childId },
655
+ data: { parentCronId: parentId },
656
+ });
657
+ } else {
658
+ const existing = existingByName.get(systemCron.name);
659
+ if (existing && existing.parentCronId !== null) {
660
+ await tx.agentCronJob.update({
661
+ where: { id: childId },
662
+ data: { parentCronId: null },
663
+ });
655
664
  }
656
- });
665
+ }
666
+ }
657
667
 
658
- return { created, updated, deleted };
668
+ // Orphan pass: delete any system cron whose name is not in the defaults.
669
+ for (const cron of existingSystemCrons) {
670
+ if (!cron.name || !systemCronNames.has(cron.name)) {
671
+ await tx.agentCronJob.delete({ where: { id: cron.id } });
672
+ deleted++;
673
+ }
659
674
  }
675
+
676
+ return { created, updated, deleted };
660
677
  }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * admin/src/agent-template-merge.ts
3
+ * ATP-2.1: resolves the effective template for one agent by merging the
4
+ * template layers by (kind, key), ascending specificity:
5
+ *
6
+ * 0. specialty-default built-in specialty defaults (extension hook or
7
+ * the built-in type, plus the platform plugins)
8
+ * 1. deployment AgentTemplate(accountId null, specialty null)
9
+ * 2. deployment-specialty AgentTemplate(accountId null, specialty = agent's)
10
+ * 3. account AgentTemplate(accountId = agent's, specialty null)
11
+ * 4. account-specialty AgentTemplate(accountId = agent's, specialty = agent's)
12
+ *
13
+ * A more specific layer replaces the whole payload of a key defined lower
14
+ * down. Pure: no DB, no crypto; the reconcile (agent-template-reconcile.ts)
15
+ * loads the layers and applies the result.
16
+ */
17
+
18
+ import { resolveDefaultPlugins } from "@app-vitals/agent-lib/default-plugins";
19
+ import type { AgentTemplateItemKind } from "./agent-template-items.ts";
20
+ import type {
21
+ SpecialtyDefaultCron,
22
+ SpecialtyDefaultsResolver,
23
+ } from "./specialty-defaults.ts";
24
+ import type { SpecialtyTypeResolver } from "./specialty-types.ts";
25
+
26
+ export const TEMPLATE_LAYERS = [
27
+ "specialty-default",
28
+ "deployment",
29
+ "deployment-specialty",
30
+ "account",
31
+ "account-specialty",
32
+ ] as const;
33
+ export type TemplateLayer = (typeof TEMPLATE_LAYERS)[number];
34
+
35
+ export interface TemplateLayerItem {
36
+ kind: AgentTemplateItemKind;
37
+ key: string;
38
+ payload: Record<string, unknown>;
39
+ }
40
+
41
+ export interface TemplateLayerInput {
42
+ layer: TemplateLayer;
43
+ items: readonly TemplateLayerItem[];
44
+ }
45
+
46
+ /** One resolved item and the layer it came from. */
47
+ export interface MergedTemplateItem extends TemplateLayerItem {
48
+ layer: TemplateLayer;
49
+ }
50
+
51
+ /** The resolved template: per kind, key → winning item (first-seen order). */
52
+ export type MergedTemplate = Record<
53
+ AgentTemplateItemKind,
54
+ Map<string, MergedTemplateItem>
55
+ >;
56
+
57
+ /** The layer an AgentTemplate row's scope sits in. */
58
+ export function templateLayerForScope(scope: {
59
+ accountId: string | null;
60
+ specialty: string | null;
61
+ }): Exclude<TemplateLayer, "specialty-default"> {
62
+ if (scope.accountId === null) {
63
+ return scope.specialty === null ? "deployment" : "deployment-specialty";
64
+ }
65
+ return scope.specialty === null ? "account" : "account-specialty";
66
+ }
67
+
68
+ /** Merge layers by (kind, key); the most specific layer wins. */
69
+ export function mergeTemplateLayers(
70
+ layers: readonly TemplateLayerInput[],
71
+ ): MergedTemplate {
72
+ const merged: MergedTemplate = {
73
+ env: new Map(),
74
+ tool: new Map(),
75
+ plugin: new Map(),
76
+ cron: new Map(),
77
+ };
78
+ const ordered = [...layers].sort(
79
+ (a, b) =>
80
+ TEMPLATE_LAYERS.indexOf(a.layer) - TEMPLATE_LAYERS.indexOf(b.layer),
81
+ );
82
+ for (const { layer, items } of ordered) {
83
+ for (const item of items) {
84
+ merged[item.kind].set(item.key, {
85
+ kind: item.kind,
86
+ key: item.key,
87
+ payload: item.payload,
88
+ layer,
89
+ });
90
+ }
91
+ }
92
+ return merged;
93
+ }
94
+
95
+ /** The built-in defaults of one specialty. */
96
+ export interface SpecialtyDefaultSet {
97
+ tools: readonly string[];
98
+ plugins: readonly string[];
99
+ crons: readonly SpecialtyDefaultCron[];
100
+ }
101
+
102
+ /**
103
+ * The specialty's built-in defaults, resolved the same way createAgent() and
104
+ * reconcileSystemCrons() do: extension-supplied values first, else the
105
+ * built-in type (no fallback to another type). Undefined when the specialty
106
+ * is neither.
107
+ */
108
+ export function resolveSpecialtyDefaultSet(
109
+ specialty: string,
110
+ registry: Pick<SpecialtyTypeResolver, "tryGetType">,
111
+ specialtyDefaults?: SpecialtyDefaultsResolver,
112
+ ): SpecialtyDefaultSet | undefined {
113
+ const extension = specialtyDefaults?.(specialty);
114
+ const type = registry.tryGetType(specialty);
115
+ if (!extension && !type) return undefined;
116
+ return {
117
+ tools: extension?.tools ?? type?.tools ?? [],
118
+ plugins: resolveDefaultPlugins(extension?.plugins),
119
+ crons: extension?.crons ?? [],
120
+ };
121
+ }
122
+
123
+ /** Layer 0: the specialty defaults as template items. */
124
+ export function specialtyDefaultLayer(
125
+ defaults: SpecialtyDefaultSet,
126
+ ): TemplateLayerInput {
127
+ const items: TemplateLayerItem[] = [
128
+ ...defaults.tools.map(
129
+ (key): TemplateLayerItem => ({ kind: "tool", key, payload: {} }),
130
+ ),
131
+ ...defaults.plugins.map(
132
+ (key): TemplateLayerItem => ({
133
+ kind: "plugin",
134
+ key,
135
+ payload: { version: null },
136
+ }),
137
+ ),
138
+ ...defaults.crons.map((c): TemplateLayerItem => {
139
+ const payload: Record<string, unknown> = {
140
+ schedule: c.schedule,
141
+ prompt: c.prompt,
142
+ };
143
+ if (c.silent !== undefined) payload.silent = c.silent;
144
+ if (c.preCheck !== undefined) payload.preCheck = c.preCheck;
145
+ if (c.enabled !== undefined) payload.enabled = c.enabled;
146
+ return { kind: "cron", key: c.name, payload };
147
+ }),
148
+ ];
149
+ return { layer: "specialty-default", items };
150
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * admin/src/agent-template-merge.unit.test.ts
3
+ * ATP-2.1: the pure five-layer template merge.
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+ import { AGENT_PLATFORM_PLUGIN } from "@app-vitals/agent-lib/default-plugins";
8
+ import {
9
+ mergeTemplateLayers,
10
+ resolveSpecialtyDefaultSet,
11
+ specialtyDefaultLayer,
12
+ TEMPLATE_LAYERS,
13
+ type TemplateLayerInput,
14
+ templateLayerForScope,
15
+ } from "./agent-template-merge.ts";
16
+ import { SPECIALIST_TYPE } from "./specialty-types.ts";
17
+
18
+ const plugin = (version: string | null) => ({
19
+ kind: "plugin" as const,
20
+ key: "p@m",
21
+ payload: { version },
22
+ });
23
+
24
+ describe("templateLayerForScope", () => {
25
+ it("maps each (accountId, specialty) scope to its layer", () => {
26
+ expect(templateLayerForScope({ accountId: null, specialty: null })).toBe(
27
+ "deployment",
28
+ );
29
+ expect(templateLayerForScope({ accountId: null, specialty: "x" })).toBe(
30
+ "deployment-specialty",
31
+ );
32
+ expect(templateLayerForScope({ accountId: "a", specialty: null })).toBe(
33
+ "account",
34
+ );
35
+ expect(templateLayerForScope({ accountId: "a", specialty: "x" })).toBe(
36
+ "account-specialty",
37
+ );
38
+ });
39
+ });
40
+
41
+ describe("mergeTemplateLayers", () => {
42
+ it("lists the layers in ascending specificity", () => {
43
+ expect([...TEMPLATE_LAYERS]).toEqual([
44
+ "specialty-default",
45
+ "deployment",
46
+ "deployment-specialty",
47
+ "account",
48
+ "account-specialty",
49
+ ]);
50
+ });
51
+
52
+ it("the most specific layer wins for a key defined in all five, whatever the input order", () => {
53
+ const layers: TemplateLayerInput[] = [
54
+ { layer: "account", items: [plugin("3")] },
55
+ { layer: "account-specialty", items: [plugin("4")] },
56
+ { layer: "deployment", items: [plugin("1")] },
57
+ { layer: "specialty-default", items: [plugin(null)] },
58
+ { layer: "deployment-specialty", items: [plugin("2")] },
59
+ ];
60
+ const merged = mergeTemplateLayers(layers);
61
+ expect(merged.plugin.get("p@m")).toEqual({
62
+ kind: "plugin",
63
+ key: "p@m",
64
+ payload: { version: "4" },
65
+ layer: "account-specialty",
66
+ });
67
+ });
68
+
69
+ it("falls through to the next most specific layer that defines the key", () => {
70
+ for (const [drop, expected] of [
71
+ ["account-specialty", "3"],
72
+ ["account", "2"],
73
+ ["deployment-specialty", "1"],
74
+ ["deployment", null],
75
+ ] as const) {
76
+ const all: TemplateLayerInput[] = [
77
+ { layer: "specialty-default", items: [plugin(null)] },
78
+ { layer: "deployment", items: [plugin("1")] },
79
+ { layer: "deployment-specialty", items: [plugin("2")] },
80
+ { layer: "account", items: [plugin("3")] },
81
+ { layer: "account-specialty", items: [plugin("4")] },
82
+ ];
83
+ const order = TEMPLATE_LAYERS.indexOf(drop);
84
+ const kept = all.filter((l) => TEMPLATE_LAYERS.indexOf(l.layer) < order);
85
+ expect(mergeTemplateLayers(kept).plugin.get("p@m")?.payload).toEqual({
86
+ version: expected,
87
+ });
88
+ }
89
+ });
90
+
91
+ it("merges by key: distinct keys from every layer are all kept, kinds stay separate", () => {
92
+ const merged = mergeTemplateLayers([
93
+ {
94
+ layer: "specialty-default",
95
+ items: [{ kind: "tool", key: "Bash", payload: {} }],
96
+ },
97
+ {
98
+ layer: "deployment",
99
+ items: [
100
+ { kind: "env", key: "SENTRY_DSN", payload: { value: "x" } },
101
+ { kind: "tool", key: "Read", payload: {} },
102
+ ],
103
+ },
104
+ {
105
+ layer: "account",
106
+ items: [{ kind: "env", key: "Bash", payload: { value: "y" } }],
107
+ },
108
+ ]);
109
+ expect([...merged.tool.keys()]).toEqual(["Bash", "Read"]);
110
+ expect([...merged.env.keys()]).toEqual(["SENTRY_DSN", "Bash"]);
111
+ expect(merged.tool.get("Bash")?.layer).toBe("specialty-default");
112
+ expect(merged.plugin.size).toBe(0);
113
+ expect(merged.cron.size).toBe(0);
114
+ });
115
+
116
+ it("an empty input yields an empty template", () => {
117
+ const merged = mergeTemplateLayers([]);
118
+ expect(merged.env.size + merged.tool.size).toBe(0);
119
+ expect(merged.plugin.size + merged.cron.size).toBe(0);
120
+ });
121
+ });
122
+
123
+ describe("specialtyDefaultLayer", () => {
124
+ it("turns specialty defaults into layer-0 items", () => {
125
+ const layer = specialtyDefaultLayer({
126
+ tools: ["Bash"],
127
+ plugins: ["a@b"],
128
+ crons: [
129
+ {
130
+ name: "loop",
131
+ schedule: "* * * * *",
132
+ prompt: "/loop",
133
+ silent: true,
134
+ parentCron: "x",
135
+ },
136
+ ],
137
+ });
138
+ expect(layer.layer).toBe("specialty-default");
139
+ expect(layer.items).toEqual([
140
+ { kind: "tool", key: "Bash", payload: {} },
141
+ { kind: "plugin", key: "a@b", payload: { version: null } },
142
+ {
143
+ kind: "cron",
144
+ key: "loop",
145
+ payload: { schedule: "* * * * *", prompt: "/loop", silent: true },
146
+ },
147
+ ]);
148
+ });
149
+ });
150
+
151
+ describe("resolveSpecialtyDefaultSet", () => {
152
+ const registry = {
153
+ tryGetType: (s: string) =>
154
+ s === SPECIALIST_TYPE.name ? SPECIALIST_TYPE : undefined,
155
+ };
156
+
157
+ it("uses the built-in type's tools and the platform plugins for a built-in type", () => {
158
+ expect(resolveSpecialtyDefaultSet("specialist", registry)).toEqual({
159
+ tools: SPECIALIST_TYPE.tools,
160
+ plugins: [AGENT_PLATFORM_PLUGIN],
161
+ crons: [],
162
+ });
163
+ });
164
+
165
+ it("prefers extension-supplied defaults", () => {
166
+ const set = resolveSpecialtyDefaultSet("coding", registry, (s) =>
167
+ s === "coding"
168
+ ? {
169
+ tools: ["Read"],
170
+ plugins: ["x@y"],
171
+ crons: [{ name: "c", schedule: "* * * * *", prompt: "p" }],
172
+ }
173
+ : undefined,
174
+ );
175
+ expect(set?.tools).toEqual(["Read"]);
176
+ expect(set?.plugins).toEqual([AGENT_PLATFORM_PLUGIN, "x@y"]);
177
+ expect(set?.crons.map((c) => c.name)).toEqual(["c"]);
178
+ });
179
+
180
+ it("returns undefined for a specialty that is neither built in nor extension-supplied", () => {
181
+ expect(resolveSpecialtyDefaultSet("nope", registry)).toBeUndefined();
182
+ });
183
+ });