@netgreener/runtime 0.1.8 → 0.1.10
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/CHANGELOG.md +12 -0
- package/TUTORIAL.md +120 -29
- package/dist/aggregator.d.ts +12 -2
- package/dist/aggregator.js +135 -8
- package/dist/analyze/buildResourceFindings.d.ts +4 -0
- package/dist/analyze/buildResourceFindings.js +17 -0
- package/dist/analyze/cli.d.ts +1 -0
- package/dist/analyze/cli.js +22 -1
- package/dist/analyze/declaredExternalApis.d.ts +31 -0
- package/dist/analyze/declaredExternalApis.js +174 -0
- package/dist/analyze/index.d.ts +1 -0
- package/dist/analyze/index.js +1 -0
- package/dist/auto.d.ts +7 -0
- package/dist/auto.js +8 -0
- package/dist/bullmq.d.ts +2 -2
- package/dist/bullmq.js +28 -58
- package/dist/carbonLedger.d.ts +28 -0
- package/dist/carbonLedger.js +52 -0
- package/dist/cgroupV2.d.ts +44 -0
- package/dist/cgroupV2.js +174 -0
- package/dist/cli/helpText.d.ts +3 -3
- package/dist/cli/helpText.js +42 -35
- package/dist/cli/netgreener.d.ts +7 -7
- package/dist/cli/netgreener.js +23 -16
- package/dist/cli/runCli.d.ts +20 -0
- package/dist/cli/runCli.js +249 -0
- package/dist/cli/runPreload.d.ts +5 -0
- package/dist/cli/runPreload.js +43 -0
- package/dist/collectorMetadata.d.ts +1 -1
- package/dist/collectorMetadata.js +2 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/exporter.d.ts +7 -2
- package/dist/exporter.js +12 -6
- package/dist/express.js +17 -6
- package/dist/externalApiMeter.d.ts +51 -2
- package/dist/externalApiMeter.js +379 -26
- package/dist/fastify.js +17 -6
- package/dist/index.d.ts +12 -2
- package/dist/index.js +11 -1
- package/dist/init.d.ts +30 -0
- package/dist/init.js +31 -0
- package/dist/lifecycle.d.ts +45 -0
- package/dist/lifecycle.js +112 -0
- package/dist/managedCollectorLauncher.d.ts +37 -0
- package/dist/managedCollectorLauncher.js +162 -0
- package/dist/mcpToolMeter.d.ts +101 -0
- package/dist/mcpToolMeter.js +496 -0
- package/dist/n4/deploymentMatrix.d.ts +9 -5
- package/dist/n4/deploymentMatrix.js +13 -9
- package/dist/n4/missingnessInventory.js +3 -3
- package/dist/next.d.ts +89 -0
- package/dist/next.js +328 -0
- package/dist/nextConfig.d.ts +34 -0
- package/dist/nextConfig.js +73 -0
- package/dist/nextEntryTransform.d.ts +9 -0
- package/dist/nextEntryTransform.js +181 -0
- package/dist/occupancyTracker.d.ts +27 -0
- package/dist/occupancyTracker.js +87 -0
- package/dist/optimize/apply.d.ts +38 -0
- package/dist/optimize/apply.js +173 -0
- package/dist/optimize/cli.d.ts +26 -0
- package/dist/optimize/cli.js +323 -0
- package/dist/optimize/index.d.ts +6 -0
- package/dist/optimize/index.js +5 -0
- package/dist/optimize/llmApply.d.ts +22 -0
- package/dist/optimize/llmApply.js +80 -0
- package/dist/optimize/llmSession.d.ts +88 -0
- package/dist/optimize/llmSession.js +135 -0
- package/dist/optimize/provider.d.ts +17 -0
- package/dist/optimize/provider.js +119 -0
- package/dist/optimize/safePatches.d.ts +18 -0
- package/dist/optimize/safePatches.js +247 -0
- package/dist/optimize/types.d.ts +79 -0
- package/dist/optimize/types.js +6 -0
- package/dist/optimize/verification.d.ts +16 -0
- package/dist/optimize/verification.js +165 -0
- package/dist/processResources.d.ts +5 -0
- package/dist/processResources.js +28 -4
- package/dist/processRuntime.js +7 -28
- package/dist/processTree.d.ts +47 -0
- package/dist/processTree.js +148 -0
- package/dist/runContextEnrichment.d.ts +11 -0
- package/dist/runContextEnrichment.js +92 -0
- package/dist/runtime.d.ts +36 -1
- package/dist/runtime.js +140 -17
- package/dist/sdk/client.d.ts +152 -0
- package/dist/sdk/client.js +396 -0
- package/dist/sdk/gitUrl.d.ts +6 -0
- package/dist/sdk/gitUrl.js +87 -0
- package/dist/sdk/index.d.ts +5 -0
- package/dist/sdk/index.js +5 -0
- package/dist/serverlessHints.d.ts +9 -6
- package/dist/serverlessHints.js +10 -7
- package/dist/taskMeter.d.ts +14 -0
- package/dist/taskMeter.js +53 -0
- package/dist/types.d.ts +43 -0
- package/examples/aca-container-gate/Dockerfile +20 -0
- package/examples/aca-container-gate/azure-container-app.yaml +27 -0
- package/examples/aca-container-gate/gate.env +7 -0
- package/examples/aca-container-gate/server.mjs +117 -0
- package/examples/azure-functions-gate/.funcignore +6 -0
- package/examples/azure-functions-gate/README.md +25 -0
- package/examples/azure-functions-gate/host.json +15 -0
- package/examples/azure-functions-gate/package-lock.json +161 -0
- package/examples/azure-functions-gate/package.json +14 -0
- package/examples/azure-functions-gate/src/functions/health.js +27 -0
- package/examples/express-local-live-smoke.mjs +127 -0
- package/examples/extractRunId.mjs +11 -0
- package/examples/next-pilot-dry-run.mjs +32 -0
- package/examples/serverless-thin-gate.mjs +89 -0
- package/fixtures/run-smoke/hello.mjs +4 -0
- package/loaders/next-entry-loader.cjs +14 -0
- package/package.json +25 -2
package/dist/index.d.ts
CHANGED
|
@@ -5,26 +5,36 @@
|
|
|
5
5
|
* N2: outbound fetch meter · N3: BullMQ worker + process/cron runtime
|
|
6
6
|
* Does not modify Python CLI/runtime capability.
|
|
7
7
|
*/
|
|
8
|
-
export type { AllocationReconciliationV0, EvidenceGrades, ExternalApiModelBucket, ExternalApiProvider, ExternalApiTenantBucket, ExternalApiV0, MeasurementProvenance, RunContext, RuntimeSessionMetadata, ServiceRuntimeTenantBucket, ServiceRuntimeUnit, ServiceRuntimeV0, TenantId, } from './types.js';
|
|
8
|
+
export type { AllocationReconciliationV0, AttributionDetailV0, EvidenceGrades, ExternalApiModelBucket, ExternalApiProvider, ExternalApiTenantBucket, ExternalApiV0, MeasurementProvenance, RunContext, RuntimeSessionMetadata, ServiceRuntimeTenantBucket, ServiceRuntimeUnit, ServiceRuntimeV0, TenantId, } from './types.js';
|
|
9
9
|
export { validateExternalApiV0, validateMeasurementProvenance, validateRuntimeSessionMetadata, validateServiceRuntimeV0, type ContractIssue, type ContractResult, } from './contract/index.js';
|
|
10
10
|
export { loadRuntimeConfig, configReady, type RuntimeConfig } from './config.js';
|
|
11
11
|
export { COMPATIBLE_COLLECTOR_METADATA, COLLECTOR_METADATA_NOTES, isCompatibleCollectorMetadata, type CompatibleCollectorMetadata, } from './collectorMetadata.js';
|
|
12
12
|
export { validateObservationEnvelope, classifyObservationDelivery, projectSemanticEnvelopeToProtobufView, validateObservationProtobufView, validateObservationDualView, } from './contract/observation-v1.mjs';
|
|
13
13
|
export { ServiceRuntimeAggregator } from './aggregator.js';
|
|
14
|
-
export {
|
|
14
|
+
export { DEFAULT_GRID_KG_CO2E_PER_KWH, carbonFactorDict, defaultGridFactor, energyKwhToCarbonG, energyKwhToCarbonKg, type CarbonFactor, } from './carbonLedger.js';
|
|
15
|
+
export { beginProcessResourceSample, endProcessResourceSample, currentRssKb, _resetRssSampleCacheForTests, type ProcessResourceMark, type ProcessResourceSample, } from './processResources.js';
|
|
16
|
+
export { CgroupV2Reader, resolveCgroupV2Path, snapshotDelta, type CgroupV2Snapshot, type CgroupV2Provenance, } from './cgroupV2.js';
|
|
17
|
+
export { sampleProcessTree, processTreeAvailability, collectDescendantPids, CPU_SOURCE_PROCESS_TREE, MEMORY_SOURCE_PROCESS_TREE, type ProcessTreeSample, } from './processTree.js';
|
|
18
|
+
export { startManagedCollector, normalizedCollectorMode, childEnvForManagedCollector, reserveTcpEndpoint, type ManagedCollectorHandle, type CollectorMode, } from './managedCollectorLauncher.js';
|
|
19
|
+
export { OccupancyTracker, getOccupancyTracker, type OccupancyWindowSnapshot, } from './occupancyTracker.js';
|
|
15
20
|
export { buildRuntimeHealthV0, mergeHealthIntoMetadata, markHooksActive, type RuntimeHealthV0, type RuntimeHealthStatus, } from './runtimeHealth.js';
|
|
16
21
|
export { newRuntimeWindowId } from './windowId.js';
|
|
17
22
|
export { uploadRunSession, type RunSessionCreatePayload, type UploadResult, } from './uploader.js';
|
|
18
23
|
export { resolveObservationExporter, exportModeFromEnv, DirectRunSessionExporter, ThinRunSessionExporter, CollectorRunSessionExporter, type ExportMode, type ExportResult, type ObservationExporter, type ObservationBatchDocument, } from './exporter.js';
|
|
19
24
|
export { detectServerlessPlatformSignals, flushModeRequestsThin, type ServerlessPlatformHint, type ServerlessPlatformSignal, } from './serverlessHints.js';
|
|
25
|
+
export { resolveLifecycle, isEphemeralLifecycle, type RuntimeModePreference, type RuntimeLifecycle, type RuntimePlatform, type RuntimeCapabilities, type ResolvedRuntimeLifecycle, } from './lifecycle.js';
|
|
26
|
+
export { NetGreener, type NetGreenerInitOptions } from './init.js';
|
|
20
27
|
export { sendCollectorEvent, encodeCollectorFrame, normalizeCollectorEndpoint, type CollectorIpcAck, } from './collectorIpc.js';
|
|
21
28
|
export { NetGreenerRuntime, getRuntime, _resetRuntimeForTests, type FlushKind, type NetGreenerRuntimeOptions, } from './runtime.js';
|
|
22
29
|
export { netgreenerExpressMiddleware, getExpressRuntime, type ExpressRequest, type ExpressResponse, type ExpressNext, } from './express.js';
|
|
23
30
|
export { netgreenerFastifyPlugin, getFastifyRuntime, fastifyRouteTemplate, bindFastifyTenant, type FastifyLike, type FastifyRequestLike, type FastifyReplyLike, } from './fastify.js';
|
|
24
31
|
export { applyNetGreenerNestHooks, detectNestHttpAdapter, getNestRuntime, netgreenerNestExpressMiddleware, netgreenerNestFastifyPlugin, type NestApplicationLike, type NestHttpAdapterKind, } from './nest.js';
|
|
32
|
+
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, observeNextAction, observeNextPage, observeNextRoute, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, type NetGreenerNextOptions, type NextRequestLike, type NextRouteContext, } from './next.js';
|
|
33
|
+
export { withNetGreener, type NextConfigLike } from './nextConfig.js';
|
|
25
34
|
export { attachWindowTenantToRunContext, getTenantContext, loadTenantConfig, normalizeTenantId, resolveTenantFromHttpRequest, resolveTenantFromTaskData, runWithTenantContext, setTenantContext, tenantConfigFromRuntime, type TenantConfig, type TenantContext, } from './tenantContext.js';
|
|
26
35
|
export { ExternalApiAggregator, buildExternalV0, clearExternalAggregator, getExternalAggregator, installOutboundInstrumentation, providerForHost, usageFromClientBody, _resetOutboundInstrumentationForTests, } from './externalApiMeter.js';
|
|
27
36
|
export { attributionServiceUnit, getRequestAttribution, runWithRequestAttribution, } from './requestContext.js';
|
|
37
|
+
export { McpToolBudgetBlocked, activeMcpToolCallId, beginToolCall, budgetMode, buildMcpLatencyV0, buildMcpToolV0, clearMcpToolLedger, finishToolCall, getMcpToolLedger, installMcpClientInstrumentation, recordHttpInToolContext, runWithMcpToolCall, type McpBudgetAction, type McpHttpLinkRow, type McpToolCallRow, type McpToolDecision, } from './mcpToolMeter.js';
|
|
28
38
|
export { getBullMqRuntime, netgreenerBullMqProcessor, runBullMqJobWithNetGreener, type BullMqJobLike, type BullMqProcessorOptions, } from './bullmq.js';
|
|
29
39
|
export { bindProcessTenant, flushProcessRuntime, runWithProcessTenant, startProcessRuntime, type ProcessRuntimeOptions, } from './processRuntime.js';
|
|
30
40
|
export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, buildServiceManifestFromPaths, listCandidateSourceFiles, NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, languageForPath, toResourceFindingCandidate, detectRetryAmplificationHits, detectApiOverconsumptionHits, detectUnboundedParallelismHits, detectPollingIdleHits, detectProcessChurnHits, detectRepeatedWorkHits, detectPerItemInsteadOfBatchHits, detectModelLoadInLoopHits, detectFullDatasetInMemoryHits, detectRepeatedFileReadHits, detectAllHitsAst, detectHotPathHitsAst, detectApiOverconsumptionHitsAst, detectPollingIdleHitsAst, detectProcessChurnHitsAst, detectRepeatedFileReadHitsAst, detectRepeatedWorkHitsAst, detectRetryAmplificationHitsAst, detectUnboundedParallelismHitsAst, detectFullDatasetInMemoryHitsAst, detectPerItemInsteadOfBatchHitsAst, detectModelLoadInLoopHitsAst, collectPreferAstHits, detectApiOverconsumptionHitsPreferAst, detectPollingIdleHitsPreferAst, detectProcessChurnHitsPreferAst, detectRepeatedFileReadHitsPreferAst, detectRepeatedWorkHitsPreferAst, detectRetryAmplificationHitsPreferAst, detectUnboundedParallelismHitsPreferAst, detectFullDatasetInMemoryHitsPreferAst, detectPerItemInsteadOfBatchHitsPreferAst, detectModelLoadInLoopHitsPreferAst, isTypescriptAnalyzeAvailable, tryLoadTypescript, allResourceFindingsValid, filterValidResourceFindings, validateResourceFindingCandidate, countGateFindings, findingsExceedFailThreshold, formatAnalyzeGateFailureMessage, resolveAnalyzeGateLimit, buildAnalyzeGateSummary, buildResourceAnalyzeResultFromPaths, buildResourceFindingsFromSources, type ServiceEndpointUnit, type ServiceFileExtraction, type ServiceManifestV0, type ServiceTaskUnit, type ListCandidateSourceFilesOptions, type AdmissionDecision, type NonResourceCategory, type ResourceDomain, type ResourceCandidateHit, type ResourceFindingCandidateV1, type ResourcePrimaryDomain, type BuildResourceFindingsOptions, type ResourceAnalyzeResultV0, type ResourceFindingValidation, type ResourceFindingValidationError, type AnalyzeGateLimit, type AnalyzeGateSummaryV0, type AstHitBundle, } from './analyze/index.js';
|
package/dist/index.js
CHANGED
|
@@ -10,20 +10,30 @@ export { loadRuntimeConfig, configReady } from './config.js';
|
|
|
10
10
|
export { COMPATIBLE_COLLECTOR_METADATA, COLLECTOR_METADATA_NOTES, isCompatibleCollectorMetadata, } from './collectorMetadata.js';
|
|
11
11
|
export { validateObservationEnvelope, classifyObservationDelivery, projectSemanticEnvelopeToProtobufView, validateObservationProtobufView, validateObservationDualView, } from './contract/observation-v1.mjs';
|
|
12
12
|
export { ServiceRuntimeAggregator } from './aggregator.js';
|
|
13
|
-
export {
|
|
13
|
+
export { DEFAULT_GRID_KG_CO2E_PER_KWH, carbonFactorDict, defaultGridFactor, energyKwhToCarbonG, energyKwhToCarbonKg, } from './carbonLedger.js';
|
|
14
|
+
export { beginProcessResourceSample, endProcessResourceSample, currentRssKb, _resetRssSampleCacheForTests, } from './processResources.js';
|
|
15
|
+
export { CgroupV2Reader, resolveCgroupV2Path, snapshotDelta, } from './cgroupV2.js';
|
|
16
|
+
export { sampleProcessTree, processTreeAvailability, collectDescendantPids, CPU_SOURCE_PROCESS_TREE, MEMORY_SOURCE_PROCESS_TREE, } from './processTree.js';
|
|
17
|
+
export { startManagedCollector, normalizedCollectorMode, childEnvForManagedCollector, reserveTcpEndpoint, } from './managedCollectorLauncher.js';
|
|
18
|
+
export { OccupancyTracker, getOccupancyTracker, } from './occupancyTracker.js';
|
|
14
19
|
export { buildRuntimeHealthV0, mergeHealthIntoMetadata, markHooksActive, } from './runtimeHealth.js';
|
|
15
20
|
export { newRuntimeWindowId } from './windowId.js';
|
|
16
21
|
export { uploadRunSession, } from './uploader.js';
|
|
17
22
|
export { resolveObservationExporter, exportModeFromEnv, DirectRunSessionExporter, ThinRunSessionExporter, CollectorRunSessionExporter, } from './exporter.js';
|
|
18
23
|
export { detectServerlessPlatformSignals, flushModeRequestsThin, } from './serverlessHints.js';
|
|
24
|
+
export { resolveLifecycle, isEphemeralLifecycle, } from './lifecycle.js';
|
|
25
|
+
export { NetGreener } from './init.js';
|
|
19
26
|
export { sendCollectorEvent, encodeCollectorFrame, normalizeCollectorEndpoint, } from './collectorIpc.js';
|
|
20
27
|
export { NetGreenerRuntime, getRuntime, _resetRuntimeForTests, } from './runtime.js';
|
|
21
28
|
export { netgreenerExpressMiddleware, getExpressRuntime, } from './express.js';
|
|
22
29
|
export { netgreenerFastifyPlugin, getFastifyRuntime, fastifyRouteTemplate, bindFastifyTenant, } from './fastify.js';
|
|
23
30
|
export { applyNetGreenerNestHooks, detectNestHttpAdapter, getNestRuntime, netgreenerNestExpressMiddleware, netgreenerNestFastifyPlugin, } from './nest.js';
|
|
31
|
+
export { UNKNOWN_NEXT_ROUTE_TEMPLATE, flushNetGreenerNext, getNextRuntime, nextRouteTemplate, observeNextAction, observeNextPage, observeNextRoute, registerNetGreenerNext, scheduleNetGreenerFlush, withNetGreenerRoute, } from './next.js';
|
|
32
|
+
export { withNetGreener } from './nextConfig.js';
|
|
24
33
|
export { attachWindowTenantToRunContext, getTenantContext, loadTenantConfig, normalizeTenantId, resolveTenantFromHttpRequest, resolveTenantFromTaskData, runWithTenantContext, setTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
|
|
25
34
|
export { ExternalApiAggregator, buildExternalV0, clearExternalAggregator, getExternalAggregator, installOutboundInstrumentation, providerForHost, usageFromClientBody, _resetOutboundInstrumentationForTests, } from './externalApiMeter.js';
|
|
26
35
|
export { attributionServiceUnit, getRequestAttribution, runWithRequestAttribution, } from './requestContext.js';
|
|
36
|
+
export { McpToolBudgetBlocked, activeMcpToolCallId, beginToolCall, budgetMode, buildMcpLatencyV0, buildMcpToolV0, clearMcpToolLedger, finishToolCall, getMcpToolLedger, installMcpClientInstrumentation, recordHttpInToolContext, runWithMcpToolCall, } from './mcpToolMeter.js';
|
|
27
37
|
export { getBullMqRuntime, netgreenerBullMqProcessor, runBullMqJobWithNetGreener, } from './bullmq.js';
|
|
28
38
|
export { bindProcessTenant, flushProcessRuntime, runWithProcessTenant, startProcessRuntime, } from './processRuntime.js';
|
|
29
39
|
export { buildServiceManifest, detectFrameworks, extractServiceUnits, isServiceProject, buildServiceManifestFromPaths, listCandidateSourceFiles, NON_RESOURCE_CATEGORIES, RESOURCE_DOMAINS, admitAnalyzeCandidate, isNonResourceCategory, languageForPath, toResourceFindingCandidate, detectRetryAmplificationHits, detectApiOverconsumptionHits, detectUnboundedParallelismHits, detectPollingIdleHits, detectProcessChurnHits, detectRepeatedWorkHits, detectPerItemInsteadOfBatchHits, detectModelLoadInLoopHits, detectFullDatasetInMemoryHits, detectRepeatedFileReadHits, detectAllHitsAst, detectHotPathHitsAst, detectApiOverconsumptionHitsAst, detectPollingIdleHitsAst, detectProcessChurnHitsAst, detectRepeatedFileReadHitsAst, detectRepeatedWorkHitsAst, detectRetryAmplificationHitsAst, detectUnboundedParallelismHitsAst, detectFullDatasetInMemoryHitsAst, detectPerItemInsteadOfBatchHitsAst, detectModelLoadInLoopHitsAst, collectPreferAstHits, detectApiOverconsumptionHitsPreferAst, detectPollingIdleHitsPreferAst, detectProcessChurnHitsPreferAst, detectRepeatedFileReadHitsPreferAst, detectRepeatedWorkHitsPreferAst, detectRetryAmplificationHitsPreferAst, detectUnboundedParallelismHitsPreferAst, detectFullDatasetInMemoryHitsPreferAst, detectPerItemInsteadOfBatchHitsPreferAst, detectModelLoadInLoopHitsPreferAst, isTypescriptAnalyzeAvailable, tryLoadTypescript, allResourceFindingsValid, filterValidResourceFindings, validateResourceFindingCandidate, countGateFindings, findingsExceedFailThreshold, formatAnalyzeGateFailureMessage, resolveAnalyzeGateLimit, buildAnalyzeGateSummary, buildResourceAnalyzeResultFromPaths, buildResourceFindingsFromSources, } from './analyze/index.js';
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single NetGreener init surface — one product, lifecycle-aware delivery.
|
|
3
|
+
*
|
|
4
|
+
* Prefer ``import '@netgreener/runtime/auto'`` or ``NetGreener.init()``.
|
|
5
|
+
* Does not create a separate Vercel/Lambda product.
|
|
6
|
+
*/
|
|
7
|
+
import { type NetGreenerRuntime, type NetGreenerRuntimeOptions } from './runtime.js';
|
|
8
|
+
import type { UploadResult } from './uploader.js';
|
|
9
|
+
import type { RuntimeModePreference } from './lifecycle.js';
|
|
10
|
+
export type NetGreenerInitOptions = NetGreenerRuntimeOptions & {
|
|
11
|
+
/**
|
|
12
|
+
* Lifecycle preference. Default ``auto`` (serverless signals → ephemeral).
|
|
13
|
+
* Most apps never need to set this.
|
|
14
|
+
*/
|
|
15
|
+
runtime?: RuntimeModePreference;
|
|
16
|
+
};
|
|
17
|
+
export declare const NetGreener: {
|
|
18
|
+
/**
|
|
19
|
+
* Initialize (or return) the process singleton and start metering.
|
|
20
|
+
* Safe to call multiple times — subsequent calls reuse the singleton.
|
|
21
|
+
*/
|
|
22
|
+
init(opts?: NetGreenerInitOptions): NetGreenerRuntime;
|
|
23
|
+
/**
|
|
24
|
+
* Flush at a serverless invoke boundary (Lambda handler finally, etc.).
|
|
25
|
+
* Fail-open: errors are returned, never thrown to the caller by design
|
|
26
|
+
* of ``flush`` (catch returns UploadResult).
|
|
27
|
+
*/
|
|
28
|
+
flushForInvokeEnd(): Promise<UploadResult | null>;
|
|
29
|
+
};
|
|
30
|
+
export default NetGreener;
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single NetGreener init surface — one product, lifecycle-aware delivery.
|
|
3
|
+
*
|
|
4
|
+
* Prefer ``import '@netgreener/runtime/auto'`` or ``NetGreener.init()``.
|
|
5
|
+
* Does not create a separate Vercel/Lambda product.
|
|
6
|
+
*/
|
|
7
|
+
import { getRuntime, } from './runtime.js';
|
|
8
|
+
export const NetGreener = {
|
|
9
|
+
/**
|
|
10
|
+
* Initialize (or return) the process singleton and start metering.
|
|
11
|
+
* Safe to call multiple times — subsequent calls reuse the singleton.
|
|
12
|
+
*/
|
|
13
|
+
init(opts = {}) {
|
|
14
|
+
const { runtime: mode, ...rest } = opts;
|
|
15
|
+
const instance = getRuntime({
|
|
16
|
+
...rest,
|
|
17
|
+
...(mode ? { runtimeMode: mode } : {}),
|
|
18
|
+
});
|
|
19
|
+
instance.start();
|
|
20
|
+
return instance;
|
|
21
|
+
},
|
|
22
|
+
/**
|
|
23
|
+
* Flush at a serverless invoke boundary (Lambda handler finally, etc.).
|
|
24
|
+
* Fail-open: errors are returned, never thrown to the caller by design
|
|
25
|
+
* of ``flush`` (catch returns UploadResult).
|
|
26
|
+
*/
|
|
27
|
+
async flushForInvokeEnd() {
|
|
28
|
+
return getRuntime().flushForInvokeEnd();
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
export default NetGreener;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime lifecycle resolution (persistent vs ephemeral).
|
|
3
|
+
*
|
|
4
|
+
* Platform (vercel / lambda / …) and lifecycle are separate concepts.
|
|
5
|
+
* Behavior depends primarily on lifecycle. Detection is best-effort;
|
|
6
|
+
* ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
|
|
7
|
+
*
|
|
8
|
+
* Does not rewrite the persistent collector pipeline. Ephemeral only
|
|
9
|
+
* changes flush timing and prefers thin export when EXPORT_MODE is unset.
|
|
10
|
+
*/
|
|
11
|
+
import { type ServerlessPlatformSignal } from './serverlessHints.js';
|
|
12
|
+
export type RuntimeModePreference = 'auto' | 'persistent' | 'ephemeral';
|
|
13
|
+
export type RuntimeLifecycle = 'persistent' | 'ephemeral';
|
|
14
|
+
export type RuntimePlatform = ServerlessPlatformSignal | 'docker' | 'kubernetes' | 'generic';
|
|
15
|
+
export type RuntimeCapabilities = {
|
|
16
|
+
/** Host CPU sampling (cgroup / host meters). Not claimed on serverless. */
|
|
17
|
+
cpu_sampling: boolean;
|
|
18
|
+
gpu_sampling: boolean;
|
|
19
|
+
/** process.cpuUsage / RSS deltas on instrumented hooks. */
|
|
20
|
+
process_cpu_time: boolean;
|
|
21
|
+
periodic_flush: boolean;
|
|
22
|
+
local_durable_spool: boolean;
|
|
23
|
+
};
|
|
24
|
+
export type ResolvedRuntimeLifecycle = {
|
|
25
|
+
/** Requested preference (auto / override). */
|
|
26
|
+
mode: RuntimeModePreference;
|
|
27
|
+
lifecycle: RuntimeLifecycle;
|
|
28
|
+
platform: RuntimePlatform;
|
|
29
|
+
capabilities: RuntimeCapabilities;
|
|
30
|
+
signals: ServerlessPlatformSignal[];
|
|
31
|
+
notes: string[];
|
|
32
|
+
};
|
|
33
|
+
export type ResolveLifecycleOptions = {
|
|
34
|
+
mode?: RuntimeModePreference;
|
|
35
|
+
env?: NodeJS.ProcessEnv;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Resolve lifecycle + platform metadata.
|
|
39
|
+
*
|
|
40
|
+
* Default ``auto``: serverless host signals → ephemeral; otherwise persistent.
|
|
41
|
+
* Docker / Kubernetes signals alone stay **persistent**.
|
|
42
|
+
*/
|
|
43
|
+
export declare function resolveLifecycle(opts?: ResolveLifecycleOptions): ResolvedRuntimeLifecycle;
|
|
44
|
+
/** True when resolved lifecycle is ephemeral. */
|
|
45
|
+
export declare function isEphemeralLifecycle(opts?: ResolveLifecycleOptions): boolean;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime lifecycle resolution (persistent vs ephemeral).
|
|
3
|
+
*
|
|
4
|
+
* Platform (vercel / lambda / …) and lifecycle are separate concepts.
|
|
5
|
+
* Behavior depends primarily on lifecycle. Detection is best-effort;
|
|
6
|
+
* ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
|
|
7
|
+
*
|
|
8
|
+
* Does not rewrite the persistent collector pipeline. Ephemeral only
|
|
9
|
+
* changes flush timing and prefers thin export when EXPORT_MODE is unset.
|
|
10
|
+
*/
|
|
11
|
+
import { detectServerlessPlatformSignals, } from './serverlessHints.js';
|
|
12
|
+
function readModePreference(env, override) {
|
|
13
|
+
if (override === 'auto' || override === 'persistent' || override === 'ephemeral') {
|
|
14
|
+
return override;
|
|
15
|
+
}
|
|
16
|
+
const raw = String(env.NETGREENER_RUNTIME || '')
|
|
17
|
+
.trim()
|
|
18
|
+
.toLowerCase();
|
|
19
|
+
if (raw === 'persistent' || raw === 'ephemeral' || raw === 'auto') {
|
|
20
|
+
return raw;
|
|
21
|
+
}
|
|
22
|
+
return 'auto';
|
|
23
|
+
}
|
|
24
|
+
function detectContainerPlatform(env) {
|
|
25
|
+
if (present(env, 'KUBERNETES_SERVICE_HOST'))
|
|
26
|
+
return 'kubernetes';
|
|
27
|
+
// Azure Container Apps — long-lived revision process (not serverless thin).
|
|
28
|
+
if (present(env, 'CONTAINER_APP_NAME') || present(env, 'CONTAINER_APP_REVISION')) {
|
|
29
|
+
return 'docker';
|
|
30
|
+
}
|
|
31
|
+
// Generic container signal — never means serverless by itself.
|
|
32
|
+
if (env.DOTNET_RUNNING_IN_CONTAINER === 'true' || present(env, 'container')) {
|
|
33
|
+
return 'docker';
|
|
34
|
+
}
|
|
35
|
+
if (present(env, 'DOCKER') || env.container === 'docker')
|
|
36
|
+
return 'docker';
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
function present(env, key) {
|
|
40
|
+
return Boolean(String(env[key] || '').trim());
|
|
41
|
+
}
|
|
42
|
+
function capabilitiesFor(lifecycle) {
|
|
43
|
+
if (lifecycle === 'ephemeral') {
|
|
44
|
+
return {
|
|
45
|
+
cpu_sampling: false,
|
|
46
|
+
gpu_sampling: false,
|
|
47
|
+
process_cpu_time: true,
|
|
48
|
+
periodic_flush: false,
|
|
49
|
+
local_durable_spool: false,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
cpu_sampling: false, // host/cgroup still not claimed by default
|
|
54
|
+
gpu_sampling: false,
|
|
55
|
+
process_cpu_time: true,
|
|
56
|
+
periodic_flush: true,
|
|
57
|
+
local_durable_spool: true, // available via opt-in collector; not forced
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Resolve lifecycle + platform metadata.
|
|
62
|
+
*
|
|
63
|
+
* Default ``auto``: serverless host signals → ephemeral; otherwise persistent.
|
|
64
|
+
* Docker / Kubernetes signals alone stay **persistent**.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveLifecycle(opts = {}) {
|
|
67
|
+
const env = opts.env ?? process.env;
|
|
68
|
+
const mode = readModePreference(env, opts.mode);
|
|
69
|
+
const hint = detectServerlessPlatformSignals(env);
|
|
70
|
+
const containerPlatform = detectContainerPlatform(env);
|
|
71
|
+
const notes = [];
|
|
72
|
+
let lifecycle;
|
|
73
|
+
if (mode === 'ephemeral') {
|
|
74
|
+
lifecycle = 'ephemeral';
|
|
75
|
+
notes.push('runtime mode override: ephemeral');
|
|
76
|
+
}
|
|
77
|
+
else if (mode === 'persistent') {
|
|
78
|
+
lifecycle = 'persistent';
|
|
79
|
+
notes.push('runtime mode override: persistent');
|
|
80
|
+
}
|
|
81
|
+
else if (hint.detected) {
|
|
82
|
+
lifecycle = 'ephemeral';
|
|
83
|
+
notes.push('auto: serverless host signal → ephemeral lifecycle (invoke-end flush; no periodic timer)');
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
lifecycle = 'persistent';
|
|
87
|
+
notes.push('auto: no serverless signal → persistent lifecycle');
|
|
88
|
+
}
|
|
89
|
+
let platform = 'generic';
|
|
90
|
+
if (hint.signals.length > 0) {
|
|
91
|
+
platform = hint.signals[0];
|
|
92
|
+
}
|
|
93
|
+
else if (containerPlatform) {
|
|
94
|
+
platform = containerPlatform;
|
|
95
|
+
notes.push(`container/platform signal: ${containerPlatform} (lifecycle remains ${lifecycle})`);
|
|
96
|
+
}
|
|
97
|
+
if (lifecycle === 'ephemeral') {
|
|
98
|
+
notes.push('ephemeral: prefer NETGREENER_EXPORT_MODE=thin when unset; flush at invoke/request idle boundary');
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
mode,
|
|
102
|
+
lifecycle,
|
|
103
|
+
platform,
|
|
104
|
+
capabilities: capabilitiesFor(lifecycle),
|
|
105
|
+
signals: hint.signals,
|
|
106
|
+
notes,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** True when resolved lifecycle is ephemeral. */
|
|
110
|
+
export function isEphemeralLifecycle(opts = {}) {
|
|
111
|
+
return resolveLifecycle(opts).lifecycle === 'ephemeral';
|
|
112
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in managed sibling collector launcher (Python ``process_launcher`` twin).
|
|
3
|
+
*
|
|
4
|
+
* When ``NETGREENER_COLLECTOR_MODE=managed``:
|
|
5
|
+
* 1. Start ``python -m netgreener.collector_server``
|
|
6
|
+
* 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
|
|
7
|
+
* 3. On child exit: terminate collector (drain)
|
|
8
|
+
*
|
|
9
|
+
* Does **not** flip the package default (unset mode → direct).
|
|
10
|
+
* Windows: ``tcp://`` only.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn, type ChildProcess } from 'node:child_process';
|
|
13
|
+
export type CollectorMode = 'managed' | 'direct' | null;
|
|
14
|
+
export declare function normalizedCollectorMode(env?: NodeJS.ProcessEnv): CollectorMode;
|
|
15
|
+
export declare function reserveTcpEndpoint(): Promise<string>;
|
|
16
|
+
export type ManagedCollectorHandle = {
|
|
17
|
+
endpoint: string;
|
|
18
|
+
spoolDir: string;
|
|
19
|
+
process: ChildProcess;
|
|
20
|
+
stop: () => Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
export type StartManagedCollectorOptions = {
|
|
23
|
+
env?: NodeJS.ProcessEnv;
|
|
24
|
+
pythonCommand?: string;
|
|
25
|
+
/** Injected spawn for tests. */
|
|
26
|
+
spawnImpl?: typeof spawn;
|
|
27
|
+
/** Skip readiness wait (tests). */
|
|
28
|
+
skipReadyWait?: boolean;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Start managed collector if mode is managed; otherwise return null.
|
|
32
|
+
*/
|
|
33
|
+
export declare function startManagedCollector(opts?: StartManagedCollectorOptions): Promise<ManagedCollectorHandle | null>;
|
|
34
|
+
/** Env overlay for a Node child that should export via the managed collector. */
|
|
35
|
+
export declare function childEnvForManagedCollector(base: NodeJS.ProcessEnv, endpoint: string, opts?: {
|
|
36
|
+
keepCredentials?: boolean;
|
|
37
|
+
}): NodeJS.ProcessEnv;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in managed sibling collector launcher (Python ``process_launcher`` twin).
|
|
3
|
+
*
|
|
4
|
+
* When ``NETGREENER_COLLECTOR_MODE=managed``:
|
|
5
|
+
* 1. Start ``python -m netgreener.collector_server``
|
|
6
|
+
* 2. Point child at ``NETGREENER_EXPORT_MODE=collector`` + endpoint
|
|
7
|
+
* 3. On child exit: terminate collector (drain)
|
|
8
|
+
*
|
|
9
|
+
* Does **not** flip the package default (unset mode → direct).
|
|
10
|
+
* Windows: ``tcp://`` only.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { createServer, Socket } from 'node:net';
|
|
14
|
+
import { homedir, tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
export function normalizedCollectorMode(env = process.env) {
|
|
17
|
+
const raw = String(env.NETGREENER_COLLECTOR_MODE || '')
|
|
18
|
+
.trim()
|
|
19
|
+
.toLowerCase();
|
|
20
|
+
if (!raw)
|
|
21
|
+
return null;
|
|
22
|
+
if (raw === 'off' || raw === 'disabled' || raw === 'legacy')
|
|
23
|
+
return 'direct';
|
|
24
|
+
if (raw === 'managed' || raw === 'direct')
|
|
25
|
+
return raw;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
export async function reserveTcpEndpoint() {
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
const server = createServer();
|
|
31
|
+
server.listen(0, '127.0.0.1', () => {
|
|
32
|
+
const addr = server.address();
|
|
33
|
+
if (!addr || typeof addr === 'string') {
|
|
34
|
+
server.close();
|
|
35
|
+
reject(new Error('failed to reserve TCP port'));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const endpoint = `tcp://127.0.0.1:${addr.port}`;
|
|
39
|
+
server.close(() => resolve(endpoint));
|
|
40
|
+
});
|
|
41
|
+
server.on('error', reject);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async function waitForTcp(endpoint, child, timeoutMs = 5000) {
|
|
45
|
+
const m = /^tcp:\/\/([^:]+):(\d+)$/i.exec(endpoint.trim());
|
|
46
|
+
if (!m)
|
|
47
|
+
return;
|
|
48
|
+
const host = m[1];
|
|
49
|
+
const port = Number(m[2]);
|
|
50
|
+
const deadline = Date.now() + timeoutMs;
|
|
51
|
+
while (Date.now() < deadline) {
|
|
52
|
+
if (child.exitCode != null) {
|
|
53
|
+
throw new Error('NetGreener collector exited during startup');
|
|
54
|
+
}
|
|
55
|
+
const ok = await new Promise((resolve) => {
|
|
56
|
+
const sock = new Socket();
|
|
57
|
+
sock.setTimeout(100);
|
|
58
|
+
sock.once('connect', () => {
|
|
59
|
+
sock.destroy();
|
|
60
|
+
resolve(true);
|
|
61
|
+
});
|
|
62
|
+
sock.once('error', () => {
|
|
63
|
+
sock.destroy();
|
|
64
|
+
resolve(false);
|
|
65
|
+
});
|
|
66
|
+
sock.once('timeout', () => {
|
|
67
|
+
sock.destroy();
|
|
68
|
+
resolve(false);
|
|
69
|
+
});
|
|
70
|
+
sock.connect(port, host);
|
|
71
|
+
});
|
|
72
|
+
if (ok)
|
|
73
|
+
return;
|
|
74
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
75
|
+
}
|
|
76
|
+
throw new Error('NetGreener collector did not become ready within 5 seconds');
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Start managed collector if mode is managed; otherwise return null.
|
|
80
|
+
*/
|
|
81
|
+
export async function startManagedCollector(opts = {}) {
|
|
82
|
+
const env = { ...(opts.env ?? process.env) };
|
|
83
|
+
if (normalizedCollectorMode(env) !== 'managed')
|
|
84
|
+
return null;
|
|
85
|
+
let endpoint = String(env.NETGREENER_COLLECTOR_ENDPOINT || '').trim();
|
|
86
|
+
if (!endpoint) {
|
|
87
|
+
endpoint = await reserveTcpEndpoint();
|
|
88
|
+
}
|
|
89
|
+
if (endpoint.startsWith('unix:') && process.platform === 'win32') {
|
|
90
|
+
throw new Error('Windows managed collector requires tcp:// endpoint');
|
|
91
|
+
}
|
|
92
|
+
const spoolDir = String(env.NETGREENER_SPOOL_DIR || '').trim() ||
|
|
93
|
+
join(homedir() || tmpdir(), '.netgreener', 'collector');
|
|
94
|
+
const python = opts.pythonCommand || process.env.NETGREENER_PYTHON || 'python';
|
|
95
|
+
const spawnImpl = opts.spawnImpl ?? spawn;
|
|
96
|
+
const collectorEnv = {
|
|
97
|
+
...env,
|
|
98
|
+
NETGREENER_RUNTIME_COLLECTOR: '1',
|
|
99
|
+
NETGREENER_COLLECTOR_ENDPOINT: endpoint,
|
|
100
|
+
NETGREENER_SPOOL_DIR: spoolDir,
|
|
101
|
+
};
|
|
102
|
+
const child = spawnImpl(python, [
|
|
103
|
+
'-m',
|
|
104
|
+
'netgreener.collector_server',
|
|
105
|
+
'--endpoint',
|
|
106
|
+
endpoint,
|
|
107
|
+
'--spool-dir',
|
|
108
|
+
spoolDir,
|
|
109
|
+
], {
|
|
110
|
+
env: collectorEnv,
|
|
111
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
112
|
+
windowsHide: true,
|
|
113
|
+
});
|
|
114
|
+
if (!opts.skipReadyWait) {
|
|
115
|
+
try {
|
|
116
|
+
await waitForTcp(endpoint, child);
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
child.kill('SIGTERM');
|
|
120
|
+
throw err;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const drainSec = Number(env.NETGREENER_COLLECTOR_DRAIN_SECONDS || '10');
|
|
124
|
+
const drainMs = Number.isFinite(drainSec) && drainSec > 0 ? drainSec * 1000 : 10_000;
|
|
125
|
+
return {
|
|
126
|
+
endpoint,
|
|
127
|
+
spoolDir,
|
|
128
|
+
process: child,
|
|
129
|
+
stop: async () => {
|
|
130
|
+
if (child.exitCode != null)
|
|
131
|
+
return;
|
|
132
|
+
child.kill('SIGTERM');
|
|
133
|
+
await new Promise((resolve) => {
|
|
134
|
+
const t = setTimeout(() => {
|
|
135
|
+
if (child.exitCode == null)
|
|
136
|
+
child.kill('SIGKILL');
|
|
137
|
+
resolve();
|
|
138
|
+
}, drainMs);
|
|
139
|
+
child.once('exit', () => {
|
|
140
|
+
clearTimeout(t);
|
|
141
|
+
resolve();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
/** Env overlay for a Node child that should export via the managed collector. */
|
|
148
|
+
export function childEnvForManagedCollector(base, endpoint, opts) {
|
|
149
|
+
const out = {
|
|
150
|
+
...base,
|
|
151
|
+
NETGREENER_EXPORT_MODE: 'collector',
|
|
152
|
+
NETGREENER_COLLECTOR_ENDPOINT: endpoint,
|
|
153
|
+
NETGREENER_COLLECTOR_MODE: 'managed',
|
|
154
|
+
};
|
|
155
|
+
const keep = opts?.keepCredentials ||
|
|
156
|
+
String(base.NETGREENER_WORKER_KEEP_CREDENTIALS || '').trim() === '1';
|
|
157
|
+
if (!keep) {
|
|
158
|
+
delete out.NETGREENER_TOKEN;
|
|
159
|
+
delete out.NETGREENER_SERVICE_TOKEN;
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-process MCP tool observation for the Node runtime.
|
|
3
|
+
*
|
|
4
|
+
* Matches the Python week-1 counter and week-2 duration rows. The active
|
|
5
|
+
* tool-call id lives in AsyncLocalStorage. A fetch that starts while that id
|
|
6
|
+
* is set records a link. The link is not written onto external_api_v0.
|
|
7
|
+
*
|
|
8
|
+
* The counter is this process only. Warn is the default. Block is opt-in and
|
|
9
|
+
* does not invoke the tool. A configured estimate is not added to API cost.
|
|
10
|
+
* The official TypeScript MCP client is not patched. Calls are recorded only
|
|
11
|
+
* when this process calls beginToolCall. A missing client hook is not monitoring.
|
|
12
|
+
*
|
|
13
|
+
* Raw tool arguments, results, and HTTP bodies are not stored.
|
|
14
|
+
*/
|
|
15
|
+
export declare class McpToolBudgetBlocked extends Error {
|
|
16
|
+
constructor(message: string);
|
|
17
|
+
}
|
|
18
|
+
export type McpBudgetAction = 'allow' | 'warn' | 'block';
|
|
19
|
+
export type McpToolCallRow = {
|
|
20
|
+
server: string;
|
|
21
|
+
tool: string;
|
|
22
|
+
started_at: string;
|
|
23
|
+
duration_ms: number;
|
|
24
|
+
success: boolean;
|
|
25
|
+
attempt: number;
|
|
26
|
+
budget_action: McpBudgetAction;
|
|
27
|
+
invoked: boolean;
|
|
28
|
+
call_id: string;
|
|
29
|
+
execution_id?: string;
|
|
30
|
+
tenant_id?: string;
|
|
31
|
+
estimated_usd?: number;
|
|
32
|
+
estimate_label?: 'configured';
|
|
33
|
+
budget_reason?: string;
|
|
34
|
+
};
|
|
35
|
+
export type McpHttpLinkRow = {
|
|
36
|
+
tool_call_id: string;
|
|
37
|
+
host: string;
|
|
38
|
+
duration_ms: number;
|
|
39
|
+
error: boolean;
|
|
40
|
+
};
|
|
41
|
+
export type McpToolDecision = {
|
|
42
|
+
callId: string;
|
|
43
|
+
server: string;
|
|
44
|
+
tool: string;
|
|
45
|
+
attempt: number;
|
|
46
|
+
action: McpBudgetAction;
|
|
47
|
+
reason: string | null;
|
|
48
|
+
};
|
|
49
|
+
export declare function budgetMode(): 'warn' | 'block';
|
|
50
|
+
export declare function activeMcpToolCallId(): string | null;
|
|
51
|
+
export declare function runWithMcpToolCall<T>(callId: string, fn: () => T): T;
|
|
52
|
+
export declare class McpToolLedger {
|
|
53
|
+
private calls;
|
|
54
|
+
private httpLinks;
|
|
55
|
+
private dropped;
|
|
56
|
+
private budgetTotals;
|
|
57
|
+
private budgetPairs;
|
|
58
|
+
hasCalls(): boolean;
|
|
59
|
+
beginToolCall(server: string, tool: string): McpToolDecision;
|
|
60
|
+
finishToolCall(decision: McpToolDecision, opts: {
|
|
61
|
+
success: boolean;
|
|
62
|
+
durationMs: number;
|
|
63
|
+
startedAt?: string;
|
|
64
|
+
}): void;
|
|
65
|
+
recordHttpLink(row: {
|
|
66
|
+
toolCallId: string;
|
|
67
|
+
host: string;
|
|
68
|
+
durationMs: number;
|
|
69
|
+
error: boolean;
|
|
70
|
+
}): void;
|
|
71
|
+
takeSnapshot(): McpToolLedger;
|
|
72
|
+
mergeSnapshot(snapshot: McpToolLedger): void;
|
|
73
|
+
buildV0(): Record<string, unknown> | null;
|
|
74
|
+
clear(): void;
|
|
75
|
+
private append;
|
|
76
|
+
}
|
|
77
|
+
export declare function getMcpToolLedger(): McpToolLedger;
|
|
78
|
+
export declare function beginToolCall(server: string, tool: string): McpToolDecision;
|
|
79
|
+
export declare function finishToolCall(decision: McpToolDecision, opts: {
|
|
80
|
+
success: boolean;
|
|
81
|
+
durationMs: number;
|
|
82
|
+
startedAt?: string;
|
|
83
|
+
}): void;
|
|
84
|
+
export declare function recordHttpInToolContext(row: {
|
|
85
|
+
toolCallId: string | null;
|
|
86
|
+
host: string;
|
|
87
|
+
durationMs: number;
|
|
88
|
+
error: boolean;
|
|
89
|
+
}): void;
|
|
90
|
+
export declare function buildMcpToolV0(): Record<string, unknown> | null;
|
|
91
|
+
export declare function httpDurationMs(externalV0: Record<string, unknown> | null | undefined): number;
|
|
92
|
+
export declare function mcpDurationMs(mcpV0: Record<string, unknown> | null | undefined, failedOnly?: boolean): number;
|
|
93
|
+
export declare function buildMcpLatencyV0(mcpV0: Record<string, unknown> | null | undefined, externalV0: Record<string, unknown> | null | undefined, wallSeconds: number | null): Record<string, unknown> | null;
|
|
94
|
+
export declare function clearMcpToolLedger(): void;
|
|
95
|
+
/**
|
|
96
|
+
* Official MCP client patching stays off until one SDK version is installed
|
|
97
|
+
* and its callTool signature is tested. A command basename is not a server name.
|
|
98
|
+
* This returns false so a caller cannot treat the hook as active.
|
|
99
|
+
*/
|
|
100
|
+
export declare function installMcpClientInstrumentation(): boolean;
|
|
101
|
+
export declare function _resetMcpToolMeterForTests(): void;
|