@blockrun/franklin 3.41.0 → 3.42.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.
@@ -17,6 +17,7 @@
17
17
  * fan-out can come later.
18
18
  */
19
19
  import http from 'node:http';
20
+ import crypto from 'node:crypto';
20
21
  import fs from 'node:fs';
21
22
  import path from 'node:path';
22
23
  // `ws` 8 moved the server class off the default export onto a named one. The
@@ -155,6 +156,11 @@ const PROVIDER_LABEL = {
155
156
  perplexity: 'Perplexity', amazon: 'Amazon', microsoft: 'Microsoft', '01-ai': 'Yi', ai21: 'AI21',
156
157
  };
157
158
  const PROVIDER_ORDER = ['Anthropic', 'OpenAI', 'Google', 'xAI', 'DeepSeek', 'Qwen', 'Moonshot', 'Meta', 'Mistral', 'MiniMax', 'NVIDIA'];
159
+ const MEDIA_MIME = {
160
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac',
161
+ mp4: 'video/mp4', webm: 'video/webm',
162
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',
163
+ };
158
164
  function providerLabel(id, ownedBy) {
159
165
  const p = (id.split('/')[0] || ownedBy || '').toLowerCase();
160
166
  return PROVIDER_LABEL[p] || (p ? p.charAt(0).toUpperCase() + p.slice(1) : 'Other');
@@ -175,7 +181,7 @@ function providerLabel(id, ownedBy) {
175
181
  // Defense-in-depth: when FRANKLIN_SERVE_TOKEN is set, every WS upgrade and
176
182
  // /file request must also carry it (?token=…).
177
183
  const DEFAULT_ALLOWED_ORIGINS = ['https://franklin.run'];
178
- function isOriginAllowed(origin) {
184
+ export function isOriginAllowed(origin) {
179
185
  if (!origin)
180
186
  return true; // non-browser local client
181
187
  if (origin === 'null')
@@ -195,11 +201,185 @@ function isOriginAllowed(origin) {
195
201
  .split(',').map((s) => s.trim()).filter(Boolean);
196
202
  return [...DEFAULT_ALLOWED_ORIGINS, ...extra].includes(origin);
197
203
  }
198
- function tokenOk(url) {
204
+ export function tokenOk(url) {
199
205
  const required = process.env.FRANKLIN_SERVE_TOKEN;
200
206
  if (!required)
201
207
  return true;
202
- return url.searchParams.get('token') === required;
208
+ const supplied = url.searchParams.get('token');
209
+ if (!supplied)
210
+ return false;
211
+ const expectedBytes = Buffer.from(required);
212
+ const suppliedBytes = Buffer.from(supplied);
213
+ return expectedBytes.length === suppliedBytes.length && crypto.timingSafeEqual(expectedBytes, suppliedBytes);
214
+ }
215
+ export function localFileUrl(port, filePath) {
216
+ const url = new URL(`http://127.0.0.1:${port}/file`);
217
+ url.searchParams.set('path', filePath);
218
+ const signingKey = process.env.FRANKLIN_SERVE_FILE_TOKEN || process.env.FRANKLIN_SERVE_TOKEN;
219
+ if (signingKey) {
220
+ url.searchParams.set('sig', crypto.createHmac('sha256', signingKey).update(filePath).digest('base64url'));
221
+ }
222
+ return url.toString();
223
+ }
224
+ export function fileTokenOk(url) {
225
+ const signingKey = process.env.FRANKLIN_SERVE_FILE_TOKEN || process.env.FRANKLIN_SERVE_TOKEN;
226
+ if (!signingKey)
227
+ return true;
228
+ const filePath = url.searchParams.get('path');
229
+ const supplied = url.searchParams.get('sig');
230
+ if (!filePath || !supplied)
231
+ return false;
232
+ const expected = crypto.createHmac('sha256', signingKey).update(filePath).digest('base64url');
233
+ const expectedBytes = Buffer.from(expected);
234
+ const suppliedBytes = Buffer.from(supplied);
235
+ return expectedBytes.length === suppliedBytes.length && crypto.timingSafeEqual(expectedBytes, suppliedBytes);
236
+ }
237
+ export function resolveServedMediaPath(candidate, fileRoots) {
238
+ if (!candidate || !fs.existsSync(candidate) || !fs.statSync(candidate).isFile())
239
+ return null;
240
+ const realPath = fs.realpathSync(candidate);
241
+ const insideRoot = fileRoots.some((root) => realPath === root || realPath.startsWith(root + path.sep));
242
+ const extension = realPath.toLowerCase().split('.').pop() || '';
243
+ const mediaType = MEDIA_MIME[extension];
244
+ return insideRoot && mediaType ? { realPath, mediaType } : null;
245
+ }
246
+ /**
247
+ * Resolve a possibly-not-yet-created path through its nearest existing parent.
248
+ * This catches both `..` escapes and an in-workspace symlink that points out of
249
+ * the workspace, including writes to a new file below that symlink.
250
+ */
251
+ function canonicalProspectivePath(candidate) {
252
+ let cursor = path.resolve(candidate);
253
+ const missing = [];
254
+ while (!fs.existsSync(cursor)) {
255
+ const parent = path.dirname(cursor);
256
+ if (parent === cursor)
257
+ break;
258
+ missing.unshift(path.basename(cursor));
259
+ cursor = parent;
260
+ }
261
+ const realParent = fs.realpathSync(cursor);
262
+ return path.resolve(realParent, ...missing);
263
+ }
264
+ /** Desktop-only policy: paths outside the workspace require explicit approval. */
265
+ export function createDesktopWorkspacePermissionPolicy(workDir) {
266
+ const canonicalRoot = fs.realpathSync(workDir);
267
+ const pathKeys = {
268
+ Read: 'file_path',
269
+ Write: 'file_path',
270
+ Edit: 'file_path',
271
+ Glob: 'path',
272
+ Grep: 'path',
273
+ };
274
+ return (toolName, input) => {
275
+ // Shell syntax is intentionally not treated as a confinement primitive.
276
+ // Every Bash call must be visibly approved in Desktop, even if Franklin's
277
+ // generic classifier would normally auto-allow a read-only command.
278
+ if (toolName === 'Bash') {
279
+ return { behavior: 'ask', reason: 'Desktop requires approval for shell commands' };
280
+ }
281
+ // Detach ultimately executes `bash -lc` in the background. Treat it as a
282
+ // shell boundary too, even when a CLI user previously persisted an allow
283
+ // rule for the tool name.
284
+ if (toolName === 'Detach') {
285
+ return { behavior: 'ask', reason: 'Desktop requires approval for background shell commands' };
286
+ }
287
+ // These confirmed actions can move funds or grant token approvals. The
288
+ // driver policy runs before persisted/session allow rules, so every
289
+ // Desktop execution receives a fresh, visible decision.
290
+ if (toolName === 'PolymarketBet') {
291
+ const action = typeof input.action === 'string' ? input.action.toLowerCase() : '';
292
+ const confirmed = input.confirm !== false && input.confirm != null;
293
+ if (confirmed && ['setup', 'fund', 'redeem', 'withdraw', 'cancel'].includes(action)) {
294
+ return { behavior: 'ask', reason: `Desktop requires approval for Polymarket ${action}` };
295
+ }
296
+ }
297
+ const candidates = [];
298
+ const key = pathKeys[toolName];
299
+ if (key)
300
+ candidates.push(input[key]);
301
+ // Media tools accept local input/output paths in addition to the core file
302
+ // tools. HTTP(S)/data references are remote/inline and need no file grant.
303
+ if (toolName === 'ImageGen') {
304
+ candidates.push(input.output_path, input.image_url, input.mask);
305
+ if (Array.isArray(input.images))
306
+ candidates.push(...input.images);
307
+ else if (input.images != null)
308
+ return { behavior: 'deny', reason: 'invalid image path list' };
309
+ }
310
+ else if (toolName === 'VideoGen') {
311
+ candidates.push(input.output_path, input.image_url);
312
+ }
313
+ else if (toolName === 'MusicGen') {
314
+ candidates.push(input.output_path);
315
+ }
316
+ else if (toolName === 'BrowserX' && input.action === 'screenshot') {
317
+ // BrowserX's implicit destination is ~/.blockrun/screenshots, outside
318
+ // the project workspace, so it also needs visible consent.
319
+ if (input.path == null || input.path === '') {
320
+ return { behavior: 'ask', reason: 'screenshot is saved outside the Desktop workspace' };
321
+ }
322
+ candidates.push(input.path);
323
+ }
324
+ else if (toolName === 'BrowserX' && input.action === 'open' && typeof input.url === 'string') {
325
+ try {
326
+ // Use WHATWG parsing, matching the browser's normalization of ASCII
327
+ // whitespace (for example `fi\tle:` still becomes the `file:` scheme).
328
+ if (new URL(input.url).protocol === 'file:') {
329
+ // A later snapshot can reveal the file contents, so authorize the
330
+ // navigation itself rather than the snapshot that follows it.
331
+ return { behavior: 'ask', reason: 'browser is opening a local file' };
332
+ }
333
+ }
334
+ catch { /* BrowserX will report malformed URLs itself. */ }
335
+ }
336
+ const localCandidates = candidates.filter((raw) => {
337
+ if (raw == null || raw === '')
338
+ return false;
339
+ return !(typeof raw === 'string' && /^(?:https?:|data:|blob:)/i.test(raw));
340
+ });
341
+ if (localCandidates.length === 0)
342
+ return undefined;
343
+ try {
344
+ for (const raw of localCandidates) {
345
+ if (typeof raw !== 'string') {
346
+ return { behavior: 'deny', reason: 'invalid workspace path' };
347
+ }
348
+ const candidate = path.isAbsolute(raw) ? raw : path.resolve(canonicalRoot, raw);
349
+ const canonical = canonicalProspectivePath(candidate);
350
+ const inside = canonical === canonicalRoot || canonical.startsWith(canonicalRoot + path.sep);
351
+ if (!inside) {
352
+ return { behavior: 'ask', reason: `path is outside Desktop workspace: ${canonicalRoot}` };
353
+ }
354
+ }
355
+ return undefined;
356
+ }
357
+ catch {
358
+ return { behavior: 'deny', reason: 'unable to validate workspace path' };
359
+ }
360
+ };
361
+ }
362
+ function refreshPersistedMediaUrls(value, port, key = '') {
363
+ if (Array.isArray(value))
364
+ return value.map((item) => refreshPersistedMediaUrls(item, port));
365
+ if (value && typeof value === 'object') {
366
+ return Object.fromEntries(Object.entries(value).map(([childKey, childValue]) => [
367
+ childKey,
368
+ refreshPersistedMediaUrls(childValue, port, childKey),
369
+ ]));
370
+ }
371
+ if (typeof value !== 'string' || !['image', 'video', 'music'].includes(key))
372
+ return value;
373
+ try {
374
+ const url = new URL(value);
375
+ const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
376
+ const filePath = url.searchParams.get('path');
377
+ if (localHosts.has(url.hostname) && url.pathname === '/file' && filePath) {
378
+ return localFileUrl(port, filePath);
379
+ }
380
+ }
381
+ catch { /* data URL, local path, or ordinary text */ }
382
+ return value;
203
383
  }
204
384
  function send(ws, id, kind, payload) {
205
385
  if (ws.readyState !== WebSocket.OPEN)
@@ -219,10 +399,15 @@ function dialogueText(content) {
219
399
  .join('');
220
400
  }
221
401
  export async function startServer(opts) {
222
- const { port, workDir, debug } = opts;
402
+ let { port } = opts;
403
+ const { workDir, debug } = opts;
223
404
  const chain = loadChain();
224
405
  const apiUrl = API_URLS[chain];
225
406
  const userConfig = loadConfig();
407
+ const desktopBoundary = process.env.FRANKLIN_DESKTOP_WORKSPACE_BOUNDARY === '1';
408
+ const desktopPermissionPolicy = desktopBoundary
409
+ ? createDesktopWorkspacePermissionPolicy(workDir)
410
+ : undefined;
226
411
  // ── Multi-agent host (dashboard fleet) ──
227
412
  // The legacy single-window path below stays byte-compatible for the
228
413
  // desktop app; hosted agents are additive, run in 'default' permission
@@ -233,6 +418,10 @@ export async function startServer(opts) {
233
418
  apiUrl,
234
419
  defaultModel: userConfig['default-model'] || FREE_DEFAULT_MODEL,
235
420
  debug,
421
+ permissionPolicyFn: desktopPermissionPolicy,
422
+ allowSubAgents: !desktopBoundary,
423
+ allowPaidPrefetch: !desktopBoundary,
424
+ defaultMaxSpendUsd: desktopBoundary ? 5 : undefined,
236
425
  });
237
426
  // Per-socket subscription bookkeeping: sessionId → unsubscribe.
238
427
  const wsSubs = new WeakMap();
@@ -262,11 +451,28 @@ export async function startServer(opts) {
262
451
  // The socket + correlation id for the in-flight turn (single-window).
263
452
  let activeWs = null;
264
453
  let activeTurnId = null;
265
- // Pending approval asks for the legacy desktop session (trade plans).
454
+ // Pending approval asks for the legacy desktop session (tools + trade plans).
266
455
  // Keyed by askId — the wire contract the desktop UI already declares
267
456
  // (agent.permissionAsk / agent.permissionResponse with askId + decision).
268
457
  let askSeq = 0;
269
458
  const legacyAsks = new Map();
459
+ const requestDesktopPermission = (toolName, description, timeoutMs = 15 * 60 * 1000) => new Promise((resolve) => {
460
+ if (!activeWs || !activeTurnId) {
461
+ resolve('no');
462
+ return;
463
+ }
464
+ const askId = `ask_${++askSeq}_${Date.now().toString(36)}`;
465
+ const timer = setTimeout(() => {
466
+ if (legacyAsks.delete(askId))
467
+ resolve('no');
468
+ }, timeoutMs);
469
+ timer.unref?.();
470
+ legacyAsks.set(askId, (decision) => {
471
+ clearTimeout(timer);
472
+ resolve(decision);
473
+ });
474
+ emit('agent.permissionAsk', { sessionId: '', toolName, description, askId });
475
+ });
270
476
  // We sometimes inject helper commands (`/model …`, `/clear`) as their own
271
477
  // turns ahead of the real prompt. Each ends with its own turn_done — which
272
478
  // would emit agent.done and clear activeTurnId, killing the real prompt's
@@ -402,7 +608,7 @@ export async function startServer(opts) {
402
608
  sessionId: '',
403
609
  toolCallId: event.id,
404
610
  preview: '',
405
- artifacts: [{ path: `http://127.0.0.1:${port}/file?path=${encodeURIComponent(filePath)}`, mediaType }],
611
+ artifacts: [{ path: localFileUrl(port, filePath), mediaType }],
406
612
  });
407
613
  }
408
614
  break;
@@ -435,13 +641,15 @@ export async function startServer(opts) {
435
641
  sessionStarted = true;
436
642
  currentModel = model;
437
643
  const systemInstructions = assembleInstructions(workDir, model);
438
- const subAgent = createSubAgentCapability(apiUrl, chain, allCapabilities, model);
644
+ const subAgent = desktopBoundary
645
+ ? null
646
+ : createSubAgentCapability(apiUrl, chain, allCapabilities, model);
439
647
  try {
440
648
  const { registerMoAConfig } = await import('../tools/moa.js');
441
649
  registerMoAConfig(apiUrl, chain, model);
442
650
  }
443
651
  catch { /* MoA optional */ }
444
- const capabilities = [...allCapabilities, subAgent];
652
+ const capabilities = subAgent ? [...allCapabilities, subAgent] : allCapabilities;
445
653
  const config = {
446
654
  model,
447
655
  apiUrl,
@@ -450,38 +658,33 @@ export async function startServer(opts) {
450
658
  capabilities,
451
659
  maxTurns: 100,
452
660
  workingDir: workDir,
453
- permissionMode: 'trust', // tools auto-run; money still gates via approvalPromptFn below
661
+ permissionMode: 'default',
662
+ permissionPromptFn: (toolName, description) => requestDesktopPermission(toolName, description),
663
+ permissionPolicyFn: desktopPermissionPolicy,
454
664
  debug: !!debug,
455
665
  showPrefetchStatus: false,
666
+ allowPaidPrefetch: !desktopBoundary,
667
+ ...(desktopBoundary ? { maxSpendUsd: 5 } : {}),
456
668
  costSaver,
669
+ // Tools such as ImageGen perform their own exact-price confirmation.
670
+ // Map the Desktop yes/no approval bridge back to the tool's choices.
671
+ onAskUser: async (question, options) => {
672
+ const decision = await requestDesktopPermission('Agent confirmation', question);
673
+ if (decision === 'yes' || decision === 'always')
674
+ return options?.[0] ?? 'yes';
675
+ return options?.[options.length - 1] ?? 'no';
676
+ },
457
677
  // Structured approvals (trade plans): surfaced to the desktop over the
458
678
  // in-flight turn stream as agent.permissionAsk; the UI answers with
459
679
  // agent.permissionResponse {askId, decision}. Without a connected
460
680
  // client — or unanswered past the TTL — the approval fails closed,
461
681
  // matching the trade-plan gate's deny-by-default posture.
462
- approvalPromptFn: (req) => new Promise((resolve) => {
463
- if (!activeWs || !activeTurnId) {
464
- resolve({ choice: 'deny', message: 'no client connected to approve' });
465
- return;
466
- }
467
- const askId = `ask_${++askSeq}_${Date.now().toString(36)}`;
468
- const timer = setTimeout(() => {
469
- if (legacyAsks.delete(askId)) {
470
- resolve({ choice: 'deny', message: 'approval timed out' });
471
- }
472
- }, req.timeoutMs ?? 15 * 60 * 1000);
473
- timer.unref?.();
474
- legacyAsks.set(askId, (decision) => {
475
- clearTimeout(timer);
476
- resolve(decision);
477
- });
478
- emit('agent.permissionAsk', {
479
- sessionId: '',
480
- toolName: req.kind === 'trade-plan' ? 'TradePlan' : req.title,
481
- description: `${req.title}\n\n${req.description}`,
482
- askId,
483
- });
484
- }),
682
+ approvalPromptFn: async (req) => {
683
+ const decision = await requestDesktopPermission(req.kind === 'trade-plan' ? 'TradePlan' : req.title, `${req.title}\n\n${req.description}`, req.timeoutMs);
684
+ return decision === 'yes' || decision === 'always'
685
+ ? { choice: 'approve' }
686
+ : { choice: 'deny', message: 'approval denied or timed out' };
687
+ },
485
688
  };
486
689
  agentConfig = config;
487
690
  interactiveSession(config, getUserInput, onEvent, (abort) => { abortFn = abort; })
@@ -523,7 +726,10 @@ export async function startServer(opts) {
523
726
  case 'wallet.info': {
524
727
  try {
525
728
  const client = await getWallet();
526
- const address = client.getWalletAddress();
729
+ // Solana resolves its public key asynchronously while Base returns it
730
+ // synchronously. Awaiting works for both and keeps the wire payload a
731
+ // string instead of accidentally serializing a pending Promise as {}.
732
+ const address = await client.getWalletAddress();
527
733
  const balanceUsd = await fetchBalanceUsd(); // best-effort; undefined on failure
528
734
  send(ws, id, 'response', { address, chain, balanceUsd });
529
735
  }
@@ -574,10 +780,10 @@ export async function startServer(opts) {
574
780
  catch { /* ignore */ }
575
781
  };
576
782
  try {
577
- const local = readLocal();
783
+ const local = refreshPersistedMediaUrls(readLocal(), port);
578
784
  if (isCloudSyncEnabled()) {
579
785
  try {
580
- const cloud = await cloudList();
786
+ const cloud = refreshPersistedMediaUrls(await cloudList(), port);
581
787
  if (cloud.length > 0) {
582
788
  writeLocal(cloud); // refresh local cache
583
789
  send(ws, id, 'response', { conversations: cloud });
@@ -598,7 +804,7 @@ export async function startServer(opts) {
598
804
  }
599
805
  case 'history.save': {
600
806
  try {
601
- const conversations = Array.isArray(p.conversations) ? p.conversations : [];
807
+ const conversations = refreshPersistedMediaUrls(Array.isArray(p.conversations) ? p.conversations : [], port);
602
808
  // Local file = instant durable cache; cloud = best-effort wallet sync.
603
809
  fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
604
810
  fs.writeFileSync(path.join(BLOCKRUN_DIR, 'franklin-desktop-history.json'), JSON.stringify(conversations), { mode: 0o600 });
@@ -746,11 +952,8 @@ export async function startServer(opts) {
746
952
  if (resolver) {
747
953
  legacyAsks.delete(askId);
748
954
  const decision = String(p.decision ?? p.choice ?? 'n').toLowerCase();
749
- const approve = decision === 'y' || decision === 'yes' || decision === 'always' || decision === 'approve';
750
- resolver({
751
- choice: approve ? 'approve' : 'deny',
752
- message: p.message ? String(p.message) : undefined,
753
- });
955
+ resolver(decision === 'always' ? 'always' :
956
+ decision === 'y' || decision === 'yes' || decision === 'approve' ? 'yes' : 'no');
754
957
  send(ws, id, 'response', { ok: true });
755
958
  }
756
959
  else {
@@ -847,44 +1050,30 @@ export async function startServer(opts) {
847
1050
  catch {
848
1051
  return null;
849
1052
  } }).filter((r) => !!r);
850
- const MEDIA_MIME = {
851
- mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac',
852
- mp4: 'video/mp4', webm: 'video/webm',
853
- png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',
854
- };
855
1053
  const httpServer = http.createServer((req, res) => {
856
1054
  try {
857
1055
  const url = new URL(req.url || '/', 'http://127.0.0.1');
858
1056
  const origin = req.headers.origin;
859
1057
  if (url.pathname === '/file') {
860
- if (!isOriginAllowed(origin) || !tokenOk(url)) {
1058
+ if (!isOriginAllowed(origin) || !fileTokenOk(url)) {
861
1059
  res.writeHead(403);
862
1060
  res.end();
863
1061
  return;
864
1062
  }
865
1063
  const p = url.searchParams.get('path') || '';
866
- if (!p || !fs.existsSync(p) || !fs.statSync(p).isFile()) {
867
- res.writeHead(404);
868
- res.end();
869
- return;
870
- }
871
- // Resolve symlinks before the prefix check so a link can't escape a root.
872
- const real = fs.realpathSync(p);
873
- const inRoot = fileRoots.some((root) => real === root || real.startsWith(root + path.sep));
874
- const ext = real.toLowerCase().split('.').pop() || '';
875
- const mime = MEDIA_MIME[ext];
876
- if (!inRoot || !mime) {
877
- res.writeHead(403);
1064
+ const media = resolveServedMediaPath(p, fileRoots);
1065
+ if (!media) {
1066
+ res.writeHead(p ? 403 : 404);
878
1067
  res.end();
879
1068
  return;
880
1069
  }
881
1070
  res.writeHead(200, {
882
- 'Content-Type': mime,
1071
+ 'Content-Type': media.mediaType,
883
1072
  // Reflect the (already vetted) origin instead of `*` so arbitrary
884
1073
  // sites can't read the bytes cross-origin.
885
1074
  ...(origin && origin !== 'null' ? { 'Access-Control-Allow-Origin': origin } : {}),
886
1075
  });
887
- fs.createReadStream(real).pipe(res);
1076
+ fs.createReadStream(media.realPath).pipe(res);
888
1077
  return;
889
1078
  }
890
1079
  }
@@ -928,26 +1117,53 @@ export async function startServer(opts) {
928
1117
  subscribedSessions.delete(ws);
929
1118
  });
930
1119
  });
931
- await new Promise((resolve) => {
1120
+ await new Promise((resolve, reject) => {
1121
+ httpServer.once('error', reject);
932
1122
  httpServer.listen(port, '127.0.0.1', () => {
1123
+ httpServer.off('error', reject);
1124
+ const address = httpServer.address();
1125
+ if (!address || typeof address === 'string') {
1126
+ reject(new Error('Franklin agent server did not report a TCP address'));
1127
+ return;
1128
+ }
1129
+ port = address.port;
933
1130
  // eslint-disable-next-line no-console
934
1131
  console.log(`Franklin agent server on ws://127.0.0.1:${port}/agent (chain: ${chain}, workdir: ${workDir})`);
935
1132
  resolve();
936
1133
  });
937
1134
  });
1135
+ // Packaged Desktop uses a private parent/child IPC channel for readiness.
1136
+ // The renderer is not created until Electron receives this effective port.
1137
+ if (typeof process.send === 'function') {
1138
+ process.send({ type: 'franklin:server-ready', port });
1139
+ }
938
1140
  // Discovery file (mirror of the panel-url pattern): lets `franklin panel`
939
1141
  // point its Agents tab at this server without configuration.
940
1142
  const serveUrlFile = path.join(BLOCKRUN_DIR, 'serve-url');
941
- try {
942
- fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
943
- fs.writeFileSync(serveUrlFile, `ws://127.0.0.1:${port}/agent`);
1143
+ const discoveryEnabled = process.env.FRANKLIN_SERVE_DISCOVERY !== 'off';
1144
+ let writtenDiscoveryUrl = null;
1145
+ if (discoveryEnabled) {
1146
+ try {
1147
+ const discoveryUrl = new URL(`ws://127.0.0.1:${port}/agent`);
1148
+ const token = process.env.FRANKLIN_SERVE_TOKEN;
1149
+ if (token)
1150
+ discoveryUrl.searchParams.set('token', token);
1151
+ writtenDiscoveryUrl = discoveryUrl.toString();
1152
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
1153
+ fs.writeFileSync(serveUrlFile, writtenDiscoveryUrl, { mode: 0o600 });
1154
+ }
1155
+ catch { /* best-effort */ }
944
1156
  }
945
- catch { /* best-effort */ }
946
1157
  const cleanup = () => {
947
- try {
948
- fs.unlinkSync(serveUrlFile);
1158
+ // Do not remove another server's discovery record. Packaged Desktop has
1159
+ // discovery disabled, and multiple standalone servers may overlap.
1160
+ if (writtenDiscoveryUrl) {
1161
+ try {
1162
+ if (fs.readFileSync(serveUrlFile, 'utf8') === writtenDiscoveryUrl)
1163
+ fs.unlinkSync(serveUrlFile);
1164
+ }
1165
+ catch { /* gone or replaced */ }
949
1166
  }
950
- catch { /* gone */ }
951
1167
  host.shutdown();
952
1168
  };
953
1169
  process.once('SIGINT', () => { cleanup(); process.exit(130); });
@@ -255,7 +255,7 @@ async function executeJupiterQuote(input) {
255
255
  };
256
256
  }
257
257
  }
258
- async function executeJupiterSwap(input, ctx) {
258
+ async function executeJupiterSwapUnsafeReference(input, ctx) {
259
259
  // Session-cap pre-check (cheapest, fail fast).
260
260
  if (liveSwapCount >= liveSwapCap) {
261
261
  return {
@@ -396,6 +396,20 @@ async function executeJupiterSwap(input, ctx) {
396
396
  };
397
397
  }
398
398
  }
399
+ async function executeJupiterSwap(input, ctx) {
400
+ // Fail closed until Franklin can independently validate the complete
401
+ // versioned transaction (including address-table-resolved accounts and all
402
+ // token/lamport effects) against the user's approved swap. Signing opaque
403
+ // transaction bytes returned by an upstream service is not an acceptable
404
+ // wallet boundary. JupiterQuote remains available.
405
+ void input;
406
+ void ctx;
407
+ void executeJupiterSwapUnsafeReference;
408
+ return {
409
+ output: 'Live Jupiter swaps are temporarily disabled for safety. Franklin will not sign an upstream transaction until it can locally verify every instruction and asset movement. Use JupiterQuote to inspect current routes and prices.',
410
+ isError: true,
411
+ };
412
+ }
399
413
  // ─── Capability handlers ──────────────────────────────────────────────────
400
414
  const COMMON_INPUT_PROPERTIES = {
401
415
  input_mint: {
@@ -429,7 +443,7 @@ export const jupiterQuoteCapability = {
429
443
  export const jupiterSwapCapability = {
430
444
  spec: {
431
445
  name: 'JupiterSwap',
432
- description: "Execute a Solana DEX swap via Jupiter Ultra. Quotes the order, asks the user to confirm via AskUser, signs locally with the Franklin Solana wallet, and submits. A 20 bps platform fee is collected on-chain by Jupiter as part of the swap (BlockRun referral — official integrator program). Returns the Solscan transaction link.",
446
+ description: "Live Solana swap execution is temporarily unavailable while Franklin adds complete local transaction validation. Use JupiterQuote for a read-only route and price; Franklin will not sign opaque upstream transaction bytes.",
433
447
  input_schema: {
434
448
  type: 'object',
435
449
  required: ['input_mint', 'output_mint', 'amount'],
@@ -253,7 +253,7 @@ async function executeBase0xQuote(input, ctx) {
253
253
  }
254
254
  }
255
255
  // ─── Swap (full execute) ─────────────────────────────────────────────────
256
- async function executeBase0xSwap(input, ctx) {
256
+ async function executeBase0xSwapUnsafeReference(input, ctx) {
257
257
  if (liveSwapCount >= liveSwapCap) {
258
258
  return {
259
259
  output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
@@ -452,6 +452,19 @@ async function executeBase0xSwap(input, ctx) {
452
452
  ].join('\n'),
453
453
  };
454
454
  }
455
+ async function executeBase0xSwap(input, ctx) {
456
+ // Fail closed until Franklin can independently bind the upstream Permit2
457
+ // typed data, allowance spender, transaction target, calldata, value, and
458
+ // token effects to the exact swap the user approved. A displayed quote is
459
+ // not sufficient proof that the bytes being signed execute that quote.
460
+ void input;
461
+ void ctx;
462
+ void executeBase0xSwapUnsafeReference;
463
+ return {
464
+ output: 'Live Base swaps through 0x are temporarily disabled for safety. Franklin will not approve a gateway-provided spender or sign an upstream transaction until every asset movement can be verified locally. Use Base0xQuote for a read-only route and price.',
465
+ isError: true,
466
+ };
467
+ }
455
468
  // ─── Capability handlers ─────────────────────────────────────────────────
456
469
  const COMMON_INPUT_PROPERTIES = {
457
470
  sell_token: {
@@ -485,7 +498,7 @@ export const base0xQuoteCapability = {
485
498
  export const base0xSwapCapability = {
486
499
  spec: {
487
500
  name: 'Base0xSwap',
488
- description: "Execute a Base DEX swap via 0x V2 (Permit2). Quotes through BlockRun gateway (x402-paid, server-side 0x key — no user setup needed), asks the user to confirm, signs locally with the Franklin Base wallet, and submits via Base RPC. A 20 bps affiliate fee in the sell-token is collected on-chain by 0x as part of the swap (BlockRun affiliate program — official 0x integrator mechanism). Returns the BaseScan transaction link.",
501
+ description: "Live Base swap execution through 0x is temporarily unavailable while Franklin adds complete local transaction and Permit2 validation. Use Base0xQuote for a read-only route and price; Franklin will not approve or sign opaque gateway-provided transaction data.",
489
502
  input_schema: {
490
503
  type: 'object',
491
504
  required: ['sell_token', 'buy_token', 'sell_amount'],
@@ -248,7 +248,7 @@ async function pollUntilDone(tradeHash, ctx) {
248
248
  }
249
249
  return last;
250
250
  }
251
- async function executeBase0xGaslessSwap(input, ctx) {
251
+ async function executeBase0xGaslessSwapUnsafeReference(input, ctx) {
252
252
  if (liveSwapCount >= liveSwapCap) {
253
253
  return {
254
254
  output: `Live-swap session cap reached (${liveSwapCount}/${liveSwapCap}). Stopping to protect your wallet.\n` +
@@ -441,13 +441,23 @@ async function executeBase0xGaslessSwap(input, ctx) {
441
441
  isError: final.status === 'failed',
442
442
  };
443
443
  }
444
+ async function executeBase0xGaslessSwap(input, ctx) {
445
+ // The relayer quote supplies both trade and approval EIP-712 payloads. Do
446
+ // not sign them until Franklin can independently bind every domain, token,
447
+ // amount, spender, nonce, recipient, and deadline to the user's approval.
448
+ void input;
449
+ void ctx;
450
+ void executeBase0xGaslessSwapUnsafeReference;
451
+ return {
452
+ output: 'Live gasless Base swaps through 0x are temporarily disabled for safety. Franklin will not sign gateway-provided trade or approval typed data until every field and asset movement can be verified locally. Use Base0xQuote for a read-only route and price.',
453
+ isError: true,
454
+ };
455
+ }
444
456
  // ─── Capability handler ──────────────────────────────────────────────────
445
457
  export const base0xGaslessSwapCapability = {
446
458
  spec: {
447
459
  name: 'Base0xGaslessSwap',
448
- description: "Execute a Base DEX swap via 0x Gasless V2. The user signs only EIP-712 typed-data (offline, no on-chain action) — 0x's relayer broadcasts the trade and pays gas. **The user does NOT need any ETH for gas.** Only input token (USDC, DAI, etc. — Permit-supporting ERC-20) is required. Returns the BaseScan link once the relayer confirms. " +
449
- "Routes through BlockRun gateway /v1/zerox/gasless/* — no 0x signup needed. Affiliate 20 bps in sell-token to BlockRun treasury (server-side enforced). " +
450
- "Use this instead of Base0xSwap when the user has 0 ETH but holds USDC/DAI. For tokens that don't support Permit (USDT etc.), the tool errors with a clear instruction to use Base0xSwap instead.",
460
+ description: "Live gasless Base swap execution through 0x is temporarily unavailable while Franklin adds complete local EIP-712 validation. Use Base0xQuote for a read-only route and price; Franklin will not sign opaque gateway-provided trade or approval data.",
451
461
  input_schema: {
452
462
  type: 'object',
453
463
  required: ['sell_token', 'buy_token', 'sell_amount'],