@pidgeon-ai/cli 1.44.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0
4
+
5
+ The command line for the new Pidgeon. A new major version: 1.x spoke the old
6
+ email API at `/api/v1`, which is retired seven days after the switch.
7
+
8
+ - `pidgeon login`: sign in with the browser through Pidgeon's OAuth server,
9
+ choosing what this machine may do; the session is refreshed from then on.
10
+ `PIDGEON_API_KEY` still wins over it.
11
+ - `pidgeon agents create`: register an agent, make its key on this machine,
12
+ publish it signed with itself, keep it in a file only you can read.
13
+ `agents list`, `agents show` (keys and reputation), `keys create`, `keys list`.
14
+ - Email: `inboxes`, `send`, `drafts` (create, show, send, approval, remove).
15
+ - `events`, and `pidgeon api <method> <path>` for any `/v1` call. `--json` everywhere.
package/LICENSE CHANGED
@@ -1,21 +1,55 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 PCN Labs OÜ
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,104 +1,39 @@
1
- # `@pidgeon-ai/cli`
1
+ # @pidgeon-ai/cli
2
2
 
3
- Email inboxes for AI agents, from a terminal. Pidgeon is the email inbox API
4
- for AI agents. It gives agents their own inboxes so they can work with emails
5
- just like a human. This is every endpoint as a command, so an agent with a
6
- shell, or you, can create an address, send, receive and reply.
3
+ `pidgeon`, Pidgeon from a terminal: sign in, set agents up with keys made on
4
+ your machine, and send from their inboxes. https://pidgeon.ai
7
5
 
8
6
  ```sh
9
7
  npm install -g @pidgeon-ai/cli
8
+ pidgeon login
9
+ pidgeon agents create "Booking agent" --purpose "Books tables."
10
10
  ```
11
11
 
12
- Or run it without installing: `npx -y @pidgeon-ai/cli --help`.
13
-
14
- ## Get a key
15
-
16
- Every command reads a `pgn_live_…` key from `PIDGEON_API_KEY`. Make one at
17
- [pidgeon.ai/app/developers/keys](https://pidgeon.ai/signup?utm_source=npm&utm_medium=readme&utm_campaign=cli&next=/app/developers/keys), or
18
- let your agent sign itself up: [pidgeon.ai/skill.md](https://pidgeon.ai/skill.md)
19
- is two calls, and the only thing it needs from a person is a six-digit code.
20
-
21
- ```sh
22
- export PIDGEON_API_KEY=pgn_live_…
23
- ```
24
-
25
- ## Create an address, send, receive, reply
12
+ `agents create` registers the agent, makes its Ed25519 key on this machine,
13
+ publishes the public half in a request signed with the key, and keeps the
14
+ private half in `~/.config/pidgeon/agents/<id>.json`, readable by you only.
15
+ Your agent signs with it: `agentFromKeyFile(path)` from `@pidgeon-ai/sdk/node`,
16
+ or `PIDGEON_AGENT_KEY` (the file's `private_jwk`) and `PIDGEON_DIRECTORY`.
26
17
 
27
18
  ```sh
28
- pidgeon identities create --address scout@pidgeon.email --type agent
29
- pidgeon messages send --from scout@pidgeon.email --to ops@example.com \
30
- --subject "Staging access" --text "Could you send me the access code?"
31
- pidgeon messages await --identity_id <id> --timeout 60
32
- pidgeon messages reply --id <message id> --text "Thanks, that worked."
19
+ pidgeon agents show <agent-id> # its keys, and how websites see it
20
+ pidgeon inboxes create bookings --agent <agent-id>
21
+ pidgeon send <inbox-id> --to ana@example.com --subject "Table for two" --text "Friday at 8?"
22
+ pidgeon drafts create <inbox-id> --to ana@example.com --subject "…" --text "…"
23
+ pidgeon drafts approval <draft-id> # a person sends or rejects it
24
+ pidgeon events
25
+ pidgeon api GET /v1/email/rules # any /v1 call
33
26
  ```
34
27
 
35
- Any free name on `pidgeon.email` works with no DNS. `messages await` holds
36
- one request open until mail arrives, and prints it with `extracted.codes` and
37
- `extracted.links` already pulled out.
38
-
39
- `pidgeon --help` lists every group; `pidgeon <group> <command> --help`
40
- describes one command, with its endpoint and its flags. Documentation:
41
- [pidgeon.ai/docs/cli](https://pidgeon.ai/docs/cli).
42
-
43
- ## Check who sent something
44
-
45
- `pidgeon id` needs no key. It checks a message, or signs a request as one of
46
- your agents:
47
-
48
- ```sh
49
- pidgeon id verify message.eml
50
- pidgeon id curl -I https://shop.example --as sunny
51
- ```
52
-
53
- `verify` asks the public verifier and says whether the signature holds, which
54
- agent sent it, who it acts for and whether the body changed. `curl` signs the
55
- request the way Web Bot Auth asks and prints what it sent. `pidgeon id --help`
56
- lists the rest, including `init` for your own domain.
57
-
58
- ## Flags
59
-
60
- - Repeat a list flag: `--to one@example.com --to two@example.com`.
61
- - `--flag value` and `--flag=value` both work, and a subject may contain
62
- an `=`.
63
- - A nested object takes JSON: `--some_field '{"a":1}'`.
64
- - `PIDGEON_BASE_URL` points it somewhere other than production.
65
-
66
- ## Retrying a send
67
-
68
- Every command that sends takes `--idempotency-key`. Run it again with the
69
- same key and the message goes out once; the second run prints the first
70
- answer. Without one, each run makes up its own key. `--verbose` prints it
71
- on stderr before the call, and a failure that may already have sent (no
72
- answer, or a 5xx) prints it in the error, so a script can retry with it.
73
-
74
- ## When it fails
75
-
76
- A refusal from the API exits 1 and prints the status, the API's code and
77
- its sentence, as in `403 abuse_blocked: That message has already gone to a
78
- lot of people today…`. Branch on the code. A mistake in the command itself,
79
- such as a missing flag, exits 2. Before 1.8.4 a refusal also exited 2 and
80
- printed only the sentence.
81
-
82
- ## It is generated
83
-
84
- One command per operation in [the published
85
- contract](https://pidgeon.ai/openapi.json), which is generated from the
86
- schemas the API validates with. The group is the operation's tag, the
87
- command is the rest of its `operationId`, and the flags are its parameters
88
- and the top level of its request body.
28
+ `pidgeon --help` lists every command; `--json` prints the API's own answer.
89
29
 
90
- So `pidgeon messages send` is `POST /messages` because the document says
91
- so, and the day an endpoint gains a field this gains a flag. The same
92
- document produces the TypeScript client this calls through, the Python
93
- client, and the MCP server's tool list.
30
+ Signing in opens the browser once; the session is kept in
31
+ `~/.config/pidgeon/credentials.json` and refreshed. On a machine with no
32
+ browser, set `PIDGEON_API_KEY` instead. `PIDGEON_CONFIG_DIR` and
33
+ `PIDGEON_BASE_URL` move the files and the server.
94
34
 
95
- ## Contributing
35
+ Version 2 is for the new Pidgeon; 1.x spoke the old API at `/api/v1`.
96
36
 
97
- This package is published from
98
- [pidgeon-ai/pidgeon-js](https://github.com/pidgeon-ai/pidgeon-js), which is
99
- copied from Pidgeon's main repository on every release, so a pull request
100
- there cannot be merged as written.
101
- [Open an issue](https://github.com/pidgeon-ai/pidgeon-js/issues) and say what
102
- is wrong, or email [support@pidgeon.ai](mailto:support@pidgeon.ai).
37
+ ## License
103
38
 
104
- MIT licensed.
39
+ Apache-2.0
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "./cli.js";
3
+ run(process.argv.slice(2), {
4
+ out: (line) => process.stdout.write(`${line}\n`),
5
+ err: (line) => process.stderr.write(`${line}\n`),
6
+ env: process.env,
7
+ }).then((code) => {
8
+ process.exitCode = code;
9
+ }, (error) => {
10
+ process.stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
11
+ process.exitCode = 1;
12
+ });
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,11 @@
1
-
2
- export { }
1
+ export declare const VERSION = "2.0.0";
2
+ export type Io = {
3
+ out: (line: string) => void;
4
+ err: (line: string) => void;
5
+ env: Record<string, string | undefined>;
6
+ fetch?: typeof fetch;
7
+ /** For tests: what a person does in the browser when signing in. */
8
+ onSignInUrl?: (url: string) => void;
9
+ openBrowser?: boolean;
10
+ };
11
+ export declare function run(argv: string[], io: Io): Promise<number>;
package/dist/cli.js CHANGED
@@ -1,26 +1,353 @@
1
- #!/usr/bin/env node
2
- import {
3
- UsageError,
4
- run
5
- } from "./chunk-M4R74E7X.js";
6
- import "./chunk-FZA3INVW.js";
1
+ /**
2
+ * `pidgeon`, the command line (CLI 2.0): Passport, Email and the account from
3
+ * a terminal. Every command is a call through `@pidgeon-ai/sdk`; signing in
4
+ * and agent keys are `@pidgeon-ai/sdk/node`'s, shared with the MCP server.
5
+ *
6
+ * `run` is the whole program, with its input and output passed in, so it is
7
+ * tested without a terminal.
8
+ */
9
+ import { parseArgs } from 'node:util';
10
+ import { PidgeonError } from '@pidgeon-ai/sdk';
11
+ import { addAgentKey, baseUrlOf, clientFromEnvironment, listAgentKeys, makeKeyProof, readSession, setUpAgent, signIn, signOut, } from '@pidgeon-ai/sdk/node';
12
+ export const VERSION = '2.0.0';
13
+ const HELP = `pidgeon ${VERSION}: Pidgeon from a terminal.
7
14
 
8
- // src/cli.ts
9
- async function main() {
10
- try {
11
- process.stdout.write(
12
- `${await run(process.argv.slice(2), process.env, {
13
- stderr: (line) => process.stderr.write(`${line}
14
- `)
15
- })}
16
- `
17
- );
18
- } catch (error) {
19
- const message = error instanceof Error ? error.message : "Something went wrong.";
20
- process.stderr.write(`${message}
21
- `);
22
- process.exit(error instanceof UsageError ? 2 : 1);
23
- }
15
+ Signing in
16
+ pidgeon login [--scope admin|send|draft|read] [--no-browser]
17
+ pidgeon logout
18
+ pidgeon status
19
+ Or set PIDGEON_API_KEY; it wins over a session. PIDGEON_BASE_URL points elsewhere.
20
+
21
+ Agents (Passport)
22
+ pidgeon agents list
23
+ pidgeon agents create <name> [--purpose <text>]
24
+ Registers the agent, makes its key on this machine, publishes the public
25
+ half signed with it, and keeps the key here (pidgeon keys list).
26
+ pidgeon agents show <agent-id> its keys and its operator's reputation
27
+ pidgeon keys create <agent-id> a new key for it, made here
28
+ pidgeon keys list the keys this machine keeps
29
+ pidgeon keys proof <agent-id> --directory <url> --url <publish-url>
30
+ For the hosted MCP server: makes the key here, keeps it, and prints the
31
+ public half and the signed proof that publishing needs. No sign-in.
32
+
33
+ Email
34
+ pidgeon inboxes list
35
+ pidgeon inboxes create <name> [--kind agent|shared|person|events] [--agent <id>]
36
+ pidgeon inboxes remove <inbox-id>
37
+ pidgeon send <inbox-id> --to <address>... --subject <text> (--text <body> | --html <body>) [--reply-to <message-id>]
38
+ pidgeon drafts create <inbox-id> --to <address>... --subject <text> --text <body>
39
+ pidgeon drafts show|remove <draft-id>
40
+ pidgeon drafts send <draft-id> [--at <ISO time>]
41
+ pidgeon drafts approval <draft-id> hold it for a person to send or reject
42
+
43
+ The account
44
+ pidgeon events [--type <type>] [--limit <n>]
45
+ pidgeon api <GET|POST|PATCH|DELETE> <path> [--data <json>] any /v1 call
46
+
47
+ Add --json to any command for the API's own JSON.`;
48
+ const OPTIONS = {
49
+ json: { type: 'boolean' },
50
+ help: { type: 'boolean', short: 'h' },
51
+ version: { type: 'boolean', short: 'v' },
52
+ scope: { type: 'string' },
53
+ 'no-browser': { type: 'boolean' },
54
+ purpose: { type: 'string' },
55
+ kind: { type: 'string' },
56
+ agent: { type: 'string' },
57
+ to: { type: 'string', multiple: true },
58
+ cc: { type: 'string', multiple: true },
59
+ bcc: { type: 'string', multiple: true },
60
+ subject: { type: 'string' },
61
+ text: { type: 'string' },
62
+ html: { type: 'string' },
63
+ 'reply-to': { type: 'string' },
64
+ at: { type: 'string' },
65
+ type: { type: 'string' },
66
+ limit: { type: 'string' },
67
+ data: { type: 'string' },
68
+ directory: { type: 'string' },
69
+ url: { type: 'string' },
70
+ };
71
+ class Usage extends Error {
72
+ }
73
+ export async function run(argv, io) {
74
+ let parsed;
75
+ try {
76
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
77
+ }
78
+ catch (error) {
79
+ io.err(error instanceof Error ? error.message : String(error));
80
+ return 2;
81
+ }
82
+ const { values, positionals } = parsed;
83
+ if (values.version) {
84
+ io.out(VERSION);
85
+ return 0;
86
+ }
87
+ if (values.help || positionals.length === 0) {
88
+ io.out(HELP);
89
+ return 0;
90
+ }
91
+ try {
92
+ await dispatch(positionals, values, io);
93
+ return 0;
94
+ }
95
+ catch (error) {
96
+ if (error instanceof Usage) {
97
+ io.err(error.message);
98
+ io.err('Run `pidgeon --help` for every command.');
99
+ return 2;
100
+ }
101
+ if (error instanceof PidgeonError) {
102
+ io.err(`${error.message} (${error.status} ${error.code})`);
103
+ return 1;
104
+ }
105
+ io.err(error instanceof Error ? error.message : String(error));
106
+ return 1;
107
+ }
108
+ }
109
+ function need(value, what) {
110
+ if (!value)
111
+ throw new Usage(`Say which ${what}.`);
112
+ return value;
113
+ }
114
+ function message(values) {
115
+ if (!values.to?.length)
116
+ throw new Usage('Send it to someone: --to <address>.');
117
+ if (values.subject === undefined)
118
+ throw new Usage('Give it a subject: --subject <text>.');
119
+ if (values.text === undefined && values.html === undefined)
120
+ throw new Usage('Give it a body: --text <body> or --html <body>.');
121
+ return {
122
+ to: values.to,
123
+ cc: values.cc,
124
+ bcc: values.bcc,
125
+ subject: values.subject,
126
+ text: values.text,
127
+ html: values.html,
128
+ replyTo: values['reply-to'],
129
+ };
130
+ }
131
+ async function dispatch(positionals, values, io) {
132
+ const [command, sub, arg] = positionals;
133
+ const baseUrl = baseUrlOf(io.env);
134
+ const client = () => clientFromEnvironment({ env: io.env, baseUrl, fetch: io.fetch });
135
+ const show = (data, plain) => {
136
+ if (values.json)
137
+ io.out(JSON.stringify(data ?? null, null, 2));
138
+ else
139
+ for (const line of plain())
140
+ io.out(line);
141
+ };
142
+ switch (command) {
143
+ case 'login': {
144
+ const scope = (values.scope ?? 'admin');
145
+ if (!['read', 'draft', 'send', 'admin'].includes(scope))
146
+ throw new Usage('--scope is read, draft, send or admin.');
147
+ const session = await signIn({
148
+ baseUrl,
149
+ scope,
150
+ env: io.env,
151
+ fetch: io.fetch,
152
+ clientName: 'Pidgeon CLI',
153
+ openBrowser: values['no-browser'] ? false : (io.openBrowser ?? true),
154
+ onUrl: (url) => {
155
+ io.err(`Sign in to Pidgeon in your browser. If it did not open, go to:\n${url}`);
156
+ io.onSignInUrl?.(url);
157
+ },
158
+ });
159
+ show({ base_url: baseUrl, scope: session.scope }, () => [
160
+ `Signed in to ${baseUrl}, with ${session.scope} access.`,
161
+ ]);
162
+ return;
163
+ }
164
+ case 'logout': {
165
+ const ended = await signOut(baseUrl, { env: io.env, fetch: io.fetch });
166
+ show({ signed_out: ended }, () => [ended ? 'Signed out.' : 'You were not signed in.']);
167
+ return;
168
+ }
169
+ case 'status': {
170
+ const session = await readSession(baseUrl, io.env);
171
+ const how = io.env.PIDGEON_API_KEY
172
+ ? 'an API key (PIDGEON_API_KEY)'
173
+ : session
174
+ ? `a session with ${session.scope} access`
175
+ : null;
176
+ show({
177
+ base_url: baseUrl,
178
+ api_key: Boolean(io.env.PIDGEON_API_KEY),
179
+ session: session ? { scope: session.scope } : null,
180
+ }, () => [
181
+ how ? `${baseUrl}, with ${how}.` : `Not signed in to ${baseUrl}: run \`pidgeon login\`.`,
182
+ ]);
183
+ return;
184
+ }
185
+ case 'agents': {
186
+ const pidgeon = client();
187
+ if (sub === 'list') {
188
+ const page = await pidgeon.agents.list();
189
+ show(page, () => page.data.length
190
+ ? page.data.map((a) => `${a.id} ${a.status.padEnd(7)} ${a.name}`)
191
+ : ['No agents yet: pidgeon agents create <name>.']);
192
+ }
193
+ else if (sub === 'create') {
194
+ const name = need(arg, 'name to give the agent');
195
+ const made = await setUpAgent(pidgeon, { name, purpose: values.purpose }, io.env);
196
+ show({ agent: made.agent, kid: made.kid, key_file: made.keyFile }, () => [
197
+ `Registered ${made.agent.name} (${made.agent.id}) and published its key ${made.kid}.`,
198
+ `Its private key is in ${made.keyFile}, on this machine only.`,
199
+ `Its directory: ${made.agent.directory}`,
200
+ ]);
201
+ }
202
+ else if (sub === 'show') {
203
+ const agent = await pidgeon.agents.get(need(arg, 'agent (its id)'));
204
+ show(agent, () => [
205
+ `${agent.name} (${agent.id}), ${agent.status}`,
206
+ agent.purpose ? `Does: ${agent.purpose}` : 'Does: (not said)',
207
+ `Directory: ${agent.directory}`,
208
+ `Keys: ${agent.keys
209
+ .filter((k) => !k.revoked_at)
210
+ .map((k) => k.kid)
211
+ .join(', ') || 'none published'}`,
212
+ `Reputation: ${agent.reputation.band}. ${agent.reputation.seen}`,
213
+ ...(agent.reputation.next ? [agent.reputation.next] : []),
214
+ ]);
215
+ }
216
+ else
217
+ throw new Usage('pidgeon agents list | create <name> | show <id>');
218
+ return;
219
+ }
220
+ case 'keys': {
221
+ if (sub === 'create') {
222
+ const made = await addAgentKey(client(), need(arg, 'agent (its id)'), io.env);
223
+ show({ kid: made.kid, key_file: made.keyFile }, () => [
224
+ `Published key ${made.kid}. Its private half is in ${made.keyFile}.`,
225
+ ]);
226
+ }
227
+ else if (sub === 'list') {
228
+ const keys = await listAgentKeys(io.env);
229
+ show(keys, () => keys.length
230
+ ? keys.map((k) => `${k.agent_id} ${k.kid} ${k.name} ${k.path}`)
231
+ : ['This machine keeps no agent keys.']);
232
+ }
233
+ else if (sub === 'proof') {
234
+ const agentId = need(arg, 'agent (its id)');
235
+ const directory = need(values.directory, 'directory (--directory)');
236
+ const publishUrl = values.url ?? `${baseUrl}/v1/agents/${encodeURIComponent(agentId)}/keys`;
237
+ const proof = await makeKeyProof({ agentId, directory, publishUrl }, io.env);
238
+ // Always JSON: it is for a coding agent to hand to publish_agent_key.
239
+ io.out(JSON.stringify(proof, null, 2));
240
+ }
241
+ else
242
+ throw new Usage('pidgeon keys create <agent-id> | list | proof <agent-id>');
243
+ return;
244
+ }
245
+ case 'inboxes': {
246
+ const pidgeon = client();
247
+ if (sub === 'list') {
248
+ const page = await pidgeon.inboxes.list();
249
+ show(page, () => page.data.length
250
+ ? page.data.map((i) => `${i.id} ${i.kind.padEnd(6)} ${i.address}`)
251
+ : ['No inboxes yet.']);
252
+ }
253
+ else if (sub === 'create') {
254
+ const kind = (values.kind ?? 'agent');
255
+ const inbox = await pidgeon.inboxes.create({
256
+ name: need(arg, 'name (the part before the @)'),
257
+ kind,
258
+ agentId: values.agent,
259
+ });
260
+ show(inbox, () => [`Made ${inbox.address} (${inbox.id}).`]);
261
+ }
262
+ else if (sub === 'remove') {
263
+ await pidgeon.inboxes.remove(need(arg, 'inbox (its id)'));
264
+ show({ removed: arg }, () => ['Removed. Its address is retired and never reissued.']);
265
+ }
266
+ else
267
+ throw new Usage('pidgeon inboxes list | create <name> | remove <id>');
268
+ return;
269
+ }
270
+ case 'send': {
271
+ const result = await client().messages.send(need(sub, 'inbox to send from (its id)'), message(values));
272
+ show(result, () => [
273
+ result.status === 'held'
274
+ ? `Held for a person of the account to approve (${result.id}).`
275
+ : `Sent (${result.id}).`,
276
+ ]);
277
+ return;
278
+ }
279
+ case 'drafts': {
280
+ const pidgeon = client();
281
+ if (sub === 'create') {
282
+ const draft = await pidgeon.drafts.create(need(arg, 'inbox (its id)'), message(values));
283
+ show(draft, () => [`Drafted ${draft.id}.`]);
284
+ }
285
+ else if (sub === 'show') {
286
+ const draft = await pidgeon.drafts.get(need(arg, 'draft (its id)'));
287
+ show(draft, () => [
288
+ `${draft.id} ${draft.status}`,
289
+ `To: ${draft.to.join(', ')}`,
290
+ `Subject: ${draft.subject}`,
291
+ '',
292
+ draft.text ?? draft.html ?? '',
293
+ ]);
294
+ }
295
+ else if (sub === 'send') {
296
+ const result = await pidgeon.drafts.send(need(arg, 'draft (its id)'), {
297
+ sendAt: values.at,
298
+ });
299
+ show(result, () => [
300
+ {
301
+ sent: 'Sent.',
302
+ held: 'Held for a person to approve.',
303
+ scheduled: `Scheduled for ${values.at}.`,
304
+ }[result.status],
305
+ ]);
306
+ }
307
+ else if (sub === 'approval') {
308
+ const draft = await pidgeon.drafts.requestApproval(need(arg, 'draft (its id)'));
309
+ show(draft, () => ['Held. A person of the account sends or rejects it from Pidgeon.']);
310
+ }
311
+ else if (sub === 'remove') {
312
+ await pidgeon.drafts.remove(need(arg, 'draft (its id)'));
313
+ show({ removed: arg }, () => ['Thrown away.']);
314
+ }
315
+ else
316
+ throw new Usage('pidgeon drafts create | show | send | approval | remove');
317
+ return;
318
+ }
319
+ case 'events': {
320
+ const page = await client().events.list({
321
+ type: values.type,
322
+ limit: values.limit ? Number(values.limit) : undefined,
323
+ });
324
+ show(page, () => page.data.length
325
+ ? page.data.map((e) => `${e.created_at} ${e.type}`)
326
+ : ['Nothing has happened yet.']);
327
+ return;
328
+ }
329
+ case 'api': {
330
+ const method = (sub ?? '').toUpperCase();
331
+ if (!['GET', 'POST', 'PATCH', 'DELETE'].includes(method) || !arg?.startsWith('/v1/'))
332
+ throw new Usage('pidgeon api <GET|POST|PATCH|DELETE> </v1/...> [--data <json>]');
333
+ let body;
334
+ if (values.data !== undefined) {
335
+ try {
336
+ body = JSON.parse(values.data);
337
+ }
338
+ catch {
339
+ throw new Usage('--data is JSON.');
340
+ }
341
+ }
342
+ const [path, query] = arg.split('?', 2);
343
+ const answer = await client().request(method, path, {
344
+ body,
345
+ query: query ? Object.fromEntries(new URLSearchParams(query)) : undefined,
346
+ });
347
+ io.out(JSON.stringify(answer ?? null, null, 2));
348
+ return;
349
+ }
350
+ default:
351
+ throw new Usage(`There is no \`pidgeon ${command}\`.`);
352
+ }
24
353
  }
25
- void main();
26
- //# sourceMappingURL=cli.js.map