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