wcz-layout 10.2.1 → 10.2.2

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 (73) hide show
  1. package/dist/{ChatLayout-BpRj5rlH.mjs → ChatLayout-CkS9oyPp.mjs} +557 -270
  2. package/dist/ChatLayout-CkS9oyPp.mjs.map +1 -0
  3. package/dist/{Employee-C8xIlBxY.d.mts → ExtractFile-ClTc-e1H.d.mts} +20 -3
  4. package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -1
  5. package/dist/Translate-Ad784Dps.d.mts +24 -0
  6. package/dist/{Approval-D1TfISUL.mjs → Translate-BiCjnlyx.mjs} +22 -2
  7. package/dist/Translate-BiCjnlyx.mjs.map +1 -0
  8. package/dist/ai.d.mts +31 -4
  9. package/dist/ai.mjs +154 -10
  10. package/dist/ai.mjs.map +1 -1
  11. package/dist/auth.d.mts +4 -3
  12. package/dist/auth.mjs +5 -5
  13. package/dist/authMiddleware-D4GSt7m9.mjs +50 -0
  14. package/dist/authMiddleware-D4GSt7m9.mjs.map +1 -0
  15. package/dist/components.mjs +13 -5
  16. package/dist/components.mjs.map +1 -1
  17. package/dist/{createApi-BXjkj4fM.mjs → createApi-CF4ZL82B.mjs} +3 -4
  18. package/dist/createApi-CF4ZL82B.mjs.map +1 -0
  19. package/dist/data/client.d.mts +17 -1
  20. package/dist/data/client.mjs +11 -5
  21. package/dist/data/client.mjs.map +1 -1
  22. package/dist/data/server.d.mts +18 -3
  23. package/dist/data/server.mjs +5 -5
  24. package/dist/{env-BwFl7nWc.mjs → env-Cddts_dn.mjs} +2 -1
  25. package/dist/env-Cddts_dn.mjs.map +1 -0
  26. package/dist/{file-BQ-Bu2g8.mjs → file-D4kSR_lC.mjs} +5 -6
  27. package/dist/file-D4kSR_lC.mjs.map +1 -0
  28. package/dist/{file-DZ0KYhoB.mjs → file-DcwYjofa.mjs} +5 -6
  29. package/dist/file-DcwYjofa.mjs.map +1 -0
  30. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -1
  31. package/dist/hooks.d.mts +2 -2
  32. package/dist/hooks.mjs +294 -192
  33. package/dist/hooks.mjs.map +1 -1
  34. package/dist/index.mjs +224 -173
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/{approval-B3ZQn9aH.mjs → layout-6We_KFgN.mjs} +28 -4
  37. package/dist/layout-6We_KFgN.mjs.map +1 -0
  38. package/dist/middleware.mjs +1 -45
  39. package/dist/middleware.mjs.map +1 -1
  40. package/dist/models.d.mts +3 -3
  41. package/dist/models.mjs +2 -2
  42. package/dist/{peoplesoft-CvwdApCK.mjs → peoplesoft-DH31FCMC.mjs} +3 -3
  43. package/dist/{peoplesoft-CvwdApCK.mjs.map → peoplesoft-DH31FCMC.mjs.map} +1 -1
  44. package/dist/{peoplesoft-C-zPdRVj.d.mts → peoplesoft-DXukeeFr.d.mts} +2 -2
  45. package/dist/{providers-BfFg_3eo.mjs → providers-DOFje2P6.mjs} +7 -7
  46. package/dist/providers-DOFje2P6.mjs.map +1 -0
  47. package/dist/{tokens-CkWpu7Qp.mjs → tokens-DNe_Qifk.mjs} +63 -9
  48. package/dist/tokens-DNe_Qifk.mjs.map +1 -0
  49. package/dist/user-Bc2nLjAG.mjs +136 -0
  50. package/dist/user-Bc2nLjAG.mjs.map +1 -0
  51. package/dist/utils-CgabUlDD.mjs +131 -0
  52. package/dist/utils-CgabUlDD.mjs.map +1 -0
  53. package/dist/utils.mjs +1 -1
  54. package/package.json +34 -13
  55. package/skills/ai/SKILL.md +108 -75
  56. package/skills/general/references/auth.md +7 -3
  57. package/skills/services/SKILL.md +41 -7
  58. package/skills/services/docs/layout.md +130 -0
  59. package/skills/start/steps/03-apm-setup.md +8 -1
  60. package/dist/Approval-D1TfISUL.mjs.map +0 -1
  61. package/dist/ChatLayout-BpRj5rlH.mjs.map +0 -1
  62. package/dist/Email-Dz5k0UWE.d.mts +0 -15
  63. package/dist/approval-B3ZQn9aH.mjs.map +0 -1
  64. package/dist/createApi-BXjkj4fM.mjs.map +0 -1
  65. package/dist/env-BwFl7nWc.mjs.map +0 -1
  66. package/dist/file-BQ-Bu2g8.mjs.map +0 -1
  67. package/dist/file-DZ0KYhoB.mjs.map +0 -1
  68. package/dist/providers-BfFg_3eo.mjs.map +0 -1
  69. package/dist/session-B_jK90RC.mjs +0 -23
  70. package/dist/session-B_jK90RC.mjs.map +0 -1
  71. package/dist/tokens-CkWpu7Qp.mjs.map +0 -1
  72. package/dist/utils-DJx-7b4M.mjs +0 -244
  73. package/dist/utils-DJx-7b4M.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-Bc2nLjAG.mjs","names":[],"sources":["../src/lib/auth/offline.ts","../src/lib/auth/session.ts","../src/lib/auth/user.ts"],"sourcesContent":["/**\n * Offline fallback for identity. The refresh token never leaves the sealed\n * httpOnly cookie — what is cached here is only the display snapshot (user\n * claims and avatar) so the UI and offline route permissions can still work\n * while the server is unreachable. Server requests remain independently\n * authorized. At-rest protection is the device's OS login and disk encryption.\n */\n\nexport const OFFLINE_USER_KEY = \"auth-user\";\nexport const OFFLINE_PHOTO_KEY = \"auth-photo\";\n\n/** One shift — matches Intune's default offline grace period. */\nconst GRACE_PERIOD = 12 * 60 * 60 * 1000;\n\ntype Cached<T> = { value: T; savedAt: number };\n\nconst recall = <T>(key: string): T | null => {\n if (typeof localStorage === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return null;\n const { value, savedAt } = JSON.parse(raw) as Cached<T>;\n if (Date.now() - savedAt > GRACE_PERIOD) {\n localStorage.removeItem(key);\n return null;\n }\n return value;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n};\n\nconst remember = (key: string, value: unknown): void => {\n if (typeof localStorage === \"undefined\") return;\n try {\n if (value === null || value === undefined) localStorage.removeItem(key);\n else localStorage.setItem(key, JSON.stringify({ value, savedAt: Date.now() }));\n } catch {\n // Storage full or blocked — the offline fallback is best-effort.\n }\n};\n\nconst isOfflineFailure = (error: unknown): boolean =>\n (typeof navigator !== \"undefined\" && !navigator.onLine) || error instanceof TypeError;\n\n/**\n * Answers from the server when reachable, remembering the result; when the call\n * has a transport failure, replays the last result instead, for up to\n * {@link GRACE_PERIOD} since it was last confirmed.\n *\n * Cached values are untrusted client state. Server authorization must never\n * depend on them.\n */\nexport const withOfflineFallback = async <T>(\n key: string,\n fetchFresh: () => Promise<T>,\n): Promise<T | null> => {\n try {\n const fresh = await fetchFresh();\n remember(key, fresh);\n return fresh;\n } catch (error) {\n if (!isOfflineFailure(error)) throw error;\n return recall<T>(key);\n }\n};\n\n/** Drops the cached identity. Call on logout, before leaving the page. */\nexport const clearSessionSnapshot = (): void => {\n if (typeof localStorage === \"undefined\") return;\n localStorage.removeItem(OFFLINE_USER_KEY);\n localStorage.removeItem(OFFLINE_PHOTO_KEY);\n localStorage.setItem(\"auth-logout\", String(Date.now()));\n};\n\nif (typeof window !== \"undefined\")\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"auth-logout\") location.href = \"/auth/logout\";\n });\n","import type { IronSession } from \"iron-session\";\nimport { serverEnv } from \"~/env\";\nimport type { ProviderId, User } from \"~/models/User\";\n\nexport interface AppSessionData {\n /** Which identity provider signed this user in. */\n provider?: ProviderId;\n /** The only token persisted; delegated access tokens are minted from it. */\n refreshToken?: string;\n user?: User;\n /** Transient, only between /auth/login and /auth/callback. */\n pkceVerifier?: string;\n state?: string;\n returnTo?: string;\n}\n\nexport type AppSession = IronSession<AppSessionData>;\n\nexport const getAppSession = async (): Promise<AppSession> => {\n // Dynamic import: `@tanstack/react-start/server` is the server entry and drags\n // in the SSR renderer (`react-dom/server`). Keep it out of the client graph —\n // this helper is only ever called server-side, and all callers already await it.\n const [{ getIronSession }, { getCookie, setCookie }] = await Promise.all([\n import(\"iron-session\"),\n import(\"@tanstack/react-start/server\"),\n ]);\n\n return getIronSession<AppSessionData>(\n { read: getCookie, write: setCookie },\n {\n // Not `session`: that name holds the pre-stable `useSession` seal, which\n // iron-session can't read. Users sign in once more after the upgrade.\n cookieName: \"app-session\",\n password: serverEnv.SESSION_SECRET,\n chunk: true,\n cookieOptions: {\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n httpOnly: true,\n path: \"/\",\n // Explicit `undefined`: browser-session cookie and a seal that never\n // expires — what `useSession` did. Omit it to fall back to iron's 14-day `ttl`.\n maxAge: undefined,\n },\n },\n );\n};\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { createServerFn } from \"@tanstack/react-start\";\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\nimport type { ProviderId, User } from \"~/models/User\";\nimport { OFFLINE_USER_KEY, withOfflineFallback } from \"./offline\";\nimport { getAppSession } from \"./session\";\n\n/**\n * Reads the signed-in user from the session cookie, or null. As a server function\n * it runs in-process when called on the server (SSR, middleware) and as an RPC\n * when called from the client — so it doubles as the client `queryFn`.\n */\nexport const getSessionUser = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<User | null> => {\n const session = await getAppSession();\n return session.user ?? null;\n },\n);\n\n/** The identity providers the server offers, for the login page. */\nexport const getLoginProviders = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<Array<{ id: ProviderId; label: string }>> => {\n // Dynamic import: `providers` reads `serverEnv` and must not reach the client.\n const { providers } = await import(\"./providers\");\n return providers.map(({ id, label }) => ({ id, label }));\n },\n);\n\n/**\n * Feeds `LoginForm`. Server config, not per-user, so it is safe to prime on the\n * server — the `/login` route's loader does that to avoid a flash of empty card.\n */\nexport const loginProvidersQueryOptions = queryOptions({\n queryKey: [\"auth\", \"providers\"],\n queryFn: () => getLoginProviders(),\n staleTime: \"static\",\n});\n\n/**\n * Client-side query for the signed-in user. Shared between `getUser` (route\n * `beforeLoad`) and the always-mounted observer in `LayoutProvider` — the\n * observer is what seeds the offline snapshot on the very first page load\n * (`beforeLoad` does not re-run after SSR hydration) and what makes\n * `refetchOnReconnect` fire once connectivity returns.\n */\nexport const userQueryOptions = queryOptions({\n queryKey: [\"auth\", \"user\"],\n queryFn: () => withOfflineFallback(OFFLINE_USER_KEY, () => getSessionUser()),\n staleTime: Infinity,\n // Default \"online\" pauses the query (never calling queryFn) once the browser\n // reports no connection — which is exactly when the fallback is needed.\n networkMode: \"offlineFirst\",\n // Back online: re-confirm the session and re-stamp the snapshot's grace period.\n refetchOnReconnect: \"always\",\n});\n\nexport const getUser = ({ queryClient }: QueryClientParam): Promise<User | null> => {\n if (import.meta.env.SSR) return getSessionUser();\n\n return queryClient.ensureQueryData(userQueryOptions);\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;;AAGjC,MAAM,eAAe;AAIrB,MAAM,UAAa,QAA0B;CAC3C,IAAI,OAAO,iBAAiB,aAAa,OAAO;CAChD,IAAI;EACF,MAAM,MAAM,aAAa,QAAQ,GAAG;EACpC,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,EAAE,OAAO,YAAY,KAAK,MAAM,GAAG;EACzC,IAAI,KAAK,IAAI,IAAI,UAAU,cAAc;GACvC,aAAa,WAAW,GAAG;GAC3B,OAAO;EACT;EACA,OAAO;CACT,QAAQ;EACN,aAAa,WAAW,GAAG;EAC3B,OAAO;CACT;AACF;AAEA,MAAM,YAAY,KAAa,UAAyB;CACtD,IAAI,OAAO,iBAAiB,aAAa;CACzC,IAAI;EACF,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,aAAa,WAAW,GAAG;OACjE,aAAa,QAAQ,KAAK,KAAK,UAAU;GAAE;GAAO,SAAS,KAAK,IAAI;EAAE,CAAC,CAAC;CAC/E,QAAQ,CAER;AACF;AAEA,MAAM,oBAAoB,UACvB,OAAO,cAAc,eAAe,CAAC,UAAU,UAAW,iBAAiB;;;;;;;;;AAU9E,MAAa,sBAAsB,OACjC,KACA,eACsB;CACtB,IAAI;EACF,MAAM,QAAQ,MAAM,WAAW;EAC/B,SAAS,KAAK,KAAK;EACnB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM;EACpC,OAAO,OAAU,GAAG;CACtB;AACF;;AAGA,MAAa,6BAAmC;CAC9C,IAAI,OAAO,iBAAiB,aAAa;CACzC,aAAa,WAAW,gBAAgB;CACxC,aAAa,WAAW,iBAAiB;CACzC,aAAa,QAAQ,eAAe,OAAO,KAAK,IAAI,CAAC,CAAC;AACxD;AAEA,IAAI,OAAO,WAAW,aACpB,OAAO,iBAAiB,YAAY,UAAU;CAC5C,IAAI,MAAM,QAAQ,eAAe,SAAS,OAAO;AACnD,CAAC;;AC7DH,MAAa,gBAAgB,YAAiC;CAI5D,MAAM,CAAC,EAAE,kBAAkB,EAAE,WAAW,eAAe,MAAM,QAAQ,IAAI,CACvE,OAAO,iBACP,OAAO,+BACT,CAAC;CAED,OAAO,eACL;EAAE,MAAM;EAAW,OAAO;CAAU,GACpC;EAGE,YAAY;EACZ,UAAU,UAAU;EACpB,OAAO;EACP,eAAe;GACb,QAAQ,QAAQ,IAAI,aAAa;GACjC,UAAU;GACV,UAAU;GACV,MAAM;GAGN,QAAQ,KAAA;EACV;CACF,CACF;AACF;;;;;;;AClCA,MAAa,iBAAiB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CAAC,QAC9D,YAAkC;CAEhC,QAAO,MADe,cAAc,EAAA,CACrB,QAAQ;AACzB,CACF;;AAGA,MAAa,oBAAoB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CAAC,QACjE,YAA+D;CAE7D,MAAM,EAAE,cAAc,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CACnC,OAAO,UAAU,KAAK,EAAE,IAAI,aAAa;EAAE;EAAI;CAAM,EAAE;AACzD,CACF;;;;;AAMA,MAAa,6BAA6B,aAAa;CACrD,UAAU,CAAC,QAAQ,WAAW;CAC9B,eAAe,kBAAkB;CACjC,WAAW;AACb,CAAC;;;;;;;;AASD,MAAa,mBAAmB,aAAa;CAC3C,UAAU,CAAC,QAAQ,MAAM;CACzB,eAAe,oBAAoB,wBAAwB,eAAe,CAAC;CAC3E,WAAW;CAGX,aAAa;CAEb,oBAAoB;AACtB,CAAC;AAED,MAAa,WAAW,EAAE,kBAA0D;CAClF,IAAI,YAAY,IAAI,KAAK,OAAO,eAAe;CAE/C,OAAO,YAAY,gBAAgB,gBAAgB;AACrD"}
@@ -0,0 +1,131 @@
1
+ import { n as getUser } from "./user-Bc2nLjAG.mjs";
2
+ import { manifest, permissions } from "virtual:wcz-layout";
3
+ import { redirect } from "@tanstack/react-router";
4
+ // src/lib/utils.ts
5
+ const WISTRON_PRIMARY_COLOR = "#00506E";
6
+ const WISTRON_SECONDARY_COLOR = "#64DC00";
7
+ var Platform = class {
8
+ static get isAndroid() {
9
+ return /android/i.test(this.userAgent);
10
+ }
11
+ static get isIOS() {
12
+ return /iPad|iPhone|iPod/.test(this.userAgent);
13
+ }
14
+ static get isWindows() {
15
+ return /windows/i.test(this.userAgent);
16
+ }
17
+ static get isMacOS() {
18
+ return /Macintosh|MacIntel|MacPPC|Mac68K/.test(this.userAgent);
19
+ }
20
+ static get userAgent() {
21
+ return typeof navigator === "undefined" ? "" : navigator.userAgent;
22
+ }
23
+ };
24
+ const rootRouteHead = (options) => ({
25
+ meta: [
26
+ { charSet: "utf-8" },
27
+ {
28
+ name: "viewport",
29
+ content: "width=device-width, initial-scale=1"
30
+ },
31
+ { title: manifest.name },
32
+ {
33
+ name: "og:type",
34
+ content: "website"
35
+ },
36
+ {
37
+ name: "og:title",
38
+ content: manifest.name
39
+ },
40
+ {
41
+ name: "og:image",
42
+ content: "/favicon-32x32.png"
43
+ }
44
+ ],
45
+ links: [
46
+ {
47
+ rel: "apple-touch-icon",
48
+ sizes: "180x180",
49
+ href: "/apple-touch-icon.png"
50
+ },
51
+ {
52
+ rel: "icon",
53
+ type: "image/png",
54
+ sizes: "32x32",
55
+ href: "/favicon-32x32.png"
56
+ },
57
+ {
58
+ rel: "icon",
59
+ type: "image/png",
60
+ sizes: "16x16",
61
+ href: "/favicon-16x16.png"
62
+ },
63
+ {
64
+ rel: "manifest",
65
+ href: options?.manifest || "/manifest.json"
66
+ },
67
+ {
68
+ rel: "icon",
69
+ href: "/favicon.ico"
70
+ }
71
+ ]
72
+ });
73
+ /**
74
+ * Route guard for `beforeLoad`. Routes are public by default; add this to close one.
75
+ *
76
+ * - `requireAuth()` — signed in with any provider. The only gate a population
77
+ * without permission groups (e.g. AWS users) can pass.
78
+ * - `requireAuth("admin")` — signed in *and* in a group listed under that key.
79
+ *
80
+ * `reloadDocument` is required: `/auth/login` is a component-less server route and
81
+ * must be reached with a full-document navigation. It starts the login directly when
82
+ * only one provider is registered, otherwise it forwards to the `/login` chooser.
83
+ */
84
+ const requireAuth = (permissionKey) => {
85
+ return async ({ location, context }) => {
86
+ const user = await getUser({ queryClient: context.queryClient });
87
+ if (!user) throw redirect({
88
+ href: `/auth/login?returnTo=${encodeURIComponent(location.href)}`,
89
+ reloadDocument: true
90
+ });
91
+ if (permissionKey && !hasPermission(user, permissionKey)) throw new Error("You do not have permission to access this page.");
92
+ return { user };
93
+ };
94
+ };
95
+ const NON_PRODUCTION = /(?:^|[.-])(?:dev|qas|uat|test)(?:[.-]|$)/i;
96
+ /** True only for a dev/qas/uat/test domain — localhost and production are not. */
97
+ const isTestEnv = (origin) => NON_PRODUCTION.test((origin ?? "").split(".").slice(1).join("."));
98
+ const getFieldStatus = (field) => {
99
+ const { meta } = field.state;
100
+ return {
101
+ isTouched: meta.isTouched,
102
+ hasError: !!meta.errors.length,
103
+ helperText: meta.errors[0]?.message
104
+ };
105
+ };
106
+ /**
107
+ * Only same-origin paths are allowed, so `returnTo` cannot become an open
108
+ * redirect. Backslash counts as a separator too: browsers normalize `/\evil`
109
+ * to the protocol-relative `//evil`.
110
+ */
111
+ const sanitizeReturnTo = (value) => value && /^\/(?![/\\])/.test(value) ? value : "/";
112
+ const foldForSearch = (value) => String(value ?? "").toLowerCase().normalize("NFD").replaceAll(/[\u{300}-\u{36F}]/gu, "").normalize("NFC");
113
+ const permissionGroups = new Set(Object.values(permissions).flat());
114
+ /**
115
+ * Maps id/access-token claims to the serializable `User`. Groups are trimmed to
116
+ * those named in `permissions.ts` — an unfiltered group list would blow the
117
+ * cookie. Cognito's claim names differ, so both are read.
118
+ */
119
+ const buildUser = (payload, provider) => ({
120
+ provider,
121
+ name: (payload.name ?? payload["cognito:username"] ?? "").split("/")[0],
122
+ email: (payload.preferred_username ?? payload.email ?? "").toLowerCase(),
123
+ department: payload.department?.toUpperCase() || "",
124
+ employeeId: (payload.employeeId ?? payload["cognito:username"] ?? "").toUpperCase(),
125
+ companyName: payload.companyName || "",
126
+ groups: (payload.groups ?? payload["cognito:groups"])?.filter((group) => permissionGroups.has(group)) ?? []
127
+ });
128
+ const hasPermission = (user, key) => user ? permissions[key].some((group) => user.groups.includes(group)) : false;
129
+ export { foldForSearch as a, isTestEnv as c, sanitizeReturnTo as d, buildUser as i, requireAuth as l, WISTRON_PRIMARY_COLOR as n, getFieldStatus as o, WISTRON_SECONDARY_COLOR as r, hasPermission as s, Platform as t, rootRouteHead as u };
130
+
131
+ //# sourceMappingURL=utils-CgabUlDD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-CgabUlDD.mjs","names":[],"sources":["../src/lib/utils.ts"],"sourcesContent":["import type { AnyFieldApi } from \"@tanstack/react-form\";\nimport { redirect } from \"@tanstack/react-router\";\nimport type { ParsedLocation } from \"@tanstack/react-router\";\nimport { manifest, permissions } from \"virtual:wcz-layout\";\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\nimport type { TokenPayload } from \"~/models/TokenPayload\";\nimport type { ProviderId, User } from \"~/models/User\";\nimport { getUser } from \"./auth/user\";\n\nexport const WISTRON_PRIMARY_COLOR = \"#00506E\";\nexport const WISTRON_SECONDARY_COLOR = \"#64DC00\";\n\nexport class Platform {\n static get isAndroid() {\n return /android/i.test(this.userAgent);\n }\n static get isIOS() {\n return /iPad|iPhone|iPod/.test(this.userAgent);\n }\n static get isWindows() {\n return /windows/i.test(this.userAgent);\n }\n static get isMacOS() {\n return /Macintosh|MacIntel|MacPPC|Mac68K/.test(this.userAgent);\n }\n\n private static get userAgent() {\n return typeof navigator === \"undefined\" ? \"\" : navigator.userAgent;\n }\n}\n\ninterface RootRouteHeadOptions {\n manifest?: string;\n}\n\nexport const rootRouteHead = (options?: RootRouteHeadOptions) => ({\n meta: [\n { charSet: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { title: manifest.name },\n { name: \"og:type\", content: \"website\" },\n { name: \"og:title\", content: manifest.name },\n { name: \"og:image\", content: \"/favicon-32x32.png\" },\n ],\n links: [\n { rel: \"apple-touch-icon\", sizes: \"180x180\", href: \"/apple-touch-icon.png\" },\n { rel: \"icon\", type: \"image/png\", sizes: \"32x32\", href: \"/favicon-32x32.png\" },\n { rel: \"icon\", type: \"image/png\", sizes: \"16x16\", href: \"/favicon-16x16.png\" },\n { rel: \"manifest\", href: options?.manifest || \"/manifest.json\" },\n { rel: \"icon\", href: \"/favicon.ico\" },\n ],\n});\n\ntype GuardArgs = { location: ParsedLocation; context: QueryClientParam };\n\n/**\n * Route guard for `beforeLoad`. Routes are public by default; add this to close one.\n *\n * - `requireAuth()` — signed in with any provider. The only gate a population\n * without permission groups (e.g. AWS users) can pass.\n * - `requireAuth(\"admin\")` — signed in *and* in a group listed under that key.\n *\n * `reloadDocument` is required: `/auth/login` is a component-less server route and\n * must be reached with a full-document navigation. It starts the login directly when\n * only one provider is registered, otherwise it forwards to the `/login` chooser.\n */\nexport const requireAuth = (permissionKey?: keyof typeof permissions) => {\n return async ({ location, context }: GuardArgs) => {\n const user = await getUser({ queryClient: context.queryClient });\n\n if (!user)\n throw redirect({\n href: `/auth/login?returnTo=${encodeURIComponent(location.href)}`,\n reloadDocument: true,\n });\n\n if (permissionKey && !hasPermission(user, permissionKey))\n throw new Error(\"You do not have permission to access this page.\");\n\n return { user };\n };\n};\n\n/* Internal Utils */\nconst NON_PRODUCTION = /(?:^|[.-])(?:dev|qas|uat|test)(?:[.-]|$)/i;\n\n/** True only for a dev/qas/uat/test domain — localhost and production are not. */\nexport const isTestEnv = (origin: string | undefined) =>\n NON_PRODUCTION.test((origin ?? \"\").split(\".\").slice(1).join(\".\"));\n\nexport type FormOmittedProps =\n | \"name\"\n | \"value\"\n | \"onChange\"\n | \"onBlur\"\n | \"error\"\n | \"helperText\"\n | \"renderInput\"\n | \"type\"\n | \"aria-label\";\n\nexport const getFieldStatus = (field: AnyFieldApi) => {\n const { meta } = field.state;\n\n const isTouched = meta.isTouched;\n const hasError = !!meta.errors.length;\n const helperText = meta.errors[0]?.message;\n\n return { isTouched, hasError, helperText };\n};\n\n/**\n * Only same-origin paths are allowed, so `returnTo` cannot become an open\n * redirect. Backslash counts as a separator too: browsers normalize `/\\evil`\n * to the protocol-relative `//evil`.\n */\nexport const sanitizeReturnTo = (value: string | null | undefined): string =>\n value && /^\\/(?![/\\\\])/.test(value) ? value : \"/\";\n\nexport const toKebabCase = (str: string): string => {\n return str\n .replaceAll(/([a-z])([A-Z])/g, \"$1-$2\")\n .replaceAll(/[\\s_]+/g, \"-\")\n .replaceAll(/[^a-zA-Z0-9-]/g, \"\")\n .toLowerCase()\n .replaceAll(/-+/g, \"-\")\n .replaceAll(/(^-|-$)/g, \"\");\n};\n\nexport const foldForSearch = (value: unknown): string =>\n String(value ?? \"\")\n .toLowerCase()\n .normalize(\"NFD\")\n .replaceAll(/[\\u{300}-\\u{36F}]/gu, \"\")\n .normalize(\"NFC\");\n\nconst permissionGroups = new Set<string>(Object.values(permissions).flat());\n\n/**\n * Maps id/access-token claims to the serializable `User`. Groups are trimmed to\n * those named in `permissions.ts` — an unfiltered group list would blow the\n * cookie. Cognito's claim names differ, so both are read.\n */\nexport const buildUser = (payload: TokenPayload, provider: ProviderId): User => ({\n provider,\n name: (payload.name ?? payload[\"cognito:username\"] ?? \"\").split(\"/\")[0],\n email: (payload.preferred_username ?? payload.email ?? \"\").toLowerCase(),\n department: payload.department?.toUpperCase() || \"\",\n employeeId: (payload.employeeId ?? payload[\"cognito:username\"] ?? \"\").toUpperCase(),\n companyName: payload.companyName || \"\",\n groups:\n (payload.groups ?? payload[\"cognito:groups\"])?.filter((group) => permissionGroups.has(group)) ??\n [],\n});\n\nexport const hasPermission = (user: User | null, key: keyof typeof permissions): boolean =>\n user ? permissions[key].some((group) => user.groups.includes(group)) : false;\n"],"mappings":"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"}
package/dist/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { l as requireAuth, s as hasPermission, t as Platform } from "./utils-DJx-7b4M.mjs";
1
+ import { l as requireAuth, s as hasPermission, t as Platform } from "./utils-CgabUlDD.mjs";
2
2
  import i18next, { t } from "i18next";
3
3
  import { createEnv } from "@t3-oss/env-core";
4
4
  import { uuidv7 } from "uuidv7";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wcz-layout",
3
- "version": "10.2.1",
3
+ "version": "10.2.2",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "tanstack-intent"
@@ -75,12 +75,12 @@
75
75
  "@t3-oss/env-core": "^0.13.11",
76
76
  "@tanstack/ai-react": "^1.0.2",
77
77
  "@tanstack/markdown": "^1.2.0",
78
- "i18next": "^26.7.1",
78
+ "i18next": "^27.1.3",
79
79
  "i18next-browser-languagedetector": "^8.3.0",
80
- "iron-session": "^9.0.1",
81
- "jose": "^6.2.15",
82
- "react-dropzone": "^20.1.4",
83
- "react-i18next": "^17.1.12",
80
+ "iron-session": "^9.1.0",
81
+ "jose": "^6.2.17",
82
+ "react-dropzone": "^20.2.0",
83
+ "react-i18next": "^18.0.1",
84
84
  "react-intersection-observer": "^11.0.1",
85
85
  "react-number-format": "^5.4.5",
86
86
  "tus-js-client": "^4.3.1",
@@ -88,22 +88,24 @@
88
88
  },
89
89
  "devDependencies": {
90
90
  "@arethetypeswrong/core": "^0.18.5",
91
- "@tanstack/ai": "^1.1.0",
92
- "@tanstack/ai-openai": "^1.1.0",
93
- "@tanstack/highlight": "^1.2.11",
91
+ "@tanstack/ai-code-mode": "^1.1.1",
92
+ "@tanstack/ai-compaction": "^1.0.1",
93
+ "@tanstack/ai-isolate-quickjs": "^1.1.0",
94
+ "@tanstack/ai-openai": "^1.1.1",
95
+ "@tanstack/highlight": "^1.2.12",
94
96
  "@tanstack/intent": "^0.5.6",
95
97
  "@tanstack/react-pacer": "^0.24.1",
96
98
  "@types/node": "^26.6.6",
97
99
  "@types/react": "^19.3.0",
98
100
  "@types/react-dom": "^19.3.0",
99
- "@vitejs/plugin-react": "^6.2.1",
100
- "jsdom": "^30.1.3",
101
+ "@vitejs/plugin-react": "^6.3.0",
102
+ "jsdom": "^31.0.1",
101
103
  "nitro": "3.0.261103-rc",
102
104
  "oxc-transform-react": "^0.156.0",
103
105
  "publint": "^0.3.25",
104
106
  "typescript": "^7.0.2",
105
- "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
106
- "vite-plus": "1.5.0"
107
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.6.0",
108
+ "vite-plus": "1.6.0"
107
109
  },
108
110
  "peerDependencies": {
109
111
  "@emotion/cache": "11.x",
@@ -112,6 +114,10 @@
112
114
  "@mui/icons-material": "9.x",
113
115
  "@mui/material": "9.x",
114
116
  "@mui/x-date-pickers": "9.x",
117
+ "@tanstack/ai": "1.x",
118
+ "@tanstack/ai-code-mode": "1.x",
119
+ "@tanstack/ai-compaction": "1.x",
120
+ "@tanstack/ai-isolate-quickjs": "1.x",
115
121
  "@tanstack/ai-openai": "1.x",
116
122
  "@tanstack/charts": "1.x",
117
123
  "@tanstack/react-form": "1.x",
@@ -130,11 +136,26 @@
130
136
  "zod": "4.x"
131
137
  },
132
138
  "peerDependenciesMeta": {
139
+ "@tanstack/ai": {
140
+ "optional": true
141
+ },
142
+ "@tanstack/ai-code-mode": {
143
+ "optional": true
144
+ },
145
+ "@tanstack/ai-compaction": {
146
+ "optional": true
147
+ },
148
+ "@tanstack/ai-isolate-quickjs": {
149
+ "optional": true
150
+ },
133
151
  "@tanstack/ai-openai": {
134
152
  "optional": true
135
153
  }
136
154
  },
137
155
  "overrides": {
156
+ "@tanstack/ai-persistence": {
157
+ "vitest": "5.1.0"
158
+ },
138
159
  "vite": "$vite"
139
160
  },
140
161
  "packageManager": "npm@12.2.2"
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ai
3
- description: "Use when adding LLM features (chat, streamed text, structured output, tools, media generation)"
3
+ description: "Use when adding LLM features (the assistant, chat, streamed text, structured output, tools, media generation)"
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
@@ -11,18 +11,50 @@ metadata:
11
11
 
12
12
  ## Rules
13
13
 
14
- - Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing); the server function imports it directly.
15
- `@tanstack/charts` is a peer of wcz-layout, which npm installs with it; the chat loads it with
16
- the first chart the model draws, so an app never defines a chart tool of its own.
14
+ - Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing). An app with the
15
+ assistant also installs `@tanstack/ai-code-mode`, `@tanstack/ai-isolate-quickjs` and
16
+ `@tanstack/ai-compaction`: `layoutChat` loads them on its first call. Code mode's optional
17
+ peers ask for an older vitest than vite-plus brings, so npm refuses to install it until the
18
+ app's `package.json` has `"overrides": { "@tanstack/ai-persistence": { "vitest": "<version>" } }`,
19
+ with the version `npm ls vitest` shows. `@tanstack/charts` is a peer of wcz-layout, which npm
20
+ installs with it; the chat loads it with the first chart the model draws.
21
+ - Code mode runs the model's programs in QuickJS, whose WebAssembly a production bundle leaves
22
+ behind: give the app's `nitro()` plugin `traceDeps: ["quickjs-emscripten"]` in `vite.config.ts`.
17
23
  - Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
18
24
  startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
19
25
  uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
20
26
  Values come from `.env.local` or Vault.
21
- - Import the adapter from `wcz-layout/ai`: `adapter: await chatAdapter("gpt-5.5")`, created
22
- per request inside the server function. It sends the app token and the subscription key itself.
23
- Never build an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups
24
- with `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments.
25
- - Call `chatAdapter` only in server functions (`src/server/...`): it reads server env and tokens.
27
+ - The assistant is one server function that returns `layoutChat({ data, user, systemPrompts,
28
+ tools, guides })` from `wcz-layout/ai`, and nothing else. `layoutChat` brings what every app's
29
+ assistant shares: the model, code mode, the guides, the shared rules (how to read and change
30
+ data, deletes, charts, attached files, the page, the reply's language), who the user is, a
31
+ conversation bounded at 100k tokens and a `[chat]` line in the server log with the tokens of
32
+ each model call. Never call `chat()` for the assistant yourself, and never repeat those rules
33
+ in the app's prompt.
34
+ - `systemPrompts` say only what the app is: what its records are called and mean, what the
35
+ assistant cannot do there, and the paths of its pages (`[name](/orders/<id>)`), so the model
36
+ links the records it mentions. Keep it the same for every user and every request: no user,
37
+ date or page in it, or the provider's prompt cache misses. `layoutChat` adds the user; the
38
+ model reads the time with `get_time` and the page with `read_page` when a request needs them.
39
+ - `tools` are server tools (`toolDefinition(...).server(...)`) that call the app's own server
40
+ functions, `deleteOrder({ data: id })`: called on the server they run in the same request, with
41
+ the screens' middleware, validation and permission checks. Never reimplement a server function
42
+ for a tool. After a write, `context?.emitCustomEvent("invalidate", { queryKey })` makes the
43
+ chat invalidate that query, so open screens refetch.
44
+ - A tool without `needsApproval` becomes a function of the programs the model runs
45
+ (`execute_typescript`): it reads, filters, joins and counts on the server, and creates or
46
+ changes many records in one program, e.g. a device per row of an attached spreadsheet. Only
47
+ the program's answer enters the conversation. So a reading tool takes no filters: it returns
48
+ every record the user may see, with an `outputSchema` that gives the model the rows' shape.
49
+ - Only tools that delete get `needsApproval: true`. They stay tool calls of their own, and the
50
+ chat asks "Are you sure?" (Cancel / Confirm) before one runs.
51
+ - Give feature tools `lazy: true`: the model sees names and first sentences, and loads a
52
+ feature's types only when a request needs them. Write each description's first sentence to
53
+ stand alone.
54
+ - `guides` is how the app works, as markdown by topic, each starting with a `# Title` line:
55
+ `import orders from "./guides/orders.md?raw"`. Only the titles ride on every request; the
56
+ model reads a guide when a question touches it. Write them from the user's view: the rules,
57
+ who may do what, what happens next. This is what lets a new user ask anything about the app.
26
58
  - Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
27
59
  `Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
28
60
  into each of the app's locale files, or the chat shows raw keys.
@@ -31,48 +63,45 @@ metadata:
31
63
  `options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
32
64
  open. From `lg` up it docks beside the page and remembers its width and whether it is open;
33
65
  below `lg` it covers the page right of the navigation rail, opens only from the button and
34
- closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its own sits in a
35
- parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root, e.g. a background;
36
- it has none of its own.
66
+ closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its
67
+ own sits in a parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root,
68
+ e.g. a background; it has none of its own.
69
+ - The chat brings these without any app code. Never build them again:
70
+ - Files: the user drops them anywhere on the chat, pastes them or picks them. They travel in
71
+ the message, never to the file service, and the model reads them as they are: images, PDF,
72
+ Word, Excel, PowerPoint, CSV and text, up to 10 MB each. Nothing is parsed in the app. Of a
73
+ spreadsheet the model sees the first 1000 rows of each sheet.
74
+ - A message sent while a reply streams waits in a queue above the input, where it can be
75
+ cancelled.
76
+ - The conversation survives a reload and ends with the tab (`sessionStorage`, per user).
77
+ - Each tool shows as one line with its name, and a program with the functions it calls.
37
78
  - Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
38
79
  charts: a `Chart` node with TanStack Charts marks as children, their official options as
39
- props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme` (light,
40
- dark or system), `navigate` (opens one of the app's pages, listed from its route tree, and
41
- leaves a page whose record was just deleted), `get_time` (the user's current time and zone,
42
- so the prompt never states it), and `read_page`, `click`, `fill` and `press_key` (the model
43
- uses the page the user is on as they would: it reads the text and numbered controls, clicks,
44
- types and presses keys, and never answers a `useDialogs` confirmation). Never define them
45
- again. The client sends its tools with every request, so the
46
- server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
47
- forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
48
- - The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
49
- `aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
50
- - Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` that
51
- call the app's own server functions, `deleteOrder({ data: id })`: called on the server they run
52
- in the same request, with the screens' middleware, validation and permission checks. Never
53
- reimplement a server function for a tool. After a write,
54
- `context?.emitCustomEvent("invalidate", { queryKey })` makes the chat invalidate that query, so
55
- open screens refetch.
56
- - Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
57
- Confirm) before they run, so the prompt tells the model to say first what it will delete.
58
- Creating and changing run straight away, and the model says what it did.
59
- - Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
60
- "first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
61
- schemas only when a request needs them. Write each description's first sentence to stand alone.
62
- Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
63
- once discovering, looking up and saving add up.
80
+ props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme`
81
+ (light, dark or system), `navigate` (opens one of the app's pages, listed from its route tree,
82
+ and leaves a page whose record was just deleted), `get_time` (the user's current time and
83
+ zone), and `read_page`, `click`, `fill` and `press_key` (the model uses the page the user is on
84
+ as they would: it reads the address, the text, the numbered controls and the one the user was
85
+ last in, clicks, types and presses keys, and never answers a `useDialogs` confirmation). Never
86
+ define them again.
64
87
  - The page tools read what a screen reader would, so a page the model can use has a name on
65
88
  every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
66
89
  and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
67
90
  `useDialogs`, which the model never clicks.
68
91
  - Other browser actions are client tools:
69
92
  `useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
70
- - The chat renders markdown links to the app's own pages (`/...`) through the router; tell the
71
- model the page paths so it links the records it mentions.
93
+ - One-off calls (a translation, a typed answer, reading a document) are `chat()` with
94
+ `adapter: await chatAdapter("gpt-5.5")` from `wcz-layout/ai`, created per request in a server
95
+ function (`src/server/...`): it reads server env and tokens, and sends the app token and the
96
+ subscription key itself. It is the one adapter for everything, files included: a `document`
97
+ part with `source: { type: "data", value: base64, mimeType }` and `metadata: { filename }`
98
+ reaches the model as the file itself (PDF, Word, Excel, PowerPoint, CSV, text). Never build
99
+ an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups with
100
+ `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments, and
101
+ TanStack's own Chat Completions adapter refuses documents.
72
102
  - Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
73
- `outputSchema` and `partial`, not the chat.
74
- - Render streamed text outside the chat with `@tanstack/markdown` (install if missing):
75
- `<Markdown>` from `@tanstack/markdown/react`.
103
+ `outputSchema` and `partial`, not the chat. Render streamed text outside the chat with
104
+ `@tanstack/markdown` (install if missing): `<Markdown>` from `@tanstack/markdown/react`.
76
105
 
77
106
  ## Example
78
107
 
@@ -82,22 +111,39 @@ AI_BASE_URL: z.url(),
82
111
  AI_SUBSCRIPTION_KEY: z.string(),
83
112
 
84
113
  // src/server/actions/assistant.ts
85
- import {
86
- chat,
87
- chatParamsFromRequestBody,
88
- maxIterations,
89
- mergeAgentTools,
90
- toServerSentEventsResponse,
91
- toolDefinition,
92
- } from "@tanstack/ai";
114
+ import { toolDefinition } from "@tanstack/ai";
93
115
  import type { RunAgentInput } from "@tanstack/ai/client";
94
116
  import { createServerFn } from "@tanstack/react-start";
117
+ import { layoutChat } from "wcz-layout/ai";
95
118
  import { authMiddleware } from "wcz-layout/middleware";
96
- import { chatAdapter } from "wcz-layout/ai";
97
119
  import z from "zod";
98
- import { deleteOrder } from "./order"; // the server function the screens call
120
+ import { OrderSchema } from "~/lib/schemas/order";
121
+ import orders from "../guides/orders.md?raw";
122
+ import { deleteOrder, insertOrder, selectOrders } from "./order"; // the screens' server functions
99
123
 
100
- const orderTools = () => [
124
+ const SYSTEM_PROMPT =
125
+ "You are the assistant in Orders, the application in which departments order material. " +
126
+ "Link an order to its page with a markdown link: [number](/orders/<id>).";
127
+
128
+ const orderTools = [
129
+ toolDefinition({
130
+ name: "list_orders",
131
+ description: "Every order the user can see, with its lines and state.",
132
+ inputSchema: z.object({}),
133
+ outputSchema: OrderSchema.array(),
134
+ lazy: true,
135
+ }).server(() => selectOrders()),
136
+ toolDefinition({
137
+ name: "create_order",
138
+ description: "Create an order. It needs a supplier and at least one line.",
139
+ inputSchema: OrderSchema.omit({ id: true }),
140
+ lazy: true,
141
+ }).server(async (order, context) => {
142
+ const id = crypto.randomUUID();
143
+ await insertOrder({ data: { ...order, id } });
144
+ context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
145
+ return { id, page: `/orders/${id}` };
146
+ }),
101
147
  toolDefinition({
102
148
  name: "delete_order",
103
149
  description: "Delete one of the user's orders.",
@@ -114,28 +160,15 @@ const orderTools = () => [
114
160
  export const assistant = createServerFn({ method: "POST" })
115
161
  .validator(z.custom<RunAgentInput>())
116
162
  .middleware([authMiddleware()])
117
- .handler(async ({ data }) => {
118
- const { messages, threadId, runId, parentRunId, resume, tools, aguiContext } =
119
- await chatParamsFromRequestBody(data);
120
- const abortController = new AbortController();
121
- const stream = chat({
122
- adapter: await chatAdapter("gpt-5.5"),
123
- threadId,
124
- runId,
125
- parentRunId,
126
- resume,
127
- systemPrompts: [
128
- SYSTEM_PROMPT,
129
- ...aguiContext.map(({ description, value }) => `${description}: ${value}`),
130
- ],
131
- messages,
132
- tools: mergeAgentTools(orderTools(), tools),
133
- lazyToolsConfig: { includeDescription: "first-sentence" },
134
- agentLoopStrategy: maxIterations(20),
135
- abortController,
136
- });
137
- return toServerSentEventsResponse(stream, { abortController });
138
- });
163
+ .handler(({ data, context: { user } }) =>
164
+ layoutChat({
165
+ data,
166
+ user,
167
+ systemPrompts: [SYSTEM_PROMPT],
168
+ tools: orderTools,
169
+ guides: { orders },
170
+ }),
171
+ );
139
172
  ```
140
173
 
141
174
  ```tsx
@@ -50,9 +50,13 @@ export const scopes = {
50
50
 
51
51
  From `wcz-layout/auth`, server-only (call inside a server function or server route):
52
52
 
53
- - `getAccessToken(scopeKey)` — delegated token for the signed-in user from their session.
54
- Requires a browser session (a Bearer caller has none). An expired session clears the cookie
55
- and throws a 401 `Response`.
53
+ - `getAccessToken(scopeKey)` — delegated token for the user behind the request: minted from
54
+ their session, or, when a sibling service calls with an Entra user token as Bearer, exchanged
55
+ for it on behalf of that user (OBO). OBO needs this app's registration to hold the delegated
56
+ permission for the downstream API, with admin consent; Cognito has no OBO, so an AWS Bearer
57
+ caller or an app token counts as no user and throws. An expired session clears the cookie and
58
+ throws a 401 `Response`. `createApi` services use it whenever there is a user, and fall back
59
+ to `getAppToken` otherwise.
56
60
  - `getAppToken(scopeKey)` — app-only Entra token (client credentials, `<resource>/.default`),
57
61
  cached in memory. For background jobs and calls with no user.
58
62
  - Downstream APIs must trust both issuers to accept AWS users; Cognito tokens have no `aud`
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: services
3
- description: "Use when a feature needs a built-in wcz-layout backend service: file upload, download, thumbnails; approval requests, approvers and flows; PeopleSoft employee, manager, department lookups; or sending email."
3
+ description: "Use when a feature needs a built-in wcz-layout backend service: file upload, download, thumbnails; approval requests, approvers and flows; PeopleSoft employee, manager, department lookups; sending email; or AI features: translating text into several languages with language detection, and extracting fields from an uploaded PDF or image. Also when an app calls another downstream REST API that wcz-layout has no service for."
4
4
  metadata:
5
5
  type: integration
6
6
  library: wcz-layout
@@ -26,9 +26,43 @@ You can read about each service in the links below. Services are categorized as
26
26
 
27
27
  ## Services
28
28
 
29
- | Service | File | Summary |
30
- | ---------- | ----------------------------------- | ----------------------------------------------------------------------- |
31
- | file | [file.md](docs/file.md) | File metadata, thumbnails, binary download/open, upload, update, delete |
32
- | approval | [approval.md](docs/approval.md) | Approval request lifecycle, approvers, flows, statuses, step results |
33
- | peoplesoft | [peoplesoft.md](docs/peoplesoft.md) | Employee, manager, department, and company general manager lookups |
34
- | email | [email.md](docs/email.md) | Server-only email sending with optional file attachment references |
29
+ | Service | File | Summary |
30
+ | ---------- | ----------------------------------- | ------------------------------------------------------------------------ |
31
+ | file | [file.md](docs/file.md) | File metadata, thumbnails, binary download/open, upload, update, delete |
32
+ | approval | [approval.md](docs/approval.md) | Approval request lifecycle, approvers, flows, statuses, step results |
33
+ | peoplesoft | [peoplesoft.md](docs/peoplesoft.md) | Employee, manager, department, and company general manager lookups |
34
+ | email | [email.md](docs/email.md) | Server-only email sending with optional file attachment references |
35
+ | layout | [layout.md](docs/layout.md) | Layout app AI: translation with language detection, file data extraction |
36
+
37
+ ## Custom API
38
+
39
+ When the app needs a downstream REST API that no service above covers, build the client with
40
+ `createApi` from `wcz-layout/data/server`. It resolves the base URL from env, attaches the
41
+ signed-in user's token for the scope and turns error responses into `Error(message)`. It is
42
+ server-only: call it inside a server function handler, never at module scope.
43
+
44
+ 1. `src/env.ts`: add `MY_API_BASE_URL: z.url()` to `serverEnv` (the key must contain `BASE_URL`).
45
+ 2. `src/lib/auth/scopes.ts`: add `myApi: "api://wistron.com/my-api/access_as_user"`.
46
+ 3. `src/lib/schemas/<name>.ts`: Zod input schemas and response models.
47
+ 4. `src/server/actions/<name>.ts`: one server function per endpoint, gated with `authMiddleware`
48
+ (the token belongs to the signed-in user); see **server-functions**.
49
+
50
+ ```ts
51
+ import { createServerFn } from "@tanstack/react-start";
52
+ import { createApi } from "wcz-layout/data/server";
53
+ import { authMiddleware } from "wcz-layout/middleware";
54
+ import { MyModelSchema, type MyModel } from "~/lib/schemas/inventory";
55
+
56
+ const myApi = () => createApi({ baseURL: "MY_API_BASE_URL", scopeKey: "myApi" });
57
+
58
+ export const getItem = createServerFn({ method: "GET" })
59
+ .validator(MyModelSchema)
60
+ .middleware([authMiddleware()])
61
+ .handler(async ({ data }) => {
62
+ const api = await myApi();
63
+ const { data: item } = await api.get<MyModel>(`/items/${encodeURIComponent(data.id)}`);
64
+ return item;
65
+ });
66
+ ```
67
+
68
+ Wrap reads in `queryOptions` and writes in `mutationOptions`, the same shape as the built-in client exports.