diff --git a/docker/kin-kvm/guest/kin-slot-agent b/docker/kin-kvm/guest/kin-slot-agent index 20e6e7205..b3836e24b 100644 --- a/docker/kin-kvm/guest/kin-slot-agent +++ b/docker/kin-kvm/guest/kin-slot-agent @@ -594,6 +594,7 @@ class SlotAgentService: handlers = { "sync_file": self._op_sync_file, "sync_preset_tz": self._op_sync_preset_tz, + "clear_slot_state": self._op_clear_slot_state, "publish": self._op_publish, "publish_universal": self._op_publish_universal, "block": self._op_block, @@ -616,22 +617,71 @@ class SlotAgentService: # Never leak payload/credentials contents in error messages. return {"id": req_id, "ok": False, "error": "internal_error", "message": type(exc).__name__} + def _resolve_claude_and_home_dirs(self) -> tuple[Path, Path]: + if self.cfg.claude_dir is not None: + return self.cfg.claude_dir, self.cfg.claude_dir.parent + return self.cfg.state_dir / "claude", self.cfg.state_dir / "home" + + def _open_state_subdir(self, target_dir: Path, *, mode: int = 0o700) -> int: + try: + rel = target_dir.relative_to(self.cfg.state_dir) + dir_fd = open_dir_nofollow(self.cfg.state_dir, rel.parts, create_sub=True, mode=mode) + except ValueError: + dir_fd = open_dir_nofollow(target_dir.parent, (target_dir.name,), create_sub=True, mode=mode) + if os.geteuid() == 0: + os.fchown(dir_fd, self.cfg.kincli_uid, self.cfg.kincli_gid) + return dir_fd + def _op_sync_file(self, params: dict[str, Any]) -> dict[str, Any]: target = params.get("target") - if target not in ("credentials", "kernel_config", "worker_config", "managed_preset"): + if target not in ("credentials", "kernel_config", "worker_config", "managed_preset", "claude_profile"): raise RpcError("invalid_params", f"unsupported sync_file target: {target!r}") raw, sha256_hex = decode_and_verify_payload(params.get("content_b64"), params.get("sha256")) + if target == "claude_profile": + try: + parsed = json.loads(raw.decode("utf-8")) + except Exception as exc: + raise RpcError("invalid_params", "claude_profile must be valid UTF-8 JSON") from exc + if not isinstance(parsed, dict): + raise RpcError("invalid_params", "claude_profile must be a JSON object") + claude_dir, home_dir = self._resolve_claude_and_home_dirs() + claude_fd = self._open_state_subdir(claude_dir, mode=0o700) + try: + atomic_write_in_dir( + claude_fd, + ".claude.json", + raw, + mode=0o600, + uid=self.cfg.kincli_uid, + gid=self.cfg.kincli_gid, + ) + finally: + os.close(claude_fd) + home_fd = self._open_state_subdir(home_dir, mode=0o700) + try: + atomic_write_in_dir( + home_fd, + ".claude.json", + raw, + mode=0o600, + uid=self.cfg.kincli_uid, + gid=self.cfg.kincli_gid, + ) + finally: + os.close(home_fd) + return { + "target": target, + "path": str(claude_dir / ".claude.json"), + "home_path": str(home_dir / ".claude.json"), + "sha256": sha256_hex, + "bytes": len(raw), + } + if target == "credentials": if self.cfg.claude_dir is not None: claude_dir = self.cfg.claude_dir - try: - rel = claude_dir.relative_to(self.cfg.state_dir) - dir_fd = open_dir_nofollow(self.cfg.state_dir, rel.parts, create_sub=True, mode=0o700) - except ValueError: - dir_fd = open_dir_nofollow(claude_dir.parent, (claude_dir.name,), create_sub=True, mode=0o700) - if os.geteuid() == 0: - os.fchown(dir_fd, self.cfg.kincli_uid, self.cfg.kincli_gid) + dir_fd = self._open_state_subdir(claude_dir, mode=0o700) dest_path = claude_dir / "credentials.json" else: dir_fd = open_dir_nofollow(self.cfg.state_dir, ("claude",), create_sub=True, mode=0o700) @@ -675,6 +725,54 @@ class SlotAgentService: "bytes": len(raw), } + def _remove_path_nofollow(self, target: Path, *, allow_dir: bool) -> bool: + try: + st = os.lstat(str(target)) + except FileNotFoundError: + return False + if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode): + os.unlink(str(target)) + return True + if not allow_dir: + raise RpcError("unsafe_path", f"expected file, found directory: {target.name}") + # Restore write/exec bits on subdirectories (e.g. 0o555 sandbox .masks) before unlinking. + stack: list[Path] = [target] + dirs: list[Path] = [] + while stack: + cur = stack.pop() + try: + os.chmod(str(cur), 0o700) + except OSError: + pass + dirs.append(cur) + with os.scandir(str(cur)) as it: + for entry in it: + entry_path = Path(entry.path) + if entry.is_dir(follow_symlinks=False): + stack.append(entry_path) + else: + os.unlink(str(entry_path)) + for d in reversed(dirs): + os.rmdir(str(d)) + return True + + def _op_clear_slot_state(self, _params: dict[str, Any]) -> dict[str, Any]: + claude_dir, home_dir = self._resolve_claude_and_home_dirs() + targets: tuple[tuple[str, Path, bool], ...] = ( + ("credentials", claude_dir / "credentials.json", False), + ("credentials_alias", claude_dir / ".credentials.json", False), + ("claude_profile", claude_dir / ".claude.json", False), + ("home_claude_profile", home_dir / ".claude.json", False), + ("crag_v3_continuations", claude_dir / "crag-v3-continuations", True), + ("telemetry", claude_dir / "telemetry", True), + ("crag_sessions", self.cfg.run_dir / "work" / ".crag-sessions", True), + ) + cleared: list[str] = [] + for label, target_path, allow_dir in targets: + if self._remove_path_nofollow(target_path, allow_dir=allow_dir): + cleared.append(label) + return {"cleared": cleared} + def _op_sync_preset_tz(self, params: dict[str, Any]) -> dict[str, Any]: tz_raw = params.get("timezone") has_tz = tz_raw is not None and tz_raw != "" diff --git a/docker/kin-kvm/guest/test_kin_slot_agent.py b/docker/kin-kvm/guest/test_kin_slot_agent.py index 3246bacd5..fdead24a9 100644 --- a/docker/kin-kvm/guest/test_kin_slot_agent.py +++ b/docker/kin-kvm/guest/test_kin_slot_agent.py @@ -939,6 +939,105 @@ def test_publish_skips_unchanged_inode_and_status_reports_digests(self) -> None: self.assertEqual(st_final["result"]["crag_sync_pending"], {"license": False, "host": False}) self.assertEqual(st_final["result"]["crag_files_sha256"]["host"]["entitlement.code"], esha_2) + def test_sync_claude_profile_and_clear_slot_state(self) -> None: + custom_claude_dir = self.state_dir / "home" / ".claude" + custom_home_dir = self.state_dir / "home" + custom_cfg = agent.AgentConfig( + token=self.token, + state_dir=self.state_dir, + claude_dir=custom_claude_dir, + run_dir=self.run_dir, + crag_root=self.crag_root, + managed_preset_dir=self.managed_dir, + store_dir=self.store_dir, + machine_id_file=self.machine_id_file, + crag_pid_file=self.crag_pid_file, + dmi_dir=self.dmi_dir, + kincli_uid=os.getuid(), + kincli_gid=os.getgid(), + project_mounts=False, + ) + svc = agent.SlotAgentService(custom_cfg) + + # Sync credentials + claude_profile + creds = b'{"claudeAiOauth":{"accessToken":"tok-clear"}}\n' + cb64, csha = _b64_and_sha(creds) + r_cred = svc.handle_request({ + "id": "c-cred", + "token": self.token, + "op": "sync_file", + "params": {"target": "credentials", "content_b64": cb64, "sha256": csha}, + }) + self.assertTrue(r_cred["ok"], r_cred) + + profile = b'{"userID":"' + b"a" * 64 + b'","machineID":"' + b"b" * 64 + b'"}\n' + pb64, psha = _b64_and_sha(profile) + r_prof = svc.handle_request({ + "id": "c-prof", + "token": self.token, + "op": "sync_file", + "params": {"target": "claude_profile", "content_b64": pb64, "sha256": psha}, + }) + self.assertTrue(r_prof["ok"], r_prof) + nested_profile = custom_claude_dir / ".claude.json" + home_profile = custom_home_dir / ".claude.json" + self.assertEqual(nested_profile.read_bytes(), profile) + self.assertEqual(home_profile.read_bytes(), profile) + self.assertEqual(stat.S_IMODE(nested_profile.stat().st_mode), 0o600) + self.assertEqual(stat.S_IMODE(home_profile.stat().st_mode), 0o600) + + # Reject invalid JSON for claude_profile + bad_b64, bad_sha = _b64_and_sha(b"not-json") + r_bad = svc.handle_request({ + "id": "c-prof-bad", + "token": self.token, + "op": "sync_file", + "params": {"target": "claude_profile", "content_b64": bad_b64, "sha256": bad_sha}, + }) + self.assertFalse(r_bad["ok"]) + self.assertEqual(r_bad["error"], "invalid_params") + + # Seed continuations, telemetry, and .crag-sessions with a 0o555 .masks directory + cont_dir = custom_claude_dir / "crag-v3-continuations" + cont_dir.mkdir(parents=True, exist_ok=True) + (cont_dir / "journal.log").write_text("entry\n", encoding="utf-8") + tel_dir = custom_claude_dir / "telemetry" + tel_dir.mkdir(parents=True, exist_ok=True) + (tel_dir / "batch.json").write_text("{}\n", encoding="utf-8") + masks_dir = self.run_dir / "work" / ".crag-sessions" / ".masks" / "m-1" + masks_dir.mkdir(parents=True, exist_ok=True) + (masks_dir / "stub").write_text("x", encoding="utf-8") + os.chmod(masks_dir, 0o555) + os.chmod(masks_dir.parent, 0o555) + + r_clear = svc.handle_request({ + "id": "c-clear", + "token": self.token, + "op": "clear_slot_state", + "params": {}, + }) + self.assertTrue(r_clear["ok"], r_clear) + cleared = set(r_clear["result"]["cleared"]) + self.assertTrue( + { + "credentials", + "credentials_alias", + "claude_profile", + "home_claude_profile", + "crag_v3_continuations", + "telemetry", + "crag_sessions", + }.issubset(cleared), + cleared, + ) + self.assertFalse((custom_claude_dir / "credentials.json").exists()) + self.assertFalse((custom_claude_dir / ".credentials.json").is_symlink()) + self.assertFalse(nested_profile.exists()) + self.assertFalse(home_profile.exists()) + self.assertFalse(cont_dir.exists()) + self.assertFalse(tel_dir.exists()) + self.assertFalse((self.run_dir / "work" / ".crag-sessions").exists()) + if __name__ == "__main__": unittest.main() diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 24f2e39b0..1c92019fe 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -253,3 +253,33 @@ isolation, refusal to claim success with a missing required file, and preservati of node machine ID, OAuth config, internal token, and credentials. No production account or telemetry switch was touched; real KVM and successful production-node publication remain separate verification boundaries. + +## Slot Machine Profile & Identity Controls + +- **Per-install HMAC pepper (`KIN_MACHINE_PROFILE_PEPPER`)**: + Account-bound 3-OS machine profiles (`darwin` / `win32` / `linux`) derive + seeds via HMAC-SHA256. Operators may set `KIN_MACHINE_PROFILE_PEPPER` (recommended + for multi-instance deployments so all control-plane replicas share the same + pepper). When unset, the control plane auto-generates a 32-byte random hex + secret on first use and persists it in the DB `settings` table under + `slot_machine_profile_pepper` (matching `panel_2fa_challenge_secret`), never + falling back to a hardcoded source constant. +- **CRAG kernel capability gate (`slot_machine_profile_v1` / `>= 5.0.2`)**: + `run/kernel.json` top-level `machine_profile` and 3-OS `telemetry.identity` + overrides (which omit `dmi_dir`) are only emitted when the active CRAG v2 + kernel advertises `slot_machine_profile_v1` or software version `>= 5.0.2`. + Older `crag-v2 <= 5.0.0` kernels retain legacy `telemetry.dmi_dir` and omit + `machine_profile`. +- **Legacy slot preservation & traits rotation**: + Pre-existing slots with a legacy `fingerprint.device_id` / Linux identity are + never lazily overwritten on the request hot path unless explicitly opted in + (`machine_profile_opt_in: true` or `machine_profile_mode: "3os"`). Newly + created Claude slots opt in automatically, and `traits` rebuilds rotate + `profile_generation` + `profile_reseed_nonce` + persisted `slot_epoch`. +- **One-way OS/Git persona rewrite (default OFF)**: + Reversible path/tool-ID/session-ID/commit-SHA isolation runs automatically on + slots with an active `machine_profile`, while one-way OS/Git persona text + rewriting (`Platform:`, `OS Version:`, `Shell:`, `Author:`, `Co-Authored-By:`, + `user.email=`, `# userEmail`) is OFF by default and requires explicit opt-in + (`KIN_SLOT_PERSONA_REWRITE=1`, `routing.slot_persona_rewrite: true`, or + `vm.machine_profile.persona_rewrite: true`). diff --git a/src/lib/admin/panel-api.mjs b/src/lib/admin/panel-api.mjs index 87e5a667c..58770fb1c 100644 --- a/src/lib/admin/panel-api.mjs +++ b/src/lib/admin/panel-api.mjs @@ -298,35 +298,58 @@ export function publicPhysicalFeatures(vm) { } if (!vm || typeof vm !== 'object') return empty const fp = vm.fingerprint && typeof vm.fingerprint === 'object' ? vm.fingerprint : {} - const hw = fp.hardware && typeof fp.hardware === 'object' ? fp.hardware : {} + const mp = vm.machine_profile && typeof vm.machine_profile === 'object' ? vm.machine_profile : {} + const mpHw = mp.hardware && typeof mp.hardware === 'object' ? mp.hardware : {} + const hw = fp.hardware && typeof fp.hardware === 'object' ? fp.hardware : mpHw const machine = vm.machine && typeof vm.machine === 'object' ? vm.machine : {} const runtime = vm.runtime && typeof vm.runtime === 'object' ? vm.runtime : {} const specMiB = machine.memory ? memoryMiB(machine.memory) : 0 return { observed_at: - presentText(hw.observed_at) || presentText(fp.collected_at) || presentText(runtime.identity_collected_at), + presentText(hw.observed_at) || + presentText(mpHw.observed_at) || + presentText(fp.collected_at) || + presentText(runtime.identity_collected_at), runtime_type: vm.runtime_type || runtimeKind(vm) || null, - hostname: presentText(fp.hostname), - os_id: presentText(fp.os_id), - os_pretty: presentText(fp.os_pretty), - kernel_release: presentText(fp.guest_kernel_release) || presentText(fp.kernel_release), - arch: presentText(fp.stainless_arch) || presentText(fp.arch), + hostname: + presentText(fp.display_hostname) || + presentText(fp.hostname) || + presentText(mp.display_hostname) || + presentText(mp.hostname), + os_id: presentText(fp.os_id) || presentText(mp.os_id), + os_pretty: presentText(fp.os_pretty) || presentText(mp.os_pretty), + kernel_release: + presentText(fp.guest_kernel_release) || presentText(fp.kernel_release) || presentText(mp.kernel_release), + arch: + presentText(fp.stainless_arch) || presentText(fp.arch) || presentText(mp.stainless_arch) || presentText(mp.arch), machine_id_present: !!( presentText(fp.guest_machine_id) || presentText(fp.machine_id) || - presentText(hw.machine_id) + presentText(hw.machine_id) || + presentText(mp.device_id) || + presentText(mp.machine_id) ), - timezone: presentText(fp.timezone) || presentText(vm.timezone), - locale: presentText(fp.locale) || presentText(vm.locale), - cpu_model: presentText(hw.cpu_model) || presentText(machine.cpu_model), - cpu_cores: presentInt(hw.cpu_cores) ?? presentInt(machine.vcpus), - memory_bytes: presentBytes(hw.memory_bytes) ?? (specMiB > 0 ? specMiB * 1024 * 1024 : null), - root_disk: presentText(hw.root_disk) || presentText(machine.disk_serial), - mac: presentText(hw.mac) || presentText(machine.mac), - dmi: publicDmi(hw, machine.smbios), - shell: presentList(hw.shell) || presentList(fp.shell), - package_managers: presentList(hw.package_managers) || presentList(fp.package_managers), - runtimes: presentList(hw.runtimes) || presentList(fp.runtimes), + timezone: presentText(fp.timezone) || presentText(mp.timezone) || presentText(vm.timezone), + locale: presentText(fp.locale) || presentText(mp.locale) || presentText(vm.locale), + cpu_model: presentText(hw.cpu_model) || presentText(mpHw.cpu_model) || presentText(machine.cpu_model), + cpu_cores: presentInt(hw.cpu_cores) ?? presentInt(mpHw.cpu_cores) ?? presentInt(machine.vcpus), + memory_bytes: + presentBytes(hw.memory_bytes) ?? presentBytes(mpHw.memory_bytes) ?? (specMiB > 0 ? specMiB * 1024 * 1024 : null), + root_disk: presentText(hw.root_disk) || presentText(mpHw.root_disk) || presentText(machine.disk_serial), + mac: presentText(hw.mac) || presentText(mpHw.mac) || presentText(machine.mac), + dmi: publicDmi(hw, mpHw.dmi || machine.smbios), + shell: presentList(hw.shell) || presentList(fp.shell) || presentList(mp.shell), + package_managers: + presentList(hw.package_managers) || presentList(fp.package_managers) || presentList(mp.package_managers), + runtimes: presentList(hw.runtimes) || presentList(fp.runtimes) || presentList(mp.runtimes), + ...(mp.os_family + ? { + os_family: presentText(mp.os_family), + stainless_os: presentText(mp.stainless_os), + os_version: presentText(mp.os_version), + machine_home: presentText(mp.machine_home), + } + : {}), } } diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index ef8080c98..b027f5139 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -87,7 +87,16 @@ import { credentialModeOfVm, liveOauthToSetupToken, } from '../oauth/credential-mode.mjs' -import { persistSlotAuthScheme, readWorkerCredentialFile } from '../oauth/oauth-credentials.mjs' +import { + persistSlotAuthScheme, + readWorkerCredentialFile, + syncSlotClaudeProfileJson, + wipeSlotSessionAndTelemetryState, + writeWorkerCredentialFile, +} from '../oauth/oauth-credentials.mjs' +import { ensureVmSlotMachineProfile, toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' +import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs' +import { notifyRustKernelSlotReset, triggerRustKernelSlotReset } from '../transport/rust-kernel-client.mjs' import { isSub2apiAccountExport, sub2apiAccountToOauth, @@ -311,7 +320,8 @@ import { discardSlotContainer, STANDARD_LOCALE, } from '../vm/vm-runtime.mjs' -import { isCragDebian13Kernel } from '../vm/custom-os-runtime.mjs' +import { isCragDebian13Kernel, isCustomKvmMode } from '../vm/custom-os-runtime.mjs' +import { syncCustomKvmSlotFiles } from '../vm/kvm-slot-agent-client.mjs' import { startSlotReady, reloadSlotReady, @@ -334,6 +344,7 @@ import { normalizeVmConfig, resolveMachineSpec, validateVmConfigPatch } from '.. import { raiseDockerSlotMemory } from '../vm/docker-slot-memory.mjs' import { isKvmRuntime, RUNTIME_KVM } from '../vm/runtime-kind.mjs' import { hostProxyUrlForVm, slotHost } from '../vm/slot-host.mjs' +import { slotHome } from '../vm/slot-identity.mjs' import { syncIpv6ProxyEgress } from '../vm/proxy-policy-runtime.mjs' import { proxyBlockedReason } from '../vm/proxy-policy.mjs' import { initializeSlotSeedFiles, writeSlotSeedFiles } from '../vm/slot-seed.mjs' @@ -992,6 +1003,7 @@ export function createPanelHandler(ctx) { geminiSlotPrefs: ctx.geminiSlotPrefs || null, geminiOwnersRepo: ctx.geminiOwnersRepo || null, schedulerRuntime: resolveSchedulerRuntime, + stickyRouter: () => ctx.stickyRouter, writeSSEHeaders: ctx.writeSSEHeaders || null, json, readBody, @@ -6263,11 +6275,21 @@ export function createPanelHandler(ctx) { return await withVmLock(vmPath, async () => { if (!fs.existsSync(vmPath)) return json(res, 404, { ok: false, error: { message: 'vm not found' } }) const prev = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const prevAccountId = prev?.claude?.account_uuid || prev?.account_uuid || null const gone = await teardownSlot(prev, mode === 'traits' ? ctx.cragSubscription : null) if (!gone.ok) { return json(res, 500, { ok: false, error: { message: gone.error || 'destroy failed', code: gone.code } }) } let { vm } = recreateVmFiles(cfg.paths.project, prev, { mode }) + if (mode !== 'keep') { + try { + await resolveSchedulerRuntime()?.deleteSticky?.({ + node_type: isCodexVm(prev) ? 'codex_vm' : 'claude_vm', + node_id: id, + }) + } catch {} + resetSlotSessionState({ vmId: id, accountId: prevAccountId, vmEpoch: vm?.slot_epoch }) + } try { invalidateLiveCredentialCache() } catch {} @@ -6355,7 +6377,13 @@ export function createPanelHandler(ctx) { } const prev = JSON.parse(fs.readFileSync(vmPath, 'utf8')) prev.id = prev.id || id + const prevAccountId = prev?.claude?.account_uuid || prev?.account_uuid || null const slotDir = path.join(cfg.paths.project, 'vms', id) + try { + await slotHost(prev).clearSlotState?.(prev, slotDir) + } catch (err) { + console.warn(`[credential/clear] vm=${id} clearSlotState failed: ${err?.message || err}`) + } const removed = [] for (const file of [ path.join(slotDir, 'codex-credentials.json'), @@ -6370,6 +6398,25 @@ export function createPanelHandler(ctx) { } } catch {} } + const wipedState = wipeSlotSessionAndTelemetryState(slotDir) + for (const rel of wipedState.removed) { + removed.push(path.relative(cfg.paths.project, path.join(slotDir, rel))) + } + for (const claudeJsonPath of [ + path.join(slotDir, 'cli-home', '.claude.json'), + path.join(slotDir, 'cli-home', '.claude', '.claude.json'), + ]) { + try { + if (!fs.existsSync(claudeJsonPath)) continue + const parsed = JSON.parse(fs.readFileSync(claudeJsonPath, 'utf8')) + if (parsed && typeof parsed === 'object') { + delete parsed.oauthAccount + delete parsed.userID + delete parsed.machineID + atomicWriteJson(claudeJsonPath, parsed, { mode: 0o600 }) + } + } catch {} + } const vm = patchVmRecord(cfg.paths.project, id, (record) => { record.email = null @@ -6378,6 +6425,8 @@ export function createPanelHandler(ctx) { record.expires_at = null record.codex = {} record.claude = {} + delete record.machine_profile + record.slot_epoch = (Number(record.slot_epoch) || 0) + 1 record.worker_credential = null record.refresh_status = null record.refresh_error = null @@ -6387,6 +6436,26 @@ export function createPanelHandler(ctx) { applyUnschedulable(record, 'no_credential') return record }) || prev + try { + await resolveSchedulerRuntime()?.deleteSticky?.({ + node_type: isCodexVm(prev) ? 'codex_vm' : 'claude_vm', + node_id: id, + }) + } catch {} + resetSlotSessionState({ vmId: id, accountId: prevAccountId, vmEpoch: vm?.slot_epoch }) + if (!isCodexVm(vm) && !slotHost(vm).native && fs.existsSync(path.join(slotDir, 'run', 'kernel.json'))) { + try { + writeKernelConfig(cfg.paths.project, vm, { routing: ctx.routingConfig, publish: true }) + if (!vm.node_id && isKvmRuntime(vm) && isCustomKvmMode({ vm })) { + await syncCustomKvmSlotFiles(cfg.paths.project, vm, { + homeDir: path.join(slotDir, 'cli-home'), + runDir: path.join(slotDir, 'run'), + targets: ['kernel_config'], + timeoutMs: 3000, + }).catch(() => null) + } + } catch {} + } try { invalidateLiveCredentialCache() } catch {} @@ -6401,6 +6470,17 @@ export function createPanelHandler(ctx) { }) kernel.restarted = !!started?.ok if (!started?.ok) kernel.error = started?.reason || 'codex_kernel_start_failed' + } else if (!slotHost(vm).native && process.env.KIN_CRS_MOCK !== '1') { + const exec = slotExec(cfg.paths.project, getVm(cfg.paths.project, id) || vm) + await notifyRustKernelSlotReset(exec, { wipeDisk: true }).catch(() => null) + const restarted = await restartRustKernel(exec, { routing: ctx.routingConfig, timeoutMs: 15_000 }) + kernel.restarted = !!restarted?.ok + if (!restarted?.ok) { + kernel.error = restarted?.error || restarted?.reason || 'rust_kernel_restart_failed' + console.warn(`[credential/clear] vm=${id} restartRustKernel failed: ${kernel.error}`) + } + } else { + triggerRustKernelSlotReset(prev, slotDir, { wipeDisk: true }) } } catch (e) { kernel.error = String(e?.message || e).slice(0, 160) @@ -6430,18 +6510,100 @@ export function createPanelHandler(ctx) { return json(res, 404, { ok: false, error: { message: 'vm not found' } }) } let vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const prevPhysicalMachineId = String(vm.fingerprint?.guest_machine_id || '').trim() const generated = assignComputerFingerprint(cfg.paths.project, vm, { taken: takenFingerprintKeys(listVms(cfg.paths.project), { exceptId: id }), }) + const physicalMachineId = String(generated.guest_machine_id || prevPhysicalMachineId || '').trim() vm.timezone = generated.timezone vm.locale = generated.locale vm.fingerprint = applyGeneratedFingerprint({}, generated) + if (physicalMachineId) vm.fingerprint.guest_machine_id = physicalMachineId vm.updated_at = generated.reset_at + const slotDir = path.join(cfg.paths.project, 'vms', id) + const homeDir = path.join(slotDir, 'cli-home') + if (!isCodexVm(vm) && (vm.claude?.account_uuid || vm.claude?.email || vm.machine_profile)) { + vm.slot_epoch = (Number(vm.slot_epoch) || 0) + 1 + vm.profile_generation = (Number(vm.profile_generation) || 0) + 1 + const ensured = ensureVmSlotMachineProfile( + vm, + { + accountUuid: vm.claude?.account_uuid || vm.account_uuid || null, + email: vm.claude?.email || vm.email || null, + orgUuid: vm.claude?.org_uuid || vm.org_uuid || null, + timezoneHint: vm.timezone, + }, + { forceReseed: true }, + ) + if (ensured.profile?.reseed_nonce) { + vm.profile_reseed_nonce = ensured.profile.reseed_nonce + } + if (physicalMachineId && vm.fingerprint && typeof vm.fingerprint === 'object') { + vm.fingerprint.guest_machine_id = physicalMachineId + } + try { + syncSlotClaudeProfileJson(homeDir, vm, { + workDir: '/run/kin/work', + containerHome: slotHome(vm), + wipeAccountState: false, + }) + } catch {} + try { + const liveCred = readWorkerCredentialFile(homeDir) + if (liveCred && ensured.profile) { + writeWorkerCredentialFile(homeDir, { + ...liveCred, + machineProfile: toPublicSlotMachineProfile(ensured.profile), + }) + } + } catch {} + resetSlotSessionState({ + vmId: id, + accountId: vm.claude?.account_uuid || vm.account_uuid || null, + vmEpoch: vm.slot_epoch, + }) + } atomicWriteJson(vmPath, vm, { mode: 0o600 }) - writeGuestMachineIdFile(cfg.paths.project, id, generated.guest_machine_id) - applyOfficialFingerprintToVm(vmPath, path.join(cfg.paths.project, 'vms', id, 'cli-home')) + if (physicalMachineId) writeGuestMachineIdFile(cfg.paths.project, id, physicalMachineId) + applyOfficialFingerprintToVm(vmPath, homeDir) try { vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + if (fs.existsSync(fingerprintDir(cfg.paths.project, id))) { + const tzSync = syncSlotIdentityTimezoneAndPreset(cfg.paths.project, vm, { + timezone: vm.timezone, + locale: vm.locale, + }) + if (tzSync?.ok && vm.status === 'running' && vm.runtime?.type === 'kvm') { + await pushLiveSlotTimezoneSync(cfg.paths.project, vm, tzSync).catch(() => null) + } + } + if (!isCodexVm(vm) && !slotHost(vm).native) { + if (fs.existsSync(path.join(slotDir, 'run', 'kernel.json'))) { + writeKernelConfig(cfg.paths.project, vm, { routing: ctx.routingConfig, publish: true }) + } + const host = slotHost(vm) + await host.syncCredentials?.(vm, slotDir)?.catch?.((err) => { + console.warn(`[reset-fingerprint] vm=${id} syncCredentials failed: ${err?.message || err}`) + }) + await host.syncClaudeProfile?.(vm, slotDir)?.catch?.((err) => { + console.warn(`[reset-fingerprint] vm=${id} syncClaudeProfile failed: ${err?.message || err}`) + }) + if (!vm.node_id && isKvmRuntime(vm) && isCustomKvmMode({ vm })) { + await syncCustomKvmSlotFiles(cfg.paths.project, vm, { + homeDir, + runDir: path.join(slotDir, 'run'), + targets: ['credentials', 'kernel_config', 'managed_preset'], + timeoutMs: 3000, + }).catch(() => null) + } + if (process.env.KIN_CRS_MOCK !== '1') { + const exec = slotExec(cfg.paths.project, vm) + await notifyRustKernelSlotReset(exec, { wipeDisk: true }).catch(() => null) + await restartRustKernel(exec, { routing: ctx.routingConfig, timeoutMs: 15_000 }).catch((err) => { + console.warn(`[reset-fingerprint] vm=${id} restartRustKernel failed: ${err?.message || err}`) + }) + } + } } catch {} return json(res, 200, panel.ok({ id, fingerprint: vm.fingerprint })) }) @@ -6614,8 +6776,17 @@ export function createPanelHandler(ctx) { latest.timezone = timezone latest.timezone_source = hasTimezone ? 'manual' : 'proxy_geo' if (latest.fingerprint && typeof latest.fingerprint === 'object') latest.fingerprint.timezone = timezone + if (latest.machine_profile && typeof latest.machine_profile === 'object') { + latest.machine_profile = { ...latest.machine_profile, timezone } + } + } + if (locale) { + latest.locale = locale + if (latest.fingerprint && typeof latest.fingerprint === 'object') latest.fingerprint.locale = locale + if (latest.machine_profile && typeof latest.machine_profile === 'object') { + latest.machine_profile = { ...latest.machine_profile, locale } + } } - if (locale) latest.locale = locale latest.seed_policy = nextPolicy latest.updated_at = new Date().toISOString() atomicWriteJson(vmPath, latest, { mode: 0o600 }) @@ -6630,6 +6801,27 @@ export function createPanelHandler(ctx) { } vm = persisted.vm const { next, unsupported } = persisted + if ((timezone || locale) && !isCodexVm(vm) && vm.machine_profile && typeof vm.machine_profile === 'object') { + const slotDir = path.join(cfg.paths.project, 'vms', id) + const homeDir = path.join(slotDir, 'cli-home') + try { + const liveCred = readWorkerCredentialFile(homeDir) + if (liveCred) { + writeWorkerCredentialFile(homeDir, { + ...liveCred, + machineProfile: toPublicSlotMachineProfile(vm.machine_profile), + }) + await slotHost(vm) + .syncCredentials?.(vm, slotDir) + ?.catch?.(() => null) + } + } catch {} + if (!slotHost(vm).native && fs.existsSync(path.join(slotDir, 'run', 'kernel.json'))) { + try { + writeKernelConfig(cfg.paths.project, vm, { routing: ctx.routingConfig, publish: true }) + } catch {} + } + } if (fs.existsSync(fingerprintDir(cfg.paths.project, id))) { try { const tzSync = syncSlotIdentityTimezoneAndPreset(cfg.paths.project, vm, { @@ -7236,6 +7428,7 @@ export function createPanelHandler(ctx) { inflight: 0, }, claude: {}, + ...(!codexCreate ? { machine_profile_opt_in: true } : {}), fingerprint: applyGeneratedFingerprint({}, generated), stats: {}, created_at: new Date().toISOString(), @@ -7382,6 +7575,31 @@ export function createPanelHandler(ctx) { vm.timezone = zoned.timezone vm.timezone_source = 'proxy_geo' if (vm.fingerprint && typeof vm.fingerprint === 'object') vm.fingerprint.timezone = zoned.timezone + if (vm.machine_profile && typeof vm.machine_profile === 'object') { + vm.machine_profile = { ...vm.machine_profile, timezone: zoned.timezone } + try { + const slotDir = path.join(cfg.paths.project, 'vms', id) + const homeDir = path.join(slotDir, 'cli-home') + const liveCred = readWorkerCredentialFile(homeDir) + if (liveCred) { + writeWorkerCredentialFile(homeDir, { + ...liveCred, + machineProfile: toPublicSlotMachineProfile(vm.machine_profile), + }) + } + if (!slotHost(vm).native && fs.existsSync(path.join(slotDir, 'run', 'kernel.json'))) { + writeKernelConfig(cfg.paths.project, vm, { routing: ctx.routingConfig, publish: true }) + } + } catch {} + } + if (fs.existsSync(fingerprintDir(cfg.paths.project, id))) { + try { + syncSlotIdentityTimezoneAndPreset(cfg.paths.project, vm, { + timezone: vm.timezone, + locale: vm.locale, + }) + } catch {} + } } let startError = null try { diff --git a/src/lib/admin/scheduler-pools-routes.mjs b/src/lib/admin/scheduler-pools-routes.mjs index 558a18db8..2ab1c8344 100644 --- a/src/lib/admin/scheduler-pools-routes.mjs +++ b/src/lib/admin/scheduler-pools-routes.mjs @@ -19,6 +19,7 @@ import { } from '../db/repos/scheduler-pools-repo.mjs' import { corsHeadersForRequest } from '../http/cors.mjs' import { resolveCredentialScheduleLevel } from '../pool/credential-weight.mjs' +import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs' import { SchedulerApiError, SchedulerUnavailableError, @@ -1962,10 +1963,21 @@ export function createSchedulerPoolsHandler({ error: { message: '删除粘性绑定至少需要一个过滤条件', code: 'sticky_filter_required' }, }) } + // Only clear the targeted session's in-memory replay/epoch state when a + // specific session_id is deleted; never trigger global resets or disk wipes + // from ordinary scheduler sticky deletion. + const purgeTargetedSessionState = () => { + const targetSession = typeof filter.session_id === 'string' ? filter.session_id.trim() : '' + if (targetSession) { + resetSlotSessionState({ sessionId: targetSession }) + } + } + if (rt && typeof rt.deleteSticky === 'function') { try { const result = await rt.deleteSticky(filter) const deleted = Number(result?.deleted) || 0 + purgeTargetedSessionState() invalidatePoolsCache(['scheduler_sticky_bindings']) return json(res, 200, { ok: true, @@ -1980,6 +1992,7 @@ export function createSchedulerPoolsHandler({ } try { const deleted = repo.deleteStickyBindings(filter) + purgeTargetedSessionState() invalidatePoolsCache(['scheduler_sticky_bindings']) return json(res, 200, { ok: true, deleted, data: { deleted } }) } catch (e) { diff --git a/src/lib/cluster/remote-slot-files.mjs b/src/lib/cluster/remote-slot-files.mjs index 65b228436..624b445c1 100644 --- a/src/lib/cluster/remote-slot-files.mjs +++ b/src/lib/cluster/remote-slot-files.mjs @@ -51,6 +51,7 @@ const SEED_SETTINGS_FILES = Object.freeze([ 'cli-home/.claude/settings.json', 'cli-home/.claude/claude.setting', 'cli-home/.claude/kin-seed.json', + 'cli-home/.claude/.claude.json', ]) export const SLOT_FILE_SETS = Object.freeze({ run: ['run/kernel.json', 'run/worker.json', 'run/internal.token'], @@ -420,6 +421,18 @@ export async function pushSlotCredentials(vm, slotDir, session = null) { // Official CLI reads ~/.claude/.credentials.json; one store, same as local slots. if (!isCodexVm(vm)) { await remoteSymlink(sftp, 'credentials.json', `${remote}/claude/.credentials.json`) + const owner = ownerFor(s, vm) + for (const rel of ['cli-home/.claude/.claude.json', 'cli-home/.claude.json']) { + const profilePath = path.join(slotDir, rel) + if (!fs.existsSync(profilePath)) continue + try { + const profileBytes = fs.readFileSync(profilePath) + await writeRemoteFile(sftp, `${remote}/${remoteSlotPath(rel)}`, profileBytes, { + mode: REMOTE_FILE_MODE, + owner, + }) + } catch {} + } } const vmPath = path.join(path.dirname(slotDir), `${vm.id}.json`) if (fs.existsSync(vmPath)) { diff --git a/src/lib/identity/crs-headers.mjs b/src/lib/identity/crs-headers.mjs index 77a39d675..44dd5abe0 100644 --- a/src/lib/identity/crs-headers.mjs +++ b/src/lib/identity/crs-headers.mjs @@ -263,8 +263,8 @@ function vmStainlessHeaders(identity = {}) { 'user-agent': identity.userAgent || DEFAULTS['user-agent'], 'x-app': fp.x_app || 'cli', 'x-stainless-lang': OFFICIAL_STAINLESS.stainless_lang, - 'x-stainless-os': OFFICIAL_STAINLESS.stainless_os, - 'x-stainless-arch': OFFICIAL_STAINLESS.stainless_arch, + 'x-stainless-os': fp.stainless_os || OFFICIAL_STAINLESS.stainless_os, + 'x-stainless-arch': fp.stainless_arch || OFFICIAL_STAINLESS.stainless_arch, 'x-stainless-runtime': OFFICIAL_STAINLESS.stainless_runtime, 'x-stainless-runtime-version': OFFICIAL_STAINLESS.stainless_runtime_version, 'x-stainless-package-version': OFFICIAL_STAINLESS.stainless_package_version, diff --git a/src/lib/identity/crs-persona.mjs b/src/lib/identity/crs-persona.mjs index a5c73c44b..f9549d712 100644 --- a/src/lib/identity/crs-persona.mjs +++ b/src/lib/identity/crs-persona.mjs @@ -30,6 +30,7 @@ * top-level system and the hop lifts any remaining turns. */ import { createHash } from 'node:crypto' +import { nativeCcProjectSlug } from './slot-machine-profile.mjs' import { resolveWorkstationProfile } from './workstation-profile.mjs' import fs from 'node:fs' import { readJsonParsedCached } from '../vm/vm-file.mjs' @@ -846,8 +847,15 @@ export function requiredTimezone(identity = {}, facts = {}) { export function configuredTimezone(identity = {}, facts = {}) { const src = identity && typeof identity === 'object' ? identity : {} const fp = src.fingerprint || {} + const mp = src.machine_profile || {} const inbound = facts && typeof facts === 'object' ? facts : {} - return validTimezone(src.timezone) || validTimezone(fp.timezone) || validTimezone(inbound.timezone) || '' + return ( + validTimezone(src.timezone) || + validTimezone(fp.timezone) || + validTimezone(mp.timezone) || + validTimezone(inbound.timezone) || + '' + ) } export function buildZeroBillingText( @@ -937,11 +945,13 @@ export function personaTemplateVars({ keep_dynamic_boundary: ['official', 'official_full', OFFICIAL_303_PRESET].includes(preset), main_prompt_303: () => isPresetGuidanceEnabled(compat, preset) - ? renderOfficial303MainPrompt({ cwd: env?.cwd, entrypoint }) + ? renderOfficial303MainPrompt({ cwd: env?.cwd, memoryDir: env?.memoryDir, entrypoint }) : OFFICIAL_303_HARNESS, harness_303: OFFICIAL_303_HARNESS, guidance_303: () => - isPresetGuidanceEnabled(compat, preset) ? renderOfficial303Guidance({ cwd: env?.cwd, entrypoint }) : '', + isPresetGuidanceEnabled(compat, preset) + ? renderOfficial303Guidance({ cwd: env?.cwd, memoryDir: env?.memoryDir, entrypoint }) + : '', env_303: () => (withEnv ? buildOfficial303Environment(env, { model: model || env?.modelId }) : ''), env_instructions_303: () => withEnv && presetFlagEnabled(compat, 'persona_env_instructions_presets', preset) @@ -1004,13 +1014,38 @@ export function personaPreviewVars({ timezone = 'UTC', model = 'claude-sonnet-5' export function officialSystemEnvFromIdentity(identity = {}, modelId = '', facts = {}, { overwrite = false } = {}) { const src = identity && typeof identity === 'object' ? identity : {} const fp = src.fingerprint || {} + const mp = src.machine_profile && typeof src.machine_profile === 'object' ? src.machine_profile : null const inbound = facts && typeof facts === 'object' ? facts : {} const ws = resolveWorkstationProfile({ id: src.vmId || src.id, kernel: src.kernel || '', fingerprint: fp, + machine_profile: mp, }) if (overwrite) { + if (mp) { + const sep = mp.path_sep || (mp.os_family === 'win32' ? '\\' : '/') + const defaultCwd = mp.work_root ? `${mp.work_root}${sep}workspace` : '' + const resolvedCwd = sanitizeInboundCwd(inbound.cwd) || defaultCwd + const memoryDir = + mp.claude_config_dir && resolvedCwd + ? `${mp.claude_config_dir}${sep}projects${sep}${nativeCcProjectSlug(resolvedCwd)}${sep}memory${sep}` + : '' + return { + cwd: resolvedCwd, + memoryDir, + machineProfile: mp, + git: inbound.git === true, + shell: mp.shell || ws.shell, + platform: mp.platform_raw || mp.os_family || 'linux', + osVersion: mp.os_version || ws.os_version, + kernel: mp.os_family === 'linux' ? mp.linux_kernel || mp.kernel_release || '' : '', + osPretty: '', + modelId: modelId || 'claude-sonnet-5-5', + timezone: src.timezone || fp.timezone || mp.timezone || '', + locale: src.locale || fp.locale || mp.locale || inbound.locale || '', + } + } return { cwd: sanitizeInboundCwd(inbound.cwd), git: inbound.git === true, @@ -1032,8 +1067,8 @@ export function officialSystemEnvFromIdentity(identity = {}, modelId = '', facts osVersion: inbound.osVersion || '', kernel: inbound.kernel || '', modelId: modelId || 'claude-sonnet-5-5', - timezone: src.timezone || fp.timezone || '', - locale: src.locale || fp.locale || inbound.locale || '', + timezone: src.timezone || fp.timezone || mp?.timezone || '', + locale: src.locale || fp.locale || mp?.locale || inbound.locale || '', } } diff --git a/src/lib/identity/cwd-mapping.mjs b/src/lib/identity/cwd-mapping.mjs new file mode 100644 index 000000000..fb8d3ab12 --- /dev/null +++ b/src/lib/identity/cwd-mapping.mjs @@ -0,0 +1,1065 @@ +/** + * Bidirectional 3-OS working directory, home, slug, `CLAUDE.md`, `ls -l`, and + * `# Environment` / `` mapper with chunk-safe SSE streaming reverse rewriter. + * + * Covers all 8 path/slug syntaxes bidirectionally: + * 1. Native OS paths (`/Users/...`, `C:\Users\...`, `/home/...`, `X:\proj`) + * 2. Forward-slash Windows paths (`C:/Users/...`, `X:/proj`) + * 3. JSON double-escaped Windows paths (`C:\\Users\\...`, `X:\\proj`) in JSON/`partial_json` + * 4. `file://` URIs (`file:///Users/...`, `file:///C:/Users/...`) + * 5. `~/...` and `~\...` tilde workspace/config paths + * 6. Native CC `kI()` project slugs (`-Users-...`, `C--Users-...`, `-home-...`) & `# Memory` dirs + * 7. `CLAUDE.md` Managed / User / Project / AutoMem paths across `darwin` / `win32` / `linux` + * 8. Shell `cd ` commands & terminal prompt anchors (`user@host:...`, `PS C:\...>`) + * + * Safeguards: + * - Never touches `thinking` or `redacted_thinking` blocks (`thinking.signature` intact). + * - Never corrupts `http://` / `https://` / `ws://` / `wss://` URLs. + * - Preserves system roots (`/usr`, `/bin`, `/sbin`, `/lib`, `/var`, `/dev`, `/proc`, + * `/etc` except `/etc/claude-code`, `/tmp` unless caller CWD is inside `/tmp/...`, `C:\Windows`). + * - Deterministic & idempotent across Turn 1..N (100% prompt-cache prefix stability). + */ +import { nativeCcProjectSlug } from './slot-machine-profile.mjs' + +const MANAGED_CLAUDE_DIRS = Object.freeze({ + darwin: '/Library/Application Support/ClaudeCode', + win32: 'C:\\Program Files\\ClaudeCode', + linux: '/etc/claude-code', +}) + +const SYSTEM_LS_OWNERS = new Set([ + 'daemon', + 'bin', + 'sys', + 'nobody', + 'nogroup', + 'www-data', + 'messagebus', + 'systemd-network', + 'systemd-resolve', +]) + +const LS_LONG_LINE_RE = /^([bcdlps-][rwxstST-]{9}[+@.]?\s+\d+\s+)(\S+)(\s+)(\S+)(\s+)/gm +const MAX_SSE_HOLD_CHARS = 512 + +function escapeRegExp(str) { + return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +function isWindowsStylePath(p) { + return /^[A-Za-z]:[/\\]/.test(String(p || '')) +} + +function trimTrailingSep(p) { + const s = String(p || '').trim() + if (!s) return '' + if (/^[A-Za-z]:[/\\]$/.test(s)) return `${s[0].toUpperCase()}:\\` + if (s === '/') return '/' + return s.replace(/[/\\]+$/, '') +} + +function normalizePathSep(p, sep) { + const s = trimTrailingSep(p) + if (!s) return '' + if (sep === '\\') { + const out = s.replace(/\//g, '\\') + return /^[a-z]:\\/.test(out) ? `${out[0].toUpperCase()}${out.slice(1)}` : out + } + return s.replace(/\\/g, '/') +} + +function toForwardSlash(p) { + return String(p || '').replace(/\\/g, '/') +} + +function toJsonEscapedWin(p) { + return String(p || '').replace(/\\/g, '\\\\') +} + +function toFileUri(p) { + const fwd = toForwardSlash(trimTrailingSep(p)) + if (!fwd) return '' + if (/^[A-Za-z]:\//.test(fwd)) return `file:///${fwd[0].toUpperCase()}${fwd.slice(1)}` + if (fwd.startsWith('/')) return `file://${fwd}` + return `file:///${fwd}` +} + +/** Legacy `vm2api` slug variant (dots/underscores preserved, leading `-`) for inbound compatibility. */ +function legacyProjectSlug(projectPath) { + const cleaned = String(projectPath || '') + .trim() + .replace(/\\/g, '/') + .replace(/\/+$/, '') + if (!cleaned) return '' + const slug = cleaned.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-') + return slug.startsWith('-') ? slug : `-${slug}` +} + +function inferHomeFromCwd(cwd) { + const s = String(cwd || '').trim() + if (!s) return '' + let m = s.match(/^(\/Users\/[^/]+)(?:\/|$)/) + if (m) return m[1] + m = s.match(/^(\/home\/[^/]+)(?:\/|$)/) + if (m) return m[1] + m = s.match(/^([A-Za-z]:[/\\]Users[/\\][^/\\]+)(?:[/\\]|$)/i) + if (m) return normalizePathSep(m[1], '\\') + m = s.match(/^(\/root)(?:\/|$)/) + if (m) return '/root' + return '' +} + +function extractBasename(p) { + const trimmed = trimTrailingSep(p) + if (!trimmed || trimmed === '/' || /^[A-Za-z]:\\?$/.test(trimmed)) return '' + const parts = trimmed.split(/[/\\]/).filter(Boolean) + const last = parts[parts.length - 1] || '' + return last.replace(/[^A-Za-z0-9._-]/g, '-') || 'workspace' +} + +function collectTextFromBody(body) { + const chunks = [] + if (!body || typeof body !== 'object') return chunks + if (typeof body.system === 'string') { + chunks.push({ zone: 'system', text: body.system }) + } else if (Array.isArray(body.system)) { + for (const b of body.system) { + if (b && typeof b === 'object' && typeof b.text === 'string') { + chunks.push({ zone: 'system', text: b.text }) + } + } + } + if (Array.isArray(body.messages)) { + for (const msg of body.messages) { + if (!msg || typeof msg !== 'object') continue + if (typeof msg.content === 'string') { + chunks.push({ zone: msg.role || 'user', text: msg.content }) + } else if (Array.isArray(msg.content)) { + for (const b of msg.content) { + if (!b || typeof b !== 'object') continue + if (b.type === 'text' && typeof b.text === 'string') { + chunks.push({ zone: msg.role || 'user', text: b.text }) + } + } + } + } + } + return chunks +} + +function detectCallerFactsFromBody(body, explicitCallerCwd = '') { + let detectedCwd = trimTrailingSep(explicitCallerCwd) + let detectedHome = '' + + const texts = collectTextFromBody(body) + for (const { text } of texts) { + if (!detectedCwd) { + const envCwd = text.match(/^\s*-\s*Primary working directory:\s*([^\r\n]+)$/m) + if (envCwd) detectedCwd = trimTrailingSep(envCwd[1]) + } + if (!detectedCwd) { + const legacyCwd = text.match(/^\s*(?:-\s*)?Working directory:\s*([^\r\n<]+)$/m) + if (legacyCwd) detectedCwd = trimTrailingSep(legacyCwd[1]) + } + if (!detectedHome) { + const memMatch = text.match( + /((?:[A-Za-z]:[/\\]|\/)[^\r\n"'`<>]+?)[/\\]\.claude[/\\]projects[/\\][^/\\\r\n"'`<>]+[/\\]memory[/\\]?/, + ) + if (memMatch) detectedHome = trimTrailingSep(memMatch[1]) + } + if (!detectedHome) { + const claudeDirMatch = text.match( + /(?:^|[\s"'`(=])((?:[A-Za-z]:[/\\]Users[/\\][^/\\\s"'`<>|*?]+|\/Users\/[^/\s"'`<>|*?]+|\/home\/[^/\s"'`<>|*?]+|\/root))[/\\]\.claude(?:[/\\]|\.json\b)/, + ) + if (claudeDirMatch) { + const candidate = trimTrailingSep(claudeDirMatch[1]) + if (candidate && candidate !== detectedCwd) { + detectedHome = candidate + } + } + } + if (!detectedHome && detectedCwd && !inferHomeFromCwd(detectedCwd)) { + const anyHomeMatch = text.match( + /(?:^|[\s"'`(=])([A-Za-z]:[/\\]Users[/\\][^/\\\s"'`<>|*?]+|\/Users\/[^/\s"'`<>|*?]+|\/home\/[^/\s"'`<>|*?]+)(?=[/\\\s"'`):,;]|$)/, + ) + if (anyHomeMatch) { + const candidate = trimTrailingSep(anyHomeMatch[1]) + if (candidate && candidate !== detectedCwd) { + detectedHome = candidate + } + } + } + } + + return { detectedCwd, detectedHome } +} + +function isProtectedSystemPath(candidatePath, callerCwdFwd) { + const fwd = toForwardSlash(candidatePath) + if (!fwd) return false + if (/^[A-Za-z]:\/Windows(?:\/|$)/i.test(fwd)) return true + if (/^\/(?:usr|bin|sbin|lib|lib64|dev|proc|sys|var)(?:\/|$)/.test(fwd)) return true + if (/^\/etc(?:\/|$)/.test(fwd) && !/^\/etc\/claude-code(?:\/|$)/.test(fwd)) return true + if (/^\/tmp(?:\/|$)/.test(fwd)) { + if ( + callerCwdFwd && + /^\/tmp\/.+/.test(callerCwdFwd) && + (fwd === callerCwdFwd || fwd.startsWith(`${callerCwdFwd}/`)) + ) { + return false + } + return true + } + return false +} + +function isUrlPrefixAt(text, matchStart, prevContext = '') { + const before = + matchStart >= 10 + ? text.slice(matchStart - 10, matchStart) + : `${prevContext ? prevContext.slice(-(10 - matchStart)) : ''}${text.slice(0, matchStart)}` + if (!before) return false + const prev = before[before.length - 1] + // e.g. `https://example.com/Users/...` -> char before `/Users` is `m` + if (/[A-Za-z0-9_.-]/.test(prev)) return true + // e.g. `https:///Users/...` or `http:///...` (not `file://`) + if (/(?:https?|wss?):\/+$/.test(before.toLowerCase())) return true + return false +} + +function convertSubpathSeparators(subpath, targetSep, isJsonString = false) { + if (!subpath) return '' + if (isJsonString) { + // Normalize `\\` or `/` inside JSON string literal subpath + const unified = subpath.replace(/\\\\/g, '/') + if (targetSep === '\\') return unified.replace(/\//g, '\\\\') + return unified + } + if (targetSep === '\\') return subpath.replace(/\//g, '\\') + return subpath.replace(/\\/g, '/') +} + +/** + * Replace `sourcePrefix` + optional subpath (`/...` or `\...` or `\\...`) in `text` + * with `targetPrefix` + separator-converted subpath, respecting URL & word boundaries. + */ +function replaceRootWithSubpath(text, rule, { isJsonString = false, callerCwdFwd = '', prevContext = '' } = {}) { + const { source, target, targetSep, allowSubpath, posixLeadingSlash } = rule + if (!source || source === target || !text.includes(source)) return text + + const escaped = escapeRegExp(source) + const subPattern = allowSubpath + ? isJsonString + ? '((?:(?:\\\\\\\\|/)(?:[^\\s"\'`<>|*?()[\\]{},;\\\\]|\\\\\\\\)*)?)' + : '((?:[/\\\\][^\\s"\'`<>|*?()[\\]{},;:]*)?)' + : '()' + + const re = new RegExp(`${escaped}${subPattern}(?![A-Za-z0-9._-])`, 'g') + return text.replace(re, (whole, subpath = '', offset) => { + if (posixLeadingSlash && isUrlPrefixAt(text, offset, prevContext)) { + return whole + } + const rawCandidate = `${source}${subpath || ''}` + if (rule.checkSystemGuard && isProtectedSystemPath(rawCandidate, callerCwdFwd)) { + return whole + } + + // Trim trailing sentence punctuation (`.` at end of sentence) from subpath + let cleanSub = subpath || '' + let trailingPunct = '' + if (cleanSub && /[.,]$/.test(cleanSub)) { + const m = cleanSub.match(/([.,]+)$/) + if (m) { + trailingPunct = m[1] + cleanSub = cleanSub.slice(0, -trailingPunct.length) + } + } + + const convertedSub = convertSubpathSeparators(cleanSub, targetSep, isJsonString) + return `${target}${convertedSub}${trailingPunct}` + }) +} + +/** + * Create a stateful/idempotent 3-OS CWD & environment mapper for `profile`. + */ +export function createCwdMapper(profile = {}, options = {}) { + const osFamily = profile.os_family === 'darwin' || profile.os_family === 'win32' ? profile.os_family : 'linux' + const virtSep = osFamily === 'win32' ? '\\' : '/' + const virtualHome = normalizePathSep( + profile.machine_home || + (osFamily === 'darwin' + ? `/Users/${profile.username || 'alexchen'}` + : osFamily === 'win32' + ? `C:\\Users\\${profile.username || 'alexchen'}` + : `/home/${profile.username || 'alexchen'}`), + virtSep, + ) + const virtualWorkRoot = normalizePathSep(profile.work_root || `${virtualHome}${virtSep}work`, virtSep) + const virtualManagedDir = MANAGED_CLAUDE_DIRS[osFamily] + const lsOwner = String(profile.ls_owner || profile.username || 'alexchen') + const lsGroup = String(profile.ls_group || (osFamily === 'darwin' ? 'staff' : lsOwner)) + const virtUser = String(profile.username || lsOwner) + const virtHost = String(profile.hostname || 'workstation') + const personaRewrite = options?.personaRewrite === true + + let state = null + let callerPromptHost = 'localhost' + + function ensureMappingState(body = null, explicitCallerCwd = '') { + const { detectedCwd, detectedHome } = detectCallerFactsFromBody(body, explicitCallerCwd || options.callerCwd || '') + + const rawCwd = detectedCwd || state?.rawCwd || '' + const rawHome = + detectedHome || inferHomeFromCwd(rawCwd) || trimTrailingSep(options.callerHome || '') || state?.rawHome || '' + + // Ignore if already pointing at virtualCwd / virtualHome on repeated pass (idempotency) + const rawCwdNormFwd = toForwardSlash(rawCwd) + if ( + state && + ((!rawCwd && !rawHome) || + rawCwdNormFwd === toForwardSlash(state.virtualCwd) || + rawCwdNormFwd === toForwardSlash(state.virtualHome)) + ) { + return state + } + + if (state && state.rawCwd === rawCwd && state.rawHome === rawHome) { + return state + } + + const callerIsWin = isWindowsStylePath(rawCwd || rawHome) + const callerSep = callerIsWin ? '\\' : '/' + const callerCwd = rawCwd ? normalizePathSep(rawCwd, callerSep) : '' + const callerHome = rawHome ? normalizePathSep(rawHome, callerSep) : '' + const callerCwdFwd = toForwardSlash(callerCwd) + const callerHomeFwd = toForwardSlash(callerHome) + const callerUser = callerHome ? extractBasename(callerHome) : '' + const callerManagedDir = callerIsWin + ? MANAGED_CLAUDE_DIRS.win32 + : callerHomeFwd.startsWith('/Users/') + ? MANAGED_CLAUDE_DIRS.darwin + : MANAGED_CLAUDE_DIRS.linux + + let virtualCwd = `${virtualWorkRoot}${virtSep}workspace` + if (callerCwd) { + const virtualWorkRootFwd = toForwardSlash(virtualWorkRoot) + if (callerHome && toForwardSlash(callerCwd) === toForwardSlash(callerHome)) { + virtualCwd = virtualHome + } else if (callerCwdFwd === virtualWorkRootFwd || callerCwdFwd.startsWith(`${virtualWorkRootFwd}/`)) { + virtualCwd = normalizePathSep(callerCwd, virtSep) + } else { + const proj = extractBasename(callerCwd) || 'workspace' + virtualCwd = `${virtualWorkRoot}${virtSep}${proj}` + } + } + + const virtualSlug = nativeCcProjectSlug(virtualCwd) + const virtualHomeSlug = nativeCcProjectSlug(virtualHome) + const callerSlug = callerCwd ? nativeCcProjectSlug(callerCwd) : '' + const callerSlugFwd = callerCwd && callerIsWin ? nativeCcProjectSlug(callerCwdFwd) : '' + const callerLegacySlug = callerCwd ? legacyProjectSlug(callerCwd) : '' + const callerHomeSlug = callerHome ? nativeCcProjectSlug(callerHome) : '' + + const virtualMemoryBase = `${virtualHome}${virtSep}.claude${virtSep}projects${virtSep}${virtualSlug}${virtSep}memory` + const virtualMemoryDir = `${virtualMemoryBase}${virtSep}` + const callerMemoryBases = [] + if (callerHome && callerSlug) { + callerMemoryBases.push( + `${callerHome}${callerSep}.claude${callerSep}projects${callerSep}${callerSlug}${callerSep}memory`, + ) + if (callerLegacySlug && callerLegacySlug !== callerSlug) { + callerMemoryBases.push( + `${callerHome}${callerSep}.claude${callerSep}projects${callerSep}${callerLegacySlug}${callerSep}memory`, + ) + } + } + + // Relative tilde workspace (`~/projects/app` <-> `~/work/app` / `~\work\app`) + let callerTildeRel = '' + let virtualTildeRel = '' + if (callerCwd && callerHome && callerCwdFwd !== callerHomeFwd && callerCwdFwd.startsWith(`${callerHomeFwd}/`)) { + callerTildeRel = callerCwdFwd.slice(callerHomeFwd.length + 1) + virtualTildeRel = toForwardSlash(virtualCwd).slice(toForwardSlash(virtualHome).length + 1) + } + + const forwardRules = [] + const reverseTextRules = [] + const reverseJsonRules = [] + + const addRootPair = (realRoot, virtRoot, { checkSystemGuard = false } = {}) => { + if (!realRoot || !virtRoot) return + const realFwd = toForwardSlash(realRoot) + const virtFwd = toForwardSlash(virtRoot) + if (realFwd === virtFwd && realRoot === virtRoot) return + + // 4. `file://` URIs (always forward-slash inside URI) + const realUri = toFileUri(realRoot) + const virtUri = toFileUri(virtRoot) + if (realUri && virtUri && realUri !== virtUri) { + forwardRules.push({ + source: realUri, + target: virtUri, + targetSep: '/', + allowSubpath: true, + posixLeadingSlash: false, + }) + reverseTextRules.push({ + source: virtUri, + target: realUri, + targetSep: '/', + allowSubpath: true, + posixLeadingSlash: false, + }) + reverseJsonRules.push({ + source: virtUri, + target: realUri, + targetSep: '/', + allowSubpath: true, + posixLeadingSlash: false, + }) + } + + // 3. JSON double-escaped Windows paths (`C:\\Users\\...`) + const realJson = + callerIsWin || isWindowsStylePath(realRoot) ? toJsonEscapedWin(normalizePathSep(realRoot, '\\')) : realRoot + const virtJson = + osFamily === 'win32' || isWindowsStylePath(virtRoot) + ? toJsonEscapedWin(normalizePathSep(virtRoot, '\\')) + : virtRoot + if (callerIsWin || isWindowsStylePath(realRoot)) { + forwardRules.push({ + source: realJson, + target: osFamily === 'win32' ? virtJson : virtRoot, + targetSep: virtSep, + allowSubpath: true, + posixLeadingSlash: false, + jsonSource: true, + }) + } + reverseJsonRules.push({ + source: virtJson, + target: realRoot, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: virtJson.startsWith('/'), + }) + if (osFamily === 'win32') { + // Also reverse-map `C:\\Users\\...` if echoed inside plain text / markdown code blocks + reverseTextRules.push({ + source: virtJson, + target: callerIsWin ? realJson : realRoot, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: false, + jsonSource: true, + }) + } + + // 1 & 2. Native OS path + Forward-slash Windows path (`C:/...`) + const realCandidates = [realRoot] + if (realFwd !== realRoot) realCandidates.push(realFwd) + // Case-insensitive drive letter convenience (`c:\...`, `c:/...`) + if (/^[A-Z]:/.test(realRoot)) { + const lowRoot = `${realRoot[0].toLowerCase()}${realRoot.slice(1)}` + const lowFwd = `${realFwd[0].toLowerCase()}${realFwd.slice(1)}` + if (!realCandidates.includes(lowRoot)) realCandidates.push(lowRoot) + if (!realCandidates.includes(lowFwd)) realCandidates.push(lowFwd) + } + + for (const src of realCandidates) { + forwardRules.push({ + source: src, + target: virtRoot, + targetSep: virtSep, + allowSubpath: true, + posixLeadingSlash: src.startsWith('/'), + checkSystemGuard, + }) + } + + const virtCandidates = [virtRoot] + if (virtFwd !== virtRoot) virtCandidates.push(virtFwd) + for (const vSrc of virtCandidates) { + reverseTextRules.push({ + source: vSrc, + target: realRoot, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: vSrc.startsWith('/'), + }) + if (vSrc !== virtJson) { + reverseJsonRules.push({ + source: vSrc, + target: realRoot, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: vSrc.startsWith('/'), + }) + } + } + } + + // Priority 1: Exact `# Memory` directories & `MEMORY.md` subpaths (preserves trailing `\` on win32!) + for (let idx = 0; idx < callerMemoryBases.length; idx++) { + const cMemBase = callerMemoryBases[idx] + if (cMemBase !== virtualMemoryBase) { + addRootPair(cMemBase, virtualMemoryBase, { checkSystemGuard: false }) + if (idx > 0) { + // Only reverse-map back to the primary canonical `kI()` memory base + const legacyTarget = cMemBase + reverseTextRules.splice( + 0, + reverseTextRules.length, + ...reverseTextRules.filter((r) => !r.target.includes(legacyTarget)), + ) + reverseJsonRules.splice( + 0, + reverseJsonRules.length, + ...reverseJsonRules.filter((r) => !r.target.includes(legacyTarget)), + ) + } + } + } + + // Priority 2: Caller CWD <-> Virtual CWD (longest prefix before Home!) + if (callerCwd) { + addRootPair(callerCwd, virtualCwd, { checkSystemGuard: false }) + } + + // Priority 3: Caller Home <-> Virtual Home (`~/.claude`, global `CLAUDE.md`, etc.) + if (callerHome && (!callerCwd || toForwardSlash(callerHome) !== toForwardSlash(callerCwd))) { + addRootPair(callerHome, virtualHome, { checkSystemGuard: true }) + } + + // Priority 4: Managed `CLAUDE.md` policy directories across all 3 OSes + for (const srcManaged of Object.values(MANAGED_CLAUDE_DIRS)) { + if (srcManaged !== virtualManagedDir) { + addRootPair(srcManaged, virtualManagedDir, { checkSystemGuard: false }) + } + } + // Ensure reverse rules map virtualManagedDir back to callerManagedDir specifically + reverseTextRules.splice( + 0, + reverseTextRules.length, + ...reverseTextRules.filter( + (r) => !Object.values(MANAGED_CLAUDE_DIRS).some((m) => r.target.startsWith(m) && m !== callerManagedDir), + ), + ) + reverseJsonRules.splice( + 0, + reverseJsonRules.length, + ...reverseJsonRules.filter( + (r) => !Object.values(MANAGED_CLAUDE_DIRS).some((m) => r.target.startsWith(m) && m !== callerManagedDir), + ), + ) + + // Priority 5: Tilde `~/...` and `~\...` workspace expansion + if (callerTildeRel && virtualTildeRel && callerTildeRel !== virtualTildeRel) { + const cTildePosix = `~/${callerTildeRel}` + const cTildeWin = `~\\${callerTildeRel.replace(/\//g, '\\')}` + const vTildeNative = `~${virtSep}${virtualTildeRel.replace(/\//g, virtSep)}` + const vTildePosix = `~/${virtualTildeRel}` + const vTildeJson = osFamily === 'win32' ? toJsonEscapedWin(vTildeNative) : vTildeNative + const cTildeTarget = `~${callerSep}${callerTildeRel.replace(/\//g, callerSep)}` + + for (const cSrc of [cTildePosix, cTildeWin]) { + forwardRules.push({ + source: cSrc, + target: vTildeNative, + targetSep: virtSep, + allowSubpath: true, + posixLeadingSlash: false, + }) + } + for (const vSrc of new Set([vTildeNative, vTildePosix])) { + reverseTextRules.push({ + source: vSrc, + target: cTildeTarget, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: false, + }) + } + reverseJsonRules.push({ + source: vTildeJson, + target: cTildeTarget, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: false, + }) + if (vTildePosix !== vTildeJson) { + reverseJsonRules.push({ + source: vTildePosix, + target: cTildeTarget, + targetSep: callerSep, + allowSubpath: true, + posixLeadingSlash: false, + }) + } + } + + // Slug pairs (`kI()` + legacy) + const forwardSlugs = [] + for (const s of [callerSlug, callerSlugFwd, callerLegacySlug]) { + if (s && s.length >= 4 && s !== virtualSlug && !forwardSlugs.some((x) => x.from === s)) { + forwardSlugs.push({ from: s, to: virtualSlug }) + } + } + if ( + callerHomeSlug && + callerHomeSlug.length >= 5 && + callerHomeSlug !== virtualHomeSlug && + !forwardSlugs.some((x) => x.from === callerHomeSlug) + ) { + forwardSlugs.push({ from: callerHomeSlug, to: virtualHomeSlug }) + } + forwardSlugs.sort((a, b) => b.from.length - a.from.length) + + const reverseSlugs = [] + if (callerSlug && virtualSlug !== callerSlug) { + reverseSlugs.push({ from: virtualSlug, to: callerSlug }) + } + if (callerHomeSlug && virtualHomeSlug !== callerHomeSlug && virtualHomeSlug !== virtualSlug) { + reverseSlugs.push({ from: virtualHomeSlug, to: callerHomeSlug }) + } + reverseSlugs.sort((a, b) => b.from.length - a.from.length) + + // Collect SSE reverse anchor prefixes for chunk-boundary holding + const textAnchors = Array.from( + new Set([ + ...reverseTextRules.map((r) => r.source), + ...reverseSlugs.map((s) => s.from), + `${virtUser}@${virtHost}:`, + ]), + ).filter(Boolean) + + const jsonAnchors = Array.from( + new Set([ + ...reverseJsonRules.map((r) => r.source), + ...reverseSlugs.map((s) => s.from), + `${virtUser}@${virtHost}:`, + ]), + ).filter(Boolean) + + state = { + rawCwd, + rawHome, + callerIsWin, + callerSep, + callerCwd, + callerCwdFwd, + callerHome, + callerUser, + callerManagedDir, + virtualCwd, + virtualHome, + virtualSlug, + virtualMemoryDir, + forwardRules, + reverseTextRules, + reverseJsonRules, + forwardSlugs, + reverseSlugs, + textAnchors, + jsonAnchors, + } + return state + } + + function applySlugs(text, slugPairs) { + let out = text + for (const { from, to } of slugPairs) { + if (!out.includes(from)) continue + const re = new RegExp(`(?') && + !text.includes('Primary working directory:') && + !text.includes('Working directory:') + ) { + return text + } + + let out = text + const replaceEnvFields = (block) => { + let b = block + b = b.replace(/^(\s*-\s*Primary working directory:\s*)([^\r\n]+)$/gm, `$1${st.virtualCwd}`) + b = b.replace(/^(\s*(?:-\s*)?Working directory:\s*)([^\r\n<]+)$/gm, `$1${st.virtualCwd}`) + if (personaRewrite) { + b = b.replace(/^(\s*(?:-\s*)?Platform:\s*)([^\r\n<]+)$/gm, `$1${profile.platform_raw || osFamily}`) + b = b.replace( + /^(\s*(?:-\s*)?Shell:\s*)([^\r\n<]+)$/gm, + `$1${profile.shell || (osFamily === 'darwin' ? 'zsh' : 'bash')}`, + ) + if (profile.os_version) { + b = b.replace( + /^(\s*(?:-\s*)?OS Version:\s*)([^\r\n<]+?)(?=\s+-\s+(?:Locale|Language|Timezone):|$)/gm, + `$1${profile.os_version}`, + ) + } + if (profile.timezone) { + b = b.replace(/^(\s*(?:-\s*)?Timezone:\s*)([^\r\n<]+)$/gm, `$1${profile.timezone}`) + b = b.replace( + /(\s+-\s+Timezone:\s*)([^\r\n<]+?)(?=\s+-\s+(?:Locale|Language|OS Version|Platform|Shell):|$)/g, + `$1${profile.timezone}`, + ) + } + if (profile.locale) { + b = b.replace(/^(\s*(?:-\s*)?(?:Locale|Language):\s*)([^\r\n<]+)$/gm, `$1${profile.locale}`) + b = b.replace( + /(\s+-\s+(?:Locale|Language):\s*)([^\r\n<]+?)(?=\s+-\s+(?:Timezone|OS Version|Platform|Shell):|$)/g, + `$1${profile.locale}`, + ) + } + } + return b + } + + let matchedSection = false + if (out.includes('')) { + matchedSection = true + out = out.replace(/[\s\S]*?<\/env>/g, (envBlock) => replaceEnvFields(envBlock)) + } + if (out.includes('# Environment')) { + matchedSection = true + out = out.replace(/(#\s*Environment\r?\n[\s\S]*?)(?=\r?\n#\s+|\r?\n<\/|$)/g, (envBlock) => + replaceEnvFields(envBlock), + ) + } + if (!matchedSection) { + out = out.replace(/^(\s*-\s*Primary working directory:\s*)([^\r\n]+)$/gm, `$1${st.virtualCwd}`) + out = out.replace(/^(\s*(?:-\s*)?Working directory:\s*)([^\r\n<]+)$/gm, `$1${st.virtualCwd}`) + } + return out + } + + function rewriteLsLongOutput(text, st) { + if (typeof text !== 'string' || !text) return text + return text.replace(LS_LONG_LINE_RE, (whole, permAndLinks, owner, sp1, group, sp2) => { + if (owner === 'root' && st.callerUser !== 'root') return whole + if (SYSTEM_LS_OWNERS.has(owner) && owner !== st.callerUser) return whole + return `${permAndLinks}${lsOwner}${sp1}${lsGroup}${sp2}` + }) + } + + function rewriteTextForward(text, st, { isToolResult = false } = {}) { + if (typeof text !== 'string' || !text) return text + let out = rewriteEnvironmentSections(text, st) + + if (isToolResult) { + out = rewriteLsLongOutput(out, st) + } + + // Shell prompt anchor (`@:`) + if (st.callerUser && st.callerUser !== virtUser) { + const promptRe = new RegExp(`\\b${escapeRegExp(st.callerUser)}@([A-Za-z0-9._-]+):`, 'g') + out = out.replace(promptRe, (_, host) => { + callerPromptHost = host + return `${virtUser}@${virtHost}:` + }) + } + + // Shell `cd /d ` -> `cd ` when virtual OS is POSIX + if (osFamily !== 'win32') { + out = out.replace(/\bcd\s+\/d\s+/gi, 'cd ') + } + + for (const rule of st.forwardRules) { + out = replaceRootWithSubpath(out, rule, { + isJsonString: Boolean(rule.jsonSource), + callerCwdFwd: st.callerCwdFwd, + }) + } + + out = applySlugs(out, st.forwardSlugs) + return out + } + + function rewriteValueForward(val, st, opts) { + if (typeof val === 'string') return rewriteTextForward(val, st, opts) + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + val[i] = rewriteValueForward(val[i], st, opts) + } + return val + } + if (val && typeof val === 'object') { + for (const k of Object.keys(val)) { + val[k] = rewriteValueForward(val[k], st, opts) + } + } + return val + } + + function rewriteBlocksForward(blocks, st, { isToolResult = false } = {}) { + if (!Array.isArray(blocks)) return + for (const block of blocks) { + if (!block || typeof block !== 'object') continue + if (block.type === 'thinking' || block.type === 'redacted_thinking') continue + + if (block.type === 'text' && typeof block.text === 'string') { + block.text = rewriteTextForward(block.text, st, { isToolResult }) + } else if (block.type === 'tool_result') { + if (typeof block.content === 'string') { + block.content = rewriteTextForward(block.content, st, { isToolResult: true }) + } else if (Array.isArray(block.content)) { + rewriteBlocksForward(block.content, st, { isToolResult: true }) + } + } else if ((block.type === 'tool_use' || block.type === 'server_tool_use') && block.input) { + rewriteValueForward(block.input, st, { isToolResult: false }) + } + } + } + + function rewriteRequestBody(body, callOptions = {}) { + if (!body || typeof body !== 'object') return body + const st = ensureMappingState(body, callOptions.callerCwd || '') + + if (typeof body.system === 'string') { + body.system = rewriteTextForward(body.system, st) + } else if (Array.isArray(body.system)) { + for (const block of body.system) { + if (block && typeof block === 'object' && typeof block.text === 'string') { + block.text = rewriteTextForward(block.text, st) + } + } + } + + if (Array.isArray(body.messages)) { + for (const msg of body.messages) { + if (!msg || typeof msg !== 'object') continue + if (typeof msg.content === 'string') { + msg.content = rewriteTextForward(msg.content, st) + } else if (Array.isArray(msg.content)) { + rewriteBlocksForward(msg.content, st) + } + } + } + + return body + } + + function rewriteResponseInternal(text, { isJsonString = false, prevContext = '' } = {}) { + if (typeof text !== 'string' || !text) return text + const st = ensureMappingState() + let out = text + + const rules = isJsonString ? st.reverseJsonRules : st.reverseTextRules + for (const rule of rules) { + if (isJsonString && st.callerIsWin && rule.target.includes('\\')) { + out = replaceRootWithSubpath( + out, + { ...rule, target: toJsonEscapedWin(rule.target) }, + { isJsonString: true, callerCwdFwd: st.callerCwdFwd, prevContext }, + ) + } else { + out = replaceRootWithSubpath(out, rule, { + isJsonString: isJsonString || Boolean(rule.jsonSource), + callerCwdFwd: st.callerCwdFwd, + prevContext, + }) + } + } + + out = applySlugs(out, st.reverseSlugs) + + if (st.callerUser && out.includes(`${virtUser}@${virtHost}:`)) { + out = out.replaceAll(`${virtUser}@${virtHost}:`, `${st.callerUser}@${callerPromptHost}:`) + } + + return out + } + + function rewriteResponseText(text) { + return rewriteResponseInternal(text, { isJsonString: false }) + } + + function rewriteResponseValue(val) { + if (typeof val === 'string') return rewriteResponseText(val) + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + val[i] = rewriteResponseValue(val[i]) + } + return val + } + if (val && typeof val === 'object') { + for (const k of Object.keys(val)) { + val[k] = rewriteResponseValue(val[k]) + } + } + return val + } + + function rewriteResponseBlocks(blocks) { + if (!Array.isArray(blocks)) return + for (const block of blocks) { + if (!block || typeof block !== 'object') continue + if (block.type === 'thinking' || block.type === 'redacted_thinking') continue + + if (block.type === 'text' && typeof block.text === 'string') { + block.text = rewriteResponseText(block.text) + } else if ((block.type === 'tool_use' || block.type === 'server_tool_use') && block.input) { + rewriteResponseValue(block.input) + } else if (Array.isArray(block.content)) { + rewriteResponseBlocks(block.content) + } + } + } + + function rewriteResponseObject(msgObj) { + if (!msgObj || typeof msgObj !== 'object') return msgObj + if (msgObj.type === 'thinking' || msgObj.type === 'redacted_thinking') return msgObj + if (msgObj.type === 'text' && typeof msgObj.text === 'string') { + msgObj.text = rewriteResponseText(msgObj.text) + } else if ((msgObj.type === 'tool_use' || msgObj.type === 'server_tool_use') && msgObj.input) { + rewriteResponseValue(msgObj.input) + } + if (Array.isArray(msgObj.content)) { + rewriteResponseBlocks(msgObj.content) + } + return msgObj + } + + function hasPathStopAfterAnchor(rest, isJsonString) { + if (!rest) return false + if (!isJsonString) { + return /[\s"'`<>|*?()[\]{},;]/.test(rest) + } + for (let i = 0; i < rest.length; i++) { + const ch = rest[i] + if (/[\s"'`<>|*?()[\]{},;]/.test(ch)) return true + if (ch === '\\') { + if (i + 1 >= rest.length) return false // trailing single `\` — wait for next char + const next = rest[i + 1] + if (next === '\\') { + i += 1 // JSON `\\` path separator — continue scanning path + continue + } + return true // JSON escape like `\n`, `\t`, `\"` terminates path + } + } + return false + } + + function findSafeFlushCut(buf, anchors, isJsonString, prevContext = '') { + if (!buf || anchors.length === 0) return buf.length + const startScan = Math.max(0, buf.length - MAX_SSE_HOLD_CHARS) + for (let i = startScan; i < buf.length; i++) { + const tail = buf.slice(i) + // Case A: `tail` is an incomplete prefix of a virtual anchor + for (const anchor of anchors) { + if (tail.length < anchor.length && anchor.startsWith(tail)) { + if (anchor.startsWith('/') && isUrlPrefixAt(buf, i, prevContext)) continue + return i + } + } + // Case B: `tail` already matched an anchor, hold until path delimiter arrives + let longestAnchor = '' + for (const anchor of anchors) { + if (tail.startsWith(anchor) && anchor.length > longestAnchor.length) { + if (anchor.startsWith('/') && isUrlPrefixAt(buf, i, prevContext)) continue + longestAnchor = anchor + } + } + if (longestAnchor) { + const rest = tail.slice(longestAnchor.length) + if (!hasPathStopAfterAnchor(rest, isJsonString)) { + return i + } + } + } + return buf.length + } + + /** + * Create a chunk-boundary-safe SSE delta reverse mapper for `text_delta` + * and `input_json_delta.partial_json` streams. + */ + function createSseStreamRewriter() { + let textPending = '' + let jsonPending = '' + let textPrevTail = '' + let jsonPrevTail = '' + + return { + pushTextDelta(str) { + if (typeof str !== 'string') return '' + if (str === '' && textPending === '') return '' + const st = ensureMappingState() + textPending += str + const cut = findSafeFlushCut(textPending, st.textAnchors, false, textPrevTail) + if (cut <= 0) return '' + const ready = textPending.slice(0, cut) + textPending = textPending.slice(cut) + const prevContext = textPrevTail + textPrevTail = (textPrevTail + ready).slice(-16) + return rewriteResponseInternal(ready, { isJsonString: false, prevContext }) + }, + flushTextDelta() { + if (!textPending) { + textPrevTail = '' + return '' + } + const rest = textPending + const prevContext = textPrevTail + textPending = '' + textPrevTail = '' + return rewriteResponseInternal(rest, { isJsonString: false, prevContext }) + }, + pushInputJsonDelta(str) { + if (typeof str !== 'string') return '' + if (str === '' && jsonPending === '') return '' + const st = ensureMappingState() + jsonPending += str + const cut = findSafeFlushCut(jsonPending, st.jsonAnchors, true, jsonPrevTail) + if (cut <= 0) return '' + const ready = jsonPending.slice(0, cut) + jsonPending = jsonPending.slice(cut) + const prevContext = jsonPrevTail + jsonPrevTail = (jsonPrevTail + ready).slice(-16) + return rewriteResponseInternal(ready, { isJsonString: true, prevContext }) + }, + flushInputJsonDelta() { + if (!jsonPending) { + jsonPrevTail = '' + return '' + } + const rest = jsonPending + const prevContext = jsonPrevTail + jsonPending = '' + jsonPrevTail = '' + return rewriteResponseInternal(rest, { isJsonString: true, prevContext }) + }, + } + } + + // Eagerly initialize state if `options.callerCwd` or `options.callerHome` was passed + if (options.callerCwd || options.callerHome) { + ensureMappingState(null, options.callerCwd || '') + } + + return { + rewriteRequestBody, + rewriteResponseText, + rewriteResponseObject, + createSseStreamRewriter, + getMappingSnapshot() { + const st = ensureMappingState() + return { + callerCwd: st.callerCwd, + callerHome: st.callerHome, + virtualCwd: st.virtualCwd, + virtualHome: st.virtualHome, + virtualSlug: st.virtualSlug, + virtualMemoryDir: st.virtualMemoryDir, + } + }, + } +} diff --git a/src/lib/identity/git-persona.mjs b/src/lib/identity/git-persona.mjs new file mode 100644 index 000000000..a9ef77588 --- /dev/null +++ b/src/lib/identity/git-persona.mjs @@ -0,0 +1,323 @@ +/** + * Per-slot Git persona alignment & stateless/stateful Feistel commit SHA mapping. + * + * - Aligns `# gitStatus` `Git user:`, `Author:`, `Commit:`, non-Claude/non-Anthropic + * `Co-Authored-By:`, `user.name=`/`user.email=`, and `` `# userEmail` + * to `profile.git_persona` (`Name `). + * - Maps 7..40-hex commit SHAs in git contexts via a balanced `(2L, 2L)`-bit + * 8-round HMAC-SHA256 Feistel network (`feistelHex`, 100% bijective for any `L >= 7`), + * recording full & short prefix mappings so model responses restore exact caller SHAs. + * - Never touches `thinking` or `redacted_thinking` blocks (`thinking.signature` safe). + */ +import crypto from 'node:crypto' + +const FEISTEL_ROUNDS = 8 +const HEX_RE = /^[0-9a-fA-F]+$/ +const ALL_ZERO_HEX_RE = /^0+$/ +const CLAUDE_COAUTHOR_RE = /\b(?:claude|anthropic|noreply@anthropic\.com)\b/i + +function resolveSeedBuffer(seedHex) { + const clean = String(seedHex ?? '').trim() + if (/^[0-9a-fA-F]{64}$/.test(clean)) return Buffer.from(clean, 'hex') + return crypto + .createHash('sha256') + .update(`kin-git-feistel-seed-v1:${clean || 'default'}`) + .digest() +} + +function feistelRoundMask(keyBuf, hexLen, round, halfVal, halfBits, mask) { + const needBytes = Math.ceil(Number(halfBits) / 8) + let hexDigest = '' + let block = 0 + while (hexDigest.length < needBytes * 2) { + hexDigest += crypto + .createHmac('sha256', keyBuf) + .update(`feistel-hex-v1|L=${hexLen}|r=${round}|b=${block}|${halfVal.toString(16)}`) + .digest('hex') + block += 1 + } + return BigInt(`0x${hexDigest}`) & mask +} + +/** + * Balanced `(2L, 2L)`-bit Feistel cipher over arbitrary hex string length `L >= 7` + * (`4L` total bits = `2L` left bits + `2L` right bits; always even regardless of `L` parity). + * 100% bijective: `feistelHex(K, feistelHex(K, h, 'encrypt'), 'decrypt') === h`. + */ +export function feistelHex(seedHex, hexStr, direction = 'encrypt') { + if (typeof hexStr !== 'string') return hexStr + const len = hexStr.length + if (len < 7 || len > 128 || !HEX_RE.test(hexStr) || ALL_ZERO_HEX_RE.test(hexStr)) { + return hexStr + } + + const isUpper = hexStr === hexStr.toUpperCase() && /[A-F]/.test(hexStr) + const lower = hexStr.toLowerCase() + const keyBuf = resolveSeedBuffer(seedHex) + + const halfBits = BigInt(2 * len) + const mask = (1n << halfBits) - 1n + const full = BigInt(`0x${lower}`) + let left = (full >> halfBits) & mask + let right = full & mask + + if (direction === 'decrypt') { + for (let r = FEISTEL_ROUNDS - 1; r >= 0; r--) { + const f = feistelRoundMask(keyBuf, len, r, left, halfBits, mask) + const prevRight = left + const prevLeft = (right ^ f) & mask + left = prevLeft + right = prevRight + } + } else { + for (let r = 0; r < FEISTEL_ROUNDS; r++) { + const f = feistelRoundMask(keyBuf, len, r, right, halfBits, mask) + const nextLeft = right + const nextRight = (left ^ f) & mask + left = nextLeft + right = nextRight + } + } + + const combined = ((left << halfBits) | right).toString(16).padStart(len, '0') + return isUpper ? combined.toUpperCase() : combined +} + +/** + * Create a request/response Git persona & commit SHA rewriter bound to `profile`. + */ +export function createGitPersonaRewriter(profile = {}, options = {}) { + const persona = profile?.git_persona && typeof profile.git_persona === 'object' ? profile.git_persona : {} + const personaName = String(persona.name || 'Alex Chen').trim() + const personaEmail = String(persona.email || 'alex-chen-100@users.noreply.github.com').trim() + const seedHex = String(persona.feistel_seed || profile?.cwd_seed || 'kin-default-git-seed').trim() + const formattedAuthor = `${personaName} <${personaEmail}>` + const personaRewrite = options?.personaRewrite === true + + const forwardSha = new Map() + const reverseSha = new Map() + const reversePrefixSha = new Map() + + function mapShaForward(rawSha) { + if (typeof rawSha !== 'string' || rawSha.length < 7 || rawSha.length > 40) return rawSha + if (!HEX_RE.test(rawSha) || ALL_ZERO_HEX_RE.test(rawSha)) return rawSha + + const isUpper = rawSha === rawSha.toUpperCase() && /[A-F]/.test(rawSha) + const low = rawSha.toLowerCase() + + // Reuse if already mapped or if already in virtual space (idempotency) + if (reverseSha.has(low)) { + return isUpper ? low.toUpperCase() : low + } + let mapped = forwardSha.get(low) + if (!mapped) { + mapped = feistelHex(seedHex, low, 'encrypt') + forwardSha.set(low, mapped) + reverseSha.set(mapped, low) + if (low.length >= 12) { + for (let k = 7; k <= Math.min(12, low.length); k++) { + const vPrefix = mapped.slice(0, k) + const rPrefix = low.slice(0, k) + if (!reversePrefixSha.has(vPrefix)) { + reversePrefixSha.set(vPrefix, rPrefix) + } + } + } + } + return isUpper ? mapped.toUpperCase() : mapped + } + + function rewriteRecentCommitsSection(text) { + if (!text.includes('Recent commits:')) return text + const lines = text.split('\n') + let inRecent = false + for (let i = 0; i < lines.length; i++) { + const line = lines[i] + const trimmed = line.trim() + if (/^(?:[-*]\s+)?Recent commits:\s*$/i.test(trimmed)) { + inRecent = true + continue + } + if (!inRecent) continue + if ( + !trimmed || + trimmed.startsWith('#') || + trimmed.startsWith(' { + return `${lead}${mapShaForward(sha)}` + }) + } + return lines.join('\n') + } + + function rewriteGitTextForward(text) { + if (typeof text !== 'string' || !text) return text + let out = text + + if (personaRewrite) { + // 1. `` `# userEmail` alignment — preserve surrounding sentence wording + // (e.g. `The user's email address is `) instead of clobbering the entire line. + out = out.replace(/(#\s*userEmail\s*\r?\n)([^\r\n<]+)/g, (_whole, header, line) => { + const replaced = line.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, personaEmail) + if (replaced !== line) return `${header}${replaced}` + return `${header}${personaEmail}` + }) + + // 2. `# gitStatus` & git log/config user identity alignment (one-way, explicit opt-in only) + out = out.replace(/^(\s*(?:[-*]\s+)?Git user:\s*)([^\r\n]+)/gm, `$1${formattedAuthor}`) + out = out.replace(/^(\s*Author:\s*)([^<\r\n]*<[^>\r\n]+>)/gm, `$1${formattedAuthor}`) + out = out.replace(/^(\s*Commit:\s*)([^<\r\n]*<[^>\r\n]+>)/gm, `$1${formattedAuthor}`) + out = out.replace(/^(\s*Co-Authored-By:\s*)([^\r\n]+)/gim, (whole, prefix, val) => { + if (CLAUDE_COAUTHOR_RE.test(val)) return whole + return `${prefix}${formattedAuthor}` + }) + out = out.replace(/\b(user\.name=)([^\r\n\s]+)/g, (_, k) => `${k}${personaName}`) + out = out.replace(/\b(user\.email=)([^\r\n\s]+)/g, (_, k) => `${k}${personaEmail}`) + } + + // 3. `Recent commits:` lines + out = rewriteRecentCommitsSection(out) + + // 4. `commit ` / `Commit: ` (git log / show / cherry-pick / prose) + out = out.replace(/\b(commit:?\s+)([0-9a-fA-F]{7,40})(?![0-9a-fA-F-])/gi, (_, lead, sha) => { + return `${lead}${mapShaForward(sha)}` + }) + + // 5. `index ..` & git revision ranges `..` / `...` + out = out.replace( + /\b(index\s+)([0-9a-fA-F]{7,40})(\.\.)([0-9a-fA-F]{7,40})\b/g, + (_, lead, s1, dots, s2) => `${lead}${mapShaForward(s1)}${dots}${mapShaForward(s2)}`, + ) + out = out.replace( + /(? `${mapShaForward(s1)}${dots}${mapShaForward(s2)}`, + ) + + // 6. `[ <7-12hex>]` (git commit / rebase output) & `HEAD is now at ` + out = out.replace(/\[([^[\]\r\n]{1,120}?\s)([0-9a-fA-F]{7,12})\]/g, (whole, branchPart, sha) => { + if (!/[a-zA-Z]/.test(branchPart)) return whole + return `[${branchPart}${mapShaForward(sha)}]` + }) + out = out.replace(/\b(HEAD is now at\s+)([0-9a-fA-F]{7,40})\b/g, (_, lead, sha) => `${lead}${mapShaForward(sha)}`) + + return out + } + + function rewriteValueStrings(val, fn) { + if (typeof val === 'string') return fn(val) + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + val[i] = rewriteValueStrings(val[i], fn) + } + return val + } + if (val && typeof val === 'object') { + for (const k of Object.keys(val)) { + val[k] = rewriteValueStrings(val[k], fn) + } + } + return val + } + + function rewriteBlocksForward(blocks) { + if (!Array.isArray(blocks)) return + for (const block of blocks) { + if (!block || typeof block !== 'object') continue + if (block.type === 'thinking' || block.type === 'redacted_thinking') continue + + if (block.type === 'text' && typeof block.text === 'string') { + block.text = rewriteGitTextForward(block.text) + } else if (block.type === 'tool_result') { + if (typeof block.content === 'string') { + block.content = rewriteGitTextForward(block.content) + } else if (Array.isArray(block.content)) { + rewriteBlocksForward(block.content) + } + } else if ((block.type === 'tool_use' || block.type === 'server_tool_use') && block.input) { + rewriteValueStrings(block.input, rewriteGitTextForward) + } + } + } + + function rewriteRequestBody(body) { + if (!body || typeof body !== 'object') return body + + if (typeof body.system === 'string') { + body.system = rewriteGitTextForward(body.system) + } else if (Array.isArray(body.system)) { + for (const block of body.system) { + if (block && typeof block === 'object' && typeof block.text === 'string') { + block.text = rewriteGitTextForward(block.text) + } + } + } + + if (Array.isArray(body.messages)) { + for (const msg of body.messages) { + if (!msg || typeof msg !== 'object') continue + if (typeof msg.content === 'string') { + msg.content = rewriteGitTextForward(msg.content) + } else if (Array.isArray(msg.content)) { + rewriteBlocksForward(msg.content) + } + } + } + + return body + } + + function rewriteResponseText(text) { + if (typeof text !== 'string' || !text) return text + if (reverseSha.size === 0 && reversePrefixSha.size === 0) return text + + return text.replace(/(? { + const low = token.toLowerCase() + const orig = reverseSha.get(low) || reversePrefixSha.get(low) + if (!orig) return token + const isUpper = token === token.toUpperCase() && /[A-F]/.test(token) + return isUpper ? orig.toUpperCase() : orig + }) + } + + function rewriteResponseBlocks(blocks) { + if (!Array.isArray(blocks)) return + for (const block of blocks) { + if (!block || typeof block !== 'object') continue + if (block.type === 'thinking' || block.type === 'redacted_thinking') continue + + if (block.type === 'text' && typeof block.text === 'string') { + block.text = rewriteResponseText(block.text) + } else if ((block.type === 'tool_use' || block.type === 'server_tool_use') && block.input) { + rewriteValueStrings(block.input, rewriteResponseText) + } else if (Array.isArray(block.content)) { + rewriteResponseBlocks(block.content) + } + } + } + + function rewriteResponseObject(msgObj) { + if (!msgObj || typeof msgObj !== 'object') return msgObj + if (msgObj.type === 'thinking' || msgObj.type === 'redacted_thinking') return msgObj + if (msgObj.type === 'text' && typeof msgObj.text === 'string') { + msgObj.text = rewriteResponseText(msgObj.text) + } else if ((msgObj.type === 'tool_use' || msgObj.type === 'server_tool_use') && msgObj.input) { + rewriteValueStrings(msgObj.input, rewriteResponseText) + } + if (Array.isArray(msgObj.content)) { + rewriteResponseBlocks(msgObj.content) + } + return msgObj + } + + return { + rewriteRequestBody, + rewriteResponseText, + rewriteResponseObject, + mapCommitSha: mapShaForward, + } +} diff --git a/src/lib/identity/official-cc-system-2.1.241.mjs b/src/lib/identity/official-cc-system-2.1.241.mjs index bdce6c48a..ef26f1aa8 100644 --- a/src/lib/identity/official-cc-system-2.1.241.mjs +++ b/src/lib/identity/official-cc-system-2.1.241.mjs @@ -7,6 +7,7 @@ import { createRequire } from 'node:module' import { validTimezone } from '../core/timezone.mjs' import { DEFAULT_SLOT_HOME, slotHome } from '../vm/slot-identity.mjs' +import { nativeCcProjectSlug } from './slot-machine-profile.mjs' const require = createRequire(import.meta.url) const FIXTURE = require('./official-cc-system-2.1.241.json') @@ -310,14 +311,23 @@ export function buildOfficialEnvironmentSection(env = {}, { sourceTexts = [], co } export function buildOfficialContinuationText(env = {}, sourceTexts = [], { overwrite = false, vm = null } = {}) { - const cwd = sanitizeInboundCwd(env.cwd) || (vm ? slotHome(vm) : '') + const mp = + (vm?.machine_profile && typeof vm.machine_profile === 'object' ? vm.machine_profile : null) || + (env?.machineProfile && typeof env.machineProfile === 'object' ? env.machineProfile : null) + const sep = mp?.path_sep || (mp?.os_family === 'win32' ? '\\' : '/') + const mpDefaultCwd = mp?.work_root ? `${mp.work_root}${sep}workspace` : '' + const cwd = sanitizeInboundCwd(env.cwd) || mpDefaultCwd || (vm ? slotHome(vm) : '') let body = String(CRS_OFFICIAL_CONTINUATION || '') - const slug = officialProjectSlug(cwd) - if (cwd && slug) { - body = body.replaceAll( - '/home/kincli/.claude/projects/-home-kincli/memory/', - `${cwd}/.claude/projects/${slug}/memory/`, - ) + let memDir = typeof env.memoryDir === 'string' && env.memoryDir.trim() ? env.memoryDir.trim() : '' + if (!memDir && mp?.claude_config_dir && cwd) { + memDir = `${mp.claude_config_dir}${sep}projects${sep}${nativeCcProjectSlug(cwd)}${sep}memory${sep}` + } + if (!memDir && cwd) { + const slug = officialProjectSlug(cwd) + if (slug) memDir = `${cwd}/.claude/projects/${slug}/memory/` + } + if (memDir) { + body = body.replaceAll('/home/kincli/.claude/projects/-home-kincli/memory/', memDir) } const envSection = overwrite ? buildOverwriteEnvironmentSection({ ...env, cwd }) diff --git a/src/lib/identity/official-fingerprint.mjs b/src/lib/identity/official-fingerprint.mjs index 9fdc1f5c6..91ffba072 100644 --- a/src/lib/identity/official-fingerprint.mjs +++ b/src/lib/identity/official-fingerprint.mjs @@ -37,11 +37,25 @@ export function readOfficialCcIdentity(homeDir) { } } -export function reconcileFingerprint(prev = {}, official = {}) { +export function reconcileFingerprint(prev = {}, official = {}, { machineProfile = null } = {}) { const next = { ...(prev && typeof prev === 'object' ? prev : {}) } for (const key of STALE_FP_KEYS) delete next[key] const machine = official.machine_id || official.machineID || null const user = official.user_id || official.userID || null + const mp = machineProfile && typeof machineProfile === 'object' && machineProfile.device_id ? machineProfile : null + if (mp) { + // 3-OS machine_profile is SSOT: keep distinct device_id (userID) and machine_id, + // never overwrite device_id with machineID or clobber physical guest_machine_id. + next.device_id = mp.device_id + if (mp.machine_id) { + next.machine_id = mp.machine_id + } + delete next.official_machine_id + if (user || mp.device_id) next.official_user_id = user || mp.device_id + if (official.account_uuid) next.official_account_uuid = official.account_uuid + next.reconciled_at = new Date().toISOString() + return next + } if (machine) { next.device_id = machine next.official_machine_id = machine @@ -85,17 +99,27 @@ export function applyOfficialFingerprintToVm(vmPath, homeDir) { } const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) const prev = vm.fingerprint && typeof vm.fingerprint === 'object' ? vm.fingerprint : {} - const next = official.machine_id || official.user_id ? reconcileFingerprint(prev, official) : prev + const mp = + vm?.machine_profile && typeof vm.machine_profile === 'object' && vm.machine_profile.device_id + ? vm.machine_profile + : null + const next = + mp || official.machine_id || official.user_id ? reconcileFingerprint(prev, official, { machineProfile: mp }) : prev const identityPath = path.join(homeDir, '.claude', 'kin-identity.json') let identityWrote = false - if (fs.existsSync(identityPath) && official.machine_id) { + const targetDeviceId = mp ? mp.device_id : official.machine_id + if (fs.existsSync(identityPath) && targetDeviceId) { try { const ident = JSON.parse(fs.readFileSync(identityPath, 'utf8')) - if (ident.device_id !== official.machine_id) { - ident.device_id = official.machine_id - if (official.user_id) ident.user_id = official.user_id + if (ident.device_id !== targetDeviceId) { + ident.device_id = targetDeviceId + if (mp) { + ident.user_id = mp.device_id + } else { + if (official.user_id) ident.user_id = official.user_id + ident.source = OFFICIAL_IDENTITY_SOURCE + } if (official.account_uuid) ident.account_uuid = official.account_uuid - ident.source = OFFICIAL_IDENTITY_SOURCE ident.written_at = new Date().toISOString() atomicWriteJson(identityPath, ident) identityWrote = true @@ -129,7 +153,7 @@ export function applyOfficialFingerprintToVm(vmPath, homeDir) { wrote: changed || leftover.removed || identityWrote, official: !!(official.machine_id || official.user_id), leftover, - replaced_device: !!(official.machine_id && prev.device_id && prev.device_id !== official.machine_id), + replaced_device: !!(targetDeviceId && prev.device_id && prev.device_id !== targetDeviceId), } } diff --git a/src/lib/identity/official-profiles.mjs b/src/lib/identity/official-profiles.mjs index e1a7d6bb7..15cd4489b 100644 --- a/src/lib/identity/official-profiles.mjs +++ b/src/lib/identity/official-profiles.mjs @@ -169,18 +169,24 @@ const INTERACTIVE_GUIDANCE_BULLET = ' - If you need the user to run a shell command themselves (e.g., an interactive login like `gcloud auth login`), suggest they type `! ` in the prompt \u2014 the `!` prefix runs the command in this session so its output lands directly in the conversation.\n' /** `cli` keeps the interactive `!` bullet. `sdk-cli` is the --print capture and drops it. */ -export function renderOfficial303Guidance({ cwd = '', entrypoint = 'cli' } = {}) { +export function renderOfficial303Guidance({ cwd = '', memoryDir = '', entrypoint = 'cli' } = {}) { const home = sanitizeInboundCwd(cwd) const slug = officialProjectSlug(home) let text = OFFICIAL_303_GUIDANCE - if (home && slug) text = text.replace('{{memory_dir}}', `${home}/.claude/projects/${slug}/memory/`) + const resolvedMemoryDir = + typeof memoryDir === 'string' && memoryDir.trim() + ? memoryDir.trim() + : home && slug + ? `${home}/.claude/projects/${slug}/memory/` + : '' + if (resolvedMemoryDir) text = text.replace('{{memory_dir}}', resolvedMemoryDir) else text = text.replace(/\n# Memory\n[\s\S]*?(?=\n# Environment\n)/, '') if (entrypoint !== 'cli') text = text.replace(INTERACTIVE_GUIDANCE_BULLET, '') return text } -export function renderOfficial303MainPrompt({ cwd = '', entrypoint = 'cli' } = {}) { - return `${OFFICIAL_303_HARNESS}${renderOfficial303Guidance({ cwd, entrypoint })}` +export function renderOfficial303MainPrompt({ cwd = '', memoryDir = '', entrypoint = 'cli' } = {}) { + return `${OFFICIAL_303_HARNESS}${renderOfficial303Guidance({ cwd, memoryDir, entrypoint })}` } /** diff --git a/src/lib/identity/slot-computer.mjs b/src/lib/identity/slot-computer.mjs index 9e19bbf37..cd8133bec 100644 --- a/src/lib/identity/slot-computer.mjs +++ b/src/lib/identity/slot-computer.mjs @@ -557,11 +557,15 @@ export function syncSlotIdentityTimezoneAndPreset(projectRoot, vm, opts = {}) { if (!projectRoot || !vm?.id) { return { ok: false, skipped: true, reason: 'vm_required' } } - const zone = validTimezone(opts.timezone ?? vm?.timezone ?? vm?.fingerprint?.timezone) + const zone = validTimezone( + opts.timezone ?? vm?.timezone ?? vm?.fingerprint?.timezone ?? vm?.machine_profile?.timezone, + ) if (!zone || !SAFE_TZ_RE.test(zone) || zone.includes('..')) { return { ok: false, skipped: true, reason: 'invalid_timezone' } } - const locale = String(opts.locale ?? vm?.locale ?? vm?.fingerprint?.locale ?? '').trim() || STANDARD_LOCALE + const locale = + String(opts.locale ?? vm?.locale ?? vm?.fingerprint?.locale ?? vm?.machine_profile?.locale ?? '').trim() || + STANDARD_LOCALE const compDir = fingerprintDir(projectRoot, vm.id) const etcDir = slotComputerSystemEtcDir(projectRoot, vm.id) const presetDir = path.join(etcDir, 'claude-code', 'managed-settings.d') @@ -859,29 +863,34 @@ export function assignComputerFingerprint(projectRoot, vm, { taken, now, cpuVend return out } -/** Point the slot record at the computer. Does not touch device_id or legacy kincli slots. */ +/** Point the slot record at the computer. Does not touch device_id, machine_profile traits, or legacy kincli slots. */ export function rememberComputer(projectRoot, vm, computer) { if (!computer?.hostname || !vm?.id) return false const fp = vm.fingerprint && typeof vm.fingerprint === 'object' ? vm.fingerprint : {} + const hasMachineProfile = Boolean(vm.machine_profile && typeof vm.machine_profile === 'object') const nextUsername = !fp.username && !fp.hostname && !fp.device_id && isValidSlotUsername(computer.username) ? computer.username : '' const nextGuestIds = nextUsername && isKvmRuntime(vm) && isCustomKvmMode({ vm }) && !fp.guest_uid && !fp.guest_gid ? { guest_uid: 1000, guest_gid: 1000 } : {} + const hostnameMatches = hasMachineProfile + ? fp.computer_hostname === computer.hostname + : fp.hostname === computer.hostname const same = - fp.hostname === computer.hostname && + hostnameMatches && String(fp.guest_machine_id || '') .trim() .toLowerCase() === computer.guest_machine_id && !nextUsername if (same) return false - const patch = { - hostname: computer.hostname, + const buildPatch = (profilePresent) => ({ + ...(profilePresent ? { computer_hostname: computer.hostname } : { hostname: computer.hostname }), guest_machine_id: computer.guest_machine_id, ...(nextUsername ? { username: nextUsername } : {}), ...nextGuestIds, - } + }) + const patch = buildPatch(hasMachineProfile) vm.fingerprint = { ...fp, ...patch, @@ -889,9 +898,12 @@ export function rememberComputer(projectRoot, vm, computer) { const vmPath = path.join(projectRoot, 'vms', `${vm.id}.json`) if (!fs.existsSync(vmPath)) return true const disk = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const diskHasMachineProfile = Boolean( + hasMachineProfile || (disk.machine_profile && typeof disk.machine_profile === 'object'), + ) disk.fingerprint = { ...(disk.fingerprint && typeof disk.fingerprint === 'object' ? disk.fingerprint : {}), - ...patch, + ...buildPatch(diskHasMachineProfile), } disk.updated_at = new Date().toISOString() atomicWriteJson(vmPath, disk, { mode: 0o600 }) diff --git a/src/lib/identity/slot-machine-profile.mjs b/src/lib/identity/slot-machine-profile.mjs new file mode 100644 index 000000000..c8bbf9ce7 --- /dev/null +++ b/src/lib/identity/slot-machine-profile.mjs @@ -0,0 +1,1647 @@ +/** + * Single-slot 3-OS physical machine profile derivation & projection. + * + * Deterministically derives a realistic physical machine identity (`darwin`, + * `win32`, or `linux`) from the bound account (`accountUuid` + `email`), + * backed by curated real physical hardware catalogs (Apple Silicon / Intel Mac + * + 19 real OEM SMBIOS/DMI workstations & laptops), with domain-separated + * cryptographic seeds so accounts share zero cross-account correlation. + */ +import crypto from 'node:crypto' +import { US_TIMEZONES, validTimezone } from '../core/timezone.mjs' +import { getDb, isDbOpen } from '../db/database.mjs' +import { SettingsRepo } from '../db/repos/settings-repo.mjs' + +const HOSTNAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/ +const DEVICE_ID_RE = /^[0-9a-f]{64}$/i +const STANDARD_LOCALE = 'en_US.UTF-8' + +export const DISALLOWED_PERSONA_USERNAMES = Object.freeze( + new Set([ + 'root', + 'daemon', + 'bin', + 'sys', + 'nobody', + 'nogroup', + 'www-data', + 'ubuntu', + 'debian', + 'fedora', + 'arch', + 'alpine', + 'centos', + 'sudo', + 'wheel', + 'staff', + 'users', + 'docker', + 'kvm', + 'qemu', + 'kin', + 'kincli', + 'kinslot', + 'vm2api', + 'crag', + 'claude', + 'anthropic', + 'admin', + 'administrator', + 'user', + 'guest', + 'test', + 'tester', + 'demo', + 'default', + 'operator', + 'service', + 'sandbox', + 'container', + 'worker', + 'bot', + 'agent', + 'dev', + 'devbox', + ]), +) + +function toPosixLocale(locale) { + const raw = String(locale ?? '').trim() + if (!raw) return STANDARD_LOCALE + const base = raw.split('.')[0].split('@')[0].replace(/-/g, '_') + const parts = base.split('_').filter(Boolean) + if (parts.length >= 2 && /^[a-z]{2,3}$/i.test(parts[0]) && /^[a-z]{2}$/i.test(parts[1])) { + return `${parts[0].toLowerCase()}_${parts[1].toUpperCase()}.UTF-8` + } + return STANDARD_LOCALE +} + +export const SLOT_MACHINE_PROFILE_SCHEMA = 'kin-slot-machine-profile/1' +export const MACHINE_PROFILE_PEPPER_SETTINGS_KEY = 'slot_machine_profile_pepper' +export const OS_FAMILIES = Object.freeze(['darwin', 'win32', 'linux']) + +let cachedProcessPepper = null + +/** + * Resolve the per-installation HMAC pepper for machine-profile derivation. + * Priority: explicit `pepper` -> `KIN_MACHINE_PROFILE_PEPPER` env -> + * persisted 32-byte random hex in DB `settings` table (`slot_machine_profile_pepper`, + * matching `panel-2fa.mjs` challenge signing key) -> per-process random fallback + * when no DB is open (isolated unit tests). Never uses a hardcoded source constant. + */ +export function resolveMachineProfilePepper({ pepper = null, db = null, settingsRepo = null } = {}) { + const explicit = String(pepper ?? '').trim() + if (explicit) return explicit + const fromEnv = String(process.env.KIN_MACHINE_PROFILE_PEPPER ?? '').trim() + if (fromEnv) return fromEnv + const repo = settingsRepo || (db ? new SettingsRepo(db) : isDbOpen() ? new SettingsRepo(getDb()) : null) + if (repo) { + let secret = repo.get(MACHINE_PROFILE_PEPPER_SETTINGS_KEY, null) + if (typeof secret !== 'string' || secret.length < 32) { + secret = crypto.randomBytes(32).toString('hex') + repo.set(MACHINE_PROFILE_PEPPER_SETTINGS_KEY, secret) + } + return secret + } + if (!cachedProcessPepper) { + cachedProcessPepper = crypto.randomBytes(32).toString('hex') + } + return cachedProcessPepper +} + +export function resetCachedMachineProfilePepperForTest() { + cachedProcessPepper = null +} + +/** + * True when `vm` is a pre-existing legacy slot with a persisted fingerprint + * (`device_id` / `machine_id` / `hostname`) and neither an active 3-OS + * `machine_profile` nor an explicit 3-OS opt-in flag. + */ +export function isLegacySlotWithoutMachineProfile(vm) { + if (!vm || typeof vm !== 'object') return false + if (vm.machine_profile && typeof vm.machine_profile === 'object') return false + if (vm.machine_profile_opt_in === true || vm.machine_profile_mode === '3os') return false + const fp = vm.fingerprint && typeof vm.fingerprint === 'object' ? vm.fingerprint : null + if (!fp) return false + return Boolean( + (typeof fp.device_id === 'string' && fp.device_id.trim()) || + (typeof fp.machine_id === 'string' && fp.machine_id.trim()) || + (typeof fp.hostname === 'string' && fp.hostname.trim()), + ) +} + +/** + * Determine whether a slot may derive/update a 3-OS `machine_profile`. + * Pre-existing legacy slots preserve their original `device_id` and Linux + * fingerprint unless explicitly opted in (`machine_profile_opt_in: true`, + * `machine_profile_mode: '3os'`, or `options.optIn / options.forceReseed`). + */ +export function shouldEnable3OsMachineProfile(vm, options = {}) { + const opts = options && typeof options === 'object' ? options : {} + if (opts.optIn === true || opts.allowLegacyMigration === true || opts.forceReseed === true) { + return true + } + if (!vm || typeof vm !== 'object') return true + if (vm.machine_profile && typeof vm.machine_profile === 'object') return true + if (vm.machine_profile_opt_in === true || vm.machine_profile_mode === '3os') return true + return !isLegacySlotWithoutMachineProfile(vm) +} + +/** + * Explicit opt-in gate for one-way OS/Git persona text rewriting (`Platform:`, + * `OS Version:`, `Shell:`, `Author:`, `Co-Authored-By:`, `user.email=`, `# userEmail`). + * Default is OFF so user-visible tool/Bash/Git context is never mutated unexpectedly. + */ +export function isSlotPersonaRewriteEnabled({ routing = null, vm = null, profile = null } = {}) { + const envVal = String(process.env.KIN_SLOT_PERSONA_REWRITE ?? '') + .trim() + .toLowerCase() + if (envVal === '1' || envVal === 'true') return true + if (routing?.slot_persona_rewrite === true || routing?.compatibility?.slot_persona_rewrite === true) { + return true + } + const targetProfile = profile || vm?.machine_profile + if (vm?.slot_persona_rewrite === true || targetProfile?.persona_rewrite === true) { + return true + } + return false +} + +const APPLE_OUIS = Object.freeze(['00:3e:e1', '3c:22:fb', '8c:85:90', 'a8:51:ab', 'f0:18:98', 'bc:d0:74']) +const APPLE_SERIAL_CHARS = 'CDFGHJKLMNPQRSTVWXYZ0123456789' +const INTEL_MAC_PLANTS = Object.freeze(['C02', 'C07', 'F5K']) + +const DARWIN_TERMINALS = Object.freeze(['iTerm.app', 'Apple_Terminal', 'ghostty', 'vscode', 'cursor']) +const WIN32_TERMINALS = Object.freeze(['windows-terminal', 'vscode', 'cursor']) +const LINUX_TERMINALS = Object.freeze(['xterm-256color', 'gnome-terminal', 'vscode']) + +/** 15 real physical Apple hardware models (11 Apple Silicon arm64 + 4 Intel x64). */ +export const DARWIN_HARDWARE_CATALOG = Object.freeze([ + Object.freeze({ + model_id: 'Mac14,2', + model_name: 'MacBook Air (M2, 2022)', + family: 'MacBook Air', + arch: 'arm64', + cpu_model: 'Apple M2', + cpu_cores: 8, + memory_gb_options: [16, 24], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-AF89B6D9451A490B', + bios_version: '11881.81.4', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '23.6.0', os_pretty: 'macOS Sonoma 14.6.1' }, + ], + host_slug: 'macbook-air', + }), + Object.freeze({ + model_id: 'Mac14,9', + model_name: 'MacBook Pro (14-inch, 2023)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M2 Pro', + cpu_cores: 10, + memory_gb_options: [16, 32], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-B4831CEBD52A0C4C', + bios_version: '11881.81.4', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + ], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac14,10', + model_name: 'MacBook Pro (16-inch, 2023)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M2 Pro', + cpu_cores: 12, + memory_gb_options: [32], + root_disk: 'APPLE SSD AP1024Z', + board_name: 'Mac-53FDB3D8DB8CA971', + bios_version: '11881.81.4', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + ], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac14,3', + model_name: 'Mac mini (2023)', + family: 'Mac mini', + arch: 'arm64', + cpu_model: 'Apple M2', + cpu_cores: 8, + memory_gb_options: [16, 24], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-2E6FAB96566FE58C', + bios_version: '11881.81.4', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '23.6.0', os_pretty: 'macOS Sonoma 14.6.1' }, + ], + host_slug: 'mac-mini', + }), + Object.freeze({ + model_id: 'Mac14,12', + model_name: 'Mac mini (M2 Pro, 2023)', + family: 'Mac mini', + arch: 'arm64', + cpu_model: 'Apple M2 Pro', + cpu_cores: 10, + memory_gb_options: [32], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-BE088AF8C5EB4FA2', + bios_version: '11881.81.4', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + ], + host_slug: 'mac-mini', + }), + Object.freeze({ + model_id: 'Mac15,6', + model_name: 'MacBook Pro (14-inch, Nov 2023)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M3 Pro', + cpu_cores: 11, + memory_gb_options: [18, 36], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-4B682C642B45593E', + bios_version: '11881.101.1', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + ], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac15,7', + model_name: 'MacBook Pro (16-inch, Nov 2023)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M3 Pro', + cpu_cores: 12, + memory_gb_options: [18, 36], + root_disk: 'APPLE SSD AP1024Z', + board_name: 'Mac-7C00C82F94D5E3A1', + bios_version: '11881.101.1', + releases: [ + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + ], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac15,12', + model_name: 'MacBook Air (13-inch, M3, 2024)', + family: 'MacBook Air', + arch: 'arm64', + cpu_model: 'Apple M3', + cpu_cores: 8, + memory_gb_options: [16, 24], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-827FAC58A8FDFA22', + bios_version: '11881.101.1', + releases: [ + { kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }, + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + ], + host_slug: 'macbook-air', + }), + Object.freeze({ + model_id: 'Mac16,1', + model_name: 'MacBook Pro (14-inch, Nov 2024)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M4', + cpu_cores: 10, + memory_gb_options: [16, 24], + root_disk: 'APPLE SSD AP1024Z', + board_name: 'Mac-F60DEB81FF30ACF6', + bios_version: '11881.101.1', + releases: [{ kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac16,6', + model_name: 'MacBook Pro (14-inch, M4 Pro, Nov 2024)', + family: 'MacBook Pro', + arch: 'arm64', + cpu_model: 'Apple M4 Pro', + cpu_cores: 12, + memory_gb_options: [24, 48], + root_disk: 'APPLE SSD AP1024Z', + board_name: 'Mac-CC7F3D19B81A9C04', + bios_version: '11881.101.1', + releases: [{ kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'Mac16,10', + model_name: 'Mac mini (2024)', + family: 'Mac mini', + arch: 'arm64', + cpu_model: 'Apple M4', + cpu_cores: 10, + memory_gb_options: [16, 24], + root_disk: 'APPLE SSD AP0512Z', + board_name: 'Mac-3B09D3A1F84C2170', + bios_version: '11881.101.1', + releases: [{ kernel: '24.4.0', os_pretty: 'macOS Sequoia 15.4' }], + host_slug: 'mac-mini', + }), + Object.freeze({ + model_id: 'Macmini8,1', + model_name: 'Mac mini (2018)', + family: 'Mac mini', + arch: 'x64', + cpu_model: 'Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz', + cpu_cores: 6, + memory_gb_options: [16, 32], + root_disk: 'APPLE SSD AP0512M', + board_name: 'Mac-7BA5B2DFE22DDD8C', + bios_version: '1968.140.7.0.0', + model_codes: ['JYVX', 'JYW0', 'MMB6'], + releases: [ + { kernel: '23.5.0', os_pretty: 'macOS Sonoma 14.5' }, + { kernel: '23.6.0', os_pretty: 'macOS Sonoma 14.6.1' }, + ], + host_slug: 'mac-mini', + }), + Object.freeze({ + model_id: 'MacBookPro16,1', + model_name: 'MacBook Pro (16-inch, 2019)', + family: 'MacBook Pro', + arch: 'x64', + cpu_model: 'Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz', + cpu_cores: 6, + memory_gb_options: [16, 32], + root_disk: 'APPLE SSD AP0512N', + board_name: 'Mac-E1008331FDC96864', + bios_version: '2020.80.5.0.0', + model_codes: ['MD6N', 'MD6R', 'MD6P'], + releases: [ + { kernel: '23.6.0', os_pretty: 'macOS Sonoma 14.6.1' }, + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + ], + host_slug: 'macbook-pro', + }), + Object.freeze({ + model_id: 'iMac20,1', + model_name: 'iMac (Retina 5K, 27-inch, 2020)', + family: 'iMac', + arch: 'x64', + cpu_model: 'Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz', + cpu_cores: 8, + memory_gb_options: [32], + root_disk: 'APPLE SSD AP0512N', + board_name: 'Mac-CFF7D910A743CAAF', + bios_version: '2020.80.5.0.0', + model_codes: ['PN5T', 'PN5V', 'PN5W'], + releases: [ + { kernel: '23.6.0', os_pretty: 'macOS Sonoma 14.6.1' }, + { kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }, + ], + host_slug: 'imac', + }), + Object.freeze({ + model_id: 'MacPro7,1', + model_name: 'Mac Pro (2019)', + family: 'Mac Pro', + arch: 'x64', + cpu_model: 'Intel(R) Xeon(R) W-3235 CPU @ 3.30GHz', + cpu_cores: 12, + memory_gb_options: [32, 64], + root_disk: 'APPLE SSD AP1024N', + board_name: 'Mac-27AD2F918AE68F61', + bios_version: '2020.80.5.0.0', + model_codes: ['P7QM', 'P7QN', 'P7QP'], + releases: [{ kernel: '24.3.0', os_pretty: 'macOS Sequoia 15.3.1' }], + host_slug: 'mac-pro', + }), +]) + +/** 19 real physical OEM DMI hardware profiles shared by Windows and Linux workstations/laptops. */ +export const PC_DMI_CATALOG = Object.freeze([ + Object.freeze({ + manufacturer: 'Dell Inc.', + product: 'OptiPlex SFF 7010', + family: 'OptiPlex', + board_name: '0P03K2', + bios_version: '1.11.0', + cpu_vendor: 'intel', + cpu_model: '13th Gen Intel(R) Core(TM) i5-13500', + cpu_cores: 14, + memory_gb: 32, + root_disk: 'PC801 NVMe SK hynix 512GB', + gpu_model: 'Intel(R) UHD Graphics 770', + oui: 'f8:b1:56', + host_slug: 'optiplex', + }), + Object.freeze({ + manufacturer: 'Dell Inc.', + product: 'Precision 3660', + family: 'Precision', + board_name: '0PR88G', + bios_version: '2.12.1', + cpu_vendor: 'intel', + cpu_model: '13th Gen Intel(R) Core(TM) i7-13700K', + cpu_cores: 16, + memory_gb: 64, + root_disk: 'PM9A1 NVMe Samsung 1024GB', + gpu_model: 'NVIDIA GeForce RTX 4060', + oui: 'd0:94:66', + host_slug: 'precision', + }), + Object.freeze({ + manufacturer: 'Dell Inc.', + product: 'Latitude 5430', + family: 'Latitude', + board_name: '0RF8G2', + bios_version: '1.18.0', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i5-1245U', + cpu_cores: 10, + memory_gb: 16, + root_disk: 'PC SN740 NVMe WD 512GB', + gpu_model: 'Intel(R) Iris(R) Xe Graphics', + oui: 'b8:ce:f6', + host_slug: 'latitude', + }), + Object.freeze({ + manufacturer: 'Dell Inc.', + product: 'Inspiron 16 5625', + family: 'Inspiron', + board_name: '0TGNR3', + bios_version: '1.14.0', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 5825U with Radeon Graphics', + cpu_cores: 8, + memory_gb: 16, + root_disk: 'BC711 NVMe SK hynix 512GB', + gpu_model: 'AMD Radeon(TM) Graphics', + oui: 'f8:b1:56', + host_slug: 'inspiron', + }), + Object.freeze({ + manufacturer: 'Dell Inc.', + product: 'XPS 15 9530', + family: 'XPS', + board_name: '0PHRDD', + bios_version: '1.10.0', + cpu_vendor: 'intel', + cpu_model: '13th Gen Intel(R) Core(TM) i7-13700H', + cpu_cores: 14, + memory_gb: 32, + root_disk: 'PM9A1 NVMe Samsung 1024GB', + gpu_model: 'NVIDIA GeForce RTX 4060', + oui: 'd0:94:66', + host_slug: 'xps', + }), + Object.freeze({ + manufacturer: 'LENOVO', + product: '21CF003WUS', + version: 'ThinkPad T14 Gen 3', + family: 'ThinkPad T14 Gen 3', + board_name: '21CF003WUS', + bios_version: 'R23ET71W (1.47 )', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 PRO 6850U with Radeon Graphics', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'SKHynix_HFS001TEJ9X101N', + gpu_model: 'AMD Radeon(TM) 680M', + oui: '98:fa:9b', + host_slug: 'thinkpad', + }), + Object.freeze({ + manufacturer: 'LENOVO', + product: '21CB000DUS', + version: 'ThinkPad X1 Carbon Gen 10', + family: 'ThinkPad X1 Carbon Gen 10', + board_name: '21CB000DUS', + bios_version: 'N3AET79W (1.44 )', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i7-1260P', + cpu_cores: 12, + memory_gb: 16, + root_disk: 'SAMSUNG MZVL2512HCJQ-00BL7', + gpu_model: 'Intel(R) Iris(R) Xe Graphics', + oui: '6c:0b:84', + host_slug: 'thinkpad', + }), + Object.freeze({ + manufacturer: 'LENOVO', + product: '11TM001WUS', + version: 'ThinkCentre M90t Gen 3', + family: 'ThinkCentre M90t Gen 3', + board_name: '330B', + bios_version: 'M4CET48A', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i7-12700', + cpu_cores: 12, + memory_gb: 32, + root_disk: 'WD PC SN810 1TB', + gpu_model: 'Intel(R) UHD Graphics 770', + oui: '00:50:b6', + host_slug: 'thinkcentre', + }), + Object.freeze({ + manufacturer: 'LENOVO', + product: '30FA001BUS', + version: 'ThinkStation P360 Tiny', + family: 'ThinkStation P360 Tiny', + board_name: '3314', + bios_version: 'M43KT45A', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i7-12700T', + cpu_cores: 12, + memory_gb: 64, + root_disk: 'SAMSUNG MZVL21T0HCLR-00BL7', + gpu_model: 'Intel(R) UHD Graphics 770', + oui: '98:fa:9b', + host_slug: 'thinkstation', + }), + Object.freeze({ + manufacturer: 'LENOVO', + product: '21K9001JUS', + version: 'ThinkPad P16s Gen 2', + family: 'ThinkPad P16s Gen 2', + board_name: '21K9001JUS', + bios_version: 'R2FET55W (1.35 )', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 PRO 7840U w/ Radeon 780M Graphics', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'SAMSUNG MZVL21T0HCLR-00BL7', + gpu_model: 'AMD Radeon(TM) 780M', + oui: '6c:0b:84', + host_slug: 'thinkpad', + }), + Object.freeze({ + manufacturer: 'HP', + product: 'HP EliteBook 840 14 inch G9 Notebook PC', + family: 'EliteBook', + board_name: '896D', + bios_version: 'U75 Ver. 01.11.00', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i5-1235U', + cpu_cores: 10, + memory_gb: 16, + root_disk: 'WD PC SN810 512GB', + gpu_model: 'Intel(R) Iris(R) Xe Graphics', + oui: '3c:d9:2b', + host_slug: 'elitebook', + }), + Object.freeze({ + manufacturer: 'HP', + product: 'HP EliteBook 845 14 inch G9 Notebook PC', + family: 'EliteBook', + board_name: '8990', + bios_version: 'U82 Ver. 01.09.00', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 PRO 6850U with Radeon Graphics', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'KXG80ZNV512G KIOXIA', + gpu_model: 'AMD Radeon(TM) 680M', + oui: '80:ce:62', + host_slug: 'elitebook', + }), + Object.freeze({ + manufacturer: 'HP', + product: 'HP Z2 Mini G9 Workstation Desktop PC', + family: 'Z2 Mini', + board_name: '895E', + bios_version: 'U50 Ver. 02.07.00', + cpu_vendor: 'intel', + cpu_model: '13th Gen Intel(R) Core(TM) i7-13700', + cpu_cores: 16, + memory_gb: 64, + root_disk: 'SAMSUNG MZVL21T0HCLR-00BH1', + gpu_model: 'NVIDIA GeForce RTX 4060', + oui: 'ec:b1:d7', + host_slug: 'z2mini', + }), + Object.freeze({ + manufacturer: 'ASUSTeK COMPUTER INC.', + product: 'ProArt B650-CREATOR', + family: 'ProArt', + board_name: 'ProArt B650-CREATOR', + bios_version: '1904', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 9 7900X 12-Core Processor', + cpu_cores: 12, + memory_gb: 64, + root_disk: 'Samsung SSD 990 PRO 2TB', + gpu_model: 'NVIDIA GeForce RTX 4060', + oui: '04:42:1a', + host_slug: 'proart', + }), + Object.freeze({ + manufacturer: 'ASUSTeK COMPUTER INC.', + product: 'MINIPC PN53', + family: 'MINIPC', + board_name: 'PN53', + bios_version: '20700', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 7735HS with Radeon Graphics', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'CT1000P3PSSD8', + gpu_model: 'AMD Radeon(TM) 680M', + oui: '04:42:1a', + host_slug: 'pn53', + }), + Object.freeze({ + manufacturer: 'Micro-Star International Co., Ltd.', + product: 'PRO B660M-A DDR4 (MS-7D43)', + family: 'PRO', + board_name: 'PRO B660M-A DDR4 (MS-7D43)', + bios_version: '1.E0', + cpu_vendor: 'intel', + cpu_model: '12th Gen Intel(R) Core(TM) i5-12400F', + cpu_cores: 6, + memory_gb: 32, + root_disk: 'Samsung SSD 980 PRO 1TB', + gpu_model: 'NVIDIA GeForce RTX 3060', + oui: 'd8:bb:c1', + host_slug: 'msipro', + }), + Object.freeze({ + manufacturer: 'Gigabyte Technology Co., Ltd.', + product: 'B650 AORUS ELITE AX', + family: 'AORUS', + board_name: 'B650 AORUS ELITE AX', + bios_version: 'F21', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 7700X 8-Core Processor', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'Samsung SSD 990 PRO 1TB', + gpu_model: 'NVIDIA GeForce RTX 4060', + oui: '74:56:3c', + host_slug: 'aorus', + }), + Object.freeze({ + manufacturer: 'Intel(R) Client Systems', + product: 'NUC13ANHi7', + family: 'NUC', + board_name: 'NUC13ANBi7', + bios_version: 'ANRPL357.0029', + cpu_vendor: 'intel', + cpu_model: '13th Gen Intel(R) Core(TM) i7-1360P', + cpu_cores: 12, + memory_gb: 32, + root_disk: 'SOLIDIGM SSDPFKKW010X7', + gpu_model: 'Intel(R) Iris(R) Xe Graphics', + oui: '48:21:0b', + host_slug: 'nuc13', + }), + Object.freeze({ + manufacturer: 'Framework', + product: 'Laptop 13 (AMD Ryzen 7040Series)', + family: 'Laptop 13', + board_name: 'FRANMDCP07', + bios_version: '03.05', + cpu_vendor: 'amd', + cpu_model: 'AMD Ryzen 7 7840U w/ Radeon 780M Graphics', + cpu_cores: 8, + memory_gb: 32, + root_disk: 'WD_BLACK SN770 1TB', + gpu_model: 'AMD Radeon(TM) 780M', + oui: 'a8:7e:ea', + host_slug: 'framework', + }), +]) + +/** Exact Native CC `win32` `os.version() + " " + os.release()` releases (never `Windows_NT`). */ +export const WINDOWS_RELEASES = Object.freeze([ + Object.freeze({ + os_version: 'Windows 11 Pro 10.0.26100', + os_pretty: 'Windows 11 Pro 24H2', + display_version: '24H2', + kernel_release: '10.0.26100', + }), + Object.freeze({ + os_version: 'Windows 11 Pro 10.0.22631', + os_pretty: 'Windows 11 Pro 23H2', + display_version: '23H2', + kernel_release: '10.0.22631', + }), + Object.freeze({ + os_version: 'Windows 10 Pro 10.0.19045', + os_pretty: 'Windows 10 Pro 22H2', + display_version: '22H2', + kernel_release: '10.0.19045', + }), +]) + +/** 6 curated Linux desktop/workstation distributions and real kernels. */ +export const LINUX_DISTROS = Object.freeze([ + Object.freeze({ + id: 'ubuntu', + version_id: '24.04', + os_pretty: 'Ubuntu 24.04.2 LTS', + kernels: ['6.8.0-57-generic', '6.8.0-52-generic', '6.11.0-19-generic'], + package_managers: 'apt,npm', + }), + Object.freeze({ + id: 'ubuntu', + version_id: '22.04', + os_pretty: 'Ubuntu 22.04.5 LTS', + kernels: ['6.8.0-52-generic'], + package_managers: 'apt,npm', + }), + Object.freeze({ + id: 'debian', + version_id: '13', + os_pretty: 'Debian GNU/Linux 13 (trixie)', + kernels: ['6.12.21-amd64'], + package_managers: 'apt,npm', + }), + Object.freeze({ + id: 'debian', + version_id: '12', + os_pretty: 'Debian GNU/Linux 12 (bookworm)', + kernels: ['6.1.0-32-amd64', '6.1.0-31-amd64'], + package_managers: 'apt,npm', + }), + Object.freeze({ + id: 'fedora', + version_id: '41', + os_pretty: 'Fedora Linux 41 (Workstation Edition)', + kernels: ['6.11.10-300.fc41.x86_64', '6.11.8-300.fc41.x86_64'], + package_managers: 'dnf,npm', + }), + Object.freeze({ + id: 'arch', + version_id: '', + os_pretty: 'Arch Linux', + kernels: ['6.12.10-arch1-1', '6.13.1-arch1-1'], + package_managers: 'pacman,npm', + }), +]) + +/** 64 × 64 realistic human first/last names (4,096 combinations, zero reserved/batch prefixes). */ +const FIRST_NAMES = Object.freeze([ + 'Alex', + 'Evan', + 'Liam', + 'Noah', + 'Maya', + 'Claire', + 'Ethan', + 'Lucas', + 'Owen', + 'Caleb', + 'Nathan', + 'Ryan', + 'Jack', + 'henry', + 'Leo', + 'julian', + 'Isaac', + 'Miles', + 'Nolan', + 'Colin', + 'gavin', + 'grant', + 'Ian', + 'Sean', + 'Adam', + 'Aaron', + 'Eric', + 'Kevin', + 'Brian', + 'Jason', + 'Justin', + 'Brandon', + 'Elena', + 'Chloe', + 'Zoe', + 'Nora', + 'Hannah', + 'Grace', + 'Lily', + 'Leah', + 'Hazel', + 'iris', + 'Audrey', + 'Alice', + 'Ruby', + 'Eva', + 'Naomi', + 'eliza', + 'Tessa', + 'Nina', + 'vera', + 'Clara', + 'julia', + 'rachel', + 'sarah', + 'lauren', + 'megan', + 'emma', + 'olivia', + 'sophia', + 'ava', + 'mia', + 'logan', + 'mason', +]) + +const LAST_NAMES = Object.freeze([ + 'Chen', + 'Patel', + 'Kim', + 'Nguyen', + 'Park', + 'Lin', + 'Wu', + 'Shah', + 'Miller', + 'Davis', + 'Wilson', + 'Moore', + 'Taylor', + 'Thomas', + 'White', + 'Harris', + 'Martin', + 'Clark', + 'Lewis', + 'Walker', + 'Hall', + 'Young', + 'Allen', + 'Wright', + 'Scott', + 'Adams', + 'Baker', + 'Nelson', + 'Carter', + 'Mitchell', + 'Turner', + 'Phillips', + 'Campbell', + 'Parker', + 'Evans', + 'Edwards', + 'Collins', + 'Stewart', + 'Morris', + 'Reed', + 'Cook', + 'Morgan', + 'Bell', + 'Murphy', + 'Bailey', + 'Rivera', + 'Cooper', + 'Cox', + 'Howard', + 'Ward', + 'Brooks', + 'Bennett', + 'Gray', + 'Hayes', + 'Myers', + 'Ford', + 'Foster', + 'Graham', + 'Wallace', + 'Cole', + 'West', + 'Ellis', + 'Harper', + 'porter', +]) + +const SECRET_SEED_KEYS = Object.freeze(['tool_id_seed', 'session_id_seed', 'cwd_seed', 'account_key']) + +function titleCaseWord(word) { + const clean = String(word || '') + .trim() + .replace(/[^a-zA-Z]/g, '') + if (!clean) return 'Alex' + return clean[0].toUpperCase() + clean.slice(1).toLowerCase() +} + +function normalizeEmail(raw) { + const s = String(raw ?? '') + .trim() + .toLowerCase() + return s.includes('@') ? s : '' +} + +function normalizeAccountUuid(raw) { + return String(raw ?? '') + .trim() + .toLowerCase() +} + +function normalizeOsFamily(raw) { + const s = String(raw ?? '') + .trim() + .toLowerCase() + if (s === 'darwin' || s === 'macos' || s === 'mac') return 'darwin' + if (s === 'win32' || s === 'windows' || s === 'win') return 'win32' + if (s === 'linux') return 'linux' + return '' +} + +function hmacBuf(key, label) { + return crypto.createHmac('sha256', key).update(label).digest() +} + +function hmacHex(key, label) { + return hmacBuf(key, label).toString('hex') +} + +function pickFromBuffer(buf, offset, list) { + const n = buf.readUInt32BE(offset % (buf.length - 3)) + return list[n % list.length] +} + +function formatDeterministicUuidV4(buf) { + const bytes = Buffer.from(buf.subarray(0, 16)) + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + const hex = bytes.toString('hex') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}` +} + +function formatMacFromOui(oui, buf, offset = 0) { + const b1 = buf[offset % buf.length].toString(16).padStart(2, '0') + const b2 = buf[(offset + 1) % buf.length].toString(16).padStart(2, '0') + const b3 = buf[(offset + 2) % buf.length].toString(16).padStart(2, '0') + return `${String(oui).toLowerCase()}:${b1}:${b2}:${b3}` +} + +function deriveAppleSerial(hw, buf) { + if (hw.arch === 'x64') { + const plant = pickFromBuffer(buf, 0, INTEL_MAC_PLANTS) + const yw = `${APPLE_SERIAL_CHARS[buf[4] % APPLE_SERIAL_CHARS.length]}${APPLE_SERIAL_CHARS[buf[5] % APPLE_SERIAL_CHARS.length]}` + const uniq = `${APPLE_SERIAL_CHARS[buf[6] % APPLE_SERIAL_CHARS.length]}${APPLE_SERIAL_CHARS[buf[7] % APPLE_SERIAL_CHARS.length]}${APPLE_SERIAL_CHARS[buf[8] % APPLE_SERIAL_CHARS.length]}` + const modelCode = pickFromBuffer(buf, 12, hw.model_codes || ['MD6N']) + return `${plant}${yw}${uniq}${modelCode}` + } + let out = '' + for (let i = 0; i < 10; i++) { + out += APPLE_SERIAL_CHARS[buf[i] % APPLE_SERIAL_CHARS.length] + } + return out +} + +function derivePcSerial(buf) { + const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' + let out = '' + for (let i = 0; i < 8; i++) { + out += chars[buf[i] % chars.length] + } + return out +} + +function derivePersonaFromRootKey(rootKey) { + const buf = hmacBuf(rootKey, 'persona-identity-v1') + const first = titleCaseWord(FIRST_NAMES[buf.readUInt16BE(0) % FIRST_NAMES.length]) + const last = titleCaseWord(LAST_NAMES[buf.readUInt16BE(2) % LAST_NAMES.length]) + const firstLower = first.toLowerCase() + const lastLower = last.toLowerCase() + + let username = `${firstLower}${lastLower}`.slice(0, 14) + if (username.length < 3 || DISALLOWED_PERSONA_USERNAMES.has(username)) { + username = `${firstLower}${lastLower.slice(0, 4)}${(buf[4] % 89) + 10}`.slice(0, 15) + } + + const suffix = ((buf.readUInt16BE(6) % 900) + 100).toString(10) + const handle = `${firstLower}-${lastLower}-${suffix}` + return { + firstLower, + lastLower, + username, + fullName: `${first} ${last}`, + handle, + noreplyEmail: `${handle}@users.noreply.github.com`, + } +} + +function deriveHostname(osFamily, persona, hwSlug, buf) { + if (osFamily === 'darwin') { + const raw = `${persona.firstLower}s-${hwSlug}`.toLowerCase().replace(/[^a-z0-9-]/g, '-') + const hostname = HOSTNAME_RE.test(raw) ? raw : `${persona.firstLower}-mac` + const displayTitle = `${titleCaseWord(persona.firstLower)}s-${hwSlug + .split('-') + .map((w) => (w === 'imac' ? 'iMac' : titleCaseWord(w))) + .join('-')}.local` + return { hostname, display_hostname: displayTitle } + } + if (osFamily === 'win32') { + const chars = '0123456789abcdefghijklmnopqrstuvwxyz' + let tag = '' + for (let i = 0; i < 7; i++) tag += chars[buf[i] % chars.length] + return { + hostname: `desktop-${tag}`, + display_hostname: `DESKTOP-${tag.toUpperCase()}`, + } + } + const tag = buf.subarray(0, 2).toString('hex') + const candidate = `${persona.firstLower}-${hwSlug}-${tag}`.slice(0, 32).replace(/-+$/g, '') + const hostname = HOSTNAME_RE.test(candidate) ? candidate : `workstation-${tag}` + return { hostname, display_hostname: hostname } +} + +function javaHash(s) { + let h = 0 + for (let i = 0; i < s.length; i++) { + h = ((h << 5) - h + s.charCodeAt(i)) | 0 + } + return h +} + +/** + * Exact Native Claude Code `2.1.321` `kI(projectPath)` slug encoding: + * every non-ASCII-alphanumeric character maps 1:1 to `-` without collapsing `--` + * or prepending `-` to Windows drive letters (`C:\Users\u` -> `C--Users-u`). + */ +export function nativeCcProjectSlug(projectPath) { + const raw = String(projectPath ?? '') + const normalized = raw.replace(/[^a-zA-Z0-9]/g, '-') + return normalized.length <= 200 ? normalized : `${normalized.slice(0, 200)}-${Math.abs(javaHash(raw)).toString(36)}` +} + +function computeRootKey({ accountUuid, email, reseedNonce = '', fallbackSeed = '', pepper, db, settingsRepo }) { + const resolvedPepper = resolveMachineProfilePepper({ pepper, db, settingsRepo }) + const cleanUuid = normalizeAccountUuid(accountUuid) + const cleanEmail = normalizeEmail(email) + const cleanNonce = String(reseedNonce ?? '').trim() + const hasAccount = Boolean(cleanUuid || cleanEmail) + const material = hasAccount + ? `${cleanUuid}|${cleanEmail}|${cleanNonce}` + : `ephemeral|${String(fallbackSeed || 'unassigned-slot').trim()}|${cleanNonce}` + const rootKey = hmacBuf(resolvedPepper, material) + const accountKey = hmacHex(rootKey, 'account-key-v1') + return { + rootKey, + accountKey, + ephemeral: !hasAccount, + reseedNonce: cleanNonce, + } +} + +/** + * Derive a complete 3-OS physical slot machine profile deterministically from + * account identity (`accountUuid` / `email`), with zero cross-account correlation. + */ +export function deriveSlotMachineProfile(input = {}) { + const accountUuid = input.accountUuid ?? input.account_uuid ?? '' + const email = input.email ?? '' + const reseedNonce = input.reseedNonce ?? input.reseed_nonce ?? '' + const fallbackSeed = input.fallbackSeed ?? input.fallback_seed ?? input.vmId ?? input.vm_id ?? '' + const { rootKey, accountKey, ephemeral } = computeRootKey({ + accountUuid, + email, + reseedNonce, + fallbackSeed, + pepper: input.pepper, + db: input.db, + settingsRepo: input.settingsRepo, + }) + + const osBuf = hmacBuf(rootKey, 'os-family-select-v1') + const explicitOs = normalizeOsFamily(input.osFamily ?? input.os_family) + const os_family = explicitOs || OS_FAMILIES[osBuf.readUInt32BE(0) % OS_FAMILIES.length] + + const persona = derivePersonaFromRootKey(rootKey) + const hwBuf = hmacBuf(rootKey, 'hardware-select-v1') + const serialBuf = hmacBuf(rootKey, 'hardware-serial-v1') + const macBuf = hmacBuf(rootKey, 'network-mac-v1') + const uuidBuf = hmacBuf(rootKey, 'smbios-uuid-v1') + const envBuf = hmacBuf(rootKey, 'runtime-env-v1') + + const device_id = hmacHex(rootKey, 'device-id-user-id-v1') + const machine_id = hmacHex(rootKey, 'machine-id-v1') + const guest_machine_id = hmacHex(rootKey, 'guest-machine-id-v1').slice(0, 32) + const cwd_seed = hmacHex(rootKey, 'cwd-mapper-seed-v1') + const tool_id_seed = hmacHex(rootKey, 'tool-id-feistel-seed-v1') + const session_id_seed = hmacHex(rootKey, 'session-id-seed-v1') + const feistel_seed = hmacHex(rootKey, 'git-commit-feistel-seed-v1') + + const timezone = validTimezone(input.timezoneHint ?? input.timezone) || pickFromBuffer(envBuf, 0, US_TIMEZONES) + const locale = toPosixLocale(input.locale) || STANDARD_LOCALE + const hardware_uuid = formatDeterministicUuidV4(uuidBuf) + const observed_at = String(input.observedAt || input.now || '2026-11-09T15:53:28.000Z') + + let platform = 'linux' + let platform_raw = 'linux' + let deployment_environment = 'unknown-linux' + let arch = 'x64' + let stainless_os = 'Linux' + let stainless_arch = 'x64' + let os_id = 'ubuntu' + let os_pretty = 'Ubuntu 24.04.2 LTS' + let os_version = 'Linux 6.8.0-57-generic' + let kernel_release = '6.8.0-57-generic' + let linux_distro_id = '' + let linux_distro_version = '' + let linux_kernel = '' + let shell = 'bash' + let terminal = 'xterm-256color' + let package_managers = 'apt,npm' + let runtimes = 'node,python3' + let path_sep = '/' + let machine_home = `/home/${persona.username}` + let ls_group = persona.username + let hostnamePair = { hostname: `${persona.firstLower}-ws`, display_hostname: `${persona.firstLower}-ws` } + let hardware = null + + if (os_family === 'darwin') { + const hw = pickFromBuffer(hwBuf, 0, DARWIN_HARDWARE_CATALOG) + const rel = pickFromBuffer(hwBuf, 4, hw.releases) + const memGb = pickFromBuffer(hwBuf, 8, hw.memory_gb_options) + const oui = pickFromBuffer(macBuf, 0, APPLE_OUIS) + const mac = formatMacFromOui(oui, macBuf, 4) + const serial = deriveAppleSerial(hw, serialBuf) + + platform = 'macos' + platform_raw = 'darwin' + deployment_environment = 'unknown-darwin' + arch = hw.arch + stainless_os = 'MacOS' + stainless_arch = hw.arch + os_id = 'macos' + os_pretty = rel.os_pretty + kernel_release = rel.kernel + os_version = `Darwin ${rel.kernel}` + shell = 'zsh' + terminal = pickFromBuffer(envBuf, 4, DARWIN_TERMINALS) + package_managers = envBuf[8] % 2 === 0 ? 'homebrew,npm' : 'homebrew,npm,pnpm' + runtimes = 'node,python3' + path_sep = '/' + machine_home = `/Users/${persona.username}` + ls_group = 'staff' + hostnamePair = deriveHostname('darwin', persona, hw.host_slug, envBuf) + + hardware = { + observed_at, + model_id: hw.model_id, + model_name: hw.model_name, + manufacturer: 'Apple Inc.', + cpu_model: hw.cpu_model, + cpu_cores: hw.cpu_cores, + memory_gb: memGb, + memory_bytes: memGb * 1024 ** 3, + root_disk: hw.root_disk, + gpu_model: hw.arch === 'arm64' ? `${hw.cpu_model} GPU` : 'AMD Radeon Pro 5300M', + mac, + board_name: hw.board_name, + bios_version: hw.bios_version, + serial, + hardware_uuid, + machine_id: guest_machine_id, + shell, + package_managers, + runtimes, + dmi: { + manufacturer: 'Apple Inc.', + product: hw.model_id, + version: hw.model_name, + family: hw.family, + serial, + uuid: hardware_uuid, + }, + } + } else if (os_family === 'win32') { + const hw = pickFromBuffer(hwBuf, 0, PC_DMI_CATALOG) + const rel = pickFromBuffer(hwBuf, 4, WINDOWS_RELEASES) + const mac = formatMacFromOui(hw.oui, macBuf, 4) + const serial = derivePcSerial(serialBuf) + + platform = 'windows' + platform_raw = 'win32' + deployment_environment = 'unknown-win32' + arch = 'x64' + stainless_os = 'Windows' + stainless_arch = 'x64' + os_id = 'windows' + os_pretty = rel.os_pretty + kernel_release = rel.kernel_release + os_version = rel.os_version + shell = 'bash' + terminal = pickFromBuffer(envBuf, 4, WIN32_TERMINALS) + package_managers = envBuf[8] % 2 === 0 ? 'winget,npm' : 'npm,pnpm' + runtimes = 'node,python' + path_sep = '\\' + machine_home = `C:\\Users\\${persona.username}` + ls_group = persona.username + hostnamePair = deriveHostname('win32', persona, hw.host_slug, envBuf) + + hardware = { + observed_at, + model_id: hw.product, + model_name: hw.version || hw.product, + manufacturer: hw.manufacturer, + cpu_model: hw.cpu_model, + cpu_cores: hw.cpu_cores, + memory_gb: hw.memory_gb, + memory_bytes: hw.memory_gb * 1024 ** 3, + root_disk: hw.root_disk, + gpu_model: hw.gpu_model, + mac, + board_name: hw.board_name, + bios_version: hw.bios_version, + serial, + hardware_uuid, + machine_id: guest_machine_id, + shell, + package_managers, + runtimes, + dmi: { + manufacturer: hw.manufacturer, + product: hw.product, + version: hw.version || hw.bios_version, + family: hw.family, + serial, + uuid: hardware_uuid, + }, + } + } else { + const hw = pickFromBuffer(hwBuf, 0, PC_DMI_CATALOG) + const distro = pickFromBuffer(hwBuf, 4, LINUX_DISTROS) + const kernel = pickFromBuffer(hwBuf, 8, distro.kernels) + const mac = formatMacFromOui(hw.oui, macBuf, 4) + const serial = derivePcSerial(serialBuf) + + platform = 'linux' + platform_raw = 'linux' + deployment_environment = 'unknown-linux' + arch = 'x64' + stainless_os = 'Linux' + stainless_arch = 'x64' + os_id = distro.id + os_pretty = distro.os_pretty + kernel_release = kernel + os_version = `Linux ${kernel}` + linux_distro_id = distro.id + linux_distro_version = distro.version_id + linux_kernel = kernel + shell = 'bash' + terminal = pickFromBuffer(envBuf, 4, LINUX_TERMINALS) + package_managers = distro.package_managers + runtimes = 'node,python3' + path_sep = '/' + machine_home = `/home/${persona.username}` + ls_group = persona.username + hostnamePair = deriveHostname('linux', persona, hw.host_slug, envBuf) + + hardware = { + observed_at, + model_id: hw.product, + model_name: hw.version || hw.product, + manufacturer: hw.manufacturer, + cpu_model: hw.cpu_model, + cpu_cores: hw.cpu_cores, + memory_gb: hw.memory_gb, + memory_bytes: hw.memory_gb * 1024 ** 3, + root_disk: hw.root_disk, + gpu_model: hw.gpu_model, + mac, + board_name: hw.board_name, + bios_version: hw.bios_version, + serial, + hardware_uuid, + machine_id: guest_machine_id, + shell, + package_managers, + runtimes, + dmi: { + manufacturer: hw.manufacturer, + product: hw.product, + version: hw.version || hw.bios_version, + family: hw.family, + serial, + uuid: hardware_uuid, + }, + } + } + + const claude_config_dir = `${machine_home}${path_sep}.claude` + const work_root = `${machine_home}${path_sep}work` + + return { + schema: SLOT_MACHINE_PROFILE_SCHEMA, + ephemeral, + account_key: accountKey, + reseed_nonce: String(reseedNonce ?? '').trim(), + os_family, + platform, + platform_raw, + deployment_environment, + arch, + stainless_os, + stainless_arch, + os_id, + os_pretty, + os_version, + kernel_release, + ...(os_family === 'linux' + ? { + linux_distro_id, + linux_distro_version, + linux_kernel, + } + : {}), + node_version: 'v24.3.0', + shell, + terminal, + package_managers, + runtimes, + username: persona.username, + ls_owner: persona.username, + ls_group, + path_sep, + machine_home, + claude_config_dir, + work_root, + hostname: hostnamePair.hostname, + display_hostname: hostnamePair.display_hostname, + device_id, + machine_id, + guest_machine_id, + timezone, + locale, + cwd_seed, + tool_id_seed, + session_id_seed, + git_persona: { + name: persona.fullName, + email: persona.noreplyEmail, + handle: persona.handle, + feistel_seed, + }, + hardware, + } +} + +/** + * Strip internal HMAC/Feistel seeds and account binding tags before writing + * `machineProfile` to `credentials.json`, `run/kernel.json`, or public APIs. + */ +export function toPublicSlotMachineProfile(profile) { + if (!profile || typeof profile !== 'object') return null + const out = {} + for (const [key, value] of Object.entries(profile)) { + if (SECRET_SEED_KEYS.includes(key)) continue + if (profile.os_family !== 'linux' && key.startsWith('linux_')) continue + if (key === 'git_persona' && value && typeof value === 'object') { + const { feistel_seed: _feistel, ...publicPersona } = value + out.git_persona = { ...publicPersona } + continue + } + if (key === 'hardware' && value && typeof value === 'object') { + out.hardware = { + ...value, + ...(value.dmi && typeof value.dmi === 'object' ? { dmi: { ...value.dmi } } : {}), + } + continue + } + out[key] = value + } + return out +} + +/** + * Project a 3-OS `profile` onto `vm.fingerprint` WITHOUT ever overwriting + * `existingFingerprint.username` (which controls Docker/KVM Linux `/home/kincli` + * mount resolution in `slotHome(vm)`). + */ +export function projectProfileToVmFingerprint(profile, existingFingerprint = {}) { + const prev = existingFingerprint && typeof existingFingerprint === 'object' ? existingFingerprint : {} + if (!profile || typeof profile !== 'object') return { ...prev } + + const prevGuestMachineId = String(prev.guest_machine_id || '').trim() || null + const prevHardware = prev.hardware && typeof prev.hardware === 'object' ? prev.hardware : {} + const profileHardware = profile.hardware && typeof profile.hardware === 'object' ? profile.hardware : {} + const mergedHardware = { + ...prevHardware, + ...profileHardware, + ...(typeof prevHardware.mac === 'string' && prevHardware.mac.trim() ? { mac: prevHardware.mac.trim() } : {}), + } + + const next = { + ...prev, + persona_username: profile.username, + machine_home: profile.machine_home, + os_family: profile.os_family, + platform: profile.platform, + platform_raw: profile.platform_raw, + os_id: profile.os_id, + os_pretty: profile.os_pretty, + os_version: profile.os_version, + kernel_release: profile.kernel_release, + guest_kernel_release: profile.kernel_release, + arch: profile.arch, + stainless_os: profile.stainless_os, + stainless_arch: profile.stainless_arch, + hostname: profile.hostname, + display_hostname: profile.display_hostname, + device_id: profile.device_id, + machine_id: profile.machine_id, + guest_machine_id: prevGuestMachineId || profile.guest_machine_id || null, + timezone: profile.timezone, + locale: profile.locale, + shell: profile.shell, + terminal: profile.terminal, + package_managers: profile.package_managers, + runtimes: profile.runtimes, + hardware: mergedHardware, + } + + if (profile.os_family === 'linux') { + next.linux_kernel = profile.linux_kernel || profile.kernel_release + } else { + delete next.linux_kernel + } + + if (Object.hasOwn(prev, 'username')) { + next.username = prev.username + } else { + delete next.username + } + + return next +} + +/** + * Build 1P telemetry `identity` block strictly following Native CC `2.1.321` + * 3-OS wire rules (omitting `linux_*` keys whenever `os_family !== 'linux'`). + */ +export function buildTelemetryIdentityFromProfile(profile) { + if (!profile || typeof profile !== 'object') return {} + const osFamily = normalizeOsFamily(profile.os_family || profile.platform_raw) || 'linux' + const platform = osFamily === 'darwin' ? 'macos' : osFamily === 'win32' ? 'windows' : 'linux' + const platform_raw = osFamily + const deployment_environment = + osFamily === 'darwin' ? 'unknown-darwin' : osFamily === 'win32' ? 'unknown-win32' : 'unknown-linux' + + const identity = { + device_id: profile.device_id || '', + user_id: profile.device_id || '', + platform, + platform_raw, + deployment_environment, + arch: profile.arch || profile.stainless_arch || 'x64', + node_version: profile.node_version || 'v24.3.0', + is_running_with_bun: true, + shell: profile.shell || (osFamily === 'darwin' ? 'zsh' : 'bash'), + terminal: profile.terminal || 'unknown', + package_managers: profile.package_managers || '', + runtimes: profile.runtimes || 'node', + } + + if (osFamily === 'linux') { + if (profile.linux_distro_id) identity.linux_distro_id = profile.linux_distro_id + if (profile.linux_distro_version) identity.linux_distro_version = profile.linux_distro_version + if (profile.linux_kernel || profile.kernel_release) { + identity.linux_kernel = profile.linux_kernel || profile.kernel_release + } + } + + return identity +} + +function isCompleteProfile(profile) { + return Boolean( + profile && + typeof profile === 'object' && + profile.schema === SLOT_MACHINE_PROFILE_SCHEMA && + OS_FAMILIES.includes(profile.os_family) && + DEVICE_ID_RE.test(String(profile.device_id || '')) && + typeof profile.machine_home === 'string' && + profile.machine_home.length > 0 && + typeof profile.tool_id_seed === 'string' && + profile.tool_id_seed.length === 64 && + typeof profile.session_id_seed === 'string' && + profile.session_id_seed.length === 64 && + typeof profile.cwd_seed === 'string' && + profile.cwd_seed.length === 64 && + typeof profile.git_persona?.feistel_seed === 'string' && + profile.git_persona.feistel_seed.length === 64, + ) +} + +/** + * Ensure `vm.machine_profile` and `vm.fingerprint` are deterministically bound + * to the slot's current account (`accountHints` or `vm.oauth`), re-deriving + * immediately on account change, ephemeral promotion, or `options.forceReseed`. + */ +export function ensureVmSlotMachineProfile(vm, accountHints = {}, options = {}) { + const targetVm = vm && typeof vm === 'object' ? vm : {} + const hints = accountHints && typeof accountHints === 'object' ? accountHints : {} + const opts = options && typeof options === 'object' ? options : {} + + // Never lazily migrate/overwrite a pre-existing legacy slot's device_id or Linux + // fingerprint unless explicitly opted in (new slot, explicit opt-in, or forceReseed). + if (!shouldEnable3OsMachineProfile(targetVm, opts)) { + return { profile: null, changed: false, accountChanged: false, legacyPreserved: true } + } + + const existing = targetVm.machine_profile + const hintUuid = normalizeAccountUuid( + hints.accountUuid ?? hints.account_uuid ?? targetVm.account_uuid ?? targetVm.oauth?.account_uuid, + ) + const hintEmail = normalizeEmail(hints.email ?? targetVm.email ?? targetVm.oauth?.email) + const hasRealAccount = Boolean(hintUuid || hintEmail) + + const explicitNonce = opts.reseedNonce ?? opts.reseed_nonce ?? hints.reseedNonce ?? hints.reseed_nonce + const vmNonce = + typeof targetVm.profile_reseed_nonce === 'string' && targetVm.profile_reseed_nonce.trim() + ? targetVm.profile_reseed_nonce.trim() + : '' + let nextNonce = + explicitNonce !== undefined ? String(explicitNonce).trim() : String(existing?.reseed_nonce ?? vmNonce ?? '') + if (opts.forceReseed && explicitNonce === undefined) { + const prevNum = Number.parseInt(nextNonce || '0', 10) + nextNonce = Number.isFinite(prevNum) ? String(prevNum + 1) : `${nextNonce}-r1` + } + + const fallbackSeed = String(opts.fallbackSeed ?? hints.fallbackSeed ?? targetVm.id ?? targetVm.vmId ?? 'slot-default') + const expected = computeRootKey({ + accountUuid: hintUuid, + email: hintEmail, + reseedNonce: nextNonce, + fallbackSeed, + pepper: opts.pepper, + db: opts.db, + settingsRepo: opts.settingsRepo, + }) + + const complete = isCompleteProfile(existing) + const explicitOs = normalizeOsFamily(opts.osFamily ?? opts.os_family ?? hints.osFamily ?? hints.os_family) + + // Fast O(1) reuse on hot request path when profile is already complete and bound + if ( + complete && + !opts.forceReseed && + !explicitOs && + (!hasRealAccount || (!existing.ephemeral && existing.account_key === expected.accountKey)) + ) { + const tzOverride = validTimezone(hints.timezoneHint ?? hints.timezone) + let changed = false + let profile = existing + if (tzOverride && tzOverride !== existing.timezone) { + profile = { ...existing, timezone: tzOverride } + targetVm.machine_profile = profile + changed = true + } + if (changed || targetVm.fingerprint?.persona_username !== profile.username) { + targetVm.fingerprint = projectProfileToVmFingerprint(profile, targetVm.fingerprint) + } + return { profile, changed, accountChanged: false } + } + + const accountChanged = Boolean( + existing && + typeof existing === 'object' && + existing.account_key && + !existing.ephemeral && + hasRealAccount && + existing.account_key !== expected.accountKey, + ) + + const preservedOs = + explicitOs || + (!opts.forceReseed && !accountChanged && existing && !existing.ephemeral + ? normalizeOsFamily(existing.os_family) + : '') + + const profile = deriveSlotMachineProfile({ + accountUuid: hintUuid, + email: hintEmail, + reseedNonce: nextNonce, + fallbackSeed, + osFamily: preservedOs || undefined, + timezoneHint: hints.timezoneHint ?? hints.timezone ?? targetVm.timezone ?? existing?.timezone, + locale: hints.locale ?? targetVm.locale ?? existing?.locale, + pepper: opts.pepper, + db: opts.db, + settingsRepo: opts.settingsRepo, + now: opts.now, + }) + + targetVm.machine_profile = profile + targetVm.fingerprint = projectProfileToVmFingerprint(profile, targetVm.fingerprint) + + return { + profile, + changed: true, + accountChanged, + } +} diff --git a/src/lib/identity/system-prompt-spec.mjs b/src/lib/identity/system-prompt-spec.mjs index dca46182e..3e52d40c6 100644 --- a/src/lib/identity/system-prompt-spec.mjs +++ b/src/lib/identity/system-prompt-spec.mjs @@ -132,7 +132,13 @@ function emptyEnvironmentSections() { function resolveLocaleValue(slot, identity) { const raw = String( - slot?.locale || slot?.fingerprint?.locale || identity?.locale || identity?.fingerprint?.locale || '', + slot?.locale || + slot?.fingerprint?.locale || + slot?.machine_profile?.locale || + identity?.locale || + identity?.fingerprint?.locale || + identity?.machine_profile?.locale || + '', ).trim() return raw || null } @@ -141,8 +147,10 @@ function resolveTimezoneValue(slot, identity) { for (const candidate of [ slot?.timezone, slot?.fingerprint?.timezone, + slot?.machine_profile?.timezone, identity?.timezone, identity?.fingerprint?.timezone, + identity?.machine_profile?.timezone, ]) { const valid = validTimezone(candidate) if (valid) return valid diff --git a/src/lib/identity/tool-id-mapping.mjs b/src/lib/identity/tool-id-mapping.mjs new file mode 100644 index 000000000..a9d4c3426 --- /dev/null +++ b/src/lib/identity/tool-id-mapping.mjs @@ -0,0 +1,291 @@ +/** + * Stateless per-account format-preserving Feistel anonymization for Anthropic + * `tool_use.id` / `tool_result.tool_use_id` values (`toolu_01<22-base62>` and + * general `(srv)toolu_ [ch, BigInt(idx)])) +const BASE62_RADIX = 62n +const BASE62_HALF_LEN = 11 +const BASE62_HALF_MOD = BASE62_RADIX ** BigInt(BASE62_HALF_LEN) + +const TOKEN64_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-' +const TOKEN64_MAP = new Map(Array.from(TOKEN64_ALPHABET, (ch, idx) => [ch, BigInt(idx)])) +const TOKEN64_RADIX = 64n + +const FEISTEL_ROUNDS = 8 +const STANDARD_TOOLU_RE = /^((?:srv)?toolu_01)([0-9A-Za-z]{22})$/ +const FALLBACK_TOOLU_RE = /^((?:srv)?toolu_)([0-9A-Za-z_-]{4,128})$/ + +const RESULT_BLOCK_TYPES = new Set([ + 'tool_result', + 'mcp_tool_result', + 'web_search_tool_result', + 'code_execution_tool_result', + 'bash_code_execution_tool_result', + 'text_editor_code_execution_tool_result', + 'advisor_tool_result', +]) + +const USE_BLOCK_TYPES = new Set(['tool_use', 'server_tool_use', 'mcp_tool_use']) + +function seedBuffer(seed) { + const clean = String(seed ?? '').trim() + if (!clean) return null + if (/^[0-9a-fA-F]{64}$/.test(clean)) return Buffer.from(clean, 'hex') + return crypto.createHash('sha256').update(`kin-tool-seed-v1:${clean}`).digest() +} + +function decodeBase(str, charMap, radix) { + let acc = 0n + for (let i = 0; i < str.length; i++) { + const digit = charMap.get(str[i]) + if (digit === undefined) return null + acc = acc * radix + digit + } + return acc +} + +function encodeBase(num, len, alphabet, radix) { + const chars = new Array(len) + let cur = num + for (let i = len - 1; i >= 0; i--) { + const rem = Number(cur % radix) + chars[i] = alphabet[rem] + cur /= radix + } + return chars.join('') +} + +function roundPrf(keyBuf, domain, round, rightVal, mod) { + const digest = crypto + .createHmac('sha256', keyBuf) + .update(`${domain}|r=${round}|${rightVal.toString(16)}`) + .digest('hex') + return BigInt(`0x${digest}`) % mod +} + +function feistelModEncrypt(keyBuf, domain, left, right, mod) { + let l = left + let r = right + for (let round = 0; round < FEISTEL_ROUNDS; round++) { + const f = roundPrf(keyBuf, domain, round, r, mod) + const nextL = r + const nextR = (l + f) % mod + l = nextL + r = nextR + } + return [l, r] +} + +function feistelModDecrypt(keyBuf, domain, left, right, mod) { + let l = left + let r = right + for (let round = FEISTEL_ROUNDS - 1; round >= 0; round--) { + const f = roundPrf(keyBuf, domain, round, l, mod) + const prevR = l + const prevL = (((r - f) % mod) + mod) % mod + l = prevL + r = prevR + } + return [l, r] +} + +function transformToolUseId(toolIdSeed, rawId, direction) { + if (typeof rawId !== 'string' || !rawId) return rawId + const keyBuf = seedBuffer(toolIdSeed) + if (!keyBuf) return rawId + + const stdMatch = STANDARD_TOOLU_RE.exec(rawId) + if (stdMatch) { + const prefix = stdMatch[1] + const payload = stdMatch[2] + const left = decodeBase(payload.slice(0, BASE62_HALF_LEN), BASE62_MAP, BASE62_RADIX) + const right = decodeBase(payload.slice(BASE62_HALF_LEN), BASE62_MAP, BASE62_RADIX) + if (left === null || right === null) return rawId + const domain = `toolu01-b62-v1|${prefix}` + const [outL, outR] = + direction === 'encrypt' + ? feistelModEncrypt(keyBuf, domain, left, right, BASE62_HALF_MOD) + : feistelModDecrypt(keyBuf, domain, left, right, BASE62_HALF_MOD) + return `${prefix}${encodeBase(outL, BASE62_HALF_LEN, BASE62_ALPHABET, BASE62_RADIX)}${encodeBase( + outR, + BASE62_HALF_LEN, + BASE62_ALPHABET, + BASE62_RADIX, + )}` + } + + const fbMatch = FALLBACK_TOOLU_RE.exec(rawId) + if (!fbMatch) return rawId + + const prefix = fbMatch[1] + const payload = fbMatch[2] + const halfLen = Math.floor(payload.length / 2) + const hasOddTail = payload.length % 2 === 1 + const mod = TOKEN64_RADIX ** BigInt(halfLen) + const domain = `toolu-fb64-v1|${prefix}|len=${payload.length}` + + const leftStr = payload.slice(0, halfLen) + const rightStr = payload.slice(halfLen, halfLen * 2) + const left = decodeBase(leftStr, TOKEN64_MAP, TOKEN64_RADIX) + const right = decodeBase(rightStr, TOKEN64_MAP, TOKEN64_RADIX) + if (left === null || right === null) return rawId + + if (!hasOddTail) { + // Cycle-walk away from the `toolu_01<22-base62>` standard namespace whenever + // a 24-char fallback payload lands inside it, preserving a 100% bijection. + let curL = left + let curR = right + let candidate = '' + do { + ;[curL, curR] = + direction === 'encrypt' + ? feistelModEncrypt(keyBuf, domain, curL, curR, mod) + : feistelModDecrypt(keyBuf, domain, curL, curR, mod) + candidate = `${prefix}${encodeBase(curL, halfLen, TOKEN64_ALPHABET, TOKEN64_RADIX)}${encodeBase( + curR, + halfLen, + TOKEN64_ALPHABET, + TOKEN64_RADIX, + )}` + } while (payload.length === 24 && STANDARD_TOOLU_RE.test(candidate)) + return candidate + } + + const tailVal = TOKEN64_MAP.get(payload[payload.length - 1]) + if (tailVal === undefined) return rawId + + if (direction === 'encrypt') { + const [outL, outR] = feistelModEncrypt(keyBuf, domain, left, right, mod) + const shift = roundPrf(keyBuf, `${domain}|tail`, 0, outL * mod + outR, TOKEN64_RADIX) + const outTail = TOKEN64_ALPHABET[Number((tailVal + shift) % TOKEN64_RADIX)] + return `${prefix}${encodeBase(outL, halfLen, TOKEN64_ALPHABET, TOKEN64_RADIX)}${encodeBase( + outR, + halfLen, + TOKEN64_ALPHABET, + TOKEN64_RADIX, + )}${outTail}` + } + + const shift = roundPrf(keyBuf, `${domain}|tail`, 0, left * mod + right, TOKEN64_RADIX) + const origTail = TOKEN64_ALPHABET[Number((((tailVal - shift) % TOKEN64_RADIX) + TOKEN64_RADIX) % TOKEN64_RADIX)] + const [origL, origR] = feistelModDecrypt(keyBuf, domain, left, right, mod) + return `${prefix}${encodeBase(origL, halfLen, TOKEN64_ALPHABET, TOKEN64_RADIX)}${encodeBase( + origR, + halfLen, + TOKEN64_ALPHABET, + TOKEN64_RADIX, + )}${origTail}` +} + +/** Forward-map a canonical/client `tool_use.id` into the target account's ID space. */ +export function mapToolUseIdForAccount(toolIdSeed, toolId) { + return transformToolUseId(toolIdSeed, toolId, 'encrypt') +} + +/** Reverse-map an upstream account's `tool_use.id` back into canonical/client ID space. */ +export function unmapToolUseIdFromAccount(toolIdSeed, upstreamToolId) { + return transformToolUseId(toolIdSeed, upstreamToolId, 'decrypt') +} + +function rewriteContentBlocks(blocks, fn) { + if (!Array.isArray(blocks)) return + for (const block of blocks) { + if (!block || typeof block !== 'object') continue + const type = block.type + if (type === 'thinking' || type === 'redacted_thinking') continue + + if (USE_BLOCK_TYPES.has(type) && typeof block.id === 'string') { + block.id = fn(block.id) + } + if (RESULT_BLOCK_TYPES.has(type) && typeof block.tool_use_id === 'string') { + block.tool_use_id = fn(block.tool_use_id) + } + if (typeof block.parent_tool_use_id === 'string') { + block.parent_tool_use_id = fn(block.parent_tool_use_id) + } + if (Array.isArray(block.content)) { + rewriteContentBlocks(block.content, fn) + } + } +} + +/** + * Rewrite all `tool_use.id` and `tool_result.tool_use_id` references inside an + * inbound Anthropic request `body` into the target account's Feistel space. + * Never touches `thinking` or `redacted_thinking` blocks. + */ +export function rewriteRequestToolIds(body, toolIdSeed) { + if (!body || typeof body !== 'object' || !toolIdSeed) return body + if (Array.isArray(body.messages)) { + const fn = (id) => mapToolUseIdForAccount(toolIdSeed, id) + for (const msg of body.messages) { + if (!msg || typeof msg !== 'object') continue + if (typeof msg.parent_tool_use_id === 'string') { + msg.parent_tool_use_id = fn(msg.parent_tool_use_id) + } + if (Array.isArray(msg.content)) { + rewriteContentBlocks(msg.content, fn) + } + } + } + return body +} + +/** + * Reverse-map all `tool_use.id` (and nested `tool_use_id`) fields on an outbound + * Anthropic message object or individual content block back to client ID space. + * Never touches `thinking` or `redacted_thinking` blocks. + */ +export function rewriteResponseToolIds(messageObj, toolIdSeed) { + if (!messageObj || typeof messageObj !== 'object' || !toolIdSeed) return messageObj + const fn = (id) => unmapToolUseIdFromAccount(toolIdSeed, id) + if (messageObj.type === 'thinking' || messageObj.type === 'redacted_thinking') { + return messageObj + } + if (USE_BLOCK_TYPES.has(messageObj.type) && typeof messageObj.id === 'string') { + messageObj.id = fn(messageObj.id) + } + if (RESULT_BLOCK_TYPES.has(messageObj.type) && typeof messageObj.tool_use_id === 'string') { + messageObj.tool_use_id = fn(messageObj.tool_use_id) + } + if (Array.isArray(messageObj.content)) { + rewriteContentBlocks(messageObj.content, fn) + } + return messageObj +} + +/** + * Deterministically derive an account-and-slot-isolated lowercase RFC 4122 UUIDv4 + * for `X-Claude-Code-Session-Id` / `metadata.user_id.session_id`. + * + * Same `(sessionIdSeed, clientSessionId, vmId, slotEpoch)` yields an identical + * UUIDv4 across turns on the same slot; switching slots, changing accounts, or + * incrementing `slotEpoch` produces a completely uncorrelated UUIDv4. + */ +export function deriveAccountSlotSessionId({ sessionIdSeed, clientSessionId, vmId, slotEpoch = 0 } = {}) { + const keyBuf = seedBuffer(sessionIdSeed || 'kin-default-session-seed') + const cleanClient = String(clientSessionId ?? '').trim() || 'anonymous-session' + const cleanVm = String(vmId ?? '').trim() || 'default-vm' + const epoch = Number.isFinite(Number(slotEpoch)) ? Math.trunc(Number(slotEpoch)) : 0 + + const digest = crypto + .createHmac('sha256', keyBuf) + .update(`account-slot-session-v1|vm=${cleanVm}|epoch=${epoch}|client=${cleanClient}`) + .digest() + + const bytes = Buffer.from(digest.subarray(0, 16)) + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + const hex = bytes.toString('hex') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}` +} diff --git a/src/lib/identity/vm-identity.mjs b/src/lib/identity/vm-identity.mjs index e75cc7f27..9c334f3e9 100644 --- a/src/lib/identity/vm-identity.mjs +++ b/src/lib/identity/vm-identity.mjs @@ -69,14 +69,15 @@ export function loadVmIdentity(exec = {}) { const dirClaude = readJsonSafe(path.join(claudeDir, '.claude.json'), {}) || {} const claudeJson = { ...dirClaude, ...homeClaude } const fp = exec.vm?.fingerprint || {} + const mp = exec.vm?.machine_profile && typeof exec.vm.machine_profile === 'object' ? exec.vm.machine_profile : {} const oauth = exec.oauth || {} const seed = exec.seedPolicy || {} - const timezone = fp.timezone || exec.timezone || 'UTC' - const locale = fp.locale || exec.locale || 'en_US.UTF-8' - // Slot fingerprint is the only device source. Leftover ~/.claude.json + const timezone = fp.timezone || mp.timezone || exec.timezone || 'UTC' + const locale = fp.locale || mp.locale || exec.locale || 'en_US.UTF-8' + // Slot fingerprint / machine_profile is the only device source. Leftover ~/.claude.json // machineID is never outbound — guest collect also never rotates device_id. - const deviceId = outboundDeviceId(fp.device_id, exec.vmId || 'kin-vm') + const deviceId = outboundDeviceId(mp.device_id || fp.device_id, exec.vmId || 'kin-vm') const sessionId = fp.session_id || crypto.randomUUID() const slotCred = readSlotCredentialIdentity(home) // Slot worker credentials.json is the only credential location. @@ -112,28 +113,34 @@ export function loadVmIdentity(exec = {}) { cliVersion, timezone, locale, - kernel: fp.kernel_release || exec.kernel || null, + kernel: mp.kernel_release || fp.kernel_release || exec.kernel || null, email, accountUuid, orgUuid, deviceId, sessionId, - machineId: deviceId, - userId: claudeJson.userID || null, + machineId: mp.machine_id || fp.machine_id || deviceId, + userId: mp.device_id || claudeJson.userID || null, displayName: claudeJson.oauthAccount?.displayName || null, settings: settingsOut, metadataUserId: formatMetadataUserId({ deviceId, accountUuid, sessionId }), userAgent, + ...(mp && Object.keys(mp).length ? { machine_profile: mp } : {}), fingerprint: { - device_id: fp.device_id || deviceId, + device_id: mp.device_id || fp.device_id || deviceId, + ...(mp.machine_id || fp.machine_id ? { machine_id: mp.machine_id || fp.machine_id } : {}), session_id: sessionId, user_agent: userAgent, ...OFFICIAL_STAINLESS, + stainless_os: mp.stainless_os || fp.stainless_os || OFFICIAL_STAINLESS.stainless_os, + stainless_arch: mp.stainless_arch || fp.stainless_arch || OFFICIAL_STAINLESS.stainless_arch, x_app: 'cli', locale, timezone, - os_pretty: fp.os_pretty || exec.osPretty || null, - kernel_release: fp.kernel_release || exec.kernel || null, + os_pretty: mp.os_pretty || fp.os_pretty || exec.osPretty || null, + ...(mp.os_version || fp.os_version ? { os_version: mp.os_version || fp.os_version } : {}), + ...(mp.shell || fp.shell ? { shell: mp.shell || fp.shell } : {}), + kernel_release: mp.kernel_release || fp.kernel_release || exec.kernel || null, }, } } @@ -168,6 +175,7 @@ export function persistVmSettings(exec, identity) { timezone: identity.timezone, locale: identity.locale, fingerprint: exec.vm?.fingerprint || identity.fingerprint, + machine_profile: exec.vm?.machine_profile || null, }, exec.seedPolicy || {}, { diff --git a/src/lib/identity/workstation-profile.mjs b/src/lib/identity/workstation-profile.mjs index 95cd54065..7cd9b546e 100644 --- a/src/lib/identity/workstation-profile.mjs +++ b/src/lib/identity/workstation-profile.mjs @@ -122,14 +122,26 @@ export const KIN_SEED_SCHEMA = 'kin-seed/2' /** Slot seed sidecar. Catalog kernel + workstation image, never host release. */ export function buildKinSeedJson(vm = {}, pol = {}, extras = {}) { const ws = resolveWorkstationProfile(vm) + const mp = vm?.machine_profile && typeof vm.machine_profile === 'object' ? vm.machine_profile : null + const isNonLinuxProfile = Boolean(mp?.os_family && mp.os_family !== 'linux') return { schema: KIN_SEED_SCHEMA, pure: true, kernel: vm.kernel || extras.kernel || null, - linux_kernel: ws.linux_kernel, + ...(isNonLinuxProfile + ? {} + : { linux_kernel: mp?.os_family === 'linux' && mp.linux_kernel ? mp.linux_kernel : ws.linux_kernel }), workstation_sku: ws.sku, - timezone: vm.timezone || extras.timezone || null, - locale: vm.locale || extras.locale || null, + ...(mp + ? { + os_family: mp.os_family, + os_version: mp.os_version, + stainless_os: mp.stainless_os, + stainless_arch: mp.stainless_arch, + } + : {}), + timezone: vm.timezone || extras.timezone || mp?.timezone || null, + locale: vm.locale || extras.locale || mp?.locale || null, seed_policy: pol && typeof pol === 'object' ? pol : {}, telemetry: isTelemetryEnabled(pol) ? 'enabled' : 'disabled', cli_version: extras.cli_version || null, diff --git a/src/lib/oauth/import-commit.mjs b/src/lib/oauth/import-commit.mjs index 28e52c8ef..d22c13883 100644 --- a/src/lib/oauth/import-commit.mjs +++ b/src/lib/oauth/import-commit.mjs @@ -21,7 +21,19 @@ import { reloadSlotReady, startSlotReady } from '../vm/slot-runtime.mjs' import { resolveImportProxy } from '../vm/proxy-resolve.mjs' import { collectSlotIdentity } from '../vm/guest-identity.mjs' import { importWorkerCredential, syncClaudeClientCredentials } from '../transport/go-worker-client.mjs' -import { rustKernelHealth, rustKernelReachable, rustKernelBusy } from '../transport/rust-kernel-client.mjs' +import { + notifyRustKernelSlotReset, + rustKernelHealth, + rustKernelReachable, + rustKernelBusy, +} from '../transport/rust-kernel-client.mjs' +import { + requestKernelReloadWhenIdle, + restartRustKernel, + wrapHopInflight, + writeKernelConfig, +} from '../transport/rust-kernel-supervisor.mjs' +import { activeCragManifestForSlot, supportsSlotMachineProfileKernel } from '../vm/slot-engine.mjs' import { credentialModeFromOauth, canOfficialCc, @@ -30,10 +42,19 @@ import { } from './credential-mode.mjs' import { resolveAuthScheme } from './auth-scheme.mjs' import { flattenOauthIdentity, normalizeSubscriptionType } from './oauth-identity.mjs' -import { persistOauthToVm } from './oauth-credentials.mjs' +import { persistOauthToVm, syncSlotClaudeProfileJson, wipeSlotSessionAndTelemetryState } from './oauth-credentials.mjs' +import { ensureVmSlotMachineProfile, toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' +import { + fingerprintDir, + pushLiveSlotTimezoneSync, + syncSlotIdentityTimezoneAndPreset, +} from '../identity/slot-computer.mjs' +import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs' import { scheduleOfficialCcBootstrap } from './official-cc-bootstrap.mjs' import { normalizeTiers } from '../pool/quota-tiers.mjs' import { slotHost } from '../vm/slot-host.mjs' +import { slotHome } from '../vm/slot-identity.mjs' +import { writeSlotSeedFiles } from '../vm/slot-seed.mjs' import { finishOAuthImport } from './guest-oauth-helper.mjs' export function createImportCommit(ctx) { @@ -185,11 +206,60 @@ export function createImportCommit(ctx) { skipOfficialCc = false, fromNativeLogin = false, }) { + const prevUuid = existing.claude?.account_uuid || existing.account_uuid || null + const prevEmail = + String(existing.claude?.email || existing.email || '') + .trim() + .toLowerCase() || null const importedCredential = importedCredentialFromOauth(oauth, existing) + const nextUuid = importedCredential.account_uuid || null + const nextEmail = + String(importedCredential.email || '') + .trim() + .toLowerCase() || null + let accountSwapped = + !isCodexVm(existing) && + Boolean( + (prevUuid && nextUuid && prevUuid !== nextUuid) || + (!prevUuid && prevEmail && nextEmail && prevEmail !== nextEmail), + ) + if (!isCodexVm(existing) && (nextUuid || nextEmail || existing.machine_profile)) { + const profileEnsured = ensureVmSlotMachineProfile(existing, { + accountUuid: nextUuid, + email: importedCredential.email || null, + orgUuid: importedCredential.org_uuid || null, + timezoneHint: existing.proxy?.geo?.timezone || existing.timezone || undefined, + }) + if (profileEnsured.accountChanged && (prevUuid || prevEmail)) { + accountSwapped = true + } + if (profileEnsured.profile) { + if (profileEnsured.profile.timezone) existing.timezone = profileEnsured.profile.timezone + if (profileEnsured.profile.locale) existing.locale = profileEnsured.profile.locale + } + } + const slotDir = path.join(ctx.cfg.paths.project, 'vms', vmId) const workerExec = { vmId, vm: existing, - homeDir: path.join(ctx.cfg.paths.project, 'vms', vmId, 'cli-home'), + homeDir: path.join(slotDir, 'cli-home'), + } + if (accountSwapped) { + try { + await slotHost(existing).clearSlotState?.(existing, slotDir) + } catch (err) { + console.warn(`[import-commit] vm=${vmId} clearSlotState failed before swap: ${err?.message || err}`) + } + wipeSlotSessionAndTelemetryState(slotDir) + } + if (!isCodexVm(existing) && existing.machine_profile?.device_id) { + try { + syncSlotClaudeProfileJson(workerExec.homeDir, existing, { + workDir: '/run/kin/work', + containerHome: slotHome(existing), + wipeAccountState: accountSwapped, + }) + } catch {} } const bound = ctx.proxyPool?.getProxyForVm?.(vmId) if (bound) { @@ -200,13 +270,14 @@ export function createImportCommit(ctx) { } // The native login terminal has already authenticated in the live guest. Saving its grant // must not depend on (or restart) an inference worker that may still be waiting for credentials. + let liveKernelHealth = null if (!fromNativeLogin && process.env.KIN_CRS_MOCK !== '1') { const desynced = isSlotProxyDesynced(existing, ctx.cfg.paths.project) const legacy = slotHost(existing).native || isCodexVm(existing) - const health = legacy ? null : await rustKernelHealth(workerExec) + liveKernelHealth = legacy ? null : await rustKernelHealth(workerExec) const ready = legacy ? !!existing.runtime?.worker_socket && fs.existsSync(existing.runtime.worker_socket) - : rustKernelReachable(health) || rustKernelBusy(health) + : rustKernelReachable(liveKernelHealth) || rustKernelBusy(liveKernelHealth) if (desynced || !ready) { const prepare = desynced || legacy ? reloadSlotReady : startSlotReady const boot = await prepare(existing, ctx.cfg.paths.project, { @@ -227,8 +298,23 @@ export function createImportCommit(ctx) { existing.status = 'running' } workerExec.vm = existing + if (!legacy) { + liveKernelHealth = await rustKernelHealth(workerExec).catch(() => liveKernelHealth) + } } } + const activeCragManifest = !isCodexVm(existing) + ? activeCragManifestForSlot(ctx.cfg.paths.project, existing, workerExec.homeDir) + : null + const kernelSupportsMachineProfile = supportsSlotMachineProfileKernel({ + manifest: activeCragManifest, + capabilities: liveKernelHealth?.capabilities || existing?.workerStatus?.capabilities || null, + }) + if (!isCodexVm(existing) && existing.machine_profile && kernelSupportsMachineProfile) { + importedCredential.machineProfile = toPublicSlotMachineProfile(existing.machine_profile) + } else { + delete importedCredential.machineProfile + } const importCred = typeof ctx.importWorkerCredential === 'function' ? ctx.importWorkerCredential : importWorkerCredential let workerImport = null @@ -250,7 +336,6 @@ export function createImportCommit(ctx) { } } let warmupStarted = false - const prevUuid = existing.claude?.account_uuid || null await withVmLock(vmPath, () => { const mode = importedCredential.mode || credentialModeFromOauth(oauth) const setupRegistration = @@ -285,7 +370,6 @@ export function createImportCommit(ctx) { // refreshes (nextUuid === prevUuid) leave an in-flight warm-up untouched. try { const warmupCfg = normalizeWarmupConfig(routing()?.warmup) - const nextUuid = importedCredential.account_uuid || null if (warmupCfg.enabled && nextUuid && nextUuid !== prevUuid && !isCodexVm(existing)) { const vmRecord = JSON.parse(fs.readFileSync(vmPath, 'utf8')) startWarmup(vmRecord, { targetRpm: warmupCfg.target_rpm, config: warmupCfg }) @@ -308,6 +392,157 @@ export function createImportCommit(ctx) { Object.assign(existing, refreshed) } }) + workerExec.vm = existing + if (!isCodexVm(existing)) { + try { + syncSlotClaudeProfileJson(workerExec.homeDir, existing, { + workDir: '/run/kin/work', + containerHome: slotHome(existing), + wipeAccountState: false, + }) + } catch {} + if (existing.machine_profile?.timezone && existing.timezone !== existing.machine_profile.timezone) { + const patchedTz = patchVmRecord(ctx.cfg.paths.project, vmId, { + timezone: existing.machine_profile.timezone, + ...(existing.machine_profile.locale ? { locale: existing.machine_profile.locale } : {}), + }) + if (patchedTz) Object.assign(existing, patchedTz) + else { + existing.timezone = existing.machine_profile.timezone + if (existing.machine_profile.locale) existing.locale = existing.machine_profile.locale + } + } + if (fs.existsSync(fingerprintDir(ctx.cfg.paths.project, vmId))) { + try { + const tzSync = syncSlotIdentityTimezoneAndPreset(ctx.cfg.paths.project, existing, { + timezone: existing.timezone, + locale: existing.locale, + }) + if (tzSync?.ok && existing.status === 'running' && existing.runtime?.type === 'kvm') { + await pushLiveSlotTimezoneSync(ctx.cfg.paths.project, existing, tzSync).catch((err) => { + console.warn(`[import-commit] vm=${vmId} pushLiveSlotTimezoneSync failed: ${err?.message || err}`) + }) + } + } catch {} + } + try { + writeSlotSeedFiles(ctx.cfg.paths.project, existing, null, { routing: routing() }) + } catch {} + let kernelCfgRes = null + if (!slotHost(existing).native) { + try { + kernelCfgRes = writeKernelConfig(ctx.cfg.paths.project, existing, { + routing: routing(), + publish: !fromNativeLogin, + capabilities: liveKernelHealth?.capabilities || null, + }) + } catch {} + } + try { + await slotHost(existing).syncClaudeProfile?.(existing, slotDir) + } catch (err) { + console.warn(`[import-commit] vm=${vmId} syncClaudeProfile failed: ${err?.message || err}`) + } + if (accountSwapped) { + const nextSlotEpoch = (Number(existing.slot_epoch) || 0) + 1 + try { + const patchedEpoch = patchVmRecord(ctx.cfg.paths.project, vmId, { slot_epoch: nextSlotEpoch }) + if (patchedEpoch) Object.assign(existing, patchedEpoch) + else existing.slot_epoch = nextSlotEpoch + } catch { + existing.slot_epoch = nextSlotEpoch + } + try { + const rt = typeof ctx.getSchedulerRuntime === 'function' ? ctx.getSchedulerRuntime() : ctx.schedulerRuntime + await rt?.deleteSticky?.({ node_type: 'claude_vm', node_id: vmId }) + } catch {} + resetSlotSessionState({ vmId, accountId: prevUuid, vmEpoch: existing.slot_epoch }) + } + if (warmupStarted) { + try { + const rt = typeof ctx.getSchedulerRuntime === 'function' ? ctx.getSchedulerRuntime() : ctx.schedulerRuntime + await rt?.syncConfigNow?.('warmup_start') + } catch {} + } + const clientSync = await syncClaudeClientCredentials(workerExec) + if (!clientSync.ok) return clientSync + if (accountSwapped && !fromNativeLogin && process.env.KIN_CRS_MOCK !== '1') { + const notifyReset = + typeof ctx.notifyRustKernelSlotReset === 'function' + ? ctx.notifyRustKernelSlotReset + : notifyRustKernelSlotReset + const restartKernel = typeof ctx.restartRustKernel === 'function' ? ctx.restartRustKernel : restartRustKernel + try { + const resetRes = await notifyReset(workerExec, { wipeDisk: true, health: liveKernelHealth }) + if (resetRes && resetRes.ok === false && !resetRes.skipped) { + console.warn( + `[import-commit] vm=${vmId} notifyRustKernelSlotReset failed after account swap: ${resetRes.error || resetRes.status || 'unknown'}`, + ) + } + } catch (err) { + console.warn( + `[import-commit] vm=${vmId} notifyRustKernelSlotReset threw after account swap: ${err?.message || err}`, + ) + } + const needsKernelRestart = + (kernelSupportsMachineProfile || kernelCfgRes?.changed === true) && + (rustKernelReachable(liveKernelHealth) || rustKernelBusy(liveKernelHealth)) + if (needsKernelRestart) { + const activeJobs = + wrapHopInflight(workerExec) + + Number(liveKernelHealth?.active || 0) + + Number(liveKernelHealth?.waiting || 0) + + Number(liveKernelHealth?.active_requests || 0) + if (rustKernelBusy(liveKernelHealth) || activeJobs > 0) { + requestKernelReloadWhenIdle(workerExec, { + restart: (exec) => restartKernel(exec, { routing: routing(), timeoutMs: 15_000 }), + requireLiveKernel: true, + }) + } else { + try { + const restartRes = await restartKernel(workerExec, { routing: routing(), timeoutMs: 15_000 }) + if (restartRes && restartRes.ok === false) { + console.warn( + `[import-commit] vm=${vmId} restartRustKernel failed after account swap: ${restartRes.error || restartRes.reason || 'unknown'}`, + ) + } + } catch (err) { + console.warn( + `[import-commit] vm=${vmId} restartRustKernel threw after account swap: ${err?.message || err}`, + ) + } + } + } + } + const mode = importedCredential.mode || credentialModeFromOauth(oauth) + const ccUnsupported = !slotHost(existing).supports('official_cc') + const skipCc = skipOfficialCc || ccUnsupported || !canOfficialCc(mode) + const routingConfig = routing() + const officialCc = skipCc + ? { + scheduled: false, + reason: ccUnsupported + ? 'remote_unsupported' + : skipOfficialCc + ? 'credential_edit' + : 'credential_mode_unsupported', + } + : scheduleOfficialCcBootstrap({ + vmId, + projectRoot: ctx.cfg.paths.project, + force: true, + collectIdentity: collectSlotIdentity, + onStats: officialCcStatsHandler(vmId, existing.claude?.account_uuid), + routingFile: ctx.routingConfigPath, + config: routingConfig.official_cc, + credentialMode: mode, + incomingOauth: { + account_uuid: importedCredential.account_uuid, + email: importedCredential.email, + }, + }) + return { ok: true, existing, client_sync: clientSync, official_cc_bootstrap: officialCc } + } if (warmupStarted) { try { const rt = typeof ctx.getSchedulerRuntime === 'function' ? ctx.getSchedulerRuntime() : ctx.schedulerRuntime @@ -318,36 +553,12 @@ export function createImportCommit(ctx) { } const clientSync = await syncClaudeClientCredentials(workerExec) if (!clientSync.ok) return clientSync - const mode = importedCredential.mode || credentialModeFromOauth(oauth) - const ccUnsupported = !slotHost(existing).supports('official_cc') - const skipCc = skipOfficialCc || ccUnsupported || isCodexVm(existing) || !canOfficialCc(mode) - const routingConfig = routing() - const officialCc = skipCc - ? { - scheduled: false, - reason: ccUnsupported - ? 'remote_unsupported' - : isCodexVm(existing) - ? 'gpt_slot' - : skipOfficialCc - ? 'credential_edit' - : 'credential_mode_unsupported', - } - : scheduleOfficialCcBootstrap({ - vmId, - projectRoot: ctx.cfg.paths.project, - force: true, - collectIdentity: collectSlotIdentity, - onStats: officialCcStatsHandler(vmId, existing.claude?.account_uuid), - routingFile: ctx.routingConfigPath, - config: routingConfig.official_cc, - credentialMode: mode, - incomingOauth: { - account_uuid: importedCredential.account_uuid, - email: importedCredential.email, - }, - }) - return { ok: true, existing, client_sync: clientSync, official_cc_bootstrap: officialCc } + return { + ok: true, + existing, + client_sync: clientSync, + official_cc_bootstrap: { scheduled: false, reason: 'gpt_slot' }, + } } async function commitImportedOauth(options) { let result diff --git a/src/lib/oauth/oauth-credentials.mjs b/src/lib/oauth/oauth-credentials.mjs index 5d3a481a1..742095acb 100644 --- a/src/lib/oauth/oauth-credentials.mjs +++ b/src/lib/oauth/oauth-credentials.mjs @@ -23,6 +23,11 @@ import { import { resolveAuthScheme } from './auth-scheme.mjs' import { flattenOauthIdentity, normalizeSubscriptionType } from './oauth-identity.mjs' import { getCacheRuntime } from '../cache/index.mjs' +import { validTimezone } from '../core/timezone.mjs' +import { isCodexVm } from '../vm/vm-kind.mjs' +import { isHexDeviceId } from '../identity/workstation-fingerprint.mjs' +import { ensureVmSlotMachineProfile, toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' +import { activeCragManifestForSlot, supportsSlotMachineProfileKernel } from '../vm/slot-engine.mjs' const credentialRefreshTail = new Map() const OAUTH_DISTRIBUTED_LOCK_TTL_MS = 30_000 @@ -498,6 +503,9 @@ export function readWorkerCredentialFile(homeDir) { auth_scheme: doc.authScheme || doc.auth_scheme || oauth.authScheme || oauth.auth_scheme, }), _token_version: oauth.kinGeneration || oauth.kin_generation || null, + ...(doc.machineProfile || doc.machine_profile + ? { machine_profile: toPublicSlotMachineProfile(doc.machineProfile || doc.machine_profile) } + : {}), } } catch { return null @@ -634,14 +642,236 @@ export function sealWorkerCredentialFile(homeDir) { return { sealed: true, path: file } } +function resolveCredentialPublicMachineProfile(homeDir, cred = {}, options = {}) { + if (options?.includeMachineProfile === false) return null + const explicit = + options?.machineProfile || + options?.machine_profile || + options?.vm?.machine_profile || + options?.vm?.machineProfile || + cred?.machineProfile || + cred?.machine_profile + if (explicit && typeof explicit === 'object') { + return toPublicSlotMachineProfile(explicit) + } + const identity = flattenOauthIdentity(cred) + const nextUuid = String(identity.account_uuid || cred?.account_uuid || cred?.accountUuid || '').trim() + const file = slotWorkerCredentialPath(homeDir) + if (file) { + try { + const prevDoc = JSON.parse(fs.readFileSync(file, 'utf8')) + const prevUuid = String(prevDoc?.claudeAiOauth?.accountUuid || prevDoc?.claudeAiOauth?.account_uuid || '').trim() + const prevMp = prevDoc?.machineProfile || prevDoc?.machine_profile + if (prevMp && typeof prevMp === 'object' && (!nextUuid || !prevUuid || prevUuid === nextUuid)) { + return toPublicSlotMachineProfile(prevMp) + } + } catch {} + } + if (homeDir) { + try { + const slotDir = path.dirname(path.resolve(homeDir)) + const vmsDir = path.dirname(slotDir) + if (path.basename(homeDir) === 'cli-home' && path.basename(vmsDir) === 'vms') { + const projectRoot = path.dirname(vmsDir) + const vmPath = path.join(vmsDir, `${path.basename(slotDir)}.json`) + if (fs.existsSync(vmPath)) { + const vmDoc = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + const vmUuid = String(vmDoc?.claude?.account_uuid || vmDoc?.account_uuid || '').trim() + if (vmDoc?.machine_profile && (!nextUuid || !vmUuid || vmUuid === nextUuid)) { + const manifest = activeCragManifestForSlot(projectRoot, vmDoc, homeDir) + if ( + supportsSlotMachineProfileKernel({ + manifest, + capabilities: options?.capabilities || vmDoc?.workerStatus?.capabilities || null, + version: options?.cragVersion || null, + }) + ) { + return toPublicSlotMachineProfile(vmDoc.machine_profile) + } + } + } + } + } catch {} + } + return null +} + +/** + * Dual-write Claude CLI onboarding + 64-hex `userID` / `machineID` into both + * `cli-home/.claude.json` and `cli-home/.claude/.claude.json` without exposing email. + */ +export function syncSlotClaudeProfileJson( + homeDir, + vm = null, + { workDir = '/run/kin/work', containerHome = '/home/kincli', wipeAccountState = false } = {}, +) { + if (!homeDir) return { wrote: false } + assertSafeSlotCredentialPaths(homeDir) + const configDir = path.join(homeDir, '.claude') + const privileged = typeof process.getuid === 'function' && process.getuid() === 0 + const owner = runtimeFileOwner(vm) + const created = fs.mkdirSync(homeDir, { recursive: true, mode: 0o700 }) + const homeStat = lstatOrNull(homeDir) + if (!homeStat || homeStat.isSymbolicLink() || !homeStat.isDirectory()) return { wrote: false } + if (created && privileged) { + try { + fs.chownSync(homeDir, owner.uid, owner.gid) + } catch {} + } + fs.mkdirSync(configDir, { recursive: true, mode: 0o700 }) + if (privileged) { + try { + fs.chownSync(configDir, owner.uid, owner.gid) + } catch {} + } + const mp = vm?.machine_profile && typeof vm.machine_profile === 'object' ? vm.machine_profile : null + const deviceId = isHexDeviceId(mp?.device_id) + ? mp.device_id + : isHexDeviceId(vm?.fingerprint?.device_id) && mp + ? vm.fingerprint.device_id + : '' + const machineId = isHexDeviceId(mp?.machine_id) ? mp.machine_id : deviceId + const accountUuid = String(vm?.claude?.account_uuid || vm?.account_uuid || '').trim() + const orgUuid = String(vm?.claude?.org_uuid || vm?.org_uuid || '').trim() + + let wroteAny = false + for (const file of [path.join(configDir, '.claude.json'), path.join(homeDir, '.claude.json')]) { + let doc = {} + let mode = 0o600 + let uid = privileged ? owner.uid : null + let gid = privileged ? owner.gid : null + let existed = false + try { + const st = lstatOrNull(file) + if (st) { + if (st.isSymbolicLink() || !st.isFile()) continue + existed = true + mode = st.mode & 0o777 + uid = st.uid + gid = st.gid + const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue + doc = wipeAccountState ? {} : parsed + } + } catch { + continue + } + + let changed = !existed || wipeAccountState + if (doc.hasCompletedOnboarding !== true) { + doc.hasCompletedOnboarding = true + changed = true + } + if (typeof doc.theme !== 'string' || !doc.theme) { + doc.theme = 'dark' + changed = true + } + if (deviceId && doc.userID !== deviceId) { + doc.userID = deviceId + changed = true + } + if (machineId && doc.machineID !== machineId) { + doc.machineID = machineId + changed = true + } + if (accountUuid) { + const prevAcct = doc.oauthAccount && typeof doc.oauthAccount === 'object' ? doc.oauthAccount : {} + const nextAcct = { + accountUuid, + ...(orgUuid ? { organizationUuid: orgUuid } : {}), + } + if ( + prevAcct.accountUuid !== nextAcct.accountUuid || + (nextAcct.organizationUuid || '') !== (prevAcct.organizationUuid || '') || + Object.hasOwn(prevAcct, 'emailAddress') || + Object.hasOwn(prevAcct, 'email') + ) { + doc.oauthAccount = nextAcct + changed = true + } + } else if (wipeAccountState && Object.hasOwn(doc, 'oauthAccount')) { + delete doc.oauthAccount + changed = true + } + if (deleteSlotCredentialEmailKeys(doc)) changed = true + + if (!doc.projects || typeof doc.projects !== 'object' || Array.isArray(doc.projects)) { + doc.projects = {} + changed = true + } + for (const folder of [workDir, containerHome].filter(Boolean)) { + const current = doc.projects[folder] + const project = current && typeof current === 'object' && !Array.isArray(current) ? current : {} + if (project.hasTrustDialogAccepted === true) continue + project.hasTrustDialogAccepted = true + doc.projects[folder] = project + changed = true + } + if (!changed) continue + const tmp = `${file}.${process.pid}.${Date.now()}.tmp` + fs.writeFileSync(tmp, `${JSON.stringify(doc)}\n`, { mode }) + if (uid != null) { + try { + fs.chownSync(tmp, uid, gid) + } catch {} + } + fs.renameSync(tmp, file) + wroteAny = true + } + return { wrote: wroteAny, userID: deviceId || null, machineID: machineId || null } +} + +/** + * Wipe per-account session, continuation, and telemetry caches inside `vms/` + * on account swap, credential clear, or full slot reset. + */ +export function wipeSlotSessionAndTelemetryState(slotDir) { + if (!slotDir) return { removed: [] } + const slotStat = lstatOrNull(slotDir) + if (!slotStat || slotStat.isSymbolicLink() || !slotStat.isDirectory()) return { removed: [] } + const targets = [ + ['run', 'work', '.crag-sessions'], + ['cli-home', '.claude', 'crag-v3-continuations'], + ['run', 'telemetry-upload.log'], + ['cli-home', '.claude', 'telemetry'], + ] + const removed = [] + for (const segments of targets) { + let current = slotDir + let safe = true + for (let i = 0; i < segments.length - 1; i++) { + current = path.join(current, segments[i]) + const st = lstatOrNull(current) + if (!st) { + safe = false + break + } + if (st.isSymbolicLink() || !st.isDirectory()) { + safe = false + break + } + } + if (!safe) continue + const leaf = path.join(current, segments[segments.length - 1]) + const leafStat = lstatOrNull(leaf) + if (!leafStat) continue + try { + fs.rmSync(leaf, { recursive: true, force: true }) + removed.push(segments.join('/')) + } catch {} + } + return { removed } +} + /** Write slot credentials.json for imports and worker-owned credential updates. */ -export function writeWorkerCredentialFile(homeDir, cred) { +export function writeWorkerCredentialFile(homeDir, cred, options = {}) { const file = slotWorkerCredentialPath(homeDir) if (!file) return null assertSafeSlotCredentialPaths(homeDir) const mode = credentialModeFromOauth(cred) const authScheme = resolveAuthScheme({ mode, auth_scheme: cred.auth_scheme || cred.authScheme }) + const publicProfile = resolveCredentialPublicMachineProfile(homeDir, cred, options) if (mode === 'apikey') { const apiKey = String(cred.api_key || cred.apiKey || cred.access_token || cred.accessToken || '').trim() if (!apiKey) return null @@ -659,6 +889,7 @@ export function writeWorkerCredentialFile(homeDir, cred) { apiKey, baseUrl: cred.base_url || cred.baseUrl || 'https://api.anthropic.com', }, + ...(publicProfile ? { machineProfile: publicProfile } : {}), }, { mode: 0o600 }, ) @@ -710,7 +941,15 @@ export function writeWorkerCredentialFile(homeDir, cred) { try { if (fs.existsSync(file)) fs.chmodSync(file, 0o600) } catch {} - atomicWriteJson(file, { type: mode, authScheme, kinGeneration: generation, claudeAiOauth: oauth }, { mode: 0o600 }) + const doc = { + type: mode, + authScheme, + kinGeneration: generation, + claudeAiOauth: oauth, + ...(publicProfile ? { machineProfile: publicProfile } : {}), + } + stripSlotCredentialEmail(doc) + atomicWriteJson(file, doc, { mode: 0o600 }) chownSlotCredentialFile(homeDir, file) sealSlotCredentialFile(file) ensureOfficialCredentialLink(homeDir, { adoptOfficial: false }) @@ -822,7 +1061,11 @@ export function restoreScheduleAfterLiveCredential(vm, { operatorImport = false return vm } -export function persistOauthToVm(vmPath, cred, { acceptLiveGrant = false, operatorImport = false } = {}) { +export function persistOauthToVm( + vmPath, + cred, + { acceptLiveGrant = false, operatorImport = false, forceReseed = false } = {}, +) { if (!vmPath || !fs.existsSync(vmPath)) return null const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) const prev = vm.claude || {} @@ -882,6 +1125,20 @@ export function persistOauthToVm(vmPath, cred, { acceptLiveGrant = false, operat } else { delete vm.claude.has_api_key } + if (!isCodexVm(vm) && (vm.claude.account_uuid || vm.claude.email || vm.machine_profile)) { + const { profile } = ensureVmSlotMachineProfile( + vm, + { + accountUuid: vm.claude.account_uuid || null, + email: vm.claude.email || null, + orgUuid: vm.claude.org_uuid || null, + timezoneHint: validTimezone(vm.proxy?.geo?.timezone) || validTimezone(vm.timezone) || undefined, + }, + { forceReseed }, + ) + if (!vm.timezone && profile?.timezone) vm.timezone = profile.timezone + if (!vm.locale && profile?.locale) vm.locale = profile.locale + } if (prevRevoked && !rotated && !acceptLiveGrant) { vm.claude.refresh_error = prev.refresh_error || 'oauth_revoked' vm.updated_at = new Date().toISOString() diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 3887bda36..0ef08f6e6 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -257,8 +257,23 @@ import { peekInterceptSession, prepareCachePrefix, } from './cache-prefix.mjs' -import { createIssuedToolReplay } from './issued-tool-replay.mjs' +import { createIssuedToolReplay, getSlotSessionEpoch } from './issued-tool-replay.mjs' import { createIssuedToolStream } from './issued-tool-stream.mjs' +import { + ensureVmSlotMachineProfile, + isSlotPersonaRewriteEnabled, + shouldEnable3OsMachineProfile, +} from '../identity/slot-machine-profile.mjs' +import { createCwdMapper } from '../identity/cwd-mapping.mjs' +import { createGitPersonaRewriter } from '../identity/git-persona.mjs' +import { + deriveAccountSlotSessionId, + mapToolUseIdForAccount, + rewriteRequestToolIds, + rewriteResponseToolIds, + unmapToolUseIdFromAccount, +} from '../identity/tool-id-mapping.mjs' +import { isCodexVm } from '../vm/vm-kind.mjs' import { createRequestBodyContext, shallowCopyBody } from './request-body-context.mjs' import { jevInterceptSessionCache } from './jev-intercept.mjs' import { ensureClaudeWebSearch, shouldInjectClaudeWebSearch } from './web-search.mjs' @@ -276,10 +291,11 @@ import { thinkingSignatureKey, thinkingOwners as defaultThinkingOwners, } from '../pool/thinking-owner.mjs' -import { getVm, listVms } from '../vm/vm-registry.mjs' +import { getVm, listVms, patchVmRecord } from '../vm/vm-registry.mjs' import { credentialModeFromOauth, isApiKeyMode } from '../oauth/credential-mode.mjs' import { prepareAnthropicRequest, + mapThinkingBlocks, rewriteToolNames, scrubUpstreamClientBody, toStandardAnthropicBody, @@ -342,6 +358,336 @@ export function createResponseHeadersSseFilter() { } } +function cloneAttemptJson(value) { + if (!value || typeof value !== 'object') return value + try { + return structuredClone(value) + } catch { + return JSON.parse(JSON.stringify(value)) + } +} + +function mapSafeguardToolIds(body, toolIdSeed) { + if (!body || typeof body !== 'object' || !toolIdSeed || !Array.isArray(body.safeguards)) return + for (const guard of body.safeguards) { + const turns = guard?.classifier_context?.prior_turn_context + if (!Array.isArray(turns)) continue + for (const turn of turns) { + if (Array.isArray(turn?.tool_use_ids)) { + turn.tool_use_ids = turn.tool_use_ids.map((id) => + typeof id === 'string' ? mapToolUseIdForAccount(toolIdSeed, id) : id, + ) + } + } + } +} + +function unmapSafeguardResultToolIds(results, toolIdSeed) { + if (!Array.isArray(results) || !toolIdSeed) return results + return results.map((guard) => { + const uses = guard?.status?.tool_uses + if (!uses || typeof uses !== 'object' || Array.isArray(uses)) return guard + const mappedUses = {} + for (const [rawId, entry] of Object.entries(uses)) { + mappedUses[unmapToolUseIdFromAccount(toolIdSeed, rawId)] = entry + } + return { + ...guard, + status: { + ...guard.status, + tool_uses: mappedUses, + }, + } + }) +} + +function applySlotForwardPipeline(rawBody, { profile, callerCwd = null, personaRewrite = false } = {}) { + if (!profile || !rawBody || typeof rawBody !== 'object') { + return { body: rawBody, slotRewrite: null, mappedCallerCwd: callerCwd } + } + const attemptBody = cloneAttemptJson(rawBody) + const cwdMapper = createCwdMapper(profile, { ...(callerCwd ? { callerCwd } : {}), personaRewrite }) + const gitRewriter = createGitPersonaRewriter(profile, { personaRewrite }) + cwdMapper.rewriteRequestBody(attemptBody, { callerCwd }) + gitRewriter.rewriteRequestBody(attemptBody) + rewriteRequestToolIds(attemptBody, profile.tool_id_seed) + mapSafeguardToolIds(attemptBody, profile.tool_id_seed) + const snap = cwdMapper.getMappingSnapshot() + const mappedCallerCwd = snap?.callerCwd && snap?.virtualCwd ? snap.virtualCwd : callerCwd + return { + body: attemptBody, + slotRewrite: { profile, cwdMapper, gitRewriter }, + mappedCallerCwd, + } +} + +function rewriteOutboundSlotMessage(messageObj, slotRewrite) { + if (!messageObj || typeof messageObj !== 'object' || !slotRewrite?.profile || messageObj.type === 'error') { + return messageObj + } + const out = cloneAttemptJson(messageObj) + const { profile, cwdMapper, gitRewriter } = slotRewrite + rewriteResponseToolIds(out, profile.tool_id_seed) + if (Array.isArray(out.safeguard_results)) { + out.safeguard_results = unmapSafeguardResultToolIds(out.safeguard_results, profile.tool_id_seed) + } + cwdMapper?.rewriteResponseObject(out) + gitRewriter?.rewriteResponseObject(out) + return out +} + +function createHexBoundaryBuffer(rewriteFn) { + let pending = '' + return { + push(chunk) { + if (typeof chunk !== 'string' || !chunk) return '' + pending += chunk + const match = /(? { + if (!gitRewriter) return null + let buf = hexTextBuffers.get(idx) + if (!buf) { + buf = createHexBoundaryBuffer((s) => gitRewriter.rewriteResponseText(s)) + hexTextBuffers.set(idx, buf) + } + return buf + } + + const getHexJsonBuf = (idx) => { + if (!gitRewriter) return null + let buf = hexJsonBuffers.get(idx) + if (!buf) { + buf = createHexBoundaryBuffer((s) => gitRewriter.rewriteResponseText(s)) + hexJsonBuffers.set(idx, buf) + } + return buf + } + + const flushBlockTail = (idx, emitEventHeader) => { + const bType = blockTypes.get(idx) + const rw = streamRewriters.get(idx) + const hexText = hexTextBuffers.get(idx) + const hexJson = hexJsonBuffers.get(idx) + const extraLines = [] + if (bType === 'text') { + const cwdFlushed = rw ? rw.flushTextDelta() : '' + const tail = hexText ? hexText.push(cwdFlushed) + hexText.flush() : cwdFlushed + if (tail) { + const flushEvent = { type: 'content_block_delta', index: idx, delta: { type: 'text_delta', text: tail } } + if (emitEventHeader) extraLines.push('event: content_block_delta') + extraLines.push(`${lastDataPrefix} ${JSON.stringify(flushEvent)}`) + if (emitEventHeader) extraLines.push('') + } + } else if (bType === 'tool_use' || bType === 'server_tool_use' || bType === 'mcp_tool_use') { + const cwdFlushed = rw ? rw.flushInputJsonDelta() : '' + const tail = hexJson ? hexJson.push(cwdFlushed) + hexJson.flush() : cwdFlushed + if (tail) { + const flushEvent = { + type: 'content_block_delta', + index: idx, + delta: { type: 'input_json_delta', partial_json: tail }, + } + if (emitEventHeader) extraLines.push('event: content_block_delta') + extraLines.push(`${lastDataPrefix} ${JSON.stringify(flushEvent)}`) + if (emitEventHeader) extraLines.push('') + } + } + streamRewriters.delete(idx) + hexTextBuffers.delete(idx) + hexJsonBuffers.delete(idx) + blockTypes.delete(idx) + return extraLines + } + + return { + transformLine(line) { + const raw = String(line ?? '') + const trimmed = raw.trim() + if (suppressNextBlank && trimmed === '') { + suppressNextBlank = false + return [] + } + suppressNextBlank = false + + if (trimmed.startsWith('event:')) { + sawEventLine = true + if (pendingEventLine !== null) { + const prev = pendingEventLine + pendingEventLine = raw + return [prev] + } + pendingEventLine = raw + return [] + } + + if (!trimmed.startsWith('data:')) { + if (pendingEventLine !== null) { + const prev = pendingEventLine + pendingEventLine = null + return [prev, raw] + } + return [raw] + } + + const evLine = pendingEventLine + pendingEventLine = null + const dataIdx = raw.indexOf('data:') + const dataPrefix = raw.slice(0, dataIdx + 5) + lastDataPrefix = dataPrefix + const jsonStr = raw.slice(dataIdx + 5).trim() + let payload + try { + payload = JSON.parse(jsonStr) + } catch { + return evLine ? [evLine, raw] : [raw] + } + if (!payload || typeof payload !== 'object') { + return evLine ? [evLine, raw] : [raw] + } + + if (payload.type === 'message_start' && payload.message && typeof payload.message === 'object') { + rewriteResponseToolIds(payload.message, profile.tool_id_seed) + cwdMapper?.rewriteResponseObject(payload.message) + gitRewriter?.rewriteResponseObject(payload.message) + const rewritten = `${dataPrefix} ${JSON.stringify(payload)}` + return evLine ? [evLine, rewritten] : [rewritten] + } + + if (payload.type === 'content_block_start') { + const idx = payload.index + const block = payload.content_block + if (Number.isInteger(idx) && block && typeof block === 'object') { + blockTypes.set(idx, block.type) + if (cwdMapper) streamRewriters.set(idx, cwdMapper.createSseStreamRewriter()) + if (block.type !== 'thinking' && block.type !== 'redacted_thinking') { + if (typeof block.id === 'string') { + block.id = unmapToolUseIdFromAccount(profile.tool_id_seed, block.id) + } + if (block.type === 'text' && typeof block.text === 'string' && block.text) { + const rw = streamRewriters.get(idx) + let nextText = rw ? rw.pushTextDelta(block.text) : block.text + const hexBuf = getHexTextBuf(idx) + if (hexBuf) nextText = hexBuf.push(nextText) + block.text = nextText + } else if (block.input && typeof block.input === 'object' && Object.keys(block.input).length > 0) { + cwdMapper?.rewriteResponseObject(block) + gitRewriter?.rewriteResponseObject(block) + } + } + } + const rewritten = `${dataPrefix} ${JSON.stringify(payload)}` + return evLine ? [evLine, rewritten] : [rewritten] + } + + if (payload.type === 'content_block_delta') { + const idx = payload.index + const delta = payload.delta + if (delta && typeof delta === 'object') { + if (delta.type === 'text_delta' && typeof delta.text === 'string') { + const orig = delta.text + const rw = streamRewriters.get(idx) + const hexBuf = getHexTextBuf(idx) + if (orig !== '') { + let nextText = rw ? rw.pushTextDelta(orig) : orig + if (hexBuf) nextText = hexBuf.push(nextText) + if (nextText === '') { + suppressNextBlank = Boolean(evLine) + return [] + } + delta.text = nextText + } + } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') { + const orig = delta.partial_json + const rw = streamRewriters.get(idx) + const hexBuf = getHexJsonBuf(idx) + if (orig === '') { + // Preserve empty `partial_json: ""` before `content_block_stop` (LESSONS.md); + // if any buffered path/SHA tail remained, flush it here cleanly. + const cwdFlushed = rw ? rw.flushInputJsonDelta() : '' + const flushed = hexBuf ? hexBuf.push(cwdFlushed) + hexBuf.flush() : cwdFlushed + delta.partial_json = flushed + } else { + let nextJson = rw ? rw.pushInputJsonDelta(orig) : orig + if (hexBuf) nextJson = hexBuf.push(nextJson) + if (nextJson === '') { + suppressNextBlank = Boolean(evLine) + return [] + } + delta.partial_json = nextJson + } + } + } + const rewritten = `${dataPrefix} ${JSON.stringify(payload)}` + return evLine ? [evLine, rewritten] : [rewritten] + } + + if (payload.type === 'content_block_stop') { + const idx = payload.index + const extraLines = flushBlockTail(idx, Boolean(evLine)) + const rewritten = `${dataPrefix} ${JSON.stringify(payload)}` + return [...extraLines, ...(evLine ? [evLine] : []), rewritten] + } + + if (payload.type === 'message_delta' && Array.isArray(payload.delta?.safeguard_results)) { + payload.delta.safeguard_results = unmapSafeguardResultToolIds( + payload.delta.safeguard_results, + profile.tool_id_seed, + ) + const rewritten = `${dataPrefix} ${JSON.stringify(payload)}` + return evLine ? [evLine, rewritten] : [rewritten] + } + + return evLine ? [evLine, raw] : [raw] + }, + flush() { + const out = [] + if (pendingEventLine !== null) { + out.push(pendingEventLine) + pendingEventLine = null + } + const openIndices = Array.from( + new Set([...blockTypes.keys(), ...streamRewriters.keys(), ...hexTextBuffers.keys(), ...hexJsonBuffers.keys()]), + ).sort((a, b) => a - b) + for (const idx of openIndices) { + out.push(...flushBlockTail(idx, sawEventLine)) + } + return out + }, + } +} + function authenticatedTenant(req) { if (req.apiKeyRecord?.id != null) return `key:${req.apiKeyRecord.id}` if (req.apiKeyKind === 'master') return 'master' @@ -1188,12 +1534,17 @@ export function createHandleProtocol(deps) { redactionPrincipal = '', redactionSession = '', cancelSessionId = '', + sessionId = null, + slotEpoch = null, tenantId = '', gatewayRequestId = null, licenseInvalidRetryState = null, + slotRewrite = null, }) { const assembler = createClaudeMessageAssembler() const skipResponseHeaders = createResponseHeadersSseFilter() + const attemptIdentity = loadVmIdentity(candidate.exec) + if (attemptIdentity && sessionId) attemptIdentity.callerSessionId = sessionId const workerResult = await dispatchStreamInference({ exec: candidate.exec, admitCragInference: deps.admitCragInference, @@ -1206,7 +1557,7 @@ export function createHandleProtocol(deps) { reqHeaders, timeoutMs, idleTimeoutMs, - identity: loadVmIdentity(candidate.exec), + identity: attemptIdentity, signal, deliveryMode, want1m, @@ -1233,6 +1584,7 @@ export function createHandleProtocol(deps) { redactionPrincipal, redactionSession, cancelSessionId, + slotEpoch, onEnvelope, onOutboundHeaders, onEvent: async (line) => { @@ -1243,6 +1595,9 @@ export function createHandleProtocol(deps) { Object.assign(workerResult, mergeAssembledAssistantHop(workerResult, assembler.message)) if (workerResult?.body) { workerResult.body = restoreToolNames(workerResult.body, toolNames) + if (slotRewrite) { + workerResult.body = rewriteOutboundSlotMessage(workerResult.body, slotRewrite) + } } return acceptAssistantHop(workerResult) } @@ -2466,16 +2821,23 @@ export function createHandleProtocol(deps) { protocol === 'anthropic.messages' && !apiNonAnthropic && tenantPrincipal && !requestContext && !summarySession ? extractCallerSession({ inbound, headers: req.headers }) : '' - const replayScope = publicSession ? JSON.stringify([tenantPrincipal, publicSession, inbound.model]) : '' - const rememberPublic = (content) => { - if (replayScope && Array.isArray(content)) issuedTools.remember(replayScope, inbound.messages, content) + const replayScope = + publicSession && inferenceBackend === 'api' + ? JSON.stringify([tenantPrincipal, publicSession, inbound.model, 'api']) + : publicSession + ? JSON.stringify([tenantPrincipal, publicSession, inbound.model]) + : '' + let activeAttemptReplayScope = replayScope + const rememberPublic = (content, scopeOverride = null) => { + const targetScope = scopeOverride || activeAttemptReplayScope || replayScope + if (targetScope && Array.isArray(content)) issuedTools.remember(targetScope, inbound.messages, content) } const sendPublicJson = (message, upstreamHeaders = null) => { const sent = json(res, 200, message, upstreamHeaders) if (message?.role === 'assistant' && message.type === 'message') rememberPublic(message.content) return sent } - if (replayScope) ctx.body = issuedTools.restore(replayScope, ctx.body) + if (replayScope && inferenceBackend === 'api') ctx.body = issuedTools.restore(replayScope, ctx.body) // Recognition alone is not passthrough. Only the protocol-tab switch keeps // the Claude Code family body; every other inbound is rewritten below. let officialPassthrough = @@ -3701,12 +4063,69 @@ export function createHandleProtocol(deps) { (extra.freshSlot ? `slot:${selected.slotIndex ?? 'x'}:${attemptStartedAt}` : `${selected.stoodIn ? 'standin' : 'vm'}:${selected.vmId || extra.attemptNo || ''}`) - const attemptSessionId = resolveOutboundSessionId(executionSession, { - ...sessionContext, - accountId: selected.accountId, - vmId: selected.vmId, - epoch: attemptEpoch, + const hasSlotAccountProfile = Boolean( + selected?.vm && + !isCodexVm(selected.vm) && + shouldEnable3OsMachineProfile(selected.vm) && + (selected.vm.machine_profile || + selected.vm.claude?.account_uuid || + selected.vm.claude?.email || + selected.vm.account_uuid || + selected.vm.email), + ) + let slotProfile = null + if (hasSlotAccountProfile) { + const ensuredProfile = ensureVmSlotMachineProfile(selected.vm, { + accountUuid: selected.vm.claude?.account_uuid || selected.vm.account_uuid || '', + email: selected.vm.claude?.email || selected.vm.email || '', + orgUuid: selected.vm.claude?.org_uuid || selected.vm.org_uuid || '', + timezoneHint: selected.vm.timezone || selected.vm.fingerprint?.timezone || undefined, + }) + slotProfile = ensuredProfile.profile + if (ensuredProfile.changed && ensuredProfile.profile && cfg?.paths?.project && selected.vm?.id) { + try { + patchVmRecord(cfg.paths.project, selected.vm.id, { + machine_profile: selected.vm.machine_profile, + fingerprint: selected.vm.fingerprint, + }) + } catch {} + } + } + if (slotProfile && selected?.exec && typeof selected.exec === 'object') { + selected.exec.vm = selected.vm + } + const slotEpoch = getSlotSessionEpoch({ + vmId: selected.vmId || selected.vm?.id || '', + sessionId: publicSession || executionSession || '', + persistedVmEpoch: Number(selected.vm?.slot_epoch) || 0, }) + const attemptReplayScope = publicSession + ? JSON.stringify([ + tenantPrincipal, + publicSession, + inbound.model, + selected.accountId || selected.vmId || 'slot', + slotEpoch, + ]) + : '' + activeAttemptReplayScope = attemptReplayScope + if (attemptReplayScope) { + body = issuedTools.restore(attemptReplayScope, body) + } + const attemptSessionId = + slotProfile?.session_id_seed && executionSession + ? deriveAccountSlotSessionId({ + sessionIdSeed: slotProfile.session_id_seed, + clientSessionId: executionSession, + vmId: selected.vmId || selected.vm?.id || '', + slotEpoch, + }) + : resolveOutboundSessionId(executionSession, { + ...sessionContext, + accountId: selected.accountId, + vmId: selected.vmId, + epoch: attemptEpoch, + }) const identity = loadVmIdentity(selected.exec) if (identity && attemptSessionId) identity.callerSessionId = attemptSessionId const credMode = credentialModeFromOauth(selected.vm?.claude || {}) @@ -3888,6 +4307,9 @@ export function createHandleProtocol(deps) { source = shallowCopyBody(standard.body) toolNames = composeToolNames(toolNames, standard.reverse) } + if (attemptReplayScope) { + source = issuedTools.restore(attemptReplayScope, source) + } // The CRAG kernel fingerprints the public stream it already sent, // including thinking. Rewriting an unrecorded signature into text // makes the tool continuation fail with tool_result history mismatch. @@ -4022,6 +4444,16 @@ export function createHandleProtocol(deps) { safeguards_stripped: Boolean(personaIn.safeguards != null && hopBody.safeguards == null), ...(cacheControlRepaired ? { cache_control_repaired: true } : {}), } + const cragSlotForward = applySlotForwardPipeline(hopBody, { + profile: slotProfile, + callerCwd: callerEnvironment?.cwd, + personaRewrite: isSlotPersonaRewriteEnabled({ + routing: routingNow, + vm: selected.vm, + profile: slotProfile, + }), + }) + hopBody = cragSlotForward.body logBag.official_cc_inference = 'crag-print' logBag.provider = 'local_cli' if (!strictPassthrough) hopBody = noteCachePrefix(selected, attemptSessionId, hopBody) @@ -4032,6 +4464,9 @@ export function createHandleProtocol(deps) { meta: { toolNames, sessionId: attemptSessionId, + slotEpoch, + replayScope: attemptReplayScope, + slotRewrite: cragSlotForward.slotRewrite, cliHop: true, cragPrint: true, strictPassthrough, @@ -4046,7 +4481,7 @@ export function createHandleProtocol(deps) { // CRAG replays caller thinking unfiltered; signatures this pool never // issued make an "Invalid signature" 400 safe to strip and retry. foreignThinking, - callerCwd: callerEnvironment?.cwd, + callerCwd: cragSlotForward.mappedCallerCwd, preparedHop, transportRouting, requestContext, @@ -4142,9 +4577,22 @@ export function createHandleProtocol(deps) { !requestContext && !effectiveOfficialPassthrough && !cliPoolPassthrough ? effectiveCliPersona : null, officialTraffic, }) + if (attemptReplayScope) { + hopBody = issuedTools.restore(attemptReplayScope, hopBody) + } + const cliSlotForward = applySlotForwardPipeline(hopBody, { + profile: slotProfile, + callerCwd: callerEnvironment?.cwd, + personaRewrite: isSlotPersonaRewriteEnabled({ + routing: routingNow, + vm: selected.vm, + profile: slotProfile, + }), + }) + hopBody = cliSlotForward.body if (!requestContext) { hopBody = ensureBillingAttribution(hopBody, { - firstUserText, + firstUserText: extractFirstUserText(hopBody?.messages) || firstUserText, sessionId: attemptSessionId, cliVersion: outboundProfile.cliVersion, indexes: billingIndexesFromMessages(hopBody.messages), @@ -4226,6 +4674,10 @@ export function createHandleProtocol(deps) { meta: { toolNames: composeToolNames(inboundToolReverse, clientToolNames), sessionId: attemptSessionId, + slotEpoch, + replayScope: attemptReplayScope, + slotRewrite: cliSlotForward.slotRewrite, + callerCwd: cliSlotForward.mappedCallerCwd, cliHop: true, cragPrint: false, promptSpec: cliPromptSpec, @@ -4311,6 +4763,19 @@ export function createHandleProtocol(deps) { }) } } + if (attemptReplayScope) { + hopBody = issuedTools.restore(attemptReplayScope, hopBody) + } + const httpSlotForward = applySlotForwardPipeline(hopBody, { + profile: slotProfile, + callerCwd: callerEnvironment?.cwd, + personaRewrite: isSlotPersonaRewriteEnabled({ + routing: routingNow, + vm: selected.vm, + profile: slotProfile, + }), + }) + hopBody = httpSlotForward.body logBag.inference_engine = resolveInferenceEngine(selected.vm, routingNow) logBag.persona_preset = configuredMode logBag.official_cc_inference = 'http' @@ -4330,7 +4795,7 @@ export function createHandleProtocol(deps) { mode: sessionMode, routing: routingNow, clientDiscriminator, - firstUserText, + firstUserText: extractFirstUserText(hopBody?.messages) || firstUserText, firstUserIdentity, apiKeyId: req.apiKeyRecord?.id ?? '', stream: upstreamStream, @@ -4369,6 +4834,9 @@ export function createHandleProtocol(deps) { meta: { toolNames: composeToolNames(inboundToolReverse, prepared.toolNames), sessionId: attemptSessionId, + slotEpoch, + replayScope: attemptReplayScope, + slotRewrite: httpSlotForward.slotRewrite, officialPassthrough: effectiveHttpOfficialPassthrough === true, officialTraffic, repaired, @@ -4378,6 +4846,7 @@ export function createHandleProtocol(deps) { }, onUpstreamRisk: (hopResult) => afterHop(hopResult, { blockSessionOn400: false }), callAttempt: async ({ candidate, body, attemptMeta, deliveryMode: attemptDelivery, signal, onCommit }) => { + activeAttemptReplayScope = attemptMeta?.replayScope || replayScope const attemptReqHeaders = attemptMeta?.stripClientBeta && outboundReqHeaders && typeof outboundReqHeaders === 'object' ? Object.fromEntries( @@ -4386,6 +4855,9 @@ export function createHandleProtocol(deps) { ), ) : outboundReqHeaders + const resolvedAttemptCancelSessionId = String( + attemptMeta?.sessionId || outboundReqHeaders?.['x-claude-code-session-id'] || '', + ) if (!clientStream) { return streamAndAssembleClaudeMessage({ candidate, @@ -4417,13 +4889,18 @@ export function createHandleProtocol(deps) { onOutboundHeaders: noteOutboundHeaders, redactionPrincipal: req.apiKeyRecord?.id || (req.apiKeyKind === 'master' ? 'master' : ''), redactionSession: String(req.headers?.['x-claude-code-session-id'] || ''), - cancelSessionId: String(outboundReqHeaders?.['x-claude-code-session-id'] || ''), + cancelSessionId: resolvedAttemptCancelSessionId, + sessionId: attemptMeta?.sessionId || null, + slotEpoch: attemptMeta?.slotEpoch ?? null, tenantId, gatewayRequestId: logCtx.request_id, licenseInvalidRetryState, + slotRewrite: attemptMeta?.slotRewrite || null, }) } - const publicStream = replayScope ? createIssuedToolStream() : null + const effectiveStreamReplayScope = attemptMeta?.replayScope || replayScope + const publicStream = effectiveStreamReplayScope ? createIssuedToolStream() : null + const slotSseRewriter = createOutboundSlotSseRewriter(attemptMeta?.slotRewrite || null) const geminiCrossSseLines = protocol === 'google.gemini' ? [] : null let sseUpstreamHeaders = null let state @@ -4448,6 +4925,54 @@ export function createHandleProtocol(deps) { }) keepalive.arm() const skipResponseHeaders = createResponseHeadersSseFilter() + const emitTransformedSseLine = (rawTransformedLine) => { + let line = rawTransformedLine + if (personaHideTokens) line = hidePersonaUsageInSseLine(line, personaHideTokens, cacheTtl) + keepalive.observeLine(line) + if (protocol === 'anthropic.messages') { + streamTracker?.observe(line) + if (!res.headersSent) writeSSEHeaders(res, sseUpstreamHeaders) + const outbound = anthropicSseErrorRemapper ? anthropicSseErrorRemapper.remapLine(line) : line + res.write(String(outbound).endsWith('\n') ? String(outbound) : String(outbound) + '\n') + publicStream?.observe(outbound) + return + } + const writeChunks = (chunks) => { + if (!chunks.length) return + if (!res.headersSent) writeSSEHeaders(res, sseUpstreamHeaders) + for (const chunk of chunks) { + const event = protocol === 'openai.responses' ? `event: ${chunk.type}\n` : '' + res.write(`${event}data: ${JSON.stringify(chunk)}\n\n`) + } + } + if (protocol === 'google.gemini') { + geminiCrossSseLines.push(String(line).endsWith('\n') ? String(line) : `${line}\n`) + return + } + if (protocol === 'openai.chat') { + writeChunks(claudeSSELineToOpenAIChatChunks(line, state)) + return + } + if (protocol === 'openai.completions') { + writeChunks(claudeSSELineToOpenAICompletionChunks(line, state)) + return + } + writeChunks(claudeSSELineToResponsesEvents(line, state)) + } + const attemptStreamIdentity = loadVmIdentity(candidate.exec) + if (attemptStreamIdentity && attemptMeta?.sessionId) { + attemptStreamIdentity.callerSessionId = attemptMeta.sessionId + } + let slotSseFlushed = false + const flushSlotSseTail = () => { + if (slotSseFlushed || !slotSseRewriter || res.writableEnded || res.destroyed) return + slotSseFlushed = true + try { + for (const flushedLine of slotSseRewriter.flush()) { + emitTransformedSseLine(flushedLine) + } + } catch {} + } try { const streamed = await dispatchStreamInference({ exec: candidate.exec, @@ -4475,7 +5000,7 @@ export function createHandleProtocol(deps) { reqHeaders: attemptReqHeaders, timeoutMs: cfg.limits.upstream_timeout_ms, idleTimeoutMs: streamIdleTimeoutMs, - identity: loadVmIdentity(candidate.exec), + identity: attemptStreamIdentity, signal, deliveryMode: attemptDelivery, want1m, @@ -4488,7 +5013,8 @@ export function createHandleProtocol(deps) { ensureCredential: (exec) => ensureWorkerCredential(exec), redactionPrincipal: req.apiKeyRecord?.id || (req.apiKeyKind === 'master' ? 'master' : ''), redactionSession: String(req.headers?.['x-claude-code-session-id'] || ''), - cancelSessionId: String(outboundReqHeaders?.['x-claude-code-session-id'] || ''), + cancelSessionId: resolvedAttemptCancelSessionId, + slotEpoch: attemptMeta?.slotEpoch ?? null, onEnvelope: noteOutboundEnvelope, onOutboundHeaders: noteOutboundHeaders, onCommit: (upstreamHeaders) => { @@ -4496,42 +5022,16 @@ export function createHandleProtocol(deps) { if (protocol === 'anthropic.messages' && !res.headersSent) writeSSEHeaders(res, sseUpstreamHeaders) onCommit() }, - onEvent: async (line) => { - if (skipResponseHeaders(line)) return - line = restoreToolNamesInSSELine(line, attemptMeta?.toolNames || {}) - if (personaHideTokens) line = hidePersonaUsageInSseLine(line, personaHideTokens, cacheTtl) - keepalive.observeLine(line) - if (protocol === 'anthropic.messages') { - streamTracker?.observe(line) - if (!res.headersSent) writeSSEHeaders(res, sseUpstreamHeaders) - const outbound = anthropicSseErrorRemapper ? anthropicSseErrorRemapper.remapLine(line) : line - res.write(String(outbound).endsWith('\n') ? String(outbound) : String(outbound) + '\n') - publicStream?.observe(outbound) - return - } - const writeChunks = (chunks) => { - if (!chunks.length) return - if (!res.headersSent) writeSSEHeaders(res, sseUpstreamHeaders) - for (const chunk of chunks) { - const event = protocol === 'openai.responses' ? `event: ${chunk.type}\n` : '' - res.write(`${event}data: ${JSON.stringify(chunk)}\n\n`) - } - } - if (protocol === 'google.gemini') { - geminiCrossSseLines.push(String(line).endsWith('\n') ? String(line) : `${line}\n`) - return - } - if (protocol === 'openai.chat') { - writeChunks(claudeSSELineToOpenAIChatChunks(line, state)) - return - } - if (protocol === 'openai.completions') { - writeChunks(claudeSSELineToOpenAICompletionChunks(line, state)) - return + onEvent: async (rawLine) => { + if (skipResponseHeaders(rawLine)) return + const restoredLine = restoreToolNamesInSSELine(rawLine, attemptMeta?.toolNames || {}) + const transformedLines = slotSseRewriter ? slotSseRewriter.transformLine(restoredLine) : [restoredLine] + for (const line of transformedLines) { + emitTransformedSseLine(line) } - writeChunks(claudeSSELineToResponsesEvents(line, state)) }, }) + flushSlotSseTail() if (protocol === 'google.gemini' && streamed?.ok && geminiCrossSseLines?.length) { const tc = await transcodeWithProtoFront({ cfg, @@ -4546,9 +5046,10 @@ export function createHandleProtocol(deps) { res.write(tc.body) } } - if (streamed?.ok) rememberPublic(publicStream?.completedContent()) + if (streamed?.ok) rememberPublic(publicStream?.completedContent(), effectiveStreamReplayScope) return streamed } finally { + flushSlotSseTail() if (anthropicKeepalive) anthropicKeepalive.endAttempt() else keepalive.stop() } diff --git a/src/lib/protocol/issued-tool-replay.mjs b/src/lib/protocol/issued-tool-replay.mjs index e1e6f954e..e458034a4 100644 --- a/src/lib/protocol/issued-tool-replay.mjs +++ b/src/lib/protocol/issued-tool-replay.mjs @@ -101,6 +101,113 @@ const DEFAULT_MAX_SCOPES = 4096 const DEFAULT_MAX_SCOPE_BYTES = 32 * MB const DEFAULT_MAX_SCOPE_RECORDS = 8192 const REFUSAL_LOG_INTERVAL_MS = 10 * 60_000 +const MAX_EPOCH_ENTRIES = 16_384 + +const activeReplayBooks = new Set() +const vmSlotEpochs = new Map() +const clientSessionEpochs = new Map() +let globalSlotEpoch = 0 + +function bumpBoundedEpochMap(map, rawKey) { + const key = String(rawKey ?? '').trim() + if (!key) return 0 + const next = (map.get(key) || 0) + 1 + map.delete(key) + map.set(key, next) + while (map.size > MAX_EPOCH_ENTRIES) { + const oldest = map.keys().next().value + if (oldest === undefined) break + map.delete(oldest) + } + return next +} + +function setBoundedEpochMap(map, rawKey, value) { + const key = String(rawKey ?? '').trim() + if (!key) return 0 + const next = Math.max(map.get(key) || 0, value) + map.delete(key) + map.set(key, next) + while (map.size > MAX_EPOCH_ENTRIES) { + const oldest = map.keys().next().value + if (oldest === undefined) break + map.delete(oldest) + } + return next +} + +export function getSlotSessionEpoch({ vmId = '', sessionId = '', persistedVmEpoch = 0 } = {}) { + const persisted = Number.isInteger(persistedVmEpoch) && persistedVmEpoch > 0 ? persistedVmEpoch : 0 + const vmPart = vmId ? vmSlotEpochs.get(String(vmId).trim()) || 0 : 0 + const sessPart = sessionId ? clientSessionEpochs.get(String(sessionId).trim()) || 0 : 0 + return globalSlotEpoch + Math.max(persisted, vmPart) + sessPart +} + +/** + * Invalidate cached `issuedTools` replay scopes and advance deterministic + * `slotEpoch` counters when a slot swaps accounts, recreates, or drops sticky bindings. + * When `vmEpoch` is provided (persisted on `vm.json`), syncs the in-memory VM epoch + * idempotently so restarts never roll back account-switch isolation epochs. + */ +export function resetSlotSessionState({ + vmId = null, + accountId = null, + sessionId = null, + vmEpoch = null, + all = false, +} = {}) { + if (all) { + globalSlotEpoch += 1 + } else { + if (vmId) { + if (Number.isInteger(vmEpoch) && vmEpoch > 0) { + setBoundedEpochMap(vmSlotEpochs, vmId, vmEpoch) + } else { + bumpBoundedEpochMap(vmSlotEpochs, vmId) + } + } + if (sessionId) bumpBoundedEpochMap(clientSessionEpochs, sessionId) + } + + let clearedScopes = 0 + for (const ref of activeReplayBooks) { + const book = ref.deref?.() + if (!book) { + activeReplayBooks.delete(ref) + continue + } + clearedScopes += book.clearScopes((scopeKey) => { + if (all) return true + let parsed = null + try { + parsed = JSON.parse(scopeKey) + } catch { + parsed = null + } + if (Array.isArray(parsed)) { + // Scope format: [tenantPrincipal, publicSession, model, slotTarget?, slotEpoch?] + const scopeSession = String(parsed[1] ?? '') + const scopeTarget = String(parsed[3] ?? '') + if (sessionId && scopeSession === String(sessionId).trim()) return true + if (accountId && scopeTarget === String(accountId).trim()) return true + if (vmId && scopeTarget === String(vmId).trim()) return true + return false + } + if (sessionId && scopeKey.includes(String(sessionId).trim())) return true + if (accountId && scopeKey.includes(String(accountId).trim())) return true + if (vmId && scopeKey.includes(String(vmId).trim())) return true + return false + }) + } + return { + clearedScopes, + epoch: getSlotSessionEpoch({ + vmId: vmId || '', + sessionId: sessionId || '', + persistedVmEpoch: Number.isInteger(vmEpoch) && vmEpoch > 0 ? vmEpoch : 0, + }), + } +} function envNumber(name, fallback, scale = 1) { const n = Number(process.env[name]) @@ -269,5 +376,25 @@ export function createIssuedToolReplay({ } return out ? { ...body, messages: out } : body } - return { remember, restore, stats } + function clearScopes(predicate = () => true) { + let removed = 0 + for (const [scope, entry] of scopes) { + let match = false + try { + match = Boolean(predicate(scope)) + } catch { + match = false + } + if (!match) continue + retained = Math.max(0, retained - entry.bytes) + scopes.delete(scope) + removed += 1 + } + return removed + } + const api = { remember, restore, clearScopes, stats } + if (typeof WeakRef === 'function') { + activeReplayBooks.add(new WeakRef(api)) + } + return api } diff --git a/src/lib/protocol/user-count-tokens.mjs b/src/lib/protocol/user-count-tokens.mjs index ba12d5b28..c4c652d1a 100644 --- a/src/lib/protocol/user-count-tokens.mjs +++ b/src/lib/protocol/user-count-tokens.mjs @@ -67,7 +67,16 @@ import { detectInboundPlatform } from './platform-detect.mjs' import { isAntigravityRoutedModel } from '../gemini/model-catalog.mjs' import { getGeminiPolicyAliasMap } from './gemini-model-policy.mjs' import { blockedClientError, blockedClientFor } from '../identity/blocked-clients.mjs' -import { resolveInboundIdentity } from '../identity/identity-rewrite.mjs' +import { extractCallerSession, resolveInboundIdentity } from '../identity/identity-rewrite.mjs' +import { + ensureVmSlotMachineProfile, + isSlotPersonaRewriteEnabled, + shouldEnable3OsMachineProfile, +} from '../identity/slot-machine-profile.mjs' +import { createCwdMapper } from '../identity/cwd-mapping.mjs' +import { createGitPersonaRewriter } from '../identity/git-persona.mjs' +import { mapToolUseIdForAccount, rewriteRequestToolIds } from '../identity/tool-id-mapping.mjs' +import { getSlotSessionEpoch } from './issued-tool-replay.mjs' /** routing.compatibility.count_tokens — whether the count_tokens entries are served. * @@ -696,16 +705,88 @@ export async function handleUserCountTokens(req, res, deps) { }) const caps = slotCapabilitiesForCountTokens(peeked, deps) if (caps.includes('count_tokens_v1')) { + const slotVm = peeked.vm || peeked.exec?.vm || null + const hasSlotAccountProfile = Boolean( + slotVm && + !isCodexVm(slotVm) && + shouldEnable3OsMachineProfile(slotVm) && + (slotVm.machine_profile || + slotVm.claude?.account_uuid || + slotVm.claude?.email || + slotVm.account_uuid || + slotVm.email), + ) + const slotProfile = + slotVm && !isCodexVm(slotVm) && slotVm.machine_profile?.session_id_seed && slotVm.machine_profile?.tool_id_seed + ? slotVm.machine_profile + : hasSlotAccountProfile + ? ensureVmSlotMachineProfile( + { ...slotVm }, + { + accountUuid: slotVm.claude?.account_uuid || slotVm.account_uuid || '', + email: slotVm.claude?.email || slotVm.email || '', + orgUuid: slotVm.claude?.org_uuid || slotVm.org_uuid || '', + timezoneHint: slotVm.timezone || slotVm.fingerprint?.timezone || undefined, + }, + ).profile + : null + const slotVmId = peeked.vmId || slotVm?.id || '' + const callerSession = extractCallerSession({ inbound, headers: req?.headers }) || '' + const slotEpoch = slotProfile?.session_id_seed + ? getSlotSessionEpoch({ + vmId: slotVmId, + sessionId: callerSession, + persistedVmEpoch: Number(slotVm?.slot_epoch) || 0, + }) + : 0 + let forwardBody = outboundBody + if (slotProfile && forwardBody && typeof forwardBody === 'object') { + forwardBody = structuredClone(forwardBody) + const personaRewrite = isSlotPersonaRewriteEnabled({ + routing, + vm: slotVm, + profile: slotProfile, + }) + const cwdMapper = createCwdMapper(slotProfile, { personaRewrite }) + const gitRewriter = createGitPersonaRewriter(slotProfile, { personaRewrite }) + cwdMapper.rewriteRequestBody(forwardBody) + gitRewriter.rewriteRequestBody(forwardBody) + rewriteRequestToolIds(forwardBody, slotProfile.tool_id_seed) + if (Array.isArray(forwardBody.safeguards) && slotProfile.tool_id_seed) { + for (const guard of forwardBody.safeguards) { + if (Array.isArray(guard?.tool_use_ids)) { + guard.tool_use_ids = guard.tool_use_ids.map((id) => + typeof id === 'string' ? mapToolUseIdForAccount(slotProfile.tool_id_seed, id) : id, + ) + } + const priorTurns = guard?.classifier_context?.prior_turn_context + if (Array.isArray(priorTurns)) { + for (const turn of priorTurns) { + if (Array.isArray(turn?.tool_use_ids)) { + turn.tool_use_ids = turn.tool_use_ids.map((id) => + typeof id === 'string' ? mapToolUseIdForAccount(slotProfile.tool_id_seed, id) : id, + ) + } + } + } + } + } + } const kernelHeaders = {} if (officialTraffic) { - const callerHeaders = extractCragCallerHeaders(req?.headers, { includeUserAgent: true }) + const callerHeaders = extractCragCallerHeaders(req?.headers, { + includeUserAgent: true, + sessionIdSeed: slotProfile?.session_id_seed || null, + vmId: slotVmId || null, + slotEpoch, + }) if (callerHeaders) Object.assign(kernelHeaders, callerHeaders) const beta = req?.headers?.['anthropic-beta'] if (typeof beta === 'string' && beta.trim()) kernelHeaders['anthropic-beta'] = beta.trim() } const callCountTokens = () => (deps.countTokensViaKernel || countTokensViaKernel)(peeked.exec, { - body: rectifyCrag321Request(outboundBody, { + body: rectifyCrag321Request(forwardBody, { strictPassthrough: officialTraffic === true, countTokens: true, }), diff --git a/src/lib/transport/go-worker-client.mjs b/src/lib/transport/go-worker-client.mjs index 8e3b7e8d2..c207a4793 100644 --- a/src/lib/transport/go-worker-client.mjs +++ b/src/lib/transport/go-worker-client.mjs @@ -16,7 +16,10 @@ import { modelDirectiveForCrag } from '../protocol/model-policy.mjs' import { capOutboundBody } from '../protocol/outbound-snapshot.mjs' import { cacheTtlFromRouting } from '../protocol/cache-ttl.mjs' import { ccEntrypointFromRouting, stripSubagentBilling } from '../identity/crs-persona.mjs' -import { isPromptSpecV1Caps, sanitizePromptSpec } from '../identity/system-prompt-spec.mjs' +import { cragEnvFromSpec, isPromptSpecV1Caps, sanitizePromptSpec } from '../identity/system-prompt-spec.mjs' +import { sanitizeCragEnv } from '../protocol/crag-whitelist.mjs' +import { deriveAccountSlotSessionId } from '../identity/tool-id-mapping.mjs' +import { getSlotSessionEpoch } from '../protocol/issued-tool-replay.mjs' import { sealClaudeCodeCch } from '../identity/cch.mjs' import { canRefreshCredential, credentialModeFromOauth, isApiKeyMode } from '../oauth/credential-mode.mjs' import { isCrsMock, writeCrsTrace, mockCrsPayload, emitMockSse } from './crs-mock.mjs' @@ -521,9 +524,13 @@ export function sanitizeCallerUserAgentHint(rawUa) { * Credentials (`authorization`, `x-api-key`, `cookie`) and hop-by-hop headers * are never accepted here. */ -export function extractCragCallerHeaders(reqHeaders, { includeUserAgent = true } = {}) { +export function extractCragCallerHeaders( + reqHeaders, + { includeUserAgent = true, sessionIdSeed = null, vmId = null, slotEpoch = 0 } = {}, +) { if (!reqHeaders || typeof reqHeaders !== 'object') return undefined const out = {} + const seed = typeof sessionIdSeed === 'string' && sessionIdSeed.trim() ? sessionIdSeed.trim() : '' let ccCount = 0 for (const [key, raw] of Object.entries(reqHeaders)) { const lower = String(key || '') @@ -552,7 +559,16 @@ export function extractCragCallerHeaders(reqHeaders, { includeUserAgent = true } if (ccCount >= MAX_CALLER_CLAUDE_CODE_HEADERS) continue ccCount++ } - out[lower] = value + if (seed && (lower === 'x-claude-code-session-id' || lower === 'x-claude-code-parent-session-id')) { + out[lower] = deriveAccountSlotSessionId({ + sessionIdSeed: seed, + clientSessionId: value, + vmId, + slotEpoch, + }) + } else { + out[lower] = value + } } } return Object.keys(out).length ? out : undefined @@ -569,9 +585,9 @@ function headerValueCaseInsensitive(headers, targetLower) { function resolveCancelSessionId(cancelSessionId, reqHeaders, envelopeHeaders) { for (const candidate of [ + headerValueCaseInsensitive(envelopeHeaders, 'x-claude-code-session-id'), cancelSessionId, headerValueCaseInsensitive(reqHeaders, 'x-claude-code-session-id'), - headerValueCaseInsensitive(envelopeHeaders, 'x-claude-code-session-id'), ]) { const clean = sanitizeCallerHeaderValue(candidate, 256) if (clean) return clean @@ -941,6 +957,22 @@ function stripClientNonCcHeaders(reqHeaders) { * `cragPrint`: explicit hop decision. Null derives it from the VM's own kernel, * never from routing.inference. */ +function extractSessionIdFromBodyMetadata(body) { + const raw = body?.metadata?.user_id + if (typeof raw !== 'string' || !raw.trim()) return '' + const trimmed = raw.trim() + if (trimmed.startsWith('{')) { + try { + const parsed = JSON.parse(trimmed) + if (typeof parsed?.session_id === 'string' && parsed.session_id.trim()) { + return parsed.session_id.trim() + } + } catch {} + } + const m = trimmed.match(/_session_([A-Za-z0-9-]+)$/) + return m ? m[1] : '' +} + export function prepareWorkerPayload({ body, reqHeaders, @@ -957,6 +989,7 @@ export function prepareWorkerPayload({ officialPassthrough = null, officialTraffic = null, safeguardsSanitized = false, + slotEpoch = null, } = {}) { const health = exec?.workerStatus const print = nativeCragRequest(exec, cragPrint) @@ -988,8 +1021,31 @@ export function prepareWorkerPayload({ const officialBetas = print && health?.capabilities?.includes('generation_controls_v3') const headlessBridge = print && isHeadlessBridgeCaps(health?.capabilities) const verifiedOfficial = officialTraffic === true || officialPassthrough === true || strictCrag + const slotSessionSeed = + typeof exec?.vm?.machine_profile?.session_id_seed === 'string' && exec.vm.machine_profile.session_id_seed.trim() + ? exec.vm.machine_profile.session_id_seed.trim() + : null + const slotVmId = exec?.vm?.id || exec?.vmId || null + const rawCallerSessionHeader = headerValueCaseInsensitive(reqHeaders, 'x-claude-code-session-id') || '' + const resolvedSlotEpoch = + Number.isInteger(slotEpoch) && slotEpoch >= 0 + ? slotEpoch + : slotSessionSeed + ? getSlotSessionEpoch({ + vmId: slotVmId || '', + sessionId: String(rawCallerSessionHeader).trim(), + persistedVmEpoch: Number(exec?.vm?.slot_epoch) || 0, + }) + : 0 const callerHeaders = - print && verifiedOfficial ? extractCragCallerHeaders(reqHeaders, { includeUserAgent: headlessBridge }) : undefined + print && verifiedOfficial + ? extractCragCallerHeaders(reqHeaders, { + includeUserAgent: headlessBridge, + sessionIdSeed: slotSessionSeed, + vmId: slotVmId, + slotEpoch: resolvedSlotEpoch, + }) + : undefined const nativeOwnsHeaders = cliHop && cragPrint === true && @@ -1023,6 +1079,31 @@ export function prepareWorkerPayload({ if (nonPassthroughHeadless && k === 'user-agent') continue headers[k] = v } + } else if (slotSessionSeed) { + const identitySession = sanitizeCallerHeaderValue(identity?.callerSessionId, 512) + const bodySession = sanitizeCallerHeaderValue( + extractSessionIdFromBodyMetadata(canonicalBody) || extractSessionIdFromBodyMetadata(body), + 512, + ) + for (const hdrName of ['x-claude-code-session-id', 'x-claude-code-parent-session-id']) { + const existingVal = headerValueCaseInsensitive(headers, hdrName) + const cleanVal = sanitizeCallerHeaderValue(existingVal, 512) + if (!cleanVal) continue + // `identity.callerSessionId` (set from `attemptSessionId` in `handle-protocol.mjs`) + // and `metadata.user_id.session_id` are already derived once — never double-derive. + if ( + hdrName === 'x-claude-code-session-id' && + ((identitySession && cleanVal === identitySession) || (bodySession && cleanVal === bodySession)) + ) { + continue + } + headers[hdrName] = deriveAccountSlotSessionId({ + sessionIdSeed: slotSessionSeed, + clientSessionId: cleanVal, + vmId: slotVmId, + slotEpoch: resolvedSlotEpoch, + }) + } } const thread = pinThreadBetas( main, @@ -1086,6 +1167,30 @@ export function finalizeWorkerPayload(args = {}) { return sealPreparedPayload(prepared, prepared.gated) } +function alignPromptSpecEnvWithMachineProfile(spec, machineProfile) { + if (!spec || !machineProfile || typeof machineProfile !== 'object') return spec + const env = spec.sections?.environment + if (!env || env.enabled !== true) return spec + const nextTz = env.timezone + ? env.timezone_value || (typeof machineProfile.timezone === 'string' && machineProfile.timezone.trim()) || null + : null + const nextLoc = env.locale + ? env.locale_value || (typeof machineProfile.locale === 'string' && machineProfile.locale.trim()) || null + : null + if (nextTz === env.timezone_value && nextLoc === env.locale_value) return spec + return { + ...spec, + sections: { + ...spec.sections, + environment: { + ...env, + timezone_value: nextTz, + locale_value: nextLoc, + }, + }, + } +} + export async function workerEnvelope({ requestContext = null, body, @@ -1110,6 +1215,7 @@ export async function workerEnvelope({ safeguardsSanitized = false, redactionPrincipal = '', redactionSession = '', + slotEpoch = null, } = {}) { const prepared = prepareWorkerPayload({ body, @@ -1127,6 +1233,7 @@ export async function workerEnvelope({ officialPassthrough, officialTraffic, safeguardsSanitized, + slotEpoch, }) const redaction = await redactionContext({ routing, exec, redactionPrincipal, redactionSession }) // Mask the separated path with the same policy as the original system text. @@ -1137,20 +1244,38 @@ export async function workerEnvelope({ const finalized = sealPreparedPayload(prepared, gated) const print = nativeCragRequest(exec, cragPrint) const nativeV3 = print && exec?.workerStatus?.capabilities?.includes('generation_controls_v3') + const slotProfile = + exec?.vm?.machine_profile && typeof exec.vm.machine_profile === 'object' ? exec.vm.machine_profile : null + let finalBody = finalized.body + if (print && slotProfile && finalBody && typeof finalBody === 'object') { + const rawCragSpec = finalBody.crag_prompt_spec + const alignedCragSpec = rawCragSpec ? alignPromptSpecEnvWithMachineProfile(rawCragSpec, slotProfile) : null + if (alignedCragSpec && alignedCragSpec !== rawCragSpec) { + finalBody = { ...finalBody, crag_prompt_spec: alignedCragSpec } + } + if (alignedCragSpec?.sections?.environment?.enabled) { + const derivedEnv = sanitizeCragEnv(cragEnvFromSpec(alignedCragSpec)) + if (derivedEnv && !finalBody.crag_env && isHeadlessBridgeCaps(exec?.workerStatus?.capabilities)) { + finalBody = + finalBody === finalized.body ? { ...finalBody, crag_env: derivedEnv } : { ...finalBody, crag_env: derivedEnv } + } + } + } // Top-level `prompt_spec` rides on the worker envelope for cli-node (never inside `envelope.body`). - const cleanPromptSpec = !print && promptSpec ? sanitizePromptSpec(promptSpec) : null + const cleanPromptSpec = + !print && promptSpec ? alignPromptSpecEnvWithMachineProfile(sanitizePromptSpec(promptSpec), slotProfile) : null // Resolve execution defaults even when cacheTtl is null for mixed-TTL accounting. const defaultCacheTtl = prepared.strictPassthrough ? (cacheTtl ?? null) : (cacheTtl ?? - finalized.body?.cache_ttl ?? - finalized.body?.crag_options?.cache_ttl ?? + finalBody?.cache_ttl ?? + finalBody?.crag_options?.cache_ttl ?? (nativeV3 && routing != null ? cacheTtlFromRouting(routing) : null)) const envelope = { ...(requestContext ? { request_context: requestContext } : {}), ...(typeof outgoingCwd === 'string' ? { caller_cwd: outgoingCwd } : {}), ...(cleanPromptSpec ? { prompt_spec: cleanPromptSpec } : {}), - body: finalized.body, + body: finalBody, ...(finalized.headers ? { headers: finalized.headers } : {}), stream: !!stream, delivery_mode: deliveryMode || 'realtime', @@ -1349,6 +1474,7 @@ async function callGoWorkerRaw({ redactionPrincipal = '', redactionSession = '', cancelSessionId = '', + slotEpoch = null, gatewayRequestId = null, beforeInferencePost, } = {}) { @@ -1374,6 +1500,7 @@ async function callGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + slotEpoch, }) const cleanPromptSpec = !nativeCragRequest(exec, cragPrint) && promptSpec ? sanitizePromptSpec(promptSpec) : null reportEnvelope( @@ -1451,6 +1578,7 @@ async function callGoWorkerRaw({ safeguardsSanitized, redactionPrincipal, redactionSession, + slotEpoch, }) reportEnvelope(onEnvelope, prepared.envelope, { specStrippedFields: prepared.specStrippedFields || [], @@ -1648,6 +1776,7 @@ async function streamGoWorkerRaw({ redactionPrincipal = '', redactionSession = '', cancelSessionId = '', + slotEpoch = null, gatewayRequestId = null, beforeInferencePost, } = {}) { @@ -1674,6 +1803,7 @@ async function streamGoWorkerRaw({ officialPassthrough, officialTraffic, safeguardsSanitized, + slotEpoch, }) const cleanPromptSpec = !nativeCragRequest(exec, cragPrint) && promptSpec ? sanitizePromptSpec(promptSpec) : null reportEnvelope( @@ -1822,6 +1952,7 @@ async function streamGoWorkerRaw({ safeguardsSanitized, redactionPrincipal, redactionSession, + slotEpoch, }) reportEnvelope(onEnvelope, prepared.envelope, { specStrippedFields: prepared.specStrippedFields || [], diff --git a/src/lib/transport/rust-kernel-client.mjs b/src/lib/transport/rust-kernel-client.mjs index 74ed30281..1f8e406d6 100644 --- a/src/lib/transport/rust-kernel-client.mjs +++ b/src/lib/transport/rust-kernel-client.mjs @@ -167,6 +167,90 @@ export function triggerRustKernelCredentialsSync(vm, slotDir, options = {}) { .catch(() => ({ ok: false, swallowed: true, via: 'rust-kernel' })) } +/** + * Capability-gated slot/session reset signal (`POST /internal/v1/slot/reset`). + * Sent only when the target CRAG v2 kernel advertises `slot_machine_profile_v1` + * (or when a test provides an explicit `post` transport / `checkCapability: false`). + */ +export async function notifyRustKernelSlotReset( + exec, + { + sessionId = null, + wipeDisk = true, + timeoutMs = 3000, + checkCapability = true, + health = null, + checkSocketExists = true, + signal, + post = null, + } = {}, +) { + const paths = rustKernelPaths(exec) + if (!post) { + if (!paths.socketPath) return { ok: false, skipped: true, reason: 'socket_missing', via: 'rust-kernel' } + if (checkSocketExists && !fs.existsSync(paths.socketPath)) { + return { ok: false, skipped: true, reason: 'socket_missing', via: 'rust-kernel' } + } + } + try { + if (checkCapability && !post) { + const liveHealth = health || (await rustKernelHealth(exec, { timeoutMs: Math.min(timeoutMs, 1500), signal })) + const caps = liveHealth?.capabilities + const hasSlotResetCap = + liveHealth?.crag_slot_reset_v1 === true || (Array.isArray(caps) && caps.includes('slot_machine_profile_v1')) + if (!hasSlotResetCap) { + return { ok: false, skipped: true, reason: 'capability_missing', via: 'rust-kernel' } + } + } + const send = + typeof post === 'function' + ? post + : (targetExec, requestPath, body, opts) => + callWorkerPost(withRustKernelExec(targetExec), requestPath, body, opts) + const cleanSession = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : null + const payload = { + ...(cleanSession ? { session_id: cleanSession } : {}), + wipe_disk: wipeDisk !== false, + } + const result = await send(exec, '/internal/v1/slot/reset', payload, { + timeoutMs, + signal, + requireInternalToken: true, + }) + return { + ok: result?.ok === true, + status: Number(result?.status) || 0, + body: result?.body ?? null, + via: 'rust-kernel', + } + } catch (error) { + return { + ok: false, + status: 0, + error: String(error?.message || error), + via: 'rust-kernel', + } + } +} + +export function triggerRustKernelSlotReset(vm, slotDir, options = {}) { + if (!vm || isCodexVm(vm)) return null + if (!slotDir && !vm?.runtime?.kernel_socket && !vm?.runtime?.worker_run_dir) return null + const exec = { + vmId: vm.id, + vm, + homeDir: slotDir ? path.join(slotDir, 'cli-home') : '', + } + if (typeof options.notify !== 'function' && typeof options.post !== 'function') { + const { socketPath } = rustKernelPaths(exec) + if (!socketPath || !fs.existsSync(socketPath)) return null + } + const run = typeof options.notify === 'function' ? options.notify : notifyRustKernelSlotReset + return Promise.resolve() + .then(() => run(exec, options)) + .catch(() => ({ ok: false, swallowed: true, via: 'rust-kernel' })) +} + export async function cancelRustKernelRequest( exec, { requestId = '', sessionId = '', timeoutMs = 3000, post = null } = {}, diff --git a/src/lib/transport/rust-kernel-supervisor.mjs b/src/lib/transport/rust-kernel-supervisor.mjs index c6dc149b1..49c83867d 100644 --- a/src/lib/transport/rust-kernel-supervisor.mjs +++ b/src/lib/transport/rust-kernel-supervisor.mjs @@ -18,6 +18,7 @@ import { maxRequestBytes, readRoutingConfigFile, streamIdleTimeoutMs } from '../ import { vmNodeId } from '../cluster/placement.mjs' import { profileForPreset } from '../identity/official-profiles.mjs' import { resolveWorkstationProfile } from '../identity/workstation-profile.mjs' +import { buildTelemetryIdentityFromProfile, toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' import { cacheTtlFromRouting, normalizeCacheTtl } from '../protocol/cache-ttl.mjs' import { thinkingDisplayMode } from '../protocol/thinking.mjs' import { getModelPolicy } from '../protocol/model-policy.mjs' @@ -55,6 +56,7 @@ import { resolveKernelDataplane, resolveSlotPersonaPreset, resolveSlotShmProfile, + supportsSlotMachineProfileKernel, } from '../vm/slot-engine.mjs' import { ensureOfficialCredentialLink, @@ -63,6 +65,7 @@ import { chownSlotRuntimeFile, replaceSlotOwnedFile, runtimeFileOwner, + syncSlotClaudeProfileJson, } from '../oauth/oauth-credentials.mjs' import { slotHost } from '../vm/slot-host.mjs' import { slotClaudeDir, slotHome } from '../vm/slot-identity.mjs' @@ -1412,68 +1415,10 @@ function kernelConfigText(config) { } function acceptNativeClaudeSetup(homeDir, workDir, vm) { - // CLAUDE_CONFIG_DIR points at ~/.claude, so the TUI reads ~/.claude/.claude.json. - // ~/.claude.json is a different file. Create the one the CLI opens when it is - // missing; otherwise a completed home file still leaves the welcome screen up. - // Root must hand a new 0700 dir to the slot user, or kincli cannot read it. - const configDir = path.join(homeDir, '.claude') - const privileged = typeof process.getuid === 'function' && process.getuid() === 0 - const owner = runtimeFileOwner(vm) - const created = fs.mkdirSync(homeDir, { recursive: true, mode: 0o700 }) - const home = fs.lstatSync(homeDir) - if (!home.isDirectory()) return - if (created && privileged) fs.chownSync(homeDir, owner.uid, owner.gid) - ensureHostPrivateDir(configDir, { uid: owner.uid, gid: owner.gid, privileged }) - for (const file of [path.join(configDir, '.claude.json'), path.join(homeDir, '.claude.json')]) { - let doc = {} - let mode = 0o600 - let uid = privileged ? owner.uid : null - let gid = privileged ? owner.gid : null - let existed = false - try { - const st = fs.lstatSync(file) - if (st.isSymbolicLink() || !st.isFile()) continue - existed = true - mode = st.mode & 0o777 - uid = st.uid - gid = st.gid - const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue - doc = parsed - } catch (error) { - if (error?.code !== 'ENOENT') continue - } - let changed = !existed - if (doc.hasCompletedOnboarding !== true) { - doc.hasCompletedOnboarding = true - changed = true - } - if (typeof doc.theme !== 'string' || !doc.theme) { - doc.theme = 'dark' - changed = true - } - if (!doc.projects || typeof doc.projects !== 'object' || Array.isArray(doc.projects)) { - doc.projects = {} - changed = true - } - for (const folder of [workDir, slotHome(vm)]) { - const current = doc.projects[folder] - const project = current && typeof current === 'object' && !Array.isArray(current) ? current : {} - if (project.hasTrustDialogAccepted === true) continue - project.hasTrustDialogAccepted = true - doc.projects[folder] = project - changed = true - } - if (!changed) continue - const tmp = `${file}.${process.pid}.tmp` - fs.writeFileSync(tmp, `${JSON.stringify(doc)}\n`, { mode }) - if (uid != null) { - try { - fs.chownSync(tmp, uid, gid) - } catch {} - } - fs.renameSync(tmp, file) - } + syncSlotClaudeProfileJson(homeDir, vm, { + workDir, + containerHome: slotHome(vm), + }) } function writeKernelJsonAtomically(configPath, config, vm) { @@ -1510,6 +1455,8 @@ export function writeKernelConfig( bridgeSocketDir, vsockEnabled, listenVsockPort, + capabilities = null, + cragVersion = null, existsSync = fs.existsSync, } = {}, ) { @@ -1587,8 +1534,30 @@ export function writeKernelConfig( ...(shmProfile ? { shmProfile } : {}), } : null - const tz = String(timezone || target.timezone || target.fingerprint?.timezone || previous.timezone || '').trim() - const loc = String(locale || target.locale || target.fingerprint?.locale || previous.locale || '').trim() + // Only emit 3-OS machine_profile when the slot actually has one (never lazily migrate + // legacy slots here) AND the active CRAG kernel advertises `slot_machine_profile_v1` + // or CRAG version >= 5.0.2 (preserves legacy `dmi_dir` on `crag-v2 <= 5.0.0`). + const activeMachineProfile = + !host.native && !isCodexVm(record) && target.machine_profile && typeof target.machine_profile === 'object' + ? target.machine_profile + : null + const kernelSupportsMachineProfile = supportsSlotMachineProfileKernel({ + manifest: activeCragManifest, + capabilities: capabilities || target?.workerStatus?.capabilities || null, + version: cragVersion || null, + }) + const emitMachineProfileToKernel = Boolean(activeMachineProfile && kernelSupportsMachineProfile) + const tz = String( + timezone || + target.timezone || + target.fingerprint?.timezone || + previous.timezone || + activeMachineProfile?.timezone || + '', + ).trim() + const loc = String( + locale || target.locale || target.fingerprint?.locale || previous.locale || activeMachineProfile?.locale || '', + ).trim() const defaultCacheTtl = routing != null ? cacheTtlFromRouting(routing) : normalizeCacheTtl(previous.default_cache_ttl) const thinkingDisplay = routing != null @@ -1655,7 +1624,7 @@ export function writeKernelConfig( cch_enabled: cchEnabled, auto_compact_window: autoCompactWindow, model_effort: modelEffort, - ...(!host.native && !isCodexVm(record) ? { telemetry: buildNativeTelemetry(record, projectRoot, routing) } : {}), + ...(!host.native && !isCodexVm(target) ? { telemetry: buildNativeTelemetry(target, projectRoot, routing) } : {}), } if (dataplane === 'crag' && resolveCragKernelVersion(target, kernelRouting) === 'v2' && !host.native) { config.session_slots = Math.min(requestedCragSessionSlots(target, routing, kernelRouting), config.slots_per_worker) @@ -1710,27 +1679,55 @@ export function writeKernelConfig( privileged, }) } - if (!resolvedClaude.headlessBridge) acceptNativeClaudeSetup(homeDir, '/run/kin/work', vm) + if (!resolvedClaude.headlessBridge) { + acceptNativeClaudeSetup( + homeDir, + '/run/kin/work', + activeMachineProfile ? { ...target, machine_profile: activeMachineProfile } : target, + ) + } } if ( config.telemetry && isTelemetryEnabled(defaultSeedPolicy(target.seed_policy || {})) && (!host.bakedKernel || kind !== 'kvm') ) { - const workstation = resolveWorkstationProfile(target) + if (emitMachineProfileToKernel) { + const { dmi_dir: _droppedDmiDir, ...telemetryBase } = config.telemetry + config.telemetry = { + ...telemetryBase, + enabled: true, + identity: { + enabled: true, + ...buildTelemetryIdentityFromProfile(activeMachineProfile), + }, + } + } else { + const workstation = resolveWorkstationProfile(target) + config.telemetry = { + ...config.telemetry, + enabled: true, + dmi_dir: '/etc/kin-dmi', + identity: { + enabled: true, + linux_kernel: workstation.linux_kernel, + linux_distro_id: workstation.linux_distro_id, + linux_distro_version: workstation.linux_distro_version, + shell: workstation.shell, + terminal: workstation.terminal, + package_managers: workstation.package_managers, + }, + } + } + } + } + + if (emitMachineProfileToKernel) { + config.machine_profile = toPublicSlotMachineProfile(activeMachineProfile) + if (config.telemetry && !config.telemetry.identity) { config.telemetry = { ...config.telemetry, - enabled: true, - dmi_dir: '/etc/kin-dmi', - identity: { - enabled: true, - linux_kernel: workstation.linux_kernel, - linux_distro_id: workstation.linux_distro_id, - linux_distro_version: workstation.linux_distro_version, - shell: workstation.shell, - terminal: workstation.terminal, - package_managers: workstation.package_managers, - }, + identity: buildTelemetryIdentityFromProfile(activeMachineProfile), } } } diff --git a/src/lib/vm/guest-identity.mjs b/src/lib/vm/guest-identity.mjs index 14e8fa4bf..867db52fa 100644 --- a/src/lib/vm/guest-identity.mjs +++ b/src/lib/vm/guest-identity.mjs @@ -79,7 +79,77 @@ function stainlessOs(goos) { return 'Linux' } -export function mergeGuestFingerprint(prev = {}, guest = {}) { +export function mergeGuestFingerprint(prev = {}, guest = {}, { machineProfile = null } = {}) { + const mp = machineProfile && typeof machineProfile === 'object' ? machineProfile : null + const profileOsFamily = mp?.os_family || prev.os_family || null + const profileActive = Boolean(profileOsFamily) + + if (profileActive) { + const deviceId = mp?.device_id || prev.device_id || guest.device_id || '' + const machineId = mp?.machine_id || prev.machine_id || null + const sessionId = prev.session_id || guest.session_id || '' + const os = mp?.stainless_os || prev.stainless_os || stainlessOs(guest.goos || guest.os || prev.stainless_os) + const arch = mp?.stainless_arch || prev.stainless_arch || stainlessArch(guest.arch || prev.stainless_arch) + const hostname = mp?.hostname || prev.hostname || guest.hostname || null + const guestHostname = guest.hostname && guest.hostname !== hostname ? guest.hostname : prev.guest_hostname || null + const outboundKernel = + mp?.kernel_release || prev.kernel_release || prev.linux_kernel || guest.kernel_release || null + const guestKernel = + guest.kernel_release && guest.kernel_release !== outboundKernel + ? guest.kernel_release + : prev.guest_kernel_release || null + const guestMachine = prev.guest_machine_id || guest.machine_id || null + const next = { + ...prev, + device_id: deviceId, + ...(machineId ? { machine_id: machineId } : {}), + session_id: sessionId, + source: prev.source === 'generated' ? 'generated' : 'guest', + schema_version: guest.schema_version || GUEST_IDENTITY_SCHEMA, + runtime_kind: guest.runtime_kind || prev.runtime_kind || null, + os_family: profileOsFamily, + platform: mp?.platform || prev.platform || null, + platform_raw: mp?.platform_raw || prev.platform_raw || profileOsFamily, + os_id: mp?.os_id || prev.os_id || guest.os_id || null, + os_pretty: mp?.os_pretty || prev.os_pretty || guest.os_pretty || null, + os_version: mp?.os_version || prev.os_version || null, + arch: mp?.arch || prev.arch || arch, + hostname, + guest_hostname: guestHostname, + kernel_release: outboundKernel, + guest_kernel_release: guestKernel, + official_user_id: prev.official_user_id || null, + guest_machine_id: guestMachine, + timezone: prev.timezone || mp?.timezone || guest.timezone || null, + locale: prev.locale || mp?.locale || guest.locale || null, + worker_version: guest.worker_version || prev.worker_version || null, + collected_at: guest.collected_at || new Date().toISOString(), + user_agent: prev.user_agent || null, + x_app: prev.x_app || 'cli', + stainless_lang: OFFICIAL_STAINLESS.stainless_lang, + stainless_os: os, + stainless_arch: arch, + stainless_runtime: OFFICIAL_STAINLESS.stainless_runtime, + stainless_runtime_version: OFFICIAL_STAINLESS.stainless_runtime_version, + stainless_package_version: OFFICIAL_STAINLESS.stainless_package_version, + reset_at: prev.reset_at || null, + updated_at: new Date().toISOString(), + } + if (profileOsFamily === 'linux') { + next.linux_kernel = mp?.linux_kernel || prev.linux_kernel || outboundKernel + } else { + delete next.linux_kernel + } + delete next.official_machine_id + // Keep machine_profile-authoritative hardware intact; do not overwrite with Linux guest probe facts. + if (prev.hardware && typeof prev.hardware === 'object') { + next.hardware = { ...prev.hardware } + } else if (mp?.hardware && typeof mp.hardware === 'object') { + next.hardware = { ...mp.hardware } + } + return next + } + const officialMachine = prev.official_machine_id || null const deviceId = officialMachine || prev.device_id || guest.device_id || '' const sessionId = prev.session_id || guest.session_id || '' @@ -171,7 +241,9 @@ export async function collectSlotIdentity(projectRoot, vm, { callGet = readGuest return { ok: false, id: vm.id, error: 'vm.json unreadable' } } if (!guest.runtime_kind) guest.runtime_kind = runtimeKind(current) - current.fingerprint = mergeGuestFingerprint(current.fingerprint, guest) + current.fingerprint = mergeGuestFingerprint(current.fingerprint, guest, { + machineProfile: current.machine_profile || null, + }) current.runtime = { ...(current.runtime || {}), type: runtimeKind(current), diff --git a/src/lib/vm/kvm-machine.mjs b/src/lib/vm/kvm-machine.mjs index ad57cc364..8e5b187c4 100644 --- a/src/lib/vm/kvm-machine.mjs +++ b/src/lib/vm/kvm-machine.mjs @@ -3,6 +3,8 @@ * They live on vm.machine and in the stopped container's env; image/network recreate * must backfill from the container (or guest hardware probe) before docker rm. */ +import fs from 'node:fs' +import path from 'node:path' import { isCustomKvmMode } from './custom-os-runtime.mjs' import { slotDiskGb, VM_CONFIG_DEFAULTS } from './machine-spec.mjs' import { patchVmRecord } from './vm-registry.mjs' @@ -52,8 +54,30 @@ export function readDockerContainerEnv(containerName, { run } = {}) { } } -function pickMac(vm, containerEnv) { - return macOk(vm?.machine?.mac) || macOk(containerEnv?.KIN_KVM_MAC) || macOk(vm?.fingerprint?.hardware?.mac) || '' +function readComputerHardwareMac(projectRoot, vmId) { + const id = presentText(vmId) + if (!projectRoot || !id) return '' + const fpDir = path.join(projectRoot, 'vms', id, 'kvm', 'fingerprint') + try { + const hw = JSON.parse(fs.readFileSync(path.join(fpDir, 'hardware.json'), 'utf8')) + const fromHw = macOk(hw?.en0_mac || hw?.mac) + if (fromHw) return fromHw + } catch {} + try { + const fromFile = macOk(fs.readFileSync(path.join(fpDir, 'system', 'hardware', 'mac'), 'utf8')) + if (fromFile) return fromFile + } catch {} + return '' +} + +function pickMac(vm, containerEnv, projectRoot) { + return ( + macOk(vm?.machine?.mac) || + macOk(containerEnv?.KIN_KVM_MAC) || + readComputerHardwareMac(projectRoot, vm?.id) || + macOk(vm?.fingerprint?.hardware?.mac) || + '' + ) } function pickDiskSerial(vm, containerEnv) { @@ -76,7 +100,7 @@ export function ensureKvmMachineRecord( : containerName ? readDockerContainerEnv(containerName, { run }) : null - const mac = pickMac(vm, containerEnv) + const mac = pickMac(vm, containerEnv, projectRoot) const disk_serial = pickDiskSerial(vm, containerEnv) if (!mac && !disk_serial) return false const machine = vm.machine && typeof vm.machine === 'object' ? { ...vm.machine } : {} diff --git a/src/lib/vm/kvm-slot-agent-client.mjs b/src/lib/vm/kvm-slot-agent-client.mjs index ea8f1bb3b..6744d1031 100644 --- a/src/lib/vm/kvm-slot-agent-client.mjs +++ b/src/lib/vm/kvm-slot-agent-client.mjs @@ -23,7 +23,7 @@ const SHA256_RE = /^[a-f0-9]{64}$/ const SAFE_PRESET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.json$/ const SAFE_REL_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/ const RESERVED_PUBLISH_NAMES = new Set(['sync-pending', 'managed', 'lock']) -const SYNC_TARGETS = new Set(['credentials', 'kernel_config', 'worker_config', 'managed_preset']) +const SYNC_TARGETS = new Set(['credentials', 'kernel_config', 'worker_config', 'managed_preset', 'claude_profile']) const DEFAULT_SLOT_SYNC_TARGETS = Object.freeze(['kernel_config', 'worker_config', 'credentials', 'managed_preset']) const PUBLISH_SCOPES = new Set(['license', 'host']) const MUTATE_SCOPES = new Set(['license', 'host', 'all']) @@ -350,6 +350,10 @@ export function createKvmSlotAgentClient({ socketPath, token, timeoutMs = AGENT_ return invoke('restart_crag', {}, opts) }, + clearSlotState(opts = {}) { + return invoke('clear_slot_state', {}, opts) + }, + coreCheck({ expectedSha256 } = {}, opts = {}) { const params = {} if (expectedSha256 != null && expectedSha256 !== '') { @@ -486,6 +490,26 @@ export async function syncCustomKvmSlotFiles(projectRoot, vm, opts = {}) { } continue } + if (target === 'claude_profile') { + const content = homeDir + ? readRegularFileBytes(path.join(homeDir, '.claude', '.claude.json')) || + readRegularFileBytes(path.join(homeDir, '.claude.json')) + : null + if (content && content.length > 0) { + const res = await agent.syncFile({ target: 'claude_profile', content }, rpcOpts) + if (!res.ok) return { ok: false, target, error: res.error, message: res.message, synced } + synced.push('claude_profile') + } else if (required.has(target)) { + return { + ok: false, + target, + error: `${target}_missing`, + message: 'Required host .claude.json is missing or empty', + synced, + } + } + continue + } if (target === 'managed_preset') { const presetDir = computerDir ? path.join(computerDir, 'system', 'etc', 'claude-code', 'managed-settings.d') : '' let names = [] @@ -522,3 +546,82 @@ export async function syncCustomKvmSlotFiles(projectRoot, vm, opts = {}) { return { ok: true, synced } } + +/** + * Best-effort push of `.claude/.claude.json` (and mirror `home/.claude.json`) to a + * custom-erofs KVM guest via `kin-slot-agent`. Older guest agents lacking the + * `claude_profile` sync_file target return `{ ok: true, skipped: true }`. + */ +export async function pushCustomKvmClaudeProfile(projectRoot, vm, opts = {}) { + const vmId = String(vm?.id || vm?.vmId || '').trim() + const slotBase = projectRoot && vmId ? path.join(projectRoot, 'vms', vmId) : '' + const homeDir = opts.homeDir || (slotBase ? path.join(slotBase, 'cli-home') : '') + const content = homeDir + ? readRegularFileBytes(path.join(homeDir, '.claude', '.claude.json')) || + readRegularFileBytes(path.join(homeDir, '.claude.json')) + : null + if (!content || content.length === 0) { + return { ok: true, skipped: true, reason: 'local_missing' } + } + + let agent = opts.client || null + if (!agent) { + const conn = resolveSlotAgentConnection(projectRoot, vm, opts) + if (!conn.socketPath || !fs.existsSync(conn.socketPath) || !TOKEN_RE.test(conn.token)) { + return { ok: true, skipped: true, reason: 'agent_unavailable' } + } + agent = createKvmSlotAgentClient({ + socketPath: conn.socketPath, + token: conn.token, + timeoutMs: opts.timeoutMs ?? AGENT_DEFAULT_TIMEOUT_MS, + }) + } + + const res = await agent.syncFile( + { target: 'claude_profile', content }, + opts.timeoutMs != null ? { timeoutMs: opts.timeoutMs } : {}, + ) + if (res?.ok) { + return { ok: true, pushed: true, result: res.result } + } + if (res?.error === 'invalid_params' || res?.error === 'unknown_op') { + return { ok: true, skipped: true, reason: 'agent_unsupported', error: res.error, message: res.message } + } + if (res?.error === 'agent_unreachable') { + return { ok: true, skipped: true, reason: 'agent_unreachable', error: res.error, message: res.message } + } + return { ok: false, skipped: false, error: res?.error || 'claude_profile_sync_failed', message: res?.message || '' } +} + +/** + * Best-effort wipe of guest account/session/telemetry state on custom-erofs KVM + * (`credentials.json`, `.credentials.json`, `.claude.json`, `.claude/.claude.json`, + * `crag-v3-continuations`, `telemetry`, `/run/kin/work/.crag-sessions`). + * Older guest agents lacking `clear_slot_state` degrade cleanly with `{ ok: true, skipped: true }`. + */ +export async function clearCustomKvmSlotState(projectRoot, vm, opts = {}) { + let agent = opts.client || null + if (!agent) { + const conn = resolveSlotAgentConnection(projectRoot, vm, opts) + if (!conn.socketPath || !fs.existsSync(conn.socketPath) || !TOKEN_RE.test(conn.token)) { + return { ok: true, skipped: true, reason: 'agent_unavailable' } + } + agent = createKvmSlotAgentClient({ + socketPath: conn.socketPath, + token: conn.token, + timeoutMs: opts.timeoutMs ?? AGENT_DEFAULT_TIMEOUT_MS, + }) + } + + const res = await agent.clearSlotState(opts.timeoutMs != null ? { timeoutMs: opts.timeoutMs } : {}) + if (res?.ok) { + return { ok: true, cleared: Array.isArray(res.result?.cleared) ? res.result.cleared : [], result: res.result } + } + if (res?.error === 'unknown_op' || res?.error === 'invalid_params') { + return { ok: true, skipped: true, reason: 'agent_unsupported', error: res.error, message: res.message } + } + if (res?.error === 'agent_unreachable') { + return { ok: true, skipped: true, reason: 'agent_unreachable', error: res.error, message: res.message } + } + return { ok: false, skipped: false, error: res?.error || 'clear_slot_state_failed', message: res?.message || '' } +} diff --git a/src/lib/vm/slot-engine.mjs b/src/lib/vm/slot-engine.mjs index 9f86171d2..5ce9fc034 100644 --- a/src/lib/vm/slot-engine.mjs +++ b/src/lib/vm/slot-engine.mjs @@ -57,6 +57,44 @@ export function isNativeMultisessionCaps(caps) { return Array.isArray(caps) && caps.includes('native_multisession_v51') } +export function isSlotMachineProfileCaps(caps) { + return Array.isArray(caps) && caps.includes('slot_machine_profile_v1') +} + +function parseCragSemverTuple(raw) { + const m = String(raw ?? '') + .trim() + .match(/^v?(\d+)\.(\d+)\.(\d+)/) + if (!m) return null + return [Number(m[1]), Number(m[2]), Number(m[3])] +} + +/** + * Capability/version gate for `run/kernel.json` `machine_profile` & 3-OS + * `telemetry.identity` fields (protects `crag-v2 <= 5.0.0` kernels that may + * reject unknown keys or expect legacy `dmi_dir`). + */ +export function supportsSlotMachineProfileKernel({ manifest = null, capabilities = null, version = null } = {}) { + const caps = Array.isArray(capabilities) + ? capabilities + : Array.isArray(manifest?.capabilities) + ? manifest.capabilities + : null + if (isSlotMachineProfileCaps(caps)) return true + const rawVer = + version ?? + manifest?.software_version ?? + manifest?.version ?? + manifest?.crag_version ?? + manifest?.kernel_version ?? + manifest?.release_version ?? + '' + const tuple = parseCragSemverTuple(rawVer) + if (!tuple) return false + const [maj, min, pat] = tuple + return maj > 5 || (maj === 5 && (min > 0 || pat >= 2)) +} + /** * Native CRAG v3+ kernel where the official Claude CLI / Headless Bridge owns * outbound beta & header assembly. Recognizes both legacy 3.1.24 TUI queue diff --git a/src/lib/vm/slot-host.mjs b/src/lib/vm/slot-host.mjs index 754d0023e..50150adcf 100644 --- a/src/lib/vm/slot-host.mjs +++ b/src/lib/vm/slot-host.mjs @@ -102,7 +102,12 @@ import { isCodexVm } from './vm-kind.mjs' import { nodeEgressProxyUrl } from '../cluster/node-egress-socks.mjs' import { isKvmRuntime } from './runtime-kind.mjs' import { isCustomKvmMode } from './custom-os-runtime.mjs' -import { resolveSlotAgentConnection, syncCustomKvmSlotFiles } from './kvm-slot-agent-client.mjs' +import { + clearCustomKvmSlotState, + pushCustomKvmClaudeProfile, + resolveSlotAgentConnection, + syncCustomKvmSlotFiles, +} from './kvm-slot-agent-client.mjs' import { stripWorkerCredentialEmail } from '../oauth/oauth-credentials.mjs' import { stopCodexKernel } from '../transport/codex-kernel-supervisor.mjs' import { triggerRustKernelCredentialsSync } from '../transport/rust-kernel-client.mjs' @@ -114,6 +119,30 @@ const syncLocalCredentials = async (vm, slotDir) => { return { skipped: true } } +function clearLocalSlotStatePaths(slotDir) { + if (!slotDir) return [] + const targets = [ + ['credentials', path.join(slotDir, 'cli-home', '.claude', 'credentials.json')], + ['credentials_alias', path.join(slotDir, 'cli-home', '.claude', '.credentials.json')], + ['claude_profile', path.join(slotDir, 'cli-home', '.claude', '.claude.json')], + ['home_claude_profile', path.join(slotDir, 'cli-home', '.claude.json')], + ['crag_v3_continuations', path.join(slotDir, 'cli-home', '.claude', 'crag-v3-continuations')], + ['telemetry', path.join(slotDir, 'cli-home', '.claude', 'telemetry')], + ['crag_sessions', path.join(slotDir, 'run', 'work', '.crag-sessions')], + ['telemetry_upload_log', path.join(slotDir, 'run', 'telemetry-upload.log')], + ] + const cleared = [] + for (const [label, target] of targets) { + try { + if (fs.lstatSync(target)) { + fs.rmSync(target, { recursive: true, force: true }) + cleared.push(label) + } + } catch {} + } + return cleared +} + async function isLocalSlotContainerRunning(vm, { dockerApi = localDocker, inspect = inspectContainerOrNull } = {}) { const name = vm?.runtime?.container_name || (vm?.id ? containerName(vm.id) : '') if (!name) return false @@ -153,9 +182,13 @@ export async function pushCustomKvmSlotCredentials(vm, slotDir, deps = {}) { } } + const runDir = vm?.runtime?.worker_run_dir || path.join(slotDir, 'run') + const hasKernelConfig = fs.existsSync(path.join(runDir, 'kernel.json')) + const targets = hasKernelConfig ? ['credentials', 'kernel_config'] : ['credentials'] const synced = await syncFn(projectRoot, vm, { homeDir, - targets: ['credentials'], + runDir, + targets, requiredTargets: ['credentials'], ...(deps.client ? { client: deps.client } : {}), ...(deps.socketPath ? { socketPath: deps.socketPath } : {}), @@ -275,6 +308,8 @@ const LOCAL_HOST = Object.freeze({ }, queueSyncRun: () => null, syncCredentials: syncLocalCredentials, + syncClaudeProfile: async () => ({ ok: true, local: true }), + clearSlotState: async (_vm, slotDir) => ({ ok: true, local: true, cleared: clearLocalSlotStatePaths(slotDir) }), onImport: syncLocalCredentials, afterRefresh: noop, }) @@ -357,6 +392,24 @@ function nodeHost(nodeId) { triggerRustKernelCredentialsSync(vm, slotDir) return result }, + syncClaudeProfile: async (vm, slotDir) => { + try { + const result = await pushSlotFiles(vm, slotDir, ['seed_settings']) + return { ok: true, pushed: result.pushed || [] } + } catch (error) { + return { + ok: false, + skipped: true, + error: error?.code || 'claude_profile_sync_failed', + message: String(error?.message || error), + } + } + }, + clearSlotState: async (_vm, slotDir) => ({ + ok: true, + local: true, + cleared: clearLocalSlotStatePaths(slotDir), + }), onImport: async (vm, slotDir) => { const result = await pushSlotCredentials(vm, slotDir) triggerRustKernelCredentialsSync(vm, slotDir) @@ -456,6 +509,25 @@ export function slotHost(vm) { ...(!nodeId ? { syncCredentials: (targetVm, slotDir) => pushCustomKvmSlotCredentials(targetVm || vm, slotDir), + syncClaudeProfile: (targetVm, slotDir, deps = {}) => { + const projectRoot = path.dirname(path.dirname(slotDir)) + return pushCustomKvmClaudeProfile(projectRoot, targetVm || vm, { + homeDir: path.join(slotDir, 'cli-home'), + ...deps, + }) + }, + clearSlotState: async (targetVm, slotDir, deps = {}) => { + const localCleared = clearLocalSlotStatePaths(slotDir) + const projectRoot = path.dirname(path.dirname(slotDir)) + const guest = await clearCustomKvmSlotState(projectRoot, targetVm || vm, deps) + return { + ok: guest?.ok !== false, + skipped: guest?.skipped === true, + ...(guest?.reason ? { reason: guest.reason } : {}), + local_cleared: localCleared, + guest_cleared: Array.isArray(guest?.cleared) ? guest.cleared : [], + } + }, onImport: (targetVm, slotDir) => pushCustomKvmSlotCredentials(targetVm || vm, slotDir), afterRefresh: noop, } diff --git a/src/lib/vm/slot-seed.mjs b/src/lib/vm/slot-seed.mjs index 4411174a8..1a60f20b1 100644 --- a/src/lib/vm/slot-seed.mjs +++ b/src/lib/vm/slot-seed.mjs @@ -15,9 +15,11 @@ import { buildKinSeedJson } from '../identity/workstation-profile.mjs' import { OFFICIAL_CLI_VERSION } from '../identity/vm-identity.mjs' import crypto from 'node:crypto' import { readRoutingConfigFile } from '../core/config.mjs' -import { runtimeFileOwner } from '../oauth/oauth-credentials.mjs' +import { runtimeFileOwner, syncSlotClaudeProfileJson } from '../oauth/oauth-credentials.mjs' import { telemetryDisableNonessentialTraffic } from './native-telemetry.mjs' import { resolveKernelDataplane } from './slot-engine.mjs' +import { slotHome } from './slot-identity.mjs' +import { isCodexVm } from './vm-kind.mjs' import { withVmLock } from './vm-file.mjs' function resolveDisableNonessential(projectRoot, routing, override) { @@ -196,6 +198,14 @@ export function writeSlotSeedFiles( }, vm, ) + if (!isCodexVm(vm) && vm?.machine_profile?.device_id) { + try { + syncSlotClaudeProfileJson(homeDir, vm, { + workDir: '/run/kin/work', + containerHome: slotHome(vm), + }) + } catch {} + } return { wrote: true, homeDir, diff --git a/src/lib/vm/vm-package.mjs b/src/lib/vm/vm-package.mjs index 506dc8820..7732f6e0d 100644 --- a/src/lib/vm/vm-package.mjs +++ b/src/lib/vm/vm-package.mjs @@ -8,7 +8,14 @@ import fs from 'node:fs' import path from 'node:path' import { validTimezone } from '../core/timezone.mjs' import { normalizeAuthScheme } from '../oauth/auth-scheme.mjs' -import { persistOauthToVm, readWorkerCredentialFile, writeWorkerCredentialFile } from '../oauth/oauth-credentials.mjs' +import { + persistOauthToVm, + readWorkerCredentialFile, + syncSlotClaudeProfileJson, + writeWorkerCredentialFile, +} from '../oauth/oauth-credentials.mjs' +import { ensureVmSlotMachineProfile, toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' +import { slotHome } from './slot-identity.mjs' import { oauthToSub2apiExport, sub2apiAccountToOauth } from '../oauth/sub2api-account.mjs' import { parseScheduleLevelInput } from '../pool/credential-weight.mjs' import { applyScheduleOff, applyUnschedulable, migrateScheduleRecord } from '../pool/schedule-state.mjs' @@ -547,10 +554,44 @@ function writeCredential(projectRoot, id, spec) { return { ok: true, account: saved[0] } } const home = path.join(projectRoot, 'vms', id, 'cli-home') + const vmPath = path.join(projectRoot, 'vms', `${id}.json`) const oauth = spec.credential.oauth - const file = writeWorkerCredentialFile(home, oauth) + let vmRecord = null + try { + vmRecord = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + } catch {} + let oauthToWrite = oauth + if (vmRecord && !isCodexVm(vmRecord)) { + const ensured = ensureVmSlotMachineProfile(vmRecord, { + accountUuid: oauth.account_uuid || null, + email: oauth.email || null, + orgUuid: oauth.org_uuid || null, + timezoneHint: vmRecord.proxy?.geo?.timezone || vmRecord.timezone || undefined, + }) + if (ensured.profile) { + oauthToWrite = { + ...oauth, + machineProfile: toPublicSlotMachineProfile(ensured.profile), + } + if (ensured.changed) { + vmRecord.updated_at = new Date().toISOString() + atomicWriteJson(vmPath, vmRecord, { mode: 0o600 }) + } + } + } + const file = writeWorkerCredentialFile(home, oauthToWrite) if (!file) return fail('credential_required', 'Claude 包需要 access_token、refresh_token 或 api_key') - persistOauthToVm(path.join(projectRoot, 'vms', `${id}.json`), oauth, { acceptLiveGrant: true, operatorImport: true }) + persistOauthToVm(vmPath, oauthToWrite, { acceptLiveGrant: true, operatorImport: true }) + try { + const saved = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + if (saved && !isCodexVm(saved) && saved.machine_profile?.device_id) { + syncSlotClaudeProfileJson(home, saved, { + workDir: '/run/kin/work', + containerHome: slotHome(saved), + wipeAccountState: false, + }) + } + } catch {} return { ok: true } } diff --git a/src/lib/vm/vm-recreate.mjs b/src/lib/vm/vm-recreate.mjs index 8a06df28c..d488ffbdc 100644 --- a/src/lib/vm/vm-recreate.mjs +++ b/src/lib/vm/vm-recreate.mjs @@ -3,6 +3,7 @@ * timezone / proxy / seed / concurrency), wipe guest home + credentials, * then the caller destroys the container and starts a new one. */ +import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' import { validTimezone } from '../core/timezone.mjs' @@ -37,6 +38,8 @@ import { writeGuestMachineIdFile, } from '../identity/workstation-fingerprint.mjs' import { assignComputerFingerprint } from '../identity/slot-computer.mjs' +import { deriveSlotMachineProfile, projectProfileToVmFingerprint } from '../identity/slot-machine-profile.mjs' +import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs' import { stripWorkerCredentialEmail } from '../oauth/oauth-credentials.mjs' const KEEP_HOME = [ @@ -208,6 +211,37 @@ export function buildRecreatedVmRecord(prev, generated, { mode = 'traits' } = {} const timezone = validTimezone(prev.timezone) || validTimezone(pack.timezone) || null const locale = prev.locale || pack.locale const account = keep ? keptAccount(prev) : { claude: {}, codex: null } + const prevGeneration = Number.isInteger(Number(prev?.profile_generation)) + ? Math.max(0, Number(prev.profile_generation)) + : 0 + const nextGeneration = keep ? prevGeneration : prevGeneration + 1 + const prevSlotEpoch = Number.isInteger(Number(prev?.slot_epoch)) ? Math.max(0, Number(prev.slot_epoch)) : 0 + const nextSlotEpoch = keep ? prevSlotEpoch : prevSlotEpoch + 1 + const had3OsProfile = + !isCodexVm(prev) && + Boolean( + (prev?.machine_profile && typeof prev.machine_profile === 'object') || + prev?.machine_profile_opt_in === true || + prev?.machine_profile_mode === '3os', + ) + const nextReseedNonce = keep + ? typeof prev?.profile_reseed_nonce === 'string' && prev.profile_reseed_nonce.trim() + ? prev.profile_reseed_nonce.trim() + : null + : had3OsProfile + ? `gen-${nextGeneration}-${crypto.randomBytes(8).toString('hex')}` + : null + const rotatedMachineProfile = + !keep && had3OsProfile + ? deriveSlotMachineProfile({ + accountUuid: '', + email: '', + reseedNonce: nextReseedNonce, + fallbackSeed: `${prev.id}:${nextReseedNonce}`, + timezoneHint: timezone || undefined, + locale: locale || undefined, + }) + : null const next = { id: prev.id, name: prev.name, @@ -231,9 +265,32 @@ export function buildRecreatedVmRecord(prev, generated, { mode = 'traits' } = {} ...(activeHours ? { active_hours: activeHours } : {}), }, claude: account.claude, - fingerprint: keep - ? { ...pack, timezone, locale } - : applyGeneratedFingerprint({}, { ...pack, timezone, locale, reset_at: now }), + ...(had3OsProfile ? { machine_profile_opt_in: true } : {}), + ...(nextGeneration > 0 ? { profile_generation: nextGeneration } : {}), + ...(nextReseedNonce ? { profile_reseed_nonce: nextReseedNonce } : {}), + ...(nextSlotEpoch > 0 ? { slot_epoch: nextSlotEpoch } : {}), + ...(keep && !isCodexVm(prev) && prev?.machine_profile && typeof prev.machine_profile === 'object' + ? { machine_profile: structuredClone(prev.machine_profile) } + : rotatedMachineProfile + ? { machine_profile: rotatedMachineProfile } + : {}), + fingerprint: (() => { + if (!keep) { + const freshFp = applyGeneratedFingerprint({}, { ...pack, timezone, locale, reset_at: now }) + if (rotatedMachineProfile) { + return projectProfileToVmFingerprint(rotatedMachineProfile, freshFp) + } + return freshFp + } + const projected = + !isCodexVm(prev) && prev?.machine_profile && typeof prev.machine_profile === 'object' + ? projectProfileToVmFingerprint(prev.machine_profile, { ...pack, timezone, locale }) + : { ...pack, timezone, locale } + if (prev?.fingerprint?.guest_machine_id) { + projected.guest_machine_id = prev.fingerprint.guest_machine_id + } + return projected + })(), stats: keep && prev.stats && typeof prev.stats === 'object' ? prev.stats : {}, created_at: prev.created_at || now, updated_at: now, @@ -274,9 +331,22 @@ export function recreateVmFiles(projectRoot, prev, { mode = 'traits', ...runtime taken: takenFingerprintKeys(listVms(projectRoot), { exceptId: prev.id }), }) const vm = buildRecreatedVmRecord(prev, generated, { mode: keep ? 'keep' : 'traits' }) + if (!keep) { + resetSlotSessionState({ + vmId: prev.id, + accountId: prev?.claude?.account_uuid || prev?.account_uuid || null, + vmEpoch: vm.slot_epoch, + }) + } const vmPath = path.join(projectRoot, 'vms', `${prev.id}.json`) atomicWriteJson(vmPath, vm, { mode: 0o600 }) - if (vm.fingerprint?.guest_machine_id) writeGuestMachineIdFile(projectRoot, vm.id, vm.fingerprint.guest_machine_id) + const machineIdPath = path.join(projectRoot, 'vms', prev.id, 'machine-id') + const physicalMachineId = keep + ? prev?.fingerprint?.guest_machine_id || vm.fingerprint?.guest_machine_id + : vm.fingerprint?.guest_machine_id + if (physicalMachineId && (!keep || !fs.existsSync(machineIdPath))) { + writeGuestMachineIdFile(projectRoot, vm.id, physicalMachineId) + } seedFreshCliHome(projectRoot, vm, runtimeOptions) return { vm, vmPath, mode: keep ? 'keep' : 'traits' } } diff --git a/src/lib/vm/vm-registry.mjs b/src/lib/vm/vm-registry.mjs index c989773fe..77cab16ba 100644 --- a/src/lib/vm/vm-registry.mjs +++ b/src/lib/vm/vm-registry.mjs @@ -18,6 +18,8 @@ import { setVmTempPark, expiresAtToMs, ensureSlotSubscriptionType, + replaceSlotOwnedFile, + sealWorkerCredentialFile, } from '../oauth/oauth-credentials.mjs' import { HOLD_MAINTENANCE, @@ -38,6 +40,7 @@ import { activeHoursOf, parseActiveHoursInput } from '../pool/active-hours.mjs' import { rollWindowHistory } from '../pool/window-history.mjs' import { normalizeOwnerId, vmOriginOf, vmOwnerId, VM_ORIGIN } from '../admin/resource-owner.mjs' import { fingerprintDir, syncSlotIdentityTimezoneAndPreset } from '../identity/slot-computer.mjs' +import { toPublicSlotMachineProfile } from '../identity/slot-machine-profile.mjs' import { isCodexVm, normalizeVmKind } from './vm-kind.mjs' import { canClaudeResetCredits } from '../oauth/credential-mode.mjs' import { validTimezone } from '../core/timezone.mjs' @@ -209,6 +212,9 @@ export function summarizeVm(rawVm, projectRoot = null, routing = null) { claude_code_version: vm.claude_code_version || null, stats: vm.stats || {}, fingerprint: vm.fingerprint || null, + ...(kind.kind !== 'codex' && vm.machine_profile + ? { machine_profile: toPublicSlotMachineProfile(vm.machine_profile) } + : {}), schedulable: vm.schedulable !== false, schedule_manual: vm.schedule_manual === true, schedule_disabled_reason: vm.schedule_disabled_reason || null, @@ -1028,13 +1034,22 @@ export function repairSlotSmbios(projectRoot) { * The fingerprint carries its own copy of the zone — leaving that stale would * make the workstation identity disagree with the container clock. */ -export function persistVmTimezone(projectRoot, id, timezone, { source = 'manual' } = {}) { +export function persistVmTimezone(projectRoot, id, timezone, { source = 'manual', locale } = {}) { const zone = validTimezone(timezone) if (!zone) return null + const cleanLocale = typeof locale === 'string' && locale.trim() ? locale.trim() : null const vm = patchVmRecord(projectRoot, id, (rec) => { rec.timezone = zone rec.timezone_source = source - if (rec.fingerprint && typeof rec.fingerprint === 'object') rec.fingerprint.timezone = zone + if (cleanLocale) rec.locale = cleanLocale + if (rec.fingerprint && typeof rec.fingerprint === 'object') { + rec.fingerprint.timezone = zone + if (cleanLocale) rec.fingerprint.locale = cleanLocale + } + if (rec.machine_profile && typeof rec.machine_profile === 'object') { + rec.machine_profile.timezone = zone + if (rec.locale) rec.machine_profile.locale = rec.locale + } }) if (!vm) return null if (fs.existsSync(fingerprintDir(projectRoot, id))) { @@ -1042,6 +1057,79 @@ export function persistVmTimezone(projectRoot, id, timezone, { source = 'manual' syncSlotIdentityTimezoneAndPreset(projectRoot, vm, { timezone: zone, locale: vm.locale }) } catch {} } + const slotDir = path.join(projectRoot, 'vms', id) + const homeDir = path.join(slotDir, 'cli-home') + const credPath = path.join(homeDir, '.claude', 'credentials.json') + if (fs.existsSync(credPath)) { + try { + let prevCredStat = null + try { + prevCredStat = fs.statSync(credPath) + } catch {} + const cred = JSON.parse(fs.readFileSync(credPath, 'utf8')) + if (cred && typeof cred === 'object' && !Array.isArray(cred)) { + let credChanged = false + if (vm.machine_profile && typeof vm.machine_profile === 'object') { + cred.machineProfile = toPublicSlotMachineProfile(vm.machine_profile) + credChanged = true + } else if (cred.machineProfile && typeof cred.machineProfile === 'object') { + cred.machineProfile = { + ...cred.machineProfile, + timezone: zone, + ...(vm.locale ? { locale: vm.locale } : {}), + } + credChanged = true + } + if (credChanged) { + replaceSlotOwnedFile(credPath, `${JSON.stringify(cred, null, 2)}\n`, vm) + sealWorkerCredentialFile(homeDir) + if (prevCredStat && typeof process.getuid === 'function' && process.getuid() === 0) { + try { + fs.chownSync(credPath, prevCredStat.uid, prevCredStat.gid) + } catch {} + } + } + } + } catch {} + } + const runDir = vm.runtime?.worker_run_dir || path.join(slotDir, 'run') + const kernelPath = path.join(runDir, 'kernel.json') + if (fs.existsSync(kernelPath)) { + try { + let prevKernelStat = null + try { + prevKernelStat = fs.statSync(kernelPath) + } catch {} + const kcfg = JSON.parse(fs.readFileSync(kernelPath, 'utf8')) + if (kcfg && typeof kcfg === 'object' && !Array.isArray(kcfg)) { + kcfg.timezone = zone + if (vm.locale) kcfg.locale = vm.locale + if (vm.machine_profile && typeof vm.machine_profile === 'object') { + kcfg.machine_profile = toPublicSlotMachineProfile(vm.machine_profile) + } else if (kcfg.machine_profile && typeof kcfg.machine_profile === 'object') { + kcfg.machine_profile = { + ...kcfg.machine_profile, + timezone: zone, + ...(vm.locale ? { locale: vm.locale } : {}), + } + } + replaceSlotOwnedFile(kernelPath, `${JSON.stringify(kcfg, null, 2)}\n`, vm) + if (prevKernelStat) { + const prevMode = prevKernelStat.mode & 0o777 + if (prevMode) { + try { + fs.chmodSync(kernelPath, prevMode) + } catch {} + } + if (typeof process.getuid === 'function' && process.getuid() === 0) { + try { + fs.chownSync(kernelPath, prevKernelStat.uid, prevKernelStat.gid) + } catch {} + } + } + } + } catch {} + } return summarizeVm(vm) } diff --git a/src/lib/vm/vm-runtime.mjs b/src/lib/vm/vm-runtime.mjs index b35774d21..9da3870c5 100644 --- a/src/lib/vm/vm-runtime.mjs +++ b/src/lib/vm/vm-runtime.mjs @@ -1211,8 +1211,8 @@ function kvmEnvPairs(vm, { uid, gid, memMb, accel, hostName, machineId, shares, `KIN_VM_ID=${vm.id}`, `KIN_VM_NAME=${slotName}`, `KIN_VM_OS=${vm.kernel}`, - `TZ=${vm.timezone || 'UTC'}`, - `LANG=${vm.locale || STANDARD_LOCALE}`, + `TZ=${vm.timezone || vm.fingerprint?.timezone || vm.machine_profile?.timezone || 'UTC'}`, + `LANG=${vm.locale || vm.fingerprint?.locale || vm.machine_profile?.locale || STANDARD_LOCALE}`, `KIN_KVM_UID=${uid}`, `KIN_KVM_GID=${gid}`, `KIN_KVM_MEMORY_MB=${memMb}`, diff --git a/test/unit/agent-summary-routing.test.mjs b/test/unit/agent-summary-routing.test.mjs index 0eb10aa81..53cc382eb 100644 --- a/test/unit/agent-summary-routing.test.mjs +++ b/test/unit/agent-summary-routing.test.mjs @@ -622,3 +622,429 @@ for (const setting of [false, true, 'foreign_only']) { } }) } + +test('4-module single-slot pipeline rewrites CWD, gitStatus, toolu_*, and session_id per hop, reverses chunk-split SSE preserving empty partial_json & thinking, and isolates cross-slot failover', async () => { + const http = await import('node:http') + const { deriveSlotMachineProfile, ensureVmSlotMachineProfile } = await import( + '../../src/lib/identity/slot-machine-profile.mjs' + ) + const { createGitPersonaRewriter } = await import('../../src/lib/identity/git-persona.mjs') + const { mapToolUseIdForAccount } = await import('../../src/lib/identity/tool-id-mapping.mjs') + const { createFailoverMockSchedulerRuntime } = await import('../helpers/mock-scheduler-runtime.mjs') + const { activateFixture, seedEncryptedPackage } = await import('../fixtures/crag-license.mjs') + const { writeWorkerCredentialFile } = await import('../../src/lib/oauth/oauth-credentials.mjs') + + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-4mod-e2e-')) + seedEncryptedPackage(root) + const prevKernelBin = process.env.KIN_KERNEL_BIN + process.env.KIN_KERNEL_BIN = '/bin/true' + const servers = [] + + try { + const routing = { + compatibility: { crag_drop_foreign_thinking: 'foreign_only', slot_persona_rewrite: true }, + failover: { max_same_account_retries: 0, max_account_switches: 2 }, + sticky: { enabled: true, outbound_session: 'rebuild' }, + } + const routingFile = path.join(root, 'routing.json') + fs.writeFileSync(routingFile, JSON.stringify(routing)) + fs.mkdirSync(path.join(root, 'vms'), { recursive: true }) + + // Slot 1: Windows profile (`win32`), Slot 2: Linux profile (`linux`) + const makeSlot = async (id, acct, email, osFamily, handlerFn) => { + const slotDir = path.join(root, 'vms', id) + const homeDir = path.join(slotDir, 'cli-home') + const runDir = path.join(slotDir, 'run') + fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true }) + fs.mkdirSync(runDir, { recursive: true }) + const sock = path.join(runDir, 'kernel.sock') + const tok = path.join(runDir, 'internal.token') + fs.writeFileSync(tok, `tok-${id}\n`) + const mp = deriveSlotMachineProfile({ accountUuid: acct, email, osFamily }) + const vm = { + id, + status: 'running', + dataplane: 'crag', + crag_kernel_version: 'v2', + timezone: mp.timezone, + locale: mp.locale, + machine_profile: mp, + fingerprint: { username: 'kincli' }, + claude: { account_uuid: acct, email, has_access: true, account_tier: 'max' }, + runtime: { type: 'docker', kernel_socket: sock, worker_run_dir: runDir, worker_token_file: tok }, + } + ensureVmSlotMachineProfile(vm, { accountUuid: acct, email }) + writeWorkerCredentialFile(homeDir, { + type: 'oauth', + access_token: `sk-ant-oat01-${id}`, + refresh_token: `sk-ant-ort01-${id}`, + expires_at: Math.floor(Date.now() / 1000) + 3600, + account_uuid: acct, + machineProfile: mp, + }) + fs.writeFileSync(path.join(root, 'vms', `${id}.json`), JSON.stringify(vm)) + activateFixture(root, vm) + const healthPayload = { + ok: true, + engine: 'rust', + runtime_variant: 'crag-v2', + ready_slots: 2, + capabilities: [ + 'caller_cwd', + 'generation_controls_v3', + 'headless_claude_bridge_v1', + 'request_safeguards', + 'slot_machine_profile_v1', + ], + } + rememberRustHealth({ vmId: id }, { ok: true, health: healthPayload }) + const srv = http.createServer((req, res) => { + if (req.url === '/internal/health') { + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify(healthPayload)) + return + } + return handlerFn(req, res, vm) + }) + await new Promise((resolve) => srv.listen(sock, resolve)) + servers.push(srv) + return vm + } + + const slot1Envelopes = [] + const slot2Envelopes = [] + let failSlot1 = true + const callerToolId = 'toolu_01AbCdEfGhIjKlMnOpQrStUv' + const serverIssuedRawToolId = 'toolu_01ZzYyXxWwVvUuTtSsRrQqPp' + const callerCommitSha = 'a1b2c3d' + + const vm1 = await makeSlot('vm-s1', 'acct-slot-1', 'dev1@alpha.dev', 'win32', async (req, res) => { + const chunks = [] + for await (const c of req) chunks.push(c) + slot1Envelopes.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))) + if (failSlot1) { + res.writeHead(529, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ type: 'error', error: { type: 'overloaded_error', message: 'overloaded' } })) + return + } + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.end() + }) + + const vm2 = await makeSlot('vm-s2', 'acct-slot-2', 'dev2@beta.org', 'linux', async (req, res, vm) => { + const chunks = [] + for await (const c of req) chunks.push(c) + const env = JSON.parse(Buffer.concat(chunks).toString('utf8')) + slot2Envelopes.push(env) + + const slot2MappedServerToolId = mapToolUseIdForAccount(vm.machine_profile.tool_id_seed, serverIssuedRawToolId) + const gitRew = createGitPersonaRewriter(vm.machine_profile) + const virtualProj = `${vm.machine_profile.work_root}/my-app` + const mappedSha = gitRew.mapCommitSha(callerCommitSha) + + res.writeHead(200, { 'content-type': 'text/event-stream' }) + const frames = [ + `event: message_start\ndata: ${JSON.stringify({ + type: 'message_start', + message: { + id: 'msg_s2', + type: 'message', + role: 'assistant', + model: 'claude-opus-4-6', + content: [], + stop_reason: null, + usage: { input_tokens: 12, output_tokens: 0 }, + }, + })}\n\n`, + `event: content_block_start\ndata: ${JSON.stringify({ type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: `Keep ${virtualProj} raw in thinking` } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig_exact_untouched_999' } })}\n\n`, + `event: content_block_stop\ndata: ${JSON.stringify({ type: 'content_block_stop', index: 0 })}\n\n`, + `event: content_block_start\ndata: ${JSON.stringify({ type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } })}\n\n`, + // Split virtual path across tiny deltas to exercise streaming holdback + content_block_stop flush + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: `Checked ${virtualProj.slice(0, 8)}` } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: `${virtualProj.slice(8)}/src/index.ts at ${mappedSha}` } })}\n\n`, + `event: content_block_stop\ndata: ${JSON.stringify({ type: 'content_block_stop', index: 1 })}\n\n`, + `event: content_block_start\ndata: ${JSON.stringify({ type: 'content_block_start', index: 2, content_block: { type: 'tool_use', id: slot2MappedServerToolId, name: 'Read', input: {} } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '' } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: `{"file_path":"${virtualProj.slice(0, 6)}` } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: `${virtualProj.slice(6)}/README.md"}` } })}\n\n`, + `event: content_block_stop\ndata: ${JSON.stringify({ type: 'content_block_stop', index: 2 })}\n\n`, + `event: message_delta\ndata: ${JSON.stringify({ type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 25 } })}\n\n`, + `event: message_stop\ndata: ${JSON.stringify({ type: 'message_stop' })}\n\n`, + ] + const joined = frames.join('') + for (let i = 0; i < joined.length; i += 17) { + res.write(joined.slice(i, i + 17)) + } + res.end() + }) + + let pickIdx = 0 + const order = [vm1, vm2] + const scheduler = { + async selectAndReserve() { + if (pickIdx >= order.length) return { ok: false, reason: 'exhausted' } + const chosen = order[pickIdx++] + return { + ok: true, + vmId: chosen.id, + accountId: chosen.claude.account_uuid, + vm: chosen, + exec: { + vmId: chosen.id, + vm: chosen, + homeDir: path.join(root, 'vms', chosen.id, 'cli-home'), + projectRoot: root, + workerStatus: { + runtime_variant: 'crag-v2', + capabilities: [ + 'caller_cwd', + 'generation_controls_v3', + 'headless_claude_bridge_v1', + 'request_safeguards', + 'slot_machine_profile_v1', + ], + }, + }, + release() {}, + } + }, + markSuccess() {}, + markCooldown() {}, + releaseAccountSessions() {}, + } + const sticky = new StickyRouter({ dataDir: root, config: routing }) + const thinkingDb = new DatabaseSync(':memory:') + const thinkingOwners = new ThinkingOwnerStore({ db: thinkingDb }) + const { thinkingSignatureKey } = await import('../../src/lib/pool/thinking-owner.mjs') + // Record foreign thinking signature against Slot 1 so failover to Slot 2 drops it under foreign_only + thinkingOwners.record( + [thinkingSignatureKey({ type: 'thinking', signature: 'sig_slot1_foreign_secret_signature' })], + 'acct-slot-1', + ) + + const runner = new FailoverRunner({ + scheduler, + schedulerRuntime: createFailoverMockSchedulerRuntime({ scheduler }), + stickyRouter: sticky, + config: routing.failover, + }) + + const sseChunks = [] + const resObj = { + headersSent: false, + statusCode: 200, + on() {}, + once() {}, + off() {}, + write(chunk) { + sseChunks.push(String(chunk)) + return true + }, + end(chunk) { + if (chunk) sseChunks.push(String(chunk)) + }, + } + + const inboundBody = { + model: 'claude-opus-4-6', + max_tokens: 1024, + stream: true, + system: [ + { type: 'text', text: "You are Claude Code, Anthropic's official CLI for Claude." }, + { + type: 'text', + text: [ + '\n/Users/alice/work/my-app\n', + '# Environment', + ' - Primary working directory: /Users/alice/work/my-app', + ' - Platform: darwin', + '# gitStatus', + 'Current branch: main', + 'Author: Alice Real ', + 'user.name=Alice Real', + 'user.email=alice.real@corp.internal', + 'Recent commits:', + `${callerCommitSha} feat: initial setup`, + ].join('\n'), + }, + ], + tools: [{ name: 'Read', description: 'Read file', input_schema: { type: 'object', properties: {} } }], + safeguards: [ + { + type: 'dangerous_tool_use', + classifier_context: { prior_turn_context: [{ tool_use_ids: [callerToolId] }] }, + }, + ], + messages: [ + { role: 'user', content: 'Inspect /Users/alice/work/my-app/package.json' }, + { + role: 'assistant', + content: [ + { type: 'thinking', thinking: 'Slot 1 thought', signature: 'sig_slot1_foreign_secret_signature' }, + { + type: 'tool_use', + id: callerToolId, + name: 'Read', + input: { file_path: '/Users/alice/work/my-app/package.json' }, + }, + ], + }, + { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: callerToolId, content: 'name: my-app' }], + }, + ], + metadata: { + user_id: JSON.stringify({ + device_id: OFFICIAL_AGENT_DEVICE, + account_uuid: '', + session_id: OFFICIAL_AGENT_SESSION, + }), + }, + } + + const handler = createHandleProtocol({ + json(_res, status, body) { + resObj.statusCode = status + resObj.body = body + resObj.headersSent = true + }, + writeSSEHeaders(res) { + res.headersSent = true + }, + readBody: async () => structuredClone(inboundBody), + requireAuth: () => true, + cfg: { + rewrite: { enabled: false }, + intercept: { rules: [] }, + distill: { enabled: false }, + limits: { max_body_bytes: 1024 * 1024, upstream_timeout_ms: 5000, stream_idle_timeout_ms: 5000 }, + paths: { data: root, project: root }, + }, + requestLog: { start: () => ({ request_id: 'req-4mod-e2e', mode: 'normal', t0: Date.now() }), finish() {} }, + stickyRouter: sticky, + accountQuota: { ingestHeaders() {} }, + apiKeyStore: { acquire: () => ({ ok: true }), release() {}, recordUsage() {} }, + apiScheduler: {}, + apiEndpointStore: {}, + settings: { get: (_k, fb) => fb }, + stats: { errors: 0, requests: 0, by_route: {}, passthrough: 0, rewrite: 0, convert: 0 }, + routingConfigPath: routingFile, + routingConfig: routing, + groupsRepo: { rateMultiplier: () => 1 }, + thinkingOwners, + failoverRunner: runner, + }) + + const req = new EventEmitter() + Object.assign(req, { + id: 'req-4mod-e2e', + method: 'POST', + url: '/v1/messages', + headers: { + authorization: 'Bearer sk-test', + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'x-app': 'cli', + 'anthropic-version': '2023-06-01', + 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20', + 'anthropic-dangerous-direct-browser-access': 'true', + 'x-claude-code-session-id': OFFICIAL_AGENT_SESSION, + 'x-stainless-lang': 'js', + 'x-stainless-package-version': '0.128.0', + 'x-stainless-os': 'MacOS', + 'x-stainless-arch': 'arm64', + 'x-stainless-runtime': 'node', + 'x-stainless-runtime-version': 'v24.3.0', + 'x-stainless-retry-count': '0', + 'x-stainless-timeout': '600', + }, + apiKeyKind: 'managed', + apiKeyRecord: { id: 'k-test' }, + }) + + await handler.handleProtocol(req, resObj, 'anthropic.messages', '/v1/messages') + assert.equal(resObj.statusCode, 200, JSON.stringify(resObj.body)) + assert.equal(slot1Envelopes.length, 1, 'Attempt 1 hit Slot 1 (win32)') + assert.equal(slot2Envelopes.length, 1, 'Attempt 2 failed over cleanly to Slot 2 (linux)') + + const env1 = slot1Envelopes[0] + const env2 = slot2Envelopes[0] + + // 1. Slot 1 (win32) vs Slot 2 (linux) received clean per-slot forward rewrites with zero Slot 1 contamination in Slot 2! + const raw1 = JSON.stringify(env1) + const raw2 = JSON.stringify(env2) + assert.doesNotMatch(raw1, /\/Users\/alice|alice\.real@corp\.internal|Alice Real/) + assert.doesNotMatch(raw2, /\/Users\/alice|alice\.real@corp\.internal|Alice Real/) + assert.ok(!raw2.includes('C:\\\\Users\\\\'), 'Slot 2 (linux) must never inherit Slot 1 (win32) paths') + assert.equal(env2.caller_cwd, `${vm2.machine_profile.work_root}/my-app`) + assert.notEqual( + env1.headers['x-claude-code-session-id'], + env2.headers['x-claude-code-session-id'], + 'Outbound session IDs are isolated per slot', + ) + assert.notEqual(env2.headers['x-claude-code-session-id'], OFFICIAL_AGENT_SESSION) + + const s1ToolId = env1.body.messages[1].content.find((b) => b.type === 'tool_use').id + const s2ToolId = env2.body.messages[1].content.find((b) => b.type === 'tool_use').id + assert.notEqual(s1ToolId, callerToolId) + assert.notEqual(s2ToolId, callerToolId) + assert.notEqual(s1ToolId, s2ToolId, 'Feistel toolu_* IDs are isolated per account') + assert.deepEqual(env2.body.safeguards[0].classifier_context.prior_turn_context[0].tool_use_ids, [s2ToolId]) + + // Foreign thinking signature from Slot 1 must be stripped before reaching Slot 2 + const s2AssistantTypes = env2.body.messages[1].content.map((b) => b.type) + assert.equal(s2AssistantTypes.includes('thinking'), false, 'Slot 1 foreign thinking block stripped on Slot 2 hop') + + // 2. Live SSE output reversed back to canonical caller CWD, commit SHA, and toolu_* ID while preserving "" partial_json & thinking! + const dataEvents = sseChunks + .join('') + .split('\n') + .filter((l) => l.startsWith('data:')) + .map((l) => JSON.parse(l.slice(5).trim())) + + const thinkingText = dataEvents + .filter((e) => e.type === 'content_block_delta' && e.delta?.type === 'thinking_delta') + .map((e) => e.delta.thinking) + .join('') + assert.equal( + thinkingText, + `Keep ${vm2.machine_profile.work_root}/my-app raw in thinking`, + 'thinking_delta must NEVER be modified', + ) + const sigText = dataEvents + .filter((e) => e.type === 'content_block_delta' && e.delta?.type === 'signature_delta') + .map((e) => e.delta.signature) + .join('') + assert.equal(sigText, 'sig_exact_untouched_999', 'signature_delta must NEVER be modified') + + const textOut = dataEvents + .filter((e) => e.type === 'content_block_delta' && e.delta?.type === 'text_delta') + .map((e) => e.delta.text) + .join('') + assert.equal(textOut, `Checked /Users/alice/work/my-app/src/index.ts at ${callerCommitSha}`) + + const toolStart = dataEvents.find((e) => e.type === 'content_block_start' && e.content_block?.type === 'tool_use') + assert.equal( + toolStart.content_block.id, + serverIssuedRawToolId, + 'Outbound tool_use.id decrypted back to canonical ID', + ) + + const jsonDeltas = dataEvents + .filter((e) => e.type === 'content_block_delta' && e.delta?.type === 'input_json_delta') + .map((e) => e.delta.partial_json) + assert.equal(jsonDeltas[0], '', 'Empty partial_json: "" frame must be preserved verbatim') + assert.deepEqual(JSON.parse(jsonDeltas.join('')), { file_path: '/Users/alice/work/my-app/README.md' }) + + thinkingDb.close() + sticky.db?.close?.() + } finally { + clearRustHealthCache() + for (const s of servers) await new Promise((resolve) => s.close(resolve)) + if (prevKernelBin === undefined) delete process.env.KIN_KERNEL_BIN + else process.env.KIN_KERNEL_BIN = prevKernelBin + fs.rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/test/unit/go-worker-client.test.mjs b/test/unit/go-worker-client.test.mjs index 6578b220a..47f2bbddc 100644 --- a/test/unit/go-worker-client.test.mjs +++ b/test/unit/go-worker-client.test.mjs @@ -20,7 +20,13 @@ import { import { prepareCliHopBody } from '../../src/lib/protocol/outbound-attempt.mjs' import { callerAutoCompactWindow, defaultSeedPolicy, sanitizeInboundBody } from '../../src/lib/protocol/seed-policy.mjs' import { extractOpenaiUsage } from '../../src/lib/protocol/openai-usage.mjs' -import { callRustKernel, rustKernelHealth } from '../../src/lib/transport/rust-kernel-client.mjs' +import { + callRustKernel, + notifyRustKernelSlotReset, + rustKernelHealth, +} from '../../src/lib/transport/rust-kernel-client.mjs' +import { ensureVmSlotMachineProfile } from '../../src/lib/identity/slot-machine-profile.mjs' +import { resetSlotSessionState } from '../../src/lib/protocol/issued-tool-replay.mjs' import { callCodexKernel, streamCodexKernel } from '../../src/lib/transport/codex-kernel-client.mjs' import { forwardApi, readApiJson } from '../../src/lib/transport/api-kernel-client.mjs' import { normalizeRedaction } from '../../src/lib/redaction/policy.mjs' @@ -2649,3 +2655,422 @@ test('V4: CRAG V4 happy-path and repaired retries never forward spoofed caller h 'x-claude-code-session-id': '11111111-1111-4111-8111-111111111111', }) }) + +test('slot machine_profile isolates x-claude-code-session-id per account/slot/epoch and gates /internal/v1/slot/reset on capability', async () => { + const vmA = { + id: 'vm-slot-a', + dataplane: 'crag', + crag_kernel_version: 'v2', + claude: { account_uuid: 'acct-a', email: 'a@example.com' }, + } + const vmB = { + id: 'vm-slot-b', + dataplane: 'crag', + crag_kernel_version: 'v2', + claude: { account_uuid: 'acct-b', email: 'b@example.com' }, + } + ensureVmSlotMachineProfile(vmA, { accountUuid: 'acct-a', email: 'a@example.com' }) + ensureVmSlotMachineProfile(vmB, { accountUuid: 'acct-b', email: 'b@example.com' }) + + const callerSession = '11111111-1111-4111-8111-111111111111' + const parentSession = '22222222-2222-4222-8222-222222222222' + const reqHeaders = { + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'x-app': 'cli', + 'x-claude-code-session-id': callerSession, + 'x-claude-code-parent-session-id': parentSession, + } + const baseBody = { + model: 'claude-sonnet-5-5', + max_tokens: 256, + messages: [{ role: 'user', content: 'hello' }], + } + const makeExec = (vm) => ({ + vmId: vm.id, + homeDir: `/tmp/${vm.id}-nonexistent`, + vm, + workerStatus: { + runtime_variant: 'crag-v2', + capabilities: ['generation_controls_v3', 'headless_claude_bridge_v1', 'slot_machine_profile_v1'], + }, + }) + + const envA1 = await workerEnvelope({ + body: baseBody, + reqHeaders, + exec: makeExec(vmA), + routing: {}, + stream: true, + cliHop: true, + cragPrint: true, + officialTraffic: true, + officialPassthrough: false, + }) + const envB1 = await workerEnvelope({ + body: baseBody, + reqHeaders, + exec: makeExec(vmB), + routing: {}, + stream: true, + cliHop: true, + cragPrint: true, + officialTraffic: true, + officialPassthrough: false, + }) + const sidA1 = envA1.envelope.headers['x-claude-code-session-id'] + const pidA1 = envA1.envelope.headers['x-claude-code-parent-session-id'] + const sidB1 = envB1.envelope.headers['x-claude-code-session-id'] + assert.match(sidA1, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + assert.match(pidA1, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + assert.notEqual(sidA1, callerSession) + assert.notEqual(pidA1, parentSession) + assert.notEqual(sidA1, sidB1, 'Slot A and Slot B must emit isolated outbound session IDs') + + resetSlotSessionState({ sessionId: callerSession }) + const envA2 = await workerEnvelope({ + body: baseBody, + reqHeaders, + exec: makeExec(vmA), + routing: {}, + stream: true, + cliHop: true, + cragPrint: true, + officialTraffic: true, + officialPassthrough: false, + }) + assert.notEqual( + envA2.envelope.headers['x-claude-code-session-id'], + sidA1, + 'sticky reset must rotate derived session ID', + ) + + // Capability gate on notifyRustKernelSlotReset + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-slot-reset-cap-')) + try { + const sock = path.join(tmp, 'kernel.sock') + const tok = path.join(tmp, 'internal.token') + fs.writeFileSync(tok, 'reset-tok\n') + let advertiseCap = false + const resetBodies = [] + const srv = http.createServer(async (req, res) => { + if (req.url === '/internal/health') { + res.setHeader('content-type', 'application/json') + res.end( + JSON.stringify({ + ok: true, + engine: 'rust', + ready_slots: 1, + capabilities: advertiseCap ? ['slot_machine_profile_v1'] : ['headless_claude_bridge_v1'], + }), + ) + return + } + if (req.url === '/internal/v1/slot/reset') { + const chunks = [] + for await (const c of req) chunks.push(c) + resetBodies.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))) + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ ok: true })) + return + } + res.statusCode = 404 + res.end() + }) + await new Promise((resolve) => srv.listen(sock, resolve)) + try { + const exec = { + vmId: 'vm-reset-1', + vm: { id: 'vm-reset-1', runtime: { kernel_socket: sock, worker_token_file: tok, worker_run_dir: tmp } }, + } + const skipped = await notifyRustKernelSlotReset(exec, { sessionId: 'sess-1', wipeDisk: false }) + assert.equal(skipped.skipped, true) + assert.equal(skipped.reason, 'capability_missing') + assert.equal(resetBodies.length, 0) + + advertiseCap = true + const sent = await notifyRustKernelSlotReset(exec, { sessionId: 'sess-1', wipeDisk: false }) + assert.equal(sent.ok, true) + assert.deepEqual(resetBodies, [{ session_id: 'sess-1', wipe_disk: false }]) + } finally { + await new Promise((resolve) => srv.close(resolve)) + } + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('slotEpoch explicit threading, count_tokens 4-module isolation, and SSE split-hex SHA + truncated flush', async () => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const { createCwdMapper } = await import('../../src/lib/identity/cwd-mapping.mjs') + const { createGitPersonaRewriter } = await import('../../src/lib/identity/git-persona.mjs') + const { deriveAccountSlotSessionId } = await import('../../src/lib/identity/tool-id-mapping.mjs') + const { createOutboundSlotSseRewriter } = await import('../../src/lib/protocol/handle-protocol.mjs') + const { handleUserCountTokens } = await import('../../src/lib/protocol/user-count-tokens.mjs') + + const profile = deriveSlotMachineProfile({ + accountUuid: 'acct-count-tokens-1111', + email: 'ct@example.com', + osFamily: 'darwin', + }) + + // 1. Explicit slotEpoch in workerEnvelope overrides empty/divergent header epoch + const callerSession = 'cccccccc-dddd-4eee-8fff-1234567890ab' + const parentSession = '22222222-3333-4444-8555-666666666666' + const vm = { + id: 'vm-epoch-1', + dataplane: 'crag', + crag_kernel_version: 'v2', + claude: { account_uuid: 'acct-count-tokens-1111' }, + machine_profile: profile, + } + const exec = { + vmId: vm.id, + homeDir: '/tmp/vm-epoch-nonexistent', + vm, + workerStatus: { + runtime_variant: 'crag-v2', + capabilities: ['generation_controls_v3', 'headless_claude_bridge_v1', 'native_handoff_v1'], + }, + } + const envEpoch7 = await workerEnvelope({ + body: { model: 'claude-sonnet-5-5', max_tokens: 128, messages: [{ role: 'user', content: 'hi' }] }, + reqHeaders: { + 'x-claude-code-session-id': callerSession, + 'x-claude-code-parent-session-id': parentSession, + 'x-app': 'cli', + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + }, + exec, + routing: {}, + stream: true, + cliHop: true, + cragPrint: true, + officialTraffic: true, + officialPassthrough: false, + slotEpoch: 7, + }) + assert.equal( + envEpoch7.envelope.headers['x-claude-code-session-id'], + deriveAccountSlotSessionId({ + sessionIdSeed: profile.session_id_seed, + clientSessionId: callerSession, + vmId: vm.id, + slotEpoch: 7, + }), + ) + + // 2. count_tokens rewrites CWD, Git commit SHA, toolu_* IDs, and maps session headers + const capturedCountTokens = [] + const rawSha = '1234567890abcdef1234567890abcdef12345678' + const rawToolId = 'toolu_01AbCdEfGhIjKlMnOpQrStUv' + const rawPriorGuardToolId = 'toolu_01ZyXwVuTsRqPoNmLkJiHgFe' + const ctBody = { + model: 'claude-sonnet-5-5', + system: [ + { + type: 'text', + text: '# Environment\n- Primary working directory: /Users/realdev/work/demo\n- Platform: darwin\n# gitStatus\nRecent commits:\n1234567890abcdef1234567890abcdef12345678 initial commit', + }, + ], + safeguards: [ + { + type: 'auto_mode', + tool_use_ids: [rawToolId], + classifier_context: { + prior_turn_context: [{ tool_use_ids: [rawPriorGuardToolId] }], + }, + }, + ], + messages: [ + { + role: 'assistant', + content: [ + { type: 'tool_use', id: rawToolId, name: 'Read', input: { file_path: '/Users/realdev/work/demo/app.js' } }, + ], + }, + { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: rawToolId, content: 'ok' }], + }, + ], + } + const ctReq = { + headers: { + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'anthropic-version': '2023-06-01', + 'anthropic-dangerous-direct-browser-access': 'true', + 'anthropic-beta': 'claude-code-20250219', + 'x-app': 'cli', + 'x-client-request-id': 'req_ct_slot_01', + 'x-stainless-lang': 'js', + 'x-stainless-os': 'Linux', + 'x-stainless-arch': 'x64', + 'x-stainless-runtime': 'node', + 'x-stainless-runtime-version': 'v24.3.0', + 'x-stainless-package-version': '0.128.0', + 'x-stainless-retry-count': '0', + 'x-stainless-timeout': '600', + 'x-claude-code-session-id': callerSession, + 'x-claude-code-parent-session-id': parentSession, + }, + apiKeyKind: 'master', + } + let ctResponse = null + await handleUserCountTokens( + ctReq, + {}, + { + requireAuth: () => true, + cfg: { paths: { project: '/tmp/nonexistent' }, limits: { max_body_bytes: 1024 * 1024 } }, + getRoutingConfig: () => ({ compatibility: { count_tokens: true } }), + stickyRouter: { extractPoolKey: () => null }, + readBody: async () => structuredClone(ctBody), + json: (_res, status, payload) => { + ctResponse = { status, payload } + return ctResponse + }, + getPoolScheduler: () => ({ + peekAccount: async () => ({ + ok: true, + vmId: vm.id, + vm: { ...vm, credential_mode: 'oauth' }, + workerStatus: { capabilities: ['count_tokens_v1'] }, + exec, + accountId: 'acct-count-tokens-1111', + }), + }), + countTokensViaKernel: async (_exec, opts) => { + capturedCountTokens.push(opts) + return { ok: true, status: 200, body: { input_tokens: 42 }, headers: {} } + }, + }, + ) + assert.equal(ctResponse?.status, 200) + assert.equal(capturedCountTokens.length, 1) + const sentCt = capturedCountTokens[0] + assert.notEqual(sentCt.headers['x-claude-code-session-id'], callerSession) + assert.notEqual(sentCt.headers['x-claude-code-parent-session-id'], parentSession) + assert.equal( + sentCt.headers['x-claude-code-session-id'], + deriveAccountSlotSessionId({ + sessionIdSeed: profile.session_id_seed, + clientSessionId: callerSession, + vmId: vm.id, + slotEpoch: 0, + }), + ) + const sentBodyStr = JSON.stringify(sentCt.body) + assert.equal(sentBodyStr.includes('/Users/realdev/work/demo'), false, 'count_tokens must rewrite caller CWD') + assert.equal(sentBodyStr.includes(rawSha), false, 'count_tokens must rewrite Git commit SHA') + assert.equal(sentBodyStr.includes(rawToolId), false, 'count_tokens must rewrite toolu_* IDs') + assert.equal( + sentBodyStr.includes(rawPriorGuardToolId), + false, + 'count_tokens must rewrite safeguards classifier_context.prior_turn_context[].tool_use_ids', + ) + + // 3. SSE rewriter: split 40-hex Git SHA across chunks + truncated stream flush() + const cwdMapper = createCwdMapper(profile, { callerCwd: '/Users/realdev/work/demo' }) + const gitRewriter = createGitPersonaRewriter(profile) + const mappedSha = gitRewriter.mapCommitSha(rawSha) + assert.notEqual(mappedSha, rawSha) + const virtualCwd = cwdMapper.getMappingSnapshot().virtualCwd + const rewriter = createOutboundSlotSseRewriter({ profile, cwdMapper, gitRewriter }) + const outLines = [] + const feed = (l) => outLines.push(...rewriter.transformLine(l)) + feed('event: content_block_start') + feed(`data: ${JSON.stringify({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } })}`) + feed('') + // Split mappedSha across 3 chunks + leave trailing virtualCwd prefix un-terminated (truncated stream!) + feed('event: content_block_delta') + feed( + `data: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `Commit ${mappedSha.slice(0, 12)}` } })}`, + ) + feed('') + feed('event: content_block_delta') + feed( + `data: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: mappedSha.slice(12, 26) } })}`, + ) + feed('') + feed('event: content_block_delta') + feed( + `data: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `${mappedSha.slice(26)} at ${virtualCwd}/src/index.js` } })}`, + ) + feed('') + // Truncated stream (NO content_block_stop): flush() must drain buffered path/SHA tail once + outLines.push(...rewriter.flush()) + assert.deepEqual(rewriter.flush(), [], 'flush() must be idempotent') + const assembledText = outLines + .filter((l) => l.startsWith('data:')) + .map((l) => JSON.parse(l.slice(5).trim())) + .filter((ev) => ev.type === 'content_block_delta' && ev.delta?.type === 'text_delta') + .map((ev) => ev.delta.text) + .join('') + assert.equal(assembledText, `Commit ${rawSha} at /Users/realdev/work/demo/src/index.js`) +}) + +test('M3: prepareWorkerPayload derives x-claude-code-session-id ONCE so CLI hop header === body metadata.user_id.session_id', async () => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const { deriveAccountSlotSessionId } = await import('../../src/lib/identity/tool-id-mapping.mjs') + + const profile = deriveSlotMachineProfile({ + accountUuid: 'acct-m3-single-derive-1', + email: 'm3@example.com', + osFamily: 'darwin', + pepper: 'test-pepper-m3', + }) + const vm = { + id: 'vm-m3-cli-hop', + dataplane: 'wrap', + claude: { account_uuid: 'acct-m3-single-derive-1' }, + machine_profile: profile, + } + const rawCallerSession = 'aaaaaaaa-1111-4222-8333-444444444444' + const expectedD1 = deriveAccountSlotSessionId({ + sessionIdSeed: profile.session_id_seed, + clientSessionId: rawCallerSession, + vmId: vm.id, + slotEpoch: 0, + }) + const body = { + model: 'claude-sonnet-4-6', + max_tokens: 128, + metadata: { + user_id: JSON.stringify({ + device_id: profile.device_id, + account_uuid: 'acct-m3-single-derive-1', + session_id: expectedD1, + }), + }, + messages: [{ role: 'user', content: 'hi' }], + } + const identity = { + deviceId: profile.device_id, + machineId: profile.machine_id, + callerSessionId: expectedD1, + fingerprint: { locale: 'en_US.UTF-8' }, + } + const prepared = prepareWorkerPayload({ + body, + reqHeaders: { + 'user-agent': 'claude-cli/2.1.321 (external, cli)', + 'x-app': 'cli', + 'x-claude-code-session-id': rawCallerSession, + }, + exec: { vmId: vm.id, homeDir: '/tmp/vm-m3-nonexistent', vm }, + identity, + routing: {}, + cliHop: true, + cragPrint: false, + officialTraffic: true, + slotEpoch: 0, + }) + const headerSid = prepared.headers['x-claude-code-session-id'] + const bodyMeta = JSON.parse(prepared.gated.metadata.user_id) + assert.equal(headerSid, expectedD1, 'CLI hop x-claude-code-session-id must NOT be double-derived') + assert.equal( + headerSid, + bodyMeta.session_id, + 'outbound header x-claude-code-session-id must equal body metadata.user_id.session_id', + ) +}) diff --git a/test/unit/guest-identity.test.mjs b/test/unit/guest-identity.test.mjs index 527df3a72..950e18c95 100644 --- a/test/unit/guest-identity.test.mjs +++ b/test/unit/guest-identity.test.mjs @@ -254,3 +254,80 @@ test('merge without guest hardware leaves previous fingerprint.hardware', () => assert.equal(out.hardware.cpu_model, 'keep-cpu') assert.equal(out.hardware.cpu_cores, 2) }) + +test('mergeGuestFingerprint preserves 3-OS macOS machine_profile against Linux x64 guest facts (F2)', () => { + const mpDeviceId = 'aa'.repeat(32) + const mpMachineId = 'bb'.repeat(32) + const physicalGuestMachineId = 'cc'.repeat(16) + const macProfile = { + os_family: 'darwin', + platform: 'macos', + platform_raw: 'darwin', + os_id: 'macos', + os_pretty: 'macOS Sequoia 15.4', + os_version: 'Darwin 24.4.0', + kernel_release: '24.4.0', + arch: 'arm64', + stainless_os: 'MacOS', + stainless_arch: 'arm64', + hostname: 'alexs-macbook-pro', + device_id: mpDeviceId, + machine_id: mpMachineId, + timezone: 'America/New_York', + locale: 'en_US.UTF-8', + hardware: { + cpu_model: 'Apple M4 Pro', + cpu_cores: 12, + memory_bytes: 24 * 1024 ** 3, + mac: '52:54:00:aa:bb:cc', + dmi: { manufacturer: 'Apple Inc.', product: 'Mac16,6' }, + shell: 'zsh', + package_managers: 'brew,npm', + runtimes: 'node,python', + }, + } + const out = mergeGuestFingerprint( + { + ...macProfile, + guest_machine_id: physicalGuestMachineId, + official_machine_id: 'stale-official-mid', + session_id: 'sess-keep', + }, + { + hostname: 'wks-debian-host', + os_id: 'debian', + os_pretty: 'Debian GNU/Linux 13', + kernel_release: '6.12.20-amd64', + arch: 'amd64', + goos: 'linux', + machine_id: 'dd'.repeat(16), + hardware: { + cpu_model: 'QEMU Virtual CPU', + cpu_cores: 2, + memory_bytes: 4 * 1024 ** 3, + mac: '52:54:00:ff:ff:ff', + dmi: { manufacturer: 'QEMU', product: 'Standard PC' }, + shell: 'bash', + package_managers: 'apt', + runtimes: 'node', + }, + }, + { machineProfile: macProfile }, + ) + assert.equal(out.os_family, 'darwin') + assert.equal(out.stainless_os, 'MacOS') + assert.equal(out.stainless_arch, 'arm64') + assert.equal(out.os_id, 'macos') + assert.equal(out.os_pretty, 'macOS Sequoia 15.4') + assert.equal(out.kernel_release, '24.4.0') + assert.equal('linux_kernel' in out, false) + assert.equal(out.hostname, 'alexs-macbook-pro') + assert.equal(out.guest_hostname, 'wks-debian-host') + assert.equal(out.device_id, mpDeviceId) + assert.equal(out.machine_id, mpMachineId) + assert.equal(out.guest_machine_id, physicalGuestMachineId) + assert.equal(out.official_machine_id, undefined) + assert.equal(out.hardware.cpu_model, 'Apple M4 Pro') + assert.equal(out.hardware.dmi.product, 'Mac16,6') + assert.equal(out.hardware.mac, '52:54:00:aa:bb:cc') +}) diff --git a/test/unit/oauth-credentials.test.mjs b/test/unit/oauth-credentials.test.mjs index d962f453d..ac9fc5230 100644 --- a/test/unit/oauth-credentials.test.mjs +++ b/test/unit/oauth-credentials.test.mjs @@ -29,8 +29,13 @@ import { ensureSlotSubscriptionType, slotUidGidFromHomeDir, ensureSlotClaudeOwnership, + syncSlotClaudeProfileJson, + wipeSlotSessionAndTelemetryState, REFRESH_SKEW_MS, } from '../../src/lib/oauth/oauth-credentials.mjs' +import { createImportCommit } from '../../src/lib/oauth/import-commit.mjs' +import { getSlotSessionEpoch } from '../../src/lib/protocol/issued-tool-replay.mjs' +import { writeKernelConfig } from '../../src/lib/transport/rust-kernel-supervisor.mjs' test('needsRefresh: missing/expired/skew', () => { const now = 1_000_000_000_000 @@ -707,6 +712,432 @@ test('custom duration quota park (quota_24h_header) is preserved by auth healing } }) +test('single-slot machine_profile co-dispatches in credentials.json + kernel.json, dual-writes .claude.json, and resets on account swap', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-slot-profile-swap-')) + try { + const vmId = 'vm-swap-01' + const slotDir = path.join(root, 'vms', vmId) + const homeDir = path.join(slotDir, 'cli-home') + const runDir = path.join(slotDir, 'run') + fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true }) + fs.mkdirSync(runDir, { recursive: true }) + const vmPath = path.join(root, 'vms', `${vmId}.json`) + fs.writeFileSync( + vmPath, + JSON.stringify({ + id: vmId, + status: 'running', + dataplane: 'crag', + crag_kernel_version: 'v2', + proxy: { id: 'px-1', host: '127.0.0.1', port: 1080, scheme: 'socks5', url: 'socks5://127.0.0.1:1080' }, + fingerprint: { username: 'kincli' }, + runtime: { type: 'docker', worker_run_dir: runDir }, + claude: {}, + }), + ) + + const schedulerDeletes = [] + const resetCalls = [] + const restartCalls = [] + const { commitImportedOauth } = createImportCommit({ + cfg: { paths: { project: root } }, + accountQuota: { rebindToVm() {}, clearGrantRevokeLeftover() {} }, + schedulerRuntime: { + async deleteSticky(filter) { + schedulerDeletes.push(filter) + return { deleted: 1 } + }, + }, + importWorkerCredential: async (exec, cred) => { + writeWorkerCredentialFile(exec.homeDir, cred) + return { ok: true, status: 200 } + }, + notifyRustKernelSlotReset: async (_exec, opts) => { + resetCalls.push(opts) + return { ok: true } + }, + restartRustKernel: async (_exec, opts) => { + restartCalls.push(opts) + return { ok: true } + }, + }) + + const http = await import('node:http') + const sock = path.join(runDir, 'kernel.sock') + const tokenFile = path.join(runDir, 'internal.token') + fs.writeFileSync(tokenFile, 'tok-swap\n') + const srv = http.createServer((_req, res) => { + res.setHeader('content-type', 'application/json') + res.end( + JSON.stringify({ + ok: true, + engine: 'rust', + cli_pid: 99, + ready_slots: 1, + capabilities: ['slot_machine_profile_v1'], + }), + ) + }) + await new Promise((resolve) => srv.listen(sock, resolve)) + + const prevMock = process.env.KIN_CRS_MOCK + delete process.env.KIN_CRS_MOCK + let saved1 + let epochBefore + try { + // 1. First account bind (`acct-alpha`) + const existing1 = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + existing1.runtime = { ...existing1.runtime, kernel_socket: sock, worker_token_file: tokenFile } + fs.writeFileSync(vmPath, JSON.stringify(existing1)) + const r1 = await commitImportedOauth({ + vmId, + vmPath, + existing: existing1, + oauth: { + access_token: 'sk-ant-oat01-ALPHA', + refresh_token: 'sk-ant-ort01-ALPHA', + expires_at: Math.floor(Date.now() / 1000) + 3600, + email: 'alpha.user@company.io', + account_uuid: 'acct-alpha-1111', + org_uuid: 'org-alpha-1111', + }, + skipOfficialCc: true, + }) + assert.equal(r1.ok, true, JSON.stringify(r1.error)) + assert.equal(restartCalls.length, 0) + + saved1 = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.ok(['darwin', 'win32', 'linux'].includes(saved1.machine_profile.os_family)) + assert.match(saved1.machine_profile.device_id, /^[0-9a-f]{64}$/) + assert.equal(saved1.fingerprint.username, 'kincli') + + const credRaw1 = fs.readFileSync(path.join(homeDir, '.claude', 'credentials.json'), 'utf8') + assert.doesNotMatch(credRaw1, /alpha\.user@company\.io/i) + const cred1 = JSON.parse(credRaw1) + assert.equal(cred1.machineProfile.device_id, saved1.machine_profile.device_id) + assert.equal(cred1.machineProfile.stainless_os, saved1.machine_profile.stainless_os) + assert.equal(cred1.machineProfile.tool_id_seed, undefined) + assert.equal(cred1.machineProfile.session_id_seed, undefined) + + for (const rel of ['.claude.json', path.join('.claude', '.claude.json')]) { + const cj = JSON.parse(fs.readFileSync(path.join(homeDir, rel), 'utf8')) + assert.equal(cj.hasCompletedOnboarding, true) + assert.equal(cj.userID, saved1.machine_profile.device_id) + assert.equal(cj.machineID, saved1.machine_profile.machine_id) + assert.equal(cj.oauthAccount.accountUuid, 'acct-alpha-1111') + assert.equal('emailAddress' in cj.oauthAccount, false) + } + + writeKernelConfig(root, saved1, { + routing: {}, + publish: false, + capabilities: ['slot_machine_profile_v1'], + }) + const kernelCfg1 = JSON.parse(fs.readFileSync(path.join(runDir, 'kernel.json'), 'utf8')) + assert.equal(kernelCfg1.machine_profile.device_id, saved1.machine_profile.device_id) + assert.equal(kernelCfg1.telemetry.identity.platform_raw, saved1.machine_profile.os_family) + if (saved1.machine_profile.os_family !== 'linux') { + assert.equal(kernelCfg1.telemetry.dmi_dir, undefined) + } + + // Seed stale session & telemetry artifacts before swapping to `acct-beta` + for (const staleRel of [ + path.join('run', 'work', '.crag-sessions', 'sess-old.json'), + path.join('cli-home', '.claude', 'crag-v3-continuations', 'cont-old.json'), + path.join('run', 'telemetry-upload.log'), + path.join('cli-home', '.claude', 'telemetry', 'batch-1.json'), + ]) { + const target = path.join(slotDir, staleRel) + fs.mkdirSync(path.dirname(target), { recursive: true }) + fs.writeFileSync(target, 'stale') + } + epochBefore = getSlotSessionEpoch({ vmId }) + + // 2. Swap slot credential to `acct-beta` -> full wipe + sticky unbind + epoch bump + kernel reset/restart + const existing2 = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + existing2.runtime = { ...existing2.runtime, kernel_socket: sock, worker_token_file: tokenFile } + fs.writeFileSync(vmPath, JSON.stringify(existing2)) + const r2 = await commitImportedOauth({ + vmId, + vmPath, + existing: existing2, + oauth: { + access_token: 'sk-ant-oat01-BETA', + refresh_token: 'sk-ant-ort01-BETA', + expires_at: Math.floor(Date.now() / 1000) + 3600, + email: 'beta.user@other.org', + account_uuid: 'acct-beta-2222', + org_uuid: 'org-beta-2222', + }, + skipOfficialCc: true, + }) + assert.equal(r2.ok, true, JSON.stringify(r2.error)) + } finally { + await new Promise((resolve) => srv.close(resolve)) + if (prevMock === undefined) delete process.env.KIN_CRS_MOCK + else process.env.KIN_CRS_MOCK = prevMock + } + + const saved2 = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.notEqual(saved2.machine_profile.device_id, saved1.machine_profile.device_id) + assert.equal(fs.existsSync(path.join(slotDir, 'run', 'work', '.crag-sessions')), false) + assert.equal(fs.existsSync(path.join(slotDir, 'cli-home', '.claude', 'crag-v3-continuations')), false) + assert.equal(fs.existsSync(path.join(slotDir, 'run', 'telemetry-upload.log')), false) + assert.equal(fs.existsSync(path.join(slotDir, 'cli-home', '.claude', 'telemetry')), false) + assert.equal(schedulerDeletes.length, 1) + assert.equal(saved2.slot_epoch, 1, 'account swap must persist incremented slot_epoch on vm.json (M8)') + assert.ok(getSlotSessionEpoch({ vmId, persistedVmEpoch: saved2.slot_epoch }) > epochBefore) + assert.equal(resetCalls.length, 1) + assert.equal(restartCalls.length, 1) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) + +test('writeKernelConfig omits dmi_dir when machine_profile is active and uses merged target telemetry', async () => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const { writeKernelConfig } = await import('../../src/lib/transport/rust-kernel-supervisor.mjs') + + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-kernel-mp-dmi-')) + try { + const vmId = 'vm-mp-linux-1' + const slotDir = path.join(root, 'vms', vmId) + fs.mkdirSync(path.join(slotDir, 'cli-home', '.claude'), { recursive: true }) + fs.mkdirSync(path.join(slotDir, 'run'), { recursive: true }) + const vmPath = path.join(root, 'vms', `${vmId}.json`) + // Disk record lacks machine_profile and has stale telemetry disabled; merged target carries Linux machine_profile + fs.writeFileSync( + vmPath, + JSON.stringify({ + id: vmId, + kernel: 'ubuntu-24.04', + dataplane: 'crag', + crag_kernel_version: 'v2', + runtime: { type: 'docker' }, + seed_policy: { telemetry_disabled: true }, + }), + ) + const linuxProfile = deriveSlotMachineProfile({ + accountUuid: 'acct-linux-dmi-1', + email: 'linux@example.com', + osFamily: 'linux', + }) + const targetVm = { + id: vmId, + kernel: 'ubuntu-24.04', + dataplane: 'crag', + crag_kernel_version: 'v2', + runtime: { type: 'docker' }, + timezone: 'America/Los_Angeles', + locale: 'en_US.UTF-8', + proxy: { id: 'px-merged-1' }, + seed_policy: { telemetry_disabled: false }, + machine_profile: linuxProfile, + } + const res = writeKernelConfig(root, targetVm, { + token: 'tok-dmi-test', + routing: { inference: { dataplane: 'crag', crag_kernel_version: 'v2' } }, + publish: false, + capabilities: ['slot_machine_profile_v1'], + }) + const cfg = JSON.parse(fs.readFileSync(res.configPath, 'utf8')) + assert.equal(cfg.machine_profile.os_family, 'linux') + assert.equal(cfg.telemetry?.enabled, true) + assert.equal( + cfg.telemetry?.proxy_id, + 'px-merged-1', + 'buildNativeTelemetry must read merged target, not stale disk record', + ) + assert.equal( + cfg.telemetry?.dmi_dir, + undefined, + 'dmi_dir must be omitted even on Linux when machine_profile is active so kin-computer DMI cannot contradict it', + ) + assert.equal(cfg.telemetry?.identity?.device_id, linuxProfile.device_id) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) + +test('panel-routes reset-fingerprint preserves physical guest_machine_id and credential/clear strips machine_profile from kernel.json', async () => { + const { Readable } = await import('node:stream') + const { createPanelHandler } = await import('../../src/lib/admin/panel-routes.mjs') + const { deriveSlotMachineProfile, toPublicSlotMachineProfile } = await import( + '../../src/lib/identity/slot-machine-profile.mjs' + ) + const { writeKernelConfig } = await import('../../src/lib/transport/rust-kernel-supervisor.mjs') + + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-panel-fp-clear-')) + const prevMock = process.env.KIN_CRS_MOCK + process.env.KIN_CRS_MOCK = '1' + try { + const vmId = 'vm-kvm-fp-clear' + const slotDir = path.join(root, 'vms', vmId) + const homeDir = path.join(slotDir, 'cli-home') + const fpDir = path.join(slotDir, 'kvm', 'fingerprint') + fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true }) + fs.mkdirSync(path.join(homeDir, '.kin', 'crag-v2'), { recursive: true }) + fs.writeFileSync( + path.join(homeDir, '.kin', 'crag-v2', 'manifest.json'), + JSON.stringify({ + software_version: '5.0.2', + officialClaude: { path: 'claude-code-2.1.321/claude', version: '2.1.321' }, + capabilities: ['slot_machine_profile_v1'], + }), + ) + fs.mkdirSync(path.join(slotDir, 'run'), { recursive: true }) + fs.mkdirSync(fpDir, { recursive: true }) + const physicalMid = 'aabbccdd11223344556677889900eeff' + fs.writeFileSync( + path.join(fpDir, 'identity.json'), + JSON.stringify({ + hostname: 'kvm-phys-box', + machine_id: physicalMid, + uuid: '12345678-1234-4123-8123-123456789abc', + }), + ) + fs.writeFileSync(path.join(fpDir, 'qemu-smbios.args'), '-uuid 12345678-1234-4123-8123-123456789abc\n') + fs.writeFileSync(path.join(slotDir, 'machine-id'), `${physicalMid}\n`) + + const initialProfile = deriveSlotMachineProfile({ + accountUuid: 'acct-panel-fp-1', + email: 'fp@example.com', + osFamily: 'darwin', + }) + const vmPath = path.join(root, 'vms', `${vmId}.json`) + const vm = { + id: vmId, + name: vmId, + kernel: 'ubuntu-24.04', + dataplane: 'crag', + crag_kernel_version: 'v2', + runtime: { type: 'kvm' }, + timezone: 'America/New_York', + locale: 'en_US.UTF-8', + claude: { account_uuid: 'acct-panel-fp-1', email: 'fp@example.com', has_access: true }, + machine_profile: initialProfile, + fingerprint: { + hostname: initialProfile.hostname, + device_id: initialProfile.device_id, + machine_id: initialProfile.machine_id, + guest_machine_id: physicalMid, + }, + } + fs.writeFileSync(vmPath, JSON.stringify(vm, null, 2)) + writeWorkerCredentialFile(homeDir, { + access_token: 'tok-fp-1', + refresh_token: 'ref-fp-1', + expires_at: Date.now() + 3600_000, + account_uuid: 'acct-panel-fp-1', + machineProfile: toPublicSlotMachineProfile(initialProfile), + }) + writeKernelConfig(root, vm, { + token: 'tok-k-fp', + routing: { inference: { dataplane: 'crag', crag_kernel_version: 'v2' } }, + publish: false, + }) + + const responses = [] + const handlePanel = createPanelHandler({ + cfg: { paths: { project: root, data: root } }, + routingConfig: { inference: { dataplane: 'crag', crag_kernel_version: 'v2' } }, + readBody: async () => ({}), + requireAuth(req) { + req.panelUser = 'admin' + req.panelRole = 'admin' + return true + }, + json(_res, status, body) { + responses.push({ status, body }) + return { status, body } + }, + }) + + const reqReset = Readable.from([]) + reqReset.method = 'POST' + await handlePanel(reqReset, {}, new URL(`http://localhost/api/panel/vms/${vmId}/reset-fingerprint`)) + assert.equal(responses[0].status, 200) + const afterReset = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal( + afterReset.fingerprint.guest_machine_id, + physicalMid, + 'reset-fingerprint must keep physical guest_machine_id', + ) + assert.equal(fs.readFileSync(path.join(slotDir, 'machine-id'), 'utf8').trim(), physicalMid) + assert.notEqual( + afterReset.machine_profile.device_id, + initialProfile.device_id, + 'reset-fingerprint must reseed profile', + ) + const kernelAfterReset = JSON.parse(fs.readFileSync(path.join(slotDir, 'run', 'kernel.json'), 'utf8')) + assert.equal(kernelAfterReset.machine_profile.device_id, afterReset.machine_profile.device_id) + + const reqClear = Readable.from([]) + reqClear.method = 'POST' + await handlePanel(reqClear, {}, new URL(`http://localhost/api/panel/vms/${vmId}/credential/clear`)) + assert.equal(responses[1].status, 200) + const afterClear = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(afterClear.machine_profile, undefined) + const kernelAfterClear = JSON.parse(fs.readFileSync(path.join(slotDir, 'run', 'kernel.json'), 'utf8')) + assert.equal( + kernelAfterClear.machine_profile, + undefined, + 'credential/clear must remove stale machine_profile from kernel.json', + ) + assert.equal(fs.existsSync(path.join(homeDir, '.claude', 'credentials.json')), false) + } finally { + if (prevMock === undefined) delete process.env.KIN_CRS_MOCK + else process.env.KIN_CRS_MOCK = prevMock + fs.rmSync(root, { recursive: true, force: true }) + } +}) + +test('writeWorkerCredentialFile honors options.vm.machine_profile without on-disk vm.json and obeys explicit precedence', async () => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-cred-vm-mp-')) + try { + const homeDir = path.join(root, 'isolated-slot', 'cli-home') + fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true }) + const winProfile = deriveSlotMachineProfile({ + accountUuid: 'acct-edge-vm-mp-1', + email: 'edge@example.com', + osFamily: 'win32', + }) + const macProfile = deriveSlotMachineProfile({ + accountUuid: 'acct-edge-vm-mp-1', + email: 'edge@example.com', + osFamily: 'darwin', + }) + const cred = { + access_token: 'sk-ant-oat01-VMMP', + refresh_token: 'sk-ant-ort01-VMMP', + expires_at: Math.floor(Date.now() / 1000) + 3600, + account_uuid: 'acct-edge-vm-mp-1', + org_uuid: 'org-edge-vm-mp-1', + email: 'edge@example.com', + } + + // Without vm.json on disk, options.vm.machine_profile must win over re-derivation + writeWorkerCredentialFile(homeDir, cred, { vm: { id: 'vm-no-disk', machine_profile: winProfile } }) + const writtenFromVm = JSON.parse(fs.readFileSync(path.join(homeDir, '.claude', 'credentials.json'), 'utf8')) + assert.equal(writtenFromVm.machineProfile.os_family, 'win32') + assert.equal(writtenFromVm.machineProfile.stainless_os, 'Windows') + assert.equal(writtenFromVm.machineProfile.device_id, winProfile.device_id) + + // Explicit options.machineProfile still takes precedence over options.vm.machine_profile + writeWorkerCredentialFile(homeDir, cred, { + machineProfile: macProfile, + vm: { id: 'vm-no-disk', machine_profile: winProfile }, + }) + const writtenExplicit = JSON.parse(fs.readFileSync(path.join(homeDir, '.claude', 'credentials.json'), 'utf8')) + assert.equal(writtenExplicit.machineProfile.os_family, 'darwin') + assert.equal(writtenExplicit.machineProfile.stainless_os, 'MacOS') + assert.equal(writtenExplicit.machineProfile.device_id, macProfile.device_id) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) + test('temp park SSOT keeps claude.* and top-level identical across expired quota -> auth cooldown and writes 0600 (A2/A3)', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-oauth-a2-a3-')) try { diff --git a/test/unit/official-fingerprint.test.mjs b/test/unit/official-fingerprint.test.mjs index c3e31b4c9..96c9f6a0a 100644 --- a/test/unit/official-fingerprint.test.mjs +++ b/test/unit/official-fingerprint.test.mjs @@ -102,3 +102,59 @@ test('discardLeftoverClaudeJson is a no-op when missing', () => { assert.deepEqual(discardLeftoverClaudeJson(root), { removed: false, conflict: false }) fs.rmSync(root, { recursive: true, force: true }) }) + +test('applyOfficialFingerprintToVm preserves 3-OS machine_profile device_id and machine_id (F1)', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-fp-mp-')) + const home = path.join(root, 'cli-home') + fs.mkdirSync(path.join(home, '.claude'), { recursive: true }) + const mpDeviceId = '11'.repeat(32) + const mpMachineId = '22'.repeat(32) + const physicalGuestMachineId = '33'.repeat(16) + fs.writeFileSync( + path.join(home, '.claude.json'), + JSON.stringify({ + userID: mpDeviceId, + machineID: mpMachineId, + oauthAccount: { accountUuid: 'acc-mp-1' }, + }), + ) + fs.writeFileSync( + path.join(home, '.claude', 'kin-identity.json'), + JSON.stringify({ + device_id: mpMachineId, + account_uuid: 'acc-mp-1', + }), + ) + const vmPath = path.join(root, 'vm-mp.json') + fs.writeFileSync( + vmPath, + JSON.stringify({ + id: 'vm-mp', + machine_profile: { + schema: 'slot-machine-profile/1', + os_family: 'darwin', + device_id: mpDeviceId, + machine_id: mpMachineId, + }, + fingerprint: { + device_id: mpDeviceId, + machine_id: mpMachineId, + guest_machine_id: physicalGuestMachineId, + official_machine_id: mpMachineId, + }, + }), + ) + try { + const res = applyOfficialFingerprintToVm(vmPath, home) + assert.equal(res.wrote, true) + const vm = JSON.parse(fs.readFileSync(vmPath, 'utf8')) + assert.equal(vm.fingerprint.device_id, mpDeviceId) + assert.equal(vm.fingerprint.machine_id, mpMachineId) + assert.equal(vm.fingerprint.guest_machine_id, physicalGuestMachineId) + assert.equal(vm.fingerprint.official_machine_id, undefined) + const ident = JSON.parse(fs.readFileSync(path.join(home, '.claude', 'kin-identity.json'), 'utf8')) + assert.equal(ident.device_id, mpDeviceId) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/test/unit/panel-public-boot.test.mjs b/test/unit/panel-public-boot.test.mjs index fd89f393b..6acaf26c4 100644 --- a/test/unit/panel-public-boot.test.mjs +++ b/test/unit/panel-public-boot.test.mjs @@ -7,6 +7,8 @@ import { publicSlotBoot, publicVmBootView, } from '../../src/lib/admin/panel-api.mjs' +import { deriveSlotMachineProfile } from '../../src/lib/identity/slot-machine-profile.mjs' +import { summarizeVm } from '../../src/lib/vm/vm-registry.mjs' test('publicAllocatedProxy uses publicProxy and drops credentials', () => { const bound = { @@ -239,3 +241,44 @@ test('publicPhysicalFeatures falls back to public machine spec', () => { assert.equal(features.observed_at, null) assert.equal(features.timezone, 'America/Los_Angeles') }) + +test('publicPhysicalFeatures and summarizeVm expose 3-OS machine_profile traits without leaking secret seeds or IDs', () => { + for (const [idx, acct] of ['acct-mac-1', 'acct-win-2', 'acct-lin-3'].entries()) { + const osOverride = ['darwin', 'win32', 'linux'][idx] + const mp = deriveSlotMachineProfile({ + accountUuid: acct, + email: `secret.${idx}@private.corp`, + osFamily: osOverride, + }) + const vm = { + id: `vm-os-${idx}`, + name: `Slot ${osOverride}`, + status: 'running', + dataplane: 'crag', + crag_kernel_version: 'v2', + timezone: mp.timezone, + locale: mp.locale, + machine_profile: mp, + fingerprint: {}, + claude: { account_uuid: acct, email: `secret.${idx}@private.corp`, has_access: true }, + } + const features = publicPhysicalFeatures(vm) + assert.equal(features.os_family, osOverride) + assert.equal(features.stainless_os, mp.stainless_os) + assert.equal(features.os_version, mp.os_version) + assert.equal(features.machine_home, mp.machine_home) + assert.ok(features.cpu_cores >= 8) + const rawFeatures = JSON.stringify(features) + assert.ok(!rawFeatures.includes(mp.device_id)) + assert.ok(!rawFeatures.includes(mp.machine_id)) + assert.ok(!rawFeatures.includes(mp.tool_id_seed)) + assert.ok(!rawFeatures.includes(mp.session_id_seed)) + assert.ok(!rawFeatures.includes(`secret.${idx}@private.corp`)) + + const summary = summarizeVm(vm) + assert.equal(summary.machine_profile.os_family, osOverride) + assert.equal(summary.machine_profile.stainless_os, mp.stainless_os) + assert.equal(summary.machine_profile.tool_id_seed, undefined) + assert.equal(summary.machine_profile.session_id_seed, undefined) + } +}) diff --git a/test/unit/rust-kernel-supervisor.test.mjs b/test/unit/rust-kernel-supervisor.test.mjs index 4ae791d7e..bf1671b14 100644 --- a/test/unit/rust-kernel-supervisor.test.mjs +++ b/test/unit/rust-kernel-supervisor.test.mjs @@ -125,3 +125,101 @@ test('writeKernelConfig uses executable /run/kin/work/.crag-native-assets for cu assert.equal(kvmDoc.asset_dir, '/run/kin/work/.crag-native-assets') assert.equal(kvmDoc.work_dir, '/run/kin/work') }) + +test('writeKernelConfig gates machine_profile & telemetry.identity on slot_machine_profile_v1 or CRAG >= 5.0.2 (M6)', async (t) => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-sup-mp-gate-')) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + const routing = { inference: { engine: 'rust', dataplane: 'crag', crag_kernel_version: 'v2' } } + const profile = deriveSlotMachineProfile({ + accountUuid: 'acct-gate-test-1', + email: 'gate@example.com', + osFamily: 'darwin', + pepper: 'test-pepper-m6', + }) + + // 1. Legacy crag-v2 5.0.0 manifest (no slot_machine_profile_v1 capability) keeps dmi_dir and omits machine_profile + const oldVmId = 'vm-crag-500' + const oldManifestDir = path.join(root, 'vms', oldVmId, 'cli-home', '.kin', 'crag-v2') + fs.mkdirSync(oldManifestDir, { recursive: true }) + fs.writeFileSync( + path.join(oldManifestDir, 'manifest.json'), + JSON.stringify({ + software_version: '5.0.0', + officialClaude: { path: 'claude-code-2.1.321/claude', version: '2.1.321' }, + capabilities: ['generation_controls_v3', 'headless_claude_bridge_v1'], + }), + ) + const oldWritten = writeKernelConfig( + root, + { + id: oldVmId, + dataplane: 'crag', + crag_kernel_version: 'v2', + machine_profile: profile, + seed_policy: { telemetry_disabled: false }, + }, + { routing, token: 'tok-500', publish: false }, + ) + const oldDoc = JSON.parse(fs.readFileSync(oldWritten.configPath, 'utf8')) + assert.equal(oldDoc.machine_profile, undefined, 'crag-v2 5.0.0 must NOT receive machine_profile') + assert.equal(oldDoc.telemetry?.dmi_dir, '/etc/kin-dmi', 'crag-v2 5.0.0 must keep legacy dmi_dir') + assert.equal(oldDoc.telemetry?.identity?.platform_raw, undefined, 'crag-v2 5.0.0 must keep legacy telemetry.identity') + + // 2. Capable crag-v2 (slot_machine_profile_v1 capability) receives machine_profile & 3-OS telemetry.identity + const capVmId = 'vm-crag-cap' + const capManifestDir = path.join(root, 'vms', capVmId, 'cli-home', '.kin', 'crag-v2') + fs.mkdirSync(capManifestDir, { recursive: true }) + fs.writeFileSync( + path.join(capManifestDir, 'manifest.json'), + JSON.stringify({ + software_version: '5.0.1', + officialClaude: { path: 'claude-code-2.1.321/claude', version: '2.1.321' }, + capabilities: ['generation_controls_v3', 'headless_claude_bridge_v1', 'slot_machine_profile_v1'], + }), + ) + const capWritten = writeKernelConfig( + root, + { + id: capVmId, + dataplane: 'crag', + crag_kernel_version: 'v2', + machine_profile: profile, + seed_policy: { telemetry_disabled: false }, + }, + { routing, token: 'tok-cap', publish: false }, + ) + const capDoc = JSON.parse(fs.readFileSync(capWritten.configPath, 'utf8')) + assert.equal(capDoc.machine_profile?.device_id, profile.device_id) + assert.equal(capDoc.machine_profile?.tool_id_seed, undefined) + assert.equal(capDoc.telemetry?.dmi_dir, undefined) + assert.equal(capDoc.telemetry?.identity?.platform_raw, 'darwin') + assert.equal(capDoc.telemetry?.identity?.device_id, profile.device_id) + + // 3. Version >= 5.0.2 manifest also enables machine_profile even if capability list omits the string + const verVmId = 'vm-crag-502' + const verManifestDir = path.join(root, 'vms', verVmId, 'cli-home', '.kin', 'crag-v2') + fs.mkdirSync(verManifestDir, { recursive: true }) + fs.writeFileSync( + path.join(verManifestDir, 'manifest.json'), + JSON.stringify({ + software_version: '5.0.2', + officialClaude: { path: 'claude-code-2.1.321/claude', version: '2.1.321' }, + capabilities: ['generation_controls_v3', 'headless_claude_bridge_v1'], + }), + ) + const verWritten = writeKernelConfig( + root, + { + id: verVmId, + dataplane: 'crag', + crag_kernel_version: 'v2', + machine_profile: profile, + seed_policy: { telemetry_disabled: false }, + }, + { routing, token: 'tok-502', publish: false }, + ) + const verDoc = JSON.parse(fs.readFileSync(verWritten.configPath, 'utf8')) + assert.equal(verDoc.machine_profile?.device_id, profile.device_id) + assert.equal(verDoc.telemetry?.dmi_dir, undefined) +}) diff --git a/test/unit/scheduler-m1b-pools-api.test.mjs b/test/unit/scheduler-m1b-pools-api.test.mjs index 2e685afff..63a887aaf 100644 --- a/test/unit/scheduler-m1b-pools-api.test.mjs +++ b/test/unit/scheduler-m1b-pools-api.test.mjs @@ -1139,3 +1139,89 @@ test('POST/PATCH /api/panel/pools validates and persists required_runtime_capabi h.cleanup() } }) + +test('DELETE /api/panel/scheduler/sticky clears targeted session replay/epoch without Node StickyRouter state I/O or global/disk wipes (M1/M10)', async () => { + const { createIssuedToolReplay, getSlotSessionEpoch } = await import('../../src/lib/protocol/issued-tool-replay.mjs') + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-sticky-del-sync-')) + try { + const vmsDir = path.join(dir, 'vms') + fs.mkdirSync(vmsDir, { recursive: true }) + fs.writeFileSync(path.join(vmsDir, 'vm-crag-1.json'), JSON.stringify(SAMPLE_VMS[0], null, 2)) + const apiKeyStore = new ApiKeyStore({ dataDir: dir }) + const repo = new SchedulerPoolsRepo(apiKeyStore.db) + const replay = createIssuedToolReplay() + const pool = repo.insert({ id: 'pool_sticky_sync', name: 'Sticky Sync Pool', provider_scope: 'anthropic' }) + repo.setMembers(pool.id, [{ node_type: 'claude_vm', node_id: 'vm-crag-1' }]) + + const sessionId = '99999999-8888-4777-8666-555555555555' + const otherSessionId = '11111111-2222-4333-8444-555555555555' + const now = Date.now() + for (const sid of [sessionId, otherSessionId]) { + repo.upsertStickyBinding({ + scope_kind: 'session', + pool_id: pool.id, + model_family: 'claude', + identity_id: sid, + session_id: sid, + machine_id: 'd'.repeat(64), + node_type: 'claude_vm', + node_id: 'vm-crag-1', + bound_at_ms: now, + last_seen_ms: now, + expires_at_ms: now + 60_000, + }) + } + + const prefix = [{ role: 'user', content: 'run tool' }] + const issued = [ + { type: 'tool_use', id: 'toolu_01AaBbCcDdEeFfGgHhIiJjKk', name: 'Bash', input: { cmd: 'pwd' }, caller: 'model' }, + ] + replay.remember(JSON.stringify(['key1', sessionId, 'claude-sonnet-5-5', 'acct-sticky-1', 0]), prefix, issued) + replay.remember(JSON.stringify(['key1', otherSessionId, 'claude-sonnet-5-5', 'acct-sticky-1', 0]), prefix, issued) + assert.equal(replay.stats().scopes, 2) + const epochBefore = getSlotSessionEpoch({ sessionId, vmId: 'vm-crag-1' }) + const otherEpochBefore = getSlotSessionEpoch({ sessionId: otherSessionId, vmId: 'vm-crag-1' }) + + const handler = createSchedulerPoolsHandler({ + getDb: () => apiKeyStore.db, + getVms: () => [SAMPLE_VMS[0]], + cfg: { paths: { project: dir, data: dir } }, + apiKeyStore, + json: (_res, status, payload) => ({ status, body: payload }), + readBody, + }) + + // 1. Targeted session deletion clears ONLY that session's replay/epoch + const req = makeRequest('DELETE', `/api/panel/scheduler/sticky?session_id=${sessionId}`) + const u = new URL(`http://localhost/api/panel/scheduler/sticky?session_id=${sessionId}`) + const res = await handler(req, {}, u.pathname, u) + assert.equal(res.status, 200) + assert.equal(res.body.ok, true) + assert.ok( + getSlotSessionEpoch({ sessionId, vmId: 'vm-crag-1' }) > epochBefore, + 'targeted session slotEpoch must advance on session sticky delete', + ) + assert.equal( + getSlotSessionEpoch({ sessionId: otherSessionId, vmId: 'vm-crag-1' }), + otherEpochBefore, + 'unrelated session epoch must remain untouched', + ) + assert.equal(replay.stats().scopes, 1, 'only deleted session replay scope must be purged') + + // 2. Bulk sticky deletion (`?all=1`) must NOT trigger global resetSlotSessionState({ all: true }) (M10) + const reqAll = makeRequest('DELETE', '/api/panel/scheduler/sticky?all=1') + const uAll = new URL('http://localhost/api/panel/scheduler/sticky?all=1') + const resAll = await handler(reqAll, {}, uAll.pathname, uAll) + assert.equal(resAll.status, 200) + assert.equal( + getSlotSessionEpoch({ sessionId: otherSessionId, vmId: 'vm-crag-1' }), + otherEpochBefore, + 'bulk sticky delete must NOT bump globalSlotEpoch', + ) + assert.equal(replay.stats().scopes, 1, 'bulk sticky delete must NOT wipe all issuedTools replay scopes') + + apiKeyStore.db.close() + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/slot-machine-env.test.mjs b/test/unit/slot-machine-env.test.mjs new file mode 100644 index 000000000..7795b5ee0 --- /dev/null +++ b/test/unit/slot-machine-env.test.mjs @@ -0,0 +1,1501 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { describe, it } from 'node:test' +import { createCwdMapper } from '../../src/lib/identity/cwd-mapping.mjs' +import { resolveVmCharacteristicHeaders } from '../../src/lib/identity/crs-headers.mjs' +import { applyCrsUnofficialPersona, officialSystemEnvFromIdentity } from '../../src/lib/identity/crs-persona.mjs' +import { createGitPersonaRewriter, feistelHex } from '../../src/lib/identity/git-persona.mjs' +import { buildOfficialContinuationText } from '../../src/lib/identity/official-cc-system-2.1.241.mjs' +import { rememberComputer, syncSlotIdentityTimezoneAndPreset } from '../../src/lib/identity/slot-computer.mjs' +import { resolveSystemPromptSpec } from '../../src/lib/identity/system-prompt-spec.mjs' +import { + DARWIN_HARDWARE_CATALOG, + DISALLOWED_PERSONA_USERNAMES, + LINUX_DISTROS, + PC_DMI_CATALOG, + buildTelemetryIdentityFromProfile, + deriveSlotMachineProfile, + ensureVmSlotMachineProfile, + nativeCcProjectSlug, + projectProfileToVmFingerprint, + toPublicSlotMachineProfile, +} from '../../src/lib/identity/slot-machine-profile.mjs' +import { + deriveAccountSlotSessionId, + mapToolUseIdForAccount, + rewriteRequestToolIds, + rewriteResponseToolIds, + unmapToolUseIdFromAccount, +} from '../../src/lib/identity/tool-id-mapping.mjs' +import { loadVmIdentity, persistVmSettings } from '../../src/lib/identity/vm-identity.mjs' +import { buildKinSeedJson } from '../../src/lib/identity/workstation-profile.mjs' +import { workerEnvelope } from '../../src/lib/transport/go-worker-client.mjs' +import { ensureKvmMachineRecord } from '../../src/lib/vm/kvm-machine.mjs' +import { slotHost } from '../../src/lib/vm/slot-host.mjs' +import { persistVmTimezone } from '../../src/lib/vm/vm-registry.mjs' +import { buildKvmRunArgs } from '../../src/lib/vm/vm-runtime.mjs' + +const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +const HEX64_RE = /^[0-9a-f]{64}$/ + +describe('slot-machine-profile', () => { + it('embeds complete 3-OS physical hardware catalogs meeting minimums', () => { + assert.ok(DARWIN_HARDWARE_CATALOG.length >= 12) + assert.ok(PC_DMI_CATALOG.length >= 16) + assert.ok(LINUX_DISTROS.length >= 6) + assert.ok(DARWIN_HARDWARE_CATALOG.some((m) => m.arch === 'arm64')) + assert.ok(DARWIN_HARDWARE_CATALOG.some((m) => m.arch === 'x64')) + }) + + it('derives authentic darwin, win32, and linux profiles with exact CC 2.1.321 wire grammar', () => { + const mac = deriveSlotMachineProfile({ + accountUuid: '11111111-2222-4333-8444-555555555555', + email: 'team01@corp.example.com', + osFamily: 'darwin', + }) + assert.equal(mac.os_family, 'darwin') + assert.equal(mac.stainless_os, 'MacOS') + assert.ok(mac.stainless_arch === 'arm64' || mac.stainless_arch === 'x64') + assert.match(mac.os_version, /^Darwin 2[34]\.\d+\.\d+$/) + assert.equal(mac.shell, 'zsh') + assert.equal(mac.machine_home, `/Users/${mac.username}`) + assert.equal(mac.ls_group, 'staff') + assert.equal(mac.path_sep, '/') + assert.match(mac.device_id, HEX64_RE) + assert.match(mac.machine_id, HEX64_RE) + + const win = deriveSlotMachineProfile({ + accountUuid: '22222222-3333-4444-8555-666666666666', + email: 'team02@corp.example.com', + osFamily: 'win32', + }) + assert.equal(win.os_family, 'win32') + assert.equal(win.stainless_os, 'Windows') + assert.equal(win.stainless_arch, 'x64') + assert.match(win.os_version, /^Windows 1[01] Pro 10\.0\.\d+$/) + assert.ok(!win.os_version.includes('Windows_NT')) + assert.equal(win.shell, 'bash') + assert.equal(win.machine_home, `C:\\Users\\${win.username}`) + assert.equal(win.path_sep, '\\') + + const lin = deriveSlotMachineProfile({ + accountUuid: '33333333-4444-4555-8666-777777777777', + email: 'team03@corp.example.com', + osFamily: 'linux', + }) + assert.equal(lin.os_family, 'linux') + assert.equal(lin.stainless_os, 'Linux') + assert.equal(lin.stainless_arch, 'x64') + assert.match(lin.os_version, /^Linux 6\.\d+\.\d+/) + assert.equal(lin.shell, 'bash') + assert.equal(lin.machine_home, `/home/${lin.username}`) + assert.equal(lin.ls_group, lin.username) + assert.ok(lin.linux_distro_id) + assert.ok(lin.linux_kernel) + }) + + it('guarantees determinism per account and zero cross-account correlation on batch emails', () => { + const a1 = deriveSlotMachineProfile({ + accountUuid: 'aaaaaaaa-0001-4000-8000-000000000001', + email: 'team01@batch-domain.io', + }) + const a2 = deriveSlotMachineProfile({ + accountUuid: 'aaaaaaaa-0001-4000-8000-000000000001', + email: 'TEAM01@batch-domain.io', + }) + assert.deepEqual(a1, a2) + + const seenDevices = new Set() + const seenToolSeeds = new Set() + const osCounts = { darwin: 0, win32: 0, linux: 0 } + for (let i = 1; i <= 60; i++) { + const p = deriveSlotMachineProfile({ + accountUuid: `bbbbbbbb-0000-4000-8000-${String(i).padStart(12, '0')}`, + email: `team${String(i).padStart(2, '0')}@batch-domain.io`, + }) + osCounts[p.os_family] += 1 + assert.ok(!DISALLOWED_PERSONA_USERNAMES.has(p.username)) + assert.ok(!p.username.startsWith('team')) + assert.match(p.git_persona.email, /^[a-z]+-[a-z]+-\d{3}@users\.noreply\.github\.com$/) + assert.ok(!seenDevices.has(p.device_id)) + assert.ok(!seenToolSeeds.has(p.tool_id_seed)) + seenDevices.add(p.device_id) + seenToolSeeds.add(p.tool_id_seed) + } + assert.ok(osCounts.darwin > 5 && osCounts.win32 > 5 && osCounts.linux > 5) + }) + + it('strips secret seeds in toPublicSlotMachineProfile and preserves vm.fingerprint.username (#2015)', () => { + const mac = deriveSlotMachineProfile({ + accountUuid: '12345678-1234-4123-8123-1234567890ab', + email: 'user@example.com', + osFamily: 'darwin', + }) + const pub = toPublicSlotMachineProfile(mac) + assert.equal(pub.device_id, mac.device_id) + assert.equal(pub.tool_id_seed, undefined) + assert.equal(pub.session_id_seed, undefined) + assert.equal(pub.cwd_seed, undefined) + assert.equal(pub.account_key, undefined) + assert.equal(pub.git_persona.feistel_seed, undefined) + assert.equal(pub.linux_kernel, undefined) + + const fp = projectProfileToVmFingerprint(mac, { + username: 'kincli', + guest_uid: 999, + guest_gid: 987, + }) + assert.equal(fp.username, 'kincli') + assert.equal(fp.persona_username, mac.username) + assert.equal(fp.machine_home, mac.machine_home) + assert.equal(fp.stainless_os, 'MacOS') + assert.equal(fp.linux_kernel, undefined) + + const telMac = buildTelemetryIdentityFromProfile(mac) + assert.equal(telMac.platform, 'macos') + assert.equal(telMac.platform_raw, 'darwin') + assert.equal(telMac.deployment_environment, 'unknown-darwin') + assert.equal('linux_kernel' in telMac, false) + assert.equal('linux_distro_id' in telMac, false) + + const win = deriveSlotMachineProfile({ + accountUuid: '12345678-1234-4123-8123-1234567890ac', + osFamily: 'win32', + }) + const telWin = buildTelemetryIdentityFromProfile(win) + assert.equal(telWin.platform, 'windows') + assert.equal(telWin.platform_raw, 'win32') + assert.equal(telWin.deployment_environment, 'unknown-win32') + assert.equal('linux_kernel' in telWin, false) + }) + + it('manages VM lifecycle in ensureVmSlotMachineProfile across ephemeral, reuse, and account swap', () => { + const vm = { id: 'vm-01', fingerprint: { username: 'kincli' } } + const step1 = ensureVmSlotMachineProfile(vm) + assert.equal(step1.profile.ephemeral, true) + assert.equal(step1.changed, true) + assert.equal(vm.fingerprint.username, 'kincli') + + const step2 = ensureVmSlotMachineProfile(vm, { + accountUuid: 'aaaa1111-2222-4333-8444-555566667777', + email: 'alice@real.org', + }) + assert.equal(step2.profile.ephemeral, false) + assert.equal(step2.changed, true) + + const step3 = ensureVmSlotMachineProfile(vm) + assert.equal(step3.changed, false) + assert.equal(step3.accountChanged, false) + assert.equal(step3.profile.device_id, step2.profile.device_id) + + const step4 = ensureVmSlotMachineProfile(vm, { + accountUuid: 'bbbb9999-2222-4333-8444-555566668888', + email: 'bob@real.org', + }) + assert.equal(step4.changed, true) + assert.equal(step4.accountChanged, true) + assert.notEqual(step4.profile.device_id, step2.profile.device_id) + }) + + it('implements exact Native CC kI() project slug encoding including Windows C-- and >200 hash', () => { + assert.equal(nativeCcProjectSlug('/Users/alex.chen/work/my_app'), '-Users-alex-chen-work-my-app') + assert.equal(nativeCcProjectSlug('C:\\Users\\alex.chen\\work\\my_app'), 'C--Users-alex-chen-work-my-app') + assert.equal(nativeCcProjectSlug('/home/alex/work/my_app'), '-home-alex-work-my-app') + const longPath = `/Users/alex/${'segment_name/'.repeat(20)}app` + const slug = nativeCcProjectSlug(longPath) + assert.ok(slug.length > 201) + assert.equal(slug.slice(0, 200), longPath.replace(/[^a-zA-Z0-9]/g, '-').slice(0, 200)) + assert.equal(slug[200], '-') + }) +}) + +describe('cwd-mapping (8 syntaxes + ls -l + safeguards + SSE chunk boundaries)', () => { + it('rewrites all 8 path/slug syntaxes forward & reverse between macOS caller and Windows slot', () => { + const winProfile = deriveSlotMachineProfile({ + accountUuid: '99990000-1111-4222-8333-444455556666', + email: 'win-slot@example.com', + osFamily: 'win32', + }) + const mapper = createCwdMapper(winProfile, { personaRewrite: true }) + const u = winProfile.username + const realCwd = '/Users/alice.dev/projects/my_app' + const realSlug = nativeCcProjectSlug(realCwd) + const virtCwd = `C:\\Users\\${u}\\work\\my_app` + const virtSlug = `C--Users-${u}-work-my-app` + + const body = { + system: [ + { type: 'text', text: 'You are Claude Code, Anthropic’s official CLI for Claude.' }, + { + type: 'text', + text: `# Memory\nPersistent auto-memory dir: /Users/alice.dev/.claude/projects/${realSlug}/memory/\nFile: /Users/alice.dev/.claude/projects/${realSlug}/memory/MEMORY.md`, + }, + ], + messages: [ + { + role: 'user', + content: [ + { + type: 'text', + text: [ + 'Contents of /Library/Application Support/ClaudeCode/CLAUDE.md (organization-managed policy instructions):', + 'Contents of /Users/alice.dev/.claude/CLAUDE.md (user global):', + `Contents of ${realCwd}/CLAUDE.md (project):`, + ].join('\n'), + }, + ], + }, + { + role: 'system', + content: [ + 'You have been invoked in the following environment: ', + '# Environment', + ` - Primary working directory: ${realCwd}`, + ' - Is a git repository: true', + ' - Platform: darwin', + ' - Shell: zsh', + ' - OS Version: Darwin 24.1.0', + ].join('\n'), + }, + { + role: 'user', + content: [ + `Native: ${realCwd}/src/index.ts`, + `URI: file://${realCwd}/src/index.ts`, + 'Tilde: ~/projects/my_app/src/util.ts', + `Slug: ${realSlug}`, + `Shell: alice.dev@alices-mbp:~/projects/my_app$ cd ${realCwd}`, + 'Keep URL: https://github.com/Users/alice.dev/projects/my_app', + 'Keep sys: /usr/local/bin/node /etc/hosts /tmp/claude.sock', + ].join('\n'), + }, + { + role: 'assistant', + content: [ + { + type: 'thinking', + thinking: `Secret signed thought mentioning ${realCwd}/src/index.ts`, + signature: 'sig_immutable_12345', + }, + { + type: 'tool_use', + id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', + name: 'Bash', + input: { command: `ls -la ${realCwd}/src` }, + }, + ], + }, + { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', + content: [ + 'total 24', + `-rw-r--r--@ 1 alice.dev staff 1042 Nov 29 10:00 ${realCwd}/src/index.ts`, + 'drwxr-xr-x 4 root wheel 128 Nov 29 09:00 /etc', + ].join('\n'), + }, + ], + }, + ], + } + + mapper.rewriteRequestBody(body) + + // System `# Memory` has Windows trailing backslash & C-- slug + assert.ok(body.system[1].text.includes(`C:\\Users\\${u}\\.claude\\projects\\${virtSlug}\\memory\\`)) + assert.ok(body.system[1].text.includes(`C:\\Users\\${u}\\.claude\\projects\\${virtSlug}\\memory\\MEMORY.md`)) + + // CLAUDE.md Managed + User + Project paths mapped to win32 + const m0 = body.messages[0].content[0].text + assert.ok(m0.includes('Contents of C:\\Program Files\\ClaudeCode\\CLAUDE.md')) + assert.ok(m0.includes(`Contents of C:\\Users\\${u}\\.claude\\CLAUDE.md`)) + assert.ok(m0.includes(`Contents of ${virtCwd}\\CLAUDE.md`)) + + // messages[1] `# Environment` aligned to win32 profile + const envMsg = body.messages[1].content + assert.ok(envMsg.includes(` - Primary working directory: ${virtCwd}`)) + assert.ok(envMsg.includes(' - Platform: win32')) + assert.ok(envMsg.includes(' - Shell: bash')) + assert.ok(envMsg.includes(` - OS Version: ${winProfile.os_version}`)) + + // User syntaxes + safeguards + const uMsg = body.messages[2].content + assert.ok(uMsg.includes(`Native: ${virtCwd}\\src\\index.ts`)) + assert.ok(uMsg.includes(`URI: file:///C:/Users/${u}/work/my_app/src/index.ts`)) + assert.ok(uMsg.includes('Tilde: ~\\work\\my_app\\src\\util.ts')) + assert.ok(uMsg.includes(`Slug: ${virtSlug}`)) + assert.ok(uMsg.includes(`${u}@${winProfile.hostname}:~\\work\\my_app$ cd ${virtCwd}`)) + assert.ok(uMsg.includes('Keep URL: https://github.com/Users/alice.dev/projects/my_app')) + assert.ok(uMsg.includes('Keep sys: /usr/local/bin/node /etc/hosts /tmp/claude.sock')) + + // Thinking block MUST NEVER be modified + assert.equal(body.messages[3].content[0].thinking, `Secret signed thought mentioning ${realCwd}/src/index.ts`) + assert.equal(body.messages[3].content[0].signature, 'sig_immutable_12345') + assert.equal(body.messages[3].content[1].input.command, `ls -la ${virtCwd}\\src`) + + // `ls -l` owner/group rewritten for caller, preserved for root + const tr = body.messages[4].content[0].content + assert.ok(tr.includes(`-rw-r--r--@ 1 ${u} ${winProfile.ls_group} 1042 Nov 29 10:00 ${virtCwd}\\src\\index.ts`)) + assert.ok(tr.includes('drwxr-xr-x 4 root wheel 128 Nov 29 09:00 /etc')) + + // Reverse non-stream response object (never touching thinking) + const resp = { + role: 'assistant', + content: [ + { + type: 'thinking', + thinking: `Internal virtual path ${virtCwd}\\src\\index.ts`, + signature: 'sig_resp_999', + }, + { + type: 'text', + text: `Updated ${virtCwd}\\src\\index.ts and file:///C:/Users/${u}/work/my_app/README.md (${virtSlug}).`, + }, + { + type: 'tool_use', + id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', + name: 'Read', + input: { file_path: `${virtCwd}\\src\\index.ts` }, + }, + ], + } + mapper.rewriteResponseObject(resp) + assert.equal(resp.content[0].thinking, `Internal virtual path ${virtCwd}\\src\\index.ts`) + assert.equal(resp.content[1].text, `Updated ${realCwd}/src/index.ts and file://${realCwd}/README.md (${realSlug}).`) + assert.equal(resp.content[2].input.file_path, `${realCwd}/src/index.ts`) + }) + + it('preserves valid JSON escaping and handles 1-char SSE chunk splits for Windows caller -> macOS slot', () => { + const macProfile = deriveSlotMachineProfile({ + accountUuid: '77770000-1111-4222-8333-444455556666', + email: 'mac-slot@example.com', + osFamily: 'darwin', + }) + const u = macProfile.username + const mapper = createCwdMapper(macProfile, { personaRewrite: true }) + + const reqBody = { + system: `\nWorking directory: D:\\repos\\cool-service\nPlatform: win32\nShell: PowerShell\nOS Version: Windows 11 Pro 10.0.26100\n`, + messages: [ + { + role: 'user', + content: + 'Check D:/repos/cool-service/src/main.rs and JSON "D:\\\\repos\\\\cool-service\\\\Cargo.toml" plus C:\\Users\\Administrator\\.claude\\CLAUDE.md', + }, + ], + } + mapper.rewriteRequestBody(reqBody) + assert.ok(reqBody.system.includes(`Working directory: /Users/${u}/work/cool-service`)) + assert.ok(reqBody.system.includes('Platform: darwin')) + assert.ok(reqBody.system.includes('Shell: zsh')) + assert.ok(reqBody.messages[0].content.includes(`/Users/${u}/work/cool-service/src/main.rs`)) + assert.ok(reqBody.messages[0].content.includes(`"/Users/${u}/work/cool-service/Cargo.toml"`)) + assert.ok(reqBody.messages[0].content.includes(`/Users/${u}/.claude/CLAUDE.md`)) + + // Stream 1 char at a time through `createSseStreamRewriter` + const sse = mapper.createSseStreamRewriter() + assert.equal(sse.pushInputJsonDelta(''), '') + assert.equal(sse.pushTextDelta(''), '') + + const rawTextStream = `Edited /Users/${u}/work/cool-service/src/lib/router.rs and /Users/${u}/.claude/CLAUDE.md.` + let assembledText = '' + for (const ch of rawTextStream) { + assembledText += sse.pushTextDelta(ch) + } + assembledText += sse.flushTextDelta() + assert.equal( + assembledText, + 'Edited D:\\repos\\cool-service\\src\\lib\\router.rs and C:\\Users\\Administrator\\.claude\\CLAUDE.md.', + ) + + const rawPartialJson = JSON.stringify({ + file_path: `/Users/${u}/work/cool-service/src/lib/router.rs`, + command: `cd /Users/${u}/work/cool-service\ncargo test`, + }) + let assembledJson = '' + for (let i = 0; i < rawPartialJson.length; i += 2) { + assembledJson += sse.pushInputJsonDelta(rawPartialJson.slice(i, i + 2)) + } + assembledJson += sse.flushInputJsonDelta() + const parsed = JSON.parse(assembledJson) + assert.equal(parsed.file_path, 'D:\\repos\\cool-service\\src\\lib\\router.rs') + assert.equal(parsed.command, 'cd D:\\repos\\cool-service\ncargo test') + }) + + it('maintains byte-identical Turn 1..N message prefixes for Anthropic prompt caching', () => { + const linProfile = deriveSlotMachineProfile({ + accountUuid: '55550000-1111-4222-8333-444455556666', + osFamily: 'linux', + }) + const turn1 = { + messages: [ + { + role: 'system', + content: + '# Environment\n - Primary working directory: /Users/dev/app\n - Platform: darwin\n - Shell: zsh\n - OS Version: Darwin 24.3.0', + }, + { role: 'user', content: 'Inspect /Users/dev/app/package.json' }, + ], + } + const turn2 = structuredClone(turn1) + turn2.messages.push( + { role: 'assistant', content: [{ type: 'text', text: 'Read /Users/dev/app/package.json' }] }, + { role: 'user', content: 'Now check /Users/dev/app/src/server.mjs' }, + ) + + const m1 = createCwdMapper(linProfile) + const m2 = createCwdMapper(linProfile) + m1.rewriteRequestBody(turn1) + m2.rewriteRequestBody(turn2) + + assert.equal(JSON.stringify(turn1.messages[0]), JSON.stringify(turn2.messages[0])) + assert.equal(JSON.stringify(turn1.messages[1]), JSON.stringify(turn2.messages[1])) + }) + + it('maps /tmp/ when caller CWD is inside /tmp while preserving unrelated /tmp sockets and /etc', () => { + const macProfile = deriveSlotMachineProfile({ + accountUuid: '66660000-1111-4222-8333-444455556666', + osFamily: 'darwin', + }) + const mapper = createCwdMapper(macProfile, { + callerCwd: '/tmp/cc-cap-proj', + callerHome: '/home/tester', + }) + const body = { + messages: [ + { + role: 'user', + content: + 'Read /tmp/cc-cap-proj/probe.txt, policy /etc/claude-code/CLAUDE.md, keep /tmp/tmux-1000/default and /etc/passwd and C:\\Windows\\System32\\cmd.exe', + }, + ], + } + mapper.rewriteRequestBody(body) + const u = macProfile.username + assert.ok(body.messages[0].content.includes(`/Users/${u}/work/cc-cap-proj/probe.txt`)) + assert.ok(body.messages[0].content.includes('/Library/Application Support/ClaudeCode/CLAUDE.md')) + assert.ok(body.messages[0].content.includes('/tmp/tmux-1000/default')) + assert.ok(body.messages[0].content.includes('/etc/passwd')) + assert.ok(body.messages[0].content.includes('C:\\Windows\\System32\\cmd.exe')) + }) +}) + +describe('git-persona (Feistel hex + #gitStatus alignment + commit SHA reversal)', () => { + it('performs 100% bijective balanced (2L, 2L)-bit Feistel across odd and even hex lengths >= 7', () => { + const seedA = 'a'.repeat(64) + const seedB = 'b'.repeat(64) + const samples = [ + 'a1b2c3d', // L = 7 (odd) + '00abcdef', // L = 8 (leading zeros) + '123456789', // L = 9 (odd) + 'deadbeefcafe', // L = 12 + '469cd6bf45a645cbd0c7dfabb278a3365a588dc7', // L = 40 (SHA-1) + 'A1B2C3D4E5F60718', // Uppercase preservation + ] + for (const hex of samples) { + const encA = feistelHex(seedA, hex, 'encrypt') + const encB = feistelHex(seedB, hex, 'encrypt') + assert.equal(encA.length, hex.length) + assert.notEqual(encA.toLowerCase(), hex.toLowerCase()) + assert.notEqual(encA.toLowerCase(), encB.toLowerCase()) + assert.equal(feistelHex(seedA, encA, 'decrypt'), hex) + } + assert.equal(feistelHex(seedA, '0000000', 'encrypt'), '0000000') + }) + + it('aligns # gitStatus user/author/userEmail, preserves Claude Co-Authored-By, and reverses SHAs', () => { + const profile = deriveSlotMachineProfile({ + accountUuid: '88880000-1111-4222-8333-444455556666', + email: 'real.engineer@corp.com', + }) + const git = createGitPersonaRewriter(profile, { personaRewrite: true }) + const fullSha = '3564984d4ace568db2d137c8ff8634f48eeba42e' + const short1 = 'a1b2c3d' + const short2 = 'f0e1d2c' + + const body = { + messages: [ + { + role: 'user', + content: [ + '', + '# userEmail', + 'real.engineer@corp.com', + '# gitStatus', + 'Current branch: feat/auth', + 'Git user: Real Engineer ', + 'Recent commits:', + `${short1} feat: add token parser`, + `${short2} fix: handle empty header`, + '', + ].join('\n'), + }, + { + role: 'assistant', + content: [ + { + type: 'thinking', + thinking: `Commit ${fullSha} by Real Engineer `, + signature: 'sig_git_keep', + }, + { + type: 'tool_use', + id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', + name: 'Bash', + input: { command: 'git show HEAD' }, + }, + ], + }, + { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', + content: [ + `commit ${fullSha}`, + 'Author: Real Engineer ', + ' [feat/auth 998877a] ship feature', + ' Co-Authored-By: Teammate Bob ', + ' Co-Authored-By: Claude Opus 4.6 ', + 'diff --git a/a.js b/a.js', + 'index 1122334..5566778 100644', + ].join('\n'), + }, + ], + }, + ], + } + + git.rewriteRequestBody(body) + + const reminder = body.messages[0].content + assert.ok(!reminder.includes('real.engineer@corp.com')) + assert.ok(reminder.includes(`# userEmail\n${profile.git_persona.email}`)) + assert.ok(reminder.includes(`Git user: ${profile.git_persona.name} <${profile.git_persona.email}>`)) + const mappedShort1 = feistelHex(profile.git_persona.feistel_seed, short1, 'encrypt') + const mappedFull = feistelHex(profile.git_persona.feistel_seed, fullSha, 'encrypt') + assert.ok(reminder.includes(`${mappedShort1} feat: add token parser`)) + + // Thinking untouched + assert.ok(body.messages[1].content[0].thinking.includes(fullSha)) + assert.equal(body.messages[1].content[0].signature, 'sig_git_keep') + + // Tool result git show aligned + const showOut = body.messages[2].content[0].content + assert.ok(showOut.includes(`commit ${mappedFull}`)) + assert.ok(showOut.includes(`Author: ${profile.git_persona.name} <${profile.git_persona.email}>`)) + assert.ok(showOut.includes(`Co-Authored-By: ${profile.git_persona.name} <${profile.git_persona.email}>`)) + assert.ok(showOut.includes('Co-Authored-By: Claude Opus 4.6 ')) + assert.ok(!showOut.includes('1122334..5566778')) + + // Response restores both full SHA, mapped 7-hex SHA, AND 7-char prefix of mapped 40-hex SHA! + const respMsg = { + role: 'assistant', + content: [ + { + type: 'text', + text: `Checked commit ${mappedFull.slice(0, 7)} (full ${mappedFull}) and earlier ${mappedShort1}.`, + }, + ], + } + git.rewriteResponseObject(respMsg) + assert.equal( + respMsg.content[0].text, + `Checked commit ${fullSha.slice(0, 7)} (full ${fullSha}) and earlier ${short1}.`, + ) + }) +}) + +describe('tool-id-mapping (Feistel toolu_* symmetry + cross-account isolation + session UUIDv4)', () => { + it('preserves toolu_01<22-base62> format, roundtrips bijectively, and isolates across accounts', () => { + const seedA = '11'.repeat(32) + const seedB = '22'.repeat(32) + const ids = [ + 'toolu_01XBPoBaQ41jJfipVBMFEt62', + 'toolu_010000000000000000000000', + 'toolu_01zzzzzzzzzzzzzzzzzzzzzz', + 'srvtoolu_01AbCdEfGhIjKlMnOpQrStUv', + 'toolu_custom_even_1234', + 'toolu_custom_odd_12345', + ] + + for (const rawId of ids) { + const clientId = unmapToolUseIdFromAccount(seedA, rawId) + assert.notEqual(clientId, rawId) + if (rawId.startsWith('toolu_01')) { + assert.match(clientId, /^toolu_01[0-9A-Za-z]{22}$/) + } + // Same-slot Turn 2: map(K_A, unmap(K_A, raw_A)) === raw_A + assert.equal(mapToolUseIdForAccount(seedA, clientId), rawId) + // Reverse order: unmap(K_A, map(K_A, x)) === x + assert.equal(unmapToolUseIdFromAccount(seedA, mapToolUseIdForAccount(seedA, rawId)), rawId) + // Cross-slot failover Turn 2: map(K_B, unmap(K_A, raw_A)) !== raw_A + const slotBId = mapToolUseIdForAccount(seedB, clientId) + assert.notEqual(slotBId, rawId) + assert.notEqual(slotBId, clientId) + } + }) + + it('rewrites request & response message structures without touching thinking blocks', () => { + const seedA = 'aa'.repeat(32) + const upstreamId = 'toolu_01XBPoBaQ41jJfipVBMFEt62' + + const responseMsg = { + role: 'assistant', + content: [ + { type: 'thinking', thinking: upstreamId, signature: 'sig_tool_1' }, + { type: 'tool_use', id: upstreamId, name: 'Read', input: { file_path: 'a.txt' } }, + ], + } + rewriteResponseToolIds(responseMsg, seedA) + const clientFacingId = responseMsg.content[1].id + assert.notEqual(clientFacingId, upstreamId) + assert.equal(responseMsg.content[0].thinking, upstreamId) + + const turn2Body = { + messages: [ + responseMsg, + { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: clientFacingId, content: 'hello' }], + }, + ], + } + rewriteRequestToolIds(turn2Body, seedA) + assert.equal(turn2Body.messages[0].content[1].id, upstreamId) + assert.equal(turn2Body.messages[1].content[0].tool_use_id, upstreamId) + }) + + it('derives RFC 4122 UUIDv4 session IDs isolated per account, slot, and epoch', () => { + const seedA = 'aa'.repeat(32) + const seedB = 'bb'.repeat(32) + const clientSid = 'd8e8fca2-dc0f-4896-8c5a-112233445566' + + const s1 = deriveAccountSlotSessionId({ + sessionIdSeed: seedA, + clientSessionId: clientSid, + vmId: 'vm-01', + slotEpoch: 0, + }) + const s1Repeat = deriveAccountSlotSessionId({ + sessionIdSeed: seedA, + clientSessionId: clientSid, + vmId: 'vm-01', + slotEpoch: 0, + }) + const sOtherSlot = deriveAccountSlotSessionId({ + sessionIdSeed: seedB, + clientSessionId: clientSid, + vmId: 'vm-02', + slotEpoch: 0, + }) + const sNextEpoch = deriveAccountSlotSessionId({ + sessionIdSeed: seedA, + clientSessionId: clientSid, + vmId: 'vm-01', + slotEpoch: 1, + }) + + assert.match(s1, UUID_V4_RE) + assert.match(sOtherSlot, UUID_V4_RE) + assert.match(sNextEpoch, UUID_V4_RE) + assert.equal(s1, s1Repeat) + assert.notEqual(s1, clientSid) + assert.notEqual(s1, sOtherSlot) + assert.notEqual(s1, sNextEpoch) + }) +}) + +describe('KVM / Docker physical fingerprint sync invariants (K1/K2/K3/K4/S1/S2)', () => { + it('K1+K4: projectProfileToVmFingerprint preserves physical guest_machine_id and hardware.mac', () => { + const physicalGuestId = 'deadbeef'.repeat(4) + const physicalMac = '52:54:00:12:34:56' + const mac = deriveSlotMachineProfile({ + accountUuid: '11111111-2222-4333-8444-555555555555', + email: 'k1@example.com', + osFamily: 'darwin', + }) + assert.notEqual(mac.guest_machine_id, physicalGuestId) + assert.notEqual(mac.hardware.mac, physicalMac) + + const projected = projectProfileToVmFingerprint(mac, { + username: 'kincli', + guest_machine_id: physicalGuestId, + hardware: { mac: physicalMac }, + }) + assert.equal(projected.username, 'kincli') + assert.equal(projected.guest_machine_id, physicalGuestId) + assert.equal(projected.hardware.mac, physicalMac) + assert.equal(projected.device_id, mac.device_id) + assert.equal(projected.machine_id, mac.machine_id) + assert.notEqual(mac.hardware.mac, physicalMac) + }) + + it('K4: ensureKvmMachineRecord prefers kvm/fingerprint/hardware.json en0_mac over vm.fingerprint.hardware.mac', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-kvm-mac-')) + try { + const fpDir = path.join(root, 'vms', 'vm-09', 'kvm', 'fingerprint') + fs.mkdirSync(fpDir, { recursive: true }) + fs.writeFileSync(path.join(fpDir, 'hardware.json'), JSON.stringify({ en0_mac: '52:54:00:aa:bb:cc' })) + const vm = { + id: 'vm-09', + runtime: { type: 'kvm' }, + machine: {}, + fingerprint: { hardware: { mac: '3c:22:fb:01:02:03' } }, + } + const updated = ensureKvmMachineRecord(vm, { projectRoot: root }) + assert.equal(updated, true) + assert.equal(vm.machine.mac, '52:54:00:aa:bb:cc') + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it('K2: rememberComputer does not overwrite machine_profile hostname and avoids ping-pong', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-rem-comp-')) + try { + fs.mkdirSync(path.join(root, 'vms'), { recursive: true }) + const mac = deriveSlotMachineProfile({ + accountUuid: '22222222-3333-4444-8555-666666666666', + email: 'k2@example.com', + osFamily: 'darwin', + }) + const physicalGuestId = 'abcdef01'.repeat(4) + const vm = { + id: 'vm-10', + machine_profile: mac, + fingerprint: projectProfileToVmFingerprint(mac, { guest_machine_id: physicalGuestId }), + } + fs.writeFileSync(path.join(root, 'vms', 'vm-10.json'), JSON.stringify(vm)) + const computer = { hostname: 'wks-linux-substrate', guest_machine_id: physicalGuestId, username: 'kincli' } + assert.equal(rememberComputer(root, vm, computer), true) + assert.equal(vm.fingerprint.hostname, mac.hostname) + assert.equal(vm.fingerprint.computer_hostname, 'wks-linux-substrate') + assert.equal(vm.fingerprint.guest_machine_id, physicalGuestId) + // Second call is an idempotent no-op (zero oscillation). + assert.equal(rememberComputer(root, vm, computer), false) + const saved = JSON.parse(fs.readFileSync(path.join(root, 'vms', 'vm-10.json'), 'utf8')) + assert.equal(saved.fingerprint.hostname, mac.hostname) + assert.equal(saved.fingerprint.computer_hostname, 'wks-linux-substrate') + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it('S1: loadVmIdentity prefers machine_profile over stale fingerprint and buildKinSeedJson/persistVmSettings omit linux_kernel on non-Linux', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-vm-ident-')) + try { + const mac = deriveSlotMachineProfile({ + accountUuid: '33333333-4444-4555-8666-777777777777', + email: 's1@example.com', + osFamily: 'darwin', + }) + const vm = { + id: 'vm-11', + kernel: 'crag-debian13', + timezone: mac.timezone, + locale: mac.locale, + machine_profile: mac, + fingerprint: { + stainless_os: 'Linux', + stainless_arch: 'x64', + os_pretty: 'Debian GNU/Linux 13', + kernel_release: '6.12.20-amd64', + device_id: '00'.repeat(32), + }, + } + const homeDir = path.join(root, 'cli-home') + const ident = loadVmIdentity({ vmId: 'vm-11', homeDir, vm }) + assert.equal(ident.deviceId, mac.device_id) + assert.equal(ident.machineId, mac.machine_id) + assert.equal(ident.fingerprint.stainless_os, 'MacOS') + assert.equal(ident.fingerprint.stainless_arch, mac.stainless_arch) + assert.equal(ident.fingerprint.os_version, mac.os_version) + assert.equal(ident.fingerprint.shell, mac.shell) + + const seedDirect = buildKinSeedJson(vm) + assert.equal(seedDirect.os_family, 'darwin') + assert.equal('linux_kernel' in seedDirect, false) + + persistVmSettings({ homeDir, vm, seedPolicy: {} }, ident) + const persistedSeed = JSON.parse(fs.readFileSync(path.join(homeDir, '.claude', 'kin-seed.json'), 'utf8')) + assert.equal(persistedSeed.os_family, 'darwin') + assert.equal(persistedSeed.stainless_os, 'MacOS') + assert.equal('linux_kernel' in persistedSeed, false) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it('S2: persistVmTimezone updates vm.machine_profile, vm.fingerprint, credentials.json, and run/kernel.json in lockstep', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-tz-sync-')) + try { + const id = 'vm-12' + const slotDir = path.join(root, 'vms', id) + fs.mkdirSync(path.join(slotDir, 'cli-home', '.claude'), { recursive: true }) + fs.mkdirSync(path.join(slotDir, 'run'), { recursive: true }) + const mac = deriveSlotMachineProfile({ + accountUuid: '44444444-5555-4666-8777-888888888888', + email: 's2@example.com', + osFamily: 'darwin', + timezoneHint: 'America/Los_Angeles', + }) + const vm = { + id, + timezone: 'America/Los_Angeles', + locale: 'en_US.UTF-8', + machine_profile: mac, + fingerprint: projectProfileToVmFingerprint(mac, { guest_machine_id: '12345678'.repeat(4) }), + } + fs.writeFileSync(path.join(root, 'vms', `${id}.json`), JSON.stringify(vm)) + fs.writeFileSync( + path.join(slotDir, 'cli-home', '.claude', 'credentials.json'), + JSON.stringify({ access_token: 'tok', machineProfile: toPublicSlotMachineProfile(mac) }), + ) + const kernelPath = path.join(slotDir, 'run', 'kernel.json') + fs.writeFileSync( + kernelPath, + JSON.stringify({ timezone: 'America/Los_Angeles', machine_profile: toPublicSlotMachineProfile(mac) }), + ) + if (process.platform !== 'win32') fs.chmodSync(kernelPath, 0o640) + + const out = persistVmTimezone(root, id, 'America/New_York', { source: 'manual' }) + assert.ok(out) + const savedVm = JSON.parse(fs.readFileSync(path.join(root, 'vms', `${id}.json`), 'utf8')) + const credPath = path.join(slotDir, 'cli-home', '.claude', 'credentials.json') + const savedCred = JSON.parse(fs.readFileSync(credPath, 'utf8')) + const savedKernel = JSON.parse(fs.readFileSync(kernelPath, 'utf8')) + assert.equal(savedVm.timezone, 'America/New_York') + assert.equal(savedVm.fingerprint.timezone, 'America/New_York') + assert.equal(savedVm.machine_profile.timezone, 'America/New_York') + assert.equal(savedCred.machineProfile.timezone, 'America/New_York') + assert.equal(savedKernel.timezone, 'America/New_York') + assert.equal(savedKernel.machine_profile.timezone, 'America/New_York') + if (process.platform !== 'win32') { + assert.equal(fs.statSync(credPath).mode & 0o777, 0o444, 'credentials.json must stay sealed 0444') + assert.equal(fs.statSync(kernelPath).mode & 0o777, 0o640, 'kernel.json must preserve 0640 mode') + } + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it('K3: slotHost exposes syncClaudeProfile and clearSlotState for custom-erofs KVM and Docker', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-k3-host-')) + try { + const id = 'vm-13' + const slotDir = path.join(root, 'vms', id) + fs.mkdirSync(path.join(slotDir, 'cli-home', '.claude', 'crag-v3-continuations'), { recursive: true }) + fs.mkdirSync(path.join(slotDir, 'run', 'work', '.crag-sessions'), { recursive: true }) + fs.writeFileSync( + path.join(slotDir, 'cli-home', '.claude', '.claude.json'), + JSON.stringify({ userID: 'a'.repeat(64) }), + ) + fs.writeFileSync( + path.join(slotDir, 'cli-home', '.claude', 'credentials.json'), + JSON.stringify({ access_token: 'x' }), + ) + + const dockerHost = slotHost({ id, runtime: { type: 'docker' } }) + assert.deepEqual(await dockerHost.syncClaudeProfile({ id }, slotDir), { ok: true, local: true }) + + const kvmVm = { id, kernel: 'crag-debian13', runtime: { type: 'kvm', mode: 'custom-erofs' } } + const kvmHost = slotHost(kvmVm) + const calls = [] + const mockClient = { + syncFile: async (params) => { + calls.push(['syncFile', params.target]) + return { ok: true, result: { target: params.target } } + }, + clearSlotState: async () => { + calls.push(['clearSlotState']) + return { ok: true, result: { cleared: ['credentials', 'claude_profile'] } } + }, + } + const synced = await kvmHost.syncClaudeProfile(kvmVm, slotDir, { client: mockClient }) + assert.equal(synced.ok, true) + assert.equal(synced.pushed, true) + + const cleared = await kvmHost.clearSlotState(kvmVm, slotDir, { client: mockClient }) + assert.equal(cleared.ok, true) + assert.deepEqual(cleared.guest_cleared, ['credentials', 'claude_profile']) + assert.equal(fs.existsSync(path.join(slotDir, 'cli-home', '.claude', 'credentials.json')), false) + assert.equal(fs.existsSync(path.join(slotDir, 'cli-home', '.claude', '.claude.json')), false) + assert.equal(fs.existsSync(path.join(slotDir, 'run', 'work', '.crag-sessions')), false) + assert.deepEqual(calls, [['syncFile', 'claude_profile'], ['clearSlotState']]) + + // Graceful fallback when older guest agent lacks claude_profile / clear_slot_state + fs.writeFileSync( + path.join(slotDir, 'cli-home', '.claude', '.claude.json'), + JSON.stringify({ userID: 'a'.repeat(64) }), + ) + const legacyClient = { + syncFile: async () => ({ ok: false, error: 'invalid_params', message: 'unsupported sync_file target' }), + clearSlotState: async () => ({ ok: false, error: 'unknown_op', message: 'unsupported op: clear_slot_state' }), + } + const legacySync = await kvmHost.syncClaudeProfile(kvmVm, slotDir, { client: legacyClient }) + assert.equal(legacySync.ok, true) + assert.equal(legacySync.skipped, true) + const legacyClear = await kvmHost.clearSlotState(kvmVm, slotDir, { client: legacyClient }) + assert.equal(legacyClear.ok, true) + assert.equal(legacyClear.skipped, true) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it('Task 1 & 2: capitalized Commit: maps symmetrically while preserving Commit: Author and UUIDs', () => { + const profile = deriveSlotMachineProfile({ + accountUuid: '55555555-6666-4777-8888-999999999999', + email: 'git-case@example.com', + osFamily: 'darwin', + }) + const rw = createGitPersonaRewriter(profile, { personaRewrite: true }) + const rawFull = 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678' + const rawShort = 'a1b2c3d' + const uuid = '99999999-1111-4222-8333-444444444444' + const body = { + messages: [ + { + role: 'user', + content: [ + 'Commit: Real Dev ', + `Commit: ${rawFull}`, + `Commit ${rawShort}.`, + `commit: ${rawShort})`, + `Commit: ${uuid}`, + ].join('\n'), + }, + ], + } + rw.rewriteRequestBody(body) + const out = body.messages[0].content + const mappedFull = rw.mapCommitSha(rawFull) + const mappedShort = rw.mapCommitSha(rawShort) + assert.notEqual(mappedFull, rawFull) + assert.notEqual(mappedShort, rawShort) + assert.ok(out.includes(`Commit: ${profile.git_persona.name} <${profile.git_persona.email}>`)) + assert.ok(out.includes(`Commit: ${mappedFull}`)) + assert.ok(out.includes(`Commit ${mappedShort}.`)) + assert.ok(out.includes(`commit: ${mappedShort})`)) + assert.ok(out.includes(`Commit: ${uuid}`), 'UUIDs after Commit: must not be treated as commit SHAs') + assert.equal(out.includes(rawFull), false) + + // Symmetric reverse-mapping + const reversed = rw.rewriteResponseText(`Checked Commit: ${mappedFull} and Commit ${mappedShort}.`) + assert.equal(reversed, `Checked Commit: ${rawFull} and Commit ${rawShort}.`) + }) + + it('Task 2: env-enabled persona, headers, continuation, prompt_spec, workerEnvelope, 10-slot-preset.json, and KVM env never penetrate host traits across 3 OSes', async () => { + const prevTz = process.env.TZ + const prevShell = process.env.SHELL + const prevUser = process.env.USER + process.env.TZ = 'Pacific/Kiritimati' + process.env.SHELL = '/usr/local/bin/host-fish' + process.env.USER = 'host_secret_operator' + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-env-noleak-')) + try { + for (const osFamily of ['darwin', 'win32', 'linux']) { + const mp = deriveSlotMachineProfile({ + accountUuid: `env-guard-${osFamily}-1`, + email: `${osFamily}@example.com`, + osFamily, + timezoneHint: + osFamily === 'darwin' ? 'America/Los_Angeles' : osFamily === 'win32' ? 'America/Chicago' : 'Europe/Berlin', + }) + const vmId = `vm-env-${osFamily}` + const homeDir = path.join(root, 'vms', vmId, 'cli-home') + fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true }) + const vm = { + id: vmId, + kernel: 'crag-debian13', + machine_profile: mp, + fingerprint: projectProfileToVmFingerprint(mp), + } + const identity = loadVmIdentity({ vmId, homeDir, vm }) + assert.equal(identity.machine_profile?.os_family, osFamily) + + // 1. Stainless headers carry bound 3-OS traits (never hardcoded Linux/x64) + const headers = resolveVmCharacteristicHeaders(identity, {}, homeDir, 'claude-sonnet-5-5', { + officialTraffic: false, + }) + assert.equal(headers['x-stainless-os'], mp.stainless_os) + assert.equal(headers['x-stainless-arch'], mp.stainless_arch) + + // 2. official_full with env enabled & NO caller # Environment -> bound 3-OS # Environment + # Memory, zero host/kincli leak + const renderedNoEnv = applyCrsUnofficialPersona( + { + model: 'claude-sonnet-5-5', + messages: [{ role: 'user', content: 'hi' }], + }, + { + forceConfigured: true, + mode: 'official_full', + identity, + routing: { + compatibility: { + persona_preset: 'official_full', + persona_env_presets: { official_full: true }, + persona_timezone_presets: { official_full: true }, + persona_locale_presets: { official_full: true }, + persona_guidance_presets: { official_full: true }, + }, + }, + }, + ) + const extractRenderedText = (doc) => { + const parts = [] + for (const b of Array.isArray(doc?.system) ? doc.system : []) { + if (typeof b === 'string') parts.push(b) + else if (typeof b?.text === 'string') parts.push(b.text) + } + for (const m of Array.isArray(doc?.messages) ? doc.messages : []) { + if (typeof m?.content === 'string') parts.push(m.content) + else if (Array.isArray(m?.content)) { + for (const b of m.content) if (typeof b?.text === 'string') parts.push(b.text) + } + } + return parts.join('\n') + } + const serializedNoEnv = extractRenderedText(renderedNoEnv) + assert.ok(serializedNoEnv.includes(`Platform: ${mp.platform_raw}`), `${osFamily}: missing Platform`) + assert.ok(serializedNoEnv.includes(`Shell: ${mp.shell}`), `${osFamily}: missing Shell`) + assert.ok(serializedNoEnv.includes(`OS Version: ${mp.os_version}`), `${osFamily}: missing OS Version`) + assert.ok(serializedNoEnv.includes(`Timezone: ${mp.timezone}`), `${osFamily}: missing Timezone`) + assert.ok(serializedNoEnv.includes(`Language: ${mp.locale}`), `${osFamily}: missing Language`) + assert.ok( + serializedNoEnv.includes(mp.work_root), + `${osFamily}: missing virtual work_root in Primary working directory`, + ) + const expectedDefaultCwd = `${mp.work_root}${mp.path_sep}workspace` + const expectedMemDir = `${mp.claude_config_dir}${mp.path_sep}projects${mp.path_sep}${nativeCcProjectSlug(expectedDefaultCwd)}${mp.path_sep}memory${mp.path_sep}` + assert.ok(serializedNoEnv.includes(expectedMemDir), `${osFamily}: missing 3-OS # Memory dir ${expectedMemDir}`) + for (const forbidden of [ + '/home/kincli', + '/run/kin/work', + 'Pacific/Kiritimati', + 'host-fish', + 'host_secret_operator', + ]) { + assert.equal(serializedNoEnv.includes(forbidden), false, `${osFamily}: leaked ${forbidden}`) + } + if (osFamily !== 'linux') { + assert.equal(/OS Version:\s*Linux\b/.test(serializedNoEnv), false, `${osFamily}: leaked Linux OS Version`) + } + + // 3. officialSystemEnvFromIdentity + buildOfficialContinuationText (2.1.241) never leak /home/kincli or conflicting caller OS + const envObj = officialSystemEnvFromIdentity( + identity, + 'claude-sonnet-5-5', + { platform: 'linux', shell: '/usr/local/bin/host-fish', osVersion: 'Linux 6.12.20-amd64' }, + { overwrite: true }, + ) + assert.equal(envObj.platform, mp.platform_raw) + assert.equal(envObj.shell, mp.shell) + assert.equal(envObj.osVersion, mp.os_version) + const contText = buildOfficialContinuationText(envObj, [], { overwrite: true, vm }) + assert.equal(contText.includes('/home/kincli'), false) + assert.ok(contText.includes(expectedMemDir)) + assert.ok(contText.includes(`OS Version: ${mp.os_version}`)) + + // 4. cwd-mapping standalone Primary working directory + inline OS Version/Timezone/Locale + no work/work double-nest + const mapper = createCwdMapper(mp, { personaRewrite: true }) + const envBody = { + messages: [ + { + role: 'user', + content: ` - Primary working directory: ${mp.work_root}\n# Environment\n - OS Version: Linux 6.12.20-amd64 - Locale: fr_FR.UTF-8 - Timezone: Pacific/Kiritimati`, + }, + ], + } + mapper.rewriteRequestBody(envBody) + const rewrittenMsg = envBody.messages[0].content + assert.equal( + rewrittenMsg.includes(`${mp.work_root}${mp.path_sep}work`), + false, + 'must not double-nest work/work', + ) + assert.ok(rewrittenMsg.includes(`OS Version: ${mp.os_version}`)) + assert.ok(rewrittenMsg.includes(`Locale: ${mp.locale}`)) + assert.ok(rewrittenMsg.includes(`Timezone: ${mp.timezone}`)) + + // 5. resolveSystemPromptSpec & workerEnvelope inherit machine_profile timezone/locale even when vm.timezone/vm.locale are omitted + const sparseVm = { id: vmId, machine_profile: mp } + const spec = resolveSystemPromptSpec({ + routing: { + compatibility: { + persona_preset: 'official_full', + persona_env_presets: { official_full: true }, + persona_timezone_presets: { official_full: true }, + persona_locale_presets: { official_full: true }, + }, + }, + slot: sparseVm, + identity: {}, + }) + assert.equal(spec.sections.environment.timezone_value, mp.timezone) + assert.equal(spec.sections.environment.locale_value, mp.locale) + + const { envelope: cragEnvRes } = await workerEnvelope({ + body: { + model: 'claude-sonnet-5-5', + messages: [{ role: 'user', content: 'hi' }], + crag_prompt_spec: { + ...spec, + sections: { + ...spec.sections, + environment: { ...spec.sections.environment, timezone_value: null, locale_value: null }, + }, + }, + }, + reqHeaders: {}, + exec: { + vmId, + homeDir, + vm: sparseVm, + workerStatus: { + runtime_variant: 'crag-v2', + capabilities: ['headless_claude_bridge_v1', 'prompt_spec_v1'], + }, + }, + identity, + routing: {}, + cliHop: true, + cragPrint: true, + }) + assert.equal(cragEnvRes.body.crag_prompt_spec.sections.environment.timezone_value, mp.timezone) + assert.equal(cragEnvRes.body.crag_prompt_spec.sections.environment.locale_value, mp.locale) + assert.equal(cragEnvRes.body.crag_env.timezone, mp.timezone) + assert.equal(cragEnvRes.body.crag_env.locale, mp.locale) + + // 6. 10-slot-preset.json & KVM docker run env inherit machine_profile and never leak host process.env + const presetSync = syncSlotIdentityTimezoneAndPreset(root, sparseVm) + assert.equal(presetSync.ok, true) + const presetJson = JSON.parse(fs.readFileSync(presetSync.presetPath, 'utf8')) + assert.equal(presetJson.env.TZ, mp.timezone) + assert.equal(presetJson.env.LANG, mp.locale) + assert.equal(presetJson.env.LC_ALL, mp.locale) + assert.equal('SHELL' in presetJson.env, false) + assert.equal('USER' in presetJson.env, false) + + const kvmArgs = buildKvmRunArgs({ + vm: { ...sparseVm, kernel: 'crag-debian13', fingerprint: vm.fingerprint }, + name: `kin-${vmId}`, + image: 'kin-kvm:test', + hostName: mp.hostname, + network: 'kin-eg-1', + memory: '2g', + accel: 'tcg', + uid: 10001, + gid: 987, + home: homeDir, + runDir: path.join(root, 'vms', vmId, 'run'), + kvmDir: path.join(root, 'vms', vmId, 'kvm'), + projectRoot: root, + }) + assert.ok(kvmArgs.includes(`TZ=${mp.timezone}`)) + assert.ok(kvmArgs.includes(`LANG=${mp.locale}`)) + assert.equal( + kvmArgs.some((a) => String(a).includes('Pacific/Kiritimati') || String(a).includes('host-fish')), + false, + ) + } + } finally { + if (prevTz === undefined) delete process.env.TZ + else process.env.TZ = prevTz + if (prevShell === undefined) delete process.env.SHELL + else process.env.SHELL = prevShell + if (prevUser === undefined) delete process.env.USER + else process.env.USER = prevUser + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe('PR #2472 review regressions & approved architectural invariants (M2/M4/M5/M7/M8/Minor1/Minor2)', () => { + it('M2: Windows caller streaming input_json_delta to virtual memory dir produces valid JSON across all 3 virtual OSes', async () => { + const { createOutboundSlotSseRewriter } = await import('../../src/lib/protocol/handle-protocol.mjs') + const callerCwd = 'C:\\Users\\bob\\proj\\app' + const callerHome = 'C:\\Users\\bob' + const expectedPath = 'C:\\Users\\bob\\.claude\\projects\\C--Users-bob-proj-app\\memory\\MEMORY.md' + + for (const osFamily of ['darwin', 'win32', 'linux']) { + const profile = deriveSlotMachineProfile({ + accountUuid: `m2-win-mem-${osFamily}`, + email: `m2-${osFamily}@example.com`, + osFamily, + pepper: 'test-pepper-m2', + }) + const cwdMapper = createCwdMapper(profile, { callerCwd, callerHome }) + const gitRewriter = createGitPersonaRewriter(profile) + const snap = cwdMapper.getMappingSnapshot() + const virtMemFile = `${snap.virtualMemoryDir}MEMORY.md` + + const rewriter = createOutboundSlotSseRewriter({ profile, cwdMapper, gitRewriter }) + const outLines = [] + const feed = (l) => outLines.push(...rewriter.transformLine(l)) + feed('event: content_block_start') + feed( + `data: ${JSON.stringify({ + type: 'content_block_start', + index: 0, + content_block: { type: 'tool_use', id: 'toolu_01XBPoBaQ41jJfipVBMFEt62', name: 'Write', input: {} }, + })}`, + ) + feed('') + + const rawJson = JSON.stringify({ file_path: virtMemFile, content: 'remember this' }) + for (let i = 0; i < rawJson.length; i += 3) { + feed('event: content_block_delta') + feed( + `data: ${JSON.stringify({ + type: 'content_block_delta', + index: 0, + delta: { type: 'input_json_delta', partial_json: rawJson.slice(i, i + 3) }, + })}`, + ) + feed('') + } + feed('event: content_block_stop') + feed(`data: ${JSON.stringify({ type: 'content_block_stop', index: 0 })}`) + feed('') + outLines.push(...rewriter.flush()) + + const assembledJson = outLines + .filter((l) => l.startsWith('data:')) + .map((l) => JSON.parse(l.slice(5).trim())) + .filter((ev) => ev.type === 'content_block_delta' && ev.delta?.type === 'input_json_delta') + .map((ev) => ev.delta.partial_json) + .join('') + + const parsed = JSON.parse(assembledJson) + assert.equal(parsed.file_path, expectedPath, `virtual OS ${osFamily} must restore valid Windows memory JSON path`) + assert.equal(parsed.content, 'remember this') + } + }) + + it('Minor 2: preserves URL paths when https://example.com and /Users//x split across SSE chunks', () => { + const macProfile = deriveSlotMachineProfile({ + accountUuid: 'minor2-url-split-1', + email: 'url@example.com', + osFamily: 'darwin', + pepper: 'test-pepper-minor2', + }) + const mapper = createCwdMapper(macProfile, { + callerCwd: '/home/realuser/proj', + callerHome: '/home/realuser', + }) + const snap = mapper.getMappingSnapshot() + const sse = mapper.createSseStreamRewriter() + + const part1 = sse.pushTextDelta('See https://example.com') + const part2 = sse.pushTextDelta(`${snap.virtualHome}/x and ${snap.virtualCwd}/a.js`) + const tail = sse.flushTextDelta() + const out = part1 + part2 + tail + + assert.equal( + out, + `See https://example.com${snap.virtualHome}/x and /home/realuser/proj/a.js`, + 'URL path split across SSE chunks must remain untouched while real virtual CWD is restored', + ) + }) + + it('Minor 1: 24-char non-standard fallback tool IDs never collide with toolu_01<22-base62> and round-trip 100%', () => { + const seed = '11'.repeat(32) + // Exact counterexample from PR #2472 review that previously collided with toolu_01... + const counterexample = 'toolu_7bYRu8kffDafjxXUZoyzPPQF' + const mapped = mapToolUseIdForAccount(seed, counterexample) + assert.doesNotMatch( + mapped, + /^toolu_01[0-9A-Za-z]{22}$/, + 'fallback ID must cycle-walk out of standard toolu_01 space', + ) + assert.equal(unmapToolUseIdFromAccount(seed, mapped), counterexample) + + const unmapped = unmapToolUseIdFromAccount(seed, counterexample) + assert.doesNotMatch(unmapped, /^toolu_01[0-9A-Za-z]{22}$/) + assert.equal(mapToolUseIdForAccount(seed, unmapped), counterexample) + }) + + it('M4: pre-existing legacy slot with device_id/Linux fingerprint is NEVER lazily overwritten on hot path', () => { + const legacyDeviceId = 'a1b2c3d4'.repeat(8) + const legacyVm = { + id: 'vm-legacy-99', + claude: { account_uuid: 'acct-legacy-1', email: 'legacy@example.com' }, + fingerprint: { + username: 'kincli', + device_id: legacyDeviceId, + hostname: 'wks-legacy-linux', + os_family: 'linux', + }, + } + const res = ensureVmSlotMachineProfile(legacyVm, { + accountUuid: 'acct-legacy-1', + email: 'legacy@example.com', + }) + assert.equal(res.profile, null) + assert.equal(res.changed, false) + assert.equal(res.legacyPreserved, true) + assert.equal(legacyVm.machine_profile, undefined) + assert.equal(legacyVm.fingerprint.device_id, legacyDeviceId) + assert.equal(legacyVm.fingerprint.hostname, 'wks-legacy-linux') + + // Explicit opt-in still enables 3-OS machine_profile + const optedIn = ensureVmSlotMachineProfile( + legacyVm, + { accountUuid: 'acct-legacy-1', email: 'legacy@example.com' }, + { optIn: true, pepper: 'test-pepper-m4' }, + ) + assert.ok(optedIn.profile) + assert.equal(optedIn.changed, true) + assert.equal(legacyVm.machine_profile.device_id, optedIn.profile.device_id) + }) + + it('M5: auto-generated pepper persists across DB reopen, differs across fresh installs, and env overrides', async () => { + const { closeDatabase, openDatabase } = await import('../../src/lib/db/database.mjs') + const { resolveMachineProfilePepper, resetCachedMachineProfilePepperForTest } = await import( + '../../src/lib/identity/slot-machine-profile.mjs' + ) + const prevEnv = process.env.KIN_MACHINE_PROFILE_PEPPER + delete process.env.KIN_MACHINE_PROFILE_PEPPER + const dirA = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-pepper-a-')) + const dirB = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-pepper-b-')) + try { + const dbA1 = openDatabase({ dbPath: path.join(dirA, 'a.sqlite') }) + const pA1 = resolveMachineProfilePepper({ db: dbA1 }) + assert.match(pA1, /^[0-9a-f]{64}$/) + closeDatabase() + + // Reopen same DB -> identical persisted pepper + const dbA2 = openDatabase({ dbPath: path.join(dirA, 'a.sqlite') }) + const pA2 = resolveMachineProfilePepper({ db: dbA2 }) + assert.equal(pA2, pA1, 'auto-generated pepper must survive DB reopen') + closeDatabase() + + // Fresh install DB -> distinct pepper + const dbB = openDatabase({ dbPath: path.join(dirB, 'b.sqlite') }) + const pB = resolveMachineProfilePepper({ db: dbB }) + assert.match(pB, /^[0-9a-f]{64}$/) + assert.notEqual(pB, pA1, 'fresh install must generate a distinct pepper') + closeDatabase() + + // Env var wins over DB + process.env.KIN_MACHINE_PROFILE_PEPPER = 'operator-pinned-cluster-pepper' + assert.equal(resolveMachineProfilePepper(), 'operator-pinned-cluster-pepper') + resetCachedMachineProfilePepperForTest() + } finally { + closeDatabase() + if (prevEnv === undefined) delete process.env.KIN_MACHINE_PROFILE_PEPPER + else process.env.KIN_MACHINE_PROFILE_PEPPER = prevEnv + fs.rmSync(dirA, { recursive: true, force: true }) + fs.rmSync(dirB, { recursive: true, force: true }) + } + }) + + it('M7: one-way OS/Git persona rewrite is OFF by default and preserves # userEmail sentence format when opted in', () => { + const winProfile = deriveSlotMachineProfile({ + accountUuid: 'm7-persona-gate-1', + email: 'm7@example.com', + osFamily: 'win32', + pepper: 'test-pepper-m7', + }) + const realSha = '3564984d4ace568db2d137c8ff8634f48eeba42e' + const baseBody = { + messages: [ + { + role: 'system', + content: [ + '# Environment', + ' - Primary working directory: /home/bob/proj', + ' - Platform: linux', + ' - Shell: bash', + ' - OS Version: Linux 6.8.0', + ].join('\n'), + }, + { + role: 'user', + content: [ + '', + '# userEmail', + "The user's email address is bob@corp.com", + '# gitStatus', + 'Git user: Bob Smith ', + 'Recent commits:', + `${realSha} feat: initial`, + '', + 'Author: Bob Smith ', + 'Co-Authored-By: Alice ', + 'user.email=bob@corp.com', + ].join('\n'), + }, + ], + } + + // 1. Default OFF: reversible CWD & SHA still mapped, one-way Platform/OS/Author/userEmail preserved verbatim + const defaultBody = structuredClone(baseBody) + createCwdMapper(winProfile).rewriteRequestBody(defaultBody) + createGitPersonaRewriter(winProfile).rewriteRequestBody(defaultBody) + assert.ok(defaultBody.messages[0].content.includes(`Primary working directory: ${winProfile.work_root}\\proj`)) + assert.ok(defaultBody.messages[0].content.includes('Platform: linux'), 'default must NOT rewrite Platform') + assert.ok( + defaultBody.messages[0].content.includes('OS Version: Linux 6.8.0'), + 'default must NOT rewrite OS Version', + ) + assert.ok( + defaultBody.messages[1].content.includes("The user's email address is bob@corp.com"), + 'default must NOT rewrite # userEmail', + ) + assert.ok(defaultBody.messages[1].content.includes('Author: Bob Smith ')) + assert.ok(defaultBody.messages[1].content.includes('Co-Authored-By: Alice ')) + assert.ok(defaultBody.messages[1].content.includes('user.email=bob@corp.com')) + assert.equal(defaultBody.messages[1].content.includes(realSha), false, 'reversible commit SHA mapping stays active') + + // 2. Explicit opt-in: OS/Git persona rewritten AND # userEmail sentence wording preserved + const optInBody = structuredClone(baseBody) + createCwdMapper(winProfile, { personaRewrite: true }).rewriteRequestBody(optInBody) + createGitPersonaRewriter(winProfile, { personaRewrite: true }).rewriteRequestBody(optInBody) + assert.ok(optInBody.messages[0].content.includes('Platform: win32')) + assert.ok(optInBody.messages[0].content.includes(`OS Version: ${winProfile.os_version}`)) + assert.ok( + optInBody.messages[1].content.includes(`The user's email address is ${winProfile.git_persona.email}`), + '# userEmail opt-in rewrite must preserve surrounding sentence wording', + ) + assert.ok( + optInBody.messages[1].content.includes( + `Author: ${winProfile.git_persona.name} <${winProfile.git_persona.email}>`, + ), + ) + assert.ok(optInBody.messages[1].content.includes(`user.email=${winProfile.git_persona.email}`)) + }) + + it('M8: persisted vm.slot_epoch preserves account-switch session isolation across control-plane restarts', async () => { + const { getSlotSessionEpoch } = await import('../../src/lib/protocol/issued-tool-replay.mjs') + const seed = 'cc'.repeat(32) + const clientSid = 'd8e8fca2-dc0f-4896-8c5a-112233445566' + const freshVmId = 'vm-m8-restart-check' + + // Simulate process restart (fresh vmId not in in-memory vmSlotEpochs map), with vm.slot_epoch=2 from disk + const epochBeforeSwap = getSlotSessionEpoch({ vmId: freshVmId, sessionId: clientSid, persistedVmEpoch: 0 }) + const epochAfterRestart = getSlotSessionEpoch({ vmId: freshVmId, sessionId: clientSid, persistedVmEpoch: 2 }) + assert.equal(epochAfterRestart, epochBeforeSwap + 2) + const sid0 = deriveAccountSlotSessionId({ + sessionIdSeed: seed, + clientSessionId: clientSid, + vmId: freshVmId, + slotEpoch: epochBeforeSwap, + }) + const sid2 = deriveAccountSlotSessionId({ + sessionIdSeed: seed, + clientSessionId: clientSid, + vmId: freshVmId, + slotEpoch: epochAfterRestart, + }) + assert.notEqual(sid2, sid0, 'persisted slot_epoch must prevent session UUID rollback after restart') + }) +}) diff --git a/test/unit/vm-recreate.test.mjs b/test/unit/vm-recreate.test.mjs index 4876efaaa..2b407255f 100644 --- a/test/unit/vm-recreate.test.mjs +++ b/test/unit/vm-recreate.test.mjs @@ -429,3 +429,109 @@ test('bare ARM64 host with amd64 CRAG preflights unstaged slots and recreates sl code: 'crag_v2_arch_mismatch', }) }) + +test('keep mode recreate preserves physical guest_machine_id and vms//machine-id when machine_profile is present', async () => { + const { deriveSlotMachineProfile } = await import('../../src/lib/identity/slot-machine-profile.mjs') + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-recreate-keep-mid-')) + try { + const vmId = 'vm-keep-kvm-mid' + const slotDir = path.join(root, 'vms', vmId) + fs.mkdirSync(path.join(slotDir, 'cli-home', '.claude'), { recursive: true }) + const template = path.join(root, 'share', 'wrap-cli') + fs.mkdirSync(template, { recursive: true }) + for (const name of ['kin-kernel.bin', 'cli-node']) fs.writeFileSync(path.join(template, name), name) + seedEncryptedPackage(root) + const physicalMid = '11223344556677889900aabbccddeeff' + fs.writeFileSync(path.join(slotDir, 'machine-id'), `${physicalMid}\n`) + + const profile = deriveSlotMachineProfile({ + accountUuid: 'acct-keep-mid-1', + email: 'keep-mid@example.com', + osFamily: 'darwin', + }) + assert.notEqual(profile.guest_machine_id, physicalMid) + + const prev = { + id: vmId, + name: 'keep-kvm', + kernel: 'ubuntu-24.04', + runtime: { type: 'kvm' }, + claude: { account_uuid: 'acct-keep-mid-1', has_access: true }, + machine_profile: profile, + fingerprint: { + hostname: 'physical-kvm-host', + device_id: profile.device_id, + guest_machine_id: physicalMid, + }, + } + const { vm } = recreateVmFiles(root, prev, { mode: 'keep' }) + assert.equal(vm.fingerprint.guest_machine_id, physicalMid) + assert.equal(fs.readFileSync(path.join(slotDir, 'machine-id'), 'utf8').trim(), physicalMid) + assert.equal(vm.machine_profile.device_id, profile.device_id) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) + +test('traits mode recreate rotates machine_profile, persists profile_generation/slot_epoch, and re-derives distinct identity on same account rebind (M4/M8)', async () => { + const { deriveSlotMachineProfile, ensureVmSlotMachineProfile } = await import( + '../../src/lib/identity/slot-machine-profile.mjs' + ) + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-recreate-traits-mp-')) + try { + const vmId = 'vm-traits-rotate' + const slotDir = path.join(root, 'vms', vmId) + fs.mkdirSync(path.join(slotDir, 'cli-home', '.claude'), { recursive: true }) + const template = path.join(root, 'share', 'wrap-cli') + fs.mkdirSync(template, { recursive: true }) + for (const name of ['kin-kernel.bin', 'cli-node']) fs.writeFileSync(path.join(template, name), name) + seedEncryptedPackage(root) + + const initialProfile = deriveSlotMachineProfile({ + accountUuid: 'acct-traits-same-1', + email: 'same@example.com', + osFamily: 'darwin', + pepper: 'test-pepper-traits', + }) + const prev = { + id: vmId, + name: 'traits-slot', + kernel: 'ubuntu-24.04', + runtime: { type: 'docker' }, + claude: { account_uuid: 'acct-traits-same-1', email: 'same@example.com', has_access: true }, + machine_profile: initialProfile, + fingerprint: { + hostname: initialProfile.hostname, + device_id: initialProfile.device_id, + }, + } + + const { vm } = recreateVmFiles(root, prev, { mode: 'traits' }) + assert.equal(vm.machine_profile_opt_in, true) + assert.equal(vm.profile_generation, 1) + assert.equal(vm.slot_epoch, 1) + assert.ok(vm.profile_reseed_nonce) + assert.ok(vm.machine_profile, 'traits recreate on 3-OS slot should rotate machine_profile') + assert.notEqual( + vm.machine_profile.device_id, + initialProfile.device_id, + 'traits rebuild must rotate machine_profile device_id', + ) + + // Re-importing the exact same account into the rebuilt slot must still derive a distinct profile + const rebound = ensureVmSlotMachineProfile( + vm, + { accountUuid: 'acct-traits-same-1', email: 'same@example.com' }, + { pepper: 'test-pepper-traits' }, + ) + assert.equal(rebound.changed, true) + assert.notEqual( + rebound.profile.device_id, + initialProfile.device_id, + 're-binding same account after traits rebuild must produce a distinct device_id', + ) + assert.notEqual(rebound.profile.tool_id_seed, initialProfile.tool_id_seed) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +})