@app-vitals/agent-admin 1.105.0 → 1.106.1

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/src/agents.ts CHANGED
@@ -7,24 +7,29 @@
7
7
  */
8
8
 
9
9
  import { findRepoNameCollisions } from "@app-vitals/agent-lib/clone-plan";
10
- import { resolveDefaultPlugins } from "@app-vitals/agent-lib/default-plugins";
11
10
  import { DEFAULT_AGENT_ENV } from "@app-vitals/agent-lib/default-agent-env";
11
+ import { resolveDefaultPlugins } from "@app-vitals/agent-lib/default-plugins";
12
12
  import { isGithubLogin } from "@app-vitals/agent-lib/github-login";
13
13
  import { isOrgRepo } from "@app-vitals/agent-lib/org-repo";
14
14
  import { SECRET_ENV_VARS } from "@app-vitals/agent-lib/secret-env-vars";
15
15
  import type { PrismaClient } from "../prisma/client/client.ts";
16
16
  import type { AgentAnthropicIdentity } from "./agent-anthropic-identity.ts";
17
- import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
18
17
  import type { AgentCronJobService } from "./agent-cron-jobs.ts";
19
18
  import type { AgentEnvService } from "./agent-envs.ts";
20
19
  import { AgentMemberService } from "./agent-members.ts";
21
20
  import type { AgentPluginService } from "./agent-plugins.ts";
22
21
  import type { AgentProvisioner } from "./agent-provisioner.ts";
22
+ import type { AgentTemplateReconcileService } from "./agent-template-reconcile.ts";
23
23
  import type { AgentToolService } from "./agent-tools.ts";
24
24
  import {
25
25
  ANTHROPIC_CREDENTIALS_BLOCKED_CODE,
26
26
  anthropicCredentialKeysIn,
27
27
  } from "./anthropic-credential-guard.ts";
28
+ import {
29
+ type EnsureAccountMemberResult,
30
+ ensureAccountMember,
31
+ type MemberCreator,
32
+ } from "./ensure-account-member.ts";
28
33
  import type { PrismaTransactionClient } from "./prisma-tx.ts";
29
34
  import type { SpecialtyDefaultsResolver } from "./specialty-defaults.ts";
30
35
  import {
@@ -778,6 +783,12 @@ export interface CreateAgentFormInput {
778
783
  * never touch them.
779
784
  */
780
785
  env?: Record<string, string>;
786
+ /**
787
+ * Who is creating the agent, for member emails that have no AccountMember
788
+ * yet (ensureAccountMember). Service-level input only, resolved from the
789
+ * authenticated principal. Absent: such emails fail instead of being created.
790
+ */
791
+ memberCreator?: MemberCreator;
781
792
  }
782
793
 
783
794
  // Deliberately simple: one @, no whitespace, a dotted domain. Enough to keep
@@ -818,6 +829,8 @@ type CreateAgentErrorCode =
818
829
  | "provision_failed"
819
830
  | "quota_exceeded"
820
831
  | "account_inactive"
832
+ | "member_account_unresolved"
833
+ | "member_not_permitted"
821
834
  | typeof ANTHROPIC_CREDENTIALS_BLOCKED_CODE;
822
835
 
823
836
  type CreateAgentResult =
@@ -906,6 +919,15 @@ async function checkAccountQuota(
906
919
  return count >= account.maxAgents ? "quota_exceeded" : null;
907
920
  }
908
921
 
922
+ /** Thrown inside the create transaction so a member failure rolls everything back. */
923
+ class MemberEnsureFailure extends Error {
924
+ constructor(
925
+ public readonly failure: Extract<EnsureAccountMemberResult, { ok: false }>,
926
+ ) {
927
+ super(failure.message);
928
+ }
929
+ }
930
+
909
931
  /** Discriminated outcome of the transactional portion of createAgent(). */
910
932
  type CreateAgentTxOutcome =
911
933
  | { ok: true; agent: AgentDetail; seededEnvKeys: Set<string> }
@@ -999,162 +1021,194 @@ export async function createAgent(
999
1021
  const restrictSlackToMembers = input.restrictSlackToMembersRaw === "true";
1000
1022
  const ownerEmail = input.ownerEmail?.trim().toLowerCase() || undefined;
1001
1023
 
1002
- const txResult = await deps.agentService.runTransaction<CreateAgentTxOutcome>(
1003
- async (tx) => {
1004
- // Quota enforcement must precede the create so a rejected request
1005
- // writes nothing. Skipped when tx is undefined (admin-ui.ts test
1006
- // doubles without runTransaction pass no real transaction).
1007
- if (input.accountId !== undefined && tx) {
1008
- const denied = await checkAccountQuota(tx, input.accountId);
1009
- if (denied) return { ok: false, errorCode: denied };
1010
- }
1011
-
1012
- const agent = await deps.agentService.create(
1013
- {
1014
- name,
1015
- selfHosted: !inCluster,
1016
- specialty,
1017
- restrictSlackToMembers,
1018
- ...(input.accountId !== undefined
1019
- ? { accountId: input.accountId }
1020
- : {}),
1021
- ...(ownerEmail !== undefined ? { ownerEmail } : {}),
1022
- ...(input.templateDetached ? { templateDetached: true } : {}),
1023
- },
1024
- tx,
1025
- );
1024
+ let txResult: CreateAgentTxOutcome;
1025
+ try {
1026
+ txResult = await deps.agentService.runTransaction<CreateAgentTxOutcome>(
1027
+ async (tx) => {
1028
+ // Quota enforcement must precede the create so a rejected request
1029
+ // writes nothing. Skipped when tx is undefined (admin-ui.ts test
1030
+ // doubles without runTransaction pass no real transaction).
1031
+ if (input.accountId !== undefined && tx) {
1032
+ const denied = await checkAccountQuota(tx, input.accountId);
1033
+ if (denied) return { ok: false, errorCode: denied };
1034
+ }
1035
+
1036
+ const agent = await deps.agentService.create(
1037
+ {
1038
+ name,
1039
+ selfHosted: !inCluster,
1040
+ specialty,
1041
+ restrictSlackToMembers,
1042
+ ...(input.accountId !== undefined
1043
+ ? { accountId: input.accountId }
1044
+ : {}),
1045
+ ...(ownerEmail !== undefined ? { ownerEmail } : {}),
1046
+ ...(input.templateDetached ? { templateDetached: true } : {}),
1047
+ },
1048
+ tx,
1049
+ );
1026
1050
 
1027
- // Seed AgentTool/AgentPlugin rows from the extension's defaults, else
1028
- // the type's tools floor. Roll the agent row back on any seeding
1029
- // failure so a retry with the same name doesn't collide with a
1030
- // half-seeded agent. Members/repos have their own dedicated handling
1031
- // below.
1032
- //
1033
- // ATP-2.2: an attached agent takes the resolved template (specialty
1034
- // defaults + deployment/account layers) from the reconcile engine in
1035
- // this same transaction; a detached agent (or a deployment without the
1036
- // engine) gets the built-in specialty defaults copied directly.
1037
- const seededEnvKeys = new Set<string>();
1038
- try {
1039
- if (deps.templateReconcile && !input.templateDetached) {
1040
- await deps.templateReconcile.reconcile(agent.id, tx);
1041
- if (tx) {
1042
- const rows = await tx.agentEnv.findMany({
1043
- where: { agentId: agent.id },
1044
- select: { key: true },
1045
- });
1046
- for (const r of rows) seededEnvKeys.add(r.key);
1051
+ // Seed AgentTool/AgentPlugin rows from the extension's defaults, else
1052
+ // the type's tools floor. Roll the agent row back on any seeding
1053
+ // failure so a retry with the same name doesn't collide with a
1054
+ // half-seeded agent. Members/repos have their own dedicated handling
1055
+ // below.
1056
+ //
1057
+ // ATP-2.2: an attached agent takes the resolved template (specialty
1058
+ // defaults + deployment/account layers) from the reconcile engine in
1059
+ // this same transaction; a detached agent (or a deployment without the
1060
+ // engine) gets the built-in specialty defaults copied directly.
1061
+ const seededEnvKeys = new Set<string>();
1062
+ try {
1063
+ if (deps.templateReconcile && !input.templateDetached) {
1064
+ await deps.templateReconcile.reconcile(agent.id, tx);
1065
+ if (tx) {
1066
+ const rows = await tx.agentEnv.findMany({
1067
+ where: { agentId: agent.id },
1068
+ select: { key: true },
1069
+ });
1070
+ for (const r of rows) seededEnvKeys.add(r.key);
1071
+ }
1072
+ } else {
1073
+ for (const pattern of extensionDefaults?.tools ??
1074
+ type?.tools ??
1075
+ []) {
1076
+ await deps.agentToolService.add(agent.id, pattern, tx);
1077
+ }
1078
+ for (const pluginName of resolveDefaultPlugins(
1079
+ extensionDefaults?.plugins,
1080
+ )) {
1081
+ await deps.agentPluginService.add(
1082
+ agent.id,
1083
+ pluginName,
1084
+ undefined,
1085
+ tx,
1086
+ );
1087
+ }
1047
1088
  }
1048
- } else {
1049
- for (const pattern of extensionDefaults?.tools ?? type?.tools ?? []) {
1050
- await deps.agentToolService.add(agent.id, pattern, tx);
1089
+ } catch (err) {
1090
+ console.error(
1091
+ "[agents] createAgent: tool/plugin seeding failed, rolling back:",
1092
+ err,
1093
+ );
1094
+ await deps.agentService.delete(agent.id, tx).catch((cleanupErr) => {
1095
+ console.error(
1096
+ "[agents] createAgent: failed to roll back agent after seeding error:",
1097
+ cleanupErr,
1098
+ );
1099
+ });
1100
+ return { ok: false, errorCode: "seed_failed" };
1101
+ }
1102
+
1103
+ // Attach repos if provided.
1104
+ if (input.reposRaw) {
1105
+ const repos = parseLines(input.reposRaw);
1106
+ const invalid = repos.filter((r) => !isOrgRepo(r));
1107
+ if (invalid.length > 0) {
1108
+ await deps.agentService.delete(agent.id, tx);
1109
+ return { ok: false, errorCode: "invalid_repo_format" };
1110
+ }
1111
+ const collision = describeRepoNameCollision(repos);
1112
+ if (collision) {
1113
+ await deps.agentService.delete(agent.id, tx);
1114
+ return {
1115
+ ok: false,
1116
+ errorCode: "repo_name_collision",
1117
+ errorMessage: collision,
1118
+ };
1051
1119
  }
1052
- for (const pluginName of resolveDefaultPlugins(
1053
- extensionDefaults?.plugins,
1054
- )) {
1055
- await deps.agentPluginService.add(
1120
+ if (repos.length > 0) {
1121
+ await deps.agentService.updateFields(agent.id, { repos }, tx);
1122
+ }
1123
+ }
1124
+
1125
+ // Attach authorAllowlist if provided.
1126
+ if (input.authorAllowlistRaw) {
1127
+ const authorAllowlist = parseLines(input.authorAllowlistRaw, {
1128
+ dedup: true,
1129
+ });
1130
+ const invalid = authorAllowlist.filter((l) => !isGithubLogin(l));
1131
+ if (invalid.length > 0) {
1132
+ await deps.agentService.delete(agent.id, tx);
1133
+ return { ok: false, errorCode: "invalid_author_allowlist_format" };
1134
+ }
1135
+ if (authorAllowlist.length > 0) {
1136
+ await deps.agentService.updateFields(
1056
1137
  agent.id,
1057
- pluginName,
1058
- undefined,
1138
+ { reviewAuthorAllowlist: authorAllowlist },
1059
1139
  tx,
1060
1140
  );
1061
1141
  }
1062
1142
  }
1063
- } catch (err) {
1064
- console.error(
1065
- "[agents] createAgent: tool/plugin seeding failed, rolling back:",
1066
- err,
1067
- );
1068
- await deps.agentService.delete(agent.id, tx).catch((cleanupErr) => {
1069
- console.error(
1070
- "[agents] createAgent: failed to roll back agent after seeding error:",
1071
- cleanupErr,
1072
- );
1073
- });
1074
- return { ok: false, errorCode: "seed_failed" };
1075
- }
1076
-
1077
- // Attach repos if provided.
1078
- if (input.reposRaw) {
1079
- const repos = parseLines(input.reposRaw);
1080
- const invalid = repos.filter((r) => !isOrgRepo(r));
1081
- if (invalid.length > 0) {
1082
- await deps.agentService.delete(agent.id, tx);
1083
- return { ok: false, errorCode: "invalid_repo_format" };
1084
- }
1085
- const collision = describeRepoNameCollision(repos);
1086
- if (collision) {
1087
- await deps.agentService.delete(agent.id, tx);
1088
- return {
1089
- ok: false,
1090
- errorCode: "repo_name_collision",
1091
- errorMessage: collision,
1092
- };
1093
- }
1094
- if (repos.length > 0) {
1095
- await deps.agentService.updateFields(agent.id, { repos }, tx);
1096
- }
1097
- }
1098
-
1099
- // Attach authorAllowlist if provided.
1100
- if (input.authorAllowlistRaw) {
1101
- const authorAllowlist = parseLines(input.authorAllowlistRaw, {
1102
- dedup: true,
1103
- });
1104
- const invalid = authorAllowlist.filter((l) => !isGithubLogin(l));
1105
- if (invalid.length > 0) {
1106
- await deps.agentService.delete(agent.id, tx);
1107
- return { ok: false, errorCode: "invalid_author_allowlist_format" };
1108
- }
1109
- if (authorAllowlist.length > 0) {
1110
- await deps.agentService.updateFields(
1111
- agent.id,
1112
- { reviewAuthorAllowlist: authorAllowlist },
1113
- tx,
1114
- );
1115
- }
1116
- }
1117
-
1118
- // Attach patchAuthorAllowlist if provided.
1119
- if (input.patchAuthorAllowlistRaw) {
1120
- const patchAuthorAllowlist = parseLines(input.patchAuthorAllowlistRaw, {
1121
- dedup: true,
1122
- });
1123
- const invalid = patchAuthorAllowlist.filter((l) => !isGithubLogin(l));
1124
- if (invalid.length > 0) {
1125
- await deps.agentService.delete(agent.id, tx);
1126
- return { ok: false, errorCode: "invalid_author_allowlist_format" };
1127
- }
1128
- if (patchAuthorAllowlist.length > 0) {
1129
- await deps.agentService.updateFields(
1130
- agent.id,
1131
- { patchAuthorAllowlist },
1132
- tx,
1143
+
1144
+ // Attach patchAuthorAllowlist if provided.
1145
+ if (input.patchAuthorAllowlistRaw) {
1146
+ const patchAuthorAllowlist = parseLines(
1147
+ input.patchAuthorAllowlistRaw,
1148
+ {
1149
+ dedup: true,
1150
+ },
1133
1151
  );
1152
+ const invalid = patchAuthorAllowlist.filter((l) => !isGithubLogin(l));
1153
+ if (invalid.length > 0) {
1154
+ await deps.agentService.delete(agent.id, tx);
1155
+ return { ok: false, errorCode: "invalid_author_allowlist_format" };
1156
+ }
1157
+ if (patchAuthorAllowlist.length > 0) {
1158
+ await deps.agentService.updateFields(
1159
+ agent.id,
1160
+ { patchAuthorAllowlist },
1161
+ tx,
1162
+ );
1163
+ }
1134
1164
  }
1135
- }
1136
-
1137
- // Attach member emails if provided — best-effort, mirrors the
1138
- // single-add POST /admin/agents/:id/members route: no format
1139
- // validation, and a failed/duplicate add is silently ignored rather
1140
- // than rolling back the agent.
1141
- if (input.memberEmailsRaw) {
1142
- const memberEmails = parseLines(input.memberEmailsRaw, {
1143
- lower: true,
1144
- dedup: true,
1145
- });
1146
- for (const email of memberEmails) {
1147
- try {
1148
- await deps.agentMemberService.add(agent.id, email, tx);
1149
- } catch {
1150
- // unique constraint violation — already a member, ignore
1165
+
1166
+ // Attach member emails if provided. Each email first gets an
1167
+ // AccountMember (ensureAccountMember: reused if present, else created
1168
+ // under the account rule when the creator may). A failure throws so the
1169
+ // whole transaction, agent and any records created for earlier emails
1170
+ // included, rolls back. No format validation (mirrors the single-add
1171
+ // route); a duplicate add is ignored.
1172
+ if (input.memberEmailsRaw) {
1173
+ const memberEmails = parseLines(input.memberEmailsRaw, {
1174
+ lower: true,
1175
+ dedup: true,
1176
+ });
1177
+ for (const email of memberEmails) {
1178
+ if (tx) {
1179
+ const ensured = await ensureAccountMember(tx, {
1180
+ email,
1181
+ agentAccountId: input.accountId ?? null,
1182
+ ...(input.memberCreator
1183
+ ? { creator: input.memberCreator }
1184
+ : {}),
1185
+ });
1186
+ if (!ensured.ok) throw new MemberEnsureFailure(ensured);
1187
+ }
1188
+ try {
1189
+ await deps.agentMemberService.add(agent.id, email, tx);
1190
+ } catch {
1191
+ // unique constraint violation — already a member, ignore
1192
+ }
1151
1193
  }
1152
1194
  }
1153
- }
1154
1195
 
1155
- return { ok: true, agent, seededEnvKeys };
1156
- },
1157
- );
1196
+ return { ok: true, agent, seededEnvKeys };
1197
+ },
1198
+ );
1199
+ } catch (err) {
1200
+ if (err instanceof MemberEnsureFailure) {
1201
+ return {
1202
+ ok: false,
1203
+ errorCode:
1204
+ err.failure.code === "not_permitted"
1205
+ ? "member_not_permitted"
1206
+ : "member_account_unresolved",
1207
+ errorMessage: err.failure.message,
1208
+ };
1209
+ }
1210
+ throw err;
1211
+ }
1158
1212
 
1159
1213
  if (!txResult.ok) {
1160
1214
  return {