@revoengine/cli 1.0.19 → 1.0.21

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 (37) hide show
  1. package/README.md +60 -9
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +20 -3
  4. package/dist/src/client.js +45 -1
  5. package/dist/src/commands/agents.d.ts +2 -0
  6. package/dist/src/commands/agents.js +56 -0
  7. package/dist/src/commands/component.js +2 -0
  8. package/dist/src/commands/index.d.ts +1 -0
  9. package/dist/src/commands/index.js +1 -0
  10. package/dist/src/commands/migrate.js +14 -2
  11. package/dist/src/component-lock.d.ts +5 -0
  12. package/dist/src/component-lock.js +45 -5
  13. package/dist/src/metadata-backfill.js +48 -1
  14. package/dist/src/migration.d.ts +9 -2
  15. package/dist/src/migration.js +60 -0
  16. package/dist/src/resource-inventory.d.ts +4 -2
  17. package/dist/src/resource-inventory.js +11 -1
  18. package/dist/src/resource-syncs/account-principal.d.ts +19 -1
  19. package/dist/src/resource-syncs/account-principal.js +94 -4
  20. package/dist/src/resource-syncs/agent-sync.d.ts +98 -0
  21. package/dist/src/resource-syncs/agent-sync.js +586 -0
  22. package/dist/src/resource-syncs/endpoint-sync.d.ts +3 -0
  23. package/dist/src/resource-syncs/endpoint-sync.js +27 -1
  24. package/dist/src/resource-syncs/group-sync.d.ts +4 -1
  25. package/dist/src/resource-syncs/group-sync.js +32 -17
  26. package/dist/src/resource-syncs/identity-migration.d.ts +1 -1
  27. package/dist/src/resource-syncs/identity-migration.js +20 -1
  28. package/dist/src/resource-syncs/job-template-sync.d.ts +2 -1
  29. package/dist/src/resource-syncs/job-template-sync.js +38 -32
  30. package/dist/src/resource-syncs/service-account-sync.js +16 -9
  31. package/dist/src/tracked-resources.d.ts +1 -1
  32. package/dist/src/tracked-resources.js +4 -2
  33. package/dist/src/types.d.ts +22 -0
  34. package/dist/src/ui.js +5 -1
  35. package/dist/src/workspace-diff.js +2 -0
  36. package/dist/src/workspace-prune.js +44 -3
  37. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { type AgentSyncPlan, type AgentSyncPull, type AgentSyncResult } from './resource-syncs/agent-sync.ts';
1
2
  import { type MigrationResourcePlan } from './migration-actions.ts';
2
3
  import { type WorkspacePrunePlan } from './workspace-prune.ts';
3
4
  import { type ServiceAccountsPlan, type ServiceAccountPullResult, type ServiceAccountPushResult } from './resource-syncs/service-account-sync.ts';
@@ -11,12 +12,12 @@ import { type GroupPullResult, type GroupPushResult, type GroupsPlan } from './r
11
12
  import { type JobTemplatePullResult, type JobTemplatePushResult, type JobTemplatesPlan } from './resource-syncs/job-template-sync.ts';
12
13
  import { type SchedulePullResult, type SchedulePushResult, type SchedulesPlan } from './resource-syncs/schedule-sync.ts';
13
14
  import { type RoleGroupPullResult, type RoleGroupPushResult, type RoleGroupsPlan } from './resource-syncs/role-group-sync.ts';
14
- export type MigrationResource = 'database-table' | 'database-view' | 'component' | 'job-template' | 'endpoint' | 'schedule' | 'event' | 'group' | 'role-group' | 'service-account';
15
+ export type MigrationResource = 'database-table' | 'database-view' | 'component' | 'job-template' | 'endpoint' | 'schedule' | 'event' | 'group' | 'role-group' | 'service-account' | 'agent-plugin' | 'agent';
15
16
  export type MigrationVerdict = 'ready' | 'ready-with-warnings' | 'blocked';
16
17
  export type MigrationOperations = Record<'noop' | 'create' | 'update' | 'adopt' | 'excluded' | 'blocked', number> & {
17
18
  delete?: number;
18
19
  };
19
- type MigrationPushResult = DatabaseSchemaPushResult | DatabaseViewPushResult | ComponentSyncResult | JobTemplatePushResult | EndpointPushResult | SchedulePushResult | EventPushResult | GroupPushResult | RoleGroupPushResult | ServiceAccountPushResult;
20
+ type MigrationPushResult = DatabaseSchemaPushResult | DatabaseViewPushResult | ComponentSyncResult | JobTemplatePushResult | EndpointPushResult | SchedulePushResult | EventPushResult | GroupPushResult | RoleGroupPushResult | ServiceAccountPushResult | AgentSyncResult;
20
21
  export type MigrationPhasePlan = {
21
22
  order: number;
22
23
  resource: MigrationResource;
@@ -69,6 +70,8 @@ export type MigrationPlan = {
69
70
  groups?: MigrationResourcePlan<GroupsPlan>;
70
71
  roleGroups?: MigrationResourcePlan<RoleGroupsPlan>;
71
72
  serviceAccounts?: MigrationResourcePlan<ServiceAccountsPlan>;
73
+ agentPlugins?: MigrationResourcePlan<AgentSyncPlan>;
74
+ agents?: MigrationResourcePlan<AgentSyncPlan>;
72
75
  warnings: string[];
73
76
  blockers: string[];
74
77
  };
@@ -93,6 +96,8 @@ export type MigrationRun = {
93
96
  groups?: GroupPullResult;
94
97
  roleGroups?: RoleGroupPullResult;
95
98
  serviceAccounts?: ServiceAccountPullResult;
99
+ agentPlugins?: AgentSyncPull;
100
+ agents?: AgentSyncPull;
96
101
  };
97
102
  plan: MigrationPlan;
98
103
  results: MigrationPushResult[];
@@ -132,6 +137,8 @@ export type ResourcePullResults = {
132
137
  groups?: GroupPullResult;
133
138
  roleGroups?: RoleGroupPullResult;
134
139
  serviceAccounts?: ServiceAccountPullResult;
140
+ agentPlugins?: AgentSyncPull;
141
+ agents?: AgentSyncPull;
135
142
  };
136
143
  export type ResourcePullInput = {
137
144
  cwd: string;
@@ -1,3 +1,4 @@
1
+ import { AGENT_LAYOUT, buildAgentsPlan, pullAgentsToWorkspace, pushAgents } from "./resource-syncs/agent-sync.js";
1
2
  import { projectRepositoryItems, migrationItemOperation, BLOCKING_SCHEMA_STATUSES, schemaItemAction, viewItemIsBlocked, viewItemAction, componentItemAction, jobTemplateItemAction, endpointItemAction, scheduleItemAction, eventItemAction, groupItemAction, roleGroupItemAction, serviceAccountItemAction, } from "./migration-actions.js";
2
3
  import fs from 'node:fs';
3
4
  import { applyWorkspacePrune, buildWorkspacePrunePlan, samePrunePlan } from "./workspace-prune.js";
@@ -25,6 +26,8 @@ const RESOURCE_ORDER = [
25
26
  'database-view',
26
27
  'component',
27
28
  'service-account',
29
+ 'agent-plugin',
30
+ 'agent',
28
31
  'job-template',
29
32
  'endpoint',
30
33
  'schedule',
@@ -32,6 +35,27 @@ const RESOURCE_ORDER = [
32
35
  'group',
33
36
  'role-group',
34
37
  ];
38
+ function agentItemAction(item) {
39
+ if (item.blocked || item.status === 'collision')
40
+ return 'blocked';
41
+ if (item.status === 'create')
42
+ return 'create';
43
+ if (['orphan', 'skipped'].includes(item.status))
44
+ return 'excluded';
45
+ if (item.status === 'clean')
46
+ return 'noop';
47
+ return item.desiredHash === item.currentHash ? 'adopt' : 'update';
48
+ }
49
+ function summarizeAgentPhase(plan) {
50
+ const operations = emptyOperations();
51
+ for (const item of plan.items)
52
+ operations[migrationItemOperation(item, agentItemAction(item))]++;
53
+ const blocked = plan.blockers.length > 0 || operations.blocked > 0;
54
+ return { order: RESOURCE_ORDER.indexOf(plan.resourceType) + 1, resource: plan.resourceType,
55
+ operations, warnings: [...plan.warnings, ...plan.exclusions], blockers: plan.blockers,
56
+ needsChanges: operations.create + operations.update + operations.adopt > 0, readyToMigrate: !blocked,
57
+ verdict: blocked ? 'blocked' : plan.exclusions.length ? 'ready-with-warnings' : 'ready' };
58
+ }
35
59
  function selectedResources(input) {
36
60
  const requested = new Set(input.resources?.length ? input.resources : RESOURCE_ORDER);
37
61
  return RESOURCE_ORDER.filter((resource) => requested.has(resource));
@@ -404,6 +428,11 @@ function summarizePulls(mode, pulls) {
404
428
  skipped: pulls.groups.skipped.length,
405
429
  };
406
430
  }
431
+ for (const [family, field] of [['agent', 'agents'], ['agent-plugin', 'agentPlugins']]) {
432
+ const pull = pulls[field];
433
+ if (pull)
434
+ byResource[family] = { pulled: pull.pulled.length, pruned: pull.pruned.length, skipped: pull.skipped.length };
435
+ }
407
436
  if (pulls.serviceAccounts) {
408
437
  byResource['service-account'] = { pulled: pulls.serviceAccounts.pulled.length, pruned: pulls.serviceAccounts.pruned.length, skipped: pulls.serviceAccounts.skipped.length };
409
438
  }
@@ -541,6 +570,10 @@ function combinePlan(input) {
541
570
  if (input.components) {
542
571
  input.components = { ...input.components, items: projectRepositoryItems(input.components.items, componentItemAction, (item) => item.lockHash) };
543
572
  }
573
+ for (const field of ['agentPlugins', 'agents']) {
574
+ if (input[field])
575
+ input[field] = { ...input[field], items: projectRepositoryItems(input[field].items, agentItemAction, baselineByKey(lock[field])) };
576
+ }
544
577
  if (input.serviceAccounts) {
545
578
  input.serviceAccounts = { ...input.serviceAccounts, items: projectRepositoryItems(input.serviceAccounts.items, serviceAccountItemAction, baselineByKey(lock.serviceAccounts)) };
546
579
  }
@@ -568,6 +601,8 @@ function combinePlan(input) {
568
601
  ...(input.databaseViews ? [summarizeViewPhase(input.databaseViews)] : []),
569
602
  ...(input.components ? [summarizeComponentPhase(input.components)] : []),
570
603
  ...(input.serviceAccounts ? [summarizeServiceAccountPhase(input.serviceAccounts)] : []),
604
+ ...(input.agentPlugins ? [summarizeAgentPhase(input.agentPlugins)] : []),
605
+ ...(input.agents ? [summarizeAgentPhase(input.agents)] : []),
571
606
  ...(input.jobTemplates ? [summarizeJobTemplatePhase(input.jobTemplates)] : []),
572
607
  ...(input.endpoints ? [summarizeEndpointPhase(input.endpoints)] : []),
573
608
  ...(input.schedules ? [summarizeSchedulePhase(input.schedules)] : []),
@@ -682,6 +717,8 @@ function combinePlan(input) {
682
717
  ...(input.groups ? { groups: input.groups } : {}),
683
718
  ...(input.roleGroups ? { roleGroups: input.roleGroups } : {}),
684
719
  ...(input.serviceAccounts ? { serviceAccounts: input.serviceAccounts } : {}),
720
+ ...(input.agentPlugins ? { agentPlugins: input.agentPlugins } : {}),
721
+ ...(input.agents ? { agents: input.agents } : {}),
685
722
  warnings,
686
723
  blockers,
687
724
  };
@@ -717,6 +754,8 @@ function createTemporaryProject(input) {
717
754
  GROUPS_DIRECTORY,
718
755
  ROLE_GROUPS_DIRECTORY,
719
756
  SERVICE_ACCOUNTS_DIRECTORY,
757
+ AGENT_LAYOUT.agent[0],
758
+ AGENT_LAYOUT['agent-plugin'][0],
720
759
  ]) {
721
760
  const sourceDirectory = path.join(workspaceRoot, directory);
722
761
  if (fs.existsSync(sourceDirectory)) {
@@ -832,6 +871,11 @@ export async function pullResourcesToWorkspace(input) {
832
871
  pulls.serviceAccounts = await runMigrationStage('source pull', 'service-account', input.sourceLabel, () => pullServiceAccountsToWorkspace({ client, cwd: input.cwd, envName: input.sourceKey, stableKeyName,
833
872
  force: input.force === true, pruneOrphans: input.pruneOrphans === true }));
834
873
  }
874
+ for (const family of ['agent-plugin', 'agent'])
875
+ if (resources.includes(family)) {
876
+ pulls[AGENT_LAYOUT[family][2]] = await runMigrationStage('source pull', family, input.sourceLabel, () => pullAgentsToWorkspace({ client, cwd: input.cwd, envName: input.sourceKey, stableKeyName, family,
877
+ force: input.force === true, pruneOrphans: input.pruneOrphans === true }));
878
+ }
835
879
  if (resources.includes('job-template')) {
836
880
  pulls.jobTemplates = await runMigrationStage('source pull', 'job-template', input.sourceLabel, () => pullJobTemplatesToWorkspace({
837
881
  client,
@@ -1045,6 +1089,11 @@ async function planWorkspace(input) {
1045
1089
  if (serviceAccounts && identities) {
1046
1090
  serviceAccounts.blockers.push(...identities.blockers);
1047
1091
  }
1092
+ const projected = { component: input.projectDependencies && components ? components.items.filter(item => !item.blocked).flatMap(item => item.stableKey ? [item.stableKey] : []) : [],
1093
+ 'service-account': identities?.projection.serviceAccounts || [], group: identities?.projection.groups || [] };
1094
+ const agentPlugins = resources.includes('agent-plugin') ? await runMigrationStage('target plan', 'agent-plugin', environmentLabel, () => buildAgentsPlan({ client, cwd: input.cwd, envName: environmentKey, stableKeyName, family: 'agent-plugin', projected })) : undefined;
1095
+ const agents = resources.includes('agent') ? await runMigrationStage('target plan', 'agent', environmentLabel, () => buildAgentsPlan({ client, cwd: input.cwd, envName: environmentKey, stableKeyName, family: 'agent', projected: { ...projected,
1096
+ 'agent-plugin': agentPlugins?.items.filter(item => !item.blocked && item.desiredHash).flatMap(item => item.stableKey ? [item.stableKey] : []) || [] } })) : undefined;
1048
1097
  const jobTemplates = resources.includes('job-template')
1049
1098
  ? await runMigrationStage('target plan', 'job-template', environmentLabel, () => buildJobTemplatesPlan({
1050
1099
  client,
@@ -1065,6 +1114,7 @@ async function planWorkspace(input) {
1065
1114
  envName: environmentKey,
1066
1115
  stableKeyName,
1067
1116
  includeDependencyBlockers: input.sourceMode === 'workspace',
1117
+ projectedServiceAccounts: identities?.projection.serviceAccounts,
1068
1118
  ...(input.projectDependencies === true && components
1069
1119
  ? { projectedComponents: projectedComponentDependencies(components) }
1070
1120
  : {}),
@@ -1129,6 +1179,8 @@ async function planWorkspace(input) {
1129
1179
  groups,
1130
1180
  roleGroups,
1131
1181
  serviceAccounts,
1182
+ agentPlugins,
1183
+ agents,
1132
1184
  });
1133
1185
  if (identities) {
1134
1186
  combined.identityOrder = identities.ordered.map(({ resource, stableKey }) => ({ resource, stableKey }));
@@ -1394,6 +1446,14 @@ export async function runMigration(input) {
1394
1446
  }
1395
1447
  }
1396
1448
  }
1449
+ for (const family of ['agent-plugin', 'agent'])
1450
+ if (resources.includes(family)) {
1451
+ const pushed = await pushAgents({ client: targetClient, cwd: input.cwd, envName: environmentKey, stableKeyName, family, force: true });
1452
+ phaseResults[family] = pushed.results;
1453
+ results.push(...pushed.results);
1454
+ if (!resultsAreComplete(pushed.results))
1455
+ return { ...base, verdict: 'failed', results, phaseResults };
1456
+ }
1397
1457
  if (resources.includes('job-template')) {
1398
1458
  const liveJobTemplatePlan = await buildJobTemplatesPlan({
1399
1459
  client: targetClient,
@@ -1,7 +1,9 @@
1
1
  import type { RevoClient } from './client.ts';
2
2
  import type { TrackableResourceType } from './tracked-resources.ts';
3
- import type { ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ScheduleRecord, ServiceAccountRecord } from './types.ts';
3
+ import type { AgentRecord, AgentPluginRecord, ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ScheduleRecord, ServiceAccountRecord } from './types.ts';
4
4
  type ResourceRecordMap = {
5
+ agent: AgentRecord;
6
+ 'agent-plugin': AgentPluginRecord;
5
7
  'service-account': ServiceAccountRecord;
6
8
  component: ComponentRecord;
7
9
  'database-table': DatabaseSchemaRecord;
@@ -14,7 +16,7 @@ type ResourceRecordMap = {
14
16
  event: EventRecord;
15
17
  };
16
18
  export type ResourceRecord = ResourceRecordMap[TrackableResourceType];
17
- export type ResourceInventoryClient = Pick<RevoClient, 'listAllServiceAccounts' | 'getServiceAccount' | 'listAllComponents' | 'getComponent' | 'listAllDatabaseSchemas' | 'listAllDatabaseViewsForSync' | 'listAllEndpoints' | 'getEndpoint' | 'listAllRoleGroups' | 'getRoleGroup' | 'listAllGroups' | 'getGroup' | 'listAllJobTemplates' | 'getJobTemplate' | 'listAllSchedules' | 'getSchedule' | 'listAllEvents' | 'getEvent'>;
19
+ export type ResourceInventoryClient = Pick<RevoClient, 'listAllAgents' | 'getAgent' | 'listAllAgentPlugins' | 'getAgentPlugin' | 'listAllServiceAccounts' | 'getServiceAccount' | 'listAllComponents' | 'getComponent' | 'listAllDatabaseSchemas' | 'listAllDatabaseViewsForSync' | 'listAllEndpoints' | 'getEndpoint' | 'listAllRoleGroups' | 'getRoleGroup' | 'listAllGroups' | 'getGroup' | 'listAllJobTemplates' | 'getJobTemplate' | 'listAllSchedules' | 'getSchedule' | 'listAllEvents' | 'getEvent'>;
18
20
  type InventoryOptions = {
19
21
  skipPartitions?: boolean;
20
22
  };
@@ -10,7 +10,9 @@ export function unwrapResource(value) {
10
10
  return value;
11
11
  }
12
12
  export function resourceIdOf(resource) {
13
- return String(('userId' in resource && resource.userId)
13
+ return String(('agentId' in resource && resource.agentId)
14
+ || ('agentPluginId' in resource && resource.agentPluginId)
15
+ || ('userId' in resource && resource.userId)
14
16
  || ('databaseId' in resource && resource.databaseId)
15
17
  || ('databaseViewId' in resource && resource.databaseViewId)
16
18
  || ('jobTemplateId' in resource && resource.jobTemplateId)
@@ -35,6 +37,14 @@ async function* readDetails(summaries, getDetail) {
35
37
  }
36
38
  }
37
39
  const readers = {
40
+ async *agent(client) {
41
+ const { agents } = await client.listAllAgents();
42
+ yield* readDetails(agents, (id) => client.getAgent(id));
43
+ },
44
+ async *'agent-plugin'(client) {
45
+ const { agentPlugins } = await client.listAllAgentPlugins();
46
+ yield* readDetails(agentPlugins, (id) => client.getAgentPlugin(id));
47
+ },
38
48
  async *'service-account'(client) {
39
49
  const { serviceAccounts } = await client.listAllServiceAccounts();
40
50
  yield* readDetails(serviceAccounts, (id) => client.getServiceAccount(id));
@@ -1,10 +1,18 @@
1
1
  import { type RevoClient } from '../client.ts';
2
2
  import type { GroupOwnerPolicy } from '../component-lock.ts';
3
- import type { ServiceAccountRecord } from '../types.ts';
3
+ import type { ServiceAccountRecord, RuntimeExecutionPolicy } from '../types.ts';
4
4
  export type ExecutionPrincipal = {
5
5
  kind: 'service-account';
6
6
  stableKey: string;
7
+ } | {
8
+ kind: 'system';
9
+ stableKey?: never;
7
10
  };
11
+ export declare const SYSTEM_ACCOUNT_ID = "00000000-0000-0000-0000-000000000000";
12
+ export declare function isBuiltinSystemAccount(account: ServiceAccountRecord): boolean;
13
+ export declare function resolveSystemAccount(client: RevoClient, requireExecutionAccess?: boolean): Promise<ServiceAccountRecord>;
14
+ export declare function ownerFromPrincipal(principal: ExecutionPrincipal): GroupOwnerPolicy;
15
+ export declare function resolveExecutionPrincipal(client: RevoClient, principal: ExecutionPrincipal, stableKeyName: string): Promise<string>;
8
16
  export type IdentityProjection = {
9
17
  serviceAccounts?: string[];
10
18
  groups?: string[];
@@ -20,3 +28,13 @@ export declare function resolvePortableOwner(client: RevoClient, owner: GroupOwn
20
28
  ownerId: string;
21
29
  }>;
22
30
  export declare function ownerIsAvailable(client: RevoClient, owner: GroupOwnerPolicy, stableKeyName: string, projection?: IdentityProjection): Promise<boolean>;
31
+ export type PortableExecutionPolicy = {
32
+ mode: 'INHERIT' | 'CALLER' | 'SERVICE_ACCOUNT';
33
+ serviceAccount?: ExecutionPrincipal;
34
+ currentUser?: 'INHERIT' | 'CALLER' | 'EXECUTION_ACCOUNT';
35
+ };
36
+ export declare function validExecutionPrincipal(value: unknown): value is ExecutionPrincipal;
37
+ export declare function validPortableExecutionPolicy(value: unknown, allowCurrentUser?: boolean): value is PortableExecutionPolicy;
38
+ export declare function portableExecutionPolicy(client: RevoClient, policy: RuntimeExecutionPolicy | null | undefined, stableKeyName: string): Promise<PortableExecutionPolicy | undefined>;
39
+ export declare function runtimeExecutionPolicyPayload(client: RevoClient, policy: PortableExecutionPolicy | undefined, stableKeyName: string): Promise<RuntimeExecutionPolicy | undefined>;
40
+ export declare function executionPrincipalAvailable(client: RevoClient, principal: ExecutionPrincipal, stableKeyName: string, projected?: string[], requireExecutionAccess?: boolean): Promise<boolean>;
@@ -1,6 +1,29 @@
1
1
  import { ApiError } from "../client.js";
2
2
  import { readConfiguredResourceMetadataStableKey } from "../resource-metadata.js";
3
3
  import { unwrapData } from "./util.js";
4
+ export const SYSTEM_ACCOUNT_ID = '00000000-0000-0000-0000-000000000000';
5
+ export function isBuiltinSystemAccount(account) {
6
+ return account.userId === SYSTEM_ACCOUNT_ID && account.serviceAccount === true;
7
+ }
8
+ export async function resolveSystemAccount(client, requireExecutionAccess = false) {
9
+ const account = await client.getAccount(SYSTEM_ACCOUNT_ID);
10
+ if (!isBuiltinSystemAccount(account) || account.deletedAt || account.deletedBy
11
+ || ![0, 'ACTIVE'].includes(account.status) || (requireExecutionAccess && account.platformAccess !== true)) {
12
+ throw new Error('The target built-in System account is unavailable; migrate the instance before using a System reference.');
13
+ }
14
+ return account;
15
+ }
16
+ export function ownerFromPrincipal(principal) {
17
+ return principal.kind === 'system' ? { type: 'system' } : { type: 'service-account', stableKey: principal.stableKey };
18
+ }
19
+ export async function resolveExecutionPrincipal(client, principal, stableKeyName) {
20
+ if (principal.kind === 'system')
21
+ return String((await resolveSystemAccount(client, true)).userId);
22
+ const matches = await serviceAccountMatches(client, principal.stableKey, stableKeyName);
23
+ if (matches.length !== 1 || !matches[0].userId)
24
+ throw new Error('Execution principal must resolve to exactly one target service account.');
25
+ return matches[0].userId;
26
+ }
4
27
  export async function accountPrincipal(client, userId, stableKeyName) {
5
28
  let account;
6
29
  try {
@@ -12,16 +35,18 @@ export async function accountPrincipal(client, userId, stableKeyName) {
12
35
  }
13
36
  throw error;
14
37
  }
15
- if (account.serviceAccount !== true || account.deletedAt) {
38
+ if (account.serviceAccount !== true || account.deletedAt || account.deletedBy) {
16
39
  return undefined;
17
40
  }
41
+ if (isBuiltinSystemAccount(account))
42
+ return { kind: 'system' };
18
43
  const stableKey = readConfiguredResourceMetadataStableKey(account, stableKeyName);
19
44
  return stableKey ? { kind: 'service-account', stableKey } : undefined;
20
45
  }
21
46
  export async function readPortableOwner(client, record, stableKeyName) {
22
47
  if (record.ownerType === 'USER' && record.ownerId) {
23
48
  const principal = await accountPrincipal(client, record.ownerId, stableKeyName);
24
- return principal ? { type: 'service-account', stableKey: principal.stableKey } : { type: 'manual-user' };
49
+ return principal ? ownerFromPrincipal(principal) : { type: 'manual-user' };
25
50
  }
26
51
  if (record.ownerType === 'GROUP' && record.ownerId) {
27
52
  const group = unwrapData(await client.getGroup(record.ownerId));
@@ -35,13 +60,16 @@ export async function serviceAccountMatches(client, stableKey, stableKeyName) {
35
60
  const matches = [];
36
61
  for (const summary of serviceAccounts) {
37
62
  const account = await client.getServiceAccount(String(summary.userId || ''));
38
- if (readConfiguredResourceMetadataStableKey(account, stableKeyName) === stableKey) {
63
+ if (!isBuiltinSystemAccount(account) && readConfiguredResourceMetadataStableKey(account, stableKeyName) === stableKey) {
39
64
  matches.push(account);
40
65
  }
41
66
  }
42
67
  return matches;
43
68
  }
44
69
  export async function resolvePortableOwner(client, owner, stableKeyName) {
70
+ if (owner.type === 'system') {
71
+ return { ownerType: 'USER', ownerId: String((await resolveSystemAccount(client)).userId) };
72
+ }
45
73
  if (owner.type === 'service-account') {
46
74
  const matches = await serviceAccountMatches(client, owner.stableKey, stableKeyName);
47
75
  if (matches.length !== 1 || !matches[0].userId) {
@@ -66,7 +94,7 @@ export async function resolvePortableOwner(client, owner, stableKeyName) {
66
94
  throw new Error('Owner requires manual target configuration.');
67
95
  }
68
96
  export async function ownerIsAvailable(client, owner, stableKeyName, projection) {
69
- if (owner.type !== 'group' && owner.type !== 'service-account') {
97
+ if (owner.type !== 'group' && owner.type !== 'service-account' && owner.type !== 'system') {
70
98
  return false;
71
99
  }
72
100
  try {
@@ -74,6 +102,8 @@ export async function ownerIsAvailable(client, owner, stableKeyName, projection)
74
102
  return true;
75
103
  }
76
104
  catch {
105
+ if (owner.type === 'system')
106
+ return false;
77
107
  // Projection cannot mask duplicate live identities.
78
108
  if (owner.type === 'service-account') {
79
109
  const matches = await serviceAccountMatches(client, owner.stableKey, stableKeyName);
@@ -84,3 +114,63 @@ export async function ownerIsAvailable(client, owner, stableKeyName, projection)
84
114
  return matches.length === 0 && (projection?.groups || []).includes(owner.stableKey);
85
115
  }
86
116
  }
117
+ export function validExecutionPrincipal(value) {
118
+ if (!value || typeof value !== 'object' || Array.isArray(value))
119
+ return false;
120
+ const principal = value;
121
+ return principal.kind === 'system' ? Object.keys(principal).length === 1
122
+ : principal.kind === 'service-account' && typeof principal.stableKey === 'string' && !!principal.stableKey.trim()
123
+ && Object.keys(principal).every(key => ['kind', 'stableKey'].includes(key));
124
+ }
125
+ export function validPortableExecutionPolicy(value, allowCurrentUser = false) {
126
+ if (!value || typeof value !== 'object' || Array.isArray(value))
127
+ return false;
128
+ const policy = value;
129
+ return ['INHERIT', 'CALLER', 'SERVICE_ACCOUNT'].includes(String(policy.mode))
130
+ && Object.keys(policy).every(key => ['mode', 'serviceAccount', ...(allowCurrentUser ? ['currentUser'] : [])].includes(key))
131
+ && (policy.mode === 'SERVICE_ACCOUNT' ? validExecutionPrincipal(policy.serviceAccount) : policy.serviceAccount === undefined)
132
+ && (policy.currentUser === undefined || allowCurrentUser && ['INHERIT', 'CALLER', 'EXECUTION_ACCOUNT'].includes(String(policy.currentUser)));
133
+ }
134
+ export async function portableExecutionPolicy(client, policy, stableKeyName) {
135
+ if (!policy)
136
+ return undefined;
137
+ if (!['INHERIT', 'CALLER', 'SERVICE_ACCOUNT'].includes(policy.mode))
138
+ throw new Error('Invalid saved runtime execution policy.');
139
+ const serviceAccount = policy.mode === 'SERVICE_ACCOUNT' && policy.serviceAccountUserId
140
+ ? await accountPrincipal(client, policy.serviceAccountUserId, stableKeyName) : undefined;
141
+ if (policy.mode === 'SERVICE_ACCOUNT' && !serviceAccount)
142
+ throw new Error('Execution account is human, unavailable, or missing a portable Stable Key.');
143
+ return { mode: policy.mode, ...(serviceAccount ? { serviceAccount } : {}), ...(policy.currentUser ? { currentUser: policy.currentUser } : {}) };
144
+ }
145
+ export async function runtimeExecutionPolicyPayload(client, policy, stableKeyName) {
146
+ if (!policy)
147
+ return undefined;
148
+ const userId = policy.mode === 'SERVICE_ACCOUNT' ? await resolveExecutionPrincipal(client, policy.serviceAccount, stableKeyName) : undefined;
149
+ if (userId && policy.serviceAccount.kind !== 'system') {
150
+ const target = await client.getAccount(userId);
151
+ if (target.deletedAt || target.deletedBy || ![0, 'ACTIVE'].includes(target.status) || target.platformAccess !== true) {
152
+ throw new Error('Execution service account must be active and have platform access.');
153
+ }
154
+ }
155
+ return { mode: policy.mode, ...(userId ? { serviceAccountUserId: userId } : {}), ...(policy.currentUser ? { currentUser: policy.currentUser } : {}) };
156
+ }
157
+ export async function executionPrincipalAvailable(client, principal, stableKeyName, projected = [], requireExecutionAccess = false) {
158
+ if (principal.kind === 'system') {
159
+ try {
160
+ await resolveSystemAccount(client, true);
161
+ return true;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ const matches = await serviceAccountMatches(client, principal.stableKey, stableKeyName);
168
+ if (matches.length === 1) {
169
+ if (!requireExecutionAccess)
170
+ return true;
171
+ const target = await client.getAccount(String(matches[0].userId));
172
+ return target.serviceAccount === true && !target.deletedAt && !target.deletedBy
173
+ && [0, 'ACTIVE'].includes(target.status) && target.platformAccess === true;
174
+ }
175
+ return matches.length === 0 && projected.includes(principal.stableKey);
176
+ }
@@ -0,0 +1,98 @@
1
+ import type { RevoClient } from '../client.ts';
2
+ import { type GroupOwnerPolicy } from '../component-lock.ts';
3
+ import { type FieldChange } from '../diff-details.ts';
4
+ import type { ComponentRecord } from '../types.ts';
5
+ import { type ExecutionPrincipal } from './account-principal.ts';
6
+ export type AgentFamily = 'agent' | 'agent-plugin';
7
+ export declare const AGENT_LAYOUT: {
8
+ readonly agent: readonly ["Agents", "agent.json", "agents"];
9
+ readonly 'agent-plugin': readonly ["AgentPlugins", "agent-plugin.json", "agentPlugins"];
10
+ };
11
+ export type AgentManifest = {
12
+ kind: AgentFamily;
13
+ stableKey: string;
14
+ name: string;
15
+ metadata: Record<string, unknown>;
16
+ definition: Record<string, unknown>;
17
+ owner?: GroupOwnerPolicy;
18
+ executionPrincipal?: ExecutionPrincipal;
19
+ };
20
+ export type AgentSyncStatus = 'clean' | 'create' | 'safe-update' | 'remote-changed' | 'conflict' | 'missing-lock' | 'orphan' | 'skipped' | 'collision';
21
+ export type AgentSyncItem = {
22
+ status: AgentSyncStatus;
23
+ stableKey?: string;
24
+ name: string;
25
+ reason?: string;
26
+ desiredHash?: string;
27
+ currentHash?: string;
28
+ baselineHash?: string;
29
+ changedFields?: string[];
30
+ fieldChanges?: FieldChange[];
31
+ blocked?: boolean;
32
+ };
33
+ export type AgentSyncPlan = {
34
+ resourceType: AgentFamily;
35
+ env: string;
36
+ counts: Record<AgentSyncStatus, number>;
37
+ items: AgentSyncItem[];
38
+ blockers: string[];
39
+ warnings: string[];
40
+ exclusions: string[];
41
+ };
42
+ export type AgentSyncPull = {
43
+ pulled: Array<{
44
+ manifest: AgentManifest;
45
+ targetPath: string;
46
+ }>;
47
+ pruned: Array<{
48
+ stableKey: string;
49
+ targetPath: string;
50
+ }>;
51
+ skipped: Array<{
52
+ name: string;
53
+ targetPath: string;
54
+ reason: string;
55
+ }>;
56
+ };
57
+ export type AgentSyncResult = {
58
+ stableKey: string;
59
+ action: 'create' | 'update' | 'noop' | 'orphan' | 'skipped';
60
+ status: 'deployed' | 'skipped' | 'failed';
61
+ targetPath: string;
62
+ error?: string;
63
+ reason?: string;
64
+ };
65
+ type SyncInput = {
66
+ client: RevoClient;
67
+ cwd: string;
68
+ envName: string;
69
+ stableKeyName: string;
70
+ family: AgentFamily;
71
+ };
72
+ type Projection = Partial<Record<'agent-plugin' | 'component' | 'service-account' | 'group', string[]>>;
73
+ export declare function agentManifestFromRecord(input: Pick<SyncInput, 'client' | 'family' | 'stableKeyName'>, value: ComponentRecord): Promise<AgentManifest | null>;
74
+ export declare function hashPortableAgent(manifest: AgentManifest): string;
75
+ export declare function readWorkspaceAgents(cwd: string, family: AgentFamily): {
76
+ manifestPath: string;
77
+ manifest: AgentManifest;
78
+ }[];
79
+ export declare function agentDependencies(manifest: AgentManifest): Array<[keyof Projection, string]>;
80
+ export declare function orderAgentPlugins(entries: Array<{
81
+ manifest: AgentManifest;
82
+ }>): {
83
+ manifest: AgentManifest;
84
+ }[];
85
+ export declare function pullAgentsToWorkspace(input: SyncInput & {
86
+ force?: boolean;
87
+ pruneOrphans?: boolean;
88
+ }): Promise<AgentSyncPull>;
89
+ export declare function buildAgentsPlan(input: SyncInput & {
90
+ projected?: Projection;
91
+ }): Promise<AgentSyncPlan>;
92
+ export declare function pushAgents(input: SyncInput & {
93
+ force?: boolean;
94
+ }): Promise<{
95
+ plan: AgentSyncPlan;
96
+ results: AgentSyncResult[];
97
+ }>;
98
+ export {};