Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

7.3 KB
Raw Blame
import 'dart:convert';
import 'dart:typed_data';

import 'bytes.dart';
import 'primitives.dart';

/// core.ts's frame-payload envelope: `{__e2e: {v, k, n, ct, epoch?}}` stands in for a frame's
/// payload while its `type` stays readable, so the relay can route what it cannot read.

const int e2eVersion = 1;

/// Frames this client must send as ciphertext — the machine's `encryptDownFrame` rule
/// (applicationFrames.ts: core.ts `ENCRYPTED_DOWN_TYPES` and the request sets beside it).
/// test/e2ee/ holds it to that whole rule, because a type missing here fails nowhere: the frame
/// simply leaves in the clear and the machine answers E2EE_REQUIRED (for terminal_* the relay
/// drops it as TERMINAL_FRAME_REJECTED).
const Set<String> encryptedDownTypes = {
  'harness_devices_list',
  'harness_device_settings',
  // Agent Messages (CLI messages/wire.ts): a tab's log carries what agents said to each other.
  'agent_messages',
  'harness_share_list',
  'harness_share_invite',
  'harness_share_remove',
  'harness_share_link',
  'harness_share_comments',
  'harness_share_comment_post',
  'harness_share_comment_remove',
  // Harness's application RPC extensions (CLI e2ee/applicationFrames.ts).
  'grid_fleet_capabilities',
  'grid_fleet_run',
  'grid_fleet_cancel',
  'machine_resources',
  'agent_close',
  'phone_pair',
  'viewer_surface',
  'api_connections',
  'connectors',
  // Sharing a machine across accounts (CLI services/sharedMachines.ts): the addresses it is shared with,
  // and where a guest may start a harness (the owner's folders).
  'shared_machines',
  'guest_folders',
  'super_tabs',
  'orchestrator',
  'route_task',
  'route_send',
  'grid_fleet_models_list',
  'grid_fleet_model_start',
  'grid_fleet_model_download',
  'grid_fleet_model_stop',
  'message',
  'question_response',
  'agents_list',
  'sessions_list',
  'session_get',
  'models_list',
  'agent_create',
  'agent_create_status', 'agent_create_cancel',
  'agent_delete',
  'agent_restart',
  // Reopens stopped work and forks a harness: the CLI has required both sealed since they were
  // added, so unsealed the machine answers E2EE_REQUIRED (the web build sends them itself).
  'agent_resume',
  'agent_fork',
  'agent_recent',
  // Writes the conversation record a switched agent reads (cli/src/lib/agentHandoff.ts).
  'agent_handoff_prepare',
  'agent_handoff_complete',
  'agent_update',
  'agent_files',
  'agent_read_file',
  'fs_list_dir',
  'project_preview',
  'git_project_info',
  // The harness's branch and pull-request history is a machine RPC too (applicationFrames.ts
  // `MACHINE_REQUESTS`): unsealed, the machine answers E2EE_REQUIRED.
  'git_pull_request', 'git_pull_requests_status',
  // Memories across machines (CLI services/memory.ts).
  'memory_snapshot',
  'memory_about_put',
  'memory_deliver',
  // Cloud agents (CLI services/cloud.ts): a cloud harness's conversation and the person's words for it.
  'cloud_transcript',
  'cloud_send',
  'cloud_agents',
  // The trust-group roster swap (`viewer/group_sync.dart`): the keys every member trusts.
  'group_sync',
  'codex_profiles_list',
  'codex_profile_link',
  // Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missing
  // here it went out in the clear and the machine's CLI refused it outright with E2EE_REQUIRED —
  // which surfaced as an empty Usage page on a phone that was linked and connected.
  'usage_read',
  // The pane colours this client paints with, for the machine's tmux sessions (cli/src/lib/hostTheme.ts).
  'theme_set',
  // What somebody searches their conversations for (cli/src/lib/sessionSearch/).
  'session_search',
  // Which conversation somebody is previewing, from the same index.
  'session_tail',
  'device_e2ee_pair',
  'e2ee_pairings_list',
  'e2ee_pairing_unpair',
  'e2ee_pairings_unpair_all',
  'e2ee_browser_link_create',
  'terminal_capabilities',
  'terminal_open',
  'terminal_alive',
  'terminal_ack',
  'terminal_input',
  'terminal_resize',
  'terminal_resync',
  'terminal_close',
  'terminal_scroll',
  'terminal_chunked_upload_begin',
  'terminal_chunked_upload_cancel',
  'p2p_offer',
  'p2p_answer',
  'p2p_ice_candidate',
  'p2p_abort',
  'p2p_promote',
  // The rest of what the machine requires sealed: its rule is `encryptDownFrame`
  // (cli/src/lib/e2ee/applicationFrames.ts), the set above OR the sets named beside
  // it (`git_pull_request` is above, beside `git_project_info`). These are listed
  // before anything sends them.
  'agent_purge',
  'agent_worktree_delete',
  'agents_cleanup_preview',
  'viewer_request',
  'viewer_data',
  'viewer_ack',
  'viewer_end',
  'viewer_close',
  'pair_watch',
  'pair_journal',
  'pair_read',
  'pair_list',
  'pair_answer',
  'pair_send',
  'pair_stop',
  'pair_start',
  'pair_pause',
  'pair_resume',
  'pair_plate_get',
};

/// Requests an older CLI took in the clear and a current one refuses unsealed — applicationFrames.ts
/// `STRICT_DOWN_TYPES`. Sealed only for a machine whose welcome says `strictDown`: an older one would
/// never open the envelope and would read the request as empty.
const Set<String> strictDownTypes = {
  'dsh_install',
  'dsh_update',
  'dsh_remove',
  'dsh_list',
  'agent_retarget',
  'engines_probe',
  'grid_models_list',
  'cancel',
  'claude_login_status',
  'speaking',
};

/// Whether [type] goes sealed to a machine — applicationFrames.ts `encryptDownFrameFor`.
bool sealsDown(String type, {required bool strictDown}) =>
    encryptedDownTypes.contains(type) ||
    (strictDown && strictDownTypes.contains(type));

Uint8List _aad(
  int v,
  String type,
  String dbSessionId,
  String k,
  String epoch,
) => utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');

/// Seals [payload] under [key]: [k] is 'p' (pairwise session) or 'g' (the machine's group key,
/// which also carries an [epoch]).
Map<String, Object?> wrapPayload(
  List<int> key,
  String k,
  int counter,
  String frameType,
  String? dbSessionId,
  Object? payload, {
  String? epoch,
}) {
  final aad = _aad(e2eVersion, frameType, dbSessionId ?? '', k, epoch ?? '');
  final sealed = aeadSeal(key, counter, aad, utf8Bytes(jsonEncode(payload)));
  return {
    '__e2e': {
      'v': e2eVersion,
      'k': k,
      'n': counter,
      'ct': b64e(sealed),
      'epoch': ?epoch,
    },
  };
}

/// The payload object [wrapPayload] sealed; null when it does not open — a wrong key or counter, or
/// an AAD (type, session, epoch) other than the one it was sealed under.
Map<String, dynamic>? unwrapPayload(
  List<int> key,
  Map<String, dynamic> env,
  String frameType,
  String? dbSessionId,
) {
  final v = env['v'], k = env['k'], n = env['n'], ct = env['ct'];
  final epoch = env['epoch'] ?? '';
  if (v is! int ||
      k is! String ||
      n is! int ||
      ct is! String ||
      epoch is! String) {
    return null;
  }
  final Uint8List sealed;
  try {
    sealed = b64d(ct);
  } on FormatException {
    return null;
  }
  final clear = aeadOpen(
    key,
    n,
    _aad(v, frameType, dbSessionId ?? '', k, epoch),
    sealed,
  );
  return clear == null ? null : jsonObjectOf(clear);
}

bool isWrapped(Object? payload) =>
    payload is Map && payload.containsKey('__e2e');

/// UTF-8 JSON that must be an object; null for anything else.
Map<String, dynamic>? jsonObjectOf(List<int> utf8Json) {
  try {
    final value = jsonDecode(utf8.decode(utf8Json));
    return value is Map<String, dynamic> ? value : null;
  } on FormatException {
    return null;
  }
}