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,445 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/engine-node/ipc/server.mjs
|
|
3
|
+
* Highbeam Micro-IPC Server.
|
|
4
|
+
*
|
|
5
|
+
* Implements high-throughput, low-latency (<0.8ms SLA) local JSON-RPC 2.0 server
|
|
6
|
+
* over Win32 Named Pipes and POSIX Unix Domain Sockets with non-spinning tool-boundary suspension.
|
|
7
|
+
* Strictly 0 npm dependencies (uses only standard node:* built-ins).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import net from 'node:net';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import {
|
|
14
|
+
resolveIpcPath,
|
|
15
|
+
formatJsonRpcResponse,
|
|
16
|
+
formatJsonRpcError,
|
|
17
|
+
JsonRpcStreamParser,
|
|
18
|
+
JSON_RPC_ERRORS,
|
|
19
|
+
IPC_LIMITS
|
|
20
|
+
} from './protocol.mjs';
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
CONTROL_STATES,
|
|
24
|
+
createInitialControlState,
|
|
25
|
+
transitionControlState,
|
|
26
|
+
evaluateToolBoundaryLatch
|
|
27
|
+
} from '../../core-isomorphic/control/controlStateMachine.mjs';
|
|
28
|
+
|
|
29
|
+
import { evaluateCoachLatch } from '../../core-isomorphic/control/coachLatches.mjs';
|
|
30
|
+
|
|
31
|
+
export class MicroIpcServer {
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} [options]
|
|
34
|
+
* @param {string} [options.ipcPath]
|
|
35
|
+
* @param {Function} [options.logger]
|
|
36
|
+
*/
|
|
37
|
+
constructor(options = {}) {
|
|
38
|
+
this.ipcPath = resolveIpcPath(options);
|
|
39
|
+
this.logger = typeof options.logger === 'function' ? options.logger : null;
|
|
40
|
+
this.server = null;
|
|
41
|
+
this.methods = new Map();
|
|
42
|
+
this.activeSockets = new Set();
|
|
43
|
+
|
|
44
|
+
// In-memory control state cache per session: Map<sessionId, ControlState>
|
|
45
|
+
this.controlStates = new Map();
|
|
46
|
+
|
|
47
|
+
// Non-spinning suspension map per session: Map<sessionId, Array<{ id, resolve, socket, timer }>>
|
|
48
|
+
this.suspensions = new Map();
|
|
49
|
+
|
|
50
|
+
this._registerDefaultMethods();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Registers default JSON-RPC 2.0 methods.
|
|
55
|
+
* @private
|
|
56
|
+
*/
|
|
57
|
+
_registerDefaultMethods() {
|
|
58
|
+
// Ping
|
|
59
|
+
this.registerMethod('daemon.ping', async () => ({
|
|
60
|
+
pong: true,
|
|
61
|
+
timestamp: Date.now(),
|
|
62
|
+
platform: process.platform,
|
|
63
|
+
pid: process.pid
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
// Control: get state
|
|
67
|
+
this.registerMethod('control.getState', async (params) => {
|
|
68
|
+
const sessionId = params?.sessionId || 'default';
|
|
69
|
+
const state = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
|
|
70
|
+
return state;
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Control: transition state
|
|
74
|
+
this.registerMethod('control.transition', async (params) => {
|
|
75
|
+
const sessionId = params?.sessionId || 'default';
|
|
76
|
+
const action = params?.action || 'run';
|
|
77
|
+
const reason = params?.reason || '';
|
|
78
|
+
const current = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
|
|
79
|
+
const next = transitionControlState(current, action, reason, params?.options || {});
|
|
80
|
+
this.controlStates.set(sessionId, next);
|
|
81
|
+
|
|
82
|
+
// Handle unpausing or stepping of suspended requests
|
|
83
|
+
if (action === 'resume' || action === 'run') {
|
|
84
|
+
this.resumeSuspended(sessionId, 'all', 'allow', reason || 'Execution resumed');
|
|
85
|
+
} else if (action === 'step') {
|
|
86
|
+
this.resumeSuspended(sessionId, 'one', 'allow', reason || 'Step executed');
|
|
87
|
+
} else if (action === 'abort') {
|
|
88
|
+
this.resumeSuspended(sessionId, 'all', 'deny', reason || 'Session aborted by user');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return next;
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// Control: check latch
|
|
95
|
+
this.registerMethod('control.checkLatch', async (params) => {
|
|
96
|
+
const sessionId = params?.sessionId || 'default';
|
|
97
|
+
const state = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
|
|
98
|
+
const flightMode = params?.flightMode || 'COACH';
|
|
99
|
+
const detectorVerdict = params?.detectorVerdict || null;
|
|
100
|
+
return evaluateCoachLatch({
|
|
101
|
+
controlState: state,
|
|
102
|
+
flightMode,
|
|
103
|
+
detectorVerdict
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// Hook: PreToolUse with atomic non-spinning suspension
|
|
108
|
+
this.registerMethod('hook.preToolUse', async (params, socket, id) => {
|
|
109
|
+
const sessionId = params?.sessionId || params?.session_id || 'default';
|
|
110
|
+
const controlState = this.controlStates.get(sessionId) || createInitialControlState(sessionId);
|
|
111
|
+
const flightMode = params?.flightMode || 'COACH';
|
|
112
|
+
|
|
113
|
+
// 1. Evaluate user control state
|
|
114
|
+
const latch = evaluateToolBoundaryLatch(controlState);
|
|
115
|
+
|
|
116
|
+
if (latch.decision === 'deny') {
|
|
117
|
+
return {
|
|
118
|
+
decision: 'deny',
|
|
119
|
+
reason: latch.reason || 'Session aborted by user',
|
|
120
|
+
hookSpecificOutput: {
|
|
121
|
+
permissionDecision: 'deny',
|
|
122
|
+
permissionDecisionReason: latch.reason || 'Session aborted by user'
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (latch.decision === 'suspend') {
|
|
128
|
+
// Suspend non-spinning: hold request in suspension map
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
const timeoutTimer = setTimeout(() => {
|
|
131
|
+
this._removeSuspension(sessionId, id);
|
|
132
|
+
resolve({
|
|
133
|
+
decision: 'deny',
|
|
134
|
+
reason: 'timeout: suspended execution exceeded safety ceiling',
|
|
135
|
+
hookSpecificOutput: {
|
|
136
|
+
permissionDecision: 'deny',
|
|
137
|
+
permissionDecisionReason: 'timeout: suspended execution exceeded safety ceiling'
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}, 600000); // 10 minutes safety timeout
|
|
141
|
+
|
|
142
|
+
if (!this.suspensions.has(sessionId)) {
|
|
143
|
+
this.suspensions.set(sessionId, []);
|
|
144
|
+
}
|
|
145
|
+
this.suspensions.get(sessionId).push({
|
|
146
|
+
id,
|
|
147
|
+
resolve,
|
|
148
|
+
socket,
|
|
149
|
+
timer: timeoutTimer
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (latch.decision === 'allow' && latch.consumeStep) {
|
|
155
|
+
// Auto-consume step: transition back to PAUSED
|
|
156
|
+
const next = transitionControlState(controlState, 'consume_step');
|
|
157
|
+
this.controlStates.set(sessionId, next);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 2. Evaluate COACH mode composite latch
|
|
161
|
+
const coachVerdict = evaluateCoachLatch({
|
|
162
|
+
controlState,
|
|
163
|
+
flightMode,
|
|
164
|
+
detectorVerdict: params?.detectorVerdict || null
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
decision: coachVerdict.decision || 'allow',
|
|
169
|
+
flightMode: coachVerdict.flightMode || flightMode,
|
|
170
|
+
advisory: coachVerdict.advisory || false,
|
|
171
|
+
systemMessage: coachVerdict.systemMessage || null,
|
|
172
|
+
hookSpecificOutput: {
|
|
173
|
+
permissionDecision: coachVerdict.decision === 'block' || coachVerdict.decision === 'deny' ? 'deny' : 'allow',
|
|
174
|
+
permissionDecisionReason: coachVerdict.reason || coachVerdict.systemMessage || null
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// Hook: PostToolUse
|
|
180
|
+
this.registerMethod('hook.postToolUse', async (params) => {
|
|
181
|
+
return {
|
|
182
|
+
success: true,
|
|
183
|
+
sanitized: false,
|
|
184
|
+
timestamp: Date.now()
|
|
185
|
+
};
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Registers a custom JSON-RPC method handler.
|
|
191
|
+
*
|
|
192
|
+
* @param {string} name
|
|
193
|
+
* @param {Function} handler
|
|
194
|
+
*/
|
|
195
|
+
registerMethod(name, handler) {
|
|
196
|
+
if (typeof handler === 'function') {
|
|
197
|
+
this.methods.set(name, handler);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Resumes suspended requests for a session.
|
|
203
|
+
*
|
|
204
|
+
* @param {string} sessionId
|
|
205
|
+
* @param {'all' | 'one'} mode
|
|
206
|
+
* @param {'allow' | 'deny'} decision
|
|
207
|
+
* @param {string} reason
|
|
208
|
+
*/
|
|
209
|
+
resumeSuspended(sessionId, mode = 'all', decision = 'allow', reason = '') {
|
|
210
|
+
const list = this.suspensions.get(sessionId);
|
|
211
|
+
if (!list || list.length === 0) return;
|
|
212
|
+
|
|
213
|
+
if (mode === 'one') {
|
|
214
|
+
const item = list.shift();
|
|
215
|
+
if (item) {
|
|
216
|
+
clearTimeout(item.timer);
|
|
217
|
+
item.resolve({
|
|
218
|
+
decision,
|
|
219
|
+
consumeStep: true,
|
|
220
|
+
reason,
|
|
221
|
+
hookSpecificOutput: {
|
|
222
|
+
permissionDecision: decision,
|
|
223
|
+
permissionDecisionReason: reason
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
} else {
|
|
228
|
+
while (list.length > 0) {
|
|
229
|
+
const item = list.shift();
|
|
230
|
+
clearTimeout(item.timer);
|
|
231
|
+
item.resolve({
|
|
232
|
+
decision,
|
|
233
|
+
reason,
|
|
234
|
+
hookSpecificOutput: {
|
|
235
|
+
permissionDecision: decision,
|
|
236
|
+
permissionDecisionReason: reason
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Helper to remove a single suspension entry.
|
|
245
|
+
* @private
|
|
246
|
+
*/
|
|
247
|
+
_removeSuspension(sessionId, id) {
|
|
248
|
+
const list = this.suspensions.get(sessionId);
|
|
249
|
+
if (!list) return;
|
|
250
|
+
const idx = list.findIndex((item) => item.id === id);
|
|
251
|
+
if (idx !== -1) {
|
|
252
|
+
clearTimeout(list[idx].timer);
|
|
253
|
+
list.splice(idx, 1);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Cleans up any pending suspensions and cancels 600s safety timers
|
|
259
|
+
* associated with a disconnected or errored socket.
|
|
260
|
+
* @param {import('node:net').Socket} socket
|
|
261
|
+
* @private
|
|
262
|
+
*/
|
|
263
|
+
_cleanupSocketSuspensions(socket) {
|
|
264
|
+
for (const [sessionId, list] of this.suspensions.entries()) {
|
|
265
|
+
const remaining = [];
|
|
266
|
+
for (const item of list) {
|
|
267
|
+
if (item.socket === socket) {
|
|
268
|
+
clearTimeout(item.timer);
|
|
269
|
+
try {
|
|
270
|
+
item.resolve({
|
|
271
|
+
decision: 'deny',
|
|
272
|
+
reason: 'Client socket disconnected'
|
|
273
|
+
});
|
|
274
|
+
} catch (_err) {
|
|
275
|
+
void _err;
|
|
276
|
+
}
|
|
277
|
+
} else {
|
|
278
|
+
remaining.push(item);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (remaining.length === 0) {
|
|
282
|
+
this.suspensions.delete(sessionId);
|
|
283
|
+
} else {
|
|
284
|
+
this.suspensions.set(sessionId, remaining);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Starts listening on the configured pipe or socket path.
|
|
291
|
+
*
|
|
292
|
+
* @returns {Promise<MicroIpcServer>}
|
|
293
|
+
*/
|
|
294
|
+
async listen() {
|
|
295
|
+
return new Promise((resolve, reject) => {
|
|
296
|
+
// POSIX socket preparation
|
|
297
|
+
if (process.platform !== 'win32') {
|
|
298
|
+
try {
|
|
299
|
+
const dir = path.dirname(this.ipcPath);
|
|
300
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
301
|
+
|
|
302
|
+
if (fs.existsSync(this.ipcPath)) {
|
|
303
|
+
// Clean stale socket if not active
|
|
304
|
+
try {
|
|
305
|
+
fs.unlinkSync(this.ipcPath);
|
|
306
|
+
} catch (_err) {
|
|
307
|
+
void _err;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} catch (prepErr) {
|
|
311
|
+
return reject(prepErr);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
this.server = net.createServer((socket) => {
|
|
316
|
+
this.activeSockets.add(socket);
|
|
317
|
+
|
|
318
|
+
const parser = new JsonRpcStreamParser(
|
|
319
|
+
async (msg) => {
|
|
320
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
|
|
321
|
+
if (!socket.destroyed) {
|
|
322
|
+
socket.write(formatJsonRpcError(null, JSON_RPC_ERRORS.INVALID_REQUEST, 'Invalid Request') + '\n');
|
|
323
|
+
}
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const id = msg.id !== undefined ? msg.id : null;
|
|
328
|
+
const method = msg.method;
|
|
329
|
+
|
|
330
|
+
if (!method || typeof method !== 'string') {
|
|
331
|
+
if (!socket.destroyed) {
|
|
332
|
+
socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.INVALID_REQUEST, 'Missing or invalid method') + '\n');
|
|
333
|
+
}
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const handler = this.methods.get(method);
|
|
338
|
+
if (!handler) {
|
|
339
|
+
if (!socket.destroyed) {
|
|
340
|
+
socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.METHOD_NOT_FOUND, `Method not found: ${method}`) + '\n');
|
|
341
|
+
}
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
try {
|
|
346
|
+
const result = await handler(msg.params || {}, socket, id);
|
|
347
|
+
if (!socket.destroyed && id !== null) {
|
|
348
|
+
socket.write(formatJsonRpcResponse(id, result));
|
|
349
|
+
}
|
|
350
|
+
} catch (execErr) {
|
|
351
|
+
if (!socket.destroyed && id !== null) {
|
|
352
|
+
socket.write(formatJsonRpcError(id, JSON_RPC_ERRORS.INTERNAL_ERROR, execErr.message) + '\n');
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
(parseErr) => {
|
|
357
|
+
// Malformed JSON: return -32700 Parse error without crashing (satisfies test 29.B2)
|
|
358
|
+
if (!socket.destroyed) {
|
|
359
|
+
socket.write(formatJsonRpcError(null, JSON_RPC_ERRORS.PARSE_ERROR, 'Parse error: Invalid JSON'));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
socket.on('data', (chunk) => parser.feed(chunk));
|
|
365
|
+
|
|
366
|
+
socket.on('error', (err) => {
|
|
367
|
+
this.activeSockets.delete(socket);
|
|
368
|
+
this._cleanupSocketSuspensions(socket);
|
|
369
|
+
// Client socket errors or disconnects mid-transmission handled cleanly without server crash
|
|
370
|
+
try {
|
|
371
|
+
socket.destroy();
|
|
372
|
+
} catch (_err) {
|
|
373
|
+
void _err;
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
socket.on('close', () => {
|
|
378
|
+
this.activeSockets.delete(socket);
|
|
379
|
+
this._cleanupSocketSuspensions(socket);
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
this.server.on('error', (err) => {
|
|
384
|
+
reject(err);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
this.server.listen(this.ipcPath, () => {
|
|
388
|
+
if (process.platform !== 'win32') {
|
|
389
|
+
try {
|
|
390
|
+
fs.chmodSync(this.ipcPath, 0o600);
|
|
391
|
+
} catch (_err) {
|
|
392
|
+
void _err;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
resolve(this);
|
|
396
|
+
});
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Closes the server and releases all socket resources.
|
|
402
|
+
*
|
|
403
|
+
* @returns {Promise<void>}
|
|
404
|
+
*/
|
|
405
|
+
async close() {
|
|
406
|
+
// Release any pending suspensions with an abort reason
|
|
407
|
+
for (const [sessionId, list] of this.suspensions.entries()) {
|
|
408
|
+
for (const item of list) {
|
|
409
|
+
clearTimeout(item.timer);
|
|
410
|
+
item.resolve({
|
|
411
|
+
decision: 'deny',
|
|
412
|
+
reason: 'IPC server shut down'
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
this.suspensions.clear();
|
|
417
|
+
|
|
418
|
+
// Close all connected sockets
|
|
419
|
+
for (const socket of this.activeSockets) {
|
|
420
|
+
try {
|
|
421
|
+
socket.destroy();
|
|
422
|
+
} catch (_err) {
|
|
423
|
+
void _err;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
this.activeSockets.clear();
|
|
427
|
+
|
|
428
|
+
return new Promise((resolve) => {
|
|
429
|
+
if (!this.server) return resolve();
|
|
430
|
+
this.server.close(() => {
|
|
431
|
+
if (process.platform !== 'win32') {
|
|
432
|
+
try {
|
|
433
|
+
if (fs.existsSync(this.ipcPath)) {
|
|
434
|
+
fs.unlinkSync(this.ipcPath);
|
|
435
|
+
}
|
|
436
|
+
} catch (_err) {
|
|
437
|
+
void _err;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
this.server = null;
|
|
441
|
+
resolve();
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/engine-node/offloader/tool_offloader.mjs
|
|
3
|
+
* Lossless PostToolUse >4k Artifact Offloader with FTS5 Indexing.
|
|
4
|
+
*
|
|
5
|
+
* Replaces oversized non-read tool dumps (>4k tokens) with error-preserving summaries
|
|
6
|
+
* while STRICTLY preserving 100% of workspace read/edit operations (never offloaded!).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { isNodeSqliteAvailable, getDatabaseSyncClass } from '../db/probe.mjs';
|
|
13
|
+
|
|
14
|
+
export const CRITICAL_ERROR_REGEX = /(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
|
|
15
|
+
|
|
16
|
+
const WORKSPACE_READ_TOOLS = /^(Read|read_file|view_file|View|Edit|edit_file|Write|write_file|write_to_file|replace_file_content|MultiEdit|NotebookEdit)$/i;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Returns true when tool is a workspace read or edit tool that must NEVER be offloaded.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} toolName
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
export function isWorkspaceReadTool(toolName = '') {
|
|
25
|
+
let cleaned = String(toolName || '').trim();
|
|
26
|
+
if (!cleaned) return false;
|
|
27
|
+
cleaned = cleaned.replace(/^(?:default_api:|mcp__[a-zA-Z0-9_-]+__)/i, '');
|
|
28
|
+
return WORKSPACE_READ_TOOLS.test(cleaned);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Strips ANSI escape sequences from text.
|
|
33
|
+
*
|
|
34
|
+
* @param {string} text
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function stripAnsi(text = '') {
|
|
38
|
+
return String(text || '').replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Estimates token count from string length (roughly 4 chars per token).
|
|
43
|
+
*
|
|
44
|
+
* @param {string} text
|
|
45
|
+
* @returns {number}
|
|
46
|
+
*/
|
|
47
|
+
export function estimateTokens(text = '') {
|
|
48
|
+
const len = String(text || '').length;
|
|
49
|
+
return Math.ceil(len / 4);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Indexes an offloaded artifact into SQLite FTS5 table if available,
|
|
54
|
+
* or appends to a JSONL fallback transcript.
|
|
55
|
+
*
|
|
56
|
+
* @param {object} record
|
|
57
|
+
* @param {string} record.id
|
|
58
|
+
* @param {string} record.tool
|
|
59
|
+
* @param {string} record.content
|
|
60
|
+
* @param {string} record.filePath
|
|
61
|
+
* @param {object} [options={}]
|
|
62
|
+
*/
|
|
63
|
+
export function indexArtifactRecord(record, options = {}) {
|
|
64
|
+
const ctxtopDir = options.ctxtopDir || path.resolve(process.cwd(), '.ctxtop');
|
|
65
|
+
const cacheDir = path.join(ctxtopDir, 'cache');
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
69
|
+
} catch (_err) {
|
|
70
|
+
// Directory creation failure handled
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// 1. Try SQLite FTS5 index if node:sqlite available
|
|
74
|
+
if (!options.forceJsonl && isNodeSqliteAvailable()) {
|
|
75
|
+
try {
|
|
76
|
+
const DatabaseSync = getDatabaseSyncClass();
|
|
77
|
+
const ftsDbPath = path.join(cacheDir, 'artifacts_fts5.db');
|
|
78
|
+
const db = new DatabaseSync(ftsDbPath);
|
|
79
|
+
try {
|
|
80
|
+
db.exec(`
|
|
81
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS artifacts USING fts5(id, tool, content, filePath);
|
|
82
|
+
`);
|
|
83
|
+
const stmt = db.prepare('INSERT INTO artifacts(id, tool, content, filePath) VALUES (?, ?, ?, ?)');
|
|
84
|
+
stmt.run(record.id, record.tool, record.content, record.filePath);
|
|
85
|
+
db.close();
|
|
86
|
+
return;
|
|
87
|
+
} catch (_err) {
|
|
88
|
+
try { db.close(); } catch (_closeErr) { /* ignore */ }
|
|
89
|
+
}
|
|
90
|
+
} catch (_err) {
|
|
91
|
+
// Fall through to JSONL fallback
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 2. Fallback to JSONL append
|
|
96
|
+
try {
|
|
97
|
+
const jsonlPath = path.join(cacheDir, 'artifacts_index.jsonl');
|
|
98
|
+
const line = JSON.stringify({
|
|
99
|
+
id: record.id,
|
|
100
|
+
tool: record.tool,
|
|
101
|
+
filePath: record.filePath,
|
|
102
|
+
timestamp: Date.now(),
|
|
103
|
+
snippet: record.content.slice(0, 300)
|
|
104
|
+
}) + '\n';
|
|
105
|
+
fs.appendFileSync(jsonlPath, line, 'utf8');
|
|
106
|
+
} catch (_err) {
|
|
107
|
+
// Graceful fallback
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Offloads tool result if eligible and exceeding token ceiling (>4k tokens),
|
|
113
|
+
* strictly preserving workspace read tools.
|
|
114
|
+
*
|
|
115
|
+
* @param {string} toolName - Name of the tool invoked
|
|
116
|
+
* @param {string} output - Tool stdout / string payload
|
|
117
|
+
* @param {object} [options={}]
|
|
118
|
+
* @param {number} [options.tokenThreshold=4000] - Token threshold for offloading
|
|
119
|
+
* @param {string} [options.artifactDir] - Directory to persist full offloaded artifacts
|
|
120
|
+
* @returns {{
|
|
121
|
+
* eligible: boolean,
|
|
122
|
+
* offloaded: boolean,
|
|
123
|
+
* output: string,
|
|
124
|
+
* sha256?: string,
|
|
125
|
+
* artifactPath?: string,
|
|
126
|
+
* originalTokens?: number,
|
|
127
|
+
* summaryTokens?: number,
|
|
128
|
+
* preservedErrorLines?: number
|
|
129
|
+
* }}
|
|
130
|
+
*/
|
|
131
|
+
export function offloadToolResult(toolName, output, options = {}) {
|
|
132
|
+
const rawOutput = String(output ?? '');
|
|
133
|
+
|
|
134
|
+
// INVARIANT: Workspace read/edit operations are strictly NEVER offloaded!
|
|
135
|
+
if (isWorkspaceReadTool(toolName)) {
|
|
136
|
+
return {
|
|
137
|
+
eligible: false,
|
|
138
|
+
offloaded: false,
|
|
139
|
+
output: rawOutput
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const tokenThreshold = options.tokenThreshold || 4000;
|
|
144
|
+
const estimatedTokens = estimateTokens(rawOutput);
|
|
145
|
+
|
|
146
|
+
// If payload does not exceed threshold, return untouched
|
|
147
|
+
if (estimatedTokens <= tokenThreshold) {
|
|
148
|
+
return {
|
|
149
|
+
eligible: true,
|
|
150
|
+
offloaded: false,
|
|
151
|
+
output: rawOutput,
|
|
152
|
+
originalTokens: estimatedTokens
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Payload > 4k tokens: proceed to lossless offload
|
|
157
|
+
const cleaned = stripAnsi(rawOutput);
|
|
158
|
+
const sha256 = crypto.createHash('sha256').update(cleaned, 'utf8').digest('hex');
|
|
159
|
+
const shortId = sha256.slice(0, 12);
|
|
160
|
+
|
|
161
|
+
const ctxtopDir = options.ctxtopDir || path.resolve(process.cwd(), '.ctxtop');
|
|
162
|
+
const artifactDir = options.artifactDir || path.join(ctxtopDir, 'cache', 'artifacts');
|
|
163
|
+
const artifactFile = `ah_${sha256}.txt`;
|
|
164
|
+
const artifactPath = path.join(artifactDir, artifactFile);
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
fs.mkdirSync(artifactDir, { recursive: true });
|
|
168
|
+
fs.writeFileSync(artifactPath, cleaned, 'utf8');
|
|
169
|
+
} catch {
|
|
170
|
+
// If writing artifact fails, return raw output fail-open
|
|
171
|
+
return {
|
|
172
|
+
eligible: true,
|
|
173
|
+
offloaded: false,
|
|
174
|
+
output: rawOutput,
|
|
175
|
+
originalTokens: estimatedTokens
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Index into FTS5
|
|
180
|
+
indexArtifactRecord({
|
|
181
|
+
id: `ah_${shortId}`,
|
|
182
|
+
tool: toolName,
|
|
183
|
+
content: cleaned,
|
|
184
|
+
filePath: artifactPath
|
|
185
|
+
}, options);
|
|
186
|
+
|
|
187
|
+
// Extract head lines and 100% of critical error lines
|
|
188
|
+
const allLines = cleaned.split(/\r?\n/);
|
|
189
|
+
const headLines = allLines.slice(0, 3);
|
|
190
|
+
const errorLines = [];
|
|
191
|
+
|
|
192
|
+
for (let i = 0; i < allLines.length; i++) {
|
|
193
|
+
const line = allLines[i];
|
|
194
|
+
if (CRITICAL_ERROR_REGEX.test(line)) {
|
|
195
|
+
errorLines.push(`[L${i + 1}] ${line.trim()}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Build compact, error-preserving summary (strictly <= 25 lines)
|
|
200
|
+
const summaryParts = [
|
|
201
|
+
`[Artifact Offloaded: ah_${shortId} (${allLines.length} lines, ~${estimatedTokens} tokens)]`,
|
|
202
|
+
`Artifact saved to: ${artifactPath}`,
|
|
203
|
+
'--- Sample Output (Head) ---',
|
|
204
|
+
...headLines
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
if (errorLines.length > 0) {
|
|
208
|
+
summaryParts.push('--- Preserved Critical Errors ---');
|
|
209
|
+
const cappedErrors = errorLines.slice(0, 12);
|
|
210
|
+
summaryParts.push(...cappedErrors);
|
|
211
|
+
if (errorLines.length > 12) {
|
|
212
|
+
summaryParts.push(`... (+${errorLines.length - 12} additional error lines preserved in artifact)`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
summaryParts.push('--- Inspection Pointer ---');
|
|
217
|
+
summaryParts.push(`To query this artifact: ctxtop search "ah_${shortId}"`);
|
|
218
|
+
|
|
219
|
+
const summaryText = summaryParts.join('\n');
|
|
220
|
+
const summaryTokens = estimateTokens(summaryText);
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
eligible: true,
|
|
224
|
+
offloaded: true,
|
|
225
|
+
output: summaryText,
|
|
226
|
+
sha256,
|
|
227
|
+
artifactPath,
|
|
228
|
+
originalTokens: estimatedTokens,
|
|
229
|
+
summaryTokens,
|
|
230
|
+
preservedErrorLines: errorLines.length
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export default {
|
|
235
|
+
isWorkspaceReadTool,
|
|
236
|
+
stripAnsi,
|
|
237
|
+
estimateTokens,
|
|
238
|
+
indexArtifactRecord,
|
|
239
|
+
offloadToolResult,
|
|
240
|
+
CRITICAL_ERROR_REGEX
|
|
241
|
+
};
|