@kivel.io/cli 0.0.0-stage → 0.6.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,81 @@
1
+ # @kivel.io/cli
2
+
3
+ ## 0.6.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b6437db: Published as `@kivel.io/sdk` and `@kivel.io/cli`, under the npm organization for kivel.io.
8
+ - Updated dependencies [b6437db]
9
+ - @kivel.io/sdk@0.6.1
10
+
11
+ ## 0.6.0
12
+
13
+ ### Minor Changes
14
+
15
+ - d096583: Add email threads, draft delivery and inbox rule inspection.
16
+ - a0aa58d: Renamed from `@socket-help/sdk` and `@socket-help/cli`. The client class is now `Kivel`, the error class `KivelError`, the CLI command `kivel`, and the default URL `https://kivel.io`. The CLI reads `KIVEL_URL`, `KIVEL_API_KEY` and `KIVEL_ACCESS_TOKEN`, and still accepts the old `SOCKET_HELP_*` names.
17
+
18
+ ### Patch Changes
19
+
20
+ - 4185eed: Examples name the client `kivel`, and new API keys start with `kv_`. Existing `sh_` keys keep working.
21
+ - Updated dependencies [d096583]
22
+ - Updated dependencies [4185eed]
23
+ - Updated dependencies [a0aa58d]
24
+ - @kivel.io/sdk@0.6.0
25
+
26
+ ## 0.5.1
27
+
28
+ ### Patch Changes
29
+
30
+ - Updated dependencies [d69807d]
31
+ - @socket-help/sdk@0.5.1
32
+
33
+ ## 0.5.0
34
+
35
+ ### Minor Changes
36
+
37
+ - 026f194: Add workspace TOTP authenticators and private email attachment links and downloads.
38
+ - 2f1574b: Add mock OAuth and OpenID Connect provider creation, configuration and lifecycle commands.
39
+
40
+ ### Patch Changes
41
+
42
+ - Updated dependencies [026f194]
43
+ - Updated dependencies [2f1574b]
44
+ - @socket-help/sdk@0.5.0
45
+
46
+ ## 0.4.1
47
+
48
+ ### Patch Changes
49
+
50
+ - 4b9c802: Default webhook inboxes to receiving without sender credentials while keeping inspection private. Document explicit private receiving and its X-Access-Token requirement.
51
+ - Updated dependencies [4b9c802]
52
+ - @socket-help/sdk@0.4.1
53
+
54
+ ## 0.4.0
55
+
56
+ ### Minor Changes
57
+
58
+ - 858c876: Support owned agent email inboxes with Free lifetimes, paid custom addresses, inbox listing and webhook forwarding, guarded outbound mail and combined event waits. Email creation now requires an account and uses activeDays instead of generic resource retention settings.
59
+
60
+ Add scheduled callbacks and delivery waits, authenticated SMTP capture, DNS monitor baselines and status-page lifecycle methods.
61
+
62
+ Add scripted LLM responses and streaming configuration, guarded phone number and inbound SMS methods, and email history clearing. Surface paid-feature errors with the required plan and upgrade URL.
63
+
64
+ Keep all event waits inside the configured client timeout and preserve structured upgrade fields in CLI and SSH errors.
65
+
66
+ ### Patch Changes
67
+
68
+ - Updated dependencies [858c876]
69
+ - @socket-help/sdk@0.4.0
70
+
71
+ ## 0.3.1
72
+
73
+ ### Patch Changes
74
+
75
+ - 5bd1172: Clarify beta installation, include package changelogs and automate reviewed client releases. Read the CLI version from its package manifest so SDK and CLI releases can version independently.
76
+ - Updated dependencies [5bd1172]
77
+ - @socket-help/sdk@0.3.1
78
+
79
+ ## 0.3.0
80
+
81
+ Initial public beta release.
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 CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @kivel.io/cli
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
+ The command-line client for [Kivel](https://kivel.io). Requires Node.js
4
+ 22.13+. Commands share the HTTP API's access rules, plan limits and expiry.
5
+
6
+ Install the current beta:
7
+
8
+ ```sh
9
+ npx --package=@kivel.io/cli@beta kivel --help
10
+ # Or install the command:
11
+ npm install --global @kivel.io/cli@beta
12
+ kivel --version
13
+ ```
14
+
15
+ For source development, run `pnpm build:packages` and `pnpm cli --help` from the
16
+ repository, or use `pnpm test:packages` to verify SDK and CLI tarballs together. The CLI depends
17
+ on the matching SDK; it does not require the backend or media-processing packages.
18
+
19
+ ```sh
20
+ export KIVEL_URL=https://kivel.io
21
+ export KIVEL_API_KEY=YOUR_WORKSPACE_KEY
22
+ kivel email create
23
+ kivel monitor list
24
+ printf '{"passed":true}' | kivel memory set project-a build/latest
25
+ kivel memory get project-a build/latest
26
+ ```
27
+
28
+ Use `kivel agent login "Agent on my laptop"` to start device login. Open the
29
+ returned verification URL in your browser. Pipe a private JSON file containing
30
+ `deviceCode` to `kivel agent token` after approval, then save the returned
31
+ key privately. The CLI prints credentials only in the response to the request that
32
+ creates them; it does not automatically persist a login or modify client config.
33
+
34
+ JSON results go to stdout, errors to stderr with exit code 1, and downloads write
35
+ raw bytes. `--help` and `--version` print plain text. Input is limited to 10 MiB;
36
+ requests time out after 90 seconds. Mutations are never automatically retried.
37
+ `KIVEL_ACCESS_TOKEN` supplies a private file token for `download` when no
38
+ `--access-token` is passed. Keep secrets out of shell history and URLs.
39
+
40
+ `job`, `status-page`, `smtp`, `phone` and `event wait` use the same owned APIs. Operator-dependent services stay disabled until configured; phone sending and calls are not implemented. Run `kivel --help` for their current commands.
41
+
42
+ `listen` streams webhook events and can forward them to a local server. It runs on
43
+ your machine, and stops on Ctrl+C. The optional server SSH gateway supports bounded
44
+ commands; it does not provide this continuous listener or a shell/SCP/SFTP service.
45
+
46
+ [Command reference](https://kivel.io/docs/cli/) ·
47
+ [Authentication](https://kivel.io/docs/authentication/) ·
48
+ [Agent workflows](https://kivel.io/docs/agent-workflows/)
49
+
50
+ Licensed under Apache-2.0. Support: support@kivel.io.
51
+
52
+ `inbox create` returns a webhook URL that accepts senders without credentials. Inspection and `listen` require your workspace key or the returned inspection token. Use `inbox create --visibility private` only when the sender can add the returned access token in `X-Access-Token`.
53
+
54
+ For accounts your human asked you to operate, pipe a private JSON setup file to
55
+ `authenticator add`: `{ "name": "Project account", "uri": "otpauth://totp/..." }`.
56
+ The input also accepts a Base32 `secret` or PNG/JPEG `imageBase64`. Use
57
+ `authenticator list`, `authenticator code <id>`, `authenticator rename <id> <name>`
58
+ and `authenticator delete <id>`. Secrets are encrypted and never returned; code
59
+ requests are audited. Never put setup secrets in command arguments or logs.
60
+
61
+ `email attachment <inbox-id> <message-id> <attachment-id>` returns a private URL
62
+ valid for two minutes. `email download-attachment` with the same IDs outputs exact
63
+ file bytes; redirect stdout to a file. Attachments are untrusted downloads. A
64
+ message can be up to 5 MiB; an inbox can hold 25 MiB of attachment content, within
65
+ workspace storage limits. Clearing messages or expiring the inbox removes files.
66
+
67
+ ## Mock OAuth provider
68
+
69
+ With a workspace key, pipe a configuration containing `name`, `redirectUris` and
70
+ synthetic `users` (`sub`, `email`, `name`) into creation. Save the returned client secret
71
+ privately, since inspection does not return it again.
72
+
73
+ ```sh
74
+ kivel oauth create --ttl-seconds 3600 < provider.json
75
+ kivel oauth inspect <id>
76
+ kivel oauth calls <id>
77
+ kivel oauth update <id> < provider.json
78
+ kivel oauth renew <id>
79
+ kivel oauth delete <id>
80
+ ```
81
+
82
+ Use `oauth list` to list workspace providers. Configure your OAuth client with the
83
+ returned discovery URL and S256 PKCE. See the [OAuth guide](https://kivel.io/docs/mock-oauth/)
84
+ for headless approval, refresh tokens and failure scenarios. This service is for tests only.
package/bin/kivel.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli.js';
@@ -0,0 +1,3 @@
1
+ import type { Kivel } from '@kivel.io/sdk';
2
+ export declare function needsInput(args: string[]): boolean;
3
+ export declare function agentCommand(client: Kivel, args: string[], input: Uint8Array): Promise<unknown>;
@@ -0,0 +1,402 @@
1
+ export function needsInput(args) {
2
+ return (['run', 'upload'].includes(args[0] ?? '') ||
3
+ (args[0] === 'api' && !['GET', 'HEAD', 'OPTIONS', 'DELETE'].includes(args[1] ?? '')) ||
4
+ (args[0] === 'agent' && args[1] === 'token') ||
5
+ (args[0] === 'memory' && args[1] === 'set') ||
6
+ (args[0] === 'authenticator' && args[1] === 'add') ||
7
+ (args[0] === 'approval' && args[1] === 'ask') ||
8
+ (args[0] === 'monitor' && args[1] === 'create') ||
9
+ (args[0] === 'email' && ['draft-create', 'draft-submit'].includes(args[1] ?? '')) ||
10
+ (args[0] === 'event' && args[1] === 'wait') ||
11
+ (['oauth', 'mock', 'mcp-server', 'status-page', 'job'].includes(args[0] ?? '') &&
12
+ ['create', 'update'].includes(args[1] ?? '')) ||
13
+ (['inbox', 'email'].includes(args[0] ?? '') &&
14
+ ['response', 'forward', 'send'].includes(args[1] ?? '')));
15
+ }
16
+ export async function agentCommand(client, args, input) {
17
+ const [group, action, ...tail] = args;
18
+ const resource = [
19
+ 'inbox',
20
+ 'email',
21
+ 'mock',
22
+ 'oauth',
23
+ 'mcp-server',
24
+ 'file',
25
+ 'status-page',
26
+ 'job',
27
+ 'smtp',
28
+ ].includes(group ?? '');
29
+ const allowed = new Set();
30
+ if (resource && action !== 'create' && group !== 'oauth')
31
+ allowed.add('--token');
32
+ if ((group === 'email' && action === 'send') || (group === 'phone' && action === 'create'))
33
+ allowed.add('--idempotency-key');
34
+ if (resource && action === 'create') {
35
+ if (group === 'email') {
36
+ allowed.add('--active-days');
37
+ allowed.add('--local-part');
38
+ }
39
+ else {
40
+ allowed.add('--ttl-seconds');
41
+ allowed.add('--persistent');
42
+ if (group !== 'oauth')
43
+ allowed.add('--visibility');
44
+ }
45
+ }
46
+ if (resource && action === 'renew')
47
+ allowed.add('--persistent');
48
+ if (resource && action === 'sharing' && group !== 'email')
49
+ allowed.add('--visibility');
50
+ if ((resource || group === 'phone') && action === 'wait') {
51
+ allowed.add('--after');
52
+ allowed.add('--timeout-seconds');
53
+ }
54
+ if (group === 'email' && action === 'threads') {
55
+ allowed.add('--cursor');
56
+ allowed.add('--limit');
57
+ }
58
+ if (group === 'agent' && ['login', 'trial'].includes(action ?? ''))
59
+ allowed.add('--client');
60
+ if (group === 'agent' && action === 'trial')
61
+ allowed.add('--human-email');
62
+ if (group === 'memory' && action === 'set')
63
+ allowed.add('--ttl-seconds');
64
+ if (group === 'memory' && action === 'list')
65
+ allowed.add('--prefix');
66
+ if (group === 'approval' && action === 'wait')
67
+ allowed.add('--timeout-seconds');
68
+ if (group === 'event' && action === 'wait')
69
+ allowed.add('--timeout-seconds');
70
+ const positional = [];
71
+ const flags = new Map();
72
+ for (let i = 0; i < tail.length; i++) {
73
+ const value = tail[i];
74
+ if (!value.startsWith('--')) {
75
+ positional.push(value);
76
+ continue;
77
+ }
78
+ if (!allowed.has(value))
79
+ throw new Error(`Unknown option: ${value}`);
80
+ if (flags.has(value))
81
+ throw new Error(`Duplicate option: ${value}`);
82
+ if (value === '--persistent')
83
+ flags.set(value, 'true');
84
+ else {
85
+ const next = tail[++i];
86
+ if (next === undefined || next.startsWith('--'))
87
+ throw new Error(`Missing value: ${value}`);
88
+ flags.set(value, next);
89
+ }
90
+ }
91
+ const take = (key) => {
92
+ const value = flags.get(key);
93
+ flags.delete(key);
94
+ return value;
95
+ };
96
+ const number = (key) => {
97
+ const value = take(key);
98
+ if (value === undefined)
99
+ return undefined;
100
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))
101
+ throw new Error(`Invalid number: ${key}`);
102
+ return Number(value);
103
+ };
104
+ const token = take('--token');
105
+ const wait = { token, after: take('--after'), timeoutSeconds: number('--timeout-seconds') };
106
+ const settings = {
107
+ ttlSeconds: number('--ttl-seconds'),
108
+ persistent: take('--persistent') === 'true' || undefined,
109
+ };
110
+ const visibility = take('--visibility');
111
+ if (visibility !== undefined && visibility !== 'public' && visibility !== 'private')
112
+ throw new Error('visibility must be private or public.');
113
+ const clientName = take('--client'), humanEmail = take('--human-email');
114
+ const prefix = take('--prefix') ?? '';
115
+ const idempotencyKey = take('--idempotency-key');
116
+ const emailSettings = { activeDays: number('--active-days'), localPart: take('--local-part') };
117
+ const threadPage = { cursor: take('--cursor'), limit: number('--limit') };
118
+ if (flags.size)
119
+ throw new Error(`Unknown option: ${flags.keys().next().value}`);
120
+ const exact = (count) => {
121
+ if (positional.length !== count)
122
+ throw new Error(`Expected ${count} arguments for ${group} ${action}.`);
123
+ };
124
+ const id = () => {
125
+ exact(1);
126
+ return positional[0];
127
+ };
128
+ const json = () => JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(input));
129
+ if (group === 'oauth') {
130
+ if (action === 'create') {
131
+ exact(0);
132
+ return client.createOAuthProvider(json(), settings);
133
+ }
134
+ if (action === 'list') {
135
+ exact(0);
136
+ return client.oauthProviders();
137
+ }
138
+ if (action === 'inspect')
139
+ return client.oauthProvider(id());
140
+ if (action === 'update')
141
+ return client.updateOAuthProvider(id(), json());
142
+ if (action === 'delete')
143
+ return client.deleteOAuthProvider(id());
144
+ if (action === 'calls')
145
+ return client.request('GET', `/api/mocks/${encodeURIComponent(id())}/calls`);
146
+ if (action === 'renew')
147
+ return client.request('POST', `/api/mocks/${encodeURIComponent(id())}/renew`, {
148
+ persistent: settings.persistent ?? false,
149
+ });
150
+ }
151
+ if (group === 'event' && action === 'wait') {
152
+ exact(0);
153
+ const value = json();
154
+ return client.waitForEvent(value.sources, wait.timeoutSeconds ?? value.timeoutSeconds ?? 20);
155
+ }
156
+ if (group === 'agent') {
157
+ if (action === 'login')
158
+ return client.startLogin(id(), clientName);
159
+ if (action === 'trial')
160
+ return client.startTrial(id(), humanEmail, clientName);
161
+ if (action === 'token') {
162
+ exact(0);
163
+ const value = json();
164
+ if (typeof value?.deviceCode !== 'string')
165
+ throw new Error('Pipe {"deviceCode":"…"} to agent token.');
166
+ return client.finishLogin(value.deviceCode);
167
+ }
168
+ if (action === 'list') {
169
+ exact(0);
170
+ return client.agents();
171
+ }
172
+ }
173
+ if (group === 'authenticator') {
174
+ if (action === 'add') {
175
+ exact(0);
176
+ return client.addAuthenticator(json());
177
+ }
178
+ if (action === 'list') {
179
+ exact(0);
180
+ return client.listAuthenticators();
181
+ }
182
+ if (action === 'code')
183
+ return client.getTotpCode(id());
184
+ if (action === 'rename') {
185
+ exact(2);
186
+ return client.renameAuthenticator(positional[0], positional[1]);
187
+ }
188
+ if (action === 'delete')
189
+ return client.deleteAuthenticator(id());
190
+ }
191
+ if (group === 'email' && ['attachment', 'download-attachment'].includes(action ?? '')) {
192
+ exact(3);
193
+ return action === 'attachment'
194
+ ? client.getEmailAttachment(positional[0], positional[1], positional[2])
195
+ : client.downloadEmailAttachment(positional[0], positional[1], positional[2]);
196
+ }
197
+ if (group === 'memory') {
198
+ if (action === 'list')
199
+ return client.memoryList(id(), prefix);
200
+ exact(2);
201
+ const [namespace, key] = positional;
202
+ if (action === 'set')
203
+ return client.memorySet(namespace, key, json(), settings.ttlSeconds);
204
+ if (action === 'get')
205
+ return client.memoryGet(namespace, key);
206
+ if (action === 'delete')
207
+ return client.memoryDelete(namespace, key);
208
+ }
209
+ if (group === 'phone') {
210
+ if (action === 'available') {
211
+ if (positional.length > 1)
212
+ throw new Error('Use an optional US area code.');
213
+ return client.availablePhoneNumbers(positional[0]);
214
+ }
215
+ if (action === 'create') {
216
+ exact(1);
217
+ if (!idempotencyKey)
218
+ throw new Error('Provide --idempotency-key and retain it for this purchase.');
219
+ return client.createPhoneNumber(positional[0], idempotencyKey);
220
+ }
221
+ if (action === 'list') {
222
+ exact(0);
223
+ return client.listPhoneNumbers();
224
+ }
225
+ if (action === 'release')
226
+ return client.releasePhoneNumber(id());
227
+ if (action === 'messages')
228
+ return client.listSms(id());
229
+ if (action === 'wait')
230
+ return client.waitForSms(id(), {
231
+ ...(wait.after ? { after: wait.after } : {}),
232
+ ...(wait.timeoutSeconds ? { timeoutSeconds: wait.timeoutSeconds } : {}),
233
+ });
234
+ }
235
+ if (group === 'smtp' && action === 'create') {
236
+ exact(0);
237
+ return client.createSmtpInbox(settings);
238
+ }
239
+ if (group === 'smtp' && action === 'inspect')
240
+ return client.smtpInbox(id());
241
+ if (group === 'smtp' && action === 'rotate')
242
+ return client.rotateSmtpPassword(id());
243
+ if (group === 'job' && action === 'create') {
244
+ exact(0);
245
+ return client.createScheduledJob(json(), settings);
246
+ }
247
+ if (group === 'job' && action === 'list') {
248
+ exact(0);
249
+ return client.scheduledJobs();
250
+ }
251
+ if (group === 'job' && action === 'inspect') {
252
+ exact(1);
253
+ return client.scheduledJob(id());
254
+ }
255
+ if (group === 'job' && action === 'cancel') {
256
+ exact(1);
257
+ return client.cancelScheduledJob(id());
258
+ }
259
+ if (group === 'status-page' && action === 'create') {
260
+ exact(0);
261
+ return client.createStatusPage(json(), {
262
+ ...settings,
263
+ ...(visibility ? { visibility } : {}),
264
+ });
265
+ }
266
+ if (group === 'status-page' && action === 'update')
267
+ return client.updateStatusPage(id(), json());
268
+ if (group === 'monitor') {
269
+ if (action === 'accept-dns')
270
+ return client.acceptDnsChanges(id());
271
+ if (action === 'create') {
272
+ exact(0);
273
+ return client.createMonitor(json());
274
+ }
275
+ if (action === 'list') {
276
+ exact(0);
277
+ return client.monitors();
278
+ }
279
+ if (action === 'inspect')
280
+ return client.monitor(id());
281
+ if (action === 'ping' || action === 'fail')
282
+ return client.pingMonitor(id(), action === 'fail');
283
+ if (action === 'pause' || action === 'resume')
284
+ return client.pauseMonitor(id(), action === 'pause');
285
+ if (action === 'delete')
286
+ return client.deleteMonitor(id());
287
+ }
288
+ if (group === 'approval') {
289
+ if (action === 'ask') {
290
+ exact(0);
291
+ return client.askHuman(json());
292
+ }
293
+ if (action === 'list' || action === 'pending') {
294
+ exact(0);
295
+ return client.approvals(action === 'pending');
296
+ }
297
+ if (action === 'inspect')
298
+ return client.approval(id());
299
+ if (action === 'wait')
300
+ return client.waitForApproval(id(), wait.timeoutSeconds);
301
+ }
302
+ if (group === 'inbox') {
303
+ if (action === 'requests')
304
+ return client.inspectInbox(id(), token);
305
+ if (action === 'wait')
306
+ return client.waitForRequests(id(), wait);
307
+ if (action === 'response')
308
+ return client.setInboxResponse(id(), json(), token);
309
+ if (action === 'forward') {
310
+ const body = json();
311
+ return client.setInboxForward(id(), body === null ? null : body.url, token);
312
+ }
313
+ if (action === 'deliveries')
314
+ return client.inboxDeliveries(id(), token);
315
+ }
316
+ if (group === 'email') {
317
+ if (action === 'threads') {
318
+ if (positional.length > 1)
319
+ throw new Error('Provide at most one inbox ID.');
320
+ return client.emailThreads(positional[0], threadPage);
321
+ }
322
+ if (action === 'thread') {
323
+ exact(2);
324
+ return client.emailThread(positional[0], positional[1]);
325
+ }
326
+ if (action === 'draft-create')
327
+ return client.createEmailDraft(id(), json());
328
+ if (action === 'drafts')
329
+ return client.emailDrafts(id());
330
+ if (action === 'draft-inspect')
331
+ return client.emailDraft(id());
332
+ if (action === 'draft-submit')
333
+ return client.submitEmailDraft(id(), input.length ? json() : {});
334
+ if (action === 'draft-delete')
335
+ return client.deleteEmailDraft(id());
336
+ if (action === 'rules')
337
+ return client.emailInboxRules(id());
338
+ if (action === 'clear')
339
+ return client.clearEmails(id(), token);
340
+ if (action === 'send') {
341
+ if (!idempotencyKey)
342
+ throw new Error('Provide --idempotency-key and reuse it only when retrying this same message.');
343
+ const value = json();
344
+ return client.sendEmail(id(), { ...value, idempotencyKey });
345
+ }
346
+ if (action === 'list') {
347
+ exact(0);
348
+ return client.emailInboxes();
349
+ }
350
+ if (action === 'forward') {
351
+ const value = json();
352
+ if (value?.url !== null && typeof value?.url !== 'string')
353
+ throw new Error('Pipe {"url":"https://your-webhook"}, or {"url":null} to disable forwarding.');
354
+ return client.emailForwarding(id(), value.url, token);
355
+ }
356
+ if (action === 'create') {
357
+ exact(0);
358
+ return client.createEmailInbox(emailSettings);
359
+ }
360
+ if (action === 'messages')
361
+ return client.emails(id(), token);
362
+ if (action === 'wait')
363
+ return client.waitForEmail(id(), wait);
364
+ }
365
+ if (group === 'mock' || group === 'mcp-server') {
366
+ if (action === 'create') {
367
+ exact(0);
368
+ return group === 'mock'
369
+ ? client.createMock(json(), { ...settings, visibility })
370
+ : client.createMcpServer(json(), { ...settings, visibility });
371
+ }
372
+ if (action === 'update' && group === 'mock')
373
+ return client.updateMock(id(), json(), token);
374
+ if (action === 'reset' && group === 'mock')
375
+ return client.resetMock(id(), token);
376
+ if (action === 'calls' && group === 'mock')
377
+ return client.mockCalls(id(), token);
378
+ }
379
+ const kinds = {
380
+ inbox: 'inboxes',
381
+ email: 'email-inboxes',
382
+ 'status-page': 'status-pages',
383
+ mock: 'mocks',
384
+ 'mcp-server': 'mcp-servers',
385
+ file: 'files',
386
+ };
387
+ const kind = Object.hasOwn(kinds, group ?? '') ? kinds[group] : undefined;
388
+ if (kind) {
389
+ if (action === 'inspect')
390
+ return client.inspectResource(kind, id(), token);
391
+ if (action === 'delete')
392
+ return client.remove(kind, id(), token);
393
+ if (action === 'renew')
394
+ return client.renew(kind, id(), settings, token);
395
+ if (action === 'sharing' && kind !== 'email-inboxes') {
396
+ if (!visibility)
397
+ throw new Error('Provide --visibility private|public.');
398
+ return client.sharing(kind, id(), visibility, token);
399
+ }
400
+ }
401
+ throw new Error('Unknown command. Run kivel --help.');
402
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process';
3
+ import { Buffer } from 'node:buffer';
4
+ import { Kivel, KivelError } from '@kivel.io/sdk';
5
+ import { command, needsInput as commandNeedsInput } from './commands.js';
6
+ import { listen } from './listen.js';
7
+ // KIVEL_* variables, with the SOCKET_HELP_* names from before the rename still accepted.
8
+ const env = (name) => process.env[`KIVEL_${name}`] ?? process.env[`SOCKET_HELP_${name}`];
9
+ try {
10
+ const args = process.argv.slice(2);
11
+ const needsInput = commandNeedsInput(args);
12
+ const chunks = [];
13
+ let size = 0;
14
+ if (needsInput && !process.stdin.isTTY)
15
+ for await (const chunk of process.stdin) {
16
+ size += chunk.length;
17
+ if (size > 10 * 1024 * 1024)
18
+ throw new Error('Input exceeds 10 MiB.');
19
+ chunks.push(Buffer.from(chunk));
20
+ }
21
+ const client = new Kivel({
22
+ ...(env('URL') ? { baseUrl: env('URL') } : {}),
23
+ ...(env('API_KEY') ? { apiKey: env('API_KEY') } : {}),
24
+ timeoutMs: 90000,
25
+ });
26
+ if (args[0] === 'listen' && args[1]) {
27
+ const options = {};
28
+ for (let index = 2; index < args.length; index++) {
29
+ const flag = args[index];
30
+ if (flag === '--all')
31
+ options.all = true;
32
+ else if (flag === '--token' && args[index + 1])
33
+ options.token = args[++index];
34
+ else if (flag === '--forward' && args[index + 1])
35
+ options.forward = args[++index];
36
+ else
37
+ throw new Error(`Unknown option: ${flag}`);
38
+ }
39
+ const stop = new AbortController();
40
+ process.once('SIGINT', () => {
41
+ stop.abort();
42
+ process.exit(0);
43
+ });
44
+ await listen(client, args[1], options, (line) => process.stdout.write(`${JSON.stringify(line)}\n`), stop.signal);
45
+ process.exit(0);
46
+ }
47
+ const accessToken = env('ACCESS_TOKEN');
48
+ if (args[0] === 'download' && args.length === 2 && accessToken)
49
+ args.push('--access-token', accessToken);
50
+ const result = await command(client, args, Buffer.concat(chunks));
51
+ if (!args.length || ['--help', 'help'].includes(args[0]))
52
+ process.stdout.write(`${result.help}\n`);
53
+ else if (args.length === 1 && args[0] === '--version')
54
+ process.stdout.write(`${result.version}\n`);
55
+ else if (result instanceof Uint8Array)
56
+ process.stdout.write(result);
57
+ else if (result !== undefined)
58
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
59
+ }
60
+ catch (error) {
61
+ process.stderr.write(`${JSON.stringify({ error: error instanceof Error ? error.message : 'Command failed.', ...(error instanceof KivelError ? { status: error.status, requestId: error.requestId, retryAfter: error.retryAfter, requiredPlan: error.requiredPlan, upgradeUrl: error.upgradeUrl } : {}) })}\n`);
62
+ process.exitCode = 1;
63
+ }
@@ -0,0 +1,4 @@
1
+ export { needsInput } from './agent-commands.js';
2
+ import type { Kivel } from '@kivel.io/sdk';
3
+ export declare const help = "kivel tools | usage | resources\nkivel --version\nkivel plans | activity\nkivel agent login <name> [--client <client>]\nkivel agent token < login.json\nkivel agent trial <name> [--human-email <email>] [--client <client>]\nkivel agent list\nkivel authenticator add < authenticator.json\nkivel authenticator list|code|delete [id]\nkivel authenticator rename <id> <name>\nkivel email attachment|download-attachment <inbox-id> <message-id> <attachment-id>\nkivel email create [--active-days <1-7>] [--local-part <paid-address>]\nkivel email list\nkivel email clear <id>\nkivel email forward <id> [--token <token>] < forwarding.json\nkivel email send <id> --idempotency-key <unique-key> < message.json\nkivel event wait [--timeout-seconds <1-30>] < sources.json\nkivel email threads [inbox-id] [--cursor <cursor>] [--limit <n>]\nkivel email thread <inbox-id> <thread-id>\nkivel email drafts|rules <inbox-id>\nkivel email draft-create <inbox-id> < content.json\nkivel email draft-inspect|draft-delete <draft-id>\nkivel email draft-submit <draft-id> [< settings.json]\nkivel email messages|wait <id> [--token <token>] [--after <id>] [--timeout-seconds <n>]\nkivel memory set <namespace> <key> [--ttl-seconds <n>] < value.json\nkivel memory get|delete <namespace> <key>\nkivel memory list <namespace> [--prefix <prefix>]\nkivel monitor create < monitor.json\nkivel monitor list|inspect|pause|resume|delete [id]\nkivel monitor ping|fail <ping-token>\nkivel monitor accept-dns <id>\nkivel job create [--ttl-seconds <n>] < job.json\nkivel job list|inspect|cancel [id]\nkivel status-page create|update [id] < page.json\nkivel smtp create [--ttl-seconds <n>]\nkivel smtp rotate <id>\nkivel phone available [US-area-code]\nkivel phone create <E.164-number> --idempotency-key <unique-key>\nkivel phone list|release|messages|wait [id] [--after <id>] [--timeout-seconds <n>]\nkivel approval ask < question.json\nkivel approval list|pending|inspect|wait [id] [--timeout-seconds <n>]\nkivel inbox requests|wait|deliveries <id> [--token <token>]\nkivel inbox response|forward <id> [--token <token>] < settings.json\nkivel oauth create [--ttl-seconds <n>] < provider.json\nkivel oauth update <id> < provider.json\nkivel oauth list|inspect|calls|renew|delete [id]\nkivel mock create|update [id] < config.json\nkivel mock calls|reset <id> [--token <token>]\nkivel mcp-server create < config.json\nkivel inbox|email|mock|mcp-server|file inspect|delete|renew <id> [--token <token>]\nkivel inbox|mock|mcp-server|file sharing <id> --visibility private|public [--token <token>]\nkivel describe <tool-id>\nkivel run <tool-id> [--file <filename>] [--options '{\"action\":\"minify\"}'] < input.txt\nkivel inbox create [--visibility private|public]\nkivel listen <inbox-id> [--token <inspection-token>] [--forward http://localhost:3000] [--all]\nkivel api <GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE> /api/path-or-/mock/path [--token <resource-token>] < body.json\nkivel upload <filename> [--visibility private|public] [--max-downloads 1] < file.bin\nkivel download <file-id> [--access-token token] > file.bin\n\nSet KIVEL_URL and KIVEL_API_KEY. Commands output JSON; downloads output binary; help is plain text. Mutations are never retried. Authenticators are only for accounts your human asked you to create or operate. Attachment downloads output untrusted binary files; attachment links expire in two minutes.\nCreation also accepts --ttl-seconds <n> and --persistent. Webhook receiving is public by default; inspection always needs workspace credentials or the inspection token. Use inbox create --visibility private only when senders can add X-Access-Token. Other resources default to private.";
4
+ export declare function command(client: Kivel, args: string[], input?: Uint8Array): Promise<unknown>;
@@ -0,0 +1,158 @@
1
+ import { VERSION } from './version.js';
2
+ import { agentCommand } from './agent-commands.js';
3
+ export { needsInput } from './agent-commands.js';
4
+ export const help = `kivel tools | usage | resources
5
+ kivel --version
6
+ kivel plans | activity
7
+ kivel agent login <name> [--client <client>]
8
+ kivel agent token < login.json
9
+ kivel agent trial <name> [--human-email <email>] [--client <client>]
10
+ kivel agent list
11
+ kivel authenticator add < authenticator.json
12
+ kivel authenticator list|code|delete [id]
13
+ kivel authenticator rename <id> <name>
14
+ kivel email attachment|download-attachment <inbox-id> <message-id> <attachment-id>
15
+ kivel email create [--active-days <1-7>] [--local-part <paid-address>]
16
+ kivel email list
17
+ kivel email clear <id>
18
+ kivel email forward <id> [--token <token>] < forwarding.json
19
+ kivel email send <id> --idempotency-key <unique-key> < message.json
20
+ kivel event wait [--timeout-seconds <1-30>] < sources.json
21
+ kivel email threads [inbox-id] [--cursor <cursor>] [--limit <n>]
22
+ kivel email thread <inbox-id> <thread-id>
23
+ kivel email drafts|rules <inbox-id>
24
+ kivel email draft-create <inbox-id> < content.json
25
+ kivel email draft-inspect|draft-delete <draft-id>
26
+ kivel email draft-submit <draft-id> [< settings.json]
27
+ kivel email messages|wait <id> [--token <token>] [--after <id>] [--timeout-seconds <n>]
28
+ kivel memory set <namespace> <key> [--ttl-seconds <n>] < value.json
29
+ kivel memory get|delete <namespace> <key>
30
+ kivel memory list <namespace> [--prefix <prefix>]
31
+ kivel monitor create < monitor.json
32
+ kivel monitor list|inspect|pause|resume|delete [id]
33
+ kivel monitor ping|fail <ping-token>
34
+ kivel monitor accept-dns <id>
35
+ kivel job create [--ttl-seconds <n>] < job.json
36
+ kivel job list|inspect|cancel [id]
37
+ kivel status-page create|update [id] < page.json
38
+ kivel smtp create [--ttl-seconds <n>]
39
+ kivel smtp rotate <id>
40
+ kivel phone available [US-area-code]
41
+ kivel phone create <E.164-number> --idempotency-key <unique-key>
42
+ kivel phone list|release|messages|wait [id] [--after <id>] [--timeout-seconds <n>]
43
+ kivel approval ask < question.json
44
+ kivel approval list|pending|inspect|wait [id] [--timeout-seconds <n>]
45
+ kivel inbox requests|wait|deliveries <id> [--token <token>]
46
+ kivel inbox response|forward <id> [--token <token>] < settings.json
47
+ kivel oauth create [--ttl-seconds <n>] < provider.json
48
+ kivel oauth update <id> < provider.json
49
+ kivel oauth list|inspect|calls|renew|delete [id]
50
+ kivel mock create|update [id] < config.json
51
+ kivel mock calls|reset <id> [--token <token>]
52
+ kivel mcp-server create < config.json
53
+ kivel inbox|email|mock|mcp-server|file inspect|delete|renew <id> [--token <token>]
54
+ kivel inbox|mock|mcp-server|file sharing <id> --visibility private|public [--token <token>]
55
+ kivel describe <tool-id>
56
+ kivel run <tool-id> [--file <filename>] [--options '{"action":"minify"}'] < input.txt
57
+ kivel inbox create [--visibility private|public]
58
+ kivel listen <inbox-id> [--token <inspection-token>] [--forward http://localhost:3000] [--all]
59
+ kivel api <GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE> /api/path-or-/mock/path [--token <resource-token>] < body.json
60
+ kivel upload <filename> [--visibility private|public] [--max-downloads 1] < file.bin
61
+ kivel download <file-id> [--access-token token] > file.bin
62
+
63
+ Set KIVEL_URL and KIVEL_API_KEY. Commands output JSON; downloads output binary; help is plain text. Mutations are never retried. Authenticators are only for accounts your human asked you to create or operate. Attachment downloads output untrusted binary files; attachment links expire in two minutes.
64
+ Creation also accepts --ttl-seconds <n> and --persistent. Webhook receiving is public by default; inspection always needs workspace credentials or the inspection token. Use inbox create --visibility private only when senders can add X-Access-Token. Other resources default to private.`;
65
+ function settings(args, file = false) {
66
+ const result = {};
67
+ const seen = new Set();
68
+ for (let index = 2; index < args.length; index++) {
69
+ const flag = args[index];
70
+ if (seen.has(flag))
71
+ throw new Error(`Duplicate option: ${flag}`);
72
+ seen.add(flag);
73
+ if (flag === '--persistent') {
74
+ result.persistent = true;
75
+ continue;
76
+ }
77
+ const value = args[++index];
78
+ if (flag === '--visibility' && (value === 'private' || value === 'public'))
79
+ result.visibility = value;
80
+ else if (flag === '--ttl-seconds' &&
81
+ value &&
82
+ /^\d+$/.test(value) &&
83
+ Number.isSafeInteger(Number(value)) &&
84
+ Number(value) >= 60)
85
+ result.ttlSeconds = Number(value);
86
+ else if (flag === '--max-downloads' &&
87
+ file &&
88
+ value &&
89
+ /^\d+$/.test(value) &&
90
+ Number.isSafeInteger(Number(value)) &&
91
+ Number(value) >= 1 &&
92
+ Number(value) <= 1000)
93
+ result.maxDownloads = Number(value);
94
+ else
95
+ throw new Error(`Invalid option or value: ${flag}`);
96
+ }
97
+ return result;
98
+ }
99
+ export async function command(client, args, input = new Uint8Array()) {
100
+ if (args.length === 1 && args[0] === '--version')
101
+ return { version: VERSION };
102
+ if (!args.length || args[0] === '--help' || args[0] === 'help')
103
+ return { help };
104
+ const text = () => new TextDecoder('utf-8', { fatal: true }).decode(input);
105
+ if (args.length === 1 && args[0] === 'tools')
106
+ return client.tools();
107
+ if (args.length === 2 && args[0] === 'describe')
108
+ return client.tool(args[1]);
109
+ if (args.length === 1 && args[0] === 'plans')
110
+ return client.plans();
111
+ if (args.length === 1 && args[0] === 'activity')
112
+ return client.activity();
113
+ if (args.length === 1 && args[0] === 'usage')
114
+ return client.usage();
115
+ if (args.length === 1 && args[0] === 'resources')
116
+ return client.resources();
117
+ if (args[0] === 'run' && args[1]) {
118
+ let options = {}, fileName;
119
+ const seen = new Set();
120
+ for (let index = 2; index < args.length; index += 2) {
121
+ const flag = args[index], value = args[index + 1];
122
+ if (seen.has(flag) || value === undefined)
123
+ throw new Error(`Invalid or duplicate option: ${flag}`);
124
+ seen.add(flag);
125
+ if (flag === '--options') {
126
+ const parsed = JSON.parse(value);
127
+ if (!parsed ||
128
+ typeof parsed !== 'object' ||
129
+ Array.isArray(parsed) ||
130
+ Object.values(parsed).some((item) => typeof item !== 'string'))
131
+ throw new Error('Options must be a JSON object of strings.');
132
+ options = parsed;
133
+ }
134
+ else if (flag === '--file' && value && value.length <= 150)
135
+ fileName = value;
136
+ else
137
+ throw new Error(`Invalid option: ${flag}`);
138
+ }
139
+ return client.run(args[1], fileName ? '' : text(), options, fileName
140
+ ? { name: fileName, base64: Buffer.from(input).toString('base64') }
141
+ : undefined);
142
+ }
143
+ if (args[0] === 'inbox' && args[1] === 'create')
144
+ return client.createInbox(settings(args));
145
+ if (args[0] === 'upload' && args[1])
146
+ return client.upload(args[1], input, settings(args, true));
147
+ if (args[0] === 'download' &&
148
+ args[1] &&
149
+ (args.length === 2 || (args.length === 4 && args[2] === '--access-token')))
150
+ return client.downloadFile(args[1], args[3]);
151
+ if (args[0] === 'api' &&
152
+ args[1] &&
153
+ args[2] &&
154
+ /^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)$/.test(args[1]) &&
155
+ (args.length === 3 || (args.length === 5 && args[3] === '--token')))
156
+ return client.request(args[1], args[2], input.length ? JSON.parse(text()) : undefined, args[4]);
157
+ return agentCommand(client, args, input);
158
+ }
@@ -0,0 +1,10 @@
1
+ import type { CapturedRequest, Kivel } from '@kivel.io/sdk';
2
+ export interface ListenOptions {
3
+ token?: string;
4
+ forward?: string;
5
+ all?: boolean;
6
+ }
7
+ export declare function forwardTarget(base: string, inboxId: string, request: CapturedRequest): URL;
8
+ export declare function forwardHeaders(request: CapturedRequest): Headers;
9
+ /** Streams new requests as JSON lines and optionally replays each one to a local server. */
10
+ export declare function listen(client: Kivel, inboxId: string, options: ListenOptions, write: (line: object) => void, signal?: AbortSignal): Promise<void>;
package/dist/listen.js ADDED
@@ -0,0 +1,81 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { KivelError } from '@kivel.io/sdk';
3
+ // Hop-by-hop and proxy headers describe the trip to Kivel, not the original sender.
4
+ const dropped = /^(host|content-length|connection|keep-alive|transfer-encoding|upgrade|te|trailer|proxy-.*|x-forwarded-.*|x-real-ip|cf-.*|cdn-loop|true-client-ip|x-access-token|authorization)$/i;
5
+ export function forwardTarget(base, inboxId, request) {
6
+ const url = new URL(base);
7
+ const suffix = request.path.replace(new RegExp(`^/hooks/${inboxId}`), '');
8
+ url.pathname = `${url.pathname.replace(/\/$/, '')}${suffix}` || '/';
9
+ for (const [key, value] of Object.entries(request.query))
10
+ for (const item of Array.isArray(value) ? value : [value])
11
+ url.searchParams.append(key, item);
12
+ return url;
13
+ }
14
+ export function forwardHeaders(request) {
15
+ const headers = new Headers();
16
+ for (const [key, value] of Object.entries(request.headers))
17
+ if (!dropped.test(key))
18
+ for (const item of Array.isArray(value) ? value : [value])
19
+ headers.append(key, item);
20
+ return headers;
21
+ }
22
+ /** Streams new requests as JSON lines and optionally replays each one to a local server. */
23
+ export async function listen(client, inboxId, options, write, signal) {
24
+ if (options.forward)
25
+ new URL(options.forward);
26
+ let after;
27
+ if (!options.all) {
28
+ const existing = (await client.inspectInbox(inboxId, options.token));
29
+ after = existing.requests.at(-1)?.id;
30
+ }
31
+ write({ event: 'listening', inboxId, forward: options.forward ?? null });
32
+ while (!signal?.aborted) {
33
+ let batch;
34
+ try {
35
+ batch = await client.waitForRequests(inboxId, {
36
+ ...(options.token ? { token: options.token } : {}),
37
+ ...(after ? { after } : {}),
38
+ });
39
+ }
40
+ catch (error) {
41
+ if (error instanceof KivelError && error.status === 429) {
42
+ await new Promise((resolve) => setTimeout(resolve, (error.retryAfter ?? 2) * 1000));
43
+ continue;
44
+ }
45
+ throw error;
46
+ }
47
+ for (const request of batch.requests) {
48
+ after = request.id;
49
+ write({ event: 'request', request });
50
+ if (!options.forward)
51
+ continue;
52
+ const started = Date.now();
53
+ try {
54
+ const body = request.method === 'GET' || request.method === 'HEAD'
55
+ ? undefined
56
+ : Buffer.from(request.body, request.bodyEncoding);
57
+ const response = await fetch(forwardTarget(options.forward, inboxId, request), {
58
+ method: request.method,
59
+ headers: forwardHeaders(request),
60
+ ...(body ? { body } : {}),
61
+ redirect: 'manual',
62
+ signal: AbortSignal.timeout(10000),
63
+ });
64
+ await response.arrayBuffer();
65
+ write({
66
+ event: 'forwarded',
67
+ requestId: request.id,
68
+ status: response.status,
69
+ durationMs: Date.now() - started,
70
+ });
71
+ }
72
+ catch (error) {
73
+ write({
74
+ event: 'forward-failed',
75
+ requestId: request.id,
76
+ error: error instanceof Error ? error.message : 'Forwarding failed.',
77
+ });
78
+ }
79
+ }
80
+ }
81
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION: string;
@@ -0,0 +1,2 @@
1
+ import { readFileSync } from 'node:fs';
2
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@kivel.io/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.6.1",
4
+ "type": "module",
5
+ "bin": {
6
+ "kivel": "./bin/kivel.mjs"
7
+ },
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/commands.d.ts",
11
+ "import": "./dist/commands.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist/**/*.js",
16
+ "dist/**/*.d.ts",
17
+ "bin",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "dependencies": {
21
+ "@kivel.io/sdk": "0.6.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^26.6.5",
25
+ "tsx": "^4.23.15",
26
+ "typescript": "^7.0.2"
27
+ },
28
+ "description": "Command-line client for Kivel: agent workflows, API tools, webhooks, email and files.",
29
+ "license": "Apache-2.0",
30
+ "engines": {
31
+ "node": ">=22.13.0"
32
+ },
33
+ "homepage": "https://kivel.io/docs/cli/",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/TangoBeee/kivel.git",
37
+ "directory": "packages/cli"
38
+ },
39
+ "bugs": {
40
+ "email": "support@kivel.io"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "registry": "https://registry.npmjs.org/",
45
+ "tag": "beta"
46
+ },
47
+ "main": "./dist/commands.js",
48
+ "types": "./dist/commands.d.ts",
49
+ "scripts": {
50
+ "build": "node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && tsc -p tsconfig.json",
51
+ "typecheck": "tsc -p tsconfig.json --noEmit",
52
+ "test": "node --import tsx --test src/listen.test.ts"
53
+ }
6
54
  }