@ax-llm/ax 23.0.0 → 23.0.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ax-llm/ax",
3
- "version": "23.0.0",
3
+ "version": "23.0.2",
4
4
  "type": "module",
5
5
  "description": "The best library to work with LLMs",
6
6
  "repository": {
@@ -24,9 +24,6 @@
24
24
  "optional": true
25
25
  }
26
26
  },
27
- "tsd": {
28
- "directory": "./"
29
- },
30
27
  "files": [
31
28
  "**/*"
32
29
  ],
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent-context
3
3
  description: This skill helps an LLM pick the right AxAgent context tool for a job - contextMap for recurring corpora, contextPolicy presets for within-run trajectory compaction, agent.optimize for offline GEPA instruction/demo tuning, agent.playbook for an evolving context playbook (offline evolve + online update), and recall/memories + skills for per-turn retrieval. Use when the user asks "which context feature should I use", confuses contextMap with contextPolicy or memory, or wants a decision guide for long-context agents. For contextPolicy/contextMap codegen use ax-agent-rlm; for recall/skills use ax-agent-memory-skills; for agent.optimize or agent.playbook use ax-agent-optimize.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent Context Selection (@ax-llm/ax)
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent-memory-skills
3
3
  description: This skill helps an LLM generate correct AxAgent memory retrieval, context-map, and dynamic skill-loading code using @ax-llm/ax. Use when the user asks about contextMap, AxAgentContextMap, onMemoriesSearch, memoriesCatalog, recall(...), inputs.memories, onLoadedMemories, onUsedMemories, onSkillsSearch, skillsCatalog, AxAgentCatalogSkill, discover({ skills }), onLoadedSkills, onUsedSkills, preloaded skills, preloading memories at forward time, relevanceRanking hints, loaded memory/skill IDs, or carrying memories across forward() calls.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent Memory And Skills Rules (@ax-llm/ax)
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent-observability
3
3
  description: This skill helps an LLM generate correct AxAgent observability code using @ax-llm/ax. Use when the user asks about actorTurnCallback, onContextEvent, agentStatusCallback, onFunctionCall, reportSuccess, reportFailure, getChatLog(), getUsage(), resetUsage(), debug traces, progress updates, or telemetry for AxAgent runs.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent Observability Rules (@ax-llm/ax)
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent-optimize
3
3
  description: This skill helps an LLM generate correct AxAgent tuning and evaluation code using @ax-llm/ax. Use when the user asks about agent.optimize(...), judgeOptions, eval datasets, optimization targets, saved optimizedProgram artifacts, or agent optimization guidance.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent Optimize Codegen Rules (@ax-llm/ax)
@@ -45,6 +45,7 @@ Pick the optimization shape from the user's need:
45
45
  - "Make the whole agent better" -> use the default actor target first; only broaden target selection when the user clearly wants that extra scope.
46
46
  - "Tune child-agent delegation" -> use tasks that exercise when to call the child agent, when to call normal tools, and when to answer directly.
47
47
  - "Compare before and after" -> include a held-out task plus artifact save/load and replay.
48
+ - "Repair the tasks it keeps failing, without eroding what works" -> this is playbook territory, not GEPA: use the agent-bound playbook evolve method (in TypeScript, `agent.playbook().evolve(dataset)`) to mine failures into verified playbook bullets under a held-out gate. Python, Java, C++, Go, and Rust expose the same loop with native method casing; see `ax-playbook`. `optimize(...)` maximizes a metric by tuning instructions and demos; playbook evolution grows durable rules.
48
49
 
49
50
  Choose task design carefully:
50
51
 
@@ -320,6 +321,13 @@ Decision rules:
320
321
 
321
322
  ## Eval Semantics
322
323
 
324
+ - MCP/UCP evaluation defaults to replay or sandbox mode. A live client is rejected unless `mcpEvaluation: 'live'` is explicit.
325
+ - Use `ax-mcp` for recording/replay transport setup and MCP side-effect policy.
326
+ - Use `AxMCPRecordingTransport` to capture a real session once and `AxMCPReplayTransport` for deterministic optimization/evaluation.
327
+ - Replay normalized MCP notifications and task transitions through
328
+ `AxEventRuntime`; do not leave a live subscription active in a default
329
+ optimization run.
330
+ - Action traces include qualified MCP/UCP operations, approvals, task transitions, raw protocol errors, and business outcomes for judges and deterministic metrics.
323
331
  - `agent.optimize(...)` runs each evaluation rollout from a clean continuation state.
324
332
  - Saved runtime state from `getState()` and `setState(...)` is not used during eval rollouts.
325
333
  - During optimize/eval, `askClarification(...)` is treated as a scored evaluation outcome instead of going through the responder.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent-rlm
3
3
  description: This skill helps an LLM generate correct AxAgent RLM/runtime code using @ax-llm/ax. Use when the user asks about RLM code execution, AxJSRuntime, contextFields, contextPolicy, liveRuntimeState, promptLevel, stage prompt controls, executorModelPolicy, maxRuntimeChars, agent.test(...), llmQuery(...), recursionOptions, or long-running agent runtime behavior.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent RLM Runtime Rules (@ax-llm/ax)
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-agent
3
- description: This skill helps an LLM generate correct core AxAgent code using @ax-llm/ax. Use when the user asks about agent(), child agents, namespaced functions, discovery mode, clarification, bubbleErrors, host-side final/clarification protocol, or ordinary agent runtime behavior. For RLM/code-runtime work use ax-agent-rlm; for callbacks and telemetry use ax-agent-observability; for recall/memory/skill loading use ax-agent-memory-skills; for agent.optimize(...) use ax-agent-optimize.
4
- version: "23.0.0"
3
+ description: This skill helps an LLM generate correct core AxAgent code using @ax-llm/ax. Use when the user asks about agent(), child agents, namespaced functions, discovery mode, clarification, bubbleErrors, host-side final/clarification protocol, or ordinary agent runtime behavior. For MCP clients, native runtime modules, subscriptions, tasks, or authentication use ax-mcp alongside this skill. For RLM/code-runtime work use ax-agent-rlm; for callbacks and telemetry use ax-agent-observability; for recall/memory/skill loading use ax-agent-memory-skills; for agent.optimize(...) use ax-agent-optimize.
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AxAgent Codegen Rules (@ax-llm/ax)
@@ -15,6 +15,8 @@ Your job is to choose the smallest correct `AxAgent` shape for the user's needs:
15
15
  - If the user wants callbacks, logs, tracing, or usage data, use the `ax-agent-observability` skill.
16
16
  - If the user wants dynamic memory retrieval or skill-guide loading, use the `ax-agent-memory-skills` skill.
17
17
  - If the user wants tuning or eval with `agent.optimize(...)`, use the `ax-agent-optimize` skill.
18
+ - If the user wants MCP transports, authentication, catalogs, subscriptions,
19
+ tasks, Apps, or event-driven wake/resume, use the `ax-mcp` skill.
18
20
 
19
21
  ## Use These Defaults
20
22
 
@@ -237,24 +239,22 @@ const parent = agent('query:string -> answer:string', {
237
239
  });
238
240
  ```
239
241
 
240
- MCP clients and other `toFunction()` providers can be placed directly inside a group after initialization:
242
+ Attach MCP/UCP clients through the native execution context. Ax initializes them once, exposes `mcp.<namespace>` / `ucp.<namespace>` runtime modules, and propagates them through actor stages, `llmQuery`, RLM, and child agents:
241
243
 
242
- ```typescript
243
- await mcpClient.init();
244
+ Use `ax-mcp` for constructing those clients, transport/authentication policy,
245
+ server-initiated handlers, resource subscriptions, task continuations, and
246
+ recording/replay. Keep this section focused on Agent attachment and discovery.
244
247
 
248
+ ```typescript
245
249
  const parent = agent('query:string -> answer:string', {
246
- functions: [
247
- {
248
- namespace: 'memory',
249
- title: 'Memory MCP',
250
- description: 'Memory server tools',
251
- selectionCriteria: 'Use for persistent memory lookup and updates.',
252
- functions: [mcpClient],
253
- },
254
- ],
250
+ mcp: [memoryClient, searchClient],
251
+ mcpInheritance: 'all',
255
252
  functionDiscovery: true,
256
253
  contextFields: [],
257
254
  });
255
+
256
+ // A child can restrict inheritance to selected namespaces or `none`.
257
+ await parent.forward(llm, { query }, { mcpInheritance: ['memory'] });
258
258
  ```
259
259
 
260
260
  Rules:
@@ -265,8 +265,23 @@ Rules:
265
265
  - `relevanceRanking` (default ON — set `false` to opt out): a deterministic local ranker that injects an advisory `### Likely Relevant` shortlist into the executor turn (dynamic, non-cached field — the cached prompt stays byte-stable). Enabled by default after its A/B gate passed on both small and frontier models and implemented in the generated language ports through AxIR Core. Details in `ax-agent-memory-skills`; outcomes observable via the `relevance_ranking` context event (`ax-agent-observability`).
266
266
  - Add `alwaysInclude: true` to a group when discovery mode is on but the actor should always see that group's full callable definitions inline in the prompt.
267
267
  - Keep `functions: [...]` either flat or grouped. Runtime validation rejects mixed plain function entries and group objects.
268
- - In flat mode, pass `fn(...)` tools, child agents, and `toFunction()` providers directly.
269
- - In grouped mode, put callable entries and `toFunction()` providers inside groups. To expose a child agent inside a group, use `childAgent.getFunction()`.
268
+ - In flat mode, pass `fn(...)` tools and child agents directly.
269
+ - In grouped mode, put callable entries inside groups. To expose a child agent inside a group, use `childAgent.getFunction()`.
270
+ - Do not place MCP clients in `functions`; use `mcp` so tasks, resources, subscriptions, elicitation, sampling, authorization, cancellation, and protocol metadata remain available.
271
+ - To wake an Agent from a resource subscription, use `AxMCPEventSource` and an
272
+ explicit authenticated `wake` route. MCP sessions are not tenant identity;
273
+ supply identity from the application's authenticated token mapping.
274
+ - An endpoint does not imply a resource URI. Inspect `client.inspectCatalog()`
275
+ and choose an explicit `resourceSubscriptions` policy. Omission means none;
276
+ `'all'` selects all discovered concrete resources; selectors can use names,
277
+ descriptions, MIME types, URIs, and annotations. Templates are not expanded.
278
+ - Map the event with a signature-aware `.wakeInput(...)` plan, or reuse an
279
+ `eventInput()` plan. Callback `mapInput` is still signature-validated and
280
+ cannot inject undeclared Agent fields. Use multiple matching routes to wake
281
+ multiple Agents with independent state, authorization, retries, and runs.
282
+ - To wake from a UCP lifecycle webhook, use `AxUCPWebhookEventSource` and map
283
+ verified profile/account state to Ax tenant identity after request
284
+ verification. Never derive tenant identity from the order payload.
270
285
 
271
286
  ## Host-Side Completion From Functions
272
287
 
@@ -529,6 +544,8 @@ agent(signature, {
529
544
  functions,
530
545
  functionDiscovery,
531
546
  autoUpgrade,
547
+ playbook,
548
+ citations,
532
549
  ...agentOptions,
533
550
  });
534
551
  ```
@@ -576,6 +593,34 @@ Rules:
576
593
  - Values in required non-string fields (arrays, objects, numbers, media) are never auto-promoted — declare those in `contextFields` explicitly when they can be large.
577
594
  - Each promotion emits a `field_auto_promoted` context event (`onContextEvent`) with the field name, original size, and preview size; use it to observe what was kept out of the prompt.
578
595
 
596
+ ### Learning And Citations
597
+
598
+ These construction-time options are portable across TypeScript and the generated
599
+ Python, Java, C++, Go, and Rust packages (both default off):
600
+
601
+ - `playbook`: attach an ACE playbook at construction. `learn` is on by default — after each run that produced failure signals (error turns, dead-ends, failing tool calls) one bounded update curates durable avoidance rules that ride the next run's actor prompt; zero LLM cost on clean runs. TypeScript seeds a prior session with `playbook: { playbook: snapshot }`; generated packages accept their full `{ playbook, artifact }` snapshot under `seed`. Persist via `onUpdate`, read the live handle with `getPlaybook()` (or the language-shaped equivalent), gate with `learn: { minSignals, dedupe }`, or disable with `learn: false`. To grow the same playbook from a task set with a held-out verify gate, use the agent-bound playbook evolve method — see `ax-playbook`.
602
+ - `citations`: add an optional `evidenceCitations: string[]` responder output listing which evidence entries (top-level keys of the curated evidence, plus memory ids) the answer relied on. Validated in-pipeline — the model cannot cite evidence it never collected (existence, not entailment). Pass `true`, or `{ field?, surface?: 'output' | 'hidden', includeMemoryIds?, onCitations? }`.
603
+
604
+ Stage guidance is portable too. `setInstruction` replaces the stage-owned actor
605
+ instruction and `addActorInstruction` appends an additive rule. Both are real
606
+ optimization components; rebuilding the split programs no longer discards them.
607
+ Generated packages use their normal casing conventions (`set_instruction` in
608
+ Python/C++/Rust and `SetInstruction` in Go).
609
+
610
+ The generated-language observer and evolve spellings are:
611
+
612
+ | Language | Citations observer | Verified agent playbook evolve |
613
+ |---|---|---|
614
+ | Python | `citations.onCitations` | `agent.playbook().evolve(dataset, options)` |
615
+ | Java | `citations.onCitations` (`Consumer`) | `agent.playbook(null).evolve(dataset, options)` |
616
+ | C++ | `set_citations_observer(...)` | `agent.get_playbook()->evolve(dataset, options)` |
617
+ | Go | `citations.onCitations` (`func([]Value)`) | `agent.GetPlaybook().EvolveAgent(ctx, dataset, options)` |
618
+ | Rust | `set_citations_observer(...)` | `playbook.evolve_agent(&mut agent, client, dataset, options)` |
619
+
620
+ C++ and Rust use `set_playbook_observer(...)` for construction-time learning
621
+ updates; Python, Java, and Go accept the `playbook.onUpdate` callback in their
622
+ native configuration map.
623
+
579
624
  ## Public Surface
580
625
 
581
626
  Use these method groups as the compact AxAgent surface map:
@@ -585,6 +630,7 @@ Use these method groups as the compact AxAgent surface map:
585
630
  - State and control: `getState()`, `setState(state?)`, `getContextMap()`, `setContextMap(map?)`, `stop()`, `getSignature()`, `setSignature(signature)`, `getFunction()`, `getId()`, and `setId(id)`. Context-map evolve policy lives on `AxAgentContextMap` (`infiniteEvolve`, `evolveSteps`, `maxChars`), not on the agent config. See [`src/examples/rlm-context-map-live.ts`](https://raw.githubusercontent.com/ax-llm/ax/refs/heads/main/src/examples/rlm-context-map-live.ts) for provider-backed persistence and finite-evolve usage.
586
631
  - Observability: `getChatLog()`, `getUsage()`, `getStagedUsage()`, `resetUsage()`, and `getTraces()`; use `ax-agent-observability` for details.
587
632
  - Demos and tuning: `setDemos(...)`, `namedPrograms()`, `namedProgramInstances()`, `optimize(...)`, `applyOptimization(...)`, `getOptimizableComponents()`, and `applyOptimizedComponents(...)`; use `ax-agent-optimize` for tuning details.
633
+ - Learning: `playbook()` returns an agent-aware playbook handle (`update(...)`, `render()`, state/load methods, and verified dataset evolution); `getPlaybook()` reads the current handle. Generated packages expose the same behavior with language-shaped method names. Use `ax-playbook` for details.
588
634
 
589
635
  Rules:
590
636
 
@@ -615,9 +661,24 @@ Fetch these for full working code:
615
661
  - [Customer Support](https://raw.githubusercontent.com/ax-llm/ax/refs/heads/main/src/examples/customer-support.ts) - classification agent
616
662
  - [Abort Patterns](https://raw.githubusercontent.com/ax-llm/ax/refs/heads/main/src/examples/abort-patterns.ts) - abort handling
617
663
  - [Smart Defaults Agent](https://raw.githubusercontent.com/ax-llm/ax/refs/heads/main/src/examples/typescript/long-agents/smart-defaults-agent.ts) - auto-upgrade context promotion, relevance hints, and runtime tools
664
+ - [Portable Playbook Evolve](https://raw.githubusercontent.com/ax-llm/ax/refs/heads/main/src/examples/python/optimization/agent-playbook-evolve.py) - Python construction-time learning, validated citations, stage guidance, and verified task-set evolution (parallel Java/C++/Go/Rust examples live beside it)
618
665
 
619
666
  RLM examples are listed in `ax-agent-rlm`. Memory/skills examples are listed in `ax-agent-memory-skills`.
620
667
 
668
+ ## Event-Driven Agents
669
+
670
+ `AxEventRuntime` can wake or resume an Agent while preserving its logical
671
+ state. Use `createProgram(instance)` for multi-tenant Agents; one mutable Agent
672
+ object must not serve multiple instance keys concurrently. Clarification and
673
+ remote task completion are represented as owned continuations, not synthetic
674
+ user turns.
675
+
676
+ Declare the Agent signature on
677
+ `eventTarget('id').createProgram(signature, factory)` and map event values with
678
+ `eventPath`. The runtime verifies every created Agent against that signature
679
+ before invoking it. Fan-out uses multiple matching routes so each Agent keeps
680
+ its own authorization, instance serialization, retry policy, and run record.
681
+
621
682
  ## Do Not Generate
622
683
 
623
684
  - Do not use `new AxAgent(...)` for new code unless explicitly required.
package/skills/ax-ai.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-ai
3
3
  description: This skill helps an LLM generate correct AI provider setup and configuration code using @ax-llm/ax. Use when the user asks about ai(), providers, models, presets, embeddings, batch audio with ai.transcribe() or ai.speak(), extended thinking, context caching, or mentions OpenAI/Anthropic/Google/Azure/DeepSeek/Mistral/Cohere/Reka/Grok with @ax-llm/ax.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # AI Provider Codegen Rules (@ax-llm/ax)
@@ -213,9 +213,10 @@ console.log(res.results[0]?.content);
213
213
 
214
214
  ### Anthropic Model-Specific Behavior
215
215
 
216
- - Opus 4.8 and 4.7: adaptive thinking, effort levels including `'xhigh'`,
217
- no manual `budget_tokens`, and no `temperature` / `topP` / `topK`.
218
- - Opus 4.6: adaptive thinking, effort levels
216
+ - Opus 4.8, 4.7, and 4.6 plus Sonnet 5: adaptive thinking, no manual
217
+ `budget_tokens`, and no `temperature` / `topP` / `topK`. When thoughts are
218
+ requested, Ax asks Anthropic for summarized display; when they are hidden,
219
+ Ax explicitly requests `display: 'omitted'`.
219
220
  - Opus 4.5: budget_tokens + effort levels (capped at `'high'`)
220
221
  - Other thinking models: budget tokens only
221
222
 
@@ -342,12 +343,22 @@ const transport = axCreateMCPStdioTransport({
342
343
  const client = new AxMCPClient(transport);
343
344
  ```
344
345
 
346
+ For server notifications, call `client.startListening({ signal, onError })` or
347
+ attach the client through `AxMCPEventSource`. The event adapter is preferred
348
+ for autonomous work because protocol callbacks only enqueue; explicit routes
349
+ decide whether to observe, invalidate, resume, or wake.
350
+
351
+ For signed UCP lifecycle requests, mount
352
+ `AxUCPWebhookEventSource.ingest(request)` in application-owned HTTP hosting.
353
+ Signature, profile, digest, freshness, and replay verification completes before
354
+ the event runtime sees the request.
355
+
345
356
  ## Critical Rules
346
357
 
347
358
  - Use `ai()` factory for all providers.
348
359
  - Provider names: `'openai'`, `'openai-responses'`, `'anthropic'`, `'google-gemini'`, `'azure-openai'`, `'mistral'`, `'cohere'`, `'deepseek'`, `'reka'`, `'grok'`
349
- - Thinking constraints on Anthropic: Opus 4.8/4.7 omit `temperature`, `topP`,
350
- and `topK`; older thinking models ignore `temperature` and `topK`, with
360
+ - Thinking constraints on Anthropic: every adaptive-thinking model omits
361
+ `temperature`, `topP`, and `topK`; older thinking models ignore `temperature` and `topK`, with
351
362
  `topP` only sent if >= 0.95.
352
363
  - Bedrock uses `new AxAIBedrock()`, not `ai()`.
353
364
  - Vercel AI SDK uses `AxAIProvider` wrapper.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ax-audio
3
3
  description: This skill helps an LLM generate correct audio code with @ax-llm/ax. Use when the user asks about ai.transcribe(), ai.speak(), signature audio inputs or outputs, agent audio behavior, .chat() conversational audio, OpenAI audio or realtime models, Gemini Live native audio, Grok Voice Agent models, voices, formats, transcripts, or how audio fits with structured outputs.
4
- version: "23.0.0"
4
+ version: "23.0.2"
5
5
  ---
6
6
 
7
7
  # Audio I/O Codegen Rules (@ax-llm/ax)
@@ -0,0 +1,145 @@
1
+ ---
2
+ name: ax-event-runtime
3
+ description: Use AxEventRuntime to ingest events, explicitly wake or resume AxGen, AxAgent, and AxFlow, persist state and results, and route outputs safely.
4
+ ---
5
+
6
+ # Ax Event Runtime
7
+
8
+ Use this skill when an Ax program should react to notifications, webhooks,
9
+ timers, queues, task completion, or application events.
10
+
11
+ ## Mental Model
12
+
13
+ ```text
14
+ source -> inbox -> route -> target -> stored run -> sink
15
+ ```
16
+
17
+ Sources never call an Ax program directly. A route must explicitly choose
18
+ `observe`, `invalidate`, `wake`, or `resume`. Only the last two invoke a model.
19
+
20
+ ## Minimal Pattern
21
+
22
+ ```ts
23
+ const source = new AxPushEventSource('application');
24
+ const target = eventTarget('triage')
25
+ .program(triageAgent)
26
+ .ai(llm)
27
+ .input((input) => input.field('incident', eventPath.data()))
28
+ .sink({ id: 'result', write: saveResult })
29
+ .build();
30
+
31
+ const events = eventRuntime({
32
+ sources: [source],
33
+ routes: [
34
+ eventRoute('incident-created')
35
+ .types('incident.created')
36
+ .wake(target)
37
+ .build(),
38
+ ],
39
+ });
40
+
41
+ await events.start();
42
+ await source.publish({ event, identity, trust: 'authenticated' });
43
+ ```
44
+
45
+ ## Rules
46
+
47
+ - Supply identity from authenticated adapter state, never from event data.
48
+ - Treat events without verified identity as anonymous and untrusted.
49
+ - Map event data into signature inputs; do not synthesize a user message.
50
+ - Use `eventPath.data('field')` and other segment-safe selectors. Do not use
51
+ dotted JSONPath strings or repurpose `s()` as a mapping language.
52
+ - Use `.project(path)` only for same-name signature projection. Explicit
53
+ `.field()` mappings override projection; missing or invalid signature inputs
54
+ dead-letter before model invocation.
55
+ - Use `eventInput().project(...).field(...)` when a declarative mapping should
56
+ be callback-free and reusable, then pass that plan to `.input()`,
57
+ `.wakeInput()`, or `.resumeInput()`.
58
+ - Callback `mapInput` is an escape hatch, not a validation bypass: its result is
59
+ normalized to the program signature and mapper failures dead-letter before
60
+ invocation.
61
+ - Use `.wakeInput()` and `.resumeInput()` when the two actions need different
62
+ contracts. Neither action silently uses the other action's mapping.
63
+ - Use `observe` for progress/logs and `invalidate` for catalog changes.
64
+ - Use `resume` only with an owned continuation correlation key.
65
+ - Use `createProgram(instance)` for stateful multi-tenant Agents.
66
+ - Declare `retrySafety: 'idempotent'` only when stable delivery keys protect
67
+ every possible side effect.
68
+ - Persist outputs before final sink delivery; redrive sink failures separately.
69
+ - Use `debounceMs` and `coalesce: 'latest'` only when replacing intermediate
70
+ events is part of the route's declared policy.
71
+ - Observe source failures with `onSourceError`.
72
+ - The in-memory store is volatile and single-process.
73
+ - For cooperating Node processes on one local disk, use
74
+ `AxSQLiteEventStore` from `@ax-llm/ax-tools/event/sqlite` with explicit
75
+ retention and `coordination: 'multi-worker'`. Never recommend SQLite on a
76
+ network filesystem.
77
+ - Close the runtime and caller-owned protocol clients explicitly.
78
+ - Fan out to several Agents with several matching routes, not a multi-target
79
+ route. This preserves independent authorization, ordering, retries, and runs.
80
+
81
+ ## Continuation Pattern
82
+
83
+ ```ts
84
+ eventContext.registerContinuation({
85
+ correlation: [{ kind: 'task', value: taskId }],
86
+ expiresAt,
87
+ });
88
+ ```
89
+
90
+ Route progress to `observe`. Route `input_required`, completed, failed, or
91
+ cancelled task events to `resume` when the owning program must run again.
92
+
93
+ ## MCP Adapter
94
+
95
+ Use `ax-mcp` for client construction, transports, authentication, catalogs,
96
+ subscriptions, tasks, and MCP-specific security policy. This skill owns the
97
+ generic inbox, routing, continuation, store, and sink behavior.
98
+
99
+ Use `client.inspectCatalog()` to discover server-owned tools, prompts, concrete
100
+ resources, and URI templates from only the endpoint. Then use
101
+ `AxMCPEventSource({ client, resourceSubscriptions, identity, trust })` with an
102
+ explicit none/all/URI/selector policy. Omitted policy subscribes to no
103
+ resources. Templates are never expanded automatically. Managed sources diff
104
+ catalog changes, restore current logical ownership on reconnect, and release
105
+ only their own subscriptions on close. Identity must come from the
106
+ application's authenticated client or token mapping; a bare MCP session is
107
+ anonymous. Add `...axMCPEventRoutes({ client })` for catalog invalidation,
108
+ progress/log observation, and task resume. Resource notifications never get an
109
+ implicit wake route. See `docs/MCP_SUBSCRIPTIONS.md`.
110
+
111
+ ## UCP Adapter
112
+
113
+ Use `AxUCPWebhookEventSource({ client, identity })` inside an application-owned
114
+ HTTP handler, then call `source.ingest(request)`. Verification of the signer
115
+ profile, RFC 9421 signature, digest, freshness window, key rotation, and replay
116
+ key completes before enqueue. Resolve tenant/account identity from application
117
+ state after verification; do not copy identity from the business payload.
118
+
119
+ Generated Python, Java, C++, Go, and Rust packages expose the same Core-owned
120
+ single-worker event state machine plus functioning inline lifecycle dispatch,
121
+ continuations, state restoration, cancellation, persisted outputs, isolated
122
+ sink redrive, signature-aware path/input/target/route builders, and host-owned
123
+ source, sink, clock, and store boundaries. Generated targets use the host
124
+ signature plus a typed invocation callback when no common object-safe program
125
+ interface exists. Do not claim persistent multi-worker support from
126
+ `axevent.single-worker` alone.
127
+
128
+ Generated runtimes do not create worker threads. `publish()` drains work due at
129
+ `clock.now()`. Hosts use `nextDueAt()` to schedule `runDue()` for debounce,
130
+ retry, and continuation expiry; `redrive()` is due immediately. Manual clocks
131
+ make these transitions deterministic. Generated in-memory stores enforce
132
+ 10,000 pending deliveries, 64 MiB queued data, 1 MiB per envelope, and a
133
+ five-second publication wait.
134
+
135
+ ## Testing
136
+
137
+ Use `AxManualEventClock`, `AxInMemoryEventStore`, deterministic event IDs, and
138
+ an output-capturing sink. Assert that unmatched or observe-only events never
139
+ invoke the program, tenant scopes do not collide, outputs exist before sinks,
140
+ and uncertain side effects become `outcome_unknown`.
141
+
142
+ Persistent store implementations must pass
143
+ `runAxEventStoreConformance(createStore, { clock })`. A store must not advertise
144
+ multi-worker capability without the conformance marker checked by runtime
145
+ startup.