@xiangyixie/dsh-superagent 0.14.7 → 0.14.8

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/CHANGELOG.md CHANGED
@@ -8,6 +8,22 @@ along with the next code release. A doc-only version leaves `lib/` and `bin/`
8
8
  byte-identical to the version before it, and the pinned install line in the
9
9
  README is updated to the version being released.
10
10
 
11
+ ## 0.14.8 — 2026-11-16
12
+
13
+ ### 变化
14
+
15
+ - **停止是真的停止。** 以前点「停止」只是请求,卡片转圈到宿主自己结束;现在会向宿主
16
+ 发起取消,并显示「停止中」,等宿主确认后才变成「已停止」。
17
+ - **历史改读宿主的会话列表。** 能看到宿主上实际有哪些对话(消息条数、产物数、最后
18
+ 更新时间),并且可以切回之前的对话继续。
19
+ - **任务线卡显示耗时和当前工具。** 每一段跑着的步骤都有实时计时,并显示它此刻在用
20
+ 哪个工具,不用等结束才知道卡在哪。
21
+ - **产物就地预览。** 点开产物直接在页面里看,不再跳新标签页;网页类产物也在框内打开。
22
+ - **审批卡说清要写什么、什么时候过期。** 卡片显示即将写入的内容和路径、剩余时间倒计时,
23
+ 并多一个「本会话内允许」:同一个工具在这个对话里不再逐次打扰,换对话后恢复询问。
24
+ - **消息可以复制、编辑后重发。** 复制按钮一键拿走原文;编辑会把原话放回输入框,改完
25
+ 重新发送,不用手打一遍。
26
+
11
27
  ## 0.14.7 — 2026-11-16
12
28
 
13
29
  ### 变化
package/README.en.md CHANGED
@@ -1,4 +1,4 @@
1
- [中文](README.md) | English
1
+ [中文](README.md) | English
2
2
 
3
3
  # dsh-superagent
4
4
 
@@ -36,12 +36,12 @@ Three steps. The desktop app and the CLI install the same plugin; each step says
36
36
 
37
37
  ### 1. Install
38
38
 
39
- Desktop: **Plugins** → **Add plugin** → enter `@xiangyixie/dsh-superagent@0.14.7` → install.
39
+ Desktop: **Plugins** → **Add plugin** → enter `@xiangyixie/dsh-superagent@0.14.8` → install.
40
40
 
41
41
  CLI:
42
42
 
43
43
  ```bash
44
- dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.7
44
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.8
45
45
  ```
46
46
 
47
47
  **Restart DSH** afterwards — plugins are loaded once at host startup. You can also add the [plugin index](https://raw.githubusercontent.com/LittleChenLiya/dsh-superagent/main/plugin-index.json) on the **Discover** page for one-click installs; upgrades are always remove-then-add.
@@ -1666,7 +1666,7 @@ appears to "hang" until the ignored-abort child returns.
1666
1666
 
1667
1667
  | What you see | What it means | What to do |
1668
1668
  | --- | --- | --- |
1669
- | `superagent_*` tools do not exist | The bundle row is not mounted, or the host refused to load the plugin. | Run `--dump-config` and check for the `@xiangyixie/dsh-superagent` block; reinstall with `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.7` and read the host log for `[dsh-superagent]` lines. |
1669
+ | `superagent_*` tools do not exist | The bundle row is not mounted, or the host refused to load the plugin. | Run `--dump-config` and check for the `@xiangyixie/dsh-superagent` block; reinstall with `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.8` and read the host log for `[dsh-superagent]` lines. |
1670
1670
  | `Cannot find module .../lib/control.js` (or `watch.js` / `report.js` / `wizard.js`), or `[dsh-superagent] dsh-superagent failed to load because a file it imports is missing: ...` in the host log | The copy in that profile is incomplete — an `add` that was interrupted leaves a partial extraction. From 0.14.3 the entry point names the missing file itself. The published package is not the cause: every version ships all thirty-four `lib/` files. | Delete the plugin's directory under the profile's `node_modules` (scoped `@xiangyixie/dsh-superagent`, or unscoped `dsh-superagent` from an older tarball install) and run the same `add` command again, with the version number. Do not copy files in by hand. |
1671
1671
  | `[error] the model provider rejected the API key` | The key env var is missing in the process that started the host. | Export `DEEPSEEK_API_KEY` (the default route) or the variable your route names, then restart `dsh`. |
1672
1672
  | `MISSING_CREDENTIAL ... no API key for provider route "..."` | The profile's route has no credential in the environment. | Set the env var named for that route and restart. The error line names the route, so use that, not this page. |
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- 中文 | [English](README.en.md)
1
+ 中文 | [English](README.en.md)
2
2
 
3
3
  # dsh-superagent
4
4
 
@@ -36,12 +36,12 @@ dsh-superagent 把这件事接过去:你说一句目标,它负责拆、负
36
36
 
37
37
  ### 1. 装
38
38
 
39
- 桌面端:侧边栏 **插件** → **Add plugin** → 输入 `@xiangyixie/dsh-superagent@0.14.7` → 安装。
39
+ 桌面端:侧边栏 **插件** → **Add plugin** → 输入 `@xiangyixie/dsh-superagent@0.14.8` → 安装。
40
40
 
41
41
  命令行:
42
42
 
43
43
  ```bash
44
- dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.7
44
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.8
45
45
  ```
46
46
 
47
47
  装完**重启 DSH**(插件只在宿主启动时加载一次)。也可以从「发现」页添加[插件索引](https://raw.githubusercontent.com/LittleChenLiya/dsh-superagent/main/plugin-index.json)一键安装;升级一律先 `remove` 再 `add`。
@@ -1090,7 +1090,7 @@ SHA-256)。`--format html` 把同样的内容写成一个自包含
1090
1090
 
1091
1091
  | 你看到的 | 含义 | 怎么办 |
1092
1092
  | --- | --- | --- |
1093
- | `superagent_*` 工具不存在 | bundle 行没挂上,或者宿主拒绝加载插件。 | 跑 `--dump-config` 查 `@xiangyixie/dsh-superagent` 块;用 `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.7` 重装,并在宿主日志里找 `[dsh-superagent]` 行。 |
1093
+ | `superagent_*` 工具不存在 | bundle 行没挂上,或者宿主拒绝加载插件。 | 跑 `--dump-config` 查 `@xiangyixie/dsh-superagent` 块;用 `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.8` 重装,并在宿主日志里找 `[dsh-superagent]` 行。 |
1094
1094
  | `Cannot find module .../lib/control.js`(或 `watch.js` / `report.js` / `wizard.js`),或宿主日志里的 `[dsh-superagent] dsh-superagent failed to load because a file it imports is missing: ...` | 那个 profile 里的副本不完整——被中断的 `add` 会留下残缺的解包结果。0.14.3 起的入口会直接点名缺哪个文件。已发布的包不是原因:每个版本都带全部三十四个 `lib/` 文件。 | 删掉 profile 的 `node_modules` 下该插件的目录(带 scope 的 `@xiangyixie/dsh-superagent`,或旧 tarball 安装留下的无 scope 的 `dsh-superagent`),再用同一条 `add` 命令重装,并带上版本号。不要手工拷贝文件进去。 |
1095
1095
  | `[error] the model provider rejected the API key` | 启动宿主的那个进程里缺 key 环境变量。 | 导出 `DEEPSEEK_API_KEY`(默认路由)或你那条路由声明的变量,然后重启 `dsh`。 |
1096
1096
  | `MISSING_CREDENTIAL ... no API key for provider route "..."` | profile 的路由在环境里没有凭据。 | 设置该路由对应的环境变量并重启。错误行里写了路由名,以它为准,不要照本文。 |
package/README.zh.md CHANGED
@@ -1,4 +1,4 @@
1
- 中文 | [English](README.en.md)
1
+ 中文 | [English](README.en.md)
2
2
 
3
3
  # dsh-superagent
4
4
 
@@ -36,12 +36,12 @@ dsh-superagent 把这件事接过去:你说一句目标,它负责拆、负
36
36
 
37
37
  ### 1. 装
38
38
 
39
- 桌面端:侧边栏 **插件** → **Add plugin** → 输入 `@xiangyixie/dsh-superagent@0.14.7` → 安装。
39
+ 桌面端:侧边栏 **插件** → **Add plugin** → 输入 `@xiangyixie/dsh-superagent@0.14.8` → 安装。
40
40
 
41
41
  命令行:
42
42
 
43
43
  ```bash
44
- dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.7
44
+ dsh plugin --profile web add @xiangyixie/dsh-superagent@0.14.8
45
45
  ```
46
46
 
47
47
  装完**重启 DSH**(插件只在宿主启动时加载一次)。也可以从「发现」页添加[插件索引](https://raw.githubusercontent.com/LittleChenLiya/dsh-superagent/main/plugin-index.json)一键安装;升级一律先 `remove` 再 `add`。
@@ -1090,7 +1090,7 @@ SHA-256)。`--format html` 把同样的内容写成一个自包含
1090
1090
 
1091
1091
  | 你看到的 | 含义 | 怎么办 |
1092
1092
  | --- | --- | --- |
1093
- | `superagent_*` 工具不存在 | bundle 行没挂上,或者宿主拒绝加载插件。 | 跑 `--dump-config` 查 `@xiangyixie/dsh-superagent` 块;用 `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.7` 重装,并在宿主日志里找 `[dsh-superagent]` 行。 |
1093
+ | `superagent_*` 工具不存在 | bundle 行没挂上,或者宿主拒绝加载插件。 | 跑 `--dump-config` 查 `@xiangyixie/dsh-superagent` 块;用 `dsh plugin --profile <p> add @xiangyixie/dsh-superagent@0.14.8` 重装,并在宿主日志里找 `[dsh-superagent]` 行。 |
1094
1094
  | `Cannot find module .../lib/control.js`(或 `watch.js` / `report.js` / `wizard.js`),或宿主日志里的 `[dsh-superagent] dsh-superagent failed to load because a file it imports is missing: ...` | 那个 profile 里的副本不完整——被中断的 `add` 会留下残缺的解包结果。0.14.3 起的入口会直接点名缺哪个文件。已发布的包不是原因:每个版本都带全部三十四个 `lib/` 文件。 | 删掉 profile 的 `node_modules` 下该插件的目录(带 scope 的 `@xiangyixie/dsh-superagent`,或旧 tarball 安装留下的无 scope 的 `dsh-superagent`),再用同一条 `add` 命令重装,并带上版本号。不要手工拷贝文件进去。 |
1095
1095
  | `[error] the model provider rejected the API key` | 启动宿主的那个进程里缺 key 环境变量。 | 导出 `DEEPSEEK_API_KEY`(默认路由)或你那条路由声明的变量,然后重启 `dsh`。 |
1096
1096
  | `MISSING_CREDENTIAL ... no API key for provider route "..."` | profile 的路由在环境里没有凭据。 | 设置该路由对应的环境变量并重启。错误行里写了路由名,以它为准,不要照本文。 |
package/lib/console.js CHANGED
@@ -160,6 +160,10 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
160
160
  // page answers them. Nothing resolves on its own: a page that never answers
161
161
  // fails closed to `cancelled`, and no path grants a call without a decision.
162
162
  const approvals = new Map()
163
+ // Tools the person chose to let through for the rest of this conversation.
164
+ // The host only grants one call at a time, so this list is the console's own
165
+ // scope, cleared whenever the conversation changes.
166
+ const sessionAllowedTools = new Set()
163
167
  let boundPort = null
164
168
  let server = null
165
169
  let page = null
@@ -394,10 +398,16 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
394
398
  */
395
399
  function askApproval(request = {}) {
396
400
  if (clients.size === 0) return Promise.resolve('cancelled')
401
+ const toolName = typeof request.toolName === 'string' && request.toolName ? request.toolName : 'tool'
402
+ if (sessionAllowedTools.has(toolName)) {
403
+ broadcast({ type: 'approval', action: 'auto', toolName })
404
+ return Promise.resolve('allowed-once')
405
+ }
397
406
  const id = `ap_${randomBytes(6).toString('hex')}`
407
+ const askedAt = Date.now()
398
408
  const payload = {
399
409
  id,
400
- toolName: typeof request.toolName === 'string' && request.toolName ? request.toolName : 'tool',
410
+ toolName,
401
411
  callId: request.callId ?? null,
402
412
  callArguments: typeof request.callArguments === 'string' ? request.callArguments.slice(0, 4000) : null,
403
413
  reason: typeof request.reason === 'string' ? request.reason : null,
@@ -406,7 +416,8 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
406
416
  : null,
407
417
  agentId: request.agentId ?? null,
408
418
  source: request.source ?? null,
409
- askedAt: new Date().toISOString(),
419
+ askedAt: new Date(askedAt).toISOString(),
420
+ expiresAt: new Date(askedAt + APPROVAL_TIMEOUT_MS).toISOString(),
410
421
  }
411
422
  return new Promise(resolve => {
412
423
  const settle = outcome => {
@@ -589,6 +600,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
589
600
  throw new WorkbenchError(502, 'the host created a session but returned no id', { id: 'session-create-failed' })
590
601
  }
591
602
  if (currentSessionId !== sessionId) {
603
+ sessionAllowedTools.clear()
592
604
  detach()
593
605
  currentSessionId = sessionId
594
606
  resetStore(sessionId)
@@ -604,6 +616,45 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
604
616
  return { sessionId, capabilities: caps }
605
617
  }
606
618
 
619
+ /**
620
+ * Show a conversation the host already has. The page reloads afterwards, so
621
+ * it re-runs bootstrap and replays that session through the normal path
622
+ * instead of the console inventing a second rendering pipeline.
623
+ *
624
+ * @param {string} sessionId - a conversation this console created.
625
+ */
626
+ async function switchSession(sessionId) {
627
+ const caps = capabilities()
628
+ if (!caps.chat) {
629
+ throw new WorkbenchError(503, caps.reason ?? 'the host exposes no conversation session API', {
630
+ id: 'console-unavailable',
631
+ })
632
+ }
633
+ if (typeof host.openSession !== 'function') {
634
+ throw new WorkbenchError(501, 'this host cannot reopen a conversation', { id: 'switch-unavailable' })
635
+ }
636
+ const target = await host.openSession(sessionId)
637
+ if (!target) {
638
+ throw new WorkbenchError(404, 'no such conversation in this console space', {
639
+ id: 'unknown-session',
640
+ hint: 'the history list only contains conversations this console created.',
641
+ })
642
+ }
643
+ if (target.sessionId === currentSessionId) {
644
+ return { sessionId: target.sessionId, capabilities: caps, switched: false }
645
+ }
646
+ currentSessionId = target.sessionId
647
+ rememberedSessionId = target.sessionId
648
+ sessionAllowedTools.clear()
649
+ detach()
650
+ resetStore(target.sessionId)
651
+ await saveTimeline(true)
652
+ broadcast({ type: 'session', sessionId: target.sessionId, mode: 'chat', switched: true })
653
+ if (clients.size > 0) attach(target.sessionId)
654
+ refreshRuns({ force: true }).catch(() => {})
655
+ return { sessionId: target.sessionId, capabilities: caps }
656
+ }
657
+
607
658
  async function ensureSession() {
608
659
  if (currentSessionId) return { sessionId: currentSessionId, capabilities: capabilities() }
609
660
  return createSession()
@@ -620,6 +671,33 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
620
671
  }
621
672
  }
622
673
 
674
+ /**
675
+ * A conversation opened for the first time in this process (a switch, or a
676
+ * restart where the local timeline only keeps one session) has no cached
677
+ * transcript. Seed it from that session's own committed events so the page
678
+ * shows what happened, rather than an empty thread that looks like lost work.
679
+ *
680
+ * @param {string} sessionId - conversation whose events should be read.
681
+ */
682
+ async function seedFromHost(sessionId) {
683
+ if (typeof host.readSessionEvents !== 'function') return
684
+ let records
685
+ try {
686
+ records = await host.readSessionEvents(sessionId)
687
+ } catch {
688
+ return
689
+ }
690
+ if (!Array.isArray(records) || records.length === 0) return
691
+ // A live follow may have filled the transcript while this read was in
692
+ // flight; its events are newer and mergeRecords de-duplicates by seq.
693
+ if (store.sessionId !== sessionId) return
694
+ if (store.entries.length > 0) return
695
+ if (mergeRecords(records) === 0) return
696
+ saveTimeline()
697
+ const frame = transcriptFrame()
698
+ if (frame) broadcast({ ...boundedSnapshot(frame), seq: nextSeq(), at: new Date().toISOString() })
699
+ }
700
+
623
701
  function openStream(req, res) {
624
702
  const caps = capabilities()
625
703
  if (!caps.chat) {
@@ -665,6 +743,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
665
743
  writeFrame(res, { type: 'runs', seq: nextSeq(), at: new Date().toISOString(), sessionId: currentSessionId, runs: lastRuns })
666
744
  }
667
745
  attach(currentSessionId)
746
+ if (!cached) seedFromHost(currentSessionId).catch(() => {})
668
747
  const heartbeat = setInterval(() => {
669
748
  if (res.destroyed || res.writableEnded) return
670
749
  try {
@@ -763,7 +842,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
763
842
  // allowed from loopback origins only — the token still gates the page.
764
843
  sendText(res, 200, page, 'text/html; charset=utf-8', {
765
844
  'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
766
- + "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; "
845
+ + "connect-src 'self'; img-src 'self' data:; frame-src 'self'; base-uri 'none'; form-action 'none'; "
767
846
  + "frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:*",
768
847
  })
769
848
  return
@@ -843,6 +922,30 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
843
922
  return
844
923
  }
845
924
 
925
+ if (leaf === 'sessions' && parts.length === 3) {
926
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
927
+ if (typeof host.listSessions !== 'function') {
928
+ send(res, 200, { ok: true, data: { sessions: [], currentSessionId, reason: 'this host cannot list conversations' } })
929
+ return
930
+ }
931
+ try {
932
+ const sessions = await host.listSessions()
933
+ send(res, 200, { ok: true, data: { sessions, currentSessionId, reason: null } })
934
+ } catch (error) {
935
+ send(res, 200, { ok: true, data: { sessions: [], currentSessionId, reason: messageOf(error) } })
936
+ }
937
+ return
938
+ }
939
+
940
+ if (leaf === 'session' && parts.length === 4 && parts[3] === 'switch') {
941
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
942
+ const body = await readJson(req)
943
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
944
+ if (!sessionId) throw new WorkbenchError(400, 'sessionId is required', { id: 'missing-session-id' })
945
+ send(res, 200, { ok: true, data: await switchSession(sessionId) })
946
+ return
947
+ }
948
+
846
949
  if (leaf === 'message' && parts.length === 3) {
847
950
  if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
848
951
  const body = await readJson(req)
@@ -882,12 +985,14 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
882
985
  if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
883
986
  const body = await readJson(req)
884
987
  const id = typeof body?.id === 'string' ? body.id.trim() : ''
885
- const decision = body?.decision === 'allow'
988
+ const wanted = body?.decision
989
+ const decision = wanted === 'allow'
886
990
  ? 'allowed-once'
887
- : body?.decision === 'reject' ? 'rejected' : null
991
+ : wanted === 'allow-tool' ? 'allowed-tool'
992
+ : wanted === 'reject' ? 'rejected' : null
888
993
  if (!id) throw new WorkbenchError(400, 'id is required', { id: 'missing-approval-id' })
889
994
  if (!decision) {
890
- throw new WorkbenchError(400, 'decision must be allow or reject', { id: 'bad-approval-decision' })
995
+ throw new WorkbenchError(400, 'decision must be allow, allow-tool or reject', { id: 'bad-approval-decision' })
891
996
  }
892
997
  const pending = approvals.get(id)
893
998
  if (!pending) {
@@ -896,6 +1001,13 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
896
1001
  hint: 'reload the page: the question expired, or another window already answered it.',
897
1002
  })
898
1003
  }
1004
+ if (decision === 'allowed-tool') {
1005
+ sessionAllowedTools.add(pending.payload.toolName)
1006
+ pending.settle('allowed-once')
1007
+ broadcast({ type: 'approval', action: 'decided', id, outcome: 'allowed-once', scope: 'tool' })
1008
+ send(res, 200, { ok: true, data: { id, outcome: 'allowed-once', scope: 'tool', toolName: pending.payload.toolName } })
1009
+ return
1010
+ }
899
1011
  pending.settle(decision)
900
1012
  broadcast({ type: 'approval', action: 'decided', id, outcome: decision })
901
1013
  send(res, 200, { ok: true, data: { id, outcome: decision } })
@@ -974,6 +1086,26 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
974
1086
  return
975
1087
  }
976
1088
 
1089
+ if (leaf === 'runs' && parts.length === 5 && parts[4] === 'cancel') {
1090
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
1091
+ if (!currentSessionId) throw new WorkbenchError(409, 'no conversation is open', { id: 'no-session' })
1092
+ if (typeof host.cancelRun !== 'function') {
1093
+ throw new WorkbenchError(501, 'this host cannot cancel runs from the console', { id: 'cancel-unavailable' })
1094
+ }
1095
+ const runId = decodeURIComponent(parts[3])
1096
+ let result
1097
+ try {
1098
+ result = await host.cancelRun(currentSessionId, runId)
1099
+ } catch (error) {
1100
+ throw new WorkbenchError(502, `the run was not cancelled: ${messageOf(error)}`, { id: 'cancel-failed' })
1101
+ }
1102
+ if (!result) throw new WorkbenchError(404, `no run ${runId} for this conversation`, { id: 'unknown-run' })
1103
+ broadcast({ type: 'canceling', sessionId: currentSessionId, runId, status: result.status })
1104
+ await refreshRuns({ force: true }).catch(() => {})
1105
+ send(res, 200, { ok: true, data: result })
1106
+ return
1107
+ }
1108
+
977
1109
  if (leaf === 'runs' && parts.length <= 4) {
978
1110
  if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
979
1111
  if (!currentSessionId) {
package/lib/index.js CHANGED
@@ -3402,6 +3402,20 @@ export function apply(ctx, config) {
3402
3402
  const consoleRoot = cfg.consoleRoot ? path.resolve(cfg.consoleRoot) : workbenchRoot
3403
3403
  const CONSOLE_SPACE_ID = 'superagent-console-space'
3404
3404
 
3405
+ function getSessionController() {
3406
+ if (typeof ctx.get === 'function') {
3407
+ const service = ctx.get('sessionController')
3408
+ if (service) return service
3409
+ }
3410
+ // Direct property is topology-sensitive; this is a fallback for hosts
3411
+ // that expose the service without the registry.
3412
+ try {
3413
+ return ctx.sessionController
3414
+ } catch {
3415
+ return undefined
3416
+ }
3417
+ }
3418
+
3405
3419
  function consoleCapabilities() {
3406
3420
  const session = getSessionController()
3407
3421
  if (!session) {
@@ -3462,6 +3476,60 @@ export function apply(ctx, config) {
3462
3476
  return null
3463
3477
  }
3464
3478
 
3479
+ /**
3480
+ * The tool a running worker is spending its time on, read from that worker's
3481
+ * own event log: the last unanswered `tool/call`, or the most recent one
3482
+ * when every call already came back (a worker between calls). Null when the
3483
+ * log cannot be read; the page then shows no tool rather than a guess.
3484
+ */
3485
+ function runningToolName(childId) {
3486
+ if (typeof childId !== 'string' || !childId) return null
3487
+ const holder = (() => {
3488
+ const sessions = consoleService('sessions')
3489
+ if (sessions && typeof sessions.get === 'function') {
3490
+ const session = sessions.get(childId)
3491
+ if (session) return session
3492
+ }
3493
+ const agents = getAgents()
3494
+ if (agents && typeof agents.get === 'function') {
3495
+ const agent = agents.get(childId)
3496
+ return agent?.session ?? agent ?? null
3497
+ }
3498
+ return null
3499
+ })()
3500
+ if (!holder || typeof holder.snapshotEvents !== 'function') return null
3501
+ let events
3502
+ try {
3503
+ events = holder.snapshotEvents()
3504
+ } catch {
3505
+ return null
3506
+ }
3507
+ if (!Array.isArray(events)) return null
3508
+ const answered = new Set()
3509
+ // The newest unanswered call is what the lane is running now. When every
3510
+ // call already came back, the most recent one still tells the user what
3511
+ // that lane is spending its time on.
3512
+ let latest = null
3513
+ for (let index = events.length - 1, scanned = 0; index >= 0 && scanned < 80; index -= 1, scanned += 1) {
3514
+ const event = events[index]
3515
+ const data = event?.data
3516
+ if (!data || typeof data !== 'object') continue
3517
+ const callId = data.callId || data.message?.toolCallId || data.message?.source?.callId
3518
+ if (event.type === 'tool/result') {
3519
+ if (callId) answered.add(callId)
3520
+ continue
3521
+ }
3522
+ if (event.type !== 'tool/call' || !callId) continue
3523
+ const name = typeof data.name === 'string' && data.name ? data.name : null
3524
+ if (answered.has(callId)) {
3525
+ if (!latest) latest = name
3526
+ continue
3527
+ }
3528
+ return name
3529
+ }
3530
+ return latest
3531
+ }
3532
+
3465
3533
  function runView(run, { detail = false } = {}) {
3466
3534
  const usage = run.usage && typeof run.usage === 'object' ? run.usage : null
3467
3535
  const cost = usage ? computeCost(usage, cfg.pricing) : null
@@ -3481,6 +3549,11 @@ export function apply(ctx, config) {
3481
3549
  title: subtask.title ?? null,
3482
3550
  status: subtask.status ?? null,
3483
3551
  childId: subtask.childId ?? null,
3552
+ // Timing is what lets the page show which line is slow; without it
3553
+ // every lane looks equally busy.
3554
+ startedAt: subtask.startedAt ?? null,
3555
+ finishedAt: subtask.finishedAt ?? null,
3556
+ tool: subtask.status === 'running' ? runningToolName(subtask.childId) : null,
3484
3557
  }))
3485
3558
  : []
3486
3559
  const report = typeof run.report === 'string' ? run.report : null
@@ -3517,6 +3590,91 @@ export function apply(ctx, config) {
3517
3590
  }
3518
3591
  }
3519
3592
 
3593
+ /**
3594
+ * Count the files and pages a run report names, using the same rule the page
3595
+ * uses for artifact chips. The history row only needs the number.
3596
+ */
3597
+ function countReportArtifacts(report) {
3598
+ const text = typeof report === 'string' ? report : ''
3599
+ if (!text) return 0
3600
+ const seen = new Set()
3601
+ const push = value => {
3602
+ const href = value.replace(/[.,;:,。;:]+$/, '')
3603
+ if (href) seen.add(href)
3604
+ }
3605
+ for (const match of text.matchAll(/https?:\/\/[^\s"'`<>)\]}|]+/g)) push(match[0])
3606
+ for (const match of text.matchAll(/(?:[A-Za-z]:[\\/]|\.{1,2}[\\/]|~[\\/])[^\s"'`<>|]+?\.(?:html?|md|pdf|docx?|xlsx?|csv|tsv|json|ya?ml|txt|log|png|jpe?g|gif|webp|svg|zip|pptx?|py|js|mjs|css)\b/gi)) {
3607
+ push(match[0])
3608
+ }
3609
+ return Math.min(seen.size, 12)
3610
+ }
3611
+
3612
+ const firstTextCache = new Map()
3613
+
3614
+ /**
3615
+ * Session records as the page consumes them (`{type:'event', event}`).
3616
+ * Pages back from the newest until the first turn is reached, bounded so a
3617
+ * very long conversation cannot stall the drawer. Null when unreadable.
3618
+ */
3619
+ async function readSessionRecords(sessionId) {
3620
+ const controller = getSessionController()
3621
+ if (!controller || typeof controller.events !== 'function') return null
3622
+ const address = { kind: 'session', sessionId }
3623
+ const { signal } = new AbortController()
3624
+ try {
3625
+ const newest = await controller.events({ address, maxMessages: 200 }, signal)
3626
+ if (!newest || !Array.isArray(newest.records)) return null
3627
+ let records = newest.records.slice()
3628
+ let page = newest
3629
+ for (let guard = 0; page.hasMore === true && guard < 8; guard += 1) {
3630
+ const oldest = records[0]?.event?.seq
3631
+ if (!Number.isSafeInteger(oldest) || oldest <= 0) break
3632
+ const older = await controller.events({ address, maxMessages: 200, beforeSeq: oldest }, signal)
3633
+ const batch = Array.isArray(older?.records) ? older.records : []
3634
+ if (batch.length === 0) break
3635
+ records = [...batch, ...records]
3636
+ page = older
3637
+ }
3638
+ return records
3639
+ } catch (error) {
3640
+ const message = error instanceof Error ? error.message : String(error)
3641
+ const frame = error instanceof Error && error.stack ? String(error.stack).split('\n')[1]?.trim() ?? '' : ''
3642
+ log(`session read error: ${message}`)
3643
+ log(`session read at: ${frame.slice(0, 100)}`)
3644
+ return null
3645
+ }
3646
+ }
3647
+
3648
+ /**
3649
+ * The first thing the user said in a conversation, read from that session's
3650
+ * own log. Cached per `updatedAt` so opening the drawer does not re-read
3651
+ * every transcript, and null when the log cannot be read.
3652
+ */
3653
+ async function firstUserText(sessionId, marker) {
3654
+ const key = `${sessionId}:${marker ?? ''}`
3655
+ if (firstTextCache.has(key)) return firstTextCache.get(key)
3656
+ const records = await readSessionRecords(sessionId)
3657
+ let text = null
3658
+ for (const record of records ?? []) {
3659
+ const event = record?.event
3660
+ if (event?.type !== 'user/message') continue
3661
+ if (event.data?.source?.kind !== 'user') continue
3662
+ const parts = Array.isArray(event.data?.content) ? event.data.content : []
3663
+ const joined = parts
3664
+ .filter(part => part?.type === 'text' && typeof part.text === 'string')
3665
+ .map(part => part.text)
3666
+ .join(' ')
3667
+ .trim()
3668
+ if (joined) {
3669
+ text = joined.slice(0, 140)
3670
+ break
3671
+ }
3672
+ }
3673
+ if (text === null && records === null) log(`[superagent-console] first text unavailable for ${sessionId}`)
3674
+ firstTextCache.set(key, text)
3675
+ return text
3676
+ }
3677
+
3520
3678
  const consoleHost = {
3521
3679
  capabilities: consoleCapabilities,
3522
3680
 
@@ -3625,6 +3783,92 @@ export function apply(ctx, config) {
3625
3783
  return runView(run, { detail: true })
3626
3784
  },
3627
3785
 
3786
+ /**
3787
+ * Stop one run through the same cancel path the `superagent_cancel` tool
3788
+ * uses. Ownership is checked against the conversation first, so a page
3789
+ * can only stop runs it is showing.
3790
+ */
3791
+ async cancelRun(sessionId, runId) {
3792
+ await ready
3793
+ if (stateError) throw stateError
3794
+ const id = typeof runId === 'string' ? runId.trim() : ''
3795
+ if (!id) return null
3796
+ const run = await store.read(id)
3797
+ if (!run || run.parentSessionId !== sessionId) return null
3798
+ const cancelled = await orchestrator.cancel(id)
3799
+ return {
3800
+ runId: id,
3801
+ status: cancelled?.status ?? null,
3802
+ cancelPending: cancelled?.cancelPending === true,
3803
+ }
3804
+ },
3805
+
3806
+ /** The console's own conversations, newest first, with what they produced. */
3807
+ async listSessions() {
3808
+ const controller = getSessionController()
3809
+ if (!controller || typeof controller.list !== 'function') return []
3810
+ await ready
3811
+ if (stateError) throw stateError
3812
+ // The registered controller answers `{ items }`; older shapes are a bare array.
3813
+ const listed = await controller.list()
3814
+ const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
3815
+ const runs = await store.list().catch(() => [])
3816
+ const counts = new Map()
3817
+ for (const run of runs) {
3818
+ if (!run || typeof run.parentSessionId !== 'string') continue
3819
+ const entry = counts.get(run.parentSessionId) ?? { runs: 0, artifacts: 0 }
3820
+ entry.runs += 1
3821
+ entry.artifacts += countReportArtifacts(run.report)
3822
+ counts.set(run.parentSessionId, entry)
3823
+ }
3824
+ const own = items
3825
+ .filter(item => item && typeof item.sessionId === 'string')
3826
+ .filter(item => item.parentSessionId === undefined)
3827
+ .filter(item => typeof item.cwd === 'string' && path.resolve(item.cwd) === consoleRoot)
3828
+ .sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
3829
+ .slice(0, 12)
3830
+ return Promise.all(own.map(async item => ({
3831
+ sessionId: item.sessionId,
3832
+ updatedAt: item.updatedAt ?? null,
3833
+ running: item.running === true,
3834
+ blank: item.blank === true,
3835
+ runs: counts.get(item.sessionId)?.runs ?? 0,
3836
+ artifacts: counts.get(item.sessionId)?.artifacts ?? 0,
3837
+ first: item.blank ? null : await firstUserText(item.sessionId, item.updatedAt),
3838
+ title: item.projections?.values?.sessionTitle ?? item.projections?.values?.title ?? null,
3839
+ })))
3840
+ },
3841
+
3842
+ /**
3843
+ * One conversation's log, newest page first and then walked back to the
3844
+ * first turn. The controller reads cold sessions too, so a conversation
3845
+ * the console has never shown can still be reopened.
3846
+ */
3847
+ async readSessionEvents(sessionId) {
3848
+ const records = await readSessionRecords(sessionId)
3849
+ return records === null ? null : records.slice(-600)
3850
+ },
3851
+
3852
+ /**
3853
+ * Resolve a conversation this console may show. Only sessions created in
3854
+ * the console space qualify, so the page cannot wander into the user's own
3855
+ * sessions by guessing an id.
3856
+ */
3857
+ async openSession(sessionId) {
3858
+ const id = typeof sessionId === 'string' ? sessionId.trim() : ''
3859
+ if (!id) return null
3860
+ const controller = getSessionController()
3861
+ if (!controller || typeof controller.list !== 'function') return null
3862
+ const listed = await controller.list()
3863
+ const items = Array.isArray(listed) ? listed : Array.isArray(listed?.items) ? listed.items : []
3864
+ const hit = items.find(item => item
3865
+ && item.sessionId === id
3866
+ && item.parentSessionId === undefined
3867
+ && typeof item.cwd === 'string'
3868
+ && path.resolve(item.cwd) === consoleRoot)
3869
+ return hit ? { sessionId: id, updatedAt: hit.updatedAt ?? null } : null
3870
+ },
3871
+
3628
3872
  async answer({ sessionId, runId, attentionId, answer }) {
3629
3873
  let agent = conversationAgent(sessionId)
3630
3874
  if (!agent) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiangyixie/dsh-superagent",
3
- "version": "0.14.7",
3
+ "version": "0.14.8",
4
4
  "description": "长周期自主执行插件:一个目标拆成可并行的子任务,交付一份合并报告,重启后仍可继续。",
5
5
  "author": "Admire (LittleChenLiya)",
6
6
  "type": "module",