macp-sdk-typescript 0.2.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 (64) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/LICENSE +201 -0
  3. package/README.md +307 -0
  4. package/dist/agent/dispatcher.d.ts +16 -0
  5. package/dist/agent/dispatcher.js +61 -0
  6. package/dist/agent/index.d.ts +6 -0
  7. package/dist/agent/index.js +25 -0
  8. package/dist/agent/participant.d.ts +38 -0
  9. package/dist/agent/participant.js +221 -0
  10. package/dist/agent/runner.d.ts +18 -0
  11. package/dist/agent/runner.js +84 -0
  12. package/dist/agent/strategies.d.ts +40 -0
  13. package/dist/agent/strategies.js +106 -0
  14. package/dist/agent/transports.d.ts +35 -0
  15. package/dist/agent/transports.js +125 -0
  16. package/dist/agent/types.d.ts +72 -0
  17. package/dist/agent/types.js +2 -0
  18. package/dist/auth.d.ts +52 -0
  19. package/dist/auth.js +112 -0
  20. package/dist/client.d.ts +171 -0
  21. package/dist/client.js +384 -0
  22. package/dist/constants.d.ts +26 -0
  23. package/dist/constants.js +29 -0
  24. package/dist/decision.d.ts +65 -0
  25. package/dist/decision.js +148 -0
  26. package/dist/envelope.d.ts +50 -0
  27. package/dist/envelope.js +97 -0
  28. package/dist/errors.d.ts +44 -0
  29. package/dist/errors.js +114 -0
  30. package/dist/handoff.d.ts +73 -0
  31. package/dist/handoff.js +160 -0
  32. package/dist/index.d.ts +18 -0
  33. package/dist/index.js +57 -0
  34. package/dist/policy.d.ts +76 -0
  35. package/dist/policy.js +118 -0
  36. package/dist/projections/decision.d.ts +49 -0
  37. package/dist/projections/decision.js +132 -0
  38. package/dist/projections/handoff.d.ts +28 -0
  39. package/dist/projections/handoff.js +111 -0
  40. package/dist/projections/proposal.d.ts +40 -0
  41. package/dist/projections/proposal.js +123 -0
  42. package/dist/projections/quorum.d.ts +36 -0
  43. package/dist/projections/quorum.js +107 -0
  44. package/dist/projections/task.d.ts +54 -0
  45. package/dist/projections/task.js +127 -0
  46. package/dist/projections.d.ts +5 -0
  47. package/dist/projections.js +21 -0
  48. package/dist/proposal.d.ts +69 -0
  49. package/dist/proposal.js +155 -0
  50. package/dist/proto-registry.d.ts +12 -0
  51. package/dist/proto-registry.js +165 -0
  52. package/dist/quorum.d.ts +65 -0
  53. package/dist/quorum.js +144 -0
  54. package/dist/retry.d.ts +14 -0
  55. package/dist/retry.js +48 -0
  56. package/dist/task.d.ts +73 -0
  57. package/dist/task.js +166 -0
  58. package/dist/types.d.ts +263 -0
  59. package/dist/types.js +2 -0
  60. package/dist/validation.d.ts +17 -0
  61. package/dist/validation.js +92 -0
  62. package/dist/watchers.d.ts +47 -0
  63. package/dist/watchers.js +176 -0
  64. package/package.json +72 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,73 @@
1
+ # Changelog
2
+
3
+ All notable changes to `macp-sdk-typescript` are documented here. The format
4
+ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the
5
+ project uses [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+ - Warn-once migration hint when the deprecated `HandoffSession.sendContext()`
11
+ alias is invoked. Scheduled for removal in `0.4.0`; use `addContext()`.
12
+ - `docs/api/sessions.md` now documents the identity-guard contract.
13
+ - `docs/guides/architecture.md` rewritten to reflect the three-layer design
14
+ (transport / session helpers / agent framework).
15
+
16
+ ### Deprecated
17
+ - `HandoffSession.sendContext()` remains available as an alias but emits a
18
+ one-shot `console.warn`. Use `HandoffSession.addContext()` instead.
19
+
20
+ ## [0.2.0] — 2026-04-15
21
+
22
+ Direct-agent authentication (RFC-MACP-0004 §4) hardening. The SDK can now
23
+ represent and enforce the authenticated sender identity client-side, so agents
24
+ fail fast on identity bugs instead of discovering them as runtime NACKs. See
25
+ [`ui-console/plans/direct-agent-auth.md`](../ui-console/plans/direct-agent-auth.md)
26
+ for the cross-repo plan.
27
+
28
+ ### Added
29
+ - `MacpIdentityMismatchError` (exported from the package root). Raised when an
30
+ explicit `sender` passed to any mode helper or to
31
+ `client.sendSignal`/`client.sendProgress` conflicts with
32
+ `auth.expectedSender`.
33
+ - `Auth.bearer(token, { expectedSender })` — structured second argument that
34
+ binds the authenticated identity. The legacy string form
35
+ (`Auth.bearer(token, 'alice')`) still works and preserves pre-0.2 behaviour
36
+ (no guard).
37
+ - `AuthConfig.expectedSender` field.
38
+ - `assertSenderMatchesIdentity(auth, sender)` exported helper.
39
+ - `allowInsecure?: boolean` option on `MacpClient` — required when
40
+ `secure: false` is passed; constructor throws otherwise (RFC-MACP-0006 §3).
41
+ - Agent runner (`fromBootstrap`) now honours a bootstrap `allow_insecure`
42
+ flag and binds `expectedSender` to `participant_id` when `auth_token` is
43
+ present.
44
+ - `HandoffSession.addContext()` as the canonical name for the
45
+ `HandoffContext` message.
46
+ - Public `newSessionId()` export — already re-exported via `envelope.ts` but
47
+ now pinned by a test so it stays visible at the package root.
48
+ - Integration test block *Direct-agent auth (pre-allocated sessionId + Bearer)*
49
+ that exercises the full initiator loop (SessionStart → stream → Proposal) and
50
+ a second Bearer client for non-initiator Evaluate + Vote.
51
+ - `tests/integration/README.md` documenting the runtime + env-var matrix for
52
+ the new test block.
53
+
54
+ ### Changed
55
+ - `MacpClient.secure` now defaults to `true`. Insecure connections require
56
+ `secure: false` *and* `allowInsecure: true` at construction time.
57
+ - All example smokes (`examples/*.ts`) pass `allowInsecure: true` alongside
58
+ `secure: false` so local dev continues to work against
59
+ `MACP_ALLOW_INSECURE=1` runtimes.
60
+ - `clientVersion` default bumped to `'0.2.0'`.
61
+ - `authSender(auth)` now prefers `expectedSender` over `senderHint` /
62
+ `agentId` when resolving the envelope sender fallback.
63
+
64
+ ### Deprecated
65
+ - `HandoffSession.sendContext()` renamed to `addContext()`. The old name
66
+ remains as a backwards-compatible alias.
67
+
68
+ ## [0.1.0] — 2026-02-?? (historical)
69
+
70
+ Initial release. `MacpClient`, five mode-session helpers
71
+ (`DecisionSession`, `ProposalSession`, `TaskSession`, `HandoffSession`,
72
+ `QuorumSession`), local projections per mode, duplex streaming, policy
73
+ builders, and the `Participant`/`Dispatcher`/`Strategies` agent framework.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,307 @@
1
+ # macp-sdk-typescript
2
+
3
+ TypeScript SDK for the [Multi-Agent Coordination Protocol (MACP)](https://github.com/multiagentcoordinationprotocol/multiagentcoordinationprotocol) runtime. Connects TypeScript/Node.js applications to the Rust MACP runtime over gRPC.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install macp-sdk-typescript
9
+ ```
10
+
11
+ The SDK depends on `@multiagentcoordinationprotocol/proto` from GitHub Packages. Create a `.npmrc` in your project root:
12
+
13
+ ```
14
+ @multiagentcoordinationprotocol:registry=https://npm.pkg.github.com
15
+ ```
16
+
17
+ And configure a GitHub PAT with `read:packages` scope:
18
+
19
+ ```bash
20
+ npm config set //npm.pkg.github.com/:_authToken YOUR_GITHUB_PAT
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```typescript
26
+ import { Auth, MacpClient, DecisionSession } from 'macp-sdk-typescript';
27
+
28
+ const client = new MacpClient({
29
+ address: '127.0.0.1:50051',
30
+ secure: false,
31
+ allowInsecure: true, // local dev only; production must use TLS
32
+ auth: Auth.devAgent('coordinator'),
33
+ });
34
+
35
+ await client.initialize();
36
+
37
+ const session = new DecisionSession(client);
38
+ await session.start({
39
+ intent: 'pick a deployment strategy',
40
+ participants: ['alice', 'bob'],
41
+ ttlMs: 60_000,
42
+ });
43
+
44
+ await session.propose({ proposalId: 'p1', option: 'canary', rationale: 'low risk' });
45
+
46
+ await session.vote({
47
+ proposalId: 'p1',
48
+ vote: 'approve',
49
+ sender: 'alice',
50
+ auth: Auth.devAgent('alice'),
51
+ });
52
+
53
+ const winner = session.projection.majorityWinner();
54
+ await session.commit({
55
+ action: 'deployment.approved',
56
+ authorityScope: 'release',
57
+ reason: `winner=${winner}`,
58
+ });
59
+
60
+ client.close();
61
+ ```
62
+
63
+ ## Architecture
64
+
65
+ The SDK uses a **two-layer** design:
66
+
67
+ - **Low-level transport** (`MacpClient`): gRPC connection to the runtime with all 14 RPCs — `initialize`, `send`, `openStream`, `getSession`, `cancelSession`, `getManifest`, `listModes`, `listRoots`, `listExtModes`, `registerExtMode`, `unregisterExtMode`, `promoteMode`, plus streaming watchers.
68
+ - **High-level session helpers**: One class per coordination mode (`DecisionSession`, `ProposalSession`, `TaskSession`, `HandoffSession`, `QuorumSession`). Each wraps `MacpClient`, builds envelopes, encodes payloads, and maintains a local state projection.
69
+
70
+ Every session class follows the same pattern:
71
+ 1. Construct with a `MacpClient` and options
72
+ 2. Call `start()` to initiate the session
73
+ 3. Call mode-specific methods (propose, vote, accept, etc.)
74
+ 4. Call `commit()` to finalize
75
+ 5. Read `session.projection` for local state
76
+
77
+ ## Coordination Modes
78
+
79
+ ### Decision Mode
80
+
81
+ Structured decision with proposals, evaluations, objections, and votes.
82
+
83
+ ```typescript
84
+ import { DecisionSession } from 'macp-sdk-typescript';
85
+
86
+ const session = new DecisionSession(client);
87
+ await session.start({ intent: '...', participants: ['alice'], ttlMs: 60_000 });
88
+ await session.propose({ proposalId: 'p1', option: 'A', rationale: '...' });
89
+ await session.evaluate({ proposalId: 'p1', recommendation: 'approve', confidence: 0.9 });
90
+ await session.raiseObjection({ proposalId: 'p1', reason: 'risk', severity: 'high' });
91
+ await session.vote({ proposalId: 'p1', vote: 'approve' });
92
+ await session.commit({ action: 'decided', authorityScope: 'team', reason: '...' });
93
+
94
+ // Projection queries
95
+ session.projection.voteTotals(); // { p1: 1 }
96
+ session.projection.majorityWinner(); // 'p1'
97
+ session.projection.hasBlockingObjection('p1'); // true (severity: high)
98
+ ```
99
+
100
+ ### Proposal Mode
101
+
102
+ Proposal and counterproposal negotiation.
103
+
104
+ ```typescript
105
+ import { ProposalSession } from 'macp-sdk-typescript';
106
+
107
+ const session = new ProposalSession(client);
108
+ await session.start({ intent: '...', participants: ['bob'], ttlMs: 60_000 });
109
+ await session.propose({ proposalId: 'p1', title: 'Plan A', summary: '...' });
110
+ await session.counterPropose({ proposalId: 'p2', supersedesProposalId: 'p1', title: 'Plan B' });
111
+ await session.accept({ proposalId: 'p2', reason: 'better' });
112
+ await session.commit({ action: 'proposal.accepted', authorityScope: 'team', reason: '...' });
113
+
114
+ // Projection queries
115
+ session.projection.activeProposals(); // proposals with status 'open'
116
+ session.projection.isAccepted('p2'); // true
117
+ session.projection.isTerminallyRejected('p1'); // false
118
+ ```
119
+
120
+ ### Task Mode
121
+
122
+ Bounded task delegation.
123
+
124
+ ```typescript
125
+ import { TaskSession } from 'macp-sdk-typescript';
126
+
127
+ const session = new TaskSession(client);
128
+ await session.start({ intent: '...', participants: ['worker'], ttlMs: 120_000 });
129
+ await session.request({ taskId: 't1', title: 'Build feature', instructions: '...' });
130
+ await session.acceptTask({ taskId: 't1', assignee: 'worker' });
131
+ await session.update({ taskId: 't1', status: 'working', progress: 0.5, message: 'halfway' });
132
+ await session.complete({ taskId: 't1', assignee: 'worker', summary: 'done' });
133
+ await session.commit({ action: 'task.completed', authorityScope: 'lead', reason: '...' });
134
+
135
+ // Projection queries
136
+ session.projection.progressOf('t1'); // 1.0
137
+ session.projection.isComplete('t1'); // true
138
+ session.projection.activeTasks(); // []
139
+ ```
140
+
141
+ ### Handoff Mode
142
+
143
+ Responsibility transfer between participants.
144
+
145
+ ```typescript
146
+ import { HandoffSession } from 'macp-sdk-typescript';
147
+
148
+ const session = new HandoffSession(client);
149
+ await session.start({ intent: '...', participants: ['bob'], ttlMs: 60_000 });
150
+ await session.offer({ handoffId: 'h1', targetParticipant: 'bob', scope: 'frontend' });
151
+ await session.addContext({ handoffId: 'h1', contentType: 'application/json', context: buf });
152
+ await session.acceptHandoff({ handoffId: 'h1', acceptedBy: 'bob' });
153
+ await session.commit({ action: 'handoff.accepted', authorityScope: 'team', reason: '...' });
154
+
155
+ // Projection queries
156
+ session.projection.isAccepted('h1'); // true
157
+ session.projection.pendingHandoffs(); // []
158
+ ```
159
+
160
+ ### Quorum Mode
161
+
162
+ Threshold-based approval voting.
163
+
164
+ ```typescript
165
+ import { QuorumSession } from 'macp-sdk-typescript';
166
+
167
+ const session = new QuorumSession(client);
168
+ await session.start({ intent: '...', participants: ['alice', 'bob', 'carol'], ttlMs: 60_000 });
169
+ await session.requestApproval({ requestId: 'r1', action: 'deploy', summary: '...', requiredApprovals: 2 });
170
+ await session.approve({ requestId: 'r1', reason: 'ok' });
171
+ await session.commit({ action: 'quorum.approved', authorityScope: 'ops', reason: '...' });
172
+
173
+ // Projection queries
174
+ session.projection.hasQuorum('r1'); // true/false
175
+ session.projection.approvalCount('r1'); // number
176
+ session.projection.remainingVotesNeeded('r1'); // number
177
+ session.projection.votedSenders('r1'); // string[]
178
+ ```
179
+
180
+ ## Authentication
181
+
182
+ ```typescript
183
+ // Development (uses x-macp-agent-id header)
184
+ const auth = Auth.devAgent('my-agent');
185
+
186
+ // Production (Bearer token with authenticated identity — RFC-MACP-0004 §4).
187
+ // The SDK refuses to emit an envelope whose `sender` differs from
188
+ // `expectedSender`, so bugs surface locally instead of as runtime NACKs.
189
+ const auth = Auth.bearer('token-value', { expectedSender: 'alice' });
190
+
191
+ // Legacy form — bearer with only a sender hint, no identity guard:
192
+ const loose = Auth.bearer('token-value', 'alice');
193
+ ```
194
+
195
+ Pass `auth` to the client constructor for default auth, or per-method for multi-agent scenarios:
196
+
197
+ ```typescript
198
+ await session.vote({
199
+ proposalId: 'p1',
200
+ vote: 'approve',
201
+ sender: 'alice',
202
+ auth: Auth.devAgent('alice'),
203
+ });
204
+ ```
205
+
206
+ ## TLS
207
+
208
+ TLS is on by default (RFC-MACP-0006 §3). To connect to an insecure runtime
209
+ during local development, you must opt out explicitly:
210
+
211
+ ```typescript
212
+ const client = new MacpClient({
213
+ address: '127.0.0.1:50051',
214
+ secure: false,
215
+ allowInsecure: true, // must be paired with secure: false
216
+ auth,
217
+ });
218
+ ```
219
+
220
+ Omit `allowInsecure` in production — the constructor throws when `secure: false` is passed without it.
221
+
222
+ ## Streaming
223
+
224
+ ### Session Streaming
225
+
226
+ ```typescript
227
+ const stream = client.openStream({ auth });
228
+ await stream.send(envelope);
229
+
230
+ for await (const envelope of stream.responses()) {
231
+ console.log(envelope.messageType, envelope.sender);
232
+ }
233
+
234
+ stream.close();
235
+ ```
236
+
237
+ ### Registry & Root Watchers
238
+
239
+ ```typescript
240
+ import { ModeRegistryWatcher, RootsWatcher } from 'macp-sdk-typescript';
241
+
242
+ const watcher = new ModeRegistryWatcher(client, { auth });
243
+
244
+ // Async iterator with abort support
245
+ const controller = new AbortController();
246
+ for await (const change of watcher.changes(controller.signal)) {
247
+ console.log('registry changed at', change.observedAtUnixMs);
248
+ }
249
+
250
+ // Or one-shot
251
+ const next = await watcher.nextChange();
252
+ ```
253
+
254
+ ## Error Handling
255
+
256
+ ```typescript
257
+ import { MacpAckError, MacpTransportError } from 'macp-sdk-typescript';
258
+
259
+ try {
260
+ await session.vote({ proposalId: 'p1', vote: 'approve' });
261
+ } catch (err) {
262
+ if (err instanceof MacpAckError) {
263
+ console.log(err.ack.error?.code); // 'SESSION_NOT_OPEN', etc.
264
+ } else if (err instanceof MacpTransportError) {
265
+ console.log('gRPC connectivity issue');
266
+ }
267
+ }
268
+ ```
269
+
270
+ ## Development
271
+
272
+ ```bash
273
+ npm run build # Compile TypeScript
274
+ npm run check # Type-check only
275
+ npm run lint # ESLint
276
+ npm run format # Prettier
277
+ npm test # Run unit + conformance tests
278
+ npm run test:watch # Watch mode
279
+ npm run test:coverage # With coverage
280
+ npm run test:integration # Integration tests (requires Docker runtime)
281
+ ```
282
+
283
+ ### Integration Tests
284
+
285
+ Run the full SDK against a live MACP runtime:
286
+
287
+ ```bash
288
+ # Build and start the runtime
289
+ docker build -t macp-runtime ../runtime/
290
+ docker run -d --name macp-runtime-test -p 50051:50051 \
291
+ -e MACP_BIND_ADDR=0.0.0.0:50051 -e MACP_ALLOW_INSECURE=1 \
292
+ -e MACP_ALLOW_DEV_SENDER_HEADER=1 -e MACP_MEMORY_ONLY=1 macp-runtime
293
+
294
+ # Run tests
295
+ npm run test:integration
296
+
297
+ # Clean up
298
+ docker rm -f macp-runtime-test
299
+ ```
300
+
301
+ ## Runtime Boundary
302
+
303
+ This SDK is a **client** for the MACP Rust runtime. The runtime handles session state, message ordering, deduplication, TTL enforcement, and mode-specific validation. The SDK provides typed helpers for building and sending envelopes, and local projections for tracking state client-side.
304
+
305
+ ## License
306
+
307
+ Apache-2.0
@@ -0,0 +1,16 @@
1
+ import type { HandlerContext, IncomingMessage, MessageHandler, PhaseChangeHandler, TerminalHandler, TerminalResult } from './types';
2
+ export declare class Dispatcher {
3
+ private handlers;
4
+ private wildcardHandlers;
5
+ private phaseHandlers;
6
+ private wildcardPhaseHandlers;
7
+ private terminalHandler?;
8
+ on(messageType: string, handler: MessageHandler): void;
9
+ onPhaseChange(phase: string, handler: PhaseChangeHandler): void;
10
+ onTerminal(handler: TerminalHandler): void;
11
+ dispatch(message: IncomingMessage, ctx: HandlerContext): Promise<void>;
12
+ dispatchPhaseChange(newPhase: string, ctx: HandlerContext): Promise<void>;
13
+ dispatchTerminal(result: TerminalResult): Promise<void>;
14
+ hasHandlersFor(messageType: string): boolean;
15
+ hasTerminalHandler(): boolean;
16
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Dispatcher = void 0;
4
+ class Dispatcher {
5
+ handlers = new Map();
6
+ wildcardHandlers = [];
7
+ phaseHandlers = new Map();
8
+ wildcardPhaseHandlers = [];
9
+ terminalHandler;
10
+ on(messageType, handler) {
11
+ if (messageType === '*') {
12
+ this.wildcardHandlers.push(handler);
13
+ return;
14
+ }
15
+ const existing = this.handlers.get(messageType) ?? [];
16
+ existing.push(handler);
17
+ this.handlers.set(messageType, existing);
18
+ }
19
+ onPhaseChange(phase, handler) {
20
+ if (phase === '*') {
21
+ this.wildcardPhaseHandlers.push(handler);
22
+ return;
23
+ }
24
+ const existing = this.phaseHandlers.get(phase) ?? [];
25
+ existing.push(handler);
26
+ this.phaseHandlers.set(phase, existing);
27
+ }
28
+ onTerminal(handler) {
29
+ this.terminalHandler = handler;
30
+ }
31
+ async dispatch(message, ctx) {
32
+ const specific = this.handlers.get(message.messageType) ?? [];
33
+ for (const handler of specific) {
34
+ await handler(message, ctx);
35
+ }
36
+ for (const handler of this.wildcardHandlers) {
37
+ await handler(message, ctx);
38
+ }
39
+ }
40
+ async dispatchPhaseChange(newPhase, ctx) {
41
+ const specific = this.phaseHandlers.get(newPhase) ?? [];
42
+ for (const handler of specific) {
43
+ await handler(newPhase, ctx);
44
+ }
45
+ for (const handler of this.wildcardPhaseHandlers) {
46
+ await handler(newPhase, ctx);
47
+ }
48
+ }
49
+ async dispatchTerminal(result) {
50
+ if (this.terminalHandler) {
51
+ await this.terminalHandler(result);
52
+ }
53
+ }
54
+ hasHandlersFor(messageType) {
55
+ return (this.handlers.get(messageType)?.length ?? 0) > 0 || this.wildcardHandlers.length > 0;
56
+ }
57
+ hasTerminalHandler() {
58
+ return this.terminalHandler !== undefined;
59
+ }
60
+ }
61
+ exports.Dispatcher = Dispatcher;
@@ -0,0 +1,6 @@
1
+ export * from './types';
2
+ export * from './dispatcher';
3
+ export * from './participant';
4
+ export * from './strategies';
5
+ export * from './runner';
6
+ export { GrpcTransportAdapter, HttpTransportAdapter, type TransportAdapter, type HttpPollingConfig, } from './transports';