@happyvertical/smrt-inference 0.61.6 → 0.62.1

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.
Files changed (75) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +4 -0
  3. package/agents/engines.md +87 -90
  4. package/agents/fusions.md +13 -5
  5. package/dist/agent-cli/session.d.ts +8 -2
  6. package/dist/agent-cli/session.d.ts.map +1 -1
  7. package/dist/agent-cli/stream.d.ts +5 -0
  8. package/dist/agent-cli/stream.d.ts.map +1 -1
  9. package/dist/agent-cli/test-support.d.ts.map +1 -1
  10. package/dist/agent-cli/test-support.js +1 -1
  11. package/dist/agent-cli/test-support.js.map +1 -1
  12. package/dist/agent-cli/turn.d.ts +12 -5
  13. package/dist/agent-cli/turn.d.ts.map +1 -1
  14. package/dist/assistant-settings.d.ts +26 -0
  15. package/dist/assistant-settings.d.ts.map +1 -0
  16. package/dist/chatgpt/model.d.ts +14 -6
  17. package/dist/chatgpt/model.d.ts.map +1 -1
  18. package/dist/chunks/{InferenceOverrideCollection-Bd-FsdB1.js → InferenceOverrideCollection-DKtFQ5gd.js} +3 -66
  19. package/dist/chunks/InferenceOverrideCollection-DKtFQ5gd.js.map +1 -0
  20. package/dist/chunks/model-fallback-BVD3BzkG.js +171 -0
  21. package/dist/chunks/model-fallback-BVD3BzkG.js.map +1 -0
  22. package/dist/chunks/{provider-config-BSpIQRVM.js → provider-config-Q1WaQKfo.js} +164 -31
  23. package/dist/chunks/provider-config-Q1WaQKfo.js.map +1 -0
  24. package/dist/classify.d.ts +9 -0
  25. package/dist/classify.d.ts.map +1 -1
  26. package/dist/engine-tiers.d.ts +100 -0
  27. package/dist/engine-tiers.d.ts.map +1 -0
  28. package/dist/executor.d.ts.map +1 -1
  29. package/dist/fusion.d.ts +7 -1
  30. package/dist/fusion.d.ts.map +1 -1
  31. package/dist/index.d.ts +3 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +3 -3
  34. package/dist/index.js.map +1 -1
  35. package/dist/manifest.json +92 -205
  36. package/dist/model-fallback.d.ts +63 -0
  37. package/dist/model-fallback.d.ts.map +1 -0
  38. package/dist/models.d.ts +0 -1
  39. package/dist/models.d.ts.map +1 -1
  40. package/dist/models.js +2 -2
  41. package/dist/node.js +1 -1
  42. package/dist/resolver.js +1 -1
  43. package/dist/server.d.ts +3 -4
  44. package/dist/server.d.ts.map +1 -1
  45. package/dist/server.js +79 -130
  46. package/dist/server.js.map +1 -1
  47. package/dist/smrt-knowledge.json +16 -88
  48. package/dist/smrt-knowledge.okf.md +6 -11
  49. package/dist/svelte/components/InferenceAssistantSettings.svelte +98 -0
  50. package/dist/svelte/components/InferenceAssistantSettings.svelte.d.ts +19 -0
  51. package/dist/svelte/components/InferenceAssistantSettings.svelte.d.ts.map +1 -0
  52. package/dist/svelte/components/InferenceSettingsPanel.svelte +22 -1
  53. package/dist/svelte/components/InferenceSettingsPanel.svelte.d.ts +10 -2
  54. package/dist/svelte/components/InferenceSettingsPanel.svelte.d.ts.map +1 -1
  55. package/dist/svelte/components/InferenceUsageTable.svelte +7 -7
  56. package/dist/svelte/components/InferenceUsageTable.svelte.d.ts +1 -1
  57. package/dist/svelte/index.d.ts +1 -1
  58. package/dist/svelte/index.d.ts.map +1 -1
  59. package/dist/svelte/types.d.ts +27 -4
  60. package/dist/svelte/types.d.ts.map +1 -1
  61. package/dist/svelte/types.js +4 -4
  62. package/package.json +100 -9
  63. package/agents/design-runs.md +0 -110
  64. package/dist/chunks/InferenceOverrideCollection-Bd-FsdB1.js.map +0 -1
  65. package/dist/chunks/provider-config-BSpIQRVM.js.map +0 -1
  66. package/dist/chunks/work-profiles-DCgIbilc.js +0 -484
  67. package/dist/chunks/work-profiles-DCgIbilc.js.map +0 -1
  68. package/dist/design-run-store.d.ts +0 -26
  69. package/dist/design-run-store.d.ts.map +0 -1
  70. package/dist/design-run.d.ts +0 -146
  71. package/dist/design-run.d.ts.map +0 -1
  72. package/dist/models/DesignRunRecord.d.ts +0 -22
  73. package/dist/models/DesignRunRecord.d.ts.map +0 -1
  74. package/dist/work-profiles.d.ts +0 -127
  75. package/dist/work-profiles.d.ts.map +0 -1
package/dist/server.js CHANGED
@@ -1,8 +1,8 @@
1
- import { B as InferenceConfigError, I as findInferenceConfigIssues, N as findFusionDefinitionIssues, P as findFusionDefinitionPromptIssues, b as listFusions, f as createInferenceResolver, y as getFusion, z as validateInferenceTarget } from "./chunks/provider-config-BSpIQRVM.js";
2
- import { a as rankOpenAIWorkModels, c as runWorkModelWithFallback, d as engineLabel, f as AGENT_TOOLS, g as createDesignRunDriver, h as DesignRunConflictError, i as projectWorkModelSelection, l as strongestWorkModel, m as isAgentTool, n as WORK_MODEL_FALLBACK_MESSAGE, o as recommendedWorkProfile, p as AGENT_TOOL_INFO, r as nextWorkModel, s as resolveWorkProfile, t as OPENAI_WORK_MODEL_RANKS, u as validateWorkModel } from "./chunks/work-profiles-DCgIbilc.js";
1
+ import { B as InferenceConfigError, I as findInferenceConfigIssues, N as findFusionDefinitionIssues, P as findFusionDefinitionPromptIssues, b as listFusions, f as createInferenceResolver, y as getFusion, z as validateInferenceTarget } from "./chunks/provider-config-Q1WaQKfo.js";
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, T as installDesignRunExecutor, _ 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, w as DesignRunRecord, x as stripKeyMembers, y as normalizeTranscriptSettings } from "./chunks/InferenceOverrideCollection-Bd-FsdB1.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-DKtFQ5gd.js";
6
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";
7
7
  import { AI_PROVIDER_TYPES } from "@happyvertical/ai/types";
8
8
  import { getDefaultAIKeyEnvName } from "@happyvertical/smrt-config";
@@ -554,8 +554,14 @@ function usageTokens(value) {
554
554
  usage.cache_creation_input_tokens ?? 0
555
555
  ];
556
556
  if (!counts.every((count) => typeof count === "number" && Number.isSafeInteger(count) && count >= 0)) return {};
557
- const total = counts.reduce((sum, count) => sum + count, 0);
558
- return Number.isSafeInteger(total) ? { tokens: total } : {};
557
+ const [input, output, cacheRead, cacheWrite] = counts;
558
+ const inputTokens = input + cacheRead + cacheWrite;
559
+ const total = inputTokens + output;
560
+ return Number.isSafeInteger(total) ? {
561
+ tokens: total,
562
+ inputTokens,
563
+ outputTokens: output
564
+ } : {};
559
565
  }
560
566
  //#endregion
561
567
  //#region src/agent-cli/session.ts
@@ -585,9 +591,11 @@ function claudeSpec(input, runDir, work) {
585
591
  "--verbose",
586
592
  "--include-partial-messages",
587
593
  "--model",
588
- input.profile?.model ?? "fable",
589
- "--effort",
590
- input.profile?.effort ?? "high",
594
+ input.model ?? engineTierModel({
595
+ engine: "claude-code",
596
+ tier: "best"
597
+ }) ?? "fable",
598
+ ...input.effort ? ["--effort", engineReasoningEffort("claude-code", input.effort)] : [],
591
599
  ...input.outputSchema ? ["--json-schema", JSON.stringify(input.outputSchema)] : [],
592
600
  ...input.protection === false ? [] : [
593
601
  "--tools",
@@ -648,8 +656,9 @@ function codexSpec(input, runDir, work) {
648
656
  const server = `mcp_servers.${MCP_SERVER_NAME}`;
649
657
  const schemaPath = join(runDir, "output-schema.json");
650
658
  if (input.outputSchema) writeFileSync(schemaPath, JSON.stringify(input.outputSchema), { mode: 384 });
659
+ const effort = engineReasoningEffort("codex", input.effort);
651
660
  const overrides = [
652
- ["model_reasoning_effort", toml(input.profile?.effort === "max" ? "xhigh" : input.profile?.effort ?? "high")],
661
+ ...effort ? [["model_reasoning_effort", toml(effort)]] : [],
653
662
  ["sandbox_mode", toml(input.protection === false ? "danger-full-access" : "workspace-write")],
654
663
  ...input.protection === false ? [] : [
655
664
  ["sandbox_workspace_write.network_access", "false"],
@@ -677,7 +686,7 @@ function codexSpec(input, runDir, work) {
677
686
  ...input.resumeId ? ["resume"] : [],
678
687
  "--json",
679
688
  "--skip-git-repo-check",
680
- ...input.profile?.model ? ["-m", input.profile.model] : [],
689
+ ...input.model ? ["-m", input.model] : [],
681
690
  ...input.outputSchema ? ["--output-schema", schemaPath] : [],
682
691
  ...input.protection === false ? [] : [
683
692
  "--ignore-user-config",
@@ -708,7 +717,7 @@ function codexSpec(input, runDir, work) {
708
717
  }
709
718
  function buildAgentRun(input) {
710
719
  assertLoopbackUrl(input.mcpUrl);
711
- if (input.profile?.model !== void 0) validateWorkModel(input.profile.model);
720
+ if (input.model !== void 0) validateModelId(input.model);
712
721
  const runRoot = join(input.stateDir, "run");
713
722
  mkdirSync(runRoot, {
714
723
  recursive: true,
@@ -946,9 +955,8 @@ async function runAgentTurn(options) {
946
955
  }
947
956
  async function runAgentTurnImpl(options) {
948
957
  const { host, tool, deps } = options;
949
- if (options.profile && (options.profile.engine !== tool || !options.profile.model)) throw new Error("The work profile does not match this connected engine.");
950
- if (options.profile?.model !== void 0) validateWorkModel(options.profile.model);
951
- if (options.fallback?.nextModel !== void 0) validateWorkModel(options.fallback.nextModel);
958
+ if (options.model !== void 0) validateModelId(options.model);
959
+ if (options.fallback?.nextModel !== void 0) validateModelId(options.fallback.nextModel);
952
960
  const emit = (event) => {
953
961
  if (event.type === "error" && !event.message.includes(" Reference: ")) {
954
962
  const reference = reportAgentFailure(tool, "process", void 0, event.code);
@@ -962,12 +970,10 @@ async function runAgentTurnImpl(options) {
962
970
  let toolCalls = 0;
963
971
  let reportedModel;
964
972
  let reportedTokens;
973
+ let reportedSplit;
965
974
  const limits = {
966
975
  ...DEFAULT_AGENT_LIMITS,
967
- ...options.profile ? {
968
- turnTimeoutMs: options.profile.budgets.requestTimeoutMs,
969
- toolResultChars: options.profile.budgets.toolResultChars
970
- } : {},
976
+ ...options.limits,
971
977
  ...deps.limits
972
978
  };
973
979
  const label = AGENT_TOOL_INFO[tool].label;
@@ -1198,7 +1204,13 @@ async function runAgentTurnImpl(options) {
1198
1204
  reportedModel = event.model;
1199
1205
  return;
1200
1206
  case "done":
1201
- if (event.tokens !== void 0) reportedTokens = (reportedTokens ?? 0) + event.tokens;
1207
+ if (event.tokens !== void 0) {
1208
+ reportedTokens = (reportedTokens ?? 0) + event.tokens;
1209
+ reportedSplit = reportedSplit !== null && event.inputTokens !== void 0 && event.outputTokens !== void 0 ? {
1210
+ input: (reportedSplit?.input ?? 0) + event.inputTokens,
1211
+ output: (reportedSplit?.output ?? 0) + event.outputTokens
1212
+ } : null;
1213
+ }
1202
1214
  finished = event;
1203
1215
  if (!event.ok && event.error === "tool_host_policy") {
1204
1216
  emit({
@@ -1215,14 +1227,15 @@ async function runAgentTurnImpl(options) {
1215
1227
  const checkHostFailure = () => {
1216
1228
  if (hostFailure) throw hostFailure.error;
1217
1229
  };
1218
- let activeProfile = options.profile;
1230
+ let activeModel = options.model;
1219
1231
  let fallback;
1220
1232
  const attempt = async (resume) => {
1221
1233
  const guidance = await host.guidance();
1222
1234
  const spec = buildAgentRun({
1223
1235
  tool,
1224
1236
  protection: options.protection,
1225
- profile: activeProfile,
1237
+ ...activeModel ? { model: activeModel } : {},
1238
+ ...options.effort ? { effort: options.effort } : {},
1226
1239
  outputSchema: options.outputSchema,
1227
1240
  location,
1228
1241
  stateDir: await deps.stateDir(),
@@ -1259,16 +1272,14 @@ async function runAgentTurnImpl(options) {
1259
1272
  }
1260
1273
  };
1261
1274
  let result;
1262
- const requestedProfile = options.profile;
1263
- if (options.fallback && requestedProfile) {
1264
- const outcome = await runWorkModelWithFallback({
1275
+ const requestedModel = options.model;
1276
+ if (options.fallback && requestedModel) {
1277
+ const outcome = await runWithModelFallback({
1265
1278
  ...options.fallback,
1266
- profile: requestedProfile,
1279
+ engine: tool,
1280
+ model: requestedModel,
1267
1281
  execute: async (model, activity) => {
1268
- activeProfile = {
1269
- ...requestedProfile,
1270
- model
1271
- };
1282
+ activeModel = model;
1272
1283
  finished = null;
1273
1284
  reportedModel = void 0;
1274
1285
  const result2 = await attempt(resumeId);
@@ -1346,17 +1357,20 @@ async function runAgentTurnImpl(options) {
1346
1357
  ${note}`
1347
1358
  });
1348
1359
  }
1349
- const execution = options.profile ? {
1350
- profile: options.profile.name,
1360
+ const execution = {
1351
1361
  engine: tool,
1352
- model: reportedModel,
1353
- requestedModel: activeProfile?.model,
1362
+ ...reportedModel ? { model: reportedModel } : {},
1363
+ ...activeModel ? { requestedModel: activeModel } : {},
1354
1364
  ...fallback ? { fallback } : {},
1355
- effort: options.profile.effort,
1365
+ ...options.effort ? { effort: options.effort } : {},
1356
1366
  durationMs: Date.now() - startedAt,
1357
1367
  toolCalls,
1358
- ...reportedTokens !== void 0 ? { tokens: reportedTokens } : {}
1359
- } : void 0;
1368
+ ...reportedTokens !== void 0 ? { tokens: reportedTokens } : {},
1369
+ ...reportedSplit ? {
1370
+ inputTokens: reportedSplit.input,
1371
+ outputTokens: reportedSplit.output
1372
+ } : {}
1373
+ };
1360
1374
  if (options.protection === false) {
1361
1375
  pendingText = redactInferenceSecret(pendingText, token);
1362
1376
  if (pendingText) emit({
@@ -1364,18 +1378,15 @@ ${note}`
1364
1378
  delta: pendingText
1365
1379
  });
1366
1380
  }
1367
- if (pendingText || sessionId || execution) await host.appendMessage({
1381
+ if (pendingText || sessionId) await host.appendMessage({
1368
1382
  role: "assistant",
1369
1383
  content: pendingText,
1370
- ...sessionId ? { meta: {
1371
- cliSession: {
1372
- tool,
1373
- id: sessionId
1374
- },
1375
- ...execution ? { workRun: execution } : {}
1376
- } } : {}
1384
+ ...sessionId ? { meta: { cliSession: {
1385
+ tool,
1386
+ id: sessionId
1387
+ } } } : {}
1377
1388
  });
1378
- if (execution) await host.recordExecution?.(execution);
1389
+ await host.recordExecution?.(execution);
1379
1390
  emit({
1380
1391
  type: "done",
1381
1392
  stop
@@ -1834,7 +1845,7 @@ function createChatGPTPlanConnection(options) {
1834
1845
  if (!session) throw new ChatGPTSignedOutError();
1835
1846
  if (modelCache && modelCache.clientId === session.clientId && now() - modelCache.at < MODELS_TTL_MS) return modelCache.models;
1836
1847
  const clientOptions = await connection.clientOptions();
1837
- const models = rankOpenAIWorkModels((await (options.createClient ? await options.createClient(clientOptions) : await (await import("@happyvertical/ai")).getAI(clientOptions)).getModels()).map((m) => ({
1848
+ const models = rankOpenAIModels((await (options.createClient ? await options.createClient(clientOptions) : await (await import("@happyvertical/ai")).getAI(clientOptions)).getModels()).map((m) => ({
1838
1849
  id: m.id,
1839
1850
  label: m.name?.trim() || m.id,
1840
1851
  ...Number.isFinite(m.intelligenceRank) ? { intelligenceRank: m.intelligenceRank } : {}
@@ -1847,7 +1858,7 @@ function createChatGPTPlanConnection(options) {
1847
1858
  return models;
1848
1859
  },
1849
1860
  async defaultModel() {
1850
- return strongestWorkModel(await connection.models());
1861
+ return strongestModel(await connection.models());
1851
1862
  }
1852
1863
  };
1853
1864
  return connection;
@@ -2001,19 +2012,14 @@ function chatgptFailureNote(error, settingsHref) {
2001
2012
  //#endregion
2002
2013
  //#region src/chatgpt/model.ts
2003
2014
  async function createChatGPTModel(input) {
2004
- const catalog = input.catalog ?? (input.profile ? await input.connection.models?.() : void 0);
2005
- const profile = input.profile ? resolveWorkProfile({
2006
- profile: input.profile,
2015
+ const catalog = input.catalog ?? (input.tier && !input.model ? await input.connection.models?.() : void 0);
2016
+ const selectedModel = input.model ?? (input.tier ? engineTierModel({
2007
2017
  engine: "chatgpt",
2008
- settings: {
2009
- ...input.settings,
2010
- ...input.model ? { model: input.model } : {}
2011
- },
2018
+ tier: input.tier,
2012
2019
  catalog
2013
- }) : void 0;
2014
- if (profile && profile.engine !== "chatgpt") throw new Error("The work profile does not match this connected engine.");
2015
- const selectedModel = profile?.model ?? input.model;
2016
- if (selectedModel !== void 0) validateWorkModel(selectedModel);
2020
+ }) : void 0);
2021
+ if (input.tier && !selectedModel) throw new Error("The connected engine has no available model.");
2022
+ if (selectedModel !== void 0) validateModelId(selectedModel);
2017
2023
  const options = await input.connection.clientOptions({
2018
2024
  ...selectedModel ? { model: selectedModel } : {},
2019
2025
  toolNamespace: input.toolNamespace
@@ -2046,11 +2052,16 @@ async function createChatGPTModel(input) {
2046
2052
  };
2047
2053
  let fallback;
2048
2054
  let reply;
2049
- if (profile && input.fallback) {
2050
- const outcome = await runWorkModelWithFallback({
2055
+ if (selectedModel && input.fallback) {
2056
+ const outcome = await runWithModelFallback({
2051
2057
  ...input.fallback,
2052
- nextModel: input.fallback.nextModel ?? nextWorkModel(catalog ?? [], profile.model),
2053
- profile,
2058
+ nextModel: input.fallback.nextModel ?? nextEngineModel({
2059
+ engine: "chatgpt",
2060
+ model: selectedModel,
2061
+ catalog: catalog ?? []
2062
+ }),
2063
+ engine: "chatgpt",
2064
+ model: selectedModel,
2054
2065
  notify: (message) => {
2055
2066
  input.fallback?.notify?.(message);
2056
2067
  request.onText(`${message}
@@ -2068,14 +2079,13 @@ async function createChatGPTModel(input) {
2068
2079
  reply = outcome.result;
2069
2080
  fallback = outcome.fallback;
2070
2081
  } else reply = await execute(actualModel);
2071
- if (profile) await input.recordExecution?.({
2072
- profile: profile.name,
2082
+ await input.recordExecution?.({
2073
2083
  engine: "chatgpt",
2074
- model: reply.model,
2075
- requestedModel: actualModel,
2076
- effort: profile.effort,
2084
+ ...reply.model ? { model: reply.model } : {},
2085
+ ...actualModel ? { requestedModel: actualModel } : {},
2086
+ ...input.effort ? { effort: input.effort } : {},
2077
2087
  durationMs: Date.now() - startedAt,
2078
- tokens: reply.totalTokens,
2088
+ ...reply.totalTokens !== void 0 ? { tokens: reply.totalTokens } : {},
2079
2089
  toolCalls: reply.toolCalls.length,
2080
2090
  ...fallback ? { fallback } : {}
2081
2091
  });
@@ -2088,67 +2098,6 @@ async function createChatGPTModel(input) {
2088
2098
  } };
2089
2099
  }
2090
2100
  //#endregion
2091
- //#region src/design-run-store.ts
2092
- function createDesignRunStore(options) {
2093
- const { db, ownerId, tenantId } = options;
2094
- if (!ownerId) throw new Error("Design runs require an owner");
2095
- const tenantPredicate = tenantId === null ? "tenant_id IS NULL" : "tenant_id = ?";
2096
- const identity = (id) => tenantId === null ? [id, ownerId] : [
2097
- id,
2098
- ownerId,
2099
- tenantId
2100
- ];
2101
- const load = async (connection, id) => {
2102
- const result = await connection.query(`SELECT payload FROM _smrt_inference_design_runs WHERE id = ? AND owner_id = ? AND ${tenantPredicate}`, ...identity(id));
2103
- if (!result.rows.length) return null;
2104
- return JSON.parse(String(result.rows[0].payload));
2105
- };
2106
- return {
2107
- async load(id, requestedOwner) {
2108
- if (requestedOwner !== ownerId) return null;
2109
- return load(db, id);
2110
- },
2111
- async releaseLease(id, requestedOwner, leaseRevision) {
2112
- if (requestedOwner !== ownerId || !options.authorizeRelease) return false;
2113
- if (!db.transaction) throw new Error("Design runs require transaction support");
2114
- return db.transaction(async (tx) => {
2115
- const state = await load(tx, id);
2116
- if (state?.status !== "stopped" || state.leaseRevision !== leaseRevision) return false;
2117
- if (!await options.authorizeRelease?.(tx, state)) return false;
2118
- const next = {
2119
- ...state,
2120
- revision: state.revision + 1,
2121
- leaseUntil: void 0,
2122
- leaseRevision: void 0
2123
- };
2124
- return (await tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ?
2125
- WHERE id = ? AND owner_id = ? AND ${tenantPredicate} AND revision = ? RETURNING id`, next.revision, JSON.stringify(next), (/* @__PURE__ */ new Date()).toISOString(), ...identity(id), state.revision)).rows.length === 1;
2126
- });
2127
- },
2128
- async save(state, expectedRevision) {
2129
- if (state.ownerId !== ownerId) throw new Error("Design run not found");
2130
- if (!db.transaction) throw new Error("Design runs require transaction support");
2131
- return db.transaction(async (tx) => {
2132
- if (options.authorizeWrite && !await options.authorizeWrite(tx, state)) return false;
2133
- const previous = await load(tx, state.id);
2134
- const encoded = JSON.stringify(state);
2135
- const date = (/* @__PURE__ */ new Date()).toISOString();
2136
- if (expectedRevision === null) {
2137
- if ((await tx.query(`INSERT INTO _smrt_inference_design_runs
2138
- (id, slug, context, created_at, updated_at, owner_id, tenant_id, revision, payload)
2139
- VALUES (?, ?, '', ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING RETURNING id`, state.id, state.id, date, date, ownerId, tenantId, state.revision, encoded)).rows.length !== 1) return false;
2140
- } else {
2141
- if (!previous || state.revision !== expectedRevision + 1) return false;
2142
- if ((await tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ?
2143
- WHERE id = ? AND owner_id = ? AND ${tenantPredicate} AND revision = ? RETURNING id`, state.revision, encoded, date, ...identity(state.id), expectedRevision)).rows.length !== 1) return false;
2144
- }
2145
- if (state.status === "running" && (!previous || previous.status === "stopped" || previous.status === "waiting-approval")) await options.enqueue(tx, state);
2146
- return true;
2147
- });
2148
- }
2149
- };
2150
- }
2151
- //#endregion
2152
2101
  //#region src/engine-status.ts
2153
2102
  function cliTool(engine) {
2154
2103
  return engine === "claude-code" || engine === "codex" ? engine : null;
@@ -3454,6 +3403,6 @@ function createInferenceSettingsController(options) {
3454
3403
  };
3455
3404
  }
3456
3405
  //#endregion
3457
- export { AGENT_TOKEN_TTL_SECONDS, AGENT_TOOLS, AGENT_TOOL_INFO, APP_INFERENCE_SCOPE_ID, AgentLogin, CHATGPT_AUTH_HOST, CHATGPT_PLAN_PROVIDER, CHATGPT_SIGN_IN_WINDOW_MS, CUSTOMIZE_INFERENCE_PERMISSION, ChatGPTSignedOutError, DEFAULT_AGENT_LIMITS, DEFAULT_TIER_BINDING, DesignRunConflictError, DesignRunRecord, 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, OPENAI_WORK_MODEL_RANKS, PERSONALIZE_INFERENCE_PERMISSION, REDACTED_KEY, TOKEN_ENV, TRANSCRIPTS_BINDING, WORK_MODEL_FALLBACK_MESSAGE, applyStoredTranscriptSettings, assertLoopbackUrl, assertValidInferenceScope, bindInferenceKey, browserCommand, buildAgentRun, buildInferenceOverrideLayers, candidateDirs, chatgptEngineStatus, chatgptFailureNote, childEnv, classifyChatGPTPlanFailure, claudeParser, cliEngineStatus, cliEnv, cliTool, codexParser, createAgentCliService, createChatGPTModel, createChatGPTPlanConnection, createChatGPTPlanResolver, createDesignRunDriver, createDesignRunStore, createInferenceOverrideResolver, createInferencePreferences, createInferenceSettingsController, createInferenceSettingsHost, defaultLocateDeps, describeInferenceTarget, detectAgentCli, detectAgentClis, engineLabel, engineModelReply, inferenceEngineStatus, inferenceKeyFor, inferenceKeyIsSet, inferenceKeyOrigin, inferencePreferenceKind, inferenceProviderConfigFromKey, inferenceSettingsFailure, inferenceTargetRef, installDesignRunExecutor, isAgentTool, isAllowedByList, isChatGPTAuthorizationUrl, killTree, loadInferenceOverrideLayers, loadInferenceTranscriptSettings, locateBinary, locateCli, matchesAllowPattern, mergeSettingsConfigs, nextWorkModel, nodeDir, normalizeTranscriptSettings, openSystemBrowser, parseInferenceBinding, preflightAgentCli, projectWorkModelSelection, rankOpenAIWorkModels, readInferenceOverrideRows, recommendedWorkProfile, redactInferenceSecret, reportAgentFailure, resolveWorkProfile, runAgentTurn, runCollect, runProcess, runWorkModelWithFallback, saveInferenceKey, shellToolName, storedTranscriptSettings, stripKeyMembers, strongestWorkModel, tierBinding, tokenCredentials, tokenFailureMessage, validateInferencePreferences, validateWorkModel };
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 };
3458
3407
 
3459
3408
  //# sourceMappingURL=server.js.map