@app-vitals/agent-admin 1.63.0 → 1.65.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,251 @@
1
+ /**
2
+ * admin/src/admin-ui-slack-config-token.ts
3
+ * GET/POST /admin/settings/slack-config-token — Settings > Slack config token
4
+ * (SCT-3.1). A thin UI over SlackConfigTokenService, scoped like the Templates
5
+ * editor: platform admins manage the deployment-wide row and any account's row
6
+ * (?accountId=); account owners manage only their own account's row; plain
7
+ * members, ownerless callers and other accounts get 403.
8
+ *
9
+ * Neither the rendered HTML nor any redirect URL carries token material: the
10
+ * pasted refresh token is validated by rotating it once, the rotated pair goes
11
+ * straight to the service, and only metadata is read back.
12
+ */
13
+
14
+ import type { Context, Hono, MiddlewareHandler } from "hono";
15
+ import { accountIdFromScope } from "./account-agent-create.ts";
16
+ import type { AccountMemberService } from "./account-members.ts";
17
+ import type { AccountService } from "./accounts.ts";
18
+ import type { AdminUIEnv } from "./admin-ui.ts";
19
+ import type { SettingsNav } from "./admin-ui-settings-layout.ts";
20
+ import {
21
+ ADMIN_SLACK_CONFIG_TOKEN_PATH as BASE,
22
+ renderSlackConfigTokenPage,
23
+ type SlackConfigTokenScopeOption,
24
+ } from "./admin-ui-slack-config-token-pages.ts";
25
+ import type { CallerScopeResolver } from "./caller-scope.ts";
26
+ import {
27
+ ApiError,
28
+ ForbiddenError,
29
+ UnprocessableEntityError,
30
+ } from "./errors.ts";
31
+ import type { SlackConfigTokenService } from "./slack-config-token.ts";
32
+ import type { SlackConfigTokenClient } from "./slack-provisioning-client.ts";
33
+
34
+ export interface AdminSlackConfigTokenRouteDeps {
35
+ requireAuth: MiddlewareHandler<AdminUIEnv>;
36
+ tokens: Pick<
37
+ SlackConfigTokenService,
38
+ "get" | "save" | "clear" | "getAccessToken"
39
+ >;
40
+ /** tooling.tokens.rotate client, used to validate a pasted refresh token. */
41
+ rotateClient: SlackConfigTokenClient;
42
+ /** SHIPWRIGHT_ENCRYPTION_KEY is configured; save is refused without it. */
43
+ encryptionConfigured: () => boolean;
44
+ callerScopeResolver: CallerScopeResolver;
45
+ /** Needed to tell account owners from plain members; absent = admins only. */
46
+ members?: Pick<AccountMemberService, "getByEmail">;
47
+ accounts?: Pick<AccountService, "listWithCounts" | "getWithCounts">;
48
+ settingsNav?: SettingsNav;
49
+ html: (content: string, opts?: { status?: number }) => Response;
50
+ }
51
+
52
+ type Actor = { kind: "admin" } | { kind: "account"; accountId: string };
53
+
54
+ const NOTICES: Record<string, string> = {
55
+ saved: "Slack config token validated and saved.",
56
+ cleared: "Slack config token cleared.",
57
+ rotated: "Slack config token rotated.",
58
+ };
59
+
60
+ const REFRESH_PREFIX = "xoxe-1-";
61
+
62
+ export function registerAdminSlackConfigTokenRoutes(
63
+ app: Hono<AdminUIEnv>,
64
+ deps: AdminSlackConfigTokenRouteDeps,
65
+ ): void {
66
+ async function resolveActor(c: Context<AdminUIEnv>): Promise<Actor> {
67
+ if (c.var.isAdmin === true) return { kind: "admin" };
68
+ const accountId = accountIdFromScope(
69
+ await deps.callerScopeResolver(c.var.userEmail, false),
70
+ );
71
+ if (accountId === null || !deps.members) {
72
+ throw new ForbiddenError("Admin or account owner access required");
73
+ }
74
+ const me = await deps.members.getByEmail(c.var.userEmail);
75
+ if (!me || me.role !== "owner" || me.accountId !== accountId) {
76
+ throw new ForbiddenError("Admin or account owner access required");
77
+ }
78
+ return { kind: "account", accountId };
79
+ }
80
+
81
+ /** Returns the account id to act on (null = deployment-wide); 403 otherwise. */
82
+ function resolveScope(actor: Actor, requested: string): string | null {
83
+ if (actor.kind === "account") {
84
+ if (requested !== "" && requested !== actor.accountId) {
85
+ throw new ForbiddenError(
86
+ "cannot manage another account's or the deployment-wide Slack config token",
87
+ );
88
+ }
89
+ return actor.accountId;
90
+ }
91
+ return requested === "" ? null : requested;
92
+ }
93
+
94
+ async function accountOptions(
95
+ actor: Actor,
96
+ ): Promise<SlackConfigTokenScopeOption[]> {
97
+ if (actor.kind === "account") {
98
+ const acct = await deps.accounts?.getWithCounts(actor.accountId);
99
+ return [{ value: actor.accountId, label: acct?.name ?? actor.accountId }];
100
+ }
101
+ const accounts = (await deps.accounts?.listWithCounts()) ?? [];
102
+ return [
103
+ { value: "", label: "Deployment-wide (all accounts)" },
104
+ ...accounts.map((a) => ({ value: a.id, label: a.name })),
105
+ ];
106
+ }
107
+
108
+ async function renderPage(
109
+ c: Context<AdminUIEnv>,
110
+ actor: Actor,
111
+ accountId: string | null,
112
+ flash: { error?: string; notice?: string; status?: number } = {},
113
+ ): Promise<Response> {
114
+ const row = await deps.tokens.get(accountId);
115
+ return deps.html(
116
+ renderSlackConfigTokenPage({
117
+ userEmail: c.var.userEmail,
118
+ isAdmin: c.var.isAdmin === true,
119
+ ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
120
+ accountOptions: await accountOptions(actor),
121
+ accountId: accountId ?? "",
122
+ status: row
123
+ ? {
124
+ lastRotatedAt: row.lastRotatedAt,
125
+ lastError: row.lastError,
126
+ slackTeamId: row.slackTeamId,
127
+ slackUserId: row.slackUserId,
128
+ }
129
+ : null,
130
+ encryptionConfigured: deps.encryptionConfigured(),
131
+ ...(flash.error ? { error: flash.error } : {}),
132
+ ...(flash.notice ? { notice: flash.notice } : {}),
133
+ }),
134
+ { status: flash.status ?? 200 },
135
+ );
136
+ }
137
+
138
+ /** Slack's own error code, if it is a safe identifier; never a message. */
139
+ function rotateFailure(err: unknown): ApiError {
140
+ const code = (err as { code?: unknown } | null)?.code;
141
+ const safe =
142
+ typeof code === "string" && /^[a-z0-9_]{1,64}$/i.test(code)
143
+ ? code
144
+ : "unknown_error";
145
+ return new UnprocessableEntityError(
146
+ `Slack rejected the refresh token (${safe}). Nothing was saved.`,
147
+ );
148
+ }
149
+
150
+ async function mutate(
151
+ c: Context<AdminUIEnv>,
152
+ notice: string,
153
+ run: (accountId: string | null, form: FormData) => Promise<void>,
154
+ ): Promise<Response> {
155
+ let actor: Actor;
156
+ try {
157
+ actor = await resolveActor(c);
158
+ } catch {
159
+ return new Response("Forbidden", { status: 403 });
160
+ }
161
+ let form: FormData;
162
+ try {
163
+ form = await c.req.formData();
164
+ } catch {
165
+ form = new FormData();
166
+ }
167
+ let accountId: string | null;
168
+ try {
169
+ accountId = resolveScope(
170
+ actor,
171
+ (form.get("accountId")?.toString() ?? "").trim(),
172
+ );
173
+ } catch {
174
+ return new Response("Forbidden", { status: 403 });
175
+ }
176
+ try {
177
+ await run(accountId, form);
178
+ } catch (err) {
179
+ if (err instanceof ApiError) {
180
+ return renderPage(c, actor, accountId, {
181
+ error: err.message,
182
+ status: err.statusCode,
183
+ });
184
+ }
185
+ throw err;
186
+ }
187
+ const qs = new URLSearchParams({
188
+ ...(accountId !== null ? { accountId } : {}),
189
+ notice,
190
+ });
191
+ return c.redirect(`${BASE}?${qs}`, 302);
192
+ }
193
+
194
+ app.get(BASE, deps.requireAuth, async (c) => {
195
+ let actor: Actor;
196
+ let accountId: string | null;
197
+ try {
198
+ actor = await resolveActor(c);
199
+ accountId = resolveScope(actor, c.req.query("accountId")?.trim() ?? "");
200
+ } catch {
201
+ return new Response("Forbidden", { status: 403 });
202
+ }
203
+ const key = c.req.query("notice");
204
+ return renderPage(c, actor, accountId, {
205
+ ...(key && NOTICES[key] ? { notice: NOTICES[key] } : {}),
206
+ });
207
+ });
208
+
209
+ app.post(`${BASE}/save`, deps.requireAuth, (c) =>
210
+ mutate(c, "saved", async (accountId, form) => {
211
+ if (!deps.encryptionConfigured()) {
212
+ throw new UnprocessableEntityError(
213
+ "SHIPWRIGHT_ENCRYPTION_KEY is not configured; refusing to store a Slack config token unencrypted. Set it to a 64-character hex string (openssl rand -hex 32) and retry.",
214
+ );
215
+ }
216
+ const pasted = (form.get("refreshToken")?.toString() ?? "").trim();
217
+ if (!pasted.startsWith(REFRESH_PREFIX)) {
218
+ throw new UnprocessableEntityError(
219
+ `Paste a Slack App Configuration refresh token (it starts with ${REFRESH_PREFIX}).`,
220
+ );
221
+ }
222
+ let rotated: Awaited<
223
+ ReturnType<SlackConfigTokenClient["rotateConfigToken"]>
224
+ >;
225
+ try {
226
+ rotated = await deps.rotateClient.rotateConfigToken(pasted);
227
+ } catch (err) {
228
+ throw rotateFailure(err);
229
+ }
230
+ await deps.tokens.save(accountId, {
231
+ refreshToken: rotated.refreshToken,
232
+ accessToken: rotated.accessToken,
233
+ accessTokenExpiresAt: new Date(rotated.exp * 1000),
234
+ slackTeamId: rotated.teamId,
235
+ slackUserId: rotated.userId,
236
+ });
237
+ }),
238
+ );
239
+
240
+ app.post(`${BASE}/clear`, deps.requireAuth, (c) =>
241
+ mutate(c, "cleared", async (accountId) => {
242
+ await deps.tokens.clear(accountId);
243
+ }),
244
+ );
245
+
246
+ app.post(`${BASE}/rotate`, deps.requireAuth, (c) =>
247
+ mutate(c, "rotated", async (accountId) => {
248
+ await deps.tokens.getAccessToken(accountId, { forceRotate: true });
249
+ }),
250
+ );
251
+ }
package/src/admin-ui.ts CHANGED
@@ -100,6 +100,10 @@ import {
100
100
  type SettingsNav,
101
101
  withoutAccountItem,
102
102
  } from "./admin-ui-settings-layout.ts";
103
+ import {
104
+ type AdminSlackConfigTokenRouteDeps,
105
+ registerAdminSlackConfigTokenRoutes,
106
+ } from "./admin-ui-slack-config-token.ts";
103
107
  import { registerAdminTemplatesRoutes } from "./admin-ui-templates.ts";
104
108
  import type { AgentCronJobService } from "./agent-cron-jobs.ts";
105
109
  import type { DeleteAgentFullyDeps } from "./agent-deletion.ts";
@@ -157,6 +161,11 @@ import {
157
161
  DEFAULT_SELF_SERVE_CONTACT_EMAIL,
158
162
  type SelfServeConfig,
159
163
  } from "./self-serve-config.ts";
164
+ import {
165
+ hasStoredSlackConfigToken,
166
+ type SlackConfigTokenResolver,
167
+ withSlackConfigToken,
168
+ } from "./slack-config-token.ts";
160
169
  import type { AppManifest } from "./slack-provisioning-client.ts";
161
170
  import {
162
171
  AGENT_BOT_SCOPES,
@@ -445,6 +454,13 @@ export interface AdminUIDeps {
445
454
  oktaIssuer?: string;
446
455
  adminAllowedEmails: string[];
447
456
  slackClient: AdminUISlackClient;
457
+ /**
458
+ * Optional stored Slack config token resolver (SCT-4.1; additive). When set,
459
+ * the create / connect-slack / sync-manifest / delete flows mint an access
460
+ * token from the agent's account row (else the default row) whenever no
461
+ * xoxpToken was pasted. Absent keeps the paste-only behavior.
462
+ */
463
+ slackConfigTokens?: SlackConfigTokenResolver;
448
464
  /**
449
465
  * GitHub App manifest-flow provisioning client, used by the auto-provision
450
466
  * sub-flow under ghAuthMode=app: GET /admin/provision/github-app/complete
@@ -474,6 +490,14 @@ export interface AdminUIDeps {
474
490
  AgentTemplateService,
475
491
  "list" | "replace" | "putItem" | "deleteItem" | "delete"
476
492
  >;
493
+ /**
494
+ * SCT-3.1: Settings > Slack config token. Optional; absent → no
495
+ * /admin/settings/slack-config-token routes and no nav entry.
496
+ */
497
+ slackConfigToken?: Pick<
498
+ AdminSlackConfigTokenRouteDeps,
499
+ "tokens" | "rotateClient" | "encryptionConfigured"
500
+ >;
477
501
  githubEnterpriseApi?: (
478
502
  path: string,
479
503
  init?: RequestInit,
@@ -913,6 +937,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
913
937
  accountServices,
914
938
  githubEnterpriseApi,
915
939
  templateService,
940
+ slackConfigToken,
916
941
  templateReconcile,
917
942
  agentsApi,
918
943
  specialtyRegistry = new SpecialtyTypes(),
@@ -962,6 +987,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
962
987
  const settingsNav = buildSettingsNav({
963
988
  githubEnterprise: Boolean(githubEnterpriseApi),
964
989
  templates: Boolean(templateService),
990
+ slackConfigToken: Boolean(slackConfigToken),
965
991
  accounts: accountNavEnabled,
966
992
  extraItems: deps.settingsNavItems ?? [],
967
993
  });
@@ -986,7 +1012,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
986
1012
 
987
1013
  // GHE-1.4: the admin-only "Settings" toolbar entry.
988
1014
  // SGL-2.2: shown to admins and to account members.
989
- if (githubEnterpriseApi || templateService || accountNavEnabled) {
1015
+ if (
1016
+ githubEnterpriseApi ||
1017
+ templateService ||
1018
+ slackConfigToken ||
1019
+ accountNavEnabled
1020
+ ) {
990
1021
  app.use("/admin/*", async (c, next) => {
991
1022
  const token = getCookie(c, SESSION_COOKIE);
992
1023
  const user = token ? await getSessionUser(token, sessionSecret) : null;
@@ -1016,6 +1047,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1016
1047
  sessionSecret,
1017
1048
  appBaseUrl,
1018
1049
  secretEnvVars: new Set(SECRET_ENV_VARS),
1050
+ ...(deps.slackConfigTokens
1051
+ ? { slackConfigTokens: deps.slackConfigTokens }
1052
+ : {}),
1019
1053
  });
1020
1054
 
1021
1055
  // Extracted GitHub App manifest-flow/PAT provisioning orchestration
@@ -1625,6 +1659,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1625
1659
  error,
1626
1660
  canProvision: provisioner.canProvision,
1627
1661
  anthropicFederationEnabled: deps.anthropicFederationEnabled,
1662
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
1663
+ deps.slackConfigTokens,
1664
+ accountId,
1665
+ ),
1628
1666
  ...(selfServeOpts ? { selfServe: selfServeOpts } : {}),
1629
1667
  ...(templateService
1630
1668
  ? {
@@ -2514,6 +2552,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2514
2552
  queueActivityLinks: deps.queueActivityLinks,
2515
2553
  marketplaces,
2516
2554
  githubEnterpriseConfigured: enterpriseConfigured,
2555
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
2556
+ deps.slackConfigTokens,
2557
+ agent.accountId ?? null,
2558
+ ),
2517
2559
  ...(installationRepos ? { installationRepos } : {}),
2518
2560
  ...(agentsApi
2519
2561
  ? { template: { detached: agent.templateDetached === true } }
@@ -3426,6 +3468,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3426
3468
  queueActivityLinks: deps.queueActivityLinks,
3427
3469
  marketplaces,
3428
3470
  githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
3471
+ slackConfigTokenStored: await hasStoredSlackConfigToken(
3472
+ deps.slackConfigTokens,
3473
+ agent.accountId ?? null,
3474
+ ),
3429
3475
  ...(agentsApi
3430
3476
  ? { template: { detached: agent.templateDetached === true } }
3431
3477
  : {}),
@@ -3486,7 +3532,17 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3486
3532
  );
3487
3533
  }
3488
3534
 
3489
- if (!xoxpToken?.startsWith("xoxe.xoxp-")) {
3535
+ // A pasted token wins and must be well-formed; with none pasted, a stored
3536
+ // Slack config token (account row, else default) is minted instead.
3537
+ xoxpToken = xoxpToken?.trim() || undefined;
3538
+ if (
3539
+ xoxpToken
3540
+ ? !xoxpToken.startsWith("xoxe.xoxp-")
3541
+ : !(await hasStoredSlackConfigToken(
3542
+ deps.slackConfigTokens,
3543
+ agent.accountId ?? null,
3544
+ ))
3545
+ ) {
3490
3546
  return c.redirect(
3491
3547
  agentSectionPath(agentId, "general", {
3492
3548
  error: "Slack app configuration token must start with xoxe.xoxp-",
@@ -3509,7 +3565,11 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3509
3565
  try {
3510
3566
  const redirectUri = `${appBaseUrl}/admin/agents/${agentId}/connect-slack/callback`;
3511
3567
  const manifest = buildAgentManifest(agent.name, redirectUri);
3512
- await slackClient.updateAppManifest(xoxpToken, appId, manifest);
3568
+ await withSlackConfigToken(
3569
+ deps.slackConfigTokens,
3570
+ { pasted: xoxpToken, accountId: agent.accountId ?? null },
3571
+ (token) => slackClient.updateAppManifest(token, appId, manifest),
3572
+ );
3513
3573
  } catch (err) {
3514
3574
  const msg =
3515
3575
  err instanceof Error ? err.message : "Unknown error syncing manifest.";
@@ -4066,7 +4126,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4066
4126
  // ─── Enterprise GitHub apps settings (GHE-1.4) ───────────────────────────
4067
4127
 
4068
4128
  // SGL-2.2: /admin/settings lands on the first nav item the viewer can see.
4069
- if (githubEnterpriseApi || templateService || accountNavEnabled) {
4129
+ if (
4130
+ githubEnterpriseApi ||
4131
+ templateService ||
4132
+ slackConfigToken ||
4133
+ accountNavEnabled
4134
+ ) {
4070
4135
  app.get("/admin/settings", requireAuth, async (c) => {
4071
4136
  // Admins without an account would 404 on the Account item; skip it.
4072
4137
  let nav = settingsNav;
@@ -4110,6 +4175,24 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4110
4175
  });
4111
4176
  }
4112
4177
 
4178
+ // ─── Slack config token settings (SCT-3.1) ───────────────────────────────
4179
+
4180
+ if (slackConfigToken) {
4181
+ registerAdminSlackConfigTokenRoutes(app, {
4182
+ requireAuth,
4183
+ ...slackConfigToken,
4184
+ settingsNav,
4185
+ callerScopeResolver,
4186
+ ...(accountServices
4187
+ ? {
4188
+ accounts: accountServices.accounts,
4189
+ members: accountServices.members,
4190
+ }
4191
+ : {}),
4192
+ html,
4193
+ });
4194
+ }
4195
+
4113
4196
  // ─── Account page (SSP-3.2) ───────────────────────────────────────────────
4114
4197
 
4115
4198
  if (accountServices) {
@@ -4926,6 +5009,9 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4926
5009
  chatService,
4927
5010
  slack,
4928
5011
  decrypt,
5012
+ ...(deps.slackConfigTokens
5013
+ ? { slackConfigTokens: deps.slackConfigTokens }
5014
+ : {}),
4929
5015
  });
4930
5016
  if (!result.agentDeleted) {
4931
5017
  // Cleanup is incomplete — keep the operator on the agent's own page
@@ -49,6 +49,11 @@ import type { AgentProvisioner } from "./agent-provisioner.ts";
49
49
  import type { ChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
50
50
  import { NotFoundError } from "./errors.ts";
51
51
  import type { DeletionServiceIntegration } from "./service-integration.ts";
52
+ import {
53
+ hasStoredSlackConfigToken,
54
+ type SlackConfigTokenResolver,
55
+ withSlackConfigToken,
56
+ } from "./slack-config-token.ts";
52
57
  import type { SlackProvisioningClient } from "./slack-provisioning-client.ts";
53
58
 
54
59
  // ─── Step identifiers ─────────────────────────────────────────────────────────
@@ -113,8 +118,17 @@ interface DeleteAgentPrisma {
113
118
  anthropicFederationRuleId: true;
114
119
  anthropicServiceAccountId: true;
115
120
  k8sServiceAccountName: true;
121
+ accountId: true;
116
122
  };
117
- }): Promise<({ id: string; name: string } & LeftoverIdentity) | null>;
123
+ }): Promise<
124
+ | ({
125
+ id: string;
126
+ name: string;
127
+ /** Owning account; picks the stored Slack config token row. */
128
+ accountId?: string | null;
129
+ } & LeftoverIdentity)
130
+ | null
131
+ >;
118
132
  delete(args: { where: { id: string } }): Promise<unknown>;
119
133
  };
120
134
  agentEnv: {
@@ -149,12 +163,20 @@ export interface DeleteAgentFullyDeps {
149
163
  * crypto and is trivially unit-testable.
150
164
  */
151
165
  decrypt(value: string): string;
166
+ /**
167
+ * Optional stored Slack config token resolver. When present and a token
168
+ * resolves for the agent's account (else the default), the Slack app is
169
+ * deleted with a minted access token if no token was pasted. Absent keeps the
170
+ * paste-only behavior.
171
+ */
172
+ slackConfigTokens?: SlackConfigTokenResolver;
152
173
  }
153
174
 
154
175
  interface DeleteAgentFullyOpts {
155
176
  /**
156
177
  * Slack user token (xoxp-) authorizing the Slack app deletion. Supplied
157
- * per-request (same UX as the sync-manifest flow) — when omitted, a Slack app
178
+ * per-request (same UX as the sync-manifest flow) and wins over a stored
179
+ * Slack config token. When omitted and no stored token resolves, a Slack app
158
180
  * (if present) is NOT auto-deleted and instead becomes a manual checklist
159
181
  * entry. Its absence is never a failure.
160
182
  */
@@ -190,6 +212,7 @@ export async function deleteAgentFully(
190
212
  anthropicFederationRuleId: true,
191
213
  anthropicServiceAccountId: true,
192
214
  k8sServiceAccountName: true,
215
+ accountId: true,
193
216
  } as const;
194
217
  const agent = await deps.prisma.agent.findUnique({
195
218
  where: { id: agentId },
@@ -266,14 +289,25 @@ export async function deleteAgentFully(
266
289
  const manualSlackSteps: ManualStep[] = [];
267
290
  if (slackAppIdRow) {
268
291
  const slackAppId = deps.decrypt(slackAppIdRow.value);
269
- if (opts.xoxpToken) {
292
+ const pasted = opts.xoxpToken?.trim() || undefined;
293
+ if (
294
+ pasted ||
295
+ (await hasStoredSlackConfigToken(
296
+ deps.slackConfigTokens,
297
+ agent.accountId ?? null,
298
+ ))
299
+ ) {
270
300
  await runStep("slack-app", async () => {
271
- await deps.slack.deleteApp(opts.xoxpToken as string, slackAppId);
301
+ await withSlackConfigToken(
302
+ deps.slackConfigTokens,
303
+ { pasted, accountId: agent.accountId ?? null },
304
+ (token) => deps.slack.deleteApp(token, slackAppId),
305
+ );
272
306
  });
273
307
  } else {
274
308
  manualSlackSteps.push({
275
309
  key: "SLACK_APP_ID",
276
- message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied. Delete it manually at api.slack.com/apps or retry with a token.`,
310
+ message: `Slack app ${slackAppId} was not deleted automatically — no Slack user token was supplied and no stored Slack config token applies. Delete it manually at api.slack.com/apps or retry with a token.`,
277
311
  });
278
312
  }
279
313
  }