@netgreener/runtime 0.1.14 → 0.1.16

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.
@@ -0,0 +1,32 @@
1
+ import { type ResourceFindingCandidateV1 } from './resourceFindingCandidate.js';
2
+ declare const DEPTH_MAX: Record<"quick" | "standard" | "thorough", number>;
3
+ export type NodeLlmDepth = keyof typeof DEPTH_MAX;
4
+ export type LlmConfig = {
5
+ api_key: string;
6
+ provider?: string;
7
+ azure_endpoint?: string;
8
+ model?: string;
9
+ api_version?: string;
10
+ };
11
+ /** One provider validation path shared by npm and the editor adapter. */
12
+ export declare function resolveNodeLlmConfig(config: LlmConfig): LlmConfig;
13
+ export type NodeLlmReviewOptions = {
14
+ projectDir: string;
15
+ projectId: string;
16
+ staticFindings: ResourceFindingCandidateV1[];
17
+ paths: string[];
18
+ config: LlmConfig;
19
+ depth?: NodeLlmDepth;
20
+ fetchImpl?: typeof fetch;
21
+ timeoutMs?: number;
22
+ progress?: (message: string) => void;
23
+ };
24
+ export type NodeLlmReviewResult = {
25
+ findings: ResourceFindingCandidateV1[];
26
+ filesReviewed: number;
27
+ filesPlanned: number;
28
+ errors: string[];
29
+ };
30
+ /** Bounded review; static results survive errors, which are always reported. */
31
+ export declare function runNodeLlmResourceReview(opts: NodeLlmReviewOptions): Promise<NodeLlmReviewResult>;
32
+ export {};
@@ -0,0 +1,285 @@
1
+ /** Shared Node Analyze LLM review, extracted from the editor reviewer. */
2
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { isAbsolute, relative, resolve } from 'node:path';
4
+ import { toResourceFindingCandidate } from './resourceFindingCandidate.js';
5
+ import { filterValidResourceFindings } from './validateResourceFinding.js';
6
+ const MAX_SOURCE_CHARS = 12_000;
7
+ const ALLOWED_MECHANISMS = new Set([
8
+ "per_item_instead_of_batch",
9
+ "retry_amplification",
10
+ "external_api_overconsumption",
11
+ "unbounded_parallelism",
12
+ "polling_or_idle_work",
13
+ "repeated_work",
14
+ "process_or_runtime_churn",
15
+ "memory_retention_or_materialization",
16
+ ]);
17
+ const DEPTH_MAX = {
18
+ quick: 1,
19
+ standard: 5,
20
+ thorough: 10,
21
+ };
22
+ /** One provider validation path shared by npm and the editor adapter. */
23
+ export function resolveNodeLlmConfig(config) {
24
+ const endpoint = (config.azure_endpoint || '').trim().replace(/\/+$/, '');
25
+ const provider = (config.provider || (/openai\.azure\.com|cognitiveservices\.azure\.com/i.test(endpoint) ? 'azure_openai' : 'openai')).trim().toLowerCase();
26
+ if (!['openai', 'azure_openai', 'anthropic', 'ollama', 'custom'].includes(provider)) {
27
+ throw new Error(`Unsupported Node LLM provider: ${provider}`);
28
+ }
29
+ if (!config.model?.trim())
30
+ throw new Error('LLM model is required.');
31
+ if (['openai', 'azure_openai', 'anthropic'].includes(provider) && !config.api_key?.trim()) {
32
+ throw new Error(`LLM provider ${provider} requires an API key.`);
33
+ }
34
+ if (['azure_openai', 'ollama', 'custom'].includes(provider) && !endpoint) {
35
+ throw new Error(`LLM provider ${provider} requires an endpoint.`);
36
+ }
37
+ return { ...config, provider, api_key: (config.api_key || '').trim(), model: config.model.trim(), azure_endpoint: endpoint };
38
+ }
39
+ function systemPrompt() {
40
+ const mechs = [...ALLOWED_MECHANISMS].join(", ");
41
+ return `You are NetGreener Node Analyze (resource scope only).
42
+ Find resource-consumption risks in JavaScript/TypeScript that waste CPU, memory, network, or paid external API cost.
43
+
44
+ Respond with ONE JSON object (no markdown):
45
+ {
46
+ "findings": [
47
+ {
48
+ "mechanism_id": one of [${mechs}],
49
+ "primary_domain": "compute.cpu"|"memory.host"|"network.io"|"external_api"|"storage.io",
50
+ "title": "short resource title",
51
+ "start_line": integer or null,
52
+ "evidence": "short quote",
53
+ "recommended_fix": "actionable fix",
54
+ "confidence": 0.0-1.0
55
+ }
56
+ ]
57
+ }
58
+
59
+ Rules:
60
+ - Only emit resource mechanisms from the list. Never security, secrets, style, or architecture.
61
+ - Do not invent files or lines not present in the payload.
62
+ - Prefer new issues not already listed in static_candidates.
63
+ - If nothing resource-relevant, return {"findings":[]}.`;
64
+ }
65
+ function userPayload(filePath, source, staticCandidates) {
66
+ let code = source;
67
+ const payload = {
68
+ schema_version: 1,
69
+ task: "node_resource_llm_v0",
70
+ file_path: filePath,
71
+ };
72
+ if (code.length > MAX_SOURCE_CHARS) {
73
+ code = code.slice(0, MAX_SOURCE_CHARS);
74
+ payload.source_code_truncated_note = `truncated to ${MAX_SOURCE_CHARS} chars`;
75
+ }
76
+ payload.source_code = code;
77
+ payload.static_candidates = staticCandidates
78
+ .filter((f) => (f.scope.source_locations[0]?.path || "").replace(/\\/g, "/") === filePath.replace(/\\/g, "/"))
79
+ .map((f) => ({
80
+ mechanism_id: f.mechanism_id,
81
+ title: f.title,
82
+ start_line: f.scope.source_locations[0]?.start_line,
83
+ }));
84
+ return payload;
85
+ }
86
+ function extractJsonObject(raw) {
87
+ const cleaned = raw.replace(/```json/gi, "").replace(/```/g, "").trim();
88
+ const m = cleaned.match(/\{[\s\S]*\}\s*$/);
89
+ return JSON.parse(m ? m[0] : cleaned);
90
+ }
91
+ function parseHits(raw, filePath) {
92
+ const data = extractJsonObject(raw);
93
+ if (!data || !Array.isArray(data.findings))
94
+ throw new Error("Invalid LLM response: expected findings array");
95
+ const list = data.findings;
96
+ const out = [];
97
+ for (const item of list) {
98
+ if (!item || typeof item !== "object")
99
+ continue;
100
+ const row = item;
101
+ const mech = String(row.mechanism_id || "").trim();
102
+ if (!ALLOWED_MECHANISMS.has(mech))
103
+ continue;
104
+ const title = String(row.title || mech).trim().slice(0, 200);
105
+ if (title.length < 8)
106
+ continue;
107
+ const domain = String(row.primary_domain || "compute.cpu").trim();
108
+ let line = null;
109
+ if (typeof row.start_line === "number" && Number.isSafeInteger(row.start_line) && row.start_line > 0) {
110
+ line = row.start_line;
111
+ }
112
+ let conf = 0.5;
113
+ try {
114
+ conf = Math.max(0, Math.min(1, Number(row.confidence ?? 0.5)));
115
+ }
116
+ catch {
117
+ conf = 0.5;
118
+ }
119
+ out.push({
120
+ mechanism_id: mech,
121
+ title,
122
+ primary_domain: domain,
123
+ path: filePath,
124
+ start_line: line,
125
+ evidence: String(row.evidence || "").slice(0, 500),
126
+ recommended_fix: String(row.recommended_fix || "").slice(0, 500),
127
+ confidence: conf,
128
+ });
129
+ }
130
+ return out;
131
+ }
132
+ async function chatCompletion(cfg, messages, fetchImpl, signal) {
133
+ const model = cfg.model || "gpt-4o-mini";
134
+ const endpoint = (cfg.azure_endpoint || "").replace(/\/+$/, "");
135
+ let url;
136
+ const headers = { "Content-Type": "application/json" };
137
+ if (cfg.provider === 'anthropic') {
138
+ const base = endpoint || 'https://api.anthropic.com/v1';
139
+ const url = base.endsWith('/messages') ? base : `${base.endsWith('/v1') ? base : `${base}/v1`}/messages`;
140
+ const response = await fetchImpl(url, {
141
+ method: 'POST', signal,
142
+ headers: { ...headers, 'x-api-key': cfg.api_key, 'anthropic-version': cfg.api_version || '2023-06-01' },
143
+ body: JSON.stringify({ model, max_tokens: 1800,
144
+ system: messages.filter(message => message.role === 'system').map(message => message.content).join('\n\n'),
145
+ messages: messages.filter(message => message.role !== 'system'),
146
+ }),
147
+ });
148
+ if (!response.ok)
149
+ throw new Error(`LLM HTTP ${response.status}`);
150
+ const data = await response.json();
151
+ return (data.content ?? []).filter(block => block.type === 'text').map(block => block.text || '').join('');
152
+ }
153
+ if (cfg.provider === "azure_openai" || (endpoint && /openai\.azure\.com|cognitiveservices\.azure\.com/i.test(endpoint))) {
154
+ url = `${endpoint}/openai/deployments/${encodeURIComponent(model)}/chat/completions?api-version=${encodeURIComponent(cfg.api_version || "2024-02-15-preview")}`;
155
+ headers["api-key"] = cfg.api_key;
156
+ }
157
+ else if (endpoint) {
158
+ const base = cfg.provider === 'ollama' && !/\/v1(?:\/|$)/.test(endpoint) ? `${endpoint}/v1` : endpoint;
159
+ url = base.endsWith('/chat/completions') ? base : `${base}/chat/completions`;
160
+ if (cfg.api_key)
161
+ headers.Authorization = `Bearer ${cfg.api_key}`;
162
+ }
163
+ else {
164
+ url = "https://api.openai.com/v1/chat/completions";
165
+ headers.Authorization = `Bearer ${cfg.api_key}`;
166
+ }
167
+ const body = {
168
+ messages,
169
+ };
170
+ if (/^(o[1-9]|gpt-5|gpt-6)/i.test(model)) {
171
+ body.max_completion_tokens = 1800;
172
+ }
173
+ else {
174
+ body.max_tokens = 1800;
175
+ body.temperature = 0;
176
+ }
177
+ // Azure deployment path does not need body.model; openai-compat does.
178
+ if (!/\/deployments\//i.test(url)) {
179
+ body.model = model;
180
+ }
181
+ // Azure deployment aliases do not identify their underlying model. Match the
182
+ // Python client's bounded unsupported-parameter fallback, under one timeout.
183
+ for (let attempt = 0; attempt < 3; attempt++) {
184
+ const resp = await fetchImpl(url, {
185
+ signal, method: 'POST', headers, body: JSON.stringify(body),
186
+ });
187
+ if (resp.ok) {
188
+ const json = await resp.json();
189
+ return String(json.choices?.[0]?.message?.content || '');
190
+ }
191
+ if (resp.status === 400 && attempt < 2) {
192
+ const data = await resp.json().catch(() => null);
193
+ const parameter = String(data?.error?.param || '').toLowerCase();
194
+ const detail = `${data?.error?.code || ''} ${data?.error?.message || ''}`.toLowerCase();
195
+ if (/unsupported|not supported|only the default/.test(detail)) {
196
+ if ('max_tokens' in body && (parameter === 'max_tokens' || detail.includes('max_tokens'))) {
197
+ body.max_completion_tokens = body.max_tokens;
198
+ delete body.max_tokens;
199
+ delete body.temperature;
200
+ continue;
201
+ }
202
+ if ('temperature' in body && (parameter === 'temperature' || detail.includes('temperature'))) {
203
+ delete body.temperature;
204
+ continue;
205
+ }
206
+ }
207
+ }
208
+ throw new Error(`LLM HTTP ${resp.status}`);
209
+ }
210
+ throw new Error('LLM rejected supported request parameters');
211
+ }
212
+ /** Bounded review; static results survive errors, which are always reported. */
213
+ export async function runNodeLlmResourceReview(opts) {
214
+ const depth = opts.depth ?? 'standard';
215
+ const counts = new Map();
216
+ for (const finding of opts.staticFindings) {
217
+ const rel = finding.scope.source_locations[0]?.path;
218
+ if (rel)
219
+ counts.set(rel, (counts.get(rel) ?? 0) + 1);
220
+ }
221
+ const files = [...new Set(opts.paths.map(p => p.replace(/\\/g, '/')))]
222
+ .sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0) || a.localeCompare(b))
223
+ .slice(0, DEPTH_MAX[depth]);
224
+ const extra = [];
225
+ const errors = [];
226
+ let config;
227
+ try {
228
+ config = resolveNodeLlmConfig(opts.config);
229
+ }
230
+ catch (err) {
231
+ return { findings: opts.staticFindings, filesReviewed: 0, filesPlanned: files.length, errors: [err instanceof Error ? err.message : String(err)] };
232
+ }
233
+ const root = realpathSync(opts.projectDir);
234
+ let filesReviewed = 0;
235
+ for (const [index, rel] of files.entries()) {
236
+ opts.progress?.(`LLM review ${index + 1}/${files.length}: ${rel}`);
237
+ try {
238
+ const abs = realpathSync(resolve(root, rel));
239
+ const inside = relative(root, abs);
240
+ if (inside === '..' || inside.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(inside)) {
241
+ throw new Error('source path is outside project');
242
+ }
243
+ if (!statSync(abs).isFile() || statSync(abs).size > 512 * 1024)
244
+ throw new Error('source file exceeds review limit');
245
+ const source = readFileSync(abs, 'utf8').slice(0, MAX_SOURCE_CHARS);
246
+ const signal = AbortSignal.timeout(Math.min(opts.timeoutMs ?? 30_000, 60_000));
247
+ const raw = await chatCompletion(config, [
248
+ { role: 'system', content: systemPrompt() },
249
+ { role: 'user', content: JSON.stringify(userPayload(rel, source, opts.staticFindings)) },
250
+ ], opts.fetchImpl ?? fetch, signal);
251
+ const lines = source.split(/\r?\n/);
252
+ for (const hit of parseHits(raw, rel)) {
253
+ if (!hit.start_line || hit.start_line > lines.length)
254
+ continue;
255
+ if (!['compute.cpu', 'memory.host', 'network.io', 'external_api', 'storage.io'].includes(hit.primary_domain))
256
+ continue;
257
+ if (!hit.evidence?.trim() || !source.includes(hit.evidence) || !lines[hit.start_line - 1]?.includes(hit.evidence.split('\n')[0]))
258
+ continue;
259
+ const duplicate = [...opts.staticFindings, ...extra].some(f => f.mechanism_id === hit.mechanism_id && f.scope.source_locations.some(l => l.path === rel && l.start_line === hit.start_line));
260
+ if (duplicate)
261
+ continue;
262
+ const candidate = toResourceFindingCandidate({
263
+ mechanism_id: hit.mechanism_id,
264
+ primary_domain: hit.primary_domain,
265
+ admission_domain: hit.primary_domain,
266
+ title: hit.title, rel_path: rel, start_line: hit.start_line, end_line: hit.start_line,
267
+ language: /\.tsx?$/.test(rel) ? 'typescript' : 'javascript',
268
+ detector_id: 'js.llm.resource_review', detector_version: '0.1.0',
269
+ }, opts.projectId);
270
+ if (candidate) {
271
+ if (candidate.optimization && hit.recommended_fix)
272
+ candidate.optimization.summary = hit.recommended_fix;
273
+ extra.push(candidate);
274
+ }
275
+ }
276
+ filesReviewed += 1;
277
+ }
278
+ catch (err) {
279
+ errors.push(`${rel}: ${err instanceof Error ? err.message : String(err)}`);
280
+ // Authentication, provider errors and timeouts should not repeat for every file.
281
+ break;
282
+ }
283
+ }
284
+ return { findings: filterValidResourceFindings([...opts.staticFindings, ...extra]), filesReviewed, filesPlanned: files.length, errors };
285
+ }
@@ -0,0 +1,6 @@
1
+ export declare function loadAnalyzeRepositoryConfig(projectDir: string): {
2
+ projectId?: string;
3
+ orgSlug?: string;
4
+ apiUrl?: string;
5
+ environment?: string;
6
+ };
@@ -0,0 +1,49 @@
1
+ /** Python-compatible Analyze repository identity and API configuration. */
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { parse } from 'yaml';
5
+ export function loadAnalyzeRepositoryConfig(projectDir) {
6
+ const documents = {};
7
+ for (const name of ['project', 'config']) {
8
+ const path = ['yaml', 'yml', 'json'].map(ext => join(projectDir, '.netgreener', `${name}.${ext}`))
9
+ .find(candidate => existsSync(candidate));
10
+ if (!path)
11
+ continue;
12
+ let data;
13
+ try {
14
+ const raw = readFileSync(path, 'utf8');
15
+ data = path.endsWith('.json') ? JSON.parse(raw) : parse(raw);
16
+ }
17
+ catch {
18
+ throw new Error(`Cannot read Analyze repository configuration: ${path}`);
19
+ }
20
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
21
+ throw new Error(`Analyze repository configuration must be an object: ${path}`);
22
+ }
23
+ documents[name] = data;
24
+ }
25
+ const projectId = documents.project?.project_id;
26
+ if (projectId != null && (typeof projectId !== 'string' && typeof projectId !== 'number'
27
+ || !/^\d+$/.test(String(projectId).trim()) || !Number.isSafeInteger(Number(projectId)) || Number(projectId) <= 0)) {
28
+ throw new Error('Repository project_id must be a positive integer.');
29
+ }
30
+ let apiUrl = typeof documents.config?.api_url === 'string' ? documents.config.api_url.trim() : undefined;
31
+ if (!apiUrl) {
32
+ for (const name of ['.env', '.env.local']) {
33
+ const path = join(projectDir, name);
34
+ if (!existsSync(path))
35
+ continue;
36
+ const match = readFileSync(path, 'utf8').match(/^\s*NETGREENER_API_URL\s*=\s*(.*?)\s*$/m);
37
+ if (match) {
38
+ apiUrl = match[1].replace(/^["']|["']$/g, '').trim();
39
+ break;
40
+ }
41
+ }
42
+ }
43
+ return {
44
+ projectId: projectId == null ? undefined : String(Number(projectId)),
45
+ orgSlug: typeof documents.project?.org_slug === 'string' ? documents.project.org_slug.trim().toLowerCase() : undefined,
46
+ apiUrl: apiUrl?.replace(/\/+$/, ''),
47
+ environment: typeof documents.config?.environment === 'string' ? documents.config.environment.trim().toLowerCase() : undefined,
48
+ };
49
+ }
package/dist/auto.js CHANGED
@@ -3,6 +3,10 @@
3
3
  * Starts NetGreener with runtime mode ``auto`` (persistent vs ephemeral).
4
4
  */
5
5
  import { NetGreener } from './init.js';
6
- NetGreener.init({ runtime: 'auto' });
6
+ import { installMcpClientInstrumentation } from './mcpToolMeter.js';
7
+ const runtime = NetGreener.init({ runtime: 'auto' });
8
+ // Complete optional ESM/CJS patching before dependent application code starts.
9
+ if (runtime.enabled)
10
+ await installMcpClientInstrumentation();
7
11
  export { NetGreener };
8
12
  export default NetGreener;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shared CLI help / version copy for the Node ``netgreener`` CLI.
3
3
  */
4
- export declare const CLI_VERSION = "0.1.8";
4
+ export declare const CLI_VERSION: string;
5
5
  export declare function formatRootHelp(): string;
6
6
  export declare function formatAnalyzeHelp(): string;
7
7
  /** @deprecated Prefer formatOptimizeHelp / formatRunHelp. Kept for older tests. */
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * Shared CLI help / version copy for the Node ``netgreener`` CLI.
3
3
  */
4
- export const CLI_VERSION = '0.1.8';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ // The extension bundles this module beside its own package metadata.
6
+ const bundledPackage = new URL('./package.json', import.meta.url);
7
+ const packageUrl = existsSync(bundledPackage) ? bundledPackage : new URL('../../package.json', import.meta.url);
8
+ export const CLI_VERSION = JSON.parse(readFileSync(packageUrl, 'utf8')).version;
5
9
  export function formatRootHelp() {
6
10
  return `NetGreener Node CLI ${CLI_VERSION}
7
11
 
@@ -33,7 +37,7 @@ Examples:
33
37
  netgreener-analyze ./my-app
34
38
 
35
39
  Notes:
36
- • Analyze is local only (upload=never).
40
+ • Analyze runs static checks + LLM review when logged in/BYOK configured; --no-llm stays offline.
37
41
  • run meters via process runtime; default EXPORT_MODE stays direct.
38
42
  • optimize emits proposals; --apply only for auto_apply_safe + VerificationProvider.
39
43
  • --llm uses shared api_server /optimize/function; --apply-verified for VP-gated writes.
@@ -45,24 +49,29 @@ Analyze: netgreener help analyze
45
49
  `;
46
50
  }
47
51
  export function formatAnalyzeHelp() {
48
- return `Usage: netgreener analyze <projectDir> [options]
49
- (alias) netgreener-analyze <projectDir> [options]
52
+ return `Usage: netgreener analyze [projectDir] [options]
53
+ (alias) netgreener-analyze [projectDir] [options]
50
54
 
51
- Print NetGreener Analyze scaffold output:
55
+ Analyze JavaScript/TypeScript with static checks and bounded LLM review:
52
56
  service_manifest_v0 + resource_finding_v1 candidates (JSON on stdout).
53
57
 
54
- Does not upload and does not modify RunSession / metering pipelines.
58
+ LLM review sends selected source files to your configured provider. Findings are not stored.
59
+ Does not modify RunSession / metering pipelines.
55
60
 
56
61
  Options:
57
- --project-id <id> Stamp project_id on candidates (default: local)
62
+ --project-id <id> Override env/repository project ID (default: local)
58
63
  --paths a,b Explicit repo-relative source paths (comma-separated)
59
64
  --findings-only Emit findings JSON array only
60
65
  --manifest-only Emit service_manifest_v0 JSON only
61
66
  --json-summary Emit netgreener_analyze_gate_summary_v0 only (CI)
62
67
  --fail-on any|<mechanism>[,…] Fail (exit 1) when matching candidates exceed cap
63
68
  --max-at-or-above <n> With --fail-on: allow up to N matches (default 0)
64
- --depth quick|standard|thorough Python-parity LLM budget (default standard; static scan ignores)
65
- --quiet No stderr status lines
69
+ --depth quick|standard|thorough LLM budget: 1 / 5 / 10 files (default standard)
70
+ --llm Require LLM review (managed login or BYOK)
71
+ --no-llm Static analysis only; no network calls
72
+ --output-file <path> Save full local report and notify the editor on completion
73
+ --no-upload Accepted; findings are never uploaded
74
+ --quiet No stderr progress (errors still reported)
66
75
  -h, --help Show this help
67
76
 
68
77
  Examples:
@@ -74,6 +83,14 @@ Examples:
74
83
  netgreener analyze ./app --paths src/server.ts --findings-only
75
84
  netgreener-analyze ./app --manifest-only
76
85
 
86
+ Configuration:
87
+ Project directory defaults to the current folder, like Python Analyze.
88
+ Identity: --project-id > NETGREENER_PROJECT_ID > .netgreener/project.yaml|yml|json.
89
+ API URL: NETGREENER_API_URL > .netgreener/config.yaml|yml|json > project .env > global config.
90
+ Managed login or BYOK: NETGREENER_LLM_PROVIDER, MODEL, KEY, ENDPOINT.
91
+ Providers: openai, azure_openai, anthropic, ollama, custom.
92
+ Ollama/custom endpoints may run without a key. LLM calls time out after 30s.
93
+
77
94
  CI tip: pair --json-summary with --fail-on for gate annotations without upload.
78
95
  `;
79
96
  }
@@ -240,7 +240,7 @@ export async function runRunCli(argv) {
240
240
  }
241
241
  if (!flags.noAnalyze) {
242
242
  process.stderr.write('netgreener run: local analyze (upload=never)…\n');
243
- const analyzeCode = runAnalyzeCli([projectAbs, '--quiet']);
243
+ const analyzeCode = await runAnalyzeCli([projectAbs, '--quiet', '--no-llm']);
244
244
  if (analyzeCode !== 0) {
245
245
  process.stderr.write(`netgreener run: analyze exited ${analyzeCode}\n`);
246
246
  }
package/dist/config.d.ts CHANGED
@@ -20,7 +20,7 @@ export type RuntimeConfig = {
20
20
  tenantLabelClaim: string | null;
21
21
  };
22
22
  /** Established v0 flush / TDP bounds (committed Node runtime foundation). */
23
- export declare const DEFAULT_RUNTIME_FLUSH_MINUTES = 5;
23
+ export declare const DEFAULT_RUNTIME_FLUSH_MINUTES = 1;
24
24
  export declare const MIN_RUNTIME_FLUSH_MINUTES = 1;
25
25
  export declare const MAX_RUNTIME_FLUSH_MINUTES: number;
26
26
  export declare const DEFAULT_ESTIMATE_TDP_WATTS = 65;
package/dist/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Established v0 flush / TDP bounds (committed Node runtime foundation). */
2
- export const DEFAULT_RUNTIME_FLUSH_MINUTES = 5;
2
+ export const DEFAULT_RUNTIME_FLUSH_MINUTES = 1;
3
3
  export const MIN_RUNTIME_FLUSH_MINUTES = 1;
4
4
  export const MAX_RUNTIME_FLUSH_MINUTES = 24 * 60;
5
5
  export const DEFAULT_ESTIMATE_TDP_WATTS = 65;
@@ -14,7 +14,7 @@ export declare function validateExternalApiV0(value: unknown, path?: string): Co
14
14
  export declare function validateMeasurementProvenance(value: unknown, path?: string): ContractResult;
15
15
  /**
16
16
  * Validate a session_metadata fragment Node will upload.
17
- * Requires at least service_runtime_v0 or external_api_v0.
17
+ * Requires runtime resources, external APIs, or MCP observations.
18
18
  */
19
19
  export declare function validateRuntimeSessionMetadata(value: unknown): ContractResult;
20
20
  export type { ExternalApiV0, MeasurementProvenance, RuntimeSessionMetadata, ServiceRuntimeV0, };
@@ -202,7 +202,7 @@ export function validateMeasurementProvenance(value, path = 'measurement_provena
202
202
  }
203
203
  /**
204
204
  * Validate a session_metadata fragment Node will upload.
205
- * Requires at least service_runtime_v0 or external_api_v0.
205
+ * Requires runtime resources, external APIs, or MCP observations.
206
206
  */
207
207
  export function validateRuntimeSessionMetadata(value) {
208
208
  const issues = [];
@@ -211,8 +211,9 @@ export function validateRuntimeSessionMetadata(value) {
211
211
  }
212
212
  const hasRuntime = value.service_runtime_v0 !== undefined;
213
213
  const hasExternal = value.external_api_v0 !== undefined;
214
- if (!hasRuntime && !hasExternal) {
215
- issues.push(issue('session_metadata', 'expected service_runtime_v0 and/or external_api_v0'));
214
+ const hasMcp = value.mcp_tool_v0 !== undefined;
215
+ if (!hasRuntime && !hasExternal && !hasMcp) {
216
+ issues.push(issue('session_metadata', 'expected service_runtime_v0, external_api_v0, or mcp_tool_v0'));
216
217
  }
217
218
  if (hasRuntime) {
218
219
  issues.push(...validateServiceRuntimeV0(value.service_runtime_v0).issues);
@@ -220,6 +221,26 @@ export function validateRuntimeSessionMetadata(value) {
220
221
  if (hasExternal) {
221
222
  issues.push(...validateExternalApiV0(value.external_api_v0).issues);
222
223
  }
224
+ if (hasMcp) {
225
+ const mcp = value.mcp_tool_v0;
226
+ if (!isObject(mcp) || mcp.schema !== 'mcp_tool_v0' || !Array.isArray(mcp.calls) || !mcp.calls.length) {
227
+ issues.push(issue('mcp_tool_v0', 'expected MCP ledger with schema and non-empty calls'));
228
+ }
229
+ else {
230
+ mcp.calls.forEach((call, index) => {
231
+ const path = `mcp_tool_v0.calls[${index}]`;
232
+ if (!isObject(call)) {
233
+ issues.push(issue(path, 'expected object'));
234
+ return;
235
+ }
236
+ requireString(call, 'server', path, issues);
237
+ requireString(call, 'tool', path, issues);
238
+ requireNumber(call, 'duration_ms', path, issues, { nonNegative: true });
239
+ if (typeof call.success !== 'boolean')
240
+ issues.push(issue(`${path}.success`, 'expected boolean'));
241
+ });
242
+ }
243
+ }
223
244
  if (value.measurement_provenance !== undefined) {
224
245
  issues.push(...validateMeasurementProvenance(value.measurement_provenance).issues);
225
246
  }
@@ -5,8 +5,8 @@
5
5
  * Behavior depends primarily on lifecycle. Detection is best-effort;
6
6
  * ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
7
7
  *
8
- * Does not rewrite the persistent collector pipeline. Ephemeral only
9
- * changes flush timing and prefers thin export when EXPORT_MODE is unset.
8
+ * Does not rewrite the persistent collector pipeline. Ephemeral bounds
9
+ * interval timers to active invocations and prefers thin export when unset.
10
10
  */
11
11
  import { type ServerlessPlatformSignal } from './serverlessHints.js';
12
12
  export type RuntimeModePreference = 'auto' | 'persistent' | 'ephemeral';
@@ -19,6 +19,8 @@ export type RuntimeCapabilities = {
19
19
  /** process.cpuUsage / RSS deltas on instrumented hooks. */
20
20
  process_cpu_time: boolean;
21
21
  periodic_flush: boolean;
22
+ /** Interval reporting while the host keeps an invocation active. */
23
+ active_invocation_flush?: boolean;
22
24
  local_durable_spool: boolean;
23
25
  };
24
26
  export type ResolvedRuntimeLifecycle = {
package/dist/lifecycle.js CHANGED
@@ -5,8 +5,8 @@
5
5
  * Behavior depends primarily on lifecycle. Detection is best-effort;
6
6
  * ``NETGREENER_RUNTIME`` / ``init({ runtime })`` always wins.
7
7
  *
8
- * Does not rewrite the persistent collector pipeline. Ephemeral only
9
- * changes flush timing and prefers thin export when EXPORT_MODE is unset.
8
+ * Does not rewrite the persistent collector pipeline. Ephemeral bounds
9
+ * interval timers to active invocations and prefers thin export when unset.
10
10
  */
11
11
  import { detectServerlessPlatformSignals, } from './serverlessHints.js';
12
12
  function readModePreference(env, override) {
@@ -46,6 +46,7 @@ function capabilitiesFor(lifecycle) {
46
46
  gpu_sampling: false,
47
47
  process_cpu_time: true,
48
48
  periodic_flush: false,
49
+ active_invocation_flush: true,
49
50
  local_durable_spool: false,
50
51
  };
51
52
  }
@@ -80,7 +81,7 @@ export function resolveLifecycle(opts = {}) {
80
81
  }
81
82
  else if (hint.detected) {
82
83
  lifecycle = 'ephemeral';
83
- notes.push('auto: serverless host signal → ephemeral lifecycle (invoke-end flush; no periodic timer)');
84
+ notes.push('auto: serverless host signal → ephemeral lifecycle (intervals while active; final partial window at invoke end)');
84
85
  }
85
86
  else {
86
87
  lifecycle = 'persistent';
@@ -95,7 +96,7 @@ export function resolveLifecycle(opts = {}) {
95
96
  notes.push(`container/platform signal: ${containerPlatform} (lifecycle remains ${lifecycle})`);
96
97
  }
97
98
  if (lifecycle === 'ephemeral') {
98
- notes.push('ephemeral: prefer NETGREENER_EXPORT_MODE=thin when unset; flush at invoke/request idle boundary');
99
+ notes.push('ephemeral: interval reporting only during active invocations; flush final partial window at invoke/request idle boundary');
99
100
  }
100
101
  return {
101
102
  mode,
@@ -7,8 +7,8 @@
7
7
  *
8
8
  * The counter is this process only. Warn is the default. Block is opt-in and
9
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.
10
+ * Await installMcpClientInstrumentation before using the supported MCP client.
11
+ * Both ESM and CommonJS SDK clients use the existing ledger and call context.
12
12
  *
13
13
  * Raw tool arguments, results, and HTTP bodies are not stored.
14
14
  */
@@ -92,10 +92,9 @@ export declare function httpDurationMs(externalV0: Record<string, unknown> | nul
92
92
  export declare function mcpDurationMs(mcpV0: Record<string, unknown> | null | undefined, failedOnly?: boolean): number;
93
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
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.
95
+ /** Optional SDK hook. Await before the first call; false means no active hook.
96
+ * Arguments, results, errors, transport URLs and connection secrets are not stored.
97
+ * Server identity is the negotiated name, or unknown before initialization.
99
98
  */
100
- export declare function installMcpClientInstrumentation(): boolean;
99
+ export declare function installMcpClientInstrumentation(): Promise<boolean>;
101
100
  export declare function _resetMcpToolMeterForTests(): void;