@agent-native/core 0.49.27 → 0.50.0
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/agent/harness/ai-sdk-adapter.d.ts +13 -0
- package/dist/agent/harness/ai-sdk-adapter.d.ts.map +1 -0
- package/dist/agent/harness/ai-sdk-adapter.js +232 -0
- package/dist/agent/harness/ai-sdk-adapter.js.map +1 -0
- package/dist/agent/harness/background.d.ts +15 -0
- package/dist/agent/harness/background.d.ts.map +1 -0
- package/dist/agent/harness/background.js +233 -0
- package/dist/agent/harness/background.js.map +1 -0
- package/dist/agent/harness/builtin.d.ts +2 -0
- package/dist/agent/harness/builtin.d.ts.map +1 -0
- package/dist/agent/harness/builtin.js +24 -0
- package/dist/agent/harness/builtin.js.map +1 -0
- package/dist/agent/harness/index.d.ts +9 -0
- package/dist/agent/harness/index.d.ts.map +1 -0
- package/dist/agent/harness/index.js +8 -0
- package/dist/agent/harness/index.js.map +1 -0
- package/dist/agent/harness/registry.d.ts +15 -0
- package/dist/agent/harness/registry.d.ts.map +1 -0
- package/dist/agent/harness/registry.js +70 -0
- package/dist/agent/harness/registry.js.map +1 -0
- package/dist/agent/harness/runner.d.ts +21 -0
- package/dist/agent/harness/runner.d.ts.map +1 -0
- package/dist/agent/harness/runner.js +86 -0
- package/dist/agent/harness/runner.js.map +1 -0
- package/dist/agent/harness/store.d.ts +46 -0
- package/dist/agent/harness/store.d.ts.map +1 -0
- package/dist/agent/harness/store.js +304 -0
- package/dist/agent/harness/store.js.map +1 -0
- package/dist/agent/harness/translate.d.ts +5 -0
- package/dist/agent/harness/translate.d.ts.map +1 -0
- package/dist/agent/harness/translate.js +120 -0
- package/dist/agent/harness/translate.js.map +1 -0
- package/dist/agent/harness/types.d.ts +127 -0
- package/dist/agent/harness/types.d.ts.map +1 -0
- package/dist/agent/harness/types.js +2 -0
- package/dist/agent/harness/types.js.map +1 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +2 -0
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +10 -1
- package/dist/cli/create.js.map +1 -1
- package/dist/cli/pr-visual-recap-workflow.d.ts +1 -1
- package/dist/cli/pr-visual-recap-workflow.d.ts.map +1 -1
- package/dist/cli/pr-visual-recap-workflow.js +1 -1
- package/dist/cli/pr-visual-recap-workflow.js.map +1 -1
- package/dist/cli/skills.d.ts +1 -1
- package/dist/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +8 -1
- package/dist/cli/skills.js.map +1 -1
- package/dist/client/blocks/library/wireframe.d.ts.map +1 -1
- package/dist/client/blocks/library/wireframe.js +0 -1
- package/dist/client/blocks/library/wireframe.js.map +1 -1
- package/dist/client/resources/use-resources.d.ts.map +1 -1
- package/dist/client/resources/use-resources.js +4 -2
- package/dist/client/resources/use-resources.js.map +1 -1
- package/dist/code-agents/background-run.d.ts +6 -4
- package/dist/code-agents/background-run.d.ts.map +1 -1
- package/dist/code-agents/background-run.js.map +1 -1
- package/dist/coding-tools/run-code.js +6 -4
- package/dist/coding-tools/run-code.js.map +1 -1
- package/dist/provider-api/index.d.ts +20 -12
- package/dist/provider-api/index.d.ts.map +1 -1
- package/dist/provider-api/index.js +157 -37
- package/dist/provider-api/index.js.map +1 -1
- package/dist/provider-api/quota-governor.d.ts +53 -0
- package/dist/provider-api/quota-governor.d.ts.map +1 -0
- package/dist/provider-api/quota-governor.js +395 -0
- package/dist/provider-api/quota-governor.js.map +1 -0
- package/dist/provider-api/staging.d.ts.map +1 -1
- package/dist/provider-api/staging.js +16 -0
- package/dist/provider-api/staging.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +34 -10
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +98 -0
- package/dist/workspace-files/index.d.ts +0 -1
- package/dist/workspace-files/index.d.ts.map +1 -1
- package/dist/workspace-files/index.js +0 -1
- package/dist/workspace-files/index.js.map +1 -1
- package/dist/workspace-files/store.d.ts +14 -9
- package/dist/workspace-files/store.d.ts.map +1 -1
- package/dist/workspace-files/store.js +89 -164
- package/dist/workspace-files/store.js.map +1 -1
- package/dist/workspace-files/tool.d.ts +3 -4
- package/dist/workspace-files/tool.d.ts.map +1 -1
- package/dist/workspace-files/tool.js +8 -7
- package/dist/workspace-files/tool.js.map +1 -1
- package/docs/content/deployment.md +1 -1
- package/package.json +2 -1
- package/src/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +98 -0
- package/dist/workspace-files/schema.d.ts +0 -195
- package/dist/workspace-files/schema.d.ts.map +0 -1
- package/dist/workspace-files/schema.js +0 -48
- package/dist/workspace-files/schema.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-chat-plugin.js","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EACL,QAAQ,EACR,yBAAyB,EACzB,eAAe,GAChB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,4BAA4B,EAC5B,oBAAoB,EACpB,0BAA0B,EAC1B,QAAQ,EACR,cAAc,GAEf,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,kCAAkC,CAAC;AAErF,OAAO,EACL,aAAa,EACb,qBAAqB,EACrB,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,8BAA8B,EAC9B,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,0BAA0B,CA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AAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACzC,CAAC;YACD,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,kBAAkB,CAAC,CAAC;YAC7D,OAAO,OAAO,CAAC,SAAS,EAAE,CAAC;QAC7B,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,CAAC,IAAI,CACV,2DAA2D,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CACjF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n runWithRequestContext,\n getRequestOrgId,\n getRequestUserEmail,\n getRequestRunContext,\n ensureRequestRunContext,\n} from \"./request-context.js\";\nimport { getSetting, putSetting } from \"../settings/store.js\";\nimport { createDbAdminAgentTools } from \"../db-admin/agent-tools.js\";\nimport {\n getH3App,\n markDefaultPluginProvided,\n trackPluginInit,\n} from \"./framework-request-handler.js\";\nimport {\n createProductionAgentHandler,\n actionsToEngineTools,\n getActiveRunForThreadAsync,\n abortRun,\n subscribeToRun,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { runAgentLoopDirectWithSoftTimeout } from \"../agent/run-loop-with-resume.js\";\nimport type { AgentEngine, EngineMessage } from \"../agent/engine/types.js\";\nimport {\n resolveEngine,\n createAnthropicEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n getAgentEngineEntry,\n isAgentEnginePackageInstalled,\n isStoredEngineUsableForRequest,\n listAgentEngines,\n registerBuiltinEngines,\n} from \"../agent/engine/index.js\";\nimport {\n canUpdateAgentAppModelDefaultSettings,\n normalizeAgentAppModelDefaultAppId,\n readAgentAppModelDefaultSettings,\n resetAgentAppModelDefaultSettings,\n writeAgentAppModelDefaultSettings,\n} from \"../agent/app-model-defaults.js\";\nimport { DEFAULT_ANTHROPIC_MODEL } from \"../agent/default-model.js\";\nimport type {\n AgentChatAttachment,\n AgentChatEvent,\n AgentChatReference,\n ActionTool,\n MentionProvider,\n} from \"../agent/types.js\";\nimport { attachToolSearch } from \"../agent/tool-search.js\";\nimport type { ActionHttpConfig } from \"../action.js\";\nimport {\n McpClientManager,\n loadMcpConfig,\n autoDetectMcpConfig,\n mcpToolsToActionEntries,\n syncMcpActionEntries,\n mountMcpServersRoutes,\n mountMcpHubRoutes,\n buildMergedConfig,\n startMcpConfigRefresh,\n areBuiltinMcpCapabilitiesSupported,\n setBuiltinMcpCapabilityEnabled,\n getHubStatus,\n isHubServeEnabled,\n type BuiltinMcpCapabilityId,\n} from \"../mcp-client/index.js\";\nimport { discoverAgents } from \"./agent-discovery.js\";\nimport { loadSchemaPromptBlock } from \"./schema-prompt.js\";\nimport {\n buildAssistantMessage,\n buildUserMessage,\n extractThreadMeta,\n foldAssistantTurn,\n mergeThreadDataForClientSave,\n upsertUserMessage,\n} from \"../agent/thread-data-builder.js\";\nimport {\n createError,\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getQuery,\n getHeader,\n type H3Event,\n} from \"h3\";\nimport { getSession } from \"./auth.js\";\nimport { getOrigin } from \"./google-oauth.js\";\nimport {\n createThread,\n forkThread,\n getThread,\n listThreads,\n searchThreads,\n renameThread,\n setThreadArchived,\n setThreadPinned,\n setThreadScope,\n updateThreadData,\n withThreadDataLock,\n deleteThread,\n setThreadQueuedMessages,\n type ChatThreadScope,\n type ForkThreadSourceSnapshot,\n} from \"../chat-threads/store.js\";\nimport { callerOwnsRun, callerOwnsThread } from \"../agent/run-ownership.js\";\nimport {\n resourceList,\n resourceListAccessible,\n resourceGet,\n resourceGetByPath,\n ensurePersonalDefaults,\n SHARED_OWNER,\n WORKSPACE_OWNER,\n} from \"../resources/store.js\";\nimport {\n getFrontmatterValue,\n getSkillNameFromPath,\n parseFrontmatter,\n} from \"../resources/metadata.js\";\nimport nodePath from \"node:path\";\nimport { readBody } from \"./h3-helpers.js\";\nimport {\n AGENT_TEAM_PROCESS_RUN_PATH,\n processAgentTeamRun,\n reconcileAgentTeamRunsForOwner,\n} from \"./agent-teams.js\";\nimport { setProgressPreListHook } from \"../progress/store.js\";\nimport {\n verifyInternalToken,\n extractBearerToken,\n} from \"../integrations/internal-token.js\";\nimport {\n hasConfiguredA2ASecret,\n isA2AProductionRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n getBuilderBrowserConnectUrlForOwner,\n resolveBuilderBranchProjectId,\n} from \"./builder-browser.js\";\nimport { captureCliOutput } from \"./cli-capture.js\";\nimport { withConfiguredAppBasePath } from \"./app-base-path.js\";\nimport {\n appendA2AArtifactLinks,\n buildA2ARecoverableArtifactMessage,\n type A2AArtifactResponseOptions,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\nimport { updateTaskStatusMessage } from \"../a2a/task-store.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport { buildRuntimeContextPrompt } from \"../agent/runtime-context.js\";\nimport {\n buildFrameworkCore,\n buildFrameworkCoreCompact,\n FIRST_SESSION_PERSONALIZATION,\n getModelFamilyOverlay,\n type PromptExamples,\n} from \"./prompts/index.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// This avoids require() which bundlers convert to createRequire(import.meta.url)\n// that crashes on CF Workers where import.meta.url is undefined.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function lazyFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\n\nconst SHARED_PROMPT_RESOURCE_MAX_CHARS = 30_000;\nconst COMPACT_PROMPT_RESOURCE_MAX_CHARS = 12_000;\nconst MAX_ACTION_SUMMARY_DESCRIPTION_CHARS = 140;\n\nfunction compactPromptLine(value: string, maxChars: number): string {\n const line = value.replace(/\\s+/g, \" \").trim();\n if (line.length <= maxChars) return line;\n return `${line.slice(0, maxChars - 1)}…`;\n}\nconst SHARED_RESOURCE_INDEX_LIMIT = 40;\n\nfunction normalizeResourcePathForPrompt(path: string): string {\n return path.replace(/^\\/+/, \"\").trim();\n}\n\nfunction resourceToolHint(\n action: \"list\" | \"read\" | \"effective\" | \"write\" | \"delete\" | \"promote\",\n extra?: string,\n): string {\n return `Use the \\`resources\\` tool with \\`action: \"${action}\"\\`${extra ? `, ${extra}` : \"\"}.`;\n}\n\nfunction skillDocsSlug(name: string): string {\n return `skill-${name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")}`;\n}\n\nfunction ensureSentence(value: string): string {\n const trimmed = value.trim();\n if (!trimmed) return \"\";\n return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction escapeXmlAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n}\n\nfunction truncatePromptResourceContent(\n content: string,\n path: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n readHint?: string,\n): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxChars) return trimmed;\n const omitted = trimmed.length - maxChars;\n const hint =\n readHint ??\n resourceToolHint(\n \"read\",\n `\\`path: \"${path}\"\\` and the resource's \\`scope\\` for the full content`,\n );\n return `${trimmed.slice(0, maxChars)}\\n\\n[Resource ${path} truncated after ${maxChars.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted. ${hint}]`;\n}\n\nfunction promptResourceBlock(input: {\n name: string;\n scope: string;\n content: string;\n path?: string;\n maxChars?: number;\n readHint?: string;\n}): string | null {\n const normalizedPath = input.path\n ? normalizeResourcePathForPrompt(input.path)\n : undefined;\n const content = truncatePromptResourceContent(\n input.content,\n normalizedPath ?? input.name,\n input.maxChars,\n input.readHint,\n );\n if (!content) return null;\n const pathAttr = normalizedPath\n ? ` path=\"${escapeXmlAttribute(normalizedPath)}\"`\n : \"\";\n return `<resource name=\"${escapeXmlAttribute(input.name)}\" scope=\"${escapeXmlAttribute(input.scope)}\"${pathAttr}>\\n${content}\\n</resource>`;\n}\n\nfunction isAutoLoadedInstructionPath(path: string): boolean {\n const normalized = normalizeResourcePathForPrompt(path);\n return normalized.startsWith(\"instructions/\") && normalized.endsWith(\".md\");\n}\n\nfunction isSpecialPromptResourcePath(path: string): boolean {\n const normalized = normalizeResourcePathForPrompt(path);\n return (\n normalized === \"AGENTS.md\" ||\n normalized === \"LEARNINGS.md\" ||\n normalized.startsWith(\"instructions/\") ||\n normalized.startsWith(\"skills/\") ||\n normalized.startsWith(\"agents/\") ||\n normalized.startsWith(\"remote-agents/\") ||\n normalized.startsWith(\"jobs/\") ||\n normalized.startsWith(\"memory/\")\n );\n}\n\nfunction isTextLikeResource(mimeType: string): boolean {\n return (\n mimeType.startsWith(\"text/\") ||\n mimeType === \"application/json\" ||\n mimeType === \"application/yaml\" ||\n mimeType === \"application/x-yaml\"\n );\n}\n\nfunction getResourceSummaryFromContent(content: string): string | null {\n const frontmatter = parseFrontmatter(content);\n const title =\n getFrontmatterValue(frontmatter, \"title\") ||\n getFrontmatterValue(frontmatter, \"name\");\n const description = getFrontmatterValue(frontmatter, \"description\");\n if (title && description) return `${title}: ${description}`;\n if (title) return title;\n if (description) return description;\n\n const heading = content\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .find((line) => /^#{1,3}\\s+\\S/.test(line));\n if (heading) return heading.replace(/^#{1,3}\\s+/, \"\").trim();\n return null;\n}\n\nfunction resourceScopeForOwner(owner: string, currentOwner?: string): string {\n if (owner === WORKSPACE_OWNER) return \"workspace\";\n if (owner === SHARED_OWNER) return \"shared\";\n if (currentOwner && owner === currentOwner) return \"personal\";\n return \"resource\";\n}\n\nasync function loadAgentsResourceForPrompt(\n owner: string,\n scope: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n): Promise<string | null> {\n try {\n const agents = await resourceGetByPath(owner, \"AGENTS.md\");\n if (!agents?.content?.trim()) return null;\n return promptResourceBlock({\n name: \"AGENTS.md\",\n scope,\n path: \"AGENTS.md\",\n content: agents.content,\n maxChars,\n });\n } catch {\n return null;\n }\n}\n\nasync function loadInstructionResourcesForPrompt(\n owner: string,\n scope: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n): Promise<string[]> {\n try {\n const resources = await resourceList(owner, \"instructions/\");\n const blocks: string[] = [];\n const sorted = resources\n .filter((resource) => isAutoLoadedInstructionPath(resource.path))\n .sort((a, b) => a.path.localeCompare(b.path));\n for (const resource of sorted) {\n const full = await resourceGet(resource.id).catch(() => null);\n if (!full?.content?.trim()) continue;\n const block = promptResourceBlock({\n name: resource.path,\n scope,\n path: resource.path,\n content: full.content,\n maxChars,\n });\n if (block) blocks.push(block);\n }\n return blocks;\n } catch {\n return [];\n }\n}\n\nasync function loadResourceSkillsPromptBlock(\n owner: string,\n): Promise<string | null> {\n try {\n const resources =\n owner === SHARED_OWNER\n ? [\n ...(await resourceList(SHARED_OWNER, \"skills/\")),\n ...(await resourceList(WORKSPACE_OWNER, \"skills/\")),\n ]\n : await resourceListAccessible(owner, \"skills/\");\n const sorted = resources.sort((a, b) => {\n const ownerOrder =\n (a.owner === owner\n ? 0\n : a.owner === SHARED_OWNER\n ? 1\n : a.owner === WORKSPACE_OWNER\n ? 2\n : 3) -\n (b.owner === owner\n ? 0\n : b.owner === SHARED_OWNER\n ? 1\n : b.owner === WORKSPACE_OWNER\n ? 2\n : 3);\n if (ownerOrder !== 0) return ownerOrder;\n return a.path.localeCompare(b.path);\n });\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const resource of sorted) {\n const full = await resourceGet(resource.id).catch(() => null);\n if (!full?.content) continue;\n const meta = parseSkillFrontmatter(full.content);\n if (meta.userInvocable === false) continue;\n const name = meta.name || getSkillNameFromPath(resource.path);\n if (!name || seen.has(name)) continue;\n seen.add(name);\n const scope = resourceScopeForOwner(resource.owner, owner);\n const description = meta.description || \"(no description)\";\n lines.push(\n `- \\`${name}\\` at resource \\`${resource.path}\\` (${scope}) - ${ensureSentence(description)} ${resourceToolHint(\n \"read\",\n `\\`path: \"${resource.path}\"\\` and \\`scope: \"${scope}\"\\` before starting a task it applies to`,\n )}`,\n );\n }\n if (lines.length === 0) return null;\n return `<resource-skills>\\nThe following workspace skills are available in addition to codebase skills. They may come from SQL resources, Dispatch workspace resources, or local file mode. Read a matching skill before starting a task it applies to.\\n\\n${lines.join(\"\\n\")}\\n</resource-skills>`;\n } catch {\n return null;\n }\n}\n\nasync function loadResourceIndexForPrompt(\n owner: string,\n scope: \"workspace\" | \"shared\",\n): Promise<string | null> {\n try {\n const resources = (await resourceList(owner))\n .filter(\n (resource) =>\n !isSpecialPromptResourcePath(resource.path) &&\n isTextLikeResource(resource.mimeType),\n )\n .sort((a, b) => a.path.localeCompare(b.path));\n if (resources.length === 0) return null;\n\n const listed = resources.slice(0, SHARED_RESOURCE_INDEX_LIMIT);\n const lines: string[] = [];\n for (const resource of listed) {\n const full = await resourceGet(resource.id).catch(() => null);\n const summary = full?.content\n ? getResourceSummaryFromContent(full.content)\n : null;\n lines.push(`- \\`${resource.path}\\`${summary ? ` - ${summary}` : \"\"}`);\n }\n if (resources.length > listed.length) {\n lines.push(\n `- ...${resources.length - listed.length} more ${scope} resources. ${resourceToolHint(\n \"list\",\n `\\`scope: \"${scope}\"\\` to inspect them`,\n )}`,\n );\n }\n\n const label =\n scope === \"workspace\"\n ? \"Workspace reference resources are inherited by every app and are available for company, brand, positioning, persona, product, or domain context.\"\n : \"Shared app/organization reference resources are available for app-specific or team context.\";\n return `<workspace-resources scope=\"${scope}\">\\n${label} ${resourceToolHint(\n \"read\",\n `\\`path: <path>\\` and \\`scope: \"${scope}\"\\` when a task may depend on them`,\n )} Do not assume their contents without reading the relevant file.\\n\\n${lines.join(\"\\n\")}\\n</workspace-resources>`;\n } catch {\n return null;\n }\n}\n\n/**\n * Wraps a core CLI script (that writes to console.log) as a ActionEntry\n * by capturing stdout. Uses an AsyncLocalStorage-backed capture so\n * concurrent tool calls do not corrupt the global console/stdout pointers\n * (see `cli-capture.ts`).\n */\nfunction wrapCliScript(\n tool: ActionTool,\n cliDefault: (args: string[]) => Promise<void>,\n opts?: { readOnly?: boolean },\n): ActionEntry {\n return {\n tool,\n ...(opts?.readOnly ? { readOnly: true as const } : {}),\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n for (const [k, v] of Object.entries(args)) {\n const raw = v as unknown;\n const value =\n raw != null && typeof raw === \"object\"\n ? JSON.stringify(raw)\n : String(raw);\n cliArgs.push(`--${k}`, value);\n }\n return captureCliOutput(() => cliDefault(cliArgs));\n },\n };\n}\n\nfunction filterReadOnlyActions(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => entry.readOnly === true),\n );\n}\n\n/** Drop actions that opted out of agent exposure via `agentTool: false`. They\n * remain callable from the frontend / HTTP (mounted separately from this\n * agent tool surface — see `httpActions`) but never appear in any agent tool\n * list (in-app assistant, MCP, A2A, job/trigger runners) or actions prompt.\n * Default-allow: only an explicit `false` is excluded. */\nfunction filterAgentTools(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => entry.agentTool !== false),\n );\n}\n\nfunction filterPublicAgentActions(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => {\n const config = entry.publicAgent;\n return (\n config?.expose === true &&\n config.readOnly === true &&\n config.requiresAuth !== true &&\n config.isConsequential !== true\n );\n }),\n );\n}\n\nexport function buildPublicAgentA2ASkills(\n actions: Record<string, ActionEntry>,\n): Array<{\n id: string;\n name: string;\n description: string;\n publicAgent: ActionEntry[\"publicAgent\"];\n}> {\n return Object.entries(filterPublicAgentActions(actions)).map(\n ([name, entry]) => ({\n id: name,\n name,\n description: entry.tool.description,\n publicAgent: entry.publicAgent,\n }),\n );\n}\n\nfunction resolveArtifactBaseUrl(event: any | undefined): string | undefined {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(String(fromEnv));\n\n try {\n const proto = getHeader(event, \"x-forwarded-proto\") || \"https\";\n const host = getHeader(event, \"host\");\n if (host) return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {}\n\n return undefined;\n}\n\nexport function assembleA2AFinalResponse(\n events: readonly AgentChatEvent[],\n toolResults: readonly A2AToolResultSummary[],\n options: A2AArtifactResponseOptions & { event?: any } = {},\n): { responseText: string; finalText: string } {\n const responseText = collectFinalResponseTextFromAgentEvents(events);\n const finalText = appendA2AArtifactLinks(responseText, [...toolResults], {\n baseUrl: options.baseUrl ?? resolveArtifactBaseUrl(options.event),\n includeReferencedArtifacts: true,\n });\n return { responseText, finalText };\n}\n\n/**\n * Creates the `get-framework-context` tool. Returns detailed instructions\n * for framework capabilities that are summarized in the compact prompt.\n * The agent calls this on-demand when it needs specifics about embeds,\n * agent teams, recurring jobs, etc.\n */\nfunction createFrameworkContextEntry(): Record<string, ActionEntry> {\n const topicList = Object.keys(FRAMEWORK_CONTEXT_SECTIONS).join(\", \");\n return {\n \"get-framework-context\": {\n tool: {\n description: `Read detailed framework instructions for a specific capability. Available topics: ${topicList}. Call with topic=\"all\" to get everything.`,\n parameters: {\n type: \"object\" as const,\n properties: {\n topic: {\n type: \"string\",\n description: `Topic to read. One of: ${topicList}, or \"all\" for everything.`,\n },\n },\n required: [\"topic\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const topic = String(args.topic ?? \"all\").toLowerCase();\n if (topic === \"all\") {\n return Object.values(FRAMEWORK_CONTEXT_SECTIONS).join(\"\\n\\n\");\n }\n const section = FRAMEWORK_CONTEXT_SECTIONS[topic];\n if (!section) {\n return `Unknown topic \"${topic}\". Available: ${topicList}`;\n }\n return section;\n },\n readOnly: true,\n },\n };\n}\n\n/**\n * Creates the `refresh-screen` tool. Writes a bump to `application_state`\n * under a well-known key; the client's `useDbSync` watches for this and\n * invalidates react-query caches so the on-screen UI re-fetches its data\n * without a full page reload.\n *\n * This is the standard way for the agent to say \"the data on the screen\n * just changed, please refresh it\" — e.g. after editing a dashboard config,\n * updating a form schema, or mutating a row that the current view renders.\n */\nfunction createRefreshScreenEntry(): Record<string, ActionEntry> {\n return {\n \"refresh-screen\": {\n // Writes __screen_refresh__ to application_state, which emits its own\n // distinct `screen-refresh` poll event. Don't double-emit a generic\n // `action` event on top of that.\n readOnly: true,\n tool: {\n description:\n \"Manually refresh the user's current screen. The framework ALREADY auto-refreshes after any successful mutating action tool call (template actions, db-exec, db-patch) — you do NOT need to call this after a normal action. Use it only when (a) you mutated data via a path the framework can't detect (e.g. a direct write to an external system the app mirrors), or (b) you want to pass a `scope` hint so the UI narrows which queries to refetch. The UI re-fetches its queries without a full page reload.\",\n parameters: {\n type: \"object\",\n properties: {\n scope: {\n type: \"string\",\n description:\n \"Optional hint describing what changed (e.g. 'dashboard', 'form', 'settings'). Templates may use it to narrow which queries to invalidate; if omitted, all queries are invalidated.\",\n },\n },\n },\n },\n run: async (args) => {\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n const nonce = Date.now();\n const scope = typeof args?.scope === \"string\" ? args.scope : undefined;\n await writeAppState(SCREEN_REFRESH_KEY, {\n nonce,\n ...(scope ? { scope } : {}),\n });\n return `refreshed${scope ? ` (scope: ${scope})` : \"\"}`;\n },\n },\n };\n}\n\n/** Well-known application-state key used by the refresh-screen tool. */\nconst SCREEN_REFRESH_KEY = \"__screen_refresh__\";\nconst SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;\n\nfunction appStateKeyForBrowserTab(key: string, browserTabId: unknown): string {\n if (typeof browserTabId !== \"string\") return key;\n const trimmed = browserTabId.trim();\n return SAFE_BROWSER_TAB_ID_RE.test(trimmed) ? `${key}:${trimmed}` : key;\n}\n\n/**\n * In-memory rate-limit tracker for `/generate-title`. Keyed by user email,\n * value is recent invocation timestamps within the rolling window. Stale\n * entries are pruned on read.\n */\nconst generateTitleRateLimit = new Map<string, number[]>();\n\n/**\n * Creates the `set-search-params` / `set-url-path` tools. Writes a one-shot\n * URL command to application_state; the client's URLSync component applies\n * it via react-router (no full page reload) and then deletes the command.\n *\n * This is how the agent edits URL state — filter query params, route\n * changes, hash — without needing a per-template navigate action. The\n * current URL is visible to the agent via the auto-injected `<current-url>`\n * block, which includes parsed search params.\n */\nfunction createUrlTools(): Record<string, ActionEntry> {\n return {\n \"set-search-params\": {\n // Writes __set_url__ to application_state, which the app-state watcher\n // already surfaces as a poll event. No need to double-emit.\n readOnly: true,\n tool: {\n description:\n \"Update the URL query string on the user's current page. Use this to change dashboard/list filters, search terms, or any other state the app stores in `?foo=bar` style query params. One-shot — the UI applies it in ~1s without a page reload. See the current URL + parsed search params in the auto-injected `<current-url>` block. Keys are the exact query param names as they appear in the URL (e.g. `f_pubDateStart`, not just `pubDateStart`). Set a value to null or empty string to clear that param. By default merges over existing params — pass `merge: false` to replace them all.\",\n parameters: {\n type: \"object\",\n properties: {\n params: {\n type: \"object\",\n description:\n 'Map of query param → value. Each value is a string, or null/\"\" to clear. Example: {\"f_pubDateStart\": null, \"f_cadence\": \"MONTH\"}.',\n },\n merge: {\n type: \"string\",\n description:\n '\"true\" (default) merges over existing params; \"false\" replaces them entirely.',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"params\"],\n },\n },\n run: async (args) => {\n const params = (args?.params ?? {}) as unknown as Record<\n string,\n string | null\n >;\n const merge = (args as any)?.merge !== \"false\";\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"__set_url__\",\n getRequestRunContext()?.browserTabId,\n ),\n {\n searchParams: params,\n mergeSearchParams: merge,\n // Unique-per-write token. The client's URLSync hook dedups by this\n // so a fire-and-forget DELETE that loses its race against the next\n // polling refetch can't cause the same URL command to be applied\n // repeatedly (which caused the editor to bounce between slides\n // when an agent turn errored partway through).\n _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n },\n );\n const keys = Object.keys(params);\n return `set-search-params: ${keys.length} key${keys.length === 1 ? \"\" : \"s\"}${merge ? \"\" : \" (replace)\"}`;\n },\n },\n \"set-url-path\": {\n // Same as set-search-params — writes application_state, already emits\n // via the app-state watcher.\n readOnly: true,\n tool: {\n description:\n \"Navigate the user to a different pathname, optionally also setting search params. For most template-specific routing prefer the template's `navigate` action if it exists — this is the generic fallback. One-shot, applied by the client without a page reload.\",\n parameters: {\n type: \"object\",\n properties: {\n pathname: {\n type: \"string\",\n description: \"New URL pathname (e.g. '/adhoc/weekly').\",\n },\n params: {\n type: \"object\",\n description:\n 'Optional query params to set alongside the path change. String values set, null/\"\" clears.',\n },\n merge: {\n type: \"string\",\n description:\n '\"true\" (default) merges over existing params; \"false\" starts fresh.',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"pathname\"],\n },\n },\n run: async (args) => {\n const pathname = String(args?.pathname ?? \"\");\n if (!pathname.startsWith(\"/\")) {\n return \"Error: pathname must start with '/'.\";\n }\n const params = (args?.params ?? {}) as unknown as Record<\n string,\n string | null\n >;\n const merge = (args as any)?.merge !== \"false\";\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"__set_url__\",\n getRequestRunContext()?.browserTabId,\n ),\n {\n pathname,\n searchParams: params,\n mergeSearchParams: merge,\n // See note in set-search-params: unique-per-write dedup token so a\n // race between GET and consume-DELETE in URLSync can't re-apply\n // this command.\n _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n },\n );\n return `set-url-path: ${pathname}`;\n },\n },\n \"ask-question\": {\n tool: {\n description:\n \"Ask the user a multiple-choice clarifying question and render it inline in the chat. Use this ONLY when you are genuinely blocked on a decision you cannot resolve from context and a wrong guess would be costly — an ambiguous metric, date range, or grain; a real fork in approach. Present 2-5 concrete options and mark the most likely one recommended. Do NOT use it for confirmations, for things the user already specified, or to dodge easy work you could just do. Ask at most once per turn. Calling this yields the turn: stop and wait for the user's answer.\",\n parameters: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description:\n \"The complete question to ask the user. Clear, specific, ends with a question mark.\",\n },\n header: {\n type: \"string\",\n description:\n 'Optional very short label (max ~12 chars) shown as a chip/heading above the question, e.g. \"Date range\", \"Approach\", \"Library\".',\n },\n options: {\n type: \"string\",\n description:\n 'A JSON array of 2-4 distinct, mutually-exclusive options (unless `allowMultiple` is true), each `{ \"label\": string, \"value\"?: string, \"description\"?: string, \"preview\"?: string, \"recommended\"?: boolean }`. `label` is 1-5 words; `description` explains the trade-off; `preview` is optional content (mockup, code snippet, short comparison) rendered under the option. `value` defaults to `label` when omitted. Mark the most likely option `\"recommended\": true`. Do NOT add an \"Other\" option — free text is provided automatically when `allowFreeText` is on.',\n },\n allowFreeText: {\n type: \"string\",\n description:\n 'Whether the user may also type a free-text \"Other\" answer. \"true\" (default) or \"false\".',\n enum: [\"true\", \"false\"],\n },\n allowMultiple: {\n type: \"string\",\n description:\n 'Whether the user may select more than one option (multi-select). \"true\" or \"false\" (default).',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"question\", \"options\"],\n },\n },\n run: async (args) => {\n const question = String(args?.question ?? \"\").trim();\n if (!question) return \"Error: 'question' is required.\";\n const header = String(args?.header ?? \"\").trim();\n const allowMultiple = String(args?.allowMultiple ?? \"\") === \"true\";\n const allowFreeText = String(args?.allowFreeText ?? \"true\") !== \"false\";\n\n let parsedOptions: unknown;\n try {\n parsedOptions = JSON.parse(String(args?.options ?? \"[]\"));\n } catch {\n return \"Error: 'options' must be a JSON array of { label, value?, description?, recommended? }.\";\n }\n if (!Array.isArray(parsedOptions) || parsedOptions.length === 0) {\n return \"Error: 'options' must be a non-empty JSON array of { label, value?, description?, recommended? }.\";\n }\n\n type AskOption = {\n label: string;\n value: string;\n description?: string;\n preview?: string;\n recommended?: boolean;\n };\n const options = parsedOptions\n .map((raw): AskOption | null => {\n const opt = (raw ?? {}) as Record<string, unknown>;\n const label =\n typeof opt.label === \"string\" && opt.label.trim()\n ? opt.label.trim()\n : typeof opt.value === \"string\"\n ? String(opt.value).trim()\n : \"\";\n if (!label) return null;\n const value =\n typeof opt.value === \"string\" && opt.value.trim()\n ? opt.value.trim()\n : label;\n const option: AskOption = { label, value };\n if (typeof opt.description === \"string\" && opt.description.trim()) {\n option.description = opt.description.trim();\n }\n if (typeof opt.preview === \"string\" && opt.preview.trim()) {\n option.preview = opt.preview;\n }\n if (opt.recommended === true) option.recommended = true;\n return option;\n })\n .filter((opt): opt is AskOption => opt !== null);\n if (options.length === 0) {\n return \"Error: 'options' must contain at least one option with a label.\";\n }\n\n // Shape must match the GuidedQuestionFlow renderer in\n // client/guided-questions.tsx: a `text-options` question whose options\n // carry `value`, with `multiSelect` for multi-pick and `allowOther` for\n // free text. The renderer otherwise injects \"Explore\"/\"Decide\" options,\n // which would be noise for a focused clarifying question, so disable them.\n const payload = {\n questions: [\n {\n id: \"q1\",\n type: \"text-options\" as const,\n question,\n ...(header ? { header } : {}),\n required: !allowFreeText,\n multiSelect: allowMultiple,\n allowOther: allowFreeText,\n includeExplore: false,\n includeDecide: false,\n options,\n },\n ],\n };\n\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"guided-questions\",\n getRequestRunContext()?.browserTabId,\n ),\n payload,\n );\n return \"Asked the user a clarifying question and rendered it in the chat. Stop here and wait for their answer — do not proceed or assume an answer.\";\n },\n },\n };\n}\n\n/**\n * Creates db-* tools (db-query, db-exec, db-patch, db-schema) as native tools.\n * These let the agent read and write the app's own SQL database. Scoping to\n * the current user/org is enforced automatically in production via temp views.\n *\n * In dev mode template actions are invoked via bash and the agent can call\n * `pnpm action db-query ...` — but in production there is no bash, so these\n * must be registered as native tools for the agent to reach the app DB at all.\n */\nasync function createDbScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const [schemaMod, queryMod, execMod, patchMod] = await Promise.all([\n import(\"../scripts/db/schema.js\"),\n import(\"../scripts/db/query.js\"),\n import(\"../scripts/db/exec.js\"),\n import(\"../scripts/db/patch.js\"),\n ]);\n\n return {\n \"db-schema\": wrapCliScript(\n {\n description:\n \"Show the app's SQL schema — all tables, columns, types, indexes, and foreign keys. Use this to understand the data model before querying.\",\n parameters: {\n type: \"object\",\n properties: {\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n schemaMod.default,\n { readOnly: true },\n ),\n \"db-query\": wrapCliScript(\n {\n description:\n \"Read from the app's own SQL database ONLY. Runs a SELECT against the app's internal tables (settings, application_state, template tables). Results are auto-scoped to the current user/org. IMPORTANT: This tool CANNOT access external data sources like data warehouses, CRMs, issue trackers, analytics platforms, calendars, mail, docs, or other third-party services. For those, use the relevant template/provider action, MCP connector, or provider-api-catalog/provider-api-docs/provider-api-request when available. If the user names a provider, that named provider wins; do not substitute a warehouse or app database copy unless they explicitly ask for it. If a table isn't in the app schema, don't try db-query — use the data-source-specific action. For extension management, use list-extensions, update-extension, hide-extension, or delete-extension instead of querying the legacy tools table.\",\n parameters: {\n type: \"object\",\n properties: {\n sql: {\n type: \"string\",\n description:\n \"SELECT query to run, e.g. \\\"SELECT key, value FROM settings WHERE key LIKE 'sql-dashboard-%'\\\"\",\n },\n args: {\n type: \"string\",\n description:\n 'Optional JSON array of positional bind args for parameterized placeholders. Example: \\'[\"draft\",\"form-123\"]\\'',\n },\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n limit: {\n type: \"string\",\n description:\n \"Append LIMIT N if the query doesn't already have one\",\n },\n },\n required: [\"sql\"],\n },\n },\n queryMod.default,\n { readOnly: true },\n ),\n \"db-exec\": wrapCliScript(\n {\n description:\n \"Write to the app's own SQL database ONLY. Runs INSERT / UPDATE / DELETE / REPLACE against the app's internal tables. For multiple related writes, pass `statements` so they run sequentially in one transaction instead of issuing several db-exec calls. Writes are auto-scoped to the current user/org, and `owner_email` / `org_id` are auto-injected on INSERT. Schema changes (CREATE/ALTER/DROP) are blocked. Never use this to backfill missing data for a read/analysis request or to create/modify users, members, roles, permissions, admin flags, or ownership; use a dedicated app action or reviewed code. IMPORTANT: This tool CANNOT write to external data sources like BigQuery, HubSpot, etc. For external services, use the appropriate template action.\",\n parameters: {\n type: \"object\",\n properties: {\n sql: {\n type: \"string\",\n description:\n \"Single INSERT / UPDATE / DELETE / REPLACE statement. Use parameterized placeholders (?) where possible.\",\n },\n args: {\n type: \"string\",\n description:\n 'Optional JSON array of positional bind args for `sql`. Example: \\'[\"published\",\"form-123\"]\\'',\n },\n statements: {\n type: \"string\",\n description:\n 'Optional JSON array of write statements to execute in one transaction. Prefer this over multiple db-exec calls. Example: \\'[{\"sql\":\"INSERT INTO notes (id,title) VALUES (?,?)\",\"args\":[\"n1\",\"One\"]},{\"sql\":\"UPDATE counters SET value = value + 1 WHERE key = ?\",\"args\":[\"notes\"]}]\\'',\n },\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n execMod.default,\n ),\n \"db-patch\": wrapCliScript(\n {\n description:\n \"Surgical patch on a large text/JSON column in the app's SQL database. Two modes: (1) text find/replace via `find`/`replace`/`edits` — best for small edits to documents, slide HTML, etc. (2) structural JSON ops via `json-ops` — STRONGLY PREFERRED when the column is JSON (dashboard configs, form schemas, slide decks) because it avoids all the brace/quote/comma surgery that text find/replace requires. Use `json-ops` to set/remove values at a JSON Pointer path, or to move/insert array items — e.g. reorder dashboard panels, add a filter, rename a field. Targets exactly one row (narrow `where` by primary key). Same per-user/org scoping as db-exec.\",\n parameters: {\n type: \"object\",\n properties: {\n table: {\n type: \"string\",\n description: \"Table name (e.g. 'settings')\",\n },\n column: {\n type: \"string\",\n description:\n \"Text/JSON column to patch (e.g. 'value' for settings)\",\n },\n where: {\n type: \"string\",\n description:\n \"WHERE clause that matches exactly one row (e.g. \\\"key = 'o:org1:sql-dashboard-foo'\\\")\",\n },\n find: {\n type: \"string\",\n description:\n \"Text mode: substring to find. Must match EXACTLY ONE occurrence by default (like Claude Code's Edit tool). If 0 matches, you get 'NOT FOUND'. If >1 matches, you get surrounding context for each match — widen `find` with unique context and retry. Use `all: \\\"true\\\"` to replace every occurrence.\",\n },\n replace: {\n type: \"string\",\n description: \"Text mode: replacement substring\",\n },\n edits: {\n type: \"string\",\n description:\n 'Text mode batch: JSON array of {find, replace} pairs. Same uniqueness rule applies to each `find`. Example: \\'[{\"find\":\"a\",\"replace\":\"b\"}]\\'',\n },\n \"json-ops\": {\n type: \"string\",\n description:\n 'JSON mode: JSON array of structural ops. Each op is {op, path, value?, from?}. `op` is one of \"set\", \"remove\", \"insert\", \"move\", \"move-before\". `path` / `from` use JSON Pointer (\"/panels/3/title\"). Examples — reorder: \\'[{\"op\":\"move\",\"from\":\"/panels/7\",\"path\":\"/panels/1\"}]\\'; edit field: \\'[{\"op\":\"set\",\"path\":\"/panels/0/title\",\"value\":\"New\"}]\\'; delete filter: \\'[{\"op\":\"remove\",\"path\":\"/filters/2\"}]\\'; add panel: \\'[{\"op\":\"insert\",\"path\":\"/panels/0\",\"value\":{\"id\":\"p\",\"title\":\"...\"}}]\\'. Much safer than text find/replace for JSON columns.',\n },\n all: {\n type: \"string\",\n description:\n 'Text mode: set to \"true\" to replace every occurrence of each `find` (default requires exactly one match)',\n enum: [\"true\"],\n },\n },\n required: [\"table\", \"column\", \"where\"],\n },\n },\n patchMod.default,\n ),\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the docs-search tool so agents can look up framework documentation.\n * Docs are bundled in @agent-native/core and read via fs at runtime.\n */\nasync function createDocsScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/docs/search.js\");\n return {\n \"docs-search\": wrapCliScript(\n {\n description:\n \"Search and read agent-native framework documentation, bundled AGENTS.md, and codebase skills. Use --list to see all pages, --query to search, --slug to read a specific page. Codebase skill pages use slugs like skill-<name>.\",\n parameters: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description:\n \"Search term to find relevant docs (e.g. 'actions', 'authentication', 'database')\",\n },\n slug: {\n type: \"string\",\n description:\n \"Read a specific doc page by slug (e.g. 'actions', 'authentication', 'database')\",\n },\n list: {\n type: \"string\",\n description: 'Set to \"true\" to list all available doc pages',\n enum: [\"true\"],\n },\n },\n },\n },\n mod.default,\n { readOnly: true },\n ),\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates resource ScriptEntries available in both prod and dev modes.\n */\nfunction shouldDefaultResourceWriteToWorkspace(path: string): boolean {\n const normalized = path.replace(/^\\/+/, \"\");\n return (\n normalized === \"AGENTS.md\" ||\n normalized === \"LEARNINGS.md\" ||\n normalized.startsWith(\"memory/\") ||\n normalized.startsWith(\"skills/\") ||\n normalized.startsWith(\"jobs/\") ||\n normalized.startsWith(\"agents/\") ||\n normalized.startsWith(\"remote-agents/\")\n );\n}\n\nasync function createResourceScriptEntries(): Promise<\n Record<string, ActionEntry>\n> {\n try {\n const [list, read, effective, write, del, saveMem, delMem, store] =\n await Promise.all([\n import(\"../scripts/resources/list.js\"),\n import(\"../scripts/resources/read.js\"),\n import(\"../scripts/resources/effective.js\"),\n import(\"../scripts/resources/write.js\"),\n import(\"../scripts/resources/delete.js\"),\n import(\"../scripts/resources/save-memory.js\"),\n import(\"../scripts/resources/delete-memory.js\"),\n import(\"../resources/store.js\"),\n ]);\n\n // Wrap each CLI runner so it captures stdout and converts args properly\n const listEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n list.default,\n { readOnly: true },\n );\n const readEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n read.default,\n { readOnly: true },\n );\n const writeEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n write.default,\n );\n const effectiveEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n effective.default,\n { readOnly: true },\n );\n const deleteEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n del.default,\n );\n\n return {\n resources: {\n tool: {\n description:\n 'Manage workspace resources. Actions: \"list\" (browse visible files), \"read\" (get contents), \"effective\" (show workspace -> organization/app -> personal inheritance for a path), \"write\" (create/update personal or shared; workspace only for local file mode control files), \"promote\" (make agent scratch visible), \"delete\" (remove personal or shared; workspace only for local file mode control files). Agent scratch writes are hidden from the Workspace view by default; use visibility=\"workspace\" only for files the user explicitly wants to keep/manage.',\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n description: \"The operation to perform\",\n enum: [\n \"list\",\n \"read\",\n \"effective\",\n \"write\",\n \"promote\",\n \"delete\",\n ],\n },\n path: {\n type: \"string\",\n description:\n \"Resource path (e.g. 'LEARNINGS.md', 'notes/ideas.md'). Required for read/write/delete.\",\n },\n content: {\n type: \"string\",\n description: \"Content to write. Required for write.\",\n },\n scope: {\n type: \"string\",\n description:\n \"personal, shared, workspace, or all (default varies by action). Workspace is read-only when inherited from Dispatch; in local file mode AGENTS.md, agent-native.json, mcp.config.json, .mcp.json, and skills/ are writable.\",\n enum: [\"personal\", \"shared\", \"workspace\", \"all\"],\n },\n prefix: {\n type: \"string\",\n description:\n \"Filter by path prefix when listing (e.g. 'notes/')\",\n },\n mime: {\n type: \"string\",\n description:\n \"MIME type for write (default: inferred from extension)\",\n },\n format: {\n type: \"string\",\n description:\n 'Output format for list: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n visibility: {\n type: \"string\",\n description:\n 'Visibility for write: \"agent_scratch\" for internal working files, \"workspace\" for user-requested files. Defaults to agent_scratch except durable instruction/skill/job/memory paths.',\n enum: [\"workspace\", \"agent_scratch\"],\n },\n includeAgentScratch: {\n type: \"boolean\",\n description: \"Include hidden agent scratch files when listing.\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const { action: a, ...rest } = args;\n if (a === \"list\") return listEntry.run(rest);\n if (a === \"read\") {\n if (!rest.path) return \"Error: path is required for read\";\n return readEntry.run(rest);\n }\n if (a === \"effective\") {\n if (!rest.path) return \"Error: path is required for effective\";\n return effectiveEntry.run(rest);\n }\n if (a === \"write\") {\n if (\n !rest.path ||\n rest.content === undefined ||\n rest.content === null\n )\n return \"Error: path and content are required for write\";\n rest.createdBy = \"agent\";\n rest.visibility =\n rest.visibility ??\n (shouldDefaultResourceWriteToWorkspace(String(rest.path))\n ? \"workspace\"\n : \"agent_scratch\");\n const runCtx = getRequestRunContext();\n if (runCtx?.threadId) rest.threadId = runCtx.threadId;\n return writeEntry.run(rest);\n }\n if (a === \"promote\") {\n if (!rest.path) return \"Error: path is required for promote\";\n const scope = rest.scope ?? \"personal\";\n if (scope === \"workspace\" || scope === \"all\") {\n return \"Error: promote supports personal or shared scope only\";\n }\n const owner =\n scope === \"shared\"\n ? store.SHARED_OWNER\n : (getRequestRunContext()?.owner ??\n getRequestUserEmail() ??\n process.env.AGENT_USER_EMAIL);\n if (!owner) {\n return \"Error: promote requires an authenticated user\";\n }\n const resource = await store.resourceGetByPath(\n owner,\n String(rest.path),\n );\n if (!resource) {\n return `Resource not found: ${rest.path}`;\n }\n const promoted = await store.resourcePut(\n owner,\n resource.path,\n resource.content,\n resource.mimeType,\n {\n createdBy: resource.createdBy,\n visibility: \"workspace\",\n threadId: resource.threadId,\n runId: resource.runId,\n expiresAt: null,\n metadata: resource.metadata,\n },\n );\n return `Promoted resource: ${promoted.path}`;\n }\n if (a === \"delete\") {\n if (!rest.path) return \"Error: path is required for delete\";\n return deleteEntry.run(rest);\n }\n return `Error: unknown action \"${a}\". Use: list, read, write, promote, delete`;\n },\n },\n \"save-memory\": wrapCliScript(\n {\n description:\n \"Save a memory for future conversations. Creates or updates a memory file and its index entry. Use proactively when you learn preferences, corrections, project context, or references.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description:\n \"Short kebab-case identifier (e.g. 'coding-style', 'deploy-process'). Used as the filename.\",\n },\n type: {\n type: \"string\",\n description: \"Memory category\",\n enum: [\"user\", \"feedback\", \"project\", \"reference\"],\n },\n description: {\n type: \"string\",\n description:\n \"One-line summary shown in the memory index (keep under 80 chars)\",\n },\n content: {\n type: \"string\",\n description:\n \"The memory content in markdown. For updates, read first and provide full updated content.\",\n },\n },\n required: [\"name\", \"type\", \"description\", \"content\"],\n },\n },\n saveMem.default,\n ),\n \"delete-memory\": wrapCliScript(\n {\n description:\n \"Delete a memory entry and remove it from the memory index.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"The memory name to delete (e.g. 'coding-style')\",\n },\n },\n required: [\"name\"],\n },\n },\n delMem.default,\n ),\n };\n } catch {\n // Resources not available — skip silently\n return {};\n }\n}\n\n/**\n * Creates a unified chat-history ActionEntry that dispatches to search, open,\n * rename, or lightweight organization actions.\n */\nasync function createChatScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const [searchMod, openMod] = await Promise.all([\n import(\"../scripts/chat/search-chats.js\"),\n import(\"../scripts/chat/open-chat.js\"),\n ]);\n\n const searchEntry = wrapCliScript(\n {\n description: \"Search or list past agent chat threads.\",\n parameters: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description:\n \"Search term to find chats by title, preview, or content\",\n },\n limit: {\n type: \"string\",\n description: \"Max number of results (default: 20)\",\n },\n format: {\n type: \"string\",\n description: \"Output format\",\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n searchMod.default,\n );\n\n const openEntry = wrapCliScript(\n {\n description: \"Open a chat thread in the UI.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"The chat thread ID to open\",\n },\n },\n required: [\"id\"],\n },\n },\n openMod.default,\n );\n\n return {\n \"chat-history\": {\n tool: {\n description:\n \"Manage past agent chat threads. Use action 'search' to find previous conversations by keyword, 'open' to open a thread in the UI, or 'rename'/'pin'/'unpin'/'archive' to organize history.\",\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n description: \"The operation to perform\",\n enum: [\"search\", \"open\", \"rename\", \"pin\", \"unpin\", \"archive\"],\n },\n query: {\n type: \"string\",\n description:\n \"(search) Search term to find chats by title, preview, or content\",\n },\n limit: {\n type: \"string\",\n description: \"(search) Max number of results (default: 20)\",\n },\n format: {\n type: \"string\",\n description: \"(search) Output format\",\n enum: [\"json\", \"text\"],\n },\n id: {\n type: \"string\",\n description:\n \"(open, rename, pin, unpin, archive) The chat thread ID to manage\",\n },\n title: {\n type: \"string\",\n description: \"(rename) New chat title\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args) => {\n if (args?.action === \"open\") {\n return openEntry.run(args);\n }\n if (\n args?.action === \"rename\" ||\n args?.action === \"pin\" ||\n args?.action === \"unpin\" ||\n args?.action === \"archive\"\n ) {\n const id = typeof args?.id === \"string\" ? args.id : \"\";\n if (!id) return \"Missing required id.\";\n const owner =\n getRequestRunContext()?.owner ?? getRequestUserEmail() ?? \"\";\n if (!owner) return \"No authenticated user is available.\";\n const thread = await getThread(id);\n if (!thread || thread.ownerEmail !== owner) {\n return `Chat thread \"${id}\" not found.`;\n }\n const title = thread.title || thread.preview || \"(untitled)\";\n if (args.action === \"rename\") {\n const nextTitle =\n typeof args?.title === \"string\"\n ? args.title.replace(/\\s+/g, \" \").trim().slice(0, 160)\n : \"\";\n if (!nextTitle) return \"Missing required title.\";\n const renamed = await renameThread(id, nextTitle, {\n ownerEmail: owner,\n });\n if (!renamed) return `Chat thread \"${id}\" could not be renamed.`;\n return `Renamed chat \"${title}\" to \"${nextTitle}\".`;\n }\n if (args.action === \"archive\") {\n const archived = await setThreadArchived(id, true, {\n ownerEmail: owner,\n });\n if (!archived)\n return `Chat thread \"${id}\" could not be archived.`;\n return `Archived chat: ${title}`;\n }\n const pinned = await setThreadPinned(id, args.action === \"pin\", {\n ownerEmail: owner,\n });\n if (!pinned) return `Chat thread \"${id}\" could not be updated.`;\n return `${args.action === \"pin\" ? \"Pinned\" : \"Unpinned\"} chat: ${title}`;\n }\n return searchEntry.run(args);\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the consolidated manage-agent-engine tool (list / set / test).\n * Let the agent inspect and configure the active LLM engine.\n */\nasync function createAgentEngineScriptEntries(\n appId?: string,\n): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/agent-engines/manage-agent-engine.js\");\n\n return {\n \"manage-agent-engine\": {\n tool: mod.tool,\n run: (args) =>\n mod.run({\n ...args,\n appId:\n typeof args.appId === \"string\" && args.appId.trim()\n ? args.appId\n : (appId ?? \"\"),\n }),\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the manage-agent-loop-settings tool. Lets the agent inspect and\n * configure the loop step limit it may hit on long-running work.\n */\nasync function createAgentLoopSettingsScriptEntries(): Promise<\n Record<string, ActionEntry>\n> {\n try {\n const mod = await import(\"../scripts/manage-agent-loop-settings.js\");\n\n return {\n \"manage-agent-loop-settings\": { tool: mod.tool, run: mod.run },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the call-agent ActionEntry for cross-agent A2A communication.\n * Binds selfAppId so the agent cannot call itself via call-agent.\n */\nasync function createCallAgentScriptEntry(\n selfAppId?: string,\n): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/call-agent.js\");\n return {\n \"call-agent\": {\n tool: mod.tool,\n run: (args, context) => mod.run(args, context, selfAppId),\n },\n };\n } catch {\n return {};\n }\n}\n\nfunction createBuilderBrowserTool(deps: {\n getOrigin: () => string;\n getOwner?: () => string | null | undefined;\n}): Record<string, ActionEntry> {\n const setBuiltinForCurrentUser = async (\n id: BuiltinMcpCapabilityId,\n enabled: boolean,\n ) => {\n const email = getRequestUserEmail();\n if (!email) {\n return {\n ok: false,\n error: \"not-signed-in\",\n message: \"You must be signed in to change built-in MCP tools.\",\n };\n }\n const enabledIds = await setBuiltinMcpCapabilityEnabled(\n \"user\",\n email,\n id,\n enabled,\n );\n const manager = getGlobalMcpManager();\n if (manager) {\n await manager.reconfigure(await buildMergedConfig());\n }\n return { ok: true, enabledIds: enabledIds ?? [] };\n };\n\n const entries: Record<string, ActionEntry> = {\n \"connect-builder\": {\n tool: {\n description:\n \"Render a Builder.io card inline in the chat. Call this as the first step (no code exploration or planning needed) when the user asks to modify the APP'S OWN SOURCE CODE: add a feature, change the UI chrome, edit a React component, add a route, add an integration, fix a bug in the app itself, or anything else that requires source-file edits while in hosted/production mode. Do NOT call this for creating or editing extensions/widgets/dashboards/calculators/mini-apps; those are sandboxed extension data and must use create-extension/update-extension instead. Do NOT call this for content the app is meant to produce — creating a video, generating a design, drafting an email, building a slide deck, making a dashboard, etc. — those run through the app's own domain actions, not Builder. Do NOT mention 'click Send to Builder' in your response unless this card is already in the conversation. If Builder is connected and Builder Cloud Agents are available, the card shows a 'Send to Builder' button that hands the work off to Builder's cloud agent and returns a branch URL. If `builderEnabled` is false, the card shows a waitlist/local-dev fallback instead; never tell the user to enable Builder Cloud Agents in Builder org settings or beta settings, and do not claim the Builder card has everything, is pre-loaded for handoff, or can run the cloud agent. When you call this for a code-change request, pass the user's request verbatim as the `prompt` arg so the card can forward it to Builder unchanged when cloud agents are available.\",\n parameters: {\n type: \"object\",\n properties: {\n prompt: {\n type: \"string\",\n description:\n \"The user's feature / change request, verbatim. Forwarded to Builder's cloud agent when the user clicks Send. Omit only for generic 'connect Builder' requests that aren't tied to a specific code change.\",\n },\n },\n },\n },\n run: async (args) => {\n const { getBuilderCredentialAuthFailure, resolveBuilderCredentials } =\n await import(\"./credential-provider.js\");\n const creds = await resolveBuilderCredentials();\n const authFailure = await getBuilderCredentialAuthFailure(creds);\n const configured = !!(\n creds.privateKey &&\n creds.publicKey &&\n !authFailure\n );\n const branchProjectId = await resolveBuilderBranchProjectId();\n const prompt = typeof args?.prompt === \"string\" ? args.prompt : \"\";\n const origin = deps.getOrigin();\n const ownerEmail = deps.getOwner?.() ?? getRequestUserEmail();\n return JSON.stringify({\n kind: \"connect-builder-card\",\n configured,\n builderEnabled: !!branchProjectId,\n connectUrl: getBuilderBrowserConnectUrlForOwner(origin, ownerEmail),\n orgName: creds.orgName || null,\n prompt,\n });\n },\n },\n \"set-browser-control\": {\n tool: {\n description:\n \"Enable or disable built-in browser-control MCP tools for the current user. Call this when the user asks to test, screenshot, inspect, or interact with a web page and browser tools are not available; confirm once before enabling. Prefer the chrome-devtools backend for live logged-in Chrome, and use playwright when an isolated browser is better.\",\n parameters: {\n type: \"object\",\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Whether browser-control tools should be enabled.\",\n },\n backend: {\n type: \"string\",\n enum: [\"chrome-devtools\", \"playwright\"],\n description:\n \"Browser backend to enable. Defaults to chrome-devtools.\",\n },\n },\n required: [\"enabled\"],\n },\n },\n run: async (args) => {\n const parsed =\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {};\n const enabled = parsed.enabled !== false;\n const requestedBackend =\n typeof parsed.backend === \"string\" ? parsed.backend : undefined;\n const backend =\n requestedBackend === \"playwright\" ? \"playwright\" : \"chrome-devtools\";\n const targetId: BuiltinMcpCapabilityId =\n backend === \"playwright\"\n ? \"browser-playwright\"\n : \"browser-chrome-devtools\";\n\n if (!enabled) {\n const chrome = await setBuiltinForCurrentUser(\n \"browser-chrome-devtools\",\n false,\n );\n if (!chrome.ok) return JSON.stringify(chrome);\n const playwright = await setBuiltinForCurrentUser(\n \"browser-playwright\",\n false,\n );\n return JSON.stringify({\n ...playwright,\n enabled: false,\n message: \"Browser-control MCP tools are disabled.\",\n });\n }\n\n const result = await setBuiltinForCurrentUser(targetId, true);\n return JSON.stringify({\n ...result,\n enabled: true,\n backend,\n message:\n backend === \"chrome-devtools\"\n ? \"Chrome DevTools MCP is enabled. Browser tools will be available on the next action when Chrome remote debugging is available.\"\n : \"Playwright MCP is enabled. Browser tools will be available on the next action in an isolated Playwright browser.\",\n });\n },\n },\n \"set-computer-use\": {\n tool: {\n description:\n \"Enable or disable built-in Computer Use MCP tools for the current user. Call only after the user explicitly asks to let the agent control local desktop apps. macOS may require Screen Recording and Accessibility permissions.\",\n parameters: {\n type: \"object\",\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Whether Computer Use tools should be enabled.\",\n },\n },\n required: [\"enabled\"],\n },\n },\n run: async (args) => {\n const parsed =\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {};\n const enabled = parsed.enabled !== false;\n if (enabled && process.platform !== \"darwin\") {\n return JSON.stringify({\n ok: false,\n error: \"unsupported-platform\",\n message: \"Computer Use is currently available only on macOS.\",\n });\n }\n const result = await setBuiltinForCurrentUser(\"computer-use\", enabled);\n return JSON.stringify({\n ...result,\n enabled,\n message: enabled\n ? \"Computer Use MCP is enabled. If macOS prompts, grant Screen Recording and Accessibility permission in System Settings > Privacy & Security.\"\n : \"Computer Use MCP is disabled.\",\n });\n },\n },\n \"activate-browser\": {\n tool: {\n description:\n \"Activate browser automation tools. Call this when you need to interact with a real browser — e.g. to extract design tokens from a rendered page, take screenshots, read computed styles from JS-heavy sites, or test a live URL. After activation, chrome-devtools MCP tools (navigate, click, evaluate_script, take_screenshot, etc.) become available on your next action. Requires Builder.io connection.\",\n parameters: {\n type: \"object\",\n properties: {\n sessionId: {\n type: \"string\",\n description:\n \"Optional session identifier for the browser connection. Auto-generated if omitted.\",\n },\n },\n },\n },\n run: async (args) => {\n const { resolveBuilderCredentials } =\n await import(\"./credential-provider.js\");\n const creds = await resolveBuilderCredentials();\n if (!creds.privateKey || !creds.publicKey) {\n return JSON.stringify({\n error: \"builder-not-connected\",\n message:\n \"Builder.io is not connected. Call `connect-builder` first to enable browser automation.\",\n });\n }\n\n const { requestBuilderBrowserConnection } =\n await import(\"./builder-browser.js\");\n const sessionId =\n (typeof args?.sessionId === \"string\" && args.sessionId) ||\n `an-browser-${Date.now()}`;\n\n let connection: Record<string, unknown>;\n try {\n connection = await requestBuilderBrowserConnection({ sessionId });\n } catch (err: any) {\n return JSON.stringify({\n error: \"browser-connection-failed\",\n message: `Failed to get browser connection: ${err?.message ?? err}`,\n });\n }\n\n const wsUrl = connection.wsUrl as string;\n if (!wsUrl) {\n return JSON.stringify({\n error: \"no-ws-url\",\n message: \"Browser connection did not return a WebSocket URL.\",\n });\n }\n\n const manager = getGlobalMcpManager();\n if (!manager) {\n return JSON.stringify({\n error: \"no-mcp-manager\",\n message: \"MCP manager is not available.\",\n });\n }\n\n // Add chrome-devtools-mcp server pointing at the provisioned browser\n const currentConfig = manager.getConfig();\n const servers = { ...(currentConfig?.servers ?? {}) };\n servers[\"chrome-devtools\"] = {\n command: \"npx\",\n args: [\n \"-y\",\n \"chrome-devtools-mcp@0.26.0\",\n \"--wsEndpoint\",\n wsUrl,\n \"--categoryEmulation=false\",\n ],\n type: \"stdio\",\n } as any;\n\n await manager.reconfigure({\n servers,\n source: currentConfig?.source ?? \"runtime\",\n });\n\n return JSON.stringify({\n success: true,\n message:\n \"Browser activated. Chrome DevTools MCP tools (mcp__chrome-devtools__*) are now available. Use them on your next action to navigate pages, read DOM, take screenshots, evaluate JavaScript, etc.\",\n wsUrl,\n sessionId,\n });\n },\n },\n };\n\n if (!areBuiltinMcpCapabilitiesSupported()) {\n delete entries[\"set-browser-control\"];\n delete entries[\"set-computer-use\"];\n }\n\n return entries;\n}\n\n/**\n * Creates the unified `agent-teams` tool that consolidates all sub-agent\n * orchestration behind a single tool with an `action` parameter.\n */\nfunction createTeamTools(deps: {\n getOwner: () => string;\n getSystemPrompt: () => string;\n getActions: () => Record<string, ActionEntry>;\n getEngine: () => AgentEngine;\n getModel: () => string;\n getParentThreadId: () => string;\n getSend: () =>\n | ((event: import(\"../agent/types.js\").AgentChatEvent) => void)\n | null;\n}): Record<string, ActionEntry> {\n return {\n \"agent-teams\": {\n tool: {\n description:\n \"Manage background sub-agent tasks. Use action 'spawn' to start a new sub-agent, 'status' to check progress, 'read-result' to get a finished task's output, 'send' to message a running sub-agent, or 'list' to see all tasks. A successful spawn only means the task started and is running; do not report it as finished until status/read-result shows a terminal status.\",\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n enum: [\"spawn\", \"status\", \"read-result\", \"send\", \"list\"],\n description: \"The operation to perform\",\n },\n task: {\n type: \"string\",\n description:\n \"(spawn) Clear description of what the sub-agent should accomplish\",\n },\n instructions: {\n type: \"string\",\n description:\n \"(spawn) Optional additional instructions or context for the sub-agent\",\n },\n name: {\n type: \"string\",\n description:\n \"(spawn) Short name for the sub-agent tab (e.g. 'Research', 'Draft email'). If omitted, derived from the task.\",\n },\n agent: {\n type: \"string\",\n description:\n \"(spawn) Optional custom agent profile from agents/*.md to use for this task.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"(status, read-result, send) The task ID returned by a previous spawn\",\n },\n message: {\n type: \"string\",\n description: \"(send) Message to send to the sub-agent\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const action = args.action;\n\n // ── spawn ──────────────────────────────────────────────\n if (action === \"spawn\") {\n if (!args.task) throw new Error(\"'task' is required for spawn\");\n // Capture the send function NOW (at spawn time) so that\n // concurrent runs don't clobber each other's send reference.\n const capturedSend = deps.getSend();\n const { spawnTask } = await import(\"./agent-teams.js\");\n // Filter out the team tool so sub-agents can't spawn sub-agents\n const subAgentActions = Object.fromEntries(\n Object.entries(deps.getActions()).filter(\n ([name]) => name !== \"agent-teams\",\n ),\n );\n let instructions = args.instructions;\n let selectedModel = deps.getModel();\n let selectedName = args.name || \"\";\n if (args.agent) {\n const { findAccessibleCustomAgent } =\n await import(\"../resources/agents.js\");\n const profile = await findAccessibleCustomAgent(\n deps.getOwner(),\n args.agent,\n );\n if (!profile) {\n throw new Error(`Custom agent not found: ${args.agent}`);\n }\n const profileInstructions =\n `## Custom Agent Profile: ${profile.name}\\n\\n` +\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\n profile.instructions;\n instructions = instructions\n ? `${profileInstructions}\\n\\n## Extra Task Context\\n\\n${instructions}`\n : profileInstructions;\n selectedModel = profile.model ?? selectedModel;\n selectedName = selectedName || profile.name;\n }\n const task = await spawnTask({\n description: args.task,\n instructions,\n ownerEmail: deps.getOwner(),\n systemPrompt: deps.getSystemPrompt(),\n actions: subAgentActions,\n engine: deps.getEngine(),\n model: selectedModel,\n name: selectedName || undefined,\n parentThreadId: deps.getParentThreadId(),\n parentSend: (event) => {\n if (capturedSend) capturedSend(event);\n },\n });\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n runId: task.runId,\n status: task.status,\n parentThreadId: task.parentThreadId,\n state: \"launched_pending_completion\",\n message:\n \"Sub-agent launched and is still running. Use status or read-result later; do not describe this task as completed from the spawn response alone.\",\n description: task.description,\n name: task.name ?? selectedName,\n });\n }\n\n // ── status ─────────────────────────────────────────────\n if (action === \"status\") {\n if (!args.taskId) throw new Error(\"'taskId' is required for status\");\n const { getTask } = await import(\"./agent-teams.js\");\n const task = await getTask(args.taskId);\n if (!task) return JSON.stringify({ error: \"Task not found\" });\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n status: task.status,\n description: task.description,\n name: task.name,\n preview: task.preview,\n currentStep: task.currentStep,\n summary: task.summary,\n });\n }\n\n // ── read-result ────────────────────────────────────────\n if (action === \"read-result\") {\n if (!args.taskId)\n throw new Error(\"'taskId' is required for read-result\");\n const { getTask } = await import(\"./agent-teams.js\");\n const task = await getTask(args.taskId);\n if (!task) return JSON.stringify({ error: \"Task not found\" });\n if (task.status === \"running\") {\n return JSON.stringify({\n status: \"running\",\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n name: task.name,\n preview: task.preview,\n message:\n \"Task is still running. Do not report it as complete; use status/read-result later.\",\n });\n }\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n name: task.name,\n status: task.status,\n summary: task.summary,\n preview: task.preview,\n });\n }\n\n // ── send ───────────────────────────────────────────────\n if (action === \"send\") {\n if (!args.taskId) throw new Error(\"'taskId' is required for send\");\n if (!args.message) throw new Error(\"'message' is required for send\");\n const { sendToTask } = await import(\"./agent-teams.js\");\n const result = await sendToTask(args.taskId, args.message);\n return JSON.stringify(result);\n }\n\n // ── list ───────────────────────────────────────────────\n if (action === \"list\") {\n const { listTasks } = await import(\"./agent-teams.js\");\n const tasks = await listTasks();\n if (tasks.length === 0) {\n return \"No sub-agent tasks.\";\n }\n return JSON.stringify(\n tasks.map((t) => ({\n taskId: t.taskId,\n threadId: t.threadId,\n parentThreadId: t.parentThreadId,\n name: t.name,\n description: t.description,\n status: t.status,\n currentStep: t.currentStep,\n hasResult: t.summary.length > 0,\n })),\n null,\n 2,\n );\n }\n\n throw new Error(\n `Unknown action '${action}'. Use one of: spawn, status, read-result, send, list`,\n );\n },\n },\n };\n}\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nexport interface AgentChatPluginOptions {\n /** Template-specific actions (email ops, booking ops, etc.) */\n actions?:\n | Record<string, ActionEntry>\n | (() =>\n | Record<string, ActionEntry>\n | Promise<Record<string, ActionEntry>>);\n /** @deprecated Use `actions` instead */\n scripts?:\n | Record<string, ActionEntry>\n | (() =>\n | Record<string, ActionEntry>\n | Promise<Record<string, ActionEntry>>);\n /** System prompt for the agent. A sensible default is provided. */\n systemPrompt?: string;\n /** Additional system prompt prepended in dev mode */\n devSystemPrompt?: string;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Optional per-app agent run chunk budget in milliseconds. Defaults to\n * AGENT_RUN_SOFT_TIMEOUT_MS when set, otherwise no framework-imposed\n * timeout. When reached, long runs continue through the hidden continuation\n * path instead of surfacing a timeout warning. */\n runSoftTimeoutMs?: number;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var */\n apiKey?: string;\n /**\n * Agent engine to use. Can be a pre-constructed AgentEngine, a registered\n * engine name (e.g. \"anthropic\", \"ai-sdk:openai\"), or an object with name\n * and config. Defaults to the \"anthropic\" engine using ANTHROPIC_API_KEY.\n */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Route path. Default: /_agent-native/agent-chat */\n path?: string;\n /** Custom mention providers for @-tagging template entities */\n mentionProviders?:\n | Record<string, MentionProvider>\n | (() =>\n | Record<string, MentionProvider>\n | Promise<Record<string, MentionProvider>>);\n /** App ID used to exclude self from agent discovery (e.g., \"mail\", \"calendar\") */\n appId?: string;\n /** Optional MCP server branding surfaced during the initialize handshake. */\n mcpServerInfo?: {\n /** Human-facing title. Defaults to the capitalized app id/name. */\n title?: string;\n /** Host-facing description. Defaults to \"Agent-native <app> agent\". */\n description?: string;\n /** Canonical app URL. Relative URLs are resolved against the request origin. */\n websiteUrl?: string;\n /** App icons. Relative `src` values are resolved against the request origin. */\n icons?: Array<{\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: \"light\" | \"dark\";\n }>;\n };\n /**\n * Optional callback to resolve the org ID for the current request.\n * When provided, the resolved value is set as AGENT_ORG_ID env var so\n * that db-query/db-exec automatically scope by org_id in addition to\n * owner_email.\n *\n * If not provided, the framework automatically uses `session.orgId` from\n * Better Auth's active organization. Only provide this callback when you\n * need custom org resolution logic (e.g., Atlassian org mapping).\n */\n resolveOrgId?: (event: any) => string | null | Promise<string | null>;\n /**\n * Optional owner resolver for public/anonymous chat surfaces. When the\n * normal app session is missing, this callback may return a synthetic\n * owner id for a narrowly-scoped public request (for example, a public\n * shared document page). Anonymous requests use a read-only tool set by\n * default so public viewers cannot mutate app data through the agent.\n */\n anonymousOwner?: (event: any) => string | null | Promise<string | null>;\n /**\n * Keep anonymous-owner requests on read-only template actions. Defaults to\n * true. Only disable for single-tenant apps that intentionally allow public\n * agent mutations.\n */\n anonymousReadOnly?: boolean;\n /**\n * Optional callback to append template-specific context to the system\n * prompt on each request. Runs after AGENTS.md / skills / memory are\n * loaded and before the schema block — use it to inject dynamic SQL\n * context like a data dictionary, active feature flags, or whatever\n * the agent should know about *right now* for this user/org.\n *\n * Return `null` or an empty string to skip. The string you return is\n * appended verbatim, so wrap it in your own XML tags (e.g.\n * `<data-dictionary>…</data-dictionary>`) to keep the prompt scannable.\n *\n * Called on every request in every prompt variant (lean, lazy, full).\n * Templates that want to suppress it in a particular mode should return\n * `null` from the callback based on their own logic.\n */\n extraContext?: (\n event: any,\n owner: string,\n ) => string | null | Promise<string | null>;\n /**\n * Optional final-answer guard. Templates can use this to require a\n * corrective retry before accepting a text-only final answer, e.g. forcing\n * real data-source tool calls for analytics requests.\n */\n finalResponseGuard?: import(\"../agent/production-agent.js\").AgentLoopFinalResponseGuard;\n /**\n * Optional per-template request normalizer. Runs after authentication and\n * before the model sees the message, so apps can translate chat attachments\n * into template-native file handles while preserving the user's visible text.\n */\n prepareRequest?: (details: {\n event: any;\n ownerEmail: string | null;\n message: string;\n displayMessage?: string;\n attachments: AgentChatAttachment[];\n references: AgentChatReference[];\n threadId?: string;\n internalContinuation?: boolean;\n mode: \"act\" | \"plan\";\n }) =>\n | void\n | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }\n | Promise<void | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }>;\n /**\n * Use ONLY the template's `systemPrompt` and the actions list — skip the\n * framework prompt wrapper, resource loading (AGENTS.md/LEARNINGS.md/\n * memory), the SQL schema block, and the workspace files/skills/agents\n * inventory. Intended for minimal or voice-first apps where a long,\n * generic preamble adds latency and iteration noise without adding value.\n *\n * When set, the same lean prompt is used in both dev and prod modes. In\n * dev mode the tool registry is ALSO swapped to the template's actions\n * (same set as prod) — the dev-only bash/db-exec/file-system tools\n * and the resource/docs/chat/team/job/browser scripts are dropped. The\n * lean system prompt has no bash-usage guidance, so routing actions\n * through bash would break. If you need the full dev tool surface,\n * leave this off.\n */\n leanPrompt?: boolean;\n /**\n * Use a compact system prompt with on-demand context loading. The system\n * prompt includes essential behavioral rules and action signatures, but\n * defers verbose framework details, SQL schema, skills, learnings, and\n * memory behind tools (`get-framework-context`, `db-schema`,\n * `resources` (action: read)). The agent fetches these on-demand when needed.\n *\n * This reduces the system prompt by ~60-70%, significantly improving\n * time-to-first-token and reducing \"thinking\" time. The agent retains\n * all capabilities — it just loads context lazily instead of upfront.\n *\n * Defaults to `true`. Set to `false` to use the original full prompt.\n * Ignored when `leanPrompt` is set (lean mode is even more minimal).\n */\n lazyContext?: boolean;\n /**\n * In dev mode, register the template's actions as native tools the agent\n * can call directly with structured JSON args — skipping the default\n * `bash(command=\"pnpm action <name> ...\")` indirection.\n *\n * The default dev behavior shells out because it \"mirrors how Claude Code\n * works locally\" and reduces empty-object tool calls for templates with\n * simple string args. But templates whose actions take structured data\n * (objects, arrays, nested JSON) can't round-trip those cleanly through\n * the CLI parser — stringified JSON on the way in, loss of type fidelity\n * on the way out.\n *\n * Set to `true` to get the same tool surface in dev that production uses.\n * `leanPrompt: true` implies this already (lean mode has no bash-usage\n * guidance, so actions must be native). Set this flag without\n * `leanPrompt` when you want native actions AND the full system prompt.\n *\n * Defaults to `false`.\n */\n nativeActionsInDev?: boolean;\n /**\n * Optional A2A-only deterministic response path. Runs after inbound A2A text\n * and user context are resolved, but before an agent engine/model is loaded.\n * Return a message to complete the A2A task without invoking the LLM, or\n * null/undefined to continue through the normal agent loop.\n */\n a2aMessageFallback?: (details: {\n message: import(\"../a2a/types.js\").Message;\n text: string;\n context: import(\"../a2a/types.js\").A2AHandlerContext;\n userEmail: string | undefined;\n }) =>\n | import(\"../a2a/types.js\").Message\n | string\n | null\n | undefined\n | Promise<import(\"../a2a/types.js\").Message | string | null | undefined>;\n /**\n * Optional injectable prompt examples for core rules (rule 5 auto-refresh\n * examples and rule 8 external provider names). When absent, generic\n * placeholders are used so no template-specific names appear in the core\n * prompt by default.\n *\n * - `providerActions`: external provider action names this template exposes\n * (e.g. `[\"warehouse-query\", \"crm-records\"]` for a template).\n * - `appActions`: representative template action names for rule 5's refresh\n * examples (e.g. `[\"log-meal\", \"update-form\"]` for a forms template).\n */\n promptExamples?: PromptExamples;\n /**\n * Curated allow-list of action names to serve external **connector** clients\n * on a hosted multi-tenant deployment.\n *\n * Whenever this list is non-empty it is active by default for **every**\n * caller (hosted connectors, code/stdio clients, and the local CLI): external\n * MCP clients see (and can call) only these actions plus the builtin\n * cross-app tools (`list_apps`, `open_app`, `ask_app`, `create_embed_session`).\n * Calls to any tool outside the list are rejected with \"Unknown tool\".\n * This prevents the full ~105-tool catalog from bloating external-agent\n * context windows and removes footguns (db-exec, seed-*, extension suite,\n * browser-session tools) from connectors. It is no longer gated behind an\n * environment variable, and the catalog is never inferred from the client.\n *\n * `tool-search` stays available so any trimmed tool is reachable on demand.\n * Callers who need the full surface up front opt in explicitly with\n * `agent-native connect --full-catalog` (embeds a `catalog_scope: \"full\"`\n * claim in their connect-minted JWT) or the deployment-wide\n * `AGENT_NATIVE_MCP_FULL_CATALOG=1` env override.\n *\n * Declare here rather than in MCPConfig directly; the plugin copies it through.\n */\n connectorCatalog?: string[];\n\n /**\n * Code-execution capability for the production agent.\n *\n * - `\"off\"` (default) — no code-execution tools in production.\n * - `\"sandboxed\"` — registers the `run-code` tool (isolated Node.js sandbox\n * with a bridge to allowlisted registered tools). Safe for shared or\n * hosted deployments.\n * - `\"trusted\"` — registers both the full coding tool registry\n * (bash / read / edit / write) and the `run-code` sandbox. Only use in\n * single-tenant or operator-controlled deployments where full shell access\n * to the host machine is intentional.\n *\n * The `AGENT_PROD_CODE_EXECUTION` environment variable (`\"trusted\"`,\n * `\"sandboxed\"`, or `\"off\"`) takes precedence over this option, allowing\n * per-deployment overrides without code changes.\n *\n * Dev-mode behavior is unchanged — both the coding tools and `run-code` are\n * always available when the environment allows toggling.\n */\n codeExecution?: {\n production?: \"off\" | \"sandboxed\" | \"trusted\";\n /**\n * Extra registered-tool names the sandbox bridge may forward (beyond the\n * default allowlist: provider-api-request, provider-api-docs,\n * provider-api-catalog, web-request).\n */\n bridgeTools?: string[];\n };\n\n /**\n * App-level default tool-call limits. Individual actions override these with\n * their own `timeoutMs` / `maxResultChars` declarations.\n */\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\n}\n\n/**\n * Verbose framework sections returned by the `get-framework-context` tool.\n * Keyed by topic so the agent can request specific sections.\n * Not template-specific — lives outside buildFrameworkPrompts().\n */\nconst FRAMEWORK_CONTEXT_SECTIONS: Record<string, string> = {\n embeds: `### Inline Embeds\n\nYou can embed an interactive view inline in your chat reply by writing an \\`embed\\` fenced code block. The chat renderer swaps the fence for a sandboxed iframe pointing at a route inside this app.\n\nSyntax:\n\n\\`\\`\\`\\`\n\\`\\`\\`embed\nsrc: /some/path?param=value\naspect: 16/9\ntitle: Optional label\n\\`\\`\\`\n\\`\\`\\`\\`\n\nKeys:\n- \\`src\\` (required) — **must be a same-origin path starting with \\`/\\`**. Cross-origin URLs are blocked. No \\`javascript:\\` or \\`data:\\` URLs.\n- \\`aspect\\` (optional) — one of \\`16/9\\` (default), \\`4/3\\`, \\`3/2\\`, \\`2/1\\`, \\`21/9\\`, \\`1/1\\`.\n- \\`title\\` (optional) — accessible label / hover tooltip.\n- \\`height\\` (optional) — fixed pixel height when aspect ratio isn't a good fit.\n\nUse for charts, visualizations, previews. Don't use for simple text/tables or external sites.`,\n\n \"chat-history\": `### Chat History\n\nYou can search and restore previous chat conversations using \\`chat-history\\`:\n- \\`chat-history\\` (action: \"search\") — Search or list past chat threads by keyword\n- \\`chat-history\\` (action: \"open\") — Open a chat thread in the UI as a new tab and focus it\n- \\`chat-history\\` (actions: \"rename\", \"pin\", \"unpin\", \"archive\") — Organize a known chat thread by ID\n\nWhen the user asks to find a previous conversation, use \\`chat-history\\` with action \"search\" first to find matching threads, then action \"open\" to restore the one they want.`,\n\n \"agent-teams\": `### Agent Teams — Orchestration\n\nYou can delegate to background sub-agents with the \\`agent-teams\\` tool:\n- \\`agent-teams\\` (action: \"spawn\") — Launch a sub-agent on a task. It runs in its own thread with a clean context while you stay available; a live preview card appears in the chat. The spawn result confirms launch only, not completion. Optionally pass a custom agent profile from \\`agents/*.md\\` via the \\`agent\\` parameter.\n- \\`agent-teams\\` (action: \"status\") — Check a running sub-agent's progress.\n- \\`agent-teams\\` (action: \"read-result\") — Read a finished sub-agent's output.\n- \\`agent-teams\\` (action: \"send\") — Message a running sub-agent.\n- \\`agent-teams\\` (action: \"list\") — List sub-agent tasks.\n\nSub-agents inherit all of your template tools but **cannot spawn sub-agents themselves** — only you orchestrate.\n\n**User intent phrases.** If the user asks you to use a \"sub-agent\" or \"background agent\", that is explicit delegation intent. Also treat phrases like \"run these in the background\", \"kick off the rest\", \"run the queued items\", \"batch run these jobs\", \"parallelize this\", or \"start the next batch\" as delegation intent when the context is a set of independent work items.\n\n**Spawn is not completion.** A successful \\`spawn\\` call means the sub-agent started and is running. Tell the user it started, show the task id if useful, and then use \\`status\\`/\\`list\\`/\\`read-result\\` to monitor it. Never say the delegated task \"completed\", \"ran successfully\", or \"finished\" until \\`status\\` or \\`read-result\\` reports \\`completed\\` or \\`errored\\`. If a task is still running, say that plainly.\n\n**Default to doing the work yourself in this thread.** A sub-agent costs real tokens and adds a merge step, so reach for one only when delegation clearly pays for that overhead.\n\n**Delegate ONE sub-agent** when a task is self-contained and heavy: deep research, long multi-step content generation, or a noisy scan whose intermediate steps would clutter this thread. The sub-agent gets its own clean context and hands you back a distilled result.\n\n**Fan out to MULTIPLE sub-agents ONLY** for units of work that are genuinely independent and don't depend on each other's decisions — e.g. research three unrelated competitors, summarize five separate threads, draft sections that don't reference one another. Each gets a distinct slice.\n\n**Do NOT parallelize tightly-coupled work** — one cohesive artifact, edits that must agree with each other, or anything needing a single consistent voice or style. Parallel sub-agents can't see each other's choices and their outputs will clash. For coupled work, do it yourself, or chain sub-agents one at a time, feeding each result into the next.\n\n**Cap fan-out:** aim for 1, use up to ~3, and go beyond that only for clearly independent bulk work. More sub-agents means more tokens and a harder merge.\n\n**Briefing contract.** A sub-agent starts in a fresh thread and can only see the brief you give it — it cannot see this conversation or ask you to clarify before it runs. Make every brief self-contained:\n1. **Objective** — what \"done\" looks like, in a sentence or two.\n2. **Context** — the specific facts it needs from this conversation: IDs, names, the user's actual goal, constraints, prior decisions. Paste the specifics; don't assume it knows them.\n3. **Output format** — what to return and how (e.g. \"a 3-bullet summary with source links\", \"the drafted email body only\") so the result drops cleanly into your synthesis.\n4. **Boundaries** — what NOT to do, and for parallel sub-agents, which slice is theirs so they don't overlap.\n\nPut the objective and output format in \\`task\\`; put longer context in \\`instructions\\`.\n\n**Synthesis discipline.** After the sub-agents you depend on finish, poll \\`status\\`/\\`list\\` until they're complete, then pull each one's output with \\`read-result\\`. Do NOT paste their outputs back to back. Read all results, reconcile any disagreements, de-duplicate, and write ONE integrated answer in your own voice. If two sub-agents conflict, resolve it or flag the discrepancy explicitly rather than presenting both. When findings came from distinct investigations, briefly note which finding came from where so the user can trust the merge.`,\n\n \"recurring-jobs\": `### Recurring Jobs\n\nYou can create recurring jobs that run on a cron schedule. Jobs are resource files under \\`jobs/\\`.\n\n- \\`manage-jobs\\` (action: \"create\") — Create a new recurring job with a cron schedule and instructions\n- \\`manage-jobs\\` (action: \"list\") — List all recurring jobs and their status\n- \\`manage-jobs\\` (action: \"update\") — Update a job's schedule, instructions, or toggle enabled/disabled\n- Delete a job with the \\`resources\\` tool: \\`action: \"delete\"\\`, \\`path: \"jobs/<name>.md\"\\`\n\nConvert natural language to 5-field cron format:\n- \"every morning\" / \"daily at 9am\" → \\`0 9 * * *\\`\n- \"every weekday at 9am\" → \\`0 9 * * 1-5\\`\n- \"every hour\" → \\`0 * * * *\\`\n- \"every monday at 9am\" → \\`0 9 * * 1\\`\n\n#### Suggesting \"Save as automation\"\n\nWhen you finish a task that has obvious recurring value — daily inbox triage, weekly metrics summaries, archive sweeps, status digests, anything the user would plausibly want re-run on a fresh cadence — close the response with ONE short line offering to save it. Examples:\n\n- After \"Summarize my unread emails\": _\"Want me to run this every morning?\"_\n- After \"What's our top traffic source this week\": _\"Want a weekly digest on Mondays?\"_\n- After \"Archive emails older than 30 days\": _\"Should I run this every Sunday?\"_\n\nIf the user says yes, call \\`manage-jobs\\` (action: \"create\") with the original prompt as the job's instructions and the cadence they confirmed.\n\nDo NOT add this offer for one-shot work: lookups (find Alice, what's the schema, who reported X), single drafts/replies, navigation requests, or any task whose value is in the moment. Skip it when the prompt is already explicitly recurring (the user said \"every morning…\" — you'd be asking what they already told you). One short sentence at most; do not turn it into a list of cadence options.`,\n\n builder: `### Connecting Builder.io\n\nWhen the user asks to connect Builder.io or you hit a \"Builder not configured\" error, call the \\`connect-builder\\` tool. It renders a one-click Connect card inline — do NOT write out multi-step setup instructions yourself. If Builder Cloud Agents are not available for this workspace, never send the user to Builder org settings or beta settings; use the card's waitlist/local-dev fallback.`,\n\n browser: `### Browser Automation\n\nYou can activate a real Chrome browser via Builder.io for tasks that need full page rendering:\n- Extracting design tokens from JS-heavy or SPA websites (computed styles, rendered colors/fonts)\n- Taking screenshots of live pages\n- Testing interactive flows on deployed URLs\n- Reading content from pages that require JavaScript execution\n\n**How to use:**\n1. In local development, call \\`set-browser-control\\` with \\`{\"enabled\":true,\"backend\":\"chrome-devtools\"}\\` after confirming once with the user. In production, use \\`activate-browser\\` for Builder-provisioned Chrome.\n2. On your next action, use \\`mcp__chrome-devtools__navigate_page\\`, \\`mcp__chrome-devtools__evaluate_script\\`, \\`mcp__chrome-devtools__take_screenshot\\`, etc.\n3. If Builder is not connected, call \\`connect-builder\\` first\n\n**When to recommend browser automation:**\n- User wants to import a design system from a URL (JS-rendered sites give almost no useful data from plain HTML fetch)\n- User asks you to check how a deployed site looks or behaves\n- Any task involving reading computed/rendered page state\n- When \\`web-request\\` returns minimal/skeleton HTML from a modern SPA\n\nPrefer \\`web-request\\` for simple API calls and static pages. Use browser automation when you need the real rendered page.`,\n\n \"call-agent\": `### call-agent — External Apps Only\n\nThe \\`call-agent\\` tool sends a message to a DIFFERENT, separately-deployed app's agent (A2A protocol). It is **not** for calling actions within the current app.\n\n**NEVER use \\`call-agent\\` to:**\n- Call your own app by name\n- Perform tasks you can accomplish with your own registered tools\n\n**ONLY use \\`call-agent\\` when:**\n- The user explicitly asks you to communicate with a different app\n- You need data that only another deployed app can provide\n- You need brand-consistent generated media and this app does not have a native generation action; call agent \"assets\" and keep returned asset IDs and URLs verbatim\n\nIf \\`call-agent\\` says a downstream agent accepted the subtask and will post its result separately, do not call that same agent again for the same subtask. Continue any remaining work and answer with the completed results you have.`,\n\n memory: `### Structured Memory\n\nYour memory index (\\`memory/MEMORY.md\\`) is loaded at the start of every conversation.\n\n**Tools:**\n- \\`save-memory\\` — Create or update a memory (name, type, description, content)\n- \\`delete-memory\\` — Remove a memory and its index entry\n- \\`resources\\` with \\`action: \"read\"\\` and \\`path: \"memory/<name>.md\"\\` — Read the full content of a specific memory\n\n**Memory types:** user, feedback, project, reference\n\n**When to save (proactively):**\n- User corrects your approach → \\`feedback\\`\n- User shares preferences → \\`user\\`\n- Non-obvious pattern or gotcha → \\`feedback\\`\n- Personal context (contacts, team) → \\`user\\`\n- Project context to track → \\`project\\`\n\n**Rules:**\n- Don't save things obvious from code or standard framework behavior\n- When updating, read first and merge — don't overwrite\n- Keep descriptions concise\n- One memory per logical topic`,\n\n \"sql-tools\": `### SQL Tools\n\n- \\`db-schema\\` — refresh the full schema with indexes and foreign keys\n- \\`db-query\\` — run a SELECT (read-only; results already filtered to the current user/org)\n- \\`db-exec\\` — run INSERT / UPDATE / DELETE / REPLACE (writes already scoped; owner_email and org_id are auto-injected on INSERT). For multiple related writes, use \\`statements\\` so they run in one transaction instead of separate tool calls. Schema changes are blocked.\n- \\`db-patch\\` — surgical search-and-replace on a large text column. Use for edits to large fields instead of re-sending multi-kilobyte strings.\n\n### When to pick which SQL tool\n- Set a short column outright, update multiple columns, or do computed updates → \\`db-exec UPDATE\\`\n- Insert/update several rows as one logical operation → \\`db-exec\\` with \\`statements: '[{\"sql\":\"...\",\"args\":[...]}]'\\`\n- Change a small slice of a large text/JSON column → \\`db-patch\\`\n- A template-specific action exists for the table → use that action (it encodes business rules and pushes live Yjs updates)\n- Read data → \\`db-query\\`. Never re-add \\`WHERE owner_email = ...\\` — scoping already applies it.\n\n### External data sources vs the app database\nThe \\`db-*\\` tools ONLY query the app's own SQL database. They do NOT reach external data warehouses. If the user asks about tables NOT in the schema, use the appropriate template action instead.`,\n};\n\n/**\n * Framework-level instructions injected into every agent's system prompt.\n * Prompt text lives in packages/core/src/server/prompts/ so this file stays\n * focused on routing and assembly logic.\n *\n * buildFrameworkPrompts() is called once per plugin instantiation (not per\n * request) with the template's promptExamples, producing the four assembled\n * prompt strings used at request time.\n */\nfunction buildFrameworkPrompts(examples?: PromptExamples): {\n FRAMEWORK_CORE: string;\n FRAMEWORK_CORE_COMPACT: string;\n PROD_FRAMEWORK_PROMPT: string;\n DEV_FRAMEWORK_PROMPT: string;\n PROD_FRAMEWORK_PROMPT_COMPACT: string;\n DEV_FRAMEWORK_PROMPT_COMPACT: string;\n} {\n // Note: FIRST_SESSION_PERSONALIZATION is NOT appended here — it is injected\n // at per-request prompt-assembly time only for new threads (no prior messages).\n // This prevents the ~1.5KB block from appearing on every request forever.\n const FRAMEWORK_CORE = buildFrameworkCore(examples);\n const FRAMEWORK_CORE_COMPACT = buildFrameworkCoreCompact(examples);\n\n const PROD_FRAMEWORK_PROMPT = `## Agent-Native Framework — Production Mode\n\nYou are an AI agent in an agent-native application, running in **production mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.\n\n### Plan Mode\n\nIf the current turn is in Plan mode, plan before anything gets written. This applies to source-code handoffs and to app-created artifacts such as extensions, widgets, dashboards, calculators, mini-apps, documents, designs, slides, or videos. Use only read-only tools, clarify the goal when needed, and return a concrete plan for approval. Do not call \\`create-extension\\`, \\`update-extension\\`, \\`connect-builder\\`, or any action that creates, updates, deletes, sends, publishes, or persists data until the user switches back to Act mode.\n\n### Extensions (Mini-Apps) — Use \\`create-extension\\` for extensions / widgets / dashboards\n\nIn Act mode, if the user asks you to create, build, or make an **extension**, **widget**, **dashboard**, **calculator**, **mini-app**, or any small self-contained interactive utility — call \\`create-extension\\` immediately with a self-contained Alpine.js HTML body. This is **NOT** a code change and does **NOT** go through \\`connect-builder\\`. Extensions are sandboxed mini-apps stored in the database — no source files are touched, no PR is opened, no build is required. The extension appears in the Extensions view and can be edited later via \\`update-extension\\`.\n\nKeep \\`create-extension\\` payloads compact enough to finish quickly. For complex extensions, create a useful working v1 first, then call \\`update-extension\\` with focused edits for refinements instead of trying to assemble one enormous initial tool input.\n\nIf the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \\`<current-screen>\\` or \\`<current-url>\\` when present. Call \\`get-extension\\` only if you need to inspect its content, then \\`update-extension\\` with that id. Use \\`list-extensions\\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes, even when the request says \"change the UI\" or \"fix this\". Do **NOT** call \\`connect-builder\\` for existing extension edits.\n\nIn Act mode, when in doubt — if the request mentions creating an extension, widget, dashboard, calculator, or asks for a new small interactive utility — choose \\`create-extension\\`. If it references an existing one or the current extension page, choose \\`update-extension\\`. Do **not** preface the call with planning text like \"let me build the dashboard…\" — just call the right extension action directly.\n\nNote: \"extension\" is the user-facing primitive (the sandboxed Alpine.js mini-app). Don't confuse it with the LLM concept of \"tools\" (function calls) — those are how you invoke ANY action, including \\`create-extension\\` itself.\n\nFor existing extensions, use \\`get-extension\\` or \\`update-extension\\` directly when \\`<current-screen>\\` or \\`<current-url>\\` provides an \\`extensionId\\`. Use \\`list-extensions\\` only to browse or resolve an unknown name. If the user wants a shared extension removed only from their view, use \\`hide-extension\\` — do not query or mutate the legacy \\`tools\\` table directly.\n\n### Extensions vs. Code Changes — Pick the Right Path\n\nRoute by what the request changes, not how it is phrased. Extensions render in their own sandboxed iframe and CANNOT change the host app's nav, restyle existing components, or replace built-in views.\n\n<routing>\n| The request is for… | Path |\n| ---------------------------------------------------------------- | ----------------------------- |\n| A new self-contained surface (widget, dashboard, calculator, viewer, list, tracker) | \\`create-extension\\` — ships instantly, no PR |\n| Editing an existing extension (fix, restyle, rename, add behavior) | \\`update-extension\\` |\n| The host app's own chrome (nav bar, sidebar, layout, routes, shipped components, existing styles, business logic) | \\`connect-builder\\` — a real source-code change |\n| Ambiguous, satisfiable either way (e.g. \"give me an unread view\") | \\`create-extension\\` (prefer the instant path) |\n</routing>\n\nWorked examples: \"a widget showing unread emails grouped by sender\", \"a dashboard summarizing my pipeline\", \"a tracker for my newsletter subscriptions\" → \\`create-extension\\`. \"Add an Unread tab to the left navigation\", \"make the subject lines wrap\", \"change the inbox grouping logic\", \"add a field to the compose form\" → \\`connect-builder\\`.\n\n### Code Changes Not Available — Call \\`connect-builder\\` Immediately\n\nIf the request matches the Extensions section above, use \\`create-extension\\` or \\`update-extension\\` instead — do NOT route it to \\`connect-builder\\`.\n\nIn Act mode, when the user asks you to change the UI, modify code, add a feature, fix a bug in the app itself, change styles, add a hook, create a component, add a route, add an integration, or anything else that requires editing source files — you MUST take exactly these steps, in order:\n\n1. Briefly acknowledge the user's specific request in their own terms — one short clause naming what they asked for (e.g. \"Got it — wider subject lines in the email list.\"). Do NOT restate the request verbatim, do NOT add a generic preamble, and do NOT promise outcomes. Skip this step entirely if the user already knows you're handing off (e.g. they said \"send this to Builder\").\n2. Call the \\`connect-builder\\` tool, passing the user's full request verbatim as the \\`prompt\\` argument. This renders an inline card. If Builder is connected and \\`builderEnabled\\` is true, the card hands the prompt off to Builder's cloud agent on one click and returns a branch URL. If Builder is not connected, it shows the Connect Builder flow. If \\`builderEnabled\\` is false, it shows a waitlist/local-dev fallback instead of a cloud handoff.\n3. After the card renders, inspect the tool result and write one sentence that frames the next click around what the user just asked — not as a Builder pitch. Examples: \"Click Send to Builder and it'll wire that up for you.\" / \"Connect Builder once and it'll handle this and future changes.\" / \"Builder Cloud Agents aren't available here yet — join the waitlist in the card, or use the Agent Native Desktop app for local code changes: https://www.agent-native.com/download.\" Do NOT say the card is pre-loaded, has everything, or lead with \"Builder Cloud Agents are…\" as if it were the headline.\n\nWhen \\`builderEnabled\\` is false, Builder Cloud Agents are not self-serve from Builder org settings. Do NOT tell the user to go to Builder org settings, beta features, \"Cloud Agents\", or \"AI Agents\" to enable them. The only allowed guidance is the card's waitlist/local-dev fallback: join the waitlist when the card offers it, use Agent Native Desktop, or edit from a local clone.\n\n**Act-mode handoff — do exactly this:** The moment a code change is requested, call \\`connect-builder\\` with the user's verbatim request, then write one sentence framing the next click. That is the whole job: Builder plans and edits in its own sandbox, so the planning, file-mapping, and code all happen there, not here. Keep your turn to the call plus that one sentence — skip code exploration, implementation plans, \\`resources\\` writes of specs, and sub-agents (they have no code-editing tools either). You don't need filesystem access to recommend Builder, so don't reach for it or list tools you lack.\n\nBuilder Cloud Agents are the recommended path when available because they are one-click and run in the cloud. Local dev and the desktop app are the fallback when cloud agent access is waitlisted or unavailable.\n${FRAMEWORK_CORE}`;\n\n const DEV_FRAMEWORK_PROMPT = `## Agent-Native Framework — Development Mode\n\nYou are an AI agent in an agent-native application, running in **development mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In development mode, you have full local access — use it with senior-engineer judgment** (read before you edit, keep changes scoped, verify before you claim done):\n- Run any shell command via the \\`bash\\` tool (node, curl, pnpm, rg, git, etc.), including arbitrary code: \\`bash({ command: 'node -e \"console.log(1+1)\"' })\\`\n- Read and write any file on the filesystem; edit source, install packages, modify the app\n- Query and modify the database\n- Call external APIs (via bash with curl, or via scripts)\n\nWhen no dedicated tool/action exists for what you need, reach for \\`bash\\` — e.g. \\`bash({ command: 'curl -s https://api.example.com/data' })\\`.\n\n**Template-specific actions are invoked via bash, NOT as direct tools.** In dev mode, the only tools registered as native tool calls are framework-level utilities (bash, read, edit, write, database, resources, chat, teams, jobs). Anything from the template's \\`actions/\\` directory must be run through bash: \\`bash({ command: 'pnpm action <name> --arg value' })\\`. The \"Available Actions\" section below shows the exact CLI syntax for each one — copy that command verbatim and pass it to \\`bash\\`. Do not try to call template actions by name as if they were tools; they will not appear in your tool list.\n\nWhen editing code, follow the agent-native architecture:\n- Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync\n- All SQL must be dialect-agnostic (works on SQLite and Postgres)\n- No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)\n- Use shadcn/ui components and Tabler Icons for all UI work\n${FRAMEWORK_CORE}`;\n\n const PROD_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Production Mode\n\nYou are an AI agent in an agent-native application, running in **production mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.\n\n### Plan Mode\n\nIf the turn is in Plan mode, plan before anything gets written — including extensions, widgets, dashboards, calculators, mini-apps, documents, designs, slides, videos, and code-change handoffs. Use read-only tools only and do not call \\`create-extension\\`, \\`update-extension\\`, \\`connect-builder\\`, or other write actions until the user switches back to Act mode.\n\n### Extensions (Mini-Apps) — Use \\`create-extension\\`\n\nIn Act mode, if the user asks for an **extension**, **widget**, **dashboard**, **calculator**, or **mini-app**, call \\`create-extension\\` immediately with a self-contained Alpine.js HTML body. This is NOT a code change — extensions are sandboxed mini-apps stored in the database. Do not preface with \"let me build…\" — just call \\`create-extension\\`.\n\nKeep the first \\`create-extension\\` call compact and working. If the request is complex, create the v1 first and then refine with focused \\`update-extension\\` edits.\n\nIf the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \\`<current-screen>\\` or \\`<current-url>\\` when present. Call \\`get-extension\\` only if you need to inspect its content, then \\`update-extension\\` with that id. Use \\`list-extensions\\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes. Do NOT call \\`connect-builder\\` for them.\n\nFor existing extensions, use \\`get-extension\\` or \\`update-extension\\` directly when \\`<current-screen>\\` or \\`<current-url>\\` provides an \\`extensionId\\`. Use \\`list-extensions\\` only to browse or resolve an unknown name. Use \\`hide-extension\\` when the user wants a shared extension removed only from their own view. Do not query the legacy \\`tools\\` table directly.\n\n### Extensions vs. Code Changes — Pick the Right Path\n\nIf the user wants a **new self-contained surface** (custom widget, dashboard, list, viewer, calculator), use \\`create-extension\\` — extensions ship instantly without a PR. Use \\`connect-builder\\` only when the request **modifies the host app's existing chrome** (nav bar, sidebar, current components, layout, styles, routes). Extensions cannot change the host nav or restyle existing components.\n\n### Code Changes — Call \\`connect-builder\\`\n\nIn Act mode, when a request genuinely needs a source-code edit (per the rules above), do this in order: (1) briefly acknowledge the user's specific ask in their own terms — one short clause, no preamble — then (2) call \\`connect-builder\\` with the user's request as the \\`prompt\\`, then (3) write one sentence framing the next click around what they asked for, not a Builder pitch. Do NOT write code, list files, make plans, or spawn sub-agents. Mention \\`npx agent-native create <app-name>\\`, Agent Native Desktop, or the waitlist card as the fallback when Builder Cloud Agents aren't available. Never tell users to enable Builder Cloud Agents from Builder org settings, beta features, \"Cloud Agents\", or \"AI Agents\"; they are not self-serve there.\n${FRAMEWORK_CORE_COMPACT}`;\n\n const DEV_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Development Mode\n\nYou are an AI agent in an agent-native application, running in **development mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In development mode, you have full local access** — shell, filesystem, database, external APIs, source edits, and package installs. Use it with senior-engineer judgment: read before you edit, keep changes scoped, verify before you claim done.\n\n**Template-specific actions are invoked via bash, NOT as direct tools.** Run them with: \\`bash({ command: 'pnpm action <name> --arg value' })\\`. See the \"Available Actions\" section below for CLI syntax.\n\nWhen editing code, follow the agent-native architecture:\n- Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync\n- All SQL must be dialect-agnostic (works on SQLite and Postgres)\n- No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)\n- Use shadcn/ui components and Tabler Icons for all UI work\n${FRAMEWORK_CORE_COMPACT}`;\n\n return {\n FRAMEWORK_CORE,\n FRAMEWORK_CORE_COMPACT,\n PROD_FRAMEWORK_PROMPT,\n DEV_FRAMEWORK_PROMPT,\n PROD_FRAMEWORK_PROMPT_COMPACT,\n DEV_FRAMEWORK_PROMPT_COMPACT,\n };\n}\n\nexport const _agentChatPromptSectionsForTests = (() => {\n // Built with default (no template-specific) examples for test stability.\n const {\n FRAMEWORK_CORE: frameworkCore,\n FRAMEWORK_CORE_COMPACT: frameworkCoreCompact,\n } = buildFrameworkPrompts();\n return {\n frameworkCore,\n frameworkCoreCompact,\n frameworkContextSections: FRAMEWORK_CONTEXT_SECTIONS,\n };\n})();\n\n/**\n * Pre-load the agent's context: AGENTS.md (workspace/template/runtime\n * instructions), the skills index, shared LEARNINGS.md (team notes), a shared\n * resource index, and memory/MEMORY.md (personal structured memory index).\n * These all get appended to the system prompt so the agent has everything it\n * needs from the first turn.\n *\n * Six sources are layered:\n *\n * 1. `<workspace>` — AGENTS.md from the enterprise workspace core.\n * 2. `<template>` — AGENTS.md + skills index from the Vite plugin bundle.\n * 3. `<workspace>` — SQL workspace AGENTS.md and instructions/*.md.\n * Runtime global defaults managed from Dispatch and inherited by apps.\n * 4. `<shared>` — SQL shared AGENTS.md and instructions/*.md. App/team/org\n * guidance that can override or narrow workspace defaults.\n * 5. `<shared>` — LEARNINGS.md from the SQL shared scope. Team-level notes.\n * 6. `<personal>` — memory/MEMORY.md from the SQL personal scope. The\n * current user's structured memory index.\n *\n * Each source is read independently — no copying between them. Editing\n * AGENTS.md and restarting the server is all it takes; Vite HMR invalidates\n * the bundle in dev so changes land instantly.\n */\nexport async function loadResourcesForPrompt(\n owner: string,\n compact = false,\n selfAppId?: string,\n): Promise<string> {\n await ensurePersonalDefaults(owner);\n\n const sections: string[] = [];\n const promptResourceMaxChars = compact\n ? COMPACT_PROMPT_RESOURCE_MAX_CHARS\n : SHARED_PROMPT_RESOURCE_MAX_CHARS;\n\n // 1. Workspace AGENTS.md + skills merged into the template bundle.\n try {\n const { loadAgentsBundle, generateSkillsPromptBlock, getRuntimeSkills } =\n await import(\"./agents-bundle.js\");\n const bundle = await loadAgentsBundle();\n\n // Workspace-core AGENTS.md (enterprise-wide instructions), if present.\n if (bundle.workspaceAgentsMd && bundle.workspaceAgentsMd.trim()) {\n const block = promptResourceBlock({\n name: \"AGENTS.md\",\n scope: \"workspace\",\n path: \"AGENTS.md\",\n content: bundle.workspaceAgentsMd,\n maxChars: promptResourceMaxChars,\n readHint:\n 'Use docs-search --slug \"agents-workspace\" to read the full workspace AGENTS.md.',\n });\n if (block) sections.push(block);\n }\n\n // 2. Template AGENTS.md — always included (critical template instructions).\n if (bundle.agentsMd.trim()) {\n const block = promptResourceBlock({\n name: \"AGENTS.md\",\n scope: \"template\",\n path: \"AGENTS.md\",\n content: bundle.agentsMd,\n maxChars: promptResourceMaxChars,\n readHint:\n 'Use docs-search --slug \"agents-template\" to read the full template AGENTS.md.',\n });\n if (block) sections.push(block);\n }\n\n // In compact mode, skip the full skills block — the agent can use\n // `docs-search` to find skills when it needs them. Either way, `scope: dev`\n // skills are excluded: they're for the human's coding agent, not runtime.\n const runtimeSkills = getRuntimeSkills(bundle);\n if (!compact) {\n const skillsBlock = generateSkillsPromptBlock(bundle);\n if (skillsBlock) sections.push(skillsBlock);\n } else if (runtimeSkills.length > 0) {\n const lines = runtimeSkills.map((s) => {\n const description = s.meta.description?.trim()\n ? ` - ${ensureSentence(s.meta.description)}`\n : \"\";\n return `- \\`${s.meta.name}\\`${description} Read with \\`docs-search --slug \"${skillDocsSlug(s.meta.name)}\"\\` before starting a task it applies to.`;\n });\n sections.push(\n `<skills-summary>\\nCodebase skills bundled from \\`.agents/skills/\\` (or legacy \\`.agent/skills/\\`) are available as docs-search pages. Do not use MCP resource reads for these skills.\\n\\n${lines.join(\"\\n\")}\\n</skills-summary>`,\n );\n }\n } catch {}\n\n // 3. Runtime workspace resources. These are global defaults inherited by\n // every app in the workspace, not copied into app scopes. They may come from\n // SQL, Dispatch, or local file mode.\n const workspaceAgents = await loadAgentsResourceForPrompt(\n WORKSPACE_OWNER,\n \"workspace\",\n promptResourceMaxChars,\n );\n if (workspaceAgents) sections.push(workspaceAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n WORKSPACE_OWNER,\n \"workspace-instruction\",\n promptResourceMaxChars,\n )),\n );\n\n // 4. Runtime shared/app/org resources from SQL. These come after workspace\n // defaults so app/team-specific guidance can override or narrow them.\n const sharedAgents = await loadAgentsResourceForPrompt(\n SHARED_OWNER,\n \"shared\",\n promptResourceMaxChars,\n );\n if (sharedAgents) sections.push(sharedAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n SHARED_OWNER,\n \"shared-instruction\",\n promptResourceMaxChars,\n )),\n );\n\n // 5. Personal SQL resources. These come last in the instruction stack so a\n // user can narrow or override organization/app and workspace defaults.\n if (owner !== SHARED_OWNER && owner !== WORKSPACE_OWNER) {\n const personalAgents = await loadAgentsResourceForPrompt(\n owner,\n \"personal\",\n promptResourceMaxChars,\n );\n if (personalAgents) sections.push(personalAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n owner,\n \"personal-instruction\",\n promptResourceMaxChars,\n )),\n );\n }\n\n const resourceSkillsBlock = await loadResourceSkillsPromptBlock(owner);\n if (resourceSkillsBlock) sections.push(resourceSkillsBlock);\n\n if (compact) {\n // In compact mode, skip learnings and memory in the prompt.\n // The agent can access them via the resources tool when needed.\n // Add a brief pointer so the agent knows they exist.\n sections.push(\n `<context-note>Shared learnings (LEARNINGS.md) and your personal memory (memory/MEMORY.md) are available via the \\`resources\\` tool with \\`action: \"read\"\\`. Check them when making decisions that might benefit from prior context.</context-note>`,\n );\n } else {\n // LEARNINGS.md from SQL (template-level instructions are in AGENTS.md above).\n // 2. Shared SQL scope\n try {\n const shared = await resourceGetByPath(SHARED_OWNER, \"LEARNINGS.md\");\n if (shared?.content?.trim()) {\n sections.push(\n `<resource name=\"LEARNINGS.md\" scope=\"shared\">\\n${shared.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n\n // 3. Personal memory index (skip if owner is the shared sentinel)\n if (owner !== SHARED_OWNER) {\n try {\n const memoryIndex = await resourceGetByPath(owner, \"memory/MEMORY.md\");\n if (memoryIndex?.content?.trim()) {\n sections.push(\n `<resource name=\"memory/MEMORY.md\" scope=\"personal\">\\n${memoryIndex.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n }\n }\n\n const workspaceResourceIndex = await loadResourceIndexForPrompt(\n WORKSPACE_OWNER,\n \"workspace\",\n );\n if (workspaceResourceIndex) sections.push(workspaceResourceIndex);\n\n const sharedResourceIndex = await loadResourceIndexForPrompt(\n SHARED_OWNER,\n \"shared\",\n );\n if (sharedResourceIndex) sections.push(sharedResourceIndex);\n\n try {\n const agents = (await discoverAgents(selfAppId)).slice(0, 30);\n if (agents.length > 0) {\n const lines = agents.map(\n (agent) =>\n `- ${agent.name} (${agent.id}) — ${agent.description || \"Connected A2A app\"}`,\n );\n sections.push(\n `<available-apps>\\nWorkspace apps available over A2A/call-agent:\\n${lines.join(\"\\n\")}\\n\\nUse \\`call-agent\\` with the app id when another app owns the work or data. Use tool-search or app-specific actions for details only when needed.\\n</available-apps>`,\n );\n }\n } catch {\n // Agent discovery is helpful context, not required for the run.\n }\n\n if (sections.length === 0) return \"\";\n return (\n \"\\n\\nThe following resources contain template-specific instructions and user context. Use the information in them to help the user.\\n\\n\" +\n sections.join(\"\\n\\n\")\n );\n}\n\n/**\n * Build the per-request SQL-schema context block. Reads AGENT_ORG_ID live\n * from the environment so scheduler/A2A/HTTP call sites all see whatever\n * org was just resolved for this request.\n */\nasync function buildSchemaBlock(\n owner: string,\n _legacyHasRawDbTools?: boolean,\n): Promise<string> {\n // db-* tools are always registered (see createDbScriptEntries), in both dev\n // and prod. The legacy boolean is kept for call-site compatibility but\n // ignored — always advertise the tools to the agent.\n try {\n return await loadSchemaPromptBlock({\n owner,\n orgId: getRequestOrgId() ?? null,\n hasRawDbTools: true,\n });\n } catch {\n return \"\";\n }\n}\n\n/**\n * Generates a system prompt section describing registered template actions.\n * This helps the agent prefer template-specific actions over raw db-query/db-exec.\n *\n * Two output modes:\n *\n * - `\"tool\"` — used in production, where template actions are registered\n * as native Anthropic tools. Output reads `name(arg*: type; ...) — desc`.\n * - `\"cli\"` — used in dev, where template actions are NOT registered as\n * native tools and must be invoked via `bash(command=\"pnpm action ...\")`.\n * Output reads `pnpm action name --arg <type> [--opt <type>] — desc`.\n */\nfunction generateActionsPrompt(\n registry: Record<string, ActionEntry>,\n mode: \"cli\" | \"tool\" = \"tool\",\n): string {\n if (!registry || Object.keys(registry).length === 0) return \"\";\n\n const actionEntries = Object.entries(registry);\n\n if (mode === \"tool\") {\n const summaryLines = actionEntries.map(([name, entry]) => {\n const desc = compactPromptLine(\n entry.tool.description,\n MAX_ACTION_SUMMARY_DESCRIPTION_CHARS,\n );\n return `- \\`${name}\\` — ${desc}`;\n });\n\n return `\\n\\n## Available Actions\n\n**Use these actions directly as tool calls.** They handle database access, validation, and business logic internally. The native tool schemas contain the full parameter details.\n\n${summaryLines.join(\"\\n\")}`;\n }\n\n const lines = actionEntries.map(([name, entry]) => {\n const desc = entry.tool.description;\n const params = entry.tool.parameters?.properties;\n const requiredFields = new Set(entry.tool.parameters?.required ?? []);\n\n // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`\n if (!params || Object.keys(params).length === 0) {\n return `- \\`pnpm action ${name}\\` — ${desc}`;\n }\n const entries = Object.entries(params);\n // Required first (alphabetical), then optional (alphabetical)\n entries.sort(([a], [b]) => {\n const ar = requiredFields.has(a) ? 0 : 1;\n const br = requiredFields.has(b) ? 0 : 1;\n if (ar !== br) return ar - br;\n return a.localeCompare(b);\n });\n const required: string[] = [];\n const optional: string[] = [];\n const requiredNames: string[] = [];\n for (const [k, v] of entries) {\n const type = (v as { type?: string }).type ?? \"any\";\n const flag = `--${k} <${type}>`;\n if (requiredFields.has(k)) {\n required.push(flag);\n requiredNames.push(`--${k}`);\n } else {\n optional.push(`[${flag}]`);\n }\n }\n const cmd = [\"pnpm action \" + name, ...required, ...optional].join(\" \");\n const requiredNote =\n requiredNames.length > 0 ? ` Required: ${requiredNames.join(\", \")}.` : \"\";\n return `- \\`${cmd}\\` — ${desc}.${requiredNote}`;\n });\n\n return `\\n\\n## Available Actions\n\n**These template actions are NOT exposed as direct tools in dev mode. To run any of them, use the \\`bash\\` tool with the exact command shown below.** Example: \\`bash(command=\"pnpm action add-slide --deckId abc --content 'Hello'\")\\`.\n\nDo NOT try to call these by name as if they were tools — they will not exist in your tool list. Always go through \\`bash\\`.\n\n${lines.join(\"\\n\")}`;\n}\n\nfunction generateCorpusToolsPrompt(\n registry: Record<string, ActionEntry>,\n): string {\n const hasProviderApi = \"provider-api-request\" in registry;\n const providerDiscoveryTools = [\n \"provider-api-catalog\" in registry ? \"`provider-api-catalog`\" : null,\n \"provider-api-docs\" in registry ? \"`provider-api-docs`\" : null,\n ].filter(Boolean);\n const hasRunCode = \"run-code\" in registry;\n const hasStagedDataset = \"query-staged-dataset\" in registry;\n if (!hasProviderApi && !hasRunCode && !hasStagedDataset) return \"\";\n\n const available = [\n ...providerDiscoveryTools,\n hasProviderApi ? \"`provider-api-request`\" : null,\n hasStagedDataset ? \"`query-staged-dataset`\" : null,\n hasRunCode ? \"`run-code`\" : null,\n ].filter(Boolean);\n\n return `\\n\\n## Broad Provider And Corpus Workflows\n\nAvailable corpus-capable tools: ${available.join(\", \")}.\n\nFor broad provider searches, raw API access, multi-page cohorts, cross-source joins, classification/counting over records, or absence-sensitive answers, do not stop at a bounded shortcut action. Use the provider's broad API/search/list surface, fetch every relevant page or an explicit bounded cohort, stage/save large responses when needed, and reduce the corpus with staged-dataset queries or code execution. In run-code, prefer providerFetchAll() for cursor/page/offset pagination and providerRequest() when response status, headers, or truncation metadata matters. Report source, filters, row counts, pagination/truncation, failed pages, and remaining gaps.`;\n}\n\n/**\n * Creates a Nitro plugin that mounts the agent chat endpoint.\n *\n * In dev mode (NODE_ENV !== \"production\"), automatically includes\n * file system, bash, and database tools alongside any template-specific actions.\n *\n * Usage in templates:\n * ```ts\n * // server/plugins/agent-chat.ts\n * import { readBody, createAgentChatPlugin } from \"@agent-native/core/server\";\n * import { scriptRegistry } from \"../../scripts/registry.js\";\n *\n * export default createAgentChatPlugin({\n * scripts: scriptRegistry,\n * systemPrompt: \"You are an email assistant...\",\n * });\n * ```\n */\nasync function collectFiles(\n dir: string,\n prefix: string,\n depth: number,\n results: Array<{ path: string; name: string; type: \"file\" | \"folder\" }>,\n): Promise<void> {\n if (depth > 4 || results.length >= 500) return;\n const skip = new Set([\n \"node_modules\",\n \".git\",\n \".next\",\n \".output\",\n \"dist\",\n \".cache\",\n \".turbo\",\n \"data\",\n ]);\n let entries: import(\"fs\").Dirent[];\n try {\n const fs = await lazyFs();\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (results.length >= 500) return;\n if (skip.has(entry.name) || entry.name.startsWith(\".\")) continue;\n const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const isDir = entry.isDirectory();\n results.push({\n path: relPath,\n name: entry.name,\n type: isDir ? \"folder\" : \"file\",\n });\n if (isDir)\n await collectFiles(\n nodePath.join(dir, entry.name),\n relPath,\n depth + 1,\n results,\n );\n }\n}\n\nfunction parseSkillFrontmatter(content: string): {\n name?: string;\n description?: string;\n userInvocable?: boolean;\n} {\n const frontmatter = parseFrontmatter(content);\n const userInvocable = getFrontmatterValue(frontmatter, \"user-invocable\");\n return {\n name: getFrontmatterValue(frontmatter, \"name\"),\n description: getFrontmatterValue(frontmatter, \"description\"),\n userInvocable:\n userInvocable === undefined\n ? undefined\n : userInvocable.toLowerCase() === \"true\",\n };\n}\n\nfunction isLocalhost(event: any): boolean {\n try {\n const host =\n event.node?.req?.headers?.host || event.headers?.get?.(\"host\") || \"\";\n const hostname = host.split(\":\")[0];\n return (\n hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\"\n );\n } catch {\n return false;\n }\n}\n\ntype AgentChatRequestSurface = \"app\" | \"dev-frame\" | \"desktop\";\n\nfunction normalizeAgentChatRequestSurface(\n value: string | null | undefined,\n): AgentChatRequestSurface | null {\n const normalized = (value ?? \"\").trim().toLowerCase();\n if (\n normalized === \"app\" ||\n normalized === \"dev-frame\" ||\n normalized === \"desktop\"\n ) {\n return normalized;\n }\n return null;\n}\n\nfunction isBrowserUserAgent(userAgent: string | null | undefined): boolean {\n return /Mozilla\\/|Chrome\\/|Safari\\/|Firefox\\/|Edg\\//i.test(userAgent ?? \"\");\n}\n\nexport function shouldBlockInProductCodeEditingSurface(input: {\n surface?: string | null;\n userAgent?: string | null;\n host?: string | null;\n}): boolean {\n const surface = normalizeAgentChatRequestSurface(input.surface);\n if (surface === \"dev-frame\") return false;\n if (surface === \"desktop\") return false;\n if (surface === \"app\") return true;\n\n // Legacy clients used to send `frame` for any iframe, which includes the\n // app-rendered sidebar inside preview frames. Treat unknown explicit surface\n // values as app-owned so they cannot accidentally receive dev code tools.\n if (input.surface && input.surface.trim()) return true;\n\n const userAgent = input.userAgent ?? \"\";\n if (/AgentNativeDesktop/i.test(userAgent)) return false;\n\n // Missing header from an older browser client. Be conservative for browser\n // UAs on any host, because preview URLs can be non-local while still running\n // a dev-mode app whose in-product chat would be reloaded by source edits.\n if (isBrowserUserAgent(userAgent)) return true;\n\n const host = (input.host ?? \"\").toLowerCase();\n const hostname = host.split(\":\")[0] ?? \"\";\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\"\n );\n}\n\nexport function createAgentChatPlugin(\n options?: AgentChatPluginOptions,\n): NitroPluginDef {\n return (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"agent-chat\");\n // Nitro v3 calls plugins synchronously and doesn't await async return\n // values. We track the async init so the framework's readiness gate\n // holds /_agent-native requests until routes are registered.\n const initPromise = (async () => {\n const { awaitBootstrap } = await import(\"./framework-request-handler.js\");\n await awaitBootstrap(nitroApp);\n\n // Reap phantom runs left over from the previous process (HMR restart,\n // process crash, isolate eviction). Any run whose heartbeat is already\n // stale by startup time had a dead producer; mark it errored so the\n // next /runs/active check returns a terminal status and reconnecting\n // clients don't spin on \"Thinking...\". Runs owned by OTHER live\n // isolates are protected by their fresh heartbeats.\n try {\n const { reapAllStaleRuns } = await import(\"../agent/run-store.js\");\n const reaped = await reapAllStaleRuns();\n if (reaped > 0) {\n console.log(`[agent-chat] reaped ${reaped} stale run(s) on startup`);\n }\n } catch {\n // Best effort — don't block plugin init if SQL isn't ready yet.\n }\n\n const env = process.env.NODE_ENV;\n // AGENT_MODE=production forces production agent constraints even in dev\n const canToggle =\n (env === \"development\" || env === \"test\") &&\n process.env.AGENT_MODE !== \"production\";\n const routePath = options?.path ?? \"/_agent-native/agent-chat\";\n\n // Mutable mode flag — persisted to the `settings` table so a user who\n // toggles to \"Production\" stays in prod mode across server restarts.\n // Hoisted here (before any tool-registry / handler closures are built)\n // so every runtime decision point can close over it and see live changes\n // when the user toggles the Environment dropdown.\n const AGENT_MODE_SETTING_KEY = \"agent-chat.mode\";\n let currentDevMode = canToggle;\n if (canToggle) {\n try {\n const persisted = await getSetting(AGENT_MODE_SETTING_KEY);\n if (persisted && typeof persisted.devMode === \"boolean\") {\n currentDevMode = persisted.devMode;\n }\n } catch {\n // Settings table may not be ready yet — fall back to default.\n }\n }\n // Every closure that picks between dev/prod tools, prompts, or handlers\n // at request time should call this getter instead of reading `canToggle`.\n // `canToggle` means \"this environment allows toggling\" (static); this\n // function means \"the user currently has dev mode ON\" (live).\n const isDevMode = () => currentDevMode;\n\n // Build the four assembled system prompt strings. These are static for the\n // lifetime of this plugin instance — examples come from options once at\n // startup, not per-request.\n const {\n PROD_FRAMEWORK_PROMPT,\n DEV_FRAMEWORK_PROMPT,\n PROD_FRAMEWORK_PROMPT_COMPACT,\n DEV_FRAMEWORK_PROMPT_COMPACT,\n } = buildFrameworkPrompts(options?.promptExamples);\n\n // Initialize MCP client. Merges file/env config + auto-detected binaries\n // + any remote servers users have added through the settings UI (persisted\n // in the settings table, scanned across all scopes so we never drop\n // another user's entries). Graceful-degrade: any failure yields zero MCP\n // tools and agent-chat keeps working as before.\n let mcpConfig = await buildMergedConfig().catch((err) => {\n console.warn(\n `[mcp-client] buildMergedConfig failed: ${err?.message ?? err}`,\n );\n return null;\n });\n if (!mcpConfig) {\n const fileOrEnv = loadMcpConfig() ?? autoDetectMcpConfig();\n mcpConfig = fileOrEnv;\n if (mcpConfig?.source) {\n console.log(\n `[mcp-client] loaded config from ${mcpConfig.source} (${Object.keys(mcpConfig.servers).length} server(s))`,\n );\n } else if (process.env.DEBUG) {\n console.log(\n \"[mcp-client] no configured MCP servers — skipping MCP tools\",\n );\n }\n } else if (mcpConfig.source) {\n console.log(\n `[mcp-client] merged config (${Object.keys(mcpConfig.servers).length} server(s), source: ${mcpConfig.source})`,\n );\n }\n const mcpManager = new McpClientManager(mcpConfig);\n try {\n await mcpManager.start();\n } catch (err: any) {\n console.warn(\n `[mcp-client] start() failed: ${err?.message ?? err}. Continuing without MCP tools.`,\n );\n }\n setGlobalMcpManager(mcpManager);\n const mcpActionEntries = mcpToolsToActionEntries(mcpManager);\n\n // Mount status + management routes so the settings UI can list / add /\n // remove remote MCP servers and hot-reload the running manager.\n mountMcpStatusRoute(nitroApp, mcpManager);\n mountMcpServersRoutes(nitroApp, mcpManager);\n startMcpConfigRefresh(mcpManager);\n // Hub-serve: expose org-scope servers to other agent-native apps in the\n // workspace when `AGENT_NATIVE_MCP_HUB_TOKEN` is set (dispatch, by\n // convention). Gated by the env var so mounting is a no-op otherwise.\n if (isHubServeEnabled()) {\n mountMcpHubRoutes(nitroApp);\n console.log(\n \"[mcp-client] hub serve enabled — other apps can pull org servers via /_agent-native/mcp/hub/servers\",\n );\n }\n const hubStatus = getHubStatus();\n if (hubStatus.consuming) {\n console.log(\n `[mcp-client] hub consume enabled — pulling from ${hubStatus.hubUrl}`,\n );\n }\n mountMcpHubStatusRoute(nitroApp);\n\n // Ensure we tear down child processes if the host shuts down cleanly.\n if (\n typeof process !== \"undefined\" &&\n typeof process.once === \"function\" &&\n !(globalThis as any).__agentNativeMcpExitHooked\n ) {\n (globalThis as any).__agentNativeMcpExitHooked = true;\n const stop = () => {\n const mgr = getGlobalMcpManager();\n // Shutdown is best-effort — a rejection here must not surface as\n // an unhandled promise rejection during process exit.\n if (mgr) mgr.stop().catch(() => {});\n };\n process.once(\"exit\", stop);\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGINT\", stop);\n }\n\n // Resolve actions — prefer explicit `actions`, fall back to deprecated\n // `scripts`. When neither is provided, auto-discover from the filesystem\n // so templates that forget to pass `actions` still work in non-serverless\n // deployments (serverless bundles need explicit imports).\n const rawActions = options?.actions ?? options?.scripts;\n // `*All` holds every discovered action including those that opted out of\n // agent exposure with `agentTool: false`. The agent-facing surfaces below\n // use the `filterAgentTools`-filtered `templateScripts`/`discoveredActions`\n // derived after discovery; `httpActions` keeps the full `*All` sets so\n // agent-hidden actions stay callable from the frontend / HTTP.\n let templateScriptsAll: Record<string, ActionEntry> =\n typeof rawActions === \"function\"\n ? await rawActions()\n : (rawActions ?? {});\n if (!rawActions && Object.keys(templateScriptsAll).length === 0) {\n try {\n const { autoDiscoverActions } = await import(\"./action-discovery.js\");\n templateScriptsAll = await autoDiscoverActions(\"auto\");\n } catch {\n // Filesystem discovery unavailable (serverless bundle) — skip.\n }\n }\n\n // Resource, chat, docs, db, and cross-agent scripts are available in both prod and dev modes\n const resourceScripts = await createResourceScriptEntries();\n const docsScripts = await createDocsScriptEntries();\n const dbScripts = await createDbScriptEntries();\n const refreshScreenTool = createRefreshScreenEntry();\n const frameworkContextTool = createFrameworkContextEntry();\n const leanPrompt = options?.leanPrompt === true;\n const lazyContext = options?.lazyContext !== false && !leanPrompt;\n const urlTools = createUrlTools();\n const engineScripts = await createAgentEngineScriptEntries(\n options?.appId,\n );\n const loopSettingsScripts = await createAgentLoopSettingsScriptEntries();\n const chatScripts = {\n ...(await createChatScriptEntries()),\n ...engineScripts,\n ...loopSettingsScripts,\n };\n const callAgentScript = await createCallAgentScriptEntry(options?.appId);\n const browserTools = createBuilderBrowserTool({\n getOrigin: () =>\n getRequestRunContext()?.requestOrigin ?? \"http://localhost:3000\",\n getOwner: () => getRequestRunContext()?.owner ?? getRequestUserEmail(),\n });\n\n // Auto-mount A2A protocol endpoints so every app is discoverable\n // and callable by other agents via the standard protocol.\n // In dev mode, include dev scripts (filesystem-discovered) so the A2A agent\n // has access to the same tools as the interactive agent.\n let devScriptsForA2A: Record<string, ActionEntry> = {};\n let discoveredActionsAll: Record<string, ActionEntry> = {};\n if (canToggle) {\n try {\n const { createDevScriptRegistry } =\n await import(\"../scripts/dev/index.js\");\n devScriptsForA2A = await createDevScriptRegistry();\n } catch {}\n\n // Auto-discover template action files and register as bash-based tools.\n // This ensures templates without a custom agent-chat plugin (e.g., analytics)\n // still have their domain actions available as tools.\n try {\n const pathMod = await import(\"path\");\n const cwd = process.cwd();\n const skipFiles = new Set([\n \"helpers\",\n \"run\",\n \"registry\",\n \"_utils\",\n \"db-connect\",\n \"db-status\",\n ]);\n\n for (const dir of [\"actions\", \"scripts\"]) {\n const actionsDir = pathMod.join(cwd, dir);\n const _fs = await lazyFs();\n if (!_fs.existsSync(actionsDir)) continue;\n const files = _fs\n .readdirSync(actionsDir)\n .filter(\n (f: string) =>\n f.endsWith(\".ts\") &&\n !f.startsWith(\"_\") &&\n !skipFiles.has(f.replace(/\\.ts$/, \"\")),\n );\n for (const file of files) {\n const name = file.replace(/\\.ts$/, \"\");\n if (templateScriptsAll[name] || devScriptsForA2A[name]) continue;\n\n // Try to load the action module directly so we get the real\n // run function (not a shell wrapper). This makes HTTP endpoints\n // work correctly. Only fall back to shell wrapper if the import\n // fails (e.g., CLI-style scripts that throw at top level).\n const filePath = pathMod.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n const def =\n mod.default && typeof mod.default === \"object\"\n ? mod.default\n : mod;\n if (def?.tool && typeof def.run === \"function\") {\n discoveredActionsAll[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...(typeof def.agentTool === \"boolean\"\n ? { agentTool: def.agentTool }\n : {}),\n };\n continue;\n }\n } catch {\n // Fall through to shell wrapper for CLI-style scripts\n // (and .ts files Node can't parse natively).\n }\n\n // Static-parse the source for `http: false` or\n // `http: { method: \"GET\" }` so the shell-wrapper fallback still\n // mounts HTTP routes with the correct method. We can't load the\n // .ts module to read the real defineAction object in this Node\n // context, so this regex sniff is the best we can do until the\n // discovery is moved into a Vite-aware codepath.\n let httpConfig: ActionHttpConfig | false | undefined;\n // Sniff `agentTool: false` the same way so a CLI-style action can\n // opt out of agent exposure even on the shell-wrapper fallback path.\n let agentToolFlag: boolean | undefined;\n try {\n const src = _fs.readFileSync(filePath, \"utf-8\");\n if (/\\bagentTool\\s*:\\s*false\\b/.test(src)) {\n agentToolFlag = false;\n }\n if (/\\bhttp\\s*:\\s*false\\b/.test(src)) {\n httpConfig = false;\n } else {\n const httpStart = src.search(/\\bhttp\\s*:\\s*\\{/);\n if (httpStart >= 0) {\n const window = src.slice(httpStart, httpStart + 200);\n const m = window.match(\n /method\\s*:\\s*['\"`](GET|POST|PUT|DELETE)['\"`]/,\n );\n const p = window.match(/path\\s*:\\s*['\"`]([^'\"`]+)['\"`]/);\n if (m || p) {\n httpConfig = {\n ...(m\n ? {\n method: m[1] as \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n }\n : {}),\n ...(p ? { path: p[1] } : {}),\n };\n }\n }\n }\n } catch {\n // File read failed — leave httpConfig undefined (default POST)\n }\n\n // Fallback: bash-based wrapper for CLI-style scripts\n discoveredActionsAll[name] = {\n tool: {\n description: `Run the ${name} action. Use: pnpm action ${name} --arg=value`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"CLI arguments as a string (e.g., --metrics=sessions --days=7)\",\n },\n },\n },\n },\n run: async (input: Record<string, string>) => {\n const bashEntry =\n devScriptsForA2A.bash ?? devScriptsForA2A.shell;\n if (!bashEntry) return \"Error: bash not available\";\n return bashEntry.run({\n command: `pnpm action ${name} ${input.args || \"\"}`.trim(),\n });\n },\n ...(httpConfig !== undefined ? { http: httpConfig } : {}),\n ...(typeof agentToolFlag === \"boolean\"\n ? { agentTool: agentToolFlag }\n : {}),\n };\n }\n }\n if (Object.keys(discoveredActionsAll).length > 0 && process.env.DEBUG)\n console.log(\n `[agent-chat] Auto-discovered ${Object.keys(discoveredActionsAll).length} action(s): ${Object.keys(discoveredActionsAll).join(\", \")}`,\n );\n } catch {}\n }\n\n // Agent-facing views of the discovered actions: actions that opted out of\n // agent exposure with `agentTool: false` are dropped from every tool\n // surface, prompt, MCP/A2A list, and job/trigger runner below. The full\n // `*All` sets are reserved for `httpActions`, which keeps agent-hidden\n // actions reachable from the frontend / HTTP.\n const templateScripts = filterAgentTools(templateScriptsAll);\n const discoveredActions = filterAgentTools(discoveredActionsAll);\n // Per-request owner is read from the AsyncLocalStorage run context\n // (populated by prepareRun). Module-scope `let` would race across\n // concurrent requests on a long-lived Node process — overlapping\n // tool calls would observe whichever request wrote last. ALS gives\n // each async call-chain its own view of the owner.\n //\n // Falls back to `getRequestUserEmail()` so callers that wrap work\n // in `runWithRequestContext({ userEmail }, …)` without going through\n // `prepareRun` (recurring jobs, trigger dispatcher) still see the\n // correct owner.\n //\n // SECURITY: returns `null` when neither the run context nor the\n // request user-email is populated. Consumers MUST short-circuit\n // with an explicit error rather than fall back to a sentinel\n // identity (e.g. DEV_MODE_USER_EMAIL). The previous fallback to\n // `local@localhost` slipped past `guard-no-localhost-fallback`\n // because the literal was hidden behind a symbolic alias —\n // any agent loop that reached this code without a populated\n // session would resolve `${keys.NAME}` against the dev-shim's\n // `app_secrets WHERE scope_id='local@localhost'` rows. See\n // audit 02 (HIGH: getCurrentRunOwner) and the\n // 2026-04-29 credentials-leak incident for the prior shape.\n const getCurrentRunOwner = (): string | null =>\n getRequestRunContext()?.owner ?? getRequestUserEmail() ?? null;\n const requireCurrentRunOwner = (operation: string): string => {\n const owner = getCurrentRunOwner();\n if (!owner) {\n throw new Error(\n `[agent-chat] No authenticated owner in run context — ` +\n `refusing to ${operation}. Ensure the request goes through ` +\n `prepareRun() or is wrapped in runWithRequestContext({ userEmail, ... }).`,\n );\n }\n return owner;\n };\n\n // Automation tools + fetch tool — depend on owner via callback.\n // Each callback short-circuits with a clear error when the run context\n // has no authenticated owner (see SECURITY note on getCurrentRunOwner).\n let automationTools: Record<string, ActionEntry> = {};\n try {\n const { createAutomationToolEntries } =\n await import(\"../triggers/actions.js\");\n automationTools = createAutomationToolEntries(() =>\n requireCurrentRunOwner(\"manage automations\"),\n );\n } catch {}\n let notificationTools: Record<string, ActionEntry> = {};\n try {\n const { createNotificationToolEntries } =\n await import(\"../notifications/actions.js\");\n notificationTools = createNotificationToolEntries(() =>\n requireCurrentRunOwner(\"manage notifications\"),\n );\n } catch {}\n let progressTools: Record<string, ActionEntry> = {};\n try {\n const { createProgressToolEntries } =\n await import(\"../progress/actions.js\");\n progressTools = createProgressToolEntries(() =>\n requireCurrentRunOwner(\"manage progress\"),\n );\n } catch {}\n let fetchTool: Record<string, ActionEntry> = {};\n try {\n const { createFetchToolEntry } =\n await import(\"../extensions/fetch-tool.js\");\n const { resolveKeyReferences, validateUrlAllowlist, getKeyAllowlist } =\n await import(\"../secrets/substitution.js\");\n fetchTool = createFetchToolEntry({\n resolveKeys: async (text) =>\n resolveKeyReferences(\n text,\n \"user\",\n requireCurrentRunOwner(\"resolve key references\"),\n ),\n validateUrl: async (url, usedKeys) => {\n for (const keyName of usedKeys) {\n const allowlist = await getKeyAllowlist(\n keyName,\n \"user\",\n requireCurrentRunOwner(\"validate URL allowlist\"),\n );\n if (allowlist && !validateUrlAllowlist(url, allowlist)) {\n return false;\n }\n }\n return true;\n },\n });\n } catch {}\n let webSearchTool: Record<string, ActionEntry> = {};\n try {\n const { createWebSearchToolEntry } =\n await import(\"../extensions/web-search-tool.js\");\n const {\n getBuilderWebSearchBaseUrl,\n resolveBuilderCredentials,\n resolveSecret,\n } = await import(\"./credential-provider.js\");\n const { getBuilderGatewayRequestHeaders } =\n await import(\"../agent/engine/builder-gateway-headers.js\");\n webSearchTool = createWebSearchToolEntry({\n resolveSecret,\n resolveBuilderCredentials,\n getBuilderWebSearchBaseUrl,\n getBuilderRequestHeaders: getBuilderGatewayRequestHeaders,\n });\n } catch {}\n let workspaceFilesTool: Record<string, ActionEntry> = {};\n try {\n const { createWorkspaceFilesTool } =\n await import(\"../workspace-files/tool.js\");\n workspaceFilesTool = createWorkspaceFilesTool();\n } catch {}\n let toolActions: Record<string, ActionEntry> = {};\n try {\n const { createExtensionActionEntries } =\n await import(\"../extensions/actions.js\");\n toolActions = createExtensionActionEntries();\n } catch {}\n let browserSessionTools: Record<string, ActionEntry> = {};\n try {\n const { createBrowserSessionActionEntries } =\n await import(\"../browser-sessions/actions.js\");\n browserSessionTools = createBrowserSessionActionEntries({\n getOwnerEmail: () => requireCurrentRunOwner(\"use browser sessions\"),\n });\n } catch {}\n\n // Core send-email tool — only registered when RESEND_API_KEY or\n // SENDGRID_API_KEY is set. Keyed \"core-send-email\" to avoid colliding\n // with the mail template's richer \"send-email\" action (template wins\n // when both surfaces spread into the same object, but distinct keys\n // keep both visible and avoid silent shadowing).\n let coreEmailTools: Record<string, ActionEntry> = {};\n try {\n const { createCoreEmailActionEntries } =\n await import(\"./email-actions.js\");\n coreEmailTools = createCoreEmailActionEntries();\n } catch {}\n\n // Core read-attachment tool — always registered so the agent can page\n // through large text/CSV/code attachments that were truncated in context.\n let coreAttachmentTools: Record<string, ActionEntry> = {};\n try {\n const { createCoreAttachmentActionEntries } =\n await import(\"./attachment-actions.js\");\n coreAttachmentTools = createCoreAttachmentActionEntries();\n } catch {}\n\n // -----------------------------------------------------------------------\n // Production code-execution mode resolution.\n //\n // Priority (highest -> lowest):\n // 1. AGENT_PROD_CODE_EXECUTION env var (\"trusted\" | \"sandboxed\" | \"off\")\n // 2. options.codeExecution.production\n // 3. Default: \"off\"\n //\n // Dev mode ignores this entirely: dev always gets the run-code sandbox.\n // Build these tools before A2A/MCP registries so every agent-loop surface\n // has the same code execution capability when enabled.\n // -----------------------------------------------------------------------\n const rawEnvCodeExec = (process.env.AGENT_PROD_CODE_EXECUTION ?? \"\")\n .toLowerCase()\n .trim();\n const resolvedProdCodeExec: \"off\" | \"sandboxed\" | \"trusted\" =\n rawEnvCodeExec === \"trusted\"\n ? \"trusted\"\n : rawEnvCodeExec === \"sandboxed\"\n ? \"sandboxed\"\n : rawEnvCodeExec === \"off\"\n ? \"off\"\n : (options?.codeExecution?.production ?? \"off\");\n\n // Forward-declaration for the production run-code bridge supplier.\n // Must come before createRunCodeEntry so the closure can capture it.\n let prodRunCodeToolActions: Record<string, ActionEntry> = {};\n let leanRunCodeToolActions: Record<string, ActionEntry> = {};\n\n // Sandboxed run-code tool: available in \"sandboxed\" or \"trusted\" prod\n // modes and always in dev mode.\n const runCodeTool: Record<string, ActionEntry> = {};\n const leanRunCodeTool: Record<string, ActionEntry> = {};\n try {\n const { createRunCodeEntry } =\n await import(\"../coding-tools/run-code.js\");\n runCodeTool[\"run-code\"] = createRunCodeEntry(\n // Supplier is evaluated at invocation time so runtime additions to\n // prodActions (e.g. MCP sync) are visible to the bridge.\n () => prodRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n leanRunCodeTool[\"run-code\"] = createRunCodeEntry(\n // Lean prompt mode intentionally exposes a much smaller action\n // surface; keep sandbox appAction() calls scoped to that same surface.\n () => leanRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n } catch {\n // Module unavailable (e.g. bundled browser build) — skip silently.\n }\n\n // Full coding tool registry (bash/read/edit/write) for \"trusted\" prod.\n // In dev mode this is handled separately via devHandler below.\n const prodCodingTools: Record<string, ActionEntry> = {};\n if (resolvedProdCodeExec === \"trusted\" && !canToggle) {\n try {\n const { createCodingToolRegistry } =\n await import(\"../coding-tools/index.js\");\n const codingRegistry = createCodingToolRegistry({\n cwd: process.cwd(),\n beforeBash: async ({ command: _command }) => {\n // In plan mode the agent loop blocks via isPlanModeToolCallAllowed;\n // this hook is a belt-and-suspenders guard inside trusted production.\n return null;\n },\n });\n Object.assign(prodCodingTools, codingRegistry);\n } catch {\n // Coding tools unavailable — skip silently.\n }\n }\n\n // Forward-declaration: populated after devActions is assembled below.\n // Must be declared before devRunCodeTool so the closure can close over it.\n let devRunCodeToolActions: Record<string, ActionEntry> = {};\n\n // Always register run-code in dev mode (when the coding module loads).\n const devRunCodeTool: Record<string, ActionEntry> = {};\n if (canToggle) {\n try {\n const { createRunCodeEntry } =\n await import(\"../coding-tools/run-code.js\");\n // devActions is not yet defined at this point; we use a late-binding\n // supplier so devRunCodeTool can reference the devActions registry\n // once it is built below (see devHandler block).\n devRunCodeTool[\"run-code\"] = createRunCodeEntry(\n () => devRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n } catch {}\n }\n\n const resolveExtraContext = async (\n event: any,\n owner: string,\n ): Promise<string> => {\n if (!options?.extraContext) return \"\";\n try {\n const extra = await options.extraContext(event, owner);\n return extra ? `\\n\\n${extra}` : \"\";\n } catch (err) {\n console.warn(\n \"[agent-chat] extraContext threw:\",\n err instanceof Error ? err.message : err,\n );\n return \"\";\n }\n };\n\n // In dev mode, template actions (templateScripts and discoveredActions) are\n // NOT registered as native tools — the agent invokes them via bash instead.\n // This avoids degenerate empty-object tool calls that Anthropic models\n // sometimes emit for actions with complex schemas. Production keeps the\n // native registration since it has no shell access.\n const allScripts = attachToolSearch(\n canToggle\n ? {\n ...filterPublicAgentActions(templateScripts),\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...discoveredActions,\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n // Full (\"production\") MCP surface served to an authenticated *real\n // caller* — a connect-minted token, an `agent-native mcp install` stdio\n // proxy, or a deployed / AGENT_MODE=production app — even in local dev.\n // `allScripts` above is intentionally the sparse, dev-toggled surface\n // (builtins + read-only public-agent actions) used by the local agent\n // chat and unauthenticated dev probes; per the external-agents contract\n // a caller that connected with a token MUST get the full surface (so\n // `create-document` etc. are callable over MCP). Only needed when\n // `canToggle` (dev/test): in production `allScripts` already IS this\n // composition, so leave it undefined and `mountMCP` skips the swap.\n const mcpFullActions = canToggle\n ? attachToolSearch({\n ...discoveredActions,\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n })\n : undefined;\n\n const { mountA2A } = await import(\"../a2a/server.js\");\n mountA2A(nitroApp, {\n name: options?.appId\n ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)\n : \"Agent\",\n description: `Agent-native ${options?.appId ?? \"app\"} agent`,\n skills: buildPublicAgentA2ASkills(allScripts),\n publicSkillsOnly: true,\n streaming: true,\n handler: async function* (message, context) {\n // Resolve the caller's identity for user-scoped data access.\n // Priority: A2A-JWT verified email (set by the A2A handler in\n // request-context) > dev session DB (dev only) > Google OAuth\n // tokeninfo (prod only). Without the JWT-verified-email path,\n // cross-app A2A calls landed owned by `local@localhost` (dev) or\n // `dispatch@shared`, which made resources invisible to the actual\n // signed-in user.\n //\n // SECURITY: we deliberately do NOT trust `context.metadata.userEmail`\n // as a fallback. The A2A endpoint runs in three modes — JWT-signed\n // (verified email lands in request context), API-key (caller is\n // app-authenticated but NOT user-authenticated), and unsigned\n // (no auth at all). Trusting caller-supplied metadata on the latter\n // two paths would let any reachable caller forge `metadata.userEmail`\n // and impersonate an arbitrary user. The JWT path already populates\n // the request context, so the metadata fallback was only ever used\n // on the unauthenticated paths — exactly where it's unsafe.\n const isDev = process.env.NODE_ENV !== \"production\";\n let userEmail: string | undefined;\n\n // 1. JWT-verified email from A2A receiver (auth boundary already\n // enforced upstream). Works in dev AND prod.\n try {\n const { getRequestUserEmail } =\n await import(\"./request-context.js\");\n userEmail = getRequestUserEmail();\n } catch {}\n\n // Dev-mode-only: when no JWT-verified email is present, fall back\n // to the most recently logged-in session. This is convenient for a\n // single-developer dev box but is a silent-impersonation hole if\n // it ever fires in production or on an exposed dev environment\n // (preview deploys, ngrok tunnels, etc.).\n //\n // SECURITY: gate this fallback narrowly:\n // - NODE_ENV strictly === \"development\" (not \"test\", not unset).\n // - AUTH_MODE === \"local\" (the dev-only auth shim).\n // - Request host is localhost / 127.0.0.1 (best-effort: when the\n // A2A handler doesn't have direct H3 event access, we rely on\n // env-based shape checks).\n //\n // In production this MUST never fire — the runtime assertion\n // below crashes loud if NODE_ENV === \"production\" somehow reaches\n // this block.\n if (!userEmail && isDev) {\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(\n \"[agent-chat] Dev-mode 'latest session' fallback reached in production — refusing.\",\n );\n }\n const strictlyDev = process.env.NODE_ENV === \"development\";\n const localAuthMode = process.env.AUTH_MODE === \"local\";\n // Request host check: rely on the request-context request origin\n // which prepareRun() / mountActionRoutes populate. The A2A\n // handler doesn't have direct H3 event access, but on a\n // misconfigured non-localhost dev box we still want to refuse.\n let isLocalHost = false;\n try {\n const origin = getRequestRunContext()?.requestOrigin;\n if (origin) {\n const url = new URL(origin);\n isLocalHost =\n url.hostname === \"localhost\" ||\n url.hostname === \"127.0.0.1\" ||\n url.hostname === \"::1\";\n } else {\n // No origin in context — the A2A handler runs without an\n // explicit request origin. Treat absence as permissive only\n // when we're confident the process is dev-only (NODE_ENV\n // strictly \"development\" + AUTH_MODE=local). Otherwise\n // refuse.\n isLocalHost = strictlyDev && localAuthMode;\n }\n } catch {\n isLocalHost = false;\n }\n if (strictlyDev && localAuthMode && isLocalHost) {\n try {\n const { getDbExec } = await import(\"../db/client.js\");\n const db = getDbExec();\n const { rows } = await db.execute({\n sql: \"SELECT email FROM sessions ORDER BY created_at DESC LIMIT 1\",\n args: [],\n });\n if (rows[0]) userEmail = rows[0].email as string;\n } catch {}\n }\n }\n\n if (!userEmail && !isDev) {\n const googleToken = context.metadata?.googleToken as string;\n if (googleToken) {\n try {\n const res = await fetch(\n `https://oauth2.googleapis.com/tokeninfo?access_token=${encodeURIComponent(googleToken)}`,\n );\n if (res.ok) {\n const info = (await res.json()) as {\n email?: string;\n email_verified?: string;\n };\n if (info.email && info.email_verified === \"true\") {\n userEmail = info.email;\n }\n }\n } catch {}\n }\n }\n\n const text = message.parts\n .filter(\n (p): p is { type: \"text\"; text: string } => p.type === \"text\",\n )\n .map((p) => p.text)\n .join(\"\\n\");\n\n if (!text) {\n yield {\n role: \"agent\" as const,\n parts: [\n { type: \"text\" as const, text: \"No text content in message\" },\n ],\n };\n return;\n }\n\n if (!userEmail) throw new Error(\"no authenticated user\");\n\n const fallbackResponse = await options?.a2aMessageFallback?.({\n message,\n text,\n context,\n userEmail,\n });\n if (fallbackResponse) {\n yield typeof fallbackResponse === \"string\"\n ? {\n role: \"agent\" as const,\n parts: [{ type: \"text\" as const, text: fallbackResponse }],\n }\n : fallbackResponse;\n return;\n }\n\n // Use the SAME agent setup as the interactive chat — identical tools,\n // prompt, and capabilities. The A2A agent IS the app's agent.\n const a2aEngine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: options?.apiKey,\n appId: options?.appId,\n });\n\n const devActive = isDevMode();\n\n // Build the same system prompt the interactive agent uses\n const owner = userEmail;\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, devActive);\n const extra = await resolveExtraContext(context.event, owner);\n const runtimeContext = runtimeContextForEvent(context.event);\n const systemPrompt = devActive\n ? devPrompt + runtimeContext + resources + schemaBlock + extra\n : basePrompt + runtimeContext + resources + schemaBlock + extra;\n\n const a2aModelCandidate =\n options?.model ??\n (await getStoredModelForEngine(a2aEngine, {\n appId: options?.appId,\n })) ??\n a2aEngine.defaultModel;\n const model = normalizeModelForEngine(a2aEngine, a2aModelCandidate);\n\n // Build tools — same as interactive handler but WITHOUT call-agent\n // to prevent infinite recursive A2A loops (agent calling itself).\n // In dev mode, template actions are invoked via bash (not native tools),\n // so they're omitted from the tool registry — see allScripts comment.\n const a2aActions = attachToolSearch(\n devActive\n ? {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n const a2aTools = actionsToEngineTools(a2aActions);\n\n const a2aMessages: EngineMessage[] = [\n { role: \"user\", content: [{ type: \"text\", text }] },\n ];\n\n // Run the SAME agent loop, then extract the final answer from the\n // event stream so pre-tool narration never leaks as the A2A result.\n const a2aEvents: AgentChatEvent[] = [];\n const a2aToolResults: Array<{ tool: string; result: string }> = [];\n let lastRecoverableArtifactText = \"\";\n const controller = new AbortController();\n\n console.log(\n `[A2A] Starting agent loop: ${a2aTools.length} tools, prompt ${systemPrompt.length} chars`,\n );\n\n await runAgentLoopDirectWithSoftTimeout(\n {\n engine: a2aEngine,\n model,\n systemPrompt,\n tools: a2aTools,\n messages: a2aMessages,\n actions: a2aActions,\n send: (event) => {\n a2aEvents.push(event);\n if (event.type === \"tool_start\") {\n console.log(`[A2A] Tool call: ${event.tool}`);\n } else if (event.type === \"tool_done\") {\n a2aToolResults.push({\n tool: event.tool,\n result: event.result,\n });\n const recoverableArtifactText =\n buildA2ARecoverableArtifactMessage(a2aToolResults, {\n baseUrl: resolveArtifactBaseUrl(context.event),\n });\n if (\n recoverableArtifactText &&\n recoverableArtifactText !== lastRecoverableArtifactText\n ) {\n lastRecoverableArtifactText = recoverableArtifactText;\n updateTaskStatusMessage(context.taskId, {\n role: \"agent\",\n metadata: { agentNativeRecoverableArtifacts: true },\n parts: [\n {\n type: \"text\",\n text: recoverableArtifactText,\n },\n ],\n }).catch((err) => {\n console.error(\n `[A2A] Failed to persist recoverable artifact message for task ${context.taskId}:`,\n err,\n );\n });\n }\n } else if (event.type === \"error\") {\n console.error(`[A2A] Error: ${event.error}`);\n } else if (event.type === \"done\") {\n console.log(`[A2A] Done. Events: ${a2aEvents.length}`);\n }\n },\n signal: controller.signal,\n },\n options?.runSoftTimeoutMs,\n );\n\n const { responseText, finalText } = assembleA2AFinalResponse(\n a2aEvents,\n a2aToolResults,\n { event: context.event },\n );\n\n console.log(\n `[A2A] Loop complete. Text: ${responseText.slice(0, 100)}...`,\n );\n\n // Yield the final accumulated text\n yield {\n role: \"agent\" as const,\n parts: [\n {\n type: \"text\" as const,\n text: finalText || \"(no response)\",\n },\n ],\n };\n },\n });\n\n // Generate an \"Available Actions\" section from template-specific actions\n // so the agent knows to use them instead of raw SQL.\n //\n // Production: actions are native tools — emit `name(arg*: type) — desc`\n // Dev: actions are invoked via bash — emit `pnpm action name --arg <type>`\n // and include discoveredActions too, since those are also missing\n // from the dev tool registry.\n const corpusToolsPrompt = generateCorpusToolsPrompt({\n ...templateScripts,\n ...(canToggle\n ? devRunCodeTool\n : resolvedProdCodeExec !== \"off\"\n ? runCodeTool\n : {}),\n });\n const prodActionsPrompt =\n generateActionsPrompt(templateScripts, \"tool\") + corpusToolsPrompt;\n const devActionsPrompt =\n generateActionsPrompt(\n { ...discoveredActions, ...templateScripts },\n \"cli\",\n ) + corpusToolsPrompt;\n\n // Build system prompts — dynamic functions that pre-load resources per-request.\n // Production gets PROD_FRAMEWORK_PROMPT, dev gets DEV_FRAMEWORK_PROMPT.\n // Custom systemPrompt from options overrides the framework default entirely.\n const prodPrompt =\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT)) + prodActionsPrompt;\n // When template actions are registered as native tools in dev (via\n // `nativeActionsInDev` or `leanPrompt`), the dev prompt's \"invoke\n // template actions via bash\" guidance is wrong — use the prod prompt\n // + tool-format action list instead, same as production.\n const devNative = options?.nativeActionsInDev === true || leanPrompt;\n const devPrompt = devNative\n ? prodPrompt\n : (options?.devSystemPrompt\n ? options.devSystemPrompt +\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT))\n : lazyContext\n ? DEV_FRAMEWORK_PROMPT_COMPACT\n : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;\n // Keep legacy names for the composition below\n const basePrompt = prodPrompt;\n\n // Mount MCP remote server — same action registry as A2A + agent chat\n const { mountMCP } = await import(\"../mcp/server.js\");\n mountMCP(nitroApp, {\n name: options?.appId\n ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)\n : \"Agent\",\n title: options?.mcpServerInfo?.title,\n appId: options?.appId,\n description:\n options?.mcpServerInfo?.description ??\n `Agent-native ${options?.appId ?? \"app\"} agent`,\n websiteUrl: options?.mcpServerInfo?.websiteUrl,\n icons: options?.mcpServerInfo?.icons,\n actions: allScripts,\n productionActions: mcpFullActions,\n ...(options?.connectorCatalog\n ? { connectorCatalog: options.connectorCatalog }\n : {}),\n askAgent: async (message: string) => {\n const mcpEngine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: options?.apiKey,\n appId: options?.appId,\n });\n const mcpModelCandidate =\n options?.model ??\n (await getStoredModelForEngine(mcpEngine, {\n appId: options?.appId,\n })) ??\n mcpEngine.defaultModel;\n const model = normalizeModelForEngine(mcpEngine, mcpModelCandidate);\n\n // Same actions as A2A — without call-agent to prevent loops.\n // In dev mode, template actions go through bash, not native tools.\n const devActiveMcp = isDevMode();\n const mcpActions = attachToolSearch(\n devActiveMcp\n ? {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...mcpActionEntries,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...mcpActionEntries,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n const mcpTools = actionsToEngineTools(mcpActions);\n\n const resources = await loadResourcesForPrompt(\n SHARED_OWNER,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(SHARED_OWNER, devActiveMcp);\n // Build the MCP handler's own prompt — always use the bash-based\n // dev prompt in dev mode because mcpActions routes template actions\n // through bash (`devScriptsForA2A`), regardless of `nativeActionsInDev`.\n const mcpDevPrompt =\n (options?.devSystemPrompt\n ? options.devSystemPrompt +\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT))\n : lazyContext\n ? DEV_FRAMEWORK_PROMPT_COMPACT\n : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;\n const systemPrompt = devActiveMcp\n ? mcpDevPrompt +\n buildRuntimeContextPrompt() +\n resources +\n schemaBlock\n : basePrompt +\n buildRuntimeContextPrompt() +\n resources +\n schemaBlock;\n\n let accumulatedText = \"\";\n const controller = new AbortController();\n\n await runAgentLoopDirectWithSoftTimeout(\n {\n engine: mcpEngine,\n model,\n systemPrompt,\n tools: mcpTools,\n messages: [\n { role: \"user\", content: [{ type: \"text\", text: message }] },\n ],\n actions: mcpActions,\n send: (event) => {\n if (event.type === \"text\") accumulatedText += event.text;\n },\n signal: controller.signal,\n },\n options?.runSoftTimeoutMs,\n );\n\n return accumulatedText || \"(no response)\";\n },\n });\n\n type OwnerContext = {\n owner: string;\n anonymous: boolean;\n name?: string;\n };\n const OWNER_CONTEXT_KEY = \"__agentNativeOwnerContext\";\n\n // Resolve owner from the H3 event's session, with an optional\n // template-provided anonymous owner for public read-only surfaces.\n const resolveOwnerContext = async (event: any): Promise<OwnerContext> => {\n const eventContext = event?.context as\n | (Record<string, unknown> & { [OWNER_CONTEXT_KEY]?: OwnerContext })\n | undefined;\n if (eventContext?.[OWNER_CONTEXT_KEY]) {\n return eventContext[OWNER_CONTEXT_KEY];\n }\n\n const session = await getSession(event);\n if (session?.email) {\n const resolved = {\n owner: session.email,\n anonymous: false,\n name: session.name,\n };\n if (eventContext) eventContext[OWNER_CONTEXT_KEY] = resolved;\n return resolved;\n }\n\n const anonymousOwner = await options?.anonymousOwner?.(event);\n if (anonymousOwner) {\n const resolved = { owner: anonymousOwner, anonymous: true };\n if (eventContext) eventContext[OWNER_CONTEXT_KEY] = resolved;\n return resolved;\n }\n\n const { createError } = await import(\"h3\");\n throw createError({\n statusCode: 401,\n statusMessage: \"Unauthenticated\",\n });\n };\n\n const getOwnerFromEvent = async (event: any): Promise<string> => {\n return (await resolveOwnerContext(event)).owner;\n };\n const getUserNameFromEvent = async (\n event: any,\n ): Promise<string | undefined> => {\n return (await resolveOwnerContext(event)).name;\n };\n\n // Auto-mount template actions as HTTP endpoints under /_agent-native/actions/\n // Include engine management script so the UI can call manage-agent-engine.\n // HTTP/frontend surface keeps the full `*All` sets so actions with\n // `agentTool: false` (hidden from every agent tool list) remain callable\n // via `useActionMutation` / `callAction` / `/_agent-native/actions/<name>`.\n const httpActions: Record<string, ActionEntry> = {\n ...discoveredActionsAll,\n ...templateScriptsAll,\n ...engineScripts,\n ...loopSettingsScripts,\n };\n // Framework-level sharing actions — merged with skipExisting semantics so\n // any template that provides a same-named action wins. When templates use\n // `loadActionsFromStaticRegistry`, `autoDiscoverActions` never runs, so\n // this is the single point that guarantees share-resource, unshare-resource,\n // list-resource-shares, and set-resource-visibility are always mounted.\n try {\n const { mergeCoreSharingActions } =\n await import(\"./action-discovery.js\");\n await mergeCoreSharingActions(httpActions);\n } catch {\n // Ignore — templates without sharing still work.\n }\n if (Object.keys(httpActions).length > 0) {\n const { mountActionRoutes } = await import(\"./action-routes.js\");\n mountActionRoutes(nitroApp, httpActions, {\n getOwnerFromEvent,\n getUserNameFromEvent,\n resolveOrgId: options?.resolveOrgId,\n });\n }\n\n const preRunGitStatusByThread = new Map<string, string | null>();\n\n async function recordPreRunGitStatus(threadId: string): Promise<void> {\n if (!isDevMode()) return;\n try {\n const { getUncommittedStatus, isGitRepo } =\n await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n preRunGitStatusByThread.set(\n threadId,\n isGitRepo(cwd) ? getUncommittedStatus(cwd) : null,\n );\n } catch {\n preRunGitStatusByThread.set(threadId, null);\n }\n }\n\n // Callback to persist agent response when run finishes (even if client disconnected).\n // Reconstructs the assistant message from buffered events and appends to thread_data.\n const onRunComplete = async (run: any, threadId: string | undefined) => {\n const runThreadId = String(run?.threadId ?? threadId ?? \"\");\n if (!threadId) {\n if (runThreadId) preRunGitStatusByThread.delete(runThreadId);\n return;\n }\n // Serialize the read-modify-write against the same thread's other\n // `thread_data` writers (setThreadQueuedMessages, setThreadEngineMeta,\n // the frontend-triggered saves below). Without the lock, a concurrent\n // queued-message save can clobber the assistant message we just\n // appended here, or vice versa.\n await withThreadDataLock(threadId, async () => {\n try {\n const thread = await getThread(threadId);\n if (!thread) {\n throw new Error(\n `Agent chat thread ${threadId} was not found while saving run ${run.runId}.`,\n );\n }\n const runOwner =\n getRequestRunContext()?.owner ?? getRequestUserEmail();\n if (runOwner && thread.ownerEmail !== runOwner) {\n throw createError({\n statusCode: 404,\n statusMessage: \"Thread not found\",\n });\n }\n\n const assistantMsg = buildAssistantMessage(\n run.events ?? [],\n run.runId,\n {\n suppressInternalContinuation: true,\n turnId:\n typeof run.turnId === \"string\" && run.turnId\n ? run.turnId\n : undefined,\n },\n );\n if (!assistantMsg) {\n // No content produced — just bump timestamp\n await updateThreadData(\n threadId,\n thread.threadData,\n thread.title,\n thread.preview,\n thread.messageCount,\n );\n return;\n }\n\n // Parse existing thread_data, append assistant message only if\n // the frontend hasn't already saved it (avoids duplicates when\n // the client is still connected during a normal flow).\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n repo = foldAssistantTurn(repo, assistantMsg, {\n runId: run.runId,\n turnId:\n typeof run.turnId === \"string\" && run.turnId\n ? run.turnId\n : undefined,\n });\n\n // Store debug metadata so we can inspect what the LLM actually\n // received (system prompt, model, engine) when diagnosing issues.\n const runCtx = getRequestRunContext();\n const debug = {\n runId: run.runId,\n systemPrompt: runCtx?.systemPrompt,\n model: runCtx?.model ?? resolvedModel,\n engine: runCtx?.engine?.name ?? \"unknown\",\n timestamp: Date.now(),\n };\n repo._debug = debug;\n const debugRuns = Array.isArray(repo._debugRuns)\n ? repo._debugRuns\n : [];\n repo._debugRuns = [...debugRuns, debug].slice(-50);\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread.title,\n meta.preview || thread.preview,\n repo.messages.length,\n );\n } catch (err) {\n // Run completion is only successful once thread_data is durable.\n throw err;\n }\n });\n\n // Keep SQL run completion gated only on durable thread data. Follow-up\n // hooks are useful, but they should never leave agent_runs stuck\n // \"running\" if an automation/checkpoint path stalls.\n void (async () => {\n // Emit agent.turn.completed for automation triggers.\n //\n // SECURITY: include `owner` so the trigger dispatcher's tenant-scope\n // check engages (see triggers/dispatcher.ts:212-218). Without an\n // owner, every user's matching `agent.turn.completed` trigger\n // would fire when ANY user's chat turn completes — cross-tenant\n // fan-out (audit 12 #9). Owner comes from the thread row when\n // available (most reliable; persisted at thread create time),\n // falling back to the current run context's owner. If neither\n // resolves we skip emission entirely rather than emit unowned.\n try {\n let ownerEmail: string | undefined;\n try {\n const ownerThread = await getThread(threadId);\n ownerEmail = ownerThread?.ownerEmail;\n } catch {\n // ignore — fall through to run-context owner\n }\n if (!ownerEmail) {\n ownerEmail = getRequestRunContext()?.owner;\n }\n if (ownerEmail) {\n const { emit } = await import(\"../event-bus/index.js\");\n emit(\n \"agent.turn.completed\",\n { threadId, model: resolvedModel },\n { owner: ownerEmail },\n );\n }\n } catch {\n // Event bus not available — skip\n }\n\n // Auto-checkpoint in dev mode after file-modifying agent turns\n if (isDevMode()) {\n try {\n const {\n createCheckpoint: gitCheckpoint,\n isGitRepo,\n hasUncommittedChanges,\n getChangedFileNames,\n getUncommittedStatus,\n } = await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n const preRunStatus = runThreadId\n ? preRunGitStatusByThread.get(runThreadId)\n : undefined;\n if (runThreadId) preRunGitStatusByThread.delete(runThreadId);\n\n // Only auto-commit checkpoints for changes produced by this run.\n // If the tree was already dirty, a checkpoint commit would sweep\n // up the user's unrelated work when a reconnect/refresh finishes.\n const postRunStatus = getUncommittedStatus(cwd);\n if (\n preRunStatus === \"\" &&\n postRunStatus?.trim() &&\n isGitRepo(cwd) &&\n hasUncommittedChanges(cwd)\n ) {\n let summary = \"\";\n\n // Try to extract the first sentence of the assistant's text response\n let assistantText = \"\";\n for (const { event } of run.events ?? []) {\n if (event.type === \"text\" && typeof event.text === \"string\") {\n assistantText += event.text;\n }\n }\n assistantText = assistantText.trim();\n if (assistantText) {\n const firstSentence = assistantText\n .split(/(?<=[.!?\\n])\\s/)[0]\n ?.replace(/\\n/g, \" \")\n .trim();\n if (firstSentence && firstSentence.length <= 120) {\n summary = firstSentence;\n } else if (firstSentence) {\n summary = firstSentence.slice(0, 117) + \"...\";\n }\n }\n\n // Fall back to listing changed files\n if (!summary) {\n const files = getChangedFileNames(cwd);\n if (files.length > 0) {\n summary = `Update ${files.join(\", \")}`;\n }\n }\n\n if (!summary) summary = \"Agent turn\";\n if (summary.length > 120)\n summary = summary.slice(0, 117) + \"...\";\n\n const sha = gitCheckpoint(cwd, summary);\n if (sha) {\n const { insertCheckpoint } =\n await import(\"../checkpoints/store.js\");\n const cpId = `cp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n await insertCheckpoint(\n cpId,\n threadId,\n run.runId,\n sha,\n summary,\n );\n }\n }\n } catch {\n // Checkpointing is best-effort — never break the run\n }\n }\n })();\n };\n\n const persistSubmittedUserMessage = async (details: {\n runId: string;\n threadId: string | undefined;\n message: string;\n attachments?: AgentChatAttachment[];\n }) => {\n const threadId = details.threadId;\n if (!threadId) return;\n const ownerEmail =\n getRequestRunContext()?.owner ?? getRequestUserEmail();\n if (!ownerEmail) return;\n\n await withThreadDataLock(threadId, async () => {\n let thread = await getThread(threadId);\n if (!thread) {\n try {\n thread = await createThread(ownerEmail, { id: threadId });\n } catch {\n thread = await getThread(threadId);\n }\n }\n if (!thread || thread.ownerEmail !== ownerEmail) {\n throw createError({\n statusCode: 404,\n statusMessage: \"Thread not found\",\n });\n }\n\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n\n repo = upsertUserMessage(\n repo,\n buildUserMessage({\n text: details.message,\n attachments: details.attachments,\n runId: details.runId,\n }),\n );\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread.title,\n meta.preview || thread.preview,\n Array.isArray(repo.messages)\n ? repo.messages.length\n : thread.messageCount,\n );\n });\n };\n\n // ─── Agent Teams: per-run send reference ─────────────────────────\n // Team tools need to emit events to the parent chat's SSE stream.\n // Each run gets its own send function, keyed by threadId so concurrent\n // requests for different threads don't clobber each other.\n const _runSendByThread = new Map<\n string,\n (event: import(\"../agent/types.js\").AgentChatEvent) => void\n >();\n const resolvedModel = options?.model ?? DEFAULT_ANTHROPIC_MODEL;\n\n // The action set a sub-agent inherits. Shared between the spawn-time team\n // tool and the `_process-run` processor route below so the durable run\n // executes with exactly the tools the orchestrator intended.\n const buildSubAgentActions = (): Record<string, ActionEntry> =>\n isDevMode()\n ? {\n // Sub-agents spawned in dev mode also invoke template actions\n // via bash, so omit them from the native tool registry.\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...devScriptsForA2A,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n };\n\n const teamTools = createTeamTools({\n getOwner: () => requireCurrentRunOwner(\"spawn or manage sub-agents\"),\n getSystemPrompt: () =>\n getRequestRunContext()?.systemPrompt ?? basePrompt,\n getActions: buildSubAgentActions,\n getEngine: () => {\n const runCtx = getRequestRunContext();\n return (\n runCtx?.engine ??\n createAnthropicEngine({\n // Sub-agents must inherit the parent run's resolved key so\n // delegations spawned by agent-teams don't silently fall back\n // to the platform key while the parent uses BYO credentials.\n apiKey:\n runCtx?.userApiKey ??\n options?.apiKey ??\n process.env.ANTHROPIC_API_KEY,\n })\n );\n },\n getModel: () => getRequestRunContext()?.model ?? resolvedModel,\n getParentThreadId: () => getRequestRunContext()?.threadId ?? \"\",\n getSend: () => {\n // Return the send for the current run's thread\n const threadId = getRequestRunContext()?.threadId ?? \"\";\n const send = _runSendByThread.get(threadId);\n return send ?? null;\n },\n });\n\n // Hook into the run lifecycle to set/clear the send reference.\n // Job management tool (manage-jobs)\n let jobTools: Record<string, ActionEntry> = {};\n try {\n const { createJobTools } = await import(\"../jobs/tools.js\");\n jobTools = createJobTools();\n } catch {}\n\n // Lean mode: only template actions + essential framework tools. Drop\n // web-request, browser tools, teams, jobs, automations, notifications,\n // progress, call-agent, and MCP entries to keep the tool list tight and\n // prevent the LLM from reaching for web-request instead of the\n // template's native actions (e.g. log-meal).\n const leanActionEntries: Record<string, ActionEntry> = {\n ...templateScripts,\n ...resourceScripts,\n ...refreshScreenTool,\n ...urlTools,\n ...chatScripts,\n ...toolActions,\n };\n const anonymousReadOnlyActions = attachToolSearch(\n filterReadOnlyActions(templateScripts),\n );\n\n // Full-database admin tools. Gated on NODE_ENV=development to match the\n // DB-admin UI + HTTP routes (which gate on the environment, not the\n // Code-mode toggle), so the agent has the same DB-admin capability the UI\n // does whenever it is available — true agent/UI parity, in App or Code mode.\n const dbAdminScripts =\n process.env.NODE_ENV === \"development\" ? createDbAdminAgentTools() : {};\n\n const prodActions = attachToolSearch({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...dbAdminScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...teamTools,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n // Sandboxed run-code for hosted production when enabled, and for the\n // app-rendered production-style handler in local dev.\n ...(canToggle || resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n // Full coding tools in production when mode is \"trusted\".\n ...(!canToggle ? prodCodingTools : {}),\n });\n\n // Wire the prod run-code bridge supplier so it sees the fully-assembled\n // prodActions registry (including MCP entries added at runtime).\n prodRunCodeToolActions = prodActions;\n\n const leanActions = attachToolSearch({\n ...leanActionEntries,\n // Lean mode still needs run-code when code execution is enabled.\n // Otherwise templates with a minimal prompt can advertise sandboxed\n // execution in the system prompt while the actual tool registry omits\n // it.\n ...(canToggle || resolvedProdCodeExec !== \"off\" ? leanRunCodeTool : {}),\n });\n leanRunCodeToolActions = leanActions;\n\n // Keep the prod action dict's MCP entries in sync when the manager's\n // server set changes at runtime (e.g. a user adds a remote MCP server\n // through the settings UI). getEngineTools() in production-agent re-reads\n // the registry per request, so updates here propagate without restart.\n mcpManager.onChange(() => {\n syncMcpActionEntries(mcpManager, prodActions);\n });\n\n // Always build the production handler (includes resource tools + call-agent + team tools)\n // In production mode (!canToggle), resolve the owner from the request session.\n const isHostedProd = !canToggle;\n\n // Lean mode: use only the template's systemPrompt + actions list.\n // Skip resource loading and schema block — those add DB round-trips\n // and tokens that minimal/voice apps don't need.\n const leanBasePrompt = (options?.systemPrompt ?? \"\") + prodActionsPrompt;\n const anonymousReadOnlyPrompt =\n (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT_COMPACT) +\n generateActionsPrompt(filterReadOnlyActions(templateScripts), \"tool\") +\n \"\\n\\nYou are answering from a public shared page. Treat the visible resource as read-only: do not create, edit, delete, comment on, share, or otherwise mutate app data. If the user asks for a change, describe what you would change or suggest signing in to edit.\";\n\n // Per-request preamble shared by both prod and dev handlers. Resolves\n // owner + user API key onto the AsyncLocalStorage run context so\n // downstream tool closures (automation, fetch, team) read the\n // current request's identity without racing against concurrent\n // requests. `extraContext` runs in every prompt variant (lean, lazy,\n // full) — if a template defined it, they opted in; framework-provided\n // content is what the token-saving modes strip.\n const prepareRun = async (event: any) => {\n const owner = await getOwnerFromEvent(event);\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n const userApiKey = await getOwnerActiveApiKey(owner);\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.requestOrigin = getOrigin(event);\n runCtx.owner = owner;\n runCtx.userApiKey = userApiKey;\n }\n const extra = await resolveExtraContext(event, owner);\n return { owner, extra };\n };\n\n const setSystemPromptOnContext = (prompt: string): string => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.systemPrompt = prompt;\n return prompt;\n };\n\n /**\n * Read the model family overlay for the currently-resolved model.\n * onEngineResolved sets runCtx.model before systemPrompt is called, so\n * this returns a non-empty string for GPT/Gemini engines.\n */\n const resolveModelOverlay = (): string => {\n const runCtx = ensureRequestRunContext();\n const model = runCtx?.model;\n if (!model) return \"\";\n return getModelFamilyOverlay(model);\n };\n\n /**\n * Returns whether this request is for a brand-new thread (no prior\n * messages). Used to gate the First-Session Personalization block:\n * once a thread has history the block is dead weight on every request.\n *\n * prepareRequest stashes `details.threadId` as `_requestThreadId` on\n * runCtx before systemPrompt is assembled. A new thread has no threadId\n * (the UI passes undefined until the first message creates the thread).\n */\n const isNewThread = (): boolean => {\n const runCtx = ensureRequestRunContext();\n return !(runCtx as any)?._requestThreadId;\n };\n\n const runtimeContextForEvent = (event: any): string => {\n const tzRaw = getHeader(event, \"x-user-timezone\");\n const timezone =\n typeof tzRaw === \"string\" &&\n tzRaw.trim().length > 0 &&\n tzRaw.trim().length < 64\n ? tzRaw.trim()\n : undefined;\n return buildRuntimeContextPrompt({ timezone });\n };\n\n // The app-rendered sidebar must never edit the app's source code\n // directly. Source-file edits can trigger HMR or full reloads of the\n // same React tree that is hosting the chat, interrupting the run and\n // losing in-progress UI state. Code edits are allowed only from the\n // outer dev frame (x-agent-native-surface: dev-frame) or from separate\n // agent surfaces such as Builder/A2A/MCP handoffs.\n const shouldBlockInProductCodeEditing = (event: any): boolean =>\n shouldBlockInProductCodeEditingSurface({\n surface: getHeader(event, \"x-agent-native-surface\"),\n userAgent: getHeader(event, \"user-agent\"),\n host: getHeader(event, \"host\"),\n });\n\n const APP_RENDERED_CHAT_NO_DIRECT_CODE_PROMPT = `\n\n<app-rendered-chat-no-direct-code-edits>\nThis chat is rendered by the app itself. It must never edit this app's source files directly, because source edits can hot-reload or replace the same UI that is hosting the chat.\n\nWhen the user asks to add a feature, edit a component, fix a bug in the app itself, change styles, add a route, scaffold a new app, run shell commands that modify code, or do anything else that requires touching source files:\n\n1. Do NOT use dev shell/filesystem tools, write code inline, list source files, propose patches, or describe file-level implementation steps from this chat.\n2. For host-app source changes in Act mode, call \\`connect-builder\\` when that tool is available so a separate Builder/cloud agent can do the work. If Builder is unavailable, give a short handoff to the outer dev frame, Agent Native Desktop, Claude Code, or Codex in the project directory.\n3. If the request is specifically to add or scaffold a new workspace app and no Builder handoff is available, mention \\`npx @agent-native/core@latest add-app\\` in this workspace directory as the CLI path.\n\nNon-code requests are still fine on this surface: read data, navigate the UI, summarize, search, create/update extensions (sandboxed Alpine.js mini-apps stored in SQL), and call template actions. The restriction is specifically about direct edits to the host app's own source files.\n</app-rendered-chat-no-direct-code-edits>`;\n\n // System-prompt note appended when production code execution is enabled.\n const prodCodeExecPromptNote =\n !canToggle && resolvedProdCodeExec !== \"off\"\n ? resolvedProdCodeExec === \"trusted\"\n ? \"\\n\\n<code-execution-mode>Full shell access is enabled (trusted mode). You have bash, read, edit, write, and run-code tools available. Use bash for file discovery, running tests and builds, and project CLIs. Use run-code for sandboxed JavaScript data processing: provider/API pagination, joins, classification, aggregation, and large-response reduction. Use `pnpm action <name>` in bash to invoke registered app actions from the shell.</code-execution-mode>\"\n : \"\\n\\n<code-execution-mode>Sandboxed code execution is enabled. The run-code tool lets you execute isolated JavaScript (ESM, top-level await) to fetch, aggregate, and reduce data. Use providerFetch(), providerFetchAll(), providerRequest(), and webFetch() inside run-code for authenticated provider calls.</code-execution-mode>\"\n : \"\";\n\n const prodHandler = createProductionAgentHandler({\n actions: leanPrompt ? leanActions : prodActions,\n systemPrompt: async (event: any) => {\n const { owner, extra } = await prepareRun(event);\n const runtimeContext = runtimeContextForEvent(event);\n const codeEditingSurfaceRestriction = shouldBlockInProductCodeEditing(\n event,\n )\n ? APP_RENDERED_CHAT_NO_DIRECT_CODE_PROMPT\n : \"\";\n // Personalization block: only include on new threads (no prior messages).\n // Once a thread exists, the agent has already run (or skipped) the flow.\n const personalizationBlock = isNewThread()\n ? FIRST_SESSION_PERSONALIZATION\n : \"\";\n // Per-model overlay: nudge GPT/Gemini engines toward our behavioral norms.\n const modelOverlay = resolveModelOverlay();\n if (leanPrompt) {\n return setSystemPromptOnContext(\n leanBasePrompt +\n runtimeContext +\n codeEditingSurfaceRestriction +\n prodCodeExecPromptNote +\n extra +\n modelOverlay,\n );\n }\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n // In lazy context mode, skip embedding the full schema — the agent\n // calls `db-schema` on demand. This saves ~1-2K tokens per request.\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return setSystemPromptOnContext(\n basePrompt +\n personalizationBlock +\n runtimeContext +\n resources +\n schemaBlock +\n codeEditingSurfaceRestriction +\n prodCodeExecPromptNote +\n extra +\n modelOverlay,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: async (details) => {\n // Stash the threadId on runCtx so systemPrompt can check isNewThread().\n // prepareRequest fires before systemPromptPromise starts, so this is safe.\n const runCtxForPrepare = ensureRequestRunContext();\n if (runCtxForPrepare && details.threadId) {\n (runCtxForPrepare as any)._requestThreadId = details.threadId;\n }\n\n // Drain any parent-completion injections queued by finished sub-agents\n // and prepend them to the user message so the orchestrator sees results\n // at the start of this turn rather than only after a manual poll.\n const threadId = details.threadId;\n let completionPrefix = \"\";\n if (threadId && !details.internalContinuation) {\n try {\n const {\n drainParentCompletionInjections,\n formatParentCompletionInjections,\n } = await import(\"./agent-teams.js\");\n const injections =\n await drainParentCompletionInjections(threadId);\n if (injections.length > 0) {\n completionPrefix = formatParentCompletionInjections(injections);\n }\n } catch {\n // best-effort — never break the run\n }\n }\n // Also run the template-provided prepareRequest (if any).\n const templateResult = await options?.prepareRequest?.(details);\n if (!completionPrefix) return templateResult ?? undefined;\n const baseMessage =\n typeof templateResult === \"object\" &&\n templateResult &&\n typeof templateResult.message === \"string\"\n ? templateResult.message\n : details.message;\n const message = `${completionPrefix}\\n\\n${baseMessage}`;\n return {\n ...(typeof templateResult === \"object\" && templateResult\n ? templateResult\n : {}),\n message,\n };\n },\n skipFilesContext: leanPrompt,\n ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (event: import(\"../agent/types.js\").AgentChatEvent) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n // Resolve owner from session for usage attribution in hosted prod\n resolveOwnerEmail: isHostedProd ? getOwnerFromEvent : undefined,\n });\n\n const anonymousHandler =\n options?.anonymousOwner && options.anonymousReadOnly !== false\n ? createProductionAgentHandler({\n actions: anonymousReadOnlyActions,\n systemPrompt: async (event: any) => {\n const { extra } = await prepareRun(event);\n return setSystemPromptOnContext(\n anonymousReadOnlyPrompt +\n runtimeContextForEvent(event) +\n extra,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: options?.prepareRequest,\n skipFilesContext: true,\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (\n event: import(\"../agent/types.js\").AgentChatEvent,\n ) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n resolveOwnerEmail: getOwnerFromEvent,\n })\n : null;\n\n // Build the dev handler (with filesystem/bash/db tools) if environment allows toggling\n let devHandler: ReturnType<typeof createProductionAgentHandler> | null =\n null;\n if (canToggle) {\n const { createDevScriptRegistry } =\n await import(\"../scripts/dev/index.js\");\n // Dev mode: template actions (templateScripts and discoveredActions) are\n // intentionally OMITTED from the native tool registry. The agent invokes\n // them via `bash(command=\"pnpm action <name> ...\")` instead. This mirrors\n // how Claude Code works locally and dramatically reduces the rate of\n // degenerate empty-object tool calls. The CLI syntax for each action is\n // listed in the dev system prompt's \"Available Actions\" section.\n // In lean mode — or when `nativeActionsInDev` is set — expose the\n // template's actions as native tools instead of routing through bash.\n // Templates with structured-arg actions (objects/arrays) need this to\n // avoid round-tripping JSON through the CLI parser.\n const devActions = attachToolSearch(\n leanPrompt\n ? leanActions\n : devNative\n ? prodActions\n : {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...callAgentScript,\n ...teamTools,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...(await createDevScriptRegistry()),\n // Full-database admin tools (NODE_ENV=development gate — see\n // dbAdminScripts; also in prodActions so App mode has them too).\n ...dbAdminScripts,\n // run-code sandbox is always available in dev mode.\n ...devRunCodeTool,\n },\n );\n // Wire the late-binding supplier for devRunCodeTool so the bridge can\n // call back into the fully-assembled devActions registry.\n devRunCodeToolActions = devActions;\n // Keep dev action dict in sync with runtime MCP additions. When\n // native-actions mode is on (lean or `nativeActionsInDev`), devActions\n // === prodActions so the prod listener already covers it.\n if (devActions !== prodActions && devActions !== leanActions) {\n mcpManager.onChange(() => {\n syncMcpActionEntries(mcpManager, devActions);\n });\n }\n devHandler = createProductionAgentHandler({\n actions: devActions,\n systemPrompt: async (event: any) => {\n const { owner, extra } = await prepareRun(event);\n const runtimeContext = runtimeContextForEvent(event);\n const personalizationBlock = isNewThread()\n ? FIRST_SESSION_PERSONALIZATION\n : \"\";\n const modelOverlay = resolveModelOverlay();\n if (leanPrompt) {\n return setSystemPromptOnContext(\n leanBasePrompt + runtimeContext + extra + modelOverlay,\n );\n }\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, true);\n return setSystemPromptOnContext(\n devPrompt +\n personalizationBlock +\n runtimeContext +\n resources +\n schemaBlock +\n extra +\n modelOverlay,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: options?.prepareRequest,\n skipFilesContext: leanPrompt,\n ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (event: import(\"../agent/types.js\").AgentChatEvent) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n });\n }\n\n // Resolve mention providers\n const rawProviders = options?.mentionProviders;\n const mentionProviders: Record<string, MentionProvider> =\n typeof rawProviders === \"function\"\n ? await rawProviders()\n : (rawProviders ?? {});\n\n // currentDevMode + persistence were hoisted to the top of this function\n // so every closure built below can close over the live flag.\n\n // Mount mode endpoint — GET returns current mode, POST toggles it (localhost only)\n getH3App(nitroApp).use(\n `${routePath}/mode`,\n defineEventHandler(async (event) => {\n if (getMethod(event) === \"POST\") {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Mode switching not available in production\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Mode switching only available on localhost\" };\n }\n const body = await readBody(event);\n if (typeof body?.devMode === \"boolean\") {\n currentDevMode = body.devMode;\n } else {\n currentDevMode = !currentDevMode;\n }\n try {\n await putSetting(AGENT_MODE_SETTING_KEY, {\n devMode: currentDevMode,\n });\n } catch {\n // Persistence is best-effort — in-memory flag still applies for\n // the lifetime of this process even if the settings write fails.\n }\n return {\n devMode: currentDevMode,\n codeMode: currentDevMode,\n canToggle,\n };\n }\n return {\n devMode: currentDevMode,\n codeMode: currentDevMode,\n canToggle,\n };\n }),\n );\n\n // Self-heal the RunsTray: when the tray lists this owner's runs, first\n // reconcile their in-flight sub-agent runs (re-fire dropped dispatches,\n // mark dead runs failed) so the tray reflects precise status without\n // waiting on the orchestrator chat to poll. Registered here to keep the\n // generic progress store free of feature-module imports.\n setProgressPreListHook((owner, context) =>\n runWithRequestContext({ userEmail: owner }, () =>\n reconcileAgentTeamRunsForOwner(owner, context.event),\n ),\n );\n\n // ─── Agent Teams: durable sub-agent run processor ─────────────────\n // Self-fire target for `spawnTask`. Executes one chunk of a queued\n // sub-agent in this fresh function invocation (its own timeout budget)\n // so background sub-agents survive serverless instead of dying as a\n // detached promise. Mounted here so it closes over the sub-agent action\n // set / base prompt / engine (per-deployment closures that can't be\n // serialized into the queue). HMAC-authed with the same internal-token\n // scheme as the A2A/webhook processors.\n getH3App(nitroApp).use(\n AGENT_TEAM_PROCESS_RUN_PATH,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n const body = (await readBody(event)) as {\n taskId?: unknown;\n mode?: unknown;\n noProgressCount?: unknown;\n } | null;\n const taskId =\n body && typeof body.taskId === \"string\" ? body.taskId : \"\";\n if (!taskId) {\n setResponseStatus(event, 400);\n return { error: \"taskId required\" };\n }\n const mode: \"start\" | \"continue\" =\n body?.mode === \"continue\" ? \"continue\" : \"start\";\n const noProgressCount =\n typeof body?.noProgressCount === \"number\"\n ? body.noProgressCount\n : undefined;\n\n if (hasConfiguredA2ASecret()) {\n const tok = extractBearerToken(getHeader(event, \"authorization\"));\n if (!verifyInternalToken(taskId, tok ?? \"\")) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired processor token\" };\n }\n } else if (isA2AProductionRuntime()) {\n setResponseStatus(event, 503);\n return {\n error:\n \"Agent Teams processor not configured — set A2A_SECRET on this deployment.\",\n };\n }\n\n try {\n return await processAgentTeamRun({\n taskId,\n mode,\n event,\n noProgressCount,\n resolveConfig: async ({ payload, ownerEmail, orgId: _orgId }) => {\n // Resolve the owner's API key so BYO-key sub-agents use the\n // same credentials as the parent chat.\n let apiKey: string | undefined;\n try {\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n apiKey =\n (await getOwnerActiveApiKey(ownerEmail)) ?? undefined;\n } catch {\n apiKey = undefined;\n }\n // Use the same resolveEngine path as the A2A and MCP\n // processors so Builder-gateway/OpenAI users get their\n // configured engine instead of always hitting the Anthropic SDK.\n const engine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: apiKey ?? options?.apiKey,\n appId: options?.appId,\n });\n const modelCandidate =\n payload.model ??\n (await getStoredModelForEngine(engine, {\n appId: options?.appId,\n })) ??\n engine.defaultModel ??\n resolvedModel;\n const model = normalizeModelForEngine(engine, modelCandidate);\n return {\n baseSystemPrompt: basePrompt,\n actions: buildSubAgentActions(),\n engine,\n model,\n };\n },\n });\n } catch (err: any) {\n console.error(\"[agent-teams] _process-run failed:\", err);\n setResponseStatus(event, 500);\n return { error: \"process-run failed\" };\n }\n }),\n );\n\n const modelDefaultsAppId =\n normalizeAgentAppModelDefaultAppId(\n options?.appId ??\n process.env.AGENT_NATIVE_APP_ID ??\n process.env.VITE_AGENT_NATIVE_TEMPLATE ??\n \"app\",\n ) ?? \"app\";\n\n const resolveModelDefaultsContext = async (event: any) => {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) {\n return {\n ok: false as const,\n status: 401,\n error: \"Authentication required\",\n };\n }\n\n let orgCtx: {\n orgId?: string | null;\n orgName?: string | null;\n role?: string | null;\n } | null = null;\n try {\n const { getOrgContext } = await import(\"../org/context.js\");\n orgCtx = await getOrgContext(event);\n } catch {\n orgCtx = null;\n }\n\n const orgId =\n (options?.resolveOrgId\n ? await options.resolveOrgId(event)\n : (orgCtx?.orgId ?? session.orgId ?? null)) ?? null;\n const canUpdate = await canUpdateAgentAppModelDefaultSettings(\n session.email,\n orgId,\n );\n\n return {\n ok: true as const,\n userEmail: session.email,\n orgId,\n orgName: orgCtx?.orgId === orgId ? (orgCtx.orgName ?? null) : null,\n role: orgCtx?.orgId === orgId ? (orgCtx.role ?? null) : null,\n canUpdate,\n };\n };\n\n const listModelDefaultEngineOptions = async (ctx: {\n userEmail?: string;\n orgId?: string | null;\n }) => {\n registerBuiltinEngines();\n return runWithRequestContext(\n {\n userEmail: ctx.userEmail,\n orgId: ctx.orgId ?? undefined,\n },\n () =>\n Promise.all(\n listAgentEngines().map(async (entry) => ({\n name: entry.name,\n label: entry.label,\n description: entry.description,\n defaultModel: entry.defaultModel,\n supportedModels: entry.supportedModels,\n requiredEnvVars: entry.requiredEnvVars,\n installPackage: entry.installPackage,\n packageInstalled: isAgentEnginePackageInstalled(entry),\n configured: await isStoredEngineUsableForRequest(\n { engine: entry.name, model: entry.defaultModel },\n entry,\n ).catch(() => false),\n })),\n ),\n );\n };\n\n const buildModelDefaultsPayload = async (event: any, appId: string) => {\n const ctx = await resolveModelDefaultsContext(event);\n if (!ctx.ok) return ctx;\n const settings = await readAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n appId,\n );\n return {\n ok: true as const,\n ...settings,\n canUpdate: ctx.canUpdate,\n orgId: ctx.orgId,\n orgName: ctx.orgName,\n role: ctx.role,\n engines: await listModelDefaultEngineOptions(ctx),\n };\n };\n\n // GET/PUT/DELETE /_agent-native/agent-model-defaults — org-scoped\n // per-app default engine/model used when a chat request does not carry\n // an explicit composer model selection.\n getH3App(nitroApp).use(\n \"/_agent-native/agent-model-defaults\",\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n const query = getQuery(event);\n const queryAppId =\n typeof query.appId === \"string\" ? query.appId : undefined;\n const appId =\n normalizeAgentAppModelDefaultAppId(queryAppId) ??\n modelDefaultsAppId;\n\n if (method === \"GET\") {\n const payload = await buildModelDefaultsPayload(event, appId);\n if (payload.ok === false) {\n setResponseStatus(event, payload.status);\n return { error: payload.error };\n }\n return payload;\n }\n\n if (method !== \"PUT\" && method !== \"DELETE\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const ctx = await resolveModelDefaultsContext(event);\n if (ctx.ok === false) {\n setResponseStatus(event, ctx.status);\n return { error: ctx.error };\n }\n if (!ctx.canUpdate) {\n setResponseStatus(event, 403);\n return {\n error: ctx.orgId\n ? \"Only organization owners and admins can change app model defaults.\"\n : \"You cannot change app model defaults.\",\n };\n }\n\n if (method === \"DELETE\") {\n await resetAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n appId,\n );\n return buildModelDefaultsPayload(event, appId);\n }\n\n const body = await readBody(event).catch(() => ({}));\n const bodyAppId =\n typeof body?.appId === \"string\" ? body.appId : undefined;\n const targetAppId =\n normalizeAgentAppModelDefaultAppId(bodyAppId) ?? appId;\n const engine =\n typeof body?.engine === \"string\" ? body.engine.trim() : \"\";\n const model =\n typeof body?.model === \"string\" ? body.model.trim() : \"\";\n if (!engine || !model) {\n setResponseStatus(event, 400);\n return { error: \"engine and model are required\" };\n }\n const entry = getAgentEngineEntry(engine);\n if (!entry) {\n setResponseStatus(event, 400);\n return { error: `Unknown engine: ${engine}` };\n }\n if (!isAgentEnginePackageInstalled(entry)) {\n setResponseStatus(event, 400);\n return {\n error: `Engine \"${engine}\" requires optional packages that are not installed in this app. Run: pnpm add ${entry.installPackage}`,\n };\n }\n if (\n entry.name === \"builder\" &&\n normalizeModelForEngine(entry, model) !== model\n ) {\n setResponseStatus(event, 400);\n return {\n error: `Model \"${model}\" is not supported by Builder. Choose one of: ${entry.supportedModels.join(\", \")}`,\n };\n }\n\n await writeAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n targetAppId,\n { engine, model, updatedBy: ctx.userEmail },\n );\n return buildModelDefaultsPayload(event, targetAppId);\n }),\n );\n\n // Mount save-key BEFORE the prefix handler so it isn't shadowed.\n // Persists the user's API key in `app_secrets` (encrypted, scope=user,\n // scopeId=email). Hard rule: never mutates process.env, never writes\n // .env. User-pasted secrets must not become deploy-level identity —\n // that's the cross-tenant leak class (KVesta Space, 2026-04).\n // Consumers read these values per-request via `resolveSecret(key)`.\n getH3App(nitroApp).use(\n `${routePath}/save-key`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = await readBody(event);\n const { key, provider: rawProvider } = body as {\n key?: string;\n provider?: string;\n };\n const provider = rawProvider || \"anthropic\";\n\n if (!key || typeof key !== \"string\" || !key.trim()) {\n setResponseStatus(event, 400);\n return { error: \"API key is required\" };\n }\n\n const trimmedKey = key.trim();\n\n const ownerEmail = await getOwnerFromEvent(event);\n if (!ownerEmail) {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n }\n\n const providerToEnv: Record<string, string> = {\n anthropic: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n google: \"GOOGLE_GENERATIVE_AI_API_KEY\",\n groq: \"GROQ_API_KEY\",\n mistral: \"MISTRAL_API_KEY\",\n cohere: \"COHERE_API_KEY\",\n };\n const secretKey =\n providerToEnv[provider] ?? `${provider.toUpperCase()}_API_KEY`;\n\n try {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n await writeAppSecret({\n key: secretKey,\n value: trimmedKey,\n scope: \"user\",\n scopeId: ownerEmail,\n });\n } catch (err) {\n console.error(\n \"[agent-chat] save-key persistence failed:\",\n err instanceof Error ? err.message : err,\n );\n setResponseStatus(event, 500);\n return {\n error:\n \"Failed to persist API key. Please try again or contact support.\",\n };\n }\n\n return { ok: true };\n }),\n );\n\n // Mount file search endpoint\n getH3App(nitroApp).use(\n `${routePath}/files`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const query = getQuery(event);\n const q = typeof query.q === \"string\" ? query.q.toLowerCase() : \"\";\n\n const files: Array<{\n path: string;\n name: string;\n source: \"codebase\" | \"resource\";\n type: string;\n }> = [];\n const seen = new Set<string>();\n\n // In dev mode, walk the filesystem\n if (currentDevMode) {\n const codebaseFiles: Array<{\n path: string;\n name: string;\n type: \"file\" | \"folder\";\n }> = [];\n try {\n await collectFiles(process.cwd(), \"\", 0, codebaseFiles);\n } catch {\n // Filesystem access failed — skip\n }\n for (const f of codebaseFiles) {\n if (!seen.has(f.path)) {\n seen.add(f.path);\n files.push({\n path: f.path,\n name: f.name,\n source: \"codebase\",\n type: f.type,\n });\n }\n }\n }\n\n // Query resources\n try {\n const resources = [\n ...(await resourceList(SHARED_OWNER)),\n ...(await resourceList(WORKSPACE_OWNER)),\n ];\n for (const r of resources) {\n if (!seen.has(r.path)) {\n seen.add(r.path);\n files.push({\n path: r.path,\n name: r.path.split(\"/\").pop() || r.path,\n source: \"resource\",\n type: \"file\",\n });\n }\n }\n } catch {\n // Resources not available — skip\n }\n\n // Filter by query and limit\n const filtered = q\n ? files.filter((f) => f.path.toLowerCase().includes(q))\n : files;\n\n return { files: filtered.slice(0, 30) };\n }),\n );\n\n // Mount skills listing endpoint\n getH3App(nitroApp).use(\n `${routePath}/skills`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const skills: Array<{\n name: string;\n description?: string;\n path: string;\n source: \"codebase\" | \"resource\";\n }> = [];\n const seenNames = new Set<string>();\n\n // In dev mode, scan .agents/skills/ plus legacy .agent/skills/.\n if (currentDevMode) {\n try {\n const _fs = await lazyFs();\n const skillRoots = [\n {\n dir: nodePath.join(process.cwd(), \".agents\", \"skills\"),\n display: \".agents/skills\",\n },\n {\n dir: nodePath.join(process.cwd(), \".agent\", \"skills\"),\n display: \".agent/skills\",\n },\n ];\n for (const root of skillRoots) {\n let entries: Array<{\n name: string;\n isDirectory: () => boolean;\n isFile: () => boolean;\n }>;\n try {\n entries = _fs.readdirSync(root.dir, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const entry of entries) {\n // Support both flat .md files and subdirectory-based skills (dir/SKILL.md)\n let skillFilePath: string;\n let skillRelPath: string;\n\n if (entry.isDirectory()) {\n // Subdirectory layout: <skills-root>/<name>/SKILL.md\n const candidate = nodePath.join(\n root.dir,\n entry.name,\n \"SKILL.md\",\n );\n if (!_fs.existsSync(candidate)) continue;\n skillFilePath = candidate;\n skillRelPath = `${root.display}/${entry.name}/SKILL.md`;\n } else if (entry.isFile() && entry.name.endsWith(\".md\")) {\n // Flat layout: <skills-root>/<name>.md\n skillFilePath = nodePath.join(root.dir, entry.name);\n skillRelPath = `${root.display}/${entry.name}`;\n } else {\n continue;\n }\n\n try {\n const content = _fs.readFileSync(skillFilePath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n if (fm.userInvocable === false) continue;\n const skillName =\n fm.name || entry.name.replace(/\\.md$/, \"\");\n if (!seenNames.has(skillName)) {\n seenNames.add(skillName);\n skills.push({\n name: skillName,\n description: fm.description,\n path: skillRelPath,\n source: \"codebase\",\n });\n }\n } catch {\n // Could not read individual skill file — skip\n }\n }\n }\n } catch {\n // Skill directories don't exist or are not readable — skip.\n }\n }\n\n // Query accessible resources with skills/ prefix. Personal skills\n // need to show alongside shared skills so slash/menu invocation can\n // find both `learn` and `learn-shared`.\n try {\n const skillsOwner = await getOwnerFromEvent(event).catch(\n () => undefined,\n );\n let skillsOrgId: string | undefined;\n if (options?.resolveOrgId) {\n try {\n skillsOrgId = (await options.resolveOrgId(event)) ?? undefined;\n } catch {\n skillsOrgId = undefined;\n }\n }\n if (skillsOwner) await ensurePersonalDefaults(skillsOwner);\n const resourceSkills = skillsOwner\n ? await resourceListAccessible(skillsOwner, \"skills/\", {\n userEmail: skillsOwner,\n orgId: skillsOrgId ?? null,\n })\n : [\n ...(await resourceList(SHARED_OWNER, \"skills/\")),\n ...(await resourceList(WORKSPACE_OWNER, \"skills/\")),\n ];\n resourceSkills.sort((a, b) => {\n const ownerOrder =\n (a.owner === skillsOwner\n ? 0\n : a.owner === SHARED_OWNER\n ? 1\n : a.owner === WORKSPACE_OWNER\n ? 2\n : 3) -\n (b.owner === skillsOwner\n ? 0\n : b.owner === SHARED_OWNER\n ? 1\n : b.owner === WORKSPACE_OWNER\n ? 2\n : 3);\n if (ownerOrder !== 0) return ownerOrder;\n const pathOrder =\n (a.path.endsWith(\"/SKILL.md\") ? 0 : 1) -\n (b.path.endsWith(\"/SKILL.md\") ? 0 : 1);\n if (pathOrder !== 0) return pathOrder;\n return a.path.localeCompare(b.path);\n });\n for (const r of resourceSkills) {\n // Try to get content to parse frontmatter\n let skillName = getSkillNameFromPath(r.path);\n let description: string | undefined;\n let userInvocable: boolean | undefined;\n try {\n const full = await resourceGet(\n r.id,\n skillsOwner\n ? { userEmail: skillsOwner, orgId: skillsOrgId ?? null }\n : undefined,\n );\n if (full) {\n const fm = parseSkillFrontmatter(full.content);\n if (fm.name) skillName = fm.name;\n description = fm.description;\n userInvocable = fm.userInvocable;\n }\n } catch {\n // Could not read resource content — use path-based name\n }\n if (userInvocable === false) continue;\n if (!seenNames.has(skillName)) {\n seenNames.add(skillName);\n skills.push({\n name: skillName,\n description,\n path: r.path,\n source: \"resource\",\n });\n }\n }\n } catch {\n // Resources not available — skip\n }\n\n const result: {\n skills: typeof skills;\n hint?: string;\n } = { skills };\n\n if (skills.length === 0) {\n result.hint =\n \"No skills found. Add skill files under skills/ in Resources. Learn more: https://agent-native.com/docs/resources#skills\";\n }\n\n return result;\n }),\n );\n\n // Mount unified mentions endpoint (files + resources + custom providers)\n getH3App(nitroApp).use(\n `${routePath}/mentions`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Resolve the caller and run the entire stream inside a request\n // context so custom mention providers can use `accessFilter` /\n // `resolveAccess` when querying ownable tables. Without this,\n // a provider that searches `decks` (or any sharable resource)\n // would see every row regardless of ownership.\n const mentionsOwner = await getOwnerFromEvent(event).catch(\n () => undefined,\n );\n let mentionsOrgId: string | undefined;\n if (options?.resolveOrgId) {\n try {\n const resolved = await options.resolveOrgId(event);\n mentionsOrgId = resolved ?? undefined;\n } catch {\n mentionsOrgId = undefined;\n }\n }\n\n const query = getQuery(event);\n const q = typeof query.q === \"string\" ? query.q.toLowerCase() : \"\";\n\n interface MentionItemResponse {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n source: string;\n refType: string;\n refPath?: string;\n refId?: string;\n section?: string;\n }\n\n const matchesQuery = (item: MentionItemResponse) =>\n !q ||\n item.label.toLowerCase().includes(q) ||\n (item.description?.toLowerCase().includes(q) ?? false);\n\n const enc = new TextEncoder();\n\n // Stream NDJSON — each source flushes its batch as soon as it's ready.\n setResponseHeader(event, \"Content-Type\", \"application/x-ndjson\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n\n const stream = new ReadableStream({\n start(controller) {\n return runWithRequestContext(\n {\n userEmail: mentionsOwner,\n orgId: mentionsOrgId,\n },\n () => mentionsStreamWork(controller),\n );\n },\n cancel() {\n // Client disconnected — stop enqueuing\n },\n });\n\n return stream;\n\n async function mentionsStreamWork(\n controller: ReadableStreamDefaultController<Uint8Array>,\n ) {\n const MAX_RESULTS = 50;\n let totalSent = 0;\n let cancelled = false;\n\n const flush = (batch: MentionItemResponse[]) => {\n if (cancelled) return;\n const filtered = batch.filter(matchesQuery);\n if (filtered.length === 0) return;\n const remaining = MAX_RESULTS - totalSent;\n const toSend = filtered.slice(0, remaining);\n if (toSend.length > 0) {\n totalSent += toSend.length;\n try {\n controller.enqueue(\n enc.encode(JSON.stringify({ items: toSend }) + \"\\n\"),\n );\n } catch {\n // Stream was closed by client\n cancelled = true;\n }\n }\n };\n\n // All sources run in parallel; each flushes independently.\n const sources: Promise<void>[] = [];\n\n // 1. Resources from SQL (fast — flush first)\n sources.push(\n (async () => {\n try {\n const resources = mentionsOwner\n ? await resourceListAccessible(mentionsOwner)\n : [\n ...(await resourceList(WORKSPACE_OWNER)),\n ...(await resourceList(SHARED_OWNER)),\n ];\n flush(\n resources.map((r) => {\n const scope = resourceScopeForOwner(\n r.owner,\n mentionsOwner,\n );\n return {\n id: `resource:${r.path}`,\n label: r.path.split(\"/\").pop() || r.path,\n description: r.path,\n icon: \"file\",\n source: `resource:${scope}`,\n refType: \"file\",\n refPath: r.path,\n section: \"Files\",\n };\n }),\n );\n } catch {}\n })(),\n );\n\n // 2. Codebase files (dev mode only — can be slow on large repos)\n if (currentDevMode) {\n sources.push(\n (async () => {\n const codebaseFiles: Array<{\n path: string;\n name: string;\n type: \"file\" | \"folder\";\n }> = [];\n try {\n await collectFiles(process.cwd(), \"\", 0, codebaseFiles);\n } catch {}\n flush(\n codebaseFiles.map((f) => ({\n id: `codebase:${f.path}`,\n label: f.name,\n description: f.path !== f.name ? f.path : undefined,\n icon: f.type,\n source: \"codebase\",\n refType: \"file\",\n refPath: f.path,\n section: \"Files\",\n })),\n );\n })(),\n );\n }\n\n // 3. Custom mention providers (each flushes independently)\n for (const [key, provider] of Object.entries(mentionProviders)) {\n sources.push(\n (async () => {\n try {\n const providerItems = await provider.search(q, event);\n flush(\n providerItems.map((item) => ({\n id: item.id,\n label: item.label,\n description: item.description,\n icon: item.icon || provider.icon || \"file\",\n source: key,\n refType: item.refType,\n refPath: item.refPath,\n refId: item.refId,\n section: provider.label,\n })),\n );\n } catch (e) {\n console.error(\n `[agent-native] Mention provider \"${key}\" failed:`,\n e,\n );\n }\n })(),\n );\n }\n\n // 4. Custom workspace agents\n sources.push(\n (async () => {\n try {\n const owner = await getOwnerFromEvent(event);\n const { listAccessibleCustomAgents } =\n await import(\"../resources/agents.js\");\n const agents = await listAccessibleCustomAgents(owner);\n flush(\n agents.map((agent) => ({\n id: `custom-agent:${agent.id}`,\n label: agent.name,\n description: agent.description || agent.path,\n icon: \"agent\",\n source: \"agent:custom\",\n refType: \"custom-agent\",\n refPath: agent.path,\n refId: agent.id,\n section: \"Agents\",\n })),\n );\n } catch (e) {\n console.error(\n \"[agent-native] Custom agent discovery failed:\",\n e,\n );\n }\n })(),\n );\n\n // 5. Peer agent discovery (network call — often slowest)\n sources.push(\n (async () => {\n try {\n const agents = await discoverAgents(options?.appId);\n flush(\n agents.map((agent) => ({\n id: `agent:${agent.id}`,\n label: agent.name,\n description: agent.description,\n icon: \"agent\",\n source: \"agent\",\n refType: \"agent\",\n refPath: agent.url,\n refId: agent.id,\n section: \"Connected Agents\",\n })),\n );\n } catch (e) {\n console.error(\"[agent-native] Agent discovery failed:\", e);\n }\n })(),\n );\n\n await Promise.all(sources);\n if (!cancelled) controller.close();\n }\n }),\n );\n\n // ─── Generate thread title ──────────────────────────────────────────\n getH3App(nitroApp).use(\n `${routePath}/generate-title`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n const ownerEmail = await getOwnerFromEvent(event);\n\n // Per-user rate limit: 10 calls / 60s. Prevents an authenticated\n // user from spamming the endpoint to exhaust shared Anthropic\n // credits on platform-key deployments.\n const now = Date.now();\n const limitWindowMs = 60_000;\n const limitMax = 10;\n const recent = (generateTitleRateLimit.get(ownerEmail) ?? []).filter(\n (t) => now - t < limitWindowMs,\n );\n if (recent.length >= limitMax) {\n setResponseStatus(event, 429);\n return { error: \"Rate limit exceeded\" };\n }\n recent.push(now);\n generateTitleRateLimit.set(ownerEmail, recent);\n\n const body = await readBody(event);\n const message = body?.message;\n if (!message || typeof message !== \"string\") {\n setResponseStatus(event, 400);\n return { error: \"message is required\" };\n }\n // Strip mention markup: @[Name|type] → @Name\n const cleanMessage = message.replace(\n /@\\[([^\\]|]+)\\|[^\\]]*\\]/g,\n \"@$1\",\n );\n // Mirror the chat-run resolution so BYO-key users have title\n // generation billed to their own key instead of the platform key.\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n const apiKey = userApiKey ?? process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n // Fallback: truncate the message\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n try {\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: \"claude-haiku-4-5-20251001\",\n max_tokens: 30,\n messages: [\n {\n role: \"user\",\n content: `Generate a very short title (3-6 words, no quotes) for a chat that starts with this message:\\n\\n${cleanMessage.slice(0, 500)}`,\n },\n ],\n }),\n });\n if (!res.ok) {\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n const data = (await res.json()) as {\n content?: Array<{ type: string; text?: string }>;\n };\n const text = data.content?.[0]?.text?.trim();\n return { title: text || cleanMessage.trim().slice(0, 60) };\n } catch {\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n }),\n );\n\n // ─── Run management endpoints (for hot-reload resilience) ─────────────\n\n // GET /runs/active?threadId=X — check if there's an active run for a thread\n getH3App(nitroApp).use(\n `${routePath}/runs`,\n defineEventHandler(async (event) => {\n // Auth check — ensure the user is authenticated\n const owner = await getOwnerFromEvent(event);\n\n const method = getMethod(event);\n const url = event.node?.req?.url || event.path || \"\";\n\n // Authorization: a run's events/abort and a thread's active-run\n // status must only be exposed to the user who OWNS the thread.\n // agent_runs carries no owner column — ownership lives on the\n // chat_threads row via thread_id. callerOwnsRun/callerOwnsThread\n // (agent/run-ownership.ts) resolve the run's thread (in-memory first,\n // SQL fallback) and compare its ownerEmail. Without this, any\n // authenticated tenant who learns another tenant's runId/threadId\n // could stream their live agent turn (assistant text + tool-result\n // payloads) or abort their run.\n const ownsThread = (threadId: string | null | undefined) =>\n callerOwnsThread(owner, threadId);\n const ownsRun = (runId: string) => callerOwnsRun(owner, runId);\n\n // Route: GET /runs/list?goalId=agent-team\n // Returns hosted Agent Teams in the Code hub-compatible run shape.\n const listMatch =\n url.match(/\\/runs\\/list(?:[/?]|$)/) ||\n url.match(/^\\/list(?:[/?]|$)/);\n if (listMatch && method === \"GET\") {\n const query = getQuery(event);\n const goalId = query.goalId ? String(query.goalId) : undefined;\n const runs = await runWithRequestContext(\n { userEmail: owner },\n async () => {\n if (goalId && goalId !== \"agent-team\") return [];\n const { listAgentTeamBackgroundRuns } =\n await import(\"./agent-teams.js\");\n return listAgentTeamBackgroundRuns();\n },\n );\n return { status: \"ok\", goalId, runs };\n }\n\n // Route: POST /runs/:id/stop\n // Stops a running Agent Teams background run (durable task-based).\n // Distinct from /abort which operates on in-memory run-manager runs.\n const stopMatch =\n url.match(/\\/runs\\/([^/?]+)\\/stop/) ||\n url.match(/^\\/([^/?]+)\\/stop/);\n if (stopMatch && method === \"POST\") {\n const runId = decodeURIComponent(stopMatch[1]);\n const { stopAgentTeamBackgroundRun } =\n await import(\"./agent-teams.js\");\n const result = await runWithRequestContext(\n { userEmail: owner },\n () => stopAgentTeamBackgroundRun(runId),\n );\n if (!result.ok) {\n setResponseStatus(\n event,\n result.error === \"Task not found\" ? 404 : 400,\n );\n return { ok: false, error: result.error };\n }\n return { ok: true };\n }\n\n // Route: POST /runs/:id/abort\n // Match both full URL (/runs/{id}/abort) and h3 prefix-stripped (/{id}/abort)\n const abortMatch =\n url.match(/\\/runs\\/([^/?]+)\\/abort/) ||\n url.match(/^\\/([^/?]+)\\/abort/);\n if (abortMatch && method === \"POST\") {\n const runId = decodeURIComponent(abortMatch[1]);\n if (!(await ownsRun(runId))) {\n // 404 (not 403) so run existence isn't leaked to non-owners.\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n let reason = \"user\";\n try {\n const body = await readBody(event);\n if (body?.reason === \"no_progress\") {\n reason = \"no_progress\";\n }\n } catch {\n // Empty/invalid body — keep the default user abort reason.\n }\n abortRun(runId, reason); // Aborts in-memory + marks aborted in SQL\n return { ok: true };\n }\n\n // Route: GET /runs/:id/background-events\n // Returns Agent Teams transcript events in the shared background-run shape.\n const backgroundEventsMatch =\n url.match(/\\/runs\\/([^/?]+)\\/background-events/) ||\n url.match(/^\\/([^/?]+)\\/background-events/);\n if (backgroundEventsMatch && method === \"GET\") {\n const runId = decodeURIComponent(backgroundEventsMatch[1]);\n const {\n getAgentTeamBackgroundRun,\n listAgentTeamBackgroundTranscriptEvents,\n } = await import(\"./agent-teams.js\");\n const run = await runWithRequestContext({ userEmail: owner }, () =>\n getAgentTeamBackgroundRun(runId),\n );\n if (!run) {\n setResponseStatus(event, 404);\n return { status: \"unavailable\", runId, events: [] };\n }\n const events = await runWithRequestContext(\n { userEmail: owner },\n () => listAgentTeamBackgroundTranscriptEvents(runId),\n );\n return { status: \"ok\", runId, events };\n }\n\n // Route: GET /runs/:id/events?after=N\n // Match both full URL (/runs/{id}/events) and h3 prefix-stripped (/{id}/events)\n const eventsMatch =\n url.match(/\\/runs\\/([^/?]+)\\/events/) ||\n url.match(/^\\/([^/?]+)\\/events/);\n if (eventsMatch && method === \"GET\") {\n const runId = decodeURIComponent(eventsMatch[1]);\n if (!(await ownsRun(runId))) {\n // 404 (not 403) so run existence isn't leaked to non-owners.\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n const query = getQuery(event);\n const after = parseInt(String(query.after ?? \"0\"), 10) || 0;\n\n const stream = subscribeToRun(runId, after);\n if (!stream) {\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n return stream;\n }\n\n // Route: GET /runs/active?threadId=X\n if (method === \"GET\") {\n const query = getQuery(event);\n const threadId = query.threadId ? String(query.threadId) : null;\n if (!threadId) {\n setResponseStatus(event, 400);\n return { error: \"threadId query parameter is required\" };\n }\n\n // Only reveal a thread's active run to the thread's owner.\n // Present non-owners (or unknown threads) as idle rather than\n // 404 so thread existence isn't leaked and the client polls\n // benignly.\n if (!(await ownsThread(threadId))) {\n return {\n active: false,\n threadId,\n status: \"idle\",\n heartbeatAt: null,\n lastProgressAt: null,\n };\n }\n\n // Check in-memory first, then SQL (cross-isolate on Workers)\n const run = await getActiveRunForThreadAsync(threadId);\n if (!run) {\n return {\n active: false,\n threadId,\n status: \"idle\",\n heartbeatAt: null,\n lastProgressAt: null,\n };\n }\n\n return {\n active: true,\n runId: run.runId,\n threadId: run.threadId,\n turnId: run.turnId,\n status: run.status,\n heartbeatAt: run.heartbeatAt,\n lastProgressAt: run.lastProgressAt,\n // Server clock so the client computes \"stuck\" elapsed time\n // server-relative, immune to client clock skew.\n serverNow: Date.now(),\n };\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // ─── Checkpoint endpoints ──────────────────────────────────────────────\n getH3App(nitroApp).use(\n `${routePath}/checkpoints`,\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n\n // GET /checkpoints?threadId=... — list checkpoints for a thread\n if (method === \"GET\") {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available in dev mode\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available on localhost\" };\n }\n const query = getQuery(event);\n const threadId = String(query.threadId || \"\");\n if (!threadId) {\n setResponseStatus(event, 400);\n return { error: \"threadId query parameter is required\" };\n }\n const owner = await getOwnerFromEvent(event);\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n try {\n const { getCheckpointsByThread } =\n await import(\"../checkpoints/store.js\");\n return await getCheckpointsByThread(threadId);\n } catch {\n return [];\n }\n }\n\n // POST /checkpoints — restore to a checkpoint\n // h3 prefix-matches, so /checkpoints/restore hits this handler with\n // event.path containing \"/restore\".\n const remainder = (event.path || \"\").replace(/^\\/+/, \"\");\n if (method === \"POST\" && remainder.startsWith(\"restore\")) {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available in dev mode\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Restore only available on localhost\" };\n }\n const body = await readBody(event);\n const checkpointId = body?.checkpointId;\n if (!checkpointId) {\n setResponseStatus(event, 400);\n return { error: \"checkpointId is required\" };\n }\n try {\n const { getCheckpointById } =\n await import(\"../checkpoints/store.js\");\n const checkpoint = await getCheckpointById(checkpointId);\n if (!checkpoint) {\n setResponseStatus(event, 404);\n return { error: \"Checkpoint not found\" };\n }\n const owner = await getOwnerFromEvent(event);\n const thread = await getThread(checkpoint.threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Checkpoint not found\" };\n }\n const {\n createCheckpoint: gitCheckpoint,\n restoreToCheckpoint,\n hasUncommittedChanges,\n isGitRepo,\n } = await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n if (!isGitRepo(cwd)) {\n setResponseStatus(event, 400);\n return { error: \"Not a git repository\" };\n }\n // Save current state before restoring so user can undo the undo\n if (hasUncommittedChanges(cwd)) {\n gitCheckpoint(cwd, \"[agent-native] Pre-restore checkpoint\");\n }\n const restored = restoreToCheckpoint(cwd, checkpoint.commitSha);\n if (!restored) {\n setResponseStatus(event, 500);\n return { error: \"Failed to restore checkpoint\" };\n }\n // Trigger UI refresh\n try {\n const { recordChange } = await import(\"./poll.js\");\n recordChange({\n source: \"checkpoint\",\n type: \"change\",\n key: \"*\",\n });\n } catch {}\n return { success: true, commitSha: checkpoint.commitSha };\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err?.message ?? \"Restore failed\" };\n }\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // ─── Thread management endpoints ──────────────────────────────────────\n // Single handler for /threads and /threads/:id — h3's use() does prefix\n // matching so we can't reliably split them into separate handlers.\n const parseScopeFromQuery = (\n q: Record<string, unknown>,\n ): ChatThreadScope | null => {\n const type = q.scopeType ? String(q.scopeType).trim() : \"\";\n const id = q.scopeId ? String(q.scopeId).trim() : \"\";\n if (!type || !id) return null;\n const label = q.scopeLabel ? String(q.scopeLabel) : undefined;\n return label ? { type, id, label } : { type, id };\n };\n const parseScopeFromBody = (raw: unknown): ChatThreadScope | null => {\n if (raw == null) return null;\n if (typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const type = typeof r.type === \"string\" ? r.type.trim() : \"\";\n const id = typeof r.id === \"string\" ? r.id.trim() : \"\";\n if (!type || !id) return null;\n const label = typeof r.label === \"string\" ? r.label : undefined;\n return label ? { type, id, label } : { type, id };\n };\n const parseForkSourceFromBody = (\n raw: unknown,\n ): ForkThreadSourceSnapshot | null => {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n if (typeof r.threadData !== \"string\") return null;\n const messageCount =\n typeof r.messageCount === \"number\"\n ? r.messageCount\n : Number(r.messageCount ?? 0);\n return {\n threadData: r.threadData,\n title: typeof r.title === \"string\" ? r.title : \"\",\n preview: typeof r.preview === \"string\" ? r.preview : \"\",\n messageCount,\n ...(Object.prototype.hasOwnProperty.call(r, \"scope\")\n ? { scope: parseScopeFromBody(r.scope) }\n : {}),\n };\n };\n const parseThreadRoute = (event: H3Event) => {\n const candidates = [event.path, event.node?.req?.url].filter(\n (value): value is string =>\n typeof value === \"string\" && value.length > 0,\n );\n for (const candidate of candidates) {\n const path = candidate.split(\"?\")[0];\n const parts = path.replace(/^\\/+/, \"\").split(\"/\").filter(Boolean);\n const threadsIndex = parts.lastIndexOf(\"threads\");\n if (threadsIndex >= 0) {\n const encodedId = parts[threadsIndex + 1];\n if (!encodedId) continue;\n return {\n threadId: decodeURIComponent(encodedId),\n tail: parts.slice(threadsIndex + 2),\n };\n }\n if (parts.length > 0) {\n return {\n threadId: decodeURIComponent(parts[0]),\n tail: parts.slice(1),\n };\n }\n }\n return { threadId: null, tail: [] as string[] };\n };\n getH3App(nitroApp).use(\n `${routePath}/threads`,\n defineEventHandler(async (event) => {\n const owner = await getOwnerFromEvent(event);\n const method = getMethod(event);\n\n const { threadId, tail: threadTail } = parseThreadRoute(event);\n const isThreadSubroute = (subroute: string) =>\n threadTail[0] === subroute;\n\n // ── Specific thread: GET/PUT/DELETE /threads/:id ──\n if (threadId) {\n if (method === \"GET\") {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return thread;\n }\n\n if (method === \"PUT\") {\n // Hold the thread_data lock for the full read-modify-write so\n // periodic saves from the frontend don't race with\n // onRunComplete / setThreadQueuedMessages / setThreadEngineMeta.\n // Without the lock, a client save that lands during an agent\n // run could clobber the assistant message the server just\n // appended (and vice versa).\n return await withThreadDataLock(threadId, async () => {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event);\n let newThreadData = body.threadData || thread.threadData;\n let newMessageCount = body.messageCount ?? thread.messageCount;\n let nextTitle =\n typeof body.title === \"string\" ? body.title : thread.title;\n const nextPreview =\n typeof body.preview === \"string\"\n ? body.preview\n : thread.preview;\n const preserveTitleOverride = (repo: unknown) => {\n if (\n repo &&\n typeof repo === \"object\" &&\n typeof (repo as { _titleOverride?: unknown })\n ._titleOverride === \"string\" &&\n (repo as { _titleOverride: string })._titleOverride.trim()\n ) {\n const meta = extractThreadMeta(repo);\n if (meta.title) nextTitle = meta.title;\n }\n };\n // Merge the incoming full-thread blob over the current SQL\n // copy. Periodic saves can be stale relative to server-side\n // run completion, and threadRuntime.export() does not carry\n // queuedMessages.\n if (body.threadData) {\n try {\n const existing = JSON.parse(thread.threadData);\n const incoming = JSON.parse(newThreadData);\n const merged = mergeThreadDataForClientSave(\n existing,\n incoming,\n );\n newThreadData = JSON.stringify(merged);\n if (Array.isArray(merged.messages)) {\n newMessageCount = merged.messages.length;\n }\n preserveTitleOverride(merged);\n } catch {\n // Invalid JSON in either side — fall back to raw body blob.\n }\n } else {\n try {\n preserveTitleOverride(JSON.parse(newThreadData));\n } catch {\n // Invalid JSON — keep the title supplied by the client.\n }\n }\n await updateThreadData(\n threadId,\n newThreadData,\n nextTitle,\n nextPreview,\n newMessageCount,\n );\n // Scope updates piggyback on the PUT — the client uses this\n // path for both \"detach\" (scope: null) and \"retag\" flows.\n // Send the field as `scope: undefined` (or omit it) when\n // you don't want to touch the existing scope.\n if (Object.prototype.hasOwnProperty.call(body, \"scope\")) {\n const incomingScope = parseScopeFromBody(body.scope);\n await setThreadScope(threadId, incomingScope);\n }\n return { ok: true };\n });\n }\n\n // POST /threads/:id/queued — debounced writes from the client\n // when the user adds/removes/dequeues a queued message. Keeps\n // queued messages durable across reloads without piggybacking\n // on full-thread saves.\n if (method === \"POST\" && isThreadSubroute(\"queued\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event);\n const queued = Array.isArray(body?.queuedMessages)\n ? body.queuedMessages\n : [];\n await setThreadQueuedMessages(threadId, queued);\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"rename\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n const title =\n typeof body?.title === \"string\"\n ? body.title.replace(/\\s+/g, \" \").trim().slice(0, 160)\n : \"\";\n if (!title) {\n setResponseStatus(event, 400);\n return { error: \"Title is required\" };\n }\n const renamed = await renameThread(threadId, title, {\n ownerEmail: owner,\n });\n if (!renamed) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"pin\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body?.pinned !== \"boolean\") {\n setResponseStatus(event, 400);\n return { error: \"pinned boolean is required\" };\n }\n const pinned = await setThreadPinned(threadId, body.pinned, {\n ownerEmail: owner,\n });\n if (!pinned) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"archive\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body?.archived !== \"boolean\") {\n setResponseStatus(event, 400);\n return { error: \"archived boolean is required\" };\n }\n const archived = await setThreadArchived(\n threadId,\n body.archived,\n { ownerEmail: owner },\n );\n if (!archived) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n // POST /threads/:id/fork — duplicate a thread with all its messages\n if (method === \"POST\" && isThreadSubroute(\"fork\")) {\n const body = await readBody(event);\n const forked = await forkThread(threadId, owner, {\n id: body?.id,\n source: parseForkSourceFromBody(body?.source),\n });\n if (!forked) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return forked;\n }\n\n if (method === \"DELETE\") {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n await deleteThread(threadId);\n return { ok: true };\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // ── Thread list: GET/POST /threads ──\n if (method === \"GET\") {\n const query = getQuery(event);\n const limit = Math.min(\n parseInt(String(query.limit ?? \"50\"), 10) || 50,\n 200,\n );\n const q = query.q ? String(query.q).trim() : \"\";\n const scope = parseScopeFromQuery(query);\n const unscopedOnly = String(query.unscoped ?? \"\") === \"1\";\n if (q) {\n const threads = await searchThreads(owner, q, limit, {\n scope: scope ?? undefined,\n });\n return { threads };\n }\n const offset = parseInt(String(query.offset ?? \"0\"), 10) || 0;\n const threads = await listThreads(owner, {\n limit,\n offset,\n scope: scope ?? undefined,\n unscopedOnly,\n });\n return { threads };\n }\n\n if (method === \"POST\") {\n const body = await readBody(event);\n // Idempotent: when the caller supplies an id and a thread with\n // that id already exists for this owner, return it instead of\n // 500'ing on the UNIQUE constraint. The client can race with\n // the agent run's `persistSubmittedUserMessage` (which also\n // creates the thread on first message); we don't want either\n // racer's POST/onRunPrepared retry to wipe the thread out of\n // the user's history.\n if (body?.id) {\n const existing = await getThread(body.id);\n if (existing) {\n if (existing.ownerEmail === owner) return existing;\n setResponseStatus(event, 409);\n return { error: \"Thread id already in use\" };\n }\n }\n try {\n const thread = await createThread(owner, {\n id: body?.id,\n title: body?.title ?? \"\",\n scope: parseScopeFromBody(body?.scope),\n });\n return thread;\n } catch (err) {\n // Lost the create race against another in-flight POST or\n // against `persistSubmittedUserMessage`. Re-fetch and\n // return the row that actually landed.\n if (body?.id) {\n const existing = await getThread(body.id);\n if (existing && existing.ownerEmail === owner) return existing;\n }\n throw err;\n }\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // Mount the main chat handler — delegates to dev or prod handler based on current mode.\n // This is mounted last because h3's use() is prefix-based, meaning /_agent-native/agent-chat\n // also matches /_agent-native/agent-chat/threads/... — we skip sub-path requests here so the\n // earlier-mounted handlers (mode, save-key, files, skills, mentions, threads) handle them.\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler(async (event) => {\n // Skip sub-path requests — they're handled by earlier-mounted handlers\n const url = event.node?.req?.url || event.path || \"\";\n const afterBase = url.slice(\n url.indexOf(routePath) + routePath.length,\n );\n if (afterBase && afterBase !== \"/\" && !afterBase.startsWith(\"?\")) {\n // Not for us — return 404 so h3 doesn't swallow the request\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }\n\n // Resolve per-request auth context\n const ownerContext = await resolveOwnerContext(event);\n const owner = ownerContext.owner;\n\n // Resolve org ID: explicit callback > session.orgId from Better Auth\n // > implicit org membership. Better Auth leaves session.orgId null\n // until the user explicitly switches orgs, so a fresh signup with\n // implicit membership (e.g. domain-matched org) would otherwise see\n // no org-scoped credentials. getOrgContext() does the same DB lookup\n // the /builder/status endpoint uses to decide \"Connected\".\n let resolvedOrgId: string | undefined;\n if (options?.resolveOrgId) {\n resolvedOrgId = (await options.resolveOrgId(event)) ?? undefined;\n } else {\n try {\n const session = await getSession(event);\n resolvedOrgId = session?.orgId ?? undefined;\n } catch {\n // Session not available\n }\n if (!resolvedOrgId) {\n try {\n const { getOrgContext } = await import(\"../org/context.js\");\n const ctx = await getOrgContext(event);\n resolvedOrgId = ctx.orgId ?? undefined;\n } catch {\n // org_members table may not exist yet on first boot\n }\n }\n }\n\n // Propagate the caller's IANA timezone from `x-user-timezone` so that\n // tool calls made by the agent (e.g. log-meal with no explicit date)\n // resolve \"today\" in the user's local timezone instead of server UTC.\n const tzRaw = getHeader(event, \"x-user-timezone\");\n const timezone =\n typeof tzRaw === \"string\" &&\n tzRaw.trim().length > 0 &&\n tzRaw.trim().length < 64\n ? tzRaw.trim()\n : undefined;\n\n return runWithRequestContext(\n {\n userEmail: owner,\n userName: ownerContext.name,\n orgId: resolvedOrgId,\n timezone,\n },\n () => {\n // App-rendered chat can't host direct code edits — HMR/full\n // reloads would kill the same chat surface mid-run. Force the\n // prod handler (no shell / no fs); the prompt block injected by\n // `prodHandler.systemPrompt` then steers source changes to a\n // separate agent surface such as Builder or the dev frame.\n const blockInProductCodeEditing =\n shouldBlockInProductCodeEditing(event);\n const handler =\n ownerContext.anonymous && anonymousHandler\n ? anonymousHandler\n : !blockInProductCodeEditing && currentDevMode && devHandler\n ? devHandler\n : prodHandler;\n return handler(event);\n },\n );\n }),\n );\n\n // ─── Recurring Jobs Scheduler ──────────────────────────────────────\n // Poll every 60 seconds for due recurring jobs and execute them.\n // Uses setInterval so it works in all deployment environments without\n // requiring Nitro experimental tasks configuration.\n try {\n const { processRecurringJobs } = await import(\"../jobs/scheduler.js\");\n\n const schedulerDeps = {\n getActions: () => ({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...toolActions,\n }),\n getSystemPrompt: async (owner: string) => {\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return basePrompt + resources + schemaBlock;\n },\n apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,\n model: options?.model,\n appId: options?.appId,\n };\n\n // Start after a 10-second delay to let the server fully initialize\n setTimeout(() => {\n setInterval(() => {\n processRecurringJobs(schedulerDeps).catch((err) => {\n console.error(\"[recurring-jobs] Scheduler error:\", err?.message);\n });\n }, 60_000);\n if (process.env.DEBUG)\n console.log(\"[recurring-jobs] Scheduler started (60s interval)\");\n }, 10_000);\n } catch (err) {\n // Jobs module not available — skip silently\n }\n\n // ─── Agent Teams orphan sweep ─────────────────────────────────────\n // Re-fires stuck/queued dispatches when the browser is closed and the\n // RunsTray's per-user reconciliation never triggers. Runs every 2 minutes\n // per instance; cheap (one indexed query when no active tasks are found).\n // Throttled by the same per-owner interval guard inside reconcileAgentTeamRunsForOwner.\n (() => {\n // Track when this instance last ran the sweep so only one sweep fires\n // per 2-min window even if multiple timers fire in overlapping invocations.\n let lastSweep = 0;\n const SWEEP_INTERVAL_MS = 2 * 60 * 1000;\n\n setTimeout(() => {\n setInterval(() => {\n const now = Date.now();\n if (now - lastSweep < SWEEP_INTERVAL_MS) return;\n lastSweep = now;\n\n (async () => {\n // Query distinct owners that have active queue rows.\n // Can't use reconcileAgentTeamRunsForOwner directly without\n // knowing the owner set — query the run queue table first.\n const { getDbExec } = await import(\"../db/client.js\");\n const db = getDbExec();\n let rows: any[];\n try {\n const result = await db.execute(\n `SELECT DISTINCT owner_email FROM agent_team_run_queue WHERE status IN ('queued', 'running') AND owner_email IS NOT NULL LIMIT 50`,\n );\n rows = result.rows as any[];\n } catch {\n return; // Table may not exist yet on first boot\n }\n const { reconcileAgentTeamRunsForOwner } =\n await import(\"./agent-teams.js\");\n for (const row of rows) {\n const owner = String((row as any).owner_email ?? \"\").trim();\n if (!owner) continue;\n try {\n await reconcileAgentTeamRunsForOwner(owner);\n } catch {\n // best-effort per owner\n }\n }\n })().catch(() => {\n // best-effort — never break the server\n });\n }, 30_000); // Check every 30s but only sweep once per 2min\n }, 15_000); // Start 15s after init (after the scheduler)\n })();\n\n // ─── Trigger Dispatcher (event-based automations) ─────────────────\n try {\n const { initTriggerDispatcher } =\n await import(\"../triggers/dispatcher.js\");\n await initTriggerDispatcher({\n getActions: () => ({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...toolActions,\n }),\n getSystemPrompt: async (owner: string) => {\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return basePrompt + resources + schemaBlock;\n },\n apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,\n model: options?.model,\n appId: options?.appId,\n });\n if (process.env.DEBUG)\n console.log(\"[triggers] Trigger dispatcher initialized\");\n } catch (err) {\n // Triggers module not available — skip silently\n }\n })().catch((err) => {\n // If the init fails, the routes never get registered and requests\n // to /_agent-native/agent-chat silently 404. Register a fallback\n // route so the user sees a meaningful error instead.\n const routePath = options?.path ?? \"/_agent-native/agent-chat\";\n const msg = (err as Error)?.message || String(err);\n console.error(\n `[agent-chat] Plugin init failed — registering error fallback: ${msg}`,\n );\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler((event) => {\n setResponseStatus(event, 503);\n return {\n error: `Agent chat failed to initialize: ${msg}`,\n };\n }),\n );\n });\n trackPluginInit(nitroApp, initPromise, {\n paths: [\n options?.path ?? \"/_agent-native/agent-chat\",\n \"/_agent-native/actions\",\n \"/_agent-native/agent-model-defaults\",\n \"/_agent-native/mcp\",\n ],\n });\n };\n}\n\n/**\n * Default agent chat plugin with no template-specific actions.\n * In dev mode, provides file system, bash, and database tools.\n * In production, provides only the default system prompt.\n */\nexport const defaultAgentChatPlugin: NitroPluginDef = createAgentChatPlugin();\n\n// ---------------------------------------------------------------------------\n// MCP client glue — a shared manager reference + a /_agent-native/mcp/status\n// route so onboarding / settings UIs can see which MCP servers are live.\n// ---------------------------------------------------------------------------\n\nlet _globalMcpManager: McpClientManager | null = null;\n\nfunction setGlobalMcpManager(manager: McpClientManager): void {\n _globalMcpManager = manager;\n}\n\n/** Internal: access the current process's MCP client manager, if any. */\nexport function getGlobalMcpManager(): McpClientManager | null {\n return _globalMcpManager;\n}\n\nfunction mountMcpHubStatusRoute(nitroApp: any): void {\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpHubStatusMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n try {\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/hub/status\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n setResponseHeader(event, \"Content-Type\", \"application/json\");\n return getHubStatus();\n }),\n );\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to mount /_agent-native/mcp/hub/status: ${err?.message ?? err}`,\n );\n }\n}\n\nfunction mountMcpStatusRoute(nitroApp: any, manager: McpClientManager): void {\n // Idempotent per Nitro app; dev-all may host multiple templates in one process.\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpStatusMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n try {\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/status\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n setResponseHeader(event, \"Content-Type\", \"application/json\");\n return manager.getStatus();\n }),\n );\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to mount /_agent-native/mcp/status: ${err?.message ?? err}`,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-chat-plugin.js","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EACL,QAAQ,EACR,yBAAyB,EACzB,eAAe,GAChB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,4BAA4B,EAC5B,oBAAoB,EACpB,0BAA0B,EAC1B,QAAQ,EACR,cAAc,GAEf,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,kCAAkC,CAAC;AAErF,OAAO,EACL,aAAa,EACb,qBAAqB,EACrB,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,8BAA8B,EAC9B,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,qCAAqC,EACrC,kCAAkC,EAClC,gCAAgC,EAChC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAQpE,OAAO,EAAE,g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,iBAAiB,CAAC,KAAK,EAAE,cAAc,EAAE,kBAAkB,CAAC,CAAC;YAC7D,OAAO,OAAO,CAAC,SAAS,EAAE,CAAC;QAC7B,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,CAAC,IAAI,CACV,2DAA2D,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CACjF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n runWithRequestContext,\n getRequestOrgId,\n getRequestUserEmail,\n getRequestRunContext,\n ensureRequestRunContext,\n} from \"./request-context.js\";\nimport { getSetting, putSetting } from \"../settings/store.js\";\nimport { createDbAdminAgentTools } from \"../db-admin/agent-tools.js\";\nimport {\n getH3App,\n markDefaultPluginProvided,\n trackPluginInit,\n} from \"./framework-request-handler.js\";\nimport {\n createProductionAgentHandler,\n actionsToEngineTools,\n getActiveRunForThreadAsync,\n abortRun,\n subscribeToRun,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { runAgentLoopDirectWithSoftTimeout } from \"../agent/run-loop-with-resume.js\";\nimport type { AgentEngine, EngineMessage } from \"../agent/engine/types.js\";\nimport {\n resolveEngine,\n createAnthropicEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n getAgentEngineEntry,\n isAgentEnginePackageInstalled,\n isStoredEngineUsableForRequest,\n listAgentEngines,\n registerBuiltinEngines,\n} from \"../agent/engine/index.js\";\nimport {\n canUpdateAgentAppModelDefaultSettings,\n normalizeAgentAppModelDefaultAppId,\n readAgentAppModelDefaultSettings,\n resetAgentAppModelDefaultSettings,\n writeAgentAppModelDefaultSettings,\n} from \"../agent/app-model-defaults.js\";\nimport { DEFAULT_ANTHROPIC_MODEL } from \"../agent/default-model.js\";\nimport type {\n AgentChatAttachment,\n AgentChatEvent,\n AgentChatReference,\n ActionTool,\n MentionProvider,\n} from \"../agent/types.js\";\nimport { attachToolSearch } from \"../agent/tool-search.js\";\nimport type { ActionHttpConfig } from \"../action.js\";\nimport {\n McpClientManager,\n loadMcpConfig,\n autoDetectMcpConfig,\n mcpToolsToActionEntries,\n syncMcpActionEntries,\n mountMcpServersRoutes,\n mountMcpHubRoutes,\n buildMergedConfig,\n startMcpConfigRefresh,\n areBuiltinMcpCapabilitiesSupported,\n setBuiltinMcpCapabilityEnabled,\n getHubStatus,\n isHubServeEnabled,\n type BuiltinMcpCapabilityId,\n} from \"../mcp-client/index.js\";\nimport { discoverAgents } from \"./agent-discovery.js\";\nimport { loadSchemaPromptBlock } from \"./schema-prompt.js\";\nimport {\n buildAssistantMessage,\n buildUserMessage,\n extractThreadMeta,\n foldAssistantTurn,\n mergeThreadDataForClientSave,\n upsertUserMessage,\n} from \"../agent/thread-data-builder.js\";\nimport {\n createError,\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getQuery,\n getHeader,\n type H3Event,\n} from \"h3\";\nimport { getSession } from \"./auth.js\";\nimport { getOrigin } from \"./google-oauth.js\";\nimport {\n createThread,\n forkThread,\n getThread,\n listThreads,\n searchThreads,\n renameThread,\n setThreadArchived,\n setThreadPinned,\n setThreadScope,\n updateThreadData,\n withThreadDataLock,\n deleteThread,\n setThreadQueuedMessages,\n type ChatThreadScope,\n type ForkThreadSourceSnapshot,\n} from \"../chat-threads/store.js\";\nimport { callerOwnsRun, callerOwnsThread } from \"../agent/run-ownership.js\";\nimport {\n resourceList,\n resourceListAccessible,\n resourceGet,\n resourceGetByPath,\n ensurePersonalDefaults,\n SHARED_OWNER,\n WORKSPACE_OWNER,\n} from \"../resources/store.js\";\nimport {\n getFrontmatterValue,\n getSkillNameFromPath,\n parseFrontmatter,\n} from \"../resources/metadata.js\";\nimport nodePath from \"node:path\";\nimport { readBody } from \"./h3-helpers.js\";\nimport {\n AGENT_TEAM_PROCESS_RUN_PATH,\n processAgentTeamRun,\n reconcileAgentTeamRunsForOwner,\n} from \"./agent-teams.js\";\nimport { setProgressPreListHook } from \"../progress/store.js\";\nimport {\n verifyInternalToken,\n extractBearerToken,\n} from \"../integrations/internal-token.js\";\nimport {\n hasConfiguredA2ASecret,\n isA2AProductionRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n getBuilderBrowserConnectUrlForOwner,\n resolveBuilderBranchProjectId,\n} from \"./builder-browser.js\";\nimport { captureCliOutput } from \"./cli-capture.js\";\nimport { withConfiguredAppBasePath } from \"./app-base-path.js\";\nimport {\n appendA2AArtifactLinks,\n buildA2ARecoverableArtifactMessage,\n type A2AArtifactResponseOptions,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\nimport { updateTaskStatusMessage } from \"../a2a/task-store.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport { buildRuntimeContextPrompt } from \"../agent/runtime-context.js\";\nimport {\n buildFrameworkCore,\n buildFrameworkCoreCompact,\n FIRST_SESSION_PERSONALIZATION,\n getModelFamilyOverlay,\n type PromptExamples,\n} from \"./prompts/index.js\";\n\n// Lazy fs — loaded via dynamic import() on first use.\n// This avoids require() which bundlers convert to createRequire(import.meta.url)\n// that crashes on CF Workers where import.meta.url is undefined.\nlet _fs: typeof import(\"fs\") | undefined;\nasync function lazyFs(): Promise<typeof import(\"fs\")> {\n if (!_fs) {\n _fs = await import(\"node:fs\");\n }\n return _fs;\n}\n\nconst SHARED_PROMPT_RESOURCE_MAX_CHARS = 30_000;\nconst COMPACT_PROMPT_RESOURCE_MAX_CHARS = 12_000;\nconst MAX_ACTION_SUMMARY_DESCRIPTION_CHARS = 140;\n\nfunction compactPromptLine(value: string, maxChars: number): string {\n const line = value.replace(/\\s+/g, \" \").trim();\n if (line.length <= maxChars) return line;\n return `${line.slice(0, maxChars - 1)}…`;\n}\nconst SHARED_RESOURCE_INDEX_LIMIT = 40;\n\nfunction normalizeResourcePathForPrompt(path: string): string {\n return path.replace(/^\\/+/, \"\").trim();\n}\n\nfunction resourceToolHint(\n action: \"list\" | \"read\" | \"effective\" | \"write\" | \"delete\" | \"promote\",\n extra?: string,\n): string {\n return `Use the \\`resources\\` tool with \\`action: \"${action}\"\\`${extra ? `, ${extra}` : \"\"}.`;\n}\n\nfunction skillDocsSlug(name: string): string {\n return `skill-${name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")}`;\n}\n\nfunction ensureSentence(value: string): string {\n const trimmed = value.trim();\n if (!trimmed) return \"\";\n return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction escapeXmlAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n}\n\nfunction truncatePromptResourceContent(\n content: string,\n path: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n readHint?: string,\n): string {\n const trimmed = content.trim();\n if (trimmed.length <= maxChars) return trimmed;\n const omitted = trimmed.length - maxChars;\n const hint =\n readHint ??\n resourceToolHint(\n \"read\",\n `\\`path: \"${path}\"\\` and the resource's \\`scope\\` for the full content`,\n );\n return `${trimmed.slice(0, maxChars)}\\n\\n[Resource ${path} truncated after ${maxChars.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted. ${hint}]`;\n}\n\nfunction promptResourceBlock(input: {\n name: string;\n scope: string;\n content: string;\n path?: string;\n maxChars?: number;\n readHint?: string;\n}): string | null {\n const normalizedPath = input.path\n ? normalizeResourcePathForPrompt(input.path)\n : undefined;\n const content = truncatePromptResourceContent(\n input.content,\n normalizedPath ?? input.name,\n input.maxChars,\n input.readHint,\n );\n if (!content) return null;\n const pathAttr = normalizedPath\n ? ` path=\"${escapeXmlAttribute(normalizedPath)}\"`\n : \"\";\n return `<resource name=\"${escapeXmlAttribute(input.name)}\" scope=\"${escapeXmlAttribute(input.scope)}\"${pathAttr}>\\n${content}\\n</resource>`;\n}\n\nfunction isAutoLoadedInstructionPath(path: string): boolean {\n const normalized = normalizeResourcePathForPrompt(path);\n return normalized.startsWith(\"instructions/\") && normalized.endsWith(\".md\");\n}\n\nfunction isSpecialPromptResourcePath(path: string): boolean {\n const normalized = normalizeResourcePathForPrompt(path);\n return (\n normalized === \"AGENTS.md\" ||\n normalized === \"LEARNINGS.md\" ||\n normalized.startsWith(\"instructions/\") ||\n normalized.startsWith(\"skills/\") ||\n normalized.startsWith(\"agents/\") ||\n normalized.startsWith(\"remote-agents/\") ||\n normalized.startsWith(\"jobs/\") ||\n normalized.startsWith(\"memory/\")\n );\n}\n\nfunction isTextLikeResource(mimeType: string): boolean {\n return (\n mimeType.startsWith(\"text/\") ||\n mimeType === \"application/json\" ||\n mimeType === \"application/yaml\" ||\n mimeType === \"application/x-yaml\"\n );\n}\n\nfunction getResourceSummaryFromContent(content: string): string | null {\n const frontmatter = parseFrontmatter(content);\n const title =\n getFrontmatterValue(frontmatter, \"title\") ||\n getFrontmatterValue(frontmatter, \"name\");\n const description = getFrontmatterValue(frontmatter, \"description\");\n if (title && description) return `${title}: ${description}`;\n if (title) return title;\n if (description) return description;\n\n const heading = content\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .find((line) => /^#{1,3}\\s+\\S/.test(line));\n if (heading) return heading.replace(/^#{1,3}\\s+/, \"\").trim();\n return null;\n}\n\nfunction resourceScopeForOwner(owner: string, currentOwner?: string): string {\n if (owner === WORKSPACE_OWNER) return \"workspace\";\n if (owner === SHARED_OWNER) return \"shared\";\n if (currentOwner && owner === currentOwner) return \"personal\";\n return \"resource\";\n}\n\nasync function loadAgentsResourceForPrompt(\n owner: string,\n scope: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n): Promise<string | null> {\n try {\n const agents = await resourceGetByPath(owner, \"AGENTS.md\");\n if (!agents?.content?.trim()) return null;\n return promptResourceBlock({\n name: \"AGENTS.md\",\n scope,\n path: \"AGENTS.md\",\n content: agents.content,\n maxChars,\n });\n } catch {\n return null;\n }\n}\n\nasync function loadInstructionResourcesForPrompt(\n owner: string,\n scope: string,\n maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS,\n): Promise<string[]> {\n try {\n const resources = await resourceList(owner, \"instructions/\");\n const blocks: string[] = [];\n const sorted = resources\n .filter((resource) => isAutoLoadedInstructionPath(resource.path))\n .sort((a, b) => a.path.localeCompare(b.path));\n for (const resource of sorted) {\n const full = await resourceGet(resource.id).catch(() => null);\n if (!full?.content?.trim()) continue;\n const block = promptResourceBlock({\n name: resource.path,\n scope,\n path: resource.path,\n content: full.content,\n maxChars,\n });\n if (block) blocks.push(block);\n }\n return blocks;\n } catch {\n return [];\n }\n}\n\nasync function loadResourceSkillsPromptBlock(\n owner: string,\n): Promise<string | null> {\n try {\n const resources =\n owner === SHARED_OWNER\n ? [\n ...(await resourceList(SHARED_OWNER, \"skills/\")),\n ...(await resourceList(WORKSPACE_OWNER, \"skills/\")),\n ]\n : await resourceListAccessible(owner, \"skills/\");\n const sorted = resources.sort((a, b) => {\n const ownerOrder =\n (a.owner === owner\n ? 0\n : a.owner === SHARED_OWNER\n ? 1\n : a.owner === WORKSPACE_OWNER\n ? 2\n : 3) -\n (b.owner === owner\n ? 0\n : b.owner === SHARED_OWNER\n ? 1\n : b.owner === WORKSPACE_OWNER\n ? 2\n : 3);\n if (ownerOrder !== 0) return ownerOrder;\n return a.path.localeCompare(b.path);\n });\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const resource of sorted) {\n const full = await resourceGet(resource.id).catch(() => null);\n if (!full?.content) continue;\n const meta = parseSkillFrontmatter(full.content);\n if (meta.userInvocable === false) continue;\n const name = meta.name || getSkillNameFromPath(resource.path);\n if (!name || seen.has(name)) continue;\n seen.add(name);\n const scope = resourceScopeForOwner(resource.owner, owner);\n const description = meta.description || \"(no description)\";\n lines.push(\n `- \\`${name}\\` at resource \\`${resource.path}\\` (${scope}) - ${ensureSentence(description)} ${resourceToolHint(\n \"read\",\n `\\`path: \"${resource.path}\"\\` and \\`scope: \"${scope}\"\\` before starting a task it applies to`,\n )}`,\n );\n }\n if (lines.length === 0) return null;\n return `<resource-skills>\\nThe following workspace skills are available in addition to codebase skills. They may come from SQL resources, Dispatch workspace resources, or local file mode. Read a matching skill before starting a task it applies to.\\n\\n${lines.join(\"\\n\")}\\n</resource-skills>`;\n } catch {\n return null;\n }\n}\n\nasync function loadResourceIndexForPrompt(\n owner: string,\n scope: \"workspace\" | \"shared\",\n): Promise<string | null> {\n try {\n const resources = (await resourceList(owner))\n .filter(\n (resource) =>\n !isSpecialPromptResourcePath(resource.path) &&\n isTextLikeResource(resource.mimeType),\n )\n .sort((a, b) => a.path.localeCompare(b.path));\n if (resources.length === 0) return null;\n\n const listed = resources.slice(0, SHARED_RESOURCE_INDEX_LIMIT);\n const lines: string[] = [];\n for (const resource of listed) {\n const full = await resourceGet(resource.id).catch(() => null);\n const summary = full?.content\n ? getResourceSummaryFromContent(full.content)\n : null;\n lines.push(`- \\`${resource.path}\\`${summary ? ` - ${summary}` : \"\"}`);\n }\n if (resources.length > listed.length) {\n lines.push(\n `- ...${resources.length - listed.length} more ${scope} resources. ${resourceToolHint(\n \"list\",\n `\\`scope: \"${scope}\"\\` to inspect them`,\n )}`,\n );\n }\n\n const label =\n scope === \"workspace\"\n ? \"Workspace reference resources are inherited by every app and are available for company, brand, positioning, persona, product, or domain context.\"\n : \"Shared app/organization reference resources are available for app-specific or team context.\";\n return `<workspace-resources scope=\"${scope}\">\\n${label} ${resourceToolHint(\n \"read\",\n `\\`path: <path>\\` and \\`scope: \"${scope}\"\\` when a task may depend on them`,\n )} Do not assume their contents without reading the relevant file.\\n\\n${lines.join(\"\\n\")}\\n</workspace-resources>`;\n } catch {\n return null;\n }\n}\n\n/**\n * Wraps a core CLI script (that writes to console.log) as a ActionEntry\n * by capturing stdout. Uses an AsyncLocalStorage-backed capture so\n * concurrent tool calls do not corrupt the global console/stdout pointers\n * (see `cli-capture.ts`).\n */\nfunction wrapCliScript(\n tool: ActionTool,\n cliDefault: (args: string[]) => Promise<void>,\n opts?: { readOnly?: boolean },\n): ActionEntry {\n return {\n tool,\n ...(opts?.readOnly ? { readOnly: true as const } : {}),\n run: async (args: Record<string, string>): Promise<string> => {\n const cliArgs: string[] = [];\n for (const [k, v] of Object.entries(args)) {\n const raw = v as unknown;\n const value =\n raw != null && typeof raw === \"object\"\n ? JSON.stringify(raw)\n : String(raw);\n cliArgs.push(`--${k}`, value);\n }\n return captureCliOutput(() => cliDefault(cliArgs));\n },\n };\n}\n\nfunction filterReadOnlyActions(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => entry.readOnly === true),\n );\n}\n\n/** Drop actions that opted out of agent exposure via `agentTool: false`. They\n * remain callable from the frontend / HTTP (mounted separately from this\n * agent tool surface — see `httpActions`) but never appear in any agent tool\n * list (in-app assistant, MCP, A2A, job/trigger runners) or actions prompt.\n * Default-allow: only an explicit `false` is excluded. */\nfunction filterAgentTools(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => entry.agentTool !== false),\n );\n}\n\nfunction filterPublicAgentActions(\n actions: Record<string, ActionEntry>,\n): Record<string, ActionEntry> {\n return Object.fromEntries(\n Object.entries(actions).filter(([, entry]) => {\n const config = entry.publicAgent;\n return (\n config?.expose === true &&\n config.readOnly === true &&\n config.requiresAuth !== true &&\n config.isConsequential !== true\n );\n }),\n );\n}\n\nexport function buildPublicAgentA2ASkills(\n actions: Record<string, ActionEntry>,\n): Array<{\n id: string;\n name: string;\n description: string;\n publicAgent: ActionEntry[\"publicAgent\"];\n}> {\n return Object.entries(filterPublicAgentActions(actions)).map(\n ([name, entry]) => ({\n id: name,\n name,\n description: entry.tool.description,\n publicAgent: entry.publicAgent,\n }),\n );\n}\n\nfunction resolveArtifactBaseUrl(event: any | undefined): string | undefined {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(String(fromEnv));\n\n try {\n const proto = getHeader(event, \"x-forwarded-proto\") || \"https\";\n const host = getHeader(event, \"host\");\n if (host) return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {}\n\n return undefined;\n}\n\nexport function assembleA2AFinalResponse(\n events: readonly AgentChatEvent[],\n toolResults: readonly A2AToolResultSummary[],\n options: A2AArtifactResponseOptions & { event?: any } = {},\n): { responseText: string; finalText: string } {\n const responseText = collectFinalResponseTextFromAgentEvents(events);\n const finalText = appendA2AArtifactLinks(responseText, [...toolResults], {\n baseUrl: options.baseUrl ?? resolveArtifactBaseUrl(options.event),\n includeReferencedArtifacts: true,\n });\n return { responseText, finalText };\n}\n\n/**\n * Creates the `get-framework-context` tool. Returns detailed instructions\n * for framework capabilities that are summarized in the compact prompt.\n * The agent calls this on-demand when it needs specifics about embeds,\n * agent teams, recurring jobs, etc.\n */\nfunction createFrameworkContextEntry(): Record<string, ActionEntry> {\n const topicList = Object.keys(FRAMEWORK_CONTEXT_SECTIONS).join(\", \");\n return {\n \"get-framework-context\": {\n tool: {\n description: `Read detailed framework instructions for a specific capability. Available topics: ${topicList}. Call with topic=\"all\" to get everything.`,\n parameters: {\n type: \"object\" as const,\n properties: {\n topic: {\n type: \"string\",\n description: `Topic to read. One of: ${topicList}, or \"all\" for everything.`,\n },\n },\n required: [\"topic\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const topic = String(args.topic ?? \"all\").toLowerCase();\n if (topic === \"all\") {\n return Object.values(FRAMEWORK_CONTEXT_SECTIONS).join(\"\\n\\n\");\n }\n const section = FRAMEWORK_CONTEXT_SECTIONS[topic];\n if (!section) {\n return `Unknown topic \"${topic}\". Available: ${topicList}`;\n }\n return section;\n },\n readOnly: true,\n },\n };\n}\n\n/**\n * Creates the `refresh-screen` tool. Writes a bump to `application_state`\n * under a well-known key; the client's `useDbSync` watches for this and\n * invalidates react-query caches so the on-screen UI re-fetches its data\n * without a full page reload.\n *\n * This is the standard way for the agent to say \"the data on the screen\n * just changed, please refresh it\" — e.g. after editing a dashboard config,\n * updating a form schema, or mutating a row that the current view renders.\n */\nfunction createRefreshScreenEntry(): Record<string, ActionEntry> {\n return {\n \"refresh-screen\": {\n // Writes __screen_refresh__ to application_state, which emits its own\n // distinct `screen-refresh` poll event. Don't double-emit a generic\n // `action` event on top of that.\n readOnly: true,\n tool: {\n description:\n \"Manually refresh the user's current screen. The framework ALREADY auto-refreshes after any successful mutating action tool call (template actions, db-exec, db-patch) — you do NOT need to call this after a normal action. Use it only when (a) you mutated data via a path the framework can't detect (e.g. a direct write to an external system the app mirrors), or (b) you want to pass a `scope` hint so the UI narrows which queries to refetch. The UI re-fetches its queries without a full page reload.\",\n parameters: {\n type: \"object\",\n properties: {\n scope: {\n type: \"string\",\n description:\n \"Optional hint describing what changed (e.g. 'dashboard', 'form', 'settings'). Templates may use it to narrow which queries to invalidate; if omitted, all queries are invalidated.\",\n },\n },\n },\n },\n run: async (args) => {\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n const nonce = Date.now();\n const scope = typeof args?.scope === \"string\" ? args.scope : undefined;\n await writeAppState(SCREEN_REFRESH_KEY, {\n nonce,\n ...(scope ? { scope } : {}),\n });\n return `refreshed${scope ? ` (scope: ${scope})` : \"\"}`;\n },\n },\n };\n}\n\n/** Well-known application-state key used by the refresh-screen tool. */\nconst SCREEN_REFRESH_KEY = \"__screen_refresh__\";\nconst SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;\n\nfunction appStateKeyForBrowserTab(key: string, browserTabId: unknown): string {\n if (typeof browserTabId !== \"string\") return key;\n const trimmed = browserTabId.trim();\n return SAFE_BROWSER_TAB_ID_RE.test(trimmed) ? `${key}:${trimmed}` : key;\n}\n\n/**\n * In-memory rate-limit tracker for `/generate-title`. Keyed by user email,\n * value is recent invocation timestamps within the rolling window. Stale\n * entries are pruned on read.\n */\nconst generateTitleRateLimit = new Map<string, number[]>();\n\n/**\n * Creates the `set-search-params` / `set-url-path` tools. Writes a one-shot\n * URL command to application_state; the client's URLSync component applies\n * it via react-router (no full page reload) and then deletes the command.\n *\n * This is how the agent edits URL state — filter query params, route\n * changes, hash — without needing a per-template navigate action. The\n * current URL is visible to the agent via the auto-injected `<current-url>`\n * block, which includes parsed search params.\n */\nfunction createUrlTools(): Record<string, ActionEntry> {\n return {\n \"set-search-params\": {\n // Writes __set_url__ to application_state, which the app-state watcher\n // already surfaces as a poll event. No need to double-emit.\n readOnly: true,\n tool: {\n description:\n \"Update the URL query string on the user's current page. Use this to change dashboard/list filters, search terms, or any other state the app stores in `?foo=bar` style query params. One-shot — the UI applies it in ~1s without a page reload. See the current URL + parsed search params in the auto-injected `<current-url>` block. Keys are the exact query param names as they appear in the URL (e.g. `f_pubDateStart`, not just `pubDateStart`). Set a value to null or empty string to clear that param. By default merges over existing params — pass `merge: false` to replace them all.\",\n parameters: {\n type: \"object\",\n properties: {\n params: {\n type: \"object\",\n description:\n 'Map of query param → value. Each value is a string, or null/\"\" to clear. Example: {\"f_pubDateStart\": null, \"f_cadence\": \"MONTH\"}.',\n },\n merge: {\n type: \"string\",\n description:\n '\"true\" (default) merges over existing params; \"false\" replaces them entirely.',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"params\"],\n },\n },\n run: async (args) => {\n const params = (args?.params ?? {}) as unknown as Record<\n string,\n string | null\n >;\n const merge = (args as any)?.merge !== \"false\";\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"__set_url__\",\n getRequestRunContext()?.browserTabId,\n ),\n {\n searchParams: params,\n mergeSearchParams: merge,\n // Unique-per-write token. The client's URLSync hook dedups by this\n // so a fire-and-forget DELETE that loses its race against the next\n // polling refetch can't cause the same URL command to be applied\n // repeatedly (which caused the editor to bounce between slides\n // when an agent turn errored partway through).\n _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n },\n );\n const keys = Object.keys(params);\n return `set-search-params: ${keys.length} key${keys.length === 1 ? \"\" : \"s\"}${merge ? \"\" : \" (replace)\"}`;\n },\n },\n \"set-url-path\": {\n // Same as set-search-params — writes application_state, already emits\n // via the app-state watcher.\n readOnly: true,\n tool: {\n description:\n \"Navigate the user to a different pathname, optionally also setting search params. For most template-specific routing prefer the template's `navigate` action if it exists — this is the generic fallback. One-shot, applied by the client without a page reload.\",\n parameters: {\n type: \"object\",\n properties: {\n pathname: {\n type: \"string\",\n description: \"New URL pathname (e.g. '/adhoc/weekly').\",\n },\n params: {\n type: \"object\",\n description:\n 'Optional query params to set alongside the path change. String values set, null/\"\" clears.',\n },\n merge: {\n type: \"string\",\n description:\n '\"true\" (default) merges over existing params; \"false\" starts fresh.',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"pathname\"],\n },\n },\n run: async (args) => {\n const pathname = String(args?.pathname ?? \"\");\n if (!pathname.startsWith(\"/\")) {\n return \"Error: pathname must start with '/'.\";\n }\n const params = (args?.params ?? {}) as unknown as Record<\n string,\n string | null\n >;\n const merge = (args as any)?.merge !== \"false\";\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"__set_url__\",\n getRequestRunContext()?.browserTabId,\n ),\n {\n pathname,\n searchParams: params,\n mergeSearchParams: merge,\n // See note in set-search-params: unique-per-write dedup token so a\n // race between GET and consume-DELETE in URLSync can't re-apply\n // this command.\n _writeId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n },\n );\n return `set-url-path: ${pathname}`;\n },\n },\n \"ask-question\": {\n tool: {\n description:\n \"Ask the user a multiple-choice clarifying question and render it inline in the chat. Use this ONLY when you are genuinely blocked on a decision you cannot resolve from context and a wrong guess would be costly — an ambiguous metric, date range, or grain; a real fork in approach. Present 2-5 concrete options and mark the most likely one recommended. Do NOT use it for confirmations, for things the user already specified, or to dodge easy work you could just do. Ask at most once per turn. Calling this yields the turn: stop and wait for the user's answer.\",\n parameters: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description:\n \"The complete question to ask the user. Clear, specific, ends with a question mark.\",\n },\n header: {\n type: \"string\",\n description:\n 'Optional very short label (max ~12 chars) shown as a chip/heading above the question, e.g. \"Date range\", \"Approach\", \"Library\".',\n },\n options: {\n type: \"string\",\n description:\n 'A JSON array of 2-4 distinct, mutually-exclusive options (unless `allowMultiple` is true), each `{ \"label\": string, \"value\"?: string, \"description\"?: string, \"preview\"?: string, \"recommended\"?: boolean }`. `label` is 1-5 words; `description` explains the trade-off; `preview` is optional content (mockup, code snippet, short comparison) rendered under the option. `value` defaults to `label` when omitted. Mark the most likely option `\"recommended\": true`. Do NOT add an \"Other\" option — free text is provided automatically when `allowFreeText` is on.',\n },\n allowFreeText: {\n type: \"string\",\n description:\n 'Whether the user may also type a free-text \"Other\" answer. \"true\" (default) or \"false\".',\n enum: [\"true\", \"false\"],\n },\n allowMultiple: {\n type: \"string\",\n description:\n 'Whether the user may select more than one option (multi-select). \"true\" or \"false\" (default).',\n enum: [\"true\", \"false\"],\n },\n },\n required: [\"question\", \"options\"],\n },\n },\n run: async (args) => {\n const question = String(args?.question ?? \"\").trim();\n if (!question) return \"Error: 'question' is required.\";\n const header = String(args?.header ?? \"\").trim();\n const allowMultiple = String(args?.allowMultiple ?? \"\") === \"true\";\n const allowFreeText = String(args?.allowFreeText ?? \"true\") !== \"false\";\n\n let parsedOptions: unknown;\n try {\n parsedOptions = JSON.parse(String(args?.options ?? \"[]\"));\n } catch {\n return \"Error: 'options' must be a JSON array of { label, value?, description?, recommended? }.\";\n }\n if (!Array.isArray(parsedOptions) || parsedOptions.length === 0) {\n return \"Error: 'options' must be a non-empty JSON array of { label, value?, description?, recommended? }.\";\n }\n\n type AskOption = {\n label: string;\n value: string;\n description?: string;\n preview?: string;\n recommended?: boolean;\n };\n const options = parsedOptions\n .map((raw): AskOption | null => {\n const opt = (raw ?? {}) as Record<string, unknown>;\n const label =\n typeof opt.label === \"string\" && opt.label.trim()\n ? opt.label.trim()\n : typeof opt.value === \"string\"\n ? String(opt.value).trim()\n : \"\";\n if (!label) return null;\n const value =\n typeof opt.value === \"string\" && opt.value.trim()\n ? opt.value.trim()\n : label;\n const option: AskOption = { label, value };\n if (typeof opt.description === \"string\" && opt.description.trim()) {\n option.description = opt.description.trim();\n }\n if (typeof opt.preview === \"string\" && opt.preview.trim()) {\n option.preview = opt.preview;\n }\n if (opt.recommended === true) option.recommended = true;\n return option;\n })\n .filter((opt): opt is AskOption => opt !== null);\n if (options.length === 0) {\n return \"Error: 'options' must contain at least one option with a label.\";\n }\n\n // Shape must match the GuidedQuestionFlow renderer in\n // client/guided-questions.tsx: a `text-options` question whose options\n // carry `value`, with `multiSelect` for multi-pick and `allowOther` for\n // free text. The renderer otherwise injects \"Explore\"/\"Decide\" options,\n // which would be noise for a focused clarifying question, so disable them.\n const payload = {\n questions: [\n {\n id: \"q1\",\n type: \"text-options\" as const,\n question,\n ...(header ? { header } : {}),\n required: !allowFreeText,\n multiSelect: allowMultiple,\n allowOther: allowFreeText,\n includeExplore: false,\n includeDecide: false,\n options,\n },\n ],\n };\n\n const { writeAppState } =\n await import(\"../application-state/script-helpers.js\");\n await writeAppState(\n appStateKeyForBrowserTab(\n \"guided-questions\",\n getRequestRunContext()?.browserTabId,\n ),\n payload,\n );\n return \"Asked the user a clarifying question and rendered it in the chat. Stop here and wait for their answer — do not proceed or assume an answer.\";\n },\n },\n };\n}\n\n/**\n * Creates db-* tools (db-query, db-exec, db-patch, db-schema) as native tools.\n * These let the agent read and write the app's own SQL database. Scoping to\n * the current user/org is enforced automatically in production via temp views.\n *\n * In dev mode template actions are invoked via bash and the agent can call\n * `pnpm action db-query ...` — but in production there is no bash, so these\n * must be registered as native tools for the agent to reach the app DB at all.\n */\nasync function createDbScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const [schemaMod, queryMod, execMod, patchMod] = await Promise.all([\n import(\"../scripts/db/schema.js\"),\n import(\"../scripts/db/query.js\"),\n import(\"../scripts/db/exec.js\"),\n import(\"../scripts/db/patch.js\"),\n ]);\n\n return {\n \"db-schema\": wrapCliScript(\n {\n description:\n \"Show the app's SQL schema — all tables, columns, types, indexes, and foreign keys. Use this to understand the data model before querying.\",\n parameters: {\n type: \"object\",\n properties: {\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n schemaMod.default,\n { readOnly: true },\n ),\n \"db-query\": wrapCliScript(\n {\n description:\n \"Read from the app's own SQL database ONLY. Runs a SELECT against the app's internal tables (settings, application_state, template tables). Results are auto-scoped to the current user/org. IMPORTANT: This tool CANNOT access external data sources like data warehouses, CRMs, issue trackers, analytics platforms, calendars, mail, docs, or other third-party services. For those, use the relevant template/provider action, MCP connector, or provider-api-catalog/provider-api-docs/provider-api-request when available. If the user names a provider, that named provider wins; do not substitute a warehouse or app database copy unless they explicitly ask for it. If a table isn't in the app schema, don't try db-query — use the data-source-specific action. For extension management, use list-extensions, update-extension, hide-extension, or delete-extension instead of querying the legacy tools table.\",\n parameters: {\n type: \"object\",\n properties: {\n sql: {\n type: \"string\",\n description:\n \"SELECT query to run, e.g. \\\"SELECT key, value FROM settings WHERE key LIKE 'sql-dashboard-%'\\\"\",\n },\n args: {\n type: \"string\",\n description:\n 'Optional JSON array of positional bind args for parameterized placeholders. Example: \\'[\"draft\",\"form-123\"]\\'',\n },\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n limit: {\n type: \"string\",\n description:\n \"Append LIMIT N if the query doesn't already have one\",\n },\n },\n required: [\"sql\"],\n },\n },\n queryMod.default,\n { readOnly: true },\n ),\n \"db-exec\": wrapCliScript(\n {\n description:\n \"Write to the app's own SQL database ONLY. Runs INSERT / UPDATE / DELETE / REPLACE against the app's internal tables. For multiple related writes, pass `statements` so they run sequentially in one transaction instead of issuing several db-exec calls. Writes are auto-scoped to the current user/org, and `owner_email` / `org_id` are auto-injected on INSERT. Schema changes (CREATE/ALTER/DROP) are blocked. Never use this to backfill missing data for a read/analysis request or to create/modify users, members, roles, permissions, admin flags, or ownership; use a dedicated app action or reviewed code. IMPORTANT: This tool CANNOT write to external data sources like BigQuery, HubSpot, etc. For external services, use the appropriate template action.\",\n parameters: {\n type: \"object\",\n properties: {\n sql: {\n type: \"string\",\n description:\n \"Single INSERT / UPDATE / DELETE / REPLACE statement. Use parameterized placeholders (?) where possible.\",\n },\n args: {\n type: \"string\",\n description:\n 'Optional JSON array of positional bind args for `sql`. Example: \\'[\"published\",\"form-123\"]\\'',\n },\n statements: {\n type: \"string\",\n description:\n 'Optional JSON array of write statements to execute in one transaction. Prefer this over multiple db-exec calls. Example: \\'[{\"sql\":\"INSERT INTO notes (id,title) VALUES (?,?)\",\"args\":[\"n1\",\"One\"]},{\"sql\":\"UPDATE counters SET value = value + 1 WHERE key = ?\",\"args\":[\"notes\"]}]\\'',\n },\n format: {\n type: \"string\",\n description: 'Output format: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n execMod.default,\n ),\n \"db-patch\": wrapCliScript(\n {\n description:\n \"Surgical patch on a large text/JSON column in the app's SQL database. Two modes: (1) text find/replace via `find`/`replace`/`edits` — best for small edits to documents, slide HTML, etc. (2) structural JSON ops via `json-ops` — STRONGLY PREFERRED when the column is JSON (dashboard configs, form schemas, slide decks) because it avoids all the brace/quote/comma surgery that text find/replace requires. Use `json-ops` to set/remove values at a JSON Pointer path, or to move/insert array items — e.g. reorder dashboard panels, add a filter, rename a field. Targets exactly one row (narrow `where` by primary key). Same per-user/org scoping as db-exec.\",\n parameters: {\n type: \"object\",\n properties: {\n table: {\n type: \"string\",\n description: \"Table name (e.g. 'settings')\",\n },\n column: {\n type: \"string\",\n description:\n \"Text/JSON column to patch (e.g. 'value' for settings)\",\n },\n where: {\n type: \"string\",\n description:\n \"WHERE clause that matches exactly one row (e.g. \\\"key = 'o:org1:sql-dashboard-foo'\\\")\",\n },\n find: {\n type: \"string\",\n description:\n \"Text mode: substring to find. Must match EXACTLY ONE occurrence by default (like Claude Code's Edit tool). If 0 matches, you get 'NOT FOUND'. If >1 matches, you get surrounding context for each match — widen `find` with unique context and retry. Use `all: \\\"true\\\"` to replace every occurrence.\",\n },\n replace: {\n type: \"string\",\n description: \"Text mode: replacement substring\",\n },\n edits: {\n type: \"string\",\n description:\n 'Text mode batch: JSON array of {find, replace} pairs. Same uniqueness rule applies to each `find`. Example: \\'[{\"find\":\"a\",\"replace\":\"b\"}]\\'',\n },\n \"json-ops\": {\n type: \"string\",\n description:\n 'JSON mode: JSON array of structural ops. Each op is {op, path, value?, from?}. `op` is one of \"set\", \"remove\", \"insert\", \"move\", \"move-before\". `path` / `from` use JSON Pointer (\"/panels/3/title\"). Examples — reorder: \\'[{\"op\":\"move\",\"from\":\"/panels/7\",\"path\":\"/panels/1\"}]\\'; edit field: \\'[{\"op\":\"set\",\"path\":\"/panels/0/title\",\"value\":\"New\"}]\\'; delete filter: \\'[{\"op\":\"remove\",\"path\":\"/filters/2\"}]\\'; add panel: \\'[{\"op\":\"insert\",\"path\":\"/panels/0\",\"value\":{\"id\":\"p\",\"title\":\"...\"}}]\\'. Much safer than text find/replace for JSON columns.',\n },\n all: {\n type: \"string\",\n description:\n 'Text mode: set to \"true\" to replace every occurrence of each `find` (default requires exactly one match)',\n enum: [\"true\"],\n },\n },\n required: [\"table\", \"column\", \"where\"],\n },\n },\n patchMod.default,\n ),\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the docs-search tool so agents can look up framework documentation.\n * Docs are bundled in @agent-native/core and read via fs at runtime.\n */\nasync function createDocsScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/docs/search.js\");\n return {\n \"docs-search\": wrapCliScript(\n {\n description:\n \"Search and read agent-native framework documentation, bundled AGENTS.md, and codebase skills. Use --list to see all pages, --query to search, --slug to read a specific page. Codebase skill pages use slugs like skill-<name>.\",\n parameters: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description:\n \"Search term to find relevant docs (e.g. 'actions', 'authentication', 'database')\",\n },\n slug: {\n type: \"string\",\n description:\n \"Read a specific doc page by slug (e.g. 'actions', 'authentication', 'database')\",\n },\n list: {\n type: \"string\",\n description: 'Set to \"true\" to list all available doc pages',\n enum: [\"true\"],\n },\n },\n },\n },\n mod.default,\n { readOnly: true },\n ),\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates resource ScriptEntries available in both prod and dev modes.\n */\nfunction shouldDefaultResourceWriteToWorkspace(path: string): boolean {\n const normalized = path.replace(/^\\/+/, \"\");\n return (\n normalized === \"AGENTS.md\" ||\n normalized === \"LEARNINGS.md\" ||\n normalized.startsWith(\"memory/\") ||\n normalized.startsWith(\"skills/\") ||\n normalized.startsWith(\"jobs/\") ||\n normalized.startsWith(\"agents/\") ||\n normalized.startsWith(\"remote-agents/\")\n );\n}\n\nasync function createResourceScriptEntries(): Promise<\n Record<string, ActionEntry>\n> {\n try {\n const [list, read, effective, write, del, saveMem, delMem, store] =\n await Promise.all([\n import(\"../scripts/resources/list.js\"),\n import(\"../scripts/resources/read.js\"),\n import(\"../scripts/resources/effective.js\"),\n import(\"../scripts/resources/write.js\"),\n import(\"../scripts/resources/delete.js\"),\n import(\"../scripts/resources/save-memory.js\"),\n import(\"../scripts/resources/delete-memory.js\"),\n import(\"../resources/store.js\"),\n ]);\n\n // Wrap each CLI runner so it captures stdout and converts args properly\n const listEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n list.default,\n { readOnly: true },\n );\n const readEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n read.default,\n { readOnly: true },\n );\n const writeEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n write.default,\n );\n const effectiveEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n effective.default,\n { readOnly: true },\n );\n const deleteEntry = wrapCliScript(\n {\n description: \"\",\n parameters: { type: \"object\" as const, properties: {} },\n },\n del.default,\n );\n\n return {\n resources: {\n tool: {\n description:\n 'Manage workspace resources. Actions: \"list\" (browse visible files), \"read\" (get contents), \"effective\" (show workspace -> organization/app -> personal inheritance for a path), \"write\" (create/update personal or shared; workspace only for local file mode control files), \"promote\" (make agent scratch visible), \"delete\" (remove personal or shared; workspace only for local file mode control files). Agent scratch writes are hidden from the Workspace view by default; use visibility=\"workspace\" only for files the user explicitly wants to keep/manage.',\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n description: \"The operation to perform\",\n enum: [\n \"list\",\n \"read\",\n \"effective\",\n \"write\",\n \"promote\",\n \"delete\",\n ],\n },\n path: {\n type: \"string\",\n description:\n \"Resource path (e.g. 'LEARNINGS.md', 'notes/ideas.md'). Required for read/write/delete.\",\n },\n content: {\n type: \"string\",\n description: \"Content to write. Required for write.\",\n },\n scope: {\n type: \"string\",\n description:\n \"personal, shared, workspace, or all (default varies by action). Workspace is read-only when inherited from Dispatch; in local file mode AGENTS.md, agent-native.json, mcp.config.json, .mcp.json, and skills/ are writable.\",\n enum: [\"personal\", \"shared\", \"workspace\", \"all\"],\n },\n prefix: {\n type: \"string\",\n description:\n \"Filter by path prefix when listing (e.g. 'notes/')\",\n },\n mime: {\n type: \"string\",\n description:\n \"MIME type for write (default: inferred from extension)\",\n },\n format: {\n type: \"string\",\n description:\n 'Output format for list: \"json\" or \"text\" (default: text)',\n enum: [\"json\", \"text\"],\n },\n visibility: {\n type: \"string\",\n description:\n 'Visibility for write: \"agent_scratch\" for internal working files, \"workspace\" for user-requested files. Defaults to agent_scratch except durable instruction/skill/job/memory paths.',\n enum: [\"workspace\", \"agent_scratch\"],\n },\n includeAgentScratch: {\n type: \"boolean\",\n description: \"Include hidden agent scratch files when listing.\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const { action: a, ...rest } = args;\n if (a === \"list\") return listEntry.run(rest);\n if (a === \"read\") {\n if (!rest.path) return \"Error: path is required for read\";\n return readEntry.run(rest);\n }\n if (a === \"effective\") {\n if (!rest.path) return \"Error: path is required for effective\";\n return effectiveEntry.run(rest);\n }\n if (a === \"write\") {\n if (\n !rest.path ||\n rest.content === undefined ||\n rest.content === null\n )\n return \"Error: path and content are required for write\";\n rest.createdBy = \"agent\";\n rest.visibility =\n rest.visibility ??\n (shouldDefaultResourceWriteToWorkspace(String(rest.path))\n ? \"workspace\"\n : \"agent_scratch\");\n const runCtx = getRequestRunContext();\n if (runCtx?.threadId) rest.threadId = runCtx.threadId;\n return writeEntry.run(rest);\n }\n if (a === \"promote\") {\n if (!rest.path) return \"Error: path is required for promote\";\n const scope = rest.scope ?? \"personal\";\n if (scope === \"workspace\" || scope === \"all\") {\n return \"Error: promote supports personal or shared scope only\";\n }\n const owner =\n scope === \"shared\"\n ? store.SHARED_OWNER\n : (getRequestRunContext()?.owner ??\n getRequestUserEmail() ??\n process.env.AGENT_USER_EMAIL);\n if (!owner) {\n return \"Error: promote requires an authenticated user\";\n }\n const resource = await store.resourceGetByPath(\n owner,\n String(rest.path),\n );\n if (!resource) {\n return `Resource not found: ${rest.path}`;\n }\n const promoted = await store.resourcePut(\n owner,\n resource.path,\n resource.content,\n resource.mimeType,\n {\n createdBy: resource.createdBy,\n visibility: \"workspace\",\n threadId: resource.threadId,\n runId: resource.runId,\n expiresAt: null,\n metadata: resource.metadata,\n },\n );\n return `Promoted resource: ${promoted.path}`;\n }\n if (a === \"delete\") {\n if (!rest.path) return \"Error: path is required for delete\";\n return deleteEntry.run(rest);\n }\n return `Error: unknown action \"${a}\". Use: list, read, write, promote, delete`;\n },\n },\n \"save-memory\": wrapCliScript(\n {\n description:\n \"Save a memory for future conversations. Creates or updates a memory file and its index entry. Use proactively when you learn preferences, corrections, project context, or references.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description:\n \"Short kebab-case identifier (e.g. 'coding-style', 'deploy-process'). Used as the filename.\",\n },\n type: {\n type: \"string\",\n description: \"Memory category\",\n enum: [\"user\", \"feedback\", \"project\", \"reference\"],\n },\n description: {\n type: \"string\",\n description:\n \"One-line summary shown in the memory index (keep under 80 chars)\",\n },\n content: {\n type: \"string\",\n description:\n \"The memory content in markdown. For updates, read first and provide full updated content.\",\n },\n },\n required: [\"name\", \"type\", \"description\", \"content\"],\n },\n },\n saveMem.default,\n ),\n \"delete-memory\": wrapCliScript(\n {\n description:\n \"Delete a memory entry and remove it from the memory index.\",\n parameters: {\n type: \"object\",\n properties: {\n name: {\n type: \"string\",\n description: \"The memory name to delete (e.g. 'coding-style')\",\n },\n },\n required: [\"name\"],\n },\n },\n delMem.default,\n ),\n };\n } catch {\n // Resources not available — skip silently\n return {};\n }\n}\n\n/**\n * Creates a unified chat-history ActionEntry that dispatches to search, open,\n * rename, or lightweight organization actions.\n */\nasync function createChatScriptEntries(): Promise<Record<string, ActionEntry>> {\n try {\n const [searchMod, openMod] = await Promise.all([\n import(\"../scripts/chat/search-chats.js\"),\n import(\"../scripts/chat/open-chat.js\"),\n ]);\n\n const searchEntry = wrapCliScript(\n {\n description: \"Search or list past agent chat threads.\",\n parameters: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description:\n \"Search term to find chats by title, preview, or content\",\n },\n limit: {\n type: \"string\",\n description: \"Max number of results (default: 20)\",\n },\n format: {\n type: \"string\",\n description: \"Output format\",\n enum: [\"json\", \"text\"],\n },\n },\n },\n },\n searchMod.default,\n );\n\n const openEntry = wrapCliScript(\n {\n description: \"Open a chat thread in the UI.\",\n parameters: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"The chat thread ID to open\",\n },\n },\n required: [\"id\"],\n },\n },\n openMod.default,\n );\n\n return {\n \"chat-history\": {\n tool: {\n description:\n \"Manage past agent chat threads. Use action 'search' to find previous conversations by keyword, 'open' to open a thread in the UI, or 'rename'/'pin'/'unpin'/'archive' to organize history.\",\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n description: \"The operation to perform\",\n enum: [\"search\", \"open\", \"rename\", \"pin\", \"unpin\", \"archive\"],\n },\n query: {\n type: \"string\",\n description:\n \"(search) Search term to find chats by title, preview, or content\",\n },\n limit: {\n type: \"string\",\n description: \"(search) Max number of results (default: 20)\",\n },\n format: {\n type: \"string\",\n description: \"(search) Output format\",\n enum: [\"json\", \"text\"],\n },\n id: {\n type: \"string\",\n description:\n \"(open, rename, pin, unpin, archive) The chat thread ID to manage\",\n },\n title: {\n type: \"string\",\n description: \"(rename) New chat title\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args) => {\n if (args?.action === \"open\") {\n return openEntry.run(args);\n }\n if (\n args?.action === \"rename\" ||\n args?.action === \"pin\" ||\n args?.action === \"unpin\" ||\n args?.action === \"archive\"\n ) {\n const id = typeof args?.id === \"string\" ? args.id : \"\";\n if (!id) return \"Missing required id.\";\n const owner =\n getRequestRunContext()?.owner ?? getRequestUserEmail() ?? \"\";\n if (!owner) return \"No authenticated user is available.\";\n const thread = await getThread(id);\n if (!thread || thread.ownerEmail !== owner) {\n return `Chat thread \"${id}\" not found.`;\n }\n const title = thread.title || thread.preview || \"(untitled)\";\n if (args.action === \"rename\") {\n const nextTitle =\n typeof args?.title === \"string\"\n ? args.title.replace(/\\s+/g, \" \").trim().slice(0, 160)\n : \"\";\n if (!nextTitle) return \"Missing required title.\";\n const renamed = await renameThread(id, nextTitle, {\n ownerEmail: owner,\n });\n if (!renamed) return `Chat thread \"${id}\" could not be renamed.`;\n return `Renamed chat \"${title}\" to \"${nextTitle}\".`;\n }\n if (args.action === \"archive\") {\n const archived = await setThreadArchived(id, true, {\n ownerEmail: owner,\n });\n if (!archived)\n return `Chat thread \"${id}\" could not be archived.`;\n return `Archived chat: ${title}`;\n }\n const pinned = await setThreadPinned(id, args.action === \"pin\", {\n ownerEmail: owner,\n });\n if (!pinned) return `Chat thread \"${id}\" could not be updated.`;\n return `${args.action === \"pin\" ? \"Pinned\" : \"Unpinned\"} chat: ${title}`;\n }\n return searchEntry.run(args);\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the consolidated manage-agent-engine tool (list / set / test).\n * Let the agent inspect and configure the active LLM engine.\n */\nasync function createAgentEngineScriptEntries(\n appId?: string,\n): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/agent-engines/manage-agent-engine.js\");\n\n return {\n \"manage-agent-engine\": {\n tool: mod.tool,\n run: (args) =>\n mod.run({\n ...args,\n appId:\n typeof args.appId === \"string\" && args.appId.trim()\n ? args.appId\n : (appId ?? \"\"),\n }),\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the manage-agent-loop-settings tool. Lets the agent inspect and\n * configure the loop step limit it may hit on long-running work.\n */\nasync function createAgentLoopSettingsScriptEntries(): Promise<\n Record<string, ActionEntry>\n> {\n try {\n const mod = await import(\"../scripts/manage-agent-loop-settings.js\");\n\n return {\n \"manage-agent-loop-settings\": { tool: mod.tool, run: mod.run },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Creates the call-agent ActionEntry for cross-agent A2A communication.\n * Binds selfAppId so the agent cannot call itself via call-agent.\n */\nasync function createCallAgentScriptEntry(\n selfAppId?: string,\n): Promise<Record<string, ActionEntry>> {\n try {\n const mod = await import(\"../scripts/call-agent.js\");\n return {\n \"call-agent\": {\n tool: mod.tool,\n run: (args, context) => mod.run(args, context, selfAppId),\n },\n };\n } catch {\n return {};\n }\n}\n\nfunction createBuilderBrowserTool(deps: {\n getOrigin: () => string;\n getOwner?: () => string | null | undefined;\n}): Record<string, ActionEntry> {\n const setBuiltinForCurrentUser = async (\n id: BuiltinMcpCapabilityId,\n enabled: boolean,\n ) => {\n const email = getRequestUserEmail();\n if (!email) {\n return {\n ok: false,\n error: \"not-signed-in\",\n message: \"You must be signed in to change built-in MCP tools.\",\n };\n }\n const enabledIds = await setBuiltinMcpCapabilityEnabled(\n \"user\",\n email,\n id,\n enabled,\n );\n const manager = getGlobalMcpManager();\n if (manager) {\n await manager.reconfigure(await buildMergedConfig());\n }\n return { ok: true, enabledIds: enabledIds ?? [] };\n };\n\n const entries: Record<string, ActionEntry> = {\n \"connect-builder\": {\n tool: {\n description:\n \"Render a Builder.io card inline in the chat. Call this as the first step (no code exploration or planning needed) when the user asks to modify the APP'S OWN SOURCE CODE: add a feature, change the UI chrome, edit a React component, add a route, add an integration, fix a bug in the app itself, or anything else that requires source-file edits while in hosted/production mode. Do NOT call this for creating or editing extensions/widgets/dashboards/calculators/mini-apps; those are sandboxed extension data and must use create-extension/update-extension instead. Do NOT call this for content the app is meant to produce — creating a video, generating a design, drafting an email, building a slide deck, making a dashboard, etc. — those run through the app's own domain actions, not Builder. Do NOT mention 'click Send to Builder' in your response unless this card is already in the conversation. If Builder is connected and Builder Cloud Agents are available, the card shows a 'Send to Builder' button that hands the work off to Builder's cloud agent and returns a branch URL. If `builderEnabled` is false, the card shows a waitlist/local-dev fallback instead; never tell the user to enable Builder Cloud Agents in Builder org settings or beta settings, and do not claim the Builder card has everything, is pre-loaded for handoff, or can run the cloud agent. When you call this for a code-change request, pass the user's request verbatim as the `prompt` arg so the card can forward it to Builder unchanged when cloud agents are available.\",\n parameters: {\n type: \"object\",\n properties: {\n prompt: {\n type: \"string\",\n description:\n \"The user's feature / change request, verbatim. Forwarded to Builder's cloud agent when the user clicks Send. Omit only for generic 'connect Builder' requests that aren't tied to a specific code change.\",\n },\n },\n },\n },\n run: async (args) => {\n const { getBuilderCredentialAuthFailure, resolveBuilderCredentials } =\n await import(\"./credential-provider.js\");\n const creds = await resolveBuilderCredentials();\n const authFailure = await getBuilderCredentialAuthFailure(creds);\n const configured = !!(\n creds.privateKey &&\n creds.publicKey &&\n !authFailure\n );\n const branchProjectId = await resolveBuilderBranchProjectId();\n const prompt = typeof args?.prompt === \"string\" ? args.prompt : \"\";\n const origin = deps.getOrigin();\n const ownerEmail = deps.getOwner?.() ?? getRequestUserEmail();\n return JSON.stringify({\n kind: \"connect-builder-card\",\n configured,\n builderEnabled: !!branchProjectId,\n connectUrl: getBuilderBrowserConnectUrlForOwner(origin, ownerEmail),\n orgName: creds.orgName || null,\n prompt,\n });\n },\n },\n \"set-browser-control\": {\n tool: {\n description:\n \"Enable or disable built-in browser-control MCP tools for the current user. Call this when the user asks to test, screenshot, inspect, or interact with a web page and browser tools are not available; confirm once before enabling. Prefer the chrome-devtools backend for live logged-in Chrome, and use playwright when an isolated browser is better.\",\n parameters: {\n type: \"object\",\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Whether browser-control tools should be enabled.\",\n },\n backend: {\n type: \"string\",\n enum: [\"chrome-devtools\", \"playwright\"],\n description:\n \"Browser backend to enable. Defaults to chrome-devtools.\",\n },\n },\n required: [\"enabled\"],\n },\n },\n run: async (args) => {\n const parsed =\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {};\n const enabled = parsed.enabled !== false;\n const requestedBackend =\n typeof parsed.backend === \"string\" ? parsed.backend : undefined;\n const backend =\n requestedBackend === \"playwright\" ? \"playwright\" : \"chrome-devtools\";\n const targetId: BuiltinMcpCapabilityId =\n backend === \"playwright\"\n ? \"browser-playwright\"\n : \"browser-chrome-devtools\";\n\n if (!enabled) {\n const chrome = await setBuiltinForCurrentUser(\n \"browser-chrome-devtools\",\n false,\n );\n if (!chrome.ok) return JSON.stringify(chrome);\n const playwright = await setBuiltinForCurrentUser(\n \"browser-playwright\",\n false,\n );\n return JSON.stringify({\n ...playwright,\n enabled: false,\n message: \"Browser-control MCP tools are disabled.\",\n });\n }\n\n const result = await setBuiltinForCurrentUser(targetId, true);\n return JSON.stringify({\n ...result,\n enabled: true,\n backend,\n message:\n backend === \"chrome-devtools\"\n ? \"Chrome DevTools MCP is enabled. Browser tools will be available on the next action when Chrome remote debugging is available.\"\n : \"Playwright MCP is enabled. Browser tools will be available on the next action in an isolated Playwright browser.\",\n });\n },\n },\n \"set-computer-use\": {\n tool: {\n description:\n \"Enable or disable built-in Computer Use MCP tools for the current user. Call only after the user explicitly asks to let the agent control local desktop apps. macOS may require Screen Recording and Accessibility permissions.\",\n parameters: {\n type: \"object\",\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Whether Computer Use tools should be enabled.\",\n },\n },\n required: [\"enabled\"],\n },\n },\n run: async (args) => {\n const parsed =\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {};\n const enabled = parsed.enabled !== false;\n if (enabled && process.platform !== \"darwin\") {\n return JSON.stringify({\n ok: false,\n error: \"unsupported-platform\",\n message: \"Computer Use is currently available only on macOS.\",\n });\n }\n const result = await setBuiltinForCurrentUser(\"computer-use\", enabled);\n return JSON.stringify({\n ...result,\n enabled,\n message: enabled\n ? \"Computer Use MCP is enabled. If macOS prompts, grant Screen Recording and Accessibility permission in System Settings > Privacy & Security.\"\n : \"Computer Use MCP is disabled.\",\n });\n },\n },\n \"activate-browser\": {\n tool: {\n description:\n \"Activate browser automation tools. Call this when you need to interact with a real browser — e.g. to extract design tokens from a rendered page, take screenshots, read computed styles from JS-heavy sites, or test a live URL. After activation, chrome-devtools MCP tools (navigate, click, evaluate_script, take_screenshot, etc.) become available on your next action. Requires Builder.io connection.\",\n parameters: {\n type: \"object\",\n properties: {\n sessionId: {\n type: \"string\",\n description:\n \"Optional session identifier for the browser connection. Auto-generated if omitted.\",\n },\n },\n },\n },\n run: async (args) => {\n const { resolveBuilderCredentials } =\n await import(\"./credential-provider.js\");\n const creds = await resolveBuilderCredentials();\n if (!creds.privateKey || !creds.publicKey) {\n return JSON.stringify({\n error: \"builder-not-connected\",\n message:\n \"Builder.io is not connected. Call `connect-builder` first to enable browser automation.\",\n });\n }\n\n const { requestBuilderBrowserConnection } =\n await import(\"./builder-browser.js\");\n const sessionId =\n (typeof args?.sessionId === \"string\" && args.sessionId) ||\n `an-browser-${Date.now()}`;\n\n let connection: Record<string, unknown>;\n try {\n connection = await requestBuilderBrowserConnection({ sessionId });\n } catch (err: any) {\n return JSON.stringify({\n error: \"browser-connection-failed\",\n message: `Failed to get browser connection: ${err?.message ?? err}`,\n });\n }\n\n const wsUrl = connection.wsUrl as string;\n if (!wsUrl) {\n return JSON.stringify({\n error: \"no-ws-url\",\n message: \"Browser connection did not return a WebSocket URL.\",\n });\n }\n\n const manager = getGlobalMcpManager();\n if (!manager) {\n return JSON.stringify({\n error: \"no-mcp-manager\",\n message: \"MCP manager is not available.\",\n });\n }\n\n // Add chrome-devtools-mcp server pointing at the provisioned browser\n const currentConfig = manager.getConfig();\n const servers = { ...(currentConfig?.servers ?? {}) };\n servers[\"chrome-devtools\"] = {\n command: \"npx\",\n args: [\n \"-y\",\n \"chrome-devtools-mcp@0.26.0\",\n \"--wsEndpoint\",\n wsUrl,\n \"--categoryEmulation=false\",\n ],\n type: \"stdio\",\n } as any;\n\n await manager.reconfigure({\n servers,\n source: currentConfig?.source ?? \"runtime\",\n });\n\n return JSON.stringify({\n success: true,\n message:\n \"Browser activated. Chrome DevTools MCP tools (mcp__chrome-devtools__*) are now available. Use them on your next action to navigate pages, read DOM, take screenshots, evaluate JavaScript, etc.\",\n wsUrl,\n sessionId,\n });\n },\n },\n };\n\n if (!areBuiltinMcpCapabilitiesSupported()) {\n delete entries[\"set-browser-control\"];\n delete entries[\"set-computer-use\"];\n }\n\n return entries;\n}\n\n/**\n * Creates the unified `agent-teams` tool that consolidates all sub-agent\n * orchestration behind a single tool with an `action` parameter.\n */\nfunction createTeamTools(deps: {\n getOwner: () => string;\n getSystemPrompt: () => string;\n getActions: () => Record<string, ActionEntry>;\n getEngine: () => AgentEngine;\n getModel: () => string;\n getParentThreadId: () => string;\n getSend: () =>\n | ((event: import(\"../agent/types.js\").AgentChatEvent) => void)\n | null;\n}): Record<string, ActionEntry> {\n return {\n \"agent-teams\": {\n tool: {\n description:\n \"Manage background sub-agent tasks. Use action 'spawn' to start a new sub-agent, 'status' to check progress, 'read-result' to get a finished task's output, 'send' to message a running sub-agent, or 'list' to see all tasks. A successful spawn only means the task started and is running; do not report it as finished until status/read-result shows a terminal status.\",\n parameters: {\n type: \"object\",\n properties: {\n action: {\n type: \"string\",\n enum: [\"spawn\", \"status\", \"read-result\", \"send\", \"list\"],\n description: \"The operation to perform\",\n },\n task: {\n type: \"string\",\n description:\n \"(spawn) Clear description of what the sub-agent should accomplish\",\n },\n instructions: {\n type: \"string\",\n description:\n \"(spawn) Optional additional instructions or context for the sub-agent\",\n },\n name: {\n type: \"string\",\n description:\n \"(spawn) Short name for the sub-agent tab (e.g. 'Research', 'Draft email'). If omitted, derived from the task.\",\n },\n agent: {\n type: \"string\",\n description:\n \"(spawn) Optional custom agent profile from agents/*.md to use for this task.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"(status, read-result, send) The task ID returned by a previous spawn\",\n },\n message: {\n type: \"string\",\n description: \"(send) Message to send to the sub-agent\",\n },\n },\n required: [\"action\"],\n },\n },\n run: async (args: Record<string, string>) => {\n const action = args.action;\n\n // ── spawn ──────────────────────────────────────────────\n if (action === \"spawn\") {\n if (!args.task) throw new Error(\"'task' is required for spawn\");\n // Capture the send function NOW (at spawn time) so that\n // concurrent runs don't clobber each other's send reference.\n const capturedSend = deps.getSend();\n const { spawnTask } = await import(\"./agent-teams.js\");\n // Filter out the team tool so sub-agents can't spawn sub-agents\n const subAgentActions = Object.fromEntries(\n Object.entries(deps.getActions()).filter(\n ([name]) => name !== \"agent-teams\",\n ),\n );\n let instructions = args.instructions;\n let selectedModel = deps.getModel();\n let selectedName = args.name || \"\";\n if (args.agent) {\n const { findAccessibleCustomAgent } =\n await import(\"../resources/agents.js\");\n const profile = await findAccessibleCustomAgent(\n deps.getOwner(),\n args.agent,\n );\n if (!profile) {\n throw new Error(`Custom agent not found: ${args.agent}`);\n }\n const profileInstructions =\n `## Custom Agent Profile: ${profile.name}\\n\\n` +\n (profile.description ? `${profile.description}\\n\\n` : \"\") +\n profile.instructions;\n instructions = instructions\n ? `${profileInstructions}\\n\\n## Extra Task Context\\n\\n${instructions}`\n : profileInstructions;\n selectedModel = profile.model ?? selectedModel;\n selectedName = selectedName || profile.name;\n }\n const task = await spawnTask({\n description: args.task,\n instructions,\n ownerEmail: deps.getOwner(),\n systemPrompt: deps.getSystemPrompt(),\n actions: subAgentActions,\n engine: deps.getEngine(),\n model: selectedModel,\n name: selectedName || undefined,\n parentThreadId: deps.getParentThreadId(),\n parentSend: (event) => {\n if (capturedSend) capturedSend(event);\n },\n });\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n runId: task.runId,\n status: task.status,\n parentThreadId: task.parentThreadId,\n state: \"launched_pending_completion\",\n message:\n \"Sub-agent launched and is still running. Use status or read-result later; do not describe this task as completed from the spawn response alone.\",\n description: task.description,\n name: task.name ?? selectedName,\n });\n }\n\n // ── status ─────────────────────────────────────────────\n if (action === \"status\") {\n if (!args.taskId) throw new Error(\"'taskId' is required for status\");\n const { getTask } = await import(\"./agent-teams.js\");\n const task = await getTask(args.taskId);\n if (!task) return JSON.stringify({ error: \"Task not found\" });\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n status: task.status,\n description: task.description,\n name: task.name,\n preview: task.preview,\n currentStep: task.currentStep,\n summary: task.summary,\n });\n }\n\n // ── read-result ────────────────────────────────────────\n if (action === \"read-result\") {\n if (!args.taskId)\n throw new Error(\"'taskId' is required for read-result\");\n const { getTask } = await import(\"./agent-teams.js\");\n const task = await getTask(args.taskId);\n if (!task) return JSON.stringify({ error: \"Task not found\" });\n if (task.status === \"running\") {\n return JSON.stringify({\n status: \"running\",\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n name: task.name,\n preview: task.preview,\n message:\n \"Task is still running. Do not report it as complete; use status/read-result later.\",\n });\n }\n return JSON.stringify({\n taskId: task.taskId,\n threadId: task.threadId,\n parentThreadId: task.parentThreadId,\n name: task.name,\n status: task.status,\n summary: task.summary,\n preview: task.preview,\n });\n }\n\n // ── send ───────────────────────────────────────────────\n if (action === \"send\") {\n if (!args.taskId) throw new Error(\"'taskId' is required for send\");\n if (!args.message) throw new Error(\"'message' is required for send\");\n const { sendToTask } = await import(\"./agent-teams.js\");\n const result = await sendToTask(args.taskId, args.message);\n return JSON.stringify(result);\n }\n\n // ── list ───────────────────────────────────────────────\n if (action === \"list\") {\n const { listTasks } = await import(\"./agent-teams.js\");\n const tasks = await listTasks();\n if (tasks.length === 0) {\n return \"No sub-agent tasks.\";\n }\n return JSON.stringify(\n tasks.map((t) => ({\n taskId: t.taskId,\n threadId: t.threadId,\n parentThreadId: t.parentThreadId,\n name: t.name,\n description: t.description,\n status: t.status,\n currentStep: t.currentStep,\n hasResult: t.summary.length > 0,\n })),\n null,\n 2,\n );\n }\n\n throw new Error(\n `Unknown action '${action}'. Use one of: spawn, status, read-result, send, list`,\n );\n },\n },\n };\n}\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nexport interface AgentChatPluginOptions {\n /** Template-specific actions (email ops, booking ops, etc.) */\n actions?:\n | Record<string, ActionEntry>\n | (() =>\n | Record<string, ActionEntry>\n | Promise<Record<string, ActionEntry>>);\n /** @deprecated Use `actions` instead */\n scripts?:\n | Record<string, ActionEntry>\n | (() =>\n | Record<string, ActionEntry>\n | Promise<Record<string, ActionEntry>>);\n /** System prompt for the agent. A sensible default is provided. */\n systemPrompt?: string;\n /** Additional system prompt prepended in dev mode */\n devSystemPrompt?: string;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Optional per-app agent run chunk budget in milliseconds. Defaults to\n * AGENT_RUN_SOFT_TIMEOUT_MS when set, otherwise no framework-imposed\n * timeout. When reached, long runs continue through the hidden continuation\n * path instead of surfacing a timeout warning. */\n runSoftTimeoutMs?: number;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var */\n apiKey?: string;\n /**\n * Agent engine to use. Can be a pre-constructed AgentEngine, a registered\n * engine name (e.g. \"anthropic\", \"ai-sdk:openai\"), or an object with name\n * and config. Defaults to the \"anthropic\" engine using ANTHROPIC_API_KEY.\n */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Route path. Default: /_agent-native/agent-chat */\n path?: string;\n /** Custom mention providers for @-tagging template entities */\n mentionProviders?:\n | Record<string, MentionProvider>\n | (() =>\n | Record<string, MentionProvider>\n | Promise<Record<string, MentionProvider>>);\n /** App ID used to exclude self from agent discovery (e.g., \"mail\", \"calendar\") */\n appId?: string;\n /** Optional MCP server branding surfaced during the initialize handshake. */\n mcpServerInfo?: {\n /** Human-facing title. Defaults to the capitalized app id/name. */\n title?: string;\n /** Host-facing description. Defaults to \"Agent-native <app> agent\". */\n description?: string;\n /** Canonical app URL. Relative URLs are resolved against the request origin. */\n websiteUrl?: string;\n /** App icons. Relative `src` values are resolved against the request origin. */\n icons?: Array<{\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: \"light\" | \"dark\";\n }>;\n };\n /**\n * Optional callback to resolve the org ID for the current request.\n * When provided, the resolved value is set as AGENT_ORG_ID env var so\n * that db-query/db-exec automatically scope by org_id in addition to\n * owner_email.\n *\n * If not provided, the framework automatically uses `session.orgId` from\n * Better Auth's active organization. Only provide this callback when you\n * need custom org resolution logic (e.g., Atlassian org mapping).\n */\n resolveOrgId?: (event: any) => string | null | Promise<string | null>;\n /**\n * Optional owner resolver for public/anonymous chat surfaces. When the\n * normal app session is missing, this callback may return a synthetic\n * owner id for a narrowly-scoped public request (for example, a public\n * shared document page). Anonymous requests use a read-only tool set by\n * default so public viewers cannot mutate app data through the agent.\n */\n anonymousOwner?: (event: any) => string | null | Promise<string | null>;\n /**\n * Keep anonymous-owner requests on read-only template actions. Defaults to\n * true. Only disable for single-tenant apps that intentionally allow public\n * agent mutations.\n */\n anonymousReadOnly?: boolean;\n /**\n * Optional callback to append template-specific context to the system\n * prompt on each request. Runs after AGENTS.md / skills / memory are\n * loaded and before the schema block — use it to inject dynamic SQL\n * context like a data dictionary, active feature flags, or whatever\n * the agent should know about *right now* for this user/org.\n *\n * Return `null` or an empty string to skip. The string you return is\n * appended verbatim, so wrap it in your own XML tags (e.g.\n * `<data-dictionary>…</data-dictionary>`) to keep the prompt scannable.\n *\n * Called on every request in every prompt variant (lean, lazy, full).\n * Templates that want to suppress it in a particular mode should return\n * `null` from the callback based on their own logic.\n */\n extraContext?: (\n event: any,\n owner: string,\n ) => string | null | Promise<string | null>;\n /**\n * Optional final-answer guard. Templates can use this to require a\n * corrective retry before accepting a text-only final answer, e.g. forcing\n * real data-source tool calls for analytics requests.\n */\n finalResponseGuard?: import(\"../agent/production-agent.js\").AgentLoopFinalResponseGuard;\n /**\n * Optional per-template request normalizer. Runs after authentication and\n * before the model sees the message, so apps can translate chat attachments\n * into template-native file handles while preserving the user's visible text.\n */\n prepareRequest?: (details: {\n event: any;\n ownerEmail: string | null;\n message: string;\n displayMessage?: string;\n attachments: AgentChatAttachment[];\n references: AgentChatReference[];\n threadId?: string;\n internalContinuation?: boolean;\n mode: \"act\" | \"plan\";\n }) =>\n | void\n | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }\n | Promise<void | {\n message?: string;\n displayMessage?: string;\n attachments?: AgentChatAttachment[];\n }>;\n /**\n * Use ONLY the template's `systemPrompt` and the actions list — skip the\n * framework prompt wrapper, resource loading (AGENTS.md/LEARNINGS.md/\n * memory), the SQL schema block, and the workspace files/skills/agents\n * inventory. Intended for minimal or voice-first apps where a long,\n * generic preamble adds latency and iteration noise without adding value.\n *\n * When set, the same lean prompt is used in both dev and prod modes. In\n * dev mode the tool registry is ALSO swapped to the template's actions\n * (same set as prod) — the dev-only bash/db-exec/file-system tools\n * and the resource/docs/chat/team/job/browser scripts are dropped. The\n * lean system prompt has no bash-usage guidance, so routing actions\n * through bash would break. If you need the full dev tool surface,\n * leave this off.\n */\n leanPrompt?: boolean;\n /**\n * Use a compact system prompt with on-demand context loading. The system\n * prompt includes essential behavioral rules and action signatures, but\n * defers verbose framework details, SQL schema, skills, learnings, and\n * memory behind tools (`get-framework-context`, `db-schema`,\n * `resources` (action: read)). The agent fetches these on-demand when needed.\n *\n * This reduces the system prompt by ~60-70%, significantly improving\n * time-to-first-token and reducing \"thinking\" time. The agent retains\n * all capabilities — it just loads context lazily instead of upfront.\n *\n * Defaults to `true`. Set to `false` to use the original full prompt.\n * Ignored when `leanPrompt` is set (lean mode is even more minimal).\n */\n lazyContext?: boolean;\n /**\n * In dev mode, register the template's actions as native tools the agent\n * can call directly with structured JSON args — skipping the default\n * `bash(command=\"pnpm action <name> ...\")` indirection.\n *\n * The default dev behavior shells out because it \"mirrors how Claude Code\n * works locally\" and reduces empty-object tool calls for templates with\n * simple string args. But templates whose actions take structured data\n * (objects, arrays, nested JSON) can't round-trip those cleanly through\n * the CLI parser — stringified JSON on the way in, loss of type fidelity\n * on the way out.\n *\n * Set to `true` to get the same tool surface in dev that production uses.\n * `leanPrompt: true` implies this already (lean mode has no bash-usage\n * guidance, so actions must be native). Set this flag without\n * `leanPrompt` when you want native actions AND the full system prompt.\n *\n * Defaults to `false`.\n */\n nativeActionsInDev?: boolean;\n /**\n * Optional A2A-only deterministic response path. Runs after inbound A2A text\n * and user context are resolved, but before an agent engine/model is loaded.\n * Return a message to complete the A2A task without invoking the LLM, or\n * null/undefined to continue through the normal agent loop.\n */\n a2aMessageFallback?: (details: {\n message: import(\"../a2a/types.js\").Message;\n text: string;\n context: import(\"../a2a/types.js\").A2AHandlerContext;\n userEmail: string | undefined;\n }) =>\n | import(\"../a2a/types.js\").Message\n | string\n | null\n | undefined\n | Promise<import(\"../a2a/types.js\").Message | string | null | undefined>;\n /**\n * Optional injectable prompt examples for core rules (rule 5 auto-refresh\n * examples and rule 8 external provider names). When absent, generic\n * placeholders are used so no template-specific names appear in the core\n * prompt by default.\n *\n * - `providerActions`: external provider action names this template exposes\n * (e.g. `[\"warehouse-query\", \"crm-records\"]` for a template).\n * - `appActions`: representative template action names for rule 5's refresh\n * examples (e.g. `[\"log-meal\", \"update-form\"]` for a forms template).\n */\n promptExamples?: PromptExamples;\n /**\n * Curated allow-list of action names to serve external **connector** clients\n * on a hosted multi-tenant deployment.\n *\n * Whenever this list is non-empty it is active by default for **every**\n * caller (hosted connectors, code/stdio clients, and the local CLI): external\n * MCP clients see (and can call) only these actions plus the builtin\n * cross-app tools (`list_apps`, `open_app`, `ask_app`, `create_embed_session`).\n * Calls to any tool outside the list are rejected with \"Unknown tool\".\n * This prevents the full ~105-tool catalog from bloating external-agent\n * context windows and removes footguns (db-exec, seed-*, extension suite,\n * browser-session tools) from connectors. It is no longer gated behind an\n * environment variable, and the catalog is never inferred from the client.\n *\n * `tool-search` stays available so any trimmed tool is reachable on demand.\n * Callers who need the full surface up front opt in explicitly with\n * `agent-native connect --full-catalog` (embeds a `catalog_scope: \"full\"`\n * claim in their connect-minted JWT) or the deployment-wide\n * `AGENT_NATIVE_MCP_FULL_CATALOG=1` env override.\n *\n * Declare here rather than in MCPConfig directly; the plugin copies it through.\n */\n connectorCatalog?: string[];\n\n /**\n * Code-execution capability for the production agent.\n *\n * - `\"off\"` (default) — no code-execution tools in production.\n * - `\"sandboxed\"` — registers the `run-code` tool (isolated Node.js sandbox\n * with a bridge to allowlisted registered tools). Safe for shared or\n * hosted deployments.\n * - `\"trusted\"` — registers both the full coding tool registry\n * (bash / read / edit / write) and the `run-code` sandbox. Only use in\n * single-tenant or operator-controlled deployments where full shell access\n * to the host machine is intentional.\n *\n * The `AGENT_PROD_CODE_EXECUTION` environment variable (`\"trusted\"`,\n * `\"sandboxed\"`, or `\"off\"`) takes precedence over this option, allowing\n * per-deployment overrides without code changes.\n *\n * Dev-mode behavior is unchanged — both the coding tools and `run-code` are\n * always available when the environment allows toggling.\n */\n codeExecution?: {\n production?: \"off\" | \"sandboxed\" | \"trusted\";\n /**\n * Extra registered-tool names the sandbox bridge may forward (beyond the\n * default allowlist: provider-api-request, provider-api-docs,\n * provider-api-catalog, web-request).\n */\n bridgeTools?: string[];\n };\n\n /**\n * App-level default tool-call limits. Individual actions override these with\n * their own `timeoutMs` / `maxResultChars` declarations.\n */\n toolLimits?: { timeoutMs?: number; maxResultChars?: number };\n}\n\n/**\n * Verbose framework sections returned by the `get-framework-context` tool.\n * Keyed by topic so the agent can request specific sections.\n * Not template-specific — lives outside buildFrameworkPrompts().\n */\nconst FRAMEWORK_CONTEXT_SECTIONS: Record<string, string> = {\n embeds: `### Inline Embeds\n\nYou can embed an interactive view inline in your chat reply by writing an \\`embed\\` fenced code block. The chat renderer swaps the fence for a sandboxed iframe pointing at a route inside this app.\n\nSyntax:\n\n\\`\\`\\`\\`\n\\`\\`\\`embed\nsrc: /some/path?param=value\naspect: 16/9\ntitle: Optional label\n\\`\\`\\`\n\\`\\`\\`\\`\n\nKeys:\n- \\`src\\` (required) — **must be a same-origin path starting with \\`/\\`**. Cross-origin URLs are blocked. No \\`javascript:\\` or \\`data:\\` URLs.\n- \\`aspect\\` (optional) — one of \\`16/9\\` (default), \\`4/3\\`, \\`3/2\\`, \\`2/1\\`, \\`21/9\\`, \\`1/1\\`.\n- \\`title\\` (optional) — accessible label / hover tooltip.\n- \\`height\\` (optional) — fixed pixel height when aspect ratio isn't a good fit.\n\nUse for charts, visualizations, previews. Don't use for simple text/tables or external sites.`,\n\n \"chat-history\": `### Chat History\n\nYou can search and restore previous chat conversations using \\`chat-history\\`:\n- \\`chat-history\\` (action: \"search\") — Search or list past chat threads by keyword\n- \\`chat-history\\` (action: \"open\") — Open a chat thread in the UI as a new tab and focus it\n- \\`chat-history\\` (actions: \"rename\", \"pin\", \"unpin\", \"archive\") — Organize a known chat thread by ID\n\nWhen the user asks to find a previous conversation, use \\`chat-history\\` with action \"search\" first to find matching threads, then action \"open\" to restore the one they want.`,\n\n \"agent-teams\": `### Agent Teams — Orchestration\n\nYou can delegate to background sub-agents with the \\`agent-teams\\` tool:\n- \\`agent-teams\\` (action: \"spawn\") — Launch a sub-agent on a task. It runs in its own thread with a clean context while you stay available; a live preview card appears in the chat. The spawn result confirms launch only, not completion. Optionally pass a custom agent profile from \\`agents/*.md\\` via the \\`agent\\` parameter.\n- \\`agent-teams\\` (action: \"status\") — Check a running sub-agent's progress.\n- \\`agent-teams\\` (action: \"read-result\") — Read a finished sub-agent's output.\n- \\`agent-teams\\` (action: \"send\") — Message a running sub-agent.\n- \\`agent-teams\\` (action: \"list\") — List sub-agent tasks.\n\nSub-agents inherit all of your template tools but **cannot spawn sub-agents themselves** — only you orchestrate.\n\n**User intent phrases.** If the user asks you to use a \"sub-agent\" or \"background agent\", that is explicit delegation intent. Also treat phrases like \"run these in the background\", \"kick off the rest\", \"run the queued items\", \"batch run these jobs\", \"parallelize this\", or \"start the next batch\" as delegation intent when the context is a set of independent work items.\n\n**Spawn is not completion.** A successful \\`spawn\\` call means the sub-agent started and is running. Tell the user it started, show the task id if useful, and then use \\`status\\`/\\`list\\`/\\`read-result\\` to monitor it. Never say the delegated task \"completed\", \"ran successfully\", or \"finished\" until \\`status\\` or \\`read-result\\` reports \\`completed\\` or \\`errored\\`. If a task is still running, say that plainly.\n\n**Default to doing the work yourself in this thread.** A sub-agent costs real tokens and adds a merge step, so reach for one only when delegation clearly pays for that overhead.\n\n**Delegate ONE sub-agent** when a task is self-contained and heavy: deep research, long multi-step content generation, or a noisy scan whose intermediate steps would clutter this thread. The sub-agent gets its own clean context and hands you back a distilled result.\n\n**Fan out to MULTIPLE sub-agents ONLY** for units of work that are genuinely independent and don't depend on each other's decisions — e.g. research three unrelated competitors, summarize five separate threads, draft sections that don't reference one another. Each gets a distinct slice.\n\n**Do NOT parallelize tightly-coupled work** — one cohesive artifact, edits that must agree with each other, or anything needing a single consistent voice or style. Parallel sub-agents can't see each other's choices and their outputs will clash. For coupled work, do it yourself, or chain sub-agents one at a time, feeding each result into the next.\n\n**Cap fan-out:** aim for 1, use up to ~3, and go beyond that only for clearly independent bulk work. More sub-agents means more tokens and a harder merge.\n\n**Briefing contract.** A sub-agent starts in a fresh thread and can only see the brief you give it — it cannot see this conversation or ask you to clarify before it runs. Make every brief self-contained:\n1. **Objective** — what \"done\" looks like, in a sentence or two.\n2. **Context** — the specific facts it needs from this conversation: IDs, names, the user's actual goal, constraints, prior decisions. Paste the specifics; don't assume it knows them.\n3. **Output format** — what to return and how (e.g. \"a 3-bullet summary with source links\", \"the drafted email body only\") so the result drops cleanly into your synthesis.\n4. **Boundaries** — what NOT to do, and for parallel sub-agents, which slice is theirs so they don't overlap.\n\nPut the objective and output format in \\`task\\`; put longer context in \\`instructions\\`.\n\n**Synthesis discipline.** After the sub-agents you depend on finish, poll \\`status\\`/\\`list\\` until they're complete, then pull each one's output with \\`read-result\\`. Do NOT paste their outputs back to back. Read all results, reconcile any disagreements, de-duplicate, and write ONE integrated answer in your own voice. If two sub-agents conflict, resolve it or flag the discrepancy explicitly rather than presenting both. When findings came from distinct investigations, briefly note which finding came from where so the user can trust the merge.`,\n\n \"recurring-jobs\": `### Recurring Jobs\n\nYou can create recurring jobs that run on a cron schedule. Jobs are resource files under \\`jobs/\\`.\n\n- \\`manage-jobs\\` (action: \"create\") — Create a new recurring job with a cron schedule and instructions\n- \\`manage-jobs\\` (action: \"list\") — List all recurring jobs and their status\n- \\`manage-jobs\\` (action: \"update\") — Update a job's schedule, instructions, or toggle enabled/disabled\n- Delete a job with the \\`resources\\` tool: \\`action: \"delete\"\\`, \\`path: \"jobs/<name>.md\"\\`\n\nConvert natural language to 5-field cron format:\n- \"every morning\" / \"daily at 9am\" → \\`0 9 * * *\\`\n- \"every weekday at 9am\" → \\`0 9 * * 1-5\\`\n- \"every hour\" → \\`0 * * * *\\`\n- \"every monday at 9am\" → \\`0 9 * * 1\\`\n\n#### Suggesting \"Save as automation\"\n\nWhen you finish a task that has obvious recurring value — daily inbox triage, weekly metrics summaries, archive sweeps, status digests, anything the user would plausibly want re-run on a fresh cadence — close the response with ONE short line offering to save it. Examples:\n\n- After \"Summarize my unread emails\": _\"Want me to run this every morning?\"_\n- After \"What's our top traffic source this week\": _\"Want a weekly digest on Mondays?\"_\n- After \"Archive emails older than 30 days\": _\"Should I run this every Sunday?\"_\n\nIf the user says yes, call \\`manage-jobs\\` (action: \"create\") with the original prompt as the job's instructions and the cadence they confirmed.\n\nDo NOT add this offer for one-shot work: lookups (find Alice, what's the schema, who reported X), single drafts/replies, navigation requests, or any task whose value is in the moment. Skip it when the prompt is already explicitly recurring (the user said \"every morning…\" — you'd be asking what they already told you). One short sentence at most; do not turn it into a list of cadence options.`,\n\n builder: `### Connecting Builder.io\n\nWhen the user asks to connect Builder.io or you hit a \"Builder not configured\" error, call the \\`connect-builder\\` tool. It renders a one-click Connect card inline — do NOT write out multi-step setup instructions yourself. If Builder Cloud Agents are not available for this workspace, never send the user to Builder org settings or beta settings; use the card's waitlist/local-dev fallback.`,\n\n browser: `### Browser Automation\n\nYou can activate a real Chrome browser via Builder.io for tasks that need full page rendering:\n- Extracting design tokens from JS-heavy or SPA websites (computed styles, rendered colors/fonts)\n- Taking screenshots of live pages\n- Testing interactive flows on deployed URLs\n- Reading content from pages that require JavaScript execution\n\n**How to use:**\n1. In local development, call \\`set-browser-control\\` with \\`{\"enabled\":true,\"backend\":\"chrome-devtools\"}\\` after confirming once with the user. In production, use \\`activate-browser\\` for Builder-provisioned Chrome.\n2. On your next action, use \\`mcp__chrome-devtools__navigate_page\\`, \\`mcp__chrome-devtools__evaluate_script\\`, \\`mcp__chrome-devtools__take_screenshot\\`, etc.\n3. If Builder is not connected, call \\`connect-builder\\` first\n\n**When to recommend browser automation:**\n- User wants to import a design system from a URL (JS-rendered sites give almost no useful data from plain HTML fetch)\n- User asks you to check how a deployed site looks or behaves\n- Any task involving reading computed/rendered page state\n- When \\`web-request\\` returns minimal/skeleton HTML from a modern SPA\n\nPrefer \\`web-request\\` for simple API calls and static pages. Use browser automation when you need the real rendered page.`,\n\n \"call-agent\": `### call-agent — External Apps Only\n\nThe \\`call-agent\\` tool sends a message to a DIFFERENT, separately-deployed app's agent (A2A protocol). It is **not** for calling actions within the current app.\n\n**NEVER use \\`call-agent\\` to:**\n- Call your own app by name\n- Perform tasks you can accomplish with your own registered tools\n\n**ONLY use \\`call-agent\\` when:**\n- The user explicitly asks you to communicate with a different app\n- You need data that only another deployed app can provide\n- You need brand-consistent generated media and this app does not have a native generation action; call agent \"assets\" and keep returned asset IDs and URLs verbatim\n\nIf \\`call-agent\\` says a downstream agent accepted the subtask and will post its result separately, do not call that same agent again for the same subtask. Continue any remaining work and answer with the completed results you have.`,\n\n memory: `### Structured Memory\n\nYour memory index (\\`memory/MEMORY.md\\`) is loaded at the start of every conversation.\n\n**Tools:**\n- \\`save-memory\\` — Create or update a memory (name, type, description, content)\n- \\`delete-memory\\` — Remove a memory and its index entry\n- \\`resources\\` with \\`action: \"read\"\\` and \\`path: \"memory/<name>.md\"\\` — Read the full content of a specific memory\n\n**Memory types:** user, feedback, project, reference\n\n**When to save (proactively):**\n- User corrects your approach → \\`feedback\\`\n- User shares preferences → \\`user\\`\n- Non-obvious pattern or gotcha → \\`feedback\\`\n- Personal context (contacts, team) → \\`user\\`\n- Project context to track → \\`project\\`\n\n**Rules:**\n- Don't save things obvious from code or standard framework behavior\n- When updating, read first and merge — don't overwrite\n- Keep descriptions concise\n- One memory per logical topic`,\n\n \"sql-tools\": `### SQL Tools\n\n- \\`db-schema\\` — refresh the full schema with indexes and foreign keys\n- \\`db-query\\` — run a SELECT (read-only; results already filtered to the current user/org)\n- \\`db-exec\\` — run INSERT / UPDATE / DELETE / REPLACE (writes already scoped; owner_email and org_id are auto-injected on INSERT). For multiple related writes, use \\`statements\\` so they run in one transaction instead of separate tool calls. Schema changes are blocked.\n- \\`db-patch\\` — surgical search-and-replace on a large text column. Use for edits to large fields instead of re-sending multi-kilobyte strings.\n\n### When to pick which SQL tool\n- Set a short column outright, update multiple columns, or do computed updates → \\`db-exec UPDATE\\`\n- Insert/update several rows as one logical operation → \\`db-exec\\` with \\`statements: '[{\"sql\":\"...\",\"args\":[...]}]'\\`\n- Change a small slice of a large text/JSON column → \\`db-patch\\`\n- A template-specific action exists for the table → use that action (it encodes business rules and pushes live Yjs updates)\n- Read data → \\`db-query\\`. Never re-add \\`WHERE owner_email = ...\\` — scoping already applies it.\n\n### External data sources vs the app database\nThe \\`db-*\\` tools ONLY query the app's own SQL database. They do NOT reach external data warehouses. If the user asks about tables NOT in the schema, use the appropriate template action instead.`,\n};\n\n/**\n * Framework-level instructions injected into every agent's system prompt.\n * Prompt text lives in packages/core/src/server/prompts/ so this file stays\n * focused on routing and assembly logic.\n *\n * buildFrameworkPrompts() is called once per plugin instantiation (not per\n * request) with the template's promptExamples, producing the four assembled\n * prompt strings used at request time.\n */\nfunction buildFrameworkPrompts(examples?: PromptExamples): {\n FRAMEWORK_CORE: string;\n FRAMEWORK_CORE_COMPACT: string;\n PROD_FRAMEWORK_PROMPT: string;\n DEV_FRAMEWORK_PROMPT: string;\n PROD_FRAMEWORK_PROMPT_COMPACT: string;\n DEV_FRAMEWORK_PROMPT_COMPACT: string;\n} {\n // Note: FIRST_SESSION_PERSONALIZATION is NOT appended here — it is injected\n // at per-request prompt-assembly time only for new threads (no prior messages).\n // This prevents the ~1.5KB block from appearing on every request forever.\n const FRAMEWORK_CORE = buildFrameworkCore(examples);\n const FRAMEWORK_CORE_COMPACT = buildFrameworkCoreCompact(examples);\n\n const PROD_FRAMEWORK_PROMPT = `## Agent-Native Framework — Production Mode\n\nYou are an AI agent in an agent-native application, running in **production mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.\n\n### Plan Mode\n\nIf the current turn is in Plan mode, plan before anything gets written. This applies to source-code handoffs and to app-created artifacts such as extensions, widgets, dashboards, calculators, mini-apps, documents, designs, slides, or videos. Use only read-only tools, clarify the goal when needed, and return a concrete plan for approval. Do not call \\`create-extension\\`, \\`update-extension\\`, \\`connect-builder\\`, or any action that creates, updates, deletes, sends, publishes, or persists data until the user switches back to Act mode.\n\n### Extensions (Mini-Apps) — Use \\`create-extension\\` for extensions / widgets / dashboards\n\nIn Act mode, if the user asks you to create, build, or make an **extension**, **widget**, **dashboard**, **calculator**, **mini-app**, or any small self-contained interactive utility — call \\`create-extension\\` immediately with a self-contained Alpine.js HTML body. This is **NOT** a code change and does **NOT** go through \\`connect-builder\\`. Extensions are sandboxed mini-apps stored in the database — no source files are touched, no PR is opened, no build is required. The extension appears in the Extensions view and can be edited later via \\`update-extension\\`.\n\nKeep \\`create-extension\\` payloads compact enough to finish quickly. For complex extensions, create a useful working v1 first, then call \\`update-extension\\` with focused edits for refinements instead of trying to assemble one enormous initial tool input.\n\nIf the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \\`<current-screen>\\` or \\`<current-url>\\` when present. Call \\`get-extension\\` only if you need to inspect its content, then \\`update-extension\\` with that id. Use \\`list-extensions\\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes, even when the request says \"change the UI\" or \"fix this\". Do **NOT** call \\`connect-builder\\` for existing extension edits.\n\nIn Act mode, when in doubt — if the request mentions creating an extension, widget, dashboard, calculator, or asks for a new small interactive utility — choose \\`create-extension\\`. If it references an existing one or the current extension page, choose \\`update-extension\\`. Do **not** preface the call with planning text like \"let me build the dashboard…\" — just call the right extension action directly.\n\nNote: \"extension\" is the user-facing primitive (the sandboxed Alpine.js mini-app). Don't confuse it with the LLM concept of \"tools\" (function calls) — those are how you invoke ANY action, including \\`create-extension\\` itself.\n\nFor existing extensions, use \\`get-extension\\` or \\`update-extension\\` directly when \\`<current-screen>\\` or \\`<current-url>\\` provides an \\`extensionId\\`. Use \\`list-extensions\\` only to browse or resolve an unknown name. If the user wants a shared extension removed only from their view, use \\`hide-extension\\` — do not query or mutate the legacy \\`tools\\` table directly.\n\n### Extensions vs. Code Changes — Pick the Right Path\n\nRoute by what the request changes, not how it is phrased. Extensions render in their own sandboxed iframe and CANNOT change the host app's nav, restyle existing components, or replace built-in views.\n\n<routing>\n| The request is for… | Path |\n| ---------------------------------------------------------------- | ----------------------------- |\n| A new self-contained surface (widget, dashboard, calculator, viewer, list, tracker) | \\`create-extension\\` — ships instantly, no PR |\n| Editing an existing extension (fix, restyle, rename, add behavior) | \\`update-extension\\` |\n| The host app's own chrome (nav bar, sidebar, layout, routes, shipped components, existing styles, business logic) | \\`connect-builder\\` — a real source-code change |\n| Ambiguous, satisfiable either way (e.g. \"give me an unread view\") | \\`create-extension\\` (prefer the instant path) |\n</routing>\n\nWorked examples: \"a widget showing unread emails grouped by sender\", \"a dashboard summarizing my pipeline\", \"a tracker for my newsletter subscriptions\" → \\`create-extension\\`. \"Add an Unread tab to the left navigation\", \"make the subject lines wrap\", \"change the inbox grouping logic\", \"add a field to the compose form\" → \\`connect-builder\\`.\n\n### Code Changes Not Available — Call \\`connect-builder\\` Immediately\n\nIf the request matches the Extensions section above, use \\`create-extension\\` or \\`update-extension\\` instead — do NOT route it to \\`connect-builder\\`.\n\nIn Act mode, when the user asks you to change the UI, modify code, add a feature, fix a bug in the app itself, change styles, add a hook, create a component, add a route, add an integration, or anything else that requires editing source files — you MUST take exactly these steps, in order:\n\n1. Briefly acknowledge the user's specific request in their own terms — one short clause naming what they asked for (e.g. \"Got it — wider subject lines in the email list.\"). Do NOT restate the request verbatim, do NOT add a generic preamble, and do NOT promise outcomes. Skip this step entirely if the user already knows you're handing off (e.g. they said \"send this to Builder\").\n2. Call the \\`connect-builder\\` tool, passing the user's full request verbatim as the \\`prompt\\` argument. This renders an inline card. If Builder is connected and \\`builderEnabled\\` is true, the card hands the prompt off to Builder's cloud agent on one click and returns a branch URL. If Builder is not connected, it shows the Connect Builder flow. If \\`builderEnabled\\` is false, it shows a waitlist/local-dev fallback instead of a cloud handoff.\n3. After the card renders, inspect the tool result and write one sentence that frames the next click around what the user just asked — not as a Builder pitch. Examples: \"Click Send to Builder and it'll wire that up for you.\" / \"Connect Builder once and it'll handle this and future changes.\" / \"Builder Cloud Agents aren't available here yet — join the waitlist in the card, or use the Agent Native Desktop app for local code changes: https://www.agent-native.com/download.\" Do NOT say the card is pre-loaded, has everything, or lead with \"Builder Cloud Agents are…\" as if it were the headline.\n\nWhen \\`builderEnabled\\` is false, Builder Cloud Agents are not self-serve from Builder org settings. Do NOT tell the user to go to Builder org settings, beta features, \"Cloud Agents\", or \"AI Agents\" to enable them. The only allowed guidance is the card's waitlist/local-dev fallback: join the waitlist when the card offers it, use Agent Native Desktop, or edit from a local clone.\n\n**Act-mode handoff — do exactly this:** The moment a code change is requested, call \\`connect-builder\\` with the user's verbatim request, then write one sentence framing the next click. That is the whole job: Builder plans and edits in its own sandbox, so the planning, file-mapping, and code all happen there, not here. Keep your turn to the call plus that one sentence — skip code exploration, implementation plans, \\`resources\\` writes of specs, and sub-agents (they have no code-editing tools either). You don't need filesystem access to recommend Builder, so don't reach for it or list tools you lack.\n\nBuilder Cloud Agents are the recommended path when available because they are one-click and run in the cloud. Local dev and the desktop app are the fallback when cloud agent access is waitlisted or unavailable.\n${FRAMEWORK_CORE}`;\n\n const DEV_FRAMEWORK_PROMPT = `## Agent-Native Framework — Development Mode\n\nYou are an AI agent in an agent-native application, running in **development mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In development mode, you have full local access — use it with senior-engineer judgment** (read before you edit, keep changes scoped, verify before you claim done):\n- Run any shell command via the \\`bash\\` tool (node, curl, pnpm, rg, git, etc.), including arbitrary code: \\`bash({ command: 'node -e \"console.log(1+1)\"' })\\`\n- Read and write any file on the filesystem; edit source, install packages, modify the app\n- Query and modify the database\n- Call external APIs (via bash with curl, or via scripts)\n\nWhen no dedicated tool/action exists for what you need, reach for \\`bash\\` — e.g. \\`bash({ command: 'curl -s https://api.example.com/data' })\\`.\n\n**Template-specific actions are invoked via bash, NOT as direct tools.** In dev mode, the only tools registered as native tool calls are framework-level utilities (bash, read, edit, write, database, resources, chat, teams, jobs). Anything from the template's \\`actions/\\` directory must be run through bash: \\`bash({ command: 'pnpm action <name> --arg value' })\\`. The \"Available Actions\" section below shows the exact CLI syntax for each one — copy that command verbatim and pass it to \\`bash\\`. Do not try to call template actions by name as if they were tools; they will not appear in your tool list.\n\nWhen editing code, follow the agent-native architecture:\n- Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync\n- All SQL must be dialect-agnostic (works on SQLite and Postgres)\n- No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)\n- Use shadcn/ui components and Tabler Icons for all UI work\n${FRAMEWORK_CORE}`;\n\n const PROD_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Production Mode\n\nYou are an AI agent in an agent-native application, running in **production mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via your tools, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In production mode, you operate through registered actions exposed as tools.** These are your capabilities — use them to read data, take actions, and help the user. You cannot edit source code or access the filesystem directly. Your tools are the app's API.\n\n### Plan Mode\n\nIf the turn is in Plan mode, plan before anything gets written — including extensions, widgets, dashboards, calculators, mini-apps, documents, designs, slides, videos, and code-change handoffs. Use read-only tools only and do not call \\`create-extension\\`, \\`update-extension\\`, \\`connect-builder\\`, or other write actions until the user switches back to Act mode.\n\n### Extensions (Mini-Apps) — Use \\`create-extension\\`\n\nIn Act mode, if the user asks for an **extension**, **widget**, **dashboard**, **calculator**, or **mini-app**, call \\`create-extension\\` immediately with a self-contained Alpine.js HTML body. This is NOT a code change — extensions are sandboxed mini-apps stored in the database. Do not preface with \"let me build…\" — just call \\`create-extension\\`.\n\nKeep the first \\`create-extension\\` call compact and working. If the request is complex, create the v1 first and then refine with focused \\`update-extension\\` edits.\n\nIf the user asks to change, edit, fix, style, rename, or add behavior to an existing extension/widget/dashboard/calculator/mini-app, use the current extension id from \\`<current-screen>\\` or \\`<current-url>\\` when present. Call \\`get-extension\\` only if you need to inspect its content, then \\`update-extension\\` with that id. Use \\`list-extensions\\` only when no current id/name is available. Existing extension edits are SQL data updates, not source-code changes. Do NOT call \\`connect-builder\\` for them.\n\nFor existing extensions, use \\`get-extension\\` or \\`update-extension\\` directly when \\`<current-screen>\\` or \\`<current-url>\\` provides an \\`extensionId\\`. Use \\`list-extensions\\` only to browse or resolve an unknown name. Use \\`hide-extension\\` when the user wants a shared extension removed only from their own view. Do not query the legacy \\`tools\\` table directly.\n\n### Extensions vs. Code Changes — Pick the Right Path\n\nIf the user wants a **new self-contained surface** (custom widget, dashboard, list, viewer, calculator), use \\`create-extension\\` — extensions ship instantly without a PR. Use \\`connect-builder\\` only when the request **modifies the host app's existing chrome** (nav bar, sidebar, current components, layout, styles, routes). Extensions cannot change the host nav or restyle existing components.\n\n### Code Changes — Call \\`connect-builder\\`\n\nIn Act mode, when a request genuinely needs a source-code edit (per the rules above), do this in order: (1) briefly acknowledge the user's specific ask in their own terms — one short clause, no preamble — then (2) call \\`connect-builder\\` with the user's request as the \\`prompt\\`, then (3) write one sentence framing the next click around what they asked for, not a Builder pitch. Do NOT write code, list files, make plans, or spawn sub-agents. Mention \\`npx agent-native create <app-name>\\`, Agent Native Desktop, or the waitlist card as the fallback when Builder Cloud Agents aren't available. Never tell users to enable Builder Cloud Agents from Builder org settings, beta features, \"Cloud Agents\", or \"AI Agents\"; they are not self-serve there.\n${FRAMEWORK_CORE_COMPACT}`;\n\n const DEV_FRAMEWORK_PROMPT_COMPACT = `## Agent-Native Framework — Development Mode\n\nYou are an AI agent in an agent-native application, running in **development mode**.\n\nThe agent and the UI are equal partners — everything the UI can do, you can do via tools/scripts, and vice versa. They share the same SQL database and stay in sync automatically.\n\n**In development mode, you have full local access** — shell, filesystem, database, external APIs, source edits, and package installs. Use it with senior-engineer judgment: read before you edit, keep changes scoped, verify before you claim done.\n\n**Template-specific actions are invoked via bash, NOT as direct tools.** Run them with: \\`bash({ command: 'pnpm action <name> --arg value' })\\`. See the \"Available Actions\" section below for CLI syntax.\n\nWhen editing code, follow the agent-native architecture:\n- Every feature needs all four areas: UI + scripts + skills/instructions + application-state sync\n- All SQL must be dialect-agnostic (works on SQLite and Postgres)\n- No Node.js-specific APIs in server routes (must work on Cloudflare Workers, etc.)\n- Use shadcn/ui components and Tabler Icons for all UI work\n${FRAMEWORK_CORE_COMPACT}`;\n\n return {\n FRAMEWORK_CORE,\n FRAMEWORK_CORE_COMPACT,\n PROD_FRAMEWORK_PROMPT,\n DEV_FRAMEWORK_PROMPT,\n PROD_FRAMEWORK_PROMPT_COMPACT,\n DEV_FRAMEWORK_PROMPT_COMPACT,\n };\n}\n\nexport const _agentChatPromptSectionsForTests = (() => {\n // Built with default (no template-specific) examples for test stability.\n const {\n FRAMEWORK_CORE: frameworkCore,\n FRAMEWORK_CORE_COMPACT: frameworkCoreCompact,\n } = buildFrameworkPrompts();\n return {\n frameworkCore,\n frameworkCoreCompact,\n frameworkContextSections: FRAMEWORK_CONTEXT_SECTIONS,\n };\n})();\n\n/**\n * Pre-load the agent's context: AGENTS.md (workspace/template/runtime\n * instructions), the skills index, shared LEARNINGS.md (team notes), a shared\n * resource index, and memory/MEMORY.md (personal structured memory index).\n * These all get appended to the system prompt so the agent has everything it\n * needs from the first turn.\n *\n * Six sources are layered:\n *\n * 1. `<workspace>` — AGENTS.md from the enterprise workspace core.\n * 2. `<template>` — AGENTS.md + skills index from the Vite plugin bundle.\n * 3. `<workspace>` — SQL workspace AGENTS.md and instructions/*.md.\n * Runtime global defaults managed from Dispatch and inherited by apps.\n * 4. `<shared>` — SQL shared AGENTS.md and instructions/*.md. App/team/org\n * guidance that can override or narrow workspace defaults.\n * 5. `<shared>` — LEARNINGS.md from the SQL shared scope. Team-level notes.\n * 6. `<personal>` — memory/MEMORY.md from the SQL personal scope. The\n * current user's structured memory index.\n *\n * Each source is read independently — no copying between them. Editing\n * AGENTS.md and restarting the server is all it takes; Vite HMR invalidates\n * the bundle in dev so changes land instantly.\n */\nexport async function loadResourcesForPrompt(\n owner: string,\n compact = false,\n selfAppId?: string,\n): Promise<string> {\n await ensurePersonalDefaults(owner);\n\n const sections: string[] = [];\n const promptResourceMaxChars = compact\n ? COMPACT_PROMPT_RESOURCE_MAX_CHARS\n : SHARED_PROMPT_RESOURCE_MAX_CHARS;\n\n // 1. Workspace AGENTS.md + skills merged into the template bundle.\n try {\n const { loadAgentsBundle, generateSkillsPromptBlock, getRuntimeSkills } =\n await import(\"./agents-bundle.js\");\n const bundle = await loadAgentsBundle();\n\n // Workspace-core AGENTS.md (enterprise-wide instructions), if present.\n if (bundle.workspaceAgentsMd && bundle.workspaceAgentsMd.trim()) {\n const block = promptResourceBlock({\n name: \"AGENTS.md\",\n scope: \"workspace\",\n path: \"AGENTS.md\",\n content: bundle.workspaceAgentsMd,\n maxChars: promptResourceMaxChars,\n readHint:\n 'Use docs-search --slug \"agents-workspace\" to read the full workspace AGENTS.md.',\n });\n if (block) sections.push(block);\n }\n\n // 2. Template AGENTS.md — always included (critical template instructions).\n if (bundle.agentsMd.trim()) {\n const block = promptResourceBlock({\n name: \"AGENTS.md\",\n scope: \"template\",\n path: \"AGENTS.md\",\n content: bundle.agentsMd,\n maxChars: promptResourceMaxChars,\n readHint:\n 'Use docs-search --slug \"agents-template\" to read the full template AGENTS.md.',\n });\n if (block) sections.push(block);\n }\n\n // In compact mode, skip the full skills block — the agent can use\n // `docs-search` to find skills when it needs them. Either way, `scope: dev`\n // skills are excluded: they're for the human's coding agent, not runtime.\n const runtimeSkills = getRuntimeSkills(bundle);\n if (!compact) {\n const skillsBlock = generateSkillsPromptBlock(bundle);\n if (skillsBlock) sections.push(skillsBlock);\n } else if (runtimeSkills.length > 0) {\n const lines = runtimeSkills.map((s) => {\n const description = s.meta.description?.trim()\n ? ` - ${ensureSentence(s.meta.description)}`\n : \"\";\n return `- \\`${s.meta.name}\\`${description} Read with \\`docs-search --slug \"${skillDocsSlug(s.meta.name)}\"\\` before starting a task it applies to.`;\n });\n sections.push(\n `<skills-summary>\\nCodebase skills bundled from \\`.agents/skills/\\` (or legacy \\`.agent/skills/\\`) are available as docs-search pages. Do not use MCP resource reads for these skills.\\n\\n${lines.join(\"\\n\")}\\n</skills-summary>`,\n );\n }\n } catch {}\n\n // 3. Runtime workspace resources. These are global defaults inherited by\n // every app in the workspace, not copied into app scopes. They may come from\n // SQL, Dispatch, or local file mode.\n const workspaceAgents = await loadAgentsResourceForPrompt(\n WORKSPACE_OWNER,\n \"workspace\",\n promptResourceMaxChars,\n );\n if (workspaceAgents) sections.push(workspaceAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n WORKSPACE_OWNER,\n \"workspace-instruction\",\n promptResourceMaxChars,\n )),\n );\n\n // 4. Runtime shared/app/org resources from SQL. These come after workspace\n // defaults so app/team-specific guidance can override or narrow them.\n const sharedAgents = await loadAgentsResourceForPrompt(\n SHARED_OWNER,\n \"shared\",\n promptResourceMaxChars,\n );\n if (sharedAgents) sections.push(sharedAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n SHARED_OWNER,\n \"shared-instruction\",\n promptResourceMaxChars,\n )),\n );\n\n // 5. Personal SQL resources. These come last in the instruction stack so a\n // user can narrow or override organization/app and workspace defaults.\n if (owner !== SHARED_OWNER && owner !== WORKSPACE_OWNER) {\n const personalAgents = await loadAgentsResourceForPrompt(\n owner,\n \"personal\",\n promptResourceMaxChars,\n );\n if (personalAgents) sections.push(personalAgents);\n sections.push(\n ...(await loadInstructionResourcesForPrompt(\n owner,\n \"personal-instruction\",\n promptResourceMaxChars,\n )),\n );\n }\n\n const resourceSkillsBlock = await loadResourceSkillsPromptBlock(owner);\n if (resourceSkillsBlock) sections.push(resourceSkillsBlock);\n\n if (compact) {\n // In compact mode, skip learnings and memory in the prompt.\n // The agent can access them via the resources tool when needed.\n // Add a brief pointer so the agent knows they exist.\n sections.push(\n `<context-note>Shared learnings (LEARNINGS.md) and your personal memory (memory/MEMORY.md) are available via the \\`resources\\` tool with \\`action: \"read\"\\`. Check them when making decisions that might benefit from prior context.</context-note>`,\n );\n } else {\n // LEARNINGS.md from SQL (template-level instructions are in AGENTS.md above).\n // 2. Shared SQL scope\n try {\n const shared = await resourceGetByPath(SHARED_OWNER, \"LEARNINGS.md\");\n if (shared?.content?.trim()) {\n sections.push(\n `<resource name=\"LEARNINGS.md\" scope=\"shared\">\\n${shared.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n\n // 3. Personal memory index (skip if owner is the shared sentinel)\n if (owner !== SHARED_OWNER) {\n try {\n const memoryIndex = await resourceGetByPath(owner, \"memory/MEMORY.md\");\n if (memoryIndex?.content?.trim()) {\n sections.push(\n `<resource name=\"memory/MEMORY.md\" scope=\"personal\">\\n${memoryIndex.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n }\n }\n\n const workspaceResourceIndex = await loadResourceIndexForPrompt(\n WORKSPACE_OWNER,\n \"workspace\",\n );\n if (workspaceResourceIndex) sections.push(workspaceResourceIndex);\n\n const sharedResourceIndex = await loadResourceIndexForPrompt(\n SHARED_OWNER,\n \"shared\",\n );\n if (sharedResourceIndex) sections.push(sharedResourceIndex);\n\n try {\n const agents = (await discoverAgents(selfAppId)).slice(0, 30);\n if (agents.length > 0) {\n const lines = agents.map(\n (agent) =>\n `- ${agent.name} (${agent.id}) — ${agent.description || \"Connected A2A app\"}`,\n );\n sections.push(\n `<available-apps>\\nWorkspace apps available over A2A/call-agent:\\n${lines.join(\"\\n\")}\\n\\nUse \\`call-agent\\` with the app id when another app owns the work or data. Use tool-search or app-specific actions for details only when needed.\\n</available-apps>`,\n );\n }\n } catch {\n // Agent discovery is helpful context, not required for the run.\n }\n\n if (sections.length === 0) return \"\";\n return (\n \"\\n\\nThe following resources contain template-specific instructions and user context. Use the information in them to help the user.\\n\\n\" +\n sections.join(\"\\n\\n\")\n );\n}\n\n/**\n * Build the per-request SQL-schema context block. Reads AGENT_ORG_ID live\n * from the environment so scheduler/A2A/HTTP call sites all see whatever\n * org was just resolved for this request.\n */\nasync function buildSchemaBlock(\n owner: string,\n _legacyHasRawDbTools?: boolean,\n): Promise<string> {\n // db-* tools are always registered (see createDbScriptEntries), in both dev\n // and prod. The legacy boolean is kept for call-site compatibility but\n // ignored — always advertise the tools to the agent.\n try {\n return await loadSchemaPromptBlock({\n owner,\n orgId: getRequestOrgId() ?? null,\n hasRawDbTools: true,\n });\n } catch {\n return \"\";\n }\n}\n\n/**\n * Generates a system prompt section describing registered template actions.\n * This helps the agent prefer template-specific actions over raw db-query/db-exec.\n *\n * Two output modes:\n *\n * - `\"tool\"` — used in production, where template actions are registered\n * as native Anthropic tools. Output reads `name(arg*: type; ...) — desc`.\n * - `\"cli\"` — used in dev, where template actions are NOT registered as\n * native tools and must be invoked via `bash(command=\"pnpm action ...\")`.\n * Output reads `pnpm action name --arg <type> [--opt <type>] — desc`.\n */\nfunction generateActionsPrompt(\n registry: Record<string, ActionEntry>,\n mode: \"cli\" | \"tool\" = \"tool\",\n): string {\n if (!registry || Object.keys(registry).length === 0) return \"\";\n\n const actionEntries = Object.entries(registry);\n\n if (mode === \"tool\") {\n const summaryLines = actionEntries.map(([name, entry]) => {\n const desc = compactPromptLine(\n entry.tool.description,\n MAX_ACTION_SUMMARY_DESCRIPTION_CHARS,\n );\n return `- \\`${name}\\` — ${desc}`;\n });\n\n return `\\n\\n## Available Actions\n\n**Use these actions directly as tool calls.** They handle database access, validation, and business logic internally. The native tool schemas contain the full parameter details.\n\n${summaryLines.join(\"\\n\")}`;\n }\n\n const lines = actionEntries.map(([name, entry]) => {\n const desc = entry.tool.description;\n const params = entry.tool.parameters?.properties;\n const requiredFields = new Set(entry.tool.parameters?.required ?? []);\n\n // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`\n if (!params || Object.keys(params).length === 0) {\n return `- \\`pnpm action ${name}\\` — ${desc}`;\n }\n const entries = Object.entries(params);\n // Required first (alphabetical), then optional (alphabetical)\n entries.sort(([a], [b]) => {\n const ar = requiredFields.has(a) ? 0 : 1;\n const br = requiredFields.has(b) ? 0 : 1;\n if (ar !== br) return ar - br;\n return a.localeCompare(b);\n });\n const required: string[] = [];\n const optional: string[] = [];\n const requiredNames: string[] = [];\n for (const [k, v] of entries) {\n const type = (v as { type?: string }).type ?? \"any\";\n const flag = `--${k} <${type}>`;\n if (requiredFields.has(k)) {\n required.push(flag);\n requiredNames.push(`--${k}`);\n } else {\n optional.push(`[${flag}]`);\n }\n }\n const cmd = [\"pnpm action \" + name, ...required, ...optional].join(\" \");\n const requiredNote =\n requiredNames.length > 0 ? ` Required: ${requiredNames.join(\", \")}.` : \"\";\n return `- \\`${cmd}\\` — ${desc}.${requiredNote}`;\n });\n\n return `\\n\\n## Available Actions\n\n**These template actions are NOT exposed as direct tools in dev mode. To run any of them, use the \\`bash\\` tool with the exact command shown below.** Example: \\`bash(command=\"pnpm action add-slide --deckId abc --content 'Hello'\")\\`.\n\nDo NOT try to call these by name as if they were tools — they will not exist in your tool list. Always go through \\`bash\\`.\n\n${lines.join(\"\\n\")}`;\n}\n\nfunction generateCorpusToolsPrompt(\n registry: Record<string, ActionEntry>,\n): string {\n const hasProviderApi = \"provider-api-request\" in registry;\n const providerDiscoveryTools = [\n \"provider-api-catalog\" in registry ? \"`provider-api-catalog`\" : null,\n \"provider-api-docs\" in registry ? \"`provider-api-docs`\" : null,\n ].filter(Boolean);\n const hasRunCode = \"run-code\" in registry;\n const hasStagedDataset = \"query-staged-dataset\" in registry;\n if (!hasProviderApi && !hasRunCode && !hasStagedDataset) return \"\";\n\n const available = [\n ...providerDiscoveryTools,\n hasProviderApi ? \"`provider-api-request`\" : null,\n hasStagedDataset ? \"`query-staged-dataset`\" : null,\n hasRunCode ? \"`run-code`\" : null,\n ].filter(Boolean);\n\n return `\\n\\n## Broad Provider And Corpus Workflows\n\nAvailable corpus-capable tools: ${available.join(\", \")}.\n\nFor broad provider searches, raw API access, multi-page cohorts, cross-source joins, classification/counting over records, or absence-sensitive answers, do not stop at a bounded shortcut action. Use the provider's broad API/search/list surface, fetch every relevant page or an explicit bounded cohort, stage/save large responses when needed, and reduce the corpus with staged-dataset queries or code execution. In run-code, prefer providerFetchAll() for cursor/page/offset pagination and providerRequest() when response status, headers, or truncation metadata matters. Report source, filters, row counts, pagination/truncation, failed pages, and remaining gaps.`;\n}\n\n/**\n * Creates a Nitro plugin that mounts the agent chat endpoint.\n *\n * In dev mode (NODE_ENV !== \"production\"), automatically includes\n * file system, bash, and database tools alongside any template-specific actions.\n *\n * Usage in templates:\n * ```ts\n * // server/plugins/agent-chat.ts\n * import { readBody, createAgentChatPlugin } from \"@agent-native/core/server\";\n * import { scriptRegistry } from \"../../scripts/registry.js\";\n *\n * export default createAgentChatPlugin({\n * scripts: scriptRegistry,\n * systemPrompt: \"You are an email assistant...\",\n * });\n * ```\n */\nasync function collectFiles(\n dir: string,\n prefix: string,\n depth: number,\n results: Array<{ path: string; name: string; type: \"file\" | \"folder\" }>,\n): Promise<void> {\n if (depth > 4 || results.length >= 500) return;\n const skip = new Set([\n \"node_modules\",\n \".git\",\n \".next\",\n \".output\",\n \"dist\",\n \".cache\",\n \".turbo\",\n \"data\",\n ]);\n let entries: import(\"fs\").Dirent[];\n try {\n const fs = await lazyFs();\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (results.length >= 500) return;\n if (skip.has(entry.name) || entry.name.startsWith(\".\")) continue;\n const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const isDir = entry.isDirectory();\n results.push({\n path: relPath,\n name: entry.name,\n type: isDir ? \"folder\" : \"file\",\n });\n if (isDir)\n await collectFiles(\n nodePath.join(dir, entry.name),\n relPath,\n depth + 1,\n results,\n );\n }\n}\n\nfunction parseSkillFrontmatter(content: string): {\n name?: string;\n description?: string;\n userInvocable?: boolean;\n} {\n const frontmatter = parseFrontmatter(content);\n const userInvocable = getFrontmatterValue(frontmatter, \"user-invocable\");\n return {\n name: getFrontmatterValue(frontmatter, \"name\"),\n description: getFrontmatterValue(frontmatter, \"description\"),\n userInvocable:\n userInvocable === undefined\n ? undefined\n : userInvocable.toLowerCase() === \"true\",\n };\n}\n\nfunction isLocalhost(event: any): boolean {\n try {\n const host =\n event.node?.req?.headers?.host || event.headers?.get?.(\"host\") || \"\";\n const hostname = host.split(\":\")[0];\n return (\n hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\"\n );\n } catch {\n return false;\n }\n}\n\ntype AgentChatRequestSurface = \"app\" | \"dev-frame\" | \"desktop\";\n\nfunction normalizeAgentChatRequestSurface(\n value: string | null | undefined,\n): AgentChatRequestSurface | null {\n const normalized = (value ?? \"\").trim().toLowerCase();\n if (\n normalized === \"app\" ||\n normalized === \"dev-frame\" ||\n normalized === \"desktop\"\n ) {\n return normalized;\n }\n return null;\n}\n\nfunction isBrowserUserAgent(userAgent: string | null | undefined): boolean {\n return /Mozilla\\/|Chrome\\/|Safari\\/|Firefox\\/|Edg\\//i.test(userAgent ?? \"\");\n}\n\nexport function shouldBlockInProductCodeEditingSurface(input: {\n surface?: string | null;\n userAgent?: string | null;\n host?: string | null;\n}): boolean {\n const surface = normalizeAgentChatRequestSurface(input.surface);\n if (surface === \"dev-frame\") return false;\n if (surface === \"desktop\") return false;\n if (surface === \"app\") return true;\n\n // Legacy clients used to send `frame` for any iframe, which includes the\n // app-rendered sidebar inside preview frames. Treat unknown explicit surface\n // values as app-owned so they cannot accidentally receive dev code tools.\n if (input.surface && input.surface.trim()) return true;\n\n const userAgent = input.userAgent ?? \"\";\n if (/AgentNativeDesktop/i.test(userAgent)) return false;\n\n // Missing header from an older browser client. Be conservative for browser\n // UAs on any host, because preview URLs can be non-local while still running\n // a dev-mode app whose in-product chat would be reloaded by source edits.\n if (isBrowserUserAgent(userAgent)) return true;\n\n const host = (input.host ?? \"\").toLowerCase();\n const hostname = host.split(\":\")[0] ?? \"\";\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\"\n );\n}\n\nexport function createAgentChatPlugin(\n options?: AgentChatPluginOptions,\n): NitroPluginDef {\n return (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"agent-chat\");\n // Nitro v3 calls plugins synchronously and doesn't await async return\n // values. We track the async init so the framework's readiness gate\n // holds /_agent-native requests until routes are registered.\n const initPromise = (async () => {\n const { awaitBootstrap } = await import(\"./framework-request-handler.js\");\n await awaitBootstrap(nitroApp);\n\n // Reap phantom runs left over from the previous process (HMR restart,\n // process crash, isolate eviction). Any run whose heartbeat is already\n // stale by startup time had a dead producer; mark it errored so the\n // next /runs/active check returns a terminal status and reconnecting\n // clients don't spin on \"Thinking...\". Runs owned by OTHER live\n // isolates are protected by their fresh heartbeats.\n try {\n const { reapAllStaleRuns } = await import(\"../agent/run-store.js\");\n const reaped = await reapAllStaleRuns();\n if (reaped > 0) {\n console.log(`[agent-chat] reaped ${reaped} stale run(s) on startup`);\n }\n } catch {\n // Best effort — don't block plugin init if SQL isn't ready yet.\n }\n\n const env = process.env.NODE_ENV;\n // AGENT_MODE=production forces production agent constraints even in dev\n const canToggle =\n (env === \"development\" || env === \"test\") &&\n process.env.AGENT_MODE !== \"production\";\n const routePath = options?.path ?? \"/_agent-native/agent-chat\";\n\n // Mutable mode flag — persisted to the `settings` table so a user who\n // toggles to \"Production\" stays in prod mode across server restarts.\n // Hoisted here (before any tool-registry / handler closures are built)\n // so every runtime decision point can close over it and see live changes\n // when the user toggles the Environment dropdown.\n const AGENT_MODE_SETTING_KEY = \"agent-chat.mode\";\n let currentDevMode = canToggle;\n if (canToggle) {\n try {\n const persisted = await getSetting(AGENT_MODE_SETTING_KEY);\n if (persisted && typeof persisted.devMode === \"boolean\") {\n currentDevMode = persisted.devMode;\n }\n } catch {\n // Settings table may not be ready yet — fall back to default.\n }\n }\n // Every closure that picks between dev/prod tools, prompts, or handlers\n // at request time should call this getter instead of reading `canToggle`.\n // `canToggle` means \"this environment allows toggling\" (static); this\n // function means \"the user currently has dev mode ON\" (live).\n const isDevMode = () => currentDevMode;\n\n // Build the four assembled system prompt strings. These are static for the\n // lifetime of this plugin instance — examples come from options once at\n // startup, not per-request.\n const {\n PROD_FRAMEWORK_PROMPT,\n DEV_FRAMEWORK_PROMPT,\n PROD_FRAMEWORK_PROMPT_COMPACT,\n DEV_FRAMEWORK_PROMPT_COMPACT,\n } = buildFrameworkPrompts(options?.promptExamples);\n\n // Initialize MCP client. Merges file/env config + auto-detected binaries\n // + any remote servers users have added through the settings UI (persisted\n // in the settings table, scanned across all scopes so we never drop\n // another user's entries). Graceful-degrade: any failure yields zero MCP\n // tools and agent-chat keeps working as before.\n let mcpConfig = await buildMergedConfig().catch((err) => {\n console.warn(\n `[mcp-client] buildMergedConfig failed: ${err?.message ?? err}`,\n );\n return null;\n });\n if (!mcpConfig) {\n const fileOrEnv = loadMcpConfig() ?? autoDetectMcpConfig();\n mcpConfig = fileOrEnv;\n if (mcpConfig?.source) {\n console.log(\n `[mcp-client] loaded config from ${mcpConfig.source} (${Object.keys(mcpConfig.servers).length} server(s))`,\n );\n } else if (process.env.DEBUG) {\n console.log(\n \"[mcp-client] no configured MCP servers — skipping MCP tools\",\n );\n }\n } else if (mcpConfig.source) {\n console.log(\n `[mcp-client] merged config (${Object.keys(mcpConfig.servers).length} server(s), source: ${mcpConfig.source})`,\n );\n }\n const mcpManager = new McpClientManager(mcpConfig);\n try {\n await mcpManager.start();\n } catch (err: any) {\n console.warn(\n `[mcp-client] start() failed: ${err?.message ?? err}. Continuing without MCP tools.`,\n );\n }\n setGlobalMcpManager(mcpManager);\n const mcpActionEntries = mcpToolsToActionEntries(mcpManager);\n\n // Mount status + management routes so the settings UI can list / add /\n // remove remote MCP servers and hot-reload the running manager.\n mountMcpStatusRoute(nitroApp, mcpManager);\n mountMcpServersRoutes(nitroApp, mcpManager);\n startMcpConfigRefresh(mcpManager);\n // Hub-serve: expose org-scope servers to other agent-native apps in the\n // workspace when `AGENT_NATIVE_MCP_HUB_TOKEN` is set (dispatch, by\n // convention). Gated by the env var so mounting is a no-op otherwise.\n if (isHubServeEnabled()) {\n mountMcpHubRoutes(nitroApp);\n console.log(\n \"[mcp-client] hub serve enabled — other apps can pull org servers via /_agent-native/mcp/hub/servers\",\n );\n }\n const hubStatus = getHubStatus();\n if (hubStatus.consuming) {\n console.log(\n `[mcp-client] hub consume enabled — pulling from ${hubStatus.hubUrl}`,\n );\n }\n mountMcpHubStatusRoute(nitroApp);\n\n // Ensure we tear down child processes if the host shuts down cleanly.\n if (\n typeof process !== \"undefined\" &&\n typeof process.once === \"function\" &&\n !(globalThis as any).__agentNativeMcpExitHooked\n ) {\n (globalThis as any).__agentNativeMcpExitHooked = true;\n const stop = () => {\n const mgr = getGlobalMcpManager();\n // Shutdown is best-effort — a rejection here must not surface as\n // an unhandled promise rejection during process exit.\n if (mgr) mgr.stop().catch(() => {});\n };\n process.once(\"exit\", stop);\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGINT\", stop);\n }\n\n // Resolve actions — prefer explicit `actions`, fall back to deprecated\n // `scripts`. When neither is provided, auto-discover from the filesystem\n // so templates that forget to pass `actions` still work in non-serverless\n // deployments (serverless bundles need explicit imports).\n const rawActions = options?.actions ?? options?.scripts;\n // `*All` holds every discovered action including those that opted out of\n // agent exposure with `agentTool: false`. The agent-facing surfaces below\n // use the `filterAgentTools`-filtered `templateScripts`/`discoveredActions`\n // derived after discovery; `httpActions` keeps the full `*All` sets so\n // agent-hidden actions stay callable from the frontend / HTTP.\n let templateScriptsAll: Record<string, ActionEntry> =\n typeof rawActions === \"function\"\n ? await rawActions()\n : (rawActions ?? {});\n if (!rawActions && Object.keys(templateScriptsAll).length === 0) {\n try {\n const { autoDiscoverActions } = await import(\"./action-discovery.js\");\n templateScriptsAll = await autoDiscoverActions(\"auto\");\n } catch {\n // Filesystem discovery unavailable (serverless bundle) — skip.\n }\n }\n\n // Resource, chat, docs, db, and cross-agent scripts are available in both prod and dev modes\n const resourceScripts = await createResourceScriptEntries();\n const docsScripts = await createDocsScriptEntries();\n const dbScripts = await createDbScriptEntries();\n const refreshScreenTool = createRefreshScreenEntry();\n const frameworkContextTool = createFrameworkContextEntry();\n const leanPrompt = options?.leanPrompt === true;\n const lazyContext = options?.lazyContext !== false && !leanPrompt;\n const urlTools = createUrlTools();\n const engineScripts = await createAgentEngineScriptEntries(\n options?.appId,\n );\n const loopSettingsScripts = await createAgentLoopSettingsScriptEntries();\n const chatScripts = {\n ...(await createChatScriptEntries()),\n ...engineScripts,\n ...loopSettingsScripts,\n };\n const callAgentScript = await createCallAgentScriptEntry(options?.appId);\n const browserTools = createBuilderBrowserTool({\n getOrigin: () =>\n getRequestRunContext()?.requestOrigin ?? \"http://localhost:3000\",\n getOwner: () => getRequestRunContext()?.owner ?? getRequestUserEmail(),\n });\n\n // Auto-mount A2A protocol endpoints so every app is discoverable\n // and callable by other agents via the standard protocol.\n // In dev mode, include dev scripts (filesystem-discovered) so the A2A agent\n // has access to the same tools as the interactive agent.\n let devScriptsForA2A: Record<string, ActionEntry> = {};\n let discoveredActionsAll: Record<string, ActionEntry> = {};\n if (canToggle) {\n try {\n const { createDevScriptRegistry } =\n await import(\"../scripts/dev/index.js\");\n devScriptsForA2A = await createDevScriptRegistry();\n } catch {}\n\n // Auto-discover template action files and register as bash-based tools.\n // This ensures templates without a custom agent-chat plugin (e.g., analytics)\n // still have their domain actions available as tools.\n try {\n const pathMod = await import(\"path\");\n const cwd = process.cwd();\n const skipFiles = new Set([\n \"helpers\",\n \"run\",\n \"registry\",\n \"_utils\",\n \"db-connect\",\n \"db-status\",\n ]);\n\n for (const dir of [\"actions\", \"scripts\"]) {\n const actionsDir = pathMod.join(cwd, dir);\n const _fs = await lazyFs();\n if (!_fs.existsSync(actionsDir)) continue;\n const files = _fs\n .readdirSync(actionsDir)\n .filter(\n (f: string) =>\n f.endsWith(\".ts\") &&\n !f.startsWith(\"_\") &&\n !skipFiles.has(f.replace(/\\.ts$/, \"\")),\n );\n for (const file of files) {\n const name = file.replace(/\\.ts$/, \"\");\n if (templateScriptsAll[name] || devScriptsForA2A[name]) continue;\n\n // Try to load the action module directly so we get the real\n // run function (not a shell wrapper). This makes HTTP endpoints\n // work correctly. Only fall back to shell wrapper if the import\n // fails (e.g., CLI-style scripts that throw at top level).\n const filePath = pathMod.join(actionsDir, file);\n try {\n const mod = await import(/* @vite-ignore */ filePath);\n const def =\n mod.default && typeof mod.default === \"object\"\n ? mod.default\n : mod;\n if (def?.tool && typeof def.run === \"function\") {\n discoveredActionsAll[name] = {\n tool: def.tool,\n run: def.run,\n ...(def.http !== undefined ? { http: def.http } : {}),\n ...(typeof def.agentTool === \"boolean\"\n ? { agentTool: def.agentTool }\n : {}),\n };\n continue;\n }\n } catch {\n // Fall through to shell wrapper for CLI-style scripts\n // (and .ts files Node can't parse natively).\n }\n\n // Static-parse the source for `http: false` or\n // `http: { method: \"GET\" }` so the shell-wrapper fallback still\n // mounts HTTP routes with the correct method. We can't load the\n // .ts module to read the real defineAction object in this Node\n // context, so this regex sniff is the best we can do until the\n // discovery is moved into a Vite-aware codepath.\n let httpConfig: ActionHttpConfig | false | undefined;\n // Sniff `agentTool: false` the same way so a CLI-style action can\n // opt out of agent exposure even on the shell-wrapper fallback path.\n let agentToolFlag: boolean | undefined;\n try {\n const src = _fs.readFileSync(filePath, \"utf-8\");\n if (/\\bagentTool\\s*:\\s*false\\b/.test(src)) {\n agentToolFlag = false;\n }\n if (/\\bhttp\\s*:\\s*false\\b/.test(src)) {\n httpConfig = false;\n } else {\n const httpStart = src.search(/\\bhttp\\s*:\\s*\\{/);\n if (httpStart >= 0) {\n const window = src.slice(httpStart, httpStart + 200);\n const m = window.match(\n /method\\s*:\\s*['\"`](GET|POST|PUT|DELETE)['\"`]/,\n );\n const p = window.match(/path\\s*:\\s*['\"`]([^'\"`]+)['\"`]/);\n if (m || p) {\n httpConfig = {\n ...(m\n ? {\n method: m[1] as \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n }\n : {}),\n ...(p ? { path: p[1] } : {}),\n };\n }\n }\n }\n } catch {\n // File read failed — leave httpConfig undefined (default POST)\n }\n\n // Fallback: bash-based wrapper for CLI-style scripts\n discoveredActionsAll[name] = {\n tool: {\n description: `Run the ${name} action. Use: pnpm action ${name} --arg=value`,\n parameters: {\n type: \"object\",\n properties: {\n args: {\n type: \"string\",\n description:\n \"CLI arguments as a string (e.g., --metrics=sessions --days=7)\",\n },\n },\n },\n },\n run: async (input: Record<string, string>) => {\n const bashEntry =\n devScriptsForA2A.bash ?? devScriptsForA2A.shell;\n if (!bashEntry) return \"Error: bash not available\";\n return bashEntry.run({\n command: `pnpm action ${name} ${input.args || \"\"}`.trim(),\n });\n },\n ...(httpConfig !== undefined ? { http: httpConfig } : {}),\n ...(typeof agentToolFlag === \"boolean\"\n ? { agentTool: agentToolFlag }\n : {}),\n };\n }\n }\n if (Object.keys(discoveredActionsAll).length > 0 && process.env.DEBUG)\n console.log(\n `[agent-chat] Auto-discovered ${Object.keys(discoveredActionsAll).length} action(s): ${Object.keys(discoveredActionsAll).join(\", \")}`,\n );\n } catch {}\n }\n\n // Agent-facing views of the discovered actions: actions that opted out of\n // agent exposure with `agentTool: false` are dropped from every tool\n // surface, prompt, MCP/A2A list, and job/trigger runner below. The full\n // `*All` sets are reserved for `httpActions`, which keeps agent-hidden\n // actions reachable from the frontend / HTTP.\n const templateScripts = filterAgentTools(templateScriptsAll);\n const discoveredActions = filterAgentTools(discoveredActionsAll);\n // Per-request owner is read from the AsyncLocalStorage run context\n // (populated by prepareRun). Module-scope `let` would race across\n // concurrent requests on a long-lived Node process — overlapping\n // tool calls would observe whichever request wrote last. ALS gives\n // each async call-chain its own view of the owner.\n //\n // Falls back to `getRequestUserEmail()` so callers that wrap work\n // in `runWithRequestContext({ userEmail }, …)` without going through\n // `prepareRun` (recurring jobs, trigger dispatcher) still see the\n // correct owner.\n //\n // SECURITY: returns `null` when neither the run context nor the\n // request user-email is populated. Consumers MUST short-circuit\n // with an explicit error rather than fall back to a sentinel\n // identity (e.g. DEV_MODE_USER_EMAIL). The previous fallback to\n // `local@localhost` slipped past `guard-no-localhost-fallback`\n // because the literal was hidden behind a symbolic alias —\n // any agent loop that reached this code without a populated\n // session would resolve `${keys.NAME}` against the dev-shim's\n // `app_secrets WHERE scope_id='local@localhost'` rows. See\n // audit 02 (HIGH: getCurrentRunOwner) and the\n // 2026-04-29 credentials-leak incident for the prior shape.\n const getCurrentRunOwner = (): string | null =>\n getRequestRunContext()?.owner ?? getRequestUserEmail() ?? null;\n const requireCurrentRunOwner = (operation: string): string => {\n const owner = getCurrentRunOwner();\n if (!owner) {\n throw new Error(\n `[agent-chat] No authenticated owner in run context — ` +\n `refusing to ${operation}. Ensure the request goes through ` +\n `prepareRun() or is wrapped in runWithRequestContext({ userEmail, ... }).`,\n );\n }\n return owner;\n };\n\n // Automation tools + fetch tool — depend on owner via callback.\n // Each callback short-circuits with a clear error when the run context\n // has no authenticated owner (see SECURITY note on getCurrentRunOwner).\n let automationTools: Record<string, ActionEntry> = {};\n try {\n const { createAutomationToolEntries } =\n await import(\"../triggers/actions.js\");\n automationTools = createAutomationToolEntries(() =>\n requireCurrentRunOwner(\"manage automations\"),\n );\n } catch {}\n let notificationTools: Record<string, ActionEntry> = {};\n try {\n const { createNotificationToolEntries } =\n await import(\"../notifications/actions.js\");\n notificationTools = createNotificationToolEntries(() =>\n requireCurrentRunOwner(\"manage notifications\"),\n );\n } catch {}\n let progressTools: Record<string, ActionEntry> = {};\n try {\n const { createProgressToolEntries } =\n await import(\"../progress/actions.js\");\n progressTools = createProgressToolEntries(() =>\n requireCurrentRunOwner(\"manage progress\"),\n );\n } catch {}\n let fetchTool: Record<string, ActionEntry> = {};\n try {\n const { createFetchToolEntry } =\n await import(\"../extensions/fetch-tool.js\");\n const { resolveKeyReferences, validateUrlAllowlist, getKeyAllowlist } =\n await import(\"../secrets/substitution.js\");\n fetchTool = createFetchToolEntry({\n resolveKeys: async (text) =>\n resolveKeyReferences(\n text,\n \"user\",\n requireCurrentRunOwner(\"resolve key references\"),\n ),\n validateUrl: async (url, usedKeys) => {\n for (const keyName of usedKeys) {\n const allowlist = await getKeyAllowlist(\n keyName,\n \"user\",\n requireCurrentRunOwner(\"validate URL allowlist\"),\n );\n if (allowlist && !validateUrlAllowlist(url, allowlist)) {\n return false;\n }\n }\n return true;\n },\n });\n } catch {}\n let webSearchTool: Record<string, ActionEntry> = {};\n try {\n const { createWebSearchToolEntry } =\n await import(\"../extensions/web-search-tool.js\");\n const {\n getBuilderWebSearchBaseUrl,\n resolveBuilderCredentials,\n resolveSecret,\n } = await import(\"./credential-provider.js\");\n const { getBuilderGatewayRequestHeaders } =\n await import(\"../agent/engine/builder-gateway-headers.js\");\n webSearchTool = createWebSearchToolEntry({\n resolveSecret,\n resolveBuilderCredentials,\n getBuilderWebSearchBaseUrl,\n getBuilderRequestHeaders: getBuilderGatewayRequestHeaders,\n });\n } catch {}\n let workspaceFilesTool: Record<string, ActionEntry> = {};\n try {\n const { createWorkspaceFilesTool } =\n await import(\"../workspace-files/tool.js\");\n workspaceFilesTool = createWorkspaceFilesTool();\n } catch {}\n let toolActions: Record<string, ActionEntry> = {};\n try {\n const { createExtensionActionEntries } =\n await import(\"../extensions/actions.js\");\n toolActions = createExtensionActionEntries();\n } catch {}\n let browserSessionTools: Record<string, ActionEntry> = {};\n try {\n const { createBrowserSessionActionEntries } =\n await import(\"../browser-sessions/actions.js\");\n browserSessionTools = createBrowserSessionActionEntries({\n getOwnerEmail: () => requireCurrentRunOwner(\"use browser sessions\"),\n });\n } catch {}\n\n // Core send-email tool — only registered when RESEND_API_KEY or\n // SENDGRID_API_KEY is set. Keyed \"core-send-email\" to avoid colliding\n // with the mail template's richer \"send-email\" action (template wins\n // when both surfaces spread into the same object, but distinct keys\n // keep both visible and avoid silent shadowing).\n let coreEmailTools: Record<string, ActionEntry> = {};\n try {\n const { createCoreEmailActionEntries } =\n await import(\"./email-actions.js\");\n coreEmailTools = createCoreEmailActionEntries();\n } catch {}\n\n // Core read-attachment tool — always registered so the agent can page\n // through large text/CSV/code attachments that were truncated in context.\n let coreAttachmentTools: Record<string, ActionEntry> = {};\n try {\n const { createCoreAttachmentActionEntries } =\n await import(\"./attachment-actions.js\");\n coreAttachmentTools = createCoreAttachmentActionEntries();\n } catch {}\n\n // -----------------------------------------------------------------------\n // Production code-execution mode resolution.\n //\n // Priority (highest -> lowest):\n // 1. AGENT_PROD_CODE_EXECUTION env var (\"trusted\" | \"sandboxed\" | \"off\")\n // 2. options.codeExecution.production\n // 3. Default: \"off\"\n //\n // Dev mode ignores this entirely: dev always gets the run-code sandbox.\n // Build these tools before A2A/MCP registries so every agent-loop surface\n // has the same code execution capability when enabled.\n // -----------------------------------------------------------------------\n const rawEnvCodeExec = (process.env.AGENT_PROD_CODE_EXECUTION ?? \"\")\n .toLowerCase()\n .trim();\n const resolvedProdCodeExec: \"off\" | \"sandboxed\" | \"trusted\" =\n rawEnvCodeExec === \"trusted\"\n ? \"trusted\"\n : rawEnvCodeExec === \"sandboxed\"\n ? \"sandboxed\"\n : rawEnvCodeExec === \"off\"\n ? \"off\"\n : (options?.codeExecution?.production ?? \"off\");\n\n // Forward-declaration for the production run-code bridge supplier.\n // Must come before createRunCodeEntry so the closure can capture it.\n let prodRunCodeToolActions: Record<string, ActionEntry> = {};\n let leanRunCodeToolActions: Record<string, ActionEntry> = {};\n\n // Sandboxed run-code tool: available in \"sandboxed\" or \"trusted\" prod\n // modes and always in dev mode.\n const runCodeTool: Record<string, ActionEntry> = {};\n const leanRunCodeTool: Record<string, ActionEntry> = {};\n try {\n const { createRunCodeEntry } =\n await import(\"../coding-tools/run-code.js\");\n runCodeTool[\"run-code\"] = createRunCodeEntry(\n // Supplier is evaluated at invocation time so runtime additions to\n // prodActions (e.g. MCP sync) are visible to the bridge.\n () => prodRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n leanRunCodeTool[\"run-code\"] = createRunCodeEntry(\n // Lean prompt mode intentionally exposes a much smaller action\n // surface; keep sandbox appAction() calls scoped to that same surface.\n () => leanRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n } catch {\n // Module unavailable (e.g. bundled browser build) — skip silently.\n }\n\n // Full coding tool registry (bash/read/edit/write) for \"trusted\" prod.\n // In dev mode this is handled separately via devHandler below.\n const prodCodingTools: Record<string, ActionEntry> = {};\n if (resolvedProdCodeExec === \"trusted\" && !canToggle) {\n try {\n const { createCodingToolRegistry } =\n await import(\"../coding-tools/index.js\");\n const codingRegistry = createCodingToolRegistry({\n cwd: process.cwd(),\n beforeBash: async ({ command: _command }) => {\n // In plan mode the agent loop blocks via isPlanModeToolCallAllowed;\n // this hook is a belt-and-suspenders guard inside trusted production.\n return null;\n },\n });\n Object.assign(prodCodingTools, codingRegistry);\n } catch {\n // Coding tools unavailable — skip silently.\n }\n }\n\n // Forward-declaration: populated after devActions is assembled below.\n // Must be declared before devRunCodeTool so the closure can close over it.\n let devRunCodeToolActions: Record<string, ActionEntry> = {};\n\n // Always register run-code in dev mode (when the coding module loads).\n const devRunCodeTool: Record<string, ActionEntry> = {};\n if (canToggle) {\n try {\n const { createRunCodeEntry } =\n await import(\"../coding-tools/run-code.js\");\n // devActions is not yet defined at this point; we use a late-binding\n // supplier so devRunCodeTool can reference the devActions registry\n // once it is built below (see devHandler block).\n devRunCodeTool[\"run-code\"] = createRunCodeEntry(\n () => devRunCodeToolActions,\n { bridgeTools: options?.codeExecution?.bridgeTools },\n );\n } catch {}\n }\n\n const resolveExtraContext = async (\n event: any,\n owner: string,\n ): Promise<string> => {\n if (!options?.extraContext) return \"\";\n try {\n const extra = await options.extraContext(event, owner);\n return extra ? `\\n\\n${extra}` : \"\";\n } catch (err) {\n console.warn(\n \"[agent-chat] extraContext threw:\",\n err instanceof Error ? err.message : err,\n );\n return \"\";\n }\n };\n\n // In dev mode, template actions (templateScripts and discoveredActions) are\n // NOT registered as native tools — the agent invokes them via bash instead.\n // This avoids degenerate empty-object tool calls that Anthropic models\n // sometimes emit for actions with complex schemas. Production keeps the\n // native registration since it has no shell access.\n const allScripts = attachToolSearch(\n canToggle\n ? {\n ...filterPublicAgentActions(templateScripts),\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...discoveredActions,\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n // Full (\"production\") MCP surface served to an authenticated *real\n // caller* — a connect-minted token, an `agent-native mcp install` stdio\n // proxy, or a deployed / AGENT_MODE=production app — even in local dev.\n // `allScripts` above is intentionally the sparse, dev-toggled surface\n // (builtins + read-only public-agent actions) used by the local agent\n // chat and unauthenticated dev probes; per the external-agents contract\n // a caller that connected with a token MUST get the full surface (so\n // `create-document` etc. are callable over MCP). Only needed when\n // `canToggle` (dev/test): in production `allScripts` already IS this\n // composition, so leave it undefined and `mountMCP` skips the swap.\n const mcpFullActions = canToggle\n ? attachToolSearch({\n ...discoveredActions,\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n })\n : undefined;\n\n const { mountA2A } = await import(\"../a2a/server.js\");\n mountA2A(nitroApp, {\n name: options?.appId\n ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)\n : \"Agent\",\n description: `Agent-native ${options?.appId ?? \"app\"} agent`,\n skills: buildPublicAgentA2ASkills(allScripts),\n publicSkillsOnly: true,\n streaming: true,\n handler: async function* (message, context) {\n // Resolve the caller's identity for user-scoped data access.\n // Priority: A2A-JWT verified email (set by the A2A handler in\n // request-context) > dev session DB (dev only) > Google OAuth\n // tokeninfo (prod only). Without the JWT-verified-email path,\n // cross-app A2A calls landed owned by `local@localhost` (dev) or\n // `dispatch@shared`, which made resources invisible to the actual\n // signed-in user.\n //\n // SECURITY: we deliberately do NOT trust `context.metadata.userEmail`\n // as a fallback. The A2A endpoint runs in three modes — JWT-signed\n // (verified email lands in request context), API-key (caller is\n // app-authenticated but NOT user-authenticated), and unsigned\n // (no auth at all). Trusting caller-supplied metadata on the latter\n // two paths would let any reachable caller forge `metadata.userEmail`\n // and impersonate an arbitrary user. The JWT path already populates\n // the request context, so the metadata fallback was only ever used\n // on the unauthenticated paths — exactly where it's unsafe.\n const isDev = process.env.NODE_ENV !== \"production\";\n let userEmail: string | undefined;\n\n // 1. JWT-verified email from A2A receiver (auth boundary already\n // enforced upstream). Works in dev AND prod.\n try {\n const { getRequestUserEmail } =\n await import(\"./request-context.js\");\n userEmail = getRequestUserEmail();\n } catch {}\n\n // Dev-mode-only: when no JWT-verified email is present, fall back\n // to the most recently logged-in session. This is convenient for a\n // single-developer dev box but is a silent-impersonation hole if\n // it ever fires in production or on an exposed dev environment\n // (preview deploys, ngrok tunnels, etc.).\n //\n // SECURITY: gate this fallback narrowly:\n // - NODE_ENV strictly === \"development\" (not \"test\", not unset).\n // - AUTH_MODE === \"local\" (the dev-only auth shim).\n // - Request host is localhost / 127.0.0.1 (best-effort: when the\n // A2A handler doesn't have direct H3 event access, we rely on\n // env-based shape checks).\n //\n // In production this MUST never fire — the runtime assertion\n // below crashes loud if NODE_ENV === \"production\" somehow reaches\n // this block.\n if (!userEmail && isDev) {\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(\n \"[agent-chat] Dev-mode 'latest session' fallback reached in production — refusing.\",\n );\n }\n const strictlyDev = process.env.NODE_ENV === \"development\";\n const localAuthMode = process.env.AUTH_MODE === \"local\";\n // Request host check: rely on the request-context request origin\n // which prepareRun() / mountActionRoutes populate. The A2A\n // handler doesn't have direct H3 event access, but on a\n // misconfigured non-localhost dev box we still want to refuse.\n let isLocalHost = false;\n try {\n const origin = getRequestRunContext()?.requestOrigin;\n if (origin) {\n const url = new URL(origin);\n isLocalHost =\n url.hostname === \"localhost\" ||\n url.hostname === \"127.0.0.1\" ||\n url.hostname === \"::1\";\n } else {\n // No origin in context — the A2A handler runs without an\n // explicit request origin. Treat absence as permissive only\n // when we're confident the process is dev-only (NODE_ENV\n // strictly \"development\" + AUTH_MODE=local). Otherwise\n // refuse.\n isLocalHost = strictlyDev && localAuthMode;\n }\n } catch {\n isLocalHost = false;\n }\n if (strictlyDev && localAuthMode && isLocalHost) {\n try {\n const { getDbExec } = await import(\"../db/client.js\");\n const db = getDbExec();\n const { rows } = await db.execute({\n sql: \"SELECT email FROM sessions ORDER BY created_at DESC LIMIT 1\",\n args: [],\n });\n if (rows[0]) userEmail = rows[0].email as string;\n } catch {}\n }\n }\n\n if (!userEmail && !isDev) {\n const googleToken = context.metadata?.googleToken as string;\n if (googleToken) {\n try {\n const res = await fetch(\n `https://oauth2.googleapis.com/tokeninfo?access_token=${encodeURIComponent(googleToken)}`,\n );\n if (res.ok) {\n const info = (await res.json()) as {\n email?: string;\n email_verified?: string;\n };\n if (info.email && info.email_verified === \"true\") {\n userEmail = info.email;\n }\n }\n } catch {}\n }\n }\n\n const text = message.parts\n .filter(\n (p): p is { type: \"text\"; text: string } => p.type === \"text\",\n )\n .map((p) => p.text)\n .join(\"\\n\");\n\n if (!text) {\n yield {\n role: \"agent\" as const,\n parts: [\n { type: \"text\" as const, text: \"No text content in message\" },\n ],\n };\n return;\n }\n\n if (!userEmail) throw new Error(\"no authenticated user\");\n\n const fallbackResponse = await options?.a2aMessageFallback?.({\n message,\n text,\n context,\n userEmail,\n });\n if (fallbackResponse) {\n yield typeof fallbackResponse === \"string\"\n ? {\n role: \"agent\" as const,\n parts: [{ type: \"text\" as const, text: fallbackResponse }],\n }\n : fallbackResponse;\n return;\n }\n\n // Use the SAME agent setup as the interactive chat — identical tools,\n // prompt, and capabilities. The A2A agent IS the app's agent.\n const a2aEngine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: options?.apiKey,\n appId: options?.appId,\n });\n\n const devActive = isDevMode();\n\n // Build the same system prompt the interactive agent uses\n const owner = userEmail;\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, devActive);\n const extra = await resolveExtraContext(context.event, owner);\n const runtimeContext = runtimeContextForEvent(context.event);\n const systemPrompt = devActive\n ? devPrompt + runtimeContext + resources + schemaBlock + extra\n : basePrompt + runtimeContext + resources + schemaBlock + extra;\n\n const a2aModelCandidate =\n options?.model ??\n (await getStoredModelForEngine(a2aEngine, {\n appId: options?.appId,\n })) ??\n a2aEngine.defaultModel;\n const model = normalizeModelForEngine(a2aEngine, a2aModelCandidate);\n\n // Build tools — same as interactive handler but WITHOUT call-agent\n // to prevent infinite recursive A2A loops (agent calling itself).\n // In dev mode, template actions are invoked via bash (not native tools),\n // so they're omitted from the tool registry — see allScripts comment.\n const a2aActions = attachToolSearch(\n devActive\n ? {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n const a2aTools = actionsToEngineTools(a2aActions);\n\n const a2aMessages: EngineMessage[] = [\n { role: \"user\", content: [{ type: \"text\", text }] },\n ];\n\n // Run the SAME agent loop, then extract the final answer from the\n // event stream so pre-tool narration never leaks as the A2A result.\n const a2aEvents: AgentChatEvent[] = [];\n const a2aToolResults: Array<{ tool: string; result: string }> = [];\n let lastRecoverableArtifactText = \"\";\n const controller = new AbortController();\n\n console.log(\n `[A2A] Starting agent loop: ${a2aTools.length} tools, prompt ${systemPrompt.length} chars`,\n );\n\n await runAgentLoopDirectWithSoftTimeout(\n {\n engine: a2aEngine,\n model,\n systemPrompt,\n tools: a2aTools,\n messages: a2aMessages,\n actions: a2aActions,\n send: (event) => {\n a2aEvents.push(event);\n if (event.type === \"tool_start\") {\n console.log(`[A2A] Tool call: ${event.tool}`);\n } else if (event.type === \"tool_done\") {\n a2aToolResults.push({\n tool: event.tool,\n result: event.result,\n });\n const recoverableArtifactText =\n buildA2ARecoverableArtifactMessage(a2aToolResults, {\n baseUrl: resolveArtifactBaseUrl(context.event),\n });\n if (\n recoverableArtifactText &&\n recoverableArtifactText !== lastRecoverableArtifactText\n ) {\n lastRecoverableArtifactText = recoverableArtifactText;\n updateTaskStatusMessage(context.taskId, {\n role: \"agent\",\n metadata: { agentNativeRecoverableArtifacts: true },\n parts: [\n {\n type: \"text\",\n text: recoverableArtifactText,\n },\n ],\n }).catch((err) => {\n console.error(\n `[A2A] Failed to persist recoverable artifact message for task ${context.taskId}:`,\n err,\n );\n });\n }\n } else if (event.type === \"error\") {\n console.error(`[A2A] Error: ${event.error}`);\n } else if (event.type === \"done\") {\n console.log(`[A2A] Done. Events: ${a2aEvents.length}`);\n }\n },\n signal: controller.signal,\n },\n options?.runSoftTimeoutMs,\n );\n\n const { responseText, finalText } = assembleA2AFinalResponse(\n a2aEvents,\n a2aToolResults,\n { event: context.event },\n );\n\n console.log(\n `[A2A] Loop complete. Text: ${responseText.slice(0, 100)}...`,\n );\n\n // Yield the final accumulated text\n yield {\n role: \"agent\" as const,\n parts: [\n {\n type: \"text\" as const,\n text: finalText || \"(no response)\",\n },\n ],\n };\n },\n });\n\n // Generate an \"Available Actions\" section from template-specific actions\n // so the agent knows to use them instead of raw SQL.\n //\n // Production: actions are native tools — emit `name(arg*: type) — desc`\n // Dev: actions are invoked via bash — emit `pnpm action name --arg <type>`\n // and include discoveredActions too, since those are also missing\n // from the dev tool registry.\n const corpusToolsPrompt = generateCorpusToolsPrompt({\n ...templateScripts,\n ...(canToggle\n ? devRunCodeTool\n : resolvedProdCodeExec !== \"off\"\n ? runCodeTool\n : {}),\n });\n const prodActionsPrompt =\n generateActionsPrompt(templateScripts, \"tool\") + corpusToolsPrompt;\n const devActionsPrompt =\n generateActionsPrompt(\n { ...discoveredActions, ...templateScripts },\n \"cli\",\n ) + corpusToolsPrompt;\n\n // Build system prompts — dynamic functions that pre-load resources per-request.\n // Production gets PROD_FRAMEWORK_PROMPT, dev gets DEV_FRAMEWORK_PROMPT.\n // Custom systemPrompt from options overrides the framework default entirely.\n const prodPrompt =\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT)) + prodActionsPrompt;\n // When template actions are registered as native tools in dev (via\n // `nativeActionsInDev` or `leanPrompt`), the dev prompt's \"invoke\n // template actions via bash\" guidance is wrong — use the prod prompt\n // + tool-format action list instead, same as production.\n const devNative = options?.nativeActionsInDev === true || leanPrompt;\n const devPrompt = devNative\n ? prodPrompt\n : (options?.devSystemPrompt\n ? options.devSystemPrompt +\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT))\n : lazyContext\n ? DEV_FRAMEWORK_PROMPT_COMPACT\n : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;\n // Keep legacy names for the composition below\n const basePrompt = prodPrompt;\n\n // Mount MCP remote server — same action registry as A2A + agent chat\n const { mountMCP } = await import(\"../mcp/server.js\");\n mountMCP(nitroApp, {\n name: options?.appId\n ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)\n : \"Agent\",\n title: options?.mcpServerInfo?.title,\n appId: options?.appId,\n description:\n options?.mcpServerInfo?.description ??\n `Agent-native ${options?.appId ?? \"app\"} agent`,\n websiteUrl: options?.mcpServerInfo?.websiteUrl,\n icons: options?.mcpServerInfo?.icons,\n actions: allScripts,\n productionActions: mcpFullActions,\n ...(options?.connectorCatalog\n ? { connectorCatalog: options.connectorCatalog }\n : {}),\n askAgent: async (message: string) => {\n const mcpEngine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: options?.apiKey,\n appId: options?.appId,\n });\n const mcpModelCandidate =\n options?.model ??\n (await getStoredModelForEngine(mcpEngine, {\n appId: options?.appId,\n })) ??\n mcpEngine.defaultModel;\n const model = normalizeModelForEngine(mcpEngine, mcpModelCandidate);\n\n // Same actions as A2A — without call-agent to prevent loops.\n // In dev mode, template actions go through bash, not native tools.\n const devActiveMcp = isDevMode();\n const mcpActions = attachToolSearch(\n devActiveMcp\n ? {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...mcpActionEntries,\n ...devScriptsForA2A,\n ...devRunCodeTool,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...mcpActionEntries,\n ...(resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n ...prodCodingTools,\n },\n );\n\n const mcpTools = actionsToEngineTools(mcpActions);\n\n const resources = await loadResourcesForPrompt(\n SHARED_OWNER,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(SHARED_OWNER, devActiveMcp);\n // Build the MCP handler's own prompt — always use the bash-based\n // dev prompt in dev mode because mcpActions routes template actions\n // through bash (`devScriptsForA2A`), regardless of `nativeActionsInDev`.\n const mcpDevPrompt =\n (options?.devSystemPrompt\n ? options.devSystemPrompt +\n (options?.systemPrompt ??\n (lazyContext\n ? PROD_FRAMEWORK_PROMPT_COMPACT\n : PROD_FRAMEWORK_PROMPT))\n : lazyContext\n ? DEV_FRAMEWORK_PROMPT_COMPACT\n : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;\n const systemPrompt = devActiveMcp\n ? mcpDevPrompt +\n buildRuntimeContextPrompt() +\n resources +\n schemaBlock\n : basePrompt +\n buildRuntimeContextPrompt() +\n resources +\n schemaBlock;\n\n let accumulatedText = \"\";\n const controller = new AbortController();\n\n await runAgentLoopDirectWithSoftTimeout(\n {\n engine: mcpEngine,\n model,\n systemPrompt,\n tools: mcpTools,\n messages: [\n { role: \"user\", content: [{ type: \"text\", text: message }] },\n ],\n actions: mcpActions,\n send: (event) => {\n if (event.type === \"text\") accumulatedText += event.text;\n },\n signal: controller.signal,\n },\n options?.runSoftTimeoutMs,\n );\n\n return accumulatedText || \"(no response)\";\n },\n });\n\n type OwnerContext = {\n owner: string;\n anonymous: boolean;\n name?: string;\n };\n const OWNER_CONTEXT_KEY = \"__agentNativeOwnerContext\";\n\n // Resolve owner from the H3 event's session, with an optional\n // template-provided anonymous owner for public read-only surfaces.\n const resolveOwnerContext = async (event: any): Promise<OwnerContext> => {\n const eventContext = event?.context as\n | (Record<string, unknown> & { [OWNER_CONTEXT_KEY]?: OwnerContext })\n | undefined;\n if (eventContext?.[OWNER_CONTEXT_KEY]) {\n return eventContext[OWNER_CONTEXT_KEY];\n }\n\n const session = await getSession(event);\n if (session?.email) {\n const resolved = {\n owner: session.email,\n anonymous: false,\n name: session.name,\n };\n if (eventContext) eventContext[OWNER_CONTEXT_KEY] = resolved;\n return resolved;\n }\n\n const anonymousOwner = await options?.anonymousOwner?.(event);\n if (anonymousOwner) {\n const resolved = { owner: anonymousOwner, anonymous: true };\n if (eventContext) eventContext[OWNER_CONTEXT_KEY] = resolved;\n return resolved;\n }\n\n const { createError } = await import(\"h3\");\n throw createError({\n statusCode: 401,\n statusMessage: \"Unauthenticated\",\n });\n };\n\n const getOwnerFromEvent = async (event: any): Promise<string> => {\n return (await resolveOwnerContext(event)).owner;\n };\n const getUserNameFromEvent = async (\n event: any,\n ): Promise<string | undefined> => {\n return (await resolveOwnerContext(event)).name;\n };\n\n // Auto-mount template actions as HTTP endpoints under /_agent-native/actions/\n // Include engine management script so the UI can call manage-agent-engine.\n // HTTP/frontend surface keeps the full `*All` sets so actions with\n // `agentTool: false` (hidden from every agent tool list) remain callable\n // via `useActionMutation` / `callAction` / `/_agent-native/actions/<name>`.\n const httpActions: Record<string, ActionEntry> = {\n ...discoveredActionsAll,\n ...templateScriptsAll,\n ...engineScripts,\n ...loopSettingsScripts,\n };\n // Framework-level sharing actions — merged with skipExisting semantics so\n // any template that provides a same-named action wins. When templates use\n // `loadActionsFromStaticRegistry`, `autoDiscoverActions` never runs, so\n // this is the single point that guarantees share-resource, unshare-resource,\n // list-resource-shares, and set-resource-visibility are always mounted.\n try {\n const { mergeCoreSharingActions } =\n await import(\"./action-discovery.js\");\n await mergeCoreSharingActions(httpActions);\n } catch {\n // Ignore — templates without sharing still work.\n }\n if (Object.keys(httpActions).length > 0) {\n const { mountActionRoutes } = await import(\"./action-routes.js\");\n mountActionRoutes(nitroApp, httpActions, {\n getOwnerFromEvent,\n getUserNameFromEvent,\n resolveOrgId: options?.resolveOrgId,\n });\n }\n\n const preRunGitStatusByThread = new Map<string, string | null>();\n\n async function recordPreRunGitStatus(threadId: string): Promise<void> {\n if (!isDevMode()) return;\n try {\n const { getUncommittedStatus, isGitRepo } =\n await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n preRunGitStatusByThread.set(\n threadId,\n isGitRepo(cwd) ? getUncommittedStatus(cwd) : null,\n );\n } catch {\n preRunGitStatusByThread.set(threadId, null);\n }\n }\n\n // Callback to persist agent response when run finishes (even if client disconnected).\n // Reconstructs the assistant message from buffered events and appends to thread_data.\n const onRunComplete = async (run: any, threadId: string | undefined) => {\n const runThreadId = String(run?.threadId ?? threadId ?? \"\");\n if (!threadId) {\n if (runThreadId) preRunGitStatusByThread.delete(runThreadId);\n return;\n }\n // Serialize the read-modify-write against the same thread's other\n // `thread_data` writers (setThreadQueuedMessages, setThreadEngineMeta,\n // the frontend-triggered saves below). Without the lock, a concurrent\n // queued-message save can clobber the assistant message we just\n // appended here, or vice versa.\n await withThreadDataLock(threadId, async () => {\n try {\n const thread = await getThread(threadId);\n if (!thread) {\n throw new Error(\n `Agent chat thread ${threadId} was not found while saving run ${run.runId}.`,\n );\n }\n const runOwner =\n getRequestRunContext()?.owner ?? getRequestUserEmail();\n if (runOwner && thread.ownerEmail !== runOwner) {\n throw createError({\n statusCode: 404,\n statusMessage: \"Thread not found\",\n });\n }\n\n const assistantMsg = buildAssistantMessage(\n run.events ?? [],\n run.runId,\n {\n suppressInternalContinuation: true,\n turnId:\n typeof run.turnId === \"string\" && run.turnId\n ? run.turnId\n : undefined,\n },\n );\n if (!assistantMsg) {\n // No content produced — just bump timestamp\n await updateThreadData(\n threadId,\n thread.threadData,\n thread.title,\n thread.preview,\n thread.messageCount,\n );\n return;\n }\n\n // Parse existing thread_data, append assistant message only if\n // the frontend hasn't already saved it (avoids duplicates when\n // the client is still connected during a normal flow).\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n repo = foldAssistantTurn(repo, assistantMsg, {\n runId: run.runId,\n turnId:\n typeof run.turnId === \"string\" && run.turnId\n ? run.turnId\n : undefined,\n });\n\n // Store debug metadata so we can inspect what the LLM actually\n // received (system prompt, model, engine) when diagnosing issues.\n const runCtx = getRequestRunContext();\n const debug = {\n runId: run.runId,\n systemPrompt: runCtx?.systemPrompt,\n model: runCtx?.model ?? resolvedModel,\n engine: runCtx?.engine?.name ?? \"unknown\",\n timestamp: Date.now(),\n };\n repo._debug = debug;\n const debugRuns = Array.isArray(repo._debugRuns)\n ? repo._debugRuns\n : [];\n repo._debugRuns = [...debugRuns, debug].slice(-50);\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread.title,\n meta.preview || thread.preview,\n repo.messages.length,\n );\n } catch (err) {\n // Run completion is only successful once thread_data is durable.\n throw err;\n }\n });\n\n // Keep SQL run completion gated only on durable thread data. Follow-up\n // hooks are useful, but they should never leave agent_runs stuck\n // \"running\" if an automation/checkpoint path stalls.\n void (async () => {\n // Emit agent.turn.completed for automation triggers.\n //\n // SECURITY: include `owner` so the trigger dispatcher's tenant-scope\n // check engages (see triggers/dispatcher.ts:212-218). Without an\n // owner, every user's matching `agent.turn.completed` trigger\n // would fire when ANY user's chat turn completes — cross-tenant\n // fan-out (audit 12 #9). Owner comes from the thread row when\n // available (most reliable; persisted at thread create time),\n // falling back to the current run context's owner. If neither\n // resolves we skip emission entirely rather than emit unowned.\n try {\n let ownerEmail: string | undefined;\n try {\n const ownerThread = await getThread(threadId);\n ownerEmail = ownerThread?.ownerEmail;\n } catch {\n // ignore — fall through to run-context owner\n }\n if (!ownerEmail) {\n ownerEmail = getRequestRunContext()?.owner;\n }\n if (ownerEmail) {\n const { emit } = await import(\"../event-bus/index.js\");\n emit(\n \"agent.turn.completed\",\n { threadId, model: resolvedModel },\n { owner: ownerEmail },\n );\n }\n } catch {\n // Event bus not available — skip\n }\n\n // Auto-checkpoint in dev mode after file-modifying agent turns\n if (isDevMode()) {\n try {\n const {\n createCheckpoint: gitCheckpoint,\n isGitRepo,\n hasUncommittedChanges,\n getChangedFileNames,\n getUncommittedStatus,\n } = await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n const preRunStatus = runThreadId\n ? preRunGitStatusByThread.get(runThreadId)\n : undefined;\n if (runThreadId) preRunGitStatusByThread.delete(runThreadId);\n\n // Only auto-commit checkpoints for changes produced by this run.\n // If the tree was already dirty, a checkpoint commit would sweep\n // up the user's unrelated work when a reconnect/refresh finishes.\n const postRunStatus = getUncommittedStatus(cwd);\n if (\n preRunStatus === \"\" &&\n postRunStatus?.trim() &&\n isGitRepo(cwd) &&\n hasUncommittedChanges(cwd)\n ) {\n let summary = \"\";\n\n // Try to extract the first sentence of the assistant's text response\n let assistantText = \"\";\n for (const { event } of run.events ?? []) {\n if (event.type === \"text\" && typeof event.text === \"string\") {\n assistantText += event.text;\n }\n }\n assistantText = assistantText.trim();\n if (assistantText) {\n const firstSentence = assistantText\n .split(/(?<=[.!?\\n])\\s/)[0]\n ?.replace(/\\n/g, \" \")\n .trim();\n if (firstSentence && firstSentence.length <= 120) {\n summary = firstSentence;\n } else if (firstSentence) {\n summary = firstSentence.slice(0, 117) + \"...\";\n }\n }\n\n // Fall back to listing changed files\n if (!summary) {\n const files = getChangedFileNames(cwd);\n if (files.length > 0) {\n summary = `Update ${files.join(\", \")}`;\n }\n }\n\n if (!summary) summary = \"Agent turn\";\n if (summary.length > 120)\n summary = summary.slice(0, 117) + \"...\";\n\n const sha = gitCheckpoint(cwd, summary);\n if (sha) {\n const { insertCheckpoint } =\n await import(\"../checkpoints/store.js\");\n const cpId = `cp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n await insertCheckpoint(\n cpId,\n threadId,\n run.runId,\n sha,\n summary,\n );\n }\n }\n } catch {\n // Checkpointing is best-effort — never break the run\n }\n }\n })();\n };\n\n const persistSubmittedUserMessage = async (details: {\n runId: string;\n threadId: string | undefined;\n message: string;\n attachments?: AgentChatAttachment[];\n }) => {\n const threadId = details.threadId;\n if (!threadId) return;\n const ownerEmail =\n getRequestRunContext()?.owner ?? getRequestUserEmail();\n if (!ownerEmail) return;\n\n await withThreadDataLock(threadId, async () => {\n let thread = await getThread(threadId);\n if (!thread) {\n try {\n thread = await createThread(ownerEmail, { id: threadId });\n } catch {\n thread = await getThread(threadId);\n }\n }\n if (!thread || thread.ownerEmail !== ownerEmail) {\n throw createError({\n statusCode: 404,\n statusMessage: \"Thread not found\",\n });\n }\n\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n\n repo = upsertUserMessage(\n repo,\n buildUserMessage({\n text: details.message,\n attachments: details.attachments,\n runId: details.runId,\n }),\n );\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread.title,\n meta.preview || thread.preview,\n Array.isArray(repo.messages)\n ? repo.messages.length\n : thread.messageCount,\n );\n });\n };\n\n // ─── Agent Teams: per-run send reference ─────────────────────────\n // Team tools need to emit events to the parent chat's SSE stream.\n // Each run gets its own send function, keyed by threadId so concurrent\n // requests for different threads don't clobber each other.\n const _runSendByThread = new Map<\n string,\n (event: import(\"../agent/types.js\").AgentChatEvent) => void\n >();\n const resolvedModel = options?.model ?? DEFAULT_ANTHROPIC_MODEL;\n\n // The action set a sub-agent inherits. Shared between the spawn-time team\n // tool and the `_process-run` processor route below so the durable run\n // executes with exactly the tools the orchestrator intended.\n const buildSubAgentActions = (): Record<string, ActionEntry> =>\n isDevMode()\n ? {\n // Sub-agents spawned in dev mode also invoke template actions\n // via bash, so omit them from the native tool registry.\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...devScriptsForA2A,\n }\n : {\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n };\n\n const teamTools = createTeamTools({\n getOwner: () => requireCurrentRunOwner(\"spawn or manage sub-agents\"),\n getSystemPrompt: () =>\n getRequestRunContext()?.systemPrompt ?? basePrompt,\n getActions: buildSubAgentActions,\n getEngine: () => {\n const runCtx = getRequestRunContext();\n return (\n runCtx?.engine ??\n createAnthropicEngine({\n // Sub-agents must inherit the parent run's resolved key so\n // delegations spawned by agent-teams don't silently fall back\n // to the platform key while the parent uses BYO credentials.\n apiKey:\n runCtx?.userApiKey ??\n options?.apiKey ??\n process.env.ANTHROPIC_API_KEY,\n })\n );\n },\n getModel: () => getRequestRunContext()?.model ?? resolvedModel,\n getParentThreadId: () => getRequestRunContext()?.threadId ?? \"\",\n getSend: () => {\n // Return the send for the current run's thread\n const threadId = getRequestRunContext()?.threadId ?? \"\";\n const send = _runSendByThread.get(threadId);\n return send ?? null;\n },\n });\n\n // Hook into the run lifecycle to set/clear the send reference.\n // Job management tool (manage-jobs)\n let jobTools: Record<string, ActionEntry> = {};\n try {\n const { createJobTools } = await import(\"../jobs/tools.js\");\n jobTools = createJobTools();\n } catch {}\n\n // Lean mode: only template actions + essential framework tools. Drop\n // web-request, browser tools, teams, jobs, automations, notifications,\n // progress, call-agent, and MCP entries to keep the tool list tight and\n // prevent the LLM from reaching for web-request instead of the\n // template's native actions (e.g. log-meal).\n const leanActionEntries: Record<string, ActionEntry> = {\n ...templateScripts,\n ...resourceScripts,\n ...refreshScreenTool,\n ...urlTools,\n ...chatScripts,\n ...toolActions,\n };\n const anonymousReadOnlyActions = attachToolSearch(\n filterReadOnlyActions(templateScripts),\n );\n\n // Full-database admin tools. Gated on NODE_ENV=development to match the\n // DB-admin UI + HTTP routes (which gate on the environment, not the\n // Code-mode toggle), so the agent has the same DB-admin capability the UI\n // does whenever it is available — true agent/UI parity, in App or Code mode.\n const dbAdminScripts =\n process.env.NODE_ENV === \"development\" ? createDbAdminAgentTools() : {};\n\n const prodActions = attachToolSearch({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...dbScripts,\n ...dbAdminScripts,\n ...refreshScreenTool,\n ...(lazyContext ? frameworkContextTool : {}),\n ...urlTools,\n ...chatScripts,\n ...callAgentScript,\n ...teamTools,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n // Sandboxed run-code for hosted production when enabled, and for the\n // app-rendered production-style handler in local dev.\n ...(canToggle || resolvedProdCodeExec !== \"off\" ? runCodeTool : {}),\n // Full coding tools in production when mode is \"trusted\".\n ...(!canToggle ? prodCodingTools : {}),\n });\n\n // Wire the prod run-code bridge supplier so it sees the fully-assembled\n // prodActions registry (including MCP entries added at runtime).\n prodRunCodeToolActions = prodActions;\n\n const leanActions = attachToolSearch({\n ...leanActionEntries,\n // Lean mode still needs run-code when code execution is enabled.\n // Otherwise templates with a minimal prompt can advertise sandboxed\n // execution in the system prompt while the actual tool registry omits\n // it.\n ...(canToggle || resolvedProdCodeExec !== \"off\" ? leanRunCodeTool : {}),\n });\n leanRunCodeToolActions = leanActions;\n\n // Keep the prod action dict's MCP entries in sync when the manager's\n // server set changes at runtime (e.g. a user adds a remote MCP server\n // through the settings UI). getEngineTools() in production-agent re-reads\n // the registry per request, so updates here propagate without restart.\n mcpManager.onChange(() => {\n syncMcpActionEntries(mcpManager, prodActions);\n });\n\n // Always build the production handler (includes resource tools + call-agent + team tools)\n // In production mode (!canToggle), resolve the owner from the request session.\n const isHostedProd = !canToggle;\n\n // Lean mode: use only the template's systemPrompt + actions list.\n // Skip resource loading and schema block — those add DB round-trips\n // and tokens that minimal/voice apps don't need.\n const leanBasePrompt = (options?.systemPrompt ?? \"\") + prodActionsPrompt;\n const anonymousReadOnlyPrompt =\n (options?.systemPrompt ?? PROD_FRAMEWORK_PROMPT_COMPACT) +\n generateActionsPrompt(filterReadOnlyActions(templateScripts), \"tool\") +\n \"\\n\\nYou are answering from a public shared page. Treat the visible resource as read-only: do not create, edit, delete, comment on, share, or otherwise mutate app data. If the user asks for a change, describe what you would change or suggest signing in to edit.\";\n\n // Per-request preamble shared by both prod and dev handlers. Resolves\n // owner + user API key onto the AsyncLocalStorage run context so\n // downstream tool closures (automation, fetch, team) read the\n // current request's identity without racing against concurrent\n // requests. `extraContext` runs in every prompt variant (lean, lazy,\n // full) — if a template defined it, they opted in; framework-provided\n // content is what the token-saving modes strip.\n const prepareRun = async (event: any) => {\n const owner = await getOwnerFromEvent(event);\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n const userApiKey = await getOwnerActiveApiKey(owner);\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.requestOrigin = getOrigin(event);\n runCtx.owner = owner;\n runCtx.userApiKey = userApiKey;\n }\n const extra = await resolveExtraContext(event, owner);\n return { owner, extra };\n };\n\n const setSystemPromptOnContext = (prompt: string): string => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.systemPrompt = prompt;\n return prompt;\n };\n\n /**\n * Read the model family overlay for the currently-resolved model.\n * onEngineResolved sets runCtx.model before systemPrompt is called, so\n * this returns a non-empty string for GPT/Gemini engines.\n */\n const resolveModelOverlay = (): string => {\n const runCtx = ensureRequestRunContext();\n const model = runCtx?.model;\n if (!model) return \"\";\n return getModelFamilyOverlay(model);\n };\n\n /**\n * Returns whether this request is for a brand-new thread (no prior\n * messages). Used to gate the First-Session Personalization block:\n * once a thread has history the block is dead weight on every request.\n *\n * prepareRequest stashes `details.threadId` as `_requestThreadId` on\n * runCtx before systemPrompt is assembled. A new thread has no threadId\n * (the UI passes undefined until the first message creates the thread).\n */\n const isNewThread = (): boolean => {\n const runCtx = ensureRequestRunContext();\n return !(runCtx as any)?._requestThreadId;\n };\n\n const runtimeContextForEvent = (event: any): string => {\n const tzRaw = getHeader(event, \"x-user-timezone\");\n const timezone =\n typeof tzRaw === \"string\" &&\n tzRaw.trim().length > 0 &&\n tzRaw.trim().length < 64\n ? tzRaw.trim()\n : undefined;\n return buildRuntimeContextPrompt({ timezone });\n };\n\n // The app-rendered sidebar must never edit the app's source code\n // directly. Source-file edits can trigger HMR or full reloads of the\n // same React tree that is hosting the chat, interrupting the run and\n // losing in-progress UI state. Code edits are allowed only from the\n // outer dev frame (x-agent-native-surface: dev-frame) or from separate\n // agent surfaces such as Builder/A2A/MCP handoffs.\n const shouldBlockInProductCodeEditing = (event: any): boolean =>\n shouldBlockInProductCodeEditingSurface({\n surface: getHeader(event, \"x-agent-native-surface\"),\n userAgent: getHeader(event, \"user-agent\"),\n host: getHeader(event, \"host\"),\n });\n\n const APP_RENDERED_CHAT_NO_DIRECT_CODE_PROMPT = `\n\n<app-rendered-chat-no-direct-code-edits>\nThis chat is rendered by the app itself. It must never edit this app's source files directly, because source edits can hot-reload or replace the same UI that is hosting the chat.\n\nWhen the user asks to add a feature, edit a component, fix a bug in the app itself, change styles, add a route, scaffold a new app, run shell commands that modify code, or do anything else that requires touching source files:\n\n1. Do NOT use dev shell/filesystem tools, write code inline, list source files, propose patches, or describe file-level implementation steps from this chat.\n2. For host-app source changes in Act mode, call \\`connect-builder\\` when that tool is available so a separate Builder/cloud agent can do the work. If Builder is unavailable, give a short handoff to the outer dev frame, Agent Native Desktop, Claude Code, or Codex in the project directory.\n3. If the request is specifically to add or scaffold a new workspace app and no Builder handoff is available, mention \\`npx @agent-native/core@latest add-app\\` in this workspace directory as the CLI path.\n\nNon-code requests are still fine on this surface: read data, navigate the UI, summarize, search, create/update extensions (sandboxed Alpine.js mini-apps stored in SQL), and call template actions. The restriction is specifically about direct edits to the host app's own source files.\n</app-rendered-chat-no-direct-code-edits>`;\n\n // System-prompt note appended when production code execution is enabled.\n const prodCodeExecPromptNote =\n !canToggle && resolvedProdCodeExec !== \"off\"\n ? resolvedProdCodeExec === \"trusted\"\n ? \"\\n\\n<code-execution-mode>Full shell access is enabled (trusted mode). You have bash, read, edit, write, and run-code tools available. Use bash for file discovery, running tests and builds, and project CLIs. Use run-code for sandboxed JavaScript data processing: provider/API pagination, joins, classification, aggregation, and large-response reduction. Use `pnpm action <name>` in bash to invoke registered app actions from the shell.</code-execution-mode>\"\n : \"\\n\\n<code-execution-mode>Sandboxed code execution is enabled. The run-code tool lets you execute isolated JavaScript (ESM, top-level await) to fetch, aggregate, and reduce data. Use providerFetch(), providerFetchAll(), providerRequest(), and webFetch() inside run-code for authenticated provider calls.</code-execution-mode>\"\n : \"\";\n\n const prodHandler = createProductionAgentHandler({\n actions: leanPrompt ? leanActions : prodActions,\n systemPrompt: async (event: any) => {\n const { owner, extra } = await prepareRun(event);\n const runtimeContext = runtimeContextForEvent(event);\n const codeEditingSurfaceRestriction = shouldBlockInProductCodeEditing(\n event,\n )\n ? APP_RENDERED_CHAT_NO_DIRECT_CODE_PROMPT\n : \"\";\n // Personalization block: only include on new threads (no prior messages).\n // Once a thread exists, the agent has already run (or skipped) the flow.\n const personalizationBlock = isNewThread()\n ? FIRST_SESSION_PERSONALIZATION\n : \"\";\n // Per-model overlay: nudge GPT/Gemini engines toward our behavioral norms.\n const modelOverlay = resolveModelOverlay();\n if (leanPrompt) {\n return setSystemPromptOnContext(\n leanBasePrompt +\n runtimeContext +\n codeEditingSurfaceRestriction +\n prodCodeExecPromptNote +\n extra +\n modelOverlay,\n );\n }\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n // In lazy context mode, skip embedding the full schema — the agent\n // calls `db-schema` on demand. This saves ~1-2K tokens per request.\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return setSystemPromptOnContext(\n basePrompt +\n personalizationBlock +\n runtimeContext +\n resources +\n schemaBlock +\n codeEditingSurfaceRestriction +\n prodCodeExecPromptNote +\n extra +\n modelOverlay,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: async (details) => {\n // Stash the threadId on runCtx so systemPrompt can check isNewThread().\n // prepareRequest fires before systemPromptPromise starts, so this is safe.\n const runCtxForPrepare = ensureRequestRunContext();\n if (runCtxForPrepare && details.threadId) {\n (runCtxForPrepare as any)._requestThreadId = details.threadId;\n }\n\n // Drain any parent-completion injections queued by finished sub-agents\n // and prepend them to the user message so the orchestrator sees results\n // at the start of this turn rather than only after a manual poll.\n const threadId = details.threadId;\n let completionPrefix = \"\";\n if (threadId && !details.internalContinuation) {\n try {\n const {\n drainParentCompletionInjections,\n formatParentCompletionInjections,\n } = await import(\"./agent-teams.js\");\n const injections =\n await drainParentCompletionInjections(threadId);\n if (injections.length > 0) {\n completionPrefix = formatParentCompletionInjections(injections);\n }\n } catch {\n // best-effort — never break the run\n }\n }\n // Also run the template-provided prepareRequest (if any).\n const templateResult = await options?.prepareRequest?.(details);\n if (!completionPrefix) return templateResult ?? undefined;\n const baseMessage =\n typeof templateResult === \"object\" &&\n templateResult &&\n typeof templateResult.message === \"string\"\n ? templateResult.message\n : details.message;\n const message = `${completionPrefix}\\n\\n${baseMessage}`;\n return {\n ...(typeof templateResult === \"object\" && templateResult\n ? templateResult\n : {}),\n message,\n };\n },\n skipFilesContext: leanPrompt,\n ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (event: import(\"../agent/types.js\").AgentChatEvent) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n // Resolve owner from session for usage attribution in hosted prod\n resolveOwnerEmail: isHostedProd ? getOwnerFromEvent : undefined,\n });\n\n const anonymousHandler =\n options?.anonymousOwner && options.anonymousReadOnly !== false\n ? createProductionAgentHandler({\n actions: anonymousReadOnlyActions,\n systemPrompt: async (event: any) => {\n const { extra } = await prepareRun(event);\n return setSystemPromptOnContext(\n anonymousReadOnlyPrompt +\n runtimeContextForEvent(event) +\n extra,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: options?.prepareRequest,\n skipFilesContext: true,\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (\n event: import(\"../agent/types.js\").AgentChatEvent,\n ) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n resolveOwnerEmail: getOwnerFromEvent,\n })\n : null;\n\n // Build the dev handler (with filesystem/bash/db tools) if environment allows toggling\n let devHandler: ReturnType<typeof createProductionAgentHandler> | null =\n null;\n if (canToggle) {\n const { createDevScriptRegistry } =\n await import(\"../scripts/dev/index.js\");\n // Dev mode: template actions (templateScripts and discoveredActions) are\n // intentionally OMITTED from the native tool registry. The agent invokes\n // them via `bash(command=\"pnpm action <name> ...\")` instead. This mirrors\n // how Claude Code works locally and dramatically reduces the rate of\n // degenerate empty-object tool calls. The CLI syntax for each action is\n // listed in the dev system prompt's \"Available Actions\" section.\n // In lean mode — or when `nativeActionsInDev` is set — expose the\n // template's actions as native tools instead of routing through bash.\n // Templates with structured-arg actions (objects/arrays) need this to\n // avoid round-tripping JSON through the CLI parser.\n const devActions = attachToolSearch(\n leanPrompt\n ? leanActions\n : devNative\n ? prodActions\n : {\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...callAgentScript,\n ...teamTools,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...workspaceFilesTool,\n ...toolActions,\n ...browserSessionTools,\n ...coreEmailTools,\n ...coreAttachmentTools,\n ...browserTools,\n ...mcpActionEntries,\n ...(await createDevScriptRegistry()),\n // Full-database admin tools (NODE_ENV=development gate — see\n // dbAdminScripts; also in prodActions so App mode has them too).\n ...dbAdminScripts,\n // run-code sandbox is always available in dev mode.\n ...devRunCodeTool,\n },\n );\n // Wire the late-binding supplier for devRunCodeTool so the bridge can\n // call back into the fully-assembled devActions registry.\n devRunCodeToolActions = devActions;\n // Keep dev action dict in sync with runtime MCP additions. When\n // native-actions mode is on (lean or `nativeActionsInDev`), devActions\n // === prodActions so the prod listener already covers it.\n if (devActions !== prodActions && devActions !== leanActions) {\n mcpManager.onChange(() => {\n syncMcpActionEntries(mcpManager, devActions);\n });\n }\n devHandler = createProductionAgentHandler({\n actions: devActions,\n systemPrompt: async (event: any) => {\n const { owner, extra } = await prepareRun(event);\n const runtimeContext = runtimeContextForEvent(event);\n const personalizationBlock = isNewThread()\n ? FIRST_SESSION_PERSONALIZATION\n : \"\";\n const modelOverlay = resolveModelOverlay();\n if (leanPrompt) {\n return setSystemPromptOnContext(\n leanBasePrompt + runtimeContext + extra + modelOverlay,\n );\n }\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, true);\n return setSystemPromptOnContext(\n devPrompt +\n personalizationBlock +\n runtimeContext +\n resources +\n schemaBlock +\n extra +\n modelOverlay,\n );\n },\n model: options?.model,\n appId: options?.appId,\n apiKey: options?.apiKey,\n runSoftTimeoutMs: options?.runSoftTimeoutMs,\n finalResponseGuard: options?.finalResponseGuard,\n prepareRequest: options?.prepareRequest,\n skipFilesContext: leanPrompt,\n ...(options?.toolLimits ? { toolLimits: options.toolLimits } : {}),\n onEngineResolved: (engine, model) => {\n const runCtx = ensureRequestRunContext();\n if (runCtx) {\n runCtx.engine = engine;\n runCtx.model = model;\n }\n },\n onRunPrepared: persistSubmittedUserMessage,\n onRunStart: async (\n send: (event: import(\"../agent/types.js\").AgentChatEvent) => void,\n threadId: string,\n ) => {\n await recordPreRunGitStatus(threadId);\n _runSendByThread.set(threadId, send);\n const runCtx = ensureRequestRunContext();\n if (runCtx) runCtx.threadId = threadId;\n },\n onRunComplete: async (run: any, threadId: string | undefined) => {\n if (threadId) _runSendByThread.delete(threadId);\n await onRunComplete(run, threadId);\n },\n });\n }\n\n // Resolve mention providers\n const rawProviders = options?.mentionProviders;\n const mentionProviders: Record<string, MentionProvider> =\n typeof rawProviders === \"function\"\n ? await rawProviders()\n : (rawProviders ?? {});\n\n // currentDevMode + persistence were hoisted to the top of this function\n // so every closure built below can close over the live flag.\n\n // Mount mode endpoint — GET returns current mode, POST toggles it (localhost only)\n getH3App(nitroApp).use(\n `${routePath}/mode`,\n defineEventHandler(async (event) => {\n if (getMethod(event) === \"POST\") {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Mode switching not available in production\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Mode switching only available on localhost\" };\n }\n const body = await readBody(event);\n if (typeof body?.devMode === \"boolean\") {\n currentDevMode = body.devMode;\n } else {\n currentDevMode = !currentDevMode;\n }\n try {\n await putSetting(AGENT_MODE_SETTING_KEY, {\n devMode: currentDevMode,\n });\n } catch {\n // Persistence is best-effort — in-memory flag still applies for\n // the lifetime of this process even if the settings write fails.\n }\n return {\n devMode: currentDevMode,\n codeMode: currentDevMode,\n canToggle,\n };\n }\n return {\n devMode: currentDevMode,\n codeMode: currentDevMode,\n canToggle,\n };\n }),\n );\n\n // Self-heal the RunsTray: when the tray lists this owner's runs, first\n // reconcile their in-flight sub-agent runs (re-fire dropped dispatches,\n // mark dead runs failed) so the tray reflects precise status without\n // waiting on the orchestrator chat to poll. Registered here to keep the\n // generic progress store free of feature-module imports.\n setProgressPreListHook((owner, context) =>\n runWithRequestContext({ userEmail: owner }, () =>\n reconcileAgentTeamRunsForOwner(owner, context.event),\n ),\n );\n\n // ─── Agent Teams: durable sub-agent run processor ─────────────────\n // Self-fire target for `spawnTask`. Executes one chunk of a queued\n // sub-agent in this fresh function invocation (its own timeout budget)\n // so background sub-agents survive serverless instead of dying as a\n // detached promise. Mounted here so it closes over the sub-agent action\n // set / base prompt / engine (per-deployment closures that can't be\n // serialized into the queue). HMAC-authed with the same internal-token\n // scheme as the A2A/webhook processors.\n getH3App(nitroApp).use(\n AGENT_TEAM_PROCESS_RUN_PATH,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n const body = (await readBody(event)) as {\n taskId?: unknown;\n mode?: unknown;\n noProgressCount?: unknown;\n } | null;\n const taskId =\n body && typeof body.taskId === \"string\" ? body.taskId : \"\";\n if (!taskId) {\n setResponseStatus(event, 400);\n return { error: \"taskId required\" };\n }\n const mode: \"start\" | \"continue\" =\n body?.mode === \"continue\" ? \"continue\" : \"start\";\n const noProgressCount =\n typeof body?.noProgressCount === \"number\"\n ? body.noProgressCount\n : undefined;\n\n if (hasConfiguredA2ASecret()) {\n const tok = extractBearerToken(getHeader(event, \"authorization\"));\n if (!verifyInternalToken(taskId, tok ?? \"\")) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired processor token\" };\n }\n } else if (isA2AProductionRuntime()) {\n setResponseStatus(event, 503);\n return {\n error:\n \"Agent Teams processor not configured — set A2A_SECRET on this deployment.\",\n };\n }\n\n try {\n return await processAgentTeamRun({\n taskId,\n mode,\n event,\n noProgressCount,\n resolveConfig: async ({ payload, ownerEmail, orgId: _orgId }) => {\n // Resolve the owner's API key so BYO-key sub-agents use the\n // same credentials as the parent chat.\n let apiKey: string | undefined;\n try {\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n apiKey =\n (await getOwnerActiveApiKey(ownerEmail)) ?? undefined;\n } catch {\n apiKey = undefined;\n }\n // Use the same resolveEngine path as the A2A and MCP\n // processors so Builder-gateway/OpenAI users get their\n // configured engine instead of always hitting the Anthropic SDK.\n const engine = await resolveEngine({\n engineOption: options?.engine,\n apiKey: apiKey ?? options?.apiKey,\n appId: options?.appId,\n });\n const modelCandidate =\n payload.model ??\n (await getStoredModelForEngine(engine, {\n appId: options?.appId,\n })) ??\n engine.defaultModel ??\n resolvedModel;\n const model = normalizeModelForEngine(engine, modelCandidate);\n return {\n baseSystemPrompt: basePrompt,\n actions: buildSubAgentActions(),\n engine,\n model,\n };\n },\n });\n } catch (err: any) {\n console.error(\"[agent-teams] _process-run failed:\", err);\n setResponseStatus(event, 500);\n return { error: \"process-run failed\" };\n }\n }),\n );\n\n const modelDefaultsAppId =\n normalizeAgentAppModelDefaultAppId(\n options?.appId ??\n process.env.AGENT_NATIVE_APP_ID ??\n process.env.VITE_AGENT_NATIVE_TEMPLATE ??\n \"app\",\n ) ?? \"app\";\n\n const resolveModelDefaultsContext = async (event: any) => {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) {\n return {\n ok: false as const,\n status: 401,\n error: \"Authentication required\",\n };\n }\n\n let orgCtx: {\n orgId?: string | null;\n orgName?: string | null;\n role?: string | null;\n } | null = null;\n try {\n const { getOrgContext } = await import(\"../org/context.js\");\n orgCtx = await getOrgContext(event);\n } catch {\n orgCtx = null;\n }\n\n const orgId =\n (options?.resolveOrgId\n ? await options.resolveOrgId(event)\n : (orgCtx?.orgId ?? session.orgId ?? null)) ?? null;\n const canUpdate = await canUpdateAgentAppModelDefaultSettings(\n session.email,\n orgId,\n );\n\n return {\n ok: true as const,\n userEmail: session.email,\n orgId,\n orgName: orgCtx?.orgId === orgId ? (orgCtx.orgName ?? null) : null,\n role: orgCtx?.orgId === orgId ? (orgCtx.role ?? null) : null,\n canUpdate,\n };\n };\n\n const listModelDefaultEngineOptions = async (ctx: {\n userEmail?: string;\n orgId?: string | null;\n }) => {\n registerBuiltinEngines();\n return runWithRequestContext(\n {\n userEmail: ctx.userEmail,\n orgId: ctx.orgId ?? undefined,\n },\n () =>\n Promise.all(\n listAgentEngines().map(async (entry) => ({\n name: entry.name,\n label: entry.label,\n description: entry.description,\n defaultModel: entry.defaultModel,\n supportedModels: entry.supportedModels,\n requiredEnvVars: entry.requiredEnvVars,\n installPackage: entry.installPackage,\n packageInstalled: isAgentEnginePackageInstalled(entry),\n configured: await isStoredEngineUsableForRequest(\n { engine: entry.name, model: entry.defaultModel },\n entry,\n ).catch(() => false),\n })),\n ),\n );\n };\n\n const buildModelDefaultsPayload = async (event: any, appId: string) => {\n const ctx = await resolveModelDefaultsContext(event);\n if (!ctx.ok) return ctx;\n const settings = await readAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n appId,\n );\n return {\n ok: true as const,\n ...settings,\n canUpdate: ctx.canUpdate,\n orgId: ctx.orgId,\n orgName: ctx.orgName,\n role: ctx.role,\n engines: await listModelDefaultEngineOptions(ctx),\n };\n };\n\n // GET/PUT/DELETE /_agent-native/agent-model-defaults — org-scoped\n // per-app default engine/model used when a chat request does not carry\n // an explicit composer model selection.\n getH3App(nitroApp).use(\n \"/_agent-native/agent-model-defaults\",\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n const query = getQuery(event);\n const queryAppId =\n typeof query.appId === \"string\" ? query.appId : undefined;\n const appId =\n normalizeAgentAppModelDefaultAppId(queryAppId) ??\n modelDefaultsAppId;\n\n if (method === \"GET\") {\n const payload = await buildModelDefaultsPayload(event, appId);\n if (payload.ok === false) {\n setResponseStatus(event, payload.status);\n return { error: payload.error };\n }\n return payload;\n }\n\n if (method !== \"PUT\" && method !== \"DELETE\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const ctx = await resolveModelDefaultsContext(event);\n if (ctx.ok === false) {\n setResponseStatus(event, ctx.status);\n return { error: ctx.error };\n }\n if (!ctx.canUpdate) {\n setResponseStatus(event, 403);\n return {\n error: ctx.orgId\n ? \"Only organization owners and admins can change app model defaults.\"\n : \"You cannot change app model defaults.\",\n };\n }\n\n if (method === \"DELETE\") {\n await resetAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n appId,\n );\n return buildModelDefaultsPayload(event, appId);\n }\n\n const body = await readBody(event).catch(() => ({}));\n const bodyAppId =\n typeof body?.appId === \"string\" ? body.appId : undefined;\n const targetAppId =\n normalizeAgentAppModelDefaultAppId(bodyAppId) ?? appId;\n const engine =\n typeof body?.engine === \"string\" ? body.engine.trim() : \"\";\n const model =\n typeof body?.model === \"string\" ? body.model.trim() : \"\";\n if (!engine || !model) {\n setResponseStatus(event, 400);\n return { error: \"engine and model are required\" };\n }\n const entry = getAgentEngineEntry(engine);\n if (!entry) {\n setResponseStatus(event, 400);\n return { error: `Unknown engine: ${engine}` };\n }\n if (!isAgentEnginePackageInstalled(entry)) {\n setResponseStatus(event, 400);\n return {\n error: `Engine \"${engine}\" requires optional packages that are not installed in this app. Run: pnpm add ${entry.installPackage}`,\n };\n }\n if (\n entry.name === \"builder\" &&\n normalizeModelForEngine(entry, model) !== model\n ) {\n setResponseStatus(event, 400);\n return {\n error: `Model \"${model}\" is not supported by Builder. Choose one of: ${entry.supportedModels.join(\", \")}`,\n };\n }\n\n await writeAgentAppModelDefaultSettings(\n { userEmail: ctx.userEmail, orgId: ctx.orgId },\n targetAppId,\n { engine, model, updatedBy: ctx.userEmail },\n );\n return buildModelDefaultsPayload(event, targetAppId);\n }),\n );\n\n // Mount save-key BEFORE the prefix handler so it isn't shadowed.\n // Persists the user's API key in `app_secrets` (encrypted, scope=user,\n // scopeId=email). Hard rule: never mutates process.env, never writes\n // .env. User-pasted secrets must not become deploy-level identity —\n // that's the cross-tenant leak class (KVesta Space, 2026-04).\n // Consumers read these values per-request via `resolveSecret(key)`.\n getH3App(nitroApp).use(\n `${routePath}/save-key`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = await readBody(event);\n const { key, provider: rawProvider } = body as {\n key?: string;\n provider?: string;\n };\n const provider = rawProvider || \"anthropic\";\n\n if (!key || typeof key !== \"string\" || !key.trim()) {\n setResponseStatus(event, 400);\n return { error: \"API key is required\" };\n }\n\n const trimmedKey = key.trim();\n\n const ownerEmail = await getOwnerFromEvent(event);\n if (!ownerEmail) {\n setResponseStatus(event, 401);\n return { error: \"Authentication required\" };\n }\n\n const providerToEnv: Record<string, string> = {\n anthropic: \"ANTHROPIC_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n google: \"GOOGLE_GENERATIVE_AI_API_KEY\",\n groq: \"GROQ_API_KEY\",\n mistral: \"MISTRAL_API_KEY\",\n cohere: \"COHERE_API_KEY\",\n };\n const secretKey =\n providerToEnv[provider] ?? `${provider.toUpperCase()}_API_KEY`;\n\n try {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n await writeAppSecret({\n key: secretKey,\n value: trimmedKey,\n scope: \"user\",\n scopeId: ownerEmail,\n });\n } catch (err) {\n console.error(\n \"[agent-chat] save-key persistence failed:\",\n err instanceof Error ? err.message : err,\n );\n setResponseStatus(event, 500);\n return {\n error:\n \"Failed to persist API key. Please try again or contact support.\",\n };\n }\n\n return { ok: true };\n }),\n );\n\n // Mount file search endpoint\n getH3App(nitroApp).use(\n `${routePath}/files`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const query = getQuery(event);\n const q = typeof query.q === \"string\" ? query.q.toLowerCase() : \"\";\n\n const files: Array<{\n path: string;\n name: string;\n source: \"codebase\" | \"resource\";\n type: string;\n }> = [];\n const seen = new Set<string>();\n\n // In dev mode, walk the filesystem\n if (currentDevMode) {\n const codebaseFiles: Array<{\n path: string;\n name: string;\n type: \"file\" | \"folder\";\n }> = [];\n try {\n await collectFiles(process.cwd(), \"\", 0, codebaseFiles);\n } catch {\n // Filesystem access failed — skip\n }\n for (const f of codebaseFiles) {\n if (!seen.has(f.path)) {\n seen.add(f.path);\n files.push({\n path: f.path,\n name: f.name,\n source: \"codebase\",\n type: f.type,\n });\n }\n }\n }\n\n // Query resources\n try {\n const resources = [\n ...(await resourceList(SHARED_OWNER)),\n ...(await resourceList(WORKSPACE_OWNER)),\n ];\n for (const r of resources) {\n if (!seen.has(r.path)) {\n seen.add(r.path);\n files.push({\n path: r.path,\n name: r.path.split(\"/\").pop() || r.path,\n source: \"resource\",\n type: \"file\",\n });\n }\n }\n } catch {\n // Resources not available — skip\n }\n\n // Filter by query and limit\n const filtered = q\n ? files.filter((f) => f.path.toLowerCase().includes(q))\n : files;\n\n return { files: filtered.slice(0, 30) };\n }),\n );\n\n // Mount skills listing endpoint\n getH3App(nitroApp).use(\n `${routePath}/skills`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const skills: Array<{\n name: string;\n description?: string;\n path: string;\n source: \"codebase\" | \"resource\";\n }> = [];\n const seenNames = new Set<string>();\n\n // In dev mode, scan .agents/skills/ plus legacy .agent/skills/.\n if (currentDevMode) {\n try {\n const _fs = await lazyFs();\n const skillRoots = [\n {\n dir: nodePath.join(process.cwd(), \".agents\", \"skills\"),\n display: \".agents/skills\",\n },\n {\n dir: nodePath.join(process.cwd(), \".agent\", \"skills\"),\n display: \".agent/skills\",\n },\n ];\n for (const root of skillRoots) {\n let entries: Array<{\n name: string;\n isDirectory: () => boolean;\n isFile: () => boolean;\n }>;\n try {\n entries = _fs.readdirSync(root.dir, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const entry of entries) {\n // Support both flat .md files and subdirectory-based skills (dir/SKILL.md)\n let skillFilePath: string;\n let skillRelPath: string;\n\n if (entry.isDirectory()) {\n // Subdirectory layout: <skills-root>/<name>/SKILL.md\n const candidate = nodePath.join(\n root.dir,\n entry.name,\n \"SKILL.md\",\n );\n if (!_fs.existsSync(candidate)) continue;\n skillFilePath = candidate;\n skillRelPath = `${root.display}/${entry.name}/SKILL.md`;\n } else if (entry.isFile() && entry.name.endsWith(\".md\")) {\n // Flat layout: <skills-root>/<name>.md\n skillFilePath = nodePath.join(root.dir, entry.name);\n skillRelPath = `${root.display}/${entry.name}`;\n } else {\n continue;\n }\n\n try {\n const content = _fs.readFileSync(skillFilePath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n if (fm.userInvocable === false) continue;\n const skillName =\n fm.name || entry.name.replace(/\\.md$/, \"\");\n if (!seenNames.has(skillName)) {\n seenNames.add(skillName);\n skills.push({\n name: skillName,\n description: fm.description,\n path: skillRelPath,\n source: \"codebase\",\n });\n }\n } catch {\n // Could not read individual skill file — skip\n }\n }\n }\n } catch {\n // Skill directories don't exist or are not readable — skip.\n }\n }\n\n // Query accessible resources with skills/ prefix. Personal skills\n // need to show alongside shared skills so slash/menu invocation can\n // find both `learn` and `learn-shared`.\n try {\n const skillsOwner = await getOwnerFromEvent(event).catch(\n () => undefined,\n );\n let skillsOrgId: string | undefined;\n if (options?.resolveOrgId) {\n try {\n skillsOrgId = (await options.resolveOrgId(event)) ?? undefined;\n } catch {\n skillsOrgId = undefined;\n }\n }\n if (skillsOwner) await ensurePersonalDefaults(skillsOwner);\n const resourceSkills = skillsOwner\n ? await resourceListAccessible(skillsOwner, \"skills/\", {\n userEmail: skillsOwner,\n orgId: skillsOrgId ?? null,\n })\n : [\n ...(await resourceList(SHARED_OWNER, \"skills/\")),\n ...(await resourceList(WORKSPACE_OWNER, \"skills/\")),\n ];\n resourceSkills.sort((a, b) => {\n const ownerOrder =\n (a.owner === skillsOwner\n ? 0\n : a.owner === SHARED_OWNER\n ? 1\n : a.owner === WORKSPACE_OWNER\n ? 2\n : 3) -\n (b.owner === skillsOwner\n ? 0\n : b.owner === SHARED_OWNER\n ? 1\n : b.owner === WORKSPACE_OWNER\n ? 2\n : 3);\n if (ownerOrder !== 0) return ownerOrder;\n const pathOrder =\n (a.path.endsWith(\"/SKILL.md\") ? 0 : 1) -\n (b.path.endsWith(\"/SKILL.md\") ? 0 : 1);\n if (pathOrder !== 0) return pathOrder;\n return a.path.localeCompare(b.path);\n });\n for (const r of resourceSkills) {\n // Try to get content to parse frontmatter\n let skillName = getSkillNameFromPath(r.path);\n let description: string | undefined;\n let userInvocable: boolean | undefined;\n try {\n const full = await resourceGet(\n r.id,\n skillsOwner\n ? { userEmail: skillsOwner, orgId: skillsOrgId ?? null }\n : undefined,\n );\n if (full) {\n const fm = parseSkillFrontmatter(full.content);\n if (fm.name) skillName = fm.name;\n description = fm.description;\n userInvocable = fm.userInvocable;\n }\n } catch {\n // Could not read resource content — use path-based name\n }\n if (userInvocable === false) continue;\n if (!seenNames.has(skillName)) {\n seenNames.add(skillName);\n skills.push({\n name: skillName,\n description,\n path: r.path,\n source: \"resource\",\n });\n }\n }\n } catch {\n // Resources not available — skip\n }\n\n const result: {\n skills: typeof skills;\n hint?: string;\n } = { skills };\n\n if (skills.length === 0) {\n result.hint =\n \"No skills found. Add skill files under skills/ in Resources. Learn more: https://agent-native.com/docs/resources#skills\";\n }\n\n return result;\n }),\n );\n\n // Mount unified mentions endpoint (files + resources + custom providers)\n getH3App(nitroApp).use(\n `${routePath}/mentions`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Resolve the caller and run the entire stream inside a request\n // context so custom mention providers can use `accessFilter` /\n // `resolveAccess` when querying ownable tables. Without this,\n // a provider that searches `decks` (or any sharable resource)\n // would see every row regardless of ownership.\n const mentionsOwner = await getOwnerFromEvent(event).catch(\n () => undefined,\n );\n let mentionsOrgId: string | undefined;\n if (options?.resolveOrgId) {\n try {\n const resolved = await options.resolveOrgId(event);\n mentionsOrgId = resolved ?? undefined;\n } catch {\n mentionsOrgId = undefined;\n }\n }\n\n const query = getQuery(event);\n const q = typeof query.q === \"string\" ? query.q.toLowerCase() : \"\";\n\n interface MentionItemResponse {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n source: string;\n refType: string;\n refPath?: string;\n refId?: string;\n section?: string;\n }\n\n const matchesQuery = (item: MentionItemResponse) =>\n !q ||\n item.label.toLowerCase().includes(q) ||\n (item.description?.toLowerCase().includes(q) ?? false);\n\n const enc = new TextEncoder();\n\n // Stream NDJSON — each source flushes its batch as soon as it's ready.\n setResponseHeader(event, \"Content-Type\", \"application/x-ndjson\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n\n const stream = new ReadableStream({\n start(controller) {\n return runWithRequestContext(\n {\n userEmail: mentionsOwner,\n orgId: mentionsOrgId,\n },\n () => mentionsStreamWork(controller),\n );\n },\n cancel() {\n // Client disconnected — stop enqueuing\n },\n });\n\n return stream;\n\n async function mentionsStreamWork(\n controller: ReadableStreamDefaultController<Uint8Array>,\n ) {\n const MAX_RESULTS = 50;\n let totalSent = 0;\n let cancelled = false;\n\n const flush = (batch: MentionItemResponse[]) => {\n if (cancelled) return;\n const filtered = batch.filter(matchesQuery);\n if (filtered.length === 0) return;\n const remaining = MAX_RESULTS - totalSent;\n const toSend = filtered.slice(0, remaining);\n if (toSend.length > 0) {\n totalSent += toSend.length;\n try {\n controller.enqueue(\n enc.encode(JSON.stringify({ items: toSend }) + \"\\n\"),\n );\n } catch {\n // Stream was closed by client\n cancelled = true;\n }\n }\n };\n\n // All sources run in parallel; each flushes independently.\n const sources: Promise<void>[] = [];\n\n // 1. Resources from SQL (fast — flush first)\n sources.push(\n (async () => {\n try {\n const resources = mentionsOwner\n ? await resourceListAccessible(mentionsOwner)\n : [\n ...(await resourceList(WORKSPACE_OWNER)),\n ...(await resourceList(SHARED_OWNER)),\n ];\n flush(\n resources.map((r) => {\n const scope = resourceScopeForOwner(\n r.owner,\n mentionsOwner,\n );\n return {\n id: `resource:${r.path}`,\n label: r.path.split(\"/\").pop() || r.path,\n description: r.path,\n icon: \"file\",\n source: `resource:${scope}`,\n refType: \"file\",\n refPath: r.path,\n section: \"Files\",\n };\n }),\n );\n } catch {}\n })(),\n );\n\n // 2. Codebase files (dev mode only — can be slow on large repos)\n if (currentDevMode) {\n sources.push(\n (async () => {\n const codebaseFiles: Array<{\n path: string;\n name: string;\n type: \"file\" | \"folder\";\n }> = [];\n try {\n await collectFiles(process.cwd(), \"\", 0, codebaseFiles);\n } catch {}\n flush(\n codebaseFiles.map((f) => ({\n id: `codebase:${f.path}`,\n label: f.name,\n description: f.path !== f.name ? f.path : undefined,\n icon: f.type,\n source: \"codebase\",\n refType: \"file\",\n refPath: f.path,\n section: \"Files\",\n })),\n );\n })(),\n );\n }\n\n // 3. Custom mention providers (each flushes independently)\n for (const [key, provider] of Object.entries(mentionProviders)) {\n sources.push(\n (async () => {\n try {\n const providerItems = await provider.search(q, event);\n flush(\n providerItems.map((item) => ({\n id: item.id,\n label: item.label,\n description: item.description,\n icon: item.icon || provider.icon || \"file\",\n source: key,\n refType: item.refType,\n refPath: item.refPath,\n refId: item.refId,\n section: provider.label,\n })),\n );\n } catch (e) {\n console.error(\n `[agent-native] Mention provider \"${key}\" failed:`,\n e,\n );\n }\n })(),\n );\n }\n\n // 4. Custom workspace agents\n sources.push(\n (async () => {\n try {\n const owner = await getOwnerFromEvent(event);\n const { listAccessibleCustomAgents } =\n await import(\"../resources/agents.js\");\n const agents = await listAccessibleCustomAgents(owner);\n flush(\n agents.map((agent) => ({\n id: `custom-agent:${agent.id}`,\n label: agent.name,\n description: agent.description || agent.path,\n icon: \"agent\",\n source: \"agent:custom\",\n refType: \"custom-agent\",\n refPath: agent.path,\n refId: agent.id,\n section: \"Agents\",\n })),\n );\n } catch (e) {\n console.error(\n \"[agent-native] Custom agent discovery failed:\",\n e,\n );\n }\n })(),\n );\n\n // 5. Peer agent discovery (network call — often slowest)\n sources.push(\n (async () => {\n try {\n const agents = await discoverAgents(options?.appId);\n flush(\n agents.map((agent) => ({\n id: `agent:${agent.id}`,\n label: agent.name,\n description: agent.description,\n icon: \"agent\",\n source: \"agent\",\n refType: \"agent\",\n refPath: agent.url,\n refId: agent.id,\n section: \"Connected Agents\",\n })),\n );\n } catch (e) {\n console.error(\"[agent-native] Agent discovery failed:\", e);\n }\n })(),\n );\n\n await Promise.all(sources);\n if (!cancelled) controller.close();\n }\n }),\n );\n\n // ─── Generate thread title ──────────────────────────────────────────\n getH3App(nitroApp).use(\n `${routePath}/generate-title`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n const ownerEmail = await getOwnerFromEvent(event);\n\n // Per-user rate limit: 10 calls / 60s. Prevents an authenticated\n // user from spamming the endpoint to exhaust shared Anthropic\n // credits on platform-key deployments.\n const now = Date.now();\n const limitWindowMs = 60_000;\n const limitMax = 10;\n const recent = (generateTitleRateLimit.get(ownerEmail) ?? []).filter(\n (t) => now - t < limitWindowMs,\n );\n if (recent.length >= limitMax) {\n setResponseStatus(event, 429);\n return { error: \"Rate limit exceeded\" };\n }\n recent.push(now);\n generateTitleRateLimit.set(ownerEmail, recent);\n\n const body = await readBody(event);\n const message = body?.message;\n if (!message || typeof message !== \"string\") {\n setResponseStatus(event, 400);\n return { error: \"message is required\" };\n }\n // Strip mention markup: @[Name|type] → @Name\n const cleanMessage = message.replace(\n /@\\[([^\\]|]+)\\|[^\\]]*\\]/g,\n \"@$1\",\n );\n // Mirror the chat-run resolution so BYO-key users have title\n // generation billed to their own key instead of the platform key.\n const { getOwnerActiveApiKey } =\n await import(\"../agent/production-agent.js\");\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n const apiKey = userApiKey ?? process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n // Fallback: truncate the message\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n try {\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: \"claude-haiku-4-5-20251001\",\n max_tokens: 30,\n messages: [\n {\n role: \"user\",\n content: `Generate a very short title (3-6 words, no quotes) for a chat that starts with this message:\\n\\n${cleanMessage.slice(0, 500)}`,\n },\n ],\n }),\n });\n if (!res.ok) {\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n const data = (await res.json()) as {\n content?: Array<{ type: string; text?: string }>;\n };\n const text = data.content?.[0]?.text?.trim();\n return { title: text || cleanMessage.trim().slice(0, 60) };\n } catch {\n return { title: cleanMessage.trim().slice(0, 60) };\n }\n }),\n );\n\n // ─── Run management endpoints (for hot-reload resilience) ─────────────\n\n // GET /runs/active?threadId=X — check if there's an active run for a thread\n getH3App(nitroApp).use(\n `${routePath}/runs`,\n defineEventHandler(async (event) => {\n // Auth check — ensure the user is authenticated\n const owner = await getOwnerFromEvent(event);\n\n const method = getMethod(event);\n const url = event.node?.req?.url || event.path || \"\";\n\n // Authorization: a run's events/abort and a thread's active-run\n // status must only be exposed to the user who OWNS the thread.\n // agent_runs carries no owner column — ownership lives on the\n // chat_threads row via thread_id. callerOwnsRun/callerOwnsThread\n // (agent/run-ownership.ts) resolve the run's thread (in-memory first,\n // SQL fallback) and compare its ownerEmail. Without this, any\n // authenticated tenant who learns another tenant's runId/threadId\n // could stream their live agent turn (assistant text + tool-result\n // payloads) or abort their run.\n const ownsThread = (threadId: string | null | undefined) =>\n callerOwnsThread(owner, threadId);\n const ownsRun = (runId: string) => callerOwnsRun(owner, runId);\n\n // Route: GET /runs/list?goalId=agent-team|agent-harness\n // Returns background agents in the Code hub-compatible run shape.\n const listMatch =\n url.match(/\\/runs\\/list(?:[/?]|$)/) ||\n url.match(/^\\/list(?:[/?]|$)/);\n if (listMatch && method === \"GET\") {\n const query = getQuery(event);\n const goalId = query.goalId ? String(query.goalId) : undefined;\n const runs = await runWithRequestContext(\n { userEmail: owner },\n async () => {\n const runs: unknown[] = [];\n if (!goalId || goalId === \"agent-team\") {\n const { listAgentTeamBackgroundRuns } =\n await import(\"./agent-teams.js\");\n runs.push(...(await listAgentTeamBackgroundRuns()));\n }\n if (!goalId || goalId === \"agent-harness\") {\n const { listAgentHarnessBackgroundRuns } =\n await import(\"../agent/harness/background.js\");\n runs.push(\n ...(await listAgentHarnessBackgroundRuns({\n goalId: \"agent-harness\",\n ownerEmail: owner,\n })),\n );\n }\n return runs;\n },\n );\n return { status: \"ok\", goalId, runs };\n }\n\n // Route: POST /runs/:id/stop\n // Stops a running Agent Teams background run (durable task-based).\n // Distinct from /abort which operates on in-memory run-manager runs.\n const stopMatch =\n url.match(/\\/runs\\/([^/?]+)\\/stop/) ||\n url.match(/^\\/([^/?]+)\\/stop/);\n if (stopMatch && method === \"POST\") {\n const runId = decodeURIComponent(stopMatch[1]);\n const { stopAgentTeamBackgroundRun } =\n await import(\"./agent-teams.js\");\n let result = await runWithRequestContext({ userEmail: owner }, () =>\n stopAgentTeamBackgroundRun(runId),\n );\n if (!result.ok && result.error === \"Task not found\") {\n const { stopAgentHarnessBackgroundRun } =\n await import(\"../agent/harness/background.js\");\n result = await runWithRequestContext({ userEmail: owner }, () =>\n stopAgentHarnessBackgroundRun(runId, { ownerEmail: owner }),\n );\n }\n if (!result.ok) {\n setResponseStatus(\n event,\n result.error === \"Task not found\" ||\n result.error === \"Harness run not found\"\n ? 404\n : 400,\n );\n return { ok: false, error: result.error };\n }\n return { ok: true };\n }\n\n // Route: POST /runs/:id/abort\n // Match both full URL (/runs/{id}/abort) and h3 prefix-stripped (/{id}/abort)\n const abortMatch =\n url.match(/\\/runs\\/([^/?]+)\\/abort/) ||\n url.match(/^\\/([^/?]+)\\/abort/);\n if (abortMatch && method === \"POST\") {\n const runId = decodeURIComponent(abortMatch[1]);\n if (!(await ownsRun(runId))) {\n // 404 (not 403) so run existence isn't leaked to non-owners.\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n let reason = \"user\";\n try {\n const body = await readBody(event);\n if (body?.reason === \"no_progress\") {\n reason = \"no_progress\";\n }\n } catch {\n // Empty/invalid body — keep the default user abort reason.\n }\n abortRun(runId, reason); // Aborts in-memory + marks aborted in SQL\n return { ok: true };\n }\n\n // Route: GET /runs/:id/background-events\n // Returns Agent Teams transcript events in the shared background-run shape.\n const backgroundEventsMatch =\n url.match(/\\/runs\\/([^/?]+)\\/background-events/) ||\n url.match(/^\\/([^/?]+)\\/background-events/);\n if (backgroundEventsMatch && method === \"GET\") {\n const runId = decodeURIComponent(backgroundEventsMatch[1]);\n const {\n getAgentTeamBackgroundRun,\n listAgentTeamBackgroundTranscriptEvents,\n } = await import(\"./agent-teams.js\");\n const run = await runWithRequestContext({ userEmail: owner }, () =>\n getAgentTeamBackgroundRun(runId),\n );\n if (run) {\n const events = await runWithRequestContext(\n { userEmail: owner },\n () => listAgentTeamBackgroundTranscriptEvents(runId),\n );\n return { status: \"ok\", runId, events };\n }\n const {\n getAgentHarnessBackgroundRun,\n listAgentHarnessBackgroundTranscriptEvents,\n } = await import(\"../agent/harness/background.js\");\n const harnessRun = await runWithRequestContext(\n { userEmail: owner },\n () => getAgentHarnessBackgroundRun(runId, { ownerEmail: owner }),\n );\n if (!harnessRun) {\n setResponseStatus(event, 404);\n return { status: \"unavailable\", runId, events: [] };\n }\n const events = await runWithRequestContext(\n { userEmail: owner },\n () =>\n listAgentHarnessBackgroundTranscriptEvents(runId, {\n ownerEmail: owner,\n }),\n );\n return { status: \"ok\", runId, events };\n }\n\n // Route: GET /runs/:id/events?after=N\n // Match both full URL (/runs/{id}/events) and h3 prefix-stripped (/{id}/events)\n const eventsMatch =\n url.match(/\\/runs\\/([^/?]+)\\/events/) ||\n url.match(/^\\/([^/?]+)\\/events/);\n if (eventsMatch && method === \"GET\") {\n const runId = decodeURIComponent(eventsMatch[1]);\n if (!(await ownsRun(runId))) {\n // 404 (not 403) so run existence isn't leaked to non-owners.\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n const query = getQuery(event);\n const after = parseInt(String(query.after ?? \"0\"), 10) || 0;\n\n const stream = subscribeToRun(runId, after);\n if (!stream) {\n setResponseStatus(event, 404);\n return { error: \"Run not found\" };\n }\n\n setResponseHeader(event, \"Content-Type\", \"text/event-stream\");\n setResponseHeader(event, \"Cache-Control\", \"no-cache\");\n setResponseHeader(event, \"Connection\", \"keep-alive\");\n return stream;\n }\n\n // Route: GET /runs/active?threadId=X\n if (method === \"GET\") {\n const query = getQuery(event);\n const threadId = query.threadId ? String(query.threadId) : null;\n if (!threadId) {\n setResponseStatus(event, 400);\n return { error: \"threadId query parameter is required\" };\n }\n\n // Only reveal a thread's active run to the thread's owner.\n // Present non-owners (or unknown threads) as idle rather than\n // 404 so thread existence isn't leaked and the client polls\n // benignly.\n if (!(await ownsThread(threadId))) {\n return {\n active: false,\n threadId,\n status: \"idle\",\n heartbeatAt: null,\n lastProgressAt: null,\n };\n }\n\n // Check in-memory first, then SQL (cross-isolate on Workers)\n const run = await getActiveRunForThreadAsync(threadId);\n if (!run) {\n return {\n active: false,\n threadId,\n status: \"idle\",\n heartbeatAt: null,\n lastProgressAt: null,\n };\n }\n\n return {\n active: true,\n runId: run.runId,\n threadId: run.threadId,\n turnId: run.turnId,\n status: run.status,\n heartbeatAt: run.heartbeatAt,\n lastProgressAt: run.lastProgressAt,\n // Server clock so the client computes \"stuck\" elapsed time\n // server-relative, immune to client clock skew.\n serverNow: Date.now(),\n };\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // ─── Checkpoint endpoints ──────────────────────────────────────────────\n getH3App(nitroApp).use(\n `${routePath}/checkpoints`,\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n\n // GET /checkpoints?threadId=... — list checkpoints for a thread\n if (method === \"GET\") {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available in dev mode\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available on localhost\" };\n }\n const query = getQuery(event);\n const threadId = String(query.threadId || \"\");\n if (!threadId) {\n setResponseStatus(event, 400);\n return { error: \"threadId query parameter is required\" };\n }\n const owner = await getOwnerFromEvent(event);\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n try {\n const { getCheckpointsByThread } =\n await import(\"../checkpoints/store.js\");\n return await getCheckpointsByThread(threadId);\n } catch {\n return [];\n }\n }\n\n // POST /checkpoints — restore to a checkpoint\n // h3 prefix-matches, so /checkpoints/restore hits this handler with\n // event.path containing \"/restore\".\n const remainder = (event.path || \"\").replace(/^\\/+/, \"\");\n if (method === \"POST\" && remainder.startsWith(\"restore\")) {\n if (!canToggle) {\n setResponseStatus(event, 403);\n return { error: \"Checkpoints only available in dev mode\" };\n }\n if (!isLocalhost(event)) {\n setResponseStatus(event, 403);\n return { error: \"Restore only available on localhost\" };\n }\n const body = await readBody(event);\n const checkpointId = body?.checkpointId;\n if (!checkpointId) {\n setResponseStatus(event, 400);\n return { error: \"checkpointId is required\" };\n }\n try {\n const { getCheckpointById } =\n await import(\"../checkpoints/store.js\");\n const checkpoint = await getCheckpointById(checkpointId);\n if (!checkpoint) {\n setResponseStatus(event, 404);\n return { error: \"Checkpoint not found\" };\n }\n const owner = await getOwnerFromEvent(event);\n const thread = await getThread(checkpoint.threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Checkpoint not found\" };\n }\n const {\n createCheckpoint: gitCheckpoint,\n restoreToCheckpoint,\n hasUncommittedChanges,\n isGitRepo,\n } = await import(\"../checkpoints/service.js\");\n const cwd = process.cwd();\n if (!isGitRepo(cwd)) {\n setResponseStatus(event, 400);\n return { error: \"Not a git repository\" };\n }\n // Save current state before restoring so user can undo the undo\n if (hasUncommittedChanges(cwd)) {\n gitCheckpoint(cwd, \"[agent-native] Pre-restore checkpoint\");\n }\n const restored = restoreToCheckpoint(cwd, checkpoint.commitSha);\n if (!restored) {\n setResponseStatus(event, 500);\n return { error: \"Failed to restore checkpoint\" };\n }\n // Trigger UI refresh\n try {\n const { recordChange } = await import(\"./poll.js\");\n recordChange({\n source: \"checkpoint\",\n type: \"change\",\n key: \"*\",\n });\n } catch {}\n return { success: true, commitSha: checkpoint.commitSha };\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err?.message ?? \"Restore failed\" };\n }\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // ─── Thread management endpoints ──────────────────────────────────────\n // Single handler for /threads and /threads/:id — h3's use() does prefix\n // matching so we can't reliably split them into separate handlers.\n const parseScopeFromQuery = (\n q: Record<string, unknown>,\n ): ChatThreadScope | null => {\n const type = q.scopeType ? String(q.scopeType).trim() : \"\";\n const id = q.scopeId ? String(q.scopeId).trim() : \"\";\n if (!type || !id) return null;\n const label = q.scopeLabel ? String(q.scopeLabel) : undefined;\n return label ? { type, id, label } : { type, id };\n };\n const parseScopeFromBody = (raw: unknown): ChatThreadScope | null => {\n if (raw == null) return null;\n if (typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const type = typeof r.type === \"string\" ? r.type.trim() : \"\";\n const id = typeof r.id === \"string\" ? r.id.trim() : \"\";\n if (!type || !id) return null;\n const label = typeof r.label === \"string\" ? r.label : undefined;\n return label ? { type, id, label } : { type, id };\n };\n const parseForkSourceFromBody = (\n raw: unknown,\n ): ForkThreadSourceSnapshot | null => {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n if (typeof r.threadData !== \"string\") return null;\n const messageCount =\n typeof r.messageCount === \"number\"\n ? r.messageCount\n : Number(r.messageCount ?? 0);\n return {\n threadData: r.threadData,\n title: typeof r.title === \"string\" ? r.title : \"\",\n preview: typeof r.preview === \"string\" ? r.preview : \"\",\n messageCount,\n ...(Object.prototype.hasOwnProperty.call(r, \"scope\")\n ? { scope: parseScopeFromBody(r.scope) }\n : {}),\n };\n };\n const parseThreadRoute = (event: H3Event) => {\n const candidates = [event.path, event.node?.req?.url].filter(\n (value): value is string =>\n typeof value === \"string\" && value.length > 0,\n );\n for (const candidate of candidates) {\n const path = candidate.split(\"?\")[0];\n const parts = path.replace(/^\\/+/, \"\").split(\"/\").filter(Boolean);\n const threadsIndex = parts.lastIndexOf(\"threads\");\n if (threadsIndex >= 0) {\n const encodedId = parts[threadsIndex + 1];\n if (!encodedId) continue;\n return {\n threadId: decodeURIComponent(encodedId),\n tail: parts.slice(threadsIndex + 2),\n };\n }\n if (parts.length > 0) {\n return {\n threadId: decodeURIComponent(parts[0]),\n tail: parts.slice(1),\n };\n }\n }\n return { threadId: null, tail: [] as string[] };\n };\n getH3App(nitroApp).use(\n `${routePath}/threads`,\n defineEventHandler(async (event) => {\n const owner = await getOwnerFromEvent(event);\n const method = getMethod(event);\n\n const { threadId, tail: threadTail } = parseThreadRoute(event);\n const isThreadSubroute = (subroute: string) =>\n threadTail[0] === subroute;\n\n // ── Specific thread: GET/PUT/DELETE /threads/:id ──\n if (threadId) {\n if (method === \"GET\") {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return thread;\n }\n\n if (method === \"PUT\") {\n // Hold the thread_data lock for the full read-modify-write so\n // periodic saves from the frontend don't race with\n // onRunComplete / setThreadQueuedMessages / setThreadEngineMeta.\n // Without the lock, a client save that lands during an agent\n // run could clobber the assistant message the server just\n // appended (and vice versa).\n return await withThreadDataLock(threadId, async () => {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event);\n let newThreadData = body.threadData || thread.threadData;\n let newMessageCount = body.messageCount ?? thread.messageCount;\n let nextTitle =\n typeof body.title === \"string\" ? body.title : thread.title;\n const nextPreview =\n typeof body.preview === \"string\"\n ? body.preview\n : thread.preview;\n const preserveTitleOverride = (repo: unknown) => {\n if (\n repo &&\n typeof repo === \"object\" &&\n typeof (repo as { _titleOverride?: unknown })\n ._titleOverride === \"string\" &&\n (repo as { _titleOverride: string })._titleOverride.trim()\n ) {\n const meta = extractThreadMeta(repo);\n if (meta.title) nextTitle = meta.title;\n }\n };\n // Merge the incoming full-thread blob over the current SQL\n // copy. Periodic saves can be stale relative to server-side\n // run completion, and threadRuntime.export() does not carry\n // queuedMessages.\n if (body.threadData) {\n try {\n const existing = JSON.parse(thread.threadData);\n const incoming = JSON.parse(newThreadData);\n const merged = mergeThreadDataForClientSave(\n existing,\n incoming,\n );\n newThreadData = JSON.stringify(merged);\n if (Array.isArray(merged.messages)) {\n newMessageCount = merged.messages.length;\n }\n preserveTitleOverride(merged);\n } catch {\n // Invalid JSON in either side — fall back to raw body blob.\n }\n } else {\n try {\n preserveTitleOverride(JSON.parse(newThreadData));\n } catch {\n // Invalid JSON — keep the title supplied by the client.\n }\n }\n await updateThreadData(\n threadId,\n newThreadData,\n nextTitle,\n nextPreview,\n newMessageCount,\n );\n // Scope updates piggyback on the PUT — the client uses this\n // path for both \"detach\" (scope: null) and \"retag\" flows.\n // Send the field as `scope: undefined` (or omit it) when\n // you don't want to touch the existing scope.\n if (Object.prototype.hasOwnProperty.call(body, \"scope\")) {\n const incomingScope = parseScopeFromBody(body.scope);\n await setThreadScope(threadId, incomingScope);\n }\n return { ok: true };\n });\n }\n\n // POST /threads/:id/queued — debounced writes from the client\n // when the user adds/removes/dequeues a queued message. Keeps\n // queued messages durable across reloads without piggybacking\n // on full-thread saves.\n if (method === \"POST\" && isThreadSubroute(\"queued\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event);\n const queued = Array.isArray(body?.queuedMessages)\n ? body.queuedMessages\n : [];\n await setThreadQueuedMessages(threadId, queued);\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"rename\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n const title =\n typeof body?.title === \"string\"\n ? body.title.replace(/\\s+/g, \" \").trim().slice(0, 160)\n : \"\";\n if (!title) {\n setResponseStatus(event, 400);\n return { error: \"Title is required\" };\n }\n const renamed = await renameThread(threadId, title, {\n ownerEmail: owner,\n });\n if (!renamed) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"pin\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body?.pinned !== \"boolean\") {\n setResponseStatus(event, 400);\n return { error: \"pinned boolean is required\" };\n }\n const pinned = await setThreadPinned(threadId, body.pinned, {\n ownerEmail: owner,\n });\n if (!pinned) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n if (method === \"POST\" && isThreadSubroute(\"archive\")) {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body?.archived !== \"boolean\") {\n setResponseStatus(event, 400);\n return { error: \"archived boolean is required\" };\n }\n const archived = await setThreadArchived(\n threadId,\n body.archived,\n { ownerEmail: owner },\n );\n if (!archived) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return { ok: true };\n }\n\n // POST /threads/:id/fork — duplicate a thread with all its messages\n if (method === \"POST\" && isThreadSubroute(\"fork\")) {\n const body = await readBody(event);\n const forked = await forkThread(threadId, owner, {\n id: body?.id,\n source: parseForkSourceFromBody(body?.source),\n });\n if (!forked) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n return forked;\n }\n\n if (method === \"DELETE\") {\n const thread = await getThread(threadId);\n if (!thread || thread.ownerEmail !== owner) {\n setResponseStatus(event, 404);\n return { error: \"Thread not found\" };\n }\n await deleteThread(threadId);\n return { ok: true };\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // ── Thread list: GET/POST /threads ──\n if (method === \"GET\") {\n const query = getQuery(event);\n const limit = Math.min(\n parseInt(String(query.limit ?? \"50\"), 10) || 50,\n 200,\n );\n const q = query.q ? String(query.q).trim() : \"\";\n const scope = parseScopeFromQuery(query);\n const unscopedOnly = String(query.unscoped ?? \"\") === \"1\";\n if (q) {\n const threads = await searchThreads(owner, q, limit, {\n scope: scope ?? undefined,\n });\n return { threads };\n }\n const offset = parseInt(String(query.offset ?? \"0\"), 10) || 0;\n const threads = await listThreads(owner, {\n limit,\n offset,\n scope: scope ?? undefined,\n unscopedOnly,\n });\n return { threads };\n }\n\n if (method === \"POST\") {\n const body = await readBody(event);\n // Idempotent: when the caller supplies an id and a thread with\n // that id already exists for this owner, return it instead of\n // 500'ing on the UNIQUE constraint. The client can race with\n // the agent run's `persistSubmittedUserMessage` (which also\n // creates the thread on first message); we don't want either\n // racer's POST/onRunPrepared retry to wipe the thread out of\n // the user's history.\n if (body?.id) {\n const existing = await getThread(body.id);\n if (existing) {\n if (existing.ownerEmail === owner) return existing;\n setResponseStatus(event, 409);\n return { error: \"Thread id already in use\" };\n }\n }\n try {\n const thread = await createThread(owner, {\n id: body?.id,\n title: body?.title ?? \"\",\n scope: parseScopeFromBody(body?.scope),\n });\n return thread;\n } catch (err) {\n // Lost the create race against another in-flight POST or\n // against `persistSubmittedUserMessage`. Re-fetch and\n // return the row that actually landed.\n if (body?.id) {\n const existing = await getThread(body.id);\n if (existing && existing.ownerEmail === owner) return existing;\n }\n throw err;\n }\n }\n\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }),\n );\n\n // Mount the main chat handler — delegates to dev or prod handler based on current mode.\n // This is mounted last because h3's use() is prefix-based, meaning /_agent-native/agent-chat\n // also matches /_agent-native/agent-chat/threads/... — we skip sub-path requests here so the\n // earlier-mounted handlers (mode, save-key, files, skills, mentions, threads) handle them.\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler(async (event) => {\n // Skip sub-path requests — they're handled by earlier-mounted handlers\n const url = event.node?.req?.url || event.path || \"\";\n const afterBase = url.slice(\n url.indexOf(routePath) + routePath.length,\n );\n if (afterBase && afterBase !== \"/\" && !afterBase.startsWith(\"?\")) {\n // Not for us — return 404 so h3 doesn't swallow the request\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }\n\n // Resolve per-request auth context\n const ownerContext = await resolveOwnerContext(event);\n const owner = ownerContext.owner;\n\n // Resolve org ID: explicit callback > session.orgId from Better Auth\n // > implicit org membership. Better Auth leaves session.orgId null\n // until the user explicitly switches orgs, so a fresh signup with\n // implicit membership (e.g. domain-matched org) would otherwise see\n // no org-scoped credentials. getOrgContext() does the same DB lookup\n // the /builder/status endpoint uses to decide \"Connected\".\n let resolvedOrgId: string | undefined;\n if (options?.resolveOrgId) {\n resolvedOrgId = (await options.resolveOrgId(event)) ?? undefined;\n } else {\n try {\n const session = await getSession(event);\n resolvedOrgId = session?.orgId ?? undefined;\n } catch {\n // Session not available\n }\n if (!resolvedOrgId) {\n try {\n const { getOrgContext } = await import(\"../org/context.js\");\n const ctx = await getOrgContext(event);\n resolvedOrgId = ctx.orgId ?? undefined;\n } catch {\n // org_members table may not exist yet on first boot\n }\n }\n }\n\n // Propagate the caller's IANA timezone from `x-user-timezone` so that\n // tool calls made by the agent (e.g. log-meal with no explicit date)\n // resolve \"today\" in the user's local timezone instead of server UTC.\n const tzRaw = getHeader(event, \"x-user-timezone\");\n const timezone =\n typeof tzRaw === \"string\" &&\n tzRaw.trim().length > 0 &&\n tzRaw.trim().length < 64\n ? tzRaw.trim()\n : undefined;\n\n return runWithRequestContext(\n {\n userEmail: owner,\n userName: ownerContext.name,\n orgId: resolvedOrgId,\n timezone,\n },\n () => {\n // App-rendered chat can't host direct code edits — HMR/full\n // reloads would kill the same chat surface mid-run. Force the\n // prod handler (no shell / no fs); the prompt block injected by\n // `prodHandler.systemPrompt` then steers source changes to a\n // separate agent surface such as Builder or the dev frame.\n const blockInProductCodeEditing =\n shouldBlockInProductCodeEditing(event);\n const handler =\n ownerContext.anonymous && anonymousHandler\n ? anonymousHandler\n : !blockInProductCodeEditing && currentDevMode && devHandler\n ? devHandler\n : prodHandler;\n return handler(event);\n },\n );\n }),\n );\n\n // ─── Recurring Jobs Scheduler ──────────────────────────────────────\n // Poll every 60 seconds for due recurring jobs and execute them.\n // Uses setInterval so it works in all deployment environments without\n // requiring Nitro experimental tasks configuration.\n try {\n const { processRecurringJobs } = await import(\"../jobs/scheduler.js\");\n\n const schedulerDeps = {\n getActions: () => ({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...toolActions,\n }),\n getSystemPrompt: async (owner: string) => {\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return basePrompt + resources + schemaBlock;\n },\n apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,\n model: options?.model,\n appId: options?.appId,\n };\n\n // Start after a 10-second delay to let the server fully initialize\n setTimeout(() => {\n setInterval(() => {\n processRecurringJobs(schedulerDeps).catch((err) => {\n console.error(\"[recurring-jobs] Scheduler error:\", err?.message);\n });\n }, 60_000);\n if (process.env.DEBUG)\n console.log(\"[recurring-jobs] Scheduler started (60s interval)\");\n }, 10_000);\n } catch (err) {\n // Jobs module not available — skip silently\n }\n\n // ─── Agent Teams orphan sweep ─────────────────────────────────────\n // Re-fires stuck/queued dispatches when the browser is closed and the\n // RunsTray's per-user reconciliation never triggers. Runs every 2 minutes\n // per instance; cheap (one indexed query when no active tasks are found).\n // Throttled by the same per-owner interval guard inside reconcileAgentTeamRunsForOwner.\n (() => {\n // Track when this instance last ran the sweep so only one sweep fires\n // per 2-min window even if multiple timers fire in overlapping invocations.\n let lastSweep = 0;\n const SWEEP_INTERVAL_MS = 2 * 60 * 1000;\n\n setTimeout(() => {\n setInterval(() => {\n const now = Date.now();\n if (now - lastSweep < SWEEP_INTERVAL_MS) return;\n lastSweep = now;\n\n (async () => {\n // Query distinct owners that have active queue rows.\n // Can't use reconcileAgentTeamRunsForOwner directly without\n // knowing the owner set — query the run queue table first.\n const { getDbExec } = await import(\"../db/client.js\");\n const db = getDbExec();\n let rows: any[];\n try {\n const result = await db.execute(\n `SELECT DISTINCT owner_email FROM agent_team_run_queue WHERE status IN ('queued', 'running') AND owner_email IS NOT NULL LIMIT 50`,\n );\n rows = result.rows as any[];\n } catch {\n return; // Table may not exist yet on first boot\n }\n const { reconcileAgentTeamRunsForOwner } =\n await import(\"./agent-teams.js\");\n for (const row of rows) {\n const owner = String((row as any).owner_email ?? \"\").trim();\n if (!owner) continue;\n try {\n await reconcileAgentTeamRunsForOwner(owner);\n } catch {\n // best-effort per owner\n }\n }\n })().catch(() => {\n // best-effort — never break the server\n });\n }, 30_000); // Check every 30s but only sweep once per 2min\n }, 15_000); // Start 15s after init (after the scheduler)\n })();\n\n // ─── Trigger Dispatcher (event-based automations) ─────────────────\n try {\n const { initTriggerDispatcher } =\n await import(\"../triggers/dispatcher.js\");\n await initTriggerDispatcher({\n getActions: () => ({\n ...templateScripts,\n ...resourceScripts,\n ...docsScripts,\n ...(lazyContext ? frameworkContextTool : {}),\n ...chatScripts,\n ...jobTools,\n ...automationTools,\n ...notificationTools,\n ...progressTools,\n ...fetchTool,\n ...webSearchTool,\n ...toolActions,\n }),\n getSystemPrompt: async (owner: string) => {\n const resources = await loadResourcesForPrompt(\n owner,\n lazyContext,\n options?.appId,\n );\n const schemaBlock = lazyContext\n ? \"\"\n : await buildSchemaBlock(owner, false);\n return basePrompt + resources + schemaBlock;\n },\n apiKey: options?.apiKey ?? process.env.ANTHROPIC_API_KEY,\n model: options?.model,\n appId: options?.appId,\n });\n if (process.env.DEBUG)\n console.log(\"[triggers] Trigger dispatcher initialized\");\n } catch (err) {\n // Triggers module not available — skip silently\n }\n })().catch((err) => {\n // If the init fails, the routes never get registered and requests\n // to /_agent-native/agent-chat silently 404. Register a fallback\n // route so the user sees a meaningful error instead.\n const routePath = options?.path ?? \"/_agent-native/agent-chat\";\n const msg = (err as Error)?.message || String(err);\n console.error(\n `[agent-chat] Plugin init failed — registering error fallback: ${msg}`,\n );\n getH3App(nitroApp).use(\n routePath,\n defineEventHandler((event) => {\n setResponseStatus(event, 503);\n return {\n error: `Agent chat failed to initialize: ${msg}`,\n };\n }),\n );\n });\n trackPluginInit(nitroApp, initPromise, {\n paths: [\n options?.path ?? \"/_agent-native/agent-chat\",\n \"/_agent-native/actions\",\n \"/_agent-native/agent-model-defaults\",\n \"/_agent-native/mcp\",\n ],\n });\n };\n}\n\n/**\n * Default agent chat plugin with no template-specific actions.\n * In dev mode, provides file system, bash, and database tools.\n * In production, provides only the default system prompt.\n */\nexport const defaultAgentChatPlugin: NitroPluginDef = createAgentChatPlugin();\n\n// ---------------------------------------------------------------------------\n// MCP client glue — a shared manager reference + a /_agent-native/mcp/status\n// route so onboarding / settings UIs can see which MCP servers are live.\n// ---------------------------------------------------------------------------\n\nlet _globalMcpManager: McpClientManager | null = null;\n\nfunction setGlobalMcpManager(manager: McpClientManager): void {\n _globalMcpManager = manager;\n}\n\n/** Internal: access the current process's MCP client manager, if any. */\nexport function getGlobalMcpManager(): McpClientManager | null {\n return _globalMcpManager;\n}\n\nfunction mountMcpHubStatusRoute(nitroApp: any): void {\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpHubStatusMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n try {\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/hub/status\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n setResponseHeader(event, \"Content-Type\", \"application/json\");\n return getHubStatus();\n }),\n );\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to mount /_agent-native/mcp/hub/status: ${err?.message ?? err}`,\n );\n }\n}\n\nfunction mountMcpStatusRoute(nitroApp: any, manager: McpClientManager): void {\n // Idempotent per Nitro app; dev-all may host multiple templates in one process.\n const mountedApps: WeakSet<object> = ((\n globalThis as any\n ).__agentNativeMcpStatusMountedApps ??= new WeakSet<object>());\n if (mountedApps.has(nitroApp)) return;\n mountedApps.add(nitroApp);\n try {\n getH3App(nitroApp).use(\n \"/_agent-native/mcp/status\",\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n setResponseHeader(event, \"Content-Type\", \"application/json\");\n return manager.getStatus();\n }),\n );\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to mount /_agent-native/mcp/status: ${err?.message ?? err}`,\n );\n }\n}\n"]}
|