@clear-capabilities/agentic-security-scanner 0.149.4 → 0.150.2
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 +138 -0
- package/bin/agentic-security.js +533 -2
- package/dist/1122.index.js +16 -16
- package/dist/1208.index.js +23 -0
- package/dist/1301.index.js +3 -3
- package/dist/1310.index.js +3161 -0
- package/dist/1379.index.js +3 -3
- package/dist/1444.index.js +3 -3
- package/dist/1660.index.js +1 -1
- package/dist/1700.index.js +5 -5
- package/dist/1905.index.js +107 -12
- package/dist/1920.index.js +10 -10
- package/dist/2238.index.js +4 -4
- package/dist/2271.index.js +3 -3
- package/dist/2432.index.js +8 -8
- package/dist/2659.index.js +1 -1
- package/dist/2826.index.js +2 -2
- package/dist/2830.index.js +3 -3
- package/dist/2923.index.js +1 -1
- package/dist/3001.index.js +4 -4
- package/dist/3117.index.js +4 -4
- package/dist/3180.index.js +9 -9
- package/dist/3276.index.js +1 -1
- package/dist/3415.index.js +1 -1
- package/dist/3499.index.js +1 -1
- package/dist/3518.index.js +4 -4
- package/dist/3736.index.js +7 -7
- package/dist/3839.index.js +4 -4
- package/dist/4113.index.js +441 -418
- package/dist/4265.index.js +4 -4
- package/dist/4384.index.js +8 -3
- package/dist/4399.index.js +292 -0
- package/dist/4547.index.js +2 -2
- package/dist/4863.index.js +6 -6
- package/dist/4970.index.js +2 -2
- package/dist/5051.index.js +15 -15
- package/dist/5144.index.js +4 -4
- package/dist/5333.index.js +8 -8
- package/dist/5343.index.js +2 -2
- package/dist/5350.index.js +6 -6
- package/dist/5561.index.js +1 -1
- package/dist/5637.index.js +10 -5
- package/dist/5724.index.js +21642 -0
- package/dist/5756.index.js +588 -0
- package/dist/5830.index.js +3 -3
- package/dist/6257.index.js +170 -0
- package/dist/6626.index.js +5 -5
- package/dist/6662.index.js +1 -1
- package/dist/6675.index.js +4 -4
- package/dist/6730.index.js +10 -10
- package/dist/6829.index.js +4 -4
- package/dist/6944.index.js +2 -2
- package/dist/6994.index.js +143 -0
- package/dist/7039.index.js +541 -0
- package/dist/7178.index.js +11 -6
- package/dist/7227.index.js +3 -3
- package/dist/7552.index.js +2 -2
- package/dist/7709.index.js +2 -2
- package/dist/7838.index.js +1037 -0
- package/dist/8218.index.js +4 -4
- package/dist/8476.index.js +4 -4
- package/dist/8513.index.js +8 -8
- package/dist/8520.index.js +1 -1
- package/dist/8752.index.js +4 -4
- package/dist/9207.index.js +2 -2
- package/dist/9220.index.js +5 -5
- package/dist/9390.index.js +6 -6
- package/dist/9503.index.js +2 -2
- package/dist/9560.index.js +3221 -0
- package/dist/957.index.js +127 -0
- package/dist/9801.index.js +1 -1
- package/dist/9824.index.js +5 -5
- package/dist/agentic-security.mjs +23 -23
- package/dist/agentic-security.mjs.sha256 +1 -1
- package/package.json +4 -3
- package/src/discovery/disprove.js +6 -1
- package/src/discovery/hunter.js +10 -1
- package/src/discovery/llm-invoke.js +77 -0
- package/src/egress/policy.js +11 -1
- package/src/egress/redact.js +1 -1
- package/src/engine.js +37 -1
- package/src/llm-validator/agent-loop.js +215 -0
- package/src/llm-validator/agent-tools.js +271 -0
- package/src/llm-validator/explain-proposal.js +106 -0
- package/src/llm-validator/fix-proposal.js +149 -0
- package/src/llm-validator/index.js +51 -3
- package/src/llm-validator/model-capabilities.js +269 -0
- package/src/llm-validator/model-probe.js +232 -0
- package/src/llm-validator/model-status.js +27 -0
- package/src/llm-validator/ollama-provider.js +382 -0
- package/src/llm-validator/oom-feedback.js +69 -0
- package/src/llm-validator/poc-proposal.js +122 -0
- package/src/llm-validator/providers.js +75 -0
- package/src/llm-validator/redact.js +177 -11
- package/src/report/index.js +33 -0
- package/src/sast/java-ast-folding.js +18 -2
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Model family hints, RAM-aware memory profiles, and the memory-admission
|
|
2
|
+
// check for the Ollama provider (agentic-security-ollama-offline-prd.md
|
|
3
|
+
// §13, §14, §15, §22.3, §30).
|
|
4
|
+
//
|
|
5
|
+
// FAMILY HINTS ARE DEFAULTS, NEVER AUTHORITY (PRD §12/§13). A name like
|
|
6
|
+
// `gemma4:e2b` tells us nothing Ollama itself won't confirm — it only lets the
|
|
7
|
+
// harness suggest a sane default before any network call. If a model actually
|
|
8
|
+
// installed under a family-hinted name lacks a capability the hint implied,
|
|
9
|
+
// the runtime probe (model-probe.js, added when tool-calling/structured-output
|
|
10
|
+
// probing lands) always wins. This module only classifies and estimates; it
|
|
11
|
+
// never asserts a capability is present.
|
|
12
|
+
//
|
|
13
|
+
// MEMORY NUMBERS ARE ESTIMATES, NOT PROMISES (PRD §22.3, §14.1). Ollama
|
|
14
|
+
// artifact sizes and this module's headroom reserves are best-effort figures
|
|
15
|
+
// sourced from what Ollama currently publishes; they exist so the harness can
|
|
16
|
+
// fail BEFORE an OS-level OOM, not so it can claim an exact answer. Every
|
|
17
|
+
// admission decision leaves a stated safety margin rather than trying to pack
|
|
18
|
+
// memory to the byte.
|
|
19
|
+
|
|
20
|
+
import * as os from 'node:os';
|
|
21
|
+
import { priorOOMFor } from './oom-feedback.js';
|
|
22
|
+
|
|
23
|
+
// PRD §12/§13 FR-1203 — non-authoritative family hint from a model name.
|
|
24
|
+
// Longest/most-specific pattern first so `qwen3.5:4b` doesn't fall through to
|
|
25
|
+
// the bare `qwen` bucket.
|
|
26
|
+
const FAMILY_PATTERNS = [
|
|
27
|
+
[/^qwen3\.5/i, 'qwen3.5'],
|
|
28
|
+
[/^qwen3-coder-next/i, 'qwen3-coder-next'],
|
|
29
|
+
[/^qwen3-coder/i, 'qwen3-coder'],
|
|
30
|
+
[/^qwen2\.5-coder/i, 'qwen2.5-coder'],
|
|
31
|
+
[/^qwen3/i, 'qwen3'],
|
|
32
|
+
[/^qwen/i, 'qwen'],
|
|
33
|
+
[/^gemma4/i, 'gemma4'],
|
|
34
|
+
[/^functiongemma/i, 'functiongemma'],
|
|
35
|
+
[/^gemma3/i, 'gemma3'],
|
|
36
|
+
[/^gemma/i, 'gemma'],
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
/** Non-authoritative family classification for defaults/messaging only. */
|
|
40
|
+
export function classifyModelFamily(modelName) {
|
|
41
|
+
const name = String(modelName || '').trim();
|
|
42
|
+
for (const [re, family] of FAMILY_PATTERNS) if (re.test(name)) return family;
|
|
43
|
+
return 'unknown';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// PRD §13.1 — non-authoritative defaults per family, overridden by any real
|
|
47
|
+
// runtime probe result (model-probe.js). `tools`/`structuredJson`/`thinking`
|
|
48
|
+
// are 'unknown' where Ollama's own behavior varies by specific tag/quant
|
|
49
|
+
// rather than by family alone.
|
|
50
|
+
const FAMILY_CAPABILITY_HINTS = {
|
|
51
|
+
'qwen3.5': { chat: true, structuredJson: true, tools: true, thinking: 'unknown' },
|
|
52
|
+
qwen3: { chat: true, structuredJson: true, tools: true, thinking: 'unknown' },
|
|
53
|
+
'qwen3-coder': { chat: true, structuredJson: true, tools: true, thinking: false },
|
|
54
|
+
'qwen3-coder-next': { chat: true, structuredJson: true, tools: true, thinking: false },
|
|
55
|
+
'qwen2.5-coder': { chat: true, structuredJson: true, tools: 'unknown', thinking: false },
|
|
56
|
+
qwen: { chat: true, structuredJson: 'unknown', tools: 'unknown', thinking: 'unknown' },
|
|
57
|
+
gemma4: { chat: true, structuredJson: true, tools: true, thinking: 'unknown' },
|
|
58
|
+
functiongemma: { chat: true, structuredJson: 'unknown', tools: true, thinking: false },
|
|
59
|
+
gemma3: { chat: true, structuredJson: true, tools: false, thinking: false },
|
|
60
|
+
gemma: { chat: true, structuredJson: 'unknown', tools: 'unknown', thinking: 'unknown' },
|
|
61
|
+
unknown: { chat: true, structuredJson: 'unknown', tools: 'unknown', thinking: 'unknown' },
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Build the PRD §13.1 ModelCapabilities object from a family hint alone
|
|
66
|
+
* (Layer B). Layer A (Ollama's own /api/show metadata) and Layer C (runtime
|
|
67
|
+
* probes) are applied by the caller and override these fields — this
|
|
68
|
+
* function only ever sets `source.familyHint: true`.
|
|
69
|
+
*/
|
|
70
|
+
export function capabilitiesFromFamilyHint(modelName) {
|
|
71
|
+
const family = classifyModelFamily(modelName);
|
|
72
|
+
const hint = FAMILY_CAPABILITY_HINTS[family] || FAMILY_CAPABILITY_HINTS.unknown;
|
|
73
|
+
return {
|
|
74
|
+
chat: hint.chat,
|
|
75
|
+
structuredJson: hint.structuredJson,
|
|
76
|
+
tools: hint.tools,
|
|
77
|
+
thinking: hint.thinking,
|
|
78
|
+
vision: false,
|
|
79
|
+
contextTokens: undefined,
|
|
80
|
+
source: { metadata: false, familyHint: true, runtimeProbe: false },
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ── RAM-aware memory profiles (PRD §14.4, §15.2, §22.3, §30) ───────────────
|
|
85
|
+
|
|
86
|
+
const MB = 1024 * 1024;
|
|
87
|
+
const GB = 1024 * MB;
|
|
88
|
+
|
|
89
|
+
// Best-effort artifact sizes as currently distributed by Ollama, used only to
|
|
90
|
+
// pick a SENSIBLE STARTING recommendation — the real admission decision below
|
|
91
|
+
// uses actually-free memory, not this table. Keep in sync with the PRD's own
|
|
92
|
+
// cited figures; a stale entry only affects the suggested default, never the
|
|
93
|
+
// admission math (which reads real os.freemem()).
|
|
94
|
+
export const KNOWN_MODEL_SIZE_GB = Object.freeze({
|
|
95
|
+
'qwen3.5:2b': 1.7,
|
|
96
|
+
'qwen3.5:4b': 3.4,
|
|
97
|
+
'qwen3.5:9b': 6.6,
|
|
98
|
+
'gemma4:e2b': 7.2,
|
|
99
|
+
'gemma4:12b': 7.6,
|
|
100
|
+
'gemma4:latest': 9.6,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
/** PRD §30 profile presets. `auto` picks between these by detected RAM. */
|
|
104
|
+
export const MEMORY_PROFILES = Object.freeze({
|
|
105
|
+
'8gb': {
|
|
106
|
+
label: '8gb',
|
|
107
|
+
preferredModel: 'qwen3.5:4b',
|
|
108
|
+
fallbackModel: 'qwen3.5:2b',
|
|
109
|
+
initialContextTokens: 4096,
|
|
110
|
+
targetContextTokens: 8192,
|
|
111
|
+
maxConcurrency: 1,
|
|
112
|
+
minFreeRamMb: 1536,
|
|
113
|
+
},
|
|
114
|
+
'16gb-qwen': {
|
|
115
|
+
label: '16gb-qwen',
|
|
116
|
+
preferredModel: 'qwen3.5:9b',
|
|
117
|
+
fallbackModel: 'qwen3.5:4b',
|
|
118
|
+
initialContextTokens: 16384,
|
|
119
|
+
targetContextTokens: 32768,
|
|
120
|
+
maxConcurrency: 1,
|
|
121
|
+
minFreeRamMb: 2048,
|
|
122
|
+
},
|
|
123
|
+
'16gb-gemma': {
|
|
124
|
+
label: '16gb-gemma',
|
|
125
|
+
preferredModel: 'gemma4:e2b',
|
|
126
|
+
fallbackModel: 'qwen3.5:4b',
|
|
127
|
+
initialContextTokens: 8192,
|
|
128
|
+
targetContextTokens: 16384,
|
|
129
|
+
maxConcurrency: 1,
|
|
130
|
+
minFreeRamMb: 2048,
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* PRD §22.3 — detect total/available system RAM. Thin wrapper over `os` so
|
|
136
|
+
* tests can inject fake values without mocking the `os` module globally.
|
|
137
|
+
*/
|
|
138
|
+
export function detectSystemMemory({ totalBytes, freeBytes } = {}) {
|
|
139
|
+
return {
|
|
140
|
+
totalBytes: Number.isFinite(totalBytes) ? totalBytes : os.totalmem(),
|
|
141
|
+
freeBytes: Number.isFinite(freeBytes) ? freeBytes : os.freemem(),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Pick the RAM tier ('8gb' | '16gb') a machine falls into. Anything under
|
|
147
|
+
* ~9 GB total is treated as the 8 GB tier — real "8 GB" machines report
|
|
148
|
+
* slightly less than 8*1024^3 bytes to userspace (firmware/GPU reservations),
|
|
149
|
+
* so a hard `< 8*GB` cutoff would misclassify real 8 GB hardware as unknown.
|
|
150
|
+
*/
|
|
151
|
+
export function detectMemoryTier(totalBytes) {
|
|
152
|
+
if (!Number.isFinite(totalBytes) || totalBytes <= 0) return 'unknown';
|
|
153
|
+
if (totalBytes < 9 * GB) return '8gb';
|
|
154
|
+
return '16gb';
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* PRD §22.3 admission algorithm: does `contextTokens` at `model` fit in
|
|
159
|
+
* currently-free memory with the configured reserve intact?
|
|
160
|
+
*
|
|
161
|
+
* This is deliberately conservative and coarse (PRD "avoid pretending memory
|
|
162
|
+
* estimates are exact"): model residency is estimated from KNOWN_MODEL_SIZE_GB
|
|
163
|
+
* when available (falling back to a pessimistic 8 GB assumption for an
|
|
164
|
+
* unrecognized tag so an unknown model never LOOKS safer than a known large
|
|
165
|
+
* one), and KV-cache growth is approximated as a fixed per-1K-token cost
|
|
166
|
+
* rather than modeled per-architecture — real KV cache size depends on layer
|
|
167
|
+
* count/head count/quantization the harness cannot know without Ollama's own
|
|
168
|
+
* runtime numbers.
|
|
169
|
+
*/
|
|
170
|
+
const ESTIMATED_KV_CACHE_MB_PER_1K_TOKENS = 32; // conservative, model-independent approximation
|
|
171
|
+
const RUNTIME_OVERHEAD_MB = 512; // Ollama server + OS scheduler slack, independent of model size
|
|
172
|
+
|
|
173
|
+
export function evaluateMemoryAdmission({
|
|
174
|
+
modelName,
|
|
175
|
+
contextTokens,
|
|
176
|
+
freeBytes,
|
|
177
|
+
minFreeRamMb,
|
|
178
|
+
modelSizeGb,
|
|
179
|
+
} = {}) {
|
|
180
|
+
const sizeGb = Number.isFinite(modelSizeGb) ? modelSizeGb : (KNOWN_MODEL_SIZE_GB[modelName] ?? 8);
|
|
181
|
+
const modelMb = sizeGb * 1024;
|
|
182
|
+
const kvCacheMb = (Number(contextTokens) || 0) / 1000 * ESTIMATED_KV_CACHE_MB_PER_1K_TOKENS;
|
|
183
|
+
const requiredMb = modelMb + kvCacheMb + RUNTIME_OVERHEAD_MB + (Number(minFreeRamMb) || 0);
|
|
184
|
+
const freeMb = (Number(freeBytes) || 0) / MB;
|
|
185
|
+
const admitted = freeMb >= requiredMb;
|
|
186
|
+
return {
|
|
187
|
+
admitted,
|
|
188
|
+
freeMb: Math.round(freeMb),
|
|
189
|
+
requiredMb: Math.round(requiredMb),
|
|
190
|
+
modelEstimateMb: Math.round(modelMb),
|
|
191
|
+
kvCacheEstimateMb: Math.round(kvCacheMb),
|
|
192
|
+
reserveMb: Number(minFreeRamMb) || 0,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Full recommendation flow (PRD §22 "Memory admission algorithm"):
|
|
198
|
+
* try the profile's preferred context, shrink it, then fall back to the
|
|
199
|
+
* profile's smaller model, before ever declaring the profile unusable.
|
|
200
|
+
* Never recommends cloud — the worst outcome this function can return is
|
|
201
|
+
* `{admitted:false}` with a human-readable explanation, which callers treat
|
|
202
|
+
* as "run deterministic-only" (PRD §23.4).
|
|
203
|
+
*/
|
|
204
|
+
export function recommendAdmission(opts = {}) {
|
|
205
|
+
const result = _recommendAdmissionCore(opts);
|
|
206
|
+
// Adversarial-review fix (2026-09): a memory-admission ESTIMATE that
|
|
207
|
+
// actually caused a real OOM (ollama-provider.js's callOllamaChat now
|
|
208
|
+
// records this via oom-feedback.js) used to have no way to affect a
|
|
209
|
+
// future admission decision for the SAME model on the SAME machine — the
|
|
210
|
+
// exact same "admitted: true" would repeat forever. This does not
|
|
211
|
+
// recalibrate the underlying estimate (that needs real hardware variety
|
|
212
|
+
// one machine's observed failures can't substitute for); it attaches an
|
|
213
|
+
// honest warning so the decision is no longer presented with unqualified
|
|
214
|
+
// confidence.
|
|
215
|
+
const chosenModel = result.model || opts.requestedModel;
|
|
216
|
+
const prior = chosenModel ? priorOOMFor(chosenModel) : null;
|
|
217
|
+
if (prior) {
|
|
218
|
+
return {
|
|
219
|
+
...result,
|
|
220
|
+
priorOOMWarning: `'${chosenModel}' has previously failed with an out-of-memory error on this machine ` +
|
|
221
|
+
`(${prior.count} time${prior.count === 1 ? '' : 's'}, most recently ${new Date(prior.lastAt).toISOString()}). ` +
|
|
222
|
+
'The memory estimate below may be optimistic for your hardware.',
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function _recommendAdmissionCore({ profile, freeBytes, requestedContextTokens, requestedModel } = {}) {
|
|
229
|
+
const p = MEMORY_PROFILES[profile];
|
|
230
|
+
if (!p) return { admitted: false, reason: `unknown memory profile '${profile}'` };
|
|
231
|
+
|
|
232
|
+
const model = requestedModel || p.preferredModel;
|
|
233
|
+
const attempts = [];
|
|
234
|
+
|
|
235
|
+
// 1. Requested (or target) context at the requested/preferred model.
|
|
236
|
+
const primaryContext = Number.isFinite(requestedContextTokens) ? requestedContextTokens : p.targetContextTokens;
|
|
237
|
+
let check = evaluateMemoryAdmission({ modelName: model, contextTokens: primaryContext, freeBytes, minFreeRamMb: p.minFreeRamMb });
|
|
238
|
+
attempts.push({ model, contextTokens: primaryContext, ...check });
|
|
239
|
+
if (check.admitted) return { admitted: true, model, contextTokens: primaryContext, attempts };
|
|
240
|
+
|
|
241
|
+
// 2. Reduce context to the profile's conservative initial value first —
|
|
242
|
+
// PRD FR-2104: "shrink context before declaring an otherwise compatible
|
|
243
|
+
// model unusable."
|
|
244
|
+
if (primaryContext !== p.initialContextTokens) {
|
|
245
|
+
check = evaluateMemoryAdmission({ modelName: model, contextTokens: p.initialContextTokens, freeBytes, minFreeRamMb: p.minFreeRamMb });
|
|
246
|
+
attempts.push({ model, contextTokens: p.initialContextTokens, ...check });
|
|
247
|
+
if (check.admitted) return { admitted: true, model, contextTokens: p.initialContextTokens, attempts, reducedContext: true };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 3. Fall back to the profile's smaller model at its initial context.
|
|
251
|
+
if (p.fallbackModel && p.fallbackModel !== model) {
|
|
252
|
+
check = evaluateMemoryAdmission({ modelName: p.fallbackModel, contextTokens: p.initialContextTokens, freeBytes, minFreeRamMb: p.minFreeRamMb });
|
|
253
|
+
attempts.push({ model: p.fallbackModel, contextTokens: p.initialContextTokens, ...check });
|
|
254
|
+
if (check.admitted) {
|
|
255
|
+
return {
|
|
256
|
+
admitted: true, model: p.fallbackModel, contextTokens: p.initialContextTokens, attempts,
|
|
257
|
+
reducedContext: true, fellBackToSmallerModel: true,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// 4. Nothing fits — deterministic-only, never cloud.
|
|
263
|
+
return {
|
|
264
|
+
admitted: false,
|
|
265
|
+
attempts,
|
|
266
|
+
reason: `No local model/context combination fit in available memory with the configured reserve. ` +
|
|
267
|
+
`Recommend deterministic-only scanning, or free memory before retrying.`,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// PRD §13.2 — the three-layer model capability detection strategy.
|
|
2
|
+
//
|
|
3
|
+
// LAYER A (metadata) is the cheapest and most authoritative: Ollama's own
|
|
4
|
+
// `/api/show` response, when it reports a `capabilities` array, is not a
|
|
5
|
+
// guess. LAYER B (model-capabilities.js's family hint) is a non-authoritative
|
|
6
|
+
// default used only where Layer A is silent. LAYER C (this module's
|
|
7
|
+
// `probeStructuredOutput`/`probeToolCalling`) is the most expensive — it
|
|
8
|
+
// consumes real inference time — so it is OPT-IN (the caller decides when
|
|
9
|
+
// "necessary" per the PRD's own wording), never run implicitly on every
|
|
10
|
+
// `models doctor`/`models inspect` invocation.
|
|
11
|
+
//
|
|
12
|
+
// PRECEDENCE: Layer C overrides Layer A overrides Layer B, field by field. A
|
|
13
|
+
// field only ever gets overridden by a MORE authoritative layer that actually
|
|
14
|
+
// has an opinion — a probe that couldn't run (offline/timeout) leaves the
|
|
15
|
+
// field exactly as the layer below it set it, it never downgrades to
|
|
16
|
+
// 'unknown'.
|
|
17
|
+
//
|
|
18
|
+
// CACHE KEY = Ollama version + model digest + model name (PRD §13.2 exactly).
|
|
19
|
+
// Digest is load-bearing: `ollama pull` replacing a tag's underlying weights
|
|
20
|
+
// must invalidate the cache even though the name/tag string is unchanged.
|
|
21
|
+
// Same disk-cache directory convention as sca/sigstore-verify.js and
|
|
22
|
+
// engine.js's OSV cache (`~/.claude/agentic-security/<name>/`).
|
|
23
|
+
//
|
|
24
|
+
// TTL + force-reprobe (adversarial-review fix, 2026-09). The key-based
|
|
25
|
+
// invalidation above is real but not complete: this module's own comment
|
|
26
|
+
// used to claim the entry is safe "forever" because the key changes when
|
|
27
|
+
// the model does — but `/api/show` doesn't expose a digest on every Ollama
|
|
28
|
+
// version (falls back to model NAME alone then, a few lines below), so a
|
|
29
|
+
// same-tag re-pull, or simply an unlucky single-trial probe the first time
|
|
30
|
+
// (see probeStructuredOutput/probeToolCalling's own single-call design),
|
|
31
|
+
// had no way to ever self-correct short of a user manually deleting a file
|
|
32
|
+
// under `~/.claude/agentic-security/`. Two independent fixes, since either
|
|
33
|
+
// alone leaves a real gap: a default TTL as a safety net for the case
|
|
34
|
+
// nobody notices, and an explicit `force` option (`models test --force`)
|
|
35
|
+
// for the case someone DOES suspect a stale answer and wants it right now.
|
|
36
|
+
|
|
37
|
+
import * as fs from 'node:fs';
|
|
38
|
+
import * as path from 'node:path';
|
|
39
|
+
import * as os from 'node:os';
|
|
40
|
+
import * as crypto from 'node:crypto';
|
|
41
|
+
import { callOllamaStructured, callOllamaChat, showOllamaModel, getOllamaVersion } from './ollama-provider.js';
|
|
42
|
+
import { capabilitiesFromFamilyHint } from './model-capabilities.js';
|
|
43
|
+
|
|
44
|
+
const CACHE_DIR = path.join(os.homedir(), '.claude', 'agentic-security', 'ollama-capability-cache');
|
|
45
|
+
|
|
46
|
+
// Default safety-net TTL: 30 days. Not the primary invalidation mechanism
|
|
47
|
+
// (the key is) — a backstop for the cases the key can't see: a same-tag
|
|
48
|
+
// re-pull on an Ollama version that doesn't expose a digest, or a single
|
|
49
|
+
// unlucky probe trial that happened to pass/fail against the model's true
|
|
50
|
+
// behavior. Overridable for anyone who wants a tighter or looser bound.
|
|
51
|
+
export const DEFAULT_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
52
|
+
|
|
53
|
+
function _ensureCacheDir() { try { fs.mkdirSync(CACHE_DIR, { recursive: true }); } catch {} }
|
|
54
|
+
function _cacheKey(ollamaVersion, modelDigest, modelName) {
|
|
55
|
+
return crypto.createHash('sha256').update(`${ollamaVersion}::${modelDigest}::${modelName}`).digest('hex');
|
|
56
|
+
}
|
|
57
|
+
function _cachePath(key) { return path.join(CACHE_DIR, key + '.json'); }
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @returns {object|null} the cached probe RESULT (not the envelope), or
|
|
61
|
+
* `null` on a miss, a parse failure, OR an entry older than `ttlMs`.
|
|
62
|
+
*/
|
|
63
|
+
function _readProbeCache(key, ttlMs) {
|
|
64
|
+
let envelope;
|
|
65
|
+
try { envelope = JSON.parse(fs.readFileSync(_cachePath(key), 'utf8')); } catch { return null; }
|
|
66
|
+
// Backward-compatible with a pre-TTL cache file that was just the bare
|
|
67
|
+
// result object (no `probedAt`) — treat an entry with no timestamp as
|
|
68
|
+
// fresh rather than discarding every cache written before this fix.
|
|
69
|
+
if (envelope && typeof envelope === 'object' && 'probedAt' in envelope && 'result' in envelope) {
|
|
70
|
+
if (Number.isFinite(ttlMs) && ttlMs > 0 && Date.now() - envelope.probedAt > ttlMs) return null;
|
|
71
|
+
return envelope.result;
|
|
72
|
+
}
|
|
73
|
+
return envelope;
|
|
74
|
+
}
|
|
75
|
+
function _writeProbeCache(key, value) {
|
|
76
|
+
_ensureCacheDir();
|
|
77
|
+
try { fs.writeFileSync(_cachePath(key), JSON.stringify({ probedAt: Date.now(), result: value })); } catch {}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* PRD §13.2 Layer A — parse `/api/show`'s response into the subset of
|
|
82
|
+
* ModelCapabilities it can actually speak to. A field this layer has no
|
|
83
|
+
* opinion on is omitted (not set to `false`) so the caller's merge never
|
|
84
|
+
* mistakes silence for a negative.
|
|
85
|
+
*/
|
|
86
|
+
export function capabilitiesFromShowMetadata(show) {
|
|
87
|
+
const out = { source: { metadata: true } };
|
|
88
|
+
if (Array.isArray(show?.capabilities) && show.capabilities.length > 0) {
|
|
89
|
+
const caps = show.capabilities;
|
|
90
|
+
out.chat = caps.includes('completion') || caps.includes('chat');
|
|
91
|
+
out.tools = caps.includes('tools');
|
|
92
|
+
out.vision = caps.includes('vision');
|
|
93
|
+
out.thinking = caps.includes('thinking');
|
|
94
|
+
}
|
|
95
|
+
const modelInfo = show?.modelInfo;
|
|
96
|
+
if (modelInfo && typeof modelInfo === 'object') {
|
|
97
|
+
const ctxKey = Object.keys(modelInfo).find((k) => k.endsWith('.context_length'));
|
|
98
|
+
if (ctxKey && Number.isFinite(modelInfo[ctxKey])) out.contextTokens = modelInfo[ctxKey];
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* PRD §13.2 Layer C — structured-output probe. A tiny schema, a request for
|
|
105
|
+
* `{"ok": true}`, verified end to end through the SAME
|
|
106
|
+
* callOllamaStructured() bounded-retry path every real structured call uses
|
|
107
|
+
* (not a bespoke lighter-weight check that could disagree with production
|
|
108
|
+
* behavior).
|
|
109
|
+
*/
|
|
110
|
+
const PROBE_SCHEMA = { type: 'object', required: ['ok'], properties: { ok: { type: 'boolean' } } };
|
|
111
|
+
|
|
112
|
+
export async function probeStructuredOutput({ host, model, timeouts, keepAlive } = {}) {
|
|
113
|
+
const r = await callOllamaStructured({
|
|
114
|
+
host, model,
|
|
115
|
+
messages: [{ role: 'user', content: 'Reply with ONLY a JSON object: {"ok": true}' }],
|
|
116
|
+
schema: PROBE_SCHEMA,
|
|
117
|
+
validateFn: (obj) => (obj && obj.ok === true ? { ok: true, value: obj } : { ok: false }),
|
|
118
|
+
keepAlive, timeouts,
|
|
119
|
+
});
|
|
120
|
+
if (r.ok) return { supported: true };
|
|
121
|
+
// A transport-level failure (server unreachable, timed out) tells us
|
|
122
|
+
// nothing about the MODEL's capability — leave it 'unknown' rather than
|
|
123
|
+
// reporting a false negative for an offline/slow server.
|
|
124
|
+
if (['ollama-unreachable', 'ollama-not-running', 'ollama-timeout', 'ollama-model-not-installed'].includes(r.code)) {
|
|
125
|
+
return { supported: 'unknown', reason: r.reason || r.code };
|
|
126
|
+
}
|
|
127
|
+
return { supported: false, reason: r.reason || r.code };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* PRD §13.2 Layer C — tool-calling probe. One harmless `echo_capability_probe`
|
|
132
|
+
* function; success is Ollama returning a structured `tool_calls` entry
|
|
133
|
+
* naming it, not a check on what the model chose to reply with in prose.
|
|
134
|
+
*/
|
|
135
|
+
const PROBE_TOOL = {
|
|
136
|
+
type: 'function',
|
|
137
|
+
function: {
|
|
138
|
+
name: 'echo_capability_probe',
|
|
139
|
+
description: 'Echo back the given value. Used only to test whether this model supports tool calling.',
|
|
140
|
+
parameters: { type: 'object', required: ['value'], properties: { value: { type: 'string' } } },
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export async function probeToolCalling({ host, model, timeouts, keepAlive } = {}) {
|
|
145
|
+
const r = await callOllamaChat({
|
|
146
|
+
host, model,
|
|
147
|
+
messages: [{ role: 'user', content: 'Call the echo_capability_probe function with value set to "probe-ok". Reply with nothing else.' }],
|
|
148
|
+
tools: [PROBE_TOOL],
|
|
149
|
+
keepAlive, timeouts,
|
|
150
|
+
});
|
|
151
|
+
if (!r.ok) {
|
|
152
|
+
if (['ollama-unreachable', 'ollama-not-running', 'ollama-timeout', 'ollama-model-not-installed'].includes(r.code)) {
|
|
153
|
+
return { supported: 'unknown', reason: r.reason || r.code };
|
|
154
|
+
}
|
|
155
|
+
return { supported: false, reason: r.reason || r.code };
|
|
156
|
+
}
|
|
157
|
+
const calls = r.result.toolCalls || [];
|
|
158
|
+
const called = calls.some((c) => c?.function?.name === 'echo_capability_probe');
|
|
159
|
+
return called ? { supported: true } : { supported: false, reason: 'model did not emit a tool_calls entry for the probe function' };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function _mergeLayer(base, overlay, sourceFlag) {
|
|
163
|
+
const merged = { ...base };
|
|
164
|
+
let touched = false;
|
|
165
|
+
for (const field of ['chat', 'structuredJson', 'tools', 'thinking', 'vision', 'contextTokens']) {
|
|
166
|
+
if (overlay[field] !== undefined) { merged[field] = overlay[field]; touched = true; }
|
|
167
|
+
}
|
|
168
|
+
if (touched) merged.source = { ...merged.source, [sourceFlag]: true };
|
|
169
|
+
return merged;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Orchestrates all three layers (PRD §13.2) with caching (PRD: "so startup
|
|
174
|
+
* does not repeatedly consume inference time"). `probe: true` opts into
|
|
175
|
+
* Layer C — omitted or false, this returns Layer A+B only, which is what
|
|
176
|
+
* every non-probing caller (models list/inspect/doctor's default path)
|
|
177
|
+
* should use, since Layer C spends real inference time on the user's
|
|
178
|
+
* machine.
|
|
179
|
+
*
|
|
180
|
+
* `force: true` (adversarial-review fix, 2026-09 — `models test --force`)
|
|
181
|
+
* skips reading the cache — always runs a fresh probe and overwrites
|
|
182
|
+
* whatever was there. `ttlMs` (default 30 days, `DEFAULT_CACHE_TTL_MS`)
|
|
183
|
+
* bounds how long a cached entry is trusted without either; pass `0`/
|
|
184
|
+
* `Infinity` to disable the TTL safety net entirely and rely on the key
|
|
185
|
+
* alone, matching this module's original design intent.
|
|
186
|
+
*
|
|
187
|
+
* @returns {{ok:true, capabilities:object, cached:boolean} | {ok:false, code, reason}}
|
|
188
|
+
*/
|
|
189
|
+
export async function getModelCapabilities({ host, model, env = process.env, probe = false, force = false, ttlMs = DEFAULT_CACHE_TTL_MS, timeouts, keepAlive } = {}) {
|
|
190
|
+
let capabilities = capabilitiesFromFamilyHint(model);
|
|
191
|
+
|
|
192
|
+
const show = await showOllamaModel({ host, model, timeouts });
|
|
193
|
+
if (show.ok) {
|
|
194
|
+
capabilities = _mergeLayer(capabilities, capabilitiesFromShowMetadata(show), 'metadata');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (!probe) {
|
|
198
|
+
return { ok: true, capabilities, cached: false };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const versionResult = await getOllamaVersion({ host, timeouts });
|
|
202
|
+
const ollamaVersion = versionResult.ok ? versionResult.version : 'unknown-version';
|
|
203
|
+
// The digest is whatever Layer A's /api/show reported under `details`
|
|
204
|
+
// (Ollama does not expose it on /api/show consistently across versions —
|
|
205
|
+
// fall back to the model name alone, which still invalidates on a tag
|
|
206
|
+
// change, just not on a same-tag re-pull).
|
|
207
|
+
const modelDigest = show.ok && show.details?.digest ? show.details.digest : 'unknown-digest';
|
|
208
|
+
const cacheKey = _cacheKey(ollamaVersion, modelDigest, model);
|
|
209
|
+
|
|
210
|
+
const cached = force ? null : _readProbeCache(cacheKey, ttlMs);
|
|
211
|
+
if (cached) {
|
|
212
|
+
return { ok: true, capabilities: _mergeLayer(capabilities, cached, 'runtimeProbe'), cached: true };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const [structured, tools] = await Promise.all([
|
|
216
|
+
probeStructuredOutput({ host, model, timeouts, keepAlive }),
|
|
217
|
+
probeToolCalling({ host, model, timeouts, keepAlive }),
|
|
218
|
+
]);
|
|
219
|
+
|
|
220
|
+
const probeResult = {};
|
|
221
|
+
if (structured.supported !== 'unknown') probeResult.structuredJson = structured.supported;
|
|
222
|
+
if (tools.supported !== 'unknown') probeResult.tools = tools.supported;
|
|
223
|
+
|
|
224
|
+
// Only cache a probe that actually resolved something — an all-'unknown'
|
|
225
|
+
// result (server unreachable mid-probe) would otherwise poison the cache
|
|
226
|
+
// with a permanent non-answer.
|
|
227
|
+
if (Object.keys(probeResult).length > 0) _writeProbeCache(cacheKey, probeResult);
|
|
228
|
+
|
|
229
|
+
return { ok: true, capabilities: _mergeLayer(capabilities, probeResult, 'runtimeProbe'), cached: false };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export const _internals = { CACHE_DIR, _cacheKey, _cachePath };
|
|
@@ -64,3 +64,30 @@ export function summarizeModelStatus(findings) {
|
|
|
64
64
|
}
|
|
65
65
|
return { counts, notApplicable, total: (findings || []).length };
|
|
66
66
|
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* agentic-security-ollama-offline-prd.md §26 — turn a summarizeModelStatus()
|
|
70
|
+
* result into the "AI stages" call/success/refused/failed breakdown a report
|
|
71
|
+
* can render. Reuses the SAME five-state taxonomy every other status
|
|
72
|
+
* consumer already trusts, rather than adding new instrumentation: COMPLETED
|
|
73
|
+
* + MALFORMED + UNAVAILABLE are all outcomes of an ATTEMPTED call (the model
|
|
74
|
+
* was actually asked); POLICY_BLOCKED never reached the network at all, so
|
|
75
|
+
* it is reported as "refused" rather than folded into "calls". DISABLED
|
|
76
|
+
* (nothing configured) contributes to neither — a caller checks that
|
|
77
|
+
* separately (status.counts[MODEL_STATUS.DISABLED] === status.total means
|
|
78
|
+
* "don't render this stage at all").
|
|
79
|
+
*
|
|
80
|
+
* @returns {{calls:number, success:number, refused:number, failed:number}}
|
|
81
|
+
*/
|
|
82
|
+
export function stageSummaryFromModelStatus(status) {
|
|
83
|
+
const c = status?.counts || {};
|
|
84
|
+
const completed = c[MODEL_STATUS.COMPLETED] || 0;
|
|
85
|
+
const malformed = c[MODEL_STATUS.MALFORMED] || 0;
|
|
86
|
+
const unavailable = c[MODEL_STATUS.UNAVAILABLE] || 0;
|
|
87
|
+
return {
|
|
88
|
+
calls: completed + malformed + unavailable,
|
|
89
|
+
success: completed,
|
|
90
|
+
refused: c[MODEL_STATUS.POLICY_BLOCKED] || 0,
|
|
91
|
+
failed: malformed + unavailable,
|
|
92
|
+
};
|
|
93
|
+
}
|