@agent-native/dispatch 0.2.12 → 0.2.14
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/app-keys-popover.js +3 -3
- package/dist/components/app-keys-popover.js.map +1 -1
- package/dist/components/create-app-popover.d.ts.map +1 -1
- package/dist/components/create-app-popover.js +5 -1
- package/dist/components/create-app-popover.js.map +1 -1
- package/dist/components/workspace-app-card.d.ts +6 -0
- package/dist/components/workspace-app-card.d.ts.map +1 -0
- package/dist/components/workspace-app-card.js +12 -0
- package/dist/components/workspace-app-card.js.map +1 -0
- package/dist/lib/workspace-apps.d.ts +15 -0
- package/dist/lib/workspace-apps.d.ts.map +1 -0
- package/dist/lib/workspace-apps.js +9 -0
- package/dist/lib/workspace-apps.js.map +1 -0
- package/dist/routes/pages/apps.$appId.d.ts.map +1 -1
- package/dist/routes/pages/apps.$appId.js +1 -5
- package/dist/routes/pages/apps.$appId.js.map +1 -1
- package/dist/routes/pages/apps.d.ts.map +1 -1
- package/dist/routes/pages/apps.js +3 -20
- package/dist/routes/pages/apps.js.map +1 -1
- package/dist/routes/pages/overview.d.ts.map +1 -1
- package/dist/routes/pages/overview.js +2 -20
- package/dist/routes/pages/overview.js.map +1 -1
- package/dist/server/lib/app-creation-store.d.ts.map +1 -1
- package/dist/server/lib/app-creation-store.js +5 -1
- package/dist/server/lib/app-creation-store.js.map +1 -1
- package/dist/server/plugins/agent-chat.d.ts.map +1 -1
- package/dist/server/plugins/agent-chat.js +1 -0
- package/dist/server/plugins/agent-chat.js.map +1 -1
- package/dist/server/plugins/integrations.d.ts.map +1 -1
- package/dist/server/plugins/integrations.js +2 -0
- 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/app-keys-popover.tsx +3 -3
- package/src/components/create-app-popover.tsx +5 -1
- package/src/components/workspace-app-card.tsx +85 -0
- package/src/lib/workspace-apps.ts +21 -0
- package/src/routes/pages/apps.$appId.tsx +4 -17
- package/src/routes/pages/apps.tsx +6 -89
- package/src/routes/pages/overview.tsx +5 -84
- package/src/server/lib/app-creation-store.ts +5 -1
- package/src/server/plugins/agent-chat.ts +1 -0
- package/src/server/plugins/integrations.ts +2 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-creation-store.js","sourceRoot":"","sources":["../../../src/server/lib/app-creation-store.ts"],"names":[],"mappings":"AAAA,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,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,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,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,gCAAgC,CAAC;AAExC,MAAM,YAAY,GAAG,gCAAgC,CAAC;AACtD,MAAM,sBAAsB,GAAG,kCAAkC,CAAC;AAClE,MAAM,4BAA4B,GAAG,qBAAqB,CAAC;AAC3D,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,eAAe,GAAG,8BAA8B,C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C,OAAO;YACL,IAAI,EAAE,qBAAqB;YAC3B,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;YACpC,OAAO,EACL,kDAAkD,QAAQ,CAAC,gBAAgB,IAAI;gBAC/E,+BAA+B,MAAM,mCAAmC;gBACxE,mHAAmH;SACtH,CAAC;IACJ,CAAC;IAED,MAAM,yBAAyB,CAAC;QAC9B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;QACpC,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 fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getSetting, putSetting } from \"@agent-native/core/settings\";\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 { assertValidWorkspaceAppId } from \"@agent-native/core/shared\";\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_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nconst MAX_PENDING_APPS = 50;\nconst AGENT_CARD_PATH = \"/.well-known/agent-card.json\";\nconst AGENT_CARD_FETCH_TIMEOUT_MS = 1_500;\n\nexport interface WorkspaceAppSummary {\n id: string;\n name: string;\n description: string;\n path: string;\n url: string | null;\n isDispatch: boolean;\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}\n\nexport interface ListWorkspaceAppsOptions {\n includeAgentCards?: 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 createdAt: string;\n updatedAt: string;\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 scopedSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${SETTINGS_KEY}:org:${orgId}`;\n return `${SETTINGS_KEY}:user:${currentOwnerEmail()}`;\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 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 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 = rawApps\n .map((entry): 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 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\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) => {\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 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 createdAt:\n typeof record.createdAt === \"string\" && record.createdAt.trim()\n ? record.createdAt.trim()\n : now,\n updatedAt:\n typeof record.updatedAt === \"string\" && record.updatedAt.trim()\n ? record.updatedAt.trim()\n : now,\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 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 status: \"pending\",\n statusLabel: \"Building in Builder\",\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 = (await listPendingWorkspaceApps())\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 branchName?: string | null;\n builderUrl?: string | null;\n}) {\n const now = new Date().toISOString();\n const raw = await readSettingsRecord();\n const pendingApps = parsePendingWorkspaceApps(raw.pendingApps);\n const existing = pendingApps.find((app) => app.id === input.appId);\n const next: PendingWorkspaceApp = {\n id: input.appId,\n name: titleCase(input.appId),\n 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 createdAt: existing?.createdAt || now,\n updatedAt: now,\n };\n\n await putSetting(scopedSettingsKey(), {\n ...raw,\n pendingApps: [\n next,\n ...pendingApps.filter((app) => app.id !== input.appId),\n ].slice(0, MAX_PENDING_APPS),\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 },\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\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())\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 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 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\nexport async function listWorkspaceApps(\n options: ListWorkspaceAppsOptions = {},\n): Promise<WorkspaceAppSummary[]> {\n const workspaceRoot = findWorkspaceRoot();\n const localFilesystemApps =\n workspaceRoot && isLocalAppCreationRuntime()\n ? readWorkspaceAppsFromFilesystem(workspaceRoot)\n : null;\n if (localFilesystemApps) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(localFilesystemApps),\n options,\n );\n }\n\n const manifestApps =\n readWorkspaceAppsFromEnv() ?? readWorkspaceAppsFromManifestFile();\n if (manifestApps) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(manifestApps),\n options,\n );\n }\n\n if (!workspaceRoot) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps([\n {\n id: \"dispatch\",\n name: \"Dispatch\",\n description: \"Workspace control plane\",\n path: \"/dispatch\",\n url: workspaceAppUrl(\"/dispatch\"),\n isDispatch: true,\n status: \"ready\",\n },\n ]),\n options,\n );\n }\n\n const apps = readWorkspaceAppsFromFilesystem(workspaceRoot) ?? [];\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(apps),\n options,\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 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 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 `Template to start from: ${input.template || \"starter\"}`,\n `User prompt: ${input.prompt.trim()}`,\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 \"\",\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 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 those shared resources. Add a short note to apps/${appId}/AGENTS.md telling the app agent to read relevant shared resources under context/ or the selected resource paths before doing GTM/domain work.`\n : \"Do not grant any 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 at /_agent-native/actions/<name> via useActionQuery / useActionMutation. 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 \"- 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.\",\n \"- Include a final verification note covering the registry entry, manifest/deploy metadata, 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 template?: string | null;\n secretIds?: string[];\n resourceIds?: string[];\n}) {\n const initial = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\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 template: input.template,\n selectedKeys,\n selectedResources,\n });\n const prompt = built.prompt;\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 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":"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/E,+BAA+B,MAAM,mCAAmC;gBACxE,mHAAmH;SACtH,CAAC;IACJ,CAAC;IAED,MAAM,yBAAyB,CAAC;QAC9B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,SAAS,EAAE,QAAQ,CAAC,gBAAgB;QACpC,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 fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getSetting, putSetting } from \"@agent-native/core/settings\";\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 { assertValidWorkspaceAppId } from \"@agent-native/core/shared\";\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_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nconst MAX_PENDING_APPS = 50;\nconst AGENT_CARD_PATH = \"/.well-known/agent-card.json\";\nconst AGENT_CARD_FETCH_TIMEOUT_MS = 1_500;\n\nexport interface WorkspaceAppSummary {\n id: string;\n name: string;\n description: string;\n path: string;\n url: string | null;\n isDispatch: boolean;\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}\n\nexport interface ListWorkspaceAppsOptions {\n includeAgentCards?: 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 createdAt: string;\n updatedAt: string;\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 scopedSettingsKey(): string {\n const orgId = currentOrgId();\n if (orgId) return `${SETTINGS_KEY}:org:${orgId}`;\n return `${SETTINGS_KEY}:user:${currentOwnerEmail()}`;\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 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 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 = rawApps\n .map((entry): 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 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\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) => {\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 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 createdAt:\n typeof record.createdAt === \"string\" && record.createdAt.trim()\n ? record.createdAt.trim()\n : now,\n updatedAt:\n typeof record.updatedAt === \"string\" && record.updatedAt.trim()\n ? record.updatedAt.trim()\n : now,\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 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 status: \"pending\",\n statusLabel: \"Building in Builder\",\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 = (await listPendingWorkspaceApps())\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 branchName?: string | null;\n builderUrl?: string | null;\n}) {\n const now = new Date().toISOString();\n const raw = await readSettingsRecord();\n const pendingApps = parsePendingWorkspaceApps(raw.pendingApps);\n const existing = pendingApps.find((app) => app.id === input.appId);\n const next: PendingWorkspaceApp = {\n id: input.appId,\n name: titleCase(input.appId),\n 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 createdAt: existing?.createdAt || now,\n updatedAt: now,\n };\n\n await putSetting(scopedSettingsKey(), {\n ...raw,\n pendingApps: [\n next,\n ...pendingApps.filter((app) => app.id !== input.appId),\n ].slice(0, MAX_PENDING_APPS),\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 },\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\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())\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 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 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\nexport async function listWorkspaceApps(\n options: ListWorkspaceAppsOptions = {},\n): Promise<WorkspaceAppSummary[]> {\n const workspaceRoot = findWorkspaceRoot();\n const localFilesystemApps =\n workspaceRoot && isLocalAppCreationRuntime()\n ? readWorkspaceAppsFromFilesystem(workspaceRoot)\n : null;\n if (localFilesystemApps) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(localFilesystemApps),\n options,\n );\n }\n\n const manifestApps =\n readWorkspaceAppsFromEnv() ?? readWorkspaceAppsFromManifestFile();\n if (manifestApps) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(manifestApps),\n options,\n );\n }\n\n if (!workspaceRoot) {\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps([\n {\n id: \"dispatch\",\n name: \"Dispatch\",\n description: \"Workspace control plane\",\n path: \"/dispatch\",\n url: workspaceAppUrl(\"/dispatch\"),\n isDispatch: true,\n status: \"ready\",\n },\n ]),\n options,\n );\n }\n\n const apps = readWorkspaceAppsFromFilesystem(workspaceRoot) ?? [];\n return maybeIncludeAgentCards(\n await appendPendingWorkspaceApps(apps),\n options,\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 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 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 `Template to start from: ${input.template || \"starter\"}`,\n `User prompt: ${input.prompt.trim()}`,\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 \"\",\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 those shared resources. Add a short note to apps/${appId}/AGENTS.md telling the app agent to read relevant shared resources under context/ or the selected resource paths before doing GTM/domain work.`\n : \"Do not grant any 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 \"- 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.\",\n \"- Include a final verification note covering the registry entry, manifest/deploy metadata, 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 template?: string | null;\n secretIds?: string[];\n resourceIds?: string[];\n}) {\n const initial = buildWorkspaceAppPrompt({\n prompt: input.prompt,\n appId: input.appId,\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 template: input.template,\n selectedKeys,\n selectedResources,\n });\n const prompt = built.prompt;\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 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-chat.d.ts","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":";AAIA,
|
|
1
|
+
{"version":3,"file":"agent-chat.d.ts","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":";AAIA,wBAiCG"}
|
|
@@ -28,6 +28,7 @@ Use the standard workspace primitives:
|
|
|
28
28
|
- Use custom agent profiles in agents/*.md for local spawned work and remote-agents/*.json for remote A2A apps.
|
|
29
29
|
- When answering whether workspace apps expose agent cards or A2A endpoints, call list-workspace-apps with includeAgentCards=true. If you have not requested that probe, absence of agent-card fields means unchecked, not unavailable.
|
|
30
30
|
- When creating a new workspace app, create a separate app under apps/<app-id> with apps/<app-id>/package.json, mount it at /<app-id>, use relative /<app-id> links, never hardcode localhost or dev ports, use shadcn/ui with @tabler/icons-react rather than lucide-react, and ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath(). There is no separate workspace app registry to edit.
|
|
31
|
+
- Treat first-party apps such as Mail, Calendar, Analytics, 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.
|
|
31
32
|
|
|
32
33
|
When a user asks for something like a digest, reminder, routing rule, or saved behavior:
|
|
33
34
|
- First decide whether it should be a resource, a recurring job, a destination, or a delegated task.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-chat.js","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,eAAe,qBAAqB,CAAC;IACnC,KAAK,EAAE,UAAU;IACjB,0EAA0E;IAC1E,2EAA2E;IAC3E,2EAA2E;IAC3E,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;QACvC,OAAO,GAAG,CAAC,KAAK,CAAC;IACnB,CAAC;IACD,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,OAAO,EAAE,eAAe;IACxB,YAAY,EAAE
|
|
1
|
+
{"version":3,"file":"agent-chat.js","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,eAAe,qBAAqB,CAAC;IACnC,KAAK,EAAE,UAAU;IACjB,0EAA0E;IAC1E,2EAA2E;IAC3E,2EAA2E;IAC3E,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;QACvC,OAAO,GAAG,CAAC,KAAK,CAAC;IACnB,CAAC;IACD,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,OAAO,EAAE,eAAe;IACxB,YAAY,EAAE;;;;;;;;;;;;;;;;;;;4EAmB4D;CAC3E,CAAC,CAAC","sourcesContent":["import { createAgentChatPlugin } from \"@agent-native/core/server\";\nimport { getOrgContext } from \"@agent-native/core/org\";\nimport { dispatchActions } from \"../../actions/index.js\";\n\nexport default createAgentChatPlugin({\n appId: \"dispatch\",\n // Without this, AGENT_ORG_ID is never set on agent action calls and every\n // row written through the frontend (vault secrets, destinations, workspace\n // resources) lands with org_id=NULL — breaking data isolation across orgs.\n resolveOrgId: async (event) => {\n const ctx = await getOrgContext(event);\n return ctx.orgId;\n },\n // Read actions directly from the package's own action map rather than from\n // a build-time-generated `.generated/actions-registry.ts` (the latter is a\n // template-only construct that the Vite plugin emits next to actions/).\n actions: dispatchActions,\n systemPrompt: `You are the central dispatch for this workspace.\n\nDefault posture:\n- Treat Slack and Telegram as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A when another app owns the job.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Prefer replying in the current external thread unless the user explicitly asks you to send to a saved destination.\n\nUse the standard workspace primitives:\n- Read and update resources like AGENTS.md, LEARNINGS.md, jobs/*.md, agents/*.md, and remote-agents/*.json when appropriate.\n- Use recurring jobs for scheduled behavior.\n- Use custom agent profiles in agents/*.md for local spawned work and remote-agents/*.json for remote A2A apps.\n- When answering whether workspace apps expose agent cards or A2A endpoints, call list-workspace-apps with includeAgentCards=true. If you have not requested that probe, absence of agent-card fields means unchecked, not unavailable.\n- When creating a new workspace app, create a separate app under apps/<app-id> with apps/<app-id>/package.json, mount it at /<app-id>, use relative /<app-id> links, never hardcode localhost or dev ports, use shadcn/ui with @tabler/icons-react rather than lucide-react, and ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath(). There is no separate workspace app registry to edit.\n- Treat first-party apps such as Mail, Calendar, Analytics, 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\nWhen a user asks for something like a digest, reminder, routing rule, or saved behavior:\n- First decide whether it should be a resource, a recurring job, a destination, or a delegated task.\n- Keep responses concise and operational.\n- Avoid inventing integrations or destinations that are not configured yet.`,\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrations.d.ts","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"integrations.d.ts","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"AA+BA;;;;GAIG;AACH,QAAA,MAAM,0BAA0B,GAAU,UAAU,GAAG,kBAuBtD,CAAC;AAEF,eAAe,0BAA0B,CAAC"}
|
|
@@ -9,6 +9,7 @@ Default posture:
|
|
|
9
9
|
- 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 images (brand image libraries and generated raster imagery).
|
|
10
10
|
- Use list-connected-agents to see what agents are available before assuming a request must be handled locally.
|
|
11
11
|
- 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.
|
|
12
|
+
- Treat first-party apps such as Mail, Calendar, Analytics, 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.
|
|
12
13
|
- Keep durable memory and operating instructions in resources rather than ephemeral chat.
|
|
13
14
|
- Reply in the originating thread unless the user explicitly asks you to send to a saved destination.
|
|
14
15
|
|
|
@@ -17,6 +18,7 @@ When a user asks for something:
|
|
|
17
18
|
- 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.
|
|
18
19
|
- 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.
|
|
19
20
|
- 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.
|
|
21
|
+
- If a new-app prompt asks for access to Mail, Calendar, Analytics, 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.
|
|
20
22
|
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/starter 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 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. 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", explain the missing Builder setup and ask them to connect/configure Builder.
|
|
21
23
|
- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.
|
|
22
24
|
- Keep responses concise and operational — messaging platforms have character limits.
|
|
@@ -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
|
|
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;;;;;;;;;;;;;;;;;;;;;4FAqBiD,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 images (brand image libraries and generated raster imagery).\n- Use list-connected-agents 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, 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- 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, images, 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, 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 user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/starter 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 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. 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\", explain the missing Builder setup and ask them to connect/configure Builder.\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.2.
|
|
3
|
+
"version": "0.2.14",
|
|
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",
|
|
@@ -96,7 +96,7 @@
|
|
|
96
96
|
"typescript": "^6.0.3",
|
|
97
97
|
"vite": "8.0.3",
|
|
98
98
|
"vitest": "^4.1.5",
|
|
99
|
-
"@agent-native/core": "0.12.
|
|
99
|
+
"@agent-native/core": "0.12.16"
|
|
100
100
|
},
|
|
101
101
|
"scripts": {
|
|
102
102
|
"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. 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/starter.",
|
|
8
|
+
"Start creating a new workspace app from Dispatch when the request truly needs its own app. 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/starter. If the request needs Mail, Calendar, Analytics, 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
|
|
@@ -54,9 +54,9 @@ export function AppKeysPopover({
|
|
|
54
54
|
type="button"
|
|
55
55
|
aria-label={`Manage keys for ${appName}`}
|
|
56
56
|
onClick={(event) => {
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
|
|
57
|
+
// Keep parent card click handlers from also firing. Do not
|
|
58
|
+
// preventDefault here: Radix uses the same click to open the
|
|
59
|
+
// popover trigger.
|
|
60
60
|
event.stopPropagation();
|
|
61
61
|
}}
|
|
62
62
|
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md border border-transparent text-muted-foreground/70 hover:border-border hover:bg-accent/40 hover:text-foreground"
|
|
@@ -103,9 +103,13 @@ function buildAppCreationPrompt(input: {
|
|
|
103
103
|
``,
|
|
104
104
|
`Pick a starter template that fits the user's prompt — analytics, calendar, content, design, dispatch, forms, mail, slides, clips, or starter when none of the others fit.`,
|
|
105
105
|
`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.`,
|
|
106
|
+
`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.`,
|
|
107
|
+
`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.`,
|
|
106
108
|
`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.`,
|
|
107
109
|
`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.`,
|
|
108
|
-
`If the user's prompt mentions
|
|
110
|
+
`Existing first-party apps are neighbors, not implementation details for this app. If the user's 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.`,
|
|
111
|
+
`Do not clone first-party templates, create wrapper apps, or scaffold child apps/routes for Mail, Calendar, Analytics, 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.`,
|
|
112
|
+
`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.`,
|
|
109
113
|
`Do not satisfy this by adding a route, page, component, or file inside apps/starter or another existing app unless the user explicitly asks to modify that existing app.`,
|
|
110
114
|
keyList
|
|
111
115
|
? `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.`
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { IconArrowUpRight, IconClockHour4 } from "@tabler/icons-react";
|
|
2
|
+
import { AppKeysPopover } from "@/components/app-keys-popover";
|
|
3
|
+
import { Badge } from "@/components/ui/badge";
|
|
4
|
+
import { cn } from "@/lib/utils";
|
|
5
|
+
import {
|
|
6
|
+
isPendingBuilderHref,
|
|
7
|
+
workspaceAppHref,
|
|
8
|
+
type WorkspaceAppSummary,
|
|
9
|
+
} from "@/lib/workspace-apps";
|
|
10
|
+
|
|
11
|
+
export function WorkspaceAppCard({
|
|
12
|
+
app,
|
|
13
|
+
className,
|
|
14
|
+
}: {
|
|
15
|
+
app: WorkspaceAppSummary;
|
|
16
|
+
className?: string;
|
|
17
|
+
}) {
|
|
18
|
+
const href = workspaceAppHref(app);
|
|
19
|
+
const openInNewTab = isPendingBuilderHref(app);
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
<div
|
|
23
|
+
aria-disabled={!href}
|
|
24
|
+
className={cn(
|
|
25
|
+
"group relative rounded-lg border bg-card p-4 transition hover:border-foreground/30 aria-disabled:opacity-60",
|
|
26
|
+
className,
|
|
27
|
+
)}
|
|
28
|
+
>
|
|
29
|
+
{href ? (
|
|
30
|
+
<a
|
|
31
|
+
href={href}
|
|
32
|
+
target={openInNewTab ? "_blank" : undefined}
|
|
33
|
+
rel={openInNewTab ? "noreferrer" : undefined}
|
|
34
|
+
aria-label={`Open ${app.name}`}
|
|
35
|
+
className="absolute inset-0 z-0 rounded-lg"
|
|
36
|
+
/>
|
|
37
|
+
) : null}
|
|
38
|
+
|
|
39
|
+
<div className="pointer-events-none relative z-10 flex h-full items-start justify-between gap-3">
|
|
40
|
+
<div className="min-w-0">
|
|
41
|
+
<div className="flex min-w-0 items-center gap-2">
|
|
42
|
+
<h3 className="truncate text-sm font-semibold text-foreground">
|
|
43
|
+
{app.name}
|
|
44
|
+
</h3>
|
|
45
|
+
{app.status === "pending" ? (
|
|
46
|
+
<Badge
|
|
47
|
+
variant="outline"
|
|
48
|
+
className="shrink-0 gap-1 border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300"
|
|
49
|
+
>
|
|
50
|
+
<IconClockHour4 size={12} />
|
|
51
|
+
Building
|
|
52
|
+
</Badge>
|
|
53
|
+
) : null}
|
|
54
|
+
</div>
|
|
55
|
+
<p className="mt-1 truncate font-mono text-xs text-muted-foreground">
|
|
56
|
+
{app.path}
|
|
57
|
+
</p>
|
|
58
|
+
{app.status === "pending" && app.branchName ? (
|
|
59
|
+
<p className="mt-1 truncate text-xs text-muted-foreground">
|
|
60
|
+
Branch: {app.branchName}
|
|
61
|
+
</p>
|
|
62
|
+
) : null}
|
|
63
|
+
{app.description ? (
|
|
64
|
+
<p className="mt-2 line-clamp-2 text-xs leading-relaxed text-muted-foreground">
|
|
65
|
+
{app.description}
|
|
66
|
+
</p>
|
|
67
|
+
) : null}
|
|
68
|
+
</div>
|
|
69
|
+
<div className="flex shrink-0 items-center gap-1">
|
|
70
|
+
{app.status === "ready" ? (
|
|
71
|
+
<div className="pointer-events-auto">
|
|
72
|
+
<AppKeysPopover appId={app.id} appName={app.name} />
|
|
73
|
+
</div>
|
|
74
|
+
) : null}
|
|
75
|
+
{href ? (
|
|
76
|
+
<IconArrowUpRight
|
|
77
|
+
size={16}
|
|
78
|
+
className="text-muted-foreground transition group-hover:text-foreground"
|
|
79
|
+
/>
|
|
80
|
+
) : null}
|
|
81
|
+
</div>
|
|
82
|
+
</div>
|
|
83
|
+
</div>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface WorkspaceAppSummary {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
path: string;
|
|
6
|
+
url?: string | null;
|
|
7
|
+
isDispatch?: boolean;
|
|
8
|
+
status?: "ready" | "pending";
|
|
9
|
+
statusLabel?: string;
|
|
10
|
+
builderUrl?: string | null;
|
|
11
|
+
branchName?: string | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function workspaceAppHref(app: WorkspaceAppSummary): string | null {
|
|
15
|
+
if (app.status === "pending") return app.builderUrl || null;
|
|
16
|
+
return app.path || app.url || null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isPendingBuilderHref(app: WorkspaceAppSummary): boolean {
|
|
20
|
+
return app.status === "pending" && !!app.builderUrl;
|
|
21
|
+
}
|