@agent-native/core 0.25.0 → 0.26.1

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.
Files changed (66) hide show
  1. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  2. package/dist/agent/engine/ai-sdk-engine.js +2 -1
  3. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  4. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -1
  5. package/dist/agent/engine/anthropic-engine.js +2 -1
  6. package/dist/agent/engine/anthropic-engine.js.map +1 -1
  7. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  8. package/dist/agent/engine/builder-engine.js +31 -12
  9. package/dist/agent/engine/builder-engine.js.map +1 -1
  10. package/dist/agent/engine/output-tokens.d.ts +8 -0
  11. package/dist/agent/engine/output-tokens.d.ts.map +1 -0
  12. package/dist/agent/engine/output-tokens.js +60 -0
  13. package/dist/agent/engine/output-tokens.js.map +1 -0
  14. package/dist/agent/production-agent.d.ts +2 -1
  15. package/dist/agent/production-agent.d.ts.map +1 -1
  16. package/dist/agent/production-agent.js +66 -25
  17. package/dist/agent/production-agent.js.map +1 -1
  18. package/dist/cli/skills.d.ts.map +1 -1
  19. package/dist/cli/skills.js +33 -7
  20. package/dist/cli/skills.js.map +1 -1
  21. package/dist/client/AssistantChat.d.ts.map +1 -1
  22. package/dist/client/AssistantChat.js +3 -1
  23. package/dist/client/AssistantChat.js.map +1 -1
  24. package/dist/client/index.d.ts +3 -1
  25. package/dist/client/index.d.ts.map +1 -1
  26. package/dist/client/index.js +3 -1
  27. package/dist/client/index.js.map +1 -1
  28. package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
  29. package/dist/client/settings/useBuilderStatus.js +106 -49
  30. package/dist/client/settings/useBuilderStatus.js.map +1 -1
  31. package/dist/client/settings/useBuilderStatus.spec.js +58 -0
  32. package/dist/client/settings/useBuilderStatus.spec.js.map +1 -1
  33. package/dist/client/use-external-value.d.ts +17 -0
  34. package/dist/client/use-external-value.d.ts.map +1 -0
  35. package/dist/client/use-external-value.js +29 -0
  36. package/dist/client/use-external-value.js.map +1 -0
  37. package/dist/collab/client.d.ts +18 -0
  38. package/dist/collab/client.d.ts.map +1 -1
  39. package/dist/collab/client.js +81 -2
  40. package/dist/collab/client.js.map +1 -1
  41. package/dist/mcp/build-server.d.ts +13 -0
  42. package/dist/mcp/build-server.d.ts.map +1 -1
  43. package/dist/mcp/build-server.js +47 -1
  44. package/dist/mcp/build-server.js.map +1 -1
  45. package/dist/mcp/server.d.ts.map +1 -1
  46. package/dist/mcp/server.js +3 -0
  47. package/dist/mcp/server.js.map +1 -1
  48. package/dist/scripts/docs/search.d.ts.map +1 -1
  49. package/dist/scripts/docs/search.js +52 -6
  50. package/dist/scripts/docs/search.js.map +1 -1
  51. package/dist/server/agent-chat-plugin.d.ts +16 -0
  52. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  53. package/dist/server/agent-chat-plugin.js +92 -80
  54. package/dist/server/agent-chat-plugin.js.map +1 -1
  55. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  56. package/dist/server/core-routes-plugin.js +6 -6
  57. package/dist/server/core-routes-plugin.js.map +1 -1
  58. package/dist/server/create-server.d.ts.map +1 -1
  59. package/dist/server/create-server.js +5 -1
  60. package/dist/server/create-server.js.map +1 -1
  61. package/dist/vite/client.d.ts.map +1 -1
  62. package/dist/vite/client.js +1 -0
  63. package/dist/vite/client.js.map +1 -1
  64. package/docs/content/skills-guide.md +6 -2
  65. package/docs/content/template-assets.md +3 -0
  66. package/package.json +1 -2
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AACZ,OAAO,EA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C,EAAE,GAChD,MAAM,MAAM,CAAC,+DAA+D,CAAC,CAAC;IAChF,MAAM,SAAS,GAAG,IAAI,wCAAwC,CAAC;QAC7D,kBAAkB,EAAE,SAAS,EAAE,oCAAoC;KACpE,CAAC,CAAC;IACH,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,UAAU,GAAG,eAAe,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAClD,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,aAAa,CAC5C,UAAU,EACV,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,QAAQ,CACtB,QAAa,EACb,MAAiB,EACjB,WAAW,GAAG,gBAAgB;IAE9B,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,GAAG,WAAW,MAAM,EACpB,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjC,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CACH,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport { buildMcpOAuthChallenge, getMcpOAuthResource } from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host = getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n return {\n origin,\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host = headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n let url = `${proto}://${host}/_agent-native/mcp`;\n try {\n if (src?.url) url = new URL(src.url).href;\n } catch {\n // keep the synthesized URL\n }\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Node fast-path** (real Node HTTP server): unchanged — delegate to the\n * SDK's `StreamableHTTPServerTransport.handleRequest(nodeReq, nodeRes,\n * body)`, which writes directly to the Node response (full protocol incl.\n * SSE).\n * - **Web-standard fallback** (Nitro 3 / Netlify web runtime, Cloudflare,\n * Deno, Bun — where there is no Node req/res): build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthResource(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n\n if (nodeReq && nodeRes) {\n // ---- Node fast-path (UNCHANGED behavior) --------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard fallback (Nitro 3 / Netlify web runtime, CF, Deno,\n // Bun) ---------------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GAInB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAE/E,6EAA6E;AAC7E,4EAA4E;AAC5E,yDAAyD;AACzD,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AAGF,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,KAAc;IAInC,MAAM,CAAC,GAAG,KAAY,CAAC;IACvB,MAAM,OAAO,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC;IACzD,MAAM,OAAO,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC;IACzD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AAC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AC,CAAC,GAAG,CACpB,GAAG,WAAW,MAAM,EACpB,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjC,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CACH,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport { buildMcpOAuthChallenge, getMcpOAuthResource } from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host = getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host = headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n let url = `${proto}://${host}/_agent-native/mcp`;\n try {\n if (src?.url) url = new URL(src.url).href;\n } catch {\n // keep the synthesized URL\n }\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Node fast-path** (real Node HTTP server): unchanged — delegate to the\n * SDK's `StreamableHTTPServerTransport.handleRequest(nodeReq, nodeRes,\n * body)`, which writes directly to the Node response (full protocol incl.\n * SSE).\n * - **Web-standard fallback** (Nitro 3 / Netlify web runtime, Cloudflare,\n * Deno, Bun — where there is no Node req/res): build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthResource(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n\n if (nodeReq && nodeRes) {\n // ---- Node fast-path (UNCHANGED behavior) --------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard fallback (Nitro 3 / Netlify web runtime, CF, Deno,\n // Bun) ---------------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../src/scripts/docs/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAsFH,wBAA8B,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAyD5E"}
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../src/scripts/docs/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAsIH,wBAA8B,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAyD5E"}
@@ -28,7 +28,7 @@ function parseFrontmatter(raw) {
28
28
  }
29
29
  return { data, body: match[2] };
30
30
  }
31
- function loadAllDocs() {
31
+ function loadFilesystemDocs() {
32
32
  const docsDir = getDocsDir();
33
33
  if (!fs.existsSync(docsDir))
34
34
  return [];
@@ -45,8 +45,54 @@ function loadAllDocs() {
45
45
  };
46
46
  });
47
47
  }
48
- function searchDocs(query) {
49
- const docs = loadAllDocs();
48
+ function slugifyDocId(value) {
49
+ return value
50
+ .trim()
51
+ .toLowerCase()
52
+ .replace(/[^a-z0-9]+/g, "-")
53
+ .replace(/^-+|-+$/g, "");
54
+ }
55
+ async function loadAgentBundleDocs() {
56
+ try {
57
+ const { loadAgentsBundle } = await import("../../server/agents-bundle.js");
58
+ const bundle = await loadAgentsBundle();
59
+ const docs = [];
60
+ if (bundle.workspaceAgentsMd?.trim()) {
61
+ docs.push({
62
+ slug: "agents-workspace",
63
+ title: "Workspace AGENTS.md",
64
+ description: "Full bundled workspace-level agent instructions.",
65
+ body: bundle.workspaceAgentsMd,
66
+ });
67
+ }
68
+ if (bundle.agentsMd?.trim()) {
69
+ docs.push({
70
+ slug: "agents-template",
71
+ title: "Template AGENTS.md",
72
+ description: "Full bundled template/app agent instructions.",
73
+ body: bundle.agentsMd,
74
+ });
75
+ }
76
+ for (const skill of Object.values(bundle.skills)) {
77
+ const slug = `skill-${slugifyDocId(skill.meta.name)}`;
78
+ docs.push({
79
+ slug,
80
+ title: `Skill: ${skill.meta.name}`,
81
+ description: skill.meta.description,
82
+ body: skill.content,
83
+ });
84
+ }
85
+ return docs;
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ }
91
+ async function loadAllDocs() {
92
+ return [...loadFilesystemDocs(), ...(await loadAgentBundleDocs())];
93
+ }
94
+ async function searchDocs(query) {
95
+ const docs = await loadAllDocs();
50
96
  const terms = query.toLowerCase().split(/\s+/);
51
97
  const scored = docs
52
98
  .map((doc) => {
@@ -86,7 +132,7 @@ Options:
86
132
  return;
87
133
  }
88
134
  if (parsed.list === "true") {
89
- const docs = loadAllDocs();
135
+ const docs = await loadAllDocs();
90
136
  const listing = docs.map((d) => ({
91
137
  slug: d.slug,
92
138
  title: d.title,
@@ -96,7 +142,7 @@ Options:
96
142
  return;
97
143
  }
98
144
  if (parsed.slug) {
99
- const docs = loadAllDocs();
145
+ const docs = await loadAllDocs();
100
146
  const doc = docs.find((d) => d.slug === parsed.slug);
101
147
  if (!doc) {
102
148
  console.log(`Doc not found: ${parsed.slug}`);
@@ -110,7 +156,7 @@ Options:
110
156
  return;
111
157
  }
112
158
  if (parsed.query) {
113
- const results = searchDocs(parsed.query);
159
+ const results = await searchDocs(parsed.query);
114
160
  if (results.length === 0) {
115
161
  console.log(`No docs found matching "${parsed.query}".`);
116
162
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"search.js","sourceRoot":"","sources":["../../../src/scripts/docs/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAYxC,SAAS,UAAU;IACjB,6EAA6E;IAC7E,OAAO,IAAI,CAAC,OAAO,CACjB,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,EAC/C,uBAAuB,CACxB,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAW;IAInC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC;IACtE,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;IAE3C,MAAM,IAAI,GAA2B,EAAE,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;QAChD,IAAI,CAAC;YAAE,IAAI,CAAC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;QAChC,IAAI,GAAG,CAAC,WAAW;YAAE,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,WAAW,IAAI,CAAC,CAAC;QACzD,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO;IACT,CAAC;IAED,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,2BAA2B,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC;YACzD,OAAO;QACT,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,SAAS,OAAO,CAAC,MAAM,qBAAqB,MAAM,CAAC,KAAK,MAAM,CAAC,CAAC;QAC5E,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YACzC,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,IAAI,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;YAClD,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;QACzD,OAAO;IACT,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,6DAA6D,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["/**\n * Core script: docs-search\n *\n * Search and read agent-native framework documentation.\n * Docs are bundled in @agent-native/core so they're always the right version.\n *\n * Usage:\n * pnpm action docs-search --query \"actions\"\n * pnpm action docs-search --slug authentication\n * pnpm action docs-search --list\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseArgs } from \"../utils.js\";\n\ninterface DocMeta {\n slug: string;\n title: string;\n description: string;\n}\n\ninterface DocFull extends DocMeta {\n body: string;\n}\n\nfunction getDocsDir(): string {\n // Resolve from the package root: src/scripts/docs/search.ts -> docs/content/\n return path.resolve(\n path.dirname(new URL(import.meta.url).pathname),\n \"../../../docs/content\",\n );\n}\n\nfunction parseFrontmatter(raw: string): {\n data: Record<string, string>;\n body: string;\n} {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) return { data: {}, body: raw };\n\n const data: Record<string, string> = {};\n for (const line of match[1].split(\"\\n\")) {\n const m = line.match(/^(\\w+):\\s*\"?(.*?)\"?\\s*$/);\n if (m) data[m[1]] = m[2];\n }\n return { data, body: match[2] };\n}\n\nfunction loadAllDocs(): DocFull[] {\n const docsDir = getDocsDir();\n if (!fs.existsSync(docsDir)) return [];\n\n const files = fs.readdirSync(docsDir).filter((f) => f.endsWith(\".md\"));\n return files.map((file) => {\n const raw = fs.readFileSync(path.join(docsDir, file), \"utf-8\");\n const slug = file.replace(/\\.md$/, \"\");\n const { data, body } = parseFrontmatter(raw);\n return {\n slug,\n title: data.title || slug,\n description: data.description || \"\",\n body,\n };\n });\n}\n\nfunction searchDocs(query: string): DocMeta[] {\n const docs = loadAllDocs();\n const terms = query.toLowerCase().split(/\\s+/);\n\n const scored = docs\n .map((doc) => {\n const searchText =\n `${doc.title} ${doc.description} ${doc.body}`.toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (doc.title.toLowerCase().includes(term)) score += 10;\n if (doc.description.toLowerCase().includes(term)) score += 5;\n if (doc.slug.includes(term)) score += 8;\n // Count body occurrences\n const bodyMatches = searchText.split(term).length - 1;\n score += Math.min(bodyMatches, 5);\n }\n return { doc, score };\n })\n .filter((item) => item.score > 0)\n .sort((a, b) => b.score - a.score);\n\n return scored.map(({ doc }) => ({\n slug: doc.slug,\n title: doc.title,\n description: doc.description,\n }));\n}\n\nexport default async function docsSearchScript(args: string[]): Promise<void> {\n const parsed = parseArgs(args);\n\n if (parsed.help === \"true\") {\n console.log(`Usage: pnpm action docs-search [options]\n\nOptions:\n --query <text> Search docs by keyword (returns matching pages)\n --slug <slug> Read a specific doc page by slug\n --list List all available doc pages\n --help Show this help message`);\n return;\n }\n\n if (parsed.list === \"true\") {\n const docs = loadAllDocs();\n const listing = docs.map((d) => ({\n slug: d.slug,\n title: d.title,\n description: d.description,\n }));\n console.log(JSON.stringify(listing, null, 2));\n return;\n }\n\n if (parsed.slug) {\n const docs = loadAllDocs();\n const doc = docs.find((d) => d.slug === parsed.slug);\n if (!doc) {\n console.log(`Doc not found: ${parsed.slug}`);\n console.log(`Available: ${docs.map((d) => d.slug).join(\", \")}`);\n return;\n }\n console.log(`# ${doc.title}\\n`);\n if (doc.description) console.log(`${doc.description}\\n`);\n console.log(doc.body);\n return;\n }\n\n if (parsed.query) {\n const results = searchDocs(parsed.query);\n if (results.length === 0) {\n console.log(`No docs found matching \"${parsed.query}\".`);\n return;\n }\n console.log(`Found ${results.length} doc(s) matching \"${parsed.query}\":\\n`);\n for (const result of results.slice(0, 8)) {\n console.log(` ${result.slug} — ${result.title}`);\n if (result.description) {\n console.log(` ${result.description}`);\n }\n }\n console.log(`\\nUse --slug <slug> to read the full doc.`);\n return;\n }\n\n console.log(\"Provide --query, --slug, or --list. Use --help for details.\");\n}\n"]}
1
+ {"version":3,"file":"search.js","sourceRoot":"","sources":["../../../src/scripts/docs/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAYxC,SAAS,UAAU;IACjB,6EAA6E;IAC7E,OAAO,IAAI,CAAC,OAAO,CACjB,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,E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,CAAC,GAAG,CAAC,SAAS,OAAO,CAAC,MAAM,qBAAqB,MAAM,CAAC,KAAK,MAAM,CAAC,CAAC;QAC5E,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YACzC,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,IAAI,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;YAClD,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,2CAA2C,CAAC,CAAC;QACzD,OAAO;IACT,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,6DAA6D,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["/**\n * Core script: docs-search\n *\n * Search and read agent-native framework documentation.\n * Docs are bundled in @agent-native/core so they're always the right version.\n *\n * Usage:\n * pnpm action docs-search --query \"actions\"\n * pnpm action docs-search --slug authentication\n * pnpm action docs-search --list\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseArgs } from \"../utils.js\";\n\ninterface DocMeta {\n slug: string;\n title: string;\n description: string;\n}\n\ninterface DocFull extends DocMeta {\n body: string;\n}\n\nfunction getDocsDir(): string {\n // Resolve from the package root: src/scripts/docs/search.ts -> docs/content/\n return path.resolve(\n path.dirname(new URL(import.meta.url).pathname),\n \"../../../docs/content\",\n );\n}\n\nfunction parseFrontmatter(raw: string): {\n data: Record<string, string>;\n body: string;\n} {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/);\n if (!match) return { data: {}, body: raw };\n\n const data: Record<string, string> = {};\n for (const line of match[1].split(\"\\n\")) {\n const m = line.match(/^(\\w+):\\s*\"?(.*?)\"?\\s*$/);\n if (m) data[m[1]] = m[2];\n }\n return { data, body: match[2] };\n}\n\nfunction loadFilesystemDocs(): DocFull[] {\n const docsDir = getDocsDir();\n if (!fs.existsSync(docsDir)) return [];\n\n const files = fs.readdirSync(docsDir).filter((f) => f.endsWith(\".md\"));\n return files.map((file) => {\n const raw = fs.readFileSync(path.join(docsDir, file), \"utf-8\");\n const slug = file.replace(/\\.md$/, \"\");\n const { data, body } = parseFrontmatter(raw);\n return {\n slug,\n title: data.title || slug,\n description: data.description || \"\",\n body,\n };\n });\n}\n\nfunction slugifyDocId(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nasync function loadAgentBundleDocs(): Promise<DocFull[]> {\n try {\n const { loadAgentsBundle } = await import(\"../../server/agents-bundle.js\");\n const bundle = await loadAgentsBundle();\n const docs: DocFull[] = [];\n if (bundle.workspaceAgentsMd?.trim()) {\n docs.push({\n slug: \"agents-workspace\",\n title: \"Workspace AGENTS.md\",\n description: \"Full bundled workspace-level agent instructions.\",\n body: bundle.workspaceAgentsMd,\n });\n }\n if (bundle.agentsMd?.trim()) {\n docs.push({\n slug: \"agents-template\",\n title: \"Template AGENTS.md\",\n description: \"Full bundled template/app agent instructions.\",\n body: bundle.agentsMd,\n });\n }\n for (const skill of Object.values(bundle.skills)) {\n const slug = `skill-${slugifyDocId(skill.meta.name)}`;\n docs.push({\n slug,\n title: `Skill: ${skill.meta.name}`,\n description: skill.meta.description,\n body: skill.content,\n });\n }\n return docs;\n } catch {\n return [];\n }\n}\n\nasync function loadAllDocs(): Promise<DocFull[]> {\n return [...loadFilesystemDocs(), ...(await loadAgentBundleDocs())];\n}\n\nasync function searchDocs(query: string): Promise<DocMeta[]> {\n const docs = await loadAllDocs();\n const terms = query.toLowerCase().split(/\\s+/);\n\n const scored = docs\n .map((doc) => {\n const searchText =\n `${doc.title} ${doc.description} ${doc.body}`.toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (doc.title.toLowerCase().includes(term)) score += 10;\n if (doc.description.toLowerCase().includes(term)) score += 5;\n if (doc.slug.includes(term)) score += 8;\n // Count body occurrences\n const bodyMatches = searchText.split(term).length - 1;\n score += Math.min(bodyMatches, 5);\n }\n return { doc, score };\n })\n .filter((item) => item.score > 0)\n .sort((a, b) => b.score - a.score);\n\n return scored.map(({ doc }) => ({\n slug: doc.slug,\n title: doc.title,\n description: doc.description,\n }));\n}\n\nexport default async function docsSearchScript(args: string[]): Promise<void> {\n const parsed = parseArgs(args);\n\n if (parsed.help === \"true\") {\n console.log(`Usage: pnpm action docs-search [options]\n\nOptions:\n --query <text> Search docs by keyword (returns matching pages)\n --slug <slug> Read a specific doc page by slug\n --list List all available doc pages\n --help Show this help message`);\n return;\n }\n\n if (parsed.list === \"true\") {\n const docs = await loadAllDocs();\n const listing = docs.map((d) => ({\n slug: d.slug,\n title: d.title,\n description: d.description,\n }));\n console.log(JSON.stringify(listing, null, 2));\n return;\n }\n\n if (parsed.slug) {\n const docs = await loadAllDocs();\n const doc = docs.find((d) => d.slug === parsed.slug);\n if (!doc) {\n console.log(`Doc not found: ${parsed.slug}`);\n console.log(`Available: ${docs.map((d) => d.slug).join(\", \")}`);\n return;\n }\n console.log(`# ${doc.title}\\n`);\n if (doc.description) console.log(`${doc.description}\\n`);\n console.log(doc.body);\n return;\n }\n\n if (parsed.query) {\n const results = await searchDocs(parsed.query);\n if (results.length === 0) {\n console.log(`No docs found matching \"${parsed.query}\".`);\n return;\n }\n console.log(`Found ${results.length} doc(s) matching \"${parsed.query}\":\\n`);\n for (const result of results.slice(0, 8)) {\n console.log(` ${result.slug} — ${result.title}`);\n if (result.description) {\n console.log(` ${result.description}`);\n }\n }\n console.log(`\\nUse --slug <slug> to read the full doc.`);\n return;\n }\n\n console.log(\"Provide --query, --slug, or --list. Use --help for details.\");\n}\n"]}
@@ -48,6 +48,22 @@ export interface AgentChatPluginOptions {
48
48
  mentionProviders?: Record<string, MentionProvider> | (() => Record<string, MentionProvider> | Promise<Record<string, MentionProvider>>);
49
49
  /** App ID used to exclude self from agent discovery (e.g., "mail", "calendar") */
50
50
  appId?: string;
51
+ /** Optional MCP server branding surfaced during the initialize handshake. */
52
+ mcpServerInfo?: {
53
+ /** Human-facing title. Defaults to the capitalized app id/name. */
54
+ title?: string;
55
+ /** Host-facing description. Defaults to "Agent-native <app> agent". */
56
+ description?: string;
57
+ /** Canonical app URL. Relative URLs are resolved against the request origin. */
58
+ websiteUrl?: string;
59
+ /** App icons. Relative `src` values are resolved against the request origin. */
60
+ icons?: Array<{
61
+ src: string;
62
+ mimeType?: string;
63
+ sizes?: string[];
64
+ theme?: "light" | "dark";
65
+ }>;
66
+ };
51
67
  /**
52
68
  * Optional callback to resolve the org ID for the current request.
53
69
  * When provided, the resolved value is set as AGENT_ORG_ID env var so
@@ -1 +1 @@
1
- {"version":3,"file":"agent-chat-plugin.d.ts","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAaA,OAAO,EASL,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AAqBtC,OAAO,KAAK,EACV,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAElB,eAAe,EAEhB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,gBAAgB,EAajB,MAAM,wBAAwB,CAAC;AA+DhC,OAAO,EAGL,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EAC1B,MAAM,6BAA6B,CAAC;AA+SrC,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GACnC,KAAK,CAAC;IACP,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;CACzC,CAAC,CASD;AAmBD,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,SAAS,cAAc,EAAE,EACjC,WAAW,EAAE,SAAS,oBAAoB,EA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M,GAAG,IAAI,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB,GAAG,OAAO,CA2BV;AAED,wBAAgB,qBAAqB,CACnC,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc,CA62GhB;AAED;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,cAAwC,CAAC;AAa9E,yEAAyE;AACzE,wBAAgB,mBAAmB,IAAI,gBAAgB,GAAG,IAAI,CAE7D"}
@@ -37,6 +37,14 @@ async function lazyFs() {
37
37
  return _fs;
38
38
  }
39
39
  const SHARED_PROMPT_RESOURCE_MAX_CHARS = 30_000;
40
+ const COMPACT_PROMPT_RESOURCE_MAX_CHARS = 12_000;
41
+ const MAX_ACTION_SUMMARY_DESCRIPTION_CHARS = 140;
42
+ function compactPromptLine(value, maxChars) {
43
+ const line = value.replace(/\s+/g, " ").trim();
44
+ if (line.length <= maxChars)
45
+ return line;
46
+ return `${line.slice(0, maxChars - 1)}…`;
47
+ }
40
48
  const SHARED_RESOURCE_INDEX_LIMIT = 40;
41
49
  function normalizeResourcePathForPrompt(path) {
42
50
  return path.replace(/^\/+/, "").trim();
@@ -44,18 +52,20 @@ function normalizeResourcePathForPrompt(path) {
44
52
  function escapeXmlAttribute(value) {
45
53
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
46
54
  }
47
- function truncatePromptResourceContent(content, path, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS) {
55
+ function truncatePromptResourceContent(content, path, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS, readHint) {
48
56
  const trimmed = content.trim();
49
57
  if (trimmed.length <= maxChars)
50
58
  return trimmed;
51
59
  const omitted = trimmed.length - maxChars;
52
- return `${trimmed.slice(0, maxChars)}\n\n[Resource ${path} truncated after ${maxChars.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted. Use resource-read --path "${path}" with the resource's scope for the full content.]`;
60
+ const hint = readHint ??
61
+ `Use resource-read --path "${path}" with the resource's scope for the full content.`;
62
+ return `${trimmed.slice(0, maxChars)}\n\n[Resource ${path} truncated after ${maxChars.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted. ${hint}]`;
53
63
  }
54
64
  function promptResourceBlock(input) {
55
65
  const normalizedPath = input.path
56
66
  ? normalizeResourcePathForPrompt(input.path)
57
67
  : undefined;
58
- const content = truncatePromptResourceContent(input.content, normalizedPath ?? input.name, input.maxChars);
68
+ const content = truncatePromptResourceContent(input.content, normalizedPath ?? input.name, input.maxChars, input.readHint);
59
69
  if (!content)
60
70
  return null;
61
71
  const pathAttr = normalizedPath
@@ -112,7 +122,7 @@ function resourceScopeForOwner(owner, currentOwner) {
112
122
  return "personal";
113
123
  return "resource";
114
124
  }
115
- async function loadAgentsResourceForPrompt(owner, scope) {
125
+ async function loadAgentsResourceForPrompt(owner, scope, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS) {
116
126
  try {
117
127
  const agents = await resourceGetByPath(owner, "AGENTS.md");
118
128
  if (!agents?.content?.trim())
@@ -122,13 +132,14 @@ async function loadAgentsResourceForPrompt(owner, scope) {
122
132
  scope,
123
133
  path: "AGENTS.md",
124
134
  content: agents.content,
135
+ maxChars,
125
136
  });
126
137
  }
127
138
  catch {
128
139
  return null;
129
140
  }
130
141
  }
131
- async function loadInstructionResourcesForPrompt(owner, scope) {
142
+ async function loadInstructionResourcesForPrompt(owner, scope, maxChars = SHARED_PROMPT_RESOURCE_MAX_CHARS) {
132
143
  try {
133
144
  const resources = await resourceList(owner, "instructions/");
134
145
  const blocks = [];
@@ -144,6 +155,7 @@ async function loadInstructionResourcesForPrompt(owner, scope) {
144
155
  scope,
145
156
  path: resource.path,
146
157
  content: full.content,
158
+ maxChars,
147
159
  });
148
160
  if (block)
149
161
  blocks.push(block);
@@ -2019,17 +2031,38 @@ const DEFAULT_SYSTEM_PROMPT = PROD_FRAMEWORK_PROMPT;
2019
2031
  export async function loadResourcesForPrompt(owner, compact = false, selfAppId) {
2020
2032
  await ensurePersonalDefaults(owner);
2021
2033
  const sections = [];
2034
+ const promptResourceMaxChars = compact
2035
+ ? COMPACT_PROMPT_RESOURCE_MAX_CHARS
2036
+ : SHARED_PROMPT_RESOURCE_MAX_CHARS;
2022
2037
  // 1. Workspace AGENTS.md + skills merged into the template bundle.
2023
2038
  try {
2024
2039
  const { loadAgentsBundle, generateSkillsPromptBlock } = await import("./agents-bundle.js");
2025
2040
  const bundle = await loadAgentsBundle();
2026
2041
  // Workspace-core AGENTS.md (enterprise-wide instructions), if present.
2027
2042
  if (bundle.workspaceAgentsMd && bundle.workspaceAgentsMd.trim()) {
2028
- sections.push(`<resource name="AGENTS.md" scope="workspace">\n${bundle.workspaceAgentsMd.trim()}\n</resource>`);
2043
+ const block = promptResourceBlock({
2044
+ name: "AGENTS.md",
2045
+ scope: "workspace",
2046
+ path: "AGENTS.md",
2047
+ content: bundle.workspaceAgentsMd,
2048
+ maxChars: promptResourceMaxChars,
2049
+ readHint: 'Use docs-search --slug "agents-workspace" to read the full workspace AGENTS.md.',
2050
+ });
2051
+ if (block)
2052
+ sections.push(block);
2029
2053
  }
2030
2054
  // 2. Template AGENTS.md — always included (critical template instructions).
2031
2055
  if (bundle.agentsMd.trim()) {
2032
- sections.push(`<resource name="AGENTS.md" scope="template">\n${bundle.agentsMd.trim()}\n</resource>`);
2056
+ const block = promptResourceBlock({
2057
+ name: "AGENTS.md",
2058
+ scope: "template",
2059
+ path: "AGENTS.md",
2060
+ content: bundle.agentsMd,
2061
+ maxChars: promptResourceMaxChars,
2062
+ readHint: 'Use docs-search --slug "agents-template" to read the full template AGENTS.md.',
2063
+ });
2064
+ if (block)
2065
+ sections.push(block);
2033
2066
  }
2034
2067
  // In compact mode, skip the full skills block — the agent can use
2035
2068
  // `docs-search` to find skills when it needs them.
@@ -2048,23 +2081,23 @@ export async function loadResourcesForPrompt(owner, compact = false, selfAppId)
2048
2081
  catch { }
2049
2082
  // 3. Runtime workspace resources from SQL. These are global defaults
2050
2083
  // inherited by every app in the workspace, not copied into app scopes.
2051
- const workspaceAgents = await loadAgentsResourceForPrompt(WORKSPACE_OWNER, "workspace");
2084
+ const workspaceAgents = await loadAgentsResourceForPrompt(WORKSPACE_OWNER, "workspace", promptResourceMaxChars);
2052
2085
  if (workspaceAgents)
2053
2086
  sections.push(workspaceAgents);
2054
- sections.push(...(await loadInstructionResourcesForPrompt(WORKSPACE_OWNER, "workspace-instruction")));
2087
+ sections.push(...(await loadInstructionResourcesForPrompt(WORKSPACE_OWNER, "workspace-instruction", promptResourceMaxChars)));
2055
2088
  // 4. Runtime shared/app/org resources from SQL. These come after workspace
2056
2089
  // defaults so app/team-specific guidance can override or narrow them.
2057
- const sharedAgents = await loadAgentsResourceForPrompt(SHARED_OWNER, "shared");
2090
+ const sharedAgents = await loadAgentsResourceForPrompt(SHARED_OWNER, "shared", promptResourceMaxChars);
2058
2091
  if (sharedAgents)
2059
2092
  sections.push(sharedAgents);
2060
- sections.push(...(await loadInstructionResourcesForPrompt(SHARED_OWNER, "shared-instruction")));
2093
+ sections.push(...(await loadInstructionResourcesForPrompt(SHARED_OWNER, "shared-instruction", promptResourceMaxChars)));
2061
2094
  // 5. Personal SQL resources. These come last in the instruction stack so a
2062
2095
  // user can narrow or override organization/app and workspace defaults.
2063
2096
  if (owner !== SHARED_OWNER && owner !== WORKSPACE_OWNER) {
2064
- const personalAgents = await loadAgentsResourceForPrompt(owner, "personal");
2097
+ const personalAgents = await loadAgentsResourceForPrompt(owner, "personal", promptResourceMaxChars);
2065
2098
  if (personalAgents)
2066
2099
  sections.push(personalAgents);
2067
- sections.push(...(await loadInstructionResourcesForPrompt(owner, "personal-instruction")));
2100
+ sections.push(...(await loadInstructionResourcesForPrompt(owner, "personal-instruction", promptResourceMaxChars)));
2068
2101
  }
2069
2102
  const resourceSkillsBlock = await loadResourceSkillsPromptBlock(owner);
2070
2103
  if (resourceSkillsBlock)
@@ -2154,84 +2187,59 @@ const DEFAULT_DEV_PROMPT = "";
2154
2187
  function generateActionsPrompt(registry, mode = "tool") {
2155
2188
  if (!registry || Object.keys(registry).length === 0)
2156
2189
  return "";
2157
- const lines = Object.entries(registry).map(([name, entry]) => {
2190
+ const actionEntries = Object.entries(registry);
2191
+ if (mode === "tool") {
2192
+ const summaryLines = actionEntries.map(([name, entry]) => {
2193
+ const desc = compactPromptLine(entry.tool.description, MAX_ACTION_SUMMARY_DESCRIPTION_CHARS);
2194
+ return `- \`${name}\` — ${desc}`;
2195
+ });
2196
+ return `\n\n## Available Actions
2197
+
2198
+ **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.
2199
+
2200
+ ${summaryLines.join("\n")}`;
2201
+ }
2202
+ const lines = actionEntries.map(([name, entry]) => {
2158
2203
  const desc = entry.tool.description;
2159
2204
  const params = entry.tool.parameters?.properties;
2160
2205
  const requiredFields = new Set(entry.tool.parameters?.required ?? []);
2161
- if (mode === "cli") {
2162
- // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`
2163
- if (!params || Object.keys(params).length === 0) {
2164
- return `- \`pnpm action ${name}\` — ${desc}`;
2206
+ // CLI mode: emit `pnpm action <name> --required <type> [--optional <type>]`
2207
+ if (!params || Object.keys(params).length === 0) {
2208
+ return `- \`pnpm action ${name}\` ${desc}`;
2209
+ }
2210
+ const entries = Object.entries(params);
2211
+ // Required first (alphabetical), then optional (alphabetical)
2212
+ entries.sort(([a], [b]) => {
2213
+ const ar = requiredFields.has(a) ? 0 : 1;
2214
+ const br = requiredFields.has(b) ? 0 : 1;
2215
+ if (ar !== br)
2216
+ return ar - br;
2217
+ return a.localeCompare(b);
2218
+ });
2219
+ const required = [];
2220
+ const optional = [];
2221
+ const requiredNames = [];
2222
+ for (const [k, v] of entries) {
2223
+ const type = v.type ?? "any";
2224
+ const flag = `--${k} <${type}>`;
2225
+ if (requiredFields.has(k)) {
2226
+ required.push(flag);
2227
+ requiredNames.push(`--${k}`);
2165
2228
  }
2166
- const entries = Object.entries(params);
2167
- // Required first (alphabetical), then optional (alphabetical)
2168
- entries.sort(([a], [b]) => {
2169
- const ar = requiredFields.has(a) ? 0 : 1;
2170
- const br = requiredFields.has(b) ? 0 : 1;
2171
- if (ar !== br)
2172
- return ar - br;
2173
- return a.localeCompare(b);
2174
- });
2175
- const required = [];
2176
- const optional = [];
2177
- const requiredNames = [];
2178
- for (const [k, v] of entries) {
2179
- const type = v.type ?? "any";
2180
- const flag = `--${k} <${type}>`;
2181
- if (requiredFields.has(k)) {
2182
- required.push(flag);
2183
- requiredNames.push(`--${k}`);
2184
- }
2185
- else {
2186
- optional.push(`[${flag}]`);
2187
- }
2229
+ else {
2230
+ optional.push(`[${flag}]`);
2188
2231
  }
2189
- const cmd = ["pnpm action " + name, ...required, ...optional].join(" ");
2190
- const requiredNote = requiredNames.length > 0
2191
- ? ` Required: ${requiredNames.join(", ")}.`
2192
- : "";
2193
- return `- \`${cmd}\` — ${desc}.${requiredNote}`;
2194
2232
  }
2195
- // tool mode (production / native tool calls)
2196
- if (params) {
2197
- // Order required params first, then optional. Mark required with "*"
2198
- // and include type + description so the agent knows exactly how to call.
2199
- const entries = Object.entries(params);
2200
- entries.sort(([a], [b]) => {
2201
- const ar = requiredFields.has(a) ? 0 : 1;
2202
- const br = requiredFields.has(b) ? 0 : 1;
2203
- if (ar !== br)
2204
- return ar - br;
2205
- return a.localeCompare(b);
2206
- });
2207
- const paramList = entries
2208
- .map(([k, v]) => {
2209
- const isRequired = requiredFields.has(k);
2210
- const type = v.type ?? "any";
2211
- const marker = isRequired ? "*" : "?";
2212
- const descPart = v.description ? ` — ${v.description}` : "";
2213
- return `${k}${marker}: ${type}${descPart}`;
2214
- })
2215
- .join("; ");
2216
- return `- \`${name}\`(${paramList}) — ${desc}`;
2217
- }
2218
- return `- \`${name}\`() — ${desc}`;
2233
+ const cmd = ["pnpm action " + name, ...required, ...optional].join(" ");
2234
+ const requiredNote = requiredNames.length > 0 ? ` Required: ${requiredNames.join(", ")}.` : "";
2235
+ return `- \`${cmd}\` ${desc}.${requiredNote}`;
2219
2236
  });
2220
- if (mode === "cli") {
2221
- return `\n\n## Available Actions
2237
+ return `\n\n## Available Actions
2222
2238
 
2223
2239
  **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'")\`.
2224
2240
 
2225
2241
  Do NOT try to call these by name as if they were tools — they will not exist in your tool list. Always go through \`bash\`.
2226
2242
 
2227
- ${lines.join("\n")}`;
2228
- }
2229
- return `\n\n## Available Actions
2230
-
2231
- **Use these actions directly as tool calls.** They are your primary tools — they handle database access, validation, and business logic internally. Prefer these over lower-level tools like \`web-request\` or \`db-query\`.
2232
-
2233
- Parameter notation: \`name*\` = required, \`name?\` = optional. Pass parameters as a JSON object.
2234
-
2235
2243
  ${lines.join("\n")}`;
2236
2244
  }
2237
2245
  /**
@@ -3114,8 +3122,12 @@ export function createAgentChatPlugin(options) {
3114
3122
  name: options?.appId
3115
3123
  ? options.appId.charAt(0).toUpperCase() + options.appId.slice(1)
3116
3124
  : "Agent",
3125
+ title: options?.mcpServerInfo?.title,
3117
3126
  appId: options?.appId,
3118
- description: `Agent-native ${options?.appId ?? "app"} agent`,
3127
+ description: options?.mcpServerInfo?.description ??
3128
+ `Agent-native ${options?.appId ?? "app"} agent`,
3129
+ websiteUrl: options?.mcpServerInfo?.websiteUrl,
3130
+ icons: options?.mcpServerInfo?.icons,
3119
3131
  actions: allScripts,
3120
3132
  productionActions: mcpFullActions,
3121
3133
  askAgent: async (message) => {