@app-vitals/agent-admin 1.43.0 → 1.45.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.
@@ -0,0 +1,578 @@
1
+ /**
2
+ * admin/src/agent-template-reconcile.ts
3
+ * ATP-2.1: per-agent template reconcile — the generalization of
4
+ * reconcileSystemCrons() (agent-cron-jobs.ts) to env, tools, plugins and
5
+ * crons.
6
+ *
7
+ * reconcile(agentId) resolves the agent's merged template
8
+ * (agent-template-merge.ts: specialty defaults, deployment/all,
9
+ * deployment/type, account/all, account/type) and applies it in ONE
10
+ * transaction, so a failure leaves no partial writes:
11
+ *
12
+ * - Missing items are created with source="template".
13
+ * - Rows with source="template" track the template: edited in place (ids
14
+ * stay stable), and deleted once no layer defines their key (orphans).
15
+ * - Rows with source="custom" are never modified. That covers admin edits and
16
+ * tombstones (ATP-1.2 turns a deleted template row into enabled=false,
17
+ * source=custom), so a deleted inherited row is never re-added.
18
+ * - Adoption: an enabled custom row whose value already equals the template
19
+ * value becomes source="template" (existing agents start all-custom). A
20
+ * same-named user cron is adopted only when schedule and prompt match;
21
+ * otherwise it is left alone and reported in `conflicts`.
22
+ * - The specialty's default crons stay system crons (system=true), applied
23
+ * through applySystemCronDefaults(); a template cron with the same name
24
+ * overrides the default's fields in place.
25
+ * - The tool rows are never reduced to zero enabled patterns (the runtime
26
+ * ignores an empty allowedTools); such removals are skipped and flagged.
27
+ * - The specialty is read on every run, so a changed specialty re-resolves:
28
+ * the old type's template rows become orphans, the new type's are added.
29
+ * - A detached agent (Agent.templateDetached) and an agent whose specialty is
30
+ * neither built in nor extension-supplied are left untouched.
31
+ *
32
+ * Only payload fields a cron template item actually sets are tracked on an
33
+ * existing row; unset fields take their defaults on create only.
34
+ */
35
+
36
+ import type {
37
+ AgentCronJob,
38
+ AgentEnv,
39
+ AgentPlugin,
40
+ AgentTool,
41
+ PrismaClient,
42
+ } from "../prisma/client/client.ts";
43
+ import { applySystemCronDefaults, isValidCron } from "./agent-cron-jobs.ts";
44
+ import {
45
+ type AgentTemplateItemKind,
46
+ openTemplateItemPayload,
47
+ TEMPLATE_ENV_DENYLIST,
48
+ type TemplateItemPayload,
49
+ } from "./agent-template-items.ts";
50
+ import {
51
+ type MergedTemplate,
52
+ type MergedTemplateItem,
53
+ mergeTemplateLayers,
54
+ resolveSpecialtyDefaultSet,
55
+ specialtyDefaultLayer,
56
+ type TemplateLayerInput,
57
+ templateLayerForScope,
58
+ } from "./agent-template-merge.ts";
59
+ import { NotFoundError } from "./errors.ts";
60
+ import type { PrismaTransactionClient } from "./prisma-tx.ts";
61
+ import type {
62
+ SpecialtyDefaultCron,
63
+ SpecialtyDefaultsResolver,
64
+ } from "./specialty-defaults.ts";
65
+ import type { SpecialtyTypeResolver } from "./specialty-types.ts";
66
+ import type { TokenCrypto } from "./token-crypto.ts";
67
+
68
+ export interface TemplateReconcileCounts {
69
+ created: number;
70
+ updated: number;
71
+ adopted: number;
72
+ deleted: number;
73
+ }
74
+
75
+ export interface TemplateReconcileConflict {
76
+ kind: AgentTemplateItemKind;
77
+ key: string;
78
+ reason: "cron_name_conflict" | "invalid_cron_schedule" | "denylisted_env_key";
79
+ }
80
+
81
+ export interface TemplateReconcileResult {
82
+ agentId: string;
83
+ /** "detached" / "unknown_specialty": nothing was written. */
84
+ status: "reconciled" | "detached" | "unknown_specialty";
85
+ /** Template-tracked rows (system crons are counted in `systemCrons`). */
86
+ counts: Record<AgentTemplateItemKind, TemplateReconcileCounts>;
87
+ systemCrons: { created: number; updated: number; deleted: number };
88
+ /** Template items deliberately not applied. */
89
+ conflicts: TemplateReconcileConflict[];
90
+ /** True when tool removals/disables were skipped to keep one enabled tool. */
91
+ toolsEmptyGuarded: boolean;
92
+ }
93
+
94
+ const zeroCounts = (): TemplateReconcileCounts => ({
95
+ created: 0,
96
+ updated: 0,
97
+ adopted: 0,
98
+ deleted: 0,
99
+ });
100
+
101
+ function emptyResult(
102
+ agentId: string,
103
+ status: TemplateReconcileResult["status"],
104
+ ): TemplateReconcileResult {
105
+ return {
106
+ agentId,
107
+ status,
108
+ counts: {
109
+ env: zeroCounts(),
110
+ tool: zeroCounts(),
111
+ plugin: zeroCounts(),
112
+ cron: zeroCounts(),
113
+ },
114
+ systemCrons: { created: 0, updated: 0, deleted: 0 },
115
+ conflicts: [],
116
+ toolsEmptyGuarded: false,
117
+ };
118
+ }
119
+
120
+ const enabledOf = (payload: Record<string, unknown>): boolean =>
121
+ payload.enabled !== false;
122
+
123
+ const versionOf = (payload: Record<string, unknown>): string | null =>
124
+ typeof payload.version === "string" ? payload.version : null;
125
+
126
+ /** Cron row fields a template item may set, in row column names. */
127
+ const CRON_FIELDS = [
128
+ "schedule",
129
+ "prompt",
130
+ "channel",
131
+ "user",
132
+ "silent",
133
+ "preCheck",
134
+ "enabled",
135
+ ] as const;
136
+ type CronField = (typeof CRON_FIELDS)[number];
137
+ type CronFields = { [K in CronField]?: AgentCronJob[K] };
138
+
139
+ /** The row fields `payload` sets (absent keys are not tracked). */
140
+ function cronFieldsOf(payload: Record<string, unknown>): CronFields {
141
+ const out: CronFields = {};
142
+ if (typeof payload.schedule === "string") out.schedule = payload.schedule;
143
+ if (typeof payload.prompt === "string") out.prompt = payload.prompt;
144
+ if ("channel" in payload) out.channel = (payload.channel as string) ?? null;
145
+ if ("user" in payload) out.user = (payload.user as string) ?? null;
146
+ if (typeof payload.silent === "boolean") out.silent = payload.silent;
147
+ if ("preCheck" in payload) {
148
+ out.preCheck = (payload.preCheck as string) ?? null;
149
+ }
150
+ if (typeof payload.enabled === "boolean") out.enabled = payload.enabled;
151
+ return out;
152
+ }
153
+
154
+ /** The subset of `want` that differs from `row`. */
155
+ function cronDiff(row: AgentCronJob, want: CronFields): CronFields {
156
+ const diff: CronFields = {};
157
+ for (const field of CRON_FIELDS) {
158
+ const value = want[field];
159
+ if (value === undefined) continue;
160
+ // A lockdown-disabled cron stays disabled until the lockdown lifts.
161
+ if (field === "enabled" && row.lockdownDisabledAt !== null) continue;
162
+ if (row[field] !== value) Object.assign(diff, { [field]: value });
163
+ }
164
+ return diff;
165
+ }
166
+
167
+ export class AgentTemplateReconcileService {
168
+ constructor(
169
+ private prisma: PrismaClient,
170
+ private crypto: TokenCrypto,
171
+ private specialtyRegistry: Pick<SpecialtyTypeResolver, "tryGetType">,
172
+ private specialtyDefaults: SpecialtyDefaultsResolver = () => undefined,
173
+ ) {}
174
+
175
+ /** Reconcile one agent against its merged template, in one transaction. */
176
+ async reconcile(agentId: string): Promise<TemplateReconcileResult> {
177
+ return this.prisma.$transaction(async (tx) => {
178
+ // Serialize concurrent reconciles of the same agent.
179
+ await tx.$queryRaw`SELECT "id" FROM "Agent" WHERE "id" = ${agentId} FOR UPDATE`;
180
+ const agent = await tx.agent.findUnique({
181
+ where: { id: agentId },
182
+ select: { specialty: true, accountId: true, templateDetached: true },
183
+ });
184
+ if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
185
+ if (agent.templateDetached) return emptyResult(agentId, "detached");
186
+
187
+ const defaults = resolveSpecialtyDefaultSet(
188
+ agent.specialty,
189
+ this.specialtyRegistry,
190
+ this.specialtyDefaults,
191
+ );
192
+ if (!defaults) {
193
+ console.error(
194
+ `template reconcile: no known type for specialty "${agent.specialty}" (agent ${agentId}) — leaving it untouched`,
195
+ );
196
+ return emptyResult(agentId, "unknown_specialty");
197
+ }
198
+
199
+ const merged = await this.resolve(
200
+ tx,
201
+ agent.accountId,
202
+ agent.specialty,
203
+ specialtyDefaultLayer(defaults),
204
+ );
205
+ const result = emptyResult(agentId, "reconciled");
206
+ // Env goes last: it is the only kind that encrypts on write.
207
+ await this.reconcileTools(tx, agentId, merged, result);
208
+ await this.reconcilePlugins(tx, agentId, merged, result);
209
+ await this.reconcileCrons(tx, agentId, merged, defaults.crons, result);
210
+ await this.reconcileEnv(tx, agentId, merged, result);
211
+ return result;
212
+ });
213
+ }
214
+
215
+ /** Loads the in-scope templates and merges them over `base`. */
216
+ private async resolve(
217
+ tx: PrismaTransactionClient,
218
+ accountId: string | null,
219
+ specialty: string,
220
+ base: TemplateLayerInput,
221
+ ): Promise<MergedTemplate> {
222
+ const templates = await tx.agentTemplate.findMany({
223
+ where: {
224
+ AND: [
225
+ {
226
+ OR: [
227
+ { accountId: null },
228
+ ...(accountId === null ? [] : [{ accountId }]),
229
+ ],
230
+ },
231
+ { OR: [{ specialty: null }, { specialty }] },
232
+ ],
233
+ },
234
+ include: { items: true },
235
+ });
236
+ const layers: TemplateLayerInput[] = [base];
237
+ for (const t of templates) {
238
+ layers.push({
239
+ layer: templateLayerForScope(t),
240
+ items: t.items.map((it) => {
241
+ const kind = it.kind as AgentTemplateItemKind;
242
+ return {
243
+ kind,
244
+ key: it.key,
245
+ payload: openTemplateItemPayload(
246
+ kind,
247
+ (it.payload ?? {}) as TemplateItemPayload,
248
+ this.crypto,
249
+ ),
250
+ };
251
+ }),
252
+ });
253
+ }
254
+ return mergeTemplateLayers(layers);
255
+ }
256
+
257
+ private async reconcileTools(
258
+ tx: PrismaTransactionClient,
259
+ agentId: string,
260
+ merged: MergedTemplate,
261
+ result: TemplateReconcileResult,
262
+ ): Promise<void> {
263
+ const counts = result.counts.tool;
264
+ const rows = await tx.agentTool.findMany({ where: { agentId } });
265
+ const byPattern = new Map(rows.map((r) => [r.pattern, r]));
266
+
267
+ const creates: { pattern: string; enabled: boolean }[] = [];
268
+ const updates: { row: AgentTool; enabled: boolean }[] = [];
269
+ const adopts: AgentTool[] = [];
270
+ for (const item of merged.tool.values()) {
271
+ const enabled = enabledOf(item.payload);
272
+ const row = byPattern.get(item.key);
273
+ if (!row) creates.push({ pattern: item.key, enabled });
274
+ else if (row.source === "template") {
275
+ if (row.enabled !== enabled) updates.push({ row, enabled });
276
+ } else if (row.enabled && enabled) adopts.push(row);
277
+ }
278
+ const orphans = rows.filter(
279
+ (r) => r.source === "template" && !merged.tool.has(r.pattern),
280
+ );
281
+
282
+ // Never leave the agent with zero enabled tools.
283
+ const finalEnabled = new Map(rows.map((r) => [r.pattern, r.enabled]));
284
+ for (const c of creates) finalEnabled.set(c.pattern, c.enabled);
285
+ for (const u of updates) finalEnabled.set(u.row.pattern, u.enabled);
286
+ for (const o of orphans) finalEnabled.delete(o.pattern);
287
+ const anyEnabled = [...finalEnabled.values()].some(Boolean);
288
+ const reducing =
289
+ orphans.length > 0 ||
290
+ updates.some((u) => !u.enabled) ||
291
+ creates.some((c) => !c.enabled);
292
+ const guard = !anyEnabled && reducing;
293
+ result.toolsEmptyGuarded = guard;
294
+
295
+ for (const c of creates) {
296
+ if (guard && !c.enabled) continue;
297
+ await tx.agentTool.create({
298
+ data: { agentId, ...c, source: "template" },
299
+ });
300
+ counts.created++;
301
+ }
302
+ for (const u of updates) {
303
+ if (guard && !u.enabled) continue;
304
+ await tx.agentTool.update({
305
+ where: { id: u.row.id },
306
+ data: { enabled: u.enabled },
307
+ });
308
+ counts.updated++;
309
+ }
310
+ for (const row of adopts) {
311
+ await tx.agentTool.update({
312
+ where: { id: row.id },
313
+ data: { source: "template" },
314
+ });
315
+ counts.adopted++;
316
+ }
317
+ if (!guard) {
318
+ for (const row of orphans) {
319
+ await tx.agentTool.delete({ where: { id: row.id } });
320
+ counts.deleted++;
321
+ }
322
+ }
323
+ }
324
+
325
+ private async reconcilePlugins(
326
+ tx: PrismaTransactionClient,
327
+ agentId: string,
328
+ merged: MergedTemplate,
329
+ result: TemplateReconcileResult,
330
+ ): Promise<void> {
331
+ const counts = result.counts.plugin;
332
+ const rows = await tx.agentPlugin.findMany({ where: { agentId } });
333
+ const byName = new Map<string, AgentPlugin>(rows.map((r) => [r.name, r]));
334
+
335
+ for (const item of merged.plugin.values()) {
336
+ const version = versionOf(item.payload);
337
+ const enabled = enabledOf(item.payload);
338
+ const row = byName.get(item.key);
339
+ if (!row) {
340
+ await tx.agentPlugin.create({
341
+ data: {
342
+ agentId,
343
+ name: item.key,
344
+ version,
345
+ enabled,
346
+ source: "template",
347
+ },
348
+ });
349
+ counts.created++;
350
+ } else if (row.source === "template") {
351
+ if (row.version !== version || row.enabled !== enabled) {
352
+ await tx.agentPlugin.update({
353
+ where: { id: row.id },
354
+ data: { version, enabled },
355
+ });
356
+ counts.updated++;
357
+ }
358
+ } else if (row.enabled && enabled && row.version === version) {
359
+ await tx.agentPlugin.update({
360
+ where: { id: row.id },
361
+ data: { source: "template" },
362
+ });
363
+ counts.adopted++;
364
+ }
365
+ }
366
+ for (const row of rows) {
367
+ if (row.source === "template" && !merged.plugin.has(row.name)) {
368
+ await tx.agentPlugin.delete({ where: { id: row.id } });
369
+ counts.deleted++;
370
+ }
371
+ }
372
+ }
373
+
374
+ private async reconcileCrons(
375
+ tx: PrismaTransactionClient,
376
+ agentId: string,
377
+ merged: MergedTemplate,
378
+ systemDefaults: readonly SpecialtyDefaultCron[],
379
+ result: TemplateReconcileResult,
380
+ ): Promise<void> {
381
+ // System crons: the specialty's defaults, with a template override of the
382
+ // same name applied to the default's fields.
383
+ const systemNames = new Set(systemDefaults.map((c) => c.name));
384
+ const systemCrons = systemDefaults.map((def): SpecialtyDefaultCron => {
385
+ const winner = merged.cron.get(def.name);
386
+ if (!winner || winner.layer === "specialty-default") return def;
387
+ const f = cronFieldsOf(winner.payload);
388
+ // An invalid override schedule would land on a required system cron and
389
+ // break scheduling at runtime; keep the specialty default instead.
390
+ if (f.schedule !== undefined && !isValidCron(f.schedule)) {
391
+ result.conflicts.push({
392
+ kind: "cron",
393
+ key: def.name,
394
+ reason: "invalid_cron_schedule",
395
+ });
396
+ return def;
397
+ }
398
+ return {
399
+ name: def.name,
400
+ schedule: f.schedule ?? def.schedule,
401
+ prompt: f.prompt ?? def.prompt,
402
+ silent: f.silent ?? def.silent,
403
+ preCheck: f.preCheck ?? def.preCheck,
404
+ enabled: f.enabled ?? def.enabled,
405
+ parentCron: def.parentCron,
406
+ };
407
+ });
408
+ const existingSystem = await tx.agentCronJob.findMany({
409
+ where: { agentId, system: true },
410
+ });
411
+ result.systemCrons = await applySystemCronDefaults(
412
+ tx,
413
+ agentId,
414
+ systemCrons,
415
+ existingSystem,
416
+ );
417
+
418
+ // Template crons: every other merged cron, keyed by name.
419
+ const counts = result.counts.cron;
420
+ const rows = await tx.agentCronJob.findMany({
421
+ where: { agentId, system: false },
422
+ orderBy: { createdAt: "asc" },
423
+ });
424
+ const wanted = new Map<string, MergedTemplateItem>();
425
+ for (const item of merged.cron.values()) {
426
+ if (!systemNames.has(item.key)) wanted.set(item.key, item);
427
+ }
428
+
429
+ for (const item of wanted.values()) {
430
+ const fields = cronFieldsOf(item.payload);
431
+ if (
432
+ fields.schedule === undefined ||
433
+ fields.prompt === undefined ||
434
+ !isValidCron(fields.schedule)
435
+ ) {
436
+ result.conflicts.push({
437
+ kind: "cron",
438
+ key: item.key,
439
+ reason: "invalid_cron_schedule",
440
+ });
441
+ continue;
442
+ }
443
+ const named = rows.filter((r) => r.name === item.key);
444
+ const owned = named.find((r) => r.source === "template");
445
+ if (owned) {
446
+ const diff = cronDiff(owned, fields);
447
+ if (Object.keys(diff).length > 0) {
448
+ await tx.agentCronJob.update({ where: { id: owned.id }, data: diff });
449
+ counts.updated++;
450
+ }
451
+ continue;
452
+ }
453
+ if (named.length === 0) {
454
+ await tx.agentCronJob.create({
455
+ data: {
456
+ agentId,
457
+ name: item.key,
458
+ system: false,
459
+ source: "template",
460
+ schedule: fields.schedule,
461
+ prompt: fields.prompt,
462
+ channel: fields.channel ?? null,
463
+ user: fields.user ?? null,
464
+ silent: fields.silent ?? false,
465
+ preCheck: fields.preCheck ?? null,
466
+ enabled: fields.enabled ?? true,
467
+ },
468
+ });
469
+ counts.created++;
470
+ continue;
471
+ }
472
+ // A disabled same-named cron is a tombstone or a user decision.
473
+ if (named.some((r) => !r.enabled)) continue;
474
+ const [only] = named;
475
+ if (
476
+ named.length === 1 &&
477
+ only &&
478
+ only.schedule === fields.schedule &&
479
+ only.prompt === fields.prompt
480
+ ) {
481
+ await tx.agentCronJob.update({
482
+ where: { id: only.id },
483
+ data: { ...cronDiff(only, fields), source: "template" },
484
+ });
485
+ counts.adopted++;
486
+ continue;
487
+ }
488
+ result.conflicts.push({
489
+ kind: "cron",
490
+ key: item.key,
491
+ reason: "cron_name_conflict",
492
+ });
493
+ }
494
+
495
+ for (const row of rows) {
496
+ if (
497
+ row.source === "template" &&
498
+ (row.name === null || !wanted.has(row.name))
499
+ ) {
500
+ await tx.agentCronJob.delete({ where: { id: row.id } });
501
+ counts.deleted++;
502
+ }
503
+ }
504
+ }
505
+
506
+ private async reconcileEnv(
507
+ tx: PrismaTransactionClient,
508
+ agentId: string,
509
+ merged: MergedTemplate,
510
+ result: TemplateReconcileResult,
511
+ ): Promise<void> {
512
+ const counts = result.counts.env;
513
+ const rows = await tx.agentEnv.findMany({ where: { agentId } });
514
+ const byKey = new Map<string, AgentEnv>(rows.map((r) => [r.key, r]));
515
+ const applied = new Set<string>();
516
+
517
+ for (const item of merged.env.values()) {
518
+ if (TEMPLATE_ENV_DENYLIST.has(item.key.toUpperCase())) {
519
+ result.conflicts.push({
520
+ kind: "env",
521
+ key: item.key,
522
+ reason: "denylisted_env_key",
523
+ });
524
+ continue;
525
+ }
526
+ applied.add(item.key);
527
+ const value =
528
+ typeof item.payload.value === "string" ? item.payload.value : "";
529
+ const secret = item.payload.secret === true;
530
+ const row = byKey.get(item.key);
531
+ if (!row) {
532
+ await tx.agentEnv.create({
533
+ data: {
534
+ agentId,
535
+ key: item.key,
536
+ value: this.crypto.encrypt(value),
537
+ secret,
538
+ source: "template",
539
+ },
540
+ });
541
+ counts.created++;
542
+ } else if (row.source === "template") {
543
+ if (
544
+ !row.enabled ||
545
+ row.secret !== secret ||
546
+ this.tryDecrypt(row.value) !== value
547
+ ) {
548
+ await tx.agentEnv.update({
549
+ where: { id: row.id },
550
+ data: { value: this.crypto.encrypt(value), secret, enabled: true },
551
+ });
552
+ counts.updated++;
553
+ }
554
+ } else if (row.enabled && this.tryDecrypt(row.value) === value) {
555
+ await tx.agentEnv.update({
556
+ where: { id: row.id },
557
+ data: { source: "template", secret },
558
+ });
559
+ counts.adopted++;
560
+ }
561
+ }
562
+ for (const row of rows) {
563
+ if (row.source === "template" && !applied.has(row.key)) {
564
+ await tx.agentEnv.delete({ where: { id: row.id } });
565
+ counts.deleted++;
566
+ }
567
+ }
568
+ }
569
+
570
+ /** Decrypted value, or undefined when the stored value does not decrypt. */
571
+ private tryDecrypt(stored: string): string | undefined {
572
+ try {
573
+ return this.crypto.decrypt(stored);
574
+ } catch {
575
+ return undefined;
576
+ }
577
+ }
578
+ }