u-foo 4.0.0 → 4.0.2
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/OBSERVABILITY.md +65 -0
- package/README.md +90 -30
- package/README.zh-CN.md +76 -26
- package/SKILLS/ufoo/SKILL.md +25 -1
- package/SKILLS/ufoo-bus/SKILL.md +25 -2
- package/bin/ucode.js +4 -0
- package/bin/ufoo.js +3 -3
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/package.json +6 -6
- package/src/agents/activity/activityDetector.js +1 -1
- package/src/agents/capabilities/agentManagement/service.js +40 -13
- package/src/agents/capabilities/coordination/index.js +1 -1
- package/src/agents/capabilities/taskReports/index.js +1 -1
- package/src/agents/controller/controllerToolExecutor.js +36 -20
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +90 -56
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +38 -29
- package/src/agents/launch/launcherReadiness.js +35 -0
- package/src/agents/launch/notifier.js +2 -2
- package/src/agents/launch/ptyWrapper.js +5 -2
- package/src/agents/launch/readyDetector.js +2 -2
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +23 -7
- package/src/agents/prompts/mainAgent.js +11 -2
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/ufoo.js +11 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +3 -0
- package/src/agents/providers/claudeThreadProvider.js +3 -2
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +23 -2
- package/src/agents/providers/codexThreadProvider.js +15 -6
- package/src/agents/providers/credentials/index.js +2 -0
- package/src/agents/providers/directAuthStatus.js +1 -1
- package/src/agents/providers/index.js +1 -1
- package/src/agents/providers/modelSettings.js +34 -0
- package/src/agents/providers/modelsCatalog.js +379 -0
- package/src/agents/providers/nativeTransport.js +58 -40
- package/src/agents/providers/runtimeConfig.js +10 -8
- package/src/agents/providers/thinkingLevels.js +10 -36
- package/src/agents/providers/transports/responsesProtocol.js +11 -6
- package/src/agents/providers/upstreamRuntime.js +135 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +2 -1
- package/src/agents/runtime/core/agentLoop.js +99 -18
- package/src/agents/runtime/core/executionBudget.js +36 -0
- package/src/agents/runtime/createAgentRuntime.js +16 -4
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -0
- package/src/app/chat/ChatController.js +26 -53
- package/src/app/chat/agentDirectory.js +1 -16
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +93 -285
- package/src/app/chat/commands.js +32 -45
- package/src/app/chat/daemonMessageRouter.js +0 -45
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +7 -33
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/multiWindow/paneManager.js +10 -3
- package/src/app/chat/streamState.js +0 -4
- package/src/app/cli/features/init.js +5 -5
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/run.js +42 -3
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +18 -13
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/assembler.js +7 -8
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/internalThread.js +10 -3
- package/src/code/launcher/ucode.js +1 -1
- package/src/code/launcher/ucodeBootstrap.js +1 -1
- package/src/code/modelCommand.js +11 -35
- package/src/code/nativeRunner.js +55 -17
- package/src/code/providers/modelsCatalog.js +1 -317
- package/src/code/repl.js +4 -11
- package/src/code/sessionStore.js +3 -3
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/toolBudget.js +1 -17
- package/src/config.js +22 -72
- package/src/coordination/bus/index.js +12 -3
- package/src/coordination/bus/inject.js +2 -2
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +1 -1
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentTrace.js +249 -0
- package/src/coordination/state/workspaceAccess.js +1 -1
- package/src/orchestration/controller/index.js +1 -8
- package/src/orchestration/controller/launchRouting.js +1 -1
- package/src/orchestration/solo/commands.js +3 -1
- package/src/runtime/contracts/agentMode.js +11 -2
- package/src/runtime/contracts/uiProtocol.js +18 -19
- package/src/runtime/daemon/agentHost.js +57 -25
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +1 -1
- package/src/runtime/daemon/controlPlaneService.js +1 -1
- package/src/runtime/daemon/groupOrchestrator.js +20 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +19 -44
- package/src/runtime/daemon/mcpHttpServer.js +39 -10
- package/src/runtime/daemon/mcpServer.js +1 -1
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +46 -23
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -589
- package/src/runtime/daemon/status.js +5 -6
- package/src/tools/controllerSchemas.js +6 -2
- package/src/tools/handlers/tier2.js +4 -2
- package/src/tools/registry.js +4 -0
- package/src/tools/schemaFixtures.js +26 -2
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- package/src/ui/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +1 -1
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +1 -4
- package/src/ui/format/index.js +14 -10
- package/src/ui/format/loopSummary.js +50 -0
- package/src/ui/format/markdownRenderer.js +3 -4
- package/src/ui/rustChatHost.js +191 -206
- package/src/ui/rustMultiSession.js +77 -36
- package/src/ui/rustUcodeHost.js +6 -1
- package/src/ui/settingsBridge.js +33 -16
- package/src/ui/toolMergeBridge.js +0 -4
- package/src/ui/uiHostServer.js +5 -8
- package/src/agents/controller/loopObservability.js +0 -200
- package/src/agents/controller/loopRuntime.js +0 -336
- package/src/agents/controller/ufooAgent.js +0 -830
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/controllerJsonTransport.js +0 -28
- package/src/agents/providers/upstreamTransport.js +0 -698
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- package/src/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/coordination/history/controllerSummary.js +0 -23
- package/src/orchestration/controller/flags.js +0 -167
- package/src/orchestration/controller/gateRouter.js +0 -211
- package/src/orchestration/controller/routerFastPath.js +0 -22
- package/src/orchestration/controller/routerFinalize.js +0 -222
- package/src/orchestration/controller/shadowGuard.js +0 -280
- package/src/runtime/daemon/executionPaths.js +0 -30
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
|
@@ -329,6 +329,7 @@ class EventBus {
|
|
|
329
329
|
if (options.envelope === false) data.envelope = false;
|
|
330
330
|
const result = eventName === "message"
|
|
331
331
|
? await this.messageManager.send(target, message, publisher, {
|
|
332
|
+
...options,
|
|
332
333
|
data,
|
|
333
334
|
injectionMode: options.injectionMode,
|
|
334
335
|
source: options.source,
|
|
@@ -406,7 +407,11 @@ class EventBus {
|
|
|
406
407
|
console.log();
|
|
407
408
|
}
|
|
408
409
|
|
|
409
|
-
|
|
410
|
+
if (this.messageManager.isRunnerManaged(subscriber)) {
|
|
411
|
+
console.log(`${colors.cyan}Internal runner confirms completed tasks automatically; queued messages are retained.${colors.reset}`);
|
|
412
|
+
} else {
|
|
413
|
+
console.log(`${colors.cyan}After handling, run: ufoo bus ack ${subscriber}${colors.reset}`);
|
|
414
|
+
}
|
|
410
415
|
|
|
411
416
|
if (autoAck) {
|
|
412
417
|
await this.ack(subscriber);
|
|
@@ -499,7 +504,9 @@ class EventBus {
|
|
|
499
504
|
|
|
500
505
|
const count = await this.messageManager.ack(subscriber);
|
|
501
506
|
|
|
502
|
-
if (
|
|
507
|
+
if (this.messageManager.isRunnerManaged(subscriber)) {
|
|
508
|
+
logOk("Internal runner confirms completed tasks automatically; queued messages are retained");
|
|
509
|
+
} else if (count > 0) {
|
|
503
510
|
logOk(`Acknowledged and cleared ${count} message(s)`);
|
|
504
511
|
} else {
|
|
505
512
|
logOk("No pending messages to acknowledge");
|
|
@@ -517,7 +524,9 @@ class EventBus {
|
|
|
517
524
|
|
|
518
525
|
const count = await this.messageManager.ackThrough(subscriber, throughSeq);
|
|
519
526
|
|
|
520
|
-
if (
|
|
527
|
+
if (this.messageManager.isRunnerManaged(subscriber)) {
|
|
528
|
+
logOk("Internal runner confirms completed tasks automatically; queued messages are retained");
|
|
529
|
+
} else if (count > 0) {
|
|
521
530
|
logOk(`Acknowledged ${count} message(s) through seq=${throughSeq}`);
|
|
522
531
|
} else {
|
|
523
532
|
logOk(`No pending messages through seq=${throughSeq}`);
|
|
@@ -459,8 +459,8 @@ class Injector {
|
|
|
459
459
|
* 3. Terminal.app/iTerm2 tty lookup(terminal mode fallback)
|
|
460
460
|
*/
|
|
461
461
|
async inject(subscriber, commandOverride, delivery = {}) {
|
|
462
|
-
if (String(subscriber || "")
|
|
463
|
-
throw new Error(`Inject disabled for ${subscriber}.
|
|
462
|
+
if (/^ucode:/.test(String(subscriber || ""))) {
|
|
463
|
+
throw new Error(`Inject disabled for ${subscriber}. ucode consumes bus internally.`);
|
|
464
464
|
}
|
|
465
465
|
|
|
466
466
|
// Terminal injection is a delivery adapter for explicit prompt text.
|
|
@@ -15,6 +15,7 @@ const { buildMessageData } = require("./messageMeta");
|
|
|
15
15
|
const { getUfooPaths } = require("../state/paths");
|
|
16
16
|
const { applyProjectNicknamePrefix } = require("../../runtime/daemon/nicknameScope");
|
|
17
17
|
const { QUEUE_TYPES, normalizeQueueEnvelope } = require("./deliveryQueue");
|
|
18
|
+
const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
|
|
18
19
|
|
|
19
20
|
const SEQ_LOCK_TIMEOUT_MS = 5000;
|
|
20
21
|
const SEQ_LOCK_POLL_MS = 25;
|
|
@@ -523,13 +524,26 @@ class MessageManager {
|
|
|
523
524
|
}
|
|
524
525
|
|
|
525
526
|
/**
|
|
526
|
-
*
|
|
527
|
+
* Internal runners own delivery claims and complete them after execution.
|
|
528
|
+
* Model-issued acknowledgements must never claim future internal tasks.
|
|
527
529
|
*/
|
|
530
|
+
isRunnerManaged(subscriber) {
|
|
531
|
+
return isInternalAgentMeta(this.busData?.agents?.[subscriber]);
|
|
532
|
+
}
|
|
533
|
+
|
|
528
534
|
async ack(subscriber) {
|
|
535
|
+
if (this.isRunnerManaged(subscriber)) return 0;
|
|
529
536
|
return this.queueManager.ackPending(subscriber);
|
|
530
537
|
}
|
|
531
538
|
|
|
532
539
|
async ackThrough(subscriber, throughSeq) {
|
|
540
|
+
if (this.isRunnerManaged(subscriber)) {
|
|
541
|
+
const limit = Number(throughSeq);
|
|
542
|
+
if (!Number.isFinite(limit) || limit <= 0) {
|
|
543
|
+
throw new Error("ack --through requires a positive sequence");
|
|
544
|
+
}
|
|
545
|
+
return 0;
|
|
546
|
+
}
|
|
533
547
|
return this.queueManager.ackPendingThrough(subscriber, throughSeq);
|
|
534
548
|
}
|
|
535
549
|
|
|
@@ -14,7 +14,7 @@ const AUTO_NICKNAME_PREFIXES = new Set([
|
|
|
14
14
|
function resolveAutoNicknamePrefix(agentType = "") {
|
|
15
15
|
const normalized = String(agentType || "").trim().toLowerCase();
|
|
16
16
|
if (normalized === "claude" || normalized === "claude-code") return "claude";
|
|
17
|
-
if (normalized === "
|
|
17
|
+
if (normalized === "ucode") return "ucode";
|
|
18
18
|
return normalized;
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const fs = require("fs");
|
|
2
2
|
const path = require("path");
|
|
3
|
-
const { getTimestamp, isAgentPidAlive, isMetaActive, isValidTty, getTtyProcessInfo } = require("./utils");
|
|
3
|
+
const { getTimestamp, isAgentPidAlive, isMetaActive, isValidTty, getTtyProcessInfo, normalizeAgentTypeAlias } = require("./utils");
|
|
4
4
|
const NicknameManager = require("./nickname");
|
|
5
5
|
const { isMismatchedAutoNickname } = require("./nickname");
|
|
6
6
|
const { spawnSync } = require("child_process");
|
|
@@ -184,7 +184,7 @@ class SubscriberManager {
|
|
|
184
184
|
: (await this.queueManager.readTty(id));
|
|
185
185
|
if (!metaTty) continue;
|
|
186
186
|
if (metaTty === ttyPath) {
|
|
187
|
-
const sameAgentType = !currentAgentType || meta?.agent_type === currentAgentType;
|
|
187
|
+
const sameAgentType = !currentAgentType || normalizeAgentTypeAlias(meta?.agent_type) === normalizeAgentTypeAlias(currentAgentType);
|
|
188
188
|
// Inherit user-set nickname only when replacing the same agent type.
|
|
189
189
|
if (
|
|
190
190
|
sameAgentType
|
|
@@ -229,6 +229,7 @@ class SubscriberManager {
|
|
|
229
229
|
* 加入总线
|
|
230
230
|
*/
|
|
231
231
|
async join(sessionId, agentType, nickname = null, options = {}) {
|
|
232
|
+
if (normalizeAgentTypeAlias(agentType) === "ucode") agentType = "ucode";
|
|
232
233
|
// Special case: ufoo-agent uses fixed ID without suffix
|
|
233
234
|
const subscriber = (sessionId === "ufoo-agent")
|
|
234
235
|
? "ufoo-agent"
|
|
@@ -372,7 +372,7 @@ function normalizeAgentTypeAlias(value = "") {
|
|
|
372
372
|
if (text === "agy") return "agy";
|
|
373
373
|
if (text === "grok" || text === "ugrok" || text === "grok-build" || text === "xai") return "grok";
|
|
374
374
|
if (text === "kimi" || text === "ukimi" || text === "kimi-cli" || text === "kimi-code") return "kimi";
|
|
375
|
-
if (text === "
|
|
375
|
+
if (text === "ucode") return "ucode";
|
|
376
376
|
return text;
|
|
377
377
|
}
|
|
378
378
|
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const terminal = new Set(["completed", "failed", "cancelled", "interrupted"]);
|
|
4
|
+
const number = value => value != null && Number.isFinite(Number(value)) && Number(value) >= 0 ? Number(value) : null;
|
|
5
|
+
const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;
|
|
6
|
+
const difference = (end, start) => end !== null && start !== null && end >= start ? end - start : null;
|
|
7
|
+
const rate = (a, b) => b ? a / b : null;
|
|
8
|
+
|
|
9
|
+
function distribution(values) {
|
|
10
|
+
const sorted = values.filter(value => value !== null && Number.isFinite(value)).sort((a, b) => a - b);
|
|
11
|
+
const percentile = fraction => sorted.length ? sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)] : null;
|
|
12
|
+
return { samples: sorted.length, mean: sorted.length ? sorted.reduce((a, b) => a + b, 0) / sorted.length : null,
|
|
13
|
+
p50: percentile(0.5), p95: percentile(0.95), max: sorted.at(-1) ?? null };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function normalizedUsage(usage) {
|
|
17
|
+
if (!usage || typeof usage !== "object") return null;
|
|
18
|
+
const value = { input: number(usage.input ?? usage.input_tokens ?? usage.prompt_tokens),
|
|
19
|
+
output: number(usage.output ?? usage.output_tokens ?? usage.completion_tokens),
|
|
20
|
+
cacheRead: number(usage.cacheRead ?? usage.cache_read_tokens ?? usage.cache_read_input_tokens ?? usage.cached_input_tokens
|
|
21
|
+
?? usage.input_tokens_details?.cached_tokens ?? usage.input_token_details?.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens),
|
|
22
|
+
cacheCreation: number(usage.cacheCreation ?? usage.cache_creation_tokens ?? usage.cache_creation_input_tokens
|
|
23
|
+
?? usage.input_tokens_details?.cache_write_tokens ?? usage.prompt_tokens_details?.cache_write_tokens) };
|
|
24
|
+
if (!Object.values(value).some(v => v !== null)) return null;
|
|
25
|
+
value.inputIncludesCache = typeof usage.inputIncludesCache === "boolean" ? usage.inputIncludesCache
|
|
26
|
+
: usage.prompt_tokens != null || usage.input_tokens_details || usage.input_token_details || usage.cached_input_tokens != null ? true
|
|
27
|
+
: usage.cache_read_input_tokens != null || usage.cache_creation_input_tokens != null ? false : null;
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function cacheObservation(samples, configuration, provider) {
|
|
32
|
+
const transport = configuration?.transport || "";
|
|
33
|
+
const includesCache = transport.startsWith("openai") ? true : transport.startsWith("anthropic") ? false
|
|
34
|
+
: ["openai", "codex", "codex-cli", "kimi", "grok", "grok-build"].includes(provider) ? true
|
|
35
|
+
: ["claude", "claude-code", "anthropic"].includes(provider) ? false : null;
|
|
36
|
+
const pairs = samples.flatMap(usage => {
|
|
37
|
+
if (usage.input === null || usage.cacheRead === null) return [];
|
|
38
|
+
const inclusive = usage.inputIncludesCache ?? includesCache;
|
|
39
|
+
if (inclusive === null || !inclusive && usage.cacheCreation === null) return [];
|
|
40
|
+
const prompt = inclusive ? usage.input : usage.input + usage.cacheRead + usage.cacheCreation;
|
|
41
|
+
return usage.cacheRead <= prompt ? [{ cached: usage.cacheRead, prompt }] : [];
|
|
42
|
+
});
|
|
43
|
+
const cachedTokens = pairs.length ? pairs.reduce((sum, pair) => sum + pair.cached, 0) : null;
|
|
44
|
+
const promptTokens = pairs.length ? pairs.reduce((sum, pair) => sum + pair.prompt, 0) : null;
|
|
45
|
+
return { samples: pairs.length, usageSamples: samples.length, cachedTokens, promptTokens, hitRate: rate(cachedTokens, promptTokens) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function aggregateCache(runs, scope) {
|
|
49
|
+
const sum = key => {
|
|
50
|
+
const values = runs.map(run => run[scope][key]).filter(value => value !== null);
|
|
51
|
+
return values.length ? values.reduce((a, b) => a + b, 0) : null;
|
|
52
|
+
};
|
|
53
|
+
const cachedTokens = sum("cachedTokens"), promptTokens = sum("promptTokens");
|
|
54
|
+
return { samples: sum("samples") || 0, usageSamples: sum("usageSamples") || 0,
|
|
55
|
+
cachedTokens, promptTokens, hitRate: rate(cachedTokens, promptTokens) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function aggregate(runs) {
|
|
59
|
+
const outcomes = Object.fromEntries(["completed", "failed", "cancelled", "interrupted", "running", "waiting_user", "queued", "unknown"].map(key => [key, runs.filter(r => r.status === key).length]));
|
|
60
|
+
const finished = Object.entries(outcomes).filter(([key]) => terminal.has(key)).reduce((sum, [, count]) => sum + count, 0);
|
|
61
|
+
const counts = {};
|
|
62
|
+
for (const run of runs) for (const [key, value] of Object.entries(run.counts)) counts[key] = (counts[key] || 0) + value;
|
|
63
|
+
const latency = {};
|
|
64
|
+
for (const key of ["elapsedMs", "activeMs", "queueMs", "firstTextMs", "firstThinkingMs", "modelMs", "toolMs", "compactionMs", "waitingUserMs", "idleMs"]) latency[key] = distribution(runs.map(r => r.timings[key]));
|
|
65
|
+
const tokenTotals = {};
|
|
66
|
+
for (const scope of ["usage", "compactionUsage"]) {
|
|
67
|
+
tokenTotals[scope] = {};
|
|
68
|
+
for (const key of ["input", "output", "cacheRead", "cacheCreation"]) {
|
|
69
|
+
const observed = runs.map(r => r[scope][key]).filter(v => v !== null);
|
|
70
|
+
tokenTotals[scope][key] = { samples: observed.length, sum: observed.length ? observed.reduce((a, b) => a + b, 0) : null };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { runs: runs.length, outcomes, completedOfFinished: rate(outcomes.completed, finished), finished,
|
|
74
|
+
counts, latency, ...tokenTotals, finalTextCharacters: distribution(runs.map(r => r.finalTextCharacters)),
|
|
75
|
+
cache: aggregateCache(runs, "cache"), compactionCache: aggregateCache(runs, "compactionCache"),
|
|
76
|
+
signals: Object.fromEntries([...new Set(runs.flatMap(r => r.signals))].map(key => [key, runs.filter(r => r.signals.includes(key)).length])) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Derived observations, never a quality grade or lifecycle authority. */
|
|
80
|
+
function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}) {
|
|
81
|
+
const now = options.now ?? Date.now();
|
|
82
|
+
const parseBound = key => {
|
|
83
|
+
if (!options[key]) return null;
|
|
84
|
+
const parsed = time(options[key]);
|
|
85
|
+
if (parsed === null) throw new Error(`${key} must be an ISO timestamp`);
|
|
86
|
+
return parsed;
|
|
87
|
+
};
|
|
88
|
+
const since = parseBound("since"), until = parseBound("until");
|
|
89
|
+
if (since !== null && until !== null && since > until) throw new Error("since must not be after until");
|
|
90
|
+
const runs = new Map();
|
|
91
|
+
const reportsByTask = new Map();
|
|
92
|
+
const enqueuedBySequence = new Map();
|
|
93
|
+
for (const event of events.filter(e => e.type === "queue.enqueued")) enqueuedBySequence.set(`${event.agentId}:${event.busSequence}`, time(event.time));
|
|
94
|
+
for (const event of events.filter(e => e.type?.startsWith("report."))) {
|
|
95
|
+
const key = `${event.taskId}:${event.agentId}`;
|
|
96
|
+
if (!reportsByTask.has(key)) reportsByTask.set(key, []);
|
|
97
|
+
reportsByTask.get(key).push(event);
|
|
98
|
+
}
|
|
99
|
+
let uncorrelatedEvents = 0;
|
|
100
|
+
for (const event of events) {
|
|
101
|
+
const type = event.type || "";
|
|
102
|
+
if (!/^(?:task\.|request.accepted|run.config|model\.|tool\.|message.delta|thinking.delta|context.compaction|loop\.|interaction\.)/.test(type)) continue;
|
|
103
|
+
if (!event.taskRunId) { uncorrelatedEvents += 1; continue; }
|
|
104
|
+
let run = runs.get(event.taskRunId);
|
|
105
|
+
if (!run) {
|
|
106
|
+
run = { taskRunId: event.taskRunId, taskId: event.taskId || event.taskRunId, agentId: event.agentId || "", sessionId: event.sessionId || "",
|
|
107
|
+
parentTaskRunId: event.parentTaskRunId || null, traceId: event.traceId || null, status: "unknown", configuration: null,
|
|
108
|
+
accepted: null, enqueued: null, started: null, ended: null, lastActivity: null, firstText: null, firstThinking: null,
|
|
109
|
+
activeStart: null, pausedAt: null, activeMs: 0, waitingUserMs: 0, attempts: new Set(), tools: new Map(),
|
|
110
|
+
usageSamples: [], modelOutcomes: 0, compactionUsageSamples: [], terminalUsage: null, finalTextCharacters: null, streamedCharacters: 0,
|
|
111
|
+
counts: { modelCalls: 0, sdkTurns: 0, modelFailures: 0, toolCalls: 0, toolErrors: 0, toolExceptions: 0, toolRejections: 0, unresolvedTools: 0,
|
|
112
|
+
repeatedToolCalls: 0, loopWarnings: 0, loopStops: 0, modelRetries: 0, compactionAttempts: 0, compactions: 0, compactionFailures: 0 },
|
|
113
|
+
modelDurations: [], modelStarts: new Map(), toolDurations: [], compactionDurations: [], fingerprints: new Map(), errorCodes: {} };
|
|
114
|
+
runs.set(event.taskRunId, run);
|
|
115
|
+
}
|
|
116
|
+
run.agentId ||= event.agentId || "";
|
|
117
|
+
run.sessionId ||= event.sessionId || "";
|
|
118
|
+
const timestamp = time(event.time);
|
|
119
|
+
if (timestamp !== null) run.lastActivity = Math.max(run.lastActivity ?? timestamp, timestamp);
|
|
120
|
+
if (event.attemptId) run.attempts.add(event.attemptId);
|
|
121
|
+
if (type === "run.config") run.configuration = event.configuration || null;
|
|
122
|
+
if (type === "request.accepted") { run.accepted ??= timestamp; if (run.started === null) run.status = "queued"; }
|
|
123
|
+
if (type === "task.started") {
|
|
124
|
+
run.started ??= timestamp;
|
|
125
|
+
if (event.queueSequence != null) run.enqueued ??= enqueuedBySequence.get(`${run.agentId}:${event.queueSequence}`) ?? null;
|
|
126
|
+
// SDK/native presentation can repeat the same committed lifecycle.
|
|
127
|
+
if (run.activeStart === null) run.activeStart = timestamp;
|
|
128
|
+
if (run.pausedAt !== null) { run.waitingUserMs += difference(timestamp, run.pausedAt) || 0; run.pausedAt = null; }
|
|
129
|
+
run.status = "running";
|
|
130
|
+
}
|
|
131
|
+
if (type === "task.paused" || /^task\.(completed|failed|cancelled|interrupted)$/.test(type)) {
|
|
132
|
+
if (run.activeStart !== null) { run.activeMs += difference(timestamp, run.activeStart) || 0; run.activeStart = null; }
|
|
133
|
+
run.status = type === "task.paused" ? "waiting_user" : type.slice(5);
|
|
134
|
+
if (type === "task.paused") run.pausedAt ??= timestamp;
|
|
135
|
+
else run.ended = timestamp;
|
|
136
|
+
run.terminalUsage = normalizedUsage(event.usage) || run.terminalUsage;
|
|
137
|
+
if (number(event.finalTextCharacters) !== null) run.finalTextCharacters = event.finalTextCharacters;
|
|
138
|
+
}
|
|
139
|
+
if (type === "message.delta" && event.textCharacters > 0) { run.firstText ??= timestamp; run.streamedCharacters += event.textCharacters; }
|
|
140
|
+
if (type === "thinking.delta" && event.textCharacters > 0) run.firstThinking ??= timestamp;
|
|
141
|
+
if (type === "model.started") {
|
|
142
|
+
run.counts[event.modelScope === "sdk-turn" ? "sdkTurns" : "modelCalls"] += 1;
|
|
143
|
+
run.provider ||= event.provider || ""; run.model ||= event.model || "";
|
|
144
|
+
run.modelStarts.set(event.turnId || event.modelScope || "api-call", timestamp);
|
|
145
|
+
}
|
|
146
|
+
if (["model.completed", "model.failed"].includes(type)) {
|
|
147
|
+
run.modelOutcomes += 1;
|
|
148
|
+
const key = event.turnId || event.modelScope || "api-call";
|
|
149
|
+
const duration = number(event.durationMs) ?? difference(timestamp, run.modelStarts.get(key) ?? null);
|
|
150
|
+
if (duration !== null) run.modelDurations.push(duration);
|
|
151
|
+
run.modelStarts.delete(key);
|
|
152
|
+
if (type === "model.failed") run.counts.modelFailures += 1;
|
|
153
|
+
else { const usage = normalizedUsage(event.usage); if (usage) run.usageSamples.push(usage); }
|
|
154
|
+
}
|
|
155
|
+
if (type === "model.retry") run.counts.modelRetries += 1;
|
|
156
|
+
if (type === "loop.warning") run.counts.loopWarnings += 1;
|
|
157
|
+
if (type === "loop.stopped") run.counts.loopStops += 1;
|
|
158
|
+
if (["tool.started", "tool.completed", "tool.failed", "tool.rejected"].includes(type)) {
|
|
159
|
+
const id = event.toolCallId || event.id;
|
|
160
|
+
const tool = run.tools.get(id) || { started: false, ended: false, outcome: null, startedAt: null, name: event.toolName || "" };
|
|
161
|
+
tool.name ||= event.toolName || "";
|
|
162
|
+
if (type === "tool.started" && !tool.started) {
|
|
163
|
+
tool.started = true; tool.startedAt = timestamp; run.counts.toolCalls += 1;
|
|
164
|
+
if (event.argumentFingerprint) {
|
|
165
|
+
const key = `${tool.name}:${event.argumentFingerprint}`;
|
|
166
|
+
if (run.fingerprints.has(key)) run.counts.repeatedToolCalls += 1;
|
|
167
|
+
run.fingerprints.set(key, (run.fingerprints.get(key) || 0) + 1);
|
|
168
|
+
}
|
|
169
|
+
} else if (type !== "tool.started" && !tool.ended) {
|
|
170
|
+
tool.ended = true;
|
|
171
|
+
tool.outcome = type === "tool.failed" ? "unknown" : type === "tool.rejected" ? "rejected" : event.ok === false ? "error" : "ok";
|
|
172
|
+
if (tool.outcome === "error") run.counts.toolErrors += 1;
|
|
173
|
+
if (type === "tool.failed") run.counts.toolExceptions += 1;
|
|
174
|
+
if (tool.outcome === "rejected") run.counts.toolRejections += 1;
|
|
175
|
+
const duration = number(event.durationMs) ?? difference(timestamp, tool.startedAt);
|
|
176
|
+
if (duration !== null) run.toolDurations.push(duration);
|
|
177
|
+
}
|
|
178
|
+
run.tools.set(id, tool);
|
|
179
|
+
}
|
|
180
|
+
if (type === "context.compaction.started") run.counts.compactionAttempts += 1;
|
|
181
|
+
if (type === "context.compaction.completed") {
|
|
182
|
+
run.counts.compactions += 1;
|
|
183
|
+
const usage = normalizedUsage(event.usage);
|
|
184
|
+
if (usage) run.compactionUsageSamples.push(usage);
|
|
185
|
+
}
|
|
186
|
+
if (type === "context.compaction.failed") run.counts.compactionFailures += 1;
|
|
187
|
+
if (["context.compaction.completed", "context.compaction.failed"].includes(type) && number(event.durationMs) !== null) run.compactionDurations.push(event.durationMs);
|
|
188
|
+
const code = event.code || event.resultCode;
|
|
189
|
+
if (code && (type.endsWith("failed") || type === "tool.rejected" || type === "model.retry" || event.ok === false)) run.errorCodes[code] = (run.errorCodes[code] || 0) + 1;
|
|
190
|
+
}
|
|
191
|
+
const rows = [];
|
|
192
|
+
for (const run of runs.values()) {
|
|
193
|
+
const anchor = run.started ?? run.accepted ?? run.lastActivity;
|
|
194
|
+
const config = run.configuration;
|
|
195
|
+
const provider = config?.provider || run.provider || "unknown", model = config?.model || run.model || "unknown";
|
|
196
|
+
if (since !== null && (anchor === null || anchor < since) || until !== null && (anchor === null || anchor >= until)) continue;
|
|
197
|
+
if (options.provider && provider !== options.provider || options.model && model !== options.model) continue;
|
|
198
|
+
const end = run.ended ?? now;
|
|
199
|
+
const paired = [...run.tools.values()];
|
|
200
|
+
run.counts.unresolvedTools = paired.filter(t => !t.ended || t.outcome === "unknown").length;
|
|
201
|
+
const modelStarts = run.counts.modelCalls + run.counts.sdkTurns;
|
|
202
|
+
// Terminal native usage is an accumulator with zero defaults. Do not use
|
|
203
|
+
// it to invent token counts when observed model calls omitted usage.
|
|
204
|
+
const usage = run.usageSamples.length ? run.usageSamples : !modelStarts && !run.modelOutcomes && run.terminalUsage ? [run.terminalUsage] : [];
|
|
205
|
+
const cache = cacheObservation(usage, config, provider);
|
|
206
|
+
const usageComplete = modelStarts ? run.usageSamples.length === modelStarts : !run.modelOutcomes && usage.length > 0;
|
|
207
|
+
const sumUsage = samples => Object.fromEntries(["input", "output", "cacheRead", "cacheCreation"].map(key => {
|
|
208
|
+
const values = samples.map(u => u[key]).filter(v => v !== null);
|
|
209
|
+
return [key, values.length ? values.reduce((a, b) => a + b, 0) : null];
|
|
210
|
+
}));
|
|
211
|
+
const signals = [];
|
|
212
|
+
if (run.counts.toolErrors) signals.push("tool_errors");
|
|
213
|
+
if (run.counts.unresolvedTools) signals.push("unresolved_tools");
|
|
214
|
+
if (run.counts.toolRejections) signals.push("rejected_tool_calls");
|
|
215
|
+
if (run.counts.repeatedToolCalls) signals.push("repeated_tool_arguments");
|
|
216
|
+
if (run.counts.loopStops) signals.push("loop_guard_stopped");
|
|
217
|
+
if (run.counts.compactionFailures) signals.push("compaction_failed");
|
|
218
|
+
const idleMs = terminal.has(run.status) ? null : difference(now, run.lastActivity);
|
|
219
|
+
if (run.status === "running" && idleMs > (options.idleThresholdMs || 300000)) signals.push("running_without_recent_events");
|
|
220
|
+
const reports = reportsByTask.get(`${run.taskId}:${run.agentId}`) || [];
|
|
221
|
+
const reportLengths = reports.map(r => number(r.reportCharacters)).filter(v => v !== null);
|
|
222
|
+
if (reportLengths.some(value => value > 600)) signals.push("long_report");
|
|
223
|
+
const lifecycleComplete = run.started !== null && (terminal.has(run.status) ? run.ended !== null : true);
|
|
224
|
+
const durations = values => values.length ? values.reduce((a, b) => a + b, 0) : null;
|
|
225
|
+
rows.push({ taskRunId: run.taskRunId, taskId: run.taskId, agentId: run.agentId, sessionId: run.sessionId,
|
|
226
|
+
parentTaskRunId: run.parentTaskRunId, traceId: run.traceId, status: run.status, provider, model,
|
|
227
|
+
startedAt: run.started !== null ? new Date(run.started).toISOString() : null,
|
|
228
|
+
endedAt: run.ended !== null ? new Date(run.ended).toISOString() : null,
|
|
229
|
+
configuration: config, attempts: run.attempts.size || null, counts: run.counts, usage: sumUsage(usage), compactionUsage: sumUsage(run.compactionUsageSamples),
|
|
230
|
+
cache, compactionCache: cacheObservation(run.compactionUsageSamples, config, provider),
|
|
231
|
+
queueTimingSource: run.enqueued !== null ? "bus.sequence" : run.accepted !== null ? "request.accepted" : "unknown",
|
|
232
|
+
finalTextCharacters: run.finalTextCharacters, streamedCharacters: run.streamedCharacters,
|
|
233
|
+
reportCharacters: distribution(reportLengths), errorCodes: run.errorCodes, signals,
|
|
234
|
+
coverage: { configuration: Boolean(config), lifecycle: lifecycleComplete, usage: usage.length > 0,
|
|
235
|
+
usageComplete, cache: cache.samples > 0, cacheComplete: usageComplete && cache.samples === usage.length,
|
|
236
|
+
toolFingerprints: run.counts.toolCalls ? [...run.fingerprints.values()].reduce((a, b) => a + b, 0) : 0 },
|
|
237
|
+
timings: { elapsedMs: lifecycleComplete ? difference(end, run.started) : null,
|
|
238
|
+
activeMs: lifecycleComplete ? run.activeMs + (run.activeStart !== null ? difference(end, run.activeStart) || 0 : 0) : null,
|
|
239
|
+
queueMs: difference(run.started, run.enqueued ?? run.accepted), firstTextMs: difference(run.firstText, run.started),
|
|
240
|
+
firstThinkingMs: difference(run.firstThinking, run.started), modelMs: durations(run.modelDurations), toolMs: durations(run.toolDurations),
|
|
241
|
+
compactionMs: durations(run.compactionDurations), waitingUserMs: run.waitingUserMs + (run.pausedAt !== null ? difference(end, run.pausedAt) || 0 : 0), idleMs } });
|
|
242
|
+
}
|
|
243
|
+
rows.sort((a, b) => String(a.startedAt || "").localeCompare(String(b.startedAt || "")) || a.taskRunId.localeCompare(b.taskRunId));
|
|
244
|
+
const groups = new Map();
|
|
245
|
+
for (const run of rows) {
|
|
246
|
+
const cohort = { provider: run.provider, model: run.model, thinkingLevel: run.configuration?.thinkingLevel || "unknown",
|
|
247
|
+
engineFingerprint: run.configuration?.engineFingerprint || "unknown",
|
|
248
|
+
requestKind: run.configuration?.requestKind || "unknown",
|
|
249
|
+
runtimeVersion: run.configuration?.runtimeVersion || "unknown", executionKind: run.configuration?.executionKind || (run.counts.sdkTurns ? "sdk" : "native") };
|
|
250
|
+
const key = JSON.stringify(cohort);
|
|
251
|
+
if (!groups.has(key)) groups.set(key, { cohort, runs: [] });
|
|
252
|
+
groups.get(key).runs.push(run);
|
|
253
|
+
}
|
|
254
|
+
const taskIds = new Set(rows.flatMap(run => [run.taskId, run.taskRunId]));
|
|
255
|
+
const selectedTasks = tasks.filter(task => (since === null && until === null && !options.provider && !options.model) || [task.taskId, task.taskRunId, task.id].some(id => id && taskIds.has(id)));
|
|
256
|
+
const delegated = selectedTasks.filter(task => task.taskId && task.workerId);
|
|
257
|
+
const accepted = delegated.filter(t => t.status === "accepted").length, rejected = delegated.filter(t => t.status === "rejected").length;
|
|
258
|
+
const reported = delegated.filter(t => ["done", "error"].includes(t.report?.phase)).length;
|
|
259
|
+
const warnings = [...(options.warnings || [])];
|
|
260
|
+
if (groups.size > 100) warnings.push({ code: "performance_cohort_limit", total: groups.size, read: 100 });
|
|
261
|
+
if (uncorrelatedEvents) warnings.push({ code: "performance_uncorrelated_events", count: uncorrelatedEvents });
|
|
262
|
+
const partialRuns = rows.filter(r => !r.coverage.lifecycle).length;
|
|
263
|
+
if (partialRuns) warnings.push({ code: "performance_partial_lifecycle", count: partialRuns });
|
|
264
|
+
const limit = options.includeRuns === false ? 0 : Math.min(100, Math.max(1, Math.floor(Number(options.limit) || 20)));
|
|
265
|
+
return { version: 1, generatedAt: new Date(now).toISOString(), window: { since: options.since || null, until: options.until || null, selection: "run-start; until exclusive" },
|
|
266
|
+
summary: aggregate(rows), cohorts: [...groups.values()].sort((a, b) => b.runs.length - a.runs.length).slice(0, 100).map(g => ({ ...g.cohort, ...aggregate(g.runs) })),
|
|
267
|
+
delegations: { tasks: delegated.length, accepted, rejected, reported, awaitingAcceptance: delegated.filter(t => t.status === "reported").length,
|
|
268
|
+
failed: delegated.filter(t => t.status === "failed").length, deliveryUncertain: delegated.filter(t => t.status === "delivery_uncertain").length,
|
|
269
|
+
acceptedOfReviewed: rate(accepted, accepted + rejected), acceptedOfReported: rate(accepted, reported),
|
|
270
|
+
reportToAcceptanceMs: distribution(delegated.map(task => difference(time(task.acceptance?.time), time(task.report?.ts)))) },
|
|
271
|
+
queues: queues.map(q => ({ ...q, ageMs: difference(now, time(q.enqueuedAt)) })).slice(-100),
|
|
272
|
+
coverage: { runsWithConfiguration: rows.filter(r => r.coverage.configuration).length, runsWithUsage: rows.filter(r => r.coverage.usage).length,
|
|
273
|
+
runsWithCompleteUsage: rows.filter(r => r.coverage.usageComplete).length,
|
|
274
|
+
runsWithCache: rows.filter(r => r.coverage.cache).length, runsWithCompleteCache: rows.filter(r => r.coverage.cacheComplete).length,
|
|
275
|
+
partialRuns, uncorrelatedEvents, retainedRuns: Math.min(rows.length, limit), runLimit: limit },
|
|
276
|
+
runs: limit ? rows.slice(-limit) : [], incomplete: warnings.length > 0, warnings };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
module.exports = { summarizeAgentPerformance, distribution };
|