open-agents-ai 0.66.0 → 0.67.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.
Files changed (2) hide show
  1. package/dist/index.js +623 -50
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -19129,14 +19129,14 @@ var require_extension = __commonJS({
19129
19129
  var require_websocket = __commonJS({
19130
19130
  "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js"(exports, module) {
19131
19131
  "use strict";
19132
- var EventEmitter4 = __require("events");
19132
+ var EventEmitter5 = __require("events");
19133
19133
  var https = __require("https");
19134
19134
  var http = __require("http");
19135
19135
  var net = __require("net");
19136
19136
  var tls = __require("tls");
19137
- var { randomBytes: randomBytes5, createHash: createHash2 } = __require("crypto");
19137
+ var { randomBytes: randomBytes6, createHash: createHash2 } = __require("crypto");
19138
19138
  var { Duplex, Readable } = __require("stream");
19139
- var { URL: URL2 } = __require("url");
19139
+ var { URL: URL3 } = __require("url");
19140
19140
  var PerMessageDeflate = require_permessage_deflate();
19141
19141
  var Receiver2 = require_receiver();
19142
19142
  var Sender2 = require_sender();
@@ -19161,7 +19161,7 @@ var require_websocket = __commonJS({
19161
19161
  var protocolVersions = [8, 13];
19162
19162
  var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
19163
19163
  var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
19164
- var WebSocket2 = class _WebSocket extends EventEmitter4 {
19164
+ var WebSocket2 = class _WebSocket extends EventEmitter5 {
19165
19165
  /**
19166
19166
  * Create a new `WebSocket`.
19167
19167
  *
@@ -19629,11 +19629,11 @@ var require_websocket = __commonJS({
19629
19629
  );
19630
19630
  }
19631
19631
  let parsedUrl;
19632
- if (address instanceof URL2) {
19632
+ if (address instanceof URL3) {
19633
19633
  parsedUrl = address;
19634
19634
  } else {
19635
19635
  try {
19636
- parsedUrl = new URL2(address);
19636
+ parsedUrl = new URL3(address);
19637
19637
  } catch (e) {
19638
19638
  throw new SyntaxError(`Invalid URL: ${address}`);
19639
19639
  }
@@ -19664,7 +19664,7 @@ var require_websocket = __commonJS({
19664
19664
  }
19665
19665
  }
19666
19666
  const defaultPort = isSecure ? 443 : 80;
19667
- const key = randomBytes5(16).toString("base64");
19667
+ const key = randomBytes6(16).toString("base64");
19668
19668
  const request = isSecure ? https.request : http.request;
19669
19669
  const protocolSet = /* @__PURE__ */ new Set();
19670
19670
  let perMessageDeflate;
@@ -19770,7 +19770,7 @@ var require_websocket = __commonJS({
19770
19770
  req.abort();
19771
19771
  let addr;
19772
19772
  try {
19773
- addr = new URL2(location, address);
19773
+ addr = new URL3(location, address);
19774
19774
  } catch (e) {
19775
19775
  const err = new SyntaxError(`Invalid URL: ${location}`);
19776
19776
  emitErrorAndClose(websocket, err);
@@ -20158,7 +20158,7 @@ var require_subprotocol = __commonJS({
20158
20158
  var require_websocket_server = __commonJS({
20159
20159
  "node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
20160
20160
  "use strict";
20161
- var EventEmitter4 = __require("events");
20161
+ var EventEmitter5 = __require("events");
20162
20162
  var http = __require("http");
20163
20163
  var { Duplex } = __require("stream");
20164
20164
  var { createHash: createHash2 } = __require("crypto");
@@ -20171,7 +20171,7 @@ var require_websocket_server = __commonJS({
20171
20171
  var RUNNING = 0;
20172
20172
  var CLOSING = 1;
20173
20173
  var CLOSED = 2;
20174
- var WebSocketServer2 = class extends EventEmitter4 {
20174
+ var WebSocketServer2 = class extends EventEmitter5 {
20175
20175
  /**
20176
20176
  * Create a `WebSocketServer` instance.
20177
20177
  *
@@ -22173,8 +22173,275 @@ var init_voice_session = __esm({
22173
22173
  }
22174
22174
  });
22175
22175
 
22176
- // packages/cli/dist/tui/call-agent.js
22176
+ // packages/cli/dist/tui/expose.js
22177
+ import { createServer as createServer2, request as httpRequest } from "node:http";
22178
+ import { spawn as spawn11 } from "node:child_process";
22177
22179
  import { EventEmitter as EventEmitter3 } from "node:events";
22180
+ import { randomBytes as randomBytes5 } from "node:crypto";
22181
+ import { URL as URL2 } from "node:url";
22182
+ var DEFAULT_TARGETS, ExposeGateway;
22183
+ var init_expose = __esm({
22184
+ "packages/cli/dist/tui/expose.js"() {
22185
+ "use strict";
22186
+ init_render();
22187
+ DEFAULT_TARGETS = {
22188
+ ollama: "http://127.0.0.1:11434",
22189
+ vllm: "http://127.0.0.1:8000",
22190
+ llvm: "http://127.0.0.1:8080",
22191
+ custom: "http://127.0.0.1:11434"
22192
+ };
22193
+ ExposeGateway = class extends EventEmitter3 {
22194
+ options;
22195
+ server = null;
22196
+ cloudflaredProcess = null;
22197
+ _tunnelUrl = null;
22198
+ _authKey;
22199
+ _targetUrl;
22200
+ _kind;
22201
+ _stats = {
22202
+ status: "standby",
22203
+ totalRequests: 0,
22204
+ activeConnections: 0,
22205
+ errors: 0,
22206
+ modelUsage: /* @__PURE__ */ new Map()
22207
+ };
22208
+ get tunnelUrl() {
22209
+ return this._tunnelUrl;
22210
+ }
22211
+ get authKey() {
22212
+ return this._authKey;
22213
+ }
22214
+ get stats() {
22215
+ return this._stats;
22216
+ }
22217
+ get kind() {
22218
+ return this._kind;
22219
+ }
22220
+ get isActive() {
22221
+ return this._stats.status === "active";
22222
+ }
22223
+ constructor(options) {
22224
+ super();
22225
+ this.options = options;
22226
+ this._kind = options.kind;
22227
+ this._targetUrl = options.targetUrl ?? DEFAULT_TARGETS[options.kind];
22228
+ if (options.authKey === void 0 || options.authKey === "") {
22229
+ this._authKey = randomBytes5(24).toString("base64url");
22230
+ } else {
22231
+ this._authKey = options.authKey;
22232
+ }
22233
+ }
22234
+ // ── Lifecycle ───────────────────────────────────────────────────────────
22235
+ async start() {
22236
+ if (this.server)
22237
+ throw new Error("Gateway already running");
22238
+ const port = await this.findFreePort();
22239
+ this.server = this.createProxyServer(port);
22240
+ await new Promise((resolve28, reject) => {
22241
+ this.server.listen(port, "127.0.0.1", () => resolve28());
22242
+ this.server.on("error", reject);
22243
+ });
22244
+ this._tunnelUrl = await this.startCloudflared(port);
22245
+ this._stats.status = "active";
22246
+ this.emitStats();
22247
+ return this._tunnelUrl;
22248
+ }
22249
+ async stop() {
22250
+ if (this.cloudflaredProcess) {
22251
+ this.cloudflaredProcess.kill("SIGTERM");
22252
+ this.cloudflaredProcess = null;
22253
+ }
22254
+ if (this.server) {
22255
+ await new Promise((resolve28) => {
22256
+ this.server.close(() => resolve28());
22257
+ });
22258
+ this.server = null;
22259
+ }
22260
+ this._tunnelUrl = null;
22261
+ this._stats.status = "standby";
22262
+ this._stats.activeConnections = 0;
22263
+ this.emitStats();
22264
+ }
22265
+ // ── Proxy server ────────────────────────────────────────────────────────
22266
+ createProxyServer(localPort) {
22267
+ const target = new URL2(this._targetUrl);
22268
+ return createServer2((req, res) => {
22269
+ const authHeader = req.headers.authorization;
22270
+ const url = new URL2(req.url ?? "/", `http://127.0.0.1:${localPort}`);
22271
+ const queryKey = url.searchParams.get("key");
22272
+ const providedKey = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : queryKey;
22273
+ if (providedKey !== this._authKey) {
22274
+ this._stats.errors++;
22275
+ res.writeHead(401, { "Content-Type": "application/json" });
22276
+ res.end(JSON.stringify({ error: "Unauthorized \u2014 provide Bearer token or ?key= parameter" }));
22277
+ this.emitStats();
22278
+ return;
22279
+ }
22280
+ this._stats.totalRequests++;
22281
+ this._stats.activeConnections++;
22282
+ this.emitStats();
22283
+ this.extractModelFromRequest(req);
22284
+ url.searchParams.delete("key");
22285
+ const forwardPath = url.pathname + url.search;
22286
+ const forwardHeaders = { ...req.headers, host: target.host };
22287
+ delete forwardHeaders.authorization;
22288
+ const proxyReq = httpRequest({
22289
+ hostname: target.hostname,
22290
+ port: target.port || (target.protocol === "https:" ? 443 : 80),
22291
+ path: forwardPath,
22292
+ method: req.method,
22293
+ headers: forwardHeaders
22294
+ }, (proxyRes) => {
22295
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
22296
+ proxyRes.pipe(res);
22297
+ proxyRes.on("end", () => {
22298
+ this._stats.activeConnections = Math.max(0, this._stats.activeConnections - 1);
22299
+ this.emitStats();
22300
+ });
22301
+ });
22302
+ proxyReq.on("error", (err) => {
22303
+ this._stats.errors++;
22304
+ this._stats.activeConnections = Math.max(0, this._stats.activeConnections - 1);
22305
+ if (!res.headersSent) {
22306
+ res.writeHead(502, { "Content-Type": "application/json" });
22307
+ res.end(JSON.stringify({ error: `Backend unreachable: ${err.message}` }));
22308
+ }
22309
+ this._stats.status = "error";
22310
+ this.emitStats();
22311
+ setTimeout(() => {
22312
+ if (this.server && this._stats.status === "error") {
22313
+ this._stats.status = "active";
22314
+ this.emitStats();
22315
+ }
22316
+ }, 5e3);
22317
+ });
22318
+ req.pipe(proxyReq);
22319
+ });
22320
+ }
22321
+ /** Best-effort model name extraction from JSON body for usage tracking */
22322
+ extractModelFromRequest(req) {
22323
+ if (req.method !== "POST")
22324
+ return;
22325
+ const chunks = [];
22326
+ const origEmit = req.emit.bind(req);
22327
+ let peeked = false;
22328
+ const stats = this._stats;
22329
+ req.emit = function(event, ...args) {
22330
+ if (event === "data" && !peeked) {
22331
+ peeked = true;
22332
+ try {
22333
+ const chunk = args[0];
22334
+ chunks.push(chunk);
22335
+ const text = Buffer.concat(chunks).toString();
22336
+ const modelMatch = text.match(/"model"\s*:\s*"([^"]+)"/);
22337
+ if (modelMatch) {
22338
+ const model = modelMatch[1];
22339
+ const count = stats.modelUsage.get(model) ?? 0;
22340
+ stats.modelUsage.set(model, count + 1);
22341
+ }
22342
+ } catch {
22343
+ }
22344
+ }
22345
+ return origEmit(event, ...args);
22346
+ };
22347
+ }
22348
+ // ── Cloudflared ─────────────────────────────────────────────────────────
22349
+ startCloudflared(port) {
22350
+ return new Promise((resolve28, reject) => {
22351
+ const timeout = setTimeout(() => {
22352
+ reject(new Error("Cloudflared tunnel start timeout (30s)"));
22353
+ }, 3e4);
22354
+ this.cloudflaredProcess = spawn11("cloudflared", [
22355
+ "tunnel",
22356
+ "--url",
22357
+ `http://127.0.0.1:${port}`
22358
+ ], {
22359
+ stdio: ["ignore", "pipe", "pipe"]
22360
+ });
22361
+ let urlFound = false;
22362
+ const handleOutput = (data) => {
22363
+ const text = data.toString();
22364
+ const urlMatch = text.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
22365
+ if (urlMatch && !urlFound) {
22366
+ urlFound = true;
22367
+ clearTimeout(timeout);
22368
+ resolve28(urlMatch[0]);
22369
+ }
22370
+ };
22371
+ this.cloudflaredProcess.stdout?.on("data", handleOutput);
22372
+ this.cloudflaredProcess.stderr?.on("data", handleOutput);
22373
+ this.cloudflaredProcess.on("error", (err) => {
22374
+ clearTimeout(timeout);
22375
+ reject(new Error(`Failed to start cloudflared: ${err.message}`));
22376
+ });
22377
+ this.cloudflaredProcess.on("close", (code) => {
22378
+ if (!urlFound) {
22379
+ clearTimeout(timeout);
22380
+ reject(new Error(`Cloudflared exited with code ${code} before providing URL`));
22381
+ }
22382
+ if (this._stats.status === "active") {
22383
+ this._stats.status = "error";
22384
+ this.emitStats();
22385
+ }
22386
+ });
22387
+ });
22388
+ }
22389
+ // ── Helpers ─────────────────────────────────────────────────────────────
22390
+ findFreePort() {
22391
+ return new Promise((resolve28, reject) => {
22392
+ const srv = createServer2();
22393
+ srv.listen(0, "127.0.0.1", () => {
22394
+ const addr = srv.address();
22395
+ if (addr && typeof addr === "object") {
22396
+ const port = addr.port;
22397
+ srv.close(() => resolve28(port));
22398
+ } else {
22399
+ srv.close(() => reject(new Error("Could not find free port")));
22400
+ }
22401
+ });
22402
+ srv.on("error", reject);
22403
+ });
22404
+ }
22405
+ emitStats() {
22406
+ this.emit("stats", { ...this._stats, modelUsage: new Map(this._stats.modelUsage) });
22407
+ }
22408
+ /** Format connection info for display */
22409
+ formatConnectionInfo() {
22410
+ const lines = [];
22411
+ lines.push(` ${c2.green("\u25CF")} Expose gateway active`);
22412
+ lines.push(` ${c2.cyan("Backend".padEnd(12))} ${this._kind} (${this._targetUrl})`);
22413
+ lines.push(` ${c2.cyan("Tunnel".padEnd(12))} ${c2.bold(this._tunnelUrl ?? "starting...")}`);
22414
+ lines.push(` ${c2.cyan("Auth Key".padEnd(12))} ${c2.bold(this._authKey)}`);
22415
+ lines.push("");
22416
+ lines.push(` ${c2.dim("Remote users connect with:")}`);
22417
+ lines.push(` ${c2.bold(`/endpoint ${this._tunnelUrl ?? "<tunnel-url>"} --auth ${this._authKey}`)}`);
22418
+ lines.push("");
22419
+ lines.push(` ${c2.yellow("!")} ${c2.dim("Keep this key secure \u2014 it grants full access to your models.")}`);
22420
+ return lines.join("\n");
22421
+ }
22422
+ /** Format usage stats for display */
22423
+ formatStats() {
22424
+ const s = this._stats;
22425
+ const lines = [];
22426
+ lines.push(` ${c2.bold("Expose Gateway Stats")}`);
22427
+ lines.push(` ${c2.cyan("Status".padEnd(16))} ${s.status === "active" ? c2.green("active") : s.status === "error" ? c2.red("error") : c2.yellow("standby")}`);
22428
+ lines.push(` ${c2.cyan("Total requests".padEnd(16))} ${s.totalRequests}`);
22429
+ lines.push(` ${c2.cyan("Active conns".padEnd(16))} ${s.activeConnections}`);
22430
+ lines.push(` ${c2.cyan("Errors".padEnd(16))} ${s.errors}`);
22431
+ if (s.modelUsage.size > 0) {
22432
+ lines.push(` ${c2.cyan("Models used:")}`);
22433
+ for (const [model, count] of s.modelUsage) {
22434
+ lines.push(` ${model}: ${count} requests`);
22435
+ }
22436
+ }
22437
+ return lines.join("\n");
22438
+ }
22439
+ };
22440
+ }
22441
+ });
22442
+
22443
+ // packages/cli/dist/tui/call-agent.js
22444
+ import { EventEmitter as EventEmitter4 } from "node:events";
22178
22445
  import crypto2 from "node:crypto";
22179
22446
  function adaptTool(tool) {
22180
22447
  return {
@@ -22234,7 +22501,7 @@ var init_call_agent = __esm({
22234
22501
  }
22235
22502
  };
22236
22503
  _globalFeed = null;
22237
- CallSubAgent = class extends EventEmitter3 {
22504
+ CallSubAgent = class extends EventEmitter4 {
22238
22505
  tier;
22239
22506
  clientId;
22240
22507
  runner = null;
@@ -23269,7 +23536,7 @@ var init_oa_directory = __esm({
23269
23536
 
23270
23537
  // packages/cli/dist/tui/setup.js
23271
23538
  import * as readline from "node:readline";
23272
- import { execSync as execSync20, spawn as spawn11 } from "node:child_process";
23539
+ import { execSync as execSync20, spawn as spawn12 } from "node:child_process";
23273
23540
  import { existsSync as existsSync22, writeFileSync as writeFileSync8, mkdirSync as mkdirSync8 } from "node:fs";
23274
23541
  import { join as join31 } from "node:path";
23275
23542
  import { homedir as homedir10, platform } from "node:os";
@@ -23755,7 +24022,7 @@ async function doSetup(config, rl) {
23755
24022
  ${c2.cyan("\u25CF")} Starting ollama serve in background...
23756
24023
  `);
23757
24024
  try {
23758
- const child = spawn11("ollama", ["serve"], { stdio: "ignore", detached: true });
24025
+ const child = spawn12("ollama", ["serve"], { stdio: "ignore", detached: true });
23759
24026
  child.unref();
23760
24027
  await new Promise((resolve28) => setTimeout(resolve28, 3e3));
23761
24028
  try {
@@ -23783,7 +24050,7 @@ async function doSetup(config, rl) {
23783
24050
  ${c2.cyan("\u25CF")} Starting ollama serve...
23784
24051
  `);
23785
24052
  try {
23786
- const child = spawn11("ollama", ["serve"], { stdio: "ignore", detached: true });
24053
+ const child = spawn12("ollama", ["serve"], { stdio: "ignore", detached: true });
23787
24054
  child.unref();
23788
24055
  await new Promise((resolve28) => setTimeout(resolve28, 3e3));
23789
24056
  try {
@@ -24897,6 +25164,71 @@ async function handleSlashCommand(input, ctx) {
24897
25164
  }
24898
25165
  return "handled";
24899
25166
  }
25167
+ case "expose": {
25168
+ if (!ctx.exposeStart) {
25169
+ renderWarning("Expose gateway not available in this context.");
25170
+ return "handled";
25171
+ }
25172
+ if (arg === "stop" || arg === "off") {
25173
+ if (ctx.isExposeActive?.()) {
25174
+ await ctx.exposeStop?.();
25175
+ renderInfo("Expose gateway stopped.");
25176
+ } else {
25177
+ renderWarning("No active expose gateway.");
25178
+ }
25179
+ return "handled";
25180
+ }
25181
+ if (arg === "status") {
25182
+ const info = ctx.getExposeInfo?.();
25183
+ if (info) {
25184
+ process.stdout.write("\n" + info.stats + "\n\n");
25185
+ } else {
25186
+ renderWarning("No active expose gateway.");
25187
+ }
25188
+ return "handled";
25189
+ }
25190
+ if (!arg) {
25191
+ const info = ctx.getExposeInfo?.();
25192
+ if (info && ctx.isExposeActive?.()) {
25193
+ process.stdout.write("\n" + info.stats + "\n\n");
25194
+ } else {
25195
+ renderInfo("Usage: /expose <backend> [--key <auth-key>]");
25196
+ renderInfo(" /expose ollama Expose local Ollama (11434)");
25197
+ renderInfo(" /expose vllm Expose local vLLM (8000)");
25198
+ renderInfo(" /expose llvm Expose local LLVM (8080)");
25199
+ renderInfo(" /expose host:port Expose custom address");
25200
+ renderInfo(" /expose stop Stop the gateway");
25201
+ renderInfo(" /expose status Show usage stats");
25202
+ renderInfo(" --key <key> Use specific auth key");
25203
+ renderInfo(" --key Auto-generate auth key");
25204
+ }
25205
+ return "handled";
25206
+ }
25207
+ if (ctx.isExposeActive?.()) {
25208
+ await ctx.exposeStop?.();
25209
+ }
25210
+ const exposeParts = arg.split(/\s+/);
25211
+ const kindOrUrl = exposeParts[0];
25212
+ let exposeAuthKey;
25213
+ const keyIdx = exposeParts.indexOf("--key");
25214
+ if (keyIdx !== -1) {
25215
+ exposeAuthKey = exposeParts[keyIdx + 1] ?? "";
25216
+ }
25217
+ try {
25218
+ const tunnelUrl = await ctx.exposeStart(kindOrUrl, exposeAuthKey);
25219
+ if (tunnelUrl) {
25220
+ const info = ctx.getExposeInfo?.();
25221
+ if (info) {
25222
+ process.stdout.write("\n" + info.stats + "\n\n");
25223
+ }
25224
+ } else {
25225
+ renderError("Failed to start expose gateway.");
25226
+ }
25227
+ } catch (err) {
25228
+ renderError(`Expose error: ${err instanceof Error ? err.message : String(err)}`);
25229
+ }
25230
+ return "handled";
25231
+ }
24900
25232
  case "bruteforce":
24901
25233
  case "brute": {
24902
25234
  const isOn = ctx.bruteForceToggle();
@@ -33578,7 +33910,7 @@ var init_status_bar = __esm({
33578
33910
  return this.toolCalls > 0;
33579
33911
  }
33580
33912
  };
33581
- StatusBar = class {
33913
+ StatusBar = class _StatusBar {
33582
33914
  metrics = {
33583
33915
  promptTokens: 0,
33584
33916
  completionTokens: 0,
@@ -33794,6 +34126,20 @@ var init_status_bar = __esm({
33794
34126
  if (this.active)
33795
34127
  this.renderFooterPreserveCursor();
33796
34128
  }
34129
+ /** Expose gateway status — shown after capability emojis */
34130
+ _expose = null;
34131
+ /** Update expose gateway status */
34132
+ setExposeStatus(status) {
34133
+ this._expose = status;
34134
+ if (this.active)
34135
+ this.renderFooterPreserveCursor();
34136
+ }
34137
+ /** Clear expose gateway status */
34138
+ clearExposeStatus() {
34139
+ this._expose = null;
34140
+ if (this.active)
34141
+ this.renderFooterPreserveCursor();
34142
+ }
33797
34143
  /** Update token metrics from a token_usage event */
33798
34144
  updateMetrics(update) {
33799
34145
  if (update.promptTokens !== void 0)
@@ -33963,68 +34309,239 @@ var init_status_bar = __esm({
33963
34309
  const pos = this.rowPositions(rows);
33964
34310
  process.stdout.write(`\x1B[${pos.inputStartRow};1H\x1B[2K`);
33965
34311
  }
33966
- /** Build the metrics line string */
34312
+ /** Strip ANSI escape codes to measure visible character width */
34313
+ static visWidth(s) {
34314
+ const stripped = s.replace(/\x1B\[[0-9;]*m/g, "");
34315
+ let w = 0;
34316
+ for (const ch of stripped) {
34317
+ const cp = ch.codePointAt(0) ?? 0;
34318
+ if (cp >= 127744 && cp <= 129784)
34319
+ w += 2;
34320
+ else
34321
+ w += 1;
34322
+ }
34323
+ return w;
34324
+ }
34325
+ /** Format number compactly: 1234 → "1.2K", 567 → "567" */
34326
+ static compactNum(n) {
34327
+ if (n < 0)
34328
+ return "0";
34329
+ if (n < 1e3)
34330
+ return String(n);
34331
+ if (n < 1e4)
34332
+ return `${(n / 1e3).toFixed(1)}K`;
34333
+ if (n < 1e6)
34334
+ return `${Math.round(n / 1e3)}K`;
34335
+ return `${(n / 1e6).toFixed(1)}M`;
34336
+ }
34337
+ /** Build the metrics line string with adaptive compaction */
33967
34338
  buildMetricsLine() {
33968
34339
  const m = this.metrics;
34340
+ const termWidth = getTermWidth();
33969
34341
  const pastel2 = (code, s) => `\x1B[38;5;${code}m${s}\x1B[0m`;
33970
34342
  const pipe = pastel2(60, " \u2502 ");
33971
- const tokIn = m.promptTokens > 0 ? m.promptTokens.toLocaleString() : `~${Math.max(m.estimatedContextTokens, 0).toLocaleString()}`;
33972
- const tokInLabel = pastel2(117, "In: ") + c2.bold(tokIn);
34343
+ const pipeW = 3;
34344
+ const sections = [];
34345
+ const tokInRaw = m.promptTokens > 0 ? m.promptTokens : Math.max(m.estimatedContextTokens, 0);
34346
+ const tokInPrefix = m.promptTokens > 0 ? "" : "~";
34347
+ const tokInExpanded = pastel2(117, "In: ") + c2.bold(tokInPrefix + tokInRaw.toLocaleString());
34348
+ const tokInCompact = pastel2(117, "I:") + c2.bold(tokInPrefix + _StatusBar.compactNum(tokInRaw));
34349
+ sections.push({
34350
+ expanded: tokInExpanded,
34351
+ compact: tokInCompact,
34352
+ expandedW: 4 + (tokInPrefix + tokInRaw.toLocaleString()).length,
34353
+ compactW: 2 + (tokInPrefix + _StatusBar.compactNum(tokInRaw)).length,
34354
+ empty: false
34355
+ });
33973
34356
  const effectiveOut = this.effectiveCompletionTokens;
33974
- const tokOut = effectiveOut > 0 ? effectiveOut.toLocaleString() : `~${Math.ceil(m.totalTokens > 0 ? m.totalTokens - m.promptTokens : m.estimatedContextTokens * 0.3).toLocaleString()}`;
33975
- const tokOutLabel = pastel2(151, "Out: ") + c2.bold(tokOut);
34357
+ const tokOutRaw = effectiveOut > 0 ? effectiveOut : Math.ceil(m.totalTokens > 0 ? m.totalTokens - m.promptTokens : m.estimatedContextTokens * 0.3);
34358
+ const tokOutPrefix = effectiveOut > 0 ? "" : "~";
34359
+ const tokOutExpanded = pastel2(151, "Out: ") + c2.bold(tokOutPrefix + Math.max(0, tokOutRaw).toLocaleString());
34360
+ const tokOutCompact = pastel2(151, "O:") + c2.bold(tokOutPrefix + _StatusBar.compactNum(Math.max(0, tokOutRaw)));
34361
+ sections.push({
34362
+ expanded: tokOutExpanded,
34363
+ compact: tokOutCompact,
34364
+ expandedW: 5 + (tokOutPrefix + Math.max(0, tokOutRaw).toLocaleString()).length,
34365
+ compactW: 2 + (tokOutPrefix + _StatusBar.compactNum(Math.max(0, tokOutRaw))).length,
34366
+ empty: false
34367
+ });
33976
34368
  const ctxUsed = m.estimatedContextTokens;
33977
34369
  const ctxTotal = m.contextWindowSize;
33978
- let ctxLabel;
34370
+ let ctxExpanded;
34371
+ let ctxCompact;
34372
+ let ctxExpandedW;
34373
+ let ctxCompactW;
33979
34374
  if (ctxTotal <= 0) {
33980
- ctxLabel = pastel2(153, "Ctx: ") + c2.dim("--");
34375
+ ctxExpanded = pastel2(153, "Ctx: ") + c2.dim("--");
34376
+ ctxCompact = pastel2(153, "Ctx:") + c2.dim("--");
34377
+ ctxExpandedW = 7;
34378
+ ctxCompactW = 6;
33981
34379
  } else {
33982
34380
  const ctxPct = Math.max(0, Math.min(100, Math.round((1 - ctxUsed / ctxTotal) * 100)));
33983
34381
  const ctxColor = ctxPct > 50 ? c2.green : ctxPct > 20 ? c2.yellow : c2.red;
33984
- ctxLabel = pastel2(153, "Ctx: ") + c2.bold(`${ctxUsed.toLocaleString()}/${ctxTotal.toLocaleString()}`) + ` ${ctxColor(`${ctxPct}%`)}`;
33985
- }
33986
- let costLabel = "";
33987
- if (m.hasPricing && m.estimatedCost !== void 0) {
33988
- const costStr = m.estimatedCost < 0.01 ? `$${m.estimatedCost.toFixed(4)}` : m.estimatedCost < 1 ? `$${m.estimatedCost.toFixed(3)}` : `$${m.estimatedCost.toFixed(2)}`;
33989
- costLabel = pipe + pastel2(222, "Cost: ") + c2.bold(costStr);
34382
+ const ctxFullStr = `${ctxUsed.toLocaleString()}/${ctxTotal.toLocaleString()}`;
34383
+ ctxExpanded = pastel2(153, "Ctx: ") + c2.bold(ctxFullStr) + ` ${ctxColor(`${ctxPct}%`)}`;
34384
+ ctxCompact = pastel2(153, "Ctx:") + ctxColor(`${ctxPct}%`);
34385
+ ctxExpandedW = 5 + ctxFullStr.length + 1 + `${ctxPct}%`.length;
34386
+ ctxCompactW = 4 + `${ctxPct}%`.length;
33990
34387
  }
33991
- let snrLabel = "";
34388
+ sections.push({ expanded: ctxExpanded, compact: ctxCompact, expandedW: ctxExpandedW, compactW: ctxCompactW, empty: false });
33992
34389
  if (this._snr) {
33993
34390
  const snrPct = Math.round(this._snr.ratio * 100);
33994
34391
  const snrColor = snrPct >= 70 ? c2.green : snrPct >= 40 ? c2.yellow : c2.red;
33995
34392
  const dPrimeStr = this._snr.dPrime.toFixed(1);
33996
34393
  const capStr = this._snr.capacityWarning ? c2.red(" !CAP") : "";
33997
- snrLabel = pipe + pastel2(183, "SNR: ") + snrColor(c2.bold(`${snrPct}%`)) + c2.dim(` d'${dPrimeStr}`) + capStr;
34394
+ const snrExpanded = pastel2(183, "SNR: ") + snrColor(c2.bold(`${snrPct}%`)) + c2.dim(` d'${dPrimeStr}`) + capStr;
34395
+ const snrCompact = snrColor(`${snrPct}%`);
34396
+ const expW = 5 + `${snrPct}%`.length + 3 + dPrimeStr.length + (this._snr.capacityWarning ? 5 : 0);
34397
+ sections.push({ expanded: snrExpanded, compact: snrCompact, expandedW: expW, compactW: `${snrPct}%`.length, empty: false });
33998
34398
  }
33999
- let emotionLabel = "";
34000
34399
  if (this._emotion) {
34001
- emotionLabel = pipe + this._emotion.emoji + " " + pastel2(183, this._emotion.label);
34400
+ const emotionExpanded = this._emotion.emoji + " " + pastel2(183, this._emotion.label);
34401
+ const emotionCompact = this._emotion.emoji;
34402
+ sections.push({
34403
+ expanded: emotionExpanded,
34404
+ compact: emotionCompact,
34405
+ expandedW: 2 + 1 + this._emotion.label.length,
34406
+ // emoji(2) + space + label
34407
+ compactW: 2,
34408
+ // just emoji
34409
+ empty: false
34410
+ });
34002
34411
  }
34003
- let speedLabel = "";
34004
34412
  if (this._speedTracker.hasData) {
34005
34413
  const ratio = this._speedTracker.getSpeedRatio();
34006
34414
  if (ratio > 0) {
34007
34415
  const ratioStr = ratio >= 10 ? `${Math.round(ratio)}x` : `${ratio.toFixed(1)}x`;
34008
34416
  const ratioColor = ratio >= 2 ? c2.green : ratio >= 1 ? c2.yellow : c2.red;
34009
- speedLabel = pipe + pastel2(218, "Exp: ") + ratioColor(c2.bold(ratioStr));
34417
+ const speedExpanded = pastel2(218, "Exp: ") + ratioColor(c2.bold(ratioStr));
34418
+ sections.push({
34419
+ expanded: speedExpanded,
34420
+ compact: speedExpanded,
34421
+ expandedW: 5 + ratioStr.length,
34422
+ compactW: 5 + ratioStr.length,
34423
+ empty: false
34424
+ });
34010
34425
  }
34011
34426
  }
34012
- let recordingLabel = "";
34427
+ if (m.hasPricing && m.estimatedCost !== void 0) {
34428
+ const costStr = m.estimatedCost < 0.01 ? `$${m.estimatedCost.toFixed(4)}` : m.estimatedCost < 1 ? `$${m.estimatedCost.toFixed(3)}` : `$${m.estimatedCost.toFixed(2)}`;
34429
+ const costExpanded = pastel2(222, "Cost: ") + c2.bold(costStr);
34430
+ const costCompact = pastel2(222, "") + c2.bold(costStr);
34431
+ sections.push({
34432
+ expanded: costExpanded,
34433
+ compact: costCompact,
34434
+ expandedW: 6 + costStr.length,
34435
+ compactW: costStr.length,
34436
+ empty: false
34437
+ });
34438
+ }
34439
+ if (this._modelName) {
34440
+ const capParts = [];
34441
+ if (this._caps.vision)
34442
+ capParts.push("\u{1F441}");
34443
+ if (this._caps.toolUse)
34444
+ capParts.push("\u{1F527}");
34445
+ if (this._caps.thinking)
34446
+ capParts.push("\u{1F9E0}");
34447
+ const capsStr = capParts.length > 0 ? " " + capParts.join(" ") : "";
34448
+ const capsVisW = capParts.length > 0 ? 1 + capParts.length * 2 + (capParts.length - 1) : 0;
34449
+ const paramMatch = this._modelName.match(/(\d+\.?\d*[bBmM])/);
34450
+ const paramStr = paramMatch ? paramMatch[1] : this._modelName.split(":")[0]?.split("/").pop() ?? this._modelName;
34451
+ const modelExpanded = pastel2(146, this._modelName) + (capsStr ? pastel2(60, " ") + pastel2(183, capParts.join(" ")) : "");
34452
+ const modelCompact = pastel2(146, paramStr) + (capsStr ? pastel2(60, " ") + pastel2(183, capParts.join(" ")) : "");
34453
+ sections.push({
34454
+ expanded: modelExpanded,
34455
+ compact: modelCompact,
34456
+ expandedW: this._modelName.length + capsVisW,
34457
+ compactW: paramStr.length + capsVisW,
34458
+ empty: false
34459
+ });
34460
+ } else {
34461
+ const capParts = [];
34462
+ if (this._caps.vision)
34463
+ capParts.push("\u{1F441}");
34464
+ if (this._caps.toolUse)
34465
+ capParts.push("\u{1F527}");
34466
+ if (this._caps.thinking)
34467
+ capParts.push("\u{1F9E0}");
34468
+ if (capParts.length > 0) {
34469
+ const capsStr = pastel2(183, capParts.join(" "));
34470
+ const capsVisW = capParts.length * 2 + (capParts.length - 1);
34471
+ sections.push({ expanded: capsStr, compact: capsStr, expandedW: capsVisW, compactW: capsVisW, empty: false });
34472
+ }
34473
+ }
34474
+ if (this._expose) {
34475
+ const statusEmoji = this._expose.status === "active" ? "\u{1F7E2}" : this._expose.status === "error" ? "\u{1F534}" : "\u{1F7E0}";
34476
+ const models = Array.from(this._expose.modelUsage.keys());
34477
+ const modelParams = models.map((mdl) => {
34478
+ const pm = mdl.match(/(\d+[bBmM])/);
34479
+ return pm ? pm[1] : mdl.split(":")[0]?.split("/").pop() ?? mdl;
34480
+ });
34481
+ const modelStr = modelParams.join(",");
34482
+ const reqStr = this._expose.totalRequests > 0 ? ` ${this._expose.totalRequests}req` : "";
34483
+ const connStr = this._expose.activeConnections > 0 ? ` ${this._expose.activeConnections}conn` : "";
34484
+ const exposeExpanded = statusEmoji + pastel2(183, (modelStr ? " " + modelStr : "") + reqStr + connStr);
34485
+ const exposeCompact = statusEmoji + (modelStr ? pastel2(183, " " + modelStr) : "");
34486
+ const expFullStr = (modelStr ? " " + modelStr : "") + reqStr + connStr;
34487
+ const expCompStr = modelStr ? " " + modelStr : "";
34488
+ sections.push({
34489
+ expanded: exposeExpanded,
34490
+ compact: exposeCompact,
34491
+ expandedW: 2 + expFullStr.length,
34492
+ // emoji(2) + text
34493
+ compactW: 2 + expCompStr.length,
34494
+ empty: false
34495
+ });
34496
+ }
34013
34497
  if (this._recording) {
34014
34498
  const dot = this._recBlink ? pastel2(210, "\u25CF") : " ";
34015
34499
  const countdown = this._countdown > 0 ? c2.dim(` ${this._countdown}s`) : "";
34016
- recordingLabel = pipe + dot + pastel2(210, " REC") + countdown;
34017
- }
34018
- const modelLabel = this._modelName ? pipe + pastel2(146, this._modelName) : "";
34019
- const capParts = [];
34020
- if (this._caps.vision)
34021
- capParts.push("\u{1F441}");
34022
- if (this._caps.toolUse)
34023
- capParts.push("\u{1F527}");
34024
- if (this._caps.thinking)
34025
- capParts.push("\u{1F9E0}");
34026
- const capsLabel = capParts.length > 0 ? pipe + pastel2(183, capParts.join(" ")) : "";
34027
- return ` ${tokInLabel}${pipe}${tokOutLabel}${pipe}${ctxLabel}${snrLabel}${emotionLabel}${speedLabel}${costLabel}${modelLabel}${capsLabel}${recordingLabel}`;
34500
+ const recStr = dot + pastel2(210, " REC") + countdown;
34501
+ const recW = 1 + 4 + (this._countdown > 0 ? 1 + `${this._countdown}s`.length : 0);
34502
+ sections.push({ expanded: recStr, compact: recStr, expandedW: recW, compactW: recW, empty: false });
34503
+ }
34504
+ const activeIndices = sections.map((s, i) => !s.empty ? i : -1).filter((i) => i >= 0);
34505
+ const isCompact = new Array(sections.length).fill(false);
34506
+ const calcTotalWidth = () => {
34507
+ let w = 1;
34508
+ for (let j = 0; j < activeIndices.length; j++) {
34509
+ const idx = activeIndices[j];
34510
+ const sec = sections[idx];
34511
+ if (j > 0)
34512
+ w += pipeW;
34513
+ w += isCompact[idx] ? sec.compactW : sec.expandedW;
34514
+ }
34515
+ return w;
34516
+ };
34517
+ let totalW = calcTotalWidth();
34518
+ for (let j = activeIndices.length - 1; j >= 0 && totalW > termWidth; j--) {
34519
+ const idx = activeIndices[j];
34520
+ if (!isCompact[idx] && sections[idx].compactW < sections[idx].expandedW) {
34521
+ isCompact[idx] = true;
34522
+ totalW = calcTotalWidth();
34523
+ }
34524
+ }
34525
+ for (let j = 0; j < activeIndices.length; j++) {
34526
+ const idx = activeIndices[j];
34527
+ if (isCompact[idx]) {
34528
+ const savings = sections[idx].expandedW - sections[idx].compactW;
34529
+ if (totalW + savings <= termWidth) {
34530
+ isCompact[idx] = false;
34531
+ totalW += savings;
34532
+ } else {
34533
+ break;
34534
+ }
34535
+ }
34536
+ }
34537
+ let result = " ";
34538
+ for (let j = 0; j < activeIndices.length; j++) {
34539
+ const idx = activeIndices[j];
34540
+ if (j > 0)
34541
+ result += pipe;
34542
+ result += isCompact[idx] ? sections[idx].compact : sections[idx].expanded;
34543
+ }
34544
+ return result;
34028
34545
  }
34029
34546
  // -------------------------------------------------------------------------
34030
34547
  // Private
@@ -35145,6 +35662,7 @@ async function startInteractive(config, repoPath) {
35145
35662
  });
35146
35663
  const voiceEngine = new VoiceEngine();
35147
35664
  let voiceSession = null;
35665
+ let exposeGateway = null;
35148
35666
  let adminSessionKey = null;
35149
35667
  const callSubAgents = /* @__PURE__ */ new Map();
35150
35668
  const streamRenderer = new StreamRenderer();
@@ -35305,6 +35823,7 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
35305
35823
  "/pause",
35306
35824
  "/stop",
35307
35825
  "/resume",
35826
+ "/expose",
35308
35827
  "/full-send-bless",
35309
35828
  "/bless",
35310
35829
  "/telegram",
@@ -35991,6 +36510,55 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
35991
36510
  getCallUrl() {
35992
36511
  return voiceSession?.tunnelUrl ?? null;
35993
36512
  },
36513
+ async exposeStart(kindOrUrl, authKey) {
36514
+ const knownKinds = ["ollama", "vllm", "llvm"];
36515
+ let kind;
36516
+ let targetUrl;
36517
+ if (knownKinds.includes(kindOrUrl)) {
36518
+ kind = kindOrUrl;
36519
+ } else {
36520
+ kind = "custom";
36521
+ targetUrl = kindOrUrl.includes("://") ? kindOrUrl : `http://${kindOrUrl}`;
36522
+ }
36523
+ exposeGateway = new ExposeGateway({ kind, targetUrl, authKey });
36524
+ exposeGateway.on("stats", (stats) => {
36525
+ statusBar.setExposeStatus({
36526
+ status: stats.status,
36527
+ totalRequests: stats.totalRequests,
36528
+ activeConnections: stats.activeConnections,
36529
+ modelUsage: stats.modelUsage
36530
+ });
36531
+ });
36532
+ try {
36533
+ const url = await exposeGateway.start();
36534
+ writeContent(() => {
36535
+ process.stdout.write("\n" + exposeGateway.formatConnectionInfo() + "\n\n");
36536
+ });
36537
+ return url;
36538
+ } catch (err) {
36539
+ exposeGateway = null;
36540
+ throw err;
36541
+ }
36542
+ },
36543
+ async exposeStop() {
36544
+ if (exposeGateway) {
36545
+ await exposeGateway.stop();
36546
+ statusBar.clearExposeStatus();
36547
+ exposeGateway = null;
36548
+ }
36549
+ },
36550
+ isExposeActive() {
36551
+ return exposeGateway?.isActive ?? false;
36552
+ },
36553
+ getExposeInfo() {
36554
+ if (!exposeGateway)
36555
+ return null;
36556
+ return {
36557
+ tunnelUrl: exposeGateway.tunnelUrl,
36558
+ authKey: exposeGateway.authKey,
36559
+ stats: exposeGateway.formatStats()
36560
+ };
36561
+ },
35994
36562
  async sendCallButton(chatId, url) {
35995
36563
  if (telegramBridge?.isActive) {
35996
36564
  await telegramBridge.sendCallButton(chatId, url);
@@ -36657,6 +37225,10 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
36657
37225
  showPrompt();
36658
37226
  }
36659
37227
  rl.on("close", () => {
37228
+ if (exposeGateway?.isActive) {
37229
+ exposeGateway.stop().catch(() => {
37230
+ });
37231
+ }
36660
37232
  statusBar.deactivate();
36661
37233
  const closeRows = process.stdout.rows ?? 24;
36662
37234
  process.stdout.write(`\x1B[${closeRows - 4};1H\x1B[J
@@ -36745,6 +37317,7 @@ var init_interactive = __esm({
36745
37317
  init_dist();
36746
37318
  init_listen();
36747
37319
  init_voice_session();
37320
+ init_expose();
36748
37321
  init_call_agent();
36749
37322
  init_config();
36750
37323
  init_updater();
@@ -37408,7 +37981,7 @@ var serve_exports = {};
37408
37981
  __export(serve_exports, {
37409
37982
  serveCommand: () => serveCommand
37410
37983
  });
37411
- import { spawn as spawn12 } from "node:child_process";
37984
+ import { spawn as spawn13 } from "node:child_process";
37412
37985
  async function serveCommand(opts, config) {
37413
37986
  const backendType = config.backendType;
37414
37987
  if (backendType === "ollama") {
@@ -37501,7 +38074,7 @@ async function serveVllm(opts, config) {
37501
38074
  }
37502
38075
  async function runVllmServer(args, verbose) {
37503
38076
  return new Promise((resolve28, reject) => {
37504
- const child = spawn12("python", args, {
38077
+ const child = spawn13("python", args, {
37505
38078
  stdio: verbose ? "inherit" : ["ignore", "pipe", "pipe"],
37506
38079
  env: { ...process.env }
37507
38080
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-agents-ai",
3
- "version": "0.66.0",
3
+ "version": "0.67.1",
4
4
  "description": "AI coding agent powered by open-source models (Ollama/vLLM) — interactive TUI with agentic tool-calling loop",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",