@happyvertical/smrt-inference 0.74.6 → 0.75.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/AGENTS.md +4 -0
- package/agents/settings.md +13 -0
- package/dist/chunks/{InferenceOverrideCollection-CVCaWM1y.js → InferenceOverrideCollection-C9bY01Rv.js} +2 -2
- package/dist/chunks/{InferenceOverrideCollection-CVCaWM1y.js.map → InferenceOverrideCollection-C9bY01Rv.js.map} +1 -1
- package/dist/i18n/catalog.d.ts +3 -0
- package/dist/i18n/catalog.d.ts.map +1 -0
- package/dist/i18n/catalog.generated.d.ts +3 -0
- package/dist/i18n/catalog.generated.d.ts.map +1 -0
- package/dist/i18n/catalog.js +280 -0
- package/dist/i18n/catalog.js.map +1 -0
- package/dist/manifest.json +1 -1
- package/dist/models.js +1 -1
- package/dist/server.d.ts +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +419 -137
- package/dist/server.js.map +1 -1
- package/dist/settings/controller.d.ts +18 -0
- package/dist/settings/controller.d.ts.map +1 -1
- package/dist/settings/history.d.ts +210 -0
- package/dist/settings/history.d.ts.map +1 -0
- package/dist/settings/settings-service.d.ts +5 -1
- package/dist/settings/settings-service.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +11 -8
- package/dist/svelte/components/InferencePromptHistory.svelte +200 -0
- package/dist/svelte/components/InferencePromptHistory.svelte.d.ts +12 -0
- package/dist/svelte/components/InferencePromptHistory.svelte.d.ts.map +1 -0
- package/dist/svelte/components/InferenceSettingsPanel.svelte +19 -1
- package/dist/svelte/components/InferenceSettingsPanel.svelte.d.ts +3 -1
- package/dist/svelte/components/InferenceSettingsPanel.svelte.d.ts.map +1 -1
- package/dist/svelte/history.messages.d.ts +57 -0
- package/dist/svelte/history.messages.d.ts.map +1 -0
- package/dist/svelte/history.messages.js +58 -0
- package/dist/svelte/index.d.ts +1 -0
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/types.d.ts +73 -0
- package/dist/svelte/types.d.ts.map +1 -1
- package/package.json +15 -10
package/dist/server.js
CHANGED
|
@@ -2,11 +2,12 @@ import { B as InferenceConfigError, I as findInferenceConfigIssues, N as findFus
|
|
|
2
2
|
import { S as resolveAssistantSettings, _ as AGENT_TOOLS, a as concreteTier, b as ASSISTANT_SETTING_KEYS, c as engineTierModel, d as rankOpenAIModels, f as resolveEngineEffort, g as engineLabel, h as weakestModel, i as OPENAI_MODEL_RANKS, l as nextEngineModel, m as validateModelId, n as runWithModelFallback, o as engineModels, p as strongestModel, r as CLAUDE_MODEL_RANKS, s as engineReasoningEffort, t as MODEL_FALLBACK_MESSAGE, u as nextModel, v as AGENT_TOOL_INFO, x as isAssistantSettings, y as isAgentTool } from "./chunks/model-fallback-BVD3BzkG.js";
|
|
3
3
|
import { createUserInferenceResolver, registerUserInferenceResolver } from "./resolver.js";
|
|
4
4
|
import { checkInferenceBindings, inferenceProbeUrl, probeInferenceCandidate } from "./node.js";
|
|
5
|
-
import { C as getInferenceOverrideGeneration, S as tierBinding, _ as normalizeFusionDefinition, a as INFERENCE_BINDING_NAME_PATTERN, b as parseInferenceBinding, c as TRANSCRIPTS_BINDING, d as inferenceTargetRef, f as isAllowedByList, g as normalizeDefaultTier, h as normalizeAllowList, i as DEFAULT_TIER_BINDING, l as describeInferenceTarget, m as normalizeAliasDefinition, n as APP_INFERENCE_SCOPE_ID, o as INFERENCE_MODES, p as matchesAllowPattern, r as InferenceOverride, s as InferenceBindingValueError, t as InferenceOverrideCollection, u as findKeyMember, v as normalizeTierTarget, x as stripKeyMembers, y as normalizeTranscriptSettings } from "./chunks/InferenceOverrideCollection-
|
|
6
|
-
import { DEFAULT_RETENTION_POLICY, DEFAULT_TRANSCRIPT_MAX_BYTES, DEFAULT_TRANSCRIPT_SAMPLE, INFERENCE_PRESETS, INFERENCE_PRESET_IDS, INFERENCE_TIERS, config, getInferenceConfig, getInferenceTranscriptsConfig, inferenceTargetKind, isInferencePresetId, isInferenceTier, mergeInferenceConfigs, reportAiUsage, resolveAutoTier, setAiTranscriptAppSettings, setInferenceResolver } from "@happyvertical/smrt-core";
|
|
5
|
+
import { C as getInferenceOverrideGeneration, S as tierBinding, _ as normalizeFusionDefinition, a as INFERENCE_BINDING_NAME_PATTERN, b as parseInferenceBinding, c as TRANSCRIPTS_BINDING, d as inferenceTargetRef, f as isAllowedByList, g as normalizeDefaultTier, h as normalizeAllowList, i as DEFAULT_TIER_BINDING, l as describeInferenceTarget, m as normalizeAliasDefinition, n as APP_INFERENCE_SCOPE_ID, o as INFERENCE_MODES, p as matchesAllowPattern, r as InferenceOverride, s as InferenceBindingValueError, t as InferenceOverrideCollection, u as findKeyMember, v as normalizeTierTarget, x as stripKeyMembers, y as normalizeTranscriptSettings } from "./chunks/InferenceOverrideCollection-C9bY01Rv.js";
|
|
6
|
+
import { DEFAULT_RETENTION_POLICY, DEFAULT_TRANSCRIPT_MAX_BYTES, DEFAULT_TRANSCRIPT_SAMPLE, INFERENCE_PRESETS, INFERENCE_PRESET_IDS, INFERENCE_TIERS, compareAiPromptRuns, config, getInferenceConfig, getInferenceTranscriptsConfig, inferenceTargetKind, isInferencePresetId, isInferenceTier, listAiPromptTemplateHistory, mergeInferenceConfigs, reportAiUsage, resolveAutoTier, setAiTranscriptAppSettings, setInferenceResolver } from "@happyvertical/smrt-core";
|
|
7
7
|
import { AI_PROVIDER_TYPES } from "@happyvertical/ai/types";
|
|
8
8
|
import { getDefaultAIKeyEnvName } from "@happyvertical/smrt-config";
|
|
9
9
|
import { SecretService } from "@happyvertical/smrt-secrets";
|
|
10
|
+
import { assertOperationPermission } from "@happyvertical/smrt-users";
|
|
10
11
|
import { accessSync, constants, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
11
12
|
import { homedir, tmpdir } from "node:os";
|
|
12
13
|
import { delimiter, dirname, join } from "node:path";
|
|
@@ -2165,6 +2166,393 @@ async function inferenceEngineStatus(engine, host) {
|
|
|
2165
2166
|
};
|
|
2166
2167
|
}
|
|
2167
2168
|
//#endregion
|
|
2169
|
+
//#region src/settings/preferences.ts
|
|
2170
|
+
var INFERENCE_PREFERENCE_KIND = "inference";
|
|
2171
|
+
var INFERENCE_PREFERENCE_SURFACE = "default";
|
|
2172
|
+
var CUSTOMIZE_INFERENCE_PERMISSION = "inference.customize";
|
|
2173
|
+
var PERSONALIZE_INFERENCE_PERMISSION = "inference.personalize";
|
|
2174
|
+
var INFERENCE_PERMISSION_DEFINITIONS = [{
|
|
2175
|
+
slug: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
2176
|
+
category: "inference",
|
|
2177
|
+
name: "Customize Inference",
|
|
2178
|
+
description: "Change the default inference mode, provider and model everyone in the tenant uses"
|
|
2179
|
+
}, {
|
|
2180
|
+
slug: PERSONALIZE_INFERENCE_PERMISSION,
|
|
2181
|
+
category: "inference",
|
|
2182
|
+
name: "Personalize Inference",
|
|
2183
|
+
description: "Keep a personal inference mode, provider and model on top of the tenant default"
|
|
2184
|
+
}];
|
|
2185
|
+
var PROVIDER_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
2186
|
+
var MODEL_PATTERN = /^[!-~\u00a1-\uffff]{1,200}$/;
|
|
2187
|
+
function issue(path, message) {
|
|
2188
|
+
return {
|
|
2189
|
+
path,
|
|
2190
|
+
code: "invalid_setting",
|
|
2191
|
+
message
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
function validBaseUrl(value) {
|
|
2195
|
+
try {
|
|
2196
|
+
const url = new URL(value);
|
|
2197
|
+
return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.search && !url.hash;
|
|
2198
|
+
} catch {
|
|
2199
|
+
return false;
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
function validateInferencePreferences(payload) {
|
|
2203
|
+
if (payload === null || payload === void 0) return {
|
|
2204
|
+
ok: true,
|
|
2205
|
+
canonical: null,
|
|
2206
|
+
issues: []
|
|
2207
|
+
};
|
|
2208
|
+
if (typeof payload !== "object" || Array.isArray(payload)) return {
|
|
2209
|
+
ok: false,
|
|
2210
|
+
canonical: null,
|
|
2211
|
+
issues: [issue("", "inference preferences are an object")]
|
|
2212
|
+
};
|
|
2213
|
+
const keyMember = findKeyMember(payload);
|
|
2214
|
+
if (keyMember) return {
|
|
2215
|
+
ok: false,
|
|
2216
|
+
canonical: null,
|
|
2217
|
+
issues: [issue(keyMember, "keys are never stored as preferences; they go to smrt-secrets")]
|
|
2218
|
+
};
|
|
2219
|
+
const input = payload;
|
|
2220
|
+
const issues = [];
|
|
2221
|
+
const canonical = {};
|
|
2222
|
+
for (const [member, value] of Object.entries(input)) {
|
|
2223
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
2224
|
+
switch (member) {
|
|
2225
|
+
case "mode":
|
|
2226
|
+
if (INFERENCE_MODES.includes(value)) canonical.mode = value;
|
|
2227
|
+
else issues.push(issue(member, `mode is one of ${INFERENCE_MODES.join(", ")}`));
|
|
2228
|
+
break;
|
|
2229
|
+
case "provider":
|
|
2230
|
+
if (typeof value === "string" && PROVIDER_PATTERN.test(value)) canonical.provider = value;
|
|
2231
|
+
else issues.push(issue(member, "invalid provider id"));
|
|
2232
|
+
break;
|
|
2233
|
+
case "baseUrl":
|
|
2234
|
+
if (typeof value === "string" && validBaseUrl(value)) canonical.baseUrl = value;
|
|
2235
|
+
else issues.push(issue(member, "the base URL is an http(s) URL without credentials, query or fragment"));
|
|
2236
|
+
break;
|
|
2237
|
+
case "model":
|
|
2238
|
+
if (typeof value === "string" && MODEL_PATTERN.test(value)) canonical.model = value;
|
|
2239
|
+
else issues.push(issue(member, "invalid model id"));
|
|
2240
|
+
break;
|
|
2241
|
+
case "defaultTier":
|
|
2242
|
+
if (isInferenceTier(value)) canonical.defaultTier = value;
|
|
2243
|
+
else issues.push(issue(member, `the default tier is one of ${INFERENCE_TIERS.join(", ")}`));
|
|
2244
|
+
break;
|
|
2245
|
+
default: issues.push(issue(member, "unknown inference preference"));
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
return {
|
|
2249
|
+
ok: issues.length === 0,
|
|
2250
|
+
canonical: Object.keys(canonical).length > 0 ? canonical : null,
|
|
2251
|
+
issues
|
|
2252
|
+
};
|
|
2253
|
+
}
|
|
2254
|
+
var inferencePreferenceKind = {
|
|
2255
|
+
kind: INFERENCE_PREFERENCE_KIND,
|
|
2256
|
+
formatVersion: 1,
|
|
2257
|
+
permissions: {
|
|
2258
|
+
tenant: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
2259
|
+
user: PERSONALIZE_INFERENCE_PERMISSION
|
|
2260
|
+
},
|
|
2261
|
+
validate(payload) {
|
|
2262
|
+
return validateInferencePreferences(payload);
|
|
2263
|
+
}
|
|
2264
|
+
};
|
|
2265
|
+
function createInferencePreferences(store, surfaceId = INFERENCE_PREFERENCE_SURFACE) {
|
|
2266
|
+
return {
|
|
2267
|
+
async read() {
|
|
2268
|
+
const state = await store.load(INFERENCE_PREFERENCE_KIND, surfaceId);
|
|
2269
|
+
const tenant = state.tenant.payload ?? null;
|
|
2270
|
+
const user = state.user?.payload ?? null;
|
|
2271
|
+
return {
|
|
2272
|
+
choices: {
|
|
2273
|
+
...tenant ?? {},
|
|
2274
|
+
...user ?? {}
|
|
2275
|
+
},
|
|
2276
|
+
tenant,
|
|
2277
|
+
user,
|
|
2278
|
+
revisions: {
|
|
2279
|
+
tenant: state.tenant.revision,
|
|
2280
|
+
user: state.user?.revision ?? null
|
|
2281
|
+
},
|
|
2282
|
+
issues: state.issues,
|
|
2283
|
+
canCustomize: state.canCustomize
|
|
2284
|
+
};
|
|
2285
|
+
},
|
|
2286
|
+
/** Save choices at a scope (default `user`); `revision` is the one the client loaded. */
|
|
2287
|
+
write(choices, options) {
|
|
2288
|
+
return store.save(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
2289
|
+
scope: options.scope ?? "user",
|
|
2290
|
+
payload: choices,
|
|
2291
|
+
revision: options.revision
|
|
2292
|
+
});
|
|
2293
|
+
},
|
|
2294
|
+
reset(options = {}) {
|
|
2295
|
+
return store.reset(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
2296
|
+
scope: options.scope ?? "user",
|
|
2297
|
+
revision: options.revision
|
|
2298
|
+
});
|
|
2299
|
+
}
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
//#endregion
|
|
2303
|
+
//#region src/settings/history.ts
|
|
2304
|
+
async function assertInferenceHistoryPermission(session) {
|
|
2305
|
+
if (!session.userId || !session.tenantId) throw Object.assign(/* @__PURE__ */ new Error("Not allowed"), { status: 403 });
|
|
2306
|
+
await assertOperationPermission({
|
|
2307
|
+
collection: "inference",
|
|
2308
|
+
action: "customize",
|
|
2309
|
+
userId: session.userId,
|
|
2310
|
+
tenantId: session.tenantId,
|
|
2311
|
+
permissionSet: session.can("inference.customize") ? [CUSTOMIZE_INFERENCE_PERMISSION] : [],
|
|
2312
|
+
allowSystemContextBypass: false,
|
|
2313
|
+
allowSuperAdminBypass: false,
|
|
2314
|
+
catalog: {
|
|
2315
|
+
permissions: [...INFERENCE_PERMISSION_DEFINITIONS],
|
|
2316
|
+
customPermissions: [],
|
|
2317
|
+
manifestPermissions: [],
|
|
2318
|
+
runtimePermissions: [...INFERENCE_PERMISSION_DEFINITIONS]
|
|
2319
|
+
}
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
function object(value) {
|
|
2323
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid history request");
|
|
2324
|
+
return value;
|
|
2325
|
+
}
|
|
2326
|
+
function selector(value) {
|
|
2327
|
+
const row = object(value);
|
|
2328
|
+
const keys = Object.keys(row);
|
|
2329
|
+
if (keys.length !== 1 || ![
|
|
2330
|
+
"templateHash",
|
|
2331
|
+
"model",
|
|
2332
|
+
"tier"
|
|
2333
|
+
].includes(keys[0]) || typeof row[keys[0]] !== "string" || !row[keys[0]].trim()) throw new TypeError("Choose a template hash, model or tier");
|
|
2334
|
+
return { [keys[0]]: row[keys[0]] };
|
|
2335
|
+
}
|
|
2336
|
+
function parseInferenceHistoryRequest(value, compare) {
|
|
2337
|
+
const row = object(value);
|
|
2338
|
+
const allowed = compare ? [
|
|
2339
|
+
"promptKey",
|
|
2340
|
+
"a",
|
|
2341
|
+
"b",
|
|
2342
|
+
"since",
|
|
2343
|
+
"until",
|
|
2344
|
+
"transcriptLimit"
|
|
2345
|
+
] : [
|
|
2346
|
+
"promptKey",
|
|
2347
|
+
"since",
|
|
2348
|
+
"until"
|
|
2349
|
+
];
|
|
2350
|
+
if (Object.keys(row).some((key) => !allowed.includes(key))) throw new TypeError("Unknown history request field");
|
|
2351
|
+
if (typeof row.promptKey !== "string" || !row.promptKey.trim()) throw new TypeError("Prompt key is required");
|
|
2352
|
+
const dates = {};
|
|
2353
|
+
for (const key of ["since", "until"]) {
|
|
2354
|
+
if (row[key] === void 0) continue;
|
|
2355
|
+
if (typeof row[key] !== "string" || !Number.isFinite(Date.parse(row[key]))) throw new TypeError("Invalid report window");
|
|
2356
|
+
dates[key] = new Date(row[key]);
|
|
2357
|
+
}
|
|
2358
|
+
if (dates.since && dates.until && dates.since > dates.until) throw new TypeError("Invalid report window");
|
|
2359
|
+
if (row.transcriptLimit !== void 0 && (!Number.isInteger(row.transcriptLimit) || Number(row.transcriptLimit) < 0 || Number(row.transcriptLimit) > 500)) throw new TypeError("Invalid transcript limit");
|
|
2360
|
+
return {
|
|
2361
|
+
promptKey: row.promptKey.trim(),
|
|
2362
|
+
...dates,
|
|
2363
|
+
...compare ? {
|
|
2364
|
+
a: selector(row.a),
|
|
2365
|
+
b: selector(row.b),
|
|
2366
|
+
...row.transcriptLimit !== void 0 ? { transcriptLimit: row.transcriptLimit } : {}
|
|
2367
|
+
} : {}
|
|
2368
|
+
};
|
|
2369
|
+
}
|
|
2370
|
+
var INFERENCE_HISTORY_TOOLS = [{
|
|
2371
|
+
name: "inference_prompt_history",
|
|
2372
|
+
operation: "history",
|
|
2373
|
+
description: "List recorded template hashes for a prompt in your tenant."
|
|
2374
|
+
}, {
|
|
2375
|
+
name: "inference_prompt_compare",
|
|
2376
|
+
operation: "compare",
|
|
2377
|
+
description: "Compare recorded prompt versions, models or tiers in your tenant; never runs prompts."
|
|
2378
|
+
}];
|
|
2379
|
+
var selectorSchema = {
|
|
2380
|
+
type: "object",
|
|
2381
|
+
properties: {
|
|
2382
|
+
templateHash: { type: "string" },
|
|
2383
|
+
model: { type: "string" },
|
|
2384
|
+
tier: { type: "string" }
|
|
2385
|
+
},
|
|
2386
|
+
minProperties: 1,
|
|
2387
|
+
maxProperties: 1,
|
|
2388
|
+
additionalProperties: false
|
|
2389
|
+
};
|
|
2390
|
+
function inferenceHistoryInputSchema(compare) {
|
|
2391
|
+
return {
|
|
2392
|
+
type: "object",
|
|
2393
|
+
properties: {
|
|
2394
|
+
promptKey: { type: "string" },
|
|
2395
|
+
since: { type: "string" },
|
|
2396
|
+
until: { type: "string" },
|
|
2397
|
+
...compare ? {
|
|
2398
|
+
a: selectorSchema,
|
|
2399
|
+
b: selectorSchema,
|
|
2400
|
+
transcriptLimit: {
|
|
2401
|
+
type: "integer",
|
|
2402
|
+
minimum: 0,
|
|
2403
|
+
maximum: 500
|
|
2404
|
+
}
|
|
2405
|
+
} : {}
|
|
2406
|
+
},
|
|
2407
|
+
required: compare ? [
|
|
2408
|
+
"promptKey",
|
|
2409
|
+
"a",
|
|
2410
|
+
"b"
|
|
2411
|
+
] : ["promptKey"],
|
|
2412
|
+
additionalProperties: false
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
async function inferenceHistoryResponse(controller, session, request) {
|
|
2416
|
+
if (request.method !== "POST") return Response.json({ error: "Method not allowed" }, {
|
|
2417
|
+
status: 405,
|
|
2418
|
+
headers: { allow: "POST" }
|
|
2419
|
+
});
|
|
2420
|
+
const operation = new URL(request.url).pathname.split("/").pop();
|
|
2421
|
+
if (operation !== "history" && operation !== "compare") return Response.json({ error: "Not found" }, { status: 404 });
|
|
2422
|
+
try {
|
|
2423
|
+
const input = await request.json();
|
|
2424
|
+
const result = operation === "history" ? await controller.history(session, input) : await controller.compare(session, input);
|
|
2425
|
+
return Response.json(result, { headers: { "cache-control": "no-store" } });
|
|
2426
|
+
} catch (cause) {
|
|
2427
|
+
const status = cause.status === 403 ? 403 : cause instanceof TypeError || cause instanceof SyntaxError ? 400 : 503;
|
|
2428
|
+
return Response.json({ error: status === 403 ? "Not allowed" : status === 400 ? "Invalid history request" : "History is unavailable" }, {
|
|
2429
|
+
status,
|
|
2430
|
+
headers: { "cache-control": "no-store" }
|
|
2431
|
+
});
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
async function inferenceTranscriptResponse(db, session, actor, request) {
|
|
2435
|
+
if (!session.tenantId || !actor || !session.can("inference.customize")) return Response.json({ error: "Not allowed" }, { status: 403 });
|
|
2436
|
+
try {
|
|
2437
|
+
await assertInferenceHistoryPermission({
|
|
2438
|
+
...session,
|
|
2439
|
+
userId: actor
|
|
2440
|
+
});
|
|
2441
|
+
} catch {
|
|
2442
|
+
return Response.json({ error: "Not allowed" }, { status: 403 });
|
|
2443
|
+
}
|
|
2444
|
+
const query = new URL(request.url).searchParams;
|
|
2445
|
+
const allowed = [
|
|
2446
|
+
"callId",
|
|
2447
|
+
"promptKey",
|
|
2448
|
+
"templateHash",
|
|
2449
|
+
"label",
|
|
2450
|
+
"since",
|
|
2451
|
+
"until"
|
|
2452
|
+
];
|
|
2453
|
+
if ([...query.keys()].some((key) => !allowed.includes(key))) return Response.json({ error: "Invalid filters" }, { status: 400 });
|
|
2454
|
+
try {
|
|
2455
|
+
const { listAiTranscripts } = await import("@happyvertical/smrt-core");
|
|
2456
|
+
const window = parseInferenceHistoryRequest({
|
|
2457
|
+
promptKey: query.get("promptKey") ?? "transcript",
|
|
2458
|
+
...query.has("since") ? { since: query.get("since") } : {},
|
|
2459
|
+
...query.has("until") ? { until: query.get("until") } : {}
|
|
2460
|
+
}, false);
|
|
2461
|
+
const filters = Object.fromEntries([
|
|
2462
|
+
"callId",
|
|
2463
|
+
"promptKey",
|
|
2464
|
+
"templateHash",
|
|
2465
|
+
"label"
|
|
2466
|
+
].flatMap((key) => query.has(key) ? [[key, query.get(key)]] : []));
|
|
2467
|
+
const result = await listAiTranscripts(db, {
|
|
2468
|
+
actor,
|
|
2469
|
+
reason: "inference settings comparison",
|
|
2470
|
+
tenantId: session.tenantId,
|
|
2471
|
+
...filters,
|
|
2472
|
+
since: window.since,
|
|
2473
|
+
until: window.until
|
|
2474
|
+
});
|
|
2475
|
+
return Response.json(result, { headers: { "cache-control": "no-store" } });
|
|
2476
|
+
} catch (cause) {
|
|
2477
|
+
return Response.json({ error: "Transcripts unavailable" }, { status: cause instanceof TypeError ? 400 : 503 });
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
function createInferenceHistoryMcpTools(controller) {
|
|
2481
|
+
return INFERENCE_HISTORY_TOOLS.map((tool) => ({
|
|
2482
|
+
name: tool.name,
|
|
2483
|
+
description: tool.description,
|
|
2484
|
+
inputSchema: inferenceHistoryInputSchema(tool.operation === "compare"),
|
|
2485
|
+
outputSchema: {
|
|
2486
|
+
type: "object",
|
|
2487
|
+
additionalProperties: true
|
|
2488
|
+
},
|
|
2489
|
+
effect: "read",
|
|
2490
|
+
idempotent: true,
|
|
2491
|
+
openWorld: false,
|
|
2492
|
+
async execute(context) {
|
|
2493
|
+
const principal = context.principal;
|
|
2494
|
+
if (!principal?.id || !principal.tenantId) throw Object.assign(/* @__PURE__ */ new Error("Not allowed"), { status: 403 });
|
|
2495
|
+
const output = await controller[tool.operation]({
|
|
2496
|
+
tenantId: principal.tenantId,
|
|
2497
|
+
userId: principal.id,
|
|
2498
|
+
can: (permission) => principal.scopes?.includes(permission) === true
|
|
2499
|
+
}, context.arguments);
|
|
2500
|
+
return {
|
|
2501
|
+
content: [{
|
|
2502
|
+
type: "text",
|
|
2503
|
+
text: JSON.stringify(output)
|
|
2504
|
+
}],
|
|
2505
|
+
structuredContent: output
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
}));
|
|
2509
|
+
}
|
|
2510
|
+
function createInferenceTranscriptMcpTool(database) {
|
|
2511
|
+
return {
|
|
2512
|
+
name: "inference_prompt_transcripts",
|
|
2513
|
+
description: "Read audited stored transcripts for your tenant, optionally filtered by exact call id.",
|
|
2514
|
+
inputSchema: {
|
|
2515
|
+
type: "object",
|
|
2516
|
+
properties: Object.fromEntries([
|
|
2517
|
+
"callId",
|
|
2518
|
+
"promptKey",
|
|
2519
|
+
"templateHash",
|
|
2520
|
+
"label",
|
|
2521
|
+
"since",
|
|
2522
|
+
"until"
|
|
2523
|
+
].map((key) => [key, { type: "string" }])),
|
|
2524
|
+
additionalProperties: false
|
|
2525
|
+
},
|
|
2526
|
+
outputSchema: {
|
|
2527
|
+
type: "object",
|
|
2528
|
+
additionalProperties: true
|
|
2529
|
+
},
|
|
2530
|
+
effect: "read",
|
|
2531
|
+
idempotent: true,
|
|
2532
|
+
openWorld: false,
|
|
2533
|
+
async execute(context) {
|
|
2534
|
+
const principal = context.principal;
|
|
2535
|
+
if (!principal?.id || !principal.tenantId || !principal.scopes?.includes("inference.customize")) throw Object.assign(/* @__PURE__ */ new Error("Not allowed"), { status: 403 });
|
|
2536
|
+
if (Object.values(context.arguments).some((value) => typeof value !== "string")) throw new TypeError("Invalid transcript filters");
|
|
2537
|
+
const query = new URLSearchParams(context.arguments);
|
|
2538
|
+
const response = await inferenceTranscriptResponse(await database(), {
|
|
2539
|
+
tenantId: principal.tenantId,
|
|
2540
|
+
userId: principal.id,
|
|
2541
|
+
can: (permission) => principal.scopes?.includes(permission) === true
|
|
2542
|
+
}, principal.id, new Request(`https://inference.invalid/api/inference/transcripts?${query}`));
|
|
2543
|
+
if (!response.ok) throw new Error("Transcripts unavailable");
|
|
2544
|
+
const output = { transcripts: await response.json() };
|
|
2545
|
+
return {
|
|
2546
|
+
content: [{
|
|
2547
|
+
type: "text",
|
|
2548
|
+
text: JSON.stringify(output)
|
|
2549
|
+
}],
|
|
2550
|
+
structuredContent: output
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
//#endregion
|
|
2168
2556
|
//#region src/settings/override-service.ts
|
|
2169
2557
|
var InferenceOverrideAuthorizationError = class extends Error {
|
|
2170
2558
|
constructor(request) {
|
|
@@ -2998,6 +3386,14 @@ var InferenceSettingsService = class InferenceSettingsService {
|
|
|
2998
3386
|
by: options.by && options.by.length > 0 ? options.by : ["model"]
|
|
2999
3387
|
});
|
|
3000
3388
|
}
|
|
3389
|
+
/** Read recorded prompt runs only; scope is required by the core reader. */
|
|
3390
|
+
compare(options) {
|
|
3391
|
+
return compareAiPromptRuns(this.overrides.db, options);
|
|
3392
|
+
}
|
|
3393
|
+
/** Template versions observed in recorded usage, never executing a prompt. */
|
|
3394
|
+
history(options) {
|
|
3395
|
+
return listAiPromptTemplateHistory(this.overrides.db, options);
|
|
3396
|
+
}
|
|
3001
3397
|
/** Local discovery for the model field (#4674's loopback probe). */
|
|
3002
3398
|
async discoverModels() {
|
|
3003
3399
|
const { discoverLocalInferenceModels } = await import("@happyvertical/smrt-core/byo-inference");
|
|
@@ -3118,140 +3514,6 @@ async function inferenceKeyIsSet(resolver) {
|
|
|
3118
3514
|
}
|
|
3119
3515
|
}
|
|
3120
3516
|
//#endregion
|
|
3121
|
-
//#region src/settings/preferences.ts
|
|
3122
|
-
var INFERENCE_PREFERENCE_KIND = "inference";
|
|
3123
|
-
var INFERENCE_PREFERENCE_SURFACE = "default";
|
|
3124
|
-
var CUSTOMIZE_INFERENCE_PERMISSION = "inference.customize";
|
|
3125
|
-
var PERSONALIZE_INFERENCE_PERMISSION = "inference.personalize";
|
|
3126
|
-
var INFERENCE_PERMISSION_DEFINITIONS = [{
|
|
3127
|
-
slug: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
3128
|
-
category: "inference",
|
|
3129
|
-
name: "Customize Inference",
|
|
3130
|
-
description: "Change the default inference mode, provider and model everyone in the tenant uses"
|
|
3131
|
-
}, {
|
|
3132
|
-
slug: PERSONALIZE_INFERENCE_PERMISSION,
|
|
3133
|
-
category: "inference",
|
|
3134
|
-
name: "Personalize Inference",
|
|
3135
|
-
description: "Keep a personal inference mode, provider and model on top of the tenant default"
|
|
3136
|
-
}];
|
|
3137
|
-
var PROVIDER_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
3138
|
-
var MODEL_PATTERN = /^[!-~\u00a1-\uffff]{1,200}$/;
|
|
3139
|
-
function issue(path, message) {
|
|
3140
|
-
return {
|
|
3141
|
-
path,
|
|
3142
|
-
code: "invalid_setting",
|
|
3143
|
-
message
|
|
3144
|
-
};
|
|
3145
|
-
}
|
|
3146
|
-
function validBaseUrl(value) {
|
|
3147
|
-
try {
|
|
3148
|
-
const url = new URL(value);
|
|
3149
|
-
return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.search && !url.hash;
|
|
3150
|
-
} catch {
|
|
3151
|
-
return false;
|
|
3152
|
-
}
|
|
3153
|
-
}
|
|
3154
|
-
function validateInferencePreferences(payload) {
|
|
3155
|
-
if (payload === null || payload === void 0) return {
|
|
3156
|
-
ok: true,
|
|
3157
|
-
canonical: null,
|
|
3158
|
-
issues: []
|
|
3159
|
-
};
|
|
3160
|
-
if (typeof payload !== "object" || Array.isArray(payload)) return {
|
|
3161
|
-
ok: false,
|
|
3162
|
-
canonical: null,
|
|
3163
|
-
issues: [issue("", "inference preferences are an object")]
|
|
3164
|
-
};
|
|
3165
|
-
const keyMember = findKeyMember(payload);
|
|
3166
|
-
if (keyMember) return {
|
|
3167
|
-
ok: false,
|
|
3168
|
-
canonical: null,
|
|
3169
|
-
issues: [issue(keyMember, "keys are never stored as preferences; they go to smrt-secrets")]
|
|
3170
|
-
};
|
|
3171
|
-
const input = payload;
|
|
3172
|
-
const issues = [];
|
|
3173
|
-
const canonical = {};
|
|
3174
|
-
for (const [member, value] of Object.entries(input)) {
|
|
3175
|
-
if (value === void 0 || value === null || value === "") continue;
|
|
3176
|
-
switch (member) {
|
|
3177
|
-
case "mode":
|
|
3178
|
-
if (INFERENCE_MODES.includes(value)) canonical.mode = value;
|
|
3179
|
-
else issues.push(issue(member, `mode is one of ${INFERENCE_MODES.join(", ")}`));
|
|
3180
|
-
break;
|
|
3181
|
-
case "provider":
|
|
3182
|
-
if (typeof value === "string" && PROVIDER_PATTERN.test(value)) canonical.provider = value;
|
|
3183
|
-
else issues.push(issue(member, "invalid provider id"));
|
|
3184
|
-
break;
|
|
3185
|
-
case "baseUrl":
|
|
3186
|
-
if (typeof value === "string" && validBaseUrl(value)) canonical.baseUrl = value;
|
|
3187
|
-
else issues.push(issue(member, "the base URL is an http(s) URL without credentials, query or fragment"));
|
|
3188
|
-
break;
|
|
3189
|
-
case "model":
|
|
3190
|
-
if (typeof value === "string" && MODEL_PATTERN.test(value)) canonical.model = value;
|
|
3191
|
-
else issues.push(issue(member, "invalid model id"));
|
|
3192
|
-
break;
|
|
3193
|
-
case "defaultTier":
|
|
3194
|
-
if (isInferenceTier(value)) canonical.defaultTier = value;
|
|
3195
|
-
else issues.push(issue(member, `the default tier is one of ${INFERENCE_TIERS.join(", ")}`));
|
|
3196
|
-
break;
|
|
3197
|
-
default: issues.push(issue(member, "unknown inference preference"));
|
|
3198
|
-
}
|
|
3199
|
-
}
|
|
3200
|
-
return {
|
|
3201
|
-
ok: issues.length === 0,
|
|
3202
|
-
canonical: Object.keys(canonical).length > 0 ? canonical : null,
|
|
3203
|
-
issues
|
|
3204
|
-
};
|
|
3205
|
-
}
|
|
3206
|
-
var inferencePreferenceKind = {
|
|
3207
|
-
kind: INFERENCE_PREFERENCE_KIND,
|
|
3208
|
-
formatVersion: 1,
|
|
3209
|
-
permissions: {
|
|
3210
|
-
tenant: CUSTOMIZE_INFERENCE_PERMISSION,
|
|
3211
|
-
user: PERSONALIZE_INFERENCE_PERMISSION
|
|
3212
|
-
},
|
|
3213
|
-
validate(payload) {
|
|
3214
|
-
return validateInferencePreferences(payload);
|
|
3215
|
-
}
|
|
3216
|
-
};
|
|
3217
|
-
function createInferencePreferences(store, surfaceId = INFERENCE_PREFERENCE_SURFACE) {
|
|
3218
|
-
return {
|
|
3219
|
-
async read() {
|
|
3220
|
-
const state = await store.load(INFERENCE_PREFERENCE_KIND, surfaceId);
|
|
3221
|
-
const tenant = state.tenant.payload ?? null;
|
|
3222
|
-
const user = state.user?.payload ?? null;
|
|
3223
|
-
return {
|
|
3224
|
-
choices: {
|
|
3225
|
-
...tenant ?? {},
|
|
3226
|
-
...user ?? {}
|
|
3227
|
-
},
|
|
3228
|
-
tenant,
|
|
3229
|
-
user,
|
|
3230
|
-
revisions: {
|
|
3231
|
-
tenant: state.tenant.revision,
|
|
3232
|
-
user: state.user?.revision ?? null
|
|
3233
|
-
},
|
|
3234
|
-
issues: state.issues,
|
|
3235
|
-
canCustomize: state.canCustomize
|
|
3236
|
-
};
|
|
3237
|
-
},
|
|
3238
|
-
/** Save choices at a scope (default `user`); `revision` is the one the client loaded. */
|
|
3239
|
-
write(choices, options) {
|
|
3240
|
-
return store.save(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
3241
|
-
scope: options.scope ?? "user",
|
|
3242
|
-
payload: choices,
|
|
3243
|
-
revision: options.revision
|
|
3244
|
-
});
|
|
3245
|
-
},
|
|
3246
|
-
reset(options = {}) {
|
|
3247
|
-
return store.reset(INFERENCE_PREFERENCE_KIND, surfaceId, {
|
|
3248
|
-
scope: options.scope ?? "user",
|
|
3249
|
-
revision: options.revision
|
|
3250
|
-
});
|
|
3251
|
-
}
|
|
3252
|
-
};
|
|
3253
|
-
}
|
|
3254
|
-
//#endregion
|
|
3255
3517
|
//#region src/settings/controller.ts
|
|
3256
3518
|
var USAGE_DIMENSIONS = [
|
|
3257
3519
|
"model",
|
|
@@ -3330,7 +3592,27 @@ function createInferenceSettingsController(options) {
|
|
|
3330
3592
|
};
|
|
3331
3593
|
}
|
|
3332
3594
|
};
|
|
3595
|
+
const readScope = async (session) => {
|
|
3596
|
+
await assertInferenceHistoryPermission(session);
|
|
3597
|
+
return { tenantId: session.tenantId };
|
|
3598
|
+
};
|
|
3333
3599
|
return {
|
|
3600
|
+
async compare(session, request) {
|
|
3601
|
+
const scope = await readScope(session);
|
|
3602
|
+
const parsed = parseInferenceHistoryRequest(request, true);
|
|
3603
|
+
return (await service(session)).compare({
|
|
3604
|
+
...parsed,
|
|
3605
|
+
...scope
|
|
3606
|
+
});
|
|
3607
|
+
},
|
|
3608
|
+
async history(session, request) {
|
|
3609
|
+
const scope = await readScope(session);
|
|
3610
|
+
const parsed = parseInferenceHistoryRequest(request, false);
|
|
3611
|
+
return (await service(session)).history({
|
|
3612
|
+
...parsed,
|
|
3613
|
+
...scope
|
|
3614
|
+
});
|
|
3615
|
+
},
|
|
3334
3616
|
canCustomize: (session) => session.can(CUSTOMIZE_INFERENCE_PERMISSION),
|
|
3335
3617
|
load: (session, by) => loadPage(options, session, by),
|
|
3336
3618
|
async saveDefaults(session, change) {
|
|
@@ -3403,6 +3685,6 @@ function createInferenceSettingsController(options) {
|
|
|
3403
3685
|
};
|
|
3404
3686
|
}
|
|
3405
3687
|
//#endregion
|
|
3406
|
-
export { AGENT_TOKEN_TTL_SECONDS, AGENT_TOOLS, AGENT_TOOL_INFO, APP_INFERENCE_SCOPE_ID, ASSISTANT_SETTING_KEYS, AgentLogin, CHATGPT_AUTH_HOST, CHATGPT_PLAN_PROVIDER, CHATGPT_SIGN_IN_WINDOW_MS, CLAUDE_MODEL_RANKS, CUSTOMIZE_INFERENCE_PERMISSION, ChatGPTSignedOutError, DEFAULT_AGENT_LIMITS, DEFAULT_TIER_BINDING, EngineModelFailure, INFERENCE_MODES, INFERENCE_PERMISSION_DEFINITIONS, INFERENCE_PREFERENCE_KIND, INFERENCE_PREFERENCE_SURFACE, InferenceBindingInUseError, InferenceBindingValueError, InferenceKeyOriginError, InferenceOverride, InferenceOverrideAuthorizationError, InferenceOverrideCollection, InferenceOverrideService, InferenceSettingsConfigError, InferenceSettingsService, InferenceTenantTargetNotAllowedError, InvalidInferenceScopeError, LOGIN_TIMEOUT_MS, MCP_SERVER_NAME, MODEL_FALLBACK_MESSAGE, OPENAI_MODEL_RANKS, PERSONALIZE_INFERENCE_PERMISSION, REDACTED_KEY, TOKEN_ENV, TRANSCRIPTS_BINDING, applyStoredTranscriptSettings, assertLoopbackUrl, assertValidInferenceScope, bindInferenceKey, browserCommand, buildAgentRun, buildInferenceOverrideLayers, candidateDirs, chatgptEngineStatus, chatgptFailureNote, childEnv, classifyChatGPTPlanFailure, claudeParser, cliEngineStatus, cliEnv, cliTool, codexParser, concreteTier, createAgentCliService, createChatGPTModel, createChatGPTPlanConnection, createChatGPTPlanResolver, createInferenceOverrideResolver, createInferencePreferences, createInferenceSettingsController, createInferenceSettingsHost, defaultLocateDeps, describeInferenceTarget, detectAgentCli, detectAgentClis, engineLabel, engineModelReply, engineModels, engineReasoningEffort, engineTierModel, inferenceEngineStatus, inferenceKeyFor, inferenceKeyIsSet, inferenceKeyOrigin, inferencePreferenceKind, inferenceProviderConfigFromKey, inferenceSettingsFailure, inferenceTargetRef, isAgentTool, isAllowedByList, isAssistantSettings, isChatGPTAuthorizationUrl, killTree, loadInferenceOverrideLayers, loadInferenceTranscriptSettings, locateBinary, locateCli, matchesAllowPattern, mergeSettingsConfigs, nextEngineModel, nextModel, nodeDir, normalizeTranscriptSettings, openSystemBrowser, parseInferenceBinding, preflightAgentCli, rankOpenAIModels, readInferenceOverrideRows, redactInferenceSecret, reportAgentFailure, resolveAssistantSettings, resolveEngineEffort, runAgentTurn, runCollect, runProcess, runWithModelFallback, saveInferenceKey, shellToolName, storedTranscriptSettings, stripKeyMembers, strongestModel, tierBinding, tokenCredentials, tokenFailureMessage, validateInferencePreferences, validateModelId, weakestModel };
|
|
3688
|
+
export { AGENT_TOKEN_TTL_SECONDS, AGENT_TOOLS, AGENT_TOOL_INFO, APP_INFERENCE_SCOPE_ID, ASSISTANT_SETTING_KEYS, AgentLogin, CHATGPT_AUTH_HOST, CHATGPT_PLAN_PROVIDER, CHATGPT_SIGN_IN_WINDOW_MS, CLAUDE_MODEL_RANKS, CUSTOMIZE_INFERENCE_PERMISSION, ChatGPTSignedOutError, DEFAULT_AGENT_LIMITS, DEFAULT_TIER_BINDING, EngineModelFailure, INFERENCE_HISTORY_TOOLS, INFERENCE_MODES, INFERENCE_PERMISSION_DEFINITIONS, INFERENCE_PREFERENCE_KIND, INFERENCE_PREFERENCE_SURFACE, InferenceBindingInUseError, InferenceBindingValueError, InferenceKeyOriginError, InferenceOverride, InferenceOverrideAuthorizationError, InferenceOverrideCollection, InferenceOverrideService, InferenceSettingsConfigError, InferenceSettingsService, InferenceTenantTargetNotAllowedError, InvalidInferenceScopeError, LOGIN_TIMEOUT_MS, MCP_SERVER_NAME, MODEL_FALLBACK_MESSAGE, OPENAI_MODEL_RANKS, PERSONALIZE_INFERENCE_PERMISSION, REDACTED_KEY, TOKEN_ENV, TRANSCRIPTS_BINDING, applyStoredTranscriptSettings, assertLoopbackUrl, assertValidInferenceScope, bindInferenceKey, browserCommand, buildAgentRun, buildInferenceOverrideLayers, candidateDirs, chatgptEngineStatus, chatgptFailureNote, childEnv, classifyChatGPTPlanFailure, claudeParser, cliEngineStatus, cliEnv, cliTool, codexParser, concreteTier, createAgentCliService, createChatGPTModel, createChatGPTPlanConnection, createChatGPTPlanResolver, createInferenceHistoryMcpTools, createInferenceOverrideResolver, createInferencePreferences, createInferenceSettingsController, createInferenceSettingsHost, createInferenceTranscriptMcpTool, defaultLocateDeps, describeInferenceTarget, detectAgentCli, detectAgentClis, engineLabel, engineModelReply, engineModels, engineReasoningEffort, engineTierModel, inferenceEngineStatus, inferenceHistoryInputSchema, inferenceHistoryResponse, inferenceKeyFor, inferenceKeyIsSet, inferenceKeyOrigin, inferencePreferenceKind, inferenceProviderConfigFromKey, inferenceSettingsFailure, inferenceTargetRef, inferenceTranscriptResponse, isAgentTool, isAllowedByList, isAssistantSettings, isChatGPTAuthorizationUrl, killTree, loadInferenceOverrideLayers, loadInferenceTranscriptSettings, locateBinary, locateCli, matchesAllowPattern, mergeSettingsConfigs, nextEngineModel, nextModel, nodeDir, normalizeTranscriptSettings, openSystemBrowser, parseInferenceBinding, parseInferenceHistoryRequest, preflightAgentCli, rankOpenAIModels, readInferenceOverrideRows, redactInferenceSecret, reportAgentFailure, resolveAssistantSettings, resolveEngineEffort, runAgentTurn, runCollect, runProcess, runWithModelFallback, saveInferenceKey, shellToolName, storedTranscriptSettings, stripKeyMembers, strongestModel, tierBinding, tokenCredentials, tokenFailureMessage, validateInferencePreferences, validateModelId, weakestModel };
|
|
3407
3689
|
|
|
3408
3690
|
//# sourceMappingURL=server.js.map
|