@blockrun/franklin 3.49.17 → 3.49.19
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/commands.js +1 -1
- package/dist/agent/evaluator.d.ts +1 -0
- package/dist/agent/evaluator.js +12 -4
- package/dist/agent/input-queue.d.ts +3 -2
- package/dist/agent/loop.d.ts +2 -2
- package/dist/agent/loop.js +33 -6
- package/dist/agent/types.d.ts +6 -1
- package/dist/panel/html.js +3 -1
- package/dist/panel/server.js +23 -4
- package/dist/serve/desktop-input.d.ts +4 -0
- package/dist/serve/desktop-input.js +33 -0
- package/dist/serve/desktop-questions.d.ts +10 -0
- package/dist/serve/desktop-questions.js +40 -0
- package/dist/serve/server.js +49 -13
- package/dist/session/storage.js +3 -3
- package/dist/skills/bootstrap.d.ts +3 -1
- package/dist/skills/bootstrap.js +4 -2
- package/dist/skills/invoke.js +4 -1
- package/dist/skills/loader.d.ts +1 -9
- package/dist/skills/loader.js +16 -77
- package/dist/skills/management.d.ts +28 -0
- package/dist/skills/management.js +113 -0
- package/dist/skills/state.d.ts +2 -0
- package/dist/skills/state.js +26 -0
- package/dist/storage/safe-id.d.ts +10 -0
- package/dist/storage/safe-id.js +24 -0
- package/dist/tasks/paths.js +4 -0
- package/dist/tools/glob.js +47 -19
- package/dist/tools/sensitive-paths.d.ts +2 -0
- package/dist/tools/sensitive-paths.js +23 -0
- package/package.json +4 -3
package/dist/agent/commands.js
CHANGED
|
@@ -1344,7 +1344,7 @@ export async function handleSlashCommand(input, ctx) {
|
|
|
1344
1344
|
}
|
|
1345
1345
|
// Argument-based rewrite commands (prefix match)
|
|
1346
1346
|
for (const { prefix, rewrite } of ARG_COMMANDS) {
|
|
1347
|
-
if (input.startsWith(prefix)) {
|
|
1347
|
+
if (input.startsWith(prefix) && (prefix.endsWith(' ') || input === prefix)) {
|
|
1348
1348
|
const arg = input.slice(prefix.length).trim();
|
|
1349
1349
|
return { handled: false, rewritten: rewrite(arg) };
|
|
1350
1350
|
}
|
|
@@ -54,6 +54,7 @@ export declare function evaluatorModel(): string;
|
|
|
54
54
|
export declare function checkGrounding(userInput: string, history: Dialogue[], assistantText: string, client: ModelClient, opts?: {
|
|
55
55
|
abortSignal?: AbortSignal;
|
|
56
56
|
model?: string;
|
|
57
|
+
userImageCount?: number;
|
|
57
58
|
}): Promise<GroundingResult>;
|
|
58
59
|
/**
|
|
59
60
|
* Convert a grounding result into a user-facing follow-up message. Returns
|
package/dist/agent/evaluator.js
CHANGED
|
@@ -39,7 +39,10 @@ const EVALUATOR_PROMPT = `You are a GROUNDING CHECK agent. Your job is to verify
|
|
|
39
39
|
### A. Ungrounded claims
|
|
40
40
|
Every **factual claim** in the answer must trace to ONE of:
|
|
41
41
|
(a) A tool call result from this turn (model-initiated OR listed under "Pre-fetched by Franklin harness"), OR
|
|
42
|
-
(b)
|
|
42
|
+
(b) User-provided material, including observations of an attached image when the summary confirms an image was supplied, OR
|
|
43
|
+
(c) Explicit acknowledgment of uncertainty ("I'm not sure", "based on older data")
|
|
44
|
+
|
|
45
|
+
**User-provided images are evidence for visual observations.** The main assistant can see attached images directly; a Read or web tool is not required to transcribe visible text or describe shapes. When the summary confirms user-provided images, do not flag those observations merely because no tool ran. This text-only check cannot verify their visual accuracy: use PARTIAL if that is the only uncertainty, not a demand for a tool call. Images do NOT establish fresh external facts: claims about live prices, latest news, or facts beyond the supplied image still require appropriate evidence.
|
|
43
46
|
|
|
44
47
|
**Harness-prefetched data is evidence.** When the turn includes a "Pre-fetched by Franklin harness" section, the data listed there was fetched live from tools on the assistant's behalf (TradingMarket, ExaAnswer, etc). Treat it identically to a model-initiated tool call — claims that reference prefetched prices, numbers, or news snippets are GROUNDED.
|
|
45
48
|
|
|
@@ -141,11 +144,16 @@ export function shouldCheckGrounding(userInput, assistantText) {
|
|
|
141
144
|
* + tool result snippets + assistant's final answer. Bounded to keep the
|
|
142
145
|
* evaluator call cheap; it doesn't need every byte of every tool output.
|
|
143
146
|
*/
|
|
144
|
-
function summarizeTurn(userInput, history, assistantText) {
|
|
147
|
+
function summarizeTurn(userInput, history, assistantText, userImageCount = 0) {
|
|
145
148
|
const lines = [];
|
|
146
149
|
lines.push(`## User question`);
|
|
147
150
|
lines.push(userInput.trim().slice(0, 800));
|
|
148
151
|
lines.push('');
|
|
152
|
+
if (userImageCount > 0) {
|
|
153
|
+
lines.push(`## User-provided images: ${userImageCount}`);
|
|
154
|
+
lines.push('The assistant received these images directly in this turn. Visual observations and transcription can use them as evidence without a tool call. Image bytes are omitted from this text-only check.');
|
|
155
|
+
lines.push('');
|
|
156
|
+
}
|
|
149
157
|
// ── Harness prefetch (treated as synthetic tool calls) ──
|
|
150
158
|
// When intent-prefetch fires, it prepends a [FRANKLIN HARNESS PREFETCH]
|
|
151
159
|
// block to the user message. The LLM answers based on that data, but
|
|
@@ -166,7 +174,7 @@ function summarizeTurn(userInput, history, assistantText) {
|
|
|
166
174
|
const toolLines = [];
|
|
167
175
|
for (let i = history.length - 1; i >= 0 && found < 40; i--) {
|
|
168
176
|
const msg = history[i];
|
|
169
|
-
if (msg.role === 'user' && typeof msg.content === 'string')
|
|
177
|
+
if (msg.role === 'user' && (typeof msg.content === 'string' || !msg.content.some(part => part.type === 'tool_result')))
|
|
170
178
|
break;
|
|
171
179
|
if (msg.role === 'assistant' && Array.isArray(msg.content)) {
|
|
172
180
|
for (const part of msg.content) {
|
|
@@ -257,7 +265,7 @@ const MAX_EVAL_TOKENS = 512;
|
|
|
257
265
|
const EVAL_TIMEOUT_MS = 15_000;
|
|
258
266
|
export async function checkGrounding(userInput, history, assistantText, client, opts = {}) {
|
|
259
267
|
const model = opts.model || evaluatorModel();
|
|
260
|
-
const summary = summarizeTurn(userInput, history, assistantText);
|
|
268
|
+
const summary = summarizeTurn(userInput, history, assistantText, opts.userImageCount);
|
|
261
269
|
// Run independently of the main agent — the evaluator gets NO tools
|
|
262
270
|
// (it just reads and grades). Limit tokens so a chatty evaluator can't
|
|
263
271
|
// balloon the cost of a cheap check.
|
|
@@ -13,9 +13,10 @@
|
|
|
13
13
|
* user input keeps waiting and is delivered at the next boundary. The
|
|
14
14
|
* user's typing is never dropped.
|
|
15
15
|
*/
|
|
16
|
+
import type { AgentInput } from './types.js';
|
|
16
17
|
export interface InputMultiplexer {
|
|
17
18
|
/** Drop-in replacement for the driver's getUserInput. */
|
|
18
|
-
getUserInput: () => Promise<
|
|
19
|
+
getUserInput: () => Promise<AgentInput | null>;
|
|
19
20
|
/** Queue a synthetic input for the next turn boundary. */
|
|
20
21
|
enqueue: (text: string, opts?: {
|
|
21
22
|
priority?: boolean;
|
|
@@ -23,4 +24,4 @@ export interface InputMultiplexer {
|
|
|
23
24
|
/** Number of injected inputs currently waiting. */
|
|
24
25
|
pending: () => number;
|
|
25
26
|
}
|
|
26
|
-
export declare function createInputMultiplexer(base: () => Promise<
|
|
27
|
+
export declare function createInputMultiplexer(base: () => Promise<AgentInput | null>): InputMultiplexer;
|
package/dist/agent/loop.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Franklin Agent Loop
|
|
3
3
|
* The core reasoning-action cycle: prompt → model → extract capabilities → execute → repeat.
|
|
4
4
|
*/
|
|
5
|
-
import type { AgentConfig, ContentPart, Dialogue, StreamEvent } from './types.js';
|
|
5
|
+
import type { AgentConfig, ContentPart, Dialogue, StreamEvent, AgentInput } from './types.js';
|
|
6
6
|
export declare function isExternalWallFailure(toolName: string, output: string, isError?: boolean): boolean;
|
|
7
7
|
/**
|
|
8
8
|
* Detect when the gateway leaked an upstream rate-limit / quota error as a
|
|
@@ -60,4 +60,4 @@ export declare function isWeakModel(model: string): boolean;
|
|
|
60
60
|
* Each user message triggers a full agent loop.
|
|
61
61
|
* Returns the accumulated conversation history.
|
|
62
62
|
*/
|
|
63
|
-
export declare function interactiveSession(config: AgentConfig, getUserInput: () => Promise<
|
|
63
|
+
export declare function interactiveSession(config: AgentConfig, getUserInput: () => Promise<AgentInput | null>, onEvent: (event: StreamEvent) => void, onAbortReady?: (abort: () => void) => void): Promise<Dialogue[]>;
|
package/dist/agent/loop.js
CHANGED
|
@@ -418,6 +418,22 @@ export function stripLargeImageData(message) {
|
|
|
418
418
|
// in via the loop's outcome-building path. Runtime structure is what
|
|
419
419
|
// matters here; we only mutate when we positively identify the shape.
|
|
420
420
|
const newContent = message.content.map((part) => {
|
|
421
|
+
// Images the user attached directly (Desktop paste / file picker) sit at
|
|
422
|
+
// the top level of the user message, not inside a tool_result. They have
|
|
423
|
+
// no source path to re-Read, so the placeholder asks for a re-attach.
|
|
424
|
+
if (typeof part === 'object' &&
|
|
425
|
+
part !== null &&
|
|
426
|
+
part.type === 'image' &&
|
|
427
|
+
part.source?.type === 'base64' &&
|
|
428
|
+
(part.source.data?.length ?? 0) > SESSION_IMAGE_STRIP_THRESHOLD) {
|
|
429
|
+
mutated = true;
|
|
430
|
+
const sz = part.source.data.length;
|
|
431
|
+
return {
|
|
432
|
+
type: 'text',
|
|
433
|
+
text: `<user-attached image stripped from session log: ${(sz / 1024).toFixed(1)} KB base64. ` +
|
|
434
|
+
`Ask the user to attach it again if you need to see it.>`,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
421
437
|
if (typeof part === 'object' &&
|
|
422
438
|
part !== null &&
|
|
423
439
|
part.type === 'tool_result' &&
|
|
@@ -599,6 +615,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
599
615
|
const inputMux = createInputMultiplexer(getUserInput);
|
|
600
616
|
const history = [];
|
|
601
617
|
let lastUserInput = ''; // For /retry
|
|
618
|
+
let lastUserImages = [];
|
|
602
619
|
// budget-cap-usd of the skill that kicked off this turn (`/name` invocation);
|
|
603
620
|
// kept across /retry, which replays the same skill prompt.
|
|
604
621
|
let turnSkillBudgetUsd;
|
|
@@ -616,7 +633,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
616
633
|
onEvent({ kind: 'text_delta', text: `[skills] ${err.path}: ${err.error}\n` });
|
|
617
634
|
}
|
|
618
635
|
}
|
|
619
|
-
|
|
636
|
+
let skillRegistry = skillBoot.registry;
|
|
620
637
|
// Track models that failed with 402 (payment required) across turns.
|
|
621
638
|
// These persist until the session ends — unlike transient errors, payment failures
|
|
622
639
|
// will keep failing until the user adds funds. Map stores failure timestamp for future TTL.
|
|
@@ -795,11 +812,15 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
795
812
|
process.once('SIGINT', exitFlush);
|
|
796
813
|
process.once('SIGTERM', exitFlush);
|
|
797
814
|
while (true) {
|
|
798
|
-
|
|
799
|
-
if (
|
|
815
|
+
const incoming = await inputMux.getUserInput();
|
|
816
|
+
if (incoming === null)
|
|
800
817
|
break; // User wants to exit
|
|
818
|
+
let input = typeof incoming === 'string' ? incoming : incoming.text;
|
|
819
|
+
let images = typeof incoming === 'string' ? [] : incoming.images;
|
|
801
820
|
if (input === '')
|
|
802
821
|
continue; // Empty input → re-prompt
|
|
822
|
+
// Desktop imports and toggles take effect without restarting this session.
|
|
823
|
+
skillRegistry = loadAllSkills(workDir).registry;
|
|
803
824
|
// ── Slash command dispatch ──
|
|
804
825
|
if (!input.startsWith('/'))
|
|
805
826
|
turnSkillBudgetUsd = undefined;
|
|
@@ -816,6 +837,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
816
837
|
continue;
|
|
817
838
|
}
|
|
818
839
|
input = lastUserInput;
|
|
840
|
+
images = lastUserImages;
|
|
819
841
|
}
|
|
820
842
|
else {
|
|
821
843
|
const cmdResult = await handleSlashCommand(input, {
|
|
@@ -847,6 +869,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
847
869
|
input = redactedText;
|
|
848
870
|
}
|
|
849
871
|
lastUserInput = input;
|
|
872
|
+
lastUserImages = images;
|
|
850
873
|
fireLifecycleHook('UserPromptSubmit');
|
|
851
874
|
// ── Skill trigger auto-invoke ──
|
|
852
875
|
// Match the user message against every skill's `triggers:` list. Strong
|
|
@@ -891,11 +914,14 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
891
914
|
// (pushback SYSTEM NOTE, prefetch context block) are applied AFTER
|
|
892
915
|
// the turn analyzer runs so they get driven by model-decided flags
|
|
893
916
|
// instead of keyword regex.
|
|
894
|
-
|
|
917
|
+
const userContent = images.length
|
|
918
|
+
? [{ type: 'text', text: input }, ...images]
|
|
919
|
+
: input;
|
|
920
|
+
history.push({ role: 'user', content: userContent });
|
|
895
921
|
turnCount++;
|
|
896
922
|
toolGuard.startTurn();
|
|
897
923
|
publishLiveState('working');
|
|
898
|
-
persistSessionMessage({ role: 'user', content:
|
|
924
|
+
persistSessionMessage({ role: 'user', content: userContent });
|
|
899
925
|
// ── Model recovery: try original model at the start of each new turn ──
|
|
900
926
|
// If we fell back to a free model last turn due to a transient error, try original again.
|
|
901
927
|
// But DON'T reset if the original model had a payment failure — it will just fail again.
|
|
@@ -1397,7 +1423,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
1397
1423
|
// images, Read's tool_result image blocks get tokenized as base64 text
|
|
1398
1424
|
// by the gateway (verified 2026-05-09) and the model hallucinates from
|
|
1399
1425
|
// the "Image file: <path>" stub. Detect upfront, route accordingly.
|
|
1400
|
-
const turnNeedsVision = loopCount === 1 && messageNeedsVision(lastUserInput);
|
|
1426
|
+
const turnNeedsVision = loopCount === 1 && (images.length > 0 || messageNeedsVision(lastUserInput));
|
|
1401
1427
|
// ── Router: resolve routing profiles to concrete models ──
|
|
1402
1428
|
// The shared Router is local/deterministic and runs once per user turn.
|
|
1403
1429
|
// The turn analyzer remains useful for planning and pushback, but no
|
|
@@ -2413,6 +2439,7 @@ async function runInteractiveSession(config, getUserInput, onEvent, onAbortReady
|
|
|
2413
2439
|
if (!config.disableGroundingRetry && shouldCheckGrounding(lastUserInput || '', assistantText)) {
|
|
2414
2440
|
const gResult = await checkGrounding(lastUserInput, history, assistantText, client, {
|
|
2415
2441
|
abortSignal: abort.signal,
|
|
2442
|
+
userImageCount: images.length,
|
|
2416
2443
|
});
|
|
2417
2444
|
if (gResult.verdict === 'UNGROUNDED' && groundingRetryCount < MAX_GROUNDING_RETRIES) {
|
|
2418
2445
|
groundingRetryCount++;
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -37,7 +37,12 @@ export interface CapabilityOutcome {
|
|
|
37
37
|
is_error?: boolean;
|
|
38
38
|
}
|
|
39
39
|
export type ContentPart = TextSegment | CapabilityInvocation | ThinkingSegment;
|
|
40
|
-
export type UserContentPart = TextSegment | CapabilityOutcome;
|
|
40
|
+
export type UserContentPart = TextSegment | ImageSegment | CapabilityOutcome;
|
|
41
|
+
/** Structured driver input; CLI and scheduled prompts can remain plain text. */
|
|
42
|
+
export type AgentInput = string | {
|
|
43
|
+
text: string;
|
|
44
|
+
images: ImageSegment[];
|
|
45
|
+
};
|
|
41
46
|
export interface Dialogue {
|
|
42
47
|
role: Role;
|
|
43
48
|
content: ContentPart[] | UserContentPart[] | string;
|
package/dist/panel/html.js
CHANGED
|
@@ -917,6 +917,8 @@ 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;
|
|
920
922
|
const nativeFetch = window.fetch.bind(window);
|
|
921
923
|
window.fetch = (input, init = {}) => {
|
|
922
924
|
const headers = new Headers(init.headers || {});
|
|
@@ -1425,7 +1427,7 @@ document.getElementById('wallet-import-btn').addEventListener('click', async ()
|
|
|
1425
1427
|
}
|
|
1426
1428
|
});
|
|
1427
1429
|
|
|
1428
|
-
const es = new EventSource('/api/events');
|
|
1430
|
+
const es = new EventSource('/api/events?token=' + encodeURIComponent(window.__FRANKLIN_PANEL_TOKEN));
|
|
1429
1431
|
const dot = document.getElementById('dot');
|
|
1430
1432
|
const statusEl = document.getElementById('status');
|
|
1431
1433
|
es.onopen = () => { dot.className = 'dot on'; statusEl.textContent = 'live'; };
|
package/dist/panel/server.js
CHANGED
|
@@ -21,6 +21,7 @@ import { describeWiring } from '../trading/providers/registry.js';
|
|
|
21
21
|
import { listTasks, readTaskMeta, readTaskEvents, } from '../tasks/store.js';
|
|
22
22
|
import { reconcileLostTasks } from '../tasks/lost-detection.js';
|
|
23
23
|
import { taskLogPath } from '../tasks/paths.js';
|
|
24
|
+
import { isSafePathSegment } from '../storage/safe-id.js';
|
|
24
25
|
import { isTerminalTaskStatus } from '../tasks/types.js';
|
|
25
26
|
import { readLiveAgents } from '../session/live-registry.js';
|
|
26
27
|
import { BLOCKRUN_DIR } from '../config.js';
|
|
@@ -95,12 +96,14 @@ function isLocalHostHeader(req) {
|
|
|
95
96
|
*/
|
|
96
97
|
const PANEL_TOKEN = crypto.randomBytes(32).toString('hex');
|
|
97
98
|
const PANEL_TOKEN_HEADER = 'x-franklin-panel-token';
|
|
98
|
-
function
|
|
99
|
-
const got = req.headers[PANEL_TOKEN_HEADER];
|
|
99
|
+
function tokenMatches(got) {
|
|
100
100
|
if (typeof got !== 'string' || got.length !== PANEL_TOKEN.length)
|
|
101
101
|
return false;
|
|
102
102
|
return crypto.timingSafeEqual(Buffer.from(got), Buffer.from(PANEL_TOKEN));
|
|
103
103
|
}
|
|
104
|
+
function hasPanelToken(req) {
|
|
105
|
+
return tokenMatches(req.headers[PANEL_TOKEN_HEADER]);
|
|
106
|
+
}
|
|
104
107
|
function isLocalPanelRequest(req) {
|
|
105
108
|
return isLoopback(req) && isTrustedPanelOrigin(req) && hasPanelToken(req);
|
|
106
109
|
}
|
|
@@ -166,6 +169,17 @@ export function createPanelServer(port) {
|
|
|
166
169
|
res.end('Forbidden');
|
|
167
170
|
return;
|
|
168
171
|
}
|
|
172
|
+
// Every API route needs the page's token, read-only ones included.
|
|
173
|
+
// Loopback + local Host does not tell OS users apart: on a shared machine
|
|
174
|
+
// another account, or anyone reaching the port through an ssh -L tunnel,
|
|
175
|
+
// passes both and could read transcripts and the audit log
|
|
176
|
+
// (GHSA-jx74-262x-94p3). EventSource cannot set headers, so /api/events
|
|
177
|
+
// alone may carry the token as ?token=.
|
|
178
|
+
if (p.startsWith('/api/') && !hasPanelToken(req)
|
|
179
|
+
&& !(p === '/api/events' && tokenMatches(url.searchParams.get('token')))) {
|
|
180
|
+
json(res, { error: 'forbidden' }, 403);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
169
183
|
// Anything that changes state needs the page's token, including routes
|
|
170
184
|
// that only check loopback (task cancel).
|
|
171
185
|
if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS' && !hasPanelToken(req)) {
|
|
@@ -768,9 +782,14 @@ export function createPanelServer(port) {
|
|
|
768
782
|
if (p.startsWith('/api/tasks/')) {
|
|
769
783
|
const rest = p.slice('/api/tasks/'.length);
|
|
770
784
|
const segments = rest.split('/');
|
|
771
|
-
|
|
785
|
+
let runId = '';
|
|
786
|
+
try {
|
|
787
|
+
runId = decodeURIComponent(segments[0] || '');
|
|
788
|
+
}
|
|
789
|
+
catch { /* malformed %-escape */ }
|
|
772
790
|
const sub = segments[1];
|
|
773
|
-
|
|
791
|
+
// getTaskDir also refuses these; answer 404 here instead of a 500.
|
|
792
|
+
if (!isSafePathSegment(runId)) {
|
|
774
793
|
res.writeHead(404);
|
|
775
794
|
res.end('Not found');
|
|
776
795
|
return;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AgentInput } from '../agent/types.js';
|
|
2
|
+
/** Accept only inline image bytes. Never turn a renderer-supplied path into a
|
|
3
|
+
* server-side file read or URL fetch. Keep image data out of the text prompt. */
|
|
4
|
+
export declare function desktopInput(text: unknown, attachments: unknown): AgentInput;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const MAX_IMAGE_BYTES = 4_000_000;
|
|
2
|
+
const MAX_DATA_URL_LENGTH = Math.ceil(MAX_IMAGE_BYTES / 3) * 4 + 64;
|
|
3
|
+
/** Accept only inline image bytes. Never turn a renderer-supplied path into a
|
|
4
|
+
* server-side file read or URL fetch. Keep image data out of the text prompt. */
|
|
5
|
+
export function desktopInput(text, attachments) {
|
|
6
|
+
const prompt = typeof text === 'string' ? text.trim() : '';
|
|
7
|
+
if (attachments === undefined || (Array.isArray(attachments) && attachments.length === 0)) {
|
|
8
|
+
if (!prompt)
|
|
9
|
+
throw new Error('empty input');
|
|
10
|
+
return prompt;
|
|
11
|
+
}
|
|
12
|
+
if (!Array.isArray(attachments) || attachments.length !== 1) {
|
|
13
|
+
throw new Error('Attach one image per message.');
|
|
14
|
+
}
|
|
15
|
+
const value = attachments[0]?.path;
|
|
16
|
+
if (typeof value !== 'string' || value.length > MAX_DATA_URL_LENGTH)
|
|
17
|
+
throw new Error('Image attachment exceeds the 4 MB limit.');
|
|
18
|
+
const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/.exec(value);
|
|
19
|
+
if (!match)
|
|
20
|
+
throw new Error('Attach a PNG, JPEG, WebP or GIF image.');
|
|
21
|
+
const [, mediaType, data] = match;
|
|
22
|
+
const bytes = Buffer.from(data, 'base64');
|
|
23
|
+
if (bytes.length > MAX_IMAGE_BYTES || bytes.toString('base64') !== data)
|
|
24
|
+
throw new Error('Invalid or oversized image attachment.');
|
|
25
|
+
const valid = mediaType === 'image/png' ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
|
|
26
|
+
: mediaType === 'image/jpeg' ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255
|
|
27
|
+
: mediaType === 'image/webp' ? bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'
|
|
28
|
+
: /^GIF8[79]a$/.test(bytes.toString('ascii', 0, 6));
|
|
29
|
+
if (!valid)
|
|
30
|
+
throw new Error('Image attachment does not match its declared format.');
|
|
31
|
+
const image = { type: 'image', source: { type: 'base64', media_type: mediaType, data } };
|
|
32
|
+
return { text: prompt || 'Describe the attached image.', images: [image] };
|
|
33
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Free-text questions have their own protocol; answers never grant tool permissions. */
|
|
2
|
+
export declare class DesktopQuestions<Owner> {
|
|
3
|
+
private timeoutMs;
|
|
4
|
+
private sequence;
|
|
5
|
+
private pending;
|
|
6
|
+
constructor(timeoutMs?: number);
|
|
7
|
+
request(owner: Owner, question: string, options: string[] | undefined, emit: (kind: 'agent.questionAsk' | 'agent.questionClosed', payload: object) => void): Promise<string>;
|
|
8
|
+
respond(owner: Owner, askId: unknown, answer: unknown): boolean;
|
|
9
|
+
cancel(owner: Owner): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Free-text questions have their own protocol; answers never grant tool permissions. */
|
|
2
|
+
export class DesktopQuestions {
|
|
3
|
+
timeoutMs;
|
|
4
|
+
sequence = 0;
|
|
5
|
+
pending = new Map();
|
|
6
|
+
constructor(timeoutMs = 15 * 60 * 1000) {
|
|
7
|
+
this.timeoutMs = timeoutMs;
|
|
8
|
+
}
|
|
9
|
+
request(owner, question, options, emit) {
|
|
10
|
+
const askId = `question_${++this.sequence}`;
|
|
11
|
+
return new Promise(resolve => {
|
|
12
|
+
const finish = (answer) => {
|
|
13
|
+
if (!this.pending.delete(askId))
|
|
14
|
+
return;
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
emit('agent.questionClosed', { askId });
|
|
17
|
+
resolve(answer);
|
|
18
|
+
};
|
|
19
|
+
const timer = setTimeout(() => finish(''), this.timeoutMs);
|
|
20
|
+
timer.unref?.();
|
|
21
|
+
this.pending.set(askId, { owner, finish });
|
|
22
|
+
emit('agent.questionAsk', { askId, question, options: options ?? [] });
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
respond(owner, askId, answer) {
|
|
26
|
+
if (typeof askId !== 'string' || typeof answer !== 'string' || answer.length > 16_000)
|
|
27
|
+
return false;
|
|
28
|
+
const request = this.pending.get(askId);
|
|
29
|
+
if (!request || request.owner !== owner)
|
|
30
|
+
return false;
|
|
31
|
+
request.finish(answer);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
cancel(owner) {
|
|
35
|
+
for (const request of [...this.pending.values()]) {
|
|
36
|
+
if (request.owner === owner)
|
|
37
|
+
request.finish('');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
package/dist/serve/server.js
CHANGED
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* fed by a getUserInput queue. Good enough for the desktop app; multi-session
|
|
17
17
|
* fan-out can come later.
|
|
18
18
|
*/
|
|
19
|
+
import { desktopInput } from './desktop-input.js';
|
|
20
|
+
import { listManagedSkills, importSkill, toggleSkill, removeSkill, resolveManagedSkill } from '../skills/management.js';
|
|
19
21
|
import http from 'node:http';
|
|
20
22
|
import crypto from 'node:crypto';
|
|
21
23
|
import fs from 'node:fs';
|
|
@@ -38,6 +40,7 @@ import { isCloudSyncEnabled, cloudList, cloudSync } from './cloud-sync.js';
|
|
|
38
40
|
import { setupAgentWallet, setupAgentSolanaWallet } from '@blockrun/llm';
|
|
39
41
|
import { retryFetchBalance } from '../commands/balance-retry.js';
|
|
40
42
|
import { AgentHost } from './agent-host.js';
|
|
43
|
+
import { DesktopQuestions } from './desktop-questions.js';
|
|
41
44
|
import { bus } from '../events/bus.js';
|
|
42
45
|
import { FREE_DEFAULT_MODEL } from '../free-models.js';
|
|
43
46
|
import { readEvmBalance } from '../wallet/manager.js';
|
|
@@ -439,6 +442,7 @@ export async function startServer(opts) {
|
|
|
439
442
|
// Pending approval asks for the legacy desktop session (tools + trade plans).
|
|
440
443
|
// Keyed by askId — the wire contract the desktop UI already declares
|
|
441
444
|
// (agent.permissionAsk / agent.permissionResponse with askId + decision).
|
|
445
|
+
const questions = new DesktopQuestions();
|
|
442
446
|
let askSeq = 0;
|
|
443
447
|
const legacyAsks = new Map();
|
|
444
448
|
const requestDesktopPermission = (toolName, description, timeoutMs = 15 * 60 * 1000) => new Promise((resolve) => {
|
|
@@ -601,6 +605,8 @@ export async function startServer(opts) {
|
|
|
601
605
|
break;
|
|
602
606
|
}
|
|
603
607
|
case 'turn_done':
|
|
608
|
+
if (activeWs)
|
|
609
|
+
questions.cancel(activeWs);
|
|
604
610
|
if (event.reason === 'completed') {
|
|
605
611
|
emit('agent.done', { sessionId: '', costUsd: 0 });
|
|
606
612
|
}
|
|
@@ -653,13 +659,12 @@ export async function startServer(opts) {
|
|
|
653
659
|
allowPaidPrefetch: !desktopBoundary,
|
|
654
660
|
...(desktopBoundary ? { maxSpendUsd: 5 } : {}),
|
|
655
661
|
costSaver,
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
return options?.[options.length - 1] ?? 'no';
|
|
662
|
+
onAskUser: (question, options) => {
|
|
663
|
+
const ws = activeWs;
|
|
664
|
+
const turnId = activeTurnId;
|
|
665
|
+
if (!ws || !turnId)
|
|
666
|
+
return Promise.resolve('');
|
|
667
|
+
return questions.request(ws, question, options, (kind, payload) => send(ws, turnId, kind, payload));
|
|
663
668
|
},
|
|
664
669
|
// Structured approvals (trade plans): surfaced to the desktop over the
|
|
665
670
|
// in-flight turn stream as agent.permissionAsk; the UI answers with
|
|
@@ -687,6 +692,27 @@ export async function startServer(opts) {
|
|
|
687
692
|
const { id, kind, payload } = msg;
|
|
688
693
|
const p = (payload ?? {});
|
|
689
694
|
switch (kind) {
|
|
695
|
+
case 'skills.list':
|
|
696
|
+
case 'skills.upload':
|
|
697
|
+
case 'skills.toggle':
|
|
698
|
+
case 'skills.remove':
|
|
699
|
+
case 'skills.resolve': {
|
|
700
|
+
try {
|
|
701
|
+
const result = kind === 'skills.list' ? listManagedSkills(workDir)
|
|
702
|
+
: kind === 'skills.upload' ? importSkill(workDir, p.content)
|
|
703
|
+
: kind === 'skills.toggle' ? toggleSkill(workDir, p.name, p.enabled)
|
|
704
|
+
: kind === 'skills.remove' ? removeSkill(workDir, p.name)
|
|
705
|
+
: resolveManagedSkill(workDir, p.input);
|
|
706
|
+
send(ws, id, 'response', result);
|
|
707
|
+
}
|
|
708
|
+
catch (err) {
|
|
709
|
+
send(ws, id, 'error', { message: err instanceof Error ? err.message : 'Skill management failed' });
|
|
710
|
+
}
|
|
711
|
+
break;
|
|
712
|
+
}
|
|
713
|
+
case 'skills.create':
|
|
714
|
+
send(ws, id, 'error', { message: 'Automatic skill generation is not available. Import a SKILL.md from Skills instead.' });
|
|
715
|
+
break;
|
|
690
716
|
case 'session.list': {
|
|
691
717
|
const metas = listSessions();
|
|
692
718
|
send(ws, id, 'response', {
|
|
@@ -857,9 +883,12 @@ export async function startServer(opts) {
|
|
|
857
883
|
break;
|
|
858
884
|
}
|
|
859
885
|
case 'agent.send': {
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
886
|
+
let input;
|
|
887
|
+
try {
|
|
888
|
+
input = desktopInput(p.text, p.attachments);
|
|
889
|
+
}
|
|
890
|
+
catch (error) {
|
|
891
|
+
send(ws, id, 'agent.error', { sessionId: '', message: error instanceof Error ? error.message : 'Invalid attachment' });
|
|
863
892
|
break;
|
|
864
893
|
}
|
|
865
894
|
activeWs = ws;
|
|
@@ -886,7 +915,7 @@ export async function startServer(opts) {
|
|
|
886
915
|
pushInput(`/model ${desiredModel}`);
|
|
887
916
|
currentModel = desiredModel;
|
|
888
917
|
}
|
|
889
|
-
pushInput(
|
|
918
|
+
pushInput(input);
|
|
890
919
|
break;
|
|
891
920
|
}
|
|
892
921
|
case 'settings.get':
|
|
@@ -903,8 +932,14 @@ export async function startServer(opts) {
|
|
|
903
932
|
break;
|
|
904
933
|
}
|
|
905
934
|
case 'agent.cancel':
|
|
906
|
-
if (
|
|
907
|
-
abortFn
|
|
935
|
+
if (ws === activeWs) {
|
|
936
|
+
if (abortFn)
|
|
937
|
+
abortFn();
|
|
938
|
+
questions.cancel(ws);
|
|
939
|
+
}
|
|
940
|
+
break;
|
|
941
|
+
case 'agent.questionResponse':
|
|
942
|
+
send(ws, id, 'response', { ok: questions.respond(ws, p.askId, p.answer) });
|
|
908
943
|
break;
|
|
909
944
|
case 'agent.permissionResponse': {
|
|
910
945
|
// Two resolution paths:
|
|
@@ -1082,6 +1117,7 @@ export async function startServer(opts) {
|
|
|
1082
1117
|
});
|
|
1083
1118
|
});
|
|
1084
1119
|
ws.on('close', () => {
|
|
1120
|
+
questions.cancel(ws);
|
|
1085
1121
|
// Tear down this socket's agent subscriptions; the agents keep running.
|
|
1086
1122
|
const subs = wsSubs.get(ws);
|
|
1087
1123
|
if (subs)
|
package/dist/session/storage.js
CHANGED
|
@@ -7,6 +7,7 @@ import os from 'node:os';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { randomUUID } from 'node:crypto';
|
|
9
9
|
import { BLOCKRUN_DIR } from '../config.js';
|
|
10
|
+
import { assertSafePathSegment } from '../storage/safe-id.js';
|
|
10
11
|
const MAX_SESSIONS = 20; // Keep last 20 sessions
|
|
11
12
|
let resolvedSessionsDir = null;
|
|
12
13
|
// When in-process tests run interactiveSession() with model="local/test*",
|
|
@@ -55,9 +56,7 @@ function getSessionsDir() {
|
|
|
55
56
|
}
|
|
56
57
|
function sessionPath(id) {
|
|
57
58
|
// Ids reach here from URLs (panel /api/sessions/:id); never let one escape the sessions dir.
|
|
58
|
-
|
|
59
|
-
throw new Error(`Invalid session id: ${JSON.stringify(id)}`);
|
|
60
|
-
}
|
|
59
|
+
assertSafePathSegment(id, 'session id');
|
|
61
60
|
return path.join(getSessionsDir(), `${id}.jsonl`);
|
|
62
61
|
}
|
|
63
62
|
/** Get the absolute path to a session's JSONL file (for external readers like search). */
|
|
@@ -65,6 +64,7 @@ export function getSessionFilePath(id) {
|
|
|
65
64
|
return sessionPath(id);
|
|
66
65
|
}
|
|
67
66
|
function metaPath(id) {
|
|
67
|
+
assertSafePathSegment(id, 'session id');
|
|
68
68
|
return path.join(getSessionsDir(), `${id}.meta.json`);
|
|
69
69
|
}
|
|
70
70
|
function withWritableSessionDir(action) {
|
|
@@ -40,7 +40,9 @@ export declare function loadBundledSkills(): BundledLoad;
|
|
|
40
40
|
* unioned; the Registry resolves name collisions by source precedence
|
|
41
41
|
* (project > user > learned > bundled).
|
|
42
42
|
*/
|
|
43
|
-
export declare function loadAllSkills(workDir: string
|
|
43
|
+
export declare function loadAllSkills(workDir: string, options?: {
|
|
44
|
+
includeDisabled?: boolean;
|
|
45
|
+
}): AllSkillsLoad;
|
|
44
46
|
/** Ensure the user-global skills root exists so `~/.blockrun/skills/<name>/`
|
|
45
47
|
* edits don't fail with ENOENT. Idempotent. */
|
|
46
48
|
export declare function ensureUserSkillsDir(): string;
|
package/dist/skills/bootstrap.js
CHANGED
|
@@ -25,6 +25,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
25
25
|
import { dirname, join } from 'node:path';
|
|
26
26
|
import { existsSync, mkdirSync } from 'node:fs';
|
|
27
27
|
import { loadSkillsFromDir } from './loader.js';
|
|
28
|
+
import { disabledSkills } from './state.js';
|
|
28
29
|
import { Registry } from './registry.js';
|
|
29
30
|
import { BLOCKRUN_DIR } from '../config.js';
|
|
30
31
|
import { migrateLegacyLearnedSkills } from '../learnings/store.js';
|
|
@@ -51,7 +52,7 @@ export function loadBundledSkills() {
|
|
|
51
52
|
* unioned; the Registry resolves name collisions by source precedence
|
|
52
53
|
* (project > user > learned > bundled).
|
|
53
54
|
*/
|
|
54
|
-
export function loadAllSkills(workDir) {
|
|
55
|
+
export function loadAllSkills(workDir, options = {}) {
|
|
55
56
|
const errors = [];
|
|
56
57
|
const all = [];
|
|
57
58
|
const counts = {};
|
|
@@ -85,7 +86,8 @@ export function loadAllSkills(workDir) {
|
|
|
85
86
|
errors.push(...result.errors);
|
|
86
87
|
counts[source] = (counts[source] ?? 0) + result.skills.length;
|
|
87
88
|
}
|
|
88
|
-
|
|
89
|
+
const disabled = options.includeDisabled ? new Set() : disabledSkills();
|
|
90
|
+
return { registry: Registry.fromLoaded(all.filter((s) => !disabled.has(s.skill.name))), errors, counts };
|
|
89
91
|
}
|
|
90
92
|
/** Ensure the user-global skills root exists so `~/.blockrun/skills/<name>/`
|
|
91
93
|
* edits don't fail with ENOENT. Idempotent. */
|
package/dist/skills/invoke.js
CHANGED
|
@@ -33,6 +33,9 @@ export function matchSkill(input, registry, vars) {
|
|
|
33
33
|
if (!skill)
|
|
34
34
|
return null;
|
|
35
35
|
const args = space < 0 ? '' : input.slice(space + 1).trim();
|
|
36
|
-
const
|
|
36
|
+
const rendered = substituteVariables(skill.skill.body, vars, args);
|
|
37
|
+
// External SKILL.md files often omit Franklin's argument placeholder.
|
|
38
|
+
const rewritten = args && !skill.skill.body.includes('$ARGUMENTS')
|
|
39
|
+
? `${rendered}\n\nUser request:\n${args}` : rendered;
|
|
37
40
|
return { rewritten, skill: skill.skill };
|
|
38
41
|
}
|
package/dist/skills/loader.d.ts
CHANGED
|
@@ -1,12 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SKILL.md loader — parses Anthropic-spec frontmatter + markdown body.
|
|
3
|
-
*
|
|
4
|
-
* The frontmatter parser is intentionally minimal: flat `key: value` lines
|
|
5
|
-
* with scalar values (string, boolean, number). Quoted strings, nested
|
|
6
|
-
* objects, and arrays are out of scope for MVP — Anthropic's SKILL.md spec
|
|
7
|
-
* never needs them and adding a YAML dependency would be heavier than the
|
|
8
|
-
* spec warrants.
|
|
9
|
-
*/
|
|
1
|
+
/** SKILL.md frontmatter and Markdown loader. Metadata is data, never executable. */
|
|
10
2
|
import type { LoadResult, ParseResult, SkillSource } from './types.js';
|
|
11
3
|
export declare function parseSkill(content: string): ParseResult;
|
|
12
4
|
/**
|
package/dist/skills/loader.js
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SKILL.md loader — parses Anthropic-spec frontmatter + markdown body.
|
|
3
|
-
*
|
|
4
|
-
* The frontmatter parser is intentionally minimal: flat `key: value` lines
|
|
5
|
-
* with scalar values (string, boolean, number). Quoted strings, nested
|
|
6
|
-
* objects, and arrays are out of scope for MVP — Anthropic's SKILL.md spec
|
|
7
|
-
* never needs them and adding a YAML dependency would be heavier than the
|
|
8
|
-
* spec warrants.
|
|
9
|
-
*/
|
|
1
|
+
/** SKILL.md frontmatter and Markdown loader. Metadata is data, never executable. */
|
|
10
2
|
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
11
3
|
import { join } from 'node:path';
|
|
4
|
+
import { parseDocument } from 'yaml';
|
|
12
5
|
const FRONTMATTER_FENCE = '---';
|
|
13
6
|
export function parseSkill(content) {
|
|
14
7
|
const fmMatch = extractFrontmatter(content);
|
|
@@ -20,10 +13,10 @@ export function parseSkill(content) {
|
|
|
20
13
|
if ('error' in parsedFrontmatter)
|
|
21
14
|
return { error: parsedFrontmatter.error };
|
|
22
15
|
const { fields, warnings } = parsedFrontmatter;
|
|
23
|
-
if (typeof fields.name !== 'string' || fields.name.length === 0) {
|
|
16
|
+
if (typeof fields.name !== 'string' || fields.name.trim().length === 0) {
|
|
24
17
|
return { error: 'frontmatter missing required field: name' };
|
|
25
18
|
}
|
|
26
|
-
if (typeof fields.description !== 'string' || fields.description.length === 0) {
|
|
19
|
+
if (typeof fields.description !== 'string' || fields.description.trim().length === 0) {
|
|
27
20
|
return { error: 'frontmatter missing required field: description' };
|
|
28
21
|
}
|
|
29
22
|
const skill = {
|
|
@@ -61,7 +54,7 @@ export function parseSkill(content) {
|
|
|
61
54
|
return { skill, warnings };
|
|
62
55
|
}
|
|
63
56
|
function extractFrontmatter(content) {
|
|
64
|
-
const normalized = content.replace(/\r\n/g, '\n');
|
|
57
|
+
const normalized = content.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
|
|
65
58
|
if (!normalized.startsWith(FRONTMATTER_FENCE + '\n'))
|
|
66
59
|
return null;
|
|
67
60
|
const rest = normalized.slice(FRONTMATTER_FENCE.length + 1);
|
|
@@ -72,54 +65,19 @@ function extractFrontmatter(content) {
|
|
|
72
65
|
const body = rest.slice(closeIdx + 1 + FRONTMATTER_FENCE.length + 1);
|
|
73
66
|
return { frontmatter, body };
|
|
74
67
|
}
|
|
75
|
-
const LIST_ITEM_RE = /^\s+-\s+(.+)$/;
|
|
76
68
|
function parseFrontmatter(text) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (colon < 0) {
|
|
89
|
-
return { error: `frontmatter line ${i + 1} is not key: value — got "${line}"` };
|
|
90
|
-
}
|
|
91
|
-
const key = line.slice(0, colon).trim();
|
|
92
|
-
const rawValue = line.slice(colon + 1).trim();
|
|
93
|
-
if (key.length === 0) {
|
|
94
|
-
return { error: `frontmatter line ${i + 1} has empty key` };
|
|
95
|
-
}
|
|
96
|
-
// Empty value followed by indented `- item` lines = YAML list.
|
|
97
|
-
if (rawValue === '') {
|
|
98
|
-
const items = [];
|
|
99
|
-
let j = i + 1;
|
|
100
|
-
while (j < lines.length) {
|
|
101
|
-
const next = lines[j];
|
|
102
|
-
if (next.trim() === '') {
|
|
103
|
-
j++;
|
|
104
|
-
continue;
|
|
105
|
-
}
|
|
106
|
-
const m = LIST_ITEM_RE.exec(next);
|
|
107
|
-
if (!m)
|
|
108
|
-
break;
|
|
109
|
-
items.push(parseScalarString(m[1].trim()));
|
|
110
|
-
j++;
|
|
111
|
-
}
|
|
112
|
-
if (items.length > 0) {
|
|
113
|
-
fields[key] = items;
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
// No list followed; treat as empty string.
|
|
117
|
-
fields[key] = '';
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
fields[key] = parseScalar(rawValue);
|
|
69
|
+
try {
|
|
70
|
+
const doc = parseDocument(text, { schema: 'core', uniqueKeys: true });
|
|
71
|
+
if (doc.errors.length)
|
|
72
|
+
return { error: 'Invalid YAML frontmatter: ' + doc.errors[0].message.split('\n')[0] };
|
|
73
|
+
const fields = doc.toJS({ maxAliasCount: 0 });
|
|
74
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields))
|
|
75
|
+
return { error: 'Frontmatter must be a mapping' };
|
|
76
|
+
return { fields: fields, warnings: doc.warnings.map((w) => w.message.split('\n')[0]) };
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return { error: 'Invalid YAML frontmatter (aliases are not supported)' };
|
|
121
80
|
}
|
|
122
|
-
return { fields, warnings };
|
|
123
81
|
}
|
|
124
82
|
/**
|
|
125
83
|
* Discover and parse every `<dir>/<name>/SKILL.md` under `root`.
|
|
@@ -174,22 +132,3 @@ export function loadSkillsFromDir(root, source) {
|
|
|
174
132
|
}
|
|
175
133
|
return result;
|
|
176
134
|
}
|
|
177
|
-
function parseScalar(raw) {
|
|
178
|
-
if (raw === 'true')
|
|
179
|
-
return true;
|
|
180
|
-
if (raw === 'false')
|
|
181
|
-
return false;
|
|
182
|
-
if (/^-?\d+$/.test(raw))
|
|
183
|
-
return Number.parseInt(raw, 10);
|
|
184
|
-
if (/^-?\d+\.\d+$/.test(raw))
|
|
185
|
-
return Number.parseFloat(raw);
|
|
186
|
-
return parseScalarString(raw);
|
|
187
|
-
}
|
|
188
|
-
/** Strip surrounding quotes from a string-shaped value, leaving everything else as-is. */
|
|
189
|
-
function parseScalarString(raw) {
|
|
190
|
-
if ((raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) ||
|
|
191
|
-
(raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2)) {
|
|
192
|
-
return raw.slice(1, -1);
|
|
193
|
-
}
|
|
194
|
-
return raw;
|
|
195
|
-
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const MAX_SKILL_BYTES: number;
|
|
2
|
+
export declare function listManagedSkills(workDir: string): {
|
|
3
|
+
skills: {
|
|
4
|
+
name: string;
|
|
5
|
+
description: string;
|
|
6
|
+
source: import("./types.js").SkillSource;
|
|
7
|
+
hidden: boolean;
|
|
8
|
+
modelInvocable: boolean;
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
removable: boolean;
|
|
11
|
+
notes: string[];
|
|
12
|
+
}[];
|
|
13
|
+
errors: string[];
|
|
14
|
+
};
|
|
15
|
+
export declare function importSkill(workDir: string, content: unknown): {
|
|
16
|
+
name: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function toggleSkill(workDir: string, name: unknown, enabled: unknown): {
|
|
19
|
+
ok: boolean;
|
|
20
|
+
};
|
|
21
|
+
export declare function removeSkill(workDir: string, name: unknown): {
|
|
22
|
+
ok: boolean;
|
|
23
|
+
};
|
|
24
|
+
/** Same prompt resolver used by slash dispatch; does not call models or tools. */
|
|
25
|
+
export declare function resolveManagedSkill(workDir: string, input: unknown): {
|
|
26
|
+
name: string;
|
|
27
|
+
prompt: string;
|
|
28
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/** Local skill management. Importing instructions never executes their contents. */
|
|
2
|
+
import { lstatSync, mkdirSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
5
|
+
import { loadAllSkills } from './bootstrap.js';
|
|
6
|
+
import { parseSkill } from './loader.js';
|
|
7
|
+
import { matchSkill } from './invoke.js';
|
|
8
|
+
import { disabledSkills, setSkillEnabled } from './state.js';
|
|
9
|
+
export const MAX_SKILL_BYTES = 256 * 1024;
|
|
10
|
+
const root = join(BLOCKRUN_DIR, 'skills');
|
|
11
|
+
const reserved = new Set(('learned explain search find refactor scaffold doc moa noplan stash unstash log status diff undo tokens help history transcript bug version mcp context doctor plan ultrathink dump execute sessions cost clear failures compact commit push pr review fix test debug init todo deps optimize security lint migrate clean tasks ultraplan session-search ssearch goal remember flush dream loop market insights learnings brain auto model branch wallet delete resume retry exit').split(' '));
|
|
12
|
+
function validName(name) {
|
|
13
|
+
if (typeof name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name.length > 64)
|
|
14
|
+
throw new Error('Skill name must be lowercase letters, numbers and hyphens (up to 64 characters)');
|
|
15
|
+
}
|
|
16
|
+
function safeRoot() {
|
|
17
|
+
mkdirSync(root, { recursive: true });
|
|
18
|
+
if (!lstatSync(root).isDirectory() || lstatSync(root).isSymbolicLink())
|
|
19
|
+
throw new Error('Skills directory must not be a symlink');
|
|
20
|
+
}
|
|
21
|
+
function describe(entry, disabled) {
|
|
22
|
+
const localBody = entry.skill.body.replace(/https?:\/\/[^\s`"')\]]+/g, '');
|
|
23
|
+
const supportFiles = /(?:\b(?:python3?|node|bash|sh)\s+[^\n`]*\.(?:py|m?js|cjs|sh)\b|(?:scripts|references|assets)\/[^\s`\])]+)/i.test(localBody);
|
|
24
|
+
return {
|
|
25
|
+
name: entry.skill.name, description: entry.skill.description, source: entry.source,
|
|
26
|
+
hidden: !!entry.skill.hidden, modelInvocable: !entry.skill.disableModelInvocation,
|
|
27
|
+
enabled: !disabled.has(entry.skill.name), removable: entry.source === 'user',
|
|
28
|
+
notes: [
|
|
29
|
+
...(supportFiles ? ['References supporting files. A SKILL.md import does not include those files; provide them separately before use.'] : []),
|
|
30
|
+
...entry.warnings,
|
|
31
|
+
],
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function listManagedSkills(workDir) {
|
|
35
|
+
const loaded = loadAllSkills(workDir, { includeDisabled: true });
|
|
36
|
+
const disabled = disabledSkills();
|
|
37
|
+
return { skills: loaded.registry.list().map((s) => describe(s, disabled)), errors: loaded.errors.map((e) => e.error) };
|
|
38
|
+
}
|
|
39
|
+
export function importSkill(workDir, content) {
|
|
40
|
+
if (typeof content !== 'string' || Buffer.byteLength(content, 'utf8') > MAX_SKILL_BYTES)
|
|
41
|
+
throw new Error('Provide a SKILL.md file up to 256 KiB');
|
|
42
|
+
const parsed = parseSkill(content);
|
|
43
|
+
if ('error' in parsed)
|
|
44
|
+
throw new Error(parsed.error);
|
|
45
|
+
const { name, body, budgetCapUsd } = parsed.skill;
|
|
46
|
+
validName(name);
|
|
47
|
+
if (reserved.has(name))
|
|
48
|
+
throw new Error(`/${name} is reserved by Franklin`);
|
|
49
|
+
if (!body.trim())
|
|
50
|
+
throw new Error('Skill instructions must not be empty');
|
|
51
|
+
if (budgetCapUsd !== undefined && (!Number.isFinite(budgetCapUsd) || budgetCapUsd < 0))
|
|
52
|
+
throw new Error('budget-cap-usd must be a non-negative number');
|
|
53
|
+
if (loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name))
|
|
54
|
+
throw new Error(`/${name} already exists; remove your imported copy before replacing it`);
|
|
55
|
+
safeRoot();
|
|
56
|
+
const dir = join(root, name);
|
|
57
|
+
// mkdir is exclusive, including against dangling symlinks and concurrent imports.
|
|
58
|
+
try {
|
|
59
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
if (err.code === 'EEXIST')
|
|
63
|
+
throw new Error(`/${name} already exists on disk`);
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
writeFileSync(join(dir, 'SKILL.md'), content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
|
|
68
|
+
setSkillEnabled(name, true);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
try {
|
|
72
|
+
unlinkSync(join(dir, 'SKILL.md'));
|
|
73
|
+
rmdirSync(dir);
|
|
74
|
+
}
|
|
75
|
+
catch { /* preserve unexpected files */ }
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
return { name };
|
|
79
|
+
}
|
|
80
|
+
export function toggleSkill(workDir, name, enabled) {
|
|
81
|
+
validName(name);
|
|
82
|
+
if (typeof enabled !== 'boolean')
|
|
83
|
+
throw new Error('enabled must be a boolean');
|
|
84
|
+
if (!loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name))
|
|
85
|
+
throw new Error('Skill not found');
|
|
86
|
+
setSkillEnabled(name, enabled);
|
|
87
|
+
return { ok: true };
|
|
88
|
+
}
|
|
89
|
+
export function removeSkill(workDir, name) {
|
|
90
|
+
validName(name);
|
|
91
|
+
const entry = loadAllSkills(workDir, { includeDisabled: true }).registry.lookup(name);
|
|
92
|
+
if (!entry || entry.source !== 'user')
|
|
93
|
+
throw new Error('Only imported user skills can be removed here');
|
|
94
|
+
safeRoot();
|
|
95
|
+
const dir = join(root, name), file = join(dir, 'SKILL.md');
|
|
96
|
+
if (lstatSync(dir).isSymbolicLink() || lstatSync(file).isSymbolicLink())
|
|
97
|
+
throw new Error('Cannot remove a linked skill');
|
|
98
|
+
if (readdirSync(dir).some((f) => f !== 'SKILL.md'))
|
|
99
|
+
throw new Error('Skill contains supporting files; manage its folder directly');
|
|
100
|
+
unlinkSync(file);
|
|
101
|
+
rmdirSync(dir);
|
|
102
|
+
setSkillEnabled(name, true);
|
|
103
|
+
return { ok: true };
|
|
104
|
+
}
|
|
105
|
+
/** Same prompt resolver used by slash dispatch; does not call models or tools. */
|
|
106
|
+
export function resolveManagedSkill(workDir, input) {
|
|
107
|
+
if (typeof input !== 'string' || input.length > MAX_SKILL_BYTES)
|
|
108
|
+
throw new Error('Provide a skill command');
|
|
109
|
+
const match = matchSkill(input, loadAllSkills(workDir).registry, {});
|
|
110
|
+
if (!match)
|
|
111
|
+
throw new Error('Skill not found or disabled');
|
|
112
|
+
return { name: match.skill.name, prompt: match.rewritten };
|
|
113
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
5
|
+
const stateFile = join(BLOCKRUN_DIR, 'skills-disabled.json');
|
|
6
|
+
export function disabledSkills() {
|
|
7
|
+
if (!existsSync(stateFile))
|
|
8
|
+
return new Set();
|
|
9
|
+
if (lstatSync(stateFile).isSymbolicLink())
|
|
10
|
+
throw new Error('Skill state must not be a symlink');
|
|
11
|
+
const names = JSON.parse(readFileSync(stateFile, 'utf8'));
|
|
12
|
+
if (!Array.isArray(names) || !names.every((n) => typeof n === 'string'))
|
|
13
|
+
throw new Error('Invalid skill state');
|
|
14
|
+
return new Set(names);
|
|
15
|
+
}
|
|
16
|
+
export function setSkillEnabled(name, enabled) {
|
|
17
|
+
const names = disabledSkills();
|
|
18
|
+
if (enabled)
|
|
19
|
+
names.delete(name);
|
|
20
|
+
else
|
|
21
|
+
names.add(name);
|
|
22
|
+
mkdirSync(BLOCKRUN_DIR, { recursive: true });
|
|
23
|
+
const temp = `${stateFile}.${randomUUID()}.tmp`;
|
|
24
|
+
writeFileSync(temp, JSON.stringify([...names]), { mode: 0o600, flag: 'wx' });
|
|
25
|
+
renameSync(temp, stateFile);
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ids that become a single path segment (session ids, task run ids).
|
|
3
|
+
*
|
|
4
|
+
* These ids reach the filesystem helpers from URLs (panel /api/sessions/:id,
|
|
5
|
+
* /api/tasks/:runId) after decodeURIComponent, so `..%2F` arrives as `../`.
|
|
6
|
+
* Validate in the shared path helper, not in each route: GHSA-jx74-262x-94p3
|
|
7
|
+
* fixed the sessions route while the tasks route kept the same hole.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isSafePathSegment(id: unknown): id is string;
|
|
10
|
+
export declare function assertSafePathSegment(id: unknown, kind: string): asserts id is string;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ids that become a single path segment (session ids, task run ids).
|
|
3
|
+
*
|
|
4
|
+
* These ids reach the filesystem helpers from URLs (panel /api/sessions/:id,
|
|
5
|
+
* /api/tasks/:runId) after decodeURIComponent, so `..%2F` arrives as `../`.
|
|
6
|
+
* Validate in the shared path helper, not in each route: GHSA-jx74-262x-94p3
|
|
7
|
+
* fixed the sessions route while the tasks route kept the same hole.
|
|
8
|
+
*/
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
export function isSafePathSegment(id) {
|
|
11
|
+
return (typeof id === 'string' &&
|
|
12
|
+
id.length > 0 &&
|
|
13
|
+
id !== '.' &&
|
|
14
|
+
!id.includes('..') &&
|
|
15
|
+
!id.includes('/') &&
|
|
16
|
+
!id.includes('\\') &&
|
|
17
|
+
!id.includes('\0') &&
|
|
18
|
+
id === path.basename(id));
|
|
19
|
+
}
|
|
20
|
+
export function assertSafePathSegment(id, kind) {
|
|
21
|
+
if (!isSafePathSegment(id)) {
|
|
22
|
+
throw new Error(`Invalid ${kind}: ${JSON.stringify(id)}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
package/dist/tasks/paths.js
CHANGED
|
@@ -23,6 +23,7 @@ import fs from 'node:fs';
|
|
|
23
23
|
import os from 'node:os';
|
|
24
24
|
import path from 'node:path';
|
|
25
25
|
import { BLOCKRUN_DIR } from '../config.js';
|
|
26
|
+
import { assertSafePathSegment } from '../storage/safe-id.js';
|
|
26
27
|
const LEGACY_FRANKLIN_HOME = path.join(os.homedir(), '.franklin');
|
|
27
28
|
function franklinHome() {
|
|
28
29
|
return process.env.FRANKLIN_HOME || BLOCKRUN_DIR;
|
|
@@ -34,6 +35,9 @@ export function getLegacyTasksDir() {
|
|
|
34
35
|
return path.join(LEGACY_FRANKLIN_HOME, 'tasks');
|
|
35
36
|
}
|
|
36
37
|
export function getTaskDir(runId) {
|
|
38
|
+
// Run ids reach here from URLs (panel /api/tasks/:runId); never let one
|
|
39
|
+
// escape the tasks dir. Every task path helper routes through here.
|
|
40
|
+
assertSafePathSegment(runId, 'task run id');
|
|
37
41
|
// Prefer the primary location. If a task already exists in the
|
|
38
42
|
// legacy ~/.franklin/tasks/ — either created by an older release or
|
|
39
43
|
// by a runner subprocess started before this version was installed —
|
package/dist/tools/glob.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import {
|
|
6
|
+
import { setImmediate as yieldToRequests } from 'node:timers/promises';
|
|
7
|
+
import { isCredentialPathAsync } from './sensitive-paths.js';
|
|
7
8
|
const MAX_RESULTS = 200;
|
|
8
9
|
const MAX_OUTPUT_CHARS = 12_000; // ~3,000 tokens — prevents huge glob results from blowing up context
|
|
9
10
|
/**
|
|
@@ -22,14 +23,15 @@ function globMatch(pattern, text) {
|
|
|
22
23
|
const regex = new RegExp(`^${regexStr}$`);
|
|
23
24
|
return regex.test(text.replace(/\\/g, '/'));
|
|
24
25
|
}
|
|
25
|
-
function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
|
|
26
|
+
async function walkDirectory(dir, baseDir, pattern, results, depth, signal, visited) {
|
|
27
|
+
signal.throwIfAborted();
|
|
26
28
|
if (depth > 50 || results.length >= MAX_RESULTS)
|
|
27
29
|
return;
|
|
28
30
|
// Symlink loop protection
|
|
29
31
|
const visitedSet = visited ?? new Set();
|
|
30
32
|
let realDir;
|
|
31
33
|
try {
|
|
32
|
-
realDir = fs.
|
|
34
|
+
realDir = await fs.promises.realpath(dir);
|
|
33
35
|
}
|
|
34
36
|
catch {
|
|
35
37
|
return;
|
|
@@ -37,18 +39,25 @@ function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
|
|
|
37
39
|
if (visitedSet.has(realDir))
|
|
38
40
|
return;
|
|
39
41
|
visitedSet.add(realDir);
|
|
42
|
+
signal.throwIfAborted();
|
|
40
43
|
let entries;
|
|
41
44
|
try {
|
|
42
|
-
entries = fs.
|
|
45
|
+
entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
43
46
|
}
|
|
44
47
|
catch {
|
|
45
48
|
return; // Permission denied or similar
|
|
46
49
|
}
|
|
50
|
+
let checked = 0;
|
|
47
51
|
for (const entry of entries) {
|
|
52
|
+
signal.throwIfAborted();
|
|
48
53
|
if (results.length >= MAX_RESULTS)
|
|
49
54
|
break;
|
|
55
|
+
// Large flat directories also need to yield, even when nothing matches.
|
|
56
|
+
if (++checked % 128 === 0)
|
|
57
|
+
await yieldToRequests(undefined, { signal });
|
|
50
58
|
// Skip hidden dirs and common large dirs
|
|
51
|
-
const isDir = entry.isDirectory() || (entry.isSymbolicLink() && isSymlinkDir(path.join(dir, entry.name)));
|
|
59
|
+
const isDir = entry.isDirectory() || (entry.isSymbolicLink() && await isSymlinkDir(path.join(dir, entry.name)));
|
|
60
|
+
signal.throwIfAborted();
|
|
52
61
|
if (entry.name.startsWith('.') && isDir)
|
|
53
62
|
continue;
|
|
54
63
|
if (entry.name === 'node_modules' || entry.name === '__pycache__' || entry.name === '.git')
|
|
@@ -56,59 +65,78 @@ function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
|
|
|
56
65
|
const fullPath = path.join(dir, entry.name);
|
|
57
66
|
const relativePath = path.relative(baseDir, fullPath);
|
|
58
67
|
if (entry.isFile() || (entry.isSymbolicLink() && !isDir)) {
|
|
59
|
-
|
|
60
|
-
if (isWalletKeyPath(fullPath) || isHostCredentialPath(fullPath))
|
|
68
|
+
if (!globMatch(pattern, relativePath))
|
|
61
69
|
continue;
|
|
62
|
-
|
|
70
|
+
// Don't hand the model a map to the key store or host credentials.
|
|
71
|
+
const secret = await isCredentialPathAsync(fullPath);
|
|
72
|
+
signal.throwIfAborted();
|
|
73
|
+
if (!secret)
|
|
63
74
|
results.push(fullPath);
|
|
64
|
-
}
|
|
65
75
|
}
|
|
66
76
|
else if (isDir) {
|
|
67
77
|
// Recurse for ** patterns; for patterns with /, only recurse if current dir is on the path
|
|
68
78
|
if (pattern.includes('**')) {
|
|
69
|
-
walkDirectory(fullPath, baseDir, pattern, results, depth + 1, visitedSet);
|
|
79
|
+
await walkDirectory(fullPath, baseDir, pattern, results, depth + 1, signal, visitedSet);
|
|
70
80
|
}
|
|
71
81
|
else if (pattern.includes('/')) {
|
|
72
82
|
// Check if this directory could be part of the pattern path
|
|
73
83
|
const relativePath = path.relative(baseDir, fullPath);
|
|
74
84
|
const patternDir = pattern.split('/').slice(0, -1).join('/');
|
|
75
85
|
if (patternDir.startsWith(relativePath) || relativePath.startsWith(patternDir)) {
|
|
76
|
-
walkDirectory(fullPath, baseDir, pattern, results, depth + 1, visitedSet);
|
|
86
|
+
await walkDirectory(fullPath, baseDir, pattern, results, depth + 1, signal, visitedSet);
|
|
77
87
|
}
|
|
78
88
|
}
|
|
79
89
|
}
|
|
80
90
|
}
|
|
81
91
|
}
|
|
82
|
-
function isSymlinkDir(p) {
|
|
92
|
+
async function isSymlinkDir(p) {
|
|
83
93
|
try {
|
|
84
|
-
return fs.
|
|
94
|
+
return (await fs.promises.stat(p)).isDirectory();
|
|
85
95
|
}
|
|
86
96
|
catch {
|
|
87
97
|
return false;
|
|
88
98
|
}
|
|
89
99
|
}
|
|
90
100
|
async function execute(input, ctx) {
|
|
101
|
+
try {
|
|
102
|
+
return await search(input, ctx);
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
if (ctx.abortSignal.aborted)
|
|
106
|
+
return { output: 'File search cancelled.', isError: true };
|
|
107
|
+
throw err;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function search(input, ctx) {
|
|
91
111
|
const { pattern, path: searchPath } = input;
|
|
112
|
+
ctx.abortSignal.throwIfAborted();
|
|
92
113
|
if (!pattern) {
|
|
93
114
|
return { output: 'Error: pattern is required', isError: true };
|
|
94
115
|
}
|
|
95
116
|
const baseDir = searchPath
|
|
96
117
|
? (path.isAbsolute(searchPath) ? searchPath : path.resolve(ctx.workingDir, searchPath))
|
|
97
118
|
: ctx.workingDir;
|
|
98
|
-
|
|
119
|
+
try {
|
|
120
|
+
await fs.promises.access(baseDir);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
99
123
|
return { output: `Error: directory not found: ${baseDir}`, isError: true };
|
|
100
124
|
}
|
|
101
125
|
const results = [];
|
|
102
|
-
walkDirectory(baseDir, baseDir, pattern, results, 0);
|
|
126
|
+
await walkDirectory(baseDir, baseDir, pattern, results, 0, ctx.abortSignal);
|
|
127
|
+
ctx.abortSignal.throwIfAborted();
|
|
103
128
|
// Sort by modification time (most recent first)
|
|
104
|
-
const withMtime =
|
|
129
|
+
const withMtime = [];
|
|
130
|
+
for (const f of results) {
|
|
131
|
+
ctx.abortSignal.throwIfAborted();
|
|
105
132
|
try {
|
|
106
|
-
|
|
133
|
+
withMtime.push({ path: f, mtime: (await fs.promises.stat(f)).mtimeMs });
|
|
107
134
|
}
|
|
108
135
|
catch {
|
|
109
|
-
|
|
136
|
+
withMtime.push({ path: f, mtime: 0 });
|
|
110
137
|
}
|
|
111
|
-
}
|
|
138
|
+
}
|
|
139
|
+
ctx.abortSignal.throwIfAborted();
|
|
112
140
|
withMtime.sort((a, b) => b.mtime - a.mtime);
|
|
113
141
|
// Convert to relative paths to save tokens
|
|
114
142
|
const sorted = withMtime.map(f => {
|
|
@@ -28,6 +28,8 @@ export declare function walletKeyFilesUnder(absDir: string): string[];
|
|
|
28
28
|
* credential store (see hostCredentialDirs / hostCredentialFiles).
|
|
29
29
|
*/
|
|
30
30
|
export declare function isHostCredentialPath(resolvedAbsPath: string): boolean;
|
|
31
|
+
/** Same file-search exclusion policy without blocking the agent's RPC loop. */
|
|
32
|
+
export declare function isCredentialPathAsync(resolvedAbsPath: string): Promise<boolean>;
|
|
31
33
|
/** Home-relative credential directories, for tools that keep their own blocklist. */
|
|
32
34
|
export declare function hostCredentialDirPaths(): string[];
|
|
33
35
|
/** The single refusal used by every model-facing tool that reads files. */
|
|
@@ -145,6 +145,29 @@ export function isHostCredentialPath(resolvedAbsPath) {
|
|
|
145
145
|
catch { /* best-effort symlink check */ }
|
|
146
146
|
return false;
|
|
147
147
|
}
|
|
148
|
+
/** Same file-search exclusion policy without blocking the agent's RPC loop. */
|
|
149
|
+
export async function isCredentialPathAsync(resolvedAbsPath) {
|
|
150
|
+
const home = os.homedir();
|
|
151
|
+
const matches = (candidate) => matchesKeyFile(candidate) || matchesHostCredential(candidate, home);
|
|
152
|
+
if (matches(resolvedAbsPath))
|
|
153
|
+
return true;
|
|
154
|
+
try {
|
|
155
|
+
const canonical = await fs.promises.realpath(resolvedAbsPath);
|
|
156
|
+
if (matches(canonical))
|
|
157
|
+
return true;
|
|
158
|
+
// Windows temp homes may use an 8.3 alias while native realpath expands
|
|
159
|
+
// it; macOS also aliases /var. Compare against the same home namespace.
|
|
160
|
+
const canonicalHome = await fs.promises.realpath(home);
|
|
161
|
+
const relative = path.relative(canonicalHome, canonical);
|
|
162
|
+
if (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep)) {
|
|
163
|
+
return matches(path.resolve(home, relative));
|
|
164
|
+
}
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
148
171
|
/** Home-relative credential directories, for tools that keep their own blocklist. */
|
|
149
172
|
export function hostCredentialDirPaths() {
|
|
150
173
|
return hostCredentialDirs(os.homedir());
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/franklin",
|
|
3
|
-
"version": "3.49.
|
|
3
|
+
"version": "3.49.19",
|
|
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": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"desktop:package:win": "npm run dist:win --workspace @blockrun/franklin-desktop",
|
|
39
39
|
"dev": "tsc --watch",
|
|
40
40
|
"start": "node dist/index.js",
|
|
41
|
-
"test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs test/subprocess-env.local.mjs test/withdraw.local.mjs test/orders.local.mjs test/payment-hold.local.mjs test/experience.local.mjs",
|
|
41
|
+
"test": "npm run build && node --test --test-concurrency=4 --test-reporter=spec test/local.mjs test/api-key.local.mjs test/solana-migration.local.mjs test/serve-security.local.mjs test/skills.local.mjs test/skills-management.local.mjs test/glob-responsive.local.mjs test/desktop-auto-routing.local.mjs test/desktop-questions.local.mjs test/desktop-question-flow.local.mjs test/desktop-input.local.mjs test/desktop-image-flow.local.mjs test/repair.mjs test/model-resolver.mjs test/exa.local.mjs test/audit-batch.local.mjs test/polymarket.local.mjs test/market.local.mjs test/hooks.local.mjs test/scheduler.local.mjs test/trade-plan.local.mjs test/goal.local.mjs test/memory.local.mjs test/agent-host.local.mjs test/reservation.local.mjs test/model-catalog.local.mjs test/arc.local.mjs test/subprocess-env.local.mjs test/withdraw.local.mjs test/orders.local.mjs test/payment-hold.local.mjs test/experience.local.mjs",
|
|
42
42
|
"test:e2e": "npm run build && node --test --test-reporter=spec test/e2e.mjs",
|
|
43
43
|
"e2e:polymarket:readonly": "npm run build && node scripts/polymarket-e2e-readonly.mjs",
|
|
44
44
|
"test:free-models": "npm run build && node --test --test-reporter=spec test/free-model-matrix.mjs",
|
|
@@ -100,7 +100,8 @@
|
|
|
100
100
|
"react": "^19.2.4",
|
|
101
101
|
"sharp": "^0.35.5",
|
|
102
102
|
"viem": "^2.48.1",
|
|
103
|
-
"ws": "^8.21.1"
|
|
103
|
+
"ws": "^8.21.1",
|
|
104
|
+
"yaml": "^2.9.1"
|
|
104
105
|
},
|
|
105
106
|
"devDependencies": {
|
|
106
107
|
"@types/node": "^26.1.1",
|