@bevel-software/platform-core-frontend 0.30.0 → 0.32.0
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/package.json +2 -2
- package/src/{modules/access/__tests__ → __tests__}/tailwindDeclarations.ts +1 -1
- package/src/__tests__/title-ink-room.ts +30 -0
- package/src/modules/access/__tests__/ManageAccessDialog.chip-truncation.test.tsx +1 -1
- package/src/modules/audit/__tests__/AuditLogPage.test.tsx +35 -2
- package/src/modules/audit/components/AuditEventsPanel.tsx +2 -1
- package/src/modules/audit/components/AuditLogPage.tsx +20 -12
- package/src/modules/audit/services/audit.api.ts +6 -4
- package/src/modules/embed/__tests__/EmbedView.test.tsx +20 -0
- package/src/modules/embed/components/EmbedView.tsx +2 -0
- package/src/modules/git/index.ts +3 -0
- package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +50 -0
- package/src/modules/library/__tests__/LibraryRoutes.test.tsx +37 -0
- package/src/modules/library/__tests__/SkillPage.test.tsx +44 -1
- package/src/modules/library/__tests__/ToolPage.test.tsx +8 -0
- package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +25 -0
- package/src/modules/library/components/LibraryPage.tsx +2 -2
- package/src/modules/library/components/LockedPluginView.tsx +2 -2
- package/src/modules/library/components/PersonalPluginPage.tsx +5 -4
- package/src/modules/library/components/PluginPage.tsx +7 -4
- package/src/modules/library/components/skill-page/SkillFilePane.tsx +11 -1
- package/src/modules/library/components/skill-page/SkillPage.tsx +12 -2
- package/src/modules/library/components/tool-page/ToolPage.tsx +8 -4
- package/src/modules/library/routes/WorkspaceItemRoute.tsx +8 -2
- package/src/modules/workspace/components/FileViewer.tsx +6 -1
- package/src/modules/workspace/components/KbPageHeader.tsx +7 -4
- package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +7 -0
- package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +164 -4
- package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +1 -0
- package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +272 -0
- package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +1 -0
- package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +44 -3
- package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +62 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +232 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +29 -1
- package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +1 -0
- package/src/modules/workspace/components/renderers/htmlSandbox.ts +92 -1
- package/src/modules/workspace/components/renderers/htmlToolBridge.ts +383 -0
- package/src/modules/workspace/components/renderers/rendererSurface.ts +6 -0
- package/src/modules/workspace/index.ts +9 -2
- package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +7 -0
- package/src/modules/workspace/routing/kb-routes.ts +33 -1
- package/src/shared/theme/header.ts +20 -0
|
@@ -143,7 +143,35 @@ describe('the html-views guide section agrees with the renderer', () => {
|
|
|
143
143
|
it('names exactly the window.bevel members core defines, and leaves data members to a distribution', () => {
|
|
144
144
|
const named = new Set([...guide.matchAll(/window\.bevel\??\.(\w+)/g)].map((m) => m[1]!));
|
|
145
145
|
expect([...named].sort()).toEqual(Object.keys(runBridge().bevel).sort());
|
|
146
|
-
expect([...named].sort()).toEqual(
|
|
146
|
+
expect([...named].sort()).toEqual(Object.keys(runBridge({}, { toolBridge: true }).bevel).sort());
|
|
147
|
+
expect([...named].sort()).toEqual(['navigate', 'openNode', 'requireTools', 'tools']);
|
|
147
148
|
expect(flat).toContain('A distribution may add data members of its own to `window.bevel`');
|
|
148
149
|
});
|
|
150
|
+
|
|
151
|
+
it('names the four functions of window.bevel.tools the runtime defines, where it is null, and requireTools with its card', async () => {
|
|
152
|
+
const named = [...new Set([...guide.matchAll(/window\.bevel\.tools\.(\w+)\(/g)].map((m) => m[1]!))].sort();
|
|
153
|
+
const onFilePage = runBridge({}, { toolBridge: true });
|
|
154
|
+
expect(named).toEqual(Object.keys(onFilePage.bevel.tools as object).sort());
|
|
155
|
+
expect(named).toEqual(['callTool', 'callToolChain', 'searchTools', 'toolsInfo']);
|
|
156
|
+
|
|
157
|
+
// Null everywhere else, and the guide tells a page to check before every use.
|
|
158
|
+
expect(runBridge().bevel.tools).toBeNull();
|
|
159
|
+
expect(flat).toContain('`window.bevel.tools` is `null` wherever tools are not available: on the embed, on a skill page and in any preview that is not the app\'s file page.');
|
|
160
|
+
expect(flat).toContain('Check it before every use, and render the page without tools when it is `null`');
|
|
161
|
+
|
|
162
|
+
// The consent rule and the two cards, in the app's words.
|
|
163
|
+
expect(flat).toContain('A call to a tool that only reads runs with no prompt.');
|
|
164
|
+
expect(flat).toContain('"<page name> wants to write to the knowledge base", with the page\'s path under it and Allow while open and Deny.');
|
|
165
|
+
expect(flat).toContain('Deny runs nothing and rejects the call with `denied`');
|
|
166
|
+
expect(flat).toContain('"<page name> uses tools that are only available in the platform", with Continue without tools and Open in the platform');
|
|
167
|
+
|
|
168
|
+
// requireTools exists on both, asks the app, and resolves with its answer.
|
|
169
|
+
for (const [bridge, answer] of [[runBridge(), false], [onFilePage, true]] as const) {
|
|
170
|
+
const required = (bridge.bevel.requireTools as () => Promise<boolean>)();
|
|
171
|
+
const ask = bridge.posted.at(-1) as { type: string; requestId: string };
|
|
172
|
+
expect(ask.type).toBe('bevel.tools.require');
|
|
173
|
+
await bridge.deliver({ type: 'bevel.tools.require.response', requestId: ask.requestId, ok: true, result: answer });
|
|
174
|
+
await expect(required).resolves.toBe(answer);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
149
177
|
});
|
|
@@ -392,6 +392,91 @@ const NAV_BRIDGE = `
|
|
|
392
392
|
})();
|
|
393
393
|
`;
|
|
394
394
|
|
|
395
|
+
/**
|
|
396
|
+
* How long a page waits for the app to answer one of its tool calls. Long,
|
|
397
|
+
* because the answer may wait on a person: the first writing call shows a
|
|
398
|
+
* card, and nothing answers until they choose. A chain runs for up to two
|
|
399
|
+
* minutes on its own.
|
|
400
|
+
*/
|
|
401
|
+
export const TOOL_CALL_TIMEOUT_MS = 15 * 60 * 1000;
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Runtime appended after the nav bridge: `window.bevel.tools`, the viewer's own
|
|
405
|
+
* tools, and `window.bevel.requireTools()`.
|
|
406
|
+
*
|
|
407
|
+
* The frame has no network (`connect-src 'none'`), so a page reaches tools the
|
|
408
|
+
* way it reaches navigation: it posts `bevel.tool.call` `{ requestId, fn, args }`
|
|
409
|
+
* to the parent and awaits `bevel.tool.response` `{ requestId, ok, result |
|
|
410
|
+
* error, code? }`. The parent (`HtmlRenderer`, through `htmlToolBridge.ts`)
|
|
411
|
+
* answers each one over the hosted MCP server with the viewer's session —
|
|
412
|
+
* after asking the viewer, on the first call that writes. Nothing about the
|
|
413
|
+
* consent lives in the frame: the card is the app's, drawn outside it, and a
|
|
414
|
+
* page can neither see nor answer it.
|
|
415
|
+
*
|
|
416
|
+
* `tools` exists only where the app can answer it — the app's file page.
|
|
417
|
+
* Everywhere else (the embed, a skill page, any other preview) it is `null`,
|
|
418
|
+
* so a page checks `window.bevel && window.bevel.tools` before every use and
|
|
419
|
+
* renders without tools when it is null. `requireTools()` is how a page that
|
|
420
|
+
* needs them asks: it posts `bevel.tools.require` and resolves with the
|
|
421
|
+
* parent's answer — `true` on the file page at once, `false` after the
|
|
422
|
+
* parent's card offered the way to the platform and the viewer chose either.
|
|
423
|
+
*
|
|
424
|
+
* Every response is matched to its request by id, and only from `parent`.
|
|
425
|
+
* The `html-views` section of the agent guide documents the members, and
|
|
426
|
+
* `htmlViewsGuide.test.ts` holds the two together.
|
|
427
|
+
*/
|
|
428
|
+
function toolBridgeRuntime(enabled: boolean): string {
|
|
429
|
+
return `
|
|
430
|
+
;(function () {
|
|
431
|
+
var pending = {};
|
|
432
|
+
var seq = 0;
|
|
433
|
+
function request(type, payload) {
|
|
434
|
+
return new Promise(function (resolve, reject) {
|
|
435
|
+
seq += 1;
|
|
436
|
+
var requestId = 'bevel-tool-' + seq + '-' + Math.random().toString(36).slice(2);
|
|
437
|
+
var timer = setTimeout(function () {
|
|
438
|
+
delete pending[requestId];
|
|
439
|
+
reject(new Error('The app did not answer in time.'));
|
|
440
|
+
}, ${TOOL_CALL_TIMEOUT_MS});
|
|
441
|
+
pending[requestId] = { resolve: resolve, reject: reject, timer: timer };
|
|
442
|
+
var message = { type: type, requestId: requestId };
|
|
443
|
+
for (var key in payload) message[key] = payload[key];
|
|
444
|
+
parent.postMessage(message, '*');
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
if (typeof globalThis.addEventListener === 'function') globalThis.addEventListener('message', function (event) {
|
|
448
|
+
if (event.source !== parent) return;
|
|
449
|
+
var msg = event.data;
|
|
450
|
+
if (!msg || typeof msg !== 'object') return;
|
|
451
|
+
if (msg.type !== 'bevel.tool.response' && msg.type !== 'bevel.tools.require.response') return;
|
|
452
|
+
var waiting = pending[msg.requestId];
|
|
453
|
+
if (!waiting) return;
|
|
454
|
+
delete pending[msg.requestId];
|
|
455
|
+
clearTimeout(waiting.timer);
|
|
456
|
+
if (msg.ok) {
|
|
457
|
+
waiting.resolve(msg.result);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
var error = new Error(typeof msg.error === 'string' ? msg.error : 'The tool call failed.');
|
|
461
|
+
if (msg.code) error.code = msg.code;
|
|
462
|
+
waiting.reject(error);
|
|
463
|
+
});
|
|
464
|
+
function call(fn, args) {
|
|
465
|
+
return request('bevel.tool.call', { fn: fn, args: args });
|
|
466
|
+
}
|
|
467
|
+
globalThis.bevel.tools = ${enabled ? `Object.freeze({
|
|
468
|
+
searchTools: function (query) { return call('searchTools', [query === undefined ? '' : query]); },
|
|
469
|
+
toolsInfo: function (names) { return call('toolsInfo', [names]); },
|
|
470
|
+
callTool: function (name, args) { return call('callTool', [name, args === undefined ? {} : args]); },
|
|
471
|
+
callToolChain: function (code) { return call('callToolChain', [code]); }
|
|
472
|
+
})` : 'null'};
|
|
473
|
+
globalThis.bevel.requireTools = function () {
|
|
474
|
+
return request('bevel.tools.require', {}).then(function (answer) { return answer === true; });
|
|
475
|
+
};
|
|
476
|
+
})();
|
|
477
|
+
`;
|
|
478
|
+
}
|
|
479
|
+
|
|
395
480
|
interface BuildSandboxedHtmlOptions {
|
|
396
481
|
/** Display title (rendered in the iframe doc's <title>). */
|
|
397
482
|
title: string;
|
|
@@ -406,6 +491,12 @@ interface BuildSandboxedHtmlOptions {
|
|
|
406
491
|
includeRuntime?: boolean;
|
|
407
492
|
/** Sanitized agent HTML, body content only. */
|
|
408
493
|
bodyHtml: string;
|
|
494
|
+
/**
|
|
495
|
+
* Give the page `window.bevel.tools`: only where the parent answers tool
|
|
496
|
+
* calls, which is the app's file page. Absent or false, the member is
|
|
497
|
+
* `null`; `requireTools()` exists either way.
|
|
498
|
+
*/
|
|
499
|
+
toolBridge?: boolean;
|
|
409
500
|
}
|
|
410
501
|
|
|
411
502
|
/**
|
|
@@ -417,7 +508,7 @@ interface BuildSandboxedHtmlOptions {
|
|
|
417
508
|
export function buildSandboxedHtml(opts: BuildSandboxedHtmlOptions): string {
|
|
418
509
|
const lib = opts.libModuleSources.map(stripRelativeImports).join('\n\n');
|
|
419
510
|
const exposeGlobals = `\n;globalThis.bevel = { ${BEVEL_GLOBAL_EXPORTS.join(', ')} };\n`;
|
|
420
|
-
const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE);
|
|
511
|
+
const inlineLib = escapeForScriptBody(lib + exposeGlobals + NAV_BRIDGE + toolBridgeRuntime(opts.toolBridge === true));
|
|
421
512
|
|
|
422
513
|
// Title and body are content-only — `srcDoc` already isolates them, but we
|
|
423
514
|
// still want to escape the few characters that would terminate the parent
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react';
|
|
2
|
+
import { authFetch } from '../../../../lib/api';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The app's half of `window.bevel.tools`: what answers an HTML page's tool
|
|
6
|
+
* calls, and what decides when the viewer is asked first.
|
|
7
|
+
*
|
|
8
|
+
* A page's call is answered over the hosted MCP server (`POST /api/mcp`) with
|
|
9
|
+
* the viewer's session, so a page sees and reaches exactly the tools the
|
|
10
|
+
* viewer's own agent does — the same listing, the same refusals, nothing of
|
|
11
|
+
* the enterprise agent's internal tools — and the server records it in the
|
|
12
|
+
* Audit log under the page's path (`X-Bevel-Page`). The four members map to
|
|
13
|
+
* what an agent calls:
|
|
14
|
+
*
|
|
15
|
+
* searchTools(query) → `list_tools`, narrowed to the names that contain
|
|
16
|
+
* every word of `query` (all of them for an empty one)
|
|
17
|
+
* toolsInfo(names) → `tools_info`
|
|
18
|
+
* callTool(name, args) → `tools/call`
|
|
19
|
+
* callToolChain(code) → `call_tool_chain`
|
|
20
|
+
*
|
|
21
|
+
* A call that only reads runs at once. A call that may write — a tool the
|
|
22
|
+
* deployment's UTCP manual tags `write`, a tool the manual does not list (a
|
|
23
|
+
* `.tool`'s, a plugin's MCP server's: nothing says they only read), and every
|
|
24
|
+
* chain (a chain may call writers) — waits for the viewer's answer to one
|
|
25
|
+
* card per page view. See {@link PageConsent}.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** What the file page tells the HTML renderer: that tools are answered here, and for which page. */
|
|
29
|
+
export interface PageTools {
|
|
30
|
+
/** The page's knowledge-base path (`Dashboards/Roadmap.html`), what the Audit log shows as the agent. */
|
|
31
|
+
pagePath: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Provided by the app's file page and nowhere else: its presence is what
|
|
36
|
+
* gives a page `window.bevel.tools`. The embed, a skill page and every other
|
|
37
|
+
* preview mount the renderer without it, and their pages get `null`.
|
|
38
|
+
*/
|
|
39
|
+
export const PageToolsContext = createContext<PageTools | null>(null);
|
|
40
|
+
|
|
41
|
+
export function usePageTools(): PageTools | null {
|
|
42
|
+
return useContext(PageToolsContext);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* How to open the page on the app's file page, for a host whose `filePath` is
|
|
47
|
+
* not a workspace path — a skill page names its files relative to the skill
|
|
48
|
+
* (`view.html`). Absent, the renderer opens its own `filePath` (the embed's
|
|
49
|
+
* surface does that in a new tab, through its host).
|
|
50
|
+
*/
|
|
51
|
+
export const OpenPageInPlatformContext = createContext<(() => void) | null>(null);
|
|
52
|
+
|
|
53
|
+
export function useOpenPageInPlatform(): (() => void) | null {
|
|
54
|
+
return useContext(OpenPageInPlatformContext);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The four members a page calls, by the name the frame posts. */
|
|
58
|
+
export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain';
|
|
59
|
+
|
|
60
|
+
const PAGE_TOOL_FUNCTIONS: ReadonlySet<string> = new Set(['searchTools', 'toolsInfo', 'callTool', 'callToolChain']);
|
|
61
|
+
|
|
62
|
+
/** The code-mode meta-tools by the name a page may also `callTool` them under: two read, the chain may write. */
|
|
63
|
+
const READING_META_TOOLS: ReadonlySet<string> = new Set(['list_tools', 'tools_info']);
|
|
64
|
+
const CHAIN_TOOL = 'call_tool_chain';
|
|
65
|
+
|
|
66
|
+
/** The answer a page gets when its viewer chose Deny. */
|
|
67
|
+
export const DENIED = 'denied';
|
|
68
|
+
|
|
69
|
+
/** A tool call's failure, as the page receives it: the message, and a code for the cases a page may handle. */
|
|
70
|
+
export class PageToolError extends Error {
|
|
71
|
+
readonly code?: string;
|
|
72
|
+
|
|
73
|
+
constructor(message: string, code?: string) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = 'PageToolError';
|
|
76
|
+
this.code = code;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
|
|
81
|
+
|
|
82
|
+
/** One MCP `CallToolResult`, as much of it as the bridge reads. */
|
|
83
|
+
interface CallToolResult {
|
|
84
|
+
isError?: boolean;
|
|
85
|
+
content?: Array<{ type: string; text?: string }>;
|
|
86
|
+
structuredContent?: unknown;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* How long the manual's read of which tools write is trusted. A page stays
|
|
91
|
+
* open for hours; a tool retagged `write` in that time must ask again, not
|
|
92
|
+
* run on the tag the page was opened under.
|
|
93
|
+
*/
|
|
94
|
+
export const MANUAL_TTL_MS = 60_000;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The viewer's tools for one page: MCP calls with the session, and the read
|
|
98
|
+
* of which tools write.
|
|
99
|
+
*/
|
|
100
|
+
export class PageToolsClient {
|
|
101
|
+
private seq = 0;
|
|
102
|
+
private writing: Promise<Map<string, boolean> | null> | undefined;
|
|
103
|
+
private writingReadAt = 0;
|
|
104
|
+
private readonly pagePath: string;
|
|
105
|
+
private readonly fetchImpl: Fetch;
|
|
106
|
+
private readonly now: () => number;
|
|
107
|
+
|
|
108
|
+
constructor(pagePath: string, fetchImpl: Fetch = authFetch, now: () => number = Date.now) {
|
|
109
|
+
this.pagePath = pagePath;
|
|
110
|
+
this.fetchImpl = fetchImpl;
|
|
111
|
+
this.now = now;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `list_tools`' names, narrowed to those containing every word of `query`. */
|
|
115
|
+
async searchTools(query: unknown): Promise<{ tools: string[] }> {
|
|
116
|
+
const listed = (await this.callTool('list_tools', {})) as { tools?: unknown };
|
|
117
|
+
const names = Array.isArray(listed?.tools) ? listed.tools.filter((n): n is string => typeof n === 'string') : [];
|
|
118
|
+
const words = String(query ?? '')
|
|
119
|
+
.toLowerCase()
|
|
120
|
+
.split(/[\s_.]+/)
|
|
121
|
+
.filter(Boolean);
|
|
122
|
+
const fold = (n: string) => n.toLowerCase().replace(/[_.]+/g, ' ');
|
|
123
|
+
return { tools: words.length === 0 ? names : names.filter((n) => words.every((w) => fold(n).includes(w))) };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** `tools_info` for `names`. */
|
|
127
|
+
toolsInfo(names: unknown): Promise<unknown> {
|
|
128
|
+
return this.callTool('tools_info', { tool_names: names });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** `call_tool_chain` with `code`. */
|
|
132
|
+
callToolChain(code: unknown): Promise<unknown> {
|
|
133
|
+
return this.callTool(CHAIN_TOOL, { code });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* `tools/call`, answered the way the page reads it: the tool's structured
|
|
138
|
+
* content when it has some, else its text — parsed when it is JSON. A tool
|
|
139
|
+
* that answers with an error, or a request the server refuses, rejects
|
|
140
|
+
* with the tool's (or the server's) own message.
|
|
141
|
+
*/
|
|
142
|
+
async callTool(name: unknown, args: unknown): Promise<unknown> {
|
|
143
|
+
if (typeof name !== 'string' || name === '') throw new PageToolError('callTool needs a tool name.');
|
|
144
|
+
const params = { name, arguments: args && typeof args === 'object' && !Array.isArray(args) ? args : {} };
|
|
145
|
+
return toPageResult((await this.rpc('tools/call', params)) as CallToolResult);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Whether a call may write, and so needs the viewer's consent: a chain, a
|
|
150
|
+
* tool the manual tags `write`, or a tool the manual does not list. When the
|
|
151
|
+
* manual cannot be read, everything but the two reading meta-tools counts
|
|
152
|
+
* as writing — the card shows once more than it had to, never once less.
|
|
153
|
+
*/
|
|
154
|
+
async mayWrite(fn: PageToolFunction, args: unknown[]): Promise<boolean> {
|
|
155
|
+
if (fn === 'searchTools' || fn === 'toolsInfo') return false;
|
|
156
|
+
if (fn === 'callToolChain') return true;
|
|
157
|
+
const name = args[0];
|
|
158
|
+
if (typeof name !== 'string') return false; // refused by callTool itself, before anything runs
|
|
159
|
+
if (READING_META_TOOLS.has(name)) return false;
|
|
160
|
+
if (name === CHAIN_TOOL) return true;
|
|
161
|
+
const writing = await this.writingTools();
|
|
162
|
+
const tagged = writing?.get(name);
|
|
163
|
+
return tagged === undefined ? true : tagged;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Tell the server the viewer refused this page a call, for the Audit log. Best-effort. */
|
|
167
|
+
async recordRefusal(name: string, args: unknown): Promise<void> {
|
|
168
|
+
try {
|
|
169
|
+
await this.fetchImpl('/api/mcp/page-refusals', {
|
|
170
|
+
method: 'POST',
|
|
171
|
+
headers: { 'Content-Type': 'application/json' },
|
|
172
|
+
body: JSON.stringify({ page: this.pagePath, tool: name, args: args && typeof args === 'object' ? args : {} }),
|
|
173
|
+
});
|
|
174
|
+
} catch {
|
|
175
|
+
// The refusal stands whether or not the log heard of it.
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The deployment's UTCP manual, read at most once a `MANUAL_TTL_MS`: tool name → whether it is tagged `write`. */
|
|
180
|
+
private writingTools(): Promise<Map<string, boolean> | null> {
|
|
181
|
+
const now = this.now();
|
|
182
|
+
if (this.writing && now - this.writingReadAt < MANUAL_TTL_MS) return this.writing;
|
|
183
|
+
this.writingReadAt = now;
|
|
184
|
+
this.writing = this.fetchImpl('/api/agent/utcp')
|
|
185
|
+
.then(async (res) => {
|
|
186
|
+
if (!res.ok) return null;
|
|
187
|
+
const manual = (await res.json()) as { tools?: Array<{ name?: unknown; tags?: unknown }> };
|
|
188
|
+
const map = new Map<string, boolean>();
|
|
189
|
+
for (const tool of manual.tools ?? []) {
|
|
190
|
+
if (typeof tool.name !== 'string') continue;
|
|
191
|
+
const tags = Array.isArray(tool.tags) ? tool.tags : [];
|
|
192
|
+
// The manual names a tool bare or under its namespace; the page calls it bare.
|
|
193
|
+
map.set(tool.name.slice(tool.name.lastIndexOf('.') + 1), tags.includes('write'));
|
|
194
|
+
}
|
|
195
|
+
return map;
|
|
196
|
+
})
|
|
197
|
+
.catch(() => null);
|
|
198
|
+
return this.writing;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** One JSON-RPC request to the hosted MCP server, as this page. */
|
|
202
|
+
private async rpc(method: string, params: unknown): Promise<unknown> {
|
|
203
|
+
this.seq += 1;
|
|
204
|
+
const id = this.seq;
|
|
205
|
+
const res = await this.fetchImpl('/api/mcp', {
|
|
206
|
+
method: 'POST',
|
|
207
|
+
headers: {
|
|
208
|
+
'Content-Type': 'application/json',
|
|
209
|
+
Accept: 'application/json, text/event-stream',
|
|
210
|
+
'X-Bevel-Page': encodeURIComponent(this.pagePath),
|
|
211
|
+
},
|
|
212
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
|
|
213
|
+
});
|
|
214
|
+
const messages = await readMessages(res);
|
|
215
|
+
const answer = messages.find((m) => m.id === id) ?? messages[0];
|
|
216
|
+
if (!answer) throw new PageToolError(`The tool server answered HTTP ${res.status} with nothing to read.`);
|
|
217
|
+
if (answer.error) throw new PageToolError(String(answer.error.message ?? 'The tool server refused the call.'));
|
|
218
|
+
return answer.result;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
interface RpcMessage {
|
|
223
|
+
id?: unknown;
|
|
224
|
+
result?: unknown;
|
|
225
|
+
error?: { message?: unknown };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The JSON-RPC messages in a response, whether it came back as one JSON body or as a stream of events. */
|
|
229
|
+
async function readMessages(res: Response): Promise<RpcMessage[]> {
|
|
230
|
+
const text = await res.text();
|
|
231
|
+
if ((res.headers.get('content-type') ?? '').includes('text/event-stream')) {
|
|
232
|
+
return text
|
|
233
|
+
.split('\n')
|
|
234
|
+
.filter((line) => line.startsWith('data:'))
|
|
235
|
+
.flatMap((line) => {
|
|
236
|
+
try {
|
|
237
|
+
return [JSON.parse(line.slice('data:'.length)) as RpcMessage];
|
|
238
|
+
} catch {
|
|
239
|
+
return [];
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
return [JSON.parse(text) as RpcMessage];
|
|
245
|
+
} catch {
|
|
246
|
+
return [];
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A tool result as a page reads it. */
|
|
251
|
+
function toPageResult(result: CallToolResult | undefined): unknown {
|
|
252
|
+
const text = (result?.content ?? [])
|
|
253
|
+
.filter((c) => c.type === 'text' && typeof c.text === 'string')
|
|
254
|
+
.map((c) => c.text!)
|
|
255
|
+
.join('\n');
|
|
256
|
+
if (result?.isError) throw new PageToolError(text || 'The tool failed.');
|
|
257
|
+
if (result?.structuredContent !== undefined) return result.structuredContent;
|
|
258
|
+
try {
|
|
259
|
+
return JSON.parse(text);
|
|
260
|
+
} catch {
|
|
261
|
+
return text;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The viewer's answer about one page view's writes: asked once, on the first
|
|
267
|
+
* writing call, and held until the page is reloaded or left (a new instance).
|
|
268
|
+
*
|
|
269
|
+
* Allow holds: every later writing call runs without a card. Deny does not:
|
|
270
|
+
* it answers the calls that were waiting on that card, and the next writing
|
|
271
|
+
* call asks again. Calls that arrive while the card is open wait on that same
|
|
272
|
+
* card, so a page that fires ten writes at once sees one card, and every one
|
|
273
|
+
* of the ten gets the answer.
|
|
274
|
+
*/
|
|
275
|
+
export class PageConsent {
|
|
276
|
+
private allowed = false;
|
|
277
|
+
private asking: Promise<boolean | null> | null = null;
|
|
278
|
+
private readonly ask: () => Promise<boolean | null>;
|
|
279
|
+
|
|
280
|
+
/** `ask` shows the card: true for Allow, false for Deny, null when the view ended with the card still open. */
|
|
281
|
+
constructor(ask: () => Promise<boolean | null>) {
|
|
282
|
+
this.ask = ask;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Whether a card is open right now — no call of the page runs while it is. */
|
|
286
|
+
get open(): Promise<boolean | null> | null {
|
|
287
|
+
return this.asking;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Whether the viewer allows this page to write, asking them if no answer holds; null when nobody answered. */
|
|
291
|
+
request(): Promise<boolean | null> {
|
|
292
|
+
if (this.allowed) return Promise.resolve(true);
|
|
293
|
+
this.asking ??= this.ask().then(
|
|
294
|
+
(ok) => {
|
|
295
|
+
this.asking = null;
|
|
296
|
+
if (ok) this.allowed = true;
|
|
297
|
+
return ok;
|
|
298
|
+
},
|
|
299
|
+
() => {
|
|
300
|
+
this.asking = null;
|
|
301
|
+
return null;
|
|
302
|
+
},
|
|
303
|
+
);
|
|
304
|
+
return this.asking;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** A frame's message asking for a tool call. */
|
|
309
|
+
export interface ToolCallMessage {
|
|
310
|
+
type: 'bevel.tool.call';
|
|
311
|
+
requestId: string;
|
|
312
|
+
fn: PageToolFunction;
|
|
313
|
+
args: unknown[];
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** What goes back to the frame. */
|
|
317
|
+
export type ToolCallResponse =
|
|
318
|
+
| { type: 'bevel.tool.response'; requestId: string; ok: true; result: unknown }
|
|
319
|
+
| { type: 'bevel.tool.response'; requestId: string; ok: false; error: string; code?: string };
|
|
320
|
+
|
|
321
|
+
/** The frame's message, when it is a well-formed tool call; null otherwise. */
|
|
322
|
+
export function asToolCall(data: unknown): ToolCallMessage | null {
|
|
323
|
+
if (!data || typeof data !== 'object') return null;
|
|
324
|
+
const msg = data as Partial<ToolCallMessage>;
|
|
325
|
+
if (msg.type !== 'bevel.tool.call' || typeof msg.requestId !== 'string') return null;
|
|
326
|
+
if (typeof msg.fn !== 'string' || !PAGE_TOOL_FUNCTIONS.has(msg.fn)) return null;
|
|
327
|
+
return { type: 'bevel.tool.call', requestId: msg.requestId, fn: msg.fn, args: Array.isArray(msg.args) ? msg.args : [] };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Answer one of a page's tool calls: wait out an open card, ask for consent
|
|
332
|
+
* when the call may write, run it, and say how it went. Never throws — every
|
|
333
|
+
* outcome is a response for the frame.
|
|
334
|
+
*/
|
|
335
|
+
export async function answerToolCall(
|
|
336
|
+
msg: ToolCallMessage,
|
|
337
|
+
client: PageToolsClient,
|
|
338
|
+
consent: PageConsent,
|
|
339
|
+
): Promise<ToolCallResponse> {
|
|
340
|
+
const fail = (error: string, code?: string): ToolCallResponse => ({
|
|
341
|
+
type: 'bevel.tool.response',
|
|
342
|
+
requestId: msg.requestId,
|
|
343
|
+
ok: false,
|
|
344
|
+
error,
|
|
345
|
+
...(code ? { code } : {}),
|
|
346
|
+
});
|
|
347
|
+
try {
|
|
348
|
+
if (await client.mayWrite(msg.fn, msg.args)) {
|
|
349
|
+
// A write that arrives while the card is open joins it, and gets its answer.
|
|
350
|
+
const allowed = await consent.request();
|
|
351
|
+
// The view ended before the viewer chose: nothing ran, and nobody refused.
|
|
352
|
+
if (allowed === null) return fail('The page was closed before the viewer answered.', 'closed');
|
|
353
|
+
if (!allowed) {
|
|
354
|
+
const name = msg.fn === 'callToolChain' ? CHAIN_TOOL : String(msg.args[0] ?? '');
|
|
355
|
+
const args = msg.fn === 'callToolChain' ? { code: msg.args[0] } : msg.args[1];
|
|
356
|
+
void client.recordRefusal(name, args);
|
|
357
|
+
return fail(DENIED, DENIED);
|
|
358
|
+
}
|
|
359
|
+
} else {
|
|
360
|
+
// Nothing of the page runs while the viewer is being asked about it.
|
|
361
|
+
while (consent.open) await consent.open;
|
|
362
|
+
}
|
|
363
|
+
const [a, b] = msg.args;
|
|
364
|
+
const result =
|
|
365
|
+
msg.fn === 'searchTools'
|
|
366
|
+
? await client.searchTools(a)
|
|
367
|
+
: msg.fn === 'toolsInfo'
|
|
368
|
+
? await client.toolsInfo(a)
|
|
369
|
+
: msg.fn === 'callToolChain'
|
|
370
|
+
? await client.callToolChain(a)
|
|
371
|
+
: await client.callTool(a, b);
|
|
372
|
+
return { type: 'bevel.tool.response', requestId: msg.requestId, ok: true, result };
|
|
373
|
+
} catch (err) {
|
|
374
|
+
return fail(err instanceof Error ? err.message : String(err), err instanceof PageToolError ? err.code : undefined);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** A page's display name: its file name without the extension. */
|
|
379
|
+
export function pageName(path: string): string {
|
|
380
|
+
const file = path.slice(path.lastIndexOf('/') + 1);
|
|
381
|
+
const dot = file.lastIndexOf('.');
|
|
382
|
+
return dot > 0 ? file.slice(0, dot) : file;
|
|
383
|
+
}
|
|
@@ -46,6 +46,12 @@ export interface RendererSurface {
|
|
|
46
46
|
* verbatim: no anchor split, no repair, `#` is part of the name.
|
|
47
47
|
*/
|
|
48
48
|
openWorkspacePath(workspacePath: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Open `workspacePath` on its FILE PAGE, even where its path alone would
|
|
51
|
+
* open a skill's page — where an HTML page's tools are. The embed opens it
|
|
52
|
+
* in a new tab through its host, so the ask rides in the URL.
|
|
53
|
+
*/
|
|
54
|
+
openFilePage(workspacePath: string): void;
|
|
49
55
|
/** Follow a node-id link (`<id>` or `<id#heading>`), the copy-link form. */
|
|
50
56
|
openNodeId(idOrLink: string): void;
|
|
51
57
|
/** The absolute, shareable address of `workspacePath` — what a copy-link yields. */
|
|
@@ -18,7 +18,13 @@
|
|
|
18
18
|
* registers (and for a stand-in one in a test).
|
|
19
19
|
* - `kbFileUrl` and `resolveKbHref`: the app's address for a file on a
|
|
20
20
|
* branch, and what a link in a page resolves to there, which a link out
|
|
21
|
-
* of such a mount has to name
|
|
21
|
+
* of such a mount has to name; `kbFilePageUrl`, the file page's address
|
|
22
|
+
* even for a file a skill's page would otherwise claim, and
|
|
23
|
+
* `asksForFilePage`, whether a location's query makes that ask.
|
|
24
|
+
* - `OpenPageInPlatformContext`: how an HTML page mounted there is taken
|
|
25
|
+
* to the file page when it needs tools and the viewer picks Open in the
|
|
26
|
+
* platform (a skill page provides it; without it the renderer opens the
|
|
27
|
+
* file's own address).
|
|
22
28
|
*/
|
|
23
29
|
export {
|
|
24
30
|
CanDownloadContext,
|
|
@@ -30,4 +36,5 @@ export {
|
|
|
30
36
|
type RendererSurface,
|
|
31
37
|
} from './components/renderers';
|
|
32
38
|
export { RendererWorkspaceContext } from './components/renderers/rendererWorkspace';
|
|
33
|
-
export { kbFileUrl, resolveKbHref } from './routing/kb-routes';
|
|
39
|
+
export { asksForFilePage, kbFilePageUrl, kbFileUrl, resolveKbHref } from './routing/kb-routes';
|
|
40
|
+
export { OpenPageInPlatformContext } from './components/renderers/htmlToolBridge';
|
|
@@ -121,6 +121,13 @@ describe('useFileNav.openFile', () => {
|
|
|
121
121
|
);
|
|
122
122
|
});
|
|
123
123
|
|
|
124
|
+
it('opens a page on its FILE PAGE by an address that asks for it — a new tab carries no router state', () => {
|
|
125
|
+
navigateMock.mockClear();
|
|
126
|
+
const { result } = renderNav('main');
|
|
127
|
+
result.current.openFilePage('knowledge-base/Skills/qa-bridge/view.html');
|
|
128
|
+
expect(navigateMock).toHaveBeenCalledWith('/workspace/main/knowledge-base/Skills/qa-bridge/view.html?as=file');
|
|
129
|
+
});
|
|
130
|
+
|
|
124
131
|
it('opens a tree path verbatim even when a folder inside it is named like the kbDirName', () => {
|
|
125
132
|
navigateMock.mockClear();
|
|
126
133
|
const { result } = renderNav('alice/draft');
|
|
@@ -63,6 +63,26 @@ export function kbFileUrl(branch: string, relativePath: string = ''): string {
|
|
|
63
63
|
return `${KB_ROUTE_PREFIX}/${branchPart}/${pathPart}`;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
/**
|
|
67
|
+
* The query that asks for a file's FILE PAGE whatever its path would
|
|
68
|
+
* otherwise open as — under `Skills/` and `Plugins/` every file in a skill's
|
|
69
|
+
* folder is that skill's page. Router state (`rawFile`) does this within one
|
|
70
|
+
* tab; a page opened in a NEW tab — the embed's "Open in the platform" —
|
|
71
|
+
* carries nothing but its URL, so the ask has to ride in it.
|
|
72
|
+
*/
|
|
73
|
+
const FILE_PAGE_PARAM = 'as';
|
|
74
|
+
const FILE_PAGE_VALUE = 'file';
|
|
75
|
+
|
|
76
|
+
/** `kbFileUrl`, asking for the file page itself (see `FILE_PAGE_PARAM`). */
|
|
77
|
+
export function kbFilePageUrl(branch: string, relativePath: string): string {
|
|
78
|
+
return `${kbFileUrl(branch, relativePath)}?${FILE_PAGE_PARAM}=${FILE_PAGE_VALUE}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Whether a location's query is `kbFilePageUrl`'s ask for the file page. */
|
|
82
|
+
export function asksForFilePage(searchParams: URLSearchParams): boolean {
|
|
83
|
+
return searchParams.get(FILE_PAGE_PARAM) === FILE_PAGE_VALUE;
|
|
84
|
+
}
|
|
85
|
+
|
|
66
86
|
/**
|
|
67
87
|
* The canonical URL for a node: `/workspace/<branch>/<id>`. A bare id segment is
|
|
68
88
|
* disjoint from a `.md` path (no slash/dot — see `NODE_ID_LINK_RE`), so the route
|
|
@@ -464,6 +484,17 @@ export function useFileNav() {
|
|
|
464
484
|
[branch, navigate],
|
|
465
485
|
);
|
|
466
486
|
|
|
487
|
+
// The file page for a path a skill's page would otherwise claim (see
|
|
488
|
+
// `FILE_PAGE_PARAM`): an HTML page's "Open in the platform", whose tools
|
|
489
|
+
// are answered there and nowhere else.
|
|
490
|
+
const openFilePage = useCallback(
|
|
491
|
+
(path: string) => {
|
|
492
|
+
if (!branch) return;
|
|
493
|
+
navigate(kbFilePageUrl(branch, path));
|
|
494
|
+
},
|
|
495
|
+
[branch, navigate],
|
|
496
|
+
);
|
|
497
|
+
|
|
467
498
|
const closeFile = useCallback(() => {
|
|
468
499
|
if (!branch) return;
|
|
469
500
|
navigate(kbFileUrl(branch));
|
|
@@ -479,10 +510,11 @@ export function useFileNav() {
|
|
|
479
510
|
openFile: (pathOrUrl: string) => surface.openLink(pathOrUrl, ''),
|
|
480
511
|
openLink: surface.openLink,
|
|
481
512
|
openWorkspacePath: surface.openWorkspacePath,
|
|
513
|
+
openFilePage: surface.openFilePage,
|
|
482
514
|
closeFile: () => undefined,
|
|
483
515
|
};
|
|
484
516
|
}
|
|
485
|
-
return { openFile, openLink, openWorkspacePath, closeFile };
|
|
517
|
+
return { openFile, openLink, openWorkspacePath, openFilePage, closeFile };
|
|
486
518
|
}
|
|
487
519
|
|
|
488
520
|
/**
|
|
@@ -30,6 +30,26 @@
|
|
|
30
30
|
*/
|
|
31
31
|
export const HEADER_BAND = 'flex h-header flex-none items-center';
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Room for the ink of a page title that truncates.
|
|
35
|
+
*
|
|
36
|
+
* A title on the band is one line at `text-display`, whose line height (1.15)
|
|
37
|
+
* is tighter than the glyphs it sets: the tails of g, y and p, and accents
|
|
38
|
+
* above capitals, reach past the line box. `truncate` clips to that box, so
|
|
39
|
+
* "Everything" lost the bottoms of its g and y. Padding widens the clipping
|
|
40
|
+
* box by the overhang and the matching negative margin hands the space back,
|
|
41
|
+
* so the title still occupies exactly its line box and the band, which
|
|
42
|
+
* centres it, does not move.
|
|
43
|
+
*
|
|
44
|
+
* It goes on EVERY box that clips the title, not only the title: a title
|
|
45
|
+
* grouped with its breadcrumb or chips sits in an `overflow-hidden` wrapper
|
|
46
|
+
* whose height is the title's margin box, the bare line box, so the wrapper
|
|
47
|
+
* cuts off what the title's own room uncovered. The wrapper takes the same
|
|
48
|
+
* class, and since padding and margin cancel there too, nothing around it
|
|
49
|
+
* moves either.
|
|
50
|
+
*/
|
|
51
|
+
export const TITLE_INK_ROOM = 'py-1 -my-1';
|
|
52
|
+
|
|
33
53
|
/**
|
|
34
54
|
* The air above the band, for every column that shows one.
|
|
35
55
|
*
|