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.

9.1 KB
Raw Blame
import 'dart:convert';
import 'dart:isolate';
import 'dart:typed_data';

import '../core/test_run.dart';
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 — core.ts `ENCRYPTED_DOWN_TYPES`.
/// `test/encrypted_down_types_test.dart` holds it to the CLI's own list, because a type missing here
/// fails nowhere on the phone: the frame simply leaves in the clear, and the machine refuses it with
/// E2EE_REQUIRED (for terminal_* the relay drops it as TERMINAL_FRAME_REJECTED).
const Set<String> encryptedDownTypes = {
  'harness_devices_list',
  'harness_device_settings',
  '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 (`AppNotifier.resumeAgent`). Missing here, every tap on a Stopped row came
  // back "Could not open this harness: E2EE_REQUIRED".
  'agent_resume',
  // Carries the fork's name and first task — what the person typed — like agent_create's prompt.
  'agent_fork',
  // Change agent (`AppNotifier.changeAgent`): the machine writes the conversation's record into the
  // project, then the old agent is saved and stopped. Both `MACHINE_REQUESTS` types in the CLI, which
  // refuses them unsealed (E2EE_REQUIRED) — without them the switch could never start.
  'agent_handoff_prepare',
  'agent_close',
  // Then which harness took over (`AppNotifier._reportReplacement`): a `MACHINE_REQUESTS` type too.
  'agent_handoff_complete',
  // Delete Harness (`AppNotifier.purgeAgent`): reviewed, then deleted under that review. A
  // `MACHINE_REQUESTS` type in the CLI, refused unsealed (E2EE_REQUIRED).
  'agent_purge',
  'agent_recent',
  'agent_update',
  'agent_files',
  'agent_read_file',
  'fs_list_dir',
  'project_preview',
  // The branches of a folder on that machine, for the New Harness form
  // (`AppNotifier.readGitProject`).
  //
  // ⚠️ **Not in the CLI's `ENCRYPTED_DOWN_TYPES`, and still required.** The
  // machine's real rule is `encryptDownFrame` in `cli/src/lib/e2ee/
  // applicationFrames.ts`, which is that set OR a handful of types named
  // outright beside it — this one among them. Sent in the clear it came back
  // `E2EE_REQUIRED`, which on this screen read as a folder with no branches.
  'git_project_info',
  // The harness's branch and pull-request history is a machine RPC too.
  'git_pull_request',
  // 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',
  // Connected services (`phone/connectors_page.dart`, CLI services/connectors.ts): the sign-in's
  // redirect, with its code, rides `callback`. A `MACHINE_REQUESTS` type in the CLI: sent in the clear
  // the machine refused it ("E2EE required"), which read as no computer online.
  'connectors',
  // A sign-in this phone caught for a page a harness's program opened (`AppNotifier.browserCallback`): it
  // carries the code. A `MACHINE_REQUESTS` type in the CLI.
  'browser_callback',
  // A Harness OS computer managed from here (`AppNotifier.osDevice`, CLI services/osDevice.ts): its
  // update, and its Wi-Fi with the password. A `MACHINE_REQUESTS` type in the CLI.
  'os_device',
  // Swarm (`AppNotifier.swarmRequest`, CLI superTabs/service.ts): the machine forwards the call to the
  // backend, and the answer is the Swarm's conversations and decisions. A `MACHINE_REQUESTS` type in the CLI.
  'super_tabs',
  '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',
  // An individual daemon's plates, asked of harnessd (daemons/README.md, "Individual art"): one of the
  // pair brain's machine-to-machine frames (`PAIR_REQUESTS` in applicationFrames.ts), always sealed.
  '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);
}

/// From this many characters of `ct` an envelope is opened off the UI isolate ([unwrapPayloadOffThread]).
/// Below it — every event, every small reply — spawning an isolate costs more than the open.
const int unwrapOffThreadFrom = 48 * 1024;

/// Whether [env]'s ciphertext is large enough to open off the UI isolate.
bool opensOffThread(Object? env) {
  if (kUnderTest || env is! Map) return false;
  final ct = env['ct'];
  return ct is String && ct.length >= unwrapOffThreadFrom;
}

/// [unwrapPayload] on a background isolate: base64, ChaCha20-Poly1305 and the JSON of a large
/// payload — a machine's whole agent list, a transcript, a file — are pure Dart, and done on the UI
/// isolate they stalled the screen for as long as they took. A pure function of its arguments, so
/// the isolate answers exactly what this one would; one that will not start is the work done here.
Future<Map<String, dynamic>?> unwrapPayloadOffThread(
  List<int> key,
  Map<String, dynamic> env,
  String frameType,
  String? dbSessionId,
) async {
  final keyBytes = Uint8List.fromList(key);
  try {
    return await Isolate.run(
      () => unwrapPayload(keyBytes, env, frameType, dbSessionId),
    );
  } on Object {
    return unwrapPayload(key, env, frameType, dbSessionId);
  }
}

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;
  }
}