atabey 0.0.13 → 0.0.14
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/ATABEY.md +1 -1
- package/README.md +252 -52
- package/dist/framework-mcp/src/index.js +914 -62
- package/dist/framework-mcp/src/index.js.map +1 -1
- package/dist/framework-mcp/src/tools/compliance/mask_pii.d.ts +17 -0
- package/dist/framework-mcp/src/tools/compliance/mask_pii.js +56 -0
- package/dist/framework-mcp/src/tools/compliance/mask_pii.js.map +1 -0
- package/dist/framework-mcp/src/tools/definitions.js +10 -9
- package/dist/framework-mcp/src/tools/definitions.js.map +1 -1
- package/dist/framework-mcp/src/tools/framework/run_tests.js +25 -0
- package/dist/framework-mcp/src/tools/framework/run_tests.js.map +1 -1
- package/dist/framework-mcp/src/tools/index.js +7 -8
- package/dist/framework-mcp/src/tools/index.js.map +1 -1
- package/dist/framework-mcp/src/tools/messaging/approve_operation.d.ts +22 -0
- package/dist/framework-mcp/src/tools/messaging/approve_operation.js +81 -0
- package/dist/framework-mcp/src/tools/messaging/approve_operation.js.map +1 -0
- package/dist/framework-mcp/src/tools/messaging/ask_human.d.ts +15 -0
- package/dist/framework-mcp/src/tools/messaging/ask_human.js +89 -20
- package/dist/framework-mcp/src/tools/messaging/ask_human.js.map +1 -1
- package/dist/framework-mcp/src/tools/observability/check_ports.js +3 -1
- package/dist/framework-mcp/src/tools/observability/check_ports.js.map +1 -1
- package/dist/framework-mcp/src/tools/quality/analyze_code_quality.js +13 -64
- package/dist/framework-mcp/src/tools/quality/analyze_code_quality.js.map +1 -1
- package/dist/framework-mcp/src/tools/schemas.d.ts +48 -53
- package/dist/framework-mcp/src/tools/schemas.js +18 -22
- package/dist/framework-mcp/src/tools/schemas.js.map +1 -1
- package/dist/framework-mcp/src/tools/shell/run_command.js +10 -0
- package/dist/framework-mcp/src/tools/shell/run_command.js.map +1 -1
- package/dist/framework-mcp/src/tools/types.d.ts +11 -105
- package/dist/framework-mcp/src/tools/types.js +1 -0
- package/dist/framework-mcp/src/tools/types.js.map +1 -1
- package/dist/framework-mcp/src/utils/auth.d.ts +36 -0
- package/dist/framework-mcp/src/utils/auth.js +79 -0
- package/dist/framework-mcp/src/utils/auth.js.map +1 -0
- package/dist/framework-mcp/src/utils/auto-rollback.d.ts +71 -0
- package/dist/framework-mcp/src/utils/auto-rollback.js +266 -0
- package/dist/framework-mcp/src/utils/auto-rollback.js.map +1 -0
- package/dist/framework-mcp/src/utils/compliance.js +12 -4
- package/dist/framework-mcp/src/utils/compliance.js.map +1 -1
- package/dist/framework-mcp/src/utils/context-optimizer.d.ts +69 -0
- package/dist/framework-mcp/src/utils/context-optimizer.js +157 -0
- package/dist/framework-mcp/src/utils/context-optimizer.js.map +1 -0
- package/dist/framework-mcp/src/utils/discipline.d.ts +68 -0
- package/dist/framework-mcp/src/utils/discipline.js +218 -0
- package/dist/framework-mcp/src/utils/discipline.js.map +1 -0
- package/dist/framework-mcp/src/utils/finops.d.ts +143 -0
- package/dist/framework-mcp/src/utils/finops.js +326 -0
- package/dist/framework-mcp/src/utils/finops.js.map +1 -0
- package/dist/framework-mcp/src/utils/human-in-loop.d.ts +95 -0
- package/dist/framework-mcp/src/utils/human-in-loop.js +216 -0
- package/dist/framework-mcp/src/utils/human-in-loop.js.map +1 -0
- package/dist/framework-mcp/src/utils/license-scanner.d.ts +71 -0
- package/dist/framework-mcp/src/utils/license-scanner.js +284 -0
- package/dist/framework-mcp/src/utils/license-scanner.js.map +1 -0
- package/dist/framework-mcp/src/utils/loop-detector.d.ts +105 -0
- package/dist/framework-mcp/src/utils/loop-detector.js +362 -0
- package/dist/framework-mcp/src/utils/loop-detector.js.map +1 -0
- package/dist/framework-mcp/src/utils/quality.d.ts +19 -0
- package/dist/framework-mcp/src/utils/quality.js +124 -0
- package/dist/framework-mcp/src/utils/quality.js.map +1 -0
- package/dist/framework-mcp/src/utils/rules-engine.d.ts +78 -0
- package/dist/framework-mcp/src/utils/rules-engine.js +232 -0
- package/dist/framework-mcp/src/utils/rules-engine.js.map +1 -0
- package/dist/framework-mcp/src/utils/silent-router.d.ts +47 -0
- package/dist/framework-mcp/src/utils/silent-router.js +129 -0
- package/dist/framework-mcp/src/utils/silent-router.js.map +1 -0
- package/dist/framework-mcp/src/utils/storage.d.ts +1 -0
- package/dist/framework-mcp/src/utils/storage.js +2 -2
- package/dist/framework-mcp/src/utils/storage.js.map +1 -1
- package/dist/framework-mcp/src/utils/telemetry-streamer.d.ts +133 -0
- package/dist/framework-mcp/src/utils/telemetry-streamer.js +397 -0
- package/dist/framework-mcp/src/utils/telemetry-streamer.js.map +1 -0
- package/dist/framework-mcp/tests/tools/file_system/file_system_tools.test.js +2 -2
- package/dist/framework-mcp/tests/tools/file_system/file_system_tools.test.js.map +1 -1
- package/dist/framework-mcp/tests/tools/framework/run_tests.test.d.ts +1 -0
- package/dist/framework-mcp/tests/tools/framework/run_tests.test.js +49 -0
- package/dist/framework-mcp/tests/tools/framework/run_tests.test.js.map +1 -0
- package/dist/framework-mcp/tests/tools/messaging/send_message.test.js +14 -5
- package/dist/framework-mcp/tests/tools/messaging/send_message.test.js.map +1 -1
- package/dist/framework-mcp/tests/tools/observability/check_ports.test.d.ts +1 -0
- package/dist/framework-mcp/tests/tools/observability/check_ports.test.js +30 -0
- package/dist/framework-mcp/tests/tools/observability/check_ports.test.js.map +1 -0
- package/dist/framework-mcp/tests/tools/shell/run_command.test.js +7 -0
- package/dist/framework-mcp/tests/tools/shell/run_command.test.js.map +1 -1
- package/dist/framework-mcp/tests/utils/auto-rollback.test.d.ts +7 -0
- package/dist/framework-mcp/tests/utils/auto-rollback.test.js +178 -0
- package/dist/framework-mcp/tests/utils/auto-rollback.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/context-optimizer.test.d.ts +1 -0
- package/dist/framework-mcp/tests/utils/context-optimizer.test.js +62 -0
- package/dist/framework-mcp/tests/utils/context-optimizer.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/finops.test.d.ts +7 -0
- package/dist/framework-mcp/tests/utils/finops.test.js +157 -0
- package/dist/framework-mcp/tests/utils/finops.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/human-in-loop.test.d.ts +1 -0
- package/dist/framework-mcp/tests/utils/human-in-loop.test.js +59 -0
- package/dist/framework-mcp/tests/utils/human-in-loop.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/license-scanner.test.d.ts +7 -0
- package/dist/framework-mcp/tests/utils/license-scanner.test.js +131 -0
- package/dist/framework-mcp/tests/utils/license-scanner.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/loop-detector.test.d.ts +7 -0
- package/dist/framework-mcp/tests/utils/loop-detector.test.js +204 -0
- package/dist/framework-mcp/tests/utils/loop-detector.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/rules-engine.test.d.ts +1 -0
- package/dist/framework-mcp/tests/utils/rules-engine.test.js +106 -0
- package/dist/framework-mcp/tests/utils/rules-engine.test.js.map +1 -0
- package/dist/framework-mcp/tests/utils/telemetry-streamer.test.d.ts +7 -0
- package/dist/framework-mcp/tests/utils/telemetry-streamer.test.js +201 -0
- package/dist/framework-mcp/tests/utils/telemetry-streamer.test.js.map +1 -0
- package/dist/src/cli/commands/check.js +16 -1
- package/dist/src/cli/commands/check.js.map +1 -1
- package/dist/src/cli/commands/dashboard.js +188 -164
- package/dist/src/cli/commands/dashboard.js.map +1 -1
- package/dist/src/cli/commands/gateway.js +2 -2
- package/dist/src/cli/commands/gateway.js.map +1 -1
- package/dist/src/cli/commands/init/scaffold-core.d.ts +2 -0
- package/dist/src/cli/commands/init/scaffold-core.js +16 -1
- package/dist/src/cli/commands/init/scaffold-core.js.map +1 -1
- package/dist/src/cli/commands/init/scaffold-ops.js +2 -2
- package/dist/src/cli/commands/init/scaffold-ops.js.map +1 -1
- package/dist/src/cli/commands/init/scaffold-standards.js +13 -1
- package/dist/src/cli/commands/init/scaffold-standards.js.map +1 -1
- package/dist/src/cli/commands/init.d.ts +4 -0
- package/dist/src/cli/commands/init.js +80 -24
- package/dist/src/cli/commands/init.js.map +1 -1
- package/dist/src/cli/commands/quickstart.d.ts +1 -1
- package/dist/src/cli/commands/quickstart.js +12 -24
- package/dist/src/cli/commands/quickstart.js.map +1 -1
- package/dist/src/cli/index.js +24 -23
- package/dist/src/cli/index.js.map +1 -1
- package/dist/src/cli/shims.js +7 -7
- package/dist/src/cli/utils/pkg.js +2 -3
- package/dist/src/cli/utils/pkg.js.map +1 -1
- package/dist/src/cli/utils/quality.d.ts +10 -0
- package/dist/src/cli/utils/quality.js +10 -0
- package/dist/src/cli/utils/quality.js.map +1 -0
- package/dist/src/modules/agents/definitions.js +45 -40
- package/dist/src/modules/agents/definitions.js.map +1 -1
- package/dist/src/modules/agents/registry/manager.js +6 -1
- package/dist/src/modules/agents/registry/manager.js.map +1 -1
- package/dist/src/modules/engines/agent-executor.d.ts +6 -10
- package/dist/src/modules/engines/agent-executor.js +53 -21
- package/dist/src/modules/engines/agent-executor.js.map +1 -1
- package/dist/src/modules/engines/agent-loop.d.ts +34 -0
- package/dist/src/modules/engines/agent-loop.js +102 -0
- package/dist/src/modules/engines/agent-loop.js.map +1 -0
- package/dist/src/modules/engines/evaluation-engine.js +2 -2
- package/dist/src/modules/engines/evaluation-engine.js.map +1 -1
- package/dist/src/modules/engines/quality-gate.d.ts +13 -5
- package/dist/src/modules/engines/quality-gate.js +39 -31
- package/dist/src/modules/engines/quality-gate.js.map +1 -1
- package/dist/src/modules/engines/routing-engine.d.ts +5 -3
- package/dist/src/modules/engines/routing-engine.js +16 -9
- package/dist/src/modules/engines/routing-engine.js.map +1 -1
- package/dist/src/modules/gateway/cost-tracker.d.ts +5 -0
- package/dist/src/modules/gateway/cost-tracker.js +71 -0
- package/dist/src/modules/gateway/cost-tracker.js.map +1 -1
- package/dist/src/modules/gateway/gateway.d.ts +4 -0
- package/dist/src/modules/gateway/gateway.js +8 -0
- package/dist/src/modules/gateway/gateway.js.map +1 -1
- package/dist/src/shared/audit.js +3 -2
- package/dist/src/shared/audit.js.map +1 -1
- package/dist/src/shared/pii.d.ts +41 -9
- package/dist/src/shared/pii.js +122 -31
- package/dist/src/shared/pii.js.map +1 -1
- package/dist/src/shared/storage.d.ts +19 -0
- package/dist/src/shared/storage.js +46 -6
- package/dist/src/shared/storage.js.map +1 -1
- package/dist/tests/embedding.test.d.ts +1 -0
- package/dist/tests/embedding.test.js +82 -0
- package/dist/tests/embedding.test.js.map +1 -0
- package/dist/tests/engines/evaluation-engine.test.d.ts +1 -0
- package/dist/tests/engines/evaluation-engine.test.js +71 -0
- package/dist/tests/engines/evaluation-engine.test.js.map +1 -0
- package/dist/tests/engines/planning-engine.test.d.ts +1 -0
- package/dist/tests/engines/planning-engine.test.js +100 -0
- package/dist/tests/engines/planning-engine.test.js.map +1 -0
- package/dist/tests/engines/quality-gate.test.d.ts +1 -0
- package/dist/tests/engines/quality-gate.test.js +59 -0
- package/dist/tests/engines/quality-gate.test.js.map +1 -0
- package/dist/tests/engines/risk-engine.test.d.ts +1 -0
- package/dist/tests/engines/risk-engine.test.js +80 -0
- package/dist/tests/engines/risk-engine.test.js.map +1 -0
- package/dist/tests/engines/routing-engine.test.d.ts +1 -0
- package/dist/tests/engines/routing-engine.test.js +78 -0
- package/dist/tests/engines/routing-engine.test.js.map +1 -0
- package/dist/tests/integration/hermes_locking.test.js +1 -0
- package/dist/tests/integration/hermes_locking.test.js.map +1 -1
- package/dist/tests/modules/gateway/cost-tracker.test.js +20 -1
- package/dist/tests/modules/gateway/cost-tracker.test.js.map +1 -1
- package/dist/tests/shared/lock.test.d.ts +1 -0
- package/dist/tests/shared/lock.test.js +95 -0
- package/dist/tests/shared/lock.test.js.map +1 -0
- package/dist/tests/shared/pii.test.d.ts +1 -0
- package/dist/tests/shared/pii.test.js +183 -0
- package/dist/tests/shared/pii.test.js.map +1 -0
- package/framework-mcp/README.md +307 -35
- package/framework-mcp/dist/dashboard/assets/index-B2mYld0c.js +1221 -0
- package/framework-mcp/dist/dashboard/index.html +1 -1
- package/framework-mcp/dist/framework-mcp/src/index.js +914 -62
- package/framework-mcp/dist/framework-mcp/src/tools/compliance/mask_pii.js +55 -0
- package/framework-mcp/dist/framework-mcp/src/tools/definitions.js +10 -9
- package/framework-mcp/dist/framework-mcp/src/tools/framework/run_tests.js +25 -0
- package/framework-mcp/dist/framework-mcp/src/tools/index.js +7 -8
- package/framework-mcp/dist/framework-mcp/src/tools/messaging/approve_operation.js +80 -0
- package/framework-mcp/dist/framework-mcp/src/tools/messaging/ask_human.js +89 -20
- package/framework-mcp/dist/framework-mcp/src/tools/observability/check_ports.js +3 -1
- package/framework-mcp/dist/framework-mcp/src/tools/quality/analyze_code_quality.js +13 -64
- package/framework-mcp/dist/framework-mcp/src/tools/schemas.js +18 -22
- package/framework-mcp/dist/framework-mcp/src/tools/shell/run_command.js +10 -0
- package/framework-mcp/dist/framework-mcp/src/tools/types.js +1 -0
- package/framework-mcp/dist/framework-mcp/src/utils/auth.js +78 -0
- package/framework-mcp/dist/framework-mcp/src/utils/auto-rollback.js +265 -0
- package/framework-mcp/dist/framework-mcp/src/utils/compliance.js +12 -4
- package/framework-mcp/dist/framework-mcp/src/utils/context-optimizer.js +156 -0
- package/framework-mcp/dist/framework-mcp/src/utils/discipline.js +217 -0
- package/framework-mcp/dist/framework-mcp/src/utils/finops.js +325 -0
- package/framework-mcp/dist/framework-mcp/src/utils/human-in-loop.js +215 -0
- package/framework-mcp/dist/framework-mcp/src/utils/license-scanner.js +283 -0
- package/framework-mcp/dist/framework-mcp/src/utils/loop-detector.js +361 -0
- package/framework-mcp/dist/framework-mcp/src/utils/quality.js +123 -0
- package/framework-mcp/dist/framework-mcp/src/utils/rules-engine.js +231 -0
- package/framework-mcp/dist/framework-mcp/src/utils/silent-router.js +128 -0
- package/framework-mcp/dist/framework-mcp/src/utils/storage.js +2 -2
- package/framework-mcp/dist/framework-mcp/src/utils/telemetry-streamer.js +396 -0
- package/framework-mcp/dist/src/cli/platforms/core.js +72 -0
- package/framework-mcp/dist/src/cli/platforms/index.js +5 -0
- package/framework-mcp/dist/src/cli/platforms/paths.js +101 -0
- package/framework-mcp/dist/src/cli/platforms/scaffold.js +72 -0
- package/framework-mcp/dist/src/cli/platforms/utils.js +75 -0
- package/framework-mcp/dist/src/cli/utils/claude.js +57 -0
- package/framework-mcp/dist/src/cli/utils/compliance.js +12 -0
- package/framework-mcp/dist/src/cli/utils/fs.js +138 -0
- package/framework-mcp/dist/src/cli/utils/pkg.js +282 -0
- package/framework-mcp/dist/src/cli/utils/quality.js +9 -0
- package/framework-mcp/dist/src/modules/agents/definitions.js +563 -0
- package/framework-mcp/dist/src/modules/agents/registry/analyst.js +39 -0
- package/framework-mcp/dist/src/modules/agents/registry/architect.js +42 -0
- package/framework-mcp/dist/src/modules/agents/registry/backend.js +50 -0
- package/framework-mcp/dist/src/modules/agents/registry/database.js +45 -0
- package/framework-mcp/dist/src/modules/agents/registry/devops.js +45 -0
- package/framework-mcp/dist/src/modules/agents/registry/explorer.js +37 -0
- package/framework-mcp/dist/src/modules/agents/registry/frontend.js +52 -0
- package/framework-mcp/dist/src/modules/agents/registry/git.js +36 -0
- package/framework-mcp/dist/src/modules/agents/registry/manager.js +64 -0
- package/framework-mcp/dist/src/modules/agents/registry/mobile.js +41 -0
- package/framework-mcp/dist/src/modules/agents/registry/native.js +41 -0
- package/framework-mcp/dist/src/modules/agents/registry/quality.js +43 -0
- package/framework-mcp/dist/src/modules/agents/registry/security.js +42 -0
- package/framework-mcp/dist/src/modules/agents/types.js +1 -0
- package/framework-mcp/dist/src/modules/engines/quality-gate.js +92 -0
- package/framework-mcp/dist/src/modules/engines/risk-engine.js +105 -0
- package/framework-mcp/dist/src/modules/engines/routing-engine.js +408 -0
- package/framework-mcp/dist/src/modules/engines/types.js +1 -0
- package/framework-mcp/dist/src/modules/providers/definitions.js +140 -0
- package/framework-mcp/dist/src/modules/providers/registry.js +18 -0
- package/framework-mcp/dist/src/modules/providers/shared.js +104 -0
- package/framework-mcp/dist/src/modules/providers/types.js +1 -0
- package/framework-mcp/dist/src/modules/skills/adapter-skills.js +449 -0
- package/framework-mcp/dist/src/modules/skills/definitions.js +70 -0
- package/framework-mcp/dist/src/shared/audit.js +220 -0
- package/framework-mcp/dist/src/shared/errors.js +68 -0
- package/framework-mcp/dist/src/shared/lock.js +159 -0
- package/framework-mcp/dist/src/shared/pii.js +122 -31
- package/framework-mcp/dist/src/shared/retention.js +170 -0
- package/framework-mcp/dist/src/shared/storage.js +46 -6
- package/framework-mcp/dist/src/shared/string.js +29 -0
- package/framework-mcp/package.json +8 -2
- package/mcp.json +11 -6
- package/package.json +13 -6
- package/templates/full/ATABEY_FULL.md +1 -1
- package/framework-mcp/dist/dashboard/assets/index-BAPGLiWE.js +0 -267
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ─── AI DISCIPLINE ENGINE ─────────────────────────────────────────
|
|
3
|
+
*
|
|
4
|
+
* Enforces strict rules on AI behavior at the MCP middleware layer.
|
|
5
|
+
* Unlike agent instructions (which AI can ignore), these are enforced
|
|
6
|
+
* at the tool level - AI cannot bypass them.
|
|
7
|
+
*
|
|
8
|
+
* Features:
|
|
9
|
+
* - Tool call rate limiting (prevents abuse)
|
|
10
|
+
* - File size limits (prevents reading/writing huge files)
|
|
11
|
+
* - Call frequency tracking (detects loops)
|
|
12
|
+
* - Tool blacklist per agent
|
|
13
|
+
* - Agent-based tool whitelist
|
|
14
|
+
* - Response content validation
|
|
15
|
+
* - Max concurrent operations
|
|
16
|
+
*/
|
|
17
|
+
import fs from "fs";
|
|
18
|
+
import path from "path";
|
|
19
|
+
// Per-agent discipline tracking
|
|
20
|
+
const agentDiscipline = new Map();
|
|
21
|
+
// ─── Configuration (from env or defaults) ─────────────────────────
|
|
22
|
+
const CONFIG = {
|
|
23
|
+
MAX_CALLS_PER_MINUTE: parseInt(process.env.MCP_MAX_CALLS_PER_MINUTE || "60", 10),
|
|
24
|
+
MAX_TOTAL_CALLS: parseInt(process.env.MCP_MAX_TOTAL_CALLS || "500", 10),
|
|
25
|
+
MAX_FILE_SIZE: parseInt(process.env.MCP_MAX_FILE_SIZE || "1048576", 10),
|
|
26
|
+
MAX_ARGS_SIZE: parseInt(process.env.MCP_MAX_ARGS_SIZE || "102400", 10),
|
|
27
|
+
COOLDOWN_MS: parseInt(process.env.MCP_COOLDOWN_MS || "30000", 10),
|
|
28
|
+
MAX_RESPONSE_SIZE: parseInt(process.env.MCP_MAX_RESPONSE_SIZE || "512000", 10), // 500KB max response
|
|
29
|
+
MAX_CONSECUTIVE_SAME_TOOL: parseInt(process.env.MCP_MAX_CONSECUTIVE_SAME_TOOL || "10", 10),
|
|
30
|
+
RESTRICTED_TOOLS: (process.env.MCP_RESTRICTED_TOOLS || "")
|
|
31
|
+
.split(",").map(t => t.trim()).filter(Boolean),
|
|
32
|
+
// Agent-based tool whitelist (format: agent1:tool1,tool2;agent2:tool3,tool4)
|
|
33
|
+
AGENT_TOOL_WHITELIST: parseAgentWhitelist(process.env.MCP_AGENT_TOOL_WHITELIST || ""),
|
|
34
|
+
};
|
|
35
|
+
function parseAgentWhitelist(input) {
|
|
36
|
+
const map = new Map();
|
|
37
|
+
if (!input)
|
|
38
|
+
return map;
|
|
39
|
+
input.split(";").forEach(pair => {
|
|
40
|
+
const [agent, tools] = pair.split(":");
|
|
41
|
+
if (agent && tools) {
|
|
42
|
+
map.set(agent.trim(), new Set(tools.split(",").map(t => t.trim())));
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
return map;
|
|
46
|
+
}
|
|
47
|
+
const cooldowns = new Map();
|
|
48
|
+
function getOrCreateAgent(agent) {
|
|
49
|
+
if (!agentDiscipline.has(agent)) {
|
|
50
|
+
const whitelist = CONFIG.AGENT_TOOL_WHITELIST.get(agent) || null;
|
|
51
|
+
agentDiscipline.set(agent, {
|
|
52
|
+
totalCalls: 0,
|
|
53
|
+
calls: [],
|
|
54
|
+
lastReset: Date.now(),
|
|
55
|
+
blacklistedTools: new Set(),
|
|
56
|
+
whitelistedTools: whitelist,
|
|
57
|
+
violations: 0,
|
|
58
|
+
lastViolation: null,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return agentDiscipline.get(agent);
|
|
62
|
+
}
|
|
63
|
+
function pruneOldCalls(agent, windowMs = 60000) {
|
|
64
|
+
const cutoff = Date.now() - windowMs;
|
|
65
|
+
agent.calls = agent.calls.filter(c => c.timestamp > cutoff);
|
|
66
|
+
}
|
|
67
|
+
function isInCooldown(agent) {
|
|
68
|
+
const until = cooldowns.get(agent);
|
|
69
|
+
if (!until)
|
|
70
|
+
return false;
|
|
71
|
+
if (Date.now() > until) {
|
|
72
|
+
cooldowns.delete(agent);
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
function recordViolation(agent, reason) {
|
|
78
|
+
const discipline = agentDiscipline.get(agent);
|
|
79
|
+
if (discipline) {
|
|
80
|
+
discipline.violations++;
|
|
81
|
+
discipline.lastViolation = reason;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Enforce discipline on a tool call before execution.
|
|
86
|
+
* Returns error message if blocked, null if allowed.
|
|
87
|
+
*/
|
|
88
|
+
export async function enforceDiscipline(agent, toolName, args) {
|
|
89
|
+
const discipline = getOrCreateAgent(agent);
|
|
90
|
+
// 1. Check cooldown
|
|
91
|
+
if (isInCooldown(agent)) {
|
|
92
|
+
const until = cooldowns.get(agent);
|
|
93
|
+
const remaining = Math.ceil((until - Date.now()) / 1000);
|
|
94
|
+
return `[DISCIPLINE] Agent ${agent} is in cooldown for ${remaining}s. Too many requests.`;
|
|
95
|
+
}
|
|
96
|
+
// 2. Check restricted tools (global blacklist)
|
|
97
|
+
if (CONFIG.RESTRICTED_TOOLS.includes(toolName)) {
|
|
98
|
+
recordViolation(agent, `Attempted to use restricted tool: ${toolName}`);
|
|
99
|
+
return `[DISCIPLINE] Tool "${toolName}" is restricted. Agent ${agent} cannot use it.`;
|
|
100
|
+
}
|
|
101
|
+
// 3. Check agent-specific whitelist
|
|
102
|
+
if (discipline.whitelistedTools && !discipline.whitelistedTools.has(toolName)) {
|
|
103
|
+
recordViolation(agent, `Attempted to use non-whitelisted tool: ${toolName}`);
|
|
104
|
+
const allowed = Array.from(discipline.whitelistedTools).join(", ");
|
|
105
|
+
return `[DISCIPLINE] Agent ${agent} is not allowed to use "${toolName}". Allowed tools: ${allowed}`;
|
|
106
|
+
}
|
|
107
|
+
// 4. Check total call limit
|
|
108
|
+
if (discipline.totalCalls >= CONFIG.MAX_TOTAL_CALLS) {
|
|
109
|
+
cooldowns.set(agent, Date.now() + CONFIG.COOLDOWN_MS);
|
|
110
|
+
recordViolation(agent, `Exceeded max total calls (${CONFIG.MAX_TOTAL_CALLS})`);
|
|
111
|
+
return `[DISCIPLINE] Agent ${agent} exceeded max total calls (${CONFIG.MAX_TOTAL_CALLS}). Cooldown ${CONFIG.COOLDOWN_MS / 1000}s.`;
|
|
112
|
+
}
|
|
113
|
+
// 5. Check rate limit (calls per minute)
|
|
114
|
+
pruneOldCalls(discipline);
|
|
115
|
+
if (discipline.calls.length >= CONFIG.MAX_CALLS_PER_MINUTE) {
|
|
116
|
+
cooldowns.set(agent, Date.now() + CONFIG.COOLDOWN_MS);
|
|
117
|
+
recordViolation(agent, `Rate limit exceeded (${CONFIG.MAX_CALLS_PER_MINUTE}/min)`);
|
|
118
|
+
return `[DISCIPLINE] Agent ${agent} exceeded rate limit (${CONFIG.MAX_CALLS_PER_MINUTE}/min). Cooldown ${CONFIG.COOLDOWN_MS / 1000}s.`;
|
|
119
|
+
}
|
|
120
|
+
// 6. Check consecutive same tool (prevents loops)
|
|
121
|
+
if (discipline.calls.length >= CONFIG.MAX_CONSECUTIVE_SAME_TOOL) {
|
|
122
|
+
const lastCalls = discipline.calls.slice(-CONFIG.MAX_CONSECUTIVE_SAME_TOOL);
|
|
123
|
+
const allSame = lastCalls.every(c => c.tool === toolName);
|
|
124
|
+
if (allSame) {
|
|
125
|
+
cooldowns.set(agent, Date.now() + CONFIG.COOLDOWN_MS);
|
|
126
|
+
recordViolation(agent, `Consecutive same tool limit: ${toolName} x${CONFIG.MAX_CONSECUTIVE_SAME_TOOL}`);
|
|
127
|
+
return `[DISCIPLINE] Agent ${agent} called "${toolName}" ${CONFIG.MAX_CONSECUTIVE_SAME_TOOL} times in a row. Possible loop. Cooldown.`;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// 7. Check args size
|
|
131
|
+
const argsStr = JSON.stringify(args);
|
|
132
|
+
if (argsStr.length > CONFIG.MAX_ARGS_SIZE) {
|
|
133
|
+
recordViolation(agent, `Args too large: ${argsStr.length} bytes`);
|
|
134
|
+
return `[DISCIPLINE] Tool call args too large (${argsStr.length} bytes, max: ${CONFIG.MAX_ARGS_SIZE}).`;
|
|
135
|
+
}
|
|
136
|
+
// 8. Check file size for read/write operations
|
|
137
|
+
if ((toolName === "read_file" || toolName === "write_file") && args.path) {
|
|
138
|
+
try {
|
|
139
|
+
const projectRoot = process.env.ATABEY_PROJECT_ROOT || process.cwd();
|
|
140
|
+
const filePath = path.resolve(projectRoot, args.path);
|
|
141
|
+
if (fs.existsSync(filePath)) {
|
|
142
|
+
const stat = fs.statSync(filePath);
|
|
143
|
+
if (stat.size > CONFIG.MAX_FILE_SIZE) {
|
|
144
|
+
return `[DISCIPLINE] File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB, max: ${(CONFIG.MAX_FILE_SIZE / 1024 / 1024).toFixed(1)}MB). Use grep_search instead.`;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch { /* ignore */ }
|
|
149
|
+
}
|
|
150
|
+
// Record the call
|
|
151
|
+
discipline.totalCalls++;
|
|
152
|
+
discipline.calls.push({
|
|
153
|
+
tool: toolName,
|
|
154
|
+
timestamp: Date.now(),
|
|
155
|
+
argsSize: argsStr.length,
|
|
156
|
+
});
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Validate tool response content before returning to AI.
|
|
161
|
+
* Returns error message if blocked, null if allowed.
|
|
162
|
+
*/
|
|
163
|
+
export function validateResponse(toolName, result) {
|
|
164
|
+
if (!result || !result.content)
|
|
165
|
+
return null;
|
|
166
|
+
for (const block of result.content) {
|
|
167
|
+
if (block.type !== "text" || !block.text)
|
|
168
|
+
continue;
|
|
169
|
+
// Check response size
|
|
170
|
+
if (block.text.length > CONFIG.MAX_RESPONSE_SIZE) {
|
|
171
|
+
return `[DISCIPLINE] Response too large (${(block.text.length / 1024).toFixed(1)}KB, max: ${(CONFIG.MAX_RESPONSE_SIZE / 1024).toFixed(1)}KB).`;
|
|
172
|
+
}
|
|
173
|
+
// Block binary/gibberish content in text responses
|
|
174
|
+
const nonPrintable = (block.text.match(/[^\x20-\x7E\n\r\t]/g) || []).length;
|
|
175
|
+
if (nonPrintable > block.text.length * 0.3) {
|
|
176
|
+
return `[DISCIPLINE] Response contains too much binary data (${nonPrintable} non-printable chars). Blocked.`;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Get discipline stats for an agent.
|
|
183
|
+
*/
|
|
184
|
+
export function getDisciplineStats(agent) {
|
|
185
|
+
const discipline = agentDiscipline.get(agent);
|
|
186
|
+
if (!discipline) {
|
|
187
|
+
return { totalCalls: 0, recentCalls: 0, inCooldown: false, cooldownRemaining: 0, violations: 0, lastViolation: null };
|
|
188
|
+
}
|
|
189
|
+
pruneOldCalls(discipline);
|
|
190
|
+
const cooldownUntil = cooldowns.get(agent);
|
|
191
|
+
return {
|
|
192
|
+
totalCalls: discipline.totalCalls,
|
|
193
|
+
recentCalls: discipline.calls.length,
|
|
194
|
+
inCooldown: isInCooldown(agent),
|
|
195
|
+
cooldownRemaining: cooldownUntil ? Math.max(0, cooldownUntil - Date.now()) : 0,
|
|
196
|
+
violations: discipline.violations,
|
|
197
|
+
lastViolation: discipline.lastViolation,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Get all agents' discipline stats.
|
|
202
|
+
*/
|
|
203
|
+
export function getAllDisciplineStats() {
|
|
204
|
+
const stats = {};
|
|
205
|
+
for (const [agent, _discipline] of agentDiscipline) {
|
|
206
|
+
stats[agent] = getDisciplineStats(agent);
|
|
207
|
+
}
|
|
208
|
+
return stats;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Reset discipline for all agents.
|
|
212
|
+
*/
|
|
213
|
+
export function resetDiscipline() {
|
|
214
|
+
agentDiscipline.clear();
|
|
215
|
+
cooldowns.clear();
|
|
216
|
+
}
|
|
217
|
+
export { CONFIG as DisciplineConfig };
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ─── FINOPS / BUDGET ENFORCEMENT ──────────────────────────────────
|
|
3
|
+
*
|
|
4
|
+
* Enterprise budget management for AI token consumption.
|
|
5
|
+
* Enforces strict cost limits per team, agent, or project.
|
|
6
|
+
*
|
|
7
|
+
* Features:
|
|
8
|
+
* - Team-based budget allocation (monthly/quarterly)
|
|
9
|
+
* - Per-agent spending limits
|
|
10
|
+
* - Automatic shutdown when budget exceeded
|
|
11
|
+
* - Central server sync for budget policies
|
|
12
|
+
* - Real-time cost tracking
|
|
13
|
+
* - Budget alerts at configurable thresholds (50%, 80%, 90%, 100%)
|
|
14
|
+
*
|
|
15
|
+
* Architecture:
|
|
16
|
+
* [Local MCP] → Budget Check → [Enterprise Server] → Shutdown Signal
|
|
17
|
+
*
|
|
18
|
+
* Environment Variables:
|
|
19
|
+
* ATABEY_BUDGET_TEAM - Team name for budget grouping
|
|
20
|
+
* ATABEY_BUDGET_MONTHLY - Monthly budget in USD (local override)
|
|
21
|
+
* ATABEY_BUDGET_AGENT_MAX - Max spend per agent in USD
|
|
22
|
+
* ATABEY_BUDGET_SYNC_URL - Enterprise server URL for budget sync
|
|
23
|
+
*/
|
|
24
|
+
import fs from "fs";
|
|
25
|
+
import path from "path";
|
|
26
|
+
// ─── Configuration ────────────────────────────────────────────────
|
|
27
|
+
const CONFIG = {
|
|
28
|
+
/** Team name for budget grouping */
|
|
29
|
+
TEAM: process.env.ATABEY_BUDGET_TEAM || "default",
|
|
30
|
+
/** Monthly budget in USD (0 = unlimited) */
|
|
31
|
+
MONTHLY_BUDGET: parseFloat(process.env.ATABEY_BUDGET_MONTHLY || "0"),
|
|
32
|
+
/** Max spend per agent in USD (0 = unlimited) */
|
|
33
|
+
AGENT_MAX_BUDGET: parseFloat(process.env.ATABEY_BUDGET_AGENT_MAX || "0"),
|
|
34
|
+
/** Enterprise server URL for budget policy sync */
|
|
35
|
+
SYNC_URL: process.env.ATABEY_BUDGET_SYNC_URL || "",
|
|
36
|
+
/** Sync token */
|
|
37
|
+
SYNC_TOKEN: process.env.ATABEY_BUDGET_SYNC_TOKEN || "",
|
|
38
|
+
/** Budget alert thresholds (percentages) */
|
|
39
|
+
ALERT_THRESHOLDS: (process.env.ATABEY_BUDGET_ALERT_THRESHOLDS || "50,80,90,100")
|
|
40
|
+
.split(",").map(t => parseInt(t.trim(), 10)).filter(t => !isNaN(t)),
|
|
41
|
+
/** Cost per 1K tokens (USD) – default: $0.003 for Claude */
|
|
42
|
+
COST_PER_1K_TOKENS: parseFloat(process.env.ATABEY_COST_PER_1K_TOKENS || "0.003"),
|
|
43
|
+
/** Sync interval in ms */
|
|
44
|
+
SYNC_INTERVAL_MS: parseInt(process.env.ATABEY_BUDGET_SYNC_INTERVAL || "60000", 10),
|
|
45
|
+
/** Enable/disable budget enforcement */
|
|
46
|
+
ENABLED: process.env.ATABEY_BUDGET_ENABLED === "true",
|
|
47
|
+
};
|
|
48
|
+
// ─── Budget Manager ───────────────────────────────────────────────
|
|
49
|
+
export class BudgetManager {
|
|
50
|
+
static instance;
|
|
51
|
+
state;
|
|
52
|
+
syncTimer = null;
|
|
53
|
+
localMetricsPath;
|
|
54
|
+
constructor() {
|
|
55
|
+
const now = new Date();
|
|
56
|
+
const periodStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
|
|
57
|
+
const periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString();
|
|
58
|
+
this.state = {
|
|
59
|
+
team: CONFIG.TEAM,
|
|
60
|
+
monthlySpend: 0,
|
|
61
|
+
agentSpend: {},
|
|
62
|
+
periodStart,
|
|
63
|
+
periodEnd,
|
|
64
|
+
blocked: false,
|
|
65
|
+
blockReason: null,
|
|
66
|
+
triggeredAlerts: [],
|
|
67
|
+
lastSync: null,
|
|
68
|
+
};
|
|
69
|
+
const frameworkDir = process.env.ATABEY_FRAMEWORK_DIR || path.join(process.cwd(), ".atabey");
|
|
70
|
+
this.localMetricsPath = path.join(frameworkDir, "observability", "metrics.json");
|
|
71
|
+
// Load existing state
|
|
72
|
+
this.loadState();
|
|
73
|
+
}
|
|
74
|
+
static getInstance() {
|
|
75
|
+
if (!BudgetManager.instance) {
|
|
76
|
+
BudgetManager.instance = new BudgetManager();
|
|
77
|
+
}
|
|
78
|
+
return BudgetManager.instance;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Start the budget manager.
|
|
82
|
+
* Begins periodic sync with enterprise server.
|
|
83
|
+
*/
|
|
84
|
+
start() {
|
|
85
|
+
if (!CONFIG.ENABLED) {
|
|
86
|
+
process.stderr.write("[FINOPS] Budget enforcement disabled.\n");
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
process.stderr.write(`[FINOPS] Starting budget manager for team "${CONFIG.TEAM}"\n`);
|
|
90
|
+
if (CONFIG.MONTHLY_BUDGET > 0) {
|
|
91
|
+
process.stderr.write(`[FINOPS] Monthly budget: $${CONFIG.MONTHLY_BUDGET.toFixed(2)}\n`);
|
|
92
|
+
}
|
|
93
|
+
// Periodic sync with enterprise server
|
|
94
|
+
if (CONFIG.SYNC_URL) {
|
|
95
|
+
this.syncTimer = setInterval(() => this.syncWithServer(), CONFIG.SYNC_INTERVAL_MS);
|
|
96
|
+
this.syncWithServer(); // Initial sync
|
|
97
|
+
}
|
|
98
|
+
// Recalculate from local metrics
|
|
99
|
+
this.recalculateFromLocalMetrics();
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Stop the budget manager.
|
|
103
|
+
*/
|
|
104
|
+
stop() {
|
|
105
|
+
if (this.syncTimer) {
|
|
106
|
+
clearInterval(this.syncTimer);
|
|
107
|
+
this.syncTimer = null;
|
|
108
|
+
}
|
|
109
|
+
this.saveState();
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Record token usage and check budget.
|
|
113
|
+
* Returns error message if budget exceeded, null if allowed.
|
|
114
|
+
*/
|
|
115
|
+
recordUsage(agent, tokens) {
|
|
116
|
+
if (!CONFIG.ENABLED)
|
|
117
|
+
return null;
|
|
118
|
+
const cost = (tokens / 1000) * CONFIG.COST_PER_1K_TOKENS;
|
|
119
|
+
// Check if team is blocked
|
|
120
|
+
if (this.state.blocked) {
|
|
121
|
+
return `[FINOPS] ⛔ Budget exceeded: ${this.state.blockReason}`;
|
|
122
|
+
}
|
|
123
|
+
// Update spend
|
|
124
|
+
this.state.monthlySpend += cost;
|
|
125
|
+
this.state.agentSpend[agent] = (this.state.agentSpend[agent] || 0) + cost;
|
|
126
|
+
// Check team budget
|
|
127
|
+
if (CONFIG.MONTHLY_BUDGET > 0 && this.state.monthlySpend > CONFIG.MONTHLY_BUDGET) {
|
|
128
|
+
this.state.blocked = true;
|
|
129
|
+
this.state.blockReason = `Team "${CONFIG.TEAM}" exceeded monthly budget of $${CONFIG.MONTHLY_BUDGET.toFixed(2)}`;
|
|
130
|
+
this.saveState();
|
|
131
|
+
this.triggerAlert(100);
|
|
132
|
+
return `[FINOPS] ⛔ ${this.state.blockReason}`;
|
|
133
|
+
}
|
|
134
|
+
// Check agent budget
|
|
135
|
+
if (CONFIG.AGENT_MAX_BUDGET > 0 && (this.state.agentSpend[agent] || 0) > CONFIG.AGENT_MAX_BUDGET) {
|
|
136
|
+
this.state.blocked = true;
|
|
137
|
+
this.state.blockReason = `Agent "${agent}" exceeded max budget of $${CONFIG.AGENT_MAX_BUDGET.toFixed(2)}`;
|
|
138
|
+
this.saveState();
|
|
139
|
+
this.triggerAlert(100);
|
|
140
|
+
return `[FINOPS] ⛔ ${this.state.blockReason}`;
|
|
141
|
+
}
|
|
142
|
+
// Check alert thresholds
|
|
143
|
+
if (CONFIG.MONTHLY_BUDGET > 0) {
|
|
144
|
+
const usagePercent = (this.state.monthlySpend / CONFIG.MONTHLY_BUDGET) * 100;
|
|
145
|
+
for (const threshold of CONFIG.ALERT_THRESHOLDS) {
|
|
146
|
+
if (usagePercent >= threshold && !this.state.triggeredAlerts.includes(threshold)) {
|
|
147
|
+
this.triggerAlert(threshold);
|
|
148
|
+
process.stderr.write(`[FINOPS] ⚠️ Budget alert: ${Math.round(usagePercent)}% used ($${this.state.monthlySpend.toFixed(2)} / $${CONFIG.MONTHLY_BUDGET.toFixed(2)})\n`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
this.saveState();
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Check if an agent is within budget without recording usage.
|
|
157
|
+
*/
|
|
158
|
+
checkBudget(agent) {
|
|
159
|
+
const agentSpend = this.state.agentSpend[agent] || 0;
|
|
160
|
+
const usagePercent = CONFIG.MONTHLY_BUDGET > 0
|
|
161
|
+
? (this.state.monthlySpend / CONFIG.MONTHLY_BUDGET) * 100
|
|
162
|
+
: 0;
|
|
163
|
+
return {
|
|
164
|
+
allowed: !this.state.blocked,
|
|
165
|
+
monthlySpend: this.state.monthlySpend,
|
|
166
|
+
monthlyBudget: CONFIG.MONTHLY_BUDGET,
|
|
167
|
+
agentSpend,
|
|
168
|
+
agentMaxBudget: CONFIG.AGENT_MAX_BUDGET,
|
|
169
|
+
usagePercent: Math.round(usagePercent * 100) / 100,
|
|
170
|
+
blocked: this.state.blocked,
|
|
171
|
+
blockReason: this.state.blockReason,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Get full budget state.
|
|
176
|
+
*/
|
|
177
|
+
getState() {
|
|
178
|
+
return { ...this.state };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Reset budget for new period.
|
|
182
|
+
*/
|
|
183
|
+
resetPeriod() {
|
|
184
|
+
const now = new Date();
|
|
185
|
+
this.state.monthlySpend = 0;
|
|
186
|
+
this.state.agentSpend = {};
|
|
187
|
+
this.state.periodStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
|
|
188
|
+
this.state.periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString();
|
|
189
|
+
this.state.blocked = false;
|
|
190
|
+
this.state.blockReason = null;
|
|
191
|
+
this.state.triggeredAlerts = [];
|
|
192
|
+
this.saveState();
|
|
193
|
+
process.stderr.write("[FINOPS] Budget period reset.\n");
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Apply a budget policy from the enterprise server.
|
|
197
|
+
*/
|
|
198
|
+
applyPolicy(policy) {
|
|
199
|
+
if (policy.team !== CONFIG.TEAM)
|
|
200
|
+
return;
|
|
201
|
+
if (policy.blocked) {
|
|
202
|
+
this.state.blocked = true;
|
|
203
|
+
this.state.blockReason = policy.blockReason || "Blocked by enterprise policy";
|
|
204
|
+
process.stderr.write(`[FINOPS] 🛑 Team "${CONFIG.TEAM}" blocked by enterprise policy: ${this.state.blockReason}\n`);
|
|
205
|
+
}
|
|
206
|
+
this.saveState();
|
|
207
|
+
}
|
|
208
|
+
// ─── Private Methods ───────────────────────────────────────
|
|
209
|
+
/**
|
|
210
|
+
* Sync budget state with enterprise server.
|
|
211
|
+
*/
|
|
212
|
+
async syncWithServer() {
|
|
213
|
+
if (!CONFIG.SYNC_URL)
|
|
214
|
+
return;
|
|
215
|
+
try {
|
|
216
|
+
// Send local state to server
|
|
217
|
+
const url = `${CONFIG.SYNC_URL.replace(/\/$/, "")}/api/finops/sync`;
|
|
218
|
+
const response = await fetch(url, {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers: {
|
|
221
|
+
"Content-Type": "application/json",
|
|
222
|
+
"Authorization": `Bearer ${CONFIG.SYNC_TOKEN}`,
|
|
223
|
+
"X-Team": CONFIG.TEAM,
|
|
224
|
+
},
|
|
225
|
+
body: JSON.stringify({
|
|
226
|
+
team: this.state.team,
|
|
227
|
+
monthlySpend: this.state.monthlySpend,
|
|
228
|
+
agentSpend: this.state.agentSpend,
|
|
229
|
+
periodStart: this.state.periodStart,
|
|
230
|
+
periodEnd: this.state.periodEnd,
|
|
231
|
+
}),
|
|
232
|
+
});
|
|
233
|
+
if (response.ok) {
|
|
234
|
+
const policy = (await response.json());
|
|
235
|
+
this.applyPolicy(policy);
|
|
236
|
+
this.state.lastSync = new Date().toISOString();
|
|
237
|
+
}
|
|
238
|
+
else if (response.status === 402) {
|
|
239
|
+
// Payment required – budget exceeded on server side
|
|
240
|
+
const data = (await response.json());
|
|
241
|
+
this.state.blocked = true;
|
|
242
|
+
this.state.blockReason = data.reason || "Budget exceeded on enterprise server";
|
|
243
|
+
process.stderr.write(`[FINOPS] 🛑 Enterprise budget exceeded: ${this.state.blockReason}\n`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
// Server unreachable – continue with local budget
|
|
248
|
+
process.stderr.write(`[FINOPS] Sync failed (server unreachable): ${error}\n`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Recalculate spend from local metrics file.
|
|
253
|
+
*/
|
|
254
|
+
recalculateFromLocalMetrics() {
|
|
255
|
+
try {
|
|
256
|
+
if (!fs.existsSync(this.localMetricsPath))
|
|
257
|
+
return;
|
|
258
|
+
const metrics = JSON.parse(fs.readFileSync(this.localMetricsPath, "utf8"));
|
|
259
|
+
const periodStart = new Date(this.state.periodStart);
|
|
260
|
+
const periodEnd = new Date(this.state.periodEnd);
|
|
261
|
+
let totalSpend = 0;
|
|
262
|
+
const agentSpend = {};
|
|
263
|
+
for (const entry of metrics) {
|
|
264
|
+
const entryDate = new Date(entry.timestamp);
|
|
265
|
+
if (entryDate >= periodStart && entryDate <= periodEnd) {
|
|
266
|
+
const cost = (entry.estimatedTokens / 1000) * CONFIG.COST_PER_1K_TOKENS;
|
|
267
|
+
totalSpend += cost;
|
|
268
|
+
agentSpend[entry.agent] = (agentSpend[entry.agent] || 0) + cost;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
this.state.monthlySpend = totalSpend;
|
|
272
|
+
this.state.agentSpend = agentSpend;
|
|
273
|
+
}
|
|
274
|
+
catch { /* ignore */ }
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Trigger a budget alert.
|
|
278
|
+
*/
|
|
279
|
+
triggerAlert(threshold) {
|
|
280
|
+
if (!this.state.triggeredAlerts.includes(threshold)) {
|
|
281
|
+
this.state.triggeredAlerts.push(threshold);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Save budget state to disk.
|
|
286
|
+
*/
|
|
287
|
+
saveState() {
|
|
288
|
+
try {
|
|
289
|
+
const frameworkDir = process.env.ATABEY_FRAMEWORK_DIR || path.join(process.cwd(), ".atabey");
|
|
290
|
+
const finopsDir = path.join(frameworkDir, "finops");
|
|
291
|
+
if (!fs.existsSync(finopsDir)) {
|
|
292
|
+
fs.mkdirSync(finopsDir, { recursive: true });
|
|
293
|
+
}
|
|
294
|
+
const statePath = path.join(finopsDir, "budget-state.json");
|
|
295
|
+
fs.writeFileSync(statePath, JSON.stringify(this.state, null, 2));
|
|
296
|
+
}
|
|
297
|
+
catch { /* ignore */ }
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Reset the singleton instance (for testing).
|
|
301
|
+
*/
|
|
302
|
+
static resetInstance() {
|
|
303
|
+
BudgetManager.instance = undefined;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Load budget state from disk.
|
|
307
|
+
*/
|
|
308
|
+
loadState() {
|
|
309
|
+
try {
|
|
310
|
+
const frameworkDir = process.env.ATABEY_FRAMEWORK_DIR || path.join(process.cwd(), ".atabey");
|
|
311
|
+
const statePath = path.join(frameworkDir, "finops", "budget-state.json");
|
|
312
|
+
if (fs.existsSync(statePath)) {
|
|
313
|
+
const saved = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
314
|
+
// Only load if same period
|
|
315
|
+
if (saved.periodStart === this.state.periodStart) {
|
|
316
|
+
this.state = saved;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch { /* ignore */ }
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
// ─── Singleton Export ─────────────────────────────────────────────
|
|
324
|
+
export const budgetManager = BudgetManager.getInstance();
|
|
325
|
+
export { CONFIG as FinOpsConfig };
|