@tangle-network/agent-app 0.60.249 → 0.60.251
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/dist/DesignCanvas-L6J72JQ2.js +15 -0
- package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
- package/dist/agent-enrollment/drizzle.js +3 -3
- package/dist/agent-enrollment/index.js +3 -3
- package/dist/app-auth/drizzle.d.ts +561 -0
- package/dist/app-auth/drizzle.js +72 -0
- package/dist/app-auth/drizzle.js.map +1 -0
- package/dist/app-auth/index.js +5 -3
- package/dist/app-auth/index.js.map +1 -1
- package/dist/app-oauth/drizzle.d.ts +2080 -0
- package/dist/app-oauth/drizzle.js +161 -0
- package/dist/app-oauth/drizzle.js.map +1 -0
- package/dist/app-oauth/index.d.ts +4 -0
- package/dist/app-oauth/index.js +8 -222
- package/dist/app-oauth/index.js.map +1 -1
- package/dist/app-oauth/issuer.d.ts +133 -0
- package/dist/app-oauth/issuer.js +247 -0
- package/dist/app-oauth/issuer.js.map +1 -0
- package/dist/assistant/index.js +13 -13
- package/dist/chat-react/index.js +4 -4
- package/dist/chat-routes/dispatch-first.d.ts +43 -0
- package/dist/chat-routes/index.js +37 -67
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/promote-file-part.d.ts +2 -3
- package/dist/chat-routes/turn-execution.d.ts +3 -1
- package/dist/chat-routes/turn-route-contracts.d.ts +31 -0
- package/dist/chat-store/index.js +4 -4
- package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
- package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
- package/dist/chunk-4GCPADYG.js.map +1 -0
- package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
- package/dist/chunk-57XPEL7X.js +26 -0
- package/dist/chunk-57XPEL7X.js.map +1 -0
- package/dist/chunk-6Z7TZVKZ.js +26 -0
- package/dist/chunk-6Z7TZVKZ.js.map +1 -0
- package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
- package/dist/chunk-AWIQQEFP.js.map +1 -0
- package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
- package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
- package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
- package/dist/chunk-CQGEGPY7.js.map +1 -0
- package/dist/chunk-CTREXL3O.js +335 -0
- package/dist/chunk-CTREXL3O.js.map +1 -0
- package/dist/chunk-DLWO3J7D.js +238 -0
- package/dist/chunk-DLWO3J7D.js.map +1 -0
- package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
- package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
- package/dist/{chunk-BDCC6UVW.js → chunk-EFPIHR6F.js} +161 -40
- package/dist/chunk-EFPIHR6F.js.map +1 -0
- package/dist/chunk-FRAICFTZ.js +191 -0
- package/dist/chunk-FRAICFTZ.js.map +1 -0
- package/dist/chunk-GS7VWV26.js +61 -0
- package/dist/chunk-GS7VWV26.js.map +1 -0
- package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
- package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
- package/dist/chunk-HY57QRRW.js +11 -0
- package/dist/chunk-HY57QRRW.js.map +1 -0
- package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
- package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
- package/dist/chunk-LSBI5MWS.js +66 -0
- package/dist/chunk-LSBI5MWS.js.map +1 -0
- package/dist/chunk-MDRH3SDA.js +106 -0
- package/dist/chunk-MDRH3SDA.js.map +1 -0
- package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
- package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
- package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
- package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
- package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
- package/dist/chunk-SFZELD6V.js +52 -0
- package/dist/chunk-SFZELD6V.js.map +1 -0
- package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
- package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
- package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
- package/dist/chunk-WL7PZK7Q.js.map +1 -0
- package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
- package/dist/chunk-WP2GYFZ4.js.map +1 -0
- package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
- package/dist/crypto/digest.d.ts +2 -0
- package/dist/crypto/index.d.ts +1 -0
- package/dist/crypto/index.js +6 -2
- package/dist/design-canvas/index.js +5 -3
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +7 -5
- package/dist/design-canvas-react/index.js +14 -12
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/index.d.ts +4 -0
- package/dist/eval/index.js +125 -0
- package/dist/eval/index.js.map +1 -1
- package/dist/eval/persona-driver.d.ts +37 -0
- package/dist/eval/research-plan.d.ts +25 -0
- package/dist/eval/research-plan.js +55 -0
- package/dist/eval/research-plan.js.map +1 -0
- package/dist/eval/scorecard.d.ts +38 -0
- package/dist/forms/blank.d.ts +2 -2
- package/dist/forms/index.js +4 -5
- package/dist/forms/index.js.map +1 -1
- package/dist/hosted-agent/application.js +2 -2
- package/dist/interactions/index.js +3 -3
- package/dist/knowledge/prelaunch-audit.d.ts +17 -0
- package/dist/knowledge/prelaunch-audit.js +67 -0
- package/dist/knowledge/prelaunch-audit.js.map +1 -0
- package/dist/media/drizzle.d.ts +207 -0
- package/dist/media/drizzle.js +26 -0
- package/dist/media/drizzle.js.map +1 -0
- package/dist/media/generate-request.d.ts +53 -0
- package/dist/media/generation-record.d.ts +68 -0
- package/dist/media/index.d.ts +13 -0
- package/dist/media/index.js +653 -0
- package/dist/media/index.js.map +1 -0
- package/dist/media/model-catalog.d.ts +109 -0
- package/dist/media/router-client.d.ts +40 -0
- package/dist/media/router-generation.d.ts +44 -0
- package/dist/media/speech-script.d.ts +20 -0
- package/dist/openui/index.js +1 -1
- package/dist/operator/index.js +4 -5
- package/dist/operator/index.js.map +1 -1
- package/dist/plans/decision.d.ts +48 -0
- package/dist/plans/drizzle.d.ts +25 -0
- package/dist/plans/drizzle.js +97 -0
- package/dist/plans/drizzle.js.map +1 -0
- package/dist/plans/index.d.ts +1 -1
- package/dist/plans/index.js +11 -3
- package/dist/platform/billing-config.d.ts +22 -0
- package/dist/platform/billing-config.js +36 -0
- package/dist/platform/billing-config.js.map +1 -0
- package/dist/platform/index.js +13 -11
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +2 -1
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/profile/index.js +4 -5
- package/dist/profile/index.js.map +1 -1
- package/dist/public-consultation/index.js +13 -11
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/telemetry-cap.d.ts +24 -0
- package/dist/runtime/telemetry-cap.js +36 -0
- package/dist/runtime/telemetry-cap.js.map +1 -0
- package/dist/sandbox/index.js +12 -9
- package/dist/sequences/index.js +4 -2
- package/dist/sequences/index.js.map +1 -1
- package/dist/skills-placement/box.d.ts +50 -0
- package/dist/skills-placement/box.js +204 -0
- package/dist/skills-placement/box.js.map +1 -0
- package/dist/skills-placement/index.js +8 -96
- package/dist/skills-placement/index.js.map +1 -1
- package/dist/spend/budget.d.ts +13 -0
- package/dist/spend/drizzle.d.ts +55 -0
- package/dist/spend/drizzle.js +131 -0
- package/dist/spend/drizzle.js.map +1 -0
- package/dist/spend/index.d.ts +2 -1
- package/dist/spend/index.js +77 -58
- package/dist/spend/index.js.map +1 -1
- package/dist/spend/platform-settlements.d.ts +46 -0
- package/dist/stream/index.js +19 -19
- package/dist/studio/generated-media/index.d.ts +6 -0
- package/dist/studio/generated-media/index.js +590 -0
- package/dist/studio/generated-media/index.js.map +1 -0
- package/dist/studio/generated-media/output.d.ts +27 -0
- package/dist/studio/generated-media/store.d.ts +175 -0
- package/dist/studio-react/download-generations.d.ts +7 -0
- package/dist/studio-react/index.d.ts +1 -0
- package/dist/studio-react/index.js +85 -0
- package/dist/studio-react/index.js.map +1 -1
- package/dist/studio-react/use-studio-route.d.ts +44 -0
- package/dist/teams/invitations-api.d.ts +4 -0
- package/dist/teams/invitations-api.js +44 -32
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/theme/dom.d.ts +22 -0
- package/dist/theme/dom.js +18 -0
- package/dist/theme/dom.js.map +1 -0
- package/dist/vault/collaboration.d.ts +83 -0
- package/dist/vault/collaboration.js +215 -0
- package/dist/vault/collaboration.js.map +1 -0
- package/dist/vault/server.js +6 -53
- package/dist/vault/server.js.map +1 -1
- package/dist/vault/store/coordinator.d.ts +64 -0
- package/dist/vault/store/index.d.ts +12 -0
- package/dist/vault/store/index.js +1202 -0
- package/dist/vault/store/index.js.map +1 -0
- package/dist/vault/store/paths.d.ts +65 -0
- package/dist/vault/store/revisions.d.ts +211 -0
- package/dist/vault/store/sandbox-sync.d.ts +74 -0
- package/dist/vault/store/store.d.ts +161 -0
- package/dist/vault/store/tree.d.ts +11 -0
- package/dist/web/entry-server.d.ts +7 -0
- package/dist/web/entry-server.js +29 -0
- package/dist/web/entry-server.js.map +1 -0
- package/dist/web/fetch-guard.d.ts +6 -0
- package/dist/web/index.d.ts +3 -0
- package/dist/web/index.js +20 -4
- package/dist/web/mime.d.ts +16 -0
- package/dist/web/rate-limit.d.ts +25 -0
- package/dist/web/timeout.d.ts +9 -0
- package/dist/web-react/agent-profile-editor.js +3 -3
- package/dist/web-react/api-access-panel.d.ts +4 -2
- package/dist/web-react/document.d.ts +41 -0
- package/dist/web-react/document.js +103 -0
- package/dist/web-react/document.js.map +1 -0
- package/dist/web-react/index.js +31 -31
- package/dist/workspace-react/index.js +5 -5
- package/package.json +95 -4
- package/dist/DesignCanvas-OW3W2QXW.js +0 -13
- package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
- package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
- package/dist/chunk-7HZCFG2A.js.map +0 -1
- package/dist/chunk-7KKOFMLD.js.map +0 -1
- package/dist/chunk-BDCC6UVW.js.map +0 -1
- package/dist/chunk-FENBDSIW.js.map +0 -1
- package/dist/chunk-LQYIBL3G.js.map +0 -1
- /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
- /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
- /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
- /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
- /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
- /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
- /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
- /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
- /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
- /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
- /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
- /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
- /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
- /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
- /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/design-canvas-react/components/CanvasInsertPanel.tsx","../../src/design-canvas-react/components/LayersPanel.tsx","../../src/design-canvas-react/components/layer-tree.ts"],"sourcesContent":["/**\n * The human \"add element to the canvas\" side panel — a reusable left rail any\n * canvas consumer can mount so a person (not just the agent) can put images,\n * shapes, and text on the canvas. Designed for the `renderSidePanel` slot of\n * {@link DesignCanvasProps}; pass `renderSidePanel={(ctx) => <CanvasInsertPanel … />}`.\n *\n * Endpoints are per-app, so every I/O path is a callback — no product route is\n * hardcoded:\n * - `onUploadImage(file) => Promise<url>` — optional. When provided, the host\n * stores the file and returns the src to insert. The url MUST be http(s) or\n * a rooted `/api/` path (enforced by `assertSceneMediaSrc` before insertion);\n * a `data:` url is rejected, matching the scene model's media boundary.\n * - `loadGenerations?()` — optional provider for \"already generated in this\n * workspace\" images; omit to hide the tab.\n * - `templates?` — optional template set; defaults to {@link DEFAULT_INSERT_TEMPLATES}.\n * A host-passed (composed) set labels its tab \"Templates\"; the built-in\n * primitives label it \"Elements\".\n *\n * Insertion goes through `onInsert`, which the host wires to its\n * `onApplyOperations` pipeline (server-validated, undoable) — the same path\n * every other edit takes.\n *\n * Tokens/icons follow the canvas convention: CSS-var design tokens and inline\n * SVG glyphs, no icon-library or Tailwind-semantic-token dependency.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { SceneOperation } from '../../design-canvas/operations'\nimport { assertSceneMediaSrc } from '../../design-canvas/model'\nimport {\n DEFAULT_INSERT_TEMPLATES,\n buildInsertImageOp,\n type InsertPageGeometry,\n type InsertTemplate,\n} from '../insert-builders'\nimport { ImageGlyph, ShapesGlyph } from './glyphs'\n\n/** An already-generated image the panel can offer for one-click insertion. */\nexport interface InsertGeneration {\n id: string\n /** The image url to insert. Must satisfy the scene media boundary\n * (http(s) or rooted `/api/`); rejected otherwise at insert time. */\n url: string\n /** Optional prompt/label shown as the tile's title. */\n label?: string\n}\n\nexport interface CanvasInsertPanelProps {\n canWrite: boolean\n /** The active page new elements are added to. */\n page: InsertPageGeometry\n /** Submit operations through the host's apply pipeline. */\n onInsert(operations: SceneOperation[]): Promise<unknown>\n /** Store an uploaded file and return its src (http(s) or rooted `/api/`). */\n onUploadImage?(file: File): Promise<string>\n /** Optional provider for the Generations tab; omit to hide it. */\n loadGenerations?(): Promise<InsertGeneration[]>\n /** Drop-in templates; defaults to the built-in starter set. */\n templates?: readonly InsertTemplate[]\n /** Accepted upload mime types. Default: PNG/JPEG/GIF/WebP. */\n accept?: string\n className?: string\n}\n\ntype Tab = 'uploads' | 'templates' | 'generations'\n\nconst DEFAULT_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp'\n\n/** Read an image url's natural dimensions in the browser; resolves `{0,0}` when\n * Image is unavailable (SSR/tests), the load fails, or the probe times out —\n * builders fall back to the size cap, so a failed probe still inserts a sensibly\n * sized element rather than blocking insertion. */\nconst PROBE_TIMEOUT_MS = 4000\n\nfunction probeImageSize(url: string): Promise<{ width: number; height: number }> {\n return new Promise((resolve) => {\n if (typeof Image === 'undefined') return resolve({ width: 0, height: 0 })\n let settled = false\n const finish = (size: { width: number; height: number }) => {\n if (settled) return\n settled = true\n resolve(size)\n }\n const img = new Image()\n img.onload = () => finish({ width: img.naturalWidth, height: img.naturalHeight })\n img.onerror = () => finish({ width: 0, height: 0 })\n // A URL that never loads (or an environment that never fires load/error)\n // must not hang the insert forever.\n setTimeout(() => finish({ width: 0, height: 0 }), PROBE_TIMEOUT_MS)\n img.src = url\n })\n}\n\nfunction UploadGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 9l5-5 5 5M12 4v12\" />\n </svg>\n )\n}\n\nfunction SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\nfunction SpinnerGlyph({ className }: { className?: string }) {\n return (\n <svg className={`${className ?? ''} animate-spin`} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-6.2-8.6\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\n/** Probe-page geometry for deriving a template's primary element kind. The\n * result drives only the tile preview, so the exact dimensions don't matter. */\nconst PREVIEW_PROBE_PAGE: InsertPageGeometry = { pageId: 'preview', width: 1000, height: 1000 }\n\n/** The visual a template tile shows. Derived from the first element the\n * template's (pure) `build` produces, so custom templates render correctly\n * too — not just the built-in set. */\ntype TemplateShape = 'heading' | 'body' | 'rect' | 'ellipse' | 'other'\n\n/** A text element is treated as a heading (shown as \"T\") when it reads as a\n * title — bold or set in a large face; otherwise body copy (shown as \"¶\"). */\nconst HEADING_FONT_SIZE = 32\n\nfunction templateShape(tpl: InsertTemplate): TemplateShape {\n try {\n const ops = tpl.build(PREVIEW_PROBE_PAGE)\n const added = ops.find((op) => op.type === 'add_element')\n if (!added || added.type !== 'add_element') return 'other'\n const el = added.element\n if (el.kind === 'rect') return 'rect'\n if (el.kind === 'ellipse') return 'ellipse'\n if (el.kind === 'text') {\n const isHeading = el.fontStyle.includes('bold') || el.fontSize >= HEADING_FONT_SIZE\n return isHeading ? 'heading' : 'body'\n }\n return 'other'\n } catch {\n // A throwing build can't preview; fall through to the neutral shape glyph.\n return 'other'\n }\n}\n\n/** A small visual standing in for what the template inserts, so tiles are\n * distinguishable at a glance instead of four identical text chips. */\nfunction TemplatePreview({ shape }: { shape: TemplateShape }) {\n if (shape === 'rect') {\n return <span className=\"block h-6 w-9 rounded-sm bg-[var(--brand-primary)]\" aria-hidden />\n }\n if (shape === 'ellipse') {\n return <span className=\"block h-7 w-7 rounded-full bg-[var(--brand-primary)]\" aria-hidden />\n }\n // Text tiles show a glyph: a semibold \"T\" for a heading, a paragraph mark\n // \"¶\" for body copy.\n if (shape === 'heading' || shape === 'body') {\n return (\n <span\n className={`block leading-none text-[var(--text-primary)] ${\n shape === 'heading' ? 'text-2xl font-semibold' : 'text-lg'\n }`}\n aria-hidden\n >\n {shape === 'heading' ? 'T' : '¶'}\n </span>\n )\n }\n return <ShapesGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n}\n\nexport function CanvasInsertPanel({\n canWrite,\n page,\n onInsert,\n onUploadImage,\n loadGenerations,\n templates,\n accept = DEFAULT_ACCEPT,\n className,\n}: CanvasInsertPanelProps) {\n // Host-passed templates are composed page sections (\"Templates\"); the\n // built-in set is single primitives, so its tab reads \"Elements\".\n const resolvedTemplates = templates ?? DEFAULT_INSERT_TEMPLATES\n const templatesLabel = templates !== undefined ? 'Templates' : 'Elements'\n const [tab, setTab] = useState<Tab>(() => (resolvedTemplates.length > 0 ? 'templates' : 'uploads'))\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n const [dragOver, setDragOver] = useState(false)\n const [generations, setGenerations] = useState<InsertGeneration[]>([])\n const [generationsLoaded, setGenerationsLoaded] = useState(false)\n const fileInputRef = useRef<HTMLInputElement | null>(null)\n\n useEffect(() => {\n if (tab === 'uploads' && !onUploadImage) {\n setTab(resolvedTemplates.length > 0 ? 'templates' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'templates' && resolvedTemplates.length === 0) {\n setTab(onUploadImage ? 'uploads' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'generations' && !loadGenerations) {\n setTab(resolvedTemplates.length > 0 ? 'templates' : onUploadImage ? 'uploads' : 'templates')\n }\n }, [tab, resolvedTemplates.length, onUploadImage, loadGenerations])\n\n useEffect(() => {\n if (tab !== 'generations' || generationsLoaded || !loadGenerations) return\n let cancelled = false\n void (async () => {\n try {\n const rows = await loadGenerations()\n if (!cancelled) setGenerations(rows.filter((g) => g.url))\n } catch (err) {\n if (!cancelled) setError(err instanceof Error ? err.message : 'Could not load generations')\n } finally {\n if (!cancelled) setGenerationsLoaded(true)\n }\n })()\n return () => {\n cancelled = true\n }\n }, [tab, generationsLoaded, loadGenerations])\n\n async function insertImageFromUrl(url: string) {\n // Validate the media boundary BEFORE probing — a data: or sandbox-local url\n // throws here (surfaced as an inline error) without a wasted image load.\n assertSceneMediaSrc(url, 'image src')\n const natural = await probeImageSize(url)\n await onInsert([buildInsertImageOp(url, natural, page)])\n }\n\n async function handleFiles(files: FileList | File[]) {\n if (!canWrite || busy) return\n if (!onUploadImage) return\n const list = Array.from(files).filter((f) => f.type.startsWith('image/'))\n if (list.length === 0) {\n setError('Only image files can be added to the canvas')\n return\n }\n setBusy(true)\n setError('')\n try {\n for (const file of list) {\n const url = await onUploadImage(file)\n await insertImageFromUrl(url)\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Upload failed')\n } finally {\n setBusy(false)\n }\n }\n\n async function runInsert(build: () => SceneOperation[] | Promise<SceneOperation[]>) {\n if (!canWrite || busy) return\n setBusy(true)\n setError('')\n try {\n await onInsert(await build())\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Insert failed')\n } finally {\n setBusy(false)\n }\n }\n\n const tabs: Array<{ id: Tab; label: string; icon: (p: { className?: string }) => ReactElement; show: boolean }> = [\n { id: 'uploads', label: 'Uploads', icon: ImageGlyph, show: !!onUploadImage },\n { id: 'templates', label: templatesLabel, icon: ShapesGlyph, show: resolvedTemplates.length > 0 },\n { id: 'generations', label: 'Generations', icon: SparkleGlyph, show: !!loadGenerations },\n ]\n const visibleTabs = tabs.filter((t) => t.show)\n\n return (\n <div className={`flex h-full min-h-0 flex-col bg-[var(--bg-input)] text-[var(--text-primary)] ${className ?? ''}`}>\n <div className=\"flex shrink-0 border-b border-[var(--border-default)]\">\n {visibleTabs.map(({ id, label, icon: Icon }) => (\n <button\n key={id}\n type=\"button\"\n onClick={() => setTab(id)}\n // These tabs sit flush against the top and side edges of a panel\n // that clips its overflow, so the floor's outward ring is cut off on\n // three sides and reads as a stray underline. The negative offset\n // draws the same ring inside the tab; width and colour still come\n // from the tokens.\n className={`flex flex-1 items-center justify-center gap-1.5 px-2 py-2.5 text-xs font-medium transition-colors focus-visible:[outline-offset:-2px] ${\n tab === id\n ? 'border-b-2 border-[var(--brand-primary)] text-[var(--text-primary)]'\n : 'text-[var(--text-muted)] hover:text-[var(--text-primary)]'\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n {label}\n </button>\n ))}\n </div>\n\n {!canWrite ? (\n <div className=\"flex flex-1 items-center justify-center p-4 text-center text-sm text-[var(--text-muted)]\">\n You have view-only access to this design.\n </div>\n ) : (\n <div className=\"min-h-0 flex-1 overflow-y-auto p-3\">\n {tab === 'uploads' && (\n <div className=\"flex flex-col gap-3\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault()\n setDragOver(true)\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e) => {\n e.preventDefault()\n setDragOver(false)\n if (e.dataTransfer?.files?.length) void handleFiles(e.dataTransfer.files)\n }}\n className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-4 py-8 text-center transition-colors disabled:opacity-50 ${\n dragOver\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_5%,transparent)]'\n : 'border-[var(--border-default)] hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)]'\n }`}\n >\n {busy ? (\n <SpinnerGlyph className=\"h-6 w-6 text-[var(--brand-primary)]\" />\n ) : (\n <UploadGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n )}\n <span className=\"text-sm font-medium text-[var(--text-primary)]\">\n {busy ? 'Uploading…' : 'Drop an image or click to upload'}\n </span>\n <span className=\"text-xs text-[var(--text-muted)]\">PNG, JPEG, GIF, or WebP</span>\n </button>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={accept}\n multiple\n className=\"hidden\"\n onChange={(e) => {\n if (e.target.files?.length) void handleFiles(e.target.files)\n e.target.value = ''\n }}\n />\n </div>\n )}\n\n {tab === 'templates' && (\n <div className=\"grid grid-cols-2 gap-2\">\n {resolvedTemplates.map((tpl) => (\n <button\n key={tpl.id}\n type=\"button\"\n disabled={busy}\n onClick={() => void runInsert(() => tpl.build(page))}\n className=\"flex h-20 flex-col items-center justify-center gap-1.5 rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] text-xs font-medium text-[var(--text-primary)] transition-colors hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)] disabled:opacity-50\"\n >\n <span className=\"flex h-7 items-center justify-center\">\n <TemplatePreview shape={templateShape(tpl)} />\n </span>\n <span>{tpl.label}</span>\n </button>\n ))}\n </div>\n )}\n\n {tab === 'generations' && (\n <div className=\"flex flex-col gap-2\">\n {!generationsLoaded ? (\n <div className=\"flex items-center justify-center py-8 text-[var(--text-muted)]\">\n <SpinnerGlyph className=\"h-5 w-5\" />\n </div>\n ) : generations.length === 0 ? (\n <p className=\"px-1 py-6 text-center text-sm text-[var(--text-muted)]\">\n No generated images yet. Ask the agent to generate one.\n </p>\n ) : (\n <div className=\"grid grid-cols-2 gap-2\">\n {generations.map((gen) => (\n <button\n key={gen.id}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n if (busy || !canWrite) return\n setBusy(true)\n setError('')\n insertImageFromUrl(gen.url)\n .catch((err) => setError(err instanceof Error ? err.message : 'Insert failed'))\n .finally(() => setBusy(false))\n }}\n title={gen.label}\n className=\"group relative aspect-square overflow-hidden rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] transition-colors hover:border-[var(--brand-primary)] disabled:opacity-50\"\n >\n {/* eslint-disable-next-line jsx-a11y/img-redundant-alt */}\n <img src={gen.url} alt={gen.label || 'Generated image'} className=\"h-full w-full object-cover\" />\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n\n {error ? <p className=\"mt-3 text-xs leading-5 text-[var(--text-danger,#dc2626)]\">{error}</p> : null}\n </div>\n )}\n </div>\n )\n}\n","/**\n * Layers panel — reverse-z list of the active page's elements. Highest z-index\n * is at the top. Groups show their children indented beneath them. Clicking\n * selects an element; meta-click adds to selection. Double-clicking the name\n * opens an inline rename input. Eye and lock icons toggle visibility/locked.\n * Rows can be drag-reordered within the list (siblings only; cross-group reorder\n * is a pending integrator concern). Capped at LAYERS_PANEL_ROW_LIMIT rows.\n */\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\nimport { flattenLayerTree, LAYERS_PANEL_ROW_LIMIT } from './layer-tree'\nimport {\n EllipseGlyph,\n EyeGlyph,\n EyeOffGlyph,\n GroupGlyph,\n ImageGlyph,\n LineGlyph,\n LockGlyph,\n RectGlyph,\n SlotGlyph,\n TextGlyph,\n UnlockGlyph,\n VideoGlyph,\n} from './glyphs'\nimport type { SceneElementKind } from '../../design-canvas/model'\n\nfunction KindIcon({ kind, className }: { kind: SceneElementKind; className?: string }) {\n switch (kind) {\n case 'rect': return <RectGlyph className={className} />\n case 'ellipse': return <EllipseGlyph className={className} />\n case 'line': return <LineGlyph className={className} />\n case 'text': return <TextGlyph className={className} />\n case 'image': return <ImageGlyph className={className} />\n case 'video': return <VideoGlyph className={className} />\n case 'group': return <GroupGlyph className={className} />\n }\n}\n\nexport interface LayersPanelProps {\n page: ScenePage\n selectedElementIds: string[]\n canWrite: boolean\n /** Emit a set_attrs command for the given element. */\n onSetAttrs(elementId: string, attrs: Partial<Pick<SceneElement, 'name' | 'visible' | 'locked'>>): void\n /** Emit a reorder_element command. */\n onReorder(elementId: string, toIndex: number): void\n onSelect(elementId: string, additive: boolean): void\n}\n\nconst INDENT_PX = 16\n\nexport function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder, onSelect }: LayersPanelProps) {\n const rows = useMemo(() => flattenLayerTree(page), [page])\n const [renamingId, setRenamingId] = useState<string | null>(null)\n const [renameValue, setRenameValue] = useState('')\n\n // Drag-reorder state: we track the dragged row's ownerIndex and the target\n // index within the SAME owner. Cross-owner reorder is not supported here.\n const dragRowRef = useRef<{ elementId: string; ownerIndex: number; ownerLength: number } | null>(null)\n const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)\n\n function startRename(element: SceneElement) {\n setRenamingId(element.id)\n setRenameValue(element.name)\n }\n\n function commitRename(elementId: string) {\n const name = renameValue.trim()\n if (name.length > 0) onSetAttrs(elementId, { name })\n setRenamingId(null)\n }\n\n const visible = rows.length > LAYERS_PANEL_ROW_LIMIT ? rows.slice(0, LAYERS_PANEL_ROW_LIMIT) : rows\n\n return (\n <div className=\"flex h-full flex-col overflow-hidden text-[var(--text-primary)]\">\n <div className=\"shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.05em] text-[var(--text-muted)]\">\n Layers\n </div>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {visible.length === 0 ? (\n <div className=\"px-3 py-2 text-xs text-[var(--text-muted)]\">No layers yet</div>\n ) : null}\n {visible.map((row) => {\n const { element } = row\n const isSelected = selectedElementIds.includes(element.id)\n const isRenaming = renamingId === element.id\n\n return (\n <div\n key={element.id}\n data-layer-row={element.id}\n draggable={canWrite}\n onDragStart={() => {\n dragRowRef.current = {\n elementId: element.id,\n ownerIndex: row.ownerIndex,\n ownerLength: row.ownerLength,\n }\n }}\n onDragOver={(event) => {\n if (!dragRowRef.current) return\n // Only allow reorder within the same owner (same parentGroupId + depth)\n event.preventDefault()\n setDragOverIndex(row.ownerIndex)\n }}\n onDragLeave={() => setDragOverIndex(null)}\n onDrop={() => {\n const drag = dragRowRef.current\n if (!drag) return\n if (drag.elementId !== element.id) {\n onReorder(drag.elementId, row.ownerIndex)\n }\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n onDragEnd={() => {\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n className={[\n 'group flex items-center gap-1.5 py-1 pr-2 text-sm transition-colors',\n isSelected ? 'bg-[color-mix(in_srgb,var(--brand-primary)_15%,transparent)] text-[var(--text-primary)]' : 'hover:bg-[hsl(var(--accent))] text-[var(--text-secondary)]',\n dragOverIndex === row.ownerIndex ? 'border-t border-[var(--brand-primary)]' : '',\n ].join(' ')}\n style={{ paddingLeft: 8 + row.depth * INDENT_PX }}\n >\n {isRenaming ? (\n <input\n autoFocus\n value={renameValue}\n onChange={(event) => setRenameValue(event.target.value)}\n onBlur={() => commitRename(element.id)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitRename(element.id)\n if (event.key === 'Escape') setRenamingId(null)\n event.stopPropagation()\n }}\n className=\"min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-sm text-[var(--text-primary)] focus:border-[var(--brand-primary)]\"\n />\n ) : (\n // Selection is a real button (sibling of the eye/lock buttons) so\n // the row is not an interactive control nesting interactive\n // controls (axe: nested-interactive).\n <button\n type=\"button\"\n onClick={(event) => onSelect(element.id, event.metaKey || event.ctrlKey)}\n onDoubleClick={() => {\n if (canWrite) startRename(element)\n }}\n title={element.name}\n className=\"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 bg-transparent text-left\"\n >\n <KindIcon kind={element.kind} className=\"h-3.5 w-3.5 shrink-0 opacity-60\" />\n {element.slot ? (\n <span title={`Bound to slot: ${element.slot}`} className=\"inline-flex shrink-0\">\n <SlotGlyph className=\"h-3 w-3 text-[var(--brand-primary)]\" />\n </span>\n ) : null}\n <span className=\"min-w-0 flex-1 truncate\">{element.name}</span>\n </button>\n )}\n\n {/* Visibility toggle */}\n <button\n type=\"button\"\n aria-label={element.visible ? 'Hide element' : 'Show element'}\n aria-pressed={!element.visible}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { visible: !element.visible })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.visible ? 'opacity-0' : 'opacity-100',\n ].join(' ')}\n >\n {element.visible\n ? <EyeGlyph className=\"h-3.5 w-3.5\" />\n : <EyeOffGlyph className=\"h-3.5 w-3.5 text-[var(--text-muted)]\" />}\n </button>\n\n {/* Lock toggle */}\n <button\n type=\"button\"\n aria-label={element.locked ? 'Unlock element' : 'Lock element'}\n aria-pressed={!!element.locked}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { locked: !element.locked })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.locked ? 'opacity-100' : 'opacity-0',\n ].join(' ')}\n >\n {element.locked\n ? <LockGlyph className=\"h-3.5 w-3.5 text-[var(--text-warning)]\" />\n : <UnlockGlyph className=\"h-3.5 w-3.5\" />}\n </button>\n </div>\n )\n })}\n\n {rows.length > LAYERS_PANEL_ROW_LIMIT ? (\n <div className=\"px-3 py-2 text-xs text-[var(--text-muted)]\">\n +{rows.length - LAYERS_PANEL_ROW_LIMIT} more elements — select a group to scope the list\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n","/**\n * Pure layer-tree helpers: flatten a page's element array into an ordered list\n * for the LayersPanel, preserving group nesting. Extracted so render order,\n * depth, and selection math can be unit-tested independently of React.\n */\n\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\n\n/** Describe a layer row with its element, depth, grouping, ownership, and parent group details */\nexport interface LayerRow {\n element: SceneElement\n depth: number\n /** True when this row is a group whose children follow it in the list. */\n isGroup: boolean\n /** Index within its owner (page.elements or group.children). */\n ownerIndex: number\n /** Length of the owner array — needed for z-order bound math. */\n ownerLength: number\n /** Id of the containing group, or null for page-root elements. */\n parentGroupId: string | null\n}\n\n/**\n * Flatten `page.elements` into display order for the layers panel.\n *\n * Z-order is bottom→top in the element array; the layers panel shows\n * top→bottom (highest z-index first). A group row precedes its children\n * (the group is \"above\" its children in the panel, reflecting that the group\n * node itself paints last in Konva when empty; children paint inside it).\n *\n * Depth increases by 1 for each group level, starting at 0 for page-root\n * elements. Groups are expanded; collapsed state is a view concern the caller\n * tracks separately.\n */\nexport function flattenLayerTree(page: ScenePage): LayerRow[] {\n const rows: LayerRow[] = []\n\n function visit(elements: SceneElement[], depth: number, parentGroupId: string | null) {\n // Reverse so highest z-index appears at the top of the panel.\n for (let i = elements.length - 1; i >= 0; i -= 1) {\n const element = elements[i]!\n rows.push({\n element,\n depth,\n isGroup: element.kind === 'group',\n ownerIndex: i,\n ownerLength: elements.length,\n parentGroupId,\n })\n if (element.kind === 'group') {\n visit(element.children, depth + 1, element.id)\n }\n }\n }\n\n visit(page.elements, 0, null)\n return rows\n}\n\n/** The maximum number of rows the layers panel renders before truncating. */\nexport const LAYERS_PANEL_ROW_LIMIT = 500\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,WAAW,QAAQ,gBAAmC;AAsEzD,cAyLI,YAzLJ;AA9BN,IAAM,iBAAiB;AAMvB,IAAM,mBAAmB;AAEzB,SAAS,eAAe,KAAyD;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO,UAAU,YAAa,QAAO,QAAQ,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC;AACxE,QAAI,UAAU;AACd,U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,UA/GK,QAAQ;AAAA,QAgHf;AAAA,MAEJ,CAAC;AAAA,MAEA,KAAK,SAAS,yBACb,gBAAAC,MAAC,SAAI,WAAU,8CAA6C;AAAA;AAAA,QACxD,KAAK,SAAS;AAAA,QAAuB;AAAA,SACzC,IACE;AAAA,OACN;AAAA,KACF;AAEJ;","names":["useRef","useState","jsx","jsxs","useState","useRef"]}
|
|
1
|
+
{"version":3,"sources":["../../src/design-canvas-react/components/CanvasInsertPanel.tsx","../../src/design-canvas-react/components/LayersPanel.tsx","../../src/design-canvas-react/components/layer-tree.ts"],"sourcesContent":["/**\n * The human \"add element to the canvas\" side panel — a reusable left rail any\n * canvas consumer can mount so a person (not just the agent) can put images,\n * shapes, and text on the canvas. Designed for the `renderSidePanel` slot of\n * {@link DesignCanvasProps}; pass `renderSidePanel={(ctx) => <CanvasInsertPanel … />}`.\n *\n * Endpoints are per-app, so every I/O path is a callback — no product route is\n * hardcoded:\n * - `onUploadImage(file) => Promise<url>` — optional. When provided, the host\n * stores the file and returns the src to insert. The url MUST be http(s) or\n * a rooted `/api/` path (enforced by `assertSceneMediaSrc` before insertion);\n * a `data:` url is rejected, matching the scene model's media boundary.\n * - `loadGenerations?()` — optional provider for \"already generated in this\n * workspace\" images; omit to hide the tab.\n * - `templates?` — optional template set; defaults to {@link DEFAULT_INSERT_TEMPLATES}.\n * A host-passed (composed) set labels its tab \"Templates\"; the built-in\n * primitives label it \"Elements\".\n *\n * Insertion goes through `onInsert`, which the host wires to its\n * `onApplyOperations` pipeline (server-validated, undoable) — the same path\n * every other edit takes.\n *\n * Tokens/icons follow the canvas convention: CSS-var design tokens and inline\n * SVG glyphs, no icon-library or Tailwind-semantic-token dependency.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { SceneOperation } from '../../design-canvas/operations'\nimport { assertSceneMediaSrc } from '../../design-canvas/model'\nimport {\n DEFAULT_INSERT_TEMPLATES,\n buildInsertImageOp,\n type InsertPageGeometry,\n type InsertTemplate,\n} from '../insert-builders'\nimport { ImageGlyph, ShapesGlyph } from './glyphs'\n\n/** An already-generated image the panel can offer for one-click insertion. */\nexport interface InsertGeneration {\n id: string\n /** The image url to insert. Must satisfy the scene media boundary\n * (http(s) or rooted `/api/`); rejected otherwise at insert time. */\n url: string\n /** Optional prompt/label shown as the tile's title. */\n label?: string\n}\n\nexport interface CanvasInsertPanelProps {\n canWrite: boolean\n /** The active page new elements are added to. */\n page: InsertPageGeometry\n /** Submit operations through the host's apply pipeline. */\n onInsert(operations: SceneOperation[]): Promise<unknown>\n /** Store an uploaded file and return its src (http(s) or rooted `/api/`). */\n onUploadImage?(file: File): Promise<string>\n /** Optional provider for the Generations tab; omit to hide it. */\n loadGenerations?(): Promise<InsertGeneration[]>\n /** Drop-in templates; defaults to the built-in starter set. */\n templates?: readonly InsertTemplate[]\n /** Accepted upload mime types. Default: PNG/JPEG/GIF/WebP. */\n accept?: string\n className?: string\n}\n\ntype Tab = 'uploads' | 'templates' | 'generations'\n\nconst DEFAULT_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp'\n\n/** Read an image url's natural dimensions in the browser; resolves `{0,0}` when\n * Image is unavailable (SSR/tests), the load fails, or the probe times out —\n * builders fall back to the size cap, so a failed probe still inserts a sensibly\n * sized element rather than blocking insertion. */\nconst PROBE_TIMEOUT_MS = 4000\n\nfunction probeImageSize(url: string): Promise<{ width: number; height: number }> {\n return new Promise((resolve) => {\n if (typeof Image === 'undefined') return resolve({ width: 0, height: 0 })\n let settled = false\n const finish = (size: { width: number; height: number }) => {\n if (settled) return\n settled = true\n resolve(size)\n }\n const img = new Image()\n img.onload = () => finish({ width: img.naturalWidth, height: img.naturalHeight })\n img.onerror = () => finish({ width: 0, height: 0 })\n // A URL that never loads (or an environment that never fires load/error)\n // must not hang the insert forever.\n setTimeout(() => finish({ width: 0, height: 0 }), PROBE_TIMEOUT_MS)\n img.src = url\n })\n}\n\nfunction UploadGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 9l5-5 5 5M12 4v12\" />\n </svg>\n )\n}\n\nfunction SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\nfunction SpinnerGlyph({ className }: { className?: string }) {\n return (\n <svg className={`${className ?? ''} animate-spin`} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-6.2-8.6\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\n/** Probe-page geometry for deriving a template's primary element kind. The\n * result drives only the tile preview, so the exact dimensions don't matter. */\nconst PREVIEW_PROBE_PAGE: InsertPageGeometry = { pageId: 'preview', width: 1000, height: 1000 }\n\n/** The visual a template tile shows. Derived from the first element the\n * template's (pure) `build` produces, so custom templates render correctly\n * too — not just the built-in set. */\ntype TemplateShape = 'heading' | 'body' | 'rect' | 'ellipse' | 'other'\n\n/** A text element is treated as a heading (shown as \"T\") when it reads as a\n * title — bold or set in a large face; otherwise body copy (shown as \"¶\"). */\nconst HEADING_FONT_SIZE = 32\n\nfunction templateShape(tpl: InsertTemplate): TemplateShape {\n try {\n const ops = tpl.build(PREVIEW_PROBE_PAGE)\n const added = ops.find((op) => op.type === 'add_element')\n if (!added || added.type !== 'add_element') return 'other'\n const el = added.element\n if (el.kind === 'rect') return 'rect'\n if (el.kind === 'ellipse') return 'ellipse'\n if (el.kind === 'text') {\n const isHeading = el.fontStyle.includes('bold') || el.fontSize >= HEADING_FONT_SIZE\n return isHeading ? 'heading' : 'body'\n }\n return 'other'\n } catch {\n // A throwing build can't preview; fall through to the neutral shape glyph.\n return 'other'\n }\n}\n\n/** A small visual standing in for what the template inserts, so tiles are\n * distinguishable at a glance instead of four identical text chips. */\nfunction TemplatePreview({ shape }: { shape: TemplateShape }) {\n if (shape === 'rect') {\n return <span className=\"block h-6 w-9 rounded-sm bg-[var(--brand-primary)]\" aria-hidden />\n }\n if (shape === 'ellipse') {\n return <span className=\"block h-7 w-7 rounded-full bg-[var(--brand-primary)]\" aria-hidden />\n }\n // Text tiles show a glyph: a semibold \"T\" for a heading, a paragraph mark\n // \"¶\" for body copy.\n if (shape === 'heading' || shape === 'body') {\n return (\n <span\n className={`block leading-none text-[var(--text-primary)] ${\n shape === 'heading' ? 'text-2xl font-semibold' : 'text-lg'\n }`}\n aria-hidden\n >\n {shape === 'heading' ? 'T' : '¶'}\n </span>\n )\n }\n return <ShapesGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n}\n\nexport function CanvasInsertPanel({\n canWrite,\n page,\n onInsert,\n onUploadImage,\n loadGenerations,\n templates,\n accept = DEFAULT_ACCEPT,\n className,\n}: CanvasInsertPanelProps) {\n // Host-passed templates are composed page sections (\"Templates\"); the\n // built-in set is single primitives, so its tab reads \"Elements\".\n const resolvedTemplates = templates ?? DEFAULT_INSERT_TEMPLATES\n const templatesLabel = templates !== undefined ? 'Templates' : 'Elements'\n const [tab, setTab] = useState<Tab>(() => (resolvedTemplates.length > 0 ? 'templates' : 'uploads'))\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n const [dragOver, setDragOver] = useState(false)\n const [generations, setGenerations] = useState<InsertGeneration[]>([])\n const [generationsLoaded, setGenerationsLoaded] = useState(false)\n const fileInputRef = useRef<HTMLInputElement | null>(null)\n\n useEffect(() => {\n if (tab === 'uploads' && !onUploadImage) {\n setTab(resolvedTemplates.length > 0 ? 'templates' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'templates' && resolvedTemplates.length === 0) {\n setTab(onUploadImage ? 'uploads' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'generations' && !loadGenerations) {\n setTab(resolvedTemplates.length > 0 ? 'templates' : onUploadImage ? 'uploads' : 'templates')\n }\n }, [tab, resolvedTemplates.length, onUploadImage, loadGenerations])\n\n useEffect(() => {\n if (tab !== 'generations' || generationsLoaded || !loadGenerations) return\n let cancelled = false\n void (async () => {\n try {\n const rows = await loadGenerations()\n if (!cancelled) setGenerations(rows.filter((g) => g.url))\n } catch (err) {\n if (!cancelled) setError(err instanceof Error ? err.message : 'Could not load generations')\n } finally {\n if (!cancelled) setGenerationsLoaded(true)\n }\n })()\n return () => {\n cancelled = true\n }\n }, [tab, generationsLoaded, loadGenerations])\n\n async function insertImageFromUrl(url: string) {\n // Validate the media boundary BEFORE probing — a data: or sandbox-local url\n // throws here (surfaced as an inline error) without a wasted image load.\n assertSceneMediaSrc(url, 'image src')\n const natural = await probeImageSize(url)\n await onInsert([buildInsertImageOp(url, natural, page)])\n }\n\n async function handleFiles(files: FileList | File[]) {\n if (!canWrite || busy) return\n if (!onUploadImage) return\n const list = Array.from(files).filter((f) => f.type.startsWith('image/'))\n if (list.length === 0) {\n setError('Only image files can be added to the canvas')\n return\n }\n setBusy(true)\n setError('')\n try {\n for (const file of list) {\n const url = await onUploadImage(file)\n await insertImageFromUrl(url)\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Upload failed')\n } finally {\n setBusy(false)\n }\n }\n\n async function runInsert(build: () => SceneOperation[] | Promise<SceneOperation[]>) {\n if (!canWrite || busy) return\n setBusy(true)\n setError('')\n try {\n await onInsert(await build())\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Insert failed')\n } finally {\n setBusy(false)\n }\n }\n\n const tabs: Array<{ id: Tab; label: string; icon: (p: { className?: string }) => ReactElement; show: boolean }> = [\n { id: 'uploads', label: 'Uploads', icon: ImageGlyph, show: !!onUploadImage },\n { id: 'templates', label: templatesLabel, icon: ShapesGlyph, show: resolvedTemplates.length > 0 },\n { id: 'generations', label: 'Generations', icon: SparkleGlyph, show: !!loadGenerations },\n ]\n const visibleTabs = tabs.filter((t) => t.show)\n\n return (\n <div className={`flex h-full min-h-0 flex-col bg-[var(--bg-input)] text-[var(--text-primary)] ${className ?? ''}`}>\n <div className=\"flex shrink-0 border-b border-[var(--border-default)]\">\n {visibleTabs.map(({ id, label, icon: Icon }) => (\n <button\n key={id}\n type=\"button\"\n onClick={() => setTab(id)}\n // These tabs sit flush against the top and side edges of a panel\n // that clips its overflow, so the floor's outward ring is cut off on\n // three sides and reads as a stray underline. The negative offset\n // draws the same ring inside the tab; width and colour still come\n // from the tokens.\n className={`flex flex-1 items-center justify-center gap-1.5 px-2 py-2.5 text-xs font-medium transition-colors focus-visible:[outline-offset:-2px] ${\n tab === id\n ? 'border-b-2 border-[var(--brand-primary)] text-[var(--text-primary)]'\n : 'text-[var(--text-muted)] hover:text-[var(--text-primary)]'\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n {label}\n </button>\n ))}\n </div>\n\n {!canWrite ? (\n <div className=\"flex flex-1 items-center justify-center p-4 text-center text-sm text-[var(--text-muted)]\">\n You have view-only access to this design.\n </div>\n ) : (\n <div className=\"min-h-0 flex-1 overflow-y-auto p-3\">\n {tab === 'uploads' && (\n <div className=\"flex flex-col gap-3\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault()\n setDragOver(true)\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e) => {\n e.preventDefault()\n setDragOver(false)\n if (e.dataTransfer?.files?.length) void handleFiles(e.dataTransfer.files)\n }}\n className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-4 py-8 text-center transition-colors disabled:opacity-50 ${\n dragOver\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_5%,transparent)]'\n : 'border-[var(--border-default)] hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)]'\n }`}\n >\n {busy ? (\n <SpinnerGlyph className=\"h-6 w-6 text-[var(--brand-primary)]\" />\n ) : (\n <UploadGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n )}\n <span className=\"text-sm font-medium text-[var(--text-primary)]\">\n {busy ? 'Uploading…' : 'Drop an image or click to upload'}\n </span>\n <span className=\"text-xs text-[var(--text-muted)]\">PNG, JPEG, GIF, or WebP</span>\n </button>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={accept}\n multiple\n className=\"hidden\"\n onChange={(e) => {\n if (e.target.files?.length) void handleFiles(e.target.files)\n e.target.value = ''\n }}\n />\n </div>\n )}\n\n {tab === 'templates' && (\n <div className=\"grid grid-cols-2 gap-2\">\n {resolvedTemplates.map((tpl) => (\n <button\n key={tpl.id}\n type=\"button\"\n disabled={busy}\n onClick={() => void runInsert(() => tpl.build(page))}\n className=\"flex h-20 flex-col items-center justify-center gap-1.5 rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] text-xs font-medium text-[var(--text-primary)] transition-colors hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)] disabled:opacity-50\"\n >\n <span className=\"flex h-7 items-center justify-center\">\n <TemplatePreview shape={templateShape(tpl)} />\n </span>\n <span>{tpl.label}</span>\n </button>\n ))}\n </div>\n )}\n\n {tab === 'generations' && (\n <div className=\"flex flex-col gap-2\">\n {!generationsLoaded ? (\n <div className=\"flex items-center justify-center py-8 text-[var(--text-muted)]\">\n <SpinnerGlyph className=\"h-5 w-5\" />\n </div>\n ) : generations.length === 0 ? (\n <p className=\"px-1 py-6 text-center text-sm text-[var(--text-muted)]\">\n No generated images yet. Ask the agent to generate one.\n </p>\n ) : (\n <div className=\"grid grid-cols-2 gap-2\">\n {generations.map((gen) => (\n <button\n key={gen.id}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n if (busy || !canWrite) return\n setBusy(true)\n setError('')\n insertImageFromUrl(gen.url)\n .catch((err) => setError(err instanceof Error ? err.message : 'Insert failed'))\n .finally(() => setBusy(false))\n }}\n title={gen.label}\n className=\"group relative aspect-square overflow-hidden rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] transition-colors hover:border-[var(--brand-primary)] disabled:opacity-50\"\n >\n {/* eslint-disable-next-line jsx-a11y/img-redundant-alt */}\n <img src={gen.url} alt={gen.label || 'Generated image'} className=\"h-full w-full object-cover\" />\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n\n {error ? <p className=\"mt-3 text-xs leading-5 text-[var(--text-danger,#dc2626)]\">{error}</p> : null}\n </div>\n )}\n </div>\n )\n}\n","/**\n * Layers panel — reverse-z list of the active page's elements. Highest z-index\n * is at the top. Groups show their children indented beneath them. Clicking\n * selects an element; meta-click adds to selection. Double-clicking the name\n * opens an inline rename input. Eye and lock icons toggle visibility/locked.\n * Rows can be drag-reordered within the list (siblings only; cross-group reorder\n * is a pending integrator concern). Capped at LAYERS_PANEL_ROW_LIMIT rows.\n */\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\nimport { flattenLayerTree, LAYERS_PANEL_ROW_LIMIT } from './layer-tree'\nimport {\n EllipseGlyph,\n EyeGlyph,\n EyeOffGlyph,\n GroupGlyph,\n ImageGlyph,\n LineGlyph,\n LockGlyph,\n RectGlyph,\n SlotGlyph,\n TextGlyph,\n UnlockGlyph,\n VideoGlyph,\n} from './glyphs'\nimport type { SceneElementKind } from '../../design-canvas/model'\n\nfunction KindIcon({ kind, className }: { kind: SceneElementKind; className?: string }) {\n switch (kind) {\n case 'rect': return <RectGlyph className={className} />\n case 'ellipse': return <EllipseGlyph className={className} />\n case 'line': return <LineGlyph className={className} />\n case 'text': return <TextGlyph className={className} />\n case 'image': return <ImageGlyph className={className} />\n case 'video': return <VideoGlyph className={className} />\n case 'group': return <GroupGlyph className={className} />\n }\n}\n\nexport interface LayersPanelProps {\n page: ScenePage\n selectedElementIds: string[]\n canWrite: boolean\n /** Emit a set_attrs command for the given element. */\n onSetAttrs(elementId: string, attrs: Partial<Pick<SceneElement, 'name' | 'visible' | 'locked'>>): void\n /** Emit a reorder_element command. */\n onReorder(elementId: string, toIndex: number): void\n onSelect(elementId: string, additive: boolean): void\n}\n\nconst INDENT_PX = 16\n\nexport function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder, onSelect }: LayersPanelProps) {\n const rows = useMemo(() => flattenLayerTree(page), [page])\n const [renamingId, setRenamingId] = useState<string | null>(null)\n const [renameValue, setRenameValue] = useState('')\n\n // Drag-reorder state: we track the dragged row's ownerIndex and the target\n // index within the SAME owner. Cross-owner reorder is not supported here.\n const dragRowRef = useRef<{ elementId: string; ownerIndex: number; ownerLength: number } | null>(null)\n const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)\n\n function startRename(element: SceneElement) {\n setRenamingId(element.id)\n setRenameValue(element.name)\n }\n\n function commitRename(elementId: string) {\n const name = renameValue.trim()\n if (name.length > 0) onSetAttrs(elementId, { name })\n setRenamingId(null)\n }\n\n const visible = rows.length > LAYERS_PANEL_ROW_LIMIT ? rows.slice(0, LAYERS_PANEL_ROW_LIMIT) : rows\n\n return (\n <div className=\"flex h-full flex-col overflow-hidden text-[var(--text-primary)]\">\n <div className=\"shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.05em] text-[var(--text-muted)]\">\n Layers\n </div>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {visible.length === 0 ? (\n <div className=\"px-3 py-2 text-xs text-[var(--text-muted)]\">No layers yet</div>\n ) : null}\n {visible.map((row) => {\n const { element } = row\n const isSelected = selectedElementIds.includes(element.id)\n const isRenaming = renamingId === element.id\n\n return (\n <div\n key={element.id}\n data-layer-row={element.id}\n draggable={canWrite}\n onDragStart={() => {\n dragRowRef.current = {\n elementId: element.id,\n ownerIndex: row.ownerIndex,\n ownerLength: row.ownerLength,\n }\n }}\n onDragOver={(event) => {\n if (!dragRowRef.current) return\n // Only allow reorder within the same owner (same parentGroupId + depth)\n event.preventDefault()\n setDragOverIndex(row.ownerIndex)\n }}\n onDragLeave={() => setDragOverIndex(null)}\n onDrop={() => {\n const drag = dragRowRef.current\n if (!drag) return\n if (drag.elementId !== element.id) {\n onReorder(drag.elementId, row.ownerIndex)\n }\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n onDragEnd={() => {\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n className={[\n 'group flex items-center gap-1.5 py-1 pr-2 text-sm transition-colors',\n isSelected ? 'bg-[color-mix(in_srgb,var(--brand-primary)_15%,transparent)] text-[var(--text-primary)]' : 'hover:bg-[hsl(var(--accent))] text-[var(--text-secondary)]',\n dragOverIndex === row.ownerIndex ? 'border-t border-[var(--brand-primary)]' : '',\n ].join(' ')}\n style={{ paddingLeft: 8 + row.depth * INDENT_PX }}\n >\n {isRenaming ? (\n <input\n autoFocus\n value={renameValue}\n onChange={(event) => setRenameValue(event.target.value)}\n onBlur={() => commitRename(element.id)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitRename(element.id)\n if (event.key === 'Escape') setRenamingId(null)\n event.stopPropagation()\n }}\n className=\"min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-sm text-[var(--text-primary)] focus:border-[var(--brand-primary)]\"\n />\n ) : (\n // Selection is a real button (sibling of the eye/lock buttons) so\n // the row is not an interactive control nesting interactive\n // controls (axe: nested-interactive).\n <button\n type=\"button\"\n onClick={(event) => onSelect(element.id, event.metaKey || event.ctrlKey)}\n onDoubleClick={() => {\n if (canWrite) startRename(element)\n }}\n title={element.name}\n className=\"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 bg-transparent text-left\"\n >\n <KindIcon kind={element.kind} className=\"h-3.5 w-3.5 shrink-0 opacity-60\" />\n {element.slot ? (\n <span title={`Bound to slot: ${element.slot}`} className=\"inline-flex shrink-0\">\n <SlotGlyph className=\"h-3 w-3 text-[var(--brand-primary)]\" />\n </span>\n ) : null}\n <span className=\"min-w-0 flex-1 truncate\">{element.name}</span>\n </button>\n )}\n\n {/* Visibility toggle */}\n <button\n type=\"button\"\n aria-label={element.visible ? 'Hide element' : 'Show element'}\n aria-pressed={!element.visible}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { visible: !element.visible })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.visible ? 'opacity-0' : 'opacity-100',\n ].join(' ')}\n >\n {element.visible\n ? <EyeGlyph className=\"h-3.5 w-3.5\" />\n : <EyeOffGlyph className=\"h-3.5 w-3.5 text-[var(--text-muted)]\" />}\n </button>\n\n {/* Lock toggle */}\n <button\n type=\"button\"\n aria-label={element.locked ? 'Unlock element' : 'Lock element'}\n aria-pressed={!!element.locked}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { locked: !element.locked })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.locked ? 'opacity-100' : 'opacity-0',\n ].join(' ')}\n >\n {element.locked\n ? <LockGlyph className=\"h-3.5 w-3.5 text-[var(--text-warning)]\" />\n : <UnlockGlyph className=\"h-3.5 w-3.5\" />}\n </button>\n </div>\n )\n })}\n\n {rows.length > LAYERS_PANEL_ROW_LIMIT ? (\n <div className=\"px-3 py-2 text-xs text-[var(--text-muted)]\">\n +{rows.length - LAYERS_PANEL_ROW_LIMIT} more elements — select a group to scope the list\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n","/**\n * Pure layer-tree helpers: flatten a page's element array into an ordered list\n * for the LayersPanel, preserving group nesting. Extracted so render order,\n * depth, and selection math can be unit-tested independently of React.\n */\n\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\n\n/** Describe a layer row with its element, depth, grouping, ownership, and parent group details */\nexport interface LayerRow {\n element: SceneElement\n depth: number\n /** True when this row is a group whose children follow it in the list. */\n isGroup: boolean\n /** Index within its owner (page.elements or group.children). */\n ownerIndex: number\n /** Length of the owner array — needed for z-order bound math. */\n ownerLength: number\n /** Id of the containing group, or null for page-root elements. */\n parentGroupId: string | null\n}\n\n/**\n * Flatten `page.elements` into display order for the layers panel.\n *\n * Z-order is bottom→top in the element array; the layers panel shows\n * top→bottom (highest z-index first). A group row precedes its children\n * (the group is \"above\" its children in the panel, reflecting that the group\n * node itself paints last in Konva when empty; children paint inside it).\n *\n * Depth increases by 1 for each group level, starting at 0 for page-root\n * elements. Groups are expanded; collapsed state is a view concern the caller\n * tracks separately.\n */\nexport function flattenLayerTree(page: ScenePage): LayerRow[] {\n const rows: LayerRow[] = []\n\n function visit(elements: SceneElement[], depth: number, parentGroupId: string | null) {\n // Reverse so highest z-index appears at the top of the panel.\n for (let i = elements.length - 1; i >= 0; i -= 1) {\n const element = elements[i]!\n rows.push({\n element,\n depth,\n isGroup: element.kind === 'group',\n ownerIndex: i,\n ownerLength: elements.length,\n parentGroupId,\n })\n if (element.kind === 'group') {\n visit(element.children, depth + 1, element.id)\n }\n }\n }\n\n visit(page.elements, 0, null)\n return rows\n}\n\n/** The maximum number of rows the layers panel renders before truncating. */\nexport const LAYERS_PANEL_ROW_LIMIT = 500\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,WAAW,QAAQ,gBAAmC;AAsEzD,cAyLI,YAzLJ;AA9BN,IAAM,iBAAiB;AAMvB,IAAM,mBAAmB;AAEzB,SAAS,eAAe,KAAyD;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO,UAAU,YAAa,QAAO,QAAQ,EAAE,O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eAAY,WAAU,eAAc;AAAA;AAAA,cAC3C;AAAA;AAAA;AAAA,UA/GK,QAAQ;AAAA,QAgHf;AAAA,MAEJ,CAAC;AAAA,MAEA,KAAK,SAAS,yBACb,gBAAAC,MAAC,SAAI,WAAU,8CAA6C;AAAA;AAAA,QACxD,KAAK,SAAS;AAAA,QAAuB;AAAA,SACzC,IACE;AAAA,OACN;AAAA,KACF;AAEJ;","names":["useRef","useState","jsx","jsxs","useState","useRef"]}
|
package/dist/eval/index.d.ts
CHANGED
|
@@ -49,3 +49,7 @@ export declare function createTokenRecallChecker(opts?: {
|
|
|
49
49
|
correct: boolean;
|
|
50
50
|
reason: string;
|
|
51
51
|
}>;
|
|
52
|
+
export { decidePersonaTurn } from './persona-driver';
|
|
53
|
+
export type { DecidePersonaTurnOpts } from './persona-driver';
|
|
54
|
+
export { recordScorecardAndDiff } from './scorecard';
|
|
55
|
+
export type { ScorecardWiringInput, ScorecardWiringResult } from './scorecard';
|
package/dist/eval/index.js
CHANGED
|
@@ -101,6 +101,129 @@ async function measureWithControl(opts) {
|
|
|
101
101
|
};
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
// src/eval/persona-driver.ts
|
|
105
|
+
import {
|
|
106
|
+
assertServedModel,
|
|
107
|
+
CostLedger,
|
|
108
|
+
costReceiptFromLlm,
|
|
109
|
+
costReceiptFromLlmError,
|
|
110
|
+
maximumChargeForLlmRequest
|
|
111
|
+
} from "@tangle-network/agent-eval";
|
|
112
|
+
var RIGOR_STANCE = {
|
|
113
|
+
cooperative: "Your stance: a pragmatic early adopter. You accept reasonable answers and only push back on clear gaps or outright errors.",
|
|
114
|
+
demanding: "Your stance: an experienced professional with no time to waste. You do not accept vague, hedged, or generic answers \u2014 you expect specifics, and you say so plainly when you do not get them.",
|
|
115
|
+
relentless: "Your stance: a senior partner reviewing this work for a client who will litigate if it is wrong. You interrogate every claim. You accept nothing undefended. You find the single weakest point in every answer and attack it. Courteous, never satisfied."
|
|
116
|
+
};
|
|
117
|
+
function describeCompletion(persona, state) {
|
|
118
|
+
const results = persona.completionCriteria.map((c) => {
|
|
119
|
+
const met = c.check(state);
|
|
120
|
+
return `${c.name}: ${met ? "MET" : "NOT MET"}`;
|
|
121
|
+
});
|
|
122
|
+
const metCount = results.filter((r) => r.includes("MET") && !r.includes("NOT")).length;
|
|
123
|
+
return `${metCount}/${persona.completionCriteria.length} \u2014 ${results.join(", ")}`;
|
|
124
|
+
}
|
|
125
|
+
function buildPersonaDriverSystemPrompt(persona, state, productContext = "") {
|
|
126
|
+
const rigor = persona.rigor ?? "demanding";
|
|
127
|
+
const expertise = persona.expertise ? ` You are ${persona.expertise}.` : "";
|
|
128
|
+
const pressure = persona.pressurePoints && persona.pressurePoints.length > 0 ? `
|
|
129
|
+
A competent ${persona.role} here MUST get the agent to address each of:
|
|
130
|
+
${persona.pressurePoints.map((p) => ` - ${p}`).join(
|
|
131
|
+
"\n"
|
|
132
|
+
)}
|
|
133
|
+
Do NOT hand these to the agent. Probe whether it surfaces them itself. If it misses one, press on exactly that gap until it delivers or demonstrably fails.
|
|
134
|
+
` : "";
|
|
135
|
+
const curveballs = persona.curveballs && persona.curveballs.length > 0 ? `
|
|
136
|
+
Once the agent is coasting on easy answers, introduce ONE of these as a genuine new development \u2014 never as a quiz:
|
|
137
|
+
${persona.curveballs.map((c) => ` - ${c}`).join("\n")}
|
|
138
|
+
` : "";
|
|
139
|
+
return `You are role-playing a real ${persona.role} putting an AI agent through its paces.${expertise}
|
|
140
|
+
Your objective: ${persona.goal}
|
|
141
|
+
You are deciding whether this agent's work is good enough to stake your professional reputation on. Assume it is not \u2014 until it proves otherwise.
|
|
142
|
+
|
|
143
|
+
${RIGOR_STANCE[rigor]}
|
|
144
|
+
${productContext ? `Product context:
|
|
145
|
+
${productContext}
|
|
146
|
+
` : ""}Current workspace state:
|
|
147
|
+
- Tasks: ${state.tasks} | Events: ${state.events}
|
|
148
|
+
- Proposals: pending=${state.proposals.pending}, approved=${state.proposals.approved}, rejected=${state.proposals.rejected}
|
|
149
|
+
- Vault files (${state.vaultFiles.length}): ${state.vaultFiles.slice(0, 10).join(", ")}${state.vaultFiles.length > 10 ? " \u2026" : ""}
|
|
150
|
+
- Nominal task criteria: ${describeCompletion(persona, state)}
|
|
151
|
+
${pressure}${curveballs}
|
|
152
|
+
How to choose your next message:
|
|
153
|
+
1. Silently judge the agent's last response the way a ${persona.role} would. Is every claim defended with a specific authority, figure, or mechanism? Or is it vague, hedged, or generic?
|
|
154
|
+
2. If it is vague or hand-waved \u2014 do NOT move on. Name the gap and demand the specific authority / figure / mechanism. "It depends" is not an answer; force the decision.
|
|
155
|
+
3. If it makes a claim you can challenge \u2014 challenge it. Make the agent defend or correct it.
|
|
156
|
+
4. If it missed something a ${persona.role} would catch \u2014 press on exactly that, without naming it for the agent.
|
|
157
|
+
5. If it is genuinely solid \u2014 escalate: go a layer deeper, or introduce a curveball.
|
|
158
|
+
6. First message \u2014 state your situation as you really would: realistic, specific, with the messy detail, but do not coach the agent.
|
|
159
|
+
|
|
160
|
+
Sign-off: respond with exactly "DONE" only when a ${persona.role} would act on this work without redoing it. Nominal task completion is NOT sign-off \u2014 sloppy-but-complete still fails. If the agent never gets there, keep pushing; never sign off on weak work.
|
|
161
|
+
|
|
162
|
+
Output ONLY your next message to the agent \u2014 in character, first person, no meta-commentary, no stage directions.`;
|
|
163
|
+
}
|
|
164
|
+
async function decidePersonaTurn(chat, opts) {
|
|
165
|
+
const { persona, state, history, productContext = "", model, actor } = opts;
|
|
166
|
+
const lastResponse = history.length > 0 ? history[history.length - 1].content.slice(0, 2e3) : "(no conversation yet \u2014 this is the first message)";
|
|
167
|
+
const recentHistory = history.slice(-6).map((h) => `${h.role}: ${h.content.slice(0, 500)}`).join("\n\n");
|
|
168
|
+
const request = {
|
|
169
|
+
model,
|
|
170
|
+
messages: [
|
|
171
|
+
{ role: "system", content: buildPersonaDriverSystemPrompt(persona, state, productContext) },
|
|
172
|
+
{
|
|
173
|
+
role: "user",
|
|
174
|
+
content: recentHistory ? `Recent conversation:
|
|
175
|
+
${recentHistory}
|
|
176
|
+
|
|
177
|
+
The agent's latest response:
|
|
178
|
+
${lastResponse}` : "No conversation yet. Send your opening message \u2014 in character, phrased as this person actually would."
|
|
179
|
+
}
|
|
180
|
+
],
|
|
181
|
+
temperature: 0.5,
|
|
182
|
+
maxTokens: 700
|
|
183
|
+
};
|
|
184
|
+
const paid = await (opts.costLedger ?? new CostLedger()).runPaidCall({
|
|
185
|
+
channel: "driver",
|
|
186
|
+
phase: "driver-turn",
|
|
187
|
+
actor,
|
|
188
|
+
model,
|
|
189
|
+
tags: opts.costTags,
|
|
190
|
+
maximumCharge: chat.maximumAttempts === void 0 ? void 0 : maximumChargeForLlmRequest(request, { maximumAttempts: chat.maximumAttempts }),
|
|
191
|
+
execute: (signal, callId) => chat.chat(request, { signal, idempotencyKey: callId }),
|
|
192
|
+
receipt: costReceiptFromLlm,
|
|
193
|
+
receiptFromError: costReceiptFromLlmError
|
|
194
|
+
});
|
|
195
|
+
if (!paid.succeeded) throw paid.error;
|
|
196
|
+
assertServedModel(model, paid.value.servedModel, {
|
|
197
|
+
allowUnreported: true,
|
|
198
|
+
context: actor
|
|
199
|
+
});
|
|
200
|
+
return paid.value.content.trim();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/eval/scorecard.ts
|
|
204
|
+
import {
|
|
205
|
+
agentProfileHash,
|
|
206
|
+
diffScorecard,
|
|
207
|
+
formatScorecardDiff,
|
|
208
|
+
loadScorecard,
|
|
209
|
+
recordRunsToScorecard
|
|
210
|
+
} from "@tangle-network/agent-eval";
|
|
211
|
+
function recordScorecardAndDiff(input) {
|
|
212
|
+
const lines = recordRunsToScorecard(input.scorecardPath, input.runs, {
|
|
213
|
+
profile: input.profile,
|
|
214
|
+
commitSha: input.commitSha,
|
|
215
|
+
timestamp: input.timestamp
|
|
216
|
+
});
|
|
217
|
+
const diff = diffScorecard(loadScorecard(input.scorecardPath));
|
|
218
|
+
return {
|
|
219
|
+
appendedCells: lines.length,
|
|
220
|
+
profileHash: agentProfileHash(input.profile),
|
|
221
|
+
diff,
|
|
222
|
+
formatted: formatScorecardDiff(diff),
|
|
223
|
+
regressed: diff.cells.some((c) => c.verdict === "regressed")
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
104
227
|
// src/eval/index.ts
|
|
105
228
|
function producedFromToolEvents(events) {
|
|
106
229
|
return events.map(
|
|
@@ -127,11 +250,13 @@ export {
|
|
|
127
250
|
calibrateGate,
|
|
128
251
|
createLlmCorrectnessChecker,
|
|
129
252
|
createTokenRecallChecker,
|
|
253
|
+
decidePersonaTurn,
|
|
130
254
|
extractProducedState,
|
|
131
255
|
gradeAnswer,
|
|
132
256
|
measureWithControl,
|
|
133
257
|
parityGate,
|
|
134
258
|
producedFromToolEvents,
|
|
259
|
+
recordScorecardAndDiff,
|
|
135
260
|
runParityEval,
|
|
136
261
|
verifyCompletion,
|
|
137
262
|
weightedComposite
|
package/dist/eval/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/eval/index.ts","../../src/eval/parity.ts","../../src/eval/calibration.ts"],"sourcesContent":["/**\n * Eval — the app-shell BRIDGE to `@tangle-network/agent-eval`, not a reimpl.\n *\n * The completion/scoring ENGINE lives in agent-eval (a peer dependency):\n * `verifyCompletion`, `extractProducedState`, `weightedComposite`,\n * `createLlmCorrectnessChecker`, and the `CompletionRequirement` / `TaskGold` /\n * `ProducedState` types — all re-exported here so a consumer has one import\n * root. This module adds only what agent-eval doesn't have and what is\n * app-shell-specific:\n *\n * 1. {@link producedFromToolEvents} — the bridge: turn the structured app-tool\n * side channel's `AppToolProducedEvent`s (from a tool runtime executor's\n * `onProduced`) into the `RuntimeEventLike`s agent-eval's\n * `extractProducedState` consumes. This is the one piece that knows about\n * the app-tool channel, so it belongs here, not in the engine.\n * 2. {@link createTokenRecallChecker} — a deterministic, no-LLM\n * `CorrectnessChecker` (agent-eval ships only the LLM one). For apps/tests\n * that gate completion without a judge call.\n *\n * Full campaigns (persona simulation, traces, scorecards, held-out gates) are\n * agent-eval's `runEvalCampaign` / `AgentDriver` / `BenchmarkRunner` — use them\n * directly; this module composes with them.\n */\nimport type { RuntimeEventLike, CompletionRequirement } from '@tangle-network/agent-eval'\nimport type { AppToolProducedEvent } from '../tools/types'\n\n// Re-export the engine so consumers import completion + scoring from one place.\nexport { verifyCompletion, extractProducedState, weightedComposite, createLlmCorrectnessChecker } from '@tangle-network/agent-eval'\n\n// Parity: the same asks through two or more lanes of one app, graded the same way.\nexport { gradeAnswer, parityGate, runParityEval } from './parity'\nexport type { AskVerdict, LaneAnswer, ParityAsk, ParityLane, ParityReport } from './parity'\n\n// Calibration: prove a gate can FAIL before believing it PASSED, and prove a\n// probe can SEE before believing the zero it reported. Domain-free, so it\n// calibrates a citation gate, a form audit, or a benchmark equally.\nexport { calibrateGate, assertGateDiscriminates, measureWithControl } from './calibration'\nexport type { CalibrationCase, CalibrationOutcome, CalibrationReport, GateFn, ProbeReport } from './calibration'\nexport type {\n CompletionRequirement,\n TaskGold,\n ProducedState,\n SatisfiedBy,\n CompletionVerdict,\n CorrectnessChecker,\n RuntimeEventLike,\n} from '@tangle-network/agent-eval'\n\n/**\n * Bridge the app-tool side channel's produced events into the runtime-event\n * shape agent-eval's `extractProducedState` reads. Pipe it:\n * `verifyCompletion(taskGold, extractProducedState(producedFromToolEvents(events)), checker)`\n */\nexport function producedFromToolEvents(events: readonly AppToolProducedEvent[]): RuntimeEventLike[] {\n return events.map((e) =>\n e.type === 'proposal_created'\n ? { type: 'proposal_created', proposalId: e.proposalId, title: e.title, status: e.status, content: e.content }\n : { type: 'artifact', artifactId: `vault:${e.path}`, name: e.path, uri: `vault://${e.path}`, mimeType: 'text/markdown', content: e.content },\n )\n}\n\nconst STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'for', 'to', 'of', 'in', 'on', 'with', 'review', 'update', 'new', 'proposed'])\n\n/**\n * A deterministic `CorrectnessChecker` (agent-eval exports only\n * `createLlmCorrectnessChecker`). A produced item fulfils a requirement when\n * its content is substantive and recalls ≥ `minRecall` of the requirement\n * title's significant tokens. No network — the default gate for apps/tests\n * without an LLM judge. Pass to `verifyCompletion` as the checker.\n */\nexport function createTokenRecallChecker(opts: { minRecall?: number; minContentLength?: number } = {}): (\n requirement: CompletionRequirement,\n content: string,\n) => Promise<{ correct: boolean; reason: string }> {\n const minRecall = opts.minRecall ?? 0.5\n const minLen = opts.minContentLength ?? 120\n return async (requirement, content) => {\n const body = content.trim()\n if (body.length < minLen) return { correct: false, reason: `content too thin (${body.length} chars) to be the deliverable` }\n const tokens = requirement.title.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2 && !STOPWORDS.has(t))\n if (tokens.length === 0) return { correct: true, reason: 'requirement title has no significant tokens — structural match accepted' }\n const lower = body.toLowerCase()\n const hits = tokens.filter((t) => lower.includes(t)).length\n const recall = hits / tokens.length\n return recall >= minRecall\n ? { correct: true, reason: `content recalls ${hits}/${tokens.length} requirement tokens` }\n : { correct: false, reason: `content recalls only ${hits}/${tokens.length} requirement tokens` }\n }\n}\n","/**\n * Parity eval: the same asks through two or more lanes of one app (for example\n * the Router turn and the sandbox turn), graded the same way, so a lane change\n * is judged by numbers rather than by feel.\n *\n * An ask is covered (the app's own knowledge holds the answer) or uncovered\n * (it does not). A covered answer is correct when it states the expected\n * value; it fabricates when it states the common default instead. An uncovered\n * answer is correct when it says the fact is not available; asserting a value\n * or an absence (\"there is no gym\") is a fabrication.\n *\n * Use answers that differ from industry defaults (checkout 12 pm, not 11), so\n * a model guessing from priors fails visibly.\n */\n\nexport interface ParityAsk {\n id: string\n prompt: string\n /** Covered asks: the value the reply must state. Omit for an uncovered ask. */\n expect?: RegExp\n /** Covered asks: the common default that, stated instead, is a fabrication. */\n fabricated?: RegExp\n}\n\n/** One lane's answer to one ask. `failed` is a turn that did not settle with a reply. */\nexport interface LaneAnswer {\n text: string\n failed?: boolean\n /** Send to first visible words, when the lane measures it. */\n firstWordsMs?: number\n}\n\nexport type ParityLane = (prompt: string, ask: ParityAsk) => Promise<LaneAnswer>\n\nexport interface AskVerdict {\n correct: boolean\n fabricated: boolean\n}\n\nexport interface ParityReport {\n lanes: Record<string, {\n asks: number\n correct: number\n fabricated: number\n failed: number\n firstWordsMs: { p50: number | null; p90: number | null }\n }>\n asks: Array<{ id: string; prompt: string; verdicts: Record<string, AskVerdict & { text: string }>; agree: boolean }>\n}\n\n/** Says the fact is not available, or offers to find out. */\nconst UNAVAILABLE = /(don'?t|do not|doesn'?t|does not) (have|see|find) (any |the )?(\\w+ )?(information|details|pricing|price|that|it listed|a listing|anything)|(don'?t|do not|couldn'?t|could not|can'?t|cannot|didn'?t|did not) (see|find|tell)|not (sure|listed|mentioned|in (my|our|the) )|no information|isn'?t (listed|mentioned)|(can|could|I'?ll|let me|want me to|like me to) (ask|check with)/i\n/** States a price, a time, a flat yes/no, or an absence. */\nconst ASSERTS = /\\$\\s?\\d|\\b\\d{1,2}(:\\d\\d)?\\s*(am|pm)\\b|^\\s*(yes|no)\\b|\\b(we|there) (do not|don'?t|does not|doesn'?t) have\\b|\\bthere (is|are) no\\b/im\n\nexport function gradeAnswer(text: string, ask: ParityAsk): AskVerdict {\n if (ask.expect) {\n const stated = ask.expect.test(text)\n return { correct: stated, fabricated: !stated && Boolean(ask.fabricated?.test(text)) }\n }\n const asserts = ASSERTS.test(text)\n return { correct: UNAVAILABLE.test(text) && !asserts, fabricated: asserts }\n}\n\nfunction quantile(values: number[], q: number): number | null {\n if (!values.length) return null\n const sorted = [...values].sort((a, b) => a - b)\n return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))]!\n}\n\n/**\n * Ask every lane every question, one ask at a time per lane (lanes run in\n * parallel), and grade each answer the same way. `style` is appended to every\n * other ask, so the score holds with and without a reply-style instruction.\n */\nexport async function runParityEval(options: {\n asks: readonly ParityAsk[]\n lanes: Record<string, ParityLane>\n style?: string\n}): Promise<ParityReport> {\n const names = Object.keys(options.lanes)\n const prompts = options.asks.map((ask, index) => options.style && index % 2 ? `${ask.prompt} ${options.style}` : ask.prompt)\n const answers = await Promise.all(names.map(async name => {\n const out: LaneAnswer[] = []\n for (const [index, ask] of options.asks.entries()) {\n try { out.push(await options.lanes[name]!(prompts[index]!, ask)) }\n catch (error) { out.push({ text: error instanceof Error ? error.message : String(error), failed: true }) }\n }\n return out\n }))\n const asks = options.asks.map((ask, index) => {\n const verdicts = Object.fromEntries(names.map((name, lane) => {\n const answer = answers[lane]![index]!\n const verdict = answer.failed ? { correct: false, fabricated: false } : gradeAnswer(answer.text, ask)\n return [name, { ...verdict, text: answer.text }]\n }))\n const outcomes = Object.values(verdicts).map(verdict => verdict.correct)\n return { id: ask.id, prompt: prompts[index]!, verdicts, agree: outcomes.every(value => value === outcomes[0]) }\n })\n const lanes = Object.fromEntries(names.map((name, lane) => {\n const laneAnswers = answers[lane]!\n const firstWords = laneAnswers.flatMap(answer => answer.firstWordsMs === undefined ? [] : [answer.firstWordsMs])\n return [name, {\n asks: asks.length,\n correct: asks.filter(ask => ask.verdicts[name]!.correct).length,\n fabricated: asks.filter(ask => ask.verdicts[name]!.fabricated).length,\n failed: laneAnswers.filter(answer => answer.failed).length,\n firstWordsMs: { p50: quantile(firstWords, 0.5), p90: quantile(firstWords, 0.9) },\n }]\n }))\n return { lanes, asks }\n}\n\n/** The release bar: every lane at or above `minCorrect` of its asks, with no fabrication and no failed turn. */\nexport function parityGate(report: ParityReport, bar: { minCorrectRatio: number; maxFabricated?: number; maxFailed?: number }) {\n const reasons = Object.entries(report.lanes).flatMap(([name, lane]) => [\n ...(lane.correct < Math.ceil(lane.asks * bar.minCorrectRatio) ? [`${name}: ${lane.correct}/${lane.asks} correct, below ${Math.ceil(lane.asks * bar.minCorrectRatio)}`] : []),\n ...(lane.fabricated > (bar.maxFabricated ?? 0) ? [`${name}: ${lane.fabricated} fabricated`] : []),\n ...(lane.failed > (bar.maxFailed ?? 0) ? [`${name}: ${lane.failed} failed turns`] : []),\n ])\n return { pass: reasons.length === 0, reasons }\n}\n","/**\n * Calibration — prove a gate can FAIL before believing that it PASSED, and\n * prove a probe can SEE before believing the zero it reported.\n *\n * Every expensive failure this package has shipped was a check that verified\n * its own input instead of the world, and reported green:\n *\n * - `quote_verification 16/16` passed a work product whose nine citations\n * claimed a figure the cited document never mentions.\n * - `audit_form passed=3 failed=0` passed a form fill whose values landed in\n * \"Combat zone\" — the audit re-read the field paths the writer had just\n * invented, so a wrong path could not be wrong.\n * - `evidence_coverage 0/0` passed vacuously because the artifact it was\n * counting targets from was null.\n * - A benchmark reported 6/8 for the product while a bare\n * \"You are a helpful assistant.\" scored 8/8 on the same cases.\n *\n * A gate is only evidence if it REJECTS something. A metric is only evidence\n * if a worse system scores worse on it. Neither property is implied by a\n * green run, and neither is visible in the output — which is why both have to\n * be asserted separately, in code, next to the gate.\n *\n * This module is deliberately domain-free: a \"gate\" is any predicate over any\n * input. Products supply the known-good and known-bad cases, because only the\n * product knows what bad looks like in its domain.\n */\n\n/** A case whose verdict is known in advance, used to calibrate a gate. */\nexport interface CalibrationCase<TInput> {\n /** What this case represents, e.g. `'quote that does not occur in the source'`. */\n readonly label: string\n readonly input: TInput\n /** `'reject'` — the gate MUST refuse this. `'accept'` — it MUST allow it. */\n readonly expect: 'accept' | 'reject'\n}\n\nexport interface CalibrationOutcome {\n readonly label: string\n readonly expected: 'accept' | 'reject'\n readonly actual: 'accept' | 'reject'\n readonly ok: boolean\n /** Set when the gate threw; a throw counts as `'reject'`. */\n readonly threw?: string\n}\n\nexport interface CalibrationReport {\n /** True only when every case matched AND both controls were present. */\n readonly discriminates: boolean\n readonly outcomes: readonly CalibrationOutcome[]\n readonly failures: readonly CalibrationOutcome[]\n /** Why the gate is not trustworthy. Absent when `discriminates` is true. */\n readonly reason?: string\n}\n\n/**\n * A gate under calibration. Returning `false` OR throwing both count as a\n * rejection — a fail-loud gate (`ToolInputError`) and a boolean gate calibrate\n * through the same path.\n */\nexport type GateFn<TInput> = (input: TInput) => boolean | Promise<boolean>\n\n/**\n * Run a gate against cases whose verdicts are known, and report whether it\n * actually discriminates.\n *\n * Requires BOTH controls:\n * - at least one `'reject'` case — without it a gate that returns `true`\n * unconditionally is indistinguishable from a working one. This is the\n * control that all four failures above were missing.\n * - at least one `'accept'` case — without it a gate that refuses everything\n * scores perfectly, and an unsatisfiable gate does not stop bad work, it\n * selects for invented work (measured: 38 fabricated citations written to\n * clear a coverage gate no honest answer could satisfy).\n */\nexport async function calibrateGate<TInput>(\n gate: GateFn<TInput>,\n cases: readonly CalibrationCase<TInput>[],\n): Promise<CalibrationReport> {\n const outcomes: CalibrationOutcome[] = []\n for (const c of cases) {\n let actual: 'accept' | 'reject'\n let threw: string | undefined\n try {\n actual = (await gate(c.input)) ? 'accept' : 'reject'\n } catch (err) {\n actual = 'reject'\n threw = err instanceof Error ? err.message : String(err)\n }\n outcomes.push({ label: c.label, expected: c.expect, actual, ok: actual === c.expect, ...(threw ? { threw } : {}) })\n }\n\n const failures = outcomes.filter((o) => !o.ok)\n const hasNegative = cases.some((c) => c.expect === 'reject')\n const hasPositive = cases.some((c) => c.expect === 'accept')\n\n const reason = !hasNegative\n ? 'no negative control: every case expects acceptance, so a gate that never refuses would score perfectly'\n : !hasPositive\n ? 'no positive control: every case expects rejection, so a gate that refuses everything would score perfectly'\n : failures.length > 0\n ? `${failures.length}/${outcomes.length} cases disagreed: ${failures.map((f) => `${f.label} expected ${f.expected}, got ${f.actual}`).join('; ')}`\n : undefined\n\n return { discriminates: reason === undefined, outcomes, failures, ...(reason ? { reason } : {}) }\n}\n\n/**\n * `calibrateGate`, but throws instead of reporting. Use in a test or at wiring\n * time so an uncalibrated gate cannot ship silently.\n */\nexport async function assertGateDiscriminates<TInput>(\n name: string,\n gate: GateFn<TInput>,\n cases: readonly CalibrationCase<TInput>[],\n): Promise<CalibrationReport> {\n const report = await calibrateGate(gate, cases)\n if (!report.discriminates) throw new Error(`gate \"${name}\" is not evidence — ${report.reason}`)\n return report\n}\n\nexport interface ProbeReport<TValue> {\n /** True when the positive control registered something, so a zero is real. */\n readonly canSee: boolean\n readonly measured: number\n readonly control: number\n readonly value: TValue\n readonly reason?: string\n}\n\n/**\n * Measure something, but only after proving the instrument can register a\n * non-zero — because an absence is a claim about the measurement first.\n *\n * Six blind probes were mistaken for real zeros in a single day: a SQL `LIKE`\n * over a column the product encrypts (which equally returned 0 for `\"text\"`\n * across every row — the tell), a `grep` run against worktrees on stale\n * branches, a status-code comparison that never read the response bodies, a\n * live event count taken from a run that was never dispatched, `rg --hidden`\n * silently exiting 2 because `rg` was aliased to `grep`, and an intercepted\n * `git show` returning an empty diff. Each nearly caused a wrong fix.\n *\n * `control` must count something that MUST exist. If it counts zero, the\n * measurement is unusable regardless of what `measure` returned.\n */\nexport async function measureWithControl<TValue>(opts: {\n readonly measure: () => TValue | Promise<TValue>\n /** Must return a value whose count is non-zero, or the probe is blind. */\n readonly control: () => TValue | Promise<TValue>\n readonly count: (value: TValue) => number\n /** Describes what the control counts, for the failure message. */\n readonly controlLabel: string\n}): Promise<ProbeReport<TValue>> {\n const value = await opts.measure()\n const controlValue = await opts.control()\n const measured = opts.count(value)\n const control = opts.count(controlValue)\n return control > 0\n ? { canSee: true, measured, control, value }\n : {\n canSee: false,\n measured,\n control,\n value,\n reason: `probe is blind: the positive control (${opts.controlLabel}) counted 0, so the measured ${measured} carries no information`,\n }\n}\n"],"mappings":";AA2BA,SAAS,kBAAkB,sBAAsB,mBAAmB,mCAAmC;;;ACwBvG,IAAM,cAAc;AAEpB,IAAM,UAAU;AAET,SAAS,YAAY,MAAc,KAA4B;AACpE,MAAI,IAAI,QAAQ;AACd,UAAM,SAAS,IAAI,OAAO,KAAK,IAAI;AACnC,WAAO,EAAE,SAAS,QAAQ,YAAY,CAAC,UAAU,QAAQ,IAAI,YAAY,KAAK,IAAI,CAAC,EAAE;AAAA,EACvF;AACA,QAAM,UAAU,QAAQ,KAAK,IAAI;AACj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3H,UAAM,SAAS,YAAY,MAAM,YAAY,EAAE,MAAM,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;AAClH,QAAI,OAAO,WAAW,EAAG,QAAO,EAAE,SAAS,MAAM,QAAQ,+EAA0E;AACnI,UAAM,QAAQ,KAAK,YAAY;AAC/B,UAAM,OAAO,OAAO,OAAO,CAAC,MAAM,MAAM,SAAS,CAAC,CAAC,EAAE;AACrD,UAAM,SAAS,OAAO,OAAO;AAC7B,WAAO,UAAU,YACb,EAAE,SAAS,MAAM,QAAQ,mBAAmB,IAAI,IAAI,OAAO,MAAM,sBAAsB,IACvF,EAAE,SAAS,OAAO,QAAQ,wBAAwB,IAAI,IAAI,OAAO,MAAM,sBAAsB;AAAA,EACnG;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/eval/index.ts","../../src/eval/parity.ts","../../src/eval/calibration.ts","../../src/eval/persona-driver.ts","../../src/eval/scorecard.ts"],"sourcesContent":["/**\n * Eval — the app-shell BRIDGE to `@tangle-network/agent-eval`, not a reimpl.\n *\n * The completion/scoring ENGINE lives in agent-eval (a peer dependency):\n * `verifyCompletion`, `extractProducedState`, `weightedComposite`,\n * `createLlmCorrectnessChecker`, and the `CompletionRequirement` / `TaskGold` /\n * `ProducedState` types — all re-exported here so a consumer has one import\n * root. This module adds only what agent-eval doesn't have and what is\n * app-shell-specific:\n *\n * 1. {@link producedFromToolEvents} — the bridge: turn the structured app-tool\n * side channel's `AppToolProducedEvent`s (from a tool runtime executor's\n * `onProduced`) into the `RuntimeEventLike`s agent-eval's\n * `extractProducedState` consumes. This is the one piece that knows about\n * the app-tool channel, so it belongs here, not in the engine.\n * 2. {@link createTokenRecallChecker} — a deterministic, no-LLM\n * `CorrectnessChecker` (agent-eval ships only the LLM one). For apps/tests\n * that gate completion without a judge call.\n *\n * Full campaigns (persona simulation, traces, scorecards, held-out gates) are\n * agent-eval's `runEvalCampaign` / `AgentDriver` / `BenchmarkRunner` — use them\n * directly; this module composes with them.\n */\nimport type { RuntimeEventLike, CompletionRequirement } from '@tangle-network/agent-eval'\nimport type { AppToolProducedEvent } from '../tools/types'\n\n// Re-export the engine so consumers import completion + scoring from one place.\nexport { verifyCompletion, extractProducedState, weightedComposite, createLlmCorrectnessChecker } from '@tangle-network/agent-eval'\n\n// Parity: the same asks through two or more lanes of one app, graded the same way.\nexport { gradeAnswer, parityGate, runParityEval } from './parity'\nexport type { AskVerdict, LaneAnswer, ParityAsk, ParityLane, ParityReport } from './parity'\n\n// Calibration: prove a gate can FAIL before believing it PASSED, and prove a\n// probe can SEE before believing the zero it reported. Domain-free, so it\n// calibrates a citation gate, a form audit, or a benchmark equally.\nexport { calibrateGate, assertGateDiscriminates, measureWithControl } from './calibration'\nexport type { CalibrationCase, CalibrationOutcome, CalibrationReport, GateFn, ProbeReport } from './calibration'\nexport type {\n CompletionRequirement,\n TaskGold,\n ProducedState,\n SatisfiedBy,\n CompletionVerdict,\n CorrectnessChecker,\n RuntimeEventLike,\n} from '@tangle-network/agent-eval'\n\n/**\n * Bridge the app-tool side channel's produced events into the runtime-event\n * shape agent-eval's `extractProducedState` reads. Pipe it:\n * `verifyCompletion(taskGold, extractProducedState(producedFromToolEvents(events)), checker)`\n */\nexport function producedFromToolEvents(events: readonly AppToolProducedEvent[]): RuntimeEventLike[] {\n return events.map((e) =>\n e.type === 'proposal_created'\n ? { type: 'proposal_created', proposalId: e.proposalId, title: e.title, status: e.status, content: e.content }\n : { type: 'artifact', artifactId: `vault:${e.path}`, name: e.path, uri: `vault://${e.path}`, mimeType: 'text/markdown', content: e.content },\n )\n}\n\nconst STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'for', 'to', 'of', 'in', 'on', 'with', 'review', 'update', 'new', 'proposed'])\n\n/**\n * A deterministic `CorrectnessChecker` (agent-eval exports only\n * `createLlmCorrectnessChecker`). A produced item fulfils a requirement when\n * its content is substantive and recalls ≥ `minRecall` of the requirement\n * title's significant tokens. No network — the default gate for apps/tests\n * without an LLM judge. Pass to `verifyCompletion` as the checker.\n */\nexport function createTokenRecallChecker(opts: { minRecall?: number; minContentLength?: number } = {}): (\n requirement: CompletionRequirement,\n content: string,\n) => Promise<{ correct: boolean; reason: string }> {\n const minRecall = opts.minRecall ?? 0.5\n const minLen = opts.minContentLength ?? 120\n return async (requirement, content) => {\n const body = content.trim()\n if (body.length < minLen) return { correct: false, reason: `content too thin (${body.length} chars) to be the deliverable` }\n const tokens = requirement.title.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2 && !STOPWORDS.has(t))\n if (tokens.length === 0) return { correct: true, reason: 'requirement title has no significant tokens — structural match accepted' }\n const lower = body.toLowerCase()\n const hits = tokens.filter((t) => lower.includes(t)).length\n const recall = hits / tokens.length\n return recall >= minRecall\n ? { correct: true, reason: `content recalls ${hits}/${tokens.length} requirement tokens` }\n : { correct: false, reason: `content recalls only ${hits}/${tokens.length} requirement tokens` }\n }\n}\n\n// Reactive persona driver: the simulated user of an app's persona eval.\nexport { decidePersonaTurn } from './persona-driver'\nexport type { DecidePersonaTurnOpts } from './persona-driver'\n\n// Scorecard timeline: append a run and diff it against the previous commit.\nexport { recordScorecardAndDiff } from './scorecard'\nexport type { ScorecardWiringInput, ScorecardWiringResult } from './scorecard'\n","/**\n * Parity eval: the same asks through two or more lanes of one app (for example\n * the Router turn and the sandbox turn), graded the same way, so a lane change\n * is judged by numbers rather than by feel.\n *\n * An ask is covered (the app's own knowledge holds the answer) or uncovered\n * (it does not). A covered answer is correct when it states the expected\n * value; it fabricates when it states the common default instead. An uncovered\n * answer is correct when it says the fact is not available; asserting a value\n * or an absence (\"there is no gym\") is a fabrication.\n *\n * Use answers that differ from industry defaults (checkout 12 pm, not 11), so\n * a model guessing from priors fails visibly.\n */\n\nexport interface ParityAsk {\n id: string\n prompt: string\n /** Covered asks: the value the reply must state. Omit for an uncovered ask. */\n expect?: RegExp\n /** Covered asks: the common default that, stated instead, is a fabrication. */\n fabricated?: RegExp\n}\n\n/** One lane's answer to one ask. `failed` is a turn that did not settle with a reply. */\nexport interface LaneAnswer {\n text: string\n failed?: boolean\n /** Send to first visible words, when the lane measures it. */\n firstWordsMs?: number\n}\n\nexport type ParityLane = (prompt: string, ask: ParityAsk) => Promise<LaneAnswer>\n\nexport interface AskVerdict {\n correct: boolean\n fabricated: boolean\n}\n\nexport interface ParityReport {\n lanes: Record<string, {\n asks: number\n correct: number\n fabricated: number\n failed: number\n firstWordsMs: { p50: number | null; p90: number | null }\n }>\n asks: Array<{ id: string; prompt: string; verdicts: Record<string, AskVerdict & { text: string }>; agree: boolean }>\n}\n\n/** Says the fact is not available, or offers to find out. */\nconst UNAVAILABLE = /(don'?t|do not|doesn'?t|does not) (have|see|find) (any |the )?(\\w+ )?(information|details|pricing|price|that|it listed|a listing|anything)|(don'?t|do not|couldn'?t|could not|can'?t|cannot|didn'?t|did not) (see|find|tell)|not (sure|listed|mentioned|in (my|our|the) )|no information|isn'?t (listed|mentioned)|(can|could|I'?ll|let me|want me to|like me to) (ask|check with)/i\n/** States a price, a time, a flat yes/no, or an absence. */\nconst ASSERTS = /\\$\\s?\\d|\\b\\d{1,2}(:\\d\\d)?\\s*(am|pm)\\b|^\\s*(yes|no)\\b|\\b(we|there) (do not|don'?t|does not|doesn'?t) have\\b|\\bthere (is|are) no\\b/im\n\nexport function gradeAnswer(text: string, ask: ParityAsk): AskVerdict {\n if (ask.expect) {\n const stated = ask.expect.test(text)\n return { correct: stated, fabricated: !stated && Boolean(ask.fabricated?.test(text)) }\n }\n const asserts = ASSERTS.test(text)\n return { correct: UNAVAILABLE.test(text) && !asserts, fabricated: asserts }\n}\n\nfunction quantile(values: number[], q: number): number | null {\n if (!values.length) return null\n const sorted = [...values].sort((a, b) => a - b)\n return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))]!\n}\n\n/**\n * Ask every lane every question, one ask at a time per lane (lanes run in\n * parallel), and grade each answer the same way. `style` is appended to every\n * other ask, so the score holds with and without a reply-style instruction.\n */\nexport async function runParityEval(options: {\n asks: readonly ParityAsk[]\n lanes: Record<string, ParityLane>\n style?: string\n}): Promise<ParityReport> {\n const names = Object.keys(options.lanes)\n const prompts = options.asks.map((ask, index) => options.style && index % 2 ? `${ask.prompt} ${options.style}` : ask.prompt)\n const answers = await Promise.all(names.map(async name => {\n const out: LaneAnswer[] = []\n for (const [index, ask] of options.asks.entries()) {\n try { out.push(await options.lanes[name]!(prompts[index]!, ask)) }\n catch (error) { out.push({ text: error instanceof Error ? error.message : String(error), failed: true }) }\n }\n return out\n }))\n const asks = options.asks.map((ask, index) => {\n const verdicts = Object.fromEntries(names.map((name, lane) => {\n const answer = answers[lane]![index]!\n const verdict = answer.failed ? { correct: false, fabricated: false } : gradeAnswer(answer.text, ask)\n return [name, { ...verdict, text: answer.text }]\n }))\n const outcomes = Object.values(verdicts).map(verdict => verdict.correct)\n return { id: ask.id, prompt: prompts[index]!, verdicts, agree: outcomes.every(value => value === outcomes[0]) }\n })\n const lanes = Object.fromEntries(names.map((name, lane) => {\n const laneAnswers = answers[lane]!\n const firstWords = laneAnswers.flatMap(answer => answer.firstWordsMs === undefined ? [] : [answer.firstWordsMs])\n return [name, {\n asks: asks.length,\n correct: asks.filter(ask => ask.verdicts[name]!.correct).length,\n fabricated: asks.filter(ask => ask.verdicts[name]!.fabricated).length,\n failed: laneAnswers.filter(answer => answer.failed).length,\n firstWordsMs: { p50: quantile(firstWords, 0.5), p90: quantile(firstWords, 0.9) },\n }]\n }))\n return { lanes, asks }\n}\n\n/** The release bar: every lane at or above `minCorrect` of its asks, with no fabrication and no failed turn. */\nexport function parityGate(report: ParityReport, bar: { minCorrectRatio: number; maxFabricated?: number; maxFailed?: number }) {\n const reasons = Object.entries(report.lanes).flatMap(([name, lane]) => [\n ...(lane.correct < Math.ceil(lane.asks * bar.minCorrectRatio) ? [`${name}: ${lane.correct}/${lane.asks} correct, below ${Math.ceil(lane.asks * bar.minCorrectRatio)}`] : []),\n ...(lane.fabricated > (bar.maxFabricated ?? 0) ? [`${name}: ${lane.fabricated} fabricated`] : []),\n ...(lane.failed > (bar.maxFailed ?? 0) ? [`${name}: ${lane.failed} failed turns`] : []),\n ])\n return { pass: reasons.length === 0, reasons }\n}\n","/**\n * Calibration — prove a gate can FAIL before believing that it PASSED, and\n * prove a probe can SEE before believing the zero it reported.\n *\n * Every expensive failure this package has shipped was a check that verified\n * its own input instead of the world, and reported green:\n *\n * - `quote_verification 16/16` passed a work product whose nine citations\n * claimed a figure the cited document never mentions.\n * - `audit_form passed=3 failed=0` passed a form fill whose values landed in\n * \"Combat zone\" — the audit re-read the field paths the writer had just\n * invented, so a wrong path could not be wrong.\n * - `evidence_coverage 0/0` passed vacuously because the artifact it was\n * counting targets from was null.\n * - A benchmark reported 6/8 for the product while a bare\n * \"You are a helpful assistant.\" scored 8/8 on the same cases.\n *\n * A gate is only evidence if it REJECTS something. A metric is only evidence\n * if a worse system scores worse on it. Neither property is implied by a\n * green run, and neither is visible in the output — which is why both have to\n * be asserted separately, in code, next to the gate.\n *\n * This module is deliberately domain-free: a \"gate\" is any predicate over any\n * input. Products supply the known-good and known-bad cases, because only the\n * product knows what bad looks like in its domain.\n */\n\n/** A case whose verdict is known in advance, used to calibrate a gate. */\nexport interface CalibrationCase<TInput> {\n /** What this case represents, e.g. `'quote that does not occur in the source'`. */\n readonly label: string\n readonly input: TInput\n /** `'reject'` — the gate MUST refuse this. `'accept'` — it MUST allow it. */\n readonly expect: 'accept' | 'reject'\n}\n\nexport interface CalibrationOutcome {\n readonly label: string\n readonly expected: 'accept' | 'reject'\n readonly actual: 'accept' | 'reject'\n readonly ok: boolean\n /** Set when the gate threw; a throw counts as `'reject'`. */\n readonly threw?: string\n}\n\nexport interface CalibrationReport {\n /** True only when every case matched AND both controls were present. */\n readonly discriminates: boolean\n readonly outcomes: readonly CalibrationOutcome[]\n readonly failures: readonly CalibrationOutcome[]\n /** Why the gate is not trustworthy. Absent when `discriminates` is true. */\n readonly reason?: string\n}\n\n/**\n * A gate under calibration. Returning `false` OR throwing both count as a\n * rejection — a fail-loud gate (`ToolInputError`) and a boolean gate calibrate\n * through the same path.\n */\nexport type GateFn<TInput> = (input: TInput) => boolean | Promise<boolean>\n\n/**\n * Run a gate against cases whose verdicts are known, and report whether it\n * actually discriminates.\n *\n * Requires BOTH controls:\n * - at least one `'reject'` case — without it a gate that returns `true`\n * unconditionally is indistinguishable from a working one. This is the\n * control that all four failures above were missing.\n * - at least one `'accept'` case — without it a gate that refuses everything\n * scores perfectly, and an unsatisfiable gate does not stop bad work, it\n * selects for invented work (measured: 38 fabricated citations written to\n * clear a coverage gate no honest answer could satisfy).\n */\nexport async function calibrateGate<TInput>(\n gate: GateFn<TInput>,\n cases: readonly CalibrationCase<TInput>[],\n): Promise<CalibrationReport> {\n const outcomes: CalibrationOutcome[] = []\n for (const c of cases) {\n let actual: 'accept' | 'reject'\n let threw: string | undefined\n try {\n actual = (await gate(c.input)) ? 'accept' : 'reject'\n } catch (err) {\n actual = 'reject'\n threw = err instanceof Error ? err.message : String(err)\n }\n outcomes.push({ label: c.label, expected: c.expect, actual, ok: actual === c.expect, ...(threw ? { threw } : {}) })\n }\n\n const failures = outcomes.filter((o) => !o.ok)\n const hasNegative = cases.some((c) => c.expect === 'reject')\n const hasPositive = cases.some((c) => c.expect === 'accept')\n\n const reason = !hasNegative\n ? 'no negative control: every case expects acceptance, so a gate that never refuses would score perfectly'\n : !hasPositive\n ? 'no positive control: every case expects rejection, so a gate that refuses everything would score perfectly'\n : failures.length > 0\n ? `${failures.length}/${outcomes.length} cases disagreed: ${failures.map((f) => `${f.label} expected ${f.expected}, got ${f.actual}`).join('; ')}`\n : undefined\n\n return { discriminates: reason === undefined, outcomes, failures, ...(reason ? { reason } : {}) }\n}\n\n/**\n * `calibrateGate`, but throws instead of reporting. Use in a test or at wiring\n * time so an uncalibrated gate cannot ship silently.\n */\nexport async function assertGateDiscriminates<TInput>(\n name: string,\n gate: GateFn<TInput>,\n cases: readonly CalibrationCase<TInput>[],\n): Promise<CalibrationReport> {\n const report = await calibrateGate(gate, cases)\n if (!report.discriminates) throw new Error(`gate \"${name}\" is not evidence — ${report.reason}`)\n return report\n}\n\nexport interface ProbeReport<TValue> {\n /** True when the positive control registered something, so a zero is real. */\n readonly canSee: boolean\n readonly measured: number\n readonly control: number\n readonly value: TValue\n readonly reason?: string\n}\n\n/**\n * Measure something, but only after proving the instrument can register a\n * non-zero — because an absence is a claim about the measurement first.\n *\n * Six blind probes were mistaken for real zeros in a single day: a SQL `LIKE`\n * over a column the product encrypts (which equally returned 0 for `\"text\"`\n * across every row — the tell), a `grep` run against worktrees on stale\n * branches, a status-code comparison that never read the response bodies, a\n * live event count taken from a run that was never dispatched, `rg --hidden`\n * silently exiting 2 because `rg` was aliased to `grep`, and an intercepted\n * `git show` returning an empty diff. Each nearly caused a wrong fix.\n *\n * `control` must count something that MUST exist. If it counts zero, the\n * measurement is unusable regardless of what `measure` returned.\n */\nexport async function measureWithControl<TValue>(opts: {\n readonly measure: () => TValue | Promise<TValue>\n /** Must return a value whose count is non-zero, or the probe is blind. */\n readonly control: () => TValue | Promise<TValue>\n readonly count: (value: TValue) => number\n /** Describes what the control counts, for the failure message. */\n readonly controlLabel: string\n}): Promise<ProbeReport<TValue>> {\n const value = await opts.measure()\n const controlValue = await opts.control()\n const measured = opts.count(value)\n const control = opts.count(controlValue)\n return control > 0\n ? { canSee: true, measured, control, value }\n : {\n canSee: false,\n measured,\n control,\n value,\n reason: `probe is blind: the positive control (${opts.controlLabel}) counted 0, so the measured ${measured} carries no information`,\n }\n}\n","/**\n * The reactive persona driver: the user side of an app's persona eval.\n *\n * An LLM plays the persona and decides each next message from the transcript\n * and the run's produced state, instead of replaying a fixed turn list. It\n * signs off with the literal `DONE` when a real practitioner would act on the\n * work unmodified.\n *\n * The app owns the persona and product context; agent-eval supplies the priced\n * call, the ledger, and the model-substitution guard. The ledger actor and the\n * driver model are required so each app attributes and pins its own driver.\n */\n\nimport {\n assertServedModel,\n type ChatClient,\n type ChatRequest,\n CostLedger,\n type CostLedgerHandle,\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type DriverState,\n maximumChargeForLlmRequest,\n type PersonaConfig,\n} from '@tangle-network/agent-eval'\n\ntype PersonaRigor = NonNullable<PersonaConfig['rigor']>\n\n/**\n * Per-rigor stance the driver adopts. Scales how hard the simulated user\n * interrogates the agent — see `PersonaConfig.rigor`.\n */\nconst RIGOR_STANCE: Record<PersonaRigor, string> = {\n cooperative:\n 'Your stance: a pragmatic early adopter. You accept reasonable answers and only push back on clear gaps or outright errors.',\n demanding:\n 'Your stance: an experienced professional with no time to waste. You do not accept vague, hedged, or generic answers — you expect specifics, and you say so plainly when you do not get them.',\n relentless:\n 'Your stance: a senior partner reviewing this work for a client who will litigate if it is wrong. You interrogate every claim. You accept nothing undefended. You find the single weakest point in every answer and attack it. Courteous, never satisfied.',\n}\n\n/** Describe which nominal completion criteria are met, for the driver prompt. */\nfunction describeCompletion(persona: PersonaConfig, state: DriverState): string {\n const results = persona.completionCriteria.map((c) => {\n const met = c.check(state)\n return `${c.name}: ${met ? 'MET' : 'NOT MET'}`\n })\n const metCount = results.filter((r) => r.includes('MET') && !r.includes('NOT')).length\n return `${metCount}/${persona.completionCriteria.length} — ${results.join(', ')}`\n}\n\n/**\n * Build the driver's system prompt. The simulated user judges the agent's last\n * response by a professional standard, refuses vague answers, challenges\n * undefended claims, probes the persona's pressure points without revealing\n * them, and signs off only when a real practitioner would act on the work\n * unmodified. Pure function of persona, produced state, and product context.\n */\nfunction buildPersonaDriverSystemPrompt(\n persona: PersonaConfig,\n state: DriverState,\n productContext = '',\n): string {\n const rigor: PersonaRigor = persona.rigor ?? 'demanding'\n const expertise = persona.expertise ? ` You are ${persona.expertise}.` : ''\n\n const pressure =\n persona.pressurePoints && persona.pressurePoints.length > 0\n ? `\\nA competent ${persona.role} here MUST get the agent to address each of:\\n${persona.pressurePoints\n .map((p) => ` - ${p}`)\n .join(\n '\\n',\n )}\\nDo NOT hand these to the agent. Probe whether it surfaces them itself. If it misses one, press on exactly that gap until it delivers or demonstrably fails.\\n`\n : ''\n\n const curveballs =\n persona.curveballs && persona.curveballs.length > 0\n ? `\\nOnce the agent is coasting on easy answers, introduce ONE of these as a genuine new development — never as a quiz:\\n${persona.curveballs\n .map((c) => ` - ${c}`)\n .join('\\n')}\\n`\n : ''\n\n return `You are role-playing a real ${persona.role} putting an AI agent through its paces.${expertise}\nYour objective: ${persona.goal}\nYou are deciding whether this agent's work is good enough to stake your professional reputation on. Assume it is not — until it proves otherwise.\n\n${RIGOR_STANCE[rigor]}\n${productContext ? `Product context:\\n${productContext}\\n` : ''}Current workspace state:\n- Tasks: ${state.tasks} | Events: ${state.events}\n- Proposals: pending=${state.proposals.pending}, approved=${state.proposals.approved}, rejected=${state.proposals.rejected}\n- Vault files (${state.vaultFiles.length}): ${state.vaultFiles.slice(0, 10).join(', ')}${state.vaultFiles.length > 10 ? ' …' : ''}\n- Nominal task criteria: ${describeCompletion(persona, state)}\n${pressure}${curveballs}\nHow to choose your next message:\n1. Silently judge the agent's last response the way a ${persona.role} would. Is every claim defended with a specific authority, figure, or mechanism? Or is it vague, hedged, or generic?\n2. If it is vague or hand-waved — do NOT move on. Name the gap and demand the specific authority / figure / mechanism. \"It depends\" is not an answer; force the decision.\n3. If it makes a claim you can challenge — challenge it. Make the agent defend or correct it.\n4. If it missed something a ${persona.role} would catch — press on exactly that, without naming it for the agent.\n5. If it is genuinely solid — escalate: go a layer deeper, or introduce a curveball.\n6. First message — state your situation as you really would: realistic, specific, with the messy detail, but do not coach the agent.\n\nSign-off: respond with exactly \"DONE\" only when a ${persona.role} would act on this work without redoing it. Nominal task completion is NOT sign-off — sloppy-but-complete still fails. If the agent never gets there, keep pushing; never sign off on weak work.\n\nOutput ONLY your next message to the agent — in character, first person, no meta-commentary, no stage directions.`\n}\n\nexport interface DecidePersonaTurnOpts {\n persona: PersonaConfig\n state: DriverState\n /** Conversation so far — alternating user/assistant messages, oldest first. */\n history: { role: string; content: string }[]\n /** Optional product context woven into the driver prompt. */\n productContext?: string\n /** Driver model. */\n model: string\n /** Cost-ledger actor for the driver-leg call, and the served-model guard context. */\n actor: string\n /** Shared account for the paid driver call. */\n costLedger?: CostLedgerHandle\n /** Attribution tags merged into the paid-call receipt. */\n costTags?: Record<string, string>\n}\n\n/**\n * Decide the simulated user's next turn. Returns the next user message, or the\n * literal `DONE` when the simulated professional would sign off.\n */\nexport async function decidePersonaTurn(\n chat: ChatClient,\n opts: DecidePersonaTurnOpts,\n): Promise<string> {\n const { persona, state, history, productContext = '', model, actor } = opts\n\n const lastResponse =\n history.length > 0\n ? history[history.length - 1]!.content.slice(0, 2000)\n : '(no conversation yet — this is the first message)'\n\n const recentHistory = history\n .slice(-6)\n .map((h) => `${h.role}: ${h.content.slice(0, 500)}`)\n .join('\\n\\n')\n\n const request = {\n model,\n messages: [\n { role: 'system', content: buildPersonaDriverSystemPrompt(persona, state, productContext) },\n {\n role: 'user',\n content: recentHistory\n ? `Recent conversation:\\n${recentHistory}\\n\\nThe agent's latest response:\\n${lastResponse}`\n : 'No conversation yet. Send your opening message — in character, phrased as this person actually would.',\n },\n ],\n temperature: 0.5,\n maxTokens: 700,\n } satisfies ChatRequest\n const paid = await (opts.costLedger ?? new CostLedger()).runPaidCall({\n channel: 'driver',\n phase: 'driver-turn',\n actor,\n model,\n tags: opts.costTags,\n maximumCharge:\n chat.maximumAttempts === undefined\n ? undefined\n : maximumChargeForLlmRequest(request, { maximumAttempts: chat.maximumAttempts }),\n execute: (signal, callId) => chat.chat(request, { signal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n // Hold the transport to its own word: a persona turn written by a different\n // model is not this driver model's behaviour. A transport that echoes no id\n // cannot be made to prove identity here.\n assertServedModel(model, paid.value.servedModel, {\n allowUnreported: true,\n context: actor,\n })\n return paid.value.content.trim()\n}\n","/**\n * Scorecard wiring: fold a benchmark's `RunRecord[]` into agent-eval's\n * `(scenarioId x profileHash)` scorecard timeline.\n *\n * The scorecard is an append-only JSONL log, one line per (cell, commit).\n * {@link recordScorecardAndDiff} appends a run and diffs the latest entries\n * against their predecessors, answering \"did this commit regress any persona on\n * the same profile?\", which a single run's pass/fail gate cannot. The app owns\n * the behaviour-only `AgentProfile` it keys the scorecard on.\n */\n\nimport {\n agentProfileHash,\n diffScorecard,\n formatScorecardDiff,\n loadScorecard,\n recordRunsToScorecard,\n type AgentProfile,\n type RunRecord,\n type ScorecardDiff,\n} from '@tangle-network/agent-eval'\n\nexport interface ScorecardWiringInput {\n scorecardPath: string\n runs: RunRecord[]\n profile: AgentProfile\n commitSha: string\n /** Defaults to `new Date().toISOString()`. */\n timestamp?: string\n}\n\nexport interface ScorecardWiringResult {\n /** Number of cell entries appended to the log this run (one per scenario). */\n appendedCells: number\n /** Profile hash this run keyed into. */\n profileHash: string\n /** Diff of the latest entries against their predecessors. */\n diff: ScorecardDiff\n /** Human-readable diff block, what a PR or CI run prints. */\n formatted: string\n /** True when any cell's verdict is `regressed`. */\n regressed: boolean\n}\n\n/**\n * Append the run to the scorecard, fold the log, diff, and surface a\n * regression flag. Pure I/O over the JSONL log, no LLM calls. Concurrent eval\n * campaigns are safe: appends are line-atomic and `loadScorecard` skips\n * malformed lines rather than failing closed.\n */\nexport function recordScorecardAndDiff(input: ScorecardWiringInput): ScorecardWiringResult {\n const lines = recordRunsToScorecard(input.scorecardPath, input.runs, {\n profile: input.profile,\n commitSha: input.commitSha,\n timestamp: input.timestamp,\n })\n const diff = diffScorecard(loadScorecard(input.scorecardPath))\n return {\n appendedCells: lines.length,\n profileHash: agentProfileHash(input.profile),\n diff,\n formatted: formatScorecardDiff(diff),\n regressed: diff.cells.some((c) => c.verdict === 'regressed'),\n }\n}\n"],"mappings":";AA2BA,SAAS,kBAAkB,sBAAsB,mBAAmB,mCAAmC;;;ACwBvG,IAAM,cAAc;AAEpB,IAAM,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KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;AAClH,QAAI,OAAO,WAAW,EAAG,QAAO,EAAE,SAAS,MAAM,QAAQ,+EAA0E;AACnI,UAAM,QAAQ,KAAK,YAAY;AAC/B,UAAM,OAAO,OAAO,OAAO,CAAC,MAAM,MAAM,SAAS,CAAC,CAAC,EAAE;AACrD,UAAM,SAAS,OAAO,OAAO;AAC7B,WAAO,UAAU,YACb,EAAE,SAAS,MAAM,QAAQ,mBAAmB,IAAI,IAAI,OAAO,MAAM,sBAAsB,IACvF,EAAE,SAAS,OAAO,QAAQ,wBAAwB,IAAI,IAAI,OAAO,MAAM,sBAAsB;AAAA,EACnG;AACF;","names":[]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The reactive persona driver: the user side of an app's persona eval.
|
|
3
|
+
*
|
|
4
|
+
* An LLM plays the persona and decides each next message from the transcript
|
|
5
|
+
* and the run's produced state, instead of replaying a fixed turn list. It
|
|
6
|
+
* signs off with the literal `DONE` when a real practitioner would act on the
|
|
7
|
+
* work unmodified.
|
|
8
|
+
*
|
|
9
|
+
* The app owns the persona and product context; agent-eval supplies the priced
|
|
10
|
+
* call, the ledger, and the model-substitution guard. The ledger actor and the
|
|
11
|
+
* driver model are required so each app attributes and pins its own driver.
|
|
12
|
+
*/
|
|
13
|
+
import { type ChatClient, type CostLedgerHandle, type DriverState, type PersonaConfig } from '@tangle-network/agent-eval';
|
|
14
|
+
export interface DecidePersonaTurnOpts {
|
|
15
|
+
persona: PersonaConfig;
|
|
16
|
+
state: DriverState;
|
|
17
|
+
/** Conversation so far — alternating user/assistant messages, oldest first. */
|
|
18
|
+
history: {
|
|
19
|
+
role: string;
|
|
20
|
+
content: string;
|
|
21
|
+
}[];
|
|
22
|
+
/** Optional product context woven into the driver prompt. */
|
|
23
|
+
productContext?: string;
|
|
24
|
+
/** Driver model. */
|
|
25
|
+
model: string;
|
|
26
|
+
/** Cost-ledger actor for the driver-leg call, and the served-model guard context. */
|
|
27
|
+
actor: string;
|
|
28
|
+
/** Shared account for the paid driver call. */
|
|
29
|
+
costLedger?: CostLedgerHandle;
|
|
30
|
+
/** Attribution tags merged into the paid-call receipt. */
|
|
31
|
+
costTags?: Record<string, string>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Decide the simulated user's next turn. Returns the next user message, or the
|
|
35
|
+
* literal `DONE` when the simulated professional would sign off.
|
|
36
|
+
*/
|
|
37
|
+
export declare function decidePersonaTurn(chat: ChatClient, opts: DecidePersonaTurnOpts): Promise<string>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* No-spend research plan: the product-benchmark manifest an app writes before
|
|
3
|
+
* any paid cell runs (zero budget, the standard four arms), plus the small CLI
|
|
4
|
+
* helpers its `eval/research-package.ts` wrapper shares.
|
|
5
|
+
*
|
|
6
|
+
* Server-side only (node:fs). The app owns the project and benchmark ids, the
|
|
7
|
+
* profile path and the scenario list; agent-eval owns the manifest shape and
|
|
8
|
+
* the repo identity.
|
|
9
|
+
*/
|
|
10
|
+
import { type ProductBenchmarkManifest } from '@tangle-network/agent-eval';
|
|
11
|
+
/** Value of `--name value` or `--name=value`, or undefined when absent. */
|
|
12
|
+
export declare function researchCliArg(argv: readonly string[], name: string): string | undefined;
|
|
13
|
+
/** The most recently modified directory under `root`; throws when there is none. */
|
|
14
|
+
export declare function latestRunDir(root: string): string;
|
|
15
|
+
export interface ResearchPlanConfig {
|
|
16
|
+
projectId: string;
|
|
17
|
+
benchmarkId: string;
|
|
18
|
+
/** Profile id the arms attach to. */
|
|
19
|
+
profileId: string;
|
|
20
|
+
/** Repo-relative path of the product's agent profile source. */
|
|
21
|
+
agentProfilePath: string;
|
|
22
|
+
scenarios: ProductBenchmarkManifest['scenarios'];
|
|
23
|
+
}
|
|
24
|
+
/** Write `<outDir>/product-benchmark-manifest.json` with zero budget; returns its path. */
|
|
25
|
+
export declare function writeResearchPlan(outDir: string, config: ResearchPlanConfig): string;
|