@app-vitals/agent-admin 1.42.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 +2 -2
- package/src/admin-boot.ts +7 -5
- package/src/admin-ui-github-enterprise-pages.ts +1 -1
- package/src/admin-ui-templates-pages.ts +155 -0
- package/src/admin-ui-templates-pages.unit.test.ts +54 -0
- package/src/admin-ui-templates.smoke.test.ts +292 -0
- package/src/admin-ui-templates.ts +316 -0
- package/src/admin-ui.ts +24 -0
- package/src/agent-cron-jobs.ts +107 -90
- package/src/agent-template-merge.ts +150 -0
- package/src/agent-template-merge.unit.test.ts +183 -0
- package/src/agent-template-reconcile.integration.test.ts +787 -0
- package/src/agent-template-reconcile.ts +578 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/admin-ui-templates.ts
|
|
3
|
+
* GET/POST /admin/settings/templates — the Settings > Templates editor
|
|
4
|
+
* (ATP-2.3). A thin UI over AgentTemplateService (the same service behind the
|
|
5
|
+
* ATP-1.3 /templates API), called directly with the same actor rules: platform
|
|
6
|
+
* admins edit every scope (including deployment-wide); an account member sees
|
|
7
|
+
* and edits only their own account's scopes; everyone else gets 403. Service
|
|
8
|
+
* errors (denylisted env key, unknown specialty, bad payload) are shown inline.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Context, Hono, MiddlewareHandler } from "hono";
|
|
12
|
+
import { accountIdFromScope } from "./account-agent-create.ts";
|
|
13
|
+
import type { AccountService } from "./accounts.ts";
|
|
14
|
+
import type { AdminUIEnv } from "./admin-ui.ts";
|
|
15
|
+
import {
|
|
16
|
+
ADMIN_TEMPLATES_PATH as BASE,
|
|
17
|
+
renderTemplatesPage,
|
|
18
|
+
type TemplateItemRow,
|
|
19
|
+
type TemplateScopeOption,
|
|
20
|
+
} from "./admin-ui-templates-pages.ts";
|
|
21
|
+
import {
|
|
22
|
+
AGENT_TEMPLATE_ITEM_KINDS,
|
|
23
|
+
type AgentTemplateItemKind,
|
|
24
|
+
} from "./agent-template-items.ts";
|
|
25
|
+
import type {
|
|
26
|
+
AgentTemplateService,
|
|
27
|
+
TemplateActor,
|
|
28
|
+
TemplateItemInput,
|
|
29
|
+
TemplateView,
|
|
30
|
+
} from "./agent-templates.ts";
|
|
31
|
+
import type { CallerScopeResolver } from "./caller-scope.ts";
|
|
32
|
+
import { ApiError, ForbiddenError } from "./errors.ts";
|
|
33
|
+
import type { SpecialtyTypeResolver } from "./specialty-types.ts";
|
|
34
|
+
|
|
35
|
+
export interface AdminTemplatesRouteDeps {
|
|
36
|
+
requireAuth: MiddlewareHandler<AdminUIEnv>;
|
|
37
|
+
templateService: Pick<
|
|
38
|
+
AgentTemplateService,
|
|
39
|
+
"list" | "replace" | "putItem" | "deleteItem" | "delete"
|
|
40
|
+
>;
|
|
41
|
+
callerScopeResolver: CallerScopeResolver;
|
|
42
|
+
/** Optional: without it admins can only pick deployment-wide. */
|
|
43
|
+
accounts?: Pick<AccountService, "listWithCounts" | "getWithCounts">;
|
|
44
|
+
specialtyRegistry: Pick<SpecialtyTypeResolver, "listTypes">;
|
|
45
|
+
html: (content: string, opts?: { status?: number }) => Response;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const NOTICES: Record<string, string> = {
|
|
49
|
+
saved: "Saved.",
|
|
50
|
+
removed: "Item removed.",
|
|
51
|
+
deleted: "Template deleted.",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const isKind = (v: string): v is AgentTemplateItemKind =>
|
|
55
|
+
(AGENT_TEMPLATE_ITEM_KINDS as readonly string[]).includes(v);
|
|
56
|
+
|
|
57
|
+
interface Scope {
|
|
58
|
+
/** "" = deployment-wide. */
|
|
59
|
+
accountId: string;
|
|
60
|
+
/** "" = every agent type. */
|
|
61
|
+
specialty: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function registerAdminTemplatesRoutes(
|
|
65
|
+
app: Hono<AdminUIEnv>,
|
|
66
|
+
deps: AdminTemplatesRouteDeps,
|
|
67
|
+
): void {
|
|
68
|
+
async function resolveActor(c: Context<AdminUIEnv>): Promise<TemplateActor> {
|
|
69
|
+
if (c.var.isAdmin === true) return { kind: "admin" };
|
|
70
|
+
const accountId = accountIdFromScope(
|
|
71
|
+
await deps.callerScopeResolver(c.var.userEmail, false),
|
|
72
|
+
);
|
|
73
|
+
if (accountId === null) {
|
|
74
|
+
throw new ForbiddenError("Admin or account access required");
|
|
75
|
+
}
|
|
76
|
+
return { kind: "account", accountId };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Account members are pinned to their account; naming another is 403. */
|
|
80
|
+
function resolveScope(
|
|
81
|
+
actor: TemplateActor,
|
|
82
|
+
accountId: string,
|
|
83
|
+
specialty: string,
|
|
84
|
+
): Scope {
|
|
85
|
+
if (actor.kind === "account") {
|
|
86
|
+
if (accountId !== "" && accountId !== actor.accountId) {
|
|
87
|
+
throw new ForbiddenError(
|
|
88
|
+
"cannot manage another account's or deployment-wide templates",
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
return { accountId: actor.accountId, specialty };
|
|
92
|
+
}
|
|
93
|
+
return { accountId, specialty };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function findTemplate(
|
|
97
|
+
actor: TemplateActor,
|
|
98
|
+
scope: Scope,
|
|
99
|
+
): Promise<TemplateView | undefined> {
|
|
100
|
+
const templates = await deps.templateService.list(actor, {
|
|
101
|
+
...(scope.accountId !== "" ? { accountId: scope.accountId } : {}),
|
|
102
|
+
...(scope.specialty !== "" ? { specialty: scope.specialty } : {}),
|
|
103
|
+
});
|
|
104
|
+
return templates.find(
|
|
105
|
+
(t) =>
|
|
106
|
+
(t.accountId ?? "") === scope.accountId &&
|
|
107
|
+
(t.specialty ?? "") === scope.specialty,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function accountOptions(
|
|
112
|
+
actor: TemplateActor,
|
|
113
|
+
): Promise<TemplateScopeOption[]> {
|
|
114
|
+
if (actor.kind === "account") {
|
|
115
|
+
const acct = await deps.accounts?.getWithCounts(actor.accountId);
|
|
116
|
+
return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
|
|
117
|
+
}
|
|
118
|
+
const accounts = (await deps.accounts?.listWithCounts()) ?? [];
|
|
119
|
+
return [
|
|
120
|
+
{ value: "", label: "Deployment-wide (all accounts)" },
|
|
121
|
+
...accounts.map((a) => ({ value: a.id, label: a.name })),
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function specialtyOptions(): TemplateScopeOption[] {
|
|
126
|
+
return [
|
|
127
|
+
{ value: "", label: "All agent types" },
|
|
128
|
+
...deps.specialtyRegistry
|
|
129
|
+
.listTypes()
|
|
130
|
+
.map((t) => ({ value: t.name, label: t.displayName })),
|
|
131
|
+
];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function renderPage(
|
|
135
|
+
c: Context<AdminUIEnv>,
|
|
136
|
+
actor: TemplateActor,
|
|
137
|
+
scope: Scope,
|
|
138
|
+
flash: { error?: string; notice?: string; status?: number } = {},
|
|
139
|
+
): Promise<Response> {
|
|
140
|
+
const template = await findTemplate(actor, scope);
|
|
141
|
+
return deps.html(
|
|
142
|
+
renderTemplatesPage({
|
|
143
|
+
userEmail: c.var.userEmail,
|
|
144
|
+
accountOptions: await accountOptions(actor),
|
|
145
|
+
specialtyOptions: specialtyOptions(),
|
|
146
|
+
accountId: scope.accountId,
|
|
147
|
+
specialty: scope.specialty,
|
|
148
|
+
items: (template?.items ?? []) as TemplateItemRow[],
|
|
149
|
+
templateExists: template !== undefined,
|
|
150
|
+
...(flash.error ? { error: flash.error } : {}),
|
|
151
|
+
...(flash.notice ? { notice: flash.notice } : {}),
|
|
152
|
+
}),
|
|
153
|
+
{ status: flash.status ?? 200 },
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const field = (form: FormData, name: string) =>
|
|
158
|
+
(form.get(name)?.toString() ?? "").trim();
|
|
159
|
+
const flag = (form: FormData, name: string) => form.get(name) !== null;
|
|
160
|
+
const orNull = (v: string) => (v === "" ? null : v);
|
|
161
|
+
|
|
162
|
+
function itemFromForm(form: FormData): TemplateItemInput {
|
|
163
|
+
const kind = field(form, "kind");
|
|
164
|
+
if (!isKind(kind)) throw new ApiError(422, `unknown item kind ${kind}`);
|
|
165
|
+
const key = field(form, "key");
|
|
166
|
+
switch (kind) {
|
|
167
|
+
case "env":
|
|
168
|
+
return {
|
|
169
|
+
kind,
|
|
170
|
+
key,
|
|
171
|
+
// Not trimmed: a value's whitespace is the user's business.
|
|
172
|
+
payload: {
|
|
173
|
+
value: form.get("value")?.toString() ?? "",
|
|
174
|
+
secret: flag(form, "secret"),
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
case "tool":
|
|
178
|
+
return { kind, key, payload: { enabled: flag(form, "enabled") } };
|
|
179
|
+
case "plugin":
|
|
180
|
+
return {
|
|
181
|
+
kind,
|
|
182
|
+
key,
|
|
183
|
+
payload: {
|
|
184
|
+
version: orNull(field(form, "version")),
|
|
185
|
+
enabled: flag(form, "enabled"),
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
case "cron":
|
|
189
|
+
return {
|
|
190
|
+
kind,
|
|
191
|
+
key,
|
|
192
|
+
payload: {
|
|
193
|
+
schedule: field(form, "schedule"),
|
|
194
|
+
prompt: field(form, "prompt"),
|
|
195
|
+
channel: orNull(field(form, "channel")),
|
|
196
|
+
user: orNull(field(form, "user")),
|
|
197
|
+
preCheck: orNull(field(form, "preCheck")),
|
|
198
|
+
silent: flag(form, "silent"),
|
|
199
|
+
enabled: flag(form, "enabled"),
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Runs a mutation; service errors render inline, success redirects. */
|
|
206
|
+
async function mutate(
|
|
207
|
+
c: Context<AdminUIEnv>,
|
|
208
|
+
notice: string,
|
|
209
|
+
run: (actor: TemplateActor, scope: Scope, form: FormData) => Promise<void>,
|
|
210
|
+
): Promise<Response> {
|
|
211
|
+
let actor: TemplateActor;
|
|
212
|
+
try {
|
|
213
|
+
actor = await resolveActor(c);
|
|
214
|
+
} catch {
|
|
215
|
+
return new Response("Forbidden", { status: 403 });
|
|
216
|
+
}
|
|
217
|
+
let form: FormData;
|
|
218
|
+
try {
|
|
219
|
+
form = await c.req.formData();
|
|
220
|
+
} catch {
|
|
221
|
+
form = new FormData();
|
|
222
|
+
}
|
|
223
|
+
const requested = {
|
|
224
|
+
accountId: field(form, "accountId"),
|
|
225
|
+
specialty: field(form, "specialty"),
|
|
226
|
+
};
|
|
227
|
+
let scope: Scope;
|
|
228
|
+
try {
|
|
229
|
+
scope = resolveScope(actor, requested.accountId, requested.specialty);
|
|
230
|
+
} catch {
|
|
231
|
+
return new Response("Forbidden", { status: 403 });
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
await run(actor, scope, form);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (err instanceof ApiError && err.statusCode < 500) {
|
|
237
|
+
return renderPage(c, actor, scope, {
|
|
238
|
+
error: err.message,
|
|
239
|
+
status: err.statusCode,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
throw err;
|
|
243
|
+
}
|
|
244
|
+
const qs = new URLSearchParams({
|
|
245
|
+
...(scope.accountId !== "" ? { accountId: scope.accountId } : {}),
|
|
246
|
+
...(scope.specialty !== "" ? { specialty: scope.specialty } : {}),
|
|
247
|
+
notice,
|
|
248
|
+
});
|
|
249
|
+
return c.redirect(`${BASE}?${qs}`, 302);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
app.get(BASE, deps.requireAuth, async (c) => {
|
|
253
|
+
let actor: TemplateActor;
|
|
254
|
+
try {
|
|
255
|
+
actor = await resolveActor(c);
|
|
256
|
+
} catch {
|
|
257
|
+
return new Response("Forbidden", { status: 403 });
|
|
258
|
+
}
|
|
259
|
+
let scope: Scope;
|
|
260
|
+
try {
|
|
261
|
+
scope = resolveScope(
|
|
262
|
+
actor,
|
|
263
|
+
c.req.query("accountId")?.trim() ?? "",
|
|
264
|
+
c.req.query("specialty")?.trim() ?? "",
|
|
265
|
+
);
|
|
266
|
+
} catch {
|
|
267
|
+
return new Response("Forbidden", { status: 403 });
|
|
268
|
+
}
|
|
269
|
+
const key = c.req.query("notice");
|
|
270
|
+
return renderPage(c, actor, scope, {
|
|
271
|
+
...(key && NOTICES[key] ? { notice: NOTICES[key] } : {}),
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
app.post(`${BASE}/items`, deps.requireAuth, (c) =>
|
|
276
|
+
mutate(c, "saved", async (actor, scope, form) => {
|
|
277
|
+
const item = itemFromForm(form);
|
|
278
|
+
const template = await findTemplate(actor, scope);
|
|
279
|
+
if (template) {
|
|
280
|
+
await deps.templateService.putItem(actor, template.id, item);
|
|
281
|
+
} else {
|
|
282
|
+
await deps.templateService.replace(
|
|
283
|
+
actor,
|
|
284
|
+
{
|
|
285
|
+
accountId: scope.accountId === "" ? null : scope.accountId,
|
|
286
|
+
specialty: scope.specialty === "" ? null : scope.specialty,
|
|
287
|
+
},
|
|
288
|
+
[item],
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
}),
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
app.post(`${BASE}/items/delete`, deps.requireAuth, (c) =>
|
|
295
|
+
mutate(c, "removed", async (actor, scope, form) => {
|
|
296
|
+
const kind = field(form, "kind");
|
|
297
|
+
if (!isKind(kind)) throw new ApiError(422, `unknown item kind ${kind}`);
|
|
298
|
+
const template = await findTemplate(actor, scope);
|
|
299
|
+
if (!template) throw new ApiError(404, "template not found");
|
|
300
|
+
await deps.templateService.deleteItem(
|
|
301
|
+
actor,
|
|
302
|
+
template.id,
|
|
303
|
+
kind,
|
|
304
|
+
field(form, "key"),
|
|
305
|
+
);
|
|
306
|
+
}),
|
|
307
|
+
);
|
|
308
|
+
|
|
309
|
+
app.post(`${BASE}/delete`, deps.requireAuth, (c) =>
|
|
310
|
+
mutate(c, "deleted", async (actor, scope) => {
|
|
311
|
+
const template = await findTemplate(actor, scope);
|
|
312
|
+
if (!template) throw new ApiError(404, "template not found");
|
|
313
|
+
await deps.templateService.delete(actor, template.id);
|
|
314
|
+
}),
|
|
315
|
+
);
|
|
316
|
+
}
|
package/src/admin-ui.ts
CHANGED
|
@@ -52,6 +52,8 @@ import {
|
|
|
52
52
|
import { renderZeroQuotaNotice } from "./admin-ui-account-pages.ts";
|
|
53
53
|
import { registerAdminAccountsRoutes } from "./admin-ui-accounts.ts";
|
|
54
54
|
import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterprise.ts";
|
|
55
|
+
import { registerAdminTemplatesRoutes } from "./admin-ui-templates.ts";
|
|
56
|
+
import type { AgentTemplateService } from "./agent-templates.ts";
|
|
55
57
|
import {
|
|
56
58
|
type GithubAccessPreviewView,
|
|
57
59
|
renderGithubAccessError,
|
|
@@ -437,6 +439,14 @@ export interface AdminUIDeps {
|
|
|
437
439
|
* (additive): when absent the Settings page and its nav entry are not
|
|
438
440
|
* registered.
|
|
439
441
|
*/
|
|
442
|
+
/**
|
|
443
|
+
* ATP-2.3: the template service behind Settings > Templates. Optional;
|
|
444
|
+
* absent → no /admin/settings/templates routes.
|
|
445
|
+
*/
|
|
446
|
+
templateService?: Pick<
|
|
447
|
+
AgentTemplateService,
|
|
448
|
+
"list" | "replace" | "putItem" | "deleteItem" | "delete"
|
|
449
|
+
>;
|
|
440
450
|
githubEnterpriseApi?: (
|
|
441
451
|
path: string,
|
|
442
452
|
init?: RequestInit,
|
|
@@ -855,6 +865,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
|
855
865
|
accountCreatedNotifier,
|
|
856
866
|
accountServices,
|
|
857
867
|
githubEnterpriseApi,
|
|
868
|
+
templateService,
|
|
858
869
|
agentsApi,
|
|
859
870
|
specialtyRegistry = new SpecialtyTypes(),
|
|
860
871
|
specialtyDefaults,
|
|
@@ -3706,6 +3717,19 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
|
|
|
3706
3717
|
});
|
|
3707
3718
|
}
|
|
3708
3719
|
|
|
3720
|
+
// ─── Template editor (ATP-2.3) ───────────────────────────────────────────
|
|
3721
|
+
|
|
3722
|
+
if (templateService) {
|
|
3723
|
+
registerAdminTemplatesRoutes(app, {
|
|
3724
|
+
requireAuth,
|
|
3725
|
+
templateService,
|
|
3726
|
+
callerScopeResolver,
|
|
3727
|
+
...(accountServices ? { accounts: accountServices.accounts } : {}),
|
|
3728
|
+
specialtyRegistry,
|
|
3729
|
+
html,
|
|
3730
|
+
});
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3709
3733
|
// ─── Account page (SSP-3.2) ───────────────────────────────────────────────
|
|
3710
3734
|
|
|
3711
3735
|
if (accountServices) {
|
package/src/agent-cron-jobs.ts
CHANGED
|
@@ -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
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
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
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
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
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
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
|
-
|
|
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
|
}
|