@leitwerk-dev/server 0.5.3 → 0.5.5

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 (84) hide show
  1. package/dist/{app-DZUsf76a.d.ts → app-DWWNqFtH.d.ts} +83 -77
  2. package/dist/app-VLQCV5WS.js +8 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/{chunk-6EEU4QOU.js → chunk-65CBLH7U.js} +350 -144
  5. package/dist/chunk-65CBLH7U.js.map +1 -0
  6. package/dist/chunk-C2K2AM5X.js +82 -0
  7. package/dist/chunk-C2K2AM5X.js.map +1 -0
  8. package/dist/{chunk-AJ2DQWI3.js → chunk-I3CCVPXY.js} +133 -83
  9. package/dist/chunk-I3CCVPXY.js.map +1 -0
  10. package/dist/config/config-loader.d.ts.map +1 -1
  11. package/dist/dashboard-model-issues.d.ts.map +1 -1
  12. package/dist/deployment-preflight.d.ts +2 -1
  13. package/dist/deployment-preflight.d.ts.map +1 -1
  14. package/dist/extension-boot-check.d.ts +5 -0
  15. package/dist/extension-boot-check.d.ts.map +1 -0
  16. package/dist/future-execution/execution.d.ts.map +1 -1
  17. package/dist/future-execution/launch-lifecycle.d.ts.map +1 -1
  18. package/dist/future-execution/lifecycle.d.ts.map +1 -1
  19. package/dist/future-execution/reconciliation.d.ts.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +41 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/main.js +6 -71
  25. package/dist/main.js.map +1 -1
  26. package/dist/process-engine/ops/execute-action.d.ts.map +1 -1
  27. package/dist/process-engine/ops/retry-startup.d.ts.map +1 -1
  28. package/dist/process-engine/turn-start-preflight.d.ts.map +1 -1
  29. package/dist/process-model-config.d.ts.map +1 -1
  30. package/dist/process-model-policy/construct.d.ts +1 -0
  31. package/dist/process-model-policy/construct.d.ts.map +1 -1
  32. package/dist/process-model-policy/evaluate.d.ts +3 -3
  33. package/dist/process-model-policy/evaluate.d.ts.map +1 -1
  34. package/dist/process-model-policy/index.d.ts +1 -0
  35. package/dist/process-model-policy/index.d.ts.map +1 -1
  36. package/dist/process-model-policy/launch.d.ts.map +1 -1
  37. package/dist/process-model-policy/project.d.ts.map +1 -1
  38. package/dist/process-model-policy/requirements.d.ts +16 -0
  39. package/dist/process-model-policy/requirements.d.ts.map +1 -0
  40. package/dist/process-model-policy/types.d.ts +87 -75
  41. package/dist/process-model-policy/types.d.ts.map +1 -1
  42. package/dist/process-model-policy-presenter.d.ts.map +1 -1
  43. package/dist/process-model-selection.d.ts.map +1 -1
  44. package/dist/process-title-generator.d.ts +2 -0
  45. package/dist/process-title-generator.d.ts.map +1 -1
  46. package/dist/routes/process-actions.d.ts.map +1 -1
  47. package/dist/supervisor/worker-start-payload-builder.d.ts.map +1 -1
  48. package/dist/test-helpers/process-model-fixtures.d.ts +6 -0
  49. package/dist/test-helpers/process-model-fixtures.d.ts.map +1 -1
  50. package/dist/testing.js +1 -1
  51. package/package.json +12 -12
  52. package/src/app.ts +21 -0
  53. package/src/config/config-loader.ts +5 -0
  54. package/src/dashboard-model-issues.ts +66 -5
  55. package/src/deployment-preflight.ts +15 -7
  56. package/src/extension-boot-check.ts +36 -0
  57. package/src/future-execution/execution.ts +3 -8
  58. package/src/future-execution/launch-lifecycle.ts +15 -10
  59. package/src/future-execution/lifecycle.ts +1 -0
  60. package/src/future-execution/reconciliation.ts +2 -34
  61. package/src/index.ts +1 -0
  62. package/src/launch-coordinator.ts +2 -2
  63. package/src/process-engine/ops/execute-action.ts +1 -0
  64. package/src/process-engine/ops/retry-startup.ts +10 -12
  65. package/src/process-engine/turn-start-preflight.ts +38 -15
  66. package/src/process-model-config.ts +7 -3
  67. package/src/process-model-policy/construct.ts +61 -3
  68. package/src/process-model-policy/evaluate.ts +73 -64
  69. package/src/process-model-policy/index.ts +16 -14
  70. package/src/process-model-policy/launch.ts +27 -29
  71. package/src/process-model-policy/project.ts +72 -43
  72. package/src/process-model-policy/requirements.ts +73 -0
  73. package/src/process-model-policy/types.ts +108 -78
  74. package/src/process-model-policy-presenter.ts +18 -2
  75. package/src/process-model-selection.ts +2 -0
  76. package/src/process-title-generator.ts +12 -16
  77. package/src/routes/launchers.ts +1 -1
  78. package/src/routes/process-actions.ts +1 -0
  79. package/src/supervisor/worker-start-payload-builder.ts +6 -1
  80. package/src/test-helpers/process-model-fixtures.ts +25 -4
  81. package/dist/app-2TCRADVA.js +0 -8
  82. package/dist/chunk-6EEU4QOU.js.map +0 -1
  83. package/dist/chunk-AJ2DQWI3.js.map +0 -1
  84. /package/dist/{app-2TCRADVA.js.map → app-VLQCV5WS.js.map} +0 -0
@@ -1,5 +1,6 @@
1
1
  import type { DurableModelSelection, TurnStartRecord } from "@leitwerk-dev/domain";
2
2
  import { trimToNull } from "@leitwerk-dev/domain";
3
+ import { profileRejections, rankedProfiles, requirementLayers } from "./requirements.js";
3
4
  import type {
4
5
  ExistingTurnSelection,
5
6
  ModelConfiguration,
@@ -8,6 +9,7 @@ import type {
8
9
  PolicySnapshot,
9
10
  ProcessModelAvailabilitySnapshot,
10
11
  ProcessModelPolicyEvaluation,
12
+ SkippedModelPreference,
11
13
  ValidModelConfiguration,
12
14
  } from "./types.js";
13
15
  import { isPinnedModelSelection, provenanceKindForSource } from "./types.js";
@@ -16,6 +18,8 @@ function processPolicy(snapshot: PolicySnapshot, processId: string): PolicyProce
16
18
  return (
17
19
  snapshot.processesById.get(processId) ?? {
18
20
  id: processId,
21
+ requirements: [],
22
+ turnRequirements: {},
19
23
  allowedProfileIds: null,
20
24
  defaultProfileId: null,
21
25
  turnProfileIds: {},
@@ -32,6 +36,7 @@ export function validateSelection(
32
36
  processId: string,
33
37
  selection: DurableModelSelection | null,
34
38
  availability?: ProcessModelAvailabilitySnapshot,
39
+ turnId?: string,
35
40
  ): ProcessModelPolicyEvaluation {
36
41
  if (!selection)
37
42
  return {
@@ -50,12 +55,14 @@ export function validateSelection(
50
55
  ...(availability ? { availabilityRevision: availability.revision } : {}),
51
56
  };
52
57
  const policy = processPolicy(snapshot, processId);
53
- if (policy.allowedProfileIds && !policy.allowedProfileIds.has(profile.id))
58
+ const rejections = profileRejections(policy, profile, turnId);
59
+ if (rejections.length)
54
60
  return {
55
61
  ok: false,
56
62
  code: "model_profile_not_allowed",
57
63
  modelProfileId: profile.id,
58
64
  processId,
65
+ rejections,
59
66
  selection,
60
67
  ...(availability ? { availabilityRevision: availability.revision } : {}),
61
68
  };
@@ -87,7 +94,10 @@ function candidate(
87
94
  | "instance_default"
88
95
  | "process_config_default"
89
96
  | "catalog_default"
90
- | "scoped_purpose_default",
97
+ | "scoped_purpose_default"
98
+ | "marked_default"
99
+ | "automatic"
100
+ | "fixed_purpose",
91
101
  ): DurableModelSelection | null {
92
102
  const id = trimToNull(modelProfileId);
93
103
  return id
@@ -120,26 +130,6 @@ export function resolveDefault(
120
130
  );
121
131
  }
122
132
 
123
- function resolveInherited(
124
- snapshot: PolicySnapshot,
125
- configuration: ValidModelConfiguration,
126
- turnId: string,
127
- ): DurableModelSelection | null {
128
- const policy = processPolicy(snapshot, configuration.processId);
129
- const instanceTurn = candidate(configuration.turnProfileIds.get(turnId), "instance_turn_config");
130
- if (instanceTurn) return instanceTurn;
131
- const instanceDefault = candidate(configuration.defaultProfileId, "instance_default");
132
- if (instanceDefault) return instanceDefault;
133
- const scopedDefault = candidate(
134
- policy.scopedProfileIdForTurn?.(turnId),
135
- "scoped_purpose_default",
136
- );
137
- if (scopedDefault) return scopedDefault;
138
- const processTurn = candidate(policy.turnProfileIds[turnId], "process_config_turn");
139
- if (processTurn) return processTurn;
140
- return resolvedDefault(snapshot, configuration);
141
- }
142
-
143
133
  function invalidConfiguration(
144
134
  configuration: Extract<ModelConfiguration, { kind: "invalid" }>,
145
135
  ): ProcessModelPolicyEvaluation {
@@ -156,7 +146,7 @@ export function resolveTurn(
156
146
  snapshot: PolicySnapshot,
157
147
  configuration: ModelConfiguration,
158
148
  turnId: string,
159
- mode: "resolve" | "initial" | "retry" | "continue",
149
+ preservePinnedSelection: boolean,
160
150
  existingSelection: ExistingTurnSelection,
161
151
  override: ModelOverride,
162
152
  availability?: ProcessModelAvailabilitySnapshot,
@@ -164,15 +154,11 @@ export function resolveTurn(
164
154
  const policy = processPolicy(snapshot, configuration.processId);
165
155
  if (!policy.llmTurnIds.has(turnId)) return { ok: true, selection: null };
166
156
  if (configuration.kind === "invalid") return invalidConfiguration(configuration);
157
+ const validate = (selection: DurableModelSelection | null) =>
158
+ validateSelection(snapshot, configuration.processId, selection, availability, turnId);
167
159
  // A configured code-defined purpose is authoritative over launch/action overrides.
168
160
  const purposeProfileId = policy.purposeProfileIdsByTurn[turnId];
169
- if (purposeProfileId)
170
- return validateSelection(
171
- snapshot,
172
- configuration.processId,
173
- candidate(purposeProfileId, "process_config_default"),
174
- availability,
175
- );
161
+ if (purposeProfileId) return validate(candidate(purposeProfileId, "fixed_purpose"));
176
162
  if (existingSelection.kind === "invalid" && existingSelection.turnId === turnId)
177
163
  return {
178
164
  ok: false,
@@ -186,34 +172,68 @@ export function resolveTurn(
186
172
  existingSelection = { kind: "none" };
187
173
  }
188
174
  if (override.kind === "profile")
189
- return validateSelection(
190
- snapshot,
191
- configuration.processId,
192
- {
193
- modelProfileId: override.profileId,
194
- provenance: { kind: "explicit", source: override.source },
195
- },
196
- availability,
197
- );
175
+ return validate({
176
+ modelProfileId: override.profileId,
177
+ provenance: { kind: "explicit", source: override.source },
178
+ });
198
179
  if (
199
180
  existingSelection.kind === "selected" &&
200
- (mode === "initial" || mode === "retry" || mode === "continue") &&
181
+ preservePinnedSelection &&
201
182
  existingSelection.turnId === turnId &&
202
183
  isPinnedModelSelection(existingSelection.selection)
203
184
  )
204
- return validateSelection(
205
- snapshot,
206
- configuration.processId,
207
- existingSelection.selection,
208
- availability,
209
- );
185
+ return validate(existingSelection.selection);
210
186
  try {
211
- return validateSelection(
212
- snapshot,
213
- configuration.processId,
214
- resolveInherited(snapshot, configuration, turnId),
215
- availability,
216
- );
187
+ const skippedPreferences: SkippedModelPreference[] = [];
188
+ const explain = (result: ProcessModelPolicyEvaluation): ProcessModelPolicyEvaluation => ({
189
+ ...result,
190
+ skippedPreferences,
191
+ });
192
+ const preferences = [
193
+ () => candidate(configuration.turnProfileIds.get(turnId), "instance_turn_config"),
194
+ () => candidate(configuration.defaultProfileId, "instance_default"),
195
+ () => candidate(policy.scopedProfileIdForTurn?.(turnId), "scoped_purpose_default"),
196
+ () => candidate(policy.turnProfileIds[turnId], "process_config_turn"),
197
+ () => candidate(policy.defaultProfileId, "process_config_default"),
198
+ () => candidate(snapshot.defaultProfileId, "catalog_default"),
199
+ ];
200
+ for (const getPreference of preferences) {
201
+ const preference = getPreference();
202
+ if (!preference) continue;
203
+ const result = validate(preference);
204
+ if (
205
+ !result.ok &&
206
+ result.code === "model_profile_not_allowed" &&
207
+ preference.provenance.source !== "instance_turn_config"
208
+ ) {
209
+ skippedPreferences.push({
210
+ profileId: preference.modelProfileId,
211
+ source: preference.provenance.source,
212
+ rejections: result.rejections ?? [],
213
+ });
214
+ continue;
215
+ }
216
+ return explain(result);
217
+ }
218
+ const ranked = rankedProfiles(policy, snapshot.profiles, turnId);
219
+ if (!ranked.profiles.length)
220
+ return {
221
+ ok: false,
222
+ code: "model_required",
223
+ selection: null,
224
+ skippedPreferences,
225
+ ...(availability ? { availabilityRevision: availability.revision } : {}),
226
+ requirements: requirementLayers(policy, turnId),
227
+ };
228
+ return {
229
+ ...explain(
230
+ validate(candidate(ranked.profiles[0]?.id, ranked.marked ? "marked_default" : "automatic")),
231
+ ),
232
+ ranking: {
233
+ kind: ranked.marked ? "marked_defaults" : "cost_id",
234
+ tiedProfileIds: ranked.tiedProfileIds,
235
+ },
236
+ };
217
237
  } catch (error) {
218
238
  return {
219
239
  ok: false,
@@ -230,7 +250,6 @@ export function recoverPreparation(
230
250
  snapshot: PolicySnapshot,
231
251
  cause: "availability_transition" | "startup_reconciliation",
232
252
  configuration: ModelConfiguration,
233
- existingSelection: ExistingTurnSelection,
234
253
  currentStart: TurnStartRecord,
235
254
  availability: ProcessModelAvailabilitySnapshot,
236
255
  ): ProcessModelPolicyEvaluation {
@@ -250,21 +269,11 @@ export function recoverPreparation(
250
269
  };
251
270
  const profileId = trimToNull(state.requestedModelProfileId);
252
271
  const provenance = state.modelSelectionProvenance;
253
- if (provenance?.kind === "inherited") {
254
- return resolveTurn(
255
- snapshot,
256
- configuration,
257
- currentStart.turnId,
258
- "retry",
259
- existingSelection,
260
- { kind: "inherit" },
261
- availability,
262
- );
263
- }
264
272
  return validateSelection(
265
273
  snapshot,
266
274
  configuration.processId,
267
275
  profileId && provenance ? { modelProfileId: profileId, provenance } : null,
268
276
  availability,
277
+ currentStart.turnId,
269
278
  );
270
279
  }
@@ -53,16 +53,6 @@ export type {
53
53
  export { isPinnedModelSelection } from "./types.js";
54
54
  export { ProcessModelPolicyConfigurationError };
55
55
 
56
- function resolutionMode(
57
- startKind: Extract<ProcessModelPolicyEvaluationSubject, { kind: "process_turn" }>["startKind"],
58
- initialSelection: boolean | undefined,
59
- ): "resolve" | "initial" | "retry" | "continue" {
60
- if (startKind === "retry" || startKind === "startup_retry") return "retry";
61
- if (startKind === "continue") return "continue";
62
- if (initialSelection) return "initial";
63
- return "resolve";
64
- }
65
-
66
56
  function evaluateSubject(
67
57
  snapshot: PolicySnapshot,
68
58
  request: ProcessModelPolicyEvaluationSubject,
@@ -72,7 +62,10 @@ function evaluateSubject(
72
62
  snapshot,
73
63
  modelConfigurationFromProcess(request.process),
74
64
  request.turnId,
75
- resolutionMode(request.startKind, request.initialSelection),
65
+ request.initialSelection === true ||
66
+ request.startKind === "retry" ||
67
+ request.startKind === "startup_retry" ||
68
+ request.startKind === "continue",
76
69
  existingTurnSelectionFromProcess(request.process),
77
70
  modelOverride(
78
71
  request.modelOverride,
@@ -92,20 +85,25 @@ function evaluateSubject(
92
85
  turnConfigsJson: request.plan.processInput.turnConfigsJson,
93
86
  }),
94
87
  request.turnId,
95
- "resolve",
88
+ false,
96
89
  { kind: "none" },
97
90
  modelOverride(selected, selected !== null, "launch_override"),
98
91
  request.availability,
99
92
  );
100
93
  }
101
94
  if (request.kind === "runtime_selection") {
102
- return validateSelection(snapshot, request.processId, request.selection, request.availability);
95
+ return validateSelection(
96
+ snapshot,
97
+ request.processId,
98
+ request.selection,
99
+ request.availability,
100
+ request.target.kind === "turn" ? request.target.turnId : undefined,
101
+ );
103
102
  }
104
103
  return recoverPreparation(
105
104
  snapshot,
106
105
  request.cause,
107
106
  modelConfigurationFromProcess(request.process),
108
- existingTurnSelectionFromProcess(request.process),
109
107
  request.currentStart,
110
108
  request.availability,
111
109
  );
@@ -116,6 +114,10 @@ export function createServerProcessModelPolicy(input: {
116
114
  config: LeitwerkConfig;
117
115
  processGraphs: ProcessGraphRegistry;
118
116
  processActionRegistry: Pick<ProcessActionRegistry, "getTurnDefinition">;
117
+ capabilities?: (
118
+ providerId: string,
119
+ modelId: string,
120
+ ) => Readonly<Record<string, boolean | "unknown">>;
119
121
  scopedSettings?: Pick<ScopedSettingsService, "modelDefault">;
120
122
  }): ServerProcessModelPolicy {
121
123
  const snapshot = constructPolicySnapshot(input);
@@ -106,7 +106,8 @@ export function prepareLaunchPlan(
106
106
  const invalidMode = opts.invalidModelConfig ?? "reject";
107
107
  const warnings: LaunchPlanPreparationIssue[] = [];
108
108
  const errors: LaunchPlanPreparationIssue[] = [];
109
- const report = (issue: LaunchPlanPreparationIssue): void => {
109
+ const report = (issue: LaunchPlanPreparationIssue | null): void => {
110
+ if (!issue) return;
110
111
  if (invalidMode === "reject") errors.push(issue);
111
112
  else warnings.push(issue);
112
113
  };
@@ -121,7 +122,7 @@ export function prepareLaunchPlan(
121
122
  : parsed.error.reason === "not_object"
122
123
  ? "turnConfigsJson must be an object"
123
124
  : `turnConfigsJson.${parsed.error.turnId ?? "<unknown>"} must be an object`;
124
- report(issue(parsed.error.code, message));
125
+ errors.push(issue(parsed.error.code, message));
125
126
  }
126
127
  const baseConfig: LaunchModelConfigInput = {
127
128
  defaultModelProfileId: launchPlan.processInput.defaultModelProfileId ?? null,
@@ -136,29 +137,29 @@ export function prepareLaunchPlan(
136
137
  const policy = snapshot.processesById.get(launchPlan.processId);
137
138
  const llmTurns = policy?.llmTurnIds ?? new Set<string>();
138
139
  const validTurns: Record<string, { modelProfileId: string }> = {};
139
- let defaultModelProfileId = normalized.defaultModelProfileId ?? null;
140
+ const defaultModelProfileId = normalized.defaultModelProfileId ?? null;
140
141
  const modelIssue = (
141
142
  profileId: string | null,
142
143
  modelTarget: ModelTarget,
143
144
  ): LaunchPlanPreparationIssue | null => {
144
145
  if (!profileId) return null;
145
- const result = validateSelection(snapshot, launchPlan.processId, {
146
- modelProfileId: profileId,
147
- provenance: { kind: "explicit", source: "instance_default" },
148
- });
146
+ const result = validateSelection(
147
+ snapshot,
148
+ launchPlan.processId,
149
+ {
150
+ modelProfileId: profileId,
151
+ provenance: { kind: "explicit", source: "instance_default" },
152
+ },
153
+ undefined,
154
+ modelTarget.kind === "default_model" ? undefined : (modelTarget.turnId ?? undefined),
155
+ );
149
156
  return result.ok ? null : issueForPolicy(result, launchPlan.processId, modelTarget);
150
157
  };
151
- const validate = (profileId: string | null, modelTarget: ModelTarget): boolean => {
152
- const issue = modelIssue(profileId, modelTarget);
153
- if (!issue) return true;
154
- report(issue);
155
- return false;
156
- };
157
- if (!validate(defaultModelProfileId, target("default_model"))) defaultModelProfileId = null;
158
+ report(modelIssue(defaultModelProfileId, target("default_model")));
158
159
  for (const [turnId, config] of Object.entries(normalized.turnConfigs ?? {})) {
159
160
  const profileId = config.modelProfileId?.trim() || null;
160
161
  if (!llmTurns.has(turnId)) {
161
- report(
162
+ errors.push(
162
163
  issue(
163
164
  "unknown_llm_turn",
164
165
  `Turn '${turnId}' is not a known LLM turn for process '${launchPlan.processId}'`,
@@ -166,31 +167,28 @@ export function prepareLaunchPlan(
166
167
  );
167
168
  continue;
168
169
  }
169
- if (profileId && validate(profileId, target("turn_model", turnId))) {
170
+ if (profileId) {
171
+ report(modelIssue(profileId, target("turn_model", turnId)));
170
172
  validTurns[turnId] = { modelProfileId: profileId };
171
173
  }
172
174
  }
173
175
 
174
176
  const selectedTurnId = launchPlan.startTurnId ?? launchPlan.processInput.selectedTurnId;
175
- const selectedProfileId = launchPlan.processInput.selectedTurnModelProfileId?.trim() || null;
176
- let selectedModelProfileId = selectedProfileId;
177
- const selectedTurnIssue: LaunchPlanPreparationIssue | null = !selectedProfileId
177
+ const selectedModelProfileId = launchPlan.processInput.selectedTurnModelProfileId?.trim() || null;
178
+ const selectedTurnIssue: LaunchPlanPreparationIssue | null = !selectedModelProfileId
178
179
  ? null
179
180
  : !selectedTurnId
180
181
  ? issue(
181
182
  "selected_turn_model_requires_selected_turn",
182
- `Selected turn model profile '${selectedProfileId}' requires a selected turn`,
183
+ `Selected turn model profile '${selectedModelProfileId}' requires a selected turn`,
183
184
  )
184
185
  : !llmTurns.has(selectedTurnId)
185
186
  ? issue(
186
187
  "selected_turn_model_requires_llm_turn",
187
- `Selected turn model profile '${selectedProfileId}' requires selected turn '${selectedTurnId}' to be an LLM turn`,
188
+ `Selected turn model profile '${selectedModelProfileId}' requires selected turn '${selectedTurnId}' to be an LLM turn`,
188
189
  )
189
- : modelIssue(selectedProfileId, target("selected_turn_model", selectedTurnId));
190
- if (selectedTurnIssue) {
191
- report(selectedTurnIssue);
192
- if (invalidMode !== "reject") selectedModelProfileId = null;
193
- }
190
+ : modelIssue(selectedModelProfileId, target("selected_turn_model", selectedTurnId));
191
+ report(selectedTurnIssue);
194
192
 
195
193
  const modelConfig = { defaultModelProfileId, turnConfigs: validTurns };
196
194
  let initialDefaultModelProfileId = null;
@@ -198,16 +196,16 @@ export function prepareLaunchPlan(
198
196
  const defaultResult = resolveDefault(snapshot, configuration);
199
197
  if (defaultResult.ok)
200
198
  initialDefaultModelProfileId = defaultResult.selection?.modelProfileId ?? null;
201
- if (selectedTurnId && !selectedModelProfileId) {
199
+ if (selectedTurnId && !selectedModelProfileId && errors.length === 0 && warnings.length === 0) {
202
200
  const turnResult = resolveTurn(
203
201
  snapshot,
204
202
  configuration,
205
203
  selectedTurnId,
206
- "resolve",
204
+ false,
207
205
  { kind: "none" },
208
206
  { kind: "inherit" },
209
207
  );
210
- if (!turnResult.ok && turnResult.code === "model_required") {
208
+ if (!turnResult.ok) {
211
209
  report(
212
210
  issueForPolicy(
213
211
  turnResult,
@@ -1,4 +1,5 @@
1
1
  import { trimToNull } from "@leitwerk-dev/domain";
2
+ import { compareModelProfileIds, modelCostRank } from "@leitwerk-dev/protocol";
2
3
  import { presentProcessModelPolicyFailure } from "../process-model-policy-presenter.js";
3
4
  import { resolveDefault, resolveTurn } from "./evaluate.js";
4
5
  import {
@@ -6,45 +7,17 @@ import {
6
7
  modelConfigurationFromLaunchInput,
7
8
  modelConfigurationFromProcess,
8
9
  } from "./input.js";
10
+ import { profileRejections } from "./requirements.js";
9
11
  import type {
10
12
  PolicySnapshot,
11
- ProcessModelAvailabilitySnapshot,
12
13
  ProcessModelPolicyProjectionByKind,
13
14
  ProcessModelPolicyProjectionKind,
14
15
  ProcessModelPolicyProjectionSubject,
15
16
  ProcessModelPolicyProjectionSubjectFor,
16
17
  ProjectedModelDefault,
17
- ProjectedModelProfile,
18
- ProjectedModelResolutionSource,
19
18
  ValidModelConfiguration,
20
19
  } from "./types.js";
21
20
 
22
- function projectProfiles(
23
- snapshot: PolicySnapshot,
24
- processId: string,
25
- availability?: ProcessModelAvailabilitySnapshot,
26
- ): readonly ProjectedModelProfile[] {
27
- const process = snapshot.processesById.get(processId);
28
- return snapshot.profiles
29
- .filter((profile) => !process?.allowedProfileIds || process.allowedProfileIds.has(profile.id))
30
- .map((profile) => {
31
- const status = availability?.profiles.find((candidate) => candidate.profileId === profile.id);
32
- return {
33
- id: profile.id,
34
- providerId: profile.provider,
35
- modelId: profile.modelId,
36
- thinkingLevel: profile.thinkingLevel,
37
- availability: status?.availability ?? "stale",
38
- safeReason: status?.safeReason ?? null,
39
- checkedAt: status?.checkedAt ?? null,
40
- };
41
- });
42
- }
43
-
44
- function sourceForPreview(source: ProjectedModelResolutionSource): ProjectedModelResolutionSource {
45
- return source === "action_override" ? "instance_turn_config" : source;
46
- }
47
-
48
21
  function defaultProjection(
49
22
  snapshot: PolicySnapshot,
50
23
  configuration: ValidModelConfiguration,
@@ -76,29 +49,76 @@ export function projectPolicy(
76
49
  ): ProcessModelPolicyProjectionByKind[ProcessModelPolicyProjectionKind] {
77
50
  const processId =
78
51
  request.kind === "process_configuration" ? request.process.processId : request.processId;
79
- const profiles = projectProfiles(
80
- snapshot,
81
- processId,
82
- "availability" in request ? request.availability : undefined,
83
- );
84
-
85
- if (request.kind === "profile_options") return profiles;
86
-
52
+ const policy = snapshot.processesById.get(processId);
53
+ const targetTurnId =
54
+ "target" in request && request.target.kind === "turn" ? request.target.turnId : undefined;
87
55
  if (request.kind === "compatible_profiles") {
88
- const allowedProfileIds = new Set(profiles.map((profile) => profile.id));
89
56
  return snapshot.profiles
90
57
  .filter(
91
58
  (profile) =>
92
59
  profile.provider === request.providerId &&
93
60
  profile.modelId === request.modelId &&
94
- allowedProfileIds.has(profile.id),
61
+ (!policy || !profileRejections(policy, profile, targetTurnId).length),
95
62
  )
96
63
  .map((profile) => profile.id);
97
64
  }
65
+ const catalog = [...snapshot.profiles]
66
+ .sort(
67
+ (a, b) =>
68
+ modelCostRank(a.labels) - modelCostRank(b.labels) || compareModelProfileIds(a.id, b.id),
69
+ )
70
+ .map((profile) => {
71
+ const status = request.availability?.profiles.find(
72
+ (candidate) => candidate.profileId === profile.id,
73
+ );
74
+ return {
75
+ source: profile,
76
+ id: profile.id,
77
+ providerId: profile.provider,
78
+ modelId: profile.modelId,
79
+ thinkingLevel: profile.thinkingLevel,
80
+ labels: profile.labels,
81
+ default: profile.default,
82
+ availability: status?.availability ?? ("stale" as const),
83
+ safeReason: status?.safeReason ?? null,
84
+ checkedAt: status?.checkedAt ?? null,
85
+ };
86
+ });
87
+ const projectProfiles = (turnId?: string) => {
88
+ const projected = catalog.map(({ source, ...option }) => {
89
+ const rejections = policy ? profileRejections(policy, source, turnId) : [];
90
+ return {
91
+ ...option,
92
+ policyReason:
93
+ rejections.map((r) => `${r.code} (${r.values.join(", ")}) from ${r.origin}`).join("; ") ||
94
+ undefined,
95
+ };
96
+ });
97
+ return {
98
+ profiles: projected.filter((profile) => !profile.policyReason),
99
+ excludedProfiles: projected.filter((profile) => profile.policyReason),
100
+ };
101
+ };
102
+ const processProfiles = projectProfiles(targetTurnId);
103
+ const { profiles } = processProfiles;
98
104
 
99
- const policy = snapshot.processesById.get(processId);
105
+ if (request.kind === "profile_options") return profiles;
106
+
107
+ const profileMaps = () => {
108
+ const turns = [...(policy?.llmTurnIds ?? [])].map(
109
+ (turnId) => [turnId, projectProfiles(turnId)] as const,
110
+ );
111
+ return {
112
+ profilesByTurn: Object.fromEntries(turns.map(([id, value]) => [id, value.profiles])),
113
+ excludedProfiles: Object.fromEntries([
114
+ ["", processProfiles.excludedProfiles],
115
+ ...turns.map(([id, value]) => [id, value.excludedProfiles]),
116
+ ]),
117
+ };
118
+ };
100
119
  if (request.kind === "launcher_schema") {
101
120
  return {
121
+ ...profileMaps(),
102
122
  profiles,
103
123
  turns: [...(policy?.llmTurnIds ?? [])].map((turnId) => ({
104
124
  turnId,
@@ -134,13 +154,17 @@ export function projectPolicy(
134
154
  snapshot,
135
155
  configuration,
136
156
  turnId,
137
- "resolve",
157
+ false,
138
158
  { kind: "none" },
139
159
  { kind: "inherit" },
140
160
  request.availability,
141
161
  );
142
162
  return {
143
163
  turnId,
164
+ explanation: resolved.skippedPreferences?.length
165
+ ? `Automatic — skipped ${resolved.skippedPreferences.map((preference) => `${preference.profileId}: ${preference.rejections.map((r) => `${r.code} (${r.values.join(", ")}) from ${r.origin}`).join("; ")}`).join("; ")}`
166
+ : undefined,
167
+ ranking: resolved.ranking,
144
168
  effectiveModelProfileId: resolved.selection?.modelProfileId ?? null,
145
169
  effectiveSource: resolved.selection?.provenance.source ?? ("none" as const),
146
170
  ...(!resolved.ok ? { effectiveError: presentProcessModelPolicyFailure(resolved) } : {}),
@@ -162,7 +186,9 @@ export function projectPolicy(
162
186
  });
163
187
 
164
188
  if (request.kind === "launcher_preview") {
165
- const profilesById = new Map(profiles.map((profile) => [profile.id, profile]));
189
+ const profilesById = new Map(
190
+ catalog.map(({ source: _source, ...profile }) => [profile.id, profile]),
191
+ );
166
192
  return {
167
193
  defaultModel: {
168
194
  source: defaultModel.source,
@@ -172,7 +198,9 @@ export function projectPolicy(
172
198
  turnId: turn.turnId,
173
199
  description: turn.description,
174
200
  effective: {
175
- source: sourceForPreview(turn.effectiveSource),
201
+ explanation: turn.explanation,
202
+ ranking: turn.ranking,
203
+ source: turn.effectiveSource,
176
204
  ...(turn.effectiveError ? { error: turn.effectiveError } : {}),
177
205
  profile: profilesById.get(turn.effectiveModelProfileId ?? "") ?? null,
178
206
  },
@@ -183,6 +211,7 @@ export function projectPolicy(
183
211
  const selectedTurn = existingTurnSelectionFromProcess(request.process);
184
212
  return {
185
213
  state: { kind: "ready" },
214
+ ...profileMaps(),
186
215
  profiles,
187
216
  defaultModel,
188
217
  turns,
@@ -0,0 +1,73 @@
1
+ import { compareModelProfileIds, modelCostRank } from "@leitwerk-dev/protocol";
2
+ import type { PolicyProcess, PolicyProfile } from "./types.js";
3
+
4
+ /** @internal */
5
+ export function requirementLayers(policy: PolicyProcess, turnId?: string) {
6
+ return policy.requirements.concat(turnId ? (policy.turnRequirements[turnId] ?? []) : []);
7
+ }
8
+
9
+ /** Stable policy evidence; availability never participates. @internal */
10
+ export function profileRejections(policy: PolicyProcess, profile: PolicyProfile, turnId?: string) {
11
+ const rejections: { origin: string; code: string; values: readonly string[] }[] = [];
12
+ if (policy.allowedProfileIds && !policy.allowedProfileIds.has(profile.id))
13
+ rejections.push({
14
+ origin: `process_configs.${policy.id}.allowed_model_profiles`,
15
+ code: "profile_not_allowed",
16
+ values: [profile.id],
17
+ });
18
+ const labels = new Set(profile.labels);
19
+ for (const { origin, requirements: r } of requirementLayers(policy, turnId)) {
20
+ if (r.profiles && !r.profiles.includes(profile.id))
21
+ rejections.push({ origin, code: "profile_not_allowed", values: r.profiles });
22
+ const missing = r.labels?.all_of?.filter((label) => !labels.has(label)) ?? [];
23
+ if (missing.length) rejections.push({ origin, code: "missing_labels", values: missing });
24
+ if (r.labels?.any_of && !r.labels.any_of.some((label) => labels.has(label)))
25
+ rejections.push({ origin, code: "no_matching_labels", values: r.labels.any_of });
26
+ const forbidden = r.labels?.none_of?.filter((label) => labels.has(label)) ?? [];
27
+ if (forbidden.length) rejections.push({ origin, code: "forbidden_labels", values: forbidden });
28
+ for (const capability of r.capabilities ?? []) {
29
+ if (profile.capabilities[capability] !== true)
30
+ rejections.push({
31
+ origin,
32
+ code:
33
+ profile.capabilities[capability] === false
34
+ ? "unsupported_capability"
35
+ : "unknown_capability",
36
+ values: [capability],
37
+ });
38
+ }
39
+ }
40
+ return rejections;
41
+ }
42
+
43
+ /** @internal */
44
+ export function rankedProfiles(
45
+ policy: PolicyProcess,
46
+ profiles: readonly PolicyProfile[],
47
+ turnId?: string,
48
+ ) {
49
+ const eligible = profiles.filter((profile) => !profileRejections(policy, profile, turnId).length);
50
+ const marked = eligible.filter((profile) => profile.default);
51
+ const relevant = new Set(
52
+ requirementLayers(policy, turnId).flatMap(({ requirements: r }) => [
53
+ ...(r.labels?.all_of ?? []),
54
+ ...(r.labels?.any_of ?? []),
55
+ ]),
56
+ );
57
+ const unrelated = (profile: PolicyProfile) =>
58
+ new Set(profile.labels.filter((label) => !relevant.has(label))).size;
59
+ const ranked = (marked.length ? marked : eligible).sort(
60
+ (a, b) =>
61
+ (marked.length ? unrelated(a) - unrelated(b) : 0) ||
62
+ modelCostRank(a.labels) - modelCostRank(b.labels) ||
63
+ compareModelProfileIds(a.id, b.id),
64
+ );
65
+ const minUnrelated = Math.min(...marked.map(unrelated));
66
+ return {
67
+ tiedProfileIds: marked
68
+ .filter((profile) => unrelated(profile) === minUnrelated)
69
+ .map((profile) => profile.id),
70
+ marked: marked.length > 0,
71
+ profiles: ranked,
72
+ };
73
+ }