@agent-native/core 0.203.1 → 0.204.0-nightly-20261008011018

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 (95) hide show
  1. package/dist/a2a/handlers.js +57 -1
  2. package/dist/a2a/server.js +37 -1
  3. package/dist/action.js +22 -1
  4. package/dist/agent/contain-principal.d.ts +9 -0
  5. package/dist/agent/contain-principal.js +53 -0
  6. package/dist/agent/production-agent.js +32 -2
  7. package/dist/agent/run-manager.js +14 -2
  8. package/dist/agent/run-store.js +66 -12
  9. package/dist/agent/thread-message-projection.d.ts +1 -0
  10. package/dist/agent/thread-message-projection.js +56 -6
  11. package/dist/audit/actions/export-audit-events.d.ts +1 -1
  12. package/dist/audit/actions/export-audit-events.js +2 -2
  13. package/dist/audit/actions/export-audit-ocsf.d.ts +11 -0
  14. package/dist/audit/actions/export-audit-ocsf.js +183 -0
  15. package/dist/audit/actions/list-audit-events.d.ts +1 -1
  16. package/dist/audit/actions/list-audit-events.js +3 -3
  17. package/dist/audit/config.d.ts +1 -1
  18. package/dist/audit/config.js +5 -1
  19. package/dist/audit/index.d.ts +1 -0
  20. package/dist/audit/index.js +1 -0
  21. package/dist/audit/ocsf.d.ts +70 -0
  22. package/dist/audit/ocsf.js +228 -0
  23. package/dist/audit/record.js +1 -1
  24. package/dist/audit/store.js +9 -2
  25. package/dist/audit/types.d.ts +12 -1
  26. package/dist/cli/connect.js +7 -2
  27. package/dist/client/chat/agentkit-agent-native.js +104 -24
  28. package/dist/coding-tools/run-code.js +22 -1
  29. package/dist/coding-tools/sandbox/local-child-process-adapter.js +20 -0
  30. package/dist/collab/awareness.d.ts +2 -2
  31. package/dist/collab/routes.d.ts +2 -2
  32. package/dist/file-upload/builder.js +18 -4
  33. package/dist/framework-tools.js +3 -0
  34. package/dist/identity/rekey.js +6 -0
  35. package/dist/localization/core-messages/supplemental/ar-SA.js +15 -0
  36. package/dist/localization/core-messages/supplemental/de-DE.js +15 -0
  37. package/dist/localization/core-messages/supplemental/en-US.js +15 -0
  38. package/dist/localization/core-messages/supplemental/es-ES.js +15 -0
  39. package/dist/localization/core-messages/supplemental/fr-FR.js +15 -0
  40. package/dist/localization/core-messages/supplemental/hi-IN.js +15 -0
  41. package/dist/localization/core-messages/supplemental/ja-JP.js +15 -0
  42. package/dist/localization/core-messages/supplemental/ko-KR.js +15 -0
  43. package/dist/localization/core-messages/supplemental/pt-BR.js +15 -0
  44. package/dist/localization/core-messages/supplemental/zh-CN.js +15 -0
  45. package/dist/localization/core-messages/supplemental/zh-TW.js +15 -0
  46. package/dist/localization/mcp-settings-messages.d.ts +15 -0
  47. package/dist/mcp/actions/create-org-service-token.d.ts +8 -0
  48. package/dist/mcp/actions/create-org-service-token.js +92 -4
  49. package/dist/mcp/actions/list-org-service-tokens.d.ts +2 -0
  50. package/dist/mcp/actions/list-org-service-tokens.js +36 -8
  51. package/dist/mcp/actions/service-principal-input.d.ts +48 -0
  52. package/dist/mcp/actions/service-principal-input.js +102 -0
  53. package/dist/mcp/actions/set-service-principal-lifecycle.d.ts +15 -0
  54. package/dist/mcp/actions/set-service-principal-lifecycle.js +150 -0
  55. package/dist/mcp/actions/set-service-principal-policy.d.ts +14 -0
  56. package/dist/mcp/actions/set-service-principal-policy.js +105 -0
  57. package/dist/mcp/build-server.js +105 -4
  58. package/dist/mcp/connect-route.js +116 -4
  59. package/dist/mcp/connect-store.d.ts +7 -0
  60. package/dist/mcp/connect-store.js +21 -14
  61. package/dist/observability/routes.d.ts +4 -4
  62. package/dist/observability/store.js +11 -5
  63. package/dist/observability/traces.js +6 -0
  64. package/dist/observability/types.d.ts +2 -0
  65. package/dist/org/index.d.ts +2 -2
  66. package/dist/org/service-principal-guard.d.ts +64 -0
  67. package/dist/org/service-principal-guard.js +140 -0
  68. package/dist/org/service-principal-policy.d.ts +104 -0
  69. package/dist/org/service-principal-policy.js +272 -0
  70. package/dist/provider-api/actions/custom-provider-registration.d.ts +2 -2
  71. package/dist/provider-api/actions/provider-api.d.ts +13 -13
  72. package/dist/resources/handlers.d.ts +1 -1
  73. package/dist/server/action-discovery.js +12 -0
  74. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  75. package/dist/server/agent-engine-default-model-route.d.ts +1 -1
  76. package/dist/server/core-routes-plugin.js +39 -12
  77. package/dist/server/realtime-token.d.ts +1 -1
  78. package/dist/server/release-schema.js +4 -0
  79. package/dist/sharing/actions/list-resource-shares.d.ts +1 -1
  80. package/dist/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +59 -70
  81. package/dist/templates/factory/.agents/skills/review-latest-feedback/references/reproduction-and-verification.md +46 -0
  82. package/dist/templates/factory/.agents/skills/review-latest-feedback/references/slack-reaction-replies.md +33 -0
  83. package/dist/templates/factory/.agents/skills/review-prs/SKILL.md +5 -3
  84. package/dist/triggers/actions/manage-automation.d.ts +2 -2
  85. package/dist/vite/client.js +1 -0
  86. package/docs/content/audit-log.mdx +15 -0
  87. package/docs/content/http-api.mdx +21 -2
  88. package/docs/content/pr-visual-recap.mdx +3 -1
  89. package/docs/content/template-clips-embed.mdx +1 -1
  90. package/docs/content/turn-into-app.mdx +118 -0
  91. package/package.json +4 -4
  92. package/src/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +59 -70
  93. package/src/templates/factory/.agents/skills/review-latest-feedback/references/reproduction-and-verification.md +46 -0
  94. package/src/templates/factory/.agents/skills/review-latest-feedback/references/slack-reaction-replies.md +33 -0
  95. package/src/templates/factory/.agents/skills/review-prs/SKILL.md +5 -3
@@ -41,6 +41,21 @@ export interface McpConnectMessages {
41
41
  couldNotCreate: string;
42
42
  networkError: string;
43
43
  urlTitle: string;
44
+ servicePrincipals: string;
45
+ principalUngoverned: string;
46
+ principalActive: string;
47
+ principalSuspended: string;
48
+ principalRetired: string;
49
+ principalUngovernedHint: string;
50
+ principalOwner: string;
51
+ principalRisk: string;
52
+ riskLow: string;
53
+ riskMedium: string;
54
+ riskHigh: string;
55
+ suspend: string;
56
+ resume: string;
57
+ couldNotUpdatePrincipal: string;
58
+ containmentIncomplete: string;
44
59
  }
45
60
  export declare const MCP_CONNECT_MESSAGES: Record<BuiltinLocaleCode, McpConnectMessages>;
46
61
  export interface McpSettingsMessages {
@@ -1,6 +1,11 @@
1
1
  declare const _default: import("../../action.js").ActionDefinition<{
2
2
  name: string;
3
3
  ttlDays?: number;
4
+ ownerEmail?: string;
5
+ team?: string;
6
+ riskTier?: "high" | "low" | "medium";
7
+ purpose?: string;
8
+ allowedActions?: string[];
4
9
  }, {
5
10
  token: string;
6
11
  id: string;
@@ -8,6 +13,9 @@ declare const _default: import("../../action.js").ActionDefinition<{
8
13
  serviceEmail: string;
9
14
  orgId: string;
10
15
  ttlDays: number;
16
+ ownerEmail: string;
17
+ riskTier: "high" | "low" | "medium";
18
+ allowedActions: string[];
11
19
  note: string;
12
20
  }>;
13
21
  export default _default;
@@ -14,17 +14,27 @@
14
14
  * never a prompt-injection target.
15
15
  * - Revocable via `revoke-org-service-token` — same `revoked_at` gate the
16
16
  * personal-token revocation path uses.
17
+ *
18
+ * GOVERNANCE: every mint leaves the principal governed. A name with no policy
19
+ * row gets one (owner defaults to the creating admin, riskTier medium,
20
+ * allowedActions null = unrestricted); an existing policy only changes the
21
+ * fields passed explicitly. A suspended or retired name is refused, since a
22
+ * token minted for it could never authenticate.
17
23
  */
18
24
  import { z } from "zod";
19
25
  import { defineAction } from "../../action.js";
26
+ import { orgAdminAudit } from "../../audit/org-admin.js";
27
+ import { getServicePrincipalPolicy, upsertServicePrincipalPolicy, } from "../../org/service-principal-policy.js";
20
28
  import { getAppProductionUrl } from "../../server/app-url.js";
21
29
  import { CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE } from "../../server/credential-membership-unavailable.js";
22
30
  import { getRequestContext } from "../../server/request-context.js";
23
31
  import { mintOrgServiceToken } from "../connect-route.js";
32
+ import { MAX_SERVICE_TOKEN_TTL_DAYS, revokeOrgServiceToken, } from "../connect-store.js";
24
33
  import { McpCredentialIssuanceError } from "../credential-issuance.js";
34
+ import { allowedActionsSchema, assertOwnerIsOrgMember, normalizeAllowedActions, ownerEmailSchema, parseServiceName, purposeSchema, riskTierSchema, teamSchema, } from "./service-principal-input.js";
25
35
  import { requireServiceTokenCaller, SERVICE_TOKEN_MANAGE_FORBIDDEN_MESSAGE, ServiceTokenError, } from "./service-token-access.js";
26
36
  export default defineAction({
27
- description: "Create a named, org-scoped service token (for CI like PR Visual Recap's PLAN_RECAP_TOKEN). The token acts as a service principal owned by the organization, not a person. Org owner/admin only. The token value is returned ONCE and never stored — copy it immediately.",
37
+ description: "Create a named, org-scoped service token (for CI like PR Visual Recap's PLAN_RECAP_TOKEN). The token acts as a service principal owned by the organization, not a person. Org owner/admin only. The token value is returned ONCE and never stored — copy it immediately. The principal is created governed: owner defaults to you, risk tier to medium, allowedActions to null (unrestricted); pass ownerEmail/team/riskTier/purpose/allowedActions to set them at birth. Refused when the name is suspended or retired.",
28
38
  schema: z.object({
29
39
  name: z
30
40
  .string()
@@ -35,17 +45,56 @@ export default defineAction({
35
45
  .number()
36
46
  .int()
37
47
  .min(1)
38
- .max(365)
48
+ .max(MAX_SERVICE_TOKEN_TTL_DAYS)
39
49
  .optional()
40
- .describe("Token lifetime in days (1-365, default 365)"),
50
+ .describe("Token lifetime in days (1-3650, default 365)"),
51
+ ownerEmail: ownerEmailSchema.optional(),
52
+ team: teamSchema.optional(),
53
+ riskTier: riskTierSchema.optional(),
54
+ purpose: purposeSchema.optional(),
55
+ allowedActions: allowedActionsSchema.nullable().optional(),
41
56
  }),
42
57
  toolCallable: false,
58
+ audit: orgAdminAudit({
59
+ targetType: "service-principal",
60
+ targetId: (_args, result) => result?.serviceName,
61
+ recordInputs: false,
62
+ summary: () => "Created or re-minted an organization service token.",
63
+ }),
43
64
  run: async (args, ctx) => {
44
65
  const caller = await requireServiceTokenCaller({
45
66
  userEmail: ctx?.userEmail,
46
67
  orgId: ctx?.orgId,
47
68
  level: "manage",
48
69
  });
70
+ const serviceName = parseServiceName(args.name);
71
+ let existing;
72
+ try {
73
+ existing = await getServicePrincipalPolicy(caller.orgId, serviceName);
74
+ }
75
+ catch (error) {
76
+ console.error("[service-principal] Policy lookup failed:", error);
77
+ throw new ServiceTokenError("Could not read service principal governance. Try again.", 503);
78
+ }
79
+ if (existing && existing.lifecycle !== "active") {
80
+ throw new ServiceTokenError(`Service principal "${serviceName}" is ${existing.lifecycle}. Resume it with set-service-principal-lifecycle before minting a token.`, 409);
81
+ }
82
+ const policyInput = {};
83
+ if (args.ownerEmail !== undefined) {
84
+ policyInput.ownerEmail = await assertOwnerIsOrgMember(caller.orgId, args.ownerEmail);
85
+ }
86
+ else if (!existing?.ownerEmail) {
87
+ policyInput.ownerEmail = caller.email.toLowerCase();
88
+ }
89
+ if (args.team !== undefined)
90
+ policyInput.team = args.team;
91
+ if (args.riskTier !== undefined)
92
+ policyInput.riskTier = args.riskTier;
93
+ if (args.purpose !== undefined)
94
+ policyInput.purpose = args.purpose;
95
+ if (args.allowedActions !== undefined) {
96
+ policyInput.allowedActions = normalizeAllowedActions(args.allowedActions);
97
+ }
49
98
  const appUrl = (getRequestContext()?.requestOrigin || getAppProductionUrl()).replace(/\/+$/, "");
50
99
  if (!appUrl && !process.env.A2A_SECRET?.trim()) {
51
100
  throw new ServiceTokenError("Could not determine the app URL needed to mint a token. Set APP_URL on the deployment.", 500);
@@ -53,7 +102,7 @@ export default defineAction({
53
102
  let minted;
54
103
  try {
55
104
  minted = await mintOrgServiceToken({
56
- serviceName: args.name,
105
+ serviceName,
57
106
  orgId: caller.orgId,
58
107
  createdBy: caller.email,
59
108
  ttlDays: args.ttlDays,
@@ -67,6 +116,42 @@ export default defineAction({
67
116
  ? new ServiceTokenError(SERVICE_TOKEN_MANAGE_FORBIDDEN_MESSAGE, 403)
68
117
  : new ServiceTokenError(CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE, 503);
69
118
  }
119
+ // Governance is written after the mint so a rejected mint leaves no orphan
120
+ // policy; a failed write revokes the token rather than leaving a live
121
+ // credential that nobody is accountable for.
122
+ let policy;
123
+ try {
124
+ policy = await upsertServicePrincipalPolicy(caller.orgId, minted.serviceName, policyInput);
125
+ }
126
+ catch (error) {
127
+ console.error("[service-principal] Policy write failed:", error);
128
+ let revoked = false;
129
+ try {
130
+ revoked = await revokeOrgServiceToken(caller.orgId, minted.id);
131
+ }
132
+ catch (revokeError) {
133
+ console.error("[service-principal] Revoke after failure:", revokeError);
134
+ }
135
+ throw new ServiceTokenError(revoked
136
+ ? "Could not record the service principal's governance, so the new token was revoked. Try again."
137
+ : `Could not record the service principal's governance AND could not revoke token ${minted.id}. Revoke it with revoke-org-service-token.`, 503);
138
+ }
139
+ // Retirement can finish revoking existing tokens after the initial
140
+ // lifecycle check but before this mint is recorded. The upsert returns the
141
+ // persisted lifecycle; contain this token before ever returning its secret.
142
+ if (policy.lifecycle !== "active") {
143
+ let revoked = false;
144
+ try {
145
+ revoked = await revokeOrgServiceToken(caller.orgId, minted.id);
146
+ }
147
+ catch (error) {
148
+ console.error("[service-principal] Revoke after lifecycle change:", error);
149
+ }
150
+ if (!revoked) {
151
+ throw new ServiceTokenError(`Service principal "${serviceName}" became ${policy.lifecycle} while minting, and token ${minted.id} could not be revoked. Revoke it with revoke-org-service-token.`, 503);
152
+ }
153
+ throw new ServiceTokenError(`Service principal "${serviceName}" became ${policy.lifecycle} while minting. The new token was revoked; resume it before minting again.`, 409);
154
+ }
70
155
  return {
71
156
  // The ONLY place the secret ever appears. Never stored, never logged.
72
157
  token: minted.token,
@@ -75,6 +160,9 @@ export default defineAction({
75
160
  serviceEmail: minted.serviceEmail,
76
161
  orgId: caller.orgId,
77
162
  ttlDays: minted.ttlDays,
163
+ ownerEmail: policy.ownerEmail,
164
+ riskTier: policy.riskTier,
165
+ allowedActions: policy.allowedActions,
78
166
  note: "Store this token now (e.g. as the PLAN_RECAP_TOKEN GitHub Actions secret). It will not be shown again. Revoke it any time with revoke-org-service-token.",
79
167
  };
80
168
  },
@@ -2,6 +2,7 @@ declare const _default: import("../../action.js").ActionDefinition<{
2
2
  includeRevoked?: boolean;
3
3
  }, {
4
4
  orgId: string;
5
+ canManage: boolean;
5
6
  tokens: {
6
7
  id: string;
7
8
  serviceName: string;
@@ -12,5 +13,6 @@ declare const _default: import("../../action.js").ActionDefinition<{
12
13
  lastUsedAt: number;
13
14
  revokedAt: number;
14
15
  }[];
16
+ principals: import("./service-principal-input.js").ServicePrincipalView[];
15
17
  }>;
16
18
  export default _default;
@@ -1,15 +1,18 @@
1
1
  /**
2
- * List the active org service tokens — metadata only (name, who minted it,
3
- * created/last-used/revoked timestamps). Token values are never stored, so
4
- * they can never appear here. Any org member may list; minting and revoking
5
- * are owner/admin-gated.
2
+ * List the org service tokens — metadata only (name, who minted it,
3
+ * created/last-used/revoked timestamps) — and the governed principals they
4
+ * belong to (state, owner, risk tier, grant). Token values are never stored, so
5
+ * they can never appear here. Any org member may list; minting, revoking and
6
+ * governance changes are owner/admin-gated.
6
7
  */
7
8
  import { z } from "zod";
8
9
  import { defineAction } from "../../action.js";
10
+ import { listServicePrincipalPolicies } from "../../org/service-principal-policy.js";
9
11
  import { listOrgServiceTokens } from "../connect-store.js";
10
- import { requireServiceTokenCaller } from "./service-token-access.js";
12
+ import { describeServicePrincipal } from "./service-principal-input.js";
13
+ import { requireServiceTokenCaller, ServiceTokenError, } from "./service-token-access.js";
11
14
  export default defineAction({
12
- description: "List your organization's service tokens (CI credentials such as PLAN_RECAP_TOKEN): name, who created them, created/last-used times, and revocation state. Token values are never stored and never shown. Any org member can list.",
15
+ description: "List your organization's service tokens (CI credentials such as PLAN_RECAP_TOKEN): name, who created them, created/last-used times, and revocation state. Also returns `principals`: one row per service name (from tokens and governance records) with state (ungoverned = no owner/grant set, active, suspended, retired), owner, team, risk tier, purpose, allowedActions (null = unrestricted) and lifecycle history. Token values are never stored and never shown. Any org member can list.",
13
16
  schema: z.object({
14
17
  includeRevoked: z
15
18
  .boolean()
@@ -23,7 +26,19 @@ export default defineAction({
23
26
  orgId: ctx?.orgId,
24
27
  level: "read",
25
28
  });
26
- const rows = await listOrgServiceTokens(caller.orgId);
29
+ let rows;
30
+ let policies;
31
+ try {
32
+ [rows, policies] = await Promise.all([
33
+ listOrgServiceTokens(caller.orgId),
34
+ listServicePrincipalPolicies(caller.orgId),
35
+ ]);
36
+ }
37
+ catch (error) {
38
+ // An unreadable policy table must not render every principal "ungoverned".
39
+ console.error("[service-principal] Listing failed:", error);
40
+ throw new ServiceTokenError("Could not read service principal governance. Try again.", 503);
41
+ }
27
42
  const tokens = rows
28
43
  .filter((row) => args.includeRevoked || row.revokedAt == null)
29
44
  .map((row) => ({
@@ -36,6 +51,19 @@ export default defineAction({
36
51
  lastUsedAt: row.lastUsedAt,
37
52
  revokedAt: row.revokedAt,
38
53
  }));
39
- return { orgId: caller.orgId, tokens };
54
+ const policyByName = new Map(policies.map((p) => [p.serviceName, p]));
55
+ const names = new Set(policyByName.keys());
56
+ for (const row of rows)
57
+ if (row.serviceName)
58
+ names.add(row.serviceName);
59
+ const principals = [...names]
60
+ .sort()
61
+ .map((name) => describeServicePrincipal(caller.orgId, name, policyByName.get(name)));
62
+ return {
63
+ orgId: caller.orgId,
64
+ canManage: caller.role !== "member",
65
+ tokens,
66
+ principals,
67
+ };
40
68
  },
41
69
  });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Governance input shared by `create-org-service-token` and
3
+ * `set-service-principal-policy`, so a principal is validated the same way
4
+ * whether it is born governed or tightened later.
5
+ */
6
+ import { z } from "zod";
7
+ import { type ServicePrincipalLifecycle, type ServicePrincipalPolicy, type ServicePrincipalRiskTier } from "../../org/service-principal-policy.js";
8
+ export declare const MAX_ALLOWED_ACTIONS = 200;
9
+ export declare const riskTierSchema: z.ZodEnum<{
10
+ high: "high";
11
+ low: "low";
12
+ medium: "medium";
13
+ }>;
14
+ export declare const allowedActionsSchema: z.ZodArray<z.ZodString>;
15
+ export declare const ownerEmailSchema: z.ZodString;
16
+ export declare const teamSchema: z.ZodString;
17
+ export declare const purposeSchema: z.ZodString;
18
+ /** Dedupe so the stored grant (and its audited count) has no repeats. */
19
+ export declare function normalizeAllowedActions(allowed: string[] | null | undefined): string[] | null | undefined;
20
+ /**
21
+ * The owner must be a person in this org. A service identity is refused by
22
+ * name so the answer is a clear 400 rather than a membership miss, and an
23
+ * unreadable membership store is a 503, never "not a member".
24
+ */
25
+ export declare function assertOwnerIsOrgMember(orgId: string, ownerEmail: string): Promise<string>;
26
+ export interface ServicePrincipalView {
27
+ serviceName: string;
28
+ serviceEmail: string;
29
+ state: "ungoverned" | ServicePrincipalLifecycle;
30
+ ownerEmail: string | null;
31
+ team: string | null;
32
+ riskTier: ServicePrincipalRiskTier | null;
33
+ purpose: string | null;
34
+ /** `null` is unrestricted. */
35
+ allowedActions: string[] | null;
36
+ lifecycleReason: string | null;
37
+ lifecycleChangedBy: string | null;
38
+ lifecycleChangedAt: number | null;
39
+ }
40
+ /** No policy row is "ungoverned": a legacy principal that is active and unrestricted. */
41
+ export declare function describeServicePrincipal(orgId: string, serviceName: string, policy: ServicePrincipalPolicy | null | undefined): ServicePrincipalView;
42
+ /**
43
+ * A name with neither a token nor a policy is a typo, not a principal; refusing
44
+ * it keeps governance rows from accumulating for names that can never act.
45
+ */
46
+ export declare function requireKnownServicePrincipal(orgId: string, serviceName: string): Promise<ServicePrincipalPolicy | null>;
47
+ /** Normalize a user-supplied name; a name with no usable characters is a 400. */
48
+ export declare function parseServiceName(raw: string): string;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Governance input shared by `create-org-service-token` and
3
+ * `set-service-principal-policy`, so a principal is validated the same way
4
+ * whether it is born governed or tightened later.
5
+ */
6
+ import { z } from "zod";
7
+ import { isOrgMember } from "../../org/membership.js";
8
+ import { parseServiceIdentityEmail } from "../../org/service-identity.js";
9
+ import { getServicePrincipalPolicy, isServicePrincipalActionPattern, MAX_SERVICE_PRINCIPAL_ACTIONS, SERVICE_PRINCIPAL_RISK_TIERS, } from "../../org/service-principal-policy.js";
10
+ import { CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE } from "../../server/credential-membership-unavailable.js";
11
+ import { listOrgServiceTokens, normalizeServiceName, serviceIdentityEmail, } from "../connect-store.js";
12
+ import { ServiceTokenError } from "./service-token-access.js";
13
+ export const MAX_ALLOWED_ACTIONS = MAX_SERVICE_PRINCIPAL_ACTIONS;
14
+ export const riskTierSchema = z
15
+ .enum(SERVICE_PRINCIPAL_RISK_TIERS)
16
+ .describe("Risk tier: low, medium (default) or high");
17
+ export const allowedActionsSchema = z
18
+ .array(z.string().refine(isServicePrincipalActionPattern))
19
+ .max(MAX_ALLOWED_ACTIONS)
20
+ .describe("Action names the principal may call; a trailing * matches a prefix (e.g. 'list-*'). An empty list grants nothing. Use null for unrestricted.");
21
+ export const ownerEmailSchema = z
22
+ .string()
23
+ .trim()
24
+ .email()
25
+ .max(320)
26
+ .describe("Accountable org member (email)");
27
+ export const teamSchema = z.string().trim().min(1).max(120);
28
+ export const purposeSchema = z.string().trim().min(1).max(500);
29
+ /** Dedupe so the stored grant (and its audited count) has no repeats. */
30
+ export function normalizeAllowedActions(allowed) {
31
+ return allowed ? [...new Set(allowed)] : allowed;
32
+ }
33
+ /**
34
+ * The owner must be a person in this org. A service identity is refused by
35
+ * name so the answer is a clear 400 rather than a membership miss, and an
36
+ * unreadable membership store is a 503, never "not a member".
37
+ */
38
+ export async function assertOwnerIsOrgMember(orgId, ownerEmail) {
39
+ const email = ownerEmail.trim().toLowerCase();
40
+ if (parseServiceIdentityEmail(email)) {
41
+ throw new ServiceTokenError("A service principal cannot own another service principal. Choose an org member.", 400);
42
+ }
43
+ let member;
44
+ try {
45
+ member = await isOrgMember(orgId, email);
46
+ }
47
+ catch (error) {
48
+ console.error("[service-principal] Owner membership lookup failed:", error);
49
+ throw new ServiceTokenError(CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE, 503);
50
+ }
51
+ if (!member) {
52
+ throw new ServiceTokenError(`${email} is not a member of this organization.`, 400);
53
+ }
54
+ return email;
55
+ }
56
+ /** No policy row is "ungoverned": a legacy principal that is active and unrestricted. */
57
+ export function describeServicePrincipal(orgId, serviceName, policy) {
58
+ return {
59
+ serviceName,
60
+ serviceEmail: serviceIdentityEmail(serviceName, orgId),
61
+ state: policy?.lifecycle ?? "ungoverned",
62
+ ownerEmail: policy?.ownerEmail ?? null,
63
+ team: policy?.team ?? null,
64
+ riskTier: policy?.riskTier ?? null,
65
+ purpose: policy?.purpose ?? null,
66
+ allowedActions: policy ? policy.allowedActions : null,
67
+ lifecycleReason: policy?.lifecycleReason ?? null,
68
+ lifecycleChangedBy: policy?.lifecycleChangedBy ?? null,
69
+ lifecycleChangedAt: policy?.lifecycleChangedAt ?? null,
70
+ };
71
+ }
72
+ /**
73
+ * A name with neither a token nor a policy is a typo, not a principal; refusing
74
+ * it keeps governance rows from accumulating for names that can never act.
75
+ */
76
+ export async function requireKnownServicePrincipal(orgId, serviceName) {
77
+ let policy;
78
+ let tokens;
79
+ try {
80
+ [policy, tokens] = await Promise.all([
81
+ getServicePrincipalPolicy(orgId, serviceName),
82
+ listOrgServiceTokens(orgId),
83
+ ]);
84
+ }
85
+ catch (error) {
86
+ console.error("[service-principal] Principal lookup failed:", error);
87
+ throw new ServiceTokenError("Could not read service principal governance. Try again.", 503);
88
+ }
89
+ if (!policy && !tokens.some((t) => t.serviceName === serviceName)) {
90
+ throw new ServiceTokenError(`No service principal named "${serviceName}" in this organization.`, 404);
91
+ }
92
+ return policy;
93
+ }
94
+ /** Normalize a user-supplied name; a name with no usable characters is a 400. */
95
+ export function parseServiceName(raw) {
96
+ try {
97
+ return normalizeServiceName(raw);
98
+ }
99
+ catch (error) {
100
+ throw new ServiceTokenError(error instanceof Error ? error.message : "Invalid service name.", 400);
101
+ }
102
+ }
@@ -0,0 +1,15 @@
1
+ declare const _default: import("../../action.js").ActionDefinition<{
2
+ serviceName: string;
3
+ lifecycle: "active" | "retired" | "suspended";
4
+ reason?: string;
5
+ }, {
6
+ orgId: string;
7
+ serviceEmail: string;
8
+ lifecycle: "active" | "retired" | "suspended";
9
+ principal: import("./service-principal-input.js").ServicePrincipalView;
10
+ abortedRuns: number;
11
+ revokedTokens: number;
12
+ contained: boolean;
13
+ containmentErrors: string[];
14
+ }>;
15
+ export default _default;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Suspend, retire, or resume an org service principal.
3
+ *
4
+ * The committed lifecycle write is what blocks new work (admission, tool
5
+ * dispatch, and run start read it). Suspended and retired also contain the
6
+ * principal: in-flight agent runs it owns are aborted, and retired additionally
7
+ * revokes every active token. The write commits before containment runs, and a
8
+ * containment failure is returned (`containmentErrors`, `contained: false`)
9
+ * rather than swallowed: a partial containment must not read as complete.
10
+ *
11
+ * Owner/admin only, and not callable by the agent tool loop.
12
+ */
13
+ import { z } from "zod";
14
+ import { defineAction } from "../../action.js";
15
+ import { containServicePrincipal, prepareServicePrincipalContainment, } from "../../agent/contain-principal.js";
16
+ import { orgAdminAudit, recordOrgAdminAuditEvent, } from "../../audit/org-admin.js";
17
+ import { SERVICE_PRINCIPAL_LIFECYCLES, ServicePrincipalRetiredError, getServicePrincipalPolicy, setServicePrincipalLifecycle, withServicePrincipalLifecycleLock, } from "../../org/service-principal-policy.js";
18
+ import { ensureConnectTables, revokeServiceTokensByName, } from "../connect-store.js";
19
+ import { describeServicePrincipal, parseServiceName, requireKnownServicePrincipal, } from "./service-principal-input.js";
20
+ import { requireServiceTokenCaller, ServiceTokenError, } from "./service-token-access.js";
21
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
22
+ export default defineAction({
23
+ description: "Suspend, retire, or resume an org service principal. Suspended and retired principals are refused at MCP admission and run start, and their in-flight agent runs are aborted; retired also revokes every active token. The result reports abortedRuns, revokedTokens, and any containmentErrors (contained: false means containment is incomplete — retry). Org owner/admin only.",
24
+ schema: z.object({
25
+ serviceName: z
26
+ .string()
27
+ .min(1)
28
+ .max(64)
29
+ .describe("Service name from list-org-service-tokens"),
30
+ lifecycle: z.enum(SERVICE_PRINCIPAL_LIFECYCLES),
31
+ reason: z.string().trim().max(500).optional(),
32
+ }),
33
+ toolCallable: false,
34
+ audit: orgAdminAudit({
35
+ targetType: "service-principal",
36
+ targetId: (args) => String(args.serviceName ?? ""),
37
+ summary: (args, result) => {
38
+ const r = result;
39
+ const errors = r.containmentErrors?.length ?? 0;
40
+ return `Set ${r.serviceEmail ?? args.serviceName} to ${args.lifecycle}: ${r.abortedRuns ?? 0} runs aborted, ${r.revokedTokens ?? 0} tokens revoked${errors ? `, ${errors} containment errors` : ""}`;
41
+ },
42
+ }),
43
+ run: async (args, ctx) => {
44
+ const caller = await requireServiceTokenCaller({
45
+ userEmail: ctx?.userEmail,
46
+ orgId: ctx?.orgId,
47
+ level: "manage",
48
+ });
49
+ const serviceName = parseServiceName(args.serviceName);
50
+ await requireKnownServicePrincipal(caller.orgId, serviceName);
51
+ let policy;
52
+ let abortedRuns = 0;
53
+ let revokedTokens = 0;
54
+ let resumeBlocked = false;
55
+ let lifecycleCommitted = false;
56
+ const containmentErrors = [];
57
+ try {
58
+ if (args.lifecycle !== "active") {
59
+ await prepareServicePrincipalContainment();
60
+ if (args.lifecycle === "retired")
61
+ await ensureConnectTables();
62
+ policy = await withServicePrincipalLifecycleLock(caller.orgId, serviceName, (db) => setServicePrincipalLifecycle(caller.orgId, serviceName, args.lifecycle, { actorEmail: caller.email, reason: args.reason || null }, db));
63
+ lifecycleCommitted = true;
64
+ policy = await withServicePrincipalLifecycleLock(caller.orgId, serviceName, async (db) => {
65
+ const current = await getServicePrincipalPolicy(caller.orgId, serviceName, db);
66
+ if (!current || current.lifecycle !== args.lifecycle) {
67
+ throw new ServiceTokenError("The service principal lifecycle changed concurrently. Read its current state before retrying.", 409);
68
+ }
69
+ try {
70
+ const contained = await containServicePrincipal(caller.orgId, serviceName);
71
+ abortedRuns = contained.abortedRuns;
72
+ containmentErrors.push(...contained.containmentErrors);
73
+ }
74
+ catch (error) {
75
+ containmentErrors.push(`abort runs: ${errorMessage(error)}`);
76
+ }
77
+ if (args.lifecycle === "retired") {
78
+ try {
79
+ revokedTokens = await revokeServiceTokensByName(caller.orgId, serviceName);
80
+ }
81
+ catch (error) {
82
+ containmentErrors.push(`revoke tokens: ${errorMessage(error)}`);
83
+ }
84
+ }
85
+ return current;
86
+ });
87
+ }
88
+ else {
89
+ policy = await withServicePrincipalLifecycleLock(caller.orgId, serviceName, async (db) => {
90
+ const current = await getServicePrincipalPolicy(caller.orgId, serviceName, db);
91
+ if (current?.lifecycle === "retired") {
92
+ throw new ServicePrincipalRetiredError();
93
+ }
94
+ if (current?.lifecycle === "suspended") {
95
+ try {
96
+ const contained = await containServicePrincipal(caller.orgId, serviceName);
97
+ abortedRuns = contained.abortedRuns;
98
+ containmentErrors.push(...contained.containmentErrors);
99
+ }
100
+ catch (error) {
101
+ containmentErrors.push(`abort runs: ${errorMessage(error)}`);
102
+ }
103
+ if (containmentErrors.length > 0) {
104
+ resumeBlocked = true;
105
+ return current;
106
+ }
107
+ }
108
+ return setServicePrincipalLifecycle(caller.orgId, serviceName, "active", { actorEmail: caller.email, reason: args.reason || null }, db);
109
+ });
110
+ if (resumeBlocked) {
111
+ throw new ServiceTokenError("The service principal could not be resumed because containment is incomplete. Retry after its in-flight runs stop.", 503);
112
+ }
113
+ }
114
+ }
115
+ catch (error) {
116
+ if (error instanceof ServicePrincipalRetiredError) {
117
+ throw new ServiceTokenError(error.message, error.statusCode);
118
+ }
119
+ if (error instanceof ServiceTokenError)
120
+ throw error;
121
+ console.error("[service-principal] Lifecycle write failed:", error);
122
+ throw new ServiceTokenError(lifecycleCommitted
123
+ ? "The lifecycle changed, but containment could not be confirmed. Retry the lifecycle request to finish containment."
124
+ : "Could not change the service principal lifecycle. Nothing was changed; try again.", 503);
125
+ }
126
+ const principal = describeServicePrincipal(caller.orgId, serviceName, policy);
127
+ if (args.lifecycle !== "active") {
128
+ await recordOrgAdminAuditEvent({
129
+ action: "contain-service-principal",
130
+ targetType: "service-principal",
131
+ targetId: serviceName,
132
+ summary: `Contained ${principal.serviceEmail}: ${abortedRuns} runs aborted, ${revokedTokens} tokens revoked${containmentErrors.length ? `, ${containmentErrors.length} errors` : ""}`,
133
+ userEmail: caller.email,
134
+ orgId: caller.orgId,
135
+ status: containmentErrors.length ? "error" : "success",
136
+ caller: ctx?.caller,
137
+ });
138
+ }
139
+ return {
140
+ orgId: caller.orgId,
141
+ serviceEmail: principal.serviceEmail,
142
+ lifecycle: args.lifecycle,
143
+ principal,
144
+ abortedRuns,
145
+ revokedTokens,
146
+ contained: containmentErrors.length === 0,
147
+ containmentErrors,
148
+ };
149
+ },
150
+ });
@@ -0,0 +1,14 @@
1
+ declare const _default: import("../../action.js").ActionDefinition<{
2
+ serviceName: string;
3
+ ownerEmail?: string;
4
+ team?: string;
5
+ riskTier?: "high" | "low" | "medium";
6
+ purpose?: string;
7
+ allowedActions?: string[];
8
+ }, {
9
+ orgId: string;
10
+ serviceEmail: string;
11
+ principal: import("./service-principal-input.js").ServicePrincipalView;
12
+ changedFields: ("allowedActions" | "ownerEmail" | "purpose" | "riskTier" | "team")[];
13
+ }>;
14
+ export default _default;