@seaveyon/harness-switch 0.33.1 → 0.34.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.
@@ -10382,6 +10382,41 @@ var en_default = {
10382
10382
  none: "Clear",
10383
10383
  invert: "Invert"
10384
10384
  }
10385
+ },
10386
+ overwrite: {
10387
+ title: "Overwrite linked configurations",
10388
+ intro: "The configurations below reference channels this save removes. Confirming switches them to the selected replacement and keeps them linked to this template; the shown diffs are exactly what will be written.",
10389
+ computing: "Computing differences…",
10390
+ affectedTitle: "Affected configurations",
10391
+ affectedCount: "{{count}} affected references",
10392
+ draftItem: "Tool model draft",
10393
+ configColumn: "Configuration",
10394
+ stateColumn: "State",
10395
+ replacementColumn: "Replacement",
10396
+ inUse: "in use",
10397
+ idle: "not active",
10398
+ autoMapped: "auto-mapped (same account and model)",
10399
+ uniqueCandidate: "only compatible option, preselected",
10400
+ pickPrompt: "Choose a replacement",
10401
+ noCandidate: "No compatible channel",
10402
+ chooseCandidate: "Choose a replacement",
10403
+ replacementRequired: "Choose a compatible replacement for these references.",
10404
+ collectionCollision: "These tool models resolve to the same destination. Choose different channels or models.",
10405
+ noCandidateHint: "{{profile}} has no compatible replacement. Go back to the draft and pick a channel for it.",
10406
+ templateDiff: "Template changes",
10407
+ confirm: "Confirm overwrite",
10408
+ stale: "The preview is stale or the state has changed. Refresh and try again.",
10409
+ refresh: "Refresh preview",
10410
+ collectionHint: "Tool model channel references are saved with the template. To update the tool’s models and startup settings, continue to the tool model preview and apply the changes.",
10411
+ reviewCollection: "Preview {{tool}} model updates",
10412
+ reviewCollectionHint: "Review the saved tool model list, model overrides, and startup selection.",
10413
+ blockedTitle: "There are unresolved blockers. Nothing will be written.",
10414
+ retry: "Retry this item",
10415
+ resumeTitle: "Continue updating affected configurations",
10416
+ resumeIntro: "The configurations below are not on the current template yet. Review the diffs, then apply them one by one.",
10417
+ resumeButton: "Continue ({{count}})",
10418
+ resumeEmpty: "Nothing left to update.",
10419
+ backToDraft: "Back to draft"
10385
10420
  }
10386
10421
  },
10387
10422
  favorite: {
@@ -12041,6 +12076,41 @@ var zh_CN_default = {
12041
12076
  none: "清空",
12042
12077
  invert: "反选"
12043
12078
  }
12079
+ },
12080
+ overwrite: {
12081
+ title: "覆盖引用的配置",
12082
+ intro: "核对渠道替换和配置差异,确认后保留这些引用与模板的关联。",
12083
+ computing: "正在计算差异…",
12084
+ affectedTitle: "受影响的配置",
12085
+ affectedCount: "{{count}} 个受影响的引用",
12086
+ draftItem: "工具模型草稿",
12087
+ configColumn: "配置",
12088
+ stateColumn: "状态",
12089
+ replacementColumn: "替换为",
12090
+ inUse: "正在使用",
12091
+ idle: "未使用",
12092
+ autoMapped: "已自动映射(同账号同模型)",
12093
+ uniqueCandidate: "唯一兼容渠道,已预选",
12094
+ pickPrompt: "选择替代渠道",
12095
+ noCandidate: "无兼容渠道",
12096
+ chooseCandidate: "待选择渠道",
12097
+ replacementRequired: "请为以下引用选择兼容的替代渠道。",
12098
+ collectionCollision: "以下工具模型的替换目标重复,请选择不同渠道或模型。",
12099
+ noCandidateHint: "{{profile}} 没有兼容替代,请回到草稿为它补选渠道。",
12100
+ templateDiff: "模板变更",
12101
+ confirm: "确认覆盖",
12102
+ stale: "预览已过期或状态已变化,请刷新后重试。",
12103
+ refresh: "刷新预览",
12104
+ collectionHint: "工具模型的渠道引用随模板保存。要更新工具中的模型和启动设置,请继续预览并应用工具模型。",
12105
+ reviewCollection: "预览 {{tool}} 工具模型更新",
12106
+ reviewCollectionHint: "将预览已保存的工具模型列表、模型覆盖项及启动选择。",
12107
+ blockedTitle: "存在无法解决的阻塞项,覆盖不会写入任何内容。",
12108
+ retry: "重试该项",
12109
+ resumeTitle: "继续更新受影响的配置",
12110
+ resumeIntro: "以下配置尚未更新到当前模板。请先核对差异,再逐项应用。",
12111
+ resumeButton: "继续更新({{count}})",
12112
+ resumeEmpty: "没有待更新的配置。",
12113
+ backToDraft: "回到草稿"
12044
12114
  }
12045
12115
  },
12046
12116
  favorite: {
@@ -26761,6 +26831,26 @@ var modelFavoriteSchema = favoriteFields.extend({
26761
26831
  updatedAt: exports_external.iso.datetime()
26762
26832
  }).superRefine(validateFavorite);
26763
26833
  var favoriteStoreSchema = exports_external.object({ schemaVersion: exports_external.literal(1), favorites: exports_external.array(modelFavoriteSchema).max(1000) }).refine((value) => new Set(value.favorites.map((favorite) => favorite.id)).size === value.favorites.length);
26834
+ var overwriteRemapFields = exports_external.object({
26835
+ harness: exports_external.enum(HARNESS_IDS),
26836
+ fromConnectionId: exports_external.uuid(),
26837
+ resolution: exports_external.enum(["auto", "chosen"]),
26838
+ connectionId: exports_external.uuid(),
26839
+ overwriteDiverged: exports_external.boolean().default(false),
26840
+ ignorePreference: exports_external.boolean().default(false),
26841
+ allowAuthOverwrite: exports_external.boolean().optional()
26842
+ });
26843
+ var overwriteReferenceFields = [
26844
+ { profile: exports_external.string().trim().min(1).max(120), itemId: exports_external.never().optional() },
26845
+ { itemId: exports_external.uuid(), profile: exports_external.never().optional() }
26846
+ ];
26847
+ var overwriteRemapSchema = exports_external.union([
26848
+ overwriteRemapFields.extend(overwriteReferenceFields[0]),
26849
+ overwriteRemapFields.extend(overwriteReferenceFields[1])
26850
+ ]);
26851
+ function overwriteReferenceKey(ref) {
26852
+ return ref.profile === undefined ? `${ref.harness}/item/${ref.itemId}` : `${ref.harness}/profile/${ref.profile}`;
26853
+ }
26764
26854
  var updateFavoriteRequestSchema = exports_external.object({
26765
26855
  name: favoriteFields.shape.name.optional(),
26766
26856
  notes: exports_external.string().max(4096).optional(),
@@ -26769,11 +26859,18 @@ var updateFavoriteRequestSchema = exports_external.object({
26769
26859
  connections: exports_external.array(favoriteConnectionSchema).max(50).optional(),
26770
26860
  defaultConnectionId: favoriteFields.shape.defaultConnectionId,
26771
26861
  toolBindings: favoriteFields.shape.toolBindings,
26772
- expectedRevision: exports_external.number().int().positive().optional()
26862
+ expectedRevision: exports_external.number().int().positive().optional(),
26863
+ connectionRemaps: exports_external.array(overwriteRemapSchema).max(200).optional(),
26864
+ overwriteApprovalId: exports_external.uuid().optional()
26773
26865
  });
26774
26866
  var favoriteRevisionRequestSchema = exports_external.object({
26775
26867
  expectedRevision: exports_external.number().int().positive().optional()
26776
26868
  });
26869
+ var overwritePreviewRequestSchema = exports_external.object({
26870
+ expectedRevision: exports_external.number().int().positive(),
26871
+ draft: createFavoriteRequestSchema,
26872
+ remaps: exports_external.array(overwriteRemapSchema).max(200).default([])
26873
+ });
26777
26874
  var ownedExtraSchema = exports_external.enum([
26778
26875
  "api",
26779
26876
  "providerType",
@@ -33037,6 +33134,9 @@ class VaultService {
33037
33134
  }
33038
33135
  return plain;
33039
33136
  }
33137
+ credentialsForRedaction() {
33138
+ return Object.values(this.read().entries).map((entry) => this.crypto.decrypt(entry.api_key)).filter(Boolean);
33139
+ }
33040
33140
  references(id) {
33041
33141
  const store = this.readProfileStore();
33042
33142
  const found = [];
@@ -33177,6 +33277,12 @@ class ProfileService {
33177
33277
  if (this.repairEndpointReferences(store, harness)) {
33178
33278
  this.files.writeJson(this.environment.files.profiles, store);
33179
33279
  }
33280
+ return this.project(harness, store);
33281
+ }
33282
+ peek(harness) {
33283
+ return this.project(harness, this.read());
33284
+ }
33285
+ project(harness, store) {
33180
33286
  return Object.entries(store[harness] ?? {}).map(([name, profile]) => this.toPublic(harness, name, profile));
33181
33287
  }
33182
33288
  fingerprint(harness, name) {
@@ -36443,10 +36549,139 @@ __decoratorMetadata(_init, HarnessService);
36443
36549
  let _HarnessService = HarnessService;
36444
36550
 
36445
36551
  // src/services/model-favorite.ts
36446
- import { createHmac, randomUUID as randomUUID5 } from "node:crypto";
36552
+ import { createHmac, randomUUID as randomUUID6 } from "node:crypto";
36447
36553
 
36448
- // src/services/tool-models.ts
36449
- import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
36554
+ // src/services/model-favorite-apply.ts
36555
+ import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
36556
+
36557
+ // src/services/model-favorite-overwrite.ts
36558
+ function resolveOverwriteRemaps({
36559
+ current,
36560
+ draft,
36561
+ refs,
36562
+ remaps
36563
+ }) {
36564
+ const problems = [];
36565
+ const affected = [];
36566
+ const resolvedRemaps = [];
36567
+ const absorbed = new Map;
36568
+ const unused = new Map(remaps.map((remap) => [overwriteReferenceKey(remap), remap]));
36569
+ if (unused.size !== remaps.length) {
36570
+ problems.push({ code: ERROR_CODES.favoritePlanStale });
36571
+ }
36572
+ for (const ref of refs) {
36573
+ const retained = draft.connections.find((connection) => connection.id === ref.connectionId);
36574
+ if (retained && pickProtocolForHarness(retained, ref.harness)) {
36575
+ continue;
36576
+ }
36577
+ const previous = current.connections.find((connection) => connection.id === ref.connectionId);
36578
+ const old = {
36579
+ providerId: previous?.providerId ?? ref.link?.baseline.providerId ?? "",
36580
+ endpointKey: previous?.endpointKey ?? ref.link?.baseline.providerEndpoint ?? "",
36581
+ requestModelId: previous?.requestModelId ?? ref.link?.baseline.model ?? ""
36582
+ };
36583
+ const key = overwriteReferenceKey(ref);
36584
+ const explicit = unused.get(key);
36585
+ unused.delete(key);
36586
+ if (explicit && explicit.fromConnectionId !== ref.connectionId) {
36587
+ problems.push({ code: ERROR_CODES.favoritePlanStale });
36588
+ continue;
36589
+ }
36590
+ const sameAccount = draft.connections.filter((connection) => connection.id !== ref.connectionId && connection.providerId === old.providerId && connection.endpointKey === old.endpointKey && connection.requestModelId === old.requestModelId);
36591
+ let target;
36592
+ let resolution = "none";
36593
+ if (explicit) {
36594
+ target = draft.connections.find((connection) => connection.id === explicit.connectionId);
36595
+ if (!target) {
36596
+ problems.push({ code: ERROR_CODES.favoriteEndpointMissing });
36597
+ continue;
36598
+ }
36599
+ const isEquivalent = sameAccount.length === 1 && sameAccount[0].id === target.id;
36600
+ resolution = isEquivalent ? "auto" : "chosen";
36601
+ if (isEquivalent) {
36602
+ target = absorb(target, previous, ref.harness, absorbed);
36603
+ }
36604
+ if (!pickProtocolForHarness(target, ref.harness)) {
36605
+ problems.push({ code: ERROR_CODES.favoriteProtocolUnsupported });
36606
+ continue;
36607
+ }
36608
+ } else if (sameAccount.length === 1) {
36609
+ target = absorb(sameAccount[0], previous, ref.harness, absorbed);
36610
+ if (!target || !pickProtocolForHarness(target, ref.harness)) {
36611
+ problems.push({ code: ERROR_CODES.favoriteProtocolUnsupported });
36612
+ continue;
36613
+ }
36614
+ resolution = "auto";
36615
+ }
36616
+ const identity2 = ref.profile === undefined ? { itemId: ref.itemId } : { profile: ref.profile };
36617
+ affected.push({
36618
+ harness: ref.harness,
36619
+ ...identity2,
36620
+ inUse: false,
36621
+ collectionManaged: ref.itemId !== undefined || ref.link?.collectionOverrides !== undefined,
36622
+ from: {
36623
+ connectionId: ref.connectionId,
36624
+ providerId: old.providerId,
36625
+ endpointKey: old.endpointKey,
36626
+ requestModelId: old.requestModelId
36627
+ },
36628
+ resolution,
36629
+ ...target ? { connectionId: target.id } : {}
36630
+ });
36631
+ if (!target || resolution === "none") {
36632
+ continue;
36633
+ }
36634
+ resolvedRemaps.push({
36635
+ harness: ref.harness,
36636
+ ...identity2,
36637
+ fromConnectionId: ref.connectionId,
36638
+ resolution,
36639
+ connectionId: target.id,
36640
+ overwriteDiverged: explicit?.overwriteDiverged ?? false,
36641
+ ignorePreference: explicit?.ignorePreference ?? false,
36642
+ allowAuthOverwrite: explicit?.allowAuthOverwrite
36643
+ });
36644
+ }
36645
+ const referenced = new Set(refs.map((ref) => ref.connectionId));
36646
+ for (const previous of current.connections) {
36647
+ if (referenced.has(previous.id) || draft.connections.some((connection) => connection.id === previous.id)) {
36648
+ continue;
36649
+ }
36650
+ const survivors = draft.connections.filter((connection) => connection.providerId === previous.providerId && connection.endpointKey === previous.endpointKey && connection.requestModelId === previous.requestModelId);
36651
+ if (survivors.length === 1) {
36652
+ absorb(survivors[0], previous, undefined, absorbed);
36653
+ }
36654
+ }
36655
+ if (unused.size) {
36656
+ problems.push({ code: ERROR_CODES.favoritePlanStale });
36657
+ }
36658
+ return {
36659
+ resolved: {
36660
+ ...draft,
36661
+ connections: draft.connections.map((connection) => absorbed.get(connection.id) ?? connection)
36662
+ },
36663
+ affected,
36664
+ remaps: resolvedRemaps,
36665
+ problems
36666
+ };
36667
+ }
36668
+ function absorb(candidate, previous, harness, absorbed) {
36669
+ if (!previous) {
36670
+ return candidate;
36671
+ }
36672
+ const base = absorbed.get(candidate.id) ?? candidate;
36673
+ const missingHarnessProtocol = !harness || pickProtocolForHarness(base, harness) ? [] : [FAVORITE_PROTOCOL_SUPPORT[harness][0]];
36674
+ const merged = {
36675
+ ...base,
36676
+ ...syncConnectionProtocols([
36677
+ ...connectionProtocols(base),
36678
+ ...connectionProtocols(previous),
36679
+ ...missingHarnessProtocol
36680
+ ])
36681
+ };
36682
+ absorbed.set(merged.id, merged);
36683
+ return merged;
36684
+ }
36450
36685
 
36451
36686
  // src/services/model-favorite-preview.ts
36452
36687
  var nativeValueSchema = exports_external.json();
@@ -36493,6 +36728,7 @@ function redact(value, credentials, secret = false) {
36493
36728
  }
36494
36729
 
36495
36730
  // src/services/tool-models.ts
36731
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
36496
36732
  var stateSchema = exports_external.object({
36497
36733
  revision: exports_external.number().int().nonnegative(),
36498
36734
  draft: toolModelDraftSchema,
@@ -36641,10 +36877,79 @@ class ToolModelsService {
36641
36877
  });
36642
36878
  return preview;
36643
36879
  }
36644
- remapFavoriteConnections(favoriteId, remaps) {
36645
- if (!remaps.size) {
36880
+ favoriteDraftItems(favoriteId) {
36881
+ const store = this.read();
36882
+ return toolModelsHarnessSchema.options.flatMap((harness) => {
36883
+ const state = store.collections[harness];
36884
+ return (state?.draft.items ?? []).filter((item) => item.source.kind === "favorite" && item.source.favoriteId === favoriteId).map((item) => ({
36885
+ harness,
36886
+ itemId: item.id,
36887
+ connectionId: item.source.kind === "favorite" ? item.source.connectionId : "",
36888
+ profile: state?.applied.find((entry) => entry.id === item.id)?.profile
36889
+ }));
36890
+ });
36891
+ }
36892
+ checkFavoriteRemaps(favoriteId, resolved, entries) {
36893
+ const problems = [];
36894
+ const store = this.read();
36895
+ const favorites = new Map(this.favorites.list().map((favorite) => [favorite.id, favorite]));
36896
+ const remaps = new Map(entries.map((entry) => [`${entry.harness}/${entry.itemId}`, entry.connectionId]));
36897
+ for (const harness of toolModelsHarnessSchema.options) {
36898
+ const state = store.collections[harness];
36899
+ const seen = new Map;
36900
+ for (const item of state?.draft.items ?? []) {
36901
+ if (item.source.kind !== "favorite") {
36902
+ continue;
36903
+ }
36904
+ const source = item.source;
36905
+ const affected = source.favoriteId === favoriteId;
36906
+ const before = favorites.get(source.favoriteId)?.connections.find((entry) => entry.id === source.connectionId);
36907
+ const connectionId = remaps.get(`${harness}/${item.id}`) ?? source.connectionId;
36908
+ const connection = affected ? resolved.connections.find((entry) => entry.id === connectionId) : before;
36909
+ const protocol = connection && pickProtocolForHarness(connection, harness);
36910
+ const subject = {
36911
+ harness,
36912
+ profile: state?.applied.find((entry) => entry.id === item.id)?.profile,
36913
+ model: before ? `${before.label} · ${before.requestModelId}` : source.connectionId
36914
+ };
36915
+ if (!connection || !protocol) {
36916
+ if (affected) {
36917
+ problems.push({
36918
+ ...subject,
36919
+ code: connection ? ERROR_CODES.favoriteProtocolUnsupported : ERROR_CODES.favoriteEndpointMissing
36920
+ });
36921
+ }
36922
+ continue;
36923
+ }
36924
+ const identity2 = `${collectionRoute(connection, protocol)}/${connection.requestModelId}`;
36925
+ const other = seen.get(identity2);
36926
+ if (other && (affected || other.affected)) {
36927
+ problems.push({
36928
+ ...subject,
36929
+ code: ERROR_CODES.toolModelsConflict,
36930
+ otherModel: other.profile ?? other.model
36931
+ });
36932
+ }
36933
+ seen.set(identity2, { ...subject, affected });
36934
+ if (affected) {
36935
+ try {
36936
+ this.projectModel(harness, resolved, connection, item);
36937
+ } catch (error52) {
36938
+ if (!(error52 instanceof HttpError)) {
36939
+ throw error52;
36940
+ }
36941
+ problems.push({ ...subject, code: error52.code });
36942
+ }
36943
+ }
36944
+ }
36945
+ }
36946
+ return problems;
36947
+ }
36948
+ remapFavoriteConnectionsScoped(favoriteId, entries) {
36949
+ if (!entries.length) {
36646
36950
  return;
36647
36951
  }
36952
+ const scoped = new Map(entries.map((entry) => [`${entry.harness}/${entry.itemId}`, entry.connectionId]));
36648
36953
  const store = this.read();
36649
36954
  let changed = false;
36650
36955
  for (const harness of toolModelsHarnessSchema.options) {
@@ -36657,7 +36962,7 @@ class ToolModelsService {
36657
36962
  if (item.source.kind !== "favorite" || item.source.favoriteId !== favoriteId) {
36658
36963
  return item;
36659
36964
  }
36660
- const nextId = remaps.get(item.source.connectionId);
36965
+ const nextId = scoped.get(`${harness}/${item.id}`);
36661
36966
  if (!nextId || nextId === item.source.connectionId) {
36662
36967
  return item;
36663
36968
  }
@@ -36768,29 +37073,13 @@ class ToolModelsService {
36768
37073
  if (!protocol) {
36769
37074
  throw failure2(ERROR_CODES.favoriteProtocolUnsupported);
36770
37075
  }
36771
- const route = `${provider.id}/${endpoint.key}/${protocol}`;
37076
+ const route = collectionRoute(connection, protocol);
36772
37077
  const identity2 = `${route}/${connection.requestModelId}`;
36773
37078
  if (seen.has(identity2)) {
36774
37079
  throw failure2(ERROR_CODES.toolModelsConflict);
36775
37080
  }
36776
37081
  seen.add(identity2);
36777
- const effective = {
36778
- ...connection,
36779
- factOverrides: { ...connection.factOverrides, ...item.factOverrides },
36780
- preferenceOverrides: { ...connection.preferenceOverrides, ...item.preferenceOverrides }
36781
- };
36782
- if (!createFavoriteRequestSchema.safeParse({
36783
- ...favorite,
36784
- connections: favorite.connections.map((entry) => entry.id === effective.id ? effective : entry)
36785
- }).success) {
36786
- throw new HttpError(400, ERROR_CODES.toolModelsFactsInvalid, {
36787
- code: ERROR_CODES.toolModelsFactsInvalid
36788
- });
36789
- }
36790
- const projection = adapter.projectFavorite(favorite, effective);
36791
- if (projection.blockers.length) {
36792
- throw failure2(projection.blockers[0].code);
36793
- }
37082
+ const projection = this.projectModel(harness, favorite, connection, item);
36794
37083
  const baseName = `${favorite.name} · ${connection.label}`.replace(/[\\/]/g, "-").slice(0, 120);
36795
37084
  const existingName = state.applied.find((entry) => entry.id === item.id)?.profile;
36796
37085
  const name = existingName ?? (this.profiles.get(harness, baseName) || names.has(baseName) ? `${baseName.slice(0, 110)}-${item.id.slice(0, 8)}` : baseName);
@@ -36853,6 +37142,26 @@ class ToolModelsService {
36853
37142
  };
36854
37143
  });
36855
37144
  }
37145
+ projectModel(harness, favorite, connection, item) {
37146
+ const effective = {
37147
+ ...connection,
37148
+ factOverrides: { ...connection.factOverrides, ...item.factOverrides },
37149
+ preferenceOverrides: { ...connection.preferenceOverrides, ...item.preferenceOverrides }
37150
+ };
37151
+ if (!createFavoriteRequestSchema.safeParse({
37152
+ ...favorite,
37153
+ connections: favorite.connections.map((entry) => entry.id === effective.id ? effective : entry)
37154
+ }).success) {
37155
+ throw new HttpError(400, ERROR_CODES.toolModelsFactsInvalid, {
37156
+ code: ERROR_CODES.toolModelsFactsInvalid
37157
+ });
37158
+ }
37159
+ const projection = this.adapters.get(harness).projectFavorite(favorite, effective);
37160
+ if (projection.blockers.length) {
37161
+ throw failure2(projection.blockers[0].code);
37162
+ }
37163
+ return projection;
37164
+ }
36856
37165
  compare(harness, revision) {
36857
37166
  const state = this.get(harness);
36858
37167
  if (state.revision !== revision) {
@@ -36911,6 +37220,9 @@ ToolModelsService = __decorateElement(_init, 0, "ToolModelsService", _dec, ToolM
36911
37220
  __runInitializers(_init, 1, ToolModelsService);
36912
37221
  __decoratorMetadata(_init, ToolModelsService);
36913
37222
  let _ToolModelsService = ToolModelsService;
37223
+ function collectionRoute(connection, protocol) {
37224
+ return `${connection.providerId}/${connection.endpointKey}/${protocol}`;
37225
+ }
36914
37226
  function hash2(value) {
36915
37227
  return createHash8("sha256").update(JSON.stringify(value)).digest("hex");
36916
37228
  }
@@ -36922,555 +37234,398 @@ function failure2(code) {
36922
37234
  return new HttpError(409, code, { code });
36923
37235
  }
36924
37236
 
36925
- // src/services/model-favorite.ts
36926
- var IModelFavoriteService = createDecorator("modelFavoriteService");
37237
+ // src/services/model-favorite-apply.ts
37238
+ var IModelFavoriteApplyService = createDecorator("modelFavoriteApplyService");
36927
37239
  var _dec = [
36928
- inject(IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, ILiveWriteService, IFavoriteBackupService, IToolModelsService)
37240
+ inject(IEnvironmentService, IFileService, IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, IActivationService, ILiveWriteService, IJournalService, IDriftService, IFavoriteBackupService, IToolModelsService)
36929
37241
  ];
36930
37242
  var _init = __decoratorStart(undefined);
36931
37243
 
36932
- class ModelFavoriteService {
36933
- store;
37244
+ class ModelFavoriteApplyService {
37245
+ environment;
37246
+ files;
37247
+ favorites;
36934
37248
  profiles;
36935
37249
  vault;
36936
37250
  adapters;
37251
+ activation;
36937
37252
  liveWrite;
37253
+ journal;
37254
+ drift;
36938
37255
  backups;
36939
37256
  toolModels;
36940
- sourceSalt = randomUUID5();
36941
- constructor(store, profiles, vault, adapters, liveWrite, backups, toolModels) {
36942
- this.store = store;
37257
+ plans = new Map;
37258
+ overwrites = new Map;
37259
+ constructor(environment, files, favorites, profiles, vault, adapters, activation, liveWrite, journal, drift, backups, toolModels) {
37260
+ this.environment = environment;
37261
+ this.files = files;
37262
+ this.favorites = favorites;
36943
37263
  this.profiles = profiles;
36944
37264
  this.vault = vault;
36945
37265
  this.adapters = adapters;
37266
+ this.activation = activation;
36946
37267
  this.liveWrite = liveWrite;
37268
+ this.journal = journal;
37269
+ this.drift = drift;
36947
37270
  this.backups = backups;
36948
37271
  this.toolModels = toolModels;
36949
37272
  }
36950
- list() {
36951
- return this.store.list().map((favorite) => ({ ...favorite, references: this.references(favorite.id) }));
36952
- }
36953
- references(id) {
36954
- return HARNESS_IDS.flatMap((harness) => this.profiles.list(harness).flatMap((profile) => profile.modelFavorite?.favoriteId === id ? [{ harness, name: profile.name, link: profile.modelFavorite }] : []));
36955
- }
36956
- create(input) {
36957
- const parsed = createFavoriteRequestSchema.parse(input);
36958
- this.validateConnections(parsed);
36959
- return this.backups.protect("change", () => this.store.create(parsed), {
36960
- action: "create",
36961
- name: parsed.name
36962
- });
36963
- }
36964
- update(id, input) {
36965
- this.store.assertRevision(id, input.expectedRevision);
36966
- const current = this.store.get(id);
36967
- let next = createFavoriteRequestSchema.parse({ ...current, ...input });
36968
- this.validateConnections(next);
36969
- const remaps = [];
36970
- const absorbed = new Map;
36971
- const absorbRemoved = (previous, harness) => {
36972
- const survivor = sameAccountModel(previous, next.connections);
36973
- if (!survivor) {
36974
- return;
37273
+ state(profile) {
37274
+ const link = profile.modelFavorite;
37275
+ const favorite = link ? this.favorites.list().find((item) => item.id === link.favoriteId) : undefined;
37276
+ const connection = favorite?.connections.find((item) => item.id === link?.connectionId);
37277
+ const projected = favorite && connection ? this.adapters.get(profile.harness).projectFavorite(favorite, {
37278
+ ...connection,
37279
+ factOverrides: {
37280
+ ...connection.factOverrides,
37281
+ ...link?.collectionOverrides?.factOverrides
37282
+ },
37283
+ preferenceOverrides: {
37284
+ ...connection.preferenceOverrides,
37285
+ ...link?.collectionOverrides?.preferenceOverrides
36975
37286
  }
36976
- const base = absorbed.get(survivor.id) ?? survivor;
36977
- const merged = {
36978
- ...base,
36979
- ...syncConnectionProtocols([
36980
- ...connectionProtocols(base),
36981
- ...connectionProtocols(previous),
36982
- ...harness && !pickProtocolForHarness(base, harness) ? [FAVORITE_PROTOCOL_SUPPORT[harness][0]] : []
36983
- ])
36984
- };
36985
- absorbed.set(merged.id, merged);
36986
- return merged;
37287
+ }, link?.baseline) : undefined;
37288
+ return {
37289
+ sourceMissing: !!link && !favorite,
37290
+ connectionMissing: !!link && !connection,
37291
+ needsUpdate: !!link && link.ignoredRevision !== favorite?.revision && !!projected && (link.projectionVersion !== projected.projectionVersion || hash3(link.baseline) !== hash3(projected.projection)),
37292
+ diverged: !!link && (profile.overriddenTargets.length > 0 || hash3(snapshot(profile, link.baseline)) !== hash3(link.baseline))
36987
37293
  };
36988
- for (const ref of this.references(id)) {
36989
- if (next.connections.some((connection) => connection.id === ref.link.connectionId)) {
36990
- continue;
37294
+ }
37295
+ plan(request, session) {
37296
+ const favorite = this.favorites.get(request.favoriteId);
37297
+ if (favorite.revision !== request.expectedRevision) {
37298
+ throw failure3(ERROR_CODES.favoriteRevisionConflict);
37299
+ }
37300
+ for (const [id, value] of this.plans) {
37301
+ if (Date.parse(value.public.expiresAt) < Date.now()) {
37302
+ this.plans.delete(id);
36991
37303
  }
36992
- const previous = current.connections.find((connection) => connection.id === ref.link.connectionId);
36993
- const target = previous ?? {
36994
- providerId: ref.link.baseline.providerId,
36995
- endpointKey: ref.link.baseline.providerEndpoint,
36996
- requestModelId: ref.link.baseline.model,
36997
- protocol: undefined,
36998
- protocols: undefined
37304
+ }
37305
+ if (this.plans.size >= 1000) {
37306
+ throw failure3(ERROR_CODES.favoriteLimitReached);
37307
+ }
37308
+ const items = request.items.toSorted((a, b) => HARNESS_IDS.indexOf(a.harness) - HARNESS_IDS.indexOf(b.harness)).map((selection) => {
37309
+ const computed = this.computeItem(favorite, selection);
37310
+ return {
37311
+ ...computed,
37312
+ writes: computed.writes,
37313
+ fingerprint: this.fingerprint(favorite.id, computed.public)
36999
37314
  };
37000
- const merged = absorbRemoved(target, ref.harness);
37001
- if (!merged || !pickProtocolForHarness(merged, ref.harness)) {
37002
- throw new HttpError(409, ERROR_CODES.favoriteConnectionInUse, {
37003
- code: ERROR_CODES.favoriteConnectionInUse
37004
- });
37005
- }
37006
- remaps.push({ ref, connectionId: merged.id });
37315
+ });
37316
+ const plan = {
37317
+ id: randomUUID5(),
37318
+ expiresAt: new Date(Date.now() + 600000).toISOString(),
37319
+ favoriteRevision: favorite.revision,
37320
+ items: items.map((item) => item.public)
37321
+ };
37322
+ this.plans.set(plan.id, {
37323
+ public: plan,
37324
+ items,
37325
+ user: this.environment.dataDir,
37326
+ session,
37327
+ favoriteId: favorite.id
37328
+ });
37329
+ return plan;
37330
+ }
37331
+ computeItem(favorite, selection) {
37332
+ const connection = favorite.connections.find((item2) => item2.id === selection.connectionId);
37333
+ if (!connection) {
37334
+ throw failure3(ERROR_CODES.favoriteEndpointMissing);
37007
37335
  }
37008
- const connectionRemaps = new Map(remaps.map(({ ref, connectionId }) => [ref.link.connectionId, connectionId]));
37009
- for (const previous of current.connections) {
37010
- if (next.connections.some((connection) => connection.id === previous.id)) {
37011
- continue;
37012
- }
37013
- if (connectionRemaps.has(previous.id)) {
37014
- continue;
37015
- }
37016
- const merged = absorbRemoved(previous);
37017
- if (merged) {
37018
- connectionRemaps.set(previous.id, merged.id);
37336
+ const provider = this.vault.get(connection.providerId);
37337
+ const endpoint = provider.endpoints.find((item2) => item2.key === connection.endpointKey);
37338
+ if (!endpoint) {
37339
+ throw failure3(ERROR_CODES.favoriteEndpointMissing);
37340
+ }
37341
+ const adapter = this.adapters.get(selection.harness);
37342
+ let name = selection.profile ?? favorite.name.replace(/[\\/]/g, "-");
37343
+ if (!selection.existing && !selection.profile) {
37344
+ let suffix = 2;
37345
+ const base = name;
37346
+ while (this.profiles.get(selection.harness, name)) {
37347
+ name = `${base.slice(0, 110)}-${suffix++}`;
37019
37348
  }
37020
37349
  }
37021
- if (absorbed.size) {
37022
- next = createFavoriteRequestSchema.parse({
37023
- ...next,
37024
- connections: next.connections.map((connection) => absorbed.get(connection.id) ?? connection)
37025
- });
37026
- this.validateConnections(next);
37027
- for (const { ref, connectionId } of remaps) {
37028
- const connection = next.connections.find((entry) => entry.id === connectionId);
37029
- if (!connection || !pickProtocolForHarness(connection, ref.harness)) {
37030
- throw new HttpError(409, ERROR_CODES.favoriteConnectionInUse, {
37031
- code: ERROR_CODES.favoriteConnectionInUse
37032
- });
37033
- }
37350
+ const prior = this.profiles.get(selection.harness, name);
37351
+ if (prior?.modelFavorite?.collectionOverrides) {
37352
+ throw failure3(ERROR_CODES.toolModelsConflict);
37353
+ }
37354
+ if (selection.existing ? prior?.modelFavorite?.favoriteId !== favorite.id : !!prior) {
37355
+ throw failure3(ERROR_CODES.favoriteInUse);
37356
+ }
37357
+ if (prior?.overriddenTargets.length) {
37358
+ throw failure3(ERROR_CODES.favoriteRawOverrideConflict);
37359
+ }
37360
+ const projection = adapter.projectFavorite(favorite, connection, prior?.modelFavorite?.baseline);
37361
+ if (prior && this.state(prior).diverged && !selection.overwriteDiverged) {
37362
+ projection.blockers.push({ code: ERROR_CODES.favoriteProfileDiverged });
37363
+ }
37364
+ if (projection.notRepresented.includes("reasoningEffort") && !selection.ignorePreference) {
37365
+ projection.blockers.push({ code: ERROR_CODES.favoritePreferenceNotRepresented });
37366
+ }
37367
+ const extras = { ...prior?.extras };
37368
+ if (!prior && ["pi", "dsh", "codex", "kimi"].includes(selection.harness)) {
37369
+ extras.providerId = `hsw-mf-${randomUUID5()}`;
37370
+ }
37371
+ for (const [key, value] of Object.entries(projection.projection.extras)) {
37372
+ if (value === null) {
37373
+ delete extras[key];
37374
+ } else {
37375
+ extras[key] = value;
37034
37376
  }
37035
37377
  }
37036
- return this.backups.protect("change", () => this.liveWrite.transaction({
37037
- kind: "favorite-apply",
37038
- harness: remaps[0]?.ref.harness ?? "claude",
37039
- profile: current.name,
37040
- writes: [],
37041
- metadata: connectionRemaps.size ? ["favorites", "profiles", "toolModels"] : ["favorites"]
37042
- }, () => {
37043
- const updated = this.store.update(id, next, input.expectedRevision);
37044
- for (const { ref, connectionId } of remaps) {
37045
- this.profiles.setFavoriteLink(ref.harness, ref.name, {
37046
- ...ref.link,
37047
- connectionId
37048
- });
37378
+ for (const key of Object.keys(projection.rendererDefaults)) {
37379
+ if (extras[key]) {
37380
+ delete projection.rendererDefaults[key];
37049
37381
  }
37050
- this.toolModels.remapFavoriteConnections(id, connectionRemaps);
37051
- return updated;
37052
- }), { action: "update", name: current.name });
37053
- }
37054
- remove(id, revision) {
37055
- this.store.assertRevision(id, revision);
37056
- if (this.references(id).length) {
37057
- throw new HttpError(409, ERROR_CODES.favoriteInUse, { code: ERROR_CODES.favoriteInUse });
37058
37382
  }
37059
- this.backups.protect("change", () => this.store.remove(id, revision), {
37060
- action: "delete",
37061
- name: this.store.get(id).name
37383
+ const profile = {
37384
+ favoriteManaged: true,
37385
+ name,
37386
+ model: connection.requestModelId,
37387
+ extras,
37388
+ baseUrl: endpoint.baseUrl,
37389
+ apiKey: this.vault.decrypt(provider.id)
37390
+ };
37391
+ adapter.validate?.(profile);
37392
+ const input = {
37393
+ name,
37394
+ model: profile.model,
37395
+ extras,
37396
+ baseUrl: profile.baseUrl,
37397
+ providerId: provider.id,
37398
+ providerEndpoint: endpoint.key
37399
+ };
37400
+ const diff = projection.ownedFields.flatMap((field) => {
37401
+ const before = field.startsWith("extras.") ? prior?.extras[field.slice(7)] ?? null : field === "model" ? prior?.model ?? null : field === "providerId" ? prior?.providerId ?? null : prior?.providerEndpoint ?? null;
37402
+ const after = projection.set[field] ?? null;
37403
+ return before === after ? [] : [{ field, before, after }];
37062
37404
  });
37063
- }
37064
- sourceFingerprint(harness, name) {
37065
- const profile = this.profiles.get(harness, name);
37066
- if (!profile) {
37067
- throw new HttpError(404, ERROR_CODES.profileNotFound, { code: ERROR_CODES.profileNotFound });
37405
+ if (selection.mode === "save" && this.activation.getActive(selection.harness)?.name === name && (diff.length || prior?.baseUrl !== endpoint.baseUrl)) {
37406
+ projection.blockers.push({ code: ERROR_CODES.favoriteActiveUpdateRequiresApply });
37068
37407
  }
37069
- return createHmac("sha256", this.sourceSalt).update(this.profiles.fingerprint(harness, name)).digest("hex");
37070
- }
37071
- capture(input) {
37072
- if (this.sourceFingerprint(input.harness, input.name) !== input.sourceFingerprint) {
37073
- throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37074
- code: ERROR_CODES.favoritePlanStale
37075
- });
37408
+ if (selection.mode === "activate" && selection.harness === "codex" && extras.authMode === "openai_auth" && selection.allowAuthOverwrite !== true) {
37409
+ projection.blockers.push({ code: ERROR_CODES.favoriteProjectionUnsupported });
37076
37410
  }
37077
- const source = this.profiles.get(input.harness, input.name);
37078
- if (source.overriddenTargets.length || source.modelFavorite) {
37079
- throw new HttpError(409, ERROR_CODES.favoriteRawOverrideConflict, {
37080
- code: ERROR_CODES.favoriteRawOverrideConflict
37081
- });
37411
+ const current = Object.fromEntries(adapter.targets().map((target) => [target.key, this.files.readOptional(target.path)]));
37412
+ if (!prior && extras.providerId && Object.values(current).some((content) => content?.includes(extras.providerId))) {
37413
+ projection.blockers.push({ code: ERROR_CODES.favoriteInUse });
37082
37414
  }
37083
- const decrypted = this.profiles.decrypt(input.harness, input.name);
37084
- const adapter = this.adapters.get(input.harness);
37085
- const extracted = adapter.extractFavorite(decrypted);
37086
- if (!source.providerId && !input.extractCredential) {
37087
- throw new HttpError(409, ERROR_CODES.favoriteCredentialConsentRequired, {
37088
- code: ERROR_CODES.favoriteCredentialConsentRequired
37089
- });
37415
+ let writes = [];
37416
+ if (selection.mode === "activate" && projection.blockers.length === 0) {
37417
+ try {
37418
+ writes = this.activation.prepareFavorite(selection.harness, profile);
37419
+ } catch (error52) {
37420
+ projection.blockers.push({
37421
+ code: error52 instanceof HttpError ? error52.code : ERROR_CODES.nativeConfigInvalid
37422
+ });
37423
+ }
37090
37424
  }
37091
- return this.backups.protect("change", () => this.liveWrite.transaction({
37092
- kind: "favorite-capture",
37093
- harness: input.harness,
37094
- profile: input.name,
37095
- writes: [],
37096
- metadata: ["profiles", "vault", "favorites"]
37097
- }, () => {
37098
- const provider = source.providerId ? this.vault.get(source.providerId) : this.vault.create({
37099
- name: input.favoriteName,
37100
- apiKey: decrypted.apiKey,
37101
- endpoints: [{ key: "api", baseUrl: decrypted.baseUrl }]
37102
- });
37103
- const endpointKey = source.providerEndpoint ?? provider.endpoints.find((endpoint) => endpoint.baseUrl === decrypted.baseUrl)?.key;
37104
- if (!endpointKey) {
37105
- throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
37106
- code: ERROR_CODES.favoriteEndpointMissing
37107
- });
37108
- }
37109
- if (!source.providerId || !source.providerEndpoint) {
37110
- this.profiles.upsert(input.harness, { name: input.name, providerId: provider.id, providerEndpoint: endpointKey }, false);
37111
- }
37112
- const favorite = this.create({
37113
- name: input.favoriteName,
37114
- notes: "",
37115
- defaults: extracted.defaults,
37116
- preferences: extracted.preferences,
37117
- connections: [
37118
- {
37119
- id: randomUUID5(),
37120
- label: provider.name,
37121
- providerId: provider.id,
37122
- endpointKey,
37123
- ...syncConnectionProtocols([extracted.protocol]),
37124
- requestModelId: extracted.requestModelId,
37125
- factOverrides: {},
37126
- preferenceOverrides: {}
37127
- }
37128
- ]
37129
- });
37130
- if (input.linkSource) {
37131
- const connection = favorite.connections[0];
37132
- const projection = adapter.projectFavorite(favorite, connection);
37133
- const current = this.profiles.get(input.harness, input.name);
37134
- const baseline = {
37135
- ...projection.projection,
37136
- model: current.model,
37137
- providerId: current.providerId ?? "",
37138
- providerEndpoint: current.providerEndpoint ?? "",
37139
- extras: Object.fromEntries(Object.keys(projection.projection.extras).map((key) => [
37140
- key,
37141
- current.extras[key] ?? null
37142
- ]))
37143
- };
37144
- this.profiles.setFavoriteLink(input.harness, input.name, {
37145
- favoriteId: favorite.id,
37146
- connectionId: connection.id,
37147
- appliedRevision: favorite.revision,
37148
- projectionVersion: projection.projectionVersion,
37149
- baseline
37150
- });
37425
+ const redactKeys = writes.length ? [profile.apiKey, ...this.vault.credentialsForRedaction()] : [];
37426
+ const item = {
37427
+ preservedFields: Object.keys(prior?.extras ?? {}).filter((key) => !Object.hasOwn(projection.projection.extras, key)),
37428
+ authMode: extras.authMode ?? extras.authVar ?? adapter.fields.find((field) => field.key === "authMode" || field.key === "authVar")?.defaultValue ?? "apiKey",
37429
+ liveState: "unknown",
37430
+ ...selection,
37431
+ profile: name,
37432
+ projection,
37433
+ resolved: resolveFavorite(favorite, connection),
37434
+ diff,
37435
+ nativeFiles: writes.map((write) => ({
37436
+ key: write.key,
37437
+ changed: current[write.key] !== write.content,
37438
+ before: favoriteNativePreview(write.format, current[write.key], redactKeys, write.key === "credentials"),
37439
+ after: favoriteNativePreview(write.format, write.content, redactKeys, write.key === "credentials")
37440
+ }))
37441
+ };
37442
+ return {
37443
+ public: item,
37444
+ input,
37445
+ profile,
37446
+ writes,
37447
+ link: {
37448
+ favoriteId: favorite.id,
37449
+ connectionId: connection.id,
37450
+ appliedRevision: favorite.revision,
37451
+ projectionVersion: projection.projectionVersion,
37452
+ baseline: projection.projection
37151
37453
  }
37152
- return favorite;
37153
- }), { action: "capture", name: input.favoriteName, tools: [input.harness] });
37154
- }
37155
- detach(harness, name, fingerprint2) {
37156
- if (this.sourceFingerprint(harness, name) !== fingerprint2) {
37157
- throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37158
- code: ERROR_CODES.favoritePlanStale
37159
- });
37160
- }
37161
- this.backups.protect("change", () => this.profiles.setFavoriteLink(harness, name, undefined), {
37162
- action: "detach",
37163
- name,
37164
- tools: [harness]
37165
- });
37454
+ };
37166
37455
  }
37167
- ignoreUpdates(id, revision) {
37168
- const favorite = this.store.get(id);
37169
- if (favorite.revision !== revision) {
37170
- throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37171
- code: ERROR_CODES.favoritePlanStale
37172
- });
37456
+ overwritePreview(favoriteId, request, session) {
37457
+ const favorite = this.favorites.get(favoriteId);
37458
+ if (favorite.revision !== request.expectedRevision) {
37459
+ throw failure3(ERROR_CODES.favoriteRevisionConflict);
37173
37460
  }
37174
- this.backups.protect("change", () => {
37175
- for (const ref of this.references(id)) {
37176
- this.profiles.setFavoriteLink(ref.harness, ref.name, {
37177
- ...ref.link,
37178
- ignoredRevision: revision
37179
- });
37461
+ const { resolution, affected, blockers, toolModelEntries } = this.resolveOverwrite(favorite, request.draft, request.remaps);
37462
+ const synthesized = { ...favorite, ...resolution.resolved };
37463
+ const items = [];
37464
+ for (const remap of resolution.remaps) {
37465
+ const row = affected.find((entry) => entry.harness === remap.harness && entry.profile === remap.profile);
37466
+ if (!row || row.collectionManaged || remap.profile === undefined) {
37467
+ continue;
37180
37468
  }
37181
- });
37182
- }
37183
- validateConnections(input) {
37184
- for (const connection of input.connections) {
37185
- const provider = this.vault.get(connection.providerId);
37186
- if (!provider.endpoints.some((endpoint) => endpoint.key === connection.endpointKey)) {
37187
- throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
37188
- code: ERROR_CODES.favoriteEndpointMissing
37469
+ try {
37470
+ const computed = this.computeItem(synthesized, {
37471
+ harness: remap.harness,
37472
+ connectionId: remap.connectionId,
37473
+ profile: remap.profile,
37474
+ existing: true,
37475
+ mode: row.inUse ? "activate" : "save",
37476
+ overwriteDiverged: remap.overwriteDiverged,
37477
+ ignorePreference: remap.ignorePreference,
37478
+ allowAuthOverwrite: remap.allowAuthOverwrite
37479
+ });
37480
+ items.push({
37481
+ public: computed.public,
37482
+ fingerprint: this.fingerprintOf(synthesized, computed.public)
37189
37483
  });
37484
+ } catch (error52) {
37485
+ if (!(error52 instanceof HttpError)) {
37486
+ throw error52;
37487
+ }
37488
+ blockers.push({ code: error52.code, harness: row.harness, profile: row.profile });
37190
37489
  }
37191
37490
  }
37192
- }
37193
- }
37194
- ModelFavoriteService = __decorateElement(_init, 0, "ModelFavoriteService", _dec, ModelFavoriteService);
37195
- __runInitializers(_init, 1, ModelFavoriteService);
37196
- __decoratorMetadata(_init, ModelFavoriteService);
37197
- let _ModelFavoriteService = ModelFavoriteService;
37198
- function sameAccountModel(previous, connections) {
37199
- return connections.find((connection) => connection.providerId === previous.providerId && connection.endpointKey === previous.endpointKey && connection.requestModelId === previous.requestModelId);
37200
- }
37201
-
37202
- // src/http/routes/harnesses.ts
37203
- function createHarnessRoutes(services) {
37204
- const app = new Hono2;
37205
- const registry2 = services.get(IHarnessRegistry);
37206
- const harnesses = services.get(IHarnessService);
37207
- const profiles = services.get(IProfileService);
37208
- const activation = services.get(IActivationService);
37209
- const profileProbe = services.get(IProbeProfileService);
37210
- const audit = services.get(IAuditService);
37211
- app.post("/:harnessId/profiles/:name/detach-favorite", async (c) => {
37212
- const body = await readJsonBody(c, favoriteDetachRequestSchema);
37213
- services.get(IModelFavoriteService).detach(registry2.require(param(c, "harnessId")), param(c, "name"), body.sourceFingerprint);
37214
- return c.json({ code: FAVORITE_CODES.result, data: { ok: true } });
37215
- });
37216
- app.get("/", (c) => c.json(harnesses.overview()));
37217
- app.get("/:harnessId", (c) => c.json(harnesses.summary(registry2.require(c.req.param("harnessId")))));
37218
- app.post("/:harnessId/profiles", async (c) => {
37219
- const harnessId = registry2.require(c.req.param("harnessId"));
37220
- const body = await readJsonBody(c, createProfileRequestSchema);
37221
- return c.json(harnesses.createProfile(harnessId, body), 201);
37222
- });
37223
- app.patch("/:harnessId/profiles/:name", async (c) => {
37224
- const harnessId = registry2.require(c.req.param("harnessId"));
37225
- const name = param(c, "name");
37226
- const body = await readJsonBody(c, updateProfileRequestSchema);
37227
- return c.json(harnesses.updateProfile(harnessId, name, body));
37228
- });
37229
- app.delete("/:harnessId/profiles/:name", (c) => {
37230
- harnesses.deleteProfile(registry2.require(c.req.param("harnessId")), param(c, "name"));
37231
- return c.json({ ok: true });
37232
- });
37233
- app.get("/:harnessId/profiles/:name/preview", (c) => {
37234
- const harnessId = registry2.require(c.req.param("harnessId"));
37235
- return c.json({ targets: activation.preview(harnessId, param(c, "name")) });
37236
- });
37237
- app.get("/:harnessId/official/preview", (c) => {
37238
- const harnessId = registry2.require(c.req.param("harnessId"));
37239
- return c.json({ targets: activation.previewOfficial(harnessId) });
37240
- });
37241
- app.post("/:harnessId/profiles/:name/probe", async (c) => {
37242
- const harnessId = registry2.require(c.req.param("harnessId"));
37243
- const name = param(c, "name");
37244
- const body = await readOptionalJsonBody(c, probeStoredRequestSchema);
37245
- const decrypted = profiles.decrypt(harnessId, name);
37246
- return c.json({
37247
- result: await profileProbe.probe(harnessId, decrypted, body)
37248
- });
37249
- });
37250
- app.post("/:harnessId/profiles/:name/activate", (c) => {
37251
- const harnessId = registry2.require(c.req.param("harnessId"));
37252
- const name = param(c, "name");
37253
- const result = activation.activate(harnessId, name);
37254
- audit.record(AUDIT_EVENTS.profileActivated, { harness: harnessId, profile: name });
37255
- return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
37256
- });
37257
- app.post("/:harnessId/official/activate", (c) => {
37258
- const harnessId = registry2.require(c.req.param("harnessId"));
37259
- const result = activation.activateOfficial(harnessId);
37260
- audit.record(AUDIT_EVENTS.officialActivated, { harness: harnessId });
37261
- return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
37262
- });
37263
- return app;
37264
- }
37265
-
37266
- // src/services/model-favorite-apply.ts
37267
- import { createHash as createHash9, randomUUID as randomUUID6 } from "node:crypto";
37268
- var IModelFavoriteApplyService = createDecorator("modelFavoriteApplyService");
37269
- var _dec = [
37270
- inject(IEnvironmentService, IFileService, IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, IActivationService, ILiveWriteService, IJournalService, IDriftService, IFavoriteBackupService)
37271
- ];
37272
- var _init = __decoratorStart(undefined);
37273
-
37274
- class ModelFavoriteApplyService {
37275
- environment;
37276
- files;
37277
- favorites;
37278
- profiles;
37279
- vault;
37280
- adapters;
37281
- activation;
37282
- liveWrite;
37283
- journal;
37284
- drift;
37285
- backups;
37286
- plans = new Map;
37287
- constructor(environment, files, favorites, profiles, vault, adapters, activation, liveWrite, journal, drift, backups) {
37288
- this.environment = environment;
37289
- this.files = files;
37290
- this.favorites = favorites;
37291
- this.profiles = profiles;
37292
- this.vault = vault;
37293
- this.adapters = adapters;
37294
- this.activation = activation;
37295
- this.liveWrite = liveWrite;
37296
- this.journal = journal;
37297
- this.drift = drift;
37298
- this.backups = backups;
37299
- }
37300
- state(profile) {
37301
- const link = profile.modelFavorite;
37302
- const favorite = link ? this.favorites.list().find((item) => item.id === link.favoriteId) : undefined;
37303
- const connection = favorite?.connections.find((item) => item.id === link?.connectionId);
37304
- const projected = favorite && connection ? this.adapters.get(profile.harness).projectFavorite(favorite, {
37305
- ...connection,
37306
- factOverrides: {
37307
- ...connection.factOverrides,
37308
- ...link?.collectionOverrides?.factOverrides
37309
- },
37310
- preferenceOverrides: {
37311
- ...connection.preferenceOverrides,
37312
- ...link?.collectionOverrides?.preferenceOverrides
37491
+ for (const [id, record2] of this.overwrites) {
37492
+ if (record2.expiresAt < Date.now()) {
37493
+ this.overwrites.delete(id);
37313
37494
  }
37314
- }, link?.baseline) : undefined;
37315
- return {
37316
- sourceMissing: !!link && !favorite,
37317
- connectionMissing: !!link && !connection,
37318
- needsUpdate: !!link && link.ignoredRevision !== favorite?.revision && !!projected && (link.projectionVersion !== projected.projectionVersion || hash3(link.baseline) !== hash3(projected.projection)),
37319
- diverged: !!link && (profile.overriddenTargets.length > 0 || hash3(snapshot(profile, link.baseline)) !== hash3(link.baseline))
37495
+ }
37496
+ if (this.overwrites.size >= 1000) {
37497
+ throw failure3(ERROR_CODES.favoriteLimitReached);
37498
+ }
37499
+ const preview = {
37500
+ id: randomUUID5(),
37501
+ expiresAt: new Date(Date.now() + 600000).toISOString(),
37502
+ favoriteRevision: favorite.revision,
37503
+ resolvedFavorite: synthesized,
37504
+ affected,
37505
+ items: items.map((item) => item.public),
37506
+ blockers
37320
37507
  };
37508
+ this.overwrites.set(preview.id, {
37509
+ id: preview.id,
37510
+ expiresAt: Date.parse(preview.expiresAt),
37511
+ session,
37512
+ user: this.environment.dataDir,
37513
+ favoriteId,
37514
+ expectedRevision: favorite.revision,
37515
+ resolved: synthesized,
37516
+ remaps: resolution.remaps,
37517
+ affected,
37518
+ blockers,
37519
+ toolModelEntries,
37520
+ toolModelsHash: this.toolModelsStateHash(),
37521
+ managedProfilesHash: this.managedProfilesHash(affected),
37522
+ items
37523
+ });
37524
+ return preview;
37321
37525
  }
37322
- plan(request, session) {
37323
- const favorite = this.favorites.get(request.favoriteId);
37324
- if (favorite.revision !== request.expectedRevision) {
37325
- throw failure3(ERROR_CODES.favoriteRevisionConflict);
37526
+ prepareOverwriteCommit(params) {
37527
+ const record2 = this.overwrites.get(params.approvalId);
37528
+ if (!record2 || record2.expiresAt < Date.now() || record2.user !== this.environment.dataDir || record2.session !== params.session || record2.favoriteId !== params.favoriteId) {
37529
+ throw failure3(ERROR_CODES.favoritePlanExpired);
37326
37530
  }
37327
- for (const [id, value] of this.plans) {
37328
- if (Date.parse(value.public.expiresAt) < Date.now()) {
37329
- this.plans.delete(id);
37330
- }
37531
+ if (record2.expectedRevision !== params.expectedRevision) {
37532
+ throw failure3(ERROR_CODES.favoritePlanStale);
37331
37533
  }
37332
- if (this.plans.size >= 1000) {
37333
- throw failure3(ERROR_CODES.favoriteLimitReached);
37534
+ if (!params.remaps) {
37535
+ throw failure3(ERROR_CODES.favoritePlanStale);
37334
37536
  }
37335
- const items = request.items.toSorted((a, b) => HARNESS_IDS.indexOf(a.harness) - HARNESS_IDS.indexOf(b.harness)).map((selection) => {
37336
- const connection = favorite.connections.find((item2) => item2.id === selection.connectionId);
37337
- if (!connection) {
37338
- throw failure3(ERROR_CODES.favoriteEndpointMissing);
37339
- }
37340
- const provider = this.vault.get(connection.providerId);
37341
- const endpoint = provider.endpoints.find((item2) => item2.key === connection.endpointKey);
37342
- if (!endpoint) {
37343
- throw failure3(ERROR_CODES.favoriteEndpointMissing);
37344
- }
37345
- const adapter = this.adapters.get(selection.harness);
37346
- let name = selection.profile ?? favorite.name.replace(/[\\/]/g, "-");
37347
- if (!selection.existing && !selection.profile) {
37348
- let suffix = 2;
37349
- const base = name;
37350
- while (this.profiles.get(selection.harness, name)) {
37351
- name = `${base.slice(0, 110)}-${suffix++}`;
37352
- }
37353
- }
37354
- const prior = this.profiles.get(selection.harness, name);
37355
- if (prior?.modelFavorite?.collectionOverrides) {
37356
- throw failure3(ERROR_CODES.toolModelsConflict);
37357
- }
37358
- if (selection.existing ? prior?.modelFavorite?.favoriteId !== favorite.id : !!prior) {
37359
- throw failure3(ERROR_CODES.favoriteInUse);
37360
- }
37361
- if (prior?.overriddenTargets.length) {
37362
- throw failure3(ERROR_CODES.favoriteRawOverrideConflict);
37363
- }
37364
- const projection = adapter.projectFavorite(favorite, connection, prior?.modelFavorite?.baseline);
37365
- if (prior && this.state(prior).diverged && !selection.overwriteDiverged) {
37366
- projection.blockers.push({ code: ERROR_CODES.favoriteProfileDiverged });
37367
- }
37368
- if (projection.notRepresented.includes("reasoningEffort") && !selection.ignorePreference) {
37369
- projection.blockers.push({ code: ERROR_CODES.favoritePreferenceNotRepresented });
37370
- }
37371
- const extras = { ...prior?.extras };
37372
- if (!prior && ["pi", "dsh", "codex", "kimi"].includes(selection.harness)) {
37373
- extras.providerId = `hsw-mf-${randomUUID6()}`;
37374
- }
37375
- for (const [key, value] of Object.entries(projection.projection.extras)) {
37376
- if (value === null) {
37377
- delete extras[key];
37378
- } else {
37379
- extras[key] = value;
37380
- }
37381
- }
37382
- for (const key of Object.keys(projection.rendererDefaults)) {
37383
- if (extras[key]) {
37384
- delete projection.rendererDefaults[key];
37385
- }
37537
+ if (record2.blockers.length) {
37538
+ throw failure3(record2.blockers[0].code);
37539
+ }
37540
+ if (this.toolModelsStateHash() !== record2.toolModelsHash || this.managedProfilesHash(record2.affected) !== record2.managedProfilesHash) {
37541
+ throw failure3(ERROR_CODES.favoritePlanStale);
37542
+ }
37543
+ const { resolution, affected, blockers, toolModelEntries } = this.resolveOverwrite(this.favorites.get(params.favoriteId), params.next, params.remaps);
37544
+ if (blockers.length || canon(affected) !== canon(record2.affected) || canon(toolModelEntries) !== canon(record2.toolModelEntries) || canon(resolution.remaps) !== canon(record2.remaps) || canon(resolution.resolved) !== canon(createFavoriteRequestSchema.parse(record2.resolved))) {
37545
+ throw failure3(ERROR_CODES.favoritePlanStale);
37546
+ }
37547
+ for (const item of record2.items) {
37548
+ if (item.public.projection.blockers.length) {
37549
+ throw failure3(item.public.projection.blockers[0].code);
37386
37550
  }
37387
- const profile = {
37388
- favoriteManaged: true,
37389
- name,
37390
- model: connection.requestModelId,
37391
- extras,
37392
- baseUrl: endpoint.baseUrl,
37393
- apiKey: this.vault.decrypt(provider.id)
37394
- };
37395
- adapter.validate?.(profile);
37396
- const input = {
37397
- name,
37398
- model: profile.model,
37399
- extras,
37400
- baseUrl: profile.baseUrl,
37401
- providerId: provider.id,
37402
- providerEndpoint: endpoint.key
37403
- };
37404
- const diff = projection.ownedFields.flatMap((field) => {
37405
- const before = field.startsWith("extras.") ? prior?.extras[field.slice(7)] ?? null : field === "model" ? prior?.model ?? null : field === "providerId" ? prior?.providerId ?? null : prior?.providerEndpoint ?? null;
37406
- const after = projection.set[field] ?? null;
37407
- return before === after ? [] : [{ field, before, after }];
37408
- });
37409
- if (selection.mode === "save" && this.activation.getActive(selection.harness)?.name === name && (diff.length || prior?.baseUrl !== endpoint.baseUrl)) {
37410
- projection.blockers.push({ code: ERROR_CODES.favoriteActiveUpdateRequiresApply });
37551
+ if (item.fingerprint !== this.fingerprintOf(record2.resolved, item.public)) {
37552
+ throw failure3(ERROR_CODES.favoritePlanStale);
37411
37553
  }
37412
- if (selection.mode === "activate" && selection.harness === "codex" && extras.authMode === "openai_auth" && selection.allowAuthOverwrite !== true) {
37413
- projection.blockers.push({ code: ERROR_CODES.favoriteProjectionUnsupported });
37554
+ }
37555
+ return {
37556
+ resolved: record2.resolved,
37557
+ remaps: record2.remaps,
37558
+ toolModelEntries: record2.toolModelEntries
37559
+ };
37560
+ }
37561
+ consumeOverwrite(approvalId) {
37562
+ this.overwrites.delete(approvalId);
37563
+ }
37564
+ prepareRegularUpdate(favorite, draft) {
37565
+ const { resolution, affected, blockers, toolModelEntries } = this.resolveOverwrite(favorite, draft, []);
37566
+ if (blockers.length || affected.some((row) => row.collectionManaged && row.profile !== undefined)) {
37567
+ throw failure3(ERROR_CODES.favoriteConnectionInUse);
37568
+ }
37569
+ return { resolved: resolution.resolved, remaps: resolution.remaps, toolModelEntries };
37570
+ }
37571
+ resolveOverwrite(favorite, draft, remaps) {
37572
+ const profiles = this.linkedReferences(favorite.id);
37573
+ const drafts = this.toolModels.favoriteDraftItems(favorite.id);
37574
+ const owners = drafts.map((item) => ({
37575
+ item,
37576
+ owner: profiles.find((ref) => ref.harness === item.harness && ref.profile === item.profile && ref.connectionId === item.connectionId && ref.link?.collectionOverrides !== undefined)
37577
+ }));
37578
+ const refs = [
37579
+ ...profiles,
37580
+ ...owners.flatMap(({ item, owner }) => owner ? [] : [{ harness: item.harness, itemId: item.itemId, connectionId: item.connectionId }])
37581
+ ];
37582
+ const resolution = resolveOverwriteRemaps({ current: favorite, draft, refs, remaps });
37583
+ if (resolution.problems.length) {
37584
+ throw failure3(resolution.problems[0].code);
37585
+ }
37586
+ const resolved = createFavoriteRequestSchema.safeParse(resolution.resolved);
37587
+ const affected = resolution.affected.map((row) => ({
37588
+ ...row,
37589
+ inUse: row.profile !== undefined && this.activation.getActive(row.harness)?.name === row.profile
37590
+ }));
37591
+ const choices = new Map(affected.map((row) => [overwriteReferenceKey(row), row.connectionId]));
37592
+ const toolModelEntries = owners.flatMap(({ item, owner }) => {
37593
+ const connectionId = choices.get(overwriteReferenceKey(owner ?? { harness: item.harness, itemId: item.itemId }));
37594
+ return connectionId ? [{ harness: item.harness, itemId: item.itemId, connectionId }] : [];
37595
+ });
37596
+ const blockers = affected.flatMap((row) => row.connectionId ? [] : [
37597
+ {
37598
+ code: ERROR_CODES.favoriteConnectionInUse,
37599
+ harness: row.harness,
37600
+ profile: row.profile,
37601
+ model: row.from.requestModelId || row.from.connectionId
37414
37602
  }
37415
- const current = Object.fromEntries(adapter.targets().map((target) => [target.key, this.files.readOptional(target.path)]));
37416
- if (!prior && extras.providerId && Object.values(current).some((content) => content?.includes(extras.providerId))) {
37417
- projection.blockers.push({ code: ERROR_CODES.favoriteInUse });
37603
+ ]);
37604
+ if (!resolved.success) {
37605
+ blockers.push({ code: ERROR_CODES.favoriteConnectionInUse });
37606
+ } else {
37607
+ resolution.resolved = resolved.data;
37608
+ if (blockers.length === 0) {
37609
+ blockers.push(...this.toolModels.checkFavoriteRemaps(favorite.id, resolved.data, toolModelEntries));
37418
37610
  }
37419
- let writes = [];
37420
- if (selection.mode === "activate" && projection.blockers.length === 0) {
37421
- try {
37422
- writes = this.activation.prepareFavorite(selection.harness, profile);
37423
- } catch (error52) {
37424
- projection.blockers.push({
37425
- code: error52 instanceof HttpError ? error52.code : ERROR_CODES.nativeConfigInvalid
37426
- });
37427
- }
37611
+ }
37612
+ return { resolution, affected, blockers, toolModelEntries };
37613
+ }
37614
+ managedProfilesHash(affected) {
37615
+ return hash3(affected.flatMap((row) => row.collectionManaged && row.profile !== undefined ? [this.profiles.fingerprint(row.harness, row.profile)] : []));
37616
+ }
37617
+ toolModelsStateHash() {
37618
+ return hash3(this.files.readOptional(this.environment.files.toolModels) ?? null);
37619
+ }
37620
+ linkedReferences(favoriteId) {
37621
+ return HARNESS_IDS.flatMap((harness) => this.profiles.peek(harness).flatMap((profile) => profile.modelFavorite?.favoriteId === favoriteId ? [
37622
+ {
37623
+ harness,
37624
+ profile: profile.name,
37625
+ connectionId: profile.modelFavorite.connectionId,
37626
+ link: profile.modelFavorite
37428
37627
  }
37429
- const item = {
37430
- preservedFields: Object.keys(prior?.extras ?? {}).filter((key) => !Object.hasOwn(projection.projection.extras, key)),
37431
- authMode: extras.authMode ?? extras.authVar ?? adapter.fields.find((field) => field.key === "authMode" || field.key === "authVar")?.defaultValue ?? "apiKey",
37432
- liveState: selection.mode === "activate" ? this.drift.inspect(selection.harness).status : "unknown",
37433
- ...selection,
37434
- profile: name,
37435
- projection,
37436
- resolved: resolveFavorite(favorite, connection),
37437
- diff,
37438
- nativeFiles: writes.map((write) => ({
37439
- key: write.key,
37440
- changed: current[write.key] !== write.content,
37441
- before: favoriteNativePreview(write.format, current[write.key], [profile.apiKey]),
37442
- after: favoriteNativePreview(write.format, write.content, [profile.apiKey])
37443
- }))
37444
- };
37445
- return {
37446
- public: item,
37447
- input,
37448
- profile,
37449
- link: {
37450
- favoriteId: favorite.id,
37451
- connectionId: connection.id,
37452
- appliedRevision: favorite.revision,
37453
- projectionVersion: projection.projectionVersion,
37454
- baseline: projection.projection
37455
- },
37456
- writes,
37457
- fingerprint: this.fingerprint(favorite.id, item)
37458
- };
37459
- });
37460
- const plan = {
37461
- id: randomUUID6(),
37462
- expiresAt: new Date(Date.now() + 600000).toISOString(),
37463
- favoriteRevision: favorite.revision,
37464
- items: items.map((item) => item.public)
37465
- };
37466
- this.plans.set(plan.id, {
37467
- public: plan,
37468
- items,
37469
- user: this.environment.dataDir,
37470
- session,
37471
- favoriteId: favorite.id
37472
- });
37473
- return plan;
37628
+ ] : []));
37474
37629
  }
37475
37630
  operation(requestId) {
37476
37631
  const receipts = this.journal.list().filter((receipt) => receipt.favoriteRequest?.requestId === requestId).toSorted((a, b) => a.favoriteRequest.item - b.favoriteRequest.item);
@@ -37523,113 +37678,433 @@ class ModelFavoriteApplyService {
37523
37678
  if (!this.matchesFingerprint(plan.favoriteId, prepared)) {
37524
37679
  throw failure3(ERROR_CODES.favoritePlanStale);
37525
37680
  }
37526
- if (item.projection.blockers.length) {
37527
- throw failure3(item.projection.blockers[0].code);
37681
+ if (item.projection.blockers.length) {
37682
+ throw failure3(item.projection.blockers[0].code);
37683
+ }
37684
+ const unchanged = item.existing && item.diff.length === 0 && (item.mode === "save" || this.activation.getActive(item.harness)?.name === item.profile && item.nativeFiles.every((file2) => !file2.changed));
37685
+ try {
37686
+ this.liveWrite.transaction({
37687
+ kind: "favorite-apply",
37688
+ harness: item.harness,
37689
+ profile: item.profile,
37690
+ writes: unchanged ? [] : prepared.writes,
37691
+ metadata: item.mode === "activate" && !unchanged ? ["profiles", "active"] : ["profiles"],
37692
+ favoriteRequest: {
37693
+ version: 1,
37694
+ requestId,
37695
+ planId: id,
37696
+ item: index,
37697
+ approvalHash: hash3(plan.public),
37698
+ targets: plan.items.map((entry) => ({
37699
+ harness: entry.public.harness,
37700
+ profile: entry.public.profile
37701
+ }))
37702
+ },
37703
+ favoriteResult: { status: unchanged ? "unchanged" : "applied" },
37704
+ beforeWrites: item.mode === "activate" && !unchanged ? () => this.activation.commitFavorite(item.harness, prepared.profile) : undefined
37705
+ }, () => {
37706
+ if (unchanged) {
37707
+ this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37708
+ return;
37709
+ }
37710
+ if (item.existing) {
37711
+ this.profiles.setFavoriteLink(item.harness, item.profile, undefined);
37712
+ }
37713
+ this.profiles.upsert(item.harness, prepared.input, !item.existing);
37714
+ this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37715
+ });
37716
+ if (item.mode === "activate" && !unchanged) {
37717
+ try {
37718
+ this.activation.refreshEnv();
37719
+ } catch {
37720
+ const receipt = this.journal.list().find((entry) => entry.favoriteRequest?.requestId === requestId && entry.favoriteRequest.item === index);
37721
+ if (receipt) {
37722
+ this.journal.setFavoriteResult(receipt.id, {
37723
+ status: unchanged ? "unchanged" : "applied",
37724
+ code: WARNING_CODES.envRebuildFailed
37725
+ });
37726
+ }
37727
+ }
37728
+ }
37729
+ } catch (error52) {
37730
+ result.items.push({
37731
+ harness: item.harness,
37732
+ profile: item.profile,
37733
+ status: "failed",
37734
+ code: error52 instanceof HttpError ? error52.code : ERROR_CODES.requestFailed
37735
+ });
37736
+ if (this.journal.list().some((receipt) => receipt.favoriteRequest?.requestId === requestId && receipt.state === "degraded") || !this.journal.list().some((receipt) => receipt.favoriteRequest?.requestId === requestId && receipt.favoriteRequest.item === index)) {
37737
+ break;
37738
+ }
37739
+ }
37740
+ }
37741
+ this.plans.delete(id);
37742
+ return {
37743
+ requestId,
37744
+ items: [
37745
+ ...this.operation(requestId).items,
37746
+ ...result.items.filter((item) => !this.operation(requestId).items.some((saved) => saved.harness === item.harness))
37747
+ ]
37748
+ };
37749
+ }
37750
+ matchesFingerprint(favoriteId, prepared) {
37751
+ try {
37752
+ return prepared.fingerprint === this.fingerprint(favoriteId, prepared.public);
37753
+ } catch {
37754
+ return false;
37755
+ }
37756
+ }
37757
+ fingerprint(favoriteId, item) {
37758
+ return this.fingerprintOf(this.favorites.get(favoriteId), item);
37759
+ }
37760
+ fingerprintOf(favorite, item) {
37761
+ const connection = favorite.connections.find((entry) => entry.id === item.connectionId);
37762
+ return hash3({
37763
+ favorite,
37764
+ profile: this.profiles.fingerprint(item.harness, item.profile),
37765
+ credential: connection ? this.vault.decrypt(connection.providerId) : null,
37766
+ provider: connection ? this.vault.get(connection.providerId) : null,
37767
+ active: this.activation.fingerprint(item.harness),
37768
+ files: this.adapters.get(item.harness).targets().map((target) => [target.key, this.files.readOptional(target.path)])
37769
+ });
37770
+ }
37771
+ }
37772
+ ModelFavoriteApplyService = __decorateElement(_init, 0, "ModelFavoriteApplyService", _dec, ModelFavoriteApplyService);
37773
+ __runInitializers(_init, 1, ModelFavoriteApplyService);
37774
+ __decoratorMetadata(_init, ModelFavoriteApplyService);
37775
+ let _ModelFavoriteApplyService = ModelFavoriteApplyService;
37776
+ function canon(value) {
37777
+ if (Array.isArray(value)) {
37778
+ return `[${value.map(canon).join(",")}]`;
37779
+ }
37780
+ if (value && typeof value === "object") {
37781
+ return `{${Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : 1).map(([key, entry]) => `${JSON.stringify(key)}:${canon(entry)}`).join(",")}}`;
37782
+ }
37783
+ return JSON.stringify(value) ?? "null";
37784
+ }
37785
+ function hash3(value) {
37786
+ return createHash9("sha256").update(JSON.stringify(value)).digest("hex");
37787
+ }
37788
+ function failure3(code) {
37789
+ return new HttpError(409, code, { code });
37790
+ }
37791
+ function snapshot(profile, baseline) {
37792
+ return {
37793
+ harness: profile.harness,
37794
+ model: profile.model,
37795
+ providerId: profile.providerId ?? "",
37796
+ providerEndpoint: profile.providerEndpoint ?? "",
37797
+ extras: Object.fromEntries(Object.keys(baseline.extras).map((key) => [key, profile.extras[key] ?? null]))
37798
+ };
37799
+ }
37800
+
37801
+ // src/services/model-favorite.ts
37802
+ var IModelFavoriteService = createDecorator("modelFavoriteService");
37803
+ var _dec = [
37804
+ inject(IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, ILiveWriteService, IFavoriteBackupService, IToolModelsService, IModelFavoriteApplyService)
37805
+ ];
37806
+ var _init = __decoratorStart(undefined);
37807
+
37808
+ class ModelFavoriteService {
37809
+ store;
37810
+ profiles;
37811
+ vault;
37812
+ adapters;
37813
+ liveWrite;
37814
+ backups;
37815
+ toolModels;
37816
+ apply;
37817
+ sourceSalt = randomUUID6();
37818
+ constructor(store, profiles, vault, adapters, liveWrite, backups, toolModels, apply) {
37819
+ this.store = store;
37820
+ this.profiles = profiles;
37821
+ this.vault = vault;
37822
+ this.adapters = adapters;
37823
+ this.liveWrite = liveWrite;
37824
+ this.backups = backups;
37825
+ this.toolModels = toolModels;
37826
+ this.apply = apply;
37827
+ }
37828
+ list() {
37829
+ return this.store.list().map((favorite) => ({ ...favorite, references: this.references(favorite.id) }));
37830
+ }
37831
+ references(id) {
37832
+ return HARNESS_IDS.flatMap((harness) => this.profiles.list(harness).flatMap((profile) => profile.modelFavorite?.favoriteId === id ? [{ harness, name: profile.name, link: profile.modelFavorite }] : []));
37833
+ }
37834
+ create(input) {
37835
+ const parsed = createFavoriteRequestSchema.parse(input);
37836
+ this.validateConnections(parsed);
37837
+ return this.backups.protect("change", () => this.store.create(parsed), {
37838
+ action: "create",
37839
+ name: parsed.name
37840
+ });
37841
+ }
37842
+ update(id, input, session) {
37843
+ this.store.assertRevision(id, input.expectedRevision);
37844
+ const current = this.store.get(id);
37845
+ const next = createFavoriteRequestSchema.parse({ ...current, ...input });
37846
+ this.validateConnections(next);
37847
+ if (input.overwriteApprovalId || input.connectionRemaps?.length) {
37848
+ return this.updateOverwrite(id, current, next, input, session);
37849
+ }
37850
+ const prepared = this.apply.prepareRegularUpdate(current, next);
37851
+ this.validateConnections(prepared.resolved);
37852
+ return this.commitUpdate(current, input.expectedRevision, prepared);
37853
+ }
37854
+ remove(id, revision) {
37855
+ this.store.assertRevision(id, revision);
37856
+ if (this.references(id).length) {
37857
+ throw new HttpError(409, ERROR_CODES.favoriteInUse, { code: ERROR_CODES.favoriteInUse });
37858
+ }
37859
+ this.backups.protect("change", () => this.store.remove(id, revision), {
37860
+ action: "delete",
37861
+ name: this.store.get(id).name
37862
+ });
37863
+ }
37864
+ updateOverwrite(id, current, next, input, session) {
37865
+ if (!session || !input.overwriteApprovalId) {
37866
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37867
+ code: ERROR_CODES.favoritePlanStale
37868
+ });
37869
+ }
37870
+ const prepared = this.apply.prepareOverwriteCommit({
37871
+ approvalId: input.overwriteApprovalId,
37872
+ remaps: input.connectionRemaps,
37873
+ favoriteId: id,
37874
+ expectedRevision: input.expectedRevision,
37875
+ next,
37876
+ session
37877
+ });
37878
+ const updated = this.commitUpdate(current, input.expectedRevision, prepared);
37879
+ this.apply.consumeOverwrite(input.overwriteApprovalId);
37880
+ return updated;
37881
+ }
37882
+ commitUpdate(current, revision, prepared) {
37883
+ return this.backups.protect("change", () => this.liveWrite.transaction({
37884
+ kind: "favorite-apply",
37885
+ harness: prepared.remaps[0]?.harness ?? "claude",
37886
+ profile: current.name,
37887
+ writes: [],
37888
+ metadata: [
37889
+ "favorites",
37890
+ "profiles",
37891
+ ...prepared.toolModelEntries.length ? ["toolModels"] : []
37892
+ ]
37893
+ }, () => {
37894
+ const saved = this.store.update(current.id, prepared.resolved, revision);
37895
+ for (const remap of prepared.remaps) {
37896
+ if (remap.profile === undefined) {
37897
+ continue;
37898
+ }
37899
+ const link = this.profiles.get(remap.harness, remap.profile)?.modelFavorite;
37900
+ if (link) {
37901
+ this.profiles.setFavoriteLink(remap.harness, remap.profile, {
37902
+ ...link,
37903
+ connectionId: remap.connectionId
37904
+ });
37905
+ }
37906
+ }
37907
+ this.toolModels.remapFavoriteConnectionsScoped(current.id, prepared.toolModelEntries);
37908
+ return saved;
37909
+ }), { action: "update", name: current.name });
37910
+ }
37911
+ sourceFingerprint(harness, name) {
37912
+ const profile = this.profiles.get(harness, name);
37913
+ if (!profile) {
37914
+ throw new HttpError(404, ERROR_CODES.profileNotFound, { code: ERROR_CODES.profileNotFound });
37915
+ }
37916
+ return createHmac("sha256", this.sourceSalt).update(this.profiles.fingerprint(harness, name)).digest("hex");
37917
+ }
37918
+ capture(input) {
37919
+ if (this.sourceFingerprint(input.harness, input.name) !== input.sourceFingerprint) {
37920
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37921
+ code: ERROR_CODES.favoritePlanStale
37922
+ });
37923
+ }
37924
+ const source = this.profiles.get(input.harness, input.name);
37925
+ if (source.overriddenTargets.length || source.modelFavorite) {
37926
+ throw new HttpError(409, ERROR_CODES.favoriteRawOverrideConflict, {
37927
+ code: ERROR_CODES.favoriteRawOverrideConflict
37928
+ });
37929
+ }
37930
+ const decrypted = this.profiles.decrypt(input.harness, input.name);
37931
+ const adapter = this.adapters.get(input.harness);
37932
+ const extracted = adapter.extractFavorite(decrypted);
37933
+ if (!source.providerId && !input.extractCredential) {
37934
+ throw new HttpError(409, ERROR_CODES.favoriteCredentialConsentRequired, {
37935
+ code: ERROR_CODES.favoriteCredentialConsentRequired
37936
+ });
37937
+ }
37938
+ return this.backups.protect("change", () => this.liveWrite.transaction({
37939
+ kind: "favorite-capture",
37940
+ harness: input.harness,
37941
+ profile: input.name,
37942
+ writes: [],
37943
+ metadata: ["profiles", "vault", "favorites"]
37944
+ }, () => {
37945
+ const provider = source.providerId ? this.vault.get(source.providerId) : this.vault.create({
37946
+ name: input.favoriteName,
37947
+ apiKey: decrypted.apiKey,
37948
+ endpoints: [{ key: "api", baseUrl: decrypted.baseUrl }]
37949
+ });
37950
+ const endpointKey = source.providerEndpoint ?? provider.endpoints.find((endpoint) => endpoint.baseUrl === decrypted.baseUrl)?.key;
37951
+ if (!endpointKey) {
37952
+ throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
37953
+ code: ERROR_CODES.favoriteEndpointMissing
37954
+ });
37955
+ }
37956
+ if (!source.providerId || !source.providerEndpoint) {
37957
+ this.profiles.upsert(input.harness, { name: input.name, providerId: provider.id, providerEndpoint: endpointKey }, false);
37528
37958
  }
37529
- const unchanged = item.existing && item.diff.length === 0 && (item.mode === "save" || this.activation.getActive(item.harness)?.name === item.profile && item.nativeFiles.every((file2) => !file2.changed));
37530
- try {
37531
- this.liveWrite.transaction({
37532
- kind: "favorite-apply",
37533
- harness: item.harness,
37534
- profile: item.profile,
37535
- writes: unchanged ? [] : prepared.writes,
37536
- metadata: item.mode === "activate" && !unchanged ? ["profiles", "active"] : ["profiles"],
37537
- favoriteRequest: {
37538
- version: 1,
37539
- requestId,
37540
- planId: id,
37541
- item: index,
37542
- approvalHash: hash3(plan.public),
37543
- targets: plan.items.map((entry) => ({
37544
- harness: entry.public.harness,
37545
- profile: entry.public.profile
37546
- }))
37547
- },
37548
- favoriteResult: { status: unchanged ? "unchanged" : "applied" },
37549
- beforeWrites: item.mode === "activate" && !unchanged ? () => this.activation.commitFavorite(item.harness, prepared.profile) : undefined
37550
- }, () => {
37551
- if (unchanged) {
37552
- this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37553
- return;
37554
- }
37555
- if (item.existing) {
37556
- this.profiles.setFavoriteLink(item.harness, item.profile, undefined);
37557
- }
37558
- this.profiles.upsert(item.harness, prepared.input, !item.existing);
37559
- this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37560
- });
37561
- if (item.mode === "activate" && !unchanged) {
37562
- try {
37563
- this.activation.refreshEnv();
37564
- } catch {
37565
- const receipt = this.journal.list().find((entry) => entry.favoriteRequest?.requestId === requestId && entry.favoriteRequest.item === index);
37566
- if (receipt) {
37567
- this.journal.setFavoriteResult(receipt.id, {
37568
- status: unchanged ? "unchanged" : "applied",
37569
- code: WARNING_CODES.envRebuildFailed
37570
- });
37571
- }
37959
+ const favorite = this.create({
37960
+ name: input.favoriteName,
37961
+ notes: "",
37962
+ defaults: extracted.defaults,
37963
+ preferences: extracted.preferences,
37964
+ connections: [
37965
+ {
37966
+ id: randomUUID6(),
37967
+ label: provider.name,
37968
+ providerId: provider.id,
37969
+ endpointKey,
37970
+ ...syncConnectionProtocols([extracted.protocol]),
37971
+ requestModelId: extracted.requestModelId,
37972
+ factOverrides: {},
37973
+ preferenceOverrides: {}
37572
37974
  }
37573
- }
37574
- } catch (error52) {
37575
- result.items.push({
37576
- harness: item.harness,
37577
- profile: item.profile,
37578
- status: "failed",
37579
- code: error52 instanceof HttpError ? error52.code : ERROR_CODES.requestFailed
37975
+ ]
37976
+ });
37977
+ if (input.linkSource) {
37978
+ const connection = favorite.connections[0];
37979
+ const projection = adapter.projectFavorite(favorite, connection);
37980
+ const current = this.profiles.get(input.harness, input.name);
37981
+ const baseline = {
37982
+ ...projection.projection,
37983
+ model: current.model,
37984
+ providerId: current.providerId ?? "",
37985
+ providerEndpoint: current.providerEndpoint ?? "",
37986
+ extras: Object.fromEntries(Object.keys(projection.projection.extras).map((key) => [
37987
+ key,
37988
+ current.extras[key] ?? null
37989
+ ]))
37990
+ };
37991
+ this.profiles.setFavoriteLink(input.harness, input.name, {
37992
+ favoriteId: favorite.id,
37993
+ connectionId: connection.id,
37994
+ appliedRevision: favorite.revision,
37995
+ projectionVersion: projection.projectionVersion,
37996
+ baseline
37580
37997
  });
37581
- if (this.journal.list().some((receipt) => receipt.favoriteRequest?.requestId === requestId && receipt.state === "degraded") || !this.journal.list().some((receipt) => receipt.favoriteRequest?.requestId === requestId && receipt.favoriteRequest.item === index)) {
37582
- break;
37583
- }
37584
37998
  }
37585
- }
37586
- this.plans.delete(id);
37587
- return {
37588
- requestId,
37589
- items: [
37590
- ...this.operation(requestId).items,
37591
- ...result.items.filter((item) => !this.operation(requestId).items.some((saved) => saved.harness === item.harness))
37592
- ]
37593
- };
37999
+ return favorite;
38000
+ }), { action: "capture", name: input.favoriteName, tools: [input.harness] });
37594
38001
  }
37595
- matchesFingerprint(favoriteId, prepared) {
37596
- try {
37597
- return prepared.fingerprint === this.fingerprint(favoriteId, prepared.public);
37598
- } catch {
37599
- return false;
38002
+ detach(harness, name, fingerprint2) {
38003
+ if (this.sourceFingerprint(harness, name) !== fingerprint2) {
38004
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
38005
+ code: ERROR_CODES.favoritePlanStale
38006
+ });
37600
38007
  }
38008
+ this.backups.protect("change", () => this.profiles.setFavoriteLink(harness, name, undefined), {
38009
+ action: "detach",
38010
+ name,
38011
+ tools: [harness]
38012
+ });
37601
38013
  }
37602
- fingerprint(favoriteId, item) {
37603
- const favorite = this.favorites.get(favoriteId);
37604
- const connection = favorite.connections.find((entry) => entry.id === item.connectionId);
37605
- return hash3({
37606
- favorite,
37607
- profile: this.profiles.fingerprint(item.harness, item.profile),
37608
- credential: connection ? this.vault.decrypt(connection.providerId) : null,
37609
- provider: connection ? this.vault.get(connection.providerId) : null,
37610
- active: this.activation.fingerprint(item.harness),
37611
- files: this.adapters.get(item.harness).targets().map((target) => [target.key, this.files.readOptional(target.path)])
38014
+ ignoreUpdates(id, revision) {
38015
+ const favorite = this.store.get(id);
38016
+ if (favorite.revision !== revision) {
38017
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
38018
+ code: ERROR_CODES.favoritePlanStale
38019
+ });
38020
+ }
38021
+ this.backups.protect("change", () => {
38022
+ for (const ref of this.references(id)) {
38023
+ this.profiles.setFavoriteLink(ref.harness, ref.name, {
38024
+ ...ref.link,
38025
+ ignoredRevision: revision
38026
+ });
38027
+ }
37612
38028
  });
37613
38029
  }
38030
+ validateConnections(input) {
38031
+ for (const connection of input.connections) {
38032
+ const provider = this.vault.get(connection.providerId);
38033
+ if (!provider.endpoints.some((endpoint) => endpoint.key === connection.endpointKey)) {
38034
+ throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
38035
+ code: ERROR_CODES.favoriteEndpointMissing
38036
+ });
38037
+ }
38038
+ }
38039
+ }
37614
38040
  }
37615
- ModelFavoriteApplyService = __decorateElement(_init, 0, "ModelFavoriteApplyService", _dec, ModelFavoriteApplyService);
37616
- __runInitializers(_init, 1, ModelFavoriteApplyService);
37617
- __decoratorMetadata(_init, ModelFavoriteApplyService);
37618
- let _ModelFavoriteApplyService = ModelFavoriteApplyService;
37619
- function hash3(value) {
37620
- return createHash9("sha256").update(JSON.stringify(value)).digest("hex");
37621
- }
37622
- function failure3(code) {
37623
- return new HttpError(409, code, { code });
37624
- }
37625
- function snapshot(profile, baseline) {
37626
- return {
37627
- harness: profile.harness,
37628
- model: profile.model,
37629
- providerId: profile.providerId ?? "",
37630
- providerEndpoint: profile.providerEndpoint ?? "",
37631
- extras: Object.fromEntries(Object.keys(baseline.extras).map((key) => [key, profile.extras[key] ?? null]))
37632
- };
38041
+ ModelFavoriteService = __decorateElement(_init, 0, "ModelFavoriteService", _dec, ModelFavoriteService);
38042
+ __runInitializers(_init, 1, ModelFavoriteService);
38043
+ __decoratorMetadata(_init, ModelFavoriteService);
38044
+ let _ModelFavoriteService = ModelFavoriteService;
38045
+
38046
+ // src/http/routes/harnesses.ts
38047
+ function createHarnessRoutes(services) {
38048
+ const app = new Hono2;
38049
+ const registry2 = services.get(IHarnessRegistry);
38050
+ const harnesses = services.get(IHarnessService);
38051
+ const profiles = services.get(IProfileService);
38052
+ const activation = services.get(IActivationService);
38053
+ const profileProbe = services.get(IProbeProfileService);
38054
+ const audit = services.get(IAuditService);
38055
+ app.post("/:harnessId/profiles/:name/detach-favorite", async (c) => {
38056
+ const body = await readJsonBody(c, favoriteDetachRequestSchema);
38057
+ services.get(IModelFavoriteService).detach(registry2.require(param(c, "harnessId")), param(c, "name"), body.sourceFingerprint);
38058
+ return c.json({ code: FAVORITE_CODES.result, data: { ok: true } });
38059
+ });
38060
+ app.get("/", (c) => c.json(harnesses.overview()));
38061
+ app.get("/:harnessId", (c) => c.json(harnesses.summary(registry2.require(c.req.param("harnessId")))));
38062
+ app.post("/:harnessId/profiles", async (c) => {
38063
+ const harnessId = registry2.require(c.req.param("harnessId"));
38064
+ const body = await readJsonBody(c, createProfileRequestSchema);
38065
+ return c.json(harnesses.createProfile(harnessId, body), 201);
38066
+ });
38067
+ app.patch("/:harnessId/profiles/:name", async (c) => {
38068
+ const harnessId = registry2.require(c.req.param("harnessId"));
38069
+ const name = param(c, "name");
38070
+ const body = await readJsonBody(c, updateProfileRequestSchema);
38071
+ return c.json(harnesses.updateProfile(harnessId, name, body));
38072
+ });
38073
+ app.delete("/:harnessId/profiles/:name", (c) => {
38074
+ harnesses.deleteProfile(registry2.require(c.req.param("harnessId")), param(c, "name"));
38075
+ return c.json({ ok: true });
38076
+ });
38077
+ app.get("/:harnessId/profiles/:name/preview", (c) => {
38078
+ const harnessId = registry2.require(c.req.param("harnessId"));
38079
+ return c.json({ targets: activation.preview(harnessId, param(c, "name")) });
38080
+ });
38081
+ app.get("/:harnessId/official/preview", (c) => {
38082
+ const harnessId = registry2.require(c.req.param("harnessId"));
38083
+ return c.json({ targets: activation.previewOfficial(harnessId) });
38084
+ });
38085
+ app.post("/:harnessId/profiles/:name/probe", async (c) => {
38086
+ const harnessId = registry2.require(c.req.param("harnessId"));
38087
+ const name = param(c, "name");
38088
+ const body = await readOptionalJsonBody(c, probeStoredRequestSchema);
38089
+ const decrypted = profiles.decrypt(harnessId, name);
38090
+ return c.json({
38091
+ result: await profileProbe.probe(harnessId, decrypted, body)
38092
+ });
38093
+ });
38094
+ app.post("/:harnessId/profiles/:name/activate", (c) => {
38095
+ const harnessId = registry2.require(c.req.param("harnessId"));
38096
+ const name = param(c, "name");
38097
+ const result = activation.activate(harnessId, name);
38098
+ audit.record(AUDIT_EVENTS.profileActivated, { harness: harnessId, profile: name });
38099
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
38100
+ });
38101
+ app.post("/:harnessId/official/activate", (c) => {
38102
+ const harnessId = registry2.require(c.req.param("harnessId"));
38103
+ const result = activation.activateOfficial(harnessId);
38104
+ audit.record(AUDIT_EVENTS.officialActivated, { harness: harnessId });
38105
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
38106
+ });
38107
+ return app;
37633
38108
  }
37634
38109
 
37635
38110
  // src/http/routes/model-favorites.ts
@@ -37641,6 +38116,7 @@ function createModelFavoriteRoutes(services) {
37641
38116
  const adapters = services.get(IAdapterRegistry);
37642
38117
  const profiles = services.get(IProfileService);
37643
38118
  const backups = services.get(IFavoriteBackupService);
38119
+ const environment = services.get(IEnvironmentService);
37644
38120
  app.get("/backups", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.list() }));
37645
38121
  app.post("/backups", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.create() }, 201));
37646
38122
  app.get("/backups/:backupId/preview", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.preview(param(c, "backupId")) }));
@@ -37685,7 +38161,11 @@ function createModelFavoriteRoutes(services) {
37685
38161
  });
37686
38162
  app.patch("/:id", async (c) => c.json({
37687
38163
  code: FAVORITE_CODES.result,
37688
- data: favorites.update(param(c, "id"), await readJsonBody(c, updateFavoriteRequestSchema))
38164
+ data: favorites.update(param(c, "id"), await readJsonBody(c, updateFavoriteRequestSchema), getCookie(c, environment.cookieName))
38165
+ }));
38166
+ app.post("/:id/overwrite-preview", async (c) => c.json({
38167
+ code: FAVORITE_CODES.result,
38168
+ data: apply.overwritePreview(param(c, "id"), await readJsonBody(c, overwritePreviewRequestSchema), getCookie(c, environment.cookieName))
37689
38169
  }));
37690
38170
  app.delete("/:id", async (c) => {
37691
38171
  const body = await readJsonBody(c, favoriteRevisionRequestSchema);