@blockrun/franklin 3.49.20 → 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.
@@ -37,7 +37,9 @@ async function openRunningPanel(section) {
37
37
  }
38
38
  catch { /* none */ }
39
39
  let alive = false;
40
- if (/^http:\/\/localhost:\d+\/\?token=[0-9a-f]{64}$/.test(launch)) {
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)) {
41
43
  try {
42
44
  const res = await fetch(launch, { signal: AbortSignal.timeout(1500) });
43
45
  alive = res.status === 200; // 401 means a different panel process owns the port now
@@ -53,7 +55,7 @@ async function openRunningPanel(section) {
53
55
  }
54
56
  openInBrowser(section ? `${launch}#${section}` : launch);
55
57
  const port = new URL(launch).port;
56
- console.log(` Opened the Franklin panel${section ? ` (${section})` : ''} on localhost:${port}.`);
58
+ console.log(` Opened the Franklin panel${section ? ` (${section})` : ''} on 127.0.0.1:${port}.`);
57
59
  }
58
60
  export async function panelCommand(options) {
59
61
  if (options.open !== undefined) {
@@ -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
- const es = new EventSource('/api/events?token=' + encodeURIComponent(window.__FRANKLIN_PANEL_TOKEN));
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
- es.onopen = () => { dot.className = 'dot on'; statusEl.textContent = 'live'; };
1434
- es.onerror = () => { dot.className = 'dot off'; statusEl.textContent = 'offline'; };
1435
- es.onmessage = (e) => {
1436
- try { if (JSON.parse(e.data).type === 'stats.updated') loadOverview(); } catch {}
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');
@@ -10,6 +10,11 @@ import http from 'node:http';
10
10
  * port through an ssh -L tunnel) could GET `/`, read the token out of the
11
11
  * HTML, and call /api/wallet/secret. Only someone who can see the terminal
12
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.
13
18
  */
14
19
  export declare function getPanelLaunchUrl(port: number): string;
15
20
  export declare const PANEL_URL_FILE: string;
@@ -110,9 +110,14 @@ function hasPanelToken(req) {
110
110
  * port through an ssh -L tunnel) could GET `/`, read the token out of the
111
111
  * HTML, and call /api/wallet/secret. Only someone who can see the terminal
112
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.
113
118
  */
114
119
  export function getPanelLaunchUrl(port) {
115
- return `http://localhost:${port}/?token=${PANEL_TOKEN}`;
120
+ return `http://127.0.0.1:${port}/?token=${PANEL_TOKEN}`;
116
121
  }
117
122
  export const PANEL_URL_FILE = path.join(BLOCKRUN_DIR, 'panel-url');
118
123
  /**
@@ -208,10 +213,9 @@ export function createPanelServer(port) {
208
213
  // Loopback + local Host does not tell OS users apart: on a shared machine
209
214
  // another account, or anyone reaching the port through an ssh -L tunnel,
210
215
  // passes both and could read transcripts and the audit log
211
- // (GHSA-jx74-262x-94p3). EventSource cannot set headers, so /api/events
212
- // alone may carry the token as ?token=.
213
- if (p.startsWith('/api/') && !hasPanelToken(req)
214
- && !(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)) {
215
219
  json(res, { error: 'forbidden' }, 403);
216
220
  return;
217
221
  }
@@ -370,7 +374,14 @@ export function createPanelServer(port) {
370
374
  return;
371
375
  }
372
376
  if (p.startsWith('/api/sessions/')) {
373
- const id = decodeURIComponent(p.slice('/api/sessions/'.length));
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
+ }
374
385
  const history = loadSessionHistory(id);
375
386
  json(res, history);
376
387
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.20",
3
+ "version": "3.49.21",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -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
- }