@aiwayds/dsh-model-sync 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -6,4 +6,8 @@ export declare const inject: string[];
6
6
  export interface ModelSyncService {
7
7
  syncNow(): Promise<string>;
8
8
  }
9
+ /** Default route list — exported for tests that need to iterate the same set
10
+ * the plugin syncs when `managedRoutes` is empty. Not part of the public
11
+ * runtime surface; subject to change without notice. */
12
+ export declare const DEFAULT_ROUTES_LIST: string[];
9
13
  export declare function apply(ctx: Context): void;
package/lib/index.js CHANGED
@@ -18,6 +18,7 @@ import { translateEntries, } from "./translate.js";
18
18
  import { syncToSettings, } from "./writer.js";
19
19
  import { BUILTIN_CATALOG_SNAPSHOT } from "./builtin-catalog-snapshot.js";
20
20
  import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from "./live-catalog.js";
21
+ import { checkRouteCredential } from "./route-credential.js";
21
22
  export const name = 'dsh-model-sync';
22
23
  /** The settings seam this plugin consumes (its own config namespace). */
23
24
  export const inject = ['settings'];
@@ -71,6 +72,10 @@ const DEFAULT_ROUTES = [
71
72
  'minimax-cn',
72
73
  'xiaomi-token-plan-cn',
73
74
  ];
75
+ /** Default route list — exported for tests that need to iterate the same set
76
+ * the plugin syncs when `managedRoutes` is empty. Not part of the public
77
+ * runtime surface; subject to change without notice. */
78
+ export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES;
74
79
  export function apply(ctx) {
75
80
  const scope = ctx.settings.register(OWN_NS, ModelSyncConfig);
76
81
  // -----------------------------------------------------------------------
@@ -148,7 +153,21 @@ export function apply(ctx) {
148
153
  const routes = config.managedRoutes.length > 0
149
154
  ? config.managedRoutes
150
155
  : DEFAULT_ROUTES;
156
+ const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
157
+ const gateCtx = ctx;
151
158
  for (const route of routes) {
159
+ // Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
160
+ // Layer 2 follows its authContextFrom(ctx).env(): launch environment,
161
+ // or process.env when the service is absent. Both miss → skip fetch,
162
+ // translate and settings.mutate, naming the missing ref in the report.
163
+ // deriveKeyRef replicates the web UI's conventional reference name.
164
+ // Known gap: after credential removal, a same-name shell export allows
165
+ // writes, but requests with the seam present still get MISSING_CREDENTIAL.
166
+ const gate = await checkRouteCredential(gateCtx, gateDesc, route);
167
+ if (!gate.ok) {
168
+ lines.push(`${route}: skipped — credential ${gate.ref} not configured`);
169
+ continue;
170
+ }
152
171
  // Fetch from pi.dev — pass force to bypass revalidation throttle (I-5)
153
172
  const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs, store, { force });
154
173
  if (result.error !== undefined && result.entries.length === 0) {
@@ -261,8 +280,10 @@ export function apply(ctx) {
261
280
  const config = scope.get();
262
281
  // Prefer the host's live pi-ai catalog for this round; the frozen
263
282
  // snapshot is only the no-host fallback. Without this, keepBuiltinOnly
264
- // re-emits ids the host's catalog has already dropped.
265
- refreshLiveCatalog(config.managedRoutes.length > 0 ? config.managedRoutes : DEFAULT_ROUTES);
283
+ // re-emits ids the host's catalog has already dropped. Awaiting keeps the
284
+ // `which`/`npm` probes off the host's event loop (they used to block every
285
+ // surface for ~0.2s per round).
286
+ await refreshLiveCatalog(config.managedRoutes.length > 0 ? config.managedRoutes : DEFAULT_ROUTES);
266
287
  if (config.writeMode === 'settings') {
267
288
  return syncSettings(config, force);
268
289
  }
@@ -275,9 +296,15 @@ export function apply(ctx) {
275
296
  };
276
297
  /** Auto rounds log the same report the /model-sync command shows. */
277
298
  const runAuto = () => {
299
+ // A rejected round (service lookups mid-dispose, a refused mutate) must
300
+ // settle here: an unhandled rejection from a timer-driven round would
301
+ // terminate the whole host process, and the auto path has no caller to
302
+ // hand the error to.
278
303
  void syncNow(false).then((report) => {
279
304
  for (const line of report.split('\n'))
280
305
  ctx.logger.info('model-sync: %s', line);
306
+ }, (error) => {
307
+ ctx.logger.warn('model-sync: auto refresh failed: %o', error);
281
308
  });
282
309
  };
283
310
  /** (Re)arm the auto-refresh interval; 0 disarms. */
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wEAAwE;AAExE;;;;;;;;;;;GAWG;AAEH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAWxC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACrD,OAAO,EACL,kBAAkB,EAClB,eAAe,GAEhB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,gBAAgB,GAIjB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EACL,cAAc,GAIf,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAA;AACxE,OAAO,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAA;AAErF,MAAM,CAAC,MAAM,IAAI,GAAG,gBAAgB,CAAA;AAEpC,yEAAyE;AACzE,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,UAAU,CAAC,CAAA;AAElC,6EAA6E;AAC7E,8DAA8D;AAC9D,8EAA8E;AAC9E,qCAAqC;AACrC,MAAM,MAAM,GAAG,YAAY,CAAA;AAE3B,2EAA2E;AAC3E,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/B;;;;OAIG;IACH,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC;IAC/D,gFAAgF;IAChF,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;IACvD,wEAAwE;IACxE,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CA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AW,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAA;IAEpD,OAAO,WAAW;SACf,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;SAC1D,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACX,EAAE,EAAE,CAAC,CAAC,EAAE;QACR,IAAI,EAAE,CAAC,CAAC,EAAE;QACV,GAAG,EAAE,CAAC,CAAC,GAAG;QACV,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,EAAE;QACX,SAAS,EAAE,KAAK;QAChB,KAAK,EAAE,CAAC,MAAM,CAAa;KAC5B,CAAC,CAAC,CAAA;AACP,CAAC;AAED;;GAEG;AACH,SAAS,wBAAwB,CAC/B,IAAoC,EACpC,KAAa;IAEb,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACxC,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,EAAE,SAAgD,CAAA;IAC7E,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,KAAK,CAAwC,CAAA;IACzE,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAA;IAC/B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAA;IAC5C,OAAO,MAAgC,CAAA;AACzC,CAAC"}
@@ -5,8 +5,11 @@ import type { BuiltinModelData } from './translate.ts';
5
5
  * file is unreadable are simply absent from the cache — callers fall back to
6
6
  * the frozen snapshot for those. When no host install is found at all the
7
7
  * cache is cleared and every route falls back.
8
+ *
9
+ * Async on purpose: the host install lookup spawns `which`/`npm`, and this
10
+ * runs on the host's event loop (see the module note). Callers await it.
8
11
  */
9
- export declare function refreshLiveCatalog(routes: readonly string[]): void;
12
+ export declare function refreshLiveCatalog(routes: readonly string[]): Promise<void>;
10
13
  /**
11
14
  * The live builtin data for a route, or undefined when the host install could
12
15
  * not be located or the route file is unreadable — callers fall back to the
@@ -17,43 +17,98 @@
17
17
  // a sibling scope of the same node_modules.
18
18
  // 2. `which dsh` realpath — the installed CLI's own node_modules.
19
19
  // 3. `npm root -g` — dsh's nested node_modules, then the flat layout.
20
- import { execFileSync } from 'node:child_process';
20
+ //
21
+ // The probes run lazily in that order, and asynchronously: the first probe
22
+ // with a working candidate wins, so the common `which dsh` hit never pays the
23
+ // (much slower) `npm root -g` spawn, and no probe blocks the host's event
24
+ // loop. Both properties are load-bearing — this runs on the host's loop 5s
25
+ // after every boot and on every interval round, where the old synchronous
26
+ // `execFileSync` pair froze every surface for ~0.2s per round (measured
27
+ // 2026-09-15; ~0.6s under CPU load).
28
+ import { execFile as execFileCb } from 'node:child_process';
21
29
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
22
30
  import { dirname, join } from 'node:path';
23
31
  const DATA_REL = join('dist', 'providers', 'data');
32
+ /**
33
+ * Subprocess budget for one probe: a hung `which`/`npm` (broken PATH, npm
34
+ * self-update stall) degrades to the next candidate instead of pinning the
35
+ * refresh round forever — the probe is async, so that wait stays off the loop.
36
+ */
37
+ const PROBE_TIMEOUT_MS = 10_000;
24
38
  let cache;
25
- function findPiAiPackageDir() {
26
- const candidates = [];
39
+ /** Run one probe command; resolves its stdout, rejects on spawn failure / non-zero exit / timeout. */
40
+ function runProbe(file, args) {
41
+ return new Promise((resolve, reject) => {
42
+ execFileCb(file, args, { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS }, (error, stdout) => {
43
+ if (error !== null)
44
+ reject(error);
45
+ else
46
+ resolve(stdout);
47
+ });
48
+ });
49
+ }
50
+ /** The real pi-ai install dir when `candidate` holds one (DATA_REL present), else undefined. */
51
+ function resolvePiAiDir(candidate) {
52
+ try {
53
+ const dir = realpathSync(candidate);
54
+ return existsSync(join(dir, DATA_REL)) ? dir : undefined;
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ }
60
+ /** Probe 1: DSH_CLOSURE_DIR override — no subprocess. */
61
+ function closureOverrideCandidates() {
27
62
  const override = process.env.DSH_CLOSURE_DIR;
28
- if (override !== undefined && override !== '') {
29
- try {
30
- candidates.push(join(dirname(realpathSync(override)), '@earendil-works', 'pi-ai'));
31
- }
32
- catch { /* bad override path — fall through to auto-discovery */ }
63
+ if (override === undefined || override === '')
64
+ return [];
65
+ try {
66
+ return [join(dirname(realpathSync(override)), '@earendil-works', 'pi-ai')];
67
+ }
68
+ catch {
69
+ return []; // bad override path — fall through to auto-discovery
33
70
  }
71
+ }
72
+ /** Probe 2: the installed CLI's own node_modules (`which dsh` realpath). */
73
+ async function whichDshCandidates() {
34
74
  try {
35
- const bin = execFileSync('which', ['dsh'], { encoding: 'utf8' }).trim();
36
- if (bin !== '') {
37
- const real = realpathSync(bin);
38
- candidates.push(join(dirname(dirname(real)), 'node_modules', '@earendil-works', 'pi-ai'));
39
- }
75
+ const bin = (await runProbe('which', ['dsh'])).trim();
76
+ if (bin === '')
77
+ return [];
78
+ return [join(dirname(dirname(realpathSync(bin))), 'node_modules', '@earendil-works', 'pi-ai')];
79
+ }
80
+ catch {
81
+ return []; // dsh not on PATH, or the probe failed
40
82
  }
41
- catch { /* dsh not on PATH */ }
83
+ }
84
+ /** Probe 3: `npm root -g` — dsh's nested node_modules, then the flat layout. */
85
+ async function npmRootCandidates() {
42
86
  try {
43
- const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8' }).trim();
44
- if (root !== '') {
45
- candidates.push(join(root, '@deepseek-ai', 'dsh', 'node_modules', '@earendil-works', 'pi-ai'));
46
- candidates.push(join(root, '@earendil-works', 'pi-ai'));
47
- }
87
+ const root = (await runProbe('npm', ['root', '-g'])).trim();
88
+ if (root === '')
89
+ return [];
90
+ return [
91
+ join(root, '@deepseek-ai', 'dsh', 'node_modules', '@earendil-works', 'pi-ai'),
92
+ join(root, '@earendil-works', 'pi-ai'),
93
+ ];
48
94
  }
49
- catch { /* npm unavailable */ }
50
- for (const candidate of candidates) {
51
- try {
52
- const dir = realpathSync(candidate);
53
- if (existsSync(join(dir, DATA_REL)))
95
+ catch {
96
+ return []; // npm unavailable
97
+ }
98
+ }
99
+ /** Locate the host's @earendil-works/pi-ai install: ordered probes, first working candidate wins. */
100
+ async function findPiAiPackageDir() {
101
+ const probes = [
102
+ closureOverrideCandidates,
103
+ whichDshCandidates,
104
+ npmRootCandidates,
105
+ ];
106
+ for (const probe of probes) {
107
+ for (const candidate of await probe()) {
108
+ const dir = resolvePiAiDir(candidate);
109
+ if (dir !== undefined)
54
110
  return dir;
55
111
  }
56
- catch { /* candidate missing — try next */ }
57
112
  }
58
113
  return undefined;
59
114
  }
@@ -78,9 +133,12 @@ function loadRoute(dir, route) {
78
133
  * file is unreadable are simply absent from the cache — callers fall back to
79
134
  * the frozen snapshot for those. When no host install is found at all the
80
135
  * cache is cleared and every route falls back.
136
+ *
137
+ * Async on purpose: the host install lookup spawns `which`/`npm`, and this
138
+ * runs on the host's event loop (see the module note). Callers await it.
81
139
  */
82
- export function refreshLiveCatalog(routes) {
83
- const dir = findPiAiPackageDir();
140
+ export async function refreshLiveCatalog(routes) {
141
+ const dir = await findPiAiPackageDir();
84
142
  if (dir === undefined) {
85
143
  cache = undefined;
86
144
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"live-catalog.js","sourceRoot":"","sources":["../src/live-catalog.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8BAA8B;AAC9B,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;AAC9E,0EAA0E;AAC1E,6EAA6E;AAC7E,4EAA4E;AAC5E,2EAA2E;AAC3E,6EAA6E;AAC7E,wCAAwC;AACxC,EAAE;AACF,gEAAgE;AAChE,sEAAsE;AACtE,6EAA6E;A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C,KAAK,CAAC,CAAA;AAClC,CAAC"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The credentials seam surface this module needs. The seam is an optional
3
+ * peer (`@deepseek-ai/dsh-credentials`), so the gate must tolerate its
4
+ * absence — `checkRouteCredential` falls through to the launch-environment
5
+ * check in that case.
6
+ *
7
+ * The actual `CredentialProvider.describe` takes a branded `CredentialRef`
8
+ * (`Branded<'CredentialRef'>` from `@deepseek-ai/dsh-brand`), but the brand is
9
+ * a structural type only — every branded string is also a plain `string` at
10
+ * runtime. Declaring the parameter as `string` here keeps the local interface
11
+ * dependency-free (we don't import the brand module just to name one
12
+ * parameter) while remaining assignable from any value the seam emits:
13
+ * `credentialRef(value)` returns `value as CredentialRef`, which is the same
14
+ * `value` retyped, so passing it to `describe(ref: string)` works under both
15
+ * the host and any plain-JS seam test double.
16
+ */
17
+ export interface CredentialsSeam {
18
+ describe(ref: string): Promise<{
19
+ configured: boolean;
20
+ }>;
21
+ }
22
+ /**
23
+ * The launch-environment snapshot surface (`@deepseek-ai/dsh-launch-environment`).
24
+ * Cordis `ctx.get` returns undefined for an unregistered service; it does not
25
+ * synthesize a snapshot. This module supplies the `process.env` fallback.
26
+ */
27
+ export interface LaunchEnvironmentSnapshot {
28
+ get(name: string): {
29
+ value: string;
30
+ } | undefined;
31
+ }
32
+ /**
33
+ * The subset of `Context` this module reads. Both services are optional:
34
+ * `credentials` is an optional peer and may be absent, `launchEnvironment` is
35
+ * provided by the launcher but the helper synthesizes a process-env snapshot
36
+ * when it is not.
37
+ */
38
+ export interface RouteCredentialContext {
39
+ get(name: 'credentials'): CredentialsSeam | undefined;
40
+ get(name: 'launchEnvironment'): LaunchEnvironmentSnapshot | undefined;
41
+ get(name: string): unknown;
42
+ }
43
+ /**
44
+ * The settings descriptor shape this module needs (matches writer.ts's
45
+ * `SettingsDescriptor`). Only `user.providers.<route>.apiKeyEnv` is read —
46
+ * the value the user explicitly declared in settings.yaml.
47
+ */
48
+ export interface RouteCredentialSettingsDescriptor {
49
+ user?: Record<string, unknown>;
50
+ }
51
+ /**
52
+ * Outcome of one route's credential check.
53
+ */
54
+ export interface RouteCredentialCheck {
55
+ /** True when either source confirms the route is configured. */
56
+ ok: boolean;
57
+ /**
58
+ * The credential reference name consulted (e.g. `OPENCODE_API_KEY`,
59
+ * `MINIMAX_CN_API_KEY`). Always present, even when `ok` is false, so the
60
+ * report can name what is missing.
61
+ */
62
+ ref: string;
63
+ /**
64
+ * Which source confirmed the route, when `ok` is true:
65
+ * - 'credentials' — the seam's `describe()` returned `configured: true`
66
+ * - 'env' — the launch-environment snapshot (process env / .env) had a
67
+ * non-empty value, with no seam hit
68
+ */
69
+ via?: 'credentials' | 'env';
70
+ }
71
+ /**
72
+ * Derive the conventional credential reference for a provider route. This is
73
+ * a byte-for-byte replica of `deriveKeyRef` from the dsh web UI's settings
74
+ * models package (see ~/github/deepseek-harness/packages/client/ui-
75
+ * settings-models/src/client/store.ts:111-113). The web UI uses it as the
76
+ * default name a typed key stores under; we use it as the fallback when the
77
+ * user has not declared an explicit `apiKeyEnv` in their provider profile.
78
+ *
79
+ * @param provider - provider route id (e.g. `opencode-go`, `minimax-cn`).
80
+ * @returns the derived reference name (e.g. `OPENCODE_GO_API_KEY`).
81
+ */
82
+ export declare function deriveKeyRef(provider: string): string;
83
+ /**
84
+ * Read the explicit `apiKeyEnv` the user declared for a route in the
85
+ * `llm-pi-ai` provider profile. Returns the trimmed string when present and
86
+ * non-empty, otherwise `undefined` (callers fall through to `deriveKeyRef`).
87
+ *
88
+ * @param desc - the settings descriptor (may be undefined when the host has
89
+ * no `llm-pi-ai` namespace registered yet).
90
+ * @param route - the provider route id.
91
+ */
92
+ export declare function getRawUserApiKeyEnv(desc: RouteCredentialSettingsDescriptor | undefined, route: string): string | undefined;
93
+ /**
94
+ * Run the per-route credential gate. Returns `{ ok, ref, via? }` where `ok`
95
+ * is true iff either source confirms the route is configured.
96
+ *
97
+ * Resolution layers (not an exact request-time credential resolver):
98
+ * 1. `credentials.describe(ref).configured === true` when the seam is
99
+ * provided AND the ref is a valid `CredentialRef` (POSIX identifier).
100
+ * The strict pattern check matters: a profile removed during logout leaves
101
+ * no `apiKeyEnv`, so we always derive; and a stray ref that does not match
102
+ * the brand grammar (e.g. the seam `resolve` would throw) must read as
103
+ * "not configured" rather than crash the round.
104
+ * 2. `launchEnvironment.get(ref).value` returns a non-empty string, following
105
+ * llm-pi-ai's `authContextFrom(ctx).env()` semantics. Like
106
+ * `launchEnvironmentOf`, we synthesize a `process.env` snapshot when the
107
+ * launch-environment service is absent, even without a launcher.
108
+ *
109
+ * Both misses → `ok: false`. The gate then skips fetch / translate /
110
+ * `settings.mutate` for the route and emits a report line naming the ref.
111
+ *
112
+ * @param ctx - the plugin's cordis context.
113
+ * @param desc - the resolved `llm-pi-ai` settings descriptor (may be undefined
114
+ * when the host has not registered the namespace yet — same shape as the
115
+ * descriptor the writer already reads).
116
+ * @param route - the provider route id being checked.
117
+ */
118
+ export declare function checkRouteCredential(ctx: RouteCredentialContext, desc: RouteCredentialSettingsDescriptor | undefined, route: string): Promise<RouteCredentialCheck>;
@@ -0,0 +1,127 @@
1
+ // Login gate for the settings-mode sync: skip routes whose credential
2
+ // reference is not configured, so a logged-out profile never silently gets
3
+ // its `models` rewritten by the sync.
4
+ //
5
+ // Layer 1 follows llm-pi-ai's `resolveApiKey`: prefer the credentials seam.
6
+ // Layer 2 follows the same package's `authContextFrom(ctx).env()` semantics:
7
+ // consult the launch environment, or process.env when that service is absent.
8
+ // A hit on either allows sync; only when BOTH miss do we skip the route.
9
+ // Known gap: after credential removal, a same-name shell export still allows
10
+ // writes, but requests with the seam present still fail with MISSING_CREDENTIAL.
11
+ //
12
+ // deriveKeyRef replicates the dsh web UI's same helper at
13
+ // packages/client/ui-settings-models/src/client/store.ts:111-113 (uppercase +
14
+ // collapse non-alphanumerics to `_` + `_API_KEY` suffix). The web UI uses it
15
+ // to mint the reference name a typed key stores under; we use it as the
16
+ // fallback when a route has no explicit `apiKeyEnv` (shell-environment users
17
+ // who `export OPENCODE_API_KEY=…` without going through the UI). The two
18
+ // conversions are byte-for-byte identical, so a value the web UI wrote
19
+ // resolves through the same name here.
20
+ /**
21
+ * Derive the conventional credential reference for a provider route. This is
22
+ * a byte-for-byte replica of `deriveKeyRef` from the dsh web UI's settings
23
+ * models package (see ~/github/deepseek-harness/packages/client/ui-
24
+ * settings-models/src/client/store.ts:111-113). The web UI uses it as the
25
+ * default name a typed key stores under; we use it as the fallback when the
26
+ * user has not declared an explicit `apiKeyEnv` in their provider profile.
27
+ *
28
+ * @param provider - provider route id (e.g. `opencode-go`, `minimax-cn`).
29
+ * @returns the derived reference name (e.g. `OPENCODE_GO_API_KEY`).
30
+ */
31
+ export function deriveKeyRef(provider) {
32
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`;
33
+ }
34
+ /**
35
+ * Read the explicit `apiKeyEnv` the user declared for a route in the
36
+ * `llm-pi-ai` provider profile. Returns the trimmed string when present and
37
+ * non-empty, otherwise `undefined` (callers fall through to `deriveKeyRef`).
38
+ *
39
+ * @param desc - the settings descriptor (may be undefined when the host has
40
+ * no `llm-pi-ai` namespace registered yet).
41
+ * @param route - the provider route id.
42
+ */
43
+ export function getRawUserApiKeyEnv(desc, route) {
44
+ if (desc === undefined)
45
+ return undefined;
46
+ const providers = desc.user?.providers;
47
+ if (providers === undefined)
48
+ return undefined;
49
+ const routeData = providers[route];
50
+ if (routeData === undefined)
51
+ return undefined;
52
+ const raw = routeData.apiKeyEnv;
53
+ if (typeof raw !== 'string')
54
+ return undefined;
55
+ const trimmed = raw.trim();
56
+ return trimmed.length > 0 ? trimmed : undefined;
57
+ }
58
+ /**
59
+ * Run the per-route credential gate. Returns `{ ok, ref, via? }` where `ok`
60
+ * is true iff either source confirms the route is configured.
61
+ *
62
+ * Resolution layers (not an exact request-time credential resolver):
63
+ * 1. `credentials.describe(ref).configured === true` when the seam is
64
+ * provided AND the ref is a valid `CredentialRef` (POSIX identifier).
65
+ * The strict pattern check matters: a profile removed during logout leaves
66
+ * no `apiKeyEnv`, so we always derive; and a stray ref that does not match
67
+ * the brand grammar (e.g. the seam `resolve` would throw) must read as
68
+ * "not configured" rather than crash the round.
69
+ * 2. `launchEnvironment.get(ref).value` returns a non-empty string, following
70
+ * llm-pi-ai's `authContextFrom(ctx).env()` semantics. Like
71
+ * `launchEnvironmentOf`, we synthesize a `process.env` snapshot when the
72
+ * launch-environment service is absent, even without a launcher.
73
+ *
74
+ * Both misses → `ok: false`. The gate then skips fetch / translate /
75
+ * `settings.mutate` for the route and emits a report line naming the ref.
76
+ *
77
+ * @param ctx - the plugin's cordis context.
78
+ * @param desc - the resolved `llm-pi-ai` settings descriptor (may be undefined
79
+ * when the host has not registered the namespace yet — same shape as the
80
+ * descriptor the writer already reads).
81
+ * @param route - the provider route id being checked.
82
+ */
83
+ export async function checkRouteCredential(ctx, desc, route) {
84
+ // 1. The user-declared ref (when present) wins over the derived one. A
85
+ // profile that names its own ref is the authoritative choice; the
86
+ // derivation is only a fallback for shell-environment users.
87
+ const declared = getRawUserApiKeyEnv(desc, route);
88
+ const ref = declared ?? deriveKeyRef(route);
89
+ // 2. Credentials seam first. The seam is optional: skip the whole branch
90
+ // when the host did not register it. Inside the branch, only consult the
91
+ // seam when the ref matches the brand's POSIX-identifier grammar — the
92
+ // seam's own `describe` throws on an invalid ref, which would crash the
93
+ // sync round. Mirroring `isCredentialRefName` from
94
+ // @deepseek-ai/dsh-credentials keeps the gate quiet on malformed input.
95
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
96
+ if (REF_PATTERN.test(ref)) {
97
+ const credentials = ctx.get('credentials');
98
+ if (credentials !== undefined) {
99
+ try {
100
+ const info = await credentials.describe(ref);
101
+ if (info.configured) {
102
+ return { ok: true, ref, via: 'credentials' };
103
+ }
104
+ }
105
+ catch {
106
+ // Treat any throw from describe (provider missing, seam half-broken)
107
+ // as "not configured here" and fall through to the env check.
108
+ }
109
+ }
110
+ }
111
+ // 3. Cordis `ctx.get` returns undefined for absent services, without throwing
112
+ // or falling through to process.env. Reproduce `launchEnvironmentOf`'s
113
+ // fallback locally, without importing the optional peer. A provided
114
+ // snapshot remains authoritative; empty values do not count as configured.
115
+ const snapshot = ctx.get('launchEnvironment') ?? {
116
+ get(name) {
117
+ const value = process.env[name];
118
+ return value !== undefined && value !== '' ? { value, source: 'process' } : undefined;
119
+ },
120
+ };
121
+ const entry = snapshot.get(ref);
122
+ if (entry !== undefined && typeof entry.value === 'string' && entry.value.length > 0) {
123
+ return { ok: true, ref, via: 'env' };
124
+ }
125
+ return { ok: false, ref };
126
+ }
127
+ //# sourceMappingURL=route-credential.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-credential.js","sourceRoot":"","sources":["../src/route-credential.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,2EAA2E;AAC3E,sCAAsC;AACtC,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,6EAA6E;AAC7E,iFAAiF;AACjF,EAAE;AACF,0DAA0D;AAC1D,8EAA8E;AAC9E,6EAA6E;AAC7E,wEAAwE;AACxE,6EAA6E;AAC7E,yEAAyE;AACzE,uEAAuE;AACvE,uCAAuC;AAyEvC;;;;;;;;;;GAUG;AACH,MAAM,UAAU,YAAY,CAAC,QAAgB;IAC3C,OAAO,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC,UAAU,CAAA;AACxE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,IAAmD,EACnD,KAAa;IAEb,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACxC,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,EAAE,SAAgD,CAAA;IAC7E,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC7C,MAAM,SAAS,GAAG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ACP,qEAAqE;gBACrE,8DAA8D;YAChE,CAAC;QACH,CAAC;IACH,CAAC;IAED,8EAA8E;IAC9E,0EAA0E;IAC1E,uEAAuE;IACvE,8EAA8E;IAC9E,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,IAAI;QAC/C,GAAG,CAAC,IAAY;YACd,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;YAC/B,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;QACvF,CAAC;KACF,CAAA;IACD,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,CAAA;IACtC,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAA;AAC3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-model-sync",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "dsh plugin: keep llm-pi-ai provider routes' model lists in step with the pi.dev gateway, written through the official settings seam",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -31,13 +31,15 @@
31
31
  "build": "tsc -p tsconfig.json",
32
32
  "check": "tsc --noEmit -p tsconfig.json",
33
33
  "pretest": "tsc -p tsconfig.json",
34
- "test": "node --test test/live-catalog.test.mjs test/diff.test.mjs test/translate.test.mjs test/writer.test.mjs test/writer-overrides.test.mjs test/remote-catalog.test.mjs test/serviceability.test.mjs test/command.test.mjs test/real-cordis.test.mjs",
34
+ "test": "node --test test/live-catalog.test.mjs test/diff.test.mjs test/translate.test.mjs test/writer.test.mjs test/writer-overrides.test.mjs test/remote-catalog.test.mjs test/serviceability.test.mjs test/command.test.mjs test/real-cordis.test.mjs test/route-credential.test.mjs",
35
35
  "smoke": "node scripts/smoke-boot.mjs"
36
36
  },
37
37
  "dependencies": {},
38
38
  "peerDependencies": {
39
39
  "@deepseek-ai/cordis": "^4.0.2",
40
40
  "@deepseek-ai/dsh-commands": ">=0.1.5-rc.2",
41
+ "@deepseek-ai/dsh-credentials": ">=0.1.5-rc.2",
42
+ "@deepseek-ai/dsh-launch-environment": ">=0.1.5-rc.2",
41
43
  "@deepseek-ai/dsh-settings": ">=0.1.5-rc.2",
42
44
  "@deepseek-ai/schemastery": "^3.18.2"
43
45
  },
@@ -48,6 +50,12 @@
48
50
  "@deepseek-ai/dsh-commands": {
49
51
  "optional": true
50
52
  },
53
+ "@deepseek-ai/dsh-credentials": {
54
+ "optional": true
55
+ },
56
+ "@deepseek-ai/dsh-launch-environment": {
57
+ "optional": true
58
+ },
51
59
  "@deepseek-ai/dsh-settings": {
52
60
  "optional": true
53
61
  },
@@ -62,7 +70,9 @@
62
70
  "@deepseek-ai/dsh-attachment": "0.1.5-rc.2",
63
71
  "@deepseek-ai/dsh-brand": "0.1.5-rc.2",
64
72
  "@deepseek-ai/dsh-commands": "0.1.5-rc.2",
73
+ "@deepseek-ai/dsh-credentials": "0.1.5-rc.2",
65
74
  "@deepseek-ai/dsh-invariants": "0.1.5-rc.2",
75
+ "@deepseek-ai/dsh-launch-environment": "0.1.5-rc.2",
66
76
  "@deepseek-ai/dsh-llm": "0.1.5-rc.2",
67
77
  "@deepseek-ai/dsh-scope": "0.1.5-rc.2",
68
78
  "@deepseek-ai/dsh-session": "0.1.5-rc.2",
package/src/index.ts CHANGED
@@ -44,6 +44,7 @@ import {
44
44
  } from './writer.ts'
45
45
  import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
46
46
  import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from './live-catalog.ts'
47
+ import { checkRouteCredential, type RouteCredentialContext } from './route-credential.ts'
47
48
 
48
49
  export const name = 'dsh-model-sync'
49
50
 
@@ -132,6 +133,11 @@ const DEFAULT_ROUTES = [
132
133
  'xiaomi-token-plan-cn',
133
134
  ]
134
135
 
136
+ /** Default route list — exported for tests that need to iterate the same set
137
+ * the plugin syncs when `managedRoutes` is empty. Not part of the public
138
+ * runtime surface; subject to change without notice. */
139
+ export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES
140
+
135
141
  export function apply(ctx: Context): void {
136
142
  const scope = ctx.settings.register(OWN_NS, ModelSyncConfig)
137
143
 
@@ -217,7 +223,22 @@ export function apply(ctx: Context): void {
217
223
  ? config.managedRoutes
218
224
  : DEFAULT_ROUTES
219
225
 
226
+ const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
227
+ const gateCtx = ctx as RouteCredentialContext
220
228
  for (const route of routes) {
229
+ // Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
230
+ // Layer 2 follows its authContextFrom(ctx).env(): launch environment,
231
+ // or process.env when the service is absent. Both miss → skip fetch,
232
+ // translate and settings.mutate, naming the missing ref in the report.
233
+ // deriveKeyRef replicates the web UI's conventional reference name.
234
+ // Known gap: after credential removal, a same-name shell export allows
235
+ // writes, but requests with the seam present still get MISSING_CREDENTIAL.
236
+ const gate = await checkRouteCredential(gateCtx, gateDesc, route)
237
+ if (!gate.ok) {
238
+ lines.push(`${route}: skipped — credential ${gate.ref} not configured`)
239
+ continue
240
+ }
241
+
221
242
  // Fetch from pi.dev — pass force to bypass revalidation throttle (I-5)
222
243
  const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs, store, { force })
223
244
 
@@ -348,8 +369,10 @@ export function apply(ctx: Context): void {
348
369
 
349
370
  // Prefer the host's live pi-ai catalog for this round; the frozen
350
371
  // snapshot is only the no-host fallback. Without this, keepBuiltinOnly
351
- // re-emits ids the host's catalog has already dropped.
352
- refreshLiveCatalog(config.managedRoutes.length > 0 ? config.managedRoutes : DEFAULT_ROUTES)
372
+ // re-emits ids the host's catalog has already dropped. Awaiting keeps the
373
+ // `which`/`npm` probes off the host's event loop (they used to block every
374
+ // surface for ~0.2s per round).
375
+ await refreshLiveCatalog(config.managedRoutes.length > 0 ? config.managedRoutes : DEFAULT_ROUTES)
353
376
 
354
377
  if (config.writeMode === 'settings') {
355
378
  return syncSettings(config, force)
@@ -365,9 +388,18 @@ export function apply(ctx: Context): void {
365
388
 
366
389
  /** Auto rounds log the same report the /model-sync command shows. */
367
390
  const runAuto = (): void => {
368
- void syncNow(false).then((report) => {
369
- for (const line of report.split('\n')) ctx.logger.info('model-sync: %s', line)
370
- })
391
+ // A rejected round (service lookups mid-dispose, a refused mutate) must
392
+ // settle here: an unhandled rejection from a timer-driven round would
393
+ // terminate the whole host process, and the auto path has no caller to
394
+ // hand the error to.
395
+ void syncNow(false).then(
396
+ (report) => {
397
+ for (const line of report.split('\n')) ctx.logger.info('model-sync: %s', line)
398
+ },
399
+ (error: unknown) => {
400
+ ctx.logger.warn('model-sync: auto refresh failed: %o', error)
401
+ },
402
+ )
371
403
  }
372
404
 
373
405
  /** (Re)arm the auto-refresh interval; 0 disarms. */
@@ -17,14 +17,29 @@
17
17
  // a sibling scope of the same node_modules.
18
18
  // 2. `which dsh` realpath — the installed CLI's own node_modules.
19
19
  // 3. `npm root -g` — dsh's nested node_modules, then the flat layout.
20
+ //
21
+ // The probes run lazily in that order, and asynchronously: the first probe
22
+ // with a working candidate wins, so the common `which dsh` hit never pays the
23
+ // (much slower) `npm root -g` spawn, and no probe blocks the host's event
24
+ // loop. Both properties are load-bearing — this runs on the host's loop 5s
25
+ // after every boot and on every interval round, where the old synchronous
26
+ // `execFileSync` pair froze every surface for ~0.2s per round (measured
27
+ // 2026-09-15; ~0.6s under CPU load).
20
28
 
21
- import { execFileSync } from 'node:child_process'
29
+ import { execFile as execFileCb } from 'node:child_process'
22
30
  import { existsSync, readFileSync, realpathSync } from 'node:fs'
23
31
  import { dirname, join } from 'node:path'
24
32
  import type { BuiltinModelData } from './translate.ts'
25
33
 
26
34
  const DATA_REL = join('dist', 'providers', 'data')
27
35
 
36
+ /**
37
+ * Subprocess budget for one probe: a hung `which`/`npm` (broken PATH, npm
38
+ * self-update stall) degrades to the next candidate instead of pinning the
39
+ * refresh round forever — the probe is async, so that wait stays off the loop.
40
+ */
41
+ const PROBE_TIMEOUT_MS = 10_000
42
+
28
43
  interface CatalogCache {
29
44
  dir: string
30
45
  byRoute: Map<string, BuiltinModelData[]>
@@ -32,33 +47,74 @@ interface CatalogCache {
32
47
 
33
48
  let cache: CatalogCache | undefined
34
49
 
35
- function findPiAiPackageDir(): string | undefined {
36
- const candidates: string[] = []
50
+ /** Run one probe command; resolves its stdout, rejects on spawn failure / non-zero exit / timeout. */
51
+ function runProbe(file: string, args: readonly string[]): Promise<string> {
52
+ return new Promise((resolve, reject) => {
53
+ execFileCb(file, args, { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS }, (error, stdout) => {
54
+ if (error !== null) reject(error)
55
+ else resolve(stdout)
56
+ })
57
+ })
58
+ }
59
+
60
+ /** The real pi-ai install dir when `candidate` holds one (DATA_REL present), else undefined. */
61
+ function resolvePiAiDir(candidate: string): string | undefined {
62
+ try {
63
+ const dir = realpathSync(candidate)
64
+ return existsSync(join(dir, DATA_REL)) ? dir : undefined
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ /** Probe 1: DSH_CLOSURE_DIR override — no subprocess. */
71
+ function closureOverrideCandidates(): string[] {
37
72
  const override = process.env.DSH_CLOSURE_DIR
38
- if (override !== undefined && override !== '') {
39
- try {
40
- candidates.push(join(dirname(realpathSync(override)), '@earendil-works', 'pi-ai'))
41
- } catch { /* bad override path — fall through to auto-discovery */ }
73
+ if (override === undefined || override === '') return []
74
+ try {
75
+ return [join(dirname(realpathSync(override)), '@earendil-works', 'pi-ai')]
76
+ } catch {
77
+ return [] // bad override path — fall through to auto-discovery
42
78
  }
79
+ }
80
+
81
+ /** Probe 2: the installed CLI's own node_modules (`which dsh` realpath). */
82
+ async function whichDshCandidates(): Promise<string[]> {
43
83
  try {
44
- const bin = execFileSync('which', ['dsh'], { encoding: 'utf8' }).trim()
45
- if (bin !== '') {
46
- const real = realpathSync(bin)
47
- candidates.push(join(dirname(dirname(real)), 'node_modules', '@earendil-works', 'pi-ai'))
48
- }
49
- } catch { /* dsh not on PATH */ }
84
+ const bin = (await runProbe('which', ['dsh'])).trim()
85
+ if (bin === '') return []
86
+ return [join(dirname(dirname(realpathSync(bin))), 'node_modules', '@earendil-works', 'pi-ai')]
87
+ } catch {
88
+ return [] // dsh not on PATH, or the probe failed
89
+ }
90
+ }
91
+
92
+ /** Probe 3: `npm root -g` — dsh's nested node_modules, then the flat layout. */
93
+ async function npmRootCandidates(): Promise<string[]> {
50
94
  try {
51
- const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8' }).trim()
52
- if (root !== '') {
53
- candidates.push(join(root, '@deepseek-ai', 'dsh', 'node_modules', '@earendil-works', 'pi-ai'))
54
- candidates.push(join(root, '@earendil-works', 'pi-ai'))
95
+ const root = (await runProbe('npm', ['root', '-g'])).trim()
96
+ if (root === '') return []
97
+ return [
98
+ join(root, '@deepseek-ai', 'dsh', 'node_modules', '@earendil-works', 'pi-ai'),
99
+ join(root, '@earendil-works', 'pi-ai'),
100
+ ]
101
+ } catch {
102
+ return [] // npm unavailable
103
+ }
104
+ }
105
+
106
+ /** Locate the host's @earendil-works/pi-ai install: ordered probes, first working candidate wins. */
107
+ async function findPiAiPackageDir(): Promise<string | undefined> {
108
+ const probes: ReadonlyArray<() => string[] | Promise<string[]>> = [
109
+ closureOverrideCandidates,
110
+ whichDshCandidates,
111
+ npmRootCandidates,
112
+ ]
113
+ for (const probe of probes) {
114
+ for (const candidate of await probe()) {
115
+ const dir = resolvePiAiDir(candidate)
116
+ if (dir !== undefined) return dir
55
117
  }
56
- } catch { /* npm unavailable */ }
57
- for (const candidate of candidates) {
58
- try {
59
- const dir = realpathSync(candidate)
60
- if (existsSync(join(dir, DATA_REL))) return dir
61
- } catch { /* candidate missing — try next */ }
62
118
  }
63
119
  return undefined
64
120
  }
@@ -86,9 +142,12 @@ function loadRoute(dir: string, route: string): BuiltinModelData[] {
86
142
  * file is unreadable are simply absent from the cache — callers fall back to
87
143
  * the frozen snapshot for those. When no host install is found at all the
88
144
  * cache is cleared and every route falls back.
145
+ *
146
+ * Async on purpose: the host install lookup spawns `which`/`npm`, and this
147
+ * runs on the host's event loop (see the module note). Callers await it.
89
148
  */
90
- export function refreshLiveCatalog(routes: readonly string[]): void {
91
- const dir = findPiAiPackageDir()
149
+ export async function refreshLiveCatalog(routes: readonly string[]): Promise<void> {
150
+ const dir = await findPiAiPackageDir()
92
151
  if (dir === undefined) {
93
152
  cache = undefined
94
153
  return
@@ -0,0 +1,205 @@
1
+ // Login gate for the settings-mode sync: skip routes whose credential
2
+ // reference is not configured, so a logged-out profile never silently gets
3
+ // its `models` rewritten by the sync.
4
+ //
5
+ // Layer 1 follows llm-pi-ai's `resolveApiKey`: prefer the credentials seam.
6
+ // Layer 2 follows the same package's `authContextFrom(ctx).env()` semantics:
7
+ // consult the launch environment, or process.env when that service is absent.
8
+ // A hit on either allows sync; only when BOTH miss do we skip the route.
9
+ // Known gap: after credential removal, a same-name shell export still allows
10
+ // writes, but requests with the seam present still fail with MISSING_CREDENTIAL.
11
+ //
12
+ // deriveKeyRef replicates the dsh web UI's same helper at
13
+ // packages/client/ui-settings-models/src/client/store.ts:111-113 (uppercase +
14
+ // collapse non-alphanumerics to `_` + `_API_KEY` suffix). The web UI uses it
15
+ // to mint the reference name a typed key stores under; we use it as the
16
+ // fallback when a route has no explicit `apiKeyEnv` (shell-environment users
17
+ // who `export OPENCODE_API_KEY=…` without going through the UI). The two
18
+ // conversions are byte-for-byte identical, so a value the web UI wrote
19
+ // resolves through the same name here.
20
+
21
+ /**
22
+ * The credentials seam surface this module needs. The seam is an optional
23
+ * peer (`@deepseek-ai/dsh-credentials`), so the gate must tolerate its
24
+ * absence — `checkRouteCredential` falls through to the launch-environment
25
+ * check in that case.
26
+ *
27
+ * The actual `CredentialProvider.describe` takes a branded `CredentialRef`
28
+ * (`Branded<'CredentialRef'>` from `@deepseek-ai/dsh-brand`), but the brand is
29
+ * a structural type only — every branded string is also a plain `string` at
30
+ * runtime. Declaring the parameter as `string` here keeps the local interface
31
+ * dependency-free (we don't import the brand module just to name one
32
+ * parameter) while remaining assignable from any value the seam emits:
33
+ * `credentialRef(value)` returns `value as CredentialRef`, which is the same
34
+ * `value` retyped, so passing it to `describe(ref: string)` works under both
35
+ * the host and any plain-JS seam test double.
36
+ */
37
+ export interface CredentialsSeam {
38
+ describe(ref: string): Promise<{ configured: boolean }>
39
+ }
40
+
41
+ /**
42
+ * The launch-environment snapshot surface (`@deepseek-ai/dsh-launch-environment`).
43
+ * Cordis `ctx.get` returns undefined for an unregistered service; it does not
44
+ * synthesize a snapshot. This module supplies the `process.env` fallback.
45
+ */
46
+ export interface LaunchEnvironmentSnapshot {
47
+ get(name: string): { value: string } | undefined
48
+ }
49
+
50
+ /**
51
+ * The subset of `Context` this module reads. Both services are optional:
52
+ * `credentials` is an optional peer and may be absent, `launchEnvironment` is
53
+ * provided by the launcher but the helper synthesizes a process-env snapshot
54
+ * when it is not.
55
+ */
56
+ export interface RouteCredentialContext {
57
+ get(name: 'credentials'): CredentialsSeam | undefined
58
+ get(name: 'launchEnvironment'): LaunchEnvironmentSnapshot | undefined
59
+ get(name: string): unknown
60
+ }
61
+
62
+ /**
63
+ * The settings descriptor shape this module needs (matches writer.ts's
64
+ * `SettingsDescriptor`). Only `user.providers.<route>.apiKeyEnv` is read —
65
+ * the value the user explicitly declared in settings.yaml.
66
+ */
67
+ export interface RouteCredentialSettingsDescriptor {
68
+ user?: Record<string, unknown>
69
+ }
70
+
71
+ /**
72
+ * Outcome of one route's credential check.
73
+ */
74
+ export interface RouteCredentialCheck {
75
+ /** True when either source confirms the route is configured. */
76
+ ok: boolean
77
+ /**
78
+ * The credential reference name consulted (e.g. `OPENCODE_API_KEY`,
79
+ * `MINIMAX_CN_API_KEY`). Always present, even when `ok` is false, so the
80
+ * report can name what is missing.
81
+ */
82
+ ref: string
83
+ /**
84
+ * Which source confirmed the route, when `ok` is true:
85
+ * - 'credentials' — the seam's `describe()` returned `configured: true`
86
+ * - 'env' — the launch-environment snapshot (process env / .env) had a
87
+ * non-empty value, with no seam hit
88
+ */
89
+ via?: 'credentials' | 'env'
90
+ }
91
+
92
+ /**
93
+ * Derive the conventional credential reference for a provider route. This is
94
+ * a byte-for-byte replica of `deriveKeyRef` from the dsh web UI's settings
95
+ * models package (see ~/github/deepseek-harness/packages/client/ui-
96
+ * settings-models/src/client/store.ts:111-113). The web UI uses it as the
97
+ * default name a typed key stores under; we use it as the fallback when the
98
+ * user has not declared an explicit `apiKeyEnv` in their provider profile.
99
+ *
100
+ * @param provider - provider route id (e.g. `opencode-go`, `minimax-cn`).
101
+ * @returns the derived reference name (e.g. `OPENCODE_GO_API_KEY`).
102
+ */
103
+ export function deriveKeyRef(provider: string): string {
104
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
105
+ }
106
+
107
+ /**
108
+ * Read the explicit `apiKeyEnv` the user declared for a route in the
109
+ * `llm-pi-ai` provider profile. Returns the trimmed string when present and
110
+ * non-empty, otherwise `undefined` (callers fall through to `deriveKeyRef`).
111
+ *
112
+ * @param desc - the settings descriptor (may be undefined when the host has
113
+ * no `llm-pi-ai` namespace registered yet).
114
+ * @param route - the provider route id.
115
+ */
116
+ export function getRawUserApiKeyEnv(
117
+ desc: RouteCredentialSettingsDescriptor | undefined,
118
+ route: string,
119
+ ): string | undefined {
120
+ if (desc === undefined) return undefined
121
+ const providers = desc.user?.providers as Record<string, unknown> | undefined
122
+ if (providers === undefined) return undefined
123
+ const routeData = providers[route] as Record<string, unknown> | undefined
124
+ if (routeData === undefined) return undefined
125
+ const raw = routeData.apiKeyEnv
126
+ if (typeof raw !== 'string') return undefined
127
+ const trimmed = raw.trim()
128
+ return trimmed.length > 0 ? trimmed : undefined
129
+ }
130
+
131
+ /**
132
+ * Run the per-route credential gate. Returns `{ ok, ref, via? }` where `ok`
133
+ * is true iff either source confirms the route is configured.
134
+ *
135
+ * Resolution layers (not an exact request-time credential resolver):
136
+ * 1. `credentials.describe(ref).configured === true` when the seam is
137
+ * provided AND the ref is a valid `CredentialRef` (POSIX identifier).
138
+ * The strict pattern check matters: a profile removed during logout leaves
139
+ * no `apiKeyEnv`, so we always derive; and a stray ref that does not match
140
+ * the brand grammar (e.g. the seam `resolve` would throw) must read as
141
+ * "not configured" rather than crash the round.
142
+ * 2. `launchEnvironment.get(ref).value` returns a non-empty string, following
143
+ * llm-pi-ai's `authContextFrom(ctx).env()` semantics. Like
144
+ * `launchEnvironmentOf`, we synthesize a `process.env` snapshot when the
145
+ * launch-environment service is absent, even without a launcher.
146
+ *
147
+ * Both misses → `ok: false`. The gate then skips fetch / translate /
148
+ * `settings.mutate` for the route and emits a report line naming the ref.
149
+ *
150
+ * @param ctx - the plugin's cordis context.
151
+ * @param desc - the resolved `llm-pi-ai` settings descriptor (may be undefined
152
+ * when the host has not registered the namespace yet — same shape as the
153
+ * descriptor the writer already reads).
154
+ * @param route - the provider route id being checked.
155
+ */
156
+ export async function checkRouteCredential(
157
+ ctx: RouteCredentialContext,
158
+ desc: RouteCredentialSettingsDescriptor | undefined,
159
+ route: string,
160
+ ): Promise<RouteCredentialCheck> {
161
+ // 1. The user-declared ref (when present) wins over the derived one. A
162
+ // profile that names its own ref is the authoritative choice; the
163
+ // derivation is only a fallback for shell-environment users.
164
+ const declared = getRawUserApiKeyEnv(desc, route)
165
+ const ref = declared ?? deriveKeyRef(route)
166
+
167
+ // 2. Credentials seam first. The seam is optional: skip the whole branch
168
+ // when the host did not register it. Inside the branch, only consult the
169
+ // seam when the ref matches the brand's POSIX-identifier grammar — the
170
+ // seam's own `describe` throws on an invalid ref, which would crash the
171
+ // sync round. Mirroring `isCredentialRefName` from
172
+ // @deepseek-ai/dsh-credentials keeps the gate quiet on malformed input.
173
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
174
+ if (REF_PATTERN.test(ref)) {
175
+ const credentials = ctx.get('credentials')
176
+ if (credentials !== undefined) {
177
+ try {
178
+ const info = await credentials.describe(ref)
179
+ if (info.configured) {
180
+ return { ok: true, ref, via: 'credentials' }
181
+ }
182
+ } catch {
183
+ // Treat any throw from describe (provider missing, seam half-broken)
184
+ // as "not configured here" and fall through to the env check.
185
+ }
186
+ }
187
+ }
188
+
189
+ // 3. Cordis `ctx.get` returns undefined for absent services, without throwing
190
+ // or falling through to process.env. Reproduce `launchEnvironmentOf`'s
191
+ // fallback locally, without importing the optional peer. A provided
192
+ // snapshot remains authoritative; empty values do not count as configured.
193
+ const snapshot = ctx.get('launchEnvironment') ?? {
194
+ get(name: string) {
195
+ const value = process.env[name]
196
+ return value !== undefined && value !== '' ? { value, source: 'process' } : undefined
197
+ },
198
+ }
199
+ const entry = snapshot.get(ref)
200
+ if (entry !== undefined && typeof entry.value === 'string' && entry.value.length > 0) {
201
+ return { ok: true, ref, via: 'env' }
202
+ }
203
+
204
+ return { ok: false, ref }
205
+ }