@seamnet/client 0.20.0 → 0.20.2

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.
package/bin/seam.js CHANGED
@@ -499,16 +499,23 @@ async function cmdTerm(subAction, restArgs) {
499
499
  if (!values.session) output(false, '--session required');
500
500
  // 关之前查 registry:这个 session 是否绑着一个 guardian
501
501
  let guardianEntry = null;
502
+ let registryReadError = null;
502
503
  try {
503
504
  const { readAll } = await import('../lib/registry.js');
504
505
  guardianEntry = readAll().find((e) => e.tmux_session === values.session) || null;
505
- } catch {}
506
+ } catch (e) {
507
+ // registry 读失败不静默——stop 杀了 guardian 不能悄无声息
508
+ registryReadError = e.message;
509
+ }
506
510
  try {
507
511
  const { kind } = tmuxUtils.stopTerm(values.session);
508
512
  const result = { session: values.session, kind, stopped: true };
509
513
  if (guardianEntry) {
510
514
  result.guardian_killed = true;
511
515
  result.warning = `注意:已一并终止该 home 的 guardian(userId=${guardianEntry.userId}, home=${guardianEntry.seam_home})`;
516
+ } else if (registryReadError) {
517
+ result.warning = `registry 读取失败(${registryReadError})——无法确认该会话是否绑 guardian;`
518
+ + `若这是 cc 会话(kind=${kind}),guardian 可能已随会话一并终止`;
512
519
  } else if (kind === 'cc') {
513
520
  result.warning = '注意:这是个 cc 会话——若它绑着 guardian,guardian 已随会话一并终止';
514
521
  }
@@ -532,11 +539,13 @@ async function cmdTerm(subAction, restArgs) {
532
539
  if (!values.session) output(false, '--session required');
533
540
  const continueSession = values['no-continue'] ? false : true;
534
541
  try {
535
- const ok = await tmuxUtils.restartTerm(values.session, { continueSession });
536
- if (ok) {
537
- output(true, { session: values.session, restarted: true });
542
+ const r = await tmuxUtils.restartTerm(values.session, { continueSession });
543
+ if (r.ok) {
544
+ const result = { session: values.session, restarted: true, startCmd: r.startCmd };
545
+ if (r.warning) result.warning = r.warning;
546
+ output(true, result);
538
547
  } else {
539
- output(false, 'restart failed: 终端未在超时内退出或重启');
548
+ output(false, r.warning || 'restart failed: 终端未在超时内退出或重启');
540
549
  }
541
550
  } catch (e) {
542
551
  output(false, e.message);
package/lib/guardian.js CHANGED
@@ -253,13 +253,14 @@ export async function guardianRun() {
253
253
  setTimeout(async () => {
254
254
  try {
255
255
  const { restartTerm } = require('./tmux-utils.cjs');
256
- const ok = await restartTerm(safeSession, { socketPath: ccSocket, continueSession: true });
257
- if (ok) {
256
+ const r = await restartTerm(safeSession, { socketPath: ccSocket, continueSession: true });
257
+ if (r.ok) {
258
258
  guardianState.set('cc_restarted', new Date().toISOString());
259
259
  if (isUpgradeRestart) guardianState.delete('pending_upgrade_restart');
260
260
  hub.logger('guardian').info('cc_restart_injected');
261
+ if (r.warning) hub.logger('guardian').warn('cc_restart_warning', { warning: r.warning });
261
262
  } else {
262
- hub.logger('guardian').error('cc_restart_failed', new Error('restartTerm returned false'));
263
+ hub.logger('guardian').error('cc_restart_failed', new Error(r.warning || 'restartTerm returned ok:false'));
263
264
  }
264
265
  } catch (e) {
265
266
  hub.logger('guardian').error('cc_restart_failed', e);
@@ -5,8 +5,8 @@
5
5
  * 这层与 pane 里跑什么无关。交互语义(审批流、idle 判断等)故意不抽象——
6
6
  * 由操作者读屏自己决定按什么键。
7
7
  *
8
- * 唯一的 per-kind 知识:KIND_CMD 表(kind → 默认启动命令);restart
9
- * cc 走优雅 /exit(跑 Stop hook 保命),codex 走 kill 重起。
8
+ * 唯一的 per-kind 知识:KIND_CMD 表(kind → 启动/续命/退出/超时)。restart
9
+ * cc codex 都走对称的优雅路径,差别全在表里。
10
10
  */
11
11
 
12
12
  const { execSync } = require('node:child_process');
@@ -15,11 +15,33 @@ const { basename } = require('node:path');
15
15
 
16
16
  const EXEC_OPTS = { encoding: 'utf8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'] };
17
17
 
18
- // kind → 默认启动命令。新增 kind 在这里加一行即可(kind 是数据,不是命令树)。
18
+ // kind → 启动命令族。声明式数据小表,不是 adapter。新增 kind 加一行即可。
19
+ // - fresh:全新会话的启动命令
20
+ // - resume:续上一次会话的命令(restart 默认走这个;--no-continue 走 fresh)
21
+ // - resetKeys/resetWaitMs:发 exit 前先把 TUI 拉回干净空闲态(逐个键发送,每个键后等一小下)
22
+ // - exit:TUI 内的优雅退出命令(restart 发 reset 后再发它 + Enter)
23
+ // - downTimeout:发了 exit 后等进程退出的轮询超时(ms)
19
24
  const KIND_CMD = {
20
- cc: 'claude --dangerously-skip-permissions',
21
- codex: 'codex -m gpt-5.4',
22
- shell: 'bash',
25
+ cc: {
26
+ fresh: 'claude --dangerously-skip-permissions',
27
+ resume: 'claude --dangerously-skip-permissions --continue',
28
+ resetKeys: ['Escape'],
29
+ resetWaitMs: 1000,
30
+ exit: '/exit',
31
+ downTimeout: 120000, // cc 退出跑 Stop hook(auto-save / semantic_memory)要 ~90s
32
+ },
33
+ codex: {
34
+ fresh: 'codex -m gpt-5.4',
35
+ resume: 'codex resume --last',
36
+ resetKeys: ['Escape', 'Escape'],
37
+ resetWaitMs: 1000,
38
+ exit: '/exit',
39
+ downTimeout: 60000, // 实测 codex /exit ~25s(退出存 session),留余量
40
+ },
41
+ shell: {
42
+ fresh: 'bash',
43
+ // shell 无优雅 restart——restartTerm 对 shell 直接报错
44
+ },
23
45
  };
24
46
  const KIND_PREFIX = { cc: 'cc', codex: 'codex', shell: 'sh' };
25
47
 
@@ -33,7 +55,14 @@ function sleep(ms) {
33
55
 
34
56
  /**
35
57
  * 检测 session 里跑的是什么:'cc' | 'codex' | 'shell'。session 不存在返回 null。
36
- * 按 pane 进程及其子进程的 comm 判断。
58
+ *
59
+ * 从 pane_pid BFS 进程子树,遇到第一个 comm 含 claude/codex 的进程即返回——
60
+ * 「最浅命中」。npm 装的 codex 是 node 包装脚本(comm 看到的是 node/MainThread),
61
+ * 真 codex 是更深一层的 Rust 二进制(comm=codex),所以必须穿透子树。
62
+ *
63
+ * 为什么是「最浅命中」而非「收集全部」:cc 会话可能 spawn codex 子进程
64
+ * (比如 AI 用 codex skill)——那个 codex 在很深的层。最浅命中保证最外层的
65
+ * 那个有意义进程(panePid 处或附近的 claude)决定 kind,不被深层 codex 干扰。
37
66
  */
38
67
  function detectKind(session, socketPath) {
39
68
  const tmux = tmuxCmd(socketPath);
@@ -43,17 +72,35 @@ function detectKind(session, socketPath) {
43
72
  } catch {
44
73
  return null;
45
74
  }
46
- const comms = [];
47
- try {
48
- comms.push(execSync(`ps -o comm= -p ${panePid} 2>/dev/null`, EXEC_OPTS).trim());
49
- } catch {}
75
+ let table;
50
76
  try {
51
- const children = execSync(`ps -o comm= --ppid ${panePid} 2>/dev/null`, EXEC_OPTS).trim();
52
- if (children) comms.push(children);
53
- } catch {}
54
- const joined = comms.join(' ').toLowerCase();
55
- if (joined.includes('claude')) return 'cc';
56
- if (joined.includes('codex')) return 'codex';
77
+ table = execSync('ps -e -o pid=,ppid=,comm=', { ...EXEC_OPTS, maxBuffer: 4 * 1024 * 1024 });
78
+ } catch {
79
+ return 'shell';
80
+ }
81
+ const childrenOf = new Map();
82
+ const commOf = new Map();
83
+ for (const line of table.split('\n')) {
84
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
85
+ if (!m) continue;
86
+ const [, pid, ppid, comm] = m;
87
+ commOf.set(pid, comm);
88
+ if (!childrenOf.has(ppid)) childrenOf.set(ppid, []);
89
+ childrenOf.get(ppid).push(pid);
90
+ }
91
+ // BFS:最浅命中即返回
92
+ const queue = [String(panePid)];
93
+ const seen = new Set();
94
+ let guard = 0;
95
+ while (queue.length && guard++ < 5000) {
96
+ const pid = queue.shift();
97
+ if (seen.has(pid)) continue;
98
+ seen.add(pid);
99
+ const comm = (commOf.get(pid) || '').toLowerCase();
100
+ if (comm.includes('claude')) return 'cc';
101
+ if (comm.includes('codex')) return 'codex';
102
+ for (const c of childrenOf.get(pid) || []) queue.push(c);
103
+ }
57
104
  return 'shell';
58
105
  }
59
106
 
@@ -75,10 +122,9 @@ function listTerms(socketPath) {
75
122
  /**
76
123
  * 读 session 屏幕。默认 last N 行;full=true 读整屏 + scrollback 历史。
77
124
  *
78
- * 实现:一律 `capture-pane -p -S -` 抓全量,在 JS 里去掉尾部空行再切最后 N 行。
125
+ * 一律 `capture-pane -p -S -` 抓全量,在 JS 里去掉尾部空行再切最后 N 行。
79
126
  * 不用 shell `| tail`——capture-pane 会把光标下方的空 viewport 行也输出,
80
- * shell 的 tail 先抓到那些空行,内容稀疏的会话(shell / 刚起的 codex)就读不到东西。
81
- * capture-pane 受 tmux history-limit 限制(默认 2000 行),输出有界。
127
+ * shell 的 tail 先抓到空行,内容稀疏的会话就读不到东西。
82
128
  */
83
129
  function readTerm(session, { lines = 20, full = false, socketPath } = {}) {
84
130
  const tmux = tmuxCmd(socketPath);
@@ -106,7 +152,6 @@ function sendTerm(session, { text, noEnter = false, keys = [], socketPath } = {}
106
152
  }
107
153
  if (hasText) {
108
154
  execSync(`${tmux} send-keys -t "${session}" -l ${JSON.stringify(text)}`, EXEC_OPTS);
109
- // 自动 Enter:仅 text-only 且未抑制时。混发按键 = 手动模式,不惊喜回车。
110
155
  if (!noEnter && !hasKeys) {
111
156
  execSync(`${tmux} send-keys -t "${session}" Enter`, EXEC_OPTS);
112
157
  }
@@ -139,7 +184,7 @@ function startTerm({ kind, cmd, session, dir, socketPath } = {}) {
139
184
  const cwdArg = dir ? `-c "${dir}"` : '';
140
185
  execSync(`${tmux} new-session -d -s "${sessionName}" ${cwdArg}`.trim(), { ...EXEC_OPTS, timeout: 10000 });
141
186
  // kind=shell 且无 --cmd:new-session 本身就是 bash,不必再 send。
142
- const startCmd = cmd || KIND_CMD[kind];
187
+ const startCmd = cmd || KIND_CMD[kind].fresh;
143
188
  if (cmd || kind !== 'shell') {
144
189
  execSync(`${tmux} send-keys -t "${sessionName}" -l ${JSON.stringify(startCmd)}`, EXEC_OPTS);
145
190
  execSync(`${tmux} send-keys -t "${sessionName}" Enter`, EXEC_OPTS);
@@ -148,20 +193,52 @@ function startTerm({ kind, cmd, session, dir, socketPath } = {}) {
148
193
  }
149
194
 
150
195
  /**
151
- * restart 通用骨架:停 → 轮询确认停了 → 起 → 轮询确认起了 → 失败 C-c 重试一次。
152
- * 0.17.1 的「别在状态真变之前动作」教训对所有 kind 通用——差别只在「怎么停」。
196
+ * restart 通用骨架:停 → 轮询确认停了 → 起 → 轮询确认起了 → 5s 存活复检。
197
+ * 返回 { ok, warning }。
198
+ *
199
+ * 三个兜底(0.20.1 加):
200
+ * - poll-down 超时:强制 kill(C-c → 不行再 kill pane 子进程)+ warning,然后照常 relaunch
201
+ * - poll-up 后 ~5s 存活复检:化解「起来一瞬间被检测到、随即自更新退出」的假 success
202
+ * - poll-up 失败:C-c 清半行重试一次
153
203
  */
154
- async function restartSkeleton(session, socketPath, { targetKind, stopAction, downTimeout, startCmd }) {
204
+ async function restartSkeleton(
205
+ session,
206
+ socketPath,
207
+ { targetKind, resetAction = async () => {}, stopAction, downTimeout, startCmd }
208
+ ) {
155
209
  const tmux = tmuxCmd(socketPath);
210
+ let warning = null;
211
+
212
+ // 1. 先 reset TUI,再优雅退出
213
+ await resetAction();
156
214
  stopAction();
157
- // poll-down:轮询直到 kind 不再是 targetKind
215
+
216
+ // 2. poll-down:轮询直到 kind 不再是 targetKind;超时强制 kill 兜底
158
217
  const downDeadline = Date.now() + downTimeout;
159
218
  while (detectKind(session, socketPath) === targetKind) {
160
- if (Date.now() >= downDeadline) return false;
219
+ if (Date.now() >= downDeadline) {
220
+ warning = `${targetKind} 未在 ${Math.round(downTimeout / 1000)}s 内优雅退出,已强制终止;`
221
+ + (targetKind === 'codex' ? 'resume 的会话可能不完整' : '会话状态可能不完整');
222
+ try { execSync(`${tmux} send-keys -t "${session}" C-c`, EXEC_OPTS); } catch {}
223
+ await sleep(2000);
224
+ if (detectKind(session, socketPath) === targetKind) {
225
+ try {
226
+ const panePid = execSync(
227
+ `${tmux} display-message -t "${session}" -p '#{pane_pid}'`, EXEC_OPTS
228
+ ).trim();
229
+ execSync(`pkill -KILL -P ${panePid} 2>/dev/null || true`, EXEC_OPTS);
230
+ } catch {}
231
+ await sleep(2000);
232
+ }
233
+ break;
234
+ }
161
235
  await sleep(1000);
162
236
  }
163
- await sleep(500); // 等 shell prompt 落定
164
- // + poll-up(30s)
237
+
238
+ // 3. shell prompt 落定
239
+ await sleep(500);
240
+
241
+ // 4-5. 起 + poll-up(30s)+ 5s 存活复检
165
242
  const tryStart = async () => {
166
243
  try {
167
244
  execSync(`${tmux} send-keys -t "${session}" -l ${JSON.stringify(startCmd)}`, EXEC_OPTS);
@@ -174,21 +251,33 @@ async function restartSkeleton(session, socketPath, { targetKind, stopAction, do
174
251
  if (Date.now() >= upDeadline) return false;
175
252
  await sleep(1000);
176
253
  }
177
- return true;
254
+ // 存活复检:起来后等 5s 再确认还在(codex 启动可能撞自更新菜单、随即自退)
255
+ await sleep(5000);
256
+ return detectKind(session, socketPath) === targetKind;
178
257
  };
179
- if (await tryStart()) return true;
180
- // 没起来:C-c 清掉可能的半行,重试一次
258
+
259
+ if (await tryStart()) return { ok: true, warning, startCmd };
260
+
261
+ // 6. 没起来 / 起来又随即退:C-c 清半行后重试一次
181
262
  try { execSync(`${tmux} send-keys -t "${session}" C-c`, EXEC_OPTS); } catch {}
182
263
  await sleep(500);
183
- return tryStart();
264
+ if (await tryStart()) return { ok: true, warning, startCmd };
265
+
266
+ return {
267
+ ok: false,
268
+ startCmd,
269
+ warning: warning
270
+ || `${targetKind} 启动后未稳定存活(可能启动时撞自更新随即退出),请 seam term read 确认`,
271
+ };
184
272
  }
185
273
 
186
274
  /**
187
275
  * 重启 session 里跑的东西。只对 cc / codex 有意义——非 cc/codex(shell 或
188
276
  * 自定义命令)直接报错,不静默重启成 bash。
189
277
  *
190
- * cc:优雅 /exit(跑 Stop hook,120s 超时覆盖 auto-save/semantic_memory)。
191
- * codex:kill 进程(30s 短超时)。两者都轮询确认停了再起。
278
+ * cc 与 codex 都走对称的优雅路径(发 exit 命令 轮询退出 → 续命命令重起),
279
+ * 差别(退出命令 / 超时 / 续命命令)全在 KIND_CMD 表里。
280
+ * 返回 { ok, warning }。
192
281
  */
193
282
  async function restartTerm(session, { socketPath, continueSession = true } = {}) {
194
283
  const tmux = tmuxCmd(socketPath);
@@ -199,38 +288,29 @@ async function restartTerm(session, { socketPath, continueSession = true } = {})
199
288
  + 'restart 不知道该用什么命令重启它。要重起请用 `seam term start --kind ... --cmd "..."`。'
200
289
  );
201
290
  }
202
- if (kind === 'cc') {
203
- const startCmd = continueSession ? `${KIND_CMD.cc} --continue` : KIND_CMD.cc;
204
- return restartSkeleton(session, socketPath, {
205
- targetKind: 'cc',
206
- // cc 必须优雅退:发 /exit 跑 Stop hook,kill 会丢 AI 记忆
207
- stopAction: () => {
208
- execSync(`${tmux} send-keys -t "${session}" -l '/exit'`, EXEC_OPTS);
209
- execSync(`${tmux} send-keys -t "${session}" Enter`, EXEC_OPTS);
210
- },
211
- downTimeout: 120000,
212
- startCmd,
213
- });
214
- }
215
- // codex:kill pane 进程的子进程(codex),bash 留着,会话不死
291
+ const spec = KIND_CMD[kind];
292
+ const startCmd = continueSession ? spec.resume : spec.fresh;
216
293
  return restartSkeleton(session, socketPath, {
217
- targetKind: 'codex',
294
+ targetKind: kind,
295
+ resetAction: async () => {
296
+ if (Array.isArray(spec.resetKeys) && spec.resetKeys.length > 0) {
297
+ for (const key of spec.resetKeys) {
298
+ execSync(`${tmux} send-keys -t "${session}" ${JSON.stringify(key)}`, EXEC_OPTS);
299
+ if (spec.resetWaitMs > 0) await sleep(spec.resetWaitMs);
300
+ }
301
+ }
302
+ },
218
303
  stopAction: () => {
219
- try {
220
- const panePid = execSync(
221
- `${tmux} display-message -t "${session}" -p '#{pane_pid}'`, EXEC_OPTS
222
- ).trim();
223
- execSync(`pkill -TERM -P ${panePid} 2>/dev/null || true`, EXEC_OPTS);
224
- } catch {}
304
+ execSync(`${tmux} send-keys -t "${session}" -l ${JSON.stringify(spec.exit)}`, EXEC_OPTS);
305
+ execSync(`${tmux} send-keys -t "${session}" Enter`, EXEC_OPTS);
225
306
  },
226
- downTimeout: 30000,
227
- startCmd: KIND_CMD.codex,
307
+ downTimeout: spec.downTimeout,
308
+ startCmd,
228
309
  });
229
310
  }
230
311
 
231
312
  /**
232
- * 关掉整个终端(kill-session)。返回关之前检测到的 kind(供调用方判断是否
233
- * 连带杀了 guardian)。
313
+ * 关掉整个终端(kill-session)。返回关之前检测到的 kind
234
314
  */
235
315
  function stopTerm(session, { socketPath } = {}) {
236
316
  const tmux = tmuxCmd(socketPath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seamnet/client",
3
- "version": "0.20.0",
3
+ "version": "0.20.2",
4
4
  "description": "One command to join Seam — the network where people and AI stay in sync.",
5
5
  "bin": {
6
6
  "seam-client": "bin/cli.js",