@app-vitals/agent-admin 1.64.0 → 1.66.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.
Files changed (32) hide show
  1. package/openapi.json +1 -1
  2. package/openapi.platform.json +6 -1
  3. package/package.json +2 -2
  4. package/prisma/client/internal/class.ts +4 -4
  5. package/prisma/client/internal/prismaNamespace.ts +1 -0
  6. package/prisma/client/internal/prismaNamespaceBrowser.ts +1 -0
  7. package/prisma/client/models/AgentTemplateItem.ts +36 -1
  8. package/prisma/migrations/20261117000000_add_agent_template_item_managed_by/migration.sql +5 -0
  9. package/prisma/schema/schema.prisma +3 -0
  10. package/src/admin-boot.boot-order.unit.test.ts +13 -1
  11. package/src/admin-boot.ts +25 -1
  12. package/src/admin-ui-pages.ts +30 -6
  13. package/src/admin-ui-pages.unit.test.ts +36 -1
  14. package/src/admin-ui-slack-config-token-flows.smoke.test.ts +346 -0
  15. package/src/admin-ui-templates-pages.ts +15 -1
  16. package/src/admin-ui-templates-pages.unit.test.ts +9 -0
  17. package/src/admin-ui-templates.smoke.test.ts +38 -0
  18. package/src/admin-ui.ts +46 -2
  19. package/src/agent-deletion.ts +39 -5
  20. package/src/agent-deletion.unit.test.ts +141 -0
  21. package/src/agent-templates-api.ts +1 -0
  22. package/src/agent-templates.ts +184 -9
  23. package/src/agents-api.smoke.test.ts +107 -1
  24. package/src/agents-api.ts +12 -4
  25. package/src/openapi-schemas.ts +9 -2
  26. package/src/slack-config-token-resolve.unit.test.ts +108 -0
  27. package/src/slack-config-token.ts +51 -0
  28. package/src/slack-provisioning-service.integration.test.ts +189 -1
  29. package/src/slack-provisioning-service.ts +43 -9
  30. package/src/template-seed.integration.test.ts +408 -0
  31. package/src/template-seed.ts +222 -0
  32. package/src/template-seed.unit.test.ts +272 -0
@@ -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
+ });
@@ -0,0 +1,222 @@
1
+ /**
2
+ * admin/src/template-seed.ts
3
+ * TMK-3.2: seed the deployment-wide, all-specialties agent template from
4
+ * SHIPWRIGHT_TEMPLATE_SEED, the JSON the agent-platform chart renders from
5
+ * `admin.templateSeed` Helm values:
6
+ *
7
+ * {"marketplaces":[{"name":"example-plugins","source":"example-org/plugins","ref":"v1.2.0"}],
8
+ * "plugins":["some-plugin@example-plugins"]}
9
+ *
10
+ * Only marketplaces and plugins can be seeded. Run once per admin boot, after
11
+ * migrations (admin-boot.ts):
12
+ *
13
+ * - Unset or blank: nothing happens; previously seeded items stay.
14
+ * - A listed kind (`marketplaces` / `plugins` present, even as `[]`) is
15
+ * replaced: its seeded items become exactly the list. A kind whose key is
16
+ * absent keeps its seeded items, so removal only ever happens by listing a
17
+ * smaller seed.
18
+ * - Invalid JSON or an entry failing the template validators (the same
19
+ * normalizeTemplateItem() as the /templates API): one error naming the
20
+ * entry is logged and nothing is written.
21
+ *
22
+ * The apply goes through AgentTemplateService.applyManagedItems(): items get
23
+ * managedBy="helm", hand-added items (managedBy null) are never touched, the
24
+ * write holds a transaction-scoped advisory lock so concurrent replicas are
25
+ * safe, and the ATP-2.2 fan-out then reconciles every attached agent.
26
+ *
27
+ * Seeded items are not read-only: UI/API edits are allowed and overwritten on
28
+ * the next boot. Never throws (like startup-policy-reconcile.ts).
29
+ */
30
+
31
+ import type { AgentTemplateItemKind } from "./agent-template-items.ts";
32
+ import {
33
+ type AgentTemplateService,
34
+ type ManagedItemsResult,
35
+ normalizeTemplateItem,
36
+ type TemplateItemInput,
37
+ } from "./agent-templates.ts";
38
+
39
+ export const TEMPLATE_SEED_ENV = "SHIPWRIGHT_TEMPLATE_SEED";
40
+
41
+ /** AgentTemplateItem.managedBy for seeded items. */
42
+ export const TEMPLATE_SEED_MANAGER = "helm";
43
+
44
+ type SeedKind = Extract<AgentTemplateItemKind, "marketplace" | "plugin">;
45
+
46
+ export interface TemplateSeed {
47
+ /** The kinds the seed lists; their seeded items are replaced. */
48
+ kinds: SeedKind[];
49
+ items: TemplateItemInput[];
50
+ }
51
+
52
+ export type TemplateSeedParse =
53
+ | { status: "unset" }
54
+ | { status: "ok"; seed: TemplateSeed }
55
+ | { status: "invalid"; error: string };
56
+
57
+ const MARKETPLACE_FIELDS = new Set(["name", "source", "ref"]);
58
+
59
+ const isObject = (v: unknown): v is Record<string, unknown> =>
60
+ v !== null && typeof v === "object" && !Array.isArray(v);
61
+
62
+ class SeedError extends Error {}
63
+
64
+ /** `marketplaces[1] (broken)` — how errors name an entry. */
65
+ function entryLabel(list: string, index: number, name: unknown): string {
66
+ return typeof name === "string" && name.trim() !== ""
67
+ ? `${list}[${index}] (${name})`
68
+ : `${list}[${index}]`;
69
+ }
70
+
71
+ /** Runs the template validators on one item, naming the entry on failure. */
72
+ function validated(label: string, item: TemplateItemInput): TemplateItemInput {
73
+ try {
74
+ const { kind, key, payload } = normalizeTemplateItem(item);
75
+ return { kind, key, payload };
76
+ } catch (err) {
77
+ throw new SeedError(
78
+ `${label}: ${err instanceof Error ? err.message : String(err)}`,
79
+ );
80
+ }
81
+ }
82
+
83
+ function parseMarketplaces(value: unknown): TemplateItemInput[] {
84
+ if (!Array.isArray(value)) {
85
+ throw new SeedError("marketplaces must be a list");
86
+ }
87
+ const names = new Set<string>();
88
+ return value.map((entry, i) => {
89
+ const name = isObject(entry) ? entry.name : undefined;
90
+ const label = entryLabel("marketplaces", i, name);
91
+ if (!isObject(entry)) {
92
+ throw new SeedError(`${label}: must be an object {name, source, ref?}`);
93
+ }
94
+ const unknown = Object.keys(entry).filter(
95
+ (k) => !MARKETPLACE_FIELDS.has(k),
96
+ );
97
+ if (unknown.length > 0) {
98
+ throw new SeedError(`${label}: unknown field ${unknown.join(", ")}`);
99
+ }
100
+ if (typeof name !== "string" || name.trim() === "") {
101
+ throw new SeedError(`${label}: name must be a non-empty string`);
102
+ }
103
+ if (typeof entry.source !== "string" || entry.source.trim() === "") {
104
+ throw new SeedError(`${label}: source must be a non-empty string`);
105
+ }
106
+ const payload: Record<string, unknown> = { source: entry.source };
107
+ if (entry.ref !== undefined) payload.ref = entry.ref;
108
+ const item = validated(label, { kind: "marketplace", key: name, payload });
109
+ if (names.has(item.key)) {
110
+ throw new SeedError(`${label}: duplicate marketplace ${item.key}`);
111
+ }
112
+ names.add(item.key);
113
+ return item;
114
+ });
115
+ }
116
+
117
+ function parsePlugins(value: unknown): TemplateItemInput[] {
118
+ if (!Array.isArray(value)) throw new SeedError("plugins must be a list");
119
+ const specs = new Set<string>();
120
+ return value.map((entry, i) => {
121
+ const label = entryLabel("plugins", i, entry);
122
+ if (typeof entry !== "string") {
123
+ throw new SeedError(`${label}: must be a plugin spec string`);
124
+ }
125
+ const item = validated(label, { kind: "plugin", key: entry, payload: {} });
126
+ if (specs.has(item.key)) {
127
+ throw new SeedError(`${label}: duplicate plugin ${item.key}`);
128
+ }
129
+ specs.add(item.key);
130
+ return item;
131
+ });
132
+ }
133
+
134
+ /** Parses and validates SHIPWRIGHT_TEMPLATE_SEED. Pure; never throws. */
135
+ export function parseTemplateSeed(raw: string | undefined): TemplateSeedParse {
136
+ if (raw === undefined || raw.trim() === "") return { status: "unset" };
137
+ let doc: unknown;
138
+ try {
139
+ doc = JSON.parse(raw);
140
+ } catch (err) {
141
+ return {
142
+ status: "invalid",
143
+ error: `not valid JSON (${err instanceof Error ? err.message : String(err)})`,
144
+ };
145
+ }
146
+ try {
147
+ if (!isObject(doc)) {
148
+ throw new SeedError(
149
+ "must be a JSON object with marketplaces and/or plugins",
150
+ );
151
+ }
152
+ const unknown = Object.keys(doc).filter(
153
+ (k) => k !== "marketplaces" && k !== "plugins",
154
+ );
155
+ if (unknown.length > 0) {
156
+ throw new SeedError(
157
+ `unknown key ${unknown.join(", ")}; only marketplaces and plugins can be seeded`,
158
+ );
159
+ }
160
+ const kinds: SeedKind[] = [];
161
+ const items: TemplateItemInput[] = [];
162
+ if (doc.marketplaces !== undefined) {
163
+ kinds.push("marketplace");
164
+ items.push(...parseMarketplaces(doc.marketplaces));
165
+ }
166
+ if (doc.plugins !== undefined) {
167
+ kinds.push("plugin");
168
+ items.push(...parsePlugins(doc.plugins));
169
+ }
170
+ return { status: "ok", seed: { kinds, items } };
171
+ } catch (err) {
172
+ if (err instanceof SeedError) {
173
+ return { status: "invalid", error: err.message };
174
+ }
175
+ throw err;
176
+ }
177
+ }
178
+
179
+ export interface TemplateSeedDeps {
180
+ /** The raw env value (process.env.SHIPWRIGHT_TEMPLATE_SEED). */
181
+ raw: string | undefined;
182
+ templateService: Pick<AgentTemplateService, "applyManagedItems">;
183
+ logger: Pick<Console, "log" | "error">;
184
+ }
185
+
186
+ export type TemplateSeedOutcome =
187
+ | { status: "unset" }
188
+ | { status: "invalid"; error: string }
189
+ | { status: "applied"; result: ManagedItemsResult }
190
+ | { status: "failed"; error: string };
191
+
192
+ /** Applies the seed on boot. Never throws; every failure is logged once. */
193
+ export async function runTemplateSeed({
194
+ raw,
195
+ templateService,
196
+ logger,
197
+ }: TemplateSeedDeps): Promise<TemplateSeedOutcome> {
198
+ const parsed = parseTemplateSeed(raw);
199
+ if (parsed.status === "unset") return parsed;
200
+ if (parsed.status === "invalid") {
201
+ logger.error(
202
+ `[template-seed] invalid ${TEMPLATE_SEED_ENV}, nothing applied (previously seeded items kept): ${parsed.error}`,
203
+ );
204
+ return parsed;
205
+ }
206
+ try {
207
+ const result = await templateService.applyManagedItems(
208
+ TEMPLATE_SEED_MANAGER,
209
+ parsed.seed.kinds,
210
+ parsed.seed.items,
211
+ );
212
+ const skipped = result.skipped.map((s) => `${s.kind}:${s.key}`).join(",");
213
+ logger.log(
214
+ `[template-seed] kinds=${parsed.seed.kinds.join(",") || "none"} created=${result.created} updated=${result.updated} unchanged=${result.unchanged} deleted=${result.deleted}${skipped ? ` skipped(hand-added)=${skipped}` : ""}`,
215
+ );
216
+ return { status: "applied", result };
217
+ } catch (err) {
218
+ const error = err instanceof Error ? err.message : String(err);
219
+ logger.error(`[template-seed] apply failed, nothing applied: ${error}`);
220
+ return { status: "failed", error };
221
+ }
222
+ }