opencode-openai-session-router 0.0.0-stage → 0.1.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 (45) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +217 -2
  3. package/dist/accounts.d.ts +31 -0
  4. package/dist/bun.lock.txt +671 -0
  5. package/dist/chunks/index-85yd61pa.js +29 -0
  6. package/dist/chunks/index-n7sr1hee.js +803 -0
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.js +1842 -0
  9. package/dist/network.d.ts +8 -0
  10. package/dist/panel-contract.d.ts +14 -0
  11. package/dist/persistence.d.ts +40 -0
  12. package/dist/relay-protocol.d.ts +86 -0
  13. package/dist/relay.d.ts +50 -0
  14. package/dist/retry-control.d.ts +41 -0
  15. package/dist/router.d.ts +55 -0
  16. package/dist/rpc.d.ts +98 -0
  17. package/dist/rpc.js +7 -0
  18. package/dist/runtime.d.ts +94 -0
  19. package/dist/settings.d.ts +32 -0
  20. package/dist/sidebar-colors.d.ts +10 -0
  21. package/dist/sidebar-model.d.ts +82 -0
  22. package/dist/sidebar.d.ts +33 -0
  23. package/dist/sidebar.js +12 -0
  24. package/dist/tui.d.ts +3 -0
  25. package/dist/tui.js +25 -0
  26. package/package.json +52 -4
  27. package/scripts/build.ts +39 -0
  28. package/src/accounts.ts +130 -0
  29. package/src/index.ts +203 -0
  30. package/src/network.ts +25 -0
  31. package/src/panel-contract.ts +15 -0
  32. package/src/persistence.ts +96 -0
  33. package/src/relay-protocol.ts +157 -0
  34. package/src/relay.ts +593 -0
  35. package/src/retry-control.ts +92 -0
  36. package/src/router.ts +156 -0
  37. package/src/rpc.ts +28 -0
  38. package/src/runtime.ts +319 -0
  39. package/src/settings.ts +68 -0
  40. package/src/sidebar-colors.ts +132 -0
  41. package/src/sidebar-model.ts +257 -0
  42. package/src/sidebar.tsx +438 -0
  43. package/src/tui.tsx +12 -0
  44. package/tsconfig.build.json +12 -0
  45. package/tsconfig.json +16 -0
@@ -0,0 +1,157 @@
1
+ import { protocol, route } from "@opencode/ai/protocols/openai-responses";
2
+ import { Effect, Schema } from "effect";
3
+ import { ai, type LLMRequest } from "@opencode/ai/effect";
4
+ import { HttpClientResponse } from "effect/http";
5
+ import { CONTROL, ORIGINAL, record } from "./retry-control";
6
+
7
+ // Public published native codec, not a replacement model or private core import.
8
+ // Decoding failures remain relay-local: host receives original wire/connection
9
+ // failure and constructs its own bundled errors.
10
+ const decode = Schema.decodeUnknownSync(protocol.stream.event);
11
+ type NativeEvent = ReturnType<typeof decode>;
12
+ export function wireEvent(raw: string): NativeEvent {
13
+ const original: unknown = JSON.parse(raw);
14
+ if (record(original) && (CONTROL in original || ORIGINAL in original)) {
15
+ throw new Error("Reserved local diagnostic field collision.");
16
+ }
17
+ const event = decode(raw);
18
+ if (!record(event)) throw new Error("Invalid native event.");
19
+ if (CONTROL in event || ORIGINAL in event) throw new Error("Reserved local diagnostic field collision.");
20
+ return event;
21
+ }
22
+ export const terminal = (event: Record<string, any>) =>
23
+ ["error", "response.failed", "response.incomplete", "response.completed"].includes(event.type);
24
+ /** Admission uses ONLY numeric wire status429, never wording/code-derived guesses. */
25
+ export function wire429(event: Record<string, any>): boolean {
26
+ return ["error", "response.failed"].includes(event.type) &&
27
+ !(typeof event.status === "number" && typeof event.status_code === "number" && event.status !== event.status_code) &&
28
+ (event.status === 429 || event.status_code === 429);
29
+ }
30
+ const nativeLimitCodes = new Set([
31
+ "rate_limit_exceeded", "rate_limit_error", "too_many_requests", "insufficient_quota",
32
+ ]);
33
+ /**
34
+ * WS may omit numeric status. Use ONLY these exact affirmative native codes at
35
+ * published errorDetail precedence. No wording, substring or HTTP400 admission.
36
+ * Official Responses schemas permit absent status; actual Codex incidence is
37
+ * unverified. Conflicting/malformed evidence closes the exchange, not guesses.
38
+ */
39
+ export function wsLimit(event: Record<string, any>): boolean {
40
+ if (!["error", "response.failed"].includes(event.type)) return false;
41
+ const statuses = [event.status, event.status_code].filter((status) => status !== undefined);
42
+ if (statuses.some((status) => typeof status !== "number" || !Number.isInteger(status)) ||
43
+ (statuses.length === 2 && statuses[0] !== statuses[1])) throw new Error("Conflicting or malformed native status.");
44
+ if (statuses.length) return statuses[0] === 429;
45
+ const nested = event.error ?? event.response?.error;
46
+ if ((event.code !== undefined && typeof event.code !== "string") ||
47
+ (nested !== undefined && nested !== null && !record(nested) && typeof nested !== "string") ||
48
+ (record(nested) && nested.code !== undefined && typeof nested.code !== "string")) {
49
+ throw new Error("Malformed native error code.");
50
+ }
51
+ const code = event.code ?? (record(nested) ? nested.code : undefined);
52
+ return typeof code === "string" && nativeLimitCodes.has(code);
53
+ }
54
+
55
+ /** Conservative native lifecycle observer. Host still performs authoritative parsing. */
56
+ export class ResponseLifecycle {
57
+ private id?: string;
58
+ private ended = false;
59
+ private invalid = false;
60
+ visible = false;
61
+ success = false;
62
+ // Validation ONLY, never returned to HOST or used to execute tools/a model.
63
+ // Native fallback parsing supports undeclared custom tools. We discard parsed
64
+ // tool values (which may differ from HOST's schema-aware values); focused wire
65
+ // regressions cover ordinary/custom/@options/hosted/reasoning lifecycles.
66
+ private parser = protocol.stream.initial({
67
+ model: { id: "relay-validation", provider: "openai", route: {
68
+ id: "openai.responses", providerMetadataKey: "openai",
69
+ } }, messages: [], tools: [],
70
+ } as unknown as LLMRequest);
71
+
72
+ observe(event: NativeEvent): void {
73
+ if (this.ended) { this.invalid = true; this.success = false; throw new Error("Native event after terminal."); }
74
+ if (event.type === "response.created") {
75
+ if (this.id || typeof event.response?.id !== "string" || !event.response.id) this.invalid = true;
76
+ else this.id = event.response.id;
77
+ } else if (event.type.startsWith("response.") && !this.id) this.invalid = true;
78
+ if (event.response?.id && event.response.id !== this.id) this.invalid = true;
79
+ if (!["error", "response.failed", "response.incomplete"].includes(event.type) && !this.invalid) {
80
+ try {
81
+ const [next, output] = Effect.runSync(protocol.stream.step(this.parser, event));
82
+ this.parser = next;
83
+ if (output.some((item) => item.type === "tool-input-error")) this.invalid = true;
84
+ } catch { this.invalid = true; }
85
+ }
86
+ // Buffer ONLY safe response setup/keepalive. Any unknown response extension,
87
+ // item (including hosted tools), reasoning, or action is treated as observable.
88
+ if (!["response.created", "response.in_progress", "ping", "keepalive"].includes(event.type) &&
89
+ !terminal(event)) this.visible = true;
90
+ if (terminal(event)) {
91
+ this.ended = true;
92
+ this.success = !this.invalid && !!this.id && event.type === "response.completed" &&
93
+ event.response?.id === this.id && event.response?.status === "completed" &&
94
+ Array.isArray(event.response.output);
95
+ }
96
+ }
97
+ }
98
+
99
+ // The endpoint response codec is not exported independently. Reuse the PUBLIC
100
+ // endpoint operation with one fixed in-memory executor: its whole-response codec,
101
+ // checkpoint requirement and conversion run unchanged. No network executor/service
102
+ // is supplied; this local model/request/error is NEVER returned to HOST.
103
+ const compactRequest = ai.request({ model: route.model({ id: "relay-validation" }), prompt: "Local response validation only." });
104
+ export async function compactSuccess(raw: string, signal?: AbortSignal): Promise<boolean> {
105
+ try {
106
+ const value = JSON.parse(raw);
107
+ if (!record(value) || CONTROL in value || ORIGINAL in value) return false;
108
+ await Effect.runPromise(Effect.scoped(route.compact!.endpoint!(compactRequest, {
109
+ execute: (request) => Effect.succeed(HttpClientResponse.fromWeb(request, new Response(raw, {
110
+ status: 200, headers: { "content-type": "application/json" },
111
+ }))),
112
+ })), { signal });
113
+ return true;
114
+ } catch { return false; }
115
+ }
116
+ export const sseFrame = (raw: string): string => raw.split("\n").map((line) => `data: ${line}`).join("\n") + "\n\n";
117
+
118
+ /** SSE framing only; protocol payloads use the native codec. UTF8/chunk-safe. */
119
+ export async function* sseData(
120
+ body: ReadableStream<Uint8Array>, signal: AbortSignal, maxFrame = 8 * 1024 * 1024,
121
+ ): AsyncGenerator<string> {
122
+ const reader = body.getReader();
123
+ const decoder = new TextDecoder();
124
+ let buffer = "";
125
+ let pendingCR = false;
126
+ const cancel = () => { void reader.cancel().catch(() => {}); };
127
+ signal.addEventListener("abort", cancel, { once: true });
128
+ try {
129
+ for (;;) {
130
+ if (signal.aborted) throw new Error("Relay request cancelled.");
131
+ const next = await reader.read();
132
+ let text = decoder.decode(next.value, { stream: !next.done });
133
+ if (pendingCR) text = "\r" + text;
134
+ pendingCR = !next.done && text.endsWith("\r");
135
+ if (pendingCR) text = text.slice(0, -1);
136
+ buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
137
+ let end: number;
138
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
139
+ const frame = buffer.slice(0, end);
140
+ if (frame.length > maxFrame) throw new Error("Native SSE frame too large.");
141
+ buffer = buffer.slice(end + 2);
142
+ const data = frame.split("\n").filter((line) => line.startsWith("data:"))
143
+ .map((line) => line.slice(5).replace(/^ /, "")).join("\n");
144
+ if (data && data !== "[DONE]") yield data;
145
+ }
146
+ if (buffer.length > maxFrame) throw new Error("Native SSE frame too large.");
147
+ if (next.done) {
148
+ if (buffer.trim()) throw new Error("Truncated native SSE frame.");
149
+ return;
150
+ }
151
+ }
152
+ } finally {
153
+ signal.removeEventListener("abort", cancel);
154
+ await reader.cancel().catch(() => {});
155
+ reader.releaseLock();
156
+ }
157
+ }