@blockrun/franklin 3.49.19 → 3.49.21
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/dist/agent/context.js +10 -22
- package/dist/agent/llm.js +1 -1
- package/dist/commands/doctor.js +1 -1
- package/dist/commands/panel.d.ts +6 -0
- package/dist/commands/panel.js +62 -19
- package/dist/commands/start.js +8 -17
- package/dist/config.d.ts +8 -0
- package/dist/config.js +26 -0
- package/dist/index.js +4 -1
- package/dist/panel/html.js +38 -8
- package/dist/panel/server.d.ts +21 -0
- package/dist/panel/server.js +56 -7
- package/dist/proxy/server.js +2 -2
- package/dist/ui/app.js +1 -1
- package/package.json +1 -1
- package/dist/proxy/sse-translator.d.ts +0 -29
- package/dist/proxy/sse-translator.js +0 -270
package/dist/agent/context.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { execSync } from 'node:child_process';
|
|
8
|
-
import { API_URLS,
|
|
8
|
+
import { API_URLS, CHAIN_LABELS, CHAINS } from '../config.js';
|
|
9
9
|
import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
|
|
10
10
|
import { Keypair } from '@solana/web3.js';
|
|
11
11
|
import bs58 from 'bs58';
|
|
@@ -204,19 +204,9 @@ After delivering results, if a better data source exists, add one line at the en
|
|
|
204
204
|
Do NOT check access before acting. Do NOT explain what you tried. Just deliver, then tip.`;
|
|
205
205
|
}
|
|
206
206
|
function getWalletKnowledgeSection() {
|
|
207
|
-
//
|
|
208
|
-
//
|
|
209
|
-
//
|
|
210
|
-
// to the canonical default when the file is missing (panel disabled or
|
|
211
|
-
// never started this session).
|
|
212
|
-
let panelUrl = 'http://localhost:3100';
|
|
213
|
-
try {
|
|
214
|
-
const persisted = fs.readFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), 'utf8').trim();
|
|
215
|
-
if (persisted.startsWith('http://') || persisted.startsWith('https://')) {
|
|
216
|
-
panelUrl = persisted;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
catch { /* fall through to default */ }
|
|
207
|
+
// The panel URL is deliberately not in this prompt: it carries the panel's
|
|
208
|
+
// access token, which must not reach a model provider or a transcript.
|
|
209
|
+
// `franklin panel --open wallet` reads it from the 0600 panel-url file.
|
|
220
210
|
return `# Wallet Storage (answer "where is my wallet" directly — no searching)
|
|
221
211
|
Franklin stores wallet keys in ~/.blockrun/. When the user asks about wallet location, answer from this map — do not grep or scan.
|
|
222
212
|
|
|
@@ -242,25 +232,23 @@ When the user asks about "my wallet" without qualifier, default to Base (it's th
|
|
|
242
232
|
|
|
243
233
|
When the user asks about depositing or funding USDC — in any language — do not describe the steps in chat. **Open the panel wallet page directly in their browser** using Bash, then confirm in chat what you opened and which chain is active.
|
|
244
234
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
${panelUrl}/#wallet
|
|
235
|
+
Bash command to open it (same on macOS, Linux and Windows; it finds the running panel's port and access link itself):
|
|
248
236
|
|
|
249
|
-
|
|
237
|
+
franklin panel --open wallet
|
|
250
238
|
|
|
251
|
-
|
|
239
|
+
If it reports that no panel is running, tell the user to run \`franklin panel\` and open the Wallet tab from there.
|
|
252
240
|
|
|
253
241
|
That page is where the deposit address, QR code, live balance, chain switcher, and back-up controls all live. The user lands on it instead of you reciting steps.
|
|
254
242
|
|
|
255
|
-
After running
|
|
256
|
-
- Tell the user one line: "Opened the wallet page
|
|
243
|
+
After running it:
|
|
244
|
+
- Tell the user one line: "Opened the wallet page in your browser. Active chain: <base|solana>."
|
|
257
245
|
- Read the active chain from ~/.blockrun/payment-chain so they know which network to send USDC on.
|
|
258
246
|
- Mention USDC is the only accepted token; ETH/SOL on their own won't settle x402 calls.
|
|
259
247
|
|
|
260
248
|
Hard rules:
|
|
261
249
|
- Do NOT print the private key in chat. The panel reveals it behind a click.
|
|
262
250
|
- Do NOT invent a \`franklin deposit\` CLI flow — there isn't one; the panel IS the funding surface.
|
|
263
|
-
- Do NOT hand-craft a
|
|
251
|
+
- Do NOT hand-craft a localhost panel URL or read ~/.blockrun/panel-url: the panel needs its access token, and \`franklin panel --open wallet\` supplies it without showing it to you.
|
|
264
252
|
- If \`open\` fails (e.g. no GUI on a remote box), fall back to giving them the URL as plain text and tell them to paste it into a browser.`;
|
|
265
253
|
}
|
|
266
254
|
function getBlockRunApiSection() {
|
package/dist/agent/llm.js
CHANGED
|
@@ -1201,7 +1201,7 @@ export class ModelClient {
|
|
|
1201
1201
|
catch (err) {
|
|
1202
1202
|
const msg = err.message || '';
|
|
1203
1203
|
if (msg.includes('insufficient') || msg.includes('balance')) {
|
|
1204
|
-
console.error(`[franklin] Insufficient USDC balance.
|
|
1204
|
+
console.error(`[franklin] Insufficient USDC balance. Run 'franklin panel --open wallet' to deposit (or 'franklin balance').`);
|
|
1205
1205
|
}
|
|
1206
1206
|
else if (this.debug) {
|
|
1207
1207
|
console.error('[franklin] Payment error:', msg);
|
package/dist/commands/doctor.js
CHANGED
|
@@ -169,7 +169,7 @@ async function runChecks() {
|
|
|
169
169
|
? `$${walletBalance.toFixed(2)} — low; paid calls likely to fail mid-stream`
|
|
170
170
|
: `$${walletBalance.toFixed(2)}`;
|
|
171
171
|
const balanceRemedy = walletBalance < LOW_BALANCE_THRESHOLD
|
|
172
|
-
? `Send USDC on ${chain} to ${walletAddress} (or open
|
|
172
|
+
? `Send USDC on ${chain} to ${walletAddress} (or run: franklin panel --open wallet)`
|
|
173
173
|
: undefined;
|
|
174
174
|
out.push({
|
|
175
175
|
name: 'USDC balance',
|
package/dist/commands/panel.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* franklin panel — launch the local web dashboard.
|
|
3
3
|
*/
|
|
4
|
+
/**
|
|
5
|
+
* Open a URL in the default browser without going through a shell: the URL
|
|
6
|
+
* carries the panel token and `?`/`#`, which a shell would glob or cut.
|
|
7
|
+
*/
|
|
8
|
+
export declare function openInBrowser(url: string): void;
|
|
4
9
|
export declare function panelCommand(options: {
|
|
5
10
|
port?: string;
|
|
11
|
+
open?: string | boolean;
|
|
6
12
|
}): Promise<void>;
|
package/dist/commands/panel.js
CHANGED
|
@@ -3,10 +3,65 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import chalk from 'chalk';
|
|
5
5
|
import fs from 'node:fs';
|
|
6
|
-
import
|
|
7
|
-
import { createPanelServer } from '../panel/server.js';
|
|
8
|
-
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { createPanelServer, writePanelUrlFile, PANEL_URL_FILE } from '../panel/server.js';
|
|
8
|
+
/**
|
|
9
|
+
* Open a URL in the default browser without going through a shell: the URL
|
|
10
|
+
* carries the panel token and `?`/`#`, which a shell would glob or cut.
|
|
11
|
+
*/
|
|
12
|
+
export function openInBrowser(url) {
|
|
13
|
+
const onError = () => { };
|
|
14
|
+
if (process.platform === 'darwin')
|
|
15
|
+
execFile('open', [url], onError);
|
|
16
|
+
else if (process.platform === 'win32') {
|
|
17
|
+
// `start` treats its first quoted argument as a window title.
|
|
18
|
+
execFile('cmd', ['/c', 'start', '""', `"${url}"`], { windowsVerbatimArguments: true }, onError);
|
|
19
|
+
}
|
|
20
|
+
else
|
|
21
|
+
execFile('xdg-open', [url], onError);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* `franklin panel --open [section]`: open the panel that is already running
|
|
25
|
+
* (started by `franklin` or `franklin panel`) at an optional #section. The
|
|
26
|
+
* agent uses this for the wallet page, so the token never enters a prompt
|
|
27
|
+
* or a transcript: nothing here prints the token-bearing URL.
|
|
28
|
+
*/
|
|
29
|
+
async function openRunningPanel(section) {
|
|
30
|
+
if (section && !/^[a-z0-9-]+$/i.test(section)) {
|
|
31
|
+
console.error(chalk.red(` Unknown panel section: ${section}`));
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
let launch = '';
|
|
35
|
+
try {
|
|
36
|
+
launch = fs.readFileSync(PANEL_URL_FILE, 'utf8').trim();
|
|
37
|
+
}
|
|
38
|
+
catch { /* none */ }
|
|
39
|
+
let alive = false;
|
|
40
|
+
// 127.0.0.1 only: a `localhost` link (written by 3.49.20) can resolve to a
|
|
41
|
+
// squatter on [::1]:<port>, so treat it as stale and make the user restart.
|
|
42
|
+
if (/^http:\/\/127\.0\.0\.1:\d+\/\?token=[0-9a-f]{64}$/.test(launch)) {
|
|
43
|
+
try {
|
|
44
|
+
const res = await fetch(launch, { signal: AbortSignal.timeout(1500) });
|
|
45
|
+
alive = res.status === 200; // 401 means a different panel process owns the port now
|
|
46
|
+
await res.body?.cancel();
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
alive = false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (!alive) {
|
|
53
|
+
console.error(chalk.yellow(' No running Franklin panel found. Start one with: franklin panel'));
|
|
54
|
+
process.exit(1);
|
|
55
|
+
}
|
|
56
|
+
openInBrowser(section ? `${launch}#${section}` : launch);
|
|
57
|
+
const port = new URL(launch).port;
|
|
58
|
+
console.log(` Opened the Franklin panel${section ? ` (${section})` : ''} on 127.0.0.1:${port}.`);
|
|
59
|
+
}
|
|
9
60
|
export async function panelCommand(options) {
|
|
61
|
+
if (options.open !== undefined) {
|
|
62
|
+
await openRunningPanel(typeof options.open === 'string' ? options.open : '');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
10
65
|
const requestedPort = parseInt(options.port || '3100', 10);
|
|
11
66
|
// Handle port-in-use by trying up to 20 subsequent ports silently.
|
|
12
67
|
// Only log when we finally bind (or fail completely) — no per-attempt spam.
|
|
@@ -28,17 +83,9 @@ export async function panelCommand(options) {
|
|
|
28
83
|
// Bind to loopback only — the panel exposes wallet secrets on /api/wallet/secret
|
|
29
84
|
// and a write-capable /api/wallet/import. Never expose these on a LAN.
|
|
30
85
|
server.listen(port, '127.0.0.1', () => {
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
|
|
34
|
-
// off the same file. Without this, a user who disables panel
|
|
35
|
-
// autostart and runs `franklin panel` separately would still get
|
|
36
|
-
// the hardcoded 3100 default in the agent prompt.
|
|
37
|
-
try {
|
|
38
|
-
fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
|
|
39
|
-
fs.writeFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), url, 'utf8');
|
|
40
|
-
}
|
|
41
|
-
catch { /* best-effort */ }
|
|
86
|
+
// Persist the launch URL (0600) so `franklin panel --open wallet`,
|
|
87
|
+
// which the agent runs for funding, finds this panel's port and token.
|
|
88
|
+
const url = writePanelUrlFile(port);
|
|
42
89
|
console.log('');
|
|
43
90
|
console.log(chalk.bold(' Franklin Panel'));
|
|
44
91
|
console.log(chalk.dim(` ${url}`) +
|
|
@@ -46,11 +93,7 @@ export async function panelCommand(options) {
|
|
|
46
93
|
console.log('');
|
|
47
94
|
console.log(chalk.dim(' Press Ctrl+C to stop.'));
|
|
48
95
|
console.log('');
|
|
49
|
-
|
|
50
|
-
const open = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
|
|
51
|
-
import('node:child_process').then(({ exec }) => {
|
|
52
|
-
exec(`${open} ${url}`);
|
|
53
|
-
}).catch(() => { });
|
|
96
|
+
openInBrowser(url);
|
|
54
97
|
});
|
|
55
98
|
// Graceful shutdown
|
|
56
99
|
const shutdown = () => {
|
package/dist/commands/start.js
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { refreshModelCatalog } from '../model-catalog.js';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
3
|
import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
|
|
6
|
-
import {
|
|
4
|
+
import { loadChain } from '../config.js';
|
|
7
5
|
import { gatewayBase } from '../payments/auth-mode.js';
|
|
8
6
|
import { retryFetchBalance } from './balance-retry.js';
|
|
9
7
|
import { flushStats, loadStats, getLiveSpendUsd } from '../stats/tracker.js';
|
|
@@ -238,7 +236,7 @@ export async function startCommand(options) {
|
|
|
238
236
|
// Full wallet address is shown so the user can copy-paste it to fund the wallet.
|
|
239
237
|
console.log(chalk.dim(' Wallet: ') + (walletAddress || chalk.yellow('not set')));
|
|
240
238
|
console.log(chalk.dim(' Dir: ') + workDir);
|
|
241
|
-
console.log(chalk.dim(' Dashboard: ') + (panelUrl ? chalk.cyan(panelUrl) : chalk.cyan('franklin panel')
|
|
239
|
+
console.log(chalk.dim(' Dashboard: ') + (panelUrl ? chalk.cyan(panelUrl) : chalk.cyan('franklin panel')));
|
|
242
240
|
console.log(chalk.dim(' Help: ') + chalk.cyan('/help'));
|
|
243
241
|
console.log('');
|
|
244
242
|
// Balance fetcher — used at startup and after each turn.
|
|
@@ -737,7 +735,7 @@ async function runWithBasicUI(agentConfig, model, workDir, initialInput) {
|
|
|
737
735
|
async function startPanelBackground(startPort) {
|
|
738
736
|
const MAX_ATTEMPTS = 20;
|
|
739
737
|
try {
|
|
740
|
-
const { createPanelServer } = await import('../panel/server.js');
|
|
738
|
+
const { createPanelServer, writePanelUrlFile } = await import('../panel/server.js');
|
|
741
739
|
return await new Promise((resolve) => {
|
|
742
740
|
const tryListen = (port, attempt) => {
|
|
743
741
|
const server = createPanelServer(port);
|
|
@@ -750,18 +748,11 @@ async function startPanelBackground(startPort) {
|
|
|
750
748
|
});
|
|
751
749
|
server.listen(port, '127.0.0.1', () => {
|
|
752
750
|
server.unref?.();
|
|
753
|
-
|
|
754
|
-
//
|
|
755
|
-
//
|
|
756
|
-
//
|
|
757
|
-
|
|
758
|
-
// since the user just sees a dead link.
|
|
759
|
-
try {
|
|
760
|
-
fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
|
|
761
|
-
fs.writeFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), url, 'utf8');
|
|
762
|
-
}
|
|
763
|
-
catch { /* best-effort */ }
|
|
764
|
-
resolve(url);
|
|
751
|
+
// Persist the launch URL (0600, token included) so the agent's
|
|
752
|
+
// `franklin panel --open wallet` finds the bound port; the panel
|
|
753
|
+
// auto-increments past EADDRINUSE. A stale file from a crashed run
|
|
754
|
+
// is harmless: --open probes it and reports no running panel.
|
|
755
|
+
resolve(writePanelUrlFile(port));
|
|
765
756
|
});
|
|
766
757
|
};
|
|
767
758
|
tryListen(startPort, 0);
|
package/dist/config.d.ts
CHANGED
|
@@ -15,6 +15,14 @@ export declare function isEvmChain(chain: Chain): boolean;
|
|
|
15
15
|
export declare const CHAIN_LABELS: Record<Chain, string>;
|
|
16
16
|
export declare const BLOCKRUN_DIR: string;
|
|
17
17
|
export declare const CHAIN_FILE: string;
|
|
18
|
+
/**
|
|
19
|
+
* ~/.blockrun holds session transcripts, the LLM audit log, cost and trade
|
|
20
|
+
* ledgers, and wallet keys. Created under the default umask it is 755 with
|
|
21
|
+
* 644 files, so any other account on the machine can read all of it.
|
|
22
|
+
* Owner-only, like ~/.ssh. Runs once per CLI start; never touches a
|
|
23
|
+
* directory owned by someone else.
|
|
24
|
+
*/
|
|
25
|
+
export declare function hardenBlockrunDir(): void;
|
|
18
26
|
export declare const API_URLS: Record<Chain, string>;
|
|
19
27
|
export declare const DEFAULT_PROXY_PORT = 8402;
|
|
20
28
|
export declare const MARKET_URL: string;
|
package/dist/config.js
CHANGED
|
@@ -34,6 +34,32 @@ export const CHAIN_LABELS = {
|
|
|
34
34
|
};
|
|
35
35
|
export const BLOCKRUN_DIR = path.join(os.homedir(), '.blockrun');
|
|
36
36
|
export const CHAIN_FILE = path.join(BLOCKRUN_DIR, 'payment-chain');
|
|
37
|
+
/**
|
|
38
|
+
* ~/.blockrun holds session transcripts, the LLM audit log, cost and trade
|
|
39
|
+
* ledgers, and wallet keys. Created under the default umask it is 755 with
|
|
40
|
+
* 644 files, so any other account on the machine can read all of it.
|
|
41
|
+
* Owner-only, like ~/.ssh. Runs once per CLI start; never touches a
|
|
42
|
+
* directory owned by someone else.
|
|
43
|
+
*/
|
|
44
|
+
export function hardenBlockrunDir() {
|
|
45
|
+
if (process.platform === 'win32')
|
|
46
|
+
return;
|
|
47
|
+
try {
|
|
48
|
+
const st = fs.statSync(BLOCKRUN_DIR);
|
|
49
|
+
if (typeof process.getuid === 'function' && st.uid !== process.getuid())
|
|
50
|
+
return;
|
|
51
|
+
if ((st.mode & 0o077) !== 0)
|
|
52
|
+
fs.chmodSync(BLOCKRUN_DIR, 0o700);
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
if (err.code === 'ENOENT') {
|
|
56
|
+
try {
|
|
57
|
+
fs.mkdirSync(BLOCKRUN_DIR, { recursive: true, mode: 0o700 });
|
|
58
|
+
}
|
|
59
|
+
catch { /* best-effort */ }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
37
63
|
export const API_URLS = {
|
|
38
64
|
base: 'https://blockrun.ai/api',
|
|
39
65
|
solana: 'https://sol.blockrun.ai/api',
|
package/dist/index.js
CHANGED
|
@@ -31,7 +31,9 @@ import { buildContentCommand } from './commands/content.js';
|
|
|
31
31
|
import { predictCommand } from './commands/predict.js';
|
|
32
32
|
import { loginCommand, logoutCommand } from './commands/login.js';
|
|
33
33
|
import { useWalletMode } from './payments/auth-mode.js';
|
|
34
|
-
import { VERSION as version } from './config.js';
|
|
34
|
+
import { VERSION as version, hardenBlockrunDir } from './config.js';
|
|
35
|
+
// Before any command reads or writes ~/.blockrun (GHSA-jx74-262x-94p3 follow-up).
|
|
36
|
+
hardenBlockrunDir();
|
|
35
37
|
// `--wallet` is process-global rather than a per-command option: it has to take
|
|
36
38
|
// effect before anything resolves a pay mode, and it belongs on `balance`,
|
|
37
39
|
// `doctor` and `models` too, not just `start`. Applying it straight from argv
|
|
@@ -120,6 +122,7 @@ program
|
|
|
120
122
|
.command('panel')
|
|
121
123
|
.description('Open the Franklin dashboard (localhost:3100)')
|
|
122
124
|
.option('-p, --port <port>', 'Dashboard port', '3100')
|
|
125
|
+
.option('--open [section]', 'Open the already-running panel in the browser (e.g. --open wallet)')
|
|
123
126
|
.action(async (options) => {
|
|
124
127
|
const { panelCommand } = await import('./commands/panel.js');
|
|
125
128
|
await panelCommand(options);
|
package/dist/panel/html.js
CHANGED
|
@@ -917,8 +917,6 @@ a:hover { text-decoration:underline; }
|
|
|
917
917
|
// refuses wallet, spend, and state-changing routes without it.
|
|
918
918
|
(() => {
|
|
919
919
|
const PANEL_TOKEN = ${JSON.stringify(panelToken)};
|
|
920
|
-
// EventSource cannot set headers; /api/events reads it from ?token=.
|
|
921
|
-
window.__FRANKLIN_PANEL_TOKEN = PANEL_TOKEN;
|
|
922
920
|
const nativeFetch = window.fetch.bind(window);
|
|
923
921
|
window.fetch = (input, init = {}) => {
|
|
924
922
|
const headers = new Headers(init.headers || {});
|
|
@@ -1427,14 +1425,46 @@ document.getElementById('wallet-import-btn').addEventListener('click', async ()
|
|
|
1427
1425
|
}
|
|
1428
1426
|
});
|
|
1429
1427
|
|
|
1430
|
-
|
|
1428
|
+
// Live updates read the SSE stream through fetch, not EventSource:
|
|
1429
|
+
// EventSource cannot send the panel token header, and a token in the URL
|
|
1430
|
+
// would land in browser history. Reconnects every 3s, as EventSource does.
|
|
1431
1431
|
const dot = document.getElementById('dot');
|
|
1432
1432
|
const statusEl = document.getElementById('status');
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1433
|
+
function setLive(on) {
|
|
1434
|
+
dot.className = on ? 'dot on' : 'dot off';
|
|
1435
|
+
statusEl.textContent = on ? 'live' : 'offline';
|
|
1436
|
+
}
|
|
1437
|
+
async function streamEvents() {
|
|
1438
|
+
for (;;) {
|
|
1439
|
+
try {
|
|
1440
|
+
const res = await fetch('/api/events', { cache: 'no-store' });
|
|
1441
|
+
if (!res.ok || !res.body) throw new Error('HTTP ' + res.status);
|
|
1442
|
+
setLive(true);
|
|
1443
|
+
const reader = res.body.getReader();
|
|
1444
|
+
const decoder = new TextDecoder();
|
|
1445
|
+
let buf = '';
|
|
1446
|
+
for (;;) {
|
|
1447
|
+
const { value, done } = await reader.read();
|
|
1448
|
+
if (done) break;
|
|
1449
|
+
buf += decoder.decode(value, { stream: true });
|
|
1450
|
+
let i;
|
|
1451
|
+
while ((i = buf.indexOf('\\n\\n')) >= 0) {
|
|
1452
|
+
const frame = buf.slice(0, i);
|
|
1453
|
+
buf = buf.slice(i + 2);
|
|
1454
|
+
const data = frame.split('\\n')
|
|
1455
|
+
.filter((l) => l.startsWith('data:'))
|
|
1456
|
+
.map((l) => l.slice(5).trimStart())
|
|
1457
|
+
.join('\\n');
|
|
1458
|
+
if (!data) continue;
|
|
1459
|
+
try { if (JSON.parse(data).type === 'stats.updated') loadOverview(); } catch {}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
} catch { /* fall through to reconnect */ }
|
|
1463
|
+
setLive(false);
|
|
1464
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
streamEvents();
|
|
1438
1468
|
|
|
1439
1469
|
async function loadAudit() {
|
|
1440
1470
|
const list = document.getElementById('audit-list');
|
package/dist/panel/server.d.ts
CHANGED
|
@@ -4,4 +4,25 @@
|
|
|
4
4
|
* Zero external dependencies — uses node:http only.
|
|
5
5
|
*/
|
|
6
6
|
import http from 'node:http';
|
|
7
|
+
/**
|
|
8
|
+
* The page itself is gated on the token too, passed once as `/?token=`.
|
|
9
|
+
* Without that, any local client (another OS user, a process reaching the
|
|
10
|
+
* port through an ssh -L tunnel) could GET `/`, read the token out of the
|
|
11
|
+
* HTML, and call /api/wallet/secret. Only someone who can see the terminal
|
|
12
|
+
* that started the panel, or read the 0600 panel-url file, has the link.
|
|
13
|
+
*
|
|
14
|
+
* The host is the literal 127.0.0.1 the server binds, never `localhost`.
|
|
15
|
+
* Browsers and Node try ::1 first for `localhost`, and another local account
|
|
16
|
+
* can listen on [::1]:<port> next to our 127.0.0.1:<port> without a bind
|
|
17
|
+
* conflict, so a `localhost` link would hand that listener the token.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getPanelLaunchUrl(port: number): string;
|
|
20
|
+
export declare const PANEL_URL_FILE: string;
|
|
21
|
+
/**
|
|
22
|
+
* Persist the launch URL (token included) for `franklin panel --open`.
|
|
23
|
+
* Owner-only: the file is the key to the panel. writeFileSync's mode only
|
|
24
|
+
* applies on create, so chmod covers a file left by an older release.
|
|
25
|
+
* Returns the launch URL.
|
|
26
|
+
*/
|
|
27
|
+
export declare function writePanelUrlFile(port: number): string;
|
|
7
28
|
export declare function createPanelServer(port: number): http.Server;
|
package/dist/panel/server.js
CHANGED
|
@@ -104,6 +104,46 @@ function tokenMatches(got) {
|
|
|
104
104
|
function hasPanelToken(req) {
|
|
105
105
|
return tokenMatches(req.headers[PANEL_TOKEN_HEADER]);
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* The page itself is gated on the token too, passed once as `/?token=`.
|
|
109
|
+
* Without that, any local client (another OS user, a process reaching the
|
|
110
|
+
* port through an ssh -L tunnel) could GET `/`, read the token out of the
|
|
111
|
+
* HTML, and call /api/wallet/secret. Only someone who can see the terminal
|
|
112
|
+
* that started the panel, or read the 0600 panel-url file, has the link.
|
|
113
|
+
*
|
|
114
|
+
* The host is the literal 127.0.0.1 the server binds, never `localhost`.
|
|
115
|
+
* Browsers and Node try ::1 first for `localhost`, and another local account
|
|
116
|
+
* can listen on [::1]:<port> next to our 127.0.0.1:<port> without a bind
|
|
117
|
+
* conflict, so a `localhost` link would hand that listener the token.
|
|
118
|
+
*/
|
|
119
|
+
export function getPanelLaunchUrl(port) {
|
|
120
|
+
return `http://127.0.0.1:${port}/?token=${PANEL_TOKEN}`;
|
|
121
|
+
}
|
|
122
|
+
export const PANEL_URL_FILE = path.join(BLOCKRUN_DIR, 'panel-url');
|
|
123
|
+
/**
|
|
124
|
+
* Persist the launch URL (token included) for `franklin panel --open`.
|
|
125
|
+
* Owner-only: the file is the key to the panel. writeFileSync's mode only
|
|
126
|
+
* applies on create, so chmod covers a file left by an older release.
|
|
127
|
+
* Returns the launch URL.
|
|
128
|
+
*/
|
|
129
|
+
export function writePanelUrlFile(port) {
|
|
130
|
+
const launch = getPanelLaunchUrl(port);
|
|
131
|
+
try {
|
|
132
|
+
fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
|
|
133
|
+
fs.writeFileSync(PANEL_URL_FILE, launch, { encoding: 'utf8', mode: 0o600 });
|
|
134
|
+
fs.chmodSync(PANEL_URL_FILE, 0o600);
|
|
135
|
+
}
|
|
136
|
+
catch { /* best-effort: the terminal still shows the link */ }
|
|
137
|
+
return launch;
|
|
138
|
+
}
|
|
139
|
+
const LOCKED_PAGE = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Franklin Panel</title>
|
|
140
|
+
<meta name="referrer" content="no-referrer"></head>
|
|
141
|
+
<body style="font-family:system-ui,sans-serif;max-width:34rem;margin:4rem auto;line-height:1.5">
|
|
142
|
+
<h1>Franklin Panel</h1>
|
|
143
|
+
<p>This link is missing its access token.</p>
|
|
144
|
+
<p>Open the Dashboard link printed in the terminal where Franklin is running,
|
|
145
|
+
or run <code>franklin panel --open</code>.</p>
|
|
146
|
+
</body></html>`;
|
|
107
147
|
function isLocalPanelRequest(req) {
|
|
108
148
|
return isLoopback(req) && isTrustedPanelOrigin(req) && hasPanelToken(req);
|
|
109
149
|
}
|
|
@@ -173,10 +213,9 @@ export function createPanelServer(port) {
|
|
|
173
213
|
// Loopback + local Host does not tell OS users apart: on a shared machine
|
|
174
214
|
// another account, or anyone reaching the port through an ssh -L tunnel,
|
|
175
215
|
// passes both and could read transcripts and the audit log
|
|
176
|
-
// (GHSA-jx74-262x-94p3).
|
|
177
|
-
//
|
|
178
|
-
if (p.startsWith('/api/') && !hasPanelToken(req)
|
|
179
|
-
&& !(p === '/api/events' && tokenMatches(url.searchParams.get('token')))) {
|
|
216
|
+
// (GHSA-jx74-262x-94p3). The page reads /api/events through fetch so it
|
|
217
|
+
// can send the header too; no route takes the token in a query string.
|
|
218
|
+
if (p.startsWith('/api/') && !hasPanelToken(req)) {
|
|
180
219
|
json(res, { error: 'forbidden' }, 403);
|
|
181
220
|
return;
|
|
182
221
|
}
|
|
@@ -188,12 +227,15 @@ export function createPanelServer(port) {
|
|
|
188
227
|
}
|
|
189
228
|
// ─── HTML ──
|
|
190
229
|
if (p === '/') {
|
|
191
|
-
|
|
230
|
+
const ok = tokenMatches(url.searchParams.get('token'));
|
|
231
|
+
res.writeHead(ok ? 200 : 401, {
|
|
192
232
|
'Content-Type': 'text/html; charset=utf-8',
|
|
193
233
|
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
|
194
234
|
'Pragma': 'no-cache',
|
|
235
|
+
// The URL carries the token; never send it on as a Referer.
|
|
236
|
+
'Referrer-Policy': 'no-referrer',
|
|
195
237
|
});
|
|
196
|
-
res.end(html);
|
|
238
|
+
res.end(ok ? html : LOCKED_PAGE);
|
|
197
239
|
return;
|
|
198
240
|
}
|
|
199
241
|
// ─── Static assets ──
|
|
@@ -332,7 +374,14 @@ export function createPanelServer(port) {
|
|
|
332
374
|
return;
|
|
333
375
|
}
|
|
334
376
|
if (p.startsWith('/api/sessions/')) {
|
|
335
|
-
|
|
377
|
+
let id;
|
|
378
|
+
try {
|
|
379
|
+
id = decodeURIComponent(p.slice('/api/sessions/'.length));
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
json(res, { error: 'invalid session id' }, 400); // malformed %-escape
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
336
385
|
const history = loadSessionHistory(id);
|
|
337
386
|
json(res, history);
|
|
338
387
|
return;
|
package/dist/proxy/server.js
CHANGED
|
@@ -815,7 +815,7 @@ function sleep(ms) {
|
|
|
815
815
|
async function handleBasePayment(response, url, method, headers, body, privateKey, fromAddress, timeoutMs = getProxyRequestTimeoutMs(), model = 'unknown') {
|
|
816
816
|
const paymentHeader = await extractPaymentHeader(response);
|
|
817
817
|
if (!paymentHeader) {
|
|
818
|
-
throw new Error('402 Payment Required — wallet may need funding.
|
|
818
|
+
throw new Error('402 Payment Required — wallet may need funding. Run: franklin panel --open wallet to deposit USDC (or: franklin balance)');
|
|
819
819
|
}
|
|
820
820
|
const paymentRequired = parsePaymentRequired(paymentHeader);
|
|
821
821
|
const details = extractPaymentDetails(paymentRequired);
|
|
@@ -852,7 +852,7 @@ async function handleBasePayment(response, url, method, headers, body, privateKe
|
|
|
852
852
|
async function handleSolanaPayment(response, url, method, headers, body, privateKey, fromAddress, timeoutMs = getProxyRequestTimeoutMs(), model = 'unknown') {
|
|
853
853
|
const paymentHeader = await extractPaymentHeader(response);
|
|
854
854
|
if (!paymentHeader) {
|
|
855
|
-
throw new Error('402 Payment Required — wallet may need funding.
|
|
855
|
+
throw new Error('402 Payment Required — wallet may need funding. Run: franklin panel --open wallet to deposit USDC (or: franklin balance)');
|
|
856
856
|
}
|
|
857
857
|
const paymentRequired = parsePaymentRequired(paymentHeader);
|
|
858
858
|
const details = extractPaymentDetails(paymentRequired, SOLANA_NETWORK);
|
package/dist/ui/app.js
CHANGED
|
@@ -653,7 +653,7 @@ function InputBox({ input, setInput, onSubmit, model, balance, chain, walletTail
|
|
|
653
653
|
const m = balance.match(/\$([\d.]+)/);
|
|
654
654
|
const num = m ? parseFloat(m[1]) : null;
|
|
655
655
|
if (num !== null && num < 0.50) {
|
|
656
|
-
return _jsxs(_Fragment, { children: [_jsx(Text, { color: "red", bold: true, children: balance }), _jsx(Text, { color: "red", children: " \u26A0 low \u2014 deposit
|
|
656
|
+
return _jsxs(_Fragment, { children: [_jsx(Text, { color: "red", bold: true, children: balance }), _jsx(Text, { color: "red", children: " \u26A0 low \u2014 deposit: franklin panel --open wallet, or /model free" })] });
|
|
657
657
|
}
|
|
658
658
|
if (num !== null && num < 1.00) {
|
|
659
659
|
return _jsx(Text, { color: "yellow", children: balance });
|
package/package.json
CHANGED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SSE Event Translator: OpenAI → Anthropic Messages API format
|
|
3
|
-
*
|
|
4
|
-
* Handles three critical gaps in the streaming pipeline:
|
|
5
|
-
* 1. Tool calls: choice.delta.tool_calls → content_block_start/content_block_delta (tool_use)
|
|
6
|
-
* 2. Reasoning: reasoning_content → content_block_start/content_block_delta (thinking)
|
|
7
|
-
* 3. Ensures proper content_block_stop and message_stop events
|
|
8
|
-
*/
|
|
9
|
-
export declare class SSETranslator {
|
|
10
|
-
private state;
|
|
11
|
-
private buffer;
|
|
12
|
-
constructor(model?: string);
|
|
13
|
-
/**
|
|
14
|
-
* Detect whether an SSE chunk is in OpenAI format.
|
|
15
|
-
* Returns true if it contains OpenAI-style `choices[].delta` structure.
|
|
16
|
-
*/
|
|
17
|
-
static isOpenAIFormat(chunk: string): boolean;
|
|
18
|
-
/**
|
|
19
|
-
* Process a raw SSE text chunk and return translated Anthropic-format SSE events.
|
|
20
|
-
* Returns null if no translation needed (already Anthropic format or not parseable).
|
|
21
|
-
*/
|
|
22
|
-
processChunk(rawChunk: string): string | null;
|
|
23
|
-
private parseSSEEvents;
|
|
24
|
-
private formatSSE;
|
|
25
|
-
private closeThinkingBlock;
|
|
26
|
-
private closeTextBlock;
|
|
27
|
-
private closeToolCalls;
|
|
28
|
-
private closeActiveBlocks;
|
|
29
|
-
}
|
|
@@ -1,270 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SSE Event Translator: OpenAI → Anthropic Messages API format
|
|
3
|
-
*
|
|
4
|
-
* Handles three critical gaps in the streaming pipeline:
|
|
5
|
-
* 1. Tool calls: choice.delta.tool_calls → content_block_start/content_block_delta (tool_use)
|
|
6
|
-
* 2. Reasoning: reasoning_content → content_block_start/content_block_delta (thinking)
|
|
7
|
-
* 3. Ensures proper content_block_stop and message_stop events
|
|
8
|
-
*/
|
|
9
|
-
// ─── SSE Translator ─────────────────────────────────────────────────────────
|
|
10
|
-
export class SSETranslator {
|
|
11
|
-
state;
|
|
12
|
-
buffer = '';
|
|
13
|
-
constructor(model = 'unknown') {
|
|
14
|
-
this.state = {
|
|
15
|
-
messageId: `msg_franklin_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
|
16
|
-
model,
|
|
17
|
-
blockIndex: 0,
|
|
18
|
-
activeToolCalls: new Map(),
|
|
19
|
-
thinkingBlockActive: false,
|
|
20
|
-
textBlockActive: false,
|
|
21
|
-
messageStarted: false,
|
|
22
|
-
inputTokens: 0,
|
|
23
|
-
outputTokens: 0,
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Detect whether an SSE chunk is in OpenAI format.
|
|
28
|
-
* Returns true if it contains OpenAI-style `choices[].delta` structure.
|
|
29
|
-
*/
|
|
30
|
-
static isOpenAIFormat(chunk) {
|
|
31
|
-
return (chunk.includes('"choices"') &&
|
|
32
|
-
chunk.includes('"delta"') &&
|
|
33
|
-
!chunk.includes('"content_block_'));
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Process a raw SSE text chunk and return translated Anthropic-format SSE events.
|
|
37
|
-
* Returns null if no translation needed (already Anthropic format or not parseable).
|
|
38
|
-
*/
|
|
39
|
-
processChunk(rawChunk) {
|
|
40
|
-
this.buffer += rawChunk;
|
|
41
|
-
const events = this.parseSSEEvents();
|
|
42
|
-
if (events.length === 0)
|
|
43
|
-
return null;
|
|
44
|
-
const translated = [];
|
|
45
|
-
for (const event of events) {
|
|
46
|
-
if (event.data === '[DONE]') {
|
|
47
|
-
translated.push(...this.closeActiveBlocks());
|
|
48
|
-
translated.push(this.formatSSE('message_delta', {
|
|
49
|
-
type: 'message_delta',
|
|
50
|
-
delta: { stop_reason: 'end_turn', stop_sequence: null },
|
|
51
|
-
usage: { output_tokens: this.state.outputTokens },
|
|
52
|
-
}));
|
|
53
|
-
translated.push(this.formatSSE('message_stop', { type: 'message_stop' }));
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
let parsed;
|
|
57
|
-
try {
|
|
58
|
-
parsed = JSON.parse(event.data);
|
|
59
|
-
}
|
|
60
|
-
catch {
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
// Skip if not OpenAI format
|
|
64
|
-
const choices = parsed.choices;
|
|
65
|
-
if (!choices || choices.length === 0) {
|
|
66
|
-
// Could be a usage-only event
|
|
67
|
-
const usage = parsed.usage;
|
|
68
|
-
if (usage) {
|
|
69
|
-
this.state.inputTokens = usage.prompt_tokens ?? 0;
|
|
70
|
-
this.state.outputTokens = usage.completion_tokens ?? 0;
|
|
71
|
-
}
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
// Emit message_start on first chunk
|
|
75
|
-
if (!this.state.messageStarted) {
|
|
76
|
-
this.state.messageStarted = true;
|
|
77
|
-
if (parsed.model)
|
|
78
|
-
this.state.model = parsed.model;
|
|
79
|
-
translated.push(this.formatSSE('message_start', {
|
|
80
|
-
type: 'message_start',
|
|
81
|
-
message: {
|
|
82
|
-
id: this.state.messageId,
|
|
83
|
-
type: 'message',
|
|
84
|
-
role: 'assistant',
|
|
85
|
-
model: this.state.model,
|
|
86
|
-
content: [],
|
|
87
|
-
stop_reason: null,
|
|
88
|
-
stop_sequence: null,
|
|
89
|
-
usage: { input_tokens: this.state.inputTokens, output_tokens: 0 },
|
|
90
|
-
},
|
|
91
|
-
}));
|
|
92
|
-
translated.push(this.formatSSE('ping', { type: 'ping' }));
|
|
93
|
-
}
|
|
94
|
-
const choice = choices[0];
|
|
95
|
-
const delta = choice.delta;
|
|
96
|
-
// ── Reasoning content → thinking block ──
|
|
97
|
-
if (delta.reasoning_content) {
|
|
98
|
-
if (!this.state.thinkingBlockActive) {
|
|
99
|
-
if (this.state.textBlockActive)
|
|
100
|
-
translated.push(...this.closeTextBlock());
|
|
101
|
-
this.state.thinkingBlockActive = true;
|
|
102
|
-
translated.push(this.formatSSE('content_block_start', {
|
|
103
|
-
type: 'content_block_start',
|
|
104
|
-
index: this.state.blockIndex,
|
|
105
|
-
content_block: { type: 'thinking', thinking: '' },
|
|
106
|
-
}));
|
|
107
|
-
}
|
|
108
|
-
translated.push(this.formatSSE('content_block_delta', {
|
|
109
|
-
type: 'content_block_delta',
|
|
110
|
-
index: this.state.blockIndex,
|
|
111
|
-
delta: { type: 'thinking_delta', thinking: delta.reasoning_content },
|
|
112
|
-
}));
|
|
113
|
-
this.state.outputTokens++;
|
|
114
|
-
}
|
|
115
|
-
// ── Text content → text block ──
|
|
116
|
-
if (delta.content) {
|
|
117
|
-
if (this.state.thinkingBlockActive)
|
|
118
|
-
translated.push(...this.closeThinkingBlock());
|
|
119
|
-
if (!this.state.textBlockActive) {
|
|
120
|
-
translated.push(...this.closeToolCalls());
|
|
121
|
-
this.state.textBlockActive = true;
|
|
122
|
-
translated.push(this.formatSSE('content_block_start', {
|
|
123
|
-
type: 'content_block_start',
|
|
124
|
-
index: this.state.blockIndex,
|
|
125
|
-
content_block: { type: 'text', text: '' },
|
|
126
|
-
}));
|
|
127
|
-
}
|
|
128
|
-
translated.push(this.formatSSE('content_block_delta', {
|
|
129
|
-
type: 'content_block_delta',
|
|
130
|
-
index: this.state.blockIndex,
|
|
131
|
-
delta: { type: 'text_delta', text: delta.content },
|
|
132
|
-
}));
|
|
133
|
-
this.state.outputTokens++;
|
|
134
|
-
}
|
|
135
|
-
// ── Tool calls → tool_use blocks ──
|
|
136
|
-
const toolCalls = delta.tool_calls;
|
|
137
|
-
if (toolCalls && toolCalls.length > 0) {
|
|
138
|
-
if (this.state.thinkingBlockActive)
|
|
139
|
-
translated.push(...this.closeThinkingBlock());
|
|
140
|
-
if (this.state.textBlockActive)
|
|
141
|
-
translated.push(...this.closeTextBlock());
|
|
142
|
-
for (const tc of toolCalls) {
|
|
143
|
-
const tcIndex = tc.index;
|
|
144
|
-
const fn = tc.function;
|
|
145
|
-
if (tc.id && fn?.name) {
|
|
146
|
-
if (this.state.activeToolCalls.has(tcIndex)) {
|
|
147
|
-
translated.push(this.formatSSE('content_block_stop', {
|
|
148
|
-
type: 'content_block_stop',
|
|
149
|
-
index: this.state.blockIndex,
|
|
150
|
-
}));
|
|
151
|
-
this.state.blockIndex++;
|
|
152
|
-
}
|
|
153
|
-
this.state.activeToolCalls.set(tcIndex, { id: tc.id, name: fn.name });
|
|
154
|
-
translated.push(this.formatSSE('content_block_start', {
|
|
155
|
-
type: 'content_block_start',
|
|
156
|
-
index: this.state.blockIndex,
|
|
157
|
-
content_block: { type: 'tool_use', id: tc.id, name: fn.name, input: {} },
|
|
158
|
-
}));
|
|
159
|
-
if (fn.arguments) {
|
|
160
|
-
translated.push(this.formatSSE('content_block_delta', {
|
|
161
|
-
type: 'content_block_delta',
|
|
162
|
-
index: this.state.blockIndex,
|
|
163
|
-
delta: { type: 'input_json_delta', partial_json: fn.arguments },
|
|
164
|
-
}));
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
else if (fn?.arguments) {
|
|
168
|
-
translated.push(this.formatSSE('content_block_delta', {
|
|
169
|
-
type: 'content_block_delta',
|
|
170
|
-
index: this.state.blockIndex,
|
|
171
|
-
delta: { type: 'input_json_delta', partial_json: fn.arguments },
|
|
172
|
-
}));
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
this.state.outputTokens++;
|
|
176
|
-
}
|
|
177
|
-
// ── Handle finish_reason ──
|
|
178
|
-
if (choice.finish_reason) {
|
|
179
|
-
translated.push(...this.closeActiveBlocks());
|
|
180
|
-
const stopReason = choice.finish_reason === 'tool_calls'
|
|
181
|
-
? 'tool_use'
|
|
182
|
-
: choice.finish_reason === 'stop'
|
|
183
|
-
? 'end_turn'
|
|
184
|
-
: choice.finish_reason;
|
|
185
|
-
translated.push(this.formatSSE('message_delta', {
|
|
186
|
-
type: 'message_delta',
|
|
187
|
-
delta: { stop_reason: stopReason, stop_sequence: null },
|
|
188
|
-
usage: { output_tokens: this.state.outputTokens },
|
|
189
|
-
}));
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return translated.length > 0 ? translated.join('') : null;
|
|
193
|
-
}
|
|
194
|
-
// ── Helpers ─────────────────────────────────────────────────────────────
|
|
195
|
-
parseSSEEvents() {
|
|
196
|
-
const events = [];
|
|
197
|
-
const lines = this.buffer.split('\n');
|
|
198
|
-
let currentEvent;
|
|
199
|
-
let dataLines = [];
|
|
200
|
-
let consumed = 0;
|
|
201
|
-
for (let i = 0; i < lines.length; i++) {
|
|
202
|
-
const line = lines[i];
|
|
203
|
-
if (line.startsWith('event: ')) {
|
|
204
|
-
currentEvent = line.slice(7).trim();
|
|
205
|
-
}
|
|
206
|
-
else if (line.startsWith('data: ')) {
|
|
207
|
-
dataLines.push(line.slice(6));
|
|
208
|
-
}
|
|
209
|
-
else if (line === '' && dataLines.length > 0) {
|
|
210
|
-
events.push({ event: currentEvent, data: dataLines.join('\n') });
|
|
211
|
-
currentEvent = undefined;
|
|
212
|
-
dataLines = [];
|
|
213
|
-
consumed = lines.slice(0, i + 1).join('\n').length + 1;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (consumed > 0)
|
|
217
|
-
this.buffer = this.buffer.slice(consumed);
|
|
218
|
-
return events;
|
|
219
|
-
}
|
|
220
|
-
formatSSE(event, data) {
|
|
221
|
-
return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
222
|
-
}
|
|
223
|
-
closeThinkingBlock() {
|
|
224
|
-
if (!this.state.thinkingBlockActive)
|
|
225
|
-
return [];
|
|
226
|
-
this.state.thinkingBlockActive = false;
|
|
227
|
-
const events = [
|
|
228
|
-
this.formatSSE('content_block_stop', {
|
|
229
|
-
type: 'content_block_stop',
|
|
230
|
-
index: this.state.blockIndex,
|
|
231
|
-
}),
|
|
232
|
-
];
|
|
233
|
-
this.state.blockIndex++;
|
|
234
|
-
return events;
|
|
235
|
-
}
|
|
236
|
-
closeTextBlock() {
|
|
237
|
-
if (!this.state.textBlockActive)
|
|
238
|
-
return [];
|
|
239
|
-
this.state.textBlockActive = false;
|
|
240
|
-
const events = [
|
|
241
|
-
this.formatSSE('content_block_stop', {
|
|
242
|
-
type: 'content_block_stop',
|
|
243
|
-
index: this.state.blockIndex,
|
|
244
|
-
}),
|
|
245
|
-
];
|
|
246
|
-
this.state.blockIndex++;
|
|
247
|
-
return events;
|
|
248
|
-
}
|
|
249
|
-
closeToolCalls() {
|
|
250
|
-
if (this.state.activeToolCalls.size === 0)
|
|
251
|
-
return [];
|
|
252
|
-
const events = [];
|
|
253
|
-
for (const [_index] of this.state.activeToolCalls) {
|
|
254
|
-
events.push(this.formatSSE('content_block_stop', {
|
|
255
|
-
type: 'content_block_stop',
|
|
256
|
-
index: this.state.blockIndex,
|
|
257
|
-
}));
|
|
258
|
-
this.state.blockIndex++;
|
|
259
|
-
}
|
|
260
|
-
this.state.activeToolCalls.clear();
|
|
261
|
-
return events;
|
|
262
|
-
}
|
|
263
|
-
closeActiveBlocks() {
|
|
264
|
-
return [
|
|
265
|
-
...this.closeThinkingBlock(),
|
|
266
|
-
...this.closeTextBlock(),
|
|
267
|
-
...this.closeToolCalls(),
|
|
268
|
-
];
|
|
269
|
-
}
|
|
270
|
-
}
|