@albinocrabs/o-switcher 0.1.1 → 0.2.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/dist/plugin.cjs CHANGED
@@ -2,25 +2,63 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var chunkVABBGKSR_cjs = require('./chunk-VABBGKSR.cjs');
5
+ var chunkTJ7ZGZHD_cjs = require('./chunk-TJ7ZGZHD.cjs');
6
+ var promises = require('fs/promises');
7
+ var path = require('path');
8
+ var os = require('os');
9
+
10
+ var STATE_DIR = path.join(os.homedir(), ".local", "share", "o-switcher");
11
+ var STATE_FILE = path.join(STATE_DIR, "tui-state.json");
12
+ var STATE_TMP = path.join(STATE_DIR, "tui-state.json.tmp");
13
+ var writeStateAtomic = async (state) => {
14
+ await promises.mkdir(path.dirname(STATE_FILE), { recursive: true });
15
+ const json = JSON.stringify(state);
16
+ await promises.writeFile(STATE_TMP, json, "utf8");
17
+ await promises.rename(STATE_TMP, STATE_FILE);
18
+ };
19
+ var createStateWriter = (debounceMs = 500) => {
20
+ let pending;
21
+ let timer;
22
+ let writePromise = Promise.resolve();
23
+ const doWrite = () => {
24
+ if (!pending) return;
25
+ const snapshot = pending;
26
+ pending = void 0;
27
+ writePromise = writeStateAtomic(snapshot).catch(() => void 0);
28
+ };
29
+ const write = (state) => {
30
+ pending = state;
31
+ if (timer) clearTimeout(timer);
32
+ timer = setTimeout(doWrite, debounceMs);
33
+ };
34
+ const flush = async () => {
35
+ if (timer) {
36
+ clearTimeout(timer);
37
+ timer = void 0;
38
+ }
39
+ doWrite();
40
+ await writePromise;
41
+ };
42
+ return { write, flush };
43
+ };
6
44
 
7
45
  // src/plugin.ts
8
46
  var initializeSwitcher = (rawConfig) => {
9
- const config = chunkVABBGKSR_cjs.validateConfig(rawConfig);
10
- const registry = chunkVABBGKSR_cjs.createRegistry(config);
11
- const logger = chunkVABBGKSR_cjs.createAuditLogger();
12
- const eventBus = chunkVABBGKSR_cjs.createRoutingEventBus();
47
+ const config = chunkTJ7ZGZHD_cjs.validateConfig(rawConfig);
48
+ const registry = chunkTJ7ZGZHD_cjs.createRegistry(config);
49
+ const logger = chunkTJ7ZGZHD_cjs.createAuditLogger();
50
+ const eventBus = chunkTJ7ZGZHD_cjs.createRoutingEventBus();
13
51
  const circuitBreakers = /* @__PURE__ */ new Map();
14
52
  for (const target of registry.getAllTargets()) {
15
53
  circuitBreakers.set(
16
54
  target.target_id,
17
- chunkVABBGKSR_cjs.createCircuitBreaker(target.target_id, config.circuit_breaker, eventBus)
55
+ chunkTJ7ZGZHD_cjs.createCircuitBreaker(target.target_id, config.circuit_breaker, eventBus)
18
56
  );
19
57
  }
20
- const concurrency = chunkVABBGKSR_cjs.createConcurrencyTracker(config.concurrency_limit);
21
- const cooldownManager = chunkVABBGKSR_cjs.createCooldownManager(registry, eventBus);
22
- const traceBuffer = chunkVABBGKSR_cjs.createRequestTraceBuffer(100);
23
- chunkVABBGKSR_cjs.createLogSubscriber(eventBus, logger);
58
+ const concurrency = chunkTJ7ZGZHD_cjs.createConcurrencyTracker(config.concurrency_limit);
59
+ const cooldownManager = chunkTJ7ZGZHD_cjs.createCooldownManager(registry, eventBus);
60
+ const traceBuffer = chunkTJ7ZGZHD_cjs.createRequestTraceBuffer(100);
61
+ chunkTJ7ZGZHD_cjs.createLogSubscriber(eventBus, logger);
24
62
  const configRef = {
25
63
  current: () => config,
26
64
  swap: () => {
@@ -35,10 +73,52 @@ var initializeSwitcher = (rawConfig) => {
35
73
  };
36
74
  return { config, registry, logger, circuitBreakers, concurrency, cooldownManager, operatorDeps };
37
75
  };
76
+ var snapshotState = (state) => {
77
+ if (!state.registry) return void 0;
78
+ const allTargets = state.registry.getAllTargets();
79
+ const activeTarget = allTargets.find((t) => t.state === "Active" && t.enabled);
80
+ const targets = allTargets.map((t) => ({
81
+ target_id: t.target_id,
82
+ provider_id: t.provider_id,
83
+ profile: t.profile,
84
+ state: t.state,
85
+ health_score: t.health_score,
86
+ latency_ema_ms: t.latency_ema_ms,
87
+ enabled: t.enabled
88
+ }));
89
+ return {
90
+ version: 1,
91
+ updated_at: Date.now(),
92
+ active_target_id: activeTarget?.target_id,
93
+ targets
94
+ };
95
+ };
38
96
  var server = async (_input) => {
39
- const logger = chunkVABBGKSR_cjs.createAuditLogger({ level: "info" });
97
+ const logger = chunkTJ7ZGZHD_cjs.createAuditLogger({ level: "info" });
40
98
  logger.info("O-Switcher plugin initializing");
41
99
  const state = {};
100
+ const stateWriter = createStateWriter();
101
+ const publishTuiState = () => {
102
+ const snapshot = snapshotState(state);
103
+ if (snapshot) stateWriter.write(snapshot);
104
+ };
105
+ const lazyOperatorDeps = {
106
+ get registry() {
107
+ return state.operatorDeps.registry;
108
+ },
109
+ get circuitBreakers() {
110
+ return state.operatorDeps.circuitBreakers;
111
+ },
112
+ get configRef() {
113
+ return state.operatorDeps.configRef;
114
+ },
115
+ get logger() {
116
+ return state.operatorDeps.logger;
117
+ },
118
+ get traceBuffer() {
119
+ return state.operatorDeps.traceBuffer;
120
+ }
121
+ };
42
122
  const hooks = {
43
123
  /**
44
124
  * Config hook: initialize O-Switcher when OpenCode config is loaded.
@@ -57,17 +137,17 @@ var server = async (_input) => {
57
137
  rawConfig["targets"] && Array.isArray(rawConfig["targets"]) && rawConfig["targets"].length > 0
58
138
  );
59
139
  if (!hasExplicitTargets) {
60
- const profileStore = await chunkVABBGKSR_cjs.loadProfiles().catch(() => ({}));
140
+ const profileStore = await chunkTJ7ZGZHD_cjs.loadProfiles().catch(() => ({}));
61
141
  const profileKeys = Object.keys(profileStore);
62
142
  if (profileKeys.length > 0) {
63
- const profileTargets = chunkVABBGKSR_cjs.discoverTargetsFromProfiles(profileStore);
143
+ const profileTargets = chunkTJ7ZGZHD_cjs.discoverTargetsFromProfiles(profileStore);
64
144
  rawConfig["targets"] = profileTargets;
65
145
  logger.info(
66
146
  { discovered: profileTargets.length, profiles: profileKeys },
67
147
  "Auto-discovered targets from O-Switcher profiles"
68
148
  );
69
149
  } else if (providerConfig && typeof providerConfig === "object") {
70
- const discoveredTargets = chunkVABBGKSR_cjs.discoverTargets(providerConfig);
150
+ const discoveredTargets = chunkTJ7ZGZHD_cjs.discoverTargets(providerConfig);
71
151
  if (discoveredTargets.length === 0) {
72
152
  logger.warn("No providers found \u2014 running in passthrough mode");
73
153
  return;
@@ -86,7 +166,8 @@ var server = async (_input) => {
86
166
  const initialized = initializeSwitcher(rawConfig);
87
167
  Object.assign(state, initialized);
88
168
  logger.info({ targets: state.registry?.getAllTargets().length }, "O-Switcher initialized");
89
- state.authWatcher = chunkVABBGKSR_cjs.createAuthWatcher({ logger });
169
+ publishTuiState();
170
+ state.authWatcher = chunkTJ7ZGZHD_cjs.createAuthWatcher({ logger });
90
171
  await state.authWatcher.start();
91
172
  logger.info("Auth watcher started");
92
173
  } catch (err) {
@@ -101,7 +182,7 @@ var server = async (_input) => {
101
182
  */
102
183
  async "chat.params"(input, output) {
103
184
  if (!state.registry) return;
104
- const requestId = chunkVABBGKSR_cjs.generateCorrelationId();
185
+ const requestId = chunkTJ7ZGZHD_cjs.generateCorrelationId();
105
186
  const targets = state.registry.getAllTargets();
106
187
  const providerId = input.provider?.info?.id ?? input.provider?.info?.name ?? input.model?.providerID ?? void 0;
107
188
  if (!providerId) return;
@@ -157,6 +238,7 @@ var server = async (_input) => {
157
238
  }
158
239
  state.registry.recordObservation(target.target_id, 0);
159
240
  state.circuitBreakers?.get(target.target_id)?.recordFailure();
241
+ publishTuiState();
160
242
  state.logger?.info(
161
243
  { target_id: target.target_id, event_type: event.type },
162
244
  "Recorded failure from session event"
@@ -166,7 +248,8 @@ var server = async (_input) => {
166
248
  }
167
249
  },
168
250
  tool: {
169
- ...chunkVABBGKSR_cjs.createProfileTools()
251
+ ...chunkTJ7ZGZHD_cjs.createProfileTools(),
252
+ ...chunkTJ7ZGZHD_cjs.createOperatorTools(lazyOperatorDeps)
170
253
  }
171
254
  };
172
255
  return hooks;
package/dist/plugin.d.cts CHANGED
@@ -10,7 +10,7 @@ export { PluginInput } from '@opencode-ai/plugin';
10
10
  * - tool definitions: 7 operator commands (list, pause, resume, drain, disable, inspect, reload)
11
11
  *
12
12
  * Install via opencode.json:
13
- * "plugin": ["@apolenkov/o-switcher@latest"]
13
+ * "plugin": ["@albinocrabs/o-switcher@latest"]
14
14
  *
15
15
  * Or local dev:
16
16
  * "plugin": ["/path/to/o-switcher"]
package/dist/plugin.d.ts CHANGED
@@ -10,7 +10,7 @@ export { PluginInput } from '@opencode-ai/plugin';
10
10
  * - tool definitions: 7 operator commands (list, pause, resume, drain, disable, inspect, reload)
11
11
  *
12
12
  * Install via opencode.json:
13
- * "plugin": ["@apolenkov/o-switcher@latest"]
13
+ * "plugin": ["@albinocrabs/o-switcher@latest"]
14
14
  *
15
15
  * Or local dev:
16
16
  * "plugin": ["/path/to/o-switcher"]
package/dist/plugin.js CHANGED
@@ -1,4 +1,42 @@
1
- import { createAuditLogger, createProfileTools, generateCorrelationId, loadProfiles, discoverTargetsFromProfiles, discoverTargets, createAuthWatcher, validateConfig, createRegistry, createRoutingEventBus, createCircuitBreaker, createConcurrencyTracker, createCooldownManager, createRequestTraceBuffer, createLogSubscriber } from './chunk-IKNWSNAS.js';
1
+ import { createAuditLogger, createOperatorTools, createProfileTools, generateCorrelationId, loadProfiles, discoverTargetsFromProfiles, discoverTargets, createAuthWatcher, validateConfig, createRegistry, createRoutingEventBus, createCircuitBreaker, createConcurrencyTracker, createCooldownManager, createRequestTraceBuffer, createLogSubscriber } from './chunk-7ITX5623.js';
2
+ import { mkdir, writeFile, rename } from 'fs/promises';
3
+ import { join, dirname } from 'path';
4
+ import { homedir } from 'os';
5
+
6
+ var STATE_DIR = join(homedir(), ".local", "share", "o-switcher");
7
+ var STATE_FILE = join(STATE_DIR, "tui-state.json");
8
+ var STATE_TMP = join(STATE_DIR, "tui-state.json.tmp");
9
+ var writeStateAtomic = async (state) => {
10
+ await mkdir(dirname(STATE_FILE), { recursive: true });
11
+ const json = JSON.stringify(state);
12
+ await writeFile(STATE_TMP, json, "utf8");
13
+ await rename(STATE_TMP, STATE_FILE);
14
+ };
15
+ var createStateWriter = (debounceMs = 500) => {
16
+ let pending;
17
+ let timer;
18
+ let writePromise = Promise.resolve();
19
+ const doWrite = () => {
20
+ if (!pending) return;
21
+ const snapshot = pending;
22
+ pending = void 0;
23
+ writePromise = writeStateAtomic(snapshot).catch(() => void 0);
24
+ };
25
+ const write = (state) => {
26
+ pending = state;
27
+ if (timer) clearTimeout(timer);
28
+ timer = setTimeout(doWrite, debounceMs);
29
+ };
30
+ const flush = async () => {
31
+ if (timer) {
32
+ clearTimeout(timer);
33
+ timer = void 0;
34
+ }
35
+ doWrite();
36
+ await writePromise;
37
+ };
38
+ return { write, flush };
39
+ };
2
40
 
3
41
  // src/plugin.ts
4
42
  var initializeSwitcher = (rawConfig) => {
@@ -31,10 +69,52 @@ var initializeSwitcher = (rawConfig) => {
31
69
  };
32
70
  return { config, registry, logger, circuitBreakers, concurrency, cooldownManager, operatorDeps };
33
71
  };
72
+ var snapshotState = (state) => {
73
+ if (!state.registry) return void 0;
74
+ const allTargets = state.registry.getAllTargets();
75
+ const activeTarget = allTargets.find((t) => t.state === "Active" && t.enabled);
76
+ const targets = allTargets.map((t) => ({
77
+ target_id: t.target_id,
78
+ provider_id: t.provider_id,
79
+ profile: t.profile,
80
+ state: t.state,
81
+ health_score: t.health_score,
82
+ latency_ema_ms: t.latency_ema_ms,
83
+ enabled: t.enabled
84
+ }));
85
+ return {
86
+ version: 1,
87
+ updated_at: Date.now(),
88
+ active_target_id: activeTarget?.target_id,
89
+ targets
90
+ };
91
+ };
34
92
  var server = async (_input) => {
35
93
  const logger = createAuditLogger({ level: "info" });
36
94
  logger.info("O-Switcher plugin initializing");
37
95
  const state = {};
96
+ const stateWriter = createStateWriter();
97
+ const publishTuiState = () => {
98
+ const snapshot = snapshotState(state);
99
+ if (snapshot) stateWriter.write(snapshot);
100
+ };
101
+ const lazyOperatorDeps = {
102
+ get registry() {
103
+ return state.operatorDeps.registry;
104
+ },
105
+ get circuitBreakers() {
106
+ return state.operatorDeps.circuitBreakers;
107
+ },
108
+ get configRef() {
109
+ return state.operatorDeps.configRef;
110
+ },
111
+ get logger() {
112
+ return state.operatorDeps.logger;
113
+ },
114
+ get traceBuffer() {
115
+ return state.operatorDeps.traceBuffer;
116
+ }
117
+ };
38
118
  const hooks = {
39
119
  /**
40
120
  * Config hook: initialize O-Switcher when OpenCode config is loaded.
@@ -82,6 +162,7 @@ var server = async (_input) => {
82
162
  const initialized = initializeSwitcher(rawConfig);
83
163
  Object.assign(state, initialized);
84
164
  logger.info({ targets: state.registry?.getAllTargets().length }, "O-Switcher initialized");
165
+ publishTuiState();
85
166
  state.authWatcher = createAuthWatcher({ logger });
86
167
  await state.authWatcher.start();
87
168
  logger.info("Auth watcher started");
@@ -153,6 +234,7 @@ var server = async (_input) => {
153
234
  }
154
235
  state.registry.recordObservation(target.target_id, 0);
155
236
  state.circuitBreakers?.get(target.target_id)?.recordFailure();
237
+ publishTuiState();
156
238
  state.logger?.info(
157
239
  { target_id: target.target_id, event_type: event.type },
158
240
  "Recorded failure from session event"
@@ -162,7 +244,8 @@ var server = async (_input) => {
162
244
  }
163
245
  },
164
246
  tool: {
165
- ...createProfileTools()
247
+ ...createProfileTools(),
248
+ ...createOperatorTools(lazyOperatorDeps)
166
249
  }
167
250
  };
168
251
  return hooks;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@albinocrabs/o-switcher",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Seamless OpenRouter profile rotation for OpenCode — buy multiple subscriptions, use as one pool",
5
5
  "type": "module",
6
- "license": "MIT",
6
+ "license": "Apache-2.0",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/apolenkov/o-switcher.git"
@@ -20,6 +20,9 @@
20
20
  ],
21
21
  "files": [
22
22
  "dist",
23
+ "src/tui.tsx",
24
+ "src/state-bridge.ts",
25
+ "src/registry/types.ts",
23
26
  "README.md",
24
27
  "LICENSE",
25
28
  "CHANGELOG.md"
@@ -47,7 +50,8 @@
47
50
  "types": "./dist/index.d.cts",
48
51
  "default": "./dist/index.cjs"
49
52
  }
50
- }
53
+ },
54
+ "./tui": "./src/tui.tsx"
51
55
  },
52
56
  "scripts": {
53
57
  "build": "tsup",
@@ -56,7 +60,7 @@
56
60
  "typecheck": "tsc --noEmit",
57
61
  "lint": "eslint src/",
58
62
  "lint:fix": "eslint src/ --fix",
59
- "lint:pkg": "publint && attw --pack . --ignore-rules no-resolution",
63
+ "lint:pkg": "publint && attw --pack . --ignore-rules no-resolution --ignore-rules cjs-resolves-to-esm",
60
64
  "format:check": "prettier --check \"src/**/*.ts\" \"*.config.*\" \"*.json\" \".prettierrc\"",
61
65
  "format": "prettier --write \"src/**/*.ts\" \"*.config.*\" \"*.json\" \".prettierrc\"",
62
66
  "test:coverage": "vitest run --coverage",
@@ -78,8 +82,10 @@
78
82
  "@changesets/cli": "^2.30.0",
79
83
  "@eslint/js": "^10.0.1",
80
84
  "@opencode-ai/plugin": "^1.4.3",
85
+ "@opentui/core": "^0.1.97",
86
+ "@opentui/solid": "^0.1.97",
81
87
  "@tsconfig/node20": "^20.1.9",
82
- "@types/node": "^22",
88
+ "@types/node": "^25",
83
89
  "@vitest/coverage-v8": "^4.1.4",
84
90
  "eslint": "^10.2.0",
85
91
  "pino-pretty": "^13",
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Target registry types.
3
+ *
4
+ * Defines the TargetEntry interface with all FOUN-02 fields,
5
+ * the TargetState enum, and RegistrySnapshot for read-only access.
6
+ *
7
+ * SECURITY: No credential fields (api_key, token, secret, password).
8
+ * provider_id is a pointer to OpenCode's auth store (D-13, SECU-01, SECU-02).
9
+ */
10
+
11
+ /**
12
+ * All valid states for a target in the registry.
13
+ *
14
+ * - Active: healthy and available for routing
15
+ * - CoolingDown: temporarily unavailable after transient failure
16
+ * - ReauthRequired: authentication failure, awaiting credential refresh
17
+ * - PolicyBlocked: blocked by policy (403), no retry
18
+ * - CircuitOpen: circuit breaker tripped, no requests allowed
19
+ * - CircuitHalfOpen: circuit breaker probing with limited requests
20
+ * - Draining: operator-initiated drain, no new requests
21
+ * - Disabled: operator-disabled or config-disabled
22
+ */
23
+ export const TARGET_STATES = [
24
+ 'Active',
25
+ 'CoolingDown',
26
+ 'ReauthRequired',
27
+ 'PolicyBlocked',
28
+ 'CircuitOpen',
29
+ 'CircuitHalfOpen',
30
+ 'Draining',
31
+ 'Disabled',
32
+ ] as const;
33
+
34
+ /** Target state type. */
35
+ export type TargetState = (typeof TARGET_STATES)[number];
36
+
37
+ /**
38
+ * A single target entry in the registry.
39
+ *
40
+ * Contains all fields per FOUN-02: target_id, provider_id, endpoint_id,
41
+ * capabilities, enabled, state, health_score, cooldown_until, latency_ema_ms,
42
+ * failure_score, operator_priority, policy_tags.
43
+ *
44
+ * NO credential fields -- provider_id maps to OpenCode's credential store.
45
+ */
46
+ export interface TargetEntry {
47
+ readonly target_id: string;
48
+ readonly provider_id: string;
49
+ readonly profile: string | undefined;
50
+ readonly endpoint_id: string | undefined;
51
+ readonly capabilities: readonly string[];
52
+ readonly enabled: boolean;
53
+ readonly state: TargetState;
54
+ readonly health_score: number;
55
+ readonly cooldown_until: number | null;
56
+ readonly latency_ema_ms: number;
57
+ readonly failure_score: number;
58
+ readonly operator_priority: number;
59
+ readonly policy_tags: readonly string[];
60
+ }
61
+
62
+ /** Read-only snapshot of the entire registry. */
63
+ export interface RegistrySnapshot {
64
+ readonly targets: ReadonlyArray<Readonly<TargetEntry>>;
65
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * State bridge between server plugin and TUI plugin.
3
+ *
4
+ * Server and TUI plugins run in separate contexts (Node.js vs Bun/Solid).
5
+ * This module provides a file-based state bridge:
6
+ * - Server writes a JSON snapshot after each meaningful state change
7
+ * - TUI polls the file to render current state
8
+ *
9
+ * Writes are atomic (tmp → rename) and debounced to avoid thrashing.
10
+ * Reads tolerate missing/corrupt files gracefully.
11
+ */
12
+
13
+ import { writeFile, rename, mkdir } from 'node:fs/promises';
14
+ import { join, dirname } from 'node:path';
15
+ import { homedir } from 'node:os';
16
+ import type { TargetState } from './registry/types.js';
17
+
18
+ // ── Shared types ──────────────────────────────────────────────────
19
+
20
+ /** Compact target summary for TUI display. */
21
+ export interface TuiTargetSummary {
22
+ readonly target_id: string;
23
+ readonly provider_id: string;
24
+ readonly profile: string | undefined;
25
+ readonly state: TargetState;
26
+ readonly health_score: number;
27
+ readonly latency_ema_ms: number;
28
+ readonly enabled: boolean;
29
+ }
30
+
31
+ /** Root state file structure written by server plugin. */
32
+ export interface TuiStateFile {
33
+ readonly version: 1;
34
+ readonly updated_at: number;
35
+ readonly active_target_id: string | undefined;
36
+ readonly targets: readonly TuiTargetSummary[];
37
+ }
38
+
39
+ // ── File path ─────────────────────────────────────────────────────
40
+
41
+ const STATE_DIR = join(homedir(), '.local', 'share', 'o-switcher');
42
+ const STATE_FILE = join(STATE_DIR, 'tui-state.json');
43
+ const STATE_TMP = join(STATE_DIR, 'tui-state.json.tmp');
44
+
45
+ /** Resolved path to the TUI state file. Exposed for tests and TUI reader. */
46
+ export const TUI_STATE_PATH = STATE_FILE;
47
+
48
+ // ── Writer (server side) ──────────────────────────────────────────
49
+
50
+ /**
51
+ * Write state atomically: write to .tmp, then rename.
52
+ * Ensures TUI never reads a partial file.
53
+ */
54
+ const writeStateAtomic = async (state: TuiStateFile): Promise<void> => {
55
+ await mkdir(dirname(STATE_FILE), { recursive: true });
56
+ const json = JSON.stringify(state);
57
+ await writeFile(STATE_TMP, json, 'utf8');
58
+ await rename(STATE_TMP, STATE_FILE);
59
+ };
60
+
61
+ /**
62
+ * Create a debounced state writer.
63
+ *
64
+ * Collapses rapid state changes into a single file write.
65
+ * Returns a `write(state)` function and a `flush()` for shutdown.
66
+ */
67
+ export const createStateWriter = (debounceMs = 500): {
68
+ write: (state: TuiStateFile) => void;
69
+ flush: () => Promise<void>;
70
+ } => {
71
+ let pending: TuiStateFile | undefined;
72
+ let timer: ReturnType<typeof setTimeout> | undefined;
73
+ let writePromise: Promise<void> = Promise.resolve();
74
+
75
+ const doWrite = (): void => {
76
+ if (!pending) return;
77
+ const snapshot = pending;
78
+ pending = undefined;
79
+ writePromise = writeStateAtomic(snapshot).catch(() => undefined);
80
+ };
81
+
82
+ const write = (state: TuiStateFile): void => {
83
+ pending = state;
84
+ if (timer) clearTimeout(timer);
85
+ timer = setTimeout(doWrite, debounceMs);
86
+ };
87
+
88
+ const flush = async (): Promise<void> => {
89
+ if (timer) {
90
+ clearTimeout(timer);
91
+ timer = undefined;
92
+ }
93
+ doWrite();
94
+ await writePromise;
95
+ };
96
+
97
+ return { write, flush };
98
+ };
99
+
100
+ // ── Reader (TUI side) ─────────────────────────────────────────────
101
+
102
+ /**
103
+ * Read the TUI state file. Returns undefined if missing or corrupt.
104
+ *
105
+ * Uses dynamic import for readFile to avoid bundling it into the server
106
+ * plugin (where only the writer is needed). This eliminates tree-shaking
107
+ * warnings from tsup.
108
+ */
109
+ export const readTuiState = async (): Promise<TuiStateFile | undefined> => {
110
+ try {
111
+ const { readFile } = await import('node:fs/promises');
112
+ const raw = await readFile(STATE_FILE, 'utf8');
113
+ const parsed = JSON.parse(raw) as TuiStateFile;
114
+ if (parsed.version !== 1) return undefined;
115
+ return parsed;
116
+ } catch {
117
+ return undefined;
118
+ }
119
+ };