dsh-notify-tray 0.1.11 → 0.1.13
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.en.md +9 -9
- package/README.md +9 -9
- package/README.zh-CN.md +9 -9
- package/assets/mascot-peeking.prompt.txt +6 -6
- package/assets/notify-icon.png +0 -0
- package/assets/tray-darwin.js +283 -283
- package/cordis.patch.yml +6 -6
- package/lib/ToastActivator.cs +33 -0
- package/lib/catalog.js +448 -448
- package/lib/client.js +65 -132
- package/lib/format.js +284 -284
- package/lib/host/context.js +11 -3
- package/lib/host/notify.js +26 -21
- package/lib/host/routes.js +9 -42
- package/lib/host/spend.js +190 -190
- package/lib/host/tray.js +120 -120
- package/lib/icon.js +159 -159
- package/lib/index.js +2 -7
- package/lib/ledger.js +285 -285
- package/lib/models-dev.json +2684 -2684
- package/lib/notices.js +3 -4
- package/lib/pricing.js +302 -302
- package/lib/quota.js +290 -290
- package/lib/system.js +11 -22
- package/lib/tracker.js +250 -250
- package/lib/tray/index.js +142 -142
- package/lib/tray/linux.js +393 -393
- package/lib/voice.js +76 -76
- package/lib/whale.js +396 -396
- package/lib/windows-toast.js +92 -0
- package/locale/en.json +7 -7
- package/locale/zh.json +7 -7
- package/package.json +2 -1
package/lib/system.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Host-side OS integration: native notifications
|
|
3
|
-
* when no DSH window is listening) and bringing the DSH window forward.
|
|
2
|
+
* Host-side OS integration: native system notifications and bringing the DSH window forward.
|
|
4
3
|
*/
|
|
4
|
+
import { registerWindowsSender, WINDOWS_SENDER, issueWindowsClick } from './windows-toast.js'
|
|
5
5
|
import { spawn } from 'node:child_process'
|
|
6
6
|
import { createHash } from 'node:crypto'
|
|
7
7
|
import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs'
|
|
@@ -43,12 +43,7 @@ export function desktopHosted() {
|
|
|
43
43
|
return Boolean(process.versions.electron && process.env.ELECTRON_RUN_AS_NODE)
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
/**
|
|
47
|
-
* Windows 10/11 toast XML. The desktop app registers the `dsh://` protocol,
|
|
48
|
-
* so a protocol-activated toast brings its window forward without any process
|
|
49
|
-
* of ours staying alive to listen for the click; without the desktop app the
|
|
50
|
-
* launch target is the web GUI's URL (or nothing).
|
|
51
|
-
*/
|
|
46
|
+
/** Windows delivers activation via the plugin protocol even after the sender exits. */
|
|
52
47
|
export function toastXml({ title, body, launch, sound = true }) {
|
|
53
48
|
const activation = launch ? ` activationType="protocol" launch="${xmlEscape(launch)}"` : ''
|
|
54
49
|
const audio = sound ? '<audio src="ms-winsoundevent:Notification.Default"/>' : '<audio silent="true"/>'
|
|
@@ -56,13 +51,6 @@ export function toastXml({ title, body, launch, sound = true }) {
|
|
|
56
51
|
+ `<text>${xmlEscape(title)}</text><text>${xmlEscape(body)}</text></binding></visual>${audio}</toast>`
|
|
57
52
|
}
|
|
58
53
|
|
|
59
|
-
/**
|
|
60
|
-
* Every Windows 10/11 install registers this AppUserModelID for the Start
|
|
61
|
-
* menu's "Windows PowerShell" shortcut, so toasts sent under it always show;
|
|
62
|
-
* the desktop app's own id is not registered in a way a helper could reuse.
|
|
63
|
-
*/
|
|
64
|
-
const POWERSHELL_AUMID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
|
|
65
|
-
|
|
66
54
|
/** Toast group every notification of this plugin is filed under. */
|
|
67
55
|
const TOAST_GROUP = 'dsh-notify-tray'
|
|
68
56
|
|
|
@@ -76,6 +64,7 @@ export function toastTag(key) {
|
|
|
76
64
|
|
|
77
65
|
function runPowerShell(lines) {
|
|
78
66
|
const script = [
|
|
67
|
+
"$ErrorActionPreference='Stop'",
|
|
79
68
|
`$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]`,
|
|
80
69
|
...lines,
|
|
81
70
|
].join('; ')
|
|
@@ -94,8 +83,9 @@ function windowsToast(xml, key) {
|
|
|
94
83
|
`$doc = New-Object Windows.Data.Xml.Dom.XmlDocument`,
|
|
95
84
|
`$doc.LoadXml(${ps(xml)})`,
|
|
96
85
|
`$toast = New-Object Windows.UI.Notifications.ToastNotification $doc`,
|
|
86
|
+
'$toast.ExpirationTime = [DateTimeOffset]::Now.AddDays(7)',
|
|
97
87
|
...(key !== undefined ? [`$toast.Tag = ${ps(toastTag(key))}`, `$toast.Group = ${ps(TOAST_GROUP)}`] : []),
|
|
98
|
-
`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${ps(
|
|
88
|
+
`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${ps(WINDOWS_SENDER)}).Show($toast)`,
|
|
99
89
|
])
|
|
100
90
|
}
|
|
101
91
|
|
|
@@ -169,11 +159,10 @@ export async function systemNotify(n) {
|
|
|
169
159
|
return run('/usr/bin/osascript', ['-e', `display notification ${as(n.body)} with title ${as(n.title)}${sound}`])
|
|
170
160
|
}
|
|
171
161
|
if (process.platform === 'win32') {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return windowsToast(toastXml({ title: n.title, body: n.body, launch, sound: n.sound !== false }), n.key)
|
|
162
|
+
await registerWindowsSender(run, powershell())
|
|
163
|
+
const target = desktopHosted() ? 'dsh://open' : safeOrigin(n.webOrigin)
|
|
164
|
+
const click = n.storageDir && issueWindowsClick(n.storageDir, n.sessionId, target)
|
|
165
|
+
return windowsToast(toastXml({ title: n.title, body: n.body, launch: click ? 'dsh-notify-tray://click/' + click : target, sound: n.sound !== false }), n.key)
|
|
177
166
|
}
|
|
178
167
|
// Linux / BSD: D-Bus first (clickable), notify-send as a fallback.
|
|
179
168
|
try {
|
|
@@ -202,7 +191,7 @@ export async function systemWithdraw(key) {
|
|
|
202
191
|
}
|
|
203
192
|
if (process.platform === 'win32') {
|
|
204
193
|
return runPowerShell([
|
|
205
|
-
`[Windows.UI.Notifications.ToastNotificationManager]::History.Remove(${ps(toastTag(key))}, ${ps(TOAST_GROUP)}, ${ps(
|
|
194
|
+
`[Windows.UI.Notifications.ToastNotificationManager]::History.Remove(${ps(toastTag(key))}, ${ps(TOAST_GROUP)}, ${ps(WINDOWS_SENDER)})`,
|
|
206
195
|
])
|
|
207
196
|
}
|
|
208
197
|
try {
|
package/lib/tracker.js
CHANGED
|
@@ -1,250 +1,250 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Session state tracker: folds `agent/status` and `session/event` into the
|
|
3
|
-
* per-session facts the tray shows (running / waiting for you / last result)
|
|
4
|
-
* and emits one notification event per user-relevant transition.
|
|
5
|
-
*
|
|
6
|
-
* Pure logic, no DSH imports, so it is unit-testable with plain objects.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/** Question tool name used by dsh-tool-ask-user. */
|
|
10
|
-
const ASK_TOOL = 'ask_user_question'
|
|
11
|
-
/** Notification events kept for clients that poll late. */
|
|
12
|
-
const EVENT_BUFFER = 50
|
|
13
|
-
/** Body excerpt cap so system notifications stay compact. */
|
|
14
|
-
const BODY_MAX = 90
|
|
15
|
-
|
|
16
|
-
export function clip(text, max = BODY_MAX) {
|
|
17
|
-
const flat = String(text ?? '').replace(/\s+/gu, ' ').trim()
|
|
18
|
-
return flat.length > max ? `${flat.slice(0, max)}…` : flat
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function localDate(time = Date.now()) {
|
|
22
|
-
const d = new Date(time)
|
|
23
|
-
const pad = n => String(n).padStart(2, '0')
|
|
24
|
-
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** True for top-level sessions; subagent children never notify on their own. */
|
|
28
|
-
export function isTopLevel(session) {
|
|
29
|
-
const header = session?.header
|
|
30
|
-
if (header === undefined) return true
|
|
31
|
-
return !(header.delegationDepth > 0) && header.origin !== 'subagent'
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Classify an ask_user_question call: any question offering options (or a
|
|
36
|
-
* plan review) needs a choice; free-text questions need input.
|
|
37
|
-
*/
|
|
38
|
-
export function classifyQuestion(argumentsJson) {
|
|
39
|
-
let questions = []
|
|
40
|
-
try {
|
|
41
|
-
questions = JSON.parse(argumentsJson)?.questions ?? []
|
|
42
|
-
} catch {
|
|
43
|
-
return { kind: 'input', text: '' }
|
|
44
|
-
}
|
|
45
|
-
const first = questions[0] ?? {}
|
|
46
|
-
const text = first.header ? `${first.header}:${first.question ?? ''}` : (first.question ?? '')
|
|
47
|
-
if (questions.some(q => q?.intent?.kind === 'plan-review')) return { kind: 'choice', text: text || '计划待确认' }
|
|
48
|
-
if (questions.some(q => Array.isArray(q?.options) && q.options.length > 0)) return { kind: 'choice', text }
|
|
49
|
-
return { kind: 'input', text }
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** Map a TurnEndReason onto the outcome the user cares about, or undefined to stay silent. */
|
|
53
|
-
export function outcomeOf(reason) {
|
|
54
|
-
switch (reason?.kind) {
|
|
55
|
-
case 'completed': return { kind: 'completed' }
|
|
56
|
-
case 'error': return { kind: 'failed', detail: reason.error?.message ?? '' }
|
|
57
|
-
case 'max-tokens': return { kind: 'failed', detail: '输出达到长度上限' }
|
|
58
|
-
case 'blocked': return { kind: 'failed', detail: '被拦截' }
|
|
59
|
-
case 'aborted': return { kind: 'aborted' }
|
|
60
|
-
default: return undefined // forked / interrupted (crash marker) / unknown
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export class Tracker {
|
|
65
|
-
constructor({ now = () => Date.now() } = {}) {
|
|
66
|
-
this.now = now
|
|
67
|
-
/** @type {Map<string, any>} */
|
|
68
|
-
this.sessions = new Map()
|
|
69
|
-
this.day = { date: localDate(now()), completed: 0, failed: 0, aborted: 0 }
|
|
70
|
-
this.events = []
|
|
71
|
-
this.seq = 0
|
|
72
|
-
this.listeners = new Set()
|
|
73
|
-
this.changeListeners = new Set()
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
onEvent(listener) {
|
|
77
|
-
this.listeners.add(listener)
|
|
78
|
-
return () => this.listeners.delete(listener)
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
onChange(listener) {
|
|
82
|
-
this.changeListeners.add(listener)
|
|
83
|
-
return () => this.changeListeners.delete(listener)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
entry(id, session) {
|
|
87
|
-
let entry = this.sessions.get(id)
|
|
88
|
-
if (entry === undefined) {
|
|
89
|
-
const cwd = session?.header?.cwd
|
|
90
|
-
entry = {
|
|
91
|
-
id,
|
|
92
|
-
title: undefined,
|
|
93
|
-
cwd,
|
|
94
|
-
running: false,
|
|
95
|
-
/** When the current run started (for "已运行 n 分钟"). */
|
|
96
|
-
since: undefined,
|
|
97
|
-
/** Last tool the running agent called (what it is doing right now). */
|
|
98
|
-
tool: undefined,
|
|
99
|
-
pending: new Map(),
|
|
100
|
-
last: undefined,
|
|
101
|
-
updatedAt: this.now(),
|
|
102
|
-
}
|
|
103
|
-
this.sessions.set(id, entry)
|
|
104
|
-
}
|
|
105
|
-
return entry
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
labelOf(entry) {
|
|
109
|
-
if (entry.title) return entry.title
|
|
110
|
-
if (entry.cwd) return entry.cwd.split(/[\\/]/u).filter(Boolean).pop() ?? entry.cwd
|
|
111
|
-
return '会话'
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
rollDay() {
|
|
115
|
-
const today = localDate(this.now())
|
|
116
|
-
if (this.day.date !== today) this.day = { date: today, completed: 0, failed: 0, aborted: 0 }
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
emit(type, entry, body) {
|
|
120
|
-
const event = { seq: ++this.seq, type, sessionId: entry.id, title: this.labelOf(entry), body: clip(body), at: this.now() }
|
|
121
|
-
this.events.push(event)
|
|
122
|
-
if (this.events.length > EVENT_BUFFER) this.events.shift()
|
|
123
|
-
for (const listener of this.listeners) listener(event)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
changed() {
|
|
127
|
-
for (const listener of this.changeListeners) listener()
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Seed from agents already alive when the plugin starts. */
|
|
131
|
-
seed(agents) {
|
|
132
|
-
for (const agent of agents) {
|
|
133
|
-
if (!isTopLevel(agent.session)) continue
|
|
134
|
-
const entry = this.entry(agent.id, agent.session)
|
|
135
|
-
entry.running = agent.status === 'running'
|
|
136
|
-
if (entry.running) entry.since = this.now()
|
|
137
|
-
}
|
|
138
|
-
this.changed()
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
agentStatus(agent, status) {
|
|
142
|
-
if (!isTopLevel(agent.session)) return
|
|
143
|
-
const entry = this.entry(agent.id, agent.session)
|
|
144
|
-
const running = status === 'running'
|
|
145
|
-
if (running && !entry.running) entry.since = this.now()
|
|
146
|
-
entry.running = running
|
|
147
|
-
entry.updatedAt = this.now()
|
|
148
|
-
// An idle agent is waiting on nothing the tray should still count.
|
|
149
|
-
if (!entry.running) {
|
|
150
|
-
entry.pending.clear()
|
|
151
|
-
entry.tool = undefined
|
|
152
|
-
}
|
|
153
|
-
this.changed()
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
agentDisposed(agent) {
|
|
157
|
-
if (this.sessions.delete(agent.id)) this.changed()
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
sessionEvent(session, event) {
|
|
161
|
-
if (!isTopLevel(session)) return
|
|
162
|
-
const entry = this.entry(session.id, session)
|
|
163
|
-
const data = event.data ?? {}
|
|
164
|
-
switch (event.type) {
|
|
165
|
-
case 'session/title':
|
|
166
|
-
entry.title = data.title
|
|
167
|
-
return
|
|
168
|
-
case 'approval/asked': {
|
|
169
|
-
const body = data.reason || `工具 ${data.toolName} 需要你批准`
|
|
170
|
-
entry.pending.set(`approval:${data.id}`, { kind: 'approval', text: body, since: this.now(), callId: data.callId })
|
|
171
|
-
this.emit('approval', entry, body)
|
|
172
|
-
break
|
|
173
|
-
}
|
|
174
|
-
case 'approval/decided':
|
|
175
|
-
entry.pending.delete(`approval:${data.id}`)
|
|
176
|
-
break
|
|
177
|
-
case 'tool/call': {
|
|
178
|
-
entry.tool = data.name
|
|
179
|
-
if (data.name !== ASK_TOOL) break
|
|
180
|
-
const { kind, text } = classifyQuestion(data.arguments)
|
|
181
|
-
entry.pending.set(`question:${data.callId}`, { kind, text, since: this.now() })
|
|
182
|
-
this.emit(kind, entry, text)
|
|
183
|
-
break
|
|
184
|
-
}
|
|
185
|
-
case 'tool/result': {
|
|
186
|
-
// ToolResultMessage names the call it answers `toolCallId` (mirrored in `source.callId`).
|
|
187
|
-
const callId = data.message?.toolCallId ?? data.message?.source?.callId
|
|
188
|
-
if (callId === undefined) return
|
|
189
|
-
let cleared = entry.pending.delete(`question:${callId}`)
|
|
190
|
-
// An approval for this call is settled once the call has a result, even if `approval/decided` was missed.
|
|
191
|
-
for (const [key, wait] of entry.pending) {
|
|
192
|
-
if (wait.callId === callId) cleared = entry.pending.delete(key) || cleared
|
|
193
|
-
}
|
|
194
|
-
if (!cleared) return
|
|
195
|
-
break
|
|
196
|
-
}
|
|
197
|
-
case 'turn/end': {
|
|
198
|
-
const outcome = outcomeOf(data.reason)
|
|
199
|
-
entry.pending.clear()
|
|
200
|
-
entry.tool = undefined
|
|
201
|
-
if (outcome === undefined) break
|
|
202
|
-
this.rollDay()
|
|
203
|
-
this.day[outcome.kind] += 1
|
|
204
|
-
entry.last = { kind: outcome.kind, at: this.now(), detail: outcome.detail }
|
|
205
|
-
if (outcome.kind === 'completed') this.emit('completed', entry, '任务已完成')
|
|
206
|
-
else if (outcome.kind === 'failed') this.emit('failed', entry, outcome.detail || '任务失败')
|
|
207
|
-
break
|
|
208
|
-
}
|
|
209
|
-
default:
|
|
210
|
-
return
|
|
211
|
-
}
|
|
212
|
-
entry.updatedAt = this.now()
|
|
213
|
-
this.changed()
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** Aggregate view used by the tray and the client. */
|
|
217
|
-
summary() {
|
|
218
|
-
this.rollDay()
|
|
219
|
-
let running = 0
|
|
220
|
-
const waiting = []
|
|
221
|
-
for (const entry of this.sessions.values()) {
|
|
222
|
-
if (entry.running) running += 1
|
|
223
|
-
for (const wait of entry.pending.values()) {
|
|
224
|
-
waiting.push({ sessionId: entry.id, title: this.labelOf(entry), kind: wait.kind, text: clip(wait.text, 60), since: wait.since })
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
waiting.sort((a, b) => a.since - b.since)
|
|
228
|
-
const recent = [...this.sessions.values()]
|
|
229
|
-
.filter(entry => entry.last !== undefined)
|
|
230
|
-
.sort((a, b) => b.last.at - a.last.at)
|
|
231
|
-
.slice(0, 5)
|
|
232
|
-
.map(entry => ({ sessionId: entry.id, title: this.labelOf(entry), kind: entry.last.kind, at: entry.last.at }))
|
|
233
|
-
const runningList = [...this.sessions.values()]
|
|
234
|
-
.filter(entry => entry.running)
|
|
235
|
-
.sort((a, b) => (a.since ?? 0) - (b.since ?? 0))
|
|
236
|
-
.map(entry => ({ sessionId: entry.id, title: this.labelOf(entry), since: entry.since, tool: entry.tool }))
|
|
237
|
-
return { running, runningList, waiting, recent, today: { ...this.day } }
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** Ids of the sessions that wait on the user right now. */
|
|
241
|
-
waitingSessions() {
|
|
242
|
-
const ids = new Set()
|
|
243
|
-
for (const entry of this.sessions.values()) if (entry.pending.size > 0) ids.add(entry.id)
|
|
244
|
-
return ids
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
eventsAfter(seq) {
|
|
248
|
-
return this.events.filter(event => event.seq > seq)
|
|
249
|
-
}
|
|
250
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Session state tracker: folds `agent/status` and `session/event` into the
|
|
3
|
+
* per-session facts the tray shows (running / waiting for you / last result)
|
|
4
|
+
* and emits one notification event per user-relevant transition.
|
|
5
|
+
*
|
|
6
|
+
* Pure logic, no DSH imports, so it is unit-testable with plain objects.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Question tool name used by dsh-tool-ask-user. */
|
|
10
|
+
const ASK_TOOL = 'ask_user_question'
|
|
11
|
+
/** Notification events kept for clients that poll late. */
|
|
12
|
+
const EVENT_BUFFER = 50
|
|
13
|
+
/** Body excerpt cap so system notifications stay compact. */
|
|
14
|
+
const BODY_MAX = 90
|
|
15
|
+
|
|
16
|
+
export function clip(text, max = BODY_MAX) {
|
|
17
|
+
const flat = String(text ?? '').replace(/\s+/gu, ' ').trim()
|
|
18
|
+
return flat.length > max ? `${flat.slice(0, max)}…` : flat
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function localDate(time = Date.now()) {
|
|
22
|
+
const d = new Date(time)
|
|
23
|
+
const pad = n => String(n).padStart(2, '0')
|
|
24
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** True for top-level sessions; subagent children never notify on their own. */
|
|
28
|
+
export function isTopLevel(session) {
|
|
29
|
+
const header = session?.header
|
|
30
|
+
if (header === undefined) return true
|
|
31
|
+
return !(header.delegationDepth > 0) && header.origin !== 'subagent'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Classify an ask_user_question call: any question offering options (or a
|
|
36
|
+
* plan review) needs a choice; free-text questions need input.
|
|
37
|
+
*/
|
|
38
|
+
export function classifyQuestion(argumentsJson) {
|
|
39
|
+
let questions = []
|
|
40
|
+
try {
|
|
41
|
+
questions = JSON.parse(argumentsJson)?.questions ?? []
|
|
42
|
+
} catch {
|
|
43
|
+
return { kind: 'input', text: '' }
|
|
44
|
+
}
|
|
45
|
+
const first = questions[0] ?? {}
|
|
46
|
+
const text = first.header ? `${first.header}:${first.question ?? ''}` : (first.question ?? '')
|
|
47
|
+
if (questions.some(q => q?.intent?.kind === 'plan-review')) return { kind: 'choice', text: text || '计划待确认' }
|
|
48
|
+
if (questions.some(q => Array.isArray(q?.options) && q.options.length > 0)) return { kind: 'choice', text }
|
|
49
|
+
return { kind: 'input', text }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Map a TurnEndReason onto the outcome the user cares about, or undefined to stay silent. */
|
|
53
|
+
export function outcomeOf(reason) {
|
|
54
|
+
switch (reason?.kind) {
|
|
55
|
+
case 'completed': return { kind: 'completed' }
|
|
56
|
+
case 'error': return { kind: 'failed', detail: reason.error?.message ?? '' }
|
|
57
|
+
case 'max-tokens': return { kind: 'failed', detail: '输出达到长度上限' }
|
|
58
|
+
case 'blocked': return { kind: 'failed', detail: '被拦截' }
|
|
59
|
+
case 'aborted': return { kind: 'aborted' }
|
|
60
|
+
default: return undefined // forked / interrupted (crash marker) / unknown
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class Tracker {
|
|
65
|
+
constructor({ now = () => Date.now() } = {}) {
|
|
66
|
+
this.now = now
|
|
67
|
+
/** @type {Map<string, any>} */
|
|
68
|
+
this.sessions = new Map()
|
|
69
|
+
this.day = { date: localDate(now()), completed: 0, failed: 0, aborted: 0 }
|
|
70
|
+
this.events = []
|
|
71
|
+
this.seq = 0
|
|
72
|
+
this.listeners = new Set()
|
|
73
|
+
this.changeListeners = new Set()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
onEvent(listener) {
|
|
77
|
+
this.listeners.add(listener)
|
|
78
|
+
return () => this.listeners.delete(listener)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
onChange(listener) {
|
|
82
|
+
this.changeListeners.add(listener)
|
|
83
|
+
return () => this.changeListeners.delete(listener)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
entry(id, session) {
|
|
87
|
+
let entry = this.sessions.get(id)
|
|
88
|
+
if (entry === undefined) {
|
|
89
|
+
const cwd = session?.header?.cwd
|
|
90
|
+
entry = {
|
|
91
|
+
id,
|
|
92
|
+
title: undefined,
|
|
93
|
+
cwd,
|
|
94
|
+
running: false,
|
|
95
|
+
/** When the current run started (for "已运行 n 分钟"). */
|
|
96
|
+
since: undefined,
|
|
97
|
+
/** Last tool the running agent called (what it is doing right now). */
|
|
98
|
+
tool: undefined,
|
|
99
|
+
pending: new Map(),
|
|
100
|
+
last: undefined,
|
|
101
|
+
updatedAt: this.now(),
|
|
102
|
+
}
|
|
103
|
+
this.sessions.set(id, entry)
|
|
104
|
+
}
|
|
105
|
+
return entry
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
labelOf(entry) {
|
|
109
|
+
if (entry.title) return entry.title
|
|
110
|
+
if (entry.cwd) return entry.cwd.split(/[\\/]/u).filter(Boolean).pop() ?? entry.cwd
|
|
111
|
+
return '会话'
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
rollDay() {
|
|
115
|
+
const today = localDate(this.now())
|
|
116
|
+
if (this.day.date !== today) this.day = { date: today, completed: 0, failed: 0, aborted: 0 }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
emit(type, entry, body) {
|
|
120
|
+
const event = { seq: ++this.seq, type, sessionId: entry.id, title: this.labelOf(entry), body: clip(body), at: this.now() }
|
|
121
|
+
this.events.push(event)
|
|
122
|
+
if (this.events.length > EVENT_BUFFER) this.events.shift()
|
|
123
|
+
for (const listener of this.listeners) listener(event)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
changed() {
|
|
127
|
+
for (const listener of this.changeListeners) listener()
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Seed from agents already alive when the plugin starts. */
|
|
131
|
+
seed(agents) {
|
|
132
|
+
for (const agent of agents) {
|
|
133
|
+
if (!isTopLevel(agent.session)) continue
|
|
134
|
+
const entry = this.entry(agent.id, agent.session)
|
|
135
|
+
entry.running = agent.status === 'running'
|
|
136
|
+
if (entry.running) entry.since = this.now()
|
|
137
|
+
}
|
|
138
|
+
this.changed()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
agentStatus(agent, status) {
|
|
142
|
+
if (!isTopLevel(agent.session)) return
|
|
143
|
+
const entry = this.entry(agent.id, agent.session)
|
|
144
|
+
const running = status === 'running'
|
|
145
|
+
if (running && !entry.running) entry.since = this.now()
|
|
146
|
+
entry.running = running
|
|
147
|
+
entry.updatedAt = this.now()
|
|
148
|
+
// An idle agent is waiting on nothing the tray should still count.
|
|
149
|
+
if (!entry.running) {
|
|
150
|
+
entry.pending.clear()
|
|
151
|
+
entry.tool = undefined
|
|
152
|
+
}
|
|
153
|
+
this.changed()
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
agentDisposed(agent) {
|
|
157
|
+
if (this.sessions.delete(agent.id)) this.changed()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
sessionEvent(session, event) {
|
|
161
|
+
if (!isTopLevel(session)) return
|
|
162
|
+
const entry = this.entry(session.id, session)
|
|
163
|
+
const data = event.data ?? {}
|
|
164
|
+
switch (event.type) {
|
|
165
|
+
case 'session/title':
|
|
166
|
+
entry.title = data.title
|
|
167
|
+
return
|
|
168
|
+
case 'approval/asked': {
|
|
169
|
+
const body = data.reason || `工具 ${data.toolName} 需要你批准`
|
|
170
|
+
entry.pending.set(`approval:${data.id}`, { kind: 'approval', text: body, since: this.now(), callId: data.callId })
|
|
171
|
+
this.emit('approval', entry, body)
|
|
172
|
+
break
|
|
173
|
+
}
|
|
174
|
+
case 'approval/decided':
|
|
175
|
+
entry.pending.delete(`approval:${data.id}`)
|
|
176
|
+
break
|
|
177
|
+
case 'tool/call': {
|
|
178
|
+
entry.tool = data.name
|
|
179
|
+
if (data.name !== ASK_TOOL) break
|
|
180
|
+
const { kind, text } = classifyQuestion(data.arguments)
|
|
181
|
+
entry.pending.set(`question:${data.callId}`, { kind, text, since: this.now() })
|
|
182
|
+
this.emit(kind, entry, text)
|
|
183
|
+
break
|
|
184
|
+
}
|
|
185
|
+
case 'tool/result': {
|
|
186
|
+
// ToolResultMessage names the call it answers `toolCallId` (mirrored in `source.callId`).
|
|
187
|
+
const callId = data.message?.toolCallId ?? data.message?.source?.callId
|
|
188
|
+
if (callId === undefined) return
|
|
189
|
+
let cleared = entry.pending.delete(`question:${callId}`)
|
|
190
|
+
// An approval for this call is settled once the call has a result, even if `approval/decided` was missed.
|
|
191
|
+
for (const [key, wait] of entry.pending) {
|
|
192
|
+
if (wait.callId === callId) cleared = entry.pending.delete(key) || cleared
|
|
193
|
+
}
|
|
194
|
+
if (!cleared) return
|
|
195
|
+
break
|
|
196
|
+
}
|
|
197
|
+
case 'turn/end': {
|
|
198
|
+
const outcome = outcomeOf(data.reason)
|
|
199
|
+
entry.pending.clear()
|
|
200
|
+
entry.tool = undefined
|
|
201
|
+
if (outcome === undefined) break
|
|
202
|
+
this.rollDay()
|
|
203
|
+
this.day[outcome.kind] += 1
|
|
204
|
+
entry.last = { kind: outcome.kind, at: this.now(), detail: outcome.detail }
|
|
205
|
+
if (outcome.kind === 'completed') this.emit('completed', entry, '任务已完成')
|
|
206
|
+
else if (outcome.kind === 'failed') this.emit('failed', entry, outcome.detail || '任务失败')
|
|
207
|
+
break
|
|
208
|
+
}
|
|
209
|
+
default:
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
entry.updatedAt = this.now()
|
|
213
|
+
this.changed()
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Aggregate view used by the tray and the client. */
|
|
217
|
+
summary() {
|
|
218
|
+
this.rollDay()
|
|
219
|
+
let running = 0
|
|
220
|
+
const waiting = []
|
|
221
|
+
for (const entry of this.sessions.values()) {
|
|
222
|
+
if (entry.running) running += 1
|
|
223
|
+
for (const wait of entry.pending.values()) {
|
|
224
|
+
waiting.push({ sessionId: entry.id, title: this.labelOf(entry), kind: wait.kind, text: clip(wait.text, 60), since: wait.since })
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
waiting.sort((a, b) => a.since - b.since)
|
|
228
|
+
const recent = [...this.sessions.values()]
|
|
229
|
+
.filter(entry => entry.last !== undefined)
|
|
230
|
+
.sort((a, b) => b.last.at - a.last.at)
|
|
231
|
+
.slice(0, 5)
|
|
232
|
+
.map(entry => ({ sessionId: entry.id, title: this.labelOf(entry), kind: entry.last.kind, at: entry.last.at }))
|
|
233
|
+
const runningList = [...this.sessions.values()]
|
|
234
|
+
.filter(entry => entry.running)
|
|
235
|
+
.sort((a, b) => (a.since ?? 0) - (b.since ?? 0))
|
|
236
|
+
.map(entry => ({ sessionId: entry.id, title: this.labelOf(entry), since: entry.since, tool: entry.tool }))
|
|
237
|
+
return { running, runningList, waiting, recent, today: { ...this.day } }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Ids of the sessions that wait on the user right now. */
|
|
241
|
+
waitingSessions() {
|
|
242
|
+
const ids = new Set()
|
|
243
|
+
for (const entry of this.sessions.values()) if (entry.pending.size > 0) ids.add(entry.id)
|
|
244
|
+
return ids
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
eventsAfter(seq) {
|
|
248
|
+
return this.events.filter(event => event.seq > seq)
|
|
249
|
+
}
|
|
250
|
+
}
|