@agent-native/actions 0.0.0-stage → 0.1.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.
Files changed (63) hide show
  1. package/README.md +41 -2
  2. package/dist/chunk-4X4LYULO.js +108 -0
  3. package/dist/chunk-4X4LYULO.js.map +1 -0
  4. package/dist/chunk-D66CG6AI.js +265 -0
  5. package/dist/chunk-D66CG6AI.js.map +1 -0
  6. package/dist/chunk-KWA4U6DI.js +273 -0
  7. package/dist/chunk-KWA4U6DI.js.map +1 -0
  8. package/dist/chunk-SXOEFWAM.js +147 -0
  9. package/dist/chunk-SXOEFWAM.js.map +1 -0
  10. package/dist/cli.js +1765 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/client-C87WZhlZ.d.ts +223 -0
  13. package/dist/client.d.ts +70 -0
  14. package/dist/client.js +110 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/contract.d.ts +251 -0
  17. package/dist/contract.js +372 -0
  18. package/dist/contract.js.map +1 -0
  19. package/dist/index.d.ts +251 -0
  20. package/dist/index.js +704 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/next-config.d.ts +16 -0
  23. package/dist/next-config.js +46 -0
  24. package/dist/next-config.js.map +1 -0
  25. package/dist/next-pages.d.ts +12 -0
  26. package/dist/next-pages.js +13 -0
  27. package/dist/next-pages.js.map +1 -0
  28. package/dist/next-server.d.ts +41 -0
  29. package/dist/next-server.js +96 -0
  30. package/dist/next-server.js.map +1 -0
  31. package/dist/next.d.ts +39 -0
  32. package/dist/next.js +68 -0
  33. package/dist/next.js.map +1 -0
  34. package/dist/nuxt.d.ts +17 -0
  35. package/dist/nuxt.js +22 -0
  36. package/dist/nuxt.js.map +1 -0
  37. package/dist/react.d.ts +50 -0
  38. package/dist/react.js +194 -0
  39. package/dist/react.js.map +1 -0
  40. package/dist/registry-CIe_aYoE.d.ts +263 -0
  41. package/dist/solid.d.ts +39 -0
  42. package/dist/solid.js +229 -0
  43. package/dist/solid.js.map +1 -0
  44. package/dist/svelte-server.d.ts +23 -0
  45. package/dist/svelte-server.js +33 -0
  46. package/dist/svelte-server.js.map +1 -0
  47. package/dist/svelte.d.ts +53 -0
  48. package/dist/svelte.js +244 -0
  49. package/dist/svelte.js.map +1 -0
  50. package/dist/vite.d.ts +30 -0
  51. package/dist/vite.js +131 -0
  52. package/dist/vite.js.map +1 -0
  53. package/dist/vue-server.d.ts +20 -0
  54. package/dist/vue-server.js +26 -0
  55. package/dist/vue-server.js.map +1 -0
  56. package/dist/vue.d.ts +64 -0
  57. package/dist/vue.js +250 -0
  58. package/dist/vue.js.map +1 -0
  59. package/dist/webmcp.d.ts +19 -0
  60. package/dist/webmcp.js +36 -0
  61. package/dist/webmcp.js.map +1 -0
  62. package/package.json +172 -4
  63. package/skills/agent-native-actions/SKILL.md +76 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai-sdk.ts","../src/mcp.ts","../src/registry.ts","../src/skill.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport { serializeActionErrorBody } from \"./errors.js\";\nimport type { ActionsRegistry } from \"./registry.js\";\nimport { schemaToJsonSchema } from \"./schema.js\";\nimport type { ActionMap, JsonSchemaObject } from \"./types.js\";\n\nexport interface ToolExportOptions<TCtx, TNames extends string = string> {\n /** Pre-resolved context for tool execution (e.g. `{ user: currentUser }`). */\n context: TCtx;\n /** Restrict exported tools to an explicit allowlist of action names. */\n only?: readonly TNames[];\n /** Exclude specific action names from exported tools. */\n exclude?: readonly TNames[];\n /** Optional approval token or verifier override when running inside an agent loop. */\n approvalToken?: string;\n}\n\nfunction selectAgentActions<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: ToolExportOptions<TCtx, Extract<keyof TActions, string>>,\n) {\n return Object.entries(registry.actions).filter(([name, action]) => {\n if (action.agentTool === false) return false;\n if (\n options.only &&\n !options.only.includes(name as Extract<keyof TActions, string>)\n ) {\n return false;\n }\n if (\n options.exclude &&\n options.exclude.includes(name as Extract<keyof TActions, string>)\n ) {\n return false;\n }\n return true;\n });\n}\n\nfunction requireToolJsonSchema(\n name: string,\n schema: StandardSchemaV1 | undefined,\n explicitOverride?: JsonSchemaObject,\n): JsonSchemaObject {\n const converted = schemaToJsonSchema(schema, \"input\", explicitOverride);\n if (!converted) {\n throw new Error(\n `Action \"${name}\" uses a schema without Standard JSON Schema support. Provide a Zod v4 / Standard JSON Schema validator or set \\`toolSchema\\` on the action.`,\n );\n }\n return converted;\n}\n\nexport interface AiSdkToolDefinition {\n description: string;\n inputSchema: StandardSchemaV1 | JsonSchemaObject;\n parameters: StandardSchemaV1 | JsonSchemaObject;\n execute: (args: unknown) => Promise<unknown>;\n}\n\n/**\n * Export registered actions as tools compatible with Vercel AI SDK (`ai`).\n */\nexport function toAiSdkTools<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: ToolExportOptions<TCtx, Extract<keyof TActions, string>>,\n): Record<string, AiSdkToolDefinition> {\n const tools: Record<string, AiSdkToolDefinition> = {};\n for (const [name, action] of selectAgentActions(registry, options)) {\n const schemaOrJson =\n action.schema ??\n requireToolJsonSchema(name, undefined, action.toolSchema);\n tools[name] = {\n description: action.description,\n inputSchema: schemaOrJson,\n parameters: schemaOrJson,\n execute: async (args: unknown) =>\n registry.invokeWithContext(name, args ?? {}, options.context, {\n caller: \"agent\",\n ...(options.approvalToken !== undefined\n ? { approvalToken: options.approvalToken }\n : {}),\n }),\n };\n }\n return tools;\n}\n\nexport interface AnthropicToolDefinition {\n name: string;\n description: string;\n input_schema: JsonSchemaObject;\n}\n\n/**\n * Export registered actions as Anthropic SDK tool definitions + executor.\n */\nexport function toAnthropicTools<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: ToolExportOptions<TCtx, Extract<keyof TActions, string>>,\n): {\n tools: AnthropicToolDefinition[];\n executeToolUse: (toolUse: {\n id: string;\n name: string;\n input: unknown;\n }) => Promise<{\n type: \"tool_result\";\n tool_use_id: string;\n content: string;\n is_error?: true;\n }>;\n} {\n const selected = selectAgentActions(registry, options);\n const allowed = new Set(selected.map(([name]) => name));\n const tools: AnthropicToolDefinition[] = selected.map(([name, action]) => ({\n name,\n description: action.description,\n input_schema: requireToolJsonSchema(name, action.schema, action.toolSchema),\n }));\n\n return {\n tools,\n executeToolUse: async (toolUse) => {\n if (!allowed.has(toolUse.name)) {\n return {\n type: \"tool_result\",\n tool_use_id: toolUse.id,\n is_error: true,\n content: JSON.stringify({\n error: `Tool \"${toolUse.name}\" is not enabled.`,\n errorCode: \"not_found\",\n }),\n };\n }\n try {\n const result = await registry.invokeWithContext(\n toolUse.name,\n toolUse.input ?? {},\n options.context,\n {\n caller: \"agent\",\n ...(options.approvalToken !== undefined\n ? { approvalToken: options.approvalToken }\n : {}),\n },\n );\n return {\n type: \"tool_result\",\n tool_use_id: toolUse.id,\n content: JSON.stringify(result ?? null),\n };\n } catch (error) {\n const { body } = serializeActionErrorBody(error);\n return {\n type: \"tool_result\",\n tool_use_id: toolUse.id,\n is_error: true,\n content: JSON.stringify(body),\n };\n }\n },\n };\n}\n\nexport interface OpenAiToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: JsonSchemaObject;\n };\n}\n\n/**\n * Export registered actions as OpenAI SDK tool definitions + executor.\n */\nexport function toOpenAiTools<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: ToolExportOptions<TCtx, Extract<keyof TActions, string>>,\n): {\n tools: OpenAiToolDefinition[];\n executeToolCall: (toolCall: {\n id: string;\n function: { name: string; arguments: string };\n }) => Promise<{\n role: \"tool\";\n tool_call_id: string;\n content: string;\n }>;\n} {\n const selected = selectAgentActions(registry, options);\n const allowed = new Set(selected.map(([name]) => name));\n const tools: OpenAiToolDefinition[] = selected.map(([name, action]) => ({\n type: \"function\",\n function: {\n name,\n description: action.description,\n parameters: requireToolJsonSchema(name, action.schema, action.toolSchema),\n },\n }));\n\n return {\n tools,\n executeToolCall: async (toolCall) => {\n const name = toolCall.function.name;\n if (!allowed.has(name)) {\n return {\n role: \"tool\",\n tool_call_id: toolCall.id,\n content: JSON.stringify({\n error: `Tool \"${name}\" is not enabled.`,\n errorCode: \"not_found\",\n }),\n };\n }\n try {\n const parsedArgs: unknown = toolCall.function.arguments.trim()\n ? JSON.parse(toolCall.function.arguments)\n : {};\n const result = await registry.invokeWithContext(\n name,\n parsedArgs,\n options.context,\n {\n caller: \"agent\",\n ...(options.approvalToken !== undefined\n ? { approvalToken: options.approvalToken }\n : {}),\n },\n );\n return {\n role: \"tool\",\n tool_call_id: toolCall.id,\n content: JSON.stringify(result ?? null),\n };\n } catch (error) {\n const { body } = serializeActionErrorBody(error);\n return {\n role: \"tool\",\n tool_call_id: toolCall.id,\n content: JSON.stringify(body),\n };\n }\n },\n };\n}\n","import {\n Server,\n createMcpHandler,\n type Tool,\n} from \"@modelcontextprotocol/server\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport { isActionReadOnly } from \"./action.js\";\nimport { isActionError, serializeActionErrorBody } from \"./errors.js\";\nimport type { ActionsRegistry, McpHandlerOptions } from \"./registry.js\";\nimport { schemaToJsonSchema } from \"./schema.js\";\nimport type { ActionMap, ActionMapEntry, JsonSchemaObject } from \"./types.js\";\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatMcpErrorText(error: unknown): string {\n const { body } = serializeActionErrorBody(error);\n const parts = [body.error];\n if (body.errorCode && body.errorCode !== \"action_failed\") {\n parts.push(`(errorCode: ${body.errorCode})`);\n }\n if (body.committed) {\n parts.push(\"[committed: true — do not blindly retry]\");\n }\n if (body.details) {\n const serialized = JSON.stringify(body.details);\n parts.push(\n `Error details: ${serialized.length > 2000 ? `${serialized.slice(0, 1997)}...` : serialized}`,\n );\n }\n return parts.join(\"\\n\");\n}\n\nfunction isExposedToMcp(\n name: string,\n action: Pick<ActionMapEntry<never>, \"agentTool\" | \"mcpTool\">,\n options: McpHandlerOptions,\n): boolean {\n if (action.agentTool === false || action.mcpTool === false) return false;\n if (options.include && !options.include.includes(name)) return false;\n if (options.exclude && options.exclude.includes(name)) return false;\n return true;\n}\n\nfunction buildMcpServerForRequest<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: McpHandlerOptions,\n invocation: {\n request?: Request;\n platform?: unknown;\n },\n): Server {\n const server = new Server(\n {\n name: options.name ?? \"agent-native-actions\",\n version: options.version ?? \"0.1.0\",\n },\n {\n capabilities: { tools: {} },\n ...(options.instructions ? { instructions: options.instructions } : {}),\n },\n );\n\n server.setRequestHandler(\"tools/list\", async () => {\n const tools: Tool[] = [];\n for (const [name, action] of Object.entries(registry.actions)) {\n if (!isExposedToMcp(name, action, options)) continue;\n\n const inputSchema: JsonSchemaObject = schemaToJsonSchema(\n action.schema,\n \"input\",\n action.toolSchema,\n ) ?? {\n type: \"object\",\n properties: {},\n };\n\n const outputSchema: JsonSchemaObject | null =\n action.mcpOutputSchema !== false && action.outputSchema\n ? schemaToJsonSchema(action.outputSchema, \"output\")\n : null;\n\n const tool: Tool = {\n name,\n ...(action.title ? { title: action.title } : {}),\n description: action.description,\n inputSchema: inputSchema as Tool[\"inputSchema\"],\n ...(outputSchema && outputSchema[\"type\"] === \"object\"\n ? { outputSchema: outputSchema as NonNullable<Tool[\"outputSchema\"]> }\n : {}),\n annotations: {\n readOnlyHint: isActionReadOnly(action),\n destructiveHint: Boolean(action.destructive),\n idempotentHint: Boolean(action.retrySafe),\n openWorldHint: false,\n },\n };\n tools.push(tool);\n }\n return { tools };\n });\n\n server.setRequestHandler(\"tools/call\", async (request) => {\n const toolName = request.params.name;\n const args = request.params.arguments ?? {};\n const action = registry.actions[toolName];\n\n if (!action || !isExposedToMcp(toolName, action, options)) {\n return {\n isError: true,\n content: [\n {\n type: \"text\" as const,\n text: `Action \"${toolName}\" is not exposed over MCP.\\n(errorCode: not_found)`,\n },\n ],\n };\n }\n\n try {\n const result = invocation.request\n ? await registry.invokeFromRequest(toolName, args, {\n caller: \"mcp\",\n request: invocation.request,\n ...(invocation.platform !== undefined\n ? { platform: invocation.platform }\n : {}),\n })\n : await registry.invokeFromCliOrStdio(toolName, args, {\n caller: \"mcp\",\n });\n\n const structuredContent = isPlainRecord(result)\n ? result\n : Array.isArray(result)\n ? { items: result }\n : undefined;\n\n const text =\n typeof result === \"string\"\n ? result\n : JSON.stringify(result ?? null, null, 2);\n\n return {\n content: [{ type: \"text\" as const, text }],\n ...(structuredContent ? { structuredContent } : {}),\n };\n } catch (error) {\n const { body } = serializeActionErrorBody(error);\n return {\n isError: true,\n content: [{ type: \"text\" as const, text: formatMcpErrorText(error) }],\n structuredContent: {\n error: {\n message: body.error,\n errorCode: body.errorCode,\n ...(body.committed ? { committed: true } : {}),\n ...(body.details ? { details: body.details } : {}),\n },\n },\n };\n }\n });\n\n return server;\n}\n\nexport function createMcpFetchHandler<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: McpHandlerOptions = {},\n): (request: Request, override?: { platform?: unknown }) => Promise<Response> {\n return async (request, override) => {\n if (options.authenticate) {\n const allowed = await options.authenticate(request);\n if (!allowed) {\n return new Response(\n JSON.stringify({\n error: \"Unauthorized MCP request.\",\n errorCode: \"unauthorized\",\n }),\n {\n status: 401,\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n },\n );\n }\n }\n\n const handler = createMcpHandler(\n () =>\n buildMcpServerForRequest(registry, options, {\n request,\n ...(override?.platform !== undefined\n ? { platform: override.platform }\n : {}),\n }),\n {\n legacy: \"stateless\",\n responseMode: \"auto\",\n },\n );\n\n try {\n return await handler.fetch(request);\n } catch (error) {\n if (isActionError(error)) {\n const { statusCode, body } = serializeActionErrorBody(error);\n return new Response(JSON.stringify(body), {\n status: statusCode,\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n }\n throw error;\n }\n };\n}\n\nexport async function runStdioMcpServer<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: McpHandlerOptions = {},\n): Promise<void> {\n const { serveStdio } = await import(\"@modelcontextprotocol/server/stdio\");\n const stdio = serveStdio(\n () => buildMcpServerForRequest(registry, options, {}),\n { legacy: \"serve\" },\n );\n await new Promise<void>((resolve) => {\n process.stdin.once(\"end\", resolve);\n process.once(\"SIGINT\", resolve);\n process.once(\"SIGTERM\", resolve);\n });\n await stdio.close();\n}\n","import {\n executeAction,\n isActionReadOnly,\n resolveActionHttpMethod,\n resolveActionHttpPath,\n} from \"./action.js\";\nimport { ActionError } from \"./errors.js\";\nimport { createActionFetchHandler, stripBasePath } from \"./http.js\";\nimport { createMcpFetchHandler } from \"./mcp.js\";\nimport type {\n ActionAfterMutateInfo,\n ActionApprovalVerifier,\n ActionCaller,\n ActionContextInput,\n ActionErrorInfo,\n ActionHttpMethod,\n ActionMap,\n ActionMetadataSummary,\n ActionMiddleware,\n DefaultActionContext,\n InferActionInputFromDef,\n InferActionReturn,\n} from \"./types.js\";\n\nexport interface ActionHttpHandlerOptions {\n /** Mount prefix stripped before resolving action names. Defaults to `\"/api/agent-native/actions\"`. */\n basePath?: string;\n /** Enforce same-origin check on cookie-authenticated mutations. Defaults to `true`. */\n csrfProtection?: boolean;\n /** Optional CORS configuration for cross-origin browser clients. */\n cors?:\n | boolean\n | {\n origin: string | readonly string[] | ((origin: string) => boolean);\n credentials?: boolean;\n };\n}\n\nexport interface McpHandlerOptions {\n /** MCP server name announced during initialize. */\n name?: string;\n /** MCP server version announced during initialize. */\n version?: string;\n /** Server instructions shown to MCP hosts. */\n instructions?: string;\n /** Explicit allowlist of action names exposed over MCP. */\n include?: readonly string[];\n /** Action names excluded from MCP. */\n exclude?: readonly string[];\n /** Optional gate run before handling an incoming HTTP MCP request. Return false to reject with 401. */\n authenticate?: (request: Request) => boolean | Promise<boolean>;\n}\n\nexport interface CombinedHandlerOptions {\n /** Base path for the combined catch-all handler. Defaults to `\"/api/agent-native\"`. */\n basePath?: string;\n /** Enable or configure Streamable HTTP MCP at `<basePath>/mcp`. Defaults to `true`. */\n mcp?: boolean | McpHandlerOptions;\n /** HTTP RPC handler options (CORS, CSRF). */\n http?: Omit<ActionHttpHandlerOptions, \"basePath\">;\n}\n\nexport interface CreateActionsOptions<\n TActions extends ActionMap<TCtx>,\n TCtx = DefaultActionContext,\n> {\n actions: TActions & ActionMap<TCtx>;\n /** Resolve the typed context passed as the 2nd argument to `authorize`, `needsApproval`, and `run`. */\n createContext?: (input: ActionContextInput) => TCtx | Promise<TCtx>;\n /** Middleware wrapping every action invocation across HTTP, MCP, CLI, server, and AI SDKs. */\n middleware?: readonly ActionMiddleware<NoInfer<TCtx>>[];\n /** Host verifier for `needsApproval` grants (e.g. signed token or DB approval lookup). */\n verifyApproval?: ActionApprovalVerifier<NoInfer<TCtx>>;\n /** Runs after a non-read-only action's `run()` and `outputSchema` succeed. */\n onAfterMutate?: (\n info: ActionAfterMutateInfo<NoInfer<TCtx>>,\n ) => void | Promise<void>;\n /** Structured error observer for logging / Sentry / OpenTelemetry. */\n onError?: (error: unknown, info: ActionErrorInfo<NoInfer<TCtx>>) => void;\n /** Default options for `actions.handler` and `actions.mcpHandler`. */\n http?: ActionHttpHandlerOptions;\n mcp?: McpHandlerOptions;\n}\n\nexport interface ActionsRegistry<TCtx, TActions extends ActionMap<TCtx>> {\n readonly actions: TActions;\n readonly __contextType?: TCtx;\n /** List all registered action names. */\n list: () => Array<Extract<keyof TActions, string>>;\n /** Return static metadata for every registered action (safe for diagnostics / client method maps). */\n describe: () => ActionMetadataSummary[];\n /** Build a `{ [actionName]: \"GET\" | \"POST\" | ... }` map for typed clients. */\n httpMethodMap: () => Record<string, ActionHttpMethod>;\n /** Resolve an incoming relative HTTP path to an action name and method. */\n resolveHttpAction: (relativePath: string) => {\n name: Extract<keyof TActions, string>;\n method: ActionHttpMethod;\n } | null;\n /**\n * Call a registered action directly with full schema validation, `authorize`,\n * `needsApproval`, middleware, and `outputSchema` enforcement.\n */\n call: <TName extends Extract<keyof TActions, string>>(\n name: TName,\n input: InferActionInputFromDef<TActions[TName]>,\n options?: {\n ctx?: TCtx;\n caller?: ActionCaller;\n request?: Request;\n headers?: HeadersInit;\n signal?: AbortSignal;\n platform?: unknown;\n approvalToken?: string;\n approved?: boolean;\n },\n ) => Promise<InferActionReturn<TActions[TName]>>;\n /** Internal / adapter entry point using an incoming Web Standard Request to build context. */\n invokeFromRequest: (\n name: string,\n rawInput: unknown,\n options: {\n caller: ActionCaller;\n request: Request;\n platform?: unknown;\n approvalToken?: string;\n },\n ) => Promise<unknown>;\n /** Internal / CLI / stdio MCP entry point using local env to build context. */\n invokeFromCliOrStdio: (\n name: string,\n rawInput: unknown,\n options: {\n caller: ActionCaller;\n approved?: boolean;\n approvalToken?: string;\n },\n ) => Promise<unknown>;\n /** Internal / AI SDK entry point with an explicit pre-resolved context. */\n invokeWithContext: (\n name: string,\n rawInput: unknown,\n ctx: TCtx,\n options: {\n caller: ActionCaller;\n approvalToken?: string;\n approved?: boolean;\n },\n ) => Promise<unknown>;\n /** Web Fetch handler for HTTP action RPC only (`/actions/:name`). */\n fetchHandler: (\n request: Request,\n override?: { actionPath?: string; platform?: unknown },\n ) => Promise<Response>;\n /** Web Fetch handler for Streamable HTTP MCP only (`/mcp`). */\n mcpHandler: (\n request: Request,\n override?: { platform?: unknown },\n ) => Promise<Response>;\n /** Single catch-all Web Fetch handler routing `/actions/*` and `/mcp` under one prefix. */\n handler: (\n request: Request,\n override?: { pathSegments?: readonly string[]; platform?: unknown },\n ) => Promise<Response>;\n /** Build a customized catch-all Web Fetch handler (e.g. custom `basePath` or MCP config). */\n createHandler: (\n options?: CombinedHandlerOptions,\n ) => (\n request: Request,\n override?: { pathSegments?: readonly string[]; platform?: unknown },\n ) => Promise<Response>;\n}\n\nfunction readRuntimeEnv(): Record<string, string | undefined> {\n return typeof process !== \"undefined\" ? process.env : {};\n}\n\nfunction defaultContext(input: ActionContextInput): DefaultActionContext {\n return {\n caller: input.caller,\n source: input.source,\n headers: input.headers,\n ...(input.request ? { request: input.request } : {}),\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.actionName ? { actionName: input.actionName } : {}),\n };\n}\n\nexport function createActions<\n TCtx = DefaultActionContext,\n TActions extends ActionMap<TCtx> = ActionMap<TCtx>,\n>(\n options: CreateActionsOptions<TActions, TCtx>,\n): ActionsRegistry<TCtx, TActions> {\n const { actions } = options;\n\n const httpRouteIndex = new Map<\n string,\n { name: Extract<keyof TActions, string>; method: ActionHttpMethod }\n >();\n\n for (const [name, action] of Object.entries(actions)) {\n const method = resolveActionHttpMethod(action);\n const routePath = resolveActionHttpPath(name, action);\n if (method && routePath) {\n if (httpRouteIndex.has(routePath)) {\n throw new Error(\n `Duplicate HTTP action route \"${routePath}\" in createActions().`,\n );\n }\n httpRouteIndex.set(routePath, {\n name: name as Extract<keyof TActions, string>,\n method,\n });\n }\n }\n\n const resolveContext = async (input: ActionContextInput): Promise<TCtx> => {\n if (options.createContext) {\n return options.createContext(input);\n }\n return defaultContext(input) as TCtx;\n };\n\n const invokeWithContext = async (\n name: string,\n rawInput: unknown,\n ctx: TCtx,\n callOpts: {\n caller: ActionCaller;\n approvalToken?: string;\n approved?: boolean;\n },\n ): Promise<unknown> => {\n const action = actions[name];\n if (!action) {\n throw new ActionError(`Action \"${name}\" not found.`, {\n statusCode: 404,\n errorCode: \"not_found\",\n });\n }\n\n return executeAction({\n name,\n action,\n rawInput,\n ctx,\n caller: callOpts.caller,\n ...(callOpts.approvalToken !== undefined\n ? { approvalToken: callOpts.approvalToken }\n : {}),\n ...(callOpts.approved !== undefined\n ? { approved: callOpts.approved }\n : {}),\n ...(options.verifyApproval\n ? { verifyApproval: options.verifyApproval }\n : {}),\n ...(options.middleware ? { middleware: options.middleware } : {}),\n ...(options.onAfterMutate\n ? { onAfterMutate: options.onAfterMutate }\n : {}),\n ...(options.onError ? { onError: options.onError } : {}),\n });\n };\n\n const invokeFromRequest: ActionsRegistry<\n TCtx,\n TActions\n >[\"invokeFromRequest\"] = async (name, rawInput, reqOpts) => {\n const ctx = await resolveContext({\n caller: reqOpts.caller,\n source: reqOpts.caller,\n actionName: name,\n request: reqOpts.request,\n headers: reqOpts.request.headers,\n signal: reqOpts.request.signal,\n env: readRuntimeEnv(),\n ...(reqOpts.platform !== undefined ? { platform: reqOpts.platform } : {}),\n });\n return invokeWithContext(name, rawInput, ctx, {\n caller: reqOpts.caller,\n ...(reqOpts.approvalToken !== undefined\n ? { approvalToken: reqOpts.approvalToken }\n : {}),\n });\n };\n\n const invokeFromCliOrStdio: ActionsRegistry<\n TCtx,\n TActions\n >[\"invokeFromCliOrStdio\"] = async (name, rawInput, cliOpts) => {\n const ctx = await resolveContext({\n caller: cliOpts.caller,\n source: cliOpts.caller,\n actionName: name,\n headers: new Headers(),\n env: readRuntimeEnv(),\n });\n return invokeWithContext(name, rawInput, ctx, {\n caller: cliOpts.caller,\n ...(cliOpts.approved !== undefined ? { approved: cliOpts.approved } : {}),\n ...(cliOpts.approvalToken !== undefined\n ? { approvalToken: cliOpts.approvalToken }\n : {}),\n });\n };\n\n const registry: ActionsRegistry<TCtx, TActions> = {\n actions,\n list: () => Object.keys(actions) as Array<Extract<keyof TActions, string>>,\n describe: () =>\n Object.entries(actions).map(([name, action]) => ({\n name,\n ...(action.title ? { title: action.title } : {}),\n description: action.description,\n httpMethod: resolveActionHttpMethod(action),\n httpPath: resolveActionHttpPath(name, action),\n readOnly: isActionReadOnly(action),\n destructive: Boolean(action.destructive),\n retrySafe: Boolean(action.retrySafe),\n mcpExposed: action.agentTool !== false && action.mcpTool !== false,\n agentExposed: action.agentTool !== false,\n hasInputSchema: Boolean(action.schema),\n hasOutputSchema: Boolean(action.outputSchema),\n })),\n httpMethodMap: () => {\n const map: Record<string, ActionHttpMethod> = {};\n for (const [name, action] of Object.entries(actions)) {\n const method = resolveActionHttpMethod(action);\n if (method) map[name] = method;\n }\n return map;\n },\n resolveHttpAction: (relativePath) =>\n httpRouteIndex.get(relativePath) ?? null,\n call: async (name, input, callOpts = {}) => {\n const caller = callOpts.caller ?? \"server\";\n const ctx =\n callOpts.ctx !== undefined\n ? callOpts.ctx\n : await resolveContext({\n caller,\n source: caller,\n actionName: name,\n ...(callOpts.request ? { request: callOpts.request } : {}),\n headers: new Headers(\n callOpts.headers ?? callOpts.request?.headers,\n ),\n ...(callOpts.signal\n ? { signal: callOpts.signal }\n : callOpts.request\n ? { signal: callOpts.request.signal }\n : {}),\n env: readRuntimeEnv(),\n ...(callOpts.platform !== undefined\n ? { platform: callOpts.platform }\n : {}),\n });\n\n return (await invokeWithContext(name, input, ctx, {\n caller,\n ...(callOpts.approvalToken !== undefined\n ? { approvalToken: callOpts.approvalToken }\n : {}),\n ...(callOpts.approved !== undefined\n ? { approved: callOpts.approved }\n : {}),\n })) as InferActionReturn<TActions[typeof name]>;\n },\n invokeFromRequest,\n invokeFromCliOrStdio,\n invokeWithContext,\n fetchHandler: async () => new Response(\"Not initialized\", { status: 500 }),\n mcpHandler: async () => new Response(\"Not initialized\", { status: 500 }),\n handler: async () => new Response(\"Not initialized\", { status: 500 }),\n createHandler: (combinedOptions = {}) => {\n const basePath = combinedOptions.basePath ?? \"/api/agent-native\";\n const actionBasePath = `${basePath.replace(/\\/+$/, \"\")}/actions`;\n const actionFetch = createActionFetchHandler(registry, {\n ...options.http,\n ...combinedOptions.http,\n basePath: actionBasePath,\n });\n const mcpEnabled = combinedOptions.mcp !== false;\n const mcpOpts: McpHandlerOptions =\n typeof combinedOptions.mcp === \"object\"\n ? { ...options.mcp, ...combinedOptions.mcp }\n : { ...options.mcp };\n const mcpFetch = mcpEnabled\n ? createMcpFetchHandler(registry, mcpOpts)\n : null;\n\n return async (request, override) => {\n const url = new URL(request.url);\n const rel =\n override?.pathSegments !== undefined\n ? override.pathSegments.join(\"/\")\n : stripBasePath(url.pathname, basePath);\n\n if (rel === \"mcp\" || rel.startsWith(\"mcp/\")) {\n if (!mcpFetch) {\n return new Response(\n JSON.stringify({\n error: \"MCP endpoint is disabled.\",\n errorCode: \"not_found\",\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json; charset=utf-8\" },\n },\n );\n }\n return mcpFetch(\n request,\n override?.platform !== undefined\n ? { platform: override.platform }\n : undefined,\n );\n }\n\n if (rel === \"actions\" || rel.startsWith(\"actions/\")) {\n const actionPath =\n rel === \"actions\" ? \"\" : rel.slice(\"actions/\".length);\n return actionFetch(request, {\n actionPath,\n ...(override?.platform !== undefined\n ? { platform: override.platform }\n : {}),\n });\n }\n\n return new Response(\n JSON.stringify({\n error: `Unknown route \"${rel}\". Expected /actions/<name> or /mcp.`,\n errorCode: \"not_found\",\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json; charset=utf-8\" },\n },\n );\n };\n },\n };\n\n registry.fetchHandler = createActionFetchHandler(registry, options.http);\n registry.mcpHandler = createMcpFetchHandler(registry, options.mcp);\n registry.handler = registry.createHandler();\n\n return registry;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport const AGENT_NATIVE_ACTIONS_SKILL_NAME = \"agent-native-actions\";\n\nexport const AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH = path.join(\n \".agents\",\n \"skills\",\n AGENT_NATIVE_ACTIONS_SKILL_NAME,\n \"SKILL.md\",\n);\n\nexport const AGENT_NATIVE_ACTIONS_SKILL_MD = `---\nname: agent-native-actions\ndescription: Build and maintain backend operations with @agent-native/actions. Use whenever adding a new feature, endpoint, mutation, data fetch, CLI command, or AI tool in this app so UI, HTTP, CLI, MCP, and AI SDKs always share one typed action.\n---\n\n# Agent-Native Actions\n\nThis repository uses \\`@agent-native/actions\\` as the single source of truth for application operations.\n\n## Core Rule: Always Build New Capabilities as Actions\n\nWhen adding any new backend feature, query, mutation, or integration:\n\n1. **Create one file per operation in \\`actions/<verb-noun>.ts\\`** (for example \\`actions/list-deals.ts\\`, \\`actions/create-invoice.ts\\`, \\`actions/refund-charge.ts\\`).\n2. **Do not create parallel ad-hoc \\`/api/*\\` REST routes, Next.js Server Actions, tRPC procedures, or standalone database scripts** for normal app operations. Put the operation in \\`actions/\\` so your UI hooks, HTTP API, CLI, MCP server, and AI SDK tools automatically stay in parity.\n3. Reserve custom routes only for streaming responses, binary/file uploads, inbound third-party webhooks, OAuth callbacks, or non-JSON endpoints.\n\n## Defining an Action\n\nUse the app's typed \\`defineAction\\` helper from \\`actions/context.ts\\` if present (otherwise import \\`defineAction\\` from \\`@agent-native/actions\\`):\n\n\\`\\`\\`ts\n// actions/list-todos.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"./context\"; // or \"@agent-native/actions\"\n\nexport default defineAction({\n description: \"List todos for the current user\",\n schema: z.object({\n done: z.boolean().optional().describe(\"Filter by completion status\"),\n }),\n http: { method: \"GET\" },\n readOnly: true,\n authorize: (_input, ctx) => Boolean(ctx.user),\n run: async ({ done }, ctx) => {\n return db.todos.findMany({ where: { userId: ctx.user.id, done } });\n },\n});\n\\`\\`\\`\n\n### Action Authoring Checklist\n\n- **Filename = action name:** \\`actions/create-todo.ts\\` becomes \\`create-todo\\`. Subfolders join with hyphens (\\`actions/billing/refund.ts\\` -> \\`billing-refund\\`). Prefix shared helpers with \\`_\\` (\\`actions/_shared/db.ts\\`) so they are not registered as actions.\n- **Describe every field:** Always provide a concise one-line \\`description\\` and \\`.describe(...)\\` on schema fields so the CLI \\`--help\\`, MCP clients, and AI agents know how to call the action.\n- **Mark reads explicitly:** Set \\`http: { method: \"GET\" }\\` and \\`readOnly: true\\` on read-only queries. Leave mutations on default \\`POST\\` (or \\`PUT\\` / \\`DELETE\\`).\n- **Enforce auth in \\`authorize(input, ctx)\\`:** Never trust UI hiding. Check \\`ctx\\` (resolved once in \\`actions/context.ts\\`) inside \\`authorize(input, ctx)\\` so HTTP, CLI, MCP, and AI callers all go through the same check.\n- **Gate sensitive writes with \\`needsApproval\\`:** For destructive, irreversible, or high-value mutations (deleting data, issuing refunds, sending external emails), set \\`needsApproval: true\\` or \\`needsApproval: (input, ctx) => ...\\` and \\`destructive: true\\`.\n- **Throw structured errors with \\`fail()\\` or \\`defineActionErrors()\\`:** Never throw bare strings or swallow errors into fake empty results. Use \\`fail(\"Invoice not found\", { statusCode: 404, errorCode: \"not_found\" })\\`.\n- **Hide internal-only actions from external agents when needed:** Set \\`mcpTool: false\\` (or \\`agentTool: false\\`) on UI-only or internal admin operations.\n\n## Calling Actions from UI Code\n\nUse the typed client hooks for this repo's framework — never hand-write \\`fetch(\"/api/...\")\\` calls for actions:\n\n- **React / Next.js:** \\`useActionQuery(\"list-todos\", { done: false })\\` and \\`useActionMutation(\"create-todo\")\\` from \\`@agent-native/actions/react\\` (or \\`@agent-native/actions/next\\`)\n- **SolidJS:** \\`createActionQuery\\` / \\`createActionMutation\\` from \\`@agent-native/actions/solid\\`\n- **Vue / Nuxt:** \\`useActionQuery\\` / \\`useActionMutation\\` from \\`@agent-native/actions/vue\\`\n- **Svelte 5 / SvelteKit:** \\`createActionQuery\\` / \\`createActionMutation\\` from \\`@agent-native/actions/svelte\\`\n- **Plain TypeScript:** \\`createActionClient()\\` from \\`@agent-native/actions/client\\`\n\nMutations automatically invalidate related queries so views stay fresh without manual query-key plumbing.\n\n## Regenerating Types & Verifying via CLI\n\nAfter adding or changing actions:\n\n1. Regenerate \\`.generated/actions.ts\\` and \\`.generated/action-types.d.ts\\` if the dev server is not running:\n \\`\\`\\`bash\n npx @agent-native/actions generate\n \\`\\`\\`\n2. Verify discovery and execution through the CLI:\n \\`\\`\\`bash\n pnpm action --list\n pnpm action <action-name> --help\n pnpm action <action-name> '{\"key\":\"value\"}'\n \\`\\`\\`\n`;\n\nexport interface InstallActionsSkillOptions {\n projectRoot: string;\n dryRun?: boolean;\n overwrite?: boolean;\n}\n\nexport interface InstallActionsSkillResult {\n filePath: string;\n relativePath: string;\n status: \"created\" | \"updated\" | \"skipped\" | \"would-create\" | \"would-update\";\n}\n\nexport function installActionsSkill(\n options: InstallActionsSkillOptions,\n): InstallActionsSkillResult {\n const filePath = path.join(\n options.projectRoot,\n AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,\n );\n const exists = fs.existsSync(filePath);\n\n if (exists && !options.overwrite) {\n return {\n filePath,\n relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,\n status: \"skipped\",\n };\n }\n\n if (options.dryRun) {\n return {\n filePath,\n relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,\n status: exists ? \"would-update\" : \"would-create\",\n };\n }\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, AGENT_NATIVE_ACTIONS_SKILL_MD, \"utf8\");\n return {\n filePath,\n relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,\n status: exists ? \"updated\" : \"created\",\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,mBACP,UACA,SACA;AACA,SAAO,OAAO,QAAQ,SAAS,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,MAAM,MAAM;AACjE,QAAI,OAAO,cAAc,MAAO,QAAO;AACvC,QACE,QAAQ,QACR,CAAC,QAAQ,KAAK,SAAS,IAAuC,GAC9D;AACA,aAAO;AAAA,IACT;AACA,QACE,QAAQ,WACR,QAAQ,QAAQ,SAAS,IAAuC,GAChE;AACA,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,SAAS,sBACP,MACA,QACA,kBACkB;AAClB,QAAM,YAAY,mBAAmB,QAAQ,SAAS,gBAAgB;AACtE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAW,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;AAYO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I,UAAU,CAAC,QAAQ,WAAW;AAChC,WAAO;AAAA,MACL;AAAA,MACA,cAAc;AAAA,MACd,QAAQ;AAAA,IACV;AAAA,EACF;AAEA,MAAI,QAAQ,QAAQ;AAClB,WAAO;AAAA,MACL;AAAA,MACA,cAAc;AAAA,MACd,QAAQ,SAAS,iBAAiB;AAAA,IACpC;AAAA,EACF;AAEA,KAAG,UAAU,KAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AACxD,KAAG,cAAc,UAAU,+BAA+B,MAAM;AAChE,SAAO;AAAA,IACL;AAAA,IACA,cAAc;AAAA,IACd,QAAQ,SAAS,YAAY;AAAA,EAC/B;AACF;","names":[]}
@@ -0,0 +1,16 @@
1
+ interface WithAgentNativeActionsOptions {
2
+ /** Directory containing `actions/*.ts`. Defaults to `"actions"`. */
3
+ actionsDir?: string;
4
+ /** Output directory for generated static manifest & types. Defaults to `".generated"`. */
5
+ generatedDir?: string;
6
+ /** Project root directory. Defaults to `process.cwd()`. */
7
+ projectRoot?: string;
8
+ }
9
+ /**
10
+ * Wrap your `next.config.ts` to deterministically generate `.generated/actions.ts`
11
+ * (static ES imports — works identically with Turbopack, Webpack, Vercel Serverless,
12
+ * and `output: "standalone"`) and `.generated/action-types.d.ts`.
13
+ */
14
+ declare function withAgentNativeActions<TConfig extends Record<string, unknown>>(nextConfig: TConfig, options?: WithAgentNativeActionsOptions): TConfig;
15
+
16
+ export { type WithAgentNativeActionsOptions, withAgentNativeActions };
@@ -0,0 +1,46 @@
1
+ import {
2
+ generateActionArtifacts
3
+ } from "./chunk-SXOEFWAM.js";
4
+
5
+ // src/next-config.ts
6
+ import fs from "fs";
7
+ import path from "path";
8
+ var activeWatchers = /* @__PURE__ */ new Map();
9
+ function withAgentNativeActions(nextConfig, options = {}) {
10
+ const projectRoot = options.projectRoot ?? process.cwd();
11
+ const actionsDir = options.actionsDir ?? "actions";
12
+ const generatedDir = options.generatedDir ?? ".generated";
13
+ generateActionArtifacts({
14
+ projectRoot,
15
+ actionsDir,
16
+ generatedDir
17
+ });
18
+ const absActionsDir = path.resolve(projectRoot, actionsDir);
19
+ if (process.env["NODE_ENV"] !== "production" && fs.existsSync(absActionsDir) && !activeWatchers.has(absActionsDir)) {
20
+ try {
21
+ const watcher = fs.watch(absActionsDir, () => {
22
+ try {
23
+ generateActionArtifacts({
24
+ projectRoot,
25
+ actionsDir,
26
+ generatedDir
27
+ });
28
+ } catch (err) {
29
+ console.error(
30
+ `[@agent-native/actions/next] Failed to regenerate actions manifest:`,
31
+ err
32
+ );
33
+ }
34
+ });
35
+ watcher.unref();
36
+ activeWatchers.set(absActionsDir, watcher);
37
+ } catch {
38
+ return nextConfig;
39
+ }
40
+ }
41
+ return nextConfig;
42
+ }
43
+ export {
44
+ withAgentNativeActions
45
+ };
46
+ //# sourceMappingURL=next-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { generateActionArtifacts } from \"./codegen.js\";\n\nexport interface WithAgentNativeActionsOptions {\n /** Directory containing `actions/*.ts`. Defaults to `\"actions\"`. */\n actionsDir?: string;\n /** Output directory for generated static manifest & types. Defaults to `\".generated\"`. */\n generatedDir?: string;\n /** Project root directory. Defaults to `process.cwd()`. */\n projectRoot?: string;\n}\n\nconst activeWatchers = new Map<string, fs.FSWatcher>();\n\n/**\n * Wrap your `next.config.ts` to deterministically generate `.generated/actions.ts`\n * (static ES imports — works identically with Turbopack, Webpack, Vercel Serverless,\n * and `output: \"standalone\"`) and `.generated/action-types.d.ts`.\n */\nexport function withAgentNativeActions<TConfig extends Record<string, unknown>>(\n nextConfig: TConfig,\n options: WithAgentNativeActionsOptions = {},\n): TConfig {\n const projectRoot = options.projectRoot ?? process.cwd();\n const actionsDir = options.actionsDir ?? \"actions\";\n const generatedDir = options.generatedDir ?? \".generated\";\n\n generateActionArtifacts({\n projectRoot,\n actionsDir,\n generatedDir,\n });\n\n const absActionsDir = path.resolve(projectRoot, actionsDir);\n if (\n process.env[\"NODE_ENV\"] !== \"production\" &&\n fs.existsSync(absActionsDir) &&\n !activeWatchers.has(absActionsDir)\n ) {\n try {\n const watcher = fs.watch(absActionsDir, () => {\n try {\n generateActionArtifacts({\n projectRoot,\n actionsDir,\n generatedDir,\n });\n } catch (err) {\n console.error(\n `[@agent-native/actions/next] Failed to regenerate actions manifest:`,\n err,\n );\n }\n });\n watcher.unref();\n activeWatchers.set(absActionsDir, watcher);\n } catch {\n return nextConfig;\n }\n }\n\n return nextConfig;\n}\n"],"mappings":";;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAajB,IAAM,iBAAiB,oBAAI,IAA0B;AAO9C,SAAS,uBACd,YACA,UAAyC,CAAC,GACjC;AACT,QAAM,cAAc,QAAQ,eAAe,QAAQ,IAAI;AACvD,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,eAAe,QAAQ,gBAAgB;AAE7C,0BAAwB;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,gBAAgB,KAAK,QAAQ,aAAa,UAAU;AAC1D,MACE,QAAQ,IAAI,UAAU,MAAM,gBAC5B,GAAG,WAAW,aAAa,KAC3B,CAAC,eAAe,IAAI,aAAa,GACjC;AACA,QAAI;AACF,YAAM,UAAU,GAAG,MAAM,eAAe,MAAM;AAC5C,YAAI;AACF,kCAAwB;AAAA,YACtB;AAAA,YACA;AAAA,YACA;AAAA,UACF,CAAC;AAAA,QACH,SAAS,KAAK;AACZ,kBAAQ;AAAA,YACN;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AACD,cAAQ,MAAM;AACd,qBAAe,IAAI,eAAe,OAAO;AAAA,IAC3C,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,12 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { i as ActionMap, j as ActionsRegistry, C as CombinedHandlerOptions } from './registry-CIe_aYoE.js';
3
+ import '@standard-schema/spec';
4
+
5
+ /**
6
+ * Create a Next.js Pages Router API handler for `pages/api/agent-native/[...path].ts`.
7
+ */
8
+ declare function createPagesHandler<TCtx, TActions extends ActionMap<TCtx>>(registry: ActionsRegistry<TCtx, TActions>, options?: CombinedHandlerOptions): (req: IncomingMessage & {
9
+ body?: unknown;
10
+ }, res: ServerResponse) => Promise<void>;
11
+
12
+ export { createPagesHandler };
@@ -0,0 +1,13 @@
1
+ import {
2
+ toNodeHandler
3
+ } from "./chunk-D66CG6AI.js";
4
+ import "./chunk-4X4LYULO.js";
5
+
6
+ // src/next-pages.ts
7
+ function createPagesHandler(registry, options = {}) {
8
+ return toNodeHandler(registry.createHandler(options));
9
+ }
10
+ export {
11
+ createPagesHandler
12
+ };
13
+ //# sourceMappingURL=next-pages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-pages.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { toNodeHandler } from \"./http.js\";\nimport type { ActionsRegistry, CombinedHandlerOptions } from \"./registry.js\";\nimport type { ActionMap } from \"./types.js\";\n\n/**\n * Create a Next.js Pages Router API handler for `pages/api/agent-native/[...path].ts`.\n */\nexport function createPagesHandler<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: CombinedHandlerOptions = {},\n): (\n req: IncomingMessage & { body?: unknown },\n res: ServerResponse,\n) => Promise<void> {\n return toNodeHandler(registry.createHandler(options));\n}\n"],"mappings":";;;;;;AASO,SAAS,mBACd,UACA,UAAkC,CAAC,GAIlB;AACjB,SAAO,cAAc,SAAS,cAAc,OAAO,CAAC;AACtD;","names":[]}
@@ -0,0 +1,41 @@
1
+ import { i as ActionMap, j as ActionsRegistry, s as InferActionInputFromDef, u as InferActionReturn } from './registry-CIe_aYoE.js';
2
+ import '@standard-schema/spec';
3
+
4
+ /**
5
+ * Decode a `FormData` payload into a plain object suitable for Zod/Standard Schema
6
+ * validation: preserves repeated fields as string arrays and leaves empty strings intact
7
+ * unless `emptyStringAsUndefined` is set.
8
+ */
9
+ declare function parseFormData(formData: FormData, options?: {
10
+ emptyStringAsUndefined?: boolean;
11
+ }): Record<string, unknown>;
12
+ /**
13
+ * Call a read-only action directly from a Next.js React Server Component with
14
+ * zero HTTP hop and automatic forwarding of incoming Next.js request headers/cookies.
15
+ */
16
+ declare function callNextAction<TCtx, TActions extends ActionMap<TCtx>, TName extends Extract<keyof TActions, string>>(registry: ActionsRegistry<TCtx, TActions>, name: TName, input: InferActionInputFromDef<TActions[TName]>, options?: {
17
+ allowMutation?: boolean;
18
+ headers?: HeadersInit;
19
+ }): Promise<InferActionReturn<TActions[TName]>>;
20
+ /**
21
+ * Helper for explicit `"use server"` functions in Next.js App Router:
22
+ *
23
+ * ```ts
24
+ * "use server";
25
+ * import { runFormAction } from "@agent-native/actions/next/server";
26
+ * import { actions } from "@/generated/actions";
27
+ *
28
+ * export async function createTodo(formData: FormData) {
29
+ * return runFormAction(actions, "create-todo", formData);
30
+ * }
31
+ * ```
32
+ */
33
+ declare function runFormAction<TCtx, TActions extends ActionMap<TCtx>, TName extends Extract<keyof TActions, string>>(registry: ActionsRegistry<TCtx, TActions>, name: TName, inputOrFormData: FormData | InferActionInputFromDef<TActions[TName]>, options?: {
34
+ emptyStringAsUndefined?: boolean;
35
+ revalidatePaths?: readonly string[];
36
+ revalidateTags?: readonly string[];
37
+ headers?: HeadersInit;
38
+ approvalToken?: string;
39
+ }): Promise<InferActionReturn<TActions[TName]>>;
40
+
41
+ export { callNextAction, parseFormData, runFormAction };
@@ -0,0 +1,96 @@
1
+ import {
2
+ isActionReadOnly
3
+ } from "./chunk-KWA4U6DI.js";
4
+ import {
5
+ ActionError
6
+ } from "./chunk-4X4LYULO.js";
7
+
8
+ // src/next-server.ts
9
+ async function readNextRequestHeaders() {
10
+ try {
11
+ const nextHeaders = await import("next/headers");
12
+ if (typeof nextHeaders.headers === "function") {
13
+ const incoming = await nextHeaders.headers();
14
+ const result = new Headers();
15
+ incoming.forEach((value, key) => {
16
+ result.append(key, value);
17
+ });
18
+ return result;
19
+ }
20
+ } catch {
21
+ return new Headers();
22
+ }
23
+ return new Headers();
24
+ }
25
+ function parseFormData(formData, options = {}) {
26
+ const out = {};
27
+ for (const [key, value] of formData.entries()) {
28
+ const normalized = options.emptyStringAsUndefined && value === "" ? void 0 : value;
29
+ if (normalized === void 0) continue;
30
+ const existing = out[key];
31
+ if (existing !== void 0) {
32
+ out[key] = Array.isArray(existing) ? [...existing, normalized] : [existing, normalized];
33
+ } else {
34
+ out[key] = normalized;
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ async function callNextAction(registry, name, input, options = {}) {
40
+ const action = registry.actions[name];
41
+ if (!action) {
42
+ throw new ActionError(`Action "${name}" not found.`, {
43
+ statusCode: 404,
44
+ errorCode: "not_found"
45
+ });
46
+ }
47
+ if (!options.allowMutation && !isActionReadOnly(action)) {
48
+ throw new ActionError(
49
+ `Action "${name}" is a mutation and should not be called directly during Server Component render. Pass \`{ allowMutation: true }\` or invoke it from a Server Action / Route Handler.`,
50
+ {
51
+ statusCode: 405,
52
+ errorCode: "mutation_in_render"
53
+ }
54
+ );
55
+ }
56
+ const headers = options.headers ? new Headers(options.headers) : await readNextRequestHeaders();
57
+ return registry.call(name, input, {
58
+ caller: "server",
59
+ headers
60
+ });
61
+ }
62
+ async function runFormAction(registry, name, inputOrFormData, options = {}) {
63
+ const headers = options.headers ? new Headers(options.headers) : await readNextRequestHeaders();
64
+ const rawInput = typeof FormData !== "undefined" && inputOrFormData instanceof FormData ? parseFormData(inputOrFormData, {
65
+ ...options.emptyStringAsUndefined !== void 0 ? { emptyStringAsUndefined: options.emptyStringAsUndefined } : {}
66
+ }) : inputOrFormData;
67
+ const result = await registry.call(
68
+ name,
69
+ rawInput,
70
+ {
71
+ caller: "server",
72
+ headers,
73
+ ...options.approvalToken !== void 0 ? { approvalToken: options.approvalToken } : {}
74
+ }
75
+ );
76
+ if (options.revalidatePaths?.length || options.revalidateTags?.length) {
77
+ try {
78
+ const nextCache = await import("next/cache");
79
+ for (const routePath of options.revalidatePaths ?? []) {
80
+ nextCache.revalidatePath(routePath);
81
+ }
82
+ for (const tag of options.revalidateTags ?? []) {
83
+ nextCache.revalidateTag(tag, "max");
84
+ }
85
+ } catch {
86
+ return result;
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+ export {
92
+ callNextAction,
93
+ parseFormData,
94
+ runFormAction
95
+ };
96
+ //# sourceMappingURL=next-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-server.ts"],"sourcesContent":["import { isActionReadOnly } from \"./action.js\";\nimport { ActionError } from \"./errors.js\";\nimport type { ActionsRegistry } from \"./registry.js\";\nimport type {\n ActionMap,\n InferActionInputFromDef,\n InferActionReturn,\n} from \"./types.js\";\n\nasync function readNextRequestHeaders(): Promise<Headers> {\n try {\n const nextHeaders = await import(\"next/headers\");\n if (typeof nextHeaders.headers === \"function\") {\n const incoming = await nextHeaders.headers();\n const result = new Headers();\n incoming.forEach((value: string, key: string) => {\n result.append(key, value);\n });\n return result;\n }\n } catch {\n return new Headers();\n }\n return new Headers();\n}\n\n/**\n * Decode a `FormData` payload into a plain object suitable for Zod/Standard Schema\n * validation: preserves repeated fields as string arrays and leaves empty strings intact\n * unless `emptyStringAsUndefined` is set.\n */\nexport function parseFormData(\n formData: FormData,\n options: { emptyStringAsUndefined?: boolean } = {},\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of formData.entries()) {\n const normalized =\n options.emptyStringAsUndefined && value === \"\" ? undefined : value;\n if (normalized === undefined) continue;\n\n const existing = out[key];\n if (existing !== undefined) {\n out[key] = Array.isArray(existing)\n ? [...existing, normalized]\n : [existing, normalized];\n } else {\n out[key] = normalized;\n }\n }\n return out;\n}\n\n/**\n * Call a read-only action directly from a Next.js React Server Component with\n * zero HTTP hop and automatic forwarding of incoming Next.js request headers/cookies.\n */\nexport async function callNextAction<\n TCtx,\n TActions extends ActionMap<TCtx>,\n TName extends Extract<keyof TActions, string>,\n>(\n registry: ActionsRegistry<TCtx, TActions>,\n name: TName,\n input: InferActionInputFromDef<TActions[TName]>,\n options: { allowMutation?: boolean; headers?: HeadersInit } = {},\n): Promise<InferActionReturn<TActions[TName]>> {\n const action: ActionMap<TCtx>[string] | undefined = registry.actions[name];\n if (!action) {\n throw new ActionError(`Action \"${name}\" not found.`, {\n statusCode: 404,\n errorCode: \"not_found\",\n });\n }\n if (!options.allowMutation && !isActionReadOnly(action)) {\n throw new ActionError(\n `Action \"${name}\" is a mutation and should not be called directly during Server Component render. Pass \\`{ allowMutation: true }\\` or invoke it from a Server Action / Route Handler.`,\n {\n statusCode: 405,\n errorCode: \"mutation_in_render\",\n },\n );\n }\n\n const headers = options.headers\n ? new Headers(options.headers)\n : await readNextRequestHeaders();\n\n return registry.call(name, input, {\n caller: \"server\",\n headers,\n });\n}\n\n/**\n * Helper for explicit `\"use server\"` functions in Next.js App Router:\n *\n * ```ts\n * \"use server\";\n * import { runFormAction } from \"@agent-native/actions/next/server\";\n * import { actions } from \"@/generated/actions\";\n *\n * export async function createTodo(formData: FormData) {\n * return runFormAction(actions, \"create-todo\", formData);\n * }\n * ```\n */\nexport async function runFormAction<\n TCtx,\n TActions extends ActionMap<TCtx>,\n TName extends Extract<keyof TActions, string>,\n>(\n registry: ActionsRegistry<TCtx, TActions>,\n name: TName,\n inputOrFormData: FormData | InferActionInputFromDef<TActions[TName]>,\n options: {\n emptyStringAsUndefined?: boolean;\n revalidatePaths?: readonly string[];\n revalidateTags?: readonly string[];\n headers?: HeadersInit;\n approvalToken?: string;\n } = {},\n): Promise<InferActionReturn<TActions[TName]>> {\n const headers = options.headers\n ? new Headers(options.headers)\n : await readNextRequestHeaders();\n\n const rawInput =\n typeof FormData !== \"undefined\" && inputOrFormData instanceof FormData\n ? parseFormData(inputOrFormData, {\n ...(options.emptyStringAsUndefined !== undefined\n ? { emptyStringAsUndefined: options.emptyStringAsUndefined }\n : {}),\n })\n : inputOrFormData;\n\n const result = await registry.call(\n name,\n rawInput as InferActionInputFromDef<TActions[TName]>,\n {\n caller: \"server\",\n headers,\n ...(options.approvalToken !== undefined\n ? { approvalToken: options.approvalToken }\n : {}),\n },\n );\n\n if (options.revalidatePaths?.length || options.revalidateTags?.length) {\n try {\n const nextCache = await import(\"next/cache\");\n for (const routePath of options.revalidatePaths ?? []) {\n nextCache.revalidatePath(routePath);\n }\n for (const tag of options.revalidateTags ?? []) {\n nextCache.revalidateTag(tag, \"max\");\n }\n } catch {\n return result;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;AASA,eAAe,yBAA2C;AACxD,MAAI;AACF,UAAM,cAAc,MAAM,OAAO,cAAc;AAC/C,QAAI,OAAO,YAAY,YAAY,YAAY;AAC7C,YAAM,WAAW,MAAM,YAAY,QAAQ;AAC3C,YAAM,SAAS,IAAI,QAAQ;AAC3B,eAAS,QAAQ,CAAC,OAAe,QAAgB;AAC/C,eAAO,OAAO,KAAK,KAAK;AAAA,MAC1B,CAAC;AACD,aAAO;AAAA,IACT;AAAA,EACF,QAAQ;AACN,WAAO,IAAI,QAAQ;AAAA,EACrB;AACA,SAAO,IAAI,QAAQ;AACrB;AAOO,SAAS,cACd,UACA,UAAgD,CAAC,GACxB;AACzB,QAAM,MAA+B,CAAC;AACtC,aAAW,CAAC,KAAK,KAAK,KAAK,SAAS,QAAQ,GAAG;AAC7C,UAAM,aACJ,QAAQ,0BAA0B,UAAU,KAAK,SAAY;AAC/D,QAAI,eAAe,OAAW;AAE9B,UAAM,WAAW,IAAI,GAAG;AACxB,QAAI,aAAa,QAAW;AAC1B,UAAI,GAAG,IAAI,MAAM,QAAQ,QAAQ,IAC7B,CAAC,GAAG,UAAU,UAAU,IACxB,CAAC,UAAU,UAAU;AAAA,IAC3B,OAAO;AACL,UAAI,GAAG,IAAI;AAAA,IACb;AAAA,EACF;A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GAAG;AACrD,kBAAU,eAAe,SAAS;AAAA,MACpC;AACA,iBAAW,OAAO,QAAQ,kBAAkB,CAAC,GAAG;AAC9C,kBAAU,cAAc,KAAK,KAAK;AAAA,MACpC;AAAA,IACF,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
package/dist/next.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { i as ActionMap, j as ActionsRegistry, k as ActionHttpHandlerOptions, C as CombinedHandlerOptions, M as McpHandlerOptions } from './registry-CIe_aYoE.js';
2
+ import '@standard-schema/spec';
3
+
4
+ interface NextRouteContext {
5
+ params: Promise<{
6
+ path?: string[];
7
+ action?: string[];
8
+ }> | {
9
+ path?: string[];
10
+ action?: string[];
11
+ };
12
+ }
13
+ type NextRouteHandler = (request: Request, context?: NextRouteContext) => Promise<Response>;
14
+ interface NextRouteHandlerExports {
15
+ GET: NextRouteHandler;
16
+ POST: NextRouteHandler;
17
+ PUT: NextRouteHandler;
18
+ PATCH: NextRouteHandler;
19
+ DELETE: NextRouteHandler;
20
+ OPTIONS: NextRouteHandler;
21
+ }
22
+ /**
23
+ * Create Next.js App Router catch-all handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`)
24
+ * serving both `/actions/:name` and `/mcp` under one route file:
25
+ * `app/api/agent-native/[...path]/route.ts`.
26
+ */
27
+ declare function createNextHandler<TCtx, TActions extends ActionMap<TCtx>>(registry: ActionsRegistry<TCtx, TActions>, options?: CombinedHandlerOptions): NextRouteHandlerExports;
28
+ /**
29
+ * Split transport helper: Next.js App Router handler for HTTP actions only
30
+ * (`app/api/actions/[...action]/route.ts`).
31
+ */
32
+ declare function createNextActionHandler<TCtx, TActions extends ActionMap<TCtx>>(registry: ActionsRegistry<TCtx, TActions>, options?: ActionHttpHandlerOptions): NextRouteHandlerExports;
33
+ /**
34
+ * Split transport helper: Next.js App Router handler for Streamable HTTP MCP only
35
+ * (`app/api/mcp/route.ts`).
36
+ */
37
+ declare function createNextMcpHandler<TCtx, TActions extends ActionMap<TCtx>>(registry: ActionsRegistry<TCtx, TActions>, options?: McpHandlerOptions): Pick<NextRouteHandlerExports, "GET" | "POST" | "DELETE" | "OPTIONS">;
38
+
39
+ export { type NextRouteContext, type NextRouteHandler, type NextRouteHandlerExports, createNextActionHandler, createNextHandler, createNextMcpHandler };
package/dist/next.js ADDED
@@ -0,0 +1,68 @@
1
+ // src/next.ts
2
+ async function resolvePathSegments(context) {
3
+ if (!context?.params) return void 0;
4
+ const resolved = await context.params;
5
+ if (Array.isArray(resolved.path)) return resolved.path;
6
+ if (Array.isArray(resolved.action)) return resolved.action;
7
+ return void 0;
8
+ }
9
+ function createNextHandler(registry, options = {}) {
10
+ const combined = registry.createHandler(options);
11
+ const handle = async (request, context) => {
12
+ const pathSegments = await resolvePathSegments(context);
13
+ return combined(
14
+ request,
15
+ pathSegments !== void 0 ? { pathSegments } : void 0
16
+ );
17
+ };
18
+ return {
19
+ GET: handle,
20
+ POST: handle,
21
+ PUT: handle,
22
+ PATCH: handle,
23
+ DELETE: handle,
24
+ OPTIONS: handle
25
+ };
26
+ }
27
+ function createNextActionHandler(registry, options = {}) {
28
+ const basePath = options.basePath ?? "/api/actions";
29
+ const handle = async (request, context) => {
30
+ const segments = await resolvePathSegments(context);
31
+ const actionFetch = registry.createHandler({
32
+ basePath,
33
+ mcp: false,
34
+ http: options
35
+ });
36
+ return actionFetch(
37
+ request,
38
+ segments !== void 0 ? { pathSegments: ["actions", ...segments] } : void 0
39
+ );
40
+ };
41
+ return {
42
+ GET: handle,
43
+ POST: handle,
44
+ PUT: handle,
45
+ PATCH: handle,
46
+ DELETE: handle,
47
+ OPTIONS: handle
48
+ };
49
+ }
50
+ function createNextMcpHandler(registry, options = {}) {
51
+ const mcpHandler = registry.createHandler({
52
+ basePath: "/api",
53
+ mcp: options
54
+ });
55
+ const handle = async (request) => mcpHandler(request, { pathSegments: ["mcp"] });
56
+ return {
57
+ GET: handle,
58
+ POST: handle,
59
+ DELETE: handle,
60
+ OPTIONS: handle
61
+ };
62
+ }
63
+ export {
64
+ createNextActionHandler,
65
+ createNextHandler,
66
+ createNextMcpHandler
67
+ };
68
+ //# sourceMappingURL=next.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next.ts"],"sourcesContent":["import type {\n ActionHttpHandlerOptions,\n ActionsRegistry,\n CombinedHandlerOptions,\n McpHandlerOptions,\n} from \"./registry.js\";\nimport type { ActionMap } from \"./types.js\";\n\nexport interface NextRouteContext {\n params:\n | Promise<{ path?: string[]; action?: string[] }>\n | { path?: string[]; action?: string[] };\n}\n\nexport type NextRouteHandler = (\n request: Request,\n context?: NextRouteContext,\n) => Promise<Response>;\n\nexport interface NextRouteHandlerExports {\n GET: NextRouteHandler;\n POST: NextRouteHandler;\n PUT: NextRouteHandler;\n PATCH: NextRouteHandler;\n DELETE: NextRouteHandler;\n OPTIONS: NextRouteHandler;\n}\n\nasync function resolvePathSegments(\n context?: NextRouteContext,\n): Promise<readonly string[] | undefined> {\n if (!context?.params) return undefined;\n const resolved = await context.params;\n if (Array.isArray(resolved.path)) return resolved.path;\n if (Array.isArray(resolved.action)) return resolved.action;\n return undefined;\n}\n\n/**\n * Create Next.js App Router catch-all handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`)\n * serving both `/actions/:name` and `/mcp` under one route file:\n * `app/api/agent-native/[...path]/route.ts`.\n */\nexport function createNextHandler<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: CombinedHandlerOptions = {},\n): NextRouteHandlerExports {\n const combined = registry.createHandler(options);\n\n const handle: NextRouteHandler = async (request, context) => {\n const pathSegments = await resolvePathSegments(context);\n return combined(\n request,\n pathSegments !== undefined ? { pathSegments } : undefined,\n );\n };\n\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n OPTIONS: handle,\n };\n}\n\n/**\n * Split transport helper: Next.js App Router handler for HTTP actions only\n * (`app/api/actions/[...action]/route.ts`).\n */\nexport function createNextActionHandler<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: ActionHttpHandlerOptions = {},\n): NextRouteHandlerExports {\n const basePath = options.basePath ?? \"/api/actions\";\n const handle: NextRouteHandler = async (request, context) => {\n const segments = await resolvePathSegments(context);\n const actionFetch = registry.createHandler({\n basePath,\n mcp: false,\n http: options,\n });\n return actionFetch(\n request,\n segments !== undefined\n ? { pathSegments: [\"actions\", ...segments] }\n : undefined,\n );\n };\n\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n OPTIONS: handle,\n };\n}\n\n/**\n * Split transport helper: Next.js App Router handler for Streamable HTTP MCP only\n * (`app/api/mcp/route.ts`).\n */\nexport function createNextMcpHandler<TCtx, TActions extends ActionMap<TCtx>>(\n registry: ActionsRegistry<TCtx, TActions>,\n options: McpHandlerOptions = {},\n): Pick<NextRouteHandlerExports, \"GET\" | \"POST\" | \"DELETE\" | \"OPTIONS\"> {\n const mcpHandler = registry.createHandler({\n basePath: \"/api\",\n mcp: options,\n });\n\n const handle: NextRouteHandler = async (request) =>\n mcpHandler(request, { pathSegments: [\"mcp\"] });\n\n return {\n GET: handle,\n POST: handle,\n DELETE: handle,\n OPTIONS: handle,\n };\n}\n"],"mappings":";AA4BA,eAAe,oBACb,SACwC;AACxC,MAAI,CAAC,SAAS,OAAQ,QAAO;AAC7B,QAAM,WAAW,MAAM,QAAQ;AAC/B,MAAI,MAAM,QAAQ,SAAS,IAAI,EAAG,QAAO,SAAS;AAClD,MAAI,MAAM,QAAQ,SAAS,MAAM,EAAG,QAAO,SAAS;AACpD,SAAO;AACT;AAOO,SAAS,kBACd,UACA,UAAkC,CAAC,GACV;AACzB,QAAM,WAAW,SAAS,cAAc,OAAO;AAE/C,QAAM,SAA2B,OAAO,SAAS,YAAY;AAC3D,UAAM,eAAe,MAAM,oBAAoB,OAAO;AACtD,WAAO;AAAA,MACL;AAAA,MACA,iBAAiB,SAAY,EAAE,aAAa,IAAI;AAAA,IAClD;AAAA,EACF;AAEA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,SAAS;AAAA,EACX;AACF;AAMO,SAAS,wBACd,UACA,UAAoC,CAAC,GACZ;AACzB,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,SAA2B,OAAO,SAAS,YAAY;AAC3D,UAAM,WAAW,MAAM,oBAAoB,OAAO;AAClD,UAAM,cAAc,SAAS,cAAc;AAAA,MACzC;AAAA,MACA,KAAK;AAAA,MACL,MAAM;AAAA,IACR,CAAC;AACD,WAAO;AAAA,MACL;AAAA,MACA,aAAa,SACT,EAAE,cAAc,CAAC,WAAW,GAAG,QAAQ,EAAE,IACzC;AAAA,IACN;AAAA,EACF;AAEA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,SAAS;AAAA,EACX;AACF;AAMO,SAAS,qBACd,UACA,UAA6B,CAAC,GACwC;AACtE,QAAM,aAAa,SAAS,cAAc;AAAA,IACxC,UAAU;AAAA,IACV,KAAK;AAAA,EACP,CAAC;AAED,QAAM,SAA2B,OAAO,YACtC,WAAW,SAAS,EAAE,cAAc,CAAC,KAAK,EAAE,CAAC;AAE/C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,EACX;AACF;","names":[]}
package/dist/nuxt.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ interface NuxtActionsModuleOptions {
2
+ actionsDir?: string;
3
+ generatedDir?: string;
4
+ }
5
+ interface NuxtLike {
6
+ options?: {
7
+ rootDir?: string;
8
+ };
9
+ hook?: (name: string, fn: () => void | Promise<void>) => void;
10
+ }
11
+ /**
12
+ * Lightweight Nuxt module that runs deterministic `.generated/actions.ts` and
13
+ * `.generated/action-types.d.ts` codegen during Nuxt prepare and build.
14
+ */
15
+ declare function agentNativeActionsNuxtModule(moduleOptions?: NuxtActionsModuleOptions, nuxt?: NuxtLike): void;
16
+
17
+ export { type NuxtActionsModuleOptions, agentNativeActionsNuxtModule as default };
package/dist/nuxt.js ADDED
@@ -0,0 +1,22 @@
1
+ import {
2
+ generateActionArtifacts
3
+ } from "./chunk-SXOEFWAM.js";
4
+
5
+ // src/nuxt.ts
6
+ function agentNativeActionsNuxtModule(moduleOptions = {}, nuxt) {
7
+ const projectRoot = nuxt?.options?.rootDir ?? process.cwd();
8
+ const run = () => {
9
+ generateActionArtifacts({
10
+ projectRoot,
11
+ ...moduleOptions.actionsDir ? { actionsDir: moduleOptions.actionsDir } : {},
12
+ ...moduleOptions.generatedDir ? { generatedDir: moduleOptions.generatedDir } : {}
13
+ });
14
+ };
15
+ run();
16
+ nuxt?.hook?.("prepare:types", run);
17
+ nuxt?.hook?.("build:before", run);
18
+ }
19
+ export {
20
+ agentNativeActionsNuxtModule as default
21
+ };
22
+ //# sourceMappingURL=nuxt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nuxt.ts"],"sourcesContent":["import { generateActionArtifacts } from \"./codegen.js\";\n\nexport interface NuxtActionsModuleOptions {\n actionsDir?: string;\n generatedDir?: string;\n}\n\ninterface NuxtLike {\n options?: {\n rootDir?: string;\n };\n hook?: (name: string, fn: () => void | Promise<void>) => void;\n}\n\n/**\n * Lightweight Nuxt module that runs deterministic `.generated/actions.ts` and\n * `.generated/action-types.d.ts` codegen during Nuxt prepare and build.\n */\nexport default function agentNativeActionsNuxtModule(\n moduleOptions: NuxtActionsModuleOptions = {},\n nuxt?: NuxtLike,\n): void {\n const projectRoot = nuxt?.options?.rootDir ?? process.cwd();\n const run = () => {\n generateActionArtifacts({\n projectRoot,\n ...(moduleOptions.actionsDir\n ? { actionsDir: moduleOptions.actionsDir }\n : {}),\n ...(moduleOptions.generatedDir\n ? { generatedDir: moduleOptions.generatedDir }\n : {}),\n });\n };\n\n run();\n nuxt?.hook?.(\"prepare:types\", run);\n nuxt?.hook?.(\"build:before\", run);\n}\n"],"mappings":";;;;;AAkBe,SAAR,6BACL,gBAA0C,CAAC,GAC3C,MACM;AACN,QAAM,cAAc,MAAM,SAAS,WAAW,QAAQ,IAAI;AAC1D,QAAM,MAAM,MAAM;AAChB,4BAAwB;AAAA,MACtB;AAAA,MACA,GAAI,cAAc,aACd,EAAE,YAAY,cAAc,WAAW,IACvC,CAAC;AAAA,MACL,GAAI,cAAc,eACd,EAAE,cAAc,cAAc,aAAa,IAC3C,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AAEA,MAAI;AACJ,QAAM,OAAO,iBAAiB,GAAG;AACjC,QAAM,OAAO,gBAAgB,GAAG;AAClC;","names":[]}
@@ -0,0 +1,50 @@
1
+ import * as _tanstack_react_query from '@tanstack/react-query';
2
+ import { UseMutationOptions, UseQueryOptions, UseQueryResult, UseMutationResult } from '@tanstack/react-query';
3
+ import { A as ActionClientError, a as ActionCallOptions, b as ActionClientOptions, c as ActionClient, d as ActionNameOf, e as ActionInputOf, f as ActionOutputOf, g as actionErrorMessage } from './client-C87WZhlZ.js';
4
+ import '@standard-schema/spec';
5
+
6
+ interface ActionQueryHookOptions<TData> extends Omit<UseQueryOptions<TData, ActionClientError, TData, readonly unknown[]>, "queryKey" | "queryFn"> {
7
+ /** Partition the local query cache by viewer/tenant without sending it to the server. */
8
+ queryKeyScope?: string;
9
+ /** Override HTTP method (defaults to GET for queries). */
10
+ method?: "GET" | "POST";
11
+ headers?: HeadersInit;
12
+ }
13
+ interface ActionMutationHookOptions<TData, TInput, TNames extends string> extends Omit<UseMutationOptions<TData, ActionClientError, TInput>, "mutationFn"> {
14
+ /**
15
+ * Targeted list of query action names to invalidate on success.
16
+ * Defaults to invalidating all active `agent-native-action` queries in this client scope.
17
+ */
18
+ invalidate?: readonly TNames[] | false;
19
+ method?: "POST" | "PUT" | "PATCH" | "DELETE";
20
+ headers?: HeadersInit;
21
+ approvalToken?: string;
22
+ }
23
+ declare function createActionHooks<TRegistry = unknown>(options?: ActionClientOptions): {
24
+ client: ActionClient<TRegistry>;
25
+ callAction: <TName extends ActionNameOf<TRegistry>>(name: TName, input?: ActionInputOf<TRegistry, TName> | undefined, options?: ActionCallOptions) => Promise<ActionOutputOf<TRegistry, TName>>;
26
+ actionQueryOptions: <TName extends ActionNameOf<TRegistry>>(name: TName, input?: ActionInputOf<TRegistry, TName>, hookOptions?: ActionQueryHookOptions<ActionOutputOf<TRegistry, TName>>) => _tanstack_react_query.OmitKeyof<UseQueryOptions<ActionOutputOf<TRegistry, TName>, ActionClientError, ActionOutputOf<TRegistry, TName>, readonly unknown[]>, "queryFn"> & {
27
+ queryFn?: _tanstack_react_query.QueryFunction<ActionOutputOf<TRegistry, TName>, readonly unknown[], never>;
28
+ } & {
29
+ queryKey: readonly unknown[] & {
30
+ [dataTagSymbol]: ActionOutputOf<TRegistry, TName>;
31
+ [dataTagErrorSymbol]: ActionClientError;
32
+ };
33
+ };
34
+ useActionQuery: <TName extends ActionNameOf<TRegistry>>(name: TName, input?: ActionInputOf<TRegistry, TName>, hookOptions?: ActionQueryHookOptions<ActionOutputOf<TRegistry, TName>>) => UseQueryResult<ActionOutputOf<TRegistry, TName>, ActionClientError>;
35
+ useActionMutation: <TName extends ActionNameOf<TRegistry>>(name: TName, hookOptions?: ActionMutationHookOptions<ActionOutputOf<TRegistry, TName>, ActionInputOf<TRegistry, TName>, ActionNameOf<TRegistry>>) => UseMutationResult<ActionOutputOf<TRegistry, TName>, ActionClientError, ActionInputOf<TRegistry, TName>>;
36
+ actionErrorMessage: typeof actionErrorMessage;
37
+ };
38
+ declare const callAction: <TName extends string>(name: TName, input?: (TName extends string ? unknown : Record<string, unknown>) | undefined, options?: ActionCallOptions) => Promise<TName extends string ? unknown : unknown>;
39
+ declare const actionQueryOptions: <TName extends string>(name: TName, input?: (TName extends string ? unknown : Record<string, unknown>) | undefined, hookOptions?: ActionQueryHookOptions<TName extends string ? unknown : unknown>) => _tanstack_react_query.OmitKeyof<UseQueryOptions<TName extends string ? unknown : unknown, ActionClientError, TName extends string ? unknown : unknown, readonly unknown[]>, "queryFn"> & {
40
+ queryFn?: _tanstack_react_query.QueryFunction<TName extends string ? unknown : unknown, readonly unknown[], never>;
41
+ } & {
42
+ queryKey: readonly unknown[] & {
43
+ [dataTagSymbol]: TName extends string ? unknown : unknown;
44
+ [dataTagErrorSymbol]: ActionClientError;
45
+ };
46
+ };
47
+ declare const useActionQuery: <TName extends string>(name: TName, input?: (TName extends string ? unknown : Record<string, unknown>) | undefined, hookOptions?: ActionQueryHookOptions<TName extends string ? unknown : unknown>) => UseQueryResult<TName extends string ? unknown : unknown, ActionClientError>;
48
+ declare const useActionMutation: <TName extends string>(name: TName, hookOptions?: ActionMutationHookOptions<TName extends string ? unknown : unknown, TName extends string ? unknown : Record<string, unknown>, string>) => UseMutationResult<TName extends string ? unknown : unknown, ActionClientError, TName extends string ? unknown : Record<string, unknown>>;
49
+
50
+ export { ActionCallOptions, ActionClient, ActionClientError, ActionClientOptions, type ActionMutationHookOptions, type ActionQueryHookOptions, actionErrorMessage, actionQueryOptions, callAction, createActionHooks, useActionMutation, useActionQuery };