@m-cpy/pi-a2a-inbox 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@m-cpy/pi-a2a-inbox` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/); versions match `package.json`.
5
+
6
+ ## [0.5.1] - 2026-12-04
7
+
8
+ ### Changed
9
+ - Busy-session reminders now use **steer** (mid-turn injection at the next tool boundary) instead of a fire-and-forget notice: visible within the current turn without interrupting it or spawning an extra empty turn.
10
+ - Busy-session reminder text is a generic trigger (`[a2a] 消息盒有新消息 → a2a_inbox_list`) carrying no peer/count snapshot, so it never goes stale while queued; idle wake reminders keep the sender/count form.
11
+
12
+ ### Fixed
13
+ - **Duplicate reminders**: the watchdog no longer escalates a reminder the host has reliably accepted (`hostQueued`) while it waits to drain — previously a long tool call (>60s) made the watchdog assume the reminder was lost and add a second follow-up. Failed wakes still retry; a genuinely stuck queue is surfaced by the STALLED alert (ops-facing), not by re-injecting into the session.
14
+ - `typecheck.sh` resolves a real `tsc` (local / require.resolve / host) and fails honestly when absent, instead of `npx` silently resolving a placeholder package and reporting a false pass.
15
+
16
+ ### Notes
17
+ - Reminder effect constraints (no drop when busy, no empty turn, no stale snapshot, no accumulation) are protocol §5; the delivery primitive (steer / follow-up / queued wake) is implementation-specific.
18
+
19
+ ## [0.5.0] - 2026-12-03
20
+
21
+ First public release.
22
+
23
+ ### Added
24
+ - A2A v1.0 envelope + private inbox extension (`https://a2a-inbox.local/ext/a2a-inbox/v1`, `required: true`): session-addressed inbox with four-state messages (pending / consuming / done / suspended).
25
+ - Seven tools: `a2a_peers`, `a2a_sessions`, `a2a_send`, `a2a_inbox_list`, `a2a_inbox_fetch`, `a2a_reply`, `a2a_inbox_drop`.
26
+ - Per-peer Bearer identity; static URL peers (no discovery daemon). Self-reported names never participate in routing.
27
+ - Credential uniqueness rule: one inbound credential mapping to more than one peer is always rejected (HTTP 401 / `-32041`), enforced at save, load, and runtime.
28
+ - Retention with two-level eviction: `pending` > 24h → `suspended(expired)` (reversible); `suspended` > 72h → purged; `done` > 24h → trimmed. Participation ledger decoupled from message rows so trimming never retracts the disclosure surface.
29
+ - Delivery-receipt semantics (`delivered` = entered the inbox), explicit reply, honest wake (at most 3 real deliveries per batch, then stop or suspend).
30
+ - Observability: persistent counters, periodic self-probe, watchdog, effective-config logging with source.
31
+ - Bundled skill (`pi-a2a-inbox`) and slash commands (`/a2a-status`, `/a2a-restart`, `/a2a-setup`).
32
+
33
+ ### Notes
34
+ - Pure-standard A2A clients that omit the extension metadata are rejected (`-32009`); the fallback surface is not opened by design.
35
+ - Host-provided packages (`@earendil-works/pi-coding-agent`, `typebox`) are declared as `peerDependencies` and are not bundled.
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 2026 Mcpy
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/NOTICE ADDED
@@ -0,0 +1,27 @@
1
+ pi-a2a-inbox
2
+ Copyright 2026 Mcpy
3
+
4
+ Derived from pi-a2a by Victor Software House. That work is distributed under
5
+ the MIT License, and its notice is retained here as required by Apache-2.0 §4(d):
6
+
7
+ MIT License
8
+
9
+ Copyright (c) 2026 Victor Software House
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ # pi-a2a-inbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Agent-to-agent (A2A) peer collaboration for pi — **static URL peers, per-peer Bearer identity, inbox semantics**. Built on the standard [A2A v1.0](https://a2aproject.github.io/A2A/) envelope plus a private inbox extension. No mDNS, no shared-trust secret, no outbox.
4
+
5
+ `@m-cpy/pi-a2a-inbox` lets pi talk to named peers (e.g. `reviewer`, `backend`). Messages are organized **per peer session**; inbound always lands in the inbox as `pending`, and replying is an explicit action.
6
+
7
+ ## What It Does
8
+
9
+ - 📨 **Send messages** — start a conversation, ask a question, share a code snippet
10
+ - 💬 **Explicit replies** — `a2a_reply` answers an inbox message in the sender's session
11
+ - 📥 **Inbox four-state** — `pending → consuming → done`, plus `suspended` for stuck messages
12
+ - 👥 **Peers + sessions** — `a2a_peers` lists configured peers; `a2a_sessions` lists the sessions you've exchanged with a peer
13
+ - 🔔 **Honest wake** — a nudge wakes the agent only on real delivery; at most 3 attempts per batch, then stop or suspend
14
+
15
+ This is a direct agent-to-agent channel, not human chat or a shared blackboard.
16
+
17
+ ## Architecture
18
+
19
+ Standard **A2A v1.0** (JSON-RPC 2.0 over HTTP) envelope + a private inbox extension:
20
+
21
+ - Extension URI: `https://a2a-inbox.local/ext/a2a-inbox/v1`, declared in the Agent Card with `required: true`.
22
+ - A pure-standard A2A client that omits the extension metadata is rejected with `-32009` (by design — the fallback surface is not opened).
23
+
24
+ ```
25
+ static URL peers (no discovery daemon)
26
+ ┌──────────────┐ HTTPS/HTTP ┌──────────────┐
27
+ │ pi │ JSON-RPC │ reviewer │
28
+ │ Agent Card │ ◄────────────► │ Agent Card │
29
+ │ POST /rpc │ SendMessage │ POST /rpc │
30
+ │ inbox (JSON) │ + ext meta │ inbox (JSON) │
31
+ └──────────────┘ └──────────────┘
32
+ ```
33
+
34
+ - **Discovery** — none. Peers are configured statically by Agent Card URL (`peers[]`). The card is fetched at startup to resolve the RPC endpoint.
35
+ - **Identity** — **per-peer Bearer token**. Outbound uses the token the peer issued for you (the one that identifies you as you); inbound resolves the peer name by matching the token against each peer's `inboundToken` (fallback `bearer`). A self-reported name never participates in routing.
36
+ - **Single writer** — the process that owns the listen port runs the inbox; other processes degrade to client-only and route inbox ops to the owner over RPC.
37
+ - **Storage** — one local JSON file (`.pi/a2a-messages.json`): messages, dedup, nudges, counters, and a participation ledger (decoupled from message rows so trimming history never retracts disclosure).
38
+
39
+ ### Trust model
40
+
41
+ - The shared `workspaceSecret` is only an **anonymous entry** (`_shared`); it does **not** produce a peer identity.
42
+ - Real communication uses **per-peer dedicated tokens**. One credential must map to exactly one peer.
43
+ - **B rule (I6):** if one inbound credential maps to **more than one** peer, requests carrying it are **always 401 + -32041** — not first-wins, not "log and accept". Enforced at save (reject), load (warn naming both peers), and runtime (401).
44
+ - Bind is LAN-oriented; for cross-internet use put agents behind a VPN.
45
+
46
+ ## Install
47
+
48
+ pi loads this as a **package**. From npm (published):
49
+
50
+ ```bash
51
+ pi install npm:@m-cpy/pi-a2a-inbox
52
+ ```
53
+
54
+ It also appears in the [Pi package gallery](https://pi.dev/packages). The package bundles the extension (`./extensions`) and a skill (`./skills/pi-a2a-inbox`). No native dependency, no mDNS daemon; host packages (`@earendil-works/pi-coding-agent`, `typebox`) are provided by pi.
55
+
56
+ Or install from the public monorepo source:
57
+
58
+ ```bash
59
+ git clone https://github.com/Mcpy/a2a-inbox
60
+ pi install ./a2a-inbox/pi-a2a-inbox
61
+ ```
62
+
63
+ (Or add the path to `~/.pi/agent/settings.json` `packages`.)
64
+
65
+ ## Configure
66
+
67
+ Config is per-project: `.pi/pi-a2a.json`.
68
+
69
+ ```json
70
+ {
71
+ "workspace": "my-team",
72
+ "workspaceSecret": "anonymous-entry-pass",
73
+ "peerName": "pi",
74
+ "listenPort": 0,
75
+ "peers": [
76
+ {
77
+ "name": "reviewer",
78
+ "url": "http://peer-host:8080/.well-known/agent-card.json",
79
+ "bearer": "outbound-token-the-peer-issued-for-me",
80
+ "inboundToken": "inbound-token-the-peer-carries-when-calling-me"
81
+ }
82
+ ]
83
+ }
84
+ ```
85
+
86
+ | Field | Meaning |
87
+ |-------|---------|
88
+ | `workspace` | Workspace label |
89
+ | `workspaceSecret` | Anonymous entry secret (`_shared`, no peer identity); communication needs `peers[]` |
90
+ | `peerName` | This agent's name |
91
+ | `listenPort` | Local HTTP port (`0` = OS-assigned) |
92
+ | `advertiseHost` | Optional outbound advertise host (multi-NIC/Docker/WSL) |
93
+ | `agentCardPath` / `rpcPath` | Card / RPC paths (defaults `/.well-known/agent-card.json`, `/rpc`) |
94
+ | `peers[]` | Static peers, one row per relationship: `name`, `url` (card), `bearer` (outbound), `inboundToken` (inbound, fallback `bearer`) |
95
+
96
+ `inboundToken` omitted = symmetric reuse of `bearer` (one dedicated pair may explicitly reuse one token; leakage is then bidirectional). Environment references supported: `"bearer": "$PEER_TOKEN"`.
97
+
98
+ ### Slash commands
99
+
100
+ | Command | Description |
101
+ |---------|-------------|
102
+ | `/a2a-status` | Engine status (config path, port, running sessions, peers) |
103
+ | `/a2a-restart` | Restart the engine (guards against busy sessions) |
104
+ | `/a2a-setup <secret> [name]` | Set engine basics (secret = anonymous entry) |
105
+ | `/a2a-setup peer <name> <cardUrl> <outToken> [inToken]` | Add/update a peer row (per-peer Bearer) |
106
+ | `/a2a-setup peers` | List peer rows (token tails, direction) |
107
+ | `/a2a-setup del-peer <name>` | Remove a peer row |
108
+
109
+ ## Tools (7)
110
+
111
+ | Tool | Description |
112
+ |------|-------------|
113
+ | `a2a_peers` | List configured peers + online status |
114
+ | `a2a_sessions` | List a peer's sessions (sessionId/title/status/pending); never guess a sessionId |
115
+ | `a2a_send` | Send. `peer` required; continue with `sessionId`, new session requires explicit `newSession:true` |
116
+ | `a2a_inbox_list` | This session's inbox overview (counts/sender/topic/mustReply), no bodies |
117
+ | `a2a_inbox_fetch` | Fetch body (→ consuming). `mustReply:true` must be answered with `a2a_reply` in the same turn |
118
+ | `a2a_reply` | Reply to an inbox message (recipient auto = original sender). New topics use `a2a_send` |
119
+ | `a2a_inbox_drop` | Destroy a **suspended** message (only on explicit user instruction) |
120
+
121
+ ### Routing rules (v3)
122
+
123
+ - `contextId` = the peer's session id: empty → new; non-empty but unknown → `-32040` (never silently creates a session; the error does not echo the caller's id).
124
+ - `metadata.senderSessionId` is required (full session id); reply routing depends on it.
125
+ - Disclosure A+: `a2a_sessions` lists only sessions exchanged with that peer, labeled by the latest topic the peer already knows; invisible sessions never echo their id.
126
+
127
+ ## Retention
128
+
129
+ | State | Age basis | Rule |
130
+ |-------|-----------|------|
131
+ | `pending` > 24h | `receivedAt` | → `suspended(expired)` (reversible) |
132
+ | `suspended` > 72h | `suspendedAt` | → deleted (`purged`) |
133
+ | `done` > 24h | `doneAt` | → trimmed (`trimmed`) |
134
+
135
+ Suspended reasons: `no-reply-3x` / `reply-failed-3x` / `session-gone` / `expired`. Deletion event lines carry the messageId list (audit). Participation facts are stored independently, so trimming `done` rows never retracts the disclosure surface.
136
+
137
+ ## Error codes
138
+
139
+ | Code | Meaning |
140
+ |------|---------|
141
+ | `-32040` | Unknown session (never creates) |
142
+ | `-32041` | Unauthorized (HTTP 401; includes ambiguous credential per B rule) |
143
+ | `-32042` | Peer unreachable (connect failure / timeout) |
144
+ | `-32043` | Same id, different body |
145
+ | `-32044` | Box full (cap 1000) |
146
+ | `-32045` | Message not pending (already consumed / suspended / done) |
147
+ | `-32046` | Message is suspended (fetch it back before replying) |
148
+ | `-32047` | Message already answered (use `a2a_send` to continue) |
149
+ | `-32048` | Session archived on the peer (exists, takes no new messages) |
150
+ | `-32009` | Extension not activated (URI mismatch / pure-standard client) |
151
+ | `-32602` | Invalid params (body > 32768, missing senderSessionId, …) |
152
+
153
+ pi has **no archive concept**: it never emits `archived` and never answers `-32048`. It is a
154
+ *consumer* of that code — the client keeps it distinct from `-32040` (retry with another id) and
155
+ `-32042` (peer down, back off), because those three demand opposite reactions. `m11` asserts all
156
+ codes stay unique and that `-32048` is never claimed by another name.
157
+
158
+ ## Delivery semantics (delivered ≠ woke)
159
+
160
+ The wire receipt `delivered:true` means **the message entered the inbox** ("received"), per PROTOCOL-v3 §9.2 — it is constant on successful receive, independent of whether the agent was woken. Wake failure never makes it false; a receive failure throws an error code instead. This semantics is aligned across implementations.
161
+
162
+ Wake state is tracked separately (internal nudge budget: at most 3 real deliveries per batch). A future `wakeState: yes|queued|no` field may expose wake progress **for reminders only** — it must never trigger body re-send (that would turn "will wake later" into "not delivered" and cause duplicate delivery).
163
+
164
+ ## Observability
165
+
166
+ Counters: `recv/dup/returned/wakeQueued/wakeFail/susp.*/lastInbound/lastClaim/lastWakeOk/rejects{noToken,unknownToken,ambiguousToken}/selfProbes/purged/trimmed`. A periodic self-probe (120s) detects a deaf sidecar; a watchdog (60s) drives reminder cooldown and stall detection. Effective config is logged at startup with its source.
167
+
168
+ ## Tests
169
+
170
+ ```bash
171
+ bash scripts/run-v3-tests.sh # m2 sessions / m10 inbox / m11 envelope / m13 single-writer / m14 wake honesty / m15 crash recovery
172
+ bash scripts/typecheck.sh
173
+ ```
174
+
175
+ ## Docs
176
+
177
+ Protocol and design documents are maintained internally by the team and are **not shipped with this package**. The code (including its comments) is the only public contract here.
@@ -0,0 +1,20 @@
1
+ {
2
+ "workspace": "my-team",
3
+ "workspaceSecret": "anonymous-entry-passphrase",
4
+ "agentId": "",
5
+ "peerName": "pi",
6
+ "role": "what this agent does (optional)",
7
+ "listenPort": 0,
8
+ "_a2a_comment": "v3 静态 URL peer + per-peer Bearer。workspaceSecret 只是匿名入口(_shared),不产生 peer 身份;通信靠 peers[] 专属 token。以下可选字段省略即用默认值。",
9
+ "agentCardPath": "/.well-known/agent-card.json",
10
+ "rpcPath": "/rpc",
11
+ "advertiseHost": "",
12
+ "peers": [
13
+ {
14
+ "name": "reviewer",
15
+ "url": "http://peer-host:8080/.well-known/agent-card.json",
16
+ "bearer": "出站token(对方会把我认成我的那把)",
17
+ "inboundToken": "入站token(对方调我方时携带;省略回退 bearer=对称复用)"
18
+ }
19
+ ]
20
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * pi-a2a-inbox — 配置读写(v3 / 静态 URL peer + per-peer Bearer)
3
+ *
4
+ * 配置形状:
5
+ * {
6
+ * "workspace": "my-team", // 工作区名(标识用)
7
+ * "workspaceSecret": "shared-pass", // 匿名入口密钥(_shared,不产生 peer 身份;通信靠 peers[] 专属 token)
8
+ * "agentId": "<auto>", // 首次自动生成并持久化
9
+ * "peerName": "pi",
10
+ * "role": "writes the API",
11
+ * "listenPort": 0, // 可选,0 = OS 分配(多进程单写者需固定端口,见下)
12
+ * "advertiseHost": "<host>", // 可选,手动指定对外广告 host(多网卡/Docker/WSL 自动检测错误时用)
13
+ * "agentCardPath": "/.well-known/agent-card.json",
14
+ * "rpcPath": "/rpc", // JSON-RPC 单端点
15
+ * "peers": [ // 静态 peer:URL 直连,一行一关系,per-peer Bearer
16
+ * { "name": "reviewer", "url": "http://peer-host:8080/.well-known/agent-card.json",
17
+ * "bearer": "出站token(对方认我的那把)", "inboundToken": "入站token(对方调我携带,省略回退bearer)" }
18
+ * ]
19
+ * }
20
+ *
21
+ * 配置优先级:项目级 (.pi/pi-a2a.json) > 全局 (~/.pi/agent/pi-a2a.json)
22
+ * v2 的 mDNS 发现 / push-notification / gossip 字段已删(无消费方)。
23
+ */
24
+ import * as fs from "node:fs";
25
+ import * as path from "node:path";
26
+ import * as os from "node:os";
27
+ import * as crypto from "node:crypto";
28
+
29
+ export interface StaticPeerConfig {
30
+ name: string; // 本地寻址名(a2a_send 的 peer)
31
+ url: string; // 对端 AgentCard URL(启动时读取,解析 RPC endpoint)
32
+ bearer?: string; // 出站 Bearer(我方调对方时用;省略则用 workspaceSecret)
33
+ inboundToken?: string; // 入站身份 token(对方调我方时携带;peerByAuth 据此认 peer;省略回退 bearer)
34
+ }
35
+
36
+ export interface A2aConfig {
37
+ workspace: string; // 工作区名(标识用)
38
+ workspaceSecret: string; // 匿名入口密钥(_shared,不产生 peer 身份;通信靠 peers[] 专属 token)
39
+ agentId: string; // 首次自动生成并持久化
40
+ peerName: string;
41
+ role?: string;
42
+ listenPort?: number; // 可选,0 = OS 分配(默认 0)
43
+ advertiseHost?: string; // 可选,手动指定对外广告 host(agent card URL 用);多网卡/Docker/WSL 环境自动检测到虚拟网卡时用此项覆盖
44
+ // ── A2A 端点(均可选,有默认)──────────────────────
45
+ agentCardPath?: string; // 默认 /.well-known/agent-card.json
46
+ rpcPath?: string; // 默认 /rpc(JSON-RPC 单端点)
47
+ peers?: StaticPeerConfig[]; // 静态 peer:URL 直连,一行一关系,per-peer Bearer(重名时静态优先)
48
+ }
49
+
50
+ // 占位符:表示 agentId 尚未真正生成(如 config.example.json 里的空串)
51
+ const AGENTID_PLACEHOLDERS = new Set(["", "auto-generated-on-first-use", "auto-generated"]);
52
+
53
+ /**
54
+ * 配置/数据库都绑定到项目级 .pi/ 目录。
55
+ * 设计:不做全局 fallback。这样不同目录各自有独立配置(独立 agentId),
56
+ * 不同项目即使 peerName 重名(都叫 FE)也能通过 workspace + secret 经全局
57
+ * presence 目录(~/.pi/agent/pi-a2a-presence/)互相发现并通信,
58
+ * 而不会因共用全局配置导致 agentId 混淆/双实例。
59
+ */
60
+ export function configPath(cwd: string): string {
61
+ return path.join(cwd, ".pi", "pi-a2a.json");
62
+ }
63
+
64
+ /** 本地数据库(JSON 文件)路径:与 config 同目录。 */
65
+ export function dbPathFor(cwd: string): string {
66
+ return path.join(cwd, ".pi", "pi-a2a.db.json");
67
+ }
68
+
69
+ /** 展开 $VAR / ${VAR} 形式的环境变量引用。 */
70
+ export function expandEnv(s: string): string {
71
+ return s.replace(/\$\{?([A-Z_][A-Z0-9_]*)\}?/g, (_, v) => process.env[v] ?? `$${v}`);
72
+ }
73
+
74
+ /** 生成稳定的 agentId(16 位 hex)。 */
75
+ export function genAgentId(): string {
76
+ return crypto
77
+ .createHash("sha256")
78
+ .update(
79
+ `${os.hostname()}:${process.pid}:${Date.now()}:${crypto.randomBytes(8).toString("hex")}`,
80
+ )
81
+ .digest("hex")
82
+ .slice(0, 16);
83
+ }
84
+
85
+ export interface LoadedConfig {
86
+ config: A2aConfig;
87
+ path: string;
88
+ }
89
+
90
+ /** 读取项目级配置(<cwd>/.pi/pi-a2a.json)。首次使用时自动补全 agentId 并回写。 */
91
+ export function loadConfig(cwd: string): LoadedConfig | null {
92
+ const p = configPath(cwd);
93
+ if (!fs.existsSync(p)) return null;
94
+ try {
95
+ const raw = JSON.parse(fs.readFileSync(p, "utf8"));
96
+ // 新形状校验:必须有 workspace + workspaceSecret + peerName
97
+ if (raw && raw.workspace && raw.workspaceSecret && raw.peerName) {
98
+ raw.workspace = expandEnv(String(raw.workspace));
99
+ raw.workspaceSecret = expandEnv(String(raw.workspaceSecret));
100
+ if (Array.isArray(raw.peers)) {
101
+ raw.peers = raw.peers
102
+ .filter((p: any) => p && p.name && p.url)
103
+ .map((p: any) => ({
104
+ name: String(p.name),
105
+ url: expandEnv(String(p.url)),
106
+ ...(p.bearer ? { bearer: expandEnv(String(p.bearer)) } : {}),
107
+ ...(p.inboundToken ? { inboundToken: expandEnv(String(p.inboundToken)) } : {}),
108
+ }));
109
+ }
110
+ if (!raw.agentId || AGENTID_PLACEHOLDERS.has(raw.agentId)) {
111
+ raw.agentId = genAgentId();
112
+ try {
113
+ fs.writeFileSync(p, JSON.stringify(raw, null, 2) + "\n");
114
+ } catch {
115
+ /* 写失败则用内存 id,本会话仍可用 */
116
+ }
117
+ }
118
+ return { config: raw as A2aConfig, path: p };
119
+ }
120
+ } catch {
121
+ /* 忽略损坏文件 */
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /** B 规则三层之一(保存时拒绝)+ I4:peers[] 名字唯一、入站凭据唯一、cardUrl 地址唯一。冲突抛错,不落盘。 */
127
+ export function validatePeers(peers: StaticPeerConfig[] | undefined): void {
128
+ const list = peers ?? [];
129
+ const byTok = new Map<string, string[]>(); const byUrl = new Map<string, string[]>(); const names = new Set<string>();
130
+ for (const p of list) {
131
+ if (!p?.name) continue;
132
+ if (names.has(p.name)) throw new Error(`peer 名重复:${p.name}(一行一关系,名字唯一)`);
133
+ names.add(p.name);
134
+ const tok = p.inboundToken ?? p.bearer;
135
+ if (tok) { const a = byTok.get(tok) ?? []; a.push(p.name); byTok.set(tok, a); }
136
+ if (p.url) { const u = p.url.trim(); const a = byUrl.get(u) ?? []; a.push(p.name); byUrl.set(u, a); }
137
+ }
138
+ for (const [tok, ns] of byTok) if (ns.length > 1) throw new Error(`入站凭据冲突(B规则/I6):尾${tok.slice(-4)} 同时映射 ${ns.join(", ")};每个 peer 必须专属 inboundToken`);
139
+ for (const [url, ns] of byUrl) if (ns.length > 1) throw new Error(`地址冲突(I4 ADDRESS_TAKEN):${url} 同时被 ${ns.join(", ")} 使用;一个 cardUrl 只能对应一个 peer 名`);
140
+ }
141
+
142
+ /** 保存配置到项目级 .pi/ 目录。保存前校验 peers(B 规则/I4),冲突抛错不落盘。返回文件路径。 */
143
+ export function saveConfig(cwd: string, config: A2aConfig): string {
144
+ validatePeers(config.peers);
145
+ const dir = path.join(cwd, ".pi");
146
+ fs.mkdirSync(dir, { recursive: true });
147
+ const fp = path.join(dir, "pi-a2a.json");
148
+ fs.writeFileSync(fp, JSON.stringify(config, null, 2) + "\n");
149
+ return fp;
150
+ }