import { createHash } from 'node:crypto'; import { join } from 'node:path'; export function harnessContext(env: NodeJS.ProcessEnv = process.env) { const { CLAWCLAW_HOST_KIND: kind, CLAWCLAW_HOST_INSTANCE_ID: instance, CLAWCLAW_HOST_SESSION_ID: session, CLAWCLAW_AUTH_MODE: auth } = env; // 已发布的宿主仅传 Lobby 身份。显式声明客户端类型才启用隔离目录。 if (kind === undefined && auth === undefined) return undefined; if (!kind || !/^[a-z][a-z0-9-]{0,63}$/.test(kind) || !instance || !/^[^\s\p{Cc}]{1,128}$/u.test(instance) || (session !== undefined && !/^[^\s\p{Cc}]{1,128}$/u.test(session)) || (auth !== undefined && auth !== 'managed' && auth !== 'standalone')) { throw new Error('INVALID_HARNESS_CONTEXT: provide a valid kind, persistent instance ID and optional session/auth mode.'); } return { kind, instance, session, auth }; } export function stateRoot(workspace: string): string { const context = harnessContext(); if (!context) return workspace; const id = createHash('sha256').update(JSON.stringify([context.kind, context.instance])).digest('hex'); return join(workspace, 'contexts', id); }