lark-remote 0.5.6 → 0.5.7

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +30 -6
  2. package/README.en.md +2 -2
  3. package/README.md +2 -2
  4. package/dist/bridge/index.d.ts +48 -1
  5. package/dist/bridge/index.js +86 -14
  6. package/dist/card/card-budget.d.ts +37 -0
  7. package/dist/card/card-budget.js +128 -5
  8. package/dist/card/run-renderer.d.ts +24 -0
  9. package/dist/card/run-renderer.js +256 -60
  10. package/dist/card/run-state.d.ts +26 -0
  11. package/dist/card/run-state.js +45 -0
  12. package/dist/card/time.d.ts +14 -0
  13. package/dist/card/time.js +30 -0
  14. package/dist/card/tool-render.d.ts +15 -2
  15. package/dist/card/tool-render.js +40 -66
  16. package/dist/common/text-width.d.ts +24 -0
  17. package/dist/common/text-width.js +93 -0
  18. package/dist/common/tool-summary.d.ts +11 -0
  19. package/dist/common/tool-summary.js +153 -0
  20. package/dist/config/index.d.ts +1 -1
  21. package/dist/config/index.js +1 -1
  22. package/dist/connector/index.js +1 -1
  23. package/dist/index.js +61 -6
  24. package/dist/platform/command.js +1 -1
  25. package/dist/platform/shell.d.ts +2 -2
  26. package/dist/platform/spawn.d.ts +1 -1
  27. package/dist/platform/spawn.js +2 -2
  28. package/dist/platform/types.d.ts +1 -1
  29. package/dist/router/card-helpers.d.ts +18 -16
  30. package/dist/router/card-helpers.js +65 -4
  31. package/dist/router/index.d.ts +9 -0
  32. package/dist/router/index.js +57 -7
  33. package/dist/runner/claude/session.d.ts +1 -1
  34. package/dist/runner/claude/session.js +3 -3
  35. package/dist/runner/common/jsonrpc/transport.d.ts +1 -1
  36. package/dist/runner/common/jsonrpc/transport.js +3 -3
  37. package/dist/runner/common/spawning-runner.d.ts +1 -1
  38. package/dist/runner/common/spawning-runner.js +2 -2
  39. package/dist/runner/dsh/auth.js +2 -1
  40. package/dist/runner/dsh/client.d.ts +100 -3
  41. package/dist/runner/dsh/client.js +289 -4
  42. package/dist/runner/dsh/exit-cancel.d.ts +32 -0
  43. package/dist/runner/dsh/exit-cancel.js +72 -0
  44. package/dist/runner/dsh/inflight.d.ts +62 -0
  45. package/dist/runner/dsh/inflight.js +140 -0
  46. package/dist/runner/dsh/runner.d.ts +90 -4
  47. package/dist/runner/dsh/runner.js +436 -18
  48. package/dist/runner/dsh/translator.d.ts +1 -1
  49. package/dist/runner/dsh/translator.js +103 -1
  50. package/dist/runner/dsh/types.d.ts +60 -0
  51. package/dist/runner/types.d.ts +76 -2
  52. package/dist/session/claude/sessions.js +2 -2
  53. package/dist/session/dsh/sessions.js +100 -15
  54. package/dist/update/install.js +1 -1
  55. package/package.json +1 -1
@@ -10,7 +10,7 @@
10
10
  * 必须经它合并(先按不区分大小写删旧键再设新值);
11
11
  * - isWindowsCommandNotFoundLine:win32 经 cmd 垫片启动失败不是 spawn 的
12
12
  * error 事件 ENOENT,而是子进程往 stderr 打
13
- * "'xxx' is not recognized as an internal or external command"(§4.4)。
13
+ * "'xxx' is not recognized as an internal or external command"(见本文件 command-not-found 嗅探)。
14
14
  */
15
15
  import crossSpawn from 'cross-spawn';
16
16
  import { currentPlatform, isWin32 } from './select.js';
@@ -68,7 +68,7 @@ export function useDetachedProcessGroup(platform = currentPlatform) {
68
68
  return !isWin32(platform);
69
69
  }
70
70
  /**
71
- * win32 command-not-found 行嗅探(§4.4):命中即视为「命令缺失」失败而非
71
+ * win32 command-not-found 行嗅探:命中即视为「命令缺失」失败而非
72
72
  * 普通非零退出。platform 注入使其在任意宿主可测。
73
73
  */
74
74
  export function isWindowsCommandNotFoundLine(line, platform = currentPlatform) {
@@ -2,7 +2,7 @@
2
2
  * 平台 seam 纯类型。
3
3
  */
4
4
  /**
5
- * spawn 发现规格 —— resolveExecutable 的产出(v2 §4.3,仅探测/诊断用)。
5
+ * spawn 发现规格 —— resolveExecutable 的产出(仅探测/诊断用)。
6
6
  * v2 收窄:.cmd 垫片命中即报告垫片路径本身,不再解析内容定位入口;
7
7
  * 执行统一走 platform/spawn.ts 的 cross-spawn 包装。
8
8
  */
@@ -10,22 +10,6 @@ import { markdownDiv } from '../card/collapsible.js';
10
10
  import type { AgentSessionContentEvent } from '../runner/index.js';
11
11
  import { formatUsageStats } from './usage-format.js';
12
12
  type SessionUsageLike = Parameters<typeof formatUsageStats>[0];
13
- /**
14
- * Build a collapsible panel for a single session content event.
15
- *
16
- * Header carries a type emoji (👤 user / 🤖 assistant·text / 💭 thinking /
17
- * 🔧 tool_use / 🟢🔴 tool_result) with optional timestamp.
18
- * Body: the event's content (markdown).
19
- *
20
- * The last `tailExpandedCount` events are expanded by default so the user
21
- * sees the most recent context without clicking; older events are collapsed.
22
- *
23
- * @param ev - Session content event
24
- * @param index - Index in the events array
25
- * @param totalEvents - Total number of events
26
- * @param tailExpandedCount - How many events from the end to keep expanded (default 2)
27
- * @param agentKind - Agent type for display name (e.g. 'claude', 'pi'). Defaults to 'claude'.
28
- */
29
13
  export declare function sessionEventPanel(ev: AgentSessionContentEvent, index: number, totalEvents: number, tailExpandedCount?: number, agentKind?: string): object;
30
14
  export { markdownDiv };
31
15
  /** 页码输入非法时的统一提示文案(/ls /ws /resume /active /order 共用)。 */
@@ -115,6 +99,19 @@ export declare function searchBar(opts: {
115
99
  currentQuery?: string;
116
100
  extra?: Record<string, unknown>;
117
101
  }): object;
102
+ /**
103
+ * 选出 resume/历史卡该展示的事件。
104
+ *
105
+ * 旧口径是 `events.slice(-max)`:按**原始事件条数**截尾。工具往返(bash 调用 →
106
+ * job 登记 → 结果)一段就能把窗口占满,于是重返会话的用户真正需要的两条信息
107
+ * ——最后一句我说了什么、最后一句它答了什么——被挤出窗口。2026-10-19 实测:
108
+ * 自动恢复卡 5 个面板全是 bash 调用,一条用户消息、一条 assistant 正文都没有。
109
+ *
110
+ * 契约:先取最新 `max` 条,再把最后一条 `user` 与最后一条 `assistant`(正文)
111
+ * 不在窗口内时补进来——补位时淘汰最早的**非锚点**事件。输出保持时间顺序,
112
+ * 长度不超过 `max`。
113
+ */
114
+ export declare function pickResumeCardEvents(events: AgentSessionContentEvent[], max: number): AgentSessionContentEvent[];
118
115
  /**
119
116
  * Build a session-history resume card (shared by auto-restore, /resume <id>,
120
117
  * config-switch resume, and run-completion notification).
@@ -145,6 +142,11 @@ export declare function buildSessionHistoryCard(state: {
145
142
  emptyPlaceholder?: string;
146
143
  /** Hidden earlier-events count (auto-restore only). */
147
144
  hiddenCount?: number;
145
+ /**
146
+ * 该会话此刻仍有在途 turn(仅 DSH 的 `isSessionActive` 是服务端 running
147
+ * 事实)。为 true 时卡上显式提示"这是历史快照、实时输出不会落在这张卡上"。
148
+ */
149
+ stillRunning?: boolean;
148
150
  /** Action buttons to render (already built, protocol-specific). */
149
151
  actions?: object[];
150
152
  /** Optional card header template (e.g. 'green' for completion cards). */
@@ -8,7 +8,8 @@
8
8
  */
9
9
  import { agentDisplayName } from '../card/card-shared.js';
10
10
  import { collapsibleMarkdownPanel, markdownDiv } from '../card/collapsible.js';
11
- import { formatTimestamp } from '../card/time.js';
11
+ import { formatMonthDayClock } from '../card/time.js';
12
+ import { displayWidth, truncateMiddleToDisplayWidth } from '../common/text-width.js';
12
13
  import { formatUsageStats } from './usage-format.js';
13
14
  /**
14
15
  * Build a collapsible panel for a single session content event.
@@ -26,10 +27,21 @@ import { formatUsageStats } from './usage-format.js';
26
27
  * @param tailExpandedCount - How many events from the end to keep expanded (default 2)
27
28
  * @param agentKind - Agent type for display name (e.g. 'claude', 'pi'). Defaults to 'claude'.
28
29
  */
30
+ /**
31
+ * resume / 历史卡片的事件面板标题宽度上限(半角单位)。
32
+ *
33
+ * 与 run 卡的工具面板同口径:手机上一行约 42 个半角宽,标题超了会折行。
34
+ */
35
+ const SESSION_PANEL_TITLE_MAX = 42;
29
36
  export function sessionEventPanel(ev, index, totalEvents, tailExpandedCount = 2, agentKind = 'claude') {
30
- const label = eventLabel(ev, agentKind);
31
- const ts = formatTimestamp(ev.timestamp);
32
- const title = ts ? `${label} (${ts})` : label;
37
+ // reader 可以给事件一个"标题即摘要"的名字(工具调用:`🔧 bash — npm test`);
38
+ // 缺省用类型标签。标题连同时间戳一起收进一行显示宽度——手机上折叠面板只有
39
+ // 一行可用(2026-10-19 工具标题被长 URL 撑成两行那次)。
40
+ const label = ev.title ?? eventLabel(ev, agentKind);
41
+ const ts = formatMonthDayClock(ev.timestamp);
42
+ const suffix = ts ? ` (${ts})` : '';
43
+ const labelMax = Math.max(8, SESSION_PANEL_TITLE_MAX - displayWidth(suffix));
44
+ const title = `${truncateMiddleToDisplayWidth(label, labelMax)}${suffix}`;
33
45
  const expanded = index >= totalEvents - tailExpandedCount;
34
46
  return collapsibleMarkdownPanel({
35
47
  title,
@@ -269,6 +281,50 @@ export function searchBar(opts) {
269
281
  }
270
282
  return { tag: 'column_set', columns };
271
283
  }
284
+ /**
285
+ * 选出 resume/历史卡该展示的事件。
286
+ *
287
+ * 旧口径是 `events.slice(-max)`:按**原始事件条数**截尾。工具往返(bash 调用 →
288
+ * job 登记 → 结果)一段就能把窗口占满,于是重返会话的用户真正需要的两条信息
289
+ * ——最后一句我说了什么、最后一句它答了什么——被挤出窗口。2026-10-19 实测:
290
+ * 自动恢复卡 5 个面板全是 bash 调用,一条用户消息、一条 assistant 正文都没有。
291
+ *
292
+ * 契约:先取最新 `max` 条,再把最后一条 `user` 与最后一条 `assistant`(正文)
293
+ * 不在窗口内时补进来——补位时淘汰最早的**非锚点**事件。输出保持时间顺序,
294
+ * 长度不超过 `max`。
295
+ */
296
+ export function pickResumeCardEvents(events, max) {
297
+ if (max <= 0)
298
+ return [];
299
+ if (events.length <= max)
300
+ return events.slice();
301
+ const picked = new Set();
302
+ for (let i = events.length - 1; i >= 0 && picked.size < max; i -= 1)
303
+ picked.add(i);
304
+ const lastIndexOf = (predicate) => {
305
+ for (let i = events.length - 1; i >= 0; i -= 1) {
306
+ const ev = events[i];
307
+ if (ev && predicate(ev))
308
+ return i;
309
+ }
310
+ return -1;
311
+ };
312
+ const anchors = [
313
+ lastIndexOf((ev) => ev.type === 'user'),
314
+ lastIndexOf((ev) => ev.type === 'assistant'),
315
+ ].filter((i) => i >= 0);
316
+ for (const anchor of anchors) {
317
+ if (picked.has(anchor))
318
+ continue;
319
+ // 腾位置时只淘汰非锚点:两个锚点之间不互相挤掉。
320
+ const victim = [...picked].filter((i) => !anchors.includes(i)).sort((a, b) => a - b)[0];
321
+ if (victim === undefined)
322
+ break;
323
+ picked.delete(victim);
324
+ picked.add(anchor);
325
+ }
326
+ return [...picked].sort((a, b) => a - b).map((i) => events[i]);
327
+ }
272
328
  /**
273
329
  * Build a session-history resume card (shared by auto-restore, /resume <id>,
274
330
  * config-switch resume, and run-completion notification).
@@ -297,6 +353,11 @@ export function buildSessionHistoryCard(state, opts) {
297
353
  header += '\n\n' + sections.join('\n\n──\n\n');
298
354
  }
299
355
  const elements = [markdownDiv(header), { tag: 'hr' }];
356
+ // 恢复时该会话仍有一个 turn 在跑(典型来源:上一个桥接实例退出/崩溃后,
357
+ // turn 留在常驻 host 里继续执行)。卡片只是快照,别让用户以为这就是全部。
358
+ if (opts.stillRunning) {
359
+ elements.push(markdownDiv('⚠️ **该会话仍有一个 turn 在运行**(可能来自已退出的实例):以下内容是历史快照,实时输出不会出现在这张卡上。'));
360
+ }
300
361
  if (opts.hiddenCount && opts.hiddenCount > 0) {
301
362
  elements.push(markdownDiv(`📜 还有 ${opts.hiddenCount} 个更早的事件未显示`));
302
363
  }
@@ -33,6 +33,8 @@ export interface CardActionPayload {
33
33
  path?: string;
34
34
  name?: string;
35
35
  runId?: string;
36
+ /** 终态卡「停止」的目标后台任务 id(DSH job/list 的 jobId)。 */
37
+ jobId?: string;
36
38
  sessionId?: string;
37
39
  /** 目标工作目录(queue.* 卡片动作定位队列;stop 等卡片回传执行目录)。 */
38
40
  cwd?: string;
@@ -352,6 +354,13 @@ export declare class CommandRouter {
352
354
  * Handle stop card action: interrupt current run.
353
355
  */
354
356
  private handleCardStop;
357
+ /**
358
+ * Handle a terminal card's 「停止」 on one background job.
359
+ *
360
+ * 任务跨 run 生命周期,所以卡片按钮是唯一入口;失败必须给出可读原因
361
+ * (任务已自行结束、服务重启后快照被回收),不能点了没反应。
362
+ */
363
+ private handleJobKill;
355
364
  /**
356
365
  * Resolve an order's text at the enqueue boundary so order.exec can enter
357
366
  * the serial queue as an equivalent user message (Plan A) — the same path a
@@ -646,6 +646,9 @@ export class CommandRouter {
646
646
  case 'stop':
647
647
  await this.handleCardStop(value, ctx);
648
648
  return;
649
+ case 'job.kill':
650
+ await this.handleJobKill(value, ctx);
651
+ return;
649
652
  case 'queue.cancel':
650
653
  // 撤销:从队列中删除这个消息
651
654
  await this.handleQueueCancel(value, ctx);
@@ -832,12 +835,17 @@ export class CommandRouter {
832
835
  // 2. Stop current running process
833
836
  // (Note: queue executing count is reset inside Bridge.interruptCurrentRun
834
837
  // so all stop paths — /stop, /t, card stop, queue.immediate — are covered.)
835
- const stopped = await this.bridge.interruptCurrentRun({
838
+ const interrupt = await this.bridge.interruptCurrentRunDetailed({
836
839
  userId: ctx.userId,
837
840
  chatId: ctx.chatId,
838
841
  cwd,
839
842
  });
840
- getLogger().info(`[router] queue.immediate: stopped=${stopped}`);
843
+ const stopped = interrupt.stopped;
844
+ // A remote (DSH) stop is only a request; when it cannot be confirmed the
845
+ // target must not be promised "immediate" execution — its prompt would sit
846
+ // behind the still-running turn with no visible progress.
847
+ const stopUnconfirmed = interrupt.stop?.status === 'unconfirmed';
848
+ getLogger().info(`[router] queue.immediate: stopped=${stopped} unconfirmed=${stopUnconfirmed}`);
841
849
  // 3. Remove all tasks BEFORE this one (by position in the current queue).
842
850
  // The target may have begun while interruptCurrentRun was awaiting (the chain
843
851
  // advances concurrently): then it is already out of the snapshot and every
@@ -910,7 +918,14 @@ export class CommandRouter {
910
918
  return;
911
919
  }
912
920
  const workspaceBusy = this.bridge.isBusyFor(cwd);
913
- if (!workspaceBusy) {
921
+ if (stopUnconfirmed) {
922
+ const name = interrupt.agentKind ? agentDisplayName(interrupt.agentKind) : 'agent';
923
+ await this.bridge.sendResult({
924
+ text: `⚠️ 未能确认 ${name} 的 turn 已停止,它可能仍在后台运行。\n` +
925
+ `已清除 ${removedCount} 条排队消息;您的消息已提交,但可能要等该 turn 结束后才开始。`,
926
+ }, ctx);
927
+ }
928
+ else if (!workspaceBusy) {
914
929
  // Normal path: nothing new began during the stop, the target is next.
915
930
  // Mark its own card as executing now so buttons grey out immediately.
916
931
  // Done BEFORE any removal so getQueuedTask still returns the task with
@@ -1351,16 +1366,42 @@ export class CommandRouter {
1351
1366
  await this.bridge.sendResult({ text: '⚠️ 无效的停止请求,缺少必要信息' }, ctx);
1352
1367
  return;
1353
1368
  }
1354
- const stopped = await this.bridge.interruptCurrentRun({
1369
+ const interrupt = await this.bridge.interruptCurrentRunDetailed({
1355
1370
  userId: ctx.userId,
1356
1371
  chatId: ctx.chatId,
1357
1372
  runId: value.runId,
1358
1373
  });
1374
+ const stopped = interrupt.stopped;
1359
1375
  // Regression 2026-06-22: card stop button silently no-op'd when the
1360
1376
  // run had already exited. Give the user a visible result.
1361
1377
  if (!stopped) {
1362
1378
  await this.bridge.sendResult({ text: '该任务已结束,无需终止' }, ctx);
1379
+ return;
1363
1380
  }
1381
+ // DSH: `session/cancel` is only a request. If the host still reports the
1382
+ // turn open, say so instead of letting the card imply a clean stop.
1383
+ if (interrupt.stop?.status === 'unconfirmed') {
1384
+ const name = interrupt.agentKind ? agentDisplayName(interrupt.agentKind) : 'agent';
1385
+ await this.bridge.sendResult({
1386
+ text: `⚠️ 未能确认 ${name} 的 turn 已停止,它可能仍在后台运行。\n` +
1387
+ '请在 DSH Web UI 检查;需要终止时再点一次停止。',
1388
+ }, ctx);
1389
+ }
1390
+ }
1391
+ /**
1392
+ * Handle a terminal card's 「停止」 on one background job.
1393
+ *
1394
+ * 任务跨 run 生命周期,所以卡片按钮是唯一入口;失败必须给出可读原因
1395
+ * (任务已自行结束、服务重启后快照被回收),不能点了没反应。
1396
+ */
1397
+ async handleJobKill(value, ctx) {
1398
+ const runId = typeof value.runId === 'string' ? value.runId : '';
1399
+ const jobId = typeof value.jobId === 'string' ? value.jobId : '';
1400
+ if (!runId || !jobId)
1401
+ return;
1402
+ if (await this.bridge.killBackgroundJob(runId, jobId, ctx))
1403
+ return;
1404
+ await this.bridge.sendResult({ text: '停止失败:任务可能已自行结束,或记录已回收' }, ctx);
1364
1405
  }
1365
1406
  /**
1366
1407
  * Resolve an order's text at the enqueue boundary so order.exec can enter
@@ -2086,7 +2127,7 @@ export class CommandRouter {
2086
2127
  switchSessionId = '';
2087
2128
  }
2088
2129
  }
2089
- // DSH preset 变更 = 下次 run 新建 session(§4.3):
2130
+ // DSH preset 变更 = 下次 run 新建 session:
2090
2131
  // preset 在 session 创建时固定,中途切换会被服务端拒绝(agent-preset-conflict)。
2091
2132
  // 旧 sessionId 存入 previousSessions 停车位(可手动 /resume,但 /resume 会做
2092
2133
  // preset 一致性校验),当前 sessionId 清空——下次 run 走 session.create 新建。
@@ -2431,11 +2472,20 @@ ${sessionCwdLine}${agentLines.map((l) => `- ${l}`).join('\n')}
2431
2472
  };
2432
2473
  }
2433
2474
  async cmdStop(ctx) {
2434
- const stopped = await this.bridge.interruptCurrentRun({
2475
+ const interrupt = await this.bridge.interruptCurrentRunDetailed({
2435
2476
  userId: ctx.userId,
2436
2477
  chatId: ctx.chatId,
2437
2478
  });
2438
- return stopped ? null : { text: '当前没有运行中的进程' };
2479
+ if (!interrupt.stopped)
2480
+ return { text: '当前没有运行中的进程' };
2481
+ if (interrupt.stop?.status === 'unconfirmed') {
2482
+ const name = interrupt.agentKind ? agentDisplayName(interrupt.agentKind) : 'agent';
2483
+ return {
2484
+ text: `⚠️ 未能确认 ${name} 的 turn 已停止,它可能仍在后台运行。\n` +
2485
+ '请在 DSH Web UI 检查;需要终止时再发一次 /stop。',
2486
+ };
2487
+ }
2488
+ return null;
2439
2489
  }
2440
2490
  async cmdExit() {
2441
2491
  // Signal handle() to invoke exitHandler after the reply is sent.
@@ -147,7 +147,7 @@ export declare class ClaudeSession extends SpawningRunner {
147
147
  private consumeTurn;
148
148
  /**
149
149
  * 构造进程退出且无终态 result 时的统一错误结果(对齐原 SpawningRunner
150
- * buildResultEvent 语义,含 §4.4 win32 command-not-found 双条件定性)。
150
+ * buildResultEvent 语义,含 win32 command-not-found 的双条件定性)。
151
151
  */
152
152
  private buildStreamEndedError;
153
153
  private wakeWaiters;
@@ -306,7 +306,7 @@ export class ClaudeSession extends SpawningRunner {
306
306
  this.cwd = opts.cwd;
307
307
  this.autoApprove = false;
308
308
  this.pendingToolInputs.clear();
309
- // §4.4 win32 嗅探嫌疑标记每次 spawn 重置(spawnChild 置位,收尾双条件消费)。
309
+ // win32 的 command-not-found 嫌疑标记每次 spawn 重置(spawnChild 置位,收尾双条件消费)。
310
310
  this.commandNotFoundSeen = false;
311
311
  // 每次 run 独立:上次 run 会话内跟踪到的计划文件不得泄漏到本次
312
312
  // (否则本次 ExitPlanMode 无 plan/planFilePath 时 resolvePlanContent
@@ -422,7 +422,7 @@ export class ClaudeSession extends SpawningRunner {
422
422
  }
423
423
  /**
424
424
  * 构造进程退出且无终态 result 时的统一错误结果(对齐原 SpawningRunner
425
- * buildResultEvent 语义,含 §4.4 win32 command-not-found 双条件定性)。
425
+ * buildResultEvent 语义,含 win32 command-not-found 的双条件定性)。
426
426
  */
427
427
  async buildStreamEndedError() {
428
428
  // 进程已死但 proc 'close' 事件可能略晚于 stdout 关闭:等退出登记拿可靠
@@ -438,7 +438,7 @@ export class ClaudeSession extends SpawningRunner {
438
438
  errorMessage = `${this.binary} killed by signal ${exited.signal}${stderrTail ? `: ${stderrTail}` : ''}`;
439
439
  }
440
440
  else if (exited.code !== null && exited.code !== 0) {
441
- // §4.4 双条件定性:本分支已保证「用户未停 + signal 为 null + 非零退出」,
441
+ // 双条件定性:本分支已保证「用户未停 + signal 为 null + 非零退出」,
442
442
  // 这里只补嗅探嫌疑标记这第二个条件。
443
443
  const commandNotFound = this.commandNotFoundSeen;
444
444
  if (commandNotFound) {
@@ -30,7 +30,7 @@ export declare class JsonlRpcTransport {
30
30
  /** JSON lines buffered while stdin is under backpressure (bounded by callers). */
31
31
  private writeQueue;
32
32
  private flushing;
33
- /** §4.4 win32 嗅探嫌疑标记(双条件定性见下方 onExit)。 */
33
+ /** win32 嗅探嫌疑标记(双条件定性见下方 onExit)。 */
34
34
  private commandNotFoundSeen;
35
35
  constructor(opts: {
36
36
  binary: string;
@@ -34,7 +34,7 @@ export class JsonlRpcTransport {
34
34
  /** JSON lines buffered while stdin is under backpressure (bounded by callers). */
35
35
  writeQueue = [];
36
36
  flushing = false;
37
- /** §4.4 win32 嗅探嫌疑标记(双条件定性见下方 onExit)。 */
37
+ /** win32 嗅探嫌疑标记(双条件定性见下方 onExit)。 */
38
38
  commandNotFoundSeen = false;
39
39
  constructor(opts) {
40
40
  this.binary = opts.binary;
@@ -106,7 +106,7 @@ export class JsonlRpcTransport {
106
106
  const text = chunk.toString('utf-8');
107
107
  stderrBuf = (stderrBuf + text).slice(-MAX_STDERR_BYTES);
108
108
  getLogger().debug(`[jsonrpc-transport] stderr: ${text.trimEnd()}`);
109
- // §4.4 win32 command-not-found 嗅探:命中只记嫌疑标记,不立即杀——
109
+ // win32 command-not-found 嗅探:命中只记嫌疑标记,不立即杀——
110
110
  // agent 正常输出可能引用该错误文本(调试 Windows 报错场景),见行即杀
111
111
  // 会误杀 run;定性由 onExit 的「标记 + 非零退出」双条件完成,真挂起由
112
112
  // 上层超时兜底
@@ -169,7 +169,7 @@ export class JsonlRpcTransport {
169
169
  // ignore trailing incomplete line
170
170
  }
171
171
  }
172
- // §4.4 双条件定性:嫌疑标记 + 非零正常退出 → command-not-found。
172
+ // 双条件定性:嫌疑标记 + 非零正常退出 → command-not-found。
173
173
  // reason 仅供日志/诊断,消费方不解析该字符串(baseOnClose 无参)。
174
174
  let reason = signal ? `signal:${signal}` : `exit:${code}`;
175
175
  if (this.commandNotFoundSeen && signal === null && code !== null && code !== 0) {
@@ -84,7 +84,7 @@ export declare abstract class SpawningRunner {
84
84
  */
85
85
  protected stoppedByUser: boolean;
86
86
  /**
87
- * §4.4 win32 command-not-found 嗅探嫌疑标记:stderr 命中特征行时置位,
87
+ * win32 command-not-found 嗅探嫌疑标记:stderr 命中特征行时置位,
88
88
  * 但**不**立即杀进程——agent 正常输出可能引用该错误文本(调试 Windows
89
89
  * 报错场景),见行即杀会误杀 run。定性走双条件:子类收尾时「标记在 +
90
90
  * 非零退出」才判 command-not-found;真挂起由既有 grace/超时兜底。
@@ -127,7 +127,7 @@ export class SpawningRunner {
127
127
  */
128
128
  stoppedByUser = false;
129
129
  /**
130
- * §4.4 win32 command-not-found 嗅探嫌疑标记:stderr 命中特征行时置位,
130
+ * win32 command-not-found 嗅探嫌疑标记:stderr 命中特征行时置位,
131
131
  * 但**不**立即杀进程——agent 正常输出可能引用该错误文本(调试 Windows
132
132
  * 报错场景),见行即杀会误杀 run。定性走双条件:子类收尾时「标记在 +
133
133
  * 非零退出」才判 command-not-found;真挂起由既有 grace/超时兜底。
@@ -253,7 +253,7 @@ export class SpawningRunner {
253
253
  const text = chunk.toString('utf-8').trim();
254
254
  if (text) {
255
255
  this.spawnStderr = (this.spawnStderr + '\n' + text).trim().slice(-STDERR_TAIL_BYTES);
256
- // §4.4 win32 command-not-found 嗅探:经 cmd 垫片启动失败不是 spawn 的
256
+ // win32 command-not-found 嗅探:经 cmd 垫片启动失败不是 spawn 的
257
257
  // ENOENT,而是 stderr 的 "is not recognized..." 行。命中只记嫌疑标记
258
258
  // (双条件之一),不立即杀——定性由子类收尾的「标记 + 非零退出」
259
259
  // 双条件完成;子进程真挂起由既有 grace/超时看门狗兜底。
@@ -13,6 +13,7 @@ import fs from 'node:fs';
13
13
  import os from 'node:os';
14
14
  import path from 'node:path';
15
15
  import YAML from 'yaml';
16
+ import { isWin32 } from '../../platform/select.js';
16
17
  /** Credential record that owns the browser-cookie signing secret. */
17
18
  export const DSH_BROWSER_CREDENTIAL_KEY = 'client-connection/browser-session';
18
19
  /** Short lifetime keeps every request safely inside DSH's configurable max age. */
@@ -40,7 +41,7 @@ function assertOwnerOnly(file, stats) {
40
41
  throw new Error(`DSH credentials file ${file} is not a regular file`);
41
42
  }
42
43
  // Windows has no POSIX mode bits; DSH itself skips the same check there.
43
- if (process.platform === 'win32')
44
+ if (isWin32())
44
45
  return;
45
46
  if ((stats.mode & 0o077) !== 0) {
46
47
  throw new Error(`DSH credentials file ${file} is readable beyond its owner ` +
@@ -19,7 +19,7 @@
19
19
  * `sessionEvents()` adds per-session filtering, reconnect + follow-snapshot
20
20
  * replay, and seq-based dedup.
21
21
  */
22
- import type { DshApprovalStreamItem, DshCommandResult, DshModelCatalogValue, DshModelSelection, DshPermissionCatalogValue, DshPresetListValue, DshQuestion, DshRemoteEventOutcome, DshSessionPageValue, DshStreamItem, DshTokenUsage } from './types.js';
22
+ import type { DshApprovalStreamItem, DshCommandResult, DshModelCatalogValue, DshModelSelection, DshOpenTurnState, DshPermissionCatalogValue, DshJobView, DshPresetListValue, DshProjectionItem, DshProjectionSnapshot, DshQuestion, DshRemoteEventOutcome, DshSessionPageValue, DshStreamItem, DshTokenUsage } from './types.js';
23
23
  interface WebSocketMessageEvent {
24
24
  data: unknown;
25
25
  }
@@ -182,6 +182,68 @@ export declare class DshClient {
182
182
  signal?: AbortSignal;
183
183
  timeoutMs?: number;
184
184
  }): Promise<DshSessionPageValue>;
185
+ /**
186
+ * Read the session's exact projection values.
187
+ *
188
+ * Returns `null` when the host has no projections for the session (e.g. it was
189
+ * deleted). A failed unary still throws — callers that only need a
190
+ * best-effort probe catch it themselves.
191
+ */
192
+ projectionSnapshot(sessionId: string, opts?: {
193
+ signal?: AbortSignal;
194
+ timeoutMs?: number;
195
+ }): Promise<DshProjectionSnapshot | null>;
196
+ /**
197
+ * Find this run's prompt if it is still sitting in the host's inbox.
198
+ *
199
+ * DSH 的 prompt 受理后先进入 inbox,被 turn 取走(claim)就不再出现;停止
200
+ * 时用它区分“还没开始 → 可以从队列里撤掉”和“已经在跑 → 只能 cancel”。
201
+ * `source.rpcId` 是 `session/prompt` 的 requestId,归属不会认错。
202
+ */
203
+ findPendingPrompt(sessionId: string, requestId: string, opts?: {
204
+ signal?: AbortSignal;
205
+ timeoutMs?: number;
206
+ }): Promise<string | undefined>;
207
+ /**
208
+ * Remove one not-yet-claimed inbox occurrence (`session/updateQueue`).
209
+ *
210
+ * @returns true when the host removed it; false when it was claimed between
211
+ * the projection read and this call (`session/queue-item-not-found`).
212
+ */
213
+ removeQueuedPrompt(sessionId: string, itemId: string, opts?: {
214
+ signal?: AbortSignal;
215
+ timeoutMs?: number;
216
+ }): Promise<boolean>;
217
+ /**
218
+ * Whether the session still has a running turn.
219
+ *
220
+ * 主信号是 `session/list` 的 `running` 字段:服务端权威(会话列表页"运行中"
221
+ * 用的就是它),一次 unary,投票不受桥接进程内存影响。名单里没有该会话或
222
+ * 服务端不返回 `running` 时,回退到事件探测({@link probeOpenTurnByEvents}),
223
+ * 两者都判不出来就返回 false(fail open,仍由 DSH 自己拒绝)。
224
+ */
225
+ hasOpenTurn(sessionId: string, opts?: {
226
+ signal?: AbortSignal;
227
+ timeoutMs?: number;
228
+ }): Promise<boolean>;
229
+ /**
230
+ * Tri-state version of {@link hasOpenTurn}.
231
+ *
232
+ * Stop verification must distinguish "the host says idle" from "the probe
233
+ * could not tell" — reporting `closed` on a failed probe would let a still
234
+ * running turn be reported as stopped. `unknown` is the honest answer there.
235
+ */
236
+ openTurnState(sessionId: string, opts?: {
237
+ signal?: AbortSignal;
238
+ timeoutMs?: number;
239
+ }): Promise<DshOpenTurnState>;
240
+ /**
241
+ * Fallback probe: the newest durable event's type tells whether a turn is open.
242
+ *
243
+ * 只在拿不到 `running` 时用。名单刻意保守——`job/*`(后台任务可在 turn 外
244
+ * 结算)、`user/message`、`turn/end` 都不算,判不出来就报告 `unknown`。
245
+ */
246
+ private probeOpenTurnByEvents;
185
247
  /**
186
248
  * One logical stream over `/api/remote.mux`. The WebSocket must carry the
187
249
  * same auth cookie as unary calls. Ends on the server's `end` frame, socket
@@ -203,9 +265,44 @@ export declare class DshClient {
203
265
  * Per-session subscription: yields session events, assistant stream chunks
204
266
  * and approval notices for `sessionId`, auto-reconnecting on stream
205
267
  * drop/error and replaying the follow snapshot (dedup by seq). Terminates on
206
- * turn/end or `signal` abort.
268
+ * the run's own turn/end or `signal` abort.
269
+ *
270
+ * `promptRequestId` binds the stream to this run's prompt. `mode:'queue'`
271
+ * prompts are accepted while the agent is mid-turn and start a turn only
272
+ * later, so the first `turn/end` after `initialSeq` can belong to that OTHER
273
+ * turn. Everything recorded before the prompt's own durable `user/message`
274
+ * (whose source echoes the request id as `rpcId`) is foreign: dropping it
275
+ * keeps the card "running" until this run's turn actually finishes.
276
+ */
277
+ sessionEvents(sessionId: string, signal: AbortSignal, initialSeq?: number, promptRequestId?: string): AsyncGenerator<DshStreamItem>;
278
+ /**
279
+ * Host-wide live projection stream (`session/control`).
280
+ *
281
+ * 一份 baseline(当前所有活跃 session 的完整投影值)+ 之后每个投影的变化帧。
282
+ * 调用方按 sessionId 过滤:这是 DSH 上唯一"服务端变一次推一次"的通道,
283
+ * 不需要轮询 `session/projections`。
284
+ *
285
+ * 失败必须降级为"没有状态条",不能影响 run:控制流是增强通道,断了运行
286
+ * 照常(异常在此吞掉并记日志,不向 merge 抛)。
287
+ */
288
+ controlFrames(signal: AbortSignal): AsyncGenerator<DshProjectionItem>;
289
+ /**
290
+ * One session's current background-job roster.
291
+ *
292
+ * `job/list` 是流(生命周期变化时推整份名单),但"此刻有哪些任务在跑"只需
293
+ * 要第一帧:文档明确首帧就是当前真相(whole-set replacement)。取到即断开,
294
+ * 不长期持有连接——任务列表只用于收尾时的一句话与停止按钮。
295
+ *
296
+ * 失败返回 undefined(与"没有任务"区分):拿不到就别在卡片上写"0 个后台任务"。
207
297
  */
208
- sessionEvents(sessionId: string, signal: AbortSignal, initialSeq?: number): AsyncGenerator<DshStreamItem>;
298
+ jobRows(sessionId: string, opts?: {
299
+ signal?: AbortSignal;
300
+ timeoutMs?: number;
301
+ }): Promise<DshJobView[] | undefined>;
302
+ /** Kill one background job on the user's behalf (`job/kill`). */
303
+ jobKill(sessionId: string, jobId: string, opts?: {
304
+ signal?: AbortSignal;
305
+ }): Promise<boolean>;
209
306
  /** Extract TokenUsage from an assistant/message data payload (absent → undefined). */
210
307
  static usageOf(data: Record<string, unknown>): DshTokenUsage | undefined;
211
308
  }