@aiwayds/dsh-model-sync 0.8.0 → 0.10.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/LICENSE +202 -0
- package/README.md +9 -4
- package/README.zh-CN.md +9 -4
- package/lib/builtin-catalog-snapshot.d.ts +5 -1
- package/lib/builtin-catalog-snapshot.js +13 -10
- package/lib/builtin-catalog-snapshot.js.map +1 -1
- package/lib/index.d.ts +366 -0
- package/lib/index.js +729 -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-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 +37 -0
- package/lib/remote-catalog.js +261 -3
- package/lib/remote-catalog.js.map +1 -1
- package/package.json +18 -18
- package/src/builtin-catalog-snapshot.ts +18 -11
- package/src/index.ts +873 -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-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 +293 -3
package/lib/index.js
CHANGED
|
@@ -22,12 +22,35 @@ import { translateEntries, } from "./translate.js";
|
|
|
22
22
|
import { syncToSettings, } from "./writer.js";
|
|
23
23
|
import { BUILTIN_CATALOG_SNAPSHOT } from "./builtin-catalog-snapshot.js";
|
|
24
24
|
import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from "./live-catalog.js";
|
|
25
|
-
import { checkRouteCredential } from "./route-credential.js";
|
|
25
|
+
import { checkRouteCredential, deriveKeyRef } from "./route-credential.js";
|
|
26
|
+
import { OPENCODE_GO_MODELS_URL, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, fetchGoOfficialModels, fetchGoPublicCatalogIds, fingerprintKey } from "./opencode-go-source.js";
|
|
27
|
+
import { GO_SLOT_ROUTES } from "./opencode-go-grouping.js";
|
|
28
|
+
import { createModelsStoreOwnershipStore } from "./opencode-go-store.js";
|
|
29
|
+
import { createModelsStoreJournalStore, } from "./opencode-go-journal.js";
|
|
30
|
+
import { GO_FETCH_SERVICE, GO_OWNERSHIP_STORE_SERVICE, GO_OVERRIDE_STORER_SERVICE, runGoSyncRound, } from "./opencode-go-sync.js";
|
|
31
|
+
import { GO_SCHEDULER_RANDOM_SERVICE, GO_SCHEDULER_TIMERS_SERVICE, GoScheduler, } from "./opencode-go-scheduler.js";
|
|
26
32
|
import { PROVIDER_NATIVE_ENDPOINTS, fetchProviderNativeModels, mergeProviderNativeEntries, resolveRouteCredentialValue, } from "./provider-native.js";
|
|
27
33
|
import { runLegacySettingsImport, resolveDshHome, } from "./legacy-import.js";
|
|
34
|
+
import { runGoDiagnostic, formatGoDiagnosticReport } from "./opencode-go-diagnose.js";
|
|
35
|
+
import { PROFILE_IDENTITY_REQUIRED_MESSAGE, PROFILE_IDENTITY_STATUS_HINT, resolveProfileKey, } from "./opencode-go-profile.js";
|
|
36
|
+
import { GO_MIGRATION_STORE_SERVICE, appliedFingerprintFieldsOf, createModelsStoreMigrationStateStore, goLedgerManagedIds, isGoRoute, MIGRATION_GATE_HINT, migrationStatusOf, readGoProviderSections, routeWriter, unclaimedRecordState, } from "./opencode-go-migration.js";
|
|
37
|
+
import { goOwnershipKey } from "./opencode-go-planner.js";
|
|
38
|
+
import { applyMigration, buildMigrationPlanFromDeps, formatMigrationPlan, migrationStatusReport, rollbackMigration, } from "./opencode-go-migrate.js";
|
|
28
39
|
export const name = 'dsh-model-sync';
|
|
29
40
|
/** The settings seam this plugin consumes (its own config namespace). */
|
|
30
41
|
export const inject = ['settings'];
|
|
42
|
+
/** P1d-2 seams: injected official entries (plan/apply) and optional reference writer. */
|
|
43
|
+
export const GO_MIGRATION_ENTRIES_SERVICE = 'goMigrationEntries';
|
|
44
|
+
export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter';
|
|
45
|
+
/** Public (unauthenticated) official catalog ids for id classification (design §14.2).
|
|
46
|
+
* `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
|
|
47
|
+
export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog';
|
|
48
|
+
/** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
|
|
49
|
+
export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled';
|
|
50
|
+
/** Optional override for the single-flight check (tests inject an in-flight mutex). */
|
|
51
|
+
export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex';
|
|
52
|
+
/** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
|
|
53
|
+
export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore';
|
|
31
54
|
// dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
|
|
32
55
|
// is gone, and a plugin's settings form is projected from its exported
|
|
33
56
|
// `Config` schema — the namespace IS the profile entry id. The bundle patch
|
|
@@ -86,6 +109,48 @@ export const Config = z.object({
|
|
|
86
109
|
* a re-emitted retired id is a model the 0.1.7 host no longer resolves.
|
|
87
110
|
*/
|
|
88
111
|
keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
|
|
112
|
+
/**
|
|
113
|
+
* OpenCode Go / Zen configuration contract (design §6.2.6). Published in one
|
|
114
|
+
* Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
|
|
115
|
+
* intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
|
|
116
|
+
* (go.routes/adoptExisting/pinnedModels/confirmRemovals,
|
|
117
|
+
* zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
|
|
118
|
+
* `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
|
|
119
|
+
* impossible. Zen stays login-only with no modelsUrl by default (design A5).
|
|
120
|
+
* Nested leaves are `.volatile()` (host settings can edit them); the parent
|
|
121
|
+
* objects are not, because schemastery forbids a volatile field under an
|
|
122
|
+
* enclosing volatile field.
|
|
123
|
+
*/
|
|
124
|
+
opencode: z.object({
|
|
125
|
+
go: z.object({
|
|
126
|
+
enabled: z.boolean().default(false).volatile(),
|
|
127
|
+
ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
|
|
128
|
+
modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
|
|
129
|
+
intervalMinutes: z.number().step(1).min(15).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
|
|
130
|
+
adoptExisting: z.boolean().default(false).volatile(),
|
|
131
|
+
pinnedModels: z.array(z.string()).default([]).volatile(),
|
|
132
|
+
routes: z.object({
|
|
133
|
+
chat: z.string().default('opencode-go').volatile(),
|
|
134
|
+
msg: z.string().default('opencode-go-msg').volatile(),
|
|
135
|
+
resp: z.string().default('opencode-go-resp').volatile(),
|
|
136
|
+
google: z.string().default('opencode-go-google').volatile(),
|
|
137
|
+
}).default({}),
|
|
138
|
+
confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
|
|
139
|
+
}).default({}),
|
|
140
|
+
zen: z.object({
|
|
141
|
+
enabled: z.boolean().default(true).volatile(),
|
|
142
|
+
ref: z.string().default('OPENCODE_API_KEY').volatile(),
|
|
143
|
+
mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
|
|
144
|
+
/** No proven listing endpoint; without it routes mode is unsupported. */
|
|
145
|
+
modelsUrl: z.string().volatile(),
|
|
146
|
+
seedFromBuiltin: z.boolean().default(false).volatile(),
|
|
147
|
+
routes: z.object({
|
|
148
|
+
chat: z.string().default('opencode-zen').volatile(),
|
|
149
|
+
msg: z.string().default('opencode-zen-msg').volatile(),
|
|
150
|
+
resp: z.string().default('opencode-zen-resp').volatile(),
|
|
151
|
+
}).default({}),
|
|
152
|
+
}).default({}),
|
|
153
|
+
}).default({}),
|
|
89
154
|
});
|
|
90
155
|
/**
|
|
91
156
|
* Default routes to manage when managedRoutes is empty.
|
|
@@ -106,12 +171,255 @@ const DEFAULT_ROUTES = [
|
|
|
106
171
|
* the plugin syncs when `managedRoutes` is empty. Not part of the public
|
|
107
172
|
* runtime surface; subject to change without notice. */
|
|
108
173
|
export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES;
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// P1c go config / dependency helpers (design §6.2.6)
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
/** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
|
|
178
|
+
function readVolatile(slot, fallback) {
|
|
179
|
+
if (slot === undefined)
|
|
180
|
+
return fallback;
|
|
181
|
+
if (typeof slot === 'object' && slot !== null && typeof slot.get === 'function') {
|
|
182
|
+
return slot.get();
|
|
183
|
+
}
|
|
184
|
+
return slot;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Project the go Config subset for one round. Reads the live volatile refs, so
|
|
188
|
+
* a settings edit takes effect on the next round without a remount. The
|
|
189
|
+
* defensive shape also keeps older/partial fake configs (no `opencode` block)
|
|
190
|
+
* on the default zero-behavior path instead of throwing during apply().
|
|
191
|
+
*/
|
|
192
|
+
function readGoRuntimeConfig(config) {
|
|
193
|
+
const raw = config;
|
|
194
|
+
const opencode = raw.opencode;
|
|
195
|
+
const go = opencode?.go;
|
|
196
|
+
const rawRoutes = go?.routes;
|
|
197
|
+
const routes = Object.fromEntries(Object.keys(GO_SLOT_ROUTES).map((slot) => [
|
|
198
|
+
slot,
|
|
199
|
+
readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
|
|
200
|
+
]));
|
|
201
|
+
return {
|
|
202
|
+
enabled: readVolatile(go?.enabled, false),
|
|
203
|
+
value: {
|
|
204
|
+
enabled: readVolatile(go?.enabled, false),
|
|
205
|
+
ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
|
|
206
|
+
modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
|
|
207
|
+
routes,
|
|
208
|
+
pinnedModels: readVolatile(go?.pinnedModels, []),
|
|
209
|
+
confirmRemovals: readVolatile(go?.confirmRemovals, 2),
|
|
210
|
+
adoptExisting: readVolatile(go?.adoptExisting, false),
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
|
|
216
|
+
* field (default 60, floor 15, enforced by the scheduler); the startup delay is
|
|
217
|
+
* the shared top-level field the design names for startup jitter.
|
|
218
|
+
*
|
|
219
|
+
* `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
|
|
220
|
+
* Migration zero-write is now enforced independently by routeWriter (§14.6 /
|
|
221
|
+
* §14.7) on every write path, so this default is a product choice, not the
|
|
222
|
+
* only protection. All scheduler paths are still gated by this value.
|
|
223
|
+
*/
|
|
224
|
+
function readGoSchedulerConfig(config) {
|
|
225
|
+
const raw = config;
|
|
226
|
+
const opencode = raw.opencode;
|
|
227
|
+
const go = opencode?.go;
|
|
228
|
+
return {
|
|
229
|
+
enabled: readVolatile(go?.enabled, false),
|
|
230
|
+
intervalMinutes: readVolatile(go?.intervalMinutes, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES),
|
|
231
|
+
startupDelaySeconds: readVolatile(raw.startupDelaySeconds, 5),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
|
|
236
|
+
* the live descriptor after a mutate, so the marker always holds the revision
|
|
237
|
+
* the host stamped on OUR write; a later event for the same ns+revision can
|
|
238
|
+
* only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
|
|
239
|
+
* never depend on a wall clock.
|
|
240
|
+
*/
|
|
241
|
+
function createOwnWriteTracker(readRevision, now) {
|
|
242
|
+
let last;
|
|
243
|
+
const tracker = {
|
|
244
|
+
record(ns) {
|
|
245
|
+
const revision = readRevision(ns);
|
|
246
|
+
if (revision !== undefined)
|
|
247
|
+
last = { ns, revision, at: now() };
|
|
248
|
+
},
|
|
249
|
+
matches(ns, eventRevision) {
|
|
250
|
+
if (last === undefined || last.ns !== ns)
|
|
251
|
+
return false;
|
|
252
|
+
if (eventRevision !== undefined)
|
|
253
|
+
return eventRevision === last.revision;
|
|
254
|
+
const current = readRevision(ns);
|
|
255
|
+
return current !== undefined && current === last.revision;
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
return tracker;
|
|
259
|
+
}
|
|
260
|
+
function settingsRevision(settings, ns) {
|
|
261
|
+
return settings?.describe().find((desc) => desc.ns === ns)?.revision;
|
|
262
|
+
}
|
|
109
263
|
export async function apply(ctx, config) {
|
|
110
264
|
// On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
|
|
111
265
|
// every volatile field is a stable reference (see VolatileRef), so the
|
|
112
266
|
// reads below are live views — no scope.get() and no scope.watch() (both
|
|
113
267
|
// removed from dsh-settings; the hot-reload notification moved to the
|
|
114
268
|
// settings/document-updated event, subscribed at the bottom of apply()).
|
|
269
|
+
// P1d-1: one reentry marker shared by every write path. `rawSettings()` is
|
|
270
|
+
// resolved per call so a host that mounts the settings service after this
|
|
271
|
+
// plugin still works; the thin wrapper records the post-mutate revision for
|
|
272
|
+
// the document-updated reentry check (§14.7.2). Every settings-writing path
|
|
273
|
+
// below goes through `settingsForWrite*` — never a bare ctx.get('settings').
|
|
274
|
+
const rawSettings = () => ctx.get('settings');
|
|
275
|
+
const ownWrite = createOwnWriteTracker((ns) => settingsRevision(rawSettings(), ns), () => Date.now());
|
|
276
|
+
const settingsForWriteFrom = (context) => {
|
|
277
|
+
const raw = context.get('settings');
|
|
278
|
+
if (raw === undefined)
|
|
279
|
+
return undefined;
|
|
280
|
+
return {
|
|
281
|
+
describe: () => raw.describe(),
|
|
282
|
+
mutate: async (ns, ops, expectedRevision) => {
|
|
283
|
+
await raw.mutate(ns, ops, expectedRevision);
|
|
284
|
+
ownWrite.record(ns);
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
const settingsForWrite = () => settingsForWriteFrom(ctx);
|
|
289
|
+
// B1/H9: one stable profile identity per plugin instance, resolved from the
|
|
290
|
+
// host (profileContext / DSH_PROFILE). Both file-backed stores below scope
|
|
291
|
+
// every shared models-store key with it so two profiles cannot share a
|
|
292
|
+
// migration record or ownership ledger entry. When no identity can be
|
|
293
|
+
// resolved there is NO 'default' collapse: every file-backed ledger path
|
|
294
|
+
// fails closed with an actionable error instead of silently sharing a key.
|
|
295
|
+
const profileKey = resolveProfileKey(ctx);
|
|
296
|
+
const requireScopedProfileKey = () => {
|
|
297
|
+
if (profileKey === undefined)
|
|
298
|
+
throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE);
|
|
299
|
+
return profileKey;
|
|
300
|
+
};
|
|
301
|
+
// The injection seam is an explicit opt-in (tests / hosts that supply their
|
|
302
|
+
// own scoped store); only the file-backed fallback requires host identity.
|
|
303
|
+
const migrationStore = () => ctx.get(GO_MIGRATION_STORE_SERVICE)
|
|
304
|
+
?? createModelsStoreMigrationStateStore(undefined, requireScopedProfileKey());
|
|
305
|
+
const ownershipStoreForRound = () => ctx.get(GO_OWNERSHIP_STORE_SERVICE)
|
|
306
|
+
?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey());
|
|
307
|
+
// O1/C2: the journal lives in the same models-store.json. An injected seam
|
|
308
|
+
// wins (tests use a temp-dir accessor); without a resolved profile identity
|
|
309
|
+
// there is NO journal — never fall back to the real default ~/.dsh from a
|
|
310
|
+
// host/test that supplied no identity (the ledger path fails closed too).
|
|
311
|
+
const journalStoreForRound = () => ctx.get(GO_JOURNAL_STORE_SERVICE)
|
|
312
|
+
?? (profileKey === undefined ? undefined : createModelsStoreJournalStore());
|
|
313
|
+
/**
|
|
314
|
+
* Read current migration status from the persisted record + live settings +
|
|
315
|
+
* (when a key fingerprint is available) the live ownership ledger.
|
|
316
|
+
* `strict` rethrows a record read failure so the §14.7.5 second gate can fail
|
|
317
|
+
* closed with `canWrite-unavailable`; the normal path degrades to "no record"
|
|
318
|
+
* (conservative legacy detection) as before.
|
|
319
|
+
*/
|
|
320
|
+
const loadMigrationStatus = async (opts = {}) => {
|
|
321
|
+
const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
|
|
322
|
+
// H9 fail-closed: with no resolvable profile identity the file-backed store
|
|
323
|
+
// factory throws. A non-strict READ degrades to "no record" (gate closed,
|
|
324
|
+
// zero writes) so boot-time status refreshes / isApplying cannot produce an
|
|
325
|
+
// unhandled rejection; strict reads (the per-mutate second gate) rethrow.
|
|
326
|
+
// Every WRITE path still fails closed when it builds its file-backed store.
|
|
327
|
+
// N2: remember an identity-refused file-backed store so the (non-strict)
|
|
328
|
+
// status read can surface it instead of looking like a normal legacy state.
|
|
329
|
+
// The check is on the thrown identity error, not on `profileKey === undefined`
|
|
330
|
+
// alone: an injected-store host has a usable ledger even with no host
|
|
331
|
+
// identity and must NOT get a false "identity unavailable" report.
|
|
332
|
+
let identityUnavailable = false;
|
|
333
|
+
let store;
|
|
334
|
+
try {
|
|
335
|
+
store = migrationStore();
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
if (opts.strict === true)
|
|
339
|
+
throw err;
|
|
340
|
+
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
|
|
341
|
+
identityUnavailable = true;
|
|
342
|
+
}
|
|
343
|
+
let record;
|
|
344
|
+
try {
|
|
345
|
+
record = await store?.read();
|
|
346
|
+
}
|
|
347
|
+
catch (err) {
|
|
348
|
+
if (opts.strict === true)
|
|
349
|
+
throw err;
|
|
350
|
+
record = undefined; // unreadable ⇒ conservative legacy detection
|
|
351
|
+
}
|
|
352
|
+
const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {});
|
|
353
|
+
let managedIds;
|
|
354
|
+
const fp = opts.keyFingerprint;
|
|
355
|
+
if (fp !== undefined) {
|
|
356
|
+
let ownership;
|
|
357
|
+
try {
|
|
358
|
+
ownership = ownershipStoreForRound();
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
if (opts.strict === true)
|
|
362
|
+
throw err;
|
|
363
|
+
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
|
|
364
|
+
identityUnavailable = true;
|
|
365
|
+
}
|
|
366
|
+
// Only routes with a REAL ledger entry join the fingerprint set. The old
|
|
367
|
+
// `<route>: []` filler for configured-but-absent routes disagreed with
|
|
368
|
+
// migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
|
|
369
|
+
// first healthy round after onboarding.
|
|
370
|
+
managedIds = await goLedgerManagedIds(goRoutes, (route) => ownership === undefined
|
|
371
|
+
? Promise.resolve(undefined)
|
|
372
|
+
: ownership.read(goOwnershipKey(route, fp)));
|
|
373
|
+
}
|
|
374
|
+
const status = migrationStatusOf(desc, record, goRoutes, managedIds);
|
|
375
|
+
// W1/D6: the go report and `migrate status` must agree on the label for a
|
|
376
|
+
// record this profile cannot claim. Use the SAME helper as migrate status;
|
|
377
|
+
// only when our own scoped read() found no record (B1 isolation). This is
|
|
378
|
+
// label-only: both states already keep the gate closed / write authority
|
|
379
|
+
// none / zero writes, and nothing is claimed or deleted.
|
|
380
|
+
if (record === undefined && store?.unclaimedRecords !== undefined) {
|
|
381
|
+
let unclaimed;
|
|
382
|
+
try {
|
|
383
|
+
unclaimed = await store.unclaimedRecords();
|
|
384
|
+
}
|
|
385
|
+
catch (err) {
|
|
386
|
+
if (opts.strict === true)
|
|
387
|
+
throw err;
|
|
388
|
+
unclaimed = []; // advisory provenance scan never changes the gate
|
|
389
|
+
}
|
|
390
|
+
const recordState = unclaimedRecordState(unclaimed);
|
|
391
|
+
if (recordState !== undefined)
|
|
392
|
+
status.state = recordState;
|
|
393
|
+
}
|
|
394
|
+
// N2: a non-strict refresh that degraded because no identity was available
|
|
395
|
+
// must be VISIBLE — log the actionable error (covers boot / document-updated
|
|
396
|
+
// refresh where there is no report line) and tag the status so sync reports
|
|
397
|
+
// do not show the normal legacy hint. This changes NO write/fail-closed
|
|
398
|
+
// behavior: the gate is already closed and no store/settings write occurs.
|
|
399
|
+
if (identityUnavailable) {
|
|
400
|
+
status.identityUnavailable = true;
|
|
401
|
+
ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE);
|
|
402
|
+
}
|
|
403
|
+
// §14.7.4 self-heal: identity matches but the stored full fingerprint is
|
|
404
|
+
// stale because the fingerprint persist failed after settings+ledger landed.
|
|
405
|
+
// Rewrite it in the same queue instead of closing the gate forever.
|
|
406
|
+
if (status.fingerprintHealed && typeof store?.write === 'function') {
|
|
407
|
+
try {
|
|
408
|
+
ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)');
|
|
409
|
+
await store.write({
|
|
410
|
+
...(record ?? {}),
|
|
411
|
+
appliedManagedIds: managedIds ?? record?.appliedManagedIds,
|
|
412
|
+
appliedFingerprint: status.expectedFingerprint,
|
|
413
|
+
});
|
|
414
|
+
status.appliedFingerprint = status.expectedFingerprint;
|
|
415
|
+
status.fingerprintHealed = false;
|
|
416
|
+
}
|
|
417
|
+
catch (err) {
|
|
418
|
+
ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return status;
|
|
422
|
+
};
|
|
115
423
|
// -----------------------------------------------------------------------
|
|
116
424
|
// Overlay mode sync (existing behavior)
|
|
117
425
|
// -----------------------------------------------------------------------
|
|
@@ -181,7 +489,7 @@ export async function apply(ctx, config) {
|
|
|
181
489
|
// Settings mode sync (Plan C: fetch → translate → write)
|
|
182
490
|
// -----------------------------------------------------------------------
|
|
183
491
|
const syncSettings = async (config, force) => {
|
|
184
|
-
const settings =
|
|
492
|
+
const settings = settingsForWrite();
|
|
185
493
|
const logger = ctx.logger;
|
|
186
494
|
const store = loadModelsStore();
|
|
187
495
|
const lines = [];
|
|
@@ -190,9 +498,35 @@ export async function apply(ctx, config) {
|
|
|
190
498
|
const routes = managedRoutes.length > 0
|
|
191
499
|
? [...managedRoutes]
|
|
192
500
|
: DEFAULT_ROUTES;
|
|
501
|
+
// P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
|
|
502
|
+
// path must NEVER write an `opencode-go*` route — not even in `absent` /
|
|
503
|
+
// `applied` state (that belongs to go sync), and especially not when the
|
|
504
|
+
// migration gate is closed. Login-triggered/manual/auto all funnel through
|
|
505
|
+
// this one loop (design §14.7.1, ADR-008).
|
|
506
|
+
const { value: goCfg } = readGoRuntimeConfig(config);
|
|
507
|
+
const goRouteIds = Object.values(goCfg.routes ?? {});
|
|
508
|
+
const piDevAuthority = { caller: 'pi.dev', goEnabled: goCfg.enabled, goRoutes: goRouteIds };
|
|
509
|
+
let piDevMigration;
|
|
193
510
|
const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
|
|
194
511
|
const gateCtx = ctx;
|
|
195
512
|
for (const route of routes) {
|
|
513
|
+
// Single-writer gate before ANY fetch/translate/mutate for go routes.
|
|
514
|
+
// A skip always produces a report line (never silent, §14.7.1).
|
|
515
|
+
if (goCfg.enabled && isGoRoute(route, goRouteIds)) {
|
|
516
|
+
piDevMigration ??= await loadMigrationStatus();
|
|
517
|
+
const decision = routeWriter(route, piDevAuthority, piDevMigration);
|
|
518
|
+
if (decision.decision === 'skip') {
|
|
519
|
+
// N2: an identity-refused ledger is NOT a normal legacy state. Surface
|
|
520
|
+
// the actionable identity hint instead of the generic migration hint.
|
|
521
|
+
const hint = piDevMigration.identityUnavailable === true
|
|
522
|
+
? `; ${PROFILE_IDENTITY_STATUS_HINT}`
|
|
523
|
+
: (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
|
|
524
|
+
? ''
|
|
525
|
+
: `; ${MIGRATION_GATE_HINT}`);
|
|
526
|
+
lines.push(`${route}: skipped — ${decision.reason}${hint}`);
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
196
530
|
// Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
|
|
197
531
|
// Layer 2 follows its authContextFrom(ctx).env(): launch environment,
|
|
198
532
|
// or process.env when the service is absent. Both miss → skip fetch,
|
|
@@ -373,6 +707,281 @@ export async function apply(ctx, config) {
|
|
|
373
707
|
}
|
|
374
708
|
return syncOverlay(config, llm, force);
|
|
375
709
|
};
|
|
710
|
+
// -----------------------------------------------------------------------
|
|
711
|
+
// P1c go round: source → planner → writer, all deps from cordis seams.
|
|
712
|
+
// P1c-2 wraps this in the scheduler below; the round itself still owns no
|
|
713
|
+
// timer and no command registration.
|
|
714
|
+
// -----------------------------------------------------------------------
|
|
715
|
+
const runGoRound = async (options = {}) => {
|
|
716
|
+
const { value } = readGoRuntimeConfig(config);
|
|
717
|
+
const settings = settingsForWrite();
|
|
718
|
+
const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
|
|
719
|
+
const apiKey = await resolveRouteCredentialValue(ctx, desc, 'opencode-go', value.ref);
|
|
720
|
+
// The ledger is keyed by the same credential fingerprint the source uses;
|
|
721
|
+
// deriving it here lets the status read include the live managed-id set.
|
|
722
|
+
const keyFingerprint = fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : '');
|
|
723
|
+
const migration = await loadMigrationStatus({ keyFingerprint });
|
|
724
|
+
const ownershipStore = ownershipStoreForRound();
|
|
725
|
+
// The existing models-store accessor already satisfies GoOverrideStorer
|
|
726
|
+
// (read(route).overrides + updateOverrides); the service seam lets tests
|
|
727
|
+
// point both stores at a temp dir instead of the real ~/.dsh.
|
|
728
|
+
const overrideStorer = ctx.get(GO_OVERRIDE_STORER_SERVICE)
|
|
729
|
+
?? loadModelsStore();
|
|
730
|
+
return runGoSyncRound({
|
|
731
|
+
settings,
|
|
732
|
+
ownershipStore,
|
|
733
|
+
overrideStorer,
|
|
734
|
+
logger: ctx.logger,
|
|
735
|
+
// The explicit `adopt` command honours the master switch: disabled means
|
|
736
|
+
// zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
|
|
737
|
+
config: options.adopt === true ? { ...value, adoptExisting: true } : value,
|
|
738
|
+
apiKey,
|
|
739
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE),
|
|
740
|
+
signal: options.signal,
|
|
741
|
+
migration,
|
|
742
|
+
// O1/C2: journal + reconciliation use the same profile/fingerprint as the
|
|
743
|
+
// ledger. Reconciliation runs before the gate inside runGoSyncRound.
|
|
744
|
+
journalStore: journalStoreForRound(),
|
|
745
|
+
profileKey,
|
|
746
|
+
keyFingerprint,
|
|
747
|
+
// §14.7.5: the second gate re-reads the persisted record on each mutate
|
|
748
|
+
// (strict: a failed read skips the route with canWrite-unavailable).
|
|
749
|
+
reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
|
|
750
|
+
// §14.7.4: settings → ledger → fingerprint, all through the same
|
|
751
|
+
// models-store queue; only successful own writes reach this callback.
|
|
752
|
+
onOwnWrite: async (route, managedIds) => {
|
|
753
|
+
const store = migrationStore();
|
|
754
|
+
if (typeof store.write !== 'function')
|
|
755
|
+
return; // read-only injected store
|
|
756
|
+
let record;
|
|
757
|
+
try {
|
|
758
|
+
record = await store.read();
|
|
759
|
+
}
|
|
760
|
+
catch {
|
|
761
|
+
return; // cannot merge safely; the next round's self-heal covers it
|
|
762
|
+
}
|
|
763
|
+
const goRoutes = Object.values(value.routes ?? {});
|
|
764
|
+
const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
|
|
765
|
+
const sections = readGoProviderSections(liveDesc, goRoutes);
|
|
766
|
+
const appliedIdentityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {});
|
|
767
|
+
const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() };
|
|
768
|
+
// Same helper + route-set convention as loadMigrationStatus: a normal
|
|
769
|
+
// onboarding/own write must not look like a fingerprint drift next round.
|
|
770
|
+
const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(sections, record, appliedManagedIds);
|
|
771
|
+
await store.write({
|
|
772
|
+
...(record ?? {}),
|
|
773
|
+
appliedIdentity: identity,
|
|
774
|
+
appliedIdentityRoutes,
|
|
775
|
+
appliedManagedIds,
|
|
776
|
+
appliedFingerprint,
|
|
777
|
+
});
|
|
778
|
+
},
|
|
779
|
+
});
|
|
780
|
+
};
|
|
781
|
+
// -----------------------------------------------------------------------
|
|
782
|
+
// P1c-2: async timer + scheduling for the go round (design §6.3 / §14.6).
|
|
783
|
+
// One GoScheduler instance serves BOTH the timer and the manual /model-sync
|
|
784
|
+
// go command, so they share the single-flight lock. Clock and jitter inputs
|
|
785
|
+
// are optional cordis services so tests never arm a real timer.
|
|
786
|
+
// -----------------------------------------------------------------------
|
|
787
|
+
const goTimers = ctx.get(GO_SCHEDULER_TIMERS_SERVICE) ?? {
|
|
788
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
789
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
790
|
+
};
|
|
791
|
+
const goRandom = ctx.get(GO_SCHEDULER_RANDOM_SERVICE)
|
|
792
|
+
?? { next: () => Math.random() };
|
|
793
|
+
const goScheduler = new GoScheduler({
|
|
794
|
+
config: () => readGoSchedulerConfig(config),
|
|
795
|
+
timers: goTimers,
|
|
796
|
+
random: goRandom,
|
|
797
|
+
runRound: async ({ adopt, signal }) => {
|
|
798
|
+
const round = await runGoRound({ adopt, signal });
|
|
799
|
+
return {
|
|
800
|
+
ok: round.ok,
|
|
801
|
+
reason: round.reason,
|
|
802
|
+
text: round.text,
|
|
803
|
+
failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
|
|
804
|
+
? round.source.error.kind
|
|
805
|
+
: undefined,
|
|
806
|
+
};
|
|
807
|
+
},
|
|
808
|
+
report: (text) => {
|
|
809
|
+
for (const line of text.split('\n'))
|
|
810
|
+
ctx.logger.info('model-sync: %s', line);
|
|
811
|
+
},
|
|
812
|
+
// M-5: drop (never queue) any round while a migration apply holds the routes.
|
|
813
|
+
isApplying: async () => (await loadMigrationStatus()).applying,
|
|
814
|
+
});
|
|
815
|
+
ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose');
|
|
816
|
+
// A changed credential invalidates any accumulated backoff: a fixed key must
|
|
817
|
+
// retry on the normal schedule instead of waiting out a capped 6h backoff
|
|
818
|
+
// (design §6.3). The effect scopes the listener to this plugin's lifetime —
|
|
819
|
+
// unload removes it together with the scheduler.
|
|
820
|
+
ctx.effect(() => ctx.on('credentials/reference-updated', (ref) => {
|
|
821
|
+
if (typeof ref !== 'string')
|
|
822
|
+
return;
|
|
823
|
+
const { value } = readGoRuntimeConfig(config);
|
|
824
|
+
if (ref !== value.ref)
|
|
825
|
+
return;
|
|
826
|
+
goScheduler.resetBackoff();
|
|
827
|
+
}), 'dsh-model-sync: credentials/reference-updated → go backoff reset');
|
|
828
|
+
goScheduler.start();
|
|
829
|
+
/** Resolve the official listing through an injectable seam (tests: a fixture array). */
|
|
830
|
+
const resolveMigrateEntries = async (value, apiKey) => {
|
|
831
|
+
const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE);
|
|
832
|
+
if (Array.isArray(injected))
|
|
833
|
+
return injected;
|
|
834
|
+
if (typeof injected === 'function')
|
|
835
|
+
return await injected();
|
|
836
|
+
const source = await fetchGoOfficialModels({
|
|
837
|
+
url: value.modelsUrl,
|
|
838
|
+
apiKey,
|
|
839
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE),
|
|
840
|
+
timeoutMs: config.refreshTimeoutMs.get(),
|
|
841
|
+
});
|
|
842
|
+
if (!source.ok) {
|
|
843
|
+
throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`);
|
|
844
|
+
}
|
|
845
|
+
return source.entries;
|
|
846
|
+
};
|
|
847
|
+
/**
|
|
848
|
+
* Public-catalog producer for id classification (§14.2): ids the current key
|
|
849
|
+
* cannot serve but that are still official are `unknown-retired`, everything
|
|
850
|
+
* else is `user-extra`. When the public list cannot be fetched the result is
|
|
851
|
+
* `undefined`, which makes the plan mark such ids `unclassified` (never
|
|
852
|
+
* deleted) instead of defaulting them to deletable `user-extra`.
|
|
853
|
+
*/
|
|
854
|
+
const resolvePublicCatalogIds = async (value, entries) => {
|
|
855
|
+
const injected = ctx.get(GO_MIGRATION_PUBLIC_CATALOG_SERVICE);
|
|
856
|
+
if (Array.isArray(injected))
|
|
857
|
+
return injected;
|
|
858
|
+
if (typeof injected === 'function')
|
|
859
|
+
return await injected();
|
|
860
|
+
// Offline fixture mode: the injected authorized entries are the only catalog
|
|
861
|
+
// available; deriving ids from them keeps `migrate plan` zero-fetch (V16).
|
|
862
|
+
if (ctx.get(GO_MIGRATION_ENTRIES_SERVICE) !== undefined)
|
|
863
|
+
return entries.map((entry) => entry.id);
|
|
864
|
+
const result = await fetchGoPublicCatalogIds({
|
|
865
|
+
url: value.modelsUrl,
|
|
866
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE),
|
|
867
|
+
timeoutMs: config.refreshTimeoutMs.get(),
|
|
868
|
+
});
|
|
869
|
+
return result.ok ? result.ids : undefined;
|
|
870
|
+
};
|
|
871
|
+
const migrateDeps = async (target, opts = {}, needsEntries = true) => {
|
|
872
|
+
const { value } = readGoRuntimeConfig(config);
|
|
873
|
+
const settings = settingsForWriteFrom(target);
|
|
874
|
+
const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
|
|
875
|
+
const apiKey = await resolveRouteCredentialValue(target, desc, 'opencode-go', value.ref);
|
|
876
|
+
const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE);
|
|
877
|
+
// Keep the pre-action-table evaluation order: the file-backed stores fail
|
|
878
|
+
// closed without a profile identity, and must do so BEFORE any source
|
|
879
|
+
// fetch (D4: no identity ⇒ zero outbound requests, zero writes).
|
|
880
|
+
const ownershipStore = target.get(GO_OWNERSHIP_STORE_SERVICE)
|
|
881
|
+
?? ownershipStoreForRound();
|
|
882
|
+
const store = migrationStore();
|
|
883
|
+
// status/rollback never need the official listing: no fetch, no extra I/O.
|
|
884
|
+
const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : [];
|
|
885
|
+
const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined;
|
|
886
|
+
const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
|
|
887
|
+
|| settings === undefined || typeof settings.mutate !== 'function';
|
|
888
|
+
return {
|
|
889
|
+
settings,
|
|
890
|
+
ownershipStore,
|
|
891
|
+
migrationStore: store,
|
|
892
|
+
logger: target.logger,
|
|
893
|
+
entries,
|
|
894
|
+
publicCatalogIds,
|
|
895
|
+
routes: value.routes,
|
|
896
|
+
ref: value.ref,
|
|
897
|
+
keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
|
|
898
|
+
adopt: opts.adopt,
|
|
899
|
+
adoptDisabled,
|
|
900
|
+
rewriteRefs: opts.rewriteRefs,
|
|
901
|
+
// Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
|
|
902
|
+
pinnedModels: value.pinnedModels,
|
|
903
|
+
pruneUserExtra: opts.pruneUserExtra,
|
|
904
|
+
now: Date.now(),
|
|
905
|
+
isSyncInFlight: ctx.get(GO_MIGRATION_MUTEX_SERVICE)
|
|
906
|
+
?? (() => goScheduler.isInFlight),
|
|
907
|
+
applyReferenceRewrite: refWriter,
|
|
908
|
+
// O1/C2: apply/rollback clear this profile's journals so a stale slot
|
|
909
|
+
// cannot re-account settings that the migration just rewrote or undid.
|
|
910
|
+
journalStore: journalStoreForRound(),
|
|
911
|
+
profileKey,
|
|
912
|
+
};
|
|
913
|
+
};
|
|
914
|
+
/** Shared by the slash command and the `modelSync` host service (§14.5). */
|
|
915
|
+
const runMigrate = async (args, target) => {
|
|
916
|
+
const usage = [
|
|
917
|
+
'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
|
|
918
|
+
' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
|
|
919
|
+
' /model-sync migrate rollback --plan <planHash>',
|
|
920
|
+
' /model-sync migrate status',
|
|
921
|
+
].join('\n');
|
|
922
|
+
const action = args[0] ?? 'plan';
|
|
923
|
+
const rest = args.slice(1);
|
|
924
|
+
if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
|
|
925
|
+
return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` };
|
|
926
|
+
}
|
|
927
|
+
// Consent has no bypass: these flags are recognised and rejected explicitly.
|
|
928
|
+
if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
|
|
929
|
+
return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' };
|
|
930
|
+
}
|
|
931
|
+
const flagValue = (name) => {
|
|
932
|
+
const index = rest.indexOf(name);
|
|
933
|
+
if (index >= 0)
|
|
934
|
+
return rest[index + 1];
|
|
935
|
+
const inline = rest.find((token) => token.startsWith(`${name}=`));
|
|
936
|
+
return inline?.slice(name.length + 1);
|
|
937
|
+
};
|
|
938
|
+
const planHash = flagValue('--plan');
|
|
939
|
+
const confirmCode = flagValue('--confirm');
|
|
940
|
+
const adopt = rest.includes('--adopt');
|
|
941
|
+
const ackManaged = rest.includes('--ack-managed');
|
|
942
|
+
const pruneUserExtra = rest.includes('--prune-user-extra');
|
|
943
|
+
const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length);
|
|
944
|
+
const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
|
|
945
|
+
? rewriteRefsRaw
|
|
946
|
+
: undefined;
|
|
947
|
+
try {
|
|
948
|
+
if (action === 'status') {
|
|
949
|
+
const deps = await migrateDeps(target, {}, false);
|
|
950
|
+
const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled });
|
|
951
|
+
return { kind: 'success', text: report.text };
|
|
952
|
+
}
|
|
953
|
+
if (action === 'plan') {
|
|
954
|
+
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
|
|
955
|
+
const record = await deps.migrationStore.read().catch(() => undefined);
|
|
956
|
+
// Same pure builder apply uses — the printed table IS the consented one.
|
|
957
|
+
// When adopt is disabled the mode is reported as adopt-disabled and the
|
|
958
|
+
// rows stay conservative; no adopt action can be printed as executable.
|
|
959
|
+
const plan = buildMigrationPlanFromDeps(deps, record);
|
|
960
|
+
return { kind: 'success', text: formatMigrationPlan(plan) };
|
|
961
|
+
}
|
|
962
|
+
if (action === 'apply') {
|
|
963
|
+
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
|
|
964
|
+
// Fail-closed fallback (§14.2): reject at the command layer before any
|
|
965
|
+
// write when the per-id action table cannot be executed verbatim.
|
|
966
|
+
if (adopt && deps.adoptDisabled === true) {
|
|
967
|
+
return {
|
|
968
|
+
kind: 'error',
|
|
969
|
+
text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
const result = await applyMigration({ planHash, confirmCode, ackManaged }, deps);
|
|
973
|
+
return { kind: result.ok ? 'success' : 'error', text: result.text };
|
|
974
|
+
}
|
|
975
|
+
// rollback
|
|
976
|
+
const deps = await migrateDeps(target, {}, false);
|
|
977
|
+
const result = await rollbackMigration({ planHash }, deps);
|
|
978
|
+
return { kind: result.ok ? 'success' : 'error', text: result.text };
|
|
979
|
+
}
|
|
980
|
+
catch (error) {
|
|
981
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
982
|
+
return { kind: 'error', text: `migrate ${action} failed: ${message}` };
|
|
983
|
+
}
|
|
984
|
+
};
|
|
376
985
|
/** Auto rounds log the same report the /model-sync command shows. */
|
|
377
986
|
const runAuto = () => {
|
|
378
987
|
// A rejected round (service lookups mid-dispose, a refused mutate) must
|
|
@@ -408,23 +1017,42 @@ export async function apply(ctx, config) {
|
|
|
408
1017
|
// settings/document-updated event (the 0.1.7 replacement for scope.watch).
|
|
409
1018
|
startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000);
|
|
410
1019
|
armInterval(config.intervalMinutes.get() ?? 240);
|
|
411
|
-
ctx.effect(() => ctx.on('settings/document-updated', (ns) => {
|
|
412
|
-
//
|
|
413
|
-
//
|
|
414
|
-
//
|
|
415
|
-
|
|
1020
|
+
ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
|
|
1021
|
+
// P1d-1 §14.7.2: if this event is the echo of a settings.mutate we just
|
|
1022
|
+
// performed, only refresh status — schedule NO round (the V23 race was a
|
|
1023
|
+
// go write echo triggering the legacy pi.dev auto round ~1s later).
|
|
1024
|
+
if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
|
|
1025
|
+
ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision);
|
|
1026
|
+
void loadMigrationStatus(); // refresh state only; no timer, no runAuto
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
// Only this plugin's own config entry (the bundle-patch id) re-arms timers;
|
|
1030
|
+
// the handler is idempotent — the refs already carry the new values, so the
|
|
1031
|
+
// next round reads them fresh. A foreign ns (including llm-pi-ai writes by
|
|
1032
|
+
// other actors) never schedules a round here.
|
|
416
1033
|
if (ns !== OWN_ENTRY_ID)
|
|
417
1034
|
return;
|
|
418
1035
|
armInterval(config.intervalMinutes.get() ?? 0);
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
1036
|
+
// §14.7.2 item 2: remove the old "immediate +1s runAuto". Config edits now
|
|
1037
|
+
// only re-arm the normal interval; an immediate round needs an explicit
|
|
1038
|
+
// /model-sync. (P1c-2 go scheduler still re-arms idempotently.)
|
|
1039
|
+
goScheduler.rearm();
|
|
1040
|
+
void loadMigrationStatus();
|
|
423
1041
|
}), 'dsh-model-sync: settings/document-updated');
|
|
424
1042
|
// The modelSync service stays exposed for UIs that want direct access. The
|
|
425
1043
|
// /model-sync command itself is registered by this plugin (below) through
|
|
426
1044
|
// the shared command registry, which interactive UIs discover on their own.
|
|
427
|
-
ctx.provide('modelSync', {
|
|
1045
|
+
ctx.provide('modelSync', {
|
|
1046
|
+
syncNow: () => syncNow(true),
|
|
1047
|
+
migratePlan: (options) => runMigrate(['plan', ...(options?.adopt === true ? ['--adopt'] : []),
|
|
1048
|
+
...(options?.pruneUserExtra === true ? ['--prune-user-extra'] : []),
|
|
1049
|
+
...(options?.rewriteRefs !== undefined ? [`--rewrite-refs=${options.rewriteRefs}`] : [])], ctx).then((result) => result.text),
|
|
1050
|
+
migrateApply: (args) => runMigrate(['apply', ...(args.planHash !== undefined ? ['--plan', args.planHash] : []),
|
|
1051
|
+
...(args.confirmCode !== undefined ? ['--confirm', args.confirmCode] : []),
|
|
1052
|
+
...(args.ackManaged === true ? ['--ack-managed'] : [])], ctx).then((result) => result.text),
|
|
1053
|
+
migrateRollback: (args) => runMigrate(['rollback', ...(args.planHash !== undefined ? ['--plan', args.planHash] : [])], ctx).then((result) => result.text),
|
|
1054
|
+
migrateStatus: () => runMigrate(['status'], ctx).then((result) => result.text),
|
|
1055
|
+
});
|
|
428
1056
|
// Register the /model-sync slash command from the plugin itself. The
|
|
429
1057
|
// registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
|
|
430
1058
|
// human-command registry shared by interactive UI adapters") — registration
|
|
@@ -440,8 +1068,67 @@ export async function apply(ctx, config) {
|
|
|
440
1068
|
cmdCtx.effect(() => {
|
|
441
1069
|
const definition = {
|
|
442
1070
|
name: 'model-sync',
|
|
443
|
-
description: 'Force one model-list sync round from the pi.dev gateway into settings (
|
|
1071
|
+
description: 'Force one model-list sync round from the pi.dev gateway into settings; go subcommands: go|status (one full opencode-go round), adopt go; migrate plan|apply|rollback|status (explicit consent only)',
|
|
444
1072
|
handler: async (invocation) => {
|
|
1073
|
+
const args = invocation.rawInput.trim().split(/\s+/).filter((part) => part.length > 0);
|
|
1074
|
+
const [sub, scope] = args;
|
|
1075
|
+
// P1d-2: migration is the ONLY explicit-consent config writer. It is
|
|
1076
|
+
// never auto-triggered and never folded into the pi.dev sync path.
|
|
1077
|
+
if (sub === 'migrate') {
|
|
1078
|
+
return runMigrate(args.slice(1), cmdCtx);
|
|
1079
|
+
}
|
|
1080
|
+
// B3 (31 R-4): `eject` is retired — `migrate rollback` is the only
|
|
1081
|
+
// rollback entry. Reject the old invocation explicitly so it never
|
|
1082
|
+
// falls through to a bare sync (which would write to go routes under
|
|
1083
|
+
// a command name the user believed was read-only).
|
|
1084
|
+
if (sub === 'eject') {
|
|
1085
|
+
return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' };
|
|
1086
|
+
}
|
|
1087
|
+
// Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
|
|
1088
|
+
// as it was. The go subcommands are additive: `go`/`status` run one
|
|
1089
|
+
// full go round, `adopt go` runs it with adoption. Status stays the
|
|
1090
|
+
// read-only `/opencode-status` command — it is never a write trigger.
|
|
1091
|
+
if ((sub === 'go' || sub === 'status' || sub === 'adopt')
|
|
1092
|
+
&& (scope === undefined || scope === 'go')) {
|
|
1093
|
+
try {
|
|
1094
|
+
// Route manual rounds through the scheduler so they share the
|
|
1095
|
+
// single-flight lock with timer-driven rounds. A second trigger
|
|
1096
|
+
// while a round is in flight is skipped and reported (design
|
|
1097
|
+
// §14.6), never queued. The report text is the round's own text,
|
|
1098
|
+
// unchanged, for real rounds.
|
|
1099
|
+
const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' });
|
|
1100
|
+
// N1: a round that threw (e.g. the file-backed ledger refusing to
|
|
1101
|
+
// build without a profile identity) is reported as a scheduler
|
|
1102
|
+
// error. It is a real failure — the command must return
|
|
1103
|
+
// `kind:'error'` so callers that only read `kind` can detect it;
|
|
1104
|
+
// the actionable reason is carried in `text`. Skips (disabled,
|
|
1105
|
+
// already-in-flight, migration-applying, disposed) stay success,
|
|
1106
|
+
// byte-identical to before.
|
|
1107
|
+
const failed = outcome.reason === 'source-failed'
|
|
1108
|
+
// oldfox #3: a writer exception is a real failure at the
|
|
1109
|
+
// command surface, but a distinct reason from source failure.
|
|
1110
|
+
|| outcome.reason === 'writer-error'
|
|
1111
|
+
|| outcome.reason === 'scheduler-error'
|
|
1112
|
+
// B4: an abandoned round must be visible as a failure at the
|
|
1113
|
+
// command surface too (it is not a successful sync). The reason
|
|
1114
|
+
// text carries the actionable "settings changed, next round
|
|
1115
|
+
// retries" guidance; no backoff is scheduled for it.
|
|
1116
|
+
|| outcome.reason === 'settings-changed-during-sync'
|
|
1117
|
+
// O1-minimal: failedRoutes (e.g. settings written but the ledger
|
|
1118
|
+
// failed) are a real failure even if other routes wrote. Callers
|
|
1119
|
+
// that only read `kind` must see `error`; the actionable reason
|
|
1120
|
+
// and the new report code are carried in `text`.
|
|
1121
|
+
|| outcome.reason === 'write-failed';
|
|
1122
|
+
return {
|
|
1123
|
+
kind: failed ? 'error' : 'success',
|
|
1124
|
+
text: outcome.text,
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
catch (error) {
|
|
1128
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1129
|
+
return { kind: 'error', text: `model-sync ${sub} failed: ${message}` };
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
445
1132
|
const ignored = invocation.rawInput.trim().length > 0
|
|
446
1133
|
? 'The sync scope is decided by the model-sync managedRoutes config; the argument is ignored.\n'
|
|
447
1134
|
: '';
|
|
@@ -457,6 +1144,35 @@ export async function apply(ctx, config) {
|
|
|
457
1144
|
};
|
|
458
1145
|
return commands.register(definition);
|
|
459
1146
|
}, 'dsh-model-sync: /model-sync');
|
|
1147
|
+
// P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
|
|
1148
|
+
// unchanged): fetch the official go listing, compare it with the current
|
|
1149
|
+
// profile's opencode-go routes, and print a structured report. This path
|
|
1150
|
+
// never calls settings.mutate, never writes credentials, and never edits
|
|
1151
|
+
// a profile file — it only reads describe()/credentials.resolve().
|
|
1152
|
+
cmdCtx.effect(() => {
|
|
1153
|
+
const definition = {
|
|
1154
|
+
name: 'opencode-status',
|
|
1155
|
+
description: 'Read-only diagnostic: compare opencode-go official /v1/models with the current profile routes (no writes)',
|
|
1156
|
+
handler: async (invocation) => {
|
|
1157
|
+
const token = invocation.rawInput.trim();
|
|
1158
|
+
const ignored = token !== '' && token !== 'go'
|
|
1159
|
+
? 'opencode-status: P0 diagnoses opencode-go only; the argument is ignored.\n'
|
|
1160
|
+
: '';
|
|
1161
|
+
try {
|
|
1162
|
+
const desc = cmdCtx.get('settings')?.describe()
|
|
1163
|
+
.find((d) => d.ns === 'llm-pi-ai');
|
|
1164
|
+
const apiKey = await resolveRouteCredentialValue(cmdCtx, desc, 'opencode-go');
|
|
1165
|
+
const report = await runGoDiagnostic({ apiKey, descriptor: desc });
|
|
1166
|
+
return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` };
|
|
1167
|
+
}
|
|
1168
|
+
catch (error) {
|
|
1169
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1170
|
+
return { kind: 'error', text: `${ignored}opencode-status failed: ${message}` };
|
|
1171
|
+
}
|
|
1172
|
+
},
|
|
1173
|
+
};
|
|
1174
|
+
return commands.register(definition);
|
|
1175
|
+
}, 'dsh-model-sync: /opencode-status');
|
|
460
1176
|
});
|
|
461
1177
|
// One-time legacy settings import (0.1.5 → 0.1.7 upgrade path, see
|
|
462
1178
|
// legacy-import.ts): recover the old `model-sync:` section for hosts where
|