qualiloop 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 QualiLoop
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,211 @@
1
- # Temporary Holding Version
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.
1
+ # qualiloop: the QualiLoop CLI and MCP server
2
+
3
+ One package, two ways in. Both use the same sign-in and run the same actions,
4
+ so either one does everything: run suites and release gates, wait
5
+ for the results, read problems and conversations, write tests, report a change
6
+ and connect an agent. Pick one and use it for everything.
7
+
8
+ - **`qualiloop`**, the CLI, suits a terminal, scripts, CI, and coding agents
9
+ that can run commands (Claude Code, Cursor, Codex).
10
+ - **`qualiloop mcp`**, the MCP server, suits chat apps and agents that cannot
11
+ run commands (Claude Desktop).
12
+
13
+ ## Start: connect an agent in one command
14
+
15
+ In the agent's folder (Node 20 or newer):
16
+
17
+ ```bash
18
+ npx qualiloop connect 12 # 12: the project's number, as the app shows it
19
+ npx qualiloop connect 12 --url <address> # a self-hosted QualiLoop
20
+ ```
21
+
22
+ It signs you in through the browser if needed (no account yet: create one from
23
+ the page that opens, and you come back to it), uses the project named by number
24
+ or name, makes it the default, writes `QUALILOOP_PROJECT_KEY` and
25
+ `QUALILOOP_OTLP_TRACES_URL` into `.env` (values never printed; it says when git
26
+ does not ignore the file) and prints the steps a coding agent follows next.
27
+ With no project named, it creates one named after the codebase (package.json or
28
+ pyproject.toml name, else the folder) when you have none, and otherwise lists
29
+ your projects and stops. The app shows the command, with the number filled in,
30
+ under New project and Settings, Coding agent. A setup token in
31
+ `QUALILOOP_SETUP_TOKEN` still wins over the sign-in.
32
+
33
+ To keep the CLI:
34
+
35
+ ```bash
36
+ npm install -g qualiloop # then: qualiloop connect 12
37
+ qualiloop login # a self-hosted QualiLoop: qualiloop login --url <address>
38
+ qualiloop connect guide # the steps to connect an agent in this codebase to QualiLoop
39
+ qualiloop guide # how to use the commands well: what to run, in what order
40
+ ```
41
+
42
+ The global install puts `qualiloop` and its short form `ql` on your PATH: `ql
43
+ suites run core --wait`. Install it globally to use the MCP server, so
44
+ `qualiloop mcp install` points your MCP client at a copy that stays.
45
+
46
+ `qualiloop guide` prints the guide the MCP server gives agents as its
47
+ instructions. `qualiloop connect guide` prints `/connect/SKILL.md` from your
48
+ QualiLoop, the steps a coding agent follows; the code for each step is at
49
+ `/connect/reference.md` on the same address.
50
+
51
+ ## Sign in
52
+
53
+ ```bash
54
+ qualiloop login # https://app.qualiloop.com
55
+ qualiloop login --url https://qualiloop.example.com # a self-hosted QualiLoop
56
+ ```
57
+
58
+ The browser opens the QualiLoop approval page. Check that it shows the code the
59
+ terminal shows, and approve. No password or key is typed into the terminal. The sign-in is stored in `credentials.json` in
60
+ `%APPDATA%\qualiloop` (Windows) or `~/.config/qualiloop`, readable by you only,
61
+ one per QualiLoop address; the last one signed in to is the default. It ends
62
+ after 90 days without use, or when revoked in Account settings,
63
+ `qualiloop tokens revoke <id>` or `qualiloop logout`.
64
+
65
+ ## Set up the MCP server
66
+
67
+ ```bash
68
+ qualiloop mcp install # Claude Desktop
69
+ qualiloop mcp install --client cursor vscode # other clients: claude-code, cursor, vscode, windsurf, codex
70
+ qualiloop mcp install --client all # every supported client
71
+ qualiloop mcp install --client claude-code cursor --scope project # this repository only (.mcp.json, .cursor/)
72
+ qualiloop mcp install --print # the settings to paste by hand, for every client
73
+ qualiloop mcp install --client codex --print # only for the clients named
74
+ ```
75
+
76
+ The server starts as this Node and this package's `cli.js`, with
77
+ `QUALILOOP_URL` set when you are not on app.qualiloop.com. If it is not signed
78
+ in, its `sign_in` tool runs the same browser approval.
79
+
80
+ Its tools are every action in `qualiloop actions`, plus `qualiloop_status`,
81
+ `sign_in`, `wait_for_runs` and the `connect_*` tools that connect an agent in
82
+ the open codebase (`connect_agent` does what `qualiloop connect` does, without
83
+ the browser sign-in, which `sign_in` runs). Those read and write files only inside the workspace, write
84
+ the project key straight into `.env`, and read a header secret from a variable,
85
+ so no secret passes through the chat.
86
+
87
+ ## Commands
88
+
89
+ ```text
90
+ qualiloop login | logout | whoami | tokens [revoke <id>]
91
+ qualiloop projects [show <project> | use <project>]
92
+ qualiloop knowledge capabilities and coverage at a glance
93
+ qualiloop knowledge list [--section <s>] | show <id> | edit <id> | general
94
+ qualiloop knowledge explore [--note <text>] | explorations
95
+ qualiloop knowledge sources [--kind <k>] [--in-force] | source <id>
96
+ qualiloop knowledge add-doc <name> --file <path> | retire-source <id>
97
+ qualiloop change <description> report a change to the agent
98
+ qualiloop tests [show <id> | create | edit <id> | delete <id> [--yes]]
99
+ qualiloop suites [run <suite> --wait | create <name> [--test <id>] | add <suite> <test-id>...]
100
+ qualiloop run <test-id>... [--wait] [--fail-on major|minor|none] [--timeout <min>]
101
+ qualiloop runs [show <run> | wait <batch>] [--batch <id>]
102
+ qualiloop problems [--run <n>] [--severity major]
103
+ qualiloop problems categories [show <id> | solve <id> [--reopen]]
104
+ qualiloop conversation <id>
105
+ qualiloop gate [run [<gate>] --wait --ref <sha> | runs | show <n> | cancel <n>]
106
+ qualiloop generate <prompt> [--suite <s> | --new-suite <name>] [--max <n>] [--wait]
107
+ qualiloop generate status <id> | cancel <id>
108
+ qualiloop guide how to use the commands well
109
+ qualiloop connect [project] sign in, choose the project, write .env, print the steps
110
+ qualiloop connect guide the connect skill, from your QualiLoop
111
+ qualiloop connect info | env | projects | create-project | rename | target |
112
+ knowledge --file <json> [--overwrite] | live on|off |
113
+ check-traces <id> | check | disconnect
114
+ qualiloop mcp [install]
115
+ qualiloop actions every action, as the MCP server offers it
116
+ qualiloop action <name> --args '{...}' run one action with JSON arguments
117
+ ```
118
+
119
+ Global options: `--url`, `--project <number or name>` (or `qualiloop projects
120
+ use`), `--json` for output a script can read.
121
+
122
+ Lists (`tests`, `suites`, `runs`, `problems`, `problems categories`, `gate runs`)
123
+ take `--limit <n>` and end with "N of M shown" when they are cut.
124
+
125
+ `run --wait` and `suites run --wait` print the batch first; if you stop waiting,
126
+ `qualiloop runs wait <batch>` picks it up again. A wait lasts until every run
127
+ has talked to the agent, been judged and had its problems sorted, so it shows
128
+ what the runs are doing (running, judging, sorting problems) as it goes.
129
+
130
+ `tests delete` asks before deleting; `--yes` skips the question (and is needed
131
+ without a terminal). `gate cancel` ends a gate run still waiting on its tests,
132
+ as cancelled, which CI treats as not passed; QualiLoop also ends a gate run that
133
+ is still open past its gate's CI time limit, as failed.
134
+
135
+ `knowledge` shows what the System knowledge page shows you: capabilities,
136
+ entity groups and entities for everyone, every section with its statuses and
137
+ evidence for a QualiLoop super admin (`show` and `edit` are theirs only).
138
+ `knowledge edit` sets a status by adding manual evidence (`yes`, `opposite`) or
139
+ removing it (`clear`). `knowledge general` changes the agent's name, summary or
140
+ description. `knowledge explore` starts a plain exploration: 3 rounds of up to
141
+ 8 conversations, so up to 24 conversation credits, not judged; `qualiloop
142
+ change` instead re-checks only what a described change touches.
143
+
144
+ `knowledge sources` lists what the knowledge is read from: the agent's system
145
+ prompts, tools and documentation, each with where it came from (the coding
146
+ agent, by hand, the connection settings, or seen in traces). `knowledge source`
147
+ shows one with its text and what it states. `knowledge add-doc` adds a document
148
+ by hand (or a new version of one) and `knowledge retire-source` takes a source
149
+ added by hand or seen in traces out of use; both are for admins and the ML
150
+ team. Sources from the agent's code change only with `connect knowledge`.
151
+
152
+ `connect` uses `QUALILOOP_SETUP_TOKEN` when it is set: the token names its own
153
+ project, and `-p` only names a project the token created. Otherwise it uses
154
+ your sign-in, on the project named by `-p`, `QUALILOOP_PROJECT` or `qualiloop
155
+ projects use`; with none named it stops and asks for one. Each `connect`
156
+ command prints the project it acted on.
157
+
158
+ `connect knowledge` (old name `connect context`) fills the system knowledge
159
+ from the code: the body of `PUT /v1/setup/knowledge`, with the prompts verbatim
160
+ and their placeholders, the tools, the documents and General. General fills
161
+ only empty fields; `--overwrite` replaces them, only when the user asked. The
162
+ answer lists each source as new, unchanged or a new version, and the ones
163
+ retired or kept.
164
+
165
+ Errors and hints name the commands to type. The same actions name tools for
166
+ the MCP server and the in-app assistant: the CLI sends `X-Qualiloop-Client: cli`.
167
+
168
+ ### Exit codes
169
+
170
+ | Code | Meaning |
171
+ |---|---|
172
+ | 0 | Done; with `--wait`, everything passed |
173
+ | 1 | What was checked failed: a gate said fail, a run found a major problem |
174
+ | 2 | The command or its arguments were wrong |
175
+ | 3 | Not signed in, the sign-in ended, or your role cannot do this |
176
+ | 4 | Not found |
177
+ | 5 | Waited longer than `--timeout` |
178
+ | 6 | QualiLoop could not be reached or answered with an error |
179
+
180
+ ### Environment
181
+
182
+ | Variable | Use |
183
+ |---|---|
184
+ | `QUALILOOP_URL` | The QualiLoop address. Default https://app.qualiloop.com |
185
+ | `QUALILOOP_TOKEN` | A CLI sign-in token, for CI instead of `qualiloop login` |
186
+ | `QUALILOOP_GATE_KEY` | A release gate's deploy token, for `qualiloop gate run` in CI |
187
+ | `QUALILOOP_PROJECT` | The project when `--project` is not given |
188
+ | `QUALILOOP_SETUP_TOKEN` | A project setup token for `qualiloop connect`; when set, it is used instead of the sign-in, on its own project |
189
+ | `QUALILOOP_CONFIG_DIR` | Where the sign-ins are stored |
190
+ | `QUALILOOP_NO_BROWSER` | Print the approval link instead of opening it |
191
+
192
+ ## CI
193
+
194
+ A release gate, with the gate's deploy token stored as a secret:
195
+
196
+ ```yaml
197
+ - run: qualiloop gate run --wait --ref "$GITHUB_SHA"
198
+ env:
199
+ QUALILOOP_GATE_KEY: ${{ secrets.QUALILOOP_GATE_KEY }}
200
+ ```
201
+
202
+ (with `npm i -g qualiloop` in an earlier step, or `npx qualiloop gate run ...`
203
+ with no install step).
204
+
205
+ The token names its gate (`POST /v1/release-gates/hooks/runs`), and the wait
206
+ uses the gate's CI time limit unless `--timeout` is given. A suite, with a
207
+ sign-in made for CI:
208
+
209
+ ```bash
210
+ QUALILOOP_TOKEN=... qualiloop suites run core --wait --project 12
211
+ ```
package/dist/api.js ADDED
@@ -0,0 +1,121 @@
1
+ import { resolveUrl, storedCredentials } from './config.js';
2
+ export const VERSION = '0.1.0';
3
+ export const EXIT = {
4
+ ok: 0,
5
+ failed: 1,
6
+ usage: 2,
7
+ auth: 3,
8
+ notFound: 4,
9
+ timeout: 5,
10
+ server: 6,
11
+ };
12
+ export class ApiError extends Error {
13
+ status;
14
+ exitCode;
15
+ constructor(message, status, exitCode) {
16
+ super(message);
17
+ this.status = status;
18
+ this.exitCode = exitCode;
19
+ }
20
+ }
21
+ const exitFor = (status) => {
22
+ if (status === 401 || status === 403)
23
+ return EXIT.auth;
24
+ if (status === 404)
25
+ return EXIT.notFound;
26
+ if (status === 400 || status === 409 || status === 422)
27
+ return EXIT.usage;
28
+ return EXIT.server;
29
+ };
30
+ const detailOf = (body, fallback) => {
31
+ if (body && typeof body === 'object' && 'detail' in body) {
32
+ const detail = body.detail;
33
+ if (typeof detail === 'string')
34
+ return detail;
35
+ if (Array.isArray(detail)) {
36
+ return detail
37
+ .map((item) => item && typeof item === 'object' && 'msg' in item
38
+ ? `${(item.loc || []).join('.')}: ${item.msg}`
39
+ : String(item))
40
+ .join('; ');
41
+ }
42
+ }
43
+ return fallback;
44
+ };
45
+ export class QualiloopClient {
46
+ url;
47
+ explicitToken;
48
+ fetchImpl;
49
+ timeoutMs;
50
+ kind;
51
+ constructor(options = {}) {
52
+ this.url = resolveUrl(options.url);
53
+ this.explicitToken = options.token;
54
+ this.fetchImpl = options.fetchImpl || fetch;
55
+ this.timeoutMs = options.timeoutMs ?? 120_000;
56
+ this.kind = options.kind ?? 'mcp';
57
+ }
58
+ token() {
59
+ return this.explicitToken || process.env.QUALILOOP_TOKEN || storedCredentials(this.url)?.token;
60
+ }
61
+ isSignedIn() {
62
+ return Boolean(this.token());
63
+ }
64
+ async request(method, path, options = {}) {
65
+ const headers = {
66
+ Accept: 'application/json',
67
+ 'User-Agent': `qualiloop-cli/${VERSION}`,
68
+ ...(this.kind === 'cli' ? { 'X-Qualiloop-Client': 'cli' } : {}),
69
+ ...options.headers,
70
+ };
71
+ if (!options.anonymous) {
72
+ const token = options.token || this.token();
73
+ if (!token) {
74
+ throw new ApiError(`Not signed in to ${this.url}. Run: qualiloop login${this.url === 'https://app.qualiloop.com' ? '' : ` --url ${this.url}`}`, 401, EXIT.auth);
75
+ }
76
+ headers.Authorization = `Bearer ${token}`;
77
+ }
78
+ let payload;
79
+ if (options.body !== undefined) {
80
+ headers['Content-Type'] = 'application/json';
81
+ payload = JSON.stringify(options.body);
82
+ }
83
+ let response;
84
+ try {
85
+ response = await this.fetchImpl(`${this.url}${path}`, {
86
+ method,
87
+ headers,
88
+ body: payload,
89
+ signal: AbortSignal.timeout(this.timeoutMs),
90
+ });
91
+ }
92
+ catch (error) {
93
+ const reason = error instanceof Error ? error.message : String(error);
94
+ throw new ApiError(`Could not reach QualiLoop at ${this.url}: ${reason}`, 0, EXIT.server);
95
+ }
96
+ const text = await response.text();
97
+ let body = undefined;
98
+ if (text) {
99
+ try {
100
+ body = JSON.parse(text);
101
+ }
102
+ catch {
103
+ body = text;
104
+ }
105
+ }
106
+ if (!response.ok) {
107
+ let message = detailOf(body, `${response.status} ${response.statusText}`);
108
+ if (response.status === 429) {
109
+ const retry = response.headers.get('retry-after');
110
+ message = `${message}${retry ? ` Try again in ${retry} seconds.` : ''}`;
111
+ }
112
+ throw new ApiError(message, response.status, exitFor(response.status));
113
+ }
114
+ return body;
115
+ }
116
+ async action(name, args = {}) {
117
+ const clean = Object.fromEntries(Object.entries(args).filter(([, value]) => value !== undefined));
118
+ const body = await this.request('POST', `/v1/actions/${name}`, { body: clean });
119
+ return body.result;
120
+ }
121
+ }
package/dist/auth.js ADDED
@@ -0,0 +1,68 @@
1
+ import { spawn } from 'node:child_process';
2
+ import os from 'node:os';
3
+ import { ApiError, EXIT } from './api.js';
4
+ import { saveCredentials } from './config.js';
5
+ export const openBrowser = (url) => {
6
+ if (process.env.QUALILOOP_NO_BROWSER || (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)) {
7
+ return false;
8
+ }
9
+ try {
10
+ const [command, args] = process.platform === 'win32'
11
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
12
+ : process.platform === 'darwin'
13
+ ? ['open', [url]]
14
+ : ['xdg-open', [url]];
15
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
16
+ child.on('error', () => undefined);
17
+ child.unref();
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
+ export const login = async (client, options = {}) => {
26
+ const started = await client.request('POST', '/v1/cli/login', {
27
+ anonymous: true,
28
+ body: { client: options.client || 'cli', hostname: os.hostname() },
29
+ });
30
+ const opened = options.browser === false ? false : openBrowser(started.verification_url_complete);
31
+ options.onStarted?.({ url: started.verification_url_complete, code: started.user_code, opened });
32
+ let interval = Math.max(1, started.interval) * 1000;
33
+ const deadline = Date.now() + started.expires_in * 1000;
34
+ while (Date.now() < deadline) {
35
+ await sleep(interval);
36
+ let polled;
37
+ try {
38
+ polled = await client.request('POST', '/v1/cli/login/poll', {
39
+ anonymous: true,
40
+ body: { device_code: started.device_code },
41
+ });
42
+ }
43
+ catch (error) {
44
+ if (error instanceof ApiError && error.exitCode === EXIT.server)
45
+ continue;
46
+ throw error;
47
+ }
48
+ if (polled.status === 'slow_down') {
49
+ interval += 1000;
50
+ continue;
51
+ }
52
+ if (polled.status === 'pending')
53
+ continue;
54
+ if (polled.status === 'approved' && polled.token) {
55
+ saveCredentials(client.url, {
56
+ token: polled.token,
57
+ expires_at: polled.expires_at ?? null,
58
+ user: polled.user ?? null,
59
+ });
60
+ return { url: client.url, user: polled.user ?? null, expires_at: polled.expires_at ?? null };
61
+ }
62
+ if (polled.status === 'denied') {
63
+ throw new ApiError('The sign-in was denied in the browser.', 403, EXIT.auth);
64
+ }
65
+ break;
66
+ }
67
+ throw new ApiError(`The sign-in expired before it was approved. ${options.again ?? 'Run the same command again.'}`, 408, EXIT.timeout);
68
+ };
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ let bundled;
5
+ const readBundled = () => {
6
+ if (!bundled) {
7
+ const here = path.dirname(fileURLToPath(import.meta.url));
8
+ bundled = JSON.parse(readFileSync(path.join(here, 'catalog.json'), 'utf8'));
9
+ }
10
+ return bundled;
11
+ };
12
+ export const bundledCatalog = () => readBundled().actions;
13
+ export const bundledGuide = () => readBundled().guide ?? '';
14
+ export const loadCatalog = async (client) => {
15
+ if (!client.isSignedIn())
16
+ return bundledCatalog();
17
+ try {
18
+ const body = await client.request('GET', '/v1/actions');
19
+ return body.actions?.length ? body.actions : bundledCatalog();
20
+ }
21
+ catch {
22
+ return bundledCatalog();
23
+ }
24
+ };