@noodleseed/one 0.182.0 → 0.183.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@noodle-borg/agent-kit/dist/generated/example-files.js +2 -2
- package/node_modules/@noodle-borg/agent-kit/dist/skill-embedded-assistant-ref.js +1 -1
- package/node_modules/@noodle-borg/agent-kit/package.json +1 -1
- package/node_modules/@noodle-borg/assistant-gateway/package.json +1 -1
- package/node_modules/@noodle-borg/authoring/dist/assistant.d.ts +6 -0
- package/node_modules/@noodle-borg/authoring/dist/assistant.js +3 -0
- package/node_modules/@noodle-borg/compiler/dist/manifest/assistant-ui-schema.js +123 -0
- package/node_modules/@noodle-borg/compiler/dist/manifest/schema.d.ts +4 -0
- package/node_modules/@noodle-borg/compiler/dist/manifest/schema.js +1 -103
- package/node_modules/@noodle-borg/service/dist/channels/runtime.js +6 -4
- package/node_modules/@noodle-borg/service/dist/conversation-history/capture.js +28 -3
- package/node_modules/@noodle-borg/service/package.json +1 -1
- package/node_modules/@noodle-borg/wire-contracts/dist/assistant.d.ts +1 -0
- package/node_modules/@noodle-borg/wire-contracts/dist/assistant.js +8 -1
- package/node_modules/@noodleseed/assistant/README.md +6 -0
- package/node_modules/@noodleseed/assistant/package.json +1 -1
- package/package.json +3 -3
|
@@ -55,10 +55,10 @@ export const BUNDLED_EXAMPLE_FILES = [
|
|
|
55
55
|
{ relPath: "examples/acme-tasks/src/views/widget-style.css", content: ":root {\n color-scheme: light dark;\n font-family:\n Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --nw-bg: #ffffff;\n --nw-surface: #f7f5ff;\n --nw-text: #1c1830;\n --nw-muted: #635d80;\n --nw-border: #e2ddf5;\n --nw-accent: #7c3aed;\n --nw-accent-strong: #6d28d9;\n --nw-accent-soft: #efe9ff;\n --nw-high: #dc2626;\n --nw-medium: #b45309;\n --nw-low: #2563eb;\n --nw-radius: 10px;\n --nw-shadow: 0 18px 50px rgb(30 20 60 / 12%);\n}\n\n.dark,\n[data-theme=\"dark\"] {\n --nw-bg: #161228;\n --nw-surface: #1d1735;\n --nw-text: #f2eeff;\n --nw-muted: #a99fce;\n --nw-border: #342a54;\n --nw-accent: #a78bfa;\n --nw-accent-strong: #8b5cf6;\n --nw-accent-soft: #2a2148;\n --nw-high: #f87171;\n --nw-medium: #fbbf24;\n --nw-low: #60a5fa;\n --nw-shadow: 0 18px 50px rgb(0 0 0 / 32%);\n}\n\n* {\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\nbutton,\ninput,\nselect {\n font: inherit;\n}\n\n.nw-shell {\n min-height: 100vh;\n padding: 14px;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\n.nw-card {\n max-width: 620px;\n margin: 0 auto;\n background: var(--nw-surface);\n border: 1px solid var(--nw-border);\n border-radius: var(--nw-radius);\n box-shadow: var(--nw-shadow);\n overflow: hidden;\n}\n\n.nw-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px;\n border-bottom: 1px solid var(--nw-border);\n}\n\n.nw-icon svg {\n width: 24px;\n height: 24px;\n fill: none;\n stroke: var(--nw-accent);\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n\n.nw-title-block {\n flex: 1;\n min-width: 0;\n}\n\n.nw-title {\n margin: 0;\n font-size: 17px;\n font-weight: 700;\n}\n\n.nw-subtitle {\n margin: 2px 0 0;\n font-size: 13px;\n color: var(--nw-muted);\n}\n\n.nw-chip {\n padding: 4px 10px;\n border-radius: 999px;\n background: var(--nw-accent-soft);\n color: var(--nw-accent-strong);\n font-size: 12px;\n font-weight: 600;\n}\n\n.nw-capture {\n display: flex;\n gap: 8px;\n padding: 14px 16px 4px;\n}\n\n.nw-input {\n flex: 1;\n padding: 9px 12px;\n border: 1px solid var(--nw-border);\n border-radius: 10px;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\n.nw-button {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 9px 14px;\n border: 1px solid var(--nw-border);\n border-radius: 10px;\n background: var(--nw-bg);\n color: var(--nw-text);\n cursor: pointer;\n}\n\n.nw-button-primary {\n background: var(--nw-accent);\n border-color: var(--nw-accent);\n color: #ffffff;\n font-weight: 600;\n}\n\n.nw-button-primary:disabled {\n opacity: 0.6;\n cursor: default;\n}\n\n.nw-list {\n list-style: none;\n margin: 0;\n padding: 8px 16px 4px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.nw-task {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 10px 12px;\n border: 1px solid var(--nw-border);\n border-radius: 12px;\n background: var(--nw-bg);\n}\n\n.nw-task-title {\n flex: 1;\n min-width: 0;\n}\n\n.nw-task-done {\n opacity: 0.55;\n}\n\n.nw-task-done .nw-task-title {\n text-decoration: line-through;\n}\n\n.nw-check {\n width: 22px;\n height: 22px;\n border: 1.5px solid var(--nw-border);\n border-radius: 999px;\n background: transparent;\n color: #ffffff;\n cursor: pointer;\n flex: none;\n}\n\n.nw-check-on {\n background: var(--nw-accent);\n border-color: var(--nw-accent);\n}\n\n.nw-priority {\n padding: 5px 8px;\n border: 1px solid var(--nw-border);\n border-radius: 8px;\n background: var(--nw-bg);\n color: var(--nw-text);\n font-size: 12px;\n font-weight: 600;\n}\n\n.nw-priority-high {\n color: var(--nw-high);\n}\n\n.nw-priority-medium {\n color: var(--nw-medium);\n}\n\n.nw-priority-low {\n color: var(--nw-low);\n}\n\n.nw-note {\n margin: 0;\n padding: 8px 16px 16px;\n font-size: 12px;\n color: var(--nw-muted);\n}\n" },
|
|
56
56
|
{ relPath: "examples/acme-tasks/test/server.test.ts", content: "import { describe, expect, it } from 'vitest';\nimport app from '../src/server.js';\n\ndescribe('acme-tasks example', () => {\n it('exports a Noodle server definition', () => {\n expect(typeof app.toManifest).toBe('function');\n });\n\n it('exposes a tool for each of the top-3 prioritized flows', async () => {\n // Capture → add_task, Prioritize → list_today (+ set_priority helper), Complete → complete_task.\n const text = JSON.stringify(await app.toManifest());\n expect(text).toContain('add_task');\n expect(text).toContain('list_today');\n expect(text).toContain('complete_task');\n expect(text).toContain('set_priority');\n });\n\n it('seeds today’s list highest-priority first', async () => {\n const text = JSON.stringify(await app.toManifest());\n expect(text).toMatch(/\"tasks\":\\[\\{\"id\":\"email_vendor\".*\"priority\":\"high\"/);\n });\n\n it('opts the conversational completion action into runtime confirmation', async () => {\n const manifest = await app.toManifest();\n const completeTask = manifest.tools.find((candidate) => candidate.name === 'complete_task');\n const addTask = manifest.tools.find((candidate) => candidate.name === 'add_task');\n const setPriority = manifest.tools.find((candidate) => candidate.name === 'set_priority');\n\n expect(completeTask?.annotations?.confirm).toBe(true);\n expect(addTask?.annotations).not.toHaveProperty('confirm');\n expect(setPriority?.visibility).toEqual(['app']);\n });\n\n it('teaches its three product workflows through one host-neutral agent guide', async () => {\n const manifest = await app.toManifest();\n const guide = manifest.server.agentGuide;\n\n expect(guide?.workflows.map((workflow) => workflow.id)).toEqual([\n 'review_tasks',\n 'capture_task',\n 'complete_task',\n ]);\n expect(\n guide?.workflows.flatMap((workflow) => workflow.steps.map((step) => step.capability.name)),\n ).toEqual(expect.arrayContaining(['list_today', 'set_priority', 'add_task', 'complete_task']));\n expect(\n guide?.workflows\n .find((workflow) => workflow.id === 'review_tasks')\n ?.steps.map((step) => step.capability.name),\n ).toContain('set_priority');\n expect(\n guide?.examples.every((example) =>\n guide.workflows.some((workflow) => workflow.id === example.workflow),\n ),\n ).toBe(true);\n expect(guide?.boundaries.some((boundary) => boundary.toLowerCase().includes('confirm'))).toBe(\n true,\n );\n });\n});\n" },
|
|
57
57
|
{ relPath: "examples/acme-tasks/vitest.config.ts", content: "import { defineConfig } from 'vitest/config';\n\n// Local config so `npm test` (vitest run) discovers this example's own tests instead of inheriting a\n// parent monorepo config's include globs.\nexport default defineConfig({\n test: { include: ['test/**/*.test.ts'] },\n});\n" },
|
|
58
|
-
{ relPath: "examples/customer-auth/README.md", content: "# Customer Auth - OIDC identity and customer-routed APIs\n\nFor a visitor who starts before signup, use the [Stateful Draft reference](../stateful-draft/README.md)\nalongside this authenticated backend integration.\n\nThis curated example owns the customer/end-user authentication capability slot. It proves that a SaaS app\ncan protect an MCP endpoint with direct OIDC, retain role/scope-based tool authorization, and route ordinary\nreads and confirmed actions to the API origin selected by the verified customer's identity provider.\n\nDirect MCP calls obtain the private route from verified OIDC claims; embedded sessions obtain it from the authenticated backend. Both keep routes out of model and browser state.\n\nThe public developer entrypoint is [`src/server.ts`](src/server.ts). It exposes a deliberately small MCP\nsurface for organization discovery and app lifecycle operations:\n\n- `help` explains the product without customer identity.\n- `list_my_organizations` publicly advertises its descriptor but requires `organizations:read` to list the signed-in customer’s organizations.\n- `list_org_apps` uses `authorization.discovery: 'public'` to expose its descriptor on an anonymously\n accessible endpoint. Execution still requires `org_apps:read` and `org_admin` or `org_member`. Visibility\n grants no permissions, records, role disclosure, or product-guide eligibility. ChatGPT sign-in is unproven.\n- `archive_org_app` archives one app only after exact runtime confirmation. It requires the\n `org_apps:write` scope and `org_admin` role.\n\nThe tools chain: `list_my_organizations` surfaces the `org_id`s the customer can act on,\n`list_org_apps` takes one of those ids, and `archive_org_app` accepts the selected app id. Tool code remains\nindependent of the selected origin.\n\nThe typed `agentGuide` retains only complete workflows the verified caller can execute. Public descriptor discovery does not grant workflow access. See the [runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime) for embedded behavior and the draft MCP Skills preview.\n\n## Declare the customer endpoint\n\n`customerEndpoint` names one private routing authority and bounds the origins an IdP may select:\n\n```ts\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\n```\n\nUse either non-empty `allowedHttpsHostSuffixes` or non-empty `allowedHttpsOrigins`, never both. Exact-origin\npolicies may include a non-default port. Suffix policies match only the exact hostname or dot-boundary\nsubdomains on port 443. A routed connector must not add `allowedOrigins`; its endpoint policy is the egress\nallowlist.\n\nThe connector uses that declaration as its normal base URL. Its token endpoint remains a fixed, independently\nvalidated HTTPS URL:\n\n```ts\nconst api = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n // read and action operations...\n },\n });\n```\n\n`delegatedTokenExchange` consumes a verified customer caller; an MCP access mode does not create one. The\nserver must declare `customerAuth.*(...)` or `embeddedAssistant(...)` so Noodle Seed can establish the caller\nsubject, issuer, and audience. Otherwise `noodle validate`, `noodle auth doctor`, and deploy fail early with\n`delegated_token_exchange_identity_required`, before secrets are resolved or any connector egress. A\nsuccessful local Devtools exchange is not evidence that the hosted server has an identity source. Devtools\nsupplies a separate, loopback-only local identity context that is never accepted by hosted deployment.\n\nAt both connector and operation level, auth must be omitted or use `delegatedTokenExchange`. The compiler\nvalidates the concrete connector definition emitted from TypeScript, including connector defaults and\noperation overrides, and reports the exact failing auth path and kind. Do not keep a bearer, API-key,\nclient-credentials, or managed-provider fallback for local mode; use operation fakes while leaving auth\ndeclarative.\n\n## Map the endpoint from verified OIDC\n\nThe IdP claim contains the complete base URL, including an optional base path. Routing is separate from the\npublic `${user}` expression scope:\n\n```ts\nauth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n}),\n```\n\nFor federated OIDC, put the same endpoint map on every issuer. Claim paths may differ, but each issuer must\nmap every endpoint the app uses:\n\n```ts\nauth: customerAuth.federatedOidc({\n issuers: [\n {\n issuer: 'https://id.customer-a.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n },\n {\n issuer: 'https://login.customer-b.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'organization.routes.customer_api' },\n },\n },\n },\n ],\n}),\n```\n\nAt runtime, Noodle Seed validates the configured stable audience, associates the caller with the exact\ntransport-derived MCP resource, projects the route into private request state, applies its policy, and\nfreezes it for the call. Missing, malformed, or\ndisallowed claims return `connector_route_unavailable` before credential lookup or connector egress.\nResolved URLs never enter artifacts, `${user}`, logs, model output, widgets, public confirmation review,\nbroker cache keys, or delegated exchange assertions.\n\nRouted reads work in tools, including declared nested calls. Routed actions require exact\n`annotations.confirm: true`; otherwise they fail with `customer_endpoint_action_unsupported`. Routed\nresources, prompts, and ambient context fail with `customer_endpoint_surface_unsupported`.\n\nThe flagship's routed action uses the normal TypeScript action helper:\n\n```ts\ntool('archive_org_app', {\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n // input, output, and the normal connectors.app_api.archiveOrgApp(...) call...\n});\n```\n\nThe flagship also opts into the current stateless hosted MCP path:\n\n```ts\ninteractions: {\n confirmationFallback: 'host',\n},\n```\n\nA bidirectional client that negotiated form elicitation can complete the standard confirmation exchange\ninstead. The explicit host fallback trusts the MCP host to have collected native write approval before the\ntool call reaches Noodle Seed; it is never inferred from client identity and does not replace auth, policy,\nor accurate action/destructive annotations. Omit the fallback when connected hosts are not trusted to\nprovide that approval. If neither standard confirmation nor the fallback is available, the action fails\nclosed with `interaction_unavailable`.\n\nPreparation stores only sorted route `{ key, fingerprint }` bindings in its private server-held\ncontinuation; the public review exposes none of them. Acceptance re-resolves the current request route and\nreturns `invalid_continuation` if it is missing or changed, before policy, credentials, or egress. A match\nreuses the current frozen snapshot for the action and all nested or later reads.\n\nThe application developer owns the direct/federated authorization server. It must publish its path-inserted\nRFC 8414 document as direct HTTP 200 JSON with exact issuer and HTTPS authorization/token/registration/JWKS\nendpoints, authorization-code and refresh grants, PKCE S256, public-client auth method `none`, RFC 8707\nresource handling, and public signing keys. It validates each exact MCP resource on authorize, code exchange,\nand refresh, then maps approved versions of this app/environment to `noodleseed-customer-auth-prod`. Other\napps and environments use distinct audiences.\n\nRun `noodle auth doctor src/server.ts` before sharing. Its bounded, read-only probes never register a client.\nAdding the embedded assistant does not choose or rewrite MCP customer auth. Its authenticated backend may\nbind `routing.endpoints.customer_api` during assistant-session exchange from server-owned membership data;\ndirect MCP requests continue to resolve the same endpoint from the configured verified OIDC claim.\n\n## Per-tool authorization remains independent\n\nThe mapped `roles` and `scopes` paths are read only after OIDC verification. The restricted tool declares its\nrule beside the rest of its public contract:\n\n```ts\ntool('list_org_apps', {\n authorization: {\n discovery: 'public',\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n // input, output, and fulfilment...\n});\n```\n\nEvery required scope must be present and at least one allowed role must match. When both lists are declared,\nboth conditions apply. In mixed customer mode, `discovery: 'public'` exposes this descriptor before sign-in;\nexecution still requires those scopes and roles. Other restricted tools remain filtered by authorization.\nRoute availability never changes discovery, and unauthorized direct calls fail closed.\n\nTool code calls the connector normally:\n\n```ts\nfulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n\n return { result: apps.result };\n}\n```\n\nThe broker exchanges a short-lived, platform-signed assertion at the fixed token endpoint and caches the\nresult by caller, connector, scopes, and a route fingerprint. The assertion carries only the route key and\nfingerprint, never the URL. The MCP access token is never forwarded to the customer API. The exchange wire\ncontract lives in docs/spec/connectors.md.\n\nFirebase and Microsoft remain supported managed adapters; their provider-specific contracts and tests live\nin docs/spec/auth-and-policy.md and the SharePoint flagship.\n\n## Supabase direct-OIDC access-token hook\n\nDynamic Client Registration lets any OAuth client register, so the presence of `client_id` is not approval.\nKeep an operator-controlled client-to-audience map and rewrite `aud` only for an exact mapped client. For a\ndynamically registered client, review its generated client ID, name, and exact redirect URIs in the consent\nflow before adding the mapping. Each new registration needs its own row; never approve by name or prefix.\n\nReplace `<approved-oauth-client-id>` with the reviewed client ID and `<stable-mcp-audience>` with the exact\nvalue configured in `customerAuth.oidc`:\n\n```sql\ncreate table if not exists public.mcp_oauth_client_audiences (\n client_id text primary key check (btrim(client_id) <> ''),\n audience text not null check (btrim(audience) <> '')\n);\n\nrevoke all on table public.mcp_oauth_client_audiences from authenticated, anon, public;\ngrant usage on schema public to supabase_auth_admin;\ngrant select on table public.mcp_oauth_client_audiences to supabase_auth_admin;\n\ninsert into public.mcp_oauth_client_audiences (client_id, audience)\nvalues ('<approved-oauth-client-id>', '<stable-mcp-audience>')\non conflict (client_id) do update set audience = excluded.audience;\n\ncreate or replace function public.mcp_access_token_hook(event jsonb)\nreturns jsonb\nlanguage plpgsql\nstable\nas $$\ndeclare\n claims jsonb := coalesce(event->'claims', '{}'::jsonb);\n oauth_client_id text := nullif(btrim(claims->>'client_id'), '');\n mapped_audience text;\nbegin\n if oauth_client_id is not null then\n select mapping.audience\n into mapped_audience\n from public.mcp_oauth_client_audiences as mapping\n where mapping.client_id = oauth_client_id;\n end if;\n\n if mapped_audience is not null then\n claims := jsonb_set(\n claims,\n '{aud}',\n to_jsonb(mapped_audience),\n true\n );\n end if;\n\n return jsonb_build_object('claims', claims);\nend;\n$$;\n\ngrant execute on function public.mcp_access_token_hook(jsonb) to supabase_auth_admin;\nrevoke execute on function public.mcp_access_token_hook(jsonb) from authenticated, anon, public;\n```\n\n| Token source | Mapping | Resulting `aud` |\n| --- | --- | --- |\n| Approved OAuth client | Exact client row | Mapped stable MCP audience |\n| Unrelated or unknown OAuth client | No row | Original Supabase audience |\n| Browser session | No `client_id` | Original Supabase audience |\n\nSelect this function under Supabase Auth Hooks before completing the interactive verification below.\n\n## Validate\n\n```bash\nnoodle validate examples/customer-auth/src/server.ts --json\nnoodle auth doctor examples/customer-auth/src/server.ts --json\nnoodle test examples/customer-auth/src/server.ts --json\n```\n\nThe doctor proves metadata and JWKS readiness without registering a client. For this protected app,\n`noodle test` proves the anonymous 401 plus exact protected-resource metadata boundary and reports\n`interactiveRequired: true`; neither command proves token issuance or audience verification.\n\nAgainst a deployed customer-protected environment, set a short-lived real customer token only in\n`NOODLE_CUSTOMER_TOKEN` and add `--live --org <org> --app <app> --env <env>`. The live doctor performs\ncredential exchanges without invoking any business tool. Add `--version 1` when testing a pinned version;\nthe reported customer resource must match that versioned MCP endpoint.\n\n## Run locally\n\n```bash\nnoodle devtools examples/customer-auth/src/server.ts\n```\n\nComplete sign-in in Devtools and load the tool list. That authenticated request is the local proof that DCR,\nPKCE, token issuance, issuer/signature verification, the stable audience, and exact-resource binding work\ntogether. Invoke a representative safe read when the configured customer API is available.\n\n### Test delegated exchange locally\n\nLocal customer OIDC sign-in and delegated-exchange assertion trust are two distinct boundaries. OIDC proves\nthe caller to the local MCP server; Devtools uses a separate local issuer only for the RFC 8693 assertion\nsent to the downstream token endpoint. This is the canonical local path and requires no `server.ts` change,\nflag, environment variable, or config surface.\n\n1. Configure the OIDC authorization server for the exact loopback callback and RFC 8707 resource. Do not add\n the Devtools assertion key to OIDC issuer metadata or change its signing keys.\n2. Start Devtools, complete customer sign-in, and copy the displayed `{ issuer, jwks }` from **Local delegated exchange**.\n3. Pin both values only in the customer-owned development RFC 8693 token endpoint.\n4. Restrict that trust to development client credentials, audience, API, and data.\n5. Invoke the delegated `list_org_apps` tool until its binding reads **Exchange verified**.\n6. Use hosted preview or `noodle auth doctor --live` to prove the production platform issuer.\n\n**Never trust the Devtools issuer in production: anyone holding the local private key could impersonate a customer.**\n\n## Configuration\n\nThe embedded assistant uses a customer-supplied Responses-compatible endpoint, selected explicitly with\n`transport: 'responses'` in `src/server.ts`. Use `transport: 'chat-completions'` or omit the field for a\nChat Completions endpoint. Noodle never falls back between them. Configure its managed values at the Noodle\ndeployment environment; none of these values belongs in the customer web application environment, and the\nAPI key never reaches the browser:\n\nThe assistant session carries a verified user, tenant, deployment, roles, and scopes. For this flagship's\nrouted tools, the embedding backend resolves the signed-in user's cluster from server-owned membership data\nand passes `routing: { endpoints: { customer_api: cluster.apiBaseUrl } }` to\n`createAssistantSession`. Noodle validates and privately stores that route; it is not returned to the\nbrowser. Do not copy the route into page context, session claims, tool input, or model instructions.\n\nThe authenticated assistant surface also declares `accountTier` as a model-visible session claim. Pass it\nfrom the same backend-owned account record as `claims: { accountTier: account.tier }`; undeclared claims are\ndropped. This is personalization context, not authorization: the verified roles/scopes beside each tool and\nthe server-owned customer route remain the enforcement boundaries. The public\n[runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nexplains how verified session claims constrain the guide content available to the model.\n\n```bash\nnoodle variables set ASSISTANT_ORIGIN https://app.example.com --scope env\nnoodle variables set ASSISTANT_MODEL_BASE_URL https://model.example.com/v1 --scope env\nnoodle variables set ASSISTANT_MODEL your-model --scope env\nnoodle secrets set ASSISTANT_MODEL_API_KEY --scope env\nnoodle variables set CUSTOMER_API_CLIENT_ID your-broker-client-id --scope env\nnoodle secrets set CUSTOMER_API_CLIENT_SECRET --scope env\nnoodle check --target embedded-assistant src/server.ts\n```\n\n`ASSISTANT_ORIGIN` is the operator-owned production embedding origin, so one source can serve every customer\nwithout an application fork. Assistant origins are exact. Production embedding origins must use HTTPS; plain HTTP is accepted only for\nloopback development origins such as `http://localhost:3000`, `http://127.0.0.1:3000`, or\n`http://[::1]:3000`. `noodle dev` serves the MCP project, not that separate embedding application.\n\nThe bounded `presentation` object configures the panel, launcher, header, composer, and messages. Its\nprimitives derive colors from shared server `branding`; raw HTML, CSS, inline SVG, renderer classes, and\ncallbacks are not accepted. This example omits `presentation.panel.surface`, so the renderer keeps the\nopaque default panel treatment while the example's light/dark `branding` surfaces provide its customer colors;\nset the bounded surface to `glass` only when translucency is intentional.\n\nThese TypeScript values remain the reusable developer defaults. After deployment, an environment operator\ncan adjust theme, logo, launcher style, position, and the bounded color palette from the Console's\n**Assistant** tab or `noodle assistant appearance` without changing the customer's embed code. See the\n[embedded assistant guide](https://docs.noodleseed.dev/docs/guides/embedded-assistant) for precedence and reset\nbehavior.\n\nCreate the backend credential after deployment. The CLI writes it to a mode-0600 file and never prints the\nsecret:\n\n```bash\nnoodle assistant clients create --name web --org noodleseed --app customer-auth --env prod\n```\n\nOnly the Noodle service URL, assistant client ID, and assistant client secret belong in the authenticated\ncustomer backend. The model URL, model name, and model API key remain managed by the Noodle deployment.\n\nThe customer's authenticated backend calls `createAssistantSession(...)` from\n`@noodleseed/assistant/server`, passing the already-verified user and browser origin. The browser then uses\nthe returned short-lived session through the managed Web Component/React renderer or a customer-owned UI:\n\n```bash\npnpm add @noodleseed/assistant\n```\n\n```tsx\nimport { NoodleAssistant } from '@noodleseed/assistant/react';\n\n<NoodleAssistant\n sessionEndpoint=\"/api/noodle-assistant/session\"\n theme={resolvedTheme}\n onSessionExpired={() => console.info('Assistant session renewed')}\n/>;\n```\n\n`resolvedTheme` is the application's current `'light' | 'dark'` value. Use `theme=\"auto\"` only when the\nbrowser operating-system preference is intentionally authoritative.\n\n### Minimal fail-closed custom renderer skeleton\n\nUse the renderer-free hook only when the product has a concrete reason to own the conversation UI. This\nminimal skeleton keeps the canonical client and App host, but intentionally refuses confirmation and input\nacceptance until the application implements their complete schema-aware presentation. Start with the managed\nrenderer unless the application accepts every obligation below.\n\n```tsx\n'use client';\n\nimport { useEffect, useState } from 'react';\nimport { NoodleAppView } from '@noodleseed/assistant/react';\nimport { useNoodleAssistant } from '@noodleseed/assistant/react/client';\n\nexport function CustomerAssistant({\n principalKey,\n resolvedTheme,\n onSignInRequested,\n}: {\n principalKey: string;\n resolvedTheme: 'light' | 'dark';\n onSignInRequested: (request: {\n signInTicket: string;\n expiresAt: string;\n }) => Promise<'started' | 'cancelled'>;\n}) {\n const [draft, setDraft] = useState('');\n const [sessionNotice, setSessionNotice] = useState('');\n const [turnNotice, setTurnNotice] = useState('');\n const [pendingSignInTicket, setPendingSignInTicket] = useState<string>();\n const { client, messages, suggestions, status, error } = useNoodleAssistant({\n sessionEndpoint: '/api/noodle-assistant/session',\n principalKey,\n });\n const busy = status === 'submitted' || status === 'streaming';\n const settle = (operation: Promise<void>) => {\n void operation.catch(() => {\n // The hook exposes this same structured failure through `error`.\n });\n };\n useEffect(\n () =>\n client.subscribe((event) => {\n if (event.event === 'session_expired') setSessionNotice('Session expired.');\n if (event.event === 'session_started' || event.event === 'session_reset') {\n setSessionNotice('');\n }\n }),\n [client],\n );\n\n return (\n <section aria-label=\"Assistant\" aria-busy={busy}>\n {messages.map((message) => (\n <article key={message.id} data-role={message.role}>\n {message.parts.map((part, index) => {\n if (part.type === 'text') return <p key={index}>{part.text}</p>;\n if (part.type === 'data-confirmation') {\n const review = part.data;\n return (\n <section key={review.id} aria-label=\"Review proposed action\">\n <h3>{review.title ?? 'Review proposed action'}</h3>\n {review.description ? <p>{review.description}</p> : null}\n <p>This custom renderer has not implemented a complete schema-aware review.</p>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'cancel' }))}\n >\n Cancel\n </button>\n </section>\n );\n }\n if (part.type === 'data-input-request') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Assistant needs input\">\n <p>{request.message}</p>\n {/* request.requestedSchema is the sole input-form contract. */}\n <p>This custom renderer has not implemented the requested schema form.</p>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'cancel' }))}\n >\n Cancel\n </button>\n </section>\n );\n }\n if (part.type === 'data-tool-result') {\n return (\n <p key={part.data.id} role=\"status\">\n A result is available, but this renderer has no trusted presentation for it.\n </p>\n );\n }\n if (part.type === 'data-view') {\n return (\n <NoodleAppView\n key={`${part.data.id}:${part.data.resourceUri}`}\n client={client}\n view={part.data}\n theme={resolvedTheme}\n />\n );\n }\n if (part.type === 'data-sign-in') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Sign in required\">\n <p>Continue with your account to use this capability.</p>\n <button\n disabled={busy || pendingSignInTicket !== undefined}\n onClick={() => {\n setPendingSignInTicket(request.signInTicket);\n void Promise.resolve()\n .then(() =>\n onSignInRequested({\n signInTicket: request.signInTicket,\n expiresAt: request.expiresAt,\n }),\n )\n .then(\n (result) => {\n if (result === 'cancelled') setPendingSignInTicket(undefined);\n },\n () => setPendingSignInTicket(undefined),\n );\n }}\n >\n Sign in\n </button>\n </section>\n );\n }\n return <p key={index}>Unsupported assistant content.</p>;\n })}\n </article>\n ))}\n <p role=\"status\" aria-live=\"polite\">\n {sessionNotice || turnNotice || (busy ? 'Assistant is working' : '')}\n </p>\n {suggestions?.prompts.length ? (\n <nav aria-label=\"Suggested messages\">\n {suggestions.prompts.map((prompt) => (\n <button\n key={prompt}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n setTurnNotice('');\n settle(client.sendMessage(prompt));\n }}\n >\n {prompt}\n </button>\n ))}\n </nav>\n ) : null}\n {error ? <p role=\"alert\">The assistant could not complete that request.</p> : null}\n <form\n onSubmit={(event) => {\n event.preventDefault();\n const message = draft.trim();\n if (!message) return;\n setDraft('');\n setTurnNotice('');\n settle(client.sendMessage(message));\n }}\n >\n <input\n aria-label=\"Message\"\n value={draft}\n onChange={(event) => setDraft(event.currentTarget.value)}\n />\n {busy ? (\n <button\n type=\"button\"\n onClick={() => {\n client.abort();\n setTurnNotice('Response stopped. This does not undo a started action.');\n }}\n >\n Stop\n </button>\n ) : (\n <button type=\"submit\">Send</button>\n )}\n </form>\n </section>\n );\n}\n```\n\n`principalKey` stays in the browser. Change it whenever the authenticated user or tenant changes; the hook\nthen aborts and clears the prior session and transcript. The sample does not render Confirm until the host\nimplements a complete schema-aware review, and it does not accept elicitation until a portable form covers\n`requestedSchema`; use the managed renderer instead of shipping either unsupported branch. Suggestions are\nhook-owned and submit ordinary messages through `client.sendMessage`.\n\n`data-sign-in` has no status and is never passed to `client.respond`. Bind `signInTicket` to the host's\nshort-lived login transaction without putting it in URLs, logs, analytics, or durable browser storage. Resolve\nthe callback as `started` only after the host owns one active transaction; return `cancelled` or reject when no\ntransaction started so the renderer restores the sign-in affordance. A\nmixed renderer uses separate public and authenticated clients: the public shell uses `embedId`, `serviceUrl`,\nand a visitor principal key; after login, the destination mounts a new client against the same-origin session\nendpoint under the user/tenant principal key. Never pass both source options or mutate the public client's\nsource in place. `session_expired` is observational: the client owns its single safe pre-execution re-exchange.\nNever add a generic Retry button or replay an interaction decision automatically.\n\nFor `data-tool-result`, do not expose technical tool names or raw JSON. Prefer the linked `data-view`;\notherwise map a known bounded result to application-trusted UI or keep the explicit unsupported state. For\n`data-view`, use `<noodle-app-view>` or its React `NoodleAppView` adapter. The element's semantic lifecycle\nidentity is the client plus `view.id` plus `view.resourceUri`, so payload/callback rerenders keep the iframe\nand only a different view, disconnect, or App teardown request retires the bridge.\nApp views remain inline by default: the host advertises only inline presentation and rejects a widget's\nfullscreen request. A customer-owned renderer may opt in explicitly with `allowFullscreen` on\n`NoodleAppView` or `allow-fullscreen` on `<noodle-app-view>` only when fullscreen is part of its intended\nexperience. When fullscreen is accepted, the shared host adds a top-right exit control that returns the same\nmounted App to inline mode without discarding its state.\nNever inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge directly. Pages with a\nContent-Security-Policy must include the Noodle service origin in both `connect-src` and `frame-src`.\n\nBefore the production-equivalent host build, run the presence-only handoff check:\n\n```sh\nnoodle assistant embed --check --json\n```\n\nAdd application-owned delegated-exchange requirements with repeatable `--require-env NAME` flags. The JSON\nreports required and missing names, CSP status, and post-deploy probes without returning environment values\nor writing scaffold files. Map the names through the production secret manager, CI environment, and any\nsecret allowlist; regenerate existing framework-owned environment binding types before the build. Default\nDevtools/model exercises to synthetic data, and obtain approval before sending real connector data to an\nexternal model.\n\nRead `evidence.levels` in order: static host, local contract, hosted session, production browser, then\noperations. Stop at `evidence.firstUnproven`. A static result may be `passed`, `partial`, or `failed`; even\ntop-level `ready: true` means only that no static blocker was detected. It never proves the local session\ncontract or a production-browser flow. Value-free diagnostics call out an MCP endpoint used as the service\nURL, an HTML redirect risk, an SSR mount risk, and a cross-origin session endpoint. The command has no live\nor browser flag; its `postDeployProbes` are next actions, not executed evidence.\n\nAfter deployment, use the assistant doctor to verify the embed client, exact model transport, and static\nsession boundary:\n\n```sh\nnoodle assistant doctor --user-id <real-test-user> --origin \"$PUBLIC_APP_ORIGIN\" --org <org> --app <app> --env <env>\n```\n\nThe doctor makes one bounded synthetic model request without business tools or customer conversation data;\nfailures show only a redacted category, status, and retryability. It does not invent or test an\napplication-specific customer route. Prove routed assistant tools by\nhaving the authenticated embedding backend pass the user's server-verified endpoint during session\nexchange, then invoke one representative safe read.\n\nDo not send a first turn on mount by default. React effect cleanup can suppress one provisional Strict Mode\neffect, but it cannot make a remount, dependency change, or client replacement idempotent. Require an\nexplicit user action unless the host owns durable one-shot state and an application idempotency key that\nmakes repeated sends safe.\n\nFor a chat-first custom host, raw `tool_started` supplies the direct call `id` and technical tool name. Map\nknown tools to concise application copy and use a neutral fallback. Reserve a stable `role=\"status\"` region\nfor thinking, tool activity, and the view skeleton; switch to the ready `<noodle-app-view>` (or React\n`NoodleAppView`) on `view_available` or to `role=\"alert\"` on error. Decorative skeleton shapes stay hidden from assistive technology, and shimmer\nor transition motion is disabled under `prefers-reduced-motion`.\n\nUse `${view.id}:${view.resourceUri}` as transport identity. Different call IDs are distinct invocations and\nmust not be deduplicated generically. If this application intentionally owns one current panel for a known\nresource, declare an application-owned slot for that resource and replace only that slot.\n\n### Framework-neutral DOM client\n\nSubscribe to the DOM-free client directly without a component wrapper and use the isolated App host.\nIt exposes the same conversation as headless AI SDK `UIMessage` state, including typed confirmation, input,\ntool-result, and linked-view parts:\n\n```html\n<div id=\"assistant-app-views\"></div>\n```\n\n```ts\nimport '@noodleseed/assistant/app-view';\nimport {\n type AssistantViewAvailableDetail,\n type NoodleAppViewElement,\n} from '@noodleseed/assistant/app-view';\nimport { createAssistantClient } from '@noodleseed/assistant/client';\n\nconst assistant = createAssistantClient({\n sessionEndpoint: '/api/noodle-assistant/session',\n});\nconst appViews = document.querySelector('#assistant-app-views');\nif (!appViews) throw new Error('Missing App views host');\nconst mountedViews = new Map<string, NoodleAppViewElement>();\nconst readResolvedTheme = (): 'light' | 'dark' =>\n document.documentElement.classList.contains('dark') ? 'dark' : 'light';\nlet resolvedTheme: 'light' | 'dark' = readResolvedTheme();\nconst syncResolvedTheme = () => {\n resolvedTheme = readResolvedTheme();\n for (const mountedView of mountedViews.values()) mountedView.theme = resolvedTheme;\n};\nnew MutationObserver(syncResolvedTheme).observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class'],\n});\nconst appViewFor = (view: AssistantViewAvailableDetail) => {\n const key = `${view.id}:${view.resourceUri}`;\n let appView = mountedViews.get(key);\n if (!appView) {\n appView = document.createElement('noodle-app-view') as NoodleAppViewElement;\n appView.client = assistant;\n mountedViews.set(key, appView);\n appViews.append(appView);\n }\n appView.theme = resolvedTheme;\n return appView;\n};\n\nassistant.subscribeChat((state) => {\n renderUIMessageState(state, {\n respond: (id, response) => assistant.respond(id, response),\n });\n const activeViewKeys = new Set<string>();\n for (const message of state.messages) {\n for (const part of message.parts) {\n if (part.type === 'data-view') {\n const key = `${part.data.id}:${part.data.resourceUri}`;\n activeViewKeys.add(key);\n appViewFor(part.data).view = part.data;\n }\n }\n }\n for (const [key, mountedView] of mountedViews) {\n if (!activeViewKeys.has(key)) {\n mountedView.remove();\n mountedViews.delete(key);\n }\n }\n});\n```\n\n`renderUIMessageState` is application code. It must present a complete schema-aware confirmation or input\nform and require an explicit user gesture before using `respond`; never call `respond` while scanning a\ntranscript snapshot.\n\n`theme=\"auto\"` follows the operating-system preference, not a SaaS-owned toggle. Pass the resolved\n`light`/`dark` theme to `NoodleAssistant` and `<noodle-app-view>`/`NoodleAppView`; updates reach mounted MCP Apps without a\nremount. CSS custom properties inherit through the host, and documented `--ns-assistant-*` variables remain\nthe final integration escape hatch. Server `branding` is shared by widgets and the assistant; there is no\nsecond branding declaration. Text streams progressively. Expired turns re-exchange and retry once;\nconfirmations never replay automatically.\n\nThe customer IdP must place the full tenant API base URL in `tenant.api_base_url`. For example, one verified\ncustomer may receive `https://customer-a.api.noodleseed.dev/v1` and another\n`https://customer-b.api.noodleseed.dev/v1`; both satisfy the declared suffix policy. Application code,\ndeployment variables, and connector arguments do not select the tenant route.\n\n`CUSTOMER_API_CLIENT_ID` and `CUSTOMER_API_CLIENT_SECRET` authenticate only the broker to the fixed exchange\nendpoint. They are not customer API bearer tokens. The exchange endpoint verifies the platform-signed\nsubject assertion and mints a short-lived token scoped to the signed-in user and route binding.\n\n## Launch and qualified-usage proof\n\nFor launch, browser verification, and qualified usage, follow the [embedded assistant guide](https://docs.noodleseed.dev/docs/guides/embedded-assistant).\n\n## Deploy customer-protected to Noodle Seed Cloud\n\n```bash\nnoodle deploy examples/customer-auth/src/server.ts \\\n --org noodleseed \\\n --app customer-auth \\\n --env prod \\\n --access customers\n```\n\nEndpoint:\n\n```text\nhttps://cloud.noodleseed.dev/o/noodleseed/customer-auth/mcp\n```\n\n## Preview anonymous Help with customer sign-in\n\nUse `noodle dev examples/customer-auth/src/server.ts --access mixed`. Help remains available before sign-in;\nprotected reads advertise descriptors and require their verified scopes/roles to execute. Customer mode\nremains the default. Local Devtools retries a protected call after successful sign-in; cancellation executes\nnothing and leaves Help available. With a hosted service, a new target may use\n`--access mixed` only after every customer tool has an authorization rule. For an existing customer-only\ntarget, preserve its org/app/env, endpoint, issuer, and audience. Follow the public guide: verify an inactive\n`customers` record for the exact version, creating it by unchanged secured redeploy if absent; add and\nvalidate every tool rule; deploy the prepared source as `customers`; recheck the rollback; then adopt mixed\naccess. On pilot failure, use\n`noodle rollback <deployment-id>` with the same org/app/env. This app-history rollback is separate from the\ncompatible hosted service-release floor. Keep the public Help endpoint through the post-deployment ChatGPT\nand customer API pilot. Local behavior and wire checks do not prove that host\njourney. See the\n[customer auth rollback and adoption procedure](https://docs.noodleseed.dev/docs/guides/customer-auth#preserve-an-app-rollback-target-and-adopt)\nfor the exact commands and checks.\n\n## Auth boundary\n\nNoodle Seed verifies the configured OIDC issuer and stable audience, then binds the exact transport-derived\nMCP resource before reading identity or routing claims. Public caller identity contains the user/role/scope\nprojection; the customer route remains private request state.\n\nConnector-backed tools ask the broker for a route-bound delegated credential; only the endpoint key and\nfingerprint enter broker cache/single-flight state or the assertion. The route claim and inbound MCP bearer\ntoken never reach tools, connectors, widgets, model output, or downstream systems. Confirmed actions keep\nthe same URL-blind binding only in private continuation state and reject acceptance-time drift.\n" },
|
|
58
|
+
{ relPath: "examples/customer-auth/README.md", content: "# Customer Auth - OIDC identity and customer-routed APIs\n\nFor a visitor who starts before signup, use the [Stateful Draft reference](../stateful-draft/README.md)\nalongside this authenticated backend integration.\n\nThis curated example owns the customer/end-user authentication capability slot. It proves that a SaaS app\ncan protect an MCP endpoint with direct OIDC, retain role/scope-based tool authorization, and route ordinary\nreads and confirmed actions to the API origin selected by the verified customer's identity provider.\n\nDirect MCP calls obtain the private route from verified OIDC claims; embedded sessions obtain it from the authenticated backend. Both keep routes out of model and browser state.\n\nThe public developer entrypoint is [`src/server.ts`](src/server.ts). It exposes a deliberately small MCP\nsurface for organization discovery and app lifecycle operations:\n\n- `help` explains the product without customer identity.\n- `list_my_organizations` publicly advertises its descriptor but requires `organizations:read` to list the signed-in customer’s organizations.\n- `list_org_apps` uses `authorization.discovery: 'public'` to expose its descriptor on an anonymously\n accessible endpoint. Execution still requires `org_apps:read` and `org_admin` or `org_member`. Visibility\n grants no permissions, records, role disclosure, or product-guide eligibility. ChatGPT sign-in is unproven.\n- `archive_org_app` archives one app only after exact runtime confirmation. It requires the\n `org_apps:write` scope and `org_admin` role.\n\nThe tools chain: `list_my_organizations` surfaces the `org_id`s the customer can act on,\n`list_org_apps` takes one of those ids, and `archive_org_app` accepts the selected app id. Tool code remains\nindependent of the selected origin.\n\nThe typed `agentGuide` retains only complete workflows the verified caller can execute. Public descriptor discovery does not grant workflow access. See the [runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime) for embedded behavior and the draft MCP Skills preview.\n\n## Declare the customer endpoint\n\n`customerEndpoint` names one private routing authority and bounds the origins an IdP may select:\n\n```ts\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\n```\n\nUse either non-empty `allowedHttpsHostSuffixes` or non-empty `allowedHttpsOrigins`, never both. Exact-origin\npolicies may include a non-default port. Suffix policies match only the exact hostname or dot-boundary\nsubdomains on port 443. A routed connector must not add `allowedOrigins`; its endpoint policy is the egress\nallowlist.\n\nThe connector uses that declaration as its normal base URL. Its token endpoint remains a fixed, independently\nvalidated HTTPS URL:\n\n```ts\nconst api = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n // read and action operations...\n },\n });\n```\n\n`delegatedTokenExchange` consumes a verified customer caller; an MCP access mode does not create one. Declare\n`customerAuth.*(...)` or `embeddedAssistant(...)` to establish its subject, issuer, and audience, or\n`noodle validate`, `noodle auth doctor`, and deploy fail with `delegated_token_exchange_identity_required`\nbefore resolving secrets or any egress. Hosted deployment never accepts the loopback-only Devtools identity.\nA successful local Devtools exchange is not evidence that the hosted server has an identity source.\n\nAt both connector and operation level, auth must be omitted or use `delegatedTokenExchange`. The compiler\nchecks the emitted connector, including defaults and operation overrides, and reports the failing auth path\nand kind. Keep no bearer, API-key, client-credentials, or managed-provider fallback for local mode; use\noperation fakes.\n\n## Map the endpoint from verified OIDC\n\nThe IdP claim contains the complete base URL, including an optional base path. Routing is separate from the\npublic `${user}` expression scope:\n\n```ts\nauth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n}),\n```\n\nFor federated OIDC, put the same endpoint map on every issuer. Claim paths may differ, but each issuer must\nmap every endpoint the app uses:\n\n```ts\nauth: customerAuth.federatedOidc({\n issuers: [\n {\n issuer: 'https://id.customer-a.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n },\n {\n issuer: 'https://login.customer-b.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'organization.routes.customer_api' },\n },\n },\n },\n ],\n}),\n```\n\nAt runtime, Noodle Seed validates the configured stable audience, associates the caller with the exact\ntransport-derived MCP resource, projects the route into private request state, applies its policy, and\nfreezes it for the call. Missing, malformed, or\ndisallowed claims return `connector_route_unavailable` before credential lookup or connector egress.\nResolved URLs never enter artifacts, `${user}`, logs, model output, widgets, public confirmation review,\nbroker cache keys, or delegated exchange assertions.\n\nRouted reads work in tools, including declared nested calls. Routed actions require exact\n`annotations.confirm: true`; otherwise they fail with `customer_endpoint_action_unsupported`. Routed\nresources, prompts, and ambient context fail with `customer_endpoint_surface_unsupported`.\n\nThe flagship's routed action uses the normal TypeScript action helper:\n\n```ts\ntool('archive_org_app', {\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n // input, output, and the normal connectors.app_api.archiveOrgApp(...) call...\n});\n```\n\nThe flagship also opts into the current stateless hosted MCP path:\n\n```ts\ninteractions: {\n confirmationFallback: 'host',\n},\n```\n\nA bidirectional client that negotiated form elicitation can complete the standard confirmation exchange\ninstead. The explicit host fallback trusts the MCP host to have collected native write approval before the\ntool call reaches Noodle Seed; it is never inferred from client identity and does not replace auth, policy,\nor accurate action/destructive annotations. Omit the fallback when connected hosts are not trusted to\nprovide that approval. If neither standard confirmation nor the fallback is available, the action fails\nclosed with `interaction_unavailable`.\n\nPreparation stores only sorted route `{ key, fingerprint }` bindings in its private server-held\ncontinuation; the public review exposes none of them. Acceptance re-resolves the current request route and\nreturns `invalid_continuation` if it is missing or changed, before policy, credentials, or egress. A match\nreuses the current frozen snapshot for the action and all nested or later reads.\n\nThe application developer owns the direct/federated authorization server. It must publish its path-inserted\nRFC 8414 document as direct HTTP 200 JSON with exact issuer and HTTPS authorization/token/registration/JWKS\nendpoints, authorization-code and refresh grants, PKCE S256, public-client auth method `none`, RFC 8707\nresource handling, and public signing keys. It validates each exact MCP resource on authorize, code exchange,\nand refresh, then maps approved versions of this app/environment to `noodleseed-customer-auth-prod`. Other\napps and environments use distinct audiences.\n\nRun `noodle auth doctor src/server.ts` before sharing. Its bounded, read-only probes never register a client.\nAdding the embedded assistant does not choose or rewrite MCP customer auth. Its authenticated backend may\nbind `routing.endpoints.customer_api` during assistant-session exchange from server-owned membership data;\ndirect MCP requests continue to resolve the same endpoint from the configured verified OIDC claim.\n\n## Per-tool authorization remains independent\n\nThe mapped `roles` and `scopes` paths are read only after OIDC verification. The restricted tool declares its\nrule beside the rest of its public contract:\n\n```ts\ntool('list_org_apps', {\n authorization: {\n discovery: 'public',\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n // input, output, and fulfilment...\n});\n```\n\nEvery required scope must be present and at least one allowed role must match. When both lists are declared,\nboth conditions apply. In mixed customer mode, `discovery: 'public'` exposes this descriptor before sign-in;\nexecution still requires those scopes and roles. Other restricted tools remain filtered by authorization.\nRoute availability never changes discovery, and unauthorized direct calls fail closed.\n\nTool code calls the connector normally:\n\n```ts\nfulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n\n return { result: apps.result };\n}\n```\n\nThe broker exchanges a short-lived, platform-signed assertion at the fixed token endpoint and caches the\nresult by caller, connector, scopes, and a route fingerprint. The assertion carries only the route key and\nfingerprint, never the URL. The MCP access token is never forwarded to the customer API. Wire contract:\ndocs/spec/connectors.md.\n\nFirebase and Microsoft remain supported managed adapters (docs/spec/auth-and-policy.md and the SharePoint\nflagship).\n\n## Supabase direct-OIDC access-token hook\n\nDynamic Client Registration lets any OAuth client register, so the presence of `client_id` is not approval.\nKeep an operator-controlled client-to-audience map and rewrite `aud` only for an exact mapped client. For a\ndynamically registered client, review its generated client ID, name, and exact redirect URIs in the consent\nflow before adding the mapping. Each new registration needs its own row; never approve by name or prefix.\n\nReplace `<approved-oauth-client-id>` with the reviewed client ID and `<stable-mcp-audience>` with the exact\nvalue configured in `customerAuth.oidc`:\n\n```sql\ncreate table if not exists public.mcp_oauth_client_audiences (\n client_id text primary key check (btrim(client_id) <> ''),\n audience text not null check (btrim(audience) <> '')\n);\n\nrevoke all on table public.mcp_oauth_client_audiences from authenticated, anon, public;\ngrant usage on schema public to supabase_auth_admin;\ngrant select on table public.mcp_oauth_client_audiences to supabase_auth_admin;\n\ninsert into public.mcp_oauth_client_audiences (client_id, audience)\nvalues ('<approved-oauth-client-id>', '<stable-mcp-audience>')\non conflict (client_id) do update set audience = excluded.audience;\n\ncreate or replace function public.mcp_access_token_hook(event jsonb)\nreturns jsonb\nlanguage plpgsql\nstable\nas $$\ndeclare\n claims jsonb := coalesce(event->'claims', '{}'::jsonb);\n oauth_client_id text := nullif(btrim(claims->>'client_id'), '');\n mapped_audience text;\nbegin\n if oauth_client_id is not null then\n select mapping.audience\n into mapped_audience\n from public.mcp_oauth_client_audiences as mapping\n where mapping.client_id = oauth_client_id;\n end if;\n\n if mapped_audience is not null then\n claims := jsonb_set(\n claims,\n '{aud}',\n to_jsonb(mapped_audience),\n true\n );\n end if;\n\n return jsonb_build_object('claims', claims);\nend;\n$$;\n\ngrant execute on function public.mcp_access_token_hook(jsonb) to supabase_auth_admin;\nrevoke execute on function public.mcp_access_token_hook(jsonb) from authenticated, anon, public;\n```\n\n| Token source | Mapping | Resulting `aud` |\n| --- | --- | --- |\n| Approved OAuth client | Exact client row | Mapped stable MCP audience |\n| Unrelated or unknown OAuth client | No row | Original Supabase audience |\n| Browser session | No `client_id` | Original Supabase audience |\n\nSelect this function under Supabase Auth Hooks before completing the interactive verification below.\n\n## Validate\n\n```bash\nnoodle validate examples/customer-auth/src/server.ts --json\nnoodle auth doctor examples/customer-auth/src/server.ts --json\nnoodle test examples/customer-auth/src/server.ts --json\n```\n\nThe doctor proves metadata and JWKS readiness without registering a client. For this protected app,\n`noodle test` proves the anonymous 401 plus exact protected-resource metadata boundary and reports\n`interactiveRequired: true`; neither command proves token issuance or audience verification.\n\nAgainst a deployed customer-protected environment, set a short-lived real customer token only in\n`NOODLE_CUSTOMER_TOKEN` and add `--live --org <org> --app <app> --env <env>`. The live doctor performs\ncredential exchanges without invoking any business tool. Add `--version 1` when testing a pinned version;\nthe reported customer resource must match that versioned MCP endpoint.\n\n## Run locally\n\n```bash\nnoodle devtools examples/customer-auth/src/server.ts\n```\n\nComplete sign-in in Devtools and load the tool list. That authenticated request is the local proof that DCR,\nPKCE, token issuance, issuer/signature verification, the stable audience, and exact-resource binding work\ntogether. Invoke a representative safe read when the configured customer API is available.\n\n### Test delegated exchange locally\n\nLocal customer OIDC sign-in and delegated-exchange assertion trust are two distinct boundaries. OIDC proves\nthe caller to the local MCP server; Devtools uses a separate local issuer only for the RFC 8693 assertion\nsent to the downstream token endpoint. This is the canonical local path and requires no `server.ts` change,\nflag, environment variable, or config surface.\n\n1. Configure the OIDC authorization server for the exact loopback callback and RFC 8707 resource. Do not add\n the Devtools assertion key to OIDC issuer metadata or change its signing keys.\n2. Start Devtools, complete customer sign-in, and copy the displayed `{ issuer, jwks }` from **Local delegated exchange**.\n3. Pin both values only in the customer-owned development RFC 8693 token endpoint.\n4. Restrict that trust to development client credentials, audience, API, and data.\n5. Invoke the delegated `list_org_apps` tool until its binding reads **Exchange verified**.\n6. Use hosted preview or `noodle auth doctor --live` to prove the production platform issuer.\n\n**Never trust the Devtools issuer in production: anyone holding the local private key could impersonate a customer.**\n\n## Configuration\n\nThe embedded assistant uses a customer-supplied Responses-compatible endpoint, selected explicitly with\n`transport: 'responses'` in `src/server.ts`. Use `transport: 'chat-completions'` or omit the field for a\nChat Completions endpoint. Noodle never falls back between them. Configure its managed values at the Noodle\ndeployment environment; none of these values belongs in the customer web application environment, and the\nAPI key never reaches the browser:\n\nThe assistant session carries a verified user, tenant, deployment, roles, and scopes. For this flagship's\nrouted tools, the embedding backend resolves the signed-in user's cluster from server-owned membership data\nand passes `routing: { endpoints: { customer_api: cluster.apiBaseUrl } }` to\n`createAssistantSession`. Noodle validates and privately stores that route; it is not returned to the\nbrowser. Do not copy the route into page context, session claims, tool input, or model instructions.\n\nThe authenticated assistant surface also declares `accountTier` as a model-visible session claim. Pass it\nfrom the same backend-owned account record as `claims: { accountTier: account.tier }`; undeclared claims are\ndropped. This is personalization context, not authorization: the verified roles/scopes beside each tool and\nthe server-owned customer route remain the enforcement boundaries. The public\n[runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nexplains how verified session claims constrain the guide content available to the model.\n\n```bash\nnoodle variables set ASSISTANT_ORIGIN https://app.example.com --scope env\nnoodle variables set ASSISTANT_MODEL_BASE_URL https://model.example.com/v1 --scope env\nnoodle variables set ASSISTANT_MODEL your-model --scope env\nnoodle secrets set ASSISTANT_MODEL_API_KEY --scope env\nnoodle variables set CUSTOMER_API_CLIENT_ID your-broker-client-id --scope env\nnoodle secrets set CUSTOMER_API_CLIENT_SECRET --scope env\nnoodle check --target embedded-assistant src/server.ts\n```\n\n`ASSISTANT_ORIGIN` is the operator-owned production embedding origin, so one source can serve every customer\nwithout an application fork. Assistant origins are exact. Production embedding origins must use HTTPS; plain HTTP is accepted only for\nloopback development origins such as `http://localhost:3000`, `http://127.0.0.1:3000`, or\n`http://[::1]:3000`. `noodle dev` serves the MCP project, not that separate embedding application.\n\nThe bounded `presentation` object configures the panel, launcher, header, composer, and messages. Its\nprimitives derive colors from shared server `branding`; raw HTML, CSS, inline SVG, renderer classes, and\ncallbacks are not accepted. This example omits `presentation.panel.surface`, so the renderer keeps the\nopaque default panel treatment while the example's light/dark `branding` surfaces provide its customer colors;\nset the bounded surface to `glass` only when translucency is intentional.\n\nThese TypeScript values remain the reusable developer defaults. After deployment, an environment operator\ncan adjust theme, logo, launcher style, position, and the bounded color palette from the Console's\n**Assistant** tab or `noodle assistant appearance` without changing the customer's embed code. See the\n[embedded assistant guide](https://docs.noodleseed.dev/docs/guides/embedded-assistant) for precedence and reset\nbehavior.\n\nCreate the backend credential after deployment. The CLI writes it to a mode-0600 file and never prints the\nsecret:\n\n```bash\nnoodle assistant clients create --name web --org noodleseed --app customer-auth --env prod\n```\n\nOnly the Noodle service URL, assistant client ID, and assistant client secret belong in the authenticated\ncustomer backend. The model URL, model name, and model API key remain managed by the Noodle deployment.\n\nThe customer's authenticated backend calls `createAssistantSession(...)` from\n`@noodleseed/assistant/server`, passing the already-verified user and browser origin. The browser then uses\nthe returned short-lived session through the managed Web Component/React renderer or a customer-owned UI:\n\n```bash\npnpm add @noodleseed/assistant\n```\n\n```tsx\nimport { NoodleAssistant } from '@noodleseed/assistant/react';\n\n<NoodleAssistant\n sessionEndpoint=\"/api/noodle-assistant/session\"\n theme={resolvedTheme}\n onSessionExpired={() => console.info('Assistant session renewed')}\n/>;\n```\n\n`resolvedTheme` is the application's current `'light' | 'dark'` value. Use `theme=\"auto\"` only when the\nbrowser operating-system preference is intentionally authoritative.\n\nThe backend's account deletion also erases the user's assistant history by the `user.id` it exchanges\n(idempotent; a no-op while the admin surface declares `history: false`):\n\n```ts\nimport { forgetUser } from '@noodleseed/assistant/server';\n\nawait forgetUser({ serviceUrl, clientId, clientSecret, user: { id: user.id } });\n```\n\n### Minimal fail-closed custom renderer skeleton\n\nUse the renderer-free hook only when the product must own the conversation UI and accepts every obligation\nbelow; otherwise start with the managed renderer. This skeleton keeps the canonical client and App host but\nrefuses confirmation and input acceptance until the application implements their schema-aware presentation.\n\n```tsx\n'use client';\n\nimport { useEffect, useState } from 'react';\nimport { NoodleAppView } from '@noodleseed/assistant/react';\nimport { useNoodleAssistant } from '@noodleseed/assistant/react/client';\n\nexport function CustomerAssistant({\n principalKey,\n resolvedTheme,\n onSignInRequested,\n}: {\n principalKey: string;\n resolvedTheme: 'light' | 'dark';\n onSignInRequested: (request: {\n signInTicket: string;\n expiresAt: string;\n }) => Promise<'started' | 'cancelled'>;\n}) {\n const [draft, setDraft] = useState('');\n const [sessionNotice, setSessionNotice] = useState('');\n const [turnNotice, setTurnNotice] = useState('');\n const [pendingSignInTicket, setPendingSignInTicket] = useState<string>();\n const { client, messages, suggestions, status, error } = useNoodleAssistant({\n sessionEndpoint: '/api/noodle-assistant/session',\n principalKey,\n });\n const busy = status === 'submitted' || status === 'streaming';\n const settle = (operation: Promise<void>) => {\n void operation.catch(() => {\n // The hook exposes this same structured failure through `error`.\n });\n };\n useEffect(\n () =>\n client.subscribe((event) => {\n if (event.event === 'session_expired') setSessionNotice('Session expired.');\n if (event.event === 'session_started' || event.event === 'session_reset') {\n setSessionNotice('');\n }\n }),\n [client],\n );\n\n return (\n <section aria-label=\"Assistant\" aria-busy={busy}>\n {messages.map((message) => (\n <article key={message.id} data-role={message.role}>\n {message.parts.map((part, index) => {\n if (part.type === 'text') return <p key={index}>{part.text}</p>;\n if (part.type === 'data-confirmation') {\n const review = part.data;\n return (\n <section key={review.id} aria-label=\"Review proposed action\">\n <h3>{review.title ?? 'Review proposed action'}</h3>\n {review.description ? <p>{review.description}</p> : null}\n <p>This custom renderer has not implemented a complete schema-aware review.</p>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'cancel' }))}\n >\n Cancel\n </button>\n </section>\n );\n }\n if (part.type === 'data-input-request') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Assistant needs input\">\n <p>{request.message}</p>\n {/* request.requestedSchema is the sole input-form contract. */}\n <p>This custom renderer has not implemented the requested schema form.</p>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'cancel' }))}\n >\n Cancel\n </button>\n </section>\n );\n }\n if (part.type === 'data-tool-result') {\n return (\n <p key={part.data.id} role=\"status\">\n A result is available, but this renderer has no trusted presentation for it.\n </p>\n );\n }\n if (part.type === 'data-view') {\n return (\n <NoodleAppView\n key={`${part.data.id}:${part.data.resourceUri}`}\n client={client}\n view={part.data}\n theme={resolvedTheme}\n />\n );\n }\n if (part.type === 'data-sign-in') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Sign in required\">\n <p>Continue with your account to use this capability.</p>\n <button\n disabled={busy || pendingSignInTicket !== undefined}\n onClick={() => {\n setPendingSignInTicket(request.signInTicket);\n void Promise.resolve()\n .then(() =>\n onSignInRequested({\n signInTicket: request.signInTicket,\n expiresAt: request.expiresAt,\n }),\n )\n .then(\n (result) => {\n if (result === 'cancelled') setPendingSignInTicket(undefined);\n },\n () => setPendingSignInTicket(undefined),\n );\n }}\n >\n Sign in\n </button>\n </section>\n );\n }\n return <p key={index}>Unsupported assistant content.</p>;\n })}\n </article>\n ))}\n <p role=\"status\" aria-live=\"polite\">\n {sessionNotice || turnNotice || (busy ? 'Assistant is working' : '')}\n </p>\n {suggestions?.prompts.length ? (\n <nav aria-label=\"Suggested messages\">\n {suggestions.prompts.map((prompt) => (\n <button\n key={prompt}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n setTurnNotice('');\n settle(client.sendMessage(prompt));\n }}\n >\n {prompt}\n </button>\n ))}\n </nav>\n ) : null}\n {error ? <p role=\"alert\">The assistant could not complete that request.</p> : null}\n <form\n onSubmit={(event) => {\n event.preventDefault();\n const message = draft.trim();\n if (!message) return;\n setDraft('');\n setTurnNotice('');\n settle(client.sendMessage(message));\n }}\n >\n <input\n aria-label=\"Message\"\n value={draft}\n onChange={(event) => setDraft(event.currentTarget.value)}\n />\n {busy ? (\n <button\n type=\"button\"\n onClick={() => {\n client.abort();\n setTurnNotice('Response stopped. This does not undo a started action.');\n }}\n >\n Stop\n </button>\n ) : (\n <button type=\"submit\">Send</button>\n )}\n </form>\n </section>\n );\n}\n```\n\n`principalKey` stays in the browser. Change it whenever the authenticated user or tenant changes; the hook\nthen aborts and clears the prior session and transcript. The sample does not render Confirm until the host\nimplements a complete schema-aware review, and it does not accept elicitation until a portable form covers\n`requestedSchema`; use the managed renderer instead of shipping either unsupported branch. Suggestions are\nhook-owned and submit ordinary messages through `client.sendMessage`.\n\n`data-sign-in` has no status and is never passed to `client.respond`. Bind `signInTicket` to the host's\nshort-lived login transaction without putting it in URLs, logs, analytics, or durable browser storage. Resolve\nthe callback as `started` only after the host owns one active transaction; return `cancelled` or reject when no\ntransaction started so the renderer restores the sign-in affordance. A\nmixed renderer uses separate public and authenticated clients: the public shell uses `embedId`, `serviceUrl`,\nand a visitor principal key; after login, the destination mounts a new client against the same-origin session\nendpoint under the user/tenant principal key. Never pass both source options or mutate the public client's\nsource in place. `session_expired` is observational: the client owns its single safe pre-execution re-exchange.\nNever add a generic Retry button or replay an interaction decision automatically.\n\nFor `data-tool-result`, do not expose technical tool names or raw JSON. Prefer the linked `data-view`;\notherwise map a known bounded result to application-trusted UI or keep the explicit unsupported state. For\n`data-view`, use `<noodle-app-view>` or its React `NoodleAppView` adapter. The element's semantic lifecycle\nidentity is the client plus `view.id` plus `view.resourceUri`, so payload/callback rerenders keep the iframe\nand only a different view, disconnect, or App teardown request retires the bridge.\nApp views remain inline by default: the host advertises only inline presentation and rejects a widget's\nfullscreen request. A customer-owned renderer may opt in explicitly with `allowFullscreen` on\n`NoodleAppView` or `allow-fullscreen` on `<noodle-app-view>` only when fullscreen is part of its intended\nexperience. When fullscreen is accepted, the shared host adds a top-right exit control that returns the same\nmounted App to inline mode without discarding its state.\nNever inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge directly. Pages with a\nContent-Security-Policy must include the Noodle service origin in both `connect-src` and `frame-src`.\n\nBefore the production-equivalent host build, run the presence-only handoff check:\n\n```sh\nnoodle assistant embed --check --json\n```\n\nAdd application-owned delegated-exchange requirements with repeatable `--require-env NAME` flags. The JSON\nreports required and missing names, CSP status, and post-deploy probes without returning environment values\nor writing scaffold files. Map the names through the production secret manager, CI environment, and any\nsecret allowlist; regenerate existing framework-owned environment binding types before the build. Default\nDevtools/model exercises to synthetic data, and obtain approval before sending real connector data to an\nexternal model.\n\nRead `evidence.levels` in order: static host, local contract, hosted session, production browser, then\noperations. Stop at `evidence.firstUnproven`. A static result may be `passed`, `partial`, or `failed`; even\ntop-level `ready: true` means only that no static blocker was detected. It never proves the local session\ncontract or a production-browser flow. Value-free diagnostics call out an MCP endpoint used as the service\nURL, an HTML redirect risk, an SSR mount risk, and a cross-origin session endpoint. The command has no live\nor browser flag; its `postDeployProbes` are next actions, not executed evidence.\n\nAfter deployment, use the assistant doctor to verify the embed client, exact model transport, and static\nsession boundary:\n\n```sh\nnoodle assistant doctor --user-id <real-test-user> --origin \"$PUBLIC_APP_ORIGIN\" --org <org> --app <app> --env <env>\n```\n\nThe doctor makes one bounded synthetic model request without business tools or customer conversation data;\nfailures show only a redacted category, status, and retryability. It does not invent or test an\napplication-specific customer route. Prove routed assistant tools by\nhaving the authenticated embedding backend pass the user's server-verified endpoint during session\nexchange, then invoke one representative safe read.\n\nDo not send a first turn on mount by default. React effect cleanup can suppress one provisional Strict Mode\neffect, but it cannot make a remount, dependency change, or client replacement idempotent. Require an\nexplicit user action unless the host owns durable one-shot state and an application idempotency key that\nmakes repeated sends safe.\n\nFor a chat-first custom host, raw `tool_started` supplies the direct call `id` and technical tool name. Map\nknown tools to concise application copy and use a neutral fallback. Reserve a stable `role=\"status\"` region\nfor thinking, tool activity, and the view skeleton; switch to the ready `<noodle-app-view>` (or React\n`NoodleAppView`) on `view_available` or to `role=\"alert\"` on error. Decorative skeleton shapes stay hidden from assistive technology, and shimmer\nor transition motion is disabled under `prefers-reduced-motion`.\n\nUse `${view.id}:${view.resourceUri}` as transport identity. Different call IDs are distinct invocations and\nmust not be deduplicated generically. If this application intentionally owns one current panel for a known\nresource, declare an application-owned slot for that resource and replace only that slot.\n\n### Framework-neutral DOM client\n\nSubscribe to the DOM-free client directly without a component wrapper and use the isolated App host.\nIt exposes the same conversation as headless AI SDK `UIMessage` state, including typed confirmation, input,\ntool-result, and linked-view parts:\n\n```html\n<div id=\"assistant-app-views\"></div>\n```\n\n```ts\nimport '@noodleseed/assistant/app-view';\nimport {\n type AssistantViewAvailableDetail,\n type NoodleAppViewElement,\n} from '@noodleseed/assistant/app-view';\nimport { createAssistantClient } from '@noodleseed/assistant/client';\n\nconst assistant = createAssistantClient({\n sessionEndpoint: '/api/noodle-assistant/session',\n});\nconst appViews = document.querySelector('#assistant-app-views');\nif (!appViews) throw new Error('Missing App views host');\nconst mountedViews = new Map<string, NoodleAppViewElement>();\nconst readResolvedTheme = (): 'light' | 'dark' =>\n document.documentElement.classList.contains('dark') ? 'dark' : 'light';\nlet resolvedTheme: 'light' | 'dark' = readResolvedTheme();\nconst syncResolvedTheme = () => {\n resolvedTheme = readResolvedTheme();\n for (const mountedView of mountedViews.values()) mountedView.theme = resolvedTheme;\n};\nnew MutationObserver(syncResolvedTheme).observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class'],\n});\nconst appViewFor = (view: AssistantViewAvailableDetail) => {\n const key = `${view.id}:${view.resourceUri}`;\n let appView = mountedViews.get(key);\n if (!appView) {\n appView = document.createElement('noodle-app-view') as NoodleAppViewElement;\n appView.client = assistant;\n mountedViews.set(key, appView);\n appViews.append(appView);\n }\n appView.theme = resolvedTheme;\n return appView;\n};\n\nassistant.subscribeChat((state) => {\n renderUIMessageState(state, {\n respond: (id, response) => assistant.respond(id, response),\n });\n const activeViewKeys = new Set<string>();\n for (const message of state.messages) {\n for (const part of message.parts) {\n if (part.type === 'data-view') {\n const key = `${part.data.id}:${part.data.resourceUri}`;\n activeViewKeys.add(key);\n appViewFor(part.data).view = part.data;\n }\n }\n }\n for (const [key, mountedView] of mountedViews) {\n if (!activeViewKeys.has(key)) {\n mountedView.remove();\n mountedViews.delete(key);\n }\n }\n});\n```\n\n`renderUIMessageState` is application code. It must present a complete schema-aware confirmation or input\nform and require an explicit user gesture before using `respond`; never call `respond` while scanning a\ntranscript snapshot.\n\n`theme=\"auto\"` follows the operating-system preference, not a SaaS-owned toggle. Pass the resolved\n`light`/`dark` theme to `NoodleAssistant` and `<noodle-app-view>`/`NoodleAppView`; updates reach mounted MCP Apps without a\nremount. CSS custom properties inherit through the host, and documented `--ns-assistant-*` variables remain\nthe final integration escape hatch. Server `branding` is shared by widgets and the assistant; there is no\nsecond branding declaration. Text streams progressively. Expired turns re-exchange and retry once;\nconfirmations never replay automatically.\n\nThe customer IdP must place the full tenant API base URL in `tenant.api_base_url`. For example, one verified\ncustomer may receive `https://customer-a.api.noodleseed.dev/v1` and another\n`https://customer-b.api.noodleseed.dev/v1`; both satisfy the declared suffix policy. Application code,\ndeployment variables, and connector arguments do not select the tenant route.\n\n`CUSTOMER_API_CLIENT_ID` and `CUSTOMER_API_CLIENT_SECRET` authenticate only the broker to the fixed exchange\nendpoint. They are not customer API bearer tokens. The exchange endpoint verifies the platform-signed\nsubject assertion and mints a short-lived token scoped to the signed-in user and route binding.\n\n## Launch and qualified-usage proof\n\nFor launch, browser verification, and qualified usage, follow the [embedded assistant guide](https://docs.noodleseed.dev/docs/guides/embedded-assistant).\n\n## Deploy customer-protected to Noodle Seed Cloud\n\n```bash\nnoodle deploy examples/customer-auth/src/server.ts \\\n --org noodleseed \\\n --app customer-auth \\\n --env prod \\\n --access customers\n```\n\nEndpoint:\n\n```text\nhttps://cloud.noodleseed.dev/o/noodleseed/customer-auth/mcp\n```\n\n## Preview anonymous Help with customer sign-in\n\nUse `noodle dev examples/customer-auth/src/server.ts --access mixed`. Help remains available before sign-in;\nprotected reads advertise descriptors and require their verified scopes/roles to execute. Customer mode\nremains the default. Local Devtools retries a protected call after successful sign-in; cancellation executes\nnothing and leaves Help available. With a hosted service, a new target may use\n`--access mixed` only after every customer tool has an authorization rule. For an existing customer-only\ntarget, preserve its org/app/env, endpoint, issuer, and audience. Follow the public guide: verify an inactive\n`customers` record for the exact version, creating it by unchanged secured redeploy if absent; add and\nvalidate every tool rule; deploy the prepared source as `customers`; recheck the rollback; then adopt mixed\naccess. On pilot failure, use\n`noodle rollback <deployment-id>` with the same org/app/env. This app-history rollback is separate from the\ncompatible hosted service-release floor. Keep the public Help endpoint through the post-deployment ChatGPT\nand customer API pilot. Local behavior and wire checks do not prove that host\njourney. See the\n[customer auth rollback and adoption procedure](https://docs.noodleseed.dev/docs/guides/customer-auth#preserve-an-app-rollback-target-and-adopt)\nfor the exact commands and checks.\n\n## Auth boundary\n\nNoodle Seed verifies the configured OIDC issuer and stable audience, then binds the exact transport-derived\nMCP resource before reading identity or routing claims. Public caller identity contains the user/role/scope\nprojection; the customer route remains private request state.\n\nConnector-backed tools ask the broker for a route-bound delegated credential; only the endpoint key and\nfingerprint enter broker cache/single-flight state or the assertion. The route claim and inbound MCP bearer\ntoken never reach tools, connectors, widgets, model output, or downstream systems. Confirmed actions keep\nthe same URL-blind binding only in private continuation state and reject acceptance-time drift.\n" },
|
|
59
59
|
{ relPath: "examples/customer-auth/noodle.json", content: "{\n \"entrypoint\": \"src/server.ts\",\n \"name\": \"customer-auth\"\n}\n" },
|
|
60
60
|
{ relPath: "examples/customer-auth/package.json", content: "{\n \"name\": \"customer-auth\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"test\": \"vitest run\",\n \"validate\": \"noodle validate\",\n \"dev\": \"noodle dev\",\n \"deploy\": \"noodle deploy\"\n },\n \"devDependencies\": {\n \"@noodleseed/one\": \"latest\",\n \"vitest\": \"latest\"\n }\n}\n" },
|
|
61
|
-
{ relPath: "examples/customer-auth/src/server.ts", content: "import {\n annotations,\n authenticatedWebsite,\n connector,\n customerAuth,\n customerEndpoint,\n embeddedAssistant,\n openAICompatible,\n publicMessaging,\n secret,\n server,\n tool,\n variable,\n z,\n} from '@noodleseed/one';\n\nconst publicHelp = tool('help', {\n title: 'Help with organizations and apps',\n description: 'Explain what customers can do before they sign in.',\n input: z.object({}),\n output: z.object({ help: z.string() }),\n annotations: annotations.readOnly(),\n fulfil() {\n return {\n help: 'Sign in to browse your organizations and apps. Archiving an app requires an administrator and confirmation.',\n };\n },\n});\n\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\nconst assistantOrigin = variable('ASSISTANT_ORIGIN');\n\nconst noodleseedApi = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n list_org_apps: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations/${args.org_id}/apps',\n query: ['skip', 'limit'],\n input: z.object({\n org_id: z.string(),\n skip: z.number().optional(),\n limit: z.number().optional(),\n }),\n output: z.object({ result: z.unknown().optional() }),\n response: {\n result: '${response}',\n },\n },\n list_organizations: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations',\n output: z.object({ organizations: z.array(z.unknown()).optional() }),\n response: {\n organizations: '${response.organizations}',\n },\n },\n archive_org_app: {\n type: 'action',\n method: 'POST',\n path: '/api/organizations/${args.org_id}/apps/${args.app_id}/archive',\n input: z.object({\n org_id: z.string(),\n app_id: z.string(),\n }),\n output: z.object({ archived: z.boolean() }),\n response: {\n archived: '${response.archived}',\n },\n },\n },\n });\n\nconst CUSTOMER_AUTH_AGENT_GUIDE = {\n description:\n 'Use the signed-in customer context to discover organizations, review their Noodle Seed apps, and archive a selected app when authorized.',\n useWhen: [\n 'A signed-in customer asks which organizations or apps they can access.',\n 'An organization administrator asks to archive one selected app.',\n ],\n workflows: [\n {\n id: 'find_organizations',\n title: 'Find the customer organizations',\n intent: 'Ground later organization-scoped work in the verified customer membership.',\n steps: [\n {\n capability: { kind: 'tool', name: 'list_my_organizations' },\n guidance: 'Use an organization identifier returned by this read in later steps.',\n },\n ],\n },\n {\n id: 'review_organization_apps',\n title: 'Review apps in one organization',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n {\n capability: { kind: 'tool', name: 'list_org_apps' },\n guidance: 'List apps only for an organization returned for the signed-in customer.',\n },\n ],\n },\n {\n id: 'archive_organization_app',\n title: 'Archive one organization app',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n { capability: { kind: 'tool', name: 'list_org_apps' } },\n {\n capability: { kind: 'tool', name: 'archive_org_app' },\n guidance: 'Archive only the exact app the customer selected after confirmation.',\n },\n ],\n },\n ],\n boundaries: [\n 'Never infer an organization or app identifier that was not returned for the signed-in customer.',\n 'Never claim an app was archived until the confirmed action succeeds.',\n ],\n examples: [\n { prompt: 'Which organizations can I access?', workflow: 'find_organizations' },\n { prompt: 'Show me the apps in this organization.', workflow: 'review_organization_apps' },\n { prompt: 'Archive the app I selected.', workflow: 'archive_organization_app' },\n ],\n} as const;\n\nexport default server(\n 'noodleseed_customer_auth',\n {\n title: 'NoodleSeed.com Customer Auth',\n version: '1.0.0',\n branding: {\n name: 'Noodle Seed Assistant',\n accent: '#E85D24',\n surface: '#FFFFFF',\n surfaceDark: '#171310',\n colorScheme: 'auto',\n theme: {\n light: { accentText: '#FFFFFF', text: '#1C1714' },\n dark: { accent: '#FF8A4C', accentText: '#1C100A', text: '#FFF8F2' },\n },\n },\n use: { app_api: noodleseedApi },\n agentGuide: CUSTOMER_AUTH_AGENT_GUIDE,\n interactions: { confirmationFallback: 'host' },\n auth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n }),\n instructions:\n 'Direct/federated MCP OIDC demo. The customer IdP proves identity and privately selects the tenant API base URL, while the broker supplies delegated credentials and confirmed actions stay bound to the reviewed route.',\n assistant: embeddedAssistant({\n model: openAICompatible({\n baseUrl: variable('ASSISTANT_MODEL_BASE_URL'),\n model: variable('ASSISTANT_MODEL'),\n apiKey: secret('ASSISTANT_MODEL_API_KEY'),\n transport: 'responses',\n }),\n // Production origins are exact HTTPS; http://localhost:<port> is allowed for local development.\n access: [\n authenticatedWebsite({\n origins: [assistantOrigin, 'https://dev.noodleseed.com', 'http://localhost:3000'],\n sessionClaims: {\n accountTier: { exposeToModel: true },\n },\n history: false, // admin chats are never kept\n }),\n publicMessaging({ channel: 'whatsapp', capabilities: [publicHelp] }),\n ],\n theme: 'auto',\n layout: { mode: 'floating', position: 'bottom-center', panelWidth: 970 },\n behavior: { showPoweredBy: true, showConfirmationDetails: false },\n labels: {\n welcomeHeading: 'How can I help with Noodle Seed?',\n launcherPlaceholder: 'Ask Noodle Seed anything',\n composerPlaceholder: 'Ask about your apps…',\n },\n presentation: {\n panel: { elevation: 'soft', border: 'subtle' },\n launcher: {\n style: 'pill',\n icon: 'brand-mark',\n status: 'session',\n effect: 'pulse',\n },\n header: {\n mark: 'status',\n badge: { text: 'Workspace online', tone: 'success', indicator: true },\n },\n composer: { leadingIcon: 'brand-mark', shape: 'pill' },\n },\n }),\n },\n [\n publicHelp,\n tool('list_org_apps', {\n title: 'List organization apps',\n description: 'List NoodleSeed.com apps for an organization from its customer API.',\n authorization: {\n discovery: 'public',\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n skip: z.number().int().min(0).optional().meta({ title: 'Starting item' }),\n limit: z.number().int().min(1).max(100).optional().meta({ title: 'Maximum results' }),\n }),\n output: z.object({\n result: z.unknown(),\n }),\n annotations: annotations.readOnly(),\n fulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n return {\n result: apps.result,\n };\n },\n }),\n tool('list_my_organizations', {\n title: 'List my organizations',\n description: 'List the NoodleSeed.com organizations the signed-in customer belongs to.',\n authorization: { discovery: 'public', requiredScopes: ['organizations:read'] },\n contextProvider: true,\n input: z.object({}),\n // The API returns all of the caller's organizations without pagination; bound the output shape.\n output: z.object({\n organizations: z.array(z.unknown()).max(100),\n }),\n annotations: annotations.readOnly(),\n fulfil({ connectors }) {\n const organizations = connectors.app_api.listOrganizations();\n return {\n organizations: organizations.organizations,\n };\n },\n }),\n tool('archive_org_app', {\n title: 'Archive organization app',\n description: 'Archive one NoodleSeed.com app through its customer API after confirmation.',\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n app_id: z.string().meta({ title: 'App' }),\n }),\n output: z.object({\n archived: z.boolean(),\n }),\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n fulfil({ input, connectors }) {\n const result = connectors.app_api.archiveOrgApp({\n org_id: input.org_id,\n app_id: input.app_id,\n });\n return {\n archived: result.archived,\n };\n },\n }),\n ],\n);\n" },
|
|
61
|
+
{ relPath: "examples/customer-auth/src/server.ts", content: "import {\n annotations,\n authenticatedWebsite,\n connector,\n customerAuth,\n customerEndpoint,\n embeddedAssistant,\n openAICompatible,\n publicMessaging,\n secret,\n server,\n tool,\n variable,\n z,\n} from '@noodleseed/one';\n\nconst publicHelp = tool('help', {\n title: 'Help with organizations and apps',\n description: 'Explain what customers can do before they sign in.',\n input: z.object({}),\n output: z.object({ help: z.string() }),\n annotations: annotations.readOnly(),\n fulfil() {\n return {\n help: 'Sign in to browse your organizations and apps. Archiving an app requires an administrator and confirmation.',\n };\n },\n});\n\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\nconst assistantOrigin = variable('ASSISTANT_ORIGIN');\n\nconst noodleseedApi = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n list_org_apps: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations/${args.org_id}/apps',\n query: ['skip', 'limit'],\n input: z.object({\n org_id: z.string(),\n skip: z.number().optional(),\n limit: z.number().optional(),\n }),\n output: z.object({ result: z.unknown().optional() }),\n response: {\n result: '${response}',\n },\n },\n list_organizations: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations',\n output: z.object({ organizations: z.array(z.unknown()).optional() }),\n response: {\n organizations: '${response.organizations}',\n },\n },\n archive_org_app: {\n type: 'action',\n method: 'POST',\n path: '/api/organizations/${args.org_id}/apps/${args.app_id}/archive',\n input: z.object({\n org_id: z.string(),\n app_id: z.string(),\n }),\n output: z.object({ archived: z.boolean() }),\n response: {\n archived: '${response.archived}',\n },\n },\n },\n });\n\nconst CUSTOMER_AUTH_AGENT_GUIDE = {\n description:\n 'Use the signed-in customer context to discover organizations, review their Noodle Seed apps, and archive a selected app when authorized.',\n useWhen: [\n 'A signed-in customer asks which organizations or apps they can access.',\n 'An organization administrator asks to archive one selected app.',\n ],\n workflows: [\n {\n id: 'find_organizations',\n title: 'Find the customer organizations',\n intent: 'Ground later organization-scoped work in the verified customer membership.',\n steps: [\n {\n capability: { kind: 'tool', name: 'list_my_organizations' },\n guidance: 'Use an organization identifier returned by this read in later steps.',\n },\n ],\n },\n {\n id: 'review_organization_apps',\n title: 'Review apps in one organization',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n {\n capability: { kind: 'tool', name: 'list_org_apps' },\n guidance: 'List apps only for an organization returned for the signed-in customer.',\n },\n ],\n },\n {\n id: 'archive_organization_app',\n title: 'Archive one organization app',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n { capability: { kind: 'tool', name: 'list_org_apps' } },\n {\n capability: { kind: 'tool', name: 'archive_org_app' },\n guidance: 'Archive only the exact app the customer selected after confirmation.',\n },\n ],\n },\n ],\n boundaries: [\n 'Never infer an organization or app identifier that was not returned for the signed-in customer.',\n 'Never claim an app was archived until the confirmed action succeeds.',\n ],\n examples: [\n { prompt: 'Which organizations can I access?', workflow: 'find_organizations' },\n { prompt: 'Show me the apps in this organization.', workflow: 'review_organization_apps' },\n { prompt: 'Archive the app I selected.', workflow: 'archive_organization_app' },\n ],\n} as const;\n\nexport default server(\n 'noodleseed_customer_auth',\n {\n title: 'NoodleSeed.com Customer Auth',\n version: '1.0.0',\n branding: {\n name: 'Noodle Seed Assistant',\n accent: '#E85D24',\n surface: '#FFFFFF',\n surfaceDark: '#171310',\n colorScheme: 'auto',\n theme: {\n light: { accentText: '#FFFFFF', text: '#1C1714' },\n dark: { accent: '#FF8A4C', accentText: '#1C100A', text: '#FFF8F2' },\n },\n },\n use: { app_api: noodleseedApi },\n agentGuide: CUSTOMER_AUTH_AGENT_GUIDE,\n interactions: { confirmationFallback: 'host' },\n auth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n }),\n instructions:\n 'Direct/federated MCP OIDC demo. The customer IdP proves identity and privately selects the tenant API base URL, while the broker supplies delegated credentials and confirmed actions stay bound to the reviewed route.',\n assistant: embeddedAssistant({\n model: openAICompatible({\n baseUrl: variable('ASSISTANT_MODEL_BASE_URL'),\n model: variable('ASSISTANT_MODEL'),\n apiKey: secret('ASSISTANT_MODEL_API_KEY'),\n transport: 'responses',\n }),\n // Exact HTTPS origins; http://localhost:<port> for local dev.\n access: [\n authenticatedWebsite({\n origins: [assistantOrigin, 'https://dev.noodleseed.com', 'http://localhost:3000'],\n sessionClaims: {\n accountTier: { exposeToModel: true },\n },\n history: false, // admin chats are never kept\n }),\n publicMessaging({ channel: 'whatsapp', capabilities: [publicHelp] }),\n ],\n theme: 'auto',\n layout: { mode: 'floating', position: 'bottom-center', panelWidth: 970 },\n behavior: { showPoweredBy: true, showConfirmationDetails: false },\n labels: {\n welcomeHeading: 'How can I help with Noodle Seed?',\n launcherPlaceholder: 'Ask Noodle Seed anything',\n composerPlaceholder: 'Ask about your apps…',\n },\n historyNotice: 'Chats are kept for {days} day(s)',\n presentation: {\n panel: { elevation: 'soft', border: 'subtle' },\n launcher: {\n style: 'pill',\n icon: 'brand-mark',\n status: 'session',\n effect: 'pulse',\n },\n header: {\n mark: 'status',\n badge: { text: 'Workspace online', tone: 'success', indicator: true },\n },\n composer: { leadingIcon: 'brand-mark', shape: 'pill' },\n },\n }),\n },\n [\n publicHelp,\n tool('list_org_apps', {\n title: 'List organization apps',\n description: 'List NoodleSeed.com apps for an organization from its customer API.',\n authorization: {\n discovery: 'public',\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n skip: z.number().int().min(0).optional().meta({ title: 'Starting item' }),\n limit: z.number().int().min(1).max(100).optional().meta({ title: 'Maximum results' }),\n }),\n output: z.object({\n result: z.unknown(),\n }),\n annotations: annotations.readOnly(),\n fulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n return {\n result: apps.result,\n };\n },\n }),\n tool('list_my_organizations', {\n title: 'List my organizations',\n description: 'List the NoodleSeed.com organizations the signed-in customer belongs to.',\n authorization: { discovery: 'public', requiredScopes: ['organizations:read'] },\n contextProvider: true,\n input: z.object({}),\n // The API returns all of the caller's organizations without pagination; bound the output shape.\n output: z.object({\n organizations: z.array(z.unknown()).max(100),\n }),\n annotations: annotations.readOnly(),\n fulfil({ connectors }) {\n const organizations = connectors.app_api.listOrganizations();\n return {\n organizations: organizations.organizations,\n };\n },\n }),\n tool('archive_org_app', {\n title: 'Archive organization app',\n description: 'Archive one NoodleSeed.com app through its customer API after confirmation.',\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n app_id: z.string().meta({ title: 'App' }),\n }),\n output: z.object({\n archived: z.boolean(),\n }),\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n fulfil({ input, connectors }) {\n const result = connectors.app_api.archiveOrgApp({\n org_id: input.org_id,\n app_id: input.app_id,\n });\n return {\n archived: result.archived,\n };\n },\n }),\n ],\n);\n" },
|
|
62
62
|
{ relPath: "examples/customer-auth/test/server.test.ts", content: "import { describe, expect, it } from 'vitest';\nimport app from '../src/server.js';\n\ndescribe('customer-auth example', () => {\n it('exports a customer-authenticated, customer-branded embedded assistant', async () => {\n expect(typeof app.toManifest).toBe('function');\n const manifest = await app.toManifest();\n expect(manifest.server.assistant).toMatchObject({\n model: { kind: 'openai-compatible', apiKey: 'ASSISTANT_MODEL_API_KEY' },\n layout: { mode: 'floating' },\n presentation: {\n panel: { elevation: 'soft', border: 'subtle' },\n launcher: { icon: 'brand-mark', status: 'session', effect: 'pulse' },\n header: { mark: 'status', badge: { text: 'Workspace online', tone: 'success' } },\n },\n });\n expect(manifest.server.assistant?.allowedOrigins).toEqual([\n '${env.ASSISTANT_ORIGIN}',\n 'https://dev.noodleseed.com',\n 'http://localhost:3000',\n ]);\n expect(manifest.server.assistant?.sessionClaims).toEqual({\n accountTier: { exposeToModel: true },\n });\n expect(manifest.server.branding).toMatchObject({\n name: 'Noodle Seed Assistant',\n colorScheme: 'auto',\n });\n expect(manifest.server.auth).toEqual({\n kind: 'oidc',\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n });\n expect(manifest.server.interactions).toEqual({ confirmationFallback: 'host' });\n expect(manifest.server.agentGuide?.workflows.map((workflow) => workflow.id)).toEqual([\n 'find_organizations',\n 'review_organization_apps',\n 'archive_organization_app',\n ]);\n expect(\n manifest.server.agentGuide?.workflows.find(\n (workflow) => workflow.id === 'archive_organization_app',\n )?.steps,\n ).toEqual([\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n { capability: { kind: 'tool', name: 'list_org_apps' } },\n {\n capability: { kind: 'tool', name: 'archive_org_app' },\n guidance: 'Archive only the exact app the customer selected after confirmation.',\n },\n ]);\n const catalog = app.toConnectorCatalog();\n expect(catalog?.connectors).toHaveLength(1);\n expect(catalog?.connectors[0]?.http).toMatchObject({\n baseUrl: {\n kind: 'customerEndpoint',\n name: 'customer_api',\n policy: { allowedHttpsHostSuffixes: ['api.noodleseed.dev'] },\n },\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: '${env.CUSTOMER_API_CLIENT_ID}',\n clientSecret: 'CUSTOMER_API_CLIENT_SECRET',\n },\n });\n expect(catalog?.connectors[0]?.operations).toMatchObject({\n list_org_apps: { type: 'read' },\n list_organizations: { type: 'read' },\n archive_org_app: { type: 'action', method: 'POST' },\n });\n expect(catalog?.connectors[0]?.http).not.toHaveProperty('allowedOrigins');\n expect(JSON.stringify({ manifest, catalog })).not.toContain('tenant-a.api.noodleseed.dev');\n expect(manifest.tools.find((tool) => tool.name === 'list_org_apps')?.authorization).toEqual({\n discovery: 'public',\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n });\n expect(\n manifest.tools.find((tool) => tool.name === 'list_my_organizations')?.authorization,\n ).toEqual({ discovery: 'public', requiredScopes: ['organizations:read'] });\n const help = manifest.tools.find((tool) => tool.name === 'help');\n expect(help).toBeDefined();\n expect(help?.authorization).toBeUndefined();\n expect(help?.annotations?.readOnlyHint).toBe(true);\n expect(manifest.tools.find((tool) => tool.name === 'archive_org_app')).toMatchObject({\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n confirm: true,\n },\n });\n expect(\n manifest.tools.find((tool) => tool.name === 'list_org_apps')?.annotations?.readOnlyHint,\n ).toBe(true);\n });\n});\n" },
|
|
63
63
|
{ relPath: "examples/customer-auth/vitest.config.ts", content: "import { defineConfig } from 'vitest/config';\n\n// Keep the flagship's own contract test executable instead of inheriting the monorepo package-only glob.\nexport default defineConfig({\n test: { include: ['test/**/*.test.ts'] },\n});\n" },
|
|
64
64
|
{ relPath: "examples/food-ordering/README.md", content: "# Food Ordering\n\n**Owns:** The flagship consumer ordering MCP App example: React view authoring, app-only helper tools,\ncaller-scoped cart state handles, invocation context, model-visible widget state/lifecycle, packaged image\nassets, portable structured elicitation, checkout handoff policy, host actions, CSP/permissions metadata,\nproduct-agent guidance, host-neutral distribution metadata, and widget preview coverage.\n\nFood Ordering is a generic, synthetic version of a live marketplace ordering app. It lets a user search\nstores, browse menus, customize an item, build a multi-line cart, review the order, and hand off checkout to\nan allowlisted example domain. It does not use real restaurant APIs, real checkout, customer credentials, or\nprivate customer data.\n\n## What It Shows\n\n| Capability | Example |\n| :--- | :--- |\n| Public entry tool | `open_ordering` returns structured fallback content and renders the React widget |\n| Product and distribution projections | `agentGuide` supplies grounded cross-capability guidance; `distribution` supplies listing, publisher, legal, image, and review facts separately from the runtime manifest |\n| App-only helper tools | `search_stores`, `load_menu`, `load_item`, `read_cart`, `sync_cart`, `prepare_checkout`; mutating widget-owned helpers use `confirm: false` (equivalent to omission) and execute directly because action hints alone never gate |\n| Durable cart state | `server(..., { state: { handles: { cart } }, use: { state } })` with caller scope, revision checks, and explicit ticket-bound adoption when an anonymous visitor authenticates |\n| React app runtime kit | `@noodleseed/one/react` supplies app flow, shell/nav/view, async state, form, quantity, choice, and handoff primitives |\n| Multi-step widget flow | One React shell navigates stores, menu, item customization, cart, review, and handoff views through `useAppFlow` |\n| Invocation context | `server.context` sets locale/time-zone defaults, derives an ambient service area/date, and exposes optional host-supplied coordinates to tools and the reserved `noodle_context` MCP adapter; location is an untrusted convenience hint, never an authorization signal or a substitute for explicit input |\n| Structured missing input | `plan_order` uses `ctx.elicit` to collect a fulfilment method and date through embedded/headless forms, standard bidirectional elicitation, a linked MCP App form, or an exact structured conversational retry on stateless hosts |\n| Model-visible widget state | `useUpdateModelContext` publishes one cohesive replacement snapshot when supported; `useWidgetLifecycle` auto-publishes mounted/cancelled/dismissed and reports author-owned submitted milestones for future context (not host-presentation proof), while the user-triggered submit pairs `useSendFollowUpMessage` for an immediate reply |\n| Handoff | `handoff.allowedDomains` allows only `https://orders.example.com` checkout URLs |\n| Progressive enhancement | Non-Apps hosts still receive stores, featured items, and a readable fallback summary |\n| Fail-closed hydration | The React view treats only the unhydrated, pre-result `{}` envelope as pending; a hydrated empty success remains distinct. It surfaces `isError`, validates required records and identifiers, and withholds ordering actions from malformed results |\n| Upstream MCP composition | This synthetic example keeps its data local. For the canonical frozen-tool import, governed upstream invocation, response normalization, and Noodle-owned widget pattern, use the repository's `shopify-storefront` flagship rather than copying another composition surface here |\n\nThe example is intentionally richer than the generated starter, but each inline view still follows the\nsame default: one immediate purpose, one primary action, at most one subordinate action, and progressive\ndisclosure for the rest. Preview it at 280px before adding navigation or local CSS; loading, empty, stale,\nerror/retry, and success states must remain readable without nested vertical scrolling.\n\nLike the comprehensive default `noodle init my-app` scaffold, this flagship keeps the server feature-rich\nwhile making each individual widget view focused; server capability breadth and screen density are separate.\nThe compiled initial widget should normally remain under the 1 MiB performance recommendation; Noodle Seed's\nhard ceilings are 10 MiB per compiled widget and 20 MiB across one deployment. Run `noodle check` to see raw\nand gzip-estimated sizes. Deploy requests are gzip-compressed as one stream so repeated self-contained React\nruntime bytes deduplicate on the wire without a cross-tenant CDN. Keep menu images or large live datasets in assets/resources and app-only tools\nrather than embedding them into the initial HTML bundle.\n\n## Local Author Loop\n\n```sh\nnoodle validate\nnoodle test\nnoodle dev\n```\n\nThe same `server.ts` declares `distribution` metadata for host adapters. It references real packaged images\nand keeps listing copy, support/legal URLs, and positive/negative review scenarios outside the canonical App\nPackage and Runtime Artifact. Explicit OpenAI and Claude adapters project those facts with the generated\nproduct skill; installable plugin archives and directory-submission dossiers remain separate outputs.\n\nIn another terminal:\n\n```sh\nnoodle tools list\nnoodle tools call open_ordering --args '{\"customer\":\"Asha\",\"query\":\"noodles\"}'\nnoodle tools call summarize_ordering_options --args '{}'\n```\n\nWhen a developer finalizes visual feedback in the local Design experience, a coding agent can inspect the\nlatest project-local brief without a path or session id:\n\n```sh\nnoodle design inspect --latest --json\n```\n\nThe agent should locate the captured elements in this example's authored React source, preserve the listed\nbehavior and accessibility constraints, and verify every acceptance check before changing unrelated UI.\n\nFor Apps metadata conformance, start `noodle dev`, copy the loopback MCP endpoint, then run:\n\n```sh\nnpx @mcpjam/cli@latest apps conformance --url http://127.0.0.1:<port>/o/demo/food-ordering/mcp --quiet --format json\n```\n\n## Export an OpenAI plugin\n\nThis flagship includes the guided workflows, listing metadata, review cases, and image assets needed to test\nOpenAI export. See the public [product-agent guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#export-an-openai-package)\nfor the current package workflow and boundaries.\n\nAgainst its deployed MCP URL, generate the Food Ordering submission candidate with:\n\n```sh\nnoodle export plugin openai \\\n --state submission \\\n --mcp-url https://food-ordering.noodleseed.app/mcp \\\n --category \"Food & Drink\" \\\n --output food-ordering-openai.zip\n```\n\nExtract `food-ordering-openai.zip` before using the portal. Upload\n`submission/chatgpt-app-submission.json` to the Codex-assisted import field and\n`submission/food-ordering-skill.zip` to **With MCP → Skills**. The outer ZIP is the complete review kit and\nis not itself a valid skill upload; `submission/README.md` repeats the portal steps.\n\nAfter registering that same URL in ChatGPT developer mode, substitute its real technical ID to generate the\nFood Ordering local test package:\n\n```sh\nnoodle export plugin openai \\\n --state local \\\n --mcp-url https://food-ordering.noodleseed.app/mcp \\\n --category \"Food & Drink\" \\\n --registered-app-id plugin_asdk_app_0123456789abcdef0123456789abcdef \\\n --output food-ordering-openai-local.zip\n```\n\n## Export for Claude\n\nClaude Code plugin packaging and Anthropic Connector Directory review are separate outputs. Generate the\ninstallable plugin repository with:\n\n```sh\nnoodle export plugin claude \\\n --mcp-url https://food-ordering.noodleseed.app/mcp \\\n --output food-ordering-claude.zip\n```\n\nGenerate the credential-free operator dossier for the remote Connector Directory with:\n\n```sh\nnoodle export connector claude \\\n --mcp-url https://food-ordering.noodleseed.app/mcp \\\n --auth none \\\n --category \"Food & Drink\" \\\n --output food-ordering-anthropic-connector.zip\n```\n\nThe dossier is deliberately marked `portalUploadable: false`: it gathers the listing, tool annotations,\nuse cases, allowed-link candidates, test-account guidance, and MCP App screenshot evidence, but a human must\nverify ownership/compliance and enter the final answers in Anthropic's portal. The plugin ZIP does not\ncontain this dossier.\n\n## Client Setup\n\nUse the CLI to print the exact setup flow for your MCP client:\n\n```sh\nnoodle connect claude\nnoodle connect chatgpt\nnoodle connect inspector\n```\n\n## Deploy\n\n```sh\nnoodle deploy --org demo --app food-ordering --env prod --access owner-only\nnoodle open\n```\n\nThat one deploy command preflights the complete target, creates a missing app/environment, and verifies\nhosted readiness. If it is interrupted, rerun the same command to resume the unfinished operation without a\nduplicate deployment. Use `--access org-members` for an org-wide internal demo. This example has no\nconnector secrets and does not include tokens, caller-key mechanisms, or `.env.noodle` values.\n\n### Publish an immutable host archive\n\nOnly when this demo is intentionally being prepared for an external directory, deploy it with exact public\naccess and use the returned deployment ID to publish the matching local source:\n\n```sh\nnoodle deploy --org demo --app food-ordering --env prod --access public\nnoodle distributions publish <deployment-id> src/server.ts --target openai --category \"Food & Drink\"\nnoodle distributions list <deployment-id> --target openai\nnoodle distributions readiness <distribution-id> --status ready --note \"Archive and review evidence checked\"\nnoodle distributions release <distribution-id> --visibility private\nnoodle distributions grant <distribution-id> --expires-in 900\nnoodle distributions download <distribution-id> --output food-ordering-openai.zip\n```\n\nPublish fails if local `src/server.ts` no longer compiles to that deployment's package snapshot. Readiness is\nan explicit operator claim, the private release keeps anonymous discovery off, and the grant prints one\nsensitive exact-version reviewer URL. Record `noodle distributions review` only after a human observes the\nreal portal state. Public Noodle delivery, rollback, deprecation, and terminal revocation are separate explicit\nactions; none submits to a directory or claims acceptance.\n\n## Demo Assets\n\nThe packaged demo images live under `assets/`. The current app uses `assets/noodle-bowl.jpg` as the server\nbranding image. Its three distribution screenshots are real, response-only MCP App captures from Noodle\nDevtools at 2× device scale; each is 1640×970 PNG and has the producing user prompt next to its `asset(...)`\nreference in `server.ts`.\n\nImage sources:\n\n- `assets/noodle-bowl.jpg` — Unsplash photo\n [`IRv8V9Hb8gI`](https://unsplash.com/photos/IRv8V9Hb8gI), downloaded from Unsplash.\n- `assets/food-ordering-stores.png` — store-discovery state produced by “Help me build a noodle order for\n pickup.”\n- `assets/food-ordering-menu.png` — Harbor Noodles menu state produced by “Show me the Harbor Noodles\n menu.”\n- `assets/food-ordering-handoff.png` — checkout-handoff state produced by “Review my spicy miso bowl order\n before checkout.”\n\nThe Unsplash branding photo is free to use under the [Unsplash License](https://unsplash.com/license);\nattribution is not required, but the source note is kept here for provenance.\n" },
|
|
@@ -443,7 +443,7 @@ export function renderEmbeddedAssistantReference() {
|
|
|
443
443
|
'',
|
|
444
444
|
'The exchange returns the versioned Embedded Assistant v1 contract. `token`, `expiresAt`, and `endpoints.turns` / legacy `endpoints.toolConfirmations` (absolute URLs) are always present; current services add `endpoints.interactions` for accept/decline/cancel. `configuration` is optional theming data. Forward the body unchanged; browser clients choose the advertised endpoint. Do not rebuild, filter, or rewrite the response.',
|
|
445
445
|
'',
|
|
446
|
-
|
|
446
|
+
"When the business records conversation history, the response carries an optional top-level `history: { retentionDays, notice? }` for the current caller, and the widget states it in its footer automatically (\"Chats are kept for 30 days\"); WhatsApp states it in the first reply. To state it in your visitors' language, declare `embeddedAssistant({ historyNotice: 'Los chats se guardan {days} días', ... })` (`{days}` required); both channels then use it and the response carries the filled-in text as `history.notice`. A custom renderer must show the same line: read `history` from the `session_started` event data, render `history.notice` when present or the English line otherwise, and render nothing when `history` is absent. A surface declared `history: false` never carries it. State the same period on the host application's privacy page.",
|
|
447
447
|
'',
|
|
448
448
|
'Recorded conversations belong to the `user.id` the backend sent at exchange, so your backend can manage them with the same client credential. Call `forgetUser` from the application\'s own account-deletion flow (idempotent; retry on a retryable `AssistantConversationsError`), and `listConversations` for a "your chats" or support view (newest first, a short first-question `preview`, `nextCursor` paging). Pass the identical id used for `createAssistantSession`; any other id sees nothing. Both are backend-only and scoped to the client\'s application environment.',
|
|
449
449
|
'',
|
|
@@ -108,6 +108,12 @@ export interface AssistantUiOptions {
|
|
|
108
108
|
readonly termsUrl?: string;
|
|
109
109
|
readonly locale?: string;
|
|
110
110
|
readonly direction?: 'ltr' | 'rtl' | 'auto';
|
|
111
|
+
/**
|
|
112
|
+
* The retention notice a recorded conversation states, in your visitors' language, e.g.
|
|
113
|
+
* `'Los chats se guardan {days} días'`. `{days}` is required and becomes the window; unset keeps
|
|
114
|
+
* the English "Chats are kept for N days". The widget footer and the first WhatsApp reply use it.
|
|
115
|
+
*/
|
|
116
|
+
readonly historyNotice?: string;
|
|
111
117
|
}
|
|
112
118
|
export type OpenAICompatibleTransport = 'chat-completions' | 'responses';
|
|
113
119
|
export interface OpenAICompatibleModelInput {
|
|
@@ -78,6 +78,9 @@ export function embeddedAssistant(input) {
|
|
|
78
78
|
assertAccessDeclared(input, access);
|
|
79
79
|
const surfaces = (Array.isArray(access) ? access : [access]);
|
|
80
80
|
assertDistinctSurfaces(surfaces);
|
|
81
|
+
if (ui.historyNotice !== undefined && !ui.historyNotice.includes('{days}')) {
|
|
82
|
+
throw new Error('historyNotice must contain {days}, where the retention window is stated');
|
|
83
|
+
}
|
|
81
84
|
const sessionClaims = surfaces.find((surface) => surface.mode === 'authenticated')?.sessionClaims;
|
|
82
85
|
return {
|
|
83
86
|
model: { ...model },
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { httpsUrlSchema } from './branding-schema.js';
|
|
3
|
+
/**
|
|
4
|
+
* The embedded assistant's renderer-owned UI shape: layout, behavior, labels, presentation, and the
|
|
5
|
+
* server-side retention notice template.
|
|
6
|
+
*
|
|
7
|
+
* Extracted verbatim from `schema.ts` so that file stays inside its size budget as the assistant
|
|
8
|
+
* surface grows. It depends only on leaf validators, never on tools, surfaces, or the assistant
|
|
9
|
+
* block that spreads it, so the split is one-directional and free of an import cycle.
|
|
10
|
+
*/
|
|
11
|
+
const assistantPresentationToneSchema = z.enum(['neutral', 'success', 'warning', 'danger']);
|
|
12
|
+
export const optionalStrictObject = (shape) => z.object(shape).strict().optional();
|
|
13
|
+
const assistantPresentationSchema = z
|
|
14
|
+
.object({
|
|
15
|
+
panel: optionalStrictObject({
|
|
16
|
+
surface: z.enum(['solid', 'glass']).optional(),
|
|
17
|
+
elevation: z.enum(['soft', 'dramatic']).optional(),
|
|
18
|
+
border: z.enum(['subtle', 'strong']).optional(),
|
|
19
|
+
radius: z.number().int().min(0).max(64).optional(),
|
|
20
|
+
}),
|
|
21
|
+
launcher: optionalStrictObject({
|
|
22
|
+
style: z.enum(['pill', 'bubble']).optional(),
|
|
23
|
+
icon: z.enum(['brand-mark', 'chat', 'none']).optional(),
|
|
24
|
+
size: z.enum(['md', 'lg']).optional(),
|
|
25
|
+
status: z.enum(['none', 'session']).optional(),
|
|
26
|
+
effect: z.enum(['none', 'pulse']).optional(),
|
|
27
|
+
}),
|
|
28
|
+
header: optionalStrictObject({
|
|
29
|
+
mark: z.enum(['none', 'brand-mark', 'status']).optional(),
|
|
30
|
+
badge: optionalStrictObject({
|
|
31
|
+
text: z.string().trim().min(1).max(80),
|
|
32
|
+
tone: assistantPresentationToneSchema.optional(),
|
|
33
|
+
indicator: z.boolean().optional(),
|
|
34
|
+
}),
|
|
35
|
+
}),
|
|
36
|
+
composer: optionalStrictObject({
|
|
37
|
+
leadingIcon: z.enum(['none', 'brand-mark']).optional(),
|
|
38
|
+
sendIcon: z.enum(['arrow-up', 'paper-plane']).optional(),
|
|
39
|
+
shape: z.enum(['rounded', 'pill']).optional(),
|
|
40
|
+
}),
|
|
41
|
+
messages: optionalStrictObject({
|
|
42
|
+
userStyle: z.enum(['bubble', 'accent']).optional(),
|
|
43
|
+
assistantStyle: z.enum(['plain', 'bubble']).optional(),
|
|
44
|
+
}),
|
|
45
|
+
})
|
|
46
|
+
.strict();
|
|
47
|
+
export const assistantUiSchema = z
|
|
48
|
+
.object({
|
|
49
|
+
theme: z.enum(['auto', 'light', 'dark', 'invert']).optional(),
|
|
50
|
+
layout: optionalStrictObject({
|
|
51
|
+
mode: z.enum(['floating', 'inline', 'drawer']).optional(),
|
|
52
|
+
position: z.enum(['bottom-left', 'bottom-center', 'bottom-right']).optional(),
|
|
53
|
+
panelWidth: z.number().int().min(280).max(1200).optional(),
|
|
54
|
+
panelMinHeight: z.number().int().min(240).max(1600).optional(),
|
|
55
|
+
panelMaxHeight: z.number().int().min(320).max(2400).optional(),
|
|
56
|
+
edgeOffset: z.number().int().min(0).max(96).optional(),
|
|
57
|
+
zIndex: z.number().int().min(0).max(2147483647).optional(),
|
|
58
|
+
density: z.enum(['compact', 'comfortable']).optional(),
|
|
59
|
+
mobileFullscreen: z.boolean().optional(),
|
|
60
|
+
}),
|
|
61
|
+
behavior: optionalStrictObject({
|
|
62
|
+
startOpen: z.boolean().optional(),
|
|
63
|
+
closeOnEscape: z.boolean().optional(),
|
|
64
|
+
closeOnOutsideClick: z.boolean().optional(),
|
|
65
|
+
showLauncher: z.boolean().optional(),
|
|
66
|
+
showHeader: z.boolean().optional(),
|
|
67
|
+
showAvatars: z.boolean().optional(),
|
|
68
|
+
showTimestamps: z.boolean().optional(),
|
|
69
|
+
showPoweredBy: z.boolean().optional(),
|
|
70
|
+
showConfirmationDetails: z.boolean().optional(),
|
|
71
|
+
}),
|
|
72
|
+
labels: optionalStrictObject({
|
|
73
|
+
welcomeHeading: z.string().trim().min(1).max(160).optional(),
|
|
74
|
+
welcomeMessage: z.string().max(1000).optional(),
|
|
75
|
+
launcherPlaceholder: z.string().trim().min(1).max(160).optional(),
|
|
76
|
+
composerPlaceholder: z.string().trim().min(1).max(160).optional(),
|
|
77
|
+
thinking: z.string().trim().min(1).max(80).optional(),
|
|
78
|
+
send: z.string().trim().min(1).max(80).optional(),
|
|
79
|
+
stop: z.string().trim().min(1).max(80).optional(),
|
|
80
|
+
close: z.string().trim().min(1).max(80).optional(),
|
|
81
|
+
open: z.string().trim().min(1).max(80).optional(),
|
|
82
|
+
confirm: z.string().trim().min(1).max(80).optional(),
|
|
83
|
+
decline: z.string().trim().min(1).max(80).optional(),
|
|
84
|
+
cancel: z.string().trim().min(1).max(80).optional(),
|
|
85
|
+
confirmationHeading: z.string().trim().min(1).max(120).optional(),
|
|
86
|
+
additionalDetails: z.string().trim().min(1).max(120).optional(),
|
|
87
|
+
redacted: z.string().trim().min(1).max(120).optional(),
|
|
88
|
+
completed: z.string().trim().min(1).max(80).optional(),
|
|
89
|
+
stopped: z.string().trim().min(1).max(80).optional(),
|
|
90
|
+
copy: z.string().trim().min(1).max(80).optional(),
|
|
91
|
+
newMessages: z.string().trim().min(1).max(80).optional(),
|
|
92
|
+
reconnect: z.string().trim().min(1).max(80).optional(),
|
|
93
|
+
newConversation: z.string().trim().min(1).max(80).optional(),
|
|
94
|
+
retry: z.string().trim().min(1).max(80).optional(),
|
|
95
|
+
unavailable: z.string().trim().min(1).max(240).optional(),
|
|
96
|
+
sessionExpired: z.string().trim().min(1).max(240).optional(),
|
|
97
|
+
sessionIdle: z.string().trim().min(1).max(120).optional(),
|
|
98
|
+
sessionLoading: z.string().trim().min(1).max(120).optional(),
|
|
99
|
+
sessionReady: z.string().trim().min(1).max(120).optional(),
|
|
100
|
+
sessionError: z.string().trim().min(1).max(120).optional(),
|
|
101
|
+
signInHeading: z.string().trim().min(1).max(120).optional(),
|
|
102
|
+
signInBody: z.string().max(240).optional(),
|
|
103
|
+
signInAction: z.string().trim().min(1).max(80).optional(),
|
|
104
|
+
signUpAction: z.string().trim().min(1).max(80).optional(),
|
|
105
|
+
}),
|
|
106
|
+
presentation: assistantPresentationSchema.optional(),
|
|
107
|
+
suggestedPrompts: z.array(z.string().trim().min(1).max(240)).max(8).optional(),
|
|
108
|
+
privacyUrl: httpsUrlSchema.optional(),
|
|
109
|
+
termsUrl: httpsUrlSchema.optional(),
|
|
110
|
+
locale: z.string().trim().min(2).max(35).optional(),
|
|
111
|
+
direction: z.enum(['ltr', 'rtl', 'auto']).optional(),
|
|
112
|
+
// Server-side only (ADR 0241 decision 17): rendered into the session's top-level `history`, never
|
|
113
|
+
// forwarded inside the browser `configuration`, whose strict published schemas reject new keys.
|
|
114
|
+
historyNotice: z
|
|
115
|
+
.string()
|
|
116
|
+
.trim()
|
|
117
|
+
.min(1)
|
|
118
|
+
.max(160)
|
|
119
|
+
.refine((value) => value.includes('{days}'), 'historyNotice must contain {days}')
|
|
120
|
+
.optional(),
|
|
121
|
+
})
|
|
122
|
+
.strict();
|
|
123
|
+
//# sourceMappingURL=assistant-ui-schema.js.map
|
|
@@ -345,6 +345,7 @@ export declare const manifestV1Schema: z.ZodObject<{
|
|
|
345
345
|
ltr: "ltr";
|
|
346
346
|
rtl: "rtl";
|
|
347
347
|
}>>;
|
|
348
|
+
historyNotice: z.ZodOptional<z.ZodString>;
|
|
348
349
|
model: z.ZodUnion<readonly [z.ZodObject<{
|
|
349
350
|
kind: z.ZodLiteral<"openai-compatible">;
|
|
350
351
|
transport: z.ZodOptional<z.ZodEnum<{
|
|
@@ -851,6 +852,7 @@ export declare const manifestV2Schema: z.ZodObject<{
|
|
|
851
852
|
ltr: "ltr";
|
|
852
853
|
rtl: "rtl";
|
|
853
854
|
}>>;
|
|
855
|
+
historyNotice: z.ZodOptional<z.ZodString>;
|
|
854
856
|
model: z.ZodUnion<readonly [z.ZodObject<{
|
|
855
857
|
kind: z.ZodLiteral<"openai-compatible">;
|
|
856
858
|
transport: z.ZodOptional<z.ZodEnum<{
|
|
@@ -1651,6 +1653,7 @@ export declare const manifestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
1651
1653
|
ltr: "ltr";
|
|
1652
1654
|
rtl: "rtl";
|
|
1653
1655
|
}>>;
|
|
1656
|
+
historyNotice: z.ZodOptional<z.ZodString>;
|
|
1654
1657
|
model: z.ZodUnion<readonly [z.ZodObject<{
|
|
1655
1658
|
kind: z.ZodLiteral<"openai-compatible">;
|
|
1656
1659
|
transport: z.ZodOptional<z.ZodEnum<{
|
|
@@ -2156,6 +2159,7 @@ export declare const manifestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
2156
2159
|
ltr: "ltr";
|
|
2157
2160
|
rtl: "rtl";
|
|
2158
2161
|
}>>;
|
|
2162
|
+
historyNotice: z.ZodOptional<z.ZodString>;
|
|
2159
2163
|
model: z.ZodUnion<readonly [z.ZodObject<{
|
|
2160
2164
|
kind: z.ZodLiteral<"openai-compatible">;
|
|
2161
2165
|
transport: z.ZodOptional<z.ZodEnum<{
|
|
@@ -5,6 +5,7 @@ import { MAX_VARIABLE_DECLARATIONS, variableDeclarationManifestSchema, } from '.
|
|
|
5
5
|
import { MAX_MANAGED_COLLECTIONS, managedCollectionManifestSchema, } from '../managed-collections.js';
|
|
6
6
|
import { MAX_COMPILED_WIDGET_HTML_BYTES, MAX_RAW_WIDGET_HTML_BYTES } from '../widget-limits.js';
|
|
7
7
|
import { agentGuideSchema } from './agent-guide-schema.js';
|
|
8
|
+
import { assistantUiSchema, optionalStrictObject } from './assistant-ui-schema.js';
|
|
8
9
|
import { serverAuthSchema, serverAuthV2Schema } from './auth-schema.js';
|
|
9
10
|
import { assistantOriginOrVariableSchema, httpsUrlSchema, managedVariableExpressionSchema, serverBrandingSchema, } from './branding-schema.js';
|
|
10
11
|
import { toolInteractionSchema } from './interaction-schema.js';
|
|
@@ -153,109 +154,6 @@ const promptSchema = z.object({
|
|
|
153
154
|
arguments: z.array(promptArgumentSchema).optional(),
|
|
154
155
|
fulfilment: fulfilmentSchema,
|
|
155
156
|
});
|
|
156
|
-
const assistantPresentationToneSchema = z.enum(['neutral', 'success', 'warning', 'danger']);
|
|
157
|
-
const optionalStrictObject = (shape) => z.object(shape).strict().optional();
|
|
158
|
-
const assistantPresentationSchema = z
|
|
159
|
-
.object({
|
|
160
|
-
panel: optionalStrictObject({
|
|
161
|
-
surface: z.enum(['solid', 'glass']).optional(),
|
|
162
|
-
elevation: z.enum(['soft', 'dramatic']).optional(),
|
|
163
|
-
border: z.enum(['subtle', 'strong']).optional(),
|
|
164
|
-
radius: z.number().int().min(0).max(64).optional(),
|
|
165
|
-
}),
|
|
166
|
-
launcher: optionalStrictObject({
|
|
167
|
-
style: z.enum(['pill', 'bubble']).optional(),
|
|
168
|
-
icon: z.enum(['brand-mark', 'chat', 'none']).optional(),
|
|
169
|
-
size: z.enum(['md', 'lg']).optional(),
|
|
170
|
-
status: z.enum(['none', 'session']).optional(),
|
|
171
|
-
effect: z.enum(['none', 'pulse']).optional(),
|
|
172
|
-
}),
|
|
173
|
-
header: optionalStrictObject({
|
|
174
|
-
mark: z.enum(['none', 'brand-mark', 'status']).optional(),
|
|
175
|
-
badge: optionalStrictObject({
|
|
176
|
-
text: z.string().trim().min(1).max(80),
|
|
177
|
-
tone: assistantPresentationToneSchema.optional(),
|
|
178
|
-
indicator: z.boolean().optional(),
|
|
179
|
-
}),
|
|
180
|
-
}),
|
|
181
|
-
composer: optionalStrictObject({
|
|
182
|
-
leadingIcon: z.enum(['none', 'brand-mark']).optional(),
|
|
183
|
-
sendIcon: z.enum(['arrow-up', 'paper-plane']).optional(),
|
|
184
|
-
shape: z.enum(['rounded', 'pill']).optional(),
|
|
185
|
-
}),
|
|
186
|
-
messages: optionalStrictObject({
|
|
187
|
-
userStyle: z.enum(['bubble', 'accent']).optional(),
|
|
188
|
-
assistantStyle: z.enum(['plain', 'bubble']).optional(),
|
|
189
|
-
}),
|
|
190
|
-
})
|
|
191
|
-
.strict();
|
|
192
|
-
const assistantUiSchema = z
|
|
193
|
-
.object({
|
|
194
|
-
theme: z.enum(['auto', 'light', 'dark', 'invert']).optional(),
|
|
195
|
-
layout: optionalStrictObject({
|
|
196
|
-
mode: z.enum(['floating', 'inline', 'drawer']).optional(),
|
|
197
|
-
position: z.enum(['bottom-left', 'bottom-center', 'bottom-right']).optional(),
|
|
198
|
-
panelWidth: z.number().int().min(280).max(1200).optional(),
|
|
199
|
-
panelMinHeight: z.number().int().min(240).max(1600).optional(),
|
|
200
|
-
panelMaxHeight: z.number().int().min(320).max(2400).optional(),
|
|
201
|
-
edgeOffset: z.number().int().min(0).max(96).optional(),
|
|
202
|
-
zIndex: z.number().int().min(0).max(2147483647).optional(),
|
|
203
|
-
density: z.enum(['compact', 'comfortable']).optional(),
|
|
204
|
-
mobileFullscreen: z.boolean().optional(),
|
|
205
|
-
}),
|
|
206
|
-
behavior: optionalStrictObject({
|
|
207
|
-
startOpen: z.boolean().optional(),
|
|
208
|
-
closeOnEscape: z.boolean().optional(),
|
|
209
|
-
closeOnOutsideClick: z.boolean().optional(),
|
|
210
|
-
showLauncher: z.boolean().optional(),
|
|
211
|
-
showHeader: z.boolean().optional(),
|
|
212
|
-
showAvatars: z.boolean().optional(),
|
|
213
|
-
showTimestamps: z.boolean().optional(),
|
|
214
|
-
showPoweredBy: z.boolean().optional(),
|
|
215
|
-
showConfirmationDetails: z.boolean().optional(),
|
|
216
|
-
}),
|
|
217
|
-
labels: optionalStrictObject({
|
|
218
|
-
welcomeHeading: z.string().trim().min(1).max(160).optional(),
|
|
219
|
-
welcomeMessage: z.string().max(1000).optional(),
|
|
220
|
-
launcherPlaceholder: z.string().trim().min(1).max(160).optional(),
|
|
221
|
-
composerPlaceholder: z.string().trim().min(1).max(160).optional(),
|
|
222
|
-
thinking: z.string().trim().min(1).max(80).optional(),
|
|
223
|
-
send: z.string().trim().min(1).max(80).optional(),
|
|
224
|
-
stop: z.string().trim().min(1).max(80).optional(),
|
|
225
|
-
close: z.string().trim().min(1).max(80).optional(),
|
|
226
|
-
open: z.string().trim().min(1).max(80).optional(),
|
|
227
|
-
confirm: z.string().trim().min(1).max(80).optional(),
|
|
228
|
-
decline: z.string().trim().min(1).max(80).optional(),
|
|
229
|
-
cancel: z.string().trim().min(1).max(80).optional(),
|
|
230
|
-
confirmationHeading: z.string().trim().min(1).max(120).optional(),
|
|
231
|
-
additionalDetails: z.string().trim().min(1).max(120).optional(),
|
|
232
|
-
redacted: z.string().trim().min(1).max(120).optional(),
|
|
233
|
-
completed: z.string().trim().min(1).max(80).optional(),
|
|
234
|
-
stopped: z.string().trim().min(1).max(80).optional(),
|
|
235
|
-
copy: z.string().trim().min(1).max(80).optional(),
|
|
236
|
-
newMessages: z.string().trim().min(1).max(80).optional(),
|
|
237
|
-
reconnect: z.string().trim().min(1).max(80).optional(),
|
|
238
|
-
newConversation: z.string().trim().min(1).max(80).optional(),
|
|
239
|
-
retry: z.string().trim().min(1).max(80).optional(),
|
|
240
|
-
unavailable: z.string().trim().min(1).max(240).optional(),
|
|
241
|
-
sessionExpired: z.string().trim().min(1).max(240).optional(),
|
|
242
|
-
sessionIdle: z.string().trim().min(1).max(120).optional(),
|
|
243
|
-
sessionLoading: z.string().trim().min(1).max(120).optional(),
|
|
244
|
-
sessionReady: z.string().trim().min(1).max(120).optional(),
|
|
245
|
-
sessionError: z.string().trim().min(1).max(120).optional(),
|
|
246
|
-
signInHeading: z.string().trim().min(1).max(120).optional(),
|
|
247
|
-
signInBody: z.string().max(240).optional(),
|
|
248
|
-
signInAction: z.string().trim().min(1).max(80).optional(),
|
|
249
|
-
signUpAction: z.string().trim().min(1).max(80).optional(),
|
|
250
|
-
}),
|
|
251
|
-
presentation: assistantPresentationSchema.optional(),
|
|
252
|
-
suggestedPrompts: z.array(z.string().trim().min(1).max(240)).max(8).optional(),
|
|
253
|
-
privacyUrl: httpsUrlSchema.optional(),
|
|
254
|
-
termsUrl: httpsUrlSchema.optional(),
|
|
255
|
-
locale: z.string().trim().min(2).max(35).optional(),
|
|
256
|
-
direction: z.enum(['ltr', 'rtl', 'auto']).optional(),
|
|
257
|
-
})
|
|
258
|
-
.strict();
|
|
259
157
|
const assistantCapabilitySchema = z
|
|
260
158
|
.object({
|
|
261
159
|
kind: z.enum(['tool', 'resource', 'prompt', 'knowledge']),
|
|
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { beginChannelProviderBlock, CHANNEL_RETENTION_MS, ChannelCoordinator, ChannelError, channelDigest, channelProviderBlocks, collectionSpecFor, finishChannelProviderBlock, messagingSurfaceOf, projectArtifactForSurface, resolveInvocationContextSnapshot, WHATSAPP_CONFIRMATION_EXPIRY_MS, withAssistantTurnExecutionAuthority, } from '@noodle-borg/assistant-gateway/portable';
|
|
3
3
|
import { guardedFetch } from '@noodle-borg/connector-http';
|
|
4
4
|
import { executePreparedTool, prepareToolForConfirmation } from '@noodle-borg/runtime';
|
|
5
|
-
import { messagingSurfaceHistory } from '../conversation-history/capture.js';
|
|
5
|
+
import { historyNoticeSentence, messagingSurfaceHistory } from '../conversation-history/capture.js';
|
|
6
6
|
import { runAgentTurn } from '../routes/assistant-agent.js';
|
|
7
7
|
import { resolveAssistantKnowledge } from '../routes/assistant-knowledge.js';
|
|
8
8
|
import { resolveAssistantModelBinding } from '../routes/assistant-model-binding.js';
|
|
@@ -444,11 +444,13 @@ export class WhatsAppRuntime {
|
|
|
444
444
|
});
|
|
445
445
|
if (failure || !text.trim())
|
|
446
446
|
throw new ChannelError(failure ?? 'answer_unavailable');
|
|
447
|
-
// WhatsApp has no footer, so a recorded channel states its window here (ADR 0241 decision 17)
|
|
447
|
+
// WhatsApp has no footer, so a recorded channel states its window here (ADR 0241 decision 17),
|
|
448
|
+
// in the author's `historyNotice` language when one is declared.
|
|
449
|
+
const surface = messagingSurfaceHistory(artifact.server.assistant);
|
|
448
450
|
const days = participant.history.length === 0
|
|
449
|
-
? ((await this.deps.conversations?.retentionDays(binding.tenant, 'whatsapp',
|
|
451
|
+
? ((await this.deps.conversations?.retentionDays(binding.tenant, 'whatsapp', surface)) ?? 0)
|
|
450
452
|
: 0;
|
|
451
|
-
const kept = days > 0 ? `
|
|
453
|
+
const kept = days > 0 ? ` ${historyNoticeSentence(days, surface.noticeTemplate)}` : '';
|
|
452
454
|
const disclosure = participant.history.length === 0
|
|
453
455
|
? `I’m ${artifact.server.branding?.name ?? artifact.server.title}’s AI assistant.${kept}\n\n`
|
|
454
456
|
: '';
|
|
@@ -25,10 +25,31 @@ export function websiteSurfaceHistory(assistant, binding) {
|
|
|
25
25
|
: binding === 'authenticated'
|
|
26
26
|
? authenticatedSurfaceOf(assistant)
|
|
27
27
|
: undefined;
|
|
28
|
-
return { historyDisabled: surface?.history === false };
|
|
28
|
+
return { historyDisabled: surface?.history === false, ...noticeTemplateOf(assistant) };
|
|
29
29
|
}
|
|
30
30
|
export function messagingSurfaceHistory(assistant) {
|
|
31
|
-
return {
|
|
31
|
+
return {
|
|
32
|
+
historyDisabled: messagingSurfaceOf(assistant)?.history === false,
|
|
33
|
+
...noticeTemplateOf(assistant),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** The compiler admits only a bounded template naming `{days}`; anything else states the default. */
|
|
37
|
+
function noticeTemplateOf(assistant) {
|
|
38
|
+
const template = assistant?.historyNotice;
|
|
39
|
+
return typeof template === 'string' && template.includes('{days}')
|
|
40
|
+
? { noticeTemplate: template }
|
|
41
|
+
: {};
|
|
42
|
+
}
|
|
43
|
+
/** The retention notice in the author's language, else the English default (ADR 0241 decision 17). */
|
|
44
|
+
export function historyNoticeText(days, template) {
|
|
45
|
+
return template
|
|
46
|
+
? template.replaceAll('{days}', String(days))
|
|
47
|
+
: `Chats are kept for ${days} ${days === 1 ? 'day' : 'days'}`;
|
|
48
|
+
}
|
|
49
|
+
/** The same notice as a sentence, for channels without a footer to state it in. */
|
|
50
|
+
export function historyNoticeSentence(days, template) {
|
|
51
|
+
const text = historyNoticeText(days, template);
|
|
52
|
+
return /[.!?。!?]$/u.test(text) ? text : `${text}.`;
|
|
32
53
|
}
|
|
33
54
|
/**
|
|
34
55
|
* Records what the customer saw beside each existing working-memory write. Capture is best-effort by
|
|
@@ -150,6 +171,10 @@ function sessionConversationId(sessionId) {
|
|
|
150
171
|
/** The additive session-response notice (ADR 0241 decision 17); empty for an unrecorded caller. */
|
|
151
172
|
export async function sessionHistoryNotice(conversations, tenant, source, surface) {
|
|
152
173
|
const retentionDays = (await conversations?.retentionDays(tenant, source, surface)) ?? 0;
|
|
153
|
-
|
|
174
|
+
if (retentionDays <= 0)
|
|
175
|
+
return {};
|
|
176
|
+
// Only an authored template is sent: absent, every widget already states its English default.
|
|
177
|
+
const notice = surface.noticeTemplate && historyNoticeText(retentionDays, surface.noticeTemplate);
|
|
178
|
+
return { history: { retentionDays, ...(notice ? { notice } : {}) } };
|
|
154
179
|
}
|
|
155
180
|
//# sourceMappingURL=capture.js.map
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"@noodle-borg/managed-capabilities": "0.0.0",
|
|
42
42
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
43
43
|
"@noodle-borg/admission-limits": "0.0.0",
|
|
44
|
-
"@noodle-borg/agent-kit": "0.
|
|
44
|
+
"@noodle-borg/agent-kit": "0.109.0",
|
|
45
45
|
"@noodle-borg/app-package": "0.0.0",
|
|
46
46
|
"@noodle-borg/assistant-gateway": "0.0.0",
|
|
47
47
|
"@noodle-borg/auth": "0.0.0",
|
|
@@ -33,6 +33,7 @@ export declare const assistantSessionResponseSchema: z.ZodObject<{
|
|
|
33
33
|
continuedAfterAuthentication: z.ZodOptional<z.ZodLiteral<true>>;
|
|
34
34
|
history: z.ZodOptional<z.ZodObject<{
|
|
35
35
|
retentionDays: z.ZodNumber;
|
|
36
|
+
notice: z.ZodOptional<z.ZodString>;
|
|
36
37
|
}, z.core.$strip>>;
|
|
37
38
|
}, z.core.$strip>;
|
|
38
39
|
export type AssistantSessionResponse = z.infer<typeof assistantSessionResponseSchema>;
|
|
@@ -65,8 +65,15 @@ export const assistantSessionResponseSchema = z.object({
|
|
|
65
65
|
* Additive retention notice (ADR 0241 decision 17): present only when this caller's conversation
|
|
66
66
|
* is recorded. Top level, never inside `configuration`, whose strict browser schema would make an
|
|
67
67
|
* older widget drop its whole appearance; older widgets ignore unknown top-level keys.
|
|
68
|
+
* `notice` is the author's localized `historyNotice` with `{days}` filled in; absent, the widget
|
|
69
|
+
* states its English default, and older widgets ignore it.
|
|
68
70
|
*/
|
|
69
|
-
history: z
|
|
71
|
+
history: z
|
|
72
|
+
.object({
|
|
73
|
+
retentionDays: z.number().int().min(1).max(365),
|
|
74
|
+
notice: z.string().min(1).max(160).optional(),
|
|
75
|
+
})
|
|
76
|
+
.optional(),
|
|
70
77
|
});
|
|
71
78
|
const recoverableViewSchema = z
|
|
72
79
|
.object({
|
|
@@ -645,6 +645,12 @@ await forgetUser({ ...credentials, user: { id: account.id } });
|
|
|
645
645
|
`forgetUser` erases stored conversation history only; a live session's short-lived working memory is not
|
|
646
646
|
touched and expires within two hours. Failures throw `AssistantConversationsError` with a typed `detail` (`status`, `retryable`, `serviceCode`).
|
|
647
647
|
|
|
648
|
+
A recorded session also carries `history: { retentionDays, notice? }`, and the widget footer states it:
|
|
649
|
+
"Chats are kept for 30 days" by default, or your own language when `server.ts` declares
|
|
650
|
+
`embeddedAssistant({ historyNotice: 'Los chats se guardan {days} días', ... })` (`{days}` is required; the
|
|
651
|
+
WhatsApp first reply uses the same text). A custom renderer shows `history.notice` from `session_started`,
|
|
652
|
+
else that English line.
|
|
653
|
+
|
|
648
654
|
The MCP server's top-level `branding` block is the portable deployment source for identity and colors shared
|
|
649
655
|
by widgets and the assistant. The embedding application may use the typed `appearance` object when it needs
|
|
650
656
|
exact control over assistant-specific roles:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noodleseed/assistant",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.38.0",
|
|
4
4
|
"description": "Embed the Noodle Seed customer-branded assistant in your web app with managed or framework-owned UI, a framework-neutral MCP App host, a DOM-free client, and a backend session helper. Authoring and deploying the server is @noodleseed/one.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noodleseed/one",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.183.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Noodle CLI by Noodle Seed — author, run, and deploy declarative MCP servers. Embedding the assistant in your own web app is @noodleseed/assistant.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -236,7 +236,7 @@
|
|
|
236
236
|
"@modelcontextprotocol/client": "2.0.0",
|
|
237
237
|
"@modelcontextprotocol/server": "2.0.0",
|
|
238
238
|
"@noodle-borg/admission-limits": "0.0.0",
|
|
239
|
-
"@noodle-borg/agent-kit": "0.
|
|
239
|
+
"@noodle-borg/agent-kit": "0.109.0",
|
|
240
240
|
"@noodle-borg/app-audit": "0.0.0",
|
|
241
241
|
"@noodle-borg/app-package": "0.0.0",
|
|
242
242
|
"@noodle-borg/assistant-gateway": "0.0.0",
|
|
@@ -285,7 +285,7 @@
|
|
|
285
285
|
"zod-to-json-schema": "3.25.2"
|
|
286
286
|
},
|
|
287
287
|
"devDependencies": {
|
|
288
|
-
"@noodleseed/assistant": "@noodleseed/assistant@file:///home/runner/
|
|
288
|
+
"@noodleseed/assistant": "@noodleseed/assistant@file:///home/runner/_work/noodle-borg/noodle-borg/packages/assistant",
|
|
289
289
|
"@types/node": "24.13.1",
|
|
290
290
|
"next": "16.2.9"
|
|
291
291
|
},
|