wake-agents 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -2
- package/bin/wake.mjs +10 -0
- package/lib/cli.mjs +524 -0
- package/lib/client.mjs +83 -0
- package/lib/config.mjs +51 -0
- package/lib/format.mjs +79 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,117 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wake-agents
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Command line for [Wake](https://agent-observatory-desk-production.up.railway.app/wake/): see which AI agents (Claude, ChatGPT, Perplexity, curl/python bots…) reach your site, what they tried, where they got stuck, the ranked fixes, your readiness score, and the AEO listing plan. It is also a stdio MCP bridge so any MCP client can ask Wake directly.
|
|
4
|
+
|
|
5
|
+
Zero dependencies. Node 18+.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm i -g wake-agents # then: wake …
|
|
11
|
+
npx wake-agents status # or one-off
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Login
|
|
15
|
+
|
|
16
|
+
Mint a key on the desk's **Connect your AI** screen (format `wk_live_` + 40 hex chars), then:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
wake login # prompts for the key
|
|
20
|
+
wake login --key wk_live_… # or pass it
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The key is saved to `~/.config/wake/config.json` (mode 0600; honours `XDG_CONFIG_HOME`). Precedence everywhere: `--key` / `--url` flags, then `WAKE_API_KEY` / `WAKE_API_URL`, then the config file. The CLI never prints a key in full (`wk_live_ab12…`) unless you ask with `--show-key`.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
wake logout # delete the config file
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Commands
|
|
30
|
+
|
|
31
|
+
Every report takes `--window 24h|7d|30d` (default `7d`) and `--json` (raw API response on stdout, ideal for piping into `jq`).
|
|
32
|
+
|
|
33
|
+
| Command | What you get | Example |
|
|
34
|
+
| --- | --- | --- |
|
|
35
|
+
| `wake status` | host, verified / provisioned, last event, this window's headline | `wake status` |
|
|
36
|
+
| `wake overview` | events, sessions, agents, conversion, providers, funnel, top friction | `wake overview --window 24h` |
|
|
37
|
+
| `wake agents` | every agent nickname seen, with stage, conversion and friction | `wake agents --json \| jq '.agents[0]'` |
|
|
38
|
+
| `wake sessions` | recent sessions | `wake sessions --limit 20 --nickname quiet-otter` |
|
|
39
|
+
| `wake funnel` | discovered → read_docs → authenticated → attempted_action → converted, with the biggest drop | `wake funnel --window 30d` |
|
|
40
|
+
| `wake friction` | where agents get stuck (auth_wall, action_unauthorized, repeated_error, docs_dead_end…) and the fixes | `wake friction` |
|
|
41
|
+
| `wake fixes` | ranked fixes plus the readiness score and recommendations | `wake fixes` |
|
|
42
|
+
| `wake pages` | page classes and the most common paths through the site | `wake pages` |
|
|
43
|
+
| `wake alerts` | things worth a look right now | `wake alerts` |
|
|
44
|
+
| `wake series` | per-hour (24h) or per-day buckets | `wake series --json` |
|
|
45
|
+
| `wake readiness` | live readiness probe: access / information / measurement scores, `llms.txt` and robots suggestions | `wake readiness --json \| jq -r '.files["llms.txt"]'` |
|
|
46
|
+
| `wake listing` | AEO listing plan, arrivals verdict, discovery files | `wake listing` |
|
|
47
|
+
| `wake listing plan` | ask the desk to (re)plan the listing steps | `wake listing plan` |
|
|
48
|
+
| `wake benchmarks` | your numbers against the cohort medians (withheld while the cohort is small) | `wake benchmarks` |
|
|
49
|
+
| `wake install` | collector status; `--kit --out <dir>` writes `cloudflare-worker.js`, `express.js`, `nextjs-middleware.js`, `README.md` | `wake install --kit --out ./wake-kit` |
|
|
50
|
+
| `wake export sessions.csv` | sessions as CSV (stdout, or `--out file`) | `wake export sessions --out sessions.csv` |
|
|
51
|
+
|
|
52
|
+
Exit code is `1` on any API error, with a one-line message on stderr (`Not signed in. Run: wake login`, `Site not verified yet…`, `Rate limited…`).
|
|
53
|
+
|
|
54
|
+
## Use Wake from your AI tools (MCP)
|
|
55
|
+
|
|
56
|
+
Wake exposes an MCP server at `<desk>/api/wake/v1/mcp` (streamable HTTP, bearer auth). `wake connect <client>` prints the exact snippet with your URL and key filled in; `--write` writes the file where the client supports it.
|
|
57
|
+
|
|
58
|
+
**Claude Code**
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
wake connect claude-code
|
|
62
|
+
# → claude mcp add --transport http wake https://…/api/wake/v1/mcp --header "Authorization: Bearer wk_live_…"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Cursor** — writes/merges `./.cursor/mcp.json`:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
wake connect cursor --write
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Codex** — add to `~/.codex/config.toml` and export the key:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
wake connect codex
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```toml
|
|
78
|
+
[mcp_servers.wake]
|
|
79
|
+
url = "https://…/api/wake/v1/mcp"
|
|
80
|
+
bearer_token_env_var = "WAKE_API_KEY"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**Claude Desktop** — stdio only, so it runs the bridge below via `npx`:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
wake connect claude-desktop --write # merges into claude_desktop_config.json, then restart Claude Desktop
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```json
|
|
90
|
+
{ "mcpServers": { "wake": { "command": "npx", "args": ["-y", "wake-agents", "mcp"],
|
|
91
|
+
"env": { "WAKE_API_KEY": "wk_live_…", "WAKE_API_URL": "https://agent-observatory-desk-production.up.railway.app" } } } }
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
**ChatGPT** — ChatGPT connectors need a hosted MCP server with OAuth, which Wake does not offer yet. Use the bridge or the REST API in the meantime (`wake connect chatgpt` prints the details).
|
|
95
|
+
|
|
96
|
+
**curl / anything else**
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
wake connect curl
|
|
100
|
+
# → curl -H "Authorization: Bearer wk_live_…" "https://…/api/wake/v1/overview?window=7d"
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### `wake mcp` — the stdio bridge
|
|
104
|
+
|
|
105
|
+
Reads newline-delimited JSON-RPC 2.0 messages on stdin, POSTs each one unchanged to `<url>/api/wake/v1/mcp` with your bearer key, and writes each response as one line on stdout. Notifications (no `id`) produce no output; batches are forwarded as-is. Errors go to stderr only, so the stdout stream stays clean for the client.
|
|
106
|
+
|
|
107
|
+
## Privacy
|
|
108
|
+
|
|
109
|
+
The API (and therefore this CLI) only ever exposes coarse data: daily HMAC nicknames for agents, page classes rather than URLs, HTTP status codes, operator families (Anthropic, OpenAI, …), and country codes. Raw IP addresses, user-agent strings, query strings and request bodies never leave the collector and are never available through any endpoint.
|
|
110
|
+
|
|
111
|
+
## Development
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
node --test test/wake-cli.test.mjs # from the repo root; spins up a fake API, no network
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
MIT.
|
package/bin/wake.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from "../lib/cli.mjs";
|
|
3
|
+
|
|
4
|
+
main(process.argv.slice(2)).then(
|
|
5
|
+
(code) => process.exit(typeof code === "number" ? code : 0),
|
|
6
|
+
(err) => {
|
|
7
|
+
process.stderr.write(`wake: ${err?.message || err}\n`);
|
|
8
|
+
process.exit(1);
|
|
9
|
+
}
|
|
10
|
+
);
|
package/lib/cli.mjs
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import readline from "node:readline";
|
|
5
|
+
import { createClient, WakeError, apiBase } from "./client.mjs";
|
|
6
|
+
import { resolveConfig, writeConfig, deleteConfig, configPath, maskKey, KEY_PATTERN, DEFAULT_URL } from "./config.mjs";
|
|
7
|
+
import * as f from "./format.mjs";
|
|
8
|
+
|
|
9
|
+
export const VERSION = "0.1.0";
|
|
10
|
+
const WINDOWS = new Set(["24h", "7d", "30d"]);
|
|
11
|
+
const BOOL_FLAGS = new Set(["json", "kit", "write", "show-key", "help", "version", "plan"]);
|
|
12
|
+
|
|
13
|
+
const out = (s = "") => process.stdout.write(s + "\n");
|
|
14
|
+
const err = (s = "") => process.stderr.write(s + "\n");
|
|
15
|
+
|
|
16
|
+
export function parseArgs(argv) {
|
|
17
|
+
const flags = {};
|
|
18
|
+
const positional = [];
|
|
19
|
+
for (let i = 0; i < argv.length; i++) {
|
|
20
|
+
const a = argv[i];
|
|
21
|
+
if (a === "--") { positional.push(...argv.slice(i + 1)); break; }
|
|
22
|
+
if (!a.startsWith("--")) { positional.push(a); continue; }
|
|
23
|
+
const eq = a.indexOf("=");
|
|
24
|
+
const name = eq > -1 ? a.slice(2, eq) : a.slice(2);
|
|
25
|
+
if (eq > -1) { flags[name] = a.slice(eq + 1); continue; }
|
|
26
|
+
if (BOOL_FLAGS.has(name) || argv[i + 1] === undefined || argv[i + 1].startsWith("--")) { flags[name] = true; continue; }
|
|
27
|
+
flags[name] = argv[++i];
|
|
28
|
+
}
|
|
29
|
+
return { flags, positional };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const HELP = `wake ${VERSION} — see which AI agents reach your site, and what to fix
|
|
33
|
+
|
|
34
|
+
Usage: wake <command> [options]
|
|
35
|
+
|
|
36
|
+
Account
|
|
37
|
+
login [--key wk_live_…] [--url https://…] Save an API key (minted on the desk's "Connect your AI" screen)
|
|
38
|
+
logout Forget the saved key
|
|
39
|
+
status Site, verification, last event and this window's headline
|
|
40
|
+
|
|
41
|
+
Reports (all accept --window 24h|7d|30d and --json)
|
|
42
|
+
overview Events, sessions, agents, conversion, funnel, top friction
|
|
43
|
+
agents Every agent nickname seen, with stage and friction
|
|
44
|
+
sessions Recent sessions [--limit N] [--nickname X]
|
|
45
|
+
funnel discovered → read_docs → authenticated → attempted_action → converted
|
|
46
|
+
friction Where agents get stuck, with fixes
|
|
47
|
+
fixes Ranked fixes plus the readiness score
|
|
48
|
+
pages Page classes and common paths
|
|
49
|
+
alerts Things worth a look right now
|
|
50
|
+
series Per-hour / per-day buckets
|
|
51
|
+
readiness Readiness probe of the live site (needs a verified site)
|
|
52
|
+
listing AEO listing plan; "wake listing plan" asks the desk to plan it
|
|
53
|
+
benchmarks How your numbers compare to the cohort
|
|
54
|
+
install Collector status; --kit --out <dir> writes the install kit
|
|
55
|
+
export sessions.csv [--out file] Download sessions as CSV
|
|
56
|
+
|
|
57
|
+
Agents / MCP
|
|
58
|
+
mcp stdio ⇄ HTTP MCP bridge (for Claude Desktop and other stdio-only clients)
|
|
59
|
+
connect <client> Print the config for claude-code | cursor | codex | claude-desktop | chatgpt | curl
|
|
60
|
+
[--write] writes the file for cursor / claude-desktop; [--show-key] prints the key unmasked
|
|
61
|
+
|
|
62
|
+
Options
|
|
63
|
+
--key, --url Override the saved key / desk URL (also WAKE_API_KEY, WAKE_API_URL)
|
|
64
|
+
--json Raw JSON to stdout
|
|
65
|
+
--version, --help`;
|
|
66
|
+
|
|
67
|
+
export async function main(argv) {
|
|
68
|
+
const { flags, positional } = parseArgs(argv);
|
|
69
|
+
const [cmd, ...rest] = positional;
|
|
70
|
+
|
|
71
|
+
if (flags.version || cmd === "--version" || cmd === "version") { out(VERSION); return 0; }
|
|
72
|
+
if (!cmd || cmd === "help" || flags.help) { out(HELP); return cmd || flags.help ? 0 : 1; }
|
|
73
|
+
|
|
74
|
+
const handler = COMMANDS[cmd];
|
|
75
|
+
if (!handler) { err(`Unknown command: ${cmd}\n`); out(HELP); return 1; }
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
return (await handler({ flags, args: rest })) ?? 0;
|
|
79
|
+
} catch (e) {
|
|
80
|
+
if (e instanceof WakeError) { err(humanError(e, flags)); return 1; }
|
|
81
|
+
throw e;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function humanError(e, flags) {
|
|
86
|
+
const { url } = resolveConfig(flags);
|
|
87
|
+
if (e.status === 401 || e.code === "unauthorized") return "Not signed in. Run: wake login";
|
|
88
|
+
if (e.code === "unverified") return `Site not verified yet. Finish verification on the desk: ${url}/wake/`;
|
|
89
|
+
if (e.code === "not_provisioned") return `Collector not provisioned yet. Finish setup on the desk: ${url}/wake/`;
|
|
90
|
+
if (e.status === 429 || e.code === "rate_limited") return "Rate limited. Try again in a moment.";
|
|
91
|
+
return `${e.message}${e.code ? ` (${e.code})` : ""}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function windowOf(flags) {
|
|
95
|
+
const w = flags.window || "7d";
|
|
96
|
+
if (!WINDOWS.has(w)) throw new WakeError(`--window must be one of 24h, 7d, 30d (got ${w})`, { code: "bad_args" });
|
|
97
|
+
return w;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function clientFor(flags, { requireKey = true } = {}) {
|
|
101
|
+
const cfg = resolveConfig(flags);
|
|
102
|
+
if (requireKey && !cfg.key) throw new WakeError("Not signed in. Run: wake login", { status: 401, code: "unauthorized" });
|
|
103
|
+
return { cfg, api: createClient(cfg) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Fetches one endpoint and either dumps JSON or hands the body to a renderer.
|
|
107
|
+
function report(path, render, { windowed = true, params = () => ({}) } = {}) {
|
|
108
|
+
return async ({ flags, args }) => {
|
|
109
|
+
const { api } = clientFor(flags);
|
|
110
|
+
const p = { ...(windowed ? { window: windowOf(flags) } : {}), ...params(flags, args) };
|
|
111
|
+
const data = await api.get(path, p);
|
|
112
|
+
if (flags.json) { out(JSON.stringify(data, null, 2)); return 0; }
|
|
113
|
+
render(data, { flags, args });
|
|
114
|
+
return 0;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function prompt(question) {
|
|
119
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
120
|
+
try {
|
|
121
|
+
return await new Promise((resolve) => rl.question(question, resolve));
|
|
122
|
+
} finally {
|
|
123
|
+
rl.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---- commands -------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
async function login({ flags }) {
|
|
130
|
+
let key = flags.key || process.env.WAKE_API_KEY || "";
|
|
131
|
+
if (!key) key = (await prompt("Paste your Wake API key (wk_live_…): ")).trim();
|
|
132
|
+
if (!KEY_PATTERN.test(key)) throw new WakeError("That doesn't look like a Wake key (expected wk_live_ followed by 40 hex characters).", { code: "bad_key" });
|
|
133
|
+
const url = (flags.url || process.env.WAKE_API_URL || DEFAULT_URL).replace(/\/+$/, "");
|
|
134
|
+
const me = await createClient({ url, key }).get("/me");
|
|
135
|
+
const file = writeConfig({ url, key });
|
|
136
|
+
out(`Connected to ${f.bold(me.host || me.site || url)} ${f.dim(`(${maskKey(key)}${me.key?.label ? `, ${me.key.label}` : ""})`)}`);
|
|
137
|
+
if (me.verified === false) out(f.yellow(`Site not verified yet — finish verification at ${url}/wake/`));
|
|
138
|
+
out(f.dim(`Saved to ${file}`));
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function logout() {
|
|
143
|
+
out(deleteConfig() ? `Signed out. Removed ${configPath()}` : "Nothing to remove.");
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function status({ flags }) {
|
|
148
|
+
const { api, cfg } = clientFor(flags);
|
|
149
|
+
const window = windowOf(flags);
|
|
150
|
+
const me = await api.get("/me");
|
|
151
|
+
let ov = null;
|
|
152
|
+
try { ov = await api.get("/overview", { window }); } catch (e) { if (!(e instanceof WakeError) || !["unverified", "not_provisioned"].includes(e.code)) throw e; }
|
|
153
|
+
if (flags.json) { out(JSON.stringify({ me, overview: ov }, null, 2)); return 0; }
|
|
154
|
+
out(f.heading(me.host || me.site || "Wake"));
|
|
155
|
+
out(f.kv([
|
|
156
|
+
["desk", cfg.url],
|
|
157
|
+
["key", `${maskKey(cfg.key)}${me.key?.label ? ` (${me.key.label})` : ""}`],
|
|
158
|
+
["verified", yn(me.verified)],
|
|
159
|
+
["provisioned", yn(me.provisioned)],
|
|
160
|
+
["last event", me.last_event_at ? `${f.ago(me.last_event_at)} ${f.dim(me.last_event_at)}` : f.yellow("none yet")],
|
|
161
|
+
]));
|
|
162
|
+
if (ov) {
|
|
163
|
+
out(f.heading(`Last ${window}`));
|
|
164
|
+
out(f.kv([
|
|
165
|
+
["agents", f.num(ov.unique_agents)],
|
|
166
|
+
["sessions", f.num(ov.sessions)],
|
|
167
|
+
["events", f.num(ov.events)],
|
|
168
|
+
["converted", `${f.num(ov.converted)} ${f.dim(f.pct(ov.conversion_rate))}`],
|
|
169
|
+
["with friction", f.num(ov.sessions_with_friction)],
|
|
170
|
+
["providers", f.topCounts(ov.by_provider)],
|
|
171
|
+
]));
|
|
172
|
+
}
|
|
173
|
+
if (me.mcp?.url) out(f.dim(`\nMCP: ${me.mcp.url} (wake connect <client>)`));
|
|
174
|
+
return 0;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const overview = report("/overview", (d) => {
|
|
178
|
+
out(f.heading(`${d.host} — last ${d.window}`) + (d.source ? f.dim(` source: ${d.source}`) : ""));
|
|
179
|
+
out(f.kv([
|
|
180
|
+
["events", f.num(d.events)],
|
|
181
|
+
["sessions", f.num(d.sessions)],
|
|
182
|
+
["agents", f.num(d.unique_agents) + (d.inferred_agents ? f.dim(` (${f.num(d.inferred_agents)} inferred)`) : "")],
|
|
183
|
+
["converted", `${f.num(d.converted)} ${f.dim(f.pct(d.conversion_rate))}`],
|
|
184
|
+
["with friction", f.num(d.sessions_with_friction)],
|
|
185
|
+
["providers", f.topCounts(d.by_provider)],
|
|
186
|
+
["classes", f.topCounts(d.by_agent_class)],
|
|
187
|
+
["intents", f.topCounts(d.by_intent)],
|
|
188
|
+
["countries", f.topCounts(d.by_country)],
|
|
189
|
+
["last event", f.ago(d.last_event_at)],
|
|
190
|
+
]));
|
|
191
|
+
if (d.funnel) {
|
|
192
|
+
out(f.heading("Funnel"));
|
|
193
|
+
out(f.kv(Object.entries(d.funnel).map(([k, v]) => [k, f.num(v)])));
|
|
194
|
+
}
|
|
195
|
+
out(f.heading("Top friction"));
|
|
196
|
+
out(frictionTable(d.top_friction));
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
function frictionTable(rows) {
|
|
200
|
+
return f.table(rows || [], [
|
|
201
|
+
{ key: "type", label: "type" },
|
|
202
|
+
{ key: "path_class", label: "where" },
|
|
203
|
+
{ key: "status", label: "status" },
|
|
204
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
205
|
+
{ key: "detail", label: "detail", render: (v) => v || "" },
|
|
206
|
+
]);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const agents = report("/agents", (d) => {
|
|
210
|
+
out(f.heading(`${d.host} — agents, last ${d.window}`));
|
|
211
|
+
out(f.table(d.agents, [
|
|
212
|
+
{ key: "nickname", label: "agent" },
|
|
213
|
+
{ key: "provider", label: "provider" },
|
|
214
|
+
{ key: "agent_class", label: "class" },
|
|
215
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
216
|
+
{ key: "events", label: "events", align: "right", render: f.num },
|
|
217
|
+
{ key: "stage", label: "stage" },
|
|
218
|
+
{ key: "converted", label: "conv", render: (v) => (v ? f.green("yes") : "") },
|
|
219
|
+
{ key: "friction_types", label: "friction", render: (v) => (v || []).join(",") },
|
|
220
|
+
{ key: "last_seen", label: "last seen", render: f.ago },
|
|
221
|
+
]));
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
const sessions = report("/sessions", (d) => {
|
|
225
|
+
out(f.heading(`${d.host} — ${f.num(d.count)} sessions, last ${d.window}`));
|
|
226
|
+
out(f.table(d.sessions, [
|
|
227
|
+
{ key: "started_at", label: "started", render: f.ago },
|
|
228
|
+
{ key: "nickname", label: "agent" },
|
|
229
|
+
{ key: "provider", label: "provider" },
|
|
230
|
+
{ key: "duration_ms", label: "dur", align: "right", render: f.duration },
|
|
231
|
+
{ key: "event_count", label: "ev", align: "right", render: f.num },
|
|
232
|
+
{ key: "stage", label: "stage" },
|
|
233
|
+
{ key: "intent", label: "intent", render: (v) => v || "" },
|
|
234
|
+
{ key: "converted", label: "conv", render: (v) => (v ? f.green("yes") : "") },
|
|
235
|
+
{ key: "friction", label: "friction", render: (v) => (v || []).map((x) => x.type).join(",") },
|
|
236
|
+
{ key: "path_classes", label: "path", render: (v) => (v || []).join(" → ") },
|
|
237
|
+
]));
|
|
238
|
+
}, { params: (flags) => ({ limit: flags.limit, nickname: flags.nickname }) });
|
|
239
|
+
|
|
240
|
+
const funnel = report("/funnel", (d) => {
|
|
241
|
+
out(f.heading(`${d.host} — funnel, last ${d.window} (${f.num(d.sessions)} sessions)`));
|
|
242
|
+
out(f.table(d.stages, [
|
|
243
|
+
{ key: "label", label: "stage" },
|
|
244
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
245
|
+
{ key: "share", label: "share", align: "right", render: f.pct },
|
|
246
|
+
{ key: "drop_from_previous", label: "lost", align: "right", render: (v) => (v == null ? "" : f.num(v)) },
|
|
247
|
+
]));
|
|
248
|
+
if (d.biggest_drop) out(`\n ${f.yellow("Biggest drop:")} ${d.biggest_drop.prev} → ${d.biggest_drop.id} lost ${f.num(d.biggest_drop.lost)} sessions`);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
function fixesList(fixes) {
|
|
252
|
+
if (!fixes?.length) return f.dim(" (nothing to fix right now)");
|
|
253
|
+
return fixes.map((x, i) => {
|
|
254
|
+
const head = ` ${i + 1}. ${f.bold(x.title)}${x.priority ? f.dim(` [${x.priority}]`) : ""}${x.inferred ? f.dim(" inferred") : ""}`;
|
|
255
|
+
const lines = [head];
|
|
256
|
+
if (x.do_this) lines.push(` ${f.cyan("do:")} ${x.do_this}`);
|
|
257
|
+
if (x.why) lines.push(` ${f.dim("why:")} ${x.why}`);
|
|
258
|
+
if (x.evidence?.sessions != null) lines.push(` ${f.dim(`evidence: ${f.num(x.evidence.sessions)} sessions`)}`);
|
|
259
|
+
return lines.join("\n");
|
|
260
|
+
}).join("\n");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const friction = report("/friction", (d) => {
|
|
264
|
+
out(f.heading(`${d.host} — friction, last ${d.window}`));
|
|
265
|
+
out(f.kv([["sessions", f.num(d.sessions)], ["with friction", f.num(d.sessions_with_friction)]]));
|
|
266
|
+
out(f.heading("Top friction"));
|
|
267
|
+
out(frictionTable(d.top_friction));
|
|
268
|
+
out(f.heading("Fixes"));
|
|
269
|
+
out(fixesList(d.fixes));
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
function readinessBlock(r) {
|
|
273
|
+
if (!r) return;
|
|
274
|
+
const scores = r.scores || r;
|
|
275
|
+
out(f.heading(`Readiness: ${scoreColor(scores.score ?? scores.total)}`));
|
|
276
|
+
const parts = ["access", "information", "measurement"].filter((k) => scores[k] != null).map((k) => [k, String(scores[k])]);
|
|
277
|
+
if (parts.length) out(f.kv(parts));
|
|
278
|
+
if (r.recommendations?.length) out(f.list(r.recommendations.map((x) => `${sev(x.severity)} ${x.title}${x.detail ? f.dim(` — ${x.detail}`) : ""}`)));
|
|
279
|
+
}
|
|
280
|
+
const scoreColor = (s) => (s == null ? "–" : s >= 80 ? f.green(s) : s >= 50 ? f.yellow(s) : f.red(s));
|
|
281
|
+
const sev = (s) => (s === "high" || s === "critical" ? f.red(`[${s}]`) : s === "medium" ? f.yellow(`[${s}]`) : f.dim(`[${s || "info"}]`));
|
|
282
|
+
|
|
283
|
+
const fixes = report("/fixes", (d) => {
|
|
284
|
+
out(f.heading(`${d.host} — fixes, last ${d.window}`));
|
|
285
|
+
out(fixesList(d.fixes));
|
|
286
|
+
readinessBlock(d.readiness);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
const pages = report("/pages", (d) => {
|
|
290
|
+
out(f.heading(`${d.host} — page classes, last ${d.window}`));
|
|
291
|
+
out(f.table(d.page_classes, [
|
|
292
|
+
{ key: "id", label: "class" },
|
|
293
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
294
|
+
{ key: "events", label: "events", align: "right", render: f.num },
|
|
295
|
+
]));
|
|
296
|
+
out(f.heading("Common paths"));
|
|
297
|
+
out(f.table(d.sequences, [
|
|
298
|
+
{ key: "path", label: "path", render: (v) => (v || []).join(" → ") },
|
|
299
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
300
|
+
{ key: "converted", label: "conv", align: "right", render: f.num },
|
|
301
|
+
{ key: "friction", label: "friction", align: "right", render: (v) => (Array.isArray(v) ? v.length : f.num(v)) },
|
|
302
|
+
]));
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
const alerts = report("/alerts", (d) => {
|
|
306
|
+
out(f.heading(`${d.host} — alerts, last ${d.window}`));
|
|
307
|
+
const lvl = (l) => (l === "critical" || l === "error" ? f.red : l === "warn" || l === "warning" ? f.yellow : f.dim);
|
|
308
|
+
out(f.list((d.alerts || []).map((a) => `${lvl(a.level)(`[${a.level || "info"}]`)} ${a.text}`)));
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const series = report("/series", (d) => {
|
|
312
|
+
out(f.heading(`${d.host} — per ${d.bucket}, last ${d.window}`));
|
|
313
|
+
out(f.table(d.buckets, [
|
|
314
|
+
{ key: "t", label: "bucket" },
|
|
315
|
+
{ key: "events", label: "events", align: "right", render: f.num },
|
|
316
|
+
{ key: "sessions", label: "sessions", align: "right", render: f.num },
|
|
317
|
+
{ key: "agents", label: "agents", align: "right", render: f.num },
|
|
318
|
+
{ key: "friction_sessions", label: "friction", align: "right", render: f.num },
|
|
319
|
+
{ key: "converted", label: "conv", align: "right", render: f.num },
|
|
320
|
+
{ key: "by_provider", label: "providers", render: (v) => f.topCounts(v, 3) },
|
|
321
|
+
]));
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
const readiness = report("/readiness", (d) => {
|
|
325
|
+
out(f.heading(`${d.host} — checked ${f.ago(d.checked_at)}`));
|
|
326
|
+
readinessBlock(d);
|
|
327
|
+
if (d.files) out(f.dim(`\nDiscovery files available: ${Object.keys(d.files).join(", ")} (wake readiness --json to print them)`));
|
|
328
|
+
}, { windowed: false });
|
|
329
|
+
|
|
330
|
+
async function listing({ flags, args }) {
|
|
331
|
+
const { api } = clientFor(flags);
|
|
332
|
+
if (args[0] === "plan" || flags.plan) {
|
|
333
|
+
const r = await api.post("/listing/plan", {});
|
|
334
|
+
if (flags.json) { out(JSON.stringify(r, null, 2)); return 0; }
|
|
335
|
+
out(`${f.green("Planned")} ${f.num((r.steps || []).length)} listing steps.${r.note ? ` ${r.note}` : ""}`);
|
|
336
|
+
out(f.list((r.steps || []).map(stepLine)));
|
|
337
|
+
return 0;
|
|
338
|
+
}
|
|
339
|
+
const d = await api.get("/listing");
|
|
340
|
+
if (flags.json) { out(JSON.stringify(d, null, 2)); return 0; }
|
|
341
|
+
out(f.heading(`${d.host} — AEO listing`) + (d.listing?.status ? f.dim(` ${d.listing.status}`) : ""));
|
|
342
|
+
if (d.arrivals) {
|
|
343
|
+
out(f.kv([
|
|
344
|
+
["identified agents", f.num(d.arrivals.identified_agents)],
|
|
345
|
+
["crawler agents", f.num(d.arrivals.crawler_agents)],
|
|
346
|
+
["unknown agents", f.num(d.arrivals.unknown_agents)],
|
|
347
|
+
["verdict", d.arrivals.verdict || "–"],
|
|
348
|
+
["note", d.arrivals.note],
|
|
349
|
+
]));
|
|
350
|
+
}
|
|
351
|
+
out(f.heading(d.listing?.planned ? "Steps" : "Steps (not planned yet — run: wake listing plan)"));
|
|
352
|
+
out(f.list((d.listing?.steps || []).map(stepLine)));
|
|
353
|
+
if (d.listing?.publish_files?.length) out(f.dim(`\nFiles to publish: ${d.listing.publish_files.join(", ")}`));
|
|
354
|
+
if (d.how) out(f.dim(`\n${d.how}`));
|
|
355
|
+
return 0;
|
|
356
|
+
}
|
|
357
|
+
const stepLine = (s) => `${f.bold(s.title || s.id)}${s.mode ? f.dim(` (${s.mode})`) : ""}${s.why ? ` — ${s.why}` : ""}${s.last ? f.dim(` last: ${f.ago(s.last)}`) : ""}`;
|
|
358
|
+
|
|
359
|
+
const benchmarks = report("/benchmarks", (d) => {
|
|
360
|
+
if (d.withheld) { out(f.yellow(`Benchmarks withheld${d.reason ? `: ${d.reason}` : " (cohort too small to share safely)."}`)); return; }
|
|
361
|
+
out(f.heading(`Cohort of ${f.num(d.cohort_size)} sites — medians`));
|
|
362
|
+
out(f.kv(Object.entries(d.medians || {}).map(([k, v]) => [k, typeof v === "number" ? f.num(v) : String(v)])));
|
|
363
|
+
}, { windowed: false });
|
|
364
|
+
|
|
365
|
+
async function install({ flags }) {
|
|
366
|
+
const { api } = clientFor(flags);
|
|
367
|
+
const d = await api.get("/install", flags.kit ? { kit: 1 } : {});
|
|
368
|
+
if (flags.json) { out(JSON.stringify(d, null, 2)); return 0; }
|
|
369
|
+
out(f.heading(`${d.host} — collector`));
|
|
370
|
+
out(f.kv([
|
|
371
|
+
["verified", yn(d.verified)],
|
|
372
|
+
["provisioned", yn(d.provisioned)],
|
|
373
|
+
["endpoint", d.collector_endpoint || d.endpoint || "–"],
|
|
374
|
+
["kit", d.kit_available ? "available (wake install --kit --out ./wake-kit)" : "not available yet"],
|
|
375
|
+
["last event", f.ago(d.last_event_at)],
|
|
376
|
+
]));
|
|
377
|
+
if (flags.kit && d.files) {
|
|
378
|
+
const dir = path.resolve(flags.out || "./wake-kit");
|
|
379
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
380
|
+
out(f.heading(`Kit written to ${dir}`));
|
|
381
|
+
for (const [name, body] of Object.entries(d.files)) {
|
|
382
|
+
const file = path.join(dir, path.basename(name));
|
|
383
|
+
fs.writeFileSync(file, body);
|
|
384
|
+
out(` ${file}`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return 0;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async function exportCmd({ flags, args }) {
|
|
391
|
+
// Accepts "export sessions --out x.csv", "export sessions.csv", "export sessions.csv --out x.csv".
|
|
392
|
+
const what = (args[0] || "sessions").replace(/\.csv$/, "");
|
|
393
|
+
if (what !== "sessions") throw new WakeError(`Only "sessions" can be exported (got ${args[0]})`, { code: "bad_args" });
|
|
394
|
+
const { api } = clientFor(flags);
|
|
395
|
+
const csv = await api.text("/sessions.csv", { window: windowOf(flags) });
|
|
396
|
+
const target = flags.out || (args[0]?.endsWith(".csv") ? args[0] : "");
|
|
397
|
+
if (!target || target === "-") { process.stdout.write(csv); return 0; }
|
|
398
|
+
const file = path.resolve(target);
|
|
399
|
+
fs.writeFileSync(file, csv);
|
|
400
|
+
const rows = Math.max(0, csv.trim().split("\n").length - 1);
|
|
401
|
+
err(`Wrote ${f.num(rows)} sessions to ${file}`);
|
|
402
|
+
return 0;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// stdio ⇄ HTTP bridge. Each stdin line is one JSON-RPC message (or batch) forwarded untouched.
|
|
406
|
+
async function mcp({ flags }) {
|
|
407
|
+
const { api } = clientFor(flags);
|
|
408
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
409
|
+
let chain = Promise.resolve();
|
|
410
|
+
rl.on("line", (line) => {
|
|
411
|
+
const trimmed = line.trim();
|
|
412
|
+
if (!trimmed) return;
|
|
413
|
+
chain = chain.then(() => forward(api, trimmed)).catch((e) => err(`wake mcp: ${e.message}`));
|
|
414
|
+
});
|
|
415
|
+
await new Promise((resolve) => rl.on("close", resolve));
|
|
416
|
+
await chain;
|
|
417
|
+
return 0;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function forward(api, raw) {
|
|
421
|
+
let msg;
|
|
422
|
+
try { msg = JSON.parse(raw); } catch { err("wake mcp: skipped a line that was not JSON"); return; }
|
|
423
|
+
const expectsReply = Array.isArray(msg) ? msg.some((m) => m && m.id !== undefined) : msg && msg.id !== undefined;
|
|
424
|
+
let res;
|
|
425
|
+
try {
|
|
426
|
+
res = await api.postRaw("/mcp", raw, "application/json, text/event-stream");
|
|
427
|
+
} catch (e) {
|
|
428
|
+
if (expectsReply) out(JSON.stringify(rpcError(msg, e)));
|
|
429
|
+
err(`wake mcp: ${e.message}`);
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (!expectsReply || res.status === 202 || !res.text.trim()) return;
|
|
433
|
+
out(res.contentType.includes("text/event-stream") ? sseToJson(res.text) : res.text.replace(/\s*\n\s*/g, " "));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// A server may answer with SSE even though we ask for JSON; keep the last data payload.
|
|
437
|
+
function sseToJson(text) {
|
|
438
|
+
const data = text.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim());
|
|
439
|
+
return data.length ? data[data.length - 1] : "";
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function rpcError(msg, e) {
|
|
443
|
+
const id = Array.isArray(msg) ? (msg.find((m) => m?.id !== undefined)?.id ?? null) : msg.id ?? null;
|
|
444
|
+
const code = e.status === 401 ? -32001 : -32000;
|
|
445
|
+
return { jsonrpc: "2.0", id, error: { code, message: `wake: ${e.message}` } };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const CLIENTS = ["claude-code", "cursor", "codex", "claude-desktop", "chatgpt", "curl"];
|
|
449
|
+
|
|
450
|
+
async function connect({ flags, args }) {
|
|
451
|
+
const client = args[0];
|
|
452
|
+
if (!CLIENTS.includes(client)) throw new WakeError(`wake connect <client> — client must be one of ${CLIENTS.join(", ")}`, { code: "bad_args" });
|
|
453
|
+
const { cfg } = clientFor(flags, { requireKey: false });
|
|
454
|
+
const mcpUrl = `${apiBase(cfg.url)}/mcp`;
|
|
455
|
+
const key = cfg.key || "wk_live_<your key>";
|
|
456
|
+
const shown = flags["show-key"] || flags.write || !cfg.key ? key : maskKey(key);
|
|
457
|
+
const masked = shown !== key;
|
|
458
|
+
|
|
459
|
+
const cursorCfg = { mcpServers: { wake: { url: mcpUrl, headers: { Authorization: `Bearer ${shown}` } } } };
|
|
460
|
+
const desktopCfg = { mcpServers: { wake: { command: "npx", args: ["-y", "wake-agents", "mcp"], env: { WAKE_API_KEY: shown, WAKE_API_URL: cfg.url } } } };
|
|
461
|
+
|
|
462
|
+
const note = masked ? f.dim("\nKey is masked; add --show-key to print it, or --write to write the real value to the file.") : "";
|
|
463
|
+
|
|
464
|
+
switch (client) {
|
|
465
|
+
case "claude-code":
|
|
466
|
+
out(`claude mcp add --transport http wake ${mcpUrl} --header "Authorization: Bearer ${shown}"${note}`);
|
|
467
|
+
break;
|
|
468
|
+
case "cursor": {
|
|
469
|
+
const file = path.resolve(".cursor/mcp.json");
|
|
470
|
+
if (flags.write) { out(`Wrote ${writeMcpJson(file, cursorCfg.mcpServers.wake)}`); }
|
|
471
|
+
else out(`${JSON.stringify(cursorCfg, null, 2)}\n\nSave as ${file} (or run: wake connect cursor --write)${note}`);
|
|
472
|
+
break;
|
|
473
|
+
}
|
|
474
|
+
case "codex":
|
|
475
|
+
out(`# ~/.codex/config.toml\n[mcp_servers.wake]\nurl = "${mcpUrl}"\nbearer_token_env_var = "WAKE_API_KEY"\n\n# in your shell profile\nexport WAKE_API_KEY=${shown}${note}`);
|
|
476
|
+
break;
|
|
477
|
+
case "claude-desktop": {
|
|
478
|
+
const file = claudeDesktopConfigPath();
|
|
479
|
+
if (flags.write) { out(`Wrote ${writeMcpJson(file, desktopCfg.mcpServers.wake)}\nRestart Claude Desktop to pick it up.`); }
|
|
480
|
+
else out(`${JSON.stringify(desktopCfg, null, 2)}\n\nMerge into ${file} (or run: wake connect claude-desktop --write)${note}`);
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
case "chatgpt":
|
|
484
|
+
out([
|
|
485
|
+
"ChatGPT connectors need a hosted MCP server with OAuth, which Wake doesn't offer yet.",
|
|
486
|
+
"",
|
|
487
|
+
`MCP endpoint (bearer auth): ${mcpUrl}`,
|
|
488
|
+
"",
|
|
489
|
+
"Supported today:",
|
|
490
|
+
" • any MCP client that can send an Authorization header (Claude Code, Cursor, Codex) — see wake connect <client>",
|
|
491
|
+
" • stdio-only clients via the bridge: npx -y wake-agents mcp",
|
|
492
|
+
` • the REST API directly: wake connect curl`,
|
|
493
|
+
].join("\n"));
|
|
494
|
+
break;
|
|
495
|
+
case "curl":
|
|
496
|
+
out(`curl -H "Authorization: Bearer ${shown}" "${apiBase(cfg.url)}/overview?window=7d"${note}`);
|
|
497
|
+
break;
|
|
498
|
+
}
|
|
499
|
+
return 0;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function claudeDesktopConfigPath() {
|
|
503
|
+
const home = os.homedir();
|
|
504
|
+
if (process.platform === "darwin") return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
505
|
+
if (process.platform === "win32") return path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
|
|
506
|
+
return path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "Claude", "claude_desktop_config.json");
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// Merges {mcpServers.wake} into an existing JSON file without touching other servers.
|
|
510
|
+
function writeMcpJson(file, server) {
|
|
511
|
+
let existing = {};
|
|
512
|
+
try { existing = JSON.parse(fs.readFileSync(file, "utf8")) || {}; } catch {}
|
|
513
|
+
existing.mcpServers = { ...(existing.mcpServers || {}), wake: server };
|
|
514
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
515
|
+
fs.writeFileSync(file, JSON.stringify(existing, null, 2) + "\n", { mode: 0o600 });
|
|
516
|
+
return file;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const yn = (v) => (v ? f.green("yes") : f.yellow("no"));
|
|
520
|
+
|
|
521
|
+
const COMMANDS = {
|
|
522
|
+
login, logout, status, overview, agents, sessions, funnel, friction, fixes, pages, alerts, series,
|
|
523
|
+
readiness, listing, benchmarks, install, export: exportCmd, mcp, connect,
|
|
524
|
+
};
|
package/lib/client.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export const USER_AGENT = "wake-cli/0.1.0";
|
|
2
|
+
const TIMEOUT_MS = 20_000;
|
|
3
|
+
|
|
4
|
+
export class WakeError extends Error {
|
|
5
|
+
constructor(message, { status = 0, code = "" } = {}) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "WakeError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function apiBase(url) {
|
|
14
|
+
return `${String(url).replace(/\/+$/, "")}/api/wake/v1`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function createClient({ url, key }) {
|
|
18
|
+
const base = apiBase(url);
|
|
19
|
+
|
|
20
|
+
function headers(extra = {}) {
|
|
21
|
+
const h = { "User-Agent": USER_AGENT, Accept: "application/json", ...extra };
|
|
22
|
+
if (key) h.Authorization = `Bearer ${key}`;
|
|
23
|
+
return h;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function request(path, { method = "GET", body, params, raw = false, accept } = {}) {
|
|
27
|
+
const u = new URL(base + path);
|
|
28
|
+
for (const [k, v] of Object.entries(params || {})) {
|
|
29
|
+
if (v !== undefined && v !== null && v !== "") u.searchParams.set(k, String(v));
|
|
30
|
+
}
|
|
31
|
+
const ctl = new AbortController();
|
|
32
|
+
const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
|
|
33
|
+
let res;
|
|
34
|
+
try {
|
|
35
|
+
res = await fetch(u, {
|
|
36
|
+
method,
|
|
37
|
+
headers: headers({
|
|
38
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
39
|
+
...(accept ? { Accept: accept } : {}),
|
|
40
|
+
}),
|
|
41
|
+
body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body),
|
|
42
|
+
signal: ctl.signal,
|
|
43
|
+
});
|
|
44
|
+
} catch (err) {
|
|
45
|
+
const msg = err?.name === "AbortError" ? `Timed out after ${TIMEOUT_MS / 1000}s: ${u}` : `Network error: ${err?.message || err}`;
|
|
46
|
+
throw new WakeError(msg, { code: "network" });
|
|
47
|
+
} finally {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
}
|
|
50
|
+
const text = await res.text();
|
|
51
|
+
if (!res.ok) throw errorFrom(res.status, text);
|
|
52
|
+
if (raw) return { status: res.status, text, contentType: res.headers.get("content-type") || "" };
|
|
53
|
+
if (!text) return null;
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(text);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new WakeError(`Unexpected non-JSON response (${res.status}) from ${u.pathname}`, { status: res.status, code: "bad_response" });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
base,
|
|
63
|
+
get: (path, params) => request(path, { params }),
|
|
64
|
+
post: (path, body) => request(path, { method: "POST", body }),
|
|
65
|
+
text: (path, params) => request(path, { params, raw: true, accept: "*/*" }).then((r) => r.text),
|
|
66
|
+
// Used by the MCP bridge: forwards a pre-serialised JSON-RPC payload untouched.
|
|
67
|
+
postRaw: (path, body, accept) => request(path, { method: "POST", body, raw: true, accept }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function errorFrom(status, text) {
|
|
72
|
+
let code = "";
|
|
73
|
+
let message = "";
|
|
74
|
+
try {
|
|
75
|
+
const j = JSON.parse(text);
|
|
76
|
+
code = j.code || "";
|
|
77
|
+
message = j.error || j.message || "";
|
|
78
|
+
} catch {
|
|
79
|
+
message = text.slice(0, 200);
|
|
80
|
+
}
|
|
81
|
+
if (!message) message = `HTTP ${status}`;
|
|
82
|
+
return new WakeError(message, { status, code });
|
|
83
|
+
}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_URL = "https://agent-observatory-desk-production.up.railway.app";
|
|
6
|
+
export const KEY_PATTERN = /^wk_live_[a-f0-9]{40}$/;
|
|
7
|
+
|
|
8
|
+
export function configPath() {
|
|
9
|
+
const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
10
|
+
return path.join(base, "wake", "config.json");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function readConfig() {
|
|
14
|
+
try {
|
|
15
|
+
const raw = fs.readFileSync(configPath(), "utf8");
|
|
16
|
+
const parsed = JSON.parse(raw);
|
|
17
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
18
|
+
} catch {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function writeConfig({ url, key }) {
|
|
24
|
+
const file = configPath();
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
26
|
+
fs.writeFileSync(file, JSON.stringify({ url, key }, null, 2) + "\n", { mode: 0o600 });
|
|
27
|
+
fs.chmodSync(file, 0o600);
|
|
28
|
+
return file;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function deleteConfig() {
|
|
32
|
+
try {
|
|
33
|
+
fs.unlinkSync(configPath());
|
|
34
|
+
return true;
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Precedence: flags > env > config file > default (url only).
|
|
41
|
+
export function resolveConfig(flags = {}) {
|
|
42
|
+
const file = readConfig();
|
|
43
|
+
const url = flags.url || process.env.WAKE_API_URL || file.url || DEFAULT_URL;
|
|
44
|
+
const key = flags.key || process.env.WAKE_API_KEY || file.key || "";
|
|
45
|
+
return { url: url.replace(/\/+$/, ""), key };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function maskKey(key) {
|
|
49
|
+
if (!key) return "(none)";
|
|
50
|
+
return key.length > 12 ? `${key.slice(0, 12)}…` : "wk_live_…";
|
|
51
|
+
}
|
package/lib/format.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
const useColor = () => Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
2
|
+
|
|
3
|
+
function paint(code) {
|
|
4
|
+
return (s) => (useColor() ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
5
|
+
}
|
|
6
|
+
export const bold = paint("1");
|
|
7
|
+
export const dim = paint("2");
|
|
8
|
+
export const green = paint("32");
|
|
9
|
+
export const yellow = paint("33");
|
|
10
|
+
export const red = paint("31");
|
|
11
|
+
export const cyan = paint("36");
|
|
12
|
+
|
|
13
|
+
export function num(n) {
|
|
14
|
+
if (n === null || n === undefined || Number.isNaN(Number(n))) return "–";
|
|
15
|
+
return Number(n).toLocaleString("en-US");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Accepts a ratio (0.42) or a percentage (42); anything > 1 is treated as already-percent.
|
|
19
|
+
export function pct(v, digits = 1) {
|
|
20
|
+
if (v === null || v === undefined || Number.isNaN(Number(v))) return "–";
|
|
21
|
+
const n = Number(v);
|
|
22
|
+
const p = n <= 1 ? n * 100 : n;
|
|
23
|
+
return `${p.toFixed(digits)}%`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function ago(iso, now = Date.now()) {
|
|
27
|
+
if (!iso) return "never";
|
|
28
|
+
const t = typeof iso === "number" ? iso : Date.parse(iso);
|
|
29
|
+
if (Number.isNaN(t)) return String(iso);
|
|
30
|
+
const s = Math.max(0, Math.round((now - t) / 1000));
|
|
31
|
+
if (s < 60) return `${s}s ago`;
|
|
32
|
+
const m = Math.round(s / 60);
|
|
33
|
+
if (m < 60) return `${m}m ago`;
|
|
34
|
+
const h = Math.round(m / 60);
|
|
35
|
+
if (h < 48) return `${h}h ago`;
|
|
36
|
+
return `${Math.round(h / 24)}d ago`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function duration(ms) {
|
|
40
|
+
if (ms === null || ms === undefined) return "–";
|
|
41
|
+
const s = Math.round(Number(ms) / 1000);
|
|
42
|
+
if (s < 60) return `${s}s`;
|
|
43
|
+
const m = Math.floor(s / 60);
|
|
44
|
+
return m < 60 ? `${m}m${s % 60}s` : `${Math.floor(m / 60)}h${m % 60}m`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const width = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, "").length;
|
|
48
|
+
const padEnd = (s, n) => String(s) + " ".repeat(Math.max(0, n - width(s)));
|
|
49
|
+
const padStart = (s, n) => " ".repeat(Math.max(0, n - width(s))) + String(s);
|
|
50
|
+
|
|
51
|
+
// columns: [{ key, label, align?: "right", render?: fn }]
|
|
52
|
+
export function table(rows, columns) {
|
|
53
|
+
if (!rows?.length) return dim(" (none)");
|
|
54
|
+
const cells = rows.map((r) => columns.map((c) => (c.render ? c.render(r[c.key]) : r[c.key] ?? "")));
|
|
55
|
+
const widths = columns.map((c, i) => Math.max(width(c.label), ...cells.map((row) => width(row[i]))));
|
|
56
|
+
const line = (vals, style = (x) => x) =>
|
|
57
|
+
" " + vals.map((v, i) => (columns[i].align === "right" ? padStart(v, widths[i]) : padEnd(v, widths[i]))).map(style).join(" ");
|
|
58
|
+
return [line(columns.map((c) => c.label), bold), ...cells.map((row) => line(row))].join("\n");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function kv(pairs) {
|
|
62
|
+
const entries = pairs.filter(([, v]) => v !== undefined);
|
|
63
|
+
const w = Math.max(...entries.map(([k]) => width(k)));
|
|
64
|
+
return entries.map(([k, v]) => ` ${dim(padEnd(k, w))} ${v}`).join("\n");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function heading(s) {
|
|
68
|
+
return `\n${bold(s)}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function list(items, bullet = "•") {
|
|
72
|
+
return items.length ? items.map((i) => ` ${bullet} ${i}`).join("\n") : dim(" (none)");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Top-N of a {name: count} map as "name 12, other 3".
|
|
76
|
+
export function topCounts(map, n = 5) {
|
|
77
|
+
const entries = Object.entries(map || {}).sort((a, b) => b[1] - a[1]).slice(0, n);
|
|
78
|
+
return entries.length ? entries.map(([k, v]) => `${k} ${num(v)}`).join(", ") : "–";
|
|
79
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wake-agents",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Wake CLI: see which AI agents reach your site, where they get stuck, and what to fix. Also a stdio MCP bridge for Claude Desktop and other MCP clients.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"wake": "bin/wake.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"lib",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/agent-observatory/agent-observatory.git",
|
|
21
|
+
"directory": "sdk/wake-cli"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://agent-observatory-desk-production.up.railway.app/wake/",
|
|
24
|
+
"keywords": [
|
|
25
|
+
"wake",
|
|
26
|
+
"agent-observatory",
|
|
27
|
+
"ai-agents",
|
|
28
|
+
"mcp",
|
|
29
|
+
"aeo",
|
|
30
|
+
"analytics",
|
|
31
|
+
"agent-readiness",
|
|
32
|
+
"cli"
|
|
33
|
+
]
|
|
34
|
+
}
|