@guren/server 2.34.0 → 2.36.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.
Files changed (63) hide show
  1. package/dist/{DocsViewerServiceProvider-BVPZjwQp.js → DocsViewerServiceProvider-DzrxQoYh.js} +15 -4
  2. package/dist/Event-COT3f5Xd.js +28 -0
  3. package/dist/{Gate-C252SwRR.js → Gate-BHyDcDKo.js} +45 -5
  4. package/dist/{HttpException-BlQ2yEmT.js → HttpException-2tfZGamp.js} +8 -2
  5. package/dist/{McpServiceProvider-CXOokGax.js → McpServiceProvider-BOeQyt7u.js} +2 -0
  6. package/dist/PrivateChannel-1krGz028.js +187 -0
  7. package/dist/{Resource-BBKaFgXf.js → Resource-PhnO_wNO.js} +116 -15
  8. package/dist/agent/derive.d.ts +23 -1
  9. package/dist/agent/dispatch.d.ts +12 -1
  10. package/dist/agent/pipeline.d.ts +6 -0
  11. package/dist/agent/public.d.ts +1 -1
  12. package/dist/agent/public.js +1 -1
  13. package/dist/{api-token-DJcqSybf.js → api-token-Cs1myxf6.js} +16 -2
  14. package/dist/auth/index.js +2 -2
  15. package/dist/{auth-Bj9uEHuC.js → auth-DYWBlmpS.js} +2 -2
  16. package/dist/authorization/Gate.d.ts +4 -1
  17. package/dist/authorization/index.js +2 -2
  18. package/dist/{authorization-C81TXOWD.js → authorization-rxx6aprN.js} +1 -1
  19. package/dist/broadcasting/BroadcastManager.d.ts +19 -5
  20. package/dist/broadcasting/event-target.d.ts +9 -0
  21. package/dist/broadcasting/index.d.ts +3 -1
  22. package/dist/broadcasting/index.js +3 -2
  23. package/dist/broadcasting/sender-envelope.d.ts +26 -0
  24. package/dist/broadcasting/types.d.ts +27 -2
  25. package/dist/{broadcasting-3pvO94xV.js → broadcasting-Bh6QoMpy.js} +51 -96
  26. package/dist/{contained-path-BkNSBljW.js → contained-path-DOVauNQC.js} +1 -22
  27. package/dist/{context-af2n5abO.js → context--l2HdOhy.js} +1 -1
  28. package/dist/{dev-banner-B_QaY29h.js → dev-banner-DGxB3HGY.js} +8 -4
  29. package/dist/{dispatch-ENWpBxbE.js → dispatch-CDNqcB3Q.js} +51 -12
  30. package/dist/errors/ExceptionHandler.d.ts +5 -1
  31. package/dist/errors/HttpException.d.ts +6 -0
  32. package/dist/errors/exceptions/NotFoundHttpException.d.ts +2 -0
  33. package/dist/errors/wants-html.d.ts +7 -0
  34. package/dist/{errors-JpkcCjjn.js → errors-C8neC8go.js} +1 -1
  35. package/dist/events/index.js +2 -1
  36. package/dist/{events-B6gfJkCH.js → events-DW197Nur.js} +2 -28
  37. package/dist/http/dev-banner.d.ts +6 -1
  38. package/dist/http/middleware/csrf.d.ts +1 -1
  39. package/dist/http/middleware/redirect-safety.d.ts +8 -0
  40. package/dist/http/vite-dev-server.d.ts +18 -1
  41. package/dist/http/vite-manifest.d.ts +4 -1
  42. package/dist/index.d.ts +7 -7
  43. package/dist/index.js +305 -161
  44. package/dist/internal/agent-principal.d.ts +8 -0
  45. package/dist/internal/testing.d.ts +1 -0
  46. package/dist/internal/testing.js +4 -4
  47. package/dist/mcp/index.js +1 -1
  48. package/dist/mvc/Router.d.ts +13 -0
  49. package/dist/mvc/inertia/InertiaEngine.d.ts +3 -0
  50. package/dist/mvc/inertia/props.d.ts +54 -3
  51. package/dist/providers/InertiaServiceProvider.d.ts +7 -0
  52. package/dist/runtime/index.js +5 -3
  53. package/dist/storage/index.js +1 -1
  54. package/dist/{storage-YPbsV9ju.js → storage-ziIKgHON.js} +2 -1
  55. package/dist/trim-slashes-BLY9hKAa.js +22 -0
  56. package/dist/vite/index.d.ts +2 -0
  57. package/dist/vite/index.js +283 -1
  58. package/dist/vite/mcp-app.d.ts +59 -0
  59. package/dist/vite/plugin.d.ts +12 -0
  60. package/dist/{vite-manifest-DO0pU1vm.js → vite-dev-server-Ag90otai.js} +25 -114
  61. package/dist/vite-manifest-BdXRybeq.js +129 -0
  62. package/package.json +1 -1
  63. package/dist/host-port-t6wQFaRu.js +0 -15
@@ -39,3 +39,11 @@ export declare function readAgentPrincipal(request: Request): InstalledAgentPrin
39
39
  export declare function markAgentDispatch(request: Request): Request;
40
40
  /** Whether the pipeline dispatched this exact request object. */
41
41
  export declare function isAgentDispatch(request: Request): boolean;
42
+ /**
43
+ * Mark `request` as allowed only the named shared Inertia props (RFC 0038 §6),
44
+ * returning that same object. A surface opts in through the pipeline's
45
+ * `sharedProps`; nothing on the wire can ask for it, and nothing can widen it.
46
+ */
47
+ export declare function installAgentSharedProps(request: Request, keys: readonly string[]): Request;
48
+ /** The shared props this exact request may carry, or `undefined` for all of them. */
49
+ export declare function readAgentSharedProps(request: Request): ReadonlySet<string> | undefined;
@@ -8,6 +8,7 @@
8
8
  export { Controller } from '../mvc/Controller.js';
9
9
  export type { InertiaPageContractLike, InertiaResponseOptions } from '../mvc/Controller.js';
10
10
  export { acceptsJson, buildInertiaPage, INERTIA_VARY, mergeInertiaVary, serializePage } from '../mvc/inertia/InertiaEngine.js';
11
+ export { always, defer, live } from '../mvc/inertia/props.js';
11
12
  export { withDefaultHeaders } from '../support/default-headers.js';
12
13
  export { Resource, JsonResource, collect } from '../http/resources/Resource.js';
13
14
  export { ValidationException } from '../errors/exceptions/ValidationException.js';
@@ -1,6 +1,6 @@
1
- import { S as serializePage, T as withDefaultHeaders, _ as INERTIA_VARY, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as mergeInertiaVary, y as buildInertiaPage } from "../Resource-BBKaFgXf.js";
1
+ import { D as defer, E as always, S as serializePage, T as withDefaultHeaders, _ as INERTIA_VARY, f as definePlugin, i as Controller, j as live, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as mergeInertiaVary, y as buildInertiaPage } from "../Resource-PhnO_wNO.js";
2
2
  import { r as formatValidationErrors } from "../request-CLOYytGP.js";
3
- import { n as ValidationException } from "../errors-JpkcCjjn.js";
3
+ import { n as ValidationException } from "../errors-C8neC8go.js";
4
4
  import { n as ServiceProvider } from "../ServiceProvider-G0YclITd.js";
5
- import { o as AuthenticationException } from "../context-af2n5abO.js";
6
- export { AuthenticationException, Controller, INERTIA_VARY, JsonResource, Resource, ServiceProvider, ValidationException, acceptsJson, buildInertiaPage, collect, defineModule, definePlugin, formatValidationErrors, mergeInertiaVary, serializePage, withDefaultHeaders };
5
+ import { o as AuthenticationException } from "../context--l2HdOhy.js";
6
+ export { AuthenticationException, Controller, INERTIA_VARY, JsonResource, Resource, ServiceProvider, ValidationException, acceptsJson, always, buildInertiaPage, collect, defer, defineModule, definePlugin, formatValidationErrors, live, mergeInertiaVary, serializePage, withDefaultHeaders };
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as McpServiceProvider } from "../McpServiceProvider-CXOokGax.js";
1
+ import { t as McpServiceProvider } from "../McpServiceProvider-BOeQyt7u.js";
2
2
  export { McpServiceProvider };
@@ -125,6 +125,19 @@ export interface AgentRouteMetadata {
125
125
  approval?: 'required';
126
126
  /** Argument fields masked in agent audit logs. */
127
127
  redact?: string[];
128
+ /** Render this tool's result in an MCP Apps host with an Inertia page (RFC 0038). */
129
+ ui?: AgentUiPage | AgentRouteUi;
130
+ }
131
+ /** A page by id: a generated `PageContract` (anything with a string `id`), or the id itself. */
132
+ export type AgentUiPage = {
133
+ readonly id: string;
134
+ } | string;
135
+ /** The object form of `AgentRouteMetadata.ui` (RFC 0038 §1). */
136
+ export interface AgentRouteUi {
137
+ /** Absent for a tool a view calls but that renders no view of its own. */
138
+ page?: AgentUiPage;
139
+ /** MCP Apps `_meta.ui.visibility`. Default `['model', 'app']`. */
140
+ visibility?: ReadonlyArray<'model' | 'app'>;
128
141
  }
129
142
  /** A registered route definition, as handed out for introspection. */
130
143
  export interface RouteDefinition {
@@ -1,4 +1,5 @@
1
1
  import type { ContainerLike } from "../../container/types.js";
2
+ import { type LivePropEntry } from "./props.js";
2
3
  /**
3
4
  * Per-response form of {@link InertiaDocumentOptions}, already resolved to
4
5
  * strings. Each field overrides the app-wide
@@ -34,6 +35,8 @@ export interface InertiaPagePayload {
34
35
  version?: string;
35
36
  /** Deferred prop keys by group, announced on a full visit and fetched by the client per group. */
36
37
  deferredProps?: Record<string, string[]>;
38
+ /** Live prop listeners by key (RFC 0037): every live prop on a full visit, the resolved ones on a partial reload. */
39
+ liveProps?: Record<string, LivePropEntry>;
37
40
  }
38
41
  export interface InertiaSsrContext {
39
42
  page: InertiaPagePayload;
@@ -4,8 +4,10 @@
4
4
  * `@guren/testing`'s controller mock resolves through the same function, so a
5
5
  * test cannot pass on a prop set production would not send.
6
6
  */
7
+ import { type BroadcastTarget } from '../../broadcasting/event-target.js';
7
8
  declare const DEFERRED_BRAND: unique symbol;
8
9
  declare const ALWAYS_BRAND: unique symbol;
10
+ declare const LIVE_BRAND: unique symbol;
9
11
  export interface AlwaysProp<T> {
10
12
  readonly [ALWAYS_BRAND]: true;
11
13
  readonly value: T;
@@ -33,13 +35,60 @@ export interface DeferredProp<T> {
33
35
  */
34
36
  export declare function defer<T>(resolve: () => T, group?: string): DeferredProp<Awaited<T>>;
35
37
  export declare function isDeferredProp(value: unknown): value is DeferredProp<unknown>;
38
+ /** The wire shape of one `liveProps` entry, restated from `@inertiajs/core`, which the server does not depend on. */
39
+ export interface LivePropEntry {
40
+ readonly listeners: readonly LiveListener[];
41
+ /** Milliseconds between two reloads of the prop. */
42
+ readonly throttle?: number;
43
+ }
44
+ export interface LiveListener {
45
+ /** Unprefixed, as Inertia expects: the transport adds the prefix back. */
46
+ readonly channel: {
47
+ readonly name: string;
48
+ readonly type: LiveChannelType;
49
+ };
50
+ readonly events: readonly string[];
51
+ }
52
+ export type LiveChannelType = 'public' | 'private' | 'presence';
53
+ /** An event named by hand, for a sender that is not an event class. */
54
+ export interface LiveListenerInput {
55
+ readonly event: string;
56
+ /** Wire names, prefix included: `private-orders.1`, `presence-chat.2`, `announcements`. */
57
+ readonly channel: string | readonly string[];
58
+ }
59
+ export type LiveEvent = BroadcastTarget;
60
+ export interface LiveOptions {
61
+ /** Event instances (their channels and name are read off them) or hand-named listeners. */
62
+ readonly on: LiveEvent | LiveListenerInput | readonly (LiveEvent | LiveListenerInput)[];
63
+ /** Milliseconds between two reloads of this prop; the client's default when absent. */
64
+ readonly throttle?: number;
65
+ }
66
+ export interface LiveProp<V> {
67
+ readonly [LIVE_BRAND]: true;
68
+ readonly value: V;
69
+ readonly entry: LivePropEntry;
70
+ /** The value, as `always()` serializes, so props serialized before the engine sees them carry no brand. */
71
+ toJSON(): unknown;
72
+ }
73
+ /**
74
+ * A prop the client reloads whenever one of the given broadcast events
75
+ * arrives (Inertia's live props, RFC 0037). The entry is computed here, so a
76
+ * mistake throws in the action that wrote it. Wraps any other prop input.
77
+ */
78
+ export declare function live<V>(value: V, options: LiveOptions): LiveProp<V>;
79
+ export declare function isLiveProp(value: unknown): value is LiveProp<unknown>;
80
+ type PlainPropInput<T> = T | DeferredProp<T> | (() => T | Promise<T>);
81
+ type BasePropInput<T> = PlainPropInput<T> | AlwaysProp<PlainPropInput<T>>;
36
82
  /** What a controller may pass for a prop the page declares as `T`. */
37
- export type InertiaPropInput<T> = T | DeferredProp<T> | AlwaysProp<T> | (() => T | Promise<T>);
83
+ export type InertiaPropInput<T> = BasePropInput<T> | LiveProp<BasePropInput<T>>;
38
84
  export type InertiaPropsInput<Props> = {
39
85
  [K in keyof Props]: InertiaPropInput<Props[K]>;
40
86
  };
41
- /** The value the page receives for one prop input: a deferred, always or lazy prop as its resolved type. */
42
- export type ResolvedInertiaProp<V> = V extends DeferredProp<unknown> ? Awaited<ReturnType<V['resolve']>> : V extends AlwaysProp<unknown> ? V['value'] : V extends () => infer R ? Awaited<R> : V;
87
+ /**
88
+ * The value the page receives for one prop input. `always()` recurses: the
89
+ * resolver unwraps it and then runs a deferred or lazy value inside.
90
+ */
91
+ export type ResolvedInertiaProp<V> = V extends LiveProp<infer Inner> ? ResolvedInertiaProp<Inner> : V extends AlwaysProp<infer Inner> ? ResolvedInertiaProp<Inner> : V extends DeferredProp<unknown> ? Awaited<ReturnType<V['resolve']>> : V extends () => infer R ? Awaited<R> : V;
43
92
  export type ResolvedInertiaProps<Props> = {
44
93
  [K in keyof Props]: ResolvedInertiaProp<Props[K]>;
45
94
  };
@@ -52,6 +101,8 @@ export interface ResolvedInertiaPage {
52
101
  readonly props: Record<string, unknown>;
53
102
  /** Present on a full visit that carried at least one deferred prop. */
54
103
  readonly deferredProps?: Record<string, string[]>;
104
+ /** The listeners of every live prop the response resolves (all of them on a full visit). */
105
+ readonly liveProps?: Record<string, LivePropEntry>;
55
106
  }
56
107
  /**
57
108
  * The partial reload a request asks for, or undefined for a full visit. A
@@ -8,6 +8,13 @@ export declare class InertiaServiceProvider extends ServiceProvider {
8
8
  boot(): void;
9
9
  /** ValidationException on Inertia requests; others fall through to JSON 422. */
10
10
  private registerValidationRenderer;
11
+ /**
12
+ * The request's host, and the one `APP_URL` names (what `config/http.ts`'s host
13
+ * authorization and the auth scaffold's links key on): a proxy that does not
14
+ * forward `Host` hands the app its upstream address instead. `X-Forwarded-Host`
15
+ * is not read, since no app-wide trusted-proxy setting says when it is genuine.
16
+ */
17
+ private refererHosts;
11
18
  /**
12
19
  * Auto-inject flashed `errors` into shared props. Scoped to this app's
13
20
  * container so a second Application booted in the same process keeps its
@@ -1,8 +1,10 @@
1
- import { a as trimTrailingSlashes, n as isRealPathWithin, t as isPathWithin } from "../contained-path-BkNSBljW.js";
1
+ import { n as trimTrailingSlashes } from "../trim-slashes-BLY9hKAa.js";
2
2
  import { n as parseImportMap } from "../inertia-defaults-BjrcT7za.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
- import { a as getManifestCss, c as isViteProduction, d as startViteDevServer, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-DO0pU1vm.js";
5
- import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-B_QaY29h.js";
4
+ import { a as getManifestCss, c as isViteProduction, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-BdXRybeq.js";
5
+ import { n as startViteDevServer } from "../vite-dev-server-Ag90otai.js";
6
+ import { n as isRealPathWithin, t as isPathWithin } from "../contained-path-DOVauNQC.js";
7
+ import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-DGxB3HGY.js";
6
8
  import { createRequire } from "node:module";
7
9
  import { dirname, extname, join, resolve } from "node:path";
8
10
  import { fileURLToPath } from "node:url";
@@ -1,2 +1,2 @@
1
- import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as MemoryDriver, t as StorageManager } from "../storage-YPbsV9ju.js";
1
+ import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as MemoryDriver, t as StorageManager } from "../storage-ziIKgHON.js";
2
2
  export { LocalDriver, MemoryDriver, S3Driver, StorageManager, createStorageManager };
@@ -1,6 +1,7 @@
1
- import { i as trimSlashes, r as realPathOfNearestExisting, t as isPathWithin } from "./contained-path-BkNSBljW.js";
1
+ import { t as trimSlashes } from "./trim-slashes-BLY9hKAa.js";
2
2
  import { t as warnOnce } from "./warn-once-p-IlMjra.js";
3
3
  import { t as describeDriverMap } from "./driver-map-BhITaLcy.js";
4
+ import { r as realPathOfNearestExisting, t as isPathWithin } from "./contained-path-DOVauNQC.js";
4
5
  import { dirname, join, relative, resolve, sep } from "node:path";
5
6
  import { copyFile, lstat, mkdir, open, readFile, readdir, readlink, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
6
7
  import { existsSync } from "node:fs";
@@ -0,0 +1,22 @@
1
+ //#region src/support/trim-slashes.ts
2
+ /**
3
+ * No regex: patterns like `/\/+$/` backtrack quadratically on long slash runs
4
+ * mid-string, and several call sites feed request-derived paths.
5
+ *
6
+ * Twins that cannot import this module: `@guren/cli` (`src/utils.ts`) and
7
+ * `@guren/plugin-cloudflare` (`src/storage/R2Driver.ts`) — keep them in step.
8
+ */
9
+ function trimTrailingSlashes(value) {
10
+ let end = value.length;
11
+ while (end > 0 && value[end - 1] === "/") end--;
12
+ return value.slice(0, end);
13
+ }
14
+ function trimSlashes(value) {
15
+ let start = 0;
16
+ let end = value.length;
17
+ while (start < end && value[start] === "/") start++;
18
+ while (end > start && value[end - 1] === "/") end--;
19
+ return value.slice(start, end);
20
+ }
21
+ //#endregion
22
+ export { trimTrailingSlashes as n, trimSlashes as t };
@@ -1,2 +1,4 @@
1
1
  export { gurenVitePlugin as default, gurenVitePlugin } from './plugin.js';
2
2
  export type { GurenVitePluginOptions } from './plugin.js';
3
+ export { MCP_APP_MODE, MCP_APP_MODULE, MCP_APP_SETUP_FILE, renderPagesModule } from './mcp-app.js';
4
+ export type { GurenMcpAppOptions } from './mcp-app.js';
@@ -1,5 +1,163 @@
1
+ import { createRequire } from "node:module";
2
+ import { createHash } from "node:crypto";
1
3
  import path from "node:path";
2
4
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ //#region src/vite/mcp-app.ts
6
+ /**
7
+ * `vite build --mode mcp-app` (RFC 0038 §4): one self-contained HTML document
8
+ * per page an `.agent({ ui })` route names, everything inlined, since a host's
9
+ * default CSP allows no origin but its own sandbox. The mode's own build only
10
+ * drives: each page is a nested build of the app's Vite config with one entry
11
+ * and no code splitting, which a single multi-input build cannot give.
12
+ */
13
+ const MCP_APP_MODE = "mcp-app";
14
+ /** Names the page a nested build makes; unset in the driving build. */
15
+ const MCP_APP_PAGE_ENV = "GUREN_MCP_APP_PAGE";
16
+ /** `rolldown` or `rollup`: which bundler the driver's Vite runs, so a page build disables splitting in its spelling. */
17
+ const MCP_APP_BUNDLER_ENV = "GUREN_MCP_APP_BUNDLER";
18
+ const MCP_APP_OUT_DIR = ".guren/mcp-app";
19
+ const MCP_APP_MODULE = ".guren/mcp-app/index.gen.ts";
20
+ const MCP_APP_SETUP_FILE = "resources/js/mcp-app.tsx";
21
+ const MCP_APP_ENTRY_ID = "\0guren-mcp-app-entry";
22
+ const MCP_APP_DRIVER_ID = "\0guren-mcp-app-driver";
23
+ const AGENTS_MODULE = ".guren/agents.gen.ts";
24
+ const PAGE_EXTENSIONS = [
25
+ ".tsx",
26
+ ".jsx",
27
+ ".ts",
28
+ ".js"
29
+ ];
30
+ /** The page ids codegen wrote as `agentUiPages`; none when the app declares no `ui` route. */
31
+ function readAgentUiPages(root) {
32
+ let source;
33
+ try {
34
+ source = readFileSync(path.resolve(root, AGENTS_MODULE), "utf8");
35
+ } catch {
36
+ return [];
37
+ }
38
+ if (!source.includes("export const agentUiPages")) return [];
39
+ const literal = /^export const agentUiPages = (\[.*\]) as const$/mu.exec(source)?.[1];
40
+ const parsed = literal === void 0 ? void 0 : JSON.parse(literal);
41
+ if (!Array.isArray(parsed)) throw new Error(`mcp-app: cannot read agentUiPages in ${AGENTS_MODULE}; run \`guren codegen\`.`);
42
+ return parsed.filter((id) => typeof id === "string");
43
+ }
44
+ /** The page module an id names, by the rule `pages.gen.ts` is written with: `pages/<id>` under the resources directory. */
45
+ function resolvePageFile(context, id) {
46
+ const base = path.resolve(context.root, context.resourcesDir, "pages", id);
47
+ return PAGE_EXTENSIONS.map((extension) => `${base}${extension}`).find((file) => existsSync(file));
48
+ }
49
+ function renderSetupTemplate(stylesheet) {
50
+ return `${stylesheet ? `import '${stylesheet}'\n` : ""}import React from 'react'
51
+ import { createRoot } from 'react-dom/client'
52
+ import { ErrorBoundary } from '@guren/inertia-client'
53
+ import type { StartMcpAppOptions } from '@guren/inertia-client/mcp-app'
54
+
55
+ // What every MCP App view mounts with (RFC 0038 §4). Owned by the app: keep its
56
+ // providers and stylesheet in step with resources/js/app.tsx.
57
+ export const setup: StartMcpAppOptions['setup'] = ({ el, App, props }) => {
58
+ createRoot(el).render(
59
+ React.createElement(ErrorBoundary, null,
60
+ React.createElement(App, props as any),
61
+ ),
62
+ )
63
+ }
64
+ `;
65
+ }
66
+ /** Writes the setup file on the first build; an existing one is the app's and is never touched. */
67
+ function ensureSetupFile(context) {
68
+ const file = path.resolve(context.root, context.setupFile);
69
+ const css = path.resolve(context.root, context.resourcesDir, "../css/app.css");
70
+ const stylesheet = existsSync(css) ? toImportPath(path.dirname(file), css) : void 0;
71
+ mkdirSync(path.dirname(file), { recursive: true });
72
+ try {
73
+ writeFileSync(file, renderSetupTemplate(stylesheet), { flag: "wx" });
74
+ } catch (error) {
75
+ if (error.code !== "EEXIST") throw error;
76
+ }
77
+ return file;
78
+ }
79
+ function renderPageEntry(id, setupFile, pageFile) {
80
+ return `import { startMcpApp } from '@guren/inertia-client/mcp-app'
81
+ import * as app from ${JSON.stringify(setupFile)}
82
+ import Page from ${JSON.stringify(pageFile)}
83
+
84
+ const id = ${JSON.stringify(id)}
85
+ void startMcpApp({
86
+ ...app,
87
+ resolve: async (name) => {
88
+ if (name === id) return { default: Page }
89
+ throw new Error(\`This view bundles the page "\${id}" only, not "\${name}".\`)
90
+ },
91
+ })
92
+ `;
93
+ }
94
+ function renderPageDocument(scripts, styles) {
95
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${styles.map((css) => `<style>${css.replaceAll("</style", "<\\/style")}</style>`).join("")}</head><body><div id="app"></div>${scripts.map((js) => `<script type="module">${js.replaceAll("<\/script", "<\\/script")}<\/script>`).join("")}</body></html>`;
96
+ }
97
+ function contentHash(html) {
98
+ return createHash("sha256").update(html).digest("hex").slice(0, 12);
99
+ }
100
+ function pageDocumentFile(root, id) {
101
+ return path.resolve(root, MCP_APP_OUT_DIR, "pages", `${id}.html`);
102
+ }
103
+ /** `.guren/mcp-app/index.gen.ts`, the shape `mcpPlugin({ ui: { pages } })` imports. */
104
+ function renderPagesModule(pages) {
105
+ return `// Generated by \`vite build --mode mcp-app\` — DO NOT EDIT.
106
+ export const mcpAppPages: Record<string, { html: string; hash: string }> = {
107
+ ${Object.entries(pages).map(([id, page]) => ` ${JSON.stringify(id)}: { html: ${JSON.stringify(page.html)}, hash: ${JSON.stringify(page.hash)} },`).join("\n")}
108
+ }
109
+ `;
110
+ }
111
+ /** One page's document from its bundle, and the files it could not inline. */
112
+ function documentFromBundle(items) {
113
+ const scripts = items.filter((item) => item.type === "chunk" && item.isEntry).map((item) => item.code ?? "");
114
+ const styles = items.filter((item) => item.type === "asset" && item.fileName.endsWith(".css")).map((item) => typeof item.source === "string" ? item.source : new TextDecoder().decode(item.source));
115
+ const leftovers = items.filter((item) => !(item.type === "chunk" && item.isEntry) && !(item.type === "asset" && item.fileName.endsWith(".css"))).map((item) => item.fileName);
116
+ return {
117
+ html: renderPageDocument(scripts, styles),
118
+ leftovers
119
+ };
120
+ }
121
+ /** The driving build: every page in turn, then the module the plugin imports. */
122
+ async function runMcpAppBuild(options) {
123
+ const { context } = options;
124
+ const ids = readAgentUiPages(context.root);
125
+ rmSync(path.resolve(context.root, MCP_APP_OUT_DIR, "pages"), {
126
+ recursive: true,
127
+ force: true
128
+ });
129
+ const pages = {};
130
+ if (ids.length > 0) {
131
+ assertExtAppsInstalled(context.root);
132
+ ensureSetupFile(context);
133
+ for (const id of ids) {
134
+ if (!resolvePageFile(context, id)) throw new Error(`The page "${id}" an .agent({ ui }) route names has no file under ${context.resourcesDir}/pages/.`);
135
+ await options.buildPage(id);
136
+ const html = readFileSync(pageDocumentFile(context.root, id), "utf8");
137
+ pages[id] = {
138
+ html,
139
+ hash: contentHash(html)
140
+ };
141
+ options.log?.(`mcp-app: ${id} (${(html.length / 1024).toFixed(1)} KB)`);
142
+ }
143
+ } else options.log?.("mcp-app: no .agent({ ui }) route in .guren/agents.gen.ts; run `guren codegen` after adding one.");
144
+ const module = path.resolve(context.root, MCP_APP_MODULE);
145
+ mkdirSync(path.dirname(module), { recursive: true });
146
+ writeFileSync(module, renderPagesModule(pages));
147
+ return pages;
148
+ }
149
+ function assertExtAppsInstalled(root) {
150
+ try {
151
+ createRequire(path.resolve(root, "package.json")).resolve("@modelcontextprotocol/ext-apps");
152
+ } catch {
153
+ throw new Error("MCP App views need @modelcontextprotocol/ext-apps: run `bun add @modelcontextprotocol/ext-apps`.");
154
+ }
155
+ }
156
+ function toImportPath(fromDir, file) {
157
+ const relative = path.relative(fromDir, file).split(path.sep).join("/");
158
+ return relative.startsWith(".") ? relative : `./${relative}`;
159
+ }
160
+ //#endregion
3
161
  //#region src/vite/plugin.ts
4
162
  /** Where the generated shell goes; `.guren/` is already gitignored and codegen-owned. */
5
163
  const PROTOTYPE_SHELL_FILE = ".guren/prototype/index.html";
@@ -26,19 +184,60 @@ function gurenVitePlugin(options = {}) {
26
184
  ...options
27
185
  };
28
186
  let prototype;
187
+ let mcpApp;
29
188
  return {
30
189
  name: "guren:vite-config",
31
190
  enforce: "pre",
32
191
  config(config, env) {
192
+ mcpApp = void 0;
33
193
  if (env?.mode === "prototype") {
34
194
  prototype = ensurePrototype(config, resolved);
35
195
  return;
36
196
  }
37
197
  prototype = void 0;
198
+ if (env?.mode === "mcp-app") {
199
+ mcpApp = ensureMcpApp(config, resolved, process.env[MCP_APP_PAGE_ENV]);
200
+ return;
201
+ }
38
202
  ensureDefaults(config, resolved, env);
39
203
  },
40
204
  configResolved(config) {
41
205
  if (prototype) prototype.outDir = path.resolve(config.root ?? prototype.root, config.build?.outDir ?? prototype.outDir);
206
+ if (mcpApp) {
207
+ mcpApp.configFile = config.configFile;
208
+ mcpApp.logLevel = config.logLevel;
209
+ }
210
+ },
211
+ resolveId(id) {
212
+ if (mcpApp && (id === "\0guren-mcp-app-entry" || id === "\0guren-mcp-app-driver")) return id;
213
+ return null;
214
+ },
215
+ load(id) {
216
+ if (!mcpApp) return null;
217
+ if (id === "\0guren-mcp-app-driver") return "export {}\n";
218
+ if (id === "\0guren-mcp-app-entry" && mcpApp.page) return renderPageEntry(mcpApp.page.id, mcpApp.page.setupFile, mcpApp.page.pageFile);
219
+ return null;
220
+ },
221
+ generateBundle: {
222
+ order: "post",
223
+ handler(_output, bundle) {
224
+ const page = mcpApp?.page;
225
+ if (!page) return;
226
+ const { html, leftovers } = documentFromBundle(Object.values(bundle));
227
+ if (leftovers.length > 0) this.warn(`mcp-app: ${page.id} produced files a view cannot load, left out of its document: ${leftovers.join(", ")}`);
228
+ const file = pageDocumentFile(mcpApp.context.root, page.id);
229
+ mkdirSync(path.dirname(file), { recursive: true });
230
+ writeFileSync(file, html);
231
+ }
232
+ },
233
+ async closeBundle() {
234
+ const driver = mcpApp;
235
+ if (!driver || driver.page) return;
236
+ await runMcpAppBuild({
237
+ context: driver.context,
238
+ buildPage: (id) => buildMcpAppPage(driver, id),
239
+ log: (message) => console.log(message)
240
+ });
42
241
  },
43
242
  configureServer(server) {
44
243
  if (!prototype) return;
@@ -65,6 +264,89 @@ function gurenVitePlugin(options = {}) {
65
264
  };
66
265
  }
67
266
  /**
267
+ * Both builds own `build` outright: nothing is written by Vite itself (the
268
+ * page build's `generateBundle` writes its document), and a page build is one
269
+ * entry with every dynamic import, stylesheet and asset inlined.
270
+ */
271
+ function ensureMcpApp(config, options, pageId) {
272
+ const root = resolveRoot(config.root);
273
+ const context = {
274
+ root,
275
+ resourcesDir: options.resourcesDir,
276
+ setupFile: options.mcpApp?.entry ?? "resources/js/mcp-app.tsx"
277
+ };
278
+ config.define ??= {};
279
+ config.define["import.meta.env.GUREN_PROTOTYPE"] ??= "false";
280
+ ensureAliases(config, options, root);
281
+ config.publicDir = false;
282
+ const shared = {
283
+ outDir: path.resolve(root, MCP_APP_OUT_DIR, "build"),
284
+ write: false,
285
+ emptyOutDir: false,
286
+ copyPublicDir: false,
287
+ manifest: false,
288
+ ssrManifest: false
289
+ };
290
+ if (pageId === void 0) {
291
+ config.build = {
292
+ ...config.build,
293
+ ...shared,
294
+ rollupOptions: { input: MCP_APP_DRIVER_ID }
295
+ };
296
+ return { context };
297
+ }
298
+ const pageFile = resolvePageFile(context, pageId);
299
+ if (!pageFile) throw new Error(`mcp-app: no page file for "${pageId}" under ${options.resourcesDir}/pages/.`);
300
+ config.build = {
301
+ ...config.build,
302
+ ...shared,
303
+ cssCodeSplit: false,
304
+ assetsInlineLimit: () => true,
305
+ modulePreload: false,
306
+ rollupOptions: {
307
+ input: MCP_APP_ENTRY_ID,
308
+ output: process.env["GUREN_MCP_APP_BUNDLER"] === "rolldown" ? {
309
+ format: "es",
310
+ codeSplitting: false
311
+ } : {
312
+ format: "es",
313
+ inlineDynamicImports: true
314
+ }
315
+ }
316
+ };
317
+ return {
318
+ context,
319
+ page: {
320
+ id: pageId,
321
+ setupFile: path.resolve(root, context.setupFile),
322
+ pageFile
323
+ }
324
+ };
325
+ }
326
+ /** A nested build of the app's own Vite config, so its plugins (React, Tailwind) apply to the view as to the app. */
327
+ async function buildMcpAppPage(driver, id) {
328
+ const vite = await import("vite");
329
+ const previous = process.env[MCP_APP_PAGE_ENV];
330
+ const previousBundler = process.env[MCP_APP_BUNDLER_ENV];
331
+ process.env[MCP_APP_PAGE_ENV] = id;
332
+ process.env[MCP_APP_BUNDLER_ENV] = vite.rolldownVersion ? "rolldown" : "rollup";
333
+ try {
334
+ await vite.build({
335
+ root: driver.context.root,
336
+ configFile: driver.configFile,
337
+ mode: MCP_APP_MODE,
338
+ logLevel: driver.logLevel ?? "warn"
339
+ });
340
+ } finally {
341
+ restoreEnv(MCP_APP_PAGE_ENV, previous);
342
+ restoreEnv(MCP_APP_BUNDLER_ENV, previousBundler);
343
+ }
344
+ }
345
+ function restoreEnv(name, value) {
346
+ if (value === void 0) delete process.env[name];
347
+ else process.env[name] = value;
348
+ }
349
+ /**
68
350
  * The prototype branch, taken before the ordinary client defaults so none of
69
351
  * `ensureBuild`'s outDir/base/publicDir reasoning applies: there is no server
70
352
  * to serve `public/`, no manifest to read, and the entry is an HTML shell.
@@ -289,4 +571,4 @@ function normalizeRollupOutput(output) {
289
571
  return output ?? {};
290
572
  }
291
573
  //#endregion
292
- export { gurenVitePlugin as default, gurenVitePlugin };
574
+ export { MCP_APP_MODE, MCP_APP_MODULE, MCP_APP_SETUP_FILE, gurenVitePlugin as default, gurenVitePlugin, renderPagesModule };
@@ -0,0 +1,59 @@
1
+ export declare const MCP_APP_MODE = "mcp-app";
2
+ /** Names the page a nested build makes; unset in the driving build. */
3
+ export declare const MCP_APP_PAGE_ENV = "GUREN_MCP_APP_PAGE";
4
+ /** `rolldown` or `rollup`: which bundler the driver's Vite runs, so a page build disables splitting in its spelling. */
5
+ export declare const MCP_APP_BUNDLER_ENV = "GUREN_MCP_APP_BUNDLER";
6
+ export declare const MCP_APP_OUT_DIR = ".guren/mcp-app";
7
+ export declare const MCP_APP_MODULE = ".guren/mcp-app/index.gen.ts";
8
+ export declare const MCP_APP_SETUP_FILE = "resources/js/mcp-app.tsx";
9
+ export declare const MCP_APP_ENTRY_ID = "\0guren-mcp-app-entry";
10
+ export declare const MCP_APP_DRIVER_ID = "\0guren-mcp-app-driver";
11
+ export interface GurenMcpAppOptions {
12
+ /** The app-owned setup every view mounts with, relative to the root. Defaults to `resources/js/mcp-app.tsx`. */
13
+ entry?: string;
14
+ }
15
+ export interface McpAppBuildContext {
16
+ root: string;
17
+ resourcesDir: string;
18
+ setupFile: string;
19
+ }
20
+ /** The page ids codegen wrote as `agentUiPages`; none when the app declares no `ui` route. */
21
+ export declare function readAgentUiPages(root: string): string[];
22
+ /** The page module an id names, by the rule `pages.gen.ts` is written with: `pages/<id>` under the resources directory. */
23
+ export declare function resolvePageFile(context: McpAppBuildContext, id: string): string | undefined;
24
+ export declare function renderSetupTemplate(stylesheet: string | undefined): string;
25
+ /** Writes the setup file on the first build; an existing one is the app's and is never touched. */
26
+ export declare function ensureSetupFile(context: McpAppBuildContext): string;
27
+ export declare function renderPageEntry(id: string, setupFile: string, pageFile: string): string;
28
+ export declare function renderPageDocument(scripts: readonly string[], styles: readonly string[]): string;
29
+ export declare function contentHash(html: string): string;
30
+ export declare function pageDocumentFile(root: string, id: string): string;
31
+ /** `.guren/mcp-app/index.gen.ts`, the shape `mcpPlugin({ ui: { pages } })` imports. */
32
+ export declare function renderPagesModule(pages: Readonly<Record<string, {
33
+ html: string;
34
+ hash: string;
35
+ }>>): string;
36
+ /** A page build's output, as the nested build's `generateBundle` sees it. */
37
+ export interface BundleItem {
38
+ type: 'chunk' | 'asset';
39
+ fileName: string;
40
+ code?: string;
41
+ source?: string | Uint8Array;
42
+ isEntry?: boolean;
43
+ }
44
+ /** One page's document from its bundle, and the files it could not inline. */
45
+ export declare function documentFromBundle(items: readonly BundleItem[]): {
46
+ html: string;
47
+ leftovers: string[];
48
+ };
49
+ export interface RunMcpAppBuildOptions {
50
+ context: McpAppBuildContext;
51
+ /** Builds one page; the nested build writes its document to `pageDocumentFile()`. */
52
+ buildPage(id: string): Promise<void>;
53
+ log?(message: string): void;
54
+ }
55
+ /** The driving build: every page in turn, then the module the plugin imports. */
56
+ export declare function runMcpAppBuild(options: RunMcpAppBuildOptions): Promise<Record<string, {
57
+ html: string;
58
+ hash: string;
59
+ }>>;
@@ -1,3 +1,4 @@
1
+ import { type BundleItem, type GurenMcpAppOptions } from './mcp-app.js';
1
2
  export interface GurenVitePluginOptions {
2
3
  /** Alias prefix for application imports such as `@/.guren/routes.gen` (defaults to `@`). */
3
4
  appAlias?: string;
@@ -27,6 +28,8 @@ export interface GurenVitePluginOptions {
27
28
  assetFileNames?: string;
28
29
  /** Prototype mode (`vite --mode prototype`, RFC 0021): the static, server-less build. */
29
30
  prototype?: GurenPrototypeOptions;
31
+ /** MCP App mode (`vite build --mode mcp-app`, RFC 0038): one inlined document per `.agent({ ui })` page. */
32
+ mcpApp?: GurenMcpAppOptions;
30
33
  }
31
34
  export interface GurenPrototypeOptions {
32
35
  /** Vite `base` for a build hosted under a subpath (a GitHub project page, a preview URL). Defaults to `/`. */
@@ -50,6 +53,15 @@ export declare function gurenVitePlugin(options?: GurenVitePluginOptions): {
50
53
  enforce: 'pre';
51
54
  config(config: Record<string, any>, env: Record<string, any>): void;
52
55
  configResolved(config: Record<string, any>): void;
56
+ resolveId(id: string): "\0guren-mcp-app-driver" | "\0guren-mcp-app-entry" | null;
57
+ load(id: string): string | null;
58
+ generateBundle: {
59
+ order: 'post';
60
+ handler(this: {
61
+ warn(message: string): void;
62
+ }, _output: unknown, bundle: Record<string, BundleItem>): void;
63
+ };
64
+ closeBundle(): Promise<void>;
53
65
  configureServer(server: ViteDevServerLike): (() => void) | undefined;
54
66
  writeBundle(): void;
55
67
  };