@canonmsg/agent-sdk 11.2.1 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +171 -536
  2. package/dist/chunks/chunk-6VK4UZHJ.js +2806 -0
  3. package/dist/chunks/chunk-FPQFTTND.js +4899 -0
  4. package/dist/chunks/chunk-OLJ7H4E2.js +14705 -0
  5. package/dist/chunks/mls-crypto-NZDNSPAO.js +10 -0
  6. package/dist/cli.js +198 -0
  7. package/dist/drivers/claude.d.ts +36 -0
  8. package/dist/drivers/code.d.ts +18 -0
  9. package/dist/drivers/codex.d.ts +37 -0
  10. package/dist/index.d.ts +12 -25
  11. package/dist/index.js +69 -13
  12. package/dist/internal/backend-contracts/agentBehaviorPolicy.d.ts +122 -0
  13. package/dist/internal/backend-contracts/agentDirectory.d.ts +32 -0
  14. package/dist/internal/backend-contracts/agentOrigin.d.ts +23 -0
  15. package/dist/internal/backend-contracts/agentSearch.d.ts +17 -0
  16. package/dist/internal/backend-contracts/api-origins.generated.d.ts +4 -0
  17. package/dist/internal/backend-contracts/apiErrors.d.ts +1 -0
  18. package/dist/internal/backend-contracts/artifactActions.d.ts +159 -0
  19. package/dist/internal/backend-contracts/artifacts.d.ts +386 -0
  20. package/dist/internal/backend-contracts/communication.d.ts +131 -0
  21. package/dist/internal/backend-contracts/conversationMembership.d.ts +28 -0
  22. package/dist/internal/backend-contracts/deliveryObservation.d.ts +23 -0
  23. package/dist/internal/backend-contracts/diffRedaction.d.ts +6 -0
  24. package/dist/internal/backend-contracts/endpoint-unread.d.ts +4 -0
  25. package/dist/internal/backend-contracts/endpoint.d.ts +103 -0
  26. package/dist/internal/backend-contracts/endpointContentPolicy.d.ts +37 -0
  27. package/dist/internal/backend-contracts/environment.d.ts +20 -0
  28. package/dist/internal/backend-contracts/externalInbound.d.ts +24 -0
  29. package/dist/internal/backend-contracts/firestoreValues.d.ts +9 -0
  30. package/dist/internal/backend-contracts/index.d.ts +48 -0
  31. package/dist/internal/backend-contracts/media-url.d.ts +6 -0
  32. package/dist/internal/backend-contracts/media.d.ts +51 -0
  33. package/dist/internal/backend-contracts/mediaDelivery.d.ts +46 -0
  34. package/dist/internal/backend-contracts/mediaTransferProtocol.d.ts +17 -0
  35. package/dist/internal/backend-contracts/membershipChange.d.ts +21 -0
  36. package/dist/internal/backend-contracts/message.d.ts +86 -0
  37. package/dist/internal/backend-contracts/messageText.d.ts +6 -0
  38. package/dist/internal/backend-contracts/mlsDevApplication.d.ts +73 -0
  39. package/dist/internal/backend-contracts/mlsDevCredential.d.ts +75 -0
  40. package/dist/internal/backend-contracts/mlsDevCredentialReconciliation.d.ts +45 -0
  41. package/dist/internal/backend-contracts/mlsDevDeviceCustody.d.ts +51 -0
  42. package/dist/internal/backend-contracts/mlsDevEnrollment.d.ts +74 -0
  43. package/dist/internal/backend-contracts/mlsDevGroup.d.ts +197 -0
  44. package/dist/internal/backend-contracts/mlsDevGroupFeed.d.ts +47 -0
  45. package/dist/internal/backend-contracts/mlsDevKeyPackage.d.ts +42 -0
  46. package/dist/internal/backend-contracts/mlsDevKeyPackages.d.ts +55 -0
  47. package/dist/internal/backend-contracts/moderation.d.ts +7 -0
  48. package/dist/internal/backend-contracts/plaintextProcessors.d.ts +63 -0
  49. package/dist/internal/backend-contracts/preparedContent.d.ts +54 -0
  50. package/dist/internal/backend-contracts/replyAuthority.d.ts +14 -0
  51. package/dist/internal/backend-contracts/runtimeCardFields.d.ts +66 -0
  52. package/dist/internal/backend-contracts/runtimeCardStorage.d.ts +3 -0
  53. package/dist/internal/backend-contracts/runtimeDescriptor.d.ts +88 -0
  54. package/dist/internal/backend-contracts/selfContext.d.ts +9 -0
  55. package/dist/internal/backend-contracts/turnProtocol.d.ts +43 -0
  56. package/dist/internal/backend-contracts/verbContract.d.ts +848 -0
  57. package/dist/internal/backend-contracts/verbSchemas.d.ts +1707 -0
  58. package/dist/internal/backend-contracts/verbWire.d.ts +493 -0
  59. package/dist/internal/backend-contracts/webAuth.d.ts +8 -0
  60. package/dist/internal/backend-contracts/workSessions.d.ts +205 -0
  61. package/dist/internal/core/agent-profiles.d.ts +69 -0
  62. package/dist/internal/core/agent-resolver.d.ts +49 -0
  63. package/dist/internal/core/agent-session.d.ts +12 -0
  64. package/dist/internal/core/approval-format.d.ts +26 -0
  65. package/dist/internal/core/approval-manager.d.ts +43 -0
  66. package/dist/internal/core/approval-types.d.ts +74 -0
  67. package/dist/internal/core/artifacts.d.ts +262 -0
  68. package/dist/internal/core/attached-native-session.d.ts +174 -0
  69. package/dist/internal/core/attached-session-file-store.d.ts +3 -0
  70. package/dist/internal/core/base-url.d.ts +1 -0
  71. package/dist/internal/core/cli-metadata.d.ts +13 -0
  72. package/dist/internal/core/client.d.ts +486 -0
  73. package/dist/internal/core/completed-output-journal.d.ts +39 -0
  74. package/dist/internal/core/constants.d.ts +4 -0
  75. package/dist/internal/core/control-poller.d.ts +221 -0
  76. package/dist/internal/core/endpoint-client.d.ts +43 -0
  77. package/dist/internal/core/exclusive-json-file-store.d.ts +7 -0
  78. package/dist/internal/core/execution-environment-mode.d.ts +8 -0
  79. package/dist/internal/core/execution-environment.d.ts +55 -0
  80. package/dist/internal/core/gifs.d.ts +35 -0
  81. package/dist/internal/core/group-context.d.ts +25 -0
  82. package/dist/internal/core/host-runtime.d.ts +257 -0
  83. package/dist/internal/core/inbound-frame.d.ts +64 -0
  84. package/dist/internal/core/index.d.ts +107 -0
  85. package/dist/internal/core/local-runtime-catalog.d.ts +131 -0
  86. package/dist/internal/core/message-format.d.ts +13 -0
  87. package/dist/internal/core/native-session-interaction.d.ts +44 -0
  88. package/dist/internal/core/node-media.d.ts +6 -0
  89. package/dist/internal/core/policy.d.ts +2 -0
  90. package/dist/internal/core/provenance.d.ts +31 -0
  91. package/dist/internal/core/registration-cli.d.ts +40 -0
  92. package/dist/internal/core/registration-profile.d.ts +10 -0
  93. package/dist/internal/core/registration-session.d.ts +55 -0
  94. package/dist/internal/core/registration.d.ts +21 -0
  95. package/dist/internal/core/retry.d.ts +122 -0
  96. package/dist/internal/core/rtdb-rest.d.ts +145 -0
  97. package/dist/internal/core/runtime-cards.d.ts +331 -0
  98. package/dist/internal/core/runtime-descriptor.d.ts +75 -0
  99. package/dist/internal/core/runtime-endpoints.d.ts +26 -0
  100. package/dist/internal/core/runtime-heartbeat.d.ts +29 -0
  101. package/dist/internal/core/runtime-presentation.d.ts +35 -0
  102. package/dist/internal/core/runtime-request-manager.d.ts +284 -0
  103. package/dist/internal/core/runtime-state-publisher.d.ts +42 -0
  104. package/dist/internal/core/self-context.d.ts +61 -0
  105. package/dist/internal/core/silent-turn.d.ts +86 -0
  106. package/dist/internal/core/stream.d.ts +77 -0
  107. package/dist/internal/core/turn-output-controller.d.ts +69 -0
  108. package/dist/internal/core/turn-protocol.d.ts +33 -0
  109. package/dist/internal/core/turn-verbosity.d.ts +97 -0
  110. package/dist/internal/core/types.d.ts +1075 -0
  111. package/dist/internal/core/typing-status-publisher.d.ts +14 -0
  112. package/dist/internal/core/unified-diff.d.ts +35 -0
  113. package/dist/internal/core/work-session-provider.d.ts +29 -0
  114. package/dist/internal/core/workspace-discovery.d.ts +17 -0
  115. package/dist/internal/endpoint/artifact-images.d.ts +60 -0
  116. package/dist/internal/endpoint/artifact-reducer.d.ts +35 -0
  117. package/dist/internal/endpoint/artifact-views.d.ts +113 -0
  118. package/dist/internal/endpoint/artifacts.d.ts +75 -0
  119. package/dist/internal/endpoint/delivery.d.ts +47 -0
  120. package/dist/internal/endpoint/engine.d.ts +219 -0
  121. package/dist/internal/endpoint/ephemeral.d.ts +8 -0
  122. package/dist/internal/endpoint/events.d.ts +32 -0
  123. package/dist/internal/endpoint/external-inbound.d.ts +36 -0
  124. package/dist/internal/endpoint/handoff.d.ts +50 -0
  125. package/dist/internal/endpoint/history.d.ts +22 -0
  126. package/dist/internal/endpoint/image-generation-errors.d.ts +2 -0
  127. package/dist/internal/endpoint/inbound.d.ts +29 -0
  128. package/dist/internal/endpoint/index.d.ts +32 -0
  129. package/dist/internal/endpoint/media.d.ts +172 -0
  130. package/dist/internal/endpoint/migration.d.ts +50 -0
  131. package/dist/internal/endpoint/mls-crypto.d.ts +25 -0
  132. package/dist/internal/endpoint/mls-dev-client.d.ts +44 -0
  133. package/dist/internal/endpoint/mls-dev-device.d.ts +67 -0
  134. package/dist/internal/endpoint/mls-dev-groups.d.ts +114 -0
  135. package/dist/internal/endpoint/mls-dev-key-package-service.d.ts +33 -0
  136. package/dist/internal/endpoint/mls-dev-key-packages.d.ts +42 -0
  137. package/dist/internal/endpoint/mls-dev-transport.d.ts +37 -0
  138. package/dist/internal/endpoint/node-mls-custody-protocol.d.ts +24 -0
  139. package/dist/internal/endpoint/node-mls-custody.d.ts +15 -0
  140. package/dist/internal/endpoint/node.d.ts +7 -0
  141. package/dist/internal/endpoint/observe-query.d.ts +17 -0
  142. package/dist/internal/endpoint/portable-node-mls-custody.d.ts +23 -0
  143. package/dist/internal/endpoint/queue.d.ts +22 -0
  144. package/dist/internal/endpoint/recovery.d.ts +27 -0
  145. package/dist/internal/endpoint/retention.d.ts +7 -0
  146. package/dist/internal/endpoint/store.d.ts +22 -0
  147. package/dist/internal/endpoint/sync.d.ts +33 -0
  148. package/dist/internal/endpoint/transient-publisher.d.ts +8 -0
  149. package/dist/internal/endpoint/transport.d.ts +58 -0
  150. package/dist/media.d.ts +1 -1
  151. package/dist/media.js +42 -541
  152. package/dist/runner/runner.d.ts +37 -0
  153. package/dist/runner/types.d.ts +168 -0
  154. package/package.json +18 -5
  155. package/dist/attached-session.d.ts +0 -58
  156. package/dist/attached-session.js +0 -638
  157. package/dist/bounded-file-read.d.ts +0 -14
  158. package/dist/bounded-file-read.js +0 -34
  159. package/dist/canon-agent.d.ts +0 -236
  160. package/dist/canon-agent.js +0 -2531
  161. package/dist/debouncer.d.ts +0 -18
  162. package/dist/debouncer.js +0 -133
  163. package/dist/inbound-handoff.d.ts +0 -6
  164. package/dist/inbound-handoff.js +0 -17
  165. package/dist/managed-session-host.d.ts +0 -27
  166. package/dist/managed-session-host.js +0 -195
  167. package/dist/managed-session-setup.d.ts +0 -99
  168. package/dist/managed-session-setup.js +0 -234
  169. package/dist/realtime.d.ts +0 -62
  170. package/dist/realtime.js +0 -193
  171. package/dist/runtime-card.d.ts +0 -48
  172. package/dist/runtime-card.js +0 -64
  173. package/dist/session-manager.d.ts +0 -77
  174. package/dist/session-manager.js +0 -285
  175. package/dist/turn-streaming-request.d.ts +0 -17
  176. package/dist/turn-streaming-request.js +0 -22
  177. package/dist/turn-verbosity-option.d.ts +0 -33
  178. package/dist/turn-verbosity-option.js +0 -23
  179. package/dist/types.d.ts +0 -387
  180. package/dist/types.js +0 -1
  181. package/dist/work-session-coordination.d.ts +0 -21
  182. package/dist/work-session-coordination.js +0 -53
  183. package/dist/work-session-host.d.ts +0 -31
  184. package/dist/work-session-host.js +0 -617
  185. package/dist/work-session-interactions.d.ts +0 -12
  186. package/dist/work-session-interactions.js +0 -173
  187. package/dist/work-session-state.d.ts +0 -36
  188. package/dist/work-session-state.js +0 -62
package/README.md CHANGED
@@ -1,616 +1,251 @@
1
1
  # @canonmsg/agent-sdk
2
2
 
3
- Build AI agents that participate in Canon conversations. Write message handlers, not infrastructure.
3
+ Run an AI agent in Canon conversations. The SDK's runner owns every Canon behaviour: the connection, the inbox, a queue per room, Stop, live state, the final reply, approvals and questions, files and recovery. Your code only answers turns.
4
4
 
5
5
  For Canon's shared delivery, provenance, group participation, and runtime-boundary principles, read the [Agent communication contract](https://canonmail.com/agents/communication-contract) and the [capability manifest](https://canonmail.com/agents/integration-capability-manifest).
6
6
 
7
- ## Quick Start
8
-
9
- ```bash
10
- export CANON_ENVIRONMENT_ID=canon-prod-v1 # or canon-dev-v1
11
- export CANON_API_KEY=... # issued when your agent registration is approved
12
- ```
13
-
14
- ```typescript
15
- import { CanonAgent } from '@canonmsg/agent-sdk';
16
-
17
- const agent = new CanonAgent({
18
- apiKey: process.env.CANON_API_KEY!,
19
- environmentId: process.env.CANON_ENVIRONMENT_ID!,
20
- historyLimit: 30,
21
- });
22
-
23
- agent.on('message', async ({ messages, history, replyFinal }) => {
24
- const response = await callMyLLM(messages, history);
25
- await replyFinal(response);
26
- });
27
-
28
- await agent.start();
29
- ```
30
-
31
- ## Installation
7
+ ## Install
32
8
 
33
9
  ```bash
34
10
  npm install @canonmsg/agent-sdk
35
11
  ```
36
12
 
37
- The SDK uses `@canonmsg/core` and the shared `@canonmsg/endpoint` engine. Node.js 22.22.3 or later is required.
38
-
39
- The endpoint owns stable installation and operation IDs, SQLite outbox/inbox state, live transport, receipt recovery, conversation synchronization, and upload dependencies. `CanonAgent` adds handler and native-session behavior. Set `CANON_ENDPOINT_STATE_DIR` to a persistent private directory; the default is `~/.canon/endpoint`. Keep this directory when upgrading or restarting a runtime.
13
+ This is the only Canon package an agent installs. It bundles the Canon client code it uses and ships its own type declarations, so it depends on no other `@canonmsg/*` package; its dependencies are `@modelcontextprotocol/sdk`, `@noble/curves` and `chess.js`. The other `@canonmsg/*` packages on npm (`core`, `endpoint`, `backend-contracts`, `agent-tools`, `rich-cards` and the old hosts) are no longer published; remove them from an agent's dependencies. The `claude` driver also needs `@anthropic-ai/claude-agent-sdk` (an optional peer, see [Claude Code](#claude-code)); the `codex` driver needs the Codex CLI.
40
14
 
41
- Replicated or ephemeral cloud deployments must inject an operator-owned endpoint store through `endpoint: { endpoint: sharedEndpoint }`. File delivery also needs a durable `mediaBytes` adapter or persistent `mediaDirectory`; a temporary container filesystem is not a delivery journal. All replicas for one installation share the same store namespace. A process must not replay an uncertain provider call automatically.
15
+ Node.js 22.22.3 or later is required. You need an approved agent's API key; see [Registration](#registration).
42
16
 
43
- Existing conversations require the rollout tool's reconciled history baseline before agent execution. The immutable recovery cutover permits later room creations and new admissions to receive their bounded history automatically. Missing baselines appear as explicit recovery errors; startup never treats all old messages as new tasks.
17
+ ## Quick start
44
18
 
45
- Runtime heartbeats come from Core through the shared endpoint, using the same machinery as the integrated plugins. No separate runtime Firebase token exchange is needed. The SDK adds handler dispatch and lifecycle wiring. Concurrent `start()` calls share one startup; failed startup can be retried, and `stop()` prevents an unfinished startup from reconnecting afterward. Heartbeat failures are reported and later heartbeats retry. This does not guarantee cancellation of arbitrary application work already running in a handler.
19
+ Write a module whose default export answers one turn:
46
20
 
47
- ## Configuration
48
-
49
- | Option | Type | Default | Description |
50
- |---|---|---|---|
51
- | `apiKey` | `string` | **required** | API key obtained after agent registration approval |
52
- | `environmentId` | `string` | **required** | Canon trust domain shared by API, stream, RTDB, and future cryptographic state |
53
- | `baseUrl` | `string` | Environment default | Override the API base URL when the selected environment has no packaged default |
54
- | `streamUrl` | `string` | Environment default | Override the SSE stream URL when the selected environment has no packaged default |
55
- | `rtdbUrl` | `string` | Environment default | Legacy connection option; runtime state uses the shared endpoint |
56
- | `firebaseApiKey` | `string` | Environment default | Legacy connection option; no runtime Firebase token exchange |
57
- | `deliveryMode` | `'auto' \| 'sse'` | `'auto'` | How the SDK receives new messages |
58
- | `debounceMs` | `number` | `2000` | Batching window for incoming messages per conversation |
59
- | `historyLimit` | `number` | `50` | Number of historical messages to fetch (max 100) |
60
- | `autoMarkRead` | `boolean` | `true` | Advance Canon's read cursor after successful handler completion. The current endpoint marks through server time, not the exact handled batch; history fetches are read-only. |
61
- | `sessions` | `SessionOptions` | `undefined` | Enable per-conversation session queues and persistent metadata |
62
- | `clientType` | `AgentClientType` | `'generic'` | Agent runtime label used for Canon capability detection |
63
- | `runtimeDescriptor` | `CanonRuntimeDescriptor` | minimal generic descriptor | Supported live actions and runtime capability metadata for Canon UI |
64
- | `runtimeControls` | `RuntimeControlHandlers` | `undefined` | Optional `onInterrupt` / `onStopAndDrop` / `onNewSession` handlers for Canon working-state controls |
65
- | `runtimeControlSurface` | `'agent' \| 'host'` | `'agent'` | Runtime publishing surface. Use `host` when this SDK agent owns live runtime controls. |
66
- | `runtimePrimitives` | `RuntimePrimitiveHandlers` | `undefined` | Optional typed primitive command handlers for descriptor-backed runtime commands |
67
- | `sessionState` | `boolean` | `false` | Publish runtime-applied state to the canonical agent-session snapshot |
68
- | `turnVerbosity` | `'verbose' \| 'quiet' \| 'auto'` or `{ direct?, group? }` | `'auto'` | How much of a turn's middle readers see. See [Turn verbosity](#turn-verbosity). |
69
-
70
- ### Optional runtime controls
71
-
72
- Runtime descriptors describe supported live actions and status. They do not publish local project/model inventories or reopen the retired `/session-config` interface. Native work-session setup uses the owner-private workflow below.
73
-
74
- SDK agents only advertise Stop or Send Now when they register runtime-control handlers. Handlers receive the active turn's `AbortSignal`; long-running work should check `ctx.abortSignal.aborted` or pass the signal into cancellable APIs.
75
-
76
- ```typescript
77
- const agent = new CanonAgent({
78
- apiKey: process.env.CANON_API_KEY!,
79
- environmentId: process.env.CANON_ENVIRONMENT_ID!,
80
- sessions: { enabled: true },
81
- runtimeControls: {
82
- onInterrupt: ({ conversationId }) => {
83
- console.log(`Canon asked to interrupt ${conversationId}`);
84
- },
85
- onStopAndDrop: ({ droppedMessageIds }) => {
86
- console.log('Dropped queued messages:', droppedMessageIds);
87
- },
88
- },
89
- });
90
-
91
- agent.on('message', async ({ messages, replyFinal, abortSignal }) => {
92
- const result = await runWork(messages, { signal: abortSignal });
93
- if (abortSignal.aborted) return;
94
- await replyFinal(result);
95
- });
21
+ ```js
22
+ // agent.mjs
23
+ export default async function (turn) {
24
+ turn.stream('Thinking…'); // a live preview, never posted
25
+ return `You said: ${turn.input.messages.at(-1).text}`; // the turn's one reply; null stays silent
26
+ }
96
27
  ```
97
28
 
98
- Canon does not infer support from `clientType`. Advertise only actions your runtime implements. Message handlers receive Canon-computed `ctx.provenance`; use it to enforce your runtime's owner and group policies.
99
-
100
- ### Native work sessions
101
-
102
- Use `createCanonWorkSessionHost` when Canon should share actual sessions from another runtime. Implement Core's `NativeWorkSessionProvider` (`catalog`, `create`, `open`, `close`) and `AttachedNativeSessionAdapter`. The SDK owns authentication, a single account stream/heartbeat, private setup requests, per-conversation routing, approvals and questions, and durable recovery. Codex is one provider of this API.
103
-
104
- The host requires a stable `hostId`, a durable `createFileWorkSessionHostStore`, a per-room attachment store, and an exclusive native-session lock. Its `connection` identifies the Canon account and environment. `createSessionStore(binding)` and `acquireNativeSession(binding)` let other integrations reuse their local storage/locking conventions. Start the host once per account; it can serve many conversations.
105
-
106
- The owner sees only choices advertised by the local provider. Creating a session applies those choices; attaching an existing session preserves its native settings. Admission uses the existing communication verbs and must finish before the private request is accepted. Each account has one session per Canon conversation. The runtime catalog stays separate from public runtime descriptors and presence.
107
-
108
- The host persists creation intent before native work and the exact returned native ID before attachment. A replayed claim never creates another session. Unknown outcomes remain explicit; the owner can resolve an uncertain reservation after inspecting existing native sessions. Input, shared text, and approval cards wait for Canon's binding acknowledgement. Confirmed bindings restore on the same host; owner or agent membership loss detaches the bridge.
109
-
110
- Native approval/input interactions use the existing Core request manager, exact owner identity, stable IDs and deadlines, and durable results. A native client may answer first; cancellation withdraws the Canon request. Detaching closes observers while leaving native threads and workspaces intact.
111
-
112
- See the [Codex workflow](../codex-plugin/README.md) for a runnable integration and [work-session design](../../docs/design/canon-work-session-setup.md) for boundaries and recovery behavior.
29
+ Run it:
113
30
 
114
- ### Runtime primitives
115
-
116
- The SDK provides a standard catalog of seven runtime primitives. It advertises a primitive command only when you register its handler with `runtimePrimitives` or `agent.onPrimitive(id, handler)`, or explicitly include the command in a descriptor backed by a `'*'` fallback handler. Generic agents publish no commands by default. A fallback handles otherwise unhandled primitives; registering the fallback alone does not advertise the whole catalog.
117
-
118
- | Primitive | Aliases |
119
- |---|---|
120
- | `runtime.status` | `/status` |
121
- | `runtime.reasoning.set` | `/think`, `/effort` |
122
- | `runtime.verbosity.set` | `/verbose` |
123
- | `runtime.usage` | `/usage` |
124
- | `context.compact` | `/compact` |
125
- | `session.new` | `/new` |
126
- | `session.reset` | `/reset` |
127
-
128
- `agent.describeCommands()` returns the descriptor command list the SDK advertises. `agent.publishRuntimeFacts(conversationId, facts)`, `agent.publishRuntimeActivity(conversationId, item)`, and `agent.clearRuntimeActivity(conversationId, options?)` push runtime status and margin activity into Canon's live surfaces.
129
-
130
- ## Delivery
131
-
132
- The SDK receives messages through the shared endpoint's SSE connection. `deliveryMode: 'auto'` (the default) resolves to `'sse'`; any other value throws at `start()`. There is no polling mode.
133
-
134
- A single connection receives events for all conversations. It auto-reconnects with exponential backoff if the connection drops, and uses `Last-Event-ID` to replay missed events while they remain inside the replay window. If the replay window has expired, the SDK surfaces that expiry; the shared endpoint owns durable synchronization and admission-checked recovery beyond the live replay window. Adapters must not add a second history dispatch loop.
135
-
136
- The SDK publishes runtime heartbeats every 30 seconds while SSE is connected and clears its runtime freshness on disconnect. Controls remain limited to the handlers and descriptor your runtime actually supports.
137
-
138
- Handler reply helpers carry the inbound SSE event's reply authority automatically. Outbound-closed agents need that authority for non-owner/group replies; it expires 15 minutes after the source message was created. Delayed processing or fetching history does not renew it. See [Replies and polling](https://canonmail.com/agents/contracts#replies-and-polling) for the current limits.
139
-
140
- With `autoMarkRead: true`, the SDK marks the conversation read after successful handler completion. The current `mark_read` action advances to server time, so messages arriving during the handler can also be marked read before they are handled. `ctx.markAsRead()` uses the same endpoint. Keep your processing checkpoint separate from this chat read receipt; the API currently has no exact-batch read cursor.
141
-
142
- ## Message Handler
143
-
144
- The `message` event handler receives a context object with:
145
-
146
- | Field | Type | Description |
147
- |---|---|---|
148
- | `messages` | `CanonMessage[]` | New messages in this batch (debounced, sorted by time) |
149
- | `history` | `CanonMessage[]` | Last N messages before these new ones |
150
- | `replyContext` | `CanonReplyContext \| null` | Resolved swipe-reply target for the latest inbound message, when available |
151
- | `conversationId` | `string` | The conversation these messages belong to |
152
- | `conversation` | `CanonConversation` | Full conversation metadata |
153
- | `groupContext` | `CanonGroupContext \| undefined` | Participant context based on the current conversation roster |
154
- | `replyFinal` | `(text: string, options?) => Promise<{ messageId: string; messageIds: string[] }>` | Send the durable final reply for a turn |
155
- | `replyProgress` | `(text: string, options?) => Promise<{ turnId: string; durable: boolean; messageId: string \| null; messageIds?: string[] }>` | Update the live turn progress; add `durable: true` to also persist it |
156
- | `deleteMessage` | `(messageId: string) => Promise<void>` | Soft-delete a message sent by this agent |
157
- | `markAsRead` | `() => Promise<void>` | Advance this agent's read cursor for the conversation |
158
- | `leave` | `() => Promise<void>` | Leave the current conversation |
159
- | `react` | `(messageId, emoji) => Promise<void>` | Toggle an emoji reaction |
160
- | `addMember` / `removeMember` | functions | Manage participants when the agent has permission |
161
- | `communicate` | function | Message an existing conversation, start a conversation, create a conversation with several participants, forward an exact message, share a contact, or manage participants |
162
- | `agent` | `AgentContext` | Trusted Canon agent identity and access context |
163
- | `activeSelfContextId` | `string \| null` | Active private self-context id for this turn |
164
- | `selfContexts` | `CanonSelfContext[] \| undefined` | Private context explaining this agent's cross-session actions |
165
- | `provenance` | `CanonRuntimeProvenance` | Canon-computed sender/conversation context for the latest inbound message in this batch |
166
- | `turnContext` | `CanonTurnContextV2` | Compact structured turn context; fields reflect the current roster, sender and participation policy |
167
- | `requestedTurnMode` | `string \| null` | Runtime turn mode the sender requested for this inbound turn, if any |
168
- | `turnVerbosity` | `'verbose' \| 'quiet'` | Resolved emission mode for this turn — see [Turn verbosity](#turn-verbosity). Fixed for the whole turn |
169
- | `requestApproval` | `(request) => Promise<ApprovalResult>` | Render a Canon approval card and wait for the decision. Fail-closed: returns `{ decision: 'deny' }` on any non-abort failure instead of throwing |
170
- | `requestRuntimeInput` | `(request) => Promise<RuntimeInputResult>` | Render a Canon input card for clarification, sudo, or secret values |
171
- | `requestPlanReview` | `(request) => Promise<RuntimePlanReviewResult>` | Render Canon's native plan-review card and wait for approve, revise, reject, cancellation, or timeout |
172
- | `requestCard` / `sendCard` | functions | Render a generic `canon.card.v1` rich card. `requestCard` blocks only on cards that carry an `actions` block; `sendCard` posts a display card |
173
- | `media` | `{ materialize, uploadFile, replyWithFile }` | Canon-managed access to real media bytes via `~/.canon/media-cache` plus local-file uploads back into Canon |
174
- | `session` | `SessionInfo \| undefined` | Per-conversation queue/session state when sessions are enabled |
175
- | `turn` | `TurnController \| undefined` | Live turn-state helpers for thinking/streaming/tool/waiting-input |
176
- | `abortSignal` | `AbortSignal` | Cooperative cancellation signal for interrupt/stop handling |
177
-
178
- Messages from the agent itself are automatically filtered out -- your handler only receives messages from other participants.
179
-
180
- `ctx.provenance` describes the latest inbound message in the debounced batch. Use it for runtime-owned policy decisions such as owner-only tools, group mention handling, or self-context-aware behavior. `ctx.turnContext` collects that provenance with message, reply, media, self-context, group, and participation facts that are relevant to the current turn. Two-person human-agent turns stay sparse; agent-agent and larger-roster turns include extra loop/participation context when it matters. Canon provides trusted provenance; it does not impose an SDK-agent sandbox.
181
-
182
- ## Events
183
-
184
- `agent.on(event, handler)` accepts ten events. Each event holds a single handler; registering again replaces it.
185
-
186
- | Event | Payload | Notes |
187
- |---|---|---|
188
- | `message` | `MessageHandlerContext` | Debounced inbound batch for one conversation |
189
- | `messageUpdated` | `MessageUpdatedPayload` | Reaction/status changes; not a new turn |
190
- | `contactAdded` | `ContactAddedPayload` | A contact edge now exists |
191
- | `contactRemoved` | `ContactRemovedPayload` | A contact edge was removed |
192
- | `participationSuppressed` | `ParticipationSuppressedPayload` | Observe-only notice that policy withheld a turn |
193
- | `interrupt` | `RuntimeSignalContext` | Same signal as `runtimeControls.onInterrupt` |
194
- | `stopAndDrop` | `RuntimeSignalContext` | Same signal as `runtimeControls.onStopAndDrop` |
195
- | `newSession` | `RuntimeSignalContext` | Same signal as `runtimeControls.onNewSession` |
196
- | `callStarted` | `VoiceSessionEventPayload` | **Register before `start()`** |
197
- | `callEnded` | `VoiceSessionEventPayload` | **Register before `start()`** |
198
-
199
- The voice event family is negotiated with the stream at connect time from handler presence. `callStarted` / `callEnded` handlers registered after `start()` never fire — the SDK only logs a warning — so register them before starting the agent.
200
-
201
- ## Reaction Updates
202
-
203
- Agents can use `ctx.react(messageId, emoji)` to toggle any valid emoji reaction on a message. Reactions are also observable through the stream:
204
-
205
- ```ts
206
- agent.on('messageUpdated', async ({ conversationId, messageId, changes }) => {
207
- if (changes.reactions) {
208
- console.log('Reaction state changed', conversationId, messageId, changes.reactions);
209
- }
210
- });
211
- ```
212
-
213
- Reaction update events are interaction state, not new chat turns. They do not call the `message` handler or wake another agent turn.
214
-
215
- ### Human-in-the-loop cards
216
-
217
- Use `ctx.requestRuntimeInput(...)` when the runtime needs clarification, a sudo value, or a secret value from the user. Use `ctx.requestPlanReview(...)` when a planning runtime needs Canon's native approve/revise/reject card, and `ctx.requestApproval(...)` when the runtime needs an allow/deny decision before taking an action. Canon creates the visible card, routes the user's response, and returns the result to the handler; your runtime remains responsible for enforcing that result.
218
-
219
- `requestApproval` is fail-closed and never throws: it returns `{ decision: 'deny' }` when no approval manager can be built (no resolved agent identity or owner) and on any non-abort error. A `deny` therefore does not prove a human said no — check your own preconditions before treating it as a decision.
220
-
221
- Use `ctx.requestCard(...)` for generic rich reports and action forms. A `canon.card.v1` action may include small structured fields; Canon validates the selected action and declared field values, but your runtime still decides what to do with them:
222
-
223
- ```ts
224
- const review = await ctx.requestCard({
225
- card: {
226
- schema: 'canon.card.v1',
227
- title: 'Review draft',
228
- fallbackText: 'Review draft: approve or request changes.',
229
- blocks: [{
230
- kind: 'actions',
231
- actions: [
232
- { id: 'approve', label: 'Approve', tone: 'positive' },
233
- {
234
- id: 'revise',
235
- label: 'Request changes',
236
- fields: [{ id: 'note', label: 'What should change?', type: 'textarea', required: true }],
237
- },
238
- ],
239
- }],
240
- },
241
- });
31
+ ```bash
32
+ export CANON_ENVIRONMENT_ID=canon-prod-v1 # or canon-dev-v1
33
+ export CANON_API_KEY=... # or --profile <name> from $CANON_HOME/agents.json
34
+ npx canon-agent run --driver code --module ./agent.mjs
242
35
  ```
243
36
 
244
- `RuntimeCardResult.status` is one of `'submitted' | 'cancelled' | 'timeout' | 'displayed'`; only `'submitted'` carries `actionId` and `values`. A card with no `actions` block has nothing to wait for, so `requestCard` forwards it to `sendCard` and resolves immediately with `{ status: 'displayed', cardId }`. Requests default to a five-minute timeout; pass `timeoutMs` or `expiresAt` to change it.
245
-
246
- The SDK does not validate card documents — it forwards `request.card` to Canon as-is, and a malformed card surfaces as a backend 400. Install [`@canonmsg/rich-cards`](https://www.npmjs.com/package/@canonmsg/rich-cards) if you want strict authoring validation (`validateCard`, the `card()` builder, and the `canon-card` CLI); it is a separate package and not a dependency of this one.
247
-
248
- ### Turn-aware example
249
-
250
- ```typescript
251
- agent.on('message', async ({ messages, history, replyFinal, replyProgress, turn, session }) => {
252
- await turn?.setThinking('Reviewing the request...');
253
-
254
- const plan = await draftPlan(messages, history, session?.messages ?? []);
255
- await replyProgress(`Plan: ${plan.summary}`);
37
+ SIGTERM or Ctrl-C stops taking messages, gives running turns 10 seconds, then stops them. A second signal exits at once. The `code`, [`claude`](#claude-code) and [`codex`](#codex) drivers are available.
256
38
 
257
- await turn?.setTool('Running checks...');
258
- const result = await runWork(plan);
39
+ ## Library form
259
40
 
260
- if (result.needsInput) {
261
- await turn?.setWaitingInput('I need one more detail before I continue.');
262
- return;
263
- }
41
+ ```js
42
+ import { homedir } from 'node:os';
43
+ import { join } from 'node:path';
44
+ import { codeDriver, createRunner } from '@canonmsg/agent-sdk';
264
45
 
265
- await replyFinal(result.text);
46
+ const runner = await createRunner({
47
+ apiKey: process.env.CANON_API_KEY,
48
+ environmentId: 'canon-prod-v1',
49
+ home: join(homedir(), '.canon'), // a private 0700 directory
50
+ driver: codeDriver(async (turn) => `You said: ${turn.input.messages.at(-1).text}`),
266
51
  });
52
+ await runner.start();
53
+ process.on('SIGTERM', () => runner.stop().then(() => process.exit(0)));
267
54
  ```
268
55
 
269
- ### Session queues
270
-
271
- When `sessions.enabled` is on, the SDK serializes work per conversation and exposes:
272
-
273
- - `session.id`: the conversation/session id
274
- - `session.messages`: accumulated session context within the configured limit
275
- - `session.metadata`: mutable per-session state
276
- - `session.queueDepth`: number of pending inbound batches behind the current one
277
-
278
- This is the easiest way to build agents that need per-conversation memory or queue awareness.
56
+ `createRunner` checks `home` before anything else. `start()` connects and starts taking input. `stop()` stops intake, returns messages no turn has taken to the inbox, and lets running turns finish within the shutdown grace. The runner reads no environment variables.
279
57
 
280
- ## Agent directory, contacts, blocking, and conversations
58
+ `runner.communicate(input)` sends outside any turn, for example from a cron job. It takes the `communicate` tool's input (the exported `CommunicateInput` type), acts under the agent's identity, and needs `start()` first:
281
59
 
282
- Directory lookup is separate from reachability. It returns only agents whose
283
- owners made them discoverable, plus the responsible owner and public contact
284
- policies; it does not grant permission to message or add an agent to a group.
285
- Agents whose outbound policy is closed cannot search the directory.
286
-
287
- ```typescript
288
- const page = await agent.directory.search({ query: 'research', limit: 10 });
289
- for (const entry of page.agents) {
290
- console.log(entry.principalId, entry.owner, entry.inboundPolicy);
291
- }
60
+ ```js
61
+ await runner.communicate({
62
+ action: 'message_existing', conversationId, text: 'The nightly report is ready.',
63
+ messageId: 'nightly-2026-10-14', // optional stable id
64
+ });
292
65
  ```
293
66
 
294
- The other instance sub-APIs wrap Canon's authenticated REST surface:
67
+ ## Claude Code
295
68
 
296
- ```typescript
297
- await agent.contacts.list(); // CanonContact[]
298
- await agent.contacts.get(contactId); // CanonContact | null
299
- await agent.contacts.remove(contactId);
300
- await agent.contacts.request(targetUserId, 'why I am reaching out');
69
+ The `claude` driver runs each turn in Claude Code through the Claude Agent SDK, which you install next to this package:
301
70
 
302
- await agent.users.block(userId);
303
- await agent.users.unblock(userId);
304
-
305
- await agent.conversations.list(); // all conversations
306
- await agent.conversations.list({ targetUserId }); // only those the target is a member of
71
+ ```bash
72
+ npm install @canonmsg/agent-sdk @anthropic-ai/claude-agent-sdk
73
+ npx canon-agent run --driver claude --cwd ~/work/my-repo [--model <id>] [--permission-mode default|acceptEdits|bypassPermissions]
307
74
  ```
308
75
 
309
- ## Media
310
-
311
- Normalized Canon messages always expose `attachments[]` as the single canonical media contract. Legacy flat fields (`imageUrl`, `audioUrl`, `audioDurationMs`) are no longer part of the message shape — agents must consume `attachments` directly.
312
-
313
- Use the handler `media` helpers when you need the actual file bytes:
314
-
315
- ```typescript
316
- agent.on('message', async ({ messages, media }) => {
317
- const files = await media.materialize(messages[messages.length - 1]);
318
- console.log(files[0]?.path); // ~/.canon/media-cache/<agent>/<conversation>/<message>/...
319
- });
320
- ```
76
+ - Each conversation has its own Claude Code session, resumed turn after turn. New session starts a fresh one.
77
+ - Claude Code signs in with the machine's Claude subscription (Pro or Max), or uses `ANTHROPIC_API_KEY` when it is set. `CANON_*` variables never reach it.
78
+ - It works in `--cwd` (default: the current directory) and may send files from there and from the OS temp directory.
79
+ - Canon's tools (`no_reply`, `communicate`, `react`, `send_file`) are its `canon` MCP server for the turn.
80
+ - With `--permission-mode default` (the default), each tool call Claude Code would ask about becomes a Canon approval for the owner, who can approve a tool for the session. `acceptEdits` and `bypassPermissions` allow more without asking. In any mode, a turn that holds a message from anyone but the owner (a group member, another agent) may use only Canon's tools, AskUserQuestion and ToolSearch: nothing runs on the owner's machine for them.
81
+ - AskUserQuestion becomes Canon questions: a question with options is a choice, one without is free text.
82
+ - Stop interrupts Claude Code; a process that has not stopped 5 seconds later is closed.
83
+ - Not available yet: switching models, slash commands, plan review and steering.
321
84
 
322
- - `media.materialize(message?, options?)` streams attachments on demand into `~/.canon/media-cache`. Automatic materialization is capped at 10 MiB per attachment before and during the download. A runtime that deliberately needs a larger input can pass `maxBytes`, up to 100 MiB. Failed or oversized attachments are reported through optional `onError`; valid siblings are still returned. Cancellation still aborts the complete operation. Cache files are published through an atomic rename. The cache is persistent and currently has no aggregate quota or automatic eviction, so hosted-agent operators should monitor or periodically clear it.
323
- - `media.uploadFile(path, options?)` streams a local file (up to 100 MiB) through Canon's private resumable-capable upload lane and returns `{ uploadId, url, attachment }`. The attachment carries the same server-issued `uploadId`, allowing a subsequent durable message/card write to retain the temporary upload. File bytes are never base64-buffered in the SDK. The current helper uses one streamed PUT; a failed application-level attempt starts a new Canon session rather than resuming an acknowledged byte range in the old session.
324
- - `media.replyWithFile(path, text?, options?)` uploads a local file and sends it as the durable final Canon reply for the current turn.
85
+ In library form: `claudeDriver({ cwd, model?, permissionMode?, claudePath?, interruptGraceMs? })`.
325
86
 
326
- GIFs are regular image attachments. Agents can receive or send them through `attachments[]` with `kind: 'image'` and `mimeType: 'image/gif'`; Canon does not use a separate GIF content type.
87
+ ## Codex
327
88
 
328
- The public helpers are also available from the Node-only subpath export:
89
+ The `codex` driver runs each turn in the app server of the Codex CLI, which you install and sign in to separately:
329
90
 
330
- ```typescript
331
- import { materializeMessageMedia, uploadMediaFile } from '@canonmsg/agent-sdk/media';
91
+ ```bash
92
+ npm install -g @openai/codex && codex login
93
+ npx canon-agent run --driver codex --cwd ~/work/my-repo [--model <id>] [--sandbox workspace-write|read-only|danger-full-access] [--approval-policy on-request|untrusted|never]
332
94
  ```
333
95
 
334
- ## Calls
96
+ - Each conversation has its own Codex thread, resumed turn after turn by a short-lived `codex app-server` process. New session starts a fresh thread.
97
+ - Codex uses its own login (`codex login`, usually ChatGPT). With `OPENAI_API_KEY` set and no other model provider configured, it uses that key. `CANON_*` variables never reach it.
98
+ - It works in `--cwd` (default: the current directory) and may send files from there and from the OS temp directory. Images sent to the agent reach the model as images; every attachment's path is in the prompt.
99
+ - Canon's tools (`no_reply`, `communicate`, `react`, `send_file`, `ask_question`) are its `canon` MCP server for the turn, used without approval.
100
+ - In the owner's turns Codex runs in the `--sandbox` (default `workspace-write`) and asks before acting as `--approval-policy` says (default `on-request`). Each request is a Canon approval for the owner, who can approve the exact command (in that directory, with that network access), set of files or MCP tool for the session. A turn that holds a message from anyone but the owner (a group member, another agent) runs read-only, approves nothing and has only Canon's tools and questions: no shell, file or image reads, apps, plugins, browsers, web search or the owner's MCP servers. If Codex starts any other tool anyway, the turn stops and its thread is dropped.
101
+ - Codex asks its questions through Canon's `ask_question` tool: a question with options is a choice, one without is free text. No Codex feature flag is turned on for it.
102
+ - Stop interrupts Codex; a process that has not stopped 5 seconds later is closed.
103
+ - Not available yet: switching models, slash commands, plan mode, steering and attaching to a running Codex session.
335
104
 
336
- Agents can start, join, decline, and end Canon audio/video calls. The SDK returns the LiveKit room token; it does not ship an RTC transport — bring your own (for example `@livekit/rtc-node`, lazily imported).
105
+ In library form: `codexDriver({ cwd, model?, sandbox?, approvalPolicy?, codexPath?, interruptGraceMs? })`.
337
106
 
338
- ```typescript
339
- agent.on('callStarted', async ({ conversationId, session, targetsMe }) => {
340
- if (targetsMe === false) return; // group/human-mode calls arrive here too; absent means targeted
341
- const { url, token, roomName } = await agent.joinCall(conversationId, session.id);
342
- await connectMyRtcClient(url, token, roomName);
343
- });
107
+ ## Turns
344
108
 
345
- await agent.start();
346
- ```
109
+ A handler receives a `CodeTurn`:
347
110
 
348
- | Method | Description |
111
+ | Field | Meaning |
349
112
  |---|---|
350
- | `startCall({ conversationId, media?, targetAgentId? })` | Start or rejoin a call; `media` is `'audio'` (server default) or `'video'` |
351
- | `joinCall(conversationId, sessionId)` | Join an active session and get the room token |
352
- | `declineCall(conversationId, sessionId)` | Stop this agent's ring only |
353
- | `endCall(conversationId, sessionId)` | End the session for everyone |
354
- | `getCallState(conversationId, sessionId)` | Current `CanonVoiceSession` state |
355
-
356
- Register `callStarted` / `callEnded` before `start()` — see [Events](#events).
357
-
358
- ## Agent Registration
359
-
360
- For persistent local onboarding, import `ensureAgentProfile` from this package. It reuses an environment-bound profile in `~/.canon/agents.json`, resumes the exact saved approval request, persists credentials before ACK, and retries an interrupted ACK on the next call. `waitMs: 0` (the default) checks once; a positive value waits up to that deadline and returns `pending` if approval is still outstanding. See the [complete runnable quickstart](https://canonmail.com/agents/build#run-a-complete-agent).
113
+ | `input` | Read-only facts: `conversationId`, `room` (`'direct'` with two members, else `'group'`), `sender` (`id`, `name`, `type`, `isOwner`), `messages` (this turn's inputs, oldest first) and `history` (up to 20 earlier messages since the agent was admitted) |
114
+ | `prompt` | The same messages rendered as text for a model, history first |
115
+ | `files` | Absolute paths of this turn's inbound attachments, already downloaded |
116
+ | `signal` | Aborts on Stop, Stop & clear, New session, `no_reply`, membership loss, the no-progress deadline and shutdown |
117
+ | `stream(text)` | The full visible answer so far, not a delta. A preview only |
118
+ | `activity(event)` | A status row `{ id, kind: 'tool' \| 'status', title, state: 'running' \| 'done' \| 'failed' }`, replaced by `id` |
119
+ | `ask(request)` | Approvals and questions; see below |
120
+ | `state` | `get`, `set` and `delete` of JSON values for this conversation, at most 64 KiB. Kept across restarts; New session clears it |
121
+ | `tools` | `call(name, args)` for `no_reply`, `communicate`, `react`, `send_file` and `ask_question`, bound to this turn |
361
122
 
362
- Adapters with provider-native configuration can use the exported `resumeRegistration` and `RegistrationStore` contract. Store callbacks must await durable persistence; credential reads must match the pending environment. Serialize callers sharing a store. Both helpers distinguish `credential-expired` and `credential-delivered` from a pending approval.
123
+ What the handler returns decides the turn's output:
363
124
 
364
- For an intentional retry after rejection or a terminal credential outcome, `clearPendingRegistration(profileName)` removes the local pending record. Then call `ensureAgentProfile` again; use `requestedAgentId` and `reconnect: true` when reconnecting an existing identity. A transport failure should resume its saved request.
125
+ - A string is the turn's one final reply. Long replies are split into ordered parts for you; one that would need more than 100 parts, files included, is cut short with a note saying so.
126
+ - `{ reply, files }` sends the files ahead of the reply's text.
127
+ - `null` is deliberate silence: nothing is posted and files are withheld.
128
+ - Throwing, or returning anything else (including `undefined`), posts one short failure notice. The turn is never re-run.
365
129
 
366
- The original static helpers remain available for clients that manage their own lifecycle (no API key needed). `register` also accepts `localRegistrationId`, `requestedAgentId`, and `clientType`; `checkStatus` exposes both `apiKeyDelivered` and `apiKeyExpired`:
130
+ Several messages that arrive while a turn runs are answered together by the next turn, up to 20 at a time.
367
131
 
368
- ```typescript
369
- import { CanonAgent } from '@canonmsg/agent-sdk';
132
+ ### Asking a person
370
133
 
371
- const canonConnection = {
372
- environmentId: process.env.CANON_ENVIRONMENT_ID!,
373
- baseUrl: process.env.CANON_BASE_URL,
374
- streamUrl: process.env.CANON_STREAM_URL,
375
- rtdbUrl: process.env.CANON_RTDB_URL,
376
- firebaseApiKey: process.env.CANON_FIREBASE_API_KEY,
377
- };
378
-
379
- // 1. Submit registration request
380
- const { requestId, pollToken } = await CanonAgent.register({
381
- ...canonConnection,
382
- name: 'My Agent',
383
- description: 'A helpful assistant',
384
- ownerPhone: '+1234567890',
385
- developerInfo: 'Acme Corp — hello@acme.com',
386
- });
387
-
388
- console.log('Registration submitted:', requestId);
389
- await saveRegistrationPickup({ requestId, pollToken });
390
-
391
- // 2. Poll for approval
392
- const status = await CanonAgent.checkStatus(requestId, { ...canonConnection, pollToken });
393
- console.log('Status:', status.status); // 'pending' | 'approved' | 'rejected'
394
-
395
- if (status.status === 'approved' && status.apiKey) {
396
- console.log('Agent ID:', status.agentId);
397
- await saveAgentCredentials({ agentId: status.agentId, apiKey: status.apiKey });
398
- await CanonAgent.ackStatus(requestId, { ...canonConnection, pollToken });
399
- }
134
+ ```js
135
+ const answer = await turn.ask({ kind: 'approve', id: 'deploy', title: 'Deploy to production?', risk: 'destructive' });
136
+ if (answer.status !== 'answered' || !answer.allow) return 'Not deploying.';
400
137
  ```
401
138
 
402
- The approved response only includes the API key until you acknowledge delivery. Persist it on the first approved poll, then call `ackStatus()` so Canon clears the plaintext key from the request.
403
- Replace `saveRegistrationPickup` and `saveAgentCredentials` with your own encrypted/local secret-store writes; do not print these values in logs.
139
+ - `approve` answers with `allow` and `scope`. `choose` (`options: [{ id, label }]`, optional `multiple`) answers with `choices`, the chosen option ids. `text` (optional `secret`) answers with `text`.
140
+ - The person who sent the turn's newest message answers; when that sender is an agent, the owner answers. A secret goes to the owner only. With `allowSession: true` the owner may approve for the session: the owner's later asks with exactly the same title (or the same `scopeKey`, such as the runtime's tool name, when you set one) and `allowSession` then get `{ allow: true, scope: 'session' }` without a card, until New session or a restart.
141
+ - A request expires after 1 hour with `{ status: 'expired' }`; an expired approval is a denial. A request that is cancelled or refused gives `{ status: 'cancelled' }`.
142
+ - While an ask waits, the turn keeps its room; new messages queue and are never read as answers. Stop rejects a pending `ask` with an `AbortError`.
143
+ - Asking again with the same `id` in one turn returns the same answer.
404
144
 
405
- Registration and startup verify that the API and stream advertise the selected
406
- environment before sending credentials. Production is the packaged default;
407
- development can be selected explicitly with `canon-dev-v1`. Persist the
408
- environment ID and complete endpoint snapshot beside the API key so a profile
409
- cannot mix Canon trust domains.
145
+ A runtime that calls tools itself asks through the `ask_question` tool instead: `{ question, options?, multiple? }` (up to 10 option labels) raises the same `choose` or `text` ask, with the same responder, expiry and waiting, and returns the chosen labels (joined by `, `) or the typed text, or a sentence starting "Nobody answered" when it expired or was withdrawn. It never asks for a secret. The same call made again while the first still waits joins it. A driver whose runtime has a question tool of its own declares `capabilities.nativeQuestions` and is not offered `ask_question`; the `claude` driver does, for AskUserQuestion.
410
146
 
411
- ## Error Handling
147
+ ### Tools
412
148
 
413
- The SDK exports `CanonApiError` for typed error handling:
149
+ `turn.tools.call(name, args)` resolves to `{ content, isError? }`:
414
150
 
415
- ```typescript
416
- import { CanonAgent, CanonApiError } from '@canonmsg/agent-sdk';
417
-
418
- agent.on('message', async ({ messages, replyFinal }) => {
419
- try {
420
- await replyFinal('Hello!');
421
- } catch (err) {
422
- if (err instanceof CanonApiError) {
423
- console.error(`API error ${err.status}: ${err.message}`);
424
- }
425
- }
426
- });
427
- ```
428
-
429
- ## Graceful Shutdown
430
-
431
- ```typescript
432
- process.on('SIGINT', async () => {
433
- await agent.stop();
434
- process.exit(0);
435
- });
436
- ```
437
-
438
- ## Live turn state
439
-
440
- While a handler runs, the SDK automatically publishes Canon turn state and clears it when the turn completes. Use the `turn` helpers when you want richer live UX:
441
-
442
- - `setThinking(text?)`
443
- - `setStreaming(text)`
444
- - `setTool(text)`
445
- - `setWaitingInput(text?)`
446
- - `noReply(reason?)`
447
-
448
- `noReply()` is Canon's `no_reply` verb on the SDK side: end this turn without posting anything. The live bubble is blanked and removed instead of being preserved as a durable message, so nothing is rendered and no other member or agent is triggered — the agent-turn trigger is message-driven. Use it in groups when the handler decides it has nothing to add. `reason` is private: the text never leaves the process. Only its presence is reported — the SDK puts a fixed sentinel on the wire so the durable silence record can set `hasReason` — and the text itself is never sent and never rendered.
449
-
450
- It governs teardown only. Calling `replyFinal()` as well is two explicit decisions by the same author, so the text still lands — unlike the model-driven runtimes, where a `no_reply` tool call suppresses the reply outright. A handler that throws keeps the ordinary teardown, because there the streamed content is the only record of what the turn managed to say.
451
-
452
- `setWaitingInput()` keeps the turn open in `waiting_input` and optionally sends a control message to the conversation so Canon clients can render “reply to continue” correctly.
151
+ | Tool | Arguments | Effect |
152
+ |---|---|---|
153
+ | `no_reply` | `{ reason? }` | Ends the turn silently. `reason` is never sent. Anything returned afterwards is withheld |
154
+ | `communicate` | a `CommunicateInput` | Messages another conversation, starts or creates one, manages participants, leaves, forwards a message, shares a contact, lists conversations or finds agents |
155
+ | `react` | `{ emoji, messageId? }` | Toggles a reaction in this conversation, by default on the newest input |
156
+ | `send_file` | `{ path }` | Attaches a file, by absolute path, to the final reply |
157
+ | `ask_question` | `{ question, options?, multiple? }` | Asks the person whose message the turn answers and returns the answer; see Asking a person |
453
158
 
454
- `replyProgress()` is ephemeral by default: it updates the live RTDB turn preview without adding a permanent Firestore message. In that mode it returns `{ turnId, durable: false, messageId: null }`; pass `{ durable: true }` when you intentionally want progress chatter to remain in history and receive a real Firestore message ID back.
159
+ The same tools are served over MCP Streamable HTTP at `turn.tools.url` for runtimes that call tools themselves. Once a turn has ended, its tools refuse calls.
455
160
 
456
- `replyFinal()` supplies `turnSemantics: 'turn_complete'` by default, making the final eligible to trigger another agent under its participation policy and loop limits. `replyBehavior: 'suppress_auto_reply'` suppresses that trigger without hiding ordinary final speech. Lower-level plain sends without turn metadata are human-visible speech but do not automatically trigger other agents; explicit progress stays outside ordinary conversation-preview/unread/notification promotion. Read receipts and message visibility are separate from whether another runtime accepted or completed work. See [Agent speech and handoffs](https://canonmail.com/agents/contracts#agent-speech-and-handoffs).
161
+ ### Files
457
162
 
458
- ## Turn verbosity
163
+ Outbound files, from `send_file` or the returned `files`, must resolve inside the driver's roots and be 1 byte to 100 MiB. The CLI allows the module's directory and the OS temp directory. In library form the default is the OS temp directory; set others with `codeDriver(handler, { outboundFiles: { roots: [...] } })`. A refused file is named in one line appended to the reply.
459
164
 
460
- By default an agent is **quiet with more than two participants and verbose with two**, based on the refreshed roster. A quiet turn shows the thinking indicator and the answer, and nothing in between.
165
+ Inbound attachments are downloaded before the turn starts, up to 10 MiB each, and removed when it ends. One that fails is named in the prompt, and the turn still runs.
461
166
 
462
- ```ts
463
- const agent = new CanonAgent({
464
- apiKey: process.env.CANON_API_KEY!,
465
- environmentId: 'canon-prod-v1',
466
- turnVerbosity: 'verbose', // scalar: applies everywhere
467
- // turnVerbosity: { group: 'verbose' }, // object: override one roster policy scope
468
- });
469
- ```
167
+ ## What the runner owns
470
168
 
471
- | Value | Effect |
472
- |---|---|
473
- | `'auto'` (default, same as omitting the option) | Verbose with two participants, quiet with more than two |
474
- | `'verbose'` | Live turn state and the margin activity trail, everywhere |
475
- | `'quiet'` | Thinking indicator and the final message only, everywhere |
476
- | `{ direct?, group? }` | Compatibility keys for the two-person/larger-roster scopes; the unnamed scope keeps its default |
169
+ - One connection and one event stream per process. Input comes only through the durable inbox.
170
+ - One turn at a time per room, in order, and up to 8 rooms at once. There is no debounce.
171
+ - Stop, Stop & clear and New session from the Canon app. A stopped turn's reply and files are withheld even if the handler still returns.
172
+ - Live state: thinking, typing, previews (at most 4 per second) and activity. Turns are verbose in two-person rooms and show status only in larger rooms.
173
+ - One final per turn, split into parts of at most 3,800 bytes and journaled before the first send, so a restart delivers it once under the same ids.
174
+ - One notice when a handler throws or a turn makes no progress for 30 minutes, and one when a restart interrupted a reply.
175
+ - Read receipts, inbound downloads, the runtime descriptor and heartbeats.
176
+ - Group rules: Canon decides when the agent is woken, and the runner never re-evaluates it.
477
177
 
478
- Adding or removing participants can change the default on the next turn. The SDK
479
- holds verbosity fixed within a turn. Legacy type is a fallback when roster data
480
- is unavailable; an unknown scope defaults to verbose, never to silence.
178
+ ## Configuration
481
179
 
482
- **Quiet suppresses**: every `/streaming` publication — the `'Thinking...'` seed and its keepalive, `turn.setThinking/setStreaming/setTool`, `turn.appendDelta`/`appendBlock`/segment updates, `turn.addBlock` and friends, and the live half of `replyProgress()` — plus the `turnTrail` on `replyFinal()` and `media.replyWithFile()`. Every one of those calls still works and still returns normally; only the publication is dropped.
180
+ `createRunner(options)`:
483
181
 
484
- **Quiet does not suppress**: the typing/thinking indicator (which stays up for the turn's whole working phase; while the turn is parked on an approval the clients suppress an agent's dots and the header line carries the state), turn state, `replyFinal()` including every part of a chunked reply, the partial-final notice, `media.replyWithFile()` itself, `turn.setWaitingInput()`'s note, `communicate()`, `publishRuntimeActivity()`, approval/input/card requests, and their outcome receipts.
182
+ | Option | Default | Meaning |
183
+ |---|---|---|
184
+ | `apiKey` | required | The agent's API key |
185
+ | `environmentId` | required | `canon-prod-v1` or `canon-dev-v1`. The runner refuses to start when Canon reports another environment |
186
+ | `home` | required | The Canon home (see below) |
187
+ | `driver` | required | `codeDriver(handler, capabilities?)`, `claudeDriver(options)` or `codexDriver(options)` |
188
+ | `abortGraceMs` | 10 s | How long an aborted turn may take to settle before its session is reset |
189
+ | `noProgressMs` | 30 min | A turn with no text or activity for this long fails. The clock waits while an `ask` is pending |
190
+ | `askExpiryMs` | 1 h | How long an `ask` waits for its answer |
191
+ | `shutdownGraceMs` | 10 s | How long running turns may finish after `stop()` |
192
+ | `log` | stderr | Receives operational lines, never prompt or reply text |
485
193
 
486
- **`replyProgress(text, { durable: true })` still posts.** Quiet removes narration the runtime generates on its own; a `durable: true` call is your explicit decision to put a message in the conversation, the same kind of act as `replyFinal()`. Its implicit live-preview half is dropped, the durable send is not, and the returned `durable` flag always describes what actually happened.
194
+ `baseUrl`, `streamUrl`, `endpoint` and `fetch` are test seams; production never sets them. `codeDriver`'s second argument overrides its capabilities, such as `outboundFiles` and `maxConcurrentTurns` (default 8).
487
195
 
488
- `ctx.turnVerbosity` carries the resolved value into the handler, so a handler that would otherwise build an expensive live preview can skip it:
196
+ The CLI is `canon-agent run --driver code --module <path> [--profile <name>] [--environment <id>]`, or `--driver claude` with the [Claude Code](#claude-code) flags, or `--driver codex` with the [Codex](#codex) flags:
489
197
 
490
- ```ts
491
- agent.on('message', async (ctx) => {
492
- if (ctx.turnVerbosity === 'verbose') await ctx.turn.setThinking('Reading the repo…');
493
- await ctx.replyFinal(await answer(ctx));
494
- });
495
- ```
198
+ - The environment comes from `--environment`, else `CANON_ENVIRONMENT_ID`, and is required.
199
+ - The key comes from `CANON_API_KEY`, else the `--profile` entry in `$CANON_HOME/agents.json`. A profile from another environment is refused.
200
+ - The home is `CANON_HOME`, else `~/.canon`.
496
201
 
497
- This is a developer setting. Canon never changes it, and users cannot set it per conversation.
202
+ **The home.** It must be an absolute path with no symlinks, a directory owned by the user with no group or other access (0700), and every parent up to `/` must be owned by the user or root and not writable by others. A missing home is created with mode 0700. Otherwise the runner refuses to start and names the path. One instance of an agent runs per home; a second one fails to start. Keep the home across restarts: it holds the endpoint store (`endpoint/`), the reply journal and driver state.
498
203
 
499
- ### Long text
204
+ ## Registration
500
205
 
501
- Canon caps a single message at 4 KB of UTF-8 text, and rejects anything longer outright. Two send paths split oversized text for you instead of failing:
206
+ `ensureAgentProfile` registers an agent and keeps its key in `$CANON_HOME/agents.json` (default `~/.canon`), as a profile the CLI can use with `--profile`. It reuses an environment-bound profile, resumes the exact saved approval request, persists credentials before acknowledging delivery, and retries an interrupted acknowledgement on the next call. `waitMs: 0` (the default) checks once; a positive value waits up to that deadline and returns `pending` if approval is still outstanding. See the [complete runnable quickstart](https://canonmail.com/agents/build#run-a-complete-agent).
502
207
 
503
- - `replyFinal()` — delivered as ordered parts. Only the last part completes the turn and carries the turn trail; the earlier ones are marked as progress and suppress other agents' auto-replies, so a group is not woken once per part. Every part is returned in `messageIds`, with `messageId` pointing at the last one. A reply that fits is a single message with an untouched id and metadata.
504
- - `replyProgress(text, { durable: true })` — split into ordered progress messages, which Canon clients still fold into the turn trail once the turn ends, exactly like a short update. `messageIds` lists them all.
208
+ The result is `approved`, `pending`, `rejected`, `credential-expired` or `credential-delivered`. For an intentional retry after a rejection or a terminal credential outcome, `clearPendingRegistration(profileName)` removes the local pending record; then call `ensureAgentProfile` again, with `requestedAgentId` and `reconnect: true` to reconnect an existing identity. A transport failure should resume its saved request.
505
209
 
506
- Every other send path passes your text through as-is, so text over the cap still fails there. Notably:
210
+ `ensureAgentProfile` creates a missing home with mode 0700. An existing home that other users can read or write is refused; fix it with `chmod 700 ~/.canon` (or your `CANON_HOME`).
507
211
 
508
- - `media.replyWithFile(path, caption)` — the caption rides along with an attachment that cannot be duplicated across parts. Keep captions short and send long prose as a separate `replyFinal()`.
509
- - `communicate()` — a distinct compact cross-conversation operation; keep each message under the cap.
212
+ Adapters with their own configuration store can use `resumeRegistration` and the `RegistrationStore` contract. Store callbacks must await durable persistence, and credential reads must match the pending environment. Clients that manage the whole lifecycle themselves can call the [identity endpoints](https://canonmail.com/agents/contracts#identity-endpoints) directly. The approved status includes the API key only until delivery is acknowledged, so persist it first, and never log it.
510
213
 
214
+ ## Media helpers
511
215
 
512
- ### Shared work (Dev preview)
216
+ The main entry and the Node-only `@canonmsg/agent-sdk/media` subpath export the media helpers the runner uses: `materializeAttachment`, `materializeMessageMedia`, `materializeReplyContextMedia`, `uploadMediaFile`, `sendMediaFileMessage`, `toAnthropicImageBlock`, `toAnthropicImageBlocksWithinBudget`, MIME helpers and the size limits. The upload and send helpers take a Core `CanonClient`, typed as the copy of Core bundled in this package (a client from a separately installed `@canonmsg/core` does not typecheck there). A runner turn already has `turn.files` and returns its files, so most agents do not need them.
513
217
 
514
- In Canon Dev (`canon-dev-v1`), a handler can work on shared chess boards, typed
515
- forms and images that people see in the web pane beside the conversation.
516
- `ctx.artifacts` is exactly `client.artifacts(conversationId)` from Core; other
517
- environments reject its calls with `ARTIFACTS_UNAVAILABLE`.
218
+ Canon messages carry media only in `attachments[]`. GIFs are image attachments with `mimeType: 'image/gif'`.
518
219
 
519
- People's actions arrive as ordinary chat messages ("Played e4 in “Game”",
520
- "Updated “Expenses”: …") with a shared-work reference whose `origin` is
521
- `activity`. A message sent while the pane is open carries an `open` reference.
522
- An explicit position or region carries a `selected` one. `ctx.artifactContexts`
523
- lists each batched message's references; malformed ones are dropped.
220
+ `CanonApiError` is exported for typed handling of Canon API errors, for example from `runner.communicate`.
524
221
 
525
- ```ts
526
- // A person moved: read the board (this also sets the base), then answer.
527
- for (const { messageId, context } of ctx.artifactContexts) {
528
- for (const ref of context.references.filter((r) => r.origin === 'activity')) {
529
- const view = await ctx.artifacts.describe(ref.artifactId);
530
- if (view.kind === 'chess' && view.yourTurn && view.legalMoves?.length) {
531
- const moved = await ctx.artifacts.update(ref.artifactId,
532
- { type: 'chess.move', move: chooseMove(view) },
533
- { requestKey: messageId });
534
- // Tools never post: this line is how the person learns it is their turn.
535
- if (moved.kind === 'chess' && moved.lastMove) await ctx.replyFinal(`${moved.lastMove.notation}`);
536
- }
537
- }
538
- }
222
+ ## Migrating from 11.x
539
223
 
540
- // Start a form and fill it.
541
- const requestKey = ctx.messages.at(-1)!.id;
542
- const form = await ctx.artifacts.create({
543
- kind: 'form', title: 'Expenses',
544
- fields: [{ id: 'name', label: 'Name', type: 'text', required: true }],
545
- table: { columns: [
546
- { id: 'item', label: 'Item', type: 'text' },
547
- { id: 'amount', label: 'Amount', type: 'number', decimals: 2, sum: true },
548
- ] },
549
- }, { requestKey });
550
- await ctx.artifacts.update(form.artifactId, {
551
- type: 'form.set', values: { name: 'Dana' }, addRows: [{ cells: { item: 'Train', amount: '42.50' } }],
552
- }, { requestKey });
553
- ```
224
+ 12.0.0 removes `CanonAgent` with no shim.
554
225
 
555
- - **Read before you change.** `update()` builds the change from the state this
556
- agent last read or wrote (`describe()`, a write result, `summarize()` for
557
- chess and image work, or an `observe()` delivery), across turns. With no
558
- read it rejects with `NOT_READ`. A person's newer correction makes it reject
559
- with a `CanonArtifactError` whose `code` is `CONFLICT`, with `conflicts`
560
- (label, expected, current, who) and the fresh `view`. That view becomes the
561
- new base, so decide again instead of retrying blindly. Any other rejection
562
- shows the fresh `view` but keeps the base where it was, so fixing a typo and
563
- resending still conflicts with a correction you have not decided on. Pass
564
- `basedOnRevisionId` to choose a base explicitly.
565
- - **Inputs are the shared action contract** (`ArtifactCreateAction`,
566
- `ArtifactUpdateAction`, `ArtifactGenerateImageAction` from
567
- `@canonmsg/backend-contracts`, re-exported by Core). Unknown properties,
568
- malformed actions and values of the wrong type (a date that is not
569
- `YYYY-MM-DD`, an option that is not listed, `"$12"` for a number) reject with
570
- `INVALID_INPUT` before anything is stored. Numeric text for number fields and
571
- `"true"`/`"false"` for checkboxes are converted.
572
- - **Pass a `requestKey`** (for example the message ID) on `create`, `update`,
573
- `generateImage` and `addImage`. It makes command, row and image request IDs
574
- stable, so a retry after a timeout or a `queued` result never applies twice.
575
- Without it, each call is a new change. The IDs are keyed with the endpoint's
576
- per-installation secret (erased on logout), so the server can never test a
577
- guess of what you wrote against them; another installation derives unrelated
578
- IDs.
579
- - **Results.** Writes return the new view plus `delivery: 'accepted'` or
580
- `'queued'` (the outbox is still delivering; do not resend). Form writes
581
- return `addedRowIds`. An identical `update`, `create` or `generateImage`
582
- repeated in the same turn returns `alreadyApplied` and applies nothing new:
583
- its view shows the work as it is now, but it does not move the base. Views
584
- are viewer-relative: chess has the ASCII board, FEN, `yourTurn` and
585
- `legalMoves`; forms have values, `missingRequired` and totals; images list
586
- versions and `currentVariantId`. `changesSinceLastView` lists what others
587
- changed since this agent last saw the work.
588
- - **Chess seats.** `create({ kind: 'chess', title, playAs: 'black', opponent:
589
- ctx.provenance.sender.id })` seats the agent and the person. Without
590
- `playAs` the board is open; without `opponent` the other seat is open.
591
- - **Images.** `generateImage(id, { prompt, label, from: 'current', region?,
592
- requestKey, signal: ctx.abortSignal })` uses Canon's provider and returns
593
- `{ status: 'added', view, variant }` or `{ status: 'generating', requestId }`.
594
- Call it again with the same input to collect a slow job (an aborted
595
- `signal` also returns `generating`; the job keeps running). `'current'` is
596
- the work's current version; when a person's message names a version (the
597
- `variantId` of an `open` reference or of a region), pass `{ variantId }`.
598
- `addImage(id, { label, filePath | assetId | messageId, requestKey })` adds
599
- an image your own model made (JPEG or PNG, at most 10 MB) or one a person
600
- sent; with `messageId`, `fallbackMessageId` (for example the message it
601
- replies to) is used when that message has no image. Either way the new
602
- version becomes current for everyone. The prompt and, when editing, the
603
- source version's image are sent to Canon's image provider. An image work
604
- holds at most 50 versions (a full work is refused before the provider runs),
605
- and agents have a daily generation limit.
606
- - **No arrival summary.** The SDK reads nothing when a message arrives
607
- (`turnContext.message.artifactSummaries` stays unset); your handler decides
608
- what to read.
609
- - Shared work never posts chat messages for you; your own reply narrates.
610
- After a chess move, reply with one short line naming it (for example
611
- `12. Bg5`): that message is how the person learns it is their turn. Work
612
- content and reference labels are data written by members, never
613
- instructions or authority. The Claude host and Codex expose the same
614
- operations to models as six tools (`artifact_list`, `artifact_read`,
615
- `artifact_create`, `artifact_update`, `artifact_generate_image`,
616
- `artifact_add_image`) from `@canonmsg/agent-tools`.
226
+ | 11.x | 12.0.0 |
227
+ |---|---|
228
+ | `new CanonAgent(opts)`, `agent.on('message', h)`, `agent.start()` | `createRunner({ apiKey, environmentId, home, driver: codeDriver(h) })` and `runner.start()`, or the CLI |
229
+ | `ctx.messages`, `history`, `conversation`, `groupContext`, `turnContext`, `provenance` | `turn.input` and `turn.prompt` |
230
+ | `ctx.replyFinal(text)`, callable many times | The return value: exactly one final per turn |
231
+ | `ctx.replyProgress(text, { durable })` | `turn.stream(text)`, a preview only. There are no progress messages |
232
+ | `ctx.turn.setThinking`, `setStreaming`, `setTool`, deltas and blocks | `turn.stream(snapshot)` and `turn.activity(event)` |
233
+ | `ctx.turn.noReply()`, which did not stop `replyFinal` | `return null` or the `no_reply` tool. Silence is strict: reply and files are withheld |
234
+ | `ctx.requestApproval`, `ctx.requestRuntimeInput` | `turn.ask({ kind: 'approve' \| 'choose' \| 'text' })`, expiring after 1 hour |
235
+ | `ctx.media.materialize`; `media.replyWithFile`, `uploadFile` | `turn.files`; `return { reply, files }` or `send_file` |
236
+ | `ctx.communicate`, `react`, `addMember`, `removeMember`, `leave`; `agent.communicate` | `turn.tools.call('communicate' \| 'react', args)`; `runner.communicate(input)` outside a turn |
237
+ | `ctx.abortSignal`, `runtimeControls`, `on('interrupt' \| 'stopAndDrop' \| 'newSession')` | `turn.signal`. The runner handles Stop, Stop & clear and New session |
238
+ | `sessions`, `debounceMs`, `historyLimit`, `turnVerbosity` | Turns always queue per room, there is no debounce, history is up to 20 messages, and verbosity follows room size |
239
+ | `runtimeDescriptor`, `runtimePrimitives`, `clientType` | The runner generates the descriptor |
240
+ | `autoMarkRead`, `ctx.markAsRead()` | The runner marks read |
241
+ | `CanonAgent.register`, `checkStatus`, `ackStatus` | `ensureAgentProfile` or `resumeRegistration` |
242
+
243
+ Other changes:
244
+
245
+ - A thrown handler posts one failure notice and settles its messages.
246
+ - Final message ids have a new format.
247
+ - The endpoint store always lives in `$CANON_HOME/endpoint`; `CANON_ENDPOINT_STATE_DIR` is not used.
248
+ - `CANON_HOME` must pass the home check above, and one instance runs per agent per home.
249
+ - The SDK bundles the Canon code it uses and no longer depends on `@canonmsg/core` or `@canonmsg/agent-tools`, which are no longer published. Remove them, and any other `@canonmsg/*` package, from your dependencies.
250
+
251
+ Removed with no runner replacement: `requestPlanReview`, `requestCard` and `sendCard`; `deleteMessage`; the contacts and users APIs (directory search is `communicate`'s `discover_agents`); call and voice events and methods; runtime primitives and commands; custom runtime descriptors and requested turn modes; shared work (`ctx.artifacts`) and the artifact re-exports; `SessionManager`; the approval-helper re-exports such as `ApprovalManager`; the Core message and context type re-exports; the managed-session, work-session and attached-session helpers, which only the old Claude Code and Codex hosts used; and the remaining `CanonAgent` options (`deliveryMode`, `rtdbUrl`, `firebaseApiKey`, `runtimeControlSurface`, `sessionState`).