@aiwayds/dsh-model-sync 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -3
- package/README.zh-CN.md +20 -3
- package/lib/builtin-catalog-snapshot.js +6 -3
- package/lib/builtin-catalog-snapshot.js.map +1 -1
- package/lib/index.d.ts +379 -0
- package/lib/index.js +897 -13
- package/lib/index.js.map +1 -1
- package/lib/opencode-go-diagnose.d.ts +74 -0
- package/lib/opencode-go-diagnose.js +146 -0
- package/lib/opencode-go-diagnose.js.map +1 -0
- package/lib/opencode-go-grouping.d.ts +29 -0
- package/lib/opencode-go-grouping.js +77 -0
- package/lib/opencode-go-grouping.js.map +1 -0
- package/lib/opencode-go-journal.d.ts +110 -0
- package/lib/opencode-go-journal.js +406 -0
- package/lib/opencode-go-journal.js.map +1 -0
- package/lib/opencode-go-migrate.d.ts +343 -0
- package/lib/opencode-go-migrate.js +1300 -0
- package/lib/opencode-go-migrate.js.map +1 -0
- package/lib/opencode-go-migration.d.ts +227 -0
- package/lib/opencode-go-migration.js +384 -0
- package/lib/opencode-go-migration.js.map +1 -0
- package/lib/opencode-go-one-shot.d.ts +276 -0
- package/lib/opencode-go-one-shot.js +1094 -0
- package/lib/opencode-go-one-shot.js.map +1 -0
- package/lib/opencode-go-patch-file.d.ts +123 -0
- package/lib/opencode-go-patch-file.js +1185 -0
- package/lib/opencode-go-patch-file.js.map +1 -0
- package/lib/opencode-go-planner.d.ts +153 -0
- package/lib/opencode-go-planner.js +339 -0
- package/lib/opencode-go-planner.js.map +1 -0
- package/lib/opencode-go-profile.d.ts +57 -0
- package/lib/opencode-go-profile.js +103 -0
- package/lib/opencode-go-profile.js.map +1 -0
- package/lib/opencode-go-scheduler.d.ts +128 -0
- package/lib/opencode-go-scheduler.js +241 -0
- package/lib/opencode-go-scheduler.js.map +1 -0
- package/lib/opencode-go-source.d.ts +117 -0
- package/lib/opencode-go-source.js +331 -0
- package/lib/opencode-go-source.js.map +1 -0
- package/lib/opencode-go-store.d.ts +18 -0
- package/lib/opencode-go-store.js +68 -0
- package/lib/opencode-go-store.js.map +1 -0
- package/lib/opencode-go-sync.d.ts +94 -0
- package/lib/opencode-go-sync.js +364 -0
- package/lib/opencode-go-sync.js.map +1 -0
- package/lib/opencode-go-writer.d.ts +132 -0
- package/lib/opencode-go-writer.js +966 -0
- package/lib/opencode-go-writer.js.map +1 -0
- package/lib/provider-native.d.ts +3 -1
- package/lib/provider-native.js +4 -2
- package/lib/provider-native.js.map +1 -1
- package/lib/remote-catalog.d.ts +61 -0
- package/lib/remote-catalog.js +307 -3
- package/lib/remote-catalog.js.map +1 -1
- package/package.json +15 -15
- package/src/builtin-catalog-snapshot.ts +6 -3
- package/src/index.ts +1060 -12
- package/src/opencode-go-diagnose.ts +222 -0
- package/src/opencode-go-grouping.ts +97 -0
- package/src/opencode-go-journal.ts +458 -0
- package/src/opencode-go-migrate.ts +1694 -0
- package/src/opencode-go-migration.ts +552 -0
- package/src/opencode-go-one-shot.ts +1354 -0
- package/src/opencode-go-patch-file.ts +1168 -0
- package/src/opencode-go-planner.ts +505 -0
- package/src/opencode-go-profile.ts +114 -0
- package/src/opencode-go-scheduler.ts +315 -0
- package/src/opencode-go-source.ts +424 -0
- package/src/opencode-go-store.ts +73 -0
- package/src/opencode-go-sync.ts +503 -0
- package/src/opencode-go-writer.ts +1189 -0
- package/src/provider-native.ts +3 -1
- package/src/remote-catalog.ts +359 -3
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// P1a pure planner: official opencode-go records + current route state +
|
|
2
|
+
// ownership ledger → a settings-independent write plan.
|
|
3
|
+
//
|
|
4
|
+
// Hard boundary (design 07 §6.2.1): this module does no I/O, never calls
|
|
5
|
+
// settings.mutate, never touches credentials, and never schedules timers. The
|
|
6
|
+
// caller in P1b turns the returned plan into settings operations. Everything
|
|
7
|
+
// here is a pure function of its inputs so it can be exercised with offline
|
|
8
|
+
// fixtures only.
|
|
9
|
+
//
|
|
10
|
+
// Design refs: §2.1/§6.2.2 (route fields + msg baseURL normalization),
|
|
11
|
+
// §6.2.3 (grouping), §6.2.4 (ownership-aware merge), §6.2.5 (route fields),
|
|
12
|
+
// §9.2-9.4 (keep the name, conflicts, empty routes), ADR-004 (ledger keyed
|
|
13
|
+
// by keyFingerprint), ADR-005 (deletion gates). F25 is intentionally absent:
|
|
14
|
+
// report 19 proved the host injects x-opencode-session, so no special header
|
|
15
|
+
// handling belongs in the plan.
|
|
16
|
+
|
|
17
|
+
import { createHash } from 'node:crypto'
|
|
18
|
+
import type { SettingsModelProfile } from './translate.ts'
|
|
19
|
+
import type { GoModelRecord } from './opencode-go-source.ts'
|
|
20
|
+
import { deriveKeyRef } from './route-credential.ts'
|
|
21
|
+
import {
|
|
22
|
+
GO_SLOT_ROUTES,
|
|
23
|
+
groupGoModelsByProtocol,
|
|
24
|
+
type GoRouteSlot,
|
|
25
|
+
} from './opencode-go-grouping.ts'
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Static route-field plan (design §2.1 / §6.2.2, confirmed by report 19)
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/** Host `api` value per slot (llm-pi-ai PROTOCOLS, report 19 §1). */
|
|
32
|
+
export const GO_API_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
|
|
33
|
+
chat: 'openai-completions',
|
|
34
|
+
msg: 'anthropic-messages',
|
|
35
|
+
resp: 'openai-responses',
|
|
36
|
+
google: 'google-generative-ai',
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The only display field the host uses to group providers (F22/13). */
|
|
40
|
+
export const GO_DISPLAY_NAME_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
|
|
41
|
+
chat: 'OpenCode Go',
|
|
42
|
+
msg: 'OpenCode Go · msg',
|
|
43
|
+
resp: 'OpenCode Go · resp',
|
|
44
|
+
google: 'OpenCode Go · google',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Fallback host baseURLs — the values report 19 confirmed end-to-end. Normally
|
|
49
|
+
* the baseURL comes from the official payload (§6.2.2); these are used only
|
|
50
|
+
* when a record carries no per-protocol `base_url`.
|
|
51
|
+
*/
|
|
52
|
+
export const GO_BASE_URL_BY_SLOT: Readonly<Record<GoRouteSlot, string>> = {
|
|
53
|
+
chat: 'https://opencode.ai/inference/go/openai/v1',
|
|
54
|
+
msg: 'https://opencode.ai/inference/go/anthropic',
|
|
55
|
+
resp: 'https://opencode.ai/inference/go/openai/v1',
|
|
56
|
+
google: 'https://opencode.ai/inference/go/google/v1beta',
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Official protocol keys that back each slot (§6.2.2 table). */
|
|
60
|
+
export const GO_PROTOCOLS_BY_SLOT: Readonly<Record<GoRouteSlot, readonly string[]>> = {
|
|
61
|
+
chat: ['chat-completions'],
|
|
62
|
+
msg: ['messages'],
|
|
63
|
+
resp: ['responses'],
|
|
64
|
+
google: ['interactions', 'generate-content'],
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Normalize an official `base_url` for host use. Only `msg` changes: pi-ai
|
|
69
|
+
* calls `beta.messages.create` and appends `/v1/messages?beta=true`, so the
|
|
70
|
+
* trailing `/v1` must be stripped (ADR-003 / report 19 negative control).
|
|
71
|
+
*/
|
|
72
|
+
export function normalizeGoBaseUrl(raw: string, slot: GoRouteSlot): string {
|
|
73
|
+
const trimmed = raw.replace(/\/+$/, '')
|
|
74
|
+
if (slot === 'msg' && trimmed.endsWith('/v1')) return trimmed.slice(0, -3)
|
|
75
|
+
return trimmed
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface GoPlannedRouteFields {
|
|
79
|
+
api: string
|
|
80
|
+
baseURL: string
|
|
81
|
+
displayName: string
|
|
82
|
+
apiKeyEnv: string
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build the route fields for a slot from the payload's per-protocol base_url.
|
|
87
|
+
* `ref` defaults to the P0-derived `OPENCODE_GO_API_KEY`.
|
|
88
|
+
*/
|
|
89
|
+
export function planGoRouteFields(
|
|
90
|
+
slot: GoRouteSlot,
|
|
91
|
+
entries: readonly GoModelRecord[],
|
|
92
|
+
ref: string = deriveKeyRef('opencode-go'),
|
|
93
|
+
): GoPlannedRouteFields {
|
|
94
|
+
const protocols = GO_PROTOCOLS_BY_SLOT[slot]
|
|
95
|
+
let raw: string | undefined
|
|
96
|
+
for (const entry of entries) {
|
|
97
|
+
for (const protocol of protocols) {
|
|
98
|
+
const base = entry.baseUrls[protocol]
|
|
99
|
+
if (base !== undefined && base.length > 0) {
|
|
100
|
+
raw = base
|
|
101
|
+
break
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (raw !== undefined) break
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
api: GO_API_BY_SLOT[slot],
|
|
108
|
+
baseURL: raw !== undefined ? normalizeGoBaseUrl(raw, slot) : GO_BASE_URL_BY_SLOT[slot],
|
|
109
|
+
displayName: GO_DISPLAY_NAME_BY_SLOT[slot],
|
|
110
|
+
apiKeyEnv: ref,
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// Model mapping (design §6.1 field mapping)
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
/** Effort keys the host schema accepts (mirrors translate.ts THINKING_LEVELS). */
|
|
119
|
+
const THINKING_LEVELS = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
|
|
120
|
+
|
|
121
|
+
/** Official GoModelRecord → host SettingsModelProfile. `created` never enters. */
|
|
122
|
+
export function mapGoModelToProfile(entry: GoModelRecord): SettingsModelProfile {
|
|
123
|
+
const profile: SettingsModelProfile = { id: entry.id }
|
|
124
|
+
if (entry.name.length > 0) profile.name = entry.name
|
|
125
|
+
if (entry.contextWindow !== undefined) profile.contextWindow = entry.contextWindow
|
|
126
|
+
if (entry.maxOutput !== undefined) profile.maxTokens = entry.maxOutput
|
|
127
|
+
if (entry.inputModalities.length > 0) profile.input = [...entry.inputModalities]
|
|
128
|
+
if (entry.reasoning !== undefined && entry.reasoning.efforts.length > 0) {
|
|
129
|
+
const efforts: Record<string, string | null> = {}
|
|
130
|
+
for (const effort of entry.reasoning.efforts) {
|
|
131
|
+
if (THINKING_LEVELS.has(effort)) efforts[effort] = effort
|
|
132
|
+
}
|
|
133
|
+
if (Object.keys(efforts).length > 0) profile.reasoningEfforts = efforts
|
|
134
|
+
}
|
|
135
|
+
return profile
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// Ownership ledger (ADR-004: keyed by <route>#<keyFingerprint>)
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
export interface GoManagedModel {
|
|
143
|
+
/** Hash of the profile the plugin last wrote for this id. */
|
|
144
|
+
hash: string
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface GoOwnershipEntry {
|
|
148
|
+
/** Route fields the plugin last wrote (used to recognize a fully-owned route). */
|
|
149
|
+
routeFields?: Partial<GoPlannedRouteFields>
|
|
150
|
+
/** Plugin-managed model ids and the hash of their last written profile. */
|
|
151
|
+
managed: Record<string, GoManagedModel>
|
|
152
|
+
/**
|
|
153
|
+
* Raw models present in the route before the plugin first claimed it (design
|
|
154
|
+
* §6.1 / ADR-004). Audit-only: never used as a whole-route write-back.
|
|
155
|
+
* Rollback restores from `preManagedSection` (§14.3), not from this field.
|
|
156
|
+
*/
|
|
157
|
+
preManagedSnapshot?: SettingsModelProfile[]
|
|
158
|
+
/**
|
|
159
|
+
* P1d-2: the COMPLETE raw provider section captured before `migrate apply`
|
|
160
|
+
* (all fields — api/baseURL/displayName/apiKeyEnv/models — exactly as found).
|
|
161
|
+
* `null` means the route did not exist before the migration. This is the
|
|
162
|
+
* authoritative rollback target (design §14.3 whole-section snapshot) and is
|
|
163
|
+
* persisted on the same models-store queue as the rest of the ledger entry;
|
|
164
|
+
* unlike the in-progress backup it is NOT released when apply succeeds.
|
|
165
|
+
*/
|
|
166
|
+
preManagedSection?: Record<string, unknown> | null
|
|
167
|
+
/**
|
|
168
|
+
* P1d-2: ids `migrate apply` newly introduced on this route (merged desired
|
|
169
|
+
* ids absent from the pre-apply section). Rollback removes these, while ids
|
|
170
|
+
* the user adds after apply are left untouched.
|
|
171
|
+
*/
|
|
172
|
+
appliedAddedIds?: string[]
|
|
173
|
+
/**
|
|
174
|
+
* Consecutive successful rounds an id has been absent from the desired set.
|
|
175
|
+
* The planner only flags a deletion-candidate; the writer owns this counter
|
|
176
|
+
* and deletes only once it reaches `confirmRemovals` (design §6.2.4 / V5).
|
|
177
|
+
*/
|
|
178
|
+
missing?: Record<string, number>
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export type GoOwnershipLedger = Readonly<Record<string, GoOwnershipEntry>>
|
|
182
|
+
|
|
183
|
+
/** Ledger key: one route's ownership is invisible under a different key. */
|
|
184
|
+
export function goOwnershipKey(route: string, keyFingerprint: string): string {
|
|
185
|
+
return `${route}#${keyFingerprint}`
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The raw current state of one provider route in settings. */
|
|
189
|
+
export interface GoRouteState {
|
|
190
|
+
exists: boolean
|
|
191
|
+
api?: string
|
|
192
|
+
baseURL?: string
|
|
193
|
+
displayName?: string
|
|
194
|
+
apiKeyEnv?: string
|
|
195
|
+
/** Raw models array (no schema defaults applied). */
|
|
196
|
+
models: readonly SettingsModelProfile[]
|
|
197
|
+
/** Ids covered by a non-empty modelOverrides key on this route. */
|
|
198
|
+
overrideIds?: readonly string[]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
// Plan output
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
export interface GoRouteConflict {
|
|
206
|
+
slot: GoRouteSlot
|
|
207
|
+
route: string
|
|
208
|
+
field: 'api' | 'baseURL' | 'apiKeyEnv'
|
|
209
|
+
expected: string
|
|
210
|
+
actual: string
|
|
211
|
+
reason: string
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export type GoPlanReportLevel = 'info' | 'warn' | 'error'
|
|
215
|
+
|
|
216
|
+
export interface GoPlanReportEntry {
|
|
217
|
+
level: GoPlanReportLevel
|
|
218
|
+
/** Stable machine code (e.g. route-conflict, kept-user-owned, unknown-protocol). */
|
|
219
|
+
code: string
|
|
220
|
+
route?: string
|
|
221
|
+
slot?: GoRouteSlot
|
|
222
|
+
id?: string
|
|
223
|
+
message: string
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export interface GoPlannedRoute {
|
|
227
|
+
slot: GoRouteSlot
|
|
228
|
+
route: string
|
|
229
|
+
fields: GoPlannedRouteFields
|
|
230
|
+
/** Complete merged models array, sorted by id (never an empty write — see unset/skip). */
|
|
231
|
+
models: SettingsModelProfile[]
|
|
232
|
+
/** Empty and fully plugin-managed: caller should unset providers.<route>. */
|
|
233
|
+
unset: boolean
|
|
234
|
+
/** Conflict, empty main route, or empty route with user content: write nothing. */
|
|
235
|
+
skip: boolean
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export interface GoPlanResult {
|
|
239
|
+
routes: GoPlannedRoute[]
|
|
240
|
+
/** Routes the caller should unset (never paired with `models: []`). */
|
|
241
|
+
unsetRoutes: string[]
|
|
242
|
+
conflicts: GoRouteConflict[]
|
|
243
|
+
report: GoPlanReportEntry[]
|
|
244
|
+
/** Shallow copy of the ledger updated only for this key's routes. */
|
|
245
|
+
nextOwnership: Record<string, GoOwnershipEntry>
|
|
246
|
+
/**
|
|
247
|
+
* The mapped desired profiles per route BEFORE the merge with current
|
|
248
|
+
* settings. The writer needs this to do a first-round conservative claim
|
|
249
|
+
* (official desired ∩ current, never ids outside the desired set) — the
|
|
250
|
+
* merged `routes[].models` already contains kept user entries and cannot be
|
|
251
|
+
* used for that distinction.
|
|
252
|
+
*/
|
|
253
|
+
desiredByRoute: Record<string, SettingsModelProfile[]>
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export interface GoPlannerOptions {
|
|
257
|
+
/** sha256(key) first 16 hex from the source result; '-' when no key. */
|
|
258
|
+
keyFingerprint: string
|
|
259
|
+
entries: readonly GoModelRecord[]
|
|
260
|
+
/** Current state of the go routes, keyed by route id. */
|
|
261
|
+
currentRoutes: Readonly<Record<string, GoRouteState>>
|
|
262
|
+
ownership: GoOwnershipLedger
|
|
263
|
+
/** go.ref; defaults to P0's deriveKeyRef('opencode-go'). */
|
|
264
|
+
ref?: string
|
|
265
|
+
/** go.routes overrides (default GO_SLOT_ROUTES). */
|
|
266
|
+
routes?: Partial<Record<GoRouteSlot, string>>
|
|
267
|
+
/** go.pinnedModels — protected from deletion (design A4). */
|
|
268
|
+
pinnedModels?: readonly string[]
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
// Helpers
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
function canonicalize(value: unknown): unknown {
|
|
276
|
+
if (Array.isArray(value)) return value.map(canonicalize)
|
|
277
|
+
if (typeof value !== 'object' || value === null) return value
|
|
278
|
+
const out: Record<string, unknown> = {}
|
|
279
|
+
for (const key of Object.keys(value as Record<string, unknown>).sort()) {
|
|
280
|
+
out[key] = canonicalize((value as Record<string, unknown>)[key])
|
|
281
|
+
}
|
|
282
|
+
return out
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Stable hash of a settings profile — the "现值哈希" of the deletion gates. */
|
|
286
|
+
export function profileHash(profile: SettingsModelProfile): string {
|
|
287
|
+
return createHash('sha256').update(JSON.stringify(canonicalize(profile))).digest('hex')
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const OWNERSHIP_FIELDS = ['api', 'baseURL', 'apiKeyEnv'] as const
|
|
291
|
+
|
|
292
|
+
/** A current route conflicts only when a field is explicitly set to a different value. */
|
|
293
|
+
function detectConflict(
|
|
294
|
+
slot: GoRouteSlot,
|
|
295
|
+
route: string,
|
|
296
|
+
fields: GoPlannedRouteFields,
|
|
297
|
+
current: GoRouteState | undefined,
|
|
298
|
+
): GoRouteConflict | undefined {
|
|
299
|
+
if (current === undefined || !current.exists) return undefined
|
|
300
|
+
for (const field of OWNERSHIP_FIELDS) {
|
|
301
|
+
const actual = current[field]
|
|
302
|
+
if (actual !== undefined && actual !== '' && actual !== fields[field]) {
|
|
303
|
+
return {
|
|
304
|
+
slot,
|
|
305
|
+
route,
|
|
306
|
+
field,
|
|
307
|
+
expected: fields[field],
|
|
308
|
+
actual,
|
|
309
|
+
reason: 'existing route field differs from plan; keep name, skip write (design §9.3)',
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return undefined
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function ownedFieldsMatch(
|
|
317
|
+
owned: GoOwnershipEntry | undefined,
|
|
318
|
+
fields: GoPlannedRouteFields,
|
|
319
|
+
): boolean {
|
|
320
|
+
if (owned === undefined || owned.routeFields === undefined) return false
|
|
321
|
+
return OWNERSHIP_FIELDS.every((field) => owned.routeFields![field] === fields[field])
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ---------------------------------------------------------------------------
|
|
325
|
+
// Planner
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Build the write plan. Pure: identical inputs always produce an identical
|
|
330
|
+
* plan (report/order included). No mutation of `options` or its nested values.
|
|
331
|
+
*/
|
|
332
|
+
export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
|
|
333
|
+
const ref = options.ref ?? deriveKeyRef('opencode-go')
|
|
334
|
+
const routes: Record<GoRouteSlot, string> = { ...GO_SLOT_ROUTES, ...(options.routes ?? {}) }
|
|
335
|
+
const pinned = new Set(options.pinnedModels ?? [])
|
|
336
|
+
const grouping = groupGoModelsByProtocol(options.entries)
|
|
337
|
+
const report: GoPlanReportEntry[] = []
|
|
338
|
+
const conflicts: GoRouteConflict[] = []
|
|
339
|
+
const plannedRoutes: GoPlannedRoute[] = []
|
|
340
|
+
const unsetRoutes: string[] = []
|
|
341
|
+
const nextOwnership: Record<string, GoOwnershipEntry> = { ...options.ownership }
|
|
342
|
+
const desiredByRoute: Record<string, SettingsModelProfile[]> = {}
|
|
343
|
+
|
|
344
|
+
// Unknown / otherwise unsupported protocols are fail-closed: reported, never
|
|
345
|
+
// written (design §6.2.3, V1).
|
|
346
|
+
for (const unassigned of grouping.unassigned) {
|
|
347
|
+
report.push({
|
|
348
|
+
level: 'warn',
|
|
349
|
+
code: unassigned.reason,
|
|
350
|
+
id: unassigned.id,
|
|
351
|
+
message: `model ${unassigned.id} not assigned (${unassigned.protocols.join(',') || 'no protocols'})`,
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const entryById = new Map(options.entries.map((entry) => [entry.id, entry]))
|
|
356
|
+
|
|
357
|
+
for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
|
|
358
|
+
const desiredIds = grouping.slots[slot] ?? []
|
|
359
|
+
const route = routes[slot]
|
|
360
|
+
const current = options.currentRoutes[route]
|
|
361
|
+
const ledgerKey = goOwnershipKey(route, options.keyFingerprint)
|
|
362
|
+
const owned = options.ownership[ledgerKey]
|
|
363
|
+
desiredByRoute[route] = []
|
|
364
|
+
|
|
365
|
+
// Google slot is conditional and default-off (design §2.1): materialize it
|
|
366
|
+
// only when it has members, or when there is a previous ledger to clean up.
|
|
367
|
+
if (slot === 'google' && desiredIds.length === 0 && owned === undefined) continue
|
|
368
|
+
|
|
369
|
+
const slotEntries = desiredIds
|
|
370
|
+
.map((id) => entryById.get(id))
|
|
371
|
+
.filter((entry): entry is GoModelRecord => entry !== undefined)
|
|
372
|
+
const fields = planGoRouteFields(slot, slotEntries, ref)
|
|
373
|
+
|
|
374
|
+
// Empty group: never produce a `models: []` write (§9.4 / A9). Unset a
|
|
375
|
+
// fully plugin-managed route, otherwise skip (keeping the route as-is) and
|
|
376
|
+
// report. A slot with no route at all is not planned at all.
|
|
377
|
+
if (desiredIds.length === 0) {
|
|
378
|
+
const currentModels = current?.models ?? []
|
|
379
|
+
if (current === undefined || !current.exists) continue
|
|
380
|
+
if (slot === 'chat') {
|
|
381
|
+
// §9.4: an empty main route after a 200 is an upstream anomaly — keep
|
|
382
|
+
// last-good, write nothing.
|
|
383
|
+
plannedRoutes.push({ slot, route, fields, models: [...currentModels], unset: false, skip: true })
|
|
384
|
+
report.push({ level: 'warn', code: 'upstream-empty', route, slot, message: 'main route has no members; kept last-good, no write' })
|
|
385
|
+
continue
|
|
386
|
+
}
|
|
387
|
+
const managed = owned?.managed ?? {}
|
|
388
|
+
const fullyManaged = owned !== undefined
|
|
389
|
+
&& currentModels.length > 0
|
|
390
|
+
&& currentModels.every((model) => {
|
|
391
|
+
const record = managed[model.id]
|
|
392
|
+
return record !== undefined && record.hash === profileHash(model)
|
|
393
|
+
})
|
|
394
|
+
&& ownedFieldsMatch(owned, fields)
|
|
395
|
+
if (fullyManaged) {
|
|
396
|
+
plannedRoutes.push({ slot, route, fields, models: [], unset: true, skip: false })
|
|
397
|
+
unsetRoutes.push(route)
|
|
398
|
+
report.push({ level: 'info', code: 'unset-route', route, slot, message: `route ${route} is empty and fully plugin-managed; unset` })
|
|
399
|
+
delete nextOwnership[ledgerKey]
|
|
400
|
+
} else {
|
|
401
|
+
plannedRoutes.push({ slot, route, fields, models: [...currentModels], unset: false, skip: true })
|
|
402
|
+
if (currentModels.length > 0) {
|
|
403
|
+
report.push({ level: 'warn', code: 'route-empty-has-user-content', route, slot, message: `route ${route} is empty but has user content; kept, no empty write` })
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
continue
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const conflict = detectConflict(slot, route, fields, current)
|
|
410
|
+
if (conflict !== undefined) {
|
|
411
|
+
conflicts.push(conflict)
|
|
412
|
+
report.push({
|
|
413
|
+
level: 'error',
|
|
414
|
+
code: 'route-conflict',
|
|
415
|
+
route,
|
|
416
|
+
slot,
|
|
417
|
+
message: `${route}.${conflict.field} is ${conflict.actual}, expected ${conflict.expected}`,
|
|
418
|
+
})
|
|
419
|
+
continue
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const desiredById = new Map<string, SettingsModelProfile>()
|
|
423
|
+
for (const id of desiredIds) {
|
|
424
|
+
const entry = entryById.get(id)
|
|
425
|
+
if (entry !== undefined) desiredById.set(id, mapGoModelToProfile(entry))
|
|
426
|
+
}
|
|
427
|
+
desiredByRoute[route] = [...desiredById.values()]
|
|
428
|
+
|
|
429
|
+
const currentModels = current?.models ?? []
|
|
430
|
+
const managed = owned?.managed ?? {}
|
|
431
|
+
const nextManaged: Record<string, GoManagedModel> = {}
|
|
432
|
+
const kept: SettingsModelProfile[] = []
|
|
433
|
+
|
|
434
|
+
for (const model of currentModels) {
|
|
435
|
+
const id = model.id
|
|
436
|
+
const desired = desiredById.get(id)
|
|
437
|
+
const record = managed[id]
|
|
438
|
+
const hashMatches = record !== undefined && record.hash === profileHash(model)
|
|
439
|
+
const hasOverride = (current?.overrideIds ?? []).includes(id)
|
|
440
|
+
const isPinned = pinned.has(id)
|
|
441
|
+
|
|
442
|
+
if (desired !== undefined) {
|
|
443
|
+
if (record !== undefined && hashMatches) {
|
|
444
|
+
// Plugin-owned and untouched: overwrite with the freshly mapped value.
|
|
445
|
+
const next = desired
|
|
446
|
+
nextManaged[id] = { hash: profileHash(next) }
|
|
447
|
+
kept.push(next)
|
|
448
|
+
report.push({ level: 'info', code: 'overwrote-managed', route, slot, id, message: `refreshed plugin-managed model ${id}` })
|
|
449
|
+
} else {
|
|
450
|
+
// Not in ledger, or hash differs (user edited): keep as-is, never claim.
|
|
451
|
+
kept.push(model)
|
|
452
|
+
if (record !== undefined) nextManaged[id] = record
|
|
453
|
+
report.push({
|
|
454
|
+
level: 'info',
|
|
455
|
+
code: 'kept-user-owned',
|
|
456
|
+
route,
|
|
457
|
+
slot,
|
|
458
|
+
id,
|
|
459
|
+
message: record !== undefined ? `model ${id} was modified; kept user value` : `model ${id} is user-owned; kept`,
|
|
460
|
+
})
|
|
461
|
+
}
|
|
462
|
+
continue
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Not desired: the three deletion gates (ADR-005 / §6.2.4).
|
|
466
|
+
if (record !== undefined && hashMatches && !hasOverride && !isPinned) {
|
|
467
|
+
report.push({ level: 'info', code: 'deletion-candidate', route, slot, id, message: `model ${id} passed all three deletion gates` })
|
|
468
|
+
continue
|
|
469
|
+
}
|
|
470
|
+
kept.push(model)
|
|
471
|
+
if (record !== undefined) nextManaged[id] = record
|
|
472
|
+
const code = record === undefined
|
|
473
|
+
? 'kept-user-owned'
|
|
474
|
+
: !hashMatches
|
|
475
|
+
? 'kept-modified'
|
|
476
|
+
: hasOverride
|
|
477
|
+
? 'kept-override'
|
|
478
|
+
: 'kept-pinned'
|
|
479
|
+
report.push({ level: 'info', code, route, slot, id, message: `model ${id} kept (${code}); not removed` })
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// New desired ids (absent from settings) are added and claimed.
|
|
483
|
+
const currentIds = new Set(currentModels.map((model) => model.id))
|
|
484
|
+
for (const id of desiredIds) {
|
|
485
|
+
if (currentIds.has(id)) continue
|
|
486
|
+
const profile = desiredById.get(id)
|
|
487
|
+
if (profile === undefined) continue
|
|
488
|
+
nextManaged[id] = { hash: profileHash(profile) }
|
|
489
|
+
kept.push(profile)
|
|
490
|
+
report.push({ level: 'info', code: 'added', route, slot, id, message: `added model ${id}` })
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// `desiredIds` is non-empty here, so the merged array is never empty.
|
|
494
|
+
const merged = [...kept].sort((a, b) => a.id.localeCompare(b.id))
|
|
495
|
+
plannedRoutes.push({ slot, route, fields, models: merged, unset: false, skip: false })
|
|
496
|
+
// P1d-2 ownership: inherit the prior entry so migration-period fields
|
|
497
|
+
// (`preManagedSection` / `appliedAddedIds` and any future ones) survive the
|
|
498
|
+
// plan round-trip untouched. The planner never writes or clears these — it
|
|
499
|
+
// only refreshes the fields it owns (routeFields / managed). The go writer
|
|
500
|
+
// applies the same merge when it persists the ledger entry.
|
|
501
|
+
nextOwnership[ledgerKey] = { ...owned, routeFields: fields, managed: nextManaged }
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return { routes: plannedRoutes, unsetRoutes, conflicts, report, nextOwnership, desiredByRoute }
|
|
505
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// B1: profile identity for the shared ~/.dsh/models-store.json (design §14.1,
|
|
2
|
+
// §14.7.4, H9). Every dsh profile on a machine writes the SAME models-store.json;
|
|
3
|
+
// without a profile dimension in the ledger/migration-record keys, profile A's
|
|
4
|
+
// `applied` record lets never-migrated profile B through the migration gate and
|
|
5
|
+
// A's rollback clobbers B's ledger + settings. This module supplies the profile
|
|
6
|
+
// dimension and the key primitives used by the file-backed stores.
|
|
7
|
+
//
|
|
8
|
+
// Identity source (host-provided — never guessed from settings or file names):
|
|
9
|
+
// 1. cordis `profileContext.name` (dsh app-boot): the launched profile name.
|
|
10
|
+
// 2. launchEnvironment `DSH_PROFILE`: the same value, launcher-provided env.
|
|
11
|
+
// 3. cordis `profileContext.dir` / launchEnvironment `DSH_PROFILE_DIR`:
|
|
12
|
+
// absolute profile directory, used ONLY when no name is available.
|
|
13
|
+
// 4. NO identity → FAIL CLOSED. `resolveProfileKey` returns undefined and the
|
|
14
|
+
// migration/ownership ledger callers refuse to read or write. There is
|
|
15
|
+
// deliberately NO silent 'default' collapse: two profiles with no resolved
|
|
16
|
+
// identity would share one key and reopen the B1 failure (design H9).
|
|
17
|
+
//
|
|
18
|
+
// Stability: the primary key is the profile NAME. It is fixed for the lifetime
|
|
19
|
+
// of a profile across restarts and processes. The host derives
|
|
20
|
+
// `name = basename(dir)`, so MOVING a profile directory while keeping its
|
|
21
|
+
// basename leaves the key stable; a move that also RENAMES the basename changes
|
|
22
|
+
// the name, hence the key: the old record becomes an orphan in the shared store,
|
|
23
|
+
// the renamed profile reads no record (absent/legacy) and fails CLOSED — it must
|
|
24
|
+
// re-run `migrate plan/apply`. We never auto-claim a record that carries another
|
|
25
|
+
// profile's identity. The directory fallback is less stable (moving/renaming the
|
|
26
|
+
// directory changes it) and is used only as a last resort.
|
|
27
|
+
|
|
28
|
+
/** Structural context seam: both services are optional peers in cordis. */
|
|
29
|
+
export interface ProfileIdentityContext {
|
|
30
|
+
get(name: 'profileContext'): { name?: string; dir?: string } | undefined
|
|
31
|
+
get(name: 'launchEnvironment'): { get(key: string): { value: string } | undefined } | undefined
|
|
32
|
+
get(name: string): unknown
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function nonEmpty(value: unknown): string | undefined {
|
|
36
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Resolve the stable profile key from the host, or `undefined` when no identity
|
|
41
|
+
* is available. Structural `ctx.get` keeps the optional peers optional (SDK
|
|
42
|
+
* hosts provide neither, tests provide fakes). Callers on a migration/ownership
|
|
43
|
+
* ledger path MUST treat `undefined` as fail-closed — see
|
|
44
|
+
* `PROFILE_IDENTITY_REQUIRED_MESSAGE` for the actionable error to surface.
|
|
45
|
+
*/
|
|
46
|
+
export function resolveProfileKey(ctx: ProfileIdentityContext): string | undefined {
|
|
47
|
+
const profile = ctx.get('profileContext')
|
|
48
|
+
const env = ctx.get('launchEnvironment')
|
|
49
|
+
return nonEmpty(profile?.name)
|
|
50
|
+
?? nonEmpty(env?.get('DSH_PROFILE')?.value)
|
|
51
|
+
?? nonEmpty(profile?.dir)
|
|
52
|
+
?? nonEmpty(env?.get('DSH_PROFILE_DIR')?.value)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Actionable error for a ledger path that cannot resolve a profile identity.
|
|
57
|
+
* Names verified against the dsh launcher source: `profileContext` ({ name,
|
|
58
|
+
* dir }) is a cordis service (profile-context.ts), `launchEnvironment` is the
|
|
59
|
+
* launcher snapshot service (`launchEnvironmentOf`), and `DSH_PROFILE` /
|
|
60
|
+
* `DSH_PROFILE_DIR` are the `DSH_` prefixed profile variables defined by the
|
|
61
|
+
* shell-env package (derived from `profileContext` for model-shell subprocesses).
|
|
62
|
+
*/
|
|
63
|
+
export const PROFILE_IDENTITY_REQUIRED_MESSAGE = [
|
|
64
|
+
'model-sync: cannot resolve the dsh profile identity for the opencode-go migration/ownership ledger.',
|
|
65
|
+
'Refusing to share a single key across profiles: without a stable per-profile key another profile could inherit this migration state.',
|
|
66
|
+
'Fix: launch the plugin inside a dsh profile so ctx.profileContext.name (or ctx.profileContext.dir) is available,',
|
|
67
|
+
'or expose the launcher-provided DSH_PROFILE / DSH_PROFILE_DIR values through ctx.launchEnvironment.',
|
|
68
|
+
'No migration record or ledger key was read or written.',
|
|
69
|
+
].join(' ')
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Compact, user-visible hint for a non-strict status refresh that degraded
|
|
73
|
+
* because the file-backed ledger could not be built without a profile identity
|
|
74
|
+
* (N2). Unlike the normal legacy hint, this states the fail-closed fact and how
|
|
75
|
+
* to fix it — it must never masquerade as a normal legacy state.
|
|
76
|
+
*/
|
|
77
|
+
export const PROFILE_IDENTITY_STATUS_HINT = [
|
|
78
|
+
'profile 身份不可用 → opencode-go 迁移记录与账本已 fail-closed(未读未写,同步已跳过);',
|
|
79
|
+
'修复:在 dsh profile 内启动插件,或向 ctx.launchEnvironment 暴露 DSH_PROFILE / DSH_PROFILE_DIR',
|
|
80
|
+
].join(' ')
|
|
81
|
+
|
|
82
|
+
/** Prefix one opaque models-store slot with the profile dimension. */
|
|
83
|
+
export function scopedStoreKey(profileKey: string, key: string): string {
|
|
84
|
+
return `${profileKey}#${key}`
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Base name of the opencode-go migration record slot (shared with migration.ts). */
|
|
88
|
+
export const GO_MIGRATION_STORE_KEY_BASE = 'migration:opencode-go'
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* True only for an UNSCOPED legacy opaque key left in the shared store — one
|
|
92
|
+
* that carries NO profile dimension and whose ownership is therefore unknown.
|
|
93
|
+
*
|
|
94
|
+
* Explicit key shapes (design §6.1 / §14.1):
|
|
95
|
+
* `<profileKey>#<route>#<keyFingerprint>` → scoped ownership (3 parts) — NOT legacy.
|
|
96
|
+
* `<profileKey>#migration:opencode-go` → scoped migration record (2 parts,
|
|
97
|
+
* tail = base name) — NOT legacy.
|
|
98
|
+
* `<route>#<keyFingerprint>` → unscoped legacy ownership (2 parts) — legacy.
|
|
99
|
+
* `migration:opencode-go` → unscoped legacy migration (1 part),
|
|
100
|
+
* reported by the caller explicitly.
|
|
101
|
+
*
|
|
102
|
+
* Such keys are reported, never read or claimed. Scoped keys are NEVER legacy,
|
|
103
|
+
* regardless of how many '#' they contain.
|
|
104
|
+
*/
|
|
105
|
+
export function isUnscopedStoreKey(key: string): boolean {
|
|
106
|
+
const parts = key.split('#')
|
|
107
|
+
if (parts.length !== 2) return false
|
|
108
|
+
const [prefix, tail] = parts
|
|
109
|
+
if (prefix.length === 0 || tail.length === 0) return false
|
|
110
|
+
// A two-part key whose tail is the migration base name is a profile-scoped
|
|
111
|
+
// migration record, not a legacy key. Only other two-part keys (an unscoped
|
|
112
|
+
// `<route>#<keyFingerprint>` ownership slot) are legacy.
|
|
113
|
+
return tail !== GO_MIGRATION_STORE_KEY_BASE
|
|
114
|
+
}
|