@seaveyon/harness-switch 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8902,6 +8902,7 @@ var PROBE_CODES = {
8902
8902
  completionHttpError: "probe.completionHttpError",
8903
8903
  completionInvalid: "probe.completionInvalid"
8904
8904
  };
8905
+ var PROBE_MODEL_LIMIT = 1000;
8905
8906
  var USER_BLOCK_CODES = {
8906
8907
  homeUnsearchable: "user.block.homeUnsearchable",
8907
8908
  homeUnwritable: "user.block.homeUnwritable",
@@ -10381,6 +10382,34 @@ var en_default = {
10381
10382
  none: "Clear",
10382
10383
  invert: "Invert"
10383
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
+ configColumn: "Configuration",
10392
+ stateColumn: "State",
10393
+ replacementColumn: "Replacement",
10394
+ inUse: "in use",
10395
+ idle: "not active",
10396
+ autoMapped: "auto-mapped (same account and model)",
10397
+ uniqueCandidate: "only compatible option, preselected",
10398
+ pickPrompt: "Choose a replacement",
10399
+ noCandidate: "No compatible channel",
10400
+ noCandidateHint: "{{profile}} has no compatible replacement. Go back to the draft and pick a channel for it.",
10401
+ templateDiff: "Template changes",
10402
+ confirm: "Confirm overwrite",
10403
+ stale: "The preview is stale or the state has changed. Refresh and try again.",
10404
+ refresh: "Refresh preview",
10405
+ collectionHint: "This configuration is managed by the tool-models flow; its field updates belong there, and for now it blocks the whole overwrite.",
10406
+ blockedTitle: "There are unresolved blockers. Nothing will be written.",
10407
+ retry: "Retry this item",
10408
+ resumeTitle: "Continue updating affected configurations",
10409
+ resumeIntro: "The configurations below are not on the current template yet. Review the diffs, then apply them one by one.",
10410
+ resumeButton: "Continue ({{count}})",
10411
+ resumeEmpty: "Nothing left to update.",
10412
+ backToDraft: "Back to draft"
10384
10413
  }
10385
10414
  },
10386
10415
  favorite: {
@@ -12040,6 +12069,34 @@ var zh_CN_default = {
12040
12069
  none: "清空",
12041
12070
  invert: "反选"
12042
12071
  }
12072
+ },
12073
+ overwrite: {
12074
+ title: "覆盖引用的配置",
12075
+ intro: "以下配置引用了将被移除的渠道。确认后将改用选定的替代渠道并保持关联本模板;差异即为最终写入内容。",
12076
+ computing: "正在计算差异…",
12077
+ affectedTitle: "受影响的配置",
12078
+ configColumn: "配置",
12079
+ stateColumn: "状态",
12080
+ replacementColumn: "替换为",
12081
+ inUse: "正在使用",
12082
+ idle: "未使用",
12083
+ autoMapped: "已自动映射(同账号同模型)",
12084
+ uniqueCandidate: "唯一兼容渠道,已预选",
12085
+ pickPrompt: "选择替代渠道",
12086
+ noCandidate: "无兼容渠道",
12087
+ noCandidateHint: "{{profile}} 没有兼容替代,请回到草稿为它补选渠道。",
12088
+ templateDiff: "模板变更",
12089
+ confirm: "确认覆盖",
12090
+ stale: "预览已过期或状态已变化,请刷新后重试。",
12091
+ refresh: "刷新预览",
12092
+ collectionHint: "该配置由工具模型托管,字段更新需走工具模型流程;本轮会阻止整单覆盖。",
12093
+ blockedTitle: "存在无法解决的阻塞项,覆盖不会写入任何内容。",
12094
+ retry: "重试该项",
12095
+ resumeTitle: "继续更新受影响的配置",
12096
+ resumeIntro: "以下配置尚未更新到当前模板。请先核对差异,再逐项应用。",
12097
+ resumeButton: "继续更新({{count}})",
12098
+ resumeEmpty: "没有待更新的配置。",
12099
+ backToDraft: "回到草稿"
12043
12100
  }
12044
12101
  },
12045
12102
  favorite: {
@@ -26760,6 +26817,16 @@ var modelFavoriteSchema = favoriteFields.extend({
26760
26817
  updatedAt: exports_external.iso.datetime()
26761
26818
  }).superRefine(validateFavorite);
26762
26819
  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);
26820
+ var overwriteRemapSchema = exports_external.object({
26821
+ harness: exports_external.enum(HARNESS_IDS),
26822
+ profile: exports_external.string().trim().min(1).max(120),
26823
+ fromConnectionId: exports_external.uuid(),
26824
+ resolution: exports_external.enum(["auto", "chosen"]),
26825
+ connectionId: exports_external.uuid(),
26826
+ overwriteDiverged: exports_external.boolean().default(false),
26827
+ ignorePreference: exports_external.boolean().default(false),
26828
+ allowAuthOverwrite: exports_external.boolean().optional()
26829
+ });
26763
26830
  var updateFavoriteRequestSchema = exports_external.object({
26764
26831
  name: favoriteFields.shape.name.optional(),
26765
26832
  notes: exports_external.string().max(4096).optional(),
@@ -26768,11 +26835,18 @@ var updateFavoriteRequestSchema = exports_external.object({
26768
26835
  connections: exports_external.array(favoriteConnectionSchema).max(50).optional(),
26769
26836
  defaultConnectionId: favoriteFields.shape.defaultConnectionId,
26770
26837
  toolBindings: favoriteFields.shape.toolBindings,
26771
- expectedRevision: exports_external.number().int().positive().optional()
26838
+ expectedRevision: exports_external.number().int().positive().optional(),
26839
+ connectionRemaps: exports_external.array(overwriteRemapSchema).max(200).optional(),
26840
+ overwriteApprovalId: exports_external.uuid().optional()
26772
26841
  });
26773
26842
  var favoriteRevisionRequestSchema = exports_external.object({
26774
26843
  expectedRevision: exports_external.number().int().positive().optional()
26775
26844
  });
26845
+ var overwritePreviewRequestSchema = exports_external.object({
26846
+ expectedRevision: exports_external.number().int().positive(),
26847
+ draft: createFavoriteRequestSchema,
26848
+ remaps: exports_external.array(overwriteRemapSchema).max(200).default([])
26849
+ });
26776
26850
  var ownedExtraSchema = exports_external.enum([
26777
26851
  "api",
26778
26852
  "providerType",
@@ -33036,6 +33110,9 @@ class VaultService {
33036
33110
  }
33037
33111
  return plain;
33038
33112
  }
33113
+ credentialsForRedaction() {
33114
+ return Object.values(this.read().entries).map((entry) => this.crypto.decrypt(entry.api_key)).filter(Boolean);
33115
+ }
33039
33116
  references(id) {
33040
33117
  const store = this.readProfileStore();
33041
33118
  const found = [];
@@ -33176,6 +33253,12 @@ class ProfileService {
33176
33253
  if (this.repairEndpointReferences(store, harness)) {
33177
33254
  this.files.writeJson(this.environment.files.profiles, store);
33178
33255
  }
33256
+ return this.project(harness, store);
33257
+ }
33258
+ peek(harness) {
33259
+ return this.project(harness, this.read());
33260
+ }
33261
+ project(harness, store) {
33179
33262
  return Object.entries(store[harness] ?? {}).map(([name, profile]) => this.toPublic(harness, name, profile));
33180
33263
  }
33181
33264
  fingerprint(harness, name) {
@@ -34131,7 +34214,6 @@ var IProbeService = createDecorator("probeService");
34131
34214
  var TIMEOUT_MS = 1e4;
34132
34215
  var COMPLETION_TIMEOUT_MS = 30000;
34133
34216
  var MAX_BODY_BYTES = 4 * 1024 * 1024;
34134
- var MAX_MODELS = 1000;
34135
34217
  var COMPLETION_PROMPT = "hi";
34136
34218
  var COMPLETION_MAX_TOKENS = 1;
34137
34219
  var COMPLETION_PROTOCOLS = [
@@ -34403,7 +34485,7 @@ function extractModels(body) {
34403
34485
  if (id && !seen.has(id)) {
34404
34486
  seen.add(id);
34405
34487
  models.push(id);
34406
- if (models.length >= MAX_MODELS) {
34488
+ if (models.length >= PROBE_MODEL_LIMIT) {
34407
34489
  break;
34408
34490
  }
34409
34491
  }
@@ -36443,10 +36525,121 @@ __decoratorMetadata(_init, HarnessService);
36443
36525
  let _HarnessService = HarnessService;
36444
36526
 
36445
36527
  // src/services/model-favorite.ts
36446
- import { createHmac, randomUUID as randomUUID5 } from "node:crypto";
36528
+ import { createHmac, randomUUID as randomUUID6 } from "node:crypto";
36447
36529
 
36448
- // src/services/tool-models.ts
36449
- import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
36530
+ // src/services/model-favorite-apply.ts
36531
+ import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
36532
+
36533
+ // src/services/model-favorite-overwrite.ts
36534
+ function resolveOverwriteRemaps({
36535
+ current,
36536
+ draft,
36537
+ refs,
36538
+ remaps
36539
+ }) {
36540
+ const problems = [];
36541
+ const affected = [];
36542
+ const resolvedRemaps = [];
36543
+ const absorbed = new Map;
36544
+ const usedExplicit = new Set(remaps.map((remap) => `${remap.harness}/${remap.profile}/${remap.fromConnectionId}`));
36545
+ for (const ref of refs) {
36546
+ if (draft.connections.some((connection) => connection.id === ref.link.connectionId)) {
36547
+ continue;
36548
+ }
36549
+ const previous = current.connections.find((connection) => connection.id === ref.link.connectionId);
36550
+ const fallback = ref.link;
36551
+ const old = {
36552
+ providerId: previous?.providerId ?? fallback.providerId ?? "",
36553
+ endpointKey: previous?.endpointKey ?? fallback.providerEndpoint ?? "",
36554
+ requestModelId: previous?.requestModelId ?? fallback.requestModelId ?? ""
36555
+ };
36556
+ const explicit = remaps.find((remap) => remap.harness === ref.harness && remap.profile === ref.name && remap.fromConnectionId === ref.link.connectionId);
36557
+ usedExplicit.delete(`${ref.harness}/${ref.name}/${ref.link.connectionId}`);
36558
+ const sameAccount = draft.connections.filter((connection) => connection.providerId === old.providerId && connection.endpointKey === old.endpointKey && connection.requestModelId === old.requestModelId);
36559
+ let target;
36560
+ let resolution = "none";
36561
+ if (explicit) {
36562
+ target = draft.connections.find((connection) => connection.id === explicit.connectionId);
36563
+ if (!target) {
36564
+ problems.push({ code: ERROR_CODES.favoriteEndpointMissing });
36565
+ continue;
36566
+ }
36567
+ if (!pickProtocolForHarness(target, ref.harness)) {
36568
+ problems.push({ code: ERROR_CODES.favoriteProtocolUnsupported });
36569
+ continue;
36570
+ }
36571
+ const isEquivalent = sameAccount.length === 1 && sameAccount[0].id === target.id;
36572
+ resolution = isEquivalent ? "auto" : "chosen";
36573
+ if (isEquivalent) {
36574
+ target = absorb(target, previous, ref.harness, absorbed);
36575
+ }
36576
+ } else if (sameAccount.length === 1) {
36577
+ target = absorb(sameAccount[0], previous, ref.harness, absorbed);
36578
+ if (!target || !pickProtocolForHarness(target, ref.harness)) {
36579
+ problems.push({ code: ERROR_CODES.favoriteProtocolUnsupported });
36580
+ continue;
36581
+ }
36582
+ resolution = "auto";
36583
+ }
36584
+ const collectionManaged = ref.link.collectionOverrides !== undefined;
36585
+ affected.push({
36586
+ harness: ref.harness,
36587
+ profile: ref.name,
36588
+ inUse: false,
36589
+ collectionManaged,
36590
+ from: {
36591
+ connectionId: ref.link.connectionId,
36592
+ providerId: old.providerId,
36593
+ endpointKey: old.endpointKey,
36594
+ requestModelId: old.requestModelId
36595
+ },
36596
+ resolution,
36597
+ ...target ? { connectionId: target.id } : {}
36598
+ });
36599
+ if (!target || resolution === "none") {
36600
+ continue;
36601
+ }
36602
+ resolvedRemaps.push({
36603
+ harness: ref.harness,
36604
+ profile: ref.name,
36605
+ fromConnectionId: ref.link.connectionId,
36606
+ resolution,
36607
+ connectionId: target.id,
36608
+ overwriteDiverged: explicit?.overwriteDiverged ?? false,
36609
+ ignorePreference: explicit?.ignorePreference ?? false,
36610
+ allowAuthOverwrite: explicit?.allowAuthOverwrite
36611
+ });
36612
+ }
36613
+ if (usedExplicit.size) {
36614
+ problems.push({ code: ERROR_CODES.favoritePlanStale });
36615
+ }
36616
+ return {
36617
+ resolved: {
36618
+ ...draft,
36619
+ connections: draft.connections.map((connection) => absorbed.get(connection.id) ?? connection)
36620
+ },
36621
+ affected,
36622
+ remaps: resolvedRemaps,
36623
+ problems
36624
+ };
36625
+ }
36626
+ function absorb(candidate, previous, harness, absorbed) {
36627
+ if (!previous) {
36628
+ return candidate;
36629
+ }
36630
+ const base = absorbed.get(candidate.id) ?? candidate;
36631
+ const missingHarnessProtocol = pickProtocolForHarness(base, harness) ? [] : [FAVORITE_PROTOCOL_SUPPORT[harness][0]];
36632
+ const merged = {
36633
+ ...base,
36634
+ ...syncConnectionProtocols([
36635
+ ...connectionProtocols(base),
36636
+ ...connectionProtocols(previous),
36637
+ ...missingHarnessProtocol
36638
+ ])
36639
+ };
36640
+ absorbed.set(merged.id, merged);
36641
+ return merged;
36642
+ }
36450
36643
 
36451
36644
  // src/services/model-favorite-preview.ts
36452
36645
  var nativeValueSchema = exports_external.json();
@@ -36493,6 +36686,7 @@ function redact(value, credentials, secret = false) {
36493
36686
  }
36494
36687
 
36495
36688
  // src/services/tool-models.ts
36689
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
36496
36690
  var stateSchema = exports_external.object({
36497
36691
  revision: exports_external.number().int().nonnegative(),
36498
36692
  draft: toolModelDraftSchema,
@@ -36680,6 +36874,58 @@ class ToolModelsService {
36680
36874
  this.files.writeJson(this.environment.files.toolModels, store);
36681
36875
  }
36682
36876
  }
36877
+ favoriteDraftItems(favoriteId) {
36878
+ const store = this.read();
36879
+ return toolModelsHarnessSchema.options.flatMap((harness) => {
36880
+ const state = store.collections[harness];
36881
+ return (state?.draft.items ?? []).filter((item) => item.source.kind === "favorite" && item.source.favoriteId === favoriteId).map((item) => ({
36882
+ harness,
36883
+ itemId: item.id,
36884
+ connectionId: item.source.kind === "favorite" ? item.source.connectionId : "",
36885
+ profile: state?.applied.find((entry) => entry.id === item.id)?.profile
36886
+ }));
36887
+ });
36888
+ }
36889
+ remapFavoriteConnectionsScoped(favoriteId, entries) {
36890
+ if (!entries.length) {
36891
+ return;
36892
+ }
36893
+ const scoped = new Map(entries.map((entry) => [`${entry.harness}/${entry.itemId}`, entry.connectionId]));
36894
+ const store = this.read();
36895
+ let changed = false;
36896
+ for (const harness of toolModelsHarnessSchema.options) {
36897
+ const state = store.collections[harness];
36898
+ if (!state) {
36899
+ continue;
36900
+ }
36901
+ let dirty = false;
36902
+ const items = state.draft.items.map((item) => {
36903
+ if (item.source.kind !== "favorite" || item.source.favoriteId !== favoriteId) {
36904
+ return item;
36905
+ }
36906
+ const nextId = scoped.get(`${harness}/${item.id}`);
36907
+ if (!nextId || nextId === item.source.connectionId) {
36908
+ return item;
36909
+ }
36910
+ dirty = true;
36911
+ return {
36912
+ ...item,
36913
+ source: { ...item.source, connectionId: nextId }
36914
+ };
36915
+ });
36916
+ if (dirty) {
36917
+ changed = true;
36918
+ store.collections[harness] = {
36919
+ ...state,
36920
+ revision: state.revision + 1,
36921
+ draft: { ...state.draft, items }
36922
+ };
36923
+ }
36924
+ }
36925
+ if (changed) {
36926
+ this.files.writeJson(this.environment.files.toolModels, store);
36927
+ }
36928
+ }
36683
36929
  apply(harness, planId, session) {
36684
36930
  const plan = this.plans.get(planId);
36685
36931
  if (!plan || plan.harness !== harness || plan.user !== this.environment.dataDir || plan.session !== session || plan.expires < Date.now()) {
@@ -36922,714 +37168,964 @@ function failure2(code) {
36922
37168
  return new HttpError(409, code, { code });
36923
37169
  }
36924
37170
 
36925
- // src/services/model-favorite.ts
36926
- var IModelFavoriteService = createDecorator("modelFavoriteService");
37171
+ // src/services/model-favorite-apply.ts
37172
+ var IModelFavoriteApplyService = createDecorator("modelFavoriteApplyService");
36927
37173
  var _dec = [
36928
- inject(IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, ILiveWriteService, IFavoriteBackupService, IToolModelsService)
37174
+ inject(IEnvironmentService, IFileService, IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, IActivationService, ILiveWriteService, IJournalService, IDriftService, IFavoriteBackupService, IToolModelsService)
36929
37175
  ];
36930
37176
  var _init = __decoratorStart(undefined);
36931
37177
 
36932
- class ModelFavoriteService {
36933
- store;
37178
+ class ModelFavoriteApplyService {
37179
+ environment;
37180
+ files;
37181
+ favorites;
36934
37182
  profiles;
36935
37183
  vault;
36936
37184
  adapters;
37185
+ activation;
36937
37186
  liveWrite;
37187
+ journal;
37188
+ drift;
36938
37189
  backups;
36939
37190
  toolModels;
36940
- sourceSalt = randomUUID5();
36941
- constructor(store, profiles, vault, adapters, liveWrite, backups, toolModels) {
36942
- this.store = store;
37191
+ plans = new Map;
37192
+ overwrites = new Map;
37193
+ constructor(environment, files, favorites, profiles, vault, adapters, activation, liveWrite, journal, drift, backups, toolModels) {
37194
+ this.environment = environment;
37195
+ this.files = files;
37196
+ this.favorites = favorites;
36943
37197
  this.profiles = profiles;
36944
37198
  this.vault = vault;
36945
37199
  this.adapters = adapters;
37200
+ this.activation = activation;
36946
37201
  this.liveWrite = liveWrite;
37202
+ this.journal = journal;
37203
+ this.drift = drift;
36947
37204
  this.backups = backups;
36948
37205
  this.toolModels = toolModels;
36949
37206
  }
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;
37207
+ state(profile) {
37208
+ const link = profile.modelFavorite;
37209
+ const favorite = link ? this.favorites.list().find((item) => item.id === link.favoriteId) : undefined;
37210
+ const connection = favorite?.connections.find((item) => item.id === link?.connectionId);
37211
+ const projected = favorite && connection ? this.adapters.get(profile.harness).projectFavorite(favorite, {
37212
+ ...connection,
37213
+ factOverrides: {
37214
+ ...connection.factOverrides,
37215
+ ...link?.collectionOverrides?.factOverrides
37216
+ },
37217
+ preferenceOverrides: {
37218
+ ...connection.preferenceOverrides,
37219
+ ...link?.collectionOverrides?.preferenceOverrides
36975
37220
  }
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;
37221
+ }, link?.baseline) : undefined;
37222
+ return {
37223
+ sourceMissing: !!link && !favorite,
37224
+ connectionMissing: !!link && !connection,
37225
+ needsUpdate: !!link && link.ignoredRevision !== favorite?.revision && !!projected && (link.projectionVersion !== projected.projectionVersion || hash3(link.baseline) !== hash3(projected.projection)),
37226
+ diverged: !!link && (profile.overriddenTargets.length > 0 || hash3(snapshot(profile, link.baseline)) !== hash3(link.baseline))
36987
37227
  };
36988
- for (const ref of this.references(id)) {
36989
- if (next.connections.some((connection) => connection.id === ref.link.connectionId)) {
36990
- continue;
37228
+ }
37229
+ plan(request, session) {
37230
+ const favorite = this.favorites.get(request.favoriteId);
37231
+ if (favorite.revision !== request.expectedRevision) {
37232
+ throw failure3(ERROR_CODES.favoriteRevisionConflict);
37233
+ }
37234
+ for (const [id, value] of this.plans) {
37235
+ if (Date.parse(value.public.expiresAt) < Date.now()) {
37236
+ this.plans.delete(id);
36991
37237
  }
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
37238
+ }
37239
+ if (this.plans.size >= 1000) {
37240
+ throw failure3(ERROR_CODES.favoriteLimitReached);
37241
+ }
37242
+ const items = request.items.toSorted((a, b) => HARNESS_IDS.indexOf(a.harness) - HARNESS_IDS.indexOf(b.harness)).map((selection) => {
37243
+ const computed = this.computeItem(favorite, selection);
37244
+ return {
37245
+ ...computed,
37246
+ writes: computed.writes,
37247
+ fingerprint: this.fingerprint(favorite.id, computed.public)
36999
37248
  };
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 });
37249
+ });
37250
+ const plan = {
37251
+ id: randomUUID5(),
37252
+ expiresAt: new Date(Date.now() + 600000).toISOString(),
37253
+ favoriteRevision: favorite.revision,
37254
+ items: items.map((item) => item.public)
37255
+ };
37256
+ this.plans.set(plan.id, {
37257
+ public: plan,
37258
+ items,
37259
+ user: this.environment.dataDir,
37260
+ session,
37261
+ favoriteId: favorite.id
37262
+ });
37263
+ return plan;
37264
+ }
37265
+ computeItem(favorite, selection) {
37266
+ const connection = favorite.connections.find((item2) => item2.id === selection.connectionId);
37267
+ if (!connection) {
37268
+ throw failure3(ERROR_CODES.favoriteEndpointMissing);
37007
37269
  }
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;
37270
+ const provider = this.vault.get(connection.providerId);
37271
+ const endpoint = provider.endpoints.find((item2) => item2.key === connection.endpointKey);
37272
+ if (!endpoint) {
37273
+ throw failure3(ERROR_CODES.favoriteEndpointMissing);
37274
+ }
37275
+ const adapter = this.adapters.get(selection.harness);
37276
+ let name = selection.profile ?? favorite.name.replace(/[\\/]/g, "-");
37277
+ if (!selection.existing && !selection.profile) {
37278
+ let suffix = 2;
37279
+ const base = name;
37280
+ while (this.profiles.get(selection.harness, name)) {
37281
+ name = `${base.slice(0, 110)}-${suffix++}`;
37012
37282
  }
37013
- if (connectionRemaps.has(previous.id)) {
37014
- continue;
37283
+ }
37284
+ const prior = this.profiles.get(selection.harness, name);
37285
+ if (prior?.modelFavorite?.collectionOverrides) {
37286
+ throw failure3(ERROR_CODES.toolModelsConflict);
37287
+ }
37288
+ if (selection.existing ? prior?.modelFavorite?.favoriteId !== favorite.id : !!prior) {
37289
+ throw failure3(ERROR_CODES.favoriteInUse);
37290
+ }
37291
+ if (prior?.overriddenTargets.length) {
37292
+ throw failure3(ERROR_CODES.favoriteRawOverrideConflict);
37293
+ }
37294
+ const projection = adapter.projectFavorite(favorite, connection, prior?.modelFavorite?.baseline);
37295
+ if (prior && this.state(prior).diverged && !selection.overwriteDiverged) {
37296
+ projection.blockers.push({ code: ERROR_CODES.favoriteProfileDiverged });
37297
+ }
37298
+ if (projection.notRepresented.includes("reasoningEffort") && !selection.ignorePreference) {
37299
+ projection.blockers.push({ code: ERROR_CODES.favoritePreferenceNotRepresented });
37300
+ }
37301
+ const extras = { ...prior?.extras };
37302
+ if (!prior && ["pi", "dsh", "codex", "kimi"].includes(selection.harness)) {
37303
+ extras.providerId = `hsw-mf-${randomUUID5()}`;
37304
+ }
37305
+ for (const [key, value] of Object.entries(projection.projection.extras)) {
37306
+ if (value === null) {
37307
+ delete extras[key];
37308
+ } else {
37309
+ extras[key] = value;
37015
37310
  }
37016
- const merged = absorbRemoved(previous);
37017
- if (merged) {
37018
- connectionRemaps.set(previous.id, merged.id);
37311
+ }
37312
+ for (const key of Object.keys(projection.rendererDefaults)) {
37313
+ if (extras[key]) {
37314
+ delete projection.rendererDefaults[key];
37019
37315
  }
37020
37316
  }
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
- }
37317
+ const profile = {
37318
+ favoriteManaged: true,
37319
+ name,
37320
+ model: connection.requestModelId,
37321
+ extras,
37322
+ baseUrl: endpoint.baseUrl,
37323
+ apiKey: this.vault.decrypt(provider.id)
37324
+ };
37325
+ adapter.validate?.(profile);
37326
+ const input = {
37327
+ name,
37328
+ model: profile.model,
37329
+ extras,
37330
+ baseUrl: profile.baseUrl,
37331
+ providerId: provider.id,
37332
+ providerEndpoint: endpoint.key
37333
+ };
37334
+ const diff = projection.ownedFields.flatMap((field) => {
37335
+ const before = field.startsWith("extras.") ? prior?.extras[field.slice(7)] ?? null : field === "model" ? prior?.model ?? null : field === "providerId" ? prior?.providerId ?? null : prior?.providerEndpoint ?? null;
37336
+ const after = projection.set[field] ?? null;
37337
+ return before === after ? [] : [{ field, before, after }];
37338
+ });
37339
+ if (selection.mode === "save" && this.activation.getActive(selection.harness)?.name === name && (diff.length || prior?.baseUrl !== endpoint.baseUrl)) {
37340
+ projection.blockers.push({ code: ERROR_CODES.favoriteActiveUpdateRequiresApply });
37341
+ }
37342
+ if (selection.mode === "activate" && selection.harness === "codex" && extras.authMode === "openai_auth" && selection.allowAuthOverwrite !== true) {
37343
+ projection.blockers.push({ code: ERROR_CODES.favoriteProjectionUnsupported });
37344
+ }
37345
+ const current = Object.fromEntries(adapter.targets().map((target) => [target.key, this.files.readOptional(target.path)]));
37346
+ if (!prior && extras.providerId && Object.values(current).some((content) => content?.includes(extras.providerId))) {
37347
+ projection.blockers.push({ code: ERROR_CODES.favoriteInUse });
37348
+ }
37349
+ let writes = [];
37350
+ if (selection.mode === "activate" && projection.blockers.length === 0) {
37351
+ try {
37352
+ writes = this.activation.prepareFavorite(selection.harness, profile);
37353
+ } catch (error52) {
37354
+ projection.blockers.push({
37355
+ code: error52 instanceof HttpError ? error52.code : ERROR_CODES.nativeConfigInvalid
37356
+ });
37034
37357
  }
37035
37358
  }
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
- });
37359
+ const redactKeys = writes.length ? [profile.apiKey, ...this.vault.credentialsForRedaction()] : [];
37360
+ const item = {
37361
+ preservedFields: Object.keys(prior?.extras ?? {}).filter((key) => !Object.hasOwn(projection.projection.extras, key)),
37362
+ authMode: extras.authMode ?? extras.authVar ?? adapter.fields.find((field) => field.key === "authMode" || field.key === "authVar")?.defaultValue ?? "apiKey",
37363
+ liveState: "unknown",
37364
+ ...selection,
37365
+ profile: name,
37366
+ projection,
37367
+ resolved: resolveFavorite(favorite, connection),
37368
+ diff,
37369
+ nativeFiles: writes.map((write) => ({
37370
+ key: write.key,
37371
+ changed: current[write.key] !== write.content,
37372
+ before: favoriteNativePreview(write.format, current[write.key], redactKeys, write.key === "credentials"),
37373
+ after: favoriteNativePreview(write.format, write.content, redactKeys, write.key === "credentials")
37374
+ }))
37375
+ };
37376
+ return {
37377
+ public: item,
37378
+ input,
37379
+ profile,
37380
+ writes,
37381
+ link: {
37382
+ favoriteId: favorite.id,
37383
+ connectionId: connection.id,
37384
+ appliedRevision: favorite.revision,
37385
+ projectionVersion: projection.projectionVersion,
37386
+ baseline: projection.projection
37049
37387
  }
37050
- this.toolModels.remapFavoriteConnections(id, connectionRemaps);
37051
- return updated;
37052
- }), { action: "update", name: current.name });
37388
+ };
37053
37389
  }
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 });
37390
+ overwritePreview(favoriteId, request, session) {
37391
+ const favorite = this.favorites.get(favoriteId);
37392
+ if (favorite.revision !== request.expectedRevision) {
37393
+ throw failure3(ERROR_CODES.favoriteRevisionConflict);
37058
37394
  }
37059
- this.backups.protect("change", () => this.store.remove(id, revision), {
37060
- action: "delete",
37061
- name: this.store.get(id).name
37395
+ const resolution = resolveOverwriteRemaps({
37396
+ current: favorite,
37397
+ draft: request.draft,
37398
+ refs: this.linkedReferences(favoriteId),
37399
+ remaps: request.remaps
37062
37400
  });
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 });
37401
+ if (resolution.problems.length) {
37402
+ throw failure3(resolution.problems[0].code);
37403
+ }
37404
+ const resolved = createFavoriteRequestSchema.parse(resolution.resolved);
37405
+ const synthesized = {
37406
+ ...resolved,
37407
+ id: favorite.id,
37408
+ revision: favorite.revision,
37409
+ createdAt: favorite.createdAt,
37410
+ updatedAt: favorite.updatedAt
37411
+ };
37412
+ const affected = resolution.affected.map((row) => ({
37413
+ ...row,
37414
+ inUse: this.activation.getActive(row.harness)?.name === row.profile
37415
+ }));
37416
+ const blockers = [];
37417
+ for (const row of affected) {
37418
+ if (row.collectionManaged && row.inUse) {
37419
+ blockers.push({ code: ERROR_CODES.toolModelsConflict });
37420
+ }
37421
+ if (!row.connectionId) {
37422
+ blockers.push({ code: ERROR_CODES.favoriteConnectionInUse });
37423
+ }
37068
37424
  }
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
37425
+ const toolModelEntries = this.resolveToolModelRemaps(synthesized, affected, blockers);
37426
+ const items = [];
37427
+ for (const remap of resolution.remaps) {
37428
+ const row = affected.find((entry) => entry.harness === remap.harness && entry.profile === remap.profile);
37429
+ if (!row || row.collectionManaged || !row.connectionId) {
37430
+ continue;
37431
+ }
37432
+ const computed = this.computeItem(synthesized, {
37433
+ harness: remap.harness,
37434
+ connectionId: remap.connectionId,
37435
+ profile: remap.profile,
37436
+ existing: true,
37437
+ mode: row.inUse ? "activate" : "save",
37438
+ overwriteDiverged: remap.overwriteDiverged,
37439
+ ignorePreference: remap.ignorePreference,
37440
+ allowAuthOverwrite: remap.allowAuthOverwrite
37075
37441
  });
37076
- }
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
37442
+ items.push({
37443
+ public: computed.public,
37444
+ fingerprint: this.fingerprintOf(synthesized, computed.public)
37081
37445
  });
37082
37446
  }
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
- });
37447
+ for (const [id, record2] of this.overwrites) {
37448
+ if (record2.expiresAt < Date.now()) {
37449
+ this.overwrites.delete(id);
37450
+ }
37090
37451
  }
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
- });
37452
+ if (this.overwrites.size >= 1000) {
37453
+ throw failure3(ERROR_CODES.favoriteLimitReached);
37454
+ }
37455
+ const preview = {
37456
+ id: randomUUID5(),
37457
+ expiresAt: new Date(Date.now() + 600000).toISOString(),
37458
+ favoriteRevision: favorite.revision,
37459
+ resolvedFavorite: synthesized,
37460
+ affected,
37461
+ items: items.map((item) => item.public),
37462
+ blockers
37463
+ };
37464
+ this.overwrites.set(preview.id, {
37465
+ id: preview.id,
37466
+ expiresAt: Date.parse(preview.expiresAt),
37467
+ session,
37468
+ user: this.environment.dataDir,
37469
+ favoriteId,
37470
+ expectedRevision: favorite.revision,
37471
+ resolved: synthesized,
37472
+ remaps: resolution.remaps,
37473
+ affected,
37474
+ blockers,
37475
+ toolModelEntries,
37476
+ toolModelsHash: this.toolModelsStateHash(),
37477
+ items
37478
+ });
37479
+ return preview;
37480
+ }
37481
+ prepareOverwriteCommit(params) {
37482
+ const record2 = this.overwrites.get(params.approvalId);
37483
+ if (!record2 || record2.expiresAt < Date.now() || record2.user !== this.environment.dataDir || record2.session !== params.session || record2.favoriteId !== params.favoriteId) {
37484
+ throw failure3(ERROR_CODES.favoritePlanExpired);
37485
+ }
37486
+ if (record2.expectedRevision !== params.expectedRevision) {
37487
+ throw failure3(ERROR_CODES.favoritePlanStale);
37488
+ }
37489
+ if (!params.remaps) {
37490
+ throw failure3(ERROR_CODES.favoritePlanStale);
37491
+ }
37492
+ if (record2.blockers.length) {
37493
+ throw failure3(record2.blockers[0].code);
37494
+ }
37495
+ const resolution = resolveOverwriteRemaps({
37496
+ current: this.favorites.get(params.favoriteId),
37497
+ draft: params.next,
37498
+ refs: this.linkedReferences(params.favoriteId),
37499
+ remaps: params.remaps
37500
+ });
37501
+ const stale = resolution.problems.length || canon(resolution.affected.map((row) => ({
37502
+ ...row,
37503
+ inUse: this.activation.getActive(row.harness)?.name === row.profile
37504
+ }))) !== canon(record2.affected) || canon(resolution.remaps) !== canon(record2.remaps) || canon(createFavoriteRequestSchema.parse(resolution.resolved)) !== canon(createFavoriteRequestSchema.parse(record2.resolved));
37505
+ if (stale) {
37506
+ throw failure3(ERROR_CODES.favoritePlanStale);
37507
+ }
37508
+ for (const item of record2.items) {
37509
+ if (item.public.projection.blockers.length) {
37510
+ throw failure3(item.public.projection.blockers[0].code);
37511
+ }
37512
+ if (item.fingerprint !== this.fingerprintOf(record2.resolved, item.public)) {
37513
+ throw failure3(ERROR_CODES.favoritePlanStale);
37108
37514
  }
37109
- if (!source.providerId || !source.providerEndpoint) {
37110
- this.profiles.upsert(input.harness, { name: input.name, providerId: provider.id, providerEndpoint: endpointKey }, false);
37515
+ }
37516
+ if (this.toolModelsStateHash() !== record2.toolModelsHash) {
37517
+ throw failure3(ERROR_CODES.favoritePlanStale);
37518
+ }
37519
+ return {
37520
+ resolved: record2.resolved,
37521
+ remaps: record2.remaps,
37522
+ toolModelEntries: record2.toolModelEntries
37523
+ };
37524
+ }
37525
+ consumeOverwrite(approvalId) {
37526
+ this.overwrites.delete(approvalId);
37527
+ }
37528
+ resolveToolModelRemaps(resolved, affected, problems) {
37529
+ const entries = [];
37530
+ const identities = new Map;
37531
+ for (const draft of this.toolModels.favoriteDraftItems(resolved.id)) {
37532
+ if (resolved.connections.some((connection) => connection.id === draft.connectionId)) {
37533
+ continue;
37111
37534
  }
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
- });
37535
+ const row = affected.find((entry) => entry.harness === draft.harness && entry.profile === draft.profile);
37536
+ const target = row?.connectionId ? resolved.connections.find((connection) => connection.id === row.connectionId) : undefined;
37537
+ if (!row?.connectionId || !target) {
37538
+ problems.push({ code: ERROR_CODES.toolModelsConflict });
37539
+ continue;
37151
37540
  }
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
- });
37541
+ const protocol = pickProtocolForHarness(target, draft.harness);
37542
+ if (!protocol) {
37543
+ problems.push({ code: ERROR_CODES.favoriteProtocolUnsupported });
37544
+ continue;
37545
+ }
37546
+ const identity2 = `${target.providerId}/${target.endpointKey}/${protocol}/${target.requestModelId}`;
37547
+ const seen = identities.get(draft.harness) ?? new Set;
37548
+ if (seen.has(identity2)) {
37549
+ problems.push({ code: ERROR_CODES.toolModelsConflict });
37550
+ continue;
37551
+ }
37552
+ seen.add(identity2);
37553
+ identities.set(draft.harness, seen);
37554
+ entries.push({ harness: draft.harness, itemId: draft.itemId, connectionId: target.id });
37160
37555
  }
37161
- this.backups.protect("change", () => this.profiles.setFavoriteLink(harness, name, undefined), {
37162
- action: "detach",
37163
- name,
37164
- tools: [harness]
37165
- });
37556
+ return entries;
37166
37557
  }
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
- });
37558
+ toolModelsStateHash() {
37559
+ return hash3(this.files.readOptional(this.environment.files.toolModels) ?? null);
37560
+ }
37561
+ linkedReferences(favoriteId) {
37562
+ return HARNESS_IDS.flatMap((harness) => this.profiles.peek(harness).flatMap((profile) => profile.modelFavorite?.favoriteId === favoriteId ? [
37563
+ {
37564
+ harness,
37565
+ name: profile.name,
37566
+ link: {
37567
+ connectionId: profile.modelFavorite.connectionId,
37568
+ collectionOverrides: profile.modelFavorite.collectionOverrides
37569
+ }
37570
+ }
37571
+ ] : []));
37572
+ }
37573
+ operation(requestId) {
37574
+ const receipts = this.journal.list().filter((receipt) => receipt.favoriteRequest?.requestId === requestId).toSorted((a, b) => a.favoriteRequest.item - b.favoriteRequest.item);
37575
+ return {
37576
+ requestId,
37577
+ items: [
37578
+ ...receipts.map((receipt) => ({
37579
+ harness: receipt.harness,
37580
+ profile: receipt.profile,
37581
+ operationId: receipt.id,
37582
+ code: receipt.favoriteResult?.code,
37583
+ status: receipt.state === "committed" || receipt.state === "metadata-committed" ? receipt.favoriteResult?.status ?? "applied" : receipt.state === "rolled-back" || receipt.state === "degraded" ? "failed" : "skipped"
37584
+ })),
37585
+ ...(receipts[0]?.favoriteRequest?.targets ?? []).filter((target) => !receipts.some((receipt) => receipt.harness === target.harness)).map((target) => ({
37586
+ ...target,
37587
+ status: "skipped",
37588
+ code: ERROR_CODES.favoritePlanExpired
37589
+ }))
37590
+ ]
37591
+ };
37592
+ }
37593
+ apply(id, requestId, session) {
37594
+ const receipts = this.journal.list().filter((receipt) => receipt.favoriteRequest?.requestId === requestId);
37595
+ if (receipts.length) {
37596
+ if (receipts.some((receipt) => receipt.favoriteRequest?.planId !== id)) {
37597
+ throw failure3(ERROR_CODES.favoriteIdempotencyConflict);
37598
+ }
37599
+ return this.operation(requestId);
37173
37600
  }
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
- });
37601
+ const plan = this.plans.get(id);
37602
+ if (!plan || plan.user !== this.environment.dataDir || plan.session !== session || Date.parse(plan.public.expiresAt) < Date.now()) {
37603
+ throw failure3(ERROR_CODES.favoritePlanExpired);
37604
+ }
37605
+ for (const prepared of plan.items) {
37606
+ if (!this.matchesFingerprint(plan.favoriteId, prepared)) {
37607
+ throw failure3(ERROR_CODES.favoritePlanStale);
37608
+ }
37609
+ if (prepared.public.projection.blockers.length) {
37610
+ throw failure3(prepared.public.projection.blockers[0].code);
37180
37611
  }
37612
+ }
37613
+ this.backups.create("apply", {
37614
+ action: "apply",
37615
+ name: this.favorites.get(plan.favoriteId).name,
37616
+ tools: plan.items.map((item) => item.public.harness)
37181
37617
  });
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
37618
+ const result = { requestId, items: [] };
37619
+ for (const [index, prepared] of plan.items.entries()) {
37620
+ const item = prepared.public;
37621
+ if (!this.matchesFingerprint(plan.favoriteId, prepared)) {
37622
+ throw failure3(ERROR_CODES.favoritePlanStale);
37623
+ }
37624
+ if (item.projection.blockers.length) {
37625
+ throw failure3(item.projection.blockers[0].code);
37626
+ }
37627
+ 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));
37628
+ try {
37629
+ this.liveWrite.transaction({
37630
+ kind: "favorite-apply",
37631
+ harness: item.harness,
37632
+ profile: item.profile,
37633
+ writes: unchanged ? [] : prepared.writes,
37634
+ metadata: item.mode === "activate" && !unchanged ? ["profiles", "active"] : ["profiles"],
37635
+ favoriteRequest: {
37636
+ version: 1,
37637
+ requestId,
37638
+ planId: id,
37639
+ item: index,
37640
+ approvalHash: hash3(plan.public),
37641
+ targets: plan.items.map((entry) => ({
37642
+ harness: entry.public.harness,
37643
+ profile: entry.public.profile
37644
+ }))
37645
+ },
37646
+ favoriteResult: { status: unchanged ? "unchanged" : "applied" },
37647
+ beforeWrites: item.mode === "activate" && !unchanged ? () => this.activation.commitFavorite(item.harness, prepared.profile) : undefined
37648
+ }, () => {
37649
+ if (unchanged) {
37650
+ this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37651
+ return;
37652
+ }
37653
+ if (item.existing) {
37654
+ this.profiles.setFavoriteLink(item.harness, item.profile, undefined);
37655
+ }
37656
+ this.profiles.upsert(item.harness, prepared.input, !item.existing);
37657
+ this.profiles.setFavoriteLink(item.harness, item.profile, prepared.link);
37189
37658
  });
37659
+ if (item.mode === "activate" && !unchanged) {
37660
+ try {
37661
+ this.activation.refreshEnv();
37662
+ } catch {
37663
+ const receipt = this.journal.list().find((entry) => entry.favoriteRequest?.requestId === requestId && entry.favoriteRequest.item === index);
37664
+ if (receipt) {
37665
+ this.journal.setFavoriteResult(receipt.id, {
37666
+ status: unchanged ? "unchanged" : "applied",
37667
+ code: WARNING_CODES.envRebuildFailed
37668
+ });
37669
+ }
37670
+ }
37671
+ }
37672
+ } catch (error52) {
37673
+ result.items.push({
37674
+ harness: item.harness,
37675
+ profile: item.profile,
37676
+ status: "failed",
37677
+ code: error52 instanceof HttpError ? error52.code : ERROR_CODES.requestFailed
37678
+ });
37679
+ 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)) {
37680
+ break;
37681
+ }
37190
37682
  }
37191
37683
  }
37684
+ this.plans.delete(id);
37685
+ return {
37686
+ requestId,
37687
+ items: [
37688
+ ...this.operation(requestId).items,
37689
+ ...result.items.filter((item) => !this.operation(requestId).items.some((saved) => saved.harness === item.harness))
37690
+ ]
37691
+ };
37692
+ }
37693
+ matchesFingerprint(favoriteId, prepared) {
37694
+ try {
37695
+ return prepared.fingerprint === this.fingerprint(favoriteId, prepared.public);
37696
+ } catch {
37697
+ return false;
37698
+ }
37699
+ }
37700
+ fingerprint(favoriteId, item) {
37701
+ return this.fingerprintOf(this.favorites.get(favoriteId), item);
37702
+ }
37703
+ fingerprintOf(favorite, item) {
37704
+ const connection = favorite.connections.find((entry) => entry.id === item.connectionId);
37705
+ return hash3({
37706
+ favorite,
37707
+ profile: this.profiles.fingerprint(item.harness, item.profile),
37708
+ credential: connection ? this.vault.decrypt(connection.providerId) : null,
37709
+ provider: connection ? this.vault.get(connection.providerId) : null,
37710
+ active: this.activation.fingerprint(item.harness),
37711
+ files: this.adapters.get(item.harness).targets().map((target) => [target.key, this.files.readOptional(target.path)])
37712
+ });
37192
37713
  }
37193
37714
  }
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);
37715
+ ModelFavoriteApplyService = __decorateElement(_init, 0, "ModelFavoriteApplyService", _dec, ModelFavoriteApplyService);
37716
+ __runInitializers(_init, 1, ModelFavoriteApplyService);
37717
+ __decoratorMetadata(_init, ModelFavoriteApplyService);
37718
+ let _ModelFavoriteApplyService = ModelFavoriteApplyService;
37719
+ function canon(value) {
37720
+ if (Array.isArray(value)) {
37721
+ return `[${value.map(canon).join(",")}]`;
37722
+ }
37723
+ if (value && typeof value === "object") {
37724
+ return `{${Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : 1).map(([key, entry]) => `${JSON.stringify(key)}:${canon(entry)}`).join(",")}}`;
37725
+ }
37726
+ return JSON.stringify(value) ?? "null";
37200
37727
  }
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;
37728
+ function hash3(value) {
37729
+ return createHash9("sha256").update(JSON.stringify(value)).digest("hex");
37730
+ }
37731
+ function failure3(code) {
37732
+ return new HttpError(409, code, { code });
37733
+ }
37734
+ function snapshot(profile, baseline) {
37735
+ return {
37736
+ harness: profile.harness,
37737
+ model: profile.model,
37738
+ providerId: profile.providerId ?? "",
37739
+ providerEndpoint: profile.providerEndpoint ?? "",
37740
+ extras: Object.fromEntries(Object.keys(baseline.extras).map((key) => [key, profile.extras[key] ?? null]))
37741
+ };
37264
37742
  }
37265
37743
 
37266
- // src/services/model-favorite-apply.ts
37267
- import { createHash as createHash9, randomUUID as randomUUID6 } from "node:crypto";
37268
- var IModelFavoriteApplyService = createDecorator("modelFavoriteApplyService");
37744
+ // src/services/model-favorite.ts
37745
+ var IModelFavoriteService = createDecorator("modelFavoriteService");
37269
37746
  var _dec = [
37270
- inject(IEnvironmentService, IFileService, IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, IActivationService, ILiveWriteService, IJournalService, IDriftService, IFavoriteBackupService)
37747
+ inject(IModelFavoriteStore, IProfileService, IVaultService, IAdapterRegistry, ILiveWriteService, IFavoriteBackupService, IToolModelsService, IModelFavoriteApplyService)
37271
37748
  ];
37272
37749
  var _init = __decoratorStart(undefined);
37273
37750
 
37274
- class ModelFavoriteApplyService {
37275
- environment;
37276
- files;
37277
- favorites;
37751
+ class ModelFavoriteService {
37752
+ store;
37278
37753
  profiles;
37279
37754
  vault;
37280
37755
  adapters;
37281
- activation;
37282
37756
  liveWrite;
37283
- journal;
37284
- drift;
37285
37757
  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;
37758
+ toolModels;
37759
+ apply;
37760
+ sourceSalt = randomUUID6();
37761
+ constructor(store, profiles, vault, adapters, liveWrite, backups, toolModels, apply) {
37762
+ this.store = store;
37291
37763
  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
37313
- }
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))
37320
- };
37764
+ this.vault = vault;
37765
+ this.adapters = adapters;
37766
+ this.liveWrite = liveWrite;
37767
+ this.backups = backups;
37768
+ this.toolModels = toolModels;
37769
+ this.apply = apply;
37321
37770
  }
37322
- plan(request, session) {
37323
- const favorite = this.favorites.get(request.favoriteId);
37324
- if (favorite.revision !== request.expectedRevision) {
37325
- throw failure3(ERROR_CODES.favoriteRevisionConflict);
37326
- }
37327
- for (const [id, value] of this.plans) {
37328
- if (Date.parse(value.public.expiresAt) < Date.now()) {
37329
- this.plans.delete(id);
37330
- }
37331
- }
37332
- if (this.plans.size >= 1000) {
37333
- throw failure3(ERROR_CODES.favoriteLimitReached);
37771
+ list() {
37772
+ return this.store.list().map((favorite) => ({ ...favorite, references: this.references(favorite.id) }));
37773
+ }
37774
+ references(id) {
37775
+ return HARNESS_IDS.flatMap((harness) => this.profiles.list(harness).flatMap((profile) => profile.modelFavorite?.favoriteId === id ? [{ harness, name: profile.name, link: profile.modelFavorite }] : []));
37776
+ }
37777
+ create(input) {
37778
+ const parsed = createFavoriteRequestSchema.parse(input);
37779
+ this.validateConnections(parsed);
37780
+ return this.backups.protect("change", () => this.store.create(parsed), {
37781
+ action: "create",
37782
+ name: parsed.name
37783
+ });
37784
+ }
37785
+ update(id, input, session) {
37786
+ this.store.assertRevision(id, input.expectedRevision);
37787
+ const current = this.store.get(id);
37788
+ let next = createFavoriteRequestSchema.parse({ ...current, ...input });
37789
+ this.validateConnections(next);
37790
+ if (input.overwriteApprovalId || input.connectionRemaps?.length) {
37791
+ return this.updateOverwrite(id, current, next, input, session);
37334
37792
  }
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);
37793
+ const remaps = [];
37794
+ const absorbed = new Map;
37795
+ const absorbRemoved = (previous, harness) => {
37796
+ const survivor = sameAccountModel(previous, next.connections);
37797
+ if (!survivor) {
37798
+ return;
37357
37799
  }
37358
- if (selection.existing ? prior?.modelFavorite?.favoriteId !== favorite.id : !!prior) {
37359
- throw failure3(ERROR_CODES.favoriteInUse);
37800
+ const base = absorbed.get(survivor.id) ?? survivor;
37801
+ const merged = {
37802
+ ...base,
37803
+ ...syncConnectionProtocols([
37804
+ ...connectionProtocols(base),
37805
+ ...connectionProtocols(previous),
37806
+ ...harness && !pickProtocolForHarness(base, harness) ? [FAVORITE_PROTOCOL_SUPPORT[harness][0]] : []
37807
+ ])
37808
+ };
37809
+ absorbed.set(merged.id, merged);
37810
+ return merged;
37811
+ };
37812
+ for (const ref of this.references(id)) {
37813
+ if (next.connections.some((connection) => connection.id === ref.link.connectionId)) {
37814
+ continue;
37360
37815
  }
37361
- if (prior?.overriddenTargets.length) {
37362
- throw failure3(ERROR_CODES.favoriteRawOverrideConflict);
37816
+ const previous = current.connections.find((connection) => connection.id === ref.link.connectionId);
37817
+ const target = previous ?? {
37818
+ providerId: ref.link.baseline.providerId,
37819
+ endpointKey: ref.link.baseline.providerEndpoint,
37820
+ requestModelId: ref.link.baseline.model,
37821
+ protocol: undefined,
37822
+ protocols: undefined
37823
+ };
37824
+ const merged = absorbRemoved(target, ref.harness);
37825
+ if (!merged || !pickProtocolForHarness(merged, ref.harness)) {
37826
+ throw new HttpError(409, ERROR_CODES.favoriteConnectionInUse, {
37827
+ code: ERROR_CODES.favoriteConnectionInUse
37828
+ });
37363
37829
  }
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 });
37830
+ remaps.push({ ref, connectionId: merged.id });
37831
+ }
37832
+ const connectionRemaps = new Map(remaps.map(({ ref, connectionId }) => [ref.link.connectionId, connectionId]));
37833
+ for (const previous of current.connections) {
37834
+ if (next.connections.some((connection) => connection.id === previous.id)) {
37835
+ continue;
37367
37836
  }
37368
- if (projection.notRepresented.includes("reasoningEffort") && !selection.ignorePreference) {
37369
- projection.blockers.push({ code: ERROR_CODES.favoritePreferenceNotRepresented });
37837
+ if (connectionRemaps.has(previous.id)) {
37838
+ continue;
37370
37839
  }
37371
- const extras = { ...prior?.extras };
37372
- if (!prior && ["pi", "dsh", "codex", "kimi"].includes(selection.harness)) {
37373
- extras.providerId = `hsw-mf-${randomUUID6()}`;
37840
+ const merged = absorbRemoved(previous);
37841
+ if (merged) {
37842
+ connectionRemaps.set(previous.id, merged.id);
37374
37843
  }
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;
37844
+ }
37845
+ if (absorbed.size) {
37846
+ next = createFavoriteRequestSchema.parse({
37847
+ ...next,
37848
+ connections: next.connections.map((connection) => absorbed.get(connection.id) ?? connection)
37849
+ });
37850
+ this.validateConnections(next);
37851
+ for (const { ref, connectionId } of remaps) {
37852
+ const connection = next.connections.find((entry) => entry.id === connectionId);
37853
+ if (!connection || !pickProtocolForHarness(connection, ref.harness)) {
37854
+ throw new HttpError(409, ERROR_CODES.favoriteConnectionInUse, {
37855
+ code: ERROR_CODES.favoriteConnectionInUse
37856
+ });
37380
37857
  }
37381
37858
  }
37382
- for (const key of Object.keys(projection.rendererDefaults)) {
37383
- if (extras[key]) {
37384
- delete projection.rendererDefaults[key];
37385
- }
37859
+ }
37860
+ return this.backups.protect("change", () => this.liveWrite.transaction({
37861
+ kind: "favorite-apply",
37862
+ harness: remaps[0]?.ref.harness ?? "claude",
37863
+ profile: current.name,
37864
+ writes: [],
37865
+ metadata: connectionRemaps.size ? ["favorites", "profiles", "toolModels"] : ["favorites"]
37866
+ }, () => {
37867
+ const updated = this.store.update(id, next, input.expectedRevision);
37868
+ for (const { ref, connectionId } of remaps) {
37869
+ this.profiles.setFavoriteLink(ref.harness, ref.name, {
37870
+ ...ref.link,
37871
+ connectionId
37872
+ });
37386
37873
  }
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 }];
37874
+ this.toolModels.remapFavoriteConnections(id, connectionRemaps);
37875
+ return updated;
37876
+ }), { action: "update", name: current.name });
37877
+ }
37878
+ remove(id, revision) {
37879
+ this.store.assertRevision(id, revision);
37880
+ if (this.references(id).length) {
37881
+ throw new HttpError(409, ERROR_CODES.favoriteInUse, { code: ERROR_CODES.favoriteInUse });
37882
+ }
37883
+ this.backups.protect("change", () => this.store.remove(id, revision), {
37884
+ action: "delete",
37885
+ name: this.store.get(id).name
37886
+ });
37887
+ }
37888
+ updateOverwrite(id, current, next, input, session) {
37889
+ if (!session || !input.overwriteApprovalId) {
37890
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37891
+ code: ERROR_CODES.favoritePlanStale
37408
37892
  });
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 });
37411
- }
37412
- if (selection.mode === "activate" && selection.harness === "codex" && extras.authMode === "openai_auth" && selection.allowAuthOverwrite !== true) {
37413
- projection.blockers.push({ code: ERROR_CODES.favoriteProjectionUnsupported });
37414
- }
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 });
37418
- }
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
37893
+ }
37894
+ const prepared = this.apply.prepareOverwriteCommit({
37895
+ approvalId: input.overwriteApprovalId,
37896
+ remaps: input.connectionRemaps,
37897
+ favoriteId: id,
37898
+ expectedRevision: input.expectedRevision,
37899
+ next,
37900
+ session
37901
+ });
37902
+ const updated = this.backups.protect("change", () => this.liveWrite.transaction({
37903
+ kind: "favorite-apply",
37904
+ harness: prepared.remaps[0]?.harness ?? "claude",
37905
+ profile: current.name,
37906
+ writes: [],
37907
+ metadata: [
37908
+ "favorites",
37909
+ "profiles",
37910
+ ...prepared.toolModelEntries.length ? ["toolModels"] : []
37911
+ ]
37912
+ }, () => {
37913
+ const saved = this.store.update(id, prepared.resolved, input.expectedRevision);
37914
+ for (const remap of prepared.remaps) {
37915
+ const link = this.profiles.get(remap.harness, remap.profile)?.modelFavorite;
37916
+ if (link) {
37917
+ this.profiles.setFavoriteLink(remap.harness, remap.profile, {
37918
+ ...link,
37919
+ connectionId: remap.connectionId
37426
37920
  });
37427
37921
  }
37428
37922
  }
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;
37923
+ this.toolModels.remapFavoriteConnectionsScoped(id, prepared.toolModelEntries);
37924
+ return saved;
37925
+ }), { action: "update", name: current.name });
37926
+ this.apply.consumeOverwrite(input.overwriteApprovalId);
37927
+ return updated;
37474
37928
  }
37475
- operation(requestId) {
37476
- const receipts = this.journal.list().filter((receipt) => receipt.favoriteRequest?.requestId === requestId).toSorted((a, b) => a.favoriteRequest.item - b.favoriteRequest.item);
37477
- return {
37478
- requestId,
37479
- items: [
37480
- ...receipts.map((receipt) => ({
37481
- harness: receipt.harness,
37482
- profile: receipt.profile,
37483
- operationId: receipt.id,
37484
- code: receipt.favoriteResult?.code,
37485
- status: receipt.state === "committed" || receipt.state === "metadata-committed" ? receipt.favoriteResult?.status ?? "applied" : receipt.state === "rolled-back" || receipt.state === "degraded" ? "failed" : "skipped"
37486
- })),
37487
- ...(receipts[0]?.favoriteRequest?.targets ?? []).filter((target) => !receipts.some((receipt) => receipt.harness === target.harness)).map((target) => ({
37488
- ...target,
37489
- status: "skipped",
37490
- code: ERROR_CODES.favoritePlanExpired
37491
- }))
37492
- ]
37493
- };
37929
+ sourceFingerprint(harness, name) {
37930
+ const profile = this.profiles.get(harness, name);
37931
+ if (!profile) {
37932
+ throw new HttpError(404, ERROR_CODES.profileNotFound, { code: ERROR_CODES.profileNotFound });
37933
+ }
37934
+ return createHmac("sha256", this.sourceSalt).update(this.profiles.fingerprint(harness, name)).digest("hex");
37494
37935
  }
37495
- apply(id, requestId, session) {
37496
- const receipts = this.journal.list().filter((receipt) => receipt.favoriteRequest?.requestId === requestId);
37497
- if (receipts.length) {
37498
- if (receipts.some((receipt) => receipt.favoriteRequest?.planId !== id)) {
37499
- throw failure3(ERROR_CODES.favoriteIdempotencyConflict);
37500
- }
37501
- return this.operation(requestId);
37936
+ capture(input) {
37937
+ if (this.sourceFingerprint(input.harness, input.name) !== input.sourceFingerprint) {
37938
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
37939
+ code: ERROR_CODES.favoritePlanStale
37940
+ });
37502
37941
  }
37503
- const plan = this.plans.get(id);
37504
- if (!plan || plan.user !== this.environment.dataDir || plan.session !== session || Date.parse(plan.public.expiresAt) < Date.now()) {
37505
- throw failure3(ERROR_CODES.favoritePlanExpired);
37942
+ const source = this.profiles.get(input.harness, input.name);
37943
+ if (source.overriddenTargets.length || source.modelFavorite) {
37944
+ throw new HttpError(409, ERROR_CODES.favoriteRawOverrideConflict, {
37945
+ code: ERROR_CODES.favoriteRawOverrideConflict
37946
+ });
37506
37947
  }
37507
- for (const prepared of plan.items) {
37508
- if (!this.matchesFingerprint(plan.favoriteId, prepared)) {
37509
- throw failure3(ERROR_CODES.favoritePlanStale);
37510
- }
37511
- if (prepared.public.projection.blockers.length) {
37512
- throw failure3(prepared.public.projection.blockers[0].code);
37513
- }
37948
+ const decrypted = this.profiles.decrypt(input.harness, input.name);
37949
+ const adapter = this.adapters.get(input.harness);
37950
+ const extracted = adapter.extractFavorite(decrypted);
37951
+ if (!source.providerId && !input.extractCredential) {
37952
+ throw new HttpError(409, ERROR_CODES.favoriteCredentialConsentRequired, {
37953
+ code: ERROR_CODES.favoriteCredentialConsentRequired
37954
+ });
37514
37955
  }
37515
- this.backups.create("apply", {
37516
- action: "apply",
37517
- name: this.favorites.get(plan.favoriteId).name,
37518
- tools: plan.items.map((item) => item.public.harness)
37519
- });
37520
- const result = { requestId, items: [] };
37521
- for (const [index, prepared] of plan.items.entries()) {
37522
- const item = prepared.public;
37523
- if (!this.matchesFingerprint(plan.favoriteId, prepared)) {
37524
- throw failure3(ERROR_CODES.favoritePlanStale);
37956
+ return this.backups.protect("change", () => this.liveWrite.transaction({
37957
+ kind: "favorite-capture",
37958
+ harness: input.harness,
37959
+ profile: input.name,
37960
+ writes: [],
37961
+ metadata: ["profiles", "vault", "favorites"]
37962
+ }, () => {
37963
+ const provider = source.providerId ? this.vault.get(source.providerId) : this.vault.create({
37964
+ name: input.favoriteName,
37965
+ apiKey: decrypted.apiKey,
37966
+ endpoints: [{ key: "api", baseUrl: decrypted.baseUrl }]
37967
+ });
37968
+ const endpointKey = source.providerEndpoint ?? provider.endpoints.find((endpoint) => endpoint.baseUrl === decrypted.baseUrl)?.key;
37969
+ if (!endpointKey) {
37970
+ throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
37971
+ code: ERROR_CODES.favoriteEndpointMissing
37972
+ });
37525
37973
  }
37526
- if (item.projection.blockers.length) {
37527
- throw failure3(item.projection.blockers[0].code);
37974
+ if (!source.providerId || !source.providerEndpoint) {
37975
+ this.profiles.upsert(input.harness, { name: input.name, providerId: provider.id, providerEndpoint: endpointKey }, false);
37528
37976
  }
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
- }
37977
+ const favorite = this.create({
37978
+ name: input.favoriteName,
37979
+ notes: "",
37980
+ defaults: extracted.defaults,
37981
+ preferences: extracted.preferences,
37982
+ connections: [
37983
+ {
37984
+ id: randomUUID6(),
37985
+ label: provider.name,
37986
+ providerId: provider.id,
37987
+ endpointKey,
37988
+ ...syncConnectionProtocols([extracted.protocol]),
37989
+ requestModelId: extracted.requestModelId,
37990
+ factOverrides: {},
37991
+ preferenceOverrides: {}
37572
37992
  }
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
37993
+ ]
37994
+ });
37995
+ if (input.linkSource) {
37996
+ const connection = favorite.connections[0];
37997
+ const projection = adapter.projectFavorite(favorite, connection);
37998
+ const current = this.profiles.get(input.harness, input.name);
37999
+ const baseline = {
38000
+ ...projection.projection,
38001
+ model: current.model,
38002
+ providerId: current.providerId ?? "",
38003
+ providerEndpoint: current.providerEndpoint ?? "",
38004
+ extras: Object.fromEntries(Object.keys(projection.projection.extras).map((key) => [
38005
+ key,
38006
+ current.extras[key] ?? null
38007
+ ]))
38008
+ };
38009
+ this.profiles.setFavoriteLink(input.harness, input.name, {
38010
+ favoriteId: favorite.id,
38011
+ connectionId: connection.id,
38012
+ appliedRevision: favorite.revision,
38013
+ projectionVersion: projection.projectionVersion,
38014
+ baseline
37580
38015
  });
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
38016
  }
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
- };
38017
+ return favorite;
38018
+ }), { action: "capture", name: input.favoriteName, tools: [input.harness] });
37594
38019
  }
37595
- matchesFingerprint(favoriteId, prepared) {
37596
- try {
37597
- return prepared.fingerprint === this.fingerprint(favoriteId, prepared.public);
37598
- } catch {
37599
- return false;
38020
+ detach(harness, name, fingerprint2) {
38021
+ if (this.sourceFingerprint(harness, name) !== fingerprint2) {
38022
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
38023
+ code: ERROR_CODES.favoritePlanStale
38024
+ });
37600
38025
  }
38026
+ this.backups.protect("change", () => this.profiles.setFavoriteLink(harness, name, undefined), {
38027
+ action: "detach",
38028
+ name,
38029
+ tools: [harness]
38030
+ });
37601
38031
  }
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)])
38032
+ ignoreUpdates(id, revision) {
38033
+ const favorite = this.store.get(id);
38034
+ if (favorite.revision !== revision) {
38035
+ throw new HttpError(409, ERROR_CODES.favoritePlanStale, {
38036
+ code: ERROR_CODES.favoritePlanStale
38037
+ });
38038
+ }
38039
+ this.backups.protect("change", () => {
38040
+ for (const ref of this.references(id)) {
38041
+ this.profiles.setFavoriteLink(ref.harness, ref.name, {
38042
+ ...ref.link,
38043
+ ignoredRevision: revision
38044
+ });
38045
+ }
37612
38046
  });
37613
38047
  }
38048
+ validateConnections(input) {
38049
+ for (const connection of input.connections) {
38050
+ const provider = this.vault.get(connection.providerId);
38051
+ if (!provider.endpoints.some((endpoint) => endpoint.key === connection.endpointKey)) {
38052
+ throw new HttpError(409, ERROR_CODES.favoriteEndpointMissing, {
38053
+ code: ERROR_CODES.favoriteEndpointMissing
38054
+ });
38055
+ }
38056
+ }
38057
+ }
37614
38058
  }
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 });
38059
+ ModelFavoriteService = __decorateElement(_init, 0, "ModelFavoriteService", _dec, ModelFavoriteService);
38060
+ __runInitializers(_init, 1, ModelFavoriteService);
38061
+ __decoratorMetadata(_init, ModelFavoriteService);
38062
+ let _ModelFavoriteService = ModelFavoriteService;
38063
+ function sameAccountModel(previous, connections) {
38064
+ return connections.find((connection) => connection.providerId === previous.providerId && connection.endpointKey === previous.endpointKey && connection.requestModelId === previous.requestModelId);
37624
38065
  }
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
- };
38066
+
38067
+ // src/http/routes/harnesses.ts
38068
+ function createHarnessRoutes(services) {
38069
+ const app = new Hono2;
38070
+ const registry2 = services.get(IHarnessRegistry);
38071
+ const harnesses = services.get(IHarnessService);
38072
+ const profiles = services.get(IProfileService);
38073
+ const activation = services.get(IActivationService);
38074
+ const profileProbe = services.get(IProbeProfileService);
38075
+ const audit = services.get(IAuditService);
38076
+ app.post("/:harnessId/profiles/:name/detach-favorite", async (c) => {
38077
+ const body = await readJsonBody(c, favoriteDetachRequestSchema);
38078
+ services.get(IModelFavoriteService).detach(registry2.require(param(c, "harnessId")), param(c, "name"), body.sourceFingerprint);
38079
+ return c.json({ code: FAVORITE_CODES.result, data: { ok: true } });
38080
+ });
38081
+ app.get("/", (c) => c.json(harnesses.overview()));
38082
+ app.get("/:harnessId", (c) => c.json(harnesses.summary(registry2.require(c.req.param("harnessId")))));
38083
+ app.post("/:harnessId/profiles", async (c) => {
38084
+ const harnessId = registry2.require(c.req.param("harnessId"));
38085
+ const body = await readJsonBody(c, createProfileRequestSchema);
38086
+ return c.json(harnesses.createProfile(harnessId, body), 201);
38087
+ });
38088
+ app.patch("/:harnessId/profiles/:name", async (c) => {
38089
+ const harnessId = registry2.require(c.req.param("harnessId"));
38090
+ const name = param(c, "name");
38091
+ const body = await readJsonBody(c, updateProfileRequestSchema);
38092
+ return c.json(harnesses.updateProfile(harnessId, name, body));
38093
+ });
38094
+ app.delete("/:harnessId/profiles/:name", (c) => {
38095
+ harnesses.deleteProfile(registry2.require(c.req.param("harnessId")), param(c, "name"));
38096
+ return c.json({ ok: true });
38097
+ });
38098
+ app.get("/:harnessId/profiles/:name/preview", (c) => {
38099
+ const harnessId = registry2.require(c.req.param("harnessId"));
38100
+ return c.json({ targets: activation.preview(harnessId, param(c, "name")) });
38101
+ });
38102
+ app.get("/:harnessId/official/preview", (c) => {
38103
+ const harnessId = registry2.require(c.req.param("harnessId"));
38104
+ return c.json({ targets: activation.previewOfficial(harnessId) });
38105
+ });
38106
+ app.post("/:harnessId/profiles/:name/probe", async (c) => {
38107
+ const harnessId = registry2.require(c.req.param("harnessId"));
38108
+ const name = param(c, "name");
38109
+ const body = await readOptionalJsonBody(c, probeStoredRequestSchema);
38110
+ const decrypted = profiles.decrypt(harnessId, name);
38111
+ return c.json({
38112
+ result: await profileProbe.probe(harnessId, decrypted, body)
38113
+ });
38114
+ });
38115
+ app.post("/:harnessId/profiles/:name/activate", (c) => {
38116
+ const harnessId = registry2.require(c.req.param("harnessId"));
38117
+ const name = param(c, "name");
38118
+ const result = activation.activate(harnessId, name);
38119
+ audit.record(AUDIT_EVENTS.profileActivated, { harness: harnessId, profile: name });
38120
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
38121
+ });
38122
+ app.post("/:harnessId/official/activate", (c) => {
38123
+ const harnessId = registry2.require(c.req.param("harnessId"));
38124
+ const result = activation.activateOfficial(harnessId);
38125
+ audit.record(AUDIT_EVENTS.officialActivated, { harness: harnessId });
38126
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
38127
+ });
38128
+ return app;
37633
38129
  }
37634
38130
 
37635
38131
  // src/http/routes/model-favorites.ts
@@ -37641,6 +38137,7 @@ function createModelFavoriteRoutes(services) {
37641
38137
  const adapters = services.get(IAdapterRegistry);
37642
38138
  const profiles = services.get(IProfileService);
37643
38139
  const backups = services.get(IFavoriteBackupService);
38140
+ const environment = services.get(IEnvironmentService);
37644
38141
  app.get("/backups", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.list() }));
37645
38142
  app.post("/backups", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.create() }, 201));
37646
38143
  app.get("/backups/:backupId/preview", (c) => c.json({ code: FAVORITE_CODES.result, data: backups.preview(param(c, "backupId")) }));
@@ -37685,7 +38182,11 @@ function createModelFavoriteRoutes(services) {
37685
38182
  });
37686
38183
  app.patch("/:id", async (c) => c.json({
37687
38184
  code: FAVORITE_CODES.result,
37688
- data: favorites.update(param(c, "id"), await readJsonBody(c, updateFavoriteRequestSchema))
38185
+ data: favorites.update(param(c, "id"), await readJsonBody(c, updateFavoriteRequestSchema), getCookie(c, environment.cookieName))
38186
+ }));
38187
+ app.post("/:id/overwrite-preview", async (c) => c.json({
38188
+ code: FAVORITE_CODES.result,
38189
+ data: apply.overwritePreview(param(c, "id"), await readJsonBody(c, overwritePreviewRequestSchema), getCookie(c, environment.cookieName))
37689
38190
  }));
37690
38191
  app.delete("/:id", async (c) => {
37691
38192
  const body = await readJsonBody(c, favoriteRevisionRequestSchema);