@octen.ai/cli 0.14.0 → 0.15.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/README.md +38 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/errors.js +8 -0
- package/dist/cli.js +2 -0
- package/dist/commands/completion.js +79 -24
- package/dist/commands/monitor/client.d.ts +6 -0
- package/dist/commands/monitor/client.js +9 -0
- package/dist/commands/monitor/confirm.d.ts +5 -0
- package/dist/commands/monitor/confirm.js +19 -0
- package/dist/commands/monitor/errors.d.ts +5 -0
- package/dist/commands/monitor/errors.js +38 -0
- package/dist/commands/monitor/index.d.ts +13 -0
- package/dist/commands/monitor/index.js +252 -0
- package/dist/commands/monitor/options.d.ts +45 -0
- package/dist/commands/monitor/options.js +187 -0
- package/dist/output/pretty/monitor.d.ts +7 -0
- package/dist/output/pretty/monitor.js +142 -0
- package/package.json +3 -2
- package/skills/manifest.json +1 -0
- package/skills/octen-monitor/SKILL.md +313 -0
- package/skills/octen-monitor/agents/openai.yaml +4 -0
- package/skills/octen-web-search/SKILL.md +6 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Command-line tool for Octen — web search, extract, chat, embeddings, and one-c
|
|
|
10
10
|
npm i -g @octen.ai/cli
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
Or run without installing: `npx @octen.ai/cli <command>`. Requires Node.js
|
|
13
|
+
Or run without installing: `npx @octen.ai/cli <command>`. Requires Node.js 20+.
|
|
14
14
|
Uninstall: `npm uninstall -g @octen.ai/cli`.
|
|
15
15
|
|
|
16
16
|
### Without Node.js — Homebrew (macOS/Linux)
|
|
@@ -553,6 +553,43 @@ Options: `-n` (result count 1–10), `--time-range` (day|week|month|year or d|w|
|
|
|
553
553
|
|
|
554
554
|
---
|
|
555
555
|
|
|
556
|
+
### `octen monitor`
|
|
557
|
+
|
|
558
|
+
Watch a topic (new results for a search query) or up to 10 pages (changes to their content) on a schedule, and get told only when a change meets a plain-language condition — by webhook, by email, or by reading the events.
|
|
559
|
+
|
|
560
|
+
```sh
|
|
561
|
+
octen monitor create --topic "solid-state battery breakthroughs" --condition "a carmaker announces a mass production date" --interval 1d
|
|
562
|
+
octen monitor create --page https://example.com/pricing --field "price:number:Monthly price in USD" --condition "price drops more than 10%"
|
|
563
|
+
octen monitor list --status active
|
|
564
|
+
octen monitor events mon_123 --limit 20
|
|
565
|
+
octen monitor pause mon_123
|
|
566
|
+
octen monitor delete mon_123
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
| Subcommand | What it does |
|
|
570
|
+
|---|---|
|
|
571
|
+
| `create` | Create a monitor; its first run starts right away |
|
|
572
|
+
| `list` | List monitors (`--status`, `--name`, `--limit`, `--cursor` or `--page-no`) |
|
|
573
|
+
| `get <id>` | Show a monitor, including why it is paused |
|
|
574
|
+
| `update <id>` | Change a monitor; sends only the options given |
|
|
575
|
+
| `pause <id>` / `resume <id>` | Stop or restart scheduled runs |
|
|
576
|
+
| `delete <id>` | Delete a monitor; asks first unless `--yes` |
|
|
577
|
+
| `trigger <id>` | Run it now, outside the schedule |
|
|
578
|
+
| `runs <id>` / `run <id> <run_id>` | List runs, or show one with its items |
|
|
579
|
+
| `events <id>` | What it found (`--run`, `--order-by`, `--limit` 1–20, `--cursor`) |
|
|
580
|
+
|
|
581
|
+
Options of `create` and `update`: `--topic` or `--page` (repeatable), `--field name:type[:description]` (type `string`, `number` or `boolean`, repeatable), `--include-domains` / `--exclude-domains` (topic monitors), `--name`, `--condition`, `--interval` (`5m`–`59m`, `1h`–`100h` or `1d`–`30d`; the API runs it hourly when unset) or `--cron` with `--timezone`, `--webhook`, `--email` (repeatable), `--metadata key=value` (repeatable), and `--params '<json>'` or `--params @file.json` for any other request field. `update` also takes `--status`, `--clear condition,webhook,email,metadata` and `--rotate-secret`; its `--email` replaces all existing recipients and its `--metadata` all existing pairs, so pass every value you want to keep.
|
|
582
|
+
|
|
583
|
+
**Deleting asks first.** In a terminal, `delete` shows the monitor and waits for `y`. In a script or pipe it refuses (exit 2) unless you pass `--yes`.
|
|
584
|
+
|
|
585
|
+
**Webhook secret.** Adding a webhook or `--rotate-secret` returns the signing secret once; the terminal view highlights it, and `--json` includes it. Verify deliveries with the webhook verification function of the Octen SDKs.
|
|
586
|
+
|
|
587
|
+
**Writes are not retried after they may have been sent**, because the API has no idempotency key. The only case where a write is retried is HTTP 429 (up to three retries, the SDK's default), which the API returns without applying the request. If `create`, `update`, `pause`, `resume`, `delete` or `trigger` times out or gets a server error, the request may already have taken effect: check with `octen monitor list` or `get` before trying again (for `trigger`, look for a new manual run with `octen monitor runs <id>`: the monitor's last run only changes once the run finishes). Error messages carry the API code, with a hint for the common ones (for example `409103`: the monitor is paused).
|
|
588
|
+
|
|
589
|
+
Pricing: a topic monitor costs $2 per 1,000 runs and a page monitor $3 per 1,000 runs per URL; skipped and failed runs are free. An account can have up to 30 monitors. See [Monitor](https://docs.octen.ai/capabilities/monitor).
|
|
590
|
+
|
|
591
|
+
---
|
|
592
|
+
|
|
556
593
|
### `octen configure-mcp`
|
|
557
594
|
|
|
558
595
|
Configure the Octen MCP server in AI clients (merges into existing config, does not clobber).
|
package/dist/api/errors.d.ts
CHANGED
|
@@ -26,6 +26,10 @@ export declare class OctenNetworkError extends OctenError {
|
|
|
26
26
|
/** A stream that was malformed, truncated, or carried a typed error event. */
|
|
27
27
|
export declare class OctenStreamError extends OctenError {
|
|
28
28
|
}
|
|
29
|
+
/** The user answered no to a confirmation prompt; nothing was sent. */
|
|
30
|
+
export declare class OctenCancelledError extends OctenError {
|
|
31
|
+
constructor(message?: string);
|
|
32
|
+
}
|
|
29
33
|
export declare class OctenAPIError extends OctenError {
|
|
30
34
|
status: number;
|
|
31
35
|
body?: unknown | undefined;
|
package/dist/api/errors.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OctenAuthenticationError as SdkAuthenticationError, OctenValidationError as SdkValidationError, } from "@octen.ai/sdk";
|
|
1
2
|
export class OctenError extends Error {
|
|
2
3
|
}
|
|
3
4
|
export class OctenAuthError extends OctenError {
|
|
@@ -26,6 +27,10 @@ export class OctenNetworkError extends OctenError {
|
|
|
26
27
|
/** A stream that was malformed, truncated, or carried a typed error event. */
|
|
27
28
|
export class OctenStreamError extends OctenError {
|
|
28
29
|
}
|
|
30
|
+
/** The user answered no to a confirmation prompt; nothing was sent. */
|
|
31
|
+
export class OctenCancelledError extends OctenError {
|
|
32
|
+
constructor(message = "Cancelled.") { super(message); }
|
|
33
|
+
}
|
|
29
34
|
export class OctenAPIError extends OctenError {
|
|
30
35
|
status;
|
|
31
36
|
body;
|
|
@@ -72,5 +77,8 @@ export function errorMessage(payload, fallback) {
|
|
|
72
77
|
export function exitCodeFor(err) {
|
|
73
78
|
if (err instanceof OctenAuthError || err instanceof OctenValidationError)
|
|
74
79
|
return 2;
|
|
80
|
+
// The monitor commands throw the SDK's own classes, which are not these.
|
|
81
|
+
if (err instanceof SdkValidationError || err instanceof SdkAuthenticationError)
|
|
82
|
+
return 2;
|
|
75
83
|
return 1;
|
|
76
84
|
}
|
package/dist/cli.js
CHANGED
|
@@ -18,6 +18,7 @@ import { registerVlEmbed } from "./commands/vlEmbed.js";
|
|
|
18
18
|
import { registerImageSearch } from "./commands/imageSearch.js";
|
|
19
19
|
import { registerDesignSearch } from "./commands/designSearch.js";
|
|
20
20
|
import { registerVideoSearch } from "./commands/videoSearch.js";
|
|
21
|
+
import { registerMonitor } from "./commands/monitor/index.js";
|
|
21
22
|
import { registerConfigureMcp } from "./commands/configureMcp.js";
|
|
22
23
|
import { registerConfigureSkills } from "./commands/configureSkills.js";
|
|
23
24
|
import { registerReset } from "./commands/reset.js";
|
|
@@ -58,6 +59,7 @@ registerVlEmbed(program);
|
|
|
58
59
|
registerImageSearch(program);
|
|
59
60
|
registerDesignSearch(program);
|
|
60
61
|
registerVideoSearch(program);
|
|
62
|
+
registerMonitor(program);
|
|
61
63
|
registerLogin(program);
|
|
62
64
|
registerLogout(program);
|
|
63
65
|
registerWhoami(program);
|
|
@@ -20,33 +20,79 @@ function buildModel(program) {
|
|
|
20
20
|
const subcommands = program.commands.map((c) => c.name());
|
|
21
21
|
const globalFlags = flagsFor(program.options);
|
|
22
22
|
const subFlags = {};
|
|
23
|
+
const groups = {};
|
|
23
24
|
for (const cmd of program.commands) {
|
|
24
25
|
subFlags[cmd.name()] = flagsFor(cmd.options);
|
|
26
|
+
if (cmd.commands.length) {
|
|
27
|
+
const inner = {};
|
|
28
|
+
for (const c of cmd.commands)
|
|
29
|
+
inner[c.name()] = flagsFor(c.options);
|
|
30
|
+
groups[cmd.name()] = { subcommands: cmd.commands.map((c) => c.name()), subFlags: inner };
|
|
31
|
+
}
|
|
25
32
|
}
|
|
26
|
-
|
|
33
|
+
const globalValueFlags = flagsFor(program.options.filter((o) => o.required || o.optional));
|
|
34
|
+
return { subcommands, globalFlags, globalValueFlags, subFlags, groups };
|
|
35
|
+
}
|
|
36
|
+
// `case` branches shared by the bash function and the native zsh file. A group nests a
|
|
37
|
+
// second `case` on the next word: its subcommands until one is typed, then that one's flags.
|
|
38
|
+
function caseBranches(model, sub2) {
|
|
39
|
+
return model.subcommands
|
|
40
|
+
.map((sub) => {
|
|
41
|
+
const group = model.groups[sub];
|
|
42
|
+
if (!group) {
|
|
43
|
+
const flags = [...(model.subFlags[sub] ?? []), ...model.globalFlags].join(" ");
|
|
44
|
+
return ` ${sub})\n opts="${flags}"\n ;;`;
|
|
45
|
+
}
|
|
46
|
+
const first = [...group.subcommands, ...(model.subFlags[sub] ?? []), ...model.globalFlags].join(" ");
|
|
47
|
+
const inner = group.subcommands
|
|
48
|
+
.map((c) => ` ${c}) opts="${[...(group.subFlags[c] ?? []), ...model.globalFlags].join(" ")}" ;;`)
|
|
49
|
+
.join("\n");
|
|
50
|
+
return ` ${sub})\n case ${sub2} in\n "") opts="${first}" ;;\n${inner}\n *) opts="${model.globalFlags.join(" ")}" ;;\n esac\n ;;`;
|
|
51
|
+
})
|
|
52
|
+
.join("\n");
|
|
27
53
|
}
|
|
28
54
|
/**
|
|
29
55
|
* The shared bash `_octen` completion function, reused verbatim by the zsh
|
|
30
56
|
* script (via bashcompinit). Returns the full function plus `complete` line.
|
|
31
57
|
*/
|
|
32
|
-
|
|
58
|
+
// `lineScan` is bash only: COMP_WORDS there also splits at = and :, and the zsh eval
|
|
59
|
+
// script reuses this function, where neither the substring nor `read -a` works.
|
|
60
|
+
function bashFunction(model, lineScan = true) {
|
|
33
61
|
const subs = model.subcommands.join(" ");
|
|
34
62
|
const globals = model.globalFlags.join(" ");
|
|
35
63
|
// Build the case branches for per-subcommand flag completion.
|
|
36
|
-
const branches = model
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
64
|
+
const branches = caseBranches(model, '"$sub2"');
|
|
65
|
+
const valueFlags = model.globalValueFlags.length ? ` ${model.globalValueFlags.join("|")}) skip=1 ;;\n` : "";
|
|
66
|
+
const scan = lineScan
|
|
67
|
+
? ` local cur sub sub2 i opts skip line n
|
|
68
|
+
local -a words
|
|
69
|
+
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
70
|
+
sub=""
|
|
71
|
+
sub2=""
|
|
72
|
+
skip=0
|
|
73
|
+
# COMP_WORDS also splits at = and :, so find the commands in the line split at spaces only.
|
|
74
|
+
cur="\${cur//\\\\$'\\n'/}"
|
|
75
|
+
line="\${COMP_LINE:0:COMP_POINT}"
|
|
76
|
+
line="\${line//\\\\$'\\n'/ }"
|
|
77
|
+
line="\${line//$'\\n'/ }"
|
|
78
|
+
IFS=$' \\t' read -ra words <<< "$line"
|
|
79
|
+
n=\${#words[@]}
|
|
80
|
+
[[ -z "$line" || "$line" == *[[:space:]] ]] && n=$((n+1))
|
|
81
|
+
for (( i=1; i < n-1; i++ )); do`
|
|
82
|
+
: ` local cur sub sub2 i opts skip
|
|
83
|
+
local -a words
|
|
44
84
|
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
45
85
|
sub=""
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
86
|
+
sub2=""
|
|
87
|
+
skip=0
|
|
88
|
+
words=("\${COMP_WORDS[@]}")
|
|
89
|
+
for (( i=1; i < COMP_CWORD; i++ )); do`;
|
|
90
|
+
return `_octen() {
|
|
91
|
+
${scan}
|
|
92
|
+
if [ "$skip" = 1 ]; then skip=0; continue; fi
|
|
93
|
+
case "\${words[i]}" in
|
|
94
|
+
${valueFlags} -*) ;;
|
|
95
|
+
*) if [ -z "$sub" ]; then sub="\${words[i]}"; elif [ -z "$sub2" ]; then sub2="\${words[i]}"; fi ;;
|
|
50
96
|
esac
|
|
51
97
|
done
|
|
52
98
|
if [ -z "$sub" ]; then
|
|
@@ -80,7 +126,7 @@ function zshScript(model) {
|
|
|
80
126
|
"fi",
|
|
81
127
|
"autoload -Uz bashcompinit && bashcompinit",
|
|
82
128
|
].join("\n");
|
|
83
|
-
return `${preamble}\n${bashFunction(model)}\n`;
|
|
129
|
+
return `${preamble}\n${bashFunction(model, false)}\n`;
|
|
84
130
|
}
|
|
85
131
|
/** Strip leading dashes for fish's `-l`/`-s` which want bare names. */
|
|
86
132
|
function fishFlagArgs(flags) {
|
|
@@ -107,6 +153,16 @@ function fishScript(model) {
|
|
|
107
153
|
if (flagArgs) {
|
|
108
154
|
lines.push(`complete -c octen -n '__fish_seen_subcommand_from ${sub}' ${flagArgs}`);
|
|
109
155
|
}
|
|
156
|
+
const group = model.groups[sub];
|
|
157
|
+
if (!group)
|
|
158
|
+
continue;
|
|
159
|
+
const names = group.subcommands.join(" ");
|
|
160
|
+
lines.push(`complete -c octen -f -n '__fish_seen_subcommand_from ${sub}; and not __fish_seen_subcommand_from ${names}' -a '${names}'`);
|
|
161
|
+
for (const c of group.subcommands) {
|
|
162
|
+
const args = fishFlagArgs(group.subFlags[c] ?? []);
|
|
163
|
+
if (args)
|
|
164
|
+
lines.push(`complete -c octen -n '__fish_seen_subcommand_from ${sub}; and __fish_seen_subcommand_from ${c}' ${args}`);
|
|
165
|
+
}
|
|
110
166
|
}
|
|
111
167
|
const globalArgs = fishFlagArgs(model.globalFlags);
|
|
112
168
|
if (globalArgs) {
|
|
@@ -124,23 +180,22 @@ function fishScript(model) {
|
|
|
124
180
|
function zshCompletionFile(model) {
|
|
125
181
|
const subs = model.subcommands.join(" ");
|
|
126
182
|
const globals = model.globalFlags.join(" ");
|
|
127
|
-
const branches = model
|
|
128
|
-
|
|
129
|
-
const flags = [...(model.subFlags[sub] ?? []), ...model.globalFlags].join(" ");
|
|
130
|
-
return ` ${sub})\n opts="${flags}"\n ;;`;
|
|
131
|
-
})
|
|
132
|
-
.join("\n");
|
|
183
|
+
const branches = caseBranches(model, "$sub2");
|
|
184
|
+
const valueFlags = model.globalValueFlags.length ? ` ${model.globalValueFlags.join("|")}) skip=1 ;;\n` : "";
|
|
133
185
|
return `#compdef octen
|
|
134
186
|
# octen zsh completion (native, fpath-autoloaded). Do not edit by hand;
|
|
135
187
|
# regenerate with: octen completion zsh --install
|
|
136
188
|
_octen() {
|
|
137
|
-
local cur sub i opts
|
|
189
|
+
local cur sub sub2 i opts skip
|
|
138
190
|
cur=\${words[CURRENT]}
|
|
139
191
|
sub=""
|
|
192
|
+
sub2=""
|
|
193
|
+
skip=0
|
|
140
194
|
for (( i = 2; i < CURRENT; i++ )); do
|
|
195
|
+
if [[ $skip == 1 ]]; then skip=0; continue; fi
|
|
141
196
|
case \${words[i]} in
|
|
142
|
-
-*) ;;
|
|
143
|
-
*) sub=\${words[i]};
|
|
197
|
+
${valueFlags} -*) ;;
|
|
198
|
+
*) if [[ -z $sub ]]; then sub=\${words[i]}; elif [[ -z $sub2 ]]; then sub2=\${words[i]}; fi ;;
|
|
144
199
|
esac
|
|
145
200
|
done
|
|
146
201
|
if [[ -z $sub ]]; then
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import Octen from "@octen.ai/sdk";
|
|
2
|
+
import { resolveApiKey, resolveBaseUrl } from "../../config/resolve.js";
|
|
3
|
+
/** SDK client for the monitor commands; the SDK owns retries and request checks. */
|
|
4
|
+
export function makeMonitorClient(g) {
|
|
5
|
+
return new Octen({
|
|
6
|
+
apiKey: resolveApiKey(g.apiKey, process.env),
|
|
7
|
+
baseURL: resolveBaseUrl(g.baseUrl, process.env),
|
|
8
|
+
});
|
|
9
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
/** Ask a yes/no question; only "y" or "yes" counts as yes, and input that ends unanswered (Ctrl-D) is no. */
|
|
3
|
+
export function confirm(question, io = { input: process.stdin, output: process.stderr }) {
|
|
4
|
+
// The prompt goes to stderr so stdout stays clean for output.
|
|
5
|
+
const rl = createInterface({ input: io.input, output: io.output });
|
|
6
|
+
return new Promise((resolve) => {
|
|
7
|
+
let answered = false;
|
|
8
|
+
rl.on("close", () => {
|
|
9
|
+
if (!answered)
|
|
10
|
+
resolve(false);
|
|
11
|
+
});
|
|
12
|
+
rl.question(question, (answer) => {
|
|
13
|
+
answered = true;
|
|
14
|
+
rl.close();
|
|
15
|
+
const a = answer.trim().toLowerCase();
|
|
16
|
+
resolve(a === "y" || a === "yes");
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** What to do when a write may or may not have been applied: check before retrying. */
|
|
2
|
+
export declare const mayHaveApplied: (check: string) => string;
|
|
3
|
+
export declare function annotateMonitorError(err: unknown, write: boolean, advice?: string): unknown;
|
|
4
|
+
/** A write answered "success" without the field it must return: it may or may not have been applied. */
|
|
5
|
+
export declare function incompleteReply(field: string, advice?: string): Error;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { OctenAPIError as CliAPIError } from "../../api/errors.js";
|
|
2
|
+
import { OctenAPIError, OctenConnectionError, OctenError, OctenServerError, OctenTimeoutError, } from "@octen.ai/sdk";
|
|
3
|
+
const HINTS = {
|
|
4
|
+
409103: "The monitor is paused; resume it first with `octen monitor resume <id>`.",
|
|
5
|
+
409101: "A run is still in progress; wait for it to finish before triggering again.",
|
|
6
|
+
429101: "Less than 3 seconds since the last manual trigger; wait a few seconds.",
|
|
7
|
+
404101: "The monitor does not exist; check the id with `octen monitor list`.",
|
|
8
|
+
409102: "A concurrent update conflicted; get the monitor again and redo your change on its current settings before retrying (--email and --metadata replace whole values).",
|
|
9
|
+
400101: "The account already has 30 monitors (deleted ones don't count); delete the ones you no longer need.",
|
|
10
|
+
};
|
|
11
|
+
/** What to do when a write may or may not have been applied: check before retrying. */
|
|
12
|
+
export const mayHaveApplied = (check) => `The request may already have taken effect; check with ${check} before retrying.`;
|
|
13
|
+
const DEFAULT_ADVICE = mayHaveApplied("`octen monitor list` or `octen monitor get`");
|
|
14
|
+
// Adds the server code and a hint to an SDK error in place, so its class (and exit code) is kept.
|
|
15
|
+
// `write` marks calls the SDK does not retry once sent (create, update, pause, resume, delete, trigger).
|
|
16
|
+
export function annotateMonitorError(err, write, advice = DEFAULT_ADVICE) {
|
|
17
|
+
if (!(err instanceof OctenError))
|
|
18
|
+
return err;
|
|
19
|
+
const lines = [err.message];
|
|
20
|
+
if (err instanceof OctenAPIError && err.code !== null) {
|
|
21
|
+
lines[0] = `${err.message} (code ${err.code})`;
|
|
22
|
+
if (HINTS[err.code])
|
|
23
|
+
lines.push(HINTS[err.code]);
|
|
24
|
+
}
|
|
25
|
+
// A connection error does not say whether the request was sent, and an unreadable 2xx means it was applied.
|
|
26
|
+
const unreadableSuccess = err instanceof OctenAPIError && err.status >= 200 && err.status < 300 && err.code === null;
|
|
27
|
+
// The SDK reports a 408 as a plain API error, but the request may have been applied.
|
|
28
|
+
const timedOut = err instanceof OctenAPIError && err.status === 408;
|
|
29
|
+
if (write && (err instanceof OctenTimeoutError || err instanceof OctenConnectionError || err instanceof OctenServerError || unreadableSuccess || timedOut)) {
|
|
30
|
+
lines.push(advice);
|
|
31
|
+
}
|
|
32
|
+
err.message = lines.join("\n");
|
|
33
|
+
return err;
|
|
34
|
+
}
|
|
35
|
+
/** A write answered "success" without the field it must return: it may or may not have been applied. */
|
|
36
|
+
export function incompleteReply(field, advice = DEFAULT_ADVICE) {
|
|
37
|
+
return new CliAPIError(`The API reported success but returned no ${field}.\n${advice}`, 200);
|
|
38
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Command } from "commander";
|
|
2
|
+
type Globals = {
|
|
3
|
+
apiKey?: string;
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
json?: boolean;
|
|
6
|
+
pretty?: boolean;
|
|
7
|
+
};
|
|
8
|
+
export declare function globalsOf(command: Command): Globals;
|
|
9
|
+
export declare function output(g: Globals, res: unknown, render: (d: any) => string): void;
|
|
10
|
+
/** Run one SDK call; `write` marks calls the SDK does not retry once sent. */
|
|
11
|
+
export declare function call<T>(write: boolean, fn: () => Promise<T>, advice?: string): Promise<T>;
|
|
12
|
+
export declare function registerMonitor(program: Command): void;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { chooseMode, emit } from "../../output/render.js";
|
|
2
|
+
import { renderDeleted, renderEvents, renderMonitor, renderMonitorList, renderRun, renderRuns, renderTriggered, } from "../../output/pretty/monitor.js";
|
|
3
|
+
import { OctenCancelledError, OctenValidationError } from "../../api/errors.js";
|
|
4
|
+
import { confirm } from "./confirm.js";
|
|
5
|
+
import { printableLine } from "../../util/terminalText.js";
|
|
6
|
+
import { parseCsvOpt, parseIntOpt } from "../utils.js";
|
|
7
|
+
import { makeMonitorClient } from "./client.js";
|
|
8
|
+
import { annotateMonitorError, incompleteReply, mayHaveApplied } from "./errors.js";
|
|
9
|
+
import { OctenAPIError as CliAPIError } from "../../api/errors.js";
|
|
10
|
+
import { buildCreateParams, buildEventsParams, buildListParams, buildRunsParams, buildUpdateParams, needsTypeLookup, parseChoiceOpt, parseField, parseMetadata, readParams, } from "./options.js";
|
|
11
|
+
const collect = (v, prev = []) => [...prev, v];
|
|
12
|
+
export function globalsOf(command) {
|
|
13
|
+
return command.optsWithGlobals();
|
|
14
|
+
}
|
|
15
|
+
export function output(g, res, render) {
|
|
16
|
+
emit(res, chooseMode(g, process.stdout.isTTY ?? false), render);
|
|
17
|
+
}
|
|
18
|
+
/** Run one SDK call; `write` marks calls the SDK does not retry once sent. */
|
|
19
|
+
export async function call(write, fn, advice) {
|
|
20
|
+
try {
|
|
21
|
+
return await fn();
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
throw annotateMonitorError(e, write, advice);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Require the field a write must return (and, for an existing monitor, its own id) before reporting success. */
|
|
28
|
+
function written(res, field, advice, expectedId) {
|
|
29
|
+
const value = res?.data?.[field];
|
|
30
|
+
if (!value || (expectedId !== undefined && value !== expectedId))
|
|
31
|
+
throw incompleteReply(`${field}${expectedId ? ` ${expectedId}` : ""}`, advice);
|
|
32
|
+
return res;
|
|
33
|
+
}
|
|
34
|
+
// Single-quoted for POSIX shells, so a copied hint keeps characters such as & and ? intact.
|
|
35
|
+
function shellQuote(v) {
|
|
36
|
+
return `'${v.replace(/'/g, "'\\''")}'`;
|
|
37
|
+
}
|
|
38
|
+
// An empty page is a list; a reply without the list is not, and must not print "No monitors".
|
|
39
|
+
function listed(res, field) {
|
|
40
|
+
if (!Array.isArray(res?.data?.[field])) {
|
|
41
|
+
throw incompleteReply(`data.${field}`, "This was a read, so running the command again is safe.");
|
|
42
|
+
}
|
|
43
|
+
return res;
|
|
44
|
+
}
|
|
45
|
+
function addSettingOptions(cmd, update) {
|
|
46
|
+
return cmd
|
|
47
|
+
.option("--topic <query>", update ? "new search query (topic monitors)" : "watch new results for this search query")
|
|
48
|
+
.option("--page <url>", update ? "replace the watched URLs (page monitors), repeatable" : "watch this page for changes, repeatable (up to 10)", collect)
|
|
49
|
+
.option("--field <name:type[:description]>", "field to extract, type string|number|boolean, repeatable", (v, p) => parseField(v, p))
|
|
50
|
+
.option("--include-domains <list>", "topic monitors: comma list of domains to search", parseCsvOpt("--include-domains"))
|
|
51
|
+
.option("--exclude-domains <list>", "topic monitors: comma list of domains to leave out", parseCsvOpt("--exclude-domains"))
|
|
52
|
+
.option("--name <name>", "monitor name")
|
|
53
|
+
.option("--condition <text>", "when to notify, in plain language")
|
|
54
|
+
.option("--interval <every>", "5m-59m, 1h-100h or 1d-30d" + (update ? "" : " (default 1h)"))
|
|
55
|
+
.option("--cron <expr>", "cron schedule instead of --interval, runs at least 5 minutes apart")
|
|
56
|
+
.option("--timezone <tz>", "IANA time zone for --cron (default UTC)")
|
|
57
|
+
.option("--webhook <url>", "https URL to push events to")
|
|
58
|
+
.option("--email <address>", update ? "email address, repeatable; replaces all existing recipients" : "email address for notifications, repeatable", collect)
|
|
59
|
+
.option("--metadata <key=value>", update ? "key=value pair, repeatable; replaces all existing metadata" : "key=value pair, repeatable", (v, p) => parseMetadata(v, p))
|
|
60
|
+
.option("--params <json|@file>", "more request fields as JSON, merged with the options above", readParams);
|
|
61
|
+
}
|
|
62
|
+
export function registerMonitor(program) {
|
|
63
|
+
const monitor = program
|
|
64
|
+
.command("monitor")
|
|
65
|
+
.description("Watch a topic or pages on a schedule and get notified when something changes");
|
|
66
|
+
addSettingOptions(monitor.command("create").description("Create a monitor; its first run starts right away"), false)
|
|
67
|
+
.action(async (opts, command) => {
|
|
68
|
+
const g = globalsOf(command);
|
|
69
|
+
const params = buildCreateParams(opts);
|
|
70
|
+
const client = makeMonitorClient(g);
|
|
71
|
+
const createCheck = params.webhook?.url
|
|
72
|
+
? "The monitor may already exist: check with `octen monitor list` and do not create it again. Its one-time webhook " +
|
|
73
|
+
"secret cannot be read back, so once you find it, run `octen monitor update <id> --rotate-secret` and set the new secret on your receiver."
|
|
74
|
+
: undefined;
|
|
75
|
+
const created = written(await call(true, () => client.monitors.create(params), createCheck), "monitor_id", createCheck);
|
|
76
|
+
// The secret is returned only once; without it the new monitor's webhook cannot be verified.
|
|
77
|
+
const createdId = created.data.monitor_id;
|
|
78
|
+
if (params.webhook?.url && !created.data.webhook?.secret) {
|
|
79
|
+
throw new CliAPIError(`Monitor ${createdId} was created, but the reply has no webhook secret. Do not create it again; ` +
|
|
80
|
+
`rotate the secret with \`octen monitor update ${createdId} --rotate-secret\` and set it on your receiver.`, 200);
|
|
81
|
+
}
|
|
82
|
+
output(g, created, renderMonitor);
|
|
83
|
+
});
|
|
84
|
+
monitor
|
|
85
|
+
.command("list")
|
|
86
|
+
.description("List monitors")
|
|
87
|
+
.option("--status <status>", "active|paused", parseChoiceOpt("--status", ["active", "paused"]))
|
|
88
|
+
.option("--name <text>", "filter by name")
|
|
89
|
+
.option("--limit <n>", "1-100", parseIntOpt("--limit"))
|
|
90
|
+
.option("--cursor <cursor>", "next_cursor from the previous page")
|
|
91
|
+
.option("--page-no <n>", "page number, instead of --cursor", parseIntOpt("--page-no"))
|
|
92
|
+
.action(async (opts, command) => {
|
|
93
|
+
const g = globalsOf(command);
|
|
94
|
+
const client = makeMonitorClient(g);
|
|
95
|
+
output(g, listed(await call(false, () => client.monitors.list(buildListParams(opts))), "monitors"), renderMonitorList);
|
|
96
|
+
});
|
|
97
|
+
monitor
|
|
98
|
+
.command("get")
|
|
99
|
+
.argument("<id>", "monitor id")
|
|
100
|
+
.description("Show a monitor")
|
|
101
|
+
.action(async (id, _opts, command) => {
|
|
102
|
+
const g = globalsOf(command);
|
|
103
|
+
const client = makeMonitorClient(g);
|
|
104
|
+
output(g, await call(false, () => client.monitors.get(id)), renderMonitor);
|
|
105
|
+
});
|
|
106
|
+
addSettingOptions(monitor.command("update").argument("<id>", "monitor id").description("Change a monitor; sends only the options given"), true)
|
|
107
|
+
.option("--status <status>", "active|paused", parseChoiceOpt("--status", ["active", "paused"]))
|
|
108
|
+
.option("--clear <fields>", "remove fields: comma list of condition, webhook, email, metadata", parseCsvOpt("--clear"))
|
|
109
|
+
.option("--rotate-secret", "issue a new webhook signing secret")
|
|
110
|
+
.action(async (id, opts, command) => {
|
|
111
|
+
const g = globalsOf(command);
|
|
112
|
+
const client = makeMonitorClient(g);
|
|
113
|
+
let type;
|
|
114
|
+
let current;
|
|
115
|
+
// Only a newly added webhook returns its secret, so a URL update needs to know whether one exists.
|
|
116
|
+
if (needsTypeLookup(opts) || opts.webhook !== undefined || opts.params?.webhook !== undefined) {
|
|
117
|
+
current = await call(false, () => client.monitors.get(id));
|
|
118
|
+
type = current?.data?.type;
|
|
119
|
+
}
|
|
120
|
+
const params = buildUpdateParams(opts, type);
|
|
121
|
+
const rotating = Boolean(params.webhook?.rotate_secret);
|
|
122
|
+
const adding = Boolean(params.webhook?.url) && current !== undefined && !current?.data?.webhook?.url;
|
|
123
|
+
// A rotation cannot be read back (no endpoint returns the secret), so an unknown outcome needs its own advice.
|
|
124
|
+
const newUrl = params.webhook?.url;
|
|
125
|
+
if (newUrl !== undefined && newUrl !== null && typeof newUrl !== "string") {
|
|
126
|
+
throw new OctenValidationError("--params: webhook.url must be a string");
|
|
127
|
+
}
|
|
128
|
+
const rotationCheck = "The rotation may already have happened and the old secret may already be invalid; no endpoint returns the secret, " +
|
|
129
|
+
"so do not retry blindly: " +
|
|
130
|
+
(newUrl
|
|
131
|
+
? `check with \`octen monitor get ${id}\` whether webhook.url changed, then rotate once more on purpose ` +
|
|
132
|
+
`(add --webhook ${shellQuote(newUrl)} if it did not) and update your receiver with the new secret.`
|
|
133
|
+
: "rotate once more on purpose and update your receiver with the new secret.");
|
|
134
|
+
const urlCheck = `Check with \`octen monitor get ${id}\` whether webhook.url changed. If the webhook was newly added, its one-time secret ` +
|
|
135
|
+
"was lost with the reply and cannot be read back: rotate it on purpose with --rotate-secret and update your receiver.";
|
|
136
|
+
const advice = rotating ? rotationCheck : params.webhook?.url ? urlCheck : undefined;
|
|
137
|
+
const updated = written(await call(true, () => client.monitors.update(id, params), advice), "monitor_id", advice, id);
|
|
138
|
+
if (rotating && !updated?.data?.webhook?.secret)
|
|
139
|
+
throw incompleteReply("new webhook secret", rotationCheck);
|
|
140
|
+
if (adding && !updated?.data?.webhook?.secret) {
|
|
141
|
+
throw incompleteReply("new webhook secret", "The monitor had no webhook just before this update, so the webhook was probably added and its one-time secret is lost " +
|
|
142
|
+
`(unless another client added a webhook meanwhile). Check with \`octen monitor get ${id}\`; if your receiver has no ` +
|
|
143
|
+
"working secret, rotate it on purpose with --rotate-secret and update your receiver.");
|
|
144
|
+
}
|
|
145
|
+
output(g, updated, renderMonitor);
|
|
146
|
+
});
|
|
147
|
+
for (const [name, status] of [["pause", "paused"], ["resume", "active"]]) {
|
|
148
|
+
monitor
|
|
149
|
+
.command(name)
|
|
150
|
+
.argument("<id>", "monitor id")
|
|
151
|
+
.description(name === "pause" ? "Stop scheduled runs" : "Start scheduled runs again")
|
|
152
|
+
.action(async (id, _opts, command) => {
|
|
153
|
+
const g = globalsOf(command);
|
|
154
|
+
const client = makeMonitorClient(g);
|
|
155
|
+
const updated = written(await call(true, () => client.monitors.update(id, { status })), "monitor_id", undefined, id);
|
|
156
|
+
if (updated?.data?.status !== status)
|
|
157
|
+
throw incompleteReply(`status "${status}"`);
|
|
158
|
+
output(g, updated, renderMonitor);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
monitor
|
|
162
|
+
.command("delete")
|
|
163
|
+
.argument("<id>", "monitor id")
|
|
164
|
+
.description("Delete a monitor (cannot be undone); asks first unless --yes")
|
|
165
|
+
.option("--yes", "delete without asking (required when not run in a terminal)")
|
|
166
|
+
.action(async (id, opts, command) => {
|
|
167
|
+
const g = globalsOf(command);
|
|
168
|
+
if (!opts.yes && !(process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY)) {
|
|
169
|
+
throw new OctenValidationError("not deleting: not running in a terminal, so pass --yes to confirm");
|
|
170
|
+
}
|
|
171
|
+
const client = makeMonitorClient(g);
|
|
172
|
+
if (!opts.yes) {
|
|
173
|
+
const describe = async () => {
|
|
174
|
+
const m = (await call(false, () => client.monitors.get(id)))?.data;
|
|
175
|
+
// The prompt must describe the monitor that will be deleted.
|
|
176
|
+
if (!m || m.monitor_id !== id) {
|
|
177
|
+
throw new OctenValidationError(`not deleting: the lookup did not return monitor ${id}`);
|
|
178
|
+
}
|
|
179
|
+
const inc = m.topic?.include_domains ?? [];
|
|
180
|
+
const exc = m.topic?.exclude_domains ?? [];
|
|
181
|
+
const what = m.topic?.query
|
|
182
|
+
? `topic "${m.topic.query}"${inc.length ? `, only ${inc.join(", ")}` : ""}${exc.length ? `, not ${exc.join(", ")}` : ""}`
|
|
183
|
+
: (m.page?.urls ?? []).join(", ");
|
|
184
|
+
const raw = JSON.stringify([m.name, m.type, m.topic?.query ?? null, inc, exc, m.page?.urls ?? null]);
|
|
185
|
+
return { shown: printableLine(`"${m.name}" (${m.monitor_id}, ${m.type}: ${what})`), raw };
|
|
186
|
+
};
|
|
187
|
+
const first = await describe();
|
|
188
|
+
if (!(await confirm(`Delete monitor ${first.shown}? This cannot be undone. [y/N] `)))
|
|
189
|
+
throw new OctenCancelledError();
|
|
190
|
+
// Someone may have changed it while the prompt was open; compare the raw values, not the display text.
|
|
191
|
+
if ((await describe()).raw !== first.raw) {
|
|
192
|
+
throw new OctenValidationError(`not deleting: monitor ${id} changed while you were confirming; run delete again`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const gone = mayHaveApplied(`\`octen monitor get ${id}\` (404101 means it is deleted)`);
|
|
196
|
+
const deleted = written(await call(true, () => client.monitors.delete(id), gone), "monitor_id", gone, id);
|
|
197
|
+
if (deleted?.data?.status !== "deleted")
|
|
198
|
+
throw incompleteReply('status "deleted"', gone);
|
|
199
|
+
output(g, deleted, renderDeleted);
|
|
200
|
+
});
|
|
201
|
+
monitor
|
|
202
|
+
.command("trigger")
|
|
203
|
+
.argument("<id>", "monitor id")
|
|
204
|
+
.description("Run a monitor now, outside its schedule")
|
|
205
|
+
.action(async (id, _opts, command) => {
|
|
206
|
+
const g = globalsOf(command);
|
|
207
|
+
const client = makeMonitorClient(g);
|
|
208
|
+
// A queued manual run shows in the run list before the monitor's last_run changes.
|
|
209
|
+
const runs = mayHaveApplied(`\`octen monitor runs ${id}\` (look for a new manual run)`);
|
|
210
|
+
output(g, written(await call(true, () => client.monitors.trigger(id), runs), "run_id", runs), renderTriggered);
|
|
211
|
+
});
|
|
212
|
+
monitor
|
|
213
|
+
.command("runs")
|
|
214
|
+
.argument("<id>", "monitor id")
|
|
215
|
+
.description("List a monitor's runs")
|
|
216
|
+
.option("--status <status>", "queued|processing|completed|skipped|failed", parseChoiceOpt("--status", ["queued", "processing", "completed", "skipped", "failed"]))
|
|
217
|
+
.option("--only-changes", "only runs that found changes")
|
|
218
|
+
.option("--order-by <order>", "time_desc|time_asc", parseChoiceOpt("--order-by", ["time_desc", "time_asc"]))
|
|
219
|
+
.option("--limit <n>", "1-100", parseIntOpt("--limit"))
|
|
220
|
+
.option("--cursor <cursor>", "next_cursor from the previous page")
|
|
221
|
+
.action(async (id, opts, command) => {
|
|
222
|
+
const g = globalsOf(command);
|
|
223
|
+
const client = makeMonitorClient(g);
|
|
224
|
+
output(g, listed(await call(false, () => client.monitors.listRuns(id, buildRunsParams(opts))), "runs"), renderRuns);
|
|
225
|
+
});
|
|
226
|
+
monitor
|
|
227
|
+
.command("run")
|
|
228
|
+
.argument("<id>", "monitor id")
|
|
229
|
+
.argument("<run_id>", "run id")
|
|
230
|
+
.description("Show one run and its items")
|
|
231
|
+
.action(async (id, runId, _opts, command) => {
|
|
232
|
+
const g = globalsOf(command);
|
|
233
|
+
const client = makeMonitorClient(g);
|
|
234
|
+
output(g, await call(false, () => client.monitors.getRun(id, runId)), renderRun);
|
|
235
|
+
});
|
|
236
|
+
monitor
|
|
237
|
+
.command("events")
|
|
238
|
+
.argument("<id>", "monitor id")
|
|
239
|
+
.description("List a monitor's events: what it found")
|
|
240
|
+
.option("--run <run_id>", "only events from this run")
|
|
241
|
+
.option("--order-by <order>", "time_desc|time_asc", parseChoiceOpt("--order-by", ["time_desc", "time_asc"]))
|
|
242
|
+
.option("--limit <n>", "1-20", parseIntOpt("--limit"))
|
|
243
|
+
.option("--cursor <cursor>", "next_cursor from the previous page")
|
|
244
|
+
.action(async (id, opts, command) => {
|
|
245
|
+
const g = globalsOf(command);
|
|
246
|
+
const client = makeMonitorClient(g);
|
|
247
|
+
output(g, listed(await call(false, () => client.monitors.listEvents(id, buildEventsParams(opts))), "events"), renderEvents);
|
|
248
|
+
});
|
|
249
|
+
// A stray extra argument (e.g. a second id) must fail rather than be ignored.
|
|
250
|
+
for (const sub of monitor.commands)
|
|
251
|
+
sub.allowExcessArguments(false);
|
|
252
|
+
}
|