@subrouter/opencode 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,9 +6,9 @@ import path from 'node:path';
6
6
  import util from 'node:util';
7
7
  import { afterEach, beforeEach, expect, test } from 'vitest';
8
8
  import { createOpencodeClient } from '@opencode-ai/sdk';
9
- import { addAccount, adapters, loadAccounts, PROVIDER_DISPLAY_NAME, PROVIDER_IDS, savePreset, } from '@subrouter/cli';
9
+ import { addAccount, adapters, loadAccounts, PROVIDER_DISPLAY_NAME, PROVIDER_IDS, savePreset, setLiveRoute, } from '@subrouter/cli';
10
10
  import { subrouterAuthPlugin, subrouterPlugin } from "./index.js";
11
- import { revealRoutedModel, rewritePoweredByModelLine } from "./provider.js";
11
+ import { appendApplyPatchConstraint, applyPatchApiId, applyPatchConstraint, revealRoutedModel, rewritePoweredByModelLine, shouldUseApplyPatch, } from "./provider.js";
12
12
  const execFile = util.promisify(childProcess.execFile);
13
13
  let home;
14
14
  const openServers = [];
@@ -19,7 +19,6 @@ beforeEach(async () => {
19
19
  process.env.SUBROUTER_MODELS_DEV_URL = await startFakeModelsDev();
20
20
  });
21
21
  afterEach(async () => {
22
- delete process.env.SUBROUTER_HOME;
23
22
  delete process.env.SUBROUTER_OPENAI_ISSUER_URL;
24
23
  delete process.env.SUBROUTER_MODELS_DEV_URL;
25
24
  for (const server of openServers.splice(0)) {
@@ -148,7 +147,7 @@ test('provider log callback forwards only to client.app.log', async () => {
148
147
  extra: { provider: 'openai', modelId: 'gpt-5.5' },
149
148
  });
150
149
  });
151
- test('cooldown fallback creates only a persisted ignored notice after idle', async () => {
150
+ test('cooldown fallback persists one ignored notice during the active run', async () => {
152
151
  const requests = [];
153
152
  const server = createServer((req, res) => {
154
153
  const chunks = [];
@@ -175,26 +174,16 @@ test('cooldown fallback creates only a persisted ignored notice after idle', asy
175
174
  expect(onCooldownFallback).toBeTypeOf('function');
176
175
  if (typeof onCooldownFallback !== 'function')
177
176
  throw new Error('expected cooldown callback');
178
- await onCooldownFallback({
177
+ const notice = {
179
178
  sessionID: 'session-1',
180
179
  agent: 'build',
181
180
  variant: 'high',
182
181
  preset: 'work',
183
- preferred: { provider: 'xai', modelId: 'grok-4.6', retryAfterMs: 252_000 },
182
+ preferred: { provider: 'xai', modelId: 'grok-4.6', retryAfterMs: 250_000 },
184
183
  active: { provider: 'openai', modelId: 'gpt-5.6-sol' },
185
- });
186
- await onCooldownFallback({
187
- sessionID: 'session-1',
188
- agent: 'compaction',
189
- preset: 'work',
190
- preferred: { provider: 'xai', modelId: 'grok-4.6', retryAfterMs: 251_000 },
191
- active: { provider: 'anthropic', modelId: 'claude-sonnet-5' },
192
- });
193
- const event = {
194
- type: 'session.idle',
195
- properties: { sessionID: 'session-1' },
196
184
  };
197
- await hooks.event?.({ event });
185
+ await onCooldownFallback(notice);
186
+ await onCooldownFallback(notice);
198
187
  expect(requests).toEqual([
199
188
  {
200
189
  path: '/session/session-1/message?directory=%2Ftmp%2Fproject',
@@ -206,7 +195,7 @@ test('cooldown fallback creates only a persisted ignored notice after idle', asy
206
195
  parts: [
207
196
  {
208
197
  type: 'text',
209
- text: 'Subrouter: xai/grok-4.6 was rate limited. This message started with openai/gpt-5.6-sol.',
198
+ text: 'Subrouter: Using openai/gpt-5.6-sol because xai/grok-4.6 is rate limited.',
210
199
  ignored: true,
211
200
  },
212
201
  ],
@@ -287,10 +276,80 @@ test('preset model limits follow the first live candidate', async () => {
287
276
  input: 900_000,
288
277
  output: 128_000,
289
278
  });
290
- expect(config.provider?.subrouter?.models?.default?.limit).toEqual({
291
- context: 1_000_000,
292
- input: 900_000,
293
- output: 128_000,
279
+ });
280
+ test('preset reasoning follows the first live candidate', async () => {
281
+ const modelId = adapters.openai.defaultModels[0];
282
+ if (!modelId)
283
+ throw new Error('openai adapter has no default model');
284
+ process.env.SUBROUTER_MODELS_DEV_URL = await startFakeModelsDev({
285
+ openai: {
286
+ models: {
287
+ [modelId]: {
288
+ id: modelId,
289
+ reasoning: true,
290
+ modalities: { input: ['text'], output: ['text'] },
291
+ limit: { context: 200_000, output: 64_000 },
292
+ },
293
+ },
294
+ },
295
+ });
296
+ await addAccount({
297
+ provider: 'openai',
298
+ account: {
299
+ type: 'oauth',
300
+ refresh: 'refresh-1',
301
+ access: 'access-1',
302
+ expires: Date.now() + 60_000,
303
+ email: 'a@x.com',
304
+ addedAt: 1,
305
+ lastUsed: 1,
306
+ },
307
+ });
308
+ await savePreset({ name: 'work', models: [`openai/${modelId}`] });
309
+ const hooks = await subrouterPlugin(pluginInput);
310
+ const config = {};
311
+ await hooks.config?.(config);
312
+ expect(config.provider?.subrouter?.models?.work?.reasoning).toBe(true);
313
+ });
314
+ test('preset variants follow the first live candidate', async () => {
315
+ const modelId = adapters.openai.defaultModels[0];
316
+ if (!modelId)
317
+ throw new Error('openai adapter has no default model');
318
+ process.env.SUBROUTER_MODELS_DEV_URL = await startFakeModelsDev({
319
+ openai: {
320
+ models: {
321
+ [modelId]: {
322
+ id: modelId,
323
+ reasoning: true,
324
+ modalities: { input: ['text'], output: ['text'] },
325
+ reasoning_options: [{ type: 'effort', values: ['none', 'low', 'medium', 'high'] }],
326
+ },
327
+ },
328
+ },
329
+ });
330
+ await addAccount({
331
+ provider: 'openai',
332
+ account: {
333
+ type: 'oauth',
334
+ refresh: 'refresh-1',
335
+ access: 'access-1',
336
+ expires: Date.now() + 60_000,
337
+ email: 'a@x.com',
338
+ addedAt: 1,
339
+ lastUsed: 1,
340
+ },
341
+ });
342
+ await savePreset({ name: 'work', models: [`openai/${modelId}#high`] });
343
+ const hooks = await subrouterPlugin(pluginInput);
344
+ const config = {};
345
+ await hooks.config?.(config);
346
+ expect(config.provider?.subrouter?.models?.work).toMatchObject({
347
+ variants: {
348
+ none: { reasoningEffort: 'none', reasoningSummary: 'auto' },
349
+ low: { reasoningEffort: 'low', reasoningSummary: 'auto' },
350
+ medium: { reasoningEffort: 'medium', reasoningSummary: 'auto' },
351
+ high: { reasoningEffort: 'high', reasoningSummary: 'auto' },
352
+ },
294
353
  });
295
354
  });
296
355
  test('preset model input modalities are the union of usable candidates', async () => {
@@ -404,6 +463,80 @@ test('Anthropic-compatible coding plans do not advertise video input', async ()
404
463
  },
405
464
  });
406
465
  });
466
+ test('OpenCode apply_patch matcher follows gpt- and skips gpt-4 and gpt-oss', () => {
467
+ expect(shouldUseApplyPatch('gpt-5.5')).toBe(true);
468
+ expect(shouldUseApplyPatch('gpt-5.4')).toBe(true);
469
+ expect(shouldUseApplyPatch('gpt-5.3-codex')).toBe(true);
470
+ expect(shouldUseApplyPatch('gpt-4.1')).toBe(false);
471
+ expect(shouldUseApplyPatch('gpt-oss-120b')).toBe(false);
472
+ expect(shouldUseApplyPatch('claude-opus-4-6')).toBe(false);
473
+ });
474
+ test('apply_patch api ids stay unique across presets that share a model', () => {
475
+ const taken = new Set();
476
+ const first = applyPatchApiId({ preset: 'codex-a', modelId: 'gpt-5.5', taken });
477
+ taken.add(first);
478
+ const second = applyPatchApiId({ preset: 'codex-b', modelId: 'gpt-5.5', taken });
479
+ expect(first).toBe('gpt-5.5');
480
+ expect(second).toBe('gpt-5.5:codex-b');
481
+ expect(shouldUseApplyPatch(second)).toBe(true);
482
+ });
483
+ test('appendApplyPatchConstraint adds the OpenCode GPT line once', () => {
484
+ const system = ['You are powered by the model named gpt-5.5.'];
485
+ appendApplyPatchConstraint({ system, modelId: 'gpt-5.5' });
486
+ appendApplyPatchConstraint({ system, modelId: 'gpt-5.5' });
487
+ expect(system).toEqual(['You are powered by the model named gpt-5.5.', applyPatchConstraint('gpt-5.5')]);
488
+ });
489
+ test('appendApplyPatchConstraint skips non-GPT models', () => {
490
+ const system = ['You are powered by the model named claude-opus-4-6.'];
491
+ appendApplyPatchConstraint({ system, modelId: 'claude-opus-4-6' });
492
+ expect(system).toEqual(['You are powered by the model named claude-opus-4-6.']);
493
+ });
494
+ test('openai live candidate spoofs a gpt api id so OpenCode prefers apply_patch', async () => {
495
+ await addAccount({
496
+ provider: 'anthropic',
497
+ account: {
498
+ type: 'oauth',
499
+ refresh: 'refresh-1',
500
+ access: 'access-1',
501
+ expires: Date.now() + 60_000,
502
+ email: 'a@x.com',
503
+ addedAt: 1,
504
+ lastUsed: 1,
505
+ },
506
+ });
507
+ await addAccount({
508
+ provider: 'openai',
509
+ account: {
510
+ type: 'oauth',
511
+ refresh: 'refresh-o',
512
+ access: 'access-o',
513
+ expires: Date.now() + 60_000,
514
+ email: 'o@x.com',
515
+ addedAt: 1,
516
+ lastUsed: 1,
517
+ },
518
+ });
519
+ await savePreset({ name: 'default', models: ['anthropic/claude-opus-4-6'] });
520
+ await savePreset({ name: 'openai-only', models: ['openai/gpt-5.5'] });
521
+ await savePreset({ name: 'codex-b', models: ['openai/gpt-5.5'] });
522
+ const hooks = await subrouterPlugin(pluginInput);
523
+ const config = {};
524
+ await hooks.config?.(config);
525
+ expect(config.provider?.subrouter?.models?.work).toBeUndefined();
526
+ expect(config.provider?.subrouter?.models?.['openai-only']).toMatchObject({
527
+ name: 'openai-only',
528
+ id: 'gpt-5.5',
529
+ });
530
+ expect(config.provider?.subrouter?.models?.['codex-b']).toMatchObject({
531
+ name: 'codex-b',
532
+ id: 'gpt-5.5:codex-b',
533
+ });
534
+ expect(config.provider?.subrouter?.models?.default?.id).toBeUndefined();
535
+ expect(config.provider?.subrouter?.options?.presetByApiId).toEqual({
536
+ 'gpt-5.5': 'openai-only',
537
+ 'gpt-5.5:codex-b': 'codex-b',
538
+ });
539
+ });
407
540
  test('rewrites the OpenCode powered-by line to the routed candidate', () => {
408
541
  const system = [
409
542
  'You are powered by the model named build. The exact model ID is subrouter/build\n<env>\n Working directory: /tmp\n</env>',
@@ -438,6 +571,78 @@ test('system transform rewrites the powered-by line to the live candidate', asyn
438
571
  expect(system[0]).toContain(`The exact model ID is anthropic/${modelId}`);
439
572
  expect(system[0]).not.toContain('subrouter/build');
440
573
  });
574
+ test('system transform uses the in-flight session route, not the first free preset model', async () => {
575
+ await addAccount({
576
+ provider: 'anthropic',
577
+ account: {
578
+ type: 'oauth',
579
+ refresh: 'refresh-1',
580
+ access: 'access-1',
581
+ expires: Date.now() + 60_000,
582
+ email: 'a@x.com',
583
+ addedAt: 1,
584
+ lastUsed: 1,
585
+ },
586
+ });
587
+ await addAccount({
588
+ provider: 'opencode-go',
589
+ account: { type: 'api', key: 'zen-key', addedAt: 1, lastUsed: 1 },
590
+ });
591
+ await savePreset({
592
+ name: 'default',
593
+ models: ['anthropic/claude-fake', 'opencode-go/fake-model'],
594
+ });
595
+ await setLiveRoute({
596
+ sessionID: 'ses_1',
597
+ preset: 'default',
598
+ provider: 'opencode-go',
599
+ modelId: 'fake-model',
600
+ });
601
+ const system = [
602
+ 'You are powered by the model named default. The exact model ID is subrouter/default',
603
+ ];
604
+ await revealRoutedModel({
605
+ providerID: 'subrouter',
606
+ preset: 'default',
607
+ sessionID: 'ses_1',
608
+ system,
609
+ });
610
+ expect(system[0]).toContain('You are powered by the model named fake-model.');
611
+ expect(system[0]).toContain('The exact model ID is opencode-go/fake-model');
612
+ expect(system[0]).not.toContain('claude-fake');
613
+ });
614
+ test('system transform appends the apply_patch constraint for a live GPT route', async () => {
615
+ await addAccount({
616
+ provider: 'openai',
617
+ account: {
618
+ type: 'oauth',
619
+ refresh: 'refresh-o',
620
+ access: 'access-o',
621
+ expires: Date.now() + 60_000,
622
+ email: 'o@x.com',
623
+ addedAt: 1,
624
+ lastUsed: 1,
625
+ },
626
+ });
627
+ await savePreset({ name: 'openai-only', models: ['openai/gpt-5.5'] });
628
+ await setLiveRoute({
629
+ sessionID: 'ses_gpt',
630
+ preset: 'openai-only',
631
+ provider: 'openai',
632
+ modelId: 'gpt-5.5',
633
+ });
634
+ const system = [
635
+ 'You are powered by the model named openai-only. The exact model ID is subrouter/openai-only',
636
+ ];
637
+ await revealRoutedModel({
638
+ providerID: 'subrouter',
639
+ preset: 'openai-only',
640
+ sessionID: 'ses_gpt',
641
+ system,
642
+ });
643
+ expect(system[0]).toContain('You are powered by the model named gpt-5.5.');
644
+ expect(system).toContain(applyPatchConstraint('gpt-5.5'));
645
+ });
441
646
  test('system transform leaves other providers unchanged', async () => {
442
647
  const original = 'You are powered by the model named claude-opus-4-6. The exact model ID is anthropic/claude-opus-4-6';
443
648
  const system = [original];
@@ -1,10 +1,23 @@
1
1
  /**
2
2
  * Provider entry loaded by opencode via `provider.subrouter.npm` (file:// URL).
3
3
  * OpenCode imports this module, calls the first export starting with `create`,
4
- * then `sdk.languageModel(modelId)` where modelId is a subrouter preset name.
5
- * Also rewrites OpenCode's powered-by identity to the live routed model.
4
+ * then `sdk.languageModel(modelId)`. For GPT presets that id is a spoofed
5
+ * `gpt-*` api id so OpenCode prefers apply_patch; createSubrouter maps it
6
+ * back to the preset. Also rewrites OpenCode's powered-by identity to the
7
+ * live routed model and appends the GPT apply_patch constraint when needed.
6
8
  */
7
9
  export { createSubrouter } from '@subrouter/cli';
10
+ export declare function shouldUseApplyPatch(modelId: string): boolean;
11
+ export declare function applyPatchApiId({ preset, modelId, taken, }: {
12
+ preset: string;
13
+ modelId: string;
14
+ taken: Set<string>;
15
+ }): string;
16
+ export declare function applyPatchConstraint(modelId: string): "Always use apply_patch for manual code edits. Do not use cat or any other commands when creating or editing files. Formatting commands or bulk edits don't need to be done with apply_patch." | "Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).";
17
+ export declare function appendApplyPatchConstraint({ system, modelId, }: {
18
+ system: string[];
19
+ modelId: string;
20
+ }): void;
8
21
  export declare function rewritePoweredByModelLine({ system, candidate, }: {
9
22
  system: string[];
10
23
  candidate: {
@@ -12,26 +25,32 @@ export declare function rewritePoweredByModelLine({ system, candidate, }: {
12
25
  modelId: string;
13
26
  };
14
27
  }): void;
15
- export declare function revealRoutedModel({ providerID, preset, system, }: {
28
+ export declare function revealRoutedModel({ providerID, preset, sessionID, system, }: {
16
29
  providerID: string;
17
30
  preset: string;
31
+ sessionID?: string;
18
32
  system: string[];
19
33
  }): Promise<void>;
20
- export declare function addSubrouterHeaders(input: {
21
- sessionID: string;
22
- agent: string;
23
- model: {
24
- providerID: string;
25
- };
26
- message: {
34
+ export declare function addSubrouterHeaders({ input, output, affinityKey, }: {
35
+ input: {
36
+ sessionID: string;
27
37
  agent: string;
28
38
  model: {
29
39
  providerID: string;
30
- modelID: string;
31
- variant?: string;
40
+ };
41
+ message: {
42
+ id: string;
43
+ agent: string;
44
+ model: {
45
+ providerID: string;
46
+ modelID: string;
47
+ variant?: string;
48
+ };
32
49
  };
33
50
  };
34
- }, output: {
35
- headers: Record<string, string>;
36
- }): void;
51
+ output: {
52
+ headers: Record<string, string>;
53
+ };
54
+ affinityKey?: string;
55
+ }): string | null;
37
56
  //# sourceMappingURL=provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAIhD,wBAAgB,yBAAyB,CAAC,EACxC,MAAM,EACN,SAAS,GACV,EAAE;IACD,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,SAAS,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CACjD,QAKA;AAED,wBAAsB,iBAAiB,CAAC,EACtC,UAAU,EACV,MAAM,EACN,MAAM,GACP,EAAE;IACD,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,EAAE,CAAA;CACjB,iBAKA;AAED,wBAAgB,mBAAmB,CACjC,KAAK,EAAE;IACL,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7B,OAAO,EAAE;QACP,KAAK,EAAE,MAAM,CAAA;QACb,KAAK,EAAE;YAAE,UAAU,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;KACjE,CAAA;CACF,EACD,MAAM,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,QAW5C"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAYH,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAKhD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,WAElD;AAED,wBAAgB,eAAe,CAAC,EAC9B,MAAM,EACN,OAAO,EACP,KAAK,GACN,EAAE;IACD,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CACnB,UAGA;AAQD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,+iBAGnD;AAED,wBAAgB,0BAA0B,CAAC,EACzC,MAAM,EACN,OAAO,GACR,EAAE;IACD,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;CAChB,QAKA;AAED,wBAAgB,yBAAyB,CAAC,EACxC,MAAM,EACN,SAAS,GACV,EAAE;IACD,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,SAAS,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CACjD,QAKA;AAED,wBAAsB,iBAAiB,CAAC,EACtC,UAAU,EACV,MAAM,EACN,SAAS,EACT,MAAM,GACP,EAAE;IACD,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,EAAE,CAAA;CACjB,iBAMA;AAED,wBAAgB,mBAAmB,CAAC,EAClC,KAAK,EACL,MAAM,EACN,WAA8B,GAC/B,EAAE;IACD,KAAK,EAAE;QACL,SAAS,EAAE,MAAM,CAAA;QACjB,KAAK,EAAE,MAAM,CAAA;QACb,KAAK,EAAE;YAAE,UAAU,EAAE,MAAM,CAAA;SAAE,CAAA;QAC7B,OAAO,EAAE;YACP,EAAE,EAAE,MAAM,CAAA;YACV,KAAK,EAAE,MAAM,CAAA;YACb,KAAK,EAAE;gBAAE,UAAU,EAAE,MAAM,CAAC;gBAAC,OAAO,EAAE,MAAM,CAAC;gBAAC,OAAO,CAAC,EAAE,MAAM,CAAA;aAAE,CAAA;SACjE,CAAA;KACF,CAAA;IACD,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAA;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,iBAYA"}
package/dist/provider.js CHANGED
@@ -1,31 +1,59 @@
1
1
  /**
2
2
  * Provider entry loaded by opencode via `provider.subrouter.npm` (file:// URL).
3
3
  * OpenCode imports this module, calls the first export starting with `create`,
4
- * then `sdk.languageModel(modelId)` where modelId is a subrouter preset name.
5
- * Also rewrites OpenCode's powered-by identity to the live routed model.
4
+ * then `sdk.languageModel(modelId)`. For GPT presets that id is a spoofed
5
+ * `gpt-*` api id so OpenCode prefers apply_patch; createSubrouter maps it
6
+ * back to the preset. Also rewrites OpenCode's powered-by identity to the
7
+ * live routed model and appends the GPT apply_patch constraint when needed.
6
8
  */
7
- import { OPENCODE_AGENT_HEADER, OPENCODE_VARIANT_HEADER, OPENAI_WEBSOCKET_SESSION_HEADER, OPENAI_WEBSOCKET_TITLE_HEADER, PROVIDER_ID, resolveActiveCandidate, } from '@subrouter/cli';
9
+ import { OPENCODE_AGENT_HEADER, OPENCODE_VARIANT_HEADER, OPENAI_WEBSOCKET_SESSION_HEADER, OPENAI_WEBSOCKET_TITLE_HEADER, PROVIDER_ID, resolveLiveModel, ROUTE_AFFINITY_HEADER, } from '@subrouter/cli';
8
10
  export { createSubrouter } from '@subrouter/cli';
9
11
  const POWERED_BY_MODEL = /You are powered by the model named [^\n]+/;
12
+ // OpenCode v1 registry.ts and v2 patch.ts: GPT (not gpt-4 / gpt-oss) uses apply_patch.
13
+ export function shouldUseApplyPatch(modelId) {
14
+ return modelId.includes('gpt-') && !modelId.includes('oss') && !modelId.includes('gpt-4');
15
+ }
16
+ export function applyPatchApiId({ preset, modelId, taken, }) {
17
+ if (!taken.has(modelId))
18
+ return modelId;
19
+ return `${modelId}:${preset}`;
20
+ }
21
+ const APPLY_PATCH_GPT = 'Always use apply_patch for manual code edits. Do not use cat or any other commands when creating or editing files. Formatting commands or bulk edits don\'t need to be done with apply_patch.';
22
+ const APPLY_PATCH_CODEX = 'Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).';
23
+ export function applyPatchConstraint(modelId) {
24
+ if (modelId.includes('codex'))
25
+ return APPLY_PATCH_CODEX;
26
+ return APPLY_PATCH_GPT;
27
+ }
28
+ export function appendApplyPatchConstraint({ system, modelId, }) {
29
+ if (!shouldUseApplyPatch(modelId))
30
+ return;
31
+ const constraint = applyPatchConstraint(modelId);
32
+ if (system.some((line) => line.includes('use apply_patch')))
33
+ return;
34
+ system.push(constraint);
35
+ }
10
36
  export function rewritePoweredByModelLine({ system, candidate, }) {
11
37
  const line = `You are powered by the model named ${candidate.modelId}. The exact model ID is ${candidate.provider}/${candidate.modelId}`;
12
38
  for (let i = 0; i < system.length; i++) {
13
39
  system[i] = system[i].replace(POWERED_BY_MODEL, line);
14
40
  }
15
41
  }
16
- export async function revealRoutedModel({ providerID, preset, system, }) {
42
+ export async function revealRoutedModel({ providerID, preset, sessionID, system, }) {
17
43
  if (providerID !== PROVIDER_ID)
18
44
  return;
19
- const candidate = await resolveActiveCandidate(preset);
45
+ const candidate = await resolveLiveModel({ preset, sessionID });
20
46
  if (!candidate)
21
47
  return;
22
48
  rewritePoweredByModelLine({ system, candidate });
49
+ appendApplyPatchConstraint({ system, modelId: candidate.modelId });
23
50
  }
24
- export function addSubrouterHeaders(input, output) {
51
+ export function addSubrouterHeaders({ input, output, affinityKey = input.message.id, }) {
25
52
  if (input.model.providerID !== PROVIDER_ID)
26
- return;
53
+ return null;
27
54
  output.headers[OPENAI_WEBSOCKET_SESSION_HEADER] = input.sessionID;
28
55
  if (input.agent === input.message.agent) {
56
+ output.headers[ROUTE_AFFINITY_HEADER] = affinityKey;
29
57
  output.headers[OPENCODE_AGENT_HEADER] = input.message.agent;
30
58
  if (input.message.model.variant) {
31
59
  output.headers[OPENCODE_VARIANT_HEADER] = input.message.model.variant;
@@ -33,4 +61,5 @@ export function addSubrouterHeaders(input, output) {
33
61
  }
34
62
  if (input.agent === 'title')
35
63
  output.headers[OPENAI_WEBSOCKET_TITLE_HEADER] = 'true';
64
+ return output.headers[ROUTE_AFFINITY_HEADER] ?? null;
36
65
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subrouter/opencode",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin that registers the subrouter provider: cycle through your personal AI subscriptions when one hits rate limits.",
6
6
  "main": "./dist/index.js",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "errore": "^0.14.1",
47
- "@subrouter/cli": "^0.5.0"
47
+ "@subrouter/cli": "^0.6.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@opencode-ai/plugin": "^1.18.23",