@aiwayds/dsh-model-sync 0.12.1 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -17
- package/README.zh-CN.md +18 -17
- package/lib/index.d.ts +54 -384
- package/lib/index.js +306 -1107
- package/lib/index.js.map +1 -1
- package/lib/official-adapter.d.ts +80 -0
- package/lib/official-adapter.js +34 -0
- package/lib/official-adapter.js.map +1 -0
- package/lib/official-migrate.d.ts +122 -0
- package/lib/official-migrate.js +653 -0
- package/lib/official-migrate.js.map +1 -0
- package/lib/official-scheduler.d.ts +72 -0
- package/lib/official-scheduler.js +195 -0
- package/lib/official-scheduler.js.map +1 -0
- package/lib/official-store.d.ts +41 -0
- package/lib/official-store.js +84 -0
- package/lib/official-store.js.map +1 -0
- package/lib/official-sync.d.ts +68 -0
- package/lib/official-sync.js +274 -0
- package/lib/official-sync.js.map +1 -0
- package/lib/opencode-go-adapter.d.ts +56 -0
- package/lib/opencode-go-adapter.js +455 -0
- package/lib/opencode-go-adapter.js.map +1 -0
- package/lib/opencode-go-patch-file.d.ts +11 -0
- package/lib/opencode-go-patch-file.js +175 -11
- package/lib/opencode-go-patch-file.js.map +1 -1
- package/lib/opencode-go-source.d.ts +1 -1
- package/lib/opencode-go-source.js +1 -1
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -3
- package/src/index.ts +352 -1281
- package/src/official-adapter.ts +111 -0
- package/src/official-migrate.ts +863 -0
- package/src/official-scheduler.ts +235 -0
- package/src/official-store.ts +122 -0
- package/src/official-sync.ts +371 -0
- package/src/opencode-go-adapter.ts +494 -0
- package/src/opencode-go-patch-file.ts +175 -9
- package/src/opencode-go-source.ts +1 -1
- package/lib/opencode-go-diagnose.d.ts +0 -96
- package/lib/opencode-go-diagnose.js +0 -177
- package/lib/opencode-go-diagnose.js.map +0 -1
- package/lib/opencode-go-grouping.d.ts +0 -7
- package/lib/opencode-go-grouping.js +0 -21
- package/lib/opencode-go-grouping.js.map +0 -1
- package/lib/opencode-go-host-catalog.d.ts +0 -42
- package/lib/opencode-go-host-catalog.js +0 -98
- package/lib/opencode-go-host-catalog.js.map +0 -1
- package/lib/opencode-go-journal.d.ts +0 -114
- package/lib/opencode-go-journal.js +0 -406
- package/lib/opencode-go-journal.js.map +0 -1
- package/lib/opencode-go-migrate.d.ts +0 -378
- package/lib/opencode-go-migrate.js +0 -1529
- package/lib/opencode-go-migrate.js.map +0 -1
- package/lib/opencode-go-migration.d.ts +0 -270
- package/lib/opencode-go-migration.js +0 -473
- package/lib/opencode-go-migration.js.map +0 -1
- package/lib/opencode-go-one-shot.d.ts +0 -282
- package/lib/opencode-go-one-shot.js +0 -1131
- package/lib/opencode-go-one-shot.js.map +0 -1
- package/lib/opencode-go-planner.d.ts +0 -168
- package/lib/opencode-go-planner.js +0 -407
- package/lib/opencode-go-planner.js.map +0 -1
- package/lib/opencode-go-scheduler.d.ts +0 -128
- package/lib/opencode-go-scheduler.js +0 -241
- package/lib/opencode-go-scheduler.js.map +0 -1
- package/lib/opencode-go-store.d.ts +0 -18
- package/lib/opencode-go-store.js +0 -68
- package/lib/opencode-go-store.js.map +0 -1
- package/lib/opencode-go-sync.d.ts +0 -107
- package/lib/opencode-go-sync.js +0 -388
- package/lib/opencode-go-sync.js.map +0 -1
- package/lib/opencode-go-writer.d.ts +0 -148
- package/lib/opencode-go-writer.js +0 -1061
- package/lib/opencode-go-writer.js.map +0 -1
- package/src/opencode-go-diagnose.ts +0 -276
- package/src/opencode-go-grouping.ts +0 -26
- package/src/opencode-go-host-catalog.ts +0 -125
- package/src/opencode-go-journal.ts +0 -460
- package/src/opencode-go-migrate.ts +0 -1951
- package/src/opencode-go-migration.ts +0 -666
- package/src/opencode-go-one-shot.ts +0 -1399
- package/src/opencode-go-planner.ts +0 -582
- package/src/opencode-go-scheduler.ts +0 -315
- package/src/opencode-go-store.ts +0 -73
- package/src/opencode-go-sync.ts +0 -541
- package/src/opencode-go-writer.ts +0 -1301
package/src/index.ts
CHANGED
|
@@ -1,84 +1,39 @@
|
|
|
1
|
-
// Plan C (settings-seam): orchestrator with overlay and settings modes.
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
|
-
* dsh-model-sync —
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* Supports two write modes:
|
|
8
|
-
* - 'settings' (default): self-contained fetch → translate → settings.mutate
|
|
9
|
-
* pipeline that writes through the host settings service (zero patch
|
|
10
|
-
* required; settings.yaml up to dsh 0.1.6, the profile patch on 0.1.7+)
|
|
11
|
-
* - 'overlay' (legacy, deprecated): delegates to the patched dsh-llm-pi-ai's
|
|
12
|
-
* piAiCatalog.refresh() to overlay pi.dev entries in memory. dsh 0.2.1
|
|
13
|
-
* removed the piAiCatalog seam entirely (the pi-ai 0.87.1 → 1.3.0
|
|
14
|
-
* ModelsStore rework), so this mode can never refresh there and every
|
|
15
|
-
* round degrades to a notice; use the settings mode.
|
|
2
|
+
* dsh-model-sync — keep Builtin Providers synchronized with pi.dev and
|
|
3
|
+
* detach supported Official Sync vendors (starting with OpenCode Go) into
|
|
4
|
+
* per-protocol Managed Custom Providers backed by their official models API.
|
|
16
5
|
*
|
|
17
6
|
* @module dsh-model-sync
|
|
18
7
|
*/
|
|
19
8
|
|
|
20
9
|
import z from '@deepseek-ai/schemastery'
|
|
21
10
|
import type { Context } from '@deepseek-ai/cordis'
|
|
22
|
-
// Type-only side-effect import: loads dsh-settings' `declare module
|
|
23
|
-
// '@deepseek-ai/cordis'` augmentation, which is what puts `ctx.settings` on
|
|
24
|
-
// the Context type. There is no runtime import — the host provides the
|
|
25
|
-
// settings service; alpha.3 removed the settingsNamespace() helper this file
|
|
26
|
-
// used to import.
|
|
27
11
|
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
12
|
import type {} from '@deepseek-ai/dsh-credentials/types'
|
|
33
|
-
// Types only (erased at emit); dsh-commands is an optional peer, so hosts
|
|
34
|
-
// without it still load this plugin — see the guarded registration below.
|
|
35
13
|
import type { CommandDefinition, CommandResult } from '@deepseek-ai/dsh-commands'
|
|
36
|
-
import {
|
|
14
|
+
import { diffEntries, diffModelIds } from './diff.ts'
|
|
37
15
|
import {
|
|
16
|
+
MODELS_STORE_PATH,
|
|
38
17
|
fetchRemoteCatalog,
|
|
39
18
|
loadModelsStore,
|
|
19
|
+
type ModelsStoreAccessor,
|
|
40
20
|
type RemoteCatalogEntry,
|
|
41
21
|
} from './remote-catalog.ts'
|
|
42
22
|
import {
|
|
43
23
|
translateEntries,
|
|
24
|
+
type BuiltinModelData,
|
|
44
25
|
type SettingsModelProfile,
|
|
45
26
|
type TranslateOptions,
|
|
46
|
-
type DropWarning,
|
|
47
|
-
type BuiltinModelData,
|
|
48
27
|
} from './translate.ts'
|
|
49
28
|
import {
|
|
50
29
|
syncToSettings,
|
|
51
|
-
type SettingsService,
|
|
52
|
-
type SettingsDescriptor,
|
|
53
30
|
type Logger,
|
|
31
|
+
type SettingsDescriptor,
|
|
32
|
+
type SettingsService,
|
|
54
33
|
} from './writer.ts'
|
|
55
34
|
import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
|
|
56
|
-
import {
|
|
57
|
-
import { checkRouteCredential,
|
|
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'
|
|
35
|
+
import { getLiveBuiltinCatalogForRoute, refreshLiveCatalog } from './live-catalog.ts'
|
|
36
|
+
import { checkRouteCredential, type RouteCredentialContext } from './route-credential.ts'
|
|
82
37
|
import {
|
|
83
38
|
PROVIDER_NATIVE_ENDPOINTS,
|
|
84
39
|
fetchProviderNativeModels,
|
|
@@ -87,219 +42,102 @@ import {
|
|
|
87
42
|
type NativeCredentialContext,
|
|
88
43
|
} from './provider-native.ts'
|
|
89
44
|
import {
|
|
90
|
-
runLegacySettingsImport,
|
|
91
45
|
resolveDshHome,
|
|
46
|
+
runLegacySettingsImport,
|
|
92
47
|
type LegacyImportLogger,
|
|
93
48
|
type SettingsUpdateSeam,
|
|
94
49
|
} from './legacy-import.ts'
|
|
95
|
-
import {
|
|
96
|
-
import {
|
|
97
|
-
PROFILE_IDENTITY_REQUIRED_MESSAGE,
|
|
98
|
-
PROFILE_IDENTITY_STATUS_HINT,
|
|
99
|
-
resolveProfileKey,
|
|
100
|
-
} from './opencode-go-profile.ts'
|
|
50
|
+
import { OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, OPENCODE_GO_MODELS_URL, type GoFetchLike } from './opencode-go-source.ts'
|
|
51
|
+
import { resolveProfileKey } from './opencode-go-profile.ts'
|
|
101
52
|
import {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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'
|
|
53
|
+
formatUnsupportedProviderError,
|
|
54
|
+
listOfficialAdapters,
|
|
55
|
+
resolveOfficialAdapter,
|
|
56
|
+
type CompatHintsByProtocol,
|
|
57
|
+
type OfficialAdapterConfig,
|
|
58
|
+
type SessionHeaderMode,
|
|
59
|
+
type UpstreamProviderAdapter,
|
|
60
|
+
} from './official-adapter.ts'
|
|
118
61
|
import {
|
|
119
|
-
|
|
120
|
-
|
|
62
|
+
createDefaultOfficialMigrationStore,
|
|
63
|
+
createOfficialMigrationStore,
|
|
64
|
+
type OfficialMigrationRecord,
|
|
65
|
+
type OfficialMigrationStore,
|
|
66
|
+
} from './official-store.ts'
|
|
121
67
|
import {
|
|
122
|
-
|
|
123
|
-
type
|
|
124
|
-
} from './
|
|
68
|
+
runOfficialSyncRound,
|
|
69
|
+
type OfficialCredentialContext,
|
|
70
|
+
} from './official-sync.ts'
|
|
125
71
|
import {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
rollbackMigration,
|
|
131
|
-
type MigrateDeps,
|
|
132
|
-
type ReferenceRewrite,
|
|
133
|
-
type RewriteRefMode,
|
|
134
|
-
} from './opencode-go-migrate.ts'
|
|
72
|
+
OfficialSyncScheduler,
|
|
73
|
+
type OfficialSchedulerRandom,
|
|
74
|
+
type OfficialSchedulerTimers,
|
|
75
|
+
} from './official-scheduler.ts'
|
|
135
76
|
import {
|
|
136
|
-
|
|
137
|
-
|
|
77
|
+
runOfficialMigrate,
|
|
78
|
+
runOfficialRollback,
|
|
79
|
+
runOfficialStatus,
|
|
138
80
|
type AskServiceShape,
|
|
139
|
-
type
|
|
140
|
-
type
|
|
141
|
-
|
|
142
|
-
} from './opencode-go-one-shot.ts'
|
|
81
|
+
type MigrateFs,
|
|
82
|
+
type OfficialMigrateDeps,
|
|
83
|
+
} from './official-migrate.ts'
|
|
143
84
|
import type { PatchFileIo } from './opencode-go-patch-file.ts'
|
|
144
|
-
import { MODELS_STORE_PATH } from './remote-catalog.ts'
|
|
145
|
-
import { mkdir, open, readFile, readdir, rename, stat as statFd, unlink, writeFile } from 'node:fs/promises'
|
|
146
|
-
import { readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
147
85
|
|
|
148
86
|
export const name = 'dsh-model-sync'
|
|
149
87
|
|
|
150
|
-
/** The settings seam this plugin consumes (its own config namespace). */
|
|
151
88
|
export const inject = ['settings']
|
|
152
89
|
|
|
153
|
-
/**
|
|
154
|
-
export const
|
|
155
|
-
export const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
export const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
* array, `null` (fail-closed shape) or an async function; production resolves
|
|
163
|
-
* through the llm seam at each call site so a host adapter swap is picked up
|
|
164
|
-
* live.
|
|
165
|
-
*/
|
|
166
|
-
export const GO_HOST_CATALOG_SERVICE = 'goHostCatalog'
|
|
167
|
-
/** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
|
|
168
|
-
export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled'
|
|
169
|
-
/** Optional override for the single-flight check (tests inject an in-flight mutex). */
|
|
170
|
-
export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex'
|
|
171
|
-
/** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
|
|
172
|
-
export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore'
|
|
173
|
-
/**
|
|
174
|
-
* One-shot migrate-go path overrides (tests point everything at a temp dir;
|
|
175
|
-
* a host may pin non-default locations). Plain `undefined` fields fall back
|
|
176
|
-
* to resolveDshHome() / MODELS_STORE_PATH / `<home>/profiles`.
|
|
177
|
-
*/
|
|
178
|
-
export const GO_ONESHOT_PATHS_SERVICE = 'goOneShotPaths'
|
|
179
|
-
export interface GoOneShotPaths {
|
|
90
|
+
/** Optional test/host service seams for Official Sync. */
|
|
91
|
+
export const OFFICIAL_FETCH_SERVICE = 'officialFetch'
|
|
92
|
+
export const OFFICIAL_SCHEDULER_TIMERS_SERVICE = 'officialSchedulerTimers'
|
|
93
|
+
export const OFFICIAL_SCHEDULER_RANDOM_SERVICE = 'officialSchedulerRandom'
|
|
94
|
+
export const OFFICIAL_SESSION_HEADER_DETECT_SERVICE = 'officialSessionHeaderDetect'
|
|
95
|
+
export const OFFICIAL_COMPAT_HINTS_SERVICE = 'officialCompatHints'
|
|
96
|
+
export const OFFICIAL_MIGRATION_PATHS_SERVICE = 'officialMigrationPaths'
|
|
97
|
+
|
|
98
|
+
export interface OfficialMigrationPaths {
|
|
180
99
|
home?: string
|
|
181
100
|
modelsStorePath?: string
|
|
182
101
|
profilesDir?: string
|
|
183
|
-
|
|
184
|
-
|
|
102
|
+
fs?: MigrateFs
|
|
103
|
+
patchIoFor?: (path: string) => PatchFileIo
|
|
104
|
+
storeAccessor?: ModelsStoreAccessor
|
|
105
|
+
now?: () => number
|
|
185
106
|
}
|
|
186
107
|
|
|
187
|
-
// dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
|
|
188
|
-
// is gone, and a plugin's settings form is projected from its exported
|
|
189
|
-
// `Config` schema — the namespace IS the profile entry id. The bundle patch
|
|
190
|
-
// mounts this plugin under the stable id below, so `dsh-model-sync` is the
|
|
191
|
-
// namespace the settings UI (and the legacy settings.yaml import) address.
|
|
192
108
|
const OWN_ENTRY_ID = 'dsh-model-sync'
|
|
193
109
|
|
|
194
|
-
/**
|
|
195
|
-
* The plugin's `Config` schema: the settings form the 0.1.7 host projects from
|
|
196
|
-
* the `dsh-model-sync` entry. Every field is user-adjustable and therefore
|
|
197
|
-
* `.volatile()` — volatile fields are the only ones the settings page can edit
|
|
198
|
-
* (and the only ones the legacy settings.yaml import accepts), and they hot-
|
|
199
|
-
* reload without remounting the plugin. Requires schemastery >= 3.18.4 (the
|
|
200
|
-
* version the dsh 0.1.7 wave ships), which provides `.volatile()`.
|
|
201
|
-
*/
|
|
202
110
|
export const Config = z.object({
|
|
203
|
-
/**
|
|
204
|
-
* Write mode: 'settings' (default, zero-patch settings.mutate pipeline) or
|
|
205
|
-
* 'overlay'. DEPRECATED: 'overlay' delegates to the patched adapter's
|
|
206
|
-
* piAiCatalog.refresh, a seam dsh 0.2.1 removed outright (pi-ai 1.3.0
|
|
207
|
-
* ModelsStore rework) — every overlay round now degrades to a notice.
|
|
208
|
-
* Use the settings mode.
|
|
209
|
-
*/
|
|
210
111
|
writeMode: z.union(['settings', 'overlay']).default('settings').volatile(),
|
|
211
|
-
/** Minutes between auto refreshes (default 240 = 4 hours); 0 = startup-only. */
|
|
212
112
|
intervalMinutes: z.number().step(1).min(0).default(240).volatile(),
|
|
213
|
-
/** Delay before the first auto refresh, so the llm adapter is ready. */
|
|
214
113
|
startupDelaySeconds: z.number().step(1).min(0).default(5).volatile(),
|
|
215
|
-
/** Abort budget for one forced refresh's network round. */
|
|
216
114
|
refreshTimeoutMs: z.number().step(1).min(1000).default(120000).volatile(),
|
|
217
|
-
/** Routes to manage (empty = all pi.dev routes). */
|
|
218
115
|
managedRoutes: z.array(z.string()).default([]).volatile(),
|
|
219
|
-
/** Keep builtin-only models not in pi.dev (smooth migration). */
|
|
220
116
|
keepBuiltinOnly: z.boolean().default(true).volatile(),
|
|
221
|
-
/** Drop unserviceable entries (true) or abort the entire route (false). */
|
|
222
117
|
dropUnserviceable: z.boolean().default(true).volatile(),
|
|
223
|
-
/**
|
|
224
|
-
* Union each mapped route's first-party /models listing into the pi.dev
|
|
225
|
-
* result (additions only — see provider-native.ts). Default on: the native
|
|
226
|
-
* listing is the fresher source; pi.dev lags (measured 2026-09-22).
|
|
227
|
-
*/
|
|
228
118
|
providerNativeFetch: z.boolean().default(true).volatile(),
|
|
229
|
-
/** Notify on changes (logger + /model-sync report). */
|
|
230
119
|
syncNotify: z.boolean().default(false).volatile(),
|
|
231
|
-
/**
|
|
232
|
-
* Force all models with a non-empty thinkingFormat to have max reasoning
|
|
233
|
-
* effort. Skips S2 gate's SRE check, ensures reasoningEfforts contains
|
|
234
|
-
* max, and forces compat.supportsReasoningEffort=true (S5 gate, openai-
|
|
235
|
-
* completions only). 400 risk is on the user.
|
|
236
|
-
*/
|
|
237
120
|
forceMaxReasoningEffort: z.boolean().default(false).volatile(),
|
|
238
|
-
/**
|
|
239
|
-
* keepBuiltinOnly may re-emit builtin ids the official default model list
|
|
240
|
-
* dropped (dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-
|
|
241
|
-
* exp). Those stay in the snapshot for historical user configurations but
|
|
242
|
-
* are excluded from the synced list unless this flag opts them back in —
|
|
243
|
-
* a re-emitted retired id is a model the 0.1.7 host no longer resolves.
|
|
244
|
-
*/
|
|
245
121
|
keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
* Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
|
|
250
|
-
* intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
|
|
251
|
-
* (go.routes/adoptExisting/pinnedModels/confirmRemovals,
|
|
252
|
-
* zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
|
|
253
|
-
* `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
|
|
254
|
-
* impossible. Zen stays login-only with no modelsUrl by default (design A5).
|
|
255
|
-
* Nested leaves are `.volatile()` (host settings can edit them); the parent
|
|
256
|
-
* objects are not, because schemastery forbids a volatile field under an
|
|
257
|
-
* enclosing volatile field.
|
|
258
|
-
*/
|
|
259
|
-
opencode: z.object({
|
|
260
|
-
go: z.object({
|
|
261
|
-
enabled: z.boolean().default(false).volatile(),
|
|
262
|
-
ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
|
|
122
|
+
officialSync: z.object({
|
|
123
|
+
'opencode-go': z.object({
|
|
124
|
+
intervalMinutes: z.number().step(1).min(0).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
|
|
263
125
|
modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
|
|
264
|
-
|
|
265
|
-
adoptExisting: z.boolean().default(false).volatile(),
|
|
266
|
-
pinnedModels: z.array(z.string()).default([]).volatile(),
|
|
126
|
+
sessionHeader: z.union(['auto', 'static', 'none']).default('auto').volatile(),
|
|
267
127
|
routes: z.object({
|
|
268
|
-
chat: z.string().default('opencode-go').volatile(),
|
|
128
|
+
chat: z.string().default('opencode-go-chat').volatile(),
|
|
269
129
|
msg: z.string().default('opencode-go-msg').volatile(),
|
|
270
130
|
resp: z.string().default('opencode-go-resp').volatile(),
|
|
271
131
|
google: z.string().default('opencode-go-google').volatile(),
|
|
272
132
|
}).default({}),
|
|
273
|
-
confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
|
|
274
|
-
}).default({}),
|
|
275
|
-
zen: z.object({
|
|
276
|
-
enabled: z.boolean().default(true).volatile(),
|
|
277
|
-
ref: z.string().default('OPENCODE_API_KEY').volatile(),
|
|
278
|
-
mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
|
|
279
|
-
/** No proven listing endpoint; without it routes mode is unsupported. */
|
|
280
|
-
modelsUrl: z.string().volatile(),
|
|
281
|
-
seedFromBuiltin: z.boolean().default(false).volatile(),
|
|
282
|
-
routes: z.object({
|
|
283
|
-
chat: z.string().default('opencode-zen').volatile(),
|
|
284
|
-
msg: z.string().default('opencode-zen-msg').volatile(),
|
|
285
|
-
resp: z.string().default('opencode-zen-resp').volatile(),
|
|
286
|
-
}).default({}),
|
|
287
133
|
}).default({}),
|
|
288
134
|
}).default({}),
|
|
289
135
|
})
|
|
290
136
|
|
|
291
|
-
/**
|
|
292
|
-
* A stable configuration reference — the protocol the 0.1.7 host hands the
|
|
293
|
-
* plugin for every volatile `Config` field (cosmokit's `Volatile<T>`, declared
|
|
294
|
-
* locally as a structural type so this module stays dependency-free). `get()`
|
|
295
|
-
* returns the current immutable snapshot; the host swaps the value in place on
|
|
296
|
-
* volatile-only edits, so reading per round is always fresh.
|
|
297
|
-
*/
|
|
298
137
|
interface VolatileRef<T> {
|
|
299
138
|
get(): T
|
|
300
139
|
}
|
|
301
140
|
|
|
302
|
-
/** Typed view of the resolved `Config` value as delivered to apply(). */
|
|
303
141
|
interface ModelSyncConfigValue {
|
|
304
142
|
writeMode: VolatileRef<'settings' | 'overlay'>
|
|
305
143
|
intervalMinutes: VolatileRef<number>
|
|
@@ -312,63 +150,31 @@ interface ModelSyncConfigValue {
|
|
|
312
150
|
forceMaxReasoningEffort: VolatileRef<boolean>
|
|
313
151
|
providerNativeFetch: VolatileRef<boolean>
|
|
314
152
|
keepDeprecatedBuiltin: VolatileRef<boolean>
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
adoptExisting: VolatileRef<boolean>
|
|
322
|
-
pinnedModels: VolatileRef<readonly string[]>
|
|
323
|
-
routes: Record<'chat' | 'msg' | 'resp' | 'google', VolatileRef<string>>
|
|
324
|
-
confirmRemovals: VolatileRef<number>
|
|
325
|
-
}
|
|
326
|
-
zen: {
|
|
327
|
-
enabled: VolatileRef<boolean>
|
|
328
|
-
ref: VolatileRef<string>
|
|
329
|
-
mode: VolatileRef<'login-only' | 'routes'>
|
|
330
|
-
modelsUrl: VolatileRef<string | undefined>
|
|
331
|
-
seedFromBuiltin: VolatileRef<boolean>
|
|
332
|
-
routes: Record<'chat' | 'msg' | 'resp', VolatileRef<string>>
|
|
333
|
-
}
|
|
334
|
-
}
|
|
153
|
+
officialSync?: Record<string, {
|
|
154
|
+
intervalMinutes?: VolatileRef<number>
|
|
155
|
+
modelsUrl?: VolatileRef<string>
|
|
156
|
+
sessionHeader?: VolatileRef<SessionHeaderMode>
|
|
157
|
+
routes?: Record<string, VolatileRef<string>>
|
|
158
|
+
}>
|
|
335
159
|
}
|
|
336
160
|
|
|
337
|
-
/** The llm seam as this plugin needs it (overlay mode + 0.12.1 host catalog). */
|
|
338
161
|
interface LlmSeam {
|
|
339
162
|
listProviders?(): readonly { id: string }[]
|
|
340
163
|
listModels?(provider: string): Promise<readonly { id: string }[]>
|
|
341
|
-
discoverModels?(
|
|
342
|
-
settingsNs: string,
|
|
343
|
-
request: { provider?: string; baseURL?: string; api?: string; apiKey?: string },
|
|
344
|
-
signal?: AbortSignal,
|
|
345
|
-
): Promise<readonly { id: string }[]>
|
|
346
164
|
}
|
|
347
165
|
|
|
348
|
-
/** The catalog-refresh seam exposed by the patched dsh-llm-pi-ai adapter. */
|
|
349
166
|
interface CatalogSeam {
|
|
350
167
|
refresh?(options: { force?: boolean; signal?: AbortSignal }): Promise<Map<string, unknown>>
|
|
351
168
|
}
|
|
352
169
|
|
|
353
|
-
/** The `modelSync` service surfaced to UIs: run one refresh round and get the report. */
|
|
354
170
|
export interface ModelSyncService {
|
|
355
171
|
syncNow(): Promise<string>
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
migrateStatus?(): Promise<string>
|
|
172
|
+
syncOfficial?(provider: string): Promise<string>
|
|
173
|
+
migrate?(provider: string, options?: { allProfiles?: boolean; confirm?: boolean }): Promise<string>
|
|
174
|
+
rollback?(provider: string, options?: { confirm?: boolean }): Promise<string>
|
|
175
|
+
status?(provider?: string): Promise<string>
|
|
361
176
|
}
|
|
362
177
|
|
|
363
|
-
/**
|
|
364
|
-
* Default routes to manage when managedRoutes is empty.
|
|
365
|
-
*
|
|
366
|
-
* NOTE (intentional deviation from design doc §5.5): the design suggests
|
|
367
|
-
* dynamically enumerating routes from the llm adapter's provider list, but
|
|
368
|
-
* that requires pi.dev to have been fetched first — unavailable during
|
|
369
|
-
* bootstrap. A static list is the pragmatic fallback; update manually when
|
|
370
|
-
* new routes appear on pi.dev.
|
|
371
|
-
*/
|
|
372
178
|
const DEFAULT_ROUTES = [
|
|
373
179
|
'opencode-go',
|
|
374
180
|
'zai-coding-cn',
|
|
@@ -376,16 +182,8 @@ const DEFAULT_ROUTES = [
|
|
|
376
182
|
'xiaomi-token-plan-cn',
|
|
377
183
|
]
|
|
378
184
|
|
|
379
|
-
/** Default route list — exported for tests that need to iterate the same set
|
|
380
|
-
* the plugin syncs when `managedRoutes` is empty. Not part of the public
|
|
381
|
-
* runtime surface; subject to change without notice. */
|
|
382
185
|
export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES
|
|
383
186
|
|
|
384
|
-
// ---------------------------------------------------------------------------
|
|
385
|
-
// P1c go config / dependency helpers (design §6.2.6)
|
|
386
|
-
// ---------------------------------------------------------------------------
|
|
387
|
-
|
|
388
|
-
/** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
|
|
389
187
|
function readVolatile<T>(slot: unknown, fallback: T): T {
|
|
390
188
|
if (slot === undefined) return fallback
|
|
391
189
|
if (typeof slot === 'object' && slot !== null && typeof (slot as { get?: unknown }).get === 'function') {
|
|
@@ -394,92 +192,42 @@ function readVolatile<T>(slot: unknown, fallback: T): T {
|
|
|
394
192
|
return slot as T
|
|
395
193
|
}
|
|
396
194
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
* on the default zero-behavior path instead of throwing during apply().
|
|
402
|
-
*/
|
|
403
|
-
function readGoRuntimeConfig(config: ModelSyncConfigValue): { enabled: boolean; value: GoSyncRuntimeConfig } {
|
|
195
|
+
function readOfficialAdapterConfig(
|
|
196
|
+
config: ModelSyncConfigValue,
|
|
197
|
+
adapter: UpstreamProviderAdapter,
|
|
198
|
+
): OfficialAdapterConfig {
|
|
404
199
|
const raw = config as unknown as Record<string, unknown>
|
|
405
|
-
const
|
|
406
|
-
const
|
|
407
|
-
const rawRoutes =
|
|
408
|
-
const routes =
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
|
|
412
|
-
]),
|
|
413
|
-
) as GoSyncRuntimeConfig['routes']
|
|
414
|
-
return {
|
|
415
|
-
enabled: readVolatile(go?.enabled, false),
|
|
416
|
-
value: {
|
|
417
|
-
enabled: readVolatile(go?.enabled, false),
|
|
418
|
-
ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
|
|
419
|
-
modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
|
|
420
|
-
routes,
|
|
421
|
-
pinnedModels: readVolatile(go?.pinnedModels, [] as readonly string[]),
|
|
422
|
-
confirmRemovals: readVolatile(go?.confirmRemovals, 2),
|
|
423
|
-
adoptExisting: readVolatile(go?.adoptExisting, false),
|
|
424
|
-
},
|
|
200
|
+
const officialRoot = raw.officialSync as Record<string, unknown> | undefined
|
|
201
|
+
const block = officialRoot?.[adapter.id] as Record<string, unknown> | undefined
|
|
202
|
+
const rawRoutes = block?.routes as Record<string, unknown> | undefined
|
|
203
|
+
const routes: Record<string, string> = {}
|
|
204
|
+
for (const slot of adapter.slotOrder) {
|
|
205
|
+
routes[slot] = readVolatile(rawRoutes?.[slot], adapter.defaultSlotRoutes[slot]!)
|
|
425
206
|
}
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
/**
|
|
429
|
-
* Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
|
|
430
|
-
* field (default 60, floor 15, enforced by the scheduler); the startup delay is
|
|
431
|
-
* the shared top-level field the design names for startup jitter.
|
|
432
|
-
*
|
|
433
|
-
* `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
|
|
434
|
-
* Migration zero-write is now enforced independently by routeWriter (§14.6 /
|
|
435
|
-
* §14.7) on every write path, so this default is a product choice, not the
|
|
436
|
-
* only protection. All scheduler paths are still gated by this value.
|
|
437
|
-
*/
|
|
438
|
-
function readGoSchedulerConfig(config: ModelSyncConfigValue): GoSchedulerConfig {
|
|
439
|
-
const raw = config as unknown as Record<string, unknown>
|
|
440
|
-
const opencode = raw.opencode as Record<string, unknown> | undefined
|
|
441
|
-
const go = opencode?.go as Record<string, unknown> | undefined
|
|
442
207
|
return {
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
208
|
+
intervalMinutes: readVolatile(block?.intervalMinutes, adapter.defaultIntervalMinutes),
|
|
209
|
+
modelsUrl: readVolatile(block?.modelsUrl, adapter.defaultModelsUrl),
|
|
210
|
+
sessionHeader: readVolatile(block?.sessionHeader, 'auto' as SessionHeaderMode),
|
|
211
|
+
routes,
|
|
446
212
|
}
|
|
447
213
|
}
|
|
448
214
|
|
|
449
|
-
// ---------------------------------------------------------------------------
|
|
450
|
-
// P1d-1: own-write reentry marker + migration status reads (design §14.7.2)
|
|
451
|
-
// ---------------------------------------------------------------------------
|
|
452
|
-
|
|
453
|
-
/** Revision-stamped marker of the last settings write this plugin performed. */
|
|
454
215
|
interface OwnWriteMarker {
|
|
455
216
|
ns: string
|
|
456
217
|
revision: number
|
|
457
|
-
at: number
|
|
458
218
|
}
|
|
459
219
|
|
|
460
220
|
interface OwnWriteTracker {
|
|
461
|
-
/** Called after a successful settings.mutate, with the post-write revision. */
|
|
462
221
|
record(ns: string): void
|
|
463
|
-
/** True when a document-updated event is the echo of our own write. */
|
|
464
222
|
matches(ns: string, eventRevision?: number): boolean
|
|
465
223
|
}
|
|
466
224
|
|
|
467
|
-
|
|
468
|
-
* Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
|
|
469
|
-
* the live descriptor after a mutate, so the marker always holds the revision
|
|
470
|
-
* the host stamped on OUR write; a later event for the same ns+revision can
|
|
471
|
-
* only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
|
|
472
|
-
* never depend on a wall clock.
|
|
473
|
-
*/
|
|
474
|
-
function createOwnWriteTracker(
|
|
475
|
-
readRevision: (ns: string) => number | undefined,
|
|
476
|
-
now: () => number,
|
|
477
|
-
): OwnWriteTracker {
|
|
225
|
+
function createOwnWriteTracker(readRevision: (ns: string) => number | undefined): OwnWriteTracker {
|
|
478
226
|
let last: OwnWriteMarker | undefined
|
|
479
|
-
|
|
227
|
+
return {
|
|
480
228
|
record(ns) {
|
|
481
229
|
const revision = readRevision(ns)
|
|
482
|
-
if (revision !== undefined) last = { ns, revision
|
|
230
|
+
if (revision !== undefined) last = { ns, revision }
|
|
483
231
|
},
|
|
484
232
|
matches(ns, eventRevision) {
|
|
485
233
|
if (last === undefined || last.ns !== ns) return false
|
|
@@ -488,7 +236,6 @@ function createOwnWriteTracker(
|
|
|
488
236
|
return current !== undefined && current === last.revision
|
|
489
237
|
},
|
|
490
238
|
}
|
|
491
|
-
return tracker
|
|
492
239
|
}
|
|
493
240
|
|
|
494
241
|
function settingsRevision(settings: SettingsService | undefined, ns: string): number | undefined {
|
|
@@ -496,22 +243,8 @@ function settingsRevision(settings: SettingsService | undefined, ns: string): nu
|
|
|
496
243
|
}
|
|
497
244
|
|
|
498
245
|
export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise<void> {
|
|
499
|
-
// On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
|
|
500
|
-
// every volatile field is a stable reference (see VolatileRef), so the
|
|
501
|
-
// reads below are live views — no scope.get() and no scope.watch() (both
|
|
502
|
-
// removed from dsh-settings; the hot-reload notification moved to the
|
|
503
|
-
// settings/document-updated event, subscribed at the bottom of apply()).
|
|
504
|
-
|
|
505
|
-
// P1d-1: one reentry marker shared by every write path. `rawSettings()` is
|
|
506
|
-
// resolved per call so a host that mounts the settings service after this
|
|
507
|
-
// plugin still works; the thin wrapper records the post-mutate revision for
|
|
508
|
-
// the document-updated reentry check (§14.7.2). Every settings-writing path
|
|
509
|
-
// below goes through `settingsForWrite*` — never a bare ctx.get('settings').
|
|
510
246
|
const rawSettings = (): SettingsService | undefined => ctx.get('settings') as SettingsService | undefined
|
|
511
|
-
const ownWrite = createOwnWriteTracker(
|
|
512
|
-
(ns) => settingsRevision(rawSettings(), ns),
|
|
513
|
-
() => Date.now(),
|
|
514
|
-
)
|
|
247
|
+
const ownWrite = createOwnWriteTracker((ns) => settingsRevision(rawSettings(), ns))
|
|
515
248
|
const settingsForWriteFrom = (context: Context): SettingsService | undefined => {
|
|
516
249
|
const raw = context.get('settings') as SettingsService | undefined
|
|
517
250
|
if (raw === undefined) return undefined
|
|
@@ -524,157 +257,31 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
524
257
|
}
|
|
525
258
|
}
|
|
526
259
|
const settingsForWrite = (): SettingsService | undefined => settingsForWriteFrom(ctx)
|
|
527
|
-
|
|
528
|
-
// B1/H9: one stable profile identity per plugin instance, resolved from the
|
|
529
|
-
// host (profileContext / DSH_PROFILE). Both file-backed stores below scope
|
|
530
|
-
// every shared models-store key with it so two profiles cannot share a
|
|
531
|
-
// migration record or ownership ledger entry. When no identity can be
|
|
532
|
-
// resolved there is NO 'default' collapse: every file-backed ledger path
|
|
533
|
-
// fails closed with an actionable error instead of silently sharing a key.
|
|
534
260
|
const profileKey = resolveProfileKey(ctx)
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
(ctx.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
|
|
546
|
-
?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey())
|
|
547
|
-
// O1/C2: the journal lives in the same models-store.json. An injected seam
|
|
548
|
-
// wins (tests use a temp-dir accessor); without a resolved profile identity
|
|
549
|
-
// there is NO journal — never fall back to the real default ~/.dsh from a
|
|
550
|
-
// host/test that supplied no identity (the ledger path fails closed too).
|
|
551
|
-
const journalStoreForRound = (): GoJournalStore | undefined =>
|
|
552
|
-
(ctx.get(GO_JOURNAL_STORE_SERVICE) as GoJournalStore | undefined)
|
|
553
|
-
?? (profileKey === undefined ? undefined : createModelsStoreJournalStore())
|
|
554
|
-
|
|
555
|
-
/**
|
|
556
|
-
* Read current migration status from the persisted record + live settings +
|
|
557
|
-
* (when a key fingerprint is available) the live ownership ledger.
|
|
558
|
-
* `strict` rethrows a record read failure so the §14.7.5 second gate can fail
|
|
559
|
-
* closed with `canWrite-unavailable`; the normal path degrades to "no record"
|
|
560
|
-
* (conservative legacy detection) as before.
|
|
561
|
-
*/
|
|
562
|
-
const loadMigrationStatus = async (
|
|
563
|
-
opts: { keyFingerprint?: string; strict?: boolean } = {},
|
|
564
|
-
): Promise<MigrationStatus> => {
|
|
565
|
-
const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
566
|
-
// H9 fail-closed: with no resolvable profile identity the file-backed store
|
|
567
|
-
// factory throws. A non-strict READ degrades to "no record" (gate closed,
|
|
568
|
-
// zero writes) so boot-time status refreshes / isApplying cannot produce an
|
|
569
|
-
// unhandled rejection; strict reads (the per-mutate second gate) rethrow.
|
|
570
|
-
// Every WRITE path still fails closed when it builds its file-backed store.
|
|
571
|
-
// N2: remember an identity-refused file-backed store so the (non-strict)
|
|
572
|
-
// status read can surface it instead of looking like a normal legacy state.
|
|
573
|
-
// The check is on the thrown identity error, not on `profileKey === undefined`
|
|
574
|
-
// alone: an injected-store host has a usable ledger even with no host
|
|
575
|
-
// identity and must NOT get a false "identity unavailable" report.
|
|
576
|
-
let identityUnavailable = false
|
|
577
|
-
let store: MigrationStateStore | undefined
|
|
578
|
-
try {
|
|
579
|
-
store = migrationStore()
|
|
580
|
-
} catch (err) {
|
|
581
|
-
if (opts.strict === true) throw err
|
|
582
|
-
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
|
|
583
|
-
}
|
|
584
|
-
let record: MigrationRecord | undefined
|
|
585
|
-
try {
|
|
586
|
-
// H4: strict status reads (the per-mutate second gate) use readStrict —
|
|
587
|
-
// a store error must reach the caller as a refusal, never as "no record".
|
|
588
|
-
record = opts.strict === true && store !== undefined && store.readStrict !== undefined
|
|
589
|
-
? await store.readStrict()
|
|
590
|
-
: await store?.read()
|
|
591
|
-
} catch (err) {
|
|
592
|
-
if (opts.strict === true) throw err
|
|
593
|
-
record = undefined // unreadable ⇒ conservative legacy detection
|
|
594
|
-
}
|
|
595
|
-
const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {})
|
|
596
|
-
let managedIds: Record<string, string[]> | undefined
|
|
597
|
-
const fp = opts.keyFingerprint
|
|
598
|
-
if (fp !== undefined) {
|
|
599
|
-
let ownership: GoOwnershipStore | undefined
|
|
600
|
-
try {
|
|
601
|
-
ownership = ownershipStoreForRound()
|
|
602
|
-
} catch (err) {
|
|
603
|
-
if (opts.strict === true) throw err
|
|
604
|
-
if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
|
|
605
|
-
}
|
|
606
|
-
// Only routes with a REAL ledger entry join the fingerprint set. The old
|
|
607
|
-
// `<route>: []` filler for configured-but-absent routes disagreed with
|
|
608
|
-
// migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
|
|
609
|
-
// first healthy round after onboarding.
|
|
610
|
-
managedIds = await goLedgerManagedIds(goRoutes, (route) =>
|
|
611
|
-
ownership === undefined
|
|
612
|
-
? Promise.resolve(undefined)
|
|
613
|
-
: ownership.read(goOwnershipKey(route, fp)))
|
|
614
|
-
}
|
|
615
|
-
const status = migrationStatusOf(desc, record, goRoutes, managedIds)
|
|
616
|
-
// W1/D6: the go report and `migrate status` must agree on the label for a
|
|
617
|
-
// record this profile cannot claim. Use the SAME helper as migrate status;
|
|
618
|
-
// only when our own scoped read() found no record (B1 isolation). This is
|
|
619
|
-
// label-only: both states already keep the gate closed / write authority
|
|
620
|
-
// none / zero writes, and nothing is claimed or deleted.
|
|
621
|
-
if (record === undefined && store?.unclaimedRecords !== undefined) {
|
|
622
|
-
let unclaimed: UnclaimedMigrationRecord[]
|
|
623
|
-
try {
|
|
624
|
-
unclaimed = await store.unclaimedRecords()
|
|
625
|
-
} catch (err) {
|
|
626
|
-
if (opts.strict === true) throw err
|
|
627
|
-
unclaimed = [] // advisory provenance scan never changes the gate
|
|
628
|
-
}
|
|
629
|
-
const recordState = unclaimedRecordState(unclaimed)
|
|
630
|
-
if (recordState !== undefined) status.state = recordState
|
|
631
|
-
}
|
|
632
|
-
// N2: a non-strict refresh that degraded because no identity was available
|
|
633
|
-
// must be VISIBLE — log the actionable error (covers boot / document-updated
|
|
634
|
-
// refresh where there is no report line) and tag the status so sync reports
|
|
635
|
-
// do not show the normal legacy hint. This changes NO write/fail-closed
|
|
636
|
-
// behavior: the gate is already closed and no store/settings write occurs.
|
|
637
|
-
if (identityUnavailable) {
|
|
638
|
-
status.identityUnavailable = true
|
|
639
|
-
ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE)
|
|
640
|
-
}
|
|
641
|
-
// §14.7.4 self-heal: identity matches but the stored full fingerprint is
|
|
642
|
-
// stale because the fingerprint persist failed after settings+ledger landed.
|
|
643
|
-
// Rewrite it in the same queue instead of closing the gate forever.
|
|
644
|
-
if (status.fingerprintHealed && typeof store?.write === 'function') {
|
|
645
|
-
try {
|
|
646
|
-
ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)')
|
|
647
|
-
await store.write({
|
|
648
|
-
...(record ?? {}),
|
|
649
|
-
appliedManagedIds: managedIds ?? record?.appliedManagedIds,
|
|
650
|
-
appliedFingerprint: status.expectedFingerprint,
|
|
651
|
-
})
|
|
652
|
-
status.appliedFingerprint = status.expectedFingerprint
|
|
653
|
-
status.fingerprintHealed = false
|
|
654
|
-
} catch (err) {
|
|
655
|
-
ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err))
|
|
656
|
-
}
|
|
261
|
+
|
|
262
|
+
const pathOverrides = (): OfficialMigrationPaths | undefined =>
|
|
263
|
+
ctx.get(OFFICIAL_MIGRATION_PATHS_SERVICE) as OfficialMigrationPaths | undefined
|
|
264
|
+
|
|
265
|
+
const migrationStoreFor = (adapterId: string, keyOverride?: string): OfficialMigrationStore | undefined => {
|
|
266
|
+
const effectiveKey = keyOverride ?? profileKey
|
|
267
|
+
if (effectiveKey === undefined) return undefined
|
|
268
|
+
const overrides = pathOverrides()
|
|
269
|
+
if (overrides?.storeAccessor !== undefined) {
|
|
270
|
+
return createOfficialMigrationStore(overrides.storeAccessor, effectiveKey, adapterId)
|
|
657
271
|
}
|
|
658
|
-
return
|
|
272
|
+
return createDefaultOfficialMigrationStore(effectiveKey, adapterId, overrides?.modelsStorePath)
|
|
659
273
|
}
|
|
660
274
|
|
|
661
275
|
// -----------------------------------------------------------------------
|
|
662
|
-
//
|
|
276
|
+
// Legacy pi.dev sync (Builtin Provider track)
|
|
663
277
|
// -----------------------------------------------------------------------
|
|
664
278
|
const syncOverlay = async (
|
|
665
|
-
|
|
279
|
+
cfg: ModelSyncConfigValue,
|
|
666
280
|
llm: LlmSeam,
|
|
667
281
|
force: boolean,
|
|
668
282
|
): Promise<string> => {
|
|
669
283
|
const catalog = ctx.get('piAiCatalog') as CatalogSeam | undefined
|
|
670
284
|
if (catalog?.refresh === undefined) {
|
|
671
|
-
// Degradation path (never throws): the overlay needs a hand-patched
|
|
672
|
-
// dsh-llm-pi-ai exposing piAiCatalog.refresh(). Since dsh 0.1.2-alpha.3
|
|
673
|
-
// the patch cannot even apply (it shims settingsNamespace and
|
|
674
|
-
// installSettingsSection, both removed from dsh-settings), and dsh
|
|
675
|
-
// 0.2.1 removed the piAiCatalog seam outright (pi-ai 1.3.0 ModelsStore
|
|
676
|
-
// rework) — so every host now lands here unless it runs the settings
|
|
677
|
-
// mode, which is the supported path.
|
|
678
285
|
return 'catalog refresh is unavailable — the dsh-llm-pi-ai remote-catalog patch is not applied (deprecated: dsh 0.2.1 removed the piAiCatalog seam, pi-ai 1.3.0 ModelsStore rework); the model list is the static catalog only. Switch writeMode to the supported settings mode.'
|
|
679
286
|
}
|
|
680
287
|
let providers: readonly { id: string }[]
|
|
@@ -699,7 +306,7 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
699
306
|
const before = await list()
|
|
700
307
|
const errors = await catalog.refresh({
|
|
701
308
|
force,
|
|
702
|
-
signal: AbortSignal.timeout(
|
|
309
|
+
signal: AbortSignal.timeout(cfg.refreshTimeoutMs.get()),
|
|
703
310
|
})
|
|
704
311
|
const after = await list()
|
|
705
312
|
|
|
@@ -725,70 +332,50 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
725
332
|
return lines.join('\n')
|
|
726
333
|
}
|
|
727
334
|
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
335
|
+
const loadMigratedSkipMap = async (): Promise<Map<string, UpstreamProviderAdapter>> => {
|
|
336
|
+
const skipped = new Map<string, UpstreamProviderAdapter>()
|
|
337
|
+
for (const adapter of listOfficialAdapters()) {
|
|
338
|
+
const store = migrationStoreFor(adapter.id)
|
|
339
|
+
const record: OfficialMigrationRecord | undefined = await store?.read().catch(() => undefined)
|
|
340
|
+
if (record !== undefined) {
|
|
341
|
+
skipped.set(adapter.builtinProviderId, adapter)
|
|
342
|
+
for (const r of record.managedRoutes) skipped.set(r, adapter)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return skipped
|
|
346
|
+
}
|
|
347
|
+
|
|
731
348
|
const syncSettings = async (
|
|
732
|
-
|
|
349
|
+
cfg: ModelSyncConfigValue,
|
|
733
350
|
force: boolean,
|
|
734
351
|
): Promise<string> => {
|
|
735
352
|
const settings = settingsForWrite()
|
|
736
353
|
const logger = ctx.logger as unknown as Logger
|
|
737
|
-
const store = loadModelsStore()
|
|
354
|
+
const store = loadModelsStore(pathOverrides()?.modelsStorePath)
|
|
738
355
|
const lines: string[] = []
|
|
739
356
|
|
|
740
|
-
|
|
741
|
-
const
|
|
742
|
-
const
|
|
743
|
-
? [...managedRoutes]
|
|
744
|
-
: DEFAULT_ROUTES
|
|
745
|
-
|
|
746
|
-
// P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
|
|
747
|
-
// path must NEVER write an `opencode-go*` route — not even in `absent` /
|
|
748
|
-
// `applied` state (that belongs to go sync), and especially not when the
|
|
749
|
-
// migration gate is closed. Login-triggered/manual/auto all funnel through
|
|
750
|
-
// this one loop (design §14.7.1, ADR-008).
|
|
751
|
-
const { value: goCfg } = readGoRuntimeConfig(config)
|
|
752
|
-
const goRouteIds = Object.values(goCfg.routes ?? {})
|
|
753
|
-
const piDevAuthority = { caller: 'pi.dev' as const, goEnabled: goCfg.enabled, goRoutes: goRouteIds }
|
|
754
|
-
let piDevMigration: MigrationStatus | undefined
|
|
357
|
+
const managedRoutes = cfg.managedRoutes.get()
|
|
358
|
+
const routes = managedRoutes.length > 0 ? [...managedRoutes] : DEFAULT_ROUTES
|
|
359
|
+
const migratedSkip = await loadMigratedSkipMap()
|
|
755
360
|
|
|
756
361
|
const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
757
362
|
const gateCtx = ctx as RouteCredentialContext
|
|
363
|
+
|
|
758
364
|
for (const route of routes) {
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
if (decision.decision === 'skip') {
|
|
765
|
-
// N2: an identity-refused ledger is NOT a normal legacy state. Surface
|
|
766
|
-
// the actionable identity hint instead of the generic migration hint.
|
|
767
|
-
const hint = piDevMigration.identityUnavailable === true
|
|
768
|
-
? `; ${PROFILE_IDENTITY_STATUS_HINT}`
|
|
769
|
-
: (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
|
|
770
|
-
? ''
|
|
771
|
-
: `; ${MIGRATION_GATE_HINT}`)
|
|
772
|
-
lines.push(`${route}: skipped — ${decision.reason}${hint}`)
|
|
773
|
-
continue
|
|
774
|
-
}
|
|
365
|
+
const ownerAdapter = migratedSkip.get(route)
|
|
366
|
+
if (ownerAdapter !== undefined) {
|
|
367
|
+
const alias = ownerAdapter.aliases[0] ?? ownerAdapter.id
|
|
368
|
+
lines.push(`${route}: skipped — migrated to official custom providers (use /model-sync ${alias})`)
|
|
369
|
+
continue
|
|
775
370
|
}
|
|
776
371
|
|
|
777
|
-
// Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
|
|
778
|
-
// Layer 2 follows its authContextFrom(ctx).env(): launch environment,
|
|
779
|
-
// or process.env when the service is absent. Both miss → skip fetch,
|
|
780
|
-
// translate and settings.mutate, naming the missing ref in the report.
|
|
781
|
-
// deriveKeyRef replicates the web UI's conventional reference name.
|
|
782
|
-
// Known gap: after credential removal, a same-name shell export allows
|
|
783
|
-
// writes, but requests with the seam present still get MISSING_CREDENTIAL.
|
|
784
372
|
const gate = await checkRouteCredential(gateCtx, gateDesc, route)
|
|
785
373
|
if (!gate.ok) {
|
|
786
374
|
lines.push(`${route}: skipped — credential ${gate.ref} not configured`)
|
|
787
375
|
continue
|
|
788
376
|
}
|
|
789
377
|
|
|
790
|
-
|
|
791
|
-
const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs.get(), store, { force })
|
|
378
|
+
const result = await fetchRemoteCatalog(route, cfg.refreshTimeoutMs.get(), store, { force })
|
|
792
379
|
|
|
793
380
|
if (result.error !== undefined && result.entries.length === 0) {
|
|
794
381
|
lines.push(`${route}: fetch failed (${result.error}); keeping last-good`)
|
|
@@ -800,27 +387,17 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
800
387
|
continue
|
|
801
388
|
}
|
|
802
389
|
|
|
803
|
-
// Translate
|
|
804
390
|
const translateOpts: TranslateOptions = {
|
|
805
|
-
keepBuiltinOnly:
|
|
806
|
-
dropUnserviceable:
|
|
391
|
+
keepBuiltinOnly: cfg.keepBuiltinOnly.get(),
|
|
392
|
+
dropUnserviceable: cfg.dropUnserviceable.get(),
|
|
807
393
|
dropWarnings: [],
|
|
808
|
-
forceMaxReasoningEffort:
|
|
394
|
+
forceMaxReasoningEffort: cfg.forceMaxReasoningEffort.get(),
|
|
809
395
|
}
|
|
810
396
|
|
|
811
|
-
// For builtin catalog snapshot: we use a mock for now since we can't
|
|
812
|
-
// import pi-ai at runtime. The builtin catalog data is needed for
|
|
813
|
-
// base-matching classification. In a real deployment, this would come
|
|
814
|
-
// from the built-in snapshot file.
|
|
815
397
|
const builtinData = getBuiltinCatalogForRoute(route)
|
|
816
398
|
|
|
817
|
-
// Provider-native union: fold the route's first-party /models listing
|
|
818
|
-
// (the fresher source — pi.dev lags; measured 2026-09-22) into the
|
|
819
|
-
// pi.dev result. Additions only, capacities only where the listing
|
|
820
|
-
// states them; any failure degrades to the pi.dev list unchanged so a
|
|
821
|
-
// native hiccup can never lose models.
|
|
822
399
|
let entries = result.entries
|
|
823
|
-
if (
|
|
400
|
+
if (cfg.providerNativeFetch.get() && PROVIDER_NATIVE_ENDPOINTS[route] !== undefined) {
|
|
824
401
|
const apiKey = await resolveRouteCredentialValue(
|
|
825
402
|
ctx as unknown as NativeCredentialContext,
|
|
826
403
|
gateDesc,
|
|
@@ -829,10 +406,8 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
829
406
|
if (apiKey === undefined) {
|
|
830
407
|
lines.push(`${route}: provider-native skipped — credential value unavailable`)
|
|
831
408
|
} else {
|
|
832
|
-
const native = await fetchProviderNativeModels(route, apiKey,
|
|
409
|
+
const native = await fetchProviderNativeModels(route, apiKey, cfg.refreshTimeoutMs.get())
|
|
833
410
|
if (native.ok) {
|
|
834
|
-
// Base-less synthesis needs the route's one addressable api;
|
|
835
|
-
// unknown or mixed-protocol routes skip synthesis wholesale.
|
|
836
411
|
const routeApis = [...new Set(builtinData.map((b) => b.api))]
|
|
837
412
|
const merged = mergeProviderNativeEntries(
|
|
838
413
|
entries,
|
|
@@ -857,7 +432,7 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
857
432
|
|
|
858
433
|
const builtinIds = new Set(builtinData.map((b) => b.id))
|
|
859
434
|
const builtinOnlyEntries = translateOpts.keepBuiltinOnly
|
|
860
|
-
? getBuiltinOnlyEntries(route, entries, builtinData,
|
|
435
|
+
? getBuiltinOnlyEntries(route, entries, builtinData, cfg.keepDeprecatedBuiltin.get())
|
|
861
436
|
: undefined
|
|
862
437
|
|
|
863
438
|
const translated = translateEntries(
|
|
@@ -869,25 +444,14 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
869
444
|
builtinOnlyEntries,
|
|
870
445
|
)
|
|
871
446
|
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
for (const w of translated.dropped) {
|
|
875
|
-
lines.push(`${route}: DROPPED ${w.id} — ${w.reason}`)
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
if (translated.warnings.length > 0) {
|
|
879
|
-
for (const w of translated.warnings) {
|
|
880
|
-
lines.push(`${route}: DEGRADED ${w.id} — ${w.reason}`)
|
|
881
|
-
}
|
|
882
|
-
}
|
|
447
|
+
for (const w of translated.dropped) lines.push(`${route}: DROPPED ${w.id} — ${w.reason}`)
|
|
448
|
+
for (const w of translated.warnings) lines.push(`${route}: DEGRADED ${w.id} — ${w.reason}`)
|
|
883
449
|
|
|
884
|
-
// B1: abort detected — skip writer, only warn
|
|
885
450
|
if (translated.aborted) {
|
|
886
451
|
lines.push(`${route}: ABORTED — dropUnserviceable=false and ${translated.dropped.length} entries dropped; settings not written`)
|
|
887
452
|
continue
|
|
888
453
|
}
|
|
889
454
|
|
|
890
|
-
// I-6: generate added/removed diff report from current raw models
|
|
891
455
|
if (settings !== undefined) {
|
|
892
456
|
const descs = settings.describe()
|
|
893
457
|
const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
|
|
@@ -899,26 +463,16 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
899
463
|
}
|
|
900
464
|
}
|
|
901
465
|
|
|
902
|
-
// Write to settings (change-only, with conflict retry); the store
|
|
903
|
-
// carries the modelOverrides replay/persist (mutual-exclusion fix)
|
|
904
466
|
const syncResult = await syncToSettings(
|
|
905
467
|
settings,
|
|
906
468
|
route,
|
|
907
469
|
translated.entries,
|
|
908
470
|
logger,
|
|
909
|
-
|
|
910
|
-
async (newRevision: number) => {
|
|
911
|
-
// Re-translate with same data (the remote data hasn't changed;
|
|
912
|
-
// only the settings revision changed)
|
|
913
|
-
void newRevision // revision is used by the caller
|
|
914
|
-
return translated.entries
|
|
915
|
-
},
|
|
471
|
+
async () => translated.entries,
|
|
916
472
|
store,
|
|
917
473
|
)
|
|
918
474
|
|
|
919
475
|
if (syncResult.wrote) {
|
|
920
|
-
// Detail suffix for the override flows; routes without overrides keep
|
|
921
|
-
// the classic "(wrote)" line byte-for-byte.
|
|
922
476
|
const reason = syncResult.reason === 'wrote' ? '' : `${syncResult.reason}; `
|
|
923
477
|
let detail: string | undefined
|
|
924
478
|
if (syncResult.overridesSource === 'settings') {
|
|
@@ -939,9 +493,6 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
939
493
|
} else if (syncResult.reason === 'mutate-rejected') {
|
|
940
494
|
lines.push(`${route}: rejected by settings validation (see log)`)
|
|
941
495
|
} else if (syncResult.reason === 'store-unavailable') {
|
|
942
|
-
// The store failed (corrupt/permission on read, or filesystem on
|
|
943
|
-
// write); settings.models was the authoritative source and stays
|
|
944
|
-
// untouched either way — the user's folded values are preserved.
|
|
945
496
|
lines.push(`${route}: skipped (models-store unavailable; settings untouched)`)
|
|
946
497
|
} else {
|
|
947
498
|
lines.push(`${route}: ${syncResult.reason} (${translated.entries.length} models)`)
|
|
@@ -951,35 +502,20 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
951
502
|
return lines.join('\n')
|
|
952
503
|
}
|
|
953
504
|
|
|
954
|
-
// -----------------------------------------------------------------------
|
|
955
|
-
// Unified syncNow
|
|
956
|
-
// -----------------------------------------------------------------------
|
|
957
|
-
/** One-shot guard for the overlay-mode deprecation warning. */
|
|
958
505
|
let overlayDeprecationWarned = false
|
|
959
506
|
const syncNow = async (force: boolean): Promise<string> => {
|
|
960
|
-
// Read the live refs up front; the volatile snapshots are fresh per call.
|
|
961
507
|
const writeMode = config.writeMode.get()
|
|
962
508
|
const managedRoutes = config.managedRoutes.get()
|
|
963
509
|
const routes = managedRoutes.length > 0 ? [...managedRoutes] : DEFAULT_ROUTES
|
|
964
|
-
|
|
965
|
-
// Prefer the host's live pi-ai catalog for this round; the frozen
|
|
966
|
-
// snapshot is only the no-host fallback. Without this, keepBuiltinOnly
|
|
967
|
-
// re-emits ids the host's catalog has already dropped. Awaiting keeps the
|
|
968
|
-
// `which`/`npm` probes off the host's event loop (they used to block every
|
|
969
|
-
// surface for ~0.2s per round).
|
|
970
510
|
await refreshLiveCatalog(routes)
|
|
971
511
|
|
|
972
512
|
if (writeMode === 'settings') {
|
|
973
513
|
return syncSettings(config, force)
|
|
974
514
|
}
|
|
975
|
-
|
|
976
|
-
// Overlay mode (legacy). dsh 0.2.1 removed the piAiCatalog seam (pi-ai
|
|
977
|
-
// 1.3.0 ModelsStore rework), so this mode can no longer refresh anywhere;
|
|
978
|
-
// warn once per process and let the round degrade with its notice.
|
|
979
515
|
if (!overlayDeprecationWarned) {
|
|
980
516
|
overlayDeprecationWarned = true
|
|
981
517
|
ctx.logger.warn(
|
|
982
|
-
"model-sync: writeMode 'overlay' is deprecated — dsh 0.2.1 removed the piAiCatalog seam
|
|
518
|
+
"model-sync: writeMode 'overlay' is deprecated — dsh 0.2.1 removed the piAiCatalog seam; switch to 'settings' mode",
|
|
983
519
|
)
|
|
984
520
|
}
|
|
985
521
|
const llm = ctx.get('llm') as LlmSeam | undefined
|
|
@@ -990,498 +526,111 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
990
526
|
}
|
|
991
527
|
|
|
992
528
|
// -----------------------------------------------------------------------
|
|
993
|
-
//
|
|
994
|
-
// P1c-2 wraps this in the scheduler below; the round itself still owns no
|
|
995
|
-
// timer and no command registration.
|
|
529
|
+
// Official Sync Schedulers (one per registered UpstreamProviderAdapter)
|
|
996
530
|
// -----------------------------------------------------------------------
|
|
997
|
-
const
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
)
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
migration,
|
|
1031
|
-
// O1/C2: journal + reconciliation use the same profile/fingerprint as the
|
|
1032
|
-
// ledger. Reconciliation runs before the gate inside runGoSyncRound.
|
|
1033
|
-
journalStore: journalStoreForRound(),
|
|
1034
|
-
profileKey,
|
|
1035
|
-
keyFingerprint,
|
|
1036
|
-
// §14.7.5: the second gate re-reads the persisted record on each mutate
|
|
1037
|
-
// (strict: a failed read skips the route with canWrite-unavailable).
|
|
1038
|
-
reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
|
|
1039
|
-
// §14.7.4: settings → ledger → fingerprint, all through the same
|
|
1040
|
-
// models-store queue; only successful own writes reach this callback.
|
|
1041
|
-
// H4: NO catch here. A strict read failure (or a read-only store) must
|
|
1042
|
-
// reach the writer's recordOwnWrite, which reports
|
|
1043
|
-
// settings-written-unaccounted and KEEPS the C2 write-ahead journal so
|
|
1044
|
-
// the next round's reconciliation re-commits the record — swallowing the
|
|
1045
|
-
// error here made recordOwnWrite report success and delete the journal,
|
|
1046
|
-
// leaving the gate drifted with no recovery (the old "self-heal" comment
|
|
1047
|
-
// was wrong: fingerprintHealed only fires on an identity MATCH, and this
|
|
1048
|
-
// write is exactly what changed the identity).
|
|
1049
|
-
onOwnWrite: async (route, managedIds, info) => {
|
|
1050
|
-
const store = migrationStore()
|
|
1051
|
-
if (typeof store.write !== 'function') {
|
|
1052
|
-
throw new Error('migration store is read-only; the migration record cannot be persisted')
|
|
531
|
+
const schedulers = new Map<string, OfficialSyncScheduler>()
|
|
532
|
+
const timers = ctx.get(OFFICIAL_SCHEDULER_TIMERS_SERVICE) as OfficialSchedulerTimers | undefined
|
|
533
|
+
const random = ctx.get(OFFICIAL_SCHEDULER_RANDOM_SERVICE) as OfficialSchedulerRandom | undefined
|
|
534
|
+
|
|
535
|
+
const buildMigrateDeps = (
|
|
536
|
+
targetCtx: Context,
|
|
537
|
+
adapter: UpstreamProviderAdapter,
|
|
538
|
+
): OfficialMigrateDeps => {
|
|
539
|
+
const overrides = pathOverrides()
|
|
540
|
+
const profileCtx = targetCtx.get('profileContext') as { name?: string; dir?: string } | undefined
|
|
541
|
+
const launchEnv = targetCtx.get('launchEnvironment') as { get(key: string): { value: string } | undefined } | undefined
|
|
542
|
+
return {
|
|
543
|
+
adapter,
|
|
544
|
+
config: readOfficialAdapterConfig(config, adapter),
|
|
545
|
+
home: overrides?.home ?? resolveDshHome(),
|
|
546
|
+
modelsStorePath: overrides?.modelsStorePath ?? MODELS_STORE_PATH,
|
|
547
|
+
profilesDir: overrides?.profilesDir,
|
|
548
|
+
currentProfile: {
|
|
549
|
+
key: resolveProfileKey(targetCtx) ?? profileKey,
|
|
550
|
+
dir: profileCtx?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
|
|
551
|
+
},
|
|
552
|
+
currentSettings: settingsForWriteFrom(targetCtx),
|
|
553
|
+
credentialCtx: targetCtx as unknown as OfficialCredentialContext,
|
|
554
|
+
logger: targetCtx.logger as unknown as Logger,
|
|
555
|
+
timeoutMs: readVolatile(config.refreshTimeoutMs, 120000),
|
|
556
|
+
fetchImpl: targetCtx.get(OFFICIAL_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
557
|
+
detectHostSessionHeader: targetCtx.get(OFFICIAL_SESSION_HEADER_DETECT_SERVICE) as (() => boolean) | undefined,
|
|
558
|
+
loadPiAiCompatHints: targetCtx.get(OFFICIAL_COMPAT_HINTS_SERVICE) as (() => CompatHintsByProtocol) | undefined,
|
|
559
|
+
resolveAsk: () => {
|
|
560
|
+
try {
|
|
561
|
+
return targetCtx.get('userQuestions') as AskServiceShape | undefined
|
|
562
|
+
} catch {
|
|
563
|
+
return undefined
|
|
1053
564
|
}
|
|
1054
|
-
const record = typeof store.readStrict === 'function'
|
|
1055
|
-
? await store.readStrict()
|
|
1056
|
-
: await store.read()
|
|
1057
|
-
const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
1058
|
-
const next = ownWriteRecordUpdate({
|
|
1059
|
-
record,
|
|
1060
|
-
source: liveDesc,
|
|
1061
|
-
routes: Object.values(value.routes ?? {}),
|
|
1062
|
-
route,
|
|
1063
|
-
managedIds,
|
|
1064
|
-
unset: info?.unset === true,
|
|
1065
|
-
})
|
|
1066
|
-
await store.write(next)
|
|
1067
565
|
},
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
1080
|
-
}
|
|
1081
|
-
const goRandom: GoSchedulerRandom = (ctx.get(GO_SCHEDULER_RANDOM_SERVICE) as GoSchedulerRandom | undefined)
|
|
1082
|
-
?? { next: () => Math.random() }
|
|
1083
|
-
const goScheduler = new GoScheduler({
|
|
1084
|
-
config: () => readGoSchedulerConfig(config),
|
|
1085
|
-
timers: goTimers,
|
|
1086
|
-
random: goRandom,
|
|
1087
|
-
runRound: async ({ adopt, signal }) => {
|
|
1088
|
-
const round = await runGoRound({ adopt, signal })
|
|
1089
|
-
return {
|
|
1090
|
-
ok: round.ok,
|
|
1091
|
-
reason: round.reason,
|
|
1092
|
-
text: round.text,
|
|
1093
|
-
failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
|
|
1094
|
-
? round.source.error.kind
|
|
1095
|
-
: undefined,
|
|
1096
|
-
}
|
|
1097
|
-
},
|
|
1098
|
-
report: (text) => {
|
|
1099
|
-
for (const line of text.split('\n')) ctx.logger.info('model-sync: %s', line)
|
|
1100
|
-
},
|
|
1101
|
-
// M-5: drop (never queue) any round while a migration apply holds the routes.
|
|
1102
|
-
isApplying: async () => (await loadMigrationStatus()).applying,
|
|
1103
|
-
})
|
|
1104
|
-
ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose')
|
|
1105
|
-
// A changed credential invalidates any accumulated backoff: a fixed key must
|
|
1106
|
-
// retry on the normal schedule instead of waiting out a capped 6h backoff
|
|
1107
|
-
// (design §6.3). The effect scopes the listener to this plugin's lifetime —
|
|
1108
|
-
// unload removes it together with the scheduler.
|
|
1109
|
-
ctx.effect(() => ctx.on('credentials/reference-updated', (ref: unknown) => {
|
|
1110
|
-
if (typeof ref !== 'string') return
|
|
1111
|
-
const { value } = readGoRuntimeConfig(config)
|
|
1112
|
-
if (ref !== value.ref) return
|
|
1113
|
-
goScheduler.resetBackoff()
|
|
1114
|
-
}), 'dsh-model-sync: credentials/reference-updated → go backoff reset')
|
|
1115
|
-
goScheduler.start()
|
|
1116
|
-
|
|
1117
|
-
// -----------------------------------------------------------------------
|
|
1118
|
-
// P1d-2: `/model-sync migrate plan|apply|rollback|status` (design §14.5).
|
|
1119
|
-
// plan is pure/read-only; apply carries the consent gate and the single-flight
|
|
1120
|
-
// mutex against goScheduler. No auto/startup path reaches any of these.
|
|
1121
|
-
// -----------------------------------------------------------------------
|
|
1122
|
-
type MigrateEntries = readonly GoModelRecord[] | (() => Promise<readonly GoModelRecord[]> | readonly GoModelRecord[])
|
|
1123
|
-
type PublicCatalog = readonly string[] | (() => Promise<readonly string[]> | readonly string[])
|
|
1124
|
-
type HostCatalogSource = readonly string[] | null | (() => Promise<readonly string[] | null> | readonly string[] | null)
|
|
1125
|
-
|
|
1126
|
-
/**
|
|
1127
|
-
* 0.12.1: the host runtime catalog ids for opencode-go, read live from the
|
|
1128
|
-
* host llm adapter (`llm.discoverModels('llm-pi-ai', { provider })` — the
|
|
1129
|
-
* adapter answers from its in-memory installed catalog with no network and
|
|
1130
|
-
* no credential; that catalog is exactly what the host validates route
|
|
1131
|
-
* models against). `null` = unknown: every WRITE path fails closed on it,
|
|
1132
|
-
* the read-only diagnostic degrades. Test seam: GO_HOST_CATALOG_SERVICE.
|
|
1133
|
-
*/
|
|
1134
|
-
const resolveHostCatalogIds = async (from: Context): Promise<readonly string[] | null> => {
|
|
1135
|
-
const injected = from.get(GO_HOST_CATALOG_SERVICE) as HostCatalogSource | undefined
|
|
1136
|
-
if (Array.isArray(injected)) return injected
|
|
1137
|
-
if (injected === null) return null
|
|
1138
|
-
if (typeof injected === 'function') return await injected()
|
|
1139
|
-
const llm = from.get('llm') as HostCatalogLlmSeam | undefined
|
|
1140
|
-
const result = await loadHostGoCatalogIds(llm)
|
|
1141
|
-
if (!result.ok) {
|
|
1142
|
-
from.logger.warn('model-sync: host-catalog-unavailable (%s): %s', result.reason, result.message)
|
|
1143
|
-
return null
|
|
1144
|
-
}
|
|
1145
|
-
return result.ids
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
/** Resolve the official listing through an injectable seam (tests: a fixture array). */
|
|
1149
|
-
const resolveMigrateEntries = async (
|
|
1150
|
-
value: GoSyncRuntimeConfig,
|
|
1151
|
-
apiKey: string | undefined,
|
|
1152
|
-
): Promise<readonly GoModelRecord[]> => {
|
|
1153
|
-
const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE) as MigrateEntries | undefined
|
|
1154
|
-
if (Array.isArray(injected)) return injected
|
|
1155
|
-
if (typeof injected === 'function') return await injected()
|
|
1156
|
-
const source = await fetchGoOfficialModels({
|
|
1157
|
-
url: value.modelsUrl,
|
|
1158
|
-
apiKey,
|
|
1159
|
-
fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
1160
|
-
timeoutMs: config.refreshTimeoutMs.get(),
|
|
1161
|
-
})
|
|
1162
|
-
if (!source.ok) {
|
|
1163
|
-
throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`)
|
|
566
|
+
storeFor: (k) => migrationStoreFor(adapter.id, k)!,
|
|
567
|
+
storeAccessor: overrides?.storeAccessor,
|
|
568
|
+
fs: overrides?.fs,
|
|
569
|
+
patchIoFor: overrides?.patchIoFor,
|
|
570
|
+
now: overrides?.now,
|
|
571
|
+
onCurrentProfileMigrated: async () => {
|
|
572
|
+
await schedulers.get(adapter.id)?.rearm()
|
|
573
|
+
},
|
|
574
|
+
onCurrentProfileRolledBack: async () => {
|
|
575
|
+
await schedulers.get(adapter.id)?.rearm()
|
|
576
|
+
},
|
|
1164
577
|
}
|
|
1165
|
-
return source.entries
|
|
1166
578
|
}
|
|
1167
579
|
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
580
|
+
for (const adapter of listOfficialAdapters()) {
|
|
581
|
+
const scheduler = new OfficialSyncScheduler({
|
|
582
|
+
adapterId: adapter.id,
|
|
583
|
+
timers,
|
|
584
|
+
random,
|
|
585
|
+
getIntervalMinutes: () => readOfficialAdapterConfig(config, adapter).intervalMinutes,
|
|
586
|
+
getStartupDelaySeconds: () => readVolatile(config.startupDelaySeconds, 5),
|
|
587
|
+
isMigrated: async () => (await migrationStoreFor(adapter.id)?.read()) !== undefined,
|
|
588
|
+
runRound: ({ signal }) => runOfficialSyncRound({
|
|
589
|
+
adapter,
|
|
590
|
+
config: readOfficialAdapterConfig(config, adapter),
|
|
591
|
+
settings: settingsForWrite(),
|
|
592
|
+
migrationStore: migrationStoreFor(adapter.id),
|
|
593
|
+
credentialCtx: ctx as unknown as OfficialCredentialContext,
|
|
594
|
+
logger: ctx.logger as unknown as Logger,
|
|
595
|
+
timeoutMs: readVolatile(config.refreshTimeoutMs, 120000),
|
|
596
|
+
signal,
|
|
597
|
+
fetchImpl: ctx.get(OFFICIAL_FETCH_SERVICE) as GoFetchLike | undefined,
|
|
598
|
+
detectHostSessionHeader: ctx.get(OFFICIAL_SESSION_HEADER_DETECT_SERVICE) as (() => boolean) | undefined,
|
|
599
|
+
loadPiAiCompatHints: ctx.get(OFFICIAL_COMPAT_HINTS_SERVICE) as (() => CompatHintsByProtocol) | undefined,
|
|
600
|
+
}),
|
|
601
|
+
onReport: (trigger, result) => {
|
|
602
|
+
if (trigger === 'manual') return
|
|
603
|
+
if (!result.ok) {
|
|
604
|
+
ctx.logger.warn('model-sync: %s (%s) %s', adapter.id, trigger, result.text)
|
|
605
|
+
} else if (result.changed && readVolatile(config.syncNotify, false)) {
|
|
606
|
+
for (const line of result.text.split('\n')) ctx.logger.info('model-sync: %s', line)
|
|
607
|
+
} else if (result.changed) {
|
|
608
|
+
ctx.logger.info('model-sync: %s (%s) updated models', adapter.id, trigger)
|
|
609
|
+
}
|
|
610
|
+
},
|
|
1189
611
|
})
|
|
1190
|
-
|
|
612
|
+
schedulers.set(adapter.id, scheduler)
|
|
613
|
+
ctx.effect(() => () => scheduler.dispose(), `dsh-model-sync: official scheduler dispose (${adapter.id})`)
|
|
614
|
+
void scheduler.start()
|
|
1191
615
|
}
|
|
1192
616
|
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
const apiKey = await resolveRouteCredentialValue(
|
|
1202
|
-
target as unknown as NativeCredentialContext,
|
|
1203
|
-
desc,
|
|
1204
|
-
'opencode-go',
|
|
1205
|
-
value.ref,
|
|
1206
|
-
)
|
|
1207
|
-
const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE) as
|
|
1208
|
-
| ((rewrite: ReferenceRewrite) => Promise<void>) | undefined
|
|
1209
|
-
// Keep the pre-action-table evaluation order: the file-backed stores fail
|
|
1210
|
-
// closed without a profile identity, and must do so BEFORE any source
|
|
1211
|
-
// fetch (D4: no identity ⇒ zero outbound requests, zero writes).
|
|
1212
|
-
const ownershipStore = (target.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
|
|
1213
|
-
?? ownershipStoreForRound()
|
|
1214
|
-
const store = migrationStore()
|
|
1215
|
-
// status/rollback never need the official listing: no fetch, no extra I/O.
|
|
1216
|
-
const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : []
|
|
1217
|
-
const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined
|
|
1218
|
-
// 0.12.1 (P0): plan/apply need the host runtime catalog (fail-closed
|
|
1219
|
-
// without it); status/rollback are read/restore-only and never resolve it.
|
|
1220
|
-
// `resolveHostCatalogIds` consults the GO_HOST_CATALOG_SERVICE test seam
|
|
1221
|
-
// and falls through to the REAL host llm adapter
|
|
1222
|
-
// (`llm.discoverModels('llm-pi-ai', { provider: 'opencode-go' })`) when no
|
|
1223
|
-
// seam is injected. There is NO fixture fallback onto the official
|
|
1224
|
-
// entries: a production ctx has no seam, and deriving the catalog from the
|
|
1225
|
-
// listing itself would silently re-open the 0.12.0 fault (writing ids the
|
|
1226
|
-
// running host does not know — incident migrate-go 20261129-114103).
|
|
1227
|
-
const hostCatalogIds = needsEntries ? await resolveHostCatalogIds(target) : undefined
|
|
1228
|
-
if (needsEntries && hostCatalogIds === null) {
|
|
1229
|
-
throw new Error('host runtime catalog unavailable (host-catalog-unavailable): 宿主 llm 目录不可读 — 为避免写入宿主不认识的模型 id,已拒绝规划/写入(fail-closed)')
|
|
1230
|
-
}
|
|
1231
|
-
const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
|
|
1232
|
-
|| settings === undefined || typeof settings.mutate !== 'function'
|
|
1233
|
-
return {
|
|
1234
|
-
settings,
|
|
1235
|
-
ownershipStore,
|
|
1236
|
-
migrationStore: store,
|
|
1237
|
-
logger: target.logger as unknown as Logger,
|
|
1238
|
-
entries,
|
|
1239
|
-
publicCatalogIds,
|
|
1240
|
-
hostCatalogIds,
|
|
1241
|
-
routes: value.routes,
|
|
1242
|
-
ref: value.ref,
|
|
1243
|
-
keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
|
|
1244
|
-
adopt: opts.adopt,
|
|
1245
|
-
adoptDisabled,
|
|
1246
|
-
rewriteRefs: opts.rewriteRefs,
|
|
1247
|
-
// Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
|
|
1248
|
-
pinnedModels: value.pinnedModels,
|
|
1249
|
-
pruneUserExtra: opts.pruneUserExtra,
|
|
1250
|
-
now: Date.now(),
|
|
1251
|
-
isSyncInFlight: (ctx.get(GO_MIGRATION_MUTEX_SERVICE) as (() => boolean) | undefined)
|
|
1252
|
-
?? (() => goScheduler.isInFlight),
|
|
1253
|
-
applyReferenceRewrite: refWriter,
|
|
1254
|
-
// O1/C2: apply/rollback clear this profile's journals so a stale slot
|
|
1255
|
-
// cannot re-account settings that the migration just rewrote or undid.
|
|
1256
|
-
journalStore: journalStoreForRound(),
|
|
1257
|
-
profileKey,
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
/** Shared by the slash command and the `modelSync` host service (§14.5). */
|
|
1262
|
-
const runMigrate = async (
|
|
1263
|
-
args: string[],
|
|
1264
|
-
target: Context,
|
|
1265
|
-
): Promise<{ kind: 'success' | 'error'; text: string }> => {
|
|
1266
|
-
const usage = [
|
|
1267
|
-
'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
|
|
1268
|
-
' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
|
|
1269
|
-
' /model-sync migrate rollback --plan <planHash>',
|
|
1270
|
-
' /model-sync migrate status',
|
|
1271
|
-
].join('\n')
|
|
1272
|
-
const action = args[0] ?? 'plan'
|
|
1273
|
-
const rest = args.slice(1)
|
|
1274
|
-
if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
|
|
1275
|
-
return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` }
|
|
1276
|
-
}
|
|
1277
|
-
// Consent has no bypass: these flags are recognised and rejected explicitly.
|
|
1278
|
-
if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
|
|
1279
|
-
return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' }
|
|
1280
|
-
}
|
|
1281
|
-
const flagValue = (name: string): string | undefined => {
|
|
1282
|
-
const index = rest.indexOf(name)
|
|
1283
|
-
if (index >= 0) return rest[index + 1]
|
|
1284
|
-
const inline = rest.find((token) => token.startsWith(`${name}=`))
|
|
1285
|
-
return inline?.slice(name.length + 1)
|
|
1286
|
-
}
|
|
1287
|
-
const planHash = flagValue('--plan')
|
|
1288
|
-
const confirmCode = flagValue('--confirm')
|
|
1289
|
-
const adopt = rest.includes('--adopt')
|
|
1290
|
-
const ackManaged = rest.includes('--ack-managed')
|
|
1291
|
-
const pruneUserExtra = rest.includes('--prune-user-extra')
|
|
1292
|
-
const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length)
|
|
1293
|
-
const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
|
|
1294
|
-
? rewriteRefsRaw as RewriteRefMode
|
|
1295
|
-
: undefined
|
|
1296
|
-
|
|
1297
|
-
try {
|
|
1298
|
-
if (action === 'status') {
|
|
1299
|
-
const deps = await migrateDeps(target, {}, false)
|
|
1300
|
-
const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled })
|
|
1301
|
-
return { kind: 'success', text: report.text }
|
|
1302
|
-
}
|
|
1303
|
-
if (action === 'plan') {
|
|
1304
|
-
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
|
|
1305
|
-
const record = await deps.migrationStore.read().catch(() => undefined)
|
|
1306
|
-
// Same pure builder apply uses — the printed table IS the consented one.
|
|
1307
|
-
// When adopt is disabled the mode is reported as adopt-disabled and the
|
|
1308
|
-
// rows stay conservative; no adopt action can be printed as executable.
|
|
1309
|
-
const plan = buildMigrationPlanFromDeps(deps, record)
|
|
1310
|
-
return { kind: 'success', text: formatMigrationPlan(plan) }
|
|
1311
|
-
}
|
|
1312
|
-
if (action === 'apply') {
|
|
1313
|
-
const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
|
|
1314
|
-
// Fail-closed fallback (§14.2): reject at the command layer before any
|
|
1315
|
-
// write when the per-id action table cannot be executed verbatim.
|
|
1316
|
-
if (adopt && deps.adoptDisabled === true) {
|
|
1317
|
-
return {
|
|
1318
|
-
kind: 'error',
|
|
1319
|
-
text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
|
|
1320
|
-
}
|
|
617
|
+
ctx.effect(() => ctx.on('credentials/reference-updated', (ref: unknown) => {
|
|
618
|
+
if (typeof ref !== 'string') return
|
|
619
|
+
for (const adapter of listOfficialAdapters()) {
|
|
620
|
+
const scheduler = schedulers.get(adapter.id)
|
|
621
|
+
if (scheduler === undefined) continue
|
|
622
|
+
void migrationStoreFor(adapter.id)?.read().then((record) => {
|
|
623
|
+
if (adapter.defaultKeyRefs.includes(ref) || record?.apiKeyEnv === ref) {
|
|
624
|
+
void scheduler.resetPause()
|
|
1321
625
|
}
|
|
1322
|
-
|
|
1323
|
-
return { kind: result.ok ? 'success' : 'error', text: result.text }
|
|
1324
|
-
}
|
|
1325
|
-
// rollback
|
|
1326
|
-
const deps = await migrateDeps(target, {}, false)
|
|
1327
|
-
const result = await rollbackMigration({ planHash }, deps)
|
|
1328
|
-
return { kind: result.ok ? 'success' : 'error', text: result.text }
|
|
1329
|
-
} catch (error) {
|
|
1330
|
-
const message = error instanceof Error ? error.message : String(error)
|
|
1331
|
-
return { kind: 'error', text: `migrate ${action} failed: ${message}` }
|
|
626
|
+
}).catch(() => {})
|
|
1332
627
|
}
|
|
1333
|
-
}
|
|
628
|
+
}), 'dsh-model-sync: credentials/reference-updated → official pause reset')
|
|
1334
629
|
|
|
1335
630
|
// -----------------------------------------------------------------------
|
|
1336
|
-
//
|
|
1337
|
-
// + apply). Assembled from the same seams migrateDeps reads; the fs subset
|
|
1338
|
-
// and the clock are the only new external surfaces, both plain adapters
|
|
1339
|
-
// over node:fs/promises and Date here so tests inject their own.
|
|
631
|
+
// Legacy pi.dev auto-refresh timers
|
|
1340
632
|
// -----------------------------------------------------------------------
|
|
1341
|
-
const oneShotFs: OneShotFs = {
|
|
1342
|
-
readFile: (path) => readFile(path, 'utf8'),
|
|
1343
|
-
writeFile: (path, data, mode) => (mode === undefined ? writeFile(path, data) : writeFile(path, data, { mode })),
|
|
1344
|
-
rename: (from, to) => rename(from, to),
|
|
1345
|
-
unlink: async (path) => { await unlink(path) },
|
|
1346
|
-
mkdir: async (path, options) => { await mkdir(path, options) },
|
|
1347
|
-
stat: async (path) => {
|
|
1348
|
-
const info = await statFd(path).catch(() => undefined)
|
|
1349
|
-
return info === undefined ? undefined : { mode: info.mode }
|
|
1350
|
-
},
|
|
1351
|
-
readdir: async (path) => readdir(path),
|
|
1352
|
-
// Backup creation: claim the final name exclusively (O_EXCL `wx` — false
|
|
1353
|
-
// when taken, so the caller retries the next sequence suffix), stamp the
|
|
1354
|
-
// claim with a recognizable placeholder line, then replace the claimed
|
|
1355
|
-
// file atomically via tmp + rename. A crash between claim and rename
|
|
1356
|
-
// leaves a self-describing placeholder (review M7) instead of a silent
|
|
1357
|
-
// 0-byte file that looks like a real backup; the tmp+rename guarantees the
|
|
1358
|
-
// backup content itself is never torn. A failure of the tmp write or the
|
|
1359
|
-
// rename releases the claim AND removes the tmp residue.
|
|
1360
|
-
writeFileExclusive: async (path, data, mode) => {
|
|
1361
|
-
let handle
|
|
1362
|
-
try {
|
|
1363
|
-
handle = await open(path, 'wx', mode)
|
|
1364
|
-
} catch (err) {
|
|
1365
|
-
if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false
|
|
1366
|
-
throw err
|
|
1367
|
-
}
|
|
1368
|
-
try {
|
|
1369
|
-
// The file was created with `mode` by open(wx); the placeholder write
|
|
1370
|
-
// keeps that mode — no explicit mode needed here.
|
|
1371
|
-
await handle.writeFile('dsh-model-sync: backup claim in progress — crash residue, NOT a backup (safe to delete)\n')
|
|
1372
|
-
} finally {
|
|
1373
|
-
await handle.close().catch(() => {})
|
|
1374
|
-
}
|
|
1375
|
-
const tmp = `${path}.tmp-${process.pid}-${exclusiveWriteSeq++}`
|
|
1376
|
-
try {
|
|
1377
|
-
await writeFile(tmp, data, mode === undefined ? undefined : { mode })
|
|
1378
|
-
await rename(tmp, path)
|
|
1379
|
-
return true
|
|
1380
|
-
} catch (err) {
|
|
1381
|
-
await unlink(tmp).catch(() => {}) // remove the tmp residue (review M7)
|
|
1382
|
-
await unlink(path).catch(() => {}) // release the claim; nothing was replaced
|
|
1383
|
-
throw err
|
|
1384
|
-
}
|
|
1385
|
-
},
|
|
1386
|
-
}
|
|
1387
|
-
let exclusiveWriteSeq = 0
|
|
1388
|
-
/** Sync-read + atomic-write io for one patch file (describe() is sync). */
|
|
1389
|
-
const patchIoFor = (path: string): PatchFileIo => {
|
|
1390
|
-
let writeSeq = 0
|
|
1391
|
-
return {
|
|
1392
|
-
readText: () => readFileSync(path, 'utf8'),
|
|
1393
|
-
writeAtomic: async (text) => {
|
|
1394
|
-
writeSeq += 1
|
|
1395
|
-
const tmp = `${path}.tmp-${process.pid}-${writeSeq}`
|
|
1396
|
-
const mode = statSync(path).mode
|
|
1397
|
-
try {
|
|
1398
|
-
writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined)
|
|
1399
|
-
await rename(tmp, path)
|
|
1400
|
-
} catch (err) {
|
|
1401
|
-
await unlink(tmp).catch(() => {}) // no tmp residue on a failed write (review M7)
|
|
1402
|
-
throw err
|
|
1403
|
-
}
|
|
1404
|
-
},
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
const buildOneShotDeps = (target: Context): OneShotDeps => {
|
|
1408
|
-
const { value } = readGoRuntimeConfig(config)
|
|
1409
|
-
const settings = settingsForWriteFrom(target)
|
|
1410
|
-
const desc = settings?.describe().find((item) => item.ns === 'llm-pi-ai')
|
|
1411
|
-
const ref = value.ref
|
|
1412
|
-
const profile = target.get('profileContext') as { name?: string; dir?: string } | undefined
|
|
1413
|
-
const launchEnv = target.get('launchEnvironment') as { get(key: string): { value: string } | undefined } | undefined
|
|
1414
|
-
const injectedMutex = target.get(GO_MIGRATION_MUTEX_SERVICE) as (() => boolean) | undefined
|
|
1415
|
-
const injectedRefWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE) as
|
|
1416
|
-
| ((rewrite: ReferenceRewrite) => Promise<void>) | undefined
|
|
1417
|
-
const pathOverrides = target.get(GO_ONESHOT_PATHS_SERVICE) as GoOneShotPaths | undefined
|
|
1418
|
-
return {
|
|
1419
|
-
home: pathOverrides?.home ?? resolveDshHome(),
|
|
1420
|
-
modelsStorePath: pathOverrides?.modelsStorePath ?? MODELS_STORE_PATH,
|
|
1421
|
-
profilesDir: pathOverrides?.profilesDir,
|
|
1422
|
-
fs: oneShotFs,
|
|
1423
|
-
patchIoFor,
|
|
1424
|
-
currentProfile: {
|
|
1425
|
-
key: resolveProfileKey(target),
|
|
1426
|
-
dir: profile?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
|
|
1427
|
-
},
|
|
1428
|
-
currentSettings: settings,
|
|
1429
|
-
hostSettings: rawSettings() as (SettingsService & { update?(ns: string, patch: object): Promise<void> }) | undefined,
|
|
1430
|
-
goConfig: {
|
|
1431
|
-
routes: value.routes,
|
|
1432
|
-
ref,
|
|
1433
|
-
pinnedModels: value.pinnedModels,
|
|
1434
|
-
adoptDisabled: target.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
|
|
1435
|
-
|| settings === undefined || typeof settings.mutate !== 'function',
|
|
1436
|
-
},
|
|
1437
|
-
resolveCredential: async () => ({
|
|
1438
|
-
value: await resolveRouteCredentialValue(
|
|
1439
|
-
target as unknown as NativeCredentialContext,
|
|
1440
|
-
desc,
|
|
1441
|
-
'opencode-go',
|
|
1442
|
-
ref,
|
|
1443
|
-
),
|
|
1444
|
-
ref,
|
|
1445
|
-
}),
|
|
1446
|
-
resolveEntries: (apiKey) => resolveMigrateEntries(value, apiKey),
|
|
1447
|
-
resolvePublicCatalogIds: (_apiKey, entries) => resolvePublicCatalogIds(value, entries),
|
|
1448
|
-
// 0.12.1: the one-shot aborts (zero writes) when the host runtime
|
|
1449
|
-
// catalog cannot be read — never fail open onto the full listing.
|
|
1450
|
-
resolveHostCatalogIds: () => resolveHostCatalogIds(target),
|
|
1451
|
-
resolveAsk: () => {
|
|
1452
|
-
try {
|
|
1453
|
-
return target.get('userQuestions') as AskServiceShape | undefined
|
|
1454
|
-
} catch {
|
|
1455
|
-
return undefined
|
|
1456
|
-
}
|
|
1457
|
-
},
|
|
1458
|
-
// File-backed stores scoped per profile in the SAME models-store.json
|
|
1459
|
-
// the backup step snapshots. The GO_MIGRATION_STORE_SERVICE /
|
|
1460
|
-
// GO_OWNERSHIP_STORE_SERVICE seams are deliberately NOT consulted
|
|
1461
|
-
// here: the one-shot needs per-profile scoping, which the injected
|
|
1462
|
-
// single-store seams cannot express — the path override below is the
|
|
1463
|
-
// test seam instead (tests point it at a temp dir).
|
|
1464
|
-
storesFor: (profileKey) => ({
|
|
1465
|
-
ownership: createModelsStoreOwnershipStore(pathOverrides?.modelsStorePath, profileKey),
|
|
1466
|
-
migration: createModelsStoreMigrationStateStore(pathOverrides?.modelsStorePath, profileKey),
|
|
1467
|
-
}),
|
|
1468
|
-
journalStore: profileKey === undefined ? undefined : createModelsStoreJournalStore(pathOverrides?.modelsStorePath),
|
|
1469
|
-
isSyncInFlight: injectedMutex ?? (() => goScheduler.isInFlight),
|
|
1470
|
-
applyReferenceRewrite: injectedRefWriter,
|
|
1471
|
-
...(pathOverrides?.testOnlyOwnershipWriteFaultPrefix !== undefined
|
|
1472
|
-
? { faultOwnershipWriteOnKeyPrefix: pathOverrides.testOnlyOwnershipWriteFaultPrefix }
|
|
1473
|
-
: {}),
|
|
1474
|
-
logger: target.logger as unknown as Logger,
|
|
1475
|
-
now: Date.now,
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
|
-
/** Auto rounds log the same report the /model-sync command shows. */
|
|
1480
633
|
const runAuto = (): void => {
|
|
1481
|
-
// A rejected round (service lookups mid-dispose, a refused mutate) must
|
|
1482
|
-
// settle here: an unhandled rejection from a timer-driven round would
|
|
1483
|
-
// terminate the whole host process, and the auto path has no caller to
|
|
1484
|
-
// hand the error to.
|
|
1485
634
|
void syncNow(false).then(
|
|
1486
635
|
(report) => {
|
|
1487
636
|
for (const line of report.split('\n')) ctx.logger.info('model-sync: %s', line)
|
|
@@ -1492,230 +641,192 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
1492
641
|
)
|
|
1493
642
|
}
|
|
1494
643
|
|
|
1495
|
-
|
|
644
|
+
let stopInterval: ReturnType<typeof setInterval> | undefined
|
|
645
|
+
let startupTimer: ReturnType<typeof setTimeout> | undefined
|
|
1496
646
|
const armInterval = (minutes: number): void => {
|
|
1497
647
|
if (stopInterval !== undefined) clearInterval(stopInterval)
|
|
1498
648
|
stopInterval = undefined
|
|
1499
649
|
if (minutes > 0) stopInterval = setInterval(runAuto, minutes * 60_000)
|
|
1500
650
|
}
|
|
1501
|
-
|
|
1502
|
-
let startupTimer: ReturnType<typeof setTimeout> | undefined
|
|
1503
|
-
// One effect releases whatever timers are live at dispose.
|
|
651
|
+
|
|
1504
652
|
ctx.effect(() => () => {
|
|
1505
653
|
if (stopInterval !== undefined) clearInterval(stopInterval)
|
|
1506
654
|
if (startupTimer !== undefined) clearTimeout(startupTimer)
|
|
1507
655
|
})
|
|
1508
656
|
|
|
1509
|
-
// Volatile fields are stable references, so the initial arms read them once
|
|
1510
|
-
// and the interval keeps working; the hot-reload notification arrives as a
|
|
1511
|
-
// settings/document-updated event (the 0.1.7 replacement for scope.watch).
|
|
1512
657
|
startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000)
|
|
1513
658
|
armInterval(config.intervalMinutes.get() ?? 240)
|
|
659
|
+
|
|
1514
660
|
ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
|
|
1515
|
-
|
|
1516
|
-
// performed, only refresh status — schedule NO round (the V23 race was a
|
|
1517
|
-
// go write echo triggering the legacy pi.dev auto round ~1s later).
|
|
1518
|
-
if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
|
|
1519
|
-
ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision)
|
|
1520
|
-
void loadMigrationStatus() // refresh state only; no timer, no runAuto
|
|
1521
|
-
return
|
|
1522
|
-
}
|
|
1523
|
-
// Only this plugin's own config entry (the bundle-patch id) re-arms timers;
|
|
1524
|
-
// the handler is idempotent — the refs already carry the new values, so the
|
|
1525
|
-
// next round reads them fresh. A foreign ns (including llm-pi-ai writes by
|
|
1526
|
-
// other actors) never schedules a round here.
|
|
661
|
+
if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) return
|
|
1527
662
|
if (ns !== OWN_ENTRY_ID) return
|
|
1528
663
|
armInterval(config.intervalMinutes.get() ?? 0)
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
goScheduler.rearm()
|
|
1533
|
-
void loadMigrationStatus()
|
|
664
|
+
for (const scheduler of schedulers.values()) {
|
|
665
|
+
void scheduler.rearm()
|
|
666
|
+
}
|
|
1534
667
|
}), 'dsh-model-sync: settings/document-updated')
|
|
1535
668
|
|
|
1536
|
-
//
|
|
1537
|
-
//
|
|
1538
|
-
//
|
|
669
|
+
// -----------------------------------------------------------------------
|
|
670
|
+
// Public service & slash command registration
|
|
671
|
+
// -----------------------------------------------------------------------
|
|
1539
672
|
ctx.provide('modelSync', {
|
|
1540
673
|
syncNow: () => syncNow(true),
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
ctx,
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
674
|
+
syncOfficial: async (provider: string) => {
|
|
675
|
+
const adapter = resolveOfficialAdapter(provider)
|
|
676
|
+
if (adapter === undefined) return formatUnsupportedProviderError(provider)
|
|
677
|
+
const scheduler = schedulers.get(adapter.id)!
|
|
678
|
+
const res = await scheduler.triggerManual()
|
|
679
|
+
return res.text
|
|
680
|
+
},
|
|
681
|
+
migrate: async (provider: string, opts?: { allProfiles?: boolean; confirm?: boolean }) => {
|
|
682
|
+
const adapter = resolveOfficialAdapter(provider)
|
|
683
|
+
if (adapter === undefined) return formatUnsupportedProviderError(provider)
|
|
684
|
+
const res = await runOfficialMigrate(buildMigrateDeps(ctx, adapter), opts)
|
|
685
|
+
return res.text
|
|
686
|
+
},
|
|
687
|
+
rollback: async (provider: string, opts?: { confirm?: boolean }) => {
|
|
688
|
+
const adapter = resolveOfficialAdapter(provider)
|
|
689
|
+
if (adapter === undefined) return formatUnsupportedProviderError(provider)
|
|
690
|
+
const res = await runOfficialRollback(buildMigrateDeps(ctx, adapter), opts)
|
|
691
|
+
return res.text
|
|
692
|
+
},
|
|
693
|
+
status: async (provider = 'opencode-go') => {
|
|
694
|
+
const adapter = resolveOfficialAdapter(provider)
|
|
695
|
+
if (adapter === undefined) return formatUnsupportedProviderError(provider)
|
|
696
|
+
const res = await runOfficialStatus(buildMigrateDeps(ctx, adapter))
|
|
697
|
+
return res.text
|
|
698
|
+
},
|
|
1558
699
|
} satisfies ModelSyncService)
|
|
1559
700
|
|
|
1560
|
-
// Register the /model-sync slash command from the plugin itself. The
|
|
1561
|
-
// registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
|
|
1562
|
-
// human-command registry shared by interactive UI adapters") — registration
|
|
1563
|
-
// is global, so every interactive UI lists the command without any UI-side
|
|
1564
|
-
// wiring. The registry is an optional peer: the `ctx.inject` sub-fiber stays
|
|
1565
|
-
// dormant until the host provides the `commands` service, so hosts without
|
|
1566
|
-
// the registry keep every other feature working. A bare `ctx.commands` read
|
|
1567
|
-
// without a declared inject throws in cordis 4.
|
|
1568
701
|
ctx.inject(['commands'], (cmdCtx) => {
|
|
1569
702
|
const commands = (cmdCtx as {
|
|
1570
703
|
commands?: { register(definition: CommandDefinition): () => void }
|
|
1571
704
|
}).commands
|
|
1572
705
|
if (commands?.register === undefined) return
|
|
706
|
+
|
|
1573
707
|
cmdCtx.effect(() => {
|
|
1574
708
|
const definition: CommandDefinition = {
|
|
1575
709
|
name: 'model-sync',
|
|
1576
|
-
description: '
|
|
1577
|
-
// GUI clients (@deepseek-ai/dsh-client-ui-commands) only claim the
|
|
1578
|
-
// text after `/model-sync ` as command arguments when the definition
|
|
1579
|
-
// declares `input`; without it matchEnter treats the whole line as a
|
|
1580
|
-
// chat message and the `/` menu can only run the bare command. The
|
|
1581
|
-
// host's parseCommand already hands the raw tail to the handler below
|
|
1582
|
-
// as rawInput, so declaring the hint is all the plugin side needs.
|
|
1583
|
-
// Attachments stay refused (no `attachments: true`) — the handler
|
|
1584
|
-
// has no attachment semantics.
|
|
710
|
+
description: 'Sync pi.dev Builtin Providers (bare), or sync/migrate/rollback/status official custom providers (e.g. /model-sync go, /model-sync migrate go, /model-sync rollback go)',
|
|
1585
711
|
input: {
|
|
1586
|
-
hint: '
|
|
712
|
+
hint: 'go | migrate <provider> [--all-profiles] [--confirm] | rollback <provider> | status [provider]',
|
|
1587
713
|
},
|
|
1588
714
|
handler: async (invocation) => {
|
|
1589
|
-
const
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
715
|
+
const tokens = invocation.rawInput.trim().split(/\s+/).filter((t) => t.length > 0)
|
|
716
|
+
if (tokens.length === 0) {
|
|
717
|
+
try {
|
|
718
|
+
const report = await syncNow(true)
|
|
719
|
+
return { kind: 'success', text: report } satisfies CommandResult
|
|
720
|
+
} catch (error) {
|
|
721
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
722
|
+
return { kind: 'error', text: `model-sync failed: ${message}` } satisfies CommandResult
|
|
723
|
+
}
|
|
1595
724
|
}
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
725
|
+
|
|
726
|
+
const [sub, ...rest] = tokens
|
|
727
|
+
const lowerSub = sub!.toLowerCase()
|
|
728
|
+
const flags = new Set(rest.filter((t) => t.startsWith('--')))
|
|
729
|
+
const positional = rest.filter((t) => !t.startsWith('--'))
|
|
730
|
+
|
|
731
|
+
if (lowerSub === 'migrate-go' || lowerSub === 'migrate') {
|
|
732
|
+
const targetName = lowerSub === 'migrate-go' ? 'opencode-go' : positional[0]
|
|
733
|
+
if (targetName === undefined) {
|
|
734
|
+
return {
|
|
735
|
+
kind: 'error',
|
|
736
|
+
text: 'usage: /model-sync migrate <provider> [--all-profiles] [--confirm] (e.g. /model-sync migrate go)',
|
|
737
|
+
} satisfies CommandResult
|
|
738
|
+
}
|
|
739
|
+
const adapter = resolveOfficialAdapter(targetName)
|
|
740
|
+
if (adapter === undefined) {
|
|
741
|
+
return { kind: 'error', text: formatUnsupportedProviderError(targetName) } satisfies CommandResult
|
|
1604
742
|
}
|
|
1605
|
-
const flags: MigrateGoFlags = parsed.flags
|
|
1606
743
|
try {
|
|
1607
|
-
return await
|
|
1608
|
-
|
|
1609
|
-
flags,
|
|
1610
|
-
|
|
1611
|
-
|
|
744
|
+
return await runOfficialMigrate(buildMigrateDeps(cmdCtx, adapter), {
|
|
745
|
+
allProfiles: flags.has('--all-profiles'),
|
|
746
|
+
confirm: flags.has('--confirm'),
|
|
747
|
+
agent: invocation.agent,
|
|
748
|
+
signal: invocation.signal,
|
|
749
|
+
})
|
|
1612
750
|
} catch (error) {
|
|
1613
751
|
const message = error instanceof Error ? error.message : String(error)
|
|
1614
|
-
return { kind: 'error', text: `migrate
|
|
752
|
+
return { kind: 'error', text: `migrate ${targetName} failed: ${message}` } satisfies CommandResult
|
|
1615
753
|
}
|
|
1616
754
|
}
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
if (sub === 'eject') {
|
|
1622
|
-
return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' } satisfies CommandResult
|
|
1623
|
-
}
|
|
1624
|
-
// Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
|
|
1625
|
-
// as it was. The go subcommands are additive: `go`/`status` run one
|
|
1626
|
-
// full go round, `adopt go` runs it with adoption. Status stays the
|
|
1627
|
-
// read-only `/opencode-status` command — it is never a write trigger.
|
|
1628
|
-
if ((sub === 'go' || sub === 'status' || sub === 'adopt')
|
|
1629
|
-
&& (scope === undefined || scope === 'go')) {
|
|
1630
|
-
try {
|
|
1631
|
-
// Route manual rounds through the scheduler so they share the
|
|
1632
|
-
// single-flight lock with timer-driven rounds. A second trigger
|
|
1633
|
-
// while a round is in flight is skipped and reported (design
|
|
1634
|
-
// §14.6), never queued. The report text is the round's own text,
|
|
1635
|
-
// unchanged, for real rounds.
|
|
1636
|
-
const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' })
|
|
1637
|
-
// N1: a round that threw (e.g. the file-backed ledger refusing to
|
|
1638
|
-
// build without a profile identity) is reported as a scheduler
|
|
1639
|
-
// error. It is a real failure — the command must return
|
|
1640
|
-
// `kind:'error'` so callers that only read `kind` can detect it;
|
|
1641
|
-
// the actionable reason is carried in `text`. Skips (disabled,
|
|
1642
|
-
// already-in-flight, migration-applying, disposed) stay success,
|
|
1643
|
-
// byte-identical to before.
|
|
1644
|
-
const failed = outcome.reason === 'source-failed'
|
|
1645
|
-
// oldfox #3: a writer exception is a real failure at the
|
|
1646
|
-
// command surface, but a distinct reason from source failure.
|
|
1647
|
-
|| outcome.reason === 'writer-error'
|
|
1648
|
-
|| outcome.reason === 'scheduler-error'
|
|
1649
|
-
// B4: an abandoned round must be visible as a failure at the
|
|
1650
|
-
// command surface too (it is not a successful sync). The reason
|
|
1651
|
-
// text carries the actionable "settings changed, next round
|
|
1652
|
-
// retries" guidance; no backoff is scheduled for it.
|
|
1653
|
-
|| outcome.reason === 'settings-changed-during-sync'
|
|
1654
|
-
// 0.12.1: the host runtime catalog was unreadable — the round
|
|
1655
|
-
// failed closed (zero writes) and the user must see why.
|
|
1656
|
-
|| outcome.reason === 'host-catalog-unavailable'
|
|
1657
|
-
// O1-minimal: failedRoutes (e.g. settings written but the ledger
|
|
1658
|
-
// failed) are a real failure even if other routes wrote. Callers
|
|
1659
|
-
// that only read `kind` must see `error`; the actionable reason
|
|
1660
|
-
// and the new report code are carried in `text`.
|
|
1661
|
-
|| outcome.reason === 'write-failed'
|
|
755
|
+
|
|
756
|
+
if (lowerSub === 'rollback') {
|
|
757
|
+
const targetName = positional[0]
|
|
758
|
+
if (targetName === undefined) {
|
|
1662
759
|
return {
|
|
1663
|
-
kind:
|
|
1664
|
-
text:
|
|
760
|
+
kind: 'error',
|
|
761
|
+
text: 'usage: /model-sync rollback <provider> [--confirm] (e.g. /model-sync rollback go)',
|
|
1665
762
|
} satisfies CommandResult
|
|
763
|
+
}
|
|
764
|
+
const adapter = resolveOfficialAdapter(targetName)
|
|
765
|
+
if (adapter === undefined) {
|
|
766
|
+
return { kind: 'error', text: formatUnsupportedProviderError(targetName) } satisfies CommandResult
|
|
767
|
+
}
|
|
768
|
+
try {
|
|
769
|
+
return await runOfficialRollback(buildMigrateDeps(cmdCtx, adapter), {
|
|
770
|
+
confirm: flags.has('--confirm'),
|
|
771
|
+
agent: invocation.agent,
|
|
772
|
+
signal: invocation.signal,
|
|
773
|
+
})
|
|
774
|
+
} catch (error) {
|
|
775
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
776
|
+
return { kind: 'error', text: `rollback ${targetName} failed: ${message}` } satisfies CommandResult
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (lowerSub === 'status') {
|
|
781
|
+
const targetName = positional[0] ?? 'opencode-go'
|
|
782
|
+
const adapter = resolveOfficialAdapter(targetName)
|
|
783
|
+
if (adapter === undefined) {
|
|
784
|
+
return { kind: 'error', text: formatUnsupportedProviderError(targetName) } satisfies CommandResult
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
return await runOfficialStatus(buildMigrateDeps(cmdCtx, adapter))
|
|
1666
788
|
} catch (error) {
|
|
1667
789
|
const message = error instanceof Error ? error.message : String(error)
|
|
1668
|
-
return { kind: 'error', text: `
|
|
790
|
+
return { kind: 'error', text: `status ${targetName} failed: ${message}` } satisfies CommandResult
|
|
1669
791
|
}
|
|
1670
792
|
}
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
793
|
+
|
|
794
|
+
const adapter = resolveOfficialAdapter(sub!)
|
|
795
|
+
if (adapter === undefined) {
|
|
796
|
+
return { kind: 'error', text: formatUnsupportedProviderError(sub!) } satisfies CommandResult
|
|
797
|
+
}
|
|
1674
798
|
try {
|
|
1675
|
-
const
|
|
1676
|
-
|
|
799
|
+
const scheduler = schedulers.get(adapter.id)!
|
|
800
|
+
const res = await scheduler.triggerManual()
|
|
801
|
+
return {
|
|
802
|
+
kind: res.ok ? 'success' : 'error',
|
|
803
|
+
text: res.text,
|
|
804
|
+
} satisfies CommandResult
|
|
1677
805
|
} catch (error) {
|
|
1678
806
|
const message = error instanceof Error ? error.message : String(error)
|
|
1679
|
-
return { kind: 'error', text:
|
|
807
|
+
return { kind: 'error', text: `model-sync ${sub} failed: ${message}` } satisfies CommandResult
|
|
1680
808
|
}
|
|
1681
809
|
},
|
|
1682
810
|
}
|
|
1683
811
|
return commands.register(definition)
|
|
1684
812
|
}, 'dsh-model-sync: /model-sync')
|
|
1685
813
|
|
|
1686
|
-
// P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
|
|
1687
|
-
// unchanged): fetch the official go listing, compare it with the current
|
|
1688
|
-
// profile's opencode-go routes, and print a structured report. This path
|
|
1689
|
-
// never calls settings.mutate, never writes credentials, and never edits
|
|
1690
|
-
// a profile file — it only reads describe()/credentials.resolve().
|
|
1691
814
|
cmdCtx.effect(() => {
|
|
1692
815
|
const definition: CommandDefinition = {
|
|
1693
816
|
name: 'opencode-status',
|
|
1694
|
-
description: 'Read-only diagnostic
|
|
817
|
+
description: 'Read-only diagnostic for OpenCode Go Official Sync status (alias for /model-sync status go)',
|
|
1695
818
|
handler: async (invocation) => {
|
|
1696
819
|
const token = invocation.rawInput.trim()
|
|
1697
|
-
const
|
|
1698
|
-
|
|
1699
|
-
|
|
820
|
+
const targetName = token === '' ? 'opencode-go' : token
|
|
821
|
+
const adapter = resolveOfficialAdapter(targetName)
|
|
822
|
+
if (adapter === undefined) {
|
|
823
|
+
return { kind: 'error', text: formatUnsupportedProviderError(targetName) } satisfies CommandResult
|
|
824
|
+
}
|
|
1700
825
|
try {
|
|
1701
|
-
|
|
1702
|
-
.find((d) => d.ns === 'llm-pi-ai')
|
|
1703
|
-
const apiKey = await resolveRouteCredentialValue(
|
|
1704
|
-
cmdCtx as unknown as NativeCredentialContext,
|
|
1705
|
-
desc,
|
|
1706
|
-
'opencode-go',
|
|
1707
|
-
)
|
|
1708
|
-
// 0.12.1: lag comparison uses the live host runtime catalog (null
|
|
1709
|
-
// tolerated — the diagnostic is read-only and degrades instead of
|
|
1710
|
-
// failing closed) and the RESOLVED go.routes (M2: custom chat
|
|
1711
|
-
// route names are diagnosed correctly).
|
|
1712
|
-
const { value: statusGoCfg } = readGoRuntimeConfig(config)
|
|
1713
|
-
const hostCatalogIds = await resolveHostCatalogIds(cmdCtx)
|
|
1714
|
-
const report = await runGoDiagnostic({ apiKey, descriptor: desc, routes: statusGoCfg.routes, hostCatalogIds })
|
|
1715
|
-
return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` } satisfies CommandResult
|
|
826
|
+
return await runOfficialStatus(buildMigrateDeps(cmdCtx, adapter))
|
|
1716
827
|
} catch (error) {
|
|
1717
828
|
const message = error instanceof Error ? error.message : String(error)
|
|
1718
|
-
return { kind: 'error', text:
|
|
829
|
+
return { kind: 'error', text: `opencode-status failed: ${message}` } satisfies CommandResult
|
|
1719
830
|
}
|
|
1720
831
|
},
|
|
1721
832
|
}
|
|
@@ -1723,28 +834,12 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
1723
834
|
}, 'dsh-model-sync: /opencode-status')
|
|
1724
835
|
})
|
|
1725
836
|
|
|
1726
|
-
// One-time legacy settings import
|
|
1727
|
-
// legacy-import.ts): recover the old `model-sync:` section for hosts where
|
|
1728
|
-
// the 0.1.7 one-shot settings.yaml import never carried it over. Wired
|
|
1729
|
-
// through ctx.inject(['settings'], …) instead of a direct `ctx.settings`
|
|
1730
|
-
// read: a real boot can run apply() before the settings service mounts,
|
|
1731
|
-
// and the direct read then silently no-settings'd the import away every
|
|
1732
|
-
// boot. The inject callback fires the moment the service exists
|
|
1733
|
-
// (immediately when it already does — fake-ctx tests stay synchronous),
|
|
1734
|
-
// fire-and-forget so activation never waits on it. Fully contained: any
|
|
1735
|
-
// failure only warns and leaves the audit marker unwritten, so the next
|
|
1736
|
-
// boot retries; activation never depends on this. The volatile refs read
|
|
1737
|
-
// fresh, and the update itself fires settings/document-updated for this
|
|
1738
|
-
// entry — the timers armed above with the pre-import value re-arm to it
|
|
1739
|
-
// without a restart.
|
|
837
|
+
// One-time legacy settings.yaml import
|
|
1740
838
|
ctx.inject(['settings'], (sctx) => {
|
|
1741
839
|
void runLegacySettingsImport({
|
|
1742
840
|
home: resolveDshHome(),
|
|
1743
841
|
settings: (sctx as unknown as { settings?: SettingsUpdateSeam }).settings,
|
|
1744
842
|
logger: (ctx as unknown as { logger?: LegacyImportLogger }).logger,
|
|
1745
|
-
// The volatile refs read fresh, and the update itself fires
|
|
1746
|
-
// settings/document-updated for this entry — the timers armed above
|
|
1747
|
-
// with the pre-import value re-arm to it without a restart.
|
|
1748
843
|
getCurrent: (key) => {
|
|
1749
844
|
const slot = (config as unknown as Record<string, unknown>)[key] as { get?: unknown } | undefined
|
|
1750
845
|
return typeof slot?.get === 'function' ? slot.get() : slot
|
|
@@ -1756,34 +851,13 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
|
|
|
1756
851
|
}
|
|
1757
852
|
|
|
1758
853
|
// ---------------------------------------------------------------------------
|
|
1759
|
-
// Builtin catalog helpers (
|
|
854
|
+
// Builtin catalog helpers (pi.dev track)
|
|
1760
855
|
// ---------------------------------------------------------------------------
|
|
1761
856
|
|
|
1762
|
-
/**
|
|
1763
|
-
* Get builtin catalog data for a route: the host's live pi-ai catalog when it
|
|
1764
|
-
* can be located, the frozen build-time snapshot otherwise. Live-first is the
|
|
1765
|
-
* point — the snapshot rots when the host's bundled pi-ai drops models
|
|
1766
|
-
* (grok-4.5 was removed in pi-ai 0.84.4), and a stale keepBuiltinOnly entry
|
|
1767
|
-
* gets the whole llm-pi-ai namespace rejected by the alpha line's strict
|
|
1768
|
-
* registration.
|
|
1769
|
-
*/
|
|
1770
857
|
function getBuiltinCatalogForRoute(route: string): BuiltinModelData[] {
|
|
1771
858
|
return getLiveBuiltinCatalogForRoute(route) ?? BUILTIN_CATALOG_SNAPSHOT[route] ?? []
|
|
1772
859
|
}
|
|
1773
860
|
|
|
1774
|
-
/**
|
|
1775
|
-
* Get entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly).
|
|
1776
|
-
* Returns minimal RemoteCatalogEntry-shaped objects — translateEntries only
|
|
1777
|
-
* reads entry.id from these, emitting {id} profiles (I-3).
|
|
1778
|
-
*
|
|
1779
|
-
* Deprecated snapshot entries (the official default model list dropped them —
|
|
1780
|
-
* dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-exp) are
|
|
1781
|
-
* excluded unless `includeDeprecated` opts them back in: a re-emitted retired
|
|
1782
|
-
* id is a model the 0.1.7 host no longer resolves. The data itself stays in
|
|
1783
|
-
* the snapshot for historical user configurations.
|
|
1784
|
-
*
|
|
1785
|
-
* Exported for the test suite; not part of the public runtime surface.
|
|
1786
|
-
*/
|
|
1787
861
|
export function getBuiltinOnlyEntries(
|
|
1788
862
|
route: string,
|
|
1789
863
|
piDevEntries: RemoteCatalogEntry[],
|
|
@@ -1795,7 +869,7 @@ export function getBuiltinOnlyEntries(
|
|
|
1795
869
|
return builtinData
|
|
1796
870
|
.filter((b) =>
|
|
1797
871
|
!piDevIds.has(b.id)
|
|
1798
|
-
&& (includeDeprecated || b.deprecated !== true)
|
|
872
|
+
&& (includeDeprecated || b.deprecated !== true),
|
|
1799
873
|
)
|
|
1800
874
|
.map((b) => ({
|
|
1801
875
|
id: b.id,
|
|
@@ -1808,9 +882,6 @@ export function getBuiltinOnlyEntries(
|
|
|
1808
882
|
}))
|
|
1809
883
|
}
|
|
1810
884
|
|
|
1811
|
-
/**
|
|
1812
|
-
* Extract raw user-segment models for a route from a settings descriptor (I-6).
|
|
1813
|
-
*/
|
|
1814
885
|
function getRawUserModelsFromDesc(
|
|
1815
886
|
desc: SettingsDescriptor | undefined,
|
|
1816
887
|
route: string,
|