@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.
- package/openapi.json +1 -1
- package/openapi.platform.json +6 -1
- 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 +25 -1
- package/src/admin-ui-pages.ts +30 -6
- package/src/admin-ui-pages.unit.test.ts +36 -1
- package/src/admin-ui-slack-config-token-flows.smoke.test.ts +346 -0
- 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/admin-ui.ts +46 -2
- package/src/agent-deletion.ts +39 -5
- package/src/agent-deletion.unit.test.ts +141 -0
- package/src/agent-templates-api.ts +1 -0
- package/src/agent-templates.ts +184 -9
- package/src/agents-api.smoke.test.ts +107 -1
- package/src/agents-api.ts +12 -4
- package/src/openapi-schemas.ts +9 -2
- package/src/slack-config-token-resolve.unit.test.ts +108 -0
- package/src/slack-config-token.ts +51 -0
- package/src/slack-provisioning-service.integration.test.ts +189 -1
- package/src/slack-provisioning-service.ts +43 -9
- 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
|
@@ -28,6 +28,7 @@ interface AgentRow {
|
|
|
28
28
|
anthropicFederationRuleId?: string | null;
|
|
29
29
|
anthropicServiceAccountId?: string | null;
|
|
30
30
|
k8sServiceAccountName?: string | null;
|
|
31
|
+
accountId?: string | null;
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
/** Minimal in-memory Prisma double tracking whether the Agent row exists. */
|
|
@@ -47,6 +48,7 @@ class FakePrisma {
|
|
|
47
48
|
anthropicFederationRuleId: true;
|
|
48
49
|
anthropicServiceAccountId: true;
|
|
49
50
|
k8sServiceAccountName: true;
|
|
51
|
+
accountId: true;
|
|
50
52
|
};
|
|
51
53
|
}) => {
|
|
52
54
|
if (this.deleted || !this.row) return null;
|
|
@@ -56,6 +58,7 @@ class FakePrisma {
|
|
|
56
58
|
anthropicFederationRuleId: this.row.anthropicFederationRuleId ?? null,
|
|
57
59
|
anthropicServiceAccountId: this.row.anthropicServiceAccountId ?? null,
|
|
58
60
|
k8sServiceAccountName: this.row.k8sServiceAccountName ?? null,
|
|
61
|
+
accountId: this.row.accountId ?? null,
|
|
59
62
|
};
|
|
60
63
|
},
|
|
61
64
|
delete: async (_args: { where: { id: string } }): Promise<unknown> => {
|
|
@@ -97,6 +100,8 @@ function makeDeps(opts: {
|
|
|
97
100
|
}>;
|
|
98
101
|
/** Give the provisioner a removeAnthropicIdentity (absent by default). */
|
|
99
102
|
withIdentityRemoval?: boolean;
|
|
103
|
+
/** Stored Slack config token resolver (absent by default). */
|
|
104
|
+
slackConfigTokens?: DeleteAgentFullyDeps["slackConfigTokens"];
|
|
100
105
|
}): { deps: DeleteAgentFullyDeps; log: CallLog } {
|
|
101
106
|
const log: CallLog = {
|
|
102
107
|
deprovision: [],
|
|
@@ -160,6 +165,9 @@ function makeDeps(opts: {
|
|
|
160
165
|
},
|
|
161
166
|
// Identity decrypt: env values in these tests are stored "plaintext".
|
|
162
167
|
decrypt: (value) => value,
|
|
168
|
+
...(opts.slackConfigTokens
|
|
169
|
+
? { slackConfigTokens: opts.slackConfigTokens }
|
|
170
|
+
: {}),
|
|
163
171
|
};
|
|
164
172
|
|
|
165
173
|
return { deps, log };
|
|
@@ -348,6 +356,139 @@ describe("deleteAgentFully — Slack app without a token", () => {
|
|
|
348
356
|
});
|
|
349
357
|
});
|
|
350
358
|
|
|
359
|
+
// ─── Stored Slack config token (SCT-4.1) ─────────────────────────────────────
|
|
360
|
+
|
|
361
|
+
/** Fake resolver: `rows` are the scopes with a stored token. */
|
|
362
|
+
function fakeStored(rows: Array<string | null>, rejectFirst = false) {
|
|
363
|
+
const minted: Array<{ scope: string | null; token: string }> = [];
|
|
364
|
+
let rotations = 0;
|
|
365
|
+
const resolver = {
|
|
366
|
+
get: async (accountId: string | null) =>
|
|
367
|
+
rows.includes(accountId) ? { accountId } : null,
|
|
368
|
+
resolveForAccount: async (accountId: string) =>
|
|
369
|
+
rows.includes(accountId)
|
|
370
|
+
? { accountId }
|
|
371
|
+
: rows.includes(null)
|
|
372
|
+
? { accountId: null }
|
|
373
|
+
: null,
|
|
374
|
+
withSlackConfigAccessToken: async <T>(
|
|
375
|
+
scope: string | null,
|
|
376
|
+
fn: (t: string) => Promise<T>,
|
|
377
|
+
) => {
|
|
378
|
+
const first = `minted-${scope ?? "default"}-${++rotations}`;
|
|
379
|
+
minted.push({ scope, token: first });
|
|
380
|
+
try {
|
|
381
|
+
return await fn(first);
|
|
382
|
+
} catch (err) {
|
|
383
|
+
if (!rejectFirst) throw err;
|
|
384
|
+
const second = `minted-${scope ?? "default"}-${++rotations}`;
|
|
385
|
+
minted.push({ scope, token: second });
|
|
386
|
+
return fn(second);
|
|
387
|
+
}
|
|
388
|
+
},
|
|
389
|
+
} as unknown as DeleteAgentFullyDeps["slackConfigTokens"];
|
|
390
|
+
return { resolver, minted };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
describe("deleteAgentFully — stored Slack config token", () => {
|
|
394
|
+
const withApp = (accountId: string | null) =>
|
|
395
|
+
new FakePrisma({ ...AGENT, accountId }, [
|
|
396
|
+
{ key: "SLACK_APP_ID", value: "A777", secret: true },
|
|
397
|
+
]);
|
|
398
|
+
|
|
399
|
+
it("deletes the Slack app with a minted token when none is pasted", async () => {
|
|
400
|
+
const { resolver, minted } = fakeStored([null]);
|
|
401
|
+
const { deps, log } = makeDeps({
|
|
402
|
+
prisma: withApp("acct-1"),
|
|
403
|
+
slackConfigTokens: resolver,
|
|
404
|
+
});
|
|
405
|
+
const result = await deleteAgentFully(AGENT.id, deps);
|
|
406
|
+
expect(result.agentDeleted).toBe(true);
|
|
407
|
+
expect(result.completed).toContain("slack-app");
|
|
408
|
+
expect(result.manualStepsRequired.map((s) => s.key)).not.toContain(
|
|
409
|
+
"SLACK_APP_ID",
|
|
410
|
+
);
|
|
411
|
+
expect(log.slackDeleted).toEqual([
|
|
412
|
+
{ token: "minted-default-1", appId: "A777" },
|
|
413
|
+
]);
|
|
414
|
+
expect(minted).toHaveLength(1);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it("uses the account row over the default row", async () => {
|
|
418
|
+
const { resolver, minted } = fakeStored([null, "acct-1"]);
|
|
419
|
+
const { deps, log } = makeDeps({
|
|
420
|
+
prisma: withApp("acct-1"),
|
|
421
|
+
slackConfigTokens: resolver,
|
|
422
|
+
});
|
|
423
|
+
await deleteAgentFully(AGENT.id, deps);
|
|
424
|
+
expect(minted[0]?.scope).toBe("acct-1");
|
|
425
|
+
expect(log.slackDeleted[0]?.token).toBe("minted-acct-1-1");
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
it("a pasted token wins over the stored one", async () => {
|
|
429
|
+
const { resolver, minted } = fakeStored([null]);
|
|
430
|
+
const { deps, log } = makeDeps({
|
|
431
|
+
prisma: withApp(null),
|
|
432
|
+
slackConfigTokens: resolver,
|
|
433
|
+
});
|
|
434
|
+
await deleteAgentFully(AGENT.id, deps, { xoxpToken: "xoxp-paste" });
|
|
435
|
+
expect(log.slackDeleted).toEqual([{ token: "xoxp-paste", appId: "A777" }]);
|
|
436
|
+
expect(minted).toEqual([]);
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
it("keeps the manual step when neither a pasted nor a stored token exists", async () => {
|
|
440
|
+
const { resolver } = fakeStored([]);
|
|
441
|
+
const { deps, log } = makeDeps({
|
|
442
|
+
prisma: withApp("acct-1"),
|
|
443
|
+
slackConfigTokens: resolver,
|
|
444
|
+
});
|
|
445
|
+
const result = await deleteAgentFully(AGENT.id, deps);
|
|
446
|
+
expect(log.slackDeleted).toEqual([]);
|
|
447
|
+
expect(result.manualStepsRequired.map((s) => s.key)).toContain(
|
|
448
|
+
"SLACK_APP_ID",
|
|
449
|
+
);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("retries once with a rotated token when Slack reports token_revoked", async () => {
|
|
453
|
+
const { resolver } = fakeStored([null], true);
|
|
454
|
+
const prisma = withApp(null);
|
|
455
|
+
const { deps, log } = makeDeps({ prisma, slackConfigTokens: resolver });
|
|
456
|
+
let calls = 0;
|
|
457
|
+
deps.slack = {
|
|
458
|
+
deleteApp: async (token, appId) => {
|
|
459
|
+
log.slackDeleted.push({ token, appId });
|
|
460
|
+
if (++calls === 1)
|
|
461
|
+
throw new Error("Slack apps.manifest.delete failed: token_revoked");
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
const result = await deleteAgentFully(AGENT.id, deps);
|
|
465
|
+
expect(result.agentDeleted).toBe(true);
|
|
466
|
+
expect(log.slackDeleted.map((c) => c.token)).toEqual([
|
|
467
|
+
"minted-default-1",
|
|
468
|
+
"minted-default-2",
|
|
469
|
+
]);
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
it("records slack-app failed when minting the token fails", async () => {
|
|
473
|
+
const resolver = {
|
|
474
|
+
get: async () => ({ accountId: null }),
|
|
475
|
+
resolveForAccount: async () => ({ accountId: null }),
|
|
476
|
+
withSlackConfigAccessToken: async () => {
|
|
477
|
+
throw new Error("rotation failed");
|
|
478
|
+
},
|
|
479
|
+
} as unknown as DeleteAgentFullyDeps["slackConfigTokens"];
|
|
480
|
+
const { deps } = makeDeps({
|
|
481
|
+
prisma: withApp(null),
|
|
482
|
+
slackConfigTokens: resolver,
|
|
483
|
+
});
|
|
484
|
+
const result = await deleteAgentFully(AGENT.id, deps);
|
|
485
|
+
expect(result.agentDeleted).toBe(false);
|
|
486
|
+
expect(result.failed).toEqual([
|
|
487
|
+
{ step: "slack-app", error: "rotation failed" },
|
|
488
|
+
]);
|
|
489
|
+
});
|
|
490
|
+
});
|
|
491
|
+
|
|
351
492
|
// ─── Edge: unknown agent ─────────────────────────────────────────────────────
|
|
352
493
|
|
|
353
494
|
describe("deleteAgentFully — unknown agent", () => {
|
|
@@ -175,6 +175,7 @@ function serialize(t: TemplateView) {
|
|
|
175
175
|
key: i.key,
|
|
176
176
|
payload: i.payload,
|
|
177
177
|
updatedAt: i.updatedAt.toISOString(),
|
|
178
|
+
...(i.managedBy ? { managedBy: i.managedBy } : {}),
|
|
178
179
|
})),
|
|
179
180
|
createdAt: t.createdAt.toISOString(),
|
|
180
181
|
updatedAt: t.updatedAt.toISOString(),
|
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);
|
|
@@ -24,11 +24,11 @@ import type { AgentTokenService } from "./agent-tokens.ts";
|
|
|
24
24
|
import type { AdminDeps } from "./agents-api.ts";
|
|
25
25
|
import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
|
|
26
26
|
import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
|
|
27
|
+
import { accessFor, envWith } from "./github-installation.fixtures.ts";
|
|
27
28
|
import {
|
|
28
29
|
createGithubInstallationRepos,
|
|
29
30
|
createGithubSync,
|
|
30
31
|
} from "./github-installation-wiring.ts";
|
|
31
|
-
import { accessFor, envWith } from "./github-installation.fixtures.ts";
|
|
32
32
|
import type { OpenWorkPort } from "./reconcile-open-work.ts";
|
|
33
33
|
import {
|
|
34
34
|
repoLostAccessBlockReason,
|
|
@@ -2162,6 +2162,112 @@ describe("admin API — delete agent", () => {
|
|
|
2162
2162
|
expect(slackCalls).toEqual([{ token: "xoxp-user-token", appId: "A123" }]);
|
|
2163
2163
|
});
|
|
2164
2164
|
|
|
2165
|
+
describe("DELETE /agents/:id with a stored Slack config token (SCT-4.1)", () => {
|
|
2166
|
+
const setup = (opts: {
|
|
2167
|
+
rejectFirst?: boolean;
|
|
2168
|
+
accountId?: string | null;
|
|
2169
|
+
}) => {
|
|
2170
|
+
const slackCalls: Array<{ token: string; appId: string }> = [];
|
|
2171
|
+
const mintedFor: Array<string | null> = [];
|
|
2172
|
+
let n = 0;
|
|
2173
|
+
const slackConfigTokens = {
|
|
2174
|
+
get: async (a: string | null) =>
|
|
2175
|
+
a === null ? { accountId: null } : null,
|
|
2176
|
+
resolveForAccount: async (a: string) =>
|
|
2177
|
+
a === "acct-1" ? { accountId: "acct-1" } : { accountId: null },
|
|
2178
|
+
withSlackConfigAccessToken: async <T>(
|
|
2179
|
+
scope: string | null,
|
|
2180
|
+
fn: (t: string) => Promise<T>,
|
|
2181
|
+
) => {
|
|
2182
|
+
mintedFor.push(scope);
|
|
2183
|
+
try {
|
|
2184
|
+
return await fn(`minted-${++n}`);
|
|
2185
|
+
} catch (err) {
|
|
2186
|
+
if (!/token_revoked/.test(String(err))) throw err;
|
|
2187
|
+
mintedFor.push(scope);
|
|
2188
|
+
return fn(`minted-${++n}`);
|
|
2189
|
+
}
|
|
2190
|
+
},
|
|
2191
|
+
} as unknown as NonNullable<AdminDeps["slackConfigTokens"]>;
|
|
2192
|
+
const base = makeMockDeps();
|
|
2193
|
+
const deps: AdminDeps = {
|
|
2194
|
+
...base,
|
|
2195
|
+
prisma: {
|
|
2196
|
+
...base.prisma,
|
|
2197
|
+
agent: {
|
|
2198
|
+
...base.prisma.agent,
|
|
2199
|
+
findUnique: async () => ({
|
|
2200
|
+
id: AGENT_ID,
|
|
2201
|
+
name: "Test Agent",
|
|
2202
|
+
accountId: opts.accountId ?? null,
|
|
2203
|
+
}),
|
|
2204
|
+
},
|
|
2205
|
+
agentEnv: {
|
|
2206
|
+
findMany: async () => [
|
|
2207
|
+
{ key: "SLACK_APP_ID", value: "A123", secret: true },
|
|
2208
|
+
],
|
|
2209
|
+
},
|
|
2210
|
+
} as unknown as AdminDeps["prisma"],
|
|
2211
|
+
slack: {
|
|
2212
|
+
deleteApp: async (token: string, appId: string) => {
|
|
2213
|
+
slackCalls.push({ token, appId });
|
|
2214
|
+
if (opts.rejectFirst && slackCalls.length === 1) {
|
|
2215
|
+
throw new Error(
|
|
2216
|
+
"Slack apps.manifest.delete failed: token_revoked",
|
|
2217
|
+
);
|
|
2218
|
+
}
|
|
2219
|
+
},
|
|
2220
|
+
},
|
|
2221
|
+
slackConfigTokens,
|
|
2222
|
+
};
|
|
2223
|
+
return { app: createAdminApp(deps), slackCalls, mintedFor };
|
|
2224
|
+
};
|
|
2225
|
+
const del = async (
|
|
2226
|
+
app: ReturnType<typeof createAdminApp>,
|
|
2227
|
+
body?: Record<string, string>,
|
|
2228
|
+
) => {
|
|
2229
|
+
const cookie = await makeSessionCookie();
|
|
2230
|
+
return app.request(`/agents/${AGENT_ID}`, {
|
|
2231
|
+
method: "DELETE",
|
|
2232
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
2233
|
+
headers: {
|
|
2234
|
+
...(body ? { "Content-Type": "application/json" } : {}),
|
|
2235
|
+
Cookie: `admin_session=${cookie}`,
|
|
2236
|
+
},
|
|
2237
|
+
});
|
|
2238
|
+
};
|
|
2239
|
+
|
|
2240
|
+
it("no body → the Slack app is deleted with a minted token", async () => {
|
|
2241
|
+
const { app, slackCalls } = setup({});
|
|
2242
|
+
const res = await del(app);
|
|
2243
|
+
const body = await res.json();
|
|
2244
|
+
expect(body.agentDeleted).toBe(true);
|
|
2245
|
+
expect(body.completed).toContain("slack-app");
|
|
2246
|
+
expect(body.manualStepsRequired).toEqual([]);
|
|
2247
|
+
expect(slackCalls).toEqual([{ token: "minted-1", appId: "A123" }]);
|
|
2248
|
+
});
|
|
2249
|
+
|
|
2250
|
+
it("the agent's account row is used (not the default)", async () => {
|
|
2251
|
+
const { app, mintedFor } = setup({ accountId: "acct-1" });
|
|
2252
|
+
await del(app);
|
|
2253
|
+
expect(mintedFor).toEqual(["acct-1"]);
|
|
2254
|
+
});
|
|
2255
|
+
|
|
2256
|
+
it("a pasted xoxpToken wins over the stored token", async () => {
|
|
2257
|
+
const { app, slackCalls, mintedFor } = setup({});
|
|
2258
|
+
await del(app, { xoxpToken: "xoxp-user-token" });
|
|
2259
|
+
expect(slackCalls).toEqual([{ token: "xoxp-user-token", appId: "A123" }]);
|
|
2260
|
+
expect(mintedFor).toEqual([]);
|
|
2261
|
+
});
|
|
2262
|
+
|
|
2263
|
+
it("token_revoked → one forced rotate + retry, deletion succeeds", async () => {
|
|
2264
|
+
const { app, slackCalls } = setup({ rejectFirst: true });
|
|
2265
|
+
const body = await (await del(app)).json();
|
|
2266
|
+
expect(body.agentDeleted).toBe(true);
|
|
2267
|
+
expect(slackCalls.map((c) => c.token)).toEqual(["minted-1", "minted-2"]);
|
|
2268
|
+
});
|
|
2269
|
+
});
|
|
2270
|
+
|
|
2165
2271
|
it("DELETE /agents/:id unknown id → 404 (no deprovision)", async () => {
|
|
2166
2272
|
const cookie = await makeSessionCookie();
|
|
2167
2273
|
const provisioner = new RecordingProvisioner();
|
package/src/agents-api.ts
CHANGED
|
@@ -61,13 +61,13 @@ import { deleteAgentFully } from "./agent-deletion.ts";
|
|
|
61
61
|
import type { AgentEnvService } from "./agent-envs.ts";
|
|
62
62
|
import type { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
|
|
63
63
|
import { AgentMarketplaceService } from "./agent-marketplaces.ts";
|
|
64
|
-
import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
|
|
65
64
|
import type { AgentMemberService } from "./agent-members.ts";
|
|
66
65
|
import type { AgentPluginService } from "./agent-plugins.ts";
|
|
67
66
|
import {
|
|
68
67
|
type AgentProvisioner,
|
|
69
68
|
hasPerAgentIdentity,
|
|
70
69
|
} from "./agent-provisioner.ts";
|
|
70
|
+
import { AGENT_TEMPLATE_ITEM_KINDS } from "./agent-template-items.ts";
|
|
71
71
|
import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
|
|
72
72
|
import type { AgentTokenService } from "./agent-tokens.ts";
|
|
73
73
|
import type { AgentToolService } from "./agent-tools.ts";
|
|
@@ -111,7 +111,9 @@ import {
|
|
|
111
111
|
UnprocessableEntityError,
|
|
112
112
|
} from "./errors.ts";
|
|
113
113
|
import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
114
|
+
import type { GithubSyncService } from "./github-sync.ts";
|
|
114
115
|
import { normalizeGithubUsername } from "./github-username.ts";
|
|
116
|
+
import type { InstallationReposService } from "./installation-repos-service.ts";
|
|
115
117
|
import {
|
|
116
118
|
AddAgentReposBodySchema,
|
|
117
119
|
AgentChatTokenUsageDailySchema,
|
|
@@ -167,8 +169,6 @@ import {
|
|
|
167
169
|
UpsertAgentMarketplaceBodySchema,
|
|
168
170
|
UpsertChatTokenDailyBodySchema,
|
|
169
171
|
} from "./openapi-schemas.ts";
|
|
170
|
-
import type { InstallationReposService } from "./installation-repos-service.ts";
|
|
171
|
-
import type { GithubSyncService } from "./github-sync.ts";
|
|
172
172
|
import type { OpenWorkPort } from "./reconcile-open-work.ts";
|
|
173
173
|
import {
|
|
174
174
|
blockRepoRemovalWork,
|
|
@@ -327,6 +327,12 @@ export interface AdminDeps {
|
|
|
327
327
|
chatService: DeleteAgentFullyDeps["chatService"];
|
|
328
328
|
slack: DeleteAgentFullyDeps["slack"];
|
|
329
329
|
decrypt: DeleteAgentFullyDeps["decrypt"];
|
|
330
|
+
/**
|
|
331
|
+
* Optional stored Slack config token resolver (SCT-4.1; additive). When set,
|
|
332
|
+
* DELETE /agents/:id deletes the Slack app with a minted token if no
|
|
333
|
+
* xoxpToken is supplied. Absent keeps the paste-only behavior.
|
|
334
|
+
*/
|
|
335
|
+
slackConfigTokens?: DeleteAgentFullyDeps["slackConfigTokens"];
|
|
330
336
|
sessionSecret: string;
|
|
331
337
|
/** Parsed SHIPWRIGHT_ADMIN_API_KEYS — optional; absent means env key auth is disabled. */
|
|
332
338
|
adminApiKeys?: Map<string, AdminApiKey>;
|
|
@@ -960,7 +966,7 @@ const deleteAgentRoute = createRoute({
|
|
|
960
966
|
path: "/agents/{id}",
|
|
961
967
|
summary: "Delete an agent",
|
|
962
968
|
description:
|
|
963
|
-
"Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
|
|
969
|
+
"Admin-only. Runs the full deleteAgentFully() teardown: deprovisions the K8s workload, removes the agent's per-agent Anthropic identity when it has one (federation rule, then Anthropic service account, then Kubernetes ServiceAccount), revokes task-store and chat-service tokens, deletes chat threads, and — if an `xoxpToken` is supplied, or a stored Slack config token resolves for the agent's account (else the deployment default) — deletes the Slack app. The Agent row (and its cascade-deleted child records) is deleted last, only if every automatable step succeeded; `agentDeleted: false` means the row was preserved and the call is safe to retry.",
|
|
964
970
|
request: {
|
|
965
971
|
params: AgentIdParamSchema,
|
|
966
972
|
body: {
|
|
@@ -2089,6 +2095,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
|
|
|
2089
2095
|
chatService,
|
|
2090
2096
|
slack,
|
|
2091
2097
|
decrypt,
|
|
2098
|
+
slackConfigTokens,
|
|
2092
2099
|
sessionSecret,
|
|
2093
2100
|
adminApiKeys,
|
|
2094
2101
|
sentryClient,
|
|
@@ -2556,6 +2563,7 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
|
|
|
2556
2563
|
chatService,
|
|
2557
2564
|
slack,
|
|
2558
2565
|
decrypt,
|
|
2566
|
+
...(slackConfigTokens ? { slackConfigTokens } : {}),
|
|
2559
2567
|
},
|
|
2560
2568
|
{ xoxpToken: body?.xoxpToken },
|
|
2561
2569
|
);
|
package/src/openapi-schemas.ts
CHANGED
|
@@ -207,8 +207,10 @@ export const CreateAgentBodySchema = z
|
|
|
207
207
|
|
|
208
208
|
/**
|
|
209
209
|
* DELETE /agents/:id request body. Entirely optional — omit it (or the
|
|
210
|
-
* xoxpToken field) to
|
|
211
|
-
*
|
|
210
|
+
* xoxpToken field) to use the stored Slack config token when one resolves for
|
|
211
|
+
* the agent's account (else the deployment default). With neither a pasted nor
|
|
212
|
+
* a stored token, a present Slack app becomes a manual checklist entry instead
|
|
213
|
+
* of a hard failure. A pasted xoxpToken wins over the stored token.
|
|
212
214
|
*/
|
|
213
215
|
export const DeleteAgentBodySchema = z
|
|
214
216
|
.object({
|
|
@@ -1598,6 +1600,11 @@ export const TemplateItemSchema = TemplateItemBaseSchema.extend({
|
|
|
1598
1600
|
.string()
|
|
1599
1601
|
.datetime()
|
|
1600
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
|
+
}),
|
|
1601
1608
|
}).openapi("TemplateItem");
|
|
1602
1609
|
|
|
1603
1610
|
export const AgentTemplateSchema = z
|