@app-vitals/agent-admin 1.65.0 → 1.67.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/openapi.platform.json +5 -0
- package/package.json +2 -2
- package/prisma/client/internal/class.ts +4 -4
- package/prisma/client/internal/prismaNamespace.ts +1 -0
- package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
- package/prisma/client/models/AgentTemplateItem.ts +36 -1
- package/prisma/migrations/20261117000000_add_agent_template_item_managed_by/migration.sql +5 -0
- package/prisma/schema/schema.prisma +3 -0
- package/src/admin-boot.boot-order.unit.test.ts +13 -1
- package/src/admin-boot.ts +14 -1
- package/src/admin-ui-templates-pages.ts +15 -1
- package/src/admin-ui-templates-pages.unit.test.ts +9 -0
- package/src/admin-ui-templates.smoke.test.ts +38 -0
- package/src/agent-templates-api.ts +1 -0
- package/src/agent-templates.ts +184 -9
- package/src/openapi-schemas.ts +5 -0
- package/src/template-seed.integration.test.ts +408 -0
- package/src/template-seed.ts +222 -0
- package/src/template-seed.unit.test.ts +272 -0
package/src/agent-templates.ts
CHANGED
|
@@ -62,6 +62,11 @@ export interface TemplateItemView {
|
|
|
62
62
|
key: string;
|
|
63
63
|
payload: Record<string, unknown>;
|
|
64
64
|
updatedAt: Date;
|
|
65
|
+
/**
|
|
66
|
+
* TMK-3.2: who owns the item ("helm" = SHIPWRIGHT_TEMPLATE_SEED). Absent for
|
|
67
|
+
* hand-added items. Optional so the exported shape stays additive.
|
|
68
|
+
*/
|
|
69
|
+
managedBy?: string;
|
|
65
70
|
}
|
|
66
71
|
|
|
67
72
|
export interface TemplateView {
|
|
@@ -73,6 +78,42 @@ export interface TemplateView {
|
|
|
73
78
|
items: TemplateItemView[];
|
|
74
79
|
}
|
|
75
80
|
|
|
81
|
+
/** Outcome of AgentTemplateService.applyManagedItems() (TMK-3.2). */
|
|
82
|
+
export interface ManagedItemsResult {
|
|
83
|
+
/** The deployment-wide template; null when none existed and none was needed. */
|
|
84
|
+
templateId: string | null;
|
|
85
|
+
created: number;
|
|
86
|
+
updated: number;
|
|
87
|
+
unchanged: number;
|
|
88
|
+
deleted: number;
|
|
89
|
+
/** Managed items not applied because a hand-added item holds the key. */
|
|
90
|
+
skipped: { kind: AgentTemplateItemKind; key: string }[];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* pg_advisory_xact_lock key serializing applyManagedItems() across admin
|
|
95
|
+
* replicas ("TMK2" as a 32-bit integer). Constant so every replica contends
|
|
96
|
+
* on the same lock.
|
|
97
|
+
*/
|
|
98
|
+
export const MANAGED_ITEMS_LOCK_KEY = 0x544d4b32;
|
|
99
|
+
|
|
100
|
+
/** Deep JSON equality that ignores object key order (jsonb reorders keys). */
|
|
101
|
+
function sameJson(a: unknown, b: unknown): boolean {
|
|
102
|
+
const canon = (v: unknown): unknown => {
|
|
103
|
+
if (Array.isArray(v)) return v.map(canon);
|
|
104
|
+
if (v !== null && typeof v === "object") {
|
|
105
|
+
return Object.fromEntries(
|
|
106
|
+
Object.entries(v as Record<string, unknown>)
|
|
107
|
+
.filter(([, x]) => x !== undefined)
|
|
108
|
+
.sort(([x], [y]) => x.localeCompare(y))
|
|
109
|
+
.map(([k, x]) => [k, canon(x)]),
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return v;
|
|
113
|
+
};
|
|
114
|
+
return JSON.stringify(canon(a)) === JSON.stringify(canon(b));
|
|
115
|
+
}
|
|
116
|
+
|
|
76
117
|
// ─── Per-kind payload shapes ──────────────────────────────────────────────────
|
|
77
118
|
|
|
78
119
|
const nonEmpty = z.string().trim().min(1);
|
|
@@ -156,6 +197,7 @@ type TemplateRow = {
|
|
|
156
197
|
key: string;
|
|
157
198
|
payload: unknown;
|
|
158
199
|
updatedAt: Date;
|
|
200
|
+
managedBy?: string | null;
|
|
159
201
|
}[];
|
|
160
202
|
};
|
|
161
203
|
|
|
@@ -208,7 +250,13 @@ export class AgentTemplateService {
|
|
|
208
250
|
} else {
|
|
209
251
|
payload = openTemplateItemPayload(kind, stored, this.crypto);
|
|
210
252
|
}
|
|
211
|
-
return {
|
|
253
|
+
return {
|
|
254
|
+
kind,
|
|
255
|
+
key: it.key,
|
|
256
|
+
payload,
|
|
257
|
+
updatedAt: it.updatedAt,
|
|
258
|
+
...(it.managedBy ? { managedBy: it.managedBy } : {}),
|
|
259
|
+
};
|
|
212
260
|
});
|
|
213
261
|
return {
|
|
214
262
|
id: row.id,
|
|
@@ -369,14 +417,17 @@ export class AgentTemplateService {
|
|
|
369
417
|
const stored = new Map(
|
|
370
418
|
(existing?.items ?? []).map((it) => [`${it.kind}:${it.key}`, it]),
|
|
371
419
|
);
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
420
|
+
// A replaced item keeps its owner (TMK-3.2): an edited seeded item
|
|
421
|
+
// keeps its badge and is overwritten again on the next admin boot.
|
|
422
|
+
const data = items.map((item) => {
|
|
423
|
+
const prior = stored.get(`${item.kind}:${item.key}`);
|
|
424
|
+
return {
|
|
425
|
+
kind: item.kind,
|
|
426
|
+
key: item.key,
|
|
427
|
+
payload: this.seal(item, prior?.payload),
|
|
428
|
+
managedBy: prior?.managedBy ?? null,
|
|
429
|
+
};
|
|
430
|
+
});
|
|
380
431
|
|
|
381
432
|
const templateId = existing
|
|
382
433
|
? existing.id
|
|
@@ -466,6 +517,130 @@ export class AgentTemplateService {
|
|
|
466
517
|
await this.propagate(existing);
|
|
467
518
|
}
|
|
468
519
|
|
|
520
|
+
/**
|
|
521
|
+
* TMK-3.2: make the deployment-wide, all-specialties template hold exactly
|
|
522
|
+
* `itemsInput` among the items `managedBy` owns for `kinds`, creating the
|
|
523
|
+
* template if absent. In one transaction under a constant advisory lock, so
|
|
524
|
+
* concurrent admin replicas serialize and end with one copy of each item:
|
|
525
|
+
*
|
|
526
|
+
* - each item is created, or updated in place, with `managedBy`;
|
|
527
|
+
* - items owned by `managedBy` of a listed kind that are not in
|
|
528
|
+
* `itemsInput` are deleted;
|
|
529
|
+
* - hand-added items (`managedBy` null) are never touched; a managed item
|
|
530
|
+
* whose key a hand-added item already holds is reported in `skipped`.
|
|
531
|
+
*
|
|
532
|
+
* Items go through normalizeTemplateItem() (the same validation as the API)
|
|
533
|
+
* before anything is written. The fan-out to agents runs after commit,
|
|
534
|
+
* whether or not this pass changed rows, so a boot also repairs a fan-out
|
|
535
|
+
* an earlier boot did not finish.
|
|
536
|
+
*/
|
|
537
|
+
async applyManagedItems(
|
|
538
|
+
managedBy: string,
|
|
539
|
+
kinds: readonly AgentTemplateItemKind[],
|
|
540
|
+
itemsInput: TemplateItemInput[],
|
|
541
|
+
): Promise<ManagedItemsResult> {
|
|
542
|
+
const seen = new Set<string>();
|
|
543
|
+
const items = itemsInput.map((raw) => {
|
|
544
|
+
const item = normalizeTemplateItem(raw);
|
|
545
|
+
if (!kinds.includes(item.kind)) {
|
|
546
|
+
throw new UnprocessableEntityError(
|
|
547
|
+
`${item.kind} item ${item.key} is not a managed kind`,
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
const id = `${item.kind}:${item.key}`;
|
|
551
|
+
if (seen.has(id)) {
|
|
552
|
+
throw new UnprocessableEntityError(
|
|
553
|
+
`duplicate ${item.kind} item key ${item.key}`,
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
seen.add(id);
|
|
557
|
+
return item;
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
const result = await this.prisma.$transaction(
|
|
561
|
+
async (tx) => {
|
|
562
|
+
await tx.$queryRaw`SELECT pg_advisory_xact_lock(${MANAGED_ITEMS_LOCK_KEY}::bigint)::text`;
|
|
563
|
+
const scope = { accountId: null, specialty: null };
|
|
564
|
+
const existing = await tx.agentTemplate.findFirst({
|
|
565
|
+
where: scope,
|
|
566
|
+
include: { items: true },
|
|
567
|
+
});
|
|
568
|
+
const out: ManagedItemsResult = {
|
|
569
|
+
templateId: existing?.id ?? null,
|
|
570
|
+
created: 0,
|
|
571
|
+
updated: 0,
|
|
572
|
+
unchanged: 0,
|
|
573
|
+
deleted: 0,
|
|
574
|
+
skipped: [],
|
|
575
|
+
};
|
|
576
|
+
if (!existing && items.length === 0) return out;
|
|
577
|
+
const templateId =
|
|
578
|
+
existing?.id ?? (await tx.agentTemplate.create({ data: scope })).id;
|
|
579
|
+
out.templateId = templateId;
|
|
580
|
+
const stored = new Map(
|
|
581
|
+
(existing?.items ?? []).map((it) => [`${it.kind}:${it.key}`, it]),
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
for (const item of items) {
|
|
585
|
+
const prior = stored.get(`${item.kind}:${item.key}`);
|
|
586
|
+
if (prior && prior.managedBy === null) {
|
|
587
|
+
out.skipped.push({ kind: item.kind, key: item.key });
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const payload = this.seal(item, prior?.payload);
|
|
591
|
+
if (!prior) {
|
|
592
|
+
await tx.agentTemplateItem.create({
|
|
593
|
+
data: {
|
|
594
|
+
templateId,
|
|
595
|
+
kind: item.kind,
|
|
596
|
+
key: item.key,
|
|
597
|
+
payload,
|
|
598
|
+
managedBy,
|
|
599
|
+
},
|
|
600
|
+
});
|
|
601
|
+
out.created++;
|
|
602
|
+
} else if (
|
|
603
|
+
prior.managedBy === managedBy &&
|
|
604
|
+
sameJson(prior.payload, payload)
|
|
605
|
+
) {
|
|
606
|
+
out.unchanged++;
|
|
607
|
+
} else {
|
|
608
|
+
await tx.agentTemplateItem.update({
|
|
609
|
+
where: { id: prior.id },
|
|
610
|
+
data: { payload, managedBy },
|
|
611
|
+
});
|
|
612
|
+
out.updated++;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const stale = (existing?.items ?? []).filter(
|
|
617
|
+
(it) =>
|
|
618
|
+
it.managedBy === managedBy &&
|
|
619
|
+
(kinds as readonly string[]).includes(it.kind) &&
|
|
620
|
+
!seen.has(`${it.kind}:${it.key}`),
|
|
621
|
+
);
|
|
622
|
+
if (stale.length > 0) {
|
|
623
|
+
await tx.agentTemplateItem.deleteMany({
|
|
624
|
+
where: { id: { in: stale.map((it) => it.id) } },
|
|
625
|
+
});
|
|
626
|
+
out.deleted = stale.length;
|
|
627
|
+
}
|
|
628
|
+
if (existing && out.created + out.updated + out.deleted > 0) {
|
|
629
|
+
await tx.agentTemplate.update({
|
|
630
|
+
where: { id: templateId },
|
|
631
|
+
data: { updatedAt: new Date() },
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
return out;
|
|
635
|
+
},
|
|
636
|
+
{ timeout: 30_000, maxWait: 30_000 },
|
|
637
|
+
);
|
|
638
|
+
if (result.templateId !== null) {
|
|
639
|
+
await this.propagate({ accountId: null, specialty: null });
|
|
640
|
+
}
|
|
641
|
+
return result;
|
|
642
|
+
}
|
|
643
|
+
|
|
469
644
|
/** Delete a template and (by cascade) its items. */
|
|
470
645
|
async delete(actor: TemplateActor, id: string): Promise<void> {
|
|
471
646
|
const existing = await this.load(actor, id);
|
package/src/openapi-schemas.ts
CHANGED
|
@@ -1600,6 +1600,11 @@ export const TemplateItemSchema = TemplateItemBaseSchema.extend({
|
|
|
1600
1600
|
.string()
|
|
1601
1601
|
.datetime()
|
|
1602
1602
|
.openapi({ example: "2026-01-01T00:00:00.000Z" }),
|
|
1603
|
+
managedBy: z.string().optional().openapi({
|
|
1604
|
+
description:
|
|
1605
|
+
'Set to "helm" on items applied from SHIPWRIGHT_TEMPLATE_SEED (Helm values); absent on hand-added items. Seeded items stay editable, but the next admin boot overwrites them.',
|
|
1606
|
+
example: "helm",
|
|
1607
|
+
}),
|
|
1603
1608
|
}).openapi("TemplateItem");
|
|
1604
1609
|
|
|
1605
1610
|
export const AgentTemplateSchema = z
|
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/template-seed.integration.test.ts
|
|
3
|
+
* TMK-3.2: applying SHIPWRIGHT_TEMPLATE_SEED to the deployment-wide template
|
|
4
|
+
* (apply, removal, unset, empty lists, invalid seed, concurrency, edits being
|
|
5
|
+
* overwritten) and the fan-out into agent rows and the config bundle, against
|
|
6
|
+
* real Postgres.
|
|
7
|
+
*
|
|
8
|
+
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
12
|
+
import { AGENT_PLATFORM_PLUGIN } from "@app-vitals/agent-lib/default-plugins";
|
|
13
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
14
|
+
import { AgentMarketplaceService } from "./agent-marketplaces.ts";
|
|
15
|
+
import { AgentPluginService } from "./agent-plugins.ts";
|
|
16
|
+
import { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
|
|
17
|
+
import { AgentTemplateService } from "./agent-templates.ts";
|
|
18
|
+
import { AgentTokenService } from "./agent-tokens.ts";
|
|
19
|
+
import { AgentService } from "./agents.ts";
|
|
20
|
+
import { parseAdminApiKeys } from "./agents-api.ts";
|
|
21
|
+
import { createAgentRuntimeApp } from "./api.ts";
|
|
22
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
23
|
+
import type { SpecialtyType } from "./specialty-types.ts";
|
|
24
|
+
import { runTemplateSeed } from "./template-seed.ts";
|
|
25
|
+
import { makeStrictTokenCrypto } from "./token-crypto.ts";
|
|
26
|
+
|
|
27
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
28
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
29
|
+
|
|
30
|
+
const KEY = "ab".repeat(32);
|
|
31
|
+
const TYPE: SpecialtyType = {
|
|
32
|
+
name: "specialist",
|
|
33
|
+
displayName: "Specialist",
|
|
34
|
+
templatesDir: "workspace/",
|
|
35
|
+
tools: ["Read"],
|
|
36
|
+
requiredEnv: [],
|
|
37
|
+
};
|
|
38
|
+
const registry = {
|
|
39
|
+
getType: () => TYPE,
|
|
40
|
+
tryGetType: (s: string) => (s === TYPE.name ? TYPE : undefined),
|
|
41
|
+
listTypes: () => [{ name: TYPE.name, displayName: TYPE.displayName }],
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const SEED = {
|
|
45
|
+
marketplaces: [
|
|
46
|
+
{ name: "example-plugins", source: "example-org/plugins", ref: "v1.2.0" },
|
|
47
|
+
],
|
|
48
|
+
plugins: ["some-plugin@example-plugins", "other-plugin@example-plugins"],
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
describeOrSkip("template seed (integration)", () => {
|
|
52
|
+
let prisma: PrismaClient;
|
|
53
|
+
let templates: AgentTemplateService;
|
|
54
|
+
const crypto = makeStrictTokenCrypto(KEY);
|
|
55
|
+
if (!crypto) throw new Error("test crypto");
|
|
56
|
+
|
|
57
|
+
const serviceFor = (client: PrismaClient) =>
|
|
58
|
+
new AgentTemplateService(
|
|
59
|
+
client,
|
|
60
|
+
crypto,
|
|
61
|
+
registry,
|
|
62
|
+
new AgentTemplateReconcileService(client, crypto, registry),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
beforeEach(async () => {
|
|
66
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
67
|
+
await prisma.agentTemplateItem.deleteMany();
|
|
68
|
+
await prisma.agentTemplate.deleteMany();
|
|
69
|
+
await prisma.agentCronJob.deleteMany();
|
|
70
|
+
await prisma.agentTool.deleteMany();
|
|
71
|
+
await prisma.agentMarketplace.deleteMany();
|
|
72
|
+
await prisma.agentPlugin.deleteMany();
|
|
73
|
+
await prisma.agentEnv.deleteMany();
|
|
74
|
+
await prisma.agentToken.deleteMany();
|
|
75
|
+
await prisma.agentMember.deleteMany();
|
|
76
|
+
await prisma.agent.deleteMany();
|
|
77
|
+
await prisma.accountInvite.deleteMany();
|
|
78
|
+
await prisma.accountMember.deleteMany();
|
|
79
|
+
await prisma.account.deleteMany();
|
|
80
|
+
templates = serviceFor(prisma);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
afterEach(async () => {
|
|
84
|
+
await prisma.$disconnect();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
function quietLogger() {
|
|
88
|
+
const logs: string[] = [];
|
|
89
|
+
const errors: string[] = [];
|
|
90
|
+
return {
|
|
91
|
+
logs,
|
|
92
|
+
errors,
|
|
93
|
+
logger: {
|
|
94
|
+
log: (...a: unknown[]) => logs.push(a.map(String).join(" ")),
|
|
95
|
+
error: (...a: unknown[]) => errors.push(a.map(String).join(" ")),
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const seed = (raw: unknown, service = templates) => {
|
|
101
|
+
const { logger, errors, logs } = quietLogger();
|
|
102
|
+
return runTemplateSeed({
|
|
103
|
+
raw: raw === undefined ? undefined : JSON.stringify(raw),
|
|
104
|
+
templateService: service,
|
|
105
|
+
logger,
|
|
106
|
+
}).then((outcome) => ({ outcome, errors, logs }));
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const mkAgent = (name: string, data: Record<string, unknown> = {}) =>
|
|
110
|
+
prisma.agent.create({ data: { name, specialty: "specialist", ...data } });
|
|
111
|
+
|
|
112
|
+
const templateItems = () =>
|
|
113
|
+
prisma.agentTemplateItem.findMany({
|
|
114
|
+
orderBy: [{ kind: "asc" }, { key: "asc" }],
|
|
115
|
+
select: { kind: true, key: true, managedBy: true, payload: true },
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// Reconcile always adds the default platform plugin; these tests only check
|
|
119
|
+
// seeded rows, so it is excluded here.
|
|
120
|
+
const pluginNames = async (agentId: string) =>
|
|
121
|
+
(
|
|
122
|
+
await prisma.agentPlugin.findMany({
|
|
123
|
+
where: { agentId, name: { not: AGENT_PLATFORM_PLUGIN } },
|
|
124
|
+
orderBy: { name: "asc" },
|
|
125
|
+
})
|
|
126
|
+
).map((p) => ({ name: p.name, source: p.source }));
|
|
127
|
+
|
|
128
|
+
it("creates helm-managed deployment-wide items and fans them out to attached agents and their config bundle", async () => {
|
|
129
|
+
const agent = await mkAgent("follower");
|
|
130
|
+
const detached = await mkAgent("detached", { templateDetached: true });
|
|
131
|
+
|
|
132
|
+
const { outcome, errors } = await seed(SEED);
|
|
133
|
+
expect(errors).toEqual([]);
|
|
134
|
+
expect(outcome.status).toBe("applied");
|
|
135
|
+
|
|
136
|
+
const template = await prisma.agentTemplate.findFirstOrThrow({
|
|
137
|
+
where: { accountId: null, specialty: null },
|
|
138
|
+
});
|
|
139
|
+
expect(template).toBeDefined();
|
|
140
|
+
expect(await templateItems()).toEqual([
|
|
141
|
+
{
|
|
142
|
+
kind: "marketplace",
|
|
143
|
+
key: "example-plugins",
|
|
144
|
+
managedBy: "helm",
|
|
145
|
+
payload: { source: "example-org/plugins", ref: "v1.2.0" },
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
kind: "plugin",
|
|
149
|
+
key: "other-plugin@example-plugins",
|
|
150
|
+
managedBy: "helm",
|
|
151
|
+
payload: {},
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
kind: "plugin",
|
|
155
|
+
key: "some-plugin@example-plugins",
|
|
156
|
+
managedBy: "helm",
|
|
157
|
+
payload: {},
|
|
158
|
+
},
|
|
159
|
+
]);
|
|
160
|
+
|
|
161
|
+
// The template service view (what the editor and API read) carries it.
|
|
162
|
+
const [view] = await templates.list({ kind: "admin" });
|
|
163
|
+
expect(view?.items.every((i) => i.managedBy === "helm")).toBe(true);
|
|
164
|
+
|
|
165
|
+
// Fan-out: the attached agent has the rows, the detached one none.
|
|
166
|
+
expect(
|
|
167
|
+
await prisma.agentMarketplace.findMany({
|
|
168
|
+
where: { agentId: agent.id },
|
|
169
|
+
select: { name: true, source: true, ref: true, rowSource: true },
|
|
170
|
+
}),
|
|
171
|
+
).toEqual([
|
|
172
|
+
{
|
|
173
|
+
name: "example-plugins",
|
|
174
|
+
source: "example-org/plugins",
|
|
175
|
+
ref: "v1.2.0",
|
|
176
|
+
rowSource: "template",
|
|
177
|
+
},
|
|
178
|
+
]);
|
|
179
|
+
expect(await pluginNames(agent.id)).toEqual([
|
|
180
|
+
{ name: "other-plugin@example-plugins", source: "template" },
|
|
181
|
+
{ name: "some-plugin@example-plugins", source: "template" },
|
|
182
|
+
]);
|
|
183
|
+
expect(
|
|
184
|
+
await prisma.agentMarketplace.count({ where: { agentId: detached.id } }),
|
|
185
|
+
).toBe(0);
|
|
186
|
+
expect(await pluginNames(detached.id)).toEqual([]);
|
|
187
|
+
|
|
188
|
+
// ...and they reach GET /agents/:id/config.
|
|
189
|
+
const tokens = new AgentTokenService(prisma);
|
|
190
|
+
const { rawToken } = await tokens.create(agent.id);
|
|
191
|
+
const runtimeApp = createAgentRuntimeApp({
|
|
192
|
+
agentEnvService: { getConfigBundle: async () => null },
|
|
193
|
+
agentCronJobService: { list: async () => [] },
|
|
194
|
+
agentService: new AgentService(prisma),
|
|
195
|
+
agentPluginService: new AgentPluginService(prisma),
|
|
196
|
+
agentMarketplaceService: new AgentMarketplaceService(prisma),
|
|
197
|
+
sessionSecret: "test-admin-session-secret-32-bytes!",
|
|
198
|
+
adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
|
|
199
|
+
agentTokenService: tokens,
|
|
200
|
+
} as never);
|
|
201
|
+
const res = await runtimeApp.request(`/${agent.id}/config`, {
|
|
202
|
+
headers: { Authorization: `Bearer ${rawToken}` },
|
|
203
|
+
});
|
|
204
|
+
expect(res.status).toBe(200);
|
|
205
|
+
const cfg = (await res.json()) as {
|
|
206
|
+
marketplaces: { name: string; source: string; ref: string | null }[];
|
|
207
|
+
plugins: { plugin: string; marketplace: string }[];
|
|
208
|
+
};
|
|
209
|
+
expect(cfg.marketplaces).toEqual([
|
|
210
|
+
{ name: "example-plugins", source: "example-org/plugins", ref: "v1.2.0" },
|
|
211
|
+
]);
|
|
212
|
+
expect(cfg.plugins).toContainEqual({
|
|
213
|
+
plugin: "some-plugin",
|
|
214
|
+
marketplace: "example-plugins",
|
|
215
|
+
});
|
|
216
|
+
expect(cfg.plugins).toContainEqual({
|
|
217
|
+
plugin: "other-plugin",
|
|
218
|
+
marketplace: "example-plugins",
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("re-applying a seed that drops a plugin deletes that item and its agent rows, keeping hand-added items", async () => {
|
|
223
|
+
const agent = await mkAgent("follower");
|
|
224
|
+
await seed(SEED);
|
|
225
|
+
// A hand-added template item (managedBy null).
|
|
226
|
+
const [template] = await templates.list({ kind: "admin" });
|
|
227
|
+
await templates.putItem({ kind: "admin" }, template?.id as string, {
|
|
228
|
+
kind: "plugin",
|
|
229
|
+
key: "manual@example-plugins",
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
const { outcome } = await seed({
|
|
233
|
+
...SEED,
|
|
234
|
+
plugins: ["some-plugin@example-plugins"],
|
|
235
|
+
});
|
|
236
|
+
expect(outcome.status === "applied" && outcome.result.deleted).toBe(1);
|
|
237
|
+
|
|
238
|
+
expect(
|
|
239
|
+
(await templateItems()).map((i) => [i.kind, i.key, i.managedBy]),
|
|
240
|
+
).toEqual([
|
|
241
|
+
["marketplace", "example-plugins", "helm"],
|
|
242
|
+
["plugin", "manual@example-plugins", null],
|
|
243
|
+
["plugin", "some-plugin@example-plugins", "helm"],
|
|
244
|
+
]);
|
|
245
|
+
expect(await pluginNames(agent.id)).toEqual([
|
|
246
|
+
{ name: "manual@example-plugins", source: "template" },
|
|
247
|
+
{ name: "some-plugin@example-plugins", source: "template" },
|
|
248
|
+
]);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it("an unset or blank seed changes nothing", async () => {
|
|
252
|
+
await seed(SEED);
|
|
253
|
+
const before = await templateItems();
|
|
254
|
+
|
|
255
|
+
const unset = await seed(undefined);
|
|
256
|
+
expect(unset.outcome.status).toBe("unset");
|
|
257
|
+
const blank = await runTemplateSeed({
|
|
258
|
+
raw: " ",
|
|
259
|
+
templateService: templates,
|
|
260
|
+
logger: quietLogger().logger,
|
|
261
|
+
});
|
|
262
|
+
expect(blank.status).toBe("unset");
|
|
263
|
+
|
|
264
|
+
expect(await templateItems()).toEqual(before);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("empty lists clear the seeded items; an absent key leaves its kind alone; hand-added items stay", async () => {
|
|
268
|
+
const agent = await mkAgent("follower");
|
|
269
|
+
await seed(SEED);
|
|
270
|
+
const [template] = await templates.list({ kind: "admin" });
|
|
271
|
+
await templates.putItem({ kind: "admin" }, template?.id as string, {
|
|
272
|
+
kind: "tool",
|
|
273
|
+
key: "Grep",
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
// plugins: [] clears the seeded plugins; marketplaces is absent.
|
|
277
|
+
await seed({ plugins: [] });
|
|
278
|
+
expect(
|
|
279
|
+
(await templateItems()).map((i) => [i.kind, i.key, i.managedBy]),
|
|
280
|
+
).toEqual([
|
|
281
|
+
["marketplace", "example-plugins", "helm"],
|
|
282
|
+
["tool", "Grep", null],
|
|
283
|
+
]);
|
|
284
|
+
expect(await pluginNames(agent.id)).toEqual([]);
|
|
285
|
+
|
|
286
|
+
await seed({ marketplaces: [], plugins: [] });
|
|
287
|
+
expect(
|
|
288
|
+
(await templateItems()).map((i) => [i.kind, i.key, i.managedBy]),
|
|
289
|
+
).toEqual([["tool", "Grep", null]]);
|
|
290
|
+
expect(
|
|
291
|
+
await prisma.agentMarketplace.count({ where: { agentId: agent.id } }),
|
|
292
|
+
).toBe(0);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it("never takes over a hand-added item that holds a seeded key", async () => {
|
|
296
|
+
await templates.replace({ kind: "admin" }, {}, [
|
|
297
|
+
{
|
|
298
|
+
kind: "marketplace",
|
|
299
|
+
key: "example-plugins",
|
|
300
|
+
payload: { source: "example-org/fork" },
|
|
301
|
+
},
|
|
302
|
+
]);
|
|
303
|
+
const { outcome, logs } = await seed(SEED);
|
|
304
|
+
expect(outcome.status === "applied" && outcome.result.skipped).toEqual([
|
|
305
|
+
{ kind: "marketplace", key: "example-plugins" },
|
|
306
|
+
]);
|
|
307
|
+
expect(logs.join("\n")).toContain("marketplace:example-plugins");
|
|
308
|
+
const mk = (await templateItems()).find((i) => i.kind === "marketplace");
|
|
309
|
+
expect(mk).toEqual({
|
|
310
|
+
kind: "marketplace",
|
|
311
|
+
key: "example-plugins",
|
|
312
|
+
managedBy: null,
|
|
313
|
+
payload: { source: "example-org/fork" },
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
it("seeded items stay editable, keep their owner, and are overwritten on the next apply", async () => {
|
|
318
|
+
await seed(SEED);
|
|
319
|
+
const [template] = await templates.list({ kind: "admin" });
|
|
320
|
+
const id = template?.id as string;
|
|
321
|
+
await templates.putItem({ kind: "admin" }, id, {
|
|
322
|
+
kind: "marketplace",
|
|
323
|
+
key: "example-plugins",
|
|
324
|
+
payload: { source: "example-org/plugins", ref: "edited" },
|
|
325
|
+
});
|
|
326
|
+
// A full replace keeps the owner of a surviving key too.
|
|
327
|
+
const current = (await templates.get({ kind: "admin" }, id)).items;
|
|
328
|
+
await templates.replace(
|
|
329
|
+
{ kind: "admin" },
|
|
330
|
+
{},
|
|
331
|
+
current.map(({ kind, key, payload }) => ({ kind, key, payload })),
|
|
332
|
+
);
|
|
333
|
+
let mk = (await templateItems()).find((i) => i.kind === "marketplace");
|
|
334
|
+
expect(mk).toMatchObject({
|
|
335
|
+
managedBy: "helm",
|
|
336
|
+
payload: { source: "example-org/plugins", ref: "edited" },
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
const { outcome } = await seed(SEED);
|
|
340
|
+
expect(outcome.status === "applied" && outcome.result.updated).toBe(1);
|
|
341
|
+
mk = (await templateItems()).find((i) => i.kind === "marketplace");
|
|
342
|
+
expect(mk).toMatchObject({
|
|
343
|
+
managedBy: "helm",
|
|
344
|
+
payload: { source: "example-org/plugins", ref: "v1.2.0" },
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
// Re-applying the same seed is a no-op on the rows.
|
|
348
|
+
const again = await seed(SEED);
|
|
349
|
+
expect(again.outcome.status === "applied" && again.outcome.result).toEqual({
|
|
350
|
+
templateId: id,
|
|
351
|
+
created: 0,
|
|
352
|
+
updated: 0,
|
|
353
|
+
unchanged: 3,
|
|
354
|
+
deleted: 0,
|
|
355
|
+
skipped: [],
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it("an invalid seed logs one error naming the entry and writes nothing", async () => {
|
|
360
|
+
await seed(SEED);
|
|
361
|
+
const before = await templateItems();
|
|
362
|
+
|
|
363
|
+
const { outcome, errors } = await seed({
|
|
364
|
+
marketplaces: [
|
|
365
|
+
{ name: "example-plugins", source: "example-org/plugins" },
|
|
366
|
+
{ name: "evil", source: "--upload-pack=touch /tmp/x" },
|
|
367
|
+
],
|
|
368
|
+
plugins: [],
|
|
369
|
+
});
|
|
370
|
+
expect(outcome.status).toBe("invalid");
|
|
371
|
+
expect(errors).toHaveLength(1);
|
|
372
|
+
expect(errors[0]).toContain("marketplaces[1] (evil)");
|
|
373
|
+
expect(await templateItems()).toEqual(before);
|
|
374
|
+
|
|
375
|
+
const bad = await runTemplateSeed({
|
|
376
|
+
raw: "{oops",
|
|
377
|
+
templateService: templates,
|
|
378
|
+
logger: quietLogger().logger,
|
|
379
|
+
});
|
|
380
|
+
expect(bad.status).toBe("invalid");
|
|
381
|
+
expect(await templateItems()).toEqual(before);
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
it("two concurrent applications against one database leave exactly one template and one copy of each item", async () => {
|
|
385
|
+
const other = createAdminPrismaClient(TEST_DB as string);
|
|
386
|
+
try {
|
|
387
|
+
const [a, b] = await Promise.all([
|
|
388
|
+
seed(SEED, templates),
|
|
389
|
+
seed(SEED, serviceFor(other)),
|
|
390
|
+
]);
|
|
391
|
+
expect(a.outcome.status).toBe("applied");
|
|
392
|
+
expect(b.outcome.status).toBe("applied");
|
|
393
|
+
expect(
|
|
394
|
+
await prisma.agentTemplate.count({
|
|
395
|
+
where: { accountId: null, specialty: null },
|
|
396
|
+
}),
|
|
397
|
+
).toBe(1);
|
|
398
|
+
const items = await templateItems();
|
|
399
|
+
expect(items.map((i) => `${i.kind}:${i.key}`)).toEqual([
|
|
400
|
+
"marketplace:example-plugins",
|
|
401
|
+
"plugin:other-plugin@example-plugins",
|
|
402
|
+
"plugin:some-plugin@example-plugins",
|
|
403
|
+
]);
|
|
404
|
+
} finally {
|
|
405
|
+
await other.$disconnect();
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
});
|