@phuetz/code-buddy 0.1.13 → 0.1.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/README.md +228 -13
- package/dist/agent/architect-mode.d.ts +11 -0
- package/dist/agent/architect-mode.js +133 -25
- package/dist/agent/architect-mode.js.map +1 -1
- package/dist/agent/codebuddy-agent.d.ts +24 -0
- package/dist/agent/codebuddy-agent.js +118 -16
- package/dist/agent/codebuddy-agent.js.map +1 -1
- package/dist/agent/execution/agent-executor.d.ts +9 -0
- package/dist/agent/execution/agent-executor.js +61 -0
- package/dist/agent/execution/agent-executor.js.map +1 -1
- package/dist/agent/message-queue.d.ts +77 -0
- package/dist/agent/message-queue.js +116 -0
- package/dist/agent/message-queue.js.map +1 -0
- package/dist/agent/middleware/auto-observation.d.ts +37 -0
- package/dist/agent/middleware/auto-observation.js +231 -0
- package/dist/agent/middleware/auto-observation.js.map +1 -0
- package/dist/agent/middleware/index.d.ts +2 -0
- package/dist/agent/middleware/index.js +1 -0
- package/dist/agent/middleware/index.js.map +1 -1
- package/dist/agent/tool-handler.js +3 -2
- package/dist/agent/tool-handler.js.map +1 -1
- package/dist/agent/types.d.ts +7 -2
- package/dist/analytics/budget-alerts.d.ts +81 -0
- package/dist/analytics/budget-alerts.js +126 -0
- package/dist/analytics/budget-alerts.js.map +1 -0
- package/dist/analytics/cost-predictor.d.ts +79 -0
- package/dist/analytics/cost-predictor.js +150 -0
- package/dist/analytics/cost-predictor.js.map +1 -0
- package/dist/analytics/index.d.ts +2 -0
- package/dist/analytics/index.js +2 -0
- package/dist/analytics/index.js.map +1 -1
- package/dist/auth/profile-manager.d.ts +205 -0
- package/dist/auth/profile-manager.js +484 -0
- package/dist/auth/profile-manager.js.map +1 -0
- package/dist/browser-automation/browser-manager.d.ts +79 -1
- package/dist/browser-automation/browser-manager.js +265 -2
- package/dist/browser-automation/browser-manager.js.map +1 -1
- package/dist/browser-automation/profile-manager.d.ts +32 -0
- package/dist/browser-automation/profile-manager.js +83 -0
- package/dist/browser-automation/profile-manager.js.map +1 -0
- package/dist/browser-automation/route-interceptor.d.ts +29 -0
- package/dist/browser-automation/route-interceptor.js +103 -0
- package/dist/browser-automation/route-interceptor.js.map +1 -0
- package/dist/browser-automation/screenshot-annotator.d.ts +23 -0
- package/dist/browser-automation/screenshot-annotator.js +86 -0
- package/dist/browser-automation/screenshot-annotator.js.map +1 -0
- package/dist/browser-automation/types.d.ts +47 -0
- package/dist/channels/discord/client.d.ts +2 -1
- package/dist/channels/discord/client.js +28 -16
- package/dist/channels/discord/client.js.map +1 -1
- package/dist/channels/google-chat/index.d.ts +210 -0
- package/dist/channels/google-chat/index.js +505 -0
- package/dist/channels/google-chat/index.js.map +1 -0
- package/dist/channels/group-security.d.ts +182 -0
- package/dist/channels/group-security.js +407 -0
- package/dist/channels/group-security.js.map +1 -0
- package/dist/channels/index.d.ts +17 -1
- package/dist/channels/index.js +16 -0
- package/dist/channels/index.js.map +1 -1
- package/dist/channels/matrix/index.d.ts +181 -0
- package/dist/channels/matrix/index.js +643 -0
- package/dist/channels/matrix/index.js.map +1 -0
- package/dist/channels/offline-queue.d.ts +92 -0
- package/dist/channels/offline-queue.js +112 -0
- package/dist/channels/offline-queue.js.map +1 -0
- package/dist/channels/reconnection-manager.d.ts +117 -0
- package/dist/channels/reconnection-manager.js +171 -0
- package/dist/channels/reconnection-manager.js.map +1 -0
- package/dist/channels/signal/index.d.ts +184 -0
- package/dist/channels/signal/index.js +488 -0
- package/dist/channels/signal/index.js.map +1 -0
- package/dist/channels/slack/client.d.ts +2 -1
- package/dist/channels/slack/client.js +30 -20
- package/dist/channels/slack/client.js.map +1 -1
- package/dist/channels/teams/index.d.ts +196 -0
- package/dist/channels/teams/index.js +477 -0
- package/dist/channels/teams/index.js.map +1 -0
- package/dist/channels/telegram/client.d.ts +3 -1
- package/dist/channels/telegram/client.js +29 -2
- package/dist/channels/telegram/client.js.map +1 -1
- package/dist/channels/webchat/index.d.ts +103 -0
- package/dist/channels/webchat/index.js +697 -0
- package/dist/channels/webchat/index.js.map +1 -0
- package/dist/channels/whatsapp/index.d.ts +105 -0
- package/dist/channels/whatsapp/index.js +533 -0
- package/dist/channels/whatsapp/index.js.map +1 -0
- package/dist/codebuddy/client.js +6 -3
- package/dist/codebuddy/client.js.map +1 -1
- package/dist/codebuddy/tool-definitions/advanced-tools.d.ts +1 -0
- package/dist/codebuddy/tool-definitions/advanced-tools.js +103 -3
- package/dist/codebuddy/tool-definitions/advanced-tools.js.map +1 -1
- package/dist/codebuddy/tool-definitions/index.d.ts +1 -1
- package/dist/codebuddy/tool-definitions/index.js +1 -1
- package/dist/codebuddy/tool-definitions/index.js.map +1 -1
- package/dist/codebuddy/tools.js +3 -1
- package/dist/codebuddy/tools.js.map +1 -1
- package/dist/commands/cli/config-command.d.ts +8 -0
- package/dist/commands/cli/config-command.js +90 -0
- package/dist/commands/cli/config-command.js.map +1 -0
- package/dist/commands/cli/openclaw-commands.d.ts +12 -0
- package/dist/commands/cli/openclaw-commands.js +446 -0
- package/dist/commands/cli/openclaw-commands.js.map +1 -0
- package/dist/commands/cli/utility-commands.js +30 -0
- package/dist/commands/cli/utility-commands.js.map +1 -1
- package/dist/commands/client-dispatcher.js +22 -2
- package/dist/commands/client-dispatcher.js.map +1 -1
- package/dist/commands/enhanced-command-handler.js +21 -2
- package/dist/commands/enhanced-command-handler.js.map +1 -1
- package/dist/commands/handlers/extra-handlers.d.ts +30 -0
- package/dist/commands/handlers/extra-handlers.js +547 -0
- package/dist/commands/handlers/extra-handlers.js.map +1 -0
- package/dist/commands/handlers/index.d.ts +1 -0
- package/dist/commands/handlers/index.js +2 -0
- package/dist/commands/handlers/index.js.map +1 -1
- package/dist/commands/slash/builtin-commands.js +41 -34
- package/dist/commands/slash/builtin-commands.js.map +1 -1
- package/dist/config/env-schema.d.ts +58 -0
- package/dist/config/env-schema.js +789 -0
- package/dist/config/env-schema.js.map +1 -0
- package/dist/config/feature-flags.js +2 -1
- package/dist/config/feature-flags.js.map +1 -1
- package/dist/context/bootstrap-loader.d.ts +48 -0
- package/dist/context/bootstrap-loader.js +123 -0
- package/dist/context/bootstrap-loader.js.map +1 -0
- package/dist/copilot/copilot-proxy.d.ts +15 -1
- package/dist/copilot/copilot-proxy.js +81 -22
- package/dist/copilot/copilot-proxy.js.map +1 -1
- package/dist/daemon/heartbeat.d.ts +112 -0
- package/dist/daemon/heartbeat.js +339 -0
- package/dist/daemon/heartbeat.js.map +1 -0
- package/dist/desktop-automation/smart-snapshot.d.ts +11 -0
- package/dist/desktop-automation/smart-snapshot.js +28 -0
- package/dist/desktop-automation/smart-snapshot.js.map +1 -1
- package/dist/identity/identity-manager.d.ts +95 -0
- package/dist/identity/identity-manager.js +242 -0
- package/dist/identity/identity-manager.js.map +1 -0
- package/dist/index.js +147 -17
- package/dist/index.js.map +1 -1
- package/dist/integrations/github-integration.js +1 -1
- package/dist/integrations/github-integration.js.map +1 -1
- package/dist/persistence/conversation-branches.js +2 -1
- package/dist/persistence/conversation-branches.js.map +1 -1
- package/dist/persistence/session-store.d.ts +1 -1
- package/dist/persistence/session-store.js +1 -1
- package/dist/persistence/session-store.js.map +1 -1
- package/dist/sandbox/auto-sandbox.d.ts +59 -0
- package/dist/sandbox/auto-sandbox.js +145 -0
- package/dist/sandbox/auto-sandbox.js.map +1 -0
- package/dist/security/audit-logger.d.ts +127 -0
- package/dist/security/audit-logger.js +194 -0
- package/dist/security/audit-logger.js.map +1 -0
- package/dist/security/bash-allowlist/allowlist-store.js +3 -2
- package/dist/security/bash-allowlist/allowlist-store.js.map +1 -1
- package/dist/security/bash-parser.js +0 -2
- package/dist/security/bash-parser.js.map +1 -1
- package/dist/security/code-validator.d.ts +51 -0
- package/dist/security/code-validator.js +185 -0
- package/dist/security/code-validator.js.map +1 -0
- package/dist/security/dangerous-patterns.d.ts +68 -0
- package/dist/security/dangerous-patterns.js +218 -0
- package/dist/security/dangerous-patterns.js.map +1 -0
- package/dist/security/remote-approval.d.ts +65 -0
- package/dist/security/remote-approval.js +138 -0
- package/dist/security/remote-approval.js.map +1 -0
- package/dist/security/security-audit.d.ts +7 -0
- package/dist/security/security-audit.js +23 -0
- package/dist/security/security-audit.js.map +1 -1
- package/dist/security/syntax-validator.d.ts +17 -0
- package/dist/security/syntax-validator.js +292 -0
- package/dist/security/syntax-validator.js.map +1 -0
- package/dist/server/index.js +277 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/prompt-builder.js +16 -0
- package/dist/services/prompt-builder.js.map +1 -1
- package/dist/skills/hub.d.ts +231 -0
- package/dist/skills/hub.js +694 -0
- package/dist/skills/hub.js.map +1 -0
- package/dist/skills/skill-loader.js +1 -1
- package/dist/skills/skill-loader.js.map +1 -1
- package/dist/skills/skill-manager.js +2 -1
- package/dist/skills/skill-manager.js.map +1 -1
- package/dist/tools/apply-patch.d.ts +1 -0
- package/dist/tools/apply-patch.js +57 -10
- package/dist/tools/apply-patch.js.map +1 -1
- package/dist/tools/bash/bash-tool.d.ts +123 -0
- package/dist/tools/bash/bash-tool.js +549 -0
- package/dist/tools/bash/bash-tool.js.map +1 -0
- package/dist/tools/bash/command-validator.d.ts +49 -0
- package/dist/tools/bash/command-validator.js +223 -0
- package/dist/tools/bash/command-validator.js.map +1 -0
- package/dist/tools/bash/index.d.ts +7 -0
- package/dist/tools/bash/index.js +8 -0
- package/dist/tools/bash/index.js.map +1 -0
- package/dist/tools/bash/security-patterns.d.ts +44 -0
- package/dist/tools/bash/security-patterns.js +234 -0
- package/dist/tools/bash/security-patterns.js.map +1 -0
- package/dist/tools/bash/streaming-executor.d.ts +23 -0
- package/dist/tools/bash/streaming-executor.js +134 -0
- package/dist/tools/bash/streaming-executor.js.map +1 -0
- package/dist/tools/code-formatter.js +41 -27
- package/dist/tools/code-formatter.js.map +1 -1
- package/dist/tools/code-review.js +1 -1
- package/dist/tools/code-review.js.map +1 -1
- package/dist/tools/computer-control-tool.js +21 -0
- package/dist/tools/computer-control-tool.js.map +1 -1
- package/dist/tools/document-tool.js +3 -2
- package/dist/tools/document-tool.js.map +1 -1
- package/dist/tools/git-tool.d.ts +45 -0
- package/dist/tools/git-tool.js +222 -0
- package/dist/tools/git-tool.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/multi-edit.js +31 -3
- package/dist/tools/multi-edit.js.map +1 -1
- package/dist/tools/process-tool.d.ts +69 -0
- package/dist/tools/process-tool.js +222 -0
- package/dist/tools/process-tool.js.map +1 -0
- package/dist/tools/registry/git-tools.d.ts +32 -0
- package/dist/tools/registry/git-tools.js +211 -0
- package/dist/tools/registry/git-tools.js.map +1 -0
- package/dist/tools/registry/index.d.ts +2 -0
- package/dist/tools/registry/index.js +8 -0
- package/dist/tools/registry/index.js.map +1 -1
- package/dist/tools/registry/misc-tools.d.ts +32 -4
- package/dist/tools/registry/misc-tools.js +230 -90
- package/dist/tools/registry/misc-tools.js.map +1 -1
- package/dist/tools/registry/process-tools.d.ts +20 -0
- package/dist/tools/registry/process-tools.js +141 -0
- package/dist/tools/registry/process-tools.js.map +1 -0
- package/dist/tools/registry/types.d.ts +2 -0
- package/dist/ui/components/ChatInterface.js +9 -0
- package/dist/ui/components/ChatInterface.js.map +1 -1
- package/dist/utils/autonomy-manager.js +3 -2
- package/dist/utils/autonomy-manager.js.map +1 -1
- package/dist/utils/config-validation/schema.d.ts +15 -15
- package/dist/utils/confirmation-service.d.ts +16 -0
- package/dist/utils/confirmation-service.js +37 -3
- package/dist/utils/confirmation-service.js.map +1 -1
- package/dist/utils/custom-instructions.js +2 -1
- package/dist/utils/custom-instructions.js.map +1 -1
- package/dist/utils/graceful-shutdown.js +9 -9
- package/dist/utils/graceful-shutdown.js.map +1 -1
- package/dist/utils/head-tail-truncation.d.ts +18 -0
- package/dist/utils/head-tail-truncation.js +127 -0
- package/dist/utils/head-tail-truncation.js.map +1 -1
- package/dist/utils/history-manager.js +3 -2
- package/dist/utils/history-manager.js.map +1 -1
- package/dist/utils/performance.js +16 -15
- package/dist/utils/performance.js.map +1 -1
- package/dist/utils/update-notifier.js +2 -1
- package/dist/utils/update-notifier.js.map +1 -1
- package/dist/workflows/pipeline.d.ts +54 -1
- package/dist/workflows/pipeline.js +128 -7
- package/dist/workflows/pipeline.js.map +1 -1
- package/dist/workflows/step-manager.js +2 -1
- package/dist/workflows/step-manager.js.map +1 -1
- package/package.json +6 -3
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget Alert Manager
|
|
3
|
+
*
|
|
4
|
+
* Monitors session and budget costs, emitting alerts when
|
|
5
|
+
* spending approaches or exceeds configured thresholds.
|
|
6
|
+
*
|
|
7
|
+
* Default thresholds:
|
|
8
|
+
* - Warning at 70% of budget
|
|
9
|
+
* - Critical at 90% of budget
|
|
10
|
+
* - Limit reached at 100%
|
|
11
|
+
*
|
|
12
|
+
* @module analytics
|
|
13
|
+
*/
|
|
14
|
+
import { EventEmitter } from 'events';
|
|
15
|
+
const DEFAULT_CONFIG = {
|
|
16
|
+
warningThreshold: 0.7,
|
|
17
|
+
criticalThreshold: 0.9,
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Budget Alert Manager
|
|
21
|
+
*
|
|
22
|
+
* Tracks spending against a budget limit and emits alerts
|
|
23
|
+
* when thresholds are crossed. Alerts are deduplicated so
|
|
24
|
+
* the same threshold level is only emitted once per session
|
|
25
|
+
* (until reset).
|
|
26
|
+
*
|
|
27
|
+
* Events:
|
|
28
|
+
* - 'alert' - Emitted with a BudgetAlert when a threshold is crossed
|
|
29
|
+
*/
|
|
30
|
+
export class BudgetAlertManager extends EventEmitter {
|
|
31
|
+
config;
|
|
32
|
+
alerts = [];
|
|
33
|
+
emittedTypes = new Set();
|
|
34
|
+
constructor(config) {
|
|
35
|
+
super();
|
|
36
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Check current cost against limits and return an alert if a threshold is crossed.
|
|
40
|
+
*
|
|
41
|
+
* Alerts are deduplicated: once an alert of a given type has been emitted,
|
|
42
|
+
* it will not be emitted again until `reset()` is called.
|
|
43
|
+
*
|
|
44
|
+
* @param currentCost - Current accumulated cost in USD
|
|
45
|
+
* @param limit - Budget limit in USD
|
|
46
|
+
* @returns A BudgetAlert if a threshold was crossed, or null
|
|
47
|
+
*/
|
|
48
|
+
check(currentCost, limit) {
|
|
49
|
+
if (limit <= 0) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
const percentage = (currentCost / limit) * 100;
|
|
53
|
+
// Check from most severe to least severe
|
|
54
|
+
if (currentCost >= limit && !this.emittedTypes.has('limit_reached')) {
|
|
55
|
+
const alert = {
|
|
56
|
+
type: 'limit_reached',
|
|
57
|
+
message: `Budget limit reached! Spent $${currentCost.toFixed(4)} of $${limit.toFixed(2)} budget (${percentage.toFixed(1)}%).`,
|
|
58
|
+
currentCost,
|
|
59
|
+
limit,
|
|
60
|
+
percentage,
|
|
61
|
+
};
|
|
62
|
+
this.recordAlert(alert);
|
|
63
|
+
return alert;
|
|
64
|
+
}
|
|
65
|
+
if (currentCost >= limit * this.config.criticalThreshold &&
|
|
66
|
+
!this.emittedTypes.has('critical')) {
|
|
67
|
+
const alert = {
|
|
68
|
+
type: 'critical',
|
|
69
|
+
message: `Critical: Approaching budget limit! Spent $${currentCost.toFixed(4)} of $${limit.toFixed(2)} budget (${percentage.toFixed(1)}%).`,
|
|
70
|
+
currentCost,
|
|
71
|
+
limit,
|
|
72
|
+
percentage,
|
|
73
|
+
};
|
|
74
|
+
this.recordAlert(alert);
|
|
75
|
+
return alert;
|
|
76
|
+
}
|
|
77
|
+
if (currentCost >= limit * this.config.warningThreshold &&
|
|
78
|
+
!this.emittedTypes.has('warning')) {
|
|
79
|
+
const alert = {
|
|
80
|
+
type: 'warning',
|
|
81
|
+
message: `Warning: Budget usage at ${percentage.toFixed(1)}%. Spent $${currentCost.toFixed(4)} of $${limit.toFixed(2)} budget.`,
|
|
82
|
+
currentCost,
|
|
83
|
+
limit,
|
|
84
|
+
percentage,
|
|
85
|
+
};
|
|
86
|
+
this.recordAlert(alert);
|
|
87
|
+
return alert;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Get the history of all alerts emitted in this session.
|
|
93
|
+
*/
|
|
94
|
+
getAlerts() {
|
|
95
|
+
return [...this.alerts];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Reset all alert state, clearing history and deduplication tracking.
|
|
99
|
+
* This allows alerts to fire again for the same thresholds.
|
|
100
|
+
*/
|
|
101
|
+
reset() {
|
|
102
|
+
this.alerts = [];
|
|
103
|
+
this.emittedTypes.clear();
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Get the current configuration.
|
|
107
|
+
*/
|
|
108
|
+
getConfig() {
|
|
109
|
+
return { ...this.config };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Update configuration thresholds.
|
|
113
|
+
*/
|
|
114
|
+
updateConfig(config) {
|
|
115
|
+
this.config = { ...this.config, ...config };
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Record an alert and emit the 'alert' event.
|
|
119
|
+
*/
|
|
120
|
+
recordAlert(alert) {
|
|
121
|
+
this.alerts.push(alert);
|
|
122
|
+
this.emittedTypes.add(alert.type);
|
|
123
|
+
this.emit('alert', alert);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
//# sourceMappingURL=budget-alerts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget-alerts.js","sourceRoot":"","sources":["../../src/analytics/budget-alerts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAsBtC,MAAM,cAAc,GAAsB;IACxC,gBAAgB,EAAE,GAAG;IACr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,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;CACF"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost Predictor
|
|
3
|
+
*
|
|
4
|
+
* Estimates the cost of a request BEFORE execution based on:
|
|
5
|
+
* - Input token count from messages
|
|
6
|
+
* - Historical average output tokens (from CostTracker stats)
|
|
7
|
+
* - Model-specific pricing
|
|
8
|
+
*
|
|
9
|
+
* @module analytics
|
|
10
|
+
*/
|
|
11
|
+
import type { CostTracker } from '../utils/cost-tracker.js';
|
|
12
|
+
export interface CostPrediction {
|
|
13
|
+
/** Estimated number of input tokens */
|
|
14
|
+
estimatedInputTokens: number;
|
|
15
|
+
/** Estimated number of output tokens */
|
|
16
|
+
estimatedOutputTokens: number;
|
|
17
|
+
/** Estimated cost in USD */
|
|
18
|
+
estimatedCost: number;
|
|
19
|
+
/** Model used for the prediction */
|
|
20
|
+
model: string;
|
|
21
|
+
/** Confidence level of the prediction */
|
|
22
|
+
confidence: 'low' | 'medium' | 'high';
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Cost Predictor - Estimates request cost before execution
|
|
26
|
+
*/
|
|
27
|
+
export declare class CostPredictor {
|
|
28
|
+
private costTracker;
|
|
29
|
+
constructor(costTracker: CostTracker);
|
|
30
|
+
/**
|
|
31
|
+
* Estimate cost based on message history length and model.
|
|
32
|
+
*
|
|
33
|
+
* @param messages - The messages array to be sent to the LLM
|
|
34
|
+
* @param model - The model identifier
|
|
35
|
+
* @returns A cost prediction with estimated tokens, cost, and confidence
|
|
36
|
+
*/
|
|
37
|
+
predict(messages: Array<{
|
|
38
|
+
role: string;
|
|
39
|
+
content: string;
|
|
40
|
+
}>, model: string): CostPrediction;
|
|
41
|
+
/**
|
|
42
|
+
* Get average cost per request from recorded history.
|
|
43
|
+
*
|
|
44
|
+
* @returns Average cost in USD, or 0 if no history exists
|
|
45
|
+
*/
|
|
46
|
+
getAverageCostPerRequest(): number;
|
|
47
|
+
/**
|
|
48
|
+
* Get cost trend based on recent usage history.
|
|
49
|
+
*
|
|
50
|
+
* Compares the average cost of the first half of recent usage
|
|
51
|
+
* to the second half. A >20% change in either direction is
|
|
52
|
+
* considered increasing or decreasing.
|
|
53
|
+
*
|
|
54
|
+
* @returns 'increasing', 'decreasing', or 'stable'
|
|
55
|
+
*/
|
|
56
|
+
getCostTrend(): 'increasing' | 'decreasing' | 'stable';
|
|
57
|
+
/**
|
|
58
|
+
* Estimate input token count from messages.
|
|
59
|
+
*
|
|
60
|
+
* Uses a character-based heuristic (approximately 4 characters per token)
|
|
61
|
+
* as a fast approximation without requiring tiktoken.
|
|
62
|
+
*/
|
|
63
|
+
private estimateInputTokens;
|
|
64
|
+
/**
|
|
65
|
+
* Estimate output tokens based on historical average.
|
|
66
|
+
*
|
|
67
|
+
* If the cost tracker has recorded usage, uses the average
|
|
68
|
+
* output token count. Otherwise falls back to a default estimate.
|
|
69
|
+
*/
|
|
70
|
+
private estimateOutputTokens;
|
|
71
|
+
/**
|
|
72
|
+
* Determine prediction confidence based on available data.
|
|
73
|
+
*
|
|
74
|
+
* - high: 5+ recent usage entries (good historical data)
|
|
75
|
+
* - medium: 1-4 recent entries (some data)
|
|
76
|
+
* - low: no recent usage (pure estimation)
|
|
77
|
+
*/
|
|
78
|
+
private determineConfidence;
|
|
79
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost Predictor
|
|
3
|
+
*
|
|
4
|
+
* Estimates the cost of a request BEFORE execution based on:
|
|
5
|
+
* - Input token count from messages
|
|
6
|
+
* - Historical average output tokens (from CostTracker stats)
|
|
7
|
+
* - Model-specific pricing
|
|
8
|
+
*
|
|
9
|
+
* @module analytics
|
|
10
|
+
*/
|
|
11
|
+
// Model pricing lookup (mirrors cost-tracker.ts)
|
|
12
|
+
const MODEL_PRICING = {
|
|
13
|
+
'grok-3-latest': { inputPer1k: 0.005, outputPer1k: 0.015 },
|
|
14
|
+
'grok-3-fast': { inputPer1k: 0.003, outputPer1k: 0.009 },
|
|
15
|
+
'grok-code-fast-1': { inputPer1k: 0.002, outputPer1k: 0.006 },
|
|
16
|
+
'grok-2-latest': { inputPer1k: 0.002, outputPer1k: 0.010 },
|
|
17
|
+
'default': { inputPer1k: 0.003, outputPer1k: 0.010 },
|
|
18
|
+
};
|
|
19
|
+
/** Average characters per token (rough heuristic) */
|
|
20
|
+
const CHARS_PER_TOKEN = 4;
|
|
21
|
+
/** Default output token estimate when no history is available */
|
|
22
|
+
const DEFAULT_OUTPUT_TOKENS = 500;
|
|
23
|
+
/**
|
|
24
|
+
* Cost Predictor - Estimates request cost before execution
|
|
25
|
+
*/
|
|
26
|
+
export class CostPredictor {
|
|
27
|
+
costTracker;
|
|
28
|
+
constructor(costTracker) {
|
|
29
|
+
this.costTracker = costTracker;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Estimate cost based on message history length and model.
|
|
33
|
+
*
|
|
34
|
+
* @param messages - The messages array to be sent to the LLM
|
|
35
|
+
* @param model - The model identifier
|
|
36
|
+
* @returns A cost prediction with estimated tokens, cost, and confidence
|
|
37
|
+
*/
|
|
38
|
+
predict(messages, model) {
|
|
39
|
+
const estimatedInputTokens = this.estimateInputTokens(messages);
|
|
40
|
+
const estimatedOutputTokens = this.estimateOutputTokens();
|
|
41
|
+
const pricing = MODEL_PRICING[model] || MODEL_PRICING['default'];
|
|
42
|
+
const estimatedCost = (estimatedInputTokens / 1000) * pricing.inputPer1k +
|
|
43
|
+
(estimatedOutputTokens / 1000) * pricing.outputPer1k;
|
|
44
|
+
const confidence = this.determineConfidence(messages);
|
|
45
|
+
return {
|
|
46
|
+
estimatedInputTokens,
|
|
47
|
+
estimatedOutputTokens,
|
|
48
|
+
estimatedCost,
|
|
49
|
+
model,
|
|
50
|
+
confidence,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Get average cost per request from recorded history.
|
|
55
|
+
*
|
|
56
|
+
* @returns Average cost in USD, or 0 if no history exists
|
|
57
|
+
*/
|
|
58
|
+
getAverageCostPerRequest() {
|
|
59
|
+
const report = this.costTracker.getReport();
|
|
60
|
+
const recentUsage = report.recentUsage;
|
|
61
|
+
if (recentUsage.length === 0) {
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
const totalCost = recentUsage.reduce((sum, u) => sum + u.cost, 0);
|
|
65
|
+
return totalCost / recentUsage.length;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Get cost trend based on recent usage history.
|
|
69
|
+
*
|
|
70
|
+
* Compares the average cost of the first half of recent usage
|
|
71
|
+
* to the second half. A >20% change in either direction is
|
|
72
|
+
* considered increasing or decreasing.
|
|
73
|
+
*
|
|
74
|
+
* @returns 'increasing', 'decreasing', or 'stable'
|
|
75
|
+
*/
|
|
76
|
+
getCostTrend() {
|
|
77
|
+
const report = this.costTracker.getReport();
|
|
78
|
+
const recentUsage = report.recentUsage;
|
|
79
|
+
if (recentUsage.length < 4) {
|
|
80
|
+
return 'stable';
|
|
81
|
+
}
|
|
82
|
+
const midpoint = Math.floor(recentUsage.length / 2);
|
|
83
|
+
const firstHalf = recentUsage.slice(0, midpoint);
|
|
84
|
+
const secondHalf = recentUsage.slice(midpoint);
|
|
85
|
+
const firstAvg = firstHalf.reduce((sum, u) => sum + u.cost, 0) / firstHalf.length;
|
|
86
|
+
const secondAvg = secondHalf.reduce((sum, u) => sum + u.cost, 0) / secondHalf.length;
|
|
87
|
+
if (firstAvg === 0) {
|
|
88
|
+
return secondAvg > 0 ? 'increasing' : 'stable';
|
|
89
|
+
}
|
|
90
|
+
const changeRatio = (secondAvg - firstAvg) / firstAvg;
|
|
91
|
+
if (changeRatio > 0.2) {
|
|
92
|
+
return 'increasing';
|
|
93
|
+
}
|
|
94
|
+
else if (changeRatio < -0.2) {
|
|
95
|
+
return 'decreasing';
|
|
96
|
+
}
|
|
97
|
+
return 'stable';
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Estimate input token count from messages.
|
|
101
|
+
*
|
|
102
|
+
* Uses a character-based heuristic (approximately 4 characters per token)
|
|
103
|
+
* as a fast approximation without requiring tiktoken.
|
|
104
|
+
*/
|
|
105
|
+
estimateInputTokens(messages) {
|
|
106
|
+
let totalChars = 0;
|
|
107
|
+
for (const message of messages) {
|
|
108
|
+
// Account for role overhead (~4 tokens per message for role + framing)
|
|
109
|
+
totalChars += 16;
|
|
110
|
+
if (message.content) {
|
|
111
|
+
totalChars += message.content.length;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return Math.ceil(totalChars / CHARS_PER_TOKEN);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Estimate output tokens based on historical average.
|
|
118
|
+
*
|
|
119
|
+
* If the cost tracker has recorded usage, uses the average
|
|
120
|
+
* output token count. Otherwise falls back to a default estimate.
|
|
121
|
+
*/
|
|
122
|
+
estimateOutputTokens() {
|
|
123
|
+
const report = this.costTracker.getReport();
|
|
124
|
+
const recentUsage = report.recentUsage;
|
|
125
|
+
if (recentUsage.length === 0) {
|
|
126
|
+
return DEFAULT_OUTPUT_TOKENS;
|
|
127
|
+
}
|
|
128
|
+
const totalOutputTokens = recentUsage.reduce((sum, u) => sum + u.outputTokens, 0);
|
|
129
|
+
return Math.ceil(totalOutputTokens / recentUsage.length);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Determine prediction confidence based on available data.
|
|
133
|
+
*
|
|
134
|
+
* - high: 5+ recent usage entries (good historical data)
|
|
135
|
+
* - medium: 1-4 recent entries (some data)
|
|
136
|
+
* - low: no recent usage (pure estimation)
|
|
137
|
+
*/
|
|
138
|
+
determineConfidence(messages) {
|
|
139
|
+
const report = this.costTracker.getReport();
|
|
140
|
+
const recentCount = report.recentUsage.length;
|
|
141
|
+
if (recentCount >= 5) {
|
|
142
|
+
return 'high';
|
|
143
|
+
}
|
|
144
|
+
else if (recentCount >= 1) {
|
|
145
|
+
return 'medium';
|
|
146
|
+
}
|
|
147
|
+
return 'low';
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=cost-predictor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost-predictor.js","sourceRoot":"","sources":["../../src/analytics/cost-predictor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAiBH,iDAAiD;AACjD,MAAM,aAAa,GAAiC;IAClD,eAAe,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;IAC1D,aAAa,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;IACxD,kBAAkB,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;IAC7D,eAAe,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;IAC1D,SAAS,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE;CACrD,CAAC;AAEF,qDAAqD;AACrD,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B,iEAAiE;AACjE,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC;;GAEG;AACH,MAAM,OAAO,aAAa;IAChB,WAAW,CAAc;IAEjC,YAAY,WAAwB;QAClC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED;;;;;;OAMG;IACH,OAAO,CACL,QAAkD,EAClD,KAAa;QAEb,MAAM,oBAAoB,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAChE,MAAM,qBAAqB,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC1D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B;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC;QAC5C,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;QAEvC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC7B,OAAO,qBAAqB,CAAC;QAC/B,CAAC;QAED,MAAM,iBAAiB,GAAG,WAAW,CAAC,MAAM,CAC1C,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,YAAY,EAChC,CAAC,CACF,CAAC;QACF,OAAO,IAAI,CAAC,IAAI,CAAC,iBAAiB,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;IAC3D,CAAC;IAED;;;;;;OAMG;IACK,mBAAmB,CACzB,QAAkD;QAElD,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC;QAC5C,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;QAE9C,IAAI,WAAW,IAAI,CAAC,EAAE,CAAC;YACrB,OAAO,MAAM,CAAC;QAChB,CAAC;aAAM,IAAI,WAAW,IAAI,CAAC,EAAE,CAAC;YAC5B,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF"}
|
|
@@ -14,3 +14,5 @@
|
|
|
14
14
|
export { PersistentAnalytics, CostBudget, UsageEvent, AnalyticsSummary, CostAlert, getPersistentAnalytics, resetPersistentAnalytics, } from './persistent-analytics.js';
|
|
15
15
|
export { MetricsDashboard, getMetricsDashboard, resetMetricsDashboard, type DashboardMetrics, type TokenMetrics, type CostMetrics, type ToolMetrics, type SessionMetrics, type PerformanceMetrics, } from './metrics-dashboard.js';
|
|
16
16
|
export { ToolAnalytics, getToolAnalytics, resetToolAnalytics, type ToolExecution, type ToolStats, type ToolChain, type ToolSuggestion, type ToolAnalyticsSnapshot, } from './tool-analytics.js';
|
|
17
|
+
export { CostPredictor, type CostPrediction, } from './cost-predictor.js';
|
|
18
|
+
export { BudgetAlertManager, type BudgetAlert, type BudgetAlertConfig, } from './budget-alerts.js';
|
package/dist/analytics/index.js
CHANGED
|
@@ -14,4 +14,6 @@
|
|
|
14
14
|
export { PersistentAnalytics, getPersistentAnalytics, resetPersistentAnalytics, } from './persistent-analytics.js';
|
|
15
15
|
export { MetricsDashboard, getMetricsDashboard, resetMetricsDashboard, } from './metrics-dashboard.js';
|
|
16
16
|
export { ToolAnalytics, getToolAnalytics, resetToolAnalytics, } from './tool-analytics.js';
|
|
17
|
+
export { CostPredictor, } from './cost-predictor.js';
|
|
18
|
+
export { BudgetAlertManager, } from './budget-alerts.js';
|
|
17
19
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/analytics/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,mBAAmB,EAKnB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,GAOtB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,kBAAkB,GAMnB,MAAM,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/analytics/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,mBAAmB,EAKnB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,qBAAqB,GAOtB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,kBAAkB,GAMnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,aAAa,GAEd,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,kBAAkB,GAGnB,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth Profile Manager
|
|
3
|
+
*
|
|
4
|
+
* OpenClaw-inspired profile manager with round-robin rotation and
|
|
5
|
+
* session stickiness. Manages authentication profiles across multiple
|
|
6
|
+
* providers with exponential backoff cooldowns, billing-aware failure
|
|
7
|
+
* handling, and persistent state.
|
|
8
|
+
*/
|
|
9
|
+
import { EventEmitter } from 'events';
|
|
10
|
+
/**
|
|
11
|
+
* Authentication profile credentials
|
|
12
|
+
*/
|
|
13
|
+
export interface AuthProfileCredentials {
|
|
14
|
+
/** API key for api-key auth */
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
/** OAuth access token */
|
|
17
|
+
accessToken?: string;
|
|
18
|
+
/** OAuth refresh token */
|
|
19
|
+
refreshToken?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Authentication profile metadata
|
|
23
|
+
*/
|
|
24
|
+
export interface AuthProfileMetadata {
|
|
25
|
+
/** Model to use with this profile */
|
|
26
|
+
model?: string;
|
|
27
|
+
/** Base URL override */
|
|
28
|
+
baseURL?: string;
|
|
29
|
+
/** Additional metadata */
|
|
30
|
+
[key: string]: string | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Authentication profile
|
|
34
|
+
*/
|
|
35
|
+
export interface AuthProfile {
|
|
36
|
+
/** Unique profile ID */
|
|
37
|
+
id: string;
|
|
38
|
+
/** Provider name (e.g. 'grok', 'openai', 'anthropic') */
|
|
39
|
+
provider: string;
|
|
40
|
+
/** Authentication type */
|
|
41
|
+
type: 'api-key' | 'oauth';
|
|
42
|
+
/** Credentials */
|
|
43
|
+
credentials: AuthProfileCredentials;
|
|
44
|
+
/** Priority (higher = preferred) */
|
|
45
|
+
priority: number;
|
|
46
|
+
/** Profile metadata */
|
|
47
|
+
metadata: AuthProfileMetadata;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Rotation strategy for profile selection
|
|
51
|
+
*/
|
|
52
|
+
export type RotationStrategy = 'round-robin' | 'priority' | 'random';
|
|
53
|
+
/**
|
|
54
|
+
* Auth Profile Manager configuration
|
|
55
|
+
*/
|
|
56
|
+
export interface AuthProfileManagerConfig {
|
|
57
|
+
/** Profiles to manage */
|
|
58
|
+
profiles: AuthProfile[];
|
|
59
|
+
/** Strategy for selecting next profile */
|
|
60
|
+
rotationStrategy: RotationStrategy;
|
|
61
|
+
/** Stick with a profile once selected for a session */
|
|
62
|
+
sessionSticky: boolean;
|
|
63
|
+
/** Base cooldown duration in ms after failure */
|
|
64
|
+
cooldownMs: number;
|
|
65
|
+
/** Cooldown duration for billing failures (5 hours) */
|
|
66
|
+
billingCooldownMs: number;
|
|
67
|
+
/** Maximum cooldown cap (24 hours) */
|
|
68
|
+
maxCooldownMs: number;
|
|
69
|
+
/** Path to persist state */
|
|
70
|
+
persistPath: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Default configuration
|
|
74
|
+
*/
|
|
75
|
+
export declare const DEFAULT_AUTH_PROFILE_MANAGER_CONFIG: AuthProfileManagerConfig;
|
|
76
|
+
/**
|
|
77
|
+
* Auth Profile Manager
|
|
78
|
+
*
|
|
79
|
+
* Manages authentication profiles with round-robin rotation, session
|
|
80
|
+
* stickiness, and exponential backoff cooldowns. Supports billing-aware
|
|
81
|
+
* failure handling with separate escalation.
|
|
82
|
+
*
|
|
83
|
+
* Events:
|
|
84
|
+
* - `profile:selected` - Emitted when a profile is selected (profileId, sessionId?)
|
|
85
|
+
* - `profile:failed` - Emitted when a profile fails (profileId, error)
|
|
86
|
+
* - `profile:cooldown` - Emitted when a profile enters cooldown (profileId, cooldownMs)
|
|
87
|
+
* - `profile:recovered` - Emitted when a profile exits cooldown (profileId)
|
|
88
|
+
*/
|
|
89
|
+
export declare class AuthProfileManager extends EventEmitter {
|
|
90
|
+
private config;
|
|
91
|
+
private profiles;
|
|
92
|
+
private cooldownStates;
|
|
93
|
+
private sessionBindings;
|
|
94
|
+
private roundRobinIndex;
|
|
95
|
+
private recoveryTimers;
|
|
96
|
+
constructor(config?: Partial<AuthProfileManagerConfig>);
|
|
97
|
+
/**
|
|
98
|
+
* Add a profile
|
|
99
|
+
*/
|
|
100
|
+
addProfile(profile: AuthProfile): void;
|
|
101
|
+
/**
|
|
102
|
+
* Remove a profile
|
|
103
|
+
*/
|
|
104
|
+
removeProfile(profileId: string): boolean;
|
|
105
|
+
/**
|
|
106
|
+
* Get a profile by ID
|
|
107
|
+
*/
|
|
108
|
+
getProfile(profileId: string): AuthProfile | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Get all registered profiles
|
|
111
|
+
*/
|
|
112
|
+
getAllProfiles(): AuthProfile[];
|
|
113
|
+
/**
|
|
114
|
+
* Get the next available profile, optionally sticky to a session.
|
|
115
|
+
*
|
|
116
|
+
* If sessionSticky is enabled and a session already has a bound profile
|
|
117
|
+
* that is healthy, that profile is returned. Otherwise a new profile is
|
|
118
|
+
* selected using the configured rotation strategy.
|
|
119
|
+
*/
|
|
120
|
+
getNextProfile(sessionId?: string): AuthProfile | null;
|
|
121
|
+
/**
|
|
122
|
+
* Get the sticky profile for a session (without selecting a new one)
|
|
123
|
+
*/
|
|
124
|
+
getProfileForSession(sessionId: string): AuthProfile | null;
|
|
125
|
+
/**
|
|
126
|
+
* Get all profiles not currently in cooldown
|
|
127
|
+
*/
|
|
128
|
+
getHealthyProfiles(): AuthProfile[];
|
|
129
|
+
/**
|
|
130
|
+
* Mark a profile as failed with exponential backoff cooldown.
|
|
131
|
+
*
|
|
132
|
+
* Normal failures: 1min -> 5min -> 25min -> 1h (max)
|
|
133
|
+
* Billing failures: 5h -> 10h -> 20h -> 24h (max)
|
|
134
|
+
*
|
|
135
|
+
* The backoff multiplier is 5x for normal and 2x for billing.
|
|
136
|
+
*/
|
|
137
|
+
markFailed(profileId: string, error: string, isBilling?: boolean): void;
|
|
138
|
+
/**
|
|
139
|
+
* Mark a profile as successful, resetting its failure count
|
|
140
|
+
*/
|
|
141
|
+
markSuccess(profileId: string): void;
|
|
142
|
+
/**
|
|
143
|
+
* Release a session's sticky profile binding
|
|
144
|
+
*/
|
|
145
|
+
releaseSession(sessionId: string): void;
|
|
146
|
+
/**
|
|
147
|
+
* Round-robin selection across healthy profiles
|
|
148
|
+
*/
|
|
149
|
+
private selectRoundRobin;
|
|
150
|
+
/**
|
|
151
|
+
* Priority-based selection (highest priority first)
|
|
152
|
+
*/
|
|
153
|
+
private selectByPriority;
|
|
154
|
+
/**
|
|
155
|
+
* Random selection
|
|
156
|
+
*/
|
|
157
|
+
private selectRandom;
|
|
158
|
+
/**
|
|
159
|
+
* Check if a profile is currently in cooldown
|
|
160
|
+
*/
|
|
161
|
+
private isInCooldown;
|
|
162
|
+
/**
|
|
163
|
+
* Recover a profile from cooldown
|
|
164
|
+
*/
|
|
165
|
+
private recoverProfile;
|
|
166
|
+
/**
|
|
167
|
+
* Schedule automatic recovery after cooldown expires
|
|
168
|
+
*/
|
|
169
|
+
private scheduleRecovery;
|
|
170
|
+
/**
|
|
171
|
+
* Save cooldown states to disk
|
|
172
|
+
*/
|
|
173
|
+
private saveState;
|
|
174
|
+
/**
|
|
175
|
+
* Load cooldown states from disk
|
|
176
|
+
*/
|
|
177
|
+
private loadState;
|
|
178
|
+
/**
|
|
179
|
+
* Get status of all profiles
|
|
180
|
+
*/
|
|
181
|
+
getStatus(): Array<{
|
|
182
|
+
profileId: string;
|
|
183
|
+
provider: string;
|
|
184
|
+
type: 'api-key' | 'oauth';
|
|
185
|
+
priority: number;
|
|
186
|
+
healthy: boolean;
|
|
187
|
+
failureCount: number;
|
|
188
|
+
inCooldown: boolean;
|
|
189
|
+
cooldownRemainingMs: number;
|
|
190
|
+
lastError?: string;
|
|
191
|
+
}>;
|
|
192
|
+
/**
|
|
193
|
+
* Shutdown - clear all timers
|
|
194
|
+
*/
|
|
195
|
+
shutdown(): void;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Get the auth profile manager singleton
|
|
199
|
+
*/
|
|
200
|
+
export declare function getAuthProfileManager(config?: Partial<AuthProfileManagerConfig>): AuthProfileManager;
|
|
201
|
+
/**
|
|
202
|
+
* Reset the auth profile manager singleton
|
|
203
|
+
*/
|
|
204
|
+
export declare function resetAuthProfileManager(): void;
|
|
205
|
+
export default AuthProfileManager;
|