@ciphrix/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +201 -0
  3. package/dist/actions.d.ts +19 -0
  4. package/dist/actions.js +30 -0
  5. package/dist/api.d.ts +27 -0
  6. package/dist/api.js +180 -0
  7. package/dist/banner.d.ts +2 -0
  8. package/dist/banner.js +12 -0
  9. package/dist/browser.d.ts +2 -0
  10. package/dist/browser.js +44 -0
  11. package/dist/cli.d.ts +14 -0
  12. package/dist/cli.js +1579 -0
  13. package/dist/commands/asset.d.ts +59 -0
  14. package/dist/commands/asset.js +237 -0
  15. package/dist/commands/check.d.ts +30 -0
  16. package/dist/commands/check.js +182 -0
  17. package/dist/commands/context.d.ts +23 -0
  18. package/dist/commands/context.js +102 -0
  19. package/dist/commands/control.d.ts +44 -0
  20. package/dist/commands/control.js +189 -0
  21. package/dist/commands/framework.d.ts +40 -0
  22. package/dist/commands/framework.js +181 -0
  23. package/dist/commands/job.d.ts +16 -0
  24. package/dist/commands/job.js +30 -0
  25. package/dist/commands/login.d.ts +12 -0
  26. package/dist/commands/login.js +54 -0
  27. package/dist/commands/logout.d.ts +9 -0
  28. package/dist/commands/logout.js +56 -0
  29. package/dist/commands/policy.d.ts +23 -0
  30. package/dist/commands/policy.js +112 -0
  31. package/dist/commands/policyActions.d.ts +37 -0
  32. package/dist/commands/policyActions.js +177 -0
  33. package/dist/commands/risk.d.ts +51 -0
  34. package/dist/commands/risk.js +289 -0
  35. package/dist/commands/test.d.ts +54 -0
  36. package/dist/commands/test.js +331 -0
  37. package/dist/commands/vendor.d.ts +45 -0
  38. package/dist/commands/vendor.js +218 -0
  39. package/dist/config.d.ts +12 -0
  40. package/dist/config.js +56 -0
  41. package/dist/constants.d.ts +7 -0
  42. package/dist/constants.js +7 -0
  43. package/dist/credentials.d.ts +19 -0
  44. package/dist/credentials.js +182 -0
  45. package/dist/deviceFlow.d.ts +32 -0
  46. package/dist/deviceFlow.js +115 -0
  47. package/dist/deviceInfo.d.ts +11 -0
  48. package/dist/deviceInfo.js +25 -0
  49. package/dist/index.d.ts +2 -0
  50. package/dist/index.js +4 -0
  51. package/dist/io.d.ts +46 -0
  52. package/dist/io.js +99 -0
  53. package/dist/output.d.ts +14 -0
  54. package/dist/output.js +37 -0
  55. package/dist/theme.d.ts +25 -0
  56. package/dist/theme.js +39 -0
  57. package/dist/toolSurface.d.ts +20 -0
  58. package/dist/toolSurface.js +49 -0
  59. package/dist/upload.d.ts +18 -0
  60. package/dist/upload.js +115 -0
  61. package/package.json +71 -0
  62. package/skills/ciphrix/SKILL.md +169 -0
  63. package/skills/ciphrix/references/commands.md +1592 -0
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,201 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="assets/brand/logo_dark_mode.svg">
4
+ <source media="(prefers-color-scheme: light)" srcset="assets/brand/logo_light_mode.svg">
5
+ <img alt="Ciphrix" src="assets/brand/logo_light_mode.svg" width="360">
6
+ </picture>
7
+ </p>
8
+
9
+ <h1 align="center">Ciphrix CLI</h1>
10
+
11
+ <p align="center">
12
+ Compliance work, wherever you and your agents work.
13
+ </p>
14
+
15
+ The official command-line interface for the [Ciphrix](https://ciphrix.com) compliance platform.
16
+ Use Ciphrix from your terminal, scripts, and agent workspaces to understand compliance context, work with
17
+ policies and evidence, run tests, and manage frameworks, controls, assets, vendors, risks, and monitoring.
18
+
19
+ ## Install
20
+
21
+ Requires Node.js 20.19 or newer.
22
+
23
+ ```bash
24
+ npm install --global @ciphrix/cli
25
+ ciphrix login
26
+ ```
27
+
28
+ Or run a command without installing:
29
+
30
+ ```bash
31
+ npx @ciphrix/cli --help
32
+ ```
33
+
34
+ Update an existing global installation with `npm install --global @ciphrix/cli@latest`.
35
+
36
+ `ciphrix login` opens the Ciphrix authorization page in your browser and prints the same link and device
37
+ code in the terminal. Your password is never entered into the CLI.
38
+
39
+ <p align="center">
40
+ <img alt="Ciphrix CLI help and document library" src="assets/readme/ciphrix-cli.jpg" width="824">
41
+ </p>
42
+
43
+ ## From question to evidence
44
+
45
+ ```bash
46
+ # Understand the organisation before changing anything
47
+ ciphrix context get business
48
+
49
+ # Find a policy and read it as Markdown
50
+ ciphrix document list
51
+ ciphrix document get "Access Control Policy"
52
+
53
+ # See what a test covers and inspect its history
54
+ ciphrix test links "MFA enforced"
55
+ ciphrix test runs "MFA enforced"
56
+
57
+ # Record a formal result
58
+ ciphrix test run result "MFA enforced" \
59
+ --status passing \
60
+ --note "Rolled out organisation-wide"
61
+ ```
62
+
63
+ Add `--json` to any command for stable machine-readable output. Commands that perform consequential
64
+ changes show the proposed action and ask for confirmation; automation can opt in with `--yes`.
65
+
66
+ ## One interface for compliance work
67
+
68
+ - **Understand the business** — read Business and Operating Context before proposing or changing controls.
69
+ - **Work with policies** — find documents, read Markdown, manage versions, and move work through review.
70
+ - **Connect evidence to assurance** — inspect tests and runs, attach evidence, and record formal results.
71
+ - **Navigate the compliance model** — trace frameworks, clauses, controls, tests, documents, and assets.
72
+ - **Manage operational registers** — work with assets, vendors, risks, treatments, ownership, and files.
73
+ - **Operate monitoring** — inspect checks, resources, runs, findings, integrations, and background jobs.
74
+
75
+ Names and stable Ciphrix codes are accepted throughout, so neither people nor agents need to work with
76
+ opaque database identifiers.
77
+
78
+ ## Built for agent workspaces
79
+
80
+ Ciphrix ships an agent skill as well as a CLI. The CLI provides the tools; the skill teaches an agent the
81
+ Ciphrix domain model, operating principles, authority boundaries, and reliable workflows.
82
+
83
+ Install the skill with the open [Skills CLI](https://skills.sh/docs/cli):
84
+
85
+ ```bash
86
+ # Choose detected agents and installation scope interactively
87
+ npx skills add CiphrixHQ/ciphrix-cli --skill ciphrix
88
+
89
+ # Or install globally for selected agents
90
+ npx skills add CiphrixHQ/ciphrix-cli --skill ciphrix \
91
+ -g \
92
+ -a codex \
93
+ -a claude-code \
94
+ -a cursor \
95
+ -a opencode
96
+ ```
97
+
98
+ The skill works with compatible agent harnesses including Codex, Claude Code, Cursor, and OpenCode. It
99
+ is also included in the npm package at [`skills/ciphrix/SKILL.md`](skills/ciphrix/SKILL.md). Installing
100
+ the npm package never modifies an agent's configuration directories.
101
+
102
+ Run `npx skills update` to update installed skills when a newer version is available.
103
+
104
+ ### Ask in natural language, operate through the CLI
105
+
106
+ An agent can translate a request into a Ciphrix command, inspect the structured result, and present the
107
+ answer in the workspace where the user is already working.
108
+
109
+ <p align="center">
110
+ <img alt="An agent uses Ciphrix CLI to inspect the vendor register" src="assets/readme/pi-harness-1.jpg" width="960">
111
+ </p>
112
+
113
+ ### Work with evidence from ChatGPT
114
+
115
+ The same command surface supports multi-step compliance work: inspect a run, reopen it, attach evidence,
116
+ return it to its intended state, and explain the resulting evidence assessment.
117
+
118
+ <table>
119
+ <tr>
120
+ <td width="50%" align="center">
121
+ <img alt="Reopen a compliance test run and attach evidence from ChatGPT" src="assets/readme/chatgpt-2.jpg">
122
+ </td>
123
+ <td width="50%" align="center">
124
+ <img alt="Review the updated run and evidence relevance in ChatGPT" src="assets/readme/chatgpt-1.jpg">
125
+ </td>
126
+ </tr>
127
+ <tr>
128
+ <td align="center"><sub>Reopen the run and attach new evidence</sub></td>
129
+ <td align="center"><sub>Confirm the result and understand evidence relevance</sub></td>
130
+ </tr>
131
+ </table>
132
+
133
+ ## Command surface
134
+
135
+ Run `ciphrix <resource> --help` for its actions and `ciphrix <resource> <action> --help` for the flags of
136
+ one command. Installed help is authoritative. The complete generated reference is available at
137
+ [`skills/ciphrix/references/commands.md`](skills/ciphrix/references/commands.md) and checked for drift in CI.
138
+
139
+ <details>
140
+ <summary>Browse the command groups</summary>
141
+
142
+ | Command | What it does |
143
+ | -------------------------------------------------- | ------------------------------------------------------------------------------ |
144
+ | `ciphrix login` · `logout` | Authorize this device or revoke its session. |
145
+ | `ciphrix context get` · `status` · `set` · `reset` | Read and maintain Business and Operating Context. |
146
+ | `ciphrix document …` | Browse, read, create, edit, version, submit, approve, and delete documents. |
147
+ | `ciphrix test …` | Inspect tests, links, runs and evidence; attach items and record results. |
148
+ | `ciphrix framework …` | Browse applied frameworks and work with clauses and mappings. |
149
+ | `ciphrix control …` | Inspect controls, ownership, applicability, design requirements, and mappings. |
150
+ | `ciphrix asset …` | Maintain the asset register, mappings, and tags. |
151
+ | `ciphrix vendor …` | Maintain vendors and their attached files. |
152
+ | `ciphrix risk …` | Maintain risks, treatment, scores, controls, and files. |
153
+ | `ciphrix check …` | Operate monitoring checks, resources, runs, findings, and integrations. |
154
+ | `ciphrix job status <jobId>` | Follow background work started by another command. |
155
+
156
+ </details>
157
+
158
+ ## Safe by default
159
+
160
+ - Credentials use the operating system keychain by default and are isolated by API environment.
161
+ - Device authorization keeps passwords out of the terminal and CLI process.
162
+ - API traffic requires HTTPS unless insecure HTTP is explicitly enabled for local testing.
163
+ - Redirects are not followed for API calls or uploads.
164
+ - Destructive and consequential actions require confirmation unless `--yes` is explicitly supplied.
165
+ - JSON output is undecorated and suitable for programs and agents.
166
+ - Requests time out, responses are size-limited, and local evidence uploads reject symbolic links and
167
+ files over 50 MiB.
168
+
169
+ Please report vulnerabilities privately as described in [SECURITY.md](SECURITY.md).
170
+
171
+ ## Non-production and advanced configuration
172
+
173
+ The CLI does not use a general configuration file. An API base is selected in this order:
174
+
175
+ 1. The command's `--api-url` option.
176
+ 2. `CIPHRIX_API_URL`.
177
+ 3. The built-in production API.
178
+
179
+ Credentials are stored separately for each API base, so local or test authentication does not replace
180
+ the production credential.
181
+
182
+ | Setting | Purpose |
183
+ | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
184
+ | `--api-url <url>` / `CIPHRIX_API_URL` | Use a different API base, including its public API prefix. |
185
+ | `--allow-insecure-http` / `CIPHRIX_ALLOW_INSECURE_HTTP=true` | Explicitly permit HTTP for trusted local testing. Never use it across an untrusted network. |
186
+ | `CIPHRIX_CREDENTIAL_STORE=file` | Use a permission-restricted plaintext credential file for intentional headless or test environments. The keychain remains the normal default. |
187
+ | `ciphrix login --no-open` | Print the authorization link without opening a browser. |
188
+ | `ciphrix logout --local-only` | Remove only this device's stored credential without contacting the API. |
189
+ | `NO_COLOR` / `FORCE_COLOR` | Apply standard terminal colour controls. Piped output is never coloured. |
190
+
191
+ API URLs containing user information, query strings, or fragments are rejected. If remote logout fails,
192
+ the local credential is retained so revocation can be retried; `--local-only` is always an explicit choice.
193
+
194
+ ## Contributing
195
+
196
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [AGENTS.md](AGENTS.md). `main` is always releasable, and every
197
+ change lands through a short-lived pull request with required review and automated checks.
198
+
199
+ ## License
200
+
201
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,19 @@
1
+ import { type CliIO } from './io.js';
2
+ import { type ToolContext } from './toolSurface.js';
3
+ export interface ApplyOptions {
4
+ ctx: ToolContext;
5
+ io: CliIO;
6
+ toolName: string;
7
+ input: unknown;
8
+ fallback: string;
9
+ yes?: boolean | undefined;
10
+ confirm?: ((question: string) => Promise<boolean>) | undefined;
11
+ }
12
+ /**
13
+ * Runs a tool, handling the two-step confirm contract when the tool requires it.
14
+ *
15
+ * - Tools that need no confirmation apply on the first call.
16
+ * - Tools that require confirmation: the first call is a preflight (summary + token), the user is asked
17
+ * once, then the change is applied with the token and an idempotency key.
18
+ */
19
+ export declare const applyTool: ({ ctx, io, toolName, input, fallback, yes, confirm, }: ApplyOptions) => Promise<Record<string, unknown> | null>;
@@ -0,0 +1,30 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { promptConfirm, writeLine } from './io.js';
3
+ import { asRecord, asText, callTool, errorMessage } from './toolSurface.js';
4
+ /**
5
+ * Runs a tool, handling the two-step confirm contract when the tool requires it.
6
+ *
7
+ * - Tools that need no confirmation apply on the first call.
8
+ * - Tools that require confirmation: the first call is a preflight (summary + token), the user is asked
9
+ * once, then the change is applied with the token and an idempotency key.
10
+ */
11
+ export const applyTool = async ({ ctx, io, toolName, input, fallback, yes = false, confirm, }) => {
12
+ const ask = confirm ?? ((question) => promptConfirm(io, question));
13
+ const idempotencyKey = randomUUID();
14
+ const first = await callTool(ctx, toolName, input, { idempotencyKey });
15
+ if (first.status !== 'ok')
16
+ throw new Error(errorMessage(first, fallback));
17
+ const confirmation = asRecord(asRecord(first.meta).confirmation);
18
+ const token = asText(confirmation.token);
19
+ if (!token)
20
+ return first;
21
+ writeLine(io.stdout, asText(confirmation.summary, 'Apply this change?'));
22
+ if (!yes && !(await ask('Apply this change?'))) {
23
+ writeLine(io.stdout, 'Cancelled.');
24
+ return null;
25
+ }
26
+ const result = await callTool(ctx, toolName, input, { confirmationToken: token, idempotencyKey });
27
+ if (result.status !== 'ok')
28
+ throw new Error(errorMessage(result, fallback));
29
+ return result;
30
+ };
package/dist/api.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export declare class ApiError extends Error {
2
+ readonly status: number;
3
+ readonly code: string | undefined;
4
+ constructor(message: string, status: number, code?: string | undefined);
5
+ }
6
+ export interface RequestOptions {
7
+ method?: string;
8
+ body?: unknown;
9
+ token?: string;
10
+ }
11
+ export interface ApiClient {
12
+ readonly baseUrl: string;
13
+ request(path: string, options?: RequestOptions): Promise<unknown>;
14
+ }
15
+ /** Default time allowed for an API request, including reading its response body. */
16
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
17
+ /** Maximum decoded response size buffered by the CLI. */
18
+ export declare const DEFAULT_MAX_RESPONSE_BYTES: number;
19
+ export interface RequestLimits {
20
+ timeoutMs?: number;
21
+ maxResponseBytes?: number;
22
+ }
23
+ export declare const withRequestTimeout: <T>(timeoutMs: number, operation: (signal: AbortSignal) => Promise<T>) => Promise<T>;
24
+ export declare const readLimitedText: (response: Response, maxBytes: number) => Promise<string>;
25
+ /** Never follow redirects for requests that may carry credentials or user data. */
26
+ export declare const fetchWithoutRedirects: (url: string, init: RequestInit) => Promise<Response>;
27
+ export declare const createApiClient: (baseUrl: string, limits?: RequestLimits) => ApiClient;
package/dist/api.js ADDED
@@ -0,0 +1,180 @@
1
+ export class ApiError extends Error {
2
+ status;
3
+ code;
4
+ constructor(message, status, code = undefined) {
5
+ super(message);
6
+ this.name = 'ApiError';
7
+ this.status = status;
8
+ this.code = code;
9
+ }
10
+ }
11
+ /** Default time allowed for an API request, including reading its response body. */
12
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
13
+ /** Maximum decoded response size buffered by the CLI. */
14
+ export const DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
15
+ export const withRequestTimeout = async (timeoutMs, operation) => {
16
+ const controller = new AbortController();
17
+ let timedOut = false;
18
+ const timer = setTimeout(() => {
19
+ timedOut = true;
20
+ controller.abort();
21
+ }, timeoutMs);
22
+ try {
23
+ return await operation(controller.signal);
24
+ }
25
+ catch (error) {
26
+ if (timedOut) {
27
+ throw new Error(`Request timed out after ${Math.ceil(timeoutMs / 1000)} seconds.`, {
28
+ cause: error,
29
+ });
30
+ }
31
+ throw error;
32
+ }
33
+ finally {
34
+ clearTimeout(timer);
35
+ }
36
+ };
37
+ export const readLimitedText = async (response, maxBytes) => {
38
+ const declaredLength = Number(response.headers.get('content-length'));
39
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
40
+ await response.body?.cancel().catch(() => undefined);
41
+ throw new Error(`The API response exceeds the ${maxBytes}-byte size limit.`);
42
+ }
43
+ if (!response.body)
44
+ return '';
45
+ const reader = response.body.getReader();
46
+ const chunks = [];
47
+ let total = 0;
48
+ try {
49
+ while (true) {
50
+ const readPromise = Promise.resolve(reader.read());
51
+ const result = await readPromise.then((value) => value);
52
+ const { done, value } = result;
53
+ if (done)
54
+ break;
55
+ if (!value)
56
+ continue;
57
+ total += value.byteLength;
58
+ if (total > maxBytes) {
59
+ await reader.cancel().catch(() => undefined);
60
+ throw new Error(`The API response exceeds the ${maxBytes}-byte size limit.`);
61
+ }
62
+ chunks.push(value);
63
+ }
64
+ }
65
+ finally {
66
+ reader.releaseLock();
67
+ }
68
+ const buffer = new Uint8Array(total);
69
+ let offset = 0;
70
+ for (const chunk of chunks) {
71
+ buffer.set(chunk, offset);
72
+ offset += chunk.byteLength;
73
+ }
74
+ return new TextDecoder().decode(buffer);
75
+ };
76
+ /** Never follow redirects for requests that may carry credentials or user data. */
77
+ export const fetchWithoutRedirects = async (url, init) => {
78
+ const response = await fetch(url, { ...init, redirect: 'manual' });
79
+ if (response.status >= 300 && response.status < 400) {
80
+ throw new Error('The API redirected this request. Redirects are blocked to protect credentials and data; update the API URL to the final HTTPS endpoint.');
81
+ }
82
+ return response;
83
+ };
84
+ const errorPayload = (data) => {
85
+ if (!data || typeof data !== 'object')
86
+ return { message: undefined, code: undefined, details: [] };
87
+ const record = data;
88
+ const nested = record.error && typeof record.error === 'object'
89
+ ? record.error
90
+ : undefined;
91
+ const message = typeof record.message === 'string'
92
+ ? record.message
93
+ : typeof record.error_description === 'string'
94
+ ? record.error_description
95
+ : typeof record.error === 'string'
96
+ ? record.error
97
+ : typeof nested?.message === 'string'
98
+ ? nested.message
99
+ : undefined;
100
+ const code = typeof record.error === 'string'
101
+ ? record.error
102
+ : typeof record.code === 'string'
103
+ ? record.code
104
+ : typeof nested?.code === 'string'
105
+ ? nested.code
106
+ : undefined;
107
+ const details = Array.isArray(nested?.details) ? nested?.details : [];
108
+ return { message, code, details };
109
+ };
110
+ /**
111
+ * Turn structured error details into something a user can act on: the ambiguous candidates, or the fields
112
+ * that failed validation. A bare "use a code" or "invalid input" is not actionable.
113
+ */
114
+ const withDetails = (message, code, details) => {
115
+ if (details.length === 0)
116
+ return message;
117
+ const asRecord = (item) => item && typeof item === 'object' ? item : {};
118
+ const text = (value) => (typeof value === 'string' ? value : '');
119
+ if (code === 'ambiguous') {
120
+ const candidates = details
121
+ .map((item) => {
122
+ const record = asRecord(item);
123
+ const candidateCode = text(record.code);
124
+ const candidateName = text(record.name);
125
+ if (candidateCode && candidateName)
126
+ return `${candidateCode} ${candidateName}`;
127
+ return candidateCode || candidateName || text(record.id);
128
+ })
129
+ .filter((value) => value !== '');
130
+ return candidates.length > 0 ? `${message}\n ${candidates.join('\n ')}` : message;
131
+ }
132
+ if (code === 'invalid_input') {
133
+ const problems = details
134
+ .map((item) => {
135
+ const record = asRecord(item);
136
+ const path = text(record.path) || text(record.field) || text(record.instancePath);
137
+ const problem = text(record.message) || text(record.error);
138
+ if (path && problem)
139
+ return `${path}: ${problem}`;
140
+ return problem || path;
141
+ })
142
+ .filter((value) => value !== '');
143
+ return problems.length > 0 ? `${message}\n ${problems.join('\n ')}` : message;
144
+ }
145
+ return message;
146
+ };
147
+ export const createApiClient = (baseUrl, limits = {}) => ({
148
+ baseUrl,
149
+ request: async (path, options = {}) => {
150
+ const timeoutMs = limits.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
151
+ const maxResponseBytes = limits.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
152
+ const { method = 'GET', body, token } = options;
153
+ const headers = {};
154
+ if (body !== undefined)
155
+ headers['content-type'] = 'application/json';
156
+ if (token)
157
+ headers.authorization = `Bearer ${token}`;
158
+ const init = { method, headers };
159
+ if (body !== undefined)
160
+ init.body = JSON.stringify(body);
161
+ return withRequestTimeout(timeoutMs, async (signal) => {
162
+ const response = await fetchWithoutRedirects(`${baseUrl}${path}`, { ...init, signal });
163
+ const text = await readLimitedText(response, maxResponseBytes);
164
+ let data = null;
165
+ if (text) {
166
+ try {
167
+ data = JSON.parse(text);
168
+ }
169
+ catch {
170
+ data = text;
171
+ }
172
+ }
173
+ if (!response.ok) {
174
+ const { message, code, details } = errorPayload(data);
175
+ throw new ApiError(withDetails(message || `Request failed with status ${response.status}`, code, details), response.status, code);
176
+ }
177
+ return data;
178
+ });
179
+ },
180
+ });
@@ -0,0 +1,2 @@
1
+ import type { Theme } from './theme.js';
2
+ export declare const formatBanner: (theme: Theme) => string;