@ngosangns/ns-bridge 0.1.20 → 0.1.22

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/dist/zcode.js ADDED
@@ -0,0 +1,824 @@
1
+ /**
2
+ * `ns-bridge zcode setup|status|remove` — register the ns-bridge serve
3
+ * endpoints as personal providers in the ZCode app.
4
+ *
5
+ * ZCode stores personal providers in ~/.zcode/v2/provider_config.json and
6
+ * keeps that file in memory while the desktop app runs, so an edit while it
7
+ * runs is lost on the app's next save. setup and remove refuse --apply while
8
+ * ZCode runs unless --force. The file can hold other providers' entries and
9
+ * secrets, so its contents are never printed — only ids and counts we own.
10
+ *
11
+ * On darwin setup also installs a launchd agent that keeps `ns-bridge serve`
12
+ * running, pinned to the globally installed CLI when one is on PATH and to
13
+ * this checkout otherwise.
14
+ */
15
+ import { chmodSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { catalogPaths, readCatalogs, } from "./catalog.js";
20
+ import { formatCommand } from "./hosts.js";
21
+ import { readSelectionFile, resolveSelection, selectionPath } from "./selection.js";
22
+ import { DEFAULT_ZCODE_PORT, ensureZcodeServeConfig, readZcodeServeConfig } from "./zcode-config.js";
23
+ /** Every provider id we write starts with this; anything else in the file is left alone. */
24
+ export const PROVIDER_ID_PREFIX = "ns-bridge-";
25
+ export const ZCODE_LAUNCH_AGENT_LABEL = "dev.ngosangns.ns-bridge.serve";
26
+ const SCHEMA_VERSION = 1;
27
+ const HEALTH_TIMEOUT_MS = 2000;
28
+ const FALLBACK_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
29
+ const VENDOR_LABEL = { kiro: "Kiro", devin: "Devin", grok: "Grok", arnict: "Arnict" };
30
+ /** The vendors setup registers: the mounts `ns-bridge serve` routes. Arnict joins only with a key. */
31
+ const ZCODE_VENDORS = ["kiro", "devin", "grok", "arnict"];
32
+ export function zcodeProviderConfigPath(env = process.env, home = homedir()) {
33
+ const override = env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE?.trim();
34
+ if (override)
35
+ return override;
36
+ return join(home, ".zcode", "v2", "provider_config.json");
37
+ }
38
+ export function launchAgentPlistPath(home) {
39
+ return join(home, "Library", "LaunchAgents", `${ZCODE_LAUNCH_AGENT_LABEL}.plist`);
40
+ }
41
+ export function serveLogPath(home) {
42
+ return join(home, ".ns-bridge", "logs", "serve.log");
43
+ }
44
+ /**
45
+ * Kiro compaction thresholds for models whose catalog entry records none,
46
+ * copied from kiro-core `long-context.ts`. Copied rather than imported: tsc
47
+ * emits dist/zcode.js verbatim, and the published CLI ships no runtime
48
+ * dependency on the cores — scripts/build.mjs bundles the only entries allowed
49
+ * to import them.
50
+ */
51
+ const KIRO_CLAUDE_COMPACTION_TARGET = 150000;
52
+ const KIRO_LONG_CONTEXT_THRESHOLDS = {
53
+ "gpt-5-6-luna": 272000,
54
+ "gpt-5-6-sol": 272000,
55
+ "gpt-5-6-terra": 272000,
56
+ };
57
+ /**
58
+ * Arnict's GLM 5.3 compaction policy, copied from ns-arnict-core for the same
59
+ * reason kiro's is copied above: every id the `zai/glm-5.3` prefix covers runs
60
+ * in the vendor's 400K agentic standard window, compacting with the shared
61
+ * 16,384 reserve, while Arnict serves those ids against a native 1,048,576
62
+ * window. `arnictGlm53Id` mirrors isArnictGlm53Id.
63
+ */
64
+ export const ARNICT_GLM_STANDARD_CONTEXT_WINDOW = 400_000;
65
+ const ARNICT_GLM_NATIVE_CONTEXT_WINDOW = 1_048_576;
66
+ export function arnictGlm53Id(id) {
67
+ return /^zai\/glm-5\.3(?:[-.:/].*)?$/i.test(id);
68
+ }
69
+ /**
70
+ * Where ns-bridge's per-model policy compacts a model whose catalog recorded
71
+ * no threshold. Kiro: a Claude model with a window past 200K compacts at the
72
+ * 150K target; everything else compacts where the OMP provider's default rule
73
+ * lands on the model's standard-price window — OMP holds back
74
+ * max(floor(0.15·W), 16384) of a window W (omp-provider-kiro models.ts
75
+ * `ompWindowForThreshold`) — so ZCode compacts where OMP does: 170000 at 200K,
76
+ * 231200 at the 272K GPT-5.6 tier. The other vendors' cores record the window
77
+ * minus its 16384 reservation (ns-core-utils `compactionBudget`).
78
+ */
79
+ export function derivedThresholdTokens(vendor, entry) {
80
+ if (vendor === "kiro") {
81
+ if (entry.id.startsWith("claude-") && entry.contextWindow > 200000)
82
+ return KIRO_CLAUDE_COMPACTION_TARGET;
83
+ const threshold = KIRO_LONG_CONTEXT_THRESHOLDS[entry.id];
84
+ const standard = threshold !== undefined && threshold < entry.contextWindow ? threshold : entry.contextWindow;
85
+ return standard - Math.max(Math.floor(standard * 0.15), 16384);
86
+ }
87
+ if (vendor === "arnict" && arnictGlm53Id(entry.id))
88
+ return ARNICT_GLM_STANDARD_CONTEXT_WINDOW - 16384;
89
+ return entry.contextWindow - Math.min(entry.maxTokens ?? 16384, 16384);
90
+ }
91
+ /**
92
+ * ZCode compacts at W - min(min(maxOutputTokens ?? 32000, 21000), W) - 13000
93
+ * for a reported window W. Reporting W = threshold + 13000 +
94
+ * min(maxOutputTokens, 21000), capped at the real window, lands the
95
+ * compaction on the threshold the catalog recorded — or, when it recorded
96
+ * none, where ns-bridge's per-model policy for the vendor compacts. The real
97
+ * window is the catalog's maxContextWindow when it recorded one (arnict's
98
+ * native window), else the GLM 5.3 native window for a glm-5.3 id, else the
99
+ * window the compaction runs in.
100
+ */
101
+ export function zcodeModelWindow(entry, vendor) {
102
+ const maxOutputTokens = entry.maxTokens ?? 32000;
103
+ const threshold = entry.thresholdTokens ?? derivedThresholdTokens(vendor, entry);
104
+ const realWindow = entry.maxContextWindow ?? (arnictGlm53Id(entry.id) ? ARNICT_GLM_NATIVE_CONTEXT_WINDOW : entry.contextWindow);
105
+ const window = Math.min(realWindow, threshold + 13000 + Math.min(maxOutputTokens, 21000));
106
+ return { window, maxOutputTokens };
107
+ }
108
+ export function supportsImage(entry) {
109
+ return entry.input?.includes("image") ?? false;
110
+ }
111
+ // --- plan ---
112
+ /**
113
+ * Reasoning levels every model rule publishes — the BridgeEffort vocabulary
114
+ * the anthropic-messages bridge maps via toBridgeEffort (bridge-core
115
+ * effort.ts accepts each of them). ZCode ignores a defaultModelSelection
116
+ * whose options.reasoningLevel is missing from the selected model's values,
117
+ * so the rules must carry them explicitly.
118
+ */
119
+ export const ZCODE_REASONING_LEVELS = ["low", "medium", "high", "xhigh", "max"];
120
+ /** The level --default pins in defaultModelSelection; always in ZCODE_REASONING_LEVELS. */
121
+ export const ZCODE_DEFAULT_REASONING_LEVEL = "high";
122
+ /** One plan per ready catalog; catalogs that are missing or empty are skipped with a reason. */
123
+ export function planZcodeProviders(catalogs, serve) {
124
+ const providers = [];
125
+ const skipped = [];
126
+ for (const report of catalogs) {
127
+ if (report.state !== "ready") {
128
+ skipped.push({ vendor: report.vendor, reason: `no catalog (${report.state})` });
129
+ continue;
130
+ }
131
+ const entries = dedupeById(report.groups.flatMap((group) => group.entries));
132
+ const usable = entries.filter((entry) => entry.contextWindow !== undefined);
133
+ if (usable.length === 0) {
134
+ skipped.push({ vendor: report.vendor, reason: "catalog has no models with a context window" });
135
+ continue;
136
+ }
137
+ const providerId = `${PROVIDER_ID_PREFIX}${report.vendor}`;
138
+ providers.push({
139
+ vendor: report.vendor,
140
+ providerId,
141
+ providerName: `ns-bridge ${VENDOR_LABEL[report.vendor]}`,
142
+ baseUrl: `http://127.0.0.1:${serve.port}/${report.vendor}`,
143
+ apiKey: serve.token,
144
+ modelIds: usable.map((entry) => entry.id),
145
+ modelRules: usable.map((entry) => {
146
+ const { window, maxOutputTokens } = zcodeModelWindow(entry, report.vendor);
147
+ return {
148
+ providerId,
149
+ modelId: entry.id,
150
+ config: {
151
+ properties: { contextWindow: window, inputFormat: { supportsImage: supportsImage(entry) } },
152
+ optionSpecs: {
153
+ maxOutputTokens: { max: maxOutputTokens },
154
+ reasoningLevel: { values: ZCODE_REASONING_LEVELS },
155
+ },
156
+ },
157
+ };
158
+ }),
159
+ skippedModels: entries.filter((entry) => entry.contextWindow === undefined).map((entry) => entry.id),
160
+ });
161
+ }
162
+ return { providers, skipped };
163
+ }
164
+ /** Kiro lists the same model per region and profile; the provider wants each id once. */
165
+ function dedupeById(entries) {
166
+ const seen = new Set();
167
+ const out = [];
168
+ for (const entry of entries) {
169
+ if (seen.has(entry.id))
170
+ continue;
171
+ seen.add(entry.id);
172
+ out.push(entry);
173
+ }
174
+ return out;
175
+ }
176
+ /**
177
+ * Idempotent merge of the ns-bridge providers into ZCode's provider config.
178
+ * Re-registered providers replace their old entries at the same position, ids
179
+ * named by keepProviderIds keep their existing provider, model, and manual
180
+ * model entries and their providerOrder slot untouched, and stale ns-bridge-*
181
+ * entries are dropped, so running it twice changes nothing the second time.
182
+ * Unknown keys and other providers' entries pass through untouched;
183
+ * defaultModelSelection is only touched when mergeOptions names one. An
184
+ * undefined `existing` builds the skeleton ZCode accepts. Throws rather than
185
+ * editing a file whose shape it does not recognize.
186
+ */
187
+ export function applyZcodeProviders(existing, plan, mergeOptions = {}) {
188
+ if (existing === undefined && plan.providers.length === 0)
189
+ return { json: {}, changed: false };
190
+ if (existing !== undefined && !isRecord(existing)) {
191
+ throw new Error("provider config is not a JSON object; refusing to overwrite it");
192
+ }
193
+ const next = existing === undefined ? { schemaVersion: SCHEMA_VERSION } : { ...existing };
194
+ const configIn = isRecord(next.config) ? next.config : undefined;
195
+ if (next.config !== undefined && configIn === undefined) {
196
+ throw new Error("config is not an object; refusing to overwrite the provider config");
197
+ }
198
+ const config = { ...(configIn ?? {}) };
199
+ const keep = new Set(mergeOptions.keepProviderIds ?? []);
200
+ const providerConfigRules = recordField(config, "providerConfigRules");
201
+ const rulesIn = arrayField(providerConfigRules ?? {}, "providerRules", "config.providerConfigRules");
202
+ const freshProviderRules = new Map(plan.providers.map((provider) => [provider.providerId, providerRule(provider)]));
203
+ if (rulesIn !== undefined || freshProviderRules.size > 0) {
204
+ config.providerConfigRules = {
205
+ ...providerConfigRules,
206
+ providerRules: mergeRules(rulesIn, freshProviderRules, oursProviderKey, keep),
207
+ };
208
+ }
209
+ const modelConfigRules = recordField(config, "modelConfigRules");
210
+ const modelRulesIn = arrayField(modelConfigRules ?? {}, "providerModelRules", "config.modelConfigRules");
211
+ const freshModelRules = new Map();
212
+ for (const provider of plan.providers) {
213
+ for (const rule of provider.modelRules)
214
+ freshModelRules.set(`${provider.providerId}/${rule.modelId}`, rule);
215
+ }
216
+ if (modelRulesIn !== undefined || freshModelRules.size > 0) {
217
+ config.modelConfigRules = {
218
+ ...modelConfigRules,
219
+ providerModelRules: mergeRules(modelRulesIn, freshModelRules, oursModelKey, keep),
220
+ };
221
+ }
222
+ const manualIn = arrayField(modelConfigRules ?? {}, "manualProviderModelRules", "config.modelConfigRules");
223
+ if (manualIn !== undefined) {
224
+ const merged = mergeRules(manualIn, new Map(), oursModelKey, keep);
225
+ if (merged.length !== manualIn.length) {
226
+ const base = (config.modelConfigRules ?? modelConfigRules ?? {});
227
+ config.modelConfigRules = { ...base, manualProviderModelRules: merged };
228
+ }
229
+ }
230
+ if (Array.isArray(config.providerOrder)) {
231
+ const freshOrderIds = new Map(plan.providers.map((provider) => [provider.providerId, provider.providerId]));
232
+ config.providerOrder = mergeRules(config.providerOrder, freshOrderIds, oursOrderKey, keep);
233
+ }
234
+ if (mergeOptions.defaultModel)
235
+ config.defaultModelSelection = { ...mergeOptions.defaultModel };
236
+ if (configIn !== undefined || configHasEntries(config))
237
+ next.config = config;
238
+ return { json: next, changed: JSON.stringify(next) !== JSON.stringify(existing) };
239
+ }
240
+ function providerRule(provider) {
241
+ return {
242
+ providerId: provider.providerId,
243
+ providerName: provider.providerName,
244
+ config: {
245
+ group: "standard-personal",
246
+ access: { type: "api-key", apiKey: provider.apiKey },
247
+ api: { type: "anthropic-messages", baseUrl: provider.baseUrl },
248
+ personalModelIds: [...provider.modelIds],
249
+ modelOrder: [...provider.modelIds],
250
+ },
251
+ };
252
+ }
253
+ /**
254
+ * Slot-preserving merge of our rules into an existing array: rules named by
255
+ * `fresh` are replaced where they stand, rules whose vendor is named by `keep`
256
+ * survive as-is, stale ns-bridge-* rules are dropped, brand-new ones are
257
+ * appended, and foreign rules pass through.
258
+ */
259
+ function mergeRules(rulesIn, fresh, keyOf, keep) {
260
+ const out = [];
261
+ const replaced = new Set();
262
+ for (const rule of rulesIn ?? []) {
263
+ const id = keyOf(rule);
264
+ if (id === undefined) {
265
+ out.push(rule);
266
+ }
267
+ else if (fresh.has(id.key)) {
268
+ if (!replaced.has(id.key)) {
269
+ replaced.add(id.key);
270
+ out.push(fresh.get(id.key));
271
+ }
272
+ }
273
+ else if (keep.has(id.providerId)) {
274
+ out.push(rule);
275
+ }
276
+ }
277
+ for (const [key, rule] of fresh) {
278
+ if (!replaced.has(key))
279
+ out.push(rule);
280
+ }
281
+ return out;
282
+ }
283
+ function oursProviderKey(rule) {
284
+ return isRecord(rule) && typeof rule.providerId === "string" && rule.providerId.startsWith(PROVIDER_ID_PREFIX)
285
+ ? { key: rule.providerId, providerId: rule.providerId }
286
+ : undefined;
287
+ }
288
+ function oursModelKey(rule) {
289
+ if (!isRecord(rule) || typeof rule.providerId !== "string" || !rule.providerId.startsWith(PROVIDER_ID_PREFIX))
290
+ return undefined;
291
+ return {
292
+ key: `${rule.providerId}/${typeof rule.modelId === "string" ? rule.modelId : ""}`,
293
+ providerId: rule.providerId,
294
+ };
295
+ }
296
+ function oursOrderKey(id) {
297
+ return typeof id === "string" && id.startsWith(PROVIDER_ID_PREFIX) ? { key: id, providerId: id } : undefined;
298
+ }
299
+ function configHasEntries(config) {
300
+ return Object.keys(config).length > 0;
301
+ }
302
+ function recordField(container, key) {
303
+ const value = container[key];
304
+ if (value === undefined)
305
+ return undefined;
306
+ if (!isRecord(value))
307
+ throw new Error(`${key} is not an object; refusing to overwrite the provider config`);
308
+ return value;
309
+ }
310
+ function arrayField(container, key, what) {
311
+ const value = container[key];
312
+ if (value === undefined)
313
+ return undefined;
314
+ if (!Array.isArray(value))
315
+ throw new Error(`${what}.${key} is not an array; refusing to overwrite the provider config`);
316
+ return value;
317
+ }
318
+ function isRecord(value) {
319
+ return typeof value === "object" && value !== null && !Array.isArray(value);
320
+ }
321
+ // --- file IO ---
322
+ export function readProviderConfig(path) {
323
+ let raw;
324
+ try {
325
+ raw = readFileSync(path, "utf8");
326
+ }
327
+ catch (error) {
328
+ return error.code === "ENOENT" ? { state: "missing" } : { state: "unreadable" };
329
+ }
330
+ try {
331
+ return { state: "ready", json: JSON.parse(raw) };
332
+ }
333
+ catch {
334
+ return { state: "unreadable" };
335
+ }
336
+ }
337
+ export function backupPathFor(path, now) {
338
+ const pad = (value) => String(value).padStart(2, "0");
339
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
340
+ return `${path}.bak-ns-bridge-${stamp}`;
341
+ }
342
+ export function backupProviderConfig(path, now) {
343
+ const base = backupPathFor(path, now);
344
+ for (let attempt = 0;; attempt++) {
345
+ const backup = attempt === 0 ? base : `${base}-${attempt}`;
346
+ try {
347
+ // COPYFILE_EXCL: a same-second rerun gets -1, -2, ... instead of clobbering a backup.
348
+ copyFileSync(path, backup, constants.COPYFILE_EXCL);
349
+ chmodSync(backup, 0o600);
350
+ return backup;
351
+ }
352
+ catch (error) {
353
+ if (error.code !== "EEXIST")
354
+ throw error;
355
+ }
356
+ }
357
+ }
358
+ export function writeProviderConfigAtomic(path, json) {
359
+ const dir = dirname(path);
360
+ mkdirSync(dir, { recursive: true });
361
+ const tmp = join(dir, `.provider_config.${process.pid}.tmp`);
362
+ writeFileSync(tmp, `${JSON.stringify(json, null, 2)}\n`, { mode: 0o600 });
363
+ renameSync(tmp, path);
364
+ }
365
+ /**
366
+ * The agent outlives this process and repo checkouts move, so it pins the
367
+ * installed CLI: the first ns-bridge on PATH via its realpath, run by the node
368
+ * sitting next to the bin (a version-managed install keeps its matching
369
+ * runtime there) when present, else execPath.
370
+ */
371
+ export function resolveServeProgram(inputs) {
372
+ const exists = inputs.exists ?? existsSync;
373
+ const realpath = inputs.realpath ?? realpathSync;
374
+ for (const dir of inputs.envPath.split(":")) {
375
+ if (!dir)
376
+ continue;
377
+ const bin = join(dir, "ns-bridge");
378
+ if (!exists(bin))
379
+ continue;
380
+ return {
381
+ script: realpath(bin),
382
+ node: exists(join(dir, "node")) ? join(dir, "node") : inputs.execPath,
383
+ source: "global",
384
+ };
385
+ }
386
+ return { node: inputs.execPath, script: inputs.fallbackScript, source: "fallback" };
387
+ }
388
+ export function launchAgentPlist(inputs) {
389
+ const label = inputs.label ?? ZCODE_LAUNCH_AGENT_LABEL;
390
+ const args = inputs.programArguments.map((arg) => ` <string>${escapeXml(arg)}</string>`).join("\n");
391
+ const env = [["PATH", inputs.envPath], ...Object.entries(inputs.extraEnv ?? {})];
392
+ const envXml = env
393
+ .map(([key, value]) => ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`)
394
+ .join("\n");
395
+ return `<?xml version="1.0" encoding="UTF-8"?>
396
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
397
+ <plist version="1.0">
398
+ <dict>
399
+ <key>Label</key>
400
+ <string>${escapeXml(label)}</string>
401
+ <key>ProgramArguments</key>
402
+ <array>
403
+ ${args}
404
+ </array>
405
+ <key>RunAtLoad</key>
406
+ <true/>
407
+ <key>KeepAlive</key>
408
+ <true/>
409
+ <key>StandardOutPath</key>
410
+ <string>${escapeXml(inputs.logPath)}</string>
411
+ <key>StandardErrorPath</key>
412
+ <string>${escapeXml(inputs.logPath)}</string>
413
+ <key>EnvironmentVariables</key>
414
+ <dict>
415
+ ${envXml}
416
+ </dict>
417
+ </dict>
418
+ </plist>
419
+ `;
420
+ }
421
+ function escapeXml(value) {
422
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
423
+ }
424
+ // --- argument parsing ---
425
+ export function parseVendorList(value) {
426
+ const out = [];
427
+ for (const item of value.split(/[\s,]+/)) {
428
+ if (!item)
429
+ continue;
430
+ if (item !== "kiro" && item !== "devin" && item !== "grok" && item !== "arnict") {
431
+ return { error: `unknown vendor ${item} (expected kiro, devin, grok, or arnict)` };
432
+ }
433
+ if (!out.includes(item))
434
+ out.push(item);
435
+ }
436
+ if (out.length === 0)
437
+ return { error: "--vendors needs at least one of kiro, devin, grok, or arnict" };
438
+ return out;
439
+ }
440
+ export function parseDefaultModel(value) {
441
+ const slash = value.indexOf("/");
442
+ if (slash <= 0)
443
+ return { error: `--default needs <vendor>/<model> (got ${value})` };
444
+ const vendor = value.slice(0, slash);
445
+ const modelId = value.slice(slash + 1);
446
+ if (vendor !== "kiro" && vendor !== "devin" && vendor !== "grok" && vendor !== "arnict") {
447
+ return { error: `--default: unknown vendor ${vendor} (expected kiro, devin, grok, or arnict)` };
448
+ }
449
+ if (!modelId)
450
+ return { error: `--default needs <vendor>/<model> (got ${value})` };
451
+ return { vendor, modelId };
452
+ }
453
+ // --- arnict key ---
454
+ /**
455
+ * Whether an Arnict key resolves, read the way the core resolves it:
456
+ * ARNICT_API_KEY, else the key file `ns-bridge arnict login` writes. The core's
457
+ * resolveArnictApiKey cannot be imported here — tsc emits dist/zcode.js
458
+ * verbatim and the published CLI ships no runtime dependency on the cores — so
459
+ * setup re-reads the same two sources. The value itself never reaches a log.
460
+ */
461
+ export function arnictKeyPresent(home, env = process.env) {
462
+ if (env["ARNICT_API_KEY"]?.trim())
463
+ return true;
464
+ const override = env["NS_BRIDGE_ARNICT_CONFIG"]?.trim();
465
+ const path = override || join(home, ".ns-bridge", "arnict.json");
466
+ try {
467
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
468
+ return typeof parsed.apiKey === "string" && parsed.apiKey.trim().length > 0;
469
+ }
470
+ catch {
471
+ return false;
472
+ }
473
+ }
474
+ export async function runZcode(options) {
475
+ const home = options.home ?? homedir();
476
+ const platform = options.platform ?? process.platform;
477
+ if (options.action === "status")
478
+ return zcodeStatus(options, home, platform);
479
+ if (options.action === "remove")
480
+ return zcodeRemove(options, home, platform);
481
+ return zcodeSetup(options, home, platform);
482
+ }
483
+ function resolveProviderConfigPath(options, home) {
484
+ return options.providerConfigPath ?? zcodeProviderConfigPath(process.env, home);
485
+ }
486
+ function defaultServeConfigPath(home) {
487
+ return join(home, ".ns-bridge", "zcode.json");
488
+ }
489
+ function resolveServeConfigPath(options, home) {
490
+ if (options.serveConfigPath)
491
+ return options.serveConfigPath;
492
+ const override = process.env.NS_BRIDGE_ZCODE_CONFIG?.trim();
493
+ if (override)
494
+ return override;
495
+ return defaultServeConfigPath(home);
496
+ }
497
+ /** launchd serve would read the default path; a moved config must be named in the plist env. */
498
+ function serveEnvFor(servePath, home) {
499
+ return servePath === defaultServeConfigPath(home) ? undefined : { NS_BRIDGE_ZCODE_CONFIG: servePath };
500
+ }
501
+ function resolveSelectionFilePath(options, home) {
502
+ return options.selectionFilePath ?? selectionPath(process.env, home);
503
+ }
504
+ function selectVendors(options, home) {
505
+ const selection = resolveSelection(readSelectionFile(resolveSelectionFilePath(options, home)), process.env);
506
+ let vendors = ZCODE_VENDORS.filter((provider) => selection[provider]);
507
+ if (options.vendors !== undefined) {
508
+ const wanted = parseVendorList(options.vendors);
509
+ if ("error" in wanted)
510
+ return wanted;
511
+ vendors = vendors.filter((vendor) => wanted.includes(vendor));
512
+ }
513
+ return vendors;
514
+ }
515
+ export async function isZcodeRunning(runner) {
516
+ const result = await runner(["pgrep", "-x", "ZCode"]);
517
+ return result.code === 0;
518
+ }
519
+ /** The darwin-only launchctl paths need the console user's uid. */
520
+ function uid() {
521
+ return process.getuid?.() ?? 0;
522
+ }
523
+ async function refuseWhileZcodeRuns(options, providerConfigPath) {
524
+ if (options.apply && !options.force && (await isZcodeRunning(options.runner))) {
525
+ options.err(`ZCode is running; it keeps ${providerConfigPath} in memory and would overwrite this change on its next save`);
526
+ options.err("quit ZCode and run this again, or pass --force. Restart ZCode afterwards to pick up the change.");
527
+ return true;
528
+ }
529
+ return false;
530
+ }
531
+ async function zcodeSetup(options, home, platform) {
532
+ const { log, err, apply } = options;
533
+ const now = options.now ?? new Date();
534
+ const vendors = selectVendors(options, home);
535
+ if ("error" in vendors) {
536
+ err(vendors.error);
537
+ return 1;
538
+ }
539
+ if (vendors.length === 0) {
540
+ err("no vendors to register; check ~/.ns-bridge/providers.json and --vendors");
541
+ return 1;
542
+ }
543
+ // Arnict without a key has nothing to serve with. Skipping it with the note
544
+ // keeps an existing ns-bridge-arnict registration (keepProviderIds below)
545
+ // instead of unregistering a provider whose key is merely unset in this shell.
546
+ const arnictWithoutKey = vendors.includes("arnict") && !arnictKeyPresent(home);
547
+ const planned = arnictWithoutKey ? vendors.filter((vendor) => vendor !== "arnict") : vendors;
548
+ const providerConfigPath = resolveProviderConfigPath(options, home);
549
+ const servePath = resolveServeConfigPath(options, home);
550
+ if (await refuseWhileZcodeRuns(options, providerConfigPath))
551
+ return 1;
552
+ // The serve config (and with it the token) is only created on --apply, so a
553
+ // preview uses a placeholder key that never reaches a file or the terminal.
554
+ const serve = apply ? ensureZcodeServeConfig(servePath) : readZcodeServeConfig(servePath);
555
+ const plan = planZcodeProviders(readCatalogs(options.catalogPaths ?? catalogPaths(), planned), {
556
+ port: serve?.port ?? DEFAULT_ZCODE_PORT,
557
+ token: serve?.token ?? "",
558
+ });
559
+ if (arnictWithoutKey)
560
+ plan.skipped.push({ vendor: "arnict", reason: "no API key (ns-bridge arnict login)" });
561
+ const file = readProviderConfig(providerConfigPath);
562
+ if (file.state === "unreadable") {
563
+ err(`cannot read ${providerConfigPath}; not overwriting it`);
564
+ return 1;
565
+ }
566
+ let defaultModel;
567
+ if (options.default !== undefined) {
568
+ const wanted = parseDefaultModel(options.default);
569
+ if ("error" in wanted) {
570
+ err(wanted.error);
571
+ return 1;
572
+ }
573
+ const provider = plan.providers.find((candidate) => candidate.vendor === wanted.vendor);
574
+ if (!provider) {
575
+ err(`--default ${wanted.vendor}: that vendor is not being registered (check --vendors and ns-bridge providers)`);
576
+ return 1;
577
+ }
578
+ if (!provider.modelIds.includes(wanted.modelId)) {
579
+ err(`--default: ${wanted.modelId} is not in the ${provider.providerId} model list`);
580
+ return 1;
581
+ }
582
+ defaultModel = {
583
+ providerId: provider.providerId,
584
+ modelId: wanted.modelId,
585
+ options: { reasoningLevel: ZCODE_DEFAULT_REASONING_LEVEL },
586
+ };
587
+ }
588
+ let merged;
589
+ try {
590
+ merged = applyZcodeProviders(file.state === "ready" ? file.json : undefined, plan, {
591
+ defaultModel,
592
+ // A skipped vendor keeps its registered provider; a planned one is refreshed.
593
+ keepProviderIds: plan.skipped.map((skip) => `${PROVIDER_ID_PREFIX}${skip.vendor}`),
594
+ });
595
+ }
596
+ catch (error) {
597
+ err(error instanceof Error ? error.message : String(error));
598
+ return 1;
599
+ }
600
+ const service = platform === "darwin" && !options.noService;
601
+ const plistPath = launchAgentPlistPath(home);
602
+ if (!apply) {
603
+ log("# dry-run (pass --apply to run)");
604
+ for (const provider of plan.providers) {
605
+ log(`register ${provider.providerId} ${provider.modelIds.length} model(s) ${provider.baseUrl}`);
606
+ const summary = modelSummary(provider.modelIds);
607
+ if (summary)
608
+ log(` ${summary}`);
609
+ if (provider.skippedModels.length > 0) {
610
+ log(` # skipped ${provider.skippedModels.length} model(s) without a context window`);
611
+ }
612
+ }
613
+ for (const skip of plan.skipped)
614
+ log(`# skipped ${skip.vendor}: ${skip.reason}`);
615
+ if (serve === undefined)
616
+ log(`# create ${servePath} (token generated on --apply)`);
617
+ if (merged.changed) {
618
+ const note = file.state === "ready" ? ` (backup ${backupPathFor(providerConfigPath, now)})` : " (new file)";
619
+ log(`write ${providerConfigPath}${note}`);
620
+ }
621
+ else {
622
+ log(`${providerConfigPath} is already up to date`);
623
+ }
624
+ if (service) {
625
+ const consoleUid = uid();
626
+ log(`write ${plistPath}`);
627
+ log(formatCommand(["launchctl", "bootout", `gui/${consoleUid}/${ZCODE_LAUNCH_AGENT_LABEL}`]));
628
+ log(formatCommand(["launchctl", "bootstrap", `gui/${consoleUid}`, plistPath]));
629
+ }
630
+ return 0;
631
+ }
632
+ if (merged.changed) {
633
+ if (file.state === "ready")
634
+ log(`backup ${backupProviderConfig(providerConfigPath, now)}`);
635
+ writeProviderConfigAtomic(providerConfigPath, merged.json);
636
+ log(`wrote ${providerConfigPath}`);
637
+ }
638
+ else {
639
+ log(`${providerConfigPath} is already up to date`);
640
+ }
641
+ for (const provider of plan.providers) {
642
+ log(`registered ${provider.providerId} ${provider.modelIds.length} model(s)`);
643
+ if (provider.skippedModels.length > 0) {
644
+ log(` # skipped ${provider.skippedModels.length} model(s) without a context window`);
645
+ }
646
+ }
647
+ for (const skip of plan.skipped)
648
+ log(`# skipped ${skip.vendor}: ${skip.reason}`);
649
+ if (!service) {
650
+ log("# start the server: ns-bridge serve");
651
+ log("# restart ZCode to pick up the new providers");
652
+ return 0;
653
+ }
654
+ const loaded = await installLaunchAgent(options, home, plistPath, serveEnvFor(servePath, home));
655
+ log(`# the launch agent runs ns-bridge serve; logs go to ${serveLogPath(home)}`);
656
+ log("# restart ZCode to pick up the new providers");
657
+ return loaded;
658
+ }
659
+ async function installLaunchAgent(options, home, plistPath, extraEnv) {
660
+ const { log, err, runner } = options;
661
+ // This file sits next to main.js in dist/ (src/ under tsx or a test run).
662
+ const mainJs = join(dirname(fileURLToPath(import.meta.url)), "main.js");
663
+ const envPath = process.env.PATH?.trim() || FALLBACK_PATH;
664
+ const program = resolveServeProgram({ envPath, fallbackScript: mainJs, execPath: process.execPath });
665
+ if (program.source === "fallback") {
666
+ log(`# launch agent pinned to ${mainJs}; install ns-bridge globally to pin the installed CLI`);
667
+ }
668
+ log(`# launch agent runs ${program.node} ${program.script} serve`);
669
+ const logPath = serveLogPath(home);
670
+ mkdirSync(dirname(plistPath), { recursive: true });
671
+ mkdirSync(dirname(logPath), { recursive: true });
672
+ writeFileSync(plistPath, launchAgentPlist({
673
+ programArguments: [program.node, program.script, "serve"],
674
+ logPath,
675
+ envPath,
676
+ extraEnv,
677
+ }));
678
+ log(`wrote ${plistPath}`);
679
+ const bootout = ["launchctl", "bootout", `gui/${uid()}/${ZCODE_LAUNCH_AGENT_LABEL}`];
680
+ log(formatCommand(bootout));
681
+ await runner(bootout); // Not running yet is fine; the result does not matter.
682
+ const bootstrap = ["launchctl", "bootstrap", `gui/${uid()}`, plistPath];
683
+ log(formatCommand(bootstrap));
684
+ const result = await runner(bootstrap);
685
+ if (result.code !== 0) {
686
+ const detail = result.stderr.trim() || result.stdout.trim() || `exited ${result.code}`;
687
+ err(`launchctl bootstrap failed: ${detail}`);
688
+ err("start the server by hand with: ns-bridge serve");
689
+ return 2;
690
+ }
691
+ return 0;
692
+ }
693
+ async function zcodeStatus(options, home, platform) {
694
+ const { log } = options;
695
+ const providerConfigPath = resolveProviderConfigPath(options, home);
696
+ const servePath = resolveServeConfigPath(options, home);
697
+ const file = readProviderConfig(providerConfigPath);
698
+ log(`provider config ${providerConfigPath} ${file.state}`);
699
+ if (file.state === "ready") {
700
+ const registered = listRegistered(file.json);
701
+ for (const vendor of ZCODE_VENDORS) {
702
+ const found = registered.find((entry) => entry.providerId === `${PROVIDER_ID_PREFIX}${vendor}`);
703
+ log(` ns-bridge-${vendor} ${found ? `present, ${found.modelCount} model(s)` : "absent"}`);
704
+ }
705
+ }
706
+ const serve = readZcodeServeConfig(servePath);
707
+ const port = serve?.port ?? DEFAULT_ZCODE_PORT;
708
+ log(`serve config ${servePath} ${serve ? `present, port ${port}` : "missing"}`);
709
+ log(`server http://127.0.0.1:${port}/healthz ${await healthLine(port)}`);
710
+ if (platform === "darwin") {
711
+ const plistPath = launchAgentPlistPath(home);
712
+ log(`launch agent ${ZCODE_LAUNCH_AGENT_LABEL} ${existsSync(plistPath) ? `installed (${plistPath})` : "not installed"}`);
713
+ }
714
+ return 0;
715
+ }
716
+ async function zcodeRemove(options, home, platform) {
717
+ const { log, err, apply } = options;
718
+ const now = options.now ?? new Date();
719
+ const providerConfigPath = resolveProviderConfigPath(options, home);
720
+ const file = readProviderConfig(providerConfigPath);
721
+ if (file.state === "missing") {
722
+ log(`nothing to remove: ${providerConfigPath} does not exist`);
723
+ return 0;
724
+ }
725
+ if (file.state === "unreadable") {
726
+ err(`cannot read ${providerConfigPath}; not overwriting it`);
727
+ return 1;
728
+ }
729
+ const registered = listRegistered(file.json);
730
+ if (await refuseWhileZcodeRuns(options, providerConfigPath))
731
+ return 1;
732
+ let merged;
733
+ try {
734
+ merged = applyZcodeProviders(file.json, { providers: [], skipped: [] });
735
+ }
736
+ catch (error) {
737
+ err(error instanceof Error ? error.message : String(error));
738
+ return 1;
739
+ }
740
+ if (!apply) {
741
+ log("# dry-run (pass --apply to run)");
742
+ for (const entry of registered)
743
+ log(`remove ${entry.providerId} ${entry.modelCount} model(s)`);
744
+ if (registered.length === 0)
745
+ log(`${providerConfigPath} has no ns-bridge providers`);
746
+ if (merged.changed)
747
+ log(`write ${providerConfigPath} (backup ${backupPathFor(providerConfigPath, now)})`);
748
+ if (platform === "darwin") {
749
+ log(formatCommand(["launchctl", "bootout", `gui/${uid()}/${ZCODE_LAUNCH_AGENT_LABEL}`]));
750
+ log(`remove ${launchAgentPlistPath(home)}`);
751
+ }
752
+ log(`# ${resolveServeConfigPath(options, home)} stays`);
753
+ return 0;
754
+ }
755
+ if (merged.changed) {
756
+ log(`backup ${backupProviderConfig(providerConfigPath, now)}`);
757
+ writeProviderConfigAtomic(providerConfigPath, merged.json);
758
+ log(`wrote ${providerConfigPath}`);
759
+ }
760
+ else {
761
+ log(`${providerConfigPath} has no ns-bridge providers`);
762
+ }
763
+ if (platform === "darwin") {
764
+ const plistPath = launchAgentPlistPath(home);
765
+ const bootout = ["launchctl", "bootout", `gui/${uid()}/${ZCODE_LAUNCH_AGENT_LABEL}`];
766
+ log(formatCommand(bootout));
767
+ await options.runner(bootout); // Not loaded is fine.
768
+ if (existsSync(plistPath)) {
769
+ rmSync(plistPath);
770
+ log(`removed ${plistPath}`);
771
+ }
772
+ }
773
+ if (defaultModelIsOurs(file.json)) {
774
+ err("# defaultModelSelection still points at an ns-bridge provider; pick another default in ZCode");
775
+ }
776
+ return 0;
777
+ }
778
+ /** What the config currently registers under our prefix; ids and counts only. */
779
+ function listRegistered(json) {
780
+ if (!isRecord(json) || !isRecord(json.config))
781
+ return [];
782
+ const rules = json.config.providerConfigRules;
783
+ if (!isRecord(rules) || !Array.isArray(rules.providerRules))
784
+ return [];
785
+ const out = [];
786
+ for (const rule of rules.providerRules) {
787
+ if (!isRecord(rule) || typeof rule.providerId !== "string" || !rule.providerId.startsWith(PROVIDER_ID_PREFIX))
788
+ continue;
789
+ const config = isRecord(rule.config) ? rule.config : undefined;
790
+ const ids = config?.personalModelIds;
791
+ out.push({
792
+ providerId: rule.providerId,
793
+ modelCount: Array.isArray(ids) ? ids.filter((id) => typeof id === "string").length : 0,
794
+ });
795
+ }
796
+ return out;
797
+ }
798
+ function defaultModelIsOurs(json) {
799
+ if (!isRecord(json) || !isRecord(json.config))
800
+ return false;
801
+ const selection = json.config.defaultModelSelection;
802
+ return (isRecord(selection) &&
803
+ typeof selection.providerId === "string" &&
804
+ selection.providerId.startsWith(PROVIDER_ID_PREFIX));
805
+ }
806
+ async function healthLine(port) {
807
+ try {
808
+ const response = await fetch(`http://127.0.0.1:${port}/healthz`, {
809
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
810
+ });
811
+ return response.ok ? "ok" : `http ${response.status}`;
812
+ }
813
+ catch {
814
+ return "unreachable";
815
+ }
816
+ }
817
+ function modelSummary(ids) {
818
+ const shown = ids.slice(0, 8);
819
+ const extra = ids.length - shown.length;
820
+ if (shown.length === 0)
821
+ return "";
822
+ return extra > 0 ? `${shown.join(", ")}, … (${extra} more)` : shown.join(", ");
823
+ }
824
+ //# sourceMappingURL=zcode.js.map