dsh-atc 0.18.0 → 0.23.0
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/README.md +109 -9
- package/client/client.js +281 -30
- package/lib/capabilities.mjs +70 -0
- package/lib/collect.mjs +169 -205
- package/lib/detail.mjs +136 -0
- package/lib/dsh-frames.mjs +94 -0
- package/lib/focus.mjs +210 -0
- package/lib/index.js +207 -3
- package/lib/openers.mjs +73 -0
- package/lib/rules.mjs +100 -0
- package/lib/tool-calls.mjs +80 -0
- package/package.json +3 -2
package/lib/detail.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The detail drawer's data: what a session has been doing, turn by turn.
|
|
3
|
+
*
|
|
4
|
+
* Only DSH can answer this — its log records tool calls with durations. Other
|
|
5
|
+
* sources get `supported: false` rather than a lookalike summary built from
|
|
6
|
+
* whatever fields happen to exist, because a drawer that says "tool calls: none"
|
|
7
|
+
* for a tool with no such concept is worse than one that says so.
|
|
8
|
+
*
|
|
9
|
+
* Read on demand only: this walks more of the log than the poll does, and a card
|
|
10
|
+
* click is the moment someone asked for it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { statSync } from 'node:fs'
|
|
14
|
+
import { walkTail } from './dsh-frames.mjs'
|
|
15
|
+
import { callTarget } from './tool-calls.mjs'
|
|
16
|
+
|
|
17
|
+
/** How many calls the drawer shows, and how far back it will look for them. */
|
|
18
|
+
const MAX_CALLS = 12
|
|
19
|
+
const MAX_FRAMES = 400
|
|
20
|
+
const DETAIL_WINDOW = 384 * 1024
|
|
21
|
+
|
|
22
|
+
/** Result content orients the reader; it is not the drawer's subject. */
|
|
23
|
+
const SNIPPET = 240
|
|
24
|
+
|
|
25
|
+
function snippet(content) {
|
|
26
|
+
if (!Array.isArray(content)) return ''
|
|
27
|
+
const text = content
|
|
28
|
+
.map((part) => (typeof part?.text === 'string' ? part.text : ''))
|
|
29
|
+
.join(' ')
|
|
30
|
+
.replace(/\s+/g, ' ')
|
|
31
|
+
.trim()
|
|
32
|
+
if (text === '') return ''
|
|
33
|
+
return text.length > SNIPPET ? `${text.slice(0, SNIPPET)}…` : text
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Read one DSH session log into the shape the drawer renders.
|
|
38
|
+
*
|
|
39
|
+
* Calls and results are collected separately and paired at the end: the walk
|
|
40
|
+
* goes newest frame first, so a result is seen before the call it belongs to.
|
|
41
|
+
* Pairing as they arrive left every row reading "进行中".
|
|
42
|
+
*
|
|
43
|
+
* @param file - absolute path to `session.v4.jsonl.zstd`.
|
|
44
|
+
*/
|
|
45
|
+
export function readDshDetail(file) {
|
|
46
|
+
const info = statSync(file)
|
|
47
|
+
const calls = new Map() // callId → what the agent asked for
|
|
48
|
+
const results = new Map() // callId → what came back
|
|
49
|
+
let usage = null
|
|
50
|
+
let lastTurnEnd = null
|
|
51
|
+
|
|
52
|
+
walkTail(file, info.size, {
|
|
53
|
+
windowBytes: DETAIL_WINDOW,
|
|
54
|
+
maxFrames: MAX_FRAMES,
|
|
55
|
+
visit(events) {
|
|
56
|
+
for (const event of events) {
|
|
57
|
+
const type = event?.type
|
|
58
|
+
if (type === 'tool/call') {
|
|
59
|
+
const callId = String(event.data?.callId ?? '')
|
|
60
|
+
const name = String(event.data?.name ?? '')
|
|
61
|
+
if (!callId || !name || calls.has(callId)) continue
|
|
62
|
+
calls.set(callId, {
|
|
63
|
+
callId,
|
|
64
|
+
name,
|
|
65
|
+
target: callTarget(event.data?.arguments),
|
|
66
|
+
startedAt: typeof event.time === 'number' ? event.time : 0,
|
|
67
|
+
})
|
|
68
|
+
} else if (type === 'tool/result') {
|
|
69
|
+
const callId = String(event.data?.toolCallId ?? event.data?.message?.source?.callId ?? '')
|
|
70
|
+
if (!callId || results.has(callId)) continue
|
|
71
|
+
const kind = String(event.data?.message?.source?.kind ?? '')
|
|
72
|
+
results.set(callId, {
|
|
73
|
+
endedAt: typeof event.time === 'number' ? event.time : 0,
|
|
74
|
+
// Unknown is reported as unknown: 'error' proves a failure, 'tool'
|
|
75
|
+
// proves a normal read, anything else stays null.
|
|
76
|
+
ok: kind === 'error' ? false : kind === 'tool' ? true : null,
|
|
77
|
+
snippet: snippet(event.data?.message?.content),
|
|
78
|
+
})
|
|
79
|
+
} else if (type === 'assistant/message') {
|
|
80
|
+
// The usage sits beside the message, not inside it.
|
|
81
|
+
const next = event.data?.usage
|
|
82
|
+
if (next && typeof next === 'object') {
|
|
83
|
+
const at = typeof event.time === 'number' ? event.time : 0
|
|
84
|
+
if (!usage || at >= usage.at) {
|
|
85
|
+
usage = {
|
|
86
|
+
at,
|
|
87
|
+
inputTokens: Number(next.inputTokens) || 0,
|
|
88
|
+
outputTokens: Number(next.outputTokens) || 0,
|
|
89
|
+
totalTokens: Number(next.totalTokens) || 0,
|
|
90
|
+
cacheReadTokens: Number(next.cacheReadTokens) || 0,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
} else if (type === 'turn/end' && typeof event.time === 'number') {
|
|
95
|
+
if (!lastTurnEnd || event.time > lastTurnEnd.time) {
|
|
96
|
+
lastTurnEnd = { time: event.time, reason: String(event.data?.reason?.kind ?? '') }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return calls.size >= MAX_CALLS && usage !== null
|
|
101
|
+
},
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
const list = [...calls.values()]
|
|
105
|
+
.sort((a, b) => b.startedAt - a.startedAt)
|
|
106
|
+
.slice(0, MAX_CALLS)
|
|
107
|
+
.map((call) => {
|
|
108
|
+
const result = results.get(call.callId)
|
|
109
|
+
return {
|
|
110
|
+
callId: call.callId,
|
|
111
|
+
name: call.name,
|
|
112
|
+
target: call.target,
|
|
113
|
+
startedAt: call.startedAt,
|
|
114
|
+
durationMs: result?.endedAt && call.startedAt ? result.endedAt - call.startedAt : null,
|
|
115
|
+
ok: result ? result.ok : null,
|
|
116
|
+
finished: Boolean(result),
|
|
117
|
+
snippet: result?.snippet ?? '',
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
supported: true,
|
|
123
|
+
calls: list,
|
|
124
|
+
usage: usage
|
|
125
|
+
? {
|
|
126
|
+
inputTokens: usage.inputTokens,
|
|
127
|
+
outputTokens: usage.outputTokens,
|
|
128
|
+
totalTokens: usage.totalTokens,
|
|
129
|
+
cacheReadTokens: usage.cacheReadTokens,
|
|
130
|
+
}
|
|
131
|
+
: null,
|
|
132
|
+
lastTurn: lastTurnEnd,
|
|
133
|
+
totalCalls: calls.size,
|
|
134
|
+
bytes: info.size,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a DSH session log: a run of independent zstd frames.
|
|
3
|
+
*
|
|
4
|
+
* The whole-file decoder stops after the first frame, which is why this exists at
|
|
5
|
+
* all — a session log appends one frame per batch of events, so reading "what
|
|
6
|
+
* happened last" means decoding frames from the tail.
|
|
7
|
+
*
|
|
8
|
+
* Kept separate from the collectors because the board reads the newest turn on
|
|
9
|
+
* every poll while the detail drawer reads more of the same file on demand; both
|
|
10
|
+
* need the same three primitives and neither should own them.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { closeSync, openSync, readSync } from 'node:fs'
|
|
14
|
+
import { zstdDecompressSync } from 'node:zlib'
|
|
15
|
+
|
|
16
|
+
/** Frame magic of zstd, searched for to find frame starts inside a window. */
|
|
17
|
+
export const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
|
|
18
|
+
|
|
19
|
+
/** How much of a log the board reads to answer "title + last turn". */
|
|
20
|
+
export const HEAD_WINDOW = 512 * 1024
|
|
21
|
+
export const TAIL_WINDOW = 96 * 1024
|
|
22
|
+
|
|
23
|
+
/** Byte offsets of every zstd frame in a window. */
|
|
24
|
+
export function frameOffsets(buffer) {
|
|
25
|
+
const offsets = []
|
|
26
|
+
let cursor = 0
|
|
27
|
+
while (true) {
|
|
28
|
+
const at = buffer.indexOf(ZSTD_MAGIC, cursor)
|
|
29
|
+
if (at === -1) break
|
|
30
|
+
offsets.push(at)
|
|
31
|
+
cursor = at + 4
|
|
32
|
+
}
|
|
33
|
+
return offsets
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Decode one frame's events, or nothing when the slice is truncated. */
|
|
37
|
+
export function eventsOfFrame(buffer, at) {
|
|
38
|
+
let text
|
|
39
|
+
try {
|
|
40
|
+
text = zstdDecompressSync(buffer.subarray(at)).toString('utf8')
|
|
41
|
+
} catch {
|
|
42
|
+
return []
|
|
43
|
+
}
|
|
44
|
+
const events = []
|
|
45
|
+
for (const line of text.split('\n')) {
|
|
46
|
+
if (!line) continue
|
|
47
|
+
try {
|
|
48
|
+
events.push(JSON.parse(line))
|
|
49
|
+
} catch {
|
|
50
|
+
/* a half-written line is not an event */
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return events
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Read `length` bytes at `from`. */
|
|
57
|
+
export function readWindow(file, size, from, length) {
|
|
58
|
+
const buffer = Buffer.alloc(length)
|
|
59
|
+
const fd = openSync(file, 'r')
|
|
60
|
+
try {
|
|
61
|
+
readSync(fd, buffer, 0, length, from)
|
|
62
|
+
} finally {
|
|
63
|
+
closeSync(fd)
|
|
64
|
+
}
|
|
65
|
+
return buffer
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Walk the tail of a log from the newest frame backwards.
|
|
70
|
+
*
|
|
71
|
+
* @param file - the session log.
|
|
72
|
+
* @param size - the file's size in bytes.
|
|
73
|
+
* @param windowBytes - how much of the tail to load; older frames are not read.
|
|
74
|
+
* @param maxFrames - stop after decoding this many frames.
|
|
75
|
+
* @param visit - called with each frame's events, newest frame first. Return
|
|
76
|
+
* true to stop the walk.
|
|
77
|
+
* @returns how many frames were decoded.
|
|
78
|
+
*/
|
|
79
|
+
export function walkTail(file, size, { windowBytes = TAIL_WINDOW, maxFrames = 64, visit }) {
|
|
80
|
+
const length = Math.min(size, windowBytes)
|
|
81
|
+
const window = readWindow(file, size, size - length, length)
|
|
82
|
+
const frames = frameOffsets(window)
|
|
83
|
+
let decoded = 0
|
|
84
|
+
// When the window does not reach the start of the file, its first frame is
|
|
85
|
+
// cut in half and cannot be decoded — skip it. A small log is fully covered,
|
|
86
|
+
// so its first frame is real and must be read.
|
|
87
|
+
const first = size <= length ? 0 : 1
|
|
88
|
+
for (let index = frames.length - 1; index >= first && decoded < maxFrames; index -= 1) {
|
|
89
|
+
decoded += 1
|
|
90
|
+
const events = eventsOfFrame(window, frames[index])
|
|
91
|
+
if (events.length > 0 && visit(events, decoded)) break
|
|
92
|
+
}
|
|
93
|
+
return decoded
|
|
94
|
+
}
|
package/lib/focus.mjs
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bringing an already-running tool to the front.
|
|
3
|
+
*
|
|
4
|
+
* The board's job ends at "which session is this"; the tool that owns the
|
|
5
|
+
* session is usually already open somewhere on the desktop, and the useful
|
|
6
|
+
* action is to show that window — not to start a second client on a session the
|
|
7
|
+
* first one is still holding.
|
|
8
|
+
*
|
|
9
|
+
* There is no Win32 binding in Node, so this goes through one PowerShell run that
|
|
10
|
+
* does the enumeration and the focus. It is slower than an in-process call
|
|
11
|
+
* (~300–600 ms) and only runs when a card is clicked.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { spawnSync } from 'node:child_process'
|
|
15
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
16
|
+
import { tmpdir } from 'node:os'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The PowerShell half.
|
|
21
|
+
*
|
|
22
|
+
* `SetForegroundWindow` only works for the process Windows considers allowed to
|
|
23
|
+
* take the foreground, so the script attaches to the current foreground thread
|
|
24
|
+
* first — that is the documented workaround, and without it the call silently
|
|
25
|
+
* does nothing while DSH itself is in front.
|
|
26
|
+
*
|
|
27
|
+
* Two criteria are ANDed when both are given, so a matcher can require "title
|
|
28
|
+
* says opencode" *and* "the window belongs to a console host".
|
|
29
|
+
*/
|
|
30
|
+
const SCRIPT = `param([string]$Mode = 'list', [string]$Title = '', [string]$Proc = '')
|
|
31
|
+
|
|
32
|
+
# The host reads stdout as UTF-8; without this Windows hands back the console
|
|
33
|
+
# code page and every non-ASCII window title arrives as mojibake.
|
|
34
|
+
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
35
|
+
$OutputEncoding = [System.Text.Encoding]::UTF8
|
|
36
|
+
|
|
37
|
+
Add-Type @"
|
|
38
|
+
using System;
|
|
39
|
+
using System.Text;
|
|
40
|
+
using System.Runtime.InteropServices;
|
|
41
|
+
public class AtcWin {
|
|
42
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr p);
|
|
43
|
+
[DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr h);
|
|
44
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
|
|
45
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
46
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
|
47
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
|
48
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
49
|
+
[DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(IntPtr h, out int pid);
|
|
50
|
+
[DllImport("user32.dll")] public static extern bool AttachThreadInput(int a, int b, bool attach);
|
|
51
|
+
[DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr h, bool alt);
|
|
52
|
+
[DllImport("user32.dll")] public static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
|
53
|
+
[DllImport("kernel32.dll")] public static extern int GetCurrentThreadId();
|
|
54
|
+
public delegate bool EnumProc(IntPtr h, IntPtr p);
|
|
55
|
+
}
|
|
56
|
+
"@
|
|
57
|
+
|
|
58
|
+
$found = New-Object System.Collections.ArrayList
|
|
59
|
+
$cb = [AtcWin+EnumProc]{
|
|
60
|
+
param($hWnd, $lParam)
|
|
61
|
+
if (-not [AtcWin]::IsWindowVisible($hWnd)) { return $true }
|
|
62
|
+
$len = [AtcWin]::GetWindowTextLength($hWnd)
|
|
63
|
+
if ($len -le 0) { return $true }
|
|
64
|
+
$sb = New-Object System.Text.StringBuilder ($len + 2)
|
|
65
|
+
[void][AtcWin]::GetWindowText($hWnd, $sb, $sb.Capacity)
|
|
66
|
+
$windowPid = 0
|
|
67
|
+
[void][AtcWin]::GetWindowThreadProcessId($hWnd, [ref]$windowPid)
|
|
68
|
+
$procName = '?'
|
|
69
|
+
try { $procName = (Get-Process -Id $windowPid -ErrorAction Stop).ProcessName } catch { }
|
|
70
|
+
[void]$found.Add([pscustomobject]@{
|
|
71
|
+
hwnd = [int64]$hWnd; pid = $windowPid; proc = $procName; title = $sb.ToString()
|
|
72
|
+
})
|
|
73
|
+
return $true
|
|
74
|
+
}
|
|
75
|
+
[void][AtcWin]::EnumWindows($cb, [IntPtr]::Zero)
|
|
76
|
+
|
|
77
|
+
if ($Mode -eq 'list') {
|
|
78
|
+
$found | ConvertTo-Json -Compress -Depth 3
|
|
79
|
+
exit 0
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
$match = $found | Where-Object {
|
|
83
|
+
(($Title -eq '') -or ($_.title -match $Title)) -and (($Proc -eq '') -or ($_.proc -match $Proc))
|
|
84
|
+
} | Select-Object -First 1
|
|
85
|
+
|
|
86
|
+
if (-not $match) { '{"ok":false,"reason":"no-window"}'; exit 0 }
|
|
87
|
+
|
|
88
|
+
$hwnd = [IntPtr]$match.hwnd
|
|
89
|
+
$before = [AtcWin]::GetForegroundWindow()
|
|
90
|
+
[void][AtcWin]::ShowWindow($hwnd, 9)
|
|
91
|
+
|
|
92
|
+
# Windows refuses SetForegroundWindow for a process the user is not currently
|
|
93
|
+
# interacting with, which is exactly the case right after a click lands in DSH.
|
|
94
|
+
# Three escalating attempts; each one is verified by reading the foreground
|
|
95
|
+
# window back, so "requested" never gets confused with "happened".
|
|
96
|
+
function Raise([IntPtr]$h) {
|
|
97
|
+
$fg = [AtcWin]::GetForegroundWindow()
|
|
98
|
+
$fgThread = [AtcWin]::GetWindowThreadProcessId($fg, [ref]$null)
|
|
99
|
+
$myThread = [AtcWin]::GetCurrentThreadId()
|
|
100
|
+
[void][AtcWin]::AttachThreadInput($myThread, $fgThread, $true)
|
|
101
|
+
$ok = [AtcWin]::SetForegroundWindow($h)
|
|
102
|
+
[void][AtcWin]::AttachThreadInput($myThread, $fgThread, $false)
|
|
103
|
+
return $ok
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
$ok = Raise $hwnd
|
|
107
|
+
Start-Sleep -Milliseconds 120
|
|
108
|
+
$now = [AtcWin]::GetForegroundWindow()
|
|
109
|
+
|
|
110
|
+
if ($now -ne $hwnd) {
|
|
111
|
+
# SwitchToThisWindow predates the foreground lock and is not subject to it.
|
|
112
|
+
[AtcWin]::SwitchToThisWindow($hwnd, $true)
|
|
113
|
+
Start-Sleep -Milliseconds 120
|
|
114
|
+
$now = [AtcWin]::GetForegroundWindow()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if ($now -ne $hwnd) {
|
|
118
|
+
# Last resort: a synthetic ALT tap is what unlocks SetForegroundWindow for
|
|
119
|
+
# the calling process. Harmless when it does not help.
|
|
120
|
+
[AtcWin]::keybd_event(0x12, 0, 0, [UIntPtr]::Zero)
|
|
121
|
+
[AtcWin]::keybd_event(0x12, 0, 2, [UIntPtr]::Zero)
|
|
122
|
+
$ok = Raise $hwnd
|
|
123
|
+
Start-Sleep -Milliseconds 120
|
|
124
|
+
$now = [AtcWin]::GetForegroundWindow()
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
[pscustomobject]@{
|
|
128
|
+
ok = ($now -eq $hwnd); requested = $ok; title = $match.title; proc = $match.proc; pid = $match.pid
|
|
129
|
+
} | ConvertTo-Json -Compress
|
|
130
|
+
`
|
|
131
|
+
|
|
132
|
+
function run(args) {
|
|
133
|
+
if (process.platform !== 'win32') return null
|
|
134
|
+
const dir = mkdtempSync(join(tmpdir(), 'dsh-atc-win-'))
|
|
135
|
+
const file = join(dir, 'windows.ps1')
|
|
136
|
+
try {
|
|
137
|
+
writeFileSync(file, SCRIPT, 'utf8')
|
|
138
|
+
const result = spawnSync(
|
|
139
|
+
'powershell.exe',
|
|
140
|
+
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file, ...args],
|
|
141
|
+
{ encoding: 'utf8', timeout: 15_000, windowsHide: true },
|
|
142
|
+
)
|
|
143
|
+
if (result.status !== 0 || !result.stdout) return null
|
|
144
|
+
return result.stdout.trim()
|
|
145
|
+
} catch {
|
|
146
|
+
return null
|
|
147
|
+
} finally {
|
|
148
|
+
try {
|
|
149
|
+
rmSync(dir, { recursive: true, force: true })
|
|
150
|
+
} catch {
|
|
151
|
+
/* a leftover temp dir is not worth failing the click */
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Every visible top-level window, for diagnostics and for finding a match. */
|
|
157
|
+
export function listWindows() {
|
|
158
|
+
const raw = run(['-Mode', 'list'])
|
|
159
|
+
if (!raw) return []
|
|
160
|
+
try {
|
|
161
|
+
const parsed = JSON.parse(raw)
|
|
162
|
+
return Array.isArray(parsed) ? parsed : [parsed]
|
|
163
|
+
} catch {
|
|
164
|
+
return []
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Bring the first window matching a title pattern and/or a process pattern to
|
|
170
|
+
* the front.
|
|
171
|
+
*
|
|
172
|
+
* @param title - regex tested against the window title.
|
|
173
|
+
* @param proc - regex tested against the window's process name.
|
|
174
|
+
* @returns `{ ok, title, proc }` when it actually reached the foreground,
|
|
175
|
+
* `{ ok:false, reason }` otherwise. The `ok` is verified by re-reading the
|
|
176
|
+
* foreground window, not taken from SetForegroundWindow's return value.
|
|
177
|
+
*/
|
|
178
|
+
export function focusWindow({ title = '', proc = '' } = {}) {
|
|
179
|
+
if (!title && !proc) return { ok: false, reason: 'no-criteria' }
|
|
180
|
+
const raw = run(['-Mode', 'focus', '-Title', title, '-Proc', proc])
|
|
181
|
+
if (!raw) return { ok: false, reason: 'unavailable' }
|
|
182
|
+
try {
|
|
183
|
+
return JSON.parse(raw)
|
|
184
|
+
} catch {
|
|
185
|
+
return { ok: false, reason: 'unparsable' }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Only console hosts count for the CLI tools.
|
|
191
|
+
*
|
|
192
|
+
* Without this, a browser tab whose title happens to contain "OpenCode" wins the
|
|
193
|
+
* match and the click steals focus to Edge instead of the terminal — observed on
|
|
194
|
+
* this machine with a real Edge window before the allowlist existed.
|
|
195
|
+
*/
|
|
196
|
+
const TERMINAL_HOSTS = '^(cmd|conhost|WindowsTerminal|powershell|pwsh|wt|Code)$'
|
|
197
|
+
|
|
198
|
+
/** How to find each tool's window: title pattern, process pattern, or both. */
|
|
199
|
+
export const WINDOW_MATCHERS = {
|
|
200
|
+
workbuddy: { proc: '^WorkBuddy$' },
|
|
201
|
+
opencode: { title: 'opencode', proc: TERMINAL_HOSTS },
|
|
202
|
+
codex: { title: 'codex', proc: TERMINAL_HOSTS },
|
|
203
|
+
zcode: { proc: '^ZCode$' },
|
|
204
|
+
trae: { proc: '^Trae CN$' },
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Which tools can be brought to the front, for the UI to describe the click. */
|
|
208
|
+
export function focusableTools() {
|
|
209
|
+
return Object.keys(WINDOW_MATCHERS)
|
|
210
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -9,10 +9,14 @@
|
|
|
9
9
|
* is cached on disk until it goes stale.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
13
|
-
import { homedir } from 'node:os'
|
|
14
|
-
import { dirname, join } from 'node:path'
|
|
12
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { homedir, tmpdir } from 'node:os'
|
|
14
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
15
15
|
import { collectBoard } from './collect.mjs'
|
|
16
|
+
import { readDshDetail } from './detail.mjs'
|
|
17
|
+
import { WINDOW_MATCHERS, focusWindow, listWindows } from './focus.mjs'
|
|
18
|
+
import { openerLabel, planOpen } from './openers.mjs'
|
|
19
|
+
import { spawn } from 'node:child_process'
|
|
16
20
|
import { discoverStores, isKnownStore } from './discover.mjs'
|
|
17
21
|
|
|
18
22
|
/** Plugin manifest name. */
|
|
@@ -33,6 +37,9 @@ const DISCOVERY_SCHEMA = 2
|
|
|
33
37
|
/** Delay before the startup scan, so boot is not competing with a directory walk. */
|
|
34
38
|
const DISCOVERY_DELAY_MS = 12_000
|
|
35
39
|
|
|
40
|
+
/** Set once the connection service is composed; used to fence our route. */
|
|
41
|
+
let connection = null
|
|
42
|
+
|
|
36
43
|
const state = {
|
|
37
44
|
/** Last discovery result, from cache or a live run. */
|
|
38
45
|
result: null,
|
|
@@ -99,6 +106,106 @@ async function discovery(force = false) {
|
|
|
99
106
|
return state.running
|
|
100
107
|
}
|
|
101
108
|
|
|
109
|
+
/**
|
|
110
|
+
* Host/Origin fence plus authenticated-peer check, the same admission the host
|
|
111
|
+
* applies to its own routes. Without it a page in the user's browser could read
|
|
112
|
+
* this endpoint over loopback (DNS rebinding / local CSRF) — the payload names
|
|
113
|
+
* every session on the machine.
|
|
114
|
+
*
|
|
115
|
+
* Returns true when the request may proceed. Hosts that predate the API get a
|
|
116
|
+
* warning and a pass, so the plugin still runs there.
|
|
117
|
+
*/
|
|
118
|
+
let fenceWarningShown = false
|
|
119
|
+
function allowed(request) {
|
|
120
|
+
if (!connection || typeof connection.requestRejection !== 'function') {
|
|
121
|
+
if (!fenceWarningShown) {
|
|
122
|
+
fenceWarningShown = true
|
|
123
|
+
console.warn('dsh-atc: ctx.connection.requestRejection unavailable — /dsh-atc routes are unfenced')
|
|
124
|
+
}
|
|
125
|
+
return true
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
return connection.requestRejection(request) === undefined
|
|
129
|
+
} catch {
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The log file a detail request is about, or null when the id points outside
|
|
136
|
+
* the sessions tree. The id comes from the browser, so it is checked rather
|
|
137
|
+
* than trusted: a board that can be asked to read any path would be worse than
|
|
138
|
+
* no board.
|
|
139
|
+
*/
|
|
140
|
+
function dshSessionFile(id) {
|
|
141
|
+
const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
142
|
+
const root = resolve(home, 'sessions')
|
|
143
|
+
const raw = String(id ?? '')
|
|
144
|
+
const candidate = raw.endsWith('.zstd') ? raw : join(raw, 'session.v4.jsonl.zstd')
|
|
145
|
+
const abs = resolve(candidate)
|
|
146
|
+
return abs.startsWith(root + sep) ? abs : null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Detail is read on demand; a second look within five seconds reuses it. */
|
|
150
|
+
const DETAIL_TTL_MS = 5_000
|
|
151
|
+
const detailCache = new Map()
|
|
152
|
+
|
|
153
|
+
/** Read a small JSON body; anything larger is refused rather than buffered. */
|
|
154
|
+
async function readJsonBody(request, limit = 8 * 1024) {
|
|
155
|
+
const chunks = []
|
|
156
|
+
let size = 0
|
|
157
|
+
for await (const chunk of request) {
|
|
158
|
+
size += chunk.length
|
|
159
|
+
if (size > limit) throw new Error(`body too large (> ${limit} bytes)`)
|
|
160
|
+
chunks.push(chunk)
|
|
161
|
+
}
|
|
162
|
+
if (chunks.length === 0) return {}
|
|
163
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Open a terminal running the planned command.
|
|
168
|
+
*
|
|
169
|
+
* The command goes into a temporary .cmd file instead of a command line: cmd's
|
|
170
|
+
* own quoting turned out to be the fragile part (`start "" /min cmd /c "..."`
|
|
171
|
+
* silently produces an empty result, while `start "" <script.cmd>` works). The
|
|
172
|
+
* script also lets the failure case stay readable — if the CLI is missing, the
|
|
173
|
+
* window pauses instead of vanishing.
|
|
174
|
+
*
|
|
175
|
+
* Only Windows is implemented: `start` is the one way to get a visible console
|
|
176
|
+
* from a detached host process, and this plugin is developed and used there.
|
|
177
|
+
* Elsewhere the caller gets "unsupported" and the board copies the path.
|
|
178
|
+
*/
|
|
179
|
+
function spawnPlan(plan) {
|
|
180
|
+
if (process.platform !== 'win32') return { ok: false, reason: 'unsupported-platform' }
|
|
181
|
+
// Verification seam: proves the route → plan → spawn wiring without opening a
|
|
182
|
+
// real terminal (and without an agent session attached to it).
|
|
183
|
+
if (process.env.DSH_ATC_DRY_OPEN === '1') return { ok: true, dry: true }
|
|
184
|
+
const script = join(tmpdir(), `dsh-atc-open-${Date.now()}.cmd`)
|
|
185
|
+
const body = [
|
|
186
|
+
'@echo off',
|
|
187
|
+
// A cwd that no longer exists would make the script fail before the CLI runs.
|
|
188
|
+
plan.cwd && existsSync(plan.cwd) ? `cd /d "${plan.cwd}"` : '',
|
|
189
|
+
[plan.command, ...plan.args].join(' '),
|
|
190
|
+
// Keep the window open when the command failed, so the error is readable.
|
|
191
|
+
'if errorlevel 1 pause',
|
|
192
|
+
].filter(Boolean).join('\r\n')
|
|
193
|
+
try {
|
|
194
|
+
writeFileSync(script, body + '\r\n', 'utf8')
|
|
195
|
+
const child = spawn('cmd.exe', ['/c', 'start', '', script], {
|
|
196
|
+
detached: true,
|
|
197
|
+
stdio: 'ignore',
|
|
198
|
+
})
|
|
199
|
+
// spawn reports failure asynchronously; without a listener that becomes an
|
|
200
|
+
// unhandled "error" event and takes the host down.
|
|
201
|
+
child.on('error', () => {})
|
|
202
|
+
child.unref()
|
|
203
|
+
return { ok: true }
|
|
204
|
+
} catch (error) {
|
|
205
|
+
return { ok: false, reason: String(error?.message ?? error) }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
102
209
|
function sendJson(response, status, body) {
|
|
103
210
|
const payload = JSON.stringify(body)
|
|
104
211
|
response.writeHead(status, {
|
|
@@ -127,12 +234,96 @@ export function mountBoardRoute(ctx) {
|
|
|
127
234
|
kind: 'prefix',
|
|
128
235
|
path: ROUTE,
|
|
129
236
|
async handler(request, response) {
|
|
237
|
+
if (!allowed(request)) {
|
|
238
|
+
sendJson(response, 403, { error: 'request rejected by the host admission fence' })
|
|
239
|
+
return
|
|
240
|
+
}
|
|
130
241
|
const url = new URL(request.url ?? '/', 'http://local')
|
|
131
242
|
if (url.pathname === `${ROUTE}/discover`) {
|
|
132
243
|
const result = await discovery(url.searchParams.get('refresh') === '1')
|
|
133
244
|
sendJson(response, 200, result ?? { error: 'discovery unavailable' })
|
|
134
245
|
return
|
|
135
246
|
}
|
|
247
|
+
if (url.pathname === `${ROUTE}/detail`) {
|
|
248
|
+
const tool = url.searchParams.get('tool') ?? ''
|
|
249
|
+
if (tool !== 'dsh') {
|
|
250
|
+
// Not an error: most sources simply do not record tool calls.
|
|
251
|
+
sendJson(response, 200, {
|
|
252
|
+
supported: false,
|
|
253
|
+
reason: '该工具不记录工具调用,抽屉暂无内容',
|
|
254
|
+
})
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
const file = dshSessionFile(url.searchParams.get('id'))
|
|
258
|
+
if (!file || !existsSync(file)) {
|
|
259
|
+
sendJson(response, 404, { supported: false, reason: 'not found' })
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
const mtime = statSync(file).mtimeMs
|
|
264
|
+
const cached = detailCache.get(file)
|
|
265
|
+
if (cached && cached.mtime === mtime && Date.now() - cached.at < DETAIL_TTL_MS) {
|
|
266
|
+
sendJson(response, 200, cached.value)
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
const value = readDshDetail(file)
|
|
270
|
+
detailCache.set(file, { mtime, at: Date.now(), value })
|
|
271
|
+
sendJson(response, 200, value)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
sendJson(response, 500, { supported: false, reason: String(error?.message ?? error) })
|
|
274
|
+
}
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
if (url.pathname === `${ROUTE}/windows`) {
|
|
278
|
+
// Which windows a click would be able to reach, so a mismatch can be
|
|
279
|
+
// diagnosed without reading the code.
|
|
280
|
+
sendJson(response, 200, { windows: listWindows(), matchers: WINDOW_MATCHERS })
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
if (url.pathname === `${ROUTE}/open`) {
|
|
284
|
+
if (request.method !== 'POST') {
|
|
285
|
+
sendJson(response, 405, { error: 'POST only' })
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
let body
|
|
289
|
+
try {
|
|
290
|
+
body = await readJsonBody(request)
|
|
291
|
+
} catch (error) {
|
|
292
|
+
sendJson(response, 400, { ok: false, reason: String(error?.message ?? error) })
|
|
293
|
+
return
|
|
294
|
+
}
|
|
295
|
+
// 1. An already-running window of that tool is the intended target:
|
|
296
|
+
// focusing it does not start a second client on a live session.
|
|
297
|
+
const matcher = WINDOW_MATCHERS[String(body.tool ?? '')]
|
|
298
|
+
let focusAttempt = null
|
|
299
|
+
if (matcher) {
|
|
300
|
+
const focused = focusWindow(matcher)
|
|
301
|
+
if (focused.ok) {
|
|
302
|
+
sendJson(response, 200, { ok: true, focused: true, title: focused.title, proc: focused.proc })
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
// Carried into the refusal so "no window" and "found but Windows would
|
|
306
|
+
// not raise it" are distinguishable without reading logs.
|
|
307
|
+
focusAttempt = focused.reason ?? focused
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// 2. No window found: a tool with a verified resume command gets a
|
|
311
|
+
// terminal of its own. 3. Anything else is refused, and the client
|
|
312
|
+
// falls back to copying the workspace path.
|
|
313
|
+
const plan = planOpen(body)
|
|
314
|
+
if (!plan.ok) {
|
|
315
|
+
const reason = plan.reason === 'no-opener' ? 'no-opener' : plan.reason
|
|
316
|
+
sendJson(response, plan.reason === 'no-opener' ? 501 : 400, {
|
|
317
|
+
ok: false,
|
|
318
|
+
reason,
|
|
319
|
+
focus: focusAttempt,
|
|
320
|
+
})
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
const opened = spawnPlan(plan)
|
|
324
|
+
sendJson(response, opened.ok ? 200 : 501, opened)
|
|
325
|
+
return
|
|
326
|
+
}
|
|
136
327
|
if (url.pathname !== `${ROUTE}/data`) {
|
|
137
328
|
sendJson(response, 404, { error: 'not found' })
|
|
138
329
|
return
|
|
@@ -150,6 +341,15 @@ export function mountBoardRoute(ctx) {
|
|
|
150
341
|
specId: app.spec,
|
|
151
342
|
}))
|
|
152
343
|
const board = await collectBoard(extra)
|
|
344
|
+
// Which rows a click can actually open, decided here so the browser does
|
|
345
|
+
// not keep its own copy of the opener table.
|
|
346
|
+
for (const item of board.items) {
|
|
347
|
+
const focusable = Boolean(WINDOW_MATCHERS[item.tool])
|
|
348
|
+
const opener = openerLabel(item.tool)
|
|
349
|
+
// Clicking tries the window first, so that is what the label says.
|
|
350
|
+
if (focusable) item.openLabel = `切到 ${item.tool} 窗口`
|
|
351
|
+
else if (opener && item.openId) item.openLabel = opener
|
|
352
|
+
}
|
|
153
353
|
board.discovery = discoverySummary()
|
|
154
354
|
sendJson(response, 200, board)
|
|
155
355
|
} catch (error) {
|
|
@@ -161,6 +361,10 @@ export function mountBoardRoute(ctx) {
|
|
|
161
361
|
|
|
162
362
|
/** Cordis plugin body. */
|
|
163
363
|
export function apply(ctx) {
|
|
364
|
+
ctx.inject(['connection'], (connCtx) => {
|
|
365
|
+
connection = connCtx.connection
|
|
366
|
+
})
|
|
367
|
+
|
|
164
368
|
ctx.inject(['webServer'], (webCtx) => {
|
|
165
369
|
webCtx.effect(() => mountBoardRoute(webCtx), 'dsh-atc: board route')
|
|
166
370
|
// One background walk per process, well after startup.
|