walkie-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/bin/walkie.mjs +9 -0
- package/dist/actions.js +95 -0
- package/dist/adapters.js +75 -0
- package/dist/channel.js +129 -0
- package/dist/cli.js +384 -0
- package/dist/config.js +114 -0
- package/dist/feed.js +20 -0
- package/dist/install.js +86 -0
- package/dist/join.js +89 -0
- package/dist/listen.js +129 -0
- package/dist/pair.js +71 -0
- package/dist/rendezvous.js +44 -0
- package/dist/report.js +57 -0
- package/dist/running.js +51 -0
- package/dist/sse.js +79 -0
- package/dist/webhook-server.js +102 -0
- package/package.json +52 -4
package/dist/join.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie join <server> <code>`: pair this machine with a bulletin in
|
|
3
|
+
* one command. Exchanges the one-time code for a recipient token, saves the
|
|
4
|
+
* credentials for this user, and installs hooks for whatever harnesses are
|
|
5
|
+
* present here.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
|
+
import { hostname } from "node:os";
|
|
9
|
+
import { join as joinPath } from "node:path";
|
|
10
|
+
import { writeUserConfig } from "./config.js";
|
|
11
|
+
import { installAgentsMd, installClaude, installCursor } from "./install.js";
|
|
12
|
+
/** Parse `join <code>` (server found through the rendezvous), `join <url> <code>`, or a single `<url>/join/<code>`. */
|
|
13
|
+
export function parseJoinArgs(args) {
|
|
14
|
+
if (args.length >= 2 && args[0] && args[1])
|
|
15
|
+
return { url: args[0].replace(/\/+$/, ""), code: args[1] };
|
|
16
|
+
if (args.length === 1 && args[0]) {
|
|
17
|
+
const m = args[0].match(/^(https?:\/\/[^/]+)(?:\/.*)?\/join\/([A-Za-z0-9-]+)\/?$/);
|
|
18
|
+
if (m)
|
|
19
|
+
return { url: m[1], code: m[2] };
|
|
20
|
+
if (/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(args[0]))
|
|
21
|
+
return { url: null, code: args[0] };
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/** Which harness is this machine most likely to run? Checked in the project dir and the environment. */
|
|
26
|
+
export function detectHarness(cwd, env = process.env) {
|
|
27
|
+
const reasons = [];
|
|
28
|
+
if (env.CLAUDE_CODE_SESSION_ID || env.CLAUDECODE)
|
|
29
|
+
reasons.push("running inside Claude Code");
|
|
30
|
+
if (existssyncAny(cwd, [".claude"]))
|
|
31
|
+
reasons.push(".claude/ present");
|
|
32
|
+
if (reasons.length)
|
|
33
|
+
return { harness: "claude-code", reasons };
|
|
34
|
+
if (existsSync(joinPath(cwd, ".cursor")))
|
|
35
|
+
return { harness: "cursor", reasons: [".cursor/ present"] };
|
|
36
|
+
if (env.CI)
|
|
37
|
+
return { harness: "ci", reasons: ["CI environment variable set"] };
|
|
38
|
+
if (existsSync(joinPath(cwd, "AGENTS.md")))
|
|
39
|
+
return { harness: "other", reasons: ["AGENTS.md present"] };
|
|
40
|
+
return { harness: "server", reasons: ["no harness markers found"] };
|
|
41
|
+
}
|
|
42
|
+
function existssyncAny(cwd, names) {
|
|
43
|
+
return names.some((n) => existsSync(joinPath(cwd, n)));
|
|
44
|
+
}
|
|
45
|
+
/** Same tolerance as the server: case-insensitive, separators ignored, O→0 and I→1. */
|
|
46
|
+
export const normalizeCode = (raw) => raw.toUpperCase().replace(/[^A-Z0-9]/g, "").replace(/O/g, "0").replace(/I/g, "1").slice(0, 26);
|
|
47
|
+
export async function requestJoin(url, code, name, harness, fetchImpl = fetch) {
|
|
48
|
+
const res = await fetchImpl(new URL("/v1/join", url + "/"), {
|
|
49
|
+
method: "POST",
|
|
50
|
+
headers: { "content-type": "application/json" },
|
|
51
|
+
body: JSON.stringify({ code: normalizeCode(code), name, harness }),
|
|
52
|
+
});
|
|
53
|
+
if (!res.ok) {
|
|
54
|
+
let detail = "";
|
|
55
|
+
try {
|
|
56
|
+
detail = (await res.json()).message ?? "";
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
/* ignore */
|
|
60
|
+
}
|
|
61
|
+
if (res.status === 404)
|
|
62
|
+
throw new Error(`code not accepted (expired or already used)${detail ? `: ${detail}` : ""}`);
|
|
63
|
+
throw new Error(`join failed: HTTP ${res.status}${detail ? ` (${detail})` : ""}`);
|
|
64
|
+
}
|
|
65
|
+
return (await res.json());
|
|
66
|
+
}
|
|
67
|
+
export async function join(url, code, opts) {
|
|
68
|
+
const log = opts.log ?? (() => { });
|
|
69
|
+
const env = opts.env ?? process.env;
|
|
70
|
+
const detected = detectHarness(opts.cwd, env);
|
|
71
|
+
const harness = opts.harness ?? detected.harness;
|
|
72
|
+
const name = opts.name ?? hostname();
|
|
73
|
+
const result = await requestJoin(url, code, name, harness, opts.fetchImpl);
|
|
74
|
+
const configPath = writeUserConfig({ url: result.serverUrl || url, token: result.token }, env);
|
|
75
|
+
log(`joined "${result.bulletin.name}" as "${result.subscriber.name}" (${harness}${opts.harness ? "" : `, ${detected.reasons.join("; ")}`})`);
|
|
76
|
+
log(`saved credentials to ${configPath}`);
|
|
77
|
+
const installed = [];
|
|
78
|
+
if (opts.install ?? true) {
|
|
79
|
+
if (harness === "claude-code")
|
|
80
|
+
installed.push(installClaude({ projectRoot: opts.cwd, global: opts.global, home: env.HOME }));
|
|
81
|
+
if (harness === "cursor")
|
|
82
|
+
installed.push(installCursor({ projectRoot: opts.cwd }));
|
|
83
|
+
if (harness === "other" && existsSync(joinPath(opts.cwd, "AGENTS.md")))
|
|
84
|
+
installed.push(installAgentsMd({ projectRoot: opts.cwd }));
|
|
85
|
+
for (const f of installed)
|
|
86
|
+
log(`installed hooks: ${f}`);
|
|
87
|
+
}
|
|
88
|
+
return { ...result, installed, configPath };
|
|
89
|
+
}
|
package/dist/listen.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie listen`: a long-running recipient for ANY machine.
|
|
3
|
+
*
|
|
4
|
+
* Holds an SSE connection to the server, resumes from the last seen event
|
|
5
|
+
* after restarts (cursor persisted on disk), runs the configured actions for
|
|
6
|
+
* each post, and acknowledges posts whose actions succeeded.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { hostname } from "node:os";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { runActions } from "./actions.js";
|
|
13
|
+
import { stateDir } from "./config.js";
|
|
14
|
+
import { fetchFeed } from "./feed.js";
|
|
15
|
+
import { consumeSse } from "./sse.js";
|
|
16
|
+
function cursorPath(opts) {
|
|
17
|
+
const key = createHash("sha256").update(`${opts.url}|${opts.token}|${opts.name ?? ""}`).digest("hex").slice(0, 16);
|
|
18
|
+
return join(stateDir(opts.env), "listen", `${key}.json`);
|
|
19
|
+
}
|
|
20
|
+
export function readCursor(opts) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(readFileSync(cursorPath(opts), "utf8")).lastEventId;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function writeCursor(opts, lastEventId) {
|
|
29
|
+
const p = cursorPath(opts);
|
|
30
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
31
|
+
writeFileSync(p, JSON.stringify({ lastEventId, savedAt: new Date().toISOString() }));
|
|
32
|
+
}
|
|
33
|
+
export async function ackPosts(opts, postIds, sessionId) {
|
|
34
|
+
if (postIds.length === 0)
|
|
35
|
+
return;
|
|
36
|
+
await (opts.fetchImpl ?? fetch)(new URL("/v1/ack", opts.url + "/"), {
|
|
37
|
+
method: "POST",
|
|
38
|
+
headers: { authorization: `Bearer ${opts.token}`, "content-type": "application/json" },
|
|
39
|
+
body: JSON.stringify({ postIds, sessionId }),
|
|
40
|
+
}).catch(() => { });
|
|
41
|
+
}
|
|
42
|
+
export function toIncoming(type, id, feed, post, markdown, replay = false) {
|
|
43
|
+
return {
|
|
44
|
+
type,
|
|
45
|
+
id,
|
|
46
|
+
bulletin: { slug: feed.bulletin.slug, name: feed.bulletin.name },
|
|
47
|
+
post,
|
|
48
|
+
markdown,
|
|
49
|
+
receivedAt: new Date().toISOString(),
|
|
50
|
+
replay,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function renderOne(bulletinName, post) {
|
|
54
|
+
const label = post.priority === "urgent" ? "🚨 URGENT: " : post.priority === "pinned" ? "📌 " : "";
|
|
55
|
+
const tags = post.tags.length ? ` _[${post.tags.join(", ")}]_` : "";
|
|
56
|
+
return `# Walkie Talkie · ${bulletinName}\n\n## ${label}${post.title}${tags}\n${post.body.trim()}\n`;
|
|
57
|
+
}
|
|
58
|
+
export async function listen(opts) {
|
|
59
|
+
const log = opts.log ?? ((m) => process.stderr.write(`walkie listen: ${m}\n`));
|
|
60
|
+
const name = opts.name ?? hostname();
|
|
61
|
+
const harness = opts.harness ?? "server";
|
|
62
|
+
const ack = opts.ack ?? true;
|
|
63
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
64
|
+
// Identify ourselves and learn the bulletin name via one feed pull.
|
|
65
|
+
const feed = await fetchFeed(opts, { sessionId: name, harness, event: "listen", cwd: process.cwd() }, { fetchImpl });
|
|
66
|
+
log(`recipient "${name}" subscribed to ${feed.bulletin.name} (${feed.subscriber.name})`);
|
|
67
|
+
const refresh = () => fetchFeed(opts, { sessionId: name, harness, event: "sync" }, { fetchImpl });
|
|
68
|
+
const actionOpts = { ...opts, log, refresh };
|
|
69
|
+
let cursor = readCursor(opts);
|
|
70
|
+
if (!cursor && opts.initial) {
|
|
71
|
+
for (const post of feed.posts) {
|
|
72
|
+
const ev = toIncoming("post.published", `initial-${post.id}`, feed, post, renderOne(feed.bulletin.name, post), true);
|
|
73
|
+
try {
|
|
74
|
+
await runActions(ev, actionOpts);
|
|
75
|
+
if (ack)
|
|
76
|
+
await ackPosts({ ...opts, fetchImpl }, [post.id], name);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
log(`action failed for ${post.title}: ${e instanceof Error ? e.message : String(e)}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!cursor) {
|
|
84
|
+
cursor = feed.generatedAt;
|
|
85
|
+
writeCursor(opts, cursor);
|
|
86
|
+
}
|
|
87
|
+
const url = new URL("/v1/stream", opts.url + "/");
|
|
88
|
+
url.searchParams.set("sessionId", name);
|
|
89
|
+
url.searchParams.set("harness", harness);
|
|
90
|
+
url.searchParams.set("event", "listen");
|
|
91
|
+
await consumeSse({
|
|
92
|
+
url: url.toString(),
|
|
93
|
+
headers: { authorization: `Bearer ${opts.token}` },
|
|
94
|
+
lastEventId: cursor,
|
|
95
|
+
signal: opts.signal,
|
|
96
|
+
fetchImpl,
|
|
97
|
+
onStatus: log,
|
|
98
|
+
onEvent: async (ev) => {
|
|
99
|
+
if (ev.event === "hello" || ev.event === "ping") {
|
|
100
|
+
if (ev.id)
|
|
101
|
+
writeCursor(opts, ev.id);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!ev.event.startsWith("post."))
|
|
105
|
+
return;
|
|
106
|
+
let payload;
|
|
107
|
+
try {
|
|
108
|
+
payload = JSON.parse(ev.data);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const post = payload.post;
|
|
114
|
+
const markdown = post && ev.event !== "post.archived" ? renderOne(feed.bulletin.name, post) : "";
|
|
115
|
+
const incoming = toIncoming(ev.event, ev.id ?? `${ev.event}-${Date.now()}`, feed, post, markdown, Boolean(payload.replay));
|
|
116
|
+
try {
|
|
117
|
+
await runActions(incoming, actionOpts);
|
|
118
|
+
if (ack && post && ev.event !== "post.archived")
|
|
119
|
+
await ackPosts({ ...opts, fetchImpl }, [post.id], name);
|
|
120
|
+
if (ev.id)
|
|
121
|
+
writeCursor(opts, ev.id);
|
|
122
|
+
}
|
|
123
|
+
catch (e) {
|
|
124
|
+
// Leave the cursor where it is so the post is replayed on the next reconnect.
|
|
125
|
+
log(`action failed for ${post?.title ?? ev.event}: ${e instanceof Error ? e.message : String(e)}`);
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
package/dist/pair.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie pair`: scan to pair. This machine makes up a long one-time code and
|
|
3
|
+
* shows it as a QR. The phone's camera opens the app on it; when the person
|
|
4
|
+
* taps Pair, their server accepts the code and announces where it lives. This
|
|
5
|
+
* machine has been asking the rendezvous for exactly that, and joins.
|
|
6
|
+
* Nothing is typed on either side.
|
|
7
|
+
*/
|
|
8
|
+
import { randomInt } from "node:crypto";
|
|
9
|
+
import { hostname } from "node:os";
|
|
10
|
+
import QRCode from "qrcode";
|
|
11
|
+
import { DEFAULT_RENDEZVOUS_URL, lookupKey } from "./rendezvous.js";
|
|
12
|
+
const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
13
|
+
/** 26 symbols of 5 bits: 130 bits. It is only ever read by a camera. */
|
|
14
|
+
export function newScanCode() {
|
|
15
|
+
let s = "";
|
|
16
|
+
for (let i = 0; i < 26; i++)
|
|
17
|
+
s += ALPHABET[randomInt(ALPHABET.length)];
|
|
18
|
+
return s;
|
|
19
|
+
}
|
|
20
|
+
/** "Nikos-MacBook-Pro.local" is a hostname; "Nikos MacBook Pro" is a name. */
|
|
21
|
+
export function machineName(raw = hostname()) {
|
|
22
|
+
const base = raw.replace(/\.(local|lan|home|internal)$/i, "").replace(/[-_]+/g, " ").trim();
|
|
23
|
+
return (base || "This computer").slice(0, 60);
|
|
24
|
+
}
|
|
25
|
+
export function pairLink(code, name) {
|
|
26
|
+
return `walkie://pair?c=${code}&n=${encodeURIComponent(name)}`;
|
|
27
|
+
}
|
|
28
|
+
export function renderQr(text) {
|
|
29
|
+
return QRCode.toString(text, { type: "terminal", small: true, errorCorrectionLevel: "L" });
|
|
30
|
+
}
|
|
31
|
+
const isLoopback = (host) => host === "localhost" || host === "127.0.0.1" || host === "[::1]";
|
|
32
|
+
/** Ask the rendezvous until the phone has approved, then return the server to join. */
|
|
33
|
+
export async function waitForApproval(code, env = process.env, opts = {}) {
|
|
34
|
+
const base = (env.WALKIE_RENDEZVOUS_URL || DEFAULT_RENDEZVOUS_URL).replace(/\/+$/, "");
|
|
35
|
+
const key = lookupKey(code);
|
|
36
|
+
const f = opts.fetchImpl ?? fetch;
|
|
37
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
38
|
+
const interval = opts.intervalMs ?? 2_500;
|
|
39
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 10 * 60_000);
|
|
40
|
+
let unreachable = 0;
|
|
41
|
+
while (Date.now() < deadline) {
|
|
42
|
+
let res = null;
|
|
43
|
+
try {
|
|
44
|
+
res = await f(`${base}/v1/rendezvous/${key}`, { signal: AbortSignal.timeout(8_000), redirect: "error" });
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
if (++unreachable >= 5)
|
|
48
|
+
throw new Error("cannot reach the pairing service. Check the connection, or pair with a code from the app: walkie join <code>");
|
|
49
|
+
}
|
|
50
|
+
if (res?.ok) {
|
|
51
|
+
const { url } = (await res.json());
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = new URL(String(url));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new Error("the pairing service returned something that is not a server address");
|
|
58
|
+
}
|
|
59
|
+
// The code is a credential: it only goes to HTTPS (or this machine, for development).
|
|
60
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback(parsed.hostname)))
|
|
61
|
+
throw new Error(`refusing to pair over an insecure address (${parsed.origin})`);
|
|
62
|
+
if (parsed.username || parsed.password)
|
|
63
|
+
throw new Error("the pairing service returned an address with credentials in it");
|
|
64
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
|
|
65
|
+
}
|
|
66
|
+
if (res)
|
|
67
|
+
unreachable = 0;
|
|
68
|
+
await sleep(res?.status === 429 ? interval * 4 : interval);
|
|
69
|
+
}
|
|
70
|
+
throw new Error("nobody scanned the code in time. Run the command again for a fresh one.");
|
|
71
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie join ABCD-EFGH` has no server address in it. The machine hashes the
|
|
3
|
+
* code (scrypt, so the rendezvous cannot work backwards to the code) and asks
|
|
4
|
+
* the rendezvous which server issued it. The code itself is only ever sent to
|
|
5
|
+
* that server, over HTTPS.
|
|
6
|
+
*/
|
|
7
|
+
import { scryptSync } from "node:crypto";
|
|
8
|
+
/** One fixed address. Override with WALKIE_RENDEZVOUS_URL. Must match the server's default. */
|
|
9
|
+
export const DEFAULT_RENDEZVOUS_URL = "https://walkie-nk-8d3d.fly.dev";
|
|
10
|
+
/** Must match apps/server/src/rendezvous.ts; both are pinned by the same test vector. */
|
|
11
|
+
export function lookupKey(code) {
|
|
12
|
+
return scryptSync(code, "walkie-rendezvous-v1", 32, { N: 16384, r: 8, p: 1 }).toString("hex");
|
|
13
|
+
}
|
|
14
|
+
const isLoopback = (host) => host === "localhost" || host === "127.0.0.1" || host === "[::1]";
|
|
15
|
+
export async function resolveServer(code, env = process.env, fetchImpl = fetch) {
|
|
16
|
+
const base = (env.WALKIE_RENDEZVOUS_URL || DEFAULT_RENDEZVOUS_URL).replace(/\/+$/, "");
|
|
17
|
+
let res;
|
|
18
|
+
try {
|
|
19
|
+
res = await fetchImpl(`${base}/v1/rendezvous/${lookupKey(code)}`, { signal: AbortSignal.timeout(8_000), redirect: "error" });
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new Error("could not look the code up. Use the long form instead: walkie join <server-url> <code>");
|
|
23
|
+
}
|
|
24
|
+
if (res.status === 404)
|
|
25
|
+
throw new Error("code not found (mistyped, expired or already used)");
|
|
26
|
+
if (res.status === 429)
|
|
27
|
+
throw new Error("too many lookups from this address; wait a few minutes or use: walkie join <server-url> <code>");
|
|
28
|
+
if (!res.ok)
|
|
29
|
+
throw new Error(`lookup failed: HTTP ${res.status}. Use the long form instead: walkie join <server-url> <code>`);
|
|
30
|
+
const { url } = (await res.json());
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = new URL(String(url));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new Error("lookup returned something that is not a server address");
|
|
37
|
+
}
|
|
38
|
+
// The pair code is a credential: never send it anywhere but HTTPS (or this machine, for development).
|
|
39
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback(parsed.hostname)))
|
|
40
|
+
throw new Error(`refusing to pair over an insecure address (${parsed.origin})`);
|
|
41
|
+
if (parsed.username || parsed.password)
|
|
42
|
+
throw new Error("lookup returned an address with credentials in it");
|
|
43
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
|
|
44
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie report`: send evidence, a question or a status back to the
|
|
3
|
+
* person, optionally with files (screenshots, logs, diffs).
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { hostname } from "node:os";
|
|
7
|
+
import { basename, extname } from "node:path";
|
|
8
|
+
const MIME = {
|
|
9
|
+
png: "image/png",
|
|
10
|
+
jpg: "image/jpeg",
|
|
11
|
+
jpeg: "image/jpeg",
|
|
12
|
+
gif: "image/gif",
|
|
13
|
+
webp: "image/webp",
|
|
14
|
+
pdf: "application/pdf",
|
|
15
|
+
txt: "text/plain",
|
|
16
|
+
log: "text/plain",
|
|
17
|
+
md: "text/markdown",
|
|
18
|
+
json: "application/json",
|
|
19
|
+
csv: "text/csv",
|
|
20
|
+
diff: "text/plain",
|
|
21
|
+
patch: "text/plain",
|
|
22
|
+
};
|
|
23
|
+
/** Best guess at the current harness session id, for the Activity view. */
|
|
24
|
+
export function detectSessionId(env = process.env) {
|
|
25
|
+
return env.WALKIE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || env.CURSOR_SESSION_ID || hostname();
|
|
26
|
+
}
|
|
27
|
+
export async function sendReport(opts) {
|
|
28
|
+
const fd = new FormData();
|
|
29
|
+
fd.append("message", opts.message);
|
|
30
|
+
fd.append("kind", opts.kind ?? "status");
|
|
31
|
+
fd.append("sessionId", opts.sessionId ?? detectSessionId());
|
|
32
|
+
if (opts.postId)
|
|
33
|
+
fd.append("postId", opts.postId);
|
|
34
|
+
for (const path of opts.files ?? []) {
|
|
35
|
+
const name = basename(path);
|
|
36
|
+
const type = MIME[extname(name).slice(1).toLowerCase()] ?? "application/octet-stream";
|
|
37
|
+
const bytes = readFileSync(path);
|
|
38
|
+
fd.append("file", new File([new Uint8Array(bytes)], name, { type }));
|
|
39
|
+
}
|
|
40
|
+
const res = await (opts.fetchImpl ?? fetch)(new URL("/v1/reports", opts.url + "/"), {
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: { authorization: `Bearer ${opts.token}` },
|
|
43
|
+
body: fd,
|
|
44
|
+
});
|
|
45
|
+
if (!res.ok) {
|
|
46
|
+
let detail = "";
|
|
47
|
+
try {
|
|
48
|
+
const j = (await res.json());
|
|
49
|
+
detail = j.message ?? j.error ?? "";
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
/* ignore */
|
|
53
|
+
}
|
|
54
|
+
throw new Error(`report failed: HTTP ${res.status}${detail ? ` (${detail})` : ""}`);
|
|
55
|
+
}
|
|
56
|
+
return (await res.json());
|
|
57
|
+
}
|
package/dist/running.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What is already running on this machine? Used by `join` and `sync` to tell
|
|
3
|
+
* the person exactly which live sessions will see the bulletin now and which
|
|
4
|
+
* need one keystroke.
|
|
5
|
+
*/
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
export function detectRunning() {
|
|
8
|
+
const out = { claudeCode: 0, cursor: 0, codex: 0 };
|
|
9
|
+
let lines = [];
|
|
10
|
+
try {
|
|
11
|
+
// ps is available on macOS and Linux; on Windows this simply reports nothing.
|
|
12
|
+
lines = execFileSync("ps", ["-eo", "pid=,args="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n");
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
const self = String(process.pid);
|
|
18
|
+
for (const raw of lines) {
|
|
19
|
+
const line = raw.trim();
|
|
20
|
+
if (!line)
|
|
21
|
+
continue;
|
|
22
|
+
const [pid, ...rest] = line.split(/\s+/);
|
|
23
|
+
if (pid === self)
|
|
24
|
+
continue;
|
|
25
|
+
const args = rest.join(" ");
|
|
26
|
+
if (/(^|\/)claude(\s|$)/.test(args) && !/walkie-cli/.test(args))
|
|
27
|
+
out.claudeCode++;
|
|
28
|
+
else if (/cursor-agent|Cursor Helper \(Plugin\)|\/Cursor\.app\/Contents\/MacOS\/Cursor(\s|$)|(^|\/)cursor(\s|$)/i.test(args))
|
|
29
|
+
out.cursor++;
|
|
30
|
+
else if (/(^|\/)codex(\s|$)/.test(args))
|
|
31
|
+
out.codex++;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/** Human guidance for sessions that were already open when the hook was installed. */
|
|
36
|
+
export function liveSessionNotes(r, installed) {
|
|
37
|
+
const notes = [];
|
|
38
|
+
if (r.claudeCode > 0) {
|
|
39
|
+
notes.push(`${r.claudeCode} Claude Code session${r.claudeCode === 1 ? " is" : "s are"} already running. ` +
|
|
40
|
+
(installed.claude
|
|
41
|
+
? "Nothing to do: Claude Code picks up the hook change automatically, and the bulletin arrives on the next prompt in each session. (If your organisation blocks config changes, /clear once.)"
|
|
42
|
+
: "Run `walkie install claude` in that project; open sessions pick it up on their next prompt."));
|
|
43
|
+
}
|
|
44
|
+
if (r.cursor > 0)
|
|
45
|
+
notes.push(`${r.cursor} Cursor process${r.cursor === 1 ? "" : "es"} running: ${installed.cursorRule ? "the always-on rule file is written, so open chats see the bulletin on their next message." : "run `walkie sync` in the project to write the rule file; no restart needed."}`);
|
|
46
|
+
if (r.codex > 0)
|
|
47
|
+
notes.push(`${r.codex} Codex session${r.codex === 1 ? "" : "s"} running: ${installed.agentsMd ? "AGENTS.md is updated; it is read on the next turn in most setups." : "run `walkie sync` to write the AGENTS.md block."}`);
|
|
48
|
+
if (notes.length === 0)
|
|
49
|
+
notes.push("No agent sessions detected right now. New ones pick the bulletin up automatically.");
|
|
50
|
+
return notes;
|
|
51
|
+
}
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export async function consumeSse(opts) {
|
|
2
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
3
|
+
const status = opts.onStatus ?? (() => { });
|
|
4
|
+
let lastEventId = opts.lastEventId;
|
|
5
|
+
let backoff = 1000;
|
|
6
|
+
const maxBackoff = opts.maxBackoffMs ?? 30_000;
|
|
7
|
+
while (!opts.signal?.aborted) {
|
|
8
|
+
try {
|
|
9
|
+
const headers = { accept: "text/event-stream", ...(opts.headers ?? {}) };
|
|
10
|
+
if (lastEventId)
|
|
11
|
+
headers["last-event-id"] = lastEventId;
|
|
12
|
+
const res = await fetchImpl(opts.url, { headers, signal: opts.signal });
|
|
13
|
+
if (!res.ok || !res.body)
|
|
14
|
+
throw new Error(`HTTP ${res.status}`);
|
|
15
|
+
status(`connected${lastEventId ? ` (resuming from ${lastEventId})` : ""}`);
|
|
16
|
+
backoff = 1000;
|
|
17
|
+
const reader = res.body.getReader();
|
|
18
|
+
const decoder = new TextDecoder();
|
|
19
|
+
let buffer = "";
|
|
20
|
+
let cur = { event: "message", data: [] };
|
|
21
|
+
const flush = async () => {
|
|
22
|
+
if (cur.data.length === 0 && !cur.id) {
|
|
23
|
+
cur = { event: "message", data: [] };
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (cur.id)
|
|
27
|
+
lastEventId = cur.id;
|
|
28
|
+
const ev = { event: cur.event, data: cur.data.join("\n"), id: cur.id };
|
|
29
|
+
cur = { event: "message", data: [] };
|
|
30
|
+
await opts.onEvent(ev);
|
|
31
|
+
};
|
|
32
|
+
for (;;) {
|
|
33
|
+
const { value, done } = await reader.read();
|
|
34
|
+
if (done)
|
|
35
|
+
break;
|
|
36
|
+
buffer += decoder.decode(value, { stream: true });
|
|
37
|
+
let nl;
|
|
38
|
+
while ((nl = buffer.indexOf("\n")) !== -1) {
|
|
39
|
+
const line = buffer.slice(0, nl).replace(/\r$/, "");
|
|
40
|
+
buffer = buffer.slice(nl + 1);
|
|
41
|
+
if (line === "") {
|
|
42
|
+
await flush();
|
|
43
|
+
}
|
|
44
|
+
else if (line.startsWith(":")) {
|
|
45
|
+
/* comment / keepalive */
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
const colon = line.indexOf(":");
|
|
49
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
50
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
51
|
+
if (field === "event")
|
|
52
|
+
cur.event = value;
|
|
53
|
+
else if (field === "data")
|
|
54
|
+
cur.data.push(value);
|
|
55
|
+
else if (field === "id")
|
|
56
|
+
cur.id = value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
status("stream ended by server");
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (opts.signal?.aborted)
|
|
64
|
+
return;
|
|
65
|
+
status(`disconnected: ${e instanceof Error ? e.message : String(e)}`);
|
|
66
|
+
}
|
|
67
|
+
if (opts.signal?.aborted)
|
|
68
|
+
return;
|
|
69
|
+
status(`reconnecting in ${Math.round(backoff / 1000)}s`);
|
|
70
|
+
await new Promise((r) => {
|
|
71
|
+
const t = setTimeout(r, backoff);
|
|
72
|
+
opts.signal?.addEventListener("abort", () => {
|
|
73
|
+
clearTimeout(t);
|
|
74
|
+
r();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
backoff = Math.min(maxBackoff, backoff * 2);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `walkie webhook-server`: turn any machine with a reachable port into
|
|
3
|
+
* a webhook recipient without writing code. Verifies Standard Webhooks
|
|
4
|
+
* signatures, dedupes by webhook-id, then runs the configured actions.
|
|
5
|
+
*/
|
|
6
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
import { runActions } from "./actions.js";
|
|
9
|
+
export const TOLERANCE_SECONDS = 300;
|
|
10
|
+
export function verifySignature(secret, headers, body, now = new Date()) {
|
|
11
|
+
const { id, timestamp, signature } = headers;
|
|
12
|
+
const ts = Number(timestamp);
|
|
13
|
+
if (!id || !Number.isFinite(ts) || !signature)
|
|
14
|
+
return { ok: false, reason: "missing signature headers" };
|
|
15
|
+
if (Math.abs(Math.floor(now.getTime() / 1000) - ts) > TOLERANCE_SECONDS)
|
|
16
|
+
return { ok: false, reason: "timestamp outside tolerance" };
|
|
17
|
+
const key = Buffer.from(secret.startsWith("whsec_") ? secret.slice(6) : secret, "base64");
|
|
18
|
+
const expected = createHmac("sha256", key).update(`${id}.${ts}.${body}`).digest();
|
|
19
|
+
for (const candidate of signature.split(" ")) {
|
|
20
|
+
const [v, value] = candidate.split(",");
|
|
21
|
+
if (v !== "v1" || !value)
|
|
22
|
+
continue;
|
|
23
|
+
const got = Buffer.from(value, "base64");
|
|
24
|
+
if (got.length === expected.length && timingSafeEqual(got, expected))
|
|
25
|
+
return { ok: true };
|
|
26
|
+
}
|
|
27
|
+
return { ok: false, reason: "no matching signature" };
|
|
28
|
+
}
|
|
29
|
+
function readBody(req) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
let data = "";
|
|
32
|
+
req.setEncoding("utf8");
|
|
33
|
+
req.on("data", (c) => (data += c));
|
|
34
|
+
req.on("end", () => resolve(data));
|
|
35
|
+
req.on("error", reject);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export function createWebhookServer(opts) {
|
|
39
|
+
const log = opts.log ?? (() => { });
|
|
40
|
+
const path = opts.path ?? "/";
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
const remember = (id) => {
|
|
43
|
+
seen.add(id);
|
|
44
|
+
if (seen.size > 2000)
|
|
45
|
+
seen.delete(seen.values().next().value);
|
|
46
|
+
};
|
|
47
|
+
return createServer(async (req, res) => {
|
|
48
|
+
if (req.method === "GET" && (req.url === "/healthz" || req.url === path)) {
|
|
49
|
+
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true, path }));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (req.method !== "POST" || !req.url?.startsWith(path)) {
|
|
53
|
+
res.writeHead(404).end();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const body = await readBody(req);
|
|
57
|
+
const h = {
|
|
58
|
+
id: String(req.headers["webhook-id"] ?? ""),
|
|
59
|
+
timestamp: String(req.headers["webhook-timestamp"] ?? ""),
|
|
60
|
+
signature: String(req.headers["webhook-signature"] ?? ""),
|
|
61
|
+
};
|
|
62
|
+
if (!opts.insecure) {
|
|
63
|
+
const ok = opts.secrets.some((s) => verifySignature(s, h, body).ok);
|
|
64
|
+
if (!ok) {
|
|
65
|
+
log(`rejected ${h.id || "(no id)"}: bad signature`);
|
|
66
|
+
res.writeHead(401).end("invalid signature");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (h.id && seen.has(h.id)) {
|
|
71
|
+
res.writeHead(200).end("duplicate");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
let payload;
|
|
75
|
+
try {
|
|
76
|
+
payload = JSON.parse(body);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
res.writeHead(400).end("invalid json");
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const ev = {
|
|
83
|
+
type: payload.type ?? String(req.headers["x-walkie-event"] ?? "unknown"),
|
|
84
|
+
id: payload.id ?? h.id,
|
|
85
|
+
bulletin: payload.bulletin ?? { slug: "", name: "" },
|
|
86
|
+
post: payload.post ?? null,
|
|
87
|
+
markdown: payload.markdown ?? "",
|
|
88
|
+
receivedAt: new Date().toISOString(),
|
|
89
|
+
};
|
|
90
|
+
try {
|
|
91
|
+
await runActions(ev, { ...opts, log });
|
|
92
|
+
if (h.id)
|
|
93
|
+
remember(h.id);
|
|
94
|
+
res.writeHead(200).end("ok");
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
// Non-2xx makes the server retry on its schedule.
|
|
98
|
+
log(`action failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
99
|
+
res.writeHead(500).end("action failed");
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
}
|