SLOPSHOPPER

Pending You

One place for everything your AI agents are waiting on you for. When a decision is yours, Claude asks in the conversation and on a Pending You card at once…

guardstatusprocesstimer
v2.56.0Apache-2.0updated 2026-10-25recordplane/pendingyou-plugin/plugins/pending-you
A shopper browsing a rack in a slop shop
README

Pending You

Pending You is one place for everything your AI agents are waiting on you for. With this plugin, when a decision, a fact or a step is yours, Claude asks in the conversation and on a Pending You card at once, so you can answer wherever you are, from your phone or your desk. The first answer wins, and Claude picks it up and carries on.

What it adds

  • The Pending You connector, at https://www.pendingyou.com/mcp. You sign in once in your browser and click Allow. No key or token is stored in the plugin.
  • The pending-you skill: when a decision is yours, and how to ask so you can answer in one tap.
  • The pending-you-setup skill: say “set up Pending You” (or type /pending-you:pending-you-setup in Claude Code). It connects, sets up check-ins (a Cowork scheduled task every hour, 7 AM–9 PM), and sends you a test question.
  • Wakes Claude Code when you answer (Claude Code 2.1.287 or later): a mod that checks the cards a session posted, through its own Pending You connection, and starts a turn when you answer, write back or a fallback comes due, or you hand the session a question from another of your assistants, even while it sits idle. Under the prompt it shows “2 waiting on you”, after the plugin’s name. Allow Pending You’s tools once in /permissions (mcp__plugin_pending-you_pendingyou) so it can check while you’re away.

Set it up

  • Claude Cowork: Customize › Plugins › Add marketplace › Add from a repository: recordplane/pendingyou-plugin. Install Pending You, connect its connector (sign in, Allow), and say “set up Pending You” in a Cowork task.
  • Claude Code: one command in Terminal sets it up, with one approval in your browser: npx -y pendingyou@latest init. Then restart Claude Code, and it finishes setting up by itself. It needs Node 20 or later; without it, install the plugin: claude plugin marketplace add recordplane/pendingyou-plugin, then claude plugin install pending-you@pendingyou. Restart Claude Code, run /mcp, choose plugin:pending-you:pendingyou and Authenticate, then say “set up Pending You” (or type /pending-you:pending-you-setup).

After that, every question Claude leaves you goes in both places: the conversation and Pending You. Answer in either; Claude takes back the other. The same command sets up every coding agent it finds on your computer: Claude Code, Codex (the CLI and the Codex app), OpenCode and Pi, each with its own connection and the one approval. Cursor is set up separately: its steps are in Help.

What this plugin runs, sends and fetches

  • The connector connects Claude to Pending You at https://www.pendingyou.com/mcp. You sign in in your browser and click Allow; the plugin holds no key or token.
  • What Claude sends through it: the questions it asks you (a title, a short summary, options, and any drafts, screenshots or files it attaches), its answers to your questions (your question as you asked it, the answer, and when and where any data in it came from), the name it goes by and a line about its work, what it set up, and, in Claude Code, usually where it works: its folder, its git remote and the computer’s name. It reads back your answers and messages, and any files you attach. Pending You tells Claude never to send passwords, codes, keys, tokens or card numbers.
  • The pending-you skill tells Claude when a question is yours and how to ask it.
  • The pending-you-setup skill sets Pending You up here and sends you a test question. In Claude Code it may run claude mcp list, claude mcp get and npx pendingyou status to find another Pending You server (claude mcp list also checks that each server you’ve added answers). It removes and installs nothing itself: when one is needed, it asks you to run claude mcp remove or npx -y pendingyou@latest init. In Cowork it creates a scheduled task that checks Pending You every hour, 7 AM–9 PM, which you approve.
  • The mod in hooks/ (Claude Code 2.1.287 or later) wakes this session when you answer one of its cards. It reads this session’s calls to Pending You’s tools and what they return, to learn the cards it posts, and under the prompt it shows how many are waiting on you. In detail:
  • The tools it calls itself ($.mcp.call), without Claude asking: get_request on each card this session posted, its answers to your questions too, until it’s closed, about every 20 seconds while the card changed in the last half hour, then every minute (one more check follows when you mark an answer Got it, since you can take that back for a few seconds); and list_pending, to look for questions you hand the session from another of your assistants, every minute for half an hour after the session last used Pending You, then every 3 minutes, for 12 hours, with get_request on each new one. It makes these calls only when Claude Code allows them without asking you: it asks Claude Code first, a question that runs nothing. If Claude Code won’t let it check, it tells Claude once, in that call’s result, how you can allow it.
  • What it sends, and where: of everything it reads, it sends only a card’s id and the name Claude goes by, in those calls, and only to Pending You, through Claude Code’s own Pending You connection: the one the session posted its cards through.
  • The prompts it submits ($.prompt.submit): when one of the session’s cards needs it (you answered, wrote back, replied to one of its answers, said you’ll handle it yourself or won’t do it, its fallback came due, it was withdrawn, or there’s word from the assistant you handed it to), it starts a turn with one prompt once the session is idle. The prompt names each card by the title Claude gave it (up to 80 characters) and its id, and says what happened and what to do next, such as which Pending You tool to call, with the name Claude goes by. It never carries your answer or your message: Claude reads those with get_request. For a question you hand the session, the prompt names it by its title (up to 80 characters) and id, says who asked it (up to 60 characters of their name), whether its answer goes straight to them or to you first, and whether you added a note, never the note itself; when they or you write on it again, it quotes the newest of those messages, up to 300 characters.
  • What its hooks change: a call to Pending You’s tools runs as it is, and Claude gets its result as it was, but for the one line above when Claude Code won’t let the mod check. It reads each Bash command Claude runs: for npx pendingyou hold <card> on a card it can check, it answers the call itself instead of running it, saying that no hold is needed because the session will be woken; every other command runs as it is. Its hook on Claude Code’s SessionStart event, after /clear, /resume or a branch, only follows the session to its new id: it passes the event and its result on as they are, and adds no context or instructions. Its hooks on the session’s start and on each turn’s start and end pass them on unchanged too: it uses them to start its checks and to know when the session is idle.
  • What it keeps and sets: each session’s cards (their ids, titles and where they stand, and which of them are its answers) in Claude Code’s plugin store, forgotten after 7 days untouched. It sets one environment variable, PENDINGYOU_WAKE_OWNER, so two copies of the mod never both act ($.env.set): its value is the name of the copy that acts and a time a minute ahead, renewed while it acts. Claude Code keeps it in its own process, so the programs it starts after, such as Bash commands, have it too; only the mod reads it. The one other variable it reads is HOME, to compare folders written as ~/….
  • Programs and files ($.process.run, $.fs.read, $.fs.write): this code is also the pendingyou command line’s own copy of the mod, and it starts programs and reads or writes files only once it has checked that it is that copy, by its name (pendingyou-wake) and its folder; in this plugin those parts never run, so it starts no programs and writes no files. In the command line’s copy, it runs the command line’s hooks script, ~/.config/pendingyou/bin/pendingyou-hook, three ways: presence, as a session starts and every 5 minutes, to tell Pending You the session is open (its id, its folder when that’s in your home folder, and the name Claude goes by); listen --handed, in one session at a time, to wait for a question you hand one of the computer’s Claude Code sessions, hearing only ids and times; and herdr report, in a Herdr terminal pane only, to show the session’s name and its cards waiting on you on that pane, through Herdr’s own command on this computer. The first two reach only Pending You, with the sign-in the command line set up for Claude Code. That copy reads which Pending You to use from ~/.config/pendingyou/claude-code.json, the command line’s record of how it set Claude Code up, and writes ~/.config/pendingyou/wake/sessions/<session id>.json, holding only the time it last started in that session ({"at":<time>}): the command line reads it to tell which open sessions started before the mod was set up, and need a restart. It also calls whoami a few seconds after a session opens, to learn whether Claude Code is set up there, and if it isn’t, starts one turn that finishes setting it up; this plugin does neither.
  • Where it connects: the connector and the mod reach only https://www.pendingyou.com, through Claude’s connection. The one download is during setup: npx pendingyou status fetches the pendingyou command line from npm when it isn’t installed.

Pending You never answers for you. It uses two small models: one reads a Later time you typed when its own reader can’t (you see the time before it’s set), and one suggests which of your assistants to hand a card to.

More

  • Help: setting up each app, and what to do when an answer doesn’t arrive.
  • The guide your agents read: when they ask you, and how. This is version 2.56.0.
  • A problem, or something you’d change: open an issue, or email support@pendingyou.com.

Generated from Pending You’s guide 2.56.0.

Source 2 files
hooks/register.js 587 lines
1// Generated from packages/claude-plugin/src/wake/register.ts in recordplane/pendingyou: edit that, then run
2// `pnpm --filter @pendingyou/claude-plugin generate`.
3
4import { argumentsOf, blockedNote, CLAIM_PREFIX, CLI_COPY, cardTool, checked, claimedElsewhere, claimHeld, claimLease, cliConfigOf, connectionOf, dueCards, emptyBook, failed, folderOf, graceEnds, HANDED_FAST_MS, HANDED_READS, HERDR_EVERY_MS, HERDR_RUN_MS, handedDue, handedNext, handedOf, handedText, handedView, herdrArgv, herdrPayload, holdOf, holdReply, inHerdr, isFresh, isRefusal, isStale, isWaitingOnYou, KEEP_MS, LISTEN_RUN_MS, LISTENER_KEY, learn, leaseFor, leaseHolder, listenArgv, listened, loadedNote, loadedPath, mayListen, momentOf, originOf, PRESENCE_EVERY_MS, PRESENCE_RUN_MS, presenceArgv, prompted, put, readBook, readClaim, readListener, readSetup, readSignal, readSince, readWait, resultObject, SETUP_AFTER_MS, SETUP_RETRY_MS, SETUP_SERVER, SETUP_TRIES, SIGNAL_KEY, settle, setUpOf, setupNeeded, setupPrompt, stateOf, statusText, TICK_MS, takesHanded, told, toTell, untold, wakeText, } from "./wake.js";
5const UNHEARD = { error: 'unavailable' };
6const RETRY_MS = 60_000;
7const live = {
8    me: '',
9    sessionId: '',
10    book: emptyBook(),
11    owner: false,
12    busy: false,
13    ticking: false,
14    pruned: false,
15    quietUntil: 0,
16    timer: null,
17    shown: undefined,
18    blocked: new Set(),
19    verified: new Set(),
20    noted: new Set(),
21    setupDue: false,
22    setupConnection: 'Claude Code',
23    seenAt: 0,
24    handedAt: 0,
25    handedTold: new Map(),
26    folders: [],
27    home: undefined,
28    presence: null,
29    presenceTimer: null,
30    herdr: null,
31    herdrSaid: undefined,
32    herdrTimer: null,
33    waiting: false,
34    signalSeen: 0,
35};
36const keyOf = (sessionId) => `session:${sessionId}`;
37function blockedServer() {
38    for (const server of live.blocked)
39        if (Object.values(live.book.cards).some((card) => card.server === server))
40            return server;
41    return undefined;
42}
43async function save($) {
44    live.book = { ...live.book, updatedAt: await $.clock.now() };
45    if (Object.keys(live.book.cards).length)
46        await $.store.set(keyOf(live.sessionId), live.book);
47    else
48        await $.store.delete(keyOf(live.sessionId));
49}
50async function claim($) {
51    const now = await $.clock.now();
52    const value = claimLease(await $.env.get('PENDINGYOU_WAKE_OWNER'), live.me, now);
53    if (value)
54        await $.env.set('PENDINGYOU_WAKE_OWNER', value);
55    live.owner = leaseHolder(await $.env.get('PENDINGYOU_WAKE_OWNER'), now) === live.me;
56    return live.owner;
57}
58function show($, text) {
59    if (text === live.shown)
60        return;
61    live.shown = text;
62    try {
63        const shown = $.ui.status(text);
64        if (shown instanceof Promise)
65            shown.catch(() => { });
66    }
67    catch { }
68}
69const showCards = ($) => {
70    show($, live.owner ? statusText(live.book, blockedServer()) : undefined);
71    void sayHerdr($);
72};
73async function sayHerdr($, again = false) {
74    try {
75        if (!live.herdr || !live.sessionId || !live.owner)
76            return;
77        const payload = herdrPayload(live.book);
78        if (!again && payload === live.herdrSaid)
79            return;
80        live.herdrSaid = payload;
81        const argv = herdrArgv(live.herdr.config, { id: live.sessionId, at: await $.clock.now() });
82        $.process.run(argv, { stdin: payload, timeoutMs: HERDR_RUN_MS }).catch(() => { });
83    }
84    catch { }
85}
86async function startHerdr($) {
87    live.herdrTimer?.cancel();
88    live.herdrTimer = null;
89    live.herdr = null;
90    live.herdrSaid = undefined;
91    const config = cliConfigOf($.plugin.root, $.plugin.name);
92    if (!config)
93        return;
94    const herdr = inHerdr(await $.env.get('HERDR_ENV'), await $.env.get('HERDR_BIN_PATH'), await $.env.get('HERDR_PANE_ID'));
95    if (!herdr)
96        return;
97    live.herdr = { config };
98    await sayHerdr($);
99    live.herdrTimer = $.clock.every(HERDR_EVERY_MS, () => sayHerdr($, true));
100}
101async function allowed($, server, args, tool = 'get_request') {
102    try {
103        const decided = await $.tool.check({ tool: `mcp__${server}__${tool}`, input: args });
104        return decided.decision === 'allow';
105    }
106    catch {
107        return false;
108    }
109}
110async function check($, requestId) {
111    const card = live.book.cards[requestId];
112    if (!card)
113        return 'error';
114    let output = null;
115    let blocked = false;
116    const args = { requestId, ...(card.name ? { name: card.name } : {}) };
117    if (await allowed($, card.server, args)) {
118        try {
119            output = resultObject(await $.mcp.call(card.server, 'get_request', args));
120        }
121        catch (error) {
122            blocked = isRefusal(error);
123        }
124    }
125    else
126        blocked = true;
127    const outcome = output && stateOf(output) ? 'ok' : blocked ? 'blocked' : 'error';
128    if (outcome === 'ok') {
129        live.verified.add(card.server);
130        live.blocked.delete(card.server);
131    }
132    else if (outcome === 'blocked')
133        live.blocked.add(card.server);
134    const current = live.book.cards[requestId];
135    if (!current)
136        return outcome;
137    const now = await $.clock.now();
138    const next = output && outcome === 'ok' ? checked(current, output, now) : failed(current, now, blocked);
139    live.book = put(live.book, next);
140    if (!current.state || (next.state && momentOf(current.state) !== momentOf(next.state)))
141        await save($);
142    return outcome;
143}
144async function deliver($) {
145    if (live.busy)
146        return false;
147    if (toTell(live.book).length === 0 || (await $.clock.now()) < live.quietUntil)
148        return false;
149    if (!(await claim($)))
150        return false;
151    const before = await $.clock.now();
152    for (const card of toTell(live.book))
153        if (!isFresh(card, before))
154            await check($, card.requestId);
155    if (live.busy)
156        return false;
157    const now = await $.clock.now();
158    const cards = toTell(live.book).filter((card) => isFresh(card, now));
159    if (cards.length === 0)
160        return false;
161    live.book = told(live.book, cards);
162    await save($);
163    $.prompt.submit({ text: wakeText(cards) }).catch(async () => {
164        live.book = untold(live.book, cards);
165        live.quietUntil = (await $.clock.now()) + RETRY_MS;
166        await save($).catch(() => { });
167    });
168    return true;
169}
170async function deliverHanded($) {
171    const { name, server } = live.book;
172    const now = await $.clock.now();
173    if (live.busy || !name || !server || !handedDue(live.seenAt, live.handedAt, now))
174        return;
175    live.handedAt = handedNext(live.seenAt, now);
176    if (!(await allowed($, server, { name }, 'list_pending')))
177        return;
178    let listed;
179    try {
180        listed = handedOf(resultObject(await $.mcp.call(server, 'list_pending', { name })));
181    }
182    catch {
183        return;
184    }
185    const cards = [];
186    const claims = [];
187    const me = live.sessionId;
188    for (const handed of listed) {
189        const known = live.handedTold.get(handed.requestId);
190        if (readSince(known, handed.updatedAt) || known === handed.updatedAt)
191            continue;
192        if (!takesHanded(handed, live.folders, live.home, now)) {
193            const again = graceEnds(handed, live.folders);
194            if (again !== null && again > now)
195                live.handedAt = Math.min(live.handedAt, again);
196            continue;
197        }
198        const key = `${CLAIM_PREFIX}${handed.requestId}`;
199        if (claimedElsewhere(await $.store.get(key), handed.updatedAt, me)) {
200            live.handedTold.set(handed.requestId, handed.updatedAt);
201            continue;
202        }
203        const args = { requestId: handed.requestId, name };
204        if (!(await allowed($, server, args)))
205            continue;
206        await $.store.set(key, { moment: handed.updatedAt, at: now, by: me });
207        let view = null;
208        try {
209            view = handedView(resultObject(await $.mcp.call(server, 'get_request', args)), handed, name);
210        }
211        catch { }
212        const stored = await $.store.get(key);
213        if (!view) {
214            if (claimHeld(stored, handed.updatedAt, me))
215                await $.store.delete(key);
216            continue;
217        }
218        if (!claimHeld(stored, handed.updatedAt, me)) {
219            live.handedTold.set(handed.requestId, handed.updatedAt);
220            continue;
221        }
222        live.handedTold.set(handed.requestId, handed.updatedAt);
223        claims.push(key);
224        cards.push(view);
225    }
226    if (cards.length === 0)
227        return;
228    $.prompt.submit({ text: handedText(cards) }).catch(async () => {
229        for (const key of claims)
230            await $.store.delete(key).catch(() => { });
231        for (const card of cards)
232            live.handedTold.delete(card.requestId);
233        live.handedAt = (await $.clock.now()) + RETRY_MS;
234    });
235}
236async function listenHanded($) {
237    const presence = live.presence;
238    if (!presence || live.waiting || !live.sessionId)
239        return;
240    const now = await $.clock.now();
241    const me = live.sessionId;
242    const record = readListener(await $.store.get(LISTENER_KEY));
243    if (!mayListen(record, me, live.seenAt, now))
244        return;
245    const lease = leaseFor(record, me, now);
246    await $.store.set(LISTENER_KEY, lease);
247    if (readListener(await $.store.get(LISTENER_KEY))?.by !== me)
248        return;
249    const argv = listenArgv(presence.config, presence.origin, lease.since);
250    let run;
251    try {
252        run = $.process.run(argv, { timeoutMs: LISTEN_RUN_MS });
253    }
254    catch {
255        await $.store.set(LISTENER_KEY, listened(lease, readWait(''), now));
256        return;
257    }
258    live.waiting = true;
259    run
260        .then((ran) => (ran.exitCode === 0 ? readWait(ran.stdout) : UNHEARD), () => UNHEARD)
261        .then(async (heard) => {
262        const at = await $.clock.now();
263        const current = readListener(await $.store.get(LISTENER_KEY));
264        if (!current || current.by === me)
265            await $.store.set(LISTENER_KEY, listened(lease, heard, at));
266        if ('handed' in heard && heard.handed.length) {
267            await $.store.set(SIGNAL_KEY, { at });
268            live.signalSeen = at;
269            live.handedAt = 0;
270        }
271    })
272        .catch(() => { })
273        .finally(() => {
274        live.waiting = false;
275        soon($);
276    });
277}
278async function heedSignal($) {
279    const at = readSignal(await $.store.get(SIGNAL_KEY));
280    if (at <= live.signalSeen)
281        return;
282    live.signalSeen = at;
283    live.handedAt = 0;
284}
285async function prune($) {
286    const now = await $.clock.now();
287    for (const key of await $.store.keys()) {
288        if (key.startsWith(CLAIM_PREFIX)) {
289            if (now - (readClaim(await $.store.get(key))?.at ?? 0) > KEEP_MS)
290                await $.store.delete(key);
291            continue;
292        }
293        if (!key.startsWith('session:') || key === keyOf(live.sessionId))
294            continue;
295        if (isStale(readBook(await $.store.get(key)), now))
296            await $.store.delete(key);
297    }
298}
299async function setupDone($) {
300    const record = readSetup(await $.store.get('setup'));
301    if (!record.done)
302        await $.store.set('setup', { ...record, done: true });
303    live.setupDue = false;
304}
305async function deliverSetup($) {
306    if (!live.setupDue || live.busy)
307        return;
308    live.setupDue = false;
309    const now = await $.clock.now();
310    const record = readSetup(await $.store.get('setup'));
311    if (!setupNeeded(record, live.sessionId, now))
312        return;
313    await $.store.set('setup', prompted(record, live.sessionId, now));
314    $.prompt.submit({ text: setupPrompt(live.setupConnection) }).catch(() => { });
315}
316async function checkSetup($, attempt) {
317    try {
318        if (!setupNeeded(readSetup(await $.store.get('setup')), live.sessionId, await $.clock.now()))
319            return;
320        const decided = await $.tool.check({ tool: `mcp__${SETUP_SERVER}__whoami`, input: {} });
321        if (decided.decision !== 'allow')
322            return;
323        let setUp = null;
324        try {
325            const output = resultObject(await $.mcp.call(SETUP_SERVER, 'whoami', {}));
326            setUp = setUpOf(output);
327            live.setupConnection = connectionOf(output);
328        }
329        catch { }
330        if (setUp === null) {
331            if (attempt < SETUP_TRIES)
332                $.clock.after(SETUP_RETRY_MS, () => checkSetup($, attempt + 1));
333            return;
334        }
335        if (setUp)
336            await setupDone($);
337        else {
338            live.setupDue = true;
339            await deliverSetup($);
340        }
341    }
342    catch { }
343}
344async function tick($) {
345    if (live.ticking || !live.sessionId)
346        return;
347    live.ticking = true;
348    try {
349        await deliverSetup($);
350        if (!live.pruned) {
351            live.pruned = true;
352            await prune($);
353        }
354        if (!(await claim($))) {
355            show($, undefined);
356            return;
357        }
358        const now = await $.clock.now();
359        const settled = settle(live.book, now);
360        if (settled !== live.book) {
361            live.book = settled;
362            await save($);
363        }
364        for (const card of dueCards(live.book, now))
365            await check($, card.requestId);
366        await listenHanded($).catch(() => { });
367        await heedSignal($).catch(() => { });
368        if (!(await deliver($)))
369            await deliverHanded($);
370        showCards($);
371    }
372    catch {
373    }
374    finally {
375        live.ticking = false;
376    }
377}
378function soon($) {
379    try {
380        $.clock.after(1500, () => tick($));
381    }
382    catch { }
383}
384function freshHanded() {
385    live.seenAt = Object.keys(live.book.cards).length ? live.book.updatedAt : 0;
386    live.handedAt = 0;
387    live.handedTold = new Map();
388}
389async function folderOfSession($, cwd) {
390    live.folders = typeof cwd === 'string' && cwd ? [cwd] : [];
391    try {
392        live.home = (await $.env.get('HOME')) || undefined;
393    }
394    catch {
395        live.home = undefined;
396    }
397}
398async function noteLoaded($) {
399    try {
400        const config = cliConfigOf($.plugin.root, $.plugin.name);
401        const path = config && live.sessionId ? loadedPath(config, live.sessionId) : null;
402        if (path)
403            await $.fs.write(path, loadedNote(await $.clock.now()));
404    }
405    catch { }
406}
407async function sayLive($) {
408    try {
409        const presence = live.presence;
410        if (!presence || !live.sessionId)
411            return;
412        const argv = presenceArgv(presence.config, presence.origin, {
413            id: live.sessionId,
414            ...(live.folders[0] ? { cwd: live.folders[0] } : {}),
415            ...(live.book.name ? { name: live.book.name } : {}),
416            at: await $.clock.now(),
417        });
418        $.process.run(argv, { timeoutMs: PRESENCE_RUN_MS }).catch(() => { });
419    }
420    catch { }
421}
422async function startPresence($) {
423    live.presenceTimer?.cancel();
424    live.presenceTimer = null;
425    live.presence = null;
426    const config = cliConfigOf($.plugin.root, $.plugin.name);
427    if (!config)
428        return;
429    let manifest = null;
430    try {
431        manifest = await $.fs.read(`${config}/claude-code.json`);
432    }
433    catch { }
434    const origin = originOf(manifest);
435    if (!origin)
436        return;
437    live.presence = { config, origin };
438    await sayLive($);
439    live.presenceTimer = $.clock.every(PRESENCE_EVERY_MS, () => sayLive($));
440}
441async function start($, e) {
442    live.me = $.plugin.name;
443    live.sessionId = await $.session.id();
444    live.book = readBook(await $.store.get(keyOf(live.sessionId)));
445    freshHanded();
446    await folderOfSession($, e.cwd);
447    await noteLoaded($);
448    await claim($);
449    live.timer?.cancel();
450    live.timer = $.clock.every(TICK_MS, () => tick($));
451    soon($);
452    await startPresence($).catch(() => { });
453    await startHerdr($).catch(() => { });
454    if ($.plugin.name === CLI_COPY && e.isInteractive !== false)
455        $.clock.after(SETUP_AFTER_MS, () => checkSetup($, 1));
456}
457async function switchSession($, e) {
458    const id = typeof e.session_id === 'string' && e.session_id ? e.session_id : await $.session.id();
459    if (!id || id === live.sessionId)
460        return;
461    const carried = e.source === 'fork' ? live.book : null;
462    live.sessionId = id;
463    live.book = carried ?? readBook(await $.store.get(keyOf(id)));
464    live.noted.clear();
465    freshHanded();
466    await noteLoaded($);
467    if (typeof e.cwd === 'string' && e.cwd)
468        await folderOfSession($, e.cwd);
469    if (carried)
470        await save($);
471    live.herdrSaid = undefined;
472    showCards($);
473    await sayLive($);
474}
475async function observe($, e, result) {
476    const found = cardTool(e.tool);
477    if (!found || !live.sessionId)
478        return result;
479    const output = resultObject(result);
480    if ($.plugin.name === CLI_COPY && found.tool === 'whoami' && setUpOf(output) === true)
481        await setupDone($);
482    const now = await $.clock.now();
483    if (output) {
484        live.seenAt = now;
485        live.handedAt = Math.min(live.handedAt, now + HANDED_FAST_MS);
486    }
487    const read = e.requestId ?? output?.requestId;
488    if (HANDED_READS.has(found.tool) && typeof read === 'string')
489        live.handedTold.set(read, `*${now}`);
490    const folder = output ? folderOf(found.tool, argumentsOf(e)) : undefined;
491    if (folder && !live.folders.includes(folder))
492        live.folders = [...live.folders, folder].slice(-5);
493    const before = live.book;
494    live.book = learn(live.book, { ...found, input: argumentsOf(e), output }, now);
495    if (live.book === before)
496        return result;
497    await save($);
498    const id = output?.requestId ?? e.requestId;
499    const card = typeof id === 'string' ? live.book.cards[id] : undefined;
500    if (live.owner && card?.state && isWaitingOnYou(card.state) && !live.verified.has(card.server)) {
501        const outcome = await check($, card.requestId);
502        if (outcome === 'blocked' && !live.noted.has(card.server)) {
503            live.noted.add(card.server);
504            showCards($);
505            return { ...result, context: [...(result.context ?? []), blockedNote(card.server)] };
506        }
507    }
508    showCards($);
509    return result;
510}
511async function answerHold($, e) {
512    const requestId = typeof e.command === 'string' ? holdOf(e.command) : null;
513    if (!requestId || !live.sessionId)
514        return null;
515    const known = live.book.cards[requestId];
516    const server = known?.server ?? live.book.server;
517    if (!server)
518        return null;
519    if (!known) {
520        const now = await $.clock.now();
521        const name = live.book.name;
522        live.book = put(live.book, {
523            requestId,
524            server,
525            ...(name ? { name } : {}),
526            learnedAt: now,
527            changedAt: now,
528            nextAt: now,
529        });
530        await save($);
531    }
532    if (!(await claim($)))
533        return null;
534    if ((await check($, requestId)) !== 'ok')
535        return null;
536    showCards($);
537    const answer = live.book.cards[requestId]?.kind === 'answer';
538    return { result: { stdout: holdReply(requestId, answer), stderr: '', interrupted: false } };
539}
540export function register(on) {
541    on('session.start', async ($, e, next) => {
542        try {
543            await start($, e);
544        }
545        catch { }
546        return next(e);
547    });
548    on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
549        try {
550            await switchSession($, e);
551        }
552        catch { }
553        return next(e);
554    });
555    on('turn.start', async (_, e, next) => {
556        if (!e.agentId)
557            live.busy = true;
558        return next(e);
559    });
560    on('turn.complete', async ($, e, next) => {
561        if (!e.agentId) {
562            live.busy = false;
563            soon($);
564        }
565        return next(e);
566    });
567    on('tool.call', {
568        tool: /^mcp__.+__(post_request|post_answer|get_request|update_request|reply_in_thread|ack_answer|cancel_request|whoami|list_pending|answer_delegated|hand_back)$/,
569    }, async ($, e, next) => {
570        const result = await next(e);
571        try {
572            return await observe($, e, result);
573        }
574        catch {
575            return result;
576        }
577    });
578    on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
579        let answer = null;
580        try {
581            answer = await answerHold($, e);
582        }
583        catch { }
584        return answer ?? next(e);
585    });
586}
587
hooks/wake.js 981 lines
1// Generated from packages/claude-plugin/src/wake/wake.ts in recordplane/pendingyou: edit that, then run
2// `pnpm --filter @pendingyou/claude-plugin generate`.
3
4export const TICK_MS = 5000;
5export const FAST_MS = 20_000;
6export const SLOW_MS = 60_000;
7export const RECENT_MS = 30 * 60_000;
8export const MAX_BACKOFF_MS = 15 * 60_000;
9export const HINT_FLOOR_MS = 5000;
10export const BLOCKED_MS = 60_000;
11export const FRESH_MS = 10_000;
12export const KEEP_MS = 7 * 24 * 60 * 60_000;
13export const MAX_CARDS = 50;
14export const LEASE_MS = 60_000;
15export const RENEW_MS = 20_000;
16export const TITLE_CHARS = 80;
17const REQUEST_ID = /^req_[A-Za-z0-9-]{1,40}$/;
18const OPEN = new Set(['pending', 'snoozed', 'delegated']);
19const CLOSED = new Set(['resolved', 'cancelled', 'expired']);
20const URGENCIES = new Set(['now', 'today', 'whenever']);
21const isUrgency = (value) => typeof value === 'string' && URGENCIES.has(value);
22const READS = new Set([
23    'post_request',
24    'post_answer',
25    'get_request',
26    'update_request',
27    'reply_in_thread',
28    'ack_answer',
29    'cancel_request',
30    'whoami',
31    'list_pending',
32    'answer_delegated',
33    'hand_back',
34]);
35export const HANDED_READS = new Set(['get_request', 'answer_delegated', 'hand_back']);
36const POSTS = new Set(['post_request', 'post_answer']);
37export const APPROVED_DRAFT_NOTICE = 'The approved words are in get_request’s answer.approvedDrafts: send them exactly.';
38const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
39const parseJson = (text) => {
40    try {
41        return JSON.parse(text);
42    }
43    catch {
44        return undefined;
45    }
46};
47const text = (value, max = 200) => typeof value === 'string' && value.trim() && value.length <= max ? value.trim() : undefined;
48const count = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
49const requestIdOf = (value) => typeof value === 'string' && REQUEST_ID.test(value) ? value : undefined;
50export function clip(title) {
51    const flat = title.replace(/\s+/g, ' ').trim().replaceAll('“', '‘').replaceAll('”', '’');
52    const chars = [...flat];
53    return chars.length <= TITLE_CHARS
54        ? flat
55        : `${chars
56            .slice(0, TITLE_CHARS - 1)
57            .join('')
58            .trimEnd()}…`;
59}
60export const isPendingYou = (server) => server
61    .toLowerCase()
62    .replace(/[^a-z0-9]/g, '')
63    .includes('pendingyou');
64export function cardTool(name) {
65    const match = /^mcp__(.+)__([a-z_]+)$/.exec(name);
66    if (!match)
67        return null;
68    const [, server = '', tool = ''] = match;
69    return READS.has(tool) && isPendingYou(server) ? { server, tool } : null;
70}
71export function resultObject(result) {
72    if (!isObject(result) || result.deny !== undefined || result.isError === true)
73        return null;
74    if (isObject(result.structuredContent))
75        return result.structuredContent;
76    const texts = [];
77    const blocks = (value) => {
78        if (Array.isArray(value))
79            for (const block of value)
80                if (isObject(block) && typeof block.text === 'string')
81                    texts.push(block.text);
82    };
83    if (typeof result.text === 'string')
84        texts.push(result.text);
85    if (typeof result.result === 'string')
86        texts.push(result.result);
87    else if (isObject(result.result)) {
88        if (isObject(result.result.structuredContent))
89            return result.result.structuredContent;
90        blocks(result.result.content);
91    }
92    else
93        blocks(result.result);
94    blocks(result.content);
95    for (const each of texts) {
96        const parsed = parseJson(each);
97        if (isObject(parsed))
98            return parsed;
99    }
100    return null;
101}
102export function nameOf(tool, input) {
103    const name = text(input.name, 120);
104    if (name || !POSTS.has(tool))
105        return name;
106    const session = typeof input.session === 'string' ? parseJson(input.session) : input.session;
107    return isObject(session) ? text(session.label, 120) : undefined;
108}
109export function argumentsOf(call) {
110    const { tool: _tool, tool_use_id: _id, agentId: _agent, consent: _consent, ...rest } = call;
111    return rest;
112}
113export const isClosed = (status) => CLOSED.has(status);
114export const isReady = (state) => state.turn === 'agent' || isClosed(state.status);
115export const isWaitingOnYou = (state) => state.turn === 'you' && OPEN.has(state.status);
116const waitsOnYou = (card) => card.kind !== 'answer' && card.state !== undefined && isWaitingOnYou(card.state);
117export const momentOf = (state) => `${state.status}/${state.turn}/${state.version}/${state.cursor}`;
118export function stateOf(output) {
119    const status = text(output.status, 40);
120    const turn = output.turn === 'you' || output.turn === 'agent' ? output.turn : undefined;
121    const version = count(output.version);
122    if (!status || !turn || version === undefined)
123        return null;
124    const given = isObject(output.answer) ? output.answer.handled : output.handled;
125    const handled = given === 'self' || given === 'leave' ? given : undefined;
126    const approvedDraft = isObject(output.answer)
127        ? Array.isArray(output.answer.approvedDrafts) && output.answer.approvedDrafts.length > 0
128        : output.approvedDraft === true;
129    return {
130        status,
131        turn,
132        version,
133        cursor: typeof output.cursor === 'string' ? output.cursor : '',
134        ...(handled ? { handled } : {}),
135        ...(approvedDraft ? { approvedDraft: true } : {}),
136    };
137}
138export const emptyBook = (now = 0) => ({ v: 1, updatedAt: now, cards: {} });
139export function readBook(value) {
140    if (!isObject(value) || value.v !== 1 || !isObject(value.cards))
141        return emptyBook();
142    const cards = {};
143    for (const [requestId, card] of Object.entries(value.cards)) {
144        if (!isObject(card) || card.requestId !== requestId || !requestIdOf(requestId))
145            continue;
146        if (typeof card.server !== 'string' || !isPendingYou(card.server))
147            continue;
148        const learnedAt = count(card.learnedAt);
149        const changedAt = count(card.changedAt);
150        if (learnedAt === undefined || changedAt === undefined)
151            continue;
152        const state = isObject(card.state) ? stateOf(card.state) : null;
153        cards[requestId] = {
154            requestId,
155            server: card.server,
156            learnedAt,
157            changedAt,
158            ...(text(card.name, 120) ? { name: text(card.name, 120) } : {}),
159            ...(text(card.title, 400) ? { title: text(card.title, 400) } : {}),
160            ...(isUrgency(card.urgency) ? { urgency: card.urgency } : {}),
161            ...(card.blocking === true ? { blocking: true } : {}),
162            ...(card.askedFirst === true ? { askedFirst: true } : {}),
163            ...(card.kind === 'answer' ? { kind: 'answer' } : {}),
164            ...(state ? { state } : {}),
165            ...(typeof card.told === 'string' ? { told: card.told } : {}),
166            ...(typeof card.seen === 'string' ? { seen: card.seen } : {}),
167            ...(count(card.failures) ? { failures: count(card.failures) } : {}),
168            ...(count(card.nextAt) !== undefined ? { nextAt: count(card.nextAt) } : {}),
169        };
170    }
171    return {
172        v: 1,
173        updatedAt: count(value.updatedAt) ?? 0,
174        ...(text(value.name, 120) ? { name: text(value.name, 120) } : {}),
175        ...(typeof value.server === 'string' && isPendingYou(value.server)
176            ? { server: value.server }
177            : {}),
178        cards,
179    };
180}
181const listening = (card) => {
182    const state = card.state;
183    if (!state || isWaitingOnYou(state))
184        return true;
185    const moment = momentOf(state);
186    return moment !== card.told && moment !== card.seen;
187};
188export function put(book, card) {
189    const cards = { ...book.cards, [card.requestId]: card };
190    const all = Object.values(cards);
191    if (all.length > MAX_CARDS)
192        for (const old of all
193            .sort((a, b) => Number(listening(a)) - Number(listening(b)) || a.changedAt - b.changedAt)
194            .slice(0, all.length - MAX_CARDS))
195            delete cards[old.requestId];
196    return { ...book, cards };
197}
198export function drop(book, requestId) {
199    if (!book.cards[requestId])
200        return book;
201    const { [requestId]: _gone, ...cards } = book.cards;
202    return { ...book, cards };
203}
204const pressingOfCard = (card) => ({
205    ...(card?.urgency ? { urgency: card.urgency } : {}),
206    ...(card?.blocking ? { blocking: true } : {}),
207    ...(card?.askedFirst ? { askedFirst: true } : {}),
208});
209function askedFirstIn(input) {
210    const asked = typeof input.askedFirst === 'string' ? parseJson(input.askedFirst) : input.askedFirst;
211    return isObject(asked);
212}
213function pressingFrom(tool, input, card) {
214    const urgency = isUrgency(input.urgency) ? input.urgency : card?.urgency;
215    const blocking = typeof input.blocking === 'boolean' ? input.blocking : card?.blocking === true;
216    const askedFirst = tool === 'post_request' ? askedFirstIn(input) : card?.askedFirst === true;
217    return {
218        ...(urgency ? { urgency } : {}),
219        ...(blocking ? { blocking: true } : {}),
220        ...(askedFirst ? { askedFirst: true } : {}),
221    };
222}
223function tracked(book, facts, now) {
224    const card = book.cards[facts.requestId];
225    const name = facts.name ?? card?.name;
226    const title = facts.title ?? card?.title;
227    const kind = facts.kind ?? card?.kind;
228    return put(book, {
229        requestId: facts.requestId,
230        server: facts.server,
231        ...(name ? { name } : {}),
232        ...(title ? { title } : {}),
233        ...(facts.pressing ?? pressingOfCard(card)),
234        ...(kind ? { kind } : {}),
235        learnedAt: card?.learnedAt ?? now,
236        changedAt: now,
237        state: facts.state,
238        nextAt: now + FAST_MS,
239    });
240}
241function followedUp(book, follows, now) {
242    const card = follows ? book.cards[follows] : undefined;
243    if (!card)
244        return book;
245    const heard = card.state && isReady(card.state) ? { seen: momentOf(card.state) } : {};
246    return put(book, { ...card, ...heard, nextAt: now });
247}
248export function learn(book, call, now) {
249    const { server, tool, input, output } = call;
250    if (!output)
251        return book;
252    const name = nameOf(tool, input);
253    let next = book;
254    if (name && (book.name !== name || book.server !== server))
255        next = { ...next, name, server };
256    const requestId = requestIdOf(output.requestId) ?? requestIdOf(input.requestId);
257    if (!requestId)
258        return next;
259    const card = next.cards[requestId];
260    const version = count(output.version);
261    switch (tool) {
262        case 'post_request':
263        case 'update_request': {
264            const status = text(output.status, 40);
265            if (!status || !OPEN.has(status) || version === undefined)
266                return next;
267            const title = text(input.title, 400);
268            const posted = tracked(next, {
269                requestId,
270                server,
271                ...(name ? { name } : {}),
272                ...(title ? { title: clip(title) } : {}),
273                pressing: pressingFrom(tool, input, card),
274                state: { status, turn: 'you', version, cursor: card?.state?.cursor ?? '' },
275            }, now);
276            return tool === 'post_request' ? followedUp(posted, requestIdOf(input.follows), now) : posted;
277        }
278        case 'post_answer': {
279            const status = text(output.status, 40);
280            if (!status || !OPEN.has(status) || version === undefined)
281                return next;
282            const title = text(input.title, 400);
283            const posted = tracked(next, {
284                requestId,
285                server,
286                ...(name ? { name } : {}),
287                ...(title ? { title: clip(title) } : {}),
288                pressing: {},
289                kind: 'answer',
290                state: { status, turn: 'you', version, cursor: card?.state?.cursor ?? '' },
291            }, now);
292            return followedUp(posted, requestIdOf(input.follows), now);
293        }
294        case 'reply_in_thread': {
295            const reopen = isObject(input.reopen) ? input.reopen : null;
296            if (version === undefined || (!reopen && output.turn !== 'you'))
297                return next;
298            const title = reopen ? text(reopen.title, 400) : undefined;
299            const status = reopen ? 'pending' : (card?.state?.status ?? 'pending');
300            const cursor = typeof output.messageId === 'string' ? output.messageId : '';
301            return tracked(next, {
302                requestId,
303                server,
304                ...(name ? { name } : {}),
305                ...(title ? { title: clip(title) } : {}),
306                state: { status: OPEN.has(status) ? status : 'pending', turn: 'you', version, cursor },
307            }, now);
308        }
309        case 'get_request': {
310            const state = stateOf(output);
311            if (!state)
312                return next;
313            if (!card)
314                return isWaitingOnYou(state)
315                    ? tracked(next, { requestId, server, ...(name ? { name } : {}), state }, now)
316                    : next;
317            const moment = momentOf(state);
318            const changed = !card.state || momentOf(card.state) !== moment;
319            return put(next, {
320                ...card,
321                state,
322                ...(changed ? { changedAt: now } : {}),
323                ...(isReady(state) ? { seen: moment } : {}),
324            });
325        }
326        case 'ack_answer':
327            return output.status === 'resolved' ? drop(next, requestId) : next;
328        case 'cancel_request':
329            return output.status === 'cancelled' || output.status === 'resolved'
330                ? drop(next, requestId)
331                : next;
332        default:
333            return next;
334    }
335}
336export function checked(card, output, now) {
337    const state = stateOf(output) ?? card.state;
338    if (!state)
339        return failed(card, now, false);
340    const changed = !card.state || momentOf(card.state) !== momentOf(state);
341    const changedAt = changed ? now : card.changedAt;
342    let wait = now - changedAt < RECENT_MS ? FAST_MS : SLOW_MS;
343    const pollAfter = count(output.pollAfterSeconds);
344    if (!isReady(state) && pollAfter !== undefined && pollAfter * 1000 < wait)
345        wait = Math.max(HINT_FLOOR_MS, pollAfter * 1000 + 1000);
346    const { failures: _failures, ...rest } = card;
347    return { ...rest, state, changedAt, nextAt: now + wait, checkedAt: now };
348}
349export function failed(card, now, blocked) {
350    if (blocked)
351        return { ...card, nextAt: now + BLOCKED_MS };
352    const failures = (card.failures ?? 0) + 1;
353    return {
354        ...card,
355        failures,
356        nextAt: now + Math.min(MAX_BACKOFF_MS, FAST_MS * 2 ** (failures - 1)),
357    };
358}
359export const ANSWER_UNDO_MS = 20_000;
360const mayComeBack = (card) => card.kind === 'answer' &&
361    card.state?.status === 'resolved' &&
362    !(card.checkedAt !== undefined && card.checkedAt - card.changedAt >= ANSWER_UNDO_MS);
363export function dueCards(book, now) {
364    return Object.values(book.cards)
365        .filter((card) => !(card.state && isClosed(card.state.status) && !mayComeBack(card)) &&
366        (card.nextAt ?? 0) <= now)
367        .sort((a, b) => (a.nextAt ?? 0) - (b.nextAt ?? 0));
368}
369export function needsTelling(card) {
370    const state = card.state;
371    if (!state || !isReady(state))
372        return false;
373    if (card.kind === 'answer' && isClosed(state.status))
374        return false;
375    if (state.status === 'resolved')
376        return false;
377    const moment = momentOf(state);
378    if (moment === card.told || moment === card.seen)
379        return false;
380    if (state.status === 'cancelled' && (card.told || card.seen))
381        return false;
382    return true;
383}
384export const isFresh = (card, now) => card.checkedAt !== undefined && now - card.checkedAt <= FRESH_MS;
385export const toTell = (book) => Object.values(book.cards)
386    .filter(needsTelling)
387    .sort((a, b) => a.changedAt - b.changedAt);
388export function told(book, cards) {
389    let next = book;
390    for (const card of cards) {
391        const current = next.cards[card.requestId];
392        if (current?.state)
393            next = put(next, { ...current, told: momentOf(current.state) });
394    }
395    return next;
396}
397export function untold(book, before) {
398    let next = book;
399    for (const card of before) {
400        const current = next.cards[card.requestId];
401        if (!current?.state || current.told !== momentOf(current.state))
402            continue;
403        const { told: _told, ...rest } = current;
404        next = put(next, card.told === undefined ? rest : { ...rest, told: card.told });
405    }
406    return next;
407}
408export function settle(book, now) {
409    let next = book;
410    for (const card of Object.values(book.cards)) {
411        const done = card.state && isClosed(card.state.status) && !needsTelling(card) && !mayComeBack(card);
412        if (done || now - Math.max(card.learnedAt, card.changedAt) > KEEP_MS)
413            next = drop(next, card.requestId);
414    }
415    return next;
416}
417export const isStale = (book, now) => now - book.updatedAt > KEEP_MS;
418const titled = (card) => card.title ? `“${clip(card.title)}” (${card.requestId})` : card.requestId;
419const named = (card) => (card.name ? `name “${card.name}”` : 'your name');
420function line(card) {
421    const state = card.state;
422    const get = `get_request (requestId ${card.requestId}, ${named(card)})`;
423    if (card.kind === 'answer')
424        return [
425            `your person replied to your answer ${titled(card)}`,
426            `call ${get}, act on their words, then ack_answer with its version and a one-line outcome (it reaches them as your reply), or post_answer with follows: its requestId for a long one`,
427        ];
428    switch (state.status) {
429        case 'expired':
430            return [
431                `nobody answered ${titled(card)} in time, so its fallback is due`,
432                'do it now if you haven’t already; there’s nothing to acknowledge',
433            ];
434        case 'cancelled':
435            return [`${titled(card)} was withdrawn`, 'nothing to do'];
436        case 'answered':
437            if (state.handled === 'self')
438                return [
439                    `your person will handle ${titled(card)} themselves`,
440                    `call ${get} to read it, then close it out: take no action on it, leave things as they are and don’t follow up; ack_answer with its version and an outcome like “Left to you”`,
441                ];
442            if (state.handled === 'leave')
443                return [
444                    `your person won’t do ${titled(card)}`,
445                    `call ${get} to read it, then close it out: don’t do it for them and don’t follow up; ack_answer with its version and an outcome like “Skipped”`,
446                ];
447            return [
448                `your person answered ${titled(card)}`,
449                `call ${get}, act on their words, then ack_answer with its version and a one-line outcome${state.approvedDraft ? `. ${APPROVED_DRAFT_NOTICE.slice(0, -1)}` : ''}`,
450            ];
451        case 'delegated':
452            return [
453                `there’s word on ${titled(card)}, which your person handed to another assistant`,
454                `call ${get} and do what its helper.next says`,
455            ];
456        default:
457            return [
458                `your person wrote to you on ${titled(card)}`,
459                `call ${get} to read it, then answer with reply_in_thread`,
460            ];
461    }
462}
463const capital = (sentence) => sentence.charAt(0).toUpperCase() + sentence.slice(1);
464export function wakeText(cards) {
465    const asked = cards.some((card) => card.state?.turn === 'agent' &&
466        !isClosed(card.state.status) &&
467        card.state.status !== 'delegated' &&
468        !card.state.handled);
469    const reopen = asked
470        ? ' If you need more from them, or the next step, post a new card with follows: that card’s requestId; never reopen.'
471        : '';
472    if (cards.length === 1) {
473        const [happened, todo] = line(cards[0]);
474        return `Pending You: ${happened}. ${capital(todo)}.${reopen}`;
475    }
476    return [
477        `Pending You: ${cards.length} of your cards need you.`,
478        ...cards.map((card) => {
479            const [happened, todo] = line(card);
480            return `- ${capital(happened)}: ${todo}.`;
481        }),
482        ...(reopen ? [reopen.trim()] : []),
483    ].join('\n');
484}
485export function statusText(book, blocked) {
486    if (blocked)
487        return `to hear answers here, allow mcp__${blocked} in /permissions`;
488    const waiting = Object.values(book.cards).filter(waitsOnYou).length;
489    return waiting ? `${waiting} waiting on you` : undefined;
490}
491export const blockedNote = (server) => `Pending You can’t wake this session when your person answers: Claude Code doesn’t let it check your cards yet. Ask them to allow mcp__${server} in /permissions (Allow, user settings). Until then, check get_request at breakpoints.`;
492export const isRefusal = (error) => /refused|permission|not allowed|haven.t granted/i.test(error instanceof Error ? error.message : String(error));
493export function shellWords(command) {
494    const words = [];
495    let word = '';
496    let inWord = false;
497    let quote = null;
498    for (let index = 0; index < command.length; index++) {
499        const char = command[index];
500        if (quote === "'") {
501            if (char === "'")
502                quote = null;
503            else
504                word += char;
505            continue;
506        }
507        if (quote === '"') {
508            if (char === '"')
509                quote = null;
510            else if (char === '$' || char === '`')
511                return null;
512            else if (char === '\\' && '"\\$`'.includes(command[index + 1] ?? ''))
513                word += command[++index];
514            else
515                word += char;
516            continue;
517        }
518        if (char === "'" || char === '"') {
519            quote = char;
520            inWord = true;
521        }
522        else if (char === '\\') {
523            const escaped = command[++index];
524            if (escaped === undefined || escaped === '\n')
525                return null;
526            word += escaped;
527            inWord = true;
528        }
529        else if (char === ' ' || char === '\t') {
530            if (inWord)
531                words.push(word);
532            word = '';
533            inWord = false;
534        }
535        else if (char === '#' && !inWord)
536            break;
537        else if (';&|<>()`$\n\r'.includes(char))
538            return null;
539        else {
540            word += char;
541            inWord = true;
542        }
543    }
544    if (quote)
545        return null;
546    if (inWord)
547        words.push(word);
548    return words;
549}
550const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
551const PACKAGE = /^pendingyou(@[\w.^~=<>*-]+)?$/;
552const NPX_FLAGS = new Set(['-y', '--yes', '-q', '--quiet', '--prefer-offline', '--prefer-online']);
553const OPTION = /^--(origin|timeout)=\S+$/;
554export function holdOf(command) {
555    const words = shellWords(command.trim());
556    if (!words?.length)
557        return null;
558    let index = 0;
559    const at = () => words[index] ?? '';
560    if (at() === 'env')
561        index++;
562    while (ASSIGNMENT.test(at()))
563        index++;
564    if (at() === 'npx') {
565        index++;
566        while (NPX_FLAGS.has(at()))
567            index++;
568        if (!PACKAGE.test(at()))
569            return null;
570        index++;
571    }
572    else if (at() === 'pnpm' && words[index + 1] === 'dlx') {
573        index += 2;
574        if (!PACKAGE.test(at()))
575            return null;
576        index++;
577    }
578    else if (at() === 'pendingyou')
579        index++;
580    else {
581        if (/(^|\/)node$/.test(at()))
582            index++;
583        if (!/(^|\/)pendingyou\/dist\/cli\.js$/.test(at()))
584            return null;
585        index++;
586    }
587    let requestId = null;
588    let held = false;
589    while (index < words.length) {
590        const word = at();
591        if (OPTION.test(word))
592            index++;
593        else if (word === '--origin' || word === '--timeout') {
594            if (index + 1 >= words.length)
595                return null;
596            index += 2;
597        }
598        else if (!held && word === 'hold') {
599            held = true;
600            index++;
601        }
602        else if (held && !requestId && REQUEST_ID.test(word)) {
603            requestId = word;
604            index++;
605        }
606        else
607            return null;
608    }
609    return held ? requestId : null;
610}
611export const holdReply = (requestId, answer = false) => `Pending You: no hold is needed in this session. It’s woken when your person ${answer ? `replies to your answer ${requestId}` : `answers ${requestId}, writes to you on it, or its fallback runs`}, even while it’s idle. Nothing is running in the background and there’s nothing to wait on: keep working, or end your turn.`;
612function leaseOf(value) {
613    const match = /^(\S+) (\d+)$/.exec(value ?? '');
614    return match ? { holder: match[1], until: Number(match[2]) } : null;
615}
616export function leaseHolder(value, now) {
617    const lease = leaseOf(value);
618    return lease && lease.until > now ? lease.holder : null;
619}
620export function claimLease(value, me, now) {
621    const lease = leaseOf(value);
622    if (lease && lease.until > now && lease.holder !== me)
623        return null;
624    if (lease && lease.holder === me && lease.until - now > LEASE_MS - RENEW_MS)
625        return null;
626    return `${me} ${now + LEASE_MS}`;
627}
628export const HANDED_FAST_MS = 60_000;
629export const HANDED_SLOW_MS = 3 * 60_000;
630export const HANDED_FOR_MS = 12 * 60 * 60_000;
631export const HANDED_GRACE_MS = 30_000;
632export const CLAIM_PREFIX = 'handed:';
633export const HANDED_PREFIX = 'Pending You: your person handed you';
634export const HANDED_REPLY = 'on the question handed to you';
635export const HANDED_TALK_TODO = 'If you know now, answer_delegated with your answer and how you know; if you need more, reply_in_thread to “asker”; if it’s your person’s to decide, reply_in_thread with escalate true; if not, hand_back with what you checked.';
636const SAID_CHARS = 300;
637export const HANDED_TODO = 'If you know, answer_delegated with your answer and how you know; if not, hand_back with what you checked.';
638const NAME_CHARS = 60;
639export function latestSaid(talk, from) {
640    if (!Array.isArray(talk))
641        return null;
642    const said = talk.filter(isObject);
643    const mine = said.findLastIndex((each) => each.from === 'helper');
644    const last = said.slice(mine + 1).at(-1);
645    const words = last ? text(last.body, 4000) : undefined;
646    if (!last || !words || (last.from !== 'asker' && last.from !== 'you'))
647        return null;
648    return { who: last.from === 'you' ? 'your person' : from, words };
649}
650export function readSince(known, updatedAt) {
651    if (!known?.startsWith('*'))
652        return false;
653    const at = Number(known.slice(1));
654    return !Number.isFinite(at) || at === 0 || Date.parse(updatedAt) <= at;
655}
656export const handedDue = (seenAt, nextAt, now) => seenAt > 0 && now - seenAt < HANDED_FOR_MS && now >= nextAt;
657export const handedNext = (seenAt, now) => now + (now - seenAt < RECENT_MS ? HANDED_FAST_MS : HANDED_SLOW_MS);
658export function handedOf(output) {
659    const requests = output && Array.isArray(output.requests) ? output.requests : [];
660    return requests.flatMap((request) => {
661        if (!isObject(request) || request.delegated !== true)
662            return [];
663        if (request.status !== 'delegated' || request.turn !== 'agent')
664            return [];
665        const requestId = requestIdOf(request.id);
666        const title = text(request.title, 400);
667        const updatedAt = text(request.updatedAt, 40);
668        const cwd = text(request.cwd, 1000);
669        return requestId && title && updatedAt
670            ? [
671                {
672                    requestId,
673                    title,
674                    updatedAt,
675                    ...(cwd ? { cwd } : {}),
676                    ...(request.byName === true ? { byName: true } : {}),
677                },
678            ]
679            : [];
680    });
681}
682export function folderKey(path, home) {
683    const given = path
684        .trim()
685        .replaceAll('\\', '/')
686        .replace(/\/{2,}/g, '/');
687    const base = home?.replace(/\/+$/, '');
688    const full = base && given === '~'
689        ? base
690        : base && given.startsWith('~/')
691            ? `${base}${given.slice(1)}`
692            : given;
693    return (full.replace(/\/+$/, '') || '/').toLowerCase();
694}
695export function inTaskFolder(folders, task, home) {
696    const there = folderKey(task, home);
697    return folders.some((folder) => {
698        const here = folderKey(folder, home);
699        return here === there || here.startsWith(there === '/' ? '/' : `${there}/`);
700    });
701}
702export function takesHanded(handed, folders, home, now) {
703    if (handed.byName || !handed.cwd)
704        return true;
705    if (folders.length === 0)
706        return now - Date.parse(handed.updatedAt) >= HANDED_GRACE_MS;
707    return inTaskFolder(folders, handed.cwd, home);
708}
709export function graceEnds(handed, folders) {
710    if (handed.byName || !handed.cwd || folders.length > 0)
711        return null;
712    const at = Date.parse(handed.updatedAt);
713    return Number.isFinite(at) ? at + HANDED_GRACE_MS : null;
714}
715export function folderOf(tool, input) {
716    if (!POSTS.has(tool))
717        return undefined;
718    const session = typeof input.session === 'string' ? parseJson(input.session) : input.session;
719    return isObject(session) ? text(session.cwd, 1000) : undefined;
720}
721export function handedView(output, handed, name) {
722    const delegated = output && isObject(output.delegated) ? output.delegated : null;
723    if (!delegated || output?.status !== 'delegated' || output.turn !== 'agent')
724        return null;
725    const from = text(delegated.from, 200);
726    const mode = delegated.mode === 'freely' || delegated.mode === 'loop' ? delegated.mode : null;
727    if (!from || !mode)
728        return null;
729    const said = latestSaid(delegated.talk, from);
730    return {
731        requestId: handed.requestId,
732        title: text(delegated.title, 400) ?? handed.title,
733        from,
734        mode,
735        note: typeof delegated.note === 'string' && delegated.note.trim() !== '',
736        name,
737        ...(said ? { said } : {}),
738    };
739}
740export function readClaim(value) {
741    if (!isObject(value) || typeof value.moment !== 'string')
742        return null;
743    const by = text(value.by, 200);
744    return { moment: value.moment, at: count(value.at) ?? 0, ...(by ? { by } : {}) };
745}
746export function claimedElsewhere(value, moment, me) {
747    const claim = readClaim(value);
748    return claim?.moment === moment && claim.by !== me;
749}
750export function claimHeld(value, moment, me) {
751    const claim = readClaim(value);
752    return claim?.moment === moment && claim.by === me;
753}
754export const LISTENER_KEY = 'handed-listener';
755export const SIGNAL_KEY = 'handed-signal';
756export const LISTEN_RUN_MS = 4 * 60_000;
757export const LISTENER_LEASE_MS = LISTEN_RUN_MS + 30_000;
758export const LISTENER_KEEP_MS = 15_000;
759export const LISTEN_RETRY_MS = 2 * 60_000;
760export const LISTEN_QUIET_MS = 30 * 60_000;
761const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
762const isoOf = (value) => typeof value === 'string' && ISO_TIME.test(value) ? value : undefined;
763export function readListener(value) {
764    if (!isObject(value))
765        return null;
766    const by = text(value.by, 200);
767    const until = count(value.until);
768    if (!by || until === undefined)
769        return null;
770    const since = isoOf(value.since);
771    const quietUntil = count(value.quietUntil);
772    return { by, until, ...(since ? { since } : {}), ...(quietUntil ? { quietUntil } : {}) };
773}
774export function mayListen(record, me, seenAt, now) {
775    if (seenAt <= 0 || now - seenAt >= HANDED_FOR_MS)
776        return false;
777    if (record?.quietUntil && now < record.quietUntil)
778        return false;
779    return !record || record.by === me || now >= record.until;
780}
781export const leaseFor = (record, me, now) => ({
782    by: me,
783    until: now + LISTENER_LEASE_MS,
784    ...(record?.since ? { since: record.since } : {}),
785});
786export function readWait(stdout) {
787    const line = stdout.trim().split('\n').at(-1) ?? '';
788    const parsed = parseJson(line);
789    if (!isObject(parsed))
790        return { error: 'unknown' };
791    const since = isoOf(parsed.since);
792    if (parsed.error === 'signin' || parsed.error === 'unavailable')
793        return { error: parsed.error, ...(since ? { since } : {}) };
794    if (!Array.isArray(parsed.handed))
795        return { error: 'unknown' };
796    const handed = parsed.handed.filter((id) => typeof id === 'string' && REQUEST_ID.test(id));
797    return { handed, ...(since ? { since } : {}) };
798}
799export function listened(record, heard, now) {
800    const since = heard.since ?? record.since;
801    const quiet = 'error' in heard
802        ? now + (heard.error === 'unavailable' ? LISTEN_RETRY_MS : LISTEN_QUIET_MS)
803        : undefined;
804    return {
805        by: record.by,
806        until: now + LISTENER_KEEP_MS,
807        ...(since ? { since } : {}),
808        ...(quiet ? { quietUntil: quiet } : {}),
809    };
810}
811export function listenArgv(config, origin, since) {
812    return [
813        `${config}/bin/pendingyou-hook`,
814        'listen',
815        '--handed',
816        '--app',
817        'claude-code',
818        ...(since ? ['--since', since] : []),
819        ...(origin === PRODUCTION ? [] : ['--origin', origin]),
820    ];
821}
822export const readSignal = (value) => (isObject(value) ? (count(value.at) ?? 0) : 0);
823function cut(value, max) {
824    const chars = [...value.replace(/\s+/g, ' ').trim()];
825    return chars.length <= max
826        ? chars.join('')
827        : `${chars
828            .slice(0, max - 1)
829            .join('')
830            .trimEnd()}…`;
831}
832const handedTitled = (card) => `“${clip(card.title)}” (${card.requestId})`;
833function asked(card) {
834    const from = cut(card.from, NAME_CHARS);
835    return `from ${from} (${card.mode === 'freely' ? `answer freely: your answer goes straight to ${from}` : 'they’ll see your answer first'})`;
836}
837const readIt = (card) => `get_request (requestId ${card.requestId}, name “${card.name}”) to read it${card.note ? ' and their note' : ''}`;
838export function handedText(cards) {
839    const quotedSaid = (card) => card.said
840        ? `: “${cut(card.said.words, SAID_CHARS).replaceAll('“', '‘').replaceAll('”', '’')}”`
841        : '';
842    const replied = (said) => said.who === 'your person'
843        ? 'your person wrote to you both'
844        : `${cut(said.who, NAME_CHARS)} replied`;
845    const readTalk = (card) => `get_request (requestId ${card.requestId}, name “${card.name}”) to read what you’ve said to each other`;
846    if (cards.length === 1) {
847        const card = cards[0];
848        if (card.said)
849            return `Pending You: ${replied(card.said)} ${HANDED_REPLY}, ${handedTitled(card)}${quotedSaid(card)}. Call ${readTalk(card)}. ${HANDED_TALK_TODO}`;
850        return `${HANDED_PREFIX} ${handedTitled(card)}, a question ${asked(card)}. Call ${readIt(card)}. ${HANDED_TODO}`;
851    }
852    return [
853        `${HANDED_PREFIX} ${cards.length} questions from other assistants.`,
854        ...cards.map((card) => card.said
855            ? `- ${handedTitled(card)}, ${asked(card)}; ${replied(card.said)}${quotedSaid(card)}: call ${readTalk(card)}.`
856            : `- ${handedTitled(card)}, ${asked(card)}: call ${readIt(card)}.`),
857        `For each one: ${HANDED_TODO.charAt(0).toLowerCase()}${HANDED_TODO.slice(1)}${cards.some((card) => card.said) ? ' Where one replied, you may also reply_in_thread to “asker”, or escalate.' : ''}`,
858    ].join('\n');
859}
860export const CLI_COPY = 'pendingyou-wake';
861export const SETUP_SERVER = 'pendingyou';
862export const SETUP_AFTER_MS = 3000;
863export const SETUP_RETRY_MS = 10_000;
864export const SETUP_TRIES = 3;
865export const SETUP_SESSIONS = 3;
866export const SETUP_QUIET_MS = 10 * 60_000;
867export function readSetup(value) {
868    if (!isObject(value))
869        return { done: false, sessions: [], lastAt: 0 };
870    return {
871        done: value.done === true,
872        sessions: Array.isArray(value.sessions)
873            ? value.sessions.filter((id) => typeof id === 'string').slice(-SETUP_SESSIONS)
874            : [],
875        lastAt: count(value.lastAt) ?? 0,
876    };
877}
878export function setUpOf(output) {
879    const app = output && isObject(output.app) ? output.app : null;
880    return typeof app?.setUp === 'boolean' ? app.setUp : null;
881}
882export function setupNeeded(record, sessionId, now) {
883    return (!record.done &&
884        !record.sessions.includes(sessionId) &&
885        record.sessions.length < SETUP_SESSIONS &&
886        now - record.lastAt >= SETUP_QUIET_MS);
887}
888export const prompted = (record, sessionId, now) => ({
889    ...record,
890    sessions: [...record.sessions, sessionId].slice(-SETUP_SESSIONS),
891    lastAt: now,
892});
893export function connectionOf(output) {
894    const app = output && isObject(output.app) ? output.app : null;
895    const agent = output && isObject(output.agent) ? output.agent : null;
896    const name = typeof app?.name === 'string' && app.name.trim() ? app.name.trim() : 'Claude Code';
897    const machine = typeof agent?.machine === 'string' ? agent.machine.trim() : '';
898    return machine ? `${name} on ${machine}` : name;
899}
900export function setupPrompt(connection = 'Claude Code') {
901    return `Pending You: ${connection} is connected, but its setup isn’t finished. Three calls, nothing to install or approve: 1. whoami with your name. If it says app.setUp is true, another session did this: stop. 2. report_setup with source claude-code, your name, skillSaved true, hears instant, and skillVersion set to whoami’s skill.latest. Its answer has a testAreaId. 3. post_request a short test question in that testAreaId, tell your person it’s on its way, and end your turn: you’re woken when they answer, so don’t ask them to type anything.`;
902}
903export const PRESENCE_EVERY_MS = 5 * 60_000;
904export const PRESENCE_RUN_MS = 15_000;
905const PRODUCTION = 'https://www.pendingyou.com';
906export function cliConfigOf(root, name = CLI_COPY) {
907    if (name !== CLI_COPY)
908        return null;
909    return (/^(.+)[\\/]cli[\\/][^\\/]+[\\/]node_modules[\\/]pendingyou[\\/]mod[\\/]?$/.exec(root)?.[1] ??
910        /^(.+)[\\/]mod[\\/]?$/.exec(root)?.[1] ??
911        null);
912}
913const SESSION_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
914export function loadedPath(config, sessionId) {
915    return SESSION_FILE.test(sessionId) ? `${config}/wake/sessions/${sessionId}.json` : null;
916}
917export const loadedNote = (at) => `${JSON.stringify({ at: Math.floor(at) })}\n`;
918export function originOf(manifest) {
919    let parsed = manifest;
920    if (typeof manifest === 'string')
921        try {
922            parsed = JSON.parse(manifest);
923        }
924        catch {
925            return null;
926        }
927    const origin = typeof parsed === 'object' && parsed !== null ? parsed.origin : null;
928    return typeof origin === 'string' && /^https?:\/\/[^\s/]+$/.test(origin) ? origin : null;
929}
930export function presenceArgv(config, origin, session) {
931    return [
932        `${config}/bin/pendingyou-hook`,
933        'presence',
934        '--app',
935        'claude-code',
936        '--state',
937        'live',
938        '--session',
939        session.id,
940        ...(session.cwd ? ['--cwd', session.cwd] : []),
941        ...(session.name ? ['--name', session.name] : []),
942        '--at',
943        String(Math.floor(session.at)),
944        ...(origin === PRODUCTION ? [] : ['--origin', origin]),
945    ];
946}
947export const HERDR_EVERY_MS = 5 * 60_000;
948export const HERDR_RUN_MS = 15_000;
949export function inHerdr(on, bin, pane) {
950    return (on === '1' &&
951        typeof bin === 'string' &&
952        bin.startsWith('/') &&
953        typeof pane === 'string' &&
954        /^[A-Za-z0-9]{1,16}:[A-Za-z0-9]{1,16}$/.test(pane));
955}
956export function herdrCards(book) {
957    return Object.values(book.cards)
958        .filter(waitsOnYou)
959        .sort((a, b) => (a.requestId < b.requestId ? -1 : a.requestId > b.requestId ? 1 : 0))
960        .map((card) => ({
961        requestId: card.requestId,
962        ...(card.title ? { title: card.title } : {}),
963        ...pressingOfCard(card),
964        at: card.learnedAt,
965    }));
966}
967export const herdrPayload = (book) => JSON.stringify({ name: book.name ?? null, cards: herdrCards(book) });
968export function herdrArgv(config, session) {
969    return [
970        `${config}/bin/pendingyou-hook`,
971        'herdr',
972        'report',
973        '--app',
974        'claude-code',
975        '--session',
976        session.id,
977        '--at',
978        String(Math.floor(session.at)),
979    ];
980}
981