instantping 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/README.md +58 -2
- package/ccn.mjs +411 -0
- package/package.json +16 -4
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# instantping
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Companion for the **InstantPing** phone app (https://instantping.app): a ping on your phone when Claude Code is done or needs you. Needs Node 18+.
|
|
4
|
+
|
|
5
|
+
## With the InstantPing app
|
|
6
|
+
1. Run `npx instantping setup` in a terminal on the computer where you use Claude Code. It adds the hooks and shows a 6-character code.
|
|
7
|
+
2. Type the code in the InstantPing app on your phone.
|
|
8
|
+
3. Restart Claude Code. Remove again: `npx instantping uninstall`.
|
|
9
|
+
|
|
10
|
+
## Without the app (ntfy, for teammates)
|
|
11
|
+
|
|
12
|
+
Push to your phone when Claude Code is done or needs you. iPhone + Android (ntfy app), computer: Windows, macOS, Linux. Needs Node 18+.
|
|
13
|
+
|
|
14
|
+
## Setup (each person, on their own computer)
|
|
15
|
+
1. `git clone <this repo>` and `cd` into it
|
|
16
|
+
2. `node ccn.mjs setup` (makes your own secret topic + adds the hooks, with a backup of settings.json)
|
|
17
|
+
3. Install the **ntfy** app, subscribe to the topic it printed (or open the `ntfy://` link on your phone)
|
|
18
|
+
4. `node ccn.mjs test`
|
|
19
|
+
|
|
20
|
+
## Rules
|
|
21
|
+
- **Never share your topic.** On ntfy.sh the topic name is the password. Teammates run `setup` themselves and get their own.
|
|
22
|
+
- Pushes carry only Claude's own message. Folder name is added with `CCN_INCLUDE_PROJECT=1`.
|
|
23
|
+
- Don't want the public ntfy.sh? Self-host ntfy and put its URL in `server` in `~/.ccn.json`.
|
|
24
|
+
- Remove: `node ccn.mjs uninstall`
|
|
25
|
+
|
|
26
|
+
## Popups on your computer
|
|
27
|
+
The hook also shows a popup on the computer itself (Windows toast, macOS notification, Linux notify-send). Phone push is optional.
|
|
28
|
+
- Popup only: skip `init`, no topic needed.
|
|
29
|
+
- Phone only: add `"desktop": false` to `~/.ccn.json`.
|
|
30
|
+
|
|
31
|
+
## The topic
|
|
32
|
+
`ccn.mjs` makes a long random topic and shows it in a box (`node ccn.mjs topic` shows it again and copies it). The phone must subscribe to exactly that name; it is not a name you choose.
|
|
33
|
+
|
|
34
|
+
## Too many notifications?
|
|
35
|
+
Background tools such as the claude-mem plugin run hidden Claude sessions whose Stop hook fires every few seconds. ccn ignores sessions whose folder contains `.claude-mem` and sends at most one "done" push per 30 seconds (permission requests always pass). Add more folder fragments in `~/.ccn.json`: `"ignore": [".claude-mem", "my-tool"]`.
|
|
36
|
+
|
|
37
|
+
## Windows popup sender
|
|
38
|
+
Popups appear as an app called "Claude Notifier" (registered per user under HKCU\Software\Classes\AppUserModelId\ClaudeNotifier). Toasts sent as "Windows PowerShell" were silently dropped on some PCs. If you see nothing, check the bell next to the clock: a bell with "zZ" is Do not disturb.
|
|
39
|
+
|
|
40
|
+
## The hook waits for the popup
|
|
41
|
+
A popup process left running in the background is killed when the hook process exits (measured on Windows: the toast never showed). So `ccn hook` waits for the popup, in parallel with the phone push. Expect each hook to take about 3-4 seconds on Windows.
|
|
42
|
+
|
|
43
|
+
## One-command install
|
|
44
|
+
The guide's single command installs Node.js if missing (winget on Windows, Homebrew on Mac), saves `ccn.mjs`, runs `setup`, and in a real terminal waits for you to subscribe your phone before sending a test (`setup` skips the wait when there is no terminal).
|
|
45
|
+
|
|
46
|
+
## Phone settings (InstantPing app)
|
|
47
|
+
With the phone app the user chooses, in the app, and the relay follows it: minimum task time ("Quiet for short tasks"), pause, quiet hours (own time zone, "waiting" may still pass), which pings (done / waiting), language, details (project + closing sentence; off by default), and the sound per ping type (Android channels `done` and `waiting`). Two of them the computer must follow itself, so the relay returns them with every event and the hook caches them in `relayPrefs` in `~/.ccn.json`: `delay` (wait N seconds first; the ping is dropped if the user sent a new prompt or Claude finished meanwhile, done by a detached `ccn delayed` process) and `detail`/`lang`. A setting made in the app wins over the same one in `~/.ccn.json`. Ceiling: clicking "Allow" on a permission prompt at the computer does not cancel a delayed "waiting" ping, because no hook fires for it.
|
|
48
|
+
|
|
49
|
+
## Settings (~/.ccn.json)
|
|
50
|
+
Change them with `node ccn.mjs config <key> <value>` (for example `config minSeconds 30`), or with `npx instantping config ...` from the npm package. `config` alone shows the current values.
|
|
51
|
+
- `minSeconds` (default 15): "klaar" only for tasks longer than this. A `UserPromptSubmit` hook records when a task starts. `0` = every task.
|
|
52
|
+
- `phoneDetail` (default false): popup shows project + Claude's closing sentence; the phone push stays generic unless this is true.
|
|
53
|
+
- `desktop` (default true), `sound` (popup sound, default true), `delay` (seconds, default 0), `lang` (`en` default, `nl`, `es`, `fr`, `de`, `pt`, `ko`, `ja`), `name` (shown in phone pings; for several computers; `setup` asks for it, and a name set in the app wins), `ignore` (default `[".claude-mem"]`).
|
|
54
|
+
- Mute one project: `ccn mute <folder name>` (`mute .` = this folder, `unmute <name>`, `mute` lists). A muted name matches a whole folder name, not part of one.
|
|
55
|
+
- `ccn config` shows everything, including what the phone has set.
|
|
56
|
+
- Skipped automatically: subagent notifications (`agent_id`), `stop_hook_active` loops, the "waiting for your input" idle reminder.
|
|
57
|
+
- Mute: empty file `~/.ccn-muted`, or `CCN_DISABLE=1` for one shell.
|
|
58
|
+
|
|
59
|
+
Ideas taken from github.com/ashmitb95/claude-notifier (GPL-3.0, no code copied): minimum task duration, closing sentence in the popup, subagent suppression, mute switches. Not taken: `PermissionRequest`/`AskUserQuestion` hooks, because those block Claude until the hook exits and our Windows popup takes 3-4 seconds.
|
package/ccn.mjs
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// claude-notifier: push to your phone (ntfy app, iOS + Android) when Claude Code is done or needs you.
|
|
3
|
+
// Runs on Windows, macOS and Linux (needs Node 18+). No dependencies.
|
|
4
|
+
// node ccn.mjs setup init + test + install in one go (what a teammate runs)
|
|
5
|
+
// node ccn.mjs init make YOUR OWN secret topic, print how to subscribe
|
|
6
|
+
// node ccn.mjs topic show your topic again (and copy it)
|
|
7
|
+
// node ccn.mjs test send a test push
|
|
8
|
+
// node ccn.mjs install add the hooks to ~/.claude/settings.json (backup made)
|
|
9
|
+
// node ccn.mjs uninstall remove them again
|
|
10
|
+
// node ccn.mjs pair link this computer to the phone app (Pro relay): shows a code, type it in the app
|
|
11
|
+
// node ccn.mjs config show or change settings, e.g. config minSeconds 30 (also: delay, lang, name, sound, desktop, phoneDetail)
|
|
12
|
+
// node ccn.mjs mute mute a project by folder name (mute <name>, mute . for this folder, unmute <name>)
|
|
13
|
+
// node ccn.mjs hook what the hooks run (reads Claude's JSON on stdin)
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import crypto from "node:crypto";
|
|
18
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
|
|
21
|
+
const CONF = path.join(os.homedir(), ".ccn.json");
|
|
22
|
+
const SETTINGS = path.join(os.homedir(), ".claude", "settings.json");
|
|
23
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
24
|
+
const MARK = "ccn.mjs"; // how we recognise our own hooks
|
|
25
|
+
const DEFAULT_RELAY = "https://relay.instantping.app";
|
|
26
|
+
// Run from npm/npx? Then SELF lives in a cache that can vanish, so the hooks point to a stable copy instead.
|
|
27
|
+
const PKG = SELF.includes(path.sep + "node_modules" + path.sep);
|
|
28
|
+
const STABLE = path.join(os.homedir(), ".instantping", "ccn.mjs");
|
|
29
|
+
|
|
30
|
+
const load = () => { try { return JSON.parse(fs.readFileSync(CONF, "utf8")); } catch { return null; } };
|
|
31
|
+
|
|
32
|
+
const clamp = (s, n) => (s.length > n ? s.slice(0, n - 3) + "..." : s);
|
|
33
|
+
|
|
34
|
+
// Last sentence of Claude's reply, stripped of markdown: tells you at a glance what "done" means.
|
|
35
|
+
export function closing(text = "") {
|
|
36
|
+
const t = String(text).replace(/```[\s\S]*?```/g, " ").replace(/`([^`]*)`/g, "$1").replace(/[*_#>]+/g, " ").replace(/\s+/g, " ").trim();
|
|
37
|
+
if (!t) return "";
|
|
38
|
+
const last = (t.match(/[^.!?]+[.!?]*/g) || [t]).map((x) => x.trim()).filter(Boolean).pop() || t;
|
|
39
|
+
return clamp(last, 140);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Pure: hook payload -> message. rich = project name + Claude's closing sentence, for the popup on this computer.
|
|
43
|
+
// The phone push stays generic unless details are on (set in the app, or "phoneDetail": true here), because its text travels through our relay.
|
|
44
|
+
const TEXT = {
|
|
45
|
+
en: { done: ["Claude is done", "Waiting for your next instruction."], waiting: ["Claude is waiting", "Claude needs you."] },
|
|
46
|
+
nl: { done: ["Claude is klaar", "Wacht op je volgende instructie."], waiting: ["Claude wacht op jou", "Claude heeft je nodig."] },
|
|
47
|
+
es: { done: ["Claude ha terminado", "Esperando tu siguiente instrucción."], waiting: ["Claude está esperando", "Claude te necesita."] },
|
|
48
|
+
fr: { done: ["Claude a terminé", "En attente de votre prochaine instruction."], waiting: ["Claude attend", "Claude a besoin de vous."] },
|
|
49
|
+
de: { done: ["Claude ist fertig", "Wartet auf deine nächste Anweisung."], waiting: ["Claude wartet", "Claude braucht dich."] },
|
|
50
|
+
pt: { done: ["Claude terminou", "Aguardando sua próxima instrução."], waiting: ["Claude está esperando", "Claude precisa de você."] },
|
|
51
|
+
ko: { done: ["Claude가 작업을 마쳤어요", "다음 지시를 기다리고 있어요."], waiting: ["Claude가 기다리고 있어요", "Claude에게 당신이 필요해요."] },
|
|
52
|
+
ja: { done: ["Claudeが完了しました", "次の指示をお待ちしています。"], waiting: ["Claudeが待っています", "Claudeはあなたを必要としています。"] },
|
|
53
|
+
};
|
|
54
|
+
export function format(p, rich = false, lang = "en", name = "") {
|
|
55
|
+
const project = p.cwd ? path.basename(p.cwd) : "";
|
|
56
|
+
const where = (rich ? [name, project] : []).filter(Boolean).map((x) => x + " · ").join("");
|
|
57
|
+
const T = Object.hasOwn(TEXT, lang) ? TEXT[lang] : TEXT.en;
|
|
58
|
+
if (p.hook_event_name === "Stop") {
|
|
59
|
+
const sentence = rich ? closing(p.last_assistant_message) : "";
|
|
60
|
+
return { title: `${where}${T.done[0]}`, body: sentence || T.done[1], priority: 3, tags: "white_check_mark" };
|
|
61
|
+
}
|
|
62
|
+
return { title: `${where}${T.waiting[0]}`, body: p.message || T.waiting[1], priority: 4, tags: "bell" };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Muted on purpose: the file ~/.ccn-muted exists, or CCN_DISABLE is set (to anything but empty, 0 or false) in this shell.
|
|
66
|
+
export function disabled(env = process.env, muteFile = path.join(os.homedir(), ".ccn-muted")) {
|
|
67
|
+
const v = String(env.CCN_DISABLE ?? "").toLowerCase();
|
|
68
|
+
return (v !== "" && v !== "0" && v !== "false") || fs.existsSync(muteFile);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Pure: should this hook payload notify? Returns null for yes, or the reason it is skipped.
|
|
72
|
+
export function skipReason(p, conf, now, startedAt) {
|
|
73
|
+
if (ignored(p, conf.ignore)) return "background session";
|
|
74
|
+
if (p.agent_id) return "subagent";
|
|
75
|
+
if (p.hook_event_name === "Stop") {
|
|
76
|
+
if (p.stop_hook_active) return "stop-hook loop guard";
|
|
77
|
+
const min = (conf.minSeconds ?? 15) * 1000; // 0 = notify for every task
|
|
78
|
+
if (min > 0 && startedAt != null && now - startedAt < min) return "task shorter than minSeconds";
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (p.hook_event_name === "Notification") return /waiting for your input/i.test(p.message || "") ? "idle reminder" : null;
|
|
82
|
+
return "not a notifying event";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// When did this session's current task start? UserPromptSubmit writes the time; Stop reads it. Unknown = notify.
|
|
86
|
+
const TASKS = path.join(os.tmpdir(), "ccn-task");
|
|
87
|
+
const marker = (id) => path.join(TASKS, String(id || "anon").replace(/[^A-Za-z0-9._-]/g, "") + ".txt");
|
|
88
|
+
function recordStart(id) { try { fs.mkdirSync(TASKS, { recursive: true }); fs.writeFileSync(marker(id), String(Date.now())); } catch { /* best effort */ } }
|
|
89
|
+
function startedAt(id) { try { return Number(fs.readFileSync(marker(id), "utf8")) || null; } catch { return null; } }
|
|
90
|
+
|
|
91
|
+
// Settings a user may change with `ccn config <key> <value>`. Everything else in ~/.ccn.json is internal.
|
|
92
|
+
// A setting chosen in the phone app wins over the same one here (the computer caches it in relayPrefs).
|
|
93
|
+
const SETTING_TYPES = { minSeconds: "number", delay: "number", phoneDetail: "boolean", desktop: "boolean", sound: "boolean", lang: ["en", "nl", "es", "fr", "de", "pt", "ko", "ja"], name: "string" };
|
|
94
|
+
const MAX = { minSeconds: 3600, delay: 600 };
|
|
95
|
+
export function parseSetting(key, raw) {
|
|
96
|
+
const type = SETTING_TYPES[key];
|
|
97
|
+
if (!type) throw new Error(`unknown setting "${key}". Use: ${Object.keys(SETTING_TYPES).join(", ")}`);
|
|
98
|
+
const s = String(raw ?? "").trim();
|
|
99
|
+
if (type === "number") {
|
|
100
|
+
const n = Number(s);
|
|
101
|
+
if (s === "" || !Number.isFinite(n) || n < 0 || n > MAX[key]) throw new Error(`${key} needs a number of seconds from 0 to ${MAX[key]}`);
|
|
102
|
+
return n;
|
|
103
|
+
}
|
|
104
|
+
if (type === "string") { if (s.length > 40) throw new Error(`${key} is at most 40 characters`); return s; } // empty = clear
|
|
105
|
+
if (Array.isArray(type)) { if (!type.includes(s)) throw new Error(`${key} must be one of: ${type.join(", ")}`); return s; }
|
|
106
|
+
if (/^(true|on|yes)$/i.test(s)) return true;
|
|
107
|
+
if (/^(false|off|no)$/i.test(s)) return false;
|
|
108
|
+
throw new Error(`${key} needs on or off`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const act = (id) => path.join(TASKS, "act-" + String(id || "anon").replace(/[^A-Za-z0-9._-]/g, "") + ".txt");
|
|
112
|
+
function touch(id) { const t = Date.now(); try { fs.mkdirSync(TASKS, { recursive: true }); fs.writeFileSync(act(id), String(t)); } catch { /* best effort */ } return t; }
|
|
113
|
+
const lastActivity = (id) => { try { return Number(fs.readFileSync(act(id), "utf8")) || 0; } catch { return 0; } };
|
|
114
|
+
|
|
115
|
+
// Background sessions are not you waiting. claude-mem runs a hidden Claude session that ends a "turn" every few
|
|
116
|
+
// seconds; its Stop hook would notify you all day. Skip any session whose folder contains one of these fragments.
|
|
117
|
+
export function ignored(p, patterns = [".claude-mem"]) {
|
|
118
|
+
const cwd = (p.cwd || "").split("\\").join("/") + "/"; // trailing slash: a muted "/name/" also matches a cwd that ends in name
|
|
119
|
+
return patterns.some((x) => cwd.includes(x.split("\\").join("/")));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Safety net for any other automated session: at most one "done" notification per 10 seconds. Permission requests always pass.
|
|
123
|
+
function throttled(p) {
|
|
124
|
+
if (p.hook_event_name !== "Stop") return false;
|
|
125
|
+
const f = path.join(os.tmpdir(), "ccn-last-stop");
|
|
126
|
+
let last = 0; try { last = fs.statSync(f).mtimeMs; } catch { /* first time */ }
|
|
127
|
+
if (Date.now() - last < 10000) return true;
|
|
128
|
+
fs.writeFileSync(f, "");
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function push(conf, m) {
|
|
133
|
+
const r = await fetch(`${conf.server}/${conf.topic}`, {
|
|
134
|
+
method: "POST",
|
|
135
|
+
// headers must be latin1; the title is encoded as RFC 2047 so emoji/accents survive
|
|
136
|
+
headers: { Title: `=?UTF-8?B?${Buffer.from(m.title).toString("base64")}?=`, Priority: String(m.priority), Tags: m.tags },
|
|
137
|
+
body: m.body,
|
|
138
|
+
});
|
|
139
|
+
if (!r.ok) throw new Error(`ntfy ${r.status}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Desktop popup on this computer. No dependencies: PowerShell toast (Windows), osascript (macOS), notify-send (Linux).
|
|
143
|
+
// Text goes through env vars, never into the command line, so quotes in Claude's message cannot break it.
|
|
144
|
+
function desktop(m) {
|
|
145
|
+
const env = { ...process.env, CCN_T: m.title, CCN_B: m.body, CCN_S: m.silent ? "1" : "" };
|
|
146
|
+
let cmd, args;
|
|
147
|
+
if (process.platform === "win32") {
|
|
148
|
+
// Own sender name "Claude Notifier", registered per user (HKCU, no admin). Toasts sent as "Windows PowerShell"
|
|
149
|
+
// were silently dropped on some PCs; a registered app of our own shows up in Windows notification settings and works.
|
|
150
|
+
cmd = "powershell.exe";
|
|
151
|
+
args = ["-NoProfile", "-NonInteractive", "-Command", [
|
|
152
|
+
"$id = 'ClaudeNotifier'",
|
|
153
|
+
"$k = 'HKCU:\\Software\\Classes\\AppUserModelId\\' + $id",
|
|
154
|
+
"if (-not (Test-Path $k)) { New-Item $k -Force | Out-Null }",
|
|
155
|
+
"New-ItemProperty $k -Name DisplayName -Value 'InstantPing' -PropertyType String -Force | Out-Null",
|
|
156
|
+
"New-ItemProperty $k -Name ShowInSettings -Value 1 -PropertyType DWord -Force | Out-Null",
|
|
157
|
+
"[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
|
|
158
|
+
"$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent(1)",
|
|
159
|
+
"$t = $x.GetElementsByTagName('text')",
|
|
160
|
+
"[void]$t.Item(0).AppendChild($x.CreateTextNode($env:CCN_T))",
|
|
161
|
+
"[void]$t.Item(1).AppendChild($x.CreateTextNode($env:CCN_B))",
|
|
162
|
+
"if ($env:CCN_S -eq '1') { $a = $x.CreateElement('audio'); $a.SetAttribute('silent','true'); [void]$x.DocumentElement.AppendChild($a) }",
|
|
163
|
+
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($id).Show([Windows.UI.Notifications.ToastNotification]::new($x))",
|
|
164
|
+
// Show() hands the toast to Windows asynchronously; leaving at once can drop it, so linger briefly.
|
|
165
|
+
"Start-Sleep -Seconds 3",
|
|
166
|
+
].join("; ")];
|
|
167
|
+
} else if (process.platform === "darwin") {
|
|
168
|
+
cmd = "osascript";
|
|
169
|
+
args = ["-e", 'display notification (system attribute "CCN_B") with title (system attribute "CCN_T")' + (m.silent ? "" : ' sound name "Glass"')];
|
|
170
|
+
} else {
|
|
171
|
+
cmd = "notify-send";
|
|
172
|
+
args = [m.title, m.body];
|
|
173
|
+
}
|
|
174
|
+
// Wait for the popup tool to finish. A popup started in the background and left behind is killed when this process
|
|
175
|
+
// exits (measured on Windows: the toast never appeared), so the hook must stay alive until it is done.
|
|
176
|
+
// Runs next to the phone push, so the wait is the slower of the two, not the sum. A missing tool is ignored.
|
|
177
|
+
return new Promise((resolve) => {
|
|
178
|
+
const c = spawn(cmd, args, { env, stdio: "ignore", windowsHide: true });
|
|
179
|
+
c.on("error", resolve);
|
|
180
|
+
c.on("exit", resolve);
|
|
181
|
+
setTimeout(resolve, 8000).unref();
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Pro relay: push through our own relay to the phone app (conf.relay = base URL, conf.relayKey = this computer's key).
|
|
186
|
+
// The relay applies the phone's own settings (pause, quiet hours, minimum task time...) and answers with the ones this computer must follow itself.
|
|
187
|
+
async function pushRelay(conf, kind, m, seconds, rich) {
|
|
188
|
+
const r = await fetch(`${conf.relay}/v1/events`, {
|
|
189
|
+
method: "POST",
|
|
190
|
+
headers: { authorization: "Bearer " + conf.relayKey, "content-type": "application/json" },
|
|
191
|
+
body: JSON.stringify({ kind, title: m.title, body: m.body, seconds, minSeconds: conf.minSeconds ?? 15, rich, computer: conf.name || undefined }),
|
|
192
|
+
signal: AbortSignal.timeout(8000),
|
|
193
|
+
});
|
|
194
|
+
if (!r.ok) throw new Error(`relay ${r.status}`);
|
|
195
|
+
const { prefs } = await r.json().catch(() => ({}));
|
|
196
|
+
if (prefs && JSON.stringify(prefs) !== JSON.stringify(conf.relayPrefs ?? {})) cachePrefs(prefs);
|
|
197
|
+
}
|
|
198
|
+
function cachePrefs(prefs) {
|
|
199
|
+
try { const c = load() ?? {}; c.relayPrefs = prefs; fs.writeFileSync(CONF, JSON.stringify(c, null, 2), { mode: 0o600 }); } catch { /* best effort */ }
|
|
200
|
+
}
|
|
201
|
+
async function phoneSettings(conf) {
|
|
202
|
+
try {
|
|
203
|
+
const r = await fetch(`${conf.relay}/v1/prefs`, { method: "POST", headers: { authorization: "Bearer " + conf.relayKey, "content-type": "application/json" }, body: "{}", signal: AbortSignal.timeout(5000) });
|
|
204
|
+
return r.ok ? await r.json() : null;
|
|
205
|
+
} catch { return null; }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Popup + phone for one event. short = shorter than our minSeconds: then only the relay hears about it, because the phone may want it.
|
|
209
|
+
async function route(conf, p, secs, short) {
|
|
210
|
+
const prefs = conf.relayPrefs ?? {};
|
|
211
|
+
const lang = prefs.lang ?? conf.lang ?? "en";
|
|
212
|
+
const detail = prefs.detail ?? conf.phoneDetail === true; // phone setting wins; details are opt-in
|
|
213
|
+
const local = { ...format(p, true, lang), silent: conf.sound === false };
|
|
214
|
+
const phone = detail ? format(p, true, lang, conf.name) : format(p, false, lang);
|
|
215
|
+
await Promise.allSettled([
|
|
216
|
+
!short && conf.desktop !== false && (conf.detach === false ? desktop(local) : detach(local)),
|
|
217
|
+
!short && conf.topic && push(conf, phone),
|
|
218
|
+
conf.relayKey && pushRelay(conf, p.hook_event_name === "Stop" ? "done" : "waiting", phone, secs, detail),
|
|
219
|
+
]);
|
|
220
|
+
}
|
|
221
|
+
// Same, but after N seconds, and only if you did not act in the meantime (new prompt, or Claude finished). Runs in its own process.
|
|
222
|
+
function later(j) {
|
|
223
|
+
try { spawn(process.execPath, [SELF, "delayed"], { env: { ...process.env, CCN_DELAYED: JSON.stringify(j) }, detached: true, stdio: "ignore", windowsHide: true }).unref(); } catch { /* best effort */ }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Pairing: ask the relay for a code, show it, wait until the phone app has claimed it, store the key.
|
|
227
|
+
async function pair(relay) {
|
|
228
|
+
const post = await fetch(`${relay}/v1/pair/start`, { method: "POST" });
|
|
229
|
+
if (!post.ok) throw new Error(`relay ${post.status}`);
|
|
230
|
+
const { code, pairId, expiresIn } = await post.json();
|
|
231
|
+
console.log(`
|
|
232
|
+
Pairing code: ${code}
|
|
233
|
+
Type it in the phone app within ${Math.round(expiresIn / 60)} minutes. Waiting...`);
|
|
234
|
+
for (let i = 0; i < expiresIn / 2; i++) {
|
|
235
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
236
|
+
const r = await fetch(`${relay}/v1/pair/${pairId}`);
|
|
237
|
+
if (!r.ok) break;
|
|
238
|
+
const p = await r.json();
|
|
239
|
+
if (p.status === "paired") {
|
|
240
|
+
const conf = load() ?? { server: "https://ntfy.sh" };
|
|
241
|
+
fs.writeFileSync(CONF, JSON.stringify({ ...conf, relay, relayKey: p.key }, null, 2), { mode: 0o600 });
|
|
242
|
+
return console.log("Paired. This computer now pushes through the relay.");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
console.error("Code expired. Run pair again.");
|
|
246
|
+
process.exit(1);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Start `ccn popup` as a separate process that outlives this hook; the hook does not wait for it.
|
|
250
|
+
function detach(m) {
|
|
251
|
+
try {
|
|
252
|
+
spawn(process.execPath, [SELF, "popup"], { env: { ...process.env, CCN_POPUP: JSON.stringify(m) }, detached: true, stdio: "ignore", windowsHide: true }).unref();
|
|
253
|
+
} catch { /* popup is best effort */ }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Show the topic so nobody mistakes it for a name they may pick, and put it on the clipboard (best effort).
|
|
257
|
+
function showTopic(conf) {
|
|
258
|
+
const clip = process.platform === "win32" ? ["clip"] : process.platform === "darwin" ? ["pbcopy"] : ["xclip", "-selection", "clipboard"];
|
|
259
|
+
const copied = spawnSync(clip[0], clip.slice(1), { input: conf.topic, stdio: ["pipe", "ignore", "ignore"] }).status === 0;
|
|
260
|
+
const bar = "=".repeat(64);
|
|
261
|
+
console.log(`\n${bar}\n YOUR TOPIC. Type it in the ntfy app EXACTLY like this:\n\n ${conf.topic}\n\n This is NOT a name you choose. This computer was given this exact\n name, and your phone must use the same one, letter for letter.\n${copied ? " It is already copied. On this computer you can paste it with Ctrl+V.\n" : ""}${bar}\n`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Ask one line in a real terminal; empty answer = def. No terminal: def is not used, nothing is asked.
|
|
265
|
+
function askLine(msg) {
|
|
266
|
+
if (!process.stdin.isTTY) return Promise.resolve(null);
|
|
267
|
+
process.stdout.write(msg);
|
|
268
|
+
return new Promise((r) => process.stdin.once("data", (d) => { process.stdin.pause(); r(String(d).trim()); }));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Wait for Enter in a real terminal; do nothing when there is none (scripts, tests, hooks).
|
|
272
|
+
function pause(msg) {
|
|
273
|
+
if (!process.stdin.isTTY) return Promise.resolve();
|
|
274
|
+
process.stdout.write(msg);
|
|
275
|
+
return new Promise((r) => process.stdin.once("data", () => { process.stdin.pause(); r(); }));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const cmd = process.argv[2];
|
|
279
|
+
const isMain = process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF); // realpath: npx starts us through a symlink on macOS/Linux
|
|
280
|
+
if (isMain) {
|
|
281
|
+
if (cmd === "setup" && PKG) {
|
|
282
|
+
// Customer flow (npx instantping setup): hooks + pairing with the phone app. No ntfy.
|
|
283
|
+
const r = spawnSync(process.execPath, [SELF, "install"], { stdio: "inherit" }); if (r.status) process.exit(r.status);
|
|
284
|
+
// A name tells your computers apart in the app and in the pings. Only sent if you accept or type one.
|
|
285
|
+
const conf0 = load() ?? {};
|
|
286
|
+
if (conf0.name === undefined) {
|
|
287
|
+
const host = os.hostname();
|
|
288
|
+
const a = await askLine(`\nName this computer, so you can tell your pings apart (Enter = "${host}", - = no name): `);
|
|
289
|
+
if (a !== null && a !== "-") fs.writeFileSync(CONF, JSON.stringify({ ...conf0, name: (a || host).slice(0, 40) }, null, 2), { mode: 0o600 });
|
|
290
|
+
}
|
|
291
|
+
console.log("\nOpen the InstantPing app on your phone; it asks for the code below.");
|
|
292
|
+
await pair(load()?.relay || DEFAULT_RELAY);
|
|
293
|
+
console.log("All set. Close Claude Code and open it again, so it loads the new hooks.");
|
|
294
|
+
} else if (cmd === "setup") {
|
|
295
|
+
for (const c of ["init", "install"]) { const r = spawnSync(process.execPath, [SELF, c], { stdio: "inherit" }); if (r.status) process.exit(r.status); }
|
|
296
|
+
await pause("\nNow subscribe your phone in the ntfy app (tap +, paste the topic above, tap Subscribe).\nThen come back to this window and press Enter: I will send a test popup and a test push.\nNo phone? Just press Enter.\n> ");
|
|
297
|
+
spawnSync(process.execPath, [SELF, "test"], { stdio: "inherit" });
|
|
298
|
+
console.log("\nAll set. Close Claude Code and open it again, so it loads the new hooks.");
|
|
299
|
+
} else if (cmd === "init") {
|
|
300
|
+
const conf = load() ?? { server: "https://ntfy.sh", topic: "ccn-" + crypto.randomBytes(12).toString("hex") };
|
|
301
|
+
fs.writeFileSync(CONF, JSON.stringify(conf, null, 2));
|
|
302
|
+
console.log(`Topic: ${conf.topic}\nServer: ${conf.server}`);
|
|
303
|
+
showTopic(conf);
|
|
304
|
+
console.log(`In the ntfy app: tap +, enter the topic above, keep the server ntfy.sh, tap Subscribe.\nOr open this link on your phone: ntfy://${new URL(conf.server).host}/${conf.topic}\nThe topic is your password: never share it, every person needs their own.`);
|
|
305
|
+
} else if (cmd === "topic") {
|
|
306
|
+
const conf = load();
|
|
307
|
+
if (conf?.topic) showTopic(conf); else console.log("No topic yet. Run: node ccn.mjs init");
|
|
308
|
+
} else if (cmd === "test") {
|
|
309
|
+
const conf = load() ?? {};
|
|
310
|
+
const m = { title: "InstantPing works", body: "Test notification.", priority: 3, tags: "tada" };
|
|
311
|
+
const [, phone] = await Promise.allSettled([conf.desktop !== false && desktop(m), conf.topic && push(conf, m)]);
|
|
312
|
+
if (phone.status === "rejected") { console.error("Phone push failed: " + phone.reason.message + " (check your internet connection)"); process.exit(1); }
|
|
313
|
+
console.log(conf.topic ? "Sent: popup on this computer + push to your phone." : "Popup sent. No phone topic yet: run init to add phone push.");
|
|
314
|
+
} else if (cmd === "install" || cmd === "uninstall") {
|
|
315
|
+
let s = {}; try { s = JSON.parse(fs.readFileSync(SETTINGS, "utf8")); } catch { /* new file */ }
|
|
316
|
+
if (fs.existsSync(SETTINGS)) fs.copyFileSync(SETTINGS, SETTINGS + ".ccn-backup");
|
|
317
|
+
s.hooks ??= {};
|
|
318
|
+
// Remove our hooks everywhere first (idempotent, also cleans up older installs), then add them back.
|
|
319
|
+
for (const ev of Object.keys(s.hooks)) {
|
|
320
|
+
s.hooks[ev] = s.hooks[ev].filter((g) => !JSON.stringify(g).includes(MARK));
|
|
321
|
+
if (!s.hooks[ev].length) delete s.hooks[ev];
|
|
322
|
+
}
|
|
323
|
+
// UserPromptSubmit only records when a task started (for minSeconds); it never notifies.
|
|
324
|
+
let target = SELF;
|
|
325
|
+
if (cmd === "install" && PKG) { fs.mkdirSync(path.dirname(STABLE), { recursive: true }); fs.copyFileSync(SELF, STABLE); target = STABLE; }
|
|
326
|
+
if (cmd === "install") for (const ev of ["Stop", "Notification", "UserPromptSubmit"]) (s.hooks[ev] ??= []).push({ hooks: [{ type: "command", command: `node "${target.replaceAll("\\", "/")}" hook` }] });
|
|
327
|
+
fs.mkdirSync(path.dirname(SETTINGS), { recursive: true });
|
|
328
|
+
fs.writeFileSync(SETTINGS, JSON.stringify(s, null, 2));
|
|
329
|
+
console.log(`${cmd}ed hooks in ${SETTINGS} (backup: settings.json.ccn-backup)`);
|
|
330
|
+
} else if (cmd === "pair") {
|
|
331
|
+
const relay = process.argv[3] || load()?.relay || DEFAULT_RELAY;
|
|
332
|
+
await pair(relay.replace(/\/$/, ""));
|
|
333
|
+
} else if (cmd === "config") {
|
|
334
|
+
// node ccn.mjs config show settings
|
|
335
|
+
// node ccn.mjs config minSeconds 30 only announce tasks longer than 30 s (0 = every task)
|
|
336
|
+
const [key, value] = process.argv.slice(3);
|
|
337
|
+
let conf = load() ?? {};
|
|
338
|
+
if (key) {
|
|
339
|
+
try { const v = parseSetting(key, value); if (v === "") delete conf[key]; else conf[key] = v; } catch (e) { console.error(e.message); process.exit(1); }
|
|
340
|
+
fs.writeFileSync(CONF, JSON.stringify(conf, null, 2));
|
|
341
|
+
}
|
|
342
|
+
const on = (v, d = true) => ((v ?? d) ? "on" : "off");
|
|
343
|
+
console.log(`This computer (${CONF}):
|
|
344
|
+
minSeconds ${conf.minSeconds ?? 15}${conf.minSeconds === undefined ? " (default)" : ""} only tasks longer than this get a "done" ping; 0 = every task
|
|
345
|
+
delay ${conf.delay ?? 0} wait this many seconds first; no ping if you act in the meantime
|
|
346
|
+
lang ${conf.lang ?? "en"} en, nl, es, fr, de, pt, ko or ja
|
|
347
|
+
name ${conf.name || "(none)"} shown in phone pings, for people with several computers
|
|
348
|
+
desktop ${on(conf.desktop)} popup on this computer
|
|
349
|
+
sound ${on(conf.sound)} popup sound
|
|
350
|
+
phoneDetail ${on(conf.phoneDetail, false)} project name and Claude's last sentence on the phone
|
|
351
|
+
muted ${(conf.ignore ?? [".claude-mem"]).join(", ") || "(none)"} change with: mute <folder name>`);
|
|
352
|
+
if (conf.relayKey) {
|
|
353
|
+
const ph = await phoneSettings(conf);
|
|
354
|
+
if (ph) {
|
|
355
|
+
cachePrefs(ph.prefs);
|
|
356
|
+
const s = ph.settings, q = s.quiet;
|
|
357
|
+
console.log(`Phone (set in the app, wins over the above):
|
|
358
|
+
minSeconds ${s.minSeconds ?? "(not set)"}, delay ${s.delay}, lang ${s.lang}, details ${on(s.detail)}
|
|
359
|
+
pings: done ${on(s.kinds.done)}, waiting ${on(s.kinds.waiting)}
|
|
360
|
+
quiet hours ${q.enabled ? `${q.from}-${q.to} (${q.tz})${q.waitingPasses ? ", waiting still pings" : ""}` : "off"}
|
|
361
|
+
${s.pausedUntil > Date.now() ? "paused until " + new Date(s.pausedUntil).toLocaleString() : "not paused"}`);
|
|
362
|
+
} else console.log("(Could not reach the relay to read the phone settings.)");
|
|
363
|
+
}
|
|
364
|
+
} else if (cmd === "mute" || cmd === "unmute") {
|
|
365
|
+
// node ccn.mjs mute my-project | mute . (this folder) | unmute my-project | mute (list)
|
|
366
|
+
const conf = load() ?? {};
|
|
367
|
+
let list = conf.ignore ?? [".claude-mem"];
|
|
368
|
+
let name = process.argv[3];
|
|
369
|
+
if (name === ".") name = path.basename(process.cwd());
|
|
370
|
+
if (name) {
|
|
371
|
+
const frag = "/" + path.basename(name) + "/";
|
|
372
|
+
list = cmd === "mute" ? [...new Set([...list, frag])] : list.filter((x) => x !== frag);
|
|
373
|
+
conf.ignore = list;
|
|
374
|
+
fs.writeFileSync(CONF, JSON.stringify(conf, null, 2));
|
|
375
|
+
}
|
|
376
|
+
console.log("Muted projects: " + (list.join(", ") || "(none)"));
|
|
377
|
+
} else if (cmd === "delayed") {
|
|
378
|
+
try {
|
|
379
|
+
const j = JSON.parse(process.env.CCN_DELAYED || "{}");
|
|
380
|
+
await new Promise((r) => setTimeout(r, j.delay * 1000));
|
|
381
|
+
if (lastActivity(j.p.session_id) <= j.at && !disabled()) await route(load() ?? {}, j.p, j.secs, j.short);
|
|
382
|
+
} catch { /* ignore */ }
|
|
383
|
+
} else if (cmd === "popup") {
|
|
384
|
+
try { await desktop(JSON.parse(process.env.CCN_POPUP || "{}")); } catch { /* ignore */ }
|
|
385
|
+
} else if (cmd === "hook") {
|
|
386
|
+
// Never break Claude: any failure is swallowed, exit 0.
|
|
387
|
+
// Popup on this computer by default; phone push only when a topic exists. "desktop": false in ~/.ccn.json turns the popup off.
|
|
388
|
+
try {
|
|
389
|
+
const conf = load() ?? {};
|
|
390
|
+
const p = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
|
|
391
|
+
if (!disabled()) {
|
|
392
|
+
const now = Date.now();
|
|
393
|
+
if (p.hook_event_name === "UserPromptSubmit") { recordStart(p.session_id); touch(p.session_id); }
|
|
394
|
+
else {
|
|
395
|
+
const at = p.hook_event_name === "Stop" ? touch(p.session_id) : now; // a finished task counts as activity: it cancels an older delayed "waiting" ping
|
|
396
|
+
const st = startedAt(p.session_id);
|
|
397
|
+
if (!skipReason(p, { ...conf, minSeconds: 0 }, now, st) && !throttled(p)) {
|
|
398
|
+
// Everything but the duration check passed. A short task still goes to the relay (the phone may want it); popup and ntfy follow our minSeconds.
|
|
399
|
+
const secs = st == null ? undefined : Math.round((now - st) / 1000);
|
|
400
|
+
const short = skipReason(p, conf, now, st) !== null;
|
|
401
|
+
const delay = conf.relayPrefs?.delay ?? conf.delay ?? 0;
|
|
402
|
+
if (delay > 0) later({ delay, at, secs, short, p: { hook_event_name: p.hook_event_name, session_id: p.session_id, cwd: p.cwd, message: p.message, last_assistant_message: clamp(String(p.last_assistant_message ?? ""), 600) } });
|
|
403
|
+
else await route(conf, p, secs, short);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
} catch { /* ignore */ }
|
|
408
|
+
} else {
|
|
409
|
+
console.log("usage: node ccn.mjs setup|init|topic|test|install|uninstall|pair|config|mute|unmute|hook");
|
|
410
|
+
}
|
|
411
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "instantping",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Phone push when Claude Code is done or needs you. Companion for the InstantPing app.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"instantping": "ccn.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"ccn.mjs",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=18"
|
|
15
|
+
},
|
|
16
|
+
"license": "UNLICENSED",
|
|
17
|
+
"homepage": "https://instantping.app"
|
|
18
|
+
}
|