@myclaw163/clawclaw-cli 0.8.35 → 0.8.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,25 @@ $env:CLAWCLAW_WORKSPACE_DIR = 'D:\clawclaw-workspace'
31
31
  - `observability/`:本地脱敏运行日志。
32
32
  - `config.json`:workspace 级可选配置,例如自定义 TTS。
33
33
 
34
+ ### 单实例与测试多开
35
+
36
+ 一个 workspace 同时只允许一个常驻 Runtime,即使使用不同账号。`ccl events`、`ccl speak`、策略控制等短命令仍可与 Runtime 同时运行。Runtime 活跃时不能切换当前账号;先正常退出参与,再切换。
37
+
38
+ Windows 使用 `LockFileEx`,macOS 使用 `flock`,Linux 使用 OFD 文件锁。CCL 在整个 Runtime 生命周期持有 `runtime/owner.lock` 的系统锁,退出或崩溃后由操作系统释放;这个文件保留在磁盘上是正常情况,不应手动删除。`runtime/owner.json` 仅用于实例身份和恢复,不以其中的 PID 是否存在判断占用。
39
+
40
+ 测试多开时,为每个 Agent 设置不同的 `CLAWCLAW_WORKSPACE_DIR`,并确保该 Agent 的长流、短命令都继承同一目录。只切换终端当前目录不会改变 CCL workspace。该锁用于单机本地目录,不提供多台机器之间的互斥。
41
+
42
+ 确认旧 Runtime 需要替换时使用 `ccl join --force`:先通过认证控制通道停止旧实例;超时后核验进程创建身份再终止;取得系统锁后才启动新实例。无法确认身份、实例已变更或仍无法取得锁时停止恢复,不启动第二个 Runtime。`--force` 不会退出后端参与,也不替换同目录另一个账号的 Runtime。本机制不自动检测卡死。
43
+ 实例身份在取得系统锁前准备并写入临时文件,拿锁后的第一步原子发布为 `runtime/owner.json`;控制通道在模块、持久化和后端初始化之前建立,可在 `starting` 阶段接收停止请求。正常就绪和停止阶段分别记为 `ready`、`stopping`。
44
+
45
+ 启动冲突和恢复失败返回 `CCL_OWNER_*` 错误。Monitor 的 500 字符通知也保留 `blocker.pid`、`instance_id`、`pid_source`、`identity` 等诊断字段。`pid_source: owner_record` 表示 PID 来自实例记录,并非由操作系统查询到的锁持有者;`identity: matched` 只表示该 PID 当前进程与记录的创建身份匹配。核验不符、不可读取或未记录时分别返回 `mismatch`、`unavailable`、`not_recorded`。系统拒绝终止时仍保留这些信息,便于人工排查,不改用不加核验的杀进程路径。
46
+
47
+ 若系统锁仍被持有、身份记录却缺失或损坏,等待有限的发布窗口后返回 `CCL_OWNER_UNKNOWN`,其中 PID 为 `null`,不会猜测或扫描后强杀。进程在原子发布前退出时系统会释放锁,新实例可正常启动;若进程恰在这个极短窗口被挂起,或运行中身份文件被删除,则不能保证识别持有者。身份发布失败会主动释放已取得的系统锁。该机制不支持附着或重连已有本地 Runtime。
48
+
49
+ 新版不再生成或读取旧账号目录的 PID 锁,旧文件为空、损坏或残留都不会阻止启动。升级前先结束旧版 Runtime;旧版不遵守新的工作目录系统锁,因此混用旧版与新版不受单实例保证覆盖。
50
+
51
+ 发行包依赖 `fs-native-extensions`,其 npm 包包含 Windows、macOS Intel/Apple Silicon 的预编译文件。内嵌 CCL 的宿主需完整携带依赖及 `prebuilds/`,无需在安装时编译;只复制 JavaScript 源码是不完整的安装。
52
+
34
53
  运行 `ccl data path` 可取得适合手动迁移的 `user-data/` 路径。该目录含账号凭据,不能公开分享。它不包含运行态、SQLite、日志、`config.json` 或基础 Agent skill;复制到另一台机器后,先安装随 CCL 提供的基础 skill,再用 `ccl load` 同步并注册当前账号选中的 Hub Skill,用 `ccl behavior list` 和 `ccl trigger list` 验证静态目录,最后在新 Runtime 启动时验证实际加载。
35
54
 
36
55
  ### 账号 Hub 装配快照
@@ -14,7 +14,7 @@ Bash --> ccl start/join ... --> Owner --> Mailbox
14
14
 
15
15
  Claude Code 加载 `clawclaw-channel` 后启动 MCP stdio 子进程。该进程打开 workspace 级本地 IPC server 并发布带随机 token 的端点描述;它不读取 active profile 或 `game-start.json`。
16
16
 
17
- 可选 Channel 模式下,Agent 另用 Bash 后台启动顶层 `ccl start ... --agent-type claude-code` 或 `ccl join ...`,且进程环境包含 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1`。CCL 命令读取 active profile,Owner 取得账号级 `owner.lock`,装配 Channel Adapter。Owner 的 socket sink 主动读取端点描述、认证连接并 push Mailbox 批次。不存在“Channel 发现 Owner”或“Channel 绑定账号”。
17
+ 可选 Channel 模式下,Agent 另用 Bash 后台启动顶层 `ccl start ... --agent-type claude-code` 或 `ccl join ...`,且进程环境包含 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1`。CCL 命令读取 active profile,Owner 取得工作目录级系统锁 `runtime/owner.lock`,装配 Channel Adapter。Owner 的 socket sink 主动读取端点描述、认证连接并 push Mailbox 批次。不存在“Channel 发现 Owner”或“Channel 绑定账号”。
18
18
 
19
19
  | 角色 | 持有什么 | 何时结束 |
20
20
  | --- | --- | --- |
@@ -32,7 +32,7 @@ Owner 打开 Runtime/SQLite,读取当前账号已解析的 Hub/本地资源、
32
32
 
33
33
  `--agent-type claude-code` 本身只标识宿主;只有同时设置 `CLAWCLAW_ENABLE_CLAUDE_CHANNELS=1` 才启用 Claude Channel 输出,否则使用默认 Monitor 路由。两种路由都不改变账号选择和游戏生命周期。
34
34
 
35
- 同一账号重复启动由 `owner.lock` 拒绝。只有用户明确要替换本地 Runtime 时才使用 `--force`;它不代表退出后端队列、对局或房间。
35
+ 同一工作目录重复启动由 `runtime/owner.lock` 系统锁拒绝,即使账号不同。只有用户明确要替换本地 Runtime 时才使用 `--force`;它不代表退出后端队列、对局或房间。
36
36
 
37
37
  Channel 和 Owner 启动顺序没有门禁:
38
38
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.35",
3
+ "version": "0.8.36",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -68,6 +68,7 @@
68
68
  "@modelcontextprotocol/sdk": "^1.30.0",
69
69
  "amaro": "^1.1.11",
70
70
  "commander": "^12.0.0",
71
+ "fs-native-extensions": "1.5.1",
71
72
  "skills": "1.5.1",
72
73
  "tsx": "^4.23.12",
73
74
  "undici": "^6.28.0",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: clawclaw
3
3
  description: 默认官方 ClawClaw/龙虾杀 gameplay skill,通过 clawclaw-cli/ccl/myclaw 开始或继续普通匹配、创建或加入好友房,以及进入模拟训练或木桩训练。Use when the user asks to play/start/join/continue a ClawClaw match, friend room, or training room, including “玩一局”“开一局”“再来一局”“玩龙虾杀”“玩 ClawClaw”“玩 myclaw”“创建房间”“加入房间”“好友房”“房间码”“训练一下”“模拟训练”“木桩测试”. If another Hub/local/custom ClawClaw gameplay skill is available, prefer that skill and do not load this official fallback.
4
- version: 4.8.109
4
+ version: 4.8.110
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -202,6 +202,8 @@ Monitor(command="ccl join", timeout_ms=1800000, description="clawclaw event stre
202
202
 
203
203
  如果健康 Monitor 已存在,继续使用它,禁止启动第二条长流。只有 Monitor 已明确结束或失败后才恢复:先运行 `ccl join`;如果报 `A ClawClaw runtime is already running (pid <PID>)`,不要复用旧 Owner,改在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行 `ccl join --force`。`--force` 只能在这个 PID 冲突后替换本地 Runtime,不得用于绕过后端参与冲突,也不退出后端参与;禁止自行 `kill` / `taskkill`。
204
204
 
205
+ 同一 CCL workspace 只允许一个常驻 Runtime,即使账号不同;短命令不受此限制。测试多开必须给每个 Agent 设置不同的 `CLAWCLAW_WORKSPACE_DIR`,并让其全部命令继承该值。已有 Runtime 时先退出参与再切换账号。`--force` 会验证旧实例身份并等待系统锁释放;若报告身份无法确认、另一账号占用或实例已变更,应报告具体错误,不删除锁文件、不循环强制重试。恢复失败时将 `blocker.pid`、`instance_id` 和 `identity` 核验结果作为诊断信息说明;PID 为 `null` 表示无法确定,不能猜测。记录中的 PID 不代表已获准手动强杀;仍只使用 CCL 的安全接管流程。
206
+
205
207
  **参与流程:**
206
208
 
207
209
  1. 运行 `ccl load`,读取人设、记忆、配置启用的 Behavior/感知/Trigger 目录和后端 `participation`。
@@ -211,7 +211,7 @@ ccl join # 恢复后端
211
211
  ccl join --force # 挤掉旧本机 runtime,再恢复后端已有参与
212
212
  ```
213
213
 
214
- 这些命令本身都是持有后端连接、事件、Behavior 控制栈和通知输出的前台 Runtime 长进程。`start` 创建新参与,`join` 跟上已有参与。若同一账号已有存活 Runtime,普通启动会报 `A ClawClaw runtime is already running (pid <PID>)`,不会附着、复用或替换;异常恢复改用 `ccl join --force`。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。
214
+ 这些命令本身都是持有后端连接、事件、Behavior 控制栈和通知输出的前台 Runtime 长进程。`start` 创建新参与,`join` 跟上已有参与。若同一工作目录已有存活 Runtime,普通启动会报 `A ClawClaw runtime is already running (pid <PID>)`,不会附着、复用或替换;异常恢复改用 `ccl join --force`。只使用 CCL 的 `--force`,不要自行运行 `kill` / `taskkill`。
215
215
 
216
216
  模型使用当前实际运行的规范 ID。Claude Code 默认用持久 Monitor 运行顶层 `start` / `join`;只有可选 Channel 模式才使用 `channel_status`。游戏参与状态优先使用 `ccl load` 的 `participation`,需要单独复核时再用 `ccl game status`。
217
217
 
@@ -10,6 +10,7 @@ import {
10
10
  import { dirname, join, relative, resolve } from 'node:path';
11
11
  import { randomUUID } from 'node:crypto';
12
12
  import type { AuthProfile } from './auth.js';
13
+ import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js';
13
14
  import {
14
15
  resolveLocalAgentWorkspacePath,
15
16
  type LocalAgentWorkspaceItem,
@@ -190,6 +191,9 @@ export function switchActiveAccountSkillLinks(
190
191
  dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
191
192
  ): AccountSkillLinkSwitchResult {
192
193
  if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
194
+ const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir);
195
+ if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
196
+ guard.release();
193
197
  const targets = dependencies.targets ?? agentSkillTargets;
194
198
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
195
199
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
package/src/lib/auth.ts CHANGED
@@ -2,6 +2,7 @@ import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'f
2
2
  import { randomUUID } from 'crypto';
3
3
  import { join, dirname } from 'path';
4
4
  import { getWorkspaceDir } from './init-command.js';
5
+ import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from './workspace-runtime-lock.js';
5
6
  import {
6
7
  ensureUserDataLayout,
7
8
  getRuntimeAuthStateFile,
@@ -68,6 +69,7 @@ function profileKeyFor(
68
69
  export class AuthStore {
69
70
  private authFile: string;
70
71
  private runtimeAuthStateFile: string;
72
+ private workspaceDir?: string;
71
73
 
72
74
  constructor(authFile?: string, runtimeAuthStateFile?: string) {
73
75
  if (authFile) {
@@ -77,6 +79,7 @@ export class AuthStore {
77
79
  }
78
80
 
79
81
  const workspaceDir = getWorkspaceDir();
82
+ this.workspaceDir = workspaceDir;
80
83
  ensureUserDataLayout(workspaceDir);
81
84
  this.authFile = getUserDataAuthFile(workspaceDir);
82
85
  this.runtimeAuthStateFile = getRuntimeAuthStateFile(workspaceDir);
@@ -109,15 +112,28 @@ export class AuthStore {
109
112
  }
110
113
 
111
114
  private writeAuth(data: AuthData): void {
112
- const dir = dirname(this.authFile);
113
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
114
- writeFileSync(this.authFile, JSON.stringify(data, null, 2), {
115
- encoding: 'utf8',
116
- mode: 0o600,
117
- });
118
- // writeFileSync preserves an existing file's mode, so tighten migrated
119
- // installs as well. Windows keeps the enclosing user-profile ACL.
120
- try { chmodSync(this.authFile, 0o600); } catch {}
115
+ let guard: WorkspaceRuntimeLock | null = null;
116
+ if (this.workspaceDir) {
117
+ let previous: AuthData = EMPTY_AUTH;
118
+ try { previous = JSON.parse(readFileSync(this.authFile, 'utf8')) as AuthData; } catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
120
+ }
121
+ if (previous.profiles[previous.activeProfile]?.apiKey !== data.profiles[data.activeProfile]?.apiKey) {
122
+ guard = tryAcquireWorkspaceRuntimeLock(this.workspaceDir);
123
+ if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
124
+ }
125
+ }
126
+ try {
127
+ const dir = dirname(this.authFile);
128
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
129
+ writeFileSync(this.authFile, JSON.stringify(data, null, 2), {
130
+ encoding: 'utf8',
131
+ mode: 0o600,
132
+ });
133
+ // writeFileSync preserves an existing file's mode, so tighten migrated
134
+ // installs as well. Windows keeps the enclosing user-profile ACL.
135
+ try { chmodSync(this.authFile, 0o600); } catch {}
136
+ } finally { guard?.release(); }
121
137
  }
122
138
 
123
139
  private mergeRuntimeState(incoming: RuntimeAuthState): void {
@@ -0,0 +1,47 @@
1
+ import { closeSync, mkdirSync, openSync, realpathSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ import { getRuntimeDir } from './user-data.js';
5
+
6
+ interface NativeFileLocks {
7
+ tryLock(fd: number): boolean;
8
+ unlock(fd: number): void;
9
+ }
10
+
11
+ const require = createRequire(import.meta.url);
12
+ let nativeLocks: NativeFileLocks | undefined;
13
+ const held = new Set<string>();
14
+
15
+ export interface WorkspaceRuntimeLock {
16
+ release(): void;
17
+ }
18
+
19
+ /** The inode must remain in place: unlinking a locked file permits two owners. */
20
+ export function tryAcquireWorkspaceRuntimeLock(workspaceDir: string): WorkspaceRuntimeLock | null {
21
+ const directory = getRuntimeDir(workspaceDir);
22
+ mkdirSync(directory, { recursive: true });
23
+ const path = join(realpathSync(directory), 'owner.lock');
24
+ const key = process.platform === 'win32' ? path.toLowerCase() : path;
25
+ if (held.has(key)) return null;
26
+ // Load only for lifecycle operations; help/schema/short commands need no addon.
27
+ const locks = nativeLocks ??= require('fs-native-extensions') as NativeFileLocks;
28
+ const fd = openSync(path, 'a+', 0o600);
29
+ let acquired = false;
30
+ try {
31
+ acquired = locks.tryLock(fd);
32
+ if (!acquired) return null;
33
+ held.add(key);
34
+ let released = false;
35
+ return {
36
+ release() {
37
+ if (released) return;
38
+ released = true;
39
+ try { locks.unlock(fd); } finally {
40
+ try { closeSync(fd); } finally { held.delete(key); }
41
+ }
42
+ },
43
+ };
44
+ } finally {
45
+ if (!acquired) closeSync(fd);
46
+ }
47
+ }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  fitShortMonitorPayload,
3
3
  } from '../canonical-monitor.js';
4
+ import { OwnerLockError } from './owner-lock-error.js';
4
5
 
5
6
  export interface ClawclawOwnerNotificationHost {
6
7
  readonly mode: 'short';
@@ -20,6 +21,21 @@ export function formatClawclawBootstrapFailure(
20
21
  error: unknown,
21
22
  sensitiveValues: readonly string[] = [],
22
23
  ): Record<string, unknown> {
24
+ if (error instanceof OwnerLockError) {
25
+ const event = {
26
+ type: 'error', code: error.code, phase: 'bootstrap',
27
+ message: errorMessage(error.reason, sensitiveValues),
28
+ blocker: error.blocker,
29
+ ...(error.osError ? { os_error: error.osError } : {}),
30
+ };
31
+ const payload = { schema: 'ccl.monitor.v1', mode: 'short', events: [event] };
32
+ // Generic compaction drops error fields. Preserve PID/verification even when
33
+ // an OS failure is verbose, so the Agent never loses the recovery target.
34
+ while (JSON.stringify(payload).length > 500 && event.message.length > 0) {
35
+ event.message = event.message.slice(0, Math.max(0, event.message.length - 16));
36
+ }
37
+ return payload;
38
+ }
23
39
  const payload = {
24
40
  schema: 'ccl.monitor.v1',
25
41
  mode: 'short',
@@ -0,0 +1,25 @@
1
+ export type OwnerIdentityStatus = 'matched' | 'mismatch' | 'unavailable' | 'not_recorded';
2
+
3
+ /** A recorded candidate, not a claim that the OS returned the lock holder PID. */
4
+ export interface OwnerBlocker {
5
+ pid: number | null;
6
+ pid_source: 'owner_record' | 'unknown';
7
+ instance_id?: string;
8
+ phase?: 'starting' | 'ready' | 'stopping';
9
+ started_at_ms?: number;
10
+ identity: OwnerIdentityStatus;
11
+ }
12
+
13
+ export class OwnerLockError extends Error {
14
+ constructor(
15
+ readonly code: string,
16
+ readonly reason: string,
17
+ readonly blocker: OwnerBlocker,
18
+ readonly osError?: string,
19
+ ) {
20
+ super(`${reason} ${blocker.pid === null ? 'Blocker PID is unknown.'
21
+ : `Recorded pid ${blocker.pid}, instance ${blocker.instance_id}, identity ${blocker.identity}.`}`
22
+ + (osError ? ` OS error: ${osError}.` : ''));
23
+ this.name = 'OwnerLockError';
24
+ }
25
+ }
@@ -0,0 +1,221 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import type { AuthData, AuthProfile } from '../../lib/auth.js';
5
+ import { getRuntimeAccountId, getWorkspaceDir } from '../../lib/init-command.js';
6
+ import { getRuntimeDir, getUserDataAuthFile } from '../../lib/user-data.js';
7
+ import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from '../../lib/workspace-runtime-lock.js';
8
+ import { readGameStartRuntime, sendOwnerControlRequestTo } from '../owner-control.js';
9
+ import { inspectProcessIdentity, sameProcessIdentity, terminateVerifiedProcess,
10
+ type ProcessIdentity } from '../process-identity.js';
11
+ import { OwnerLockError, type OwnerBlocker } from './owner-lock-error.js';
12
+
13
+ export type OwnerPhase = 'starting' | 'ready' | 'stopping';
14
+ export interface OwnerLock extends WorkspaceRuntimeLock {
15
+ instanceId: string;
16
+ setPhase(phase: OwnerPhase): void;
17
+ }
18
+ export interface OwnerRecord {
19
+ schema: 'clawclaw.workspace-owner.v1';
20
+ instance_id: string;
21
+ pid: number;
22
+ runtime_account_id: string;
23
+ workspace_id: string;
24
+ process_identity: ProcessIdentity | null;
25
+ phase?: OwnerPhase;
26
+ }
27
+ export interface OwnerLockOperations {
28
+ inspectProcess(pid: number): ProcessIdentity | null;
29
+ requestStop(stateDir: string, owner: OwnerRecord): Promise<void>;
30
+ terminateProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void;
31
+ }
32
+ const defaultOperations: OwnerLockOperations = {
33
+ inspectProcess: inspectProcessIdentity,
34
+ async requestStop(stateDir, owner) {
35
+ const pointer = readGameStartRuntime(stateDir);
36
+ if (pointer?.owner_pid !== owner.pid || pointer?.instance_id !== owner.instance_id) return;
37
+ await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: owner.instance_id });
38
+ },
39
+ terminateProcess: terminateVerifiedProcess,
40
+ };
41
+ const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
42
+
43
+ export function workspaceOwnerRecordPath(workspaceDir = getWorkspaceDir()): string {
44
+ // Windows exclusive byte locks prevent reads, so metadata has its own file.
45
+ return join(getRuntimeDir(workspaceDir), 'owner.json');
46
+ }
47
+ export function workspaceOwnerIdentity(workspaceDir = getWorkspaceDir()): string {
48
+ const real = realpathSync(workspaceDir);
49
+ return createHash('sha256').update(process.platform === 'win32' ? real.toLowerCase() : real).digest('hex');
50
+ }
51
+ function readOwnerRecord(path: string): OwnerRecord | null {
52
+ try {
53
+ const value = JSON.parse(readFileSync(path, 'utf8')) as OwnerRecord;
54
+ return value?.schema === 'clawclaw.workspace-owner.v1'
55
+ && Number.isSafeInteger(value.pid) && value.pid > 0
56
+ && typeof value.instance_id === 'string' && value.instance_id.length > 0 && value.instance_id.length <= 64
57
+ && /^[a-f0-9]{64}$/.test(value.workspace_id)
58
+ && /^acct_[a-f0-9]{32}$/.test(value.runtime_account_id) ? value : null;
59
+ } catch { return null; }
60
+ }
61
+ function validIdentity(value: ProcessIdentity | null): value is ProcessIdentity {
62
+ return !!value && typeof value.birth === 'string' && value.birth.length > 0
63
+ && typeof value.executable === 'string' && value.executable.length > 0
64
+ && Number.isFinite(value.startedAtMs);
65
+ }
66
+ function describeBlocker(record: OwnerRecord | null, operations: OwnerLockOperations): OwnerBlocker {
67
+ if (!record) return { pid: null, pid_source: 'unknown', identity: 'not_recorded' };
68
+ const expected = validIdentity(record.process_identity) ? record.process_identity : null;
69
+ const actual = expected ? operations.inspectProcess(record.pid) : null;
70
+ return {
71
+ pid: record.pid, pid_source: 'owner_record', instance_id: record.instance_id,
72
+ phase: ['starting', 'ready', 'stopping'].includes(record.phase ?? '') ? record.phase : undefined,
73
+ ...(expected ? { started_at_ms: expected.startedAtMs } : {}),
74
+ identity: !expected ? 'not_recorded' : !actual ? 'unavailable'
75
+ : sameProcessIdentity(expected, actual) ? 'matched' : 'mismatch',
76
+ };
77
+ }
78
+ function claimOwner(
79
+ held: WorkspaceRuntimeLock,
80
+ workspaceDir: string,
81
+ profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
82
+ record: OwnerRecord,
83
+ tempPath: string,
84
+ ): OwnerLock {
85
+ const recordPath = workspaceOwnerRecordPath(workspaceDir);
86
+ try {
87
+ // All expensive preparation and the complete write happened BEFORE locking.
88
+ // The first operation after winning the system lock publishes our identity.
89
+ renameSync(tempPath, recordPath);
90
+ let auth: AuthData | undefined;
91
+ try { auth = JSON.parse(readFileSync(getUserDataAuthFile(workspaceDir), 'utf8')) as AuthData; } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
93
+ }
94
+ if (auth && auth.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
95
+ throw new Error('The active ClawClaw account changed during startup. Retry with the current account.');
96
+ }
97
+ let released = false;
98
+ return {
99
+ instanceId: record.instance_id,
100
+ setPhase(phase) {
101
+ if (released) throw new Error('ClawClaw workspace lock is already released.');
102
+ if (readOwnerRecord(recordPath)?.instance_id !== record.instance_id) {
103
+ throw new Error('ClawClaw owner metadata changed while the workspace is locked.');
104
+ }
105
+ record.phase = phase;
106
+ try {
107
+ writeFileSync(tempPath, JSON.stringify(record), { mode: 0o600 });
108
+ renameSync(tempPath, recordPath);
109
+ } finally { try { unlinkSync(tempPath); } catch {} }
110
+ },
111
+ release() {
112
+ if (released) return;
113
+ released = true;
114
+ try {
115
+ if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) {
116
+ try { unlinkSync(recordPath); } catch {}
117
+ }
118
+ } finally { held.release(); }
119
+ },
120
+ };
121
+ } catch (error) {
122
+ try {
123
+ if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) unlinkSync(recordPath);
124
+ } catch {}
125
+ held.release();
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ export async function acquireOwnerLock(
131
+ profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
132
+ options: { force?: boolean; operations?: OwnerLockOperations } = {},
133
+ ): Promise<OwnerLock> {
134
+ const workspaceDir = getWorkspaceDir();
135
+ const operations = options.operations ?? defaultOperations;
136
+ const recordPath = workspaceOwnerRecordPath(workspaceDir);
137
+ mkdirSync(dirname(recordPath), { recursive: true });
138
+ const prepared: OwnerRecord = {
139
+ schema: 'clawclaw.workspace-owner.v1', instance_id: randomUUID(), pid: process.pid,
140
+ runtime_account_id: getRuntimeAccountId(profile), process_identity: operations.inspectProcess(process.pid),
141
+ workspace_id: workspaceOwnerIdentity(workspaceDir),
142
+ phase: 'starting',
143
+ };
144
+ const tempPath = `${recordPath}.${prepared.instance_id}.tmp`;
145
+ const claim = (held: WorkspaceRuntimeLock) => claimOwner(held, workspaceDir, profile, prepared, tempPath);
146
+ const fail = (code: string, reason: string, record: OwnerRecord | null, osError?: string): never => {
147
+ throw new OwnerLockError(code, reason, describeBlocker(record, operations), osError);
148
+ };
149
+ try {
150
+ writeFileSync(tempPath, JSON.stringify(prepared), { mode: 0o600, flag: 'wx' });
151
+ let record: OwnerRecord | null = null;
152
+ for (let attempt = 0; attempt < 40; attempt++) {
153
+ const held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
154
+ if (held) return claim(held);
155
+ record = readOwnerRecord(recordPath);
156
+ if (record) break;
157
+ await sleep(50);
158
+ }
159
+ if (!record) return fail('CCL_OWNER_UNKNOWN', 'Workspace locked; owner identity is missing, unreadable, or incomplete. No process was terminated.', null);
160
+ if (record.workspace_id !== prepared.workspace_id) {
161
+ return fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record belongs to a different workspace. No process was terminated.', record);
162
+ }
163
+ if (!options.force) {
164
+ return fail('CCL_OWNER_BUSY', `A ClawClaw runtime is already running (pid ${record.pid}) in this workspace. Re-run with --force to replace it.`, record);
165
+ }
166
+ if (record.runtime_account_id !== prepared.runtime_account_id) {
167
+ return fail('CCL_OWNER_OTHER_ACCOUNT', 'Another account owns this workspace. Stop it first or use a different workspace.', record);
168
+ }
169
+ if (record.pid === process.pid) return fail('CCL_OWNER_SELF', 'Refusing to replace the current ClawClaw runtime process.', record);
170
+ const target = record;
171
+ const checkGeneration = (requireRecord: boolean): void => {
172
+ const current = readOwnerRecord(recordPath);
173
+ if (current && current.instance_id !== target.instance_id) {
174
+ fail('CCL_OWNER_CHANGED', 'The active ClawClaw runtime changed during replacement; no new instance was terminated.', current);
175
+ }
176
+ if (current && current.workspace_id !== prepared.workspace_id) {
177
+ fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record changed to a different workspace. No process was terminated.', current);
178
+ }
179
+ if (!current && requireRecord) {
180
+ fail('CCL_OWNER_UNKNOWN', 'Owner identity disappeared while the workspace remained locked. No process was terminated.', null);
181
+ }
182
+ };
183
+ const waitForLock = async (timeoutMs: number): Promise<WorkspaceRuntimeLock | null> => {
184
+ const deadline = Date.now() + timeoutMs;
185
+ do {
186
+ const held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
187
+ if (held) return held;
188
+ // Normal teardown removes metadata just before releasing the system lock.
189
+ checkGeneration(false);
190
+ await sleep(50);
191
+ } while (Date.now() < deadline);
192
+ return null;
193
+ };
194
+ checkGeneration(true);
195
+ const stateDir = join(getRuntimeDir(workspaceDir), 'accounts', target.runtime_account_id);
196
+ try { await operations.requestStop(stateDir, target); } catch {}
197
+ let held = await waitForLock(1_500);
198
+ if (held) return claim(held);
199
+ for (const [signal, timeout] of [['SIGTERM', 1_500], ['SIGKILL', 2_000]] as const) {
200
+ held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
201
+ if (held) return claim(held);
202
+ checkGeneration(true);
203
+ if (!validIdentity(target.process_identity)
204
+ || !sameProcessIdentity(target.process_identity, operations.inspectProcess(target.pid))) {
205
+ return fail('CCL_OWNER_UNVERIFIED', 'Unable to verify the recorded runtime identity; no process was terminated.', target);
206
+ }
207
+ try { operations.terminateProcess(target.pid, target.process_identity, signal); } catch (error) {
208
+ // The target may have exited between verification and signalling.
209
+ held = tryAcquireWorkspaceRuntimeLock(workspaceDir);
210
+ if (held) return claim(held);
211
+ checkGeneration(true);
212
+ const osError = typeof (error as NodeJS.ErrnoException)?.code === 'string'
213
+ ? (error as NodeJS.ErrnoException).code!.slice(0, 40) : 'termination_failed';
214
+ return fail('CCL_OWNER_STOP_FAILED', 'The OS did not terminate the old runtime; the workspace remains locked.', target, osError);
215
+ }
216
+ held = await waitForLock(timeout);
217
+ if (held) return claim(held);
218
+ }
219
+ return fail('CCL_OWNER_STOP_FAILED', 'Unable to replace the old runtime; the workspace remains locked.', target);
220
+ } finally { try { unlinkSync(tempPath); } catch {} }
221
+ }
@@ -1,9 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { spawnSync } from 'node:child_process';
2
+ import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
3
+ import { createStartingOwnerControl } from './starting-owner-control.js';
4
+ export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js';
3
5
  import {
4
6
  chmodSync,
5
- closeSync,
6
- openSync,
7
7
  readFileSync,
8
8
  renameSync,
9
9
  unlinkSync,
@@ -43,7 +43,6 @@ import {
43
43
  import {
44
44
  gameStartRuntimePath,
45
45
  readGameStartRuntime,
46
- sendProfileOwnerControlRequest,
47
46
  startOwnerControlServer,
48
47
  type OwnerControlServer,
49
48
  } from '../owner-control.js';
@@ -251,9 +250,6 @@ export function deriveClawclawOwnerRuntimeStart(
251
250
  };
252
251
  }
253
252
 
254
- export interface OwnerLock {
255
- release(): void;
256
- }
257
253
 
258
254
  interface OwnerRuntimePointer {
259
255
  release(): void;
@@ -263,10 +259,6 @@ const MAILBOX_DRAIN_TIMEOUT_MS = 2_000;
263
259
  const DESKTOP_RESOURCE_LOCALE = 'zh-CN';
264
260
  const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 10_000;
265
261
  const LOCAL_STOP_FORCE_EXIT_MS = 10_000;
266
- const FORCE_STOP_GRACE_MS = 1_500;
267
- const FORCE_STOP_TERM_MS = 1_500;
268
- const FORCE_STOP_KILL_MS = 2_000;
269
- const FORCE_STOP_POLL_MS = 50;
270
262
 
271
263
  type ConfigurationWarning = (code: string, details: Readonly<Record<string, unknown>>) => void;
272
264
 
@@ -428,206 +420,17 @@ async function waitForMailboxDrain(
428
420
  return true;
429
421
  }
430
422
 
431
- function processAlive(pid: number): boolean {
432
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
433
- try {
434
- process.kill(pid, 0);
435
- return true;
436
- } catch {
437
- return false;
438
- }
439
- }
440
-
441
- function terminateRuntimeProcessTree(pid: number, signal: NodeJS.Signals): boolean {
442
- if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) return false;
443
- if (process.platform === 'win32') {
444
- const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? 'C:\\Windows';
445
- const result = spawnSync(join(systemRoot, 'System32', 'taskkill.exe'), [
446
- '/PID',
447
- String(pid),
448
- '/T',
449
- '/F',
450
- ], {
451
- stdio: 'ignore',
452
- windowsHide: true,
453
- timeout: FORCE_STOP_TERM_MS,
454
- });
455
- return result.status === 0 || !processAlive(pid);
456
- }
457
-
458
- const childSignal = signal === 'SIGKILL' ? '-KILL' : '-TERM';
459
- try {
460
- spawnSync('pkill', [childSignal, '-P', String(pid)], {
461
- stdio: 'ignore',
462
- timeout: FORCE_STOP_TERM_MS,
463
- });
464
- } catch {}
465
- try {
466
- process.kill(pid, signal);
467
- return true;
468
- } catch {
469
- return !processAlive(pid);
470
- }
471
- }
472
-
473
- async function waitForProcessExit(
474
- pid: number,
475
- timeoutMs: number,
476
- isAlive = processAlive,
477
- ): Promise<boolean> {
478
- const deadline = Date.now() + timeoutMs;
479
- while (Date.now() < deadline) {
480
- if (!isAlive(pid)) return true;
481
- await new Promise((resolve) => setTimeout(resolve, FORCE_STOP_POLL_MS));
482
- }
483
- return !isAlive(pid);
484
- }
485
-
486
- export interface OwnerLockOperations {
487
- processAlive(pid: number): boolean;
488
- requestStop(
489
- profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
490
- expectedPid: number,
491
- ): Promise<void>;
492
- terminateProcessTree(pid: number, signal: NodeJS.Signals): boolean;
493
- waitForExit(pid: number, timeoutMs: number): Promise<boolean>;
494
- }
495
-
496
- const defaultOwnerLockOperations: OwnerLockOperations = {
497
- processAlive,
498
- requestStop: async (profile, expectedPid) => {
499
- const stateDir = getProfileRuntimeStateDir(profile);
500
- const pointer = readGameStartRuntime(stateDir);
501
- const pointerPid = Number(pointer?.owner_pid ?? pointer?.pid);
502
- if (pointerPid !== expectedPid) return;
503
- try {
504
- await sendProfileOwnerControlRequest(profile, 'stop');
505
- } catch {}
506
- },
507
- terminateProcessTree: terminateRuntimeProcessTree,
508
- waitForExit: (pid, timeoutMs) => waitForProcessExit(pid, timeoutMs),
509
- };
510
-
511
- function readOwnerLockPid(path: string): number | null {
512
- try {
513
- const pid = Number((JSON.parse(readFileSync(path, 'utf8')) as { pid?: number }).pid);
514
- return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
515
- } catch {
516
- return null;
517
- }
518
- }
519
-
520
- function removeOwnerLockForPid(path: string, pid: number): boolean {
521
- try {
522
- if (readOwnerLockPid(path) !== pid) return false;
523
- unlinkSync(path);
524
- return true;
525
- } catch {
526
- return false;
527
- }
528
- }
529
-
530
- function removeRuntimePointerForPid(stateDir: string, pid: number): void {
531
- const pointer = readGameStartRuntime(stateDir);
532
- const pointerPid = Number(pointer?.owner_pid ?? pointer?.pid);
533
- if (pointerPid !== pid) return;
534
- const controlPath = typeof pointer?.control?.path === 'string' ? pointer.control.path : '';
535
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
536
- if (process.platform !== 'win32' && controlPath) {
537
- try { unlinkSync(controlPath); } catch {}
538
- }
539
- }
540
-
541
- async function stopExistingRuntime(
542
- profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
543
- pid: number,
544
- operations: OwnerLockOperations,
545
- ): Promise<void> {
546
- try { await operations.requestStop(profile, pid); } catch {}
547
- if (await operations.waitForExit(pid, FORCE_STOP_GRACE_MS)) return;
548
-
549
- operations.terminateProcessTree(pid, 'SIGTERM');
550
- if (await operations.waitForExit(pid, FORCE_STOP_TERM_MS)) return;
551
-
552
- operations.terminateProcessTree(pid, 'SIGKILL');
553
- if (await operations.waitForExit(pid, FORCE_STOP_KILL_MS)) return;
554
-
555
- throw new Error(`Unable to replace the running ClawClaw runtime (pid ${pid}).`);
556
- }
557
-
558
- export async function acquireOwnerLock(
559
- profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
560
- options: {
561
- force?: boolean;
562
- operations?: OwnerLockOperations;
563
- } = {},
564
- ): Promise<OwnerLock> {
565
- const stateDir = getProfileRuntimeStateDir(profile);
566
- const path = join(stateDir, 'owner.lock');
567
- const operations = options.operations ?? defaultOwnerLockOperations;
568
- let replacementPid: number | undefined;
569
- for (let attempt = 0; attempt < 4; attempt += 1) {
570
- try {
571
- const fd = openSync(path, 'wx');
572
- writeFileSync(fd, JSON.stringify({ pid: process.pid, started_at: new Date().toISOString() }));
573
- closeSync(fd);
574
- let released = false;
575
- return {
576
- release: () => {
577
- if (released) return;
578
- released = true;
579
- try {
580
- const current = JSON.parse(readFileSync(path, 'utf8')) as { pid?: number };
581
- if (current.pid === process.pid) unlinkSync(path);
582
- } catch {}
583
- },
584
- };
585
- } catch (error: any) {
586
- if (error?.code !== 'EEXIST') throw error;
587
- const ownerPid = readOwnerLockPid(path);
588
- if (ownerPid === null) {
589
- try { unlinkSync(path); } catch {}
590
- continue;
591
- }
592
- if (!operations.processAlive(ownerPid)) {
593
- removeRuntimePointerForPid(stateDir, ownerPid);
594
- removeOwnerLockForPid(path, ownerPid);
595
- continue;
596
- }
597
- if (!options.force) {
598
- throw new Error(
599
- `A ClawClaw runtime is already running (pid ${ownerPid}). Re-run with --force to replace it.`,
600
- );
601
- }
602
- if (ownerPid === process.pid) {
603
- throw new Error('Refusing to replace the current ClawClaw runtime process.');
604
- }
605
- if (replacementPid !== undefined && replacementPid !== ownerPid) {
606
- throw new Error(
607
- `The active ClawClaw runtime changed from pid ${replacementPid} to pid ${ownerPid}; refusing to replace the new process.`,
608
- );
609
- }
610
- replacementPid = ownerPid;
611
- await stopExistingRuntime(profile, ownerPid, operations);
612
- if (operations.processAlive(ownerPid)) {
613
- throw new Error(`Unable to replace the running ClawClaw runtime (pid ${ownerPid}).`);
614
- }
615
- removeRuntimePointerForPid(stateDir, ownerPid);
616
- removeOwnerLockForPid(path, ownerPid);
617
- }
618
- }
619
- throw new Error('Unable to acquire the ClawClaw runtime owner lock.');
620
- }
621
-
622
423
  export function publishOwnerRuntimePointer(
623
424
  stateDir: string,
624
425
  control: OwnerControlServer,
426
+ instanceId?: string,
625
427
  ): OwnerRuntimePointer {
626
428
  const path = gameStartRuntimePath(stateDir);
627
429
  const tempPath = `${path}.${process.pid}.tmp`;
628
430
  const value = {
629
431
  schema: 'clawclaw.owner.v1',
630
432
  owner_pid: process.pid,
433
+ ...(instanceId ? { instance_id: instanceId } : {}),
631
434
  started_at: new Date().toISOString(),
632
435
  control: control.control,
633
436
  control_token: control.token,
@@ -683,6 +486,7 @@ export async function runClawclawOwner(
683
486
  let mailboxBroker: MailboxRelayBroker | undefined;
684
487
  let ownerControl: OwnerControlServer | undefined;
685
488
  let runtimePointer: OwnerRuntimePointer | undefined;
489
+ let startingControl: ReturnType<typeof createStartingOwnerControl> | undefined;
686
490
  let relayAlive = false;
687
491
  let relayAbort: AbortController | undefined;
688
492
  let relayPromise: Promise<void> | undefined;
@@ -695,6 +499,7 @@ export async function runClawclawOwner(
695
499
  const requestLocalStop = (): void => {
696
500
  if (localStopRequested) return;
697
501
  localStopRequested = true;
502
+ try { lock?.setPhase('stopping'); } catch {}
698
503
  forceExitTimer = setTimeout(() => process.exit(1), LOCAL_STOP_FORCE_EXIT_MS);
699
504
  forceExitTimer.unref?.();
700
505
  void source?.submitIntent({ kind: 'stop' }).catch(() => {});
@@ -705,7 +510,26 @@ export async function runClawclawOwner(
705
510
  lock = await acquireOwnerLock(options.profile, {
706
511
  force: options.forceExistingRuntime === true,
707
512
  });
513
+ startingControl = createStartingOwnerControl(lock.instanceId, requestLocalStop);
514
+ ownerControl = await startOwnerControlServer(
515
+ getProfileRuntimeStateDir(options.profile), startingControl.handle,
516
+ { get observability() { return telemetry; } },
517
+ );
518
+ runtimePointer = publishOwnerRuntimePointer(
519
+ getProfileRuntimeStateDir(options.profile), ownerControl, lock.instanceId,
520
+ );
521
+ parentWatch = watchParentProcess(() => {
522
+ runtime?.diagnostic('runtime.owner.parent_exited', {
523
+ parent_pid: parentWatch?.parentPid ?? process.ppid,
524
+ }, 'warn');
525
+ requestLocalStop();
526
+ });
527
+ process.on('SIGINT', onSignal);
528
+ process.on('SIGTERM', onSignal);
708
529
  telemetry = createOwnerTelemetryRecorder(options.profile);
530
+ telemetry.log('info', 'owner.control.started', { transport: ownerControl.control.kind }, {
531
+ component: 'runtime.owner_control',
532
+ });
709
533
  const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
710
534
  if (fullDiagnosticsEnabled) {
711
535
  const retention = observabilityRetention();
@@ -1112,9 +936,7 @@ export async function runClawclawOwner(
1112
936
  }, 'error');
1113
937
  });
1114
938
  }
1115
- ownerControl = await startOwnerControlServer(
1116
- getProfileRuntimeStateDir(options.profile),
1117
- async (request, context) => {
939
+ startingControl.setHandler(async (request, context) => {
1118
940
  if (context.principal === 'host_relay') {
1119
941
  if (request.type === 'mailbox_claim') mailboxService?.prepareMonitor();
1120
942
  return mailboxBroker?.handle(request) ?? { ok: false, error: 'mailbox_monitor_unavailable' };
@@ -1429,10 +1251,7 @@ export async function runClawclawOwner(
1429
1251
  config: latest.triggers[request.trigger] ?? null,
1430
1252
  };
1431
1253
  }
1432
- if (request.type === 'stop') {
1433
- requestLocalStop();
1434
- return { ok: true, type: request.type };
1435
- }
1254
+
1436
1255
  if (request.type === 'quit' || request.type === 'leave') {
1437
1256
  await ownerSource.submitIntent({ kind: 'leave' });
1438
1257
  return { ok: true, type: request.type };
@@ -1462,27 +1281,13 @@ export async function runClawclawOwner(
1462
1281
  return { ok: true, type: request.type, result };
1463
1282
  }
1464
1283
  return { ok: false, error: 'owner_request_not_supported' };
1465
- },
1466
- {
1467
- observability: telemetry,
1468
- },
1469
- );
1470
- runtimePointer = publishOwnerRuntimePointer(
1471
- getProfileRuntimeStateDir(options.profile),
1472
- ownerControl,
1473
- );
1474
- parentWatch = watchParentProcess(() => {
1475
- runtime?.diagnostic('runtime.owner.parent_exited', {
1476
- parent_pid: parentWatch?.parentPid ?? process.ppid,
1477
- }, 'warn');
1478
- requestLocalStop();
1479
1284
  });
1480
- process.on('SIGINT', onSignal);
1481
- process.on('SIGTERM', onSignal);
1285
+ if (localStopRequested) return { reason: 'stopped' };
1482
1286
  await runtime.startSourcePlugin(ownerSource);
1483
1287
  await desktopEventPump?.flush();
1484
1288
  await channelEventPump?.flush();
1485
1289
  if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' });
1290
+ if (!localStopRequested) lock.setPhase('ready');
1486
1291
  options.notificationHost?.markMailboxReady();
1487
1292
  const completion = await source.waitForCompletion();
1488
1293
  await runtime.flush();
@@ -0,0 +1,26 @@
1
+ import type { OwnerControlRequest, OwnerControlRequestContext, OwnerControlResponse } from '../owner-control.js';
2
+
3
+ type OwnerRequestHandler = (
4
+ request: OwnerControlRequest, context: OwnerControlRequestContext,
5
+ ) => OwnerControlResponse | Promise<OwnerControlResponse>;
6
+
7
+ /** Stop works before modules, persistence, or backend transports initialize. */
8
+ export function createStartingOwnerControl(instanceId: string, requestStop: () => void) {
9
+ let handler: OwnerRequestHandler | undefined;
10
+ return {
11
+ setHandler(value: OwnerRequestHandler) { handler = value; },
12
+ handle: ((request, context) => {
13
+ if (context.principal === 'master' && request.type === 'stop') {
14
+ if (request.instance_id !== undefined && request.instance_id !== instanceId) {
15
+ return { ok: false, error: 'owner_instance_changed', instance_id: instanceId };
16
+ }
17
+ requestStop();
18
+ return { ok: true, type: 'stop', instance_id: instanceId };
19
+ }
20
+ if (!handler) {
21
+ return { ok: false, error: 'runtime_starting', retryable: true, instance_id: instanceId, pid: process.pid };
22
+ }
23
+ return handler(request, context);
24
+ }) satisfies OwnerRequestHandler,
25
+ };
26
+ }
@@ -282,6 +282,16 @@ export function sendOwnerControlRequest(
282
282
  timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
283
283
  ): Promise<OwnerControlResponse | null> {
284
284
  const info = readGameStartRuntime(stateDir);
285
+ return sendOwnerControlRequestTo(info, type, payload, timeoutMs);
286
+ }
287
+
288
+ /** Use a captured endpoint when replacing an owner; do not re-read a newer pointer. */
289
+ export function sendOwnerControlRequestTo(
290
+ info: Record<string, any> | null,
291
+ type: OwnerControlType,
292
+ payload: Record<string, any> = {},
293
+ timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
294
+ ): Promise<OwnerControlResponse | null> {
285
295
  const path = typeof info?.control?.path === 'string' ? info.control.path : '';
286
296
  const token = typeof info?.control_token === 'string' ? info.control_token : '';
287
297
  if (!path || !token) return Promise.resolve(null);
@@ -0,0 +1,72 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync, readlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ export interface ProcessIdentity {
6
+ /** OS process creation value, never the time the lock file was written. */
7
+ birth: string;
8
+ startedAtMs: number;
9
+ executable: string;
10
+ }
11
+
12
+ export function inspectProcessIdentity(pid: number): ProcessIdentity | null {
13
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
14
+ try {
15
+ if (process.platform === 'win32') {
16
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
17
+ const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
18
+ + '$t=$p.StartTime.ToUniversalTime(); '
19
+ + '@{birth=$t.Ticks.ToString();startedAtMs=([DateTimeOffset]$t).ToUnixTimeMilliseconds();executable=$p.ProcessName} | ConvertTo-Json -Compress';
20
+ const output = execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
21
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
22
+ { encoding: 'utf8', windowsHide: true, timeout: 5_000, stdio: ['ignore', 'pipe', 'ignore'] });
23
+ return JSON.parse(output) as ProcessIdentity;
24
+ }
25
+ if (process.platform === 'linux') {
26
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
27
+ const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
28
+ const boot = Number(/^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]);
29
+ const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2_000 }));
30
+ return { birth: `${boot}:${ticks}`, startedAtMs: (boot + ticks / hz) * 1_000,
31
+ executable: readlinkSync(`/proc/${pid}/exe`) };
32
+ }
33
+ if (process.platform === 'darwin') {
34
+ const options = { encoding: 'utf8' as const, timeout: 2_000, env: { ...process.env, LC_ALL: 'C' } };
35
+ const birth = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'lstart='], options).trim();
36
+ const executable = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'comm='], options).trim();
37
+ const startedAtMs = Date.parse(birth);
38
+ return birth && executable && Number.isFinite(startedAtMs) ? { birth, startedAtMs, executable } : null;
39
+ }
40
+ } catch {}
41
+ return null;
42
+ }
43
+
44
+ export function sameProcessIdentity(a: ProcessIdentity | null, b: ProcessIdentity | null): boolean {
45
+ return !!a && !!b && a.birth === b.birth && a.executable === b.executable;
46
+ }
47
+
48
+ /** Recheck immediately before signalling; a PID alone never authorizes a kill. */
49
+ export function terminateVerifiedProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void {
50
+ if (pid === process.pid || !sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
51
+ throw new Error(`Refusing to terminate an unverified ClawClaw runtime (pid ${pid}).`);
52
+ }
53
+ if (process.platform === 'win32') {
54
+ const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
55
+ if (!/^\d+$/.test(identity.birth)) throw new Error('Invalid Windows process creation identity.');
56
+ // Retain the kernel handle before validating creation time. Killing via that
57
+ // Process object cannot target a later process that happens to reuse the PID.
58
+ // Runtime computation workers are threads of this process, so they exit too.
59
+ const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
60
+ + `try { $null=$p.Handle; if ($p.StartTime.ToUniversalTime().Ticks.ToString() -ne '${identity.birth}') `
61
+ + "{ throw 'runtime_identity_changed' }; $p.Kill(); } finally { $p.Dispose() }";
62
+ execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
63
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
64
+ { stdio: 'ignore', windowsHide: true, timeout: 5_000 });
65
+ return;
66
+ }
67
+ if (sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
68
+ try { process.kill(pid, signal); } catch (error) {
69
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
70
+ }
71
+ }
72
+ }