@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
package/src/index.ts
CHANGED
|
@@ -25,6 +25,11 @@ import type { Context } from '@deepseek-ai/cordis'
|
|
|
25
25
|
// settings service; alpha.3 removed the settingsNamespace() helper this file
|
|
26
26
|
// used to import.
|
|
27
27
|
import type {} from '@deepseek-ai/dsh-settings'
|
|
28
|
+
// Type-only side-effect import: loads dsh-credentials' `declare module
|
|
29
|
+
// '@deepseek-ai/cordis'` Events augmentation, which types the
|
|
30
|
+
// `credentials/reference-updated` listener used for backoff reset. Erased at
|
|
31
|
+
// emit — the host provides the service at runtime.
|
|
32
|
+
import type {} from '@deepseek-ai/dsh-credentials/types'
|
|
28
33
|
// Types only (erased at emit); dsh-commands is an optional peer, so hosts
|
|
29
34
|
// without it still load this plugin — see the guarded registration below.
|
|
30
35
|
import type { CommandDefinition, CommandResult } from '@deepseek-ai/dsh-commands'
|
|
@@ -49,7 +54,31 @@ import {
|
|
|
49
54
|
} from './writer.ts'
|
|
50
55
|
import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
|
|
51
56
|
import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from './live-catalog.ts'
|
|
52
|
-
import { checkRouteCredential, type RouteCredentialContext } from './route-credential.ts'
|
|
57
|
+
import { checkRouteCredential, deriveKeyRef, type RouteCredentialContext } from './route-credential.ts'
|
|
58
|
+
import { OPENCODE_GO_MODELS_URL, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, fetchGoOfficialModels, fetchGoPublicCatalogIds, fingerprintKey, type GoFetchLike, type GoModelRecord } from './opencode-go-source.ts'
|
|
59
|
+
import { GO_SLOT_ROUTES, type GoRouteSlot } from './opencode-go-grouping.ts'
|
|
60
|
+
import { createModelsStoreOwnershipStore } from './opencode-go-store.ts'
|
|
61
|
+
import {
|
|
62
|
+
createModelsStoreJournalStore,
|
|
63
|
+
type GoJournalStore,
|
|
64
|
+
} from './opencode-go-journal.ts'
|
|
65
|
+
import {
|
|
66
|
+
GO_FETCH_SERVICE,
|
|
67
|
+
GO_OWNERSHIP_STORE_SERVICE,
|
|
68
|
+
GO_OVERRIDE_STORER_SERVICE,
|
|
69
|
+
runGoSyncRound,
|
|
70
|
+
type GoSyncRoundResult,
|
|
71
|
+
type GoSyncRuntimeConfig,
|
|
72
|
+
} from './opencode-go-sync.ts'
|
|
73
|
+
import type { GoOverrideStorer, GoOwnershipStore } from './opencode-go-writer.ts'
|
|
74
|
+
import {
|
|
75
|
+
GO_SCHEDULER_RANDOM_SERVICE,
|
|
76
|
+
GO_SCHEDULER_TIMERS_SERVICE,
|
|
77
|
+
GoScheduler,
|
|
78
|
+
type GoSchedulerConfig,
|
|
79
|
+
type GoSchedulerRandom,
|
|
80
|
+
type GoSchedulerTimers,
|
|
81
|
+
} from './opencode-go-scheduler.ts'
|
|
53
82
|
import {
|
|
54
83
|
PROVIDER_NATIVE_ENDPOINTS,
|
|
55
84
|
fetchProviderNativeModels,
|
|
@@ -63,12 +92,83 @@ import {
|
|
|
63
92
|
type LegacyImportLogger,
|
|
64
93
|
type SettingsUpdateSeam,
|
|
65
94
|
} from './legacy-import.ts'
|
|
95
|
+
import { runGoDiagnostic, formatGoDiagnosticReport } from './opencode-go-diagnose.ts'
|
|
96
|
+
import {
|
|
97
|
+
PROFILE_IDENTITY_REQUIRED_MESSAGE,
|
|
98
|
+
PROFILE_IDENTITY_STATUS_HINT,
|
|
99
|
+
resolveProfileKey,
|
|
100
|
+
} from './opencode-go-profile.ts'
|
|
101
|
+
import {
|
|
102
|
+
GO_MIGRATION_STORE_SERVICE,
|
|
103
|
+
appliedFingerprintFieldsOf,
|
|
104
|
+
createModelsStoreMigrationStateStore,
|
|
105
|
+
goLedgerManagedIds,
|
|
106
|
+
isGoRoute,
|
|
107
|
+
MIGRATION_GATE_HINT,
|
|
108
|
+
migrationStatusOf,
|
|
109
|
+
readGoProviderSections,
|
|
110
|
+
routeWriter,
|
|
111
|
+
unclaimedRecordState,
|
|
112
|
+
type MigrationRecord,
|
|
113
|
+
type MigrationStatus,
|
|
114
|
+
type MigrationStateStore,
|
|
115
|
+
type UnclaimedMigrationRecord,
|
|
116
|
+
} from './opencode-go-migration.ts'
|
|
117
|
+
import { goOwnershipKey } from './opencode-go-planner.ts'
|
|
118
|
+
import {
|
|
119
|
+
applyMigration,
|
|
120
|
+
buildMigrationPlanFromDeps,
|
|
121
|
+
formatMigrationPlan,
|
|
122
|
+
migrationStatusReport,
|
|
123
|
+
rollbackMigration,
|
|
124
|
+
type MigrateDeps,
|
|
125
|
+
type ReferenceRewrite,
|
|
126
|
+
type RewriteRefMode,
|
|
127
|
+
} from './opencode-go-migrate.ts'
|
|
128
|
+
import {
|
|
129
|
+
runMigrateGoOneShot,
|
|
130
|
+
parseMigrateGoFlags,
|
|
131
|
+
type AskServiceShape,
|
|
132
|
+
type MigrateGoFlags,
|
|
133
|
+
type OneShotFs,
|
|
134
|
+
type OneShotDeps,
|
|
135
|
+
} from './opencode-go-one-shot.ts'
|
|
136
|
+
import type { PatchFileIo } from './opencode-go-patch-file.ts'
|
|
137
|
+
import { MODELS_STORE_PATH } from './remote-catalog.ts'
|
|
138
|
+
import { mkdir, open, readFile, readdir, rename, stat as statFd, unlink, writeFile } from 'node:fs/promises'
|
|
139
|
+
import { readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
66
140
|
|
|
67
141
|
export const name = 'dsh-model-sync'
|
|
68
142
|
|
|
69
143
|
/** The settings seam this plugin consumes (its own config namespace). */
|
|
70
144
|
export const inject = ['settings']
|
|
71
145
|
|
|
146
|
+
/** P1d-2 seams: injected official entries (plan/apply) and optional reference writer. */
|
|
147
|
+
export const GO_MIGRATION_ENTRIES_SERVICE = 'goMigrationEntries'
|
|
148
|
+
export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter'
|
|
149
|
+
/** Public (unauthenticated) official catalog ids for id classification (design §14.2).
|
|
150
|
+
* `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
|
|
151
|
+
export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog'
|
|
152
|
+
/** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
|
|
153
|
+
export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled'
|
|
154
|
+
/** Optional override for the single-flight check (tests inject an in-flight mutex). */
|
|
155
|
+
export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex'
|
|
156
|
+
/** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
|
|
157
|
+
export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore'
|
|
158
|
+
/**
|
|
159
|
+
* One-shot migrate-go path overrides (tests point everything at a temp dir;
|
|
160
|
+
* a host may pin non-default locations). Plain `undefined` fields fall back
|
|
161
|
+
* to resolveDshHome() / MODELS_STORE_PATH / `<home>/profiles`.
|
|
162
|
+
*/
|
|
163
|
+
export const GO_ONESHOT_PATHS_SERVICE = 'goOneShotPaths'
|
|
164
|
+
export interface GoOneShotPaths {
|
|
165
|
+
home?: string
|
|
166
|
+
modelsStorePath?: string
|
|
167
|
+
profilesDir?: string
|
|
168
|
+
/** TEST FAULT INJECTION ONLY: see OneShotDeps.faultOwnershipWriteOnKeyPrefix. */
|
|
169
|
+
testOnlyOwnershipWriteFaultPrefix?: string
|
|
170
|
+
}
|
|
171
|
+
|
|
72
172
|
// dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
|
|
73
173
|
// is gone, and a plugin's settings form is projected from its exported
|
|
74
174
|
// `Config` schema — the namespace IS the profile entry id. The bundle patch
|
|
@@ -128,6 +228,49 @@ export const Config = z.object({
|
|
|
128
228
|
* a re-emitted retired id is a model the 0.1.7 host no longer resolves.
|
|
129
229
|
*/
|
|
130
230
|
keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* OpenCode Go / Zen configuration contract (design §6.2.6). Published in one
|
|
234
|
+
* Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
|
|
235
|
+
* intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
|
|
236
|
+
* (go.routes/adoptExisting/pinnedModels/confirmRemovals,
|
|
237
|
+
* zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
|
|
238
|
+
* `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
|
|
239
|
+
* impossible. Zen stays login-only with no modelsUrl by default (design A5).
|
|
240
|
+
* Nested leaves are `.volatile()` (host settings can edit them); the parent
|
|
241
|
+
* objects are not, because schemastery forbids a volatile field under an
|
|
242
|
+
* enclosing volatile field.
|
|
243
|
+
*/
|
|
244
|
+
opencode: z.object({
|
|
245
|
+
go: z.object({
|
|
246
|
+
enabled: z.boolean().default(false).volatile(),
|
|
247
|
+
ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
|
|
248
|
+
modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
|
|
249
|
+
intervalMinutes: z.number().step(1).min(15).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
|
|
250
|
+
adoptExisting: z.boolean().default(false).volatile(),
|
|
251
|
+
pinnedModels: z.array(z.string()).default([]).volatile(),
|
|
252
|
+
routes: z.object({
|
|
253
|
+
chat: z.string().default('opencode-go').volatile(),
|
|
254
|
+
msg: z.string().default('opencode-go-msg').volatile(),
|
|
255
|
+
resp: z.string().default('opencode-go-resp').volatile(),
|
|
256
|
+
google: z.string().default('opencode-go-google').volatile(),
|
|
257
|
+
}).default({}),
|
|
258
|
+
confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
|
|
259
|
+
}).default({}),
|
|
260
|
+
zen: z.object({
|
|
261
|
+
enabled: z.boolean().default(true).volatile(),
|
|
262
|
+
ref: z.string().default('OPENCODE_API_KEY').volatile(),
|
|
263
|
+
mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
|
|
264
|
+
/** No proven listing endpoint; without it routes mode is unsupported. */
|
|
265
|
+
modelsUrl: z.string().volatile(),
|
|
266
|
+
seedFromBuiltin: z.boolean().default(false).volatile(),
|
|
267
|
+
routes: z.object({
|
|
268
|
+
chat: z.string().default('opencode-zen').volatile(),
|
|
269
|
+
msg: z.string().default('opencode-zen-msg').volatile(),
|
|
270
|
+
resp: z.string().default('opencode-zen-resp').volatile(),
|
|
271
|
+
}).default({}),
|
|
272
|
+
}).default({}),
|
|
273
|
+
}).default({}),
|
|
131
274
|
})
|
|
132
275
|
|
|
133
276
|
/**
|
|
@@ -154,6 +297,26 @@ interface ModelSyncConfigValue {
|
|
|
154
297
|
forceMaxReasoningEffort: VolatileRef<boolean>
|
|
155
298
|
providerNativeFetch: VolatileRef<boolean>
|
|
156
299
|
keepDeprecatedBuiltin: VolatileRef<boolean>
|
|
300
|
+
opencode: {
|
|
301
|
+
go: {
|
|
302
|
+
enabled: VolatileRef<boolean>
|
|
303
|
+
ref: VolatileRef<string>
|
|
304
|
+
modelsUrl: VolatileRef<string>
|
|
305
|
+
intervalMinutes: VolatileRef<number>
|
|
306
|
+
adoptExisting: VolatileRef<boolean>
|
|
307
|
+
pinnedModels: VolatileRef<readonly string[]>
|
|
308
|
+
routes: Record<'chat' | 'msg' | 'resp' | 'google', VolatileRef<string>>
|
|
309
|
+
confirmRemovals: VolatileRef<number>
|
|
310
|
+
}
|
|
311
|
+
zen: {
|
|
312
|
+
enabled: VolatileRef<boolean>
|
|
313
|
+
ref: VolatileRef<string>
|
|
314
|
+
mode: VolatileRef<'login-only' | 'routes'>
|
|
315
|
+
modelsUrl: VolatileRef<string | undefined>
|
|
316
|
+
seedFromBuiltin: VolatileRef<boolean>
|
|
317
|
+
routes: Record<'chat' | 'msg' | 'resp', VolatileRef<string>>
|
|
318
|
+
}
|
|
319
|
+
}
|
|
157
320
|
}
|
|
158
321
|
|
|
159
322
|
/** The llm seam as this plugin needs it (overlay mode). */
|
|
@@ -170,6 +333,11 @@ interface CatalogSeam {
|
|
|
170
333
|
/** The `modelSync` service surfaced to UIs: run one refresh round and get the report. */
|
|
171
334
|
export interface ModelSyncService {
|
|
172
335
|
syncNow(): Promise<string>
|
|
336
|
+
/** P1d-2: host-service mirrors of the migrate commands (design §14.5). */
|
|
337
|
+
migratePlan?(options?: { adopt?: boolean; rewriteRefs?: RewriteRefMode; pruneUserExtra?: boolean }): Promise<string>
|
|
338
|
+
migrateApply?(args: { planHash?: string; confirmCode?: string; ackManaged?: boolean }): Promise<string>
|
|
339
|
+
migrateRollback?(args: { planHash?: string }): Promise<string>
|
|
340
|
+
migrateStatus?(): Promise<string>
|
|
173
341
|
}
|
|
174
342
|
|
|
175
343
|
/**
|
|
@@ -193,6 +361,120 @@ const DEFAULT_ROUTES = [
|
|
|
193
361
|
* runtime surface; subject to change without notice. */
|
|
194
362
|
export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES
|
|
195
363
|
|
|
364
|
+
// ---------------------------------------------------------------------------
|
|
365
|
+
// P1c go config / dependency helpers (design §6.2.6)
|
|
366
|
+
// ---------------------------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
/** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
|
|
369
|
+
function readVolatile<T>(slot: unknown, fallback: T): T {
|
|
370
|
+
if (slot === undefined) return fallback
|
|
371
|
+
if (typeof slot === 'object' && slot !== null && typeof (slot as { get?: unknown }).get === 'function') {
|
|
372
|
+
return (slot as { get(): T }).get()
|
|
373
|
+
}
|
|
374
|
+
return slot as T
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Project the go Config subset for one round. Reads the live volatile refs, so
|
|
379
|
+
* a settings edit takes effect on the next round without a remount. The
|
|
380
|
+
* defensive shape also keeps older/partial fake configs (no `opencode` block)
|
|
381
|
+
* on the default zero-behavior path instead of throwing during apply().
|
|
382
|
+
*/
|
|
383
|
+
function readGoRuntimeConfig(config: ModelSyncConfigValue): { enabled: boolean; value: GoSyncRuntimeConfig } {
|
|
384
|
+
const raw = config as unknown as Record<string, unknown>
|
|
385
|
+
const opencode = raw.opencode as Record<string, unknown> | undefined
|
|
386
|
+
const go = opencode?.go as Record<string, unknown> | undefined
|
|
387
|
+
const rawRoutes = go?.routes as Record<string, unknown> | undefined
|
|
388
|
+
const routes = Object.fromEntries(
|
|
389
|
+
(Object.keys(GO_SLOT_ROUTES) as GoRouteSlot[]).map((slot) => [
|
|
390
|
+
slot,
|
|
391
|
+
readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
|
|
392
|
+
]),
|
|
393
|
+
) as GoSyncRuntimeConfig['routes']
|
|
394
|
+
return {
|
|
395
|
+
enabled: readVolatile(go?.enabled, false),
|
|
396
|
+
value: {
|
|
397
|
+
enabled: readVolatile(go?.enabled, false),
|
|
398
|
+
ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
|
|
399
|
+
modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
|
|
400
|
+
routes,
|
|
401
|
+
pinnedModels: readVolatile(go?.pinnedModels, [] as readonly string[]),
|
|
402
|
+
confirmRemovals: readVolatile(go?.confirmRemovals, 2),
|
|
403
|
+
adoptExisting: readVolatile(go?.adoptExisting, false),
|
|
404
|
+
},
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
|
|
410
|
+
* field (default 60, floor 15, enforced by the scheduler); the startup delay is
|
|
411
|
+
* the shared top-level field the design names for startup jitter.
|
|
412
|
+
*
|
|
413
|
+
* `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
|
|
414
|
+
* Migration zero-write is now enforced independently by routeWriter (§14.6 /
|
|
415
|
+
* §14.7) on every write path, so this default is a product choice, not the
|
|
416
|
+
* only protection. All scheduler paths are still gated by this value.
|
|
417
|
+
*/
|
|
418
|
+
function readGoSchedulerConfig(config: ModelSyncConfigValue): GoSchedulerConfig {
|
|
419
|
+
const raw = config as unknown as Record<string, unknown>
|
|
420
|
+
const opencode = raw.opencode as Record<string, unknown> | undefined
|
|
421
|
+
const go = opencode?.go as Record<string, unknown> | undefined
|
|
422
|
+
return {
|
|
423
|
+
enabled: readVolatile(go?.enabled, false),
|
|
424
|
+
intervalMinutes: readVolatile(go?.intervalMinutes, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES),
|
|
425
|
+
startupDelaySeconds: readVolatile(raw.startupDelaySeconds, 5),
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ---------------------------------------------------------------------------
|
|
430
|
+
// P1d-1: own-write reentry marker + migration status reads (design §14.7.2)
|
|
431
|
+
// ---------------------------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
/** Revision-stamped marker of the last settings write this plugin performed. */
|
|
434
|
+
interface OwnWriteMarker {
|
|
435
|
+
ns: string
|
|
436
|
+
revision: number
|
|
437
|
+
at: number
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
interface OwnWriteTracker {
|
|
441
|
+
/** Called after a successful settings.mutate, with the post-write revision. */
|
|
442
|
+
record(ns: string): void
|
|
443
|
+
/** True when a document-updated event is the echo of our own write. */
|
|
444
|
+
matches(ns: string, eventRevision?: number): boolean
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
|
|
449
|
+
* the live descriptor after a mutate, so the marker always holds the revision
|
|
450
|
+
* the host stamped on OUR write; a later event for the same ns+revision can
|
|
451
|
+
* only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
|
|
452
|
+
* never depend on a wall clock.
|
|
453
|
+
*/
|
|
454
|
+
function createOwnWriteTracker(
|
|
455
|
+
readRevision: (ns: string) => number | undefined,
|
|
456
|
+
now: () => number,
|
|
457
|
+
): OwnWriteTracker {
|
|
458
|
+
let last: OwnWriteMarker | undefined
|
|
459
|
+
const tracker: OwnWriteTracker = {
|
|
460
|
+
record(ns) {
|
|
461
|
+
const revision = readRevision(ns)
|
|
462
|
+
if (revision !== undefined) last = { ns, revision, at: now() }
|
|
463
|
+
},
|
|
464
|
+
matches(ns, eventRevision) {
|
|
465
|
+
if (last === undefined || last.ns !== ns) return false
|
|
466
|
+
if (eventRevision !== undefined) return eventRevision === last.revision
|
|
467
|
+
const current = readRevision(ns)
|
|
468
|
+
return current !== undefined && current === last.revision
|
|
469
|
+
},
|
|
470
|
+
}
|
|
471
|
+
return tracker
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function settingsRevision(settings: SettingsService | undefined, ns: string): number | undefined {
|
|
475
|
+
return settings?.describe().find((desc) => desc.ns === ns)?.revision
|
|
476
|
+
}
|
|
477
|
+
|
|
196
478
|
export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise<void> {
|
|
197
479
|
// On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
|
|
198
480
|
// every volatile field is a stable reference (see VolatileRef), so the
|
|
@@ -200,6 +482,158 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
200
482
|
// removed from dsh-settings; the hot-reload notification moved to the
|
|
201
483
|
// settings/document-updated event, subscribed at the bottom of apply()).
|
|
202
484
|
|
|
485
|
+
// P1d-1: one reentry marker shared by every write path. `rawSettings()` is
|
|
486
|
+
// resolved per call so a host that mounts the settings service after this
|
|
487
|
+
// plugin still works; the thin wrapper records the post-mutate revision for
|
|
488
|
+
// the document-updated reentry check (§14.7.2). Every settings-writing path
|
|
489
|
+
// below goes through `settingsForWrite*` — never a bare ctx.get('settings').
|
|
490
|
+
const rawSettings = (): SettingsService | undefined => ctx.get('settings') as SettingsService | undefined
|
|
491
|
+
const ownWrite = createOwnWriteTracker(
|
|
492
|
+
(ns) => settingsRevision(rawSettings(), ns),
|
|
493
|
+
() => Date.now(),
|
|
494
|
+
)
|
|
495
|
+
const settingsForWriteFrom = (context: Context): SettingsService | undefined => {
|
|
496
|
+
const raw = context.get('settings') as SettingsService | undefined
|
|
497
|
+
if (raw === undefined) return undefined
|
|
498
|
+
return {
|
|
499
|
+
describe: () => raw.describe(),
|
|
500
|
+
mutate: async (ns, ops, expectedRevision) => {
|
|
501
|
+
await raw.mutate(ns, ops, expectedRevision)
|
|
502
|
+
ownWrite.record(ns)
|
|
503
|
+
},
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const settingsForWrite = (): SettingsService | undefined => settingsForWriteFrom(ctx)
|
|
507
|
+
|
|
508
|
+
// B1/H9: one stable profile identity per plugin instance, resolved from the
|
|
509
|
+
// host (profileContext / DSH_PROFILE). Both file-backed stores below scope
|
|
510
|
+
// every shared models-store key with it so two profiles cannot share a
|
|
511
|
+
// migration record or ownership ledger entry. When no identity can be
|
|
512
|
+
// resolved there is NO 'default' collapse: every file-backed ledger path
|
|
513
|
+
// fails closed with an actionable error instead of silently sharing a key.
|
|
514
|
+
const profileKey = resolveProfileKey(ctx)
|
|
515
|
+
const requireScopedProfileKey = (): string => {
|
|
516
|
+
if (profileKey === undefined) throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE)
|
|
517
|
+
return profileKey
|
|
518
|
+
}
|
|
519
|
+
// The injection seam is an explicit opt-in (tests / hosts that supply their
|
|
520
|
+
// own scoped store); only the file-backed fallback requires host identity.
|
|
521
|
+
const migrationStore = (): MigrationStateStore =>
|
|
522
|
+
(ctx.get(GO_MIGRATION_STORE_SERVICE) as MigrationStateStore | undefined)
|
|
523
|
+
?? createModelsStoreMigrationStateStore(undefined, requireScopedProfileKey())
|
|
524
|
+
const ownershipStoreForRound = (): GoOwnershipStore =>
|
|
525
|
+
(ctx.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
|
|
526
|
+
?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey())
|
|
527
|
+
// O1/C2: the journal lives in the same models-store.json. An injected seam
|
|
528
|
+
// wins (tests use a temp-dir accessor); without a resolved profile identity
|
|
529
|
+
// there is NO journal — never fall back to the real default ~/.dsh from a
|
|
530
|
+
// host/test that supplied no identity (the ledger path fails closed too).
|
|
531
|
+
const journalStoreForRound = (): GoJournalStore | undefined =>
|
|
532
|
+
(ctx.get(GO_JOURNAL_STORE_SERVICE) as GoJournalStore | undefined)
|
|
533
|
+
?? (profileKey === undefined ? undefined : createModelsStoreJournalStore())
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Read current migration status from the persisted record + live settings +
|
|
537
|
+
* (when a key fingerprint is available) the live ownership ledger.
|
|
538
|
+
* `strict` rethrows a record read failure so the §14.7.5 second gate can fail
|
|
539
|
+
* closed with `canWrite-unavailable`; the normal path degrades to "no record"
|
|
540
|
+
* (conservative legacy detection) as before.
|
|
541
|
+
*/
|
|
542
|
+
const loadMigrationStatus = async (
|
|
543
|
+
opts: { keyFingerprint?: string; strict?: boolean } = {},
|
|
544
|
+
): Promise<MigrationStatus> => {
|
|
545
|
+
const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
546
|
+
// H9 fail-closed: with no resolvable profile identity the file-backed store
|
|
547
|
+
// factory throws. A non-strict READ degrades to "no record" (gate closed,
|
|
548
|
+
// zero writes) so boot-time status refreshes / isApplying cannot produce an
|
|
549
|
+
// unhandled rejection; strict reads (the per-mutate second gate) rethrow.
|
|
550
|
+
// Every WRITE path still fails closed when it builds its file-backed store.
|
|
551
|
+
// N2: remember an identity-refused file-backed store so the (non-strict)
|
|
552
|
+
// status read can surface it instead of looking like a normal legacy state.
|
|
553
|
+
// The check is on the thrown identity error, not on `profileKey === undefined`
|
|
554
|
+
// alone: an injected-store host has a usable ledger even with no host
|
|
555
|
+
// identity and must NOT get a false "identity unavailable" report.
|
|
556
|
+
let identityUnavailable = false
|
|
557
|
+
let store: MigrationStateStore | undefined
|
|
558
|
+
try {
|
|
559
|
+
store = migrationStore()
|
|
560
|
+
} catch (err) {
|
|
561
|
+
if (opts.strict === true) throw err
|
|
562
|
+
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
|
|
563
|
+
}
|
|
564
|
+
let record: MigrationRecord | undefined
|
|
565
|
+
try {
|
|
566
|
+
record = await store?.read()
|
|
567
|
+
} catch (err) {
|
|
568
|
+
if (opts.strict === true) throw err
|
|
569
|
+
record = undefined // unreadable ⇒ conservative legacy detection
|
|
570
|
+
}
|
|
571
|
+
const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {})
|
|
572
|
+
let managedIds: Record<string, string[]> | undefined
|
|
573
|
+
const fp = opts.keyFingerprint
|
|
574
|
+
if (fp !== undefined) {
|
|
575
|
+
let ownership: GoOwnershipStore | undefined
|
|
576
|
+
try {
|
|
577
|
+
ownership = ownershipStoreForRound()
|
|
578
|
+
} catch (err) {
|
|
579
|
+
if (opts.strict === true) throw err
|
|
580
|
+
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
|
|
581
|
+
}
|
|
582
|
+
// Only routes with a REAL ledger entry join the fingerprint set. The old
|
|
583
|
+
// `<route>: []` filler for configured-but-absent routes disagreed with
|
|
584
|
+
// migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
|
|
585
|
+
// first healthy round after onboarding.
|
|
586
|
+
managedIds = await goLedgerManagedIds(goRoutes, (route) =>
|
|
587
|
+
ownership === undefined
|
|
588
|
+
? Promise.resolve(undefined)
|
|
589
|
+
: ownership.read(goOwnershipKey(route, fp)))
|
|
590
|
+
}
|
|
591
|
+
const status = migrationStatusOf(desc, record, goRoutes, managedIds)
|
|
592
|
+
// W1/D6: the go report and `migrate status` must agree on the label for a
|
|
593
|
+
// record this profile cannot claim. Use the SAME helper as migrate status;
|
|
594
|
+
// only when our own scoped read() found no record (B1 isolation). This is
|
|
595
|
+
// label-only: both states already keep the gate closed / write authority
|
|
596
|
+
// none / zero writes, and nothing is claimed or deleted.
|
|
597
|
+
if (record === undefined && store?.unclaimedRecords !== undefined) {
|
|
598
|
+
let unclaimed: UnclaimedMigrationRecord[]
|
|
599
|
+
try {
|
|
600
|
+
unclaimed = await store.unclaimedRecords()
|
|
601
|
+
} catch (err) {
|
|
602
|
+
if (opts.strict === true) throw err
|
|
603
|
+
unclaimed = [] // advisory provenance scan never changes the gate
|
|
604
|
+
}
|
|
605
|
+
const recordState = unclaimedRecordState(unclaimed)
|
|
606
|
+
if (recordState !== undefined) status.state = recordState
|
|
607
|
+
}
|
|
608
|
+
// N2: a non-strict refresh that degraded because no identity was available
|
|
609
|
+
// must be VISIBLE — log the actionable error (covers boot / document-updated
|
|
610
|
+
// refresh where there is no report line) and tag the status so sync reports
|
|
611
|
+
// do not show the normal legacy hint. This changes NO write/fail-closed
|
|
612
|
+
// behavior: the gate is already closed and no store/settings write occurs.
|
|
613
|
+
if (identityUnavailable) {
|
|
614
|
+
status.identityUnavailable = true
|
|
615
|
+
ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE)
|
|
616
|
+
}
|
|
617
|
+
// §14.7.4 self-heal: identity matches but the stored full fingerprint is
|
|
618
|
+
// stale because the fingerprint persist failed after settings+ledger landed.
|
|
619
|
+
// Rewrite it in the same queue instead of closing the gate forever.
|
|
620
|
+
if (status.fingerprintHealed && typeof store?.write === 'function') {
|
|
621
|
+
try {
|
|
622
|
+
ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)')
|
|
623
|
+
await store.write({
|
|
624
|
+
...(record ?? {}),
|
|
625
|
+
appliedManagedIds: managedIds ?? record?.appliedManagedIds,
|
|
626
|
+
appliedFingerprint: status.expectedFingerprint,
|
|
627
|
+
})
|
|
628
|
+
status.appliedFingerprint = status.expectedFingerprint
|
|
629
|
+
status.fingerprintHealed = false
|
|
630
|
+
} catch (err) {
|
|
631
|
+
ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err))
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return status
|
|
635
|
+
}
|
|
636
|
+
|
|
203
637
|
// -----------------------------------------------------------------------
|
|
204
638
|
// Overlay mode sync (existing behavior)
|
|
205
639
|
// -----------------------------------------------------------------------
|
|
@@ -274,7 +708,7 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
274
708
|
config: ModelSyncConfigValue,
|
|
275
709
|
force: boolean,
|
|
276
710
|
): Promise<string> => {
|
|
277
|
-
const settings =
|
|
711
|
+
const settings = settingsForWrite()
|
|
278
712
|
const logger = ctx.logger as unknown as Logger
|
|
279
713
|
const store = loadModelsStore()
|
|
280
714
|
const lines: string[] = []
|
|
@@ -285,9 +719,37 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
285
719
|
? [...managedRoutes]
|
|
286
720
|
: DEFAULT_ROUTES
|
|
287
721
|
|
|
722
|
+
// P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
|
|
723
|
+
// path must NEVER write an `opencode-go*` route — not even in `absent` /
|
|
724
|
+
// `applied` state (that belongs to go sync), and especially not when the
|
|
725
|
+
// migration gate is closed. Login-triggered/manual/auto all funnel through
|
|
726
|
+
// this one loop (design §14.7.1, ADR-008).
|
|
727
|
+
const { value: goCfg } = readGoRuntimeConfig(config)
|
|
728
|
+
const goRouteIds = Object.values(goCfg.routes ?? {})
|
|
729
|
+
const piDevAuthority = { caller: 'pi.dev' as const, goEnabled: goCfg.enabled, goRoutes: goRouteIds }
|
|
730
|
+
let piDevMigration: MigrationStatus | undefined
|
|
731
|
+
|
|
288
732
|
const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
289
733
|
const gateCtx = ctx as RouteCredentialContext
|
|
290
734
|
for (const route of routes) {
|
|
735
|
+
// Single-writer gate before ANY fetch/translate/mutate for go routes.
|
|
736
|
+
// A skip always produces a report line (never silent, §14.7.1).
|
|
737
|
+
if (goCfg.enabled && isGoRoute(route, goRouteIds)) {
|
|
738
|
+
piDevMigration ??= await loadMigrationStatus()
|
|
739
|
+
const decision = routeWriter(route, piDevAuthority, piDevMigration)
|
|
740
|
+
if (decision.decision === 'skip') {
|
|
741
|
+
// N2: an identity-refused ledger is NOT a normal legacy state. Surface
|
|
742
|
+
// the actionable identity hint instead of the generic migration hint.
|
|
743
|
+
const hint = piDevMigration.identityUnavailable === true
|
|
744
|
+
? `; ${PROFILE_IDENTITY_STATUS_HINT}`
|
|
745
|
+
: (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
|
|
746
|
+
? ''
|
|
747
|
+
: `; ${MIGRATION_GATE_HINT}`)
|
|
748
|
+
lines.push(`${route}: skipped — ${decision.reason}${hint}`)
|
|
749
|
+
continue
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
291
753
|
// Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
|
|
292
754
|
// Layer 2 follows its authContextFrom(ctx).env(): launch environment,
|
|
293
755
|
// or process.env when the service is absent. Both miss → skip fetch,
|
|
@@ -503,6 +965,451 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
503
965
|
return syncOverlay(config, llm, force)
|
|
504
966
|
}
|
|
505
967
|
|
|
968
|
+
// -----------------------------------------------------------------------
|
|
969
|
+
// P1c go round: source → planner → writer, all deps from cordis seams.
|
|
970
|
+
// P1c-2 wraps this in the scheduler below; the round itself still owns no
|
|
971
|
+
// timer and no command registration.
|
|
972
|
+
// -----------------------------------------------------------------------
|
|
973
|
+
const runGoRound = async (options: { adopt?: boolean; signal?: AbortSignal } = {}): Promise<GoSyncRoundResult> => {
|
|
974
|
+
const { value } = readGoRuntimeConfig(config)
|
|
975
|
+
const settings = settingsForWrite()
|
|
976
|
+
const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
977
|
+
const apiKey = await resolveRouteCredentialValue(
|
|
978
|
+
ctx as unknown as NativeCredentialContext,
|
|
979
|
+
desc,
|
|
980
|
+
'opencode-go',
|
|
981
|
+
value.ref,
|
|
982
|
+
)
|
|
983
|
+
// The ledger is keyed by the same credential fingerprint the source uses;
|
|
984
|
+
// deriving it here lets the status read include the live managed-id set.
|
|
985
|
+
const keyFingerprint = fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : '')
|
|
986
|
+
const migration = await loadMigrationStatus({ keyFingerprint })
|
|
987
|
+
const ownershipStore = ownershipStoreForRound()
|
|
988
|
+
// The existing models-store accessor already satisfies GoOverrideStorer
|
|
989
|
+
// (read(route).overrides + updateOverrides); the service seam lets tests
|
|
990
|
+
// point both stores at a temp dir instead of the real ~/.dsh.
|
|
991
|
+
const overrideStorer = (ctx.get(GO_OVERRIDE_STORER_SERVICE) as GoOverrideStorer | undefined)
|
|
992
|
+
?? loadModelsStore()
|
|
993
|
+
return runGoSyncRound({
|
|
994
|
+
settings,
|
|
995
|
+
ownershipStore,
|
|
996
|
+
overrideStorer,
|
|
997
|
+
logger: ctx.logger as unknown as Logger,
|
|
998
|
+
// The explicit `adopt` command honours the master switch: disabled means
|
|
999
|
+
// zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
|
|
1000
|
+
config: options.adopt === true ? { ...value, adoptExisting: true } : value,
|
|
1001
|
+
apiKey,
|
|
1002
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
1003
|
+
signal: options.signal,
|
|
1004
|
+
migration,
|
|
1005
|
+
// O1/C2: journal + reconciliation use the same profile/fingerprint as the
|
|
1006
|
+
// ledger. Reconciliation runs before the gate inside runGoSyncRound.
|
|
1007
|
+
journalStore: journalStoreForRound(),
|
|
1008
|
+
profileKey,
|
|
1009
|
+
keyFingerprint,
|
|
1010
|
+
// §14.7.5: the second gate re-reads the persisted record on each mutate
|
|
1011
|
+
// (strict: a failed read skips the route with canWrite-unavailable).
|
|
1012
|
+
reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
|
|
1013
|
+
// §14.7.4: settings → ledger → fingerprint, all through the same
|
|
1014
|
+
// models-store queue; only successful own writes reach this callback.
|
|
1015
|
+
onOwnWrite: async (route, managedIds) => {
|
|
1016
|
+
const store = migrationStore()
|
|
1017
|
+
if (typeof store.write !== 'function') return // read-only injected store
|
|
1018
|
+
let record: MigrationRecord | undefined
|
|
1019
|
+
try {
|
|
1020
|
+
record = await store.read()
|
|
1021
|
+
} catch {
|
|
1022
|
+
return // cannot merge safely; the next round's self-heal covers it
|
|
1023
|
+
}
|
|
1024
|
+
const goRoutes = Object.values(value.routes ?? {})
|
|
1025
|
+
const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
1026
|
+
const sections = readGoProviderSections(liveDesc, goRoutes)
|
|
1027
|
+
const appliedIdentityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
|
|
1028
|
+
const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() }
|
|
1029
|
+
// Same helper + route-set convention as loadMigrationStatus: a normal
|
|
1030
|
+
// onboarding/own write must not look like a fingerprint drift next round.
|
|
1031
|
+
const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
|
|
1032
|
+
sections, record, appliedManagedIds,
|
|
1033
|
+
)
|
|
1034
|
+
await store.write({
|
|
1035
|
+
...(record ?? {}),
|
|
1036
|
+
appliedIdentity: identity,
|
|
1037
|
+
appliedIdentityRoutes,
|
|
1038
|
+
appliedManagedIds,
|
|
1039
|
+
appliedFingerprint,
|
|
1040
|
+
})
|
|
1041
|
+
},
|
|
1042
|
+
})
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// -----------------------------------------------------------------------
|
|
1046
|
+
// P1c-2: async timer + scheduling for the go round (design §6.3 / §14.6).
|
|
1047
|
+
// One GoScheduler instance serves BOTH the timer and the manual /model-sync
|
|
1048
|
+
// go command, so they share the single-flight lock. Clock and jitter inputs
|
|
1049
|
+
// are optional cordis services so tests never arm a real timer.
|
|
1050
|
+
// -----------------------------------------------------------------------
|
|
1051
|
+
const goTimers: GoSchedulerTimers = (ctx.get(GO_SCHEDULER_TIMERS_SERVICE) as GoSchedulerTimers | undefined) ?? {
|
|
1052
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
1053
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
1054
|
+
}
|
|
1055
|
+
const goRandom: GoSchedulerRandom = (ctx.get(GO_SCHEDULER_RANDOM_SERVICE) as GoSchedulerRandom | undefined)
|
|
1056
|
+
?? { next: () => Math.random() }
|
|
1057
|
+
const goScheduler = new GoScheduler({
|
|
1058
|
+
config: () => readGoSchedulerConfig(config),
|
|
1059
|
+
timers: goTimers,
|
|
1060
|
+
random: goRandom,
|
|
1061
|
+
runRound: async ({ adopt, signal }) => {
|
|
1062
|
+
const round = await runGoRound({ adopt, signal })
|
|
1063
|
+
return {
|
|
1064
|
+
ok: round.ok,
|
|
1065
|
+
reason: round.reason,
|
|
1066
|
+
text: round.text,
|
|
1067
|
+
failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
|
|
1068
|
+
? round.source.error.kind
|
|
1069
|
+
: undefined,
|
|
1070
|
+
}
|
|
1071
|
+
},
|
|
1072
|
+
report: (text) => {
|
|
1073
|
+
for (const line of text.split('\n')) ctx.logger.info('model-sync: %s', line)
|
|
1074
|
+
},
|
|
1075
|
+
// M-5: drop (never queue) any round while a migration apply holds the routes.
|
|
1076
|
+
isApplying: async () => (await loadMigrationStatus()).applying,
|
|
1077
|
+
})
|
|
1078
|
+
ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose')
|
|
1079
|
+
// A changed credential invalidates any accumulated backoff: a fixed key must
|
|
1080
|
+
// retry on the normal schedule instead of waiting out a capped 6h backoff
|
|
1081
|
+
// (design §6.3). The effect scopes the listener to this plugin's lifetime —
|
|
1082
|
+
// unload removes it together with the scheduler.
|
|
1083
|
+
ctx.effect(() => ctx.on('credentials/reference-updated', (ref: unknown) => {
|
|
1084
|
+
if (typeof ref !== 'string') return
|
|
1085
|
+
const { value } = readGoRuntimeConfig(config)
|
|
1086
|
+
if (ref !== value.ref) return
|
|
1087
|
+
goScheduler.resetBackoff()
|
|
1088
|
+
}), 'dsh-model-sync: credentials/reference-updated → go backoff reset')
|
|
1089
|
+
goScheduler.start()
|
|
1090
|
+
|
|
1091
|
+
// -----------------------------------------------------------------------
|
|
1092
|
+
// P1d-2: `/model-sync migrate plan|apply|rollback|status` (design §14.5).
|
|
1093
|
+
// plan is pure/read-only; apply carries the consent gate and the single-flight
|
|
1094
|
+
// mutex against goScheduler. No auto/startup path reaches any of these.
|
|
1095
|
+
// -----------------------------------------------------------------------
|
|
1096
|
+
type MigrateEntries = readonly GoModelRecord[] | (() => Promise<readonly GoModelRecord[]> | readonly GoModelRecord[])
|
|
1097
|
+
type PublicCatalog = readonly string[] | (() => Promise<readonly string[]> | readonly string[])
|
|
1098
|
+
|
|
1099
|
+
/** Resolve the official listing through an injectable seam (tests: a fixture array). */
|
|
1100
|
+
const resolveMigrateEntries = async (
|
|
1101
|
+
value: GoSyncRuntimeConfig,
|
|
1102
|
+
apiKey: string | undefined,
|
|
1103
|
+
): Promise<readonly GoModelRecord[]> => {
|
|
1104
|
+
const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE) as MigrateEntries | undefined
|
|
1105
|
+
if (Array.isArray(injected)) return injected
|
|
1106
|
+
if (typeof injected === 'function') return await injected()
|
|
1107
|
+
const source = await fetchGoOfficialModels({
|
|
1108
|
+
url: value.modelsUrl,
|
|
1109
|
+
apiKey,
|
|
1110
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
1111
|
+
timeoutMs: config.refreshTimeoutMs.get(),
|
|
1112
|
+
})
|
|
1113
|
+
if (!source.ok) {
|
|
1114
|
+
throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`)
|
|
1115
|
+
}
|
|
1116
|
+
return source.entries
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* Public-catalog producer for id classification (§14.2): ids the current key
|
|
1121
|
+
* cannot serve but that are still official are `unknown-retired`, everything
|
|
1122
|
+
* else is `user-extra`. When the public list cannot be fetched the result is
|
|
1123
|
+
* `undefined`, which makes the plan mark such ids `unclassified` (never
|
|
1124
|
+
* deleted) instead of defaulting them to deletable `user-extra`.
|
|
1125
|
+
*/
|
|
1126
|
+
const resolvePublicCatalogIds = async (
|
|
1127
|
+
value: GoSyncRuntimeConfig,
|
|
1128
|
+
entries: readonly GoModelRecord[],
|
|
1129
|
+
): Promise<readonly string[] | undefined> => {
|
|
1130
|
+
const injected = ctx.get(GO_MIGRATION_PUBLIC_CATALOG_SERVICE) as PublicCatalog | undefined
|
|
1131
|
+
if (Array.isArray(injected)) return injected
|
|
1132
|
+
if (typeof injected === 'function') return await injected()
|
|
1133
|
+
// Offline fixture mode: the injected authorized entries are the only catalog
|
|
1134
|
+
// available; deriving ids from them keeps `migrate plan` zero-fetch (V16).
|
|
1135
|
+
if (ctx.get(GO_MIGRATION_ENTRIES_SERVICE) !== undefined) return entries.map((entry) => entry.id)
|
|
1136
|
+
const result = await fetchGoPublicCatalogIds({
|
|
1137
|
+
url: value.modelsUrl,
|
|
1138
|
+
fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
1139
|
+
timeoutMs: config.refreshTimeoutMs.get(),
|
|
1140
|
+
})
|
|
1141
|
+
return result.ok ? result.ids : undefined
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const migrateDeps = async (
|
|
1145
|
+
target: Context,
|
|
1146
|
+
opts: { adopt?: boolean; rewriteRefs?: RewriteRefMode; pruneUserExtra?: boolean } = {},
|
|
1147
|
+
needsEntries = true,
|
|
1148
|
+
): Promise<MigrateDeps> => {
|
|
1149
|
+
const { value } = readGoRuntimeConfig(config)
|
|
1150
|
+
const settings = settingsForWriteFrom(target)
|
|
1151
|
+
const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
1152
|
+
const apiKey = await resolveRouteCredentialValue(
|
|
1153
|
+
target as unknown as NativeCredentialContext,
|
|
1154
|
+
desc,
|
|
1155
|
+
'opencode-go',
|
|
1156
|
+
value.ref,
|
|
1157
|
+
)
|
|
1158
|
+
const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE) as
|
|
1159
|
+
| ((rewrite: ReferenceRewrite) => Promise<void>) | undefined
|
|
1160
|
+
// Keep the pre-action-table evaluation order: the file-backed stores fail
|
|
1161
|
+
// closed without a profile identity, and must do so BEFORE any source
|
|
1162
|
+
// fetch (D4: no identity ⇒ zero outbound requests, zero writes).
|
|
1163
|
+
const ownershipStore = (target.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
|
|
1164
|
+
?? ownershipStoreForRound()
|
|
1165
|
+
const store = migrationStore()
|
|
1166
|
+
// status/rollback never need the official listing: no fetch, no extra I/O.
|
|
1167
|
+
const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : []
|
|
1168
|
+
const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined
|
|
1169
|
+
const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
|
|
1170
|
+
|| settings === undefined || typeof settings.mutate !== 'function'
|
|
1171
|
+
return {
|
|
1172
|
+
settings,
|
|
1173
|
+
ownershipStore,
|
|
1174
|
+
migrationStore: store,
|
|
1175
|
+
logger: target.logger as unknown as Logger,
|
|
1176
|
+
entries,
|
|
1177
|
+
publicCatalogIds,
|
|
1178
|
+
routes: value.routes,
|
|
1179
|
+
ref: value.ref,
|
|
1180
|
+
keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
|
|
1181
|
+
adopt: opts.adopt,
|
|
1182
|
+
adoptDisabled,
|
|
1183
|
+
rewriteRefs: opts.rewriteRefs,
|
|
1184
|
+
// Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
|
|
1185
|
+
pinnedModels: value.pinnedModels,
|
|
1186
|
+
pruneUserExtra: opts.pruneUserExtra,
|
|
1187
|
+
now: Date.now(),
|
|
1188
|
+
isSyncInFlight: (ctx.get(GO_MIGRATION_MUTEX_SERVICE) as (() => boolean) | undefined)
|
|
1189
|
+
?? (() => goScheduler.isInFlight),
|
|
1190
|
+
applyReferenceRewrite: refWriter,
|
|
1191
|
+
// O1/C2: apply/rollback clear this profile's journals so a stale slot
|
|
1192
|
+
// cannot re-account settings that the migration just rewrote or undid.
|
|
1193
|
+
journalStore: journalStoreForRound(),
|
|
1194
|
+
profileKey,
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/** Shared by the slash command and the `modelSync` host service (§14.5). */
|
|
1199
|
+
const runMigrate = async (
|
|
1200
|
+
args: string[],
|
|
1201
|
+
target: Context,
|
|
1202
|
+
): Promise<{ kind: 'success' | 'error'; text: string }> => {
|
|
1203
|
+
const usage = [
|
|
1204
|
+
'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
|
|
1205
|
+
' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
|
|
1206
|
+
' /model-sync migrate rollback --plan <planHash>',
|
|
1207
|
+
' /model-sync migrate status',
|
|
1208
|
+
].join('\n')
|
|
1209
|
+
const action = args[0] ?? 'plan'
|
|
1210
|
+
const rest = args.slice(1)
|
|
1211
|
+
if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
|
|
1212
|
+
return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` }
|
|
1213
|
+
}
|
|
1214
|
+
// Consent has no bypass: these flags are recognised and rejected explicitly.
|
|
1215
|
+
if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
|
|
1216
|
+
return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' }
|
|
1217
|
+
}
|
|
1218
|
+
const flagValue = (name: string): string | undefined => {
|
|
1219
|
+
const index = rest.indexOf(name)
|
|
1220
|
+
if (index >= 0) return rest[index + 1]
|
|
1221
|
+
const inline = rest.find((token) => token.startsWith(`${name}=`))
|
|
1222
|
+
return inline?.slice(name.length + 1)
|
|
1223
|
+
}
|
|
1224
|
+
const planHash = flagValue('--plan')
|
|
1225
|
+
const confirmCode = flagValue('--confirm')
|
|
1226
|
+
const adopt = rest.includes('--adopt')
|
|
1227
|
+
const ackManaged = rest.includes('--ack-managed')
|
|
1228
|
+
const pruneUserExtra = rest.includes('--prune-user-extra')
|
|
1229
|
+
const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length)
|
|
1230
|
+
const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
|
|
1231
|
+
? rewriteRefsRaw as RewriteRefMode
|
|
1232
|
+
: undefined
|
|
1233
|
+
|
|
1234
|
+
try {
|
|
1235
|
+
if (action === 'status') {
|
|
1236
|
+
const deps = await migrateDeps(target, {}, false)
|
|
1237
|
+
const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled })
|
|
1238
|
+
return { kind: 'success', text: report.text }
|
|
1239
|
+
}
|
|
1240
|
+
if (action === 'plan') {
|
|
1241
|
+
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
|
|
1242
|
+
const record = await deps.migrationStore.read().catch(() => undefined)
|
|
1243
|
+
// Same pure builder apply uses — the printed table IS the consented one.
|
|
1244
|
+
// When adopt is disabled the mode is reported as adopt-disabled and the
|
|
1245
|
+
// rows stay conservative; no adopt action can be printed as executable.
|
|
1246
|
+
const plan = buildMigrationPlanFromDeps(deps, record)
|
|
1247
|
+
return { kind: 'success', text: formatMigrationPlan(plan) }
|
|
1248
|
+
}
|
|
1249
|
+
if (action === 'apply') {
|
|
1250
|
+
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
|
|
1251
|
+
// Fail-closed fallback (§14.2): reject at the command layer before any
|
|
1252
|
+
// write when the per-id action table cannot be executed verbatim.
|
|
1253
|
+
if (adopt && deps.adoptDisabled === true) {
|
|
1254
|
+
return {
|
|
1255
|
+
kind: 'error',
|
|
1256
|
+
text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
const result = await applyMigration({ planHash, confirmCode, ackManaged }, deps)
|
|
1260
|
+
return { kind: result.ok ? 'success' : 'error', text: result.text }
|
|
1261
|
+
}
|
|
1262
|
+
// rollback
|
|
1263
|
+
const deps = await migrateDeps(target, {}, false)
|
|
1264
|
+
const result = await rollbackMigration({ planHash }, deps)
|
|
1265
|
+
return { kind: result.ok ? 'success' : 'error', text: result.text }
|
|
1266
|
+
} catch (error) {
|
|
1267
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1268
|
+
return { kind: 'error', text: `migrate ${action} failed: ${message}` }
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// -----------------------------------------------------------------------
|
|
1273
|
+
// One-shot migrate-go deps (design: one command = plan + backup + confirm
|
|
1274
|
+
// + apply). Assembled from the same seams migrateDeps reads; the fs subset
|
|
1275
|
+
// and the clock are the only new external surfaces, both plain adapters
|
|
1276
|
+
// over node:fs/promises and Date here so tests inject their own.
|
|
1277
|
+
// -----------------------------------------------------------------------
|
|
1278
|
+
const oneShotFs: OneShotFs = {
|
|
1279
|
+
readFile: (path) => readFile(path, 'utf8'),
|
|
1280
|
+
writeFile: (path, data, mode) => (mode === undefined ? writeFile(path, data) : writeFile(path, data, { mode })),
|
|
1281
|
+
rename: (from, to) => rename(from, to),
|
|
1282
|
+
unlink: async (path) => { await unlink(path) },
|
|
1283
|
+
mkdir: async (path, options) => { await mkdir(path, options) },
|
|
1284
|
+
stat: async (path) => {
|
|
1285
|
+
const info = await statFd(path).catch(() => undefined)
|
|
1286
|
+
return info === undefined ? undefined : { mode: info.mode }
|
|
1287
|
+
},
|
|
1288
|
+
readdir: async (path) => readdir(path),
|
|
1289
|
+
// Backup creation: claim the final name exclusively (O_EXCL `wx` — false
|
|
1290
|
+
// when taken, so the caller retries the next sequence suffix), stamp the
|
|
1291
|
+
// claim with a recognizable placeholder line, then replace the claimed
|
|
1292
|
+
// file atomically via tmp + rename. A crash between claim and rename
|
|
1293
|
+
// leaves a self-describing placeholder (review M7) instead of a silent
|
|
1294
|
+
// 0-byte file that looks like a real backup; the tmp+rename guarantees the
|
|
1295
|
+
// backup content itself is never torn. A failure of the tmp write or the
|
|
1296
|
+
// rename releases the claim AND removes the tmp residue.
|
|
1297
|
+
writeFileExclusive: async (path, data, mode) => {
|
|
1298
|
+
let handle
|
|
1299
|
+
try {
|
|
1300
|
+
handle = await open(path, 'wx', mode)
|
|
1301
|
+
} catch (err) {
|
|
1302
|
+
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false
|
|
1303
|
+
throw err
|
|
1304
|
+
}
|
|
1305
|
+
try {
|
|
1306
|
+
// The file was created with `mode` by open(wx); the placeholder write
|
|
1307
|
+
// keeps that mode — no explicit mode needed here.
|
|
1308
|
+
await handle.writeFile('dsh-model-sync: backup claim in progress — crash residue, NOT a backup (safe to delete)\n')
|
|
1309
|
+
} finally {
|
|
1310
|
+
await handle.close().catch(() => {})
|
|
1311
|
+
}
|
|
1312
|
+
const tmp = `${path}.tmp-${process.pid}-${exclusiveWriteSeq++}`
|
|
1313
|
+
try {
|
|
1314
|
+
await writeFile(tmp, data, mode === undefined ? undefined : { mode })
|
|
1315
|
+
await rename(tmp, path)
|
|
1316
|
+
return true
|
|
1317
|
+
} catch (err) {
|
|
1318
|
+
await unlink(tmp).catch(() => {}) // remove the tmp residue (review M7)
|
|
1319
|
+
await unlink(path).catch(() => {}) // release the claim; nothing was replaced
|
|
1320
|
+
throw err
|
|
1321
|
+
}
|
|
1322
|
+
},
|
|
1323
|
+
}
|
|
1324
|
+
let exclusiveWriteSeq = 0
|
|
1325
|
+
/** Sync-read + atomic-write io for one patch file (describe() is sync). */
|
|
1326
|
+
const patchIoFor = (path: string): PatchFileIo => {
|
|
1327
|
+
let writeSeq = 0
|
|
1328
|
+
return {
|
|
1329
|
+
readText: () => readFileSync(path, 'utf8'),
|
|
1330
|
+
writeAtomic: async (text) => {
|
|
1331
|
+
writeSeq += 1
|
|
1332
|
+
const tmp = `${path}.tmp-${process.pid}-${writeSeq}`
|
|
1333
|
+
const mode = statSync(path).mode
|
|
1334
|
+
try {
|
|
1335
|
+
writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined)
|
|
1336
|
+
await rename(tmp, path)
|
|
1337
|
+
} catch (err) {
|
|
1338
|
+
await unlink(tmp).catch(() => {}) // no tmp residue on a failed write (review M7)
|
|
1339
|
+
throw err
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
const buildOneShotDeps = (target: Context): OneShotDeps => {
|
|
1345
|
+
const { value } = readGoRuntimeConfig(config)
|
|
1346
|
+
const settings = settingsForWriteFrom(target)
|
|
1347
|
+
const desc = settings?.describe().find((item) => item.ns === 'llm-pi-ai')
|
|
1348
|
+
const ref = value.ref
|
|
1349
|
+
const profile = target.get('profileContext') as { name?: string; dir?: string } | undefined
|
|
1350
|
+
const launchEnv = target.get('launchEnvironment') as { get(key: string): { value: string } | undefined } | undefined
|
|
1351
|
+
const injectedMutex = target.get(GO_MIGRATION_MUTEX_SERVICE) as (() => boolean) | undefined
|
|
1352
|
+
const injectedRefWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE) as
|
|
1353
|
+
| ((rewrite: ReferenceRewrite) => Promise<void>) | undefined
|
|
1354
|
+
const pathOverrides = target.get(GO_ONESHOT_PATHS_SERVICE) as GoOneShotPaths | undefined
|
|
1355
|
+
return {
|
|
1356
|
+
home: pathOverrides?.home ?? resolveDshHome(),
|
|
1357
|
+
modelsStorePath: pathOverrides?.modelsStorePath ?? MODELS_STORE_PATH,
|
|
1358
|
+
profilesDir: pathOverrides?.profilesDir,
|
|
1359
|
+
fs: oneShotFs,
|
|
1360
|
+
patchIoFor,
|
|
1361
|
+
currentProfile: {
|
|
1362
|
+
key: resolveProfileKey(target),
|
|
1363
|
+
dir: profile?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
|
|
1364
|
+
},
|
|
1365
|
+
currentSettings: settings,
|
|
1366
|
+
hostSettings: rawSettings() as (SettingsService & { update?(ns: string, patch: object): Promise<void> }) | undefined,
|
|
1367
|
+
goConfig: {
|
|
1368
|
+
routes: value.routes,
|
|
1369
|
+
ref,
|
|
1370
|
+
pinnedModels: value.pinnedModels,
|
|
1371
|
+
adoptDisabled: target.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
|
|
1372
|
+
|| settings === undefined || typeof settings.mutate !== 'function',
|
|
1373
|
+
},
|
|
1374
|
+
resolveCredential: async () => ({
|
|
1375
|
+
value: await resolveRouteCredentialValue(
|
|
1376
|
+
target as unknown as NativeCredentialContext,
|
|
1377
|
+
desc,
|
|
1378
|
+
'opencode-go',
|
|
1379
|
+
ref,
|
|
1380
|
+
),
|
|
1381
|
+
ref,
|
|
1382
|
+
}),
|
|
1383
|
+
resolveEntries: (apiKey) => resolveMigrateEntries(value, apiKey),
|
|
1384
|
+
resolvePublicCatalogIds: (_apiKey, entries) => resolvePublicCatalogIds(value, entries),
|
|
1385
|
+
resolveAsk: () => {
|
|
1386
|
+
try {
|
|
1387
|
+
return target.get('userQuestions') as AskServiceShape | undefined
|
|
1388
|
+
} catch {
|
|
1389
|
+
return undefined
|
|
1390
|
+
}
|
|
1391
|
+
},
|
|
1392
|
+
// File-backed stores scoped per profile in the SAME models-store.json
|
|
1393
|
+
// the backup step snapshots. The GO_MIGRATION_STORE_SERVICE /
|
|
1394
|
+
// GO_OWNERSHIP_STORE_SERVICE seams are deliberately NOT consulted
|
|
1395
|
+
// here: the one-shot needs per-profile scoping, which the injected
|
|
1396
|
+
// single-store seams cannot express — the path override below is the
|
|
1397
|
+
// test seam instead (tests point it at a temp dir).
|
|
1398
|
+
storesFor: (profileKey) => ({
|
|
1399
|
+
ownership: createModelsStoreOwnershipStore(pathOverrides?.modelsStorePath, profileKey),
|
|
1400
|
+
migration: createModelsStoreMigrationStateStore(pathOverrides?.modelsStorePath, profileKey),
|
|
1401
|
+
}),
|
|
1402
|
+
journalStore: profileKey === undefined ? undefined : createModelsStoreJournalStore(pathOverrides?.modelsStorePath),
|
|
1403
|
+
isSyncInFlight: injectedMutex ?? (() => goScheduler.isInFlight),
|
|
1404
|
+
applyReferenceRewrite: injectedRefWriter,
|
|
1405
|
+
...(pathOverrides?.testOnlyOwnershipWriteFaultPrefix !== undefined
|
|
1406
|
+
? { faultOwnershipWriteOnKeyPrefix: pathOverrides.testOnlyOwnershipWriteFaultPrefix }
|
|
1407
|
+
: {}),
|
|
1408
|
+
logger: target.logger as unknown as Logger,
|
|
1409
|
+
now: Date.now,
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
506
1413
|
/** Auto rounds log the same report the /model-sync command shows. */
|
|
507
1414
|
const runAuto = (): void => {
|
|
508
1415
|
// A rejected round (service lookups mid-dispose, a refused mutate) must
|
|
@@ -538,22 +1445,51 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
538
1445
|
// settings/document-updated event (the 0.1.7 replacement for scope.watch).
|
|
539
1446
|
startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000)
|
|
540
1447
|
armInterval(config.intervalMinutes.get() ?? 240)
|
|
541
|
-
ctx.effect(() => ctx.on('settings/document-updated', (ns) => {
|
|
542
|
-
//
|
|
543
|
-
//
|
|
544
|
-
//
|
|
545
|
-
|
|
1448
|
+
ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
|
|
1449
|
+
// P1d-1 §14.7.2: if this event is the echo of a settings.mutate we just
|
|
1450
|
+
// performed, only refresh status — schedule NO round (the V23 race was a
|
|
1451
|
+
// go write echo triggering the legacy pi.dev auto round ~1s later).
|
|
1452
|
+
if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
|
|
1453
|
+
ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision)
|
|
1454
|
+
void loadMigrationStatus() // refresh state only; no timer, no runAuto
|
|
1455
|
+
return
|
|
1456
|
+
}
|
|
1457
|
+
// Only this plugin's own config entry (the bundle-patch id) re-arms timers;
|
|
1458
|
+
// the handler is idempotent — the refs already carry the new values, so the
|
|
1459
|
+
// next round reads them fresh. A foreign ns (including llm-pi-ai writes by
|
|
1460
|
+
// other actors) never schedules a round here.
|
|
546
1461
|
if (ns !== OWN_ENTRY_ID) return
|
|
547
1462
|
armInterval(config.intervalMinutes.get() ?? 0)
|
|
548
|
-
//
|
|
549
|
-
|
|
550
|
-
|
|
1463
|
+
// §14.7.2 item 2: remove the old "immediate +1s runAuto". Config edits now
|
|
1464
|
+
// only re-arm the normal interval; an immediate round needs an explicit
|
|
1465
|
+
// /model-sync. (P1c-2 go scheduler still re-arms idempotently.)
|
|
1466
|
+
goScheduler.rearm()
|
|
1467
|
+
void loadMigrationStatus()
|
|
551
1468
|
}), 'dsh-model-sync: settings/document-updated')
|
|
552
1469
|
|
|
553
1470
|
// The modelSync service stays exposed for UIs that want direct access. The
|
|
554
1471
|
// /model-sync command itself is registered by this plugin (below) through
|
|
555
1472
|
// the shared command registry, which interactive UIs discover on their own.
|
|
556
|
-
ctx.provide('modelSync', {
|
|
1473
|
+
ctx.provide('modelSync', {
|
|
1474
|
+
syncNow: () => syncNow(true),
|
|
1475
|
+
migratePlan: (options) => runMigrate(
|
|
1476
|
+
['plan', ...(options?.adopt === true ? ['--adopt'] : []),
|
|
1477
|
+
...(options?.pruneUserExtra === true ? ['--prune-user-extra'] : []),
|
|
1478
|
+
...(options?.rewriteRefs !== undefined ? [`--rewrite-refs=${options.rewriteRefs}`] : [])],
|
|
1479
|
+
ctx,
|
|
1480
|
+
).then((result) => result.text),
|
|
1481
|
+
migrateApply: (args) => runMigrate(
|
|
1482
|
+
['apply', ...(args.planHash !== undefined ? ['--plan', args.planHash] : []),
|
|
1483
|
+
...(args.confirmCode !== undefined ? ['--confirm', args.confirmCode] : []),
|
|
1484
|
+
...(args.ackManaged === true ? ['--ack-managed'] : [])],
|
|
1485
|
+
ctx,
|
|
1486
|
+
).then((result) => result.text),
|
|
1487
|
+
migrateRollback: (args) => runMigrate(
|
|
1488
|
+
['rollback', ...(args.planHash !== undefined ? ['--plan', args.planHash] : [])],
|
|
1489
|
+
ctx,
|
|
1490
|
+
).then((result) => result.text),
|
|
1491
|
+
migrateStatus: () => runMigrate(['status'], ctx).then((result) => result.text),
|
|
1492
|
+
} satisfies ModelSyncService)
|
|
557
1493
|
|
|
558
1494
|
// Register the /model-sync slash command from the plugin itself. The
|
|
559
1495
|
// registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
|
|
@@ -571,8 +1507,87 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
571
1507
|
cmdCtx.effect(() => {
|
|
572
1508
|
const definition: CommandDefinition = {
|
|
573
1509
|
name: 'model-sync',
|
|
574
|
-
description: 'Force one model-list sync round from the pi.dev gateway into settings (
|
|
1510
|
+
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); migrate-go (one-shot full migration with file backups + one confirmation)',
|
|
575
1511
|
handler: async (invocation) => {
|
|
1512
|
+
const args = invocation.rawInput.trim().split(/\s+/).filter((part) => part.length > 0)
|
|
1513
|
+
const [sub, scope] = args
|
|
1514
|
+
// P1d-2: migration is the ONLY explicit-consent config writer. It is
|
|
1515
|
+
// never auto-triggered and never folded into the pi.dev sync path.
|
|
1516
|
+
if (sub === 'migrate') {
|
|
1517
|
+
return runMigrate(args.slice(1), cmdCtx)
|
|
1518
|
+
}
|
|
1519
|
+
// One-shot migrate-go: the full plan → backup → confirm → apply
|
|
1520
|
+
// pipeline for the current profile (or --all-profiles). Its consent
|
|
1521
|
+
// is the interactive confirmation; apply still passes through the
|
|
1522
|
+
// unchanged verifyConsent gate with the computed hash/code.
|
|
1523
|
+
if (sub === 'migrate-go') {
|
|
1524
|
+
const parsed = parseMigrateGoFlags(args.slice(1))
|
|
1525
|
+
if (!parsed.ok) {
|
|
1526
|
+
return { kind: 'error', text: parsed.error } satisfies CommandResult
|
|
1527
|
+
}
|
|
1528
|
+
const flags: MigrateGoFlags = parsed.flags
|
|
1529
|
+
try {
|
|
1530
|
+
return await runMigrateGoOneShot(
|
|
1531
|
+
buildOneShotDeps(cmdCtx),
|
|
1532
|
+
flags,
|
|
1533
|
+
{ agent: invocation.agent, signal: invocation.signal },
|
|
1534
|
+
)
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1537
|
+
return { kind: 'error', text: `migrate-go failed: ${message}` } satisfies CommandResult
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
// B3 (31 R-4): `eject` is retired — `migrate rollback` is the only
|
|
1541
|
+
// rollback entry. Reject the old invocation explicitly so it never
|
|
1542
|
+
// falls through to a bare sync (which would write to go routes under
|
|
1543
|
+
// a command name the user believed was read-only).
|
|
1544
|
+
if (sub === 'eject') {
|
|
1545
|
+
return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' } satisfies CommandResult
|
|
1546
|
+
}
|
|
1547
|
+
// Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
|
|
1548
|
+
// as it was. The go subcommands are additive: `go`/`status` run one
|
|
1549
|
+
// full go round, `adopt go` runs it with adoption. Status stays the
|
|
1550
|
+
// read-only `/opencode-status` command — it is never a write trigger.
|
|
1551
|
+
if ((sub === 'go' || sub === 'status' || sub === 'adopt')
|
|
1552
|
+
&& (scope === undefined || scope === 'go')) {
|
|
1553
|
+
try {
|
|
1554
|
+
// Route manual rounds through the scheduler so they share the
|
|
1555
|
+
// single-flight lock with timer-driven rounds. A second trigger
|
|
1556
|
+
// while a round is in flight is skipped and reported (design
|
|
1557
|
+
// §14.6), never queued. The report text is the round's own text,
|
|
1558
|
+
// unchanged, for real rounds.
|
|
1559
|
+
const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' })
|
|
1560
|
+
// N1: a round that threw (e.g. the file-backed ledger refusing to
|
|
1561
|
+
// build without a profile identity) is reported as a scheduler
|
|
1562
|
+
// error. It is a real failure — the command must return
|
|
1563
|
+
// `kind:'error'` so callers that only read `kind` can detect it;
|
|
1564
|
+
// the actionable reason is carried in `text`. Skips (disabled,
|
|
1565
|
+
// already-in-flight, migration-applying, disposed) stay success,
|
|
1566
|
+
// byte-identical to before.
|
|
1567
|
+
const failed = outcome.reason === 'source-failed'
|
|
1568
|
+
// oldfox #3: a writer exception is a real failure at the
|
|
1569
|
+
// command surface, but a distinct reason from source failure.
|
|
1570
|
+
|| outcome.reason === 'writer-error'
|
|
1571
|
+
|| outcome.reason === 'scheduler-error'
|
|
1572
|
+
// B4: an abandoned round must be visible as a failure at the
|
|
1573
|
+
// command surface too (it is not a successful sync). The reason
|
|
1574
|
+
// text carries the actionable "settings changed, next round
|
|
1575
|
+
// retries" guidance; no backoff is scheduled for it.
|
|
1576
|
+
|| outcome.reason === 'settings-changed-during-sync'
|
|
1577
|
+
// O1-minimal: failedRoutes (e.g. settings written but the ledger
|
|
1578
|
+
// failed) are a real failure even if other routes wrote. Callers
|
|
1579
|
+
// that only read `kind` must see `error`; the actionable reason
|
|
1580
|
+
// and the new report code are carried in `text`.
|
|
1581
|
+
|| outcome.reason === 'write-failed'
|
|
1582
|
+
return {
|
|
1583
|
+
kind: failed ? 'error' : 'success',
|
|
1584
|
+
text: outcome.text,
|
|
1585
|
+
} satisfies CommandResult
|
|
1586
|
+
} catch (error) {
|
|
1587
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1588
|
+
return { kind: 'error', text: `model-sync ${sub} failed: ${message}` } satisfies CommandResult
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
576
1591
|
const ignored = invocation.rawInput.trim().length > 0
|
|
577
1592
|
? 'The sync scope is decided by the model-sync managedRoutes config; the argument is ignored.\n'
|
|
578
1593
|
: ''
|
|
@@ -587,6 +1602,39 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
587
1602
|
}
|
|
588
1603
|
return commands.register(definition)
|
|
589
1604
|
}, 'dsh-model-sync: /model-sync')
|
|
1605
|
+
|
|
1606
|
+
// P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
|
|
1607
|
+
// unchanged): fetch the official go listing, compare it with the current
|
|
1608
|
+
// profile's opencode-go routes, and print a structured report. This path
|
|
1609
|
+
// never calls settings.mutate, never writes credentials, and never edits
|
|
1610
|
+
// a profile file — it only reads describe()/credentials.resolve().
|
|
1611
|
+
cmdCtx.effect(() => {
|
|
1612
|
+
const definition: CommandDefinition = {
|
|
1613
|
+
name: 'opencode-status',
|
|
1614
|
+
description: 'Read-only diagnostic: compare opencode-go official /v1/models with the current profile routes (no writes)',
|
|
1615
|
+
handler: async (invocation) => {
|
|
1616
|
+
const token = invocation.rawInput.trim()
|
|
1617
|
+
const ignored = token !== '' && token !== 'go'
|
|
1618
|
+
? 'opencode-status: P0 diagnoses opencode-go only; the argument is ignored.\n'
|
|
1619
|
+
: ''
|
|
1620
|
+
try {
|
|
1621
|
+
const desc = (cmdCtx.get('settings') as SettingsService | undefined)?.describe()
|
|
1622
|
+
.find((d) => d.ns === 'llm-pi-ai')
|
|
1623
|
+
const apiKey = await resolveRouteCredentialValue(
|
|
1624
|
+
cmdCtx as unknown as NativeCredentialContext,
|
|
1625
|
+
desc,
|
|
1626
|
+
'opencode-go',
|
|
1627
|
+
)
|
|
1628
|
+
const report = await runGoDiagnostic({ apiKey, descriptor: desc })
|
|
1629
|
+
return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` } satisfies CommandResult
|
|
1630
|
+
} catch (error) {
|
|
1631
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1632
|
+
return { kind: 'error', text: `${ignored}opencode-status failed: ${message}` } satisfies CommandResult
|
|
1633
|
+
}
|
|
1634
|
+
},
|
|
1635
|
+
}
|
|
1636
|
+
return commands.register(definition)
|
|
1637
|
+
}, 'dsh-model-sync: /opencode-status')
|
|
590
1638
|
})
|
|
591
1639
|
|
|
592
1640
|
// One-time legacy settings import (0.1.5 → 0.1.7 upgrade path, see
|