oc-agent-router 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/README.md CHANGED
@@ -22,7 +22,8 @@ Set `TYPESAFE_API_KEY` in the environment that starts OpenCode, then configure t
22
22
  "anthropic/claude-sonnet-4-6",
23
23
  "google/gemini-3-pro"
24
24
  ],
25
- "fallbackModel": "anthropic/claude-sonnet-4-6"
25
+ "agents": ["general", "explore"],
26
+ "confidenceThreshold": 0.8
26
27
  }
27
28
  ]
28
29
  ]
@@ -33,23 +34,38 @@ All configured models must already be available in OpenCode. Restart OpenCode af
33
34
 
34
35
  `TYPESAFE_API_KEY` is read only from the environment of the OpenCode process. Do not put it in `opencode.json`.
35
36
 
37
+ ## Local Testing
38
+
39
+ This repository includes `.opencode/opencode.json`, which loads the built `dist/` plugin directory. Before starting OpenCode from this directory, build the plugin and update its `models` to model IDs enabled in your OpenCode configuration.
40
+
41
+ ```sh
42
+ npm run build
43
+ TYPESAFE_API_KEY=... opencode
44
+ ```
45
+
46
+ Ask OpenCode to delegate work with a `subagent`. A new child session will receive the model selected by Jev; resumed child sessions and calls with an explicit model are intentionally left unchanged. Restart OpenCode after changing the plugin source, build output, or `.opencode/opencode.json`.
47
+
48
+ To leave child sessions on their configured or inherited model, omit `TYPESAFE_API_KEY` or set a threshold higher than Jev's returned confidence.
49
+
36
50
  ## Options
37
51
 
38
52
  | Option | Default | Description |
39
53
  | --- | --- | --- |
40
54
  | `models` | Required | Non-empty allowed model list in `provider/model` form. |
41
- | `fallbackModel` | First model | Used when the API key is missing, Jev errors, times out, or returns an invalid choice. Must be in `models`. |
55
+ | `agents` | All subagents | Optional list of subagent IDs this plugin may route. An explicit empty list routes none. |
56
+ | `confidenceThreshold` | `0.8` | Minimum Jev choice confidence from 0 to 1 required to override the child model. |
57
+ | `instructions` | Built-in routing guidance | Instructions sent to Jev to guide its model choice. |
42
58
  | `jevModel` | `jev-latest` | TypeSafe model ID. Pin a version if routing behavior must be stable. |
43
59
  | `apiKeyEnv` | `TYPESAFE_API_KEY` | Environment variable containing the TypeSafe API key. |
44
60
  | `timeoutMs` | `5000` | Jev request deadline, from 100 to 30,000 ms. |
45
61
 
46
62
  ## How It Works
47
63
 
48
- The plugin uses the documented `tool.execute.before` hook, calls `POST https://api.typesafe.ai/v1/systemone` with a Choice question whose only choices are your allowed models, then sets the task's `model` field. It leaves the task's original `subagent_type` and description unchanged.
64
+ The plugin calls `POST https://api.typesafe.ai/v1/systemone` with a Choice question whose only choices are your allowed models, then supplies the selected model to OpenCode's native `subagent` tool immediately before it creates the child session. The original agent ID, system prompt, permissions, task, and display name remain unchanged.
49
65
 
50
- Task resumes (`task_id`) are deliberately not rerouted, so a resumed session keeps its original model. API failures never expand the configured model allowlist and use `fallbackModel` instead.
66
+ Child-session resumes (`sessionID`) are deliberately not rerouted, so a resumed session keeps its original model. Calls that explicitly select a model are also left unchanged. If Jev is unavailable, returns an invalid choice, or is below `confidenceThreshold`, the plugin leaves the model unset so OpenCode uses the configured agent model or parent session model.
51
67
 
52
- The routing request sends only the subagent type, short task description, and task prompt. It does not send session history, tool outputs, or API credentials.
68
+ The routing request sends only the subagent ID, short task description, and task prompt. It does not send session history, tool outputs, or API credentials.
53
69
 
54
70
  For example, a task that asks `general` to implement a parser sends the following payload. Its `Authorization` header is `Bearer $TYPESAFE_API_KEY`, which comes from the process environment rather than any config file.
55
71
 
@@ -75,4 +91,4 @@ For example, a task that asks `general` to implement a parser sends the followin
75
91
  }
76
92
  ```
77
93
 
78
- Every new task is eligible for routing, including configured and Markdown-defined subagents. Task resumes (`task_id`) retain their existing model.
94
+ Every new child session is eligible for routing, including configured and Markdown-defined subagents. Resumes (`sessionID`) retain their existing model.
package/dist/index.d.ts CHANGED
@@ -1,22 +1,32 @@
1
- import { Plugin } from '@opencode-ai/plugin';
1
+ import { Plugin } from '@opencode/plugin';
2
2
 
3
3
  interface RouterOptions {
4
4
  /** Models eligible to receive subagent tasks, in OpenCode provider/model form. */
5
5
  models: string[];
6
+ /** Subagent IDs eligible for routing. When omitted, all subagents are eligible. */
7
+ agents?: string[];
8
+ /** Minimum Jev choice confidence required to override the child model. Defaults to 0.8. */
9
+ confidenceThreshold?: number;
10
+ /** Routing guidance sent to Jev. */
11
+ instructions?: string;
6
12
  /** TypeSafe model ID used for routing. Defaults to jev-latest. */
7
13
  jevModel?: string;
8
14
  /** Environment variable containing the TypeSafe API key. Defaults to TYPESAFE_API_KEY. */
9
15
  apiKeyEnv?: string;
10
16
  /** Maximum time to wait for a route decision. Defaults to 5000. */
11
17
  timeoutMs?: number;
12
- /** Model to use when Jev is unavailable or returns an invalid answer. Defaults to the first model. */
13
- fallbackModel?: string;
14
18
  }
15
- interface TaskArgs {
19
+ interface ParsedRouterOptions extends Omit<Required<RouterOptions>, "agents"> {
20
+ agents?: string[];
21
+ }
22
+ interface SubagentArgs {
16
23
  description?: unknown;
17
24
  prompt?: unknown;
18
- subagent_type?: unknown;
19
- task_id?: unknown;
25
+ agent?: unknown;
26
+ /** An explicit model is not overridden by the router. */
27
+ model?: unknown;
28
+ /** Resumed child sessions keep their existing model. */
29
+ sessionID?: unknown;
20
30
  }
21
31
  interface FetchResponse {
22
32
  ok: boolean;
@@ -24,9 +34,9 @@ interface FetchResponse {
24
34
  json(): Promise<unknown>;
25
35
  }
26
36
  type Fetcher = (input: string, init: RequestInit) => Promise<FetchResponse>;
27
- declare function parseOptions(value: unknown): Required<RouterOptions>;
28
- declare function selectModel(options: Required<RouterOptions>, args: TaskArgs, apiKey: string | undefined, fetcher?: Fetcher): Promise<string>;
37
+ declare function parseOptions(value: unknown): ParsedRouterOptions;
38
+ declare function selectModel(options: ParsedRouterOptions, args: SubagentArgs, apiKey: string | undefined, fetcher?: Fetcher): Promise<string | undefined>;
29
39
 
30
- declare const plugin: Plugin;
40
+ declare const plugin: Plugin.Plugin;
31
41
 
32
42
  export { type RouterOptions, plugin as default, parseOptions, selectModel };
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ // src/index.ts
2
+ import { Plugin } from "@opencode/plugin";
3
+
1
4
  // src/router.ts
2
5
  function parseOptions(value) {
3
6
  if (!isRecord(value) || !Array.isArray(value.models)) {
@@ -7,47 +10,62 @@ function parseOptions(value) {
7
10
  if (models.length !== value.models.length || models.length === 0) {
8
11
  throw new Error("oc-agent-router models must be provider/model strings");
9
12
  }
10
- const fallbackModel = typeof value.fallbackModel === "string" ? value.fallbackModel : models[0];
11
- if (!models.includes(fallbackModel)) throw new Error("oc-agent-router fallbackModel must appear in models");
13
+ const agents = value.agents === void 0 ? void 0 : Array.isArray(value.agents) && value.agents.every((agent) => typeof agent === "string" && agent.trim()) ? value.agents : void 0;
14
+ if (value.agents !== void 0 && agents === void 0) {
15
+ throw new Error("oc-agent-router agents must be an array of non-empty agent IDs");
16
+ }
17
+ const confidenceThreshold = value.confidenceThreshold === void 0 ? 0.8 : typeof value.confidenceThreshold === "number" && Number.isFinite(value.confidenceThreshold) ? value.confidenceThreshold : void 0;
18
+ if (confidenceThreshold === void 0 || confidenceThreshold < 0 || confidenceThreshold > 1) {
19
+ throw new Error("oc-agent-router confidenceThreshold must be a number from 0 to 1");
20
+ }
12
21
  return {
13
22
  models,
23
+ agents,
24
+ confidenceThreshold,
25
+ instructions: typeof value.instructions === "string" && value.instructions.trim() ? value.instructions : "Choose the configured model most suitable for completing this OpenCode subagent task. Prefer a capable model for implementation, debugging, and complex reasoning; prefer an efficient model for focused exploration or simple tasks.",
14
26
  jevModel: typeof value.jevModel === "string" ? value.jevModel : "jev-latest",
15
27
  apiKeyEnv: typeof value.apiKeyEnv === "string" ? value.apiKeyEnv : "TYPESAFE_API_KEY",
16
- timeoutMs: typeof value.timeoutMs === "number" && value.timeoutMs >= 100 && value.timeoutMs <= 3e4 ? value.timeoutMs : 5e3,
17
- fallbackModel
28
+ timeoutMs: typeof value.timeoutMs === "number" && value.timeoutMs >= 100 && value.timeoutMs <= 3e4 ? value.timeoutMs : 5e3
18
29
  };
19
30
  }
20
31
  async function selectModel(options, args, apiKey, fetcher = fetch) {
21
- if (!apiKey) return options.fallbackModel;
32
+ if (!apiKey) {
33
+ return void 0;
34
+ }
22
35
  const controller = new AbortController();
23
36
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
24
37
  try {
38
+ const body = {
39
+ model: options.jevModel,
40
+ state: {
41
+ task: typeof args.prompt === "string" ? args.prompt : "",
42
+ description: typeof args.description === "string" ? args.description : "",
43
+ requested_agent: typeof args.agent === "string" ? args.agent : ""
44
+ },
45
+ questions: {
46
+ model: {
47
+ type: "choice",
48
+ instructions: options.instructions,
49
+ criteria: Object.fromEntries(options.models.map((model) => [model, `Use the configured OpenCode model ${model}.`]))
50
+ }
51
+ }
52
+ };
25
53
  const response = await fetcher("https://api.typesafe.ai/v1/systemone", {
26
54
  method: "POST",
27
55
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
28
- body: JSON.stringify({
29
- model: options.jevModel,
30
- state: {
31
- task: typeof args.prompt === "string" ? args.prompt : "",
32
- description: typeof args.description === "string" ? args.description : "",
33
- requested_agent: typeof args.subagent_type === "string" ? args.subagent_type : ""
34
- },
35
- questions: {
36
- model: {
37
- type: "choice",
38
- instructions: "Choose the configured model most suitable for completing this OpenCode subagent task. Prefer a capable model for implementation, debugging, and complex reasoning; prefer an efficient model for focused exploration or simple tasks.",
39
- criteria: Object.fromEntries(options.models.map((model) => [model, `Use the configured OpenCode model ${model}.`]))
40
- }
41
- }
42
- }),
56
+ body: JSON.stringify(body),
43
57
  signal: controller.signal
44
58
  });
45
- if (!response.ok) return options.fallbackModel;
46
- const body = await response.json();
47
- const choice = isRecord(body) && isRecord(body.answers) && isRecord(body.answers.model) ? body.answers.model.choice : void 0;
48
- return typeof choice === "string" && options.models.includes(choice) ? choice : options.fallbackModel;
59
+ const responseBody = await response.json();
60
+ if (!response.ok) return void 0;
61
+ const answer = isRecord(responseBody) && isRecord(responseBody.answers) && isRecord(responseBody.answers.model) ? responseBody.answers.model : void 0;
62
+ const choice = isRecord(answer) ? answer.choice : void 0;
63
+ const confidence = isRecord(answer) ? answer.confidence : void 0;
64
+ if (typeof choice !== "string" || !options.models.includes(choice) || typeof confidence !== "number" || !Number.isFinite(confidence) || confidence < options.confidenceThreshold)
65
+ return void 0;
66
+ return choice;
49
67
  } catch {
50
- return options.fallbackModel;
68
+ return void 0;
51
69
  } finally {
52
70
  clearTimeout(timeout);
53
71
  }
@@ -61,18 +79,20 @@ function isRecord(value) {
61
79
  }
62
80
 
63
81
  // src/index.ts
64
- var plugin = async (_input, rawOptions) => {
65
- const options = parseOptions(rawOptions);
66
- return {
67
- "tool.execute.before": async (input, output) => {
68
- if (input.tool !== "task") return;
69
- const args = output.args;
70
- if (typeof args.subagent_type !== "string" || typeof args.prompt !== "string" || args.task_id) return;
71
- const model = await selectModel(options, args, process.env[options.apiKeyEnv]);
72
- args.model = model;
73
- }
74
- };
75
- };
82
+ var plugin = Plugin.define({
83
+ id: "oc-agent-router",
84
+ async setup(ctx) {
85
+ const options = parseOptions(ctx.options);
86
+ await ctx.tool.hook("execute.before", async (event) => {
87
+ if (event.tool !== "subagent") return;
88
+ const input = event.input;
89
+ if (typeof input.agent !== "string" || typeof input.prompt !== "string" || input.model !== void 0 || input.sessionID !== void 0 || options.agents !== void 0 && !options.agents.includes(input.agent))
90
+ return;
91
+ const model = await selectModel(options, input, process.env[options.apiKeyEnv], fetch);
92
+ if (model !== void 0) input.model = model;
93
+ });
94
+ }
95
+ });
76
96
  var index_default = plugin;
77
97
  export {
78
98
  index_default as default,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-agent-router",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Route OpenCode subagent tasks to configured models with Jev.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,10 +28,10 @@
28
28
  "verify": "npm run check && npm test && npm run build"
29
29
  },
30
30
  "peerDependencies": {
31
- "@opencode-ai/plugin": ">=1.18.0"
31
+ "@opencode/plugin": "^2.0.0"
32
32
  },
33
33
  "devDependencies": {
34
- "@opencode-ai/plugin": "1.18.31",
34
+ "@opencode/plugin": "^2.0.15",
35
35
  "@types/node": "^24.0.0",
36
36
  "tsup": "^8.5.0",
37
37
  "tsx": "^4.20.0",