@revoengine/cli 1.0.29 → 1.0.31

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 (69) hide show
  1. package/README.md +156 -3
  2. package/dist/src/automation-contract.generated.d.ts +742 -0
  3. package/dist/src/automation-contract.generated.js +1021 -0
  4. package/dist/src/cli.js +9 -1
  5. package/dist/src/client.d.ts +24 -0
  6. package/dist/src/client.js +60 -0
  7. package/dist/src/commands/component.js +56 -23
  8. package/dist/src/commands/env.js +1 -1
  9. package/dist/src/commands/index.d.ts +2 -0
  10. package/dist/src/commands/index.js +2 -0
  11. package/dist/src/commands/studio.d.ts +3 -0
  12. package/dist/src/commands/studio.js +114 -0
  13. package/dist/src/commands/terminal-browser-human-input.d.ts +11 -0
  14. package/dist/src/commands/terminal-browser-human-input.js +44 -0
  15. package/dist/src/commands/terminal-browser-interaction.d.ts +25 -0
  16. package/dist/src/commands/terminal-browser-interaction.js +56 -0
  17. package/dist/src/commands/terminal-browser-live-protocol.d.ts +151 -0
  18. package/dist/src/commands/terminal-browser-live-protocol.js +177 -0
  19. package/dist/src/commands/terminal-browser-live-transport.d.ts +41 -0
  20. package/dist/src/commands/terminal-browser-live-transport.js +206 -0
  21. package/dist/src/commands/terminal-browser-live.d.ts +114 -0
  22. package/dist/src/commands/terminal-browser-live.js +455 -0
  23. package/dist/src/commands/terminal-browser-observation.d.ts +10 -0
  24. package/dist/src/commands/terminal-browser-observation.js +27 -0
  25. package/dist/src/commands/terminal-browser-page-input.d.ts +8 -0
  26. package/dist/src/commands/terminal-browser-page-input.js +94 -0
  27. package/dist/src/commands/terminal-browser-profile-preferences.d.ts +37 -0
  28. package/dist/src/commands/terminal-browser-profile-preferences.js +136 -0
  29. package/dist/src/commands/terminal-browser-profile.d.ts +52 -0
  30. package/dist/src/commands/terminal-browser-profile.js +447 -0
  31. package/dist/src/commands/terminal-browser.d.ts +28 -1
  32. package/dist/src/commands/terminal-browser.js +401 -55
  33. package/dist/src/commands/terminal-policy.js +2 -0
  34. package/dist/src/commands/terminal-public-web-proxy.d.ts +14 -0
  35. package/dist/src/commands/terminal-public-web-proxy.js +141 -0
  36. package/dist/src/commands/terminal-public-web.d.ts +11 -0
  37. package/dist/src/commands/terminal-public-web.js +99 -0
  38. package/dist/src/commands/terminal.d.ts +1 -0
  39. package/dist/src/commands/terminal.js +92 -9
  40. package/dist/src/commands/tests.d.ts +3 -0
  41. package/dist/src/commands/tests.js +236 -0
  42. package/dist/src/component-element-validation.d.ts +8 -0
  43. package/dist/src/component-element-validation.js +79 -0
  44. package/dist/src/component-lifecycle.d.ts +3 -0
  45. package/dist/src/component-lifecycle.js +17 -0
  46. package/dist/src/component-lock.d.ts +17 -12
  47. package/dist/src/component-lock.js +57 -6
  48. package/dist/src/component-manifests.js +3 -0
  49. package/dist/src/component-source-validation.d.ts +5 -0
  50. package/dist/src/component-source-validation.js +27 -0
  51. package/dist/src/env-sync.js +67 -9
  52. package/dist/src/native-tests.d.ts +61 -0
  53. package/dist/src/native-tests.js +20 -0
  54. package/dist/src/request-contract.d.ts +39 -0
  55. package/dist/src/request-contract.js +138 -0
  56. package/dist/src/resource-syncs/agent-sync.js +47 -7
  57. package/dist/src/resource-syncs/database-table-sync.js +8 -8
  58. package/dist/src/resource-syncs/endpoint-sync.js +20 -14
  59. package/dist/src/resource-syncs/group-sync.js +8 -3
  60. package/dist/src/resource-syncs/job-template-sync.js +75 -28
  61. package/dist/src/resource-syncs/role-group-sync.js +8 -0
  62. package/dist/src/resource-syncs/runtime-definition-validation.d.ts +14 -0
  63. package/dist/src/resource-syncs/runtime-definition-validation.js +153 -0
  64. package/dist/src/test-workspace.d.ts +33 -0
  65. package/dist/src/test-workspace.js +156 -0
  66. package/dist/src/types.d.ts +1 -0
  67. package/dist/src/ui.js +12 -0
  68. package/dist/src/update-notifier.d.ts +1 -1
  69. package/package.json +5 -3
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 { handleAgentsCommand, 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";
6
+ import { handleAgentsCommand, handleAuthCommand, handleComponentCommand, handleDatabaseTablesCommand, handleDatabaseViewsCommand, handleDeployCommand, handleDiffCommand, handleEndpointsCommand, handleEnvCommand, handleEventsCommand, handleGroupsCommand, handleInfoCommand, handleJobTemplatesCommand, handleMetadataCommand, handleMigrateCommand, handlePlanCommand, handlePullCommand, handleProjectCommand, handleRequestCommand, handleRoleGroupsCommand, handleServiceAccountsCommand, handleSearchCommand, handleStudioCommand, handleSchedulesCommand, handleTerminalCommand, handleTestsCommand, } 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";
@@ -285,6 +285,14 @@ async function runMain(args, argv) {
285
285
  await handleProjectCommand(context);
286
286
  return;
287
287
  }
288
+ if (command === 'studio') {
289
+ await handleStudioCommand(context);
290
+ return;
291
+ }
292
+ if (command === 'tests') {
293
+ await handleTestsCommand(context);
294
+ return;
295
+ }
288
296
  if (command === 'search') {
289
297
  await handleSearchCommand(context);
290
298
  return;
@@ -2,6 +2,7 @@ import type { AutomationRuntimeInputFields, RuntimeExecutionPolicy } from './typ
2
2
  import { RequestQueue } from './request-queue.ts';
3
3
  import type { AgentRecord, AgentPluginRecord, ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ServiceAccountRecord, ScheduleRecord } from './types.ts';
4
4
  import type { TrackableResourceType } from './tracked-resources.ts';
5
+ import type { NativeTestCatalog, NativeTestRun, NativeTestRunInput } from './native-tests.ts';
5
6
  export type RequestOptions = {
6
7
  query?: Record<string, unknown>;
7
8
  body?: unknown;
@@ -449,9 +450,32 @@ export declare class RevoClient {
449
450
  discoveredTotal: number | null;
450
451
  }>;
451
452
  getComponent(componentId: string, options?: Pick<RequestOptions, 'timeoutMs'>): Promise<unknown>;
453
+ /** Studio writes stage durable drafts; review, source commit and runtime activation are explicit operations. */
454
+ listStudioSessions(query?: Record<string, unknown>): Promise<unknown>;
455
+ createStudioSession(body: Record<string, unknown>): Promise<unknown>;
456
+ getStudioSession(sessionId: string): Promise<unknown>;
457
+ updateStudioSession(sessionId: string, body: Record<string, unknown>): Promise<unknown>;
458
+ deleteStudioSession(sessionId: string, body: Record<string, unknown>): Promise<unknown>;
459
+ readStudioSession(sessionId: string, action: 'diff' | 'files' | 'events' | 'chat' | 'search' | 'rebase' | 'claims', query?: Record<string, unknown>): Promise<unknown>;
460
+ readStudioFile(sessionId: string, fileId: string, query?: Record<string, unknown>): Promise<unknown>;
461
+ mutateStudioSession(sessionId: string, action: 'patch' | 'resources' | 'fork' | 'test-runs' | 'proposals' | 'commit' | 'prepare' | 'activate' | 'rebase' | 'share' | 'participants' | 'presence' | 'claims' | 'chat/message' | 'runtime/baseline' | 'runtime/rollback', body: Record<string, unknown>): Promise<unknown>;
462
+ reviewStudioProposal(sessionId: string, proposalId: string, body: Record<string, unknown>): Promise<unknown>;
463
+ releaseStudioWorkClaim(sessionId: string, claimId: string, body: Record<string, unknown>): Promise<unknown>;
464
+ cancelStudioTestRun(sessionId: string, testRunId: string, body: Record<string, unknown>): Promise<unknown>;
452
465
  createComponent(body: unknown): Promise<unknown>;
466
+ listNativeTests(query?: {
467
+ search?: string;
468
+ take?: number;
469
+ skip?: number;
470
+ }): Promise<NativeTestCatalog>;
471
+ createNativeTestRun(body: NativeTestRunInput): Promise<NativeTestRun>;
472
+ getNativeTestRun(runId: string): Promise<NativeTestRun>;
473
+ executeNativeTestRun(runId: string): Promise<NativeTestRun>;
474
+ cancelNativeTestRun(runId: string): Promise<NativeTestRun>;
453
475
  reviewComponent(componentId: string, body: unknown): Promise<unknown>;
454
476
  updateComponent(componentId: string, body: unknown, expectedToken?: string): Promise<unknown>;
477
+ reviewComponentLifecycle(componentId: string, action: 'activate' | 'disable'): Promise<unknown>;
478
+ setComponentActive(componentId: string, active: boolean, expectedToken: string): Promise<unknown>;
455
479
  deleteComponent(componentId: string): Promise<ApiResponse<unknown>>;
456
480
  deleteWorkspaceResource(resource: TrackableResourceType, id: string): Promise<unknown>;
457
481
  private accountForSync;
@@ -1214,12 +1214,63 @@ export class RevoClient {
1214
1214
  async getComponent(componentId, options = {}) {
1215
1215
  return this.requestData('GET', `/api/v1/component/${componentId}`, options);
1216
1216
  }
1217
+ /** Studio writes stage durable drafts; review, source commit and runtime activation are explicit operations. */
1218
+ async listStudioSessions(query = {}) {
1219
+ return this.requestData('GET', '/api/v1/studio/sessions', { query });
1220
+ }
1221
+ async createStudioSession(body) {
1222
+ return this.requestData('POST', '/api/v1/studio/sessions', { body });
1223
+ }
1224
+ async getStudioSession(sessionId) {
1225
+ return this.requestData('GET', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}`);
1226
+ }
1227
+ async updateStudioSession(sessionId, body) {
1228
+ return this.requestData('PATCH', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}`, { body });
1229
+ }
1230
+ async deleteStudioSession(sessionId, body) {
1231
+ return this.requestData('DELETE', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}`, { body });
1232
+ }
1233
+ async readStudioSession(sessionId, action, query = {}) {
1234
+ return this.requestData('GET', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/${action}`, { query });
1235
+ }
1236
+ async readStudioFile(sessionId, fileId, query = {}) {
1237
+ return this.requestData('GET', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/files/${encodeURIComponent(fileId)}`, { query });
1238
+ }
1239
+ async mutateStudioSession(sessionId, action, body) {
1240
+ return this.requestData('POST', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/${action}`, { body });
1241
+ }
1242
+ async reviewStudioProposal(sessionId, proposalId, body) {
1243
+ return this.requestData('POST', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/proposals/${encodeURIComponent(proposalId)}/review`, { body });
1244
+ }
1245
+ async releaseStudioWorkClaim(sessionId, claimId, body) {
1246
+ return this.requestData('POST', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/claims/${encodeURIComponent(claimId)}/release`, { body });
1247
+ }
1248
+ async cancelStudioTestRun(sessionId, testRunId, body) {
1249
+ return this.requestData('POST', `/api/v1/studio/sessions/${encodeURIComponent(sessionId)}/test-runs/${encodeURIComponent(testRunId)}/cancel`, { body });
1250
+ }
1217
1251
  async createComponent(body) {
1218
1252
  return this.requestData('POST', '/api/v1/component', {
1219
1253
  body,
1220
1254
  spinnerLabel: 'Creating component',
1221
1255
  });
1222
1256
  }
1257
+ async listNativeTests(query = {}) {
1258
+ return this.requestData('GET', '/api/v1/native-tests', { query });
1259
+ }
1260
+ async createNativeTestRun(body) {
1261
+ return this.requestData('POST', '/api/v1/native-tests/runs', { body });
1262
+ }
1263
+ async getNativeTestRun(runId) {
1264
+ return this.requestData('GET', `/api/v1/native-tests/runs/${encodeURIComponent(runId)}`);
1265
+ }
1266
+ async executeNativeTestRun(runId) {
1267
+ return this.requestData('POST', `/api/v1/native-tests/runs/${encodeURIComponent(runId)}/execute`, {
1268
+ body: {}, timeoutMs: 70_000,
1269
+ });
1270
+ }
1271
+ async cancelNativeTestRun(runId) {
1272
+ return this.requestData('POST', `/api/v1/native-tests/runs/${encodeURIComponent(runId)}/cancel`, { body: {} });
1273
+ }
1223
1274
  async reviewComponent(componentId, body) {
1224
1275
  return this.requestData('POST', `/api/v1/component/${componentId}/review`, { body });
1225
1276
  }
@@ -1230,6 +1281,15 @@ export class RevoClient {
1230
1281
  spinnerLabel: 'Updating component',
1231
1282
  });
1232
1283
  }
1284
+ async reviewComponentLifecycle(componentId, action) {
1285
+ return this.requestData('POST', `/api/v1/component/${componentId}/${action}/review`);
1286
+ }
1287
+ async setComponentActive(componentId, active, expectedToken) {
1288
+ return this.requestData('POST', `/api/v1/component/${componentId}/${active ? 'activate' : 'disable'}`, {
1289
+ headers: { 'x-revo-mutation-review': expectedToken },
1290
+ spinnerLabel: active ? 'Activating component' : 'Disabling component',
1291
+ });
1292
+ }
1233
1293
  async deleteComponent(componentId) {
1234
1294
  return this.request('DELETE', `/api/v1/component/${componentId}`, {
1235
1295
  spinnerLabel: 'Deleting component',
@@ -1,12 +1,15 @@
1
1
  import { hydrateComponentManifest, listComponentManifests } from "../component-manifests.js";
2
2
  import { verifyComponentRuntime } from "../component-contract.js";
3
+ import { changeComponentActivation } from "../component-lifecycle.js";
4
+ import { componentElementValidationErrors } from "../component-element-validation.js";
5
+ import { componentSourceConfigurationErrors } from "../component-source-validation.js";
3
6
  import fs from 'node:fs';
4
7
  import path from 'node:path';
5
8
  import { execFileSync } from 'node:child_process';
6
9
  import { randomUUID } from 'node:crypto';
7
10
  import { ApiError, COMPONENT_LIST_PAGE_SIZE, PermissionDeniedError } from "../client.js";
8
11
  import { getConfigDir } from "../config.js";
9
- import { REVO_LOCK_FILE, buildPortableComponentUpdatePayload, componentLockMatchesIdentity, diffPortableComponentSource, getComponentLockEntry, getComponentLockEntries, hashComponentSource, hashPortableComponentSource, hashStable, normalizePortableComponentSource, readComponentLock, removeComponentLockBaseline, sanitizeComponentSource, upsertComponentLockEntry, writeComponentLock, } from "../component-lock.js";
12
+ import { REVO_LOCK_FILE, buildPortableComponentUpdatePayload, componentLockMatchesIdentity, componentTypeTransitionReason, componentActivationValidationError, componentUpdateValidationError, diffPortableComponentSource, getComponentLockEntry, getComponentLockEntries, hashComponentSource, hashPortableComponentSource, hashStable, normalizePortableComponentSource, readComponentLock, removeComponentLockBaseline, sanitizeComponentSource, upsertComponentLockEntry, writeComponentLock, } from "../component-lock.js";
10
13
  import { describeFieldChanges, formatDiffValue, unifiedLineDiff } from "../diff-details.js";
11
14
  import { buildSandboxDebugStreamUrl, buildSandboxDebugUrl, extractSandboxEndpoint, readProjectComponentIdentity, readProjectMetadata, resolveProjectRoot, resolveProjectWorkspace, } from "../project.js";
12
15
  import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
@@ -156,20 +159,7 @@ function normalizeComponentType(component) {
156
159
  return 'CODE_JS';
157
160
  }
158
161
  function componentTypeTransitionBlocker(desired, current) {
159
- const desiredType = normalizeComponentType(desired).trim().toUpperCase();
160
- const currentType = normalizeComponentType(current).trim().toUpperCase();
161
- const languagePairs = new Map([
162
- ['CODE_JS', 'component'],
163
- ['CODE_TS', 'component'],
164
- ['CODE_JS_LIB', 'library'],
165
- ['CODE_TS_LIB', 'library'],
166
- ]);
167
- if (desiredType === currentType
168
- || !languagePairs.has(desiredType)
169
- || languagePairs.get(desiredType) !== languagePairs.get(currentType)) {
170
- return null;
171
- }
172
- return `The target API cannot change Component type from ${currentType} to ${desiredType}; resolve this transition manually before syncing.`;
162
+ return componentTypeTransitionReason(normalizeComponentType(desired), normalizeComponentType(current));
173
163
  }
174
164
  function componentDeploymentRank(type) {
175
165
  const normalized = type.trim().toUpperCase();
@@ -1114,9 +1104,12 @@ async function resolveRemoteComponentForLocal(context, component, identity, remo
1114
1104
  return catalog.byIdentity.get(identityKey)?.component || null;
1115
1105
  }
1116
1106
  function buildPushElements(component, remote, identity) {
1107
+ const errors = componentElementValidationErrors({ ...component, type: normalizeComponentType(component) }, { mode: 'save' });
1108
+ if (errors.length)
1109
+ throw new Error(errors.join('; '));
1117
1110
  const remoteElementsByKey = new Map((remote.elements || []).map((element) => [element.key, element]));
1118
1111
  return (component.elements || []).map((element) => {
1119
- const targetElementId = identity.mode === 'stableKey'
1112
+ const targetElementId = identity.mode === 'stableKey' || element.key === '@default'
1120
1113
  ? remoteElementsByKey.get(element.key)?.componentElementId
1121
1114
  : element.componentElementId;
1122
1115
  return {
@@ -1141,6 +1134,7 @@ function buildComponentCreatePayload(component, identity) {
1141
1134
  active: component.active ?? true,
1142
1135
  async: Boolean(component.async),
1143
1136
  metadata: sanitizeUserMetadata(component.metadata),
1137
+ ...(component.testConfig !== undefined ? { testConfig: component.testConfig } : {}),
1144
1138
  elements: buildPushElements(component, { elements: [] }, identity),
1145
1139
  };
1146
1140
  }
@@ -1179,6 +1173,20 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1179
1173
  }
1180
1174
  try {
1181
1175
  const remote = await resolveRemoteComponentForLocal(context, component, identity, resolvedRemoteCatalog);
1176
+ const elementErrors = componentElementValidationErrors({ ...component, type: normalizeComponentType(component) }, {
1177
+ mode: !remote || diffPortableComponentSource(component, remote).elementsChanged ? 'save' : 'create',
1178
+ });
1179
+ if (elementErrors.length)
1180
+ throw new Error(`Cannot push ${targetPath}: ${elementErrors.join('; ')}`);
1181
+ const configurationErrors = componentSourceConfigurationErrors(component);
1182
+ if (configurationErrors.length)
1183
+ throw new Error(`Cannot push ${targetPath}: ${configurationErrors.join('; ')}`);
1184
+ const updateError = remote ? componentUpdateValidationError(component, remote) : null;
1185
+ if (updateError)
1186
+ throw new Error(`Cannot push ${targetPath}: ${updateError}`);
1187
+ const activationError = componentActivationValidationError(component);
1188
+ if (activationError)
1189
+ throw new Error(`Cannot push ${targetPath}: ${activationError}`);
1182
1190
  if (context.componentReview) {
1183
1191
  const reviewed = context.componentReview.get(identityKey);
1184
1192
  if (!reviewed || componentSourceHash(component, identity) !== reviewed.localHash
@@ -1320,9 +1328,19 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1320
1328
  let expectedSaveVersion = componentVersion(remote);
1321
1329
  const operations = {};
1322
1330
  let errorOperationId;
1323
- if (portableDiff.configurationFields.length > 0) {
1331
+ const activationChanged = portableDiff.configurationFields.includes('active');
1332
+ const desiredActive = component.active ?? true;
1333
+ const updateFields = portableDiff.configurationFields.filter(field => field !== 'active' && field !== 'type');
1334
+ const updatePayload = updateFields.length || activationChanged ? buildPortableComponentUpdatePayload(component, remote, updateFields) : undefined;
1335
+ const elementPayload = portableDiff.elementsChanged ? buildPushElements(component, remote, identity) : undefined;
1336
+ if (activationChanged && !desiredActive) {
1337
+ expectedSaveVersion = await changeComponentActivation(client, remoteComponentId, false, expectedSaveVersion);
1338
+ configurationChanged = true;
1339
+ operations.disable = { outcome: 'accepted' };
1340
+ }
1341
+ if (updateFields.length > 0) {
1324
1342
  try {
1325
- const body = buildPortableComponentUpdatePayload(component, remote, portableDiff.configurationFields);
1343
+ const body = { ...updatePayload, version: expectedSaveVersion };
1326
1344
  if (context.componentReview) {
1327
1345
  const token = componentReviewToken(await client.reviewComponent(remoteComponentId, body), remoteComponentId, expectedSaveVersion, targetPath);
1328
1346
  await client.updateComponent(remoteComponentId, body, token);
@@ -1358,7 +1376,7 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1358
1376
  let elementsChanged = false;
1359
1377
  if (portableDiff.elementsChanged) {
1360
1378
  try {
1361
- const elements = buildPushElements(component, remote, identity);
1379
+ const elements = elementPayload;
1362
1380
  let expectedToken;
1363
1381
  if (context.componentReview) {
1364
1382
  expectedToken = componentReviewToken(await client.reviewComponentElements(remoteComponentId, elements), remoteComponentId, expectedSaveVersion, targetPath);
@@ -1367,6 +1385,8 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1367
1385
  ? await client.saveComponentElements(remoteComponentId, elements, expectedToken)
1368
1386
  : await client.saveComponentElements(remoteComponentId, elements);
1369
1387
  elementsChanged = response.status !== 304;
1388
+ if (elementsChanged && expectedSaveVersion !== null)
1389
+ expectedSaveVersion += 1;
1370
1390
  const operationId = readRevoOperationId(response.headers);
1371
1391
  errorOperationId = operationId || errorOperationId;
1372
1392
  operations.elementsSave = {
@@ -1387,13 +1407,22 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1387
1407
  }
1388
1408
  }
1389
1409
  }
1390
- const refreshedRemote = hasLiveRemote
1410
+ let refreshedRemote = hasLiveRemote
1391
1411
  ? unwrapComponent(await client.getComponent(remoteComponentId))
1392
1412
  : {
1393
1413
  ...component,
1394
1414
  componentId: remoteComponentId,
1395
1415
  ...(componentVersion(remote) != null ? { version: componentVersion(remote) } : {}),
1396
1416
  };
1417
+ if (activationChanged && desiredActive) {
1418
+ if (!hasLiveRemote || componentSourceHash(refreshedRemote, identity) !== componentSourceHash({ ...component, active: false }, identity)) {
1419
+ throw new Error(`Cannot push ${targetPath}: component source did not verify before activation.`);
1420
+ }
1421
+ expectedSaveVersion = await changeComponentActivation(client, remoteComponentId, true, expectedSaveVersion);
1422
+ configurationChanged = true;
1423
+ operations.activate = { outcome: 'accepted' };
1424
+ refreshedRemote = unwrapComponent(await client.getComponent(remoteComponentId));
1425
+ }
1397
1426
  if (hasLiveRemote
1398
1427
  && componentSourceHash(refreshedRemote, identity) !== componentSourceHash(component, identity)) {
1399
1428
  const logPath = writeComponentPushVerificationLog({
@@ -1692,9 +1721,13 @@ export async function buildComponentPlan(context, scope = { enabled: false, base
1692
1721
  status = 'conflict';
1693
1722
  reason = 'local and remote changed since lock';
1694
1723
  }
1695
- const typeTransitionBlocker = local && remote
1696
- ? componentTypeTransitionBlocker(local.component, remote.component)
1697
- : null;
1724
+ const elementErrors = local ? componentElementValidationErrors({ ...local.component, type: normalizeComponentType(local.component) }, {
1725
+ mode: !remote || diffPortableComponentSource(local.component, remote.component).elementsChanged ? 'save' : 'create',
1726
+ }) : [];
1727
+ const configurationErrors = local ? componentSourceConfigurationErrors(local.component) : [];
1728
+ const typeTransitionBlocker = (local ? componentActivationValidationError(local.component) : null) || (configurationErrors.length ? configurationErrors.join('; ') : null) || (elementErrors.length ? elementErrors.join('; ') : local && remote
1729
+ ? componentTypeTransitionBlocker(local.component, remote.component) || componentUpdateValidationError(local.component, remote.component)
1730
+ : null);
1698
1731
  if (typeTransitionBlocker) {
1699
1732
  status = 'blocked';
1700
1733
  reason = typeTransitionBlocker;
@@ -300,7 +300,7 @@ async function handleEnvApply(context) {
300
300
  const changeCount = plan.counts.create + plan.counts.update + plan.counts.delete;
301
301
  const blocked = plan.items.filter(item => item.blocked);
302
302
  if (blocked.length)
303
- throw new Error(`Cannot apply: ${blocked.length} component runtime(s) are not ready. ${blocked.map(item => item.reason).join(' ')}`);
303
+ throw new Error(`Cannot apply: ${blocked.length} component(s) are blocked. ${blocked.map(item => item.reason).join(' ')}`);
304
304
  if (plan.counts.collision > 0) {
305
305
  throw new Error(`Cannot apply: ${plan.counts.collision} stable-key collision(s) in scope. Resolve duplicates or narrow the scope with --key/--category.`);
306
306
  }
@@ -18,3 +18,5 @@ export * from './search.ts';
18
18
  export * from './terminal.ts';
19
19
  export * from './schedules.ts';
20
20
  export * from './agents.ts';
21
+ export * from './studio.ts';
22
+ export * from './tests.ts';
@@ -18,3 +18,5 @@ export * from "./search.js";
18
18
  export * from "./terminal.js";
19
19
  export * from "./schedules.js";
20
20
  export * from "./agents.js";
21
+ export * from "./studio.js";
22
+ export * from "./tests.js";
@@ -0,0 +1,3 @@
1
+ import type { CommandContext } from '../types.ts';
2
+ /** Never turns a rejected legacy write into an unreviewed source commit. */
3
+ export declare function handleStudioCommand(context: CommandContext): Promise<void>;
@@ -0,0 +1,114 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { readFlag } from "../utils.js";
5
+ const mutations = { patch: 'patch', attach: 'resources', fork: 'fork', test: 'test-runs', freeze: 'proposals', commit: 'commit', prepare: 'prepare', activate: 'activate', rebase: 'rebase', share: 'share', participant: 'participants', presence: 'presence', claim: 'claims', message: 'chat/message', baseline: 'runtime/baseline', rollback: 'runtime/rollback' };
6
+ const reads = new Set(['diff', 'files', 'events', 'chat', 'search', 'preview-rebase', 'claims']);
7
+ function readStudioFile(file, cwd) {
8
+ const resolved = path.resolve(cwd, file);
9
+ const stat = fs.statSync(resolved);
10
+ if (!stat.isFile() || stat.size > 8 * 1048576)
11
+ throw new Error('Studio input must be a file of at most 8 MiB.');
12
+ return fs.readFileSync(resolved, 'utf8');
13
+ }
14
+ function readBody(context) {
15
+ const file = readFlag(context.args, ['body-file']);
16
+ const inline = readFlag(context.args, ['body']);
17
+ if (file && inline)
18
+ throw new Error('Choose --body-file or --body.');
19
+ const value = file ? readStudioFile(file, context.cwd) : inline;
20
+ if (value && Buffer.byteLength(value, 'utf8') > 8 * 1048576)
21
+ throw new Error('Studio JSON body exceeds 8 MiB.');
22
+ if (!value)
23
+ return {};
24
+ const parsed = JSON.parse(value);
25
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
26
+ throw new Error('Studio body must be a JSON object.');
27
+ return parsed;
28
+ }
29
+ /** Never turns a rejected legacy write into an unreviewed source commit. */
30
+ export async function handleStudioCommand(context) {
31
+ const { args, client } = context;
32
+ const action = args._[1] || 'list';
33
+ const sessionId = args._[2];
34
+ if (action === 'list') {
35
+ context.print(await client.listStudioSessions({ status: readFlag(args, ['status']) || 'OPEN' }));
36
+ return;
37
+ }
38
+ if (!['create', 'promote'].includes(action) && !sessionId)
39
+ throw new Error('Studio command requires a session ID.');
40
+ if (action === 'get') {
41
+ context.print(await client.getStudioSession(sessionId));
42
+ return;
43
+ }
44
+ if (reads.has(action)) {
45
+ const query = {};
46
+ for (const flag of ['afterCursor', 'take', 'q']) {
47
+ const value = readFlag(args, [flag]);
48
+ if (value)
49
+ query[flag] = value;
50
+ }
51
+ context.print(await client.readStudioSession(sessionId, action === 'preview-rebase' ? 'rebase' : action, query));
52
+ return;
53
+ }
54
+ if (action === 'file') {
55
+ if (!args._[3])
56
+ throw new Error('Studio file requires a file ID.');
57
+ context.print(await client.readStudioFile(sessionId, args._[3]));
58
+ return;
59
+ }
60
+ const body = readBody(context);
61
+ const operationId = readFlag(args, ['operation-id']) || body.operationId || randomUUID();
62
+ if (typeof operationId !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(operationId))
63
+ throw new Error('operationId must be a UUID.');
64
+ if (body.operationId && body.operationId !== operationId)
65
+ throw new Error('Body and --operation-id must identify the same retry.');
66
+ body.operationId = operationId;
67
+ if (action === 'create' || action === 'promote') {
68
+ if (action === 'promote') {
69
+ if (!Array.isArray(body.resources) || !body.resources.length)
70
+ throw new Error('Promote requires a full resources array.');
71
+ for (const resource of body.resources)
72
+ if (resource?.componentId && !Number.isSafeInteger(resource.baseVersion))
73
+ throw new Error('Each existing component must include its observed baseVersion.');
74
+ }
75
+ const snapshot = await client.createStudioSession(body);
76
+ if (action === 'promote')
77
+ context.print({ operationId, sessionId: snapshot.session?.studioSessionId, committed: false, snapshot, diff: await client.readStudioSession(snapshot.session.studioSessionId, 'diff') });
78
+ else
79
+ context.print({ operationId, result: snapshot });
80
+ return;
81
+ }
82
+ let result;
83
+ if (action === 'update')
84
+ result = await client.updateStudioSession(sessionId, body);
85
+ else if (action === 'delete')
86
+ result = await client.deleteStudioSession(sessionId, body);
87
+ else if (action === 'review') {
88
+ if (!args._[3])
89
+ throw new Error('Review requires a proposal ID and body with its exact proposalDigest and decision.');
90
+ result = await client.reviewStudioProposal(sessionId, args._[3], body);
91
+ }
92
+ else if (action === 'release-claim') {
93
+ if (!args._[3])
94
+ throw new Error('Release requires a work claim ID.');
95
+ result = await client.releaseStudioWorkClaim(sessionId, args._[3], body);
96
+ }
97
+ else if (action === 'cancel-test') {
98
+ if (!args._[3])
99
+ throw new Error('Cancel requires a test run ID.');
100
+ result = await client.cancelStudioTestRun(sessionId, args._[3], body);
101
+ }
102
+ else if (Object.hasOwn(mutations, action)) {
103
+ const patchFile = readFlag(args, ['patch-file']);
104
+ if (patchFile) {
105
+ if (action !== 'patch' || body.patch !== undefined)
106
+ throw new Error('--patch-file is accepted only for patch without a body patch.');
107
+ body.patch = readStudioFile(patchFile, context.cwd);
108
+ }
109
+ result = await client.mutateStudioSession(sessionId, mutations[action], body);
110
+ }
111
+ else
112
+ throw new Error(`Unknown Studio action: ${action}.`);
113
+ context.print({ operationId, result });
114
+ }
@@ -0,0 +1,11 @@
1
+ import { type BrowserLiveControl } from './terminal-browser-live-protocol.ts';
2
+ import { type BrowserInteraction } from './terminal-browser-interaction.ts';
3
+ import type { SecureBrowserIdentity } from './terminal-secure-browser.ts';
4
+ export type HumanInputScope = {
5
+ browserSessionId: string;
6
+ actorUserId: string;
7
+ threadId: string;
8
+ agentTerminalWorkspaceId?: string;
9
+ connectionId: string;
10
+ };
11
+ export declare function decryptBrowserHumanInput(frame: BrowserLiveControl, scope: HumanInputScope, identity: SecureBrowserIdentity): BrowserInteraction;
@@ -0,0 +1,44 @@
1
+ import { createDecipheriv, createPublicKey, diffieHellman, hkdfSync } from 'node:crypto';
2
+ import { browserLiveInputAad, BROWSER_LIVE_INPUT_INFO } from "./terminal-browser-live-protocol.js";
3
+ import { validBrowserInteraction } from "./terminal-browser-interaction.js";
4
+ function bytes(value, size) {
5
+ const data = Buffer.from(value, 'base64');
6
+ if (data.toString('base64') !== value || size !== undefined && data.length !== size)
7
+ throw new Error('browser_private_input_invalid');
8
+ return data;
9
+ }
10
+ export function decryptBrowserHumanInput(frame, scope, identity) {
11
+ const input = frame.privateInput;
12
+ if (!input || input.keyId !== identity.keyId || !Number.isSafeInteger(input.expiresAt)
13
+ || input.expiresAt <= Date.now() || input.expiresAt > Date.now() + 60_000)
14
+ throw new Error('browser_private_input_invalid');
15
+ let key;
16
+ let shared;
17
+ let plaintext;
18
+ try {
19
+ const publicKey = createPublicKey({ key: bytes(input.ephemeralPublicKey), type: 'spki', format: 'der' });
20
+ if (publicKey.asymmetricKeyType !== 'x25519')
21
+ throw new Error();
22
+ shared = diffieHellman({ privateKey: identity.privateKey, publicKey });
23
+ key = Buffer.from(hkdfSync('sha256', shared, Buffer.from(frame.requestId), Buffer.from(BROWSER_LIVE_INPUT_INFO), 32));
24
+ const cipher = createDecipheriv('aes-256-gcm', key, bytes(input.iv, 12));
25
+ cipher.setAAD(browserLiveInputAad({ ...scope, ...frame, ...input }));
26
+ cipher.setAuthTag(bytes(input.tag, 16));
27
+ const ciphertext = bytes(input.ciphertext);
28
+ if (ciphertext.length > 16_384)
29
+ throw new Error();
30
+ plaintext = Buffer.concat([cipher.update(ciphertext), cipher.final()]);
31
+ const interaction = JSON.parse(plaintext.toString('utf8'));
32
+ if (!validBrowserInteraction(interaction) || interaction.observationId !== input.observationId)
33
+ throw new Error();
34
+ return interaction;
35
+ }
36
+ catch {
37
+ throw new Error('browser_private_input_invalid');
38
+ }
39
+ finally {
40
+ shared?.fill(0);
41
+ key?.fill(0);
42
+ plaintext?.fill(0);
43
+ }
44
+ }
@@ -0,0 +1,25 @@
1
+ /** Browser-page input in CSS viewport pixels; this is never desktop or CDP access. */
2
+ export type BrowserInteraction = {
3
+ kind: 'click' | 'move' | 'drag' | 'scroll' | 'key' | 'text';
4
+ observationId: string;
5
+ x?: number;
6
+ y?: number;
7
+ toX?: number;
8
+ toY?: number;
9
+ button?: 'left' | 'right' | 'middle';
10
+ clickCount?: number;
11
+ deltaX?: number;
12
+ deltaY?: number;
13
+ key?: string;
14
+ text?: string;
15
+ modifiers?: Array<'Alt' | 'Control' | 'Meta' | 'Shift'>;
16
+ };
17
+ export type BrowserObservation = {
18
+ id: string;
19
+ tabId: string;
20
+ width: number;
21
+ height: number;
22
+ };
23
+ /** Nullable schema members are removed before authorization digests and runner dispatch. */
24
+ export declare function normalizeBrowserInteraction(value: unknown): BrowserInteraction | undefined;
25
+ export declare function validBrowserInteraction(value: unknown): value is BrowserInteraction;
@@ -0,0 +1,56 @@
1
+ const MODIFIERS = new Set(['Alt', 'Control', 'Meta', 'Shift']);
2
+ const KEYS = new Set(['Enter', 'Tab', 'Escape', 'Backspace', 'Delete', 'Insert', 'Home', 'End',
3
+ 'PageUp', 'PageDown', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space',
4
+ ...Array.from({ length: 12 }, (_, i) => `F${i + 1}`)]);
5
+ const FIELDS = {
6
+ click: ['x', 'y', 'button', 'clickCount', 'modifiers'], move: ['x', 'y'],
7
+ drag: ['x', 'y', 'toX', 'toY', 'button', 'modifiers'], scroll: ['deltaX', 'deltaY'],
8
+ key: ['key', 'modifiers'], text: ['text'],
9
+ };
10
+ /** Nullable schema members are removed before authorization digests and runner dispatch. */
11
+ export function normalizeBrowserInteraction(value) {
12
+ if (!value || typeof value !== 'object' || Array.isArray(value))
13
+ return undefined;
14
+ const schemaFields = new Set(['kind', 'observationId', ...Object.values(FIELDS).flat()]);
15
+ if (Object.keys(value).some(key => !schemaFields.has(key)))
16
+ return undefined;
17
+ const normalized = Object.fromEntries(Object.entries(value).filter(([, item]) => item != null));
18
+ return validBrowserInteraction(normalized) ? normalized : undefined;
19
+ }
20
+ export function validBrowserInteraction(value) {
21
+ if (!value || typeof value !== 'object' || Array.isArray(value))
22
+ return false;
23
+ const item = value;
24
+ if (typeof item.kind !== 'string' || !Object.prototype.hasOwnProperty.call(FIELDS, item.kind) || typeof item.observationId !== 'string'
25
+ || !/^[A-Za-z0-9_-]{1,128}$/u.test(item.observationId))
26
+ return false;
27
+ const allowed = new Set(['kind', 'observationId', ...FIELDS[item.kind]]);
28
+ if (Object.keys(item).some(key => !allowed.has(key)))
29
+ return false;
30
+ if (item.modifiers !== undefined && (!Array.isArray(item.modifiers) || item.modifiers.length > 4
31
+ || new Set(item.modifiers).size !== item.modifiers.length || item.modifiers.some(key => !MODIFIERS.has(key))))
32
+ return false;
33
+ if (item.button !== undefined && !['left', 'right', 'middle'].includes(item.button))
34
+ return false;
35
+ const point = (x, y) => Number.isInteger(x) && Number.isInteger(y)
36
+ && x >= 0 && x < 1920 && y >= 0 && y < 1080;
37
+ if (['click', 'move', 'drag'].includes(item.kind) && !point(item.x, item.y))
38
+ return false;
39
+ if (item.kind === 'drag' && !point(item.toX, item.toY))
40
+ return false;
41
+ if (item.kind === 'click' && item.clickCount !== undefined
42
+ && (!Number.isInteger(item.clickCount) || item.clickCount < 1 || item.clickCount > 2))
43
+ return false;
44
+ if (item.kind === 'scroll') {
45
+ const deltas = [item.deltaX ?? 0, item.deltaY ?? 0];
46
+ if (!deltas.every(delta => Number.isInteger(delta) && Math.abs(delta) <= 3000) || deltas.every(delta => delta === 0))
47
+ return false;
48
+ }
49
+ if (item.kind === 'key' && (typeof item.key !== 'string'
50
+ || !(KEYS.has(item.key) || /^[\x20-\x7e]$/u.test(item.key))))
51
+ return false;
52
+ if (item.kind === 'text' && (typeof item.text !== 'string' || !item.text.length
53
+ || item.text.length > 4096 || item.text.includes('\0')))
54
+ return false;
55
+ return true;
56
+ }