@revoengine/cli 1.0.21 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,6 +82,8 @@ revo terminal connect --workspace "$HOME/projects/my-project" --name "Work Mac"
82
82
  revo terminal status
83
83
  ```
84
84
 
85
+ For an existing registration, `connect --terminal-id <uuid> --realtime-url <url>` overrides its Realtime endpoint for that invocation without pairing again or changing the saved registration. The URL is normalized to the runner WebSocket route; remote endpoints require TLS.
86
+
85
87
  An approved terminal can run as a per-user background service on macOS or Linux. The service uses the active project at installation, or an explicit `--project <name>`; use the same project when uninstalling after a switch.
86
88
 
87
89
  ```bash
@@ -90,7 +92,9 @@ revo terminal service uninstall --workspace "$HOME/projects/my-project" --name "
90
92
  revo terminal disconnect --workspace "$HOME/projects/my-project" --name "Work Mac"
91
93
  ```
92
94
 
93
- Stop the foreground runner before installing its service. The service starts at login, reconnects automatically, and pins the selected terminal UUID and project profile at installation. Multiple terminals can share one machine and workspace when they have distinct names; pass the same `--name` to `connect`, `service install|uninstall`, and `disconnect`. Without `--name`, the CLI uses the machine hostname. If two registrations have the same name, the CLI refuses an ambiguous choice; use `revo terminal status` to find the UUID and pass `--terminal-id <uuid>`. A legacy workspace service must be uninstalled before installing a terminal-specific service. Uninstall stops the selected service but keeps its grant and local registration. `disconnect` revokes only the selected grant and removes its local credential; uninstall its service first. On macOS, service logs are in `~/Library/Logs/RevoEngine/`. On Linux, inspect them with `journalctl --user -u <unit-name>`; `install` prints the unit name. Linux user services normally stop after logout unless an administrator enables user lingering.
95
+ Stop the foreground runner before installing its service. The service starts at login, reconnects automatically, and pins the selected terminal UUID and project profile at installation. Multiple terminals can share one machine and workspace when they have distinct names; pass the same `--name` to `connect`, `service install|uninstall`, and `disconnect`. Without `--name`, the CLI uses the machine hostname. If two registrations have the same name, the CLI refuses an ambiguous choice; use `revo terminal status` to find the UUID and pass `--terminal-id <uuid>`. A legacy workspace service must be uninstalled before installing a terminal-specific service. Uninstall stops the selected service but keeps its grant and local registration. `disconnect` stops/removes the selected terminal-specific service, revokes its grant and removes its local credential. Uninstall a legacy workspace service first so it cannot affect a different terminal. On macOS, service logs are in `~/Library/Logs/RevoEngine/`. On Linux, inspect them with `journalctl --user -u <unit-name>`; `install` prints the unit name. Linux user services normally stop after logout unless an administrator enables user lingering.
96
+
97
+ The runner retries temporary API startup failures and WebSocket outages without a retry-count limit, using exponential backoff capped at 30 seconds with jitter. Startup reads have a 30-second request deadline; pairing and other writes are not automatically repeated. Ctrl+C or SIGTERM interrupts both a pending API request and a reconnect wait. Realtime restarts and Cloud Run connection timeouts renew transport without revoking the device. A newly supported ACL-change renewal immediately stops work under the old connection and reconnects against the current approved grant; it never extends the old command permission. Older runners stop on that change and need restarting. Actual grant/account/API-key revocation, expiration or invalid frames stop the runner; background services do not restart these deliberate security cutoffs. Availability has no fixed 30-day runner expiry, but depends on the machine, network, valid credentials and supervisor remaining available. An outage longer than the three-minute recovery window stops existing processes and Browser sessions; the runner continues reconnecting afterward.
94
98
 
95
99
  Runner credentials are stored in `runner.json` beside the CLI configuration. Each executed shell command writes raw output to a private `runner-logs/<executionId>.log` there, capped at 10 MB per file. Logs older than 24 hours are removed when the next command starts; a runner left idle does not perform timed cleanup. Optional CLI HTTP tracing writes sanitized request metadata under the project `.revoengine/logs/http-trace/`. These are separate from the Assistant's server-side tool history and do not form a complete local transcript. Treat runner logs as sensitive because command output may contain secrets.
96
100
 
@@ -433,7 +437,7 @@ revo schedules push --all --yes --force
433
437
 
434
438
  `--force` permits adopting a missing Schedule baseline or overwriting reviewed target drift. It also approves a reviewed transition between Job Template and Materialized View targets under one Schedule Stable Key. Materialized View refresh Schedules are included with the other Schedules and identify their Database View by Stable Key and refresh mode, never by a source UUID. User-managed `JOB_TEMPLATE` and `PLATFORM_OPERATION` schedules of kind `refresh_materialized_view` are supported. Other platform operations, `AGENT`, and system-managed Schedules are excluded; `--strict` treats exclusions as incomplete coverage.
435
439
 
436
- Pull initializes each Schedule's editable activation candidate from the source. A new target Schedule is created inactive, while a configuration update preserves its target activation state. `schedules push --all --yes --activate` activates only candidates created or updated and verified during that push; unchanged Schedules are not activated. Interactive activation asks for a second confirmation. Repository `deploy` and named `migrate` leave this activation step to the dedicated command.
440
+ Pull initializes each Schedule's editable activation candidate from the source. A new target Schedule is created inactive, while a configuration update preserves its target activation state. `activationCandidate` records the desired active state. Plans report activation-only differences as `activation-drift`, including without a target lock baseline; repository plans mark them as pending changes, and strict plans or deployment verification do not report convergence until they are aligned. `schedules push --all --yes --activate` aligns verified new, updated and otherwise unchanged Schedules with manifest activation intent, including disabling them. Failed configuration preflight skips activation; changed definitions or dependencies block activation. Interactive activation asks for a second confirmation. Repository `deploy` and named `migrate` leave this activation step to the dedicated command.
437
441
 
438
442
  Use `--project` to select a saved project explicitly (`--env` remains a compatible alias):
439
443
 
@@ -458,6 +462,8 @@ revo database-tables push 'Sales/Orders#1234abcd' --project target --yes
458
462
  revo database-views push 'Sales/Revenue#1234abcd' --project target --yes
459
463
  ```
460
464
 
465
+ Endpoint route uniqueness applies to live resources, matching the API. Soft-deleted endpoints with other Stable Keys do not reserve routes. Exact-key restore also checks the endpoint's old route during planning and again immediately before restoration, even when the desired path changes. The backend remains the final authority for concurrent route changes.
466
+
461
467
  Database View plans show a line diff for changed RAW_SQL queries, including unchanged context and red/green removed and added lines in color terminals.
462
468
 
463
469
  Preview failures use `validation-failed`, preserve the definition diff, and show the backend message, HTTP status, definition mode, and timeout information. RAW_SQL failures also suggest checking whether the instance enables RAW SQL Database Views. They block deployment of the affected view even with `--force`; `database-views push` continues with independent views but exits unsuccessfully if validation failed. An unchanged view skips planning preview only when its target hash and source-table dependency fingerprint match the environment lock; old locks still require preview. Pull and verified push update this fingerprint, while plan remains fileless. Creates and updates always revalidate immediately before writing.
@@ -495,7 +501,7 @@ Resource plans support `--json` for automation and generally support `--strict`
495
501
  - `--force` approves only explicitly supported risky or drifted operations; it is not a universal bypass.
496
502
  - Writes resolve the target UUID and version immediately before mutation and verify the portable result afterward.
497
503
  - Stable Keys cross environments; source UUIDs, versions, members, users, ACLs, and other target-local identities do not.
498
- - New Schedules and Events are created inactive; ordinary updates preserve target activation. Dedicated `schedules push --all --yes --activate` activates only flagged candidates written and verified in that push, not unchanged Schedules. `events push --all --yes --activate` aligns verified Events with manifest activation intent, including disabling them; configuration failures skip Event activation. Interactive activation requires an additional confirmation. `deploy` and `migrate` do not run this activation phase.
504
+ - New Schedules and Events are created inactive; ordinary updates preserve target activation. Dedicated `schedules push --all --yes --activate` aligns manifest activation intent for verified new, updated and otherwise unchanged Schedules, including disabling them. Activation drift is shown by plans and prevents repository strict-plan/deployment convergence until aligned. `events push --all --yes --activate` aligns verified Events with manifest activation intent, including disabling them; configuration failures skip Event activation. Interactive activation requires an additional confirmation. `deploy` and `migrate` do not run this activation phase.
499
505
  - Groups and Role Groups are intentionally late phases because they can affect ownership and access.
500
506
  - Lock data is stored in `.revoengine/revo.lock.json`; API tokens are never persisted in the project.
501
507
 
@@ -622,3 +628,16 @@ Agent `config.memory`, workspace files, conversations, runs, terminal selection,
622
628
  MCP URLs must use public HTTPS without embedded credentials, query or fragment. New authenticated MCP plugins (including inline plugins) require manual target-local authentication setup and the matching Stable Key before deployment. CLI preserves existing target MCP authentication; it neither provisions secrets nor invokes MCP test/sync or an external provider. Unauthenticated MCP definitions can be created normally. Legacy numeric Component revision pins require a portable `componentDigest` before export; Vault-bound tool inputs and instance-specific rollout snapshots are rejected rather than copied.
623
629
 
624
630
  Agent and Agent Plugin synchronization is upsert-only. Repository prune blocks deletion of either family; retained Agents and inline/registry plugin references also protect Components, Groups and Service Accounts from unsafe pruning. Existing Service Account synchronization remains unchanged, including target-local credentials and membership policy.
631
+
632
+
633
+ ### Deployment verification in 1.0.22
634
+
635
+ Portable comparison includes ordinary Component metadata and full structured Database Table / Materialized View index definitions (logical names, methods, expressions, predicates, ordering, null placement, collation, operator classes and included columns). Physical index names, resource IDs and backend-reserved metadata remain instance-local. Older table/view manifests that omitted index settings should be refreshed from the source before promotion.
636
+
637
+ Endpoint and Job Template pins use the API content identity `v1:sha256:<64 lowercase hex characters>`, independently of the configuration hash. Latest bindings explicitly clear old digest pins. Endpoint `pinnedDigest` fingerprints from older CLI versions are upgraded in memory only when their exact local Component source proves the content identity; otherwise re-pull the source definition. Numeric-only Job Template pins remain explicitly unsupported; use a canonical digest pin instead.
638
+
639
+ Schedule and Event activation differences remain pending changes even if their configuration matches. Ordinary deployment preserves activation; use the existing explicit `schedules push --all --yes --activate` or `events push --all --yes --activate` step to align it. Strict plans and final verification cannot report convergence until activation matches. Deprecated Schedule `targetVersion` is reported diagnostically; the backend does not use it to select a Job Template revision.
640
+
641
+ `CUSTOM_NODEJS` deployment verifies runtime availability and the active desired revision after source readback. Automatic deployment waits up to two minutes for readiness; failed attempts, manual activation requirements and unavailable/pending revisions fail verification without adopting a deployment baseline. Re-run after the runtime is ready. Named `env diff/apply` also reports unavailable unchanged custom runtimes and returns an error on unverified writes. Definition synchronization does not invoke provider/plugin tests; component dependencies and their pinned revisions are checked with read-only API calls, including unchanged definitions.
642
+
643
+ Execution options are compared without hiding runtime differences: missing Job Template memory means 256 MB; explicit 128 MB remains distinct. An empty `options.input` overrides legacy `inputs`. Endpoint `memory: null` remains distinct from 32 MB. If the backend substitutes a different value, readback verification fails rather than recording false convergence.
@@ -45,9 +45,12 @@ export type DatabaseSchemaMetadataWritePayload = {
45
45
  export type DatabaseSchemaUpdatePayload = Omit<DatabaseSchemaMetadataWritePayload, 'metadata'> & {
46
46
  name?: string;
47
47
  metadata?: Record<string, unknown>;
48
- category?: string;
48
+ category?: string | null;
49
49
  desc?: string;
50
50
  definition?: Record<string, unknown>[];
51
+ options?: {
52
+ indexes: Record<string, unknown>[];
53
+ };
51
54
  };
52
55
  export type DatabaseSchemaCreatePayload = {
53
56
  name: string;
@@ -57,6 +60,9 @@ export type DatabaseSchemaCreatePayload = {
57
60
  definition?: Record<string, unknown>[];
58
61
  partition?: Record<string, unknown>;
59
62
  parent?: string;
63
+ options?: {
64
+ indexes: Record<string, unknown>[];
65
+ };
60
66
  audit?: false;
61
67
  restricted?: boolean;
62
68
  };
@@ -84,9 +90,8 @@ export type DatabaseViewCreatePayload = {
84
90
  groups: [];
85
91
  uniqueKey?: string[];
86
92
  indexes?: Array<{
87
- columns: Array<{
88
- name: string;
89
- }>;
93
+ [key: string]: unknown;
94
+ columns: Array<Record<string, unknown>>;
90
95
  unique?: boolean;
91
96
  }>;
92
97
  } & ({
@@ -109,9 +114,7 @@ export type DatabaseViewUpdatePayload = {
109
114
  uniqueKey?: string[];
110
115
  indexes?: Array<{
111
116
  name?: string;
112
- columns: Array<{
113
- name: string;
114
- }>;
117
+ columns: Array<Record<string, unknown>>;
115
118
  unique?: boolean;
116
119
  [key: string]: unknown;
117
120
  }>;
@@ -132,6 +135,7 @@ export type EndpointWritePayload = {
132
135
  desc?: string;
133
136
  componentId?: string | null;
134
137
  componentVersion?: number | null;
138
+ componentDigest?: string | null;
135
139
  timeout?: number;
136
140
  path?: string;
137
141
  method?: string;
@@ -251,6 +255,8 @@ export type JobTemplateUpdatePayload = {
251
255
  desc?: string;
252
256
  metadata?: Record<string, unknown>;
253
257
  componentId?: string;
258
+ componentDigest?: string | null;
259
+ componentVersion?: number | null;
254
260
  timeout?: number | null;
255
261
  options?: unknown;
256
262
  inputs?: unknown;
@@ -263,6 +269,8 @@ export type JobTemplateCreatePayload = {
263
269
  desc?: string;
264
270
  metadata: Record<string, unknown>;
265
271
  componentId: string;
272
+ componentDigest?: string | null;
273
+ componentVersion?: number | null;
266
274
  timeout?: number;
267
275
  options?: unknown;
268
276
  inputs?: unknown;
@@ -418,6 +426,13 @@ export declare class RevoClient {
418
426
  activateEndpoint(endpointId: string): Promise<void>;
419
427
  disableEndpoint(endpointId: string): Promise<void>;
420
428
  restoreEndpoint(endpointId: string): Promise<void>;
429
+ resolveComponentDigest(digest: string): Promise<Array<{
430
+ componentId: string;
431
+ digest: string;
432
+ version: number;
433
+ current?: boolean;
434
+ }>>;
435
+ getComponentRuntime(componentId: string): Promise<unknown>;
421
436
  getComponentSnapshotVersion(componentId: string, version: number): Promise<ComponentRecord>;
422
437
  getEditorTypes(requestPath?: string): Promise<unknown>;
423
438
  debugComponent(requestPath: string, body: unknown): Promise<unknown>;
@@ -487,6 +502,7 @@ export declare class RevoClient {
487
502
  createSchedule(body: ScheduleCreatePayload): Promise<ScheduleResponse>;
488
503
  updateSchedule(scheduleId: string, body: ScheduleWritePayload): Promise<ScheduleResponse>;
489
504
  activateSchedule(scheduleId: string): Promise<unknown>;
505
+ disableSchedule(scheduleId: string): Promise<unknown>;
490
506
  listEvents(options?: EventListRequest): Promise<unknown>;
491
507
  listAllEvents({ includeDeleted }?: EventListAllOptions): Promise<{
492
508
  events: EventRecord[];
@@ -1023,6 +1023,15 @@ export class RevoClient {
1023
1023
  spinnerLabel: 'Restoring endpoint',
1024
1024
  });
1025
1025
  }
1026
+ async resolveComponentDigest(digest) {
1027
+ const result = await this.requestData('GET', `/api/v1/component/digest/${encodeURIComponent(digest)}`);
1028
+ if (!Array.isArray(result.data))
1029
+ throw new Error('Incomplete component digest response.');
1030
+ return result.data;
1031
+ }
1032
+ async getComponentRuntime(componentId) {
1033
+ return this.requestData('GET', `/api/v1/component/${encodeURIComponent(componentId)}/runtime`);
1034
+ }
1026
1035
  async getComponentSnapshotVersion(componentId, version) {
1027
1036
  return this.requestData('GET', `/api/v1/activity/${encodeURIComponent(componentId)}/${encodeURIComponent(String(version))}`, { query: { refType: 'COMPONENTS' } });
1028
1037
  }
@@ -1517,6 +1526,11 @@ export class RevoClient {
1517
1526
  spinnerLabel: 'Activating schedule',
1518
1527
  });
1519
1528
  }
1529
+ async disableSchedule(scheduleId) {
1530
+ return this.requestData('POST', `/api/v1/automation/schedule/${scheduleId}/disable`, {
1531
+ spinnerLabel: 'Disabling schedule',
1532
+ });
1533
+ }
1520
1534
  async listEvents(options = {}) {
1521
1535
  return this.requestData('GET', options.path || '/api/v1/automation/event', {
1522
1536
  query: options.query,
@@ -1,3 +1,4 @@
1
+ import { verifyComponentRuntime } from "../component-contract.js";
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { execFileSync } from 'node:child_process';
@@ -1184,6 +1185,7 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1184
1185
  });
1185
1186
  throw new Error(`Cannot push ${targetPath}: created component did not verify against local source. Diagnostic: ${logPath}`);
1186
1187
  }
1188
+ await verifyComponentRuntime(client, refreshedRemote, 120_000);
1187
1189
  upsertLockFromRemote(context, refreshedRemote, targetPath, component, context.componentEnvironment);
1188
1190
  const result = { status: 'deployed', targetPath };
1189
1191
  printSyncStatus(println, { status: 'Deployed', direction: 'push', targetPath });
@@ -1206,6 +1208,8 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1206
1208
  if (!remoteComponentId) {
1207
1209
  throw new Error(`Remote component matched by ${identityDescription(identity)} "${identityKey}" has no componentId.`);
1208
1210
  }
1211
+ if (componentSourceHash(component, identity) === componentSourceHash(remote, identity))
1212
+ await verifyComponentRuntime(client, remote);
1209
1213
  const typeTransitionBlocker = componentTypeTransitionBlocker(component, remote);
1210
1214
  if (typeTransitionBlocker) {
1211
1215
  throw new Error(`Cannot push ${targetPath}: ${typeTransitionBlocker}`);
@@ -1365,6 +1369,7 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1365
1369
  });
1366
1370
  throw new Error(`Cannot push ${targetPath}: updated component did not verify against local source. Diagnostic: ${logPath}`);
1367
1371
  }
1372
+ await verifyComponentRuntime(client, refreshedRemote, 120_000);
1368
1373
  upsertLockFromRemote(context, refreshedRemote, targetPath, component, context.componentEnvironment);
1369
1374
  if (!configurationChanged && !elementsChanged) {
1370
1375
  const result = {
@@ -1681,6 +1686,18 @@ export async function buildComponentPlan(context, scope = { enabled: false, base
1681
1686
  ...(scope.enabled ? { inScope } : {}),
1682
1687
  };
1683
1688
  });
1689
+ for (const item of items) {
1690
+ if (item.componentType !== 'CUSTOM_NODEJS' || item.status !== 'clean' || !item.remoteComponentId)
1691
+ continue;
1692
+ try {
1693
+ await verifyComponentRuntime(context.client, remoteCatalog.byIdentity.get(item.identityKey || item.componentId)?.component || { type: 'CUSTOM_NODEJS', componentId: item.remoteComponentId });
1694
+ }
1695
+ catch (error) {
1696
+ item.status = 'blocked';
1697
+ item.blocked = true;
1698
+ item.reason = error instanceof Error ? error.message : String(error);
1699
+ }
1700
+ }
1684
1701
  const scopedItems = (scope.enabled ? items.filter((item) => item.inScope) : items)
1685
1702
  .sort((left, right) => (componentDeploymentRank(left.componentType) - componentDeploymentRank(right.componentType)
1686
1703
  || String(left.identityKey || left.componentId).localeCompare(String(right.identityKey || right.componentId))));
@@ -51,7 +51,7 @@ function printPlanText(context, plan) {
51
51
  const { println } = context;
52
52
  println(`Comparing ${paint(plan.from.env, ANSI.bold + ANSI.cyan)} -> ${paint(plan.to.env, ANSI.bold + ANSI.cyan)}`);
53
53
  for (const item of plan.items) {
54
- if (item.action === 'noop') {
54
+ if (item.action === 'noop' && !item.blocked) {
55
55
  continue;
56
56
  }
57
57
  const mark = ACTION_MARKS[item.action];
@@ -60,7 +60,7 @@ function printPlanText(context, plan) {
60
60
  : item.reason
61
61
  ? ` (${item.reason})`
62
62
  : '';
63
- const line = `${mark.symbol} ${item.action.padEnd(9)} ${item.resourceType} ${item.stableKey}${detail}`;
63
+ const line = `${item.blocked ? '!' : mark.symbol} ${(item.blocked ? 'blocked' : item.action).padEnd(9)} ${item.resourceType} ${item.stableKey}${detail}`;
64
64
  println(paint(line, mark.code));
65
65
  }
66
66
  const { counts } = plan;
@@ -68,7 +68,7 @@ function printPlanText(context, plan) {
68
68
  + `${counts.noop} unchanged, ${counts.orphan} orphaned, ${counts.collision} collisions.`);
69
69
  }
70
70
  function hasBlockingDrift(plan) {
71
- return plan.items.some((item) => item.action !== 'noop');
71
+ return plan.items.some((item) => item.action !== 'noop' || item.blocked);
72
72
  }
73
73
  function readScope(args) {
74
74
  const keys = readValues(args, ['key']);
@@ -298,6 +298,9 @@ async function handleEnvApply(context) {
298
298
  printPlanText(context, plan);
299
299
  }
300
300
  const changeCount = plan.counts.create + plan.counts.update + plan.counts.delete;
301
+ const blocked = plan.items.filter(item => item.blocked);
302
+ if (blocked.length)
303
+ throw new Error(`Cannot apply: ${blocked.length} component runtime(s) are not ready. ${blocked.map(item => item.reason).join(' ')}`);
301
304
  if (plan.counts.collision > 0) {
302
305
  throw new Error(`Cannot apply: ${plan.counts.collision} stable-key collision(s) in scope. Resolve duplicates or narrow the scope with --key/--category.`);
303
306
  }
@@ -342,8 +345,8 @@ async function handleEnvApply(context) {
342
345
  println(paint(`Warning: ${unverified.length} component(s) did not verify against the source after apply.`, ANSI.bold + ANSI.yellow));
343
346
  }
344
347
  }
345
- if (failed.length > 0) {
346
- throw new Error(`Apply finished with ${failed.length} failure(s).`);
348
+ if (failed.length > 0 || unverified.length > 0) {
349
+ throw new Error(`Apply finished with ${failed.length} failure(s), ${unverified.length} verification mismatch(es).`);
347
350
  }
348
351
  }
349
352
  export async function handleEnvCommand(context) {
@@ -364,6 +364,8 @@ function printMigrationPlan(context, plan) {
364
364
  }
365
365
  }
366
366
  function migrationItemActionLabel(item, legacyAction) {
367
+ if (item.status === 'activation-drift')
368
+ return item.status;
367
369
  return item.operation ?? (legacyAction === 'noop' ? item.status : legacyAction);
368
370
  }
369
371
  async function confirmRun(context, from, to) {
@@ -429,7 +431,9 @@ async function handleMigrationRead(context, input, command) {
429
431
  }
430
432
  if (command === 'plan' && input.sourceMode === 'workspace'
431
433
  && readBoolFlag(context.args, ['strict']) && plan.needsChanges) {
432
- throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update${plan.prune ? `, ${plan.operations.delete || 0} delete` : ''}.`);
434
+ const eventActivationDrift = plan.events?.items.filter(item => item.status === 'activation-drift').length || 0;
435
+ const activationDrift = plan.schedules?.items.filter((item) => item.status === 'activation-drift').length || 0;
436
+ throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update${activationDrift ? `, ${activationDrift} Schedule activation drift` : ''}${eventActivationDrift ? `, ${eventActivationDrift} Event activation drift` : ''}${plan.prune ? `, ${plan.operations.delete || 0} delete` : ''}.`);
433
437
  }
434
438
  if (command === 'verify' && plan.needsChanges) {
435
439
  throw new Error('Migration verification failed: target still requires changes.');
@@ -39,17 +39,19 @@ export async function handleSchedulesCommand(context) {
39
39
  let activation;
40
40
  if (activate) {
41
41
  const candidateCount = pushed.verifiedActivationCandidates.length;
42
- const confirmed = !isInteractiveTerminal() || await promptConfirm(`Activate ${candidateCount} verified Schedule(s) on "${displayName}"?`, false);
43
- if (confirmed) {
44
- const activationResults = await activateVerifiedSchedules({
45
- client,
46
- candidates: pushed.verifiedActivationCandidates,
47
- });
48
- results.push(...activationResults);
49
- activation = { candidateCount, results: activationResults };
42
+ if (pushed.results.some((item) => item.status === 'failed')) {
43
+ activation = { candidateCount, results: [], skipped: 'configuration phase has failures' };
50
44
  }
51
45
  else {
52
- activation = { candidateCount, results: [], skipped: 'activation not confirmed' };
46
+ const confirmed = !isInteractiveTerminal() || await promptConfirm(`Align activation for ${candidateCount} verified Schedule(s) on "${displayName}"?`, false);
47
+ if (confirmed) {
48
+ const activationResults = await activateVerifiedSchedules({ client, candidates: pushed.verifiedActivationCandidates });
49
+ results.push(...activationResults);
50
+ activation = { candidateCount, results: activationResults };
51
+ }
52
+ else {
53
+ activation = { candidateCount, results: [], skipped: 'activation not confirmed' };
54
+ }
53
55
  }
54
56
  }
55
57
  if (readBoolFlag(context.args, ['json'])) {
@@ -1,5 +1,7 @@
1
1
  import { type ChildProcess } from 'node:child_process';
2
2
  import { type TerminalNetworkAccess, type TerminalSandbox } from './terminal-sandbox.ts';
3
+ /** Equal jitter avoids synchronized reconnect storms while retaining a bounded delay. */
4
+ export declare function terminalReconnectDelay(backoffMs: number, random?: number): number;
3
5
  type TerminalGrant = {
4
6
  agentTerminalId: string;
5
7
  name?: string;
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { setTimeout as delay } from 'node:timers/promises';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
@@ -18,6 +19,12 @@ import { TerminalOperationalLog } from "./terminal-operational-log.js";
18
19
  import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
19
20
  class TerminalRunnerFatalError extends Error {
20
21
  }
22
+ class TerminalApiTransientError extends Error {
23
+ }
24
+ /** Equal jitter avoids synchronized reconnect storms while retaining a bounded delay. */
25
+ export function terminalReconnectDelay(backoffMs, random = Math.random()) {
26
+ return Math.round(backoffMs * (0.5 + random * 0.5));
27
+ }
21
28
  export function selectRegisteredTerminal(devices, grants, name, terminalId) {
22
29
  const matching = devices.filter(device => terminalId
23
30
  ? device.agentTerminalId === terminalId : device.name === name);
@@ -279,22 +286,60 @@ function apiUrl(profile, route) {
279
286
  return `${base}/api/v1${route}`;
280
287
  }
281
288
  async function api(profile, method, route, body) {
282
- const response = await fetch(apiUrl(profile, route), {
283
- method,
284
- redirect: 'manual',
285
- headers: { Authorization: `Bearer ${profile.token}`,
286
- ...(profile.instance ? { instance: profile.instance } : {}),
287
- ...(body ? { 'Content-Type': 'application/json' } : {}) },
288
- ...(body ? { body: JSON.stringify(body) } : {}),
289
- });
290
- if (response.status >= 300 && response.status < 400)
291
- throw new Error(`Revo API ${method} ${route} redirected; refusing to forward credentials.`);
292
- const value = await response.json().catch(() => ({}));
293
- if ([401, 403].includes(response.status))
294
- throw new TerminalRunnerFatalError('Terminal authentication or authorization was rejected. Renew the CLI credentials or grant before connecting.');
295
- if (!response.ok)
296
- throw new Error(`Revo API ${method} ${route} returned ${response.status}: ${String(value?.message || 'request failed')}`);
297
- return (value?.data ?? value);
289
+ const url = apiUrl(profile, route);
290
+ let backoffMs = 1_000;
291
+ for (;;) {
292
+ profile.signal?.throwIfAborted();
293
+ try {
294
+ let response;
295
+ try {
296
+ response = await fetch(url, {
297
+ method, redirect: 'manual',
298
+ signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(profile.signal ? [profile.signal] : [])]),
299
+ headers: { Authorization: `Bearer ${profile.token}`,
300
+ ...(profile.instance ? { instance: profile.instance } : {}),
301
+ ...(body ? { 'Content-Type': 'application/json' } : {}) },
302
+ ...(body ? { body: JSON.stringify(body) } : {}),
303
+ });
304
+ }
305
+ catch {
306
+ throw new TerminalApiTransientError('Terminal API transport unavailable.');
307
+ }
308
+ if (response.status >= 300 && response.status < 400) {
309
+ await response.body?.cancel();
310
+ throw new Error(`Revo API ${method} ${route} redirected; refusing to forward credentials.`);
311
+ }
312
+ if ([401, 403].includes(response.status)) {
313
+ await response.body?.cancel();
314
+ throw new TerminalRunnerFatalError('Terminal authentication or authorization was rejected. Renew the CLI credentials or grant before connecting.');
315
+ }
316
+ if ([408, 429].includes(response.status) || response.status >= 500) {
317
+ await response.body?.cancel();
318
+ throw new TerminalApiTransientError(`Terminal API temporarily unavailable (${response.status}).`);
319
+ }
320
+ let value;
321
+ try {
322
+ value = await response.json();
323
+ }
324
+ catch {
325
+ if (!response.ok)
326
+ throw new Error(`Revo API ${method} ${route} returned ${response.status}.`);
327
+ throw new TerminalApiTransientError('Terminal API returned an incomplete response.');
328
+ }
329
+ if (!response.ok)
330
+ throw new Error(`Revo API ${method} ${route} returned ${response.status}: ${String(value?.message || 'request failed')}`);
331
+ return (value?.data ?? value);
332
+ }
333
+ catch (error) {
334
+ profile.signal?.throwIfAborted();
335
+ // Only connect's reads are repeatable. Never replay pairing, revocation or other mutations.
336
+ if (!profile.retryReads || method !== 'GET' || !(error instanceof TerminalApiTransientError))
337
+ throw error;
338
+ console.error('Terminal API unavailable; connection setup will retry.');
339
+ await delay(terminalReconnectDelay(backoffMs), undefined, { signal: profile.signal });
340
+ backoffMs = Math.min(backoffMs * 2, 30_000);
341
+ }
342
+ }
298
343
  }
299
344
  function realtimeUrl(value) {
300
345
  const url = new URL(value);
@@ -533,11 +578,18 @@ export function runWorkspacePatch(input, onDone) {
533
578
  throw new Error('terminal_policy_expired');
534
579
  const workerJs = fileURLToPath(new URL('./terminal-patch-worker.js', import.meta.url));
535
580
  const worker = fs.existsSync(workerJs) ? workerJs : fileURLToPath(new URL('./terminal-patch-worker.ts', import.meta.url));
536
- const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'revo-terminal-patch-'));
581
+ const scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'revo-terminal-patch-')));
537
582
  let launch;
538
583
  try {
539
- const command = [process.execPath, worker, input.workspace, String(input.allowDelete)].map(shellQuote).join(' ');
540
- launch = sandboxCommand(input.workspace, input.workspace, command, 'workspace', process.platform, scratch, [path.dirname(worker)], 'none');
584
+ // Run the fixed helper files from their own package scope. Node's loader must
585
+ // not traverse a CLI installation outside this command's readable workspace.
586
+ const isolatedWorker = path.join(scratch, path.basename(worker));
587
+ const helperName = `terminal-patch${path.extname(worker)}`;
588
+ fs.copyFileSync(worker, isolatedWorker);
589
+ fs.copyFileSync(path.join(path.dirname(worker), helperName), path.join(scratch, helperName));
590
+ fs.writeFileSync(path.join(scratch, 'package.json'), JSON.stringify({ type: 'module' }), { mode: 0o600 });
591
+ const command = [process.execPath, isolatedWorker, input.workspace, String(input.allowDelete)].map(shellQuote).join(' ');
592
+ launch = sandboxCommand(input.workspace, input.workspace, command, 'workspace', process.platform, scratch, [], 'none');
541
593
  }
542
594
  catch (error) {
543
595
  fs.rmSync(scratch, { recursive: true, force: true });
@@ -693,7 +745,7 @@ async function connect(profile, device) {
693
745
  reconnectGrace.clear();
694
746
  });
695
747
  socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
696
- secret: device.secret, capabilities: ['workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
748
+ secret: device.secret, capabilities: ['grant_refresh_v1', 'workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
697
749
  'terminal_policy_v2', 'terminal_policy_selective_v1', 'background_shell_v1', 'terminal_thread_scope_v1',
698
750
  'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
699
751
  'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'browser_tabs_v1', 'save_image_v1',
@@ -1158,10 +1210,13 @@ async function connect(profile, device) {
1158
1210
  if (activeSocket === socket)
1159
1211
  activeConnectionId = '';
1160
1212
  resumed.clear();
1161
- if (code === 1008 && reason.toString() !== 'heartbeat_timeout') {
1213
+ const grantChanged = code === 1012 && reason.toString() === 'grant_changed';
1214
+ if (grantChanged || code === 1008 && reason.toString() !== 'heartbeat_timeout') {
1162
1215
  reconnectGrace.clear();
1163
- for (const child of children.values())
1216
+ for (const [executionId, child] of children) {
1217
+ cancelledExecutions.add(executionId);
1164
1218
  child.terminate();
1219
+ }
1165
1220
  void closeBrowserSessions();
1166
1221
  }
1167
1222
  else if (!stopping)
@@ -1199,8 +1254,9 @@ async function connect(profile, device) {
1199
1254
  }
1200
1255
  if (stopping)
1201
1256
  break;
1202
- operationalLog.write('INFO', {}, 'runner.reconnect_wait', { milliseconds: backoffMs });
1203
- await new Promise(resolve => setTimeout(resolve, backoffMs));
1257
+ const reconnectDelayMs = terminalReconnectDelay(backoffMs);
1258
+ operationalLog.write('INFO', {}, 'runner.reconnect_wait', { milliseconds: reconnectDelayMs });
1259
+ await delay(reconnectDelayMs, undefined, { signal: profile.signal });
1204
1260
  backoffMs = Math.min(backoffMs * 2, 30_000);
1205
1261
  }
1206
1262
  }
@@ -1210,7 +1266,7 @@ async function connect(profile, device) {
1210
1266
  process.off('SIGTERM', stop);
1211
1267
  }
1212
1268
  }
1213
- async function runTerminalCommand(argv) {
1269
+ async function runTerminalCommand(argv, signal) {
1214
1270
  const command = argv[0] || 'help';
1215
1271
  if (command === 'help' || argv.includes('--help')) {
1216
1272
  console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--url URL] [--realtime-url URL]\nrevo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
@@ -1287,7 +1343,7 @@ async function runTerminalCommand(argv) {
1287
1343
  : `Terminal service already installed (${result.label}).`);
1288
1344
  return;
1289
1345
  }
1290
- const profile = resolveProfile(argv);
1346
+ const profile = { ...resolveProfile(argv), retryReads: command === 'connect', signal };
1291
1347
  let me;
1292
1348
  if (!profile.instance) {
1293
1349
  const currentUser = await api(profile, 'GET', '/me');
@@ -1326,9 +1382,12 @@ async function runTerminalCommand(argv) {
1326
1382
  throw new Error(`Multiple removed terminals match ${name} (${matchingDevices.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
1327
1383
  selectedDevice = matchingDevices[0];
1328
1384
  }
1329
- if (terminalServiceInstalled(selectedDevice.workspace, selectedProject(argv) || getActiveEnvironmentName(), selectedDevice.agentTerminalId)
1330
- || terminalServiceInstalled(selectedDevice.workspace, selectedProject(argv) || getActiveEnvironmentName()))
1331
- throw new Error('Uninstall the selected terminal service before revoking its grant.');
1385
+ const envName = selectedProject(argv) || getActiveEnvironmentName();
1386
+ if (terminalServiceInstalled(selectedDevice.workspace, envName))
1387
+ throw new Error('Uninstall the legacy workspace service before revoking its grant.');
1388
+ if (terminalServiceInstalled(selectedDevice.workspace, envName, selectedDevice.agentTerminalId))
1389
+ uninstallTerminalService({ workspace: selectedDevice.workspace, envName, terminalId: selectedDevice.agentTerminalId,
1390
+ configHome: process.env.XDG_CONFIG_HOME });
1332
1391
  if (listing.devices.some(item => item.agentTerminalId === selectedDevice.agentTerminalId))
1333
1392
  await api(profile, 'POST', `/agents/terminals/${selectedDevice.agentTerminalId}/revoke`);
1334
1393
  await updateStore(current => {
@@ -1391,6 +1450,8 @@ async function runTerminalCommand(argv) {
1391
1450
  }
1392
1451
  console.log(`Pending approval in AI Agents → Terminals: ${device.name} (${device.agentTerminalId}).`);
1393
1452
  }
1453
+ if (profile.realtimeUrl)
1454
+ device = { ...device, realtimeUrl: realtimeUrl(profile.realtimeUrl) };
1394
1455
  if (device.workspace !== workspace) {
1395
1456
  await api(profile, 'POST', `/agents/terminals/${device.agentTerminalId}/workspaces/register`, { path: workspace, name: path.basename(workspace) });
1396
1457
  await updateStore(current => {
@@ -1407,7 +1468,7 @@ async function runTerminalCommand(argv) {
1407
1468
  break;
1408
1469
  if (!grant || grant.status === 'revoked')
1409
1470
  throw new TerminalRunnerFatalError('Terminal grant revoked or missing.');
1410
- await new Promise(resolve => setTimeout(resolve, 2_000));
1471
+ await delay(2_000, undefined, { signal: profile.signal });
1411
1472
  }
1412
1473
  let releaseRunnerLock;
1413
1474
  try {
@@ -1429,14 +1490,28 @@ async function runTerminalCommand(argv) {
1429
1490
  }
1430
1491
  /** Supervisors retry crashes, but a revoked grant or 401/403 needs a human credential/grant change. */
1431
1492
  export async function handleTerminalCommand(argv) {
1493
+ const controller = argv[0] === 'connect' ? new AbortController() : undefined;
1494
+ const stopSetup = () => controller?.abort();
1495
+ if (controller) {
1496
+ process.on('SIGINT', stopSetup);
1497
+ process.on('SIGTERM', stopSetup);
1498
+ }
1432
1499
  try {
1433
- await runTerminalCommand(argv);
1500
+ await runTerminalCommand(argv, controller?.signal);
1434
1501
  }
1435
1502
  catch (error) {
1503
+ if (controller?.signal.aborted)
1504
+ return;
1436
1505
  if (argv.includes('--service-runner') && error instanceof TerminalRunnerFatalError) {
1437
1506
  console.error(error.message);
1438
1507
  return;
1439
1508
  }
1440
1509
  throw error;
1441
1510
  }
1511
+ finally {
1512
+ if (controller) {
1513
+ process.off('SIGINT', stopSetup);
1514
+ process.off('SIGTERM', stopSetup);
1515
+ }
1516
+ }
1442
1517
  }
@@ -0,0 +1,8 @@
1
+ import type { RevoClient } from './client.ts';
2
+ import type { ComponentRecord } from './types.ts';
3
+ export declare function isComponentDigest(value: unknown): value is string;
4
+ /** Canonical API content identity, separate from portable configuration hashes. */
5
+ export declare function componentContentDigest(component: ComponentRecord): string;
6
+ export declare function componentRevisionByDigest(client: RevoClient, componentId: string, digest: string): Promise<ComponentRecord>;
7
+ export declare function componentRuntimeBlocker(runtime: unknown, active?: boolean): string | null;
8
+ export declare function verifyComponentRuntime(client: RevoClient, component: ComponentRecord, waitMs?: number): Promise<void>;