dsh-agent-floor 0.0.0-stage → 0.2.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 +46 -2
- package/client.js +242 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +11 -0
- package/index.js +528 -0
- package/package.json +46 -4
- package/scripts/README.md +24 -0
- package/scripts/harness.js +254 -0
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Agent Floor · 常驻监控条
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
给 DeepSeek Harness 左下角挂一条**常驻监控条**:不用开标签页,随时能瞄一眼哪个会话在跑、跑到第几步、烧了多少 token、改了哪些文件。
|
|
4
|
+
|
|
5
|
+
DSH 自带的「任务管理」页已经能看到 agent 树和后台任务,但它是**按会话打开的标签页**,而且没有步/轮/token/改动文件这些指标。这个插件只补这块,不重复画树。
|
|
6
|
+
|
|
7
|
+
## 长什么样
|
|
8
|
+
|
|
9
|
+
- **收起**:`● 2 在跑 / 5 在岗`(有会话在跑时圆点呼吸)
|
|
10
|
+
- **点开**:每个会话一行 —— 状态点、名字(组长带 `带队 N`)、`第N步·第T轮 · 12.3k tok`、正在跑的 `bash · pnpm run build` 或 `改 client.js · index.js`
|
|
11
|
+
- 点任意一行 → 跳到那个会话
|
|
12
|
+
|
|
13
|
+
## 装
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
dsh plugin install dsh-agent-floor # npm,0.2.0+
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
或加市场索引源:`https://raw.githubusercontent.com/ITxuezhe/dsh-agent-floor/main/market/index.json`
|
|
20
|
+
|
|
21
|
+
装完刷新页面(⌘⇧R)。
|
|
22
|
+
|
|
23
|
+
## 数据从哪来
|
|
24
|
+
|
|
25
|
+
插件挂官方插槽 `shell.overlay`,客户端每 2 秒(收起时 6 秒)拉一次只读路由 `GET /dsh-agent-floor/state`。
|
|
26
|
+
Host 半监听会话事件折叠成快照,并按会话 cwd 跑 `git status --porcelain`(10 秒缓存、失败降级为空)拿真实改动文件。
|
|
27
|
+
|
|
28
|
+
- 状态:`running` 或 45 秒内有动静 → RUNNING;5 分钟内 → STANDBY;否则 IDLE
|
|
29
|
+
- 子代理靠 `parentSession` 归到组长名下,空闲超过 10 分钟自动淡出
|
|
30
|
+
- 展开/收起状态存在 localStorage `dsh.agent-floor.open`
|
|
31
|
+
|
|
32
|
+
## 自检
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
node scripts/harness.js # 桩宿主环境、真渲染一次,成功打印 render ok
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
详见 [scripts/README.md](scripts/README.md)。
|
|
39
|
+
|
|
40
|
+
## 皮肤与重载
|
|
41
|
+
|
|
42
|
+
- 颜色全部来自 `--dsw-*` 主题 token,深浅色皮肤自动跟随。
|
|
43
|
+
- 改完代码到插件设置里把开关切一次即可热重载,不用重启 DSH。
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
MIT
|
package/client.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'dsh-agent-floor',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const React = require('react');
|
|
5
|
+
const h = React.createElement;
|
|
6
|
+
const { useState, useEffect, useRef } = React;
|
|
7
|
+
|
|
8
|
+
const inject = ['slots'];
|
|
9
|
+
const ROUTE = '/dsh-agent-floor/state';
|
|
10
|
+
const OPEN_KEY = 'dsh.agent-floor.open';
|
|
11
|
+
const CHILD_TTL = 10 * 60 * 1000;
|
|
12
|
+
const MAX_ROWS = 8;
|
|
13
|
+
|
|
14
|
+
const CSS = `
|
|
15
|
+
.fg-root{position:fixed;left:14px;bottom:14px;z-index:60;pointer-events:auto;
|
|
16
|
+
font:12px/1.5 ui-sans-serif,-apple-system,"SF Pro Text","PingFang SC",system-ui,sans-serif;
|
|
17
|
+
color:var(--dsw-alias-label-primary,#1c1c1e);}
|
|
18
|
+
.fg-dock{min-width:196px;max-width:340px;border-radius:12px;overflow:hidden;
|
|
19
|
+
background:var(--dsw-alias-bg-overlay,#fff);
|
|
20
|
+
border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.09));
|
|
21
|
+
box-shadow:0 8px 28px rgba(0,0,0,.12);}
|
|
22
|
+
.fg-head{display:flex;align-items:center;gap:7px;padding:7px 10px;cursor:pointer;
|
|
23
|
+
user-select:none;-webkit-user-select:none;}
|
|
24
|
+
.fg-head:hover{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.03));}
|
|
25
|
+
.fg-pulse{width:7px;height:7px;border-radius:50%;flex:0 0 auto;
|
|
26
|
+
background:var(--dsw-alias-state-idle-primary,#9aa0a6);}
|
|
27
|
+
.fg-pulse.on{background:var(--dsw-alias-state-success-primary,#1a9b4e);
|
|
28
|
+
animation:fg-breathe 1.6s ease-in-out infinite;}
|
|
29
|
+
@keyframes fg-breathe{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.45;transform:scale(.82)}}
|
|
30
|
+
.fg-sum{font-weight:600;letter-spacing:.1px;white-space:nowrap;}
|
|
31
|
+
.fg-sum i{font-style:normal;font-weight:500;opacity:.55;}
|
|
32
|
+
.fg-caret{margin-left:auto;opacity:.45;font-size:11px;}
|
|
33
|
+
.fg-body{max-height:280px;overflow:auto;
|
|
34
|
+
border-top:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.07));}
|
|
35
|
+
.fg-row{display:grid;grid-template-columns:9px 1fr auto;gap:2px 7px;
|
|
36
|
+
padding:6px 10px;cursor:pointer;align-items:center;}
|
|
37
|
+
.fg-row:hover{background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.035));}
|
|
38
|
+
.fg-dot{width:7px;height:7px;border-radius:50%;
|
|
39
|
+
background:var(--dsw-alias-state-idle-primary,#c2c6cc);}
|
|
40
|
+
.fg-dot.run{background:var(--dsw-alias-state-success-primary,#1a9b4e);}
|
|
41
|
+
.fg-dot.wait{background:var(--dsw-alias-state-warn-primary,#e0a72e);}
|
|
42
|
+
.fg-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;}
|
|
43
|
+
.fg-name em{font-style:normal;font-weight:500;opacity:.5;font-size:11px;margin-left:5px;}
|
|
44
|
+
.fg-num{font-variant-numeric:tabular-nums;opacity:.6;white-space:nowrap;font-size:11px;}
|
|
45
|
+
.fg-file{grid-column:2 / 4;font-size:11px;opacity:.5;overflow:hidden;
|
|
46
|
+
text-overflow:ellipsis;white-space:nowrap;}
|
|
47
|
+
.fg-more{grid-column:1 / 4;padding:5px 10px;font-size:11px;opacity:.5;}
|
|
48
|
+
`;
|
|
49
|
+
|
|
50
|
+
function ensureStyle() {
|
|
51
|
+
if (typeof document === 'undefined' || !document.head) return;
|
|
52
|
+
if (document.getElementById('fg-style')) return;
|
|
53
|
+
const el = document.createElement('style');
|
|
54
|
+
el.id = 'fg-style';
|
|
55
|
+
el.textContent = CSS;
|
|
56
|
+
document.head.appendChild(el);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function num(n) {
|
|
60
|
+
if (!n) return '0';
|
|
61
|
+
if (n < 1000) return String(n);
|
|
62
|
+
if (n < 1e6) return (n / 1000).toFixed(n < 1e4 ? 1 : 0) + 'k';
|
|
63
|
+
return (n / 1e6).toFixed(1) + 'M';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function ago(t) {
|
|
67
|
+
if (!t) return '';
|
|
68
|
+
const s = Math.max(0, Math.round((Date.now() - t) / 1000));
|
|
69
|
+
if (s < 60) return s + '秒前';
|
|
70
|
+
if (s < 3600) return Math.round(s / 60) + '分钟前';
|
|
71
|
+
return Math.round(s / 3600) + '小时前';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function useFloor(open, initial) {
|
|
75
|
+
const [data, setData] = useState(() => initial || null);
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
let alive = true;
|
|
78
|
+
let timer = null;
|
|
79
|
+
const tick = () => {
|
|
80
|
+
Promise.resolve()
|
|
81
|
+
.then(() => fetch(ROUTE, { headers: { accept: 'application/json' } }))
|
|
82
|
+
.then((r) => (r && r.ok ? r.json() : null))
|
|
83
|
+
.then((d) => { if (alive && d) setData(d); })
|
|
84
|
+
.catch(() => {})
|
|
85
|
+
.then(() => { if (alive) timer = setTimeout(tick, open ? 2000 : 6000); });
|
|
86
|
+
};
|
|
87
|
+
tick();
|
|
88
|
+
return () => { alive = false; if (timer) clearTimeout(timer); };
|
|
89
|
+
}, [open]);
|
|
90
|
+
return data;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function deriveAgents(data) {
|
|
94
|
+
if (!data) return [];
|
|
95
|
+
const rows = Array.isArray(data.sessions) ? data.sessions : null;
|
|
96
|
+
const now = Date.now();
|
|
97
|
+
const list = rows ? rows.map((s) => ({
|
|
98
|
+
id: s.id,
|
|
99
|
+
name: s.title || s.cwd || s.id,
|
|
100
|
+
parent: s.parent || null,
|
|
101
|
+
status: s.running ? 'RUNNING' : (now - (s.updatedAt || 0) < 300000 ? 'STANDBY' : 'IDLE'),
|
|
102
|
+
step: s.step || 0,
|
|
103
|
+
turn: s.turn || 0,
|
|
104
|
+
tools: s.toolCalls || 0,
|
|
105
|
+
tokens: (s.tokensIn || 0) + (s.tokensOut || 0),
|
|
106
|
+
tool: s.lastTool || null,
|
|
107
|
+
forked: !!(data.focus && s.id === data.focus),
|
|
108
|
+
files: (Array.isArray(s.diffFiles) && s.diffFiles.length)
|
|
109
|
+
? s.diffFiles.slice(0, 4).map((f) => ({ name: String(f).split('/').pop(), write: true }))
|
|
110
|
+
: (Array.isArray(s.files) ? s.files : []),
|
|
111
|
+
updatedAt: s.updatedAt || 0,
|
|
112
|
+
})) : [];
|
|
113
|
+
|
|
114
|
+
const seen = new Map();
|
|
115
|
+
for (const a of list) seen.set((a.name || '').trim(), (seen.get((a.name || '').trim()) || 0) + 1);
|
|
116
|
+
for (const a of list) {
|
|
117
|
+
if (seen.get((a.name || '').trim()) > 1) {
|
|
118
|
+
a.name = a.name + ' · ' + String(a.id || '').slice(-4);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const live = list.filter((a) => {
|
|
123
|
+
if (!a.parent) return true;
|
|
124
|
+
if (a.status === 'RUNNING') return true;
|
|
125
|
+
return now - (a.updatedAt || 0) < CHILD_TTL;
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const rank = (a) => (a.status === 'RUNNING' ? 0 : a.status === 'STANDBY' ? 1 : 2);
|
|
129
|
+
const byId = new Map(live.map((a) => [a.id, a]));
|
|
130
|
+
const leaders = live.filter((a) => !a.parent || !byId.has(a.parent));
|
|
131
|
+
leaders.sort((x, y) => rank(x) - rank(y) || (y.updatedAt || 0) - (x.updatedAt || 0));
|
|
132
|
+
|
|
133
|
+
const out = [];
|
|
134
|
+
for (const lead of leaders) {
|
|
135
|
+
const kids = live.filter((a) => a.parent === lead.id);
|
|
136
|
+
kids.sort((x, y) => rank(x) - rank(y) || (y.updatedAt || 0) - (x.updatedAt || 0));
|
|
137
|
+
out.push({ ...lead, depth: 0, kids: kids.length });
|
|
138
|
+
for (const k of kids) out.push({ ...k, depth: 1, kids: 0 });
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function fileLine(a) {
|
|
144
|
+
const files = (a.files || []).slice(0, 3).map((f) => (f.write ? '改 ' : '') + f.name);
|
|
145
|
+
if (files.length) return files.join(' · ');
|
|
146
|
+
if (a.tool && a.tool.name) {
|
|
147
|
+
const target = String(a.tool.target || '').split('/').pop();
|
|
148
|
+
return a.tool.name + (target ? ' · ' + target : '');
|
|
149
|
+
}
|
|
150
|
+
return '';
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function MonitorRow(props) {
|
|
154
|
+
const a = props.agent;
|
|
155
|
+
const cls = 'fg-dot ' + (a.status === 'RUNNING' ? 'run' : a.status === 'STANDBY' ? 'wait' : '');
|
|
156
|
+
const shot = fileLine(a);
|
|
157
|
+
return h('div', { className: 'fg-row', onClick: () => props.onOpen(a) }, [
|
|
158
|
+
h('span', { className: cls, key: 'dot' }),
|
|
159
|
+
h('span', { className: 'fg-name', key: 'name' }, [
|
|
160
|
+
a.depth ? '↳ ' : '',
|
|
161
|
+
a.name || '未命名',
|
|
162
|
+
a.depth ? null : (a.kids ? h('em', { key: 'k' }, '带队 ' + a.kids) : null),
|
|
163
|
+
]),
|
|
164
|
+
h('span', { className: 'fg-num', key: 'num' },
|
|
165
|
+
'第' + a.step + '步·第' + a.turn + '轮 · ' + num(a.tokens) + ' tok'),
|
|
166
|
+
shot ? h('span', { className: 'fg-file', key: 'file' }, shot) : null,
|
|
167
|
+
]);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function MonitorBar(props) {
|
|
171
|
+
const ctx = (props && props.ctx) || null;
|
|
172
|
+
const [open, setOpen] = useState(() => {
|
|
173
|
+
try { return localStorage.getItem(OPEN_KEY) === '1'; } catch { return false; }
|
|
174
|
+
});
|
|
175
|
+
const data = useFloor(open, props && props.initialData);
|
|
176
|
+
const agents = deriveAgents(data);
|
|
177
|
+
const running = agents.filter((a) => a.status === 'RUNNING').length;
|
|
178
|
+
const shown = agents.slice(0, MAX_ROWS);
|
|
179
|
+
const hidden = agents.length - shown.length;
|
|
180
|
+
|
|
181
|
+
const toggle = () => {
|
|
182
|
+
const next = !open;
|
|
183
|
+
setOpen(next);
|
|
184
|
+
try { localStorage.setItem(OPEN_KEY, next ? '1' : '0'); } catch {}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
useEffect(() => { ensureStyle(); }, []);
|
|
188
|
+
|
|
189
|
+
const openSession = (a) => {
|
|
190
|
+
const id = a && a.id;
|
|
191
|
+
if (!id) return;
|
|
192
|
+
try {
|
|
193
|
+
const ui = ctx && typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null;
|
|
194
|
+
if (ui && typeof ui.openSession === 'function') { ui.openSession(id); return; }
|
|
195
|
+
const ses = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null;
|
|
196
|
+
if (ses && typeof ses.scope === 'function') ses.scope(id);
|
|
197
|
+
} catch {}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
return h('div', { className: 'fg-root' }, h('div', { className: 'fg-dock' }, [
|
|
201
|
+
h('div', { className: 'fg-head', key: 'head', onClick: toggle, title: open ? '收起监控条' : '展开监控条' }, [
|
|
202
|
+
h('span', { className: 'fg-pulse' + (running ? ' on' : ''), key: 'p' }),
|
|
203
|
+
h('span', { className: 'fg-sum', key: 's' }, [
|
|
204
|
+
running ? running + ' 在跑' : '全部空闲',
|
|
205
|
+
h('i', { key: 'i' }, ' / ' + agents.length + ' 在岗'),
|
|
206
|
+
]),
|
|
207
|
+
h('span', { className: 'fg-caret', key: 'c' }, open ? '⌄' : '⌃'),
|
|
208
|
+
]),
|
|
209
|
+
open ? h('div', { className: 'fg-body', key: 'body' }, [
|
|
210
|
+
...shown.map((a) => h(MonitorRow, { key: a.id || a.name, agent: a, onOpen: openSession })),
|
|
211
|
+
hidden > 0 ? h('div', { className: 'fg-more', key: 'more' }, '还有 ' + hidden + ' 个会话') : null,
|
|
212
|
+
agents.length === 0 ? h('div', { className: 'fg-more', key: 'empty' }, '暂无会话') : null,
|
|
213
|
+
]) : null,
|
|
214
|
+
]));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function apply(ctx) {
|
|
218
|
+
const bridge = (ready) => {
|
|
219
|
+
const target = ready && ready.slots ? ready : ctx;
|
|
220
|
+
const slots = target && target.slots;
|
|
221
|
+
if (!slots) return;
|
|
222
|
+
const render = () => {
|
|
223
|
+
slots.inject('shell.overlay', () => slots.register({
|
|
224
|
+
name: 'shell.overlay',
|
|
225
|
+
id: 'dsh-agent-floor',
|
|
226
|
+
order: 940,
|
|
227
|
+
label: 'Agent Floor',
|
|
228
|
+
}, () => h(MonitorBar, { ctx })));
|
|
229
|
+
};
|
|
230
|
+
if (typeof target.effect === 'function') target.effect(render, 'dsh-agent-floor: mounts');
|
|
231
|
+
else render();
|
|
232
|
+
};
|
|
233
|
+
if (typeof ctx.inject === 'function') {
|
|
234
|
+
ctx.inject(['slots'], bridge);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (ctx.slots) bridge(ctx);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return { inject, apply, __dshTest: { deriveAgents, MonitorBar, MonitorRow } };
|
|
241
|
+
},
|
|
242
|
+
});
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" role="img" aria-label="Agent Floor">
|
|
2
|
+
<rect width="128" height="128" rx="28" fill="#111827"/>
|
|
3
|
+
<rect x="20" y="26" width="88" height="76" rx="12" fill="#1B2033" stroke="#2B3350" stroke-width="2"/>
|
|
4
|
+
<circle cx="34" cy="42" r="4" fill="#4ADE80"/>
|
|
5
|
+
<rect x="44" y="38" width="30" height="8" rx="4" fill="#4C6FFF"/>
|
|
6
|
+
<rect x="80" y="38" width="18" height="8" rx="4" fill="#2B3350"/>
|
|
7
|
+
<rect x="28" y="58" width="8" height="8" rx="4" fill="#4ADE80"/>
|
|
8
|
+
<rect x="42" y="58" width="44" height="8" rx="4" fill="#3A4158"/>
|
|
9
|
+
<rect x="28" y="76" width="8" height="8" rx="4" fill="#9AA0A6"/>
|
|
10
|
+
<rect x="42" y="76" width="34" height="8" rx="4" fill="#3A4158"/>
|
|
11
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
// Host half of Agent Ops: folds the live Session append feed into one compact
|
|
2
|
+
// telemetry snapshot served at GET /dsh-agent-floor/state.
|
|
3
|
+
//
|
|
4
|
+
// The browser half polls this route. Nothing here renders; nothing here is
|
|
5
|
+
// authoritative — a missing session simply yields an empty snapshot and the
|
|
6
|
+
// browser half switches to its own simulation.
|
|
7
|
+
|
|
8
|
+
import { execFileSync } from 'node:child_process';
|
|
9
|
+
import { isAbsolute, relative } from 'node:path';
|
|
10
|
+
|
|
11
|
+
export const name = 'dsh-agent-floor';
|
|
12
|
+
export const inject = ['webServer', 'sessions'];
|
|
13
|
+
|
|
14
|
+
const ROUTE = '/dsh-agent-floor/state';
|
|
15
|
+
const MAX_EVENTS = 160;
|
|
16
|
+
const MAX_TOOLS = 40;
|
|
17
|
+
const MAX_FILES = 18;
|
|
18
|
+
const MAX_SESSIONS = 8;
|
|
19
|
+
const IDLE_MS = 150000;
|
|
20
|
+
|
|
21
|
+
function pad(n, w = 2) {
|
|
22
|
+
const s = String(Math.max(0, Math.floor(Number(n) || 0)));
|
|
23
|
+
return s.length >= w ? s : '0'.repeat(w - s.length) + s;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function clip(text, max) {
|
|
27
|
+
const s = String(text == null ? '' : text).replace(/\s+/g, ' ').trim();
|
|
28
|
+
return s.length > max ? s.slice(0, max - 1) + '…' : s;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseArgs(raw) {
|
|
32
|
+
if (!raw) return {};
|
|
33
|
+
if (typeof raw === 'object') return raw;
|
|
34
|
+
try {
|
|
35
|
+
const v = JSON.parse(String(raw));
|
|
36
|
+
return v && typeof v === 'object' ? v : {};
|
|
37
|
+
} catch {
|
|
38
|
+
return {};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function targetOf(name, args) {
|
|
43
|
+
const pick = (keys) => {
|
|
44
|
+
for (const k of keys) {
|
|
45
|
+
const v = args[k];
|
|
46
|
+
if (typeof v === 'string' && v.trim()) return v;
|
|
47
|
+
}
|
|
48
|
+
return '';
|
|
49
|
+
};
|
|
50
|
+
const n = String(name || '').toLowerCase();
|
|
51
|
+
if (n === 'bash' || n === 'pwsh' || n === 'terminal_open' || n === 'terminal_send') {
|
|
52
|
+
return clip(pick(['command', 'cmd', 'line']), 46);
|
|
53
|
+
}
|
|
54
|
+
if (n === 'grep' || n === 'glob' || n === 'grep_search') return clip(pick(['pattern', 'query']), 40);
|
|
55
|
+
if (n === 'web_search' || n === 'web_fetch') return clip(pick(['query', 'url']), 46);
|
|
56
|
+
if (n === 'skill') return clip(pick(['name']), 32);
|
|
57
|
+
if (n === 'present' || n === 'spawn_teammate' || n === 'send_message') return clip(pick(['name', 'target']), 32);
|
|
58
|
+
if (n === 'subagent' || n === 'subagent_fork' || n === 'workflow') return clip(pick(['prompt', 'script']), 42);
|
|
59
|
+
return clip(
|
|
60
|
+
pick(['path', 'file_path', 'filePath', 'target', 'name', 'input', 'text', 'prompt']),
|
|
61
|
+
46,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function fileOf(name, args) {
|
|
66
|
+
const n = String(name || '').toLowerCase();
|
|
67
|
+
const p = args.path || args.file_path || args.filePath || '';
|
|
68
|
+
if (typeof p !== 'string' || !p.trim()) return null;
|
|
69
|
+
const write = ['edit', 'write', 'edit_text', 'apply_patch', 'write_text', 'writeText'].includes(n);
|
|
70
|
+
const read = ['read', 'grep', 'glob', 'read_image', 'list_dir', 'ls', 'search'].includes(n);
|
|
71
|
+
if (!write && !read) return null;
|
|
72
|
+
return { path: p, write };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function snippet(text, max) {
|
|
76
|
+
const s = String(text || '').replace(/[`*#>\n\r\t]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
77
|
+
return clip(s, max);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function contentText(message) {
|
|
81
|
+
const blocks = message && Array.isArray(message.content) ? message.content : [];
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const b of blocks) {
|
|
84
|
+
if (!b || typeof b !== 'object') continue;
|
|
85
|
+
if (b.type === 'text' && typeof b.text === 'string') out.push(b.text);
|
|
86
|
+
if (b.type === 'tool-call' && typeof b.name === 'string') out.push(`[${b.name}]`);
|
|
87
|
+
if (b.type === 'tool-result') out.push('[result]');
|
|
88
|
+
}
|
|
89
|
+
return snippet(out.join(' '), 120);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function fallbackTitle(cwd, id) {
|
|
93
|
+
const raw = String(cwd || '').replace(/[\\/]+$/, '');
|
|
94
|
+
const base = raw ? raw.split(/[\\/]/).filter(Boolean).pop() : '';
|
|
95
|
+
if (base) return base;
|
|
96
|
+
return 'SESSION ' + String(id || '').slice(-8).toUpperCase();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Real git changes for one session cwd: `diffFiles` is what the floor calls
|
|
100
|
+
// "changes on disk", as up to MAX_DIFF_FILES repo-relative paths. A missing
|
|
101
|
+
// cwd, a non-git directory, a timeout or any git failure degrades to [] — this
|
|
102
|
+
// runs inside a polling HTTP route, so it must never throw or block for long.
|
|
103
|
+
const MAX_DIFF_FILES = 6;
|
|
104
|
+
const DIFF_CACHE_MS = 10000;
|
|
105
|
+
const diffCache = new Map();
|
|
106
|
+
|
|
107
|
+
function diffFilesOf(cwd) {
|
|
108
|
+
const dir = String(cwd || '').trim();
|
|
109
|
+
if (!dir) return [];
|
|
110
|
+
const cached = diffCache.get(dir);
|
|
111
|
+
if (cached && Date.now() - cached.t < DIFF_CACHE_MS) return cached.files;
|
|
112
|
+
const files = [];
|
|
113
|
+
try {
|
|
114
|
+
const opts = { cwd: dir, encoding: 'utf8', timeout: 800, stdio: ['ignore', 'pipe', 'ignore'] };
|
|
115
|
+
const seen = new Set();
|
|
116
|
+
const add = (raw) => {
|
|
117
|
+
if (files.length >= MAX_DIFF_FILES) return;
|
|
118
|
+
let p = String(raw || '').trim();
|
|
119
|
+
if (!p) return;
|
|
120
|
+
if (p.includes(' -> ')) p = p.split(' -> ').pop().trim(); // rename: keep the new name
|
|
121
|
+
if (p.length > 1 && p.startsWith('"') && p.endsWith('"')) p = p.slice(1, -1);
|
|
122
|
+
p = p.replace(/\\/g, '/');
|
|
123
|
+
if (isAbsolute(p)) {
|
|
124
|
+
const rel = relative(dir, p).replace(/\\/g, '/');
|
|
125
|
+
if (!rel || rel.startsWith('..')) return;
|
|
126
|
+
p = rel;
|
|
127
|
+
}
|
|
128
|
+
if (!p || seen.has(p)) return;
|
|
129
|
+
seen.add(p);
|
|
130
|
+
files.push(p);
|
|
131
|
+
};
|
|
132
|
+
const status = execFileSync('git', ['status', '--porcelain'], opts);
|
|
133
|
+
for (const line of String(status || '').split(/\r?\n/)) {
|
|
134
|
+
if (line.length < 4) continue;
|
|
135
|
+
add(line.slice(3));
|
|
136
|
+
}
|
|
137
|
+
if (files.length === 0) {
|
|
138
|
+
const diff = execFileSync('git', ['diff', '--name-only', 'HEAD'], opts);
|
|
139
|
+
for (const line of String(diff || '').split(/\r?\n/)) add(line);
|
|
140
|
+
}
|
|
141
|
+
} catch {
|
|
142
|
+
files.length = 0;
|
|
143
|
+
}
|
|
144
|
+
const result = files.slice(0, MAX_DIFF_FILES);
|
|
145
|
+
if (diffCache.size > 64) diffCache.clear();
|
|
146
|
+
diffCache.set(dir, { t: Date.now(), files: result });
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function apply(ctx) {
|
|
151
|
+
/** @type {Map<string, any>} */
|
|
152
|
+
const models = new Map();
|
|
153
|
+
let lastActivity = 0;
|
|
154
|
+
let focus = null;
|
|
155
|
+
let totalToolCalls = 0;
|
|
156
|
+
let totalErrors = 0;
|
|
157
|
+
let tokensIn = 0;
|
|
158
|
+
let tokensOut = 0;
|
|
159
|
+
|
|
160
|
+
function ensure(sessionId, cwd, parent) {
|
|
161
|
+
let m = models.get(sessionId);
|
|
162
|
+
if (!m) {
|
|
163
|
+
m = {
|
|
164
|
+
id: sessionId,
|
|
165
|
+
title: fallbackTitle(cwd, sessionId),
|
|
166
|
+
cwd: cwd || '',
|
|
167
|
+
parent: parent || null,
|
|
168
|
+
model: '',
|
|
169
|
+
provider: '',
|
|
170
|
+
running: false,
|
|
171
|
+
updatedAt: 0,
|
|
172
|
+
startedAt: 0,
|
|
173
|
+
turns: 0,
|
|
174
|
+
steps: 0,
|
|
175
|
+
toolCalls: 0,
|
|
176
|
+
tokensIn: 0,
|
|
177
|
+
tokensOut: 0,
|
|
178
|
+
events: [],
|
|
179
|
+
tools: [],
|
|
180
|
+
files: new Map(),
|
|
181
|
+
seq: -1,
|
|
182
|
+
};
|
|
183
|
+
models.set(sessionId, m);
|
|
184
|
+
}
|
|
185
|
+
return m;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function pushEvent(m, kind, label, detail, status, t) {
|
|
189
|
+
m.events.push({ seq: m.seq, t: t || Date.now(), kind, label: clip(label, 64), detail: clip(detail, 80), status: status || 'info', sessionId: m.id });
|
|
190
|
+
if (m.events.length > MAX_EVENTS) m.events.splice(0, m.events.length - MAX_EVENTS);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function addTool(m, tool) {
|
|
194
|
+
m.tools.push(tool);
|
|
195
|
+
if (m.tools.length > MAX_TOOLS) m.tools.splice(0, m.tools.length - MAX_TOOLS);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function addFile(m, path, write, tool) {
|
|
199
|
+
let f = m.files.get(path);
|
|
200
|
+
if (!f) {
|
|
201
|
+
f = { path, reads: 0, writes: 0, lastT: 0, tool };
|
|
202
|
+
m.files.set(path, f);
|
|
203
|
+
}
|
|
204
|
+
if (write) f.writes += 1;
|
|
205
|
+
else f.reads += 1;
|
|
206
|
+
f.lastT = Date.now();
|
|
207
|
+
f.tool = tool;
|
|
208
|
+
if (m.files.size > MAX_FILES) {
|
|
209
|
+
let oldest = null;
|
|
210
|
+
for (const [k, v] of m.files) if (!oldest || v.lastT < m.files.get(oldest).lastT) oldest = k;
|
|
211
|
+
if (oldest) m.files.delete(oldest);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function record(session, event) {
|
|
216
|
+
if (!session || !event || typeof event.type !== 'string') return;
|
|
217
|
+
const sid = String(session.id || '');
|
|
218
|
+
if (!sid) return;
|
|
219
|
+
const header = session.header || {};
|
|
220
|
+
const m = ensure(sid, header.cwd, header.parentSession ? String(header.parentSession) : null);
|
|
221
|
+
if (event.origin === 'subagent' || header.origin === 'subagent') m.parent = m.parent || 'subagent';
|
|
222
|
+
const idx = Number(event.seq);
|
|
223
|
+
if (Number.isFinite(idx) && idx <= m.seq && idx > -1) return; // duplicate
|
|
224
|
+
m.seq = Number.isFinite(idx) ? Math.max(m.seq, idx) : m.seq + 1;
|
|
225
|
+
if (!m.startedAt) m.startedAt = Number(event.time) || Date.now();
|
|
226
|
+
m.updatedAt = Date.now();
|
|
227
|
+
lastActivity = m.updatedAt;
|
|
228
|
+
focus = sid;
|
|
229
|
+
|
|
230
|
+
const data = event.data && typeof event.data === 'object' ? event.data : {};
|
|
231
|
+
const t = Number(event.time) || Date.now();
|
|
232
|
+
|
|
233
|
+
switch (event.type) {
|
|
234
|
+
case 'session/title': {
|
|
235
|
+
const title = clip(data.title, 80);
|
|
236
|
+
if (title) m.title = title;
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
case 'turn/start': {
|
|
240
|
+
m.running = true;
|
|
241
|
+
m.turns = Math.max(m.turns, Number(data.turn) || m.turns);
|
|
242
|
+
pushEvent(m, 'TURN', `TURN ${pad(data.turn)} ENGAGED`, 'inbox dispatch', 'run', t);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
case 'turn/end': {
|
|
246
|
+
m.running = false;
|
|
247
|
+
if (Number(data.turn)) m.turns = Math.max(m.turns, Number(data.turn));
|
|
248
|
+
const reason = data.reason && data.reason.kind ? data.reason.kind : 'stop';
|
|
249
|
+
pushEvent(m, 'TURN', `TURN ${pad(data.turn)} CLOSED`, `reason: ${reason}`, reason === 'error' ? 'error' : 'ok', t);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
case 'step/start': {
|
|
253
|
+
m.steps += 1;
|
|
254
|
+
m.running = true;
|
|
255
|
+
if (Number(data.turn)) m.turns = Math.max(m.turns, Number(data.turn));
|
|
256
|
+
pushEvent(m, 'STEP', `STEP ${pad(data.step)} · REASONING`, `turn ${pad(data.turn)}`, 'run', t);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
case 'tool/call': {
|
|
260
|
+
const name = String(data.name || 'tool');
|
|
261
|
+
const args = parseArgs(data.arguments);
|
|
262
|
+
const target = targetOf(name, args);
|
|
263
|
+
m.toolCalls += 1;
|
|
264
|
+
m.running = true;
|
|
265
|
+
if (Number(data.turn)) m.turns = Math.max(m.turns, Number(data.turn));
|
|
266
|
+
totalToolCalls += 1;
|
|
267
|
+
addTool(m, {
|
|
268
|
+
id: String(data.callId || `${sid}:${m.seq}`),
|
|
269
|
+
name,
|
|
270
|
+
target,
|
|
271
|
+
turn: Number(data.turn) || 0,
|
|
272
|
+
step: Number(data.step) || 0,
|
|
273
|
+
status: 'RUNNING',
|
|
274
|
+
t,
|
|
275
|
+
sessionId: sid,
|
|
276
|
+
});
|
|
277
|
+
const f = fileOf(name, args);
|
|
278
|
+
if (f) addFile(m, f.path, f.write, name);
|
|
279
|
+
pushEvent(m, 'TOOL', `${String(name).toUpperCase()} DISPATCHED`, target || 'no target', 'run', t);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
case 'tool/result': {
|
|
283
|
+
const result = data.message || {};
|
|
284
|
+
const callId = String(result.toolCallId || '');
|
|
285
|
+
const isError = Boolean(data.error) || Boolean(result.isError);
|
|
286
|
+
let tool = null;
|
|
287
|
+
for (let i = m.tools.length - 1; i >= 0; i -= 1) {
|
|
288
|
+
if (m.tools[i].status === 'RUNNING') {
|
|
289
|
+
tool = m.tools[i];
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (tool) {
|
|
294
|
+
tool.status = isError ? 'ERROR' : 'OK';
|
|
295
|
+
if (!tool.id && callId) tool.id = callId;
|
|
296
|
+
}
|
|
297
|
+
if (isError) totalErrors += 1;
|
|
298
|
+
pushEvent(m, 'TOOL', `${tool ? String(tool.name).toUpperCase() : 'TOOL'} RETURNED`, isError ? 'error path' : 'nominal', isError ? 'error' : 'ok', t);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
case 'assistant/message': {
|
|
302
|
+
const usage = data.usage || {};
|
|
303
|
+
const i = Number(usage.inputTokens) || 0;
|
|
304
|
+
const o = Number(usage.outputTokens) || 0;
|
|
305
|
+
m.tokensIn += i;
|
|
306
|
+
m.tokensOut += o;
|
|
307
|
+
tokensIn += i;
|
|
308
|
+
tokensOut += o;
|
|
309
|
+
const text = contentText(data.message);
|
|
310
|
+
pushEvent(m, 'MODEL', `MODEL REPLY · ${pad(Math.round((i + o) / 100))}00 TOK`, text || 'assistant message', 'ok', t);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
case 'assistant/attempt': {
|
|
314
|
+
pushEvent(m, 'MODEL', 'MODEL ATTEMPT STREAM', 'retry / first pass', 'run', t);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
case 'user/message': {
|
|
318
|
+
pushEvent(m, 'OPERATOR', 'OPERATOR INPUT RECEIVED', contentText(data) || 'prompt', 'info', t);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
case 'request/header': {
|
|
322
|
+
const cfg = data.header && data.header.config ? data.header.config : {};
|
|
323
|
+
if (cfg.model) m.model = String(cfg.model);
|
|
324
|
+
if (cfg.provider) m.provider = String(cfg.provider);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
case 'compaction/summary': {
|
|
328
|
+
pushEvent(m, 'SYSTEM', 'CONTEXT COMPACTION', 'summary committed', 'warn', t);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
case 'session/end-seed': {
|
|
332
|
+
pushEvent(m, 'SYSTEM', 'SEED BOUNDARY', 'inherited history', 'info', t);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
default:
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function seed(session) {
|
|
341
|
+
try {
|
|
342
|
+
const all = session.snapshotEvents ? session.snapshotEvents() : [];
|
|
343
|
+
const slice = all.length > 400 ? all.slice(all.length - 400) : all;
|
|
344
|
+
const header = session.header || {};
|
|
345
|
+
const m = ensure(String(session.id || ''), header.cwd, header.parentSession ? String(header.parentSession) : null);
|
|
346
|
+
m.startedAt = Number(header.createdAt) || m.startedAt;
|
|
347
|
+
try {
|
|
348
|
+
const hdr = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined;
|
|
349
|
+
const cfg = hdr && hdr.config ? hdr.config : null;
|
|
350
|
+
if (cfg && cfg.model) m.model = String(cfg.model);
|
|
351
|
+
if (cfg && cfg.provider) m.provider = String(cfg.provider);
|
|
352
|
+
} catch {}
|
|
353
|
+
for (const ev of slice) {
|
|
354
|
+
try {
|
|
355
|
+
record(session, ev);
|
|
356
|
+
} catch {}
|
|
357
|
+
}
|
|
358
|
+
} catch {}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
try {
|
|
362
|
+
for (const s of ctx.sessions.list()) seed(s);
|
|
363
|
+
} catch {}
|
|
364
|
+
|
|
365
|
+
const offEvent = ctx.on('session/event', (session, event) => {
|
|
366
|
+
try {
|
|
367
|
+
record(session, event);
|
|
368
|
+
} catch {}
|
|
369
|
+
});
|
|
370
|
+
const offDisposed = ctx.on('session/disposed', (session) => {
|
|
371
|
+
try {
|
|
372
|
+
const sid = session && session.id ? String(session.id) : '';
|
|
373
|
+
const m = models.get(sid);
|
|
374
|
+
if (m) {
|
|
375
|
+
m.running = false;
|
|
376
|
+
m.updatedAt = Date.now();
|
|
377
|
+
pushEvent(m, 'SYSTEM', 'SESSION DETACHED', 'agent released', 'warn', Date.now());
|
|
378
|
+
}
|
|
379
|
+
} catch {}
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
ctx.effect(
|
|
383
|
+
() => () => {
|
|
384
|
+
try {
|
|
385
|
+
offEvent();
|
|
386
|
+
offDisposed();
|
|
387
|
+
} catch {}
|
|
388
|
+
},
|
|
389
|
+
'dsh-agent-floor: session feed',
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
function snapshot() {
|
|
393
|
+
const now = Date.now();
|
|
394
|
+
const live = [...models.values()]
|
|
395
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
396
|
+
.slice(0, MAX_SESSIONS)
|
|
397
|
+
.reverse();
|
|
398
|
+
|
|
399
|
+
const focusModel = (focus && models.get(focus)) || live[live.length - 1] || null;
|
|
400
|
+
const idle = !focusModel || now - lastActivity > IDLE_MS;
|
|
401
|
+
|
|
402
|
+
const sessions = live.map((m) => ({
|
|
403
|
+
id: m.id,
|
|
404
|
+
title: m.title || m.cwd || m.id,
|
|
405
|
+
cwd: m.cwd,
|
|
406
|
+
model: m.model,
|
|
407
|
+
provider: m.provider,
|
|
408
|
+
running: m.running,
|
|
409
|
+
updatedAt: m.updatedAt,
|
|
410
|
+
startedAt: m.startedAt,
|
|
411
|
+
parent: m.parent,
|
|
412
|
+
turns: m.turns,
|
|
413
|
+
steps: m.steps,
|
|
414
|
+
step: m.tools.length ? m.tools[m.tools.length - 1].step : 0,
|
|
415
|
+
turn: m.tools.length ? m.tools[m.tools.length - 1].turn : m.turns,
|
|
416
|
+
lastLabel: m.events.length ? m.events[m.events.length - 1].label : '',
|
|
417
|
+
lastTool: (() => {
|
|
418
|
+
const t = m.tools.length ? m.tools[m.tools.length - 1] : null;
|
|
419
|
+
return t ? { name: t.name, target: t.target || '', status: t.status } : null;
|
|
420
|
+
})(),
|
|
421
|
+
files: [...m.files.values()]
|
|
422
|
+
.sort((a, b) => b.lastT - a.lastT)
|
|
423
|
+
.slice(0, 4)
|
|
424
|
+
.map((f) => ({ name: String(f.path).split('/').pop(), write: f.writes > 0 })),
|
|
425
|
+
diffFiles: diffFilesOf(m.cwd),
|
|
426
|
+
toolCalls: m.toolCalls,
|
|
427
|
+
tokensIn: m.tokensIn,
|
|
428
|
+
tokensOut: m.tokensOut,
|
|
429
|
+
events: m.events.length,
|
|
430
|
+
}));
|
|
431
|
+
|
|
432
|
+
const agents = sessions.map((s, i) => {
|
|
433
|
+
const last = (focusModel && focusModel.events.slice(-1)[0]) || null;
|
|
434
|
+
const age = now - (s.updatedAt || 0);
|
|
435
|
+
const status = s.running || age < 45000 ? 'RUNNING' : age < 300000 ? 'STANDBY' : 'IDLE';
|
|
436
|
+
return {
|
|
437
|
+
id: s.id,
|
|
438
|
+
name: s.title ? clip(s.title, 26) : `AGENT ${pad(i + 1)}`,
|
|
439
|
+
role: s.parent ? 'SUBAGENT' : 'LEAD',
|
|
440
|
+
status,
|
|
441
|
+
activity: s.parent ? `CHILD · ${clip(s.id, 12)}` : 'PRIMARY LOOP',
|
|
442
|
+
sessionId: s.id,
|
|
443
|
+
tools: s.toolCalls,
|
|
444
|
+
tokens: s.tokensIn + s.tokensOut,
|
|
445
|
+
lastEvent: last ? last.label : '',
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
const tools = (focusModel ? focusModel.tools.slice(-MAX_TOOLS) : []).map((x) => ({
|
|
450
|
+
id: x.id,
|
|
451
|
+
name: x.name,
|
|
452
|
+
target: x.target,
|
|
453
|
+
status: x.status,
|
|
454
|
+
turn: x.turn,
|
|
455
|
+
step: x.step,
|
|
456
|
+
t: x.t,
|
|
457
|
+
}));
|
|
458
|
+
|
|
459
|
+
const files = (focusModel ? [...focusModel.files.values()].sort((a, b) => b.lastT - a.lastT).slice(0, MAX_FILES) : []).map((f) => ({
|
|
460
|
+
path: f.path,
|
|
461
|
+
reads: f.reads,
|
|
462
|
+
writes: f.writes,
|
|
463
|
+
tool: f.tool,
|
|
464
|
+
lastT: f.lastT,
|
|
465
|
+
}));
|
|
466
|
+
|
|
467
|
+
const events = (focusModel ? focusModel.events.slice(-MAX_EVENTS) : []).map((e) => ({
|
|
468
|
+
seq: e.seq,
|
|
469
|
+
t: e.t,
|
|
470
|
+
kind: e.kind,
|
|
471
|
+
label: e.label,
|
|
472
|
+
detail: e.detail,
|
|
473
|
+
status: e.status,
|
|
474
|
+
}));
|
|
475
|
+
|
|
476
|
+
return {
|
|
477
|
+
ok: true,
|
|
478
|
+
source: 'dsh-agent-floor',
|
|
479
|
+
mode: idle ? 'idle' : 'live',
|
|
480
|
+
generatedAt: now,
|
|
481
|
+
uptimeMs: focusModel && focusModel.startedAt ? now - focusModel.startedAt : 0,
|
|
482
|
+
focus: focusModel ? focusModel.id : null,
|
|
483
|
+
sessions,
|
|
484
|
+
agents,
|
|
485
|
+
stats: {
|
|
486
|
+
turns: sessions.reduce((n, s) => n + s.turns, 0),
|
|
487
|
+
steps: sessions.reduce((n, s) => n + s.steps, 0),
|
|
488
|
+
toolCalls: totalToolCalls,
|
|
489
|
+
errors: totalErrors,
|
|
490
|
+
tokensIn,
|
|
491
|
+
tokensOut,
|
|
492
|
+
agents: sessions.length,
|
|
493
|
+
files: models.size ? [...models.values()].reduce((n, m) => n + m.files.size, 0) : 0,
|
|
494
|
+
events: sessions.reduce((n, s) => n + s.events, 0),
|
|
495
|
+
},
|
|
496
|
+
tools,
|
|
497
|
+
files,
|
|
498
|
+
events,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function handler(req, res) {
|
|
503
|
+
try {
|
|
504
|
+
if (req.method && req.method !== 'GET' && req.method !== 'HEAD') {
|
|
505
|
+
res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' });
|
|
506
|
+
res.end(JSON.stringify({ ok: false, error: 'method-not-allowed' }));
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const body = JSON.stringify(snapshot());
|
|
510
|
+
res.writeHead(200, {
|
|
511
|
+
'content-type': 'application/json; charset=utf-8',
|
|
512
|
+
'cache-control': 'no-store, max-age=0',
|
|
513
|
+
'content-length': Buffer.byteLength(body),
|
|
514
|
+
});
|
|
515
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
try {
|
|
518
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
|
|
519
|
+
res.end(JSON.stringify({ ok: false, error: String((error && error.message) || error) }));
|
|
520
|
+
} catch {}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
ctx.effect(
|
|
525
|
+
() => ctx.webServer.register({ kind: 'exact', path: ROUTE, handler }),
|
|
526
|
+
'dsh-agent-floor: state route',
|
|
527
|
+
);
|
|
528
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-agent-floor",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Agent Floor — a compact always-on dock for DeepSeek Harness: which session is running, how far along, how many tokens, which files changed.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"dsh",
|
|
9
|
+
"dsh-plugin",
|
|
10
|
+
"deepseek-harness",
|
|
11
|
+
"agents",
|
|
12
|
+
"dashboard",
|
|
13
|
+
"observability"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/ITxuezhe/dsh-agent-floor",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/ITxuezhe/dsh-agent-floor.git"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"dsh": "^0.2.0"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./index.js",
|
|
25
|
+
"./client": "./client.js"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"index.js",
|
|
29
|
+
"client.js",
|
|
30
|
+
"cordis.patch.yml",
|
|
31
|
+
"icon.svg",
|
|
32
|
+
"README.md",
|
|
33
|
+
"scripts/harness.js",
|
|
34
|
+
"scripts/README.md"
|
|
35
|
+
],
|
|
36
|
+
"dsh": {
|
|
37
|
+
"bundle": {
|
|
38
|
+
"patch": "./cordis.patch.yml"
|
|
39
|
+
},
|
|
40
|
+
"client": {
|
|
41
|
+
"platform": "web",
|
|
42
|
+
"immediately": true,
|
|
43
|
+
"inject": [
|
|
44
|
+
"@deepseek-ai/dsh-client-ui-slots"
|
|
45
|
+
]
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# 自检脚本
|
|
2
|
+
|
|
3
|
+
改 `client.js` 之后,不用开浏览器就能验证它没炸。
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
node scripts/harness.js # 默认检查 ../client.js
|
|
7
|
+
node scripts/harness.js path/to.js # 检查别的构建产物
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
它做四件事:
|
|
11
|
+
|
|
12
|
+
1. 桩掉 `window.__ModuleLoader__` / `React` / `document` / `localStorage` / `fetch`,
|
|
13
|
+
2. 真的执行 `client.js`,走一遍 `apply()` 的 `ctx.inject(['slots'])` → `slots.register('shell.overlay', …)` 链路,
|
|
14
|
+
3. 把注册出来的 **MonitorBar** 真渲染一次(带假会话数据),再单独渲染一行 **MonitorRow**,
|
|
15
|
+
4. 顺带验证 `deriveAgents` 的分组与排序(子代理挂到组长后面、depth=1)。
|
|
16
|
+
|
|
17
|
+
成功时末行固定打印 `render ok` 并以 0 退出;失败打印堆栈、退出码 1。
|
|
18
|
+
|
|
19
|
+
常见失败:
|
|
20
|
+
|
|
21
|
+
- `client.js 没有调用 window.__ModuleLoader__.load(...)` —— 文件头被改坏了。
|
|
22
|
+
- `apply() 没有注册任何组件到 shell.overlay` —— `inject`/`apply` 链路断了。
|
|
23
|
+
- `MonitorBar 顶层不是 div` / `缺少 fg-* className` —— 组件根节点被换了。
|
|
24
|
+
- `ReferenceError: xxx is not defined` —— 改代码时删掉了函数还在被引用(`node --check` 查不出来这种)。
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* harness.js — 无需 DSH / 浏览器的客户端自检。
|
|
4
|
+
*
|
|
5
|
+
* 桩掉 window.__ModuleLoader__、React、document 等宿主环境,真的加载 ../client.js,
|
|
6
|
+
* 走一遍 apply() 的注册链路,然后把注册出来的监控条(MonitorBar)真渲染一次,
|
|
7
|
+
* 再用假会话验证 deriveAgents 的分组与排序。任何一步抛错都以 exit 1 结束并打印堆栈。
|
|
8
|
+
*
|
|
9
|
+
* 用法:
|
|
10
|
+
* node scripts/harness.js # 默认检查 ../client.js
|
|
11
|
+
* node scripts/harness.js path/to/x.js # 检查别的构建产物
|
|
12
|
+
*
|
|
13
|
+
* 成功输出末行固定为 `render ok`。
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
|
|
19
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const target = path.resolve(process.argv[2] || path.join(HERE, '..', 'client.js'));
|
|
21
|
+
|
|
22
|
+
function fail(err) {
|
|
23
|
+
const stack = err && err.stack ? err.stack : String(err);
|
|
24
|
+
console.error(stack);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// 最小 React 运行时:支持 createElement / useState / useRef / useEffect。
|
|
30
|
+
// 只渲染一遍(setState 是空实现),足够验证组件在真实数据形状下不炸。
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
const effects = [];
|
|
33
|
+
let activeInstance = null;
|
|
34
|
+
|
|
35
|
+
function currentInstance(hookName) {
|
|
36
|
+
if (!activeInstance) throw new Error(hookName + ' called outside a component render');
|
|
37
|
+
return activeInstance;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const React = {
|
|
41
|
+
createElement(tag, props, ...kids) { return { tag, props: props || {}, kids }; },
|
|
42
|
+
useState(initial) {
|
|
43
|
+
const inst = currentInstance('useState');
|
|
44
|
+
const i = inst.cursor++;
|
|
45
|
+
if (!(i in inst.slots)) inst.slots[i] = typeof initial === 'function' ? initial() : initial;
|
|
46
|
+
return [inst.slots[i], () => {}];
|
|
47
|
+
},
|
|
48
|
+
useRef(value) {
|
|
49
|
+
const inst = currentInstance('useRef');
|
|
50
|
+
const i = inst.cursor++;
|
|
51
|
+
if (!(i in inst.slots)) inst.slots[i] = { current: value };
|
|
52
|
+
return inst.slots[i];
|
|
53
|
+
},
|
|
54
|
+
useEffect(fn) {
|
|
55
|
+
const inst = currentInstance('useEffect');
|
|
56
|
+
inst.cursor += 1;
|
|
57
|
+
effects.push(fn);
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
function renderNode(node) {
|
|
62
|
+
if (node === null || node === undefined || node === false || node === true) return [];
|
|
63
|
+
if (typeof node === 'string' || typeof node === 'number') return [{ text: String(node) }];
|
|
64
|
+
if (Array.isArray(node)) {
|
|
65
|
+
const out = [];
|
|
66
|
+
for (const item of node) out.push(...renderNode(item));
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
const { tag, props, kids } = node;
|
|
70
|
+
if (typeof tag === 'function') {
|
|
71
|
+
const inst = { slots: [], cursor: 0 };
|
|
72
|
+
const prev = activeInstance;
|
|
73
|
+
activeInstance = inst;
|
|
74
|
+
let rendered;
|
|
75
|
+
try { rendered = tag(props || {}); } finally { activeInstance = prev; }
|
|
76
|
+
return renderNode(rendered);
|
|
77
|
+
}
|
|
78
|
+
const children = [];
|
|
79
|
+
for (const kid of kids || []) children.push(...renderNode(kid));
|
|
80
|
+
return [{ tag, props: props || {}, children }];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function countNodes(nodes) {
|
|
84
|
+
let n = 0;
|
|
85
|
+
for (const node of nodes) {
|
|
86
|
+
n += 1;
|
|
87
|
+
if (node.children) n += countNodes(node.children);
|
|
88
|
+
}
|
|
89
|
+
return n;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function findTag(nodes, tag) {
|
|
93
|
+
for (const node of nodes) {
|
|
94
|
+
if (node.tag === tag) return node;
|
|
95
|
+
if (node.children) {
|
|
96
|
+
const hit = findTag(node.children, tag);
|
|
97
|
+
if (hit) return hit;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// 宿主环境桩
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
function createStubs() {
|
|
107
|
+
const store = { 'dsh.agent-floor.open': '1' };
|
|
108
|
+
const storage = {
|
|
109
|
+
getItem: (k) => (k in store ? store[k] : null),
|
|
110
|
+
setItem: () => {},
|
|
111
|
+
removeItem: () => {},
|
|
112
|
+
};
|
|
113
|
+
const win = {
|
|
114
|
+
__ModuleLoader__: { load(mod) { captured = mod; } },
|
|
115
|
+
setTimeout: () => 0,
|
|
116
|
+
clearTimeout: () => {},
|
|
117
|
+
setInterval: () => 0,
|
|
118
|
+
clearInterval: () => {},
|
|
119
|
+
innerWidth: 1440,
|
|
120
|
+
innerHeight: 900,
|
|
121
|
+
addEventListener: () => {},
|
|
122
|
+
removeEventListener: () => {},
|
|
123
|
+
};
|
|
124
|
+
const doc = {
|
|
125
|
+
head: { appendChild: () => {} },
|
|
126
|
+
body: { appendChild: () => {} },
|
|
127
|
+
documentElement: {},
|
|
128
|
+
getElementById: () => null,
|
|
129
|
+
createElement: () => ({ style: {}, set id(v) {}, set textContent(v) {} }),
|
|
130
|
+
addEventListener: () => {},
|
|
131
|
+
removeEventListener: () => {},
|
|
132
|
+
};
|
|
133
|
+
const fakeFetch = () => Promise.resolve({
|
|
134
|
+
ok: false,
|
|
135
|
+
status: 503,
|
|
136
|
+
json: () => Promise.resolve({}),
|
|
137
|
+
});
|
|
138
|
+
return { win, doc, storage, fakeFetch };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let captured = null;
|
|
142
|
+
|
|
143
|
+
function main() {
|
|
144
|
+
const { win, doc, storage, fakeFetch } = createStubs();
|
|
145
|
+
|
|
146
|
+
if (!fs.existsSync(target)) throw new Error('client file not found: ' + target);
|
|
147
|
+
let src = fs.readFileSync(target, 'utf8');
|
|
148
|
+
|
|
149
|
+
// 只在内存里改写导出语句,把内部组件暴露给自检;不落盘。
|
|
150
|
+
if (src.indexOf('__dshTest') < 0) {
|
|
151
|
+
const EXPORT_RE = /return\s*\{\s*inject\s*,\s*apply\s*\};/;
|
|
152
|
+
if (!EXPORT_RE.test(src)) {
|
|
153
|
+
throw new Error('client.js: 既没有 __dshTest,也找不到 `return { inject, apply };` —— 导出结构变了?');
|
|
154
|
+
}
|
|
155
|
+
src = src.replace(EXPORT_RE,
|
|
156
|
+
'return { inject, apply, __dshTest: { deriveAgents: deriveAgents, MonitorBar: MonitorBar } };');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const factoryFn = new Function(
|
|
160
|
+
'window', 'document', 'localStorage', 'fetch', 'console', '__filename', '__dirname', src,
|
|
161
|
+
);
|
|
162
|
+
factoryFn(win, doc, storage, fakeFetch, console, target, path.dirname(target));
|
|
163
|
+
|
|
164
|
+
if (!captured || typeof captured.factory !== 'function') {
|
|
165
|
+
throw new Error('client.js 没有调用 window.__ModuleLoader__.load({ factory })');
|
|
166
|
+
}
|
|
167
|
+
const mod = captured.factory((name) => {
|
|
168
|
+
if (name === 'react' || name === 'React') return React;
|
|
169
|
+
throw new Error('unexpected require("' + name + '") — harness 只桩了 react');
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// 1) 走一遍 apply():验证 inject 链路会注册 shell.overlay 组件。
|
|
173
|
+
const registered = [];
|
|
174
|
+
const ready = {
|
|
175
|
+
effect: (fn) => fn(),
|
|
176
|
+
slots: {
|
|
177
|
+
inject: (name, cb) => { if (typeof cb === 'function') return cb(); return undefined; },
|
|
178
|
+
register: (spec, render) => { registered.push({ spec: spec || {}, render }); return spec; },
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
const ctx = {
|
|
182
|
+
inject: (deps, cb) => cb(ready),
|
|
183
|
+
get: () => null,
|
|
184
|
+
effect: (fn) => fn(),
|
|
185
|
+
slots: ready.slots,
|
|
186
|
+
};
|
|
187
|
+
if (typeof mod.apply !== 'function') throw new Error('模块没有导出 apply()');
|
|
188
|
+
mod.apply(ctx);
|
|
189
|
+
if (!registered.length) throw new Error('apply() 没有注册任何组件到 shell.overlay');
|
|
190
|
+
const entry = registered[registered.length - 1];
|
|
191
|
+
if (typeof entry.render !== 'function') throw new Error('slots.register 的 render 不是函数');
|
|
192
|
+
|
|
193
|
+
// 2) 真的把注册出来的组件渲染一次。
|
|
194
|
+
const tree = renderNode(React.createElement(entry.render, {}));
|
|
195
|
+
if (!tree.length) throw new Error('FloorDock 渲染结果为空');
|
|
196
|
+
const rootTag = tree[0].tag;
|
|
197
|
+
if (typeof rootTag !== 'string') throw new Error('FloorDock 顶层不是 DOM 标签: ' + String(rootTag));
|
|
198
|
+
if (!tree[0].props.className || String(tree[0].props.className).indexOf('fg-') !== 0) {
|
|
199
|
+
throw new Error('FloorDock 顶层缺少 fg-* className: ' + JSON.stringify(tree[0].props.className));
|
|
200
|
+
}
|
|
201
|
+
const dockNodes = countNodes(tree);
|
|
202
|
+
|
|
203
|
+
// 3) 用 5 个假 agent 渲染 IsoFloor(满屏场景),确保场景层也能画出来。
|
|
204
|
+
const test = mod.__dshTest;
|
|
205
|
+
if (!test || typeof test.MonitorBar !== 'function' || typeof test.deriveAgents !== 'function') {
|
|
206
|
+
throw new Error('client.js 没有暴露 __dshTest.MonitorBar / deriveAgents');
|
|
207
|
+
}
|
|
208
|
+
const now = Date.now();
|
|
209
|
+
const sessions = [
|
|
210
|
+
{ id: 's1', title: 'MY', running: true, step: 10, turn: 2, toolCalls: 68, tokensIn: 90000, tokensOut: 30000, lastTool: { name: 'bash', target: 'pnpm run build' }, files: [{ name: 'client.js', write: true }], updatedAt: now },
|
|
211
|
+
{ id: 's2', title: 'dsh-skill-pilot', running: false, step: 1, turn: 1, toolCalls: 41, tokensIn: 20000, tokensOut: 2000, updatedAt: now - 120000 },
|
|
212
|
+
{ id: 's3', title: 'Mnemon · Idle review', running: false, step: 3, turn: 1, toolCalls: 3, updatedAt: now - 3 * 600000 },
|
|
213
|
+
{ id: 's4', title: '执行一条 bash 命令:sleep 25', running: false, step: 1, turn: 1, toolCalls: 1, updatedAt: now - 4 * 600000 },
|
|
214
|
+
{ id: 's5', title: '子代理 · token-econ', running: true, parent: 's1', step: 4, turn: 1, toolCalls: 12, tokensIn: 5000, tokensOut: 900, lastTool: { name: 'grep', target: 'token' }, files: [{ name: 'index.js', write: false }], updatedAt: now },
|
|
215
|
+
];
|
|
216
|
+
const ordered = test.deriveAgents({ sessions });
|
|
217
|
+
if (ordered.length !== 5) throw new Error('deriveAgents 期望 5 个 agent,实际 ' + ordered.length);
|
|
218
|
+
if (ordered.filter((o) => o.depth === 1).length !== 1) throw new Error('deriveAgents 没把子代理排成 depth 1');
|
|
219
|
+
|
|
220
|
+
const bar = renderNode(React.createElement(test.MonitorBar, { ctx: ctx }));
|
|
221
|
+
if (!bar.length || bar[0].tag !== 'div') throw new Error('MonitorBar 顶层不是 div');
|
|
222
|
+
const barNodes = countNodes(bar);
|
|
223
|
+
const expanded = renderNode(React.createElement(test.MonitorBar, { ctx: ctx, initialData: { sessions } }));
|
|
224
|
+
let rowCount = 0;
|
|
225
|
+
(function walk3(n) {
|
|
226
|
+
if (!n || typeof n !== 'object') return;
|
|
227
|
+
const cls = n.props && n.props.className;
|
|
228
|
+
if (typeof cls === 'string' && cls.indexOf('fg-row') === 0) rowCount++;
|
|
229
|
+
for (const c of n.children || []) walk3(c);
|
|
230
|
+
})(expanded[0]);
|
|
231
|
+
if (rowCount !== 5) throw new Error('展开状态应渲染 5 行,实际 ' + rowCount);
|
|
232
|
+
|
|
233
|
+
const row = renderNode(React.createElement(test.MonitorRow, { agent: ordered[0], onOpen: () => {} }));
|
|
234
|
+
if (!row.length || row[0].tag !== 'div') throw new Error('MonitorRow 顶层不是 div');
|
|
235
|
+
if (String(row[0].props.className).indexOf('fg-row') !== 0) throw new Error('MonitorRow 缺少 fg-row className');
|
|
236
|
+
|
|
237
|
+
// 4) 跑一次 effect(useFloor 会发起一次假 fetch),确认轮询逻辑不炸。
|
|
238
|
+
for (const fn of effects) {
|
|
239
|
+
const cleanup = fn();
|
|
240
|
+
if (typeof cleanup === 'function') cleanup();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
console.log(' client : ' + target);
|
|
244
|
+
console.log(' dock : <' + rootTag + ' class="' + tree[0].props.className + '"> (' + dockNodes + ' nodes)');
|
|
245
|
+
console.log(' bar : <div fg-root> (' + barNodes + ' nodes, ' + ordered.length + ' agents)');
|
|
246
|
+
console.log(' effects: ' + effects.length + ' 个已执行');
|
|
247
|
+
console.log('render ok');
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
main();
|
|
252
|
+
} catch (err) {
|
|
253
|
+
fail(err);
|
|
254
|
+
}
|