omnicell-router 0.2.0 → 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.
Files changed (102) hide show
  1. package/backend/dist/budget/budget-manager.d.ts +25 -0
  2. package/backend/dist/budget/budget-manager.js +54 -0
  3. package/backend/dist/cli/clients/index.js +2 -0
  4. package/backend/dist/cli/clients/omp.d.ts +53 -0
  5. package/backend/dist/cli/clients/omp.js +664 -0
  6. package/backend/dist/cli/clients/pi.js +79 -32
  7. package/backend/dist/cli/index.js +2 -2
  8. package/backend/dist/cli/types.d.ts +1 -1
  9. package/backend/dist/config/governance-limits.d.ts +68 -0
  10. package/backend/dist/config/governance-limits.js +261 -0
  11. package/backend/dist/config/index.js +1 -1
  12. package/backend/dist/config/types.d.ts +15 -5
  13. package/backend/dist/flywheel/collector.d.ts +74 -0
  14. package/backend/dist/flywheel/collector.js +235 -0
  15. package/backend/dist/flywheel/dataset.d.ts +130 -0
  16. package/backend/dist/flywheel/dataset.js +638 -0
  17. package/backend/dist/flywheel/decision-capture.d.ts +68 -0
  18. package/backend/dist/flywheel/decision-capture.js +85 -0
  19. package/backend/dist/flywheel/prune.d.ts +133 -0
  20. package/backend/dist/flywheel/prune.js +495 -0
  21. package/backend/dist/flywheel/schema.d.ts +108 -0
  22. package/backend/dist/flywheel/schema.js +117 -0
  23. package/backend/dist/flywheel/trainer.d.ts +84 -0
  24. package/backend/dist/flywheel/trainer.js +198 -0
  25. package/backend/dist/harness/adapters/amp.js +1 -0
  26. package/backend/dist/harness/adapters/claude.js +1 -0
  27. package/backend/dist/harness/adapters/cline.js +3 -1
  28. package/backend/dist/harness/adapters/codex.js +3 -1
  29. package/backend/dist/harness/adapters/cursor.js +1 -0
  30. package/backend/dist/harness/adapters/declarative.d.ts +3 -1
  31. package/backend/dist/harness/adapters/declarative.js +15 -1
  32. package/backend/dist/harness/adapters/dsh.js +1 -1
  33. package/backend/dist/harness/adapters/gemini-cli.js +1 -0
  34. package/backend/dist/harness/adapters/github-copilot.js +1 -0
  35. package/backend/dist/harness/adapters/index.d.ts +11 -3
  36. package/backend/dist/harness/adapters/index.js +48 -1
  37. package/backend/dist/harness/adapters/omp.d.ts +11 -0
  38. package/backend/dist/harness/adapters/omp.js +22 -0
  39. package/backend/dist/harness/adapters/opencode.js +1 -0
  40. package/backend/dist/harness/adapters/pi.js +2 -1
  41. package/backend/dist/harness/adapters/types.d.ts +19 -4
  42. package/backend/dist/harness/adapters/windsurf.js +1 -0
  43. package/backend/dist/harness/adapters/zed.js +3 -1
  44. package/backend/dist/harness/hosts.js +1 -0
  45. package/backend/dist/harness/translation.js +12 -4
  46. package/backend/dist/harness/types.d.ts +2 -2
  47. package/backend/dist/harness/writers/skill.d.ts +1 -1
  48. package/backend/dist/opencode/agents.d.ts +7 -0
  49. package/backend/dist/opencode/agents.js +22 -3
  50. package/backend/dist/opencode/catalog/custom-store.d.ts +50 -0
  51. package/backend/dist/opencode/catalog/custom-store.js +144 -0
  52. package/backend/dist/opencode/credentials/push.d.ts +38 -0
  53. package/backend/dist/opencode/credentials/push.js +116 -0
  54. package/backend/dist/opencode/credentials/reconcile.d.ts +49 -0
  55. package/backend/dist/opencode/credentials/reconcile.js +216 -0
  56. package/backend/dist/opencode/sync.d.ts +29 -0
  57. package/backend/dist/opencode/sync.js +186 -0
  58. package/backend/dist/pipeline/account-selection.d.ts +101 -0
  59. package/backend/dist/pipeline/account-selection.js +112 -0
  60. package/backend/dist/pipeline/orchestrator.js +34 -3
  61. package/backend/dist/providers/systemone.d.ts +29 -0
  62. package/backend/dist/providers/systemone.js +170 -0
  63. package/backend/dist/ratelimit/duration.d.ts +24 -0
  64. package/backend/dist/ratelimit/duration.js +43 -0
  65. package/backend/dist/ratelimit/governance-runtime.d.ts +121 -0
  66. package/backend/dist/ratelimit/governance-runtime.js +183 -0
  67. package/backend/dist/ratelimit/index.d.ts +4 -0
  68. package/backend/dist/ratelimit/index.js +4 -0
  69. package/backend/dist/ratelimit/limiter.d.ts +157 -0
  70. package/backend/dist/ratelimit/limiter.js +244 -0
  71. package/backend/dist/ratelimit/sliding-window-counter.d.ts +63 -0
  72. package/backend/dist/ratelimit/sliding-window-counter.js +103 -0
  73. package/backend/dist/ratelimit/subject.d.ts +26 -0
  74. package/backend/dist/ratelimit/subject.js +28 -0
  75. package/backend/dist/resilience/account-state.d.ts +84 -0
  76. package/backend/dist/resilience/account-state.js +228 -0
  77. package/backend/dist/router/layer1-classifier.d.ts +111 -0
  78. package/backend/dist/router/layer1-classifier.js +467 -0
  79. package/backend/dist/router/layer2-judge.d.ts +111 -0
  80. package/backend/dist/router/layer2-judge.js +373 -0
  81. package/backend/dist/router/retry-escalation.d.ts +89 -0
  82. package/backend/dist/router/retry-escalation.js +99 -0
  83. package/backend/dist/routes/flywheel.d.ts +3 -0
  84. package/backend/dist/routes/flywheel.js +268 -0
  85. package/backend/dist/routes/harness.js +4 -1
  86. package/backend/dist/routes/systemone.d.ts +3 -0
  87. package/backend/dist/routes/systemone.js +90 -0
  88. package/backend/dist/server.d.ts +0 -15
  89. package/backend/dist/server.js +40 -43
  90. package/backend/dist/session/session-manager.d.ts +15 -0
  91. package/backend/dist/session/session-manager.js +17 -0
  92. package/backend/dist/session/session-row.d.ts +78 -0
  93. package/backend/dist/session/session-row.js +52 -0
  94. package/backend/dist/surfaces/governance-envelope.d.ts +34 -0
  95. package/backend/dist/surfaces/governance-envelope.js +47 -0
  96. package/backend/dist/utils/token-estimator.d.ts +7 -0
  97. package/backend/dist/utils/token-estimator.js +20 -0
  98. package/bin/ocr.js +2 -2
  99. package/frontend/dist/assets/{index-DvXKvNxl.js → index-B7GKsUyU.js} +264 -244
  100. package/frontend/dist/assets/{index-1o7qI-KJ.css → index-DLKLOkQJ.css} +1 -1
  101. package/frontend/dist/index.html +2 -2
  102. package/package.json +1 -1
@@ -32,6 +32,7 @@ const CONFIG_DIR = path.dirname(CONFIG_CANDIDATES[0]);
32
32
  // time requirement rather than a comment.
33
33
  export const opencodeAdapter = defineFullHost('opencode', {
34
34
  configRootEnv: 'OPENCODE_CONFIG_DIR',
35
+ presence: { command: 'opencode', dir: CONFIG_DIR },
35
36
  skills: {
36
37
  global: path.join(xdgConfig(), 'opencode', 'skills'),
37
38
  project: UNIVERSAL_SKILLS.project,
@@ -1,7 +1,7 @@
1
1
  import os from 'node:os';
2
2
  import path from 'node:path';
3
3
  import { defineHost } from './declarative.js';
4
- import { UNIVERSAL_SKILLS } from './skills-paths.js';
4
+ import { UNIVERSAL_SKILLS, home } from './skills-paths.js';
5
5
  /**
6
6
  * Pi — shared skills directory + package-manager extension landing (ADR-0015 §D8.9).
7
7
  *
@@ -12,6 +12,7 @@ import { UNIVERSAL_SKILLS } from './skills-paths.js';
12
12
  */
13
13
  const AGENT_DIR = path.join(os.homedir(), '.pi', 'agent');
14
14
  export const piAdapter = defineHost('pi', {
15
+ presence: { command: 'pi', dir: path.join(home(), '.pi') },
15
16
  skills: { global: UNIVERSAL_SKILLS.global, project: UNIVERSAL_SKILLS.project, readsUniversal: true },
16
17
  ext: {
17
18
  subprocess: 'pi',
@@ -12,12 +12,12 @@ import type { ExtDiscoveryOrigin, HarnessHostId, HarnessScope, ResolvedRoot } fr
12
12
  *
13
13
  * WHY installation verbs are NOT here: install/uninstall are one pipeline — plan → confirm → apply →
14
14
  * ledger → claims (ADR-0015 gates 2/3) — implemented once per KIND in `writers/`, not once per host.
15
- * An adapter that owned `installExtension` would either duplicate that pipeline thirteen times or
15
+ * An adapter that owned `installExtension` would either duplicate that pipeline fourteen times or
16
16
  * become a forwarder. The split is: **the adapter answers WHERE, the writer answers HOW.**
17
17
  *
18
18
  * WHY skills are not a host capability at all: a skill lands in a DIRECTORY, and one directory is
19
- * read by up to nine hosts (`readsUniversal` / `skillOwner`). "Install this skill into this host"
20
- * would invite writing the same tree nine times; skills live on the location level
19
+ * read by up to ten hosts (`readsUniversal` / `skillOwner`). "Install this skill into this host"
20
+ * would invite writing the same tree ten times; skills live on the location level
21
21
  * (`skillRoots` / `skillTarget` on this interface, aggregated by `skillLocationRoots`).
22
22
  *
23
23
  * WHY one adapter per VERSION is not modelled: `opencode` v1 and v2 differ in landing SPELLINGS
@@ -107,6 +107,20 @@ export interface HostAdapter {
107
107
  readonly id: HarnessHostId;
108
108
  /** Env var that relocates this runtime's config root, when it honours one. */
109
109
  readonly configRootEnv?: string;
110
+ /**
111
+ * Install-presence markers: how the console answers "is this runtime on this machine". Either
112
+ * marker suffices — the executable on PATH or its config directory on disk. A host whose
113
+ * runtime reads a skills directory is ALSO present once that directory exists (a runtime may
114
+ * keep its skills tree after the executable is gone, and its rows must stay manageable).
115
+ */
116
+ readonly presence?: HostPresence;
117
+ }
118
+ /** One way to detect an installed runtime; `dir` is an absolute path. */
119
+ export interface HostPresence {
120
+ /** Executable name probed on PATH (extensionless; the probe adds platform suffixes). */
121
+ command?: string;
122
+ /** The runtime's config/agent directory, e.g. `~/.claude`. */
123
+ dir?: string;
110
124
  }
111
125
  /** Where a host's skills land: one directory per scope, relocated by the host's env root when set. */
112
126
  export interface SkillsSpec {
@@ -120,7 +134,8 @@ export interface SkillsHost extends HostAdapter {
120
134
  /**
121
135
  * Candidate skills roots for one scope, highest precedence first. Global scope may include the
122
136
  * cross-agent `.agents/skills` directory when the runtime reads it (`readsUniversal`); project
123
- * scope is a single directory, because no runtime reads a second project root.
137
+ * scope lists the private project root first and, for a `readsUniversal` host with a private
138
+ * project root, the shared project tree second (omp reads both `.omp/skills` and `.agents/skills`).
124
139
  */
125
140
  skillRoots(ctx: AdapterContext, scope: HarnessScope): ResolvedRoot[];
126
141
  /** Where one skill NAME lands in this host, refusing anything that escapes its root. */
@@ -3,6 +3,7 @@ import { defineHost } from './declarative.js';
3
3
  import { home } from './skills-paths.js';
4
4
  /** Windsurf — its own skills directory (project `.windsurf/skills`); no MCP or extension landing. */
5
5
  export const windsurfAdapter = defineHost('windsurf', {
6
+ presence: { command: 'windsurf', dir: path.join(home(), '.codeium') },
6
7
  skills: {
7
8
  global: path.join(home(), '.codeium', 'windsurf', 'skills'),
8
9
  project: path.join('.windsurf', 'skills'),
@@ -1,6 +1,8 @@
1
+ import path from 'node:path';
1
2
  import { defineHost } from './declarative.js';
2
- import { UNIVERSAL_SKILLS } from './skills-paths.js';
3
+ import { home, UNIVERSAL_SKILLS } from './skills-paths.js';
3
4
  /** Zed — reads the shared cross-agent skills directory; its extension packages are editor-built. */
4
5
  export const zedAdapter = defineHost('zed', {
6
+ presence: { command: 'zed', dir: path.join(home(), '.zed') },
5
7
  skills: { global: UNIVERSAL_SKILLS.global, project: UNIVERSAL_SKILLS.project, readsUniversal: true },
6
8
  });
@@ -5,6 +5,7 @@ export const HOSTS = [
5
5
  { id: 'codex', label: 'Codex' },
6
6
  { id: 'pi', label: 'Pi' },
7
7
  { id: 'dsh', label: 'DSH' },
8
+ { id: 'omp', label: 'omp' },
8
9
  { id: 'cursor', label: 'Cursor' },
9
10
  { id: 'github-copilot', label: 'GitHub Copilot / VS Code' },
10
11
  { id: 'gemini-cli', label: 'Gemini CLI' },
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { defaultGatewayPort } from '../cli/clients/base.js';
5
5
  import { loadConfig } from '../config/index.js';
6
+ import { INTERNAL_SESSION_PREFIX } from '../session/session-manager.js';
6
7
  import { renameWithRetry } from '../utils/atomic-write.js';
7
8
  import { harnessEnvDir } from './manifest.js';
8
9
  const SUPPORTED = ['zh', 'en', 'es', 'fr', 'de', 'ja', 'ko', 'pt'];
@@ -287,6 +288,9 @@ const MD_MAX_INPUT = 20_000;
287
288
  * inside the tier, never jumps to another one). Retrying here keeps that contract intact.
288
289
  */
289
290
  const TAIL_MODEL = 'lite';
291
+ /** Reserved internal-session ids (ADR-0015) — one shared session per purpose. */
292
+ const SESSION_TRANSLATION = `${INTERNAL_SESSION_PREFIX}translation`;
293
+ const SESSION_TRANSLATION_PROBE = `${INTERNAL_SESSION_PREFIX}translation-probe`;
290
294
  /**
291
295
  * The attempt chain for a given configured value. Whitespace or a `lite` value collapses to the
292
296
  * tail alone; an empty string (a cleared picker) means "as if unset".
@@ -312,7 +316,7 @@ export function translationChain() {
312
316
  return chainFor(configured);
313
317
  }
314
318
  /** One gateway round-trip for a fixed model ref. Errors are values, so the caller can retry. */
315
- async function callGateway(key, model, text, lang, systemPrompt = SYSTEM_PROMPT) {
319
+ async function callGateway(key, model, text, lang, systemPrompt = SYSTEM_PROMPT, sessionId) {
316
320
  let response;
317
321
  try {
318
322
  response = await fetch(`http://127.0.0.1:${defaultGatewayPort()}/v1/chat/completions`, {
@@ -325,6 +329,10 @@ async function callGateway(key, model, text, lang, systemPrompt = SYSTEM_PROMPT)
325
329
  { role: 'system', content: systemPrompt },
326
330
  { role: 'user', content: `Target language: ${LANG_LABEL[lang]}\n\n${text}` },
327
331
  ],
332
+ // Pin the reserved internal-session namespace (ADR-0015) so these
333
+ // loopback calls share one session instead of minting a fresh
334
+ // cold_start session per call — the id IS the internal marker.
335
+ ...(sessionId ? { router_options: { session_id: sessionId } } : {}),
328
336
  }),
329
337
  signal: AbortSignal.timeout(30_000),
330
338
  });
@@ -364,7 +372,7 @@ export async function translateDescription(text, lang) {
364
372
  const attempts = translationChain();
365
373
  const failures = [];
366
374
  for (const model of attempts) {
367
- const result = await callGateway(key, model, text, lang);
375
+ const result = await callGateway(key, model, text, lang, SYSTEM_PROMPT, SESSION_TRANSLATION);
368
376
  if ('error' in result) {
369
377
  failures.push(result.error);
370
378
  continue;
@@ -522,7 +530,7 @@ export async function translateMarkdown(markdown, lang) {
522
530
  async function callGatewayOnce(key, text, lang) {
523
531
  const failures = [];
524
532
  for (const model of translationChain()) {
525
- const result = await callGateway(key, model, text, lang, MARKDOWN_SYSTEM_PROMPT);
533
+ const result = await callGateway(key, model, text, lang, MARKDOWN_SYSTEM_PROMPT, SESSION_TRANSLATION);
526
534
  if (!('error' in result))
527
535
  return result;
528
536
  failures.push(result.error);
@@ -555,7 +563,7 @@ export async function probeTranslationChain(lang = 'en', overrideModel) {
555
563
  }
556
564
  const attempts = [];
557
565
  for (const model of chain) {
558
- const result = await callGateway(key, model, PROBE_TEXT, lang);
566
+ const result = await callGateway(key, model, PROBE_TEXT, lang, SYSTEM_PROMPT, SESSION_TRANSLATION_PROBE);
559
567
  if ('error' in result) {
560
568
  attempts.push({ model, ok: false, error: result.error });
561
569
  continue;
@@ -6,7 +6,7 @@
6
6
  * traffic clients, and welding the two would pollute the traffic domain.
7
7
  */
8
8
  export type HarnessKind = 'skill' | 'mcp' | 'extension';
9
- export type HarnessHostId = 'universal' | 'opencode' | 'claude' | 'codex' | 'pi' | 'dsh' | 'cursor' | 'github-copilot' | 'gemini-cli' | 'cline' | 'amp' | 'windsurf' | 'zed';
9
+ export type HarnessHostId = 'universal' | 'opencode' | 'claude' | 'codex' | 'pi' | 'dsh' | 'omp' | 'cursor' | 'github-copilot' | 'gemini-cli' | 'cline' | 'amp' | 'windsurf' | 'zed';
10
10
  /**
11
11
  * Where an artifact may be materialized: project-local or user-level.
12
12
  *
@@ -135,7 +135,7 @@ export interface CopyView {
135
135
  * Skill copies only: every host whose skills roots resolve to this directory, owner FIRST.
136
136
  *
137
137
  * `host` answers ownership (one directory, one owner — install/claims/removal), this answers
138
- * READERSHIP (the cross-agent `.agents/skills` tree is read by up to nine runtimes). Absent for
138
+ * READERSHIP (the cross-agent `.agents/skills` tree is read by up to ten runtimes). Absent for
139
139
  * config-shaped copies, where the file IS the landing and its host is the only reader.
140
140
  */
141
141
  readers?: HarnessHostId[];
@@ -8,7 +8,7 @@ import type { HarnessHostId, HarnessScope, Pin, TrustTier } from '../types.js';
8
8
  * skill; the store copy is content-addressed, so a retry re-uses it and costs no network.
9
9
  *
10
10
  * One host can refuse (no skills location, path already occupied, claimed by another environment)
11
- * while the rest proceed — refusals are reported per host, never silently dropped. Nine hosts read
11
+ * while the rest proceed — refusals are reported per host, never silently dropped. Ten hosts read
12
12
  * the same project directory, so identical target paths are installed ONCE, labeled by the owner
13
13
  * host; the console can then never show "installed under Codex" for a directory the scan reports as
14
14
  * universal.
@@ -18,6 +18,13 @@ export interface OpenCodeAgentView {
18
18
  source: 'builtin' | 'file' | 'config' | 'service';
19
19
  /** Bound model (router-prefixed values stripped); undefined = inherit default model. */
20
20
  model?: string;
21
+ /** Inherit target — the config's top-level default model (router prefix
22
+ * stripped), populated ONLY when `model` is absent. Display-only: the
23
+ * console's profile table shows it as the row's current-model infotip
24
+ * (pi/omp parity, where setup pins every role so the echo is concrete);
25
+ * the binding draft and write path ignore it so `auto` keeps its
26
+ * inherit-the-default semantics (no literal `omnicell-router/auto` pin). */
27
+ effective?: string;
21
28
  /** The agent's own description (file frontmatter / config node / live
22
29
  * roster). Feeds the console's smart-assign role context — absent means
23
30
  * unknown, never invented here. */
@@ -57,6 +57,14 @@ function mergeConfigNode(byName, node) {
57
57
  });
58
58
  }
59
59
  }
60
+ /** The config's top-level default model, router prefix stripped. The inherit
61
+ * target every agent without an explicit `model` resolves to at runtime. */
62
+ function configDefaultModel(configPath) {
63
+ const top = readJsonc(configPath)?.model;
64
+ if (typeof top !== 'string' || !top)
65
+ return undefined;
66
+ return stripRouterPrefix(top) ?? top;
67
+ }
60
68
  export function listOpenCodeAgents(overrides = {}) {
61
69
  const byName = new Map();
62
70
  for (const b of BUILTIN_AGENTS) {
@@ -105,7 +113,15 @@ export function listOpenCodeAgents(overrides = {}) {
105
113
  const parsed = readJsonc(configPath);
106
114
  mergeConfigNode(byName, parsed?.agent);
107
115
  mergeConfigNode(byName, parsed?.agents);
108
- return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
116
+ return fillInheritTargets([...byName.values()], configPath);
117
+ }
118
+ /** Attach the inherit target to every agent that has no explicit `model` —
119
+ * the config's top-level default. Display-only (see `effective`). */
120
+ function fillInheritTargets(agents, configPath) {
121
+ const fallback = configDefaultModel(configPath);
122
+ if (fallback === undefined)
123
+ return agents;
124
+ return agents.map(a => (a.model === undefined ? { ...a, effective: fallback } : a));
109
125
  }
110
126
  /** Map the live service roster to the console view. Hidden internal agents
111
127
  * (compaction / title / summary …) are bindable in principle but noise for the
@@ -149,8 +165,11 @@ export async function listOpenCodeAgentsLive(overrides = {}) {
149
165
  const conn = overrides.connector ?? new OpenCodeConnector();
150
166
  if (conn.isAvailable()) {
151
167
  const raw = await conn.getAgents();
152
- if (raw.length > 0)
153
- return mapServiceAgents(raw);
168
+ if (raw.length > 0) {
169
+ // The service watches the same config file the file scan reads — its
170
+ // top-level default is the inherit target for both sources.
171
+ return fillInheritTargets(mapServiceAgents(raw), overrides.configPath ?? getOpenCodeConfigPath());
172
+ }
154
173
  }
155
174
  }
156
175
  catch {
@@ -0,0 +1,50 @@
1
+ import type { CatalogModel } from './types.js';
2
+ /**
3
+ * Custom-pull store (~/.onecast-router/catalog/custom.json).
4
+ *
5
+ * Models pulled for CREDENTIAL-ONLY providers (auth.json entry without an
6
+ * defs-file definition) — they have no defs node to write into, so the
7
+ * pulled lists land here and feed the aggregation as the 'custom' source
8
+ * (after config defs, entry-creating like the baseline). Merge is add-only:
9
+ * a model id already present for a provider is never overwritten.
10
+ */
11
+ export interface CustomProviderEntry {
12
+ name?: string;
13
+ npm?: string;
14
+ api?: string;
15
+ models: CatalogModel[];
16
+ }
17
+ export interface CustomModelStore {
18
+ version: 1;
19
+ updated: number;
20
+ providers: Record<string, CustomProviderEntry>;
21
+ }
22
+ export declare function getCustomStorePath(): string;
23
+ export declare function readCustomStore(): CustomModelStore | null;
24
+ /** Merge (add-only) one provider's pulled models into the store. */
25
+ export declare function upsertCustomProviderModels(providerId: string, meta: {
26
+ name?: string;
27
+ npm?: string;
28
+ api?: string;
29
+ }, models: CatalogModel[]): number;
30
+ export declare function removeCustomProvider(providerId: string): void;
31
+ export declare function getCustomProviderModels(providerId: string): CatalogModel[];
32
+ export declare function upsertCustomModel(providerId: string, model: CatalogModel): {
33
+ success: boolean;
34
+ error?: string;
35
+ };
36
+ /**
37
+ * Clear models from a provider's custom-store entry — mirrors clearProviderModels
38
+ * semantics (no pattern → all, pattern → glob matches). Fails when the provider
39
+ * has no custom-store entry at all (same 404 signal as an unknown jsonc node),
40
+ * but succeeds with removed: 0 when the entry exists and nothing matches.
41
+ */
42
+ export declare function clearCustomModels(providerId: string, pattern?: string): {
43
+ success: boolean;
44
+ removed?: number;
45
+ error?: string;
46
+ };
47
+ export declare function removeCustomModel(providerId: string, modelId: string): {
48
+ success: boolean;
49
+ error?: string;
50
+ };
@@ -0,0 +1,144 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getOcrStorePath } from './ocr-store.js';
4
+ import { matchesGlobPattern } from '../user-config.js';
5
+ export function getCustomStorePath() {
6
+ return path.join(path.dirname(getOcrStorePath()), 'custom.json');
7
+ }
8
+ export function readCustomStore() {
9
+ try {
10
+ const file = getCustomStorePath();
11
+ if (!fs.existsSync(file))
12
+ return null;
13
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
14
+ if (parsed?.version !== 1 || typeof parsed.providers !== 'object' || parsed.providers === null)
15
+ return null;
16
+ return parsed;
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ /** Merge (add-only) one provider's pulled models into the store. */
23
+ export function upsertCustomProviderModels(providerId, meta, models) {
24
+ try {
25
+ const file = getCustomStorePath();
26
+ const store = readCustomStore() ?? { version: 1, updated: 0, providers: {} };
27
+ const entry = store.providers[providerId] ?? { models: [] };
28
+ if (meta.name && !entry.name)
29
+ entry.name = meta.name;
30
+ if (meta.npm && !entry.npm)
31
+ entry.npm = meta.npm;
32
+ if (meta.api && !entry.api)
33
+ entry.api = meta.api;
34
+ const byId = new Map(entry.models.map((m) => [m.id, m]));
35
+ let added = 0;
36
+ for (const m of models) {
37
+ if (byId.has(m.id))
38
+ continue; // add-only
39
+ byId.set(m.id, m);
40
+ added++;
41
+ }
42
+ entry.models = [...byId.values()];
43
+ store.providers[providerId] = entry;
44
+ store.updated = Date.now();
45
+ fs.mkdirSync(path.dirname(file), { recursive: true });
46
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
47
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
48
+ fs.renameSync(tmp, file);
49
+ return added;
50
+ }
51
+ catch {
52
+ return 0;
53
+ }
54
+ }
55
+ export function removeCustomProvider(providerId) {
56
+ try {
57
+ const store = readCustomStore();
58
+ if (!store?.providers[providerId])
59
+ return;
60
+ delete store.providers[providerId];
61
+ store.updated = Date.now();
62
+ const file = getCustomStorePath();
63
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
64
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
65
+ fs.renameSync(tmp, file);
66
+ }
67
+ catch {
68
+ // best effort
69
+ }
70
+ }
71
+ export function getCustomProviderModels(providerId) {
72
+ return readCustomStore()?.providers[providerId]?.models ?? [];
73
+ }
74
+ export function upsertCustomModel(providerId, model) {
75
+ try {
76
+ const file = getCustomStorePath();
77
+ const store = readCustomStore() ?? { version: 1, updated: 0, providers: {} };
78
+ const entry = store.providers[providerId] ?? { models: [] };
79
+ const byId = new Map(entry.models.map((m) => [m.id, m]));
80
+ byId.set(model.id, model);
81
+ entry.models = [...byId.values()];
82
+ store.providers[providerId] = entry;
83
+ store.updated = Date.now();
84
+ fs.mkdirSync(path.dirname(file), { recursive: true });
85
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
86
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
87
+ fs.renameSync(tmp, file);
88
+ return { success: true };
89
+ }
90
+ catch (err) {
91
+ return { success: false, error: err?.message };
92
+ }
93
+ }
94
+ /**
95
+ * Clear models from a provider's custom-store entry — mirrors clearProviderModels
96
+ * semantics (no pattern → all, pattern → glob matches). Fails when the provider
97
+ * has no custom-store entry at all (same 404 signal as an unknown jsonc node),
98
+ * but succeeds with removed: 0 when the entry exists and nothing matches.
99
+ */
100
+ export function clearCustomModels(providerId, pattern) {
101
+ try {
102
+ const store = readCustomStore();
103
+ const entry = store?.providers[providerId];
104
+ if (!store || !entry) {
105
+ return { success: false, error: `Provider '${providerId}' has no models in the custom store` };
106
+ }
107
+ const trimmed = pattern?.trim();
108
+ const keep = trimmed ? entry.models.filter((m) => !matchesGlobPattern(trimmed, m.id)) : [];
109
+ const removed = entry.models.length - keep.length;
110
+ if (removed === 0)
111
+ return { success: true, removed: 0 };
112
+ entry.models = keep;
113
+ store.updated = Date.now();
114
+ const file = getCustomStorePath();
115
+ fs.mkdirSync(path.dirname(file), { recursive: true });
116
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
117
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
118
+ fs.renameSync(tmp, file);
119
+ return { success: true, removed };
120
+ }
121
+ catch (err) {
122
+ return { success: false, error: err?.message };
123
+ }
124
+ }
125
+ export function removeCustomModel(providerId, modelId) {
126
+ try {
127
+ const store = readCustomStore();
128
+ const entry = store?.providers[providerId];
129
+ if (!entry || !entry.models.some((m) => m.id === modelId)) {
130
+ return { success: false, error: `Model '${modelId}' not found in the custom store` };
131
+ }
132
+ entry.models = entry.models.filter((m) => m.id !== modelId);
133
+ store.providers[providerId] = entry;
134
+ store.updated = Date.now();
135
+ const file = getCustomStorePath();
136
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
137
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
138
+ fs.renameSync(tmp, file);
139
+ return { success: true };
140
+ }
141
+ catch (err) {
142
+ return { success: false, error: err?.message };
143
+ }
144
+ }
@@ -0,0 +1,38 @@
1
+ import { CredentialPaths } from './paths.js';
2
+ import { CredentialStore } from './types.js';
3
+ import { DbOpener } from './opencode-v2-store.js';
4
+ import { ReconcileLogSink } from './reconcile.js';
5
+ export type PushPrecondition = 'not_ocr_bound' | 'opencode_v2_service_unreachable' | 'opencode_v2_db_unreadable';
6
+ export interface PushOutcome {
7
+ /** set instead of attempting anything when the endpoint's gate fails. */
8
+ precondition?: PushPrecondition;
9
+ /** provider ids fully converged (pushed or deduped AND local entry removed). */
10
+ pushed: string[];
11
+ /**
12
+ * Converged (provider, keyHashPrefix) pairs — consumers need the
13
+ * key identity per KEY (a push of a new key is a reconnect and lifts
14
+ * that account's SUSPECT flag; provider ids alone cannot name the account).
15
+ */
16
+ pushedKeys: {
17
+ provider: string;
18
+ keyHashPrefix: string;
19
+ }[];
20
+ /** per-entry failures; the local copy of each is KEPT (never blind-delete). */
21
+ failed: {
22
+ provider: string;
23
+ reason: string;
24
+ }[];
25
+ }
26
+ export interface PushDeps {
27
+ /** the bound store — precondition + local entries + removals. */
28
+ store: CredentialStore;
29
+ paths?: CredentialPaths;
30
+ /** absent = every provider with local entries. */
31
+ provider?: string;
32
+ env?: Readonly<Record<string, string | undefined>>;
33
+ fetchImpl?: typeof fetch;
34
+ now?: () => number;
35
+ openDatabase?: DbOpener;
36
+ log?: ReconcileLogSink;
37
+ }
38
+ export declare function pushLocalCredentialsToV2(deps: PushDeps): Promise<PushOutcome>;
@@ -0,0 +1,116 @@
1
+ import { defaultEnv, resolveDefaultPaths } from './paths.js';
2
+ import { keyHashPrefix } from './types.js';
3
+ import { StoreUnreadableError } from './types.js';
4
+ import { OpencodeV2Store, resolveServiceConfigForPaths } from './opencode-v2-store.js';
5
+ import { indexStoreKeyHashes } from './reconcile.js';
6
+ /**
7
+ * The one-shot **Push to opencode**.
8
+ *
9
+ * When OCR lands on OcrStore (standalone, or the badged db_unreadable
10
+ * degraded binding) it accumulates local entries that opencode never saw.
11
+ * On recovery (opencode v2 service reachable NOW), converge them toward opencode —
12
+ * push-ONLY, the single-truth direction. Per local entry:
13
+ * 1. dedup against the current opencode v2 db via the shared dedup rule
14
+ * (integration/provider + label advisory + keyHash primary);
15
+ * 2. push what's missing through a FRESH writable OpencodeV2Store (HTTP connect/key
16
+ * sink — never raw sqlite writes);
17
+ * 3. on CONFIRMED convergence (pushed, or already present by keyHash) remove
18
+ * the local OcrStore entry — the key has now converged INTO opencode and
19
+ * the single truth is restored. A failed push keeps the local copy (never
20
+ * lose data); the removal itself is logged.
21
+ *
22
+ * Raw-key note: `resolveKeyChain` is boot/pool-rebuild-only per types.ts —
23
+ * this push is the one other sanctioned consumer: convergence must read the
24
+ * LOCAL raw keys and hand them TO opencode (which can never export keys
25
+ * back). Nothing that leaves this module carries key material: the response
26
+ * is provider ids + reasons only.
27
+ */
28
+ const LOG_PREFIX = '[push]';
29
+ const defaultLog = {
30
+ info: (m) => console.log(m),
31
+ warn: (m) => console.warn(m),
32
+ };
33
+ export async function pushLocalCredentialsToV2(deps) {
34
+ const log = deps.log ?? defaultLog;
35
+ const paths = deps.paths ?? resolveDefaultPaths();
36
+ const env = deps.env ?? defaultEnv();
37
+ const store = deps.store;
38
+ // Precondition: only the OCR-owned store holds local leftovers. An opencode v2
39
+ // binding means opencode's own files ARE the truth already — nothing to
40
+ // converge (capability branch: envVisible false ⇔ OcrStore).
41
+ if (store.capabilities.envVisible) {
42
+ return { precondition: 'not_ocr_bound', pushed: [], pushedKeys: [], failed: [] };
43
+ }
44
+ const providerIds = deps.provider ? [deps.provider] : store.accountsOverview().map((a) => a.providerId);
45
+ const local = [];
46
+ for (const id of providerIds)
47
+ local.push(...store.resolveKeyChain(id));
48
+ if (local.length === 0)
49
+ return { pushed: [], pushedKeys: [], failed: [] };
50
+ // "a OpencodeV2Store is reachable NOW": service discovery first (fail fast, no db
51
+ // open), then the readonly db handle the credential view needs for dedup.
52
+ if (!resolveServiceConfigForPaths(paths, env)) {
53
+ return { precondition: 'opencode_v2_service_unreachable', pushed: [], pushedKeys: [], failed: [] };
54
+ }
55
+ let opencodeV2;
56
+ try {
57
+ const createDeps = { paths, writable: true, env };
58
+ if (deps.fetchImpl)
59
+ createDeps.fetchImpl = deps.fetchImpl;
60
+ if (deps.now)
61
+ createDeps.now = deps.now;
62
+ if (deps.openDatabase)
63
+ createDeps.openDatabase = deps.openDatabase;
64
+ opencodeV2 = await OpencodeV2Store.create(createDeps);
65
+ }
66
+ catch (e) {
67
+ if (e instanceof StoreUnreadableError) {
68
+ return { precondition: 'opencode_v2_db_unreadable', pushed: [], pushedKeys: [], failed: [] };
69
+ }
70
+ throw e;
71
+ }
72
+ try {
73
+ const index = indexStoreKeyHashes(opencodeV2, log);
74
+ const pushed = new Set();
75
+ const pushedKeys = [];
76
+ const failed = [];
77
+ for (const cred of local) {
78
+ const prefix = keyHashPrefix(cred.key);
79
+ const bucket = index.get(cred.providerId.toLowerCase());
80
+ if (bucket?.has(prefix)) {
81
+ log.info(`${LOG_PREFIX} ${cred.providerId}: already in opencode (key ${prefix}) — local entry removed`);
82
+ }
83
+ else {
84
+ try {
85
+ await opencodeV2.connectKey(cred.providerId, cred.key, cred.label);
86
+ log.info(`${LOG_PREFIX} ${cred.providerId}: pushed (key ${prefix})`);
87
+ }
88
+ catch (e) {
89
+ const reason = e instanceof Error ? e.message : String(e);
90
+ log.warn(`${LOG_PREFIX} ${cred.providerId}: push failed — ${reason}; local entry kept`);
91
+ failed.push({ provider: cred.providerId, reason });
92
+ continue;
93
+ }
94
+ }
95
+ // Confirmed convergence — remove the local copy (single truth restored).
96
+ try {
97
+ await store.disconnect(cred.accountId);
98
+ store.invalidate();
99
+ pushed.add(cred.providerId);
100
+ // Account-level identity for the route's SUSPECT clear (Decision 6:
101
+ // "cleared only by manual reconnect or Push" — this converged entry is
102
+ // exactly that gesture for this key material, deduped or freshly sent).
103
+ pushedKeys.push({ provider: cred.providerId, keyHashPrefix: prefix });
104
+ }
105
+ catch (e) {
106
+ const reason = e instanceof Error ? e.message : String(e);
107
+ log.warn(`${LOG_PREFIX} ${cred.providerId}: local removal failed after push — ${reason}`);
108
+ failed.push({ provider: cred.providerId, reason: `pushed to opencode but local entry not removed: ${reason}` });
109
+ }
110
+ }
111
+ return { pushed: [...pushed], pushedKeys, failed };
112
+ }
113
+ finally {
114
+ opencodeV2.close(); // one transient readonly handle per push — do not leak it
115
+ }
116
+ }
@@ -0,0 +1,49 @@
1
+ import { CredentialPaths } from './paths.js';
2
+ import { CredentialStore } from './types.js';
3
+ import { ReconcileEntryRecord, StoreStatus } from './factory.js';
4
+ import { AuthSnapshot } from './auth-snapshot.js';
5
+ /** Minimal structured sink; routes/boot pass pino-compatible objects (req.log fits). */
6
+ export interface ReconcileLogSink {
7
+ info(msg: string): void;
8
+ warn(msg: string): void;
9
+ }
10
+ export interface EnsureReconciledDeps {
11
+ paths?: CredentialPaths;
12
+ /** auth.json reader seam; defaults to the injected-path bridge (read-only use). */
13
+ bridge?: AuthSnapshot;
14
+ log?: ReconcileLogSink;
15
+ now?: () => number;
16
+ }
17
+ export interface ReconcileResult {
18
+ ran: boolean;
19
+ skipped?: 'not-opencode-v2' | 'already-done';
20
+ entries: ReconcileEntryRecord[];
21
+ authWriteDisabled: boolean;
22
+ }
23
+ export declare function ensureReconciled(store: CredentialStore, status: StoreStatus, deps?: EnsureReconciledDeps): Promise<ReconcileResult>;
24
+ /**
25
+ * Sync read of the Decision 4 gate's B4 seam: true only when the PERSISTED
26
+ * binding is a writable 'opencode-v2' AND the reconcile marker completed (or the
27
+ * marker completed in-process this boot — see override above). Cheap
28
+ * single-file read; no file-state cache — the answer must reflect a
29
+ * just-completed reconcile within the same boot, and it is only consulted on
30
+ * admin credential writes.
31
+ */
32
+ export declare function isAuthJsonWriteDisabled(paths?: CredentialPaths): boolean;
33
+ /**
34
+ * B4 parallel flag (NOT folded into isAuthJsonWriteDisabled, which stays the
35
+ * opencode-v2 reconcile gate per Decision 4): true when the standalone one-shot import
36
+ * landed this machine on OcrStore with auth.json entries — from then on
37
+ * auth.json is superseded by <ocrHome>/credentials.json as the OCR-side truth
38
+ * and the console must not side-write it (same anti-double-truth reason).
39
+ */
40
+ export declare function isStandaloneAuthImported(paths?: CredentialPaths): boolean;
41
+ /**
42
+ * KeyHash dedup index of a store's current credentials (shared dedup
43
+ * rule: keyHash primary, label advisory). Shared by the reconcile gate and
44
+ * the push endpoint — one guard, two converge-toward-opencode
45
+ * flows. An empty index on throw degrades toward pushing (a duplicate push is
46
+ * louder and safer than skipping real keys); push failures land in results,
47
+ * never silence.
48
+ */
49
+ export declare function indexStoreKeyHashes(store: CredentialStore, log?: ReconcileLogSink): Map<string, Set<string>>;