@app-vitals/agent-admin 1.57.0 → 1.59.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.
@@ -987,6 +987,29 @@
987
987
  "adopted",
988
988
  "deleted"
989
989
  ]
990
+ },
991
+ "marketplace": {
992
+ "type": "object",
993
+ "properties": {
994
+ "created": {
995
+ "type": "integer"
996
+ },
997
+ "updated": {
998
+ "type": "integer"
999
+ },
1000
+ "adopted": {
1001
+ "type": "integer"
1002
+ },
1003
+ "deleted": {
1004
+ "type": "integer"
1005
+ }
1006
+ },
1007
+ "required": [
1008
+ "created",
1009
+ "updated",
1010
+ "adopted",
1011
+ "deleted"
1012
+ ]
990
1013
  }
991
1014
  },
992
1015
  "required": [
@@ -1038,7 +1061,8 @@
1038
1061
  "enum": [
1039
1062
  "cron_name_conflict",
1040
1063
  "invalid_cron_schedule",
1041
- "denylisted_env_key"
1064
+ "denylisted_env_key",
1065
+ "marketplace_conflict"
1042
1066
  ]
1043
1067
  }
1044
1068
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.57.0",
3
+ "version": "1.59.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@anthropic-ai/sdk": "0.137.0",
45
- "@app-vitals/agent-lib": "1.57.0",
45
+ "@app-vitals/agent-lib": "1.59.0",
46
46
  "@hono/zod-openapi": "^1.0.0",
47
47
  "@prisma/adapter-pg": "^7.10.0",
48
48
  "@prisma/client": "^7.10.0",
@@ -66,6 +66,7 @@ describeOrSkip("AgentTemplateReconcileService (integration)", () => {
66
66
  await prisma.agentTemplate.deleteMany();
67
67
  await prisma.agentCronJob.deleteMany();
68
68
  await prisma.agentTool.deleteMany();
69
+ await prisma.agentMarketplace.deleteMany();
69
70
  await prisma.agentPlugin.deleteMany();
70
71
  await prisma.agentEnv.deleteMany();
71
72
  await prisma.agentToken.deleteMany();
@@ -820,6 +821,222 @@ describeOrSkip("AgentTemplateReconcileService (integration)", () => {
820
821
  ]);
821
822
  });
822
823
 
824
+ // ─── marketplaces (TMK-2.3) ───────────────────────────────────────────────
825
+
826
+ describe("marketplaces", () => {
827
+ const mkt = (agentId: string, name: string) =>
828
+ prisma.agentMarketplace.findUnique({
829
+ where: { agentId_name: { agentId, name } },
830
+ });
831
+
832
+ it("creates a missing template marketplace", async () => {
833
+ const agentId = await agent();
834
+ await template(null, null, [
835
+ {
836
+ kind: "marketplace",
837
+ key: "mk",
838
+ payload: { source: "example-org/plugins", ref: "v1" },
839
+ },
840
+ ]);
841
+ const result = await service.reconcile(agentId);
842
+ expect(result.counts.marketplace).toEqual({
843
+ created: 1,
844
+ updated: 0,
845
+ adopted: 0,
846
+ deleted: 0,
847
+ });
848
+ expect(await mkt(agentId, "mk")).toMatchObject({
849
+ source: "example-org/plugins",
850
+ ref: "v1",
851
+ rowSource: "template",
852
+ enabled: true,
853
+ });
854
+ });
855
+
856
+ it("updates a changed ref in place, keeping the row id", async () => {
857
+ const agentId = await agent();
858
+ const tid = await template(null, null, [
859
+ {
860
+ kind: "marketplace",
861
+ key: "mk",
862
+ payload: { source: "example-org/plugins", ref: "v1" },
863
+ },
864
+ ]);
865
+ await service.reconcile(agentId);
866
+ const before = await mkt(agentId, "mk");
867
+ await setItems(tid, [
868
+ {
869
+ kind: "marketplace",
870
+ key: "mk",
871
+ payload: { source: "example-org/plugins", ref: "v2" },
872
+ },
873
+ ]);
874
+ const result = await service.reconcile(agentId);
875
+ expect(result.counts.marketplace?.updated).toBe(1);
876
+ const after = await mkt(agentId, "mk");
877
+ expect(after?.id).toBe(before?.id);
878
+ expect(after?.ref).toBe("v2");
879
+ });
880
+
881
+ it("adopts an enabled custom row with the same name, source and ref", async () => {
882
+ const agentId = await agent();
883
+ const row = await prisma.agentMarketplace.create({
884
+ data: { agentId, name: "mk", source: "example-org/plugins" },
885
+ });
886
+ await template(null, null, [
887
+ {
888
+ kind: "marketplace",
889
+ key: "mk",
890
+ payload: { source: "example-org/plugins" },
891
+ },
892
+ ]);
893
+ const result = await service.reconcile(agentId);
894
+ expect(result.counts.marketplace?.adopted).toBe(1);
895
+ expect(await mkt(agentId, "mk")).toMatchObject({
896
+ id: row.id,
897
+ rowSource: "template",
898
+ });
899
+ });
900
+
901
+ it("leaves a same-named custom row with a different source and reports a conflict", async () => {
902
+ const agentId = await agent();
903
+ await prisma.agentMarketplace.create({
904
+ data: { agentId, name: "mk", source: "someone/else" },
905
+ });
906
+ await template(null, null, [
907
+ {
908
+ kind: "marketplace",
909
+ key: "mk",
910
+ payload: { source: "example-org/plugins" },
911
+ },
912
+ ]);
913
+ const before = await mkt(agentId, "mk");
914
+ const result = await service.reconcile(agentId);
915
+ expect(result.conflicts).toEqual([
916
+ { kind: "marketplace", key: "mk", reason: "marketplace_conflict" },
917
+ ]);
918
+ expect(await mkt(agentId, "mk")).toEqual(before);
919
+ });
920
+
921
+ it("deletes an orphaned template row but never a custom row", async () => {
922
+ const agentId = await agent();
923
+ const tid = await template(null, null, [
924
+ {
925
+ kind: "marketplace",
926
+ key: "mk",
927
+ payload: { source: "example-org/plugins" },
928
+ },
929
+ ]);
930
+ await service.reconcile(agentId);
931
+ await prisma.agentMarketplace.create({
932
+ data: { agentId, name: "mine", source: "me/mine" },
933
+ });
934
+ await setItems(tid, []);
935
+ const result = await service.reconcile(agentId);
936
+ expect(result.counts.marketplace?.deleted).toBe(1);
937
+ expect(await mkt(agentId, "mk")).toBeNull();
938
+ expect((await mkt(agentId, "mine"))?.rowSource).toBe("custom");
939
+ });
940
+
941
+ it("does not re-add or re-enable a tombstoned row", async () => {
942
+ const agentId = await agent();
943
+ await prisma.agentMarketplace.create({
944
+ data: {
945
+ agentId,
946
+ name: "mk",
947
+ source: "example-org/plugins",
948
+ rowSource: "custom",
949
+ enabled: false,
950
+ },
951
+ });
952
+ await template(null, null, [
953
+ {
954
+ kind: "marketplace",
955
+ key: "mk",
956
+ payload: { source: "example-org/plugins" },
957
+ },
958
+ ]);
959
+ const before = await mkt(agentId, "mk");
960
+ const result = await service.reconcile(agentId);
961
+ expect(result.counts.marketplace).toEqual({
962
+ created: 0,
963
+ updated: 0,
964
+ adopted: 0,
965
+ deleted: 0,
966
+ });
967
+ expect(result.conflicts).toEqual([]);
968
+ expect(await mkt(agentId, "mk")).toEqual(before);
969
+ });
970
+
971
+ it("reset drops custom rows and tombstones for template keys and re-creates them", async () => {
972
+ const agentId = await agent();
973
+ await template(null, null, [
974
+ {
975
+ kind: "marketplace",
976
+ key: "mk",
977
+ payload: { source: "example-org/plugins" },
978
+ },
979
+ {
980
+ kind: "marketplace",
981
+ key: "tomb",
982
+ payload: { source: "example-org/other" },
983
+ },
984
+ ]);
985
+ await prisma.agentMarketplace.create({
986
+ data: { agentId, name: "mk", source: "someone/else" },
987
+ });
988
+ await prisma.agentMarketplace.create({
989
+ data: {
990
+ agentId,
991
+ name: "tomb",
992
+ source: "example-org/other",
993
+ rowSource: "custom",
994
+ enabled: false,
995
+ },
996
+ });
997
+ await prisma.agentMarketplace.create({
998
+ data: { agentId, name: "mine", source: "me/mine" },
999
+ });
1000
+
1001
+ await service.reset(agentId, { kind: "marketplace", key: "mk" });
1002
+ expect(await mkt(agentId, "mk")).toMatchObject({
1003
+ source: "example-org/plugins",
1004
+ rowSource: "template",
1005
+ });
1006
+ expect((await mkt(agentId, "tomb"))?.enabled).toBe(false);
1007
+
1008
+ await service.reset(agentId);
1009
+ expect(await mkt(agentId, "tomb")).toMatchObject({
1010
+ rowSource: "template",
1011
+ enabled: true,
1012
+ });
1013
+ expect((await mkt(agentId, "mine"))?.rowSource).toBe("custom");
1014
+ });
1015
+
1016
+ it("leaves a detached agent's marketplaces untouched", async () => {
1017
+ const agentId = await agent({ templateDetached: true });
1018
+ await prisma.agentMarketplace.create({
1019
+ data: {
1020
+ agentId,
1021
+ name: "old",
1022
+ source: "example-org/old",
1023
+ rowSource: "template",
1024
+ },
1025
+ });
1026
+ await template(null, null, [
1027
+ {
1028
+ kind: "marketplace",
1029
+ key: "mk",
1030
+ payload: { source: "example-org/plugins" },
1031
+ },
1032
+ ]);
1033
+ const result = await service.reconcile(agentId);
1034
+ expect(result.status).toBe("detached");
1035
+ expect(await mkt(agentId, "mk")).toBeNull();
1036
+ expect(await mkt(agentId, "old")).not.toBeNull();
1037
+ });
1038
+ });
1039
+
823
1040
  it("throws NotFoundError for an unknown agent", async () => {
824
1041
  await expect(service.reconcile("missing")).rejects.toBeInstanceOf(
825
1042
  NotFoundError,
@@ -12,6 +12,13 @@
12
12
  * - Missing items are created with source="template".
13
13
  * - Rows with source="template" track the template: edited in place (ids
14
14
  * stay stable), and deleted once no layer defines their key (orphans).
15
+ * - Marketplaces (TMK-2.3) follow the plugin rules, keyed by name, on
16
+ * AgentMarketplace.rowSource: created and updated in place (source/ref)
17
+ * through AgentMarketplaceService.addFromTemplate(), adopted when an enabled
18
+ * custom row has the same source and ref, and deleted as orphans. A custom
19
+ * row with the same name but a different source/ref is left alone and
20
+ * reported in `conflicts` (marketplace_conflict). They run before plugins,
21
+ * whose "<plugin>@<marketplace>" names refer to them.
15
22
  * - Rows with source="custom" are never modified. That covers admin edits and
16
23
  * tombstones (ATP-1.2 turns a deleted template row into enabled=false,
17
24
  * source=custom), so a deleted inherited row is never re-added.
@@ -36,11 +43,13 @@
36
43
  import type {
37
44
  AgentCronJob,
38
45
  AgentEnv,
46
+ AgentMarketplace,
39
47
  AgentPlugin,
40
48
  AgentTool,
41
49
  PrismaClient,
42
50
  } from "../prisma/client/client.ts";
43
51
  import { applySystemCronDefaults, isValidCron } from "./agent-cron-jobs.ts";
52
+ import { AgentMarketplaceService } from "./agent-marketplaces.ts";
44
53
  import {
45
54
  type AgentTemplateItemKind,
46
55
  openTemplateItemPayload,
@@ -76,7 +85,11 @@ export interface TemplateReconcileCounts {
76
85
  export interface TemplateReconcileConflict {
77
86
  kind: AgentTemplateItemKind;
78
87
  key: string;
79
- reason: "cron_name_conflict" | "invalid_cron_schedule" | "denylisted_env_key";
88
+ reason:
89
+ | "cron_name_conflict"
90
+ | "invalid_cron_schedule"
91
+ | "denylisted_env_key"
92
+ | "marketplace_conflict";
80
93
  }
81
94
 
82
95
  export interface TemplateReconcileResult {
@@ -88,7 +101,7 @@ export interface TemplateReconcileResult {
88
101
  Exclude<AgentTemplateItemKind, "marketplace">,
89
102
  TemplateReconcileCounts
90
103
  > & {
91
- /** TMK-2.3: present once the marketplace reconcile lands (additive). */
104
+ /** TMK-2.3: optional so the exported shape stays additive for consumers. */
92
105
  marketplace?: TemplateReconcileCounts;
93
106
  };
94
107
  systemCrons: { created: number; updated: number; deleted: number };
@@ -117,6 +130,7 @@ function emptyResult(
117
130
  tool: zeroCounts(),
118
131
  plugin: zeroCounts(),
119
132
  cron: zeroCounts(),
133
+ marketplace: zeroCounts(),
120
134
  },
121
135
  systemCrons: { created: 0, updated: 0, deleted: 0 },
122
136
  conflicts: [],
@@ -296,6 +310,7 @@ export class AgentTemplateReconcileService {
296
310
  const result = emptyResult(agentId, "reconciled");
297
311
  // Env goes last: it is the only kind that encrypts on write.
298
312
  await this.reconcileTools(tx, agentId, merged, result);
313
+ await this.reconcileMarketplaces(tx, agentId, merged, result);
299
314
  await this.reconcilePlugins(tx, agentId, merged, result);
300
315
  await this.reconcileCrons(tx, agentId, merged, defaults.crons, result);
301
316
  await this.reconcileEnv(tx, agentId, merged, result);
@@ -320,6 +335,13 @@ export class AgentTemplateReconcileService {
320
335
  pattern: { in: keys("tool", merged.tool.keys()) },
321
336
  },
322
337
  });
338
+ await tx.agentMarketplace.deleteMany({
339
+ where: {
340
+ agentId,
341
+ rowSource: "custom",
342
+ name: { in: keys("marketplace", merged.marketplace.keys()) },
343
+ },
344
+ });
323
345
  await tx.agentPlugin.deleteMany({
324
346
  where: {
325
347
  agentId,
@@ -466,6 +488,59 @@ export class AgentTemplateReconcileService {
466
488
  }
467
489
  }
468
490
 
491
+ private async reconcileMarketplaces(
492
+ tx: PrismaTransactionClient,
493
+ agentId: string,
494
+ merged: MergedTemplate,
495
+ result: TemplateReconcileResult,
496
+ ): Promise<void> {
497
+ const counts = result.counts.marketplace ?? zeroCounts();
498
+ result.counts.marketplace = counts;
499
+ const rows = await tx.agentMarketplace.findMany({ where: { agentId } });
500
+ const byName = new Map<string, AgentMarketplace>(
501
+ rows.map((r) => [r.name, r]),
502
+ );
503
+ const service = new AgentMarketplaceService(this.prisma);
504
+
505
+ for (const item of merged.marketplace.values()) {
506
+ const source =
507
+ typeof item.payload.source === "string" ? item.payload.source : "";
508
+ const ref =
509
+ typeof item.payload.ref === "string" ? item.payload.ref : null;
510
+ const fromTemplate = { name: item.key, source, ref };
511
+ const row = byName.get(item.key);
512
+ if (!row) {
513
+ await service.addFromTemplate(agentId, fromTemplate, tx);
514
+ counts.created++;
515
+ } else if (row.rowSource === "template") {
516
+ if (row.source !== source || row.ref !== ref || !row.enabled) {
517
+ await service.addFromTemplate(agentId, fromTemplate, tx);
518
+ counts.updated++;
519
+ }
520
+ } else if (!row.enabled) {
521
+ // Tombstone: the user deleted the inherited row; never re-add it.
522
+ } else if (row.source === source && row.ref === ref) {
523
+ await tx.agentMarketplace.update({
524
+ where: { id: row.id },
525
+ data: { rowSource: "template" },
526
+ });
527
+ counts.adopted++;
528
+ } else {
529
+ result.conflicts.push({
530
+ kind: "marketplace",
531
+ key: item.key,
532
+ reason: "marketplace_conflict",
533
+ });
534
+ }
535
+ }
536
+ for (const row of rows) {
537
+ if (row.rowSource === "template" && !merged.marketplace.has(row.name)) {
538
+ await tx.agentMarketplace.delete({ where: { id: row.id } });
539
+ counts.deleted++;
540
+ }
541
+ }
542
+ }
543
+
469
544
  private async reconcilePlugins(
470
545
  tx: PrismaTransactionClient,
471
546
  agentId: string,
@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
10
10
  import type { PrismaClient } from "../prisma/client/client.ts";
11
11
  import { AgentCronJobService } from "./agent-cron-jobs.ts";
12
12
  import { AgentEnvService } from "./agent-envs.ts";
13
+ import { AgentMarketplaceService } from "./agent-marketplaces.ts";
13
14
  import { AgentMemberService } from "./agent-members.ts";
14
15
  import { AgentPluginService } from "./agent-plugins.ts";
15
16
  import { NoopAgentProvisioner } from "./agent-provisioner.ts";
@@ -23,6 +24,7 @@ import {
23
24
  createAdminApp,
24
25
  parseAdminApiKeys,
25
26
  } from "./agents-api.ts";
27
+ import { createAgentRuntimeApp } from "./api.ts";
26
28
  import { createAdminPrismaClient } from "./prisma-client.ts";
27
29
  import type { SpecialtyType } from "./specialty-types.ts";
28
30
  import { makeStrictTokenCrypto } from "./token-crypto.ts";
@@ -58,6 +60,7 @@ describeOrSkip("agent template triggers (integration)", () => {
58
60
  await prisma.agentTemplate.deleteMany();
59
61
  await prisma.agentCronJob.deleteMany();
60
62
  await prisma.agentTool.deleteMany();
63
+ await prisma.agentMarketplace.deleteMany();
61
64
  await prisma.agentPlugin.deleteMany();
62
65
  await prisma.agentEnv.deleteMany();
63
66
  await prisma.agentToken.deleteMany();
@@ -365,4 +368,91 @@ describeOrSkip("agent template triggers (integration)", () => {
365
368
  expect(await envOf(id, "MINE")).toEqual({ value: "1", source: "custom" });
366
369
  });
367
370
  });
371
+
372
+ describe("template marketplaces in the config bundle", () => {
373
+ it("fans a marketplace plus its plugin out to agents in scope and into GET /agents/:id/config", async () => {
374
+ const agent = await mkAgent("a");
375
+ const other = await mkAgent("detached", { templateDetached: true });
376
+ const tokens = new AgentTokenService(prisma);
377
+ const { rawToken } = await tokens.create(agent.id);
378
+ const runtimeApp = createAgentRuntimeApp({
379
+ agentEnvService: { getConfigBundle: async () => null },
380
+ agentCronJobService: { list: async () => [] },
381
+ agentService: new AgentService(prisma),
382
+ agentPluginService: new AgentPluginService(prisma),
383
+ agentMarketplaceService: new AgentMarketplaceService(prisma),
384
+ sessionSecret: "test-admin-session-secret-32-bytes!",
385
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
386
+ agentTokenService: tokens,
387
+ } as never);
388
+ const config = async () => {
389
+ const res = await runtimeApp.request(`/${agent.id}/config`, {
390
+ headers: { Authorization: `Bearer ${rawToken}` },
391
+ });
392
+ expect(res.status).toBe(200);
393
+ return (await res.json()) as {
394
+ marketplaces: { name: string; source: string; ref: string | null }[];
395
+ plugins: { plugin: string; marketplace: string }[];
396
+ };
397
+ };
398
+
399
+ await templates.replace({ kind: "admin" }, {}, [
400
+ {
401
+ kind: "marketplace",
402
+ key: "example-mk",
403
+ payload: { source: "example-org/plugins", ref: "v1" },
404
+ },
405
+ { kind: "plugin", key: "tool@example-mk" },
406
+ ]);
407
+ let cfg = await config();
408
+ expect(cfg.marketplaces).toEqual([
409
+ { name: "example-mk", source: "example-org/plugins", ref: "v1" },
410
+ ]);
411
+ expect(cfg.plugins).toContainEqual({
412
+ plugin: "tool",
413
+ marketplace: "example-mk",
414
+ });
415
+ expect(
416
+ await prisma.agentMarketplace.count({ where: { agentId: other.id } }),
417
+ ).toBe(0);
418
+
419
+ // Editing the template fans out again.
420
+ await templates.replace({ kind: "admin" }, {}, [
421
+ {
422
+ kind: "marketplace",
423
+ key: "example-mk",
424
+ payload: { source: "example-org/plugins", ref: "v2" },
425
+ },
426
+ { kind: "plugin", key: "tool@example-mk" },
427
+ ]);
428
+ cfg = await config();
429
+ expect(cfg.marketplaces[0]?.ref).toBe("v2");
430
+
431
+ // A tombstoned row stays out of the bundle and is not re-added by the
432
+ // next fan-out.
433
+ const marketplaces = new AgentMarketplaceService(prisma);
434
+ const row = await prisma.agentMarketplace.findUniqueOrThrow({
435
+ where: { agentId_name: { agentId: agent.id, name: "example-mk" } },
436
+ });
437
+ await marketplaces.remove(agent.id, row.id);
438
+ await templates.replace({ kind: "admin" }, {}, [
439
+ {
440
+ kind: "marketplace",
441
+ key: "example-mk",
442
+ payload: { source: "example-org/plugins", ref: "v3" },
443
+ },
444
+ { kind: "plugin", key: "tool@example-mk" },
445
+ ]);
446
+ cfg = await config();
447
+ expect(cfg.marketplaces).toEqual([]);
448
+ const tomb = await prisma.agentMarketplace.findUniqueOrThrow({
449
+ where: { id: row.id },
450
+ });
451
+ expect(tomb).toMatchObject({
452
+ enabled: false,
453
+ rowSource: "custom",
454
+ ref: "v2",
455
+ });
456
+ });
457
+ });
368
458
  });
package/src/agents-api.ts CHANGED
@@ -1084,6 +1084,7 @@ const TemplateReconcileResultSchema = z
1084
1084
  tool: TemplateReconcileCountsSchema,
1085
1085
  plugin: TemplateReconcileCountsSchema,
1086
1086
  cron: TemplateReconcileCountsSchema,
1087
+ marketplace: TemplateReconcileCountsSchema.optional(),
1087
1088
  }),
1088
1089
  systemCrons: z.object({
1089
1090
  created: z.number().int(),
@@ -1098,6 +1099,7 @@ const TemplateReconcileResultSchema = z
1098
1099
  "cron_name_conflict",
1099
1100
  "invalid_cron_schedule",
1100
1101
  "denylisted_env_key",
1102
+ "marketplace_conflict",
1101
1103
  ]),
1102
1104
  }),
1103
1105
  ),
@@ -94,5 +94,36 @@
94
94
  "authTest_missing_user_id": {
95
95
  "status": 200,
96
96
  "body": { "ok": true, "team_id": "T0123456789" }
97
+ },
98
+ "rotateConfigToken_success": {
99
+ "status": 200,
100
+ "body": {
101
+ "ok": true,
102
+ "token": "xoxb-rotated-access-token",
103
+ "refresh_token": "xoxe-1-rotated-refresh-token",
104
+ "team_id": "T0123456789",
105
+ "user_id": "U0AALR8M69X",
106
+ "iat": 1234567890,
107
+ "exp": 1234571490
108
+ }
109
+ },
110
+ "rotateConfigToken_invalid_refresh_token": {
111
+ "status": 200,
112
+ "body": { "ok": false, "error": "invalid_refresh_token" }
113
+ },
114
+ "rotateConfigToken_token_revoked": {
115
+ "status": 200,
116
+ "body": { "ok": false, "error": "token_revoked" }
117
+ },
118
+ "rotateConfigToken_http_error": {
119
+ "status": 500,
120
+ "body": { "ok": false, "error": "internal_error" }
121
+ },
122
+ "rotateConfigToken_missing_fields": {
123
+ "status": 200,
124
+ "body": {
125
+ "ok": true,
126
+ "token": "xoxb-rotated-access-token"
127
+ }
97
128
  }
98
129
  }
@@ -295,6 +295,94 @@ describe("HttpSlackProvisioningClient — authTest", () => {
295
295
  });
296
296
  });
297
297
 
298
+ // ─── rotateConfigToken ──────────────────────────────────────────────────────
299
+
300
+ describe("HttpSlackProvisioningClient — rotateConfigToken", () => {
301
+ it("POSTs form-encoded refresh_token to tooling.tokens.rotate and returns rotated tokens", async () => {
302
+ const { client, lastRequest } = makeClient("rotateConfigToken_success");
303
+ const result = await client.rotateConfigToken("xoxe-1-test-refresh-token");
304
+
305
+ const req = lastRequest();
306
+ expect(req.method).toBe("POST");
307
+ expect(req.url).toBe("https://slack.com/api/tooling.tokens.rotate");
308
+ expect(req.headers.get("content-type")).toBe(
309
+ "application/x-www-form-urlencoded",
310
+ );
311
+ const params = new URLSearchParams(req.body);
312
+ expect(params.get("refresh_token")).toBe("xoxe-1-test-refresh-token");
313
+
314
+ expect(result).toEqual({
315
+ accessToken: "xoxb-rotated-access-token",
316
+ refreshToken: "xoxe-1-rotated-refresh-token",
317
+ teamId: "T0123456789",
318
+ userId: "U0AALR8M69X",
319
+ iat: 1234567890,
320
+ exp: 1234571490,
321
+ });
322
+ });
323
+
324
+ it("throws SlackConfigTokenError with invalid_refresh_token code when Slack returns that error", async () => {
325
+ const { client } = makeClient("rotateConfigToken_invalid_refresh_token");
326
+ try {
327
+ await client.rotateConfigToken("xoxe-1-test-refresh-token");
328
+ expect.unreachable("Should have thrown");
329
+ } catch (err: unknown) {
330
+ expect(err instanceof Error).toBe(true);
331
+ const error = err as Error;
332
+ expect(error.message).not.toContain("xoxe-1-test-refresh-token");
333
+ if (err && typeof err === "object" && "code" in err) {
334
+ expect((err as any).code).toBe("invalid_refresh_token");
335
+ }
336
+ }
337
+ });
338
+
339
+ it("throws SlackConfigTokenError with token_revoked code when Slack returns that error", async () => {
340
+ const { client } = makeClient("rotateConfigToken_token_revoked");
341
+ try {
342
+ await client.rotateConfigToken("xoxe-1-test-refresh-token");
343
+ expect.unreachable("Should have thrown");
344
+ } catch (err: unknown) {
345
+ expect(err instanceof Error).toBe(true);
346
+ const error = err as Error;
347
+ expect(error.message).not.toContain("xoxe-1-test-refresh-token");
348
+ if (err && typeof err === "object" && "code" in err) {
349
+ expect((err as any).code).toBe("token_revoked");
350
+ }
351
+ }
352
+ });
353
+
354
+ it("throws SlackConfigTokenError with http_error code on HTTP error", async () => {
355
+ const { client } = makeClient("rotateConfigToken_http_error");
356
+ try {
357
+ await client.rotateConfigToken("xoxe-1-test-refresh-token");
358
+ expect.unreachable("Should have thrown");
359
+ } catch (err: unknown) {
360
+ expect(err instanceof Error).toBe(true);
361
+ const error = err as Error;
362
+ expect(error.message).toMatch(/Slack tooling\.tokens\.rotate HTTP error: 500/);
363
+ if (err && typeof err === "object" && "code" in err) {
364
+ expect((err as any).code).toBe("http_error");
365
+ }
366
+ }
367
+ });
368
+
369
+ it("throws SlackConfigTokenError when response is missing required fields", async () => {
370
+ const { client } = makeClient("rotateConfigToken_missing_fields");
371
+ try {
372
+ await client.rotateConfigToken("xoxe-1-test-refresh-token");
373
+ expect.unreachable("Should have thrown");
374
+ } catch (err: unknown) {
375
+ expect(err instanceof Error).toBe(true);
376
+ const error = err as Error;
377
+ expect(error.message).toContain("response missing required fields");
378
+ expect(error.message).not.toContain("xoxe-1-test-refresh-token");
379
+ if (err && typeof err === "object" && "code" in err) {
380
+ expect((err as any).code).toBe("missing_response_fields");
381
+ }
382
+ }
383
+ });
384
+ });
385
+
298
386
  // ─── Default construction (no opts) ─────────────────────────────────────────
299
387
 
300
388
  describe("HttpSlackProvisioningClient — default construction", () => {
@@ -9,6 +9,23 @@
9
9
  * directly in the response — no separate oauth.v2.access exchange needed.
10
10
  */
11
11
 
12
+ // ─── Errors ───────────────────────────────────────────────────────────────────
13
+
14
+ /**
15
+ * Typed error for Slack config token rotation failures.
16
+ * Errors include Slack API errors and HTTP errors.
17
+ * Error messages never contain token values.
18
+ */
19
+ export class SlackConfigTokenError extends Error {
20
+ constructor(
21
+ public readonly code: string,
22
+ message: string,
23
+ ) {
24
+ super(message);
25
+ this.name = "SlackConfigTokenError";
26
+ }
27
+ }
28
+
12
29
  // ─── Types ────────────────────────────────────────────────────────────────────
13
30
 
14
31
  interface AppManifestDisplayInfo {
@@ -112,6 +129,31 @@ export interface SlackProvisioningClient {
112
129
  authTest(botToken: string): Promise<{ userId: string }>;
113
130
  }
114
131
 
132
+ // ─── SlackConfigTokenClient ───────────────────────────────────────────────────
133
+
134
+ /**
135
+ * Client for Slack config token rotation operations.
136
+ * Used to refresh expired or rotating OAuth tokens via tooling.tokens.rotate.
137
+ */
138
+ export interface SlackConfigTokenClient {
139
+ /**
140
+ * Call tooling.tokens.rotate with a refresh token to get a new access token.
141
+ * Returns the new access token, refresh token, team ID, user ID, and timestamps.
142
+ * Throws SlackConfigTokenError on Slack API errors (invalid_refresh_token, token_revoked, etc.)
143
+ * or on HTTP errors.
144
+ */
145
+ rotateConfigToken(
146
+ refreshToken: string,
147
+ ): Promise<{
148
+ accessToken: string;
149
+ refreshToken: string;
150
+ teamId: string;
151
+ userId: string;
152
+ iat: number;
153
+ exp: number;
154
+ }>;
155
+ }
156
+
115
157
  // ─── Agent manifest ───────────────────────────────────────────────────────────
116
158
 
117
159
  /**
@@ -199,7 +241,9 @@ export function buildAgentManifest(
199
241
  *
200
242
  * The constructor takes optional Slack API URL overrides for testing/staging.
201
243
  */
202
- export class HttpSlackProvisioningClient implements SlackProvisioningClient {
244
+ export class HttpSlackProvisioningClient
245
+ implements SlackProvisioningClient, SlackConfigTokenClient
246
+ {
203
247
  private readonly apiBase: string;
204
248
  private readonly fetchFn: typeof fetch;
205
249
 
@@ -408,4 +452,76 @@ export class HttpSlackProvisioningClient implements SlackProvisioningClient {
408
452
  signingSecret: data.credentials.signing_secret,
409
453
  };
410
454
  }
455
+
456
+ async rotateConfigToken(
457
+ refreshToken: string,
458
+ ): Promise<{
459
+ accessToken: string;
460
+ refreshToken: string;
461
+ teamId: string;
462
+ userId: string;
463
+ iat: number;
464
+ exp: number;
465
+ }> {
466
+ const url = `${this.apiBase}/tooling.tokens.rotate`;
467
+ const params = new URLSearchParams({
468
+ refresh_token: refreshToken,
469
+ });
470
+
471
+ const resp = await this.fetchFn(url, {
472
+ method: "POST",
473
+ headers: {
474
+ "Content-Type": "application/x-www-form-urlencoded",
475
+ },
476
+ body: params.toString(),
477
+ });
478
+
479
+ if (!resp.ok) {
480
+ throw new SlackConfigTokenError(
481
+ "http_error",
482
+ `Slack tooling.tokens.rotate HTTP error: ${resp.status} ${resp.statusText}`,
483
+ );
484
+ }
485
+
486
+ const data = (await resp.json()) as {
487
+ ok: boolean;
488
+ error?: string;
489
+ token?: string;
490
+ refresh_token?: string;
491
+ team_id?: string;
492
+ user_id?: string;
493
+ iat?: number;
494
+ exp?: number;
495
+ };
496
+
497
+ if (!data.ok) {
498
+ throw new SlackConfigTokenError(
499
+ data.error ?? "unknown_error",
500
+ `Slack tooling.tokens.rotate failed: ${data.error}`,
501
+ );
502
+ }
503
+
504
+ if (
505
+ !data.token ||
506
+ !data.refresh_token ||
507
+ !data.team_id ||
508
+ !data.user_id ||
509
+ data.iat === undefined ||
510
+ data.exp === undefined
511
+ ) {
512
+ throw new SlackConfigTokenError(
513
+ "missing_response_fields",
514
+ "Slack tooling.tokens.rotate response missing required fields",
515
+ );
516
+ }
517
+
518
+ return {
519
+ accessToken: data.token,
520
+ refreshToken: data.refresh_token,
521
+ teamId: data.team_id,
522
+ userId: data.user_id,
523
+ iat: data.iat,
524
+ exp: data.exp,
525
+ };
526
+ }
411
527
  }