@revoengine/cli 1.0.15 → 1.0.16

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 (49) hide show
  1. package/README.md +45 -9
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +25 -3
  4. package/dist/src/client.js +67 -2
  5. package/dist/src/commands/component.js +1 -0
  6. package/dist/src/commands/index.d.ts +1 -0
  7. package/dist/src/commands/index.js +1 -0
  8. package/dist/src/commands/migrate.js +12 -2
  9. package/dist/src/commands/service-accounts.d.ts +2 -0
  10. package/dist/src/commands/service-accounts.js +149 -0
  11. package/dist/src/commands/terminal-browser.d.ts +29 -2
  12. package/dist/src/commands/terminal-browser.js +144 -35
  13. package/dist/src/commands/terminal-file.d.ts +21 -0
  14. package/dist/src/commands/terminal-file.js +160 -0
  15. package/dist/src/commands/terminal-operational-log.js +2 -2
  16. package/dist/src/commands/terminal-policy.d.ts +5 -2
  17. package/dist/src/commands/terminal-policy.js +10 -4
  18. package/dist/src/commands/terminal-reconnect-grace.js +1 -1
  19. package/dist/src/commands/terminal-sandbox.js +7 -0
  20. package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
  21. package/dist/src/commands/terminal-secure-browser.js +2 -1
  22. package/dist/src/commands/terminal-service.js +4 -4
  23. package/dist/src/commands/terminal.d.ts +12 -0
  24. package/dist/src/commands/terminal.js +134 -45
  25. package/dist/src/component-lock.d.ts +4 -0
  26. package/dist/src/component-lock.js +21 -2
  27. package/dist/src/metadata-backfill.js +50 -1
  28. package/dist/src/migration.d.ts +10 -2
  29. package/dist/src/migration.js +159 -68
  30. package/dist/src/resource-inventory.d.ts +3 -2
  31. package/dist/src/resource-inventory.js +6 -1
  32. package/dist/src/resource-syncs/account-principal.d.ts +22 -0
  33. package/dist/src/resource-syncs/account-principal.js +86 -0
  34. package/dist/src/resource-syncs/group-sync.d.ts +10 -0
  35. package/dist/src/resource-syncs/group-sync.js +92 -20
  36. package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
  37. package/dist/src/resource-syncs/identity-migration.js +108 -0
  38. package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
  39. package/dist/src/resource-syncs/job-template-sync.js +55 -12
  40. package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
  41. package/dist/src/resource-syncs/service-account-sync.js +620 -0
  42. package/dist/src/sync-output.js +3 -0
  43. package/dist/src/tracked-resources.d.ts +1 -1
  44. package/dist/src/tracked-resources.js +5 -1
  45. package/dist/src/types.d.ts +12 -0
  46. package/dist/src/ui.js +4 -1
  47. package/dist/src/workspace-diff.d.ts +1 -0
  48. package/dist/src/workspace-diff.js +4 -1
  49. package/package.json +2 -2
package/README.md CHANGED
@@ -92,11 +92,28 @@ The Agent terminal has independent command and network grants. Grants are ceilin
92
92
 
93
93
  Browser actions use Playwright's Chromium headless shell. The CLI's npm install downloads that browser into Playwright's per-user cache without requiring Python 3; a separate Chrome installation is not required. If npm scripts were disabled or the download was interrupted, reinstall the CLI with scripts enabled before using Browser. Linux hosts still need Playwright's system libraries; an administrator can install them with `npx playwright install-deps chromium`.
94
94
 
95
- The runner keeps a separate browser context for each connected assistant chat, so navigation, DOM inspection, clicks, form controls, waiting, scrolling, and screenshots share that chat's cookies and page state. It follows an SSO popup opened by a click or key press and returns to its opener when the popup closes. Browser sessions expire after 10 minutes idle (up to four per runner), on a Local or Full network lease expiry, or when the runner stops or its access is revoked. A one-time Browser network approval closes its context immediately after that action finishes. DOM results include bounded selector hints for interactive elements without their field values. The Browser action supports `fill`, `check`, `select`, `press`, `scroll`, and `wait_for` as well as navigation, DOM, and click. Ordinary `fill` rejects password and secret-like controls; the Assistant may request a one-time secure credential dialog, which encrypts the value to this runner and fills it in memory without sending it in model tool arguments. Screenshots can capture the viewport (default), the full page, one selected element, or a bounded viewport crop. For viewport capture, an optional selector limits only the returned DOM text; the image still covers the viewport. Element capture requires a selector. Full-page and crop capture reject selectors. A screenshot is uploaded and attached automatically; calling `save_image` on its local path uploads a second copy. For custom Playwright E2E scripts, run them as ordinary terminal commands in the project, using the requested sandbox and network grant; the Browser action does not execute arbitrary JavaScript.
95
+ On macOS, workspace commands may use Unix-domain sockets only inside their own private temporary directory. This lets build tools exchange worker messages without enabling IP networking or access to workspace, other-command or host-service sockets. Local development servers still need Local network access and must bind to localhost. Ordinary process deadlines cover the whole lifetime, not startup. The runner advertises `background_shell_v1`: `terminal.start` with `background=true` and `timeout_ms=null` keeps a dev server or watcher on the existing execution ID without the ordinary lifetime timer. Status, output, stdin, PTY and cancel remain available; hiding the terminal view does not stop the process. Scope expiry, revocation, runner stop and the three-minute disconnect grace still apply. Reuse a healthy project server or check fresh HTTP readiness after starting it.
96
+
97
+ The terminal approval UI supports Allow once, Allow for 15 minutes, Allow for 1 hour, Allow for 8 hours, Allow for 24 hours and Allow for this thread. Whole-thread access requires this runner's `terminal_thread_scope_v1` capability. It covers only the requested Commands and Network levels, survives later messages and short reconnects, and carries no hourly deadline. Disconnect, thread deletion and a device grant revision change revoke it. Realtime rechecks the consent on heartbeat, including idle Browser contexts; scope revocation closes only the affected context. Process `background` mode and the one-hour Browser idle retention are independent of this approval duration.
98
+
99
+ The runner keeps a separate browser context for each connected assistant chat, so navigation, DOM inspection, clicks, form controls, waiting, scrolling, and screenshots share that chat's cookies and page state. Completed actions return a stable browserSessionId, activeTabId and tab inventory (ID, title, sanitized URL and active flag), plus sessionCreated. Use tabs, new_tab with a URL, select_tab or close_tab with tabId, and close to manage the session. Other actions accept tabId. Selecting a tab brings it to the foreground without navigation; popup tabs receive IDs and return to their opener when closed. Tab-aware operations require browser_tabs_v1 in Realtime and Gateway. Browser sessions expire after one hour idle (up to four per runner and sixteen tabs per session), on a Local or Full network lease expiry, or when the runner stops or its access is revoked. A one-time Browser network approval closes its context immediately after that action finishes. DOM results include bounded selector hints for interactive elements without their field values. The Browser action supports `fill`, `check`, `select`, `press`, `scroll`, and `wait_for` as well as navigation, DOM, and click. Ordinary `fill` rejects password and secret-like controls; the Assistant may request a one-time secure credential dialog, which encrypts the value to this runner and fills it in memory without sending it in model tool arguments. The tab-aware handoff authenticates its target tab ID and rejects a switched page even on the same origin. Screenshots can capture the viewport (default), the full page, one selected element, or a bounded viewport crop. For viewport capture, an optional selector limits only the returned DOM text; the image still covers the viewport. Element capture requires a selector. Full-page and crop capture reject selectors. A screenshot is uploaded and attached automatically; calling `save_image` on its local path uploads a second copy. For custom Playwright E2E scripts, run them as ordinary terminal commands in the project, using the requested sandbox and network grant; the Browser action does not execute arbitrary JavaScript.
100
+
101
+
102
+ The Browser bridge advertises `browser_timeout_v1`. Agent calls can set `action_timeout_ms` between 1 and 120000 ms for Playwright navigation, interactions, DOM reads and capture. Omitted values retain navigation 30 s, interaction/DOM 10 s and capture 20 s defaults. Selector waits accept `wait_timeout_ms` up to 120000 ms and are capped by the operation timeout when both are supplied. These budgets never extend access expiry or retry an interaction. At a capacity limit the agent can list and close a selected tab, or close its own chat Browser session; closing a session discards its cookies.
103
+
104
+ ### Device workspaces and direct transfer
105
+
106
+ The saved `agentTerminalId` identifies the device across terminal restarts. `deviceId` is an alias. Connecting another directory with the same profile and terminal name reuses the saved device secret and registers a pending workspace under that device. Approve its access in AI Agents → Terminals → Workspaces. A running device refreshes its contract; it does not need a second runner. Ambiguous older duplicate registrations require `--terminal-id`. Services remain pinned to the device UUID and original service directory.
107
+
108
+ Current runners advertise `terminal_workspaces_v1`, `browser_control_v1` and `file_transfer_v1`. Gateway can request socket reconnect without stopping the CLI. Temporary transport/dependency failures retry and resume within three minutes; authentication failures and revocation stop retry. Newly installed services stop on fatal authentication and restart other failed processes. Reinstall existing services to adopt that supervisor behavior. CLI stop does not persist local processes or browser cookies. Changing workspace grant revision conservatively terminates workspace-bound work and contexts.
109
+
110
+ Browser inventory exposes its owning chat and workspace. The model can explicitly close permitted same-actor sessions/tabs to free the four-session/sixteen-tab capacity; active sessions are never silently evicted. Inventory/cleanup preserves the existing network lease. Local/full scope changes recreate the browser context and require browser workflow recovery.
111
+
112
+ `upload_file` and `download_file` stream an explicit authorized workspace file directly to/from GCS HTTPS signed/resumable URLs with permitted headers. Full network permission is required. WebSocket carries metadata only. Resumable uploads report committed offsets and partial completion; do not finalize a Storage upload before completion or blindly repeat an uncertain upload. Downloads commit atomically and do not overwrite unless explicitly requested. The stream's idle timeout is 90 seconds; grant expiry and runner lifetime still apply. Signed URLs/headers are credentials and must not be copied into logs or source files.
96
113
 
97
114
  Interactive PTY commands use the optional native `node-pty` package. An unavailable native build does not block CLI installation; PTY requests return `pty_unavailable` until the optional package can be installed. To skip native installation when PTY is not needed, install locally with `npm install --omit=optional @revoengine/cli` and run `npx revo`; npm 11.9 may still install the optional dependency during a global installation. On macOS, the runner verifies the spawn helper's executable permission when a PTY starts. Ordinary commands and local development servers run with pipes.
98
115
 
99
- Local Browser mode filters HTTP and WebSocket requests and disables WebRTC, WebTransport, Worker and SharedWorker before page scripts. Worker-dependent pages may not work in this mode; Chromium is not enclosed in an OS network sandbox. A temporary Local or Full network lease closes the Browser context at expiry when the current permanent grant does not cover it, including before a queued secure credential fill. A lost WebSocket connection, a controlled Realtime restart, or a temporary dependency outage retains running processes and Browser contexts for one two-minute reconnect period; repeated failures do not renew it. Receiving `ready` alone does not reset that period while executions still await resume confirmation. Handshake, ready and execution resume each have a ten-second transport deadline. Access revocation and malformed runner frames stop the runner and its processes. Grant revision changes reject older execute frames and stop only work outside the remaining permanent or temporary scope. A network upgrade preserves the original temporary lease for a subsequent downgrade.
116
+ Local Browser mode filters HTTP and WebSocket requests and disables WebRTC, WebTransport, Worker and SharedWorker before page scripts. Worker-dependent pages may not work in this mode; Chromium is not enclosed in an OS network sandbox. A temporary Local or Full network lease closes the Browser context at expiry when the current permanent grant does not cover it, including before a queued secure credential fill. A lost WebSocket connection, a controlled Realtime restart, or a temporary dependency outage retains running processes and Browser contexts for one three-minute reconnect period; repeated failures do not renew it. Receiving `ready` alone does not reset that period while executions still await resume confirmation. Handshake, ready and execution resume each have a ten-second transport deadline. Access revocation and malformed runner frames stop the runner and its processes. Grant revision changes reject older execute frames and stop only work outside the remaining permanent or temporary scope. A network upgrade preserves the original temporary lease for a subsequent downgrade.
100
117
 
101
118
  `save_image` validates the canonical path of the opened file descriptor and reads the image from that same descriptor (up to 30 MiB). It rejects the upload if the descriptor path cannot be verified, including when `lsof` is unavailable on macOS or `/proc/self/fd` cannot be resolved on Linux.
102
119
 
@@ -342,16 +359,17 @@ Full pull, deployment, and migration use this fixed dependency order:
342
359
  | 1 | `database-table` | `database-tables` | `DatabaseTables/` | Tables, columns, and partitions; destructive DDL remains guarded. |
343
360
  | 2 | `database-view` | `database-views` | `DatabaseViews/` | STRUCTURED and RAW_SQL views, including materialized views; target schemas must be ready first. |
344
361
  | 3 | `component` | `component` | `Components/` | Portable code, libraries, and elements. Libraries are deployed before executable components. |
345
- | 4 | `job-template` | `job-templates` | `JobTemplates/` | Resolves Component dependencies by Stable Key. Pull skips WIP templates without a Stable Key or with an unkeyed Component and reports each skip. |
346
- | 5 | `endpoint` | `endpoints` | `Endpoints/` | Resolves Component dependencies and route ordering. |
347
- | 6 | `schedule` | `schedules` | `Schedules/` | Targets Job Templates or Materialized Views. New schedules are inactive by default. |
348
- | 7 | `event` | `events` | `Events/` | Supports Job Template event targets. Manifests retain `custom: true/false` alongside `type`; new events are inactive by default. |
349
- | 8 | `group` | `groups` | `Groups/` | Group owners use Stable Keys; users and memberships remain target-local. |
350
- | 9 | `role-group` | `role-groups` | `RoleGroups/` | Role assignments run last; members and user identifiers remain target-local. |
362
+ | 4 | `service-account` | `service-accounts` | `ServiceAccounts/` | Owner identities are resolved before dependent Groups and Job Templates; secrets are target-local. |
363
+ | 5 | `job-template` | `job-templates` | `JobTemplates/` | Resolves Component and Service Account dependencies by Stable Key. Pull skips WIP templates without a Stable Key or with an unkeyed Component and reports each skip. |
364
+ | 6 | `endpoint` | `endpoints` | `Endpoints/` | Resolves Component dependencies and route ordering. |
365
+ | 7 | `schedule` | `schedules` | `Schedules/` | Targets Job Templates or Materialized Views. New schedules are inactive by default. |
366
+ | 8 | `event` | `events` | `Events/` | Supports Job Template event targets. Manifests retain `custom: true/false` alongside `type`; new events are inactive by default. |
367
+ | 9 | `group` | `groups` | `Groups/` | Group owners use Stable Keys; Service Account owners resolve early; human users and memberships remain target-local. |
368
+ | 10 | `role-group` | `role-groups` | `RoleGroups/` | Role assignments run last; members and user identifiers remain target-local. |
351
369
 
352
370
  Active Materialized View refresh Schedules are reported in Database View plans but do not block push, repository deployment, or named migration. Updating a view preserves Schedule activation; API write failures and readback verification failures are still reported.
353
371
 
354
- `--resources all` selects all nine families. Singular, plural, and common compact aliases are accepted where the command parser documents them, but the selectors above are the canonical values.
372
+ `--resources all` selects all ten families. Singular, plural, and common compact aliases are accepted where the command parser documents them, but the selectors above are the canonical values.
355
373
 
356
374
  Existing `database-schema` selectors and `revo database-schemas` commands remain accepted as compatibility aliases. New table manifests use `DatabaseTables/**/database-table.json`; older `DatabaseSchemas/**/database-schema.json` files remain readable and are relocated by the next successful table pull. A locally edited manifest still needs `--force` before pull replaces it. The manifest `kind` and `databaseSchemas` lock and plan keys retain their existing schema names for format compatibility.
357
375
 
@@ -501,3 +519,21 @@ npm run check
501
519
  npm test
502
520
  npm pack --dry-run
503
521
  ```
522
+
523
+ ## Service Accounts in migration
524
+
525
+ `revo metadata plan --resources service-account` and `revo metadata apply` assign Stable Keys explicitly.
526
+ `revo service-accounts pull --all`, `plan --all`, and `push --all --yes` manage the portable definition.
527
+ The same family is included in `revo pull --all`, repository `diff`/`plan`/`deploy`, and named `migrate plan`/`run`/`verify`.
528
+ Select it alone with `--resources service-account`. Named profiles (`--project`/`--env`), URL/token environment variables,
529
+ and the ordinary authenticated runtime work through the existing config resolution. `--force` retains the existing drift policy.
530
+
531
+ The portable manifest contains the Stable Key, name, and Stable Key of a Group or Service Account owner.
532
+ Group USER owners and Job Template `triggerUser` references to Service Accounts are resolved to target `userId` at write time.
533
+ Human principals are reported for manual configuration; an account with a human owner needs a target account with the exact Stable Key before it can be adopted.
534
+ A missing or circular owner dependency blocks writes. Groups and accounts are created in dependency order before their consumers.
535
+
536
+ API keys and secrets cannot be exported. Every newly created Service Account is active and has platform access but has no migrated credentials.
537
+ The push result contains `credentials: { stableKey, environment, policy: "target-local", status: "configure-manually" }`.
538
+ Existing target secrets remain local and are never compared, copied, rotated, or exposed in manifests, plans, lock files, or HTTP trace.
539
+ Memberships, ACL, other account metadata, and `metadataAdvanced` remain outside this sync contract.
package/dist/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import { pathToFileURL } from 'node:url';
3
3
  import { RevoClient } from "./client.js";
4
4
  import { readComponentLock } from "./component-lock.js";
5
5
  import { getActiveEnvironmentName } from "./config.js";
6
- import { handleAuthCommand, handleComponentCommand, handleDatabaseTablesCommand, handleDatabaseViewsCommand, handleDeployCommand, handleDiffCommand, handleEndpointsCommand, handleEnvCommand, handleEventsCommand, handleGroupsCommand, handleInfoCommand, handleJobTemplatesCommand, handleMetadataCommand, handleMigrateCommand, handlePlanCommand, handlePullCommand, handleProjectCommand, handleRequestCommand, handleRoleGroupsCommand, handleSearchCommand, handleSchedulesCommand, handleTerminalCommand, } from "./commands/index.js";
6
+ import { handleAuthCommand, handleComponentCommand, handleDatabaseTablesCommand, handleDatabaseViewsCommand, handleDeployCommand, handleDiffCommand, handleEndpointsCommand, handleEnvCommand, handleEventsCommand, handleGroupsCommand, handleInfoCommand, handleJobTemplatesCommand, handleMetadataCommand, handleMigrateCommand, handlePlanCommand, handlePullCommand, handleProjectCommand, handleRequestCommand, handleRoleGroupsCommand, handleServiceAccountsCommand, handleSearchCommand, handleSchedulesCommand, handleTerminalCommand, } from "./commands/index.js";
7
7
  import { createHttpTraceSession, finalizeHttpTraceSession, withHttpTraceSession, } from "./http-trace.js";
8
8
  import { resolveProjectRoot } from "./project.js";
9
9
  import { withRequestQueue } from "./request-queue.js";
@@ -293,6 +293,10 @@ async function runMain(args, argv) {
293
293
  await handleRequestCommand(context);
294
294
  return;
295
295
  }
296
+ if (command === 'service-accounts') {
297
+ await handleServiceAccountsCommand(context);
298
+ return;
299
+ }
296
300
  if (command === 'role-groups') {
297
301
  await handleRoleGroupsCommand(context);
298
302
  return;
@@ -1,8 +1,9 @@
1
1
  import { RequestQueue } from './request-queue.ts';
2
- import type { ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ScheduleRecord } from './types.ts';
2
+ import type { ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ServiceAccountRecord, ScheduleRecord } from './types.ts';
3
3
  export type RequestOptions = {
4
4
  query?: Record<string, unknown>;
5
5
  body?: unknown;
6
+ sensitiveAccountPayload?: boolean;
6
7
  headers?: HeadersInit;
7
8
  authGuard?: boolean;
8
9
  spinnerLabel?: string;
@@ -139,6 +140,13 @@ export type EndpointCreatePayload = Omit<EndpointWritePayload, 'version'> & {
139
140
  path: string;
140
141
  method: string;
141
142
  };
143
+ export type ServiceAccountWritePayload = {
144
+ name?: string;
145
+ metadata?: Record<string, unknown>;
146
+ ownerId?: string;
147
+ ownerType?: 'USER' | 'GROUP';
148
+ version?: number;
149
+ };
142
150
  export type RoleGroupListRequest = {
143
151
  path?: string;
144
152
  query?: Record<string, unknown>;
@@ -209,6 +217,7 @@ export type ScheduleCreatePayload = {
209
217
  targetConfig?: Record<string, unknown> | null;
210
218
  };
211
219
  export type JobTemplateUpdatePayload = {
220
+ triggerUser?: string;
212
221
  version: number;
213
222
  name?: string;
214
223
  category?: string | null;
@@ -220,6 +229,7 @@ export type JobTemplateUpdatePayload = {
220
229
  inputs?: unknown;
221
230
  };
222
231
  export type JobTemplateCreatePayload = {
232
+ triggerUser?: string;
223
233
  name: string;
224
234
  category?: string | null;
225
235
  desc?: string;
@@ -242,12 +252,12 @@ export type GroupWritePayload = {
242
252
  category?: string | null;
243
253
  desc?: string;
244
254
  ownerId?: string;
245
- ownerType?: 'GROUP';
255
+ ownerType?: 'USER' | 'GROUP';
246
256
  };
247
257
  export type GroupCreatePayload = Omit<GroupWritePayload, 'version'> & {
248
258
  name: string;
249
259
  ownerId: string;
250
- ownerType: 'GROUP';
260
+ ownerType: 'USER' | 'GROUP';
251
261
  members: string[];
252
262
  };
253
263
  export type RoleGroupWritePayload = {
@@ -394,6 +404,18 @@ export declare class RevoClient {
394
404
  createComponent(body: unknown): Promise<unknown>;
395
405
  updateComponent(componentId: string, body: unknown): Promise<unknown>;
396
406
  deleteComponent(componentId: string): Promise<ApiResponse<unknown>>;
407
+ private accountForSync;
408
+ getAccount(userId: string): Promise<ServiceAccountRecord>;
409
+ listAllServiceAccounts(): Promise<{
410
+ serviceAccounts: ServiceAccountRecord[];
411
+ }>;
412
+ getServiceAccount(userId: string): Promise<ServiceAccountRecord>;
413
+ createServiceAccount(body: ServiceAccountWritePayload & {
414
+ name: string;
415
+ ownerId: string;
416
+ ownerType: 'USER' | 'GROUP';
417
+ }): Promise<ServiceAccountRecord>;
418
+ updateServiceAccount(userId: string, body: ServiceAccountWritePayload): Promise<ServiceAccountRecord>;
397
419
  listRoleGroups(options?: RoleGroupListRequest): Promise<unknown>;
398
420
  listAllRoleGroups(): Promise<{
399
421
  roleGroups: RoleGroupRecord[];
@@ -521,7 +521,7 @@ export class RevoClient {
521
521
  const traceRequest = beginHttpTraceRequest({
522
522
  method,
523
523
  url,
524
- body: body,
524
+ body: options.sensitiveAccountPayload ? '[account payload omitted]' : body,
525
525
  context: this.environmentName ? { environment: this.environmentName } : undefined,
526
526
  });
527
527
  const maxRetries = options.maxRetries ?? this.maxRetries;
@@ -599,10 +599,13 @@ export class RevoClient {
599
599
  status: response.status,
600
600
  ok: accepted,
601
601
  responseHeaders: response.headers,
602
- responseData: data,
602
+ responseData: options.sensitiveAccountPayload ? '[account payload omitted]' : data,
603
603
  responseBytes: responseSize(data, response.headers),
604
604
  });
605
605
  if (!response.ok && response.status !== 304) {
606
+ if (options.sensitiveAccountPayload) {
607
+ data = { message: `Account request failed (HTTP ${response.status}).` };
608
+ }
606
609
  if (response.status === 401) {
607
610
  saveAuthValidationState({
608
611
  key: this.authValidationKey,
@@ -1174,6 +1177,68 @@ export class RevoClient {
1174
1177
  spinnerLabel: 'Deleting component',
1175
1178
  });
1176
1179
  }
1180
+ accountForSync(value) {
1181
+ const wrapper = isRecord(value) && isRecord(value.data) ? value.data : value;
1182
+ if (!isRecord(wrapper)) {
1183
+ throw new Error('Invalid account response.');
1184
+ }
1185
+ const record = {};
1186
+ for (const field of ['userId', 'name', 'serviceAccount', 'ownerId', 'ownerType', 'version', 'deletedAt']) {
1187
+ if (wrapper[field] !== undefined) {
1188
+ Object.assign(record, { [field]: wrapper[field] });
1189
+ }
1190
+ }
1191
+ const metadata = isRecord(wrapper.metadata) ? wrapper.metadata : wrapper.metaData;
1192
+ if (isRecord(metadata)) {
1193
+ record.metadata = metadata;
1194
+ }
1195
+ return record;
1196
+ }
1197
+ async getAccount(userId) {
1198
+ return this.accountForSync(await this.requestData('GET', `/api/v1/accounts/${encodeURIComponent(userId)}`, { sensitiveAccountPayload: true }));
1199
+ }
1200
+ async listAllServiceAccounts() {
1201
+ const serviceAccounts = [];
1202
+ let skip = 0;
1203
+ const seenIds = new Set();
1204
+ while (true) {
1205
+ // Use unfiltered page sizes/total for offsets: /accounts also lists humans.
1206
+ const page = unwrapListPage(await this.requestData('GET', '/api/v1/accounts', {
1207
+ sensitiveAccountPayload: true,
1208
+ query: { take: COMPONENT_LIST_PAGE_SIZE, skip, count: true },
1209
+ }));
1210
+ for (const item of page.items) {
1211
+ const account = this.accountForSync(item);
1212
+ if (account.serviceAccount === true && !account.deletedAt) {
1213
+ if (!account.userId || seenIds.has(account.userId)) {
1214
+ throw new Error('Invalid or repeated account ID while listing service accounts.');
1215
+ }
1216
+ seenIds.add(account.userId);
1217
+ serviceAccounts.push(account);
1218
+ }
1219
+ }
1220
+ skip += page.items.length;
1221
+ if (page.items.length === 0 || (page.total !== null && skip >= page.total)
1222
+ || (page.total === null && page.items.length < COMPONENT_LIST_PAGE_SIZE)) {
1223
+ break;
1224
+ }
1225
+ }
1226
+ return { serviceAccounts };
1227
+ }
1228
+ async getServiceAccount(userId) {
1229
+ const account = await this.getAccount(userId);
1230
+ if (account.serviceAccount !== true || account.deletedAt) {
1231
+ throw new Error('Account is not an active service account.');
1232
+ }
1233
+ return account;
1234
+ }
1235
+ async createServiceAccount(body) {
1236
+ return this.accountForSync(await this.requestData('POST', '/api/v1/accounts/createServiceAccount', { body, sensitiveAccountPayload: true }));
1237
+ }
1238
+ async updateServiceAccount(userId, body) {
1239
+ await this.getServiceAccount(userId);
1240
+ return this.accountForSync(await this.requestData('PUT', `/api/v1/accounts/${encodeURIComponent(userId)}`, { body, sensitiveAccountPayload: true }));
1241
+ }
1177
1242
  async listRoleGroups(options = {}) {
1178
1243
  return this.requestData('GET', options.path || '/api/v1/role-groups', {
1179
1244
  query: options.query,
@@ -617,6 +617,7 @@ function migrateComponentLockIdentity(cwd, identity, localCatalog, remoteCatalog
617
617
  components: migratedComponents,
618
618
  groups: lock.groups,
619
619
  roleGroups: lock.roleGroups,
620
+ serviceAccounts: lock.serviceAccounts,
620
621
  jobTemplates: lock.jobTemplates,
621
622
  schedules: lock.schedules,
622
623
  events: lock.events,
@@ -12,6 +12,7 @@ export * from './metadata.ts';
12
12
  export * from './migrate.ts';
13
13
  export * from './project.ts';
14
14
  export * from './request.ts';
15
+ export * from './service-accounts.ts';
15
16
  export * from './role-groups.ts';
16
17
  export * from './search.ts';
17
18
  export * from './terminal.ts';
@@ -12,6 +12,7 @@ export * from "./metadata.js";
12
12
  export * from "./migrate.js";
13
13
  export * from "./project.js";
14
14
  export * from "./request.js";
15
+ export * from "./service-accounts.js";
15
16
  export * from "./role-groups.js";
16
17
  export * from "./search.js";
17
18
  export * from "./terminal.js";
@@ -30,6 +30,8 @@ const RESOURCE_ALIASES = {
30
30
  events: 'event',
31
31
  group: 'group',
32
32
  groups: 'group',
33
+ 'service-account': 'service-account',
34
+ 'service-accounts': 'service-account',
33
35
  'role-group': 'role-group',
34
36
  'role-groups': 'role-group',
35
37
  rolegroup: 'role-group',
@@ -39,6 +41,7 @@ const MIGRATION_RESOURCE_ORDER = [
39
41
  'database-table',
40
42
  'database-view',
41
43
  'component',
44
+ 'service-account',
42
45
  'job-template',
43
46
  'endpoint',
44
47
  'schedule',
@@ -60,7 +63,7 @@ function readMigrationResources(context, commandLabel = 'Migration') {
60
63
  for (const value of values) {
61
64
  const resource = RESOURCE_ALIASES[value];
62
65
  if (!resource) {
63
- throw new Error(`${commandLabel} currently supports: database-table, database-view, component, job-template, endpoint, schedule, event, group, role-group, or all.`);
66
+ throw new Error(`${commandLabel} currently supports: database-table, database-view, component, job-template, endpoint, schedule, event, group, role-group, service-account, or all.`);
64
67
  }
65
68
  if (!resources.includes(resource)) {
66
69
  resources.push(resource);
@@ -114,6 +117,9 @@ function printMigrationPlan(context, plan) {
114
117
  : 'configured workspace';
115
118
  context.println(`Source snapshot: ${plan.sourcePull.pulled} pulled, ${plan.sourcePull.pruned} pruned, ${plan.sourcePull.skipped} skipped in ${pullLocation}.`);
116
119
  }
120
+ if (plan.identityOrder?.length) {
121
+ context.println(`Identity order before consumers: ${plan.identityOrder.map((node) => `${node.resource}:${node.stableKey}`).join(' -> ')}.`);
122
+ }
117
123
  for (const phase of plan.phases) {
118
124
  const pull = plan.sourcePull.byResource[phase.resource];
119
125
  if (pull) {
@@ -184,6 +190,10 @@ function printMigrationPlan(context, plan) {
184
190
  blockers: phase.blockers,
185
191
  });
186
192
  }
193
+ if (phase.resource === 'service-account' && plan.serviceAccounts) {
194
+ printSyncPlan(context.println, { title: `${phaseLabel} phase ${phase.order} / Service Account`, environment: plan.to,
195
+ counts: phase.operations, items: plan.serviceAccounts.items, warnings: phase.warnings, blockers: phase.blockers });
196
+ }
187
197
  if (phase.resource === 'job-template' && plan.jobTemplates) {
188
198
  printSyncPlan(context.println, {
189
199
  title: `${phaseLabel} phase ${phase.order} / Job Template`,
@@ -644,7 +654,7 @@ export async function handleMigrateCommand(context) {
644
654
  const dryRun = readBoolFlag(context.args, ['dry-run']);
645
655
  const subcommand = dryRun ? 'plan' : requestedSubcommand;
646
656
  if (requestedSubcommand !== 'plan' && requestedSubcommand !== 'run' && requestedSubcommand !== 'verify') {
647
- throw new Error('Unknown migrate command. Usage: revo migrate <plan|run|verify> --from <env> --to <env> [--resources database-table,database-view,component,job-template,endpoint,schedule,event,group,role-group] [--skip-groups] [--dry-run]');
657
+ throw new Error('Unknown migrate command. Usage: revo migrate <plan|run|verify> --from <env> --to <env> [--resources database-table,database-view,component,job-template,endpoint,schedule,event,group,role-group,service-account] [--skip-groups] [--dry-run]');
648
658
  }
649
659
  const input = readMigrationInput(context);
650
660
  const json = readBoolFlag(context.args, ['json']);
@@ -0,0 +1,2 @@
1
+ import type { CommandContext } from '../types.ts';
2
+ export declare function handleServiceAccountsCommand(context: CommandContext): Promise<void>;
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolveProjectRoot, readProjectStableKeyName } from "../project.js";
4
+ import { resolveResourceTarget } from "../resource-target.js";
5
+ import { buildServiceAccountsPlan, pullServiceAccountsToWorkspace, pushServiceAccounts } from "../resource-syncs/service-account-sync.js";
6
+ import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
7
+ import { printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
8
+ import { readBoolFlag } from "../utils.js";
9
+ function warnAboutExperimentalState(context) {
10
+ const projectRoot = resolveProjectRoot(context.cwd) || path.resolve(context.cwd);
11
+ const legacyPaths = [
12
+ path.join(projectRoot, '.revoengine', 'resources'),
13
+ path.join(projectRoot, '.revoengine', 'resources.lock.json'),
14
+ path.join(projectRoot, '.revoengine', 'plans'),
15
+ ].filter((candidate) => fs.existsSync(candidate));
16
+ if (legacyPaths.length > 0) {
17
+ const warning = `Ignoring experimental ${legacyPaths.map((candidate) => path.relative(projectRoot, candidate)).join(', ')}; service-accounts use workspace/ServiceAccounts and .revoengine/revo.lock.json.`;
18
+ if (readBoolFlag(context.args, ['json'])) {
19
+ (context.warn || context.error)(warning);
20
+ }
21
+ else {
22
+ context.println(warning);
23
+ }
24
+ }
25
+ }
26
+ async function handlePull(context) {
27
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
28
+ throw new Error('Service-account pull currently requires --all.');
29
+ }
30
+ const { client, envName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
31
+ const startedAt = Date.now();
32
+ const result = await pullServiceAccountsToWorkspace({
33
+ client,
34
+ cwd: context.cwd,
35
+ envName,
36
+ stableKeyName: readProjectStableKeyName(context.cwd),
37
+ force: readBoolFlag(context.args, ['force', 'f']),
38
+ });
39
+ if (readBoolFlag(context.args, ['json'])) {
40
+ context.print(result);
41
+ return;
42
+ }
43
+ const outputResults = [];
44
+ for (const pulled of result.pulled) {
45
+ printSyncStatus(context.println, { status: 'Pulled', direction: 'pull', targetPath: pulled.targetPath });
46
+ outputResults.push({ status: 'pulled', targetPath: pulled.targetPath });
47
+ }
48
+ for (const skipped of result.skipped) {
49
+ printSyncStatus(context.println, { status: 'Skipped', direction: 'pull', targetPath: skipped.targetPath, reason: skipped.reason });
50
+ outputResults.push({ status: 'skipped', targetPath: skipped.targetPath, reason: skipped.reason });
51
+ }
52
+ printSyncSummary(context.println, 'Pulled', outputResults, Date.now() - startedAt);
53
+ }
54
+ async function handlePlan(context) {
55
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
56
+ throw new Error('Service-account plan currently requires --all.');
57
+ }
58
+ if (readBoolFlag(context.args, ['prune'])) {
59
+ throw new Error('Service-account prune is disabled until the backend soft-delete contract is confirmed.');
60
+ }
61
+ const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
62
+ const plan = await buildServiceAccountsPlan({
63
+ client,
64
+ cwd: context.cwd,
65
+ envName,
66
+ stableKeyName: readProjectStableKeyName(context.cwd),
67
+ });
68
+ if (readBoolFlag(context.args, ['json'])) {
69
+ context.print(plan);
70
+ }
71
+ else {
72
+ printSyncPlan(context.println, {
73
+ title: 'Service-account',
74
+ environment: displayName,
75
+ counts: plan.counts,
76
+ showHints: readBoolFlag(context.args, ['hints']),
77
+ items: plan.items.map((item) => ({
78
+ ...item,
79
+ details: [],
80
+ })),
81
+ blockers: plan.blockers,
82
+ warnings: plan.exclusions,
83
+ });
84
+ }
85
+ if (readBoolFlag(context.args, ['strict'])) {
86
+ const drift = plan.items.filter((item) => !['clean', 'orphan', 'skipped'].includes(item.status));
87
+ if (plan.blockers.length > 0 || drift.length > 0) {
88
+ throw new Error(`Service-account plan is not clean: ${drift.length} drift item(s), ${plan.blockers.length} blocker(s).`);
89
+ }
90
+ }
91
+ }
92
+ async function handlePush(context) {
93
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
94
+ throw new Error('Service-account push currently requires --all.');
95
+ }
96
+ if (readBoolFlag(context.args, ['prune'])) {
97
+ throw new Error('Service-account prune is disabled until the backend soft-delete contract is confirmed.');
98
+ }
99
+ const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
100
+ if (!readBoolFlag(context.args, ['yes', 'y'])) {
101
+ if (!isInteractiveTerminal() || !await promptConfirm(`Push service-accounts to "${displayName}"?`, false)) {
102
+ throw new Error('Service-account push requires confirmation. Re-run with --yes or use an interactive terminal.');
103
+ }
104
+ }
105
+ const startedAt = Date.now();
106
+ const result = await pushServiceAccounts({
107
+ client,
108
+ cwd: context.cwd,
109
+ envName,
110
+ stableKeyName: readProjectStableKeyName(context.cwd),
111
+ force: readBoolFlag(context.args, ['force', 'f']),
112
+ });
113
+ if (readBoolFlag(context.args, ['json'])) {
114
+ context.print(result);
115
+ }
116
+ else {
117
+ for (const item of result.results) {
118
+ const label = item.status === 'deployed' ? 'Deployed' : item.status === 'failed' ? 'Failed' : 'Skipped';
119
+ printSyncStatus(context.println, {
120
+ status: label,
121
+ direction: 'push',
122
+ targetPath: item.targetPath,
123
+ reason: item.error || item.reason,
124
+ });
125
+ }
126
+ printSyncSummary(context.println, 'Deployed', result.results, Date.now() - startedAt);
127
+ }
128
+ const failed = result.results.filter((item) => item.status === 'failed');
129
+ if (failed.length > 0) {
130
+ throw new Error(`Service-account push finished with ${failed.length} failure(s).`);
131
+ }
132
+ }
133
+ export async function handleServiceAccountsCommand(context) {
134
+ warnAboutExperimentalState(context);
135
+ const subcommand = context.args._[1] || '';
136
+ if (subcommand === 'pull') {
137
+ await handlePull(context);
138
+ return;
139
+ }
140
+ if (subcommand === 'plan') {
141
+ await handlePlan(context);
142
+ return;
143
+ }
144
+ if (subcommand === 'push') {
145
+ await handlePush(context);
146
+ return;
147
+ }
148
+ throw new Error('Unknown service-accounts command. Usage: revo service-accounts <pull|plan|push> --all [--env <name>]');
149
+ }
@@ -1,4 +1,4 @@
1
- export type BrowserAction = 'navigate' | 'dom' | 'click' | 'fill' | 'check' | 'select' | 'press' | 'scroll' | 'wait_for' | 'screenshot';
1
+ export type BrowserAction = 'navigate' | 'dom' | 'click' | 'fill' | 'check' | 'select' | 'press' | 'scroll' | 'wait_for' | 'screenshot' | 'tabs' | 'new_tab' | 'select_tab' | 'close_tab' | 'close';
2
2
  export type BrowserCapture = 'viewport' | 'full_page' | 'element' | 'crop';
3
3
  export type BrowserClip = {
4
4
  x: number;
@@ -10,7 +10,9 @@ export type BrowserActionInput = {
10
10
  url: string;
11
11
  action: BrowserAction;
12
12
  workspace: string;
13
+ agentTerminalWorkspaceId?: string;
13
14
  browserSessionId: string;
15
+ tabId?: string;
14
16
  selector?: string | null;
15
17
  width?: number;
16
18
  height?: number;
@@ -20,29 +22,54 @@ export type BrowserActionInput = {
20
22
  deltaY?: number;
21
23
  state?: 'visible' | 'hidden';
22
24
  waitTimeoutMs?: number;
25
+ actionTimeoutMs?: number;
23
26
  capture?: BrowserCapture;
24
27
  clip?: BrowserClip;
25
28
  localOnly?: boolean;
26
29
  networkAccessExpiresAt?: number | null;
27
30
  networkAccessOnce?: boolean;
31
+ networkAccessForThread?: boolean;
32
+ actorUserId?: string;
33
+ threadId?: string;
34
+ policyGrantRevision?: number;
28
35
  signal?: AbortSignal;
29
36
  onActionAttempt?: () => void;
30
37
  };
38
+ export type BrowserTab = {
39
+ id: string;
40
+ title: string;
41
+ url: string;
42
+ active: boolean;
43
+ };
31
44
  export type BrowserActionResult = {
32
45
  dom: string;
33
46
  pageUrl: string;
34
47
  screenshotPath?: string;
48
+ browserSessionId: string;
49
+ activeTabId: string | null;
50
+ tabs: BrowserTab[];
51
+ sessionCreated: boolean;
35
52
  };
36
53
  export declare function browserUrl(value: string): string;
37
54
  export declare function localBrowserUrl(value: string): string;
38
55
  export declare function validateBrowserActionInput(input: BrowserActionInput): void;
39
56
  export declare function closeBrowserSessions(): Promise<void>;
40
- export declare function reconcileBrowserSessions(networkMode: 'restricted' | 'sandbox' | 'external'): Promise<number>;
57
+ export declare function reconcileBrowserSessions(networkMode: 'restricted' | 'sandbox' | 'external', policyGrantRevision?: number): Promise<number>;
58
+ export declare function threadBrowserScopes(): Array<{
59
+ browserSessionId: string;
60
+ actorUserId: string;
61
+ threadId: string;
62
+ policyGrantRevision: number;
63
+ networkAccess: 'local' | 'full';
64
+ }>;
65
+ export declare function closeThreadBrowserSession(browserSessionId: string): Promise<void>;
66
+ export declare function browserSessionIds(): string[];
41
67
  export declare function hasBrowserSessions(): boolean;
42
68
  export declare function writePrivateScreenshot(file: string, bytes: Buffer): void;
43
69
  export declare function runBrowserAction(input: BrowserActionInput): Promise<BrowserActionResult>;
44
70
  export declare function fillBrowserSecret(input: {
45
71
  browserSessionId: string;
72
+ browserTabId?: string;
46
73
  origin: string;
47
74
  selector: string;
48
75
  value: string;