@oaksecurity/aitm 0.0.0-stage → 2.3.0
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/.env.example +11 -0
- package/CHANGELOG.md +100 -0
- package/LICENSE +21 -0
- package/README.md +229 -2
- package/SECURITY.md +49 -0
- package/SPEC.md +304 -0
- package/docs/api.md +332 -0
- package/docs/inputs-and-limits.md +78 -0
- package/docs/usage.md +351 -0
- package/examples/custody-architecture.md +27 -0
- package/package.json +67 -4
- package/src/api/server.js +591 -0
- package/src/api/web.js +38 -0
- package/src/application.js +32 -0
- package/src/assessments.js +37 -0
- package/src/assets/BDOGrotesk-Bold.ttf +0 -0
- package/src/assets/BDOGrotesk-Regular.ttf +0 -0
- package/src/assets/OFL.txt +93 -0
- package/src/assets/README.md +10 -0
- package/src/cli.js +224 -0
- package/src/client.js +88 -0
- package/src/config.js +105 -0
- package/src/doctor.js +128 -0
- package/src/engine/credentials.js +31 -0
- package/src/engine/download.js +135 -0
- package/src/engine/engine.js +783 -0
- package/src/engine/errors.js +23 -0
- package/src/engine/generation.js +121 -0
- package/src/engine/ingest.js +444 -0
- package/src/engine/pdf-layout.js +204 -0
- package/src/engine/pdf-report.js +573 -0
- package/src/engine/prompts.js +82 -0
- package/src/engine/providers.js +476 -0
- package/src/engine/references.js +112 -0
- package/src/engine/report.js +200 -0
- package/src/engine/schema.js +267 -0
- package/src/engine/store.js +115 -0
- package/src/engine/validate.js +397 -0
- package/src/engine/zip.js +70 -0
- package/src/index.js +5 -0
- package/src/source-input.js +32 -0
- package/src/token.js +59 -0
- package/src/tui/app.js +694 -0
- package/src/tui/editor.js +34 -0
- package/src/tui/file-picker.js +111 -0
- package/src/tui/logo.js +8 -0
- package/src/tui/progress.js +90 -0
- package/src/tui/report-reader.js +105 -0
- package/src/tui/select.js +63 -0
- package/src/tui/workbench.js +377 -0
- package/src/version.js +5 -0
- package/src/web/app.js +729 -0
- package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
- package/src/web/assets/README.md +5 -0
- package/src/web/assets/aitm-mark.svg +12 -0
- package/src/web/assets/oak-white.svg +166 -0
- package/src/web/html.js +32 -0
- package/src/web/index.html +26 -0
- package/src/web/markdown.js +48 -0
- package/src/web/styles.css +1450 -0
- package/src/web/views.js +254 -0
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import { jsonSchema, Schemas, DEFAULT_MODELS, MODEL_CATALOG, ProviderId } from './schema.js';
|
|
2
|
+
import { AppError, insist } from './errors.js';
|
|
3
|
+
import { credentialPatch } from './credentials.js';
|
|
4
|
+
|
|
5
|
+
// Claude's grammar supports fewer bounds than JSON Schema. Keep the original
|
|
6
|
+
// Zod validation in the engine and convey unsupported bounds in descriptions.
|
|
7
|
+
export function anthropicSchema(schema) {
|
|
8
|
+
const result = jsonSchema(schema, { reused: 'ref', target: 'draft-2020-12' });
|
|
9
|
+
const unsupported = new Set([
|
|
10
|
+
'minimum',
|
|
11
|
+
'maximum',
|
|
12
|
+
'exclusiveMinimum',
|
|
13
|
+
'exclusiveMaximum',
|
|
14
|
+
'multipleOf',
|
|
15
|
+
'minLength',
|
|
16
|
+
'maxLength',
|
|
17
|
+
'maxItems',
|
|
18
|
+
'uniqueItems',
|
|
19
|
+
]);
|
|
20
|
+
function visit(node) {
|
|
21
|
+
if (!node || typeof node !== 'object') return;
|
|
22
|
+
const bounds = [];
|
|
23
|
+
for (const key of Object.keys(node)) {
|
|
24
|
+
if (unsupported.has(key) || (key === 'minItems' && node[key] > 1)) {
|
|
25
|
+
bounds.push(`${key}: ${JSON.stringify(node[key])}`);
|
|
26
|
+
delete node[key];
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (bounds.length)
|
|
30
|
+
node.description = [node.description, `Required constraints: ${bounds.join(', ')}.`]
|
|
31
|
+
.filter(Boolean)
|
|
32
|
+
.join(' ');
|
|
33
|
+
if (node.$ref && Object.keys(node).some((key) => !['$ref', 'description'].includes(key))) {
|
|
34
|
+
const base = node.$ref
|
|
35
|
+
.split('/')
|
|
36
|
+
.slice(1)
|
|
37
|
+
.reduce((value, key) => value[key], result);
|
|
38
|
+
const merged = { ...structuredClone(base), ...node };
|
|
39
|
+
merged.description = [base.description, node.description].filter(Boolean).join(' ');
|
|
40
|
+
delete merged.$ref;
|
|
41
|
+
for (const key of Object.keys(node)) delete node[key];
|
|
42
|
+
Object.assign(node, merged);
|
|
43
|
+
visit(node);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
for (const map of [node.properties, node.$defs, node.definitions])
|
|
47
|
+
if (map) for (const child of Object.values(map)) visit(child);
|
|
48
|
+
for (const child of [node.items, node.additionalProperties]) visit(child);
|
|
49
|
+
for (const alternatives of [node.anyOf, node.allOf, node.oneOf])
|
|
50
|
+
if (alternatives) for (const child of alternatives) visit(child);
|
|
51
|
+
}
|
|
52
|
+
visit(result);
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function* readSSE(body) {
|
|
57
|
+
const decoder = new TextDecoder();
|
|
58
|
+
let buffer = '';
|
|
59
|
+
for await (const chunk of body) {
|
|
60
|
+
buffer = (buffer + decoder.decode(chunk, { stream: true })).replace(/\r\n/g, '\n');
|
|
61
|
+
insist(
|
|
62
|
+
buffer.length < 8 * 1024 * 1024,
|
|
63
|
+
'Provider event exceeded the size limit.',
|
|
64
|
+
502,
|
|
65
|
+
'provider_protocol',
|
|
66
|
+
);
|
|
67
|
+
let boundary;
|
|
68
|
+
while ((boundary = buffer.indexOf('\n\n')) >= 0) {
|
|
69
|
+
const frame = buffer.slice(0, boundary);
|
|
70
|
+
buffer = buffer.slice(boundary + 2);
|
|
71
|
+
const data = frame
|
|
72
|
+
.split('\n')
|
|
73
|
+
.filter((l) => l.startsWith('data:'))
|
|
74
|
+
.map((l) => l.slice(5).trimStart())
|
|
75
|
+
.join('\n');
|
|
76
|
+
if (data && data !== '[DONE]') yield JSON.parse(data);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
insist(!buffer.trim(), 'Provider stream ended in a partial event.', 502, 'provider_protocol');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Safety classifiers on these models can decline security analysis. With this
|
|
83
|
+
// opt-in, the API reruns a declined request on the model Anthropic recommends.
|
|
84
|
+
const ANTHROPIC_FALLBACK = /^claude-(?:opus-5|sonnet-5-5|fable-5|mythos-5)(?:-|$)/;
|
|
85
|
+
const FALLBACK_BETA = 'server-side-fallback-2026-07-01';
|
|
86
|
+
|
|
87
|
+
export class Providers {
|
|
88
|
+
constructor({
|
|
89
|
+
keys = {},
|
|
90
|
+
keySources = {},
|
|
91
|
+
keyFile = null,
|
|
92
|
+
saveCredentials,
|
|
93
|
+
anthropicWorkspaceId = '',
|
|
94
|
+
fetchImpl = fetch,
|
|
95
|
+
} = {}) {
|
|
96
|
+
this.keys = { ...keys };
|
|
97
|
+
this.keySources = { ...keySources };
|
|
98
|
+
this.keyFile = keyFile;
|
|
99
|
+
this.saveCredentials = saveCredentials;
|
|
100
|
+
this.redactedKeys = new Set(Object.values(keys).filter(Boolean));
|
|
101
|
+
insist(
|
|
102
|
+
!anthropicWorkspaceId || /^wrkspc_[A-Za-z0-9]+$/.test(anthropicWorkspaceId),
|
|
103
|
+
'ANTHROPIC_WORKSPACE_ID must be a wrkspc_ workspace ID.',
|
|
104
|
+
);
|
|
105
|
+
this.anthropicWorkspaceId = anthropicWorkspaceId;
|
|
106
|
+
this.fetch = fetchImpl;
|
|
107
|
+
}
|
|
108
|
+
status() {
|
|
109
|
+
return Object.fromEntries(
|
|
110
|
+
Object.entries(DEFAULT_MODELS).map(([name, models]) => [
|
|
111
|
+
name,
|
|
112
|
+
{
|
|
113
|
+
configured: Boolean(this.keys[name]),
|
|
114
|
+
keySource: this.keySources[name] || (this.keys[name] ? 'session' : 'not configured'),
|
|
115
|
+
...models,
|
|
116
|
+
},
|
|
117
|
+
]),
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
redact(text) {
|
|
121
|
+
let result = String(text);
|
|
122
|
+
for (const key of this.redactedKeys) if (key) result = result.split(key).join('[REDACTED]');
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
configure(input) {
|
|
126
|
+
const patch = credentialPatch(input);
|
|
127
|
+
if (!Object.keys(patch).length) return false;
|
|
128
|
+
// Commit to disk before changing the active credentials. Never send them to project storage.
|
|
129
|
+
try {
|
|
130
|
+
this.saveCredentials?.(patch);
|
|
131
|
+
} catch {
|
|
132
|
+
throw new AppError(
|
|
133
|
+
500,
|
|
134
|
+
'credential_save_failed',
|
|
135
|
+
'Could not save API keys. Check permissions on the AiTM configuration directory.',
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
for (const provider of ['openai', 'anthropic'])
|
|
139
|
+
if (patch[provider]) {
|
|
140
|
+
this.keys[provider] = patch[provider];
|
|
141
|
+
this.redactedKeys.add(patch[provider]);
|
|
142
|
+
this.keySources[provider] = this.saveCredentials ? 'saved settings' : 'session';
|
|
143
|
+
}
|
|
144
|
+
if (patch.anthropicWorkspaceId !== undefined)
|
|
145
|
+
this.anthropicWorkspaceId = patch.anthropicWorkspaceId;
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
headers(provider) {
|
|
149
|
+
return provider === 'openai'
|
|
150
|
+
? { authorization: `Bearer ${this.keys[provider]}` }
|
|
151
|
+
: {
|
|
152
|
+
'x-api-key': this.keys[provider],
|
|
153
|
+
'anthropic-version': '2023-06-01',
|
|
154
|
+
...(this.anthropicWorkspaceId
|
|
155
|
+
? { 'anthropic-workspace-id': this.anthropicWorkspaceId }
|
|
156
|
+
: {}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
async models(provider, signal) {
|
|
160
|
+
ProviderId.parse(provider);
|
|
161
|
+
const defaults = MODEL_CATALOG[provider];
|
|
162
|
+
const fallback = (notice) => ({
|
|
163
|
+
source: 'defaults',
|
|
164
|
+
models: defaults.map((id) => ({ id })),
|
|
165
|
+
notice,
|
|
166
|
+
});
|
|
167
|
+
if (!this.keys[provider])
|
|
168
|
+
return fallback('Add an API key in Settings to load account models. Showing defaults.');
|
|
169
|
+
try {
|
|
170
|
+
const requestSignal = AbortSignal.any([
|
|
171
|
+
...(signal ? [signal] : []),
|
|
172
|
+
AbortSignal.timeout(10000),
|
|
173
|
+
]);
|
|
174
|
+
const entries = [];
|
|
175
|
+
let cursor = '';
|
|
176
|
+
for (let page = 0; page < 10; page++) {
|
|
177
|
+
const url = new URL(
|
|
178
|
+
provider === 'openai'
|
|
179
|
+
? 'https://api.openai.com/v1/models'
|
|
180
|
+
: 'https://api.anthropic.com/v1/models',
|
|
181
|
+
);
|
|
182
|
+
if (provider === 'anthropic') {
|
|
183
|
+
url.searchParams.set('limit', '1000');
|
|
184
|
+
if (cursor) url.searchParams.set('after_id', cursor);
|
|
185
|
+
}
|
|
186
|
+
const response = await this.fetch(url.toString(), {
|
|
187
|
+
method: 'GET',
|
|
188
|
+
headers: this.headers(provider),
|
|
189
|
+
redirect: 'error',
|
|
190
|
+
signal: requestSignal,
|
|
191
|
+
});
|
|
192
|
+
if (!response.ok) {
|
|
193
|
+
await response.body?.cancel();
|
|
194
|
+
return fallback(
|
|
195
|
+
`Could not load account models (HTTP ${response.status}). Showing defaults; check the API key in Settings.`,
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
const body = await response.json();
|
|
199
|
+
insist(Array.isArray(body.data), 'Invalid model list.');
|
|
200
|
+
entries.push(...body.data.slice(0, 10000));
|
|
201
|
+
if (provider === 'openai' || !body.has_more) break;
|
|
202
|
+
insist(
|
|
203
|
+
typeof body.last_id === 'string' && body.last_id !== cursor && page < 9,
|
|
204
|
+
'Invalid model pagination.',
|
|
205
|
+
);
|
|
206
|
+
cursor = body.last_id;
|
|
207
|
+
}
|
|
208
|
+
const models = [
|
|
209
|
+
...new Map(
|
|
210
|
+
entries
|
|
211
|
+
.filter((model) => {
|
|
212
|
+
if (
|
|
213
|
+
typeof model?.id !== 'string' ||
|
|
214
|
+
!/^[\w.:-]{1,300}$/.test(model.id) ||
|
|
215
|
+
this.redact(model.id) !== model.id
|
|
216
|
+
)
|
|
217
|
+
return false;
|
|
218
|
+
if (provider === 'anthropic')
|
|
219
|
+
return model.capabilities
|
|
220
|
+
? model.capabilities.structured_outputs?.supported &&
|
|
221
|
+
model.capabilities.effort?.supported &&
|
|
222
|
+
(!model.max_tokens || model.max_tokens >= 64000)
|
|
223
|
+
: defaults.includes(model.id);
|
|
224
|
+
// The pipeline uses reasoning effort and strict Responses output. Exclude specialist endpoints.
|
|
225
|
+
return (
|
|
226
|
+
/^gpt-[5-9](?:[.-]|$)/.test(model.id) &&
|
|
227
|
+
!/(chat|audio|realtime|search|transcribe|tts|image|deep-research)/.test(model.id) &&
|
|
228
|
+
!/(?:^|-)(?:pro|codex)(?:-|$)/.test(model.id)
|
|
229
|
+
);
|
|
230
|
+
})
|
|
231
|
+
.map((model) => [model.id, { id: model.id }]),
|
|
232
|
+
).values(),
|
|
233
|
+
];
|
|
234
|
+
models.sort((a, b) => {
|
|
235
|
+
const rank = (id) => (defaults.includes(id) ? defaults.indexOf(id) : defaults.length);
|
|
236
|
+
return rank(a.id) - rank(b.id) || a.id.localeCompare(b.id);
|
|
237
|
+
});
|
|
238
|
+
return models.length
|
|
239
|
+
? { source: 'account', models, notice: '' }
|
|
240
|
+
: fallback(
|
|
241
|
+
'No compatible models returned. Showing defaults; use the connection test to verify access.',
|
|
242
|
+
);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (signal?.aborted) throw error;
|
|
245
|
+
return fallback(
|
|
246
|
+
'Account model lookup is unavailable. Showing defaults; refresh the model list to retry.',
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// The provider for a new project: the first one with a key, OpenAI when none has one.
|
|
251
|
+
preferred() {
|
|
252
|
+
return Object.keys(DEFAULT_MODELS).find((name) => this.keys[name]) || 'openai';
|
|
253
|
+
}
|
|
254
|
+
assertConfigured(provider) {
|
|
255
|
+
const name = (id) => (id === 'openai' ? 'OpenAI' : 'Anthropic');
|
|
256
|
+
const other = Object.keys(DEFAULT_MODELS).find((id) => id !== provider && this.keys[id]);
|
|
257
|
+
insist(
|
|
258
|
+
this.keys[provider],
|
|
259
|
+
other
|
|
260
|
+
? `This project uses ${name(provider)}, which has no API key. ${name(other)} has a key: select ${name(other)} in the provider and model settings of the project and save, or add an ${name(provider)} key in Settings.`
|
|
261
|
+
: `No ${name(provider)} API key is configured. Add one in Settings, or run aitm configure, then start the run again.`,
|
|
262
|
+
422,
|
|
263
|
+
'missing_key',
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
async call({
|
|
267
|
+
provider,
|
|
268
|
+
model,
|
|
269
|
+
phase,
|
|
270
|
+
system,
|
|
271
|
+
user,
|
|
272
|
+
effort = 'medium',
|
|
273
|
+
signal,
|
|
274
|
+
onProgress = () => {},
|
|
275
|
+
schema = Schemas[phase],
|
|
276
|
+
}) {
|
|
277
|
+
this.assertConfigured(provider);
|
|
278
|
+
const openai = provider === 'openai';
|
|
279
|
+
let fallbacks = !openai && ANTHROPIC_FALLBACK.test(model);
|
|
280
|
+
const body = openai
|
|
281
|
+
? {
|
|
282
|
+
model,
|
|
283
|
+
instructions: system,
|
|
284
|
+
input: user,
|
|
285
|
+
stream: true,
|
|
286
|
+
store: false,
|
|
287
|
+
reasoning: { effort },
|
|
288
|
+
max_output_tokens: 32000,
|
|
289
|
+
text: {
|
|
290
|
+
format: {
|
|
291
|
+
type: 'json_schema',
|
|
292
|
+
name: `aitm_${phase}`,
|
|
293
|
+
strict: true,
|
|
294
|
+
schema: jsonSchema(schema),
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
}
|
|
298
|
+
: {
|
|
299
|
+
model,
|
|
300
|
+
system,
|
|
301
|
+
messages: [{ role: 'user', content: user }],
|
|
302
|
+
stream: true,
|
|
303
|
+
max_tokens: 64000,
|
|
304
|
+
output_config: {
|
|
305
|
+
effort,
|
|
306
|
+
format: { type: 'json_schema', schema: anthropicSchema(schema) },
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
let response;
|
|
310
|
+
for (;;) {
|
|
311
|
+
try {
|
|
312
|
+
response = await this.fetch(
|
|
313
|
+
openai ? 'https://api.openai.com/v1/responses' : 'https://api.anthropic.com/v1/messages',
|
|
314
|
+
{
|
|
315
|
+
method: 'POST',
|
|
316
|
+
redirect: 'error',
|
|
317
|
+
signal,
|
|
318
|
+
headers: {
|
|
319
|
+
'content-type': 'application/json',
|
|
320
|
+
...this.headers(provider),
|
|
321
|
+
...(fallbacks ? { 'anthropic-beta': FALLBACK_BETA } : {}),
|
|
322
|
+
},
|
|
323
|
+
body: JSON.stringify(fallbacks ? { ...body, fallbacks: 'default' } : body),
|
|
324
|
+
},
|
|
325
|
+
);
|
|
326
|
+
} catch (error) {
|
|
327
|
+
if (signal?.aborted) throw error;
|
|
328
|
+
throw new AppError(
|
|
329
|
+
502,
|
|
330
|
+
'provider_network',
|
|
331
|
+
`${provider} connection failed; check your network and retry.`,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
if (response.ok) break;
|
|
335
|
+
// Recognize this actionable account-configuration error without reflecting
|
|
336
|
+
// arbitrary provider bodies (which can contain source text or credentials).
|
|
337
|
+
if (!openai && response.status === 400) {
|
|
338
|
+
const detail = await response.json().catch(() => ({}));
|
|
339
|
+
if (/anthropic-workspace-id/.test(String(detail.error?.message || '')))
|
|
340
|
+
throw new AppError(
|
|
341
|
+
422,
|
|
342
|
+
'workspace_required',
|
|
343
|
+
'Anthropic requires a workspace selection. Set ANTHROPIC_WORKSPACE_ID in your private configuration and restart the server.',
|
|
344
|
+
);
|
|
345
|
+
// An account or platform without the fallback beta rejects the field. Send the plain request.
|
|
346
|
+
if (fallbacks) {
|
|
347
|
+
fallbacks = false;
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (!response.bodyUsed) await response.body?.cancel();
|
|
352
|
+
const reason =
|
|
353
|
+
response.status === 401 || response.status === 403
|
|
354
|
+
? 'key or model access was rejected'
|
|
355
|
+
: response.status === 429
|
|
356
|
+
? 'rate or billing limit reached'
|
|
357
|
+
: `request failed (HTTP ${response.status})`;
|
|
358
|
+
throw new AppError(502, 'provider_error', `${provider}: ${reason}. Model: ${model}.`);
|
|
359
|
+
}
|
|
360
|
+
let output = '',
|
|
361
|
+
served = model,
|
|
362
|
+
completed = false,
|
|
363
|
+
stopped = false,
|
|
364
|
+
inputTokens = 0,
|
|
365
|
+
outputTokens = 0,
|
|
366
|
+
lastProgress = 0;
|
|
367
|
+
try {
|
|
368
|
+
for await (const event of readSSE(response.body)) {
|
|
369
|
+
signal?.throwIfAborted();
|
|
370
|
+
if (['error', 'response.failed', 'response.incomplete'].includes(event.type))
|
|
371
|
+
throw new AppError(
|
|
372
|
+
502,
|
|
373
|
+
'provider_incomplete',
|
|
374
|
+
`${provider} did not complete the response. Check model access, limits or content restrictions.`,
|
|
375
|
+
);
|
|
376
|
+
if (event.type === 'response.refusal.delta' || event.type === 'response.refusal.done')
|
|
377
|
+
throw new AppError(502, 'provider_refusal', `${provider} declined this analysis.`);
|
|
378
|
+
if (event.type === 'response.output_text.delta') output += event.delta;
|
|
379
|
+
if (event.type === 'response.completed') {
|
|
380
|
+
insist(
|
|
381
|
+
event.response.status === 'completed',
|
|
382
|
+
'Provider response is incomplete.',
|
|
383
|
+
502,
|
|
384
|
+
'provider_incomplete',
|
|
385
|
+
);
|
|
386
|
+
completed = true;
|
|
387
|
+
inputTokens = event.response.usage?.input_tokens || 0;
|
|
388
|
+
outputTokens = event.response.usage?.output_tokens || 0;
|
|
389
|
+
}
|
|
390
|
+
if (event.type === 'message_start') {
|
|
391
|
+
inputTokens = event.message?.usage?.input_tokens || 0;
|
|
392
|
+
if (typeof event.message?.model === 'string') served = event.message.model;
|
|
393
|
+
}
|
|
394
|
+
if (event.type === 'content_block_start' && event.content_block?.type === 'fallback') {
|
|
395
|
+
// A switch after partial output cannot give one valid JSON document.
|
|
396
|
+
if (output)
|
|
397
|
+
throw new AppError(
|
|
398
|
+
502,
|
|
399
|
+
'provider_incomplete',
|
|
400
|
+
'Anthropic declined part-way and changed to its fallback model. Retry this phase.',
|
|
401
|
+
);
|
|
402
|
+
if (typeof event.content_block.to?.model === 'string')
|
|
403
|
+
served = event.content_block.to.model;
|
|
404
|
+
}
|
|
405
|
+
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta')
|
|
406
|
+
output += event.delta.text;
|
|
407
|
+
if (event.type === 'message_delta') {
|
|
408
|
+
outputTokens = event.usage?.output_tokens || outputTokens;
|
|
409
|
+
const reason = event.delta?.stop_reason;
|
|
410
|
+
if (reason === 'refusal')
|
|
411
|
+
throw new AppError(502, 'provider_refusal', 'Anthropic declined this analysis.');
|
|
412
|
+
if (reason && reason !== 'end_turn')
|
|
413
|
+
throw new AppError(
|
|
414
|
+
502,
|
|
415
|
+
'provider_incomplete',
|
|
416
|
+
`Anthropic stopped before completion (${reason}).`,
|
|
417
|
+
);
|
|
418
|
+
if (reason === 'end_turn') stopped = true;
|
|
419
|
+
}
|
|
420
|
+
if (event.type === 'message_stop') completed = stopped;
|
|
421
|
+
insist(
|
|
422
|
+
output.length < 4 * 1024 * 1024,
|
|
423
|
+
'Provider output exceeded the limit.',
|
|
424
|
+
502,
|
|
425
|
+
'provider_protocol',
|
|
426
|
+
);
|
|
427
|
+
if (Date.now() - lastProgress > 500) {
|
|
428
|
+
onProgress({ characters: output.length, inputTokens, outputTokens });
|
|
429
|
+
lastProgress = Date.now();
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
} catch (error) {
|
|
433
|
+
if (signal?.aborted || error instanceof AppError) throw error;
|
|
434
|
+
throw new AppError(
|
|
435
|
+
502,
|
|
436
|
+
'provider_protocol',
|
|
437
|
+
'Provider stream was interrupted or malformed. Retry this phase.',
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
insist(
|
|
441
|
+
completed && output.trim(),
|
|
442
|
+
'Provider stream ended without a complete structured result.',
|
|
443
|
+
502,
|
|
444
|
+
'provider_incomplete',
|
|
445
|
+
);
|
|
446
|
+
try {
|
|
447
|
+
return {
|
|
448
|
+
data: JSON.parse(this.redact(output)),
|
|
449
|
+
usage: { inputTokens, outputTokens },
|
|
450
|
+
// The model that produced the result; it differs from the request after a fallback.
|
|
451
|
+
model: /^[\w.:-]{1,300}$/.test(served) ? served : model,
|
|
452
|
+
provider,
|
|
453
|
+
};
|
|
454
|
+
} catch {
|
|
455
|
+
throw new AppError(
|
|
456
|
+
502,
|
|
457
|
+
'provider_json',
|
|
458
|
+
'Provider returned invalid structured JSON. Retry this phase.',
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
async test(provider, model, signal) {
|
|
463
|
+
const { z } = await import('zod');
|
|
464
|
+
await this.call({
|
|
465
|
+
provider,
|
|
466
|
+
model,
|
|
467
|
+
phase: 'connection',
|
|
468
|
+
system: 'Reply with a JSON object containing ok: true.',
|
|
469
|
+
user: 'Test connection.',
|
|
470
|
+
effort: 'low',
|
|
471
|
+
signal,
|
|
472
|
+
schema: z.strictObject({ ok: z.boolean() }),
|
|
473
|
+
});
|
|
474
|
+
return { provider, model, verified: true };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { modelItems } from './validate.js';
|
|
2
|
+
|
|
3
|
+
const normalize = (value) =>
|
|
4
|
+
String(value || '')
|
|
5
|
+
.toLowerCase()
|
|
6
|
+
.replace(/[^a-z0-9]/g, '');
|
|
7
|
+
|
|
8
|
+
// Repair only an unambiguous identity/name match. Never guess a semantic mapping
|
|
9
|
+
// or create a model object to make a generated reference pass validation.
|
|
10
|
+
export function resolveReferences(phase, data, project) {
|
|
11
|
+
const model = phase === 'model' ? data : project.artifacts.model?.data;
|
|
12
|
+
if (!model) return { corrections: [], warnings: [] };
|
|
13
|
+
const objects = modelItems(model);
|
|
14
|
+
const known = [...objects, ...(project.artifacts.ingest?.data.candidates || [])];
|
|
15
|
+
const corrections = [],
|
|
16
|
+
warnings = [];
|
|
17
|
+
function resolve(value, allowed, path) {
|
|
18
|
+
if (allowed.some((item) => item.id === value)) return value;
|
|
19
|
+
const old = known.find((item) => item.id === value);
|
|
20
|
+
const matches = allowed.filter(
|
|
21
|
+
(item) =>
|
|
22
|
+
normalize(item.id) === normalize(value) ||
|
|
23
|
+
(old && normalize(item.name) === normalize(old.name)),
|
|
24
|
+
);
|
|
25
|
+
if (matches.length !== 1) return null;
|
|
26
|
+
corrections.push({ path, from: value, to: matches[0].id });
|
|
27
|
+
return matches[0].id;
|
|
28
|
+
}
|
|
29
|
+
function note(owner, path, rejected) {
|
|
30
|
+
const message = `Reference review required: ${path} contains unresolved IDs (${rejected.join(', ')}). These links were not included; review the claim's model mapping.`;
|
|
31
|
+
warnings.push({
|
|
32
|
+
path,
|
|
33
|
+
claim: owner.title || owner.name || owner.id || path,
|
|
34
|
+
rejectedIds: rejected,
|
|
35
|
+
note: message,
|
|
36
|
+
});
|
|
37
|
+
if (typeof owner.assumption === 'string') {
|
|
38
|
+
owner.assumption = `${message}\n${owner.assumption}`.trim().slice(0, 12000);
|
|
39
|
+
if ('confidence' in owner) owner.confidence = 'low';
|
|
40
|
+
} else if (data.openQuestions?.length < 200) data.openQuestions.push(message);
|
|
41
|
+
}
|
|
42
|
+
function links(owner, field, allowed, path, minimum = 0) {
|
|
43
|
+
const rejected = [],
|
|
44
|
+
values = [];
|
|
45
|
+
for (const value of owner[field]) {
|
|
46
|
+
const mapped = resolve(value, allowed, `${path}.${field}`);
|
|
47
|
+
if (mapped) values.push(mapped);
|
|
48
|
+
else rejected.push(value);
|
|
49
|
+
}
|
|
50
|
+
// A required relationship with no identifiable endpoint needs the bounded
|
|
51
|
+
// structural repair. Preserve the invalid value for the validator to explain.
|
|
52
|
+
if (values.length < minimum) return;
|
|
53
|
+
owner[field] = [...new Set(values)];
|
|
54
|
+
if (rejected.length) note(owner, `${path}.${field}`, rejected);
|
|
55
|
+
}
|
|
56
|
+
if (phase === 'model') {
|
|
57
|
+
const endpoints = [
|
|
58
|
+
...model.components,
|
|
59
|
+
...model.roles,
|
|
60
|
+
...model.threatActors,
|
|
61
|
+
...model.protectedAssets,
|
|
62
|
+
];
|
|
63
|
+
for (const edge of model.edges)
|
|
64
|
+
for (const key of ['from', 'to'])
|
|
65
|
+
edge[key] = resolve(edge[key], endpoints, `model.${edge.id}.${key}`) || edge[key];
|
|
66
|
+
}
|
|
67
|
+
if (phase === 'stride') {
|
|
68
|
+
for (const threat of data.threats) {
|
|
69
|
+
const path = `stride.${threat.id}`;
|
|
70
|
+
links(threat, 'targetIds', [...model.components, ...model.roles, ...model.edges], path, 1);
|
|
71
|
+
links(threat, 'actorIds', model.threatActors, path);
|
|
72
|
+
links(threat, 'assetIds', model.protectedAssets, path);
|
|
73
|
+
links(threat, 'invariantIds', model.invariants, path);
|
|
74
|
+
}
|
|
75
|
+
const rows = new Map();
|
|
76
|
+
for (const row of data.coverage) {
|
|
77
|
+
const mapped = resolve(row.objectId, objects, 'stride.coverage.objectId');
|
|
78
|
+
if (!mapped) {
|
|
79
|
+
note(row, 'stride.coverage.objectId', [row.objectId]);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!rows.has(mapped)) rows.set(mapped, { ...row, objectId: mapped });
|
|
83
|
+
}
|
|
84
|
+
data.coverage = [...rows.values()];
|
|
85
|
+
}
|
|
86
|
+
if (phase === 'coordination')
|
|
87
|
+
for (const scenario of data.scenarios) {
|
|
88
|
+
links(
|
|
89
|
+
scenario,
|
|
90
|
+
'actorIds',
|
|
91
|
+
[...model.threatActors, ...model.roles],
|
|
92
|
+
`coordination.${scenario.id}`,
|
|
93
|
+
1,
|
|
94
|
+
);
|
|
95
|
+
links(scenario, 'assetIds', model.protectedAssets, `coordination.${scenario.id}`, 1);
|
|
96
|
+
}
|
|
97
|
+
if (phase === 'report')
|
|
98
|
+
for (const row of data.roadmap)
|
|
99
|
+
links(
|
|
100
|
+
row,
|
|
101
|
+
'linkedIds',
|
|
102
|
+
[
|
|
103
|
+
...objects,
|
|
104
|
+
...(project.artifacts.stride?.data.threats || []),
|
|
105
|
+
...(project.artifacts.trees?.data.trees || []).flatMap((tree) => tree.nodes),
|
|
106
|
+
...(project.artifacts.coordination?.data.scenarios || []),
|
|
107
|
+
],
|
|
108
|
+
`report.${row.id}`,
|
|
109
|
+
1,
|
|
110
|
+
);
|
|
111
|
+
return { corrections, warnings };
|
|
112
|
+
}
|