@sixzjd/dsh-workbuddy-connect 0.0.0-stage → 0.3.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/lib/catalog.js ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * WorkBuddy model catalog.
3
+ *
4
+ * Three sources, in descending order of authority:
5
+ *
6
+ * 1. **live** — the upstream's own answer, fetched on a schedule.
7
+ * 2. **saved** — the last live list this account produced, kept on disk so a
8
+ * restart or an offline start still serves a usable roster.
9
+ * 3. **fallback** — a compiled-in roster, so the provider registers with
10
+ * something before the first fetch lands.
11
+ *
12
+ * The card says which one is in force, because "the list you see" and "the
13
+ * list the upstream currently serves" are different questions and a silent
14
+ * answer to the first one is how a plugin ends up advertising a retired model.
15
+ *
16
+ * @module dsh-workbuddy-connect/catalog
17
+ */
18
+ import { modelWithCurrentPromotion } from './upstream.js'
19
+
20
+ /**
21
+ * The per-request prompt ceiling each model actually enforces, measured
22
+ * 2026-10-28 against the live gateways.
23
+ *
24
+ * A row's own `contextWindow` is not that number, and the gap runs in both
25
+ * directions. Under-declared: `deepseek-v4.1-flash` and `kimi-k3.1-pro` accept
26
+ * 1048576 tokens, while the CN document's `maxInputTokens` (the 1M maximum) is
27
+ * clamped to the product document's 300000 default, so a third of the window is
28
+ * thrown away. Over-declared: `hy3` (192000) and `minimax-m3.1-flash` (300000)
29
+ * are refused at 100000, so the harness sends past a hard wall before its
30
+ * compaction threshold — 0.8 of the *declared* window — ever fires, and the
31
+ * compaction request then fails the same way, stranding the session.
32
+ *
33
+ * Each value comes from the gateway's own refusal, which names the ceiling it
34
+ * enforces (`prompt is too long: N tokens > M maximum`), or from a body past
35
+ * the previous bound streaming successfully. Ids absent here keep whatever the
36
+ * catalog row and `DEFAULT_CONTEXT_WINDOWS` resolve to.
37
+ */
38
+ const MEASURED_CONTEXT_WINDOWS = new Map([
39
+ ['deepseek-v4.1-flash', 1_048_576],
40
+ ['kimi-k3.1-pro', 1_048_576],
41
+ ['hy3', 100_000],
42
+ ['minimax-m3.1-flash', 100_000],
43
+ ])
44
+
45
+ /**
46
+ * Static CLI models for the international endpoint, captured 2026-10-20 from
47
+ * the App-channel `/v3/config` document (the 24 ids of its `cli` agent).
48
+ *
49
+ * Same purpose and same discipline as the CN roster: it covers the window
50
+ * before the first successful fetch and an offline start, and it is
51
+ * deliberately *not* a promise about the upstream's current state.
52
+ *
53
+ * The three `x0.00` rows are the models WorkBuddy International currently
54
+ * serves for free (its DeepSeek-V4.1-Flash promotion, alongside Hy4 preview
55
+ * and Hy3). The free flag is a *snapshot*, not a promise: the upstream bakes
56
+ * a promotion's discounted rate into the row, and the live catalog re-derives
57
+ * it against the promotion's own validity window, so an ended promotion
58
+ * drops the "free" claim on its own. The live answer always wins.
59
+ */
60
+ export const FALLBACK_WORKBUDDY_AI_MODELS = [
61
+ { id: 'default-model', name: 'Auto', contextWindow: 176000, maxTokens: 24000, supportsImages: true, reasoning: { supports: false, onlyReasoning: false, canDisableThinking: true }, billing: { free: false } },
62
+ { id: 'fast-model', name: 'Fast', contextWindow: 200000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.34', free: false } },
63
+ { id: 'balanced-model', name: 'Balanced', contextWindow: 256000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.59', free: false } },
64
+ { id: 'primary-model', name: 'Primary', contextWindow: 272000, maxTokens: 72000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x3.31', free: false } },
65
+ { id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 200000, maxTokens: 64000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['high'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.29', free: false } },
66
+ { id: 'hy3', name: 'Hy3', contextWindow: 192000, maxTokens: 64000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high'], defaultEffort: 'high', canDisableThinking: false }, billing: { free: true } },
67
+ { id: 'step-5-preview', name: 'Step-5-Preview', contextWindow: 300000, maxTokens: 64000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high'], defaultEffort: 'high', canDisableThinking: false }, billing: { free: true } },
68
+ { id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 300000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { free: true } },
69
+ { id: 'deepseek-v4.1-flash-sg', name: 'Deepseek-V4.1-Flash', contextWindow: 300000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.03', free: false } },
70
+ { id: 'gpt-6-astra', name: 'GPT-6-Astra', contextWindow: 400000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x6.67', free: false } },
71
+ { id: 'gpt-6.1-sol', name: 'GPT-6.1-Sol', contextWindow: 272000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.33', free: false } },
72
+ { id: 'gpt-6-sol', name: 'GPT-6-Sol', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.33', free: false } },
73
+ { id: 'gpt-6-luna', name: 'GPT-6-Luna', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.07', free: false } },
74
+ { id: 'gpt-5.6-sol', name: 'GPT-5.6-Sol', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x3.47', free: false } },
75
+ { id: 'gpt-5.6-terra', name: 'GPT-5.6-Terra', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.39', free: false } },
76
+ { id: 'gpt-5.6-luna', name: 'GPT-5.6-Luna', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.14', free: false } },
77
+ { id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 1000000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x3.31', free: false } },
78
+ { id: 'gpt-5.4', name: 'GPT-5.4', contextWindow: 272000, maxTokens: 72000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.65', free: false } },
79
+ { id: 'grok-4.7', name: 'Grok-4.7', contextWindow: 200000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.90', free: false } },
80
+ { id: 'gemini-3.8-flash', name: 'Gemini-3.8-Flash', contextWindow: 300000, maxTokens: 65536, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.95', free: false } },
81
+ { id: 'gemini-3.5-flash', name: 'Gemini-3.5-Flash', contextWindow: 1000000, maxTokens: 65536, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.99', free: false } },
82
+ { id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', contextWindow: 300000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.08', free: false } },
83
+ { id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1000000, maxTokens: 48000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.69', free: false } },
84
+ { id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1000000, maxTokens: 48000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['high', 'xhigh'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.79', free: false } },
85
+ { id: 'minimax-m3.1-flash', name: 'MiniMax-M3.1-Flash', contextWindow: 300000, maxTokens: 128000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.08', free: false } },
86
+ { id: 'kimi-k3', name: 'Kimi-K3', contextWindow: 1000000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x1.62', free: false } },
87
+ { id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.52', free: false } },
88
+ { id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 300000, maxTokens: 32000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.77', free: false } },
89
+ ]
90
+
91
+ /**
92
+ * Static CLI models observed on the CN endpoint.
93
+ *
94
+ * The upstream refresh replaces this list at startup; it exists so the provider
95
+ * registers with a usable catalog even while the first fetch is in flight or
96
+ * offline.
97
+ */
98
+ export const FALLBACK_WORKBUDDY_MODELS = [
99
+ { id: 'auto', name: 'Auto', contextWindow: 168_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'high', canDisableThinking: false }, billing: { free: false } },
100
+ { id: 'hy4-preview', name: 'Hy4 preview', contextWindow: 1_000_000, maxTokens: 64_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['high'], defaultEffort: 'high', canDisableThinking: false }, billing: { free: false, rateUnknown: true } },
101
+ { id: 'hy3', name: 'Hy3', contextWindow: 192_000, maxTokens: 64_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'high', canDisableThinking: false }, billing: { free: false, rateUnknown: true } },
102
+ { id: 'hy3-x', name: 'Hy3-X', contextWindow: 192_000, maxTokens: 64_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high'], defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.05', free: false } },
103
+ { id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash', contextWindow: 1_000_000, maxTokens: 128_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.03', badges: ['独家优惠'], free: false } },
104
+ { id: 'glm-5.3', name: 'GLM-5.3', contextWindow: 1_000_000, maxTokens: 48_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: true }, billing: { credits: 'x0.79', free: false } },
105
+ { id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: true }, billing: { credits: 'x0.06', free: false } },
106
+ { id: 'glm-5.2', name: 'GLM-5.2', contextWindow: 1_000_000, maxTokens: 48_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.79', badges: ['夜间折扣'], free: false } },
107
+ { id: 'glm-5.1', name: 'GLM-5.1', contextWindow: 200_000, maxTokens: 48_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.79', free: false } },
108
+ { id: 'glm-5v-turbo', name: 'GLM-5v-Turbo', contextWindow: 200_000, maxTokens: 64_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.71', free: false } },
109
+ { id: 'kimi-k3-1', name: 'Kimi-K3', contextWindow: 1_000_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x1.62', free: false } },
110
+ { id: 'kimi-k2.8-preview', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, supportedEfforts: ['low', 'high', 'max'], defaultEffort: 'high', canDisableThinking: true }, billing: { credits: 'x0.77', free: false } },
111
+ { id: 'kimi-k2.7', name: 'Kimi-K2.7-Code', contextWindow: 256_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.57', free: false } },
112
+ { id: 'kimi-k2.6', name: 'Kimi-K2.6', contextWindow: 256_000, maxTokens: 32_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.52', free: false } },
113
+ { id: 'minimax-m3', name: 'MiniMax-M3', contextWindow: 512_000, maxTokens: 128_000, supportsImages: true, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'medium', canDisableThinking: false }, billing: { credits: 'x0.25', free: false } },
114
+ { id: 'deepseek-v4-pro', name: 'Deepseek-V4-Pro', contextWindow: 1_000_000, maxTokens: 50_000, supportsImages: false, reasoning: { supports: true, onlyReasoning: true, defaultEffort: 'high', canDisableThinking: false }, billing: { credits: 'x0.51', free: false } },
115
+ ]
116
+
117
+ /** The compiled-in roster for a region. */
118
+ export function fallbackFor(region) {
119
+ return region === 'global' ? FALLBACK_WORKBUDDY_AI_MODELS : FALLBACK_WORKBUDDY_MODELS
120
+ }
121
+
122
+ /**
123
+ * Mutable catalog shared by the shim's `/v1/models` and the adapter.
124
+ *
125
+ * Visibility is separate from content. A variant whose app has no credentials
126
+ * must expose *no* models rather than a fallback roster: the DSH model picker
127
+ * drops an empty group, so an empty catalog is exactly how a provider hides
128
+ * without touching registration. Serving the fallback to a signed-out user
129
+ * instead offers models that can only fail.
130
+ */
131
+ export class WorkBuddyCatalog {
132
+ /**
133
+ * @param {object} [options]
134
+ * @param {readonly object[]} [options.initial] The compiled-in roster.
135
+ * @param {string} [options.region] The realm this catalog serves.
136
+ */
137
+ constructor(options = {}) {
138
+ this.region = options.region ?? 'global'
139
+ this.models = [...(options.initial ?? fallbackFor(this.region))]
140
+ this.source = 'fallback'
141
+ this.fetchedAtMs = undefined
142
+ this.lastError = undefined
143
+ this.visible = true
144
+ this.useMaximumContextWindow = false
145
+ this.disabledModelIds = new Set()
146
+ }
147
+
148
+ /** All known models before filtering disabled ones; empty while invisible. */
149
+ all() {
150
+ if (!this.visible) return []
151
+ return this.models.map(model => {
152
+ const current = modelWithCurrentPromotion(model)
153
+ // A measured ceiling outranks both the row and the compiled-in default:
154
+ // it is what the gateway itself reported enforcing for this id.
155
+ const measured = MEASURED_CONTEXT_WINDOWS.get(current.id)
156
+ const base = measured === undefined || measured === current.contextWindow
157
+ ? current
158
+ : { ...current, contextWindow: measured }
159
+ const maximum = base.supportedContextWindows === undefined ? undefined : Math.max(...base.supportedContextWindows)
160
+ return this.useMaximumContextWindow && maximum !== undefined && maximum > base.contextWindow
161
+ ? { ...base, defaultContextWindow: base.defaultContextWindow ?? base.contextWindow, contextWindow: maximum }
162
+ : base
163
+ })
164
+ }
165
+
166
+ /** Current enabled entries; empty while the variant has no usable credential. */
167
+ current() {
168
+ return this.all().filter(model => !this.disabledModelIds.has(model.id))
169
+ }
170
+
171
+ /** Replace the list; callers invalidate their adapter snapshot after this. */
172
+ set(models, source, fetchedAtMs) {
173
+ this.models = models.map(model => ({ ...model }))
174
+ if (source !== undefined) this.source = source
175
+ if (fetchedAtMs !== undefined) this.fetchedAtMs = fetchedAtMs
176
+ }
177
+
178
+ /** Whether this variant's models are exposed at all. */
179
+ isVisible() {
180
+ return this.visible
181
+ }
182
+
183
+ /**
184
+ * Show or hide the whole catalog. Returns whether the value changed, so the
185
+ * caller can skip an invalidation that would re-render an identical list.
186
+ */
187
+ setVisible(visible) {
188
+ if (this.visible === visible) return false
189
+ this.visible = visible
190
+ return true
191
+ }
192
+
193
+ /** Select the largest declared window where the upstream offers one. */
194
+ setUseMaximumContextWindow(useMaximum) {
195
+ if (this.useMaximumContextWindow === useMaximum) return false
196
+ this.useMaximumContextWindow = useMaximum
197
+ return true
198
+ }
199
+
200
+ /** Update the set of disabled model ids. Returns whether the effective set changed. */
201
+ setDisabledModels(disabled) {
202
+ const next = new Set(disabled)
203
+ if (next.size === this.disabledModelIds.size) {
204
+ let same = true
205
+ for (const id of next) {
206
+ if (!this.disabledModelIds.has(id)) {
207
+ same = false
208
+ break
209
+ }
210
+ }
211
+ if (same) return false
212
+ }
213
+ this.disabledModelIds = next
214
+ return true
215
+ }
216
+
217
+ /** Currently disabled model ids as an array. */
218
+ disabledModels() {
219
+ return [...this.disabledModelIds]
220
+ }
221
+
222
+ /** Models to fall back to when the upstream fetch fails; ignores visibility. */
223
+ fallback() {
224
+ return this.models
225
+ }
226
+ }
@@ -0,0 +1,309 @@
1
+ /**
2
+ * The desktop-client identity WorkBuddy's gateway expects.
3
+ *
4
+ * The gateway is UA-gated: it splits requests by User-Agent and refuses the
5
+ * shapes it does not recognise (`deepseek-harness/*` and `python-requests/*`
6
+ * are measured refusals, business code 11128). Two identities matter here, and
7
+ * they are NOT the same:
8
+ *
9
+ * - **Chat / probe** carry the desktop form `WorkBuddy/<v> <product>/<v>
10
+ * CLI/<cli>` — the product token names the app that owns the region's
11
+ * requests: `WorkBuddy` for CN, `WorkBuddy AI` for international.
12
+ * - **The international catalog** (`/v3/config`) is served only to the terse
13
+ * App form `WorkBuddyAI/<v>`. The spaced form is refused with 400/12403.
14
+ *
15
+ * Versions come from the installed App when it can be read, degrade to a
16
+ * per-region saved value, and finally to a compiled-in constant. A CLI version
17
+ * that does not resolve drops the `CLI/…` token instead of inventing one.
18
+ *
19
+ * @module dsh-workbuddy-connect/identity
20
+ */
21
+ import { readFile } from 'node:fs/promises'
22
+ import { homedir } from 'node:os'
23
+ import { join } from 'node:path'
24
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
25
+ import { workbuddyStateDir } from './paths.js'
26
+
27
+ /**
28
+ * Last-resort UA version for the international App.
29
+ *
30
+ * The gateway ignores the version number when splitting the UA (measured:
31
+ * `CLI/1.0.0`, `CLI/99.0.0` and the real version all return the same
32
+ * document), so this constant is a shape requirement rather than a currency
33
+ * claim. It is *not* used to infer anything about model capabilities.
34
+ */
35
+ export const FALLBACK_APP_VERSION = '5.7.6'
36
+
37
+ /**
38
+ * Compiled-in CN fallback for the `WorkBuddy/<v>` tokens.
39
+ *
40
+ * Like the international fallback it is a shape requirement, not a currency
41
+ * claim — the gateway has not been observed to branch on the number.
42
+ */
43
+ export const FALLBACK_CN_APP_VERSION = '5.5.6'
44
+
45
+ /** Basename of the international saved-version cache under the state dir. */
46
+ export const WORKBUDDY_APP_VERSION_FILENAME = '.workbuddy-ai-version.json'
47
+
48
+ /** Basename of the CN saved-version cache under the state dir. */
49
+ export const CN_APP_VERSION_FILENAME = '.workbuddy-app-version.json'
50
+
51
+ /** Where a version came from, for the status card. */
52
+ export const VERSION_SOURCES = ['installed', 'saved', 'fallback']
53
+
54
+ /**
55
+ * Whether a string is safe to interpolate into an HTTP header.
56
+ *
57
+ * Strict on purpose: the value reaches a header, so anything that could split
58
+ * the request (CR, LF) or inject a second UA token must never pass.
59
+ */
60
+ export function validAppVersion(value) {
61
+ return typeof value === 'string' && /^\d{1,6}(?:\.\d{1,6}){1,3}$/u.test(value)
62
+ }
63
+
64
+ /**
65
+ * Whether a value is a CLI version that may reach a header.
66
+ *
67
+ * Tolerates a prerelease suffix (`2.156.0-rc.1`) because the bundled CLI's own
68
+ * metadata uses that spelling; anything with whitespace, CR or LF never passes.
69
+ */
70
+ export function validCliVersion(value) {
71
+ return typeof value === 'string' && /^\d{1,6}(?:\.\d{1,6}){1,3}(?:-[0-9A-Za-z.]+)?$/u.test(value)
72
+ }
73
+
74
+ /** macOS App-bundle roots: system-wide first, then the user's own install. */
75
+ function macAppRoots() {
76
+ return ['/Applications', join(homedir(), 'Applications')]
77
+ }
78
+
79
+ /**
80
+ * Read `CFBundleShortVersionString` out of an `Info.plist`.
81
+ *
82
+ * Parsed as XML rather than grepped, because the plist contains several
83
+ * `<string>` values and a regex would be one unrelated key away from returning
84
+ * the wrong one. A binary plist has no `<dict>` in its bytes and is reported as
85
+ * unreadable rather than guessed at.
86
+ */
87
+ export async function readBundleVersion(plistPath) {
88
+ let text
89
+ try {
90
+ text = await readFile(plistPath, 'utf8')
91
+ } catch {
92
+ return undefined
93
+ }
94
+ const match = /<key>\s*CFBundleShortVersionString\s*<\/key>\s*<string>([^<]*)<\/string>/u.exec(text)
95
+ const version = match?.[1]?.trim()
96
+ return validAppVersion(version) ? version : undefined
97
+ }
98
+
99
+ /** Write a small JSON document atomically; failures are the caller's to ignore. */
100
+ function writeJsonAtomic(path, value) {
101
+ try {
102
+ mkdirSync(join(path, '..'), { recursive: true })
103
+ const tmp = `${path}.tmp`
104
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
105
+ renameSync(tmp, path)
106
+ } catch {
107
+ // Caching a version is best effort: losing it must never fail the request
108
+ // that asked for it.
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The installed international App's version, or undefined when it is not
114
+ * installed (or not readable).
115
+ *
116
+ * Windows and Linux have no verified bundle-metadata location, so this returns
117
+ * undefined there and the saved/fallback value applies instead of guessing a
118
+ * path.
119
+ */
120
+ export async function installedAppVersion() {
121
+ if (process.platform !== 'darwin') return undefined
122
+ for (const root of macAppRoots()) {
123
+ const bundle = join(root, 'WorkBuddy AI.app')
124
+ const version = await readBundleVersion(join(bundle, 'Contents', 'Info.plist'))
125
+ if (version !== undefined) return { version, bundle }
126
+ }
127
+ return undefined
128
+ }
129
+
130
+ /** The installed CN App's version, or undefined. */
131
+ export async function installedCnAppVersion() {
132
+ if (process.platform !== 'darwin') return undefined
133
+ for (const root of macAppRoots()) {
134
+ const bundle = join(root, 'WorkBuddy.app')
135
+ const version = await readBundleVersion(join(bundle, 'Contents', 'Info.plist'))
136
+ if (version !== undefined) return { version, bundle }
137
+ }
138
+ return undefined
139
+ }
140
+
141
+ /**
142
+ * The bundled agent CLI's real version, or undefined when it does not resolve.
143
+ *
144
+ * `cli/package.json` ships a `0.0.0` placeholder in `version` with the real
145
+ * version in `publishConfig.customPackage.version`; a valid non-placeholder
146
+ * `version` wins, otherwise the custom-package value applies, and unreadable or
147
+ * invalid metadata yields undefined (the caller drops the `CLI/…` UA token
148
+ * rather than guessing).
149
+ */
150
+ export async function readCliVersion(bundle) {
151
+ if (bundle === undefined) return undefined
152
+ let document
153
+ try {
154
+ document = JSON.parse(await readFile(join(bundle, 'Contents', 'Resources', 'app.asar.unpacked', 'cli', 'package.json'), 'utf8'))
155
+ } catch {
156
+ return undefined
157
+ }
158
+ if (typeof document !== 'object' || document === null || Array.isArray(document)) return undefined
159
+ const declared = document['version']
160
+ if (validCliVersion(declared) && declared !== '0.0.0') return declared
161
+ const custom = document['publishConfig']?.['customPackage']
162
+ const customVersion = typeof custom === 'object' && custom !== null ? custom['version'] : undefined
163
+ return validCliVersion(customVersion) ? customVersion : undefined
164
+ }
165
+
166
+ /**
167
+ * Resolve the international UA version: installed App → saved value → constant.
168
+ *
169
+ * A version read from the App is written back immediately, so an uninstalled
170
+ * App or an unreadable plist later still has the last real version to fall
171
+ * back on.
172
+ */
173
+ export async function resolveAppVersion(options = {}) {
174
+ const path = options.path ?? join(workbuddyStateDir(), WORKBUDDY_APP_VERSION_FILENAME)
175
+ const installed = await (options.installed ?? installedAppVersion)()
176
+ if (installed !== undefined && validAppVersion(installed.version)) {
177
+ writeJsonAtomic(path, { version: installed.version, bundle: installed.bundle, observedAt: Date.now() })
178
+ return { version: installed.version, source: 'installed', bundle: installed.bundle }
179
+ }
180
+ try {
181
+ const saved = JSON.parse(await readFile(path, 'utf8'))
182
+ if (typeof saved === 'object' && saved !== null && validAppVersion(saved['version'])) {
183
+ return { version: saved['version'], source: 'saved' }
184
+ }
185
+ } catch {
186
+ // Absent or malformed cache: fall through to the compiled-in default.
187
+ }
188
+ return { version: FALLBACK_APP_VERSION, source: 'fallback' }
189
+ }
190
+
191
+ /**
192
+ * Build the App-shaped User-Agent for the international catalog request.
193
+ *
194
+ * `WorkBuddyAI/<version>` with no space is the form measured to reach the App
195
+ * document; the space form is refused with 400/12403.
196
+ */
197
+ export function appUserAgent(version) {
198
+ if (!validAppVersion(version)) throw new Error(`invalid WorkBuddy AI version for User-Agent: ${JSON.stringify(version)}`)
199
+ return `WorkBuddyAI/${version}`
200
+ }
201
+
202
+ /** The resolved identity a chat request presents as. */
203
+ export function fallbackChatIdentity(region) {
204
+ return { clientVersion: region === 'global' ? FALLBACK_APP_VERSION : FALLBACK_CN_APP_VERSION }
205
+ }
206
+
207
+ /**
208
+ * Build the chat User-Agent for one region.
209
+ *
210
+ * Throws on an invalid version rather than interpolating one into a header;
211
+ * `resolveChatIdentity` never produces such an identity, so the throw is a
212
+ * last gate against future call-site mistakes, not an expected path.
213
+ */
214
+ export function chatUserAgent(identity, region) {
215
+ if (!validAppVersion(identity.clientVersion)) {
216
+ throw new Error(`invalid client version for chat User-Agent: ${JSON.stringify(identity.clientVersion)}`)
217
+ }
218
+ if (identity.cliVersion !== undefined && !validCliVersion(identity.cliVersion)) {
219
+ throw new Error(`invalid CLI version for chat User-Agent: ${JSON.stringify(identity.cliVersion)}`)
220
+ }
221
+ const product = region === 'global' ? 'WorkBuddy AI' : 'WorkBuddy'
222
+ const parts = [`WorkBuddy/${identity.clientVersion}`, `${product}/${identity.clientVersion}`]
223
+ if (identity.cliVersion !== undefined) parts.push(`CLI/${identity.cliVersion}`)
224
+ return parts.join(' ')
225
+ }
226
+
227
+ /**
228
+ * How long a resolved chat identity is reused before the install tree is read
229
+ * again.
230
+ *
231
+ * The identity names the client channel the upstream sees, and the desktop app
232
+ * updates on its own schedule — a process that cached the identity forever
233
+ * would keep presenting a version the gateway has already moved past. A short
234
+ * TTL costs one plist read every few minutes and lets an app update take
235
+ * effect without restarting the harness.
236
+ */
237
+ const IDENTITY_TTL_MS = 10 * 60 * 1000
238
+
239
+ const identityCache = new Map()
240
+
241
+ /**
242
+ * Resolve the chat identity for one region: installed App → region's saved
243
+ * value → compiled-in fallback.
244
+ *
245
+ * Never throws — a missing App, an unreadable plist, or a reader that throws
246
+ * outright all degrade to {@link fallbackChatIdentity}. Resolution never blocks
247
+ * a message, and the answer is cached per region so a message does not re-read
248
+ * the install tree.
249
+ */
250
+ export async function resolveChatIdentity(region, options = {}) {
251
+ const injectable = options.installedCn !== undefined
252
+ || options.resolveIntl !== undefined
253
+ || options.cliVersion !== undefined
254
+ || options.cnSavedPath !== undefined
255
+ if (!injectable) {
256
+ const cached = identityCache.get(region)
257
+ if (cached !== undefined && cached.expiresAtMs > Date.now()) return cached.identity
258
+ }
259
+ let identity
260
+ try {
261
+ identity = region === 'global'
262
+ ? await resolveGlobalIdentity(options)
263
+ : await resolveCnIdentity(options)
264
+ } catch {
265
+ // A reader that throws must not block a message and must not pin this
266
+ // degraded answer for the process lifetime.
267
+ return fallbackChatIdentity(region)
268
+ }
269
+ if (!injectable) {
270
+ identityCache.set(region, { identity, expiresAtMs: Date.now() + IDENTITY_TTL_MS })
271
+ }
272
+ return identity
273
+ }
274
+
275
+ /** CN: installed `WorkBuddy.app` → CN saved cache → CN fallback. */
276
+ async function resolveCnIdentity(options) {
277
+ const savedPath = options.cnSavedPath ?? join(workbuddyStateDir(), CN_APP_VERSION_FILENAME)
278
+ const installed = await (options.installedCn ?? installedCnAppVersion)()
279
+ if (installed !== undefined && validAppVersion(installed.version)) {
280
+ const cliVersion = await (options.cliVersion ?? readCliVersion)(installed.bundle)
281
+ const identity = {
282
+ clientVersion: installed.version,
283
+ ...(cliVersion !== undefined && validCliVersion(cliVersion) ? { cliVersion } : {}),
284
+ }
285
+ writeJsonAtomic(savedPath, { version: identity.clientVersion, observedAt: Date.now() })
286
+ return identity
287
+ }
288
+ try {
289
+ const saved = JSON.parse(await readFile(savedPath, 'utf8'))
290
+ if (typeof saved === 'object' && saved !== null && validAppVersion(saved['version'])) {
291
+ return { clientVersion: saved['version'] }
292
+ }
293
+ } catch {
294
+ // Absent or malformed cache: fall through to the compiled-in constant.
295
+ }
296
+ return fallbackChatIdentity('cn')
297
+ }
298
+
299
+ /** International: installed → saved → fallback, plus the CLI token when a bundle exists. */
300
+ async function resolveGlobalIdentity(options) {
301
+ const info = await (options.resolveIntl ?? resolveAppVersion)()
302
+ const clientVersion = validAppVersion(info.version) ? info.version : FALLBACK_APP_VERSION
303
+ let cliVersion
304
+ if (info.bundle !== undefined) {
305
+ const read = await (options.cliVersion ?? readCliVersion)(info.bundle)
306
+ if (read !== undefined && validCliVersion(read)) cliVersion = read
307
+ }
308
+ return { clientVersion, ...cliVersion === undefined ? {} : { cliVersion } }
309
+ }