@aivax/cli 0.0.0-stage → 1.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.
@@ -0,0 +1,37 @@
1
+ import { UsageError } from "../errors.js";
2
+ import { call } from "../http.js";
3
+ import { dataOption, readJson } from "../input.js";
4
+
5
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
6
+
7
+ export default {
8
+ description: "Call any API endpoint directly.",
9
+ options: {
10
+ data: dataOption(),
11
+ query: { value: "<key=value>", list: true, description: "Query parameter. Repeatable." },
12
+ header: { alias: "H", value: "<name:value>", list: true, description: "Extra request header. Repeatable." },
13
+ output: { alias: "o", value: "<file>", description: "Write the response to a file." }
14
+ },
15
+ args: "<method> <path>",
16
+ minArgs: 2,
17
+ async run(ctx) {
18
+ const [method, path] = ctx.args;
19
+ const upper = method.toUpperCase();
20
+
21
+ if (!METHODS.includes(upper)) {
22
+ throw new UsageError(`Unsupported method "${method}". Use ${METHODS.join(", ")}.`);
23
+ }
24
+
25
+ const split = (value, separator) => {
26
+ const index = value.indexOf(separator);
27
+ if (index < 1) throw new UsageError(`Invalid value "${value}". Expected name${separator}value.`);
28
+ return [value.slice(0, index).trim(), value.slice(index + 1).trim()];
29
+ };
30
+
31
+ await call(ctx, upper, path.startsWith("/") ? path : `/${path}`, {
32
+ body: ctx.options.data === undefined ? undefined : await readJson(ctx.options.data),
33
+ query: Object.fromEntries((ctx.options.query ?? []).map(value => split(value, "="))),
34
+ headers: Object.fromEntries((ctx.options.header ?? []).map(value => split(value, ":")))
35
+ });
36
+ }
37
+ };
@@ -0,0 +1,142 @@
1
+ import { UsageError } from "../errors.js";
2
+ import { fetchData, print } from "../http.js";
3
+ import { defaultEndpoint, deleteToken, findProfile, loadProfiles, resolveSession, saveProfiles, slugify, storeToken } from "../profiles.js";
4
+ import { ask } from "../prompt.js";
5
+
6
+ async function loginWithApiKey(ctx, endpoint, apiKey) {
7
+ const account = await fetchData(ctx, "GET", "/api/v1/accounts", {
8
+ auth: false,
9
+ endpoint,
10
+ headers: { Authorization: `Bearer ${apiKey}` }
11
+ });
12
+
13
+ return { accessToken: apiKey, account };
14
+ }
15
+
16
+ async function loginWithLoginKey(ctx, endpoint) {
17
+ const loginKey = ctx.options.loginKey ?? await ask("Login key: ", { hidden: true });
18
+
19
+ if (!loginKey) {
20
+ throw new UsageError("A login key is required.");
21
+ }
22
+
23
+ const send = totpCode => fetchData(ctx, "POST", "/api/v1/auth/login", {
24
+ auth: false,
25
+ endpoint,
26
+ body: { loginKey, totpCode }
27
+ });
28
+
29
+ let result = await send(ctx.options["2fa"]);
30
+
31
+ if (result.requiresTwoFactor && !result.accessToken) {
32
+ result = await send(await ask("Two-factor code: "));
33
+ }
34
+
35
+ if (!result.accessToken) {
36
+ throw new UsageError("The server did not return an access token.");
37
+ }
38
+
39
+ return result;
40
+ }
41
+
42
+ const login = {
43
+ description: "Log in to an AIVAX account and save the account profile.",
44
+ options: {
45
+ loginKey: { value: "<key>", description: "Account login key. Prompted when neither --login-key nor --api-key is given." },
46
+ apiKey: { value: "<key>", description: "Account API key. Links the profile without the login key or authenticator code." },
47
+ "2fa": { value: "<code>", description: "Six-digit authenticator code. Prompted when the account requires it." },
48
+ profileName: { value: "<name>", description: "Profile name. Defaults to the sanitized account name." },
49
+ endpoint: { value: "<url>", description: "API endpoint. Defaults to https://inference.aivax.net." }
50
+ },
51
+ async run(ctx) {
52
+ const endpoint = ctx.options.endpoint ?? defaultEndpoint();
53
+ const { accessToken, account } = ctx.options.apiKey
54
+ ? await loginWithApiKey(ctx, endpoint, ctx.options.apiKey)
55
+ : await loginWithLoginKey(ctx, endpoint);
56
+
57
+ const name = ctx.options.profileName?.trim() || slugify(account.name) || "default";
58
+ const data = await loadProfiles();
59
+
60
+ await storeToken(name, accessToken);
61
+
62
+ data.profiles[name] = {
63
+ accountId: account.id,
64
+ accountName: account.name,
65
+ email: account.email,
66
+ endpoint,
67
+ createdAt: new Date().toISOString()
68
+ };
69
+ data.default ??= name;
70
+ await saveProfiles(data);
71
+
72
+ const suffix = data.default === name ? " as the default profile" : `. Run "aivax auth use ${name}" to make it the default`;
73
+ process.stderr.write(`Logged in as ${account.name}. Profile "${name}" saved${suffix}.\n`);
74
+ }
75
+ };
76
+
77
+ const logout = {
78
+ description: "Remove the linked account profile.",
79
+ options: {
80
+ profileName: { value: "<name>", description: "Profile to remove. Defaults to --profile or the default profile." }
81
+ },
82
+ async run(ctx) {
83
+ const data = await loadProfiles();
84
+ const name = findProfile(data, ctx.options.profileName ?? ctx.options.profile ?? data.default);
85
+
86
+ await deleteToken(name);
87
+ delete data.profiles[name];
88
+
89
+ if (data.default === name) {
90
+ data.default = Object.keys(data.profiles)[0] ?? null;
91
+ }
92
+
93
+ await saveProfiles(data);
94
+ process.stderr.write(`Profile "${name}" removed from this device.\n`);
95
+ }
96
+ };
97
+
98
+ const profiles = {
99
+ aliases: ["list"],
100
+ description: "List the saved account profiles.",
101
+ async run() {
102
+ const data = await loadProfiles();
103
+ const rows = Object.entries(data.profiles)
104
+ .map(([name, profile]) => `${name === data.default ? "*" : " "} ${name}\t${profile.accountName} <${profile.email}>\t${profile.endpoint}`);
105
+
106
+ print(rows.length ? rows.join("\n") : "No profiles saved. Run \"aivax auth login\".");
107
+ }
108
+ };
109
+
110
+ const use = {
111
+ description: "Set the default account profile.",
112
+ args: "<profile>",
113
+ minArgs: 1,
114
+ async run(ctx) {
115
+ const data = await loadProfiles();
116
+ data.default = findProfile(data, ctx.args[0]);
117
+
118
+ await saveProfiles(data);
119
+ process.stderr.write(`Default profile set to "${data.default}".\n`);
120
+ }
121
+ };
122
+
123
+ const whoami = {
124
+ description: "Show the profile used by the current operation.",
125
+ async run(ctx) {
126
+ const session = await resolveSession(ctx);
127
+
128
+ if (!session.name) {
129
+ print(`Using the AIVAX_API_KEY environment variable against ${session.endpoint}.`);
130
+ return;
131
+ }
132
+
133
+ const { profiles } = await loadProfiles();
134
+ const profile = profiles[session.name];
135
+ print(`${session.name}\n${profile.accountName} <${profile.email}>\nAccount ID: ${profile.accountId}\nEndpoint: ${session.endpoint}`);
136
+ }
137
+ };
138
+
139
+ export default {
140
+ description: "Authentication-specific commands.",
141
+ commands: { login, logout, profiles, use, whoami }
142
+ };
@@ -0,0 +1,191 @@
1
+ import { basename } from "node:path";
2
+ import { UsageError } from "../errors.js";
3
+ import { call, seg } from "../http.js";
4
+ import { dataOption, openFile, payload, readSource } from "../input.js";
5
+ import { confirm } from "../prompt.js";
6
+ import { crud, filterOption } from "./crud.js";
7
+
8
+ const workflow = { alias: "w", value: "<id>", required: true, description: "Batch workflow identifier." };
9
+
10
+ const job = { alias: "j", value: "<id>", required: true, description: "Batch job identifier." };
11
+
12
+ const jobsPath = ctx => `/api/v1/batch/workflows/${seg(ctx.options.workflow)}/jobs`;
13
+
14
+ const jobPath = ctx => `${jobsPath(ctx)}/${seg(ctx.options.job)}`;
15
+
16
+ const setState = state => ({
17
+ description: `Set the job state to ${state}.`,
18
+ options: { workflow, job },
19
+ run: ctx => call(ctx, "PATCH", jobPath(ctx), { body: { state } })
20
+ });
21
+
22
+ const jobs = {
23
+ description: "Batch job commands.",
24
+ commands: {
25
+ list: {
26
+ aliases: ["ls"],
27
+ description: "List jobs of a workflow, or recent jobs of the account when --workflow is omitted.",
28
+ options: { workflow: { ...workflow, required: false }, filter: filterOption },
29
+ run: ctx => ctx.options.workflow
30
+ ? call(ctx, "GET", jobsPath(ctx), { query: { filter: ctx.options.filter } })
31
+ : call(ctx, "GET", "/api/v1/batch/jobs")
32
+ },
33
+ get: {
34
+ aliases: ["view"],
35
+ description: "Show a job with its processing summary.",
36
+ options: { workflow, job },
37
+ run: ctx => call(ctx, "GET", jobPath(ctx))
38
+ },
39
+ create: {
40
+ description: "Create a paused job. Import items, then run \"batch jobs start\".",
41
+ options: { workflow, title: { alias: "t", value: "<title>", description: "Optional job title." } },
42
+ run: ctx => call(ctx, "POST", jobsPath(ctx), { body: ctx.options.title ? { title: ctx.options.title } : {} })
43
+ },
44
+ patch: {
45
+ aliases: ["update", "edit"],
46
+ description: "Change a job title or state.",
47
+ options: {
48
+ workflow,
49
+ job,
50
+ title: { alias: "t", value: "<title>", description: "New title." },
51
+ state: { value: "<state>", description: "Active, Paused or Finished." },
52
+ data: dataOption()
53
+ },
54
+ run: async ctx => call(ctx, "PATCH", jobPath(ctx), { body: await payload(ctx, { title: ctx.options.title, state: ctx.options.state }) })
55
+ },
56
+ start: setState("Active"),
57
+ pause: setState("Paused"),
58
+ finish: setState("Finished"),
59
+ delete: {
60
+ aliases: ["rm"],
61
+ description: "Delete a job and all its items.",
62
+ options: { workflow, job },
63
+ async run(ctx) {
64
+ await confirm(ctx, `Delete job ${ctx.options.job} and all its items?`);
65
+ await call(ctx, "DELETE", jobPath(ctx));
66
+ }
67
+ },
68
+ export: {
69
+ description: "Export job results as JSONL.",
70
+ options: {
71
+ workflow,
72
+ job,
73
+ state: { value: "<state>", description: "all, finished, failed, errors, success or an item state." },
74
+ confidence: { value: "<level>", description: "high or low." },
75
+ output: { alias: "o", value: "<file>", description: "Write the export to a file." }
76
+ },
77
+ run: ctx => call(ctx, "GET", `${jobPath(ctx)}/export.jsonl`, {
78
+ query: { state: ctx.options.state, confidence: ctx.options.confidence },
79
+ agentOutput: false
80
+ })
81
+ }
82
+ }
83
+ };
84
+
85
+ const itemId = { value: "<id>", required: true, description: "Item identifier." };
86
+
87
+ const items = {
88
+ description: "Batch item commands.",
89
+ commands: {
90
+ import: {
91
+ description: "Import items from files or text. Lines mode imports each non-empty line as one item.",
92
+ options: {
93
+ workflow,
94
+ job,
95
+ file: { alias: "f", value: "<file>", list: true, description: "Input file. Repeatable." },
96
+ text: { value: "<text>", description: "Manual item input (text mode). Use @file or - to read it." },
97
+ mode: { alias: "m", value: "<mode>", description: "lines (default), files, zip or text." }
98
+ },
99
+ async run(ctx) {
100
+ const { options } = ctx;
101
+ const form = new FormData();
102
+
103
+ if (!options.file && options.text === undefined) {
104
+ throw new UsageError("Provide items with -f <file> or --text <text>.");
105
+ }
106
+
107
+ form.append("mode", options.mode ?? (options.file ? "lines" : "text"));
108
+
109
+ for (const path of options.file ?? []) {
110
+ form.append("items", await openFile(path), basename(path));
111
+ }
112
+
113
+ if (options.text !== undefined) {
114
+ form.append("text", await readSource(options.text));
115
+ }
116
+
117
+ await call(ctx, "POST", `${jobPath(ctx)}/items`, { body: form });
118
+ }
119
+ },
120
+ list: {
121
+ aliases: ["ls"],
122
+ description: "List job items.",
123
+ options: {
124
+ workflow,
125
+ job,
126
+ state: { value: "<state>", description: "Pending, Finished, ExecutionError, ValidationError..." },
127
+ confidence: { value: "<level>", description: "high or low." },
128
+ filter: filterOption,
129
+ sort: { value: "<order>", description: "inserted-desc, inserted-asc, processed-desc or processed-asc." },
130
+ limit: { value: "<n>", number: true, description: "Maximum number of items." }
131
+ },
132
+ run: ctx => call(ctx, "GET", `${jobPath(ctx)}/items`, {
133
+ query: {
134
+ state: ctx.options.state,
135
+ confidence: ctx.options.confidence,
136
+ filter: ctx.options.filter,
137
+ sort: ctx.options.sort,
138
+ limit: ctx.options.limit
139
+ }
140
+ })
141
+ },
142
+ get: {
143
+ description: "Show one item.",
144
+ options: { workflow, job, id: itemId },
145
+ run: ctx => call(ctx, "GET", `${jobPath(ctx)}/items/${seg(ctx.options.id)}`)
146
+ },
147
+ patch: {
148
+ aliases: ["update", "edit"],
149
+ description: "Edit one item.",
150
+ options: { workflow, job, id: itemId, data: dataOption(true) },
151
+ run: async ctx => call(ctx, "PATCH", `${jobPath(ctx)}/items/${seg(ctx.options.id)}`, { body: await payload(ctx) })
152
+ },
153
+ delete: {
154
+ aliases: ["rm"],
155
+ description: "Delete one item, or many items with --mode.",
156
+ options: {
157
+ workflow,
158
+ job,
159
+ id: { ...itemId, required: false },
160
+ mode: { value: "<mode>", description: "Bulk removal: pending, finished, errors or all." }
161
+ },
162
+ async run(ctx) {
163
+ const { id, mode } = ctx.options;
164
+
165
+ if (!id && !mode) {
166
+ throw new UsageError("Provide --id <item> or --mode <pending|finished|errors|all>.");
167
+ }
168
+
169
+ await confirm(ctx, id ? `Delete item ${id}?` : `Delete ${mode} items of job ${ctx.options.job}?`);
170
+ await call(ctx, "DELETE", id ? `${jobPath(ctx)}/items/${seg(id)}` : `${jobPath(ctx)}/items`, { query: { mode } });
171
+ }
172
+ },
173
+ retry: {
174
+ description: "Retry failed or low-confidence items.",
175
+ options: { workflow, job, mode: { value: "<mode>", description: "errors, execution-error, validation-error or low-confidence." } },
176
+ run: ctx => call(ctx, "POST", `${jobPath(ctx)}/items/retry`, { query: { mode: ctx.options.mode } })
177
+ }
178
+ }
179
+ };
180
+
181
+ export default {
182
+ description: "Batch job commands.",
183
+ commands: {
184
+ workflows: {
185
+ description: "Batch workflow commands.",
186
+ commands: crud({ base: "/api/v1/batch/workflows", noun: "batch workflow" })
187
+ },
188
+ jobs,
189
+ items
190
+ }
191
+ };
@@ -0,0 +1,157 @@
1
+ import { call, seg } from "../http.js";
2
+ import { dataOption, payload, readSource } from "../input.js";
3
+ import { confirm } from "../prompt.js";
4
+ import { crud, filterOption } from "./crud.js";
5
+
6
+ const client = { alias: "c", value: "<id>", required: true, description: "Chat client identifier." };
7
+
8
+ const clientPath = ctx => `/api/v1/web-chat-client/${seg(ctx.options.client)}`;
9
+
10
+ const schedulesPath = ctx => `/api/v1/web-chat-clients/${seg(ctx.options.client)}/hook-schedules`;
11
+
12
+ const accessKey = { alias: "k", value: "<key>", required: true, description: "Session access key." };
13
+
14
+ const publicPath = ctx => `/api/v1/public/chat-clients/${seg(ctx.options.accessKey)}`;
15
+
16
+ const sessions = {
17
+ description: "Chat client session commands.",
18
+ commands: {
19
+ list: {
20
+ aliases: ["ls"],
21
+ description: "List the sessions of a chat client.",
22
+ options: { client, filter: filterOption },
23
+ run: ctx => call(ctx, "GET", `${clientPath(ctx)}/sessions`, { query: { filter: ctx.options.filter } })
24
+ },
25
+ create: {
26
+ description: "Create a session and return its access key.",
27
+ options: {
28
+ client,
29
+ context: { value: "<text>", description: "Extra context for the session. Use @file or - to read it." },
30
+ tag: { value: "<tag>", description: "Optional session tag (external user id)." },
31
+ expires: { value: "<seconds>", number: true, description: "Session lifetime in seconds." },
32
+ data: dataOption()
33
+ },
34
+ async run(ctx) {
35
+ const body = await payload(ctx, {
36
+ extraContext: ctx.options.context && await readSource(ctx.options.context),
37
+ tag: ctx.options.tag,
38
+ expires: ctx.options.expires
39
+ });
40
+
41
+ await call(ctx, "POST", `${clientPath(ctx)}/sessions`, { body });
42
+ }
43
+ },
44
+ delete: {
45
+ aliases: ["rm"],
46
+ description: "Delete a session.",
47
+ options: { client, id: { value: "<id>", required: true, description: "Session identifier." } },
48
+ async run(ctx) {
49
+ await confirm(ctx, `Delete session ${ctx.options.id}?`);
50
+ await call(ctx, "DELETE", `${clientPath(ctx)}/sessions/${seg(ctx.options.id)}`);
51
+ }
52
+ }
53
+ }
54
+ };
55
+
56
+ const integrations = {
57
+ description: "Messaging integration commands (Zapi, Telegram, EvolutionApi, Kapso).",
58
+ commands: {
59
+ set: {
60
+ description: "Create or replace an integration.",
61
+ options: { client, data: dataOption(true) },
62
+ run: async ctx => call(ctx, "PUT", `${clientPath(ctx)}/integrations`, { body: await payload(ctx) })
63
+ },
64
+ delete: {
65
+ aliases: ["rm"],
66
+ description: "Remove an integration.",
67
+ options: { client, name: { alias: "n", value: "<name>", required: true, description: "Zapi, Telegram, EvolutionApi or Kapso." } },
68
+ async run(ctx) {
69
+ await confirm(ctx, `Remove the ${ctx.options.name} integration?`);
70
+ await call(ctx, "DELETE", `${clientPath(ctx)}/integrations/${seg(ctx.options.name)}`);
71
+ }
72
+ }
73
+ }
74
+ };
75
+
76
+ const scheduleKind = { alias: "t", value: "<type>", required: true, description: "schedule (one-time) or recurring." };
77
+
78
+ const scheduleItem = ctx => `${schedulesPath(ctx)}/${ctx.options.type === "recurring" ? "recurring" : "schedules"}/${seg(ctx.options.id)}`;
79
+
80
+ const scheduleId = { value: "<id>", required: true, description: "Schedule or recurring task identifier." };
81
+
82
+ const schedules = {
83
+ description: "Scheduled hook activation commands.",
84
+ commands: {
85
+ list: {
86
+ aliases: ["ls"],
87
+ description: "List one-time schedules and recurring tasks.",
88
+ options: { client, user: { alias: "u", value: "<id>", description: "Restrict to one external user id." } },
89
+ run: ctx => call(ctx, "GET", schedulesPath(ctx), { query: { "external-user-id": ctx.options.user } })
90
+ },
91
+ get: {
92
+ description: "Show one schedule or recurring task.",
93
+ options: { client, type: scheduleKind, id: scheduleId },
94
+ run: ctx => call(ctx, "GET", scheduleItem(ctx))
95
+ },
96
+ cancel: {
97
+ description: "Cancel a schedule or recurring task.",
98
+ options: { client, type: scheduleKind, id: scheduleId },
99
+ async run(ctx) {
100
+ await confirm(ctx, `Cancel ${ctx.options.type} ${ctx.options.id}?`);
101
+ await call(ctx, "DELETE", scheduleItem(ctx));
102
+ }
103
+ }
104
+ }
105
+ };
106
+
107
+ const talk = {
108
+ aliases: ["send"],
109
+ description: "Send a prompt to a public chat session.",
110
+ options: {
111
+ accessKey,
112
+ prompt: { alias: "p", value: "<text>", description: "Message text. Use @file or - to read it. Also accepted as positional text." },
113
+ instructions: { value: "<text>", description: "Extra context for this inference only." },
114
+ noCommit: { description: "Do not save this turn in the session history." },
115
+ data: dataOption()
116
+ },
117
+ args: "[prompt]",
118
+ async run(ctx) {
119
+ const body = await payload(ctx, {
120
+ prompt: ctx.options.prompt ? await readSource(ctx.options.prompt) : ctx.args.join(" ") || undefined,
121
+ instructions: ctx.options.instructions,
122
+ commit: ctx.options.noCommit ? false : undefined
123
+ });
124
+
125
+ await call(ctx, "POST", `${publicPath(ctx)}/prompt`, { body });
126
+ }
127
+ };
128
+
129
+ const session = {
130
+ description: "Show a public session, its transcript, or retry its last message.",
131
+ options: {
132
+ accessKey,
133
+ transcript: { description: "Download the session transcript." },
134
+ retry: { description: "Retry the last message of the session." },
135
+ output: { alias: "o", value: "<file>", description: "Write the transcript to a file." }
136
+ },
137
+ run(ctx) {
138
+ if (ctx.options.retry) return call(ctx, "POST", `${publicPath(ctx)}/retry`);
139
+ if (ctx.options.transcript) return call(ctx, "GET", `${publicPath(ctx)}/transcript.json`, { agentOutput: false });
140
+ return call(ctx, "GET", publicPath(ctx));
141
+ }
142
+ };
143
+
144
+ const { list, ...rest } = crud({ base: "/api/v1/web-chat-client", noun: "chat client", updateMethod: "PUT" });
145
+
146
+ export default {
147
+ description: "Commands for Chat Clients.",
148
+ commands: {
149
+ list: { ...list, options: {} },
150
+ ...rest,
151
+ sessions,
152
+ integrations,
153
+ schedules,
154
+ talk,
155
+ session
156
+ }
157
+ };
@@ -0,0 +1,92 @@
1
+ import { call, seg } from "../http.js";
2
+ import { confirm } from "../prompt.js";
3
+
4
+ const id = { value: "<id>", required: true, description: "Conversation identifier." };
5
+
6
+ const exportOptions = {
7
+ media: { value: "<mode>", description: "text (default) or include." },
8
+ thinking: { value: "<mode>", description: "visible (default), all or none." },
9
+ truncate: { value: "<tokens>", number: true, description: "Maximum tokens per conversation. 0 disables truncation." },
10
+ output: { alias: "o", value: "<file>", description: "Write the export to a file." }
11
+ };
12
+
13
+ const exportQuery = ctx => ({
14
+ period: ctx.options.period,
15
+ media: ctx.options.media,
16
+ thinking: ctx.options.thinking,
17
+ truncate: ctx.options.truncate
18
+ });
19
+
20
+ const filters = {
21
+ model: "--model",
22
+ user: "--user",
23
+ apiKey: "--api-key",
24
+ gateway: "--gateway",
25
+ chatClient: "--chat-client",
26
+ chatSession: "--chat-session"
27
+ };
28
+
29
+ export default {
30
+ description: "Conversation and observability commands.",
31
+ commands: {
32
+ list: {
33
+ aliases: ["ls"],
34
+ description: "List recent conversations.",
35
+ options: {
36
+ minutes: { value: "<n>", number: true, description: "Lookback window in minutes (default 120)." },
37
+ from: { value: "<date>", description: "ISO 8601 start date." },
38
+ to: { value: "<date>", description: "ISO 8601 end date." },
39
+ model: { alias: "m", value: "<model>", description: "Filter by model." },
40
+ user: { alias: "u", value: "<id>", description: "Filter by external user." },
41
+ apiKey: { value: "<id>", description: "Filter by API key." },
42
+ gateway: { alias: "g", value: "<id>", description: "Filter by AI gateway." },
43
+ chatClient: { value: "<id>", description: "Filter by chat client." },
44
+ chatSession: { value: "<id>", description: "Filter by chat session." },
45
+ filter: { value: "<expr>", description: "Raw filter expression, e.g. \"--gateway <id> -u joe\"." }
46
+ },
47
+ run(ctx) {
48
+ const expression = [
49
+ ...Object.entries(filters)
50
+ .filter(([key]) => ctx.options[key])
51
+ .map(([key, flag]) => `${flag} ${JSON.stringify(ctx.options[key])}`),
52
+ ctx.options.filter
53
+ ].filter(Boolean).join(" ");
54
+
55
+ return call(ctx, "GET", "/api/v1/conversations", {
56
+ query: {
57
+ offsetminutes: ctx.options.minutes,
58
+ timeStart: ctx.options.from,
59
+ timeEnd: ctx.options.to,
60
+ filter: expression
61
+ }
62
+ });
63
+ }
64
+ },
65
+ get: {
66
+ aliases: ["view"],
67
+ description: "Show one conversation.",
68
+ options: { id },
69
+ run: ctx => call(ctx, "GET", `/api/v1/conversations/${seg(ctx.options.id)}`)
70
+ },
71
+ export: {
72
+ description: "Export one conversation as JSON, or every conversation of a period as JSONL when --id is omitted.",
73
+ options: {
74
+ id: { ...id, required: false },
75
+ period: { value: "<period>", description: "2h, 1d, 7d (default) or 30d." },
76
+ ...exportOptions
77
+ },
78
+ run: ctx => call(ctx, "GET", ctx.options.id
79
+ ? `/api/v1/conversations/${seg(ctx.options.id)}/export.json`
80
+ : "/api/v1/conversations/management/export.jsonl", { query: exportQuery(ctx), agentOutput: false })
81
+ },
82
+ delete: {
83
+ aliases: ["rm"],
84
+ description: "Delete a conversation.",
85
+ options: { id },
86
+ async run(ctx) {
87
+ await confirm(ctx, `Delete conversation ${ctx.options.id}?`);
88
+ await call(ctx, "DELETE", `/api/v1/conversations/${seg(ctx.options.id)}`);
89
+ }
90
+ }
91
+ }
92
+ };