ctxtop 4.0.0 → 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 +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHECKSUMS.sha256 +59 -42
- package/README.md +351 -330
- package/bin/ah-statusline.mjs +30 -0
- package/bin/ctxtop.mjs +330 -5
- package/config/default_flightcheck.json +19 -0
- package/config/modelCatalog.json +165 -0
- package/hooks/handlers/compact-lifecycle.mjs +323 -8
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +56 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +117 -16
- package/hooks/handlers/pre-model-switch.mjs +823 -24
- package/hooks/handlers/pre-tool-use.mjs +271 -4
- package/hooks/handlers/stop-gate.mjs +297 -11
- package/hooks/handlers/user-prompt-submit.mjs +224 -0
- package/hooks/hooks.json +50 -0
- package/hooks/post_tool_use.mjs +8 -0
- package/hooks/register.js +48 -9
- package/hooks/session_start.mjs +11 -1
- package/hooks/stop.mjs +11 -1
- package/package.json +11 -4
- package/packages/antigravity/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/core/package.json +1 -1
- package/packages/engine-node/package.json +1 -1
- package/packages/mcp/package.json +1 -1
- package/packages/mcp/src/server.mjs +1 -1
- package/packages/pro/package.json +1 -1
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +38 -2
- package/skills/handoff/SKILL.md +8 -0
- package/src/adapters/antigravity/index.mjs +31 -1
- package/src/adapters/claude-code/index.mjs +40 -1
- package/src/cli/horizon_hud.mjs +254 -52
- package/src/config/modelCatalog.json +84 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/constants.mjs +191 -4
- package/src/core/detectors_det01_to_16.mjs +54 -5
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/layer5_hygiene.mjs +118 -0
- package/src/core/parser.mjs +2 -1
- package/src/core/paths.mjs +3 -2
- 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/session_auditor.mjs +658 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/task_quota_router.mjs +1 -1
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
- package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
- package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
- package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
- package/src/core-isomorphic/economics/driftLatency.mjs +114 -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 +191 -191
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +1 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
- package/src/core-isomorphic/ui/modViews.mjs +35 -9
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +95 -3
- package/src/engine-node/db/probe.mjs +234 -2
- package/src/engine-node/index.mjs +3 -0
- package/src/engine-node/sensors/blindspots.mjs +13 -6
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/post_invocation.mjs +196 -4
- package/src/hooks/pre_invocation.mjs +732 -22
- package/src/hooks/session_start.mjs +39 -1
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/horizon_panel.html +1325 -317
|
@@ -12,6 +12,9 @@ import { recordHookDiagnostic } from '../core/hook_diagnostics.mjs';
|
|
|
12
12
|
import { auditWorkspaceAndGlobalMcpConfigs } from '../core/mcp_auditor.mjs';
|
|
13
13
|
import { loadHorizonConfig, resolveDetectorOverride } from '../core/horizon_config.mjs';
|
|
14
14
|
import { loadMicroSkillsRegistry, formatMicroSkillsBatonSnippet } from '../core/micro_skills_store.mjs';
|
|
15
|
+
import { auditAntigravityRulesIntegrity } from '../core/layer5_hygiene.mjs';
|
|
16
|
+
import { snapshotWorkspaceTestHashes } from '../core/shield_manager.mjs';
|
|
17
|
+
import { evaluateGeminiThinkingTimeoutRisk } from '../core-isomorphic/economics/driftLatency.mjs';
|
|
15
18
|
|
|
16
19
|
async function readStdinSafe({ maxTimeoutMs = 1000, settleMs = 50 } = {}) {
|
|
17
20
|
if (process.stdin.isTTY || process.stdin.readableEnded) return {};
|
|
@@ -141,8 +144,43 @@ export async function handleSessionStart(inputData = {}) {
|
|
|
141
144
|
}
|
|
142
145
|
}
|
|
143
146
|
|
|
147
|
+
// Item A2 (#3), Item A5 (#15) & Item A6 (#11): Test-Hash Baseline, Antigravity Rule Validator, & Thinking Timeout Guard
|
|
148
|
+
const rulesAudit = auditAntigravityRulesIntegrity({ workspacePath });
|
|
149
|
+
const thinkingTimeoutAudit = evaluateGeminiThinkingTimeoutRisk({
|
|
150
|
+
modelId: activeModel,
|
|
151
|
+
maxOutputTokens: inputData.maxOutputTokens ?? inputData.max_output_tokens ?? 0,
|
|
152
|
+
thinkingBudget: inputData.thinkingBudget ?? inputData.thinking_budget ?? 0,
|
|
153
|
+
timeoutMs: inputData.timeoutMs ?? inputData.timeout_ms ?? 0
|
|
154
|
+
});
|
|
155
|
+
const testHashSnapshot =
|
|
156
|
+
inputData.snapshotTestHashes !== false && inputData.workspacePath
|
|
157
|
+
? snapshotWorkspaceTestHashes({ cwd: workspacePath, sessionId: conversationId })
|
|
158
|
+
: null;
|
|
159
|
+
|
|
160
|
+
sidecar.sensors.rulesAudit = rulesAudit;
|
|
161
|
+
sidecar.sensors.thinkingTimeoutAudit = thinkingTimeoutAudit;
|
|
162
|
+
if (testHashSnapshot) {
|
|
163
|
+
sidecar.sessionMeta.testHashSnapshotPath = testHashSnapshot.snapshotPath;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const sessionWarnings = [];
|
|
167
|
+
if (microSkillsSnippet) sessionWarnings.push(microSkillsSnippet);
|
|
168
|
+
if (rulesAudit.triggered && rulesAudit.advisory) sessionWarnings.push(rulesAudit.advisory);
|
|
169
|
+
if (thinkingTimeoutAudit.triggered && thinkingTimeoutAudit.advisory) {
|
|
170
|
+
sessionWarnings.push(thinkingTimeoutAudit.advisory);
|
|
171
|
+
}
|
|
172
|
+
|
|
144
173
|
writeSidecarAtomicSync(conversationId, sidecar);
|
|
145
|
-
|
|
174
|
+
const combinedSystemMessage = sessionWarnings.join('\n\n');
|
|
175
|
+
return combinedSystemMessage
|
|
176
|
+
? {
|
|
177
|
+
systemMessage: combinedSystemMessage,
|
|
178
|
+
...(microSkillsSnippet ? { microSkillsBaton: microSkillsSnippet } : {}),
|
|
179
|
+
rulesAudit,
|
|
180
|
+
thinkingTimeoutAudit,
|
|
181
|
+
...(testHashSnapshot ? { testHashSnapshot } : {})
|
|
182
|
+
}
|
|
183
|
+
: {};
|
|
146
184
|
}
|
|
147
185
|
|
|
148
186
|
// Auto-run when executed directly
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/utils/modelSwitchTelemetry.mjs
|
|
3
|
+
* Local-only privacy-sanitized telemetry counters for `PreModelSwitch` ("ask" / "deny" / "allow")
|
|
4
|
+
* vs `PostModelSwitch` events, plus sanitized hook stdin captures (`cache_ttl`, `prompt_cache_warm`).
|
|
5
|
+
*
|
|
6
|
+
* Privacy Invariant:
|
|
7
|
+
* - Zero file paths, zero OS usernames, zero repository directory names, and zero raw session IDs
|
|
8
|
+
* are persisted. Session identifiers are one-way SHA-256 hashed (`sess_<12hex>`).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { fs, path, os, crypto, readJsonSafe, writeJsonAtomic } from './nodeIo.mjs';
|
|
12
|
+
|
|
13
|
+
export const MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION = 1;
|
|
14
|
+
const MAX_RECENT_CAPTURES = 50;
|
|
15
|
+
const MAX_PENDING_ASKS = 64;
|
|
16
|
+
|
|
17
|
+
const SAFE_TOKEN_RX = /^[a-z0-9._:/-]{1,64}$/i;
|
|
18
|
+
const PATH_LIKE_RX = /([\\/]{1,2}[a-z0-9_.-]+|[a-z]:[\\/]|users[\\/]|home[\\/])/i;
|
|
19
|
+
|
|
20
|
+
function sanitizeShortToken(value, maxLen = 64) {
|
|
21
|
+
if (typeof value !== 'string') return null;
|
|
22
|
+
const trimmed = value.trim();
|
|
23
|
+
if (!trimmed || trimmed.length > maxLen) return null;
|
|
24
|
+
if (PATH_LIKE_RX.test(trimmed)) return null;
|
|
25
|
+
if (!SAFE_TOKEN_RX.test(trimmed)) return null;
|
|
26
|
+
return trimmed;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sanitizeFiniteNumber(value) {
|
|
30
|
+
const num = Number(value);
|
|
31
|
+
return Number.isFinite(num) ? num : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Hash an arbitrary session identifier into a non-reversible 12-hex tag (`sess_<12hex>`).
|
|
36
|
+
* @param {string|null|undefined} sessionId
|
|
37
|
+
* @returns {string|null}
|
|
38
|
+
*/
|
|
39
|
+
export function hashSessionIdentifier(sessionId) {
|
|
40
|
+
if (typeof sessionId !== 'string' || !sessionId.trim()) return null;
|
|
41
|
+
const digest = crypto.createHash('sha256').update(sessionId.trim()).digest('hex').slice(0, 12);
|
|
42
|
+
return `sess_${digest}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve the local telemetry JSON path under `~/.attention-horizon/cache/`.
|
|
47
|
+
* @param {object} [options={}]
|
|
48
|
+
* @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
export function resolveModelSwitchTelemetryPath(options = {}) {
|
|
51
|
+
if (typeof options.telemetryPath === 'string' && options.telemetryPath.trim()) {
|
|
52
|
+
return options.telemetryPath.trim();
|
|
53
|
+
}
|
|
54
|
+
const envPath = globalThis.process?.env?.AH_MODEL_SWITCH_TELEMETRY_PATH;
|
|
55
|
+
if (typeof envPath === 'string' && envPath.trim()) {
|
|
56
|
+
return envPath.trim();
|
|
57
|
+
}
|
|
58
|
+
const homeDir = options.homeDir || os.homedir();
|
|
59
|
+
return path.join(homeDir, '.attention-horizon', 'cache', 'model_switch_telemetry.json');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Produce a strictly allowlisted, path-free, username-free summary of a
|
|
64
|
+
* `PreModelSwitch` or `PostModelSwitch` stdin payload.
|
|
65
|
+
*
|
|
66
|
+
* @param {object} [rawEvent={}]
|
|
67
|
+
* @param {'PreModelSwitch'|'PostModelSwitch'} [hookEventName='PreModelSwitch']
|
|
68
|
+
* @returns {object}
|
|
69
|
+
*/
|
|
70
|
+
export function sanitizeModelSwitchStdin(rawEvent = {}, hookEventName = 'PreModelSwitch') {
|
|
71
|
+
const ev = rawEvent && typeof rawEvent === 'object' ? rawEvent : {};
|
|
72
|
+
const sessionHash = hashSessionIdentifier(ev.session_id || ev.sessionId || null);
|
|
73
|
+
|
|
74
|
+
const rawWarm =
|
|
75
|
+
ev.prompt_cache_warm !== undefined
|
|
76
|
+
? ev.prompt_cache_warm
|
|
77
|
+
: ev.cache_warm !== undefined
|
|
78
|
+
? ev.cache_warm
|
|
79
|
+
: ev.promptCacheWarm;
|
|
80
|
+
const promptCacheWarm =
|
|
81
|
+
rawWarm === undefined || rawWarm === null ? null : Boolean(rawWarm);
|
|
82
|
+
|
|
83
|
+
const rawTtl = ev.cache_ttl ?? ev.cacheTtl ?? ev.cache_ttl_tier ?? ev.cacheTtlTier ?? null;
|
|
84
|
+
const cacheTtl = sanitizeShortToken(rawTtl ? String(rawTtl) : null, 16);
|
|
85
|
+
|
|
86
|
+
const rawSource = ev.source ?? ev.trigger ?? null;
|
|
87
|
+
const source = sanitizeShortToken(rawSource ? String(rawSource) : null, 32) || 'unknown';
|
|
88
|
+
|
|
89
|
+
const fromModel = sanitizeShortToken(
|
|
90
|
+
ev.from_model ?? ev.fromModel ?? ev.current_model ?? ev.currentModel ?? null,
|
|
91
|
+
64
|
|
92
|
+
);
|
|
93
|
+
const toModel = sanitizeShortToken(
|
|
94
|
+
ev.to_model ?? ev.toModel ?? ev.target_model ?? ev.targetModel ?? ev.requested_model ?? null,
|
|
95
|
+
64
|
|
96
|
+
);
|
|
97
|
+
const requestedModel = sanitizeShortToken(ev.requested_model ?? ev.requestedModel ?? null, 64);
|
|
98
|
+
|
|
99
|
+
const observedKeys = Object.keys(ev)
|
|
100
|
+
.filter((k) => /^[a-z0-9_]{1,48}$/i.test(k))
|
|
101
|
+
.sort();
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
hookEventName: hookEventName === 'PostModelSwitch' ? 'PostModelSwitch' : 'PreModelSwitch',
|
|
105
|
+
recordedAtIso: new Date().toISOString(),
|
|
106
|
+
sessionHash,
|
|
107
|
+
source,
|
|
108
|
+
fromModel,
|
|
109
|
+
toModel,
|
|
110
|
+
requestedModel,
|
|
111
|
+
cacheTtl,
|
|
112
|
+
promptCacheWarm,
|
|
113
|
+
contextTokens: sanitizeFiniteNumber(ev.context_tokens ?? ev.contextTokens),
|
|
114
|
+
cachedTokens: sanitizeFiniteNumber(
|
|
115
|
+
ev.cached_tokens ?? ev.cachedTokens ?? ev.cache_read_input_tokens
|
|
116
|
+
),
|
|
117
|
+
estimatedCacheWriteUsd: sanitizeFiniteNumber(
|
|
118
|
+
ev.estimated_cache_write_usd ?? ev.estimatedCacheWriteUsd
|
|
119
|
+
),
|
|
120
|
+
hasPricingPayload: Boolean(ev.pricing && typeof ev.pricing === 'object'),
|
|
121
|
+
observedKeys
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function createEmptyTelemetryState() {
|
|
126
|
+
return {
|
|
127
|
+
schemaVersion: MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION,
|
|
128
|
+
updatedAtIso: null,
|
|
129
|
+
counts: {
|
|
130
|
+
preModelSwitchTotal: 0,
|
|
131
|
+
preModelSwitchAsk: 0,
|
|
132
|
+
preModelSwitchDeny: 0,
|
|
133
|
+
preModelSwitchAllow: 0,
|
|
134
|
+
postModelSwitchTotal: 0,
|
|
135
|
+
postModelSwitchFromAsk: 0
|
|
136
|
+
},
|
|
137
|
+
metrics: {
|
|
138
|
+
askAcceptanceRate: null,
|
|
139
|
+
rawPostToAskRatio: null,
|
|
140
|
+
pendingOrDeclinedAsks: 0,
|
|
141
|
+
sourceBreakdown: {}
|
|
142
|
+
},
|
|
143
|
+
pendingAsks: [],
|
|
144
|
+
recentSanitizedCaptures: []
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function normalizeTelemetryState(raw) {
|
|
149
|
+
const base = createEmptyTelemetryState();
|
|
150
|
+
if (!raw || typeof raw !== 'object') return base;
|
|
151
|
+
const counts = {
|
|
152
|
+
preModelSwitchTotal: Math.max(0, Number(raw.counts?.preModelSwitchTotal || 0)),
|
|
153
|
+
preModelSwitchAsk: Math.max(0, Number(raw.counts?.preModelSwitchAsk || 0)),
|
|
154
|
+
preModelSwitchDeny: Math.max(0, Number(raw.counts?.preModelSwitchDeny || 0)),
|
|
155
|
+
preModelSwitchAllow: Math.max(0, Number(raw.counts?.preModelSwitchAllow || 0)),
|
|
156
|
+
postModelSwitchTotal: Math.max(0, Number(raw.counts?.postModelSwitchTotal || 0)),
|
|
157
|
+
postModelSwitchFromAsk: Math.max(0, Number(raw.counts?.postModelSwitchFromAsk || 0))
|
|
158
|
+
};
|
|
159
|
+
const sourceBreakdown =
|
|
160
|
+
raw.metrics?.sourceBreakdown && typeof raw.metrics.sourceBreakdown === 'object'
|
|
161
|
+
? { ...raw.metrics.sourceBreakdown }
|
|
162
|
+
: {};
|
|
163
|
+
const pendingAsks = Array.isArray(raw.pendingAsks)
|
|
164
|
+
? raw.pendingAsks.slice(-MAX_PENDING_ASKS)
|
|
165
|
+
: [];
|
|
166
|
+
const recentSanitizedCaptures = Array.isArray(raw.recentSanitizedCaptures)
|
|
167
|
+
? raw.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES)
|
|
168
|
+
: [];
|
|
169
|
+
return recomputeTelemetryMetrics({
|
|
170
|
+
schemaVersion: MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION,
|
|
171
|
+
updatedAtIso: typeof raw.updatedAtIso === 'string' ? raw.updatedAtIso : null,
|
|
172
|
+
counts,
|
|
173
|
+
metrics: {
|
|
174
|
+
askAcceptanceRate: null,
|
|
175
|
+
rawPostToAskRatio: null,
|
|
176
|
+
pendingOrDeclinedAsks: 0,
|
|
177
|
+
sourceBreakdown
|
|
178
|
+
},
|
|
179
|
+
pendingAsks,
|
|
180
|
+
recentSanitizedCaptures
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function recomputeTelemetryMetrics(state) {
|
|
185
|
+
const { counts } = state;
|
|
186
|
+
const askCount = counts.preModelSwitchAsk;
|
|
187
|
+
const matchedPost = Math.min(askCount, counts.postModelSwitchFromAsk);
|
|
188
|
+
counts.postModelSwitchFromAsk = matchedPost;
|
|
189
|
+
|
|
190
|
+
state.metrics.askAcceptanceRate =
|
|
191
|
+
askCount > 0 ? Number((matchedPost / askCount).toFixed(4)) : null;
|
|
192
|
+
state.metrics.rawPostToAskRatio =
|
|
193
|
+
askCount > 0 ? Number((counts.postModelSwitchTotal / askCount).toFixed(4)) : null;
|
|
194
|
+
state.metrics.pendingOrDeclinedAsks = Math.max(0, askCount - matchedPost);
|
|
195
|
+
return state;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function writeTelemetryStateAtomic(targetPath, state) {
|
|
199
|
+
const dir = path.dirname(targetPath);
|
|
200
|
+
if (dir && dir !== '.' && !fs.existsSync(dir)) {
|
|
201
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
202
|
+
}
|
|
203
|
+
writeJsonAtomic(targetPath, state);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Read persisted local-only `PreModelSwitch` vs `PostModelSwitch` telemetry.
|
|
208
|
+
* @param {object} [options={}]
|
|
209
|
+
*/
|
|
210
|
+
export function readModelSwitchTelemetry(options = {}) {
|
|
211
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
212
|
+
const raw = readJsonSafe(targetPath, null);
|
|
213
|
+
return {
|
|
214
|
+
telemetryPath: targetPath,
|
|
215
|
+
exists: Boolean(raw),
|
|
216
|
+
state: normalizeTelemetryState(raw)
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Record a sanitized `PreModelSwitch` decision and stdin capture locally.
|
|
222
|
+
* @param {object} [rawEvent={}]
|
|
223
|
+
* @param {string} [decision='allow']
|
|
224
|
+
* @param {object} [options={}]
|
|
225
|
+
*/
|
|
226
|
+
export function recordPreModelSwitchEvent(rawEvent = {}, decision = 'allow', options = {}) {
|
|
227
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
228
|
+
const state = normalizeTelemetryState(readJsonSafe(targetPath, null));
|
|
229
|
+
const capture = sanitizeModelSwitchStdin(rawEvent, 'PreModelSwitch');
|
|
230
|
+
const normDecision = String(decision || 'allow').toLowerCase();
|
|
231
|
+
|
|
232
|
+
state.counts.preModelSwitchTotal += 1;
|
|
233
|
+
if (normDecision === 'ask') {
|
|
234
|
+
state.counts.preModelSwitchAsk += 1;
|
|
235
|
+
state.pendingAsks.push({
|
|
236
|
+
sessionHash: capture.sessionHash,
|
|
237
|
+
toModel: capture.toModel,
|
|
238
|
+
source: capture.source,
|
|
239
|
+
recordedAtIso: capture.recordedAtIso
|
|
240
|
+
});
|
|
241
|
+
if (state.pendingAsks.length > MAX_PENDING_ASKS) {
|
|
242
|
+
state.pendingAsks = state.pendingAsks.slice(-MAX_PENDING_ASKS);
|
|
243
|
+
}
|
|
244
|
+
} else if (normDecision === 'deny') {
|
|
245
|
+
state.counts.preModelSwitchDeny += 1;
|
|
246
|
+
} else {
|
|
247
|
+
state.counts.preModelSwitchAllow += 1;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const sourceKey = capture.source || 'unknown';
|
|
251
|
+
state.metrics.sourceBreakdown[sourceKey] =
|
|
252
|
+
(Number(state.metrics.sourceBreakdown[sourceKey]) || 0) + 1;
|
|
253
|
+
|
|
254
|
+
state.recentSanitizedCaptures.push({
|
|
255
|
+
...capture,
|
|
256
|
+
decision: normDecision
|
|
257
|
+
});
|
|
258
|
+
if (state.recentSanitizedCaptures.length > MAX_RECENT_CAPTURES) {
|
|
259
|
+
state.recentSanitizedCaptures = state.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
state.updatedAtIso = capture.recordedAtIso;
|
|
263
|
+
recomputeTelemetryMetrics(state);
|
|
264
|
+
writeTelemetryStateAtomic(targetPath, state);
|
|
265
|
+
return { telemetryPath: targetPath, state, capture };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Record a sanitized `PostModelSwitch` completion event and reconcile against pending asks.
|
|
270
|
+
* @param {object} [rawEvent={}]
|
|
271
|
+
* @param {object} [options={}]
|
|
272
|
+
*/
|
|
273
|
+
export function recordPostModelSwitchEvent(rawEvent = {}, options = {}) {
|
|
274
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
275
|
+
const state = normalizeTelemetryState(readJsonSafe(targetPath, null));
|
|
276
|
+
const capture = sanitizeModelSwitchStdin(rawEvent, 'PostModelSwitch');
|
|
277
|
+
|
|
278
|
+
state.counts.postModelSwitchTotal += 1;
|
|
279
|
+
|
|
280
|
+
// Match the earliest pending `"ask"` for the same hashed session + target model
|
|
281
|
+
const matchIdx = state.pendingAsks.findIndex((pending) => {
|
|
282
|
+
const sameSession =
|
|
283
|
+
pending.sessionHash === null ||
|
|
284
|
+
capture.sessionHash === null ||
|
|
285
|
+
pending.sessionHash === capture.sessionHash;
|
|
286
|
+
const sameTarget =
|
|
287
|
+
pending.toModel === null || capture.toModel === null || pending.toModel === capture.toModel;
|
|
288
|
+
return sameSession && sameTarget;
|
|
289
|
+
});
|
|
290
|
+
const matchedPendingAsk = matchIdx >= 0;
|
|
291
|
+
if (matchedPendingAsk) {
|
|
292
|
+
state.pendingAsks.splice(matchIdx, 1);
|
|
293
|
+
state.counts.postModelSwitchFromAsk += 1;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
state.recentSanitizedCaptures.push({
|
|
297
|
+
...capture,
|
|
298
|
+
matchedPendingAsk
|
|
299
|
+
});
|
|
300
|
+
if (state.recentSanitizedCaptures.length > MAX_RECENT_CAPTURES) {
|
|
301
|
+
state.recentSanitizedCaptures = state.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
state.updatedAtIso = capture.recordedAtIso;
|
|
305
|
+
recomputeTelemetryMetrics(state);
|
|
306
|
+
writeTelemetryStateAtomic(targetPath, state);
|
|
307
|
+
return { telemetryPath: targetPath, state, capture, matchedPendingAsk };
|
|
308
|
+
}
|