diff --git a/AGENTS.md b/AGENTS.md index 27a56fc..b39fc6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,9 @@ typecheck + test. 3. **Trim, don't pin.** Only the `tools` array is modified; `tool_choice` is never touched (providers reject forced `tool_choice` in thinking mode, HTTP 400). 4. **Responses-API built-in tools** (`type !== "function"`) are never offered - to Jev and never trimmed to. + to Jev and never trimmed to — and they always survive the trim: Jev may + only demote function tools, never delete capabilities it was forbidden to + consider (issue #12 verdict). 5. **Unconfigured = invisible.** No `apiKey` → no hook registered, no log file, zero latency. 6. **The 401/403 latch** (`jevAuthFailed`) disables routing for the process diff --git a/README.md b/README.md index 495e525..fe3400a 100644 --- a/README.md +++ b/README.md @@ -133,19 +133,37 @@ Jev must never break a session. The request passes through **untouched** on: low failure, timeout, parse errors, or an invalid API key (latched off after the first 401/403 — zero added latency afterwards). Only primary agent-loop requests are considered (`event.kind === "primary"`); title/compaction traffic is skipped. Responses-API built-in tools -(`type !== "function"`) are never offered to Jev and never trimmed to. +(`type !== "function"`) are never offered to Jev, never trimmed to, and never removed by a trim — +they always survive (issue #12 verdict: Jev may only demote function tools). ### Reading the decision log Every decision is appended to the debug log — `tail -f /tmp/opencode-jev.log` to watch routing live. Each request ends in one tagged line: -- **`apply:`** — Jev acted; tools trimmed to its pick. +- **`apply:`** — Jev acted; tools trimmed to its pick (+ any built-ins kept). - **`bypass:`** — request untouched, with the reason. Line-by-line interpretation: [docs/DEVELOPMENT.md — "Reading the decision log"](./docs/DEVELOPMENT.md#reading-the-decision-log). +## Privacy + +With routing active, every eligible request POSTs a compact snapshot to `apiUrl` (default +`https://api.typesafe.ai/v1/systemone` — TypeSafe's endpoint; override with the `apiUrl` config +field or `JEV_API_URL`). The snapshot contains: + +- **`state`** — the first user message plus the last 4 conversation turns, each turn capped at + 2 KB and the whole payload at 8 KB. In a coding agent those turns routinely contain file + contents, tool output, and error messages — treat this like sending context to another model + provider. +- **Tool names** — up to the first 254 names, offered as routing choices. Names only, never + schemas or descriptions. + +No `apiKey` configured = no hook registered = nothing ever leaves your machine. If conversation +egress is not acceptable at all, leave the plugin unconfigured or point `apiUrl` at a self-hosted +Jev-compatible endpoint. + ## Development Full developer guide — architecture, unit testing, local manual testing with OpenCode, PR diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index ae8be45..a88fbf2 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -63,7 +63,10 @@ inspection` → `Jev client` → `interception core` → `transport` → `entryp mode (HTTP 400, verified live). Only the `tools` array is modified; `tool_choice` is passed through byte-for-byte. 4. **Responses-API built-ins are never offered to Jev** (`toolNames` skips - `type !== "function"`) — they cannot be trimmed-to-one either. + `type !== "function"`) — they cannot be trimmed-to-one and are never + removed by a trim either: they always pass through (issue #12 verdict). + Consequence: a payload with at most one function tool has nothing left for + Jev to decide and skips the round-trip. 5. **Unconfigured = invisible.** No hook, no log file touched, no latency. 6. **The 401/403 latch** (`jevAuthFailed`) disables routing for the process lifetime; don't turn it into a per-request retry. @@ -238,16 +241,19 @@ grep -c 'bypass:' /tmp/opencode-jev.log # requests handed to the LLM untouched | Line | Meaning | What the reasoning model received | | --- | --- | --- | | `apply: tools trimmed to X only (X@0.91 >= minConfidence 0.75)` | **jev acted.** Its pick cleared the threshold. | Only tool `X` — it executes instead of deciding. | +| `apply: tools trimmed to X (+ N built-ins kept) (...)` | Same, on Responses-API payloads carrying built-ins. | Tool `X` plus the untouched built-ins — Jev never removes what it never saw. | | `bypass: jev choice X@0.53 below minConfidence 0.8 — ...` | Jev picked a tool but wasn't sure enough. | Full tool list, normal deliberation. | | `bypass: jev says answer directly (respond_to_user@0.81) — ...` | Jev voted "no tool needed". Never forces this — trimming has nothing to target, and stripping all tools on a cheap model's word is too destructive. | Full tool list; the big model may still answer directly or use a tool. | | `bypass: jev choice X is not among this request's tools — ...` | Jev hallucinated/held a stale tool name. | Full tool list. | | `bypass: jev choice X listed but missing from payload — ...` | Name passed the criteria list but matched no payload entry (format mismatch edge case). | Full tool list. | | `bypass: jev unavailable (see preceding 'jev ...' error line) — ...` | The round-trip failed; the **preceding** error line names why. | Full tool list. | -Error/context lines that precede a `bypass: jev unavailable`: +Error/context lines that precede a `bypass: jev unavailable`, plus the +`note:` line (which can precede **any** tagged line, `apply:` included): | Line | Meaning | | --- | --- | +| `note: N tools exceed criteria cap 254 — first 254 offered to jev` | Payload has more than 254 function tools; the excess is invisible to Jev's choice (a pick among the kept tools still trims correctly). Operator awareness only — behavior unchanged. | | `jev http 500` (or any non-401/403 status) | Transient provider failure — plugin keeps trying next request. | | `jev http 401 (invalid key, routing disabled)` | **Latched off.** Auth failed; all later requests bypass silently with zero jev round-trips and **no further log lines**. Fix the key and restart OpenCode. | | `jev answer malformed` | Jev's JSON didn't parse into `{choice, confidence}`. | @@ -263,13 +269,15 @@ rebuild threw; the consumed original is passed through as the last resort). Silent paths (no log line by design, request simply untouched): non-POST / non-target URLs, non-primary `event.kind` (title, compaction), -payloads with no usable tools, payloads whose single function tool is the only entry in `tools`, and everything after the 401 latch. If the +payloads with at most one function tool (built-ins survive the trim, so no +trim can change anything), and everything after the 401 latch. If the log goes quiet mid-session, check for a latch line first. ### Verify trimming actually happened Start any OpenCode session that triggers tool use; in the log, `apply:` means the outbound request's `tools` array was trimmed to the chosen tool +plus any Responses-API built-ins (which are never removed) and the model had no choice. Confirm the session behaves normally — that's the whole safety contract. @@ -300,7 +308,8 @@ export JEV_API_URL=http://localhost:9999 TYPESAFE_API_KEY=*** The echoed body is exactly what Jev sees (`state`, `criteria`, `model`). Returning `"read"` at 0.99 makes the log show `apply: tools trimmed to read -only ...` on every request that offers the `read` tool — proof the trim path +only ...` on every request that offers `read` alongside another function tool +(the lone-candidate case skips the round-trip) — proof the trim path works end to end without a network dependency — keep the trial session short, every tool turn is now a `read`. Change `choice` to `"respond_to_user"` or `confidence` to `0.1` to watch the `bypass:` paths diff --git a/src/index.ts b/src/index.ts index b97f5fc..8c27267 100644 --- a/src/index.ts +++ b/src/index.ts @@ -268,18 +268,26 @@ function targetOf(url: string): Target | undefined { return undefined; } +// Responses-API built-ins (web_search, file_search, namespace groups, ...): +// typed entries that are not plain function tools. Chat/Anthropic tools carry +// no `type` and are NOT built-ins. +function isBuiltIn(tool: unknown): boolean { + if (typeof tool !== "object" || tool === null) return false; + const type = (tool as { type?: unknown }).type; + return type !== undefined && type !== "function"; +} + function toolNames(tools: unknown[]): string[] { const names: string[] = []; for (const tool of tools) { if (typeof tool !== "object" || tool === null) continue; + // Responses API built-ins cannot be pinned via tool_choice, so only + // plain function tools become candidates. + if (isBuiltIn(tool)) continue; const record = tool as { name?: unknown; - type?: unknown; function?: { name?: unknown }; }; - // Responses API built-ins (web_search, file_search, namespace groups, ...) - // cannot be pinned via tool_choice, so only keep plain function tools. - if (record.type !== undefined && record.type !== "function") continue; const name = typeof record.name === "string" ? record.name @@ -339,6 +347,10 @@ async function askJev( state: string, names: string[], ): Promise { + if (names.length > MAX_CRITERIA - 1) + log( + `note: ${names.length} tools exceed criteria cap ${MAX_CRITERIA - 1} — first ${MAX_CRITERIA - 1} offered to jev`, + ); const criteria: Record = { respond_to_user: "Task is complete, or clarification from user is required", }; @@ -402,11 +414,10 @@ async function routePayload( payload: Record, ): Promise { const names = toolNames(payload.tools as unknown[]); - // No usable candidate, or a lone candidate with nothing else in the payload: - // trimming can only reproduce the original tools array, so there is no - // decision for Jev and the round-trip would be pure added latency. - // (A built-in alongside the lone tool still counts — trimming drops it.) - if (names.length === 0 || (names.length === 1 && (payload.tools as unknown[]).length === 1)) { + // No usable candidate, or a lone candidate: trimming can only reproduce the + // original tools array — built-ins always pass through untouched — so there + // is no decision for Jev and the round-trip would be pure added latency. + if (names.length <= 1) { return false; } // Invalid key latched earlier: skip the round-trip, zero added latency. @@ -447,6 +458,9 @@ async function routePayload( name?: unknown; function?: { name?: unknown }; }; + // Invariant 4 (issue #12 verdict): built-ins are never offered to Jev, + // so Jev must never remove them either — they always survive the trim. + if (isBuiltIn(tool)) return true; return ( record.name === answer.choice || record.function?.name === answer.choice ); @@ -456,7 +470,14 @@ async function routePayload( return false; } payload.tools = tools; - log(`apply: tools trimmed to ${answer.choice} only (${at} >= minConfidence ${cfg.minConfidence})`); + const keptBuiltIns = tools.filter(isBuiltIn).length; + log( + `apply: tools trimmed to ${answer.choice}${ + keptBuiltIns + ? ` (+ ${keptBuiltIns} built-in${keptBuiltIns === 1 ? "" : "s"} kept)` + : " only" + } (${at} >= minConfidence ${cfg.minConfidence})`, + ); return true; } diff --git a/test/index.test.ts b/test/index.test.ts index d46b888..631d265 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -256,7 +256,7 @@ test("6. openai chat format: matched via function.name", async () => { assert.equal(calls.length, 1); }); -test("7. responses format: built-ins excluded from criteria, trimmed by function.name", async () => { +test("7. responses format: built-ins excluded from criteria, survive the trim", async () => { const { calls, holder } = await setupPlugin(undefined, () => jevResponse(choice("shell", 0.95)), ); @@ -266,6 +266,7 @@ test("7. responses format: built-ins excluded from criteria, trimmed by function tools: [ { type: "web_search" }, { type: "function", function: { name: "shell" } }, + { type: "function", function: { name: "read" } }, ], input: [{ type: "message", role: "user", content: "run ls" }], }; @@ -279,9 +280,40 @@ test("7. responses format: built-ins excluded from criteria, trimmed by function assert.ok(criteriaKeys.includes("respond_to_user")); assert.ok(!criteriaKeys.includes("web_search")); + // Issue #12 verdict: Jev may only demote function tools — a built-in it + // was never allowed to consider is never removed either. const body = await bodyJson(event); - assert.deepEqual(body.tools, [{ type: "function", function: { name: "shell" } }]); + assert.deepEqual(body.tools, [ + { type: "web_search" }, + { type: "function", function: { name: "shell" } }, + ]); assert.deepEqual(body.input, payload.input); + assert.match( + readFileSync(process.env.JEV_DEBUG_FILE!, "utf8"), + /\[jev\] apply: tools trimmed to shell \(\+ 1 built-in kept\) \(shell@0\.95/, + ); +}); + +test("7b. responses: lone function tool beside built-ins: passthrough, no fetch", async () => { + const { calls, holder } = await setupPlugin(undefined, () => + jevResponse(choice("shell", 0.95)), + ); + assert.ok(holder.captured); + const payload = { + model: "gpt-x", + tools: [ + { type: "web_search" }, + { type: "function", function: { name: "shell" } }, + ], + input: [{ type: "message", role: "user", content: "run ls" }], + }; + const url = "https://api.openai.com/v1/responses"; + const event = jsonEvent(url, payload); + await holder.captured!(event); + // Built-ins survive the trim, so a lone function candidate can only + // reproduce the payload — skip the round-trip entirely. + assert.deepEqual(await bodyJson(event), payload); + assert.equal(calls.length, 0); }); test("8. responses with only built-in tools: passthrough, no fetch", async () => { @@ -564,3 +596,26 @@ test("22. bogus config timeoutMs (0 / non-numeric): default used, routes normall assert.equal(calls.length, 1); } }); + +test("23. 260 tools: criteria truncated to first 254 + note logged, trim still applies", async () => { + const { calls, holder } = await setupPlugin(undefined, () => + jevResponse(choice("tool_0", 0.99)), + ); + assert.ok(holder.captured); + const payload = anthropicPayload(); + payload.tools = Array.from({ length: 260 }, (_, i) => ({ + name: `tool_${i}`, + input_schema: {}, + })); + const event = jsonEvent(ANTHROPIC_URL, payload); + await holder.captured!(event); + const jevBody = JSON.parse(calls[0].init.body); + const criteria = jevBody.questions.next_tool.criteria; + // 254 kept tools + the reserved respond_to_user slot; tool_254..259 invisible. + assert.equal(Object.keys(criteria).length, 255); // MAX_CRITERIA: 254 tools + respond_to_user + assert.ok("tool_253" in criteria); + assert.ok(!("tool_254" in criteria)); + const logText = readFileSync(process.env.JEV_DEBUG_FILE!, "utf8"); + assert.match(logText, /\[jev\] note: 260 tools exceed criteria cap 254/); + assert.match(logText, /\[jev\] apply: tools trimmed to tool_0/); +});