pendingyou 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - The next-message hook's reminder now names this folder's open cards still waiting on you, so a question you answer
6
+ in chat gets its card cancelled: `Pending You: anything you need from your person also goes on a card. Your open
7
+ cards here: "Which DNS host?" (req_…); … +2 more. If this message answers or settles one, cancel_request it with
8
+ answeredHere (or update_request if it changed).` At most 3 cards, newest first, titles cut to 50 characters; the
9
+ plain reminder when none are open. One small request per message while signed in (answers too while a hold is
10
+ outstanding), given up after 1.5 seconds; on any error, or against a server that doesn't list open cards yet, the
11
+ line is the plain reminder.
12
+ - The Stop check no longer asks Claude Code to go on when its message says a card is coming ("you'll get a card to
13
+ publish it once it's merged", "I'll post a card", "I'll send you a card").
14
+
15
+ ## 0.3.0
16
+
17
+ - New Stop hook, `pendingyou stopcheck`: when Claude Code ends a turn with a question for you, a step only you can do
18
+ or a "Your part:" list, and posted nothing to Pending You in that turn, it's asked once to post them as cards (or
19
+ say they don't need one). Pattern matching only, on the last turn, at most 4 MB of the transcript; quiet when not
20
+ signed in, never twice in a row (`stop_hook_active`), and silent on any error.
21
+ - The next-message hook adds one line while you're signed in: “Pending You: anything you need from your person also
22
+ goes on a card.”
23
+ - `init` adds the Stop hook (run it again on 0.2.x to get it), `uninstall` removes it, and `status` lists it.
24
+
3
25
  ## 0.2.1
4
26
 
5
27
  - Fixed: after `init --origin <url>` (any origin but the default), every Claude Code message was blocked with
package/README.md CHANGED
@@ -12,15 +12,37 @@ Run it once on each computer. It:
12
12
  - adds the Pending You MCP server to Claude Code for every project (unless it's already there),
13
13
  - saves the Pending You skill to `~/.claude/skills/pendingyou/SKILL.md`,
14
14
  - signs this computer in (your browser opens once; press Allow),
15
- - adds two hooks to `~/.claude/settings.json`: a new session picks up answers that arrived while nothing was running,
16
- and your next message brings a waiting answer with it,
15
+ - adds three hooks to `~/.claude/settings.json`: a new session picks up answers that arrived while nothing was
16
+ running, your next message brings a waiting answer with it, and a check when Claude Code finishes a turn (below),
17
17
  - lets Claude Code start `npx pendingyou hold` and use Pending You's tools without a permission prompt, so a question
18
18
  it asks while you're away doesn't wait on one.
19
19
 
20
20
  Your other settings are kept as they are. `npx pendingyou uninstall` removes exactly what `init` added.
21
21
 
22
22
  The hooks never get in your way: if anything goes wrong (no network, not signed in, a bad option), they print nothing
23
- and let your message through. Running `init` again updates them in place.
23
+ and let your message through. Running `init` again updates them in place, and adds any a newer version brings.
24
+
25
+ ## Nothing left only in chat
26
+
27
+ Deep into a long conversation, Claude Code tends to end a turn with a question for you, a step only you can do, or a
28
+ "Your part:" list, and not put it in Pending You. Two small things catch that while you're signed in:
29
+
30
+ - Each message you send carries one line for Claude Code (about 18 tokens): *Pending You: anything you need from your
31
+ person also goes on a card.* While cards Claude Code posted from this folder are still waiting on you, the same line
32
+ names them (at most 3, newest first, about 20 tokens each) and asks it to `cancel_request` one with `answeredHere`
33
+ when your message answers it, so a question you answer in chat doesn't stay in your queue. That costs one small
34
+ request per message, given up after 1.5 seconds.
35
+ - When Claude Code finishes a turn, `pendingyou stopcheck` looks at its last message. If it has something for you and
36
+ nothing was posted, updated or replied to in Pending You that turn (and the message doesn't say it's on a card, or
37
+ that one is coming),
38
+ Claude Code is asked to go on once (about 31 tokens): post them as cards, or say they don't need one. It never asks
39
+ twice in a row.
40
+
41
+ The check is pattern matching on your computer: no model, no network. It reads only the last turn from the end of the
42
+ transcript (at most 4 MB) and skips code blocks and quotes. It counts as for you: a question to you (a sentence ending
43
+ in "?" with "you" or "your"); "you'll need to", "your step", "can you", "please run", "in your terminal", "only you
44
+ can", "waiting on you" and the like; or a list under a heading like "Your part", "Your steps", "For you", "Waiting on
45
+ you" or "Left for you".
24
46
 
25
47
  **On 0.2.0 with another origin?** Its hooks blocked every message (`There's no "--origin" command`). Run
26
48
  `npx pendingyou@latest init --origin <url>` again to repair them; see [CHANGELOG.md](CHANGELOG.md).
@@ -75,6 +97,7 @@ more, then skipped. `--once` stops after the first.
75
97
  | `login` / `logout` | Sign this computer in or out (`--device`, `--force`, `--all`) |
76
98
  | `watch -- <command>` | Run a command each time an answer is ready (`--once`) |
77
99
  | `pickup` / `handoff` | The session-start and next-message hooks |
100
+ | `stopcheck` | The Stop hook: items for you left only in chat |
78
101
  | `uninstall` | Remove what `init` added, and sign out |
79
102
 
80
103
  Every command takes `--origin` (default `https://www.pendingyou.com`, or `$PENDINGYOU_ORIGIN`). Options can come
package/dist/args.js CHANGED
@@ -45,6 +45,7 @@ const COMMANDS = new Set([
45
45
  'hold',
46
46
  'pickup',
47
47
  'handoff',
48
+ 'stopcheck',
48
49
  'init',
49
50
  'uninstall',
50
51
  'watch',
@@ -59,6 +60,7 @@ const FLAGS = {
59
60
  hold: { origin: true, timeout: true },
60
61
  pickup: { origin: true },
61
62
  handoff: { origin: true },
63
+ stopcheck: { origin: true },
62
64
  init: { origin: true, 'no-login': false, 'no-browser': false, device: false },
63
65
  uninstall: { origin: true },
64
66
  watch: { origin: true, once: false },
@@ -81,7 +83,7 @@ export function commandOf(argv) {
81
83
  return splitCommand(argv)[1];
82
84
  }
83
85
  /** The commands Claude Code's hooks run. Whatever goes wrong, they exit 0 and never block the person. */
84
- export const HOOK_COMMANDS = new Set(['pickup', 'handoff']);
86
+ export const HOOK_COMMANDS = new Set(['pickup', 'handoff', 'stopcheck']);
85
87
  export function parseArgs(argv, env = {}) {
86
88
  const [leading, first, after] = splitCommand(argv);
87
89
  const helps = (arg) => arg === '-h' || arg === '--help';
@@ -169,6 +171,9 @@ export function parseArgs(argv, env = {}) {
169
171
  case 'handoff':
170
172
  none();
171
173
  return { name: 'handoff', origin };
174
+ case 'stopcheck':
175
+ none();
176
+ return { name: 'stopcheck', origin };
172
177
  case 'uninstall':
173
178
  none();
174
179
  return { name: 'uninstall', origin };
@@ -204,7 +209,8 @@ export function parseArgs(argv, env = {}) {
204
209
  export const USAGE = `pendingyou: Pending You for Claude Code
205
210
 
206
211
  npx pendingyou init Set up Claude Code on this computer: the MCP server, the skill,
207
- this command's sign-in, and two hooks that hand answers over
212
+ this command's sign-in, and three hooks (answers, and a check
213
+ that what Claude Code leaves you in chat is also in Pending You)
208
214
  npx pendingyou hold <req_…> Wait in the background until the answer to a request is ready,
209
215
  print it, and exit (which wakes Claude Code)
210
216
  npx pendingyou status What's set up, and whether Claude Code hears answers right away
@@ -215,6 +221,7 @@ export const USAGE = `pendingyou: Pending You for Claude Code
215
221
  npx pendingyou uninstall Remove exactly what init added
216
222
  npx pendingyou pickup Answers waiting for this folder (the session-start hook)
217
223
  npx pendingyou handoff The same, only while a hold is outstanding (the next-message hook)
224
+ npx pendingyou stopcheck Questions or steps for you left only in chat (the Stop hook)
218
225
 
219
226
  Options: --origin <url> (default ${DEFAULT_ORIGIN}), --timeout 4h (hold), --no-browser and --device (login,
220
227
  init), --no-login (init), --all (logout), --force (login), --once (watch).
package/dist/claude.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Claude Code's side of `pendingyou init` and `uninstall`: the Pending You MCP server (user scope), the stub skill, the
2
- // two hooks (session-start pickup, next-message hand-off) and the permissions the background wait needs, in
2
+ // three hooks (session-start pickup, next-message hand-off, the Stop check) and the permissions the background wait needs, in
3
3
  // ~/.claude/settings.json. Settings are merged, never replaced: a file that isn't JSON is left alone, entries that
4
4
  // aren't ours are never touched, and running init again changes nothing it doesn't need to. What init added is written
5
5
  // down in ~/.config/pendingyou/claude-code.json, so uninstall removes exactly that.
@@ -12,7 +12,11 @@ import { claudeDir, configDir, readJson, readText, writeWhole } from "./files.js
12
12
  import { VERSION } from "./version.js";
13
13
  export const MCP_NAME = 'pendingyou';
14
14
  /** The hooks, by Claude Code event, and the command each runs. */
15
- export const HOOKS = { SessionStart: 'pickup', UserPromptSubmit: 'handoff' };
15
+ export const HOOKS = {
16
+ SessionStart: 'pickup',
17
+ UserPromptSubmit: 'handoff',
18
+ Stop: 'stopcheck',
19
+ };
16
20
  /** Seconds Claude Code gives each hook; they time-box themselves well inside it. */
17
21
  const HOOK_TIMEOUT = 10;
18
22
  /**
@@ -50,7 +54,7 @@ export function hookCommand(io, origin, sub) {
50
54
  const flag = origin === DEFAULT_ORIGIN ? '' : ` --origin ${quote(origin)}`;
51
55
  return `${selfCommand(io)} ${sub}${flag} || true`;
52
56
  }
53
- /** Whether a hook command is one of ours: it runs pendingyou's `pickup` or `handoff`. */
57
+ /** Whether a hook command is one of ours: it runs pendingyou's `pickup`, `handoff` or `stopcheck`. */
54
58
  export function isOurHook(command, sub) {
55
59
  if (typeof command !== 'string' || !command.includes('pendingyou'))
56
60
  return false;
@@ -242,17 +246,17 @@ export async function installClaude(io, origin) {
242
246
  steps.push(mcp.step);
243
247
  const skill = await saveSkill(io, origin, before?.skill ?? null);
244
248
  steps.push(skill.step);
245
- const commands = {
246
- SessionStart: hookCommand(io, origin, HOOKS.SessionStart),
247
- UserPromptSubmit: hookCommand(io, origin, HOOKS.UserPromptSubmit),
248
- };
249
+ const commands = Object.fromEntries(Object.keys(HOOKS).map((event) => [
250
+ event,
251
+ hookCommand(io, origin, HOOKS[event]),
252
+ ]));
249
253
  const merged = mergeSettings(await readSettings(io), commands);
250
254
  if (merged.changed)
251
255
  await writeSettings(io, merged.settings);
252
256
  steps.push({
253
257
  ok: true,
254
258
  text: merged.changed
255
- ? `Installed or updated the session-start pickup and next-message hand-off hooks in ${settingsPath(io)}.`
259
+ ? `Installed or updated the session-start pickup, next-message hand-off and Stop check hooks in ${settingsPath(io)}.`
256
260
  : 'The hooks were already installed.',
257
261
  });
258
262
  const manifest = {
@@ -309,13 +313,18 @@ export async function claudeState(io) {
309
313
  const claude = version.code === 0 ? version.stdout.trim().split(/\s+/)[0] || 'installed' : null;
310
314
  const mcp = claude ? (await io.run('claude', ['mcp', 'get', MCP_NAME], 20_000)).code === 0 : false;
311
315
  const skill = (await readText(skillPath(io))) !== null;
312
- let hooks = false;
316
+ let installed = (_event) => false;
313
317
  try {
314
- const settings = await readSettings(io);
315
- const all = objectAt(settings, 'hooks') ?? {};
316
- hooks = Object.keys(HOOKS).every((event) => Array.isArray(all[event]) &&
317
- all[event].some((group) => (group.hooks ?? []).some((hook) => isOurHook(hook.command, HOOKS[event]))));
318
+ const all = objectAt(await readSettings(io), 'hooks') ?? {};
319
+ installed = (event) => Array.isArray(all[event]) &&
320
+ all[event].some((group) => (group.hooks ?? []).some((hook) => isOurHook(hook.command, HOOKS[event])));
318
321
  }
319
322
  catch { }
320
- return { claude, mcp, skill, hooks };
323
+ return {
324
+ claude,
325
+ mcp,
326
+ skill,
327
+ hooks: installed('SessionStart') && installed('UserPromptSubmit'),
328
+ stopcheck: installed('Stop'),
329
+ };
321
330
  }
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { realIo } from "./io.js";
4
4
  import { isHook, main } from "./main.js";
5
5
  const argv = process.argv.slice(2);
6
- // A hook (pickup, handoff) exits 0 even here: it must never block the person's message.
6
+ // A hook (pickup, handoff, stopcheck) exits 0 even here: it must never block the person's message.
7
7
  const failed = isHook(argv) ? 0 : 1;
8
8
  try {
9
9
  main(argv, realIo()).then((code) => process.exit(code), () => {
package/dist/format.js CHANGED
@@ -5,7 +5,7 @@ const MAX_ANSWER = 600;
5
5
  const MAX_MESSAGE = 400;
6
6
  const MAX_TITLE = 140;
7
7
  /** Cuts text to `max` characters on one line, and says so. */
8
- function clip(text, max) {
8
+ export function clip(text, max) {
9
9
  const flat = text.replace(/\s+/g, ' ').trim();
10
10
  const chars = [...flat];
11
11
  if (chars.length <= max)
package/dist/main.js CHANGED
@@ -8,6 +8,7 @@ import { PlainError } from "./errors.js";
8
8
  import { hold } from "./hold.js";
9
9
  import { OAuthError, revoke, signIn, signInWithDevice } from "./oauth.js";
10
10
  import { pickup } from "./pickup.js";
11
+ import { stopcheck } from "./stopcheck.js";
11
12
  import { VERSION } from "./version.js";
12
13
  import { watch } from "./watch.js";
13
14
  /** Whether this computer's sign-in works, and how many Claude Code connections it hears for. */
@@ -81,7 +82,7 @@ async function status(io, origin) {
81
82
  ? 'ended; run npx pendingyou login'
82
83
  : signIn.state === 'none'
83
84
  ? 'not signed in; run npx pendingyou login'
84
- : 'Pending You couldn’t be reached'}`, ` ${mark(claude.claude !== null)} Claude Code: ${claude.claude ?? 'not found on PATH'}`, ` ${mark(claude.mcp)} MCP server: ${claude.mcp ? 'pendingyou' : 'not added; run npx pendingyou init'}`, ` ${mark(claude.skill)} Skill: ${claude.skill ? 'saved' : 'not saved; run npx pendingyou init'}`, ` ${mark(claude.hooks)} Hooks: ${claude.hooks ? 'session-start pickup and next-message hand-off' : 'not installed; run npx pendingyou init'}`);
85
+ : 'Pending You couldn’t be reached'}`, ` ${mark(claude.claude !== null)} Claude Code: ${claude.claude ?? 'not found on PATH'}`, ` ${mark(claude.mcp)} MCP server: ${claude.mcp ? 'pendingyou' : 'not added; run npx pendingyou init'}`, ` ${mark(claude.skill)} Skill: ${claude.skill ? 'saved' : 'not saved; run npx pendingyou init'}`, ` ${mark(claude.hooks)} Hooks: ${claude.hooks ? 'session-start pickup and next-message hand-off' : 'not installed; run npx pendingyou init'}`, ` ${mark(claude.stopcheck)} Stop check: ${claude.stopcheck ? 'asks Claude Code to post what it leaves you in chat' : 'not installed; run npx pendingyou init'}`);
85
86
  const ready = signIn.state === 'ok' && claude.hooks;
86
87
  lines.push(ready
87
88
  ? 'Ready: Claude Code hears answers right away (report_setup hears "instant").'
@@ -135,6 +136,8 @@ async function run(io, command) {
135
136
  return pickup(io, { origin: command.origin, mode: 'pickup' });
136
137
  case 'handoff':
137
138
  return pickup(io, { origin: command.origin, mode: 'handoff' });
139
+ case 'stopcheck':
140
+ return stopcheck(io, { origin: command.origin });
138
141
  case 'init':
139
142
  return init(io, command);
140
143
  case 'uninstall':
@@ -144,7 +147,7 @@ async function run(io, command) {
144
147
  }
145
148
  }
146
149
  /**
147
- * Whether these arguments run a Claude Code hook (pickup or handoff). A hook must never get in the way of the person:
150
+ * Whether these arguments run a Claude Code hook (pickup, handoff or stopcheck). A hook must never get in the way of the person:
148
151
  * Claude Code blocks their message when a UserPromptSubmit hook exits 2 and flags any other failure, so a hook exits 0
149
152
  * whatever goes wrong, with at most a short note on stderr (which Claude Code doesn't add to the conversation).
150
153
  */
package/dist/pickup.js CHANGED
@@ -3,15 +3,47 @@
3
3
  // - `pendingyou pickup` (SessionStart): a new or resumed session picks up answers that arrived while nothing was
4
4
  // running, for questions asked from this folder.
5
5
  // - `pendingyou handoff` (UserPromptSubmit): your next message brings a waiting answer with it ("You answered in
6
- // Pending You: …"). It only calls Pending You while a hold from this computer is outstanding, so an ordinary message
7
- // costs no network call.
6
+ // Pending You: …"). While signed in, it also adds one short line (REMINDER) to every message, so an assistant
7
+ // deep in a long conversation still puts what it needs from the person on a card, and that line names this folder's
8
+ // cards still waiting on the person (openLine), so one they answer in chat gets cancelled with answeredHere. That's
9
+ // one small request per message (the open cards, and answers too while a hold from this computer is outstanding),
10
+ // time-boxed short; on any error, or from a server too old to list open cards, the line is the plain reminder.
8
11
  //
9
12
  // Whatever they print, Claude Code adds to the conversation. A hook must never get in the way: each is time-boxed,
10
13
  // prints nothing when there's nothing new, never repeats an answer it handed over, and always exits 0.
11
14
  import { getJson, SignInNeeded } from "./api.js";
12
- import { describe, isClosed } from "./format.js";
15
+ import { readCredential } from "./credentials.js";
16
+ import { clip, describe, isClosed } from "./format.js";
13
17
  import { markHanded, momentOf, waitingOn, wasHanded } from "./state.js";
14
- const TIME_BOX_MS = { pickup: 5000, handoff: 2500 };
18
+ const TIME_BOX_MS = { pickup: 5000, handoff: 2500, open: 1500 };
19
+ /** What every message carries while signed in (about 18 tokens). */
20
+ export const REMINDER = 'Pending You: anything you need from your person also goes on a card.';
21
+ /** The most open cards the line names, and how much of each title. */
22
+ export const OPEN_SHOWN = 3;
23
+ export const OPEN_TITLE = 50;
24
+ /**
25
+ * The reminder, naming this folder's open cards still waiting on the person when there are any (about 45 tokens plus
26
+ * 20 a card): `… Your open cards here: "Which DNS host?" (req_…); … +2 more. If this message answers …`.
27
+ */
28
+ export function openLine(open) {
29
+ if (typeof open !== 'object' || open === null)
30
+ return REMINDER;
31
+ const { requests, total } = open;
32
+ if (!Array.isArray(requests))
33
+ return REMINDER;
34
+ const cards = requests
35
+ .filter((card) => typeof card?.requestId === 'string' &&
36
+ /^req_[A-Za-z0-9-]{1,40}$/.test(card.requestId) &&
37
+ typeof card.title === 'string')
38
+ .slice(0, OPEN_SHOWN);
39
+ if (cards.length === 0)
40
+ return REMINDER;
41
+ const more = typeof total === 'number' && total > cards.length ? total - cards.length : 0;
42
+ const named = cards
43
+ .map((card) => `"${clip(card.title.replaceAll('"', "'"), OPEN_TITLE).text}" (${card.requestId})`)
44
+ .join('; ');
45
+ return `${REMINDER} Your open cards here: ${named}${more ? ` +${more} more` : ''}. If this message answers or settles one, cancel_request it with answeredHere (or update_request if it changed).`;
46
+ }
15
47
  /** The folder Claude Code says the session is in (the hook's stdin), or where this runs. */
16
48
  async function sessionFolder(io) {
17
49
  const text = await io.readStdin(500).catch(() => '');
@@ -33,16 +65,29 @@ export function folderForms(cwd, home) {
33
65
  }
34
66
  export async function pickup(io, options) {
35
67
  const { origin, mode } = options;
68
+ let remind = false;
69
+ let line = REMINDER;
36
70
  try {
37
71
  const cwd = await sessionFolder(io);
38
- if (mode === 'handoff' && (await waitingOn(io, origin)).length === 0)
39
- return 0;
72
+ // The hand-off hears answers only while a hold from this computer is outstanding; it always asks for open cards.
73
+ let answers = true;
74
+ if (mode === 'handoff') {
75
+ remind = (await readCredential(io, origin)) !== null;
76
+ if (!remind)
77
+ return 0;
78
+ answers = (await waitingOn(io, origin)).length > 0;
79
+ }
40
80
  const query = new URLSearchParams([
41
81
  ...folderForms(cwd, io.home).map((form) => ['cwd', form]),
42
- ['limit', '5'],
82
+ ['limit', answers ? '5' : '0'],
83
+ ...(mode === 'handoff' ? [['open', String(OPEN_SHOWN)]] : []),
43
84
  ]);
44
- const { status, body } = await getJson(io, origin, `/mcp/cli/answers?${query}`, TIME_BOX_MS[mode], io.signal);
45
- if (status !== 200 || !Array.isArray(body.requests))
85
+ const { status, body } = await getJson(io, origin, `/mcp/cli/answers?${query}`, answers ? TIME_BOX_MS[mode] : TIME_BOX_MS.open, io.signal);
86
+ if (status !== 200)
87
+ return 0;
88
+ if (mode === 'handoff')
89
+ line = openLine(body.open);
90
+ if (!answers || !Array.isArray(body.requests))
46
91
  return 0;
47
92
  const fresh = [];
48
93
  for (const heard of body.requests)
@@ -69,6 +114,12 @@ export async function pickup(io, options) {
69
114
  catch (error) {
70
115
  if (mode === 'pickup' && error instanceof SignInNeeded && error.ended)
71
116
  io.out('Pending You: this computer’s pendingyou sign-in has ended, so answers can’t wake Claude Code. Ask your person to run `npx pendingyou login`.\n');
117
+ if (error instanceof SignInNeeded)
118
+ remind = false;
72
119
  return 0;
73
120
  }
121
+ finally {
122
+ if (remind)
123
+ io.out(`${line}\n`);
124
+ }
74
125
  }
@@ -0,0 +1,181 @@
1
+ // `pendingyou stopcheck`, the Stop hook `init` installs: when Claude Code is about to end its turn with something for
2
+ // the person in the chat (a question to them, a step only they can do, a "Your part:" list) and it posted nothing to
3
+ // Pending You in that turn, it asks Claude Code to go on and post it (`{"decision":"block","reason":…}`), once.
4
+ //
5
+ // Pattern matching only, no model, no network: it reads the hook's JSON, the final message, and the tail of the
6
+ // transcript back to the person's last message, never more than READ_CAP bytes. It never loops (stop_hook_active),
7
+ // stays quiet for anyone not signed in to this origin, and exits 0 silently on any error.
8
+ import { open } from 'node:fs/promises';
9
+ import { readCredential } from "./credentials.js";
10
+ /** The most of the transcript it reads, from the end. A turn longer than this is let through. */
11
+ export const READ_CAP = 4 * 1024 * 1024;
12
+ const CHUNK = 64 * 1024;
13
+ /** What Claude Code reads when it's asked to go on: one short line (about 30 tokens). */
14
+ export const STOP_REASON = 'Items for your person are in chat but not in Pending You: post them as cards (ask in both places), or say they don’t need one.';
15
+ /** Tools that put something in front of the person: Pending You's, under any MCP server name. */
16
+ const POSTING_TOOL = /^mcp__.+__(post_request|update_request|reply_in_thread)$/;
17
+ /**
18
+ * Text that says the items are already in Pending You, or will be: "you'll get a card to publish it once it's merged"
19
+ * announces a card to come, not a step left in chat.
20
+ */
21
+ const SAYS_POSTED = /\b(posted|put|added|raised|filed)\b[^.\n]{0,60}\b(cards?|pending ?you)\b|\bon (a|the|its|their|your|that|this) cards?\b|\b(in|to|through|via|on) pending ?you\b|\bpending ?you cards?\b|\b(i|we|you)(?:(?:'|’)ll| will)\s+(?:\w+\s+)?(post|send|put|add|raise|file|get|see|find)\b[^.\n]{0,40}\bcards?\b/i;
22
+ /** Steps only the person can take, said to them. */
23
+ const STEPS_FOR_THEM = /\b(you(?:'|’)ll need to|you will need to|you(?:'|’)ll have to|you will have to|your (?:next )?steps?\b|can you|could you|would you mind|please (?:run|confirm|approve|check|add|set|sign|create|open|paste|reply|send|choose|pick|decide|let me know)|in your terminal|only you can|waiting on you|waiting for you|needs? you to|over to you|parked for you|when you(?:'|’)re ready|up to you|your call\b|is yours\b|say the word|let me know (?:which|whether)|tell me (?:which|whether)|needs? your (?:ok|okay|approval|decision|sign-?off|go-ahead))/i;
24
+ /** A heading over a list of things for the person. */
25
+ const FOR_THEM_HEADING = /\b(your part|your steps?|your to-?dos?|your turn|your call|for you|waiting on you|left for you|parked for you|needs you|over to you|what you need to do|you(?:'|’)ll need)\b/i;
26
+ const LIST_ITEM = /^\s*(?:\d+[.)]|[-*•]|\[ \])\s+\S/;
27
+ const YOU = /\byou(?:r|rs|(?:'|’)(?:ll|d|re|ve))?\b/i;
28
+ /** The text without what isn't said to the person: code (fenced and inline), block quotes and quoted strings. */
29
+ export function plainText(text) {
30
+ const kept = [];
31
+ let fence = null;
32
+ for (const line of text.split('\n')) {
33
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
34
+ if (fence) {
35
+ if (marker?.startsWith(fence))
36
+ fence = null;
37
+ continue;
38
+ }
39
+ if (marker) {
40
+ fence = marker;
41
+ continue;
42
+ }
43
+ if (/^\s*>/.test(line))
44
+ continue;
45
+ kept.push(line.replace(/`[^`]*`/g, '').replace(/“[^”]*”|"[^"]*"/g, ''));
46
+ }
47
+ return kept.join('\n');
48
+ }
49
+ /** A heading's words (`## Your part`, `**Your part:**`, `Your part:`), or null when the line isn't one. */
50
+ function headingOf(line) {
51
+ const bare = line.replace(/[*_#]/g, '').trim();
52
+ if (!bare || bare.length > 80)
53
+ return null;
54
+ return /^\s*#/.test(line) || bare.endsWith(':') || /^\s*\*\*.+\*\*\s*$/.test(line) ? bare : null;
55
+ }
56
+ /**
57
+ * What in the final text is for the person, or null: `list` (a list under a heading like "Your part:"), `steps`
58
+ * (something only they can do) or `question` (a question to them).
59
+ */
60
+ export function itemsForPerson(text) {
61
+ const plain = plainText(text);
62
+ const lines = plain.split('\n');
63
+ for (let index = 0; index < lines.length; index++) {
64
+ const heading = headingOf(lines[index]);
65
+ if (!heading || !FOR_THEM_HEADING.test(heading))
66
+ continue;
67
+ const next = lines.slice(index + 1, index + 4).find((candidate) => candidate.trim());
68
+ if (next && LIST_ITEM.test(next))
69
+ return 'list';
70
+ }
71
+ if (STEPS_FOR_THEM.test(plain))
72
+ return 'steps';
73
+ for (const sentence of plain.split(/(?<=[.!?])\s+|\n/))
74
+ if (sentence.trim().endsWith('?') && YOU.test(sentence))
75
+ return 'question';
76
+ return null;
77
+ }
78
+ /** Whether the text says the items are already in Pending You. */
79
+ export const saysPosted = (text) => SAYS_POSTED.test(plainText(text));
80
+ /** A message from the person (not a tool's result): where a turn starts. */
81
+ function startsTurn(entry) {
82
+ if (entry.type !== 'user' || entry.isMeta || entry.message?.role !== 'user')
83
+ return false;
84
+ const content = entry.message.content;
85
+ if (typeof content === 'string')
86
+ return true;
87
+ return Array.isArray(content) && content.some((block) => block?.type === 'text');
88
+ }
89
+ /**
90
+ * The last turn of a Claude Code transcript (JSONL): read backwards from the end in chunks, line by line, until the
91
+ * person's last message, never more than `cap` bytes.
92
+ */
93
+ export async function lastTurn(path, cap = READ_CAP) {
94
+ const file = await open(path, 'r');
95
+ try {
96
+ const size = (await file.stat()).size;
97
+ let position = size;
98
+ let bytesRead = 0;
99
+ let carry = Buffer.alloc(0);
100
+ const texts = [];
101
+ let finalDone = false;
102
+ let posted = false;
103
+ const take = (raw) => {
104
+ if (!raw.trim())
105
+ return false;
106
+ let entry;
107
+ try {
108
+ entry = JSON.parse(raw);
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ if (entry.isSidechain)
114
+ return false;
115
+ if (startsTurn(entry))
116
+ return true;
117
+ if (entry.type !== 'assistant' || !Array.isArray(entry.message?.content))
118
+ return false;
119
+ const blocks = entry.message.content;
120
+ for (const block of [...blocks].reverse()) {
121
+ if (block?.type === 'tool_use') {
122
+ finalDone = true;
123
+ const name = typeof block.name === 'string' ? block.name : '';
124
+ const command = typeof block.input?.command === 'string' ? block.input.command : '';
125
+ if (POSTING_TOOL.test(name) || /\bpendingyou\b.*\bhold\s+req_/.test(command))
126
+ posted = true;
127
+ }
128
+ else if (block?.type === 'text' && !finalDone && typeof block.text === 'string')
129
+ texts.unshift(block.text);
130
+ }
131
+ return false;
132
+ };
133
+ while (position > 0 && bytesRead < cap) {
134
+ const length = Math.min(CHUNK, position, cap - bytesRead);
135
+ position -= length;
136
+ const chunk = Buffer.alloc(length);
137
+ await file.read(chunk, 0, length, position);
138
+ bytesRead += length;
139
+ let buffer = Buffer.concat([chunk, carry]);
140
+ let newline = buffer.lastIndexOf(10);
141
+ while (newline !== -1) {
142
+ if (take(buffer.subarray(newline + 1).toString('utf8')))
143
+ return { text: texts.join('\n'), posted, complete: true, bytesRead };
144
+ buffer = buffer.subarray(0, newline);
145
+ newline = buffer.lastIndexOf(10);
146
+ }
147
+ carry = buffer;
148
+ }
149
+ if (position === 0 && take(carry.toString('utf8')))
150
+ return { text: texts.join('\n'), posted, complete: true, bytesRead };
151
+ return { text: texts.join('\n'), posted, complete: position === 0, bytesRead };
152
+ }
153
+ finally {
154
+ await file.close();
155
+ }
156
+ }
157
+ export async function stopcheck(io, options) {
158
+ try {
159
+ const input = JSON.parse(await io.readStdin(1000));
160
+ if (typeof input !== 'object' || input === null || input.stop_hook_active === true)
161
+ return 0;
162
+ if (typeof input.transcript_path !== 'string' || !input.transcript_path)
163
+ return 0;
164
+ if (!(await readCredential(io, options.origin)))
165
+ return 0;
166
+ const turn = await lastTurn(input.transcript_path);
167
+ if (!turn.complete)
168
+ return 0;
169
+ // The transcript can lag the final message; Claude Code hands it over itself.
170
+ const text = typeof input.last_assistant_message === 'string' && input.last_assistant_message.trim()
171
+ ? input.last_assistant_message
172
+ : turn.text;
173
+ if (turn.posted || !text || saysPosted(text) || !itemsForPerson(text))
174
+ return 0;
175
+ io.out(`${JSON.stringify({ decision: 'block', reason: STOP_REASON })}\n`);
176
+ return 0;
177
+ }
178
+ catch {
179
+ return 0;
180
+ }
181
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The command line's version, as published (package.json). A test keeps them the same.
2
- export const VERSION = '0.2.1';
2
+ export const VERSION = '0.4.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pendingyou",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Pending You for Claude Code: hear your answers from Pending You in the background, and set Claude Code up in one command.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://www.pendingyou.com",