@odysx/codemind 0.0.0-stage → 0.1.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/README.md +293 -2
- package/dist/commands/agents.d.ts +2 -0
- package/dist/commands/agents.js +91 -0
- package/dist/commands/auth.d.ts +2 -0
- package/dist/commands/auth.js +35 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +180 -0
- package/dist/commands/keys.d.ts +2 -0
- package/dist/commands/keys.js +81 -0
- package/dist/commands/local.d.ts +2 -0
- package/dist/commands/local.js +325 -0
- package/dist/commands/mcp.d.ts +2 -0
- package/dist/commands/mcp.js +73 -0
- package/dist/commands/prompts.d.ts +2 -0
- package/dist/commands/prompts.js +59 -0
- package/dist/commands/skills.d.ts +2 -0
- package/dist/commands/skills.js +41 -0
- package/dist/core/auth/index.d.ts +10 -0
- package/dist/core/auth/index.js +82 -0
- package/dist/core/config/index.d.ts +47 -0
- package/dist/core/config/index.js +118 -0
- package/dist/core/history.d.ts +14 -0
- package/dist/core/history.js +80 -0
- package/dist/core/markdown-renderer.d.ts +47 -0
- package/dist/core/markdown-renderer.js +385 -0
- package/dist/core/permissions/index.d.ts +31 -0
- package/dist/core/permissions/index.js +64 -0
- package/dist/core/provider/external.d.ts +28 -0
- package/dist/core/provider/external.js +248 -0
- package/dist/core/provider/index.d.ts +138 -0
- package/dist/core/provider/index.js +510 -0
- package/dist/core/registry/index.d.ts +25 -0
- package/dist/core/registry/index.js +216 -0
- package/dist/core/schema/types.d.ts +93 -0
- package/dist/core/schema/types.js +12 -0
- package/dist/core/terminal.d.ts +40 -0
- package/dist/core/terminal.js +134 -0
- package/dist/core/workspace/index.d.ts +35 -0
- package/dist/core/workspace/index.js +194 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +393 -0
- package/dist/ui/app.d.ts +3 -0
- package/dist/ui/app.js +554 -0
- package/dist/ui/commands/cases/catalog.d.ts +11 -0
- package/dist/ui/commands/cases/catalog.js +62 -0
- package/dist/ui/commands/cases/misc.d.ts +35 -0
- package/dist/ui/commands/cases/misc.js +245 -0
- package/dist/ui/commands/cases/tasks.d.ts +13 -0
- package/dist/ui/commands/cases/tasks.js +91 -0
- package/dist/ui/commands/runCommand.d.ts +22 -0
- package/dist/ui/commands/runCommand.js +136 -0
- package/dist/ui/components/AgentPicker.d.ts +11 -0
- package/dist/ui/components/AgentPicker.js +7 -0
- package/dist/ui/components/AuthPicker.d.ts +14 -0
- package/dist/ui/components/AuthPicker.js +7 -0
- package/dist/ui/components/Banner.d.ts +8 -0
- package/dist/ui/components/Banner.js +24 -0
- package/dist/ui/components/CommandMenu.d.ts +17 -0
- package/dist/ui/components/CommandMenu.js +21 -0
- package/dist/ui/components/ErrorBoundary.d.ts +24 -0
- package/dist/ui/components/ErrorBoundary.js +51 -0
- package/dist/ui/components/InputBar.d.ts +28 -0
- package/dist/ui/components/InputBar.js +108 -0
- package/dist/ui/components/KeysPanel.d.ts +12 -0
- package/dist/ui/components/KeysPanel.js +25 -0
- package/dist/ui/components/MessageView.d.ts +29 -0
- package/dist/ui/components/MessageView.js +107 -0
- package/dist/ui/components/PermissionPrompt.d.ts +10 -0
- package/dist/ui/components/PermissionPrompt.js +4 -0
- package/dist/ui/components/Pickers.d.ts +43 -0
- package/dist/ui/components/Pickers.js +33 -0
- package/dist/ui/components/SearchOverlay.d.ts +21 -0
- package/dist/ui/components/SearchOverlay.js +14 -0
- package/dist/ui/components/SessionPicker.d.ts +12 -0
- package/dist/ui/components/SessionPicker.js +8 -0
- package/dist/ui/components/WorkingIndicator.d.ts +10 -0
- package/dist/ui/components/WorkingIndicator.js +23 -0
- package/dist/ui/controls/ApiKeyEntry.d.ts +8 -0
- package/dist/ui/controls/ApiKeyEntry.js +5 -0
- package/dist/ui/controls/MultiSelect.d.ts +18 -0
- package/dist/ui/controls/MultiSelect.js +9 -0
- package/dist/ui/hooks/useAgentPicker.d.ts +14 -0
- package/dist/ui/hooks/useAgentPicker.js +53 -0
- package/dist/ui/hooks/useAuthFlow.d.ts +14 -0
- package/dist/ui/hooks/useAuthFlow.js +31 -0
- package/dist/ui/hooks/useKeysFlow.d.ts +17 -0
- package/dist/ui/hooks/useKeysFlow.js +130 -0
- package/dist/ui/hooks/useSessionPicker.d.ts +29 -0
- package/dist/ui/hooks/useSessionPicker.js +58 -0
- package/dist/ui/hooks/useTerminalSize.d.ts +6 -0
- package/dist/ui/hooks/useTerminalSize.js +29 -0
- package/dist/ui/input/keyRouter.d.ts +125 -0
- package/dist/ui/input/keyRouter.js +574 -0
- package/dist/ui/layouts/ScreenLayout.d.ts +98 -0
- package/dist/ui/layouts/ScreenLayout.js +56 -0
- package/dist/ui/shared/types.d.ts +143 -0
- package/dist/ui/shared/types.js +38 -0
- package/dist/ui/theme.d.ts +29 -0
- package/dist/ui/theme.js +54 -0
- package/dist/ui/utils/markdown.d.ts +74 -0
- package/dist/ui/utils/markdown.js +187 -0
- package/dist/ui/utils/mentions.d.ts +12 -0
- package/dist/ui/utils/mentions.js +28 -0
- package/dist/ui/utils/terminal-text.d.ts +33 -0
- package/dist/ui/utils/terminal-text.js +123 -0
- package/dist/ui/utils/text.d.ts +72 -0
- package/dist/ui/utils/text.js +171 -0
- package/package.json +50 -6
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API provider — HTTP client for the OdysX backend.
|
|
3
|
+
*
|
|
4
|
+
* Handles: auth headers, JSON parsing, SSE streaming, error mapping.
|
|
5
|
+
* Mirrors the frontend's `apiMap` pattern.
|
|
6
|
+
*
|
|
7
|
+
* Every request is bounded by a timeout. Callers that pass their own signal
|
|
8
|
+
* (Esc to interrupt) still get their abort honoured, and user aborts stay
|
|
9
|
+
* distinguishable from timeouts so the REPL can report them differently.
|
|
10
|
+
*/
|
|
11
|
+
import { getConfig } from "../config/index.js";
|
|
12
|
+
/**
|
|
13
|
+
* Parse one raw `data:` payload into a normalised stream event.
|
|
14
|
+
*
|
|
15
|
+
* Legacy shapes: `hello` (token), `[DONE]`, `[ERROR] reason`.
|
|
16
|
+
* Typed shape: `{"event":"token","data":{"text":"hello"}}` etc.
|
|
17
|
+
* Malformed JSON is treated as a raw token so a proxy injecting text can't
|
|
18
|
+
* kill a turn; unknown event names are ignored rather than rendered.
|
|
19
|
+
*/
|
|
20
|
+
export function parseStreamFrame(raw) {
|
|
21
|
+
if (!raw)
|
|
22
|
+
return null;
|
|
23
|
+
if (raw.startsWith("{")) {
|
|
24
|
+
let value;
|
|
25
|
+
try {
|
|
26
|
+
value = JSON.parse(raw);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return { type: "token", data: raw };
|
|
30
|
+
}
|
|
31
|
+
const rec = value;
|
|
32
|
+
const type = rec?.event;
|
|
33
|
+
const data = (rec?.data && typeof rec.data === "object" ? rec.data : {});
|
|
34
|
+
switch (type) {
|
|
35
|
+
case "token":
|
|
36
|
+
if (typeof data.text !== "string")
|
|
37
|
+
return null;
|
|
38
|
+
return { type: "token", data: data.text, payload: { kind: "token", text: data.text } };
|
|
39
|
+
case "done":
|
|
40
|
+
return {
|
|
41
|
+
type: "done",
|
|
42
|
+
data: "",
|
|
43
|
+
payload: { kind: "done", finishReason: String(data.finish_reason ?? "stop") },
|
|
44
|
+
};
|
|
45
|
+
case "usage": {
|
|
46
|
+
const prompt = Number(data.prompt_tokens);
|
|
47
|
+
const completion = Number(data.completion_tokens);
|
|
48
|
+
const total = Number(data.total_tokens ?? prompt + completion);
|
|
49
|
+
if (!Number.isFinite(prompt) || !Number.isFinite(completion))
|
|
50
|
+
return null;
|
|
51
|
+
return {
|
|
52
|
+
type: "usage",
|
|
53
|
+
data: "",
|
|
54
|
+
payload: { kind: "usage", promptTokens: prompt, completionTokens: completion, totalTokens: total },
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
case "error":
|
|
58
|
+
return {
|
|
59
|
+
type: "error",
|
|
60
|
+
data: String(data.message ?? "Stream error"),
|
|
61
|
+
payload: { kind: "error", message: String(data.message ?? "Stream error"), code: String(data.code ?? "stream_error") },
|
|
62
|
+
};
|
|
63
|
+
default:
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (raw === "[DONE]")
|
|
68
|
+
return { type: "done", data: "" };
|
|
69
|
+
if (raw.startsWith("[ERROR]"))
|
|
70
|
+
return { type: "error", data: raw.slice(7).trim() || "Stream error" };
|
|
71
|
+
return { type: "token", data: raw };
|
|
72
|
+
}
|
|
73
|
+
/** Default ceiling for a non-streaming API call. */
|
|
74
|
+
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
75
|
+
/** Streaming turns may legitimately run long, but never forever. */
|
|
76
|
+
export const STREAM_IDLE_TIMEOUT_MS = 120_000;
|
|
77
|
+
/** Build full URL from path */
|
|
78
|
+
function buildUrl(path, baseUrl) {
|
|
79
|
+
const base = baseUrl ?? getConfig().apiUrl;
|
|
80
|
+
return `${base}${path.replace(/^\//, "/")}`;
|
|
81
|
+
}
|
|
82
|
+
/** Build auth headers */
|
|
83
|
+
async function authHeaders() {
|
|
84
|
+
const config = getConfig();
|
|
85
|
+
const headers = {
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
Accept: "application/json",
|
|
88
|
+
};
|
|
89
|
+
if (config.apiKey) {
|
|
90
|
+
headers["X-Api-Key"] = config.apiKey;
|
|
91
|
+
}
|
|
92
|
+
else if (config.token) {
|
|
93
|
+
headers["Authorization"] = `Bearer ${config.token}`;
|
|
94
|
+
}
|
|
95
|
+
return headers;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Combine a caller signal with a timeout. Abort reasons are reported through
|
|
99
|
+
* `timedOut()` so callers can tell "user pressed Esc" from "server hung".
|
|
100
|
+
*/
|
|
101
|
+
function withTimeout(external, ms) {
|
|
102
|
+
const controller = new AbortController();
|
|
103
|
+
let fired = false;
|
|
104
|
+
const timer = setTimeout(() => {
|
|
105
|
+
fired = true;
|
|
106
|
+
controller.abort();
|
|
107
|
+
}, ms);
|
|
108
|
+
// Do not keep the event loop alive just for the timer.
|
|
109
|
+
timer.unref?.();
|
|
110
|
+
// The listener must be removed on success too. A long-lived caller signal
|
|
111
|
+
// (a shared controller, a batch runner) accumulated one listener per
|
|
112
|
+
// request; Node warns at eleven, and the warning is written to stderr in
|
|
113
|
+
// the middle of the Ink frame.
|
|
114
|
+
let detach;
|
|
115
|
+
if (external) {
|
|
116
|
+
if (external.aborted) {
|
|
117
|
+
controller.abort();
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
const onAbort = () => controller.abort();
|
|
121
|
+
external.addEventListener("abort", onAbort, { once: true });
|
|
122
|
+
detach = () => external.removeEventListener("abort", onAbort);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
signal: controller.signal,
|
|
127
|
+
clear: () => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
detach?.();
|
|
130
|
+
detach = undefined;
|
|
131
|
+
},
|
|
132
|
+
timedOut: () => fired,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
export function idleTimeout(ms, external) {
|
|
136
|
+
const controller = new AbortController();
|
|
137
|
+
let fired = false;
|
|
138
|
+
let timer = null;
|
|
139
|
+
const arm = () => {
|
|
140
|
+
if (fired)
|
|
141
|
+
return;
|
|
142
|
+
timer = setTimeout(() => {
|
|
143
|
+
fired = true;
|
|
144
|
+
controller.abort();
|
|
145
|
+
}, ms);
|
|
146
|
+
timer.unref?.();
|
|
147
|
+
};
|
|
148
|
+
arm();
|
|
149
|
+
let detach;
|
|
150
|
+
if (external) {
|
|
151
|
+
if (external.aborted) {
|
|
152
|
+
// Already cancelled by the caller — do not arm a timer that can never
|
|
153
|
+
// fire, and surface the abort immediately.
|
|
154
|
+
fired = false;
|
|
155
|
+
if (timer)
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
controller.abort(external.reason);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
const onAbort = () => controller.abort(external.reason);
|
|
161
|
+
external.addEventListener("abort", onAbort, { once: true });
|
|
162
|
+
// Removed on clear() as well: a long-lived caller signal otherwise
|
|
163
|
+
// accumulates a listener per request until Node warns at eleven.
|
|
164
|
+
detach = () => external.removeEventListener("abort", onAbort);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
signal: controller.signal,
|
|
169
|
+
touch: () => {
|
|
170
|
+
if (fired)
|
|
171
|
+
return;
|
|
172
|
+
if (timer)
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
arm();
|
|
175
|
+
},
|
|
176
|
+
clear: () => {
|
|
177
|
+
if (timer)
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
detach?.();
|
|
180
|
+
detach = undefined;
|
|
181
|
+
timer = null;
|
|
182
|
+
},
|
|
183
|
+
timedOut: () => fired,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** Human-readable error message from a non-2xx JSON or text body. */
|
|
187
|
+
function errorMessage(data, status, statusText) {
|
|
188
|
+
const rec = data;
|
|
189
|
+
if (rec && typeof rec === "object") {
|
|
190
|
+
const detail = rec.detail ?? rec.message ?? rec.error;
|
|
191
|
+
if (typeof detail === "string" && detail.trim())
|
|
192
|
+
return detail;
|
|
193
|
+
// FastAPI validation errors arrive as an array of {loc, msg}.
|
|
194
|
+
if (Array.isArray(detail) && detail.length > 0) {
|
|
195
|
+
const first = detail[0];
|
|
196
|
+
if (first?.msg)
|
|
197
|
+
return `${first.msg}${first.loc ? ` (${first.loc.join(".")})` : ""}`;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status}`;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Parse a response body without ever throwing on malformed JSON.
|
|
204
|
+
*
|
|
205
|
+
* `kind` reports what actually arrived so callers can refuse to treat an HTML
|
|
206
|
+
* login page as a successful API payload:
|
|
207
|
+
* json — parsed JSON object/array/number
|
|
208
|
+
* empty — no body at all
|
|
209
|
+
* text — non-JSON content type, or a JSON content type with broken JSON
|
|
210
|
+
*/
|
|
211
|
+
async function readBody(res) {
|
|
212
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
213
|
+
const raw = await res.text();
|
|
214
|
+
if (!raw)
|
|
215
|
+
return { data: null, raw, kind: "empty" };
|
|
216
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) {
|
|
217
|
+
try {
|
|
218
|
+
return { data: JSON.parse(raw), raw, kind: "json" };
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return { data: raw, raw, kind: "text" };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return { data: raw, raw, kind: "text" };
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Encode a value for use as a single URL path segment.
|
|
228
|
+
*
|
|
229
|
+
* Ids come straight from the command line. Interpolated raw, `x/../../y`
|
|
230
|
+
* would be normalised by undici into a *different* endpoint and sent with the
|
|
231
|
+
* user's credentials; `?`/`#` would truncate the path. Always encode.
|
|
232
|
+
*/
|
|
233
|
+
export const urlSegment = (value) => encodeURIComponent(value);
|
|
234
|
+
/** Generic API call */
|
|
235
|
+
export async function apiCall(path, options = {}) {
|
|
236
|
+
const url = buildUrl(path);
|
|
237
|
+
const authHdrs = await authHeaders();
|
|
238
|
+
const timeout = withTimeout(options.signal, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
239
|
+
try {
|
|
240
|
+
const res = await fetch(url, {
|
|
241
|
+
method: options.method ?? "GET",
|
|
242
|
+
headers: { ...authHdrs, ...options.headers },
|
|
243
|
+
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
|
244
|
+
signal: timeout.signal,
|
|
245
|
+
});
|
|
246
|
+
const { data, kind } = await readBody(res);
|
|
247
|
+
if (!res.ok) {
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
status: res.status,
|
|
251
|
+
data: data,
|
|
252
|
+
error: errorMessage(data, res.status, res.statusText),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
// A 2xx that isn't JSON is not a success this client can use: a proxy
|
|
256
|
+
// login page or a captive portal returns 200 text/html, and returning it
|
|
257
|
+
// as `data` made callers read properties off a string (`data.api_key` →
|
|
258
|
+
// undefined, printed as if it were the created key).
|
|
259
|
+
if (kind !== "json" && kind !== "empty") {
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
status: res.status,
|
|
263
|
+
data: data,
|
|
264
|
+
error: `Unexpected non-JSON response from ${url} (${res.headers.get("content-type") ?? "no content type"})`,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return { ok: true, status: res.status, data: data };
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
if (timeout.timedOut()) {
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
status: 0,
|
|
274
|
+
data: null,
|
|
275
|
+
error: `Request timed out after ${Math.round((options.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000)}s — ${url}`,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
279
|
+
// undici reports the real failure in err.cause.code; the message is often
|
|
280
|
+
// just "fetch failed", which told the user nothing actionable.
|
|
281
|
+
const code = err?.cause?.code ?? "";
|
|
282
|
+
if (msg.includes("fetch failed") || msg.includes("ECONNREFUSED") ||
|
|
283
|
+
msg.includes("ENOTFOUND") || NETWORK_ERROR_CODES.has(code)) {
|
|
284
|
+
const detail = code && !msg.includes(code) ? ` (${code})` : "";
|
|
285
|
+
return {
|
|
286
|
+
ok: false,
|
|
287
|
+
status: 0,
|
|
288
|
+
data: null,
|
|
289
|
+
error: `Cannot connect to ${getConfig().apiUrl}${detail}. Is the server running?`,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
293
|
+
return { ok: false, status: 0, data: null, error: "Request cancelled" };
|
|
294
|
+
}
|
|
295
|
+
return { ok: false, status: 0, data: null, error: msg };
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
timeout.clear();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** Socket-level failures that mean "the server is unreachable", not a bug. */
|
|
302
|
+
const NETWORK_ERROR_CODES = new Set([
|
|
303
|
+
"ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "ETIMEDOUT",
|
|
304
|
+
"EHOSTUNREACH", "ENETUNREACH", "CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
305
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UND_ERR_CONNECT_TIMEOUT",
|
|
306
|
+
]);
|
|
307
|
+
/* ── SSE ─────────────────────────────────────────────────────────────────── */
|
|
308
|
+
/**
|
|
309
|
+
* Incremental SSE reader shared by the platform stream and the external
|
|
310
|
+
* providers. It tolerates the framing differences seen in the wild:
|
|
311
|
+
* - `data:` with or without a space
|
|
312
|
+
* - CRLF and LF line endings
|
|
313
|
+
* - a final event with no trailing newline
|
|
314
|
+
* - comments / `event:` lines (ignored)
|
|
315
|
+
* `onData` receives the raw payload string of every `data:` line.
|
|
316
|
+
* `onActivity` fires on every chunk read, so a caller can keep an idle
|
|
317
|
+
* timeout armed only while the stream is genuinely silent.
|
|
318
|
+
*/
|
|
319
|
+
export async function readSSE(res, onData, signal, onActivity) {
|
|
320
|
+
const reader = res.body?.getReader();
|
|
321
|
+
if (!reader)
|
|
322
|
+
throw new Error("No response body");
|
|
323
|
+
const decoder = new TextDecoder();
|
|
324
|
+
let buffer = "";
|
|
325
|
+
const dispatch = (line) => {
|
|
326
|
+
const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
327
|
+
if (!trimmed.startsWith("data:"))
|
|
328
|
+
return;
|
|
329
|
+
const payload = trimmed.slice(5).replace(/^ /, "");
|
|
330
|
+
if (payload !== "")
|
|
331
|
+
onData(payload);
|
|
332
|
+
};
|
|
333
|
+
try {
|
|
334
|
+
while (true) {
|
|
335
|
+
if (signal?.aborted) {
|
|
336
|
+
await reader.cancel().catch(() => { });
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
const { done, value } = await reader.read();
|
|
340
|
+
if (done)
|
|
341
|
+
break;
|
|
342
|
+
onActivity?.();
|
|
343
|
+
buffer += decoder.decode(value, { stream: true });
|
|
344
|
+
const lines = buffer.split("\n");
|
|
345
|
+
buffer = lines.pop() ?? "";
|
|
346
|
+
for (const line of lines)
|
|
347
|
+
dispatch(line);
|
|
348
|
+
}
|
|
349
|
+
// Flush whatever the decoder and the line buffer still hold: a final
|
|
350
|
+
// `data: [DONE]` without a newline is common behind proxies.
|
|
351
|
+
buffer += decoder.decode();
|
|
352
|
+
if (buffer.trim())
|
|
353
|
+
dispatch(buffer);
|
|
354
|
+
}
|
|
355
|
+
catch (err) {
|
|
356
|
+
// A throwing onData (an `[ERROR]` frame, a render failure) must not leave
|
|
357
|
+
// the HTTP response streaming in the background: cancel the body before
|
|
358
|
+
// the error continues up the stack.
|
|
359
|
+
await reader.cancel().catch(() => { });
|
|
360
|
+
throw err;
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
reader.releaseLock();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** Stream SSE from the chat endpoint. Calls `onToken` for each token.
|
|
367
|
+
* `onUsage` (when given) receives token counts: exact counts from a typed
|
|
368
|
+
* `usage` event when the server sends one, otherwise the legacy ~4 chars ≈ 1
|
|
369
|
+
* token estimate. `onError` receives structured error payloads (typed streams)
|
|
370
|
+
* in addition to the thrown error. */
|
|
371
|
+
export async function streamChat(path, body, onToken, onDone, signal, onUsage, onError) {
|
|
372
|
+
const url = buildUrl(path);
|
|
373
|
+
const authHdrs = await authHeaders();
|
|
374
|
+
const timeout = idleTimeout(STREAM_IDLE_TIMEOUT_MS, signal);
|
|
375
|
+
let completionChars = 0;
|
|
376
|
+
let reportedUsage = null;
|
|
377
|
+
// A completed stream reaches both the `[DONE]` frame and the code after
|
|
378
|
+
// readSSE returns. Firing usage/done in both places doubled every session's
|
|
379
|
+
// token count and called `onDone` twice (which double-prompts interactive
|
|
380
|
+
// chat). The guard makes "finish" idempotent whichever path gets there first.
|
|
381
|
+
let finished = false;
|
|
382
|
+
const finish = () => {
|
|
383
|
+
if (finished)
|
|
384
|
+
return;
|
|
385
|
+
finished = true;
|
|
386
|
+
onUsage?.(reportedUsage ?? {
|
|
387
|
+
promptTokens: Math.max(1, Math.ceil((body?.message?.length ?? 0) / 4)),
|
|
388
|
+
completionTokens: Math.max(1, Math.ceil(completionChars / 4)),
|
|
389
|
+
});
|
|
390
|
+
onDone?.();
|
|
391
|
+
};
|
|
392
|
+
try {
|
|
393
|
+
const res = await fetch(url, {
|
|
394
|
+
method: "POST",
|
|
395
|
+
headers: { ...authHdrs, "Content-Type": "application/json" },
|
|
396
|
+
body: JSON.stringify(body),
|
|
397
|
+
signal: timeout.signal,
|
|
398
|
+
});
|
|
399
|
+
if (!res.ok) {
|
|
400
|
+
const { data } = await readBody(res);
|
|
401
|
+
throw new Error(errorMessage(data, res.status, res.statusText));
|
|
402
|
+
}
|
|
403
|
+
await readSSE(res, (data) => {
|
|
404
|
+
const event = parseStreamFrame(data);
|
|
405
|
+
if (!event)
|
|
406
|
+
return;
|
|
407
|
+
switch (event.type) {
|
|
408
|
+
case "done":
|
|
409
|
+
finish();
|
|
410
|
+
return;
|
|
411
|
+
case "error": {
|
|
412
|
+
const payload = event.payload;
|
|
413
|
+
const message = payload?.kind === "error" ? payload.message : event.data;
|
|
414
|
+
const code = payload?.kind === "error" ? payload.code : "stream_error";
|
|
415
|
+
onError?.({ message, code });
|
|
416
|
+
throw new Error(message);
|
|
417
|
+
}
|
|
418
|
+
case "usage": {
|
|
419
|
+
const p = event.payload;
|
|
420
|
+
if (p?.kind === "usage") {
|
|
421
|
+
reportedUsage = {
|
|
422
|
+
promptTokens: p.promptTokens,
|
|
423
|
+
completionTokens: p.completionTokens,
|
|
424
|
+
totalTokens: p.totalTokens,
|
|
425
|
+
exact: true,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
case "token":
|
|
431
|
+
completionChars += event.data.length;
|
|
432
|
+
onToken(event.data);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
}, timeout.signal, timeout.touch);
|
|
436
|
+
// Some servers close without a `[DONE]` frame: settle the turn here too.
|
|
437
|
+
finish();
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
if (timeout.timedOut()) {
|
|
441
|
+
throw new Error(`Stream timed out after ${Math.round(STREAM_IDLE_TIMEOUT_MS / 1000)}s with no response — ${url}`);
|
|
442
|
+
}
|
|
443
|
+
throw err;
|
|
444
|
+
}
|
|
445
|
+
finally {
|
|
446
|
+
timeout.clear();
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* One chat turn for every CLI front-end.
|
|
451
|
+
*
|
|
452
|
+
* Three chat paths used to disagree: the Ink REPL handled BYOK and fell back
|
|
453
|
+
* from master's unsupported SSE to POST /llm/chat, while `odysx chat` and the
|
|
454
|
+
* piped REPL streamed blindly and failed out of the box. Keeping the choice
|
|
455
|
+
* here means a new front-end cannot forget either behaviour.
|
|
456
|
+
*
|
|
457
|
+
* `history` is only used for external providers (which need the whole
|
|
458
|
+
* conversation); the platform owns session history server-side.
|
|
459
|
+
*/
|
|
460
|
+
export async function streamTurn(message, opts) {
|
|
461
|
+
// Dynamic import: external.ts imports readSSE/idleTimeout from this module.
|
|
462
|
+
const { getActiveProvider, streamExternalChat } = await import("./external.js");
|
|
463
|
+
const active = getActiveProvider();
|
|
464
|
+
if (active) {
|
|
465
|
+
const wire = [
|
|
466
|
+
...(opts.history ?? []),
|
|
467
|
+
{ role: "user", content: message },
|
|
468
|
+
];
|
|
469
|
+
await streamExternalChat(wire, {
|
|
470
|
+
system: opts.system,
|
|
471
|
+
onToken: opts.onToken,
|
|
472
|
+
signal: opts.signal,
|
|
473
|
+
});
|
|
474
|
+
opts.onUsage?.({
|
|
475
|
+
promptTokens: Math.max(1, Math.ceil(message.length / 4)),
|
|
476
|
+
completionTokens: 0, // external providers don't report usage here
|
|
477
|
+
});
|
|
478
|
+
opts.onDone?.();
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
const body = {
|
|
482
|
+
agent_id: opts.agentId ?? "master",
|
|
483
|
+
message,
|
|
484
|
+
session_id: opts.sessionId,
|
|
485
|
+
stream_format: "typed",
|
|
486
|
+
};
|
|
487
|
+
try {
|
|
488
|
+
await streamChat("/api/v1/llm/chat/stream", body, opts.onToken, opts.onDone, opts.signal, opts.onUsage, opts.onError);
|
|
489
|
+
}
|
|
490
|
+
catch (err) {
|
|
491
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
492
|
+
if (!/HTTP 400/.test(text) || !/Streaming is not supported/i.test(text))
|
|
493
|
+
throw err;
|
|
494
|
+
// Master (and other non-SSE agents) answer over the blocking endpoint.
|
|
495
|
+
const res = await apiCall("/api/v1/llm/chat", {
|
|
496
|
+
method: "POST",
|
|
497
|
+
body,
|
|
498
|
+
signal: opts.signal,
|
|
499
|
+
});
|
|
500
|
+
if (!res.ok)
|
|
501
|
+
throw new Error(res.error ?? `HTTP ${res.status}`);
|
|
502
|
+
opts.onUsage?.({
|
|
503
|
+
promptTokens: res.data?.usage?.prompt_tokens ?? 0,
|
|
504
|
+
completionTokens: res.data?.usage?.completion_tokens ?? 0,
|
|
505
|
+
});
|
|
506
|
+
opts.onToken(res.data?.answer ?? "(empty reply)");
|
|
507
|
+
opts.onDone?.();
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command registry — builds commander.js program from command schemas.
|
|
3
|
+
*
|
|
4
|
+
* Each command group (agents, chat, skills, etc.) registers a schema + handler.
|
|
5
|
+
* The registry builds the CLI tree. Subcommand routing is handled by each
|
|
6
|
+
* command's own handler (not auto-wired).
|
|
7
|
+
*/
|
|
8
|
+
import { Command } from "commander";
|
|
9
|
+
import type { CommandSchema, CommandHandler } from "../schema/types.js";
|
|
10
|
+
interface RegisteredCommand {
|
|
11
|
+
schema: CommandSchema;
|
|
12
|
+
handler: CommandHandler;
|
|
13
|
+
}
|
|
14
|
+
/** Options extended by commander (includes args array) */
|
|
15
|
+
export interface CliOptions extends Record<string, unknown> {
|
|
16
|
+
args: string[];
|
|
17
|
+
}
|
|
18
|
+
/** Register a command schema + handler */
|
|
19
|
+
export declare function registerCommand(schema: CommandSchema, handler: CommandHandler): void;
|
|
20
|
+
/** Get all registered commands */
|
|
21
|
+
export declare function getAllCommands(): Map<string, RegisteredCommand>;
|
|
22
|
+
/** Build the root commander program from all registered commands */
|
|
23
|
+
export declare function buildProgram(): Command;
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=index.d.ts.map
|