@0perator/operator 0.1.30 → 0.1.31
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/dashboard/README.md +62 -0
- package/dashboard/index.html +527 -0
- package/dashboard/server.mjs +346 -0
- package/dist/cli.js +35 -1
- package/package.json +2 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Swarm Console
|
|
2
|
+
|
|
3
|
+
Live observability dashboard for Operator agent sessions. Renders the human-supervision
|
|
4
|
+
surface for a swarm of Operator sessions: tool activity, token/turn throughput, tier
|
|
5
|
+
denials (security), remote-control state, and service health — all from the frozen
|
|
6
|
+
`OperatorEvent` wire shape (v1) in `kode-tsi/src/telemetry/events.ts`.
|
|
7
|
+
|
|
8
|
+
Zero dependencies — Node.js standard library only. No `npm install` needed.
|
|
9
|
+
|
|
10
|
+
## Run it
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
cd kode-tsi/dashboard
|
|
14
|
+
node server.mjs
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Listens on port 8899 by default. Override with `PORT`:
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
PORT=9000 node server.mjs
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Open `http://127.0.0.1:8899/` in a browser.
|
|
24
|
+
|
|
25
|
+
## Point Operator at it
|
|
26
|
+
|
|
27
|
+
Operator's `EventSink` posts each `OperatorEvent` to `KODE_TELEMETRY_URL` (fire-and-forget)
|
|
28
|
+
and always appends to `~/.axe/operator/events.jsonl` regardless. Point the URL at this
|
|
29
|
+
server's `/events` endpoint:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
KODE_TELEMETRY_URL=http://127.0.0.1:8899/events operator
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The server also reads directly from `~/.axe/operator/events.jsonl` on boot (backfill), so
|
|
36
|
+
even without `KODE_TELEMETRY_URL` set, restarting the dashboard after Operator has been
|
|
37
|
+
running will repopulate recent history from that file. Override the file path with
|
|
38
|
+
`KODE_EVENTS_FILE` (or `KODE_AUDIT_FILE`), matching the env vars `EventSink` itself reads.
|
|
39
|
+
|
|
40
|
+
## Endpoints
|
|
41
|
+
|
|
42
|
+
- `POST /events` — receive one `OperatorEvent`, or a JSON array of them. Validates
|
|
43
|
+
`v === 1` and the required fields; malformed input returns `400` and is dropped
|
|
44
|
+
without affecting the server. Valid events are kept in a ~2000-event in-memory ring
|
|
45
|
+
buffer, appended to the JSONL file (best-effort, never blocks the response), and
|
|
46
|
+
broadcast to any connected SSE clients.
|
|
47
|
+
- `GET /events/stream` — Server-Sent Events. Replays the ring buffer, then streams new
|
|
48
|
+
events live as `event: operator-event` messages.
|
|
49
|
+
- `GET /api/state` — JSON snapshot: summary tiles, a per-session rollup (last activity,
|
|
50
|
+
current tool/activity, tier, surface, cumulative tokens, turn count, ctx%, remote-control
|
|
51
|
+
state), recent tier-denials (last hour), and service health.
|
|
52
|
+
- `GET /` — the dashboard page (`index.html`), self-contained (inline CSS/JS, no external
|
|
53
|
+
hosts).
|
|
54
|
+
|
|
55
|
+
## Notes
|
|
56
|
+
|
|
57
|
+
- The dashboard page shows clearly-marked example rows ("waiting for events") only when
|
|
58
|
+
it has received nothing live yet; the moment a real event arrives, the example data is
|
|
59
|
+
cleared.
|
|
60
|
+
- Session rollups (cumulative tokens, turn count, etc.) are kept in a persistent map that
|
|
61
|
+
is never evicted, so they survive past events rolling off the ~2000-event ring buffer
|
|
62
|
+
used for the live feed and short time-window stats (tools/min, active-sessions).
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<title>Swarm Console</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root {
|
|
9
|
+
color-scheme: light;
|
|
10
|
+
--surface-0: #f9f9f7;
|
|
11
|
+
--surface-1: #fcfcfb;
|
|
12
|
+
--surface-2: #f2f1ee;
|
|
13
|
+
--text-primary: #0b0b0b;
|
|
14
|
+
--text-secondary: #52514e;
|
|
15
|
+
--text-muted: #898781;
|
|
16
|
+
--gridline: #e1e0d9;
|
|
17
|
+
--border: rgba(11,11,11,0.10);
|
|
18
|
+
--accent: #2a78d6;
|
|
19
|
+
--accent-ink: #ffffff;
|
|
20
|
+
--status-good: #0ca30c;
|
|
21
|
+
--status-warning: #b8790f;
|
|
22
|
+
--status-serious: #c65a34;
|
|
23
|
+
--status-critical: #d03b3b;
|
|
24
|
+
--id-cli: #2a78d6;
|
|
25
|
+
--id-web: #1baf7a;
|
|
26
|
+
--id-mobile: #4a3aa7;
|
|
27
|
+
padding-top: env(safe-area-inset-top, 0px);
|
|
28
|
+
padding-bottom: env(safe-area-inset-bottom, 0px);
|
|
29
|
+
}
|
|
30
|
+
@media (prefers-color-scheme: dark) {
|
|
31
|
+
:root:not([data-theme="light"]) {
|
|
32
|
+
color-scheme: dark;
|
|
33
|
+
--surface-0: #0d0d0d;
|
|
34
|
+
--surface-1: #1a1a19;
|
|
35
|
+
--surface-2: #232322;
|
|
36
|
+
--text-primary: #ffffff;
|
|
37
|
+
--text-secondary: #c3c2b7;
|
|
38
|
+
--text-muted: #898781;
|
|
39
|
+
--gridline: #2c2c2a;
|
|
40
|
+
--border: rgba(255,255,255,0.10);
|
|
41
|
+
--accent: #3987e5;
|
|
42
|
+
--accent-ink: #ffffff;
|
|
43
|
+
--status-good: #0ca30c;
|
|
44
|
+
--status-warning: #d99a1f;
|
|
45
|
+
--status-serious: #e0805a;
|
|
46
|
+
--status-critical: #e66767;
|
|
47
|
+
--id-cli: #3987e5;
|
|
48
|
+
--id-web: #199e70;
|
|
49
|
+
--id-mobile: #9085e9;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
:root[data-theme="dark"] {
|
|
53
|
+
color-scheme: dark;
|
|
54
|
+
--surface-0: #0d0d0d;
|
|
55
|
+
--surface-1: #1a1a19;
|
|
56
|
+
--surface-2: #232322;
|
|
57
|
+
--text-primary: #ffffff;
|
|
58
|
+
--text-secondary: #c3c2b7;
|
|
59
|
+
--text-muted: #898781;
|
|
60
|
+
--gridline: #2c2c2a;
|
|
61
|
+
--border: rgba(255,255,255,0.10);
|
|
62
|
+
--accent: #3987e5;
|
|
63
|
+
--accent-ink: #ffffff;
|
|
64
|
+
--status-good: #0ca30c;
|
|
65
|
+
--status-warning: #d99a1f;
|
|
66
|
+
--status-serious: #e0805a;
|
|
67
|
+
--status-critical: #e66767;
|
|
68
|
+
--id-cli: #3987e5;
|
|
69
|
+
--id-web: #199e70;
|
|
70
|
+
--id-mobile: #9085e9;
|
|
71
|
+
}
|
|
72
|
+
* { box-sizing: border-box; }
|
|
73
|
+
img { max-width: 100%; }
|
|
74
|
+
[hidden] { display: none !important; }
|
|
75
|
+
body {
|
|
76
|
+
margin: 0;
|
|
77
|
+
background: var(--surface-0);
|
|
78
|
+
color: var(--text-primary);
|
|
79
|
+
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
80
|
+
padding: 0 max(16px, env(safe-area-inset-left, 0px)) 40px max(16px, env(safe-area-inset-right, 0px));
|
|
81
|
+
}
|
|
82
|
+
.num { font-variant-numeric: tabular-nums; }
|
|
83
|
+
a { color: var(--accent); }
|
|
84
|
+
|
|
85
|
+
header.topbar {
|
|
86
|
+
position: sticky;
|
|
87
|
+
top: env(safe-area-inset-top, 0px);
|
|
88
|
+
z-index: 10;
|
|
89
|
+
display: flex;
|
|
90
|
+
align-items: center;
|
|
91
|
+
gap: 12px;
|
|
92
|
+
padding: 14px 0;
|
|
93
|
+
background: var(--surface-0);
|
|
94
|
+
border-bottom: 1px solid var(--gridline);
|
|
95
|
+
margin-bottom: 18px;
|
|
96
|
+
}
|
|
97
|
+
.brand { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }
|
|
98
|
+
.brand small { font-weight: 500; color: var(--text-muted); margin-left: 6px; }
|
|
99
|
+
.spacer { flex: 1; }
|
|
100
|
+
.conn-dot {
|
|
101
|
+
width: 8px; height: 8px; border-radius: 50%;
|
|
102
|
+
background: var(--text-muted); display: inline-block; margin-right: 6px;
|
|
103
|
+
}
|
|
104
|
+
.conn-dot.live { background: var(--status-good); }
|
|
105
|
+
.conn-dot.down { background: var(--status-critical); }
|
|
106
|
+
.conn-label { color: var(--text-secondary); font-size: 12px; }
|
|
107
|
+
button.themeBtn {
|
|
108
|
+
border: 1px solid var(--border);
|
|
109
|
+
background: var(--surface-1);
|
|
110
|
+
color: var(--text-primary);
|
|
111
|
+
border-radius: 6px;
|
|
112
|
+
padding: 6px 10px;
|
|
113
|
+
font: inherit;
|
|
114
|
+
cursor: pointer;
|
|
115
|
+
}
|
|
116
|
+
button.themeBtn:hover { background: var(--surface-2); }
|
|
117
|
+
|
|
118
|
+
.banner {
|
|
119
|
+
background: var(--surface-1);
|
|
120
|
+
border: 1px dashed var(--border);
|
|
121
|
+
color: var(--text-secondary);
|
|
122
|
+
border-radius: 8px;
|
|
123
|
+
padding: 10px 14px;
|
|
124
|
+
margin-bottom: 16px;
|
|
125
|
+
font-size: 13px;
|
|
126
|
+
}
|
|
127
|
+
.banner strong { color: var(--text-primary); }
|
|
128
|
+
|
|
129
|
+
h2 {
|
|
130
|
+
font-size: 12px;
|
|
131
|
+
text-transform: uppercase;
|
|
132
|
+
letter-spacing: 0.06em;
|
|
133
|
+
color: var(--text-muted);
|
|
134
|
+
margin: 24px 0 10px;
|
|
135
|
+
font-weight: 600;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
.tiles {
|
|
139
|
+
display: grid;
|
|
140
|
+
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
|
141
|
+
gap: 10px;
|
|
142
|
+
}
|
|
143
|
+
.tile {
|
|
144
|
+
background: var(--surface-1);
|
|
145
|
+
border: 1px solid var(--border);
|
|
146
|
+
border-radius: 10px;
|
|
147
|
+
padding: 12px 14px;
|
|
148
|
+
}
|
|
149
|
+
.tile .label { color: var(--text-muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; }
|
|
150
|
+
.tile .value { font-size: 26px; font-weight: 700; margin-top: 4px; }
|
|
151
|
+
.tile .value.warn { color: var(--status-warning); }
|
|
152
|
+
.tile .value.bad { color: var(--status-critical); }
|
|
153
|
+
.tile .sub { font-size: 11px; color: var(--text-muted); margin-top: 2px; }
|
|
154
|
+
|
|
155
|
+
.sessions {
|
|
156
|
+
display: grid;
|
|
157
|
+
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
|
158
|
+
gap: 10px;
|
|
159
|
+
}
|
|
160
|
+
.empty-note { color: var(--text-muted); font-size: 12px; padding: 8px 0; }
|
|
161
|
+
.card {
|
|
162
|
+
background: var(--surface-1);
|
|
163
|
+
border: 1px solid var(--border);
|
|
164
|
+
border-radius: 10px;
|
|
165
|
+
padding: 12px 14px;
|
|
166
|
+
position: relative;
|
|
167
|
+
}
|
|
168
|
+
.card.demo { opacity: 0.72; }
|
|
169
|
+
.card-top { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
|
170
|
+
.session-id { font-weight: 600; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
171
|
+
.badge {
|
|
172
|
+
font-size: 10px;
|
|
173
|
+
font-weight: 600;
|
|
174
|
+
text-transform: uppercase;
|
|
175
|
+
letter-spacing: 0.03em;
|
|
176
|
+
border-radius: 4px;
|
|
177
|
+
padding: 2px 6px;
|
|
178
|
+
border: 1px solid var(--border);
|
|
179
|
+
color: var(--text-secondary);
|
|
180
|
+
white-space: nowrap;
|
|
181
|
+
}
|
|
182
|
+
.badge.surface-cli { border-color: var(--id-cli); color: var(--id-cli); }
|
|
183
|
+
.badge.surface-web { border-color: var(--id-web); color: var(--id-web); }
|
|
184
|
+
.badge.surface-mobile { border-color: var(--id-mobile); color: var(--id-mobile); }
|
|
185
|
+
.rc-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--text-muted); display: inline-block; margin-right: 5px; }
|
|
186
|
+
.rc-dot.on { background: var(--status-good); }
|
|
187
|
+
.card-row { display: flex; justify-content: space-between; font-size: 12px; color: var(--text-secondary); margin-top: 4px; }
|
|
188
|
+
.card-row .v { color: var(--text-primary); font-weight: 600; }
|
|
189
|
+
.activity { font-size: 12px; color: var(--text-primary); margin-top: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
190
|
+
.tag-example {
|
|
191
|
+
position: absolute; top: 8px; right: 8px;
|
|
192
|
+
font-size: 9px; text-transform: uppercase; letter-spacing: 0.05em;
|
|
193
|
+
color: var(--text-muted); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
.feed { max-width: 100%; }
|
|
197
|
+
.feed-list { display: flex; flex-direction: column; gap: 4px; }
|
|
198
|
+
.feed-row {
|
|
199
|
+
display: grid;
|
|
200
|
+
grid-template-columns: 82px 90px 1fr auto;
|
|
201
|
+
gap: 10px;
|
|
202
|
+
align-items: center;
|
|
203
|
+
padding: 7px 10px;
|
|
204
|
+
border-radius: 6px;
|
|
205
|
+
border-left: 3px solid var(--gridline);
|
|
206
|
+
background: var(--surface-1);
|
|
207
|
+
font-size: 12.5px;
|
|
208
|
+
}
|
|
209
|
+
.feed-row.good { border-left-color: var(--status-good); }
|
|
210
|
+
.feed-row.warning { border-left-color: var(--status-warning); }
|
|
211
|
+
.feed-row.serious { border-left-color: var(--status-serious); }
|
|
212
|
+
.feed-row.critical { border-left-color: var(--status-critical); }
|
|
213
|
+
.feed-row.demo { opacity: 0.65; }
|
|
214
|
+
.feed-ts { color: var(--text-muted); font-size: 11px; }
|
|
215
|
+
.feed-kind { color: var(--text-secondary); font-size: 11px; text-transform: uppercase; letter-spacing: 0.03em; }
|
|
216
|
+
.feed-detail { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
217
|
+
.feed-detail .sess { color: var(--text-muted); margin-right: 6px; }
|
|
218
|
+
.sec-alert {
|
|
219
|
+
font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
|
|
220
|
+
color: var(--status-critical); border: 1px solid var(--status-critical); border-radius: 4px; padding: 1px 5px;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
@media (max-width: 480px) {
|
|
224
|
+
.feed-row { grid-template-columns: 62px 1fr; grid-template-areas: "ts kind" "detail detail" "flag flag"; row-gap: 2px; }
|
|
225
|
+
.feed-ts { grid-area: ts; }
|
|
226
|
+
.feed-kind { grid-area: kind; text-align: right; }
|
|
227
|
+
.feed-detail { grid-area: detail; }
|
|
228
|
+
.sec-alert { grid-area: flag; justify-self: start; }
|
|
229
|
+
}
|
|
230
|
+
</style>
|
|
231
|
+
</head>
|
|
232
|
+
<body>
|
|
233
|
+
|
|
234
|
+
<header class="topbar">
|
|
235
|
+
<div class="brand">Swarm Console<small>Operator observability</small></div>
|
|
236
|
+
<div class="spacer"></div>
|
|
237
|
+
<span><span class="conn-dot" id="connDot"></span><span class="conn-label" id="connLabel">connecting…</span></span>
|
|
238
|
+
<button class="themeBtn" id="themeToggle" type="button">Theme</button>
|
|
239
|
+
</header>
|
|
240
|
+
|
|
241
|
+
<div class="banner" id="waitingBanner" hidden>
|
|
242
|
+
<strong>Waiting for events.</strong> No live OperatorEvents received yet — the rows below are
|
|
243
|
+
<strong>example data</strong> so you can see the layout. Point Operator at this server with
|
|
244
|
+
<code>KODE_TELEMETRY_URL</code> to replace them.
|
|
245
|
+
</div>
|
|
246
|
+
|
|
247
|
+
<h2>Overview</h2>
|
|
248
|
+
<div class="tiles" id="tiles"></div>
|
|
249
|
+
|
|
250
|
+
<h2>Sessions</h2>
|
|
251
|
+
<div class="sessions" id="sessionsGrid"></div>
|
|
252
|
+
<div class="empty-note" id="sessionsEmpty" hidden>No sessions observed yet.</div>
|
|
253
|
+
|
|
254
|
+
<h2>Live feed</h2>
|
|
255
|
+
<div class="feed-list" id="feedList"></div>
|
|
256
|
+
|
|
257
|
+
<script>
|
|
258
|
+
(function () {
|
|
259
|
+
"use strict";
|
|
260
|
+
|
|
261
|
+
// ---- theme toggle ---------------------------------------------------------
|
|
262
|
+
var root = document.documentElement;
|
|
263
|
+
try {
|
|
264
|
+
var saved = localStorage.getItem("swarm-console-theme");
|
|
265
|
+
if (saved === "light" || saved === "dark") root.setAttribute("data-theme", saved);
|
|
266
|
+
} catch (e) { /* storage unavailable — fall back to system theme */ }
|
|
267
|
+
document.getElementById("themeToggle").addEventListener("click", function () {
|
|
268
|
+
var cur = root.getAttribute("data-theme");
|
|
269
|
+
var next = cur === "dark" ? "light" : cur === "light" ? null : (matchMedia("(prefers-color-scheme: dark)").matches ? "light" : "dark");
|
|
270
|
+
if (next) root.setAttribute("data-theme", next); else root.removeAttribute("data-theme");
|
|
271
|
+
try { localStorage.setItem("swarm-console-theme", next || ""); } catch (e) {}
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// ---- state ------------------------------------------------------------
|
|
275
|
+
var RING_MAX = 2000;
|
|
276
|
+
var FEED_RENDER_MAX = 250;
|
|
277
|
+
var ring = []; // raw events, oldest first
|
|
278
|
+
var sessions = new Map();
|
|
279
|
+
var services = new Map();
|
|
280
|
+
var denials = []; // {ts, session, event, detail}
|
|
281
|
+
var sawRealEvent = false;
|
|
282
|
+
var demoMode = false;
|
|
283
|
+
|
|
284
|
+
function esc(s) {
|
|
285
|
+
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
|
|
286
|
+
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c];
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
function shortSession(id) {
|
|
290
|
+
return id && id.length > 18 ? id.slice(0, 8) + "…" + id.slice(-6) : id;
|
|
291
|
+
}
|
|
292
|
+
function fmtTime(ts) {
|
|
293
|
+
try { return new Date(ts).toLocaleTimeString(); } catch (e) { return ts; }
|
|
294
|
+
}
|
|
295
|
+
function fmtNum(n) {
|
|
296
|
+
return typeof n === "number" ? n.toLocaleString() : "—";
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function rollupFor(id) {
|
|
300
|
+
var s = sessions.get(id);
|
|
301
|
+
if (!s) {
|
|
302
|
+
s = { session: id, tier: undefined, surface: undefined, lastActivity: undefined,
|
|
303
|
+
currentActivity: undefined, lastTool: undefined, tokens: 0, turns: 0,
|
|
304
|
+
ctxPct: undefined, tokPerSec: undefined, rc: false, demo: false };
|
|
305
|
+
sessions.set(id, s);
|
|
306
|
+
}
|
|
307
|
+
return s;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function applyEvent(e) {
|
|
311
|
+
var s = rollupFor(e.session);
|
|
312
|
+
s.tier = e.actor.tier;
|
|
313
|
+
s.surface = e.actor.surface;
|
|
314
|
+
s.lastActivity = e.ts;
|
|
315
|
+
s.demo = !!e.__demo;
|
|
316
|
+
if (e.kind === "tool" && e.tool) {
|
|
317
|
+
s.lastTool = e.tool;
|
|
318
|
+
s.currentActivity = "tool: " + e.tool.name + " (" + e.tool.outcome + ")";
|
|
319
|
+
} else if (e.kind === "turn" && e.turn) {
|
|
320
|
+
s.tokens += Number(e.turn.tokens) || 0;
|
|
321
|
+
s.turns += 1;
|
|
322
|
+
s.ctxPct = e.turn.ctxPct;
|
|
323
|
+
s.tokPerSec = e.turn.tokPerSec;
|
|
324
|
+
s.currentActivity = "turn via " + e.turn.route;
|
|
325
|
+
} else if (e.kind === "control" && e.control) {
|
|
326
|
+
s.currentActivity = "control: " + e.control.event;
|
|
327
|
+
if (e.control.event === "rc_connected") s.rc = true;
|
|
328
|
+
else if (e.control.event === "rc_disconnected") s.rc = false;
|
|
329
|
+
if (e.control.event === "tool_denied_by_tier" || e.control.event === "signature_required") {
|
|
330
|
+
denials.push({ ts: e.ts, session: e.session, event: e.control.event, detail: e.control.detail });
|
|
331
|
+
if (denials.length > 500) denials.shift();
|
|
332
|
+
}
|
|
333
|
+
} else if (e.kind === "service" && e.service) {
|
|
334
|
+
services.set(e.service.name, { state: e.service.state, ts: e.ts, demo: !!e.__demo });
|
|
335
|
+
s.currentActivity = "service " + e.service.name + ": " + e.service.state;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function classify(e) {
|
|
340
|
+
// Maps an event to a status role: good | warning | serious | critical | neutral
|
|
341
|
+
if (e.kind === "tool" && e.tool) {
|
|
342
|
+
if (e.tool.outcome === "ok") return "good";
|
|
343
|
+
if (e.tool.outcome === "denied") return "critical";
|
|
344
|
+
if (e.tool.outcome === "error") return "serious";
|
|
345
|
+
if (e.tool.decision === "deny") return "critical";
|
|
346
|
+
}
|
|
347
|
+
if (e.kind === "control" && e.control) {
|
|
348
|
+
if (e.control.event === "tool_denied_by_tier" || e.control.event === "signature_required") return "critical";
|
|
349
|
+
if (e.control.event === "rc_disconnected") return "warning";
|
|
350
|
+
if (e.control.event === "rc_connected" || e.control.event === "tier_resolved") return "good";
|
|
351
|
+
}
|
|
352
|
+
if (e.kind === "service" && e.service) {
|
|
353
|
+
if (e.service.state === "down") return "critical";
|
|
354
|
+
return "good";
|
|
355
|
+
}
|
|
356
|
+
return "neutral";
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function isSecurityAlert(e) {
|
|
360
|
+
return e.kind === "control" && e.control &&
|
|
361
|
+
(e.control.event === "tool_denied_by_tier" || e.control.event === "signature_required");
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function feedDetail(e) {
|
|
365
|
+
if (e.kind === "tool" && e.tool) return e.tool.name + " · " + e.tool.decision + " → " + e.tool.outcome;
|
|
366
|
+
if (e.kind === "turn" && e.turn) return e.turn.route + " · " + e.turn.tokens + " tok" + (e.turn.tokPerSec ? " · " + e.turn.tokPerSec.toFixed(1) + " tok/s" : "") + " · ctx " + e.turn.ctxPct + "%";
|
|
367
|
+
if (e.kind === "control" && e.control) return e.control.event + (e.control.detail ? " — " + e.control.detail : "");
|
|
368
|
+
if (e.kind === "service" && e.service) return e.service.name + " → " + e.service.state;
|
|
369
|
+
return "";
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
var feedListEl = document.getElementById("feedList");
|
|
373
|
+
function prependFeedRow(e) {
|
|
374
|
+
var row = document.createElement("div");
|
|
375
|
+
var status = classify(e);
|
|
376
|
+
row.className = "feed-row " + status + (e.__demo ? " demo" : "");
|
|
377
|
+
row.innerHTML =
|
|
378
|
+
'<span class="feed-ts num">' + esc(fmtTime(e.ts)) + '</span>' +
|
|
379
|
+
'<span class="feed-kind">' + esc(e.kind) + '</span>' +
|
|
380
|
+
'<span class="feed-detail"><span class="sess">' + esc(shortSession(e.session)) + '</span>' + esc(feedDetail(e)) + '</span>' +
|
|
381
|
+
(isSecurityAlert(e) ? '<span class="sec-alert">Security</span>' : '<span></span>');
|
|
382
|
+
feedListEl.insertBefore(row, feedListEl.firstChild);
|
|
383
|
+
while (feedListEl.children.length > FEED_RENDER_MAX) feedListEl.removeChild(feedListEl.lastChild);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// ---- rendering ----------------------------------------------------------
|
|
387
|
+
var tilesEl = document.getElementById("tiles");
|
|
388
|
+
var sessionsEl = document.getElementById("sessionsGrid");
|
|
389
|
+
var sessionsEmptyEl = document.getElementById("sessionsEmpty");
|
|
390
|
+
|
|
391
|
+
function renderTiles() {
|
|
392
|
+
var now = Date.now();
|
|
393
|
+
var rows = Array.from(sessions.values());
|
|
394
|
+
var active = rows.filter(function (s) { return s.lastActivity && now - Date.parse(s.lastActivity) <= 5 * 60 * 1000; }).length;
|
|
395
|
+
var toolsMin = ring.filter(function (e) { return e.kind === "tool" && now - Date.parse(e.ts) <= 60 * 1000; }).length;
|
|
396
|
+
var totalTokens = rows.reduce(function (sum, s) { return sum + (s.tokens || 0); }, 0);
|
|
397
|
+
var recentDenials = denials.filter(function (d) { return now - Date.parse(d.ts) <= 60 * 60 * 1000; }).length;
|
|
398
|
+
var svc = Array.from(services.values());
|
|
399
|
+
var up = svc.filter(function (s) { return s.state === "up" || s.state === "started"; }).length;
|
|
400
|
+
var down = svc.filter(function (s) { return s.state === "down"; }).length;
|
|
401
|
+
|
|
402
|
+
var tiles = [
|
|
403
|
+
{ label: "Active sessions", value: active },
|
|
404
|
+
{ label: "Tools / min", value: toolsMin },
|
|
405
|
+
{ label: "Total tokens", value: fmtNum(totalTokens) },
|
|
406
|
+
{ label: "Tier denials (1h)", value: recentDenials, cls: recentDenials > 0 ? "bad" : "" },
|
|
407
|
+
{ label: "Services", value: up + " up / " + down + " down", cls: down > 0 ? "warn" : "" },
|
|
408
|
+
];
|
|
409
|
+
tilesEl.innerHTML = tiles.map(function (t) {
|
|
410
|
+
return '<div class="tile"><div class="label">' + esc(t.label) + '</div>' +
|
|
411
|
+
'<div class="value num ' + (t.cls || "") + '">' + t.value + '</div>' +
|
|
412
|
+
(demoMode ? '<div class="sub">example data</div>' : '') + '</div>';
|
|
413
|
+
}).join("");
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function renderSessions() {
|
|
417
|
+
var rows = Array.from(sessions.values()).sort(function (a, b) {
|
|
418
|
+
return (b.lastActivity || "").localeCompare(a.lastActivity || "");
|
|
419
|
+
});
|
|
420
|
+
sessionsEmptyEl.hidden = rows.length > 0;
|
|
421
|
+
sessionsEl.innerHTML = rows.map(function (s) {
|
|
422
|
+
var tokPerSec = typeof s.tokPerSec === "number" ? s.tokPerSec.toFixed(1) : "—";
|
|
423
|
+
var ctx = typeof s.ctxPct === "number" ? s.ctxPct + "%" : "—";
|
|
424
|
+
return '<div class="card' + (s.demo ? ' demo' : '') + '">' +
|
|
425
|
+
(s.demo ? '<span class="tag-example">example</span>' : '') +
|
|
426
|
+
'<div class="card-top">' +
|
|
427
|
+
'<span class="session-id" title="' + esc(s.session) + '">' + esc(shortSession(s.session)) + '</span>' +
|
|
428
|
+
'<span class="badge surface-' + esc(s.surface) + '">' + esc(s.surface) + '</span>' +
|
|
429
|
+
'<span class="badge">' + esc(s.tier) + '</span>' +
|
|
430
|
+
'</div>' +
|
|
431
|
+
'<div class="activity">' + esc(s.currentActivity || "idle") + '</div>' +
|
|
432
|
+
'<div class="card-row"><span>Tokens</span><span class="v num">' + fmtNum(s.tokens) + ' (' + fmtNum(s.turns) + ' turns)</span></div>' +
|
|
433
|
+
'<div class="card-row"><span>Throughput</span><span class="v num">' + tokPerSec + ' tok/s</span></div>' +
|
|
434
|
+
'<div class="card-row"><span>Context</span><span class="v num">' + ctx + '</span></div>' +
|
|
435
|
+
'<div class="card-row"><span>Remote control</span><span class="v"><span class="rc-dot' + (s.rc ? ' on' : '') + '"></span>' + (s.rc ? "connected" : "off") + '</span></div>' +
|
|
436
|
+
'<div class="card-row"><span>Last activity</span><span class="v">' + esc(fmtTime(s.lastActivity)) + '</span></div>' +
|
|
437
|
+
'</div>';
|
|
438
|
+
}).join("");
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function renderAll() {
|
|
442
|
+
renderTiles();
|
|
443
|
+
renderSessions();
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// ---- ingest ---------------------------------------------------------------
|
|
447
|
+
function ingest(e, opts) {
|
|
448
|
+
opts = opts || {};
|
|
449
|
+
ring.push(e);
|
|
450
|
+
if (ring.length > RING_MAX) ring.shift();
|
|
451
|
+
applyEvent(e);
|
|
452
|
+
if (!opts.skipFeed) prependFeedRow(e);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ---- demo data --------------------------------------------------------
|
|
456
|
+
function demoEvents() {
|
|
457
|
+
var now = Date.now();
|
|
458
|
+
var iso = function (offsetMs) { return new Date(now - offsetMs).toISOString(); };
|
|
459
|
+
var s1 = "cli-a1b2c3d4e5f6", s2 = "web-9f8e7d6c5b4a", s3 = "mobile-1122334455";
|
|
460
|
+
var mk = function (o) { o.v = 1; o.__demo = true; return o; };
|
|
461
|
+
return [
|
|
462
|
+
mk({ ts: iso(240000), kind: "control", session: s1, actor: { tier: "admin", surface: "cli" }, control: { event: "tier_resolved", detail: "admin" } }),
|
|
463
|
+
mk({ ts: iso(230000), kind: "tool", session: s1, actor: { tier: "admin", surface: "cli" }, tool: { name: "fs.read", args: "path=src/index.ts", decision: "allow", outcome: "ok", durationMs: 42 } }),
|
|
464
|
+
mk({ ts: iso(220000), kind: "turn", session: s1, actor: { tier: "admin", surface: "cli" }, turn: { tokens: 812, tokPerSec: 47.3, ctxPct: 18, route: "aurora", durationMs: 1900 } }),
|
|
465
|
+
mk({ ts: iso(200000), kind: "control", session: s2, actor: { tier: "readonly", surface: "web" }, control: { event: "tier_resolved", detail: "readonly" } }),
|
|
466
|
+
mk({ ts: iso(190000), kind: "tool", session: s2, actor: { tier: "readonly", surface: "web" }, tool: { name: "fleet.ssh_exec", args: "host=jl2", decision: "deny", outcome: "denied" } }),
|
|
467
|
+
mk({ ts: iso(189000), kind: "control", session: s2, actor: { tier: "readonly", surface: "web" }, control: { event: "tool_denied_by_tier", detail: "fleet.ssh_exec requires admin" } }),
|
|
468
|
+
mk({ ts: iso(150000), kind: "tool", session: s3, actor: { tier: "enterprise", surface: "mobile" }, tool: { name: "web.search", args: "q=aurora+status", decision: "ask", approved: true, outcome: "ok", durationMs: 610 } }),
|
|
469
|
+
mk({ ts: iso(120000), kind: "control", session: s3, actor: { tier: "enterprise", surface: "mobile" }, control: { event: "rc_connected", detail: "ssh:jl1" } }),
|
|
470
|
+
mk({ ts: iso(90000), kind: "turn", session: s3, actor: { tier: "enterprise", surface: "mobile" }, turn: { tokens: 340, tokPerSec: 51.0, ctxPct: 34, route: "aurora" } }),
|
|
471
|
+
mk({ ts: iso(60000), kind: "service", session: s1, actor: { tier: "admin", surface: "cli" }, service: { name: "aurora-1m", state: "up" } }),
|
|
472
|
+
mk({ ts: iso(30000), kind: "tool", session: s1, actor: { tier: "admin", surface: "cli" }, tool: { name: "code.write_file", args: "path=dashboard/server.mjs", decision: "allow", outcome: "error", durationMs: 12 } }),
|
|
473
|
+
mk({ ts: iso(10000), kind: "control", session: s2, actor: { tier: "readonly", surface: "web" }, control: { event: "signature_required", detail: "sql.migrate" } }),
|
|
474
|
+
];
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function enterDemoMode() {
|
|
478
|
+
demoMode = true;
|
|
479
|
+
document.getElementById("waitingBanner").hidden = false;
|
|
480
|
+
demoEvents().forEach(function (e) { ingest(e); });
|
|
481
|
+
renderAll();
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function exitDemoMode() {
|
|
485
|
+
if (!demoMode) return;
|
|
486
|
+
demoMode = false;
|
|
487
|
+
document.getElementById("waitingBanner").hidden = true;
|
|
488
|
+
ring = []; sessions = new Map(); services = new Map(); denials = [];
|
|
489
|
+
feedListEl.innerHTML = "";
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// ---- live connection --------------------------------------------------
|
|
493
|
+
var connDot = document.getElementById("connDot");
|
|
494
|
+
var connLabel = document.getElementById("connLabel");
|
|
495
|
+
var demoTimer = setTimeout(function () { if (!sawRealEvent) enterDemoMode(); }, 800);
|
|
496
|
+
|
|
497
|
+
if (typeof EventSource === "undefined") {
|
|
498
|
+
connLabel.textContent = "streaming unsupported";
|
|
499
|
+
} else {
|
|
500
|
+
var es = new EventSource("/events/stream");
|
|
501
|
+
es.addEventListener("open", function () {
|
|
502
|
+
connDot.className = "conn-dot live";
|
|
503
|
+
connLabel.textContent = "live";
|
|
504
|
+
});
|
|
505
|
+
es.addEventListener("error", function () {
|
|
506
|
+
connDot.className = "conn-dot down";
|
|
507
|
+
connLabel.textContent = "reconnecting…";
|
|
508
|
+
});
|
|
509
|
+
es.addEventListener("operator-event", function (msg) {
|
|
510
|
+
var e;
|
|
511
|
+
try { e = JSON.parse(msg.data); } catch (err) { return; }
|
|
512
|
+
if (!sawRealEvent) {
|
|
513
|
+
sawRealEvent = true;
|
|
514
|
+
clearTimeout(demoTimer);
|
|
515
|
+
exitDemoMode();
|
|
516
|
+
}
|
|
517
|
+
ingest(e);
|
|
518
|
+
renderAll();
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
renderAll();
|
|
523
|
+
setInterval(renderTiles, 5000); // keep time-windowed tiles (active/tools-per-min/denials) fresh even when idle
|
|
524
|
+
})();
|
|
525
|
+
</script>
|
|
526
|
+
</body>
|
|
527
|
+
</html>
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Swarm console — live observability server for Operator's OperatorEvent stream (v1, see
|
|
3
|
+
// kode-tsi/src/telemetry/events.ts). Node stdlib only, zero dependencies.
|
|
4
|
+
//
|
|
5
|
+
// Endpoints:
|
|
6
|
+
// POST /events receive one OperatorEvent, or a JSON array of them
|
|
7
|
+
// GET /events/stream Server-Sent Events: replays the ring buffer then streams live
|
|
8
|
+
// GET /api/state JSON snapshot: per-session rollup, recent tier-denials, service health
|
|
9
|
+
// GET / the dashboard page (index.html, served self-contained)
|
|
10
|
+
//
|
|
11
|
+
// This process IS the sink Operator's KODE_TELEMETRY_URL should point at:
|
|
12
|
+
// KODE_TELEMETRY_URL=http://127.0.0.1:8899/events operator
|
|
13
|
+
|
|
14
|
+
import http from "node:http";
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
|
|
21
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const PORT = Number(process.env.PORT) || 8899;
|
|
23
|
+
const RING_MAX = 2000;
|
|
24
|
+
const EVENTS_FILE = resolveHome(
|
|
25
|
+
process.env.KODE_EVENTS_FILE || process.env.KODE_AUDIT_FILE || "~/.axe/operator/events.jsonl",
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
function resolveHome(p) {
|
|
29
|
+
return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ---- in-memory state -------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
/** Ring buffer of raw events, oldest first, capped at RING_MAX — backs SSE replay and short-window stats. */
|
|
35
|
+
const ring = [];
|
|
36
|
+
let filePos = 0; // byte offset the tailer has consumed up to (set to EOF after backfill)
|
|
37
|
+
let tailBuf = ""; // carry a partial trailing line between reads
|
|
38
|
+
|
|
39
|
+
/** session id -> rollup */
|
|
40
|
+
const sessions = new Map();
|
|
41
|
+
|
|
42
|
+
/** service name -> { state, ts } */
|
|
43
|
+
const services = new Map();
|
|
44
|
+
|
|
45
|
+
/** recent tier-denial / signature-required control events, capped, newest last */
|
|
46
|
+
const denials = [];
|
|
47
|
+
const DENIALS_MAX = 500;
|
|
48
|
+
|
|
49
|
+
const KINDS = new Set(["tool", "turn", "control", "service"]);
|
|
50
|
+
const TIERS = new Set(["admin", "enterprise", "readonly"]);
|
|
51
|
+
const SURFACES = new Set(["cli", "web", "mobile"]);
|
|
52
|
+
|
|
53
|
+
function validateEvent(e) {
|
|
54
|
+
if (!e || typeof e !== "object") return "not an object";
|
|
55
|
+
if (e.v !== 1) return "unsupported v (expected 1)";
|
|
56
|
+
if (!KINDS.has(e.kind)) return "invalid kind";
|
|
57
|
+
if (typeof e.session !== "string" || !e.session) return "missing session";
|
|
58
|
+
if (!e.actor || typeof e.actor !== "object") return "missing actor";
|
|
59
|
+
if (!TIERS.has(e.actor.tier)) return "invalid actor.tier";
|
|
60
|
+
if (!SURFACES.has(e.actor.surface)) return "invalid actor.surface";
|
|
61
|
+
if (typeof e.ts !== "string") return "missing ts";
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function rollupFor(sessionId) {
|
|
66
|
+
let s = sessions.get(sessionId);
|
|
67
|
+
if (!s) {
|
|
68
|
+
s = {
|
|
69
|
+
session: sessionId,
|
|
70
|
+
tier: undefined,
|
|
71
|
+
surface: undefined,
|
|
72
|
+
sub: undefined,
|
|
73
|
+
lastActivity: undefined,
|
|
74
|
+
currentActivity: undefined,
|
|
75
|
+
currentTool: undefined,
|
|
76
|
+
lastTool: undefined,
|
|
77
|
+
tokens: 0,
|
|
78
|
+
turns: 0,
|
|
79
|
+
ctxPct: undefined,
|
|
80
|
+
tokPerSec: undefined,
|
|
81
|
+
rc: false,
|
|
82
|
+
};
|
|
83
|
+
sessions.set(sessionId, s);
|
|
84
|
+
}
|
|
85
|
+
return s;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Fold one validated event into the persistent rollups (sessions/services/denials). Never evicted by
|
|
89
|
+
* the ring buffer, so a session's cumulative totals survive even after its early events roll off. */
|
|
90
|
+
function applyToRollups(e) {
|
|
91
|
+
const s = rollupFor(e.session);
|
|
92
|
+
s.tier = e.actor.tier;
|
|
93
|
+
s.surface = e.actor.surface;
|
|
94
|
+
s.sub = e.actor.sub;
|
|
95
|
+
s.lastActivity = e.ts;
|
|
96
|
+
|
|
97
|
+
if (e.kind === "tool" && e.tool) {
|
|
98
|
+
s.currentTool = e.tool.name;
|
|
99
|
+
s.lastTool = { name: e.tool.name, decision: e.tool.decision, outcome: e.tool.outcome, ts: e.ts };
|
|
100
|
+
s.currentActivity = `tool:${e.tool.name}`;
|
|
101
|
+
} else if (e.kind === "turn" && e.turn) {
|
|
102
|
+
s.tokens += Number(e.turn.tokens) || 0;
|
|
103
|
+
s.turns += 1;
|
|
104
|
+
s.ctxPct = e.turn.ctxPct;
|
|
105
|
+
s.tokPerSec = e.turn.tokPerSec;
|
|
106
|
+
s.currentActivity = `turn:${e.turn.route}`;
|
|
107
|
+
} else if (e.kind === "control" && e.control) {
|
|
108
|
+
s.currentActivity = `control:${e.control.event}`;
|
|
109
|
+
if (e.control.event === "rc_connected") s.rc = true;
|
|
110
|
+
else if (e.control.event === "rc_disconnected") s.rc = false;
|
|
111
|
+
if (e.control.event === "tool_denied_by_tier" || e.control.event === "signature_required") {
|
|
112
|
+
denials.push({ ts: e.ts, session: e.session, event: e.control.event, detail: e.control.detail, tier: e.actor.tier });
|
|
113
|
+
if (denials.length > DENIALS_MAX) denials.splice(0, denials.length - DENIALS_MAX);
|
|
114
|
+
}
|
|
115
|
+
} else if (e.kind === "service" && e.service) {
|
|
116
|
+
services.set(e.service.name, { state: e.service.state, ts: e.ts });
|
|
117
|
+
s.currentActivity = `service:${e.service.name}:${e.service.state}`;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const sseClients = new Set();
|
|
122
|
+
|
|
123
|
+
function broadcast(e) {
|
|
124
|
+
const payload = `event: operator-event\ndata: ${JSON.stringify(e)}\n\n`;
|
|
125
|
+
for (const res of sseClients) {
|
|
126
|
+
try { res.write(payload); } catch { /* client gone, cleaned up on 'close' */ }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let appendChain = Promise.resolve();
|
|
131
|
+
function persist(e) {
|
|
132
|
+
// Fire-and-forget, serialized so lines never interleave; never awaited by the request handler.
|
|
133
|
+
appendChain = appendChain
|
|
134
|
+
.then(() => mkdir(path.dirname(EVENTS_FILE), { recursive: true }))
|
|
135
|
+
.then(() => appendFile(EVENTS_FILE, JSON.stringify(e) + "\n", "utf8"))
|
|
136
|
+
.catch(() => { /* best-effort — a write failure must never surface to the caller */ });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Ingest one validated event: ring buffer + rollups, and optionally persist/broadcast. */
|
|
140
|
+
function ingest(e, { persist: doPersist, broadcastIt }) {
|
|
141
|
+
ring.push(e);
|
|
142
|
+
if (ring.length > RING_MAX) ring.shift();
|
|
143
|
+
applyToRollups(e);
|
|
144
|
+
if (doPersist) persist(e);
|
|
145
|
+
if (broadcastIt) broadcast(e);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function backfill() {
|
|
149
|
+
let text;
|
|
150
|
+
try {
|
|
151
|
+
text = await readFile(EVENTS_FILE, "utf8");
|
|
152
|
+
} catch {
|
|
153
|
+
return; // no file yet — nothing to backfill, not an error
|
|
154
|
+
}
|
|
155
|
+
filePos = Buffer.byteLength(text, "utf8"); // tail starts at current EOF — only NEW appends stream live
|
|
156
|
+
const lines = text.split("\n").filter(Boolean);
|
|
157
|
+
const tail = lines.slice(-RING_MAX);
|
|
158
|
+
let ok = 0;
|
|
159
|
+
for (const line of tail) {
|
|
160
|
+
try {
|
|
161
|
+
const e = JSON.parse(line);
|
|
162
|
+
if (!validateEvent(e)) {
|
|
163
|
+
ingest(e, { persist: false, broadcastIt: false });
|
|
164
|
+
ok++;
|
|
165
|
+
}
|
|
166
|
+
} catch { /* skip malformed line */ }
|
|
167
|
+
}
|
|
168
|
+
if (ok) console.error(`[dashboard] backfilled ${ok} event(s) from ${EVENTS_FILE}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Live-tail the events file so EVERY Operator session shows up with zero per-session config: any session's
|
|
172
|
+
// EventSink appends to ~/.axe/operator/events.jsonl by default, and this reads new lines as they land. The
|
|
173
|
+
// file is the single source of truth — POSTs are persisted (not ingested directly), and this tailer is the
|
|
174
|
+
// SOLE ingester, so a POSTed event and a directly-appended one are never double-counted. fs.watch on the
|
|
175
|
+
// directory catches creates/renames too; a slow poll backstops filesystems where watch misses events.
|
|
176
|
+
function startTail() {
|
|
177
|
+
try { fs.mkdirSync(path.dirname(EVENTS_FILE), { recursive: true }); } catch { /* best-effort */ }
|
|
178
|
+
let reading = false;
|
|
179
|
+
const readNew = async () => {
|
|
180
|
+
if (reading) return;
|
|
181
|
+
reading = true;
|
|
182
|
+
try {
|
|
183
|
+
const stat = await fs.promises.stat(EVENTS_FILE).catch(() => null);
|
|
184
|
+
if (!stat) return;
|
|
185
|
+
if (stat.size < filePos) { filePos = 0; tailBuf = ""; } // truncated or rotated — re-read from the top
|
|
186
|
+
if (stat.size <= filePos) return;
|
|
187
|
+
const fd = await fs.promises.open(EVENTS_FILE, "r");
|
|
188
|
+
try {
|
|
189
|
+
const len = stat.size - filePos;
|
|
190
|
+
const buf = Buffer.alloc(len);
|
|
191
|
+
await fd.read(buf, 0, len, filePos);
|
|
192
|
+
filePos = stat.size;
|
|
193
|
+
tailBuf += buf.toString("utf8");
|
|
194
|
+
} finally { await fd.close(); }
|
|
195
|
+
let nl;
|
|
196
|
+
while ((nl = tailBuf.indexOf("\n")) >= 0) {
|
|
197
|
+
const line = tailBuf.slice(0, nl); tailBuf = tailBuf.slice(nl + 1);
|
|
198
|
+
if (!line.trim()) continue;
|
|
199
|
+
try { const e = JSON.parse(line); if (!validateEvent(e)) ingest(e, { persist: false, broadcastIt: true }); } catch { /* skip malformed */ }
|
|
200
|
+
}
|
|
201
|
+
} finally { reading = false; }
|
|
202
|
+
};
|
|
203
|
+
try { fs.watch(path.dirname(EVENTS_FILE), (_ev, fname) => { if (!fname || fname === path.basename(EVENTS_FILE)) void readNew(); }); } catch { /* watch unsupported — poll only */ }
|
|
204
|
+
const t = setInterval(() => void readNew(), 2000);
|
|
205
|
+
t.unref?.();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---- HTTP handlers ----------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
function sendJSON(res, code, obj) {
|
|
211
|
+
const body = JSON.stringify(obj);
|
|
212
|
+
res.writeHead(code, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body) });
|
|
213
|
+
res.end(body);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function readBody(req, limit = 1024 * 1024) {
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
let size = 0;
|
|
219
|
+
const chunks = [];
|
|
220
|
+
req.on("data", (c) => {
|
|
221
|
+
size += c.length;
|
|
222
|
+
if (size > limit) { reject(new Error("body too large")); req.destroy(); return; }
|
|
223
|
+
chunks.push(c);
|
|
224
|
+
});
|
|
225
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
226
|
+
req.on("error", reject);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function handleEvents(req, res) {
|
|
231
|
+
readBody(req)
|
|
232
|
+
.then((raw) => {
|
|
233
|
+
let parsed;
|
|
234
|
+
try {
|
|
235
|
+
parsed = raw.trim() ? JSON.parse(raw) : null;
|
|
236
|
+
} catch {
|
|
237
|
+
sendJSON(res, 400, { ok: false, error: "invalid JSON" });
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const list = Array.isArray(parsed) ? parsed : [parsed];
|
|
241
|
+
if (list.length === 0) {
|
|
242
|
+
sendJSON(res, 400, { ok: false, error: "empty payload" });
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const errors = [];
|
|
246
|
+
let accepted = 0;
|
|
247
|
+
for (const e of list) {
|
|
248
|
+
const err = validateEvent(e);
|
|
249
|
+
if (err) { errors.push(err); continue; }
|
|
250
|
+
persist(e); // append to the file; the tailer is the sole ingester (no double-count with direct writes)
|
|
251
|
+
accepted++;
|
|
252
|
+
}
|
|
253
|
+
if (accepted === 0) {
|
|
254
|
+
sendJSON(res, 400, { ok: false, error: "no valid events", details: errors });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
sendJSON(res, 200, { ok: true, accepted, rejected: list.length - accepted });
|
|
258
|
+
})
|
|
259
|
+
.catch((err) => {
|
|
260
|
+
sendJSON(res, 400, { ok: false, error: String(err && err.message || err) });
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function handleStream(req, res) {
|
|
265
|
+
res.writeHead(200, {
|
|
266
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
267
|
+
"cache-control": "no-cache, no-transform",
|
|
268
|
+
connection: "keep-alive",
|
|
269
|
+
"x-accel-buffering": "no",
|
|
270
|
+
});
|
|
271
|
+
res.write("retry: 2000\n\n");
|
|
272
|
+
for (const e of ring) res.write(`event: operator-event\ndata: ${JSON.stringify(e)}\n\n`);
|
|
273
|
+
|
|
274
|
+
sseClients.add(res);
|
|
275
|
+
const heartbeat = setInterval(() => {
|
|
276
|
+
try { res.write(": heartbeat\n\n"); } catch { /* ignore */ }
|
|
277
|
+
}, 15000);
|
|
278
|
+
|
|
279
|
+
req.on("close", () => {
|
|
280
|
+
clearInterval(heartbeat);
|
|
281
|
+
sseClients.delete(res);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function handleState(req, res) {
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
const ACTIVE_WINDOW_MS = 5 * 60 * 1000;
|
|
288
|
+
const TOOLS_MIN_WINDOW_MS = 60 * 1000;
|
|
289
|
+
const DENIAL_WINDOW_MS = 60 * 60 * 1000;
|
|
290
|
+
|
|
291
|
+
const sessionRows = [...sessions.values()].sort((a, b) => (b.lastActivity || "").localeCompare(a.lastActivity || ""));
|
|
292
|
+
const activeSessions = sessionRows.filter((s) => s.lastActivity && now - Date.parse(s.lastActivity) <= ACTIVE_WINDOW_MS).length;
|
|
293
|
+
const toolsPerMin = ring.filter((e) => e.kind === "tool" && now - Date.parse(e.ts) <= TOOLS_MIN_WINDOW_MS).length;
|
|
294
|
+
const totalTokens = sessionRows.reduce((sum, s) => sum + (s.tokens || 0), 0);
|
|
295
|
+
const recentDenials = denials.filter((d) => now - Date.parse(d.ts) <= DENIAL_WINDOW_MS);
|
|
296
|
+
const serviceRows = [...services.entries()].map(([name, v]) => ({ name, state: v.state, ts: v.ts }));
|
|
297
|
+
|
|
298
|
+
sendJSON(res, 200, {
|
|
299
|
+
ok: true,
|
|
300
|
+
generatedAt: new Date(now).toISOString(),
|
|
301
|
+
tiles: {
|
|
302
|
+
activeSessions,
|
|
303
|
+
toolsPerMin,
|
|
304
|
+
totalTokens,
|
|
305
|
+
tierDenialsLastHour: recentDenials.length,
|
|
306
|
+
servicesUp: serviceRows.filter((s) => s.state === "up" || s.state === "started").length,
|
|
307
|
+
servicesDown: serviceRows.filter((s) => s.state === "down").length,
|
|
308
|
+
},
|
|
309
|
+
sessions: sessionRows,
|
|
310
|
+
recentDenials: recentDenials.slice(-50).reverse(),
|
|
311
|
+
services: serviceRows,
|
|
312
|
+
ringSize: ring.length,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function handleIndex(req, res) {
|
|
317
|
+
fs.readFile(path.join(__dirname, "index.html"), (err, data) => {
|
|
318
|
+
if (err) { sendJSON(res, 500, { ok: false, error: "index.html missing" }); return; }
|
|
319
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-length": data.length });
|
|
320
|
+
res.end(data);
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const server = http.createServer((req, res) => {
|
|
325
|
+
try {
|
|
326
|
+
const url = new URL(req.url, "http://localhost");
|
|
327
|
+
if (req.method === "POST" && url.pathname === "/events") return handleEvents(req, res);
|
|
328
|
+
if (req.method === "GET" && url.pathname === "/events/stream") return handleStream(req, res);
|
|
329
|
+
if (req.method === "GET" && url.pathname === "/api/state") return handleState(req, res);
|
|
330
|
+
if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) return handleIndex(req, res);
|
|
331
|
+
sendJSON(res, 404, { ok: false, error: "not found" });
|
|
332
|
+
} catch (err) {
|
|
333
|
+
// Last-resort guard: a handler bug must never take the process down.
|
|
334
|
+
try { sendJSON(res, 500, { ok: false, error: String(err && err.message || err) }); } catch { /* response already sent */ }
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
process.on("uncaughtException", (err) => console.error("[dashboard] uncaughtException", err));
|
|
339
|
+
process.on("unhandledRejection", (err) => console.error("[dashboard] unhandledRejection", err));
|
|
340
|
+
|
|
341
|
+
backfill().finally(() => {
|
|
342
|
+
startTail(); // live-tail the events file so new appends (any Operator session) stream in with no config
|
|
343
|
+
server.listen(PORT, "127.0.0.1", () => {
|
|
344
|
+
console.error(`[dashboard] swarm console listening on http://127.0.0.1:${PORT} (events file: ${EVENTS_FILE}, live-tailing)`);
|
|
345
|
+
});
|
|
346
|
+
});
|
package/dist/cli.js
CHANGED
|
@@ -18,7 +18,7 @@ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
|
18
18
|
import { join } from "node:path";
|
|
19
19
|
import { homedir, hostname } from "node:os";
|
|
20
20
|
import { createHash } from "node:crypto";
|
|
21
|
-
const VERSION = "0.1.
|
|
21
|
+
const VERSION = "0.1.31";
|
|
22
22
|
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
23
23
|
const settings = loadSettings();
|
|
24
24
|
// Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
|
|
@@ -144,6 +144,7 @@ const HELP = [
|
|
|
144
144
|
" /endpoints show the aurora endpoint + live health",
|
|
145
145
|
" /services ensure/inspect the service lever (aurora+autopilot+searxng); /services stop",
|
|
146
146
|
" /audit [n] recent tool + control-plane events from the audit trail (default 15)",
|
|
147
|
+
" /dashboard launch the live swarm console (watches every Operator session)",
|
|
147
148
|
" /compact force-compact the conversation now",
|
|
148
149
|
" /remember <note> store a note to recall in future sessions",
|
|
149
150
|
" /memory [query] show remembered notes (all, or matching query)",
|
|
@@ -575,6 +576,39 @@ function Root() {
|
|
|
575
576
|
sys(rows.length ? `audit (last ${rows.length}):\n` + rows.join("\n") : "no tool/control events in the audit log yet");
|
|
576
577
|
break;
|
|
577
578
|
}
|
|
579
|
+
case "dashboard": {
|
|
580
|
+
// Launch the live swarm console (dashboard/server.mjs) if it isn't already up. It live-tails
|
|
581
|
+
// ~/.axe/operator/events.jsonl, so it shows EVERY Operator session with zero per-session config.
|
|
582
|
+
const port = Number(process.env.KODE_DASHBOARD_PORT) || 8899;
|
|
583
|
+
const url = `http://127.0.0.1:${port}`;
|
|
584
|
+
const net = await import("node:net");
|
|
585
|
+
const up = await new Promise((resolve) => {
|
|
586
|
+
const s = net.connect(port, "127.0.0.1");
|
|
587
|
+
s.on("connect", () => { s.destroy(); resolve(true); });
|
|
588
|
+
s.on("error", () => resolve(false));
|
|
589
|
+
setTimeout(() => { try {
|
|
590
|
+
s.destroy();
|
|
591
|
+
}
|
|
592
|
+
catch { /* noop */ } resolve(false); }, 800);
|
|
593
|
+
});
|
|
594
|
+
if (up) {
|
|
595
|
+
sys(`swarm console already running → ${url}`);
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
try {
|
|
599
|
+
const { spawn } = await import("node:child_process");
|
|
600
|
+
const { fileURLToPath } = await import("node:url");
|
|
601
|
+
const { dirname } = await import("node:path");
|
|
602
|
+
const server = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "server.mjs");
|
|
603
|
+
const child = spawn(process.execPath, [server], { detached: true, stdio: "ignore", env: { ...process.env, PORT: String(port) } });
|
|
604
|
+
child.unref();
|
|
605
|
+
sys(`launched the swarm console → ${url} — live-tailing ~/.axe/operator/events.jsonl (every Operator session, zero config). Open it in a browser.`);
|
|
606
|
+
}
|
|
607
|
+
catch (e) {
|
|
608
|
+
sys(`could not launch the dashboard: ${e.message}`);
|
|
609
|
+
}
|
|
610
|
+
break;
|
|
611
|
+
}
|
|
578
612
|
case "services": {
|
|
579
613
|
// The lever, on demand: `/services` probes + starts any down launchd service; `/services stop`
|
|
580
614
|
// tears down only the session-scoped SearXNG (Aurora/autopilot are shared and stay up).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0perator/operator",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.31",
|
|
4
4
|
"description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
11
|
"dist",
|
|
12
|
+
"dashboard",
|
|
12
13
|
"README.md"
|
|
13
14
|
],
|
|
14
15
|
"engines": {
|