@aiwayds/dsh-model-sync 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -376
  4. package/lib/index.js +305 -1049
  5. package/lib/index.js.map +1 -1
  6. package/lib/official-adapter.d.ts +80 -0
  7. package/lib/official-adapter.js +34 -0
  8. package/lib/official-adapter.js.map +1 -0
  9. package/lib/official-migrate.d.ts +116 -0
  10. package/lib/official-migrate.js +643 -0
  11. package/lib/official-migrate.js.map +1 -0
  12. package/lib/official-scheduler.d.ts +72 -0
  13. package/lib/official-scheduler.js +195 -0
  14. package/lib/official-scheduler.js.map +1 -0
  15. package/lib/official-store.d.ts +41 -0
  16. package/lib/official-store.js +84 -0
  17. package/lib/official-store.js.map +1 -0
  18. package/lib/official-sync.d.ts +68 -0
  19. package/lib/official-sync.js +274 -0
  20. package/lib/official-sync.js.map +1 -0
  21. package/lib/opencode-go-adapter.d.ts +56 -0
  22. package/lib/opencode-go-adapter.js +455 -0
  23. package/lib/opencode-go-adapter.js.map +1 -0
  24. package/lib/opencode-go-patch-file.d.ts +11 -0
  25. package/lib/opencode-go-patch-file.js +175 -11
  26. package/lib/opencode-go-patch-file.js.map +1 -1
  27. package/lib/opencode-go-source.d.ts +1 -1
  28. package/lib/opencode-go-source.js +1 -1
  29. package/locale/en.json +1 -1
  30. package/locale/zh.json +1 -1
  31. package/package.json +3 -3
  32. package/src/index.ts +351 -1214
  33. package/src/official-adapter.ts +111 -0
  34. package/src/official-migrate.ts +840 -0
  35. package/src/official-scheduler.ts +235 -0
  36. package/src/official-store.ts +122 -0
  37. package/src/official-sync.ts +371 -0
  38. package/src/opencode-go-adapter.ts +494 -0
  39. package/src/opencode-go-patch-file.ts +175 -9
  40. package/src/opencode-go-source.ts +1 -1
  41. package/lib/opencode-go-diagnose.d.ts +0 -75
  42. package/lib/opencode-go-diagnose.js +0 -146
  43. package/lib/opencode-go-diagnose.js.map +0 -1
  44. package/lib/opencode-go-grouping.d.ts +0 -7
  45. package/lib/opencode-go-grouping.js +0 -21
  46. package/lib/opencode-go-grouping.js.map +0 -1
  47. package/lib/opencode-go-journal.d.ts +0 -110
  48. package/lib/opencode-go-journal.js +0 -406
  49. package/lib/opencode-go-journal.js.map +0 -1
  50. package/lib/opencode-go-migrate.d.ts +0 -345
  51. package/lib/opencode-go-migrate.js +0 -1371
  52. package/lib/opencode-go-migrate.js.map +0 -1
  53. package/lib/opencode-go-migration.d.ts +0 -227
  54. package/lib/opencode-go-migration.js +0 -384
  55. package/lib/opencode-go-migration.js.map +0 -1
  56. package/lib/opencode-go-one-shot.d.ts +0 -276
  57. package/lib/opencode-go-one-shot.js +0 -1096
  58. package/lib/opencode-go-one-shot.js.map +0 -1
  59. package/lib/opencode-go-planner.d.ts +0 -154
  60. package/lib/opencode-go-planner.js +0 -305
  61. package/lib/opencode-go-planner.js.map +0 -1
  62. package/lib/opencode-go-scheduler.d.ts +0 -128
  63. package/lib/opencode-go-scheduler.js +0 -241
  64. package/lib/opencode-go-scheduler.js.map +0 -1
  65. package/lib/opencode-go-store.d.ts +0 -18
  66. package/lib/opencode-go-store.js +0 -68
  67. package/lib/opencode-go-store.js.map +0 -1
  68. package/lib/opencode-go-sync.d.ts +0 -94
  69. package/lib/opencode-go-sync.js +0 -364
  70. package/lib/opencode-go-sync.js.map +0 -1
  71. package/lib/opencode-go-writer.d.ts +0 -132
  72. package/lib/opencode-go-writer.js +0 -977
  73. package/lib/opencode-go-writer.js.map +0 -1
  74. package/src/opencode-go-diagnose.ts +0 -223
  75. package/src/opencode-go-grouping.ts +0 -26
  76. package/src/opencode-go-journal.ts +0 -458
  77. package/src/opencode-go-migrate.ts +0 -1764
  78. package/src/opencode-go-migration.ts +0 -552
  79. package/src/opencode-go-one-shot.ts +0 -1356
  80. package/src/opencode-go-planner.ts +0 -472
  81. package/src/opencode-go-scheduler.ts +0 -315
  82. package/src/opencode-go-store.ts +0 -73
  83. package/src/opencode-go-sync.ts +0 -503
  84. package/src/opencode-go-writer.ts +0 -1201
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Per-adapter timer & single-flight scheduler for Official Sync.
3
+ *
4
+ * Behavior:
5
+ * - Arms automatically once a profile has migrated (`isMigrated() === true`)
6
+ * and `intervalMinutes > 0` (default 60; 0 = manual-only).
7
+ * - Shares a single-flight lock between timer rounds and manual triggers.
8
+ * - Pauses automatic retries on `auth` / `entitlement` errors until
9
+ * credentials update or the user runs a manual sync.
10
+ * - Uses capped exponential backoff (1m → 30m) on transient transport/parse
11
+ * errors.
12
+ *
13
+ * @module dsh-model-sync/official-scheduler
14
+ */
15
+
16
+ import type { OfficialSyncRoundResult } from './official-sync.ts'
17
+
18
+ export type OfficialTrigger = 'startup' | 'interval' | 'backoff' | 'manual'
19
+
20
+ export type OfficialTimerHandle = unknown
21
+
22
+ export interface OfficialSchedulerTimers {
23
+ setTimeout(fn: () => void, ms: number): OfficialTimerHandle
24
+ clearTimeout(handle: OfficialTimerHandle): void
25
+ }
26
+
27
+ export interface OfficialSchedulerRandom {
28
+ next(): number
29
+ }
30
+
31
+ export interface OfficialSchedulerDeps {
32
+ adapterId: string
33
+ timers?: OfficialSchedulerTimers
34
+ random?: OfficialSchedulerRandom
35
+ getIntervalMinutes: () => number
36
+ getStartupDelaySeconds: () => number
37
+ isMigrated: () => Promise<boolean> | boolean
38
+ runRound: (request: { trigger: OfficialTrigger; signal: AbortSignal }) => Promise<OfficialSyncRoundResult>
39
+ onReport: (trigger: OfficialTrigger, result: OfficialSyncRoundResult) => void
40
+ }
41
+
42
+ export interface OfficialScheduledResult extends OfficialSyncRoundResult {
43
+ skipped: boolean
44
+ }
45
+
46
+ export const OFFICIAL_STARTUP_JITTER_MAX_MS = 5_000
47
+ export const OFFICIAL_TRANSIENT_BACKOFF_BASE_MS = 60_000
48
+ export const OFFICIAL_TRANSIENT_BACKOFF_CAP_MS = 30 * 60_000
49
+
50
+ const DEFAULT_TIMERS: OfficialSchedulerTimers = {
51
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
52
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
53
+ }
54
+
55
+ export function computeTransientBackoffMs(streak: number): number {
56
+ const n = Math.max(1, Math.floor(streak))
57
+ return Math.min(OFFICIAL_TRANSIENT_BACKOFF_CAP_MS, OFFICIAL_TRANSIENT_BACKOFF_BASE_MS * 2 ** (n - 1))
58
+ }
59
+
60
+ export function computeStartupDelayMs(delaySeconds: number, rand: number): number {
61
+ const base = Number.isFinite(delaySeconds) && delaySeconds > 0 ? delaySeconds * 1000 : 0
62
+ const r = Math.min(1, Math.max(0, Number.isFinite(rand) ? rand : 0))
63
+ return base + Math.floor(r * OFFICIAL_STARTUP_JITTER_MAX_MS)
64
+ }
65
+
66
+ export class OfficialSyncScheduler {
67
+ private readonly deps: OfficialSchedulerDeps
68
+ private readonly timers: OfficialSchedulerTimers
69
+ private readonly random: OfficialSchedulerRandom
70
+ private readonly abort = new AbortController()
71
+
72
+ private handle: OfficialTimerHandle | undefined
73
+ private started = false
74
+ private disposed = false
75
+ private inFlight = false
76
+ private pausedForAuth = false
77
+ private transientStreak = 0
78
+
79
+ constructor(deps: OfficialSchedulerDeps) {
80
+ this.deps = deps
81
+ this.timers = deps.timers ?? DEFAULT_TIMERS
82
+ this.random = deps.random ?? { next: () => Math.random() }
83
+ }
84
+
85
+ get isInFlight(): boolean {
86
+ return this.inFlight
87
+ }
88
+
89
+ get isPausedForAuth(): boolean {
90
+ return this.pausedForAuth
91
+ }
92
+
93
+ get failureStreak(): number {
94
+ return this.transientStreak
95
+ }
96
+
97
+ async start(): Promise<void> {
98
+ if (this.started || this.disposed) return
99
+ this.started = true
100
+ const migrated = await this.safeIsMigrated()
101
+ const interval = this.normalizedIntervalMinutes()
102
+ if (!migrated || interval <= 0) return
103
+ const delay = computeStartupDelayMs(this.deps.getStartupDelaySeconds(), this.random.next())
104
+ this.arm(delay, 'startup')
105
+ }
106
+
107
+ async rearm(): Promise<void> {
108
+ if (this.disposed) return
109
+ this.started = true
110
+ this.cancel()
111
+ if (this.inFlight) return
112
+ await this.scheduleNext()
113
+ }
114
+
115
+ async resetPause(): Promise<void> {
116
+ this.pausedForAuth = false
117
+ this.transientStreak = 0
118
+ if (this.disposed || !this.started || this.inFlight) return
119
+ await this.scheduleNext()
120
+ }
121
+
122
+ triggerManual(): Promise<OfficialScheduledResult> {
123
+ return this.fire('manual')
124
+ }
125
+
126
+ dispose(): void {
127
+ this.disposed = true
128
+ this.abort.abort()
129
+ this.cancel()
130
+ }
131
+
132
+ private async safeIsMigrated(): Promise<boolean> {
133
+ try {
134
+ return await this.deps.isMigrated()
135
+ } catch {
136
+ return false
137
+ }
138
+ }
139
+
140
+ private normalizedIntervalMinutes(): number {
141
+ const raw = this.deps.getIntervalMinutes()
142
+ if (!Number.isFinite(raw)) return 60
143
+ return Math.max(0, Math.floor(raw))
144
+ }
145
+
146
+ private arm(delayMs: number, trigger: OfficialTrigger): void {
147
+ this.cancel()
148
+ this.handle = this.timers.setTimeout(() => this.fire(trigger), Math.max(0, delayMs))
149
+ }
150
+
151
+ private cancel(): void {
152
+ if (this.handle !== undefined) {
153
+ this.timers.clearTimeout(this.handle)
154
+ this.handle = undefined
155
+ }
156
+ }
157
+
158
+ private async scheduleNext(): Promise<void> {
159
+ if (this.disposed || this.pausedForAuth) return
160
+ const migrated = await this.safeIsMigrated()
161
+ if (!migrated || this.disposed) return
162
+ const intervalMinutes = this.normalizedIntervalMinutes()
163
+ if (intervalMinutes <= 0) return
164
+ if (this.transientStreak > 0) {
165
+ this.arm(computeTransientBackoffMs(this.transientStreak), 'backoff')
166
+ } else {
167
+ this.arm(intervalMinutes * 60_000, 'interval')
168
+ }
169
+ }
170
+
171
+ private async fire(trigger: OfficialTrigger): Promise<OfficialScheduledResult> {
172
+ if (this.disposed) {
173
+ return {
174
+ ok: false,
175
+ changed: false,
176
+ skipped: true,
177
+ reason: 'settings-unavailable',
178
+ text: `${this.deps.adapterId}: scheduler disposed.`,
179
+ }
180
+ }
181
+ if (this.inFlight) {
182
+ return {
183
+ ok: false,
184
+ changed: false,
185
+ skipped: true,
186
+ reason: 'no-change',
187
+ text: `${this.deps.adapterId}: sync already in flight; skipped duplicate ${trigger} trigger.`,
188
+ }
189
+ }
190
+
191
+ this.cancel()
192
+ this.inFlight = true
193
+ if (trigger === 'manual') {
194
+ this.pausedForAuth = false
195
+ this.transientStreak = 0
196
+ }
197
+
198
+ let result: OfficialSyncRoundResult
199
+ try {
200
+ result = await this.deps.runRound({ trigger, signal: this.abort.signal })
201
+ } catch (error) {
202
+ const msg = error instanceof Error ? error.message : String(error)
203
+ result = {
204
+ ok: false,
205
+ changed: false,
206
+ reason: 'source-failed',
207
+ failureKind: 'transport',
208
+ text: `${this.deps.adapterId}: round error — ${msg}`,
209
+ }
210
+ } finally {
211
+ this.inFlight = false
212
+ }
213
+
214
+ if (result.reason === 'not-migrated') {
215
+ this.cancel()
216
+ } else if (result.ok) {
217
+ this.transientStreak = 0
218
+ this.pausedForAuth = false
219
+ } else if (result.failureKind === 'auth' || result.failureKind === 'entitlement') {
220
+ this.pausedForAuth = true
221
+ } else {
222
+ this.transientStreak += 1
223
+ }
224
+
225
+ if (trigger === 'manual' || result.changed || !result.ok) {
226
+ this.deps.onReport(trigger, result)
227
+ }
228
+
229
+ if (!this.disposed && result.reason !== 'not-migrated') {
230
+ await this.scheduleNext()
231
+ }
232
+
233
+ return { ...result, skipped: false }
234
+ }
235
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Per-profile persistence for Official Sync migration state in
3
+ * `~/.dsh/models-store.json`.
4
+ *
5
+ * Keys are strictly scoped by `<profileKey>#official-migration:<adapterId>` so
6
+ * multiple dsh profiles sharing the same `models-store.json` never collide or
7
+ * claim another profile's migration state.
8
+ *
9
+ * @module dsh-model-sync/official-store
10
+ */
11
+
12
+ import { scopedStoreKey } from './opencode-go-profile.ts'
13
+ import { loadModelsStore, type ModelsStoreAccessor } from './remote-catalog.ts'
14
+
15
+ export interface OfficialMigrationRecord {
16
+ version: 2
17
+ adapterId: string
18
+ profileKey: string
19
+ migratedAt: number
20
+ apiKeyEnv: string
21
+ builtinProviderId: string
22
+ managedRoutes: string[]
23
+ /** Complete pre-migration `providers.<builtinProviderId>` section for rollback. */
24
+ previousBuiltinSection: Record<string, unknown>
25
+ /** Pre-existing sections on target custom provider routes before migration (`null` = absent). */
26
+ previousManagedSections?: Record<string, Record<string, unknown> | null>
27
+ /** Pre-migration `agent-default-model` config when migration rewrote it. */
28
+ previousDefaultModel?: Record<string, unknown>
29
+ rewroteDefaultModel?: boolean
30
+ }
31
+
32
+ export interface OfficialMigrationStore {
33
+ read(): Promise<OfficialMigrationRecord | undefined>
34
+ write(record: OfficialMigrationRecord): Promise<void>
35
+ delete(): Promise<void>
36
+ }
37
+
38
+ export function officialMigrationStoreKeyBase(adapterId: string): string {
39
+ return `official-migration:${adapterId}`
40
+ }
41
+
42
+ export function officialMigrationStoreKey(profileKey: string, adapterId: string): string {
43
+ return scopedStoreKey(profileKey, officialMigrationStoreKeyBase(adapterId))
44
+ }
45
+
46
+ function isOfficialMigrationRecord(raw: unknown): raw is OfficialMigrationRecord {
47
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return false
48
+ const rec = raw as Record<string, unknown>
49
+ return rec.version === 2
50
+ && typeof rec.adapterId === 'string'
51
+ && typeof rec.profileKey === 'string'
52
+ && typeof rec.apiKeyEnv === 'string'
53
+ && typeof rec.builtinProviderId === 'string'
54
+ && Array.isArray(rec.managedRoutes)
55
+ && rec.previousBuiltinSection !== null
56
+ && typeof rec.previousBuiltinSection === 'object'
57
+ && !Array.isArray(rec.previousBuiltinSection)
58
+ }
59
+
60
+ export function createOfficialMigrationStore(
61
+ accessor: ModelsStoreAccessor,
62
+ profileKey: string,
63
+ adapterId: string,
64
+ ): OfficialMigrationStore {
65
+ const key = officialMigrationStoreKey(profileKey, adapterId)
66
+ return {
67
+ async read(): Promise<OfficialMigrationRecord | undefined> {
68
+ try {
69
+ const raw = await accessor.readRaw(key)
70
+ return isOfficialMigrationRecord(raw) ? raw : undefined
71
+ } catch {
72
+ return undefined
73
+ }
74
+ },
75
+ async write(record: OfficialMigrationRecord): Promise<void> {
76
+ await accessor.writeRaw(key, record as unknown as Record<string, unknown>)
77
+ },
78
+ async delete(): Promise<void> {
79
+ await accessor.deleteRaw(key)
80
+ },
81
+ }
82
+ }
83
+
84
+ export function createDefaultOfficialMigrationStore(
85
+ profileKey: string,
86
+ adapterId: string,
87
+ storePath?: string,
88
+ ): OfficialMigrationStore {
89
+ return createOfficialMigrationStore(loadModelsStore(storePath), profileKey, adapterId)
90
+ }
91
+
92
+ /**
93
+ * Remove legacy v0.11/v0.12 opencode-go migration & ownership ledger keys for
94
+ * `profileKey` after a v0.13 migration succeeds.
95
+ */
96
+ export async function cleanupLegacyGoStoreKeys(
97
+ accessor: ModelsStoreAccessor,
98
+ profileKey: string,
99
+ extraRoutes: readonly string[] = [],
100
+ ): Promise<void> {
101
+ const keys = await accessor.listRawKeys().catch(() => [] as string[])
102
+ const routePrefixes = new Set([
103
+ 'opencode-go',
104
+ 'opencode-go-msg',
105
+ 'opencode-go-resp',
106
+ 'opencode-go-google',
107
+ ...extraRoutes,
108
+ ])
109
+ const legacyMigrationKey = `${profileKey}#migration:opencode-go`
110
+ for (const key of keys) {
111
+ if (key === legacyMigrationKey) {
112
+ await accessor.deleteRaw(key).catch(() => {})
113
+ continue
114
+ }
115
+ if (!key.startsWith(`${profileKey}#`)) continue
116
+ const rest = key.slice(profileKey.length + 1)
117
+ const hashIdx = rest.indexOf('#')
118
+ if (hashIdx > 0 && routePrefixes.has(rest.slice(0, hashIdx))) {
119
+ await accessor.deleteRaw(key).catch(() => {})
120
+ }
121
+ }
122
+ }