@pingroom/cli 0.7.2 → 0.7.4
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 +54 -12
- package/bin/pingroom.js +22 -3016
- package/lib/commands/ask.js +146 -0
- package/lib/commands/config.js +114 -0
- package/lib/commands/connect.js +726 -0
- package/lib/commands/handoff.js +149 -0
- package/lib/commands/hook.js +301 -0
- package/lib/commands/listen.js +83 -0
- package/lib/commands/live.js +166 -0
- package/lib/commands/mcp.js +47 -0
- package/lib/commands/ping.js +127 -0
- package/lib/config.js +206 -0
- package/lib/constants.js +14 -0
- package/lib/github-output.js +76 -0
- package/lib/help.js +310 -0
- package/lib/http.js +214 -0
- package/lib/parser.js +218 -0
- package/lib/render.js +174 -0
- package/lib/util.js +109 -0
- package/lib/version.js +10 -0
- package/package.json +3 -2
package/bin/pingroom.js
CHANGED
|
@@ -29,3023 +29,29 @@
|
|
|
29
29
|
//
|
|
30
30
|
// Exit codes: 0 success/answered/acked · 1 error · 2 bad usage · 3 expired ·
|
|
31
31
|
// 4 cancelled/recipient-not-ready.
|
|
32
|
-
|
|
33
|
-
import { randomBytes } from 'node:crypto';
|
|
34
|
-
import {
|
|
35
|
-
appendFileSync, chmodSync, closeSync, fchmodSync, mkdirSync, openSync,
|
|
36
|
-
readFileSync, renameSync, unlinkSync, writeFileSync,
|
|
37
|
-
} from 'node:fs';
|
|
38
|
-
import { homedir } from 'node:os';
|
|
39
|
-
import { join } from 'node:path';
|
|
40
|
-
|
|
41
|
-
// Kept in lockstep with package.json / package-lock.json. The GitHub Action is
|
|
42
|
-
// pinned independently to the latest version already published on npm; a test
|
|
43
|
-
// makes that release gate explicit. `hook --print-config` emits this candidate.
|
|
44
|
-
const VERSION = '0.7.2';
|
|
45
|
-
|
|
46
|
-
const BUILTIN_API = 'https://api.pingroom.io';
|
|
47
|
-
const MCP_ENDPOINT = `${BUILTIN_API}/api/agent/mcp`;
|
|
48
|
-
const DEFAULT_API = process.env.PINGROOM_API_URL || BUILTIN_API;
|
|
49
|
-
|
|
50
|
-
// The help text lives as one section per command plus intro/shared/tail, so
|
|
51
|
-
// `pingroom <command> --help` can print a focused excerpt (see commandHelp).
|
|
52
|
-
// The full HELP below joins them in the historical order — `pingroom --help`
|
|
53
|
-
// output is byte-identical to the pre-split single blob.
|
|
54
|
-
const HELP_INTRO = `pingroom — send a ping, or ask a human a question, from CI/scripts/agents
|
|
55
|
-
|
|
56
|
-
Usage:
|
|
57
|
-
pingroom <command> [options]
|
|
58
|
-
|
|
59
|
-
Commands:
|
|
60
|
-
ping Send a ping to a room (webhook URL, or agent token + room)
|
|
61
|
-
ask Ask a human a question; with --wait, block until they answer
|
|
62
|
-
watch Block until a question resolves and print the outcome
|
|
63
|
-
list List the agent's questions by state
|
|
64
|
-
cancel Withdraw a pending question
|
|
65
|
-
handoff Hand a decision (ack or question) to a specific human; with --wait,
|
|
66
|
-
block until they acknowledge or answer
|
|
67
|
-
handoffs List the agent's open handoffs or bounded recent history
|
|
68
|
-
listen Block on pings arriving in your rooms and print them as they land
|
|
69
|
-
live Drive a live progress card on the lock screen (Live Activity)
|
|
70
|
-
hook Claude Code hook: ping on Stop/Notification, and route tool
|
|
71
|
-
permission prompts to a PingRoom question you answer from your phone
|
|
72
|
-
mcp Print the remote MCP endpoint and setup for Claude Code, Cursor, and
|
|
73
|
-
Claude Desktop
|
|
74
|
-
activate Retry Agent Inbox activation with the saved QR-paired credential
|
|
75
|
-
config Read/write local settings (config list | get <key> | set <key> <val>)
|
|
76
|
-
logout Forget the stored credential`;
|
|
77
|
-
|
|
78
|
-
const HELP_PING = `ping options:
|
|
79
|
-
-m, --message <text> Ping body text (required)
|
|
80
|
-
-t, --title <text> Ping title (<= 40 chars)
|
|
81
|
-
-a, --action <1-4> Quick-action slot to attribute the ping to
|
|
82
|
-
-d, --data <json> Extra JSON data object, e.g. '{"commit":"abc123"}'
|
|
83
|
-
--url <https-url> Make the ping a tappable link (absolute http(s) URL)
|
|
84
|
-
--button-label <t> Link button text (<= 26 chars; requires --url)
|
|
85
|
-
--require-ack Keep the ping open until an eligible recipient acknowledges it
|
|
86
|
-
--ack-timeout <s> Ack deadline in seconds (requires --require-ack)
|
|
87
|
-
--attach <path> Attach a file (md/pdf/html/txt/jpg/jpeg/png, <= 5 MiB);
|
|
88
|
-
repeat for up to 4. Requires --token and a Pro account
|
|
89
|
-
-w, --webhook <url> Room webhook URL (or env PINGROOM_WEBHOOK_URL)
|
|
90
|
-
--token <token> Agent access token (or env PINGROOM_TOKEN)
|
|
91
|
-
--room <code> Room invite code (used with --token)`;
|
|
92
|
-
|
|
93
|
-
const HELP_ASK = `ask options (agent token required):
|
|
94
|
-
-p, --prompt <text> The question a human reads (required)
|
|
95
|
-
-o, --option <v:label[:style]>
|
|
96
|
-
An answer option (style: primary|danger|default);
|
|
97
|
-
repeat for 2–4. Omit for Approve/Deny
|
|
98
|
-
-c, --context <text> Secondary line, e.g. a build number (<= 40 chars)
|
|
99
|
-
--scope <s> Who answers: 'direct' (default) or 'room'
|
|
100
|
-
--target <uuid> For --scope direct: a specific room member
|
|
101
|
-
--ttl <seconds> Expiry; omit for the server default (1h; 30..86400)
|
|
102
|
-
--text-input <ph> Invite a short typed answer; <ph> is the placeholder
|
|
103
|
-
--text-max <n> Max typed-answer length (1..60)
|
|
104
|
-
--wait Block until answered/expired/cancelled
|
|
105
|
-
--timeout <sec> Per long-poll hold with --wait/watch (0–30, default 25)
|
|
106
|
-
-d, --data <json> Structured data object echoed back on the answer
|
|
107
|
-
--correlation-id <id> Opaque id echoed on every read of this question
|
|
108
|
-
--reply-to <id> Id of the ping this question replies to
|
|
109
|
-
--room <code> Room invite code (required for ask)`;
|
|
110
|
-
|
|
111
|
-
const HELP_LIST = `list options:
|
|
112
|
-
--state <s> pending | answered | expired | cancelled | all`;
|
|
113
|
-
|
|
114
|
-
const HELP_HANDOFF = `handoff options (agent token required; consent scope pingroom:handoffs:create):
|
|
115
|
-
-m, --message <text> The prompt a human reads (required)
|
|
116
|
-
--question Make it a question (else a simple acknowledge). Also
|
|
117
|
-
implied whenever one or more --option is given.
|
|
118
|
-
-o, --option <v:label> A question option; repeat for 2–4. Requires --question.
|
|
119
|
-
--target <id> Recipient: 'me' (default) or a specific user uuid
|
|
120
|
-
--expires-in <s> Expiry in seconds (120..86400, default 900)
|
|
121
|
-
--urgency <u> 'active' (default) or 'passive'
|
|
122
|
-
--idempotency-key <key> Dedupe key; retries reuse it (Idempotency-Key)
|
|
123
|
-
--correlation-id <id> Opaque id echoed on every read of this handoff
|
|
124
|
-
--reply-to <id> Opaque reply-to id echoed back
|
|
125
|
-
-d, --data <json> Structured data object echoed on the handoff
|
|
126
|
-
--wait Block until acked / answered / expired / cancelled
|
|
127
|
-
--timeout <sec> Per long-poll hold with --wait (0–20, server caps 25)
|
|
128
|
-
--github-output <path> Safely append handoff outputs for GitHub Actions`;
|
|
129
|
-
|
|
130
|
-
const HELP_HANDOFFS = `handoffs options (agent token required; consent scope pingroom:handoffs:create):
|
|
131
|
-
--state <s> open | all (default open)`;
|
|
132
|
-
|
|
133
|
-
const HELP_LISTEN = `listen options (agent token required; consent scope pingroom:notifications:read):
|
|
134
|
-
--timeout <sec> Per long-poll hold (0-30, default 25)
|
|
135
|
-
--limit <n> Max pings per batch (1-100, default 50)
|
|
136
|
-
--from <id> Start after this ping id instead of "now"
|
|
137
|
-
--once Print one batch and exit instead of blocking forever
|
|
138
|
-
--json One JSON object per line instead of a readable line`;
|
|
139
|
-
|
|
140
|
-
const HELP_LIVE = `live <start|update|end|get> options (agent token, or a room webhook):
|
|
141
|
-
-c, --correlation-id <id> The stream key — reuse it for every ping (required)
|
|
142
|
-
--template <name> start only: status | steps | progress | metrics |
|
|
143
|
-
countdown | decision | matchup (fixed at creation;
|
|
144
|
-
'decision' is the app's name for the wire id
|
|
145
|
-
'question', which is still accepted)
|
|
146
|
-
--category <name> start only: status | steps | alert. Legacy, but
|
|
147
|
-
'alert' has no template equivalent and is the only
|
|
148
|
-
way to start time-sensitive without --require-ack
|
|
149
|
-
--steps <a,b,c> start only: 2-8 comma-separated step labels
|
|
150
|
-
-m, --message <text> The card's live message line
|
|
151
|
-
--progress <0..1> Progress bar / Dynamic Island gauge
|
|
152
|
-
--step <n> Current step index (steps template)
|
|
153
|
-
--metric <label:value> Repeatable, up to 3 (metrics template)
|
|
154
|
-
--deadline-at <epoch> Countdown target (countdown template)
|
|
155
|
-
--eta-at <epoch> Live ETA (status/progress templates)
|
|
156
|
-
--prompt <text> The ask (decision template)
|
|
157
|
-
--option <value:label> Repeatable, up to 4 (decision template). A bare
|
|
158
|
-
token is both value and label
|
|
159
|
-
--left <label:value> Left side (matchup template)
|
|
160
|
-
--right <label:value> Right side (matchup template)
|
|
161
|
-
--center <text> Center score/clock, <= 40 (matchup template)
|
|
162
|
-
--accent-override <#rrggbb> Semantic accent for this frame
|
|
163
|
-
--failed end only: finish as failed instead of done
|
|
164
|
-
-d, --data <json> Structured data object carried on this frame
|
|
165
|
-
-t, --title <text> Card title (<= 40 chars)
|
|
166
|
-
-a, --action <1-4> Quick-action slot supplying the icon and sound
|
|
167
|
-
--require-ack Add an Acknowledge button
|
|
168
|
-
--ack-timeout <s> Ack deadline in seconds
|
|
169
|
-
--room <code> Room invite code (used with --token)
|
|
170
|
-
-w, --webhook <url> Room webhook URL instead of a token`;
|
|
171
|
-
|
|
172
|
-
const HELP_HOOK = `hook options (reads a Claude Code event; defaults to stored credentials/config):
|
|
173
|
-
--room <code> Room invite code (or env/config/paired room)
|
|
174
|
-
--ttl <seconds> Approval-question expiry for PreToolUse (default 900)
|
|
175
|
-
--quiet Suppress the informational stderr lines
|
|
176
|
-
--print-config Print a ready-to-paste ~/.claude/settings.json block`;
|
|
177
|
-
|
|
178
|
-
const HELP_MCP = `mcp:
|
|
179
|
-
pingroom mcp Print the endpoint and client setup snippets
|
|
180
|
-
pingroom mcp add claude-code Print the Claude Code setup command
|
|
181
|
-
(output-only; does not change client config)`;
|
|
182
|
-
|
|
183
|
-
const HELP_ACTIVATE = `activate:
|
|
184
|
-
pingroom activate Send one test Question to your phone to prove the
|
|
185
|
-
saved QR-paired credential works (optional —
|
|
186
|
-
connecting no longer does this for you)`;
|
|
187
|
-
|
|
188
|
-
const HELP_CONFIG = `config options:
|
|
189
|
-
pingroom config list Print the stored settings
|
|
190
|
-
pingroom config get <key> Print one setting
|
|
191
|
-
pingroom config set <key> <val> Store a setting (an empty value clears it)
|
|
192
|
-
Keys: default_room, api_url`;
|
|
193
|
-
|
|
194
|
-
const HELP_SHARED = `Shared:
|
|
195
|
-
--token <token> Agent access token (or env PINGROOM_TOKEN)
|
|
196
|
-
--api <url> API base URL (default ${DEFAULT_API}; env PINGROOM_API_URL)
|
|
197
|
-
--json Print the raw JSON response
|
|
198
|
-
-h, --help Show this help
|
|
199
|
-
-v, --version Show the CLI version`;
|
|
200
|
-
|
|
201
|
-
const HELP_TAIL = `Connecting:
|
|
202
|
-
Install globally, then run with no arguments:
|
|
203
|
-
npm install --global @pingroom/cli
|
|
204
|
-
pingroom
|
|
205
|
-
|
|
206
|
-
Or connect without installing globally:
|
|
207
|
-
npx --yes @pingroom/cli
|
|
208
|
-
|
|
209
|
-
It prints a QR code you scan with the PingRoom app — you pick the account and
|
|
210
|
-
the rooms it may reach there (one, several, or all of them). Once paired, it
|
|
211
|
-
saves the credential and you are done; connecting sends nothing to your phone.
|
|
212
|
-
Run "pingroom activate" if you want to prove the round-trip with one test
|
|
213
|
-
Question. The emailed-code fallback stores no server-side delivery room.
|
|
214
|
-
"config set default_room" enables room-addressed commands, but private
|
|
215
|
-
Inbox/Handoff delivery requires QR pairing.
|
|
216
|
-
There is no "login" command: being unconnected is a state the tool resolves,
|
|
217
|
-
not one you have to discover.
|
|
218
|
-
|
|
219
|
-
The credential is written to ~/.pingroom/credentials.json (mode 0600, in a
|
|
220
|
-
0700 directory). PINGROOM_HOME overrides that directory. PINGROOM_TOKEN in the
|
|
221
|
-
environment ALWAYS wins over the stored credential, so CI is unaffected.
|
|
222
|
-
"pingroom logout" forgets it.
|
|
223
|
-
|
|
224
|
-
Settings precedence, highest first:
|
|
225
|
-
explicit flag > env var > ~/.pingroom/config.json > the paired
|
|
226
|
-
credential > built-in default
|
|
227
|
-
So --room beats PINGROOM_ROOM beats "config set default_room", and --api beats
|
|
228
|
-
PINGROOM_API_URL beats "config set api_url" beats the host you paired against,
|
|
229
|
-
beats ${BUILTIN_API}. A stored credential is bound to the origin it was paired
|
|
230
|
-
against: an API override may change the path on that origin, but a different
|
|
231
|
-
origin is refused before the token is sent. To target another origin
|
|
232
|
-
intentionally, provide that host's token with --token or PINGROOM_TOKEN.
|
|
233
|
-
|
|
234
|
-
Non-interactive shells (CI, pipes) never prompt and never draw a QR: set
|
|
235
|
-
PINGROOM_TOKEN there instead.
|
|
236
|
-
|
|
237
|
-
Examples:
|
|
238
|
-
pingroom ping -w "$PINGROOM_WEBHOOK_URL" -m "Deploy succeeded ✅"
|
|
239
|
-
pingroom ping --token "$PINGROOM_TOKEN" --room ab12cd -m "Release shipped"
|
|
240
|
-
|
|
241
|
-
# Link ping — a tappable button that opens a URL:
|
|
242
|
-
pingroom ping -w "$PINGROOM_WEBHOOK_URL" -m "Build 512 ready" \\
|
|
243
|
-
--url https://ci.example.com/builds/512 --button-label "Open build"
|
|
244
|
-
|
|
245
|
-
# Gate a deploy on a human tap — the chosen value prints to stdout:
|
|
246
|
-
if [ "$(pingroom ask --token "$T" --room ab12cd --wait \\
|
|
247
|
-
-p 'Deploy 1.4.0 to production?')" = approve ]; then ./deploy.sh; fi
|
|
248
|
-
|
|
249
|
-
# Multi-option question, blocking:
|
|
250
|
-
pingroom ask --token "$T" --room ab12cd --scope room --wait \\
|
|
251
|
-
-p 'Which environment?' -o prod:Production -o staging:Staging
|
|
252
|
-
|
|
253
|
-
pingroom list --token "$T" --state pending
|
|
254
|
-
pingroom watch --token "$T" q_01H... # block on an existing question
|
|
255
|
-
pingroom cancel --token "$T" q_01H...
|
|
256
|
-
|
|
257
|
-
# Hand a deploy decision to yourself and block on the acknowledgement:
|
|
258
|
-
pingroom handoff --token "$T" -m "Prod deploy 1.4.0 — ack to proceed" --wait
|
|
259
|
-
|
|
260
|
-
# A blocking question handed to a specific human; branch in CI on exit code:
|
|
261
|
-
pingroom handoff --token "$T" -m "Ship 1.4.0?" --question \\
|
|
262
|
-
-o deploy:Deploy -o hold:Hold --wait
|
|
263
|
-
# -> exit 0 (answered, any value incl. 'hold'); 3 expired; 4 recipient-not-ready
|
|
264
|
-
|
|
265
|
-
pingroom handoffs --token "$T" --state all # recent history (up to 200/kind)
|
|
266
|
-
|
|
267
|
-
# A live deploy card on everyone's lock screen — one stream, three calls:
|
|
268
|
-
pingroom live start --token "$T" --room ab12cd -c "deploy-$GITHUB_RUN_ID" \\
|
|
269
|
-
--template steps --steps "Build,Test,Stage,Ship" -t "Deploy 2.1.0"
|
|
270
|
-
pingroom live update --token "$T" --room ab12cd -c "deploy-$GITHUB_RUN_ID" \\
|
|
271
|
-
--step 2 -m "Smoke tests green"
|
|
272
|
-
pingroom live end --token "$T" --room ab12cd -c "deploy-$GITHUB_RUN_ID" \\
|
|
273
|
-
-m "Live on production"
|
|
274
|
-
# ...or end it as a failure, which still delivers one completion alert:
|
|
275
|
-
# pingroom live end ... --failed -m "Rollback triggered"
|
|
276
|
-
|
|
277
|
-
# Connect Claude Code hooks to your paired credential (no env vars needed):
|
|
278
|
-
pingroom hook --print-config
|
|
279
|
-
|
|
280
|
-
# Connect an MCP client through browser OAuth (no API key needed):
|
|
281
|
-
pingroom mcp
|
|
282
|
-
|
|
283
|
-
Security:
|
|
284
|
-
Prefer the env vars (PINGROOM_WEBHOOK_URL / PINGROOM_TOKEN) over passing
|
|
285
|
-
secrets as --webhook / --token flags: argv is visible to other users via the
|
|
286
|
-
process table (ps) and may be captured in shell history. URLs must use https
|
|
287
|
-
(loopback http is allowed for local dev).
|
|
288
|
-
|
|
289
|
-
A paired credential is only sent to its recorded API origin. --api,
|
|
290
|
-
PINGROOM_API_URL and config.api_url cannot redirect that stored bearer to a
|
|
291
|
-
different origin; provide an explicit --token or PINGROOM_TOKEN to override.
|
|
292
|
-
|
|
293
|
-
Exit codes: 0 on success (answered / acked), 1 on error (network/auth/5xx),
|
|
294
|
-
2 on bad usage, 3 when a handoff or question expired, 4 when it was cancelled
|
|
295
|
-
or the recipient was not ready (409 recipient_not_ready). A question answered
|
|
296
|
-
with ANY value — including a negative one like 'hold' or 'deny' — exits 0: a
|
|
297
|
-
human decision is not an infrastructure failure.`;
|
|
298
|
-
|
|
299
|
-
const HELP = [
|
|
300
|
-
HELP_INTRO, HELP_PING, HELP_ASK, HELP_LIST, HELP_HANDOFF, HELP_HANDOFFS,
|
|
301
|
-
HELP_LISTEN, HELP_LIVE, HELP_HOOK, HELP_MCP, HELP_ACTIVATE, HELP_CONFIG,
|
|
302
|
-
HELP_SHARED, HELP_TAIL,
|
|
303
|
-
].join('\n\n');
|
|
304
|
-
|
|
305
|
-
// Sections for `pingroom <command> --help`. watch/cancel/logout have no block
|
|
306
|
-
// of their own in the full help, so they get a minimal one here.
|
|
307
|
-
const COMMAND_HELP_SECTIONS = {
|
|
308
|
-
ping: HELP_PING,
|
|
309
|
-
ask: HELP_ASK,
|
|
310
|
-
watch: `watch:
|
|
311
|
-
pingroom watch <question-id> Block until the question resolves and
|
|
312
|
-
print the outcome
|
|
313
|
-
--timeout <sec> Per long-poll hold (0–30, default 25)`,
|
|
314
|
-
cancel: `cancel:
|
|
315
|
-
pingroom cancel <question-id> Withdraw a pending question`,
|
|
316
|
-
list: HELP_LIST,
|
|
317
|
-
handoff: HELP_HANDOFF,
|
|
318
|
-
handoffs: HELP_HANDOFFS,
|
|
319
|
-
listen: HELP_LISTEN,
|
|
320
|
-
live: HELP_LIVE,
|
|
321
|
-
hook: HELP_HOOK,
|
|
322
|
-
activate: HELP_ACTIVATE,
|
|
323
|
-
config: HELP_CONFIG,
|
|
324
|
-
logout: `logout:
|
|
325
|
-
pingroom logout Forget the stored credential (PINGROOM_TOKEN
|
|
326
|
-
in the environment is unaffected)`,
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
// config and logout are local-only commands that reject --token/--api (and,
|
|
330
|
-
// for logout, --json), so their help gets a footer that only lists what they
|
|
331
|
-
// actually accept instead of the full shared block.
|
|
332
|
-
const COMMAND_HELP_FOOTERS = {
|
|
333
|
-
config: `Shared:
|
|
334
|
-
--json Print the raw JSON response
|
|
335
|
-
-h, --help Show this help`,
|
|
336
|
-
logout: `Shared:
|
|
337
|
-
-h, --help Show this help`,
|
|
338
|
-
};
|
|
339
|
-
|
|
340
|
-
// `<command> --help`: that command's section plus the shared flags, instead of
|
|
341
|
-
// the full reference `pingroom --help` / `pingroom help` still print.
|
|
342
|
-
function commandHelp(name) {
|
|
343
|
-
const section = COMMAND_HELP_SECTIONS[name];
|
|
344
|
-
return section ? `${section}\n\n${COMMAND_HELP_FOOTERS[name] ?? HELP_SHARED}` : HELP;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
const EXIT = { OK: 0, ERROR: 1, USAGE: 2, EXPIRED: 3, CANCELLED: 4 };
|
|
348
|
-
|
|
349
|
-
function fail(message, code = EXIT.ERROR) {
|
|
350
|
-
process.stderr.write(`pingroom: ${message}\n`);
|
|
351
|
-
process.exit(code);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* The fixes that live on THIS side of the wire. The server's message always
|
|
356
|
-
* leads; these are appended only for the codes where the operator would
|
|
357
|
-
* otherwise have no way to know what to do next, and where the answer is a
|
|
358
|
-
* local action rather than "try again".
|
|
359
|
-
*/
|
|
360
|
-
const API_HINTS = {
|
|
361
|
-
room_not_granted:
|
|
362
|
-
'That room is outside the grant this agent was given. Add it under Connected Agents in the PingRoom app, or run "pingroom" to reconnect and pick it.',
|
|
363
|
-
insufficient_scope:
|
|
364
|
-
'This credential was approved before the command needed that permission. Run "pingroom" to reconnect and re-approve.',
|
|
365
|
-
no_room_configured:
|
|
366
|
-
'This agent has no delivery room. Pick one under Connected Agents in the PingRoom app.',
|
|
367
|
-
};
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* What to print when an API call fails: the server's own wording, plus the one
|
|
371
|
-
* thing that would fix it when we know one.
|
|
372
|
-
*/
|
|
373
|
-
function apiDetail(res, json) {
|
|
374
|
-
// The server's wording is untrusted text headed for the terminal — strip
|
|
375
|
-
// escapes so a hostile API can't smuggle ANSI (same threat model as pair_url).
|
|
376
|
-
const base = stripControlChars(
|
|
377
|
-
(json && (json.message || json.error || json.code)) || `HTTP ${res ? res.status : 'error'}`,
|
|
378
|
-
);
|
|
379
|
-
const hint = json && typeof json.code === 'string' ? API_HINTS[json.code] : undefined;
|
|
380
|
-
return hint ? `${base}\n ${hint}` : base;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
// --- local state (~/.pingroom) ---------------------------------------------
|
|
384
|
-
//
|
|
385
|
-
// Two files, both under a 0700 directory:
|
|
386
|
-
// credentials.json the agent credential this machine paired (mode 0600)
|
|
387
|
-
// config.json user settings: default_room, api_url
|
|
388
|
-
//
|
|
389
|
-
// PINGROOM_HOME relocates the directory (tests, sandboxes, multi-account
|
|
390
|
-
// shells). Every lookup is layered: explicit flag > env var > config file >
|
|
391
|
-
// the paired credential > built-in default. PINGROOM_TOKEN is the one env var
|
|
392
|
-
// that also outranks the stored credential, which is what keeps CI working
|
|
393
|
-
// untouched.
|
|
394
|
-
|
|
395
|
-
function pingroomHome() {
|
|
396
|
-
return process.env.PINGROOM_HOME || join(homedir(), '.pingroom');
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
function credentialsPath() { return join(pingroomHome(), 'credentials.json'); }
|
|
400
|
-
function configPath() { return join(pingroomHome(), 'config.json'); }
|
|
401
|
-
|
|
402
|
-
// Read a JSON object, or null for anything unreadable/corrupt. Local state must
|
|
403
|
-
// never be able to crash a ping: a hand-edited file degrades to "not set".
|
|
404
|
-
function readJsonFile(path) {
|
|
405
|
-
let raw;
|
|
406
|
-
try { raw = readFileSync(path, 'utf8'); } catch { return null; }
|
|
407
|
-
let value;
|
|
408
|
-
try { value = JSON.parse(raw); } catch { return null; }
|
|
409
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
410
|
-
return value;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Write JSON with restrictive permissions, atomically.
|
|
414
|
-
//
|
|
415
|
-
// Writing in place truncates first, so a crash or a full disk between truncate
|
|
416
|
-
// and write leaves a half-written file — and readJsonFile() degrades anything
|
|
417
|
-
// unparseable to {}, so the *next* `config set` would silently drop every other
|
|
418
|
-
// setting. Writing a sibling temp file and renaming over the target means a
|
|
419
|
-
// reader only ever sees the old file or the new one, never a torn one.
|
|
420
|
-
//
|
|
421
|
-
// The temp file is opened 'wx' with mode 0600 and fchmod'd before a single byte
|
|
422
|
-
// is written: `mode` on an existing file is ignored and a post-write chmod
|
|
423
|
-
// leaves a window where the credential is world-readable. rename() carries the
|
|
424
|
-
// 0600 over the target, so a pre-existing loose file is tightened too.
|
|
425
|
-
//
|
|
426
|
-
// mkdirSync(recursive) returns the first path it created, or undefined when the
|
|
427
|
-
// directory already existed. chmod'ing only on the former keeps this from
|
|
428
|
-
// narrowing a directory the user deliberately created at 0755.
|
|
429
|
-
function writeJsonFile(path, value) {
|
|
430
|
-
const dir = pingroomHome();
|
|
431
|
-
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
432
|
-
let fd;
|
|
433
|
-
try {
|
|
434
|
-
const created = mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
435
|
-
if (created !== undefined) chmodSync(dir, 0o700);
|
|
436
|
-
|
|
437
|
-
fd = openSync(tmp, 'wx', 0o600);
|
|
438
|
-
fchmodSync(fd, 0o600); // defeat a permissive umask masking the open mode
|
|
439
|
-
writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`);
|
|
440
|
-
closeSync(fd);
|
|
441
|
-
fd = undefined;
|
|
442
|
-
renameSync(tmp, path);
|
|
443
|
-
} catch (err) {
|
|
444
|
-
if (fd !== undefined) { try { closeSync(fd); } catch { /* already gone */ } }
|
|
445
|
-
try { unlinkSync(tmp); } catch { /* never created */ }
|
|
446
|
-
fail(`could not write ${path}: ${err.message}`);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
function readStoredCredential() {
|
|
451
|
-
const cred = readJsonFile(credentialsPath());
|
|
452
|
-
if (!cred || typeof cred.token !== 'string' || cred.token === '') return null;
|
|
453
|
-
return cred;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
function readConfigFile() {
|
|
457
|
-
return readJsonFile(configPath()) || {};
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/** Agent token: --token > PINGROOM_TOKEN > the paired credential. */
|
|
461
|
-
function resolveToken(args) {
|
|
462
|
-
return args.token || process.env.PINGROOM_TOKEN || readStoredCredential()?.token || undefined;
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/**
|
|
466
|
-
* API base: --api > PINGROOM_API_URL > config.api_url > the host the credential
|
|
467
|
-
* was paired against > built-in, no trailing slash.
|
|
468
|
-
*
|
|
469
|
-
* The credential layer is not optional. saveCredential() records `api_url`, and
|
|
470
|
-
* a token minted by a self-hosted / staging server is only valid there; without
|
|
471
|
-
* this layer the next command would present that bearer to api.pingroom.io —
|
|
472
|
-
* leaking it to a host it was never issued for. resolveRoom() already consults
|
|
473
|
-
* the credential last, so the two layerings now agree.
|
|
474
|
-
*
|
|
475
|
-
* It is also an issuer boundary when resolveToken() falls through to the stored
|
|
476
|
-
* credential. Overrides may change the path on the same origin, but
|
|
477
|
-
* requireStoredCredentialOrigin() refuses a different origin unless the caller
|
|
478
|
-
* supplies an explicit --token or PINGROOM_TOKEN for that host.
|
|
479
|
-
*/
|
|
480
|
-
function resolveApiBase(args) {
|
|
481
|
-
const raw = args.api
|
|
482
|
-
|| process.env.PINGROOM_API_URL
|
|
483
|
-
|| readConfigFile().api_url
|
|
484
|
-
|| readStoredCredential()?.api_url
|
|
485
|
-
|| BUILTIN_API;
|
|
486
|
-
return String(raw).replace(/\/$/, '');
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/**
|
|
490
|
-
* A paired bearer belongs to the API origin that minted it. API settings still
|
|
491
|
-
* resolve independently so callers can select a path or an intentional custom
|
|
492
|
-
* host, but a stored token may only follow them within its recorded origin.
|
|
493
|
-
* Supplying --token / PINGROOM_TOKEN makes the token source explicit and opts
|
|
494
|
-
* out of this stored-credential binding.
|
|
495
|
-
*/
|
|
496
|
-
function storedCredentialOriginError(args, apiBase) {
|
|
497
|
-
if (args.token || process.env.PINGROOM_TOKEN) return null;
|
|
498
|
-
|
|
499
|
-
const credential = readStoredCredential();
|
|
500
|
-
if (!credential || typeof credential.api_url !== 'string' || credential.api_url === '') return null;
|
|
501
|
-
|
|
502
|
-
let credentialOrigin;
|
|
503
|
-
let targetOrigin;
|
|
504
|
-
try {
|
|
505
|
-
credentialOrigin = new URL(credential.api_url).origin;
|
|
506
|
-
targetOrigin = new URL(apiBase).origin;
|
|
507
|
-
} catch {
|
|
508
|
-
// URL validation owns malformed values. This guard only compares origins.
|
|
509
|
-
return null;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
if (credentialOrigin === targetOrigin) return null;
|
|
513
|
-
return `stored credential is bound to ${credentialOrigin}; refusing to send it to ${targetOrigin}. Provide --token or PINGROOM_TOKEN for an intentional API origin override`;
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
function requireStoredCredentialOrigin(args, apiBase) {
|
|
517
|
-
const error = storedCredentialOriginError(args, apiBase);
|
|
518
|
-
if (error) fail(error, EXIT.USAGE);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/**
|
|
522
|
-
* Room invite code: --room > PINGROOM_ROOM > config.default_room > the room the
|
|
523
|
-
* credential was paired to. The paired room is last because it is the weakest
|
|
524
|
-
* signal — it is where the agent was told to deliver, not necessarily where
|
|
525
|
-
* this invocation means to.
|
|
526
|
-
*/
|
|
527
|
-
function resolveRoom(args) {
|
|
528
|
-
return args.room
|
|
529
|
-
|| process.env.PINGROOM_ROOM
|
|
530
|
-
|| readConfigFile().default_room
|
|
531
|
-
|| readStoredCredential()?.room?.invite_code
|
|
532
|
-
|| undefined;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
/**
|
|
536
|
-
* True when it is safe to prompt / draw a QR. Both streams must be a TTY: a
|
|
537
|
-
* piped stdin cannot answer a prompt and a piped stdout would capture the QR as
|
|
538
|
-
* garbage.
|
|
539
|
-
*
|
|
540
|
-
* The override is deliberately double-locked (internal-looking name AND
|
|
541
|
-
* NODE_ENV=test) and not documented in --help. A single well-known env var
|
|
542
|
-
* shipping in the published binary is one stray `export` away from making a CI
|
|
543
|
-
* job prompt into the void and poll for the full 15-minute pairing window
|
|
544
|
-
* instead of failing in a second.
|
|
545
|
-
*/
|
|
546
|
-
function isInteractive() {
|
|
547
|
-
if (process.env.PINGROOM_INTERNAL_TEST_TTY === '1' && process.env.NODE_ENV === 'test') return true;
|
|
548
|
-
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
function sleep(ms) {
|
|
552
|
-
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// Drop C0/C1 control characters before echoing server-supplied text to the
|
|
556
|
-
// terminal. Without this an attacker-controlled API base can smuggle ANSI
|
|
557
|
-
// escapes into the output and repaint, erase or overwrite the lines around them.
|
|
558
|
-
/**
|
|
559
|
-
* Reject an over-long field here rather than letting it become a 422.
|
|
560
|
-
*
|
|
561
|
-
* Every bound mirrors a Laravel rule (StoreNotificationRequest,
|
|
562
|
-
* StoreQuestionRequest, LiveStatusRules) and is documented in --help, so a value
|
|
563
|
-
* past it was always going to be refused — locally it reads as the usage error
|
|
564
|
-
* it is, with the limit and the actual length named.
|
|
565
|
-
*/
|
|
566
|
-
function requireMaxLength(value, max, flag) {
|
|
567
|
-
if (typeof value === 'string' && value.length > max) {
|
|
568
|
-
fail(`${flag} must be at most ${max} characters (got ${value.length})`, EXIT.USAGE);
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Validate --timeout and resolve the per-poll hold. Called by ask/handoff
|
|
574
|
-
* BEFORE the create POST: the old in-wait check ran only after the question or
|
|
575
|
-
* handoff already existed, so `--timeout -5` put a live question on someone's
|
|
576
|
-
* phone and then exited 2, orphaning it until its TTL.
|
|
577
|
-
*/
|
|
578
|
-
function resolveWaitHold(args, { def, cap }) {
|
|
579
|
-
if (args.timeout === undefined) return Math.min(def, cap);
|
|
580
|
-
const hold = Number(args.timeout);
|
|
581
|
-
if (!Number.isFinite(hold) || hold < 0) fail('--timeout must be a non-negative integer', EXIT.USAGE);
|
|
582
|
-
return Math.min(hold, cap);
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
function stripControlChars(value) {
|
|
586
|
-
// eslint-disable-next-line no-control-regex
|
|
587
|
-
return String(value).replace(/[\u0000-\u001F\u007F-\u009F]/g, '');
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// --- argument parsing -------------------------------------------------------
|
|
591
|
-
|
|
592
|
-
/**
|
|
593
|
-
* Build an argv parser from a flag table. Every command parser runs the same
|
|
594
|
-
* loop; only the tables differ:
|
|
595
|
-
* aliases flag or alias -> canonical args key
|
|
596
|
-
* booleans keys that take no value
|
|
597
|
-
* repeatable keys collected into an array (the flag may repeat)
|
|
598
|
-
* bareDashIsPositional whether a lone `-` collects into `_` (the question-
|
|
599
|
-
* style parsers) or fails as an unknown option (ping,
|
|
600
|
-
* live)
|
|
601
|
-
* Unknown flags always fail as a usage error; bare words collect into `_`.
|
|
602
|
-
*/
|
|
603
|
-
function makeParser({ aliases, booleans, repeatable = [], bareDashIsPositional = false }) {
|
|
604
|
-
const booleanKeys = new Set(booleans);
|
|
605
|
-
const repeatableKeys = new Set(repeatable);
|
|
606
|
-
return function parse(argv) {
|
|
607
|
-
const args = { _: [] };
|
|
608
|
-
for (let i = 0; i < argv.length; i++) {
|
|
609
|
-
const token = argv[i];
|
|
610
|
-
// Object.hasOwn, not aliases[token]: a bare lookup walks the prototype
|
|
611
|
-
// chain, so `constructor` / `toString` / `__proto__` in flag position
|
|
612
|
-
// resolve to a truthy inherited value, get treated as an option, and
|
|
613
|
-
// swallow the next argument instead of failing as an unknown flag.
|
|
614
|
-
const key = Object.hasOwn(aliases, token) ? aliases[token] : undefined;
|
|
615
|
-
if (key && booleanKeys.has(key)) {
|
|
616
|
-
args[key] = true;
|
|
617
|
-
} else if (key) {
|
|
618
|
-
const value = argv[++i];
|
|
619
|
-
if (value === undefined) {
|
|
620
|
-
fail(`option ${token} needs a value`, EXIT.USAGE);
|
|
621
|
-
}
|
|
622
|
-
if (repeatableKeys.has(key)) (args[key] ||= []).push(value);
|
|
623
|
-
else args[key] = value;
|
|
624
|
-
} else if (token.startsWith('-') && !(bareDashIsPositional && token === '-')) {
|
|
625
|
-
fail(`Unknown option: ${token}`, EXIT.USAGE);
|
|
626
|
-
} else {
|
|
627
|
-
args._.push(token);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
return args;
|
|
631
|
-
};
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
// --- ping (unchanged wire behaviour) ---------------------------------------
|
|
635
|
-
|
|
636
|
-
const parseArgs = makeParser({
|
|
637
|
-
aliases: {
|
|
638
|
-
'-m': 'message', '--message': 'message',
|
|
639
|
-
'-t': 'title', '--title': 'title',
|
|
640
|
-
'-a': 'action', '--action': 'action',
|
|
641
|
-
'-d': 'data', '--data': 'data',
|
|
642
|
-
'-w': 'webhook', '--webhook': 'webhook',
|
|
643
|
-
'--url': 'url',
|
|
644
|
-
'--button-label': 'button_label',
|
|
645
|
-
'--require-ack': 'require_ack',
|
|
646
|
-
'--ack-timeout': 'ack_timeout',
|
|
647
|
-
'--attach': 'attach',
|
|
648
|
-
'--token': 'token',
|
|
649
|
-
'--room': 'room',
|
|
650
|
-
'--api': 'api',
|
|
651
|
-
'--json': 'json',
|
|
652
|
-
'-h': 'help', '--help': 'help',
|
|
653
|
-
},
|
|
654
|
-
booleans: ['require_ack', 'json', 'help'],
|
|
655
|
-
repeatable: ['attach'],
|
|
656
|
-
});
|
|
657
|
-
|
|
658
|
-
// Parser for the question commands: supports repeatable --option and a trailing
|
|
659
|
-
// positional (a question id). Unknown flags fail like the ping parser.
|
|
660
|
-
const parseQArgs = makeParser({
|
|
661
|
-
aliases: {
|
|
662
|
-
'-p': 'prompt', '--prompt': 'prompt',
|
|
663
|
-
'-o': 'option', '--option': 'option',
|
|
664
|
-
'-c': 'context', '--context': 'context',
|
|
665
|
-
'--scope': 'scope',
|
|
666
|
-
'--target': 'target',
|
|
667
|
-
'--ttl': 'ttl',
|
|
668
|
-
'-d': 'data', '--data': 'data',
|
|
669
|
-
'--correlation-id': 'correlation_id',
|
|
670
|
-
'--reply-to': 'reply_to',
|
|
671
|
-
'--text-input': 'text_input',
|
|
672
|
-
'--text-max': 'text_max',
|
|
673
|
-
'--timeout': 'timeout',
|
|
674
|
-
'--state': 'state',
|
|
675
|
-
'--limit': 'limit',
|
|
676
|
-
'--from': 'from',
|
|
677
|
-
'--once': 'once',
|
|
678
|
-
'--token': 'token',
|
|
679
|
-
'--room': 'room',
|
|
680
|
-
'--api': 'api',
|
|
681
|
-
'--wait': 'wait',
|
|
682
|
-
'--json': 'json',
|
|
683
|
-
'-h': 'help', '--help': 'help',
|
|
684
|
-
},
|
|
685
|
-
booleans: ['wait', 'json', 'help', 'once'],
|
|
686
|
-
repeatable: ['option'],
|
|
687
|
-
bareDashIsPositional: true,
|
|
688
|
-
});
|
|
689
|
-
|
|
690
|
-
// Parser for `handoff`: --message plus repeatable --option, boolean --question,
|
|
691
|
-
// and the handoff-specific flags. Unknown flags fail like the other parsers.
|
|
692
|
-
const parseHandoffArgs = makeParser({
|
|
693
|
-
aliases: {
|
|
694
|
-
'-m': 'message', '--message': 'message',
|
|
695
|
-
'--question': 'question',
|
|
696
|
-
'-o': 'option', '--option': 'option',
|
|
697
|
-
'--target': 'target',
|
|
698
|
-
'--expires-in': 'expires_in',
|
|
699
|
-
'--urgency': 'urgency',
|
|
700
|
-
'--idempotency-key': 'idempotency_key',
|
|
701
|
-
'--correlation-id': 'correlation_id',
|
|
702
|
-
'--reply-to': 'reply_to',
|
|
703
|
-
'-d': 'data', '--data': 'data',
|
|
704
|
-
'--timeout': 'timeout',
|
|
705
|
-
'--github-output': 'github_output',
|
|
706
|
-
'--token': 'token',
|
|
707
|
-
'--api': 'api',
|
|
708
|
-
'--wait': 'wait',
|
|
709
|
-
'--json': 'json',
|
|
710
|
-
'-h': 'help', '--help': 'help',
|
|
711
|
-
},
|
|
712
|
-
booleans: ['question', 'wait', 'json', 'help'],
|
|
713
|
-
repeatable: ['option'],
|
|
714
|
-
bareDashIsPositional: true,
|
|
715
|
-
});
|
|
716
|
-
|
|
717
|
-
// True when a URL is safe to attach a bearer token or webhook secret to: https,
|
|
718
|
-
// or http on loopback so local dev against http://localhost still works.
|
|
719
|
-
// Split out of requireSafeUrl for the `hook` command, which must apply the same
|
|
720
|
-
// rule but fails open (it defers instead of exiting — see hook()).
|
|
721
|
-
function isSafeUrl(raw) {
|
|
722
|
-
let u;
|
|
723
|
-
try {
|
|
724
|
-
u = new URL(raw);
|
|
725
|
-
} catch {
|
|
726
|
-
return false;
|
|
727
|
-
}
|
|
728
|
-
const isLoopback = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]';
|
|
729
|
-
return u.protocol === 'https:' || (u.protocol === 'http:' && isLoopback);
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
// Refuse to send a bearer token or webhook secret over cleartext http. A
|
|
733
|
-
// loopback host is allowed so local dev against http://localhost still works.
|
|
734
|
-
function requireSafeUrl(kind, raw) {
|
|
735
|
-
try {
|
|
736
|
-
new URL(raw);
|
|
737
|
-
} catch {
|
|
738
|
-
fail(`${kind} is not a valid URL`, EXIT.USAGE);
|
|
739
|
-
}
|
|
740
|
-
if (!isSafeUrl(raw)) {
|
|
741
|
-
fail(`${kind} must use https (refusing to send credentials over cleartext)`, EXIT.USAGE);
|
|
742
|
-
}
|
|
743
|
-
return raw;
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
function parseDataObject(raw) {
|
|
747
|
-
let data;
|
|
748
|
-
try {
|
|
749
|
-
data = JSON.parse(raw);
|
|
750
|
-
} catch {
|
|
751
|
-
fail('--data must be valid JSON', EXIT.USAGE);
|
|
752
|
-
}
|
|
753
|
-
if (typeof data !== 'object' || Array.isArray(data) || data === null) {
|
|
754
|
-
fail('--data must be a JSON object', EXIT.USAGE);
|
|
755
|
-
}
|
|
756
|
-
return data;
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
// `soft: true` returns { error } instead of exiting on a transport failure. The
|
|
760
|
-
// bounded pairing and activation loops use it so a single DNS blip or dropped
|
|
761
|
-
// connection does not discard an otherwise recoverable human workflow. Every
|
|
762
|
-
// other caller keeps the hard exit.
|
|
763
|
-
async function httpJson(method, url, { body, headers = {}, soft = false, signal } = {}) {
|
|
764
|
-
let res;
|
|
765
|
-
try {
|
|
766
|
-
res = await fetch(url, {
|
|
767
|
-
method,
|
|
768
|
-
headers: {
|
|
769
|
-
Accept: 'application/json',
|
|
770
|
-
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
771
|
-
...headers,
|
|
772
|
-
},
|
|
773
|
-
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
774
|
-
...(signal ? { signal } : {}),
|
|
775
|
-
});
|
|
776
|
-
} catch (err) {
|
|
777
|
-
if (soft) return { res: null, text: '', json: null, error: err };
|
|
778
|
-
fail(`network error: ${err.message}`);
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
let text;
|
|
782
|
-
try {
|
|
783
|
-
text = await res.text();
|
|
784
|
-
} catch (err) {
|
|
785
|
-
// A connection dropped mid-body throws here, not at fetch().
|
|
786
|
-
if (soft) return { res: null, text: '', json: null, error: err };
|
|
787
|
-
fail(`network error: ${err.message}`);
|
|
788
|
-
}
|
|
789
|
-
let json = null;
|
|
790
|
-
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON response */ }
|
|
791
|
-
|
|
792
|
-
return { res, text, json };
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
// The extensions the attachment endpoint accepts. Mirrored here so a typo is a
|
|
796
|
-
// local usage error instead of a 422 after the bytes have already been sent.
|
|
797
|
-
// Keep in lockstep with laravel config/attachments.php `allowed_extensions`.
|
|
798
|
-
const ATTACHMENT_EXTENSIONS = ['md', 'pdf', 'html', 'txt', 'jpg', 'jpeg', 'png'];
|
|
799
|
-
const ATTACHMENT_MAX_BYTES = 5 * 1024 * 1024;
|
|
800
|
-
const ATTACHMENT_MAX_COUNT = 4;
|
|
801
|
-
const ATTACHMENT_MIME = {
|
|
802
|
-
md: 'text/markdown',
|
|
803
|
-
pdf: 'application/pdf',
|
|
804
|
-
html: 'text/html',
|
|
805
|
-
txt: 'text/plain',
|
|
806
|
-
jpg: 'image/jpeg',
|
|
807
|
-
jpeg: 'image/jpeg',
|
|
808
|
-
png: 'image/png',
|
|
809
|
-
};
|
|
810
|
-
|
|
811
|
-
/**
|
|
812
|
-
* Upload each --attach path and return the ids in flag order. Bytes go up as
|
|
813
|
-
* multipart; only the resulting ids ride the ping body. An id we never manage
|
|
814
|
-
* to attach expires server-side after 24h, so a mid-run failure leaks nothing
|
|
815
|
-
* permanent.
|
|
816
|
-
*/
|
|
817
|
-
async function uploadAttachments(paths, apiBase, token) {
|
|
818
|
-
if (paths.length > ATTACHMENT_MAX_COUNT) {
|
|
819
|
-
fail(`--attach accepts at most ${ATTACHMENT_MAX_COUNT} files`, EXIT.USAGE);
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
const { readFile, stat } = await import('node:fs/promises');
|
|
823
|
-
const { basename, extname } = await import('node:path');
|
|
824
|
-
const ids = [];
|
|
825
|
-
|
|
826
|
-
for (const path of paths) {
|
|
827
|
-
const name = basename(path);
|
|
828
|
-
const ext = extname(name).slice(1).toLowerCase();
|
|
829
|
-
if (!ATTACHMENT_EXTENSIONS.includes(ext)) {
|
|
830
|
-
fail(`--attach ${name}: only ${ATTACHMENT_EXTENSIONS.join(', ')} files are supported`, EXIT.USAGE);
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
let info;
|
|
834
|
-
try {
|
|
835
|
-
info = await stat(path);
|
|
836
|
-
} catch {
|
|
837
|
-
fail(`--attach ${path}: file not found`, EXIT.USAGE);
|
|
838
|
-
}
|
|
839
|
-
if (!info.isFile()) fail(`--attach ${path}: not a file`, EXIT.USAGE);
|
|
840
|
-
if (info.size < 1) fail(`--attach ${name}: file is empty`, EXIT.USAGE);
|
|
841
|
-
if (info.size > ATTACHMENT_MAX_BYTES) {
|
|
842
|
-
fail(`--attach ${name}: file exceeds the 5 MiB limit`, EXIT.USAGE);
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
const body = new FormData();
|
|
846
|
-
body.append('file', new Blob([await readFile(path)], { type: ATTACHMENT_MIME[ext] }), name);
|
|
847
|
-
|
|
848
|
-
let res;
|
|
849
|
-
try {
|
|
850
|
-
// Not httpJson: that helper JSON-encodes the body and would strip the
|
|
851
|
-
// multipart boundary the runtime generates for us.
|
|
852
|
-
res = await fetch(`${apiBase}/api/agent/attachments`, {
|
|
853
|
-
method: 'POST',
|
|
854
|
-
headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
|
|
855
|
-
body,
|
|
856
|
-
});
|
|
857
|
-
} catch (err) {
|
|
858
|
-
fail(`network error uploading ${name}: ${err.message}`);
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
const text = await res.text().catch(() => '');
|
|
862
|
-
let json = null;
|
|
863
|
-
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON response */ }
|
|
864
|
-
|
|
865
|
-
if (res.status === 402) {
|
|
866
|
-
fail(`--attach ${name}: ping attachments are a Pro feature`, EXIT.USAGE);
|
|
867
|
-
}
|
|
868
|
-
if (!res.ok || !json?.attachment?.id) {
|
|
869
|
-
const detail = apiDetail(res, json);
|
|
870
|
-
fail(`upload failed for ${name}: ${detail}`);
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
ids.push(json.attachment.id);
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
return ids;
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
async function ping(args) {
|
|
880
|
-
if (args.help) { process.stdout.write(`${commandHelp('ping')}\n`); return EXIT.OK; }
|
|
881
|
-
|
|
882
|
-
const message = args.message;
|
|
883
|
-
if (!message) fail('a --message is required', EXIT.USAGE);
|
|
884
|
-
requireMaxLength(message, 500, '--message');
|
|
885
|
-
requireMaxLength(args.title, 40, '--title');
|
|
886
|
-
|
|
887
|
-
if (args.action !== undefined && !/^[1-4]$/.test(String(args.action))) {
|
|
888
|
-
fail('--action must be an integer 1–4', EXIT.USAGE);
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
let ackTimeout;
|
|
892
|
-
if (args.ack_timeout !== undefined) {
|
|
893
|
-
if (!args.require_ack) {
|
|
894
|
-
fail('--ack-timeout requires --require-ack', EXIT.USAGE);
|
|
895
|
-
}
|
|
896
|
-
if (!/^\d+$/.test(String(args.ack_timeout))) {
|
|
897
|
-
fail('--ack-timeout must be an integer number of seconds', EXIT.USAGE);
|
|
898
|
-
}
|
|
899
|
-
ackTimeout = Number(args.ack_timeout);
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
let data;
|
|
903
|
-
if (args.data !== undefined) {
|
|
904
|
-
data = parseDataObject(args.data);
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
// Link ping: --url/--button-label fold into the structured data object
|
|
908
|
-
// (server contract: data.url = absolute http(s) <= 2048, data.button_label <= 26).
|
|
909
|
-
if (args.button_label !== undefined && args.url === undefined) {
|
|
910
|
-
fail('--button-label requires --url', EXIT.USAGE);
|
|
911
|
-
}
|
|
912
|
-
if (args.url !== undefined) {
|
|
913
|
-
let linkUrl;
|
|
914
|
-
try {
|
|
915
|
-
linkUrl = new URL(args.url);
|
|
916
|
-
} catch {
|
|
917
|
-
fail('--url is not a valid URL', EXIT.USAGE);
|
|
918
|
-
}
|
|
919
|
-
if (linkUrl.protocol !== 'https:' && linkUrl.protocol !== 'http:') {
|
|
920
|
-
fail('--url must be an absolute http(s) URL', EXIT.USAGE);
|
|
921
|
-
}
|
|
922
|
-
if (args.url.length > 2048) {
|
|
923
|
-
fail('--url must be at most 2048 characters', EXIT.USAGE);
|
|
924
|
-
}
|
|
925
|
-
if (args.button_label !== undefined && args.button_label.length > 26) {
|
|
926
|
-
fail('--button-label must be at most 26 characters', EXIT.USAGE);
|
|
927
|
-
}
|
|
928
|
-
data = { ...(data || {}), url: args.url };
|
|
929
|
-
if (args.button_label !== undefined) data.button_label = args.button_label;
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
const webhook = args.webhook || process.env.PINGROOM_WEBHOOK_URL;
|
|
933
|
-
const token = resolveToken(args);
|
|
934
|
-
const apiBase = resolveApiBase(args);
|
|
935
|
-
const room = resolveRoom(args);
|
|
936
|
-
|
|
937
|
-
let result;
|
|
938
|
-
|
|
939
|
-
// Attachments exist only on the agent-token path: an incoming webhook has no
|
|
940
|
-
// uploader identity to bind private files to, so the API takes no ids there.
|
|
941
|
-
const attachPaths = args.attach ?? [];
|
|
942
|
-
if (attachPaths.length && (webhook || !token)) {
|
|
943
|
-
fail('--attach requires an agent token (--token / PINGROOM_TOKEN), not a webhook ping', EXIT.USAGE);
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
if (webhook) {
|
|
947
|
-
if (ackTimeout !== undefined && (ackTimeout < 1 || ackTimeout > 86_400)) {
|
|
948
|
-
fail('--ack-timeout must be between 1 and 86400 seconds for a webhook ping', EXIT.USAGE);
|
|
949
|
-
}
|
|
950
|
-
requireSafeUrl('--webhook', webhook);
|
|
951
|
-
const body = { message };
|
|
952
|
-
if (args.title) body.title = args.title;
|
|
953
|
-
if (args.action !== undefined) body.action = Number(args.action);
|
|
954
|
-
if (data) body.data = data;
|
|
955
|
-
if (args.require_ack) body.requires_ack = true;
|
|
956
|
-
if (ackTimeout !== undefined) body.ack_timeout_seconds = ackTimeout;
|
|
957
|
-
result = await httpJson('POST', webhook, { body });
|
|
958
|
-
} else if (token) {
|
|
959
|
-
requireStoredCredentialOrigin(args, apiBase);
|
|
960
|
-
if (!room) fail('--room is required when using --token (or set one with "pingroom config set default_room <code>")', EXIT.USAGE);
|
|
961
|
-
if (ackTimeout !== undefined && (ackTimeout < 60 || ackTimeout > 86_400)) {
|
|
962
|
-
fail('--ack-timeout must be between 60 and 86400 seconds for an agent room ping', EXIT.USAGE);
|
|
963
|
-
}
|
|
964
|
-
requireSafeUrl('--api', apiBase);
|
|
965
|
-
const url = `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/notifications`;
|
|
966
|
-
const body = { message };
|
|
967
|
-
if (args.title) body.title = args.title;
|
|
968
|
-
if (args.action !== undefined) body.action_number = Number(args.action);
|
|
969
|
-
if (data) body.data = data;
|
|
970
|
-
if (args.require_ack) body.requires_ack = true;
|
|
971
|
-
if (ackTimeout !== undefined) body.ack_timeout_seconds = ackTimeout;
|
|
972
|
-
if (attachPaths.length) {
|
|
973
|
-
body.attachment_ids = await uploadAttachments(attachPaths, apiBase, token);
|
|
974
|
-
}
|
|
975
|
-
result = await httpJson('POST', url, { body, headers: { Authorization: `Bearer ${token}` } });
|
|
976
|
-
} else {
|
|
977
|
-
fail('provide a webhook (--webhook / PINGROOM_WEBHOOK_URL) or an agent token (--token / PINGROOM_TOKEN, or run "pingroom" to connect)', EXIT.USAGE);
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
const { res, text, json } = result;
|
|
981
|
-
|
|
982
|
-
if (args.json) {
|
|
983
|
-
process.stdout.write(`${text || '{}'}\n`);
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
const ok = res.ok && !(json && json.success === false);
|
|
987
|
-
|
|
988
|
-
if (!ok) {
|
|
989
|
-
const detail = apiDetail(res, json);
|
|
990
|
-
fail(`delivery failed: ${detail}`);
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
if (!args.json) process.stdout.write('ping sent ✅\n');
|
|
994
|
-
return EXIT.OK;
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
// --- live status -----------------------------------------------------------
|
|
998
|
-
|
|
999
|
-
// The templates the server accepts on `live start`. Mirrored here so a typo is
|
|
1000
|
-
// a local usage error instead of a 422 from the API. Keep in lockstep with the
|
|
1001
|
-
// --template line in HELP and with LIVE_ACTIVITY_TEMPLATES.md.
|
|
1002
|
-
const LIVE_TEMPLATES = ['status', 'steps', 'progress', 'metrics', 'countdown', 'question', 'matchup'];
|
|
1003
|
-
|
|
1004
|
-
/**
|
|
1005
|
-
* Names the API does not take, folded onto the wire id it does.
|
|
1006
|
-
*
|
|
1007
|
-
* The `question` template is labelled **Decision** everywhere a person sees it,
|
|
1008
|
-
* so it is never confused with PingRoom's first-class Question protocol — that
|
|
1009
|
-
* one is answered through `pingroom ask`, carries a real Question id, and this
|
|
1010
|
-
* template does not. The wire id stayed `question`, so someone who reads
|
|
1011
|
-
* "Decision" in the app and types it would otherwise get a usage error for
|
|
1012
|
-
* using the only name they have been shown.
|
|
1013
|
-
*/
|
|
1014
|
-
const LIVE_TEMPLATE_ALIASES = { decision: 'question' };
|
|
1015
|
-
|
|
1016
|
-
/** The wire id for a template name a human typed, or the name unchanged. */
|
|
1017
|
-
function canonicalTemplate(name) {
|
|
1018
|
-
return LIVE_TEMPLATE_ALIASES[name] ?? name;
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
/** What we offer in help and errors: the alias leads, since it is what the app shows. */
|
|
1022
|
-
const LIVE_TEMPLATE_NAMES = ['status', 'steps', 'progress', 'metrics', 'countdown', 'decision', 'matchup'];
|
|
1023
|
-
|
|
1024
|
-
// Parser for `live`: a leading subcommand (start|update|end|get) plus the
|
|
1025
|
-
// live-status flags. Unknown flags fail like the other parsers.
|
|
1026
|
-
const parseLiveArgs = makeParser({
|
|
1027
|
-
aliases: {
|
|
1028
|
-
'-c': 'correlation_id', '--correlation-id': 'correlation_id',
|
|
1029
|
-
'-t': 'title', '--title': 'title',
|
|
1030
|
-
'-m': 'message', '--message': 'message',
|
|
1031
|
-
'--template': 'template',
|
|
1032
|
-
'--category': 'category',
|
|
1033
|
-
'--progress': 'progress',
|
|
1034
|
-
'--step': 'step',
|
|
1035
|
-
'--steps': 'steps',
|
|
1036
|
-
'--metric': 'metric',
|
|
1037
|
-
'--deadline-at': 'deadline_at',
|
|
1038
|
-
'--eta-at': 'eta_at',
|
|
1039
|
-
'--prompt': 'prompt',
|
|
1040
|
-
'--option': 'option',
|
|
1041
|
-
'--left': 'left',
|
|
1042
|
-
'--right': 'right',
|
|
1043
|
-
'--center': 'center',
|
|
1044
|
-
'--accent-override': 'accent_override',
|
|
1045
|
-
'--failed': 'failed',
|
|
1046
|
-
'-a': 'action', '--action': 'action',
|
|
1047
|
-
'-d': 'data', '--data': 'data',
|
|
1048
|
-
'--require-ack': 'require_ack',
|
|
1049
|
-
'--ack-timeout': 'ack_timeout',
|
|
1050
|
-
'-w': 'webhook', '--webhook': 'webhook',
|
|
1051
|
-
'--token': 'token',
|
|
1052
|
-
'--room': 'room',
|
|
1053
|
-
'--api': 'api',
|
|
1054
|
-
'--json': 'json',
|
|
1055
|
-
'-h': 'help', '--help': 'help',
|
|
1056
|
-
},
|
|
1057
|
-
booleans: ['require_ack', 'json', 'help', 'failed'],
|
|
1058
|
-
repeatable: ['metric', 'option'],
|
|
1059
|
-
});
|
|
1060
|
-
|
|
1061
|
-
// "label:value" -> {label, value}. Only the first colon splits.
|
|
1062
|
-
function buildMetrics(list) {
|
|
1063
|
-
if (!list || list.length === 0) return undefined;
|
|
1064
|
-
return list.map((spec) => {
|
|
1065
|
-
const idx = spec.indexOf(':');
|
|
1066
|
-
if (idx <= 0) fail(`--metric must be "label:value" (got "${spec}")`, EXIT.USAGE);
|
|
1067
|
-
return { label: spec.slice(0, idx), value: spec.slice(idx + 1) };
|
|
1068
|
-
});
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
// "value:label" -> {value, label}; a bare token is both. Matches the `ask`
|
|
1072
|
-
// command's option syntax minus `style`, which live_status options don't carry.
|
|
1073
|
-
function buildLiveOptions(list) {
|
|
1074
|
-
if (!list || list.length === 0) return undefined;
|
|
1075
|
-
return list.map((spec) => {
|
|
1076
|
-
const idx = spec.indexOf(':');
|
|
1077
|
-
if (idx < 0) return { value: spec, label: spec };
|
|
1078
|
-
if (idx === 0) fail(`--option needs a value before the colon (got "${spec}")`, EXIT.USAGE);
|
|
1079
|
-
return { value: spec.slice(0, idx), label: spec.slice(idx + 1) };
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
// "label:value" -> {label, value}, for --left / --right on the matchup template.
|
|
1084
|
-
function buildSide(spec, flag) {
|
|
1085
|
-
if (spec === undefined) return undefined;
|
|
1086
|
-
const idx = spec.indexOf(':');
|
|
1087
|
-
if (idx <= 0) fail(`${flag} must be "label:value" (got "${spec}")`, EXIT.USAGE);
|
|
1088
|
-
return { label: spec.slice(0, idx), value: spec.slice(idx + 1) };
|
|
1089
|
-
}
|
|
1090
|
-
|
|
1091
|
-
// The server accepts #rrggbb with or without the leading #; normalize to one
|
|
1092
|
-
// form so a shell that ate the # (unquoted) still produces a valid payload.
|
|
1093
|
-
function normalizeAccent(raw) {
|
|
1094
|
-
if (raw === undefined) return undefined;
|
|
1095
|
-
const hex = raw.trim().replace(/^#/, '');
|
|
1096
|
-
if (!/^[0-9A-Fa-f]{6}$/.test(hex)) {
|
|
1097
|
-
fail(`--accent-override must be a 6-digit hex color (got "${raw}")`, EXIT.USAGE);
|
|
1098
|
-
}
|
|
1099
|
-
return `#${hex.toLowerCase()}`;
|
|
1100
|
-
}
|
|
1101
|
-
|
|
1102
|
-
function numberOption(raw, flag, { min, max, integer = false } = {}) {
|
|
1103
|
-
if (raw === undefined) return undefined;
|
|
1104
|
-
const value = Number(raw);
|
|
1105
|
-
if (!Number.isFinite(value)) fail(`${flag} must be a number`, EXIT.USAGE);
|
|
1106
|
-
if (integer && !Number.isInteger(value)) fail(`${flag} must be an integer`, EXIT.USAGE);
|
|
1107
|
-
if (min !== undefined && value < min) fail(`${flag} must be at least ${min}`, EXIT.USAGE);
|
|
1108
|
-
if (max !== undefined && value > max) fail(`${flag} must be at most ${max}`, EXIT.USAGE);
|
|
1109
|
-
return value;
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* Drive a live progress card on the room members' lock screen.
|
|
1114
|
-
*
|
|
1115
|
-
* One correlation id = one stream: `start` opens it (one alert), `update` moves
|
|
1116
|
-
* it silently, `end` closes it with one completion alert. Works with either an
|
|
1117
|
-
* agent token (--token, needs pingroom:live:write) or a room's incoming webhook
|
|
1118
|
-
* (--webhook), which speak the same `live_status` contract.
|
|
1119
|
-
*/
|
|
1120
|
-
async function live(args) {
|
|
1121
|
-
if (args.help) { process.stdout.write(`${commandHelp('live')}\n`); return EXIT.OK; }
|
|
1122
|
-
const sub = args._[0];
|
|
1123
|
-
const known = ['start', 'update', 'end', 'get'];
|
|
1124
|
-
if (!sub || !known.includes(sub)) {
|
|
1125
|
-
fail(`live needs a subcommand: ${known.join(' | ')}`, EXIT.USAGE);
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
const correlationId = args.correlation_id;
|
|
1129
|
-
if (!correlationId) fail('--correlation-id is required', EXIT.USAGE);
|
|
1130
|
-
|
|
1131
|
-
const webhook = args.webhook || process.env.PINGROOM_WEBHOOK_URL;
|
|
1132
|
-
const token = resolveToken(args);
|
|
1133
|
-
const apiBase = resolveApiBase(args);
|
|
1134
|
-
const room = resolveRoom(args);
|
|
1135
|
-
|
|
1136
|
-
if (sub === 'get') {
|
|
1137
|
-
if (!token) fail('live get requires an agent token (--token or PINGROOM_TOKEN)', EXIT.USAGE);
|
|
1138
|
-
requireStoredCredentialOrigin(args, apiBase);
|
|
1139
|
-
if (!room) fail('--room is required', EXIT.USAGE);
|
|
1140
|
-
requireSafeUrl('--api', apiBase);
|
|
1141
|
-
const url = `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/live/${encodeURIComponent(correlationId)}`;
|
|
1142
|
-
const { res, text, json } = await httpJson('GET', url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1143
|
-
if (args.json) process.stdout.write(`${text || '{}'}\n`);
|
|
1144
|
-
if (!res.ok) {
|
|
1145
|
-
fail(`read failed: ${apiDetail(res, json)}`);
|
|
1146
|
-
}
|
|
1147
|
-
if (!args.json) process.stdout.write(`${(json && json.state) || 'unknown'}\n`);
|
|
1148
|
-
return EXIT.OK;
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
const liveStatus = {
|
|
1152
|
-
state: sub === 'end' ? (args.failed ? 'failed' : 'done') : 'running',
|
|
1153
|
-
};
|
|
1154
|
-
|
|
1155
|
-
// 256, not the 500 a ping body gets: this is the card's one live line.
|
|
1156
|
-
requireMaxLength(args.message, 256, '--message');
|
|
1157
|
-
requireMaxLength(args.title, 40, '--title');
|
|
1158
|
-
requireMaxLength(args.prompt, 256, '--prompt');
|
|
1159
|
-
requireMaxLength(args.center, 40, '--center');
|
|
1160
|
-
if (args.message !== undefined) liveStatus.message = args.message;
|
|
1161
|
-
if (args.prompt !== undefined) liveStatus.prompt = args.prompt;
|
|
1162
|
-
|
|
1163
|
-
const progress = numberOption(args.progress, '--progress', { min: 0, max: 1 });
|
|
1164
|
-
if (progress !== undefined) liveStatus.progress = progress;
|
|
1165
|
-
|
|
1166
|
-
const step = numberOption(args.step, '--step', { min: 0, max: 8, integer: true });
|
|
1167
|
-
if (step !== undefined) liveStatus.current_step = step;
|
|
1168
|
-
|
|
1169
|
-
const deadlineAt = numberOption(args.deadline_at, '--deadline-at', { min: 0, integer: true });
|
|
1170
|
-
if (deadlineAt !== undefined) liveStatus.deadline_at = deadlineAt;
|
|
1171
|
-
|
|
1172
|
-
const etaAt = numberOption(args.eta_at, '--eta-at', { min: 0, integer: true });
|
|
1173
|
-
if (etaAt !== undefined) liveStatus.eta_at = etaAt;
|
|
1174
|
-
|
|
1175
|
-
const metrics = buildMetrics(args.metric);
|
|
1176
|
-
if (metrics) liveStatus.metrics = metrics;
|
|
1177
|
-
|
|
1178
|
-
const options = buildLiveOptions(args.option);
|
|
1179
|
-
if (options) {
|
|
1180
|
-
if (options.length > 4) fail('--option accepts at most 4 choices', EXIT.USAGE);
|
|
1181
|
-
liveStatus.options = options;
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
const left = buildSide(args.left, '--left');
|
|
1185
|
-
if (left) liveStatus.left = left;
|
|
1186
|
-
const right = buildSide(args.right, '--right');
|
|
1187
|
-
if (right) liveStatus.right = right;
|
|
1188
|
-
if (args.center !== undefined) liveStatus.center = args.center;
|
|
1189
|
-
|
|
1190
|
-
const accent = normalizeAccent(args.accent_override);
|
|
1191
|
-
if (accent) liveStatus.accent_override = accent;
|
|
1192
|
-
|
|
1193
|
-
// Template, category and step labels are fixed when the stream is created;
|
|
1194
|
-
// sending them on an update is a no-op server-side, so only `start` takes them.
|
|
1195
|
-
if (sub === 'start') {
|
|
1196
|
-
// Validated locally for the same reason --category is: a typo'd name is a
|
|
1197
|
-
// usage error, and letting it reach the server turns it into a 422 round
|
|
1198
|
-
// trip that reads like an outage.
|
|
1199
|
-
if (args.template) {
|
|
1200
|
-
const template = canonicalTemplate(args.template);
|
|
1201
|
-
if (!LIVE_TEMPLATES.includes(template)) {
|
|
1202
|
-
fail(`--template must be one of: ${LIVE_TEMPLATE_NAMES.join(', ')}`, EXIT.USAGE);
|
|
1203
|
-
}
|
|
1204
|
-
liveStatus.template = template;
|
|
1205
|
-
}
|
|
1206
|
-
// `alert` has no template equivalent and is the only way to start a stream
|
|
1207
|
-
// time-sensitive (breaking through Focus) without also demanding an ack.
|
|
1208
|
-
if (args.category) {
|
|
1209
|
-
if (!['status', 'steps', 'alert'].includes(args.category)) {
|
|
1210
|
-
fail('--category must be status, steps or alert', EXIT.USAGE);
|
|
1211
|
-
}
|
|
1212
|
-
liveStatus.category = args.category;
|
|
1213
|
-
}
|
|
1214
|
-
if (args.steps) {
|
|
1215
|
-
const labels = args.steps.split(',').map((s) => s.trim()).filter(Boolean);
|
|
1216
|
-
if (labels.length < 2 || labels.length > 8) {
|
|
1217
|
-
fail('--steps needs between 2 and 8 comma-separated labels', EXIT.USAGE);
|
|
1218
|
-
}
|
|
1219
|
-
liveStatus.steps = labels;
|
|
1220
|
-
}
|
|
1221
|
-
} else if (args.template || args.steps || args.category) {
|
|
1222
|
-
fail('--template, --category and --steps are fixed at stream creation; pass them to "live start"', EXIT.USAGE);
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
const body = { correlation_id: correlationId, live_status: liveStatus };
|
|
1226
|
-
if (args.title) body.title = args.title;
|
|
1227
|
-
if (args.action !== undefined) body.action = Number(args.action);
|
|
1228
|
-
// Same object-shape guard ping/ask/handoff use. A bare JSON.parse also accepts
|
|
1229
|
-
// an array, which the server then rejects — a wasted round trip for what is a
|
|
1230
|
-
// local usage error.
|
|
1231
|
-
// `!== undefined`, not truthiness: `-d ''` is a malformed value, and a
|
|
1232
|
-
// truthiness test drops it on the floor and ships the ping without the data
|
|
1233
|
-
// the caller believed they attached. ping/ask/handoff all reject it loudly.
|
|
1234
|
-
if (args.data !== undefined) body.data = parseDataObject(args.data);
|
|
1235
|
-
if (args.require_ack) body.requires_ack = true;
|
|
1236
|
-
const ackTimeout = numberOption(args.ack_timeout, '--ack-timeout', { min: 1, max: 86_400, integer: true });
|
|
1237
|
-
if (ackTimeout !== undefined) body.ack_timeout_seconds = ackTimeout;
|
|
1238
|
-
|
|
1239
|
-
let result;
|
|
1240
|
-
if (webhook) {
|
|
1241
|
-
requireSafeUrl('--webhook', webhook);
|
|
1242
|
-
result = await httpJson('POST', webhook, { body });
|
|
1243
|
-
} else if (token) {
|
|
1244
|
-
requireStoredCredentialOrigin(args, apiBase);
|
|
1245
|
-
if (!room) fail('--room is required when using --token (or set one with "pingroom config set default_room <code>")', EXIT.USAGE);
|
|
1246
|
-
requireSafeUrl('--api', apiBase);
|
|
1247
|
-
const url = `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/live`;
|
|
1248
|
-
result = await httpJson('POST', url, { body, headers: { Authorization: `Bearer ${token}` } });
|
|
1249
|
-
} else {
|
|
1250
|
-
fail('provide a webhook (--webhook / PINGROOM_WEBHOOK_URL) or an agent token (--token / PINGROOM_TOKEN, or run "pingroom" to connect)', EXIT.USAGE);
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
const { res, text, json } = result;
|
|
1254
|
-
if (args.json) process.stdout.write(`${text || '{}'}\n`);
|
|
1255
|
-
|
|
1256
|
-
if (!res.ok || (json && json.success === false)) {
|
|
1257
|
-
const detail = apiDetail(res, json);
|
|
1258
|
-
fail(`live ${sub} failed: ${detail}`);
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
if (!args.json) {
|
|
1262
|
-
const state = (json && (json.state || (json.live_status && json.live_status.state))) || sub;
|
|
1263
|
-
process.stdout.write(`live ${sub} → ${state} ✅\n`);
|
|
1264
|
-
}
|
|
1265
|
-
return EXIT.OK;
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
// --- questions -------------------------------------------------------------
|
|
1269
|
-
|
|
1270
|
-
// Resolve the credential + endpoint a token-only command needs. When nothing is
|
|
1271
|
-
// available this is a usage error pointing at PINGROOM_TOKEN — never a prompt,
|
|
1272
|
-
// so a CI job fails in a second instead of hanging on an invisible question.
|
|
1273
|
-
function agentContext(args, { needRoom = false } = {}) {
|
|
1274
|
-
const token = resolveToken(args);
|
|
1275
|
-
if (!token) {
|
|
1276
|
-
fail(
|
|
1277
|
-
'an agent token is required (--token or PINGROOM_TOKEN). Run "pingroom" in an interactive terminal to connect this machine; in CI set PINGROOM_TOKEN.',
|
|
1278
|
-
EXIT.USAGE,
|
|
1279
|
-
);
|
|
1280
|
-
}
|
|
1281
|
-
const apiBase = resolveApiBase(args);
|
|
1282
|
-
requireStoredCredentialOrigin(args, apiBase);
|
|
1283
|
-
requireSafeUrl('--api', apiBase);
|
|
1284
|
-
const room = resolveRoom(args);
|
|
1285
|
-
if (needRoom && !room) {
|
|
1286
|
-
fail('--room is required (or set one with "pingroom config set default_room <code>")', EXIT.USAGE);
|
|
1287
|
-
}
|
|
1288
|
-
return { token, apiBase, room };
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
// value:label -> {value, label}. Labels may contain colons (only the first
|
|
1292
|
-
// splits). A bare token is both value and label. Omit all for Approve/Deny.
|
|
1293
|
-
function buildOptions(list) {
|
|
1294
|
-
if (!list || list.length === 0) return undefined;
|
|
1295
|
-
return list.map((spec) => {
|
|
1296
|
-
const idx = spec.indexOf(':');
|
|
1297
|
-
const value = idx === -1 ? spec : spec.slice(0, idx);
|
|
1298
|
-
let label = idx === -1 ? spec : spec.slice(idx + 1);
|
|
1299
|
-
if (!value) fail(`--option must be "value", "value:label" or "value:label:style" (got "${spec}")`, EXIT.USAGE);
|
|
1300
|
-
// A trailing :primary|:danger|:default segment styles the button; any other
|
|
1301
|
-
// trailing segment stays part of the label (labels may contain colons).
|
|
1302
|
-
let style;
|
|
1303
|
-
const lastColon = label.lastIndexOf(':');
|
|
1304
|
-
if (lastColon !== -1) {
|
|
1305
|
-
const candidate = label.slice(lastColon + 1);
|
|
1306
|
-
if (candidate === 'primary' || candidate === 'danger' || candidate === 'default') {
|
|
1307
|
-
style = candidate;
|
|
1308
|
-
label = label.slice(0, lastColon);
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
return style ? { value, label, style } : { value, label };
|
|
1312
|
-
});
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
function exitForState(state) {
|
|
1316
|
-
switch (state) {
|
|
1317
|
-
case 'answered': return EXIT.OK;
|
|
1318
|
-
case 'expired': return EXIT.EXPIRED;
|
|
1319
|
-
case 'cancelled': return EXIT.CANCELLED;
|
|
1320
|
-
default: return EXIT.ERROR;
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
|
|
1324
|
-
// Print the outcome. On `answered`, the chosen value (or typed text) goes to
|
|
1325
|
-
// stdout so `$(pingroom ask --wait ...)` captures it; other outcomes report to
|
|
1326
|
-
// stderr and leave stdout empty.
|
|
1327
|
-
function printResolution(q) {
|
|
1328
|
-
if (q.state === 'answered') {
|
|
1329
|
-
const out = q.answer && (q.answer.text || q.answer.value) || '';
|
|
1330
|
-
process.stdout.write(`${out}\n`);
|
|
1331
|
-
} else {
|
|
1332
|
-
process.stderr.write(`pingroom: question ${q.state}\n`);
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
// Long-poll the wait endpoint until the question leaves `pending`, then print
|
|
1337
|
-
// and return the state's exit code. The server expires it at its ttl, so this
|
|
1338
|
-
// always terminates.
|
|
1339
|
-
async function waitForResolution(id, args, { token, apiBase }) {
|
|
1340
|
-
const hold = resolveWaitHold(args, { def: 25, cap: 30 });
|
|
1341
|
-
|
|
1342
|
-
for (;;) {
|
|
1343
|
-
const started = Date.now();
|
|
1344
|
-
const url = `${apiBase}/api/agent/questions/${encodeURIComponent(id)}/wait?timeout=${hold}`;
|
|
1345
|
-
const { res, text, json } = await httpJson('GET', url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1346
|
-
if (!res.ok) {
|
|
1347
|
-
const detail = apiDetail(res, json);
|
|
1348
|
-
fail(`wait failed: ${detail}`);
|
|
1349
|
-
}
|
|
1350
|
-
if (json && json.state && json.state !== 'pending') {
|
|
1351
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1352
|
-
else printResolution(json);
|
|
1353
|
-
return exitForState(json.state);
|
|
1354
|
-
}
|
|
1355
|
-
// Still pending at the hold timeout — poll again, but never hot-loop: a
|
|
1356
|
-
// misbehaving server that answers `pending` instantly (ignoring the hold)
|
|
1357
|
-
// would otherwise be hammered at full speed.
|
|
1358
|
-
const elapsed = Date.now() - started;
|
|
1359
|
-
if (elapsed < 1000) await sleep(1000 - elapsed);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
async function ask(args) {
|
|
1364
|
-
if (args.help) { process.stdout.write(`${commandHelp('ask')}\n`); return EXIT.OK; }
|
|
1365
|
-
|
|
1366
|
-
const prompt = args.prompt;
|
|
1367
|
-
if (!prompt) fail('a --prompt is required', EXIT.USAGE);
|
|
1368
|
-
requireMaxLength(prompt, 500, '--prompt');
|
|
1369
|
-
requireMaxLength(args.context, 40, '--context');
|
|
1370
|
-
|
|
1371
|
-
const { token, apiBase, room } = agentContext(args, { needRoom: true });
|
|
1372
|
-
|
|
1373
|
-
const body = { prompt };
|
|
1374
|
-
const options = buildOptions(args.option);
|
|
1375
|
-
if (options) body.options = options;
|
|
1376
|
-
if (args.context) body.context = args.context;
|
|
1377
|
-
if (args.scope !== undefined) {
|
|
1378
|
-
if (args.scope !== 'direct' && args.scope !== 'room') fail("--scope must be 'direct' or 'room'", EXIT.USAGE);
|
|
1379
|
-
body.responder_scope = args.scope;
|
|
1380
|
-
}
|
|
1381
|
-
if (args.target !== undefined) body.target_user_id = args.target;
|
|
1382
|
-
if (args.ttl !== undefined) {
|
|
1383
|
-
if (!/^\d+$/.test(String(args.ttl))) fail('--ttl must be an integer number of seconds', EXIT.USAGE);
|
|
1384
|
-
body.ttl = Number(args.ttl);
|
|
1385
|
-
}
|
|
1386
|
-
if (args.correlation_id !== undefined) body.correlation_id = args.correlation_id;
|
|
1387
|
-
if (args.reply_to !== undefined) body.reply_to = args.reply_to;
|
|
1388
|
-
if (args.text_input !== undefined || args.text_max !== undefined) {
|
|
1389
|
-
const textInput = {};
|
|
1390
|
-
if (args.text_input) textInput.placeholder = String(args.text_input).slice(0, 60);
|
|
1391
|
-
if (args.text_max !== undefined) {
|
|
1392
|
-
const n = Number(args.text_max);
|
|
1393
|
-
if (!/^\d+$/.test(String(args.text_max)) || n < 1 || n > 60) {
|
|
1394
|
-
fail('--text-max must be an integer between 1 and 60', EXIT.USAGE);
|
|
1395
|
-
}
|
|
1396
|
-
textInput.max_length = n;
|
|
1397
|
-
}
|
|
1398
|
-
body.text_input = textInput;
|
|
1399
|
-
}
|
|
1400
|
-
if (args.data !== undefined) body.data = parseDataObject(args.data);
|
|
1401
|
-
|
|
1402
|
-
// Pre-flight: reject a bad --timeout before the question exists.
|
|
1403
|
-
if (args.wait) resolveWaitHold(args, { def: 25, cap: 30 });
|
|
1404
|
-
|
|
1405
|
-
const url = `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/questions`;
|
|
1406
|
-
const { res, text, json } = await httpJson('POST', url, { body, headers: { Authorization: `Bearer ${token}` } });
|
|
1407
|
-
if (!res.ok) {
|
|
1408
|
-
const detail = apiDetail(res, json);
|
|
1409
|
-
fail(`ask failed: ${detail}`);
|
|
1410
|
-
}
|
|
1411
|
-
|
|
1412
|
-
if (!args.wait) {
|
|
1413
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1414
|
-
else process.stdout.write(`${json.id}\n`);
|
|
1415
|
-
return EXIT.OK;
|
|
1416
|
-
}
|
|
1417
|
-
|
|
1418
|
-
return waitForResolution(json.id, args, { token, apiBase });
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
async function watch(args) {
|
|
1422
|
-
if (args.help) { process.stdout.write(`${commandHelp('watch')}\n`); return EXIT.OK; }
|
|
1423
|
-
const id = args._[0];
|
|
1424
|
-
if (!id) fail('a question id is required (pingroom watch <id>)', EXIT.USAGE);
|
|
1425
|
-
const { token, apiBase } = agentContext(args);
|
|
1426
|
-
return waitForResolution(id, args, { token, apiBase });
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
async function cancel(args) {
|
|
1430
|
-
if (args.help) { process.stdout.write(`${commandHelp('cancel')}\n`); return EXIT.OK; }
|
|
1431
|
-
const id = args._[0];
|
|
1432
|
-
if (!id) fail('a question id is required (pingroom cancel <id>)', EXIT.USAGE);
|
|
1433
|
-
const { token, apiBase } = agentContext(args);
|
|
1434
|
-
const url = `${apiBase}/api/agent/questions/${encodeURIComponent(id)}/cancel`;
|
|
1435
|
-
const { res, text, json } = await httpJson('POST', url, { body: {}, headers: { Authorization: `Bearer ${token}` } });
|
|
1436
|
-
if (!res.ok) {
|
|
1437
|
-
const detail = apiDetail(res, json);
|
|
1438
|
-
fail(`cancel failed: ${detail}`);
|
|
1439
|
-
}
|
|
1440
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1441
|
-
else process.stdout.write(`cancelled (${json && json.state})\n`);
|
|
1442
|
-
return EXIT.OK;
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
async function list(args) {
|
|
1446
|
-
if (args.help) { process.stdout.write(`${commandHelp('list')}\n`); return EXIT.OK; }
|
|
1447
|
-
const { token, apiBase } = agentContext(args);
|
|
1448
|
-
const qs = args.state ? `?state=${encodeURIComponent(args.state)}` : '';
|
|
1449
|
-
const url = `${apiBase}/api/agent/questions${qs}`;
|
|
1450
|
-
const { res, text, json } = await httpJson('GET', url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1451
|
-
if (!res.ok) {
|
|
1452
|
-
const detail = apiDetail(res, json);
|
|
1453
|
-
fail(`list failed: ${detail}`);
|
|
1454
|
-
}
|
|
1455
|
-
if (args.json) { process.stdout.write(`${text}\n`); return EXIT.OK; }
|
|
1456
|
-
|
|
1457
|
-
const questions = (json && json.questions) || [];
|
|
1458
|
-
if (questions.length === 0) { process.stdout.write('no questions\n'); return EXIT.OK; }
|
|
1459
|
-
for (const q of questions) {
|
|
1460
|
-
const answer = q.answer && q.answer.value ? ` → ${q.answer.value}` : '';
|
|
1461
|
-
process.stdout.write(`${q.id} ${String(q.state).padEnd(9)} ${q.prompt}${answer}\n`);
|
|
1462
|
-
}
|
|
1463
|
-
return EXIT.OK;
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
// --- listen ----------------------------------------------------------------
|
|
1467
|
-
//
|
|
1468
|
-
// The inbound half. Everything else here talks; this is how an agent hears —
|
|
1469
|
-
// replies to its own structured pings, a human's ping in a room it belongs to,
|
|
1470
|
-
// anything landing while it works.
|
|
1471
|
-
//
|
|
1472
|
-
// The server holds each request open until something arrives or the timeout
|
|
1473
|
-
// elapses, so this is a long-poll, not a poll loop: an idle hour costs ~144
|
|
1474
|
-
// requests, not one per second.
|
|
1475
|
-
|
|
1476
|
-
/** Cursor bookkeeping is the whole protocol: `after` in, `cursor` back. */
|
|
1477
|
-
async function listen(args) {
|
|
1478
|
-
if (args.help) { process.stdout.write(`${commandHelp('listen')}\n`); return EXIT.OK; }
|
|
1479
|
-
|
|
1480
|
-
const { token, apiBase } = agentContext(args);
|
|
1481
|
-
const headers = { Authorization: `Bearer ${token}` };
|
|
1482
|
-
|
|
1483
|
-
const timeout = numberOption(args.timeout, '--timeout', { min: 0, max: 30, integer: true }) ?? 25;
|
|
1484
|
-
const limit = numberOption(args.limit, '--limit', { min: 1, max: 100, integer: true }) ?? 50;
|
|
1485
|
-
|
|
1486
|
-
// No cursor means "from now": the server answers an empty `after` with the
|
|
1487
|
-
// head id and no rows, so starting up never replays history the agent has
|
|
1488
|
-
// already seen. `--from` opts into catching up from a known id instead.
|
|
1489
|
-
let cursor = args.from;
|
|
1490
|
-
if (!cursor) {
|
|
1491
|
-
const { res, json } = await httpJson('GET', `${apiBase}/api/agent/notifications/wait`, {
|
|
1492
|
-
headers,
|
|
1493
|
-
soft: true,
|
|
1494
|
-
});
|
|
1495
|
-
if (!res?.ok) fail(`listen failed: ${apiDetail(res, json)}`);
|
|
1496
|
-
cursor = json && json.cursor;
|
|
1497
|
-
if (!cursor) {
|
|
1498
|
-
// A brand-new account with no pings at all has no head id. Nothing is
|
|
1499
|
-
// wrong; there is simply nothing to be after yet.
|
|
1500
|
-
cursor = '';
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
let transientRun = 0;
|
|
1505
|
-
|
|
1506
|
-
for (;;) {
|
|
1507
|
-
const query = new URLSearchParams({ timeout: String(timeout), limit: String(limit) });
|
|
1508
|
-
if (cursor) query.set('after', cursor);
|
|
1509
|
-
|
|
1510
|
-
const { res, json, error } = await httpJson(
|
|
1511
|
-
'GET',
|
|
1512
|
-
`${apiBase}/api/agent/notifications/wait?${query}`,
|
|
1513
|
-
// The hold plus headroom: aborting at exactly the server's deadline would
|
|
1514
|
-
// race it and turn every quiet window into a client-side error.
|
|
1515
|
-
{ headers, soft: true, signal: AbortSignal.timeout((timeout + 10) * 1000) },
|
|
1516
|
-
);
|
|
1517
|
-
|
|
1518
|
-
if (error || res.status === 429 || res.status >= 500) {
|
|
1519
|
-
transientRun += 1;
|
|
1520
|
-
const retryAfter = res?.status === 429 ? retryAfterMs(res) : null;
|
|
1521
|
-
// Geometric backoff so a real outage is not also a thundering herd. The
|
|
1522
|
-
// loop is unbounded by design — `listen` is a daemon, not a request.
|
|
1523
|
-
const backoff = Math.min(1000 * 2 ** Math.max(0, transientRun - 1), 30_000);
|
|
1524
|
-
await sleep(Math.max(0, retryAfter ?? backoff));
|
|
1525
|
-
continue;
|
|
1526
|
-
}
|
|
1527
|
-
|
|
1528
|
-
if (!res.ok) fail(`listen failed: ${apiDetail(res, json)}`);
|
|
1529
|
-
transientRun = 0;
|
|
1530
|
-
|
|
1531
|
-
const batch = Array.isArray(json?.notifications) ? json.notifications : [];
|
|
1532
|
-
for (const item of batch) {
|
|
1533
|
-
process.stdout.write(args.json ? `${JSON.stringify(item)}\n` : `${formatIncoming(item)}\n`);
|
|
1534
|
-
}
|
|
1535
|
-
// Advance only on a cursor the server actually returned, or a batch could be
|
|
1536
|
-
// replayed forever against a stale `after`.
|
|
1537
|
-
if (json && typeof json.cursor === 'string' && json.cursor) cursor = json.cursor;
|
|
1538
|
-
|
|
1539
|
-
if (args.once) return EXIT.OK;
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
|
|
1543
|
-
/** One readable line per incoming ping. */
|
|
1544
|
-
function formatIncoming(item) {
|
|
1545
|
-
const room = item?.room?.name || item?.room?.code || '?';
|
|
1546
|
-
const body = stripControlChars(item?.message ?? '');
|
|
1547
|
-
const marks = [];
|
|
1548
|
-
if (item?.correlation_id) marks.push(`corr=${stripControlChars(item.correlation_id)}`);
|
|
1549
|
-
if (item?.reply_to) marks.push(`reply_to=${stripControlChars(item.reply_to)}`);
|
|
1550
|
-
if (item?.question) marks.push('question');
|
|
1551
|
-
if (Array.isArray(item?.attachments) && item.attachments.length) {
|
|
1552
|
-
marks.push(`${item.attachments.length} attachment${item.attachments.length === 1 ? '' : 's'}`);
|
|
1553
|
-
}
|
|
1554
|
-
const suffix = marks.length ? ` (${marks.join(' · ')})` : '';
|
|
1555
|
-
return `[${stripControlChars(room)}] ${body}${suffix}`;
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
async function listHandoffs(args) {
|
|
1559
|
-
if (args.help) { process.stdout.write(`${commandHelp('handoffs')}\n`); return EXIT.OK; }
|
|
1560
|
-
const { token, apiBase } = agentContext(args);
|
|
1561
|
-
const state = args.state || 'open';
|
|
1562
|
-
if (state !== 'open' && state !== 'all') {
|
|
1563
|
-
fail("--state must be 'open' or 'all' for handoffs", EXIT.USAGE);
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
const url = `${apiBase}/api/agent/handoffs?state=${encodeURIComponent(state)}`;
|
|
1567
|
-
const { res, text, json } = await httpJson('GET', url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1568
|
-
if (!res.ok) {
|
|
1569
|
-
const detail = apiDetail(res, json);
|
|
1570
|
-
fail(`handoffs list failed: ${detail}`);
|
|
1571
|
-
}
|
|
1572
|
-
if (args.json) { process.stdout.write(`${text}\n`); return EXIT.OK; }
|
|
1573
|
-
|
|
1574
|
-
const handoffs = (json && json.handoffs) || [];
|
|
1575
|
-
if (handoffs.length === 0) { process.stdout.write('no handoffs\n'); return EXIT.OK; }
|
|
1576
|
-
for (const h of handoffs) {
|
|
1577
|
-
const answer = h.answer && (h.answer.value ?? h.answer.text);
|
|
1578
|
-
const outcome = answer !== undefined && answer !== null ? ` → ${answer}` : '';
|
|
1579
|
-
process.stdout.write(
|
|
1580
|
-
`${h.id} ${String(h.kind || '').padEnd(8)} ${String(h.state || '').padEnd(9)} ${h.prompt || ''}${outcome}\n`,
|
|
1581
|
-
);
|
|
1582
|
-
}
|
|
1583
|
-
return EXIT.OK;
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
// --- handoff ---------------------------------------------------------------
|
|
1587
|
-
|
|
1588
|
-
// Terminal wire states across both kinds. ack: open→acked|expired.
|
|
1589
|
-
// question: pending→answered|expired|cancelled. `open`/`pending` are the only
|
|
1590
|
-
// non-terminal states, so a wait loop against these always terminates.
|
|
1591
|
-
const HANDOFF_PENDING = new Set(['open', 'pending']);
|
|
1592
|
-
|
|
1593
|
-
// Map a terminal handoff state to an exit code. A `question` answered with ANY
|
|
1594
|
-
// value is a success (0) — a negative human decision ('hold'/'deny') is NOT an
|
|
1595
|
-
// infra failure. `acked` is likewise 0. `expired` is a distinct 3 so CI can
|
|
1596
|
-
// branch; `cancelled` shares 4 with recipient_not_ready.
|
|
1597
|
-
function exitForHandoffState(state) {
|
|
1598
|
-
switch (state) {
|
|
1599
|
-
case 'acked': return EXIT.OK;
|
|
1600
|
-
case 'answered': return EXIT.OK;
|
|
1601
|
-
case 'expired': return EXIT.EXPIRED;
|
|
1602
|
-
case 'cancelled': return EXIT.CANCELLED;
|
|
1603
|
-
default: return EXIT.ERROR;
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
|
|
1607
|
-
// Print a machine-readable summary of a handoff: id, state, delivery-state, and
|
|
1608
|
-
// the answer value / acked-by when present, one `key=value` per line to stdout.
|
|
1609
|
-
function printHandoff(h) {
|
|
1610
|
-
const lines = [`id=${h.id ?? ''}`, `state=${h.state ?? ''}`];
|
|
1611
|
-
if (h.delivery_state != null) lines.push(`delivery-state=${h.delivery_state}`);
|
|
1612
|
-
if (h.correlation_id) lines.push(`correlation-id=${h.correlation_id}`);
|
|
1613
|
-
if (h.state === 'answered') {
|
|
1614
|
-
const value = h.answer && (h.answer.value ?? h.answer.text) || '';
|
|
1615
|
-
lines.push(`answer=${value}`);
|
|
1616
|
-
}
|
|
1617
|
-
if (h.state === 'acked') {
|
|
1618
|
-
// The Handoff API returns a privacy-aware actor object. Only expose its id
|
|
1619
|
-
// in the machine-readable CLI/GitHub Action output; a redacted actor yields
|
|
1620
|
-
// an empty value instead of the unhelpful "[object Object]" string.
|
|
1621
|
-
const ackerId = h.acked_by && typeof h.acked_by === 'object'
|
|
1622
|
-
? h.acked_by.id
|
|
1623
|
-
: h.acked_by;
|
|
1624
|
-
lines.push(`acked-by=${ackerId ?? ''}`);
|
|
1625
|
-
if (h.acked_at) lines.push(`acked-at=${h.acked_at}`);
|
|
1626
|
-
}
|
|
1627
|
-
process.stdout.write(`${lines.join('\n')}\n`);
|
|
1628
|
-
}
|
|
1629
|
-
|
|
1630
|
-
/**
|
|
1631
|
-
* Append the composite Action's declared outputs without interpreting stdout.
|
|
1632
|
-
* Values use GitHub's multiline protocol with a fresh random delimiter. Output
|
|
1633
|
-
* names are a fixed allowlist; untrusted answer text can never create a key.
|
|
1634
|
-
*/
|
|
1635
|
-
function writeGitHubHandoffOutputs(path, h) {
|
|
1636
|
-
if (typeof path !== 'string' || path.length === 0) {
|
|
1637
|
-
fail('--github-output must be a non-empty path', EXIT.USAGE);
|
|
1638
|
-
}
|
|
1639
|
-
|
|
1640
|
-
const ackerId = h.acked_by && typeof h.acked_by === 'object'
|
|
1641
|
-
? h.acked_by.id
|
|
1642
|
-
: h.acked_by;
|
|
1643
|
-
const fields = [
|
|
1644
|
-
['handoff-id', h.id ?? ''],
|
|
1645
|
-
['state', h.state ?? ''],
|
|
1646
|
-
];
|
|
1647
|
-
if (h.delivery_state != null) fields.push(['delivery-state', h.delivery_state]);
|
|
1648
|
-
if (h.state === 'answered') {
|
|
1649
|
-
fields.push(['answer', h.answer && (h.answer.value ?? h.answer.text) || '']);
|
|
1650
|
-
}
|
|
1651
|
-
if (h.state === 'acked') fields.push(['acknowledged-by', ackerId ?? '']);
|
|
1652
|
-
|
|
1653
|
-
const blocks = fields.map(([name, rawValue]) => {
|
|
1654
|
-
const value = String(rawValue ?? '');
|
|
1655
|
-
let delimiter;
|
|
1656
|
-
do {
|
|
1657
|
-
delimiter = `pingroom_${randomBytes(24).toString('hex')}`;
|
|
1658
|
-
} while (value.includes(delimiter));
|
|
1659
|
-
// Keep the collision check next to serialization: a delimiter must never
|
|
1660
|
-
// occur in an untrusted value, even though a 192-bit collision is remote.
|
|
1661
|
-
if (value.includes(delimiter)) {
|
|
1662
|
-
fail('could not create a safe GitHub output delimiter');
|
|
1663
|
-
}
|
|
1664
|
-
return `${name}<<${delimiter}\n${value}\n${delimiter}\n`;
|
|
1665
|
-
});
|
|
1666
|
-
|
|
1667
|
-
try {
|
|
1668
|
-
appendFileSync(path, blocks.join(''), { encoding: 'utf8' });
|
|
1669
|
-
} catch {
|
|
1670
|
-
fail('could not write GitHub outputs');
|
|
1671
|
-
}
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1674
|
-
// Long-poll GET /handoffs/{id}/wait until the handoff leaves open/pending, then
|
|
1675
|
-
// print it and return the state's exit code. Reuses the shared bounded hold.
|
|
1676
|
-
async function waitForHandoff(id, args, { token, apiBase }, initialDeliveryState) {
|
|
1677
|
-
const hold = resolveWaitHold(args, { def: 20, cap: 25 });
|
|
1678
|
-
|
|
1679
|
-
for (;;) {
|
|
1680
|
-
const started = Date.now();
|
|
1681
|
-
const url = `${apiBase}/api/agent/handoffs/${encodeURIComponent(id)}/wait?timeout=${hold}`;
|
|
1682
|
-
const { res, text, json } = await httpJson('GET', url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1683
|
-
if (!res.ok) {
|
|
1684
|
-
const detail = apiDetail(res, json);
|
|
1685
|
-
fail(`wait failed: ${detail}`);
|
|
1686
|
-
}
|
|
1687
|
-
if (json && json.state && !HANDOFF_PENDING.has(json.state)) {
|
|
1688
|
-
// Read/wait responses intentionally carry delivery_state=null. Preserve
|
|
1689
|
-
// the create response's durable delivery result so --wait callers and
|
|
1690
|
-
// the GitHub Action do not lose it at the terminal read boundary.
|
|
1691
|
-
const resolved = json.delivery_state == null && initialDeliveryState != null
|
|
1692
|
-
? { ...json, delivery_state: initialDeliveryState }
|
|
1693
|
-
: json;
|
|
1694
|
-
if (args.github_output !== undefined) writeGitHubHandoffOutputs(args.github_output, resolved);
|
|
1695
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1696
|
-
else printHandoff(resolved);
|
|
1697
|
-
return exitForHandoffState(resolved.state);
|
|
1698
|
-
}
|
|
1699
|
-
// Still open/pending at the hold timeout — poll again, with the same
|
|
1700
|
-
// hot-loop floor as waitForResolution.
|
|
1701
|
-
const elapsed = Date.now() - started;
|
|
1702
|
-
if (elapsed < 1000) await sleep(1000 - elapsed);
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
|
|
1706
|
-
async function handoff(args) {
|
|
1707
|
-
if (args.help) { process.stdout.write(`${commandHelp('handoff')}\n`); return EXIT.OK; }
|
|
1708
|
-
|
|
1709
|
-
const message = args.message;
|
|
1710
|
-
if (!message) fail('a --message is required', EXIT.USAGE);
|
|
1711
|
-
requireMaxLength(message, 500, '--message');
|
|
1712
|
-
|
|
1713
|
-
const { token, apiBase } = agentContext(args);
|
|
1714
|
-
|
|
1715
|
-
const options = buildOptions(args.option);
|
|
1716
|
-
// Any --option (or an explicit --question) makes this a question handoff.
|
|
1717
|
-
const isQuestion = Boolean(args.question) || Boolean(options);
|
|
1718
|
-
if (isQuestion && (!options || options.length < 2)) {
|
|
1719
|
-
fail('a question handoff needs at least 2 --option values', EXIT.USAGE);
|
|
1720
|
-
}
|
|
1721
|
-
if (isQuestion && options && options.length > 4) {
|
|
1722
|
-
fail('a question handoff accepts at most 4 --option values', EXIT.USAGE);
|
|
1723
|
-
}
|
|
1724
|
-
if (!isQuestion && options) {
|
|
1725
|
-
fail('--option requires --question', EXIT.USAGE);
|
|
1726
|
-
}
|
|
1727
|
-
|
|
1728
|
-
const body = { kind: isQuestion ? 'question' : 'ack', prompt: message };
|
|
1729
|
-
|
|
1730
|
-
const target = args.target || 'me';
|
|
1731
|
-
body.audience = { type: 'direct', user_id: target };
|
|
1732
|
-
|
|
1733
|
-
if (options) body.options = options;
|
|
1734
|
-
|
|
1735
|
-
if (args.expires_in !== undefined) {
|
|
1736
|
-
if (!/^\d+$/.test(String(args.expires_in))) fail('--expires-in must be an integer number of seconds', EXIT.USAGE);
|
|
1737
|
-
const secs = Number(args.expires_in);
|
|
1738
|
-
if (secs < 120 || secs > 86_400) fail('--expires-in must be between 120 and 86400 seconds', EXIT.USAGE);
|
|
1739
|
-
body.expires_in = secs;
|
|
1740
|
-
}
|
|
1741
|
-
if (args.urgency !== undefined) {
|
|
1742
|
-
if (args.urgency !== 'active' && args.urgency !== 'passive') fail("--urgency must be 'active' or 'passive'", EXIT.USAGE);
|
|
1743
|
-
body.urgency = args.urgency;
|
|
1744
|
-
}
|
|
1745
|
-
if (args.correlation_id !== undefined) body.correlation_id = args.correlation_id;
|
|
1746
|
-
if (args.reply_to !== undefined) body.reply_to = args.reply_to;
|
|
1747
|
-
if (args.data !== undefined) body.data = parseDataObject(args.data);
|
|
1748
|
-
|
|
1749
|
-
const headers = { Authorization: `Bearer ${token}` };
|
|
1750
|
-
// A stable Idempotency-Key lets network retries collapse to one resource; the
|
|
1751
|
-
// server returns the same handoff for a matching key+hash (409 on conflict).
|
|
1752
|
-
if (args.idempotency_key !== undefined) {
|
|
1753
|
-
if (!args.idempotency_key) fail('--idempotency-key must be non-empty', EXIT.USAGE);
|
|
1754
|
-
headers['Idempotency-Key'] = args.idempotency_key;
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
// Pre-flight: reject a bad --timeout before the handoff exists.
|
|
1758
|
-
if (args.wait) resolveWaitHold(args, { def: 20, cap: 25 });
|
|
1759
|
-
|
|
1760
|
-
const url = `${apiBase}/api/agent/handoffs`;
|
|
1761
|
-
const { res, text, json } = await httpJson('POST', url, { body, headers });
|
|
1762
|
-
if (!res.ok) {
|
|
1763
|
-
const code = json && json.code;
|
|
1764
|
-
const detail = apiDetail(res, json);
|
|
1765
|
-
// A recipient who isn't reachable yet is a distinct, retriable outcome (4),
|
|
1766
|
-
// not a generic error — CI may want to wait and retry rather than fail hard.
|
|
1767
|
-
if (res.status === 409 && code === 'recipient_not_ready') {
|
|
1768
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1769
|
-
else process.stderr.write(`pingroom: recipient not ready\n`);
|
|
1770
|
-
return EXIT.CANCELLED;
|
|
1771
|
-
}
|
|
1772
|
-
fail(`handoff failed: ${detail}`);
|
|
1773
|
-
}
|
|
1774
|
-
|
|
1775
|
-
if (!args.wait) {
|
|
1776
|
-
if (args.github_output !== undefined) writeGitHubHandoffOutputs(args.github_output, json);
|
|
1777
|
-
if (args.json) process.stdout.write(`${text}\n`);
|
|
1778
|
-
else printHandoff(json);
|
|
1779
|
-
return EXIT.OK;
|
|
1780
|
-
}
|
|
1781
|
-
|
|
1782
|
-
return waitForHandoff(json.id, args, { token, apiBase }, json.delivery_state);
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
|
-
// --- hook (Claude Code integration) ----------------------------------------
|
|
1786
|
-
//
|
|
1787
|
-
// A single command wired into several Claude Code hook events. It reads the
|
|
1788
|
-
// hook's JSON payload on stdin and switches on `hook_event_name`:
|
|
1789
|
-
// Stop / SubagentStop / SessionEnd -> ping the room ("Claude finished")
|
|
1790
|
-
// Notification -> ping the room (idle / needs-input)
|
|
1791
|
-
// PreToolUse -> ask a PingRoom question and gate the
|
|
1792
|
-
// tool call on the phone's Approve/Deny.
|
|
1793
|
-
//
|
|
1794
|
-
// Safety: the hook FAILS OPEN. It never blocks the agent and never
|
|
1795
|
-
// auto-approves. Any missing config / network error / non-answer defers to the
|
|
1796
|
-
// normal local prompt (PreToolUse -> permissionDecision "ask") and exits 0. It
|
|
1797
|
-
// must not call fail() (a non-zero exit — 2 especially — would break the run).
|
|
1798
|
-
|
|
1799
|
-
const parseHookArgs = makeParser({
|
|
1800
|
-
aliases: {
|
|
1801
|
-
'--room': 'room',
|
|
1802
|
-
'--ttl': 'ttl',
|
|
1803
|
-
'--quiet': 'quiet',
|
|
1804
|
-
'--print-config': 'print_config',
|
|
1805
|
-
'--token': 'token',
|
|
1806
|
-
'--api': 'api',
|
|
1807
|
-
'--json': 'json',
|
|
1808
|
-
'-h': 'help', '--help': 'help',
|
|
1809
|
-
},
|
|
1810
|
-
booleans: ['quiet', 'print_config', 'json', 'help'],
|
|
1811
|
-
bareDashIsPositional: true,
|
|
1812
|
-
});
|
|
1813
|
-
|
|
1814
|
-
// Read all of stdin as a string. Resolves '' when nothing is piped (TTY), so a
|
|
1815
|
-
// stray `pingroom hook` in a terminal is a silent no-op rather than a hang.
|
|
1816
|
-
function readStdin() {
|
|
1817
|
-
return new Promise((resolve) => {
|
|
1818
|
-
if (process.stdin.isTTY) { resolve(''); return; }
|
|
1819
|
-
let data = '';
|
|
1820
|
-
process.stdin.setEncoding('utf8');
|
|
1821
|
-
process.stdin.on('data', (chunk) => { data += chunk; });
|
|
1822
|
-
process.stdin.on('end', () => resolve(data));
|
|
1823
|
-
process.stdin.on('error', () => resolve(data));
|
|
1824
|
-
});
|
|
1825
|
-
}
|
|
1826
|
-
|
|
1827
|
-
function truncate(value, max) {
|
|
1828
|
-
const str = String(value ?? '');
|
|
1829
|
-
return str.length <= max ? str : `${str.slice(0, max - 1)}…`;
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
|
-
// A minimal HTTP helper for the hook path that THROWS instead of calling fail(),
|
|
1833
|
-
// so every failure funnels into a fail-open decision. Mirrors httpJson's header
|
|
1834
|
-
// handling but leaves control flow to the caller.
|
|
1835
|
-
async function hookFetch(method, url, { body, token } = {}) {
|
|
1836
|
-
const res = await fetch(url, {
|
|
1837
|
-
method,
|
|
1838
|
-
headers: {
|
|
1839
|
-
Accept: 'application/json',
|
|
1840
|
-
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
1841
|
-
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
1842
|
-
},
|
|
1843
|
-
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
1844
|
-
});
|
|
1845
|
-
const text = await res.text();
|
|
1846
|
-
let json = null;
|
|
1847
|
-
try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON response */ }
|
|
1848
|
-
if (!res.ok) {
|
|
1849
|
-
throw new Error(apiDetail(res, json));
|
|
1850
|
-
}
|
|
1851
|
-
return json;
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
// Pull the readable text out of a Claude transcript message's content, which is
|
|
1855
|
-
// either a plain string or an array of typed blocks.
|
|
1856
|
-
function extractAssistantText(content) {
|
|
1857
|
-
if (typeof content === 'string') return content;
|
|
1858
|
-
if (Array.isArray(content)) {
|
|
1859
|
-
return content
|
|
1860
|
-
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
1861
|
-
.map((b) => b.text)
|
|
1862
|
-
.join(' ');
|
|
1863
|
-
}
|
|
1864
|
-
return '';
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
// Tail a Claude Code transcript (JSONL) and return the last assistant message as
|
|
1868
|
-
// a single truncated line. Best-effort: any read/parse failure yields ''.
|
|
1869
|
-
function summarizeTranscript(path) {
|
|
1870
|
-
if (!path || typeof path !== 'string') return '';
|
|
1871
|
-
let content;
|
|
1872
|
-
try { content = readFileSync(path, 'utf8'); } catch { return ''; }
|
|
1873
|
-
const lines = content.split('\n');
|
|
1874
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1875
|
-
const line = lines[i].trim();
|
|
1876
|
-
if (!line) continue;
|
|
1877
|
-
let entry;
|
|
1878
|
-
try { entry = JSON.parse(line); } catch { continue; }
|
|
1879
|
-
const msg = entry && entry.message;
|
|
1880
|
-
if (!msg || msg.role !== 'assistant') continue;
|
|
1881
|
-
const text = extractAssistantText(msg.content).replace(/\s+/g, ' ').trim();
|
|
1882
|
-
if (text) return truncate(text, 500);
|
|
1883
|
-
}
|
|
1884
|
-
return '';
|
|
1885
|
-
}
|
|
1886
|
-
|
|
1887
|
-
// A short, single-line description of the tool call for the question prompt.
|
|
1888
|
-
// Never emits more than a truncated line, and strips whitespace/newlines so an
|
|
1889
|
-
// untrusted command can't reshape the message.
|
|
1890
|
-
function summarizeToolInput(input) {
|
|
1891
|
-
if (!input || typeof input !== 'object') return '';
|
|
1892
|
-
let raw = '';
|
|
1893
|
-
if (typeof input.command === 'string') raw = input.command; // Bash
|
|
1894
|
-
else if (typeof input.file_path === 'string') raw = input.file_path; // Read/Write/Edit
|
|
1895
|
-
else if (typeof input.path === 'string') raw = input.path;
|
|
1896
|
-
else if (typeof input.url === 'string') raw = input.url; // WebFetch
|
|
1897
|
-
else if (typeof input.pattern === 'string') raw = input.pattern; // Grep/Glob
|
|
1898
|
-
else { try { raw = JSON.stringify(input); } catch { raw = ''; } }
|
|
1899
|
-
return truncate(String(raw).replace(/\s+/g, ' ').trim(), 160);
|
|
1900
|
-
}
|
|
1901
|
-
|
|
1902
|
-
function emitPreToolUseDecision(decision, reason) {
|
|
1903
|
-
process.stdout.write(`${JSON.stringify({
|
|
1904
|
-
hookSpecificOutput: {
|
|
1905
|
-
hookEventName: 'PreToolUse',
|
|
1906
|
-
permissionDecision: decision,
|
|
1907
|
-
permissionDecisionReason: reason,
|
|
1908
|
-
},
|
|
1909
|
-
})}\n`);
|
|
1910
|
-
}
|
|
1911
|
-
|
|
1912
|
-
// Long-poll the wait endpoint until the question leaves `pending`. The server
|
|
1913
|
-
// expires it at its ttl, so this always terminates; a mid-poll throw propagates
|
|
1914
|
-
// to the caller's fail-open handler.
|
|
1915
|
-
async function hookWaitForAnswer(id, { token, apiBase }) {
|
|
1916
|
-
for (;;) {
|
|
1917
|
-
const url = `${apiBase}/api/agent/questions/${encodeURIComponent(id)}/wait?timeout=25`;
|
|
1918
|
-
const json = await hookFetch('GET', url, { token });
|
|
1919
|
-
if (json && json.state && json.state !== 'pending') return json;
|
|
1920
|
-
}
|
|
1921
|
-
}
|
|
1922
|
-
|
|
1923
|
-
async function hookPreToolUse(event, { token, room, apiBase, args }) {
|
|
1924
|
-
if (!token || !room) {
|
|
1925
|
-
emitPreToolUseDecision('ask', 'PingRoom not configured (pair by QR, or configure both a token and room)');
|
|
1926
|
-
return EXIT.OK;
|
|
1927
|
-
}
|
|
1928
|
-
|
|
1929
|
-
const toolName = event.tool_name || 'a tool';
|
|
1930
|
-
const summary = summarizeToolInput(event.tool_input);
|
|
1931
|
-
const prompt = truncate(`Run ${toolName}${summary ? `: ${summary}` : ''}?`, 500);
|
|
1932
|
-
|
|
1933
|
-
let ttl = 900;
|
|
1934
|
-
if (args.ttl !== undefined && /^\d+$/.test(String(args.ttl))) ttl = Number(args.ttl);
|
|
1935
|
-
|
|
1936
|
-
let questionId;
|
|
1937
|
-
let cancelled = false;
|
|
1938
|
-
const cancelQuestion = async () => {
|
|
1939
|
-
if (!questionId || cancelled) return;
|
|
1940
|
-
cancelled = true;
|
|
1941
|
-
try {
|
|
1942
|
-
await hookFetch('POST', `${apiBase}/api/agent/questions/${encodeURIComponent(questionId)}/cancel`, { body: {}, token });
|
|
1943
|
-
} catch { /* best-effort — a leftover question expires on its own ttl */ }
|
|
1944
|
-
};
|
|
1945
|
-
// If the agent aborts the tool call, withdraw the question so it doesn't linger
|
|
1946
|
-
// on the phone. Exit 0 so the abort itself isn't reported as a hook failure.
|
|
1947
|
-
const onSignal = () => { cancelQuestion().finally(() => process.exit(EXIT.OK)); };
|
|
1948
|
-
process.on('SIGINT', onSignal);
|
|
1949
|
-
process.on('SIGTERM', onSignal);
|
|
1950
|
-
|
|
1951
|
-
try {
|
|
1952
|
-
const data = { tool_name: String(toolName) };
|
|
1953
|
-
if (event.cwd) data.cwd = String(event.cwd);
|
|
1954
|
-
const created = await hookFetch('POST', `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/questions`, {
|
|
1955
|
-
token,
|
|
1956
|
-
body: {
|
|
1957
|
-
prompt,
|
|
1958
|
-
context: 'Claude Code',
|
|
1959
|
-
options: [
|
|
1960
|
-
{ value: 'allow', label: 'Approve', style: 'primary' },
|
|
1961
|
-
{ value: 'deny', label: 'Deny', style: 'danger' },
|
|
1962
|
-
],
|
|
1963
|
-
ttl,
|
|
1964
|
-
data,
|
|
1965
|
-
...(event.session_id ? { correlation_id: String(event.session_id) } : {}),
|
|
1966
|
-
},
|
|
1967
|
-
});
|
|
1968
|
-
questionId = created && created.id;
|
|
1969
|
-
if (!questionId) {
|
|
1970
|
-
emitPreToolUseDecision('ask', 'PingRoom did not return a question — deferring to local prompt');
|
|
1971
|
-
return EXIT.OK;
|
|
1972
|
-
}
|
|
1973
|
-
|
|
1974
|
-
const resolved = await hookWaitForAnswer(questionId, { token, apiBase });
|
|
1975
|
-
if (resolved.state === 'answered') {
|
|
1976
|
-
const value = resolved.answer && (resolved.answer.value || resolved.answer.text);
|
|
1977
|
-
if (value === 'allow') { emitPreToolUseDecision('allow', 'Approved via PingRoom'); return EXIT.OK; }
|
|
1978
|
-
if (value === 'deny') { emitPreToolUseDecision('deny', 'Denied via PingRoom'); return EXIT.OK; }
|
|
1979
|
-
emitPreToolUseDecision('ask', `PingRoom answer "${value}" — deferring to local prompt`);
|
|
1980
|
-
return EXIT.OK;
|
|
1981
|
-
}
|
|
1982
|
-
emitPreToolUseDecision('ask', `PingRoom question ${resolved.state} — deferring to local prompt`);
|
|
1983
|
-
return EXIT.OK;
|
|
1984
|
-
} catch (err) {
|
|
1985
|
-
emitPreToolUseDecision('ask', `PingRoom unavailable (${err.message}) — deferring to local prompt`);
|
|
1986
|
-
return EXIT.OK;
|
|
1987
|
-
} finally {
|
|
1988
|
-
process.removeListener('SIGINT', onSignal);
|
|
1989
|
-
process.removeListener('SIGTERM', onSignal);
|
|
1990
|
-
}
|
|
1991
|
-
}
|
|
1992
|
-
|
|
1993
|
-
async function hookNotify(event, name, { token, room, apiBase, args }) {
|
|
1994
|
-
if (!token || !room) {
|
|
1995
|
-
if (!args.quiet) process.stderr.write('pingroom: hook skipped (pair by QR, or configure both a token and room)\n');
|
|
1996
|
-
return EXIT.OK;
|
|
1997
|
-
}
|
|
1998
|
-
|
|
1999
|
-
let title;
|
|
2000
|
-
let message;
|
|
2001
|
-
if (name === 'Stop' || name === 'SubagentStop') {
|
|
2002
|
-
title = 'Claude finished';
|
|
2003
|
-
message = summarizeTranscript(event.transcript_path) || 'Session finished — waiting for you.';
|
|
2004
|
-
} else if (name === 'Notification') {
|
|
2005
|
-
message = truncate(event.message || 'Claude is waiting for your input.', 500);
|
|
2006
|
-
// A PreToolUse hook already turns permission prompts into a question; skip
|
|
2007
|
-
// the duplicate "needs your permission" Notification so you aren't paged twice.
|
|
2008
|
-
if (/permission/i.test(message)) return EXIT.OK;
|
|
2009
|
-
title = 'Claude needs you';
|
|
2010
|
-
} else if (name === 'SessionEnd') {
|
|
2011
|
-
if (event.reason === 'clear') return EXIT.OK; // /clear isn't worth a ping
|
|
2012
|
-
title = 'Session ended';
|
|
2013
|
-
message = `Claude Code session ended (${event.reason || 'unknown'}).`;
|
|
2014
|
-
} else {
|
|
2015
|
-
return EXIT.OK; // unknown event — stay silent rather than send noise
|
|
2016
|
-
}
|
|
2017
|
-
|
|
2018
|
-
const data = { event: name };
|
|
2019
|
-
if (event.session_id) data.session_id = String(event.session_id);
|
|
2020
|
-
if (event.cwd) data.cwd = String(event.cwd);
|
|
2021
|
-
|
|
2022
|
-
try {
|
|
2023
|
-
await hookFetch('POST', `${apiBase}/api/agent/rooms/${encodeURIComponent(room)}/notifications`, {
|
|
2024
|
-
token,
|
|
2025
|
-
body: {
|
|
2026
|
-
message,
|
|
2027
|
-
title,
|
|
2028
|
-
data,
|
|
2029
|
-
...(event.session_id ? { correlation_id: String(event.session_id) } : {}),
|
|
2030
|
-
},
|
|
2031
|
-
});
|
|
2032
|
-
if (!args.quiet) process.stderr.write('pingroom: pinged ✅\n');
|
|
2033
|
-
} catch (err) {
|
|
2034
|
-
// A broken ping must never break the agent — report to stderr and exit 0.
|
|
2035
|
-
if (!args.quiet) process.stderr.write(`pingroom: hook ping failed (${err.message})\n`);
|
|
2036
|
-
}
|
|
2037
|
-
return EXIT.OK;
|
|
2038
|
-
}
|
|
2039
|
-
|
|
2040
|
-
function printHookConfig() {
|
|
2041
|
-
const command = `npx --yes @pingroom/cli@${VERSION} hook`;
|
|
2042
|
-
const config = {
|
|
2043
|
-
hooks: {
|
|
2044
|
-
Stop: [{ hooks: [{ type: 'command', command }] }],
|
|
2045
|
-
Notification: [{ hooks: [{ type: 'command', command }] }],
|
|
2046
|
-
PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command, timeout: 960 }] }],
|
|
2047
|
-
},
|
|
2048
|
-
};
|
|
2049
|
-
process.stdout.write(
|
|
2050
|
-
`# PingRoom × Claude Code — merge this into ~/.claude/settings.json
|
|
2051
|
-
#
|
|
2052
|
-
# 1. Connect once and choose a delivery room when you scan the QR:
|
|
2053
|
-
# npm install --global @pingroom/cli && pingroom
|
|
2054
|
-
# Or, without a global install:
|
|
2055
|
-
# npx --yes @pingroom/cli@${VERSION}
|
|
2056
|
-
# The hook reads that stored credential and paired room automatically; you do
|
|
2057
|
-
# not need to export PINGROOM_TOKEN or PINGROOM_ROOM for a local setup.
|
|
2058
|
-
#
|
|
2059
|
-
# 2. Merge the "hooks" block below into ~/.claude/settings.json.
|
|
2060
|
-
# Stop / Notification -> ping your phone.
|
|
2061
|
-
# PreToolUse (Bash) -> ask a question you Approve/Deny from the lock
|
|
2062
|
-
# screen before the command runs. Add or change the
|
|
2063
|
-
# matcher to gate other tools.
|
|
2064
|
-
#
|
|
2065
|
-
# If PingRoom is unreachable the hook defers to the normal local prompt — it
|
|
2066
|
-
# never auto-approves and never blocks the agent.
|
|
2067
|
-
# PINGROOM_TOKEN / PINGROOM_ROOM remain supported for CI and headless shells.
|
|
2068
|
-
|
|
2069
|
-
${JSON.stringify(config, null, 2)}
|
|
2070
|
-
`);
|
|
2071
|
-
}
|
|
2072
|
-
|
|
2073
|
-
async function hook(args) {
|
|
2074
|
-
if (args.help) { process.stdout.write(`${commandHelp('hook')}\n`); return EXIT.OK; }
|
|
2075
|
-
if (args.print_config) { printHookConfig(); return EXIT.OK; }
|
|
2076
|
-
|
|
2077
|
-
let event = {};
|
|
2078
|
-
const raw = await readStdin();
|
|
2079
|
-
if (raw) { try { event = JSON.parse(raw); } catch { event = {}; } }
|
|
2080
|
-
const name = event.hook_event_name || '';
|
|
2081
|
-
|
|
2082
|
-
// The hook fails open, so it reads the same layered config as everything else
|
|
2083
|
-
// but never complains about a missing piece — it just defers.
|
|
2084
|
-
const token = resolveToken(args);
|
|
2085
|
-
const room = resolveRoom(args);
|
|
2086
|
-
const apiBase = resolveApiBase(args);
|
|
2087
|
-
|
|
2088
|
-
const originError = storedCredentialOriginError(args, apiBase);
|
|
2089
|
-
if (originError) {
|
|
2090
|
-
if (name === 'PreToolUse') {
|
|
2091
|
-
emitPreToolUseDecision('ask', `${originError}; deferring to local prompt`);
|
|
2092
|
-
} else if (!args.quiet) {
|
|
2093
|
-
process.stderr.write(`pingroom: hook skipped (${originError})\n`);
|
|
2094
|
-
}
|
|
2095
|
-
return EXIT.OK;
|
|
2096
|
-
}
|
|
2097
|
-
|
|
2098
|
-
// Every other command that attaches a bearer gates its base through
|
|
2099
|
-
// requireSafeUrl first; the hook was the one that didn't, so a config or env
|
|
2100
|
-
// pointing at plain http shipped `Authorization: Bearer …` in the clear with
|
|
2101
|
-
// nothing on screen. Same rule here — but enforced by deferring, not by
|
|
2102
|
-
// exiting: the hook's whole contract is that it never blocks the agent, so a
|
|
2103
|
-
// hard failure would trade a credential leak for a broken session.
|
|
2104
|
-
if (!isSafeUrl(apiBase)) {
|
|
2105
|
-
const why = `${apiBase} is not https — refusing to send credentials over cleartext`;
|
|
2106
|
-
if (name === 'PreToolUse') {
|
|
2107
|
-
emitPreToolUseDecision('ask', `PingRoom API base ${why}; deferring to local prompt`);
|
|
2108
|
-
} else if (!args.quiet) {
|
|
2109
|
-
process.stderr.write(`pingroom: hook skipped (API base ${why})\n`);
|
|
2110
|
-
}
|
|
2111
|
-
return EXIT.OK;
|
|
2112
|
-
}
|
|
2113
|
-
|
|
2114
|
-
if (name === 'PreToolUse') {
|
|
2115
|
-
return hookPreToolUse(event, { token, room, apiBase, args });
|
|
2116
|
-
}
|
|
2117
|
-
return hookNotify(event, name, { token, room, apiBase, args });
|
|
2118
|
-
}
|
|
2119
|
-
|
|
2120
|
-
// --- MCP client setup ------------------------------------------------------
|
|
2121
|
-
|
|
2122
|
-
function mcp(rest) {
|
|
2123
|
-
const claudeCommand = `claude mcp add --transport http pingroom ${MCP_ENDPOINT}`;
|
|
2124
|
-
|
|
2125
|
-
if (rest.length === 0 || (rest.length === 1 && (rest[0] === '-h' || rest[0] === '--help'))) {
|
|
2126
|
-
const config = {
|
|
2127
|
-
mcpServers: {
|
|
2128
|
-
pingroom: { url: MCP_ENDPOINT },
|
|
2129
|
-
},
|
|
2130
|
-
};
|
|
2131
|
-
process.stdout.write(
|
|
2132
|
-
`PingRoom MCP endpoint:
|
|
2133
|
-
${MCP_ENDPOINT}
|
|
2134
|
-
|
|
2135
|
-
Claude Code:
|
|
2136
|
-
${claudeCommand}
|
|
2137
|
-
|
|
2138
|
-
Cursor JSON (~/.cursor/mcp.json):
|
|
2139
|
-
${JSON.stringify(config, null, 2)}
|
|
2140
|
-
|
|
2141
|
-
Claude Desktop:
|
|
2142
|
-
Customize > Connectors > Add custom connector
|
|
2143
|
-
Name: PingRoom
|
|
2144
|
-
URL: ${MCP_ENDPOINT}
|
|
2145
|
-
|
|
2146
|
-
After adding the server, use your client's MCP controls to authenticate in the
|
|
2147
|
-
browser. No API key is needed.
|
|
2148
|
-
This command only prints setup instructions and does not modify client config.
|
|
2149
|
-
`);
|
|
2150
|
-
return EXIT.OK;
|
|
2151
|
-
}
|
|
2152
|
-
|
|
2153
|
-
if (rest.length === 2 && rest[0] === 'add' && rest[1] === 'claude-code') {
|
|
2154
|
-
process.stdout.write(
|
|
2155
|
-
`No client configuration was changed. Copy and run:
|
|
2156
|
-
${claudeCommand}
|
|
2157
|
-
`);
|
|
2158
|
-
return EXIT.OK;
|
|
2159
|
-
}
|
|
2160
|
-
|
|
2161
|
-
fail('usage: pingroom mcp [add claude-code]', EXIT.USAGE);
|
|
2162
|
-
}
|
|
2163
|
-
|
|
2164
|
-
// --- connecting (pairing + email fallback) ---------------------------------
|
|
2165
32
|
//
|
|
2166
|
-
//
|
|
2167
|
-
//
|
|
2168
|
-
//
|
|
2169
|
-
//
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
// A connect command should prove the phone round-trip, but it must not hold a
|
|
2189
|
-
// terminal for the onboarding Question's full 24-hour server TTL. The Question
|
|
2190
|
-
// remains answerable after this local deadline and the credential is already
|
|
2191
|
-
// durable before the wait begins.
|
|
2192
|
-
const ACTIVATION_MAX_WAIT_MS = 2 * 60 * 1000;
|
|
2193
|
-
// The wait route is limited to 30 requests/minute. Keep immediate pending or
|
|
2194
|
-
// answered-without-completion observations safely below that ceiling while a
|
|
2195
|
-
// mixed-version or commit-propagation race is still being reconciled.
|
|
2196
|
-
const ACTIVATION_MIN_POLL_INTERVAL_MS = 2100;
|
|
2197
|
-
|
|
2198
|
-
function activationMaxWaitMs() {
|
|
2199
|
-
// Keep production fixed at two minutes. The guarded override lets the real
|
|
2200
|
-
// subprocess tests exercise deadline behavior without holding the suite for
|
|
2201
|
-
// two minutes; it is ignored outside NODE_ENV=test.
|
|
2202
|
-
if (process.env.NODE_ENV === 'test') {
|
|
2203
|
-
const testValue = Number(process.env.PINGROOM_INTERNAL_ACTIVATION_TIMEOUT_MS);
|
|
2204
|
-
if (Number.isInteger(testValue) && testValue > 0 && testValue <= ACTIVATION_MAX_WAIT_MS) {
|
|
2205
|
-
return testValue;
|
|
2206
|
-
}
|
|
2207
|
-
}
|
|
2208
|
-
return ACTIVATION_MAX_WAIT_MS;
|
|
2209
|
-
}
|
|
2210
|
-
|
|
2211
|
-
// Widest QR we render (compact half-block form of a ~110-char pair URL is 39
|
|
2212
|
-
// columns). Anything narrower would wrap and become unscannable, so we print
|
|
2213
|
-
// the URL alone instead of a broken QR.
|
|
2214
|
-
const QR_MIN_COLUMNS = 41;
|
|
2215
|
-
|
|
2216
|
-
/**
|
|
2217
|
-
* Draw the pair URL as a scannable QR. Returns false when it could not — a too
|
|
2218
|
-
* narrow terminal, or the optional dependency being absent (someone vendored
|
|
2219
|
-
* just bin/) — and the caller falls back to the printed URL, which always works.
|
|
2220
|
-
*/
|
|
2221
|
-
async function renderQr(url) {
|
|
2222
|
-
// A real terminal reports its width on the stream; COLUMNS covers the rest.
|
|
2223
|
-
// Unknown width is treated as wide enough — the URL is printed either way.
|
|
2224
|
-
const columns = Number(process.stdout.columns || process.env.COLUMNS || 0);
|
|
2225
|
-
if (columns > 0 && columns < QR_MIN_COLUMNS) return false;
|
|
2226
|
-
|
|
2227
|
-
let qr;
|
|
2228
|
-
try {
|
|
2229
|
-
const mod = await import('qrcode-terminal');
|
|
2230
|
-
qr = mod.default || mod;
|
|
2231
|
-
} catch { return false; }
|
|
2232
|
-
if (!qr || typeof qr.generate !== 'function') return false;
|
|
2233
|
-
|
|
2234
|
-
try {
|
|
2235
|
-
let art = '';
|
|
2236
|
-
// Call it as a method: qrcode-terminal reads its error-correction level off
|
|
2237
|
-
// `this`, so a detached `generate` reference silently builds a version-1
|
|
2238
|
-
// code and throws on anything longer than a few characters.
|
|
2239
|
-
// `small` is the half-block form: two module rows per text row, so the code
|
|
2240
|
-
// stays square-ish and fits an 80-column terminal.
|
|
2241
|
-
qr.generate(url, { small: true }, (rendered) => { art = rendered; });
|
|
2242
|
-
if (!art) return false;
|
|
2243
|
-
process.stdout.write(`\n${art}\n`);
|
|
2244
|
-
return true;
|
|
2245
|
-
} catch { return false; }
|
|
2246
|
-
}
|
|
2247
|
-
|
|
2248
|
-
/**
|
|
2249
|
-
* A line-at-a-time reader over stdin.
|
|
2250
|
-
*
|
|
2251
|
-
* Deliberately not node:readline: its Interface keeps consuming while we are
|
|
2252
|
-
* awaiting an HTTP round trip between two questions and drops the lines nobody
|
|
2253
|
-
* is listening for, which silently loses piped answers. This queues every line
|
|
2254
|
-
* instead, so the answers can arrive in one blob or one keystroke at a time.
|
|
2255
|
-
*
|
|
2256
|
-
* ask() resolves `null` — never a string — once the input is closed, so it can
|
|
2257
|
-
* never be confused with a real empty line. That distinction is load-bearing:
|
|
2258
|
-
* callers treat an empty line as "take the default", and a caller that reads EOF
|
|
2259
|
-
* as an empty line will take that default again on the next question, and the
|
|
2260
|
-
* next, forever, because nothing will ever arrive to change its mind. Callers
|
|
2261
|
-
* that genuinely want the empty-line behaviour opt in with `?? ''`.
|
|
2262
|
-
*/
|
|
2263
|
-
function createPrompter() {
|
|
2264
|
-
const queued = [];
|
|
2265
|
-
const waiting = [];
|
|
2266
|
-
let buffer = '';
|
|
2267
|
-
let closed = false;
|
|
2268
|
-
|
|
2269
|
-
const deliver = (line) => {
|
|
2270
|
-
const waiter = waiting.shift();
|
|
2271
|
-
if (waiter) waiter(line);
|
|
2272
|
-
else queued.push(line);
|
|
2273
|
-
};
|
|
2274
|
-
const onData = (chunk) => {
|
|
2275
|
-
buffer += chunk;
|
|
2276
|
-
let idx;
|
|
2277
|
-
while ((idx = buffer.indexOf('\n')) !== -1) {
|
|
2278
|
-
deliver(buffer.slice(0, idx).replace(/\r$/, ''));
|
|
2279
|
-
buffer = buffer.slice(idx + 1);
|
|
2280
|
-
}
|
|
2281
|
-
};
|
|
2282
|
-
const onEnd = () => {
|
|
2283
|
-
if (closed) return;
|
|
2284
|
-
closed = true;
|
|
2285
|
-
if (buffer) { deliver(buffer); buffer = ''; }
|
|
2286
|
-
while (waiting.length) waiting.shift()(null);
|
|
2287
|
-
};
|
|
2288
|
-
|
|
2289
|
-
process.stdin.setEncoding('utf8');
|
|
2290
|
-
process.stdin.on('data', onData);
|
|
2291
|
-
process.stdin.once('end', onEnd);
|
|
2292
|
-
process.stdin.resume();
|
|
2293
|
-
|
|
2294
|
-
return {
|
|
2295
|
-
ask(question) {
|
|
2296
|
-
process.stdout.write(question);
|
|
2297
|
-
if (queued.length > 0) return Promise.resolve(queued.shift());
|
|
2298
|
-
if (closed) return Promise.resolve(null);
|
|
2299
|
-
return new Promise((resolve) => { waiting.push(resolve); });
|
|
2300
|
-
},
|
|
2301
|
-
close() {
|
|
2302
|
-
process.stdin.off('data', onData);
|
|
2303
|
-
process.stdin.off('end', onEnd);
|
|
2304
|
-
process.stdin.pause();
|
|
2305
|
-
},
|
|
2306
|
-
};
|
|
2307
|
-
}
|
|
2308
|
-
|
|
2309
|
-
/** POST /api/agent/auth — anonymous registration, yields the pre-claim credential. */
|
|
2310
|
-
async function registerAnonymous(apiBase) {
|
|
2311
|
-
const { res, json } = await httpJson('POST', `${apiBase}/api/agent/auth`, {
|
|
2312
|
-
body: { type: 'anonymous', agent_label: AGENT_LABEL, scopes: CLI_SCOPES },
|
|
2313
|
-
});
|
|
2314
|
-
if (!res.ok || !json || typeof json.credential !== 'string') {
|
|
2315
|
-
const detail = apiDetail(res, json);
|
|
2316
|
-
fail(`could not start a connection: ${detail}`);
|
|
2317
|
-
}
|
|
2318
|
-
return json.credential;
|
|
2319
|
-
}
|
|
2320
|
-
|
|
2321
|
-
/** Persist the active credential plus the bits the status line prints. */
|
|
2322
|
-
function saveCredential({ token, handle, room, rooms, roomAccess, account, scopes, apiBase }) {
|
|
2323
|
-
writeJsonFile(credentialsPath(), {
|
|
2324
|
-
version: 1,
|
|
2325
|
-
token,
|
|
2326
|
-
handle: handle || null,
|
|
2327
|
-
// `room` is the delivery room — where handoffs and questions land. `rooms`
|
|
2328
|
-
// is the whole grant, which can be wider; `room_access: "all"` means the
|
|
2329
|
-
// human granted every room they are in, listing none.
|
|
2330
|
-
room: room || null,
|
|
2331
|
-
rooms: Array.isArray(rooms) ? rooms : [],
|
|
2332
|
-
room_access: roomAccess || null,
|
|
2333
|
-
account: account || null,
|
|
2334
|
-
scopes: scopes || [],
|
|
2335
|
-
api_url: apiBase,
|
|
2336
|
-
created_at: new Date().toISOString(),
|
|
2337
|
-
});
|
|
2338
|
-
}
|
|
2339
|
-
|
|
2340
|
-
/**
|
|
2341
|
-
* "✓ Connected as @agt_ab12 → #Project X" — the room half is omitted if unknown,
|
|
2342
|
-
* and widened to "→ all rooms" / "→ #Project X +2 more" when the human granted
|
|
2343
|
-
* this agent more than the one delivery room.
|
|
2344
|
-
*/
|
|
2345
|
-
function connectedLine(cred) {
|
|
2346
|
-
const who = cred.handle ? `@${cred.handle}` : 'this machine';
|
|
2347
|
-
const room = cred.room && (cred.room.name || cred.room.invite_code);
|
|
2348
|
-
const access = cred.room_access ?? cred.roomAccess;
|
|
2349
|
-
|
|
2350
|
-
if (access === 'all') return `✓ Connected as ${who} → all rooms`;
|
|
2351
|
-
|
|
2352
|
-
if (!room) return `✓ Connected as ${who}`;
|
|
2353
|
-
|
|
2354
|
-
const extra = Math.max(0, (Array.isArray(cred.rooms) ? cred.rooms.length : 0) - 1);
|
|
2355
|
-
return `✓ Connected as ${who} → #${room}${extra > 0 ? ` +${extra} more` : ''}`;
|
|
2356
|
-
}
|
|
2357
|
-
|
|
2358
|
-
function activationFailureDetail(result) {
|
|
2359
|
-
if (result.error) return result.error.message;
|
|
2360
|
-
const status = result.res ? `HTTP ${result.res.status}` : 'request failed';
|
|
2361
|
-
return (result.json && (result.json.message || result.json.error || result.json.code)) || status;
|
|
2362
|
-
}
|
|
2363
|
-
|
|
2364
|
-
function isJsonObject(value) {
|
|
2365
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
2366
|
-
}
|
|
2367
|
-
|
|
2368
|
-
function isNonEmptyString(value) {
|
|
2369
|
-
return typeof value === 'string' && value.trim() !== '';
|
|
2370
|
-
}
|
|
2371
|
-
|
|
2372
|
-
function isNullableString(value) {
|
|
2373
|
-
return value === null || typeof value === 'string';
|
|
2374
|
-
}
|
|
2375
|
-
|
|
2376
|
-
function validateActivationEnsure(json) {
|
|
2377
|
-
const room = json?.room;
|
|
2378
|
-
const question = json?.question;
|
|
2379
|
-
const validState = question?.state === 'pending'
|
|
2380
|
-
|| question?.state === 'answered'
|
|
2381
|
-
|| question?.state === 'expired'
|
|
2382
|
-
|| question?.state === 'cancelled';
|
|
2383
|
-
if (
|
|
2384
|
-
!isJsonObject(json)
|
|
2385
|
-
|| json.onboarded !== true
|
|
2386
|
-
|| typeof json.replayed !== 'boolean'
|
|
2387
|
-
|| !isJsonObject(room)
|
|
2388
|
-
|| !isNonEmptyString(room.id)
|
|
2389
|
-
|| typeof room.name !== 'string'
|
|
2390
|
-
|| !isNonEmptyString(room.invite_code)
|
|
2391
|
-
|| typeof room.is_agent_inbox !== 'boolean'
|
|
2392
|
-
|| !isJsonObject(question)
|
|
2393
|
-
|| !isNonEmptyString(question.id)
|
|
2394
|
-
|| question.kind !== 'question'
|
|
2395
|
-
|| !isNonEmptyString(question.prompt)
|
|
2396
|
-
|| !Array.isArray(question.options)
|
|
2397
|
-
|| question.options.some((option) => (
|
|
2398
|
-
!isJsonObject(option)
|
|
2399
|
-
|| !isNonEmptyString(option.value)
|
|
2400
|
-
|| !isNonEmptyString(option.label)
|
|
2401
|
-
))
|
|
2402
|
-
|| !validState
|
|
2403
|
-
|| !isNullableString(question.expires_at)
|
|
2404
|
-
|| !isNullableString(question.created_at)
|
|
2405
|
-
) {
|
|
2406
|
-
return { error: 'PingRoom returned an incomplete Agent Inbox ensure response' };
|
|
2407
|
-
}
|
|
2408
|
-
return { question };
|
|
2409
|
-
}
|
|
2410
|
-
|
|
2411
|
-
function validateActivationWait(json, questionId) {
|
|
2412
|
-
const state = json?.state;
|
|
2413
|
-
const validState = state === 'pending' || state === 'answered' || state === 'expired' || state === 'cancelled';
|
|
2414
|
-
if (
|
|
2415
|
-
!isJsonObject(json)
|
|
2416
|
-
|| !isNonEmptyString(json.id)
|
|
2417
|
-
|| json.id !== questionId
|
|
2418
|
-
|| json.kind !== 'question'
|
|
2419
|
-
|| !validState
|
|
2420
|
-
|| (json.activation_completed !== undefined && typeof json.activation_completed !== 'boolean')
|
|
2421
|
-
|| (state !== 'answered' && json.activation_completed === true)
|
|
2422
|
-
) {
|
|
2423
|
-
return { error: 'PingRoom returned a mismatched Agent Inbox wait response' };
|
|
2424
|
-
}
|
|
2425
|
-
|
|
2426
|
-
if (state === 'answered') {
|
|
2427
|
-
const answer = json.answer;
|
|
2428
|
-
const responder = answer?.responder;
|
|
2429
|
-
if (
|
|
2430
|
-
!isJsonObject(answer)
|
|
2431
|
-
|| !isNullableString(answer.value)
|
|
2432
|
-
|| !isNullableString(answer.label)
|
|
2433
|
-
|| !isNullableString(answer.text)
|
|
2434
|
-
|| (!isNonEmptyString(answer.value) && !isNonEmptyString(answer.text))
|
|
2435
|
-
|| !isNullableString(answer.answered_at)
|
|
2436
|
-
|| (responder !== null && !isJsonObject(responder))
|
|
2437
|
-
|| (isJsonObject(responder)
|
|
2438
|
-
&& (!isNullableString(responder.id) || !isNullableString(responder.display_name)))
|
|
2439
|
-
) {
|
|
2440
|
-
return { error: 'PingRoom returned an answered activation without a valid answer' };
|
|
2441
|
-
}
|
|
2442
|
-
} else if (json.answer !== undefined && json.answer !== null) {
|
|
2443
|
-
return { error: 'PingRoom returned an answer for an unresolved activation' };
|
|
2444
|
-
}
|
|
2445
|
-
|
|
2446
|
-
return { value: json };
|
|
2447
|
-
}
|
|
2448
|
-
|
|
2449
|
-
function retryAfterMs(response) {
|
|
2450
|
-
const raw = response?.headers?.get('retry-after')?.trim();
|
|
2451
|
-
if (!raw) return null;
|
|
2452
|
-
if (/^\d+(?:\.\d+)?$/.test(raw)) return Number(raw) * 1000;
|
|
2453
|
-
const at = Date.parse(raw);
|
|
2454
|
-
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
|
|
2455
|
-
}
|
|
2456
|
-
|
|
2457
|
-
function activationRetryDelay(result, transientRun, deadline) {
|
|
2458
|
-
const fromHeader = result.res?.status === 429 ? retryAfterMs(result.res) : null;
|
|
2459
|
-
const fallback = Math.min(1000 * 2 ** Math.max(0, transientRun - 1), 10_000);
|
|
2460
|
-
return Math.max(0, Math.min(fromHeader ?? fallback, deadline - Date.now()));
|
|
2461
|
-
}
|
|
2462
|
-
|
|
2463
|
-
function activationIncomplete(detail, instruction = 'Run "pingroom activate" to retry with this saved connection.') {
|
|
2464
|
-
const safeDetail = detail ? `: ${stripControlChars(detail)}` : '';
|
|
2465
|
-
process.stdout.write(` Agent Inbox activation is not complete${safeDetail}\n`);
|
|
2466
|
-
process.stdout.write(' Your connection is saved and usable.\n');
|
|
2467
|
-
process.stdout.write(` ${instruction}\n`);
|
|
2468
|
-
}
|
|
2469
|
-
|
|
2470
|
-
/**
|
|
2471
|
-
* Prove the freshly paired credential can complete a human round-trip. This is
|
|
2472
|
-
* intentionally best-effort: saveCredential() has already committed the active
|
|
2473
|
-
* bearer atomically, so no activation outage can roll back or corrupt it.
|
|
2474
|
-
*/
|
|
2475
|
-
async function activateInboxAfterPairing(cred) {
|
|
2476
|
-
const headers = { Authorization: `Bearer ${cred.token}` };
|
|
2477
|
-
const overallDeadline = Date.now() + activationMaxWaitMs();
|
|
2478
|
-
process.stdout.write(' Sending a test question to PingRoom…\n');
|
|
2479
|
-
|
|
2480
|
-
let ensured;
|
|
2481
|
-
let ensureTransientRun = 0;
|
|
2482
|
-
while (Date.now() < overallDeadline) {
|
|
2483
|
-
ensured = await httpJson('POST', `${cred.apiBase}/api/agent/inbox/ensure`, {
|
|
2484
|
-
body: {},
|
|
2485
|
-
headers,
|
|
2486
|
-
soft: true,
|
|
2487
|
-
signal: AbortSignal.timeout(Math.max(1, Math.min(15_000, overallDeadline - Date.now()))),
|
|
2488
|
-
});
|
|
2489
|
-
const transient = ensured.error || ensured.res?.status === 429 || ensured.res?.status >= 500;
|
|
2490
|
-
if (!transient) break;
|
|
2491
|
-
ensureTransientRun += 1;
|
|
2492
|
-
await sleep(activationRetryDelay(ensured, ensureTransientRun, overallDeadline));
|
|
2493
|
-
}
|
|
2494
|
-
|
|
2495
|
-
if (!ensured.res?.ok) {
|
|
2496
|
-
const detail = Date.now() >= overallDeadline
|
|
2497
|
-
? 'the two-minute activation deadline elapsed while PingRoom was unavailable'
|
|
2498
|
-
: activationFailureDetail(ensured);
|
|
2499
|
-
activationIncomplete(detail);
|
|
2500
|
-
return false;
|
|
2501
|
-
}
|
|
2502
|
-
|
|
2503
|
-
const ensureEnvelope = validateActivationEnsure(ensured.json);
|
|
2504
|
-
if (ensureEnvelope.error) {
|
|
2505
|
-
activationIncomplete(ensureEnvelope.error);
|
|
2506
|
-
return false;
|
|
2507
|
-
}
|
|
2508
|
-
const { question } = ensureEnvelope;
|
|
2509
|
-
|
|
2510
|
-
process.stdout.write(' Answer “PingRoom connected. Can you answer this?” on your phone.\n');
|
|
2511
|
-
// The server stamp, not the terminal state by itself, is the activation
|
|
2512
|
-
// authority. A terminal answer without the stamp cannot become a valid
|
|
2513
|
-
// receipt-before-answer sequence later, so fail clearly instead of polling a
|
|
2514
|
-
// state the server intentionally will not rewrite.
|
|
2515
|
-
const deadline = overallDeadline;
|
|
2516
|
-
let transientRun = 0;
|
|
2517
|
-
|
|
2518
|
-
while (Date.now() < deadline) {
|
|
2519
|
-
const pollStartedAt = Date.now();
|
|
2520
|
-
const remainingSeconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
|
2521
|
-
const hold = Math.min(20, remainingSeconds);
|
|
2522
|
-
const waited = await httpJson(
|
|
2523
|
-
'GET',
|
|
2524
|
-
`${cred.apiBase}/api/agent/handoffs/${encodeURIComponent(question.id)}/wait?timeout=${hold}`,
|
|
2525
|
-
{
|
|
2526
|
-
headers,
|
|
2527
|
-
soft: true,
|
|
2528
|
-
signal: AbortSignal.timeout(Math.max(1, Math.min(
|
|
2529
|
-
hold * 1000 + 10_000,
|
|
2530
|
-
deadline - Date.now(),
|
|
2531
|
-
))),
|
|
2532
|
-
},
|
|
2533
|
-
);
|
|
2534
|
-
|
|
2535
|
-
const transient = waited.error || waited.res?.status === 429 || waited.res?.status >= 500;
|
|
2536
|
-
if (transient) {
|
|
2537
|
-
transientRun += 1;
|
|
2538
|
-
const retryDelay = activationRetryDelay(waited, transientRun, deadline);
|
|
2539
|
-
const cadenceDelay = ACTIVATION_MIN_POLL_INTERVAL_MS - (Date.now() - pollStartedAt);
|
|
2540
|
-
await sleep(Math.max(0, Math.min(Math.max(retryDelay, cadenceDelay), deadline - Date.now())));
|
|
2541
|
-
continue;
|
|
2542
|
-
}
|
|
2543
|
-
transientRun = 0;
|
|
2544
|
-
|
|
2545
|
-
if (!waited.res?.ok) {
|
|
2546
|
-
activationIncomplete(activationFailureDetail(waited));
|
|
2547
|
-
return false;
|
|
2548
|
-
}
|
|
2549
|
-
|
|
2550
|
-
const waitEnvelope = validateActivationWait(waited.json, question.id);
|
|
2551
|
-
if (waitEnvelope.error) {
|
|
2552
|
-
activationIncomplete(waitEnvelope.error);
|
|
2553
|
-
return false;
|
|
2554
|
-
}
|
|
2555
|
-
const resolved = waitEnvelope.value;
|
|
2556
|
-
const state = resolved.state;
|
|
2557
|
-
if (state === 'answered') {
|
|
2558
|
-
if (resolved.activation_completed !== true) {
|
|
2559
|
-
activationIncomplete(
|
|
2560
|
-
'the test question was answered without verified phone receipt before the answer',
|
|
2561
|
-
'Update the PingRoom app if needed, then run "pingroom activate" to send a fresh test with this saved connection.',
|
|
2562
|
-
);
|
|
2563
|
-
return false;
|
|
2564
|
-
}
|
|
2565
|
-
const answer = resolved.answer.text || resolved.answer.label || resolved.answer.value;
|
|
2566
|
-
process.stdout.write(`✓ Test question answered (${stripControlChars(answer)}). Agent Inbox is ready.\n`);
|
|
2567
|
-
return true;
|
|
2568
|
-
}
|
|
2569
|
-
if (state === 'expired' || state === 'cancelled') {
|
|
2570
|
-
activationIncomplete(
|
|
2571
|
-
`the test question ${state}`,
|
|
2572
|
-
'Run "pingroom activate" to send a fresh test with this saved connection.',
|
|
2573
|
-
);
|
|
2574
|
-
return false;
|
|
2575
|
-
}
|
|
2576
|
-
// `pending` at the bounded hold timeout — continue at a throttle-safe
|
|
2577
|
-
// cadence until the local/server deadline.
|
|
2578
|
-
const cadenceDelay = ACTIVATION_MIN_POLL_INTERVAL_MS - (Date.now() - pollStartedAt);
|
|
2579
|
-
await sleep(Math.max(0, Math.min(cadenceDelay, deadline - Date.now())));
|
|
2580
|
-
}
|
|
2581
|
-
|
|
2582
|
-
activationIncomplete(
|
|
2583
|
-
'still waiting for the test answer at the activation deadline',
|
|
2584
|
-
);
|
|
2585
|
-
return false;
|
|
2586
|
-
}
|
|
2587
|
-
|
|
2588
|
-
/** Retry activation only for the durable credential created by QR pairing. */
|
|
2589
|
-
async function activateStoredInbox(args) {
|
|
2590
|
-
if (args.help) { process.stdout.write(`${commandHelp('activate')}\n`); return EXIT.OK; }
|
|
2591
|
-
if (args._.length > 0) fail('usage: pingroom activate', EXIT.USAGE);
|
|
2592
|
-
if (args.token !== undefined) {
|
|
2593
|
-
fail('pingroom activate uses the saved QR-paired credential; remove --token', EXIT.USAGE);
|
|
2594
|
-
}
|
|
2595
|
-
const unsupported = Object.keys(args).filter((key) => !['_', 'help', 'api', 'token'].includes(key));
|
|
2596
|
-
if (unsupported.length > 0) {
|
|
2597
|
-
fail('usage: pingroom activate [--api <url>]', EXIT.USAGE);
|
|
2598
|
-
}
|
|
2599
|
-
|
|
2600
|
-
const credential = readStoredCredential();
|
|
2601
|
-
if (!credential) {
|
|
2602
|
-
fail('no saved QR-paired credential; run "pingroom" in an interactive terminal first', EXIT.USAGE);
|
|
2603
|
-
}
|
|
2604
|
-
if (!credential.room || !isNonEmptyString(credential.room.invite_code)) {
|
|
2605
|
-
// Granting every room is a valid answer that pins no destination, so the
|
|
2606
|
-
// fix there is picking one — not pairing again, which would only offer the
|
|
2607
|
-
// same choice back.
|
|
2608
|
-
fail(
|
|
2609
|
-
credential.room_access === 'all'
|
|
2610
|
-
? 'this agent was granted all rooms but no delivery room; pick one in the PingRoom app under Connected Agents, then run "pingroom activate" again'
|
|
2611
|
-
: 'the saved credential has no QR-selected delivery room; reconnect with QR pairing before running "pingroom activate"',
|
|
2612
|
-
EXIT.USAGE,
|
|
2613
|
-
);
|
|
2614
|
-
}
|
|
2615
|
-
if (!Array.isArray(credential.scopes) || !credential.scopes.includes('pingroom:handoffs:create')) {
|
|
2616
|
-
fail('the saved credential lacks pingroom:handoffs:create; reconnect with QR pairing before running "pingroom activate"', EXIT.USAGE);
|
|
2617
|
-
}
|
|
2618
|
-
|
|
2619
|
-
const apiBase = resolveApiBase(args);
|
|
2620
|
-
requireSafeUrl('--api', apiBase);
|
|
2621
|
-
if (!isNonEmptyString(credential.api_url)) {
|
|
2622
|
-
fail('the saved QR-paired credential has no trusted API origin; pair again before running "pingroom activate"', EXIT.USAGE);
|
|
2623
|
-
}
|
|
2624
|
-
let credentialOrigin;
|
|
2625
|
-
let targetOrigin;
|
|
2626
|
-
try {
|
|
2627
|
-
credentialOrigin = new URL(credential.api_url).origin;
|
|
2628
|
-
targetOrigin = new URL(apiBase).origin;
|
|
2629
|
-
} catch {
|
|
2630
|
-
fail('the saved QR-paired credential has an invalid API origin; pair again', EXIT.USAGE);
|
|
2631
|
-
}
|
|
2632
|
-
if (credentialOrigin !== targetOrigin) {
|
|
2633
|
-
fail(`stored credential is bound to ${credentialOrigin}; refusing to send it to ${targetOrigin}`, EXIT.USAGE);
|
|
2634
|
-
}
|
|
2635
|
-
process.stdout.write(`${connectedLine(credential)}\n`);
|
|
2636
|
-
|
|
2637
|
-
const completed = await activateInboxAfterPairing({
|
|
2638
|
-
...credential,
|
|
2639
|
-
apiBase,
|
|
2640
|
-
});
|
|
2641
|
-
return completed ? EXIT.OK : EXIT.ERROR;
|
|
2642
|
-
}
|
|
2643
|
-
|
|
2644
|
-
/**
|
|
2645
|
-
* The QR path. Mints a pre-claim credential, asks the server for a pairing
|
|
2646
|
-
* token, renders it, then polls until the human approves. Returns a credential
|
|
2647
|
-
* object, or null when the pairing lapsed and the user declined a fresh one.
|
|
2648
|
-
*/
|
|
2649
|
-
async function connectByPairing(apiBase, ask) {
|
|
2650
|
-
for (;;) {
|
|
2651
|
-
const preClaim = await registerAnonymous(apiBase);
|
|
2652
|
-
const headers = { Authorization: `Bearer ${preClaim}` };
|
|
2653
|
-
|
|
2654
|
-
const start = await httpJson('POST', `${apiBase}/api/agent/auth/pair/start`, {
|
|
2655
|
-
body: { scopes: CLI_SCOPES },
|
|
2656
|
-
headers,
|
|
2657
|
-
});
|
|
2658
|
-
if (!start.res.ok || !start.json || typeof start.json.pair_url !== 'string') {
|
|
2659
|
-
const detail = (start.json && (start.json.message || start.json.error || start.json.code))
|
|
2660
|
-
|| `HTTP ${start.res.status}`;
|
|
2661
|
-
fail(`could not start pairing: ${detail}`);
|
|
2662
|
-
}
|
|
2663
|
-
|
|
2664
|
-
// The URL is server-controlled and goes straight to the terminal, so strip
|
|
2665
|
-
// C0/C1 controls: an --api / config api_url pointing at a hostile host could
|
|
2666
|
-
// otherwise emit ANSI escapes that repaint or hide the line the user is
|
|
2667
|
-
// about to trust with their account.
|
|
2668
|
-
const pairUrl = stripControlChars(start.json.pair_url);
|
|
2669
|
-
// 900s is the server's pre-claim lifetime; never poll past it, and clamp the
|
|
2670
|
-
// server's suggested interval so a bad value can't busy-loop or stall.
|
|
2671
|
-
// The 1000ms floor is not cosmetic: AGENT_PAIRING_SPEC.md throttles
|
|
2672
|
-
// pair/status at `60,1`, so a faster floor spends the pairing window
|
|
2673
|
-
// collecting 429s instead of the approval.
|
|
2674
|
-
const lifetimeMs = Math.max(1, Number(start.json.expires_in) || 900) * 1000;
|
|
2675
|
-
const intervalMs = Math.min(Math.max(Number(start.json.poll_interval_ms) || 1500, 1000), 10_000);
|
|
2676
|
-
const deadline = Date.now() + lifetimeMs;
|
|
2677
|
-
|
|
2678
|
-
const drew = await renderQr(pairUrl);
|
|
2679
|
-
process.stdout.write(`${drew ? ' Or open' : ' Open'}: ${pairUrl}\n`);
|
|
2680
|
-
process.stdout.write(' Waiting for approval… ');
|
|
2681
|
-
|
|
2682
|
-
// A transient failure must not end a wait the human is mid-way through.
|
|
2683
|
-
// Network errors, 5xx and 429 are the load balancer / rate limiter talking,
|
|
2684
|
-
// not the pairing being over; hard-failing on the first one throws away the
|
|
2685
|
-
// whole 15 minutes over a single blip. 401/403/404 still exit immediately —
|
|
2686
|
-
// those say the pre-claim is gone, and retrying can only spin.
|
|
2687
|
-
// The `Date.now() < deadline` bound is what keeps a *persistent* outage from
|
|
2688
|
-
// retrying forever: it ends at the same moment a clean poll would have.
|
|
2689
|
-
let transientRun = 0;
|
|
2690
|
-
let lastTransient = null;
|
|
2691
|
-
let warnedTransient = false;
|
|
2692
|
-
|
|
2693
|
-
while (Date.now() < deadline) {
|
|
2694
|
-
const { res, json, error } = await httpJson(
|
|
2695
|
-
'GET', `${apiBase}/api/agent/auth/pair/status`, { headers, soft: true },
|
|
2696
|
-
);
|
|
2697
|
-
|
|
2698
|
-
if (error || res.status >= 500 || res.status === 429) {
|
|
2699
|
-
transientRun += 1;
|
|
2700
|
-
lastTransient = error
|
|
2701
|
-
? error.message
|
|
2702
|
-
: `HTTP ${res.status}`;
|
|
2703
|
-
// Say something rather than sitting mute: a user watching a QR with no
|
|
2704
|
-
// output cannot tell a slow approval from a broken endpoint.
|
|
2705
|
-
if (transientRun === 3 && !warnedTransient) {
|
|
2706
|
-
warnedTransient = true;
|
|
2707
|
-
process.stdout.write(`\n (still trying — ${lastTransient}) `);
|
|
2708
|
-
}
|
|
2709
|
-
// Ride out a short blip at the normal cadence, then back off
|
|
2710
|
-
// geometrically so a real outage is not also a thundering herd. Never
|
|
2711
|
-
// sleep past the deadline this loop is bounded by.
|
|
2712
|
-
const backoff = Math.min(intervalMs * 2 ** Math.max(0, transientRun - 3), 30_000);
|
|
2713
|
-
await sleep(Math.max(0, Math.min(backoff, deadline - Date.now())));
|
|
2714
|
-
continue;
|
|
2715
|
-
}
|
|
2716
|
-
|
|
2717
|
-
transientRun = 0;
|
|
2718
|
-
|
|
2719
|
-
if (!res.ok) {
|
|
2720
|
-
process.stdout.write('\n');
|
|
2721
|
-
const detail = apiDetail(res, json);
|
|
2722
|
-
fail(`pairing failed: ${detail}`);
|
|
2723
|
-
}
|
|
2724
|
-
const status = json && json.status;
|
|
2725
|
-
if (status === 'active') {
|
|
2726
|
-
// A server that says "active" with no credential has not paired us.
|
|
2727
|
-
// Without this, `token: undefined` is written to credentials.json and
|
|
2728
|
-
// every later command reads a credential file that exists but cannot
|
|
2729
|
-
// authenticate — a far more confusing failure than stopping here.
|
|
2730
|
-
if (typeof json.credential !== 'string' || json.credential === '') {
|
|
2731
|
-
process.stdout.write('\n');
|
|
2732
|
-
fail('pairing succeeded but the server returned no credential');
|
|
2733
|
-
}
|
|
2734
|
-
const cred = {
|
|
2735
|
-
token: json.credential,
|
|
2736
|
-
handle: json.handle,
|
|
2737
|
-
room: json.room,
|
|
2738
|
-
rooms: Array.isArray(json.rooms) ? json.rooms : [],
|
|
2739
|
-
roomAccess: typeof json.room_access === 'string' ? json.room_access : null,
|
|
2740
|
-
account: json.account,
|
|
2741
|
-
scopes: json.scopes,
|
|
2742
|
-
apiBase,
|
|
2743
|
-
};
|
|
2744
|
-
saveCredential(cred);
|
|
2745
|
-
process.stdout.write(`${connectedLine(cred)}\n`);
|
|
2746
|
-
// Connecting deliberately sends nothing to the human's phone. The
|
|
2747
|
-
// approval they just tapped IS the round-trip; a test Question on top of
|
|
2748
|
-
// it was one more thing to answer before the tool could be used, and it
|
|
2749
|
-
// made a healthy connection look broken whenever the answer was slow.
|
|
2750
|
-
// `pingroom activate` still sends one for anyone who wants the proof.
|
|
2751
|
-
return cred;
|
|
2752
|
-
}
|
|
2753
|
-
if (status === 'expired') break;
|
|
2754
|
-
// `pending` (or anything unrecognized) — keep waiting.
|
|
2755
|
-
await sleep(intervalMs);
|
|
2756
|
-
}
|
|
2757
|
-
|
|
2758
|
-
if (transientRun > 0) {
|
|
2759
|
-
process.stdout.write(`\n Gave up waiting — the server kept failing (last: ${lastTransient}).\n`);
|
|
2760
|
-
} else {
|
|
2761
|
-
process.stdout.write(`\n That code expired.\n`);
|
|
2762
|
-
}
|
|
2763
|
-
|
|
2764
|
-
// `null` means the input is closed, and that is the whole point of this
|
|
2765
|
-
// guard. Reading EOF as "" would fall through the y/yes test below (empty
|
|
2766
|
-
// means "take the default: yes"), restart the for(;;), mint another
|
|
2767
|
-
// anonymous registration, and do it again — a Ctrl-D or a piped stdin turns
|
|
2768
|
-
// a single pairing attempt into thousands of registrations against the API.
|
|
2769
|
-
const again = await ask(' Show a fresh QR code? [Y/n]: ');
|
|
2770
|
-
if (again === null) { process.stdout.write('\n'); return null; }
|
|
2771
|
-
const answer = again.trim().toLowerCase();
|
|
2772
|
-
if (answer && answer !== 'y' && answer !== 'yes') return null;
|
|
2773
|
-
}
|
|
2774
|
-
}
|
|
2775
|
-
|
|
2776
|
-
/**
|
|
2777
|
-
* The email fallback, over the unchanged claim/* endpoints: the server mails a
|
|
2778
|
-
* link, the web page shows a 6-digit code, the user reads it back here.
|
|
2779
|
-
*/
|
|
2780
|
-
async function connectByEmail(apiBase, ask) {
|
|
2781
|
-
const preClaim = await registerAnonymous(apiBase);
|
|
2782
|
-
const headers = { Authorization: `Bearer ${preClaim}` };
|
|
2783
|
-
|
|
2784
|
-
// `?? ''` preserves the old EOF behaviour deliberately: ask() now returns null
|
|
2785
|
-
// at EOF, and without the coalesce this would throw a TypeError on `.trim()`
|
|
2786
|
-
// instead of reaching the "this is required" error the user should see.
|
|
2787
|
-
const email = (await ask(' Your PingRoom email: ') ?? '').trim();
|
|
2788
|
-
if (!email) fail('an email address is required', EXIT.USAGE);
|
|
2789
|
-
|
|
2790
|
-
const start = await httpJson('POST', `${apiBase}/api/agent/auth/claim/start`, {
|
|
2791
|
-
body: { email },
|
|
2792
|
-
headers,
|
|
2793
|
-
});
|
|
2794
|
-
if (!start.res.ok) {
|
|
2795
|
-
const detail = (start.json && (start.json.message || start.json.error || start.json.code))
|
|
2796
|
-
|| `HTTP ${start.res.status}`;
|
|
2797
|
-
fail(`could not send the email: ${detail}`);
|
|
2798
|
-
}
|
|
2799
|
-
|
|
2800
|
-
process.stdout.write(' Sent. Open the link in that email — the page shows a 6-digit code.\n');
|
|
2801
|
-
|
|
2802
|
-
// A mistyped code is the common case, so allow a few tries before giving up.
|
|
2803
|
-
// The server locks the registration out after its own attempt cap anyway.
|
|
2804
|
-
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
2805
|
-
// Same reason as the email prompt: EOF stays an empty answer, which the
|
|
2806
|
-
// server rejects, rather than a TypeError on null.
|
|
2807
|
-
const otp = (await ask(' Code: ') ?? '').trim();
|
|
2808
|
-
const done = await httpJson('POST', `${apiBase}/api/agent/auth/claim/complete`, {
|
|
2809
|
-
body: { email, otp },
|
|
2810
|
-
headers,
|
|
2811
|
-
});
|
|
2812
|
-
if (done.res.ok && done.json && typeof done.json.credential === 'string') {
|
|
2813
|
-
const cred = {
|
|
2814
|
-
token: done.json.credential,
|
|
2815
|
-
handle: done.json.handle,
|
|
2816
|
-
// claim/complete carries no room — the email flow does not choose one.
|
|
2817
|
-
room: done.json.room,
|
|
2818
|
-
account: done.json.account,
|
|
2819
|
-
scopes: done.json.scopes,
|
|
2820
|
-
apiBase,
|
|
2821
|
-
};
|
|
2822
|
-
saveCredential(cred);
|
|
2823
|
-
process.stdout.write(`${connectedLine(cred)}\n`);
|
|
2824
|
-
if (!cred.room) {
|
|
2825
|
-
process.stdout.write(' For room commands: pingroom config set default_room <invite code>\n');
|
|
2826
|
-
process.stdout.write(' For private Inbox/Handoff delivery, reconnect with QR pairing.\n');
|
|
2827
|
-
}
|
|
2828
|
-
return cred;
|
|
2829
|
-
}
|
|
2830
|
-
const detail = (done.json && (done.json.message || done.json.error || done.json.code))
|
|
2831
|
-
|| `HTTP ${done.res.status}`;
|
|
2832
|
-
if (attempt === 3) fail(`could not connect: ${detail}`);
|
|
2833
|
-
process.stderr.write(`pingroom: ${detail}\n`);
|
|
2834
|
-
}
|
|
2835
|
-
return null;
|
|
2836
|
-
}
|
|
2837
|
-
|
|
2838
|
-
/**
|
|
2839
|
-
* Resolve the unconnected state interactively. Refuses outright when there is no
|
|
2840
|
-
* TTY — a hung prompt in CI is worse than a clean failure, and the fix there is
|
|
2841
|
-
* PINGROOM_TOKEN, not a QR nobody can scan.
|
|
2842
|
-
*/
|
|
2843
|
-
async function connect(args) {
|
|
2844
|
-
if (!isInteractive()) {
|
|
2845
|
-
fail(
|
|
2846
|
-
'not connected, and this is not an interactive terminal. Set PINGROOM_TOKEN (CI, pipes), or run "pingroom" from a terminal to pair.',
|
|
2847
|
-
EXIT.USAGE,
|
|
2848
|
-
);
|
|
2849
|
-
}
|
|
2850
|
-
|
|
2851
|
-
const apiBase = resolveApiBase(args);
|
|
2852
|
-
requireSafeUrl('--api', apiBase);
|
|
2853
|
-
|
|
2854
|
-
const prompter = createPrompter();
|
|
2855
|
-
const ask = (question) => prompter.ask(question);
|
|
2856
|
-
try {
|
|
2857
|
-
process.stdout.write(' Not connected. How do you want to connect?\n');
|
|
2858
|
-
process.stdout.write(' 1) Scan a QR code with the PingRoom app\n');
|
|
2859
|
-
process.stdout.write(' 2) Email me a code\n');
|
|
2860
|
-
// EOF here means "no answer", which is what the default already covers, so
|
|
2861
|
-
// coalesce rather than crash on null — the pairing branch below is the one
|
|
2862
|
-
// that must distinguish EOF, and it does.
|
|
2863
|
-
const choice = (await ask(' Choose [1]: ') ?? '').trim();
|
|
2864
|
-
if (choice && choice !== '1' && choice !== '2') {
|
|
2865
|
-
process.stderr.write('pingroom: choose 1 or 2\n');
|
|
2866
|
-
return EXIT.USAGE;
|
|
2867
|
-
}
|
|
2868
|
-
|
|
2869
|
-
const cred = choice === '2'
|
|
2870
|
-
? await connectByEmail(apiBase, ask)
|
|
2871
|
-
: await connectByPairing(apiBase, ask);
|
|
2872
|
-
|
|
2873
|
-
return cred ? EXIT.OK : EXIT.EXPIRED;
|
|
2874
|
-
} finally {
|
|
2875
|
-
prompter.close();
|
|
2876
|
-
}
|
|
2877
|
-
}
|
|
2878
|
-
|
|
2879
|
-
// --- status / bare invocation ----------------------------------------------
|
|
2880
|
-
|
|
2881
|
-
/**
|
|
2882
|
-
* `pingroom` with no arguments. Connected -> one status line then the usual
|
|
2883
|
-
* help. Not connected -> pair (interactive) or, in a pipe/CI, say so on stderr
|
|
2884
|
-
* and still print the help rather than prompting into the void.
|
|
2885
|
-
*/
|
|
2886
|
-
async function bare(args) {
|
|
2887
|
-
const envToken = process.env.PINGROOM_TOKEN;
|
|
2888
|
-
const stored = readStoredCredential();
|
|
2889
|
-
|
|
2890
|
-
if (envToken) {
|
|
2891
|
-
process.stdout.write('Using the agent token from PINGROOM_TOKEN.\n');
|
|
2892
|
-
if (stored) process.stdout.write(`(the stored credential in ${credentialsPath()} is ignored while it is set)\n`);
|
|
2893
|
-
const room = resolveRoom(args);
|
|
2894
|
-
if (room) process.stdout.write(`Default room: ${room}\n`);
|
|
2895
|
-
process.stdout.write(`\n${HELP}\n`);
|
|
2896
|
-
return EXIT.OK;
|
|
2897
|
-
}
|
|
2898
|
-
|
|
2899
|
-
if (stored) {
|
|
2900
|
-
process.stdout.write(`${connectedLine(stored)}\n`);
|
|
2901
|
-
const room = resolveRoom(args);
|
|
2902
|
-
if (room) process.stdout.write(`Default room: ${room}\n`);
|
|
2903
|
-
process.stdout.write(`\n${HELP}\n`);
|
|
2904
|
-
return EXIT.OK;
|
|
2905
|
-
}
|
|
2906
|
-
|
|
2907
|
-
if (!isInteractive()) {
|
|
2908
|
-
process.stderr.write('pingroom: not connected. Set PINGROOM_TOKEN, or run "pingroom" from an interactive terminal to pair.\n');
|
|
2909
|
-
process.stdout.write(`${HELP}\n`);
|
|
2910
|
-
return EXIT.OK;
|
|
2911
|
-
}
|
|
2912
|
-
|
|
2913
|
-
return connect(args);
|
|
2914
|
-
}
|
|
2915
|
-
|
|
2916
|
-
// --- config ----------------------------------------------------------------
|
|
2917
|
-
|
|
2918
|
-
// Only these keys are storable. An unknown key is a usage error rather than a
|
|
2919
|
-
// silently-ignored setting the user then blames the tool for not honouring.
|
|
2920
|
-
const CONFIG_KEYS = {
|
|
2921
|
-
default_room: {
|
|
2922
|
-
describe: 'Room invite code used when --room / PINGROOM_ROOM is absent',
|
|
2923
|
-
validate: (value) => {
|
|
2924
|
-
if (/\s/.test(value) || value.length > 64) return 'default_room must be an invite code (no spaces, <= 64 chars)';
|
|
2925
|
-
return null;
|
|
2926
|
-
},
|
|
2927
|
-
},
|
|
2928
|
-
api_url: {
|
|
2929
|
-
describe: `API base URL (default ${BUILTIN_API})`,
|
|
2930
|
-
validate: (value) => {
|
|
2931
|
-
let u;
|
|
2932
|
-
try { u = new URL(value); } catch { return 'api_url must be a valid URL'; }
|
|
2933
|
-
const loopback = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]';
|
|
2934
|
-
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) {
|
|
2935
|
-
return 'api_url must use https (refusing to send credentials over cleartext)';
|
|
2936
|
-
}
|
|
2937
|
-
return null;
|
|
2938
|
-
},
|
|
2939
|
-
},
|
|
2940
|
-
};
|
|
2941
|
-
|
|
2942
|
-
async function config(args) {
|
|
2943
|
-
if (args.help) { process.stdout.write(`${commandHelp('config')}\n`); return EXIT.OK; }
|
|
2944
|
-
|
|
2945
|
-
const sub = args._[0];
|
|
2946
|
-
const known = ['list', 'get', 'set'];
|
|
2947
|
-
if (!sub || !known.includes(sub)) {
|
|
2948
|
-
fail(`config needs a subcommand: ${known.join(' | ')}`, EXIT.USAGE);
|
|
2949
|
-
}
|
|
2950
|
-
|
|
2951
|
-
const stored = readConfigFile();
|
|
2952
|
-
|
|
2953
|
-
if (sub === 'list') {
|
|
2954
|
-
if (args.json) { process.stdout.write(`${JSON.stringify(stored)}\n`); return EXIT.OK; }
|
|
2955
|
-
const keys = Object.keys(CONFIG_KEYS).filter((k) => stored[k] !== undefined && stored[k] !== '');
|
|
2956
|
-
if (keys.length === 0) {
|
|
2957
|
-
process.stdout.write(`no settings stored in ${configPath()}\n`);
|
|
2958
|
-
return EXIT.OK;
|
|
2959
|
-
}
|
|
2960
|
-
for (const key of keys) process.stdout.write(`${key}=${stored[key]}\n`);
|
|
2961
|
-
return EXIT.OK;
|
|
2962
|
-
}
|
|
2963
|
-
|
|
2964
|
-
const key = args._[1];
|
|
2965
|
-
if (!key) fail(`config ${sub} needs a key (${Object.keys(CONFIG_KEYS).join(', ')})`, EXIT.USAGE);
|
|
2966
|
-
if (!Object.hasOwn(CONFIG_KEYS, key)) {
|
|
2967
|
-
fail(`unknown config key: ${key} (known keys: ${Object.keys(CONFIG_KEYS).join(', ')})`, EXIT.USAGE);
|
|
2968
|
-
}
|
|
2969
|
-
|
|
2970
|
-
if (sub === 'get') {
|
|
2971
|
-
const value = stored[key];
|
|
2972
|
-
if (value === undefined || value === '') return EXIT.OK; // unset: print nothing, exit 0
|
|
2973
|
-
process.stdout.write(`${value}\n`);
|
|
2974
|
-
return EXIT.OK;
|
|
2975
|
-
}
|
|
2976
|
-
|
|
2977
|
-
// set
|
|
2978
|
-
const raw = args._[2];
|
|
2979
|
-
if (raw === undefined) fail(`config set needs a value (pass "" to clear ${key})`, EXIT.USAGE);
|
|
2980
|
-
const value = String(raw).trim();
|
|
2981
|
-
|
|
2982
|
-
if (value === '') {
|
|
2983
|
-
delete stored[key];
|
|
2984
|
-
writeJsonFile(configPath(), stored);
|
|
2985
|
-
process.stdout.write(`${key} cleared\n`);
|
|
2986
|
-
return EXIT.OK;
|
|
2987
|
-
}
|
|
2988
|
-
|
|
2989
|
-
const problem = CONFIG_KEYS[key].validate(value);
|
|
2990
|
-
if (problem) fail(problem, EXIT.USAGE);
|
|
2991
|
-
|
|
2992
|
-
stored[key] = value;
|
|
2993
|
-
writeJsonFile(configPath(), stored);
|
|
2994
|
-
process.stdout.write(`${key}=${value}\n`);
|
|
2995
|
-
return EXIT.OK;
|
|
2996
|
-
}
|
|
2997
|
-
|
|
2998
|
-
// --- logout ----------------------------------------------------------------
|
|
2999
|
-
|
|
3000
|
-
async function logout(args) {
|
|
3001
|
-
if (args.help) { process.stdout.write(`${commandHelp('logout')}\n`); return EXIT.OK; }
|
|
3002
|
-
|
|
3003
|
-
const path = credentialsPath();
|
|
3004
|
-
const stored = readStoredCredential();
|
|
3005
|
-
try {
|
|
3006
|
-
unlinkSync(path);
|
|
3007
|
-
} catch (err) {
|
|
3008
|
-
if (err.code === 'ENOENT') {
|
|
3009
|
-
process.stdout.write('not connected — there was no stored credential to clear\n');
|
|
3010
|
-
return EXIT.OK;
|
|
3011
|
-
}
|
|
3012
|
-
fail(`could not clear ${path}: ${err.message}`);
|
|
3013
|
-
}
|
|
3014
|
-
|
|
3015
|
-
const who = stored && stored.handle ? ` (@${stored.handle})` : '';
|
|
3016
|
-
process.stdout.write(`logged out${who} — cleared ${path}\n`);
|
|
3017
|
-
if (process.env.PINGROOM_TOKEN) {
|
|
3018
|
-
process.stdout.write('note: PINGROOM_TOKEN is still set in this environment and will keep being used\n');
|
|
3019
|
-
}
|
|
3020
|
-
return EXIT.OK;
|
|
3021
|
-
}
|
|
3022
|
-
|
|
3023
|
-
// config/logout/handoffs used to share parseQArgs, which silently accepted and
|
|
3024
|
-
// ignored flags those commands never read (`logout --wait --prompt x`). Minimal
|
|
3025
|
-
// tables instead, so an irrelevant flag is a usage error like everywhere else.
|
|
3026
|
-
const parseConfigArgs = makeParser({
|
|
3027
|
-
aliases: { '--json': 'json', '-h': 'help', '--help': 'help' },
|
|
3028
|
-
booleans: ['json', 'help'],
|
|
3029
|
-
bareDashIsPositional: true,
|
|
3030
|
-
});
|
|
3031
|
-
|
|
3032
|
-
const parseLogoutArgs = makeParser({
|
|
3033
|
-
aliases: { '-h': 'help', '--help': 'help' },
|
|
3034
|
-
booleans: ['help'],
|
|
3035
|
-
bareDashIsPositional: true,
|
|
3036
|
-
});
|
|
3037
|
-
|
|
3038
|
-
const parseHandoffsArgs = makeParser({
|
|
3039
|
-
aliases: {
|
|
3040
|
-
'--state': 'state',
|
|
3041
|
-
'--token': 'token',
|
|
3042
|
-
'--api': 'api',
|
|
3043
|
-
'--json': 'json',
|
|
3044
|
-
'-h': 'help', '--help': 'help',
|
|
3045
|
-
},
|
|
3046
|
-
booleans: ['json', 'help'],
|
|
3047
|
-
bareDashIsPositional: true,
|
|
3048
|
-
});
|
|
33
|
+
// This file is the entry point only: the dispatch table, main(), and the
|
|
34
|
+
// top-level catch. Everything it calls lives under lib/ — see lib/help.js for
|
|
35
|
+
// the --help text, lib/parser.js for the flag vocabulary, and lib/commands/*
|
|
36
|
+
// for one module per command.
|
|
37
|
+
|
|
38
|
+
import { EXIT } from '../lib/constants.js';
|
|
39
|
+
import { fail, stripControlChars } from '../lib/util.js';
|
|
40
|
+
import { VERSION } from '../lib/version.js';
|
|
41
|
+
import { HELP } from '../lib/help.js';
|
|
42
|
+
import {
|
|
43
|
+
parseArgs, parseConfigArgs, parseHandoffArgs, parseHandoffsArgs, parseHookArgs,
|
|
44
|
+
parseLiveArgs, parseLogoutArgs, parseQArgs,
|
|
45
|
+
} from '../lib/parser.js';
|
|
46
|
+
import { ping } from '../lib/commands/ping.js';
|
|
47
|
+
import { ask, cancel, list, watch } from '../lib/commands/ask.js';
|
|
48
|
+
import { handoff, listHandoffs } from '../lib/commands/handoff.js';
|
|
49
|
+
import { listen } from '../lib/commands/listen.js';
|
|
50
|
+
import { live } from '../lib/commands/live.js';
|
|
51
|
+
import { hook } from '../lib/commands/hook.js';
|
|
52
|
+
import { mcp } from '../lib/commands/mcp.js';
|
|
53
|
+
import { activateStoredInbox, bare } from '../lib/commands/connect.js';
|
|
54
|
+
import { config, logout } from '../lib/commands/config.js';
|
|
3049
55
|
|
|
3050
56
|
const COMMANDS = {
|
|
3051
57
|
ping: (rest) => ping(parseArgs(rest)),
|