@uuaid/pillar 0.2.0-alpha.10

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.
@@ -0,0 +1,44 @@
1
+ # Pillar Interaction Convention v1
2
+
3
+ App-layer standard for bidirectional interactive conversations over the
4
+ pillar carrier (v0.2.0-alpha.5). No core protocol changes — this is a
5
+ convention any enrolled agent opts into by mutual agreement. LLM-agnostic:
6
+ pure JSON envelopes; any client that can HTTPS + Ed25519-seal can speak it.
7
+
8
+ ## Kinds
9
+
10
+ | kind | semantics |
11
+ |-----------|--------------------------------------------------------|
12
+ | `request` | expects exactly one `reply`; its envelope id = thread root |
13
+ | `reply` | answers a `request`; MUST carry `thread` + `inReplyTo` |
14
+ | `ack` | receipt for any envelope; echoes the id being acked |
15
+ | `message` | fire-and-forget (default kind, unchanged) |
16
+
17
+ ## Payload fields (all optional unless stated)
18
+
19
+ - `text` — human/agent-readable body
20
+ - `thread` — id of the thread-root `request` envelope (REQUIRED on `reply`)
21
+ - `inReplyTo` — id of the envelope being answered (REQUIRED on `reply`/`ack`)
22
+ - `status` — on `reply`: `"ok"` | `"error"`; on error add `reason`
23
+ - `acks` — no receipt field needed; the `ack` envelope IS the receipt
24
+ (carrier limitation #5: receipts are app-layer by design)
25
+
26
+ ## Rules
27
+
28
+ 1. Thread root = the first `request`'s envelope id (known to recipient from
29
+ the envelope itself; the request payload needs no thread field).
30
+ 2. Every `request` and `reply` SHOULD be acked within 30s. Absence of an
31
+ ack = retry (idempotent — carrier dedups on envelope id), not failure.
32
+ 3. Multi-turn: same `thread` for the whole conversation, `inReplyTo` =
33
+ the latest envelope id each time.
34
+ 4. Errors ride the normal channel: `kind: "reply", status: "error",
35
+ reason: "<why>"` — never a different side-channel.
36
+ 5. `kind` stays non-sensitive (visible to carrier); anything sensitive goes
37
+ inside the sealed payload.
38
+
39
+ ## Interactive helper
40
+
41
+ `bin/pillar-ask.mjs <recipient-uuaid> '<question>' [--to-pubkey HEX]`
42
+ sends a `request` and blocks until the `ack`+`reply` arrive (default
43
+ 120s timeout), printing: request id → ack latency → reply latency → text.
44
+ Synchronous Q→A over the same carrier as everything else.
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,114 @@
1
+ # @uuaid/pillar
2
+
3
+ **Pillar** — **P**rotocol for **I**nter-agent **L**inked **L**edger **A**nd
4
+ **R**elay — is the secure delivery layer of **UACP**, the Universal Agent
5
+ Communication Protocol:
6
+
7
+ > **UACP = UUAID (who) + Envelope (what) + Pillar (how it moves).**
8
+
9
+ UUAID handles identity, discovery, keys, and resolution. The Envelope is the
10
+ canonical signed, encrypted message container. Pillar moves it: encrypted
11
+ relay, chain-hashed mailbox ledger, routing, and store-and-forward transport.
12
+
13
+ Every agent mints its own identity (UUAID + keypair) with one command, then
14
+ exchanges encrypted, signed envelopes through the pillar network — a
15
+ store-and-forward carrier mesh with a LimeWire/BitTorrent-style seed topology:
16
+ no single carrier is the only store.
17
+
18
+ **Minimal requirements:** Node.js >= 20, outbound HTTPS. That's it. Carrier
19
+ mode needs no inbound ports, no daemon, no account. One identity = one
20
+ keychain file + one SQLite mailbox.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ npm install -g @uuaid/pillar # global bins: pillar, pillar-carrier, pillar-ask, pillar-responder, pillar-seed
26
+ # or per-project:
27
+ npm install @uuaid/pillar # then npx pillar ... / npx pillar-ask ...
28
+ ```
29
+
30
+ ## Quick start — become an addressable agent in 3 commands
31
+
32
+ ```sh
33
+ # 1. Mint an identity and wire the carrier mesh from the public directory
34
+ pillar init --directory https://pillar.uuaid.org/directory.json
35
+ # -> prints your uuaid:... and publicKey
36
+
37
+ # 2. See who you are
38
+ pillar id
39
+
40
+ # 3. Ask another agent a question (blocks for their ack + reply)
41
+ pillar ask <their-uuaid> "<your question>"
42
+ ```
43
+
44
+ Check your mail any time — `pillar-ask` never drains your inbox, so replies
45
+ and messages queue at the carrier until you pull them:
46
+
47
+ ```sh
48
+ pillar inbox # one-shot: fetch pending envelopes, print, exit
49
+ pillar inbox --unread # also print older stored-but-never-shown envelopes
50
+ pillar inbox --notify 'osascript -e "display notification ..."' # hook when mail waits
51
+ ```
52
+
53
+ For automated checking, put `pillar inbox --notify <cmd>` on a cron/launchd
54
+ interval — the hook gets `PILLAR_NEW` / `PILLAR_UNREAD` / `PILLAR_UUAID` env
55
+ vars and a JSON summary on stdin, and only fires when there is mail.
56
+
57
+ > **One home, one live consumer.** Never point `pillar inbox` (or `pillar-ask`)
58
+ > at a home directory that a running `pillar-responder`/`pillar recv` daemon
59
+ > owns. Carrier reads are non-destructive, but the shared mailbox is idempotent
60
+ > on envelope id — whichever process appends an envelope first fires its
61
+ > handlers, and the other sees a duplicate and stays silent. Concretely: a
62
+ > drain can consume a request the responder then never acks (cursor advance),
63
+ > and an ask from a daemon-owned home can time out even though the reply
64
+ > arrived (the daemon appended it first). Give interactive tools their own
65
+ > identity/home.
66
+
67
+ `--directory` fetches the directory and configures every carrier + seed listed
68
+ there, and writes every `agents[]` entry (uuaid + publicKey) into
69
+ `<home>/fleet.json` as your address book — so step 3 works immediately, no key
70
+ exchange needed. For peers outside any directory, pass their key once with
71
+ `pillar ask <uuaid> "..." --to-pubkey HEX`. Point it at your own directory.json
72
+ to build a private mesh.
73
+
74
+ ## The three always-on roles
75
+
76
+ | Bin | What it runs | Ongoing requirements |
77
+ |---|---|---|
78
+ | `pillar-responder` | Always-on auto-attendant: acks requests instantly, replies from fixed text or a command hook. Run it as a service; agents anywhere get ack+reply without you being live. | one process, outbound HTTPS |
79
+ | `pillar-seed` | A carrier seed — makes you part of the p2p mesh. Any agent that lists your URL replicates every envelope to you and polls you in parallel with other seeds. | one process, one SQLite file, TLS-terminating proxy in front |
80
+ | `pillar` | The full CLI (`init`, `id`, `send`, `send-group`, `recv`, `inbox`, `peers`) — optional libp2p DHT, or carrier-only. | only when used interactively |
81
+
82
+ ```sh
83
+ pillar-responder --home ~/.pillar-responder --reply-text "ack" &
84
+ pillar-seed --port 8799 --db /var/lib/pillar/seed.db & # loopback by default
85
+ ```
86
+
87
+ ## Seed topology — how messages survive
88
+
89
+ On send, `deliver()` replicates the envelope to **every** carrier in your set
90
+ in parallel — any one accepting it is success. On receive, you poll **all** of
91
+ them; duplicates across seeds are deduped by envelope id, so handlers fire
92
+ exactly once. Kill any single seed and delivery continues through the
93
+ survivors. To join the mesh as a seed: TLS-terminate a public URL and list it
94
+ in a directory.json:
95
+
96
+ ```json
97
+ { "url": "https://your-host", "operator": "you", "region": "eu", "since": "2026-08-20" }
98
+ ```
99
+
100
+ `pillar init --directory <that-directory>` picks it up automatically.
101
+
102
+ ## Protocol
103
+
104
+ Envelope v2 (`uuaid-pillar-envelope/2`): mandatory E2E
105
+ (x25519-hkdf-sha256-aes256gcm) when a recipient key is known, JCS-canonical
106
+ Ed25519 transport signature. Carrier API: `/carrier/v1` (POST
107
+ `/v1/envelopes`, GET `/v1/inbox/<uuaid>` long-poll, GET `/v1/health`).
108
+ App-layer convention: kinds `request`/`reply`/`ack`/`message` (see
109
+ INTERACTION-CONVENTION.md). Directory:
110
+ `https://pillar.uuaid.org/directory.json` (protocol, carrier, agents, seeds).
111
+
112
+ ## License
113
+
114
+ Apache-2.0.
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * carrier — run a standalone carrier server (the 24/7 post office).
4
+ *
5
+ * carrier --port 8799 --host 127.0.0.1 --db /opt/pillar-carrier/carrier.db
6
+ *
7
+ * Defaults to loopback (RedTeam F5) — expose only behind a TLS-terminating
8
+ * proxy (nginx/Caddy). Pass --host 0.0.0.0 deliberately only if the carrier
9
+ * must terminate TLS itself. One carrier serves any number of agents; agents
10
+ * authenticate per-request with their own keys. No accounts, no state
11
+ * about who exists — pure store-and-forward.
12
+ */
13
+ import { CarrierServer } from "../src/net/carrier-server.mjs";
14
+
15
+ function parseArgs(argv) {
16
+ const args = {};
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const a = argv[i];
19
+ if (a.startsWith("--")) {
20
+ const k = a.slice(2);
21
+ args[k] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : true;
22
+ }
23
+ }
24
+ return args;
25
+ }
26
+
27
+ const args = parseArgs(process.argv.slice(2));
28
+ const port = Number(args.port ?? process.env.CARRIER_PORT ?? 8799);
29
+ const host = args.host ?? process.env.CARRIER_HOST ?? "127.0.0.1";
30
+ const dbPath = args.db ?? process.env.CARRIER_DB ?? "carrier.db";
31
+ const ttlDays = Number(args.ttl ?? process.env.CARRIER_TTL_DAYS ?? 14);
32
+
33
+ const server = new CarrierServer({ dbPath, ttlDays });
34
+ const addr = await server.listen(port, host);
35
+ console.log(`carrier listening on ${addr.address}:${addr.port}`);
36
+ console.log(` db: ${dbPath}`);
37
+ console.log(` ttl: ${ttlDays} days`);
38
+
39
+ // Vacuum expired envelopes hourly.
40
+ const vacuumTimer = setInterval(() => {
41
+ const n = server.vacuum();
42
+ if (n > 0) console.log(`vacuumed ${n} expired envelopes`);
43
+ }, 3600_000);
44
+
45
+ const shutdown = async () => {
46
+ clearInterval(vacuumTimer);
47
+ await server.close();
48
+ process.exit(0);
49
+ };
50
+ process.on("SIGINT", shutdown);
51
+ process.on("SIGTERM", shutdown);
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pillar-ask — synchronous interactive Q→A over the pillar carrier.
4
+ *
5
+ * pillar-ask <recipient-uuaid> '<question>' [--to-pubkey HEX] [--home DIR]
6
+ * [--fleet FLEET.json] [--timeout SECONDS] [--kind request]
7
+ *
8
+ * Sends a `request` envelope (its id becomes the thread root) and blocks
9
+ * until the recipient's `ack` + `reply` arrive, printing latency for each.
10
+ * Exits 0 on reply(status ok), 3 on reply(status error), 4 on timeout.
11
+ * See INTERACTION-CONVENTION.md for the wire contract.
12
+ */
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { homedir } from "node:os";
16
+ import { argv, exit } from "node:process";
17
+ import { Keychain } from "../src/identity/keychain.mjs";
18
+ import { Pillar } from "../src/pillar.mjs";
19
+ import { loadFleetAddressBook } from "../src/address-book.mjs";
20
+
21
+ function parseArgs(argv) {
22
+ const args = { _: [] };
23
+ for (let i = 0; i < argv.length; i++) {
24
+ const a = argv[i];
25
+ if (a.startsWith("--")) {
26
+ const [k, ...rest] = a.slice(2).split("=");
27
+ args[k] = rest.length ? rest.join("=") : (argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[++i] : true);
28
+ } else {
29
+ args._.push(a);
30
+ }
31
+ }
32
+ return args;
33
+ }
34
+
35
+ const args = parseArgs(argv.slice(2));
36
+ const [recipient, question] = args._;
37
+ if (!recipient || !question) {
38
+ console.error("usage: pillar-ask <recipient-uuaid> '<question>' [--to-pubkey HEX] [--home DIR] [--fleet FLEET.json] [--timeout S]");
39
+ exit(2);
40
+ }
41
+
42
+ const home = args.home || process.env.PILLAR_HOME || join(homedir(), ".pillar");
43
+ const kcPath = join(home, "keychain.json");
44
+ const mbPath = join(home, "mailbox.db");
45
+ const cfgPath = join(home, "config.json");
46
+ if (!existsSync(kcPath)) {
47
+ console.error(`no pillar found at ${home}. run: pillar init`);
48
+ exit(2);
49
+ }
50
+ const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
51
+ const kc = new Keychain(kcPath);
52
+ kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" });
53
+ const carriers = args.carrier
54
+ ? [args.carrier]
55
+ : (process.env.PILLAR_CARRIERS ? process.env.PILLAR_CARRIERS.split(",") : (cfg.carriers ?? []));
56
+ const p = new Pillar({
57
+ keychain: kc,
58
+ mailboxPath: mbPath,
59
+ listenAddrs: cfg.listenAddrs ?? ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/tcp/0/ws"],
60
+ bootstrapPeers: cfg.bootstrapPeers ?? [],
61
+ enableRelay: cfg.enableRelay ?? false,
62
+ dhtClientMode: cfg.dhtClientMode ?? true,
63
+ carriers,
64
+ enableLibp2p: !(cfg.carrierOnly === true),
65
+ });
66
+
67
+ const t0 = Date.now();
68
+ const timeoutMs = (Number(args.timeout) || 120) * 1000;
69
+ const kind = args.kind || "request";
70
+
71
+ await p.start();
72
+ if (p.carrierClient) p.startCarrierPolling(); // receive ack/reply from the carrier (p.start() does not poll)
73
+ // Address book default: <home>/fleet.json (written by `pillar init --directory`
74
+ // from the directory's agents[]) — so `pillar ask` works with no key plumbing.
75
+ const fleetFile = args.fleet || join(home, "fleet.json");
76
+ if (existsSync(fleetFile)) {
77
+ const n = loadFleetAddressBook(fleetFile, p);
78
+ if (n > 0) console.log(`address book: ${n} peers from ${fleetFile}`);
79
+ }
80
+ let envelopeId = null; // set after send; handlers may fire during start/send (carrier polling is live)
81
+ const gotAck = new Promise((resolve) => p.onEnvelope((env) => {
82
+ if (env.kind === "ack" && envelopeId && env.payload?.inReplyTo === envelopeId) resolve(env);
83
+ }));
84
+ const gotReply = new Promise((resolve) => p.onEnvelope((env) => {
85
+ if (env.kind === "reply" && envelopeId && env.payload?.inReplyTo === envelopeId) resolve(env);
86
+ }));
87
+
88
+ const { envelope } = await p.send({
89
+ recipient,
90
+ recipientPublicKey: args["to-pubkey"] ?? undefined,
91
+ kind,
92
+ payload: { text: question },
93
+ });
94
+ envelopeId = envelope.id;
95
+ console.log(`request ${envelopeId} sent to ${recipient} (kind=${kind})`);
96
+
97
+ const waitFor = async (promise, label) => {
98
+ const winner = await Promise.race([
99
+ promise.then((env) => ({ env })),
100
+ new Promise((r) => setTimeout(() => r({ timeout: true }), timeoutMs)),
101
+ ]);
102
+ if (winner.timeout) {
103
+ console.error(`${label}: TIMEOUT after ${timeoutMs / 1000}s`);
104
+ exit(4);
105
+ }
106
+ const ms = Date.now() - t0;
107
+ console.log(`${label} from ${winner.env.sender} in ${ms}ms`);
108
+ return winner.env;
109
+ };
110
+
111
+ const ackEnv = await waitFor(gotAck, "ack");
112
+ const replyEnv = await waitFor(gotReply, "reply");
113
+ const status = replyEnv.payload?.status ?? "ok";
114
+ if (status !== "ok") {
115
+ console.error(`reply status=${status} reason=${replyEnv.payload?.reason ?? "none"}`);
116
+ exit(3);
117
+ }
118
+ // Convention rule 2: the requester acks the reply it received (ack of ack would regress).
119
+ await p.send({
120
+ recipient,
121
+ recipientPublicKey: args["to-pubkey"] ?? undefined,
122
+ kind: "ack",
123
+ payload: { inReplyTo: replyEnv.id },
124
+ });
125
+ console.log(`ack ${replyEnv.id} sent to ${recipient}`);
126
+ console.log(replyEnv.payload?.text ?? "(empty reply)");
127
+ await p.stop();
128
+ exit(0);