sentinelayer-cli 0.8.8 → 0.8.9
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/package.json +1 -1
- package/src/session/agent-registry.js +60 -1
- package/src/session/senti-naming.js +180 -0
- package/src/session/transcript.js +7 -1
- package/src/session/usage.js +213 -0
package/package.json
CHANGED
|
@@ -7,6 +7,11 @@ import { STUCK_THRESHOLDS } from "../agents/jules/pulse.js";
|
|
|
7
7
|
import { createAgentEvent } from "../events/schema.js";
|
|
8
8
|
import { resolveSessionPaths } from "./paths.js";
|
|
9
9
|
import { emitContextBriefing } from "./recap.js";
|
|
10
|
+
import {
|
|
11
|
+
assignFriendlyName,
|
|
12
|
+
buildSentiWelcome,
|
|
13
|
+
shouldAutoRenameInRegistry,
|
|
14
|
+
} from "./senti-naming.js";
|
|
10
15
|
import { appendToStream } from "./stream.js";
|
|
11
16
|
|
|
12
17
|
const AGENT_SNAPSHOT_SCHEMA_VERSION = "1.0.0";
|
|
@@ -181,7 +186,26 @@ export async function registerAgent(
|
|
|
181
186
|
) {
|
|
182
187
|
const paths = resolveSessionPaths(sessionId, { targetPath });
|
|
183
188
|
const nowIso = new Date().toISOString();
|
|
184
|
-
const
|
|
189
|
+
const originalCallerAgentId = normalizeString(agentId);
|
|
190
|
+
let resolvedAgentId = originalCallerAgentId || generateAgentId(model);
|
|
191
|
+
let renamedFrom = "";
|
|
192
|
+
|
|
193
|
+
// Senti orchestrator hook: when the caller didn't supply an id, or
|
|
194
|
+
// supplied an explicit placeholder (`cli-user`, `agent-…`, `guest-…`),
|
|
195
|
+
// pick a friendly sequential name like `claude-3` / `codex-2` /
|
|
196
|
+
// `guest-1` so participants have a "face" in the transcript instead of
|
|
197
|
+
// a random hex blob. Caller-supplied real ids are NEVER renamed
|
|
198
|
+
// (kill tests like PR 348/351 register `codex-task-holder-1` with
|
|
199
|
+
// model="" and need the id to round-trip verbatim).
|
|
200
|
+
if (shouldAutoRenameInRegistry({ originalCallerAgentId })) {
|
|
201
|
+
const existingAgents = await listAgentsInternal(paths);
|
|
202
|
+
const friendly = assignFriendlyName({ model, existingAgents });
|
|
203
|
+
if (friendly && friendly !== resolvedAgentId.toLowerCase()) {
|
|
204
|
+
renamedFrom = resolvedAgentId;
|
|
205
|
+
resolvedAgentId = friendly;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
185
209
|
const snapshotPath = buildAgentSnapshotPath(paths, resolvedAgentId);
|
|
186
210
|
|
|
187
211
|
const snapshot = normalizeAgentSnapshot(
|
|
@@ -210,6 +234,21 @@ export async function registerAgent(
|
|
|
210
234
|
role: snapshot.role,
|
|
211
235
|
status: snapshot.status,
|
|
212
236
|
}, { targetPath });
|
|
237
|
+
|
|
238
|
+
if (renamedFrom) {
|
|
239
|
+
const welcome = buildSentiWelcome({
|
|
240
|
+
agentId: snapshot.agentId,
|
|
241
|
+
model: snapshot.model,
|
|
242
|
+
role: snapshot.role,
|
|
243
|
+
wasAnonymous: true,
|
|
244
|
+
originalAgentId: renamedFrom,
|
|
245
|
+
});
|
|
246
|
+
await emitAgentEvent(paths.sessionId, "agent_identified", {
|
|
247
|
+
...welcome,
|
|
248
|
+
sessionId: paths.sessionId,
|
|
249
|
+
}, { targetPath });
|
|
250
|
+
}
|
|
251
|
+
|
|
213
252
|
if (normalizeString(snapshot.agentId).toLowerCase() !== "senti") {
|
|
214
253
|
await emitContextBriefing(paths.sessionId, {
|
|
215
254
|
forAgentId: snapshot.agentId,
|
|
@@ -223,6 +262,26 @@ export async function registerAgent(
|
|
|
223
262
|
};
|
|
224
263
|
}
|
|
225
264
|
|
|
265
|
+
async function listAgentsInternal(paths) {
|
|
266
|
+
try {
|
|
267
|
+
const entries = await fsp.readdir(paths.agentsDir, { withFileTypes: true });
|
|
268
|
+
const out = [];
|
|
269
|
+
for (const entry of entries) {
|
|
270
|
+
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
271
|
+
const raw = await readAgentSnapshot(path.join(paths.agentsDir, entry.name));
|
|
272
|
+
if (raw && typeof raw === "object" && raw.agentId) {
|
|
273
|
+
out.push({ agentId: raw.agentId, model: raw.model || "" });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (error && typeof error === "object" && error.code === "ENOENT") {
|
|
279
|
+
return [];
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
226
285
|
export async function heartbeatAgent(
|
|
227
286
|
sessionId,
|
|
228
287
|
agentId,
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Senti — auto-name + welcome anonymous participants.
|
|
3
|
+
*
|
|
4
|
+
* When an agent joins without a clear name + model, Senti steps in:
|
|
5
|
+
*
|
|
6
|
+
* 1. `assignFriendlyName({ model, existingAgents })` — generates a
|
|
7
|
+
* stable, human-readable id like "guest-3", "claude-2",
|
|
8
|
+
* "codex-anon-1" derived from the model family + the next free
|
|
9
|
+
* ordinal in the session. Sequential beats hex-suffix for the
|
|
10
|
+
* ChatGPT-style "everyone has a face" UX Carter asked for.
|
|
11
|
+
*
|
|
12
|
+
* 2. `buildSentiWelcome({ agentId, model, role })` — produces the
|
|
13
|
+
* payload for an `agent_identified` event Senti emits in the
|
|
14
|
+
* stream so the new participant + everyone watching sees the
|
|
15
|
+
* auto-assignment + how to override it.
|
|
16
|
+
*
|
|
17
|
+
* 3. `isAnonymousAgent({ agentId, model })` — single-source check
|
|
18
|
+
* for "this registration didn't carry real identity" used by
|
|
19
|
+
* callers to decide whether to invoke (1) and (2). Generic
|
|
20
|
+
* prefixes (`agent-…`, `cli-user`) and unknown models qualify.
|
|
21
|
+
*
|
|
22
|
+
* This module never touches the network or the disk; it's pure naming
|
|
23
|
+
* logic that the agent-registry wires into the registration path.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const ANONYMOUS_AGENT_PREFIXES = Object.freeze(["agent-", "cli-user", "guest-"]);
|
|
27
|
+
const ANONYMOUS_MODELS = Object.freeze(["", "unknown", "cli", "anonymous"]);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Strict: should the agent-registry auto-rename this registration?
|
|
31
|
+
*
|
|
32
|
+
* The hook's contract is "if a name is already there, leave it alone; if
|
|
33
|
+
* not, give them one." So we ONLY auto-rename when the caller gave us
|
|
34
|
+
* nothing OR the literal default placeholder `cli-user`. Any other
|
|
35
|
+
* caller-supplied id — even ones that *look* generic like `agent-alpha`,
|
|
36
|
+
* `guest-team`, or `codex-task-holder-1` — was an intentional choice and
|
|
37
|
+
* round-trips verbatim.
|
|
38
|
+
*
|
|
39
|
+
* Why so strict:
|
|
40
|
+
* - e2e test #91 (CLI session commands flow) does `session join
|
|
41
|
+
* --name agent-alpha` and asserts the id round-trips. The previous
|
|
42
|
+
* rule (`agent-` prefix => rename) clobbered it.
|
|
43
|
+
* - PR 348/351 kill tests register `codex-task-holder-1` with model=""
|
|
44
|
+
* and need verbatim round-trip.
|
|
45
|
+
* - `isAnonymousAgent` is intentionally separate and stays permissive
|
|
46
|
+
* (model can flag) for downstream callers that decide whether to
|
|
47
|
+
* *welcome* a participant; the registry hook is stricter.
|
|
48
|
+
*
|
|
49
|
+
* @param {{originalCallerAgentId: string}} params
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
export function shouldAutoRenameInRegistry({ originalCallerAgentId = "" } = {}) {
|
|
53
|
+
const id = normalize(originalCallerAgentId).toLowerCase();
|
|
54
|
+
if (!id) return true;
|
|
55
|
+
return id === "cli-user";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @typedef {object} AgentLike
|
|
60
|
+
* @property {string} agentId
|
|
61
|
+
* @property {string} [model]
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
function normalize(value) {
|
|
65
|
+
return String(value == null ? "" : value).trim();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function familyFromModel(modelName) {
|
|
69
|
+
const lower = normalize(modelName).toLowerCase();
|
|
70
|
+
if (!lower || lower === "unknown" || lower === "anonymous") return "guest";
|
|
71
|
+
if (lower.includes("claude") || lower.includes("sonnet") || lower.includes("opus")) {
|
|
72
|
+
return "claude";
|
|
73
|
+
}
|
|
74
|
+
if (lower.includes("codex") || lower.includes("gpt-")) return "codex";
|
|
75
|
+
if (lower.includes("gemini")) return "gemini";
|
|
76
|
+
if (lower.includes("senti") || lower.includes("sentinel")) return "senti";
|
|
77
|
+
if (lower === "cli") return "guest";
|
|
78
|
+
// Otherwise use the first sanitized token so distinct providers stay
|
|
79
|
+
// distinct even when we don't recognize them.
|
|
80
|
+
const token = lower.split(/[\s:/_-]+/).find(Boolean) || "guest";
|
|
81
|
+
return token.replace(/[^a-z0-9]/g, "") || "guest";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Given the existing agent roster + the model the new participant
|
|
86
|
+
* declared (which may be empty/unknown), pick the next free ordinal
|
|
87
|
+
* within that family and return `<family>-<ordinal>`. Stable across
|
|
88
|
+
* runs because we pass the existing agents in.
|
|
89
|
+
*
|
|
90
|
+
* @param {{model?: string, existingAgents?: Array<AgentLike>}} params
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
export function assignFriendlyName({ model = "", existingAgents = [] } = {}) {
|
|
94
|
+
const family = familyFromModel(model);
|
|
95
|
+
const taken = new Set(
|
|
96
|
+
(Array.isArray(existingAgents) ? existingAgents : [])
|
|
97
|
+
.map((agent) => normalize(agent && agent.agentId).toLowerCase())
|
|
98
|
+
.filter(Boolean),
|
|
99
|
+
);
|
|
100
|
+
for (let n = 1; n <= 9999; n += 1) {
|
|
101
|
+
const candidate = `${family}-${n}`;
|
|
102
|
+
if (!taken.has(candidate)) return candidate;
|
|
103
|
+
}
|
|
104
|
+
// Pathological fallback — should never hit in practice, but a
|
|
105
|
+
// 4-digit ceiling without an escape would be a footgun.
|
|
106
|
+
return `${family}-${Date.now().toString(36)}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Decide whether the registration looks anonymous and therefore needs
|
|
111
|
+
* Senti to step in with a friendly name. We treat any of:
|
|
112
|
+
*
|
|
113
|
+
* - empty / fallback agentId (`agent-…`, `cli-user`, `guest-…`)
|
|
114
|
+
* - empty / unknown / cli model
|
|
115
|
+
*
|
|
116
|
+
* as a signal. Either alone is enough — the cli-user default agent
|
|
117
|
+
* still wants Senti's welcome the first time.
|
|
118
|
+
*
|
|
119
|
+
* @param {AgentLike} agent
|
|
120
|
+
* @returns {boolean}
|
|
121
|
+
*/
|
|
122
|
+
export function isAnonymousAgent(agent = {}) {
|
|
123
|
+
const id = normalize(agent.agentId).toLowerCase();
|
|
124
|
+
const model = normalize(agent.model).toLowerCase();
|
|
125
|
+
const idAnonymous =
|
|
126
|
+
!id ||
|
|
127
|
+
ANONYMOUS_AGENT_PREFIXES.some((prefix) => id.startsWith(prefix));
|
|
128
|
+
const modelAnonymous = ANONYMOUS_MODELS.includes(model);
|
|
129
|
+
return idAnonymous || modelAnonymous;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Build the payload Senti emits as `agent_identified` when it has
|
|
134
|
+
* stepped in to name a participant. Consumers (CLI / web) render it
|
|
135
|
+
* verbatim; the `instructions` line tells the user how to override.
|
|
136
|
+
*
|
|
137
|
+
* @param {{
|
|
138
|
+
* agentId: string,
|
|
139
|
+
* model?: string,
|
|
140
|
+
* role?: string,
|
|
141
|
+
* sessionId?: string,
|
|
142
|
+
* wasAnonymous: boolean,
|
|
143
|
+
* originalAgentId?: string,
|
|
144
|
+
* }} params
|
|
145
|
+
* @returns {{
|
|
146
|
+
* alert: "agent_identified",
|
|
147
|
+
* agentId: string,
|
|
148
|
+
* model: string,
|
|
149
|
+
* role: string,
|
|
150
|
+
* wasAnonymous: boolean,
|
|
151
|
+
* originalAgentId: string,
|
|
152
|
+
* message: string,
|
|
153
|
+
* instructions: string,
|
|
154
|
+
* }}
|
|
155
|
+
*/
|
|
156
|
+
export function buildSentiWelcome({
|
|
157
|
+
agentId,
|
|
158
|
+
model = "unknown",
|
|
159
|
+
role = "observer",
|
|
160
|
+
wasAnonymous = false,
|
|
161
|
+
originalAgentId = "",
|
|
162
|
+
} = {}) {
|
|
163
|
+
const cleanModel = normalize(model) || "unknown";
|
|
164
|
+
const cleanRole = normalize(role) || "observer";
|
|
165
|
+
const cleanId = normalize(agentId);
|
|
166
|
+
const message = wasAnonymous
|
|
167
|
+
? `Welcome ${cleanId}. I auto-named you because you joined without a name; introduce yourself anytime.`
|
|
168
|
+
: `Welcome ${cleanId}. You're in as ${cleanRole}.`;
|
|
169
|
+
const instructions = `Update with: sl session rename <sessionId> ${cleanId} --to <new-id> [--model <model>]`;
|
|
170
|
+
return {
|
|
171
|
+
alert: "agent_identified",
|
|
172
|
+
agentId: cleanId,
|
|
173
|
+
model: cleanModel,
|
|
174
|
+
role: cleanRole,
|
|
175
|
+
wasAnonymous: Boolean(wasAnonymous),
|
|
176
|
+
originalAgentId: normalize(originalAgentId),
|
|
177
|
+
message,
|
|
178
|
+
instructions,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -41,6 +41,7 @@ const TRANSCRIPT_EVENT_KINDS = new Set([
|
|
|
41
41
|
"session_message",
|
|
42
42
|
"session_say",
|
|
43
43
|
"agent_response",
|
|
44
|
+
"session_usage",
|
|
44
45
|
"human_relay",
|
|
45
46
|
"agent_join",
|
|
46
47
|
"agent_left",
|
|
@@ -153,9 +154,14 @@ function eventTimestamp(event) {
|
|
|
153
154
|
|
|
154
155
|
function eventBody(event) {
|
|
155
156
|
const payload = event && typeof event.payload === "object" ? event.payload : {};
|
|
157
|
+
// session_usage carries the response inside payload.response.text
|
|
158
|
+
const responseText =
|
|
159
|
+
typeof payload.response === "object" && payload.response
|
|
160
|
+
? payload.response.text
|
|
161
|
+
: payload.response;
|
|
156
162
|
const text =
|
|
157
163
|
payload.message ||
|
|
158
|
-
|
|
164
|
+
responseText ||
|
|
159
165
|
payload.text ||
|
|
160
166
|
payload.alert ||
|
|
161
167
|
payload.reason ||
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session usage emitter — records every LLM interaction inside a session
|
|
3
|
+
* as a `session_usage` event so consumers (web dashboard, transcript
|
|
4
|
+
* download, telemetry sync) can surface live, accurate token + cost
|
|
5
|
+
* counters per-agent + session-wide.
|
|
6
|
+
*
|
|
7
|
+
* Senti orchestrator philosophy: "tokens on point every time any LLM
|
|
8
|
+
* interacts." Every persona / Jules / Codex / Claude call inside a
|
|
9
|
+
* session should land here so the running tally is authoritative.
|
|
10
|
+
*
|
|
11
|
+
* Event shape:
|
|
12
|
+
*
|
|
13
|
+
* {
|
|
14
|
+
* event: "session_usage",
|
|
15
|
+
* ts: ISO8601,
|
|
16
|
+
* agent: { id, model },
|
|
17
|
+
* payload: {
|
|
18
|
+
* interactionId, // stable id for the LLM call
|
|
19
|
+
* agentId, model, role,
|
|
20
|
+
* inputTokens, outputTokens, totalTokens,
|
|
21
|
+
* costUsd,
|
|
22
|
+
* durationMs, // wall-clock duration of the call
|
|
23
|
+
* prompt: { tokens, chars },
|
|
24
|
+
* response: { tokens, chars, text? },
|
|
25
|
+
* usage: { // mirrors transcript.js payload.usage
|
|
26
|
+
* totalTokens,
|
|
27
|
+
* costUsd,
|
|
28
|
+
* inputTokens,
|
|
29
|
+
* outputTokens,
|
|
30
|
+
* },
|
|
31
|
+
* }
|
|
32
|
+
* }
|
|
33
|
+
*
|
|
34
|
+
* Design choice: emit BOTH the convenient flat fields AND a
|
|
35
|
+
* `payload.usage` block, so transcript.js's existing usage roll-up
|
|
36
|
+
* picks it up without changes, while web UIs can display the structured
|
|
37
|
+
* fields directly without re-parsing.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import process from "node:process";
|
|
41
|
+
import { randomUUID } from "node:crypto";
|
|
42
|
+
|
|
43
|
+
import { createAgentEvent } from "../events/schema.js";
|
|
44
|
+
import { resolveSessionPaths } from "./paths.js";
|
|
45
|
+
import { appendToStream } from "./stream.js";
|
|
46
|
+
|
|
47
|
+
const SESSION_USAGE_EVENT = "session_usage";
|
|
48
|
+
|
|
49
|
+
function n(value) {
|
|
50
|
+
return String(value == null ? "" : value).trim();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function num(value) {
|
|
54
|
+
const v = Number(value);
|
|
55
|
+
return Number.isFinite(v) && v >= 0 ? v : 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function clipText(text, max = 4000) {
|
|
59
|
+
const s = n(text);
|
|
60
|
+
if (s.length <= max) return s;
|
|
61
|
+
return `${s.slice(0, max)}…`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Emit a `session_usage` event into the session's NDJSON stream.
|
|
66
|
+
*
|
|
67
|
+
* @param {string} sessionId
|
|
68
|
+
* @param {object} params
|
|
69
|
+
* @param {string} params.agentId
|
|
70
|
+
* @param {string} [params.agentModel]
|
|
71
|
+
* @param {string} [params.role]
|
|
72
|
+
* @param {number} [params.inputTokens]
|
|
73
|
+
* @param {number} [params.outputTokens]
|
|
74
|
+
* @param {number} [params.costUsd]
|
|
75
|
+
* @param {number} [params.durationMs]
|
|
76
|
+
* @param {string} [params.prompt] full prompt text (clipped)
|
|
77
|
+
* @param {string} [params.response] full response text (clipped)
|
|
78
|
+
* @param {string} [params.interactionId] opaque id for cross-event correlation
|
|
79
|
+
* @param {string} [params.targetPath] workspace path (default cwd)
|
|
80
|
+
* @returns {Promise<{ event: string, interactionId: string, totalTokens: number, costUsd: number }>}
|
|
81
|
+
*/
|
|
82
|
+
export async function emitLLMInteraction(
|
|
83
|
+
sessionId,
|
|
84
|
+
{
|
|
85
|
+
agentId,
|
|
86
|
+
agentModel = "",
|
|
87
|
+
role = "",
|
|
88
|
+
inputTokens = 0,
|
|
89
|
+
outputTokens = 0,
|
|
90
|
+
costUsd = 0,
|
|
91
|
+
durationMs = 0,
|
|
92
|
+
prompt = "",
|
|
93
|
+
response = "",
|
|
94
|
+
interactionId = "",
|
|
95
|
+
targetPath = process.cwd(),
|
|
96
|
+
} = {},
|
|
97
|
+
) {
|
|
98
|
+
const sid = n(sessionId);
|
|
99
|
+
if (!sid) throw new Error("sessionId is required.");
|
|
100
|
+
const aid = n(agentId);
|
|
101
|
+
if (!aid) throw new Error("agentId is required.");
|
|
102
|
+
|
|
103
|
+
const paths = resolveSessionPaths(sid, { targetPath });
|
|
104
|
+
const ts = new Date().toISOString();
|
|
105
|
+
const id = n(interactionId) || randomUUID();
|
|
106
|
+
const inT = Math.floor(num(inputTokens));
|
|
107
|
+
const outT = Math.floor(num(outputTokens));
|
|
108
|
+
const totalT = inT + outT;
|
|
109
|
+
const cost = Math.round(num(costUsd) * 1_000_000) / 1_000_000;
|
|
110
|
+
|
|
111
|
+
const promptText = clipText(prompt);
|
|
112
|
+
const responseText = clipText(response);
|
|
113
|
+
|
|
114
|
+
const payload = {
|
|
115
|
+
interactionId: id,
|
|
116
|
+
agentId: aid,
|
|
117
|
+
model: n(agentModel) || "unknown",
|
|
118
|
+
role: n(role) || "observer",
|
|
119
|
+
inputTokens: inT,
|
|
120
|
+
outputTokens: outT,
|
|
121
|
+
totalTokens: totalT,
|
|
122
|
+
costUsd: cost,
|
|
123
|
+
durationMs: Math.max(0, Math.floor(num(durationMs))),
|
|
124
|
+
prompt: { tokens: inT, chars: promptText.length },
|
|
125
|
+
response: {
|
|
126
|
+
tokens: outT,
|
|
127
|
+
chars: responseText.length,
|
|
128
|
+
text: responseText || undefined,
|
|
129
|
+
},
|
|
130
|
+
// Mirror into payload.usage so transcript.js + telemetry sync pick
|
|
131
|
+
// it up via the same code path used for ad-hoc agent_response usage.
|
|
132
|
+
usage: {
|
|
133
|
+
totalTokens: totalT,
|
|
134
|
+
costUsd: cost,
|
|
135
|
+
inputTokens: inT,
|
|
136
|
+
outputTokens: outT,
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const envelope = createAgentEvent({
|
|
141
|
+
event: SESSION_USAGE_EVENT,
|
|
142
|
+
agentId: aid,
|
|
143
|
+
agentModel: n(agentModel) || "unknown",
|
|
144
|
+
sessionId: paths.sessionId,
|
|
145
|
+
payload,
|
|
146
|
+
ts,
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
await appendToStream(paths.sessionId, envelope, { targetPath });
|
|
150
|
+
return {
|
|
151
|
+
event: SESSION_USAGE_EVENT,
|
|
152
|
+
interactionId: id,
|
|
153
|
+
totalTokens: totalT,
|
|
154
|
+
costUsd: cost,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Aggregate `session_usage` events into a per-agent + global tally.
|
|
160
|
+
* Pure helper for renderers that want a snapshot at a point in time.
|
|
161
|
+
*
|
|
162
|
+
* @param {Array<object>} events
|
|
163
|
+
* @returns {{
|
|
164
|
+
* perAgent: Map<string, { agentId, model, totalTokens, inputTokens, outputTokens, costUsd, interactions }>,
|
|
165
|
+
* totals: { totalTokens, inputTokens, outputTokens, costUsd, interactions },
|
|
166
|
+
* }}
|
|
167
|
+
*/
|
|
168
|
+
export function aggregateSessionUsage(events = []) {
|
|
169
|
+
const perAgent = new Map();
|
|
170
|
+
const totals = {
|
|
171
|
+
totalTokens: 0,
|
|
172
|
+
inputTokens: 0,
|
|
173
|
+
outputTokens: 0,
|
|
174
|
+
costUsd: 0,
|
|
175
|
+
interactions: 0,
|
|
176
|
+
};
|
|
177
|
+
for (const event of events) {
|
|
178
|
+
if (!event || event.event !== SESSION_USAGE_EVENT) continue;
|
|
179
|
+
const payload = event.payload || {};
|
|
180
|
+
const agentId = n(payload.agentId || event.agent?.id);
|
|
181
|
+
if (!agentId) continue;
|
|
182
|
+
if (!perAgent.has(agentId)) {
|
|
183
|
+
perAgent.set(agentId, {
|
|
184
|
+
agentId,
|
|
185
|
+
model: n(payload.model || event.agent?.model) || "unknown",
|
|
186
|
+
totalTokens: 0,
|
|
187
|
+
inputTokens: 0,
|
|
188
|
+
outputTokens: 0,
|
|
189
|
+
costUsd: 0,
|
|
190
|
+
interactions: 0,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
const record = perAgent.get(agentId);
|
|
194
|
+
record.totalTokens += num(payload.totalTokens);
|
|
195
|
+
record.inputTokens += num(payload.inputTokens);
|
|
196
|
+
record.outputTokens += num(payload.outputTokens);
|
|
197
|
+
record.costUsd += num(payload.costUsd);
|
|
198
|
+
record.interactions += 1;
|
|
199
|
+
|
|
200
|
+
totals.totalTokens += num(payload.totalTokens);
|
|
201
|
+
totals.inputTokens += num(payload.inputTokens);
|
|
202
|
+
totals.outputTokens += num(payload.outputTokens);
|
|
203
|
+
totals.costUsd += num(payload.costUsd);
|
|
204
|
+
totals.interactions += 1;
|
|
205
|
+
}
|
|
206
|
+
totals.costUsd = Math.round(totals.costUsd * 1_000_000) / 1_000_000;
|
|
207
|
+
for (const record of perAgent.values()) {
|
|
208
|
+
record.costUsd = Math.round(record.costUsd * 1_000_000) / 1_000_000;
|
|
209
|
+
}
|
|
210
|
+
return { perAgent, totals };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export const SESSION_USAGE_EVENT_KIND = SESSION_USAGE_EVENT;
|