ctxtop 0.0.0-stage → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { getHomeDir } from './paths.mjs';
|
|
3
|
+
import { findSessionDirectory, parseTranscriptIncremental } from './parser.mjs';
|
|
4
|
+
import {
|
|
5
|
+
normalizeModelId,
|
|
6
|
+
resolveModelDescriptor,
|
|
7
|
+
resolveModelRates,
|
|
8
|
+
calculateModelCost,
|
|
9
|
+
createSwarmAgentState,
|
|
10
|
+
validateSwarmAgentState,
|
|
11
|
+
CORE_SCHEMAS
|
|
12
|
+
} from './constants.mjs';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Multi-Agent (`invoke_subagent`) Context Tree & Handoff Inspector.
|
|
16
|
+
*
|
|
17
|
+
* Scans parent transcript steps for `invoke_subagent` tool calls, resolves child
|
|
18
|
+
* session transcripts across `inherit`, `branch`, and `share` workspace modes,
|
|
19
|
+
* and computes isolated child exploration bloat vs. parent handoff compression.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export const HANDOFF_BLOAT_THRESHOLD_TOKENS = 4000;
|
|
23
|
+
|
|
24
|
+
export function inspectSubagentTree(steps = [], {
|
|
25
|
+
homeDir = getHomeDir(),
|
|
26
|
+
cacheDir = null
|
|
27
|
+
} = {}) {
|
|
28
|
+
const invocations = [];
|
|
29
|
+
const childIdsSeen = new Set();
|
|
30
|
+
|
|
31
|
+
for (let i = 0; i < steps.length; i++) {
|
|
32
|
+
const step = steps[i] || {};
|
|
33
|
+
const calls = step.toolCalls || [];
|
|
34
|
+
for (const call of calls) {
|
|
35
|
+
const name = String(call.name || '').toLowerCase();
|
|
36
|
+
if (name === 'invoke_subagent') {
|
|
37
|
+
const args = call.args || {};
|
|
38
|
+
const role = args.Role || args.role || 'Subagent';
|
|
39
|
+
const typeName = args.TypeName || args.typeName || 'self';
|
|
40
|
+
const workspaceMode = args.Workspace || args.workspace || 'inherit';
|
|
41
|
+
const model = args.Model || args.model || 'inherit';
|
|
42
|
+
|
|
43
|
+
// Extract returned conversationId or subagent response from subsequent steps
|
|
44
|
+
let childConversationId = call.result?.conversationId || call.conversationId || args.conversationId || null;
|
|
45
|
+
let handoffTokens = 0;
|
|
46
|
+
let handoffStepIdx = i;
|
|
47
|
+
|
|
48
|
+
// Look ahead up to 6 steps for the subagent completion/response or conversationId
|
|
49
|
+
for (let j = i; j < Math.min(steps.length, i + 7); j++) {
|
|
50
|
+
const lookStep = steps[j] || {};
|
|
51
|
+
const text = String(lookStep.content || '');
|
|
52
|
+
if (!childConversationId) {
|
|
53
|
+
const matches = text.matchAll(/conversation(?:Id|_id)["'\s:=]+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi);
|
|
54
|
+
for (const m of matches) {
|
|
55
|
+
if (m[1] && !childIdsSeen.has(m[1])) {
|
|
56
|
+
childConversationId = m[1];
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const isParentStep = !lookStep.agentId || lookStep.agentId === 'parent';
|
|
62
|
+
if (j > i && isParentStep && (text.toLowerCase().includes('subagent') || text.includes(role))) {
|
|
63
|
+
const est = lookStep.outputTokens || Math.ceil(text.length / 4) || 0;
|
|
64
|
+
if (est > handoffTokens) {
|
|
65
|
+
handoffTokens = est;
|
|
66
|
+
handoffStepIdx = j;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (handoffTokens === 0) {
|
|
72
|
+
handoffTokens = Math.max(250, Math.min(2500, Math.ceil(String(step.content || '').length / 4) || 600));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let isolatedTokens = 0;
|
|
76
|
+
let childStepCount = 0;
|
|
77
|
+
|
|
78
|
+
// If child session exists on disk, measure its isolated transcript size
|
|
79
|
+
if (childConversationId) {
|
|
80
|
+
childIdsSeen.add(childConversationId);
|
|
81
|
+
try {
|
|
82
|
+
const childSession = findSessionDirectory(childConversationId, homeDir);
|
|
83
|
+
if (childSession && fs.existsSync(childSession.sessionDir)) {
|
|
84
|
+
const parsedChild = parseTranscriptIncremental(childSession.sessionDir, cacheDir);
|
|
85
|
+
childStepCount = (parsedChild.steps || []).length;
|
|
86
|
+
isolatedTokens = (parsedChild.steps || []).reduce((sum, cs) => {
|
|
87
|
+
const tok = cs.outputTokens || Math.ceil((cs.untruncatedLength || 0) / 4) || 500;
|
|
88
|
+
return sum + tok;
|
|
89
|
+
}, 0);
|
|
90
|
+
}
|
|
91
|
+
} catch {}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Fallback estimate for child steps embedded via agentId === `child:...`
|
|
95
|
+
if (isolatedTokens === 0) {
|
|
96
|
+
const embeddedChildSteps = steps.filter(s => s.agentId && s.agentId !== 'parent');
|
|
97
|
+
if (embeddedChildSteps.length > 0) {
|
|
98
|
+
childStepCount = embeddedChildSteps.length;
|
|
99
|
+
isolatedTokens = embeddedChildSteps.reduce((sum, cs) => sum + (cs.outputTokens || Math.ceil((cs.untruncatedLength || 0) / 4) || 800), 0);
|
|
100
|
+
} else {
|
|
101
|
+
isolatedTokens = Math.max(handoffTokens * 12, 18000);
|
|
102
|
+
childStepCount = 8;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const compressionRatio = parseFloat((isolatedTokens / Math.max(1, handoffTokens)).toFixed(1));
|
|
107
|
+
const rawDumpLeak = handoffTokens >= HANDOFF_BLOAT_THRESHOLD_TOKENS;
|
|
108
|
+
|
|
109
|
+
const resolvedConvId = childConversationId || `subagent-step-${i}-${invocations.length}`;
|
|
110
|
+
if (invocations.some((inv) => inv.conversationId === resolvedConvId)) {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
invocations.push({
|
|
115
|
+
stepIndex: i,
|
|
116
|
+
handoffStepIndex: handoffStepIdx,
|
|
117
|
+
conversationId: resolvedConvId,
|
|
118
|
+
role,
|
|
119
|
+
typeName,
|
|
120
|
+
workspaceMode,
|
|
121
|
+
model,
|
|
122
|
+
childStepCount,
|
|
123
|
+
isolatedTokens,
|
|
124
|
+
handoffTokens,
|
|
125
|
+
tokensSaved: Math.max(0, isolatedTokens - handoffTokens),
|
|
126
|
+
compressionRatio,
|
|
127
|
+
rawDumpLeak,
|
|
128
|
+
badgeLabel: `[Subagent: ${typeName} | ${(isolatedTokens / 1000).toFixed(1)}k isolated -> ${(handoffTokens / 1000).toFixed(1)}k handoff (${Math.round(compressionRatio)}x)]`
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const totalIsolatedTokens = invocations.reduce((s, x) => s + x.isolatedTokens, 0);
|
|
135
|
+
const totalHandoffTokens = invocations.reduce((s, x) => s + x.handoffTokens, 0);
|
|
136
|
+
const totalSavedTokens = invocations.reduce((s, x) => s + x.tokensSaved, 0);
|
|
137
|
+
const overallCompressionRatio = totalHandoffTokens > 0
|
|
138
|
+
? parseFloat((totalIsolatedTokens / totalHandoffTokens).toFixed(1))
|
|
139
|
+
: 0;
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
count: invocations.length,
|
|
143
|
+
totalIsolatedTokens,
|
|
144
|
+
totalHandoffTokens,
|
|
145
|
+
totalSavedTokens,
|
|
146
|
+
overallCompressionRatio,
|
|
147
|
+
hasRawDumpLeak: invocations.some(x => x.rawDumpLeak),
|
|
148
|
+
invocations
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Builds a parent -> subagent worktree DAG (`inherit`, `branch`, `share`),
|
|
154
|
+
* tracking isolated vs handoff tokens, `cacheCreationEphemeral5mInputTokens` TTL countdowns,
|
|
155
|
+
* and detecting concurrent `fileCollisions` when >= 2 active subagents edit the same file path.
|
|
156
|
+
*/
|
|
157
|
+
export function buildSubagentWorktreeDag(steps = [], { childTranscripts = [], nowMs = Date.now() } = {}) {
|
|
158
|
+
const baseTree = inspectSubagentTree(steps);
|
|
159
|
+
const editsByAgent = new Map(); // canonPath -> Set<agentId>
|
|
160
|
+
const readsByAgent = new Map(); // canonPath -> Set<agentId>
|
|
161
|
+
const nodes = [];
|
|
162
|
+
|
|
163
|
+
for (const child of (childTranscripts || [])) {
|
|
164
|
+
const agentId = String(child.agentId || child.conversationId || `sub-${nodes.length}`);
|
|
165
|
+
const workspaceMode = child.workspaceMode || 'inherit';
|
|
166
|
+
const childSteps = Array.isArray(child.steps) ? child.steps : [];
|
|
167
|
+
let isolatedTokens = 0;
|
|
168
|
+
let latestTs = 0;
|
|
169
|
+
const modifiedFiles = new Set();
|
|
170
|
+
const readFiles = new Set();
|
|
171
|
+
|
|
172
|
+
for (const cs of childSteps) {
|
|
173
|
+
isolatedTokens += Math.max(0, Number(cs.outputTokens ?? cs.output_tokens ?? 0) || 0);
|
|
174
|
+
const ts = cs.createdAt ? Date.parse(cs.createdAt) : (cs.timestamp ? Date.parse(cs.timestamp) : 0);
|
|
175
|
+
if (Number.isFinite(ts) && ts > latestTs) latestTs = ts;
|
|
176
|
+
|
|
177
|
+
const calls = Array.isArray(cs.toolCalls) ? cs.toolCalls : (Array.isArray(cs.tool_calls) ? cs.tool_calls : []);
|
|
178
|
+
for (const c of calls) {
|
|
179
|
+
const name = String(c.name || c.tool || '').toLowerCase();
|
|
180
|
+
const args = c.args || c.parameters || c.Arguments || {};
|
|
181
|
+
const fp = args.Path || args.path || args.TargetFile || args.AbsolutePath;
|
|
182
|
+
if (fp && /edit|write|replace/i.test(name)) {
|
|
183
|
+
const norm = String(fp).replace(/\\/g, '/').toLowerCase();
|
|
184
|
+
modifiedFiles.add(norm);
|
|
185
|
+
if (!editsByAgent.has(norm)) editsByAgent.set(norm, new Set());
|
|
186
|
+
editsByAgent.get(norm).add(agentId);
|
|
187
|
+
}
|
|
188
|
+
if (fp && /view|read/i.test(name)) {
|
|
189
|
+
const norm = String(fp).replace(/\\/g, '/').toLowerCase();
|
|
190
|
+
readFiles.add(norm);
|
|
191
|
+
if (!readsByAgent.has(norm)) readsByAgent.set(norm, new Set());
|
|
192
|
+
readsByAgent.get(norm).add(agentId);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const idleSec = latestTs > 0 ? Math.max(0, Math.round((nowMs - latestTs) / 1000)) : 0;
|
|
198
|
+
const ttlRemainingSec = latestTs > 0 ? Math.max(0, 300 - idleSec) : 300;
|
|
199
|
+
|
|
200
|
+
nodes.push({
|
|
201
|
+
agentId,
|
|
202
|
+
workspaceMode,
|
|
203
|
+
isolatedTokens,
|
|
204
|
+
ttlWindowSec: 300,
|
|
205
|
+
ttlRemainingSec,
|
|
206
|
+
modifiedFiles: Array.from(modifiedFiles),
|
|
207
|
+
readFiles: Array.from(readFiles)
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const fileCollisions = [];
|
|
212
|
+
for (const [filePath, agentsSet] of editsByAgent.entries()) {
|
|
213
|
+
if (agentsSet.size >= 2) {
|
|
214
|
+
fileCollisions.push({
|
|
215
|
+
filePath,
|
|
216
|
+
agents: Array.from(agentsSet),
|
|
217
|
+
severity: 'CONCURRENT_EDIT_COLLISION'
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const readCollisions = [];
|
|
223
|
+
for (const [filePath, agentsSet] of readsByAgent.entries()) {
|
|
224
|
+
if (agentsSet.size >= 2) {
|
|
225
|
+
readCollisions.push({
|
|
226
|
+
filePath,
|
|
227
|
+
agents: Array.from(agentsSet),
|
|
228
|
+
severity: 'DUPLICATE_READ_COLLISION'
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
parentInvocationCount: baseTree.count,
|
|
235
|
+
nodes,
|
|
236
|
+
fileCollisions,
|
|
237
|
+
hasFileCollision: fileCollisions.length > 0,
|
|
238
|
+
readCollisions,
|
|
239
|
+
hasReadCollision: readCollisions.length > 0
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export const SWARM_IDLE_TTL_CONSTANTS = Object.freeze({
|
|
244
|
+
DEFAULT_CACHE_TTL_MS: 300000, // 5 minutes (300,000 ms)
|
|
245
|
+
DEFAULT_COLD_WAKE_THRESHOLD_TOKENS: 100000, // 100,000 warm prefix tokens
|
|
246
|
+
CLIFF_WARNING_SECONDS: 60, // warn when within 60 seconds of falling off cache cliff
|
|
247
|
+
SWARM_TOOL_MATCHER: 'invoke_subagent|define_subagent|send_message|manage_subagents'
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Determines whether a model is considered a frontier model subject to cold-cache wakeup diagnostics.
|
|
252
|
+
*/
|
|
253
|
+
export function isFrontierSwarmModel(modelId = '') {
|
|
254
|
+
const desc = resolveModelDescriptor(modelId);
|
|
255
|
+
if (desc && (desc.family === 'carbon' || desc.family === 'argon' || desc.family === 'opus' || desc.family === 'sonnet')) {
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
const norm = normalizeModelId(modelId);
|
|
259
|
+
return norm.includes('carbon') || norm.includes('argon') || norm.includes('opus') || norm.includes('pro');
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Extracts target recipient agent IDs from a `send_message` tool call or `@mention` text.
|
|
264
|
+
*/
|
|
265
|
+
export function extractTargetRecipientAgents(toolInput = {}, rawText = '') {
|
|
266
|
+
const targets = new Set();
|
|
267
|
+
const recipient = toolInput?.Recipient || toolInput?.recipient || toolInput?.targetAgent || toolInput?.agent_id || toolInput?.agentId;
|
|
268
|
+
if (recipient && typeof recipient === 'string' && recipient.trim()) {
|
|
269
|
+
targets.add(recipient.trim());
|
|
270
|
+
}
|
|
271
|
+
const msgText = String(toolInput?.Message || toolInput?.message || toolInput?.brief || rawText || '');
|
|
272
|
+
const mentionMatches = msgText.match(/@([a-z0-9_-]+)/gi) || [];
|
|
273
|
+
for (const m of mentionMatches) {
|
|
274
|
+
const clean = m.slice(1).trim();
|
|
275
|
+
if (clean) targets.add(clean);
|
|
276
|
+
}
|
|
277
|
+
return Array.from(targets);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Computes per-agent TTL countdown badges for the local state JSON so the UI/statusline
|
|
282
|
+
* warns when a parked Carbon coordinator or verifier is within 60 seconds of falling off the cache cliff.
|
|
283
|
+
*/
|
|
284
|
+
export function computeSwarmRosterTtlBadges(swarmRoster = {}, {
|
|
285
|
+
nowMs = Date.now(),
|
|
286
|
+
cacheTtlMs = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS
|
|
287
|
+
} = {}) {
|
|
288
|
+
const badges = [];
|
|
289
|
+
const entries = swarmRoster instanceof Map
|
|
290
|
+
? Array.from(swarmRoster.entries())
|
|
291
|
+
: Object.entries(swarmRoster || {});
|
|
292
|
+
|
|
293
|
+
for (const [keyId, rawAgent] of entries) {
|
|
294
|
+
if (!rawAgent || typeof rawAgent !== 'object') continue;
|
|
295
|
+
const state = createSwarmAgentState({ ...rawAgent, agent_id: rawAgent.agent_id || keyId });
|
|
296
|
+
const ttlMs = Number(state.cache_ttl_ms || cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
|
|
297
|
+
const elapsedMs = Math.max(0, nowMs - state.last_active_timestamp);
|
|
298
|
+
const remainingMs = state.status === 'terminated' ? 0 : Math.max(0, ttlMs - elapsedMs);
|
|
299
|
+
const remainingSec = Math.ceil(remainingMs / 1000);
|
|
300
|
+
const isExpired = state.status !== 'terminated' && elapsedMs > ttlMs;
|
|
301
|
+
const isNearCliff = state.status === 'idle_zero_token' && remainingSec > 0 && remainingSec <= SWARM_IDLE_TTL_CONSTANTS.CLIFF_WARNING_SECONDS;
|
|
302
|
+
|
|
303
|
+
const mins = Math.floor(remainingSec / 60);
|
|
304
|
+
const secs = remainingSec % 60;
|
|
305
|
+
const countdownLabel = remainingSec > 0
|
|
306
|
+
? `${mins}m ${String(secs).padStart(2, '0')}s`
|
|
307
|
+
: '0m 00s (expired)';
|
|
308
|
+
|
|
309
|
+
const badgeText = isNearCliff
|
|
310
|
+
? `⚠️ [${state.agent_id} • ${state.model_id}] Cache cliff in ${remainingSec}s (${Math.round(state.warm_prefix_tokens / 1000)}k warm) [CACHE CLIFF WARNING]`
|
|
311
|
+
: (isExpired
|
|
312
|
+
? `❄️ [${state.agent_id} • ${state.model_id}] Cold cache (${Math.round(state.warm_prefix_tokens / 1000)}k expired)`
|
|
313
|
+
: `🟢 [${state.agent_id} • ${state.model_id}] ${countdownLabel} (${Math.round(state.warm_prefix_tokens / 1000)}k warm)`);
|
|
314
|
+
|
|
315
|
+
badges.push({
|
|
316
|
+
agent_id: state.agent_id,
|
|
317
|
+
model_id: state.model_id,
|
|
318
|
+
status: state.status,
|
|
319
|
+
warm_prefix_tokens: state.warm_prefix_tokens,
|
|
320
|
+
last_active_timestamp: state.last_active_timestamp,
|
|
321
|
+
cache_ttl_ms: ttlMs,
|
|
322
|
+
elapsed_ms: elapsedMs,
|
|
323
|
+
ttl_remaining_ms: remainingMs,
|
|
324
|
+
ttl_remaining_sec: remainingSec,
|
|
325
|
+
remaining_ttl_sec: remainingSec,
|
|
326
|
+
is_near_cliff: isNearCliff,
|
|
327
|
+
within_cliff_warning: isNearCliff,
|
|
328
|
+
is_expired: isExpired,
|
|
329
|
+
countdown_label: countdownLabel,
|
|
330
|
+
badge_text: badgeText,
|
|
331
|
+
badge_label: badgeText
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return badges;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Evaluates a `PreToolUse` on `send_message` (or `@mention` dispatch) targeting a specific `Recipient` agent.
|
|
340
|
+
* If the target agent is running `gemini-4-carbon` (or another frontier model), has
|
|
341
|
+
* `warm_prefix_tokens >= cold_wake_threshold` (default 100,000), and `now - target.last_active_timestamp > cache_ttl_ms`,
|
|
342
|
+
* surfaces a Cold-Cache Wakeup diagnostic quantifying the uncached input rebuild cost using `resolveModelRates()`.
|
|
343
|
+
*/
|
|
344
|
+
export function evaluateSwarmColdCacheWakeup({
|
|
345
|
+
recipientAgentId,
|
|
346
|
+
swarmRoster = {},
|
|
347
|
+
nowMs = Date.now(),
|
|
348
|
+
eventTimestampUtc = null,
|
|
349
|
+
serviceTier = 'standard',
|
|
350
|
+
coldWakeThresholdTokens = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS,
|
|
351
|
+
cacheTtlMs = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS
|
|
352
|
+
} = {}) {
|
|
353
|
+
const targetRecord = swarmRoster instanceof Map
|
|
354
|
+
? swarmRoster.get(recipientAgentId)
|
|
355
|
+
: (swarmRoster?.[recipientAgentId] || null);
|
|
356
|
+
|
|
357
|
+
if (!targetRecord) {
|
|
358
|
+
return {
|
|
359
|
+
triggered: false,
|
|
360
|
+
reason: 'UNKNOWN_AGENT',
|
|
361
|
+
recipientAgentId: recipientAgentId || null
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const state = createSwarmAgentState({ ...targetRecord, agent_id: targetRecord.agent_id || recipientAgentId });
|
|
366
|
+
const ttlMs = Number(state.cache_ttl_ms || cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
|
|
367
|
+
const threshold = Number(coldWakeThresholdTokens ?? SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS);
|
|
368
|
+
const elapsedMs = Math.max(0, nowMs - state.last_active_timestamp);
|
|
369
|
+
const elapsedSec = Math.round(elapsedMs / 1000);
|
|
370
|
+
const ttlRemainingSec = Math.max(0, Math.ceil((ttlMs - elapsedMs) / 1000));
|
|
371
|
+
const isCacheExpired = elapsedMs > ttlMs;
|
|
372
|
+
const isFrontier = isFrontierSwarmModel(state.model_id);
|
|
373
|
+
const meetsTokenThreshold = state.warm_prefix_tokens >= threshold;
|
|
374
|
+
|
|
375
|
+
const effectiveTimestamp = eventTimestampUtc ?? nowMs;
|
|
376
|
+
const rates = resolveModelRates(state.model_id, effectiveTimestamp, serviceTier);
|
|
377
|
+
const uncachedRebuildCost = calculateModelCost(
|
|
378
|
+
{ input_tokens: state.warm_prefix_tokens, output_tokens: 0, thinking_tokens: 0, cached_read_tokens: 0 },
|
|
379
|
+
{ modelId: state.model_id, eventTimestampUtc: effectiveTimestamp, serviceTier }
|
|
380
|
+
);
|
|
381
|
+
const warmHitCost = calculateModelCost(
|
|
382
|
+
{ input_tokens: 0, output_tokens: 0, thinking_tokens: 0, cached_read_tokens: state.warm_prefix_tokens },
|
|
383
|
+
{ modelId: state.model_id, eventTimestampUtc: effectiveTimestamp, serviceTier }
|
|
384
|
+
);
|
|
385
|
+
|
|
386
|
+
const rebuildCostUsd = uncachedRebuildCost.inputCostUsd;
|
|
387
|
+
const warmReadCostUsd = warmHitCost.cachedReadCostUsd;
|
|
388
|
+
const penaltyDeltaUsd = Number((rebuildCostUsd - warmReadCostUsd).toFixed(6));
|
|
389
|
+
|
|
390
|
+
if (state.status !== 'terminated' && isFrontier && meetsTokenThreshold && isCacheExpired) {
|
|
391
|
+
return {
|
|
392
|
+
triggered: true,
|
|
393
|
+
coldWakeDetected: true,
|
|
394
|
+
cacheWarm: false,
|
|
395
|
+
diagnosticType: 'COLD_CACHE_WAKEUP',
|
|
396
|
+
recipientAgentId: state.agent_id,
|
|
397
|
+
modelId: state.model_id,
|
|
398
|
+
status: state.status,
|
|
399
|
+
warmPrefixTokens: state.warm_prefix_tokens,
|
|
400
|
+
elapsedMs,
|
|
401
|
+
elapsedSec,
|
|
402
|
+
cacheTtlMs: ttlMs,
|
|
403
|
+
ttlRemainingSec: 0,
|
|
404
|
+
pricingWindow: rates.pricingWindow,
|
|
405
|
+
serviceTier: rates.serviceTier,
|
|
406
|
+
inputRatePer1M: rates.input_per_1m,
|
|
407
|
+
cachedReadRatePer1M: rates.cached_read_per_1m,
|
|
408
|
+
uncachedRebuildCostUsd: rebuildCostUsd,
|
|
409
|
+
warmReadCostUsd,
|
|
410
|
+
penaltyDeltaUsd,
|
|
411
|
+
incrementalColdPenaltyUsd: penaltyDeltaUsd,
|
|
412
|
+
message: `[Cold-Cache Wakeup] Waking idle agent "${state.agent_id}" (${state.model_id}) after ${elapsedSec}s (> ${Math.round(ttlMs / 1000)}s TTL) triggers an uncached rebuild of ${state.warm_prefix_tokens.toLocaleString('en-US')} prefix tokens costing $${rebuildCostUsd.toFixed(4)} ($${rates.input_per_1m.toFixed(2)}/1M ${rates.pricingWindow} ${rates.serviceTier} rate vs $${warmReadCostUsd.toFixed(4)} warm hit).`
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return {
|
|
417
|
+
triggered: false,
|
|
418
|
+
coldWakeDetected: false,
|
|
419
|
+
cacheWarm: !isCacheExpired,
|
|
420
|
+
diagnosticType: 'WARM_CACHE_HIT',
|
|
421
|
+
recipientAgentId: state.agent_id,
|
|
422
|
+
modelId: state.model_id,
|
|
423
|
+
status: state.status,
|
|
424
|
+
warmPrefixTokens: state.warm_prefix_tokens,
|
|
425
|
+
elapsedMs,
|
|
426
|
+
elapsedSec,
|
|
427
|
+
cacheTtlMs: ttlMs,
|
|
428
|
+
ttlRemainingSec,
|
|
429
|
+
pricingWindow: rates.pricingWindow,
|
|
430
|
+
serviceTier: rates.serviceTier,
|
|
431
|
+
uncachedRebuildCostUsd: 0,
|
|
432
|
+
warmReadCostUsd,
|
|
433
|
+
penaltyDeltaUsd: 0,
|
|
434
|
+
incrementalColdPenaltyUsd: 0,
|
|
435
|
+
message: ''
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Stateful `/swarm` roster & idle-TTL tracker for coordinator and subagent lifecycles.
|
|
441
|
+
*/
|
|
442
|
+
export class SwarmIdleTtlTracker {
|
|
443
|
+
constructor(options = {}) {
|
|
444
|
+
this.cacheTtlMs = Number(options.cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
|
|
445
|
+
this.coldWakeThresholdTokens = Number(options.coldWakeThresholdTokens || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS);
|
|
446
|
+
this.roster = new Map();
|
|
447
|
+
if (options.initialRoster && typeof options.initialRoster === 'object') {
|
|
448
|
+
for (const [k, v] of Object.entries(options.initialRoster)) {
|
|
449
|
+
const st = createSwarmAgentState({ ...v, agent_id: v?.agent_id || k, cache_ttl_ms: v?.cache_ttl_ms || this.cacheTtlMs });
|
|
450
|
+
this.roster.set(st.agent_id, st);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
registerOrActivateAgent(agentId, {
|
|
456
|
+
modelId = 'gemini-4-carbon',
|
|
457
|
+
warmPrefixTokens = 0,
|
|
458
|
+
timestampMs = Date.now(),
|
|
459
|
+
role = null
|
|
460
|
+
} = {}) {
|
|
461
|
+
const existing = this.roster.get(agentId);
|
|
462
|
+
const state = createSwarmAgentState({
|
|
463
|
+
agent_id: agentId,
|
|
464
|
+
model_id: modelId || existing?.model_id || 'gemini-4-carbon',
|
|
465
|
+
status: 'active',
|
|
466
|
+
last_active_timestamp: timestampMs,
|
|
467
|
+
warm_prefix_tokens: warmPrefixTokens > 0 ? warmPrefixTokens : (existing?.warm_prefix_tokens || 0),
|
|
468
|
+
cache_ttl_ms: this.cacheTtlMs,
|
|
469
|
+
role: role || existing?.role || null
|
|
470
|
+
});
|
|
471
|
+
this.roster.set(state.agent_id, state);
|
|
472
|
+
return { ...state };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Transitions an agent to `idle_zero_token` when its turn completes while the parent swarm remains live.
|
|
477
|
+
*/
|
|
478
|
+
markTurnCompleted(agentId, {
|
|
479
|
+
warmPrefixTokens = undefined,
|
|
480
|
+
timestampMs = Date.now(),
|
|
481
|
+
parentSwarmLive = true
|
|
482
|
+
} = {}) {
|
|
483
|
+
const existing = this.roster.get(agentId) || createSwarmAgentState({ agent_id: agentId });
|
|
484
|
+
const nextStatus = parentSwarmLive ? 'idle_zero_token' : 'terminated';
|
|
485
|
+
const updated = createSwarmAgentState({
|
|
486
|
+
...existing,
|
|
487
|
+
agent_id: agentId,
|
|
488
|
+
status: nextStatus,
|
|
489
|
+
last_active_timestamp: timestampMs,
|
|
490
|
+
warm_prefix_tokens: warmPrefixTokens !== undefined ? warmPrefixTokens : existing.warm_prefix_tokens,
|
|
491
|
+
cache_ttl_ms: existing.cache_ttl_ms || this.cacheTtlMs
|
|
492
|
+
});
|
|
493
|
+
this.roster.set(updated.agent_id, updated);
|
|
494
|
+
return { ...updated };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
terminateAgent(agentId, timestampMs = Date.now()) {
|
|
498
|
+
const existing = this.roster.get(agentId) || createSwarmAgentState({ agent_id: agentId });
|
|
499
|
+
const updated = createSwarmAgentState({
|
|
500
|
+
...existing,
|
|
501
|
+
agent_id: agentId,
|
|
502
|
+
status: 'terminated',
|
|
503
|
+
last_active_timestamp: timestampMs
|
|
504
|
+
});
|
|
505
|
+
this.roster.set(updated.agent_id, updated);
|
|
506
|
+
return { ...updated };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
interceptSendMessagePreToolUse(toolInput = {}, {
|
|
510
|
+
nowMs = Date.now(),
|
|
511
|
+
eventTimestampUtc = null,
|
|
512
|
+
serviceTier = 'standard'
|
|
513
|
+
} = {}) {
|
|
514
|
+
const recipients = extractTargetRecipientAgents(toolInput);
|
|
515
|
+
const diagnostics = [];
|
|
516
|
+
for (const recipientId of recipients) {
|
|
517
|
+
const diag = evaluateSwarmColdCacheWakeup({
|
|
518
|
+
recipientAgentId: recipientId,
|
|
519
|
+
swarmRoster: this.roster,
|
|
520
|
+
nowMs,
|
|
521
|
+
eventTimestampUtc: eventTimestampUtc ?? nowMs,
|
|
522
|
+
serviceTier,
|
|
523
|
+
coldWakeThresholdTokens: this.coldWakeThresholdTokens,
|
|
524
|
+
cacheTtlMs: this.cacheTtlMs
|
|
525
|
+
});
|
|
526
|
+
diagnostics.push(diag);
|
|
527
|
+
}
|
|
528
|
+
const triggeredDiagnostics = diagnostics.filter(d => d.triggered);
|
|
529
|
+
return {
|
|
530
|
+
triggered: triggeredDiagnostics.length > 0,
|
|
531
|
+
recipients,
|
|
532
|
+
diagnostics,
|
|
533
|
+
coldWakeupAlerts: triggeredDiagnostics,
|
|
534
|
+
primaryAlert: triggeredDiagnostics[0] || null
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
getBadges(nowMsOrOpts = Date.now()) {
|
|
539
|
+
const nowMs = typeof nowMsOrOpts === 'object' && nowMsOrOpts !== null
|
|
540
|
+
? (nowMsOrOpts.nowMs ?? Date.now())
|
|
541
|
+
: nowMsOrOpts;
|
|
542
|
+
return computeSwarmRosterTtlBadges(this.roster, { nowMs, cacheTtlMs: this.cacheTtlMs });
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
getTtlBadges(nowMsOrOpts = Date.now()) {
|
|
546
|
+
return this.getBadges(nowMsOrOpts);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
touchAgentActive(agentId, options = {}) {
|
|
550
|
+
return this.registerOrActivateAgent(agentId, options);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
onTurnComplete(agentId, options = {}) {
|
|
554
|
+
if (options.modelId && !this.roster.has(agentId)) {
|
|
555
|
+
this.registerOrActivateAgent(agentId, {
|
|
556
|
+
modelId: options.modelId,
|
|
557
|
+
warmPrefixTokens: options.warmPrefixTokens ?? 0,
|
|
558
|
+
timestampMs: options.timestampMs ?? Date.now()
|
|
559
|
+
});
|
|
560
|
+
} else if (options.modelId && this.roster.has(agentId)) {
|
|
561
|
+
const cur = this.roster.get(agentId);
|
|
562
|
+
this.roster.set(agentId, { ...cur, model_id: normalizeModelId(options.modelId) });
|
|
563
|
+
}
|
|
564
|
+
return this.markTurnCompleted(agentId, options);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
handlePreToolSendMessage(toolInput = {}, options = {}) {
|
|
568
|
+
const res = this.interceptSendMessagePreToolUse(toolInput, options);
|
|
569
|
+
const primary = res.primaryAlert || res.diagnostics[0] || {
|
|
570
|
+
triggered: false,
|
|
571
|
+
coldWakeDetected: false,
|
|
572
|
+
cacheWarm: true,
|
|
573
|
+
uncachedRebuildCostUsd: 0,
|
|
574
|
+
incrementalColdPenaltyUsd: 0,
|
|
575
|
+
message: ''
|
|
576
|
+
};
|
|
577
|
+
return {
|
|
578
|
+
...primary,
|
|
579
|
+
...res,
|
|
580
|
+
coldWakeDetected: Boolean(primary.coldWakeDetected || res.triggered),
|
|
581
|
+
cacheWarm: Boolean(primary.cacheWarm && !res.triggered),
|
|
582
|
+
uncachedRebuildCostUsd: primary.uncachedRebuildCostUsd ?? 0,
|
|
583
|
+
incrementalColdPenaltyUsd: primary.incrementalColdPenaltyUsd ?? 0,
|
|
584
|
+
warmPrefixTokens: primary.warmPrefixTokens ?? 0,
|
|
585
|
+
message: primary.message || ''
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
getRosterSnapshot() {
|
|
590
|
+
const agents = {};
|
|
591
|
+
for (const [id, st] of this.roster.entries()) {
|
|
592
|
+
agents[id] = { ...st };
|
|
593
|
+
}
|
|
594
|
+
return agents;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
toJSON(nowMs = Date.now()) {
|
|
598
|
+
const agents = {};
|
|
599
|
+
for (const [id, st] of this.roster.entries()) {
|
|
600
|
+
agents[id] = { ...st };
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
agents,
|
|
604
|
+
badges: this.getBadges(nowMs)
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
|