vim-todo-ai-bridge 0.0.0-stage → 1.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -2
  3. package/package.json +19 -4
  4. package/server.js +506 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 carlosmva
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # vim-todo-list AI bridge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The bridge is an adapter between the Chrome extension and the local `omp` RPC process. It does not store provider keys and does not call provider APIs directly; omp does that.
4
+
5
+ ## Setup
6
+
7
+ ### 1. Install omp
8
+
9
+ Windows PowerShell:
10
+
11
+ ```powershell
12
+ irm https://omp.sh/install.ps1 | iex
13
+ omp --version
14
+ ```
15
+
16
+ macOS/Linux:
17
+
18
+ ```sh
19
+ curl -fsSL https://omp.sh/install | sh
20
+ omp --version
21
+ ```
22
+
23
+ ### 2. Authenticate providers in omp
24
+
25
+ Start omp once:
26
+
27
+ ```sh
28
+ omp
29
+ ```
30
+
31
+ Inside omp, run `/login <provider>` for each provider you use. Provider IDs:
32
+
33
+ | omp provider | Notes |
34
+ | --- | --- |
35
+ | `openai` | OpenAI API |
36
+ | `openai-codex` | ChatGPT subscription |
37
+ | `anthropic` | Claude |
38
+ | `github-copilot` | GitHub Copilot |
39
+
40
+ Choose a default model with `/model`, then exit omp. To list models:
41
+
42
+ ```sh
43
+ omp models
44
+ omp models openai
45
+ ```
46
+
47
+ OMP stores credentials in its local credential store. For API-key providers, omp also supports environment variables and `.env` files; do not commit those files.
48
+
49
+ ### 3. Start the bridge
50
+
51
+ Requires Node.js 20.19 or newer. Run this in a terminal and keep it open:
52
+
53
+ ```sh
54
+ npx -y vim-todo-ai-bridge
55
+ ```
56
+
57
+ The bridge starts `omp --mode rpc --no-session --no-tools` and listens on `http://127.0.0.1:43197`. Set `AI_BRIDGE_HOST` or `AI_BRIDGE_PORT` to change the address.
58
+
59
+ If `omp` is not on `PATH`, set the executable before starting the bridge (PowerShell):
60
+
61
+ ```powershell
62
+ $env:OMP_BIN = "C:\path\to\omp.exe"
63
+ npx -y vim-todo-ai-bridge
64
+ ```
65
+
66
+ ### 4. Connect the extension
67
+
68
+ In **Settings → AI**:
69
+
70
+ - **Provider**: choose **OMP**.
71
+ - **Local AI bridge**: keep `http://127.0.0.1:43197`.
72
+ - **Model** (optional): leave blank, or enter `provider/model`.
73
+ - Click **Save AI settings**.
74
+
75
+ ## Development
76
+
77
+ From a repository checkout:
78
+
79
+ ```sh
80
+ npm install --prefix ai-bridge
81
+ npm start --prefix ai-bridge
82
+ ```
83
+
84
+ ## Troubleshooting
85
+
86
+ - `omp executable not found`: run `omp --version`, reopen the terminal, or set `OMP_BIN`.
87
+ - `Sign in to a provider with omp first`: run `omp`, then `/login <provider>`.
88
+ - `No authenticated omp model is available`: run `omp models` and sign in to a provider that lists models.
89
+ - The bridge is reachable but completion fails: keep the bridge terminal open and read its `[omp]` stderr lines.
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "vim-todo-ai-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Local omp RPC bridge for vim-todo-list",
5
+ "license": "MIT",
6
+ "type": "commonjs",
7
+ "bin": {
8
+ "vim-todo-ai-bridge": "server.js"
9
+ },
10
+ "files": [
11
+ "server.js",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20.19.0"
17
+ },
18
+ "scripts": {
19
+ "start": "node server.js"
20
+ }
21
+ }
package/server.js ADDED
@@ -0,0 +1,506 @@
1
+ #!/usr/bin/env node
2
+ const http = require('node:http');
3
+ const { spawn } = require('node:child_process');
4
+ const HOST = process.env.AI_BRIDGE_HOST || '127.0.0.1';
5
+ const PORT = Number(process.env.AI_BRIDGE_PORT || 43197);
6
+ const MAX_BODY_BYTES = 256 * 1024;
7
+ const REQUEST_TIMEOUT_MS = 45_000;
8
+ function readOmpArgs() {
9
+ const raw = String(process.env.OMP_ARGS || '').trim();
10
+ if (!raw) return ['--mode', 'rpc', '--no-session', '--no-tools'];
11
+ try {
12
+ const args = JSON.parse(raw);
13
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== 'string')) throw new Error('OMP_ARGS must be a JSON string array');
14
+ return args;
15
+ } catch (error) {
16
+ throw new Error(error instanceof Error ? error.message : 'OMP_ARGS must be a JSON string array');
17
+ }
18
+ }
19
+
20
+ const OMP_BIN = process.env.OMP_BIN || 'omp';
21
+ const OMP_ARGS = readOmpArgs();
22
+ const OMP_PROVIDER_IDS = {
23
+ openai: 'openai',
24
+ 'openai-codex': 'openai-codex',
25
+ anthropic: 'anthropic',
26
+ copilot: 'github-copilot',
27
+ };
28
+
29
+ function providerOf(value) {
30
+ const provider = String(value || '').trim().toLowerCase();
31
+ return provider === 'omp' || Object.hasOwn(OMP_PROVIDER_IDS, provider) ? provider : '';
32
+ }
33
+
34
+ function ompProviderOf(provider) {
35
+ return OMP_PROVIDER_IDS[provider] || '';
36
+ }
37
+
38
+ function modelIdFromSelector(provider, selector) {
39
+ const value = String(selector || '').trim();
40
+ const ompProvider = ompProviderOf(provider);
41
+ if (value.startsWith(`${ompProvider}/`)) return value.slice(ompProvider.length + 1);
42
+ if (value.startsWith(`${provider}/`)) return value.slice(provider.length + 1);
43
+ return value;
44
+ }
45
+
46
+ function modelProviderId(model) {
47
+ if (typeof model?.provider === 'string') return model.provider;
48
+ if (typeof model?.provider?.id === 'string') return model.provider.id;
49
+ return '';
50
+ }
51
+
52
+ function modelSelector(provider, model) {
53
+ return `${provider}/${String(model?.id || '').trim()}`;
54
+ }
55
+
56
+ class OmpRpcClient {
57
+ constructor() {
58
+ this.child = null;
59
+ this.stdoutBuffer = '';
60
+ this.nextId = 1;
61
+ this.pending = new Map();
62
+ this.readyPromise = null;
63
+ this.readyReject = null;
64
+ this.activePrompt = null;
65
+ this.requestQueue = Promise.resolve();
66
+ }
67
+
68
+ async start() {
69
+ if (this.child) return;
70
+ if (this.readyPromise) return this.readyPromise;
71
+ this.readyPromise = new Promise((resolve, reject) => {
72
+ this.readyReject = reject;
73
+ const child = spawn(OMP_BIN, OMP_ARGS, {
74
+ env: process.env,
75
+ stdio: ['pipe', 'pipe', 'pipe'],
76
+ windowsHide: true,
77
+ });
78
+ this.child = child;
79
+ child.stdout.setEncoding('utf8');
80
+ child.stdout.on('data', (chunk) => this.readStdout(chunk, resolve, reject));
81
+ child.stderr.setEncoding('utf8');
82
+ child.stderr.on('data', (chunk) => process.stderr.write(`[omp] ${chunk}`));
83
+ child.once('error', (error) => this.fail(error));
84
+ child.once('exit', (code, signal) => {
85
+ if (this.child !== child) return;
86
+ this.child = null;
87
+ this.fail(new Error(`omp exited (${code ?? signal ?? 'unknown'})`));
88
+ });
89
+ });
90
+ return this.readyPromise;
91
+ }
92
+
93
+ readStdout(chunk, resolveReady, rejectReady) {
94
+ this.stdoutBuffer += chunk;
95
+ let newlineIndex = this.stdoutBuffer.indexOf('\n');
96
+ while (newlineIndex >= 0) {
97
+ const line = this.stdoutBuffer.slice(0, newlineIndex).trim();
98
+ this.stdoutBuffer = this.stdoutBuffer.slice(newlineIndex + 1);
99
+ if (line) {
100
+ try {
101
+ this.handleFrame(JSON.parse(line), resolveReady, rejectReady);
102
+ } catch (error) {
103
+ this.fail(error);
104
+ }
105
+ }
106
+ newlineIndex = this.stdoutBuffer.indexOf('\n');
107
+ }
108
+ }
109
+
110
+ handleFrame(frame, resolveReady, rejectReady) {
111
+ if (frame?.type === 'ready') {
112
+ this.readyReject = null;
113
+ resolveReady(frame);
114
+ return;
115
+ }
116
+ if (frame?.type === 'extension_ui_request') {
117
+ if (this.child?.stdin.writable) {
118
+ this.child.stdin.write(`${JSON.stringify({
119
+ type: 'extension_ui_response',
120
+ id: frame.id,
121
+ cancelled: true,
122
+ })}\n`);
123
+ }
124
+ return;
125
+ }
126
+ const active = this.activePrompt;
127
+ if (frame?.type === 'message_update' && active) {
128
+ const event = frame.assistantMessageEvent;
129
+ if (event?.type === 'text_delta' && typeof event.delta === 'string') active.parts.push(event.delta);
130
+ if (event?.type === 'error') this.finishPrompt(new Error(event.message || 'omp response failed'));
131
+ return;
132
+ }
133
+ if (frame?.type === 'agent_end' && active && frame.isTerminal !== false) {
134
+ this.finishPrompt(null, active.parts.join('').trim());
135
+ return;
136
+ }
137
+ if (frame?.type === 'prompt_result' && active && frame.id === active.id && frame.agentInvoked === false) {
138
+ this.finishPrompt(null, active.parts.join('').trim());
139
+ return;
140
+ }
141
+ if (frame?.type !== 'response' || !frame.id) return;
142
+ const pending = this.pending.get(frame.id);
143
+ if (!pending) return;
144
+ this.pending.delete(frame.id);
145
+ if (frame.command === 'prompt' && this.activePrompt?.id === frame.id) {
146
+ if (!frame.success) this.finishPrompt(new Error(frame.error || 'omp prompt failed'));
147
+ else if (frame.data?.agentInvoked === false) this.finishPrompt(null, '');
148
+ }
149
+ if (frame.success) pending.resolve(frame);
150
+ else pending.reject(new Error(frame.error || `omp ${frame.command || 'request'} failed`));
151
+ }
152
+
153
+ fail(error) {
154
+ const failure = error instanceof Error ? error : new Error(String(error));
155
+ if (this.readyReject) {
156
+ const reject = this.readyReject;
157
+ this.readyReject = null;
158
+ this.readyPromise = null;
159
+ reject(failure);
160
+ }
161
+ for (const pending of this.pending.values()) pending.reject(failure);
162
+ this.pending.clear();
163
+ if (this.activePrompt) this.finishPrompt(failure);
164
+ }
165
+
166
+ async request(type, body = {}) {
167
+ await this.start();
168
+ const id = `omp-${this.nextId++}`;
169
+ const frame = { id, type, ...body };
170
+ return new Promise((resolve, reject) => {
171
+ this.pending.set(id, { resolve, reject });
172
+ if (!this.child?.stdin.writable) {
173
+ this.pending.delete(id);
174
+ reject(new Error('omp RPC stdin is unavailable'));
175
+ return;
176
+ }
177
+ this.child.stdin.write(`${JSON.stringify(frame)}\n`);
178
+ }).then((response) => {
179
+ if (!response.success) throw new Error(response.error || `omp ${type} failed`);
180
+ return response.data || {};
181
+ });
182
+ }
183
+
184
+ async providers() {
185
+ const data = await this.request('get_login_providers');
186
+ return Array.isArray(data.providers) ? data.providers : [];
187
+ }
188
+
189
+ async models() {
190
+ const data = await this.request('get_available_models');
191
+ return Array.isArray(data.models) ? data.models : [];
192
+ }
193
+
194
+ async resolveModel(provider, requested) {
195
+ const requestedValue = String(requested || '').trim();
196
+ const models = await this.models();
197
+ if (provider === 'omp') {
198
+ const providers = await this.providers();
199
+ const authenticated = new Set(
200
+ providers.filter((entry) => entry?.authenticated).map((entry) => String(entry.id || ''))
201
+ );
202
+ const matches = models.filter((model) => authenticated.has(modelProviderId(model)));
203
+ const model = requestedValue
204
+ ? matches.find(
205
+ (candidate) =>
206
+ String(candidate.id) === requestedValue ||
207
+ modelSelector(modelProviderId(candidate), candidate) === requestedValue
208
+ )
209
+ : matches[0];
210
+ if (!model) {
211
+ throw new Error(
212
+ requestedValue
213
+ ? `Model ${requestedValue} is not available in omp`
214
+ : 'No authenticated omp model is available'
215
+ );
216
+ }
217
+ return model;
218
+ }
219
+
220
+ const ompProvider = ompProviderOf(provider);
221
+ const requestedId = modelIdFromSelector(provider, requestedValue);
222
+ const matches = models.filter((model) => modelProviderId(model) === ompProvider);
223
+ const model = requestedId
224
+ ? matches.find((candidate) => String(candidate.id) === requestedId)
225
+ : matches[0];
226
+ if (!model) {
227
+ throw new Error(
228
+ requestedId
229
+ ? `Model ${provider}/${requestedId} is not available in omp`
230
+ : `No authenticated ${provider} model is available in omp`
231
+ );
232
+ }
233
+ return model;
234
+ }
235
+
236
+ async complete(provider, requestedModel, prompt) {
237
+ const run = this.requestQueue.catch(() => undefined).then(async () => {
238
+ const model = await this.resolveModel(provider, requestedModel);
239
+ await this.request('new_session');
240
+ await this.request('set_model', {
241
+ provider: modelProviderId(model),
242
+ modelId: String(model.id),
243
+ });
244
+ const text = await new Promise((resolve, reject) => {
245
+ const id = `omp-${this.nextId++}`;
246
+ const timer = setTimeout(() => this.finishPrompt(new Error('omp prompt timed out')), REQUEST_TIMEOUT_MS);
247
+ this.activePrompt = { id, parts: [], timer, resolve, reject };
248
+ this.pending.set(id, { resolve: () => undefined, reject: () => undefined });
249
+ if (!this.child?.stdin.writable) {
250
+ this.finishPrompt(new Error('omp RPC stdin is unavailable'));
251
+ return;
252
+ }
253
+ this.child.stdin.write(`${JSON.stringify({ id, type: 'prompt', message: prompt })}\n`);
254
+ });
255
+ return { text, model: String(model.id) };
256
+ });
257
+ this.requestQueue = run.catch(() => undefined);
258
+ return run;
259
+ }
260
+
261
+ finishPrompt(error, text) {
262
+ const active = this.activePrompt;
263
+ if (!active) return;
264
+ clearTimeout(active.timer);
265
+ this.activePrompt = null;
266
+ this.pending.delete(active.id);
267
+ if (error) active.reject(error);
268
+ else active.resolve(text || '');
269
+ }
270
+
271
+ async stop() {
272
+ const child = this.child;
273
+ this.child = null;
274
+ this.readyPromise = null;
275
+ if (!child) return;
276
+ child.stdin.end();
277
+ await new Promise((resolve) => child.once('exit', resolve));
278
+ }
279
+ }
280
+
281
+ const omp = new OmpRpcClient();
282
+
283
+ function corsHeaders(origin) {
284
+ const headers = {
285
+ 'access-control-allow-headers': 'content-type',
286
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
287
+ 'content-type': 'application/json; charset=utf-8',
288
+ vary: 'Origin',
289
+ };
290
+ if (typeof origin === 'string' && origin.startsWith('chrome-extension://')) {
291
+ headers['access-control-allow-origin'] = origin;
292
+ }
293
+ return headers;
294
+ }
295
+
296
+ function sendJson(res, status, value, origin) {
297
+ const body = JSON.stringify(value);
298
+ res.writeHead(status, { ...corsHeaders(origin), 'content-length': Buffer.byteLength(body) });
299
+ res.end(body);
300
+ }
301
+
302
+ function readJson(req) {
303
+ return new Promise((resolve, reject) => {
304
+ let size = 0;
305
+ let body = '';
306
+ req.setEncoding('utf8');
307
+ req.on('data', (chunk) => {
308
+ size += Buffer.byteLength(chunk);
309
+ if (size > MAX_BODY_BYTES) {
310
+ reject(new Error('request too large'));
311
+ req.destroy();
312
+ return;
313
+ }
314
+ body += chunk;
315
+ });
316
+ req.on('end', () => {
317
+ if (!body.trim()) return resolve({});
318
+ try {
319
+ resolve(JSON.parse(body));
320
+ } catch {
321
+ reject(new Error('request body must be valid JSON'));
322
+ }
323
+ });
324
+ req.on('error', reject);
325
+ });
326
+ }
327
+
328
+ async function complete(body) {
329
+ const provider = providerOf(body.provider);
330
+ if (!provider) throw new Error('provider must be omp, openai, openai-codex, anthropic, or copilot');
331
+ const documentBlock = String(body.documentBlock || '').trim();
332
+ if (!documentBlock) throw new Error('documentBlock is required');
333
+ const systemPrompt = String(body.systemPrompt || '').trim();
334
+ const prompt = [
335
+ 'You are a terse autocomplete engine.',
336
+ 'Return only the completion text. Do not explain, use tools, or add markdown.',
337
+ systemPrompt,
338
+ documentBlock,
339
+ ].filter(Boolean).join('\n\n');
340
+ const result = await omp.complete(provider, body.model, prompt);
341
+ return {
342
+ provider,
343
+ model: result.model,
344
+ text: result.text,
345
+ };
346
+ }
347
+
348
+ async function authenticatedOmpProviderIds() {
349
+ const providers = await omp.providers();
350
+ return new Set(providers.filter((item) => item?.authenticated).map((item) => String(item.id)));
351
+ }
352
+
353
+ async function providerStatus(provider) {
354
+ if (provider === 'omp') {
355
+ const authenticatedIds = await authenticatedOmpProviderIds();
356
+ const authenticated = authenticatedIds.size > 0;
357
+ const models = authenticated
358
+ ? (await omp.models()).filter((item) => authenticatedIds.has(modelProviderId(item)))
359
+ : [];
360
+ return { ompProvider: 'omp', entry: undefined, authenticated, models };
361
+ }
362
+ const ompProvider = ompProviderOf(provider);
363
+ const providers = await omp.providers();
364
+ const entry = providers.find((item) => item?.id === ompProvider);
365
+ const authenticated = Boolean(entry?.authenticated);
366
+ const models = authenticated
367
+ ? (await omp.models()).filter((item) => modelProviderId(item) === ompProvider)
368
+ : [];
369
+ return { ompProvider, entry, authenticated, models };
370
+ }
371
+
372
+ async function probe(body) {
373
+ const provider = providerOf(body.provider);
374
+ if (!provider) throw new Error('provider must be omp, openai, openai-codex, anthropic, or copilot');
375
+ const status = await providerStatus(provider);
376
+ if (!status.authenticated) {
377
+ return {
378
+ ok: false,
379
+ provider,
380
+ ompProvider: status.ompProvider,
381
+ configured: false,
382
+ authenticated: false,
383
+ error: provider === 'omp'
384
+ ? 'Sign in to a provider with omp first: run "omp", then "/login <provider>"'
385
+ : `Sign in to ${status.ompProvider} with omp first: run "omp", then "/login ${status.ompProvider}"`,
386
+ };
387
+ }
388
+ let model;
389
+ try {
390
+ model = await omp.resolveModel(provider, body.model);
391
+ } catch (error) {
392
+ return {
393
+ ok: false,
394
+ provider,
395
+ ompProvider: status.ompProvider,
396
+ configured: true,
397
+ authenticated: true,
398
+ error: error instanceof Error ? error.message : 'No usable omp model found',
399
+ };
400
+ }
401
+ return {
402
+ ok: true,
403
+ provider,
404
+ ompProvider: status.ompProvider,
405
+ configured: true,
406
+ authenticated: true,
407
+ model: String(model.id),
408
+ models: status.models.map((item) => String(item.id)),
409
+ };
410
+ }
411
+
412
+ async function listProviders() {
413
+ const providers = await omp.providers();
414
+ return {
415
+ providers: providers.map((provider) => ({
416
+ id: provider.id,
417
+ name: provider.name,
418
+ available: Boolean(provider.available),
419
+ authenticated: Boolean(provider.authenticated),
420
+ })),
421
+ };
422
+ }
423
+
424
+ async function listModels(body = {}) {
425
+ const models = await omp.models();
426
+ const requested = providerOf(body.provider);
427
+ const authenticatedIds = requested === 'omp' ? await authenticatedOmpProviderIds() : null;
428
+ return {
429
+ models: models
430
+ .filter((model) => {
431
+ if (!requested) return true;
432
+ if (requested === 'omp') return authenticatedIds.has(modelProviderId(model));
433
+ return modelProviderId(model) === ompProviderOf(requested);
434
+ })
435
+ .map((model) => ({
436
+ id: String(model.id),
437
+ provider: modelProviderId(model),
438
+ name: model.name,
439
+ model: modelSelector(modelProviderId(model), model),
440
+ })),
441
+ };
442
+ }
443
+
444
+ async function handle(req, res) {
445
+ const origin = req.headers.origin;
446
+ const route = String(req.url || '').split('?')[0];
447
+ if (req.method === 'OPTIONS') {
448
+ res.writeHead(204, corsHeaders(origin));
449
+ res.end();
450
+ return;
451
+ }
452
+ if (route === '/health' && req.method === 'GET') {
453
+ sendJson(res, 200, { ok: true, service: 'vim-todo-ai-bridge', backend: 'omp-rpc' }, origin);
454
+ return;
455
+ }
456
+ if (route === '/v1/providers' && req.method === 'GET') {
457
+ try {
458
+ sendJson(res, 200, { ok: true, ...(await listProviders()) }, origin);
459
+ } catch (error) {
460
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : 'omp provider lookup failed' }, origin);
461
+ }
462
+ return;
463
+ }
464
+ if (route === '/v1/models' && (req.method === 'GET' || req.method === 'POST')) {
465
+ try {
466
+ const body = req.method === 'POST' ? await readJson(req) : {};
467
+ sendJson(res, 200, { ok: true, ...(await listModels(body)) }, origin);
468
+ } catch (error) {
469
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : 'omp model lookup failed' }, origin);
470
+ }
471
+ return;
472
+ }
473
+ if (route !== '/v1/complete' && route !== '/v1/probe') {
474
+ sendJson(res, 404, { ok: false, error: 'not found' }, origin);
475
+ return;
476
+ }
477
+ if (req.method !== 'POST') {
478
+ sendJson(res, 405, { ok: false, error: 'method not allowed' }, origin);
479
+ return;
480
+ }
481
+ try {
482
+ const body = await readJson(req);
483
+ const result = route === '/v1/probe' ? await probe(body) : await complete(body);
484
+ sendJson(res, 200, { ok: true, ...result }, origin);
485
+ } catch (error) {
486
+ sendJson(res, 400, { ok: false, error: error instanceof Error ? error.message : 'request failed' }, origin);
487
+ }
488
+ }
489
+
490
+ const server = http.createServer((req, res) => {
491
+ void handle(req, res);
492
+ });
493
+
494
+ server.listen(PORT, HOST, () => {
495
+ console.log(`vim-todo AI bridge listening on http://${HOST}:${PORT}`);
496
+ console.log(`Bridge backend: ${OMP_BIN} ${OMP_ARGS.join(' ')}`);
497
+ console.log('Authenticate providers in omp with: omp, then /login <provider>');
498
+ });
499
+
500
+ async function shutdown() {
501
+ await omp.stop().catch(() => undefined);
502
+ server.close(() => process.exit(0));
503
+ }
504
+
505
+ process.on('SIGINT', () => void shutdown());
506
+ process.on('SIGTERM', () => void shutdown());