@vellumai/assistant 0.10.11-dev.202607222325.35fc367 → 0.10.11-dev.202607230047.d24069d

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.
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
@@ -100,3 +100,93 @@ export interface RemoteWebPairingTokenApprovedResponse {
100
100
  export type RemoteWebPairingTokenResponse =
101
101
  | RemoteWebPairingTokenPendingResponse
102
102
  | RemoteWebPairingTokenApprovedResponse;
103
+
104
+ // ── Shared pairing URL helpers ──────────────────────────────────────────────
105
+ //
106
+ // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
107
+ // settings "Pair a device" card) must accept the same public URLs and build
108
+ // the same scannable links. The helpers are environment-neutral (WHATWG URL
109
+ // only) so both Node and browser callers share one implementation.
110
+
111
+ /** Why a public base URL can't be advertised in a pairing challenge. */
112
+ export type PublicBaseUrlRejection = "unparseable" | "loopback" | "non-https";
113
+
114
+ export type PublicBaseUrlResult =
115
+ | { ok: true; url: string }
116
+ | { ok: false; reason: PublicBaseUrlRejection };
117
+
118
+ /**
119
+ * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
120
+ * encodes a loopback address is unreachable from the scanning device.
121
+ */
122
+ export function isLoopbackPublicUrl(url: string): boolean {
123
+ try {
124
+ // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
125
+ const hostname = new URL(url).hostname;
126
+ return (
127
+ hostname === "localhost" ||
128
+ hostname === "[::1]" ||
129
+ /^127(?:\.\d{1,3}){3}$/.test(hostname)
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Normalize an address to the public base a scanning device opens:
138
+ * query/hash stripped, the `assistant` path segment (and everything after it)
139
+ * removed so a pasted pair-page URL collapses to its base, and trailing
140
+ * slashes trimmed. Throws if the value is not a parseable URL.
141
+ */
142
+ export function normalizePublicBaseUrl(value: string): string {
143
+ const url = new URL(value);
144
+ url.search = "";
145
+ url.hash = "";
146
+ const parts = url.pathname.split("/").filter(Boolean);
147
+ const assistantIndex = parts.indexOf("assistant");
148
+ if (assistantIndex >= 0) {
149
+ parts.splice(assistantIndex);
150
+ }
151
+ url.pathname = parts.length ? `/${parts.join("/")}` : "/";
152
+ return url.toString().replace(/\/+$/, "");
153
+ }
154
+
155
+ /**
156
+ * Resolve an address to the public https base URL to advertise in a pairing
157
+ * challenge, or report why it can't be used. Loopback and non-https links are
158
+ * refused with a specific reason callers turn into their own guidance.
159
+ */
160
+ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
161
+ let normalized: string;
162
+ try {
163
+ normalized = normalizePublicBaseUrl(raw);
164
+ } catch {
165
+ return { ok: false, reason: "unparseable" };
166
+ }
167
+ if (isLoopbackPublicUrl(normalized)) {
168
+ return { ok: false, reason: "loopback" };
169
+ }
170
+ if (new URL(normalized).protocol !== "https:") {
171
+ return { ok: false, reason: "non-https" };
172
+ }
173
+ return { ok: true, url: normalized };
174
+ }
175
+
176
+ /**
177
+ * The scannable pair URL: the challenge's verification URI with the device
178
+ * code carried in the fragment (`#device_code=…`), matching what the pair
179
+ * page reads on load. Fragments never reach the wire.
180
+ */
181
+ export function buildRemoteWebPairingUrl(
182
+ challenge: Pick<
183
+ RemoteWebPairingChallengeResponse,
184
+ "verificationUri" | "deviceCode"
185
+ >,
186
+ ): string {
187
+ const url = new URL(challenge.verificationUri);
188
+ url.hash = new URLSearchParams({
189
+ device_code: challenge.deviceCode,
190
+ }).toString();
191
+ return url.toString();
192
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.11-dev.202607222325.35fc367",
3
+ "version": "0.10.11-dev.202607230047.d24069d",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -247,3 +247,107 @@ describe("cleanup on dismiss", () => {
247
247
  expect(ctx.accumulatedSurfaceState.get("surface-2")).toEqual({ y: 2 });
248
248
  });
249
249
  });
250
+
251
+ describe("ui_update preserves client-owned keys the daemon schema omits", () => {
252
+ test("a valid patch keeps unmodeled keys on the merged, sent, and stored data", async () => {
253
+ const sent: ServerMessage[] = [];
254
+ const ctx = makeContext({ sent });
255
+ // A document_preview whose stored data carries `surfaceId` — an unmodeled
256
+ // key read by the client renderer, not by the daemon schema.
257
+ ctx.surfaceState.set("doc-1", {
258
+ surfaceType: "document_preview",
259
+ data: {
260
+ title: "Notes",
261
+ surfaceId: "doc-real",
262
+ content: "# Heading",
263
+ mimeType: "text/markdown",
264
+ } as SurfaceData,
265
+ });
266
+
267
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
268
+ surface_id: "doc-1",
269
+ data: { title: "Notes (edited)" },
270
+ });
271
+ expect(result.isError).toBe(false);
272
+
273
+ // Stored state keeps the unmodeled key and applies the patch.
274
+ expect(ctx.surfaceState.get("doc-1")?.data).toMatchObject({
275
+ title: "Notes (edited)",
276
+ surfaceId: "doc-real",
277
+ });
278
+
279
+ // The update sent to the client also carries it.
280
+ const update = sent.find((m) => m.type === "ui_surface_update");
281
+ expect(update).toBeDefined();
282
+ expect((update as { data: Record<string, unknown> }).data).toMatchObject({
283
+ title: "Notes (edited)",
284
+ surfaceId: "doc-real",
285
+ });
286
+ });
287
+ });
288
+
289
+ describe("ui_update on a restored unknown surface type", () => {
290
+ test("forwards the merge opaquely instead of storing garbage", async () => {
291
+ const sent: ServerMessage[] = [];
292
+ const ctx = makeContext({ sent });
293
+ // Restore preserves an unknown-but-non-empty surfaceType verbatim (a
294
+ // newer/custom client-rendered surface). safeParseSurfaceData has no schema
295
+ // for it — the update must forward the merge, not the type string.
296
+ ctx.surfaceState.set("future-1", {
297
+ surfaceType: "future_widget" as SurfaceType,
298
+ data: { title: "Widget", customField: 42 } as SurfaceData,
299
+ });
300
+
301
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
302
+ surface_id: "future-1",
303
+ data: { title: "Widget (edited)" },
304
+ });
305
+ expect(result.isError).toBe(false);
306
+
307
+ const stored = ctx.surfaceState.get("future-1");
308
+ expect(stored?.surfaceType as string).toBe("future_widget");
309
+ expect(stored?.data as Record<string, unknown>).toEqual({
310
+ title: "Widget (edited)",
311
+ customField: 42,
312
+ });
313
+
314
+ const update = sent.find((m) => m.type === "ui_surface_update");
315
+ expect(update).toBeDefined();
316
+ expect((update as { data: Record<string, unknown> }).data).toEqual({
317
+ title: "Widget (edited)",
318
+ customField: 42,
319
+ });
320
+ });
321
+ });
322
+
323
+ describe("ui_update normalizes modeled fields for known surface types", () => {
324
+ test("a malformed dynamic_page html patch is stored as its schema-coerced string", async () => {
325
+ const sent: ServerMessage[] = [];
326
+ const ctx = makeContext({ sent });
327
+ ctx.surfaceState.set("page-1", {
328
+ surfaceType: "dynamic_page",
329
+ data: { html: "<p>original</p>" } as SurfaceData,
330
+ });
331
+
332
+ // A malformed patch: `html` as a non-string. The tolerant schema
333
+ // (`z.string().catch("")`) accepts it, so the update must not revert — but
334
+ // the stored/sent value must be the coerced string, never the raw object,
335
+ // or later `truncateHtml(...).slice()` on the stored html would crash.
336
+ const result = await surfaceProxyResolver(ctx, "ui_update", {
337
+ surface_id: "page-1",
338
+ data: { html: { unexpected: "object" } },
339
+ });
340
+ expect(result.isError).toBe(false);
341
+
342
+ const storedHtml = (
343
+ ctx.surfaceState.get("page-1")?.data as { html: unknown }
344
+ ).html;
345
+ expect(typeof storedHtml).toBe("string");
346
+
347
+ const update = sent.find((m) => m.type === "ui_surface_update");
348
+ expect(update).toBeDefined();
349
+ expect(typeof (update as { data: { html: unknown } }).data.html).toBe(
350
+ "string",
351
+ );
352
+ });
353
+ });
@@ -509,6 +509,20 @@ export const MODEL_INVOKABLE_SURFACE_TYPES = SURFACE_TYPES.filter(
509
509
  (type) => !isDaemonInternalSurfaceType(type),
510
510
  );
511
511
 
512
+ const SURFACE_TYPE_SET = new Set<string>(SURFACE_TYPES);
513
+
514
+ /**
515
+ * Whether `type` is a surface type this daemon models (has a canonical schema
516
+ * for). Restore preserves an unknown-but-non-empty persisted `surfaceType`
517
+ * verbatim (a newer/custom client-rendered surface), so a runtime string can
518
+ * reach code that dispatches on the type; callers must gate on this before
519
+ * handing the type to `safeParseSurfaceData`, which has no schema for unknown
520
+ * types.
521
+ */
522
+ export function isKnownSurfaceType(type: string): type is SurfaceType {
523
+ return SURFACE_TYPE_SET.has(type);
524
+ }
525
+
512
526
  export type SurfaceData =
513
527
  | CardSurfaceData
514
528
  | ChoiceSurfaceData
@@ -8,6 +8,7 @@ import {
8
8
  coerceSurfaceDataRecord,
9
9
  DynamicPageSurfaceDataSchema,
10
10
  isDaemonInternalSurfaceType,
11
+ isKnownSurfaceType,
11
12
  MODEL_INVOKABLE_SURFACE_TYPES,
12
13
  normalizeCopyBlockShowData,
13
14
  OAuthConnectSurfaceDataSchema,
@@ -3250,19 +3251,38 @@ export async function surfaceProxyResolver(
3250
3251
  pushUndoState(ctx.surfaceUndoStacks, surfaceId, currentHtml);
3251
3252
  }
3252
3253
  const rawMerged = { ...stored.data, ...patch };
3253
- // Validate the merged data through the surface type's canonical schema
3254
- // so malformed patches (e.g. metadata as a string) are caught here
3255
- // instead of crashing the client's safeParse.
3256
- const parsed = safeParseSurfaceData(stored.surfaceType, rawMerged);
3257
- if (parsed !== undefined) {
3258
- mergedData = parsed;
3254
+ if (!isKnownSurfaceType(stored.surfaceType)) {
3255
+ // Restore preserves an unknown-but-non-empty persisted surfaceType
3256
+ // verbatim (a newer/custom client-rendered surface). safeParseSurfaceData
3257
+ // has no schema for it — it falls through to returning the type string
3258
+ // rather than a data object — so forward the merge opaquely rather than
3259
+ // storing that garbage, mirroring restore's verbatim handling.
3260
+ mergedData = rawMerged as SurfaceData;
3259
3261
  } else {
3260
- log.warn(
3261
- { surfaceId, surfaceType: stored.surfaceType },
3262
- "ui_update patch produced invalid merged data; reverting to stored data",
3263
- );
3264
- mergedData =
3265
- safeParseSurfaceData(stored.surfaceType, stored.data) ?? stored.data;
3262
+ // Validate the merged data through the surface type's canonical schema
3263
+ // so malformed patches (e.g. metadata as a string) are caught here
3264
+ // instead of crashing the client's safeParse. Keep unmodeled
3265
+ // client-owned keys from the raw merge, but take the schema-NORMALIZED
3266
+ // value for every modeled field: a tolerant field (dynamic_page `html`
3267
+ // is `z.string().catch("")`, file_upload `acceptedTypes` coerces to
3268
+ // `string[]`) accepts a malformed input and coerces it, and later daemon
3269
+ // code (active-workspace injection's `truncateHtml`, undo-stack pushes)
3270
+ // assumes the canonical shape — so storing the raw value would poison
3271
+ // surfaceState. The parsed object holds only modeled keys, so spreading
3272
+ // it over the raw merge normalizes those while preserving the
3273
+ // client-owned ones. Only a failed parse reverts to the stored data.
3274
+ const parsed = safeParseSurfaceData(stored.surfaceType, rawMerged);
3275
+ if (parsed !== undefined) {
3276
+ mergedData = { ...rawMerged, ...parsed } as SurfaceData;
3277
+ } else {
3278
+ log.warn(
3279
+ { surfaceId, surfaceType: stored.surfaceType },
3280
+ "ui_update patch produced invalid merged data; reverting to stored data",
3281
+ );
3282
+ mergedData =
3283
+ safeParseSurfaceData(stored.surfaceType, stored.data) ??
3284
+ stored.data;
3285
+ }
3266
3286
  }
3267
3287
  stored.data = mergedData;
3268
3288
  } else {