@tangle-network/agent-app 0.60.35 → 0.60.36

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.
@@ -66,6 +66,19 @@ export interface NativeCompletionTurnReceipt {
66
66
  servedSource?: 'request' | 'environment' | 'profile';
67
67
  error?: string;
68
68
  }
69
+ /**
70
+ * Serialized UTF-8 budget for one terminal receipt. A Cloudflare Workflow
71
+ * refuses a step result over 1 MiB and D1 refuses a row over 2 MB, and a
72
+ * receipt approaches both as tool payloads accumulate over a long turn.
73
+ */
74
+ export declare const NATIVE_COMPLETION_RECEIPT_MAX_BYTES: number;
75
+ /**
76
+ * Fit a terminal receipt inside {@link NATIVE_COMPLETION_RECEIPT_MAX_BYTES}.
77
+ * A receipt under the budget is returned unchanged. Over it, the longest
78
+ * strings in tool payloads and reasoning are clipped with a marker, at
79
+ * successively smaller caps, so a long turn's answer is always persistable.
80
+ */
81
+ export declare function boundNativeCompletionReceipt(receipt: NativeCompletionReceipt, maxBytes?: number): NativeCompletionReceipt;
69
82
  /** Assemble admitted exact receipts in dispatch order. Missing usage stays unknown. */
70
83
  export declare function aggregateNativeCompletionReceipts(turns: readonly NativeCompletionTurnReceipt[]): NativeCompletionReceipt;
71
84
  /**
@@ -823,10 +823,11 @@ var VaultPane = forwardRef(function VaultPane2(props, ref) {
823
823
  setDeleting(false);
824
824
  }
825
825
  }, [selectedFile, port, refresh, commitPath, reportFailure]);
826
+ const shownPath = selectedFile?.path ?? null;
826
827
  useEffect2(() => {
827
- if (!displayReadyPath || !treeStateKey) return;
828
- setRecentFiles({ key: treeStateKey, paths: recordRecentFile(treeStateKey, displayReadyPath) });
829
- }, [displayReadyPath, treeStateKey]);
828
+ if (!shownPath || !treeStateKey) return;
829
+ setRecentFiles({ key: treeStateKey, paths: recordRecentFile(treeStateKey, shownPath) });
830
+ }, [shownPath, treeStateKey]);
830
831
  const recentToOffer = recentFiles.paths.filter((path) => path !== selectedPath && treePaths.files.has(path)).slice(0, RECENT_SHOWN);
831
832
  const createFileName = newPath.trim().split("/").pop()?.trim() ?? "";
832
833
  const dockButtonLabel = persistentDock ? dockLabel : dockToggleCfg.label;
@@ -1209,4 +1210,4 @@ export {
1209
1210
  ConfirmDialog,
1210
1211
  VaultPane
1211
1212
  };
1212
- //# sourceMappingURL=chunk-FMX3IOJM.js.map
1213
+ //# sourceMappingURL=chunk-QBNV6BJ4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vault/VaultPane.tsx","../src/vault/ConfirmDialog.tsx","../src/vault/recent-files.ts"],"sourcesContent":["/**\n * The shared 3-pane vault: tree | artifact viewer | optional agent dock. This is\n * shell mechanism — selection, the dirty-guard + pending-nav state machine,\n * rich/source editor modes, create/delete/refresh, skeletons, and an error\n * boundary — plus the vault's tree (sandbox-ui's `VaultTree`) in a contained surface. It\n * renders no artifact viewer of its own: that arrives through the\n * `renderArtifact` / `renderDock` seams, and `renderTree` can replace the tree.\n *\n * Data flows exclusively through `port` (a `VaultDataPort`). The pane never\n * imports a fetch client, a router, a toast system, or a markdown library — the\n * optional `codec` seam supplies rich/source parsing (identity passthrough by\n * default). Chrome uses the shared theme tokens (bg-card, border-border, …).\n */\n\nimport {\n Component,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useLayoutEffect,\n useId,\n useMemo,\n useRef,\n useState,\n type ErrorInfo,\n type ReactNode,\n} from 'react'\nimport { Download, FileText, Folder, Plus, RefreshCw, Trash2 } from 'lucide-react'\nimport { ConfirmDialog } from './ConfirmDialog'\nimport { readRecentFiles, recordRecentFile } from './recent-files'\nimport { filterFileNodes, VaultTree } from '@tangle-network/sandbox-ui/vault-tree'\nimport type {\n VaultEditorMode,\n VaultFile,\n VaultMarkdownCodec,\n VaultOperation,\n VaultOperationFailure,\n VaultOperationPhase,\n VaultPaneHandle,\n VaultPaneProps,\n VaultRichParts,\n VaultTreeNode,\n} from './contracts'\n\n/** Narrowest pane that places a dock beside the document rather than in it. */\nconst DOCK_SIDE_MIN_PX = 960\n\n/** Square header action on the control scale's small step, a touch target on coarse pointers. */\nconst TREE_ICON_BUTTON = 'inline-flex size-8 shrink-0 items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [@media(pointer:coarse)]:size-10'\n\nconst IDENTITY_CODEC: VaultMarkdownCodec = {\n parse: (raw) => raw,\n serialize: (parts) => (typeof parts === 'string' ? parts : String(parts ?? '')),\n}\n\ntype PendingNav = { path: string; request?: PendingOpen } | null\ntype PendingOpen = {\n path: string\n fromPath: string | null\n resolve: (opened: boolean) => void\n loaded: boolean\n selected: boolean\n}\n\ninterface TreeRefreshContext {\n operation: Extract<VaultOperation, 'list' | 'create' | 'delete'>\n phase: VaultOperationPhase\n path?: string\n selectAfterRecovery?: string\n}\n\ninterface TreeFailureState {\n failure: VaultOperationFailure\n context: TreeRefreshContext\n}\n\nconst LIST_CONTEXT: TreeRefreshContext = { operation: 'list', phase: 'operation' }\n\nfunction operationMessage(error: unknown, fallback: string): string {\n return error instanceof Error && error.message ? error.message : fallback\n}\n\nfunction treeFailureMessage(failure: VaultOperationFailure, label: string): string {\n if (failure.phase !== 'post-mutation-refresh') return failure.message\n const completed = failure.operation === 'create' ? 'created' : 'deleted'\n return `The file was ${completed}, but ${label} couldn't refresh. ${failure.message}`\n}\n\ninterface TreePaths {\n files: Set<string>\n directories: Set<string>\n}\n\n// Directories are collected alongside files because a click on one has to be\n// RECOGNIZED to be answered — dropping them here is what made a folder row a\n// dead target: the path resolved to nothing and every downstream branch was\n// keyed on a file.\nfunction collectTreePaths(nodes: VaultTreeNode[], into: TreePaths): TreePaths {\n for (const node of nodes) {\n if (node.type === 'file') into.files.add(node.path)\n else into.directories.add(node.path)\n if (node.children) collectTreePaths(node.children, into)\n }\n return into\n}\n\nfunction resolveFilePath(rawPath: string, filePaths: Set<string>): string | null {\n if (filePaths.has(rawPath)) return rawPath\n const path = rawPath.replace(/^\\/+|\\/+$/g, '')\n return filePaths.has(path) ? path : null\n}\n\nfunction resolveTreePath(rawPath: string, paths: TreePaths): { path: string; type: 'file' | 'directory' } | null {\n const file = resolveFilePath(rawPath, paths.files)\n if (file) return { path: file, type: 'file' }\n if (paths.directories.has(rawPath)) return { path: rawPath, type: 'directory' }\n const trimmed = rawPath.replace(/^\\/+|\\/+$/g, '')\n return paths.directories.has(trimmed) ? { path: trimmed, type: 'directory' } : null\n}\n\nfunction findDirectory(nodes: VaultTreeNode[], path: string): VaultTreeNode | null {\n for (const node of nodes) {\n if (node.type === 'directory' && node.path === path) return node\n const found = node.children ? findDirectory(node.children, path) : null\n if (found) return found\n }\n return null\n}\n\nclass EditorErrorBoundary extends Component<{ children: ReactNode; label: string; onReset?: () => void }, { error: unknown }> {\n state: { error: unknown } = { error: null }\n static getDerivedStateFromError(error: unknown) {\n return { error }\n }\n componentDidCatch(error: unknown, info: ErrorInfo) {\n console.error('Vault crashed:', error, info)\n }\n render() {\n if (this.state.error) {\n const msg = this.state.error instanceof Error\n ? this.state.error.message\n : typeof this.state.error === 'string'\n ? this.state.error\n : `${this.props.label} did not load. Reload the page to try again.`\n return (\n <div className=\"flex h-full flex-1 flex-col items-center justify-center p-8 text-center\">\n <h3 className=\"mb-1 text-sm font-medium text-foreground\">{this.props.label} failed to load</h3>\n <p className=\"mb-4 max-w-xs text-xs text-muted-foreground\">{String(msg)}</p>\n <button\n type=\"button\"\n onClick={() => { this.setState({ error: null }); this.props.onReset?.() }}\n className=\"inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted\"\n >\n Try again\n </button>\n </div>\n )\n }\n return this.props.children\n }\n}\n\n/**\n * A skeleton is a picture of a wait, and a picture is exactly what a screen\n * reader cannot see. `aria-hidden` on the shimmer bars is right — they carry no\n * information — but hiding them without saying anything else is what left the\n * whole load silent. The container announces the wait instead: `aria-busy` for\n * the state, a `status` live region so arrival is reported, and a real text\n * label, since a live region with only decorative children announces nothing.\n */\nfunction SkeletonRegion({ label, className, children }: { label: string; className: string; children: ReactNode }) {\n // The live region is a SIBLING of the shimmer, not a wrapper around it: the\n // shimmer container keeps its exact classes and its exact position in the\n // parent's layout, so adding the announcement cannot move a pixel. Wrapping\n // it would put a new box between `space-y-*` and the bars it spaces.\n return (\n <>\n <span role=\"status\" aria-live=\"polite\" aria-busy={true} className=\"sr-only\">\n {label}\n </span>\n <div className={className} aria-hidden=\"true\">\n {children}\n </div>\n </>\n )\n}\n\nfunction TreeSkeleton() {\n return (\n <SkeletonRegion label=\"Loading files…\" className=\"space-y-2 p-4\">\n {[32, 48, 40, 52].map((w, i) => (\n <div key={i} className=\"h-4 animate-pulse rounded bg-muted\" style={{ width: `${w * 4}px` }} />\n ))}\n </SkeletonRegion>\n )\n}\n\nfunction EditorSkeleton() {\n return (\n <SkeletonRegion label=\"Loading file…\" className=\"space-y-3 p-8\">\n <div className=\"h-5 w-1/2 animate-pulse rounded bg-muted\" />\n <div className=\"h-4 w-full animate-pulse rounded bg-muted\" />\n <div className=\"h-4 w-3/4 animate-pulse rounded bg-muted\" />\n <div className=\"h-4 w-2/3 animate-pulse rounded bg-muted\" />\n </SkeletonRegion>\n )\n}\n\nfunction ReadErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {\n return (\n <div className=\"flex h-full flex-col items-center justify-center gap-3 p-8 text-center\">\n <div>\n <h3 className=\"text-sm font-medium text-foreground\">Couldn't open this file</h3>\n <p className=\"mt-1 max-w-md text-xs text-muted-foreground\">{message}</p>\n </div>\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted\"\n >\n Retry\n </button>\n </div>\n )\n}\n\nfunction TreeErrorState({ label, message, onRetry }: { label: string; message: string; onRetry: () => void }) {\n return (\n <div role=\"alert\" className=\"flex h-full flex-col items-center justify-center gap-3 p-6 text-center\">\n <div>\n <h3 className=\"text-sm font-medium text-foreground\">Couldn't load {label}</h3>\n <p className=\"mt-1 max-w-xs text-xs text-muted-foreground\">{message}</p>\n </div>\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted\"\n >\n Retry\n </button>\n </div>\n )\n}\n\n/**\n * The tree pane when the vault holds nothing at all. It sits under the header\n * whose controls add files, so it names the state and offers the same action\n * instead of leaving a blank column under a search box with nothing to search.\n */\nfunction TreeEmptyState({ canCreate, onCreate }: { canCreate: boolean; onCreate: () => void }) {\n return (\n <div className=\"flex h-full flex-col items-center justify-center gap-3 p-6 text-center\">\n <div>\n <h3 className=\"text-sm font-medium text-foreground\">No files yet</h3>\n <p className=\"mt-1 max-w-xs text-xs text-muted-foreground\">\n {canCreate ? 'Create a file to start.' : 'Files appear here once they are added.'}\n </p>\n </div>\n {canCreate && (\n <button\n type=\"button\"\n onClick={onCreate}\n className=\"inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90\"\n >\n <Plus className=\"h-3.5 w-3.5\" aria-hidden=\"true\" />\n New file\n </button>\n )}\n </div>\n )\n}\n\nfunction TreeNoMatchState({ query, onClear }: { query: string; onClear: () => void }) {\n return (\n <div className=\"flex flex-col items-center gap-3 p-6 text-center\">\n <p className=\"max-w-xs break-words text-xs text-muted-foreground\">No files match “{query}”.</p>\n <button\n type=\"button\"\n onClick={onClear}\n className=\"inline-flex h-8 items-center rounded-md border border-border px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted\"\n >\n Clear search\n </button>\n </div>\n )\n}\n\nfunction OperationErrorAlert({\n message,\n retryLabel,\n onRetry,\n onDismiss,\n}: {\n message: string\n retryLabel: string\n onRetry: () => void\n onDismiss: () => void\n}) {\n return (\n <div\n role=\"alert\"\n className=\"flex shrink-0 items-center justify-between gap-3 border-b border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-[var(--surface-danger-text)]\"\n >\n <span className=\"min-w-0 flex-1\">{message}</span>\n <div className=\"flex shrink-0 items-center gap-3\">\n <button type=\"button\" aria-label={retryLabel} onClick={onRetry} className=\"font-medium underline-offset-2 hover:underline\">\n Retry\n </button>\n <button type=\"button\" onClick={onDismiss} className=\"underline-offset-2 hover:underline\">\n Dismiss\n </button>\n </div>\n </div>\n )\n}\n\n/** How many recent files the empty document pane offers. */\nconst RECENT_SHOWN = 5\n\n/**\n * The document pane with nothing open: says what to do, and offers the files\n * this reader opened last in this vault so returning work is one click away.\n */\nfunction DocumentEmptyState({ label, recent, onOpen }: { label: string; recent: string[]; onOpen: (path: string) => void }) {\n const recentHeadingId = useId()\n return (\n <div data-vault-document-empty className=\"flex h-full items-center justify-center overflow-y-auto p-8\">\n <div className=\"w-full max-w-sm text-center\">\n <span className=\"mx-auto flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground\">\n <FileText className=\"size-5\" aria-hidden=\"true\" />\n </span>\n <h3 className=\"mt-4 text-base font-semibold text-foreground\">Select a file</h3>\n <p className=\"mt-1 text-sm text-muted-foreground\">Choose a file in {label} to open it here.</p>\n {recent.length > 0 && (\n <section aria-labelledby={recentHeadingId} className=\"mt-8 text-left\">\n <h4 id={recentHeadingId} className=\"text-xs font-medium text-muted-foreground\">Recently opened</h4>\n <ul className=\"mt-2 overflow-hidden rounded-xl border border-border bg-card shadow-raised\">\n {recent.map((path) => {\n const slash = path.lastIndexOf('/')\n return (\n <li key={path} className=\"border-b border-border last:border-b-0\">\n <button\n type=\"button\"\n onClick={() => onOpen(path)}\n title={path}\n className=\"flex min-h-10 w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\"\n >\n <FileText className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <span className=\"min-w-0 truncate font-medium\">{path.slice(slash + 1)}</span>\n {slash > 0 && <span className=\"ml-auto min-w-0 shrink truncate text-xs text-muted-foreground\">{path.slice(0, slash)}</span>}\n </button>\n </li>\n )\n })}\n </ul>\n </section>\n )}\n </div>\n </div>\n )\n}\n\n/**\n * Browse and edit files in the available pane width.\n * Below 45rem, Files and the selected document share one pane.\n * Switching panes keeps the editor mounted and preserves unsaved changes.\n */\nexport const VaultPane = forwardRef<VaultPaneHandle, VaultPaneProps>(function VaultPane(props, ref) {\n const {\n port,\n renderTree,\n treeStateKey,\n renderArtifact,\n renderDock,\n canWrite = true,\n selectedPath: controlledPath,\n onSelectedPathChange,\n onOperationError,\n codec,\n className,\n dockToggle,\n refreshKey,\n headerActions,\n onDownloadFile,\n pathBarClassName,\n label = 'Vault',\n emptyState,\n treeEmptyState,\n dockLabel = 'Details',\n fileActions,\n } = props\n const noun = label.toLowerCase()\n const canCreate = canWrite && (props.canCreate ?? true)\n const canDelete = canWrite && (props.canDelete ?? true)\n\n const activeCodec = codec ?? IDENTITY_CODEC\n const controlled = controlledPath !== undefined\n const isMarkdownCapable = codec !== undefined\n // `false` → a persistent dock (no toggle, always open with the selected file).\n const persistentDock = dockToggle === false\n const dockToggleCfg = dockToggle ? dockToggle : { label: 'Discuss', disabledWhenDirty: true }\n\n const [tree, setTree] = useState<VaultTreeNode[]>([])\n const [treeLoading, setTreeLoading] = useState(true)\n const [treeLoaded, setTreeLoaded] = useState(false)\n const [treeError, setTreeError] = useState<TreeFailureState | null>(null)\n const [internalPath, setInternalPath] = useState<string | null>(null)\n const selectedPath = controlled ? (controlledPath ?? null) : internalPath\n const [filesOpen, setFilesOpen] = useState(false)\n const showFiles = filesOpen || !selectedPath\n const searchRef = useRef<HTMLInputElement>(null)\n const documentRef = useRef<HTMLDivElement>(null)\n const treeHeadingId = useId()\n const [recentFiles, setRecentFiles] = useState(() => ({ key: treeStateKey, paths: readRecentFiles(treeStateKey) }))\n if (recentFiles.key !== treeStateKey) setRecentFiles({ key: treeStateKey, paths: readRecentFiles(treeStateKey) })\n\n useEffect(() => {\n setFilesOpen(false)\n }, [selectedPath])\n\n const showDocument = useCallback(() => {\n const focused = document.activeElement\n setFilesOpen(false)\n requestAnimationFrame(() => {\n if (document.activeElement === focused || document.activeElement === document.body) {\n documentRef.current?.focus({ preventScroll: true })\n }\n })\n }, [])\n\n const [selectedFile, setSelectedFile] = useState<VaultFile | null>(null)\n const [displayReadyPath, setDisplayReadyPath] = useState<string | null>(null)\n const [fileLoading, setFileLoading] = useState(false)\n const [readError, setReadError] = useState<string | null>(null)\n const [reloadNonce, setReloadNonce] = useState(0)\n const [saving, setSaving] = useState(false)\n const [saveError, setSaveError] = useState<VaultOperationFailure | null>(null)\n\n const [editorMode, setEditorMode] = useState<VaultEditorMode>('rich')\n const [richDraft, setRichDraft] = useState<VaultRichParts>('')\n const [sourceDraft, setSourceDraft] = useState('')\n const [isDirty, setIsDirty] = useState(false)\n\n const [createOpen, setCreateOpen] = useState(false)\n const [newPath, setNewPath] = useState('')\n const [creating, setCreating] = useState(false)\n const [createError, setCreateError] = useState<VaultOperationFailure | null>(null)\n const [deleteOpen, setDeleteOpen] = useState(false)\n const [deleting, setDeleting] = useState(false)\n const [deleteError, setDeleteError] = useState<VaultOperationFailure | null>(null)\n const [dockOpen, setDockOpen] = useState(false)\n // Below DOCK_SIDE_MIN_PX of pane width a side dock squeezes the document to\n // nothing (measured on Legal at 390px: the review panel took the whole width\n // and the document and its Files switcher were unreachable). There the dock\n // opens IN the document pane instead, behind a path-bar toggle. Measured, not\n // a media query: the pane is often a drawer or a split inside a wide window.\n const rootRef = useRef<HTMLDivElement>(null)\n const [dockInline, setDockInline] = useState(false)\n useLayoutEffect(() => {\n const root = rootRef.current\n if (!root || !renderDock || typeof ResizeObserver === 'undefined') return\n const apply = (width: number) => { if (width > 0) setDockInline(width < DOCK_SIDE_MIN_PX) }\n apply(root.getBoundingClientRect().width)\n const observer = new ResizeObserver((entries) => apply(entries[0]?.contentRect.width ?? 0))\n observer.observe(root)\n return () => observer.disconnect()\n }, [renderDock])\n const [pendingNav, setPendingNav] = useState<PendingNav>(null)\n const [query, setQuery] = useState('')\n const [folderPath, setFolderPath] = useState<string | null>(null)\n\n const dirtyRef = useRef(isDirty)\n dirtyRef.current = isDirty\n const treeRequestRef = useRef(0)\n const savedContentRef = useRef('')\n const loadedPathRef = useRef<string | null>(null)\n const onOperationErrorRef = useRef(onOperationError)\n onOperationErrorRef.current = onOperationError\n const pendingOpenRef = useRef<PendingOpen | null>(null)\n const previousPortRef = useRef(port)\n\n const finishPendingOpen = useCallback((opened: boolean, clearNavigation = true) => {\n const pending = pendingOpenRef.current\n if (!pending) return\n pendingOpenRef.current = null\n if (!opened && clearNavigation) {\n setPendingNav((current) => current?.request === pending ? null : current)\n }\n pending.resolve(opened)\n }, [])\n\n useEffect(() => () => finishPendingOpen(false, false), [finishPendingOpen])\n\n useEffect(() => {\n if (previousPortRef.current !== port) finishPendingOpen(false)\n previousPortRef.current = port\n }, [port, finishPendingOpen])\n\n useEffect(() => {\n const pending = pendingOpenRef.current\n if (!pending) return\n if (selectedPath === pending.path) pending.selected = true\n else if (pending.selected || selectedPath !== pending.fromPath) finishPendingOpen(false)\n }, [selectedPath, finishPendingOpen])\n\n const treePaths = useMemo(\n () => collectTreePaths(tree, { files: new Set<string>(), directories: new Set<string>() }),\n [tree],\n )\n const resolvedSelectedPath = useMemo(() => {\n if (!selectedPath) return null\n const listed = resolveTreePath(selectedPath, treePaths)\n if (listed?.type === 'directory') return null\n // A committed file can be readable before an older tree snapshot lists it.\n // The data port owns validation and missing-file errors for explicit paths.\n return listed?.path ?? selectedPath\n }, [selectedPath, treePaths])\n // The clicked folder, resolved against the CURRENT tree — a folder that a\n // refresh removed stops being the active one on its own, so neither the\n // search scope nor the create target can point at a directory that is gone.\n const activeFolderNode = useMemo(\n () => (folderPath ? findDirectory(tree, folderPath) : null),\n [tree, folderPath],\n )\n const activeFolder = activeFolderNode?.path ?? null\n const treeRoot = useMemo<VaultTreeNode>(\n () => ({ name: label, path: '', type: 'directory', children: tree }),\n [tree, label],\n )\n // With no query the whole vault stays on screen: the tree owns expansion, so\n // re-rooting on a plain folder click would fight the expand the click already\n // performs. The folder scopes the SEARCH, which is where a narrowed list is\n // what the reader asked for.\n const visibleRoot = useMemo<VaultTreeNode>(() => {\n const q = query.trim().toLowerCase()\n if (!q) return treeRoot\n const base = activeFolderNode ?? treeRoot\n return { ...base, children: filterFileNodes(base.children ?? [], q) }\n }, [treeRoot, activeFolderNode, query])\n\n const commitPath = useCallback(\n (next: string | null) => {\n if (controlled) {\n const decision: unknown = onSelectedPathChange?.(next)\n return decision !== false\n }\n setInternalPath(next)\n onSelectedPathChange?.(next)\n return true\n },\n [controlled, onSelectedPathChange],\n )\n\n const reportFailure = useCallback((\n operation: VaultOperation,\n phase: VaultOperationPhase,\n error: unknown,\n fallback: string,\n path?: string,\n ): VaultOperationFailure => {\n const failure: VaultOperationFailure = {\n operation,\n phase,\n path,\n message: operationMessage(error, fallback),\n cause: error,\n }\n try {\n onOperationErrorRef.current?.(failure)\n } catch (callbackError) {\n console.error('Vault onOperationError callback failed:', callbackError)\n }\n return failure\n }, [])\n\n const refresh = useCallback(async (context: TreeRefreshContext = LIST_CONTEXT): Promise<boolean> => {\n const request = ++treeRequestRef.current\n setTreeLoading(true)\n setTreeError(null)\n try {\n const nextTree = await port.listTree()\n if (request !== treeRequestRef.current) return false\n setTree(nextTree)\n setTreeLoaded(true)\n return true\n } catch (error) {\n if (request !== treeRequestRef.current) return false\n const failure = reportFailure(\n context.operation,\n context.phase,\n error,\n `Failed to load ${label}`,\n context.path,\n )\n setTreeError({ failure, context })\n return false\n } finally {\n if (request === treeRequestRef.current) setTreeLoading(false)\n }\n }, [port, reportFailure, label])\n\n useEffect(() => {\n setTree([])\n setTreeLoaded(false)\n setTreeError(null)\n setSelectedFile(null)\n }, [port])\n\n useEffect(() => {\n void refresh()\n return () => { treeRequestRef.current += 1 }\n }, [refresh, refreshKey])\n\n const retryTree = useCallback(async () => {\n if (!treeError) return\n const { context } = treeError\n const recovered = await refresh(context)\n if (recovered && context.selectAfterRecovery) commitPath(context.selectAfterRecovery)\n }, [treeError, refresh, commitPath])\n\n useEffect(() => {\n if (!selectedPath) {\n setSelectedFile(null)\n setFileLoading(false)\n setReadError(null)\n loadedPathRef.current = null\n return\n }\n // An external path can be read after listing fails; the data port still validates access.\n const explicitOpenAfterTreeError = !!treeError && pendingOpenRef.current?.path === selectedPath\n if (treeLoading || (!treeLoaded && !explicitOpenAfterTreeError) || isDirty || saving) return\n if (!resolvedSelectedPath) {\n finishPendingOpen(false)\n commitPath(null)\n setSelectedFile(null)\n setFileLoading(false)\n setReadError(null)\n loadedPathRef.current = null\n return\n }\n let cancelled = false\n const path = resolvedSelectedPath\n if (path !== selectedPath) commitPath(path)\n setFileLoading(true)\n setReadError(null)\n void (async () => {\n try {\n const file = await port.readFile(path)\n if (file.path !== path) throw new Error(`Vault returned ${file.path} for ${path}`)\n if (!cancelled && !dirtyRef.current) {\n const pending = pendingOpenRef.current\n if (pending?.path === path) pending.loaded = true\n setSelectedFile(file)\n } else if (!cancelled && pendingOpenRef.current?.path === path) {\n finishPendingOpen(false)\n }\n } catch (err) {\n // Surface read failures instead of making them indistinguishable from\n // the intentionally empty \"no file selected\" state.\n if (!cancelled) {\n if (pendingOpenRef.current?.path === path) finishPendingOpen(false)\n const failure = reportFailure('read', 'operation', err, 'Failed to read file', path)\n setSelectedFile((current) => current?.path === path ? current : null)\n setReadError(failure.message)\n }\n } finally {\n if (!cancelled) setFileLoading(false)\n }\n })()\n return () => {\n cancelled = true\n }\n }, [port, selectedPath, resolvedSelectedPath, treeLoading, treeLoaded, treeError, isDirty, saving, reloadNonce, commitPath, reportFailure, finishPendingOpen])\n\n useEffect(() => {\n if (!selectedFile) {\n loadedPathRef.current = null\n setDisplayReadyPath(null)\n savedContentRef.current = ''\n setRichDraft('')\n setSourceDraft('')\n setEditorMode('rich')\n setIsDirty(false)\n setSaveError(null)\n return\n }\n const pathChanged = loadedPathRef.current !== selectedFile.path\n loadedPathRef.current = selectedFile.path\n setDisplayReadyPath(selectedFile.path)\n savedContentRef.current = selectedFile.content\n setRichDraft(activeCodec.parse(selectedFile.content))\n setSourceDraft(selectedFile.content)\n if (pathChanged) setEditorMode('rich')\n setIsDirty(false)\n setSaveError(null)\n setDockOpen(false)\n }, [selectedFile?.path, selectedFile?.content, activeCodec])\n\n useEffect(() => {\n const pending = pendingOpenRef.current\n if (\n pending?.loaded &&\n pending.path === selectedPath &&\n selectedFile?.path === pending.path &&\n displayReadyPath === pending.path &&\n sourceDraft === selectedFile.content &&\n !fileLoading\n ) {\n finishPendingOpen(true)\n }\n }, [selectedPath, selectedFile, displayReadyPath, sourceDraft, fileLoading, finishPendingOpen])\n\n const guardedOpen = useCallback((rawPath: string, resolve?: (opened: boolean) => void) => {\n const target = resolveTreePath(rawPath, treePaths)\n if (!rawPath.trim() || target?.type === 'directory') {\n resolve?.(false)\n return\n }\n const path = target?.path ?? rawPath\n finishPendingOpen(false)\n setPendingNav(null)\n if (path === selectedPath && selectedFile?.path === path && displayReadyPath === path) {\n showDocument()\n resolve?.(true)\n return\n }\n if (resolve) {\n const pending: PendingOpen = {\n path,\n fromPath: selectedPath,\n resolve,\n loaded: false,\n selected: path === selectedPath,\n }\n pendingOpenRef.current = pending\n }\n if (path === selectedPath) {\n showDocument()\n if (!fileLoading && (readError || (treeError && !treeLoaded))) setReloadNonce((nonce) => nonce + 1)\n return\n }\n if (isDirty) {\n setPendingNav({ path, request: resolve ? pendingOpenRef.current ?? undefined : undefined })\n return\n }\n showDocument()\n if (commitPath(path) === false) finishPendingOpen(false)\n }, [finishPendingOpen, treePaths, selectedPath, selectedFile, displayReadyPath, fileLoading, showDocument, readError, treeError, treeLoaded, isDirty, commitPath])\n\n useImperativeHandle(ref, () => ({\n openFile: (path) => new Promise<boolean>((resolve) => guardedOpen(path, resolve)),\n }), [guardedOpen])\n\n // Clicking a folder makes it the vault's active folder: the search narrows to\n // it and a new file lands inside it. Clicking it again clears that — the same\n // row is the way back out, so the gesture is reversible where it was made.\n const toggleFolder = useCallback((path: string) => {\n setFolderPath((current) => (current === path ? null : path))\n }, [])\n // The built-in tree reports the folder's new state: expanding a folder makes\n // it active, and collapsing the active folder or one around it clears it.\n const handleFolderToggle = useCallback((path: string, expanded: boolean) => {\n setFolderPath((current) => {\n if (expanded) return path\n return current && (current === path || current.startsWith(`${path}/`)) ? null : current\n })\n }, [])\n\n // Some tree models keep their original selection callback while resetting\n // paths internally. Keep the callable stable, but have it execute the latest\n // path validation and dirty-guard logic.\n const selectFileRef = useRef<(path: string) => void>(() => {})\n selectFileRef.current = (rawPath: string) => {\n const target = resolveTreePath(rawPath, treePaths)\n if (!target) return\n if (target.type === 'file') {\n guardedOpen(target.path)\n return\n }\n toggleFolder(target.path)\n }\n const handleTreeSelect = useCallback((path: string) => selectFileRef.current(path), [])\n\n const confirmDiscard = useCallback(() => {\n const nav = pendingNav\n setPendingNav(null)\n if (!nav) return\n if (nav.request && pendingOpenRef.current !== nav.request) return\n if (!commitPath(nav.path)) {\n finishPendingOpen(false)\n return\n }\n setIsDirty(false)\n showDocument()\n }, [pendingNav, commitPath, showDocument, finishPendingOpen])\n\n const showRichMode = useCallback(() => {\n setEditorMode((mode) => {\n if (mode === 'rich') return mode\n setRichDraft(activeCodec.parse(sourceDraft))\n setIsDirty(sourceDraft !== savedContentRef.current)\n return 'rich'\n })\n }, [activeCodec, sourceDraft])\n\n const showSourceMode = useCallback(() => {\n setEditorMode((mode) => {\n if (mode === 'source') return mode\n const content = isDirty ? activeCodec.serialize(richDraft) : savedContentRef.current\n setSourceDraft(content)\n setIsDirty(content !== savedContentRef.current)\n return 'source'\n })\n }, [activeCodec, isDirty, richDraft])\n\n const onSourceChange = useCallback((next: string) => {\n dirtyRef.current = next !== savedContentRef.current\n setSourceDraft(next)\n setIsDirty(dirtyRef.current)\n }, [])\n\n const onRichChange = useCallback((next: VaultRichParts) => {\n dirtyRef.current = activeCodec.serialize(next) !== savedContentRef.current\n setRichDraft(next)\n setIsDirty(dirtyRef.current)\n }, [activeCodec])\n\n const saveCurrent = useCallback(async () => {\n if (!selectedFile) return\n const content = editorMode === 'source' ? sourceDraft : activeCodec.serialize(richDraft)\n setSaving(true)\n setSaveError(null)\n try {\n await port.writeFile(selectedFile.path, content)\n savedContentRef.current = content\n setSelectedFile({ ...selectedFile, content })\n setSourceDraft(content)\n setRichDraft(activeCodec.parse(content))\n setIsDirty(false)\n } catch (error) {\n setSaveError(reportFailure('save', 'operation', error, 'Failed to save file', selectedFile.path))\n } finally {\n setSaving(false)\n }\n }, [selectedFile, editorMode, sourceDraft, richDraft, activeCodec, port, reportFailure])\n\n const handleCreate = useCallback(async () => {\n const trimmed = newPath.trim()\n // Same rule as the confirm button, enforced here too: the dialog can also be\n // confirmed by keyboard, and a directory path is not a file to create.\n if (!trimmed || !(trimmed.split('/').pop()?.trim())) return\n setCreating(true)\n setCreateError(null)\n try {\n const created = await port.createFile(trimmed)\n setCreateOpen(false)\n setNewPath('')\n const refreshed = await refresh({\n operation: 'create',\n phase: 'post-mutation-refresh',\n path: created,\n selectAfterRecovery: created,\n })\n if (refreshed) commitPath(created)\n } catch (error) {\n setCreateError(reportFailure('create', 'operation', error, 'Failed to create file', trimmed))\n } finally {\n setCreating(false)\n }\n }, [newPath, port, refresh, commitPath, reportFailure])\n\n const handleDelete = useCallback(async () => {\n if (!selectedFile) return\n const path = selectedFile.path\n setDeleting(true)\n setDeleteError(null)\n try {\n await port.deleteFile(path)\n setDeleteOpen(false)\n setIsDirty(false)\n commitPath(null)\n setSelectedFile(null)\n await refresh({ operation: 'delete', phase: 'post-mutation-refresh', path })\n } catch (error) {\n setDeleteError(reportFailure('delete', 'operation', error, 'Failed to delete file', path))\n } finally {\n setDeleting(false)\n }\n }, [selectedFile, port, refresh, commitPath, reportFailure])\n\n // A file counts as opened once it is on screen, not when it is requested.\n // It is recorded in the commit that first shows it: `displayReadyPath` trails\n // that commit by one render, so a pane closed right after showing a file\n // (or a reader who navigates away at once) lost the record.\n const shownPath = selectedFile?.path ?? null\n useEffect(() => {\n if (!shownPath || !treeStateKey) return\n setRecentFiles({ key: treeStateKey, paths: recordRecentFile(treeStateKey, shownPath) })\n }, [shownPath, treeStateKey])\n const recentToOffer = recentFiles.paths\n .filter((path) => path !== selectedPath && treePaths.files.has(path))\n .slice(0, RECENT_SHOWN)\n\n const createFileName = newPath.trim().split('/').pop()?.trim() ?? ''\n const dockButtonLabel = persistentDock ? dockLabel : dockToggleCfg.label\n const dockBlockedByDraft = !persistentDock && (dockToggleCfg.disabledWhenDirty ?? true) && isDirty\n const openCreate = () => { setCreateError(null); setNewPath(activeFolder ? `${activeFolder}/` : ''); setCreateOpen(true) }\n // A loaded vault with nothing in it has no document to show beside the tree,\n // so the tree pane takes the whole width and carries the empty state. A\n // selected path still opens the document pane: a committed file can be\n // readable before the tree lists it.\n const vaultEmpty = treeLoaded && treePaths.files.size === 0 && treePaths.directories.size === 0\n const treeSpansPane = vaultEmpty && !selectedPath\n const trimmedQuery = query.trim()\n\n let treeContent: ReactNode\n if (!treeLoaded && (treeLoading || !treeError)) {\n treeContent = <TreeSkeleton />\n } else if (!treeLoaded && treeError) {\n treeContent = <TreeErrorState label={label} message={treeFailureMessage(treeError.failure, label)} onRetry={() => void retryTree()} />\n } else {\n treeContent = (\n <>\n {treeError && (\n <OperationErrorAlert\n message={treeFailureMessage(treeError.failure, label)}\n retryLabel={`Retry ${noun} refresh`}\n onRetry={() => void retryTree()}\n onDismiss={() => setTreeError(null)}\n />\n )}\n {vaultEmpty && !trimmedQuery\n ? (treeEmptyState !== undefined ? treeEmptyState : <TreeEmptyState canCreate={canCreate} onCreate={openCreate} />)\n : trimmedQuery && (visibleRoot.children?.length ?? 0) === 0\n ? <TreeNoMatchState query={trimmedQuery} onClear={() => setQuery('')} />\n : renderTree\n ? renderTree({\n root: visibleRoot,\n selectedPath: resolvedSelectedPath ?? undefined,\n onSelect: handleTreeSelect,\n })\n : (\n <VaultTree\n root={visibleRoot}\n selectedPath={resolvedSelectedPath ?? undefined}\n activeFolder={activeFolder}\n onSelect={handleTreeSelect}\n onFolderToggle={handleFolderToggle}\n storageKey={treeStateKey}\n expandAll={!!trimmedQuery}\n label={label}\n />\n )}\n </>\n )\n }\n\n return (\n <EditorErrorBoundary label={label} onReset={() => { commitPath(null); setSelectedFile(null) }}>\n <div ref={rootRef} className={`flex min-h-0 min-w-0 flex-1 overflow-hidden ${className ?? ''}`}>\n <div className=\"@container/vault flex min-w-0 flex-1 flex-col\">\n {/* The pane switcher exists only while there is a document to switch\n to; with nothing selected the Files pane is already all there is,\n and a lone Files chip would be a control that does nothing. */}\n {selectedPath && (\n <nav aria-label={`${label} navigation`} className=\"flex shrink-0 items-center gap-1 border-b border-border p-2 @[45rem]/vault:hidden\">\n <button\n type=\"button\"\n aria-pressed={showFiles}\n onClick={() => {\n const focused = document.activeElement\n setFilesOpen(true)\n requestAnimationFrame(() => {\n if (document.activeElement === focused || document.activeElement === document.body) {\n searchRef.current?.focus()\n }\n })\n }}\n className={`shrink-0 rounded-md px-3 py-2 text-sm ${showFiles ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted'}`}\n >\n Files\n </button>\n {selectedPath && (\n <button\n type=\"button\"\n aria-pressed={!showFiles}\n onClick={showDocument}\n title={selectedPath}\n className={`min-w-0 truncate rounded-md px-3 py-2 text-sm ${!showFiles ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted'}`}\n >\n {selectedPath.split('/').pop()}\n </button>\n )}\n </nav>\n )}\n <div className=\"flex min-h-0 min-w-0 flex-1\">\n <div data-vault-tree className={`${showFiles ? 'flex' : 'hidden'} min-w-0 flex-1 flex-col p-2 @[45rem]/vault:flex @[45rem]/vault:p-3 ${treeSpansPane ? '' : '@[45rem]/vault:w-[23rem] @[45rem]/vault:min-w-[23rem] @[45rem]/vault:flex-none'}`}>\n {/* The tree is its own surface: a card on the page background,\n so the file list reads as a finished panel rather than\n text floating on the canvas. */}\n <section\n aria-labelledby={treeHeadingId}\n data-vault-tree-surface\n className=\"flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-raised\"\n >\n <div className=\"flex shrink-0 items-center gap-2 px-3 pb-2 pt-3\">\n <h2 id={treeHeadingId} className=\"min-w-0 flex-1 truncate text-sm font-semibold text-foreground\">\n {label}\n </h2>\n <div className=\"flex shrink-0 items-center gap-1\">\n {headerActions}\n <button\n type=\"button\"\n aria-label={`Refresh ${noun}`}\n title=\"Refresh\"\n onClick={() => void refresh()}\n className={`${TREE_ICON_BUTTON} text-muted-foreground hover:bg-muted hover:text-foreground`}\n >\n <RefreshCw className=\"size-4\" aria-hidden=\"true\" />\n </button>\n {canCreate && (\n <button\n type=\"button\"\n title=\"New file\"\n aria-label={activeFolder ? `New file in ${activeFolder}` : 'New file'}\n onClick={openCreate}\n className={`${TREE_ICON_BUTTON} bg-primary text-primary-foreground hover:bg-primary/90`}\n >\n <Plus className=\"size-4\" aria-hidden=\"true\" />\n </button>\n )}\n </div>\n </div>\n {!vaultEmpty && (\n <div className=\"shrink-0 px-3 pb-2\">\n <input\n ref={searchRef}\n type=\"search\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={activeFolder ? `Search ${activeFolder}…` : `Search ${noun}…`}\n aria-label={`Search ${noun}`}\n className=\"h-8 w-full rounded-md border border-border bg-input px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [@media(pointer:coarse)]:h-10 [@media(pointer:coarse)]:text-base\"\n />\n </div>\n )}\n {activeFolder && (\n <div className=\"mx-3 mb-2 flex shrink-0 items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs\">\n <Folder className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <span data-vault-folder className=\"min-w-0 flex-1 truncate font-medium text-foreground\" title={activeFolder}>\n {activeFolder}\n </span>\n <button\n type=\"button\"\n aria-label=\"Clear the active folder\"\n onClick={() => setFolderPath(null)}\n className=\"shrink-0 rounded px-1 text-muted-foreground underline-offset-2 transition-colors hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n Clear\n </button>\n </div>\n )}\n <div className=\"min-h-0 flex-1 overflow-y-auto border-t border-border px-1.5 py-1.5\">\n {treeContent}\n </div>\n </section>\n </div>\n\n <div\n ref={documentRef}\n role=\"region\"\n aria-label={`${label} document`}\n tabIndex={-1}\n className={`${showFiles || treeSpansPane ? 'hidden' : 'flex'} min-w-0 flex-1 flex-col overflow-hidden ${treeSpansPane ? '' : '@[45rem]/vault:flex'}`}\n >\n {selectedFile && (\n <div className={`flex h-14 shrink-0 items-center justify-between gap-2 border-b border-border px-4 ${pathBarClassName ?? 'bg-card'}`}>\n <span data-vault-path className=\"min-w-0 flex-1 truncate text-xs font-medium text-foreground\">{selectedFile.path}</span>\n <div className=\"flex shrink-0 items-center gap-1\">\n {canWrite && isMarkdownCapable && (\n <div className=\"mr-1 flex items-center gap-1\">\n <button\n type=\"button\"\n aria-label=\"Edit as rich text\"\n aria-pressed={editorMode === 'rich'}\n onClick={showRichMode}\n className={`inline-flex h-7 items-center rounded px-2 text-xs transition-colors ${\n editorMode === 'rich'\n ? 'bg-primary text-primary-foreground'\n : 'text-muted-foreground hover:bg-muted hover:text-foreground'\n }`}\n >\n Rich\n </button>\n <button\n type=\"button\"\n aria-label=\"Edit as source\"\n aria-pressed={editorMode === 'source'}\n onClick={showSourceMode}\n className={`inline-flex h-7 items-center rounded px-2 text-xs transition-colors ${\n editorMode === 'source'\n ? 'bg-primary text-primary-foreground'\n : 'text-muted-foreground hover:bg-muted hover:text-foreground'\n }`}\n >\n Source\n </button>\n </div>\n )}\n {renderDock && (!persistentDock || dockInline) && (\n <button\n type=\"button\"\n aria-label={dockButtonLabel}\n aria-pressed={dockOpen}\n disabled={dockBlockedByDraft}\n title={dockBlockedByDraft ? 'Save your changes first' : (persistentDock ? dockLabel : (dockToggleCfg.title ?? dockToggleCfg.label))}\n onClick={() => setDockOpen((v) => !v)}\n className={`inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs transition-colors disabled:pointer-events-none disabled:opacity-40 ${\n dockOpen\n ? 'bg-primary text-primary-foreground'\n : 'text-muted-foreground hover:bg-muted hover:text-foreground'\n }`}\n >\n {dockButtonLabel}\n </button>\n )}\n {fileActions?.(selectedFile)}\n {onDownloadFile && (\n <button\n type=\"button\"\n aria-label=\"Download this file\"\n title=\"Download file\"\n onClick={() => onDownloadFile(selectedFile)}\n className=\"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n >\n <Download className=\"h-4 w-4\" />\n </button>\n )}\n {canDelete && (\n <button\n type=\"button\"\n aria-label=\"Delete this file\"\n title=\"Delete file\"\n onClick={() => { setDeleteError(null); setDeleteOpen(true) }}\n className=\"inline-flex h-7 w-7 items-center justify-center rounded text-[var(--surface-danger-text)] transition-colors hover:bg-destructive/10\"\n >\n <Trash2 className=\"h-4 w-4\" />\n </button>\n )}\n </div>\n </div>\n )}\n {selectedFile && saveError && (\n <OperationErrorAlert\n message={saveError.message}\n retryLabel=\"Retry save\"\n onRetry={() => void saveCurrent()}\n onDismiss={() => setSaveError(null)}\n />\n )}\n {readError && selectedFile?.path === resolvedSelectedPath && (\n <OperationErrorAlert\n message={readError}\n retryLabel=\"Retry file refresh\"\n onRetry={() => setReloadNonce((n) => n + 1)}\n onDismiss={() => setReadError(null)}\n />\n )}\n <div className=\"flex-1 overflow-hidden\">\n {fileLoading && selectedFile?.path !== resolvedSelectedPath ? (\n <EditorSkeleton />\n ) : readError && selectedFile?.path !== resolvedSelectedPath ? (\n <ReadErrorState message={readError} onRetry={() => setReloadNonce((n) => n + 1)} />\n ) : selectedFile && renderDock && dockInline && dockOpen ? (\n <div data-vault-dock=\"inline\" className=\"flex h-full min-h-0 flex-col overflow-y-auto\">\n {renderDock({ file: selectedFile, open: true, onClose: () => setDockOpen(false), placement: 'inline' })}\n </div>\n ) : selectedFile && canWrite && isMarkdownCapable && editorMode === 'source' ? (\n <SourceEditor\n path={selectedFile.path}\n content={sourceDraft}\n saving={saving}\n dirty={isDirty}\n onChange={onSourceChange}\n onSave={() => void saveCurrent()}\n />\n ) : selectedFile ? (\n renderArtifact({\n file: selectedFile,\n loading: false,\n mode: editorMode,\n canWrite,\n richDraft,\n dirty: isDirty,\n onRichChange,\n onSave: () => void saveCurrent(),\n })\n ) : emptyState !== undefined ? emptyState : (\n <DocumentEmptyState label={label} recent={recentToOffer} onOpen={(path) => guardedOpen(path)} />\n )}\n </div>\n </div>\n </div>\n </div>\n\n {renderDock && selectedFile && !dockInline && renderDock({\n file: selectedFile,\n open: persistentDock ? true : dockOpen,\n onClose: persistentDock ? () => {} : () => setDockOpen(false),\n placement: 'side',\n })}\n\n <ConfirmDialog\n open={createOpen}\n title=\"Create file\"\n description={activeFolder ? `Add a new document to ${activeFolder}.` : `Add a new document to ${label}.`}\n confirmLabel={creating ? 'Creating…' : 'Create'}\n // A prefilled folder is a path with no file name yet, so emptiness is\n // not the test — `folder/` would otherwise be sent to the port as a\n // file to create.\n confirmDisabled={creating || !createFileName}\n onConfirm={() => void handleCreate()}\n onCancel={() => { setCreateOpen(false); setNewPath(''); setCreateError(null) }}\n >\n <div className=\"space-y-2\">\n <input\n value={newPath}\n autoFocus\n onChange={(e) => setNewPath(e.target.value)}\n placeholder=\"e.g. playbooks/new-strategy.md\"\n aria-label=\"New file path\"\n className=\"h-9 w-full rounded-md border border-border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground\"\n />\n {createError && <p role=\"alert\" className=\"text-xs text-[var(--surface-danger-text)]\">{createError.message}</p>}\n </div>\n </ConfirmDialog>\n\n <ConfirmDialog\n open={deleteOpen}\n title=\"Delete file?\"\n description={`This permanently removes ${selectedFile?.path ?? 'this file'} from ${label}.`}\n confirmLabel={deleting ? 'Deleting…' : 'Delete file'}\n confirmDisabled={deleting}\n destructive\n onConfirm={() => void handleDelete()}\n onCancel={() => { setDeleteOpen(false); setDeleteError(null) }}\n >\n {deleteError && <p role=\"alert\" className=\"text-xs text-[var(--surface-danger-text)]\">{deleteError.message}</p>}\n </ConfirmDialog>\n\n <ConfirmDialog\n open={pendingNav !== null}\n title=\"Discard unsaved changes?\"\n description=\"Your edits to this document haven't been saved. Continue and lose them?\"\n confirmLabel=\"Discard changes\"\n destructive\n onConfirm={confirmDiscard}\n onCancel={() => { finishPendingOpen(false); setPendingNav(null) }}\n />\n </div>\n </EditorErrorBoundary>\n )\n})\n\nfunction SourceEditor({\n path,\n content,\n saving,\n dirty,\n onChange,\n onSave,\n}: {\n path: string\n content: string\n saving: boolean\n dirty: boolean\n onChange: (content: string) => void\n onSave: () => void\n}) {\n return (\n <div className=\"flex h-full min-h-0 flex-col bg-background\">\n <div className=\"flex items-center justify-between gap-2 border-b border-border px-4 py-2\">\n <p className=\"truncate font-mono text-xs text-muted-foreground\">{path}</p>\n <div className=\"flex shrink-0 items-center gap-2\">\n <span className=\"rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground\">\n {dirty ? 'Unsaved changes' : 'Saved'}\n </span>\n <button\n type=\"button\"\n onClick={onSave}\n disabled={saving || !dirty}\n className=\"inline-flex h-7 items-center rounded-md bg-primary px-2 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50\"\n >\n {saving ? 'Saving…' : 'Save'}\n </button>\n </div>\n </div>\n <textarea\n value={content}\n onChange={(event) => onChange(event.target.value)}\n spellCheck={false}\n aria-label=\"Source editor\"\n // Full-bleed editor: keep the floor's ring but draw it inside the border\n // box, since an outward ring on a `flex-1` pane child is clipped.\n className=\"min-h-0 flex-1 resize-none border-0 bg-background p-4 font-mono text-sm leading-6 text-foreground focus-visible:[outline-offset:-2px]\"\n />\n </div>\n )\n}\n","/**\n * Self-contained confirm dialog — no dialog library. A focus-trapped modal with\n * Escape-to-cancel and Enter from text inputs, used for create / delete / discard-unsaved\n * flows so the pane carries zero UI-kit dependency.\n */\n\nimport { useEffect, useRef, type ReactNode } from 'react'\n\nexport interface ConfirmDialogProps {\n open: boolean\n title: string\n description?: ReactNode\n confirmLabel?: string\n cancelLabel?: string\n /** Styles the confirm button as a destructive action. */\n destructive?: boolean\n /** Disables the confirm button (e.g. while the action is in flight). */\n confirmDisabled?: boolean\n onConfirm: () => void\n onCancel: () => void\n /** Optional body (e.g. an input field for the create flow). */\n children?: ReactNode\n}\n\nexport function ConfirmDialog({\n open,\n title,\n description,\n confirmLabel = 'Confirm',\n cancelLabel = 'Cancel',\n destructive = false,\n confirmDisabled = false,\n onConfirm,\n onCancel,\n children,\n}: ConfirmDialogProps) {\n const panelRef = useRef<HTMLDivElement>(null)\n const confirmRef = useRef<HTMLButtonElement>(null)\n\n useEffect(() => {\n if (!open) return\n confirmRef.current?.focus()\n }, [open])\n\n if (!open) return null\n\n function onKeyDown(event: React.KeyboardEvent) {\n if (event.key === 'Escape') {\n event.preventDefault()\n onCancel()\n return\n }\n const target = event.target\n if (\n event.key === 'Enter'\n && !event.defaultPrevented\n && !event.nativeEvent.isComposing\n && !confirmDisabled\n && target instanceof HTMLInputElement\n && ['text', 'search', 'email', 'url', 'tel', 'password', 'number'].includes(target.type)\n ) {\n event.preventDefault()\n onConfirm()\n return\n }\n if (event.key !== 'Tab') return\n const focusable = panelRef.current?.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n )\n if (!focusable || focusable.length === 0) return\n const first = focusable[0]\n const last = focusable[focusable.length - 1]\n const active = document.activeElement as HTMLElement | null\n if (event.shiftKey && active === first) {\n event.preventDefault()\n last?.focus()\n } else if (!event.shiftKey && active === last) {\n event.preventDefault()\n first?.focus()\n }\n }\n\n return (\n <div\n className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4\"\n onMouseDown={(e) => { if (e.target === e.currentTarget) onCancel() }}\n >\n <div\n ref={panelRef}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={title}\n onKeyDown={onKeyDown}\n className=\"w-full max-w-md rounded-lg border border-border bg-card p-5 shadow-lg\"\n >\n <h2 className=\"text-sm font-semibold text-foreground\">{title}</h2>\n {description && <p className=\"mt-1.5 text-xs text-muted-foreground\">{description}</p>}\n {children && <div className=\"mt-3\">{children}</div>}\n <div className=\"mt-5 flex justify-end gap-2\">\n <button\n type=\"button\"\n onClick={onCancel}\n className=\"inline-flex h-8 items-center rounded-md px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n >\n {cancelLabel}\n </button>\n <button\n ref={confirmRef}\n type=\"button\"\n onClick={onConfirm}\n disabled={confirmDisabled}\n className={`inline-flex h-8 items-center rounded-md px-3 text-xs font-medium transition-colors disabled:pointer-events-none disabled:opacity-50 ${\n destructive\n ? 'bg-destructive text-destructive-foreground hover:bg-destructive/90'\n : 'bg-primary text-primary-foreground hover:bg-primary/90'\n }`}\n >\n {confirmLabel}\n </button>\n </div>\n </div>\n </div>\n )\n}\n","/**\n * The files a reader opened most recently in this browser, per vault scope\n * (`treeStateKey`). Storage can be blocked or full; every access degrades to\n * an empty list rather than failing the pane.\n */\n\nconst PREFIX = 'tangle:vault-recent:'\n/** How many paths are kept; the empty state shows a few of them. */\nconst RECENT_FILE_LIMIT = 8\n\nfunction storage(key: string | undefined): Storage | null {\n if (!key || typeof window === 'undefined') return null\n try {\n return window.localStorage\n } catch {\n return null\n }\n}\n\nexport function readRecentFiles(key: string | undefined): string[] {\n const store = storage(key)\n if (!store) return []\n try {\n const parsed: unknown = JSON.parse(store.getItem(PREFIX + key) ?? '[]')\n return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : []\n } catch {\n return []\n }\n}\n\n/** Moves `path` to the front and returns the new list. */\nexport function recordRecentFile(key: string | undefined, path: string): string[] {\n const next = [path, ...readRecentFiles(key).filter((item) => item !== path)].slice(0, RECENT_FILE_LIMIT)\n const store = storage(key)\n if (store) {\n try {\n store.setItem(PREFIX + key, JSON.stringify(next))\n } catch {\n // Full or blocked storage: the list lives for this render only.\n }\n }\n return next\n}\n"],"mappings":";AAcA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,OAGK;AACP,SAAS,UAAU,UAAU,QAAQ,MAAM,WAAW,cAAc;;;ACtBpE,SAAS,WAAW,cAA8B;AAyF1C,cAGA,YAHA;AAvED,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf,cAAc;AAAA,EACd,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AACF,GAAuB;AACrB,QAAM,WAAW,OAAuB,IAAI;AAC5C,QAAM,aAAa,OAA0B,IAAI;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,KAAM;AACX,eAAW,SAAS,MAAM;AAAA,EAC5B,GAAG,CAAC,IAAI,CAAC;AAET,MAAI,CAAC,KAAM,QAAO;AAElB,WAAS,UAAU,OAA4B;AAC7C,QAAI,MAAM,QAAQ,UAAU;AAC1B,YAAM,eAAe;AACrB,eAAS;AACT;AAAA,IACF;AACA,UAAM,SAAS,MAAM;AACrB,QACE,MAAM,QAAQ,WACX,CAAC,MAAM,oBACP,CAAC,MAAM,YAAY,eACnB,CAAC,mBACD,kBAAkB,oBAClB,CAAC,QAAQ,UAAU,SAAS,OAAO,OAAO,YAAY,QAAQ,EAAE,SAAS,OAAO,IAAI,GACvF;AACA,YAAM,eAAe;AACrB,gBAAU;AACV;AAAA,IACF;AACA,QAAI,MAAM,QAAQ,MAAO;AACzB,UAAM,YAAY,SAAS,SAAS;AAAA,MAClC;AAAA,IACF;AACA,QAAI,CAAC,aAAa,UAAU,WAAW,EAAG;AAC1C,UAAM,QAAQ,UAAU,CAAC;AACzB,UAAM,OAAO,UAAU,UAAU,SAAS,CAAC;AAC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AAAC,MAAC,SAAI,WAAU,8CACb;AAAA,oBAAAA,MAAC,SAAI,WAAU,4EACb;AAAA,sBAAAD,KAAC,OAAE,WAAU,oDAAoD,gBAAK;AAAA,MACtE,gBAAAC,MAAC,SAAI,WAAU,oCACb;AAAA,wBAAAD,KAAC,UAAK,WAAU,6FACb,kBAAQ,oBAAoB,SAC/B;AAAA,QACA,gBAAAA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,UAAU,UAAU,CAAC;AAAA,YACrB,WAAU;AAAA,YAET,mBAAS,iBAAY;AAAA;AAAA,QACxB;AAAA,SACF;AAAA,OACF;AAAA,IACA,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC,OAAO;AAAA,QACP,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,QAChD,YAAY;AAAA,QACZ,cAAW;AAAA,QAGX,WAAU;AAAA;AAAA,IACZ;AAAA,KACF;AAEJ;","names":["useEffect","useRef","jsx","jsxs","VaultPane","useRef","useEffect"]}
@@ -39,7 +39,10 @@ export interface DetachedTurnWorkflowTickOptions<TPayload extends DetachedTurnWo
39
39
  drive: (payload: TPayload) => Promise<DetachedTurnDriveOutcome<TResult>>;
40
40
  /** Must be idempotent: the Worker can stop after the write but before commit. */
41
41
  settle: (payload: TPayload, result: DetachedTurnTerminalResult<TResult>) => Promise<TSettled>;
42
- pollDelay?: CloudflareWorkflowSleepDuration;
42
+ /** Wait between passes: one duration, or one per zero-based pass so a long
43
+ * turn polls less often. It must depend only on the pass number, so a
44
+ * replayed Workflow takes the same steps. Default: 5 seconds. */
45
+ pollDelay?: CloudflareWorkflowSleepDuration | ((attempt: number) => CloudflareWorkflowSleepDuration);
43
46
  stepName?: string;
44
47
  }
45
48
  /**
@@ -59,7 +59,8 @@ async function runDetachedTurnWorkflowTick(options) {
59
59
  assertIdentity(options.event?.payload);
60
60
  const payload = Object.freeze({ ...options.event.payload });
61
61
  const name = options.stepName ?? "detached-turn";
62
- const delay = options.pollDelay ?? "5 seconds";
62
+ const pollDelay = options.pollDelay ?? "5 seconds";
63
+ const delayFor = (attempt2) => typeof pollDelay === "function" ? pollDelay(attempt2) : pollDelay;
63
64
  let attempt = 0;
64
65
  let terminalResult;
65
66
  while (true) {
@@ -72,13 +73,18 @@ async function runDetachedTurnWorkflowTick(options) {
72
73
  terminalResult = driveResult;
73
74
  break;
74
75
  }
75
- await options.step.sleep(`${name}:wait:${attempt}`, delay);
76
+ await options.step.sleep(`${name}:wait:${attempt}`, delayFor(attempt));
76
77
  attempt += 1;
77
78
  }
78
79
  return options.step.do(`${name}:settle`, () => options.settle(payload, terminalResult));
79
80
  }
80
81
 
81
82
  // src/preset-cloudflare/native-completion-workflow.ts
83
+ function nativeCompletionPollDelay(attempt) {
84
+ if (attempt < 24) return "5 seconds";
85
+ if (attempt < 136) return "15 seconds";
86
+ return "30 seconds";
87
+ }
82
88
  function validObservation(value) {
83
89
  if (!value || value.state !== "running" && value.state !== "completed" && value.state !== "failed") {
84
90
  throw new Error(`native completion observer returned unknown state: ${String(value?.state)}`);
@@ -93,9 +99,13 @@ async function runNativeCompletionWorkflow(options) {
93
99
  let receipt = await runDetachedTurnWorkflowTick({
94
100
  event: options.event,
95
101
  step: options.step,
96
- pollDelay: options.pollDelay,
102
+ pollDelay: options.pollDelay ?? nativeCompletionPollDelay,
97
103
  stepName: `${name}:observe`,
98
- drive: async (payload) => ({ succeeded: true, value: validObservation(await options.observe(payload)) }),
104
+ drive: async (payload) => {
105
+ const observation = validObservation(await options.observe(payload));
106
+ if (observation.state !== "running") await options.persistTranscript(payload, observation.receipt);
107
+ return { succeeded: true, value: observation };
108
+ },
99
109
  settle: async (_payload, result) => result.receipt
100
110
  });
101
111
  if (options.prepare) receipt = await options.prepare(options.event.payload, receipt);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/preset-cloudflare/workflow-instance.ts","../../src/preset-cloudflare/detached-turn-workflow.ts","../../src/preset-cloudflare/native-completion-workflow.ts","../../src/preset-cloudflare/headers.ts","../../src/preset-cloudflare/index.ts"],"sourcesContent":["/**\n * The structural part of a Cloudflare Workflow instance used to prove that a\n * failed create call actually left an addressable durable instance behind.\n */\nexport interface CloudflareWorkflowInstanceLike<TStatus = unknown> {\n status(): Promise<TStatus>\n}\n\n/** The structural binding implemented by Cloudflare's `Workflow<TParams>`. */\nexport interface CloudflareWorkflowBindingLike<\n TParams,\n TStatus = unknown,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus> =\n CloudflareWorkflowInstanceLike<TStatus>,\n> {\n create(input: { id: string; params: TParams }): Promise<TInstance>\n get(id: string): Promise<TInstance>\n}\n\nexport interface EnsureCloudflareWorkflowInstanceResult<\n TStatus,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus>,\n> {\n instance: TInstance\n /** False only when create failed but the same id was proven readable. */\n created: boolean\n /** Present on reuse because reading status is the proof the instance exists. */\n status?: TStatus\n}\n\n/**\n * Create one durable Workflow instance, or prove an instance with the same id\n * already exists before accepting a create error as an idempotent retry.\n *\n * Cloudflare does not expose a stable duplicate-error class. Matching error\n * text can therefore swallow unrelated failures. This helper uses the durable\n * resource itself as proof: `get(id).status()` must succeed, otherwise the\n * original create error is rethrown.\n */\nexport async function ensureCloudflareWorkflowInstance<\n TParams,\n TStatus,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus>,\n>(\n binding: CloudflareWorkflowBindingLike<TParams, TStatus, TInstance>,\n input: { id: string; params: TParams },\n): Promise<EnsureCloudflareWorkflowInstanceResult<TStatus, TInstance>> {\n try {\n return {\n instance: await binding.create(input),\n created: true,\n }\n } catch (createError) {\n try {\n const instance = await binding.get(input.id)\n const status = await instance.status()\n return { instance, created: false, status }\n } catch {\n throw createError\n }\n }\n}\n","import type { TurnDriveResult } from '@tangle-network/sandbox'\nimport type { Outcome } from '../sandbox/outcome'\n\n/** The stable identity a Workflow reuses on every retry of one turn. */\nexport interface DetachedTurnWorkflowIdentity {\n /** Sandbox session resume key. */\n sessionId: string\n /** Sandbox completed-turn idempotency key. */\n turnId: string\n}\n\n/** The part of Cloudflare's Workflow event needed by the tick. */\nexport interface CloudflareWorkflowEventLike<TPayload> {\n payload: TPayload\n}\n\n/** A duration accepted by Cloudflare Workflow `step.sleep`. */\nexport type CloudflareWorkflowSleepDuration =\n | `${number} ${\n | 'second'\n | 'seconds'\n | 'minute'\n | 'minutes'\n | 'hour'\n | 'hours'\n | 'day'\n | 'days'\n | 'week'\n | 'weeks'\n | 'month'\n | 'months'\n | 'year'\n | 'years'}`\n | number\n\n/** The durable Workflow operations used by the tick. */\nexport interface CloudflareWorkflowStepLike {\n do<T>(name: string, callback: (context: unknown) => Promise<T>): Promise<T>\n sleep(name: string, duration: CloudflareWorkflowSleepDuration): Promise<void>\n}\n\n/** The states returned by the Sandbox `driveTurn` primitive. */\nexport type DetachedTurnDriveState = TurnDriveResult['state']\n\n/** The small state contract a durable tick needs. Product observers may carry\n * a richer terminal receipt than Sandbox's `TurnDriveResult`. */\nexport interface DetachedTurnDriveResultLike {\n state: DetachedTurnDriveState\n}\n\n/** The terminal result passed to product settlement. */\nexport type DetachedTurnTerminalResult<\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> = Exclude<TResult, { state: 'running' }>\n\n/** A drive call's retryable transport boundary. */\nexport type DetachedTurnDriveOutcome<\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> = Outcome<TResult>\n\n/** Options for one durable detached-turn Workflow run. */\nexport interface DetachedTurnWorkflowTickOptions<\n TPayload extends DetachedTurnWorkflowIdentity,\n TSettled,\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> {\n event: CloudflareWorkflowEventLike<TPayload>\n step: CloudflareWorkflowStepLike\n /** One SDK drive pass. Rejected results must not enter the Workflow cache. */\n drive: (payload: TPayload) => Promise<DetachedTurnDriveOutcome<TResult>>\n /** Must be idempotent: the Worker can stop after the write but before commit. */\n settle: (payload: TPayload, result: DetachedTurnTerminalResult<TResult>) => Promise<TSettled>\n pollDelay?: CloudflareWorkflowSleepDuration\n stepName?: string\n}\n\nfunction assertIdentity(payload: DetachedTurnWorkflowIdentity): void {\n if (!payload || typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) {\n throw new Error('detached turn Workflow payload requires a non-empty sessionId')\n }\n if (typeof payload.turnId !== 'string' || !payload.turnId.trim()) {\n throw new Error('detached turn Workflow payload requires a non-empty turnId')\n }\n}\n\n// Keyed by the SDK's own union, so a state a new Sandbox adds fails this\n// package's build instead of retrying a settled turn as \"unknown\" forever.\nconst DRIVE_STATES: Record<DetachedTurnDriveState, true> = {\n running: true,\n completed: true,\n failed: true,\n awaiting_plan_decision: true,\n blocked_on_approval: true,\n awaiting_question: true,\n awaiting_interaction: true,\n}\n\nfunction isKnownDriveState(state: unknown): state is DetachedTurnDriveState {\n return typeof state === 'string' && Object.hasOwn(DRIVE_STATES, state)\n}\n\nfunction checkedDriveResult<TResult extends DetachedTurnDriveResultLike>(value: TResult): TResult {\n const state = (value as { state?: unknown } | null)?.state\n if (!isKnownDriveState(state)) {\n throw new Error(`detached turn drive returned unknown state: ${String(state)}`)\n }\n return value\n}\n\n/**\n * Drive a detached SDK turn with durable steps, not an HTTP waitUntil lifetime.\n * Stable step names let an evicted Workflow resume without repeating committed\n * passes. Validation belongs inside step.do so a transient malformed response\n * is retried rather than committed permanently as a poisoned checkpoint.\n */\nexport async function runDetachedTurnWorkflowTick<\n TPayload extends DetachedTurnWorkflowIdentity,\n TSettled,\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n>(\n options: DetachedTurnWorkflowTickOptions<TPayload, TSettled, TResult>,\n): Promise<TSettled> {\n assertIdentity(options.event?.payload)\n // Never allow a callback to change the admission identity for later passes.\n const payload = Object.freeze({ ...options.event.payload }) as TPayload\n const name = options.stepName ?? 'detached-turn'\n const delay = options.pollDelay ?? '5 seconds'\n let attempt = 0\n let terminalResult: DetachedTurnTerminalResult<TResult>\n while (true) {\n const driveResult = checkedDriveResult(await options.step.do<TResult>(`${name}:drive:${attempt}`, async () => {\n const outcome = await options.drive(payload)\n if (!outcome.succeeded) throw outcome.error\n return checkedDriveResult(outcome.value)\n }))\n // Validate replayed values as well, including checkpoints from older code.\n if (driveResult.state !== 'running') {\n terminalResult = driveResult as DetachedTurnTerminalResult<TResult>\n break\n }\n await options.step.sleep(`${name}:wait:${attempt}`, delay)\n attempt += 1\n }\n return options.step.do(`${name}:settle`, () => options.settle(payload, terminalResult))\n}\n","/**\n * Durable terminal assembly for a native turn admitted by another request.\n * Product callbacks own domain effects and may use their own Workflow steps;\n * this helper never nests those callbacks inside `step.do`.\n */\n\nimport type {\n NativeCompletionObservation,\n NativeCompletionReceipt,\n} from '../chat-routes/native-completion'\nimport {\n runDetachedTurnWorkflowTick,\n type CloudflareWorkflowEventLike,\n type CloudflareWorkflowSleepDuration,\n type CloudflareWorkflowStepLike,\n type DetachedTurnWorkflowIdentity,\n} from './detached-turn-workflow'\n\n/** Stable identity required to resume a registered native completion. */\nexport interface NativeCompletionWorkflowPayload extends DetachedTurnWorkflowIdentity {\n registeredAt: number\n}\n\ntype NativeCompletionDriveResult = NativeCompletionObservation\n\nexport interface NativeCompletionWorkflowOptions<\n TPayload extends NativeCompletionWorkflowPayload,\n TMessageId,\n> {\n event: CloudflareWorkflowEventLike<TPayload>\n step: CloudflareWorkflowStepLike\n /** Read-only exact observation. It must never dispatch, drive, or cancel. */\n observe(payload: TPayload): Promise<NativeCompletionObservation>\n /**\n * Product-owned idempotent preparation, for example artifact promotion and\n * output classification. It runs outside an enclosing Workflow step so a\n * product may use its own named steps without nesting `step.do`.\n */\n prepare?(payload: TPayload, receipt: NativeCompletionReceipt): Promise<NativeCompletionReceipt>\n /** Durable transcript write. A supplied message id updates the existing row. */\n persistTranscript(\n payload: TPayload,\n receipt: NativeCompletionReceipt,\n existingMessageId?: TMessageId,\n ): Promise<TMessageId>\n /**\n * Product-owned idempotent settlement. A rejection leaves the lock held and\n * skips finalization, making the failed dependency observable and retryable.\n */\n settle(\n payload: TPayload,\n receipt: NativeCompletionReceipt,\n messageId: TMessageId,\n ): Promise<NativeCompletionReceipt | void>\n /** Optional product buffer completion after successful settlement. */\n finalizeBuffer?(payload: TPayload, receipt: NativeCompletionReceipt, messageId: TMessageId): Promise<void>\n /** Release the product lock only after every terminal effect completed. */\n releaseLock(payload: TPayload): Promise<void>\n pollDelay?: CloudflareWorkflowSleepDuration\n stepName?: string\n}\n\nfunction validObservation(value: NativeCompletionObservation): NativeCompletionDriveResult {\n if (!value || (value.state !== 'running' && value.state !== 'completed' && value.state !== 'failed')) {\n throw new Error(`native completion observer returned unknown state: ${String((value as { state?: unknown } | null)?.state)}`)\n }\n if (value.state !== 'running' && !value.receipt) {\n throw new Error('native completion observer returned a terminal state without a receipt')\n }\n return value\n}\n\n/**\n * Drive exact observation through durable retry steps, then run the terminal\n * sequence once. `prepare` and `settle` are deliberately outside `step.do` so\n * product callbacks can compose their own named Cloudflare Workflow steps.\n */\nexport async function runNativeCompletionWorkflow<\n TPayload extends NativeCompletionWorkflowPayload,\n TMessageId,\n>(options: NativeCompletionWorkflowOptions<TPayload, TMessageId>): Promise<NativeCompletionReceipt> {\n const name = options.stepName ?? 'native-completion'\n let receipt = await runDetachedTurnWorkflowTick<\n TPayload,\n NativeCompletionReceipt,\n NativeCompletionDriveResult\n >({\n event: options.event,\n step: options.step,\n pollDelay: options.pollDelay,\n stepName: `${name}:observe`,\n drive: async (payload) => ({ succeeded: true, value: validObservation(await options.observe(payload)) }),\n settle: async (_payload, result) => result.receipt,\n })\n\n if (options.prepare) receipt = await options.prepare(options.event.payload, receipt)\n const messageId = await options.step.do(`${name}:persist-transcript`, () => (\n options.persistTranscript(options.event.payload, receipt)\n ))\n const settledReceipt = await options.settle(options.event.payload, receipt, messageId)\n if (settledReceipt) {\n receipt = settledReceipt\n await options.step.do(`${name}:persist-final-transcript`, () => (\n options.persistTranscript(options.event.payload, receipt, messageId)\n ))\n }\n if (options.finalizeBuffer) {\n await options.step.do(`${name}:finalize-buffer`, () => (\n options.finalizeBuffer!(options.event.payload, receipt, messageId)\n ))\n }\n await options.step.do(`${name}:release-lock`, () => options.releaseLock(options.event.payload))\n return receipt\n}\n","const HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\n/** One path rule in Cloudflare's static-asset `_headers` file. */\nexport interface CloudflareHeadersRule {\n pattern: string\n headers: Readonly<Record<string, string>>\n}\n\nfunction assertSingleLine(value: string, label: string): void {\n if (value.length === 0 || /[\\r\\n]/.test(value)) {\n throw new Error(`${label} must be a non-empty single line`)\n }\n}\n\n/**\n * Render native Cloudflare static-asset header rules.\n *\n * Values are validated before serialization so a product setting cannot add a\n * second path rule or response header through a newline.\n */\nexport function renderCloudflareHeadersFile(\n rules: readonly CloudflareHeadersRule[],\n): string {\n if (rules.length === 0) {\n throw new Error('At least one Cloudflare header rule is required')\n }\n\n const renderedRules = rules.map(({ pattern, headers }) => {\n assertSingleLine(pattern, 'Cloudflare header pattern')\n if (!pattern.startsWith('/') || /\\s/.test(pattern)) {\n throw new Error('Cloudflare header patterns must start with / and contain no whitespace')\n }\n\n const entries = Object.entries(headers)\n if (entries.length === 0) {\n throw new Error(`Cloudflare header rule ${pattern} must contain at least one header`)\n }\n\n const renderedHeaders = entries.map(([name, value]) => {\n if (!HEADER_NAME.test(name)) {\n throw new Error(`Invalid HTTP header name: ${name}`)\n }\n assertSingleLine(value, `Cloudflare header ${name}`)\n return ` ${name}: ${value}`\n })\n\n return [pattern, ...renderedHeaders].join('\\n')\n })\n\n return `${renderedRules.join('\\n\\n')}\\n`\n}\n","/**\n * `@tangle-network/agent-app/preset-cloudflare` — the batteries-included default\n * stack.\n *\n * Every fleet agent runs the SAME backend: Cloudflare D1 (SQLite) through\n * Drizzle for state, a KV namespace as the artifact vault, AES-GCM field crypto\n * for PII, and per-workspace budget-capped model keys. The other agent-app\n * modules are pure SEAMS — `./tools` needs an `AppToolHandlers`, `./knowledge`\n * needs a `KnowledgeStateAccessor`, `./billing` needs a `WorkspaceKeyStore` +\n * `KeyCrypto`. This module is the ONE implementation of those seams against the\n * house stack, so a consumer that runs D1 + KV stands the whole shell up with\n * config + bindings and ZERO handler code.\n *\n * Layering:\n * - Drizzle is a PEER (the consumer installs `drizzle-orm`, never bundled). The\n * schema is therefore expressed two ways that need no import here: the plain\n * DDL ({@link PRESET_MIGRATION_SQL}) a consumer runs to create the tables, and\n * a {@link createPresetDrizzleSchema} factory that takes the consumer's\n * `drizzle-orm/sqlite-core` builder module and returns the typed tables. The\n * column names in {@link PRESET_TABLES} are the contract the handlers,\n * accessor, and DDL all agree on.\n * - D1 + KV are STRUCTURAL: {@link D1Like} (Cloudflare `D1Database` satisfies it)\n * and `KvLike` from `../web` (Cloudflare `KVNamespace` satisfies it). No\n * `@cloudflare/workers-types` dependency.\n * - Crypto/billing reuse `../crypto` + `../billing` exactly — this only wires\n * them to the D1 key table.\n */\n\nimport { createFieldCrypto } from '../crypto/index'\nimport {\n createWorkspaceKeyManager,\n type KeyCrypto,\n type KeyProvisioner,\n type WorkspaceKeyManager,\n type WorkspaceKeyRecord,\n type WorkspaceKeyStore,\n} from '../billing/index'\nimport type { KnowledgeStateAccessor } from '../knowledge/index'\nimport type {\n AddCitationArgs,\n AddCitationResult,\n AppToolContext,\n AppToolHandlers,\n RenderUiArgs,\n RenderUiResult,\n ScheduleFollowupArgs,\n ScheduleFollowupResult,\n SubmitProposalArgs,\n SubmitProposalResult,\n} from '../tools/index'\nimport { assertRenderUiSchema } from '../tools/render-ui-schema'\nimport type { KvLike } from '../web/index'\n\nexport {\n ensureCloudflareWorkflowInstance,\n type CloudflareWorkflowBindingLike,\n type CloudflareWorkflowInstanceLike,\n type EnsureCloudflareWorkflowInstanceResult,\n} from './workflow-instance'\n\nexport {\n runDetachedTurnWorkflowTick,\n type CloudflareWorkflowEventLike,\n type CloudflareWorkflowSleepDuration,\n type CloudflareWorkflowStepLike,\n type DetachedTurnDriveOutcome,\n type DetachedTurnDriveState,\n type DetachedTurnTerminalResult,\n type DetachedTurnWorkflowIdentity,\n type DetachedTurnWorkflowTickOptions,\n} from './detached-turn-workflow'\n\nexport {\n runNativeCompletionWorkflow,\n type NativeCompletionWorkflowOptions,\n type NativeCompletionWorkflowPayload,\n} from './native-completion-workflow'\n\nexport {\n renderCloudflareHeadersFile,\n type CloudflareHeadersRule,\n} from './headers'\n\n// ---------------------------------------------------------------------------\n// D1 structural seam\n//\n// The minimal surface of Cloudflare's `D1Database` the handlers + accessor use.\n// `D1Database` satisfies it structurally, so the consumer passes `env.DB`\n// directly and tests pass an in-memory fake. We keep it to the\n// prepare/bind/first/run/all shape D1 already exposes — no Drizzle here, so the\n// default handlers run on a fresh Worker with only the D1 binding.\n// ---------------------------------------------------------------------------\n\n/** A prepared, bound D1 statement. */\nexport interface D1PreparedLike {\n bind(...values: unknown[]): D1PreparedLike\n first<T = Record<string, unknown>>(colName?: string): Promise<T | null>\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n}\n\n/** The D1 surface the preset needs. Cloudflare `D1Database` satisfies it. */\nexport interface D1Like {\n prepare(query: string): D1PreparedLike\n}\n\n// ---------------------------------------------------------------------------\n// Default schema\n//\n// The four tables the default handlers + accessor read/write. Column names are\n// the single source of truth shared by the DDL, the Drizzle factory, the\n// handlers, and the accessor. Every table is workspace-scoped on `workspace_id`\n// (the accessor's default `where` column) so the knowledge `count` rule and the\n// tool writes agree without per-consumer wiring.\n//\n// Deliberately NOT here: chat thread/message tables. `/chat-store` is the\n// single thread-schema owner (`createChatTables` + `createChatStore`); the\n// preset once declared an unconsumed `threads` DDL, removed so two schemas\n// can't drift.\n// ---------------------------------------------------------------------------\n\n/** The preset table + column names — the contract the DDL, Drizzle schema,\n * handlers, and accessor share. Exposed so a consumer can reference a column\n * without a string literal. */\nexport const PRESET_TABLES = {\n proposals: {\n name: 'proposals',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n threadId: 'thread_id',\n type: 'type',\n title: 'title',\n description: 'description',\n status: 'status',\n createdBy: 'created_by',\n createdAt: 'created_at',\n },\n },\n knowledge: {\n name: 'knowledge',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n path: 'path',\n kind: 'kind',\n label: 'label',\n content: 'content',\n createdAt: 'created_at',\n },\n },\n deadlines: {\n name: 'deadlines',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n threadId: 'thread_id',\n title: 'title',\n dueDate: 'due_date',\n priority: 'priority',\n status: 'status',\n createdAt: 'created_at',\n },\n },\n workspaceKeys: {\n name: 'workspace_keys',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n keyId: 'key_id',\n keyEncrypted: 'key_encrypted',\n budgetUsd: 'budget_usd',\n expiresAt: 'expires_at',\n revokedAt: 'revoked_at',\n createdAt: 'created_at',\n },\n },\n} as const\n\n/**\n * Plain DDL for the preset schema — run by a consumer to create the tables with\n * ZERO drizzle (`for (const sql of PRESET_MIGRATION_SQL) await db.prepare(sql).run()`,\n * or paste into a `.sql` migration). One statement per table so D1's\n * single-statement `prepare` accepts each. Matches {@link PRESET_TABLES} exactly.\n */\nexport const PRESET_MIGRATION_SQL: readonly string[] = [\n `CREATE TABLE IF NOT EXISTS proposals (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n thread_id TEXT,\n type TEXT NOT NULL,\n title TEXT NOT NULL,\n description TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n created_by TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS knowledge (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n path TEXT NOT NULL,\n kind TEXT NOT NULL,\n label TEXT,\n content TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS deadlines (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n thread_id TEXT,\n title TEXT NOT NULL,\n due_date TEXT NOT NULL,\n priority TEXT,\n status TEXT NOT NULL DEFAULT 'scheduled',\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS workspace_keys (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n key_id TEXT NOT NULL,\n key_encrypted TEXT NOT NULL,\n budget_usd REAL NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS idx_proposals_ws ON proposals (workspace_id, status)`,\n `CREATE INDEX IF NOT EXISTS idx_deadlines_ws ON deadlines (workspace_id, status)`,\n `CREATE INDEX IF NOT EXISTS idx_knowledge_ws ON knowledge (workspace_id)`,\n `CREATE INDEX IF NOT EXISTS idx_workspace_keys_ws ON workspace_keys (workspace_id, revoked_at)`,\n]\n\n/** A chainable column builder — every modifier returns the builder so calls\n * like `.notNull().default('pending')` typecheck. The concrete drizzle builders\n * satisfy this structurally. */\nexport interface DrizzleColumnLike {\n primaryKey: () => DrizzleColumnLike\n notNull: () => DrizzleColumnLike\n default: (v: unknown) => DrizzleColumnLike\n}\n\n/** The shape of a `drizzle-orm/sqlite-core` module — the few builders the\n * preset schema uses. The consumer passes the real module; agent-app never\n * imports it (it stays a peer). */\nexport interface DrizzleSqliteCoreLike {\n sqliteTable: (name: string, columns: Record<string, DrizzleColumnLike>) => unknown\n text: (name?: string) => DrizzleColumnLike\n integer: (name?: string, config?: unknown) => DrizzleColumnLike\n real: (name?: string) => DrizzleColumnLike\n}\n\n/**\n * Build the typed Drizzle schema for the preset, given the consumer's\n * `drizzle-orm/sqlite-core` module. Returns one table object per\n * {@link PRESET_TABLES} entry — pass to `drizzle(db, { schema })` for typed\n * queries, or to drizzle-kit for migration generation. agent-app never imports\n * drizzle; the builder module is the seam.\n *\n * ```ts\n * import * as d from 'drizzle-orm/sqlite-core'\n * const schema = createPresetDrizzleSchema(d)\n * ```\n */\nexport function createPresetDrizzleSchema(d: DrizzleSqliteCoreLike) {\n const { sqliteTable, text, integer, real } = d\n const C = PRESET_TABLES\n return {\n proposals: sqliteTable(C.proposals.name, {\n id: text(C.proposals.columns.id).primaryKey(),\n workspaceId: text(C.proposals.columns.workspaceId).notNull(),\n threadId: text(C.proposals.columns.threadId),\n type: text(C.proposals.columns.type).notNull(),\n title: text(C.proposals.columns.title).notNull(),\n description: text(C.proposals.columns.description),\n status: text(C.proposals.columns.status).notNull().default('pending'),\n createdBy: text(C.proposals.columns.createdBy),\n createdAt: integer(C.proposals.columns.createdAt).notNull(),\n }),\n knowledge: sqliteTable(C.knowledge.name, {\n id: text(C.knowledge.columns.id).primaryKey(),\n workspaceId: text(C.knowledge.columns.workspaceId).notNull(),\n path: text(C.knowledge.columns.path).notNull(),\n kind: text(C.knowledge.columns.kind).notNull(),\n label: text(C.knowledge.columns.label),\n content: text(C.knowledge.columns.content),\n createdAt: integer(C.knowledge.columns.createdAt).notNull(),\n }),\n deadlines: sqliteTable(C.deadlines.name, {\n id: text(C.deadlines.columns.id).primaryKey(),\n workspaceId: text(C.deadlines.columns.workspaceId).notNull(),\n threadId: text(C.deadlines.columns.threadId),\n title: text(C.deadlines.columns.title).notNull(),\n dueDate: text(C.deadlines.columns.dueDate).notNull(),\n priority: text(C.deadlines.columns.priority),\n status: text(C.deadlines.columns.status).notNull().default('scheduled'),\n createdAt: integer(C.deadlines.columns.createdAt).notNull(),\n }),\n workspaceKeys: sqliteTable(C.workspaceKeys.name, {\n id: text(C.workspaceKeys.columns.id).primaryKey(),\n workspaceId: text(C.workspaceKeys.columns.workspaceId).notNull(),\n keyId: text(C.workspaceKeys.columns.keyId).notNull(),\n keyEncrypted: text(C.workspaceKeys.columns.keyEncrypted).notNull(),\n budgetUsd: real(C.workspaceKeys.columns.budgetUsd).notNull(),\n expiresAt: integer(C.workspaceKeys.columns.expiresAt).notNull(),\n revokedAt: integer(C.workspaceKeys.columns.revokedAt),\n createdAt: integer(C.workspaceKeys.columns.createdAt).notNull(),\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Default AppToolHandlers over D1 + KV\n// ---------------------------------------------------------------------------\n\n/** The KV-backed vault. `KvLike` (from `../web`) is the structural KV contract;\n * Cloudflare `KVNamespace` satisfies it. Artifacts are stored under their path. */\nexport type VaultKv = KvLike\n\n/** Define configuration options for handling preset tools including database, vault, and optional utilities */\nexport interface PresetToolHandlerOptions {\n /** The D1 database (Cloudflare `D1Database` satisfies {@link D1Like}). */\n db: D1Like\n /** The KV namespace used as the artifact vault. */\n vault: VaultKv\n /** Id generator. Default `crypto.randomUUID`. Injectable for deterministic tests. */\n newId?: () => string\n /** Clock (epoch ms). Default `Date.now`. Injectable for deterministic tests. */\n now?: () => number\n /** Vault path prefix for `render_ui` artifacts. Default `'ui'`. */\n uiPathPrefix?: string\n /** Vault path prefix for `add_citation` artifacts. Default `'citations'`. */\n citationPathPrefix?: string\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 64) || 'item'\n}\n\n/**\n * The default {@link AppToolHandlers} for the house stack:\n * - `submit_proposal` → insert a `proposals` row (`status='pending'`), deduped\n * on (workspace, title) so a retried turn doesn't double-queue.\n * - `schedule_followup` → insert a `deadlines` row, deduped on (workspace, title, due_date).\n * - `render_ui` → write the schema JSON as a `ui/<thread>/<slug>.json`\n * vault artifact AND a `knowledge` row pointing at it.\n * - `add_citation` → write the quote as a `citations/<slug>.json` artifact AND\n * a `knowledge` row.\n *\n * Returns the EXACT persisted content from `render_ui` (per the seam contract) so\n * a completion oracle sees real bytes. Pure seam wiring: a consumer that runs\n * D1 + KV gets all four tools with no handler code.\n */\nexport function createPresetToolHandlers(opts: PresetToolHandlerOptions): AppToolHandlers {\n const { db, vault } = opts\n const newId = opts.newId ?? (() => crypto.randomUUID())\n const now = opts.now ?? (() => Date.now())\n const uiPrefix = opts.uiPathPrefix ?? 'ui'\n const citationPrefix = opts.citationPathPrefix ?? 'citations'\n const P = PRESET_TABLES.proposals\n const D = PRESET_TABLES.deadlines\n const K = PRESET_TABLES.knowledge\n\n async function persistArtifact(path: string, body: string): Promise<void> {\n await vault.put(path, body)\n }\n\n async function insertKnowledge(workspaceId: string, path: string, kind: string, label: string | null, content: string): Promise<void> {\n await db\n .prepare(\n `INSERT INTO ${K.name} (${K.columns.id}, ${K.columns.workspaceId}, ${K.columns.path}, ${K.columns.kind}, ${K.columns.label}, ${K.columns.content}, ${K.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n )\n .bind(newId(), workspaceId, path, kind, label, content, now())\n .run()\n }\n\n return {\n async submitProposal(args: SubmitProposalArgs, ctx: AppToolContext): Promise<SubmitProposalResult> {\n const existing = await db\n .prepare(`SELECT ${P.columns.id} AS id FROM ${P.name} WHERE ${P.columns.workspaceId} = ? AND ${P.columns.title} = ? LIMIT 1`)\n .bind(ctx.workspaceId, args.title)\n .first<{ id: string }>()\n if (existing) return { proposalId: existing.id, deduped: true }\n\n const id = newId()\n await db\n .prepare(\n `INSERT INTO ${P.name} (${P.columns.id}, ${P.columns.workspaceId}, ${P.columns.threadId}, ${P.columns.type}, ${P.columns.title}, ${P.columns.description}, ${P.columns.status}, ${P.columns.createdBy}, ${P.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,\n )\n .bind(id, ctx.workspaceId, ctx.threadId, args.type, args.title, args.description ?? null, ctx.userId, now())\n .run()\n return { proposalId: id, deduped: false }\n },\n\n async scheduleFollowup(args: ScheduleFollowupArgs, ctx: AppToolContext): Promise<ScheduleFollowupResult> {\n const existing = await db\n .prepare(\n `SELECT ${D.columns.id} AS id, ${D.columns.dueDate} AS dueDate FROM ${D.name} WHERE ${D.columns.workspaceId} = ? AND ${D.columns.title} = ? AND ${D.columns.dueDate} = ? LIMIT 1`,\n )\n .bind(ctx.workspaceId, args.title, args.dueDate)\n .first<{ id: string; dueDate: string }>()\n if (existing) return { id: existing.id, dueDate: existing.dueDate, deduped: true }\n\n const id = newId()\n await db\n .prepare(\n `INSERT INTO ${D.name} (${D.columns.id}, ${D.columns.workspaceId}, ${D.columns.threadId}, ${D.columns.title}, ${D.columns.dueDate}, ${D.columns.priority}, ${D.columns.status}, ${D.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, 'scheduled', ?)`,\n )\n .bind(id, ctx.workspaceId, ctx.threadId, args.title, args.dueDate, args.priority ?? null, now())\n .run()\n return { id, dueDate: args.dueDate, deduped: false }\n },\n\n async renderUi(args: RenderUiArgs, ctx: AppToolContext): Promise<RenderUiResult> {\n assertRenderUiSchema(args.schema)\n const content = JSON.stringify(args.schema)\n const path = `${uiPrefix}/${ctx.threadId ?? 'global'}/${slug(args.title)}.json`\n await persistArtifact(path, content)\n await insertKnowledge(ctx.workspaceId, path, 'ui', args.title, content)\n return { path, content }\n },\n\n async addCitation(args: AddCitationArgs, ctx: AppToolContext): Promise<AddCitationResult> {\n const citationId = newId()\n const path = `${citationPrefix}/${slug(args.label ?? args.path)}-${citationId.slice(0, 8)}.json`\n const body = JSON.stringify({ sourcePath: args.path, quote: args.quote, label: args.label ?? null })\n await persistArtifact(path, body)\n await insertKnowledge(ctx.workspaceId, path, 'citation', args.label ?? null, body)\n return { citationId, path }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// D1-backed KnowledgeStateAccessor\n// ---------------------------------------------------------------------------\n\n/** Define options for accessing preset knowledge scoped to a specific workspace and configuration */\nexport interface PresetKnowledgeAccessorOptions {\n db: D1Like\n /** The active workspace — every `count` is scoped to it. */\n workspaceId: string\n /** Workspace config the `satisfiedBy: { config }` rules read. A resolved\n * object (dot-path lookup), or a function the accessor calls per path. */\n config: Record<string, unknown> | ((path: string) => unknown)\n /** The default workspace fk column a `count` rule scopes on when its rule\n * omits `where`. Default `'workspace_id'` (the preset schema convention). */\n defaultWhereColumn?: string\n}\n\nfunction readDotPath(obj: Record<string, unknown>, path: string): unknown {\n let cur: unknown = obj\n for (const part of path.split('.')) {\n if (cur == null || typeof cur !== 'object') return undefined\n cur = (cur as Record<string, unknown>)[part]\n }\n return cur\n}\n\n/**\n * The {@link KnowledgeStateAccessor} over the preset D1 schema — the seam that\n * lets the declarative `satisfiedBy` rules resolve with ZERO consumer code:\n * - `config(path)` reads the supplied workspace config by dot-path.\n * - `count({ table, where, statusIn })` runs `SELECT count(*)` scoped to the\n * active workspace (the rule's `where` column, default `workspace_id`),\n * optionally filtered to `statusIn` via a parameterized `IN (...)`.\n *\n * Identifiers (table/column) are validated against a safe pattern before\n * interpolation — they originate from the product's own config, never model\n * input, but we fail loud rather than build a malformed/injectable query.\n */\nexport function createD1KnowledgeStateAccessor(opts: PresetKnowledgeAccessorOptions): KnowledgeStateAccessor {\n const { db, workspaceId } = opts\n const defaultWhere = opts.defaultWhereColumn ?? 'workspace_id'\n const configFn = typeof opts.config === 'function' ? opts.config : (path: string) => readDotPath(opts.config as Record<string, unknown>, path)\n\n const isIdentifier = (s: string) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(s)\n\n return {\n config: configFn,\n async count(query) {\n if (!isIdentifier(query.table)) throw new Error(`unsafe table identifier: ${query.table}`)\n const whereCol = query.where ?? defaultWhere\n if (!isIdentifier(whereCol)) throw new Error(`unsafe where identifier: ${whereCol}`)\n\n let sql = `SELECT count(*) AS n FROM ${query.table} WHERE ${whereCol} = ?`\n const binds: unknown[] = [workspaceId]\n if (query.statusIn && query.statusIn.length > 0) {\n sql += ` AND status IN (${query.statusIn.map(() => '?').join(', ')})`\n binds.push(...query.statusIn)\n }\n const row = await db.prepare(sql).bind(...binds).first<{ n: number }>()\n return row?.n ?? 0\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Crypto + per-workspace key wiring\n// ---------------------------------------------------------------------------\n\n/** Build the {@link KeyCrypto} the billing key store uses — AES-256-GCM field\n * crypto bound to the product's 64-char-hex `ENCRYPTION_KEY` (or a resolver).\n * This is the concrete impl behind the `../billing` `KeyCrypto` seam. */\nexport function createPresetFieldCrypto(key: string | (() => string)): KeyCrypto {\n return createFieldCrypto(key)\n}\n\n/**\n * The {@link WorkspaceKeyStore} over the preset `workspace_keys` table — the\n * persistence seam the per-workspace key manager needs. \"Active\" = a row with a\n * null `revoked_at`. Pure D1 wiring; no key minting (that's the provisioner).\n */\nexport function createPresetWorkspaceKeyStore(db: D1Like): WorkspaceKeyStore {\n const W = PRESET_TABLES.workspaceKeys\n return {\n async getActive(workspaceId: string): Promise<WorkspaceKeyRecord | null> {\n const row = await db\n .prepare(\n `SELECT ${W.columns.id} AS id, ${W.columns.keyId} AS keyId, ${W.columns.keyEncrypted} AS keyEncrypted, ${W.columns.budgetUsd} AS budgetUsd, ${W.columns.expiresAt} AS expiresAt FROM ${W.name} WHERE ${W.columns.workspaceId} = ? AND ${W.columns.revokedAt} IS NULL ORDER BY ${W.columns.createdAt} DESC LIMIT 1`,\n )\n .bind(workspaceId)\n .first<{ id: string; keyId: string; keyEncrypted: string; budgetUsd: number; expiresAt: number | null }>()\n if (!row) return null\n return {\n id: row.id,\n keyId: row.keyId,\n keyEncrypted: row.keyEncrypted,\n budgetUsd: row.budgetUsd,\n expiresAt: row.expiresAt == null ? null : new Date(row.expiresAt),\n }\n },\n async listActive(workspaceId: string): Promise<Array<{ id: string; keyId: string }>> {\n const res = await db\n .prepare(`SELECT ${W.columns.id} AS id, ${W.columns.keyId} AS keyId FROM ${W.name} WHERE ${W.columns.workspaceId} = ? AND ${W.columns.revokedAt} IS NULL`)\n .bind(workspaceId)\n .all<{ id: string; keyId: string }>()\n return res.results\n },\n async insert(record): Promise<void> {\n await db\n .prepare(\n `INSERT INTO ${W.name} (${W.columns.id}, ${W.columns.workspaceId}, ${W.columns.keyId}, ${W.columns.keyEncrypted}, ${W.columns.budgetUsd}, ${W.columns.expiresAt}, ${W.columns.revokedAt}, ${W.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n )\n .bind(crypto.randomUUID(), record.workspaceId, record.keyId, record.keyEncrypted, record.budgetUsd, record.expiresAt.getTime(), Date.now())\n .run()\n },\n async markRevoked(id: string, now: Date): Promise<void> {\n await db\n .prepare(`UPDATE ${W.name} SET ${W.columns.revokedAt} = ? WHERE ${W.columns.id} = ?`)\n .bind(now.getTime(), id)\n .run()\n },\n }\n}\n\n/** Define preset billing options including database, provisioner, encryption key, budget, and optional settings */\nexport interface PresetBillingOptions {\n db: D1Like\n /** The key provisioner (`@tangle-network/tcloud`'s client satisfies it structurally). */\n provisioner: KeyProvisioner\n /** Field-crypto key (64-char hex) or resolver — encrypts the minted key at rest. */\n encryptionKey: string | (() => string)\n /** Default monthly USD allowance when a call doesn't specify one. */\n defaultBudgetUsd: number\n /** Injectable clock. */\n now?: () => Date\n /** tcloud product the key is scoped to. Default `'router'`. */\n product?: string\n}\n\n/**\n * Stand up the per-workspace budget-capped {@link WorkspaceKeyManager} on the\n * house stack: the preset `workspace_keys` D1 store + AES-GCM field crypto +\n * the consumer's tcloud provisioner. The mint/rotate/rollover/usage LOGIC lives\n * in `../billing`; this only binds it to the preset table + crypto.\n */\nexport function createPresetWorkspaceKeyManager(opts: PresetBillingOptions): WorkspaceKeyManager {\n return createWorkspaceKeyManager({\n provisioner: opts.provisioner,\n store: createPresetWorkspaceKeyStore(opts.db),\n crypto: createPresetFieldCrypto(opts.encryptionKey),\n defaultBudgetUsd: opts.defaultBudgetUsd,\n now: opts.now,\n product: opts.product,\n })\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,eAAsB,iCAKpB,SACA,OACqE;AACrE,MAAI;AACF,WAAO;AAAA,MACL,UAAU,MAAM,QAAQ,OAAO,KAAK;AAAA,MACpC,SAAS;AAAA,IACX;AAAA,EACF,SAAS,aAAa;AACpB,QAAI;AACF,YAAM,WAAW,MAAM,QAAQ,IAAI,MAAM,EAAE;AAC3C,YAAM,SAAS,MAAM,SAAS,OAAO;AACrC,aAAO,EAAE,UAAU,SAAS,OAAO,OAAO;AAAA,IAC5C,QAAQ;AACN,YAAM;AAAA,IACR;AAAA,EACF;AACF;;;ACeA,SAAS,eAAe,SAA6C;AACnE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cloudflare/native-completion-workflow.ts","../../src/preset-cloudflare/headers.ts","../../src/preset-cloudflare/index.ts"],"sourcesContent":["/**\n * The structural part of a Cloudflare Workflow instance used to prove that a\n * failed create call actually left an addressable durable instance behind.\n */\nexport interface CloudflareWorkflowInstanceLike<TStatus = unknown> {\n status(): Promise<TStatus>\n}\n\n/** The structural binding implemented by Cloudflare's `Workflow<TParams>`. */\nexport interface CloudflareWorkflowBindingLike<\n TParams,\n TStatus = unknown,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus> =\n CloudflareWorkflowInstanceLike<TStatus>,\n> {\n create(input: { id: string; params: TParams }): Promise<TInstance>\n get(id: string): Promise<TInstance>\n}\n\nexport interface EnsureCloudflareWorkflowInstanceResult<\n TStatus,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus>,\n> {\n instance: TInstance\n /** False only when create failed but the same id was proven readable. */\n created: boolean\n /** Present on reuse because reading status is the proof the instance exists. */\n status?: TStatus\n}\n\n/**\n * Create one durable Workflow instance, or prove an instance with the same id\n * already exists before accepting a create error as an idempotent retry.\n *\n * Cloudflare does not expose a stable duplicate-error class. Matching error\n * text can therefore swallow unrelated failures. This helper uses the durable\n * resource itself as proof: `get(id).status()` must succeed, otherwise the\n * original create error is rethrown.\n */\nexport async function ensureCloudflareWorkflowInstance<\n TParams,\n TStatus,\n TInstance extends CloudflareWorkflowInstanceLike<TStatus>,\n>(\n binding: CloudflareWorkflowBindingLike<TParams, TStatus, TInstance>,\n input: { id: string; params: TParams },\n): Promise<EnsureCloudflareWorkflowInstanceResult<TStatus, TInstance>> {\n try {\n return {\n instance: await binding.create(input),\n created: true,\n }\n } catch (createError) {\n try {\n const instance = await binding.get(input.id)\n const status = await instance.status()\n return { instance, created: false, status }\n } catch {\n throw createError\n }\n }\n}\n","import type { TurnDriveResult } from '@tangle-network/sandbox'\nimport type { Outcome } from '../sandbox/outcome'\n\n/** The stable identity a Workflow reuses on every retry of one turn. */\nexport interface DetachedTurnWorkflowIdentity {\n /** Sandbox session resume key. */\n sessionId: string\n /** Sandbox completed-turn idempotency key. */\n turnId: string\n}\n\n/** The part of Cloudflare's Workflow event needed by the tick. */\nexport interface CloudflareWorkflowEventLike<TPayload> {\n payload: TPayload\n}\n\n/** A duration accepted by Cloudflare Workflow `step.sleep`. */\nexport type CloudflareWorkflowSleepDuration =\n | `${number} ${\n | 'second'\n | 'seconds'\n | 'minute'\n | 'minutes'\n | 'hour'\n | 'hours'\n | 'day'\n | 'days'\n | 'week'\n | 'weeks'\n | 'month'\n | 'months'\n | 'year'\n | 'years'}`\n | number\n\n/** The durable Workflow operations used by the tick. */\nexport interface CloudflareWorkflowStepLike {\n do<T>(name: string, callback: (context: unknown) => Promise<T>): Promise<T>\n sleep(name: string, duration: CloudflareWorkflowSleepDuration): Promise<void>\n}\n\n/** The states returned by the Sandbox `driveTurn` primitive. */\nexport type DetachedTurnDriveState = TurnDriveResult['state']\n\n/** The small state contract a durable tick needs. Product observers may carry\n * a richer terminal receipt than Sandbox's `TurnDriveResult`. */\nexport interface DetachedTurnDriveResultLike {\n state: DetachedTurnDriveState\n}\n\n/** The terminal result passed to product settlement. */\nexport type DetachedTurnTerminalResult<\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> = Exclude<TResult, { state: 'running' }>\n\n/** A drive call's retryable transport boundary. */\nexport type DetachedTurnDriveOutcome<\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> = Outcome<TResult>\n\n/** Options for one durable detached-turn Workflow run. */\nexport interface DetachedTurnWorkflowTickOptions<\n TPayload extends DetachedTurnWorkflowIdentity,\n TSettled,\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n> {\n event: CloudflareWorkflowEventLike<TPayload>\n step: CloudflareWorkflowStepLike\n /** One SDK drive pass. Rejected results must not enter the Workflow cache. */\n drive: (payload: TPayload) => Promise<DetachedTurnDriveOutcome<TResult>>\n /** Must be idempotent: the Worker can stop after the write but before commit. */\n settle: (payload: TPayload, result: DetachedTurnTerminalResult<TResult>) => Promise<TSettled>\n /** Wait between passes: one duration, or one per zero-based pass so a long\n * turn polls less often. It must depend only on the pass number, so a\n * replayed Workflow takes the same steps. Default: 5 seconds. */\n pollDelay?: CloudflareWorkflowSleepDuration | ((attempt: number) => CloudflareWorkflowSleepDuration)\n stepName?: string\n}\n\nfunction assertIdentity(payload: DetachedTurnWorkflowIdentity): void {\n if (!payload || typeof payload.sessionId !== 'string' || !payload.sessionId.trim()) {\n throw new Error('detached turn Workflow payload requires a non-empty sessionId')\n }\n if (typeof payload.turnId !== 'string' || !payload.turnId.trim()) {\n throw new Error('detached turn Workflow payload requires a non-empty turnId')\n }\n}\n\n// Keyed by the SDK's own union, so a state a new Sandbox adds fails this\n// package's build instead of retrying a settled turn as \"unknown\" forever.\nconst DRIVE_STATES: Record<DetachedTurnDriveState, true> = {\n running: true,\n completed: true,\n failed: true,\n awaiting_plan_decision: true,\n blocked_on_approval: true,\n awaiting_question: true,\n awaiting_interaction: true,\n}\n\nfunction isKnownDriveState(state: unknown): state is DetachedTurnDriveState {\n return typeof state === 'string' && Object.hasOwn(DRIVE_STATES, state)\n}\n\nfunction checkedDriveResult<TResult extends DetachedTurnDriveResultLike>(value: TResult): TResult {\n const state = (value as { state?: unknown } | null)?.state\n if (!isKnownDriveState(state)) {\n throw new Error(`detached turn drive returned unknown state: ${String(state)}`)\n }\n return value\n}\n\n/**\n * Drive a detached SDK turn with durable steps, not an HTTP waitUntil lifetime.\n * Stable step names let an evicted Workflow resume without repeating committed\n * passes. Validation belongs inside step.do so a transient malformed response\n * is retried rather than committed permanently as a poisoned checkpoint.\n */\nexport async function runDetachedTurnWorkflowTick<\n TPayload extends DetachedTurnWorkflowIdentity,\n TSettled,\n TResult extends DetachedTurnDriveResultLike = TurnDriveResult,\n>(\n options: DetachedTurnWorkflowTickOptions<TPayload, TSettled, TResult>,\n): Promise<TSettled> {\n assertIdentity(options.event?.payload)\n // Never allow a callback to change the admission identity for later passes.\n const payload = Object.freeze({ ...options.event.payload }) as TPayload\n const name = options.stepName ?? 'detached-turn'\n const pollDelay = options.pollDelay ?? '5 seconds'\n const delayFor = (attempt: number): CloudflareWorkflowSleepDuration =>\n typeof pollDelay === 'function' ? pollDelay(attempt) : pollDelay\n let attempt = 0\n let terminalResult: DetachedTurnTerminalResult<TResult>\n while (true) {\n const driveResult = checkedDriveResult(await options.step.do<TResult>(`${name}:drive:${attempt}`, async () => {\n const outcome = await options.drive(payload)\n if (!outcome.succeeded) throw outcome.error\n return checkedDriveResult(outcome.value)\n }))\n // Validate replayed values as well, including checkpoints from older code.\n if (driveResult.state !== 'running') {\n terminalResult = driveResult as DetachedTurnTerminalResult<TResult>\n break\n }\n await options.step.sleep(`${name}:wait:${attempt}`, delayFor(attempt))\n attempt += 1\n }\n return options.step.do(`${name}:settle`, () => options.settle(payload, terminalResult))\n}\n","/**\n * Durable terminal assembly for a native turn admitted by another request.\n * Product callbacks own domain effects and may use their own Workflow steps;\n * this helper never nests those callbacks inside `step.do`.\n */\n\nimport type {\n NativeCompletionObservation,\n NativeCompletionReceipt,\n} from '../chat-routes/native-completion'\nimport {\n runDetachedTurnWorkflowTick,\n type CloudflareWorkflowEventLike,\n type CloudflareWorkflowSleepDuration,\n type CloudflareWorkflowStepLike,\n type DetachedTurnWorkflowIdentity,\n} from './detached-turn-workflow'\n\n/** Stable identity required to resume a registered native completion. */\nexport interface NativeCompletionWorkflowPayload extends DetachedTurnWorkflowIdentity {\n registeredAt: number\n}\n\ntype NativeCompletionDriveResult = NativeCompletionObservation\n\nexport interface NativeCompletionWorkflowOptions<\n TPayload extends NativeCompletionWorkflowPayload,\n TMessageId,\n> {\n event: CloudflareWorkflowEventLike<TPayload>\n step: CloudflareWorkflowStepLike\n /** Read-only exact observation. It must never dispatch, drive, or cancel. */\n observe(payload: TPayload): Promise<NativeCompletionObservation>\n /**\n * Product-owned idempotent preparation, for example artifact promotion and\n * output classification. It runs outside an enclosing Workflow step so a\n * product may use its own named steps without nesting `step.do`.\n */\n prepare?(payload: TPayload, receipt: NativeCompletionReceipt): Promise<NativeCompletionReceipt>\n /**\n * Durable transcript write. Without a message id it must upsert the turn's\n * one row: the terminal observation step checkpoints the observed receipt\n * with it before preparation, and the transcript step writes the prepared\n * receipt over that checkpoint. A supplied message id updates the existing row.\n */\n persistTranscript(\n payload: TPayload,\n receipt: NativeCompletionReceipt,\n existingMessageId?: TMessageId,\n ): Promise<TMessageId>\n /**\n * Product-owned idempotent settlement. A rejection leaves the lock held and\n * skips finalization, making the failed dependency observable and retryable.\n */\n settle(\n payload: TPayload,\n receipt: NativeCompletionReceipt,\n messageId: TMessageId,\n ): Promise<NativeCompletionReceipt | void>\n /** Optional product buffer completion after successful settlement. */\n finalizeBuffer?(payload: TPayload, receipt: NativeCompletionReceipt, messageId: TMessageId): Promise<void>\n /** Release the product lock only after every terminal effect completed. */\n releaseLock(payload: TPayload): Promise<void>\n /** Default: 5 s for the first two minutes, 15 s until thirty minutes, then 30 s. */\n pollDelay?: CloudflareWorkflowSleepDuration | ((attempt: number) => CloudflareWorkflowSleepDuration)\n stepName?: string\n}\n\n/**\n * Wait before observation pass `attempt + 1`: 5 s for the first two minutes,\n * 15 s until thirty minutes, then 30 s. Each pass is two Workflow steps and a\n * Workflow allows 10,000, so a fixed 5 s wait ends an instance after about\n * seven hours; this schedule leaves room for more than forty.\n */\nfunction nativeCompletionPollDelay(attempt: number): CloudflareWorkflowSleepDuration {\n if (attempt < 24) return '5 seconds'\n if (attempt < 136) return '15 seconds'\n return '30 seconds'\n}\n\nfunction validObservation(value: NativeCompletionObservation): NativeCompletionDriveResult {\n if (!value || (value.state !== 'running' && value.state !== 'completed' && value.state !== 'failed')) {\n throw new Error(`native completion observer returned unknown state: ${String((value as { state?: unknown } | null)?.state)}`)\n }\n if (value.state !== 'running' && !value.receipt) {\n throw new Error('native completion observer returned a terminal state without a receipt')\n }\n return value\n}\n\n/**\n * Drive exact observation through durable retry steps, then run the terminal\n * sequence once. `prepare` and `settle` are deliberately outside `step.do` so\n * product callbacks can compose their own named Cloudflare Workflow steps.\n */\nexport async function runNativeCompletionWorkflow<\n TPayload extends NativeCompletionWorkflowPayload,\n TMessageId,\n>(options: NativeCompletionWorkflowOptions<TPayload, TMessageId>): Promise<NativeCompletionReceipt> {\n const name = options.stepName ?? 'native-completion'\n let receipt = await runDetachedTurnWorkflowTick<\n TPayload,\n NativeCompletionReceipt,\n NativeCompletionDriveResult\n >({\n event: options.event,\n step: options.step,\n pollDelay: options.pollDelay ?? nativeCompletionPollDelay,\n stepName: `${name}:observe`,\n drive: async (payload) => {\n const observation = validObservation(await options.observe(payload))\n // The observed answer is written in the same step that observed it, so\n // a later preparation, settlement or Workflow failure cannot lose it.\n if (observation.state !== 'running') await options.persistTranscript(payload, observation.receipt)\n return { succeeded: true, value: observation }\n },\n settle: async (_payload, result) => result.receipt,\n })\n\n if (options.prepare) receipt = await options.prepare(options.event.payload, receipt)\n const messageId = await options.step.do(`${name}:persist-transcript`, () => (\n options.persistTranscript(options.event.payload, receipt)\n ))\n const settledReceipt = await options.settle(options.event.payload, receipt, messageId)\n if (settledReceipt) {\n receipt = settledReceipt\n await options.step.do(`${name}:persist-final-transcript`, () => (\n options.persistTranscript(options.event.payload, receipt, messageId)\n ))\n }\n if (options.finalizeBuffer) {\n await options.step.do(`${name}:finalize-buffer`, () => (\n options.finalizeBuffer!(options.event.payload, receipt, messageId)\n ))\n }\n await options.step.do(`${name}:release-lock`, () => options.releaseLock(options.event.payload))\n return receipt\n}\n","const HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\n/** One path rule in Cloudflare's static-asset `_headers` file. */\nexport interface CloudflareHeadersRule {\n pattern: string\n headers: Readonly<Record<string, string>>\n}\n\nfunction assertSingleLine(value: string, label: string): void {\n if (value.length === 0 || /[\\r\\n]/.test(value)) {\n throw new Error(`${label} must be a non-empty single line`)\n }\n}\n\n/**\n * Render native Cloudflare static-asset header rules.\n *\n * Values are validated before serialization so a product setting cannot add a\n * second path rule or response header through a newline.\n */\nexport function renderCloudflareHeadersFile(\n rules: readonly CloudflareHeadersRule[],\n): string {\n if (rules.length === 0) {\n throw new Error('At least one Cloudflare header rule is required')\n }\n\n const renderedRules = rules.map(({ pattern, headers }) => {\n assertSingleLine(pattern, 'Cloudflare header pattern')\n if (!pattern.startsWith('/') || /\\s/.test(pattern)) {\n throw new Error('Cloudflare header patterns must start with / and contain no whitespace')\n }\n\n const entries = Object.entries(headers)\n if (entries.length === 0) {\n throw new Error(`Cloudflare header rule ${pattern} must contain at least one header`)\n }\n\n const renderedHeaders = entries.map(([name, value]) => {\n if (!HEADER_NAME.test(name)) {\n throw new Error(`Invalid HTTP header name: ${name}`)\n }\n assertSingleLine(value, `Cloudflare header ${name}`)\n return ` ${name}: ${value}`\n })\n\n return [pattern, ...renderedHeaders].join('\\n')\n })\n\n return `${renderedRules.join('\\n\\n')}\\n`\n}\n","/**\n * `@tangle-network/agent-app/preset-cloudflare` — the batteries-included default\n * stack.\n *\n * Every fleet agent runs the SAME backend: Cloudflare D1 (SQLite) through\n * Drizzle for state, a KV namespace as the artifact vault, AES-GCM field crypto\n * for PII, and per-workspace budget-capped model keys. The other agent-app\n * modules are pure SEAMS — `./tools` needs an `AppToolHandlers`, `./knowledge`\n * needs a `KnowledgeStateAccessor`, `./billing` needs a `WorkspaceKeyStore` +\n * `KeyCrypto`. This module is the ONE implementation of those seams against the\n * house stack, so a consumer that runs D1 + KV stands the whole shell up with\n * config + bindings and ZERO handler code.\n *\n * Layering:\n * - Drizzle is a PEER (the consumer installs `drizzle-orm`, never bundled). The\n * schema is therefore expressed two ways that need no import here: the plain\n * DDL ({@link PRESET_MIGRATION_SQL}) a consumer runs to create the tables, and\n * a {@link createPresetDrizzleSchema} factory that takes the consumer's\n * `drizzle-orm/sqlite-core` builder module and returns the typed tables. The\n * column names in {@link PRESET_TABLES} are the contract the handlers,\n * accessor, and DDL all agree on.\n * - D1 + KV are STRUCTURAL: {@link D1Like} (Cloudflare `D1Database` satisfies it)\n * and `KvLike` from `../web` (Cloudflare `KVNamespace` satisfies it). No\n * `@cloudflare/workers-types` dependency.\n * - Crypto/billing reuse `../crypto` + `../billing` exactly — this only wires\n * them to the D1 key table.\n */\n\nimport { createFieldCrypto } from '../crypto/index'\nimport {\n createWorkspaceKeyManager,\n type KeyCrypto,\n type KeyProvisioner,\n type WorkspaceKeyManager,\n type WorkspaceKeyRecord,\n type WorkspaceKeyStore,\n} from '../billing/index'\nimport type { KnowledgeStateAccessor } from '../knowledge/index'\nimport type {\n AddCitationArgs,\n AddCitationResult,\n AppToolContext,\n AppToolHandlers,\n RenderUiArgs,\n RenderUiResult,\n ScheduleFollowupArgs,\n ScheduleFollowupResult,\n SubmitProposalArgs,\n SubmitProposalResult,\n} from '../tools/index'\nimport { assertRenderUiSchema } from '../tools/render-ui-schema'\nimport type { KvLike } from '../web/index'\n\nexport {\n ensureCloudflareWorkflowInstance,\n type CloudflareWorkflowBindingLike,\n type CloudflareWorkflowInstanceLike,\n type EnsureCloudflareWorkflowInstanceResult,\n} from './workflow-instance'\n\nexport {\n runDetachedTurnWorkflowTick,\n type CloudflareWorkflowEventLike,\n type CloudflareWorkflowSleepDuration,\n type CloudflareWorkflowStepLike,\n type DetachedTurnDriveOutcome,\n type DetachedTurnDriveState,\n type DetachedTurnTerminalResult,\n type DetachedTurnWorkflowIdentity,\n type DetachedTurnWorkflowTickOptions,\n} from './detached-turn-workflow'\n\nexport {\n runNativeCompletionWorkflow,\n type NativeCompletionWorkflowOptions,\n type NativeCompletionWorkflowPayload,\n} from './native-completion-workflow'\n\nexport {\n renderCloudflareHeadersFile,\n type CloudflareHeadersRule,\n} from './headers'\n\n// ---------------------------------------------------------------------------\n// D1 structural seam\n//\n// The minimal surface of Cloudflare's `D1Database` the handlers + accessor use.\n// `D1Database` satisfies it structurally, so the consumer passes `env.DB`\n// directly and tests pass an in-memory fake. We keep it to the\n// prepare/bind/first/run/all shape D1 already exposes — no Drizzle here, so the\n// default handlers run on a fresh Worker with only the D1 binding.\n// ---------------------------------------------------------------------------\n\n/** A prepared, bound D1 statement. */\nexport interface D1PreparedLike {\n bind(...values: unknown[]): D1PreparedLike\n first<T = Record<string, unknown>>(colName?: string): Promise<T | null>\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n}\n\n/** The D1 surface the preset needs. Cloudflare `D1Database` satisfies it. */\nexport interface D1Like {\n prepare(query: string): D1PreparedLike\n}\n\n// ---------------------------------------------------------------------------\n// Default schema\n//\n// The four tables the default handlers + accessor read/write. Column names are\n// the single source of truth shared by the DDL, the Drizzle factory, the\n// handlers, and the accessor. Every table is workspace-scoped on `workspace_id`\n// (the accessor's default `where` column) so the knowledge `count` rule and the\n// tool writes agree without per-consumer wiring.\n//\n// Deliberately NOT here: chat thread/message tables. `/chat-store` is the\n// single thread-schema owner (`createChatTables` + `createChatStore`); the\n// preset once declared an unconsumed `threads` DDL, removed so two schemas\n// can't drift.\n// ---------------------------------------------------------------------------\n\n/** The preset table + column names — the contract the DDL, Drizzle schema,\n * handlers, and accessor share. Exposed so a consumer can reference a column\n * without a string literal. */\nexport const PRESET_TABLES = {\n proposals: {\n name: 'proposals',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n threadId: 'thread_id',\n type: 'type',\n title: 'title',\n description: 'description',\n status: 'status',\n createdBy: 'created_by',\n createdAt: 'created_at',\n },\n },\n knowledge: {\n name: 'knowledge',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n path: 'path',\n kind: 'kind',\n label: 'label',\n content: 'content',\n createdAt: 'created_at',\n },\n },\n deadlines: {\n name: 'deadlines',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n threadId: 'thread_id',\n title: 'title',\n dueDate: 'due_date',\n priority: 'priority',\n status: 'status',\n createdAt: 'created_at',\n },\n },\n workspaceKeys: {\n name: 'workspace_keys',\n columns: {\n id: 'id',\n workspaceId: 'workspace_id',\n keyId: 'key_id',\n keyEncrypted: 'key_encrypted',\n budgetUsd: 'budget_usd',\n expiresAt: 'expires_at',\n revokedAt: 'revoked_at',\n createdAt: 'created_at',\n },\n },\n} as const\n\n/**\n * Plain DDL for the preset schema — run by a consumer to create the tables with\n * ZERO drizzle (`for (const sql of PRESET_MIGRATION_SQL) await db.prepare(sql).run()`,\n * or paste into a `.sql` migration). One statement per table so D1's\n * single-statement `prepare` accepts each. Matches {@link PRESET_TABLES} exactly.\n */\nexport const PRESET_MIGRATION_SQL: readonly string[] = [\n `CREATE TABLE IF NOT EXISTS proposals (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n thread_id TEXT,\n type TEXT NOT NULL,\n title TEXT NOT NULL,\n description TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n created_by TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS knowledge (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n path TEXT NOT NULL,\n kind TEXT NOT NULL,\n label TEXT,\n content TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS deadlines (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n thread_id TEXT,\n title TEXT NOT NULL,\n due_date TEXT NOT NULL,\n priority TEXT,\n status TEXT NOT NULL DEFAULT 'scheduled',\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS workspace_keys (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n key_id TEXT NOT NULL,\n key_encrypted TEXT NOT NULL,\n budget_usd REAL NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS idx_proposals_ws ON proposals (workspace_id, status)`,\n `CREATE INDEX IF NOT EXISTS idx_deadlines_ws ON deadlines (workspace_id, status)`,\n `CREATE INDEX IF NOT EXISTS idx_knowledge_ws ON knowledge (workspace_id)`,\n `CREATE INDEX IF NOT EXISTS idx_workspace_keys_ws ON workspace_keys (workspace_id, revoked_at)`,\n]\n\n/** A chainable column builder — every modifier returns the builder so calls\n * like `.notNull().default('pending')` typecheck. The concrete drizzle builders\n * satisfy this structurally. */\nexport interface DrizzleColumnLike {\n primaryKey: () => DrizzleColumnLike\n notNull: () => DrizzleColumnLike\n default: (v: unknown) => DrizzleColumnLike\n}\n\n/** The shape of a `drizzle-orm/sqlite-core` module — the few builders the\n * preset schema uses. The consumer passes the real module; agent-app never\n * imports it (it stays a peer). */\nexport interface DrizzleSqliteCoreLike {\n sqliteTable: (name: string, columns: Record<string, DrizzleColumnLike>) => unknown\n text: (name?: string) => DrizzleColumnLike\n integer: (name?: string, config?: unknown) => DrizzleColumnLike\n real: (name?: string) => DrizzleColumnLike\n}\n\n/**\n * Build the typed Drizzle schema for the preset, given the consumer's\n * `drizzle-orm/sqlite-core` module. Returns one table object per\n * {@link PRESET_TABLES} entry — pass to `drizzle(db, { schema })` for typed\n * queries, or to drizzle-kit for migration generation. agent-app never imports\n * drizzle; the builder module is the seam.\n *\n * ```ts\n * import * as d from 'drizzle-orm/sqlite-core'\n * const schema = createPresetDrizzleSchema(d)\n * ```\n */\nexport function createPresetDrizzleSchema(d: DrizzleSqliteCoreLike) {\n const { sqliteTable, text, integer, real } = d\n const C = PRESET_TABLES\n return {\n proposals: sqliteTable(C.proposals.name, {\n id: text(C.proposals.columns.id).primaryKey(),\n workspaceId: text(C.proposals.columns.workspaceId).notNull(),\n threadId: text(C.proposals.columns.threadId),\n type: text(C.proposals.columns.type).notNull(),\n title: text(C.proposals.columns.title).notNull(),\n description: text(C.proposals.columns.description),\n status: text(C.proposals.columns.status).notNull().default('pending'),\n createdBy: text(C.proposals.columns.createdBy),\n createdAt: integer(C.proposals.columns.createdAt).notNull(),\n }),\n knowledge: sqliteTable(C.knowledge.name, {\n id: text(C.knowledge.columns.id).primaryKey(),\n workspaceId: text(C.knowledge.columns.workspaceId).notNull(),\n path: text(C.knowledge.columns.path).notNull(),\n kind: text(C.knowledge.columns.kind).notNull(),\n label: text(C.knowledge.columns.label),\n content: text(C.knowledge.columns.content),\n createdAt: integer(C.knowledge.columns.createdAt).notNull(),\n }),\n deadlines: sqliteTable(C.deadlines.name, {\n id: text(C.deadlines.columns.id).primaryKey(),\n workspaceId: text(C.deadlines.columns.workspaceId).notNull(),\n threadId: text(C.deadlines.columns.threadId),\n title: text(C.deadlines.columns.title).notNull(),\n dueDate: text(C.deadlines.columns.dueDate).notNull(),\n priority: text(C.deadlines.columns.priority),\n status: text(C.deadlines.columns.status).notNull().default('scheduled'),\n createdAt: integer(C.deadlines.columns.createdAt).notNull(),\n }),\n workspaceKeys: sqliteTable(C.workspaceKeys.name, {\n id: text(C.workspaceKeys.columns.id).primaryKey(),\n workspaceId: text(C.workspaceKeys.columns.workspaceId).notNull(),\n keyId: text(C.workspaceKeys.columns.keyId).notNull(),\n keyEncrypted: text(C.workspaceKeys.columns.keyEncrypted).notNull(),\n budgetUsd: real(C.workspaceKeys.columns.budgetUsd).notNull(),\n expiresAt: integer(C.workspaceKeys.columns.expiresAt).notNull(),\n revokedAt: integer(C.workspaceKeys.columns.revokedAt),\n createdAt: integer(C.workspaceKeys.columns.createdAt).notNull(),\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Default AppToolHandlers over D1 + KV\n// ---------------------------------------------------------------------------\n\n/** The KV-backed vault. `KvLike` (from `../web`) is the structural KV contract;\n * Cloudflare `KVNamespace` satisfies it. Artifacts are stored under their path. */\nexport type VaultKv = KvLike\n\n/** Define configuration options for handling preset tools including database, vault, and optional utilities */\nexport interface PresetToolHandlerOptions {\n /** The D1 database (Cloudflare `D1Database` satisfies {@link D1Like}). */\n db: D1Like\n /** The KV namespace used as the artifact vault. */\n vault: VaultKv\n /** Id generator. Default `crypto.randomUUID`. Injectable for deterministic tests. */\n newId?: () => string\n /** Clock (epoch ms). Default `Date.now`. Injectable for deterministic tests. */\n now?: () => number\n /** Vault path prefix for `render_ui` artifacts. Default `'ui'`. */\n uiPathPrefix?: string\n /** Vault path prefix for `add_citation` artifacts. Default `'citations'`. */\n citationPathPrefix?: string\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 64) || 'item'\n}\n\n/**\n * The default {@link AppToolHandlers} for the house stack:\n * - `submit_proposal` → insert a `proposals` row (`status='pending'`), deduped\n * on (workspace, title) so a retried turn doesn't double-queue.\n * - `schedule_followup` → insert a `deadlines` row, deduped on (workspace, title, due_date).\n * - `render_ui` → write the schema JSON as a `ui/<thread>/<slug>.json`\n * vault artifact AND a `knowledge` row pointing at it.\n * - `add_citation` → write the quote as a `citations/<slug>.json` artifact AND\n * a `knowledge` row.\n *\n * Returns the EXACT persisted content from `render_ui` (per the seam contract) so\n * a completion oracle sees real bytes. Pure seam wiring: a consumer that runs\n * D1 + KV gets all four tools with no handler code.\n */\nexport function createPresetToolHandlers(opts: PresetToolHandlerOptions): AppToolHandlers {\n const { db, vault } = opts\n const newId = opts.newId ?? (() => crypto.randomUUID())\n const now = opts.now ?? (() => Date.now())\n const uiPrefix = opts.uiPathPrefix ?? 'ui'\n const citationPrefix = opts.citationPathPrefix ?? 'citations'\n const P = PRESET_TABLES.proposals\n const D = PRESET_TABLES.deadlines\n const K = PRESET_TABLES.knowledge\n\n async function persistArtifact(path: string, body: string): Promise<void> {\n await vault.put(path, body)\n }\n\n async function insertKnowledge(workspaceId: string, path: string, kind: string, label: string | null, content: string): Promise<void> {\n await db\n .prepare(\n `INSERT INTO ${K.name} (${K.columns.id}, ${K.columns.workspaceId}, ${K.columns.path}, ${K.columns.kind}, ${K.columns.label}, ${K.columns.content}, ${K.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n )\n .bind(newId(), workspaceId, path, kind, label, content, now())\n .run()\n }\n\n return {\n async submitProposal(args: SubmitProposalArgs, ctx: AppToolContext): Promise<SubmitProposalResult> {\n const existing = await db\n .prepare(`SELECT ${P.columns.id} AS id FROM ${P.name} WHERE ${P.columns.workspaceId} = ? AND ${P.columns.title} = ? LIMIT 1`)\n .bind(ctx.workspaceId, args.title)\n .first<{ id: string }>()\n if (existing) return { proposalId: existing.id, deduped: true }\n\n const id = newId()\n await db\n .prepare(\n `INSERT INTO ${P.name} (${P.columns.id}, ${P.columns.workspaceId}, ${P.columns.threadId}, ${P.columns.type}, ${P.columns.title}, ${P.columns.description}, ${P.columns.status}, ${P.columns.createdBy}, ${P.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,\n )\n .bind(id, ctx.workspaceId, ctx.threadId, args.type, args.title, args.description ?? null, ctx.userId, now())\n .run()\n return { proposalId: id, deduped: false }\n },\n\n async scheduleFollowup(args: ScheduleFollowupArgs, ctx: AppToolContext): Promise<ScheduleFollowupResult> {\n const existing = await db\n .prepare(\n `SELECT ${D.columns.id} AS id, ${D.columns.dueDate} AS dueDate FROM ${D.name} WHERE ${D.columns.workspaceId} = ? AND ${D.columns.title} = ? AND ${D.columns.dueDate} = ? LIMIT 1`,\n )\n .bind(ctx.workspaceId, args.title, args.dueDate)\n .first<{ id: string; dueDate: string }>()\n if (existing) return { id: existing.id, dueDate: existing.dueDate, deduped: true }\n\n const id = newId()\n await db\n .prepare(\n `INSERT INTO ${D.name} (${D.columns.id}, ${D.columns.workspaceId}, ${D.columns.threadId}, ${D.columns.title}, ${D.columns.dueDate}, ${D.columns.priority}, ${D.columns.status}, ${D.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, 'scheduled', ?)`,\n )\n .bind(id, ctx.workspaceId, ctx.threadId, args.title, args.dueDate, args.priority ?? null, now())\n .run()\n return { id, dueDate: args.dueDate, deduped: false }\n },\n\n async renderUi(args: RenderUiArgs, ctx: AppToolContext): Promise<RenderUiResult> {\n assertRenderUiSchema(args.schema)\n const content = JSON.stringify(args.schema)\n const path = `${uiPrefix}/${ctx.threadId ?? 'global'}/${slug(args.title)}.json`\n await persistArtifact(path, content)\n await insertKnowledge(ctx.workspaceId, path, 'ui', args.title, content)\n return { path, content }\n },\n\n async addCitation(args: AddCitationArgs, ctx: AppToolContext): Promise<AddCitationResult> {\n const citationId = newId()\n const path = `${citationPrefix}/${slug(args.label ?? args.path)}-${citationId.slice(0, 8)}.json`\n const body = JSON.stringify({ sourcePath: args.path, quote: args.quote, label: args.label ?? null })\n await persistArtifact(path, body)\n await insertKnowledge(ctx.workspaceId, path, 'citation', args.label ?? null, body)\n return { citationId, path }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// D1-backed KnowledgeStateAccessor\n// ---------------------------------------------------------------------------\n\n/** Define options for accessing preset knowledge scoped to a specific workspace and configuration */\nexport interface PresetKnowledgeAccessorOptions {\n db: D1Like\n /** The active workspace — every `count` is scoped to it. */\n workspaceId: string\n /** Workspace config the `satisfiedBy: { config }` rules read. A resolved\n * object (dot-path lookup), or a function the accessor calls per path. */\n config: Record<string, unknown> | ((path: string) => unknown)\n /** The default workspace fk column a `count` rule scopes on when its rule\n * omits `where`. Default `'workspace_id'` (the preset schema convention). */\n defaultWhereColumn?: string\n}\n\nfunction readDotPath(obj: Record<string, unknown>, path: string): unknown {\n let cur: unknown = obj\n for (const part of path.split('.')) {\n if (cur == null || typeof cur !== 'object') return undefined\n cur = (cur as Record<string, unknown>)[part]\n }\n return cur\n}\n\n/**\n * The {@link KnowledgeStateAccessor} over the preset D1 schema — the seam that\n * lets the declarative `satisfiedBy` rules resolve with ZERO consumer code:\n * - `config(path)` reads the supplied workspace config by dot-path.\n * - `count({ table, where, statusIn })` runs `SELECT count(*)` scoped to the\n * active workspace (the rule's `where` column, default `workspace_id`),\n * optionally filtered to `statusIn` via a parameterized `IN (...)`.\n *\n * Identifiers (table/column) are validated against a safe pattern before\n * interpolation — they originate from the product's own config, never model\n * input, but we fail loud rather than build a malformed/injectable query.\n */\nexport function createD1KnowledgeStateAccessor(opts: PresetKnowledgeAccessorOptions): KnowledgeStateAccessor {\n const { db, workspaceId } = opts\n const defaultWhere = opts.defaultWhereColumn ?? 'workspace_id'\n const configFn = typeof opts.config === 'function' ? opts.config : (path: string) => readDotPath(opts.config as Record<string, unknown>, path)\n\n const isIdentifier = (s: string) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(s)\n\n return {\n config: configFn,\n async count(query) {\n if (!isIdentifier(query.table)) throw new Error(`unsafe table identifier: ${query.table}`)\n const whereCol = query.where ?? defaultWhere\n if (!isIdentifier(whereCol)) throw new Error(`unsafe where identifier: ${whereCol}`)\n\n let sql = `SELECT count(*) AS n FROM ${query.table} WHERE ${whereCol} = ?`\n const binds: unknown[] = [workspaceId]\n if (query.statusIn && query.statusIn.length > 0) {\n sql += ` AND status IN (${query.statusIn.map(() => '?').join(', ')})`\n binds.push(...query.statusIn)\n }\n const row = await db.prepare(sql).bind(...binds).first<{ n: number }>()\n return row?.n ?? 0\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Crypto + per-workspace key wiring\n// ---------------------------------------------------------------------------\n\n/** Build the {@link KeyCrypto} the billing key store uses — AES-256-GCM field\n * crypto bound to the product's 64-char-hex `ENCRYPTION_KEY` (or a resolver).\n * This is the concrete impl behind the `../billing` `KeyCrypto` seam. */\nexport function createPresetFieldCrypto(key: string | (() => string)): KeyCrypto {\n return createFieldCrypto(key)\n}\n\n/**\n * The {@link WorkspaceKeyStore} over the preset `workspace_keys` table — the\n * persistence seam the per-workspace key manager needs. \"Active\" = a row with a\n * null `revoked_at`. Pure D1 wiring; no key minting (that's the provisioner).\n */\nexport function createPresetWorkspaceKeyStore(db: D1Like): WorkspaceKeyStore {\n const W = PRESET_TABLES.workspaceKeys\n return {\n async getActive(workspaceId: string): Promise<WorkspaceKeyRecord | null> {\n const row = await db\n .prepare(\n `SELECT ${W.columns.id} AS id, ${W.columns.keyId} AS keyId, ${W.columns.keyEncrypted} AS keyEncrypted, ${W.columns.budgetUsd} AS budgetUsd, ${W.columns.expiresAt} AS expiresAt FROM ${W.name} WHERE ${W.columns.workspaceId} = ? AND ${W.columns.revokedAt} IS NULL ORDER BY ${W.columns.createdAt} DESC LIMIT 1`,\n )\n .bind(workspaceId)\n .first<{ id: string; keyId: string; keyEncrypted: string; budgetUsd: number; expiresAt: number | null }>()\n if (!row) return null\n return {\n id: row.id,\n keyId: row.keyId,\n keyEncrypted: row.keyEncrypted,\n budgetUsd: row.budgetUsd,\n expiresAt: row.expiresAt == null ? null : new Date(row.expiresAt),\n }\n },\n async listActive(workspaceId: string): Promise<Array<{ id: string; keyId: string }>> {\n const res = await db\n .prepare(`SELECT ${W.columns.id} AS id, ${W.columns.keyId} AS keyId FROM ${W.name} WHERE ${W.columns.workspaceId} = ? AND ${W.columns.revokedAt} IS NULL`)\n .bind(workspaceId)\n .all<{ id: string; keyId: string }>()\n return res.results\n },\n async insert(record): Promise<void> {\n await db\n .prepare(\n `INSERT INTO ${W.name} (${W.columns.id}, ${W.columns.workspaceId}, ${W.columns.keyId}, ${W.columns.keyEncrypted}, ${W.columns.budgetUsd}, ${W.columns.expiresAt}, ${W.columns.revokedAt}, ${W.columns.createdAt}) VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n )\n .bind(crypto.randomUUID(), record.workspaceId, record.keyId, record.keyEncrypted, record.budgetUsd, record.expiresAt.getTime(), Date.now())\n .run()\n },\n async markRevoked(id: string, now: Date): Promise<void> {\n await db\n .prepare(`UPDATE ${W.name} SET ${W.columns.revokedAt} = ? WHERE ${W.columns.id} = ?`)\n .bind(now.getTime(), id)\n .run()\n },\n }\n}\n\n/** Define preset billing options including database, provisioner, encryption key, budget, and optional settings */\nexport interface PresetBillingOptions {\n db: D1Like\n /** The key provisioner (`@tangle-network/tcloud`'s client satisfies it structurally). */\n provisioner: KeyProvisioner\n /** Field-crypto key (64-char hex) or resolver — encrypts the minted key at rest. */\n encryptionKey: string | (() => string)\n /** Default monthly USD allowance when a call doesn't specify one. */\n defaultBudgetUsd: number\n /** Injectable clock. */\n now?: () => Date\n /** tcloud product the key is scoped to. Default `'router'`. */\n product?: string\n}\n\n/**\n * Stand up the per-workspace budget-capped {@link WorkspaceKeyManager} on the\n * house stack: the preset `workspace_keys` D1 store + AES-GCM field crypto +\n * the consumer's tcloud provisioner. The mint/rotate/rollover/usage LOGIC lives\n * in `../billing`; this only binds it to the preset table + crypto.\n */\nexport function createPresetWorkspaceKeyManager(opts: PresetBillingOptions): WorkspaceKeyManager {\n return createWorkspaceKeyManager({\n provisioner: opts.provisioner,\n store: createPresetWorkspaceKeyStore(opts.db),\n crypto: createPresetFieldCrypto(opts.encryptionKey),\n defaultBudgetUsd: opts.defaultBudgetUsd,\n now: opts.now,\n product: opts.product,\n })\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,eAAsB,iCAKpB,SACA,OACqE;AACrE,MAAI;AACF,WAAO;AAAA,MACL,UAAU,MAAM,QAAQ,OAAO,KAAK;AAAA,MACpC,SAAS;AAAA,IACX;AAAA,EACF,SAAS,aAAa;AACpB,QAAI;AACF,YAAM,WAAW,MAAM,QAAQ,IAAI,MAAM,EAAE;AAC3C,YAAM,SAAS,MAAM,SAAS,OAAO;AACrC,aAAO,EAAE,UAAU,SAAS,OAAO,OAAO;AAAA,IAC5C,QAAQ;AACN,YAAM;AAAA,IACR;AAAA,EACF;AACF;;;ACkBA,SAAS,eAAe,SAA6C;AACnE,MAAI,CAAC,WAAW,OAAO,QAAQ,cAAc,YAAY,CAAC,QAAQ,UAAU,KAAK,GAAG;AAClF,UAAM,IAAI,MAAM,+DAA+D;AAAA,EACjF;AACA,MAAI,OAAO,QAAQ,WAAW,YAAY,CAAC,QAAQ,OAAO,KAAK,GAAG;AAChE,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACF;AAIA,IAAM,eAAqD;AAAA,EACzD,SAAS;AAAA,EACT,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,mBAAmB;AAAA,EACnB,sBAAsB;AACxB;AAEA,SAAS,kBAAkB,OAAiD;AAC1E,S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