@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,108 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ hasStoredSlackConfigToken,
4
+ type SlackConfigTokenResolver,
5
+ withSlackConfigToken,
6
+ } from "./slack-config-token.ts";
7
+
8
+ interface Row {
9
+ accountId: string | null;
10
+ }
11
+
12
+ /** Fake resolver: rows by scope; records which scope minted tokens. */
13
+ function fake(rows: Row[]) {
14
+ const used: Array<string | null> = [];
15
+ const resolver = {
16
+ get: async (accountId: string | null) =>
17
+ rows.find((r) => r.accountId === accountId) ?? null,
18
+ resolveForAccount: async (accountId: string) =>
19
+ rows.find((r) => r.accountId === accountId) ??
20
+ rows.find((r) => r.accountId === null) ??
21
+ null,
22
+ withSlackConfigAccessToken: async <T>(
23
+ accountId: string | null,
24
+ fn: (t: string) => Promise<T>,
25
+ ) => {
26
+ used.push(accountId);
27
+ return fn(`minted-${accountId ?? "default"}`);
28
+ },
29
+ } as unknown as SlackConfigTokenResolver;
30
+ return { resolver, used };
31
+ }
32
+
33
+ describe("hasStoredSlackConfigToken", () => {
34
+ test("false without a resolver or rows", async () => {
35
+ expect(await hasStoredSlackConfigToken(undefined, "a1")).toBe(false);
36
+ expect(await hasStoredSlackConfigToken(fake([]).resolver, "a1")).toBe(
37
+ false,
38
+ );
39
+ });
40
+ test("true for the account row, the default row, and null account + default", async () => {
41
+ expect(
42
+ await hasStoredSlackConfigToken(
43
+ fake([{ accountId: "a1" }]).resolver,
44
+ "a1",
45
+ ),
46
+ ).toBe(true);
47
+ expect(
48
+ await hasStoredSlackConfigToken(
49
+ fake([{ accountId: null }]).resolver,
50
+ "a1",
51
+ ),
52
+ ).toBe(true);
53
+ expect(
54
+ await hasStoredSlackConfigToken(
55
+ fake([{ accountId: null }]).resolver,
56
+ null,
57
+ ),
58
+ ).toBe(true);
59
+ expect(
60
+ await hasStoredSlackConfigToken(
61
+ fake([{ accountId: "a1" }]).resolver,
62
+ null,
63
+ ),
64
+ ).toBe(false);
65
+ });
66
+ });
67
+
68
+ describe("withSlackConfigToken", () => {
69
+ test("a pasted token wins and never touches the resolver", async () => {
70
+ const { resolver, used } = fake([{ accountId: "a1" }]);
71
+ const got = await withSlackConfigToken(
72
+ resolver,
73
+ { pasted: " xoxe.xoxp-paste ", accountId: "a1" },
74
+ async (t) => t,
75
+ );
76
+ expect(got).toBe("xoxe.xoxp-paste");
77
+ expect(used).toEqual([]);
78
+ });
79
+ test("account row overrides the default row", async () => {
80
+ const { resolver, used } = fake([{ accountId: null }, { accountId: "a1" }]);
81
+ const got = await withSlackConfigToken(
82
+ resolver,
83
+ { accountId: "a1" },
84
+ async (t) => t,
85
+ );
86
+ expect(got).toBe("minted-a1");
87
+ expect(used).toEqual(["a1"]);
88
+ });
89
+ test("falls back to the default row", async () => {
90
+ const { resolver, used } = fake([{ accountId: null }]);
91
+ expect(
92
+ await withSlackConfigToken(resolver, { accountId: "a9" }, async (t) => t),
93
+ ).toBe("minted-default");
94
+ expect(used).toEqual([null]);
95
+ });
96
+ test("throws when nothing resolves", async () => {
97
+ await expect(
98
+ withSlackConfigToken(
99
+ fake([]).resolver,
100
+ { accountId: "a1" },
101
+ async (t) => t,
102
+ ),
103
+ ).rejects.toThrow(/No .*Slack config token/);
104
+ await expect(
105
+ withSlackConfigToken(undefined, {}, async (t) => t),
106
+ ).rejects.toThrow(/No .*Slack config token/);
107
+ });
108
+ });
@@ -431,3 +431,54 @@ export class SlackConfigTokenService {
431
431
  return crypto.decrypt(row.accessTokenEncrypted);
432
432
  }
433
433
  }
434
+
435
+ /**
436
+ * The slice of SlackConfigTokenService the create / connect / sync / delete
437
+ * flows need. Flows take it as an optional dependency: absent means no stored
438
+ * token and today's paste-only behavior.
439
+ */
440
+ export type SlackConfigTokenResolver = Pick<
441
+ SlackConfigTokenService,
442
+ "get" | "resolveForAccount" | "withSlackConfigAccessToken"
443
+ >;
444
+
445
+ async function resolveStoredScope(
446
+ resolver: SlackConfigTokenResolver | undefined,
447
+ accountId: string | null | undefined,
448
+ ): Promise<SlackConfigTokenMetadata | null> {
449
+ if (!resolver) return null;
450
+ return accountId ? resolver.resolveForAccount(accountId) : resolver.get(null);
451
+ }
452
+
453
+ /**
454
+ * True when a stored config token applies to this account: its own row, else
455
+ * the deployment-wide default row (a null account only sees the default).
456
+ */
457
+ export async function hasStoredSlackConfigToken(
458
+ resolver: SlackConfigTokenResolver | undefined,
459
+ accountId: string | null | undefined,
460
+ ): Promise<boolean> {
461
+ return (await resolveStoredScope(resolver, accountId)) !== null;
462
+ }
463
+
464
+ /**
465
+ * Run `fn` with a Slack config token: a pasted token wins (used as-is, no
466
+ * retry); otherwise mint an access token from the account's stored row, else
467
+ * the default row, with the revoked-token retry-once of
468
+ * withSlackConfigAccessToken. Throws SlackConfigTokenNotConfiguredError when
469
+ * neither exists, so callers check hasStoredSlackConfigToken() first when they
470
+ * have a paste-only fallback.
471
+ */
472
+ export async function withSlackConfigToken<T>(
473
+ resolver: SlackConfigTokenResolver | undefined,
474
+ opts: { pasted?: string | undefined; accountId?: string | null | undefined },
475
+ fn: (token: string) => Promise<T>,
476
+ ): Promise<T> {
477
+ const pasted = opts.pasted?.trim();
478
+ if (pasted) return fn(pasted);
479
+ const row = await resolveStoredScope(resolver, opts.accountId);
480
+ if (!row || !resolver) {
481
+ throw new SlackConfigTokenNotConfiguredError(opts.accountId ?? null);
482
+ }
483
+ return resolver.withSlackConfigAccessToken(row.accountId, fn);
484
+ }
@@ -14,8 +14,12 @@ import { readFileSync } from "node:fs";
14
14
  import { sign } from "hono/jwt";
15
15
  import type { AdminUISlackClient } from "./admin-ui.ts";
16
16
  import type { AgentDetail } from "./agents.ts";
17
- import { SlackProvisioningService } from "./slack-provisioning-service.ts";
17
+ import {
18
+ isSlackConfigTokenRevokedError,
19
+ type SlackConfigTokenResolver,
20
+ } from "./slack-config-token.ts";
18
21
  import type { AppManifest } from "./slack-provisioning-client.ts";
22
+ import { SlackProvisioningService } from "./slack-provisioning-service.ts";
19
23
 
20
24
  // ─── Constants ────────────────────────────────────────────────────────────────
21
25
 
@@ -120,6 +124,7 @@ function makeService(opts?: {
120
124
  allowedTools: string[];
121
125
  } | null>;
122
126
  getDetail?: () => Promise<AgentDetail | null>;
127
+ slackConfigTokens?: SlackConfigTokenResolver;
123
128
  }): SlackProvisioningService {
124
129
  const patchCalls = opts?.patchCalls ?? [];
125
130
  const reconcileCalls = opts?.reconcileCalls ?? [];
@@ -184,9 +189,76 @@ function makeService(opts?: {
184
189
  sessionSecret: SESSION_SECRET,
185
190
  appBaseUrl: APP_BASE_URL,
186
191
  secretEnvVars: new Set(["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"]),
192
+ ...(opts?.slackConfigTokens
193
+ ? { slackConfigTokens: opts.slackConfigTokens }
194
+ : {}),
187
195
  });
188
196
  }
189
197
 
198
+ /** Records the token each createAppManifest call received; can reject the first. */
199
+ class TokenRecordingSlackClient extends RecordedSlackClient {
200
+ readonly tokens: string[] = [];
201
+ constructor(private readonly rejectFirstWith?: string) {
202
+ super(CASSETTE_PATH);
203
+ }
204
+ override async createAppManifest(xoxpToken: string, manifest: AppManifest) {
205
+ this.tokens.push(xoxpToken);
206
+ if (this.rejectFirstWith && this.tokens.length === 1) {
207
+ throw new Error(
208
+ `Slack apps.manifest.create failed: ${this.rejectFirstWith}`,
209
+ );
210
+ }
211
+ return super.createAppManifest(xoxpToken, manifest);
212
+ }
213
+ }
214
+
215
+ /** Stored-token resolver double: `scopes` are the rows that exist; mints sequential tokens. */
216
+ function makeStoredResolver(scopes: Array<string | null>) {
217
+ const mintedFor: Array<string | null> = [];
218
+ let n = 0;
219
+ const resolver = {
220
+ get: async (a: string | null) =>
221
+ scopes.includes(a) ? { accountId: a } : null,
222
+ resolveForAccount: async (a: string) =>
223
+ scopes.includes(a)
224
+ ? { accountId: a }
225
+ : scopes.includes(null)
226
+ ? { accountId: null }
227
+ : null,
228
+ withSlackConfigAccessToken: async <T>(
229
+ scope: string | null,
230
+ fn: (t: string) => Promise<T>,
231
+ ) => {
232
+ mintedFor.push(scope);
233
+ try {
234
+ return await fn(`minted-${++n}`);
235
+ } catch (err) {
236
+ if (!isSlackConfigTokenRevokedError(err)) throw err;
237
+ mintedFor.push(scope);
238
+ return fn(`minted-${++n}`);
239
+ }
240
+ },
241
+ } as unknown as SlackConfigTokenResolver;
242
+ return { resolver, mintedFor };
243
+ }
244
+
245
+ const agentInAccount = (accountId: string | null) => async () =>
246
+ ({
247
+ id: AGENT_ID,
248
+ name: "Test Agent",
249
+ accountId,
250
+ slackId: null,
251
+ selfHosted: false,
252
+ createdAt: new Date("2024-01-01"),
253
+ updatedAt: new Date("2024-01-01"),
254
+ repos: [],
255
+ reviewAuthorAllowlist: [],
256
+ patchAuthorAllowlist: [],
257
+ restrictSlackToMembers: false,
258
+ specialty: "coding",
259
+ missingRequiredEnv: [],
260
+ }) as unknown as AgentDetail;
261
+
190
262
  async function makeProvisionStateToken(
191
263
  overrides: Partial<{
192
264
  agentId: string;
@@ -355,6 +427,122 @@ describe("SlackProvisioningService.startConnect", () => {
355
427
  });
356
428
  });
357
429
 
430
+ describe("SlackProvisioningService.startConnect — stored Slack config token", () => {
431
+ it("no pasted token + stored default row → mints a token and creates the app", async () => {
432
+ const client = new TokenRecordingSlackClient();
433
+ const { resolver, mintedFor } = makeStoredResolver([null]);
434
+ const service = makeService({
435
+ slackClient: client,
436
+ getDetail: agentInAccount("acct-1"),
437
+ slackConfigTokens: resolver,
438
+ });
439
+ const result = await service.startConnect(
440
+ AGENT_ID,
441
+ undefined,
442
+ CONNECT_SLACK_CALLBACK,
443
+ );
444
+ expect(result.ok).toBe(true);
445
+ expect(client.tokens).toEqual(["minted-1"]);
446
+ expect(mintedFor).toEqual([null]);
447
+ });
448
+
449
+ it("account row overrides the default row", async () => {
450
+ const { resolver, mintedFor } = makeStoredResolver([null, "acct-1"]);
451
+ const service = makeService({
452
+ slackClient: new TokenRecordingSlackClient(),
453
+ getDetail: agentInAccount("acct-1"),
454
+ slackConfigTokens: resolver,
455
+ });
456
+ await service.startConnect(AGENT_ID, "", CONNECT_SLACK_CALLBACK);
457
+ expect(mintedFor).toEqual(["acct-1"]);
458
+ });
459
+
460
+ it("a pasted token wins and the resolver is not used", async () => {
461
+ const client = new TokenRecordingSlackClient();
462
+ const { resolver, mintedFor } = makeStoredResolver([null]);
463
+ const service = makeService({
464
+ slackClient: client,
465
+ slackConfigTokens: resolver,
466
+ });
467
+ const result = await service.startConnect(
468
+ AGENT_ID,
469
+ "xoxe.xoxp-1-pasted",
470
+ CONNECT_SLACK_CALLBACK,
471
+ );
472
+ expect(result.ok).toBe(true);
473
+ expect(client.tokens).toEqual(["xoxe.xoxp-1-pasted"]);
474
+ expect(mintedFor).toEqual([]);
475
+ });
476
+
477
+ it("a pasted token still needs the xoxe.xoxp- prefix even when a stored token exists", async () => {
478
+ const client = new TokenRecordingSlackClient();
479
+ const { resolver } = makeStoredResolver([null]);
480
+ const service = makeService({
481
+ slackClient: client,
482
+ slackConfigTokens: resolver,
483
+ });
484
+ const result = await service.startConnect(
485
+ AGENT_ID,
486
+ "xoxb-nope",
487
+ CONNECT_SLACK_CALLBACK,
488
+ );
489
+ expect(result.ok).toBe(false);
490
+ expect(client.tokens).toEqual([]);
491
+ });
492
+
493
+ it("neither pasted nor stored → today's prefix error", async () => {
494
+ const { resolver } = makeStoredResolver([]);
495
+ const service = makeService({ slackConfigTokens: resolver });
496
+ const result = await service.startConnect(
497
+ AGENT_ID,
498
+ undefined,
499
+ CONNECT_SLACK_CALLBACK,
500
+ );
501
+ expect(result.ok).toBe(false);
502
+ if (result.ok) throw new Error("expected error result");
503
+ expect(result.error).toContain("xoxe.xoxp-");
504
+ });
505
+
506
+ it("token_revoked on the manifest call → one forced rotate + retry succeeds", async () => {
507
+ const client = new TokenRecordingSlackClient("token_revoked");
508
+ const { resolver, mintedFor } = makeStoredResolver([null]);
509
+ const service = makeService({
510
+ slackClient: client,
511
+ slackConfigTokens: resolver,
512
+ });
513
+ const result = await service.startConnect(
514
+ AGENT_ID,
515
+ undefined,
516
+ CONNECT_SLACK_CALLBACK,
517
+ );
518
+ expect(result.ok).toBe(true);
519
+ expect(client.tokens).toEqual(["minted-1", "minted-2"]);
520
+ expect(mintedFor).toHaveLength(2);
521
+ });
522
+
523
+ it("createAppManifest (legacy wizard) mints a token when none is pasted, and prefers a pasted one", async () => {
524
+ const client = new TokenRecordingSlackClient();
525
+ const { resolver } = makeStoredResolver([null]);
526
+ const service = makeService({
527
+ slackClient: client,
528
+ slackConfigTokens: resolver,
529
+ });
530
+ await service.createAppManifest(
531
+ "wiz",
532
+ undefined,
533
+ LEGACY_PROVISION_COMPLETE,
534
+ null,
535
+ );
536
+ await service.createAppManifest(
537
+ "wiz",
538
+ "xoxe.xoxp-1-p",
539
+ LEGACY_PROVISION_COMPLETE,
540
+ null,
541
+ );
542
+ expect(client.tokens).toEqual(["minted-1", "xoxe.xoxp-1-p"]);
543
+ });
544
+ });
545
+
358
546
  describe("SlackProvisioningService.completeConnect", () => {
359
547
  it("valid state token + code → exchanges OAuth code (cassette) and stores SLACK_BOT_TOKEN, returns needs_app_token", async () => {
360
548
  const patchCalls: PatchCall[] = [];
@@ -21,6 +21,11 @@ import type { AdminUISlackClient } from "./admin-ui.ts";
21
21
  import type { AgentCronJobService } from "./agent-cron-jobs.ts";
22
22
  import type { AgentEnvService } from "./agent-envs.ts";
23
23
  import type { AgentService } from "./agents.ts";
24
+ import {
25
+ hasStoredSlackConfigToken,
26
+ type SlackConfigTokenResolver,
27
+ withSlackConfigToken,
28
+ } from "./slack-config-token.ts";
24
29
  import { buildAgentManifest } from "./slack-provisioning-client.ts";
25
30
 
26
31
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -115,6 +120,12 @@ interface SlackProvisioningServiceDeps {
115
120
  appBaseUrl: string;
116
121
  /** Env var keys that must be stored as secrets — mirrors SECRET_ENV_VARS. */
117
122
  secretEnvVars: Set<string>;
123
+ /**
124
+ * Optional stored Slack config token resolver (SCT-4.1). When present, a
125
+ * token minted from the agent's account row (else the default row) is used
126
+ * whenever no xoxpToken was pasted. Absent keeps the paste-only behavior.
127
+ */
128
+ slackConfigTokens?: SlackConfigTokenResolver;
118
129
  }
119
130
 
120
131
  // ─── Service ──────────────────────────────────────────────────────────────────
@@ -142,11 +153,23 @@ export class SlackProvisioningService {
142
153
  */
143
154
  async createAppManifest(
144
155
  agentName: string,
145
- xoxpToken: string,
156
+ xoxpToken: string | undefined,
146
157
  redirectUri: string,
158
+ /**
159
+ * Account whose stored Slack config token applies when `xoxpToken` is
160
+ * absent (its own row, else the deployment-wide default). Ignored when a
161
+ * token was pasted.
162
+ */
163
+ accountId?: string | null,
147
164
  ): Promise<SlackAppManifestResult> {
148
165
  const manifest = buildAgentManifest(agentName, redirectUri);
149
- return this.deps.slackClient.createAppManifest(xoxpToken, manifest);
166
+ // A pasted token wins (no retry); a stored one is minted per call, with one
167
+ // forced rotate + retry if Slack reports token_revoked / invalid_auth.
168
+ return withSlackConfigToken(
169
+ this.deps.slackConfigTokens,
170
+ { pasted: xoxpToken, accountId },
171
+ (token) => this.deps.slackClient.createAppManifest(token, manifest),
172
+ );
150
173
  }
151
174
 
152
175
  /**
@@ -213,24 +236,35 @@ export class SlackProvisioningService {
213
236
  redirectUri: string,
214
237
  ghConnectError?: string,
215
238
  ): Promise<StartConnectResult> {
216
- if (!xoxpToken?.startsWith("xoxe.xoxp-")) {
217
- return {
218
- ok: false,
219
- error: "Slack app configuration token must start with xoxe.xoxp-",
220
- };
221
- }
239
+ const prefixError = {
240
+ ok: false,
241
+ error: "Slack app configuration token must start with xoxe.xoxp-",
242
+ } as const;
243
+ // A pasted token must be well-formed; the prefix check never applies to a
244
+ // minted token. Without a resolver this is the original up-front check.
245
+ const pasted = xoxpToken?.trim() || undefined;
246
+ if (pasted && !pasted.startsWith("xoxe.xoxp-")) return prefixError;
247
+ if (!pasted && !this.deps.slackConfigTokens) return prefixError;
222
248
 
223
249
  const agent = await this.deps.agentService.getDetail(agentId);
224
250
  if (!agent) {
225
251
  return { ok: false, error: "Agent not found." };
226
252
  }
253
+ const accountId = agent.accountId ?? null;
254
+ if (
255
+ !pasted &&
256
+ !(await hasStoredSlackConfigToken(this.deps.slackConfigTokens, accountId))
257
+ ) {
258
+ return prefixError;
259
+ }
227
260
 
228
261
  let slackResult: SlackAppManifestResult;
229
262
  try {
230
263
  slackResult = await this.createAppManifest(
231
264
  agent.name,
232
- xoxpToken,
265
+ pasted,
233
266
  redirectUri,
267
+ accountId,
234
268
  );
235
269
  } catch (err) {
236
270
  const msg =