@guren/server 2.35.0 → 2.37.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 (54) hide show
  1. package/dist/{DocsViewerServiceProvider-BVPZjwQp.js → DocsViewerServiceProvider-DzrxQoYh.js} +15 -4
  2. package/dist/Event-COT3f5Xd.js +28 -0
  3. package/dist/{McpServiceProvider-CXOokGax.js → McpServiceProvider-BOeQyt7u.js} +2 -0
  4. package/dist/PrivateChannel-1krGz028.js +187 -0
  5. package/dist/{Resource-y-7zzZSB.js → Resource-PhnO_wNO.js} +113 -12
  6. package/dist/agent/derive.d.ts +23 -1
  7. package/dist/agent/dispatch.d.ts +12 -1
  8. package/dist/agent/pipeline.d.ts +6 -0
  9. package/dist/agent/public.d.ts +1 -1
  10. package/dist/agent/public.js +1 -1
  11. package/dist/{api-token-1-INqeVU.js → api-token-Cs1myxf6.js} +15 -1
  12. package/dist/auth/SessionGuard.d.ts +20 -0
  13. package/dist/auth/index.js +2 -2
  14. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  15. package/dist/auth/types.d.ts +7 -0
  16. package/dist/{auth-CO9MlQNE.js → auth-X27d4l78.js} +88 -6
  17. package/dist/broadcasting/BroadcastManager.d.ts +19 -5
  18. package/dist/broadcasting/event-target.d.ts +9 -0
  19. package/dist/broadcasting/index.d.ts +3 -1
  20. package/dist/broadcasting/index.js +3 -2
  21. package/dist/broadcasting/sender-envelope.d.ts +26 -0
  22. package/dist/broadcasting/types.d.ts +27 -2
  23. package/dist/{broadcasting-D04a3R02.js → broadcasting-Bh6QoMpy.js} +50 -95
  24. package/dist/{contained-path-BkNSBljW.js → contained-path-DOVauNQC.js} +1 -22
  25. package/dist/{dev-banner-BUrHz-LF.js → dev-banner-Uydpgbrm.js} +3 -3
  26. package/dist/{dispatch-ENWpBxbE.js → dispatch-CDNqcB3Q.js} +51 -12
  27. package/dist/events/index.js +2 -1
  28. package/dist/{events-B6gfJkCH.js → events-DW197Nur.js} +2 -28
  29. package/dist/http/vite-dev-server.d.ts +18 -1
  30. package/dist/http/vite-manifest.d.ts +4 -1
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +110 -23
  33. package/dist/internal/agent-principal.d.ts +8 -0
  34. package/dist/internal/testing.d.ts +1 -0
  35. package/dist/internal/testing.js +2 -2
  36. package/dist/mail/index.js +1 -1
  37. package/dist/mail/types.d.ts +9 -0
  38. package/dist/{mail-BQ2y2U5c.js → mail-D4AP4_Wd.js} +6 -1
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Router.d.ts +13 -0
  41. package/dist/mvc/inertia/InertiaEngine.d.ts +3 -0
  42. package/dist/mvc/inertia/props.d.ts +54 -3
  43. package/dist/runtime/index.js +5 -3
  44. package/dist/storage/index.js +1 -1
  45. package/dist/{storage-YPbsV9ju.js → storage-ziIKgHON.js} +2 -1
  46. package/dist/trim-slashes-BLY9hKAa.js +22 -0
  47. package/dist/vite/index.d.ts +2 -0
  48. package/dist/vite/index.js +283 -1
  49. package/dist/vite/mcp-app.d.ts +59 -0
  50. package/dist/vite/plugin.d.ts +12 -0
  51. package/dist/{vite-manifest-DO0pU1vm.js → vite-dev-server-Ag90otai.js} +25 -114
  52. package/dist/vite-manifest-BdXRybeq.js +129 -0
  53. package/package.json +2 -2
  54. package/dist/host-port-t6wQFaRu.js +0 -15
@@ -1,8 +1,7 @@
1
1
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
2
2
  import { n as createDocsViewerAccessGuard, r as isDocsViewerEnabled, t as DOCS_VIEWER_PATH } from "./endpoint-CTIzcagh.js";
3
- import { createRequire } from "node:module";
4
3
  import { createHash } from "node:crypto";
5
- import { join } from "node:path";
4
+ import { dirname, join } from "node:path";
6
5
  import { readFile } from "node:fs/promises";
7
6
  //#region src/docs-viewer/DocsViewerServiceProvider.ts
8
7
  /**
@@ -12,6 +11,18 @@ import { readFile } from "node:fs/promises";
12
11
  */
13
12
  const DATA_CACHE_TTL_MS = 15e3;
14
13
  /**
14
+ * `node_modules/mermaid/dist/mermaid.min.js` in `cwd` or its nearest ancestor.
15
+ * Read off the disk, not through the module resolver: Bun caches a failed
16
+ * resolution for the life of the process.
17
+ */
18
+ async function readAppMermaid(cwd) {
19
+ for (let dir = cwd;; dir = dirname(dir)) try {
20
+ return await readFile(join(dir, "node_modules", "mermaid", "dist", "mermaid.min.js"));
21
+ } catch (error) {
22
+ if (dirname(dir) === dir) throw error;
23
+ }
24
+ }
25
+ /**
15
26
  * The docs viewer (RFC 0005) at /_guren/docs: a read-only, loopback-guarded UI
16
27
  * over the OKF docs bundle, mounted only while `isDocsViewerEnabled()` holds.
17
28
  */
@@ -61,7 +72,7 @@ var DocsViewerServiceProvider = class extends ServiceProvider {
61
72
  let mermaid = null;
62
73
  hono.get(`${DOCS_VIEWER_PATH}/assets/mermaid.js`, async (ctx) => {
63
74
  try {
64
- mermaid ??= readFile(createRequire(join(cwd, "package.json")).resolve("mermaid/dist/mermaid.min.js"));
75
+ mermaid ??= readAppMermaid(cwd);
65
76
  const source = await mermaid;
66
77
  return ctx.body(new Uint8Array(source), 200, {
67
78
  "Content-Type": "text/javascript",
@@ -69,7 +80,7 @@ var DocsViewerServiceProvider = class extends ServiceProvider {
69
80
  });
70
81
  } catch {
71
82
  mermaid = null;
72
- return ctx.json({ message: "mermaid is not installed (bun add -d mermaid)" }, 404);
83
+ return ctx.json({ message: "mermaid is not installed (bun add -d mermaid)" }, 404, { "Cache-Control": "no-store" });
73
84
  }
74
85
  });
75
86
  }
@@ -0,0 +1,28 @@
1
+ //#region src/events/Event.ts
2
+ /** Base class for all application events. */
3
+ var Event = class {
4
+ timestamp = /* @__PURE__ */ new Date();
5
+ /**
6
+ * Stable wire name: queued emits record it and the worker resolves the class
7
+ * back from it. Declare it as a static field to pin the name against a
8
+ * rename or identifier mangling.
9
+ * @default the class name
10
+ */
11
+ static get eventName() {
12
+ return this.name;
13
+ }
14
+ get eventName() {
15
+ return resolveEventName(this.constructor);
16
+ }
17
+ };
18
+ /**
19
+ * Only an *own* `eventName` counts: statics are inherited, so reading the
20
+ * prototype chain would make every subclass of a pinned event claim its
21
+ * parent's name and take over its listeners. The base class's own entry is the
22
+ * accessor, which answers with the class name.
23
+ */
24
+ function resolveEventName(eventClass) {
25
+ return (Object.prototype.hasOwnProperty.call(eventClass, "eventName") ? eventClass.eventName : void 0) ?? eventClass.name;
26
+ }
27
+ //#endregion
28
+ export { resolveEventName as n, Event as t };
@@ -48,6 +48,8 @@ var McpServiceProvider = class extends ServiceProvider {
48
48
  "/_guren/browser/:run/screenshots/:sha256",
49
49
  "/_guren/ui",
50
50
  "/_guren/ui.json",
51
+ "/_guren/mcp-apps",
52
+ "/_guren/mcp-apps/sandbox",
51
53
  DEV_CENTER_FEEDBACK_ROUTE
52
54
  ]) {
53
55
  hono.use(path, createMcpAccessGuard());
@@ -0,0 +1,187 @@
1
+ import { n as resolveEventName } from "./Event-COT3f5Xd.js";
2
+ //#region src/broadcasting/event-target.ts
3
+ /**
4
+ * The one reading of a broadcastable event (RFC 0037 §1): which name and which
5
+ * channels it is broadcast as. `BroadcastManager.broadcastEvent()` sends with it
6
+ * and `live()` subscribes with it, so a live prop cannot listen for a name the
7
+ * sender never uses.
8
+ */
9
+ /** `broadcastAs()`, else the event's `eventName`, else its class name. */
10
+ function broadcastNameOf(event) {
11
+ const name = event.broadcastAs?.() ?? event.eventName ?? classEventName(event);
12
+ if (typeof name !== "string" || name === "") throw new Error("A broadcast event needs a name: define broadcastAs(), extend Event, or construct it from a class.");
13
+ return name;
14
+ }
15
+ /** The wire names `broadcastOn()` returns, prefix included, verbatim. */
16
+ function broadcastChannelsOf(event) {
17
+ const channels = event.broadcastOn();
18
+ if (!Array.isArray(channels) || channels.some((channel) => typeof channel !== "string")) throw new Error(`${describe(event)}.broadcastOn() must return an array of channel names.`);
19
+ return channels;
20
+ }
21
+ function classEventName(event) {
22
+ const ctor = event.constructor;
23
+ return ctor && ctor !== Object ? resolveEventName(ctor) : void 0;
24
+ }
25
+ function describe(event) {
26
+ const ctor = event.constructor;
27
+ return ctor && ctor !== Object && ctor.name ? ctor.name : "The event";
28
+ }
29
+ //#endregion
30
+ //#region src/broadcasting/sender-envelope.ts
31
+ /**
32
+ * The sender of a broadcast, carried inside its payload (RFC 0037 §4) so every
33
+ * driver passes it across instances. `__inertia.socketId` and `__inertia.userId`
34
+ * are reserved: every manager publish path strips them from what the app passes
35
+ * before marking, so a relayed payload cannot forge a mark, and delivery strips
36
+ * them before any client sees the payload.
37
+ */
38
+ const ENVELOPE_KEY = "__inertia";
39
+ /** `s_` and 32 hex digits: what `registerWebSocketClient()` issues. */
40
+ const SOCKET_ID_PATTERN = /^s_[0-9a-f]{32}$/;
41
+ function isSocketId(value) {
42
+ return typeof value === "string" && SOCKET_ID_PATTERN.test(value);
43
+ }
44
+ /** A user id that survives JSON as itself: `NaN` and the infinities become `null` on the Redis driver. */
45
+ function isSenderUserId(value) {
46
+ return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
47
+ }
48
+ function isPlainObject(value) {
49
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
50
+ const prototype = Object.getPrototypeOf(value);
51
+ return prototype === Object.prototype || prototype === null;
52
+ }
53
+ /**
54
+ * The payload with the sender added. An object that is not plain (a class
55
+ * instance, one with `toJSON()`) is marked as the JSON a client would receive;
56
+ * an array or a primitive cannot carry a mark.
57
+ */
58
+ function markSender(data, sender) {
59
+ const object = isPlainObject(data) ? data : asJsonObject(data);
60
+ if (!object) return data;
61
+ const envelope = isPlainObject(object[ENVELOPE_KEY]) ? object[ENVELOPE_KEY] : {};
62
+ return {
63
+ ...object,
64
+ [ENVELOPE_KEY]: {
65
+ ...envelope,
66
+ socketId: sender.socketId,
67
+ userId: sender.userId
68
+ }
69
+ };
70
+ }
71
+ function asJsonObject(data) {
72
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return void 0;
73
+ const json = JSON.parse(JSON.stringify(data));
74
+ return isPlainObject(json) ? json : void 0;
75
+ }
76
+ function readSender(data) {
77
+ if (!isPlainObject(data) || !isPlainObject(data[ENVELOPE_KEY])) return void 0;
78
+ const { socketId, userId } = data[ENVELOPE_KEY];
79
+ if (!isSocketId(socketId) || !isSenderUserId(userId)) return void 0;
80
+ return {
81
+ socketId,
82
+ userId
83
+ };
84
+ }
85
+ /**
86
+ * The payload without the reserved fields, valid or not, and without the
87
+ * envelope once nothing else is in it.
88
+ */
89
+ function stripSender(data) {
90
+ if (!isPlainObject(data) || !isPlainObject(data[ENVELOPE_KEY])) return data;
91
+ if (!("socketId" in data[ENVELOPE_KEY]) && !("userId" in data[ENVELOPE_KEY])) return data;
92
+ const { socketId: _socketId, userId: _userId, ...rest } = data[ENVELOPE_KEY];
93
+ const { [ENVELOPE_KEY]: _envelope, ...payload } = data;
94
+ return Object.keys(rest).length > 0 ? {
95
+ ...payload,
96
+ [ENVELOPE_KEY]: rest
97
+ } : payload;
98
+ }
99
+ //#endregion
100
+ //#region src/broadcasting/channels/Channel.ts
101
+ var Channel = class {
102
+ name;
103
+ driver;
104
+ constructor(name, driver) {
105
+ this.name = name;
106
+ this.driver = driver;
107
+ }
108
+ async broadcast(event, data) {
109
+ await this.driver.publish(this.name, event, stripSender(data));
110
+ }
111
+ /** Returns an unsubscribe function. */
112
+ subscribe(callback) {
113
+ return this.driver.subscribe(this.name, (e) => {
114
+ callback(e.event, stripSender(e.data));
115
+ });
116
+ }
117
+ getChannelName() {
118
+ return this.name;
119
+ }
120
+ };
121
+ //#endregion
122
+ //#region src/broadcasting/channels/PresenceChannel.ts
123
+ /** Broadcast channel that tracks the members who have joined it. */
124
+ var PresenceChannel = class PresenceChannel extends Channel {
125
+ static PREFIX = "presence-";
126
+ presenceDriver;
127
+ constructor(name, driver) {
128
+ const channelName = name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
129
+ super(channelName, driver);
130
+ if (this.isPresenceDriver(driver)) this.presenceDriver = driver;
131
+ else throw new Error("Driver does not support presence channels. Ensure the driver implements PresenceBroadcastDriver interface.");
132
+ }
133
+ isPresenceDriver(driver) {
134
+ return "getMembers" in driver && "addMember" in driver && "removeMember" in driver;
135
+ }
136
+ members() {
137
+ return this.presenceDriver.getMembers(this.name);
138
+ }
139
+ async join(member) {
140
+ this.presenceDriver.addMember(this.name, member);
141
+ await this.broadcast("presence:joining", { member });
142
+ }
143
+ async leave(memberId) {
144
+ const member = this.members().find((m) => m.id === memberId);
145
+ this.presenceDriver.removeMember(this.name, memberId);
146
+ if (member) await this.broadcast("presence:leaving", { member });
147
+ }
148
+ hasMember(memberId) {
149
+ return this.members().some((m) => m.id === memberId);
150
+ }
151
+ getMember(memberId) {
152
+ return this.members().find((m) => m.id === memberId);
153
+ }
154
+ count() {
155
+ return this.members().length;
156
+ }
157
+ getBaseName() {
158
+ return this.name.startsWith(PresenceChannel.PREFIX) ? this.name.slice(PresenceChannel.PREFIX.length) : this.name;
159
+ }
160
+ static isPresenceChannel(name) {
161
+ return name.startsWith(PresenceChannel.PREFIX);
162
+ }
163
+ static normalize(name) {
164
+ return name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
165
+ }
166
+ };
167
+ //#endregion
168
+ //#region src/broadcasting/channels/PrivateChannel.ts
169
+ /** Broadcast channel that requires authentication to subscribe. */
170
+ var PrivateChannel = class PrivateChannel extends Channel {
171
+ static PREFIX = "private-";
172
+ constructor(name, driver) {
173
+ const channelName = name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
174
+ super(channelName, driver);
175
+ }
176
+ getBaseName() {
177
+ return this.name.startsWith(PrivateChannel.PREFIX) ? this.name.slice(PrivateChannel.PREFIX.length) : this.name;
178
+ }
179
+ static isPrivateChannel(name) {
180
+ return name.startsWith(PrivateChannel.PREFIX);
181
+ }
182
+ static normalize(name) {
183
+ return name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
184
+ }
185
+ };
186
+ //#endregion
187
+ export { isSocketId as a, stripSender as c, isSenderUserId as i, broadcastChannelsOf as l, PresenceChannel as n, markSender as o, Channel as r, readSender as s, PrivateChannel as t, broadcastNameOf as u };
@@ -5,8 +5,9 @@ import { n as parseImportMap, t as DEFAULT_DEV_STYLES_ENTRY } from "./inertia-de
5
5
  import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
6
6
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter } from "./default-application-s9SE-Er7.js";
7
7
  import { n as initialPageElement, t as INITIAL_PAGE_SELECTOR } from "./initial-page-U637q3gO.js";
8
+ import { l as broadcastChannelsOf, n as PresenceChannel, t as PrivateChannel, u as broadcastNameOf } from "./PrivateChannel-1krGz028.js";
8
9
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
9
- import { o as getApiTokenOrFail } from "./api-token-1-INqeVU.js";
10
+ import { F as readAgentSharedProps, o as getApiTokenOrFail } from "./api-token-Cs1myxf6.js";
10
11
  import { r as getAuthContext } from "./context--l2HdOhy.js";
11
12
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
12
13
  import { a as resolveI18n } from "./i18n-BShPpJZa.js";
@@ -78,6 +79,8 @@ function copyStackFromError(target, source) {
78
79
  */
79
80
  const DEFERRED_BRAND = Symbol.for("guren.inertia.deferred");
80
81
  const ALWAYS_BRAND = Symbol.for("guren.inertia.always");
82
+ const LIVE_BRAND = Symbol.for("guren.inertia.live");
83
+ const LIVE_OUTERMOST = "live() must be the outermost prop helper: write live(always(…)) or live(defer(…)), never the other way round.";
81
84
  /**
82
85
  * A prop sent on every response, partial reloads included, whatever the
83
86
  * `only`/`except` lists say (Laravel's `Inertia::always()`). The protocol's
@@ -85,6 +88,7 @@ const ALWAYS_BRAND = Symbol.for("guren.inertia.always");
85
88
  * flash the partial filter drops is gone with the request.
86
89
  */
87
90
  function always(value) {
91
+ if (isLiveProp(value)) throw new Error(LIVE_OUTERMOST);
88
92
  return Object.freeze({
89
93
  [ALWAYS_BRAND]: true,
90
94
  value,
@@ -111,6 +115,80 @@ function isDeferredProp(value) {
111
115
  return typeof value === "object" && value !== null && value[DEFERRED_BRAND] === true;
112
116
  }
113
117
  /**
118
+ * A prop the client reloads whenever one of the given broadcast events
119
+ * arrives (Inertia's live props, RFC 0037). The entry is computed here, so a
120
+ * mistake throws in the action that wrote it. Wraps any other prop input.
121
+ */
122
+ function live(value, options) {
123
+ if (isLiveProp(value)) throw new Error("A live prop cannot wrap another live prop.");
124
+ const entry = {
125
+ listeners: liveListeners(options.on),
126
+ ...options.throttle !== void 0 ? { throttle: liveThrottle(options.throttle) } : {}
127
+ };
128
+ return Object.freeze({
129
+ [LIVE_BRAND]: true,
130
+ value,
131
+ entry,
132
+ toJSON: () => isAlwaysProp(value) ? value.toJSON() : value
133
+ });
134
+ }
135
+ function isLiveProp(value) {
136
+ return typeof value === "object" && value !== null && value[LIVE_BRAND] === true;
137
+ }
138
+ function liveThrottle(throttle) {
139
+ if (!Number.isFinite(throttle) || throttle < 0) throw new Error(`A live prop's throttle is milliseconds, a finite number of zero or more; got ${throttle}.`);
140
+ return throttle;
141
+ }
142
+ function isListenerInput(value) {
143
+ return typeof value.broadcastOn !== "function";
144
+ }
145
+ /** Listeners grouped per channel, events deduplicated: the shape the Laravel adapter's `addLiveListener()` sends. */
146
+ function liveListeners(on) {
147
+ const sources = Array.isArray(on) ? on : [on];
148
+ if (sources.length === 0) throw new Error("A live prop must listen for at least one event.");
149
+ const byChannel = /* @__PURE__ */ new Map();
150
+ for (const source of sources) {
151
+ if (typeof source === "function") throw new Error(`live() reads channels off an event instance: pass new ${source.name || "TheEvent"}(…), not the class.`);
152
+ const { event, channels } = isListenerInput(source) ? {
153
+ event: source.event,
154
+ channels: typeof source.channel === "string" ? [source.channel] : [...source.channel ?? []]
155
+ } : {
156
+ event: broadcastNameOf(source),
157
+ channels: broadcastChannelsOf(source)
158
+ };
159
+ if (typeof event !== "string" || event === "") throw new Error("A live prop listener needs an event name.");
160
+ if (channels.length === 0) throw new Error(`A live prop listening for "${event}" has no channel: the event broadcasts on none.`);
161
+ for (const wireName of channels) {
162
+ const channel = liveChannel(wireName);
163
+ const key = `${channel.type}:${channel.name}`;
164
+ const listener = byChannel.get(key) ?? {
165
+ channel,
166
+ events: []
167
+ };
168
+ if (!listener.events.includes(event)) listener.events.push(event);
169
+ byChannel.set(key, listener);
170
+ }
171
+ }
172
+ return [...byChannel.values()];
173
+ }
174
+ /** A Guren wire name as Inertia's `{ name, type }`; the prefixes are the channel classes' own. */
175
+ function liveChannel(wireName) {
176
+ if (wireName.startsWith(`${PrivateChannel.PREFIX}encrypted-`)) throw new Error(`Guren has no encrypted channels; "${wireName}" cannot be live.`);
177
+ for (const [prefix, type] of [[PrivateChannel.PREFIX, "private"], [PresenceChannel.PREFIX, "presence"]]) if (wireName.startsWith(prefix)) {
178
+ const name = wireName.slice(prefix.length);
179
+ if (name === "") throw new Error(`"${wireName}" names no channel.`);
180
+ return {
181
+ name,
182
+ type
183
+ };
184
+ }
185
+ if (wireName === "") throw new Error("A live prop channel name is empty.");
186
+ return {
187
+ name: wireName,
188
+ type: "public"
189
+ };
190
+ }
191
+ /**
114
192
  * A header list as its top-level prop names: `author.name` selects `author`.
115
193
  * The prototype client (`@guren/inertia-client/prototype`) answers a fixture
116
194
  * with the same rule; the two cannot import each other, so keep them in step.
@@ -143,7 +221,10 @@ function isSelected(key, partial) {
143
221
  * every sibling rather than leaving the ones already started unhandled.
144
222
  */
145
223
  function startProp(value) {
146
- return Promise.resolve().then(() => isDeferredProp(value) ? value.resolve() : value());
224
+ return Promise.resolve().then(() => isDeferredProp(value) ? value.resolve() : value()).then((resolved) => {
225
+ if (isLiveProp(resolved)) throw new Error(LIVE_OUTERMOST);
226
+ return resolved;
227
+ });
147
228
  }
148
229
  /**
149
230
  * The props a response carries under the protocol's evaluation rules: a full
@@ -155,16 +236,23 @@ function startProp(value) {
155
236
  async function resolveInertiaProps(input, partial) {
156
237
  const props = {};
157
238
  const deferredProps = {};
239
+ const liveProps = {};
158
240
  const pending = [];
159
- for (const [key, raw] of Object.entries(input)) {
241
+ for (const [key, given] of Object.entries(input)) {
242
+ const liveProp = isLiveProp(given) ? given : void 0;
243
+ const raw = liveProp ? liveProp.value : given;
160
244
  const alwaysProp = isAlwaysProp(raw);
161
245
  const value = alwaysProp ? raw.value : raw;
162
246
  const deferred = isDeferredProp(value);
163
247
  if (partial) {
164
248
  if (!alwaysProp && !isSelected(key, partial)) continue;
165
- } else if (deferred) {
166
- (deferredProps[value.group] ??= []).push(key);
167
- continue;
249
+ if (liveProp) liveProps[key] = liveProp.entry;
250
+ } else {
251
+ if (liveProp) liveProps[key] = liveProp.entry;
252
+ if (deferred) {
253
+ (deferredProps[value.group] ??= []).push(key);
254
+ continue;
255
+ }
168
256
  }
169
257
  if (deferred || typeof value === "function") {
170
258
  props[key] = void 0;
@@ -174,10 +262,11 @@ async function resolveInertiaProps(input, partial) {
174
262
  } else props[key] = value;
175
263
  }
176
264
  if (pending.length > 0) await Promise.all(pending);
177
- return Object.keys(deferredProps).length > 0 ? {
265
+ return {
178
266
  props,
179
- deferredProps
180
- } : { props };
267
+ ...Object.keys(deferredProps).length > 0 ? { deferredProps } : {},
268
+ ...Object.keys(liveProps).length > 0 ? { liveProps } : {}
269
+ };
181
270
  }
182
271
  //#endregion
183
272
  //#region src/support/default-headers.ts
@@ -308,7 +397,8 @@ async function buildInertiaPage(component, props, options) {
308
397
  props: resolved.props,
309
398
  url: options.url ?? inertiaPageUrl(options.request) ?? "",
310
399
  version: options.version,
311
- ...resolved.deferredProps ? { deferredProps: resolved.deferredProps } : {}
400
+ ...resolved.deferredProps ? { deferredProps: resolved.deferredProps } : {},
401
+ ...resolved.liveProps ? { liveProps: resolved.liveProps } : {}
312
402
  };
313
403
  }
314
404
  /**
@@ -923,7 +1013,7 @@ var Controller = class {
923
1013
  const ctx = this.ctx;
924
1014
  const component = typeof componentOrPage === "string" ? componentOrPage : componentOrPage.component ?? componentOrPage.id;
925
1015
  const { response, page } = await renderInertia(component, {
926
- ...await resolveSharedInertiaProps(ctx, this._container),
1016
+ ...await resolveSharedProps(ctx, this._container),
927
1017
  ...props
928
1018
  }, {
929
1019
  ...options,
@@ -1114,6 +1204,17 @@ var Controller = class {
1114
1204
  return asRecord(await this.getRawBody());
1115
1205
  }
1116
1206
  };
1207
+ /**
1208
+ * Shared props, narrowed to what the agent pipeline allowed this exact request (RFC 0038 §6).
1209
+ * An empty allowlist runs no resolver; a non-empty one runs them all, since one resolver returns several keys.
1210
+ */
1211
+ async function resolveSharedProps(ctx, container) {
1212
+ const allowed = readAgentSharedProps(ctx.req.raw);
1213
+ if (allowed?.size === 0) return {};
1214
+ const shared = await resolveSharedInertiaProps(ctx, container);
1215
+ if (!allowed) return shared;
1216
+ return Object.fromEntries(Object.entries(shared).filter(([key]) => allowed.has(key)));
1217
+ }
1117
1218
  //#endregion
1118
1219
  //#region src/http/resources/Resource.ts
1119
1220
  /**
@@ -1184,4 +1285,4 @@ var JsonResource = class extends Resource {
1184
1285
  }
1185
1286
  };
1186
1287
  //#endregion
1187
- export { ensureErrorStackTracePolyfill as A, setInertiaDocument as C, defer as D, always as E, isAlwaysProp as O, serializePage as S, withDefaultHeaders as T, INERTIA_VARY as _, renderDocument as a, inertia as b, getRequestLocale as c, mountModuleRoutes as d, definePlugin as f, shareInertiaProps as g, setInertiaSharedProps as h, Controller as i, isDeferredProp as k, getRequestTranslator as l, resolveSharedInertiaProps as m, Resource as n, LOCALE_CONTEXT_KEY as o, getInertiaSharedPropsResolver as p, collect as r, detectLocaleMiddleware as s, JsonResource as t, defineModule as u, acceptsJson as v, setInertiaSsrRenderer as w, mergeInertiaVary as x, buildInertiaPage as y };
1288
+ export { isLiveProp as A, setInertiaDocument as C, defer as D, always as E, ensureErrorStackTracePolyfill as M, isAlwaysProp as O, serializePage as S, withDefaultHeaders as T, INERTIA_VARY as _, renderDocument as a, inertia as b, getRequestLocale as c, mountModuleRoutes as d, definePlugin as f, shareInertiaProps as g, setInertiaSharedProps as h, Controller as i, live as j, isDeferredProp as k, getRequestTranslator as l, resolveSharedInertiaProps as m, Resource as n, LOCALE_CONTEXT_KEY as o, getInertiaSharedPropsResolver as p, collect as r, detectLocaleMiddleware as s, JsonResource as t, defineModule as u, acceptsJson as v, setInertiaSsrRenderer as w, mergeInertiaVary as x, buildInertiaPage as y };
@@ -8,7 +8,7 @@
8
8
  * result, and `guren check` turns those warnings into a failing build. Opt-in —
9
9
  * a route becomes a tool only by declaring `.agent()` *and* carrying a name.
10
10
  */
11
- import type { ResourceResponseShape, RouteDefinition } from '../mvc/Router.js';
11
+ import type { AgentRouteMetadata, ResourceResponseShape, RouteDefinition } from '../mvc/Router.js';
12
12
  import { type JsonSchemaObject } from '../internal/zod-json-schema.js';
13
13
  /**
14
14
  * A JSON Schema 2020-12 object as an agent tool advertises it — an alias of the
@@ -34,6 +34,15 @@ export interface DerivedAgentToolExposure {
34
34
  mcp: boolean;
35
35
  webMcp: boolean;
36
36
  }
37
+ /**
38
+ * MCP Apps metadata (RFC 0038), resolved: `visibility` always present, so no
39
+ * consumer re-applies the specification's both-audiences default.
40
+ */
41
+ export interface DerivedAgentToolUi {
42
+ /** The Inertia page rendering this tool's result. Absent for a tool only a view calls. */
43
+ page?: string;
44
+ visibility: Array<'model' | 'app'>;
45
+ }
37
46
  export interface DerivedAgentTool {
38
47
  /** Tool identity: `agent.toolName` when given, otherwise the route name, verbatim. */
39
48
  toolName: string;
@@ -89,6 +98,14 @@ export interface DerivedAgentTool {
89
98
  /** Declared verbatim: argument fields masked in agent audit logs. */
90
99
  redact?: string[];
91
100
  expose: DerivedAgentToolExposure;
101
+ /**
102
+ * Input names two sources declared, of which the later one won. A visit that
103
+ * carries both cannot be rebuilt into one flat call, so the MCP Apps bridge
104
+ * leaves such a tool alone (RFC 0038 §5). Absent when there were none.
105
+ */
106
+ inputCollisions?: string[];
107
+ /** Declared `ui`, normalized (RFC 0038). Absent when the route declares none. */
108
+ ui?: DerivedAgentToolUi;
92
109
  /**
93
110
  * What could not be expressed while deriving *this* tool, unprefixed. The
94
111
  * same lines appear prefixed in {@link DeriveAgentToolsResult.warnings};
@@ -119,3 +136,8 @@ export type AgentToolInputSource = 'params' | 'path' | 'query' | 'body';
119
136
  * @param definitions Registered routes, as `Router.definitions()` hands them out.
120
137
  */
121
138
  export declare function deriveAgentTools(definitions: RouteDefinition[]): DeriveAgentToolsResult;
139
+ /**
140
+ * The declared `ui` resolved, or why it is malformed. The one rule: the
141
+ * derivation and `guren check` both judge a declaration through it.
142
+ */
143
+ export declare function deriveAgentToolUi(declared: NonNullable<AgentRouteMetadata['ui']>): DerivedAgentToolUi | string;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { DerivedAgentTool } from './derive.js';
8
8
  import type { AgentSurface } from './events.js';
9
+ import type { InertiaPagePayload } from '../mvc/inertia/InertiaEngine.js';
9
10
  export interface BuildToolRequestOptions {
10
11
  /**
11
12
  * Origin the synthesized URL is built on. Never leaves the process — the
@@ -95,6 +96,16 @@ export interface ToolCallOutcome {
95
96
  * route as a rehearsal that never ran.
96
97
  */
97
98
  preflightVerdict?: boolean;
99
+ /**
100
+ * A 3xx response's `Location`, resolved against the dispatched request's URL
101
+ * when the caller passes it (a relative `../13` means the route's own path).
102
+ * Read by adapters instead of parsing `content`.
103
+ */
104
+ location?: string;
105
+ /** A 422 response's `errors` object, when the body carries one (RFC 0038 §6). */
106
+ errors?: Record<string, string[]>;
107
+ /** The whole Inertia page a `ui` page tool's action answered with, before `content` unwraps it to its props. */
108
+ inertiaPage?: InertiaPagePayload;
98
109
  }
99
110
  /**
100
111
  * Whether the tool advertises an object output schema — the only kind MCP
@@ -110,4 +121,4 @@ export declare function advertisesStructuredOutput(tool: DerivedAgentTool): bool
110
121
  * with the handler's body; other → capped text. An object-`outputSchema` success
111
122
  * lacking an object becomes `isError`: the SDK client rejects it after the route ran.
112
123
  */
113
- export declare function mapToolResponse(tool: DerivedAgentTool, response: Response): Promise<ToolCallOutcome>;
124
+ export declare function mapToolResponse(tool: DerivedAgentTool, response: Response, requestUrl?: string): Promise<ToolCallOutcome>;
@@ -157,6 +157,12 @@ export interface AgentInvocationOptions {
157
157
  * so a route behind those refuses. Omitted, nothing is installed.
158
158
  */
159
159
  handoff?: 'seam';
160
+ /**
161
+ * The shared Inertia props the dispatched request may carry (RFC 0038 §6),
162
+ * installed on the request object so nothing on the wire can widen it.
163
+ * Undefined leaves them all.
164
+ */
165
+ sharedProps?: readonly string[];
160
166
  /** Forwarded to `app.fetch` — D1/R2 bindings on Workers (RFC 0016 §3.1). */
161
167
  env?: unknown;
162
168
  /** Forwarded to `app.fetch` — `waitUntil` on Workers. */
@@ -10,5 +10,5 @@
10
10
  */
11
11
  export { advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse, PREFLIGHT_ARGUMENT, } from './dispatch.js';
12
12
  export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, ToolRequestBuildFailure, } from './dispatch.js';
13
- export type { AgentToolInputSource, AgentToolSchema, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './derive.js';
13
+ export type { AgentToolInputSource, AgentToolSchema, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, DerivedAgentToolUi, } from './derive.js';
14
14
  export type { AgentSurface } from './events.js';
@@ -1,2 +1,2 @@
1
- import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-ENWpBxbE.js";
1
+ import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-CDNqcB3Q.js";
2
2
  export { PREFLIGHT_ARGUMENT, advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse };
@@ -34,6 +34,20 @@ function markAgentDispatch(request) {
34
34
  function isAgentDispatch(request) {
35
35
  return dispatched.has(request);
36
36
  }
37
+ const sharedProps = /* @__PURE__ */ new WeakMap();
38
+ /**
39
+ * Mark `request` as allowed only the named shared Inertia props (RFC 0038 §6),
40
+ * returning that same object. A surface opts in through the pipeline's
41
+ * `sharedProps`; nothing on the wire can ask for it, and nothing can widen it.
42
+ */
43
+ function installAgentSharedProps(request, keys) {
44
+ sharedProps.set(request, new Set(keys));
45
+ return request;
46
+ }
47
+ /** The shared props this exact request may carry, or `undefined` for all of them. */
48
+ function readAgentSharedProps(request) {
49
+ return sharedProps.get(request);
50
+ }
37
51
  //#endregion
38
52
  //#region src/auth/utils.ts
39
53
  function hashToken(token, algorithm = "sha256") {
@@ -480,4 +494,4 @@ function getApiTokenOrFail(ctx) {
480
494
  return result;
481
495
  }
482
496
  //#endregion
483
- export { secureStringCompare as A, scopesAllowTool as C, hashToken as D, generateToken as E, markAgentDispatch as M, readAgentPrincipal as N, parseTokenUrl as O, parseToolScope as S, generateId as T, tokenCanAny as _, getApiToken as a, classifyRegistrationScope as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAll as g, tokenCan as h, createBearerTokenMiddleware as i, installAgentPrincipal as j, secureCompare as k, parseApiToken as l, tokenAuthenticatesRequest as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, verifyApiToken as v, buildTokenUrl as w, expandToolScopes as x, AGENT_TOOL_NAME_PATTERN as y };
497
+ export { secureStringCompare as A, scopesAllowTool as C, hashToken as D, generateToken as E, readAgentSharedProps as F, installAgentSharedProps as M, markAgentDispatch as N, parseTokenUrl as O, readAgentPrincipal as P, parseToolScope as S, generateId as T, tokenCanAny as _, getApiToken as a, classifyRegistrationScope as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAll as g, tokenCan as h, createBearerTokenMiddleware as i, installAgentPrincipal as j, secureCompare as k, parseApiToken as l, tokenAuthenticatesRequest as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, verifyApiToken as v, buildTokenUrl as w, expandToolScopes as x, AGENT_TOOL_NAME_PATTERN as y };
@@ -16,6 +16,26 @@ export declare class SessionGuard<User extends Authenticatable = Authenticatable
16
16
  private rememberSessionKey;
17
17
  private loadRememberedUser;
18
18
  private sanitizeUser;
19
+ private fingerprintSessionKey;
20
+ /**
21
+ * Whether the session was opened under the credential `user` holds now. A
22
+ * session with no fingerprint fails for an account that has a credential:
23
+ * nothing shows it was opened under the current one.
24
+ */
25
+ private holdsCurrentCredential;
26
+ private bindCredential;
27
+ /**
28
+ * validate() may rehash the password of the user this session belongs to
29
+ * (a profile form confirming the current password). The session moves to the
30
+ * new hash, or its own next request would read as a password change.
31
+ */
32
+ private followRehash;
33
+ /**
34
+ * Whose session this is. A remembered session carries no id key, and must be
35
+ * resolved before a rehash: afterwards its fingerprint reads as stale.
36
+ */
37
+ private sessionUserId;
38
+ private forgetLogin;
19
39
  private resolveUser;
20
40
  check(): Promise<boolean>;
21
41
  guest(): Promise<boolean>;
@@ -1,3 +1,3 @@
1
- import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-CO9MlQNE.js";
2
- import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, T as generateId, _ as tokenCanAny, a as getApiToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, k as secureCompare, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "../api-token-1-INqeVU.js";
1
+ import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-X27d4l78.js";
2
+ import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, T as generateId, _ as tokenCanAny, a as getApiToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, k as secureCompare, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "../api-token-Cs1myxf6.js";
3
3
  export { API_TOKEN_KEY, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };