@agent-native/core 0.51.15 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -96
- package/blueprints/action/crud.md +98 -0
- package/blueprints/channel/discord.md +74 -0
- package/blueprints/provider/stripe.md +87 -0
- package/blueprints/sandbox/docker.md +78 -0
- package/dist/action.d.ts +24 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +4 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/observational-memory/compactor.d.ts +43 -0
- package/dist/agent/observational-memory/compactor.d.ts.map +1 -0
- package/dist/agent/observational-memory/compactor.js +50 -0
- package/dist/agent/observational-memory/compactor.js.map +1 -0
- package/dist/agent/observational-memory/config.d.ts +37 -0
- package/dist/agent/observational-memory/config.d.ts.map +1 -0
- package/dist/agent/observational-memory/config.js +48 -0
- package/dist/agent/observational-memory/config.js.map +1 -0
- package/dist/agent/observational-memory/index.d.ts +26 -0
- package/dist/agent/observational-memory/index.d.ts.map +1 -0
- package/dist/agent/observational-memory/index.js +25 -0
- package/dist/agent/observational-memory/index.js.map +1 -0
- package/dist/agent/observational-memory/internal-run.d.ts +37 -0
- package/dist/agent/observational-memory/internal-run.d.ts.map +1 -0
- package/dist/agent/observational-memory/internal-run.js +59 -0
- package/dist/agent/observational-memory/internal-run.js.map +1 -0
- package/dist/agent/observational-memory/message-text.d.ts +13 -0
- package/dist/agent/observational-memory/message-text.d.ts.map +1 -0
- package/dist/agent/observational-memory/message-text.js +46 -0
- package/dist/agent/observational-memory/message-text.js.map +1 -0
- package/dist/agent/observational-memory/migrations.d.ts +13 -0
- package/dist/agent/observational-memory/migrations.d.ts.map +1 -0
- package/dist/agent/observational-memory/migrations.js +43 -0
- package/dist/agent/observational-memory/migrations.js.map +1 -0
- package/dist/agent/observational-memory/observer.d.ts +37 -0
- package/dist/agent/observational-memory/observer.d.ts.map +1 -0
- package/dist/agent/observational-memory/observer.js +82 -0
- package/dist/agent/observational-memory/observer.js.map +1 -0
- package/dist/agent/observational-memory/plugin.d.ts +16 -0
- package/dist/agent/observational-memory/plugin.d.ts.map +1 -0
- package/dist/agent/observational-memory/plugin.js +26 -0
- package/dist/agent/observational-memory/plugin.js.map +1 -0
- package/dist/agent/observational-memory/prompts.d.ts +27 -0
- package/dist/agent/observational-memory/prompts.d.ts.map +1 -0
- package/dist/agent/observational-memory/prompts.js +42 -0
- package/dist/agent/observational-memory/prompts.js.map +1 -0
- package/dist/agent/observational-memory/read.d.ts +47 -0
- package/dist/agent/observational-memory/read.d.ts.map +1 -0
- package/dist/agent/observational-memory/read.js +99 -0
- package/dist/agent/observational-memory/read.js.map +1 -0
- package/dist/agent/observational-memory/reflector.d.ts +31 -0
- package/dist/agent/observational-memory/reflector.d.ts.map +1 -0
- package/dist/agent/observational-memory/reflector.js +76 -0
- package/dist/agent/observational-memory/reflector.js.map +1 -0
- package/dist/agent/observational-memory/schema.d.ts +267 -0
- package/dist/agent/observational-memory/schema.d.ts.map +1 -0
- package/dist/agent/observational-memory/schema.js +48 -0
- package/dist/agent/observational-memory/schema.js.map +1 -0
- package/dist/agent/observational-memory/store.d.ts +52 -0
- package/dist/agent/observational-memory/store.d.ts.map +1 -0
- package/dist/agent/observational-memory/store.js +197 -0
- package/dist/agent/observational-memory/store.js.map +1 -0
- package/dist/agent/observational-memory/types.d.ts +61 -0
- package/dist/agent/observational-memory/types.d.ts.map +1 -0
- package/dist/agent/observational-memory/types.js +9 -0
- package/dist/agent/observational-memory/types.js.map +1 -0
- package/dist/agent/production-agent.d.ts +15 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +240 -1
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-loop-with-resume.d.ts.map +1 -1
- package/dist/agent/run-loop-with-resume.js +49 -0
- package/dist/agent/run-loop-with-resume.js.map +1 -1
- package/dist/agent/run-store.d.ts +17 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +55 -0
- package/dist/agent/run-store.js.map +1 -1
- package/dist/agent/runtime-context.d.ts +30 -0
- package/dist/agent/runtime-context.d.ts.map +1 -1
- package/dist/agent/runtime-context.js +54 -1
- package/dist/agent/runtime-context.js.map +1 -1
- package/dist/agent/tool-call-journal.d.ts +101 -0
- package/dist/agent/tool-call-journal.d.ts.map +1 -0
- package/dist/agent/tool-call-journal.js +214 -0
- package/dist/agent/tool-call-journal.js.map +1 -0
- package/dist/agent/types.d.ts +24 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/cli/add.d.ts +109 -0
- package/dist/cli/add.d.ts.map +1 -0
- package/dist/cli/add.js +352 -0
- package/dist/cli/add.js.map +1 -0
- package/dist/cli/connect.d.ts +5 -4
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +157 -48
- package/dist/cli/connect.js.map +1 -1
- package/dist/cli/eval.d.ts +17 -0
- package/dist/cli/eval.d.ts.map +1 -0
- package/dist/cli/eval.js +121 -0
- package/dist/cli/eval.js.map +1 -0
- package/dist/cli/index.js +44 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp-config-writers.d.ts +20 -13
- package/dist/cli/mcp-config-writers.d.ts.map +1 -1
- package/dist/cli/mcp-config-writers.js +152 -13
- package/dist/cli/mcp-config-writers.js.map +1 -1
- package/dist/cli/mcp.d.ts +2 -2
- package/dist/cli/mcp.d.ts.map +1 -1
- package/dist/cli/mcp.js +50 -196
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli/plan-local.d.ts +69 -6
- package/dist/cli/plan-local.d.ts.map +1 -1
- package/dist/cli/plan-local.js +517 -23
- package/dist/cli/plan-local.js.map +1 -1
- package/dist/cli/recap.d.ts.map +1 -1
- package/dist/cli/recap.js +1 -1
- package/dist/cli/recap.js.map +1 -1
- package/dist/cli/skills.d.ts +13 -6
- package/dist/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +287 -111
- package/dist/cli/skills.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +118 -92
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +16 -0
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/agent-engine-key.d.ts +6 -4
- package/dist/client/agent-engine-key.d.ts.map +1 -1
- package/dist/client/agent-engine-key.js +9 -6
- package/dist/client/agent-engine-key.js.map +1 -1
- package/dist/client/chat/run-recovery.js +1 -1
- package/dist/client/chat/run-recovery.js.map +1 -1
- package/dist/client/chat/tool-call-display.d.ts +20 -1
- package/dist/client/chat/tool-call-display.d.ts.map +1 -1
- package/dist/client/chat/tool-call-display.js +32 -7
- package/dist/client/chat/tool-call-display.js.map +1 -1
- package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
- package/dist/client/settings/SettingsPanel.js +7 -14
- package/dist/client/settings/SettingsPanel.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts +13 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +21 -0
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/coding-tools/run-code.d.ts +7 -0
- package/dist/coding-tools/run-code.d.ts.map +1 -1
- package/dist/coding-tools/run-code.js +21 -106
- package/dist/coding-tools/run-code.js.map +1 -1
- package/dist/coding-tools/sandbox/adapter.d.ts +79 -0
- package/dist/coding-tools/sandbox/adapter.d.ts.map +1 -0
- package/dist/coding-tools/sandbox/adapter.js +24 -0
- package/dist/coding-tools/sandbox/adapter.js.map +1 -0
- package/dist/coding-tools/sandbox/index.d.ts +51 -0
- package/dist/coding-tools/sandbox/index.d.ts.map +1 -0
- package/dist/coding-tools/sandbox/index.js +79 -0
- package/dist/coding-tools/sandbox/index.js.map +1 -0
- package/dist/coding-tools/sandbox/local-child-process-adapter.d.ts +24 -0
- package/dist/coding-tools/sandbox/local-child-process-adapter.d.ts.map +1 -0
- package/dist/coding-tools/sandbox/local-child-process-adapter.js +141 -0
- package/dist/coding-tools/sandbox/local-child-process-adapter.js.map +1 -0
- package/dist/db/client.d.ts +4 -2
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +6 -4
- package/dist/db/client.js.map +1 -1
- package/dist/deploy/route-discovery.d.ts.map +1 -1
- package/dist/deploy/route-discovery.js +1 -0
- package/dist/deploy/route-discovery.js.map +1 -1
- package/dist/eval/agent-runner.d.ts +63 -0
- package/dist/eval/agent-runner.d.ts.map +1 -0
- package/dist/eval/agent-runner.js +142 -0
- package/dist/eval/agent-runner.js.map +1 -0
- package/dist/eval/define-eval.d.ts +29 -0
- package/dist/eval/define-eval.d.ts.map +1 -0
- package/dist/eval/define-eval.js +43 -0
- package/dist/eval/define-eval.js.map +1 -0
- package/dist/eval/index.d.ts +18 -0
- package/dist/eval/index.d.ts.map +1 -0
- package/dist/eval/index.js +17 -0
- package/dist/eval/index.js.map +1 -0
- package/dist/eval/report.d.ts +8 -0
- package/dist/eval/report.d.ts.map +1 -0
- package/dist/eval/report.js +44 -0
- package/dist/eval/report.js.map +1 -0
- package/dist/eval/runner.d.ts +67 -0
- package/dist/eval/runner.d.ts.map +1 -0
- package/dist/eval/runner.js +256 -0
- package/dist/eval/runner.js.map +1 -0
- package/dist/eval/scorer.d.ts +83 -0
- package/dist/eval/scorer.d.ts.map +1 -0
- package/dist/eval/scorer.js +195 -0
- package/dist/eval/scorer.js.map +1 -0
- package/dist/eval/types.d.ts +162 -0
- package/dist/eval/types.d.ts.map +1 -0
- package/dist/eval/types.js +20 -0
- package/dist/eval/types.js.map +1 -0
- package/dist/observability/traces.d.ts.map +1 -1
- package/dist/observability/traces.js +100 -1
- package/dist/observability/traces.js.map +1 -1
- package/dist/observability/tracing.d.ts +73 -0
- package/dist/observability/tracing.d.ts.map +1 -0
- package/dist/observability/tracing.js +126 -0
- package/dist/observability/tracing.js.map +1 -0
- package/dist/onboarding/default-steps.d.ts.map +1 -1
- package/dist/onboarding/default-steps.js +4 -1
- package/dist/onboarding/default-steps.js.map +1 -1
- package/dist/provider-api/actions/query-staged-dataset.d.ts +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.js +10 -3
- package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
- package/dist/server/action-discovery.d.ts.map +1 -1
- package/dist/server/action-discovery.js +4 -0
- package/dist/server/action-discovery.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +9 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +118 -110
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +37 -0
- package/dist/server/agent-engine-api-key-route.d.ts.map +1 -0
- package/dist/server/agent-engine-api-key-route.js +105 -0
- package/dist/server/agent-engine-api-key-route.js.map +1 -0
- package/dist/server/agent-teams.d.ts +62 -0
- package/dist/server/agent-teams.d.ts.map +1 -1
- package/dist/server/agent-teams.js +99 -2
- package/dist/server/agent-teams.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +17 -10
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/create-server.js +1 -1
- package/dist/server/create-server.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +2 -0
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +33 -1
- package/dist/server/framework-request-handler.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +17 -4
- package/dist/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +20 -0
- package/dist/templates/workspace-core/.agents/skills/observability/SKILL.md +20 -0
- package/docs/content/agent-teams.md +32 -0
- package/docs/content/blueprint-installer.md +73 -0
- package/docs/content/evals.md +141 -0
- package/docs/content/pr-visual-recap.md +7 -4
- package/docs/content/sandbox-adapters.md +134 -0
- package/docs/content/template-plan.md +20 -8
- package/package.json +5 -1
- package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +17 -4
- package/src/templates/workspace-core/.agents/skills/harness-agents/SKILL.md +20 -0
- package/src/templates/workspace-core/.agents/skills/observability/SKILL.md +20 -0
package/dist/action.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAkFA;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,eAAe,GAAG,IAAI,CAAC;IACvB,SAAS,CAAU;IACnB,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,UAAkC,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACvC,CAAC;CACF;AAED,MAAM,UAAU,sBAAsB,CACpC,GAAY;IAEZ,OAAO,CACL,GAAG,YAAY,oBAAoB;QACnC,OAAO,CACL,GAAG;YACH,OAAO,GAAG,KAAK,QAAQ;YACvB,iBAAiB,IAAI,GAAG;YACvB,GAAqC,CAAC,eAAe,KAAK,IAAI,CAChE,CACF,CAAC;AACJ,CAAC;AA0CD,MAAM,CAAC,MAAM,oBAAoB,GAAG,4BAAqC,CAAC;AAC1E,MAAM,CAAC,MAAM,iBAAiB,GAAG,2BAAoC,CAAC;AACtE,MAAM,CAAC,MAAM,6BAA6B,GAAG,gBAAyB,CAAC;AAqTvE,MAAM,UAAU,YAAY,CAAC,OAAY;IACvC,MAAM,SAAS,G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B,GAAG,wCAAwC,CAAC;YAC3E,CAAC;YAED,MAAM,IAAI,KAAK,CACb,+BAA+B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,QAAQ,IAAI,QAAQ,EAAE,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAE,MAA8C,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzE,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ActionTool,\n AgentChatAttachment,\n AgentChatEvent,\n} from \"./agent/types.js\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * How an action's `run` was invoked. Tagged at each dispatch site so the action\n * (and tracking) can branch on the surface that called it.\n *\n * - `\"tool\"` — the in-app agent loop, sub-agents/agent-teams, or A2A (which\n * drives the same agent loop). All agent tool calls are `\"tool\"`.\n * - `\"http\"` — a programmatic HTTP POST/GET to `/_agent-native/actions/<name>`\n * without the frontend request marker.\n * - `\"frontend\"` — a browser call via `useActionQuery` / `useActionMutation` /\n * `callAction` (tagged with the `X-Request-Source` header).\n * - `\"cli\"` — `pnpm action <name>` (the CLI runner).\n * - `\"mcp\"` — an external agent over the MCP `tools/call` endpoint.\n * - `\"a2a\"` — a direct A2A action dispatch (currently unused: A2A runs through\n * the agent loop, so those calls are `\"tool\"`). Reserved for completeness.\n */\nexport type ActionCaller = \"tool\" | \"http\" | \"frontend\" | \"cli\" | \"mcp\" | \"a2a\";\n\n/**\n * Context passed as the optional second argument to an action's `run`.\n * Carries the resolved request identity and the invocation source so actions\n * can read `ctx.userEmail` / `ctx.orgId` / `ctx.caller` directly instead of\n * calling `getRequestUserEmail()` / `getRequestOrgId()` by hand.\n *\n * Backward compatible: existing 1-arg `run(args)` functions keep working, and\n * callers that only need `send` (the agent loop) can still destructure it.\n */\nexport interface ActionRunContext {\n /**\n * Emit an SSE event to the client. Only meaningful inside the agent tool\n * loop (e.g. `agent_call_text` streaming); `undefined` on every other\n * surface.\n */\n send?: (event: AgentChatEvent) => void;\n /**\n * Resolved request user email, or `undefined` when there is no authenticated\n * identity. NEVER defaulted to a dev identity — actions that need a fallback\n * must apply their own.\n */\n userEmail?: string;\n /** Resolved org id, or `null` when the request has no org. */\n orgId?: string | null;\n /** How this action was invoked. */\n caller: ActionCaller;\n /**\n * Attachments submitted with the current agent turn (pasted text blocks,\n * uploaded files, images), exactly as the server received them — with full,\n * untruncated `text` for text attachments. Populated only inside the agent\n * tool loop (`caller: \"tool\"`); `undefined` on every other surface.\n *\n * Lets an action consume a large pasted artifact BY REFERENCE (e.g.\n * `create-extension`'s `contentFromAttachment`) instead of forcing the model\n * to re-emit the whole file as a tool argument — which frequently gets cut\n * off mid-stream and triggers a continuation loop.\n */\n attachments?: AgentChatAttachment[];\n /**\n * Abort signal for the current agent run. Fires when the run is soft-timed\n * out, user-cancelled, or the server is shutting down. Well-behaved actions\n * can observe this signal to cancel in-flight work early instead of waiting\n * for the per-tool 60-second hard timeout.\n *\n * Populated only inside the agent tool loop (`caller: \"tool\"`); `undefined`\n * on every other surface. Never throws — checking `signal.aborted` or\n * attaching an `\"abort\"` listener is always safe.\n */\n signal?: AbortSignal;\n}\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n /**\n * Optional MCP Apps UI resource for hosts that render inline app iframes.\n * Required when the action should open an interactive app view. Omit when\n * you only need `compactCatalog: true` to keep a non-UI action visible in\n * the compact catalog (e.g. read/update actions that should be callable from\n * Claude.ai / ChatGPT without a dedicated iframe resource).\n */\n resource?: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n /**\n * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with\n * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so\n * hosts do not ingest every action-specific UI resource. Set this only when\n * this specific action must stay visible in that compact catalog.\n */\n compactCatalog?: boolean;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. Set to false only for metadata/read actions that safely\n * handle `ctx.userEmail` / `getRequestUserEmail()` being undefined. */\n requiresAuth?: boolean;\n /** Whether this action is exposed to the agent — the in-app assistant and the\n * app's MCP/A2A tool surfaces — as a callable tool. **Default-allow opt-out**:\n * `undefined` / `true` expose it; only an explicit `false` hides it from every\n * agent tool list while keeping it callable from the frontend / HTTP\n * (`useActionMutation`, `callAction`, `/_agent-native/actions/<name>`). Use\n * this for UI-only or purely programmatic actions you want behind the\n * framework's auth + action surface WITHOUT spending a slot in the model's\n * tool list. Distinct from `toolCallable`, which only governs the sandboxed\n * extension (\"tools\") iframe bridge. See `packages/core/docs/content/actions.md`. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.md`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n run: (\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. See the schema overload above. */\n requiresAuth?: boolean;\n /** Whether this action is exposed to the agent as a callable tool. Only an\n * explicit `false` hides it from every agent tool list while keeping it\n * frontend/HTTP-callable. See the schema overload above and actions.md. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Return type — carries schema-inferred input + run return for client inference\n// ---------------------------------------------------------------------------\n\n/**\n * Opaque typed wrapper returned by `defineAction`. The type parameters carry\n * the schema-inferred input and the `run` return type so that:\n *\n * - The generated `.generated/action-types.d.ts` can extract them via\n * `typeof import(\"../actions/my-action\").default.run` and augment\n * `ActionRegistry` with concrete param/result types.\n * - `useActionQuery` / `useActionMutation` / `callAction` in the client hooks\n * flow the correct types end-to-end without manual generic annotations.\n *\n * Runtime shape is unchanged — this is a declaration-only wrapper.\n */\nexport interface ActionDefinition<TInput, TReturn> {\n /**\n * Typed run function — declaration only; infer input/return from this.\n * `TInput` is the schema's input type (optional defaults allowed at call\n * sites); `TReturn` is the awaited result type of the run callback.\n */\n readonly run: (\n args: TInput,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n /** @internal Framework use only — do not call directly. */\n readonly tool: import(\"./agent/types.js\").ActionTool;\n readonly http?: ActionHttpConfig | false;\n readonly requiresAuth?: boolean;\n readonly agentTool?: boolean;\n readonly readOnly?: boolean;\n readonly parallelSafe?: boolean;\n readonly toolCallable?: boolean;\n readonly publicAgent?: PublicAgentActionConfig;\n readonly link?: ActionLinkBuilder;\n readonly mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<TSchema extends StandardSchemaV1, TReturn>(\n options: DefineActionWithSchema<TSchema, TReturn>,\n): ActionDefinition<StandardSchemaV1.InferInput<TSchema>, TReturn>;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(\n options: DefineActionWithParams<TParams, TReturn>,\n): ActionDefinition<InferParams<TParams>, TReturn>;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // Wrap run() with validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const run = hasSchema\n ? wrapWithValidation(options.schema, options.run, toolParameters)\n : options.run;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n // agentTool: default-allow opt-out. Only an explicit `false` hides the action\n // from the agent tool surfaces; undefined is preserved (treated as exposed).\n const agentTool: boolean | undefined =\n typeof options.agentTool === \"boolean\" ? options.agentTool : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined = (() => {\n if (\n !options.mcpApp ||\n typeof options.mcpApp !== \"object\" ||\n Array.isArray(options.mcpApp)\n ) {\n return undefined;\n }\n // compactCatalog-only: no resource required; just keep the flag.\n if (options.mcpApp.compactCatalog === true && !options.mcpApp.resource) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n // Full resource: validate html is present.\n if (\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n return undefined;\n })();\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof options.requiresAuth === \"boolean\"\n ? { requiresAuth: options.requiresAuth }\n : {}),\n ...(typeof agentTool === \"boolean\" ? { agentTool } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return result as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return zodDefToJsonSchema(s._zod.def);\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (\n fieldDef.type !== \"optional\" &&\n fieldDef.type !== \"default\" &&\n fieldDef.type !== \"nullable\"\n ) {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n // Surface null as a valid value so the model knows it may pass null\n // (and doesn't treat the field as a non-nullable required string).\n return { anyOf: [inner, { type: \"null\" }] };\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n const values = def.options.map((o: any) => o._zod.def.value);\n const jsonTypeOf = (v: any) =>\n typeof v === \"number\"\n ? \"number\"\n : typeof v === \"boolean\"\n ? \"boolean\"\n : \"string\";\n const uniqueTypes = [...new Set(values.map(jsonTypeOf))];\n if (uniqueTypes.length === 1) {\n // Homogeneous literal union (e.g. all numbers) — derive the JSON\n // type instead of hardcoding \"string\", which would contradict the\n // enum values and make the model coerce/round-trip them wrongly.\n return { type: uniqueTypes[0], enum: values };\n }\n // Mixed literal types: emit anyOf so each branch stays self-consistent.\n return {\n anyOf: values.map((v: any) => ({ type: jsonTypeOf(v), enum: [v] })),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // z.preprocess / z.pipe / .superRefine / .transform all produce a \"pipe\"\n // def with `in` (pre-transform) and `out` (post-transform). For JSON Schema\n // purposes, use `out` — it reflects the validated output shape the model\n // should populate.\n if (type === \"pipe\") {\n if (def.out?._zod?.def) {\n return zodDefToJsonSchema(def.out._zod.def);\n }\n if (def.in?._zod?.def) {\n return zodDefToJsonSchema(def.in._zod.def);\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value, ctx);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAkFA;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,eAAe,GAAG,IAAI,CAAC;IACvB,SAAS,CAAU;IACnB,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,UAAkC,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACvC,CAAC;CACF;AAED,MAAM,UAAU,sBAAsB,CACpC,GAAY;IAEZ,OAAO,CACL,GAAG,YAAY,oBAAoB;QACnC,OAAO,CACL,GAAG;YACH,OAAO,GAAG,KAAK,QAAQ;YACvB,iBAAiB,IAAI,GAAG;YACvB,GAAqC,CAAC,eAAe,KAAK,IA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AO,CAAC,cAAc,CAAC,UAAU,CAAC;qBAClD,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE;oBACd,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;oBACzC,MAAM,IAAI,GAAI,CAAuB,CAAC,IAAI,IAAI,KAAK,CAAC;oBACpD,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,IAAI,EAAE,CAAC;gBAChC,CAAC,CAAC;qBACD,IAAI,CAAC,IAAI,CAAC,CAAC;gBACd,IAAI,GAAG;oBACL,QAAQ,GAAG,gBAAgB,GAAG,wCAAwC,CAAC;YAC3E,CAAC;YAED,MAAM,IAAI,KAAK,CACb,+BAA+B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,QAAQ,IAAI,QAAQ,EAAE,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAE,MAA8C,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzE,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ActionTool,\n AgentChatAttachment,\n AgentChatEvent,\n} from \"./agent/types.js\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * How an action's `run` was invoked. Tagged at each dispatch site so the action\n * (and tracking) can branch on the surface that called it.\n *\n * - `\"tool\"` — the in-app agent loop, sub-agents/agent-teams, or A2A (which\n * drives the same agent loop). All agent tool calls are `\"tool\"`.\n * - `\"http\"` — a programmatic HTTP POST/GET to `/_agent-native/actions/<name>`\n * without the frontend request marker.\n * - `\"frontend\"` — a browser call via `useActionQuery` / `useActionMutation` /\n * `callAction` (tagged with the `X-Request-Source` header).\n * - `\"cli\"` — `pnpm action <name>` (the CLI runner).\n * - `\"mcp\"` — an external agent over the MCP `tools/call` endpoint.\n * - `\"a2a\"` — a direct A2A action dispatch (currently unused: A2A runs through\n * the agent loop, so those calls are `\"tool\"`). Reserved for completeness.\n */\nexport type ActionCaller = \"tool\" | \"http\" | \"frontend\" | \"cli\" | \"mcp\" | \"a2a\";\n\n/**\n * Context passed as the optional second argument to an action's `run`.\n * Carries the resolved request identity and the invocation source so actions\n * can read `ctx.userEmail` / `ctx.orgId` / `ctx.caller` directly instead of\n * calling `getRequestUserEmail()` / `getRequestOrgId()` by hand.\n *\n * Backward compatible: existing 1-arg `run(args)` functions keep working, and\n * callers that only need `send` (the agent loop) can still destructure it.\n */\nexport interface ActionRunContext {\n /**\n * Emit an SSE event to the client. Only meaningful inside the agent tool\n * loop (e.g. `agent_call_text` streaming); `undefined` on every other\n * surface.\n */\n send?: (event: AgentChatEvent) => void;\n /**\n * Resolved request user email, or `undefined` when there is no authenticated\n * identity. NEVER defaulted to a dev identity — actions that need a fallback\n * must apply their own.\n */\n userEmail?: string;\n /** Resolved org id, or `null` when the request has no org. */\n orgId?: string | null;\n /** How this action was invoked. */\n caller: ActionCaller;\n /**\n * Attachments submitted with the current agent turn (pasted text blocks,\n * uploaded files, images), exactly as the server received them — with full,\n * untruncated `text` for text attachments. Populated only inside the agent\n * tool loop (`caller: \"tool\"`); `undefined` on every other surface.\n *\n * Lets an action consume a large pasted artifact BY REFERENCE (e.g.\n * `create-extension`'s `contentFromAttachment`) instead of forcing the model\n * to re-emit the whole file as a tool argument — which frequently gets cut\n * off mid-stream and triggers a continuation loop.\n */\n attachments?: AgentChatAttachment[];\n /**\n * Abort signal for the current agent run. Fires when the run is soft-timed\n * out, user-cancelled, or the server is shutting down. Well-behaved actions\n * can observe this signal to cancel in-flight work early instead of waiting\n * for the per-tool 60-second hard timeout.\n *\n * Populated only inside the agent tool loop (`caller: \"tool\"`); `undefined`\n * on every other surface. Never throws — checking `signal.aborted` or\n * attaching an `\"abort\"` listener is always safe.\n */\n signal?: AbortSignal;\n}\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n /**\n * Host-specific sandbox domain hint. Do not set this to the app's normal\n * production URL; app origins belong in CSP/open-link metadata. ChatGPT uses\n * the separate `openai/widgetDomain` compatibility field.\n */\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n /**\n * Optional MCP Apps UI resource for hosts that render inline app iframes.\n * Required when the action should open an interactive app view. Omit when\n * you only need `compactCatalog: true` to keep a non-UI action visible in\n * the compact catalog (e.g. read/update actions that should be callable from\n * Claude.ai / ChatGPT without a dedicated iframe resource).\n */\n resource?: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n /**\n * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with\n * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so\n * hosts do not ingest every action-specific UI resource. Set this only when\n * this specific action must stay visible in that compact catalog.\n */\n compactCatalog?: boolean;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. Set to false only for metadata/read actions that safely\n * handle `ctx.userEmail` / `getRequestUserEmail()` being undefined. */\n requiresAuth?: boolean;\n /** Whether this action is exposed to the agent — the in-app assistant and the\n * app's MCP/A2A tool surfaces — as a callable tool. **Default-allow opt-out**:\n * `undefined` / `true` expose it; only an explicit `false` hides it from every\n * agent tool list while keeping it callable from the frontend / HTTP\n * (`useActionMutation`, `callAction`, `/_agent-native/actions/<name>`). Use\n * this for UI-only or purely programmatic actions you want behind the\n * framework's auth + action surface WITHOUT spending a slot in the model's\n * tool list. Distinct from `toolCallable`, which only governs the sandboxed\n * extension (\"tools\") iframe bridge. See `packages/core/docs/content/actions.md`. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.md`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n /**\n * Opt-in human-in-the-loop approval gate. **Default off** — the framework\n * intentionally keeps HITL approvals rare; almost every action should run\n * without one. Set this only for high-consequence, outward-facing,\n * hard-to-undo operations (the canonical example is actually sending an\n * email). When `needsApproval` resolves truthy and the agent calls this\n * action, the loop does NOT execute `run()`: it emits an `approval_required`\n * event and stops the turn, waiting for a human to approve. The action runs\n * only once the human re-issues the turn approving this specific call.\n *\n * - `true` — always require approval.\n * - `(args, ctx) => boolean | Promise<boolean>` — require approval only when\n * the predicate returns true (e.g. only for external recipients, only\n * above a dollar threshold). Keep it pure + fast; thrown errors are treated\n * as \"approval required\" (fail closed).\n */\n needsApproval?:\n | boolean\n | ((\n args: StandardSchemaV1.InferOutput<TSchema>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n run: (\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** Whether the HTTP/frontend action route must have an authenticated owner.\n * Defaults to true. See the schema overload above. */\n requiresAuth?: boolean;\n /** Whether this action is exposed to the agent as a callable tool. Only an\n * explicit `false` hides it from every agent tool list while keeping it\n * frontend/HTTP-callable. See the schema overload above and actions.md. */\n agentTool?: boolean;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n /** Opt-in human-in-the-loop approval gate (default off). See the schema\n * overload above for full semantics. */\n needsApproval?:\n | boolean\n | ((\n args: InferParams<TParams>,\n ctx?: ActionRunContext,\n ) => boolean | Promise<boolean>);\n}\n\n// ---------------------------------------------------------------------------\n// Return type — carries schema-inferred input + run return for client inference\n// ---------------------------------------------------------------------------\n\n/**\n * Opaque typed wrapper returned by `defineAction`. The type parameters carry\n * the schema-inferred input and the `run` return type so that:\n *\n * - The generated `.generated/action-types.d.ts` can extract them via\n * `typeof import(\"../actions/my-action\").default.run` and augment\n * `ActionRegistry` with concrete param/result types.\n * - `useActionQuery` / `useActionMutation` / `callAction` in the client hooks\n * flow the correct types end-to-end without manual generic annotations.\n *\n * Runtime shape is unchanged — this is a declaration-only wrapper.\n */\nexport interface ActionDefinition<TInput, TReturn> {\n /**\n * Typed run function — declaration only; infer input/return from this.\n * `TInput` is the schema's input type (optional defaults allowed at call\n * sites); `TReturn` is the awaited result type of the run callback.\n */\n readonly run: (\n args: TInput,\n ctx?: ActionRunContext,\n ) => Promise<TReturn> | TReturn;\n /** @internal Framework use only — do not call directly. */\n readonly tool: import(\"./agent/types.js\").ActionTool;\n readonly http?: ActionHttpConfig | false;\n readonly requiresAuth?: boolean;\n readonly agentTool?: boolean;\n readonly readOnly?: boolean;\n readonly parallelSafe?: boolean;\n readonly toolCallable?: boolean;\n readonly publicAgent?: PublicAgentActionConfig;\n readonly link?: ActionLinkBuilder;\n readonly mcpApp?: ActionMcpAppConfig;\n /** Opt-in human-in-the-loop approval gate (default off). When truthy, the\n * agent loop emits `approval_required` and pauses instead of executing this\n * action until a human approves the specific call. */\n readonly needsApproval?:\n | boolean\n | ((args: TInput, ctx?: ActionRunContext) => boolean | Promise<boolean>);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<TSchema extends StandardSchemaV1, TReturn>(\n options: DefineActionWithSchema<TSchema, TReturn>,\n): ActionDefinition<StandardSchemaV1.InferInput<TSchema>, TReturn>;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(\n options: DefineActionWithParams<TParams, TReturn>,\n): ActionDefinition<InferParams<TParams>, TReturn>;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // Wrap run() with validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const run = hasSchema\n ? wrapWithValidation(options.schema, options.run, toolParameters)\n : options.run;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n // agentTool: default-allow opt-out. Only an explicit `false` hides the action\n // from the agent tool surfaces; undefined is preserved (treated as exposed).\n const agentTool: boolean | undefined =\n typeof options.agentTool === \"boolean\" ? options.agentTool : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined = (() => {\n if (\n !options.mcpApp ||\n typeof options.mcpApp !== \"object\" ||\n Array.isArray(options.mcpApp)\n ) {\n return undefined;\n }\n // compactCatalog-only: no resource required; just keep the flag.\n if (options.mcpApp.compactCatalog === true && !options.mcpApp.resource) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n // Full resource: validate html is present.\n if (\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ) {\n return options.mcpApp as ActionMcpAppConfig;\n }\n return undefined;\n })();\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof options.requiresAuth === \"boolean\"\n ? { requiresAuth: options.requiresAuth }\n : {}),\n ...(typeof agentTool === \"boolean\" ? { agentTool } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n ...(typeof options.needsApproval === \"boolean\" ||\n typeof options.needsApproval === \"function\"\n ? { needsApproval: options.needsApproval }\n : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return result as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return zodDefToJsonSchema(s._zod.def);\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (\n fieldDef.type !== \"optional\" &&\n fieldDef.type !== \"default\" &&\n fieldDef.type !== \"nullable\"\n ) {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n // Surface null as a valid value so the model knows it may pass null\n // (and doesn't treat the field as a non-nullable required string).\n return { anyOf: [inner, { type: \"null\" }] };\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n const values = def.options.map((o: any) => o._zod.def.value);\n const jsonTypeOf = (v: any) =>\n typeof v === \"number\"\n ? \"number\"\n : typeof v === \"boolean\"\n ? \"boolean\"\n : \"string\";\n const uniqueTypes = [...new Set(values.map(jsonTypeOf))];\n if (uniqueTypes.length === 1) {\n // Homogeneous literal union (e.g. all numbers) — derive the JSON\n // type instead of hardcoding \"string\", which would contradict the\n // enum values and make the model coerce/round-trip them wrongly.\n return { type: uniqueTypes[0], enum: values };\n }\n // Mixed literal types: emit anyOf so each branch stays self-consistent.\n return {\n anyOf: values.map((v: any) => ({ type: jsonTypeOf(v), enum: [v] })),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // z.preprocess / z.pipe / .superRefine / .transform all produce a \"pipe\"\n // def with `in` (pre-transform) and `out` (post-transform). For JSON Schema\n // purposes, use `out` — it reflects the validated output shape the model\n // should populate.\n if (type === \"pipe\") {\n if (def.out?._zod?.def) {\n return zodDefToJsonSchema(def.out._zod.def);\n }\n if (def.in?._zod?.def) {\n return zodDefToJsonSchema(def.in._zod.def);\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any, ctx?: ActionRunContext) => any {\n return async (args: any, ctx?: ActionRunContext) => {\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value, ctx);\n };\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compactor orchestration for Observational Memory.
|
|
3
|
+
*
|
|
4
|
+
* `maybeCompactThread` is the single, decoupled entry point the agent loop can
|
|
5
|
+
* call AFTER a turn: it runs the Observer (which no-ops below the observation
|
|
6
|
+
* threshold) and then the Reflector (which no-ops below the reflection
|
|
7
|
+
* threshold). It is intentionally NOT wired into production-agent.ts here — it
|
|
8
|
+
* is exported so the loop can call it later.
|
|
9
|
+
*
|
|
10
|
+
* Messages can be supplied directly (the loop already has them) or loaded from
|
|
11
|
+
* the chat-threads store by `threadId` via the persisted `thread_data`. Loading
|
|
12
|
+
* goes through the existing `threadDataToEngineMessages` reader so OM never
|
|
13
|
+
* reimplements thread parsing.
|
|
14
|
+
*/
|
|
15
|
+
import type { EngineMessage } from "../engine/types.js";
|
|
16
|
+
import type { ObservationalMemoryConfig } from "./config.js";
|
|
17
|
+
import { type RunObserverResult } from "./observer.js";
|
|
18
|
+
import { type RunReflectorResult } from "./reflector.js";
|
|
19
|
+
import type { InternalAgentRunFn } from "./internal-run.js";
|
|
20
|
+
import type { ObservationalMemoryOwner } from "./types.js";
|
|
21
|
+
export interface MaybeCompactThreadOptions extends ObservationalMemoryOwner {
|
|
22
|
+
threadId: string;
|
|
23
|
+
/**
|
|
24
|
+
* The full, ordered thread messages. When omitted, they are loaded from the
|
|
25
|
+
* chat-threads store by `threadId`.
|
|
26
|
+
*/
|
|
27
|
+
messages?: EngineMessage[];
|
|
28
|
+
config?: Partial<ObservationalMemoryConfig>;
|
|
29
|
+
/** Internal-run seam — defaults to the real one; injected in tests. */
|
|
30
|
+
runInternal?: InternalAgentRunFn;
|
|
31
|
+
}
|
|
32
|
+
export interface MaybeCompactThreadResult {
|
|
33
|
+
observer: RunObserverResult;
|
|
34
|
+
reflector: RunReflectorResult;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Run a full compaction pass for a thread. Observer first (may fold the
|
|
38
|
+
* unobserved tail into an observation), then Reflector (may condense the
|
|
39
|
+
* observation log into a reflection). Both are no-ops below their thresholds,
|
|
40
|
+
* so this is cheap to call after every turn.
|
|
41
|
+
*/
|
|
42
|
+
export declare function maybeCompactThread(options: MaybeCompactThreadOptions): Promise<MaybeCompactThreadResult>;
|
|
43
|
+
//# sourceMappingURL=compactor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compactor.d.ts","sourceRoot":"","sources":["../../../src/agent/observational-memory/compactor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAe,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAgB,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAE3D,MAAM,WAAW,yBAA0B,SAAQ,wBAAwB;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC5C,uEAAuE;IACvE,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,SAAS,EAAE,kBAAkB,CAAC;CAC/B;AAQD;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,wBAAwB,CAAC,CAsBnC"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compactor orchestration for Observational Memory.
|
|
3
|
+
*
|
|
4
|
+
* `maybeCompactThread` is the single, decoupled entry point the agent loop can
|
|
5
|
+
* call AFTER a turn: it runs the Observer (which no-ops below the observation
|
|
6
|
+
* threshold) and then the Reflector (which no-ops below the reflection
|
|
7
|
+
* threshold). It is intentionally NOT wired into production-agent.ts here — it
|
|
8
|
+
* is exported so the loop can call it later.
|
|
9
|
+
*
|
|
10
|
+
* Messages can be supplied directly (the loop already has them) or loaded from
|
|
11
|
+
* the chat-threads store by `threadId` via the persisted `thread_data`. Loading
|
|
12
|
+
* goes through the existing `threadDataToEngineMessages` reader so OM never
|
|
13
|
+
* reimplements thread parsing.
|
|
14
|
+
*/
|
|
15
|
+
import { getThread } from "../../chat-threads/store.js";
|
|
16
|
+
import { threadDataToEngineMessages } from "../thread-data-builder.js";
|
|
17
|
+
import { runObserver } from "./observer.js";
|
|
18
|
+
import { runReflector } from "./reflector.js";
|
|
19
|
+
async function loadThreadMessages(threadId) {
|
|
20
|
+
const thread = await getThread(threadId);
|
|
21
|
+
if (!thread?.threadData)
|
|
22
|
+
return [];
|
|
23
|
+
return threadDataToEngineMessages(thread.threadData);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Run a full compaction pass for a thread. Observer first (may fold the
|
|
27
|
+
* unobserved tail into an observation), then Reflector (may condense the
|
|
28
|
+
* observation log into a reflection). Both are no-ops below their thresholds,
|
|
29
|
+
* so this is cheap to call after every turn.
|
|
30
|
+
*/
|
|
31
|
+
export async function maybeCompactThread(options) {
|
|
32
|
+
const messages = options.messages ?? (await loadThreadMessages(options.threadId));
|
|
33
|
+
const observer = await runObserver({
|
|
34
|
+
ownerEmail: options.ownerEmail,
|
|
35
|
+
orgId: options.orgId ?? null,
|
|
36
|
+
threadId: options.threadId,
|
|
37
|
+
messages,
|
|
38
|
+
config: options.config,
|
|
39
|
+
runInternal: options.runInternal,
|
|
40
|
+
});
|
|
41
|
+
const reflector = await runReflector({
|
|
42
|
+
ownerEmail: options.ownerEmail,
|
|
43
|
+
orgId: options.orgId ?? null,
|
|
44
|
+
threadId: options.threadId,
|
|
45
|
+
config: options.config,
|
|
46
|
+
runInternal: options.runInternal,
|
|
47
|
+
});
|
|
48
|
+
return { observer, reflector };
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=compactor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compactor.js","sourceRoot":"","sources":["../../../src/agent/observational-memory/compactor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAEvE,OAAO,EAAE,WAAW,EAA0B,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,YAAY,EAA2B,MAAM,gBAAgB,CAAC;AAqBvE,KAAK,UAAU,kBAAkB,CAAC,QAAgB;IAChD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,QAAQ,CAAC,CAAC;IACzC,IAAI,CAAC,MAAM,EAAE,UAAU;QAAE,OAAO,EAAE,CAAC;IACnC,OAAO,0BAA0B,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACvD,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAkC;IAElC,MAAM,QAAQ,GACZ,OAAO,CAAC,QAAQ,IAAI,CAAC,MAAM,kBAAkB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEnE,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC;QACjC,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,IAAI;QAC5B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ;QACR,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,WAAW,EAAE,OAAO,CAAC,WAAW;KACjC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC;QACnC,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,IAAI;QAC5B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,WAAW,EAAE,OAAO,CAAC,WAAW;KACjC,CAAC,CAAC;IAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Compactor orchestration for Observational Memory.\n *\n * `maybeCompactThread` is the single, decoupled entry point the agent loop can\n * call AFTER a turn: it runs the Observer (which no-ops below the observation\n * threshold) and then the Reflector (which no-ops below the reflection\n * threshold). It is intentionally NOT wired into production-agent.ts here — it\n * is exported so the loop can call it later.\n *\n * Messages can be supplied directly (the loop already has them) or loaded from\n * the chat-threads store by `threadId` via the persisted `thread_data`. Loading\n * goes through the existing `threadDataToEngineMessages` reader so OM never\n * reimplements thread parsing.\n */\n\nimport type { EngineMessage } from \"../engine/types.js\";\nimport { getThread } from \"../../chat-threads/store.js\";\nimport { threadDataToEngineMessages } from \"../thread-data-builder.js\";\nimport type { ObservationalMemoryConfig } from \"./config.js\";\nimport { runObserver, type RunObserverResult } from \"./observer.js\";\nimport { runReflector, type RunReflectorResult } from \"./reflector.js\";\nimport type { InternalAgentRunFn } from \"./internal-run.js\";\nimport type { ObservationalMemoryOwner } from \"./types.js\";\n\nexport interface MaybeCompactThreadOptions extends ObservationalMemoryOwner {\n threadId: string;\n /**\n * The full, ordered thread messages. When omitted, they are loaded from the\n * chat-threads store by `threadId`.\n */\n messages?: EngineMessage[];\n config?: Partial<ObservationalMemoryConfig>;\n /** Internal-run seam — defaults to the real one; injected in tests. */\n runInternal?: InternalAgentRunFn;\n}\n\nexport interface MaybeCompactThreadResult {\n observer: RunObserverResult;\n reflector: RunReflectorResult;\n}\n\nasync function loadThreadMessages(threadId: string): Promise<EngineMessage[]> {\n const thread = await getThread(threadId);\n if (!thread?.threadData) return [];\n return threadDataToEngineMessages(thread.threadData);\n}\n\n/**\n * Run a full compaction pass for a thread. Observer first (may fold the\n * unobserved tail into an observation), then Reflector (may condense the\n * observation log into a reflection). Both are no-ops below their thresholds,\n * so this is cheap to call after every turn.\n */\nexport async function maybeCompactThread(\n options: MaybeCompactThreadOptions,\n): Promise<MaybeCompactThreadResult> {\n const messages =\n options.messages ?? (await loadThreadMessages(options.threadId));\n\n const observer = await runObserver({\n ownerEmail: options.ownerEmail,\n orgId: options.orgId ?? null,\n threadId: options.threadId,\n messages,\n config: options.config,\n runInternal: options.runInternal,\n });\n\n const reflector = await runReflector({\n ownerEmail: options.ownerEmail,\n orgId: options.orgId ?? null,\n threadId: options.threadId,\n config: options.config,\n runInternal: options.runInternal,\n });\n\n return { observer, reflector };\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tunable thresholds for Observational Memory compaction.
|
|
3
|
+
*
|
|
4
|
+
* Defaults are conservative and overridable per call. Deploy-level
|
|
5
|
+
* AGENT_NATIVE_* env overrides let an operator dial compaction without a
|
|
6
|
+
* redeploy; an invalid/missing value always falls back to the named default.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Once a thread's UNOBSERVED messages exceed this many tokens, the Observer
|
|
10
|
+
* compacts them into a single dense, dated observation entry.
|
|
11
|
+
*/
|
|
12
|
+
export declare const DEFAULT_OBSERVATION_TOKEN_THRESHOLD = 30000;
|
|
13
|
+
/**
|
|
14
|
+
* Once the persisted observation log itself exceeds this many tokens, the
|
|
15
|
+
* Reflector condenses the observations into a higher-level reflection.
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEFAULT_REFLECTION_TOKEN_THRESHOLD = 40000;
|
|
18
|
+
/**
|
|
19
|
+
* How many of the most-recent thread messages to always keep verbatim in the
|
|
20
|
+
* read-side context (the "recent raw messages" tier). These are never folded
|
|
21
|
+
* into an observation, so the agent always sees the latest turns in full.
|
|
22
|
+
*/
|
|
23
|
+
export declare const DEFAULT_RECENT_RAW_MESSAGE_COUNT = 12;
|
|
24
|
+
/** Cap on the Observer's output so one observation can't itself blow the budget. */
|
|
25
|
+
export declare const DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS = 4000;
|
|
26
|
+
/** Cap on the Reflector's output. */
|
|
27
|
+
export declare const DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS = 2000;
|
|
28
|
+
/** Resolved thresholds, applying env overrides over the named defaults. */
|
|
29
|
+
export interface ObservationalMemoryConfig {
|
|
30
|
+
observationTokenThreshold: number;
|
|
31
|
+
reflectionTokenThreshold: number;
|
|
32
|
+
recentRawMessageCount: number;
|
|
33
|
+
observationMaxOutputTokens: number;
|
|
34
|
+
reflectionMaxOutputTokens: number;
|
|
35
|
+
}
|
|
36
|
+
export declare function resolveObservationalMemoryConfig(overrides?: Partial<ObservationalMemoryConfig>): ObservationalMemoryConfig;
|
|
37
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/agent/observational-memory/config.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;GAGG;AACH,eAAO,MAAM,mCAAmC,QAAS,CAAC;AAE1D;;;GAGG;AACH,eAAO,MAAM,kCAAkC,QAAS,CAAC;AAEzD;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,KAAK,CAAC;AAEnD,oFAAoF;AACpF,eAAO,MAAM,qCAAqC,OAAQ,CAAC;AAE3D,qCAAqC;AACrC,eAAO,MAAM,oCAAoC,OAAQ,CAAC;AAQ1D,2EAA2E;AAC3E,MAAM,WAAW,yBAAyB;IACxC,yBAAyB,EAAE,MAAM,CAAC;IAClC,wBAAwB,EAAE,MAAM,CAAC;IACjC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,0BAA0B,EAAE,MAAM,CAAC;IACnC,yBAAyB,EAAE,MAAM,CAAC;CACnC;AAED,wBAAgB,gCAAgC,CAC9C,SAAS,GAAE,OAAO,CAAC,yBAAyB,CAAM,GACjD,yBAAyB,CA2B3B"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tunable thresholds for Observational Memory compaction.
|
|
3
|
+
*
|
|
4
|
+
* Defaults are conservative and overridable per call. Deploy-level
|
|
5
|
+
* AGENT_NATIVE_* env overrides let an operator dial compaction without a
|
|
6
|
+
* redeploy; an invalid/missing value always falls back to the named default.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Once a thread's UNOBSERVED messages exceed this many tokens, the Observer
|
|
10
|
+
* compacts them into a single dense, dated observation entry.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_OBSERVATION_TOKEN_THRESHOLD = 30_000;
|
|
13
|
+
/**
|
|
14
|
+
* Once the persisted observation log itself exceeds this many tokens, the
|
|
15
|
+
* Reflector condenses the observations into a higher-level reflection.
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_REFLECTION_TOKEN_THRESHOLD = 40_000;
|
|
18
|
+
/**
|
|
19
|
+
* How many of the most-recent thread messages to always keep verbatim in the
|
|
20
|
+
* read-side context (the "recent raw messages" tier). These are never folded
|
|
21
|
+
* into an observation, so the agent always sees the latest turns in full.
|
|
22
|
+
*/
|
|
23
|
+
export const DEFAULT_RECENT_RAW_MESSAGE_COUNT = 12;
|
|
24
|
+
/** Cap on the Observer's output so one observation can't itself blow the budget. */
|
|
25
|
+
export const DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS = 4_000;
|
|
26
|
+
/** Cap on the Reflector's output. */
|
|
27
|
+
export const DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS = 2_000;
|
|
28
|
+
function readEnvInt(raw, fallback) {
|
|
29
|
+
if (!raw)
|
|
30
|
+
return fallback;
|
|
31
|
+
const parsed = Number.parseInt(raw, 10);
|
|
32
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
33
|
+
}
|
|
34
|
+
export function resolveObservationalMemoryConfig(overrides = {}) {
|
|
35
|
+
return {
|
|
36
|
+
observationTokenThreshold: overrides.observationTokenThreshold ??
|
|
37
|
+
readEnvInt(process.env.AGENT_NATIVE_OM_OBSERVATION_TOKEN_THRESHOLD, DEFAULT_OBSERVATION_TOKEN_THRESHOLD),
|
|
38
|
+
reflectionTokenThreshold: overrides.reflectionTokenThreshold ??
|
|
39
|
+
readEnvInt(process.env.AGENT_NATIVE_OM_REFLECTION_TOKEN_THRESHOLD, DEFAULT_REFLECTION_TOKEN_THRESHOLD),
|
|
40
|
+
recentRawMessageCount: overrides.recentRawMessageCount ??
|
|
41
|
+
readEnvInt(process.env.AGENT_NATIVE_OM_RECENT_RAW_MESSAGE_COUNT, DEFAULT_RECENT_RAW_MESSAGE_COUNT),
|
|
42
|
+
observationMaxOutputTokens: overrides.observationMaxOutputTokens ??
|
|
43
|
+
DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS,
|
|
44
|
+
reflectionMaxOutputTokens: overrides.reflectionMaxOutputTokens ??
|
|
45
|
+
DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/agent/observational-memory/config.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAE1D;;;GAGG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAEzD;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,EAAE,CAAC;AAEnD,oFAAoF;AACpF,MAAM,CAAC,MAAM,qCAAqC,GAAG,KAAK,CAAC;AAE3D,qCAAqC;AACrC,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D,SAAS,UAAU,CAAC,GAAuB,EAAE,QAAgB;IAC3D,IAAI,CAAC,GAAG;QAAE,OAAO,QAAQ,CAAC;IAC1B,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACxC,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC;AACnE,CAAC;AAWD,MAAM,UAAU,gCAAgC,CAC9C,YAAgD,EAAE;IAElD,OAAO;QACL,yBAAyB,EACvB,SAAS,CAAC,yBAAyB;YACnC,UAAU,CACR,OAAO,CAAC,GAAG,CAAC,2CAA2C,EACvD,mCAAmC,CACpC;QACH,wBAAwB,EACtB,SAAS,CAAC,wBAAwB;YAClC,UAAU,CACR,OAAO,CAAC,GAAG,CAAC,0CAA0C,EACtD,kCAAkC,CACnC;QACH,qBAAqB,EACnB,SAAS,CAAC,qBAAqB;YAC/B,UAAU,CACR,OAAO,CAAC,GAAG,CAAC,wCAAwC,EACpD,gCAAgC,CACjC;QACH,0BAA0B,EACxB,SAAS,CAAC,0BAA0B;YACpC,qCAAqC;QACvC,yBAAyB,EACvB,SAAS,CAAC,yBAAyB;YACnC,oCAAoC;KACvC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Tunable thresholds for Observational Memory compaction.\n *\n * Defaults are conservative and overridable per call. Deploy-level\n * AGENT_NATIVE_* env overrides let an operator dial compaction without a\n * redeploy; an invalid/missing value always falls back to the named default.\n */\n\n/**\n * Once a thread's UNOBSERVED messages exceed this many tokens, the Observer\n * compacts them into a single dense, dated observation entry.\n */\nexport const DEFAULT_OBSERVATION_TOKEN_THRESHOLD = 30_000;\n\n/**\n * Once the persisted observation log itself exceeds this many tokens, the\n * Reflector condenses the observations into a higher-level reflection.\n */\nexport const DEFAULT_REFLECTION_TOKEN_THRESHOLD = 40_000;\n\n/**\n * How many of the most-recent thread messages to always keep verbatim in the\n * read-side context (the \"recent raw messages\" tier). These are never folded\n * into an observation, so the agent always sees the latest turns in full.\n */\nexport const DEFAULT_RECENT_RAW_MESSAGE_COUNT = 12;\n\n/** Cap on the Observer's output so one observation can't itself blow the budget. */\nexport const DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS = 4_000;\n\n/** Cap on the Reflector's output. */\nexport const DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS = 2_000;\n\nfunction readEnvInt(raw: string | undefined, fallback: number): number {\n if (!raw) return fallback;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\n/** Resolved thresholds, applying env overrides over the named defaults. */\nexport interface ObservationalMemoryConfig {\n observationTokenThreshold: number;\n reflectionTokenThreshold: number;\n recentRawMessageCount: number;\n observationMaxOutputTokens: number;\n reflectionMaxOutputTokens: number;\n}\n\nexport function resolveObservationalMemoryConfig(\n overrides: Partial<ObservationalMemoryConfig> = {},\n): ObservationalMemoryConfig {\n return {\n observationTokenThreshold:\n overrides.observationTokenThreshold ??\n readEnvInt(\n process.env.AGENT_NATIVE_OM_OBSERVATION_TOKEN_THRESHOLD,\n DEFAULT_OBSERVATION_TOKEN_THRESHOLD,\n ),\n reflectionTokenThreshold:\n overrides.reflectionTokenThreshold ??\n readEnvInt(\n process.env.AGENT_NATIVE_OM_REFLECTION_TOKEN_THRESHOLD,\n DEFAULT_REFLECTION_TOKEN_THRESHOLD,\n ),\n recentRawMessageCount:\n overrides.recentRawMessageCount ??\n readEnvInt(\n process.env.AGENT_NATIVE_OM_RECENT_RAW_MESSAGE_COUNT,\n DEFAULT_RECENT_RAW_MESSAGE_COUNT,\n ),\n observationMaxOutputTokens:\n overrides.observationMaxOutputTokens ??\n DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS,\n reflectionMaxOutputTokens:\n overrides.reflectionMaxOutputTokens ??\n DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS,\n };\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observational Memory (OM) — background compaction of a long agent thread into
|
|
3
|
+
* a dated, three-tier context (recent raw messages → dense observations →
|
|
4
|
+
* higher-level reflections) so long-running threads cost far fewer tokens and
|
|
5
|
+
* stay prompt-cache stable.
|
|
6
|
+
*
|
|
7
|
+
* Public surface:
|
|
8
|
+
* - `buildObservationalContext` — read API returning the three tiers ready for
|
|
9
|
+
* prompt injection. NOT yet wired into production-agent.ts (see the
|
|
10
|
+
* TODO(charlie-merge) seam in `read.ts`).
|
|
11
|
+
* - `maybeCompactThread` — decoupled compactor the agent loop can call after a
|
|
12
|
+
* turn; runs the Observer then the Reflector. Wired later, not now.
|
|
13
|
+
* - `runObserver` / `runReflector` — the individual compaction passes.
|
|
14
|
+
* - store helpers + the migration plugin factory.
|
|
15
|
+
*/
|
|
16
|
+
export { resolveObservationalMemoryConfig, DEFAULT_OBSERVATION_TOKEN_THRESHOLD, DEFAULT_REFLECTION_TOKEN_THRESHOLD, DEFAULT_RECENT_RAW_MESSAGE_COUNT, DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS, DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS, type ObservationalMemoryConfig, } from "./config.js";
|
|
17
|
+
export { insertObservationalMemory, listObservationalMemory, getObservedThroughIndex, getObservationLogTokens, __resetObservationalMemoryTableCache, type InsertObservationalMemoryInput, type ListObservationalMemoryOptions, } from "./store.js";
|
|
18
|
+
export { runInternalAgentCall, type InternalAgentRunOptions, type InternalAgentRunFn, } from "./internal-run.js";
|
|
19
|
+
export { runObserver, type RunObserverOptions, type RunObserverResult, } from "./observer.js";
|
|
20
|
+
export { runReflector, type RunReflectorOptions, type RunReflectorResult, } from "./reflector.js";
|
|
21
|
+
export { maybeCompactThread, type MaybeCompactThreadOptions, type MaybeCompactThreadResult, } from "./compactor.js";
|
|
22
|
+
export { buildObservationalContext, hasObservationalMemory, serializeObservationalMemoryBlock, type BuildObservationalContextOptions, } from "./read.js";
|
|
23
|
+
export { createObservationalMemoryPlugin, defaultObservationalMemoryPlugin, } from "./plugin.js";
|
|
24
|
+
export { OBSERVATIONAL_MEMORY_MIGRATIONS } from "./migrations.js";
|
|
25
|
+
export type { ObservationalMemoryTier, ObservationalMemoryEntry, ObservationalMemoryOwner, ObservationalContext, } from "./types.js";
|
|
26
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agent/observational-memory/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACnC,kCAAkC,EAClC,gCAAgC,EAChC,qCAAqC,EACrC,oCAAoC,EACpC,KAAK,yBAAyB,GAC/B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,oCAAoC,EACpC,KAAK,8BAA8B,EACnC,KAAK,8BAA8B,GACpC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,oBAAoB,EACpB,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,WAAW,EACX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,YAAY,EACZ,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,GACxB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,GAC9B,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,yBAAyB,EACzB,sBAAsB,EACtB,iCAAiC,EACjC,KAAK,gCAAgC,GACtC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC;AAElE,YAAY,EACV,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observational Memory (OM) — background compaction of a long agent thread into
|
|
3
|
+
* a dated, three-tier context (recent raw messages → dense observations →
|
|
4
|
+
* higher-level reflections) so long-running threads cost far fewer tokens and
|
|
5
|
+
* stay prompt-cache stable.
|
|
6
|
+
*
|
|
7
|
+
* Public surface:
|
|
8
|
+
* - `buildObservationalContext` — read API returning the three tiers ready for
|
|
9
|
+
* prompt injection. NOT yet wired into production-agent.ts (see the
|
|
10
|
+
* TODO(charlie-merge) seam in `read.ts`).
|
|
11
|
+
* - `maybeCompactThread` — decoupled compactor the agent loop can call after a
|
|
12
|
+
* turn; runs the Observer then the Reflector. Wired later, not now.
|
|
13
|
+
* - `runObserver` / `runReflector` — the individual compaction passes.
|
|
14
|
+
* - store helpers + the migration plugin factory.
|
|
15
|
+
*/
|
|
16
|
+
export { resolveObservationalMemoryConfig, DEFAULT_OBSERVATION_TOKEN_THRESHOLD, DEFAULT_REFLECTION_TOKEN_THRESHOLD, DEFAULT_RECENT_RAW_MESSAGE_COUNT, DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS, DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS, } from "./config.js";
|
|
17
|
+
export { insertObservationalMemory, listObservationalMemory, getObservedThroughIndex, getObservationLogTokens, __resetObservationalMemoryTableCache, } from "./store.js";
|
|
18
|
+
export { runInternalAgentCall, } from "./internal-run.js";
|
|
19
|
+
export { runObserver, } from "./observer.js";
|
|
20
|
+
export { runReflector, } from "./reflector.js";
|
|
21
|
+
export { maybeCompactThread, } from "./compactor.js";
|
|
22
|
+
export { buildObservationalContext, hasObservationalMemory, serializeObservationalMemoryBlock, } from "./read.js";
|
|
23
|
+
export { createObservationalMemoryPlugin, defaultObservationalMemoryPlugin, } from "./plugin.js";
|
|
24
|
+
export { OBSERVATIONAL_MEMORY_MIGRATIONS } from "./migrations.js";
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agent/observational-memory/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACnC,kCAAkC,EAClC,gCAAgC,EAChC,qCAAqC,EACrC,oCAAoC,GAErC,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,oCAAoC,GAGrC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,oBAAoB,GAGrB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,WAAW,GAGZ,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,YAAY,GAGb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,kBAAkB,GAGnB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,yBAAyB,EACzB,sBAAsB,EACtB,iCAAiC,GAElC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["/**\n * Observational Memory (OM) — background compaction of a long agent thread into\n * a dated, three-tier context (recent raw messages → dense observations →\n * higher-level reflections) so long-running threads cost far fewer tokens and\n * stay prompt-cache stable.\n *\n * Public surface:\n * - `buildObservationalContext` — read API returning the three tiers ready for\n * prompt injection. NOT yet wired into production-agent.ts (see the\n * TODO(charlie-merge) seam in `read.ts`).\n * - `maybeCompactThread` — decoupled compactor the agent loop can call after a\n * turn; runs the Observer then the Reflector. Wired later, not now.\n * - `runObserver` / `runReflector` — the individual compaction passes.\n * - store helpers + the migration plugin factory.\n */\n\nexport {\n resolveObservationalMemoryConfig,\n DEFAULT_OBSERVATION_TOKEN_THRESHOLD,\n DEFAULT_REFLECTION_TOKEN_THRESHOLD,\n DEFAULT_RECENT_RAW_MESSAGE_COUNT,\n DEFAULT_OBSERVATION_MAX_OUTPUT_TOKENS,\n DEFAULT_REFLECTION_MAX_OUTPUT_TOKENS,\n type ObservationalMemoryConfig,\n} from \"./config.js\";\n\nexport {\n insertObservationalMemory,\n listObservationalMemory,\n getObservedThroughIndex,\n getObservationLogTokens,\n __resetObservationalMemoryTableCache,\n type InsertObservationalMemoryInput,\n type ListObservationalMemoryOptions,\n} from \"./store.js\";\n\nexport {\n runInternalAgentCall,\n type InternalAgentRunOptions,\n type InternalAgentRunFn,\n} from \"./internal-run.js\";\n\nexport {\n runObserver,\n type RunObserverOptions,\n type RunObserverResult,\n} from \"./observer.js\";\nexport {\n runReflector,\n type RunReflectorOptions,\n type RunReflectorResult,\n} from \"./reflector.js\";\n\nexport {\n maybeCompactThread,\n type MaybeCompactThreadOptions,\n type MaybeCompactThreadResult,\n} from \"./compactor.js\";\n\nexport {\n buildObservationalContext,\n hasObservationalMemory,\n serializeObservationalMemoryBlock,\n type BuildObservationalContextOptions,\n} from \"./read.js\";\n\nexport {\n createObservationalMemoryPlugin,\n defaultObservationalMemoryPlugin,\n} from \"./plugin.js\";\n\nexport { OBSERVATIONAL_MEMORY_MIGRATIONS } from \"./migrations.js\";\n\nexport type {\n ObservationalMemoryTier,\n ObservationalMemoryEntry,\n ObservationalMemoryOwner,\n ObservationalContext,\n} from \"./types.js\";\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny headless internal-agent-call seam for Observational Memory.
|
|
3
|
+
*
|
|
4
|
+
* The Observer and Reflector each need a single, tool-less LLM round-trip:
|
|
5
|
+
* "here is some text, compress it". Rather than touch `production-agent.ts`,
|
|
6
|
+
* this reuses the SAME pattern the evals lane built — resolve a provider-
|
|
7
|
+
* agnostic engine + model from the registry (NEVER hardcode a model) and drive
|
|
8
|
+
* one `engine.stream()` to completion, collecting the text. It mirrors the
|
|
9
|
+
* `analyzeContext().judge` helper in `eval/agent-runner.ts`.
|
|
10
|
+
*
|
|
11
|
+
* Everything is injectable so tests can supply a fake engine and assert no real
|
|
12
|
+
* model is ever called.
|
|
13
|
+
*/
|
|
14
|
+
import type { AgentEngine } from "../engine/types.js";
|
|
15
|
+
export interface InternalAgentRunOptions {
|
|
16
|
+
systemPrompt: string;
|
|
17
|
+
prompt: string;
|
|
18
|
+
maxOutputTokens?: number;
|
|
19
|
+
/** Pre-resolved engine; resolved from the registry when omitted. */
|
|
20
|
+
engine?: AgentEngine;
|
|
21
|
+
/** Pre-resolved model; resolved from the engine's stored/default when omitted. */
|
|
22
|
+
model?: string;
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Run one tool-less internal agent call and return the collected text.
|
|
28
|
+
*
|
|
29
|
+
* Resolution goes through `resolveEngine` / `getStoredModelForEngine` /
|
|
30
|
+
* `normalizeModelForEngine` — identical to the eval runner — so the compactor
|
|
31
|
+
* uses whatever provider/model the app is configured for. No model is ever
|
|
32
|
+
* hardcoded here.
|
|
33
|
+
*/
|
|
34
|
+
export declare function runInternalAgentCall(options: InternalAgentRunOptions): Promise<string>;
|
|
35
|
+
/** The shape the Observer/Reflector depend on — injectable for tests. */
|
|
36
|
+
export type InternalAgentRunFn = (options: InternalAgentRunOptions) => Promise<string>;
|
|
37
|
+
//# sourceMappingURL=internal-run.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-run.d.ts","sourceRoot":"","sources":["../../../src/agent/observational-memory/internal-run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAStD,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kFAAkF;IAClF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,MAAM,CAAC,CAsCjB;AAED,yEAAyE;AACzE,MAAM,MAAM,kBAAkB,GAAG,CAC/B,OAAO,EAAE,uBAAuB,KAC7B,OAAO,CAAC,MAAM,CAAC,CAAC"}
|