@agent-native/dispatch 0.11.8 → 0.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/start-workspace-app-creation.js +1 -1
- package/dist/actions/start-workspace-app-creation.js.map +1 -1
- package/dist/components/create-app-popover.js +1 -1
- package/dist/components/create-app-popover.js.map +1 -1
- package/dist/server/lib/app-creation-store.js +1 -1
- package/dist/server/lib/app-creation-store.js.map +1 -1
- package/dist/server/plugins/integrations.js +1 -1
- package/dist/server/plugins/integrations.js.map +1 -1
- package/package.json +2 -2
- package/src/actions/start-workspace-app-creation.ts +1 -1
- package/src/components/create-app-popover.tsx +1 -1
- package/src/server/lib/app-creation-store.ts +1 -1
- package/src/server/plugins/integrations.ts +1 -1
|
@@ -3,7 +3,7 @@ import { getWorkspaceAppIdValidationError } from "@agent-native/core/shared";
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { startWorkspaceAppCreation } from "../server/lib/app-creation-store.js";
|
|
5
5
|
export default defineAction({
|
|
6
|
-
description: 'Start creating a new workspace app from Dispatch when the request truly needs its own app. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it creates a Builder branch when a Builder project is configured. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not clone, wrap, or nest those templates inside the new app unless the user explicitly asks for a customized copy.',
|
|
6
|
+
description: 'Start creating a new workspace app from Dispatch when the request truly needs its own app. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it creates a Builder branch only when a Builder branch project is configured. If the result mode is "coming-soon", the work still requires a code change but no Builder Cloud Agent can run here; tell the user to edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like, and do not send them to Builder org/beta settings. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not clone, wrap, or nest those templates inside the new app unless the user explicitly asks for a customized copy.',
|
|
7
7
|
schema: z.object({
|
|
8
8
|
prompt: z.string().min(1).describe("The user's app creation request"),
|
|
9
9
|
appId: z
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-workspace-app-creation.js","sourceRoot":"","sources":["../../src/actions/start-workspace-app-creation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAEhF,eAAe,YAAY,CAAC;IAC1B,WAAW,EACT,
|
|
1
|
+
{"version":3,"file":"start-workspace-app-creation.js","sourceRoot":"","sources":["../../src/actions/start-workspace-app-creation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAEhF,eAAe,YAAY,CAAC;IAC1B,WAAW,EACT,0qCAA0qC;IAC5qC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC;QACf,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iCAAiC,CAAC;QACrE,KAAK,EAAE,CAAC;aACL,MAAM,EAAE;aACR,GAAG,CAAC,EAAE,CAAC;aACP,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,gCAAgC,CAAC,KAAK,CAAC,EAAE;YAC3D,OAAO,EACL,yEAAyE;SAC5E,CAAC;aACD,QAAQ,EAAE;aACV,QAAQ,EAAE;aACV,QAAQ,CAAC,+BAA+B,CAAC;QAC5C,QAAQ,EAAE,CAAC;aACR,MAAM,EAAE;aACR,QAAQ,EAAE;aACV,QAAQ,EAAE;aACV,QAAQ,CAAC,wBAAwB,CAAC;QACrC,WAAW,EAAE,CAAC;aACX,MAAM,EAAE;aACR,GAAG,CAAC,GAAG,CAAC;aACR,QAAQ,EAAE;aACV,QAAQ,EAAE;aACV,QAAQ,CACP,6HAA6H,CAC9H;QACH,SAAS,EAAE,CAAC;aACT,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;aACjB,GAAG,CAAC,GAAG,CAAC;aACR,QAAQ,EAAE;aACV,QAAQ,CAAC,+CAA+C,CAAC;QAC5D,WAAW,EAAE,CAAC;aACX,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;aACjB,GAAG,CAAC,GAAG,CAAC;aACR,QAAQ,EAAE;aACV,QAAQ,CACP,wEAAwE,CACzE;KACJ,CAAC;IACF,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC;CACrD,CAAC,CAAC","sourcesContent":["import { defineAction } from \"@agent-native/core\";\nimport { getWorkspaceAppIdValidationError } from \"@agent-native/core/shared\";\nimport { z } from \"zod\";\nimport { startWorkspaceAppCreation } from \"../server/lib/app-creation-store.js\";\n\nexport default defineAction({\n description:\n 'Start creating a new workspace app from Dispatch when the request truly needs its own app. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it creates a Builder branch only when a Builder branch project is configured. If the result mode is \"coming-soon\", the work still requires a code change but no Builder Cloud Agent can run here; tell the user to edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like, and do not send them to Builder org/beta settings. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not clone, wrap, or nest those templates inside the new app unless the user explicitly asks for a customized copy.',\n schema: z.object({\n prompt: z.string().min(1).describe(\"The user's app creation request\"),\n appId: z\n .string()\n .max(64)\n .refine((appId) => !getWorkspaceAppIdValidationError(appId), {\n message:\n \"Use a non-reserved app id with lowercase letters, numbers, and hyphens.\",\n })\n .optional()\n .nullable()\n .describe(\"Desired workspace app id/path\"),\n template: z\n .string()\n .optional()\n .nullable()\n .describe(\"Template to start from\"),\n description: z\n .string()\n .max(500)\n .optional()\n .nullable()\n .describe(\n \"Concise AI-generated description of the app based on the user's prompt. Dispatch saves this while the app is being created.\",\n ),\n secretIds: z\n .array(z.string())\n .max(100)\n .optional()\n .describe(\"Dispatch vault secret IDs to grant to the app\"),\n resourceIds: z\n .array(z.string())\n .max(100)\n .optional()\n .describe(\n \"Dispatch workspace resource IDs or knowledge packs to grant to the app\",\n ),\n }),\n run: async (args) => startWorkspaceAppCreation(args),\n});\n"]}
|
|
@@ -226,7 +226,7 @@ export function CreateAppFlow({ onClose, className = "", }) {
|
|
|
226
226
|
}
|
|
227
227
|
else {
|
|
228
228
|
setStatusMessage(result?.message ||
|
|
229
|
-
"
|
|
229
|
+
"This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.");
|
|
230
230
|
}
|
|
231
231
|
}
|
|
232
232
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-app-popover.js","sourceRoot":"","sources":["../../src/components/create-app-popover.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AAC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,UAAU,EAAE,EAAE,EACd,SAAS,EAAC,4DAA4D,YAEtE,KAAC,aAAa,IAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,GAAI,GACjC,IACT,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useMemo, useState, type ReactNode } from \"react\";\nimport {\n PromptComposer,\n agentNativePath,\n appBasePath,\n isInBuilderFrame,\n sendToAgentChat,\n useDevMode,\n} from \"@agent-native/core/client\";\nimport { getWorkspaceAppIdValidationError } from \"@agent-native/core/shared\";\nimport {\n IconArrowLeft,\n IconArrowUpRight,\n IconBook,\n IconCheck,\n IconChevronDown,\n IconFileText,\n IconKey,\n IconLoader2,\n IconPlus,\n} from \"@tabler/icons-react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@/components/ui/popover\";\nimport { Button } from \"@/components/ui/button\";\n\ninterface VaultSecretOption {\n id: string;\n name: string;\n credentialKey: string;\n provider?: string | null;\n description?: string | null;\n}\n\ninterface WorkspaceResourceOption {\n id: string;\n kind: \"skill\" | \"instruction\" | \"agent\" | \"knowledge\" | \"mcp-server\";\n name: string;\n description?: string | null;\n path: string;\n scope: \"all\" | \"selected\";\n updatedAt?: number;\n}\n\ntype VaultAccessMode = \"all-apps\" | \"manual\";\n\ninterface CreateAppPopoverProps {\n /**\n * Custom trigger element. Defaults to a dashed-border tile that matches the\n * apps grid empty state.\n */\n trigger?: ReactNode;\n /**\n * Override the popover alignment. Defaults to \"center\" with a 10px offset.\n */\n align?: \"start\" | \"center\" | \"end\";\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 48);\n}\n\nfunction titleFromPrompt(prompt: string): string {\n const cleaned = prompt\n .replace(/\\b(build|create|make|an?|the|app|tool|dashboard)\\b/gi, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return slugify(cleaned || \"new-app\") || \"new-app\";\n}\n\nfunction buildAppCreationPrompt(input: {\n appId: string;\n prompt: string;\n selectedKeys: string[];\n selectedResources: WorkspaceResourceOption[];\n vaultAccessMode: VaultAccessMode;\n}): string {\n const keyList = input.selectedKeys.join(\", \");\n const grantRequest =\n input.vaultAccessMode === \"all-apps\"\n ? `Dispatch vault access: all saved vault keys are available to every workspace app by default. No per-app vault grants are needed.`\n : keyList\n ? `Requested Dispatch vault key grants for this app: ${keyList}`\n : `Requested Dispatch vault key grants for this app: none`;\n const resourceList = input.selectedResources.length\n ? input.selectedResources\n .map(\n (resource) =>\n `- ${resource.name} (${resource.kind}, ${resource.path})`,\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n `Create a new agent-native app in this workspace.`,\n `This is a new workspace app request, not a feature request for the current app.`,\n ``,\n `Suggested app name: ${input.appId} (you may adjust the slug if it conflicts)`,\n `User prompt: ${input.prompt.trim()}`,\n `Generate a concise one-sentence app description from the user prompt before coding; save it in apps/${input.appId}/package.json \"description\" so Dispatch and A2A can describe the app.`,\n `If the user mentions a product or company such as Granola, Loom, Superhuman, Linear, or Notion, treat it as product inspiration unless they explicitly ask to connect to that service. Do not invent or require third-party API keys like GRANOLA_API_KEY just because a product is named.`,\n grantRequest,\n `Requested Dispatch workspace resources for this app:\\n${resourceList}`,\n `Dispatch workspace resources with scope=all are inherited workspace context. Do not copy or sync them into the new app; every workspace app reads them at runtime and may override with app shared or personal resources.`,\n ``,\n `Pick a UI template that fits the user's prompt — analytics, assets, brain, calendar, chat, content, design, dispatch, forms, mail, slides, or clips when none of the others fit.`,\n `If you use the chat template, treat it as scaffolding only: the finished app must use the requested app's real name, home screen, navigation, package metadata, and manifest, and it must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.`,\n `Use the workspace app layout: create it under apps/${input.appId}, mount it at /${input.appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `Important routing rule: from outside the app, link to /${input.appId}; inside apps/${input.appId}, React Router routes are app-local. Use <Link to=\"/review\"> and navigate(\"/review\"), not \"/${input.appId}/review\"; APP_BASE_PATH supplies the mounted prefix, and hardcoding it causes doubled URLs like /${input.appId}/${input.appId}/review.`,\n `Prefer useActionQuery/useActionMutation for actions. If you must raw-fetch framework endpoints, wrap them with agentNativePath(\"/_agent-native/actions/<name>\") so mounted apps call the right URL.`,\n `Use relative workspace links like /${input.appId}. Do not hardcode localhost, 127.0.0.1, 8080, 8100, or any dev port; the active workspace gateway/browser origin owns the port.`,\n `Use the framework/template UI stack: shadcn/ui components and @tabler/icons-react. Do not add lucide-react or another icon library for standard UI.`,\n `Existing first-party apps are neighbors, not implementation details for this app. If the user's prompt mentions Mail, Calendar, Analytics, Brain, Assets, Dispatch, or other templates, treat them as existing hosted/connected apps that this app can link to or call through A2A/default connected agents. For example, Mail, Calendar, Analytics, Brain, and Assets already exist at https://mail.agent-native.com, https://calendar.agent-native.com, https://analytics.agent-native.com, https://brain.agent-native.com, and https://assets.agent-native.com.`,\n `Do not clone first-party templates, create wrapper apps, or scaffold child apps/routes for Mail, Calendar, Analytics, Brain, Assets, etc. inside apps/${input.appId} just so this app can access them. If the request is a cross-app dashboard or overview, build only the new dashboard/overview app and delegate to the existing apps for domain work.`,\n `Only create another first-party app copy when the user explicitly asks for a customized fork/copy of that app; otherwise keep using the hosted/shared app so improvements to the base template keep flowing to users.`,\n `Do not satisfy this by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app.`,\n input.vaultAccessMode === \"all-apps\"\n ? `Do not create per-app Dispatch vault grants unless the workspace switches vault access to manual or the user explicitly asks for manual grants.`\n : keyList\n ? `After the app exists, grant the selected Dispatch vault keys to appId \"${input.appId}\" and sync them once the app server is available. Treat these as requested grants, not active grants before creation succeeds.`\n : `Do not grant any Dispatch vault keys unless the user asks later.`,\n input.selectedResources.length\n ? `After the app exists, grant the selected Dispatch workspace resources to appId \"${input.appId}\". Do not sync All-app workspace resources; they are inherited.`\n : `Do not grant any selected-only Dispatch workspace resources unless the user asks later.`,\n ``,\n `App readiness requirements before handing off:`,\n `- Ensure apps/${input.appId}/package.json exists with displayName/name and a concise description; Dispatch discovers workspace apps from apps/<app-id>/package.json, not a separate app registry.`,\n `- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model.`,\n `- Ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() so /${input.appId} hydrates correctly.`,\n `- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment. Every sibling workspace app is available over A2A by default through call-agent, with names and descriptions from the workspace app registry.`,\n `When it is ready, start or update the workspace dev server and navigate the user to the absolute path /${input.appId} on the workspace origin. Do not prefix with /dispatch/, /apps/, /workspace/, or any other Dispatch tab — the new app is mounted at the workspace root, not under Dispatch. If you have a navigate tool available, pass /${input.appId} verbatim; if you only have a window.location-style escape hatch, set it to /${input.appId}.`,\n ].join(\"\\n\");\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n const data = await res.json().catch(() => null);\n if (!res.ok) {\n throw new Error(\n data?.error || data?.message || `Request failed ${res.status}`,\n );\n }\n return data;\n}\n\nfunction defaultDispatchBasePath(): string | null {\n const base = appBasePath();\n if (base === \"/dispatch\") return null;\n return null;\n}\n\nfunction actionUrl(basePath: string | null, action: string): string {\n const path = `/_agent-native/actions/${action}`;\n if (basePath === null) return agentNativePath(path);\n const normalized = basePath.replace(/\\/+$/, \"\");\n return `${normalized}${path}`;\n}\n\n/**\n * Inline two-step app-creation flow: prompt → optional access picker → submit.\n * Used both in the popover form and in the dedicated `/new-app` page so the\n * same UX shows up everywhere a teammate kicks off a new workspace app.\n */\nexport function CreateAppFlow({\n onClose,\n className = \"\",\n}: {\n onClose?: () => void;\n className?: string;\n}) {\n const [step, setStep] = useState<\"prompt\" | \"access\">(\"prompt\");\n const [prompt, setPrompt] = useState(\"\");\n const [selectedSecretIds, setSelectedSecretIds] = useState<string[]>([]);\n const [selectedResourceIds, setSelectedResourceIds] = useState<string[]>([]);\n const [secrets, setSecrets] = useState<VaultSecretOption[]>([]);\n const [resources, setResources] = useState<WorkspaceResourceOption[]>([]);\n const [vaultAccessMode, setVaultAccessMode] =\n useState<VaultAccessMode>(\"all-apps\");\n const [secretsError, setSecretsError] = useState<string | null>(null);\n const [resourcesError, setResourcesError] = useState<string | null>(null);\n const [statusMessage, setStatusMessage] = useState<string | null>(null);\n const [branchUrl, setBranchUrl] = useState<string | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n const { isDevMode } = useDevMode();\n\n const basePath = useMemo(() => defaultDispatchBasePath(), []);\n\n // Fetch access options eagerly so step 2 has them ready immediately.\n useEffect(() => {\n let cancelled = false;\n fetchJson(actionUrl(basePath, \"list-vault-secret-options\"))\n .then((data) => {\n if (cancelled) return;\n setSecrets(Array.isArray(data) ? data : []);\n setSecretsError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setSecrets([]);\n setSecretsError(err?.message || \"Could not load Dispatch keys\");\n });\n fetchJson(actionUrl(basePath, \"get-vault-access-settings\"))\n .then((data) => {\n if (cancelled) return;\n setVaultAccessMode(data?.mode === \"manual\" ? \"manual\" : \"all-apps\");\n })\n .catch(() => {\n if (cancelled) return;\n setVaultAccessMode(\"manual\");\n });\n fetchJson(actionUrl(basePath, \"list-workspace-resource-options\"))\n .then((data) => {\n if (cancelled) return;\n setResources(Array.isArray(data) ? data : []);\n setResourcesError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setResources([]);\n setResourcesError(err?.message || \"Could not load Dispatch resources\");\n });\n return () => {\n cancelled = true;\n };\n }, [basePath]);\n\n const selectedSecrets = useMemo(\n () => secrets.filter((s) => selectedSecretIds.includes(s.id)),\n [secrets, selectedSecretIds],\n );\n const selectedResources = useMemo(\n () => resources.filter((r) => selectedResourceIds.includes(r.id)),\n [resources, selectedResourceIds],\n );\n const selectedSecretLabel =\n vaultAccessMode === \"all-apps\"\n ? \"all keys\"\n : selectedSecretIds.length === 0\n ? \"no keys\"\n : `${selectedSecretIds.length} key${selectedSecretIds.length === 1 ? \"\" : \"s\"}`;\n const selectedResourceLabel =\n selectedResourceIds.length === 0\n ? \"no resources\"\n : `${selectedResourceIds.length} resource${selectedResourceIds.length === 1 ? \"\" : \"s\"}`;\n const selectedAccessLabel = [selectedSecretLabel, selectedResourceLabel].join(\n \" · \",\n );\n\n function toggleSecret(id: string) {\n setSelectedSecretIds((cur) =>\n cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id],\n );\n }\n\n function toggleResource(id: string) {\n setSelectedResourceIds((cur) =>\n cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id],\n );\n }\n\n async function submit(rawPrompt: string) {\n const trimmed = rawPrompt.trim();\n if (!trimmed || isSubmitting) return;\n const appId = titleFromPrompt(trimmed);\n const validationError = getWorkspaceAppIdValidationError(appId);\n if (validationError) {\n setStatusMessage(validationError);\n return;\n }\n\n const message = buildAppCreationPrompt({\n appId,\n prompt: trimmed,\n selectedKeys:\n vaultAccessMode === \"manual\"\n ? selectedSecrets.map((s) => s.credentialKey)\n : [],\n selectedResources,\n vaultAccessMode,\n });\n setIsSubmitting(true);\n setStatusMessage(null);\n setBranchUrl(null);\n\n try {\n if (isInBuilderFrame()) {\n sendToAgentChat({ message, submit: true, type: \"code\" });\n setStatusMessage(\"Sent to Builder chat.\");\n onClose?.();\n } else if (isDevMode) {\n sendToAgentChat({ message, submit: true, type: \"code\", newTab: true });\n setStatusMessage(\"Sent to the local agent.\");\n onClose?.();\n } else {\n const result = await fetchJson(\n actionUrl(basePath, \"start-workspace-app-creation\"),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n prompt: trimmed,\n appId,\n secretIds:\n vaultAccessMode === \"manual\" && selectedSecretIds.length > 0\n ? selectedSecretIds\n : [],\n resourceIds:\n selectedResourceIds.length > 0 ? selectedResourceIds : [],\n }),\n },\n );\n if (result?.mode === \"builder\") {\n setBranchUrl(result?.url || null);\n setStatusMessage(\"Builder branch created.\");\n } else {\n setStatusMessage(\n result?.message ||\n \"Builder app creation is coming soon. Open this workspace in Builder to create an app from this prompt.\",\n );\n }\n }\n } catch (err: any) {\n setStatusMessage(err?.message || \"Could not start the new app flow.\");\n } finally {\n setIsSubmitting(false);\n }\n }\n\n const submitWithSelectedAccess = () => submit(prompt);\n\n return (\n <div className={`flex flex-col gap-3 ${className}`}>\n {step === \"prompt\" ? (\n <>\n <div className=\"flex items-center justify-between gap-2 px-1\">\n <p className=\"text-sm font-semibold text-foreground\">Create app</p>\n <button\n type=\"button\"\n onClick={() => setStep(\"access\")}\n className=\"inline-flex cursor-pointer items-center gap-1 rounded-md border border-border bg-background/40 px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground hover:bg-accent/50\"\n >\n <IconKey size={11} />\n {selectedAccessLabel}\n </button>\n </div>\n <PromptComposer\n autoFocus\n disabled={isSubmitting}\n placeholder=\"Describe the app your teammate should be able to use...\"\n draftScope=\"dispatch:create-app\"\n preserveDraftOnSubmit\n onSubmit={(text) => {\n setPrompt(text);\n submit(text);\n }}\n />\n </>\n ) : (\n <>\n <div className=\"flex items-center justify-between gap-2 px-1\">\n <button\n type=\"button\"\n onClick={() => setStep(\"prompt\")}\n className=\"inline-flex cursor-pointer items-center gap-1 text-xs text-muted-foreground hover:text-foreground\"\n >\n <IconArrowLeft size={12} />\n Back\n </button>\n <span className=\"text-[11px] text-muted-foreground/70\">\n {selectedAccessLabel}\n </span>\n </div>\n <div className=\"max-h-[180px] space-y-2 overflow-y-auto rounded-md border border-border bg-card p-2\">\n <div className=\"flex items-center gap-1.5 px-1 pb-1 text-[11px] font-medium text-muted-foreground\">\n <IconKey size={12} />\n Dispatch keys\n </div>\n {vaultAccessMode === \"all-apps\" ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n Every saved Dispatch vault key is available to new apps.\n </p>\n ) : secretsError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {secretsError}\n </p>\n ) : secrets.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch vault keys found yet.\n </p>\n ) : (\n secrets.map((secret) => {\n const selected = selectedSecretIds.includes(secret.id);\n return (\n <div\n key={secret.id}\n className={`group rounded-md border text-sm ${\n selected\n ? \"border-primary/45 bg-primary/5\"\n : \"border-border hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleSecret(secret.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">\n {secret.credentialKey}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {selected\n ? \"Will be requested for this app\"\n : \"Click to request\"}\n </span>\n </span>\n </button>\n {(secret.provider || secret.name) && (\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Provider: {secret.provider || \"Not specified\"}\n </div>\n <div className=\"truncate\">Name: {secret.name}</div>\n </div>\n </details>\n )}\n </div>\n );\n })\n )}\n </div>\n <div className=\"max-h-[180px] space-y-2 overflow-y-auto rounded-md border border-border bg-card p-2\">\n <div className=\"flex items-center gap-1.5 px-1 pb-1 text-[11px] font-medium text-muted-foreground\">\n <IconBook size={12} />\n Resource packs\n </div>\n {resourcesError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {resourcesError}\n </p>\n ) : resources.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch resource packs found yet.\n </p>\n ) : (\n resources.map((resource) => {\n const selected = selectedResourceIds.includes(resource.id);\n return (\n <div\n key={resource.id}\n className={`group rounded-md border text-sm ${\n selected\n ? \"border-primary/45 bg-primary/5\"\n : \"border-border hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleResource(resource.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n <IconFileText className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground/70\" />\n <span className=\"block truncate font-medium\">\n {resource.name}\n </span>\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {resource.kind} · {resource.path}\n </span>\n </span>\n </button>\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Scope:{\" \"}\n {resource.scope === \"all\"\n ? \"All apps\"\n : \"Selected apps\"}\n </div>\n {resource.description ? (\n <div className=\"line-clamp-2\">\n {resource.description}\n </div>\n ) : null}\n </div>\n </details>\n </div>\n );\n })\n )}\n </div>\n <div className=\"flex items-center justify-end gap-2\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={submitWithSelectedAccess}\n disabled={!prompt.trim() || isSubmitting}\n >\n {isSubmitting ? (\n <IconLoader2 className=\"h-3.5 w-3.5 animate-spin\" />\n ) : (\n <IconPlus className=\"h-3.5 w-3.5\" />\n )}\n Create app\n </Button>\n </div>\n {!prompt.trim() ? (\n <p className=\"px-1 text-[11px] text-muted-foreground/70\">\n Add a prompt on the previous step before creating the app.\n </p>\n ) : null}\n </>\n )}\n\n {statusMessage ? (\n <div className=\"rounded-md border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground\">\n {statusMessage}\n {branchUrl ? (\n <a\n href={branchUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"ml-2 inline-flex items-center gap-1 font-medium text-foreground underline\"\n >\n Open branch <IconArrowUpRight className=\"h-3 w-3\" />\n </a>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n\nexport function CreateAppPopover({\n trigger,\n align = \"center\",\n}: CreateAppPopoverProps) {\n const [open, setOpen] = useState(false);\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n {trigger ?? (\n <button\n type=\"button\"\n className=\"flex min-h-32 cursor-pointer items-center justify-center rounded-lg border border-dashed bg-card p-4 text-sm font-medium text-muted-foreground transition hover:border-foreground/30 hover:text-foreground\"\n >\n <span className=\"inline-flex items-center gap-2\">\n <IconPlus size={16} />\n Create app\n </span>\n </button>\n )}\n </PopoverTrigger>\n <PopoverContent\n align={align}\n sideOffset={10}\n className=\"w-[calc(100vw-2rem)] rounded-xl p-3 shadow-xl sm:w-[460px]\"\n >\n <CreateAppFlow onClose={() => setOpen(false)} />\n </PopoverContent>\n </Popover>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-app-popover.js","sourceRoot":"","sources":["../../src/components/create-app-popover.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AACrE,OAAO,EACL,cAAc,EACd,eAAe,EACf,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,UAAU,GACX,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,QAAQ,EACR,SAAS,EACT,eAAe,EACf,YAAY,EACZ,OAAO,EACP,WAAW,EACX,QAAQ,GACT,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,OAAO,EACP,cAAc,EACd,cAAc,GACf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAkChD,SAAS,OAAO,CAAC,KAAa;IAC5B,OAAO,KAAK;SACT,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,SAAS,eAAe,CAAC,MAAc;IACrC,MAAM,OAAO,GAAG,MAAM;SACnB,OAAO,CAAC,sDAAsD,EAAE,GAAG,CAAC;SACpE,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,IAAI,EAAE,CAAC;IACV,OAAO,OAAO,CAAC,OAAO,IAAI,SAAS,CAAC,IAAI,SAAS,CAAC;AACpD,CAAC;AAED,SAAS,sBAAsB,CAAC,KAM/B;IACC,MAAM,OAAO,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9C,MAAM,YAAY,GAChB,KAAK,CAAC,eAAe,KAAK,UAAU;QAClC,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,SAAS,EAAC,gCAAgC,aAC9C,KAAC,QAAQ,IAAC,IAAI,EAAE,EAAE,GAAI,kBAEjB,GACA,CACV,GACc,EACjB,KAAC,cAAc,IACb,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,EAAE,EACd,SAAS,EAAC,4DAA4D,YAEtE,KAAC,aAAa,IAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,GAAI,GACjC,IACT,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useMemo, useState, type ReactNode } from \"react\";\nimport {\n PromptComposer,\n agentNativePath,\n appBasePath,\n isInBuilderFrame,\n sendToAgentChat,\n useDevMode,\n} from \"@agent-native/core/client\";\nimport { getWorkspaceAppIdValidationError } from \"@agent-native/core/shared\";\nimport {\n IconArrowLeft,\n IconArrowUpRight,\n IconBook,\n IconCheck,\n IconChevronDown,\n IconFileText,\n IconKey,\n IconLoader2,\n IconPlus,\n} from \"@tabler/icons-react\";\nimport {\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from \"@/components/ui/popover\";\nimport { Button } from \"@/components/ui/button\";\n\ninterface VaultSecretOption {\n id: string;\n name: string;\n credentialKey: string;\n provider?: string | null;\n description?: string | null;\n}\n\ninterface WorkspaceResourceOption {\n id: string;\n kind: \"skill\" | \"instruction\" | \"agent\" | \"knowledge\" | \"mcp-server\";\n name: string;\n description?: string | null;\n path: string;\n scope: \"all\" | \"selected\";\n updatedAt?: number;\n}\n\ntype VaultAccessMode = \"all-apps\" | \"manual\";\n\ninterface CreateAppPopoverProps {\n /**\n * Custom trigger element. Defaults to a dashed-border tile that matches the\n * apps grid empty state.\n */\n trigger?: ReactNode;\n /**\n * Override the popover alignment. Defaults to \"center\" with a 10px offset.\n */\n align?: \"start\" | \"center\" | \"end\";\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 48);\n}\n\nfunction titleFromPrompt(prompt: string): string {\n const cleaned = prompt\n .replace(/\\b(build|create|make|an?|the|app|tool|dashboard)\\b/gi, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return slugify(cleaned || \"new-app\") || \"new-app\";\n}\n\nfunction buildAppCreationPrompt(input: {\n appId: string;\n prompt: string;\n selectedKeys: string[];\n selectedResources: WorkspaceResourceOption[];\n vaultAccessMode: VaultAccessMode;\n}): string {\n const keyList = input.selectedKeys.join(\", \");\n const grantRequest =\n input.vaultAccessMode === \"all-apps\"\n ? `Dispatch vault access: all saved vault keys are available to every workspace app by default. No per-app vault grants are needed.`\n : keyList\n ? `Requested Dispatch vault key grants for this app: ${keyList}`\n : `Requested Dispatch vault key grants for this app: none`;\n const resourceList = input.selectedResources.length\n ? input.selectedResources\n .map(\n (resource) =>\n `- ${resource.name} (${resource.kind}, ${resource.path})`,\n )\n .join(\"\\n\")\n : \"none\";\n\n return [\n `Create a new agent-native app in this workspace.`,\n `This is a new workspace app request, not a feature request for the current app.`,\n ``,\n `Suggested app name: ${input.appId} (you may adjust the slug if it conflicts)`,\n `User prompt: ${input.prompt.trim()}`,\n `Generate a concise one-sentence app description from the user prompt before coding; save it in apps/${input.appId}/package.json \"description\" so Dispatch and A2A can describe the app.`,\n `If the user mentions a product or company such as Granola, Loom, Superhuman, Linear, or Notion, treat it as product inspiration unless they explicitly ask to connect to that service. Do not invent or require third-party API keys like GRANOLA_API_KEY just because a product is named.`,\n grantRequest,\n `Requested Dispatch workspace resources for this app:\\n${resourceList}`,\n `Dispatch workspace resources with scope=all are inherited workspace context. Do not copy or sync them into the new app; every workspace app reads them at runtime and may override with app shared or personal resources.`,\n ``,\n `Pick a UI template that fits the user's prompt — analytics, assets, brain, calendar, chat, content, design, dispatch, forms, mail, slides, or clips when none of the others fit.`,\n `If you use the chat template, treat it as scaffolding only: the finished app must use the requested app's real name, home screen, navigation, package metadata, and manifest, and it must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.`,\n `Use the workspace app layout: create it under apps/${input.appId}, mount it at /${input.appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `Important routing rule: from outside the app, link to /${input.appId}; inside apps/${input.appId}, React Router routes are app-local. Use <Link to=\"/review\"> and navigate(\"/review\"), not \"/${input.appId}/review\"; APP_BASE_PATH supplies the mounted prefix, and hardcoding it causes doubled URLs like /${input.appId}/${input.appId}/review.`,\n `Prefer useActionQuery/useActionMutation for actions. If you must raw-fetch framework endpoints, wrap them with agentNativePath(\"/_agent-native/actions/<name>\") so mounted apps call the right URL.`,\n `Use relative workspace links like /${input.appId}. Do not hardcode localhost, 127.0.0.1, 8080, 8100, or any dev port; the active workspace gateway/browser origin owns the port.`,\n `Use the framework/template UI stack: shadcn/ui components and @tabler/icons-react. Do not add lucide-react or another icon library for standard UI.`,\n `Existing first-party apps are neighbors, not implementation details for this app. If the user's prompt mentions Mail, Calendar, Analytics, Brain, Assets, Dispatch, or other templates, treat them as existing hosted/connected apps that this app can link to or call through A2A/default connected agents. For example, Mail, Calendar, Analytics, Brain, and Assets already exist at https://mail.agent-native.com, https://calendar.agent-native.com, https://analytics.agent-native.com, https://brain.agent-native.com, and https://assets.agent-native.com.`,\n `Do not clone first-party templates, create wrapper apps, or scaffold child apps/routes for Mail, Calendar, Analytics, Brain, Assets, etc. inside apps/${input.appId} just so this app can access them. If the request is a cross-app dashboard or overview, build only the new dashboard/overview app and delegate to the existing apps for domain work.`,\n `Only create another first-party app copy when the user explicitly asks for a customized fork/copy of that app; otherwise keep using the hosted/shared app so improvements to the base template keep flowing to users.`,\n `Do not satisfy this by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app.`,\n input.vaultAccessMode === \"all-apps\"\n ? `Do not create per-app Dispatch vault grants unless the workspace switches vault access to manual or the user explicitly asks for manual grants.`\n : keyList\n ? `After the app exists, grant the selected Dispatch vault keys to appId \"${input.appId}\" and sync them once the app server is available. Treat these as requested grants, not active grants before creation succeeds.`\n : `Do not grant any Dispatch vault keys unless the user asks later.`,\n input.selectedResources.length\n ? `After the app exists, grant the selected Dispatch workspace resources to appId \"${input.appId}\". Do not sync All-app workspace resources; they are inherited.`\n : `Do not grant any selected-only Dispatch workspace resources unless the user asks later.`,\n ``,\n `App readiness requirements before handing off:`,\n `- Ensure apps/${input.appId}/package.json exists with displayName/name and a concise description; Dispatch discovers workspace apps from apps/<app-id>/package.json, not a separate app registry.`,\n `- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model.`,\n `- Ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() so /${input.appId} hydrates correctly.`,\n `- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment. Every sibling workspace app is available over A2A by default through call-agent, with names and descriptions from the workspace app registry.`,\n `When it is ready, start or update the workspace dev server and navigate the user to the absolute path /${input.appId} on the workspace origin. Do not prefix with /dispatch/, /apps/, /workspace/, or any other Dispatch tab — the new app is mounted at the workspace root, not under Dispatch. If you have a navigate tool available, pass /${input.appId} verbatim; if you only have a window.location-style escape hatch, set it to /${input.appId}.`,\n ].join(\"\\n\");\n}\n\nasync function fetchJson(url: string, init?: RequestInit): Promise<any> {\n const res = await fetch(url, init);\n const data = await res.json().catch(() => null);\n if (!res.ok) {\n throw new Error(\n data?.error || data?.message || `Request failed ${res.status}`,\n );\n }\n return data;\n}\n\nfunction defaultDispatchBasePath(): string | null {\n const base = appBasePath();\n if (base === \"/dispatch\") return null;\n return null;\n}\n\nfunction actionUrl(basePath: string | null, action: string): string {\n const path = `/_agent-native/actions/${action}`;\n if (basePath === null) return agentNativePath(path);\n const normalized = basePath.replace(/\\/+$/, \"\");\n return `${normalized}${path}`;\n}\n\n/**\n * Inline two-step app-creation flow: prompt → optional access picker → submit.\n * Used both in the popover form and in the dedicated `/new-app` page so the\n * same UX shows up everywhere a teammate kicks off a new workspace app.\n */\nexport function CreateAppFlow({\n onClose,\n className = \"\",\n}: {\n onClose?: () => void;\n className?: string;\n}) {\n const [step, setStep] = useState<\"prompt\" | \"access\">(\"prompt\");\n const [prompt, setPrompt] = useState(\"\");\n const [selectedSecretIds, setSelectedSecretIds] = useState<string[]>([]);\n const [selectedResourceIds, setSelectedResourceIds] = useState<string[]>([]);\n const [secrets, setSecrets] = useState<VaultSecretOption[]>([]);\n const [resources, setResources] = useState<WorkspaceResourceOption[]>([]);\n const [vaultAccessMode, setVaultAccessMode] =\n useState<VaultAccessMode>(\"all-apps\");\n const [secretsError, setSecretsError] = useState<string | null>(null);\n const [resourcesError, setResourcesError] = useState<string | null>(null);\n const [statusMessage, setStatusMessage] = useState<string | null>(null);\n const [branchUrl, setBranchUrl] = useState<string | null>(null);\n const [isSubmitting, setIsSubmitting] = useState(false);\n const { isDevMode } = useDevMode();\n\n const basePath = useMemo(() => defaultDispatchBasePath(), []);\n\n // Fetch access options eagerly so step 2 has them ready immediately.\n useEffect(() => {\n let cancelled = false;\n fetchJson(actionUrl(basePath, \"list-vault-secret-options\"))\n .then((data) => {\n if (cancelled) return;\n setSecrets(Array.isArray(data) ? data : []);\n setSecretsError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setSecrets([]);\n setSecretsError(err?.message || \"Could not load Dispatch keys\");\n });\n fetchJson(actionUrl(basePath, \"get-vault-access-settings\"))\n .then((data) => {\n if (cancelled) return;\n setVaultAccessMode(data?.mode === \"manual\" ? \"manual\" : \"all-apps\");\n })\n .catch(() => {\n if (cancelled) return;\n setVaultAccessMode(\"manual\");\n });\n fetchJson(actionUrl(basePath, \"list-workspace-resource-options\"))\n .then((data) => {\n if (cancelled) return;\n setResources(Array.isArray(data) ? data : []);\n setResourcesError(null);\n })\n .catch((err) => {\n if (cancelled) return;\n setResources([]);\n setResourcesError(err?.message || \"Could not load Dispatch resources\");\n });\n return () => {\n cancelled = true;\n };\n }, [basePath]);\n\n const selectedSecrets = useMemo(\n () => secrets.filter((s) => selectedSecretIds.includes(s.id)),\n [secrets, selectedSecretIds],\n );\n const selectedResources = useMemo(\n () => resources.filter((r) => selectedResourceIds.includes(r.id)),\n [resources, selectedResourceIds],\n );\n const selectedSecretLabel =\n vaultAccessMode === \"all-apps\"\n ? \"all keys\"\n : selectedSecretIds.length === 0\n ? \"no keys\"\n : `${selectedSecretIds.length} key${selectedSecretIds.length === 1 ? \"\" : \"s\"}`;\n const selectedResourceLabel =\n selectedResourceIds.length === 0\n ? \"no resources\"\n : `${selectedResourceIds.length} resource${selectedResourceIds.length === 1 ? \"\" : \"s\"}`;\n const selectedAccessLabel = [selectedSecretLabel, selectedResourceLabel].join(\n \" · \",\n );\n\n function toggleSecret(id: string) {\n setSelectedSecretIds((cur) =>\n cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id],\n );\n }\n\n function toggleResource(id: string) {\n setSelectedResourceIds((cur) =>\n cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id],\n );\n }\n\n async function submit(rawPrompt: string) {\n const trimmed = rawPrompt.trim();\n if (!trimmed || isSubmitting) return;\n const appId = titleFromPrompt(trimmed);\n const validationError = getWorkspaceAppIdValidationError(appId);\n if (validationError) {\n setStatusMessage(validationError);\n return;\n }\n\n const message = buildAppCreationPrompt({\n appId,\n prompt: trimmed,\n selectedKeys:\n vaultAccessMode === \"manual\"\n ? selectedSecrets.map((s) => s.credentialKey)\n : [],\n selectedResources,\n vaultAccessMode,\n });\n setIsSubmitting(true);\n setStatusMessage(null);\n setBranchUrl(null);\n\n try {\n if (isInBuilderFrame()) {\n sendToAgentChat({ message, submit: true, type: \"code\" });\n setStatusMessage(\"Sent to Builder chat.\");\n onClose?.();\n } else if (isDevMode) {\n sendToAgentChat({ message, submit: true, type: \"code\", newTab: true });\n setStatusMessage(\"Sent to the local agent.\");\n onClose?.();\n } else {\n const result = await fetchJson(\n actionUrl(basePath, \"start-workspace-app-creation\"),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n prompt: trimmed,\n appId,\n secretIds:\n vaultAccessMode === \"manual\" && selectedSecretIds.length > 0\n ? selectedSecretIds\n : [],\n resourceIds:\n selectedResourceIds.length > 0 ? selectedResourceIds : [],\n }),\n },\n );\n if (result?.mode === \"builder\") {\n setBranchUrl(result?.url || null);\n setStatusMessage(\"Builder branch created.\");\n } else {\n setStatusMessage(\n result?.message ||\n \"This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.\",\n );\n }\n }\n } catch (err: any) {\n setStatusMessage(err?.message || \"Could not start the new app flow.\");\n } finally {\n setIsSubmitting(false);\n }\n }\n\n const submitWithSelectedAccess = () => submit(prompt);\n\n return (\n <div className={`flex flex-col gap-3 ${className}`}>\n {step === \"prompt\" ? (\n <>\n <div className=\"flex items-center justify-between gap-2 px-1\">\n <p className=\"text-sm font-semibold text-foreground\">Create app</p>\n <button\n type=\"button\"\n onClick={() => setStep(\"access\")}\n className=\"inline-flex cursor-pointer items-center gap-1 rounded-md border border-border bg-background/40 px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground hover:bg-accent/50\"\n >\n <IconKey size={11} />\n {selectedAccessLabel}\n </button>\n </div>\n <PromptComposer\n autoFocus\n disabled={isSubmitting}\n placeholder=\"Describe the app your teammate should be able to use...\"\n draftScope=\"dispatch:create-app\"\n preserveDraftOnSubmit\n onSubmit={(text) => {\n setPrompt(text);\n submit(text);\n }}\n />\n </>\n ) : (\n <>\n <div className=\"flex items-center justify-between gap-2 px-1\">\n <button\n type=\"button\"\n onClick={() => setStep(\"prompt\")}\n className=\"inline-flex cursor-pointer items-center gap-1 text-xs text-muted-foreground hover:text-foreground\"\n >\n <IconArrowLeft size={12} />\n Back\n </button>\n <span className=\"text-[11px] text-muted-foreground/70\">\n {selectedAccessLabel}\n </span>\n </div>\n <div className=\"max-h-[180px] space-y-2 overflow-y-auto rounded-md border border-border bg-card p-2\">\n <div className=\"flex items-center gap-1.5 px-1 pb-1 text-[11px] font-medium text-muted-foreground\">\n <IconKey size={12} />\n Dispatch keys\n </div>\n {vaultAccessMode === \"all-apps\" ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n Every saved Dispatch vault key is available to new apps.\n </p>\n ) : secretsError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {secretsError}\n </p>\n ) : secrets.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch vault keys found yet.\n </p>\n ) : (\n secrets.map((secret) => {\n const selected = selectedSecretIds.includes(secret.id);\n return (\n <div\n key={secret.id}\n className={`group rounded-md border text-sm ${\n selected\n ? \"border-primary/45 bg-primary/5\"\n : \"border-border hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleSecret(secret.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium\">\n {secret.credentialKey}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {selected\n ? \"Will be requested for this app\"\n : \"Click to request\"}\n </span>\n </span>\n </button>\n {(secret.provider || secret.name) && (\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Provider: {secret.provider || \"Not specified\"}\n </div>\n <div className=\"truncate\">Name: {secret.name}</div>\n </div>\n </details>\n )}\n </div>\n );\n })\n )}\n </div>\n <div className=\"max-h-[180px] space-y-2 overflow-y-auto rounded-md border border-border bg-card p-2\">\n <div className=\"flex items-center gap-1.5 px-1 pb-1 text-[11px] font-medium text-muted-foreground\">\n <IconBook size={12} />\n Resource packs\n </div>\n {resourcesError ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n {resourcesError}\n </p>\n ) : resources.length === 0 ? (\n <p className=\"rounded-md border border-dashed border-border px-3 py-3 text-xs text-muted-foreground\">\n No Dispatch resource packs found yet.\n </p>\n ) : (\n resources.map((resource) => {\n const selected = selectedResourceIds.includes(resource.id);\n return (\n <div\n key={resource.id}\n className={`group rounded-md border text-sm ${\n selected\n ? \"border-primary/45 bg-primary/5\"\n : \"border-border hover:border-muted-foreground/40 hover:bg-accent/35\"\n }`}\n >\n <button\n type=\"button\"\n aria-pressed={selected}\n onClick={() => toggleResource(resource.id)}\n className=\"flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2 text-left\"\n >\n <span\n className={`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border ${\n selected\n ? \"border-primary/60 bg-primary/10 text-primary\"\n : \"border-muted-foreground/35 text-transparent\"\n }`}\n >\n {selected ? <IconCheck className=\"h-3 w-3\" /> : null}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n <IconFileText className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground/70\" />\n <span className=\"block truncate font-medium\">\n {resource.name}\n </span>\n </span>\n <span className=\"block truncate text-xs text-muted-foreground/70\">\n {resource.kind} · {resource.path}\n </span>\n </span>\n </button>\n <details className=\"group/details border-t border-border/60 px-3 py-1.5 text-xs text-muted-foreground/75\">\n <summary className=\"flex cursor-pointer list-none items-center gap-1.5 text-[11px] hover:text-muted-foreground [&::-webkit-details-marker]:hidden\">\n <IconChevronDown className=\"h-3 w-3 transition-transform group-open/details:rotate-180\" />\n Details\n </summary>\n <div className=\"mt-1.5 space-y-1 pb-0.5 pl-4\">\n <div className=\"truncate\">\n Scope:{\" \"}\n {resource.scope === \"all\"\n ? \"All apps\"\n : \"Selected apps\"}\n </div>\n {resource.description ? (\n <div className=\"line-clamp-2\">\n {resource.description}\n </div>\n ) : null}\n </div>\n </details>\n </div>\n );\n })\n )}\n </div>\n <div className=\"flex items-center justify-end gap-2\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={submitWithSelectedAccess}\n disabled={!prompt.trim() || isSubmitting}\n >\n {isSubmitting ? (\n <IconLoader2 className=\"h-3.5 w-3.5 animate-spin\" />\n ) : (\n <IconPlus className=\"h-3.5 w-3.5\" />\n )}\n Create app\n </Button>\n </div>\n {!prompt.trim() ? (\n <p className=\"px-1 text-[11px] text-muted-foreground/70\">\n Add a prompt on the previous step before creating the app.\n </p>\n ) : null}\n </>\n )}\n\n {statusMessage ? (\n <div className=\"rounded-md border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground\">\n {statusMessage}\n {branchUrl ? (\n <a\n href={branchUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"ml-2 inline-flex items-center gap-1 font-medium text-foreground underline\"\n >\n Open branch <IconArrowUpRight className=\"h-3 w-3\" />\n </a>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n\nexport function CreateAppPopover({\n trigger,\n align = \"center\",\n}: CreateAppPopoverProps) {\n const [open, setOpen] = useState(false);\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n {trigger ?? (\n <button\n type=\"button\"\n className=\"flex min-h-32 cursor-pointer items-center justify-center rounded-lg border border-dashed bg-card p-4 text-sm font-medium text-muted-foreground transition hover:border-foreground/30 hover:text-foreground\"\n >\n <span className=\"inline-flex items-center gap-2\">\n <IconPlus size={16} />\n Create app\n </span>\n </button>\n )}\n </PopoverTrigger>\n <PopoverContent\n align={align}\n sideOffset={10}\n className=\"w-[calc(100vw-2rem)] rounded-xl p-3 shadow-xl sm:w-[460px]\"\n >\n <CreateAppFlow onClose={() => setOpen(false)} />\n </PopoverContent>\n </Popover>\n );\n}\n"]}
|
|
@@ -1447,7 +1447,7 @@ export async function startWorkspaceAppCreation(input) {
|
|
|
1447
1447
|
return {
|
|
1448
1448
|
mode: "coming-soon",
|
|
1449
1449
|
appId: built.appId,
|
|
1450
|
-
message: "
|
|
1450
|
+
message: "This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.",
|
|
1451
1451
|
};
|
|
1452
1452
|
}
|
|
1453
1453
|
let result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-creation-store.js","sourceRoot":"","sources":["../../../src/server/lib/app-creation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,yBAAyB,EACzB,eAAe,GAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACX,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EACL,4BAA4B,EAC5B,4BAA4B,GAE7B,MAAM,gCA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GAAG;KACvB,CAAC,CAAC;IAEH,MAAM,wBAAwB,CAAC;QAC7B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,YAAY;KACb,CAAC,CAAC;IACH,MAAM,+BAA+B,CAAC;QACpC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,WAAW,EAAE,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;KAC9D,CAAC,CAAC;IAEH,OAAO;QACL,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,IAAI,KAAK,CAAC,KAAK,EAAE;QACvB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;QACpC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,YAAY,EAAE,eAAe,CAAC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,OAAO,EACL,iCAAiC,KAAK,CAAC,KAAK,sDAAsD;YAClG,0HAA0H;KAC7H,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getSetting, putSetting } from \"@agent-native/core/settings\";\nimport { assertValidWorkspaceAppId } from \"@agent-native/core/shared\";\nimport {\n getBuilderBranchProjectId,\n getRequestContext,\n isIntegrationCallerRequest,\n resolveBuilderBranchProjectId,\n resolveBuilderCredentials,\n runBuilderAgent,\n} from \"@agent-native/core/server\";\nimport { getDbExec } from \"@agent-native/core/db\";\nimport {\n currentOrgId,\n currentOwnerEmail,\n recordAudit,\n resolveLinkedOwner,\n} from \"./dispatch-store.js\";\nimport { identityKeyForIncoming } from \"./dispatch-integrations.js\";\nimport { createRequest, listSecrets } from \"./vault-store.js\";\nimport {\n grantWorkspaceResourcesToApp,\n listWorkspaceResourceOptions,\n type WorkspaceResourceOption,\n} from \"./workspace-resources-store.js\";\n\nconst SETTINGS_KEY = \"dispatch-app-creation-settings\";\nconst WORKSPACE_APP_METADATA_SETTINGS_KEY = \"workspace-app-metadata\";\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nconst WORKSPACE_APPS_GATEWAY_PATH = \"/_workspace/apps\";\nconst WORKSPACE_APPS_GATEWAY_TIMEOUT_MS = 1_000;\nconst MAX_PENDING_APPS = 50;\nconst PENDING_WORKSPACE_APP_TTL_MS = 7 * 24 * 60 * 60 * 1_000;\nconst AGENT_CARD_PATH = \"/.well-known/agent-card.json\";\nconst AGENT_CARD_FETCH_TIMEOUT_MS = 1_500;\nconst DEFAULT_WORKSPACE_APP_AUDIENCE = \"internal\";\n\ntype WorkspaceAppAudience = \"internal\" | \"public\";\n\nexport interface WorkspaceAppSummary {\n id: string;\n name: string;\n description: string;\n path: string;\n url: string | null;\n isDispatch: boolean;\n audience: WorkspaceAppAudience;\n publicPaths: string[];\n protectedPaths: string[];\n status?: \"ready\" | \"pending\";\n statusLabel?: string;\n builderUrl?: string | null;\n branchName?: string | null;\n createdAt?: string | null;\n agentCardUrl?: string | null;\n agentCardReachable?: boolean;\n a2aEndpointUrl?: string | null;\n agentName?: string | null;\n agentSkillsCount?: number | null;\n archived?: boolean;\n}\n\nexport interface ListWorkspaceAppsOptions {\n includeAgentCards?: boolean;\n /**\n * Include apps the current viewer has hidden (archived). Defaults to false\n * so polling/UI callers see only the visible set; the apps page passes true\n * when rendering the \"Hidden apps\" expander.\n */\n includeArchived?: boolean;\n audience?: WorkspaceAppAudience | \"all\";\n}\n\nexport interface AvailableWorkspaceTemplate {\n name: string;\n label: string;\n hint: string;\n icon: string;\n color: string;\n colorRgb: string;\n core: boolean;\n}\n\nexport interface AppCreationSettings {\n builderProjectId: string | null;\n builderProjectIdSource: \"env\" | \"dispatch\" | \"default\" | \"unset\";\n envBuilderProjectId: string | null;\n savedBuilderProjectId: string | null;\n builderBranchingEnabled: boolean;\n}\n\nexport interface WorkspaceInfo {\n /** Slug from the workspace root package.json `name` (e.g. \"on-call-todo-manager\"). */\n name: string | null;\n /** Title-cased version for display (e.g. \"On Call Todo Manager\"). */\n displayName: string | null;\n /** Absolute path to the workspace root, if detected. */\n rootPath: string | null;\n /** Number of apps currently scaffolded under apps/. */\n appCount: number;\n}\n\ninterface PendingWorkspaceApp {\n id: string;\n name: string;\n description: string;\n path: string;\n builderUrl: string | null;\n branchName: string | null;\n projectId: string | null;\n contextId: string | null;\n contextLabel: string | null;\n audience?: WorkspaceAppAudience;\n createdAt: string;\n updatedAt: string;\n expiresAt: string | null;\n}\n\ninterface WorkspaceAppMetadataOverride {\n name?: string;\n description?: string;\n generated?: boolean;\n sourcePrompt?: string;\n updatedAt?: string;\n updatedBy?: string;\n}\n\ninterface WorkspaceAppMetadataSettings {\n apps: Record<string, WorkspaceAppMetadataOverride>;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction ensureSentence(value: string): string {\n if (!value) return value;\n const capitalized = value.charAt(0).toUpperCase() + value.slice(1);\n return /[.!?]$/.test(capitalized) ? capitalized : `${capitalized}.`;\n}\n\nfunction clipSentence(value: string, max = 180): string {\n if (value.length <= max) return value;\n const clipped = value\n .slice(0, max - 1)\n .replace(/\\s+\\S*$/, \"\")\n .trim();\n return `${clipped || value.slice(0, max - 1).trim()}…`;\n}\n\nexport function generateWorkspaceAppDescription(\n prompt: string,\n appId: string,\n): string {\n const cleaned = normalizeWhitespace(prompt)\n .replace(\n /^(please\\s+)?(build|create|make|generate|scaffold)\\s+(me\\s+|us\\s+)?/i,\n \"\",\n )\n .replace(\n /^(an?\\s+)?(workspace\\s+)?(agent-native\\s+)?(app|tool)\\s+(that|to|for)\\s+/i,\n \"\",\n )\n .replace(/^(an?\\s+)?(dashboard|workspace|agent)\\s+(that|to|for)\\s+/i, \"\");\n\n if (!cleaned) return `Workspace app for ${titleCase(appId)}.`;\n return clipSentence(ensureSentence(cleaned));\n}\n\nfunction scopedSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${SETTINGS_KEY}:org:${orgId}`;\n return `${SETTINGS_KEY}:user:${currentOwnerEmail()}`;\n}\n\nfunction workspaceAppMetadataSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:org:${orgId}`;\n return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:user:${currentOwnerEmail()}`;\n}\n\nfunction cleanOptionalString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction normalizeContextPart(value: string): string {\n return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction pendingWorkspaceAppContext(): { id: string; label: string } | null {\n const branch =\n cleanOptionalString(process.env.BRANCH) ??\n cleanOptionalString(process.env.HEAD) ??\n cleanOptionalString(process.env.VERCEL_GIT_COMMIT_REF) ??\n cleanOptionalString(process.env.CF_PAGES_BRANCH) ??\n cleanOptionalString(process.env.RENDER_GIT_BRANCH) ??\n cleanOptionalString(process.env.FLY_BRANCH);\n if (branch) {\n const normalized = normalizeContextPart(branch);\n return { id: `branch:${normalized}`, label: `Branch: ${normalized}` };\n }\n\n const origin =\n cleanOptionalString(process.env.DEPLOY_PRIME_URL) ??\n cleanOptionalString(process.env.DEPLOY_URL) ??\n cleanOptionalString(process.env.URL) ??\n cleanOptionalString(process.env.APP_URL) ??\n cleanOptionalString(process.env.BETTER_AUTH_URL) ??\n cleanOptionalString(process.env.WORKSPACE_GATEWAY_URL);\n if (!origin) return null;\n\n try {\n const parsed = new URL(origin);\n return {\n id: `origin:${parsed.origin}`,\n label: parsed.hostname,\n };\n } catch {\n const normalized = normalizeContextPart(origin);\n return { id: `origin:${normalized}`, label: normalized };\n }\n}\n\nasync function readSettingsRecord(): Promise<Record<string, any>> {\n const raw = await getSetting(scopedSettingsKey()).catch(() => null);\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, any>)\n : {};\n}\n\nfunction cleanOptionalText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction parseWorkspaceAppMetadataSettings(\n raw: unknown,\n): WorkspaceAppMetadataSettings {\n const record =\n raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n const rawApps =\n record.apps &&\n typeof record.apps === \"object\" &&\n !Array.isArray(record.apps)\n ? (record.apps as Record<string, unknown>)\n : {};\n const apps: Record<string, WorkspaceAppMetadataOverride> = {};\n\n for (const [id, value] of Object.entries(rawApps)) {\n if (!id.trim() || !value || typeof value !== \"object\") continue;\n const item = value as Record<string, unknown>;\n const override: WorkspaceAppMetadataOverride = {};\n const name = cleanOptionalText(item.name);\n const description = cleanOptionalText(item.description);\n const sourcePrompt = cleanOptionalText(item.sourcePrompt);\n const updatedAt = cleanOptionalText(item.updatedAt);\n const updatedBy = cleanOptionalText(item.updatedBy);\n\n if (name) override.name = name;\n if (description) override.description = description;\n if (item.generated === true) override.generated = true;\n if (sourcePrompt) override.sourcePrompt = sourcePrompt;\n if (updatedAt) override.updatedAt = updatedAt;\n if (updatedBy) override.updatedBy = updatedBy;\n\n if (Object.keys(override).length > 0) apps[id.trim()] = override;\n }\n\n return { apps };\n}\n\nasync function readWorkspaceAppMetadataSettings(): Promise<WorkspaceAppMetadataSettings> {\n const raw = await getSetting(workspaceAppMetadataSettingsKey()).catch(\n () => null,\n );\n return parseWorkspaceAppMetadataSettings(raw);\n}\n\nasync function writeWorkspaceAppMetadataOverride(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n generated?: boolean;\n sourcePrompt?: string | null;\n updatedBy?: string | null;\n}): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n const current = parseWorkspaceAppMetadataSettings(\n await getSetting(key).catch(() => null),\n );\n const appId = input.appId.trim();\n const existing = current.apps[appId] ?? {};\n const next: WorkspaceAppMetadataOverride = {\n ...existing,\n updatedAt: new Date().toISOString(),\n };\n const name = cleanOptionalText(input.name);\n const description = cleanOptionalText(input.description);\n const sourcePrompt = cleanOptionalText(input.sourcePrompt);\n const updatedBy = cleanOptionalText(input.updatedBy);\n\n if (name) next.name = name;\n else delete next.name;\n if (description) next.description = description;\n else delete next.description;\n if (input.generated === true) next.generated = true;\n else if (input.generated === false) delete next.generated;\n if (sourcePrompt) next.sourcePrompt = sourcePrompt;\n if (updatedBy) next.updatedBy = updatedBy;\n\n current.apps[appId] = next;\n await putSetting(key, { apps: current.apps });\n return current;\n}\n\nfunction applyWorkspaceAppMetadataOverride(\n app: WorkspaceAppSummary,\n settings: WorkspaceAppMetadataSettings,\n): WorkspaceAppSummary {\n const override = settings.apps[app.id];\n if (!override) return app;\n\n const name = cleanOptionalText(override.name);\n const description = cleanOptionalText(override.description);\n const generated = override.generated === true;\n const shouldApplyName = !!name && !generated;\n const shouldApplyDescription =\n !!description && (!generated || !cleanOptionalText(app.description));\n if (!shouldApplyName && !shouldApplyDescription) return app;\n\n return {\n ...app,\n ...(shouldApplyName ? { name } : {}),\n ...(shouldApplyDescription ? { description } : {}),\n };\n}\n\nfunction workspaceAppUrl(appPath: string): string | null {\n const base =\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null;\n if (!base) return null;\n try {\n return new URL(appPath, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppLink(\n appPath: string,\n explicitUrl?: unknown,\n): string | null {\n const urlValue = typeof explicitUrl === \"string\" ? explicitUrl.trim() : \"\";\n if (!urlValue) return workspaceAppUrl(appPath);\n if (urlValue.startsWith(\"/\")) return workspaceAppUrl(urlValue) ?? urlValue;\n try {\n return new URL(urlValue).toString();\n } catch {\n return urlValue;\n }\n}\n\nfunction normalizeWorkspaceAppAudience(value: unknown): WorkspaceAppAudience {\n return value === \"public\" ? \"public\" : DEFAULT_WORKSPACE_APP_AUDIENCE;\n}\n\nfunction normalizeWorkspaceAppPathList(value: unknown): string[] {\n let rawPaths: unknown[] = [];\n if (Array.isArray(value)) {\n rawPaths = value;\n } else if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) return [];\n try {\n const parsed = JSON.parse(trimmed);\n rawPaths = Array.isArray(parsed) ? parsed : [trimmed];\n } catch {\n rawPaths = trimmed.split(\",\");\n }\n }\n\n const paths = rawPaths\n .map((entry) => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter((entry) => entry.startsWith(\"/\"))\n .map((entry) =>\n entry.length > 1 && entry.endsWith(\"/\") ? entry.slice(0, -1) : entry,\n );\n return Array.from(new Set(paths));\n}\n\nfunction workspaceAppAudienceFromPackageJson(\n pkg: unknown,\n): WorkspaceAppAudience | undefined {\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) return undefined;\n const record = pkg as Record<string, any>;\n const config = record[\"agent-native\"] ?? record.agentNative;\n const nested =\n config && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, any>)\n : {};\n const raw =\n nested.workspaceApp?.audience ??\n nested.workspace?.audience ??\n nested.audience ??\n record.workspaceAppAudience;\n if (raw === undefined) return undefined;\n return normalizeWorkspaceAppAudience(raw);\n}\n\nfunction workspaceAppRouteAccessFromPackageJson(pkg: unknown): {\n publicPaths: string[];\n protectedPaths: string[];\n} {\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) {\n return { publicPaths: [], protectedPaths: [] };\n }\n const record = pkg as Record<string, any>;\n const config = record[\"agent-native\"] ?? record.agentNative;\n const nested =\n config && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, any>)\n : {};\n return {\n publicPaths: normalizeWorkspaceAppPathList(\n nested.workspaceApp?.publicPaths ??\n nested.workspaceApp?.publicPagePaths ??\n nested.workspace?.publicPaths ??\n nested.publicPaths ??\n record.workspaceAppPublicPaths,\n ),\n protectedPaths: normalizeWorkspaceAppPathList(\n nested.workspaceApp?.protectedPaths ??\n nested.workspaceApp?.privatePaths ??\n nested.workspaceApp?.authRequiredPaths ??\n nested.workspace?.protectedPaths ??\n nested.protectedPaths ??\n record.workspaceAppProtectedPaths,\n ),\n };\n}\n\nfunction parseWorkspaceAppsManifest(parsed: any): WorkspaceAppSummary[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps: WorkspaceAppSummary[] = rawApps\n .map((entry: any): WorkspaceAppSummary | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url: workspaceAppLink(pathValue, entry.url),\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n audience:\n entry.audience === undefined\n ? DEFAULT_WORKSPACE_APP_AUDIENCE\n : normalizeWorkspaceAppAudience(entry.audience),\n publicPaths: normalizeWorkspaceAppPathList(entry.publicPaths),\n protectedPaths: normalizeWorkspaceAppPathList(entry.protectedPaths),\n status: \"ready\",\n } satisfies WorkspaceAppSummary;\n })\n .filter(\n (app: WorkspaceAppSummary | null): app is WorkspaceAppSummary =>\n app !== null,\n )\n .sort(sortWorkspaceApps);\n\n return apps.length ? apps : null;\n}\n\nfunction parseDateMs(value: string | null | undefined): number | null {\n if (!value) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pendingWorkspaceAppExpiresAt(createdAt: string): string {\n const createdMs = parseDateMs(createdAt) ?? Date.now();\n return new Date(createdMs + PENDING_WORKSPACE_APP_TTL_MS).toISOString();\n}\n\nfunction isPendingWorkspaceAppExpired(\n app: Pick<PendingWorkspaceApp, \"createdAt\" | \"expiresAt\">,\n): boolean {\n const expiresMs =\n parseDateMs(app.expiresAt) ??\n (parseDateMs(app.createdAt) ?? Date.now()) + PENDING_WORKSPACE_APP_TTL_MS;\n return expiresMs <= Date.now();\n}\n\nfunction pendingWorkspaceAppMatchesCurrentContext(\n app: Pick<PendingWorkspaceApp, \"contextId\" | \"createdAt\" | \"expiresAt\">,\n): boolean {\n if (isPendingWorkspaceAppExpired(app)) return false;\n const currentContext = pendingWorkspaceAppContext();\n if (!app.contextId) return true;\n return app.contextId === currentContext?.id;\n}\n\nfunction pendingWorkspaceAppContextRank(\n app: Pick<PendingWorkspaceApp, \"contextId\">,\n): number {\n const currentContext = pendingWorkspaceAppContext();\n if (app.contextId && app.contextId === currentContext?.id) return 2;\n if (!app.contextId) return 1;\n return 0;\n}\n\nfunction dedupePendingWorkspaceAppsForCurrentContext(\n apps: PendingWorkspaceApp[],\n): PendingWorkspaceApp[] {\n const byId = new Map<string, PendingWorkspaceApp>();\n for (const app of apps) {\n const existing = byId.get(app.id);\n if (\n !existing ||\n pendingWorkspaceAppContextRank(app) >\n pendingWorkspaceAppContextRank(existing)\n ) {\n byId.set(app.id, app);\n }\n }\n return Array.from(byId.values());\n}\n\nfunction sortWorkspaceApps(a: WorkspaceAppSummary, b: WorkspaceAppSummary) {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n if (a.status === \"pending\" && b.status !== \"pending\") return 1;\n if (a.status !== \"pending\" && b.status === \"pending\") return -1;\n return a.name.localeCompare(b.name);\n}\n\nfunction parsePendingWorkspaceApps(value: unknown): PendingWorkspaceApp[] {\n if (!Array.isArray(value)) return [];\n return value\n .map((entry): PendingWorkspaceApp | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const record = entry as Record<string, unknown>;\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\n const pathValue =\n typeof record.path === \"string\" ? record.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n const now = new Date().toISOString();\n const createdAt = cleanOptionalString(record.createdAt) ?? now;\n return {\n id,\n name:\n typeof record.name === \"string\" && record.name.trim()\n ? record.name.trim()\n : titleCase(id),\n description:\n typeof record.description === \"string\"\n ? record.description\n : \"Builder is creating this app. The workspace path becomes live after the branch is merged and deployed.\",\n path: pathValue,\n builderUrl:\n typeof record.builderUrl === \"string\" && record.builderUrl.trim()\n ? record.builderUrl.trim()\n : null,\n branchName:\n typeof record.branchName === \"string\" && record.branchName.trim()\n ? record.branchName.trim()\n : null,\n projectId:\n typeof record.projectId === \"string\" && record.projectId.trim()\n ? record.projectId.trim()\n : null,\n contextId: cleanOptionalString(record.contextId),\n contextLabel: cleanOptionalString(record.contextLabel),\n ...(record.audience === undefined\n ? {}\n : { audience: normalizeWorkspaceAppAudience(record.audience) }),\n createdAt,\n updatedAt:\n typeof record.updatedAt === \"string\" && record.updatedAt.trim()\n ? record.updatedAt.trim()\n : now,\n expiresAt:\n cleanOptionalString(record.expiresAt) ??\n pendingWorkspaceAppExpiresAt(createdAt),\n } satisfies PendingWorkspaceApp;\n })\n .filter((app): app is PendingWorkspaceApp => !!app)\n .slice(0, MAX_PENDING_APPS);\n}\n\nasync function listPendingWorkspaceApps(): Promise<PendingWorkspaceApp[]> {\n const raw = await readSettingsRecord();\n return parsePendingWorkspaceApps(raw.pendingApps);\n}\n\nfunction parseArchivedAppIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const ids = value\n .map((entry) => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter(Boolean);\n return Array.from(new Set(ids));\n}\n\nasync function listArchivedAppIds(): Promise<string[]> {\n const raw = await readSettingsRecord();\n return parseArchivedAppIds(raw.archivedAppIds);\n}\n\nexport async function archiveWorkspaceApp(input: {\n appId: string;\n}): Promise<{ archivedAppIds: string[] }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const current = parseArchivedAppIds(raw.archivedAppIds);\n if (!current.includes(appId)) current.push(appId);\n await putSetting(scopedSettingsKey(), { ...raw, archivedAppIds: current });\n await recordAudit({\n action: \"workspace-app.archived\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Hid workspace app from the Apps list\",\n });\n return { archivedAppIds: current };\n}\n\nexport async function unarchiveWorkspaceApp(input: {\n appId: string;\n}): Promise<{ archivedAppIds: string[] }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const current = parseArchivedAppIds(raw.archivedAppIds).filter(\n (id) => id !== appId,\n );\n await putSetting(scopedSettingsKey(), { ...raw, archivedAppIds: current });\n await recordAudit({\n action: \"workspace-app.unarchived\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Restored workspace app to the Apps list\",\n });\n return { archivedAppIds: current };\n}\n\nexport async function removePendingWorkspaceApp(input: {\n appId: string;\n}): Promise<{ removed: boolean }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const pending = parsePendingWorkspaceApps(raw.pendingApps);\n const next = pending.filter(\n (app) => app.id !== appId || !pendingWorkspaceAppMatchesCurrentContext(app),\n );\n const removed = next.length !== pending.length;\n if (!removed) return { removed: false };\n await putSetting(scopedSettingsKey(), { ...raw, pendingApps: next });\n await recordAudit({\n action: \"workspace-app.pending-removed\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Removed pending Builder app from the Apps list\",\n });\n return { removed: true };\n}\n\nfunction pendingAppToSummary(app: PendingWorkspaceApp): WorkspaceAppSummary {\n return {\n id: app.id,\n name: app.name,\n description: app.description,\n path: app.path,\n url: app.builderUrl,\n isDispatch: false,\n audience: app.audience ?? DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: [],\n protectedPaths: [],\n status: \"pending\",\n statusLabel: \"Pending Builder branch\",\n builderUrl: app.builderUrl,\n branchName: app.branchName,\n createdAt: app.createdAt,\n };\n}\n\nasync function appendPendingWorkspaceApps(\n apps: WorkspaceAppSummary[],\n): Promise<WorkspaceAppSummary[]> {\n const readyIds = new Set(apps.map((app) => app.id));\n const pendingApps = dedupePendingWorkspaceAppsForCurrentContext(\n (await listPendingWorkspaceApps())\n .filter(pendingWorkspaceAppMatchesCurrentContext)\n .filter((app) => !readyIds.has(app.id)),\n ).map(pendingAppToSummary);\n return [...apps, ...pendingApps].sort(sortWorkspaceApps);\n}\n\nfunction agentCardUrlForApp(appUrl: string | null): string | null {\n if (!appUrl) return null;\n const trimmed = appUrl.replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n return new URL(`${trimmed}${AGENT_CARD_PATH}`).toString();\n } catch {\n return `${trimmed}${AGENT_CARD_PATH}`;\n }\n}\n\nfunction stringField(\n record: Record<string, unknown>,\n key: string,\n): string | null {\n const value = record[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction numberOfSkills(card: Record<string, unknown>): number | null {\n return Array.isArray(card.skills) ? card.skills.length : null;\n}\n\nasync function fetchAgentCardMetadata(\n app: WorkspaceAppSummary,\n): Promise<\n Pick<\n WorkspaceAppSummary,\n | \"agentCardUrl\"\n | \"agentCardReachable\"\n | \"a2aEndpointUrl\"\n | \"agentName\"\n | \"agentSkillsCount\"\n >\n> {\n const agentCardUrl = agentCardUrlForApp(app.url);\n if (!agentCardUrl) {\n return {\n agentCardUrl: null,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n AGENT_CARD_FETCH_TIMEOUT_MS,\n );\n\n try {\n const response = await fetch(agentCardUrl, {\n headers: { accept: \"application/json\" },\n signal: controller.signal,\n });\n if (!response.ok) {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n const parsed = await response.json().catch(() => null);\n const card =\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n if (!card) {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n return {\n agentCardUrl,\n agentCardReachable: true,\n a2aEndpointUrl:\n stringField(card, \"url\") ?? stringField(card, \"endpointUrl\"),\n agentName: stringField(card, \"name\"),\n agentSkillsCount: numberOfSkills(card),\n };\n } catch {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function maybeIncludeAgentCards(\n apps: WorkspaceAppSummary[],\n options: ListWorkspaceAppsOptions,\n): Promise<WorkspaceAppSummary[]> {\n if (!options.includeAgentCards) return apps;\n return Promise.all(\n apps.map(async (app) => {\n if (app.status === \"pending\") return app;\n const metadata = await fetchAgentCardMetadata(app);\n return { ...app, ...metadata };\n }),\n );\n}\n\nasync function recordPendingWorkspaceApp(input: {\n appId: string;\n projectId: string | null;\n description: string;\n sourcePrompt: string;\n branchName?: string | null;\n builderUrl?: string | null;\n}) {\n const now = new Date().toISOString();\n const context = pendingWorkspaceAppContext();\n const raw = await readSettingsRecord();\n const pendingApps = parsePendingWorkspaceApps(raw.pendingApps);\n const contextId = context?.id ?? null;\n const samePendingEntry = (app: PendingWorkspaceApp) =>\n app.id === input.appId &&\n (app.contextId === contextId || (!!contextId && !app.contextId));\n const existing = pendingApps\n .filter((app) => !isPendingWorkspaceAppExpired(app))\n .find(samePendingEntry);\n const next: PendingWorkspaceApp = {\n id: input.appId,\n name: titleCase(input.appId),\n description:\n input.description ||\n \"Builder is creating this app. The workspace path becomes live after the branch is merged and deployed.\",\n path: `/${input.appId}`,\n builderUrl: input.builderUrl?.trim() || null,\n branchName: input.branchName?.trim() || null,\n projectId: input.projectId,\n contextId: context?.id ?? null,\n contextLabel: context?.label ?? null,\n createdAt: existing?.createdAt || now,\n updatedAt: now,\n expiresAt: pendingWorkspaceAppExpiresAt(existing?.createdAt || now),\n };\n\n await putSetting(scopedSettingsKey(), {\n ...raw,\n pendingApps: [\n next,\n ...pendingApps.filter((app) => !samePendingEntry(app)),\n ].slice(0, MAX_PENDING_APPS),\n });\n\n await writeWorkspaceAppMetadataOverride({\n appId: input.appId,\n description: input.description,\n generated: true,\n sourcePrompt: input.sourcePrompt,\n updatedBy: currentOwnerEmail(),\n });\n\n await recordAudit({\n action: \"workspace-app.pending\",\n targetType: \"workspace-app\",\n targetId: input.appId,\n summary: \"Started Builder branch for workspace app creation\",\n metadata: {\n builderBranchUrlConfigured: !!next.builderUrl,\n branchName: next.branchName,\n projectIdConfigured: !!next.projectId,\n contextLabel: next.contextLabel,\n },\n });\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppSummary[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nasync function readWorkspaceAppsFromGateway(): Promise<\n WorkspaceAppSummary[] | null\n> {\n const base = process.env.WORKSPACE_GATEWAY_URL;\n if (!base) return null;\n\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n WORKSPACE_APPS_GATEWAY_TIMEOUT_MS,\n );\n\n try {\n const response = await fetch(\n new URL(WORKSPACE_APPS_GATEWAY_PATH, `${base.replace(/\\/$/, \"\")}/`),\n {\n headers: { accept: \"application/json\" },\n signal: controller.signal,\n },\n );\n if (!response.ok) return null;\n return parseWorkspaceAppsManifest(await response.json().catch(() => null));\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile(): WorkspaceAppSummary[] | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(\n workspaceRoot: string,\n): WorkspaceAppSummary[] | null {\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\"))\n .map((entry): WorkspaceAppSummary | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n const routeAccess = workspaceAppRouteAccessFromPackageJson(pkg);\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n url: workspaceAppUrl(`/${entry.name}`),\n isDispatch: entry.name === \"dispatch\",\n audience:\n workspaceAppAudienceFromPackageJson(pkg) ??\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: routeAccess.publicPaths,\n protectedPaths: routeAccess.protectedPaths,\n status: \"ready\",\n } satisfies WorkspaceAppSummary;\n })\n .filter((app): app is WorkspaceAppSummary => !!app)\n .sort(sortWorkspaceApps);\n\n return apps.length ? apps : null;\n}\n\nexport function getEnvBuilderProjectId(): string | null {\n return (\n process.env.DISPATCH_BUILDER_PROJECT_ID ||\n process.env.BUILDER_BRANCH_PROJECT_ID ||\n process.env.BUILDER_PROJECT_ID ||\n null\n );\n}\n\n/**\n * Read the workspace's identity from the workspace root's package.json. Used to\n * surface \"Workspace: <name>\" in the Dispatch UI so first-time users can see\n * the container their apps live inside (rather than only seeing app names like\n * \"starter\" / \"dispatch\" with no parent context).\n */\nexport function getWorkspaceInfo(): WorkspaceInfo {\n const rootPath = findWorkspaceRoot();\n if (!rootPath) {\n return { name: null, displayName: null, rootPath: null, appCount: 0 };\n }\n const pkg = readJson(path.join(rootPath, \"package.json\"));\n const rawName = typeof pkg?.name === \"string\" ? pkg.name.trim() : \"\";\n // Strip a leading \"@scope/\" if the workspace root happens to be scoped.\n const name = rawName.replace(/^@[^/]+\\//, \"\") || null;\n // Honor an explicit `displayName` in the workspace package.json before\n // falling back to a title-cased version of the slug. Users naming a\n // workspace \"On-Call Todo Manager\" via `displayName` should see that\n // exact label rather than `On Call Todo Manager`.\n const rawDisplay =\n typeof pkg?.displayName === \"string\" ? pkg.displayName.trim() : \"\";\n const displayName = rawDisplay || (name ? titleCase(name) : null);\n let appCount = 0;\n const appsDir = path.join(rootPath, \"apps\");\n if (fs.existsSync(appsDir)) {\n try {\n appCount = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory()).length;\n } catch {\n appCount = 0;\n }\n }\n return {\n name,\n displayName,\n rootPath,\n appCount,\n };\n}\n\nasync function applyArchivedAndPending(\n apps: WorkspaceAppSummary[],\n options: ListWorkspaceAppsOptions,\n): Promise<WorkspaceAppSummary[]> {\n const [withPending, archivedIds, metadataSettings] = await Promise.all([\n appendPendingWorkspaceApps(apps),\n listArchivedAppIds(),\n readWorkspaceAppMetadataSettings(),\n ]);\n const archivedSet = new Set(archivedIds);\n const annotated = withPending.map((app) => {\n const withMetadata = applyWorkspaceAppMetadataOverride(\n app,\n metadataSettings,\n );\n return archivedSet.has(app.id)\n ? { ...withMetadata, archived: true }\n : withMetadata;\n });\n return options.includeArchived\n ? filterAppsByAudience(annotated, options.audience)\n : filterAppsByAudience(\n annotated.filter((app) => !app.archived),\n options.audience,\n );\n}\n\nfunction filterAppsByAudience(\n apps: WorkspaceAppSummary[],\n audience: ListWorkspaceAppsOptions[\"audience\"],\n): WorkspaceAppSummary[] {\n if (!audience || audience === \"all\") return apps;\n return apps.filter(\n (app) =>\n (app.audience ?? DEFAULT_WORKSPACE_APP_AUDIENCE) ===\n normalizeWorkspaceAppAudience(audience),\n );\n}\n\nexport async function updateWorkspaceAppMetadata(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n}): Promise<WorkspaceAppSummary> {\n await assertCanManageAppCreationSettings();\n const appId = input.appId.trim();\n assertValidWorkspaceAppId(appId);\n\n const apps = await listWorkspaceApps({\n includeAgentCards: false,\n includeArchived: true,\n });\n const app = apps.find((candidate) => candidate.id === appId);\n if (!app) throw new Error(`Workspace app \"${appId}\" was not found.`);\n\n // Treat undefined/null as \"field omitted, leave existing value alone\"; an\n // explicit empty string clears the override (the app reverts to its\n // built-in name / no description). Without this, a partial update that\n // only touches one field silently wipes the other.\n const name = input.name == null ? app.name : input.name.trim();\n const description =\n input.description == null\n ? (app.description ?? undefined)\n : input.description.trim();\n await writeWorkspaceAppMetadataOverride({\n appId,\n name,\n description,\n generated: false,\n updatedBy: currentOwnerEmail(),\n });\n\n await recordAudit({\n action: \"workspace-app.metadata-updated\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: `Updated workspace app details for ${name}`,\n metadata: {\n name,\n descriptionConfigured: !!description,\n },\n });\n\n const updated = (\n await listWorkspaceApps({\n includeAgentCards: false,\n includeArchived: true,\n })\n ).find((candidate) => candidate.id === appId);\n return updated ?? { ...app, name, description };\n}\n\nexport async function listWorkspaceApps(\n options: ListWorkspaceAppsOptions = {},\n): Promise<WorkspaceAppSummary[]> {\n const gatewayApps = await readWorkspaceAppsFromGateway();\n if (gatewayApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(gatewayApps, options),\n options,\n );\n }\n\n const workspaceRoot = findWorkspaceRoot();\n const localFilesystemApps =\n workspaceRoot && isLocalAppCreationRuntime()\n ? readWorkspaceAppsFromFilesystem(workspaceRoot)\n : null;\n if (localFilesystemApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(localFilesystemApps, options),\n options,\n );\n }\n\n const manifestApps =\n readWorkspaceAppsFromEnv() ?? readWorkspaceAppsFromManifestFile();\n if (manifestApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(manifestApps, options),\n options,\n );\n }\n\n if (!workspaceRoot) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(\n [\n {\n id: \"dispatch\",\n name: \"Dispatch\",\n description: \"Workspace control plane\",\n path: \"/dispatch\",\n url: workspaceAppUrl(\"/dispatch\"),\n isDispatch: true,\n audience: DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: [],\n protectedPaths: [],\n status: \"ready\",\n },\n ],\n options,\n ),\n options,\n );\n }\n\n const apps = readWorkspaceAppsFromFilesystem(workspaceRoot) ?? [];\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(apps, options),\n options,\n );\n}\n\n/**\n * First-party templates the user can scaffold into this workspace via the\n * Apps page tiles. Inlined here (rather than importing from\n * `@agent-native/shared-app-config`) because the published `@agent-native/dispatch`\n * package has no `workspace:*` runtime dependencies. Keep in sync with\n * `packages/core/src/cli/templates-meta.ts`.\n */\nconst ADDABLE_TEMPLATES: AvailableWorkspaceTemplate[] = [\n {\n name: \"mail\",\n label: \"Mail\",\n hint: \"Email client with keyboard shortcuts and AI triage\",\n icon: \"Mail\",\n color: \"#3B82F6\",\n colorRgb: \"59 130 246\",\n core: true,\n },\n {\n name: \"calendar\",\n label: \"Calendar\",\n hint: \"Manage events, sync, and public booking\",\n icon: \"CalendarMonth\",\n color: \"#8B5CF6\",\n colorRgb: \"139 92 246\",\n core: true,\n },\n {\n name: \"content\",\n label: \"Content\",\n hint: \"Write and organize with agent assistance\",\n icon: \"FileText\",\n color: \"#10B981\",\n colorRgb: \"16 185 129\",\n core: true,\n },\n {\n name: \"slides\",\n label: \"Slides\",\n hint: \"Generate and edit React presentations\",\n icon: \"Presentation\",\n color: \"#EC4899\",\n colorRgb: \"236 72 153\",\n core: true,\n },\n {\n name: \"clips\",\n label: \"Clips\",\n hint: \"Screen recording, meeting notes, and voice dictation\",\n icon: \"ScreenShare\",\n color: \"#625DF5\",\n colorRgb: \"98 93 245\",\n core: true,\n },\n {\n name: \"brain\",\n label: \"Brain\",\n hint: \"Cited company knowledge from Slack, meetings, transcripts, and decisions\",\n icon: \"Brain\",\n color: \"#8B5CF6\",\n colorRgb: \"139 92 246\",\n core: true,\n },\n {\n name: \"assets\",\n label: \"Assets\",\n hint: \"Upload, organize, search, and generate on-brand images and videos\",\n icon: \"Photo\",\n color: \"#0F766E\",\n colorRgb: \"15 118 110\",\n core: true,\n },\n {\n name: \"analytics\",\n label: \"Analytics\",\n hint: \"Connect data sources, prompt for charts\",\n icon: \"ChartBar\",\n color: \"#F59E0B\",\n colorRgb: \"245 158 11\",\n core: true,\n },\n {\n name: \"forms\",\n label: \"Forms\",\n hint: \"Create, edit, and manage forms\",\n icon: \"ClipboardList\",\n color: \"#06B6D4\",\n colorRgb: \"6 182 212\",\n core: true,\n },\n {\n name: \"contracts\",\n label: \"Contracts\",\n hint: \"Review assumptions, feedback, and proof for coding-agent work\",\n icon: \"Contract\",\n color: \"#4F46E5\",\n colorRgb: \"79 70 229\",\n core: false,\n },\n {\n name: \"design\",\n label: \"Design\",\n hint: \"Create and edit visual designs with agent assistance\",\n icon: \"Brush\",\n color: \"#F472B6\",\n colorRgb: \"244 114 182\",\n core: true,\n },\n {\n name: \"videos\",\n label: \"Video\",\n hint: \"Video editing with Remotion\",\n icon: \"Video\",\n color: \"#EF4444\",\n colorRgb: \"239 68 68\",\n core: false,\n },\n];\n\nexport async function listAvailableWorkspaceTemplates(): Promise<\n AvailableWorkspaceTemplate[]\n> {\n if (!isLocalAppCreationRuntime()) return [];\n\n const installed = new Set(\n (await listWorkspaceApps({ includeArchived: true })).map((app) => app.id),\n );\n return ADDABLE_TEMPLATES.filter((tpl) => !installed.has(tpl.name));\n}\n\nconst SCAFFOLD_TIMEOUT_MS = 90_000;\n\nexport async function scaffoldWorkspaceAppFromTemplate(input: {\n template: string;\n appId?: string | null;\n}): Promise<{ appId: string; template: string; output: string }> {\n if (!isLocalAppCreationRuntime()) {\n throw new Error(\n \"Scaffolding from Dispatch is only available in local development. \" +\n \"Use the Builder branch flow on a deployed workspace.\",\n );\n }\n const template = input.template.trim();\n if (!template) throw new Error(\"template is required\");\n if (!ADDABLE_TEMPLATES.some((tpl) => tpl.name === template)) {\n throw new Error(`Unknown template \"${template}\".`);\n }\n\n const appId = (input.appId?.trim() || template).toLowerCase();\n assertValidWorkspaceAppId(appId);\n\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) {\n throw new Error(\"No agent-native workspace detected for scaffolding.\");\n }\n const appDir = path.join(workspaceRoot, \"apps\", appId);\n if (fs.existsSync(appDir)) {\n throw new Error(`apps/${appId} already exists.`);\n }\n\n const output = await runScaffoldCli({\n cwd: workspaceRoot,\n args: [\"add-app\", appId, \"--template\", template],\n });\n\n await recordAudit({\n action: \"workspace-app.scaffolded\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: `Scaffolded apps/${appId} from ${template}`,\n metadata: { template },\n });\n\n return { appId, template, output };\n}\n\nfunction runScaffoldCli(input: {\n cwd: string;\n args: string[];\n}): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"pnpm\", [\"exec\", \"agent-native\", ...input.args], {\n cwd: input.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (chunk) => {\n stdout += String(chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += String(chunk);\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n reject(\n new Error(\n `Scaffold timed out after ${Math.round(SCAFFOLD_TIMEOUT_MS / 1000)}s`,\n ),\n );\n }, SCAFFOLD_TIMEOUT_MS);\n timer.unref();\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n reject(err);\n });\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n if (code === 0) {\n resolve([stdout, stderr].filter(Boolean).join(\"\\n\").trim());\n return;\n }\n const detail = (stderr || stdout || \"\").trim() || `exit code ${code}`;\n reject(new Error(`Scaffold failed: ${detail}`));\n });\n });\n}\n\nexport async function getAppCreationSettings(): Promise<AppCreationSettings> {\n const envBuilderProjectId = getEnvBuilderProjectId();\n const resolvedBuilderProjectId = await resolveBuilderBranchProjectId();\n const raw = await readSettingsRecord();\n const savedBuilderProjectId =\n typeof raw?.builderProjectId === \"string\" && raw.builderProjectId.trim()\n ? raw.builderProjectId.trim()\n : null;\n const builderProjectId = envBuilderProjectId || savedBuilderProjectId;\n const enableBuilder =\n process.env.ENABLE_BUILDER === \"true\" || process.env.ENABLE_BUILDER === \"1\";\n const effectiveBuilderProjectId =\n builderProjectId ||\n resolvedBuilderProjectId ||\n (enableBuilder ? getBuilderBranchProjectId() : null);\n\n return {\n builderProjectId: effectiveBuilderProjectId,\n builderProjectIdSource: envBuilderProjectId\n ? \"env\"\n : savedBuilderProjectId\n ? \"dispatch\"\n : effectiveBuilderProjectId\n ? \"default\"\n : \"unset\",\n envBuilderProjectId,\n savedBuilderProjectId,\n builderBranchingEnabled: !!effectiveBuilderProjectId,\n };\n}\n\nexport async function setAppCreationSettings(input: {\n builderProjectId?: string | null;\n}): Promise<AppCreationSettings> {\n await assertCanManageAppCreationSettings();\n const builderProjectId = input.builderProjectId?.trim() || null;\n const raw = await readSettingsRecord();\n await putSetting(scopedSettingsKey(), { ...raw, builderProjectId });\n await recordAudit({\n action: \"settings.updated\",\n targetType: \"dispatch-app-creation-settings\",\n targetId: SETTINGS_KEY,\n summary: builderProjectId\n ? \"Updated default Builder project for app creation\"\n : \"Cleared default Builder project for app creation\",\n metadata: { builderProjectIdConfigured: !!builderProjectId },\n });\n return getAppCreationSettings();\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 64);\n}\n\nfunction isLocalAppCreationRuntime(): boolean {\n if (process.env.NODE_ENV === \"production\") return false;\n if (\n process.env.NETLIFY ||\n process.env.VERCEL ||\n process.env.CF_PAGES ||\n process.env.DEPLOY_URL ||\n process.env.URL ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME\n ) {\n return false;\n }\n return true;\n}\n\nfunction isSyntheticIntegrationOwner(ownerEmail: string): boolean {\n return (\n ownerEmail.startsWith(\"integration@\") ||\n ownerEmail.endsWith(\"@integration.local\")\n );\n}\n\nasync function requestOwnerRole(): Promise<string | null> {\n const orgId = currentOrgId();\n const ownerEmail = currentOwnerEmail();\n if (!orgId) return null;\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT role FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [orgId, ownerEmail.toLowerCase()],\n });\n const role = (rows[0] as any)?.role;\n return typeof role === \"string\" ? role : null;\n } catch {\n return null;\n }\n}\n\nasync function assertCanManageAppCreationSettings(): Promise<void> {\n const orgId = currentOrgId();\n if (!orgId) return;\n const role = await requestOwnerRole();\n if (role !== \"owner\" && role !== \"admin\") {\n throw new Error(\n \"Only organization owners and admins can update app creation settings.\",\n );\n }\n}\n\nasync function isCurrentIntegrationExplicitlyLinked(): Promise<boolean> {\n const incoming = getRequestContext()?.integration?.incoming;\n if (!incoming) return true;\n const externalUserId = identityKeyForIncoming(incoming);\n const linkedOwner = await resolveLinkedOwner(\n incoming.platform,\n externalUserId,\n {\n allowAnyOrgFallback: true,\n },\n ).catch(() => null);\n return linkedOwner === currentOwnerEmail();\n}\n\nasync function defaultOwnerAppCreationAllowed(): Promise<boolean> {\n const defaultOwner = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (!defaultOwner || defaultOwner !== currentOwnerEmail()) return false;\n if (await isCurrentIntegrationExplicitlyLinked()) return true;\n return (\n process.env.DISPATCH_ALLOW_DEFAULT_OWNER_APP_CREATION === \"true\" ||\n process.env.DISPATCH_ALLOW_DEFAULT_OWNER_APP_CREATION === \"1\" ||\n process.env.ENABLE_BUILDER === \"true\" ||\n process.env.ENABLE_BUILDER === \"1\"\n );\n}\n\nfunction normalizeBuilderRunString(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new Error(`Builder app creation returned a blank ${fieldName}`);\n }\n const trimmed = value.trim();\n if (/[\u0000-\u001f]/.test(trimmed)) {\n throw new Error(`Builder app creation returned a malformed ${fieldName}`);\n }\n return trimmed;\n}\n\nfunction normalizeBuilderRunUrl(value: unknown): string {\n const urlString = normalizeBuilderRunString(value, \"url\");\n let parsed: URL;\n try {\n parsed = new URL(urlString);\n } catch {\n throw new Error(\"Builder app creation returned a malformed url\");\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\"Builder app creation returned a malformed url\");\n }\n if (\n parsed.hostname !== \"builder.io\" &&\n !parsed.hostname.endsWith(\".builder.io\")\n ) {\n throw new Error(\"Builder app creation returned a non-Builder url\");\n }\n return parsed.toString();\n}\n\nfunction normalizeBuilderRunResult(result: unknown): {\n branchName: string;\n url: string;\n status: string;\n} {\n const record =\n result && typeof result === \"object\" && !Array.isArray(result)\n ? (result as Record<string, unknown>)\n : {};\n return {\n branchName: normalizeBuilderRunString(record.branchName, \"branchName\"),\n url: normalizeBuilderRunUrl(record.url),\n status:\n typeof record.status === \"string\" && record.status.trim()\n ? record.status.trim()\n : \"processing\",\n };\n}\n\nasync function remoteAppCreationAuthorization(): Promise<\n { ok: true } | { ok: false; message: string }\n> {\n const ownerEmail = currentOwnerEmail();\n const isIntegrationCaller = isIntegrationCallerRequest();\n const defaultOwner = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (isIntegrationCaller && defaultOwner && defaultOwner === ownerEmail) {\n if (await defaultOwnerAppCreationAllowed()) return { ok: true };\n return {\n ok: false,\n message:\n \"Messaging-triggered app creation is using the deployment default Dispatch owner. \" +\n \"Link the messaging identity to a Dispatch user with /link, start the app from Dispatch while signed in, or explicitly set ENABLE_BUILDER=true for this deployment.\",\n };\n }\n if (!isSyntheticIntegrationOwner(ownerEmail)) return { ok: true };\n\n const source = isIntegrationCaller\n ? \"Messaging-triggered\"\n : \"Synthetic integration\";\n return {\n ok: false,\n message:\n `${source} app creation needs a trusted Dispatch owner before Builder can start a branch. ` +\n \"Link the messaging identity to a Dispatch user with /link, start the app from Dispatch while signed in, or explicitly set ENABLE_BUILDER=true for this deployment.\",\n };\n}\n\nfunction buildWorkspaceAppPrompt(input: {\n prompt: string;\n appId?: string | null;\n description?: string | null;\n template?: string | null;\n selectedKeys?: string[];\n selectedResources?: WorkspaceResourceOption[];\n}): { appId: string; prompt: string } {\n const appId =\n slugify(input.appId || \"\") ||\n slugify(\n input.prompt.replace(/\\b(build|create|make|an?|the|app|tool)\\b/gi, \" \"),\n ) ||\n \"new-app\";\n const appDescription =\n input.description?.trim() ||\n generateWorkspaceAppDescription(input.prompt, appId);\n const selectedKeys = input.selectedKeys || [];\n const selectedResources = input.selectedResources || [];\n const resourceList = selectedResources.length\n ? selectedResources\n .map(\n (resource) =>\n `- ${resource.name} (${resource.kind}, ${resource.path})`,\n )\n .join(\"\\n\")\n : \"none\";\n return {\n appId,\n prompt: [\n \"Create a new agent-native app in this workspace.\",\n \"\",\n `App name: ${appId}`,\n `App description: ${appDescription}`,\n `Template to start from: ${input.template || \"starter\"}`,\n `User prompt: ${input.prompt.trim()}`,\n \"If the user mentions a product or company such as Granola, Loom, Superhuman, Linear, or Notion, treat it as product inspiration unless they explicitly ask to connect to that service. Do not invent or require third-party API keys like GRANOLA_API_KEY just because a product is named.\",\n selectedKeys.length\n ? `Dispatch vault keys selected for this app: ${selectedKeys.join(\", \")}`\n : \"Dispatch vault keys selected for this app: none\",\n `Dispatch workspace resources selected for this app:\\n${resourceList}`,\n `Dispatch workspace resources with scope=all are global. After the app exists, sync workspace resources to appId \"${appId}\" so global skills, guardrail instructions, and reference resources reach the new app even when no per-app resources were selected.`,\n \"\",\n `Use the workspace app layout: create it under apps/${appId}, mount it at /${appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `Important routing rule: from outside the app, link to /${appId}; inside apps/${appId}, React Router routes are app-local. Use <Link to=\"/review\"> and navigate(\"/review\"), not \"/${appId}/review\"; APP_BASE_PATH supplies the mounted prefix, and hardcoding it causes doubled URLs like /${appId}/${appId}/review.`,\n \"Existing first-party apps are neighbors, not implementation details for this app. If the user prompt mentions Mail, Calendar, Analytics, Dispatch, or other templates, treat them as existing hosted/connected apps that this app can link to or call through A2A/default connected agents. For example, Mail, Calendar, and Analytics already exist at https://mail.agent-native.com, https://calendar.agent-native.com, and https://analytics.agent-native.com.\",\n `Do not clone first-party templates, create wrapper apps, or scaffold child apps/routes for Mail, Calendar, Analytics, etc. inside apps/${appId} just so this app can access them. If the request is a cross-app dashboard or overview, build only the new dashboard/overview app and delegate to the existing apps for domain work.`,\n \"Only create another first-party app copy when the user explicitly asks for a customized fork/copy of that app; otherwise keep using the hosted/shared app so improvements to the base template keep flowing to users.\",\n selectedKeys.length\n ? `Dispatch will create pending vault requests for the selected keys for appId \"${appId}\" after this app creation request is accepted. Do not grant or sync vault keys directly from the app-creation branch.`\n : \"Do not grant or request any Dispatch vault keys unless the user asks later.\",\n selectedResources.length\n ? `Dispatch will create workspace resource grants for the selected resources for appId \"${appId}\". After the app exists, sync workspace resources so the app receives both global and selected shared resources.`\n : \"Do not grant any selected-only Dispatch workspace resources unless the user asks later.\",\n \"\",\n \"Agent-native rules (these are the framework's contract — not optional):\",\n `- Persist ALL data in SQL via Drizzle. Add tables to apps/${appId}/server/db/schema.ts and migrations to apps/${appId}/server/plugins/db.ts. NEVER use localStorage, sessionStorage, IndexedDB, or in-memory state for anything the user expects to persist — agent and UI must read the same source of truth.`,\n `- Define every create/read/update/delete as an action in apps/${appId}/actions/ using defineAction. The agent calls these as tools and the frontend calls them via useActionQuery / useActionMutation. If you must raw-fetch framework action endpoints, use agentNativePath(\"/_agent-native/actions/<name>\") so mounted apps call the right URL. Don't add /api/* routes for CRUD.`,\n \"- Build the UI from shadcn/ui components in app/components/ui/ (Button, Input, Dialog, Popover, Card, etc.) and Tailwind utilities. Don't author bespoke CSS classes in global.css unless you genuinely need a primitive that shadcn doesn't ship.\",\n \"- Use Tabler Icons (@tabler/icons-react) for every icon. Never use emojis as icons.\",\n `- Expose what the user is looking at via application_state (navigation.view, selection, etc.) so the agent has live context. Mirror the patterns in templates/mail or templates/slides.`,\n \"- Optimistic UI for every mutation: update the React Query cache immediately, navigate immediately, run the mutation in the background, roll back on error. Don't await a server round-trip before re-rendering.\",\n \"\",\n \"Branch readiness requirements before handing off:\",\n \"- The CLI auto-fills package.json name and displayName from the app id; only edit the description / scripts / dependencies if the app actually needs more than the template provides.\",\n `- Save a concise, human-readable app description in apps/${appId}/package.json \"description\" so Dispatch, A2A discovery, and connected agents can describe what this app does. Use the description above or improve it based on the prompt.`,\n \"- Do not add or update workspace-apps.json or .agent-native/workspace-apps.json unless the app needs an explicit external URL override; the root deploy generates the workspace app registry from apps/* and deploy metadata.\",\n \"- Update pnpm-lock.yaml when adding or changing dependencies so Netlify can install the branch reliably.\",\n \"- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model; do not leave the branch relying only on uncommitted local state.\",\n \"- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment. Every sibling workspace app should be usable over A2A by default through call-agent.\",\n \"- Give the app agent context that sibling workspace apps are available over A2A with names and descriptions from the workspace app registry; do not hardcode a stale app list.\",\n \"- Include a final verification note covering the registry entry, manifest/deploy metadata, relative same-origin routing, and agent-card readiness.\",\n `When it is ready, start or update the workspace dev server and navigate the user to /${appId}.`,\n ].join(\"\\n\"),\n };\n}\n\nasync function requestSelectedVaultKeys(input: {\n appId: string;\n selectedKeys: string[];\n}) {\n if (input.selectedKeys.length === 0) return;\n await Promise.allSettled(\n input.selectedKeys.map((credentialKey) =>\n Promise.resolve().then(() =>\n createRequest({\n appId: input.appId,\n credentialKey,\n reason: `Requested during workspace app creation for ${input.appId}.`,\n }),\n ),\n ),\n );\n}\n\nasync function selectedWorkspaceResourcesForIds(\n resourceIds: string[] | undefined,\n): Promise<WorkspaceResourceOption[]> {\n if (!resourceIds?.length) return [];\n const requested = new Set(resourceIds);\n const resources = await listWorkspaceResourceOptions();\n return resources.filter((resource) => requested.has(resource.id));\n}\n\nasync function grantSelectedWorkspaceResources(input: {\n appId: string;\n resourceIds: string[];\n}) {\n if (input.resourceIds.length === 0) return;\n await grantWorkspaceResourcesToApp(input);\n}\n\nexport async function startWorkspaceAppCreation(input: {\n prompt: string;\n appId?: string | null;\n description?: string | null;\n template?: string | null;\n secretIds?: string[];\n resourceIds?: string[];\n}) {\n const initial = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\n description: input.description,\n template: input.template,\n });\n assertValidWorkspaceAppId(initial.appId);\n const isLocal = isLocalAppCreationRuntime();\n\n if (!isLocal) {\n const authorization = await remoteAppCreationAuthorization();\n if (authorization.ok === false) {\n return {\n mode: \"builder-unavailable\",\n appId: initial.appId,\n message: authorization.message,\n };\n }\n }\n\n const selectedKeys = input.secretIds?.length\n ? (await listSecrets())\n .filter((secret) => input.secretIds?.includes(secret.id))\n .map((secret) => secret.credentialKey)\n : [];\n const selectedResources = await selectedWorkspaceResourcesForIds(\n input.resourceIds,\n );\n const built = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\n description: input.description,\n template: input.template,\n selectedKeys,\n selectedResources,\n });\n const prompt = built.prompt;\n const appDescription =\n input.description?.trim() ||\n generateWorkspaceAppDescription(input.prompt, built.appId);\n\n if (isLocal) {\n await requestSelectedVaultKeys({\n appId: built.appId,\n selectedKeys,\n });\n await grantSelectedWorkspaceResources({\n appId: built.appId,\n resourceIds: selectedResources.map((resource) => resource.id),\n });\n return {\n mode: \"local-agent\",\n appId: built.appId,\n prompt,\n message:\n \"Use the local code agent to create this app in the workspace, then open it from /dispatch/apps.\",\n };\n }\n\n const settings = await getAppCreationSettings();\n\n if (!settings.builderProjectId) {\n return {\n mode: \"coming-soon\",\n appId: built.appId,\n message:\n \"Builder app creation is coming soon here. Set a default Builder project in Dispatch or provide BUILDER_BRANCH_PROJECT_ID to enable branch creation.\",\n };\n }\n\n let result: {\n branchName: string;\n url: string;\n status: string;\n };\n try {\n const builderCreds = await resolveBuilderCredentials().catch(() => null);\n const builderUserId = builderCreds?.userId || undefined;\n result = normalizeBuilderRunResult(\n await runBuilderAgent({\n prompt,\n projectId: settings.builderProjectId,\n ...(builderUserId\n ? { userId: builderUserId }\n : { userEmail: currentOwnerEmail() }),\n }),\n );\n } catch (err) {\n const detail =\n err instanceof Error && err.message\n ? err.message\n : \"Builder could not start the app branch\";\n return {\n mode: \"builder-unavailable\",\n appId: built.appId,\n projectId: settings.builderProjectId,\n message:\n `Builder app creation is configured for project ${settings.builderProjectId}, ` +\n `but it could not start yet: ${detail}. Connect Builder for this user, ` +\n `link the messaging identity to that user, or configure deployment-managed Builder credentials for this workspace.`,\n };\n }\n\n await recordPendingWorkspaceApp({\n appId: built.appId,\n projectId: settings.builderProjectId,\n description: appDescription,\n sourcePrompt: input.prompt,\n branchName: result.branchName,\n builderUrl: result.url,\n });\n\n await requestSelectedVaultKeys({\n appId: built.appId,\n selectedKeys,\n });\n await grantSelectedWorkspaceResources({\n appId: built.appId,\n resourceIds: selectedResources.map((resource) => resource.id),\n });\n\n return {\n mode: \"builder\",\n appId: built.appId,\n path: `/${built.appId}`,\n projectId: settings.builderProjectId,\n branchName: result.branchName,\n url: result.url,\n workspaceUrl: workspaceAppUrl(`/${built.appId}`),\n status: result.status,\n message:\n `Builder started a branch for /${built.appId}. Use the Builder branch URL to track creation now. ` +\n `The workspace path will be live after that branch is merged and the workspace deploy finishes, so it may 404 until then.`,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app-creation-store.js","sourceRoot":"","sources":["../../../src/server/lib/app-creation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,yBAAyB,EACzB,eAAe,GAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACX,kBAAkB,GACnB,M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EAAE,KAAK,CAAC,KAAK;QAClB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;QACpC,WAAW,EAAE,cAAc;QAC3B,YAAY,EAAE,KAAK,CAAC,MAAM;QAC1B,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,UAAU,EAAE,MAAM,CAAC,GAAG;KACvB,CAAC,CAAC;IAEH,MAAM,wBAAwB,CAAC;QAC7B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,YAAY;KACb,CAAC,CAAC;IACH,MAAM,+BAA+B,CAAC;QACpC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,WAAW,EAAE,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;KAC9D,CAAC,CAAC;IAEH,OAAO;QACL,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,IAAI,KAAK,CAAC,KAAK,EAAE;QACvB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;QACpC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,YAAY,EAAE,eAAe,CAAC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,OAAO,EACL,iCAAiC,KAAK,CAAC,KAAK,sDAAsD;YAClG,0HAA0H;KAC7H,CAAC;AACJ,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getSetting, putSetting } from \"@agent-native/core/settings\";\nimport { assertValidWorkspaceAppId } from \"@agent-native/core/shared\";\nimport {\n getBuilderBranchProjectId,\n getRequestContext,\n isIntegrationCallerRequest,\n resolveBuilderBranchProjectId,\n resolveBuilderCredentials,\n runBuilderAgent,\n} from \"@agent-native/core/server\";\nimport { getDbExec } from \"@agent-native/core/db\";\nimport {\n currentOrgId,\n currentOwnerEmail,\n recordAudit,\n resolveLinkedOwner,\n} from \"./dispatch-store.js\";\nimport { identityKeyForIncoming } from \"./dispatch-integrations.js\";\nimport { createRequest, listSecrets } from \"./vault-store.js\";\nimport {\n grantWorkspaceResourcesToApp,\n listWorkspaceResourceOptions,\n type WorkspaceResourceOption,\n} from \"./workspace-resources-store.js\";\n\nconst SETTINGS_KEY = \"dispatch-app-creation-settings\";\nconst WORKSPACE_APP_METADATA_SETTINGS_KEY = \"workspace-app-metadata\";\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nconst WORKSPACE_APPS_GATEWAY_PATH = \"/_workspace/apps\";\nconst WORKSPACE_APPS_GATEWAY_TIMEOUT_MS = 1_000;\nconst MAX_PENDING_APPS = 50;\nconst PENDING_WORKSPACE_APP_TTL_MS = 7 * 24 * 60 * 60 * 1_000;\nconst AGENT_CARD_PATH = \"/.well-known/agent-card.json\";\nconst AGENT_CARD_FETCH_TIMEOUT_MS = 1_500;\nconst DEFAULT_WORKSPACE_APP_AUDIENCE = \"internal\";\n\ntype WorkspaceAppAudience = \"internal\" | \"public\";\n\nexport interface WorkspaceAppSummary {\n id: string;\n name: string;\n description: string;\n path: string;\n url: string | null;\n isDispatch: boolean;\n audience: WorkspaceAppAudience;\n publicPaths: string[];\n protectedPaths: string[];\n status?: \"ready\" | \"pending\";\n statusLabel?: string;\n builderUrl?: string | null;\n branchName?: string | null;\n createdAt?: string | null;\n agentCardUrl?: string | null;\n agentCardReachable?: boolean;\n a2aEndpointUrl?: string | null;\n agentName?: string | null;\n agentSkillsCount?: number | null;\n archived?: boolean;\n}\n\nexport interface ListWorkspaceAppsOptions {\n includeAgentCards?: boolean;\n /**\n * Include apps the current viewer has hidden (archived). Defaults to false\n * so polling/UI callers see only the visible set; the apps page passes true\n * when rendering the \"Hidden apps\" expander.\n */\n includeArchived?: boolean;\n audience?: WorkspaceAppAudience | \"all\";\n}\n\nexport interface AvailableWorkspaceTemplate {\n name: string;\n label: string;\n hint: string;\n icon: string;\n color: string;\n colorRgb: string;\n core: boolean;\n}\n\nexport interface AppCreationSettings {\n builderProjectId: string | null;\n builderProjectIdSource: \"env\" | \"dispatch\" | \"default\" | \"unset\";\n envBuilderProjectId: string | null;\n savedBuilderProjectId: string | null;\n builderBranchingEnabled: boolean;\n}\n\nexport interface WorkspaceInfo {\n /** Slug from the workspace root package.json `name` (e.g. \"on-call-todo-manager\"). */\n name: string | null;\n /** Title-cased version for display (e.g. \"On Call Todo Manager\"). */\n displayName: string | null;\n /** Absolute path to the workspace root, if detected. */\n rootPath: string | null;\n /** Number of apps currently scaffolded under apps/. */\n appCount: number;\n}\n\ninterface PendingWorkspaceApp {\n id: string;\n name: string;\n description: string;\n path: string;\n builderUrl: string | null;\n branchName: string | null;\n projectId: string | null;\n contextId: string | null;\n contextLabel: string | null;\n audience?: WorkspaceAppAudience;\n createdAt: string;\n updatedAt: string;\n expiresAt: string | null;\n}\n\ninterface WorkspaceAppMetadataOverride {\n name?: string;\n description?: string;\n generated?: boolean;\n sourcePrompt?: string;\n updatedAt?: string;\n updatedBy?: string;\n}\n\ninterface WorkspaceAppMetadataSettings {\n apps: Record<string, WorkspaceAppMetadataOverride>;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction ensureSentence(value: string): string {\n if (!value) return value;\n const capitalized = value.charAt(0).toUpperCase() + value.slice(1);\n return /[.!?]$/.test(capitalized) ? capitalized : `${capitalized}.`;\n}\n\nfunction clipSentence(value: string, max = 180): string {\n if (value.length <= max) return value;\n const clipped = value\n .slice(0, max - 1)\n .replace(/\\s+\\S*$/, \"\")\n .trim();\n return `${clipped || value.slice(0, max - 1).trim()}…`;\n}\n\nexport function generateWorkspaceAppDescription(\n prompt: string,\n appId: string,\n): string {\n const cleaned = normalizeWhitespace(prompt)\n .replace(\n /^(please\\s+)?(build|create|make|generate|scaffold)\\s+(me\\s+|us\\s+)?/i,\n \"\",\n )\n .replace(\n /^(an?\\s+)?(workspace\\s+)?(agent-native\\s+)?(app|tool)\\s+(that|to|for)\\s+/i,\n \"\",\n )\n .replace(/^(an?\\s+)?(dashboard|workspace|agent)\\s+(that|to|for)\\s+/i, \"\");\n\n if (!cleaned) return `Workspace app for ${titleCase(appId)}.`;\n return clipSentence(ensureSentence(cleaned));\n}\n\nfunction scopedSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${SETTINGS_KEY}:org:${orgId}`;\n return `${SETTINGS_KEY}:user:${currentOwnerEmail()}`;\n}\n\nfunction workspaceAppMetadataSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:org:${orgId}`;\n return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:user:${currentOwnerEmail()}`;\n}\n\nfunction cleanOptionalString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction normalizeContextPart(value: string): string {\n return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction pendingWorkspaceAppContext(): { id: string; label: string } | null {\n const branch =\n cleanOptionalString(process.env.BRANCH) ??\n cleanOptionalString(process.env.HEAD) ??\n cleanOptionalString(process.env.VERCEL_GIT_COMMIT_REF) ??\n cleanOptionalString(process.env.CF_PAGES_BRANCH) ??\n cleanOptionalString(process.env.RENDER_GIT_BRANCH) ??\n cleanOptionalString(process.env.FLY_BRANCH);\n if (branch) {\n const normalized = normalizeContextPart(branch);\n return { id: `branch:${normalized}`, label: `Branch: ${normalized}` };\n }\n\n const origin =\n cleanOptionalString(process.env.DEPLOY_PRIME_URL) ??\n cleanOptionalString(process.env.DEPLOY_URL) ??\n cleanOptionalString(process.env.URL) ??\n cleanOptionalString(process.env.APP_URL) ??\n cleanOptionalString(process.env.BETTER_AUTH_URL) ??\n cleanOptionalString(process.env.WORKSPACE_GATEWAY_URL);\n if (!origin) return null;\n\n try {\n const parsed = new URL(origin);\n return {\n id: `origin:${parsed.origin}`,\n label: parsed.hostname,\n };\n } catch {\n const normalized = normalizeContextPart(origin);\n return { id: `origin:${normalized}`, label: normalized };\n }\n}\n\nasync function readSettingsRecord(): Promise<Record<string, any>> {\n const raw = await getSetting(scopedSettingsKey()).catch(() => null);\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, any>)\n : {};\n}\n\nfunction cleanOptionalText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction parseWorkspaceAppMetadataSettings(\n raw: unknown,\n): WorkspaceAppMetadataSettings {\n const record =\n raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n const rawApps =\n record.apps &&\n typeof record.apps === \"object\" &&\n !Array.isArray(record.apps)\n ? (record.apps as Record<string, unknown>)\n : {};\n const apps: Record<string, WorkspaceAppMetadataOverride> = {};\n\n for (const [id, value] of Object.entries(rawApps)) {\n if (!id.trim() || !value || typeof value !== \"object\") continue;\n const item = value as Record<string, unknown>;\n const override: WorkspaceAppMetadataOverride = {};\n const name = cleanOptionalText(item.name);\n const description = cleanOptionalText(item.description);\n const sourcePrompt = cleanOptionalText(item.sourcePrompt);\n const updatedAt = cleanOptionalText(item.updatedAt);\n const updatedBy = cleanOptionalText(item.updatedBy);\n\n if (name) override.name = name;\n if (description) override.description = description;\n if (item.generated === true) override.generated = true;\n if (sourcePrompt) override.sourcePrompt = sourcePrompt;\n if (updatedAt) override.updatedAt = updatedAt;\n if (updatedBy) override.updatedBy = updatedBy;\n\n if (Object.keys(override).length > 0) apps[id.trim()] = override;\n }\n\n return { apps };\n}\n\nasync function readWorkspaceAppMetadataSettings(): Promise<WorkspaceAppMetadataSettings> {\n const raw = await getSetting(workspaceAppMetadataSettingsKey()).catch(\n () => null,\n );\n return parseWorkspaceAppMetadataSettings(raw);\n}\n\nasync function writeWorkspaceAppMetadataOverride(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n generated?: boolean;\n sourcePrompt?: string | null;\n updatedBy?: string | null;\n}): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n const current = parseWorkspaceAppMetadataSettings(\n await getSetting(key).catch(() => null),\n );\n const appId = input.appId.trim();\n const existing = current.apps[appId] ?? {};\n const next: WorkspaceAppMetadataOverride = {\n ...existing,\n updatedAt: new Date().toISOString(),\n };\n const name = cleanOptionalText(input.name);\n const description = cleanOptionalText(input.description);\n const sourcePrompt = cleanOptionalText(input.sourcePrompt);\n const updatedBy = cleanOptionalText(input.updatedBy);\n\n if (name) next.name = name;\n else delete next.name;\n if (description) next.description = description;\n else delete next.description;\n if (input.generated === true) next.generated = true;\n else if (input.generated === false) delete next.generated;\n if (sourcePrompt) next.sourcePrompt = sourcePrompt;\n if (updatedBy) next.updatedBy = updatedBy;\n\n current.apps[appId] = next;\n await putSetting(key, { apps: current.apps });\n return current;\n}\n\nfunction applyWorkspaceAppMetadataOverride(\n app: WorkspaceAppSummary,\n settings: WorkspaceAppMetadataSettings,\n): WorkspaceAppSummary {\n const override = settings.apps[app.id];\n if (!override) return app;\n\n const name = cleanOptionalText(override.name);\n const description = cleanOptionalText(override.description);\n const generated = override.generated === true;\n const shouldApplyName = !!name && !generated;\n const shouldApplyDescription =\n !!description && (!generated || !cleanOptionalText(app.description));\n if (!shouldApplyName && !shouldApplyDescription) return app;\n\n return {\n ...app,\n ...(shouldApplyName ? { name } : {}),\n ...(shouldApplyDescription ? { description } : {}),\n };\n}\n\nfunction workspaceAppUrl(appPath: string): string | null {\n const base =\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null;\n if (!base) return null;\n try {\n return new URL(appPath, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppLink(\n appPath: string,\n explicitUrl?: unknown,\n): string | null {\n const urlValue = typeof explicitUrl === \"string\" ? explicitUrl.trim() : \"\";\n if (!urlValue) return workspaceAppUrl(appPath);\n if (urlValue.startsWith(\"/\")) return workspaceAppUrl(urlValue) ?? urlValue;\n try {\n return new URL(urlValue).toString();\n } catch {\n return urlValue;\n }\n}\n\nfunction normalizeWorkspaceAppAudience(value: unknown): WorkspaceAppAudience {\n return value === \"public\" ? \"public\" : DEFAULT_WORKSPACE_APP_AUDIENCE;\n}\n\nfunction normalizeWorkspaceAppPathList(value: unknown): string[] {\n let rawPaths: unknown[] = [];\n if (Array.isArray(value)) {\n rawPaths = value;\n } else if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) return [];\n try {\n const parsed = JSON.parse(trimmed);\n rawPaths = Array.isArray(parsed) ? parsed : [trimmed];\n } catch {\n rawPaths = trimmed.split(\",\");\n }\n }\n\n const paths = rawPaths\n .map((entry) => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter((entry) => entry.startsWith(\"/\"))\n .map((entry) =>\n entry.length > 1 && entry.endsWith(\"/\") ? entry.slice(0, -1) : entry,\n );\n return Array.from(new Set(paths));\n}\n\nfunction workspaceAppAudienceFromPackageJson(\n pkg: unknown,\n): WorkspaceAppAudience | undefined {\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) return undefined;\n const record = pkg as Record<string, any>;\n const config = record[\"agent-native\"] ?? record.agentNative;\n const nested =\n config && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, any>)\n : {};\n const raw =\n nested.workspaceApp?.audience ??\n nested.workspace?.audience ??\n nested.audience ??\n record.workspaceAppAudience;\n if (raw === undefined) return undefined;\n return normalizeWorkspaceAppAudience(raw);\n}\n\nfunction workspaceAppRouteAccessFromPackageJson(pkg: unknown): {\n publicPaths: string[];\n protectedPaths: string[];\n} {\n if (!pkg || typeof pkg !== \"object\" || Array.isArray(pkg)) {\n return { publicPaths: [], protectedPaths: [] };\n }\n const record = pkg as Record<string, any>;\n const config = record[\"agent-native\"] ?? record.agentNative;\n const nested =\n config && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, any>)\n : {};\n return {\n publicPaths: normalizeWorkspaceAppPathList(\n nested.workspaceApp?.publicPaths ??\n nested.workspaceApp?.publicPagePaths ??\n nested.workspace?.publicPaths ??\n nested.publicPaths ??\n record.workspaceAppPublicPaths,\n ),\n protectedPaths: normalizeWorkspaceAppPathList(\n nested.workspaceApp?.protectedPaths ??\n nested.workspaceApp?.privatePaths ??\n nested.workspaceApp?.authRequiredPaths ??\n nested.workspace?.protectedPaths ??\n nested.protectedPaths ??\n record.workspaceAppProtectedPaths,\n ),\n };\n}\n\nfunction parseWorkspaceAppsManifest(parsed: any): WorkspaceAppSummary[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps: WorkspaceAppSummary[] = rawApps\n .map((entry: any): WorkspaceAppSummary | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url: workspaceAppLink(pathValue, entry.url),\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n audience:\n entry.audience === undefined\n ? DEFAULT_WORKSPACE_APP_AUDIENCE\n : normalizeWorkspaceAppAudience(entry.audience),\n publicPaths: normalizeWorkspaceAppPathList(entry.publicPaths),\n protectedPaths: normalizeWorkspaceAppPathList(entry.protectedPaths),\n status: \"ready\",\n } satisfies WorkspaceAppSummary;\n })\n .filter(\n (app: WorkspaceAppSummary | null): app is WorkspaceAppSummary =>\n app !== null,\n )\n .sort(sortWorkspaceApps);\n\n return apps.length ? apps : null;\n}\n\nfunction parseDateMs(value: string | null | undefined): number | null {\n if (!value) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pendingWorkspaceAppExpiresAt(createdAt: string): string {\n const createdMs = parseDateMs(createdAt) ?? Date.now();\n return new Date(createdMs + PENDING_WORKSPACE_APP_TTL_MS).toISOString();\n}\n\nfunction isPendingWorkspaceAppExpired(\n app: Pick<PendingWorkspaceApp, \"createdAt\" | \"expiresAt\">,\n): boolean {\n const expiresMs =\n parseDateMs(app.expiresAt) ??\n (parseDateMs(app.createdAt) ?? Date.now()) + PENDING_WORKSPACE_APP_TTL_MS;\n return expiresMs <= Date.now();\n}\n\nfunction pendingWorkspaceAppMatchesCurrentContext(\n app: Pick<PendingWorkspaceApp, \"contextId\" | \"createdAt\" | \"expiresAt\">,\n): boolean {\n if (isPendingWorkspaceAppExpired(app)) return false;\n const currentContext = pendingWorkspaceAppContext();\n if (!app.contextId) return true;\n return app.contextId === currentContext?.id;\n}\n\nfunction pendingWorkspaceAppContextRank(\n app: Pick<PendingWorkspaceApp, \"contextId\">,\n): number {\n const currentContext = pendingWorkspaceAppContext();\n if (app.contextId && app.contextId === currentContext?.id) return 2;\n if (!app.contextId) return 1;\n return 0;\n}\n\nfunction dedupePendingWorkspaceAppsForCurrentContext(\n apps: PendingWorkspaceApp[],\n): PendingWorkspaceApp[] {\n const byId = new Map<string, PendingWorkspaceApp>();\n for (const app of apps) {\n const existing = byId.get(app.id);\n if (\n !existing ||\n pendingWorkspaceAppContextRank(app) >\n pendingWorkspaceAppContextRank(existing)\n ) {\n byId.set(app.id, app);\n }\n }\n return Array.from(byId.values());\n}\n\nfunction sortWorkspaceApps(a: WorkspaceAppSummary, b: WorkspaceAppSummary) {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n if (a.status === \"pending\" && b.status !== \"pending\") return 1;\n if (a.status !== \"pending\" && b.status === \"pending\") return -1;\n return a.name.localeCompare(b.name);\n}\n\nfunction parsePendingWorkspaceApps(value: unknown): PendingWorkspaceApp[] {\n if (!Array.isArray(value)) return [];\n return value\n .map((entry): PendingWorkspaceApp | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const record = entry as Record<string, unknown>;\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\n const pathValue =\n typeof record.path === \"string\" ? record.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n const now = new Date().toISOString();\n const createdAt = cleanOptionalString(record.createdAt) ?? now;\n return {\n id,\n name:\n typeof record.name === \"string\" && record.name.trim()\n ? record.name.trim()\n : titleCase(id),\n description:\n typeof record.description === \"string\"\n ? record.description\n : \"Builder is creating this app. The workspace path becomes live after the branch is merged and deployed.\",\n path: pathValue,\n builderUrl:\n typeof record.builderUrl === \"string\" && record.builderUrl.trim()\n ? record.builderUrl.trim()\n : null,\n branchName:\n typeof record.branchName === \"string\" && record.branchName.trim()\n ? record.branchName.trim()\n : null,\n projectId:\n typeof record.projectId === \"string\" && record.projectId.trim()\n ? record.projectId.trim()\n : null,\n contextId: cleanOptionalString(record.contextId),\n contextLabel: cleanOptionalString(record.contextLabel),\n ...(record.audience === undefined\n ? {}\n : { audience: normalizeWorkspaceAppAudience(record.audience) }),\n createdAt,\n updatedAt:\n typeof record.updatedAt === \"string\" && record.updatedAt.trim()\n ? record.updatedAt.trim()\n : now,\n expiresAt:\n cleanOptionalString(record.expiresAt) ??\n pendingWorkspaceAppExpiresAt(createdAt),\n } satisfies PendingWorkspaceApp;\n })\n .filter((app): app is PendingWorkspaceApp => !!app)\n .slice(0, MAX_PENDING_APPS);\n}\n\nasync function listPendingWorkspaceApps(): Promise<PendingWorkspaceApp[]> {\n const raw = await readSettingsRecord();\n return parsePendingWorkspaceApps(raw.pendingApps);\n}\n\nfunction parseArchivedAppIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n const ids = value\n .map((entry) => (typeof entry === \"string\" ? entry.trim() : \"\"))\n .filter(Boolean);\n return Array.from(new Set(ids));\n}\n\nasync function listArchivedAppIds(): Promise<string[]> {\n const raw = await readSettingsRecord();\n return parseArchivedAppIds(raw.archivedAppIds);\n}\n\nexport async function archiveWorkspaceApp(input: {\n appId: string;\n}): Promise<{ archivedAppIds: string[] }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const current = parseArchivedAppIds(raw.archivedAppIds);\n if (!current.includes(appId)) current.push(appId);\n await putSetting(scopedSettingsKey(), { ...raw, archivedAppIds: current });\n await recordAudit({\n action: \"workspace-app.archived\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Hid workspace app from the Apps list\",\n });\n return { archivedAppIds: current };\n}\n\nexport async function unarchiveWorkspaceApp(input: {\n appId: string;\n}): Promise<{ archivedAppIds: string[] }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const current = parseArchivedAppIds(raw.archivedAppIds).filter(\n (id) => id !== appId,\n );\n await putSetting(scopedSettingsKey(), { ...raw, archivedAppIds: current });\n await recordAudit({\n action: \"workspace-app.unarchived\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Restored workspace app to the Apps list\",\n });\n return { archivedAppIds: current };\n}\n\nexport async function removePendingWorkspaceApp(input: {\n appId: string;\n}): Promise<{ removed: boolean }> {\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n const raw = await readSettingsRecord();\n const pending = parsePendingWorkspaceApps(raw.pendingApps);\n const next = pending.filter(\n (app) => app.id !== appId || !pendingWorkspaceAppMatchesCurrentContext(app),\n );\n const removed = next.length !== pending.length;\n if (!removed) return { removed: false };\n await putSetting(scopedSettingsKey(), { ...raw, pendingApps: next });\n await recordAudit({\n action: \"workspace-app.pending-removed\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: \"Removed pending Builder app from the Apps list\",\n });\n return { removed: true };\n}\n\nfunction pendingAppToSummary(app: PendingWorkspaceApp): WorkspaceAppSummary {\n return {\n id: app.id,\n name: app.name,\n description: app.description,\n path: app.path,\n url: app.builderUrl,\n isDispatch: false,\n audience: app.audience ?? DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: [],\n protectedPaths: [],\n status: \"pending\",\n statusLabel: \"Pending Builder branch\",\n builderUrl: app.builderUrl,\n branchName: app.branchName,\n createdAt: app.createdAt,\n };\n}\n\nasync function appendPendingWorkspaceApps(\n apps: WorkspaceAppSummary[],\n): Promise<WorkspaceAppSummary[]> {\n const readyIds = new Set(apps.map((app) => app.id));\n const pendingApps = dedupePendingWorkspaceAppsForCurrentContext(\n (await listPendingWorkspaceApps())\n .filter(pendingWorkspaceAppMatchesCurrentContext)\n .filter((app) => !readyIds.has(app.id)),\n ).map(pendingAppToSummary);\n return [...apps, ...pendingApps].sort(sortWorkspaceApps);\n}\n\nfunction agentCardUrlForApp(appUrl: string | null): string | null {\n if (!appUrl) return null;\n const trimmed = appUrl.replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n return new URL(`${trimmed}${AGENT_CARD_PATH}`).toString();\n } catch {\n return `${trimmed}${AGENT_CARD_PATH}`;\n }\n}\n\nfunction stringField(\n record: Record<string, unknown>,\n key: string,\n): string | null {\n const value = record[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction numberOfSkills(card: Record<string, unknown>): number | null {\n return Array.isArray(card.skills) ? card.skills.length : null;\n}\n\nasync function fetchAgentCardMetadata(\n app: WorkspaceAppSummary,\n): Promise<\n Pick<\n WorkspaceAppSummary,\n | \"agentCardUrl\"\n | \"agentCardReachable\"\n | \"a2aEndpointUrl\"\n | \"agentName\"\n | \"agentSkillsCount\"\n >\n> {\n const agentCardUrl = agentCardUrlForApp(app.url);\n if (!agentCardUrl) {\n return {\n agentCardUrl: null,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n AGENT_CARD_FETCH_TIMEOUT_MS,\n );\n\n try {\n const response = await fetch(agentCardUrl, {\n headers: { accept: \"application/json\" },\n signal: controller.signal,\n });\n if (!response.ok) {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n const parsed = await response.json().catch(() => null);\n const card =\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n if (!card) {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n }\n\n return {\n agentCardUrl,\n agentCardReachable: true,\n a2aEndpointUrl:\n stringField(card, \"url\") ?? stringField(card, \"endpointUrl\"),\n agentName: stringField(card, \"name\"),\n agentSkillsCount: numberOfSkills(card),\n };\n } catch {\n return {\n agentCardUrl,\n agentCardReachable: false,\n a2aEndpointUrl: null,\n agentName: null,\n agentSkillsCount: null,\n };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function maybeIncludeAgentCards(\n apps: WorkspaceAppSummary[],\n options: ListWorkspaceAppsOptions,\n): Promise<WorkspaceAppSummary[]> {\n if (!options.includeAgentCards) return apps;\n return Promise.all(\n apps.map(async (app) => {\n if (app.status === \"pending\") return app;\n const metadata = await fetchAgentCardMetadata(app);\n return { ...app, ...metadata };\n }),\n );\n}\n\nasync function recordPendingWorkspaceApp(input: {\n appId: string;\n projectId: string | null;\n description: string;\n sourcePrompt: string;\n branchName?: string | null;\n builderUrl?: string | null;\n}) {\n const now = new Date().toISOString();\n const context = pendingWorkspaceAppContext();\n const raw = await readSettingsRecord();\n const pendingApps = parsePendingWorkspaceApps(raw.pendingApps);\n const contextId = context?.id ?? null;\n const samePendingEntry = (app: PendingWorkspaceApp) =>\n app.id === input.appId &&\n (app.contextId === contextId || (!!contextId && !app.contextId));\n const existing = pendingApps\n .filter((app) => !isPendingWorkspaceAppExpired(app))\n .find(samePendingEntry);\n const next: PendingWorkspaceApp = {\n id: input.appId,\n name: titleCase(input.appId),\n description:\n input.description ||\n \"Builder is creating this app. The workspace path becomes live after the branch is merged and deployed.\",\n path: `/${input.appId}`,\n builderUrl: input.builderUrl?.trim() || null,\n branchName: input.branchName?.trim() || null,\n projectId: input.projectId,\n contextId: context?.id ?? null,\n contextLabel: context?.label ?? null,\n createdAt: existing?.createdAt || now,\n updatedAt: now,\n expiresAt: pendingWorkspaceAppExpiresAt(existing?.createdAt || now),\n };\n\n await putSetting(scopedSettingsKey(), {\n ...raw,\n pendingApps: [\n next,\n ...pendingApps.filter((app) => !samePendingEntry(app)),\n ].slice(0, MAX_PENDING_APPS),\n });\n\n await writeWorkspaceAppMetadataOverride({\n appId: input.appId,\n description: input.description,\n generated: true,\n sourcePrompt: input.sourcePrompt,\n updatedBy: currentOwnerEmail(),\n });\n\n await recordAudit({\n action: \"workspace-app.pending\",\n targetType: \"workspace-app\",\n targetId: input.appId,\n summary: \"Started Builder branch for workspace app creation\",\n metadata: {\n builderBranchUrlConfigured: !!next.builderUrl,\n branchName: next.branchName,\n projectIdConfigured: !!next.projectId,\n contextLabel: next.contextLabel,\n },\n });\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppSummary[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nasync function readWorkspaceAppsFromGateway(): Promise<\n WorkspaceAppSummary[] | null\n> {\n const base = process.env.WORKSPACE_GATEWAY_URL;\n if (!base) return null;\n\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n WORKSPACE_APPS_GATEWAY_TIMEOUT_MS,\n );\n\n try {\n const response = await fetch(\n new URL(WORKSPACE_APPS_GATEWAY_PATH, `${base.replace(/\\/$/, \"\")}/`),\n {\n headers: { accept: \"application/json\" },\n signal: controller.signal,\n },\n );\n if (!response.ok) return null;\n return parseWorkspaceAppsManifest(await response.json().catch(() => null));\n } catch {\n return null;\n } finally {\n clearTimeout(timeout);\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile(): WorkspaceAppSummary[] | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(\n workspaceRoot: string,\n): WorkspaceAppSummary[] | null {\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\"))\n .map((entry): WorkspaceAppSummary | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n const routeAccess = workspaceAppRouteAccessFromPackageJson(pkg);\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n url: workspaceAppUrl(`/${entry.name}`),\n isDispatch: entry.name === \"dispatch\",\n audience:\n workspaceAppAudienceFromPackageJson(pkg) ??\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: routeAccess.publicPaths,\n protectedPaths: routeAccess.protectedPaths,\n status: \"ready\",\n } satisfies WorkspaceAppSummary;\n })\n .filter((app): app is WorkspaceAppSummary => !!app)\n .sort(sortWorkspaceApps);\n\n return apps.length ? apps : null;\n}\n\nexport function getEnvBuilderProjectId(): string | null {\n return (\n process.env.DISPATCH_BUILDER_PROJECT_ID ||\n process.env.BUILDER_BRANCH_PROJECT_ID ||\n process.env.BUILDER_PROJECT_ID ||\n null\n );\n}\n\n/**\n * Read the workspace's identity from the workspace root's package.json. Used to\n * surface \"Workspace: <name>\" in the Dispatch UI so first-time users can see\n * the container their apps live inside (rather than only seeing app names like\n * \"starter\" / \"dispatch\" with no parent context).\n */\nexport function getWorkspaceInfo(): WorkspaceInfo {\n const rootPath = findWorkspaceRoot();\n if (!rootPath) {\n return { name: null, displayName: null, rootPath: null, appCount: 0 };\n }\n const pkg = readJson(path.join(rootPath, \"package.json\"));\n const rawName = typeof pkg?.name === \"string\" ? pkg.name.trim() : \"\";\n // Strip a leading \"@scope/\" if the workspace root happens to be scoped.\n const name = rawName.replace(/^@[^/]+\\//, \"\") || null;\n // Honor an explicit `displayName` in the workspace package.json before\n // falling back to a title-cased version of the slug. Users naming a\n // workspace \"On-Call Todo Manager\" via `displayName` should see that\n // exact label rather than `On Call Todo Manager`.\n const rawDisplay =\n typeof pkg?.displayName === \"string\" ? pkg.displayName.trim() : \"\";\n const displayName = rawDisplay || (name ? titleCase(name) : null);\n let appCount = 0;\n const appsDir = path.join(rootPath, \"apps\");\n if (fs.existsSync(appsDir)) {\n try {\n appCount = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory()).length;\n } catch {\n appCount = 0;\n }\n }\n return {\n name,\n displayName,\n rootPath,\n appCount,\n };\n}\n\nasync function applyArchivedAndPending(\n apps: WorkspaceAppSummary[],\n options: ListWorkspaceAppsOptions,\n): Promise<WorkspaceAppSummary[]> {\n const [withPending, archivedIds, metadataSettings] = await Promise.all([\n appendPendingWorkspaceApps(apps),\n listArchivedAppIds(),\n readWorkspaceAppMetadataSettings(),\n ]);\n const archivedSet = new Set(archivedIds);\n const annotated = withPending.map((app) => {\n const withMetadata = applyWorkspaceAppMetadataOverride(\n app,\n metadataSettings,\n );\n return archivedSet.has(app.id)\n ? { ...withMetadata, archived: true }\n : withMetadata;\n });\n return options.includeArchived\n ? filterAppsByAudience(annotated, options.audience)\n : filterAppsByAudience(\n annotated.filter((app) => !app.archived),\n options.audience,\n );\n}\n\nfunction filterAppsByAudience(\n apps: WorkspaceAppSummary[],\n audience: ListWorkspaceAppsOptions[\"audience\"],\n): WorkspaceAppSummary[] {\n if (!audience || audience === \"all\") return apps;\n return apps.filter(\n (app) =>\n (app.audience ?? DEFAULT_WORKSPACE_APP_AUDIENCE) ===\n normalizeWorkspaceAppAudience(audience),\n );\n}\n\nexport async function updateWorkspaceAppMetadata(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n}): Promise<WorkspaceAppSummary> {\n await assertCanManageAppCreationSettings();\n const appId = input.appId.trim();\n assertValidWorkspaceAppId(appId);\n\n const apps = await listWorkspaceApps({\n includeAgentCards: false,\n includeArchived: true,\n });\n const app = apps.find((candidate) => candidate.id === appId);\n if (!app) throw new Error(`Workspace app \"${appId}\" was not found.`);\n\n // Treat undefined/null as \"field omitted, leave existing value alone\"; an\n // explicit empty string clears the override (the app reverts to its\n // built-in name / no description). Without this, a partial update that\n // only touches one field silently wipes the other.\n const name = input.name == null ? app.name : input.name.trim();\n const description =\n input.description == null\n ? (app.description ?? undefined)\n : input.description.trim();\n await writeWorkspaceAppMetadataOverride({\n appId,\n name,\n description,\n generated: false,\n updatedBy: currentOwnerEmail(),\n });\n\n await recordAudit({\n action: \"workspace-app.metadata-updated\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: `Updated workspace app details for ${name}`,\n metadata: {\n name,\n descriptionConfigured: !!description,\n },\n });\n\n const updated = (\n await listWorkspaceApps({\n includeAgentCards: false,\n includeArchived: true,\n })\n ).find((candidate) => candidate.id === appId);\n return updated ?? { ...app, name, description };\n}\n\nexport async function listWorkspaceApps(\n options: ListWorkspaceAppsOptions = {},\n): Promise<WorkspaceAppSummary[]> {\n const gatewayApps = await readWorkspaceAppsFromGateway();\n if (gatewayApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(gatewayApps, options),\n options,\n );\n }\n\n const workspaceRoot = findWorkspaceRoot();\n const localFilesystemApps =\n workspaceRoot && isLocalAppCreationRuntime()\n ? readWorkspaceAppsFromFilesystem(workspaceRoot)\n : null;\n if (localFilesystemApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(localFilesystemApps, options),\n options,\n );\n }\n\n const manifestApps =\n readWorkspaceAppsFromEnv() ?? readWorkspaceAppsFromManifestFile();\n if (manifestApps) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(manifestApps, options),\n options,\n );\n }\n\n if (!workspaceRoot) {\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(\n [\n {\n id: \"dispatch\",\n name: \"Dispatch\",\n description: \"Workspace control plane\",\n path: \"/dispatch\",\n url: workspaceAppUrl(\"/dispatch\"),\n isDispatch: true,\n audience: DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: [],\n protectedPaths: [],\n status: \"ready\",\n },\n ],\n options,\n ),\n options,\n );\n }\n\n const apps = readWorkspaceAppsFromFilesystem(workspaceRoot) ?? [];\n return maybeIncludeAgentCards(\n await applyArchivedAndPending(apps, options),\n options,\n );\n}\n\n/**\n * First-party templates the user can scaffold into this workspace via the\n * Apps page tiles. Inlined here (rather than importing from\n * `@agent-native/shared-app-config`) because the published `@agent-native/dispatch`\n * package has no `workspace:*` runtime dependencies. Keep in sync with\n * `packages/core/src/cli/templates-meta.ts`.\n */\nconst ADDABLE_TEMPLATES: AvailableWorkspaceTemplate[] = [\n {\n name: \"mail\",\n label: \"Mail\",\n hint: \"Email client with keyboard shortcuts and AI triage\",\n icon: \"Mail\",\n color: \"#3B82F6\",\n colorRgb: \"59 130 246\",\n core: true,\n },\n {\n name: \"calendar\",\n label: \"Calendar\",\n hint: \"Manage events, sync, and public booking\",\n icon: \"CalendarMonth\",\n color: \"#8B5CF6\",\n colorRgb: \"139 92 246\",\n core: true,\n },\n {\n name: \"content\",\n label: \"Content\",\n hint: \"Write and organize with agent assistance\",\n icon: \"FileText\",\n color: \"#10B981\",\n colorRgb: \"16 185 129\",\n core: true,\n },\n {\n name: \"slides\",\n label: \"Slides\",\n hint: \"Generate and edit React presentations\",\n icon: \"Presentation\",\n color: \"#EC4899\",\n colorRgb: \"236 72 153\",\n core: true,\n },\n {\n name: \"clips\",\n label: \"Clips\",\n hint: \"Screen recording, meeting notes, and voice dictation\",\n icon: \"ScreenShare\",\n color: \"#625DF5\",\n colorRgb: \"98 93 245\",\n core: true,\n },\n {\n name: \"brain\",\n label: \"Brain\",\n hint: \"Cited company knowledge from Slack, meetings, transcripts, and decisions\",\n icon: \"Brain\",\n color: \"#8B5CF6\",\n colorRgb: \"139 92 246\",\n core: true,\n },\n {\n name: \"assets\",\n label: \"Assets\",\n hint: \"Upload, organize, search, and generate on-brand images and videos\",\n icon: \"Photo\",\n color: \"#0F766E\",\n colorRgb: \"15 118 110\",\n core: true,\n },\n {\n name: \"analytics\",\n label: \"Analytics\",\n hint: \"Connect data sources, prompt for charts\",\n icon: \"ChartBar\",\n color: \"#F59E0B\",\n colorRgb: \"245 158 11\",\n core: true,\n },\n {\n name: \"forms\",\n label: \"Forms\",\n hint: \"Create, edit, and manage forms\",\n icon: \"ClipboardList\",\n color: \"#06B6D4\",\n colorRgb: \"6 182 212\",\n core: true,\n },\n {\n name: \"contracts\",\n label: \"Contracts\",\n hint: \"Review assumptions, feedback, and proof for coding-agent work\",\n icon: \"Contract\",\n color: \"#4F46E5\",\n colorRgb: \"79 70 229\",\n core: false,\n },\n {\n name: \"design\",\n label: \"Design\",\n hint: \"Create and edit visual designs with agent assistance\",\n icon: \"Brush\",\n color: \"#F472B6\",\n colorRgb: \"244 114 182\",\n core: true,\n },\n {\n name: \"videos\",\n label: \"Video\",\n hint: \"Video editing with Remotion\",\n icon: \"Video\",\n color: \"#EF4444\",\n colorRgb: \"239 68 68\",\n core: false,\n },\n];\n\nexport async function listAvailableWorkspaceTemplates(): Promise<\n AvailableWorkspaceTemplate[]\n> {\n if (!isLocalAppCreationRuntime()) return [];\n\n const installed = new Set(\n (await listWorkspaceApps({ includeArchived: true })).map((app) => app.id),\n );\n return ADDABLE_TEMPLATES.filter((tpl) => !installed.has(tpl.name));\n}\n\nconst SCAFFOLD_TIMEOUT_MS = 90_000;\n\nexport async function scaffoldWorkspaceAppFromTemplate(input: {\n template: string;\n appId?: string | null;\n}): Promise<{ appId: string; template: string; output: string }> {\n if (!isLocalAppCreationRuntime()) {\n throw new Error(\n \"Scaffolding from Dispatch is only available in local development. \" +\n \"Use the Builder branch flow on a deployed workspace.\",\n );\n }\n const template = input.template.trim();\n if (!template) throw new Error(\"template is required\");\n if (!ADDABLE_TEMPLATES.some((tpl) => tpl.name === template)) {\n throw new Error(`Unknown template \"${template}\".`);\n }\n\n const appId = (input.appId?.trim() || template).toLowerCase();\n assertValidWorkspaceAppId(appId);\n\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) {\n throw new Error(\"No agent-native workspace detected for scaffolding.\");\n }\n const appDir = path.join(workspaceRoot, \"apps\", appId);\n if (fs.existsSync(appDir)) {\n throw new Error(`apps/${appId} already exists.`);\n }\n\n const output = await runScaffoldCli({\n cwd: workspaceRoot,\n args: [\"add-app\", appId, \"--template\", template],\n });\n\n await recordAudit({\n action: \"workspace-app.scaffolded\",\n targetType: \"workspace-app\",\n targetId: appId,\n summary: `Scaffolded apps/${appId} from ${template}`,\n metadata: { template },\n });\n\n return { appId, template, output };\n}\n\nfunction runScaffoldCli(input: {\n cwd: string;\n args: string[];\n}): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(\"pnpm\", [\"exec\", \"agent-native\", ...input.args], {\n cwd: input.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (chunk) => {\n stdout += String(chunk);\n });\n child.stderr?.on(\"data\", (chunk) => {\n stderr += String(chunk);\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n reject(\n new Error(\n `Scaffold timed out after ${Math.round(SCAFFOLD_TIMEOUT_MS / 1000)}s`,\n ),\n );\n }, SCAFFOLD_TIMEOUT_MS);\n timer.unref();\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n reject(err);\n });\n child.on(\"exit\", (code) => {\n clearTimeout(timer);\n if (code === 0) {\n resolve([stdout, stderr].filter(Boolean).join(\"\\n\").trim());\n return;\n }\n const detail = (stderr || stdout || \"\").trim() || `exit code ${code}`;\n reject(new Error(`Scaffold failed: ${detail}`));\n });\n });\n}\n\nexport async function getAppCreationSettings(): Promise<AppCreationSettings> {\n const envBuilderProjectId = getEnvBuilderProjectId();\n const resolvedBuilderProjectId = await resolveBuilderBranchProjectId();\n const raw = await readSettingsRecord();\n const savedBuilderProjectId =\n typeof raw?.builderProjectId === \"string\" && raw.builderProjectId.trim()\n ? raw.builderProjectId.trim()\n : null;\n const builderProjectId = envBuilderProjectId || savedBuilderProjectId;\n const enableBuilder =\n process.env.ENABLE_BUILDER === \"true\" || process.env.ENABLE_BUILDER === \"1\";\n const effectiveBuilderProjectId =\n builderProjectId ||\n resolvedBuilderProjectId ||\n (enableBuilder ? getBuilderBranchProjectId() : null);\n\n return {\n builderProjectId: effectiveBuilderProjectId,\n builderProjectIdSource: envBuilderProjectId\n ? \"env\"\n : savedBuilderProjectId\n ? \"dispatch\"\n : effectiveBuilderProjectId\n ? \"default\"\n : \"unset\",\n envBuilderProjectId,\n savedBuilderProjectId,\n builderBranchingEnabled: !!effectiveBuilderProjectId,\n };\n}\n\nexport async function setAppCreationSettings(input: {\n builderProjectId?: string | null;\n}): Promise<AppCreationSettings> {\n await assertCanManageAppCreationSettings();\n const builderProjectId = input.builderProjectId?.trim() || null;\n const raw = await readSettingsRecord();\n await putSetting(scopedSettingsKey(), { ...raw, builderProjectId });\n await recordAudit({\n action: \"settings.updated\",\n targetType: \"dispatch-app-creation-settings\",\n targetId: SETTINGS_KEY,\n summary: builderProjectId\n ? \"Updated default Builder project for app creation\"\n : \"Cleared default Builder project for app creation\",\n metadata: { builderProjectIdConfigured: !!builderProjectId },\n });\n return getAppCreationSettings();\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/^[^a-z]+/, \"\")\n .slice(0, 64);\n}\n\nfunction isLocalAppCreationRuntime(): boolean {\n if (process.env.NODE_ENV === \"production\") return false;\n if (\n process.env.NETLIFY ||\n process.env.VERCEL ||\n process.env.CF_PAGES ||\n process.env.DEPLOY_URL ||\n process.env.URL ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME\n ) {\n return false;\n }\n return true;\n}\n\nfunction isSyntheticIntegrationOwner(ownerEmail: string): boolean {\n return (\n ownerEmail.startsWith(\"integration@\") ||\n ownerEmail.endsWith(\"@integration.local\")\n );\n}\n\nasync function requestOwnerRole(): Promise<string | null> {\n const orgId = currentOrgId();\n const ownerEmail = currentOwnerEmail();\n if (!orgId) return null;\n try {\n const { rows } = await getDbExec().execute({\n sql: `SELECT role FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [orgId, ownerEmail.toLowerCase()],\n });\n const role = (rows[0] as any)?.role;\n return typeof role === \"string\" ? role : null;\n } catch {\n return null;\n }\n}\n\nasync function assertCanManageAppCreationSettings(): Promise<void> {\n const orgId = currentOrgId();\n if (!orgId) return;\n const role = await requestOwnerRole();\n if (role !== \"owner\" && role !== \"admin\") {\n throw new Error(\n \"Only organization owners and admins can update app creation settings.\",\n );\n }\n}\n\nasync function isCurrentIntegrationExplicitlyLinked(): Promise<boolean> {\n const incoming = getRequestContext()?.integration?.incoming;\n if (!incoming) return true;\n const externalUserId = identityKeyForIncoming(incoming);\n const linkedOwner = await resolveLinkedOwner(\n incoming.platform,\n externalUserId,\n {\n allowAnyOrgFallback: true,\n },\n ).catch(() => null);\n return linkedOwner === currentOwnerEmail();\n}\n\nasync function defaultOwnerAppCreationAllowed(): Promise<boolean> {\n const defaultOwner = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (!defaultOwner || defaultOwner !== currentOwnerEmail()) return false;\n if (await isCurrentIntegrationExplicitlyLinked()) return true;\n return (\n process.env.DISPATCH_ALLOW_DEFAULT_OWNER_APP_CREATION === \"true\" ||\n process.env.DISPATCH_ALLOW_DEFAULT_OWNER_APP_CREATION === \"1\" ||\n process.env.ENABLE_BUILDER === \"true\" ||\n process.env.ENABLE_BUILDER === \"1\"\n );\n}\n\nfunction normalizeBuilderRunString(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new Error(`Builder app creation returned a blank ${fieldName}`);\n }\n const trimmed = value.trim();\n if (/[\u0000-\u001f]/.test(trimmed)) {\n throw new Error(`Builder app creation returned a malformed ${fieldName}`);\n }\n return trimmed;\n}\n\nfunction normalizeBuilderRunUrl(value: unknown): string {\n const urlString = normalizeBuilderRunString(value, \"url\");\n let parsed: URL;\n try {\n parsed = new URL(urlString);\n } catch {\n throw new Error(\"Builder app creation returned a malformed url\");\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\"Builder app creation returned a malformed url\");\n }\n if (\n parsed.hostname !== \"builder.io\" &&\n !parsed.hostname.endsWith(\".builder.io\")\n ) {\n throw new Error(\"Builder app creation returned a non-Builder url\");\n }\n return parsed.toString();\n}\n\nfunction normalizeBuilderRunResult(result: unknown): {\n branchName: string;\n url: string;\n status: string;\n} {\n const record =\n result && typeof result === \"object\" && !Array.isArray(result)\n ? (result as Record<string, unknown>)\n : {};\n return {\n branchName: normalizeBuilderRunString(record.branchName, \"branchName\"),\n url: normalizeBuilderRunUrl(record.url),\n status:\n typeof record.status === \"string\" && record.status.trim()\n ? record.status.trim()\n : \"processing\",\n };\n}\n\nasync function remoteAppCreationAuthorization(): Promise<\n { ok: true } | { ok: false; message: string }\n> {\n const ownerEmail = currentOwnerEmail();\n const isIntegrationCaller = isIntegrationCallerRequest();\n const defaultOwner = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (isIntegrationCaller && defaultOwner && defaultOwner === ownerEmail) {\n if (await defaultOwnerAppCreationAllowed()) return { ok: true };\n return {\n ok: false,\n message:\n \"Messaging-triggered app creation is using the deployment default Dispatch owner. \" +\n \"Link the messaging identity to a Dispatch user with /link, start the app from Dispatch while signed in, or explicitly set ENABLE_BUILDER=true for this deployment.\",\n };\n }\n if (!isSyntheticIntegrationOwner(ownerEmail)) return { ok: true };\n\n const source = isIntegrationCaller\n ? \"Messaging-triggered\"\n : \"Synthetic integration\";\n return {\n ok: false,\n message:\n `${source} app creation needs a trusted Dispatch owner before Builder can start a branch. ` +\n \"Link the messaging identity to a Dispatch user with /link, start the app from Dispatch while signed in, or explicitly set ENABLE_BUILDER=true for this deployment.\",\n };\n}\n\nfunction buildWorkspaceAppPrompt(input: {\n prompt: string;\n appId?: string | null;\n description?: string | null;\n template?: string | null;\n selectedKeys?: string[];\n selectedResources?: WorkspaceResourceOption[];\n}): { appId: string; prompt: string } {\n const appId =\n slugify(input.appId || \"\") ||\n slugify(\n input.prompt.replace(/\\b(build|create|make|an?|the|app|tool)\\b/gi, \" \"),\n ) ||\n \"new-app\";\n const appDescription =\n input.description?.trim() ||\n generateWorkspaceAppDescription(input.prompt, appId);\n const selectedKeys = input.selectedKeys || [];\n const selectedResources = input.selectedResources || [];\n const resourceList = selectedResources.length\n ? selectedResources\n .map(\n (resource) =>\n `- ${resource.name} (${resource.kind}, ${resource.path})`,\n )\n .join(\"\\n\")\n : \"none\";\n return {\n appId,\n prompt: [\n \"Create a new agent-native app in this workspace.\",\n \"\",\n `App name: ${appId}`,\n `App description: ${appDescription}`,\n `Template to start from: ${input.template || \"starter\"}`,\n `User prompt: ${input.prompt.trim()}`,\n \"If the user mentions a product or company such as Granola, Loom, Superhuman, Linear, or Notion, treat it as product inspiration unless they explicitly ask to connect to that service. Do not invent or require third-party API keys like GRANOLA_API_KEY just because a product is named.\",\n selectedKeys.length\n ? `Dispatch vault keys selected for this app: ${selectedKeys.join(\", \")}`\n : \"Dispatch vault keys selected for this app: none\",\n `Dispatch workspace resources selected for this app:\\n${resourceList}`,\n `Dispatch workspace resources with scope=all are global. After the app exists, sync workspace resources to appId \"${appId}\" so global skills, guardrail instructions, and reference resources reach the new app even when no per-app resources were selected.`,\n \"\",\n `Use the workspace app layout: create it under apps/${appId}, mount it at /${appId}, keep it on the shared workspace database/hosting model, and avoid table-name collisions by namespacing any new domain tables to the app.`,\n `Important routing rule: from outside the app, link to /${appId}; inside apps/${appId}, React Router routes are app-local. Use <Link to=\"/review\"> and navigate(\"/review\"), not \"/${appId}/review\"; APP_BASE_PATH supplies the mounted prefix, and hardcoding it causes doubled URLs like /${appId}/${appId}/review.`,\n \"Existing first-party apps are neighbors, not implementation details for this app. If the user prompt mentions Mail, Calendar, Analytics, Dispatch, or other templates, treat them as existing hosted/connected apps that this app can link to or call through A2A/default connected agents. For example, Mail, Calendar, and Analytics already exist at https://mail.agent-native.com, https://calendar.agent-native.com, and https://analytics.agent-native.com.\",\n `Do not clone first-party templates, create wrapper apps, or scaffold child apps/routes for Mail, Calendar, Analytics, etc. inside apps/${appId} just so this app can access them. If the request is a cross-app dashboard or overview, build only the new dashboard/overview app and delegate to the existing apps for domain work.`,\n \"Only create another first-party app copy when the user explicitly asks for a customized fork/copy of that app; otherwise keep using the hosted/shared app so improvements to the base template keep flowing to users.\",\n selectedKeys.length\n ? `Dispatch will create pending vault requests for the selected keys for appId \"${appId}\" after this app creation request is accepted. Do not grant or sync vault keys directly from the app-creation branch.`\n : \"Do not grant or request any Dispatch vault keys unless the user asks later.\",\n selectedResources.length\n ? `Dispatch will create workspace resource grants for the selected resources for appId \"${appId}\". After the app exists, sync workspace resources so the app receives both global and selected shared resources.`\n : \"Do not grant any selected-only Dispatch workspace resources unless the user asks later.\",\n \"\",\n \"Agent-native rules (these are the framework's contract — not optional):\",\n `- Persist ALL data in SQL via Drizzle. Add tables to apps/${appId}/server/db/schema.ts and migrations to apps/${appId}/server/plugins/db.ts. NEVER use localStorage, sessionStorage, IndexedDB, or in-memory state for anything the user expects to persist — agent and UI must read the same source of truth.`,\n `- Define every create/read/update/delete as an action in apps/${appId}/actions/ using defineAction. The agent calls these as tools and the frontend calls them via useActionQuery / useActionMutation. If you must raw-fetch framework action endpoints, use agentNativePath(\"/_agent-native/actions/<name>\") so mounted apps call the right URL. Don't add /api/* routes for CRUD.`,\n \"- Build the UI from shadcn/ui components in app/components/ui/ (Button, Input, Dialog, Popover, Card, etc.) and Tailwind utilities. Don't author bespoke CSS classes in global.css unless you genuinely need a primitive that shadcn doesn't ship.\",\n \"- Use Tabler Icons (@tabler/icons-react) for every icon. Never use emojis as icons.\",\n `- Expose what the user is looking at via application_state (navigation.view, selection, etc.) so the agent has live context. Mirror the patterns in templates/mail or templates/slides.`,\n \"- Optimistic UI for every mutation: update the React Query cache immediately, navigate immediately, run the mutation in the background, roll back on error. Don't await a server round-trip before re-rendering.\",\n \"\",\n \"Branch readiness requirements before handing off:\",\n \"- The CLI auto-fills package.json name and displayName from the app id; only edit the description / scripts / dependencies if the app actually needs more than the template provides.\",\n `- Save a concise, human-readable app description in apps/${appId}/package.json \"description\" so Dispatch, A2A discovery, and connected agents can describe what this app does. Use the description above or improve it based on the prompt.`,\n \"- Do not add or update workspace-apps.json or .agent-native/workspace-apps.json unless the app needs an explicit external URL override; the root deploy generates the workspace app registry from apps/* and deploy metadata.\",\n \"- Update pnpm-lock.yaml when adding or changing dependencies so Netlify can install the branch reliably.\",\n \"- Update the app manifest/package/deploy metadata needed by the existing workspace deployment model; do not leave the branch relying only on uncommitted local state.\",\n \"- Verify the app's agent card/A2A metadata is ready so Dispatch can discover and delegate to the app after deployment. Every sibling workspace app should be usable over A2A by default through call-agent.\",\n \"- Give the app agent context that sibling workspace apps are available over A2A with names and descriptions from the workspace app registry; do not hardcode a stale app list.\",\n \"- Include a final verification note covering the registry entry, manifest/deploy metadata, relative same-origin routing, and agent-card readiness.\",\n `When it is ready, start or update the workspace dev server and navigate the user to /${appId}.`,\n ].join(\"\\n\"),\n };\n}\n\nasync function requestSelectedVaultKeys(input: {\n appId: string;\n selectedKeys: string[];\n}) {\n if (input.selectedKeys.length === 0) return;\n await Promise.allSettled(\n input.selectedKeys.map((credentialKey) =>\n Promise.resolve().then(() =>\n createRequest({\n appId: input.appId,\n credentialKey,\n reason: `Requested during workspace app creation for ${input.appId}.`,\n }),\n ),\n ),\n );\n}\n\nasync function selectedWorkspaceResourcesForIds(\n resourceIds: string[] | undefined,\n): Promise<WorkspaceResourceOption[]> {\n if (!resourceIds?.length) return [];\n const requested = new Set(resourceIds);\n const resources = await listWorkspaceResourceOptions();\n return resources.filter((resource) => requested.has(resource.id));\n}\n\nasync function grantSelectedWorkspaceResources(input: {\n appId: string;\n resourceIds: string[];\n}) {\n if (input.resourceIds.length === 0) return;\n await grantWorkspaceResourcesToApp(input);\n}\n\nexport async function startWorkspaceAppCreation(input: {\n prompt: string;\n appId?: string | null;\n description?: string | null;\n template?: string | null;\n secretIds?: string[];\n resourceIds?: string[];\n}) {\n const initial = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\n description: input.description,\n template: input.template,\n });\n assertValidWorkspaceAppId(initial.appId);\n const isLocal = isLocalAppCreationRuntime();\n\n if (!isLocal) {\n const authorization = await remoteAppCreationAuthorization();\n if (authorization.ok === false) {\n return {\n mode: \"builder-unavailable\",\n appId: initial.appId,\n message: authorization.message,\n };\n }\n }\n\n const selectedKeys = input.secretIds?.length\n ? (await listSecrets())\n .filter((secret) => input.secretIds?.includes(secret.id))\n .map((secret) => secret.credentialKey)\n : [];\n const selectedResources = await selectedWorkspaceResourcesForIds(\n input.resourceIds,\n );\n const built = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\n description: input.description,\n template: input.template,\n selectedKeys,\n selectedResources,\n });\n const prompt = built.prompt;\n const appDescription =\n input.description?.trim() ||\n generateWorkspaceAppDescription(input.prompt, built.appId);\n\n if (isLocal) {\n await requestSelectedVaultKeys({\n appId: built.appId,\n selectedKeys,\n });\n await grantSelectedWorkspaceResources({\n appId: built.appId,\n resourceIds: selectedResources.map((resource) => resource.id),\n });\n return {\n mode: \"local-agent\",\n appId: built.appId,\n prompt,\n message:\n \"Use the local code agent to create this app in the workspace, then open it from /dispatch/apps.\",\n };\n }\n\n const settings = await getAppCreationSettings();\n\n if (!settings.builderProjectId) {\n return {\n mode: \"coming-soon\",\n appId: built.appId,\n message:\n \"This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.\",\n };\n }\n\n let result: {\n branchName: string;\n url: string;\n status: string;\n };\n try {\n const builderCreds = await resolveBuilderCredentials().catch(() => null);\n const builderUserId = builderCreds?.userId || undefined;\n result = normalizeBuilderRunResult(\n await runBuilderAgent({\n prompt,\n projectId: settings.builderProjectId,\n ...(builderUserId\n ? { userId: builderUserId }\n : { userEmail: currentOwnerEmail() }),\n }),\n );\n } catch (err) {\n const detail =\n err instanceof Error && err.message\n ? err.message\n : \"Builder could not start the app branch\";\n return {\n mode: \"builder-unavailable\",\n appId: built.appId,\n projectId: settings.builderProjectId,\n message:\n `Builder app creation is configured for project ${settings.builderProjectId}, ` +\n `but it could not start yet: ${detail}. Connect Builder for this user, ` +\n `link the messaging identity to that user, or configure deployment-managed Builder credentials for this workspace.`,\n };\n }\n\n await recordPendingWorkspaceApp({\n appId: built.appId,\n projectId: settings.builderProjectId,\n description: appDescription,\n sourcePrompt: input.prompt,\n branchName: result.branchName,\n builderUrl: result.url,\n });\n\n await requestSelectedVaultKeys({\n appId: built.appId,\n selectedKeys,\n });\n await grantSelectedWorkspaceResources({\n appId: built.appId,\n resourceIds: selectedResources.map((resource) => resource.id),\n });\n\n return {\n mode: \"builder\",\n appId: built.appId,\n path: `/${built.appId}`,\n projectId: settings.builderProjectId,\n branchName: result.branchName,\n url: result.url,\n workspaceUrl: workspaceAppUrl(`/${built.appId}`),\n status: result.status,\n message:\n `Builder started a branch for /${built.appId}. Use the Builder branch URL to track creation now. ` +\n `The workspace path will be live after that branch is merged and the workspace deploy finishes, so it may 404 until then.`,\n };\n}\n"]}
|
|
@@ -21,7 +21,7 @@ When a user asks for something:
|
|
|
21
21
|
- If the user asks to create, build, make, scaffold, or generate an "agent" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.
|
|
22
22
|
- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized fork/copy.
|
|
23
23
|
- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind.
|
|
24
|
-
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode "local-agent", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode "coming-soon" or "builder-unavailable",
|
|
24
|
+
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode "local-agent", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode "coming-soon", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to Builder org/beta settings. If it returns mode "builder-unavailable", report the action's message exactly enough to preserve the missing identity/credential detail.
|
|
25
25
|
- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.
|
|
26
26
|
- Keep responses concise and operational — messaging platforms have character limits.
|
|
27
27
|
- Use markdown sparingly (bold and lists are fine, avoid complex formatting).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EACL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,kCAAkC,GAAG;;;;;;;;;;;;;;;;;;;;;;;4FAuBiD,CAAC;AAE7F;;;;GAIG;AACH,MAAM,0BAA0B,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;IACzD,MAAM,EAAE,YAAY,GAAG,EAAE,EAAE,GAAG,iBAAiB,EAAE,CAAC;IAClD,MAAM,cAAc,GAAG,YAAY,CAAC,YAAY,CAAC;IACjD,MAAM,YAAY,GAChB,OAAO,cAAc,KAAK,QAAQ;QAChC,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,OAAO,cAAc,KAAK,UAAU;YACpC,CAAC,CAAC,cAAc,CAAC,kCAAkC,CAAC;YACpD,CAAC,CAAC,kCAAkC,CAAC;IAE3C,MAAM,MAAM,GAAG,wBAAwB,CAAC;QACtC,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,eAAe;QACxB,YAAY,EAAE,oBAAoB;QAClC,aAAa,EAAE,qBAAqB;QACpC,YAAY;QACZ,wDAAwD;QACxD,yEAAyE;QACzE,+DAA+D;QAC/D,6EAA6E;KAC9E,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC,CAAC;AAEF,eAAe,0BAA0B,CAAC","sourcesContent":["import { createIntegrationsPlugin } from \"@agent-native/core/server\";\nimport {\n beforeDispatchProcess,\n resolveDispatchOwner,\n} from \"../lib/dispatch-integrations.js\";\nimport { getDispatchConfig } from \"../index.js\";\nimport { dispatchActions } from \"../../actions/index.js\";\n\nconst DISPATCH_INTEGRATION_SYSTEM_PROMPT = `You are the central dispatch for this workspace, responding via a messaging platform integration (Slack, Telegram, email, etc.).\n\nDefault posture:\n- Treat Slack, Telegram, and email as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A (call-agent) when another app owns the job. Apps you can delegate to include slides (decks/presentations), analytics (data/dashboards), content (docs/articles), videos (Remotion compositions), forms (form builder), clips (screen recordings), design (visual designs), and assets (brand libraries plus generated images/videos).\n- Use the available-apps prompt context first, then list-connected-agents when you need fresh details, to see what agents are available before assuming a request must be handled locally.\n- When asked whether workspace apps expose agent cards or A2A endpoints, call list-workspace-apps with includeAgentCards=true. Without that probe, missing agent-card fields mean unchecked, not unavailable.\n- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.\n- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Reply in the originating thread unless the user explicitly asks you to send to a saved destination.\n\nWhen a user asks for something:\n- If it belongs to analytics, content, slides, videos, assets, etc., delegate via call-agent — do not re-implement the domain logic in dispatch.\n- After call-agent returns an answer, RELAY IT DIRECTLY to the user with at most a one-line preface — do not rephrase, summarize, or add commentary. The downstream agent already crafted the answer; your job is delivery, not editing. This minimizes round-trips and keeps the user-visible reply fast.\n- Exception: if the downstream agent reports a missing model/provider credential, do not name exact env vars, Vault keys, tokens, or secrets. Say the target app needs an LLM connection and recommend connecting Builder/managed LLM for that app; keep bring-your-own provider keys as a secondary option only if the user asks.\n- If the user asks to create, build, make, scaffold, or generate an \"agent\" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.\n- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized fork/copy.\n- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.\n- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode \"builder\", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode \"local-agent\", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode \"coming-soon\" or \"builder-unavailable\",
|
|
1
|
+
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EACL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,kCAAkC,GAAG;;;;;;;;;;;;;;;;;;;;;;;4FAuBiD,CAAC;AAE7F;;;;GAIG;AACH,MAAM,0BAA0B,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;IACzD,MAAM,EAAE,YAAY,GAAG,EAAE,EAAE,GAAG,iBAAiB,EAAE,CAAC;IAClD,MAAM,cAAc,GAAG,YAAY,CAAC,YAAY,CAAC;IACjD,MAAM,YAAY,GAChB,OAAO,cAAc,KAAK,QAAQ;QAChC,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,OAAO,cAAc,KAAK,UAAU;YACpC,CAAC,CAAC,cAAc,CAAC,kCAAkC,CAAC;YACpD,CAAC,CAAC,kCAAkC,CAAC;IAE3C,MAAM,MAAM,GAAG,wBAAwB,CAAC;QACtC,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,eAAe;QACxB,YAAY,EAAE,oBAAoB;QAClC,aAAa,EAAE,qBAAqB;QACpC,YAAY;QACZ,wDAAwD;QACxD,yEAAyE;QACzE,+DAA+D;QAC/D,6EAA6E;KAC9E,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC,CAAC;AAEF,eAAe,0BAA0B,CAAC","sourcesContent":["import { createIntegrationsPlugin } from \"@agent-native/core/server\";\nimport {\n beforeDispatchProcess,\n resolveDispatchOwner,\n} from \"../lib/dispatch-integrations.js\";\nimport { getDispatchConfig } from \"../index.js\";\nimport { dispatchActions } from \"../../actions/index.js\";\n\nconst DISPATCH_INTEGRATION_SYSTEM_PROMPT = `You are the central dispatch for this workspace, responding via a messaging platform integration (Slack, Telegram, email, etc.).\n\nDefault posture:\n- Treat Slack, Telegram, and email as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A (call-agent) when another app owns the job. Apps you can delegate to include slides (decks/presentations), analytics (data/dashboards), content (docs/articles), videos (Remotion compositions), forms (form builder), clips (screen recordings), design (visual designs), and assets (brand libraries plus generated images/videos).\n- Use the available-apps prompt context first, then list-connected-agents when you need fresh details, to see what agents are available before assuming a request must be handled locally.\n- When asked whether workspace apps expose agent cards or A2A endpoints, call list-workspace-apps with includeAgentCards=true. Without that probe, missing agent-card fields mean unchecked, not unavailable.\n- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.\n- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Reply in the originating thread unless the user explicitly asks you to send to a saved destination.\n\nWhen a user asks for something:\n- If it belongs to analytics, content, slides, videos, assets, etc., delegate via call-agent — do not re-implement the domain logic in dispatch.\n- After call-agent returns an answer, RELAY IT DIRECTLY to the user with at most a one-line preface — do not rephrase, summarize, or add commentary. The downstream agent already crafted the answer; your job is delivery, not editing. This minimizes round-trips and keeps the user-visible reply fast.\n- Exception: if the downstream agent reports a missing model/provider credential, do not name exact env vars, Vault keys, tokens, or secrets. Say the target app needs an LLM connection and recommend connecting Builder/managed LLM for that app; keep bring-your-own provider keys as a secondary option only if the user asks.\n- If the user asks to create, build, make, scaffold, or generate an \"agent\" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.\n- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized fork/copy.\n- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.\n- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode \"builder\", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode \"local-agent\", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode \"coming-soon\", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to Builder org/beta settings. If it returns mode \"builder-unavailable\", report the action's message exactly enough to preserve the missing identity/credential detail.\n- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.\n- Keep responses concise and operational — messaging platforms have character limits.\n- Use markdown sparingly (bold and lists are fine, avoid complex formatting).\n- If a task requires many steps, summarize what you did rather than streaming every detail.`;\n\n/**\n * Defer plugin construction until the Nitro plugin actually fires so the\n * config-aware system prompt resolves AFTER `setupDispatch(config)` has\n * stamped the active config (plugin module load order is not guaranteed).\n */\nconst dispatchIntegrationsPlugin = async (nitroApp: any) => {\n const { integrations = {} } = getDispatchConfig();\n const promptOverride = integrations.systemPrompt;\n const systemPrompt =\n typeof promptOverride === \"string\"\n ? promptOverride\n : typeof promptOverride === \"function\"\n ? promptOverride(DISPATCH_INTEGRATION_SYSTEM_PROMPT)\n : DISPATCH_INTEGRATION_SYSTEM_PROMPT;\n\n const plugin = createIntegrationsPlugin({\n appId: \"dispatch\",\n actions: dispatchActions,\n resolveOwner: resolveDispatchOwner,\n beforeProcess: beforeDispatchProcess,\n systemPrompt,\n // Inherit the framework default (claude-sonnet-4-6 from\n // packages/core/src/integrations/plugin.ts). Haiku was tried for latency\n // but hallucinated URLs/IDs after delegated call-agent results\n // (e.g. inventing `https://slides.workspace.com/deck/builder-io-deck-2024`).\n });\n\n return plugin(nitroApp);\n};\n\nexport default dispatchIntegrationsPlugin;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-native/dispatch",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.9",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Dispatch — workspace control plane for agent-native apps. Vault, integrations, destinations, scheduled jobs, and cross-app delegation, shipped as a single drop-in package.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
"typescript": "^6.0.3",
|
|
101
101
|
"vite": "8.0.3",
|
|
102
102
|
"vitest": "^4.1.5",
|
|
103
|
-
"@agent-native/core": "0.
|
|
103
|
+
"@agent-native/core": "0.74.0"
|
|
104
104
|
},
|
|
105
105
|
"scripts": {
|
|
106
106
|
"build": "tsc && tsc-alias --resolve-full-paths",
|
|
@@ -5,7 +5,7 @@ import { startWorkspaceAppCreation } from "../server/lib/app-creation-store.js";
|
|
|
5
5
|
|
|
6
6
|
export default defineAction({
|
|
7
7
|
description:
|
|
8
|
-
'Start creating a new workspace app from Dispatch when the request truly needs its own app. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it creates a Builder branch when a Builder project is configured. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not clone, wrap, or nest those templates inside the new app unless the user explicitly asks for a customized copy.',
|
|
8
|
+
'Start creating a new workspace app from Dispatch when the request truly needs its own app. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it creates a Builder branch only when a Builder branch project is configured. If the result mode is "coming-soon", the work still requires a code change but no Builder Cloud Agent can run here; tell the user to edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like, and do not send them to Builder org/beta settings. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not clone, wrap, or nest those templates inside the new app unless the user explicitly asks for a customized copy.',
|
|
9
9
|
schema: z.object({
|
|
10
10
|
prompt: z.string().min(1).describe("The user's app creation request"),
|
|
11
11
|
appId: z
|
|
@@ -322,7 +322,7 @@ export function CreateAppFlow({
|
|
|
322
322
|
} else {
|
|
323
323
|
setStatusMessage(
|
|
324
324
|
result?.message ||
|
|
325
|
-
"
|
|
325
|
+
"This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.",
|
|
326
326
|
);
|
|
327
327
|
}
|
|
328
328
|
}
|
|
@@ -1860,7 +1860,7 @@ export async function startWorkspaceAppCreation(input: {
|
|
|
1860
1860
|
mode: "coming-soon",
|
|
1861
1861
|
appId: built.appId,
|
|
1862
1862
|
message:
|
|
1863
|
-
"
|
|
1863
|
+
"This requires a code change. Edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way you like.",
|
|
1864
1864
|
};
|
|
1865
1865
|
}
|
|
1866
1866
|
|
|
@@ -25,7 +25,7 @@ When a user asks for something:
|
|
|
25
25
|
- If the user asks to create, build, make, scaffold, or generate an "agent" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.
|
|
26
26
|
- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized fork/copy.
|
|
27
27
|
- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind.
|
|
28
|
-
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode "local-agent", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode "coming-soon" or "builder-unavailable",
|
|
28
|
+
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode "local-agent", tell the user it is ready for the local code agent and include the returned app path/prompt summary. If it returns mode "coming-soon", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to Builder org/beta settings. If it returns mode "builder-unavailable", report the action's message exactly enough to preserve the missing identity/credential detail.
|
|
29
29
|
- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.
|
|
30
30
|
- Keep responses concise and operational — messaging platforms have character limits.
|
|
31
31
|
- Use markdown sparingly (bold and lists are fine, avoid complex formatting).
|