@kumion/cli 0.2.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 +21 -0
- package/README.md +263 -0
- package/dist/cli.js +73 -0
- package/dist/client.js +138 -0
- package/dist/credentials.js +132 -0
- package/dist/device-login.js +100 -0
- package/dist/errors.js +71 -0
- package/dist/main.js +681 -0
- package/dist/mcp.js +144 -0
- package/package.json +50 -0
- package/skills/kumion/SKILL.md +88 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KAOPA株式会社
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# @kumion/cli
|
|
2
|
+
|
|
3
|
+
`kumion` manages the voice agents of one Kumion tenant from your terminal, over the
|
|
4
|
+
Kumion Partner API (`/api/v1`). It reads and edits an agent's draft, runs the agent's
|
|
5
|
+
regression tests, publishes through the same pre-publish check the Portal uses,
|
|
6
|
+
starts test calls, and reads the tenant's call history and transcripts.
|
|
7
|
+
|
|
8
|
+
Everything happens remotely, on the tenant's own agents. There is nothing to clone and
|
|
9
|
+
no local agent definition to keep in sync.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm i -g @kumion/cli
|
|
15
|
+
kumion --help
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Requires Node.js 20.18 or later.
|
|
19
|
+
|
|
20
|
+
By default the CLI talks to `https://app.kumion.jp`. Another environment can be
|
|
21
|
+
selected with `--base-url` or `KUMION_API_BASE` (see [Options and environment](#options-and-environment)).
|
|
22
|
+
`kumion auth login --base-url <url>` saves that origin with the profile.
|
|
23
|
+
|
|
24
|
+
## Authenticate
|
|
25
|
+
|
|
26
|
+
Two ways in. Both end with a `kum_live_` key in the OS keychain (macOS Keychain,
|
|
27
|
+
Windows Credential Manager, the Secret Service on Linux); neither ever writes the key
|
|
28
|
+
to a file. The profile file (`~/.config/kumion/config.json`, or `%APPDATA%\kumion` on
|
|
29
|
+
Windows) holds only profile names, tenant IDs, base URLs and, for a browser login,
|
|
30
|
+
when the key expires.
|
|
31
|
+
|
|
32
|
+
### In the browser: a personal key (tenant administrators)
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
kumion auth login
|
|
36
|
+
# To log in, open this page in a browser where you are signed in to the Kumion Portal:
|
|
37
|
+
# https://app.kumion.jp/device?user_code=ABCDEFGH
|
|
38
|
+
# and check that it shows this code: ABCD-EFGH
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Open the link, check the code, pick the tenant and the permissions, and press
|
|
42
|
+
承認する. The CLI then receives a **personal** key for that tenant:
|
|
43
|
+
|
|
44
|
+
- it expires after 12 hours (or sooner, if your organization's key policy says so) —
|
|
45
|
+
run `kumion auth login` again then;
|
|
46
|
+
- it stops working as soon as you are no longer an administrator of the tenant;
|
|
47
|
+
- only tenant administrators can approve one.
|
|
48
|
+
|
|
49
|
+
Your Portal session stays in the browser; the CLI only ever holds the key.
|
|
50
|
+
`kumion auth status` shows the key's kind and expiry. `--scopes agents:read,calls:read`
|
|
51
|
+
asks for less than every permission the CLI can use.
|
|
52
|
+
|
|
53
|
+
### With an API key from 設定 → 開発者
|
|
54
|
+
|
|
55
|
+
For a key someone issued on the Portal's **設定 → 開発者** page (a *service* key —
|
|
56
|
+
the tenant's, not a person's; choose the scopes you need, see below). You also need
|
|
57
|
+
the tenant ID: the UUID in the Portal URL (`/tenants/<tenant-id>/…`) and in the curl
|
|
58
|
+
examples on the same page.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
kumion auth login --with-api-key
|
|
62
|
+
# Tenant ID: <tenant-id>
|
|
63
|
+
# API key (input hidden): <paste the key>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The key is checked against the API before it is stored.
|
|
67
|
+
|
|
68
|
+
To pipe the key instead of typing it (it stays out of your shell history either way):
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
kumion auth login --with-api-key --tenant <tenant-id> < ./key-file
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Several customers: one profile per tenant
|
|
75
|
+
|
|
76
|
+
A key only reaches its own tenant, so a partner managing several customers keeps one
|
|
77
|
+
profile per customer:
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
kumion auth login --profile acme # pick Acme's tenant in the browser
|
|
81
|
+
kumion auth login --profile beta --with-api-key --tenant <beta-tenant-id>
|
|
82
|
+
kumion auth list # * marks the default
|
|
83
|
+
kumion auth use beta # change the default
|
|
84
|
+
kumion agents list --profile acme
|
|
85
|
+
kumion auth logout --profile acme
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### CI and machines without a keychain: environment variables
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
export KUMION_API_KEY=<your key> # from your CI secret store
|
|
92
|
+
export KUMION_TENANT_ID=<tenant-id>
|
|
93
|
+
kumion agents list
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
When `KUMION_API_KEY` is set and no `--profile` is given, the keychain is not used.
|
|
97
|
+
|
|
98
|
+
`kumion auth status` shows which tenant, base URL and key (prefix only) a command
|
|
99
|
+
would use.
|
|
100
|
+
|
|
101
|
+
## Commands
|
|
102
|
+
|
|
103
|
+
| Command | Scope the key needs |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| `kumion agents list` | `agents:read` |
|
|
106
|
+
| `kumion agents get <agentId> [--json]` | `agents:read` |
|
|
107
|
+
| `kumion agents patch <agentId> --revision <rev> [--prompt <text> \| --prompt-file <path>] [--graph-file <path>]` | `agents:write` |
|
|
108
|
+
| `kumion agents publish <agentId> [--revision <rev>]` | `agents:publish` |
|
|
109
|
+
| `kumion test-runs start <agentId> [--no-wait] [--interval <sec>] [--timeout <sec>]` | `tests:run` |
|
|
110
|
+
| `kumion test-runs get <agentId> <runId>` / `test-runs list <agentId>` | `tests:run` |
|
|
111
|
+
| `kumion calls create <agentId> [--campaign-contact <id>]` | `calls:create` |
|
|
112
|
+
| `kumion calls list [--agent <id>] [--channel webcall\|sip_did\|trigger] [--from <iso>] [--to <iso>] [--search <text>] [--limit <n>] [--offset <n>]` | `calls:read` |
|
|
113
|
+
| `kumion calls get <callId>` / `calls transcript <callId>` | `calls:read` |
|
|
114
|
+
|
|
115
|
+
A command whose key lacks the scope fails with a message naming the scope it needs.
|
|
116
|
+
`calls:read` is its own scope: a key that can start calls (`calls:create`) cannot read
|
|
117
|
+
them. `calls list` returns one page (20 by default, at most 100) and prints the
|
|
118
|
+
`--offset` of the next one. A transcript holds only what the caller and the agent said.
|
|
119
|
+
Add `--json` to any command for the API's JSON instead of a summary.
|
|
120
|
+
|
|
121
|
+
### Editing a draft
|
|
122
|
+
|
|
123
|
+
Edits go to the agent's **draft**. Callers hear nothing new until you publish.
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
kumion agents get <agentId> --json > agent.json # note "revision"
|
|
127
|
+
# edit agent.json's draft.graph, or write a new prompt to prompt.txt
|
|
128
|
+
kumion agents patch <agentId> --graph-file agent.json
|
|
129
|
+
kumion agents patch <agentId> --revision <rev> --prompt-file prompt.txt
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`--revision` says which version of the draft your change is based on. If someone saved
|
|
133
|
+
the agent in the Portal (or from another client) since you read it, the patch is
|
|
134
|
+
refused with a conflict and nothing is written: read it again and re-apply your change.
|
|
135
|
+
`--graph-file` accepts either a bare flow graph or the whole `agents get --json`
|
|
136
|
+
output, in which case the revision inside the file is used.
|
|
137
|
+
|
|
138
|
+
### What the CLI does not cover
|
|
139
|
+
|
|
140
|
+
The CLI is a client of the Partner API (the commands above), so it can only do what
|
|
141
|
+
that API exposes. These Portal features have no Partner API route yet and are not in
|
|
142
|
+
the CLI: conversation-edit mode and its monthly count, per-agent operating hours and the
|
|
143
|
+
hand-off to another agent outside them, knowledge-base confirm / bulk delete, filtering
|
|
144
|
+
bookings by agent, applying 解決策 to pre-publish findings, the opening-line name toggle,
|
|
145
|
+
external-tool rate-limit / circuit-breaker status, and the agent language / English
|
|
146
|
+
locale. Flow-level settings that live inside the graph (IVR recording, slot sources,
|
|
147
|
+
transfer nodes) travel with `agents get --json` / `agents patch --graph-file` unchanged.
|
|
148
|
+
|
|
149
|
+
### Testing and publishing
|
|
150
|
+
|
|
151
|
+
```sh
|
|
152
|
+
kumion test-runs start <agentId> # waits for the result; exit code 0 only on pass
|
|
153
|
+
kumion agents publish <agentId> # runs the pre-publish check, then publishes
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`test-runs start` checks the draft without publishing anything. `agents publish` runs
|
|
157
|
+
the Portal's pre-publish check and publishes only when it passes; when it does not, the
|
|
158
|
+
failing cases are printed and nothing goes live. The CLI has no way to skip or override
|
|
159
|
+
the check.
|
|
160
|
+
|
|
161
|
+
## Use it from an AI coding assistant (MCP)
|
|
162
|
+
|
|
163
|
+
`kumion mcp` serves the same operations as MCP tools over stdio, for Claude Code,
|
|
164
|
+
Codex or any other MCP host: `list_agents`, `get_agent`, `patch_agent`,
|
|
165
|
+
`publish_agent`, `start_test_run`, `get_test_run`, `list_test_runs`, `create_call`,
|
|
166
|
+
`list_calls`, `get_call`, `get_call_transcript`.
|
|
167
|
+
Each needs the same scope as its command above.
|
|
168
|
+
|
|
169
|
+
The server reads the key the same way every command does — the OS keychain profile,
|
|
170
|
+
or `KUMION_API_KEY` / `KUMION_TENANT_ID` from its own environment — when it starts.
|
|
171
|
+
**The host's MCP configuration holds only the command and its arguments; never put
|
|
172
|
+
a key in it.** Log in first (`kumion auth login`), then register:
|
|
173
|
+
|
|
174
|
+
```sh
|
|
175
|
+
# Claude Code
|
|
176
|
+
claude mcp add kumion -- kumion mcp
|
|
177
|
+
claude mcp add kumion-acme -- kumion mcp --profile acme # one server per customer profile
|
|
178
|
+
|
|
179
|
+
# Codex
|
|
180
|
+
codex mcp add kumion -- kumion mcp
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Or in a project's `.mcp.json` (safe to commit — there is nothing secret in it):
|
|
184
|
+
|
|
185
|
+
```json
|
|
186
|
+
{
|
|
187
|
+
"mcpServers": {
|
|
188
|
+
"kumion": { "command": "kumion", "args": ["mcp", "--profile", "acme"] }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
In CI, export `KUMION_API_KEY` and `KUMION_TENANT_ID` from the CI secret store in the
|
|
194
|
+
environment the host runs in; the server inherits them.
|
|
195
|
+
|
|
196
|
+
If nothing is logged in, the server does not start: it prints
|
|
197
|
+
`Not logged in. Run kumion auth login, …` to stderr and exits 2, which the host shows
|
|
198
|
+
as a failed server.
|
|
199
|
+
|
|
200
|
+
`publish_agent` blocks while the pre-publish check runs (a few minutes).
|
|
201
|
+
`start_test_run` returns at once unless given `waitSeconds` (at most 120); follow the
|
|
202
|
+
run with `get_test_run`.
|
|
203
|
+
|
|
204
|
+
### Skill
|
|
205
|
+
|
|
206
|
+
`skills/kumion/SKILL.md` in this package tells an assistant when to use Kumion and how
|
|
207
|
+
the read → edit → test → publish loop goes. For Claude Code, copy it into your skills:
|
|
208
|
+
|
|
209
|
+
```sh
|
|
210
|
+
cp -R "$(npm root -g)/@kumion/cli/skills/kumion" ~/.claude/skills/
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## Options and environment
|
|
214
|
+
|
|
215
|
+
| Option | Environment | Meaning |
|
|
216
|
+
| --- | --- | --- |
|
|
217
|
+
| `--profile <name>` | `KUMION_PROFILE` | Use this saved profile |
|
|
218
|
+
| `--base-url <url>` | `KUMION_API_BASE` | Kumion Portal origin. Default `https://app.kumion.jp`. Another environment can be selected with this option |
|
|
219
|
+
| — | `KUMION_API_KEY`, `KUMION_TENANT_ID` | Use this key instead of a saved profile |
|
|
220
|
+
| — | `KUMION_CONFIG_DIR` | Where the profile file lives |
|
|
221
|
+
| `--json` | — | Print JSON |
|
|
222
|
+
| `--debug` | — | Show stack traces on errors |
|
|
223
|
+
|
|
224
|
+
A `403` that does not name a scope is about the tenant, not the key: a plan that
|
|
225
|
+
cannot publish, or the call-minute limit on `calls create`.
|
|
226
|
+
|
|
227
|
+
Exit codes: `0` success, `1` the API refused or the result is a failure (test run not
|
|
228
|
+
passed, publish blocked), `2` the command was used wrongly or is not logged in.
|
|
229
|
+
|
|
230
|
+
## Development
|
|
231
|
+
|
|
232
|
+
This package lives in the Kumion repository at `packages/cli`, as its own npm package.
|
|
233
|
+
|
|
234
|
+
```sh
|
|
235
|
+
npm --prefix packages/cli ci
|
|
236
|
+
npm run cli:typecheck && npm run cli:test && npm run cli:build
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
The tests are offline: `fetch` and the keychain are injected fakes.
|
|
240
|
+
|
|
241
|
+
## Publishing
|
|
242
|
+
|
|
243
|
+
Publishing is manual; nothing publishes on push, merge or tag.
|
|
244
|
+
|
|
245
|
+
- **Who:** a member of the `@kumion` npm organization with publish rights on the
|
|
246
|
+
`@kumion` scope. The organization must exist before the first publish, or npm
|
|
247
|
+
refuses the scoped name.
|
|
248
|
+
- **When:** only after the release is approved. Bump `version` in `package.json`
|
|
249
|
+
(and `package-lock.json`) in a PR first; npm never accepts the same version twice.
|
|
250
|
+
- **How:** run the **Publish @kumion/cli** workflow (Actions → Run workflow). It
|
|
251
|
+
installs, typechecks, tests, builds and packs the CLI, then runs
|
|
252
|
+
`npm publish --access public` with the `NPM_TOKEN` repository
|
|
253
|
+
secret (an npm automation token for the `@kumion` scope). It dry-runs unless
|
|
254
|
+
`publish` is ticked.
|
|
255
|
+
Or, from a clean checkout of `main`:
|
|
256
|
+
|
|
257
|
+
```sh
|
|
258
|
+
cd packages/cli # not `npm --prefix`: pack/publish would take the repo root
|
|
259
|
+
npm ci
|
|
260
|
+
npm run typecheck && npm test
|
|
261
|
+
npm publish --dry-run # review the file list
|
|
262
|
+
npm publish --access public
|
|
263
|
+
```
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
5
|
+
import { ConfigFile, keychainStore } from "./credentials.js";
|
|
6
|
+
import { run } from "./main.js";
|
|
7
|
+
const dispatcher = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
|
|
8
|
+
const fetchImpl = (url, init) => undiciFetch(url, { ...init, dispatcher });
|
|
9
|
+
async function prompt(question, options = {}) {
|
|
10
|
+
if (!process.stdin.isTTY) {
|
|
11
|
+
const rl = createInterface({ input: process.stdin });
|
|
12
|
+
for await (const line of rl) {
|
|
13
|
+
rl.close();
|
|
14
|
+
return line;
|
|
15
|
+
}
|
|
16
|
+
return "";
|
|
17
|
+
}
|
|
18
|
+
process.stderr.write(question);
|
|
19
|
+
if (!options.hidden) {
|
|
20
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: false });
|
|
21
|
+
const line = await new Promise((resolve) => rl.once("line", resolve));
|
|
22
|
+
rl.close();
|
|
23
|
+
return line;
|
|
24
|
+
}
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const stdin = process.stdin;
|
|
27
|
+
let value = "";
|
|
28
|
+
stdin.setRawMode(true);
|
|
29
|
+
stdin.resume();
|
|
30
|
+
stdin.setEncoding("utf8");
|
|
31
|
+
const done = (fn) => {
|
|
32
|
+
stdin.setRawMode(false);
|
|
33
|
+
stdin.pause();
|
|
34
|
+
stdin.removeListener("data", onData);
|
|
35
|
+
process.stderr.write("\n");
|
|
36
|
+
fn();
|
|
37
|
+
};
|
|
38
|
+
const onData = (chunk) => {
|
|
39
|
+
for (const ch of chunk) {
|
|
40
|
+
if (ch === "\r" || ch === "\n")
|
|
41
|
+
return done(() => resolve(value));
|
|
42
|
+
if (ch === "\u0003")
|
|
43
|
+
return done(() => reject(new Error("Cancelled.")));
|
|
44
|
+
if (ch === "\u007f" || ch === "\b")
|
|
45
|
+
value = value.slice(0, -1);
|
|
46
|
+
else
|
|
47
|
+
value += ch;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
stdin.on("data", onData);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
const io = {
|
|
54
|
+
out: (text) => process.stdout.write(text.endsWith("\n") ? text : text + "\n"),
|
|
55
|
+
err: (text) => process.stderr.write(text.endsWith("\n") ? text : text + "\n"),
|
|
56
|
+
prompt,
|
|
57
|
+
};
|
|
58
|
+
async function stdioTransport() {
|
|
59
|
+
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
|
60
|
+
const transport = new StdioServerTransport();
|
|
61
|
+
process.stdin.once("end", () => void transport.close());
|
|
62
|
+
return transport;
|
|
63
|
+
}
|
|
64
|
+
const code = await run(process.argv.slice(2), {
|
|
65
|
+
env: process.env,
|
|
66
|
+
fetch: fetchImpl,
|
|
67
|
+
secrets: keychainStore,
|
|
68
|
+
config: ConfigFile.forEnv(process.env),
|
|
69
|
+
io,
|
|
70
|
+
sleep: (ms) => sleep(ms),
|
|
71
|
+
mcpTransport: stdioTransport,
|
|
72
|
+
});
|
|
73
|
+
process.exitCode = code;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export class ApiError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
body;
|
|
4
|
+
scope;
|
|
5
|
+
retryAfter;
|
|
6
|
+
constructor(status, body, scope, retryAfter) {
|
|
7
|
+
super(typeof body.error === "string" ? body.error : `HTTP ${status}`);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.body = body;
|
|
10
|
+
this.scope = scope;
|
|
11
|
+
this.retryAfter = retryAfter;
|
|
12
|
+
}
|
|
13
|
+
get code() {
|
|
14
|
+
return typeof this.body.code === "string" ? this.body.code : undefined;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class NetworkError extends Error {
|
|
18
|
+
url;
|
|
19
|
+
cause;
|
|
20
|
+
constructor(url, cause) {
|
|
21
|
+
super(`Could not reach ${url}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
22
|
+
this.url = url;
|
|
23
|
+
this.cause = cause;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class KumionClient {
|
|
27
|
+
creds;
|
|
28
|
+
fetchImpl;
|
|
29
|
+
constructor(creds, fetchImpl) {
|
|
30
|
+
this.creds = creds;
|
|
31
|
+
this.fetchImpl = fetchImpl;
|
|
32
|
+
}
|
|
33
|
+
get tenantId() {
|
|
34
|
+
return this.creds.tenantId;
|
|
35
|
+
}
|
|
36
|
+
tenantPath(rest) {
|
|
37
|
+
return `/api/v1/${encodeURIComponent(this.creds.tenantId)}${rest}`;
|
|
38
|
+
}
|
|
39
|
+
agentPath(agentId, rest = "") {
|
|
40
|
+
return this.tenantPath(`/agents/${encodeURIComponent(agentId)}${rest}`);
|
|
41
|
+
}
|
|
42
|
+
async request(method, path, scope, options = {}) {
|
|
43
|
+
const url = this.creds.baseUrl + path;
|
|
44
|
+
const headers = {
|
|
45
|
+
Authorization: `Bearer ${this.creds.apiKey}`,
|
|
46
|
+
Accept: "application/json",
|
|
47
|
+
};
|
|
48
|
+
if (options.body !== undefined)
|
|
49
|
+
headers["Content-Type"] = "application/json";
|
|
50
|
+
if (options.ifMatch)
|
|
51
|
+
headers["If-Match"] = `"${options.ifMatch}"`;
|
|
52
|
+
let res;
|
|
53
|
+
try {
|
|
54
|
+
res = await this.fetchImpl(url, {
|
|
55
|
+
method,
|
|
56
|
+
headers,
|
|
57
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
throw new NetworkError(url, err);
|
|
62
|
+
}
|
|
63
|
+
const text = await res.text();
|
|
64
|
+
let body = {};
|
|
65
|
+
if (text) {
|
|
66
|
+
try {
|
|
67
|
+
const parsed = JSON.parse(text);
|
|
68
|
+
body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
body = { error: `Unexpected non-JSON response: ${text.slice(0, 200)}` };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (res.status < 200 || res.status >= 300) {
|
|
75
|
+
throw new ApiError(res.status, body, scope, res.headers.get("retry-after"));
|
|
76
|
+
}
|
|
77
|
+
return { status: res.status, body };
|
|
78
|
+
}
|
|
79
|
+
async listAgents() {
|
|
80
|
+
const { body } = await this.request("GET", this.tenantPath("/agents"), "agents:read");
|
|
81
|
+
return body.agents;
|
|
82
|
+
}
|
|
83
|
+
async getAgent(agentId) {
|
|
84
|
+
const { body } = await this.request("GET", this.agentPath(agentId), "agents:read");
|
|
85
|
+
return body;
|
|
86
|
+
}
|
|
87
|
+
async patchAgent(agentId, patch, revision) {
|
|
88
|
+
const { body } = await this.request("PATCH", this.agentPath(agentId), "agents:write", {
|
|
89
|
+
body: patch,
|
|
90
|
+
ifMatch: revision,
|
|
91
|
+
});
|
|
92
|
+
return body;
|
|
93
|
+
}
|
|
94
|
+
async publishAgent(agentId, revision) {
|
|
95
|
+
const { body } = await this.request("POST", this.agentPath(agentId, "/publish"), "agents:publish", {
|
|
96
|
+
body: {},
|
|
97
|
+
ifMatch: revision,
|
|
98
|
+
});
|
|
99
|
+
return body;
|
|
100
|
+
}
|
|
101
|
+
async startTestRun(agentId) {
|
|
102
|
+
const { body } = await this.request("POST", this.agentPath(agentId, "/test-runs"), "tests:run", { body: {} });
|
|
103
|
+
return body.testRun;
|
|
104
|
+
}
|
|
105
|
+
async getTestRun(agentId, runId) {
|
|
106
|
+
const { body } = await this.request("GET", this.agentPath(agentId, `/test-runs/${encodeURIComponent(runId)}`), "tests:run");
|
|
107
|
+
return body.testRun;
|
|
108
|
+
}
|
|
109
|
+
async listTestRuns(agentId, limit) {
|
|
110
|
+
const query = limit ? `?limit=${limit}` : "";
|
|
111
|
+
const { body } = await this.request("GET", this.agentPath(agentId, `/test-runs${query}`), "tests:run");
|
|
112
|
+
return body.testRuns;
|
|
113
|
+
}
|
|
114
|
+
async createCall(agentId, campaignContactId) {
|
|
115
|
+
const { body } = await this.request("POST", this.tenantPath("/calls"), "calls:create", {
|
|
116
|
+
body: campaignContactId ? { agentId, campaignContactId } : { agentId },
|
|
117
|
+
});
|
|
118
|
+
return body;
|
|
119
|
+
}
|
|
120
|
+
async listCalls(filter = {}) {
|
|
121
|
+
const query = new URLSearchParams();
|
|
122
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
123
|
+
if (value !== undefined && value !== "")
|
|
124
|
+
query.set(key, String(value));
|
|
125
|
+
}
|
|
126
|
+
const qs = query.toString();
|
|
127
|
+
const { body } = await this.request("GET", this.tenantPath(`/calls${qs ? `?${qs}` : ""}`), "calls:read");
|
|
128
|
+
return body;
|
|
129
|
+
}
|
|
130
|
+
async getCall(callId) {
|
|
131
|
+
const { body } = await this.request("GET", this.tenantPath(`/calls/${encodeURIComponent(callId)}`), "calls:read");
|
|
132
|
+
return body.call;
|
|
133
|
+
}
|
|
134
|
+
async getTranscript(callId) {
|
|
135
|
+
const { body } = await this.request("GET", this.tenantPath(`/calls/${encodeURIComponent(callId)}/transcript`), "calls:read");
|
|
136
|
+
return body.transcript;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { UsageError } from "./errors.js";
|
|
5
|
+
export const DEFAULT_BASE_URL = "https://app.kumion.jp";
|
|
6
|
+
export const KEYCHAIN_SERVICE = "kumion-cli";
|
|
7
|
+
const KEY_PREFIX = "kum_live_";
|
|
8
|
+
export function looksLikeApiKey(value) {
|
|
9
|
+
return value.startsWith(KEY_PREFIX) && value.length >= KEY_PREFIX.length + 32;
|
|
10
|
+
}
|
|
11
|
+
export function keyPrefix(key) {
|
|
12
|
+
return key.slice(0, KEY_PREFIX.length + 4) + "…";
|
|
13
|
+
}
|
|
14
|
+
export function normalizeBaseUrl(raw) {
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(raw.trim());
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw new UsageError(`Not a valid URL: ${raw}`);
|
|
21
|
+
}
|
|
22
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
23
|
+
throw new UsageError(`The base URL must be http(s): ${raw}`);
|
|
24
|
+
}
|
|
25
|
+
return url.origin;
|
|
26
|
+
}
|
|
27
|
+
export function configDir(env) {
|
|
28
|
+
if (env.KUMION_CONFIG_DIR)
|
|
29
|
+
return env.KUMION_CONFIG_DIR;
|
|
30
|
+
if (process.platform === "win32" && env.APPDATA)
|
|
31
|
+
return join(env.APPDATA, "kumion");
|
|
32
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "kumion");
|
|
33
|
+
}
|
|
34
|
+
export class ConfigFile {
|
|
35
|
+
path;
|
|
36
|
+
constructor(path) {
|
|
37
|
+
this.path = path;
|
|
38
|
+
}
|
|
39
|
+
static forEnv(env) {
|
|
40
|
+
return new ConfigFile(join(configDir(env), "config.json"));
|
|
41
|
+
}
|
|
42
|
+
async read() {
|
|
43
|
+
let text;
|
|
44
|
+
try {
|
|
45
|
+
text = await readFile(this.path, "utf8");
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (err.code === "ENOENT")
|
|
49
|
+
return { profiles: {} };
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const parsed = JSON.parse(text);
|
|
54
|
+
return { defaultProfile: parsed.defaultProfile, profiles: parsed.profiles ?? {} };
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new UsageError(`${this.path} is not valid JSON. Fix or delete it, then log in again.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async write(config) {
|
|
61
|
+
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
62
|
+
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
63
|
+
await writeFile(tmp, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
|
|
64
|
+
await rename(tmp, this.path);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export async function resolveCredentials(input) {
|
|
68
|
+
const { env, config } = input;
|
|
69
|
+
const baseOverride = input.baseUrlFlag ?? env.KUMION_API_BASE;
|
|
70
|
+
const explicitProfile = input.profileFlag ?? env.KUMION_PROFILE;
|
|
71
|
+
if (!explicitProfile && env.KUMION_API_KEY) {
|
|
72
|
+
const apiKey = env.KUMION_API_KEY.trim();
|
|
73
|
+
const tenantId = env.KUMION_TENANT_ID?.trim();
|
|
74
|
+
if (!tenantId) {
|
|
75
|
+
throw new UsageError("KUMION_API_KEY is set but KUMION_TENANT_ID is not. Set both, or unset KUMION_API_KEY to use a saved profile.");
|
|
76
|
+
}
|
|
77
|
+
if (!looksLikeApiKey(apiKey))
|
|
78
|
+
throw new UsageError("KUMION_API_KEY does not look like a Kumion API key (kum_live_…).");
|
|
79
|
+
return { apiKey, tenantId, baseUrl: normalizeBaseUrl(baseOverride ?? DEFAULT_BASE_URL), profile: null, source: "env" };
|
|
80
|
+
}
|
|
81
|
+
const name = explicitProfile ?? config.defaultProfile;
|
|
82
|
+
if (!name) {
|
|
83
|
+
throw new UsageError("Not logged in. Run `kumion auth login`, or set KUMION_API_KEY and KUMION_TENANT_ID.");
|
|
84
|
+
}
|
|
85
|
+
const profile = config.profiles[name];
|
|
86
|
+
if (!profile) {
|
|
87
|
+
const known = Object.keys(config.profiles);
|
|
88
|
+
throw new UsageError(`No profile named "${name}".` + (known.length ? ` Known profiles: ${known.join(", ")}.` : " Run `kumion auth login`."));
|
|
89
|
+
}
|
|
90
|
+
const apiKey = await input.secrets().get(name);
|
|
91
|
+
if (!apiKey) {
|
|
92
|
+
throw new UsageError(`Profile "${name}" has no API key in the keychain. Run \`kumion auth login --profile ${name}\` again.`);
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
apiKey,
|
|
96
|
+
tenantId: profile.tenantId,
|
|
97
|
+
baseUrl: normalizeBaseUrl(baseOverride ?? profile.baseUrl ?? DEFAULT_BASE_URL),
|
|
98
|
+
profile: name,
|
|
99
|
+
source: "keychain",
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
export function keychainStore() {
|
|
103
|
+
const entry = async (profile) => {
|
|
104
|
+
let mod;
|
|
105
|
+
try {
|
|
106
|
+
mod = await import("@napi-rs/keyring");
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
throw keychainUnavailable(err);
|
|
110
|
+
}
|
|
111
|
+
return new mod.AsyncEntry(KEYCHAIN_SERVICE, profile);
|
|
112
|
+
};
|
|
113
|
+
const guard = async (run) => {
|
|
114
|
+
try {
|
|
115
|
+
return await run();
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
if (err instanceof UsageError)
|
|
119
|
+
throw err;
|
|
120
|
+
throw keychainUnavailable(err);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
get: (profile) => guard(async () => (await (await entry(profile)).getPassword()) ?? null),
|
|
125
|
+
set: (profile, apiKey) => guard(async () => (await entry(profile)).setPassword(apiKey)),
|
|
126
|
+
delete: (profile) => guard(async () => (await entry(profile)).deletePassword()),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function keychainUnavailable(err) {
|
|
130
|
+
return new UsageError(`The OS keychain is not available here (${err instanceof Error ? err.message : String(err)}). ` +
|
|
131
|
+
"Set KUMION_API_KEY and KUMION_TENANT_ID in the environment instead.");
|
|
132
|
+
}
|