@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
|
@@ -0,0 +1,496 @@
|
|
|
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
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
16
|
+
import { randomUUID } from 'node:crypto';
|
|
17
|
+
import { connect } from 'node:net';
|
|
18
|
+
import { sendCollectorEvent } from './collectorIpc.js';
|
|
19
|
+
import { getTenantContext } from './tenantContext.js';
|
|
20
|
+
const MAX_STORED = 200;
|
|
21
|
+
const NOTES = [
|
|
22
|
+
'Budget is in-process only. Another process, worker, or machine does not share it.',
|
|
23
|
+
'This counter covers the whole Node process. It is not a per-job budget.',
|
|
24
|
+
'A high call count is not an anomaly and is not waste.',
|
|
25
|
+
'stdio transport is not an HTTP call. HTTP made inside a tool stays in external_api_v0.',
|
|
26
|
+
'A configured estimate is not a provider bill and is not added to API cost or CPU time.',
|
|
27
|
+
];
|
|
28
|
+
const CANNOT_SAY = [
|
|
29
|
+
'Which API made a tool slow.',
|
|
30
|
+
'Which wait was the Celery queue.',
|
|
31
|
+
'Which retry slept. Failed-call time is not backoff.',
|
|
32
|
+
];
|
|
33
|
+
export class McpToolBudgetBlocked extends Error {
|
|
34
|
+
constructor(message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'McpToolBudgetBlocked';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const activeCall = new AsyncLocalStorage();
|
|
40
|
+
const sequences = new Map();
|
|
41
|
+
function clean(value, fallback) {
|
|
42
|
+
const text = value.trim().slice(0, 128);
|
|
43
|
+
return text || fallback;
|
|
44
|
+
}
|
|
45
|
+
function optionalIntEnv(name) {
|
|
46
|
+
const raw = (process.env[name] || '').trim();
|
|
47
|
+
if (!raw)
|
|
48
|
+
return null;
|
|
49
|
+
const value = Number(raw);
|
|
50
|
+
if (!Number.isInteger(value) || value < 0)
|
|
51
|
+
return null;
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
export function budgetMode() {
|
|
55
|
+
const mode = (process.env.NETGREENER_MCP_BUDGET_MODE || 'warn').trim().toLowerCase();
|
|
56
|
+
return mode === 'block' ? 'block' : 'warn';
|
|
57
|
+
}
|
|
58
|
+
function configuredEstimates() {
|
|
59
|
+
const raw = (process.env.NETGREENER_MCP_TOOL_ESTIMATE_USD || '').trim();
|
|
60
|
+
const out = new Map();
|
|
61
|
+
if (!raw)
|
|
62
|
+
return out;
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(raw);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
71
|
+
return out;
|
|
72
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
73
|
+
const amount = typeof value === 'number' ? value : Number(value);
|
|
74
|
+
if (!Number.isFinite(amount) || amount < 0)
|
|
75
|
+
continue;
|
|
76
|
+
out.set(String(key).slice(0, 160), amount);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function configuredEstimateUsd(server, tool) {
|
|
81
|
+
const estimates = configuredEstimates();
|
|
82
|
+
if (estimates.size === 0)
|
|
83
|
+
return null;
|
|
84
|
+
const pair = estimates.get(`${server}::${tool}`);
|
|
85
|
+
if (pair !== undefined)
|
|
86
|
+
return pair;
|
|
87
|
+
const toolOnly = estimates.get(tool);
|
|
88
|
+
return toolOnly === undefined ? null : toolOnly;
|
|
89
|
+
}
|
|
90
|
+
function tenantIdNow() {
|
|
91
|
+
try {
|
|
92
|
+
const text = String(getTenantContext()?.tenantId || '').trim().slice(0, 128);
|
|
93
|
+
return text || null;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function collectorEndpoint() {
|
|
100
|
+
return (process.env.NETGREENER_COLLECTOR_ENDPOINT || '').trim();
|
|
101
|
+
}
|
|
102
|
+
function metricsPort() {
|
|
103
|
+
return (process.env.NETGREENER_METRICS_PORT || '').trim();
|
|
104
|
+
}
|
|
105
|
+
function emitSample(payload) {
|
|
106
|
+
const collector = collectorEndpoint();
|
|
107
|
+
const port = metricsPort();
|
|
108
|
+
if (!collector && !port)
|
|
109
|
+
return false;
|
|
110
|
+
if (collector) {
|
|
111
|
+
void emitToCollector(collector, payload);
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
emitToMetricsPort(port, payload);
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
function emitToMetricsPort(port, payload) {
|
|
118
|
+
const portNumber = Number(port);
|
|
119
|
+
if (!Number.isInteger(portNumber) || portNumber <= 0)
|
|
120
|
+
return;
|
|
121
|
+
const socket = connect({ host: '127.0.0.1', port: portNumber, timeout: 2000 });
|
|
122
|
+
socket.unref();
|
|
123
|
+
const fail = () => {
|
|
124
|
+
socket.destroy();
|
|
125
|
+
};
|
|
126
|
+
socket.once('error', fail);
|
|
127
|
+
socket.once('timeout', fail);
|
|
128
|
+
socket.once('connect', () => {
|
|
129
|
+
socket.end(JSON.stringify(payload));
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async function emitToCollector(endpoint, payload) {
|
|
133
|
+
try {
|
|
134
|
+
const projectId = Number(process.env.NETGREENER_PROJECT_ID || '');
|
|
135
|
+
if (!Number.isInteger(projectId) || projectId <= 0)
|
|
136
|
+
return;
|
|
137
|
+
const event = {
|
|
138
|
+
...payload,
|
|
139
|
+
project_id: projectId,
|
|
140
|
+
wall_time_utc: new Date().toISOString(),
|
|
141
|
+
};
|
|
142
|
+
const executionId = String(event.execution_id || '');
|
|
143
|
+
if (executionId) {
|
|
144
|
+
const sequence = (sequences.get(executionId) ?? 0) + 1;
|
|
145
|
+
sequences.set(executionId, sequence);
|
|
146
|
+
event.event_id = randomUUID();
|
|
147
|
+
event.sequence_number = sequence;
|
|
148
|
+
}
|
|
149
|
+
const timeoutMs = Math.max(1, Number(process.env.NETGREENER_EMIT_TIMEOUT_MS || '100') || 100);
|
|
150
|
+
await sendCollectorEvent({ endpoint, payload: event, timeoutMs });
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
/* fail open: a missing collector must not break the tool call */
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function activeMcpToolCallId() {
|
|
157
|
+
const value = activeCall.getStore();
|
|
158
|
+
const text = String(value || '').trim().slice(0, 64);
|
|
159
|
+
return text || null;
|
|
160
|
+
}
|
|
161
|
+
export function runWithMcpToolCall(callId, fn) {
|
|
162
|
+
return activeCall.run(String(callId).slice(0, 64), fn);
|
|
163
|
+
}
|
|
164
|
+
export class McpToolLedger {
|
|
165
|
+
calls = [];
|
|
166
|
+
httpLinks = [];
|
|
167
|
+
dropped = 0;
|
|
168
|
+
budgetTotals = new Map();
|
|
169
|
+
budgetPairs = new Map();
|
|
170
|
+
hasCalls() {
|
|
171
|
+
return this.calls.length > 0;
|
|
172
|
+
}
|
|
173
|
+
beginToolCall(server, tool) {
|
|
174
|
+
const serverName = clean(server, 'unknown');
|
|
175
|
+
const toolName = clean(tool, 'unknown');
|
|
176
|
+
const scope = 'process';
|
|
177
|
+
const total = (this.budgetTotals.get(scope) ?? 0) + 1;
|
|
178
|
+
this.budgetTotals.set(scope, total);
|
|
179
|
+
let pairs = this.budgetPairs.get(scope);
|
|
180
|
+
if (!pairs) {
|
|
181
|
+
pairs = new Map();
|
|
182
|
+
this.budgetPairs.set(scope, pairs);
|
|
183
|
+
}
|
|
184
|
+
const pairKey = `${serverName}\0${toolName}`;
|
|
185
|
+
const attempt = (pairs.get(pairKey) ?? 0) + 1;
|
|
186
|
+
pairs.set(pairKey, attempt);
|
|
187
|
+
const maxCalls = optionalIntEnv('NETGREENER_MCP_MAX_CALLS');
|
|
188
|
+
const maxRepeats = optionalIntEnv('NETGREENER_MCP_MAX_REPEATS');
|
|
189
|
+
const reasons = [];
|
|
190
|
+
if (maxCalls !== null && total > maxCalls)
|
|
191
|
+
reasons.push(`max calls per run is ${maxCalls}`);
|
|
192
|
+
if (maxRepeats !== null && attempt > maxRepeats) {
|
|
193
|
+
reasons.push(`max calls for this tool is ${maxRepeats}`);
|
|
194
|
+
}
|
|
195
|
+
const action = reasons.length === 0 ? 'allow' : budgetMode();
|
|
196
|
+
return {
|
|
197
|
+
callId: randomUUID().replace(/-/g, ''),
|
|
198
|
+
server: serverName,
|
|
199
|
+
tool: toolName,
|
|
200
|
+
attempt,
|
|
201
|
+
action,
|
|
202
|
+
reason: reasons.length ? reasons.join('; ') : null,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
finishToolCall(decision, opts) {
|
|
206
|
+
const blocked = decision.action === 'block';
|
|
207
|
+
const row = {
|
|
208
|
+
server: decision.server,
|
|
209
|
+
tool: decision.tool,
|
|
210
|
+
started_at: opts.startedAt ?? new Date().toISOString(),
|
|
211
|
+
duration_ms: Math.round(Math.max(0, opts.durationMs) * 1000) / 1000,
|
|
212
|
+
success: Boolean(opts.success) && !blocked,
|
|
213
|
+
attempt: decision.attempt,
|
|
214
|
+
budget_action: decision.action,
|
|
215
|
+
invoked: !blocked,
|
|
216
|
+
call_id: decision.callId,
|
|
217
|
+
};
|
|
218
|
+
const tenantId = tenantIdNow();
|
|
219
|
+
if (tenantId)
|
|
220
|
+
row.tenant_id = tenantId;
|
|
221
|
+
const estimate = configuredEstimateUsd(decision.server, decision.tool);
|
|
222
|
+
if (estimate !== null) {
|
|
223
|
+
row.estimated_usd = estimate;
|
|
224
|
+
row.estimate_label = 'configured';
|
|
225
|
+
}
|
|
226
|
+
if (decision.reason)
|
|
227
|
+
row.budget_reason = decision.reason;
|
|
228
|
+
if (emitSample({ kind: 'mcp_tool_sample', ...row }))
|
|
229
|
+
return;
|
|
230
|
+
this.append(row);
|
|
231
|
+
}
|
|
232
|
+
recordHttpLink(row) {
|
|
233
|
+
const toolCallId = row.toolCallId.trim().slice(0, 64);
|
|
234
|
+
const host = row.host.trim().toLowerCase().slice(0, 255);
|
|
235
|
+
if (!toolCallId || !host)
|
|
236
|
+
return;
|
|
237
|
+
const link = {
|
|
238
|
+
tool_call_id: toolCallId,
|
|
239
|
+
host,
|
|
240
|
+
duration_ms: Math.round(Math.max(0, row.durationMs) * 1000) / 1000,
|
|
241
|
+
error: row.error,
|
|
242
|
+
};
|
|
243
|
+
if (emitSample({
|
|
244
|
+
kind: 'mcp_http_link_sample',
|
|
245
|
+
...link,
|
|
246
|
+
})) {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (this.httpLinks.length >= MAX_STORED) {
|
|
250
|
+
this.dropped += 1;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
this.httpLinks.push(link);
|
|
254
|
+
}
|
|
255
|
+
takeSnapshot() {
|
|
256
|
+
const snapshot = new McpToolLedger();
|
|
257
|
+
snapshot.calls = this.calls;
|
|
258
|
+
snapshot.httpLinks = this.httpLinks;
|
|
259
|
+
snapshot.dropped = this.dropped;
|
|
260
|
+
this.calls = [];
|
|
261
|
+
this.httpLinks = [];
|
|
262
|
+
this.dropped = 0;
|
|
263
|
+
return snapshot;
|
|
264
|
+
}
|
|
265
|
+
mergeSnapshot(snapshot) {
|
|
266
|
+
this.calls = snapshot.calls.concat(this.calls);
|
|
267
|
+
this.httpLinks = snapshot.httpLinks.concat(this.httpLinks);
|
|
268
|
+
this.dropped += snapshot.dropped;
|
|
269
|
+
snapshot.calls = [];
|
|
270
|
+
snapshot.httpLinks = [];
|
|
271
|
+
snapshot.dropped = 0;
|
|
272
|
+
if (this.calls.length > MAX_STORED) {
|
|
273
|
+
this.dropped += this.calls.length - MAX_STORED;
|
|
274
|
+
this.calls = this.calls.slice(-MAX_STORED);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
buildV0() {
|
|
278
|
+
if (this.calls.length === 0)
|
|
279
|
+
return null;
|
|
280
|
+
const byTool = new Map();
|
|
281
|
+
const tenants = new Set();
|
|
282
|
+
for (const row of this.calls) {
|
|
283
|
+
const key = `${row.server}\0${row.tool}`;
|
|
284
|
+
const bucket = byTool.get(key) ?? {
|
|
285
|
+
server: row.server,
|
|
286
|
+
tool: row.tool,
|
|
287
|
+
calls: 0,
|
|
288
|
+
failures: 0,
|
|
289
|
+
duration_ms: 0,
|
|
290
|
+
estimated_usd: null,
|
|
291
|
+
};
|
|
292
|
+
bucket.calls += 1;
|
|
293
|
+
if (!row.success)
|
|
294
|
+
bucket.failures += 1;
|
|
295
|
+
bucket.duration_ms = Math.round((bucket.duration_ms + row.duration_ms) * 1000) / 1000;
|
|
296
|
+
if (row.estimated_usd !== undefined) {
|
|
297
|
+
bucket.estimated_usd = Math.round(((bucket.estimated_usd ?? 0) + row.estimated_usd) * 1_000_000) / 1_000_000;
|
|
298
|
+
}
|
|
299
|
+
if (row.tenant_id)
|
|
300
|
+
tenants.add(row.tenant_id);
|
|
301
|
+
byTool.set(key, bucket);
|
|
302
|
+
}
|
|
303
|
+
const tools = [...byTool.values()]
|
|
304
|
+
.map((bucket) => {
|
|
305
|
+
const row = {
|
|
306
|
+
server: bucket.server,
|
|
307
|
+
tool: bucket.tool,
|
|
308
|
+
calls: bucket.calls,
|
|
309
|
+
failures: bucket.failures,
|
|
310
|
+
duration_ms: bucket.duration_ms,
|
|
311
|
+
};
|
|
312
|
+
if (bucket.estimated_usd !== null) {
|
|
313
|
+
row.estimated_usd = bucket.estimated_usd;
|
|
314
|
+
row.estimate_label = 'configured';
|
|
315
|
+
}
|
|
316
|
+
return row;
|
|
317
|
+
})
|
|
318
|
+
.sort((a, b) => Number(b.calls) - Number(a.calls) || String(a.tool).localeCompare(String(b.tool)));
|
|
319
|
+
const payload = {
|
|
320
|
+
schema: 'mcp_tool_v0',
|
|
321
|
+
budget_scope: 'in_process',
|
|
322
|
+
not_distributed: true,
|
|
323
|
+
budget_mode: budgetMode(),
|
|
324
|
+
limits: {
|
|
325
|
+
max_calls: optionalIntEnv('NETGREENER_MCP_MAX_CALLS'),
|
|
326
|
+
max_repeats: optionalIntEnv('NETGREENER_MCP_MAX_REPEATS'),
|
|
327
|
+
},
|
|
328
|
+
calls: this.calls,
|
|
329
|
+
by_tool: tools,
|
|
330
|
+
notes: NOTES,
|
|
331
|
+
};
|
|
332
|
+
if (this.httpLinks.length > 0) {
|
|
333
|
+
payload.http_in_context = this.httpLinks;
|
|
334
|
+
payload.attribution_note =
|
|
335
|
+
'Each HTTP row started while that tool call was active in this process. ' +
|
|
336
|
+
'That is context, not proof the request was unnecessary. ' +
|
|
337
|
+
'Cost stays in external_api_v0 and is not counted again.';
|
|
338
|
+
}
|
|
339
|
+
if (this.dropped > 0) {
|
|
340
|
+
payload.truncated = true;
|
|
341
|
+
payload.dropped_calls = this.dropped;
|
|
342
|
+
}
|
|
343
|
+
if (tenants.size === 1)
|
|
344
|
+
payload.tenant_id = [...tenants][0];
|
|
345
|
+
return payload;
|
|
346
|
+
}
|
|
347
|
+
clear() {
|
|
348
|
+
this.calls = [];
|
|
349
|
+
this.httpLinks = [];
|
|
350
|
+
this.dropped = 0;
|
|
351
|
+
this.budgetTotals.clear();
|
|
352
|
+
this.budgetPairs.clear();
|
|
353
|
+
}
|
|
354
|
+
append(row) {
|
|
355
|
+
if (this.calls.length >= MAX_STORED) {
|
|
356
|
+
this.dropped += 1;
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
this.calls.push(row);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const ledger = new McpToolLedger();
|
|
363
|
+
export function getMcpToolLedger() {
|
|
364
|
+
return ledger;
|
|
365
|
+
}
|
|
366
|
+
export function beginToolCall(server, tool) {
|
|
367
|
+
return ledger.beginToolCall(server, tool);
|
|
368
|
+
}
|
|
369
|
+
export function finishToolCall(decision, opts) {
|
|
370
|
+
ledger.finishToolCall(decision, opts);
|
|
371
|
+
}
|
|
372
|
+
export function recordHttpInToolContext(row) {
|
|
373
|
+
if (!row.toolCallId)
|
|
374
|
+
return;
|
|
375
|
+
ledger.recordHttpLink({
|
|
376
|
+
toolCallId: row.toolCallId,
|
|
377
|
+
host: row.host,
|
|
378
|
+
durationMs: row.durationMs,
|
|
379
|
+
error: row.error,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
export function buildMcpToolV0() {
|
|
383
|
+
return ledger.buildV0();
|
|
384
|
+
}
|
|
385
|
+
export function httpDurationMs(externalV0) {
|
|
386
|
+
if (!externalV0)
|
|
387
|
+
return 0;
|
|
388
|
+
const providers = externalV0.providers;
|
|
389
|
+
if (!Array.isArray(providers))
|
|
390
|
+
return 0;
|
|
391
|
+
let total = 0;
|
|
392
|
+
for (const row of providers) {
|
|
393
|
+
if (!row || typeof row !== 'object')
|
|
394
|
+
continue;
|
|
395
|
+
const record = row;
|
|
396
|
+
if (record.duration_ms_total !== undefined && record.duration_ms_total !== null) {
|
|
397
|
+
total += Number(record.duration_ms_total) || 0;
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
total += (Number(record.calls) || 0) * (Number(record.duration_ms_avg) || 0);
|
|
401
|
+
}
|
|
402
|
+
return total;
|
|
403
|
+
}
|
|
404
|
+
export function mcpDurationMs(mcpV0, failedOnly = false) {
|
|
405
|
+
if (!mcpV0 || !Array.isArray(mcpV0.calls))
|
|
406
|
+
return 0;
|
|
407
|
+
let total = 0;
|
|
408
|
+
for (const row of mcpV0.calls) {
|
|
409
|
+
if (!row || typeof row !== 'object')
|
|
410
|
+
continue;
|
|
411
|
+
const record = row;
|
|
412
|
+
if (failedOnly && record.success)
|
|
413
|
+
continue;
|
|
414
|
+
if (failedOnly && record.success !== false)
|
|
415
|
+
continue;
|
|
416
|
+
total += Number(record.duration_ms) || 0;
|
|
417
|
+
}
|
|
418
|
+
return total;
|
|
419
|
+
}
|
|
420
|
+
export function buildMcpLatencyV0(mcpV0, externalV0, wallSeconds) {
|
|
421
|
+
if (!mcpV0 || !Array.isArray(mcpV0.calls) || mcpV0.calls.length === 0)
|
|
422
|
+
return null;
|
|
423
|
+
const wallMs = wallSeconds === null ? null : Math.max(0, wallSeconds * 1000);
|
|
424
|
+
const mcpMs = mcpDurationMs(mcpV0);
|
|
425
|
+
const httpMs = httpDurationMs(externalV0);
|
|
426
|
+
const failedMs = mcpDurationMs(mcpV0, true);
|
|
427
|
+
const mcpOver = wallMs !== null && mcpMs > wallMs;
|
|
428
|
+
const httpOver = wallMs !== null && httpMs > wallMs;
|
|
429
|
+
let remainder = null;
|
|
430
|
+
let rowsOverlap = false;
|
|
431
|
+
if (wallMs !== null && !mcpOver && !httpOver) {
|
|
432
|
+
if (mcpMs + httpMs <= wallMs)
|
|
433
|
+
remainder = Math.round((wallMs - mcpMs - httpMs) * 1000) / 1000;
|
|
434
|
+
else
|
|
435
|
+
rowsOverlap = true;
|
|
436
|
+
}
|
|
437
|
+
const rows = [];
|
|
438
|
+
if (wallMs !== null) {
|
|
439
|
+
rows.push({
|
|
440
|
+
id: 'wall',
|
|
441
|
+
label: 'Task wall time',
|
|
442
|
+
duration_ms: Math.round(wallMs * 1000) / 1000,
|
|
443
|
+
overlapping: false,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
rows.push({
|
|
447
|
+
id: 'mcp',
|
|
448
|
+
label: 'MCP tools',
|
|
449
|
+
duration_ms: Math.round(mcpMs * 1000) / 1000,
|
|
450
|
+
overlapping: mcpOver,
|
|
451
|
+
});
|
|
452
|
+
rows.push({
|
|
453
|
+
id: 'http',
|
|
454
|
+
label: 'HTTP, including LLM',
|
|
455
|
+
duration_ms: Math.round(httpMs * 1000) / 1000,
|
|
456
|
+
overlapping: httpOver,
|
|
457
|
+
note: 'Full call duration. Not time to first token.',
|
|
458
|
+
});
|
|
459
|
+
rows.push({
|
|
460
|
+
id: 'failed_mcp',
|
|
461
|
+
label: 'Failed MCP calls',
|
|
462
|
+
duration_ms: Math.round(failedMs * 1000) / 1000,
|
|
463
|
+
overlapping: false,
|
|
464
|
+
note: 'Time inside calls that failed. Not backoff, and not proof of a retry loop.',
|
|
465
|
+
});
|
|
466
|
+
if (remainder !== null) {
|
|
467
|
+
rows.push({
|
|
468
|
+
id: 'unattributed',
|
|
469
|
+
label: 'Unattributed',
|
|
470
|
+
duration_ms: remainder,
|
|
471
|
+
overlapping: false,
|
|
472
|
+
note: 'Not CPU or GPU.',
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
return {
|
|
476
|
+
schema: 'mcp_latency_v0',
|
|
477
|
+
rows,
|
|
478
|
+
remainder_omitted: remainder === null,
|
|
479
|
+
rows_overlap_each_other: rowsOverlap,
|
|
480
|
+
cannot_say: CANNOT_SAY,
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
export function clearMcpToolLedger() {
|
|
484
|
+
ledger.clear();
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Official MCP client patching stays off until one SDK version is installed
|
|
488
|
+
* and its callTool signature is tested. A command basename is not a server name.
|
|
489
|
+
* This returns false so a caller cannot treat the hook as active.
|
|
490
|
+
*/
|
|
491
|
+
export function installMcpClientInstrumentation() {
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
export function _resetMcpToolMeterForTests() {
|
|
495
|
+
ledger.clear();
|
|
496
|
+
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* CAP-R6 deployment-mode matrix (Node Runtime production scope).
|
|
3
3
|
*
|
|
4
|
-
* Freezes what we **claim** vs **exercise** vs **exclude**.
|
|
5
|
-
*
|
|
4
|
+
* Freezes what we **claim** vs **exercise** vs **exclude**.
|
|
5
|
+
* Honesty pass 2026-10-06: ACA + serverless gates exist as code/dry-run only —
|
|
6
|
+
* not production claims until live run_id evidence is retained.
|
|
7
|
+
* Does not flip export defaults for persistent apps.
|
|
6
8
|
*/
|
|
7
9
|
export type DeployModeStatus = 'claimed_and_exercised' | 'documented_degraded' | 'not_claimed' | 'open';
|
|
8
10
|
export type DeployModeEntry = {
|
|
@@ -13,10 +15,12 @@ export type DeployModeEntry = {
|
|
|
13
15
|
notes: string;
|
|
14
16
|
};
|
|
15
17
|
/**
|
|
16
|
-
* Production claim scope
|
|
17
|
-
*
|
|
18
|
-
* Container/K8s/CI/serverless are **not** silently included.
|
|
18
|
+
* Production claim scope (honest): long-running process only.
|
|
19
|
+
* ACA container + serverless thin = gate-ready / pilot until live acceptance.
|
|
19
20
|
*/
|
|
20
21
|
export declare const NODE_DEPLOYMENT_MATRIX: readonly DeployModeEntry[];
|
|
21
22
|
export declare function claimedDeployModes(): DeployModeEntry[];
|
|
23
|
+
/**
|
|
24
|
+
* Production scope must claim exactly long_running_process until live gates land.
|
|
25
|
+
*/
|
|
22
26
|
export declare function assertProductionScopeIsExplicit(): boolean;
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* CAP-R6 deployment-mode matrix (Node Runtime production scope).
|
|
3
3
|
*
|
|
4
|
-
* Freezes what we **claim** vs **exercise** vs **exclude**.
|
|
5
|
-
*
|
|
4
|
+
* Freezes what we **claim** vs **exercise** vs **exclude**.
|
|
5
|
+
* Honesty pass 2026-10-06: ACA + serverless gates exist as code/dry-run only —
|
|
6
|
+
* not production claims until live run_id evidence is retained.
|
|
7
|
+
* Does not flip export defaults for persistent apps.
|
|
6
8
|
*/
|
|
7
9
|
/**
|
|
8
|
-
* Production claim scope
|
|
9
|
-
*
|
|
10
|
-
* Container/K8s/CI/serverless are **not** silently included.
|
|
10
|
+
* Production claim scope (honest): long-running process only.
|
|
11
|
+
* ACA container + serverless thin = gate-ready / pilot until live acceptance.
|
|
11
12
|
*/
|
|
12
13
|
export const NODE_DEPLOYMENT_MATRIX = [
|
|
13
14
|
{
|
|
@@ -21,8 +22,8 @@ export const NODE_DEPLOYMENT_MATRIX = [
|
|
|
21
22
|
check_id: 'CHK-R6.container',
|
|
22
23
|
mode: 'container',
|
|
23
24
|
status: 'not_claimed',
|
|
24
|
-
evidence: '
|
|
25
|
-
notes: '
|
|
25
|
+
evidence: 'examples/aca-container-gate + artifacts/aca-container-gate (dry-run / ACA-shaped); no live ACA run_id yet',
|
|
26
|
+
notes: 'Gate-ready for Azure Container Apps only. Do not claim until live upload + dashboard run_id retained. AWS/GCP not gated.',
|
|
26
27
|
},
|
|
27
28
|
{
|
|
28
29
|
check_id: 'CHK-R6.kubernetes',
|
|
@@ -42,13 +43,16 @@ export const NODE_DEPLOYMENT_MATRIX = [
|
|
|
42
43
|
check_id: 'CHK-R6.serverless-degraded',
|
|
43
44
|
mode: 'serverless_thin',
|
|
44
45
|
status: 'documented_degraded',
|
|
45
|
-
evidence: 'serverlessHints
|
|
46
|
-
notes: '
|
|
46
|
+
evidence: 'lifecycle + serverlessHints tests; artifacts/serverless-thin-gate dry-run; Next pilot helpers',
|
|
47
|
+
notes: 'Pilot / degraded until live Vercel (or Lambda) run_id. Not durable spool. Explicit EXPORT_MODE / NETGREENER_RUNTIME=persistent win.',
|
|
47
48
|
},
|
|
48
49
|
];
|
|
49
50
|
export function claimedDeployModes() {
|
|
50
51
|
return NODE_DEPLOYMENT_MATRIX.filter((e) => e.status === 'claimed_and_exercised');
|
|
51
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Production scope must claim exactly long_running_process until live gates land.
|
|
55
|
+
*/
|
|
52
56
|
export function assertProductionScopeIsExplicit() {
|
|
53
57
|
const claimed = claimedDeployModes();
|
|
54
58
|
if (claimed.length !== 1)
|
|
@@ -35,17 +35,17 @@ export const NODE_DIRECT_MISSINGNESS_INVENTORY = [
|
|
|
35
35
|
signal_id: 'unit.peak_rss_kb_max',
|
|
36
36
|
status: 'measured',
|
|
37
37
|
provenance: MEMORY_SOURCE_PROCESS,
|
|
38
|
-
notes: 'process.memoryUsage().rss
|
|
38
|
+
notes: 'process.memoryUsage().rss (KiB); OS read rate-limited (~50ms) — cached values are prior measured samples, never invented',
|
|
39
39
|
},
|
|
40
40
|
{
|
|
41
41
|
signal_id: 'unit.energy_kwh_carbon_g',
|
|
42
42
|
status: 'derived_estimate',
|
|
43
|
-
notes: 'Emitter-side TDP util estimate (prefers measured CPU when present);
|
|
43
|
+
notes: 'Emitter-side TDP util estimate (prefers measured CPU when present); carbon via netgreener_default_grid (0.276 kg/kWh, Python twin); GPU/RAM/IO energy still open',
|
|
44
44
|
},
|
|
45
45
|
{
|
|
46
46
|
signal_id: 'collector.process_tree_cgroup',
|
|
47
47
|
status: 'not_measured',
|
|
48
|
-
notes: '
|
|
48
|
+
notes: 'Opt-in: NETGREENER_COLLECTOR_MODE=managed + collector enrich (`collector_resource_sample_v0` via emitter_pid). Direct emitter still process-only; Windows cgroup = honest unavailable',
|
|
49
49
|
},
|
|
50
50
|
{
|
|
51
51
|
signal_id: 'runtime_health_v0',
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Next.js App Router adapter (Wave 3 pilot).
|
|
3
|
+
*
|
|
4
|
+
* Maps into the same Runtime / observation / export path as Express.
|
|
5
|
+
* Not a Vercel production claim — use persistent Node or pilot wording.
|
|
6
|
+
* Does not change NETGREENER_EXPORT_MODE defaults.
|
|
7
|
+
*/
|
|
8
|
+
import { type NetGreenerRuntime, type NetGreenerRuntimeOptions } from './runtime.js';
|
|
9
|
+
import type { UploadResult } from './uploader.js';
|
|
10
|
+
export { withNetGreener, type NextConfigLike } from './nextConfig.js';
|
|
11
|
+
type NextAfterFn = (task: () => Promise<unknown> | unknown) => void;
|
|
12
|
+
export declare function _setNextAfterForTests(fn: NextAfterFn | null | undefined): void;
|
|
13
|
+
export declare function _setInvokeFlushQuietMsForTests(ms: number): void;
|
|
14
|
+
export declare const UNKNOWN_NEXT_ROUTE_TEMPLATE = "<unmatched>";
|
|
15
|
+
/** Minimal Next Request-like shape (App Router / Fetch API). */
|
|
16
|
+
export type NextRequestLike = {
|
|
17
|
+
method?: string;
|
|
18
|
+
url?: string;
|
|
19
|
+
nextUrl?: {
|
|
20
|
+
pathname?: string;
|
|
21
|
+
};
|
|
22
|
+
headers?: Headers | Record<string, unknown>;
|
|
23
|
+
/** Platform keep-alive when Next.js ``after`` is not available. */
|
|
24
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
25
|
+
};
|
|
26
|
+
export type NextRouteContext = Record<string, unknown>;
|
|
27
|
+
/** App-supplied tenant id for this invoke. NetGreener does not read Supabase. */
|
|
28
|
+
export type NextTenantResolver = (req: NextRequestLike) => Promise<string | null | undefined> | string | null | undefined;
|
|
29
|
+
export type NetGreenerNextOptions = NetGreenerRuntimeOptions & {
|
|
30
|
+
/**
|
|
31
|
+
* Static route template override (e.g. ``/api/intake/[id]``).
|
|
32
|
+
* Prefer this over raw pathnames that may embed customer ids.
|
|
33
|
+
*/
|
|
34
|
+
routeTemplate?: string;
|
|
35
|
+
/** Overrides the header tenant for this install. */
|
|
36
|
+
resolveTenant?: NextTenantResolver;
|
|
37
|
+
/** Service-unit verb recorded on the sample. Defaults to the request method. */
|
|
38
|
+
recordMethod?: string;
|
|
39
|
+
/** Aggregator unit type. Defaults to ``http_route`` or ``cron``. */
|
|
40
|
+
unitType?: string;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Call from ``instrumentation.ts`` ``register()`` to start the Runtime singleton.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* export async function register() {
|
|
47
|
+
* const { registerNetGreenerNext } = await import('@netgreener/runtime/next')
|
|
48
|
+
* registerNetGreenerNext()
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function registerNetGreenerNext(opts?: NetGreenerNextOptions): NetGreenerRuntime;
|
|
53
|
+
/**
|
|
54
|
+
* Bounded route template for service_unit attribution.
|
|
55
|
+
* Never use query strings; prefer an explicit ``routeTemplate`` option.
|
|
56
|
+
*/
|
|
57
|
+
export declare function nextRouteTemplate(req: NextRequestLike, override?: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Wrap an App Router route handler (``GET``/``POST``/…) with NetGreener metering.
|
|
60
|
+
*
|
|
61
|
+
* ```ts
|
|
62
|
+
* export const POST = withNetGreenerRoute(async (req) => {
|
|
63
|
+
* return Response.json({ ok: true })
|
|
64
|
+
* }, { routeTemplate: '/api/intake' })
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function withNetGreenerRoute<TReq extends NextRequestLike, TArgs extends unknown[], TResult>(handler: (req: TReq, ...args: TArgs) => Promise<TResult> | TResult, opts?: NetGreenerNextOptions): (req: TReq, ...args: TArgs) => Promise<TResult>;
|
|
68
|
+
/**
|
|
69
|
+
* Loader target for an App Router route handler.
|
|
70
|
+
* ``cron: true`` records the service unit as ``CRON <template>``.
|
|
71
|
+
*/
|
|
72
|
+
export declare function observeNextRoute<T extends (...args: never[]) => unknown>(handler: T, _method: string, routeTemplate: string, opts?: {
|
|
73
|
+
cron?: boolean;
|
|
74
|
+
}): T;
|
|
75
|
+
/** Loader target for a server page. */
|
|
76
|
+
export declare function observeNextPage<T extends (...args: never[]) => unknown>(component: T, routeTemplate: string): T;
|
|
77
|
+
/** Loader target for a `'use server'` export. */
|
|
78
|
+
export declare function observeNextAction<T extends (...args: never[]) => unknown>(action: T, name: string, routeTemplate: string): T;
|
|
79
|
+
export declare function getNextRuntime(): NetGreenerRuntime;
|
|
80
|
+
/** Explicit flush helper for instrumentation ``onRequestError`` / custom hooks. */
|
|
81
|
+
export declare function flushNetGreenerNext(kind?: 'manual' | 'shutdown' | 'invoke_end'): Promise<UploadResult | null>;
|
|
82
|
+
/**
|
|
83
|
+
* Schedule a best-effort flush after the response (Vercel ``waitUntil`` when present).
|
|
84
|
+
* Fail-open: never throws into the customer path.
|
|
85
|
+
*
|
|
86
|
+
* Prefers Next.js ``after()``, which runs once the response (including a stream)
|
|
87
|
+
* has closed and is already passed to platform ``waitUntil``.
|
|
88
|
+
*/
|
|
89
|
+
export declare function scheduleNetGreenerFlush(waitUntil?: (promise: Promise<unknown>) => void): void;
|