@oracle-agent/oracle 0.9.6 → 0.9.7

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.
@@ -0,0 +1,272 @@
1
+ import { stripAnsi, THEME } from "./theme.mjs";
2
+
3
+ const WORDMARK = Object.freeze([
4
+ ["#B8F0FF", " ██████ ████████ ██████ ██████ ░███ ██████ "],
5
+ ["#B8F0FF", " ███░░███░░███░░███ ░░░░░███ ███░░███ ░███ ███░░███ "],
6
+ ["#ACDEEF", " ░███ ░███ ░███ ░░░ ███████ ░███ ░░░ ░███ ░███████ "],
7
+ ["#A5D9EB", " ░███ ░███ ░███ ███░░███ ░███ ███ ░███ ░███░░░ "],
8
+ ["#9FCBDD", " ░░██████ █████ ░░████████░░██████ █████░░██████ "],
9
+ ["#B8F0FF", " ░░░░░░ ░░░░░ ░░░░░░░░ ░░░░░░ ░░░░░ ░░░░░░ "],
10
+ ]);
11
+
12
+ const TAGLINE = "THE FUTURE IS AGENTIC / by DEMI";
13
+ const ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
14
+
15
+ function cellWidth(character) {
16
+ if (/\p{Mark}/u.test(character)) return 0;
17
+ const point = character.codePointAt(0);
18
+ if (point === 0x200d || point === 0xfe0f) return 0;
19
+ if (point >= 0x1100 && (
20
+ point <= 0x115f || point === 0x2329 || point === 0x232a ||
21
+ (point >= 0x2e80 && point <= 0xa4cf && point !== 0x303f) ||
22
+ (point >= 0xac00 && point <= 0xd7a3) ||
23
+ (point >= 0xf900 && point <= 0xfaff) ||
24
+ (point >= 0xfe10 && point <= 0xfe19) ||
25
+ (point >= 0xfe30 && point <= 0xfe6f) ||
26
+ (point >= 0xff00 && point <= 0xff60) ||
27
+ (point >= 0xffe0 && point <= 0xffe6) ||
28
+ (point >= 0x1f300 && point <= 0x1faff) ||
29
+ (point >= 0x20000 && point <= 0x3fffd)
30
+ )) return 2;
31
+ return point < 0x20 || (point >= 0x7f && point < 0xa0) ? 0 : 1;
32
+ }
33
+
34
+ export function visibleWidth(text) {
35
+ return [...stripAnsi(text)].reduce((width, character) => width + cellWidth(character), 0);
36
+ }
37
+
38
+ function truncateTo(text, width) {
39
+ if (width <= 0) return "";
40
+ const tokens = String(text).split(/(\u001B\[[0-9;]*m)/g);
41
+ let result = "";
42
+ let used = 0;
43
+ let styled = false;
44
+ for (const token of tokens) {
45
+ if (!token) continue;
46
+ if (ANSI_PATTERN.test(token)) {
47
+ ANSI_PATTERN.lastIndex = 0;
48
+ result += token;
49
+ styled = token !== "\u001B[0m";
50
+ continue;
51
+ }
52
+ ANSI_PATTERN.lastIndex = 0;
53
+ for (const character of token) {
54
+ const cells = cellWidth(character);
55
+ if (used + cells > width) return styled ? `${result}\u001B[0m` : result;
56
+ result += character;
57
+ used += cells;
58
+ }
59
+ }
60
+ return result;
61
+ }
62
+
63
+ export function padTo(text, width, align = "left") {
64
+ const target = Math.max(0, Math.floor(Number(width) || 0));
65
+ const value = truncateTo(String(text), target);
66
+ const spaces = Math.max(0, target - visibleWidth(value));
67
+ if (align === "right") return `${" ".repeat(spaces)}${value}`;
68
+ if (align === "center") {
69
+ const left = Math.floor(spaces / 2);
70
+ return `${" ".repeat(left)}${value}${" ".repeat(spaces - left)}`;
71
+ }
72
+ return `${value}${" ".repeat(spaces)}`;
73
+ }
74
+
75
+ export function wrapText(text, width) {
76
+ const target = Math.max(1, Math.floor(Number(width) || 1));
77
+ const out = [];
78
+ for (const rawLine of String(text ?? "").split("\n")) {
79
+ if (rawLine === "") {
80
+ out.push("");
81
+ continue;
82
+ }
83
+ let current = "";
84
+ let used = 0;
85
+ for (const word of rawLine.split(" ")) {
86
+ const wordWidth = visibleWidth(word);
87
+ if (used > 0 && used + 1 + wordWidth > target) {
88
+ out.push(current);
89
+ current = "";
90
+ used = 0;
91
+ }
92
+ if (wordWidth > target) {
93
+ if (used > 0) {
94
+ out.push(current);
95
+ current = "";
96
+ used = 0;
97
+ }
98
+ let rest = word;
99
+ while (visibleWidth(rest) > target) {
100
+ const head = truncateTo(rest, target);
101
+ out.push(head);
102
+ rest = rest.slice(head.length);
103
+ }
104
+ current = rest;
105
+ used = visibleWidth(rest);
106
+ continue;
107
+ }
108
+ current = used === 0 ? word : `${current} ${word}`;
109
+ used = used === 0 ? wordWidth : used + 1 + wordWidth;
110
+ }
111
+ out.push(current);
112
+ }
113
+ return out;
114
+ }
115
+
116
+ export function bannerGeometry(width) {
117
+ const target = Math.max(0, Math.floor(Number(width) || 0));
118
+ const panelWidth = Math.max(36, Math.min(target - 4, 76));
119
+ const panelLeft = Math.max(0, Math.floor((target - panelWidth) / 2));
120
+ const contentLeft = panelLeft + 3;
121
+ const inner = Math.max(0, panelWidth - 6);
122
+ return { target, panelWidth, panelLeft, contentLeft, inner };
123
+ }
124
+
125
+ function inkBounds(lines) {
126
+ let first = Infinity;
127
+ let last = -1;
128
+ for (const line of lines) {
129
+ for (let i = 0; i < line.length; i += 1) {
130
+ if (line[i] !== " ") {
131
+ if (i < first) first = i;
132
+ if (i > last) last = i;
133
+ }
134
+ }
135
+ }
136
+ if (last < 0) return { offset: 0, width: 0 };
137
+ return { offset: first, width: last - first + 1 };
138
+ }
139
+
140
+ export function centerPad(geometry, inkWidth, inkOffset = 0) {
141
+ const { target, contentLeft, inner } = geometry;
142
+ const desired = Math.round((target - inkWidth) / 2);
143
+ const pad = desired - inkOffset - contentLeft;
144
+ const ceiling = Math.max(0, inner - inkWidth - inkOffset);
145
+ return Math.max(0, Math.min(ceiling, pad));
146
+ }
147
+
148
+ export function renderBanner({ width, palette }) {
149
+ const geometry = bannerGeometry(width);
150
+ const { target, panelWidth, panelLeft, inner } = geometry;
151
+ if (target < 72 || inner <= 0) {
152
+ return [
153
+ padTo(palette.bold(palette.fg(THEME.accent, "oracle")), target, "center"),
154
+ padTo(palette.fg(THEME.banner_text, TAGLINE), target, "center"),
155
+ ];
156
+ }
157
+
158
+ const art = WORDMARK.map(([, line]) => line);
159
+ const { offset, width: inkWidth } = inkBounds(art);
160
+ const artPad = " ".repeat(centerPad(geometry, inkWidth, offset));
161
+ const taglinePad = " ".repeat(centerPad(geometry, visibleWidth(TAGLINE)));
162
+
163
+ const body = [];
164
+ for (const [color, line] of WORDMARK) {
165
+ body.push(palette.bold(palette.fg(color, `${artPad}${line.replace(/\s+$/, "")}`)));
166
+ }
167
+ body.push("");
168
+ body.push(palette.bold(palette.fg(THEME.banner_text, `${taglinePad}${TAGLINE}`)));
169
+
170
+ const border = (text) => palette.fg(THEME.banner_border, text);
171
+ const shift = " ".repeat(panelLeft);
172
+ const rule = "─".repeat(Math.max(0, panelWidth - 2));
173
+ const frame = (middle) => padTo(`${shift}${middle}`, target);
174
+ const out = [frame(`${border("╭")}${border(rule)}${border("╮")}`)];
175
+ const blank = frame(`${border("│")}${" ".repeat(Math.max(0, panelWidth - 2))}${border("│")}`);
176
+ out.push(blank);
177
+ for (const line of body) {
178
+ out.push(frame(`${border("│")} ${padTo(line, inner)} ${border("│")}`));
179
+ }
180
+ out.push(blank);
181
+ out.push(frame(`${border("╰")}${border(rule)}${border("╯")}`));
182
+ return out;
183
+ }
184
+
185
+ export function renderBox({ lines, width, palette, title = "" }) {
186
+ const target = Math.max(2, Math.floor(Number(width) || 0));
187
+ const innerWidth = Math.max(0, target - 2);
188
+ const cleanTitle = truncateTo(String(title), Math.max(0, innerWidth - 2));
189
+ const titleText = cleanTitle ? ` ${cleanTitle} ` : "";
190
+ const topRule = `${titleText}${"─".repeat(Math.max(0, innerWidth - visibleWidth(titleText)))}`;
191
+ const border = (text) => palette.fg(THEME.banner_border, text);
192
+ return [
193
+ `${border("╭")}${border(topRule)}${border("╮")}`,
194
+ ...lines.map((line) => `${border("│")}${padTo(line, innerWidth)}${border("│")}`),
195
+ `${border("╰")}${border("─".repeat(innerWidth))}${border("╯")}`,
196
+ ];
197
+ }
198
+
199
+ export function compactTokens(n) {
200
+ const value = Number(n);
201
+ if (!Number.isFinite(value)) return "0";
202
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
203
+ if (value >= 1e3) return `${(value / 1e3).toFixed(0)}K`;
204
+ return String(Math.round(value));
205
+ }
206
+
207
+ export function contextBar(percent, width) {
208
+ const target = Math.max(0, Math.floor(Number(width) || 0));
209
+ const numeric = Number(percent);
210
+ const clamped = Number.isFinite(numeric) ? Math.min(100, Math.max(0, numeric)) : 0;
211
+ const filled = Math.round(target * clamped / 100);
212
+ return `${"█".repeat(filled)}${"░".repeat(target - filled)}`;
213
+ }
214
+
215
+ export function formatElapsed(ms) {
216
+ const value = Number(ms);
217
+ if (!Number.isFinite(value) || value < 0) return "0s";
218
+ const seconds = Math.floor(value / 1000);
219
+ if (seconds < 60) return `${seconds}s`;
220
+ const minutes = Math.floor(seconds / 60);
221
+ const rest = seconds % 60;
222
+ if (minutes < 60) return `${minutes}m${String(rest).padStart(2, "0")}s`;
223
+ const hours = Math.floor(minutes / 60);
224
+ return `${hours}h${String(minutes % 60).padStart(2, "0")}m`;
225
+ }
226
+
227
+ export function renderStatusBar({
228
+ model,
229
+ contextTokens,
230
+ contextLength,
231
+ percent,
232
+ effort,
233
+ thinking,
234
+ chain,
235
+ width,
236
+ palette,
237
+ }) {
238
+ const target = Math.max(0, Math.floor(Number(width) || 0));
239
+ const separator = palette.fg(THEME.status_bar_dim, " / ");
240
+ const barWidth = target >= 120 ? 12 : target >= 60 ? 8 : 4;
241
+ const tokens = Number(contextLength) > 0
242
+ ? `${compactTokens(contextTokens)}/${compactTokens(contextLength)}`
243
+ : compactTokens(contextTokens);
244
+ const pct = Number.isFinite(Number(percent)) ? `${Math.round(Number(percent))}%` : "0%";
245
+
246
+ const segments = [
247
+ { text: String(model ?? ""), strong: true },
248
+ ];
249
+ // The gateway does not know context_max until the first turn completes.
250
+ // Show nothing rather than a misleading "0 0%".
251
+ if (Number(contextLength) > 0) {
252
+ segments.push({ text: `ctx ${contextBar(percent, barWidth)} ${tokens} ${pct}` });
253
+ }
254
+ if (effort) segments.push({ text: String(effort) });
255
+ if (thinking) segments.push({ text: String(thinking) });
256
+ if (typeof chain === "string" && chain.length > 0) segments.push({ text: chain });
257
+
258
+ // Drop optional trailing segments rather than letting the bar truncate mid-word.
259
+ let kept = segments;
260
+ const plainWidth = (list) => list.reduce(
261
+ (total, segment, index) => total + visibleWidth(segment.text) + (index > 0 ? 3 : 0),
262
+ 0,
263
+ );
264
+ while (kept.length > 1 && plainWidth(kept) > target) kept = kept.slice(0, -1);
265
+
266
+ const content = kept
267
+ .map((segment) => (segment.strong
268
+ ? palette.fg(THEME.status_bar_strong, segment.text)
269
+ : palette.fg(THEME.status_bar_text, segment.text)))
270
+ .join(separator);
271
+ return palette.bg(THEME.status_bar_bg, padTo(content, target));
272
+ }
@@ -0,0 +1,177 @@
1
+ import { spawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { createInterface } from "node:readline";
4
+
5
+ const DEFAULT_STARTUP_TIMEOUT_MS = 15_000;
6
+ const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;
7
+
8
+ function errorFromPayload(payload) {
9
+ const message = typeof payload === "string"
10
+ ? payload
11
+ : payload?.message || "Gateway request failed";
12
+ const error = new Error(message);
13
+ error.error = payload;
14
+ return error;
15
+ }
16
+
17
+ function truncateLog(line) {
18
+ const bytes = Buffer.from(line);
19
+ if (bytes.length <= 4096) return line;
20
+ const removed = bytes.length - 4096;
21
+ return `${bytes.subarray(0, 4096).toString("utf8")} ... [truncated ${removed} bytes]`;
22
+ }
23
+
24
+ export function createGatewayClient({
25
+ python,
26
+ pythonArgs = [],
27
+ cwd,
28
+ env,
29
+ spawnFn = spawn,
30
+ startupTimeoutMs = DEFAULT_STARTUP_TIMEOUT_MS,
31
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
32
+ } = {}) {
33
+ const emitter = new EventEmitter();
34
+ const pending = new Map();
35
+ let child = null;
36
+ let nextId = 1;
37
+ let startPromise = null;
38
+ let stopPromise = null;
39
+ let exited = false;
40
+
41
+ function emitError(error) {
42
+ if (emitter.listenerCount("error") > 0) emitter.emit("error", error);
43
+ }
44
+
45
+ function rejectPending(error) {
46
+ for (const entry of pending.values()) {
47
+ clearTimeout(entry.timer);
48
+ entry.reject(error);
49
+ }
50
+ pending.clear();
51
+ }
52
+
53
+ function handleMessage(message) {
54
+ if (!("id" in message)) {
55
+ emitter.emit("event", message);
56
+ return;
57
+ }
58
+ const entry = pending.get(message.id);
59
+ if (!entry) return;
60
+ pending.delete(message.id);
61
+ clearTimeout(entry.timer);
62
+ if ("error" in message) entry.reject(errorFromPayload(message.error));
63
+ else entry.resolve(message.result);
64
+ }
65
+
66
+ function start() {
67
+ if (startPromise) return startPromise;
68
+
69
+ startPromise = new Promise((resolve, reject) => {
70
+ let settled = false;
71
+ let startupTimer;
72
+
73
+ const finishStart = (error) => {
74
+ if (settled) return;
75
+ settled = true;
76
+ clearTimeout(startupTimer);
77
+ if (error) reject(error);
78
+ else resolve();
79
+ };
80
+
81
+ try {
82
+ child = spawnFn(python, [...pythonArgs, "-m", "tui_gateway.entry"], { cwd, env });
83
+ } catch (error) {
84
+ finishStart(error);
85
+ emitError(error);
86
+ return;
87
+ }
88
+
89
+ const stdout = createInterface({ input: child.stdout });
90
+ const stderr = createInterface({ input: child.stderr });
91
+
92
+ stdout.on("line", (line) => {
93
+ let message;
94
+ try {
95
+ message = JSON.parse(line);
96
+ } catch {
97
+ emitter.emit("log", line);
98
+ return;
99
+ }
100
+ finishStart();
101
+ handleMessage(message);
102
+ });
103
+
104
+ stderr.on("line", (line) => emitter.emit("log", truncateLog(line)));
105
+
106
+ child.once("error", (error) => {
107
+ finishStart(error);
108
+ rejectPending(error);
109
+ emitError(error);
110
+ });
111
+
112
+ child.once("exit", (code, signal) => {
113
+ exited = true;
114
+ const error = new Error(`Gateway exited with code ${code} and signal ${signal}`);
115
+ finishStart(error);
116
+ rejectPending(error);
117
+ emitter.emit("exit", { code, signal });
118
+ });
119
+
120
+ startupTimer = setTimeout(() => {
121
+ finishStart(new Error(`Gateway startup timed out after ${startupTimeoutMs} ms`));
122
+ }, startupTimeoutMs);
123
+ });
124
+
125
+ return startPromise;
126
+ }
127
+
128
+ function request(method, params) {
129
+ if (!child || exited) return Promise.reject(new Error("Gateway is not running"));
130
+ const id = nextId++;
131
+ return new Promise((resolve, reject) => {
132
+ const timer = setTimeout(() => {
133
+ pending.delete(id);
134
+ reject(new Error(`Gateway request ${id} timed out after ${requestTimeoutMs} ms`));
135
+ }, requestTimeoutMs);
136
+ pending.set(id, { resolve, reject, timer });
137
+ try {
138
+ child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
139
+ } catch (error) {
140
+ clearTimeout(timer);
141
+ pending.delete(id);
142
+ reject(error);
143
+ }
144
+ });
145
+ }
146
+
147
+ function stop() {
148
+ if (stopPromise) return stopPromise;
149
+ if (!child || exited) return Promise.resolve();
150
+
151
+ const error = new Error("Gateway stopped while requests were pending");
152
+ rejectPending(error);
153
+ stopPromise = new Promise((resolve) => {
154
+ child.once("exit", resolve);
155
+ try {
156
+ child.kill();
157
+ } catch {
158
+ resolve();
159
+ }
160
+ });
161
+ return stopPromise;
162
+ }
163
+
164
+ return {
165
+ start,
166
+ request,
167
+ stop,
168
+ on(event, listener) {
169
+ emitter.on(event, listener);
170
+ return this;
171
+ },
172
+ off(event, listener) {
173
+ emitter.off(event, listener);
174
+ return this;
175
+ },
176
+ };
177
+ }