solrouter 0.3.5 → 0.4.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solrouter",
3
- "version": "0.3.5",
3
+ "version": "0.4.1",
4
4
  "description": "Local privacy router for coding tools: pseudonymises every request before it leaves your machine, and sends work a frontier model would refuse to an uncensored open-weight model you control.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/index.js CHANGED
@@ -115,7 +115,16 @@ export async function handleStream(body, ctx = {}, cfg) {
115
115
  const toSend = withIntent(masked, kind, intent);
116
116
  const r = await streamLeg(cfg.frontier, toSend, ctx.headers);
117
117
  return { status: r.status, ok: r.ok, stream: r.stream, masker, leg, reason,
118
- model: cfg.frontier.model, sent: JSON.stringify(masked) };
118
+ model: cfg.frontier.model, sent: JSON.stringify(masked),
119
+ // context the server needs to reactively reroute a streamed refusal to private:
120
+ kind, mode, maskedPrompt: extractText(masked, kind) };
121
+ }
122
+
123
+ /** Call the private leg for a (masked) prompt. Returns { reply, ok }. */
124
+ export async function privateReply(cfg, maskedPrompt) {
125
+ const { callSolrouterAgent } = await import("./providers.js");
126
+ const r = await callSolrouterAgent(cfg.private, maskedPrompt);
127
+ return { reply: r.reply || "", ok: r.ok };
119
128
  }
120
129
 
121
130
  export { createMasker } from "./mask.js";
package/src/route.js CHANGED
@@ -26,10 +26,13 @@ const LIKELY_REFUSED = [
26
26
  ];
27
27
 
28
28
  const REFUSAL_SIGNATURES = [
29
- /\bI (?:can(?:'|no)?t|won'?t|am (?:not able|unable))\b.{0,60}\b(?:help|assist|comply|provide|create|generate|continue)\b/i,
30
- /\bI'?m (?:sorry|afraid)\b.{0,40}\b(?:can(?:'|no)?t|won'?t|unable)\b/i,
29
+ /\bI (?:can(?:'|no)?t|won'?t|am (?:not able|unable))\b.{0,60}\b(?:help|assist|comply|provide|create|generate|continue|do that|with that)\b/i,
30
+ /\bI'?m not (?:going to|willing to|able to|comfortable)\b.{0,30}\b(?:help|assist|do|provide|create|with that|that)\b/i,
31
+ /\bI (?:won'?t|will not|am not going to)\b.{0,20}\b(?:help|assist|do that|provide|create)\b/i,
32
+ /\bI'?m (?:sorry|afraid)\b.{0,40}\b(?:can(?:'|no)?t|won'?t|unable|not able)\b/i,
31
33
  /\b(?:against|violates?)\b.{0,30}\b(?:policy|policies|guidelines|content policy)\b/i,
32
34
  /\bI (?:must|have to) (?:decline|refuse)\b/i,
35
+ /\bI (?:can'?t|cannot|won'?t) (?:help|assist) (?:you )?with (?:that|this)\b/i,
33
36
  ];
34
37
 
35
38
  /** Cheap local guess: would the frontier model likely refuse this? */
package/src/server.js CHANGED
@@ -7,11 +7,38 @@
7
7
  // localhost only — nothing here should be reachable off the machine.
8
8
 
9
9
  import { createServer } from "node:http";
10
- import { handle, handleStream, createMasker } from "./index.js";
10
+ import { handle, handleStream, createMasker, privateReply } from "./index.js";
11
11
  import { forward } from "./providers.js";
12
12
  import { dialect, rewriteText } from "./wire.js";
13
+ import { isRefusal } from "./route.js";
13
14
  import { writeReceipt } from "./receipt.js";
14
15
 
16
+ /** Pull assistant text out of an Anthropic SSE chunk (text_delta events). */
17
+ function extractSseText(chunk) {
18
+ let out = "";
19
+ for (const line of String(chunk).split("\n")) {
20
+ if (!line.startsWith("data:")) continue;
21
+ try {
22
+ const d = JSON.parse(line.slice(5).trim());
23
+ if (d?.type === "content_block_delta" && d.delta?.type === "text_delta") out += d.delta.text || "";
24
+ } catch {}
25
+ }
26
+ return out;
27
+ }
28
+
29
+ /** Build a complete Anthropic-format SSE message from a plain text answer. */
30
+ function synthAnthropicSse(text, model) {
31
+ const ev = (e, d) => `event: ${e}\ndata: ${JSON.stringify(d)}\n\n`;
32
+ return (
33
+ ev("message_start", { type: "message_start", message: { id: "msg_proxy", type: "message", role: "assistant", model: model || "solrouter", content: [], stop_reason: null, usage: { input_tokens: 0, output_tokens: 0 } } }) +
34
+ ev("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }) +
35
+ ev("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: String(text) } }) +
36
+ ev("content_block_stop", { type: "content_block_stop", index: 0 }) +
37
+ ev("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 0 } }) +
38
+ ev("message_stop", { type: "message_stop" })
39
+ );
40
+ }
41
+
15
42
  function readBody(req) {
16
43
  return new Promise((resolve, reject) => {
17
44
  let data = "";
@@ -66,19 +93,49 @@ export function startServer(cfg) {
66
93
  if (!s.ok || !s.stream) return send(s.status || 502, { error: "upstream error", leg: s.leg });
67
94
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", "connection": "keep-alive" });
68
95
  const restorer = cfg.masking?.enabled === false ? null : s.masker.streamingUnmasker();
96
+ const emit = (t) => res.write(restorer ? restorer.push(t) : t);
69
97
  const reader = s.stream.getReader();
70
98
  const dec = new TextDecoder();
99
+
100
+ // Buffer the frontier stream until we can rule out a SHORT refusal. Once
101
+ // the answer is clearly substantive (past the refusal window) we commit and
102
+ // stream live. If the whole short response is a refusal and mode is auto,
103
+ // we discard it and reroute to the private/uncensored leg.
104
+ const COMMIT_AT = 380; // chars of answer text that means "real answer"
105
+ let committed = false, held = "", acc = "", refusalLikely = false;
71
106
  for (;;) {
72
107
  const { done, value } = await reader.read();
73
108
  if (done) break;
74
109
  const chunk = dec.decode(value, { stream: true });
75
- res.write(restorer ? restorer.push(chunk) : chunk);
110
+ acc += extractSseText(chunk);
111
+ if (committed) { emit(chunk); continue; }
112
+ held += chunk;
113
+ // Lock onto a refusal as soon as its opening matches — then never commit,
114
+ // so even a long, multi-paragraph refusal gets fully buffered and rerouted.
115
+ if (!refusalLikely && isRefusal(acc)) refusalLikely = true;
116
+ if (!refusalLikely && acc.replace(/\s/g, "").length >= COMMIT_AT) { committed = true; emit(held); held = ""; }
117
+ }
118
+
119
+ let leg = s.leg, refused = false, model = s.model;
120
+ if (!committed && s.mode === "auto" && refusalLikely) {
121
+ // Streamed refusal → reroute to the uncensored private leg.
122
+ const pr = await privateReply(cfg, s.maskedPrompt);
123
+ if (pr.ok && pr.reply) {
124
+ leg = "private"; refused = true; model = cfg.private.model;
125
+ const restored = restorer ? s.masker.unmask(pr.reply) : pr.reply;
126
+ res.write(synthAnthropicSse(restored, model));
127
+ res.end();
128
+ if (cfg.receipt?.enabled) writeReceipt(cfg.receipt.path, {
129
+ leg, reason: "reactive-refusal", model, entities: s.masker.entities(), refused: true, sentToProvider: s.sent });
130
+ return;
131
+ }
132
+ // private leg unavailable → fall through and just relay the refusal
76
133
  }
134
+ if (!committed) emit(held); // short non-refusal: flush the buffer
77
135
  if (restorer) res.write(restorer.flush());
78
136
  res.end();
79
137
  if (cfg.receipt?.enabled) writeReceipt(cfg.receipt.path, {
80
- leg: s.leg, reason: s.reason, model: s.model,
81
- entities: s.masker.entities(), refused: false, sentToProvider: s.sent,
138
+ leg, reason: s.reason, model, entities: s.masker.entities(), refused, sentToProvider: s.sent,
82
139
  });
83
140
  return;
84
141
  }