slashvibe-mcp 0.9.14 → 0.9.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,6 +60,11 @@ was marked read, until you chose.
60
60
  session, picks the person it is for, writes it, and shows you the exact message. Send,
61
61
  Edit or Cancel. Or just say it: `message @sam: ship it`.
62
62
 
63
+ **Someone who is not here yet.** If the person you are writing to has no /vibe account, the
64
+ preview says so, and Keep holds your exact message for the GitHub account of that name for
65
+ 30 days. You get a join link and your setup line to pass on; when they sign in to /vibe with
66
+ that account, it is your first message to them. Nothing reaches them before then.
67
+
63
68
  ## Who's here
64
69
 
65
70
  When you open a session, one line tells you which of the people you know are around:
package/draft-cli.js CHANGED
@@ -46,7 +46,10 @@ async function main() {
46
46
  // do that under the lock first, so an abandoned draft is listed as
47
47
  // 'unknown' (retry or discard) instead of hidden forever (codex r2).
48
48
  moves.transact((drafts) => { for (const d of drafts) moves.reconcileAbandoned(d); return drafts; });
49
- const mine = moves.loadDrafts().filter((d) => String(d.from || '').toLowerCase() === me && (d.status === 'previewed' || d.status === 'unknown'));
49
+ // A held draft (for someone not on /vibe yet) is decided only where its
50
+ // preview says so: a companion that renders it as an ordinary Send would
51
+ // describe a different act than the one it performs.
52
+ const mine = moves.loadDrafts().filter((d) => String(d.from || '').toLowerCase() === me && (d.status === 'previewed' || d.status === 'unknown') && !d.held);
50
53
  // Exactly what the person would see in the terminal preview — and the rev
51
54
  // that binds a Send to those bytes. Nothing private: context stays out.
52
55
  const drafts = mine.map((d) => ({
package/invite.js CHANGED
@@ -29,6 +29,18 @@ function fromArg(argv = process.argv) {
29
29
  return null;
30
30
  }
31
31
 
32
+ /**
33
+ * The platform folds '-' to '_' when it first gives a GitHub login a handle
34
+ * (api/lib/handles.js), and its identity lookup answers with that spelling:
35
+ * asking for "a-b" finds "a_b". Only that one difference is forgiven when
36
+ * confirming the answer; any other mismatch is still "could not confirm".
37
+ */
38
+ const sameAccount = (asked, answered) => asked.replace(/-/g, '_') === answered.replace(/-/g, '_');
39
+
40
+ /**
41
+ * { found: true, kind, handle } where handle is the platform's own spelling;
42
+ * { found: false } on a definite 404; { found: null } when it could not tell.
43
+ */
32
44
  async function lookup(h, { apiUrl, fetchImpl = fetch } = {}) {
33
45
  const base = String(apiUrl || process.env.VIBE_API_URL || 'https://www.slashvibe.dev').replace(/\/+$/, '');
34
46
  const controller = new AbortController();
@@ -37,8 +49,9 @@ async function lookup(h, { apiUrl, fetchImpl = fetch } = {}) {
37
49
  const response = await fetchImpl(`${base}/api/identity/${encodeURIComponent(h)}`, { signal: controller.signal, headers: { Accept: 'application/json' } });
38
50
  if (response.status === 404) return { found: false };
39
51
  const who = response.ok ? await response.json().catch(() => null) : null;
40
- if (!who || String(who.handle || '').toLowerCase() !== h) return { found: null };
41
- return { found: true, kind: who.kind === 'agent' ? 'agent' : (who.kind === 'human' ? 'human' : 'account') };
52
+ const handle = who ? String(who.handle || '').toLowerCase() : '';
53
+ if (!handle || !sameAccount(h, handle)) return { found: null };
54
+ return { found: true, kind: who.kind === 'agent' ? 'agent' : (who.kind === 'human' ? 'human' : 'account'), handle };
42
55
  } catch {
43
56
  return { found: null };
44
57
  } finally {
@@ -46,6 +59,34 @@ async function lookup(h, { apiUrl, fetchImpl = fetch } = {}) {
46
59
  }
47
60
  }
48
61
 
62
+ /**
63
+ * The handle to address, for a recipient typed with a '-'.
64
+ *
65
+ * GitHub sign-in gives a login like "a-b" the handle "a_b" (the platform folds
66
+ * '-' to '_'), and its inbox is read under that spelling. A message addressed
67
+ * to "a-b" is accepted by the platform but stored under "a-b", where "a_b"
68
+ * never sees it. So the platform's own answer decides: when the identity
69
+ * lookup finds the account under a spelling that differs only by '-' for '_',
70
+ * that spelling is used. Some older accounts really are stored with the dash;
71
+ * then the lookup says so and the dash stays. Nothing is folded blindly.
72
+ *
73
+ * No '-', no request. Any answer other than a found account (absent, unclear,
74
+ * offline, a throw) leaves the handle exactly as typed.
75
+ *
76
+ * @returns {Promise<{ handle: string, who: object|null }>} who is the lookup
77
+ * result when one was made (callers reuse it rather than asking twice).
78
+ */
79
+ async function resolveRecipient(h, opts = {}) {
80
+ const typed = String(h || '');
81
+ if (!typed.includes('-')) return { handle: typed, who: null };
82
+ let who;
83
+ try { who = await lookup(typed, opts); } catch { who = { found: null }; }
84
+ if (!who || typeof who !== 'object') who = { found: null };
85
+ const theirs = who.found === true && typeof who.handle === 'string' ? who.handle : '';
86
+ const handle = theirs && theirs !== typed && sameAccount(typed, theirs) && validHandle(theirs) ? theirs : typed;
87
+ return { handle, who };
88
+ }
89
+
49
90
  /**
50
91
  * Mark the inviter as known. Returns the lines to print; never throws, because
51
92
  * a setup that just succeeded must not end in an error over a courtesy.
@@ -57,15 +98,19 @@ async function accept(typed, me, opts = {}) {
57
98
  const who = await lookup(h, opts);
58
99
  if (who.found === false) return { known: false, lines: [`There is no @${h} on /vibe, so nobody was marked as your inviter. Check the spelling with them.`] };
59
100
  if (who.found !== true) return { known: false, lines: [`Could not confirm @${h} just now, so they were not marked. Write to them once and they are known.`] };
60
- reach.know(h, opts.env);
61
- if (!reach.isKnown(h, opts.env)) return { known: false, lines: [] };
101
+ // Their messages arrive from the handle as the platform stores it, which
102
+ // can differ from what was typed only by '-' for '_'. That is the one marked.
103
+ const them = who.handle && validHandle(who.handle) ? who.handle : h;
104
+ if (them === reach.norm(me)) return { known: false, lines: [] };
105
+ reach.know(them, opts.env);
106
+ if (!reach.isKnown(them, opts.env)) return { known: false, lines: [] };
62
107
  const what = who.kind === 'agent' ? ', an agent,' : '';
63
108
  return {
64
109
  known: true,
65
- handle: h,
110
+ handle: them,
66
111
  lines: [
67
- `@${h}${what} invited you, so what they write reaches you while you work.`,
68
- `Nothing was sent and no line was opened. Undo: npx slashvibe-mcp mute @${h}`,
112
+ `@${them}${what} invited you, so what they write reaches you while you work.`,
113
+ `Nothing was sent and no line was opened. Undo: npx slashvibe-mcp mute @${them}`,
69
114
  ],
70
115
  };
71
116
  }
@@ -77,4 +122,4 @@ function line(me) {
77
122
  return { command: `npx slashvibe-mcp setup --from @${h}`, link: `https://www.slashvibe.dev/join?from=${h}` };
78
123
  }
79
124
 
80
- module.exports = { fromArg, accept, line, lookup };
125
+ module.exports = { fromArg, accept, line, lookup, resolveRecipient };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slashvibe-mcp",
3
- "version": "0.9.14",
3
+ "version": "0.9.16",
4
4
  "mcpName": "io.github.vibecodinginc/vibe",
5
5
  "description": "Telepathic messaging between people, from inside Claude Code",
6
6
  "main": "index.js",
package/presence.js CHANGED
@@ -145,15 +145,20 @@ async function poll() {
145
145
  * Known = an open line, a send recorded on this machine, or (checked once and
146
146
  * then remembered) any message of yours in the conversation, so someone you
147
147
  * wrote to from another device still reaches you here. Reading the
148
- * conversation does not mark it read. A failed read is "not known yet".
148
+ * conversation does not mark it read.
149
+ *
150
+ * Three answers: true, false (the conversation was read and holds nothing of
151
+ * yours), or null (it could not be read, so this says nothing either way).
152
+ * store.getThread reports a failed read by value, an empty list carrying
153
+ * readFailed, rather than by throwing; a throw counts as could-not-tell too.
149
154
  */
150
155
  async function knows(me, them) {
151
156
  if (line.isOpen(them) || reach.isKnown(them)) return true;
152
- try {
153
- const thread = await store.getThread(me, them);
154
- const mine = String(me).toLowerCase();
155
- if ((thread || []).some((m) => String(m.from || '').toLowerCase() === mine)) { reach.know(them); return true; }
156
- } catch {}
157
+ let thread;
158
+ try { thread = await store.getThread(me, them); } catch { return null; }
159
+ if (!Array.isArray(thread) || thread.readFailed) return null;
160
+ const mine = String(me).toLowerCase();
161
+ if (thread.some((m) => String((m && m.from) || '').toLowerCase() === mine)) { reach.know(them); return true; }
157
162
  return false;
158
163
  }
159
164
 
@@ -186,11 +191,15 @@ async function noteArrivals(handle, threads) {
186
191
  .filter((t) => !arrival.isClaimed(t.lastMessageId) && !arrival.isSpooled(t.lastMessageId));
187
192
  // Only someone you know reaches you mid-work (reach.js). A muted person, or
188
193
  // someone you have never written to, stays waiting: remembered here so the
189
- // question is asked once per message, not once per poll.
194
+ // question is asked once per message, not once per poll. A conversation that
195
+ // could not be read decides nothing, so that message is asked about again
196
+ // on the next poll instead of being parked for the rest of the session.
190
197
  const candidates = [];
191
198
  for (const t of wanted) {
192
- if (!reach.isMuted(t.lastFrom) && await knows(handle, t.lastFrom)) candidates.push(t);
193
- else waitingAtStart.add(t.lastMessageId);
199
+ if (reach.isMuted(t.lastFrom)) { waitingAtStart.add(t.lastMessageId); continue; }
200
+ const known = await knows(handle, t.lastFrom);
201
+ if (known === true) candidates.push(t);
202
+ else if (known === false) waitingAtStart.add(t.lastMessageId);
194
203
  }
195
204
  if (candidates.length === 0) return;
196
205
  const allowed = new Set(candidates.map((t) => t.lastMessageId));
@@ -4,13 +4,17 @@
4
4
  * This exists because the same defect has landed three times now: a padded/cased handle
5
5
  * normalized differently in different layers, so a self-DM passed the self-check AND
6
6
  * delivered. The most recent instance is instructive — `normalizeHandle` in
7
- * tools/_shared.js strips a leading `@` BEFORE trimming, so " @alice " becomes "@alice"
8
- * (the leading space defeats the ^@ match), which then fails to equal "alice" and lets a
9
- * padded self-target through. Order of operations, not intent.
7
+ * tools/_shared.js stripped a leading `@` BEFORE trimming, so " @alice " became "@alice"
8
+ * (the leading space defeated the ^@ match), which then failed to equal "alice" and let a
9
+ * padded self-target through. Order of operations, not intent. (Fixed: it trims first
10
+ * now, and tools/deliver.js uses canonicalHandle for the recipient and the self-check.)
10
11
  *
11
12
  * Rules, matching api/lib/handles.js so the platform and the protocol agree:
12
13
  * strip zero-width characters → NFC normalize → trim → strip leading @s → trim again
13
- * → lowercase → map '-' to '_' (the platform treats them as the same handle).
14
+ * → lowercase. The dash is KEPT: a handle is a GitHub login and logins may contain
15
+ * '-'. The platform's handles.js folds '-' to '_' when it first assigns a handle, so
16
+ * 'a-b' and 'a_b' can name the same account there; this form does not merge them
17
+ * (see the note in canonicalHandle).
14
18
  *
15
19
  * NOT done: unicode folding of letters. Platform handles are ASCII [a-z0-9_], so a
16
20
  * non-ASCII handle is INVALID rather than something to fold — folding lookalikes would
@@ -25,7 +29,6 @@
25
29
  // Zero-width and bidi controls: invisible padding that makes two handles look identical.
26
30
  const INVISIBLE = /[​-‍⁠؜‎‏‪-‮⁦-⁩]/g;
27
31
 
28
- /** Canonical comparison/storage form, or '' when there isn't one. */
29
32
  /**
30
33
  * The recipient exactly as the platform STORES it (message-service
31
34
  * storedRecipientHandle: lowercase, leading @ stripped, hyphens KEPT). The
@@ -36,6 +39,7 @@ function storedRecipientHandle(value) {
36
39
  return String(value || '').toLowerCase().replace(/^@/, '');
37
40
  }
38
41
 
42
+ /** Canonical comparison/storage form, or '' when there isn't one. */
39
43
  function canonicalHandle(value) {
40
44
  if (typeof value !== 'string') return '';
41
45
  let h = value.replace(INVISIBLE, '');
package/setup.js CHANGED
@@ -17,7 +17,7 @@
17
17
  const fs = require('fs');
18
18
  const path = require('path');
19
19
  const os = require('os');
20
- const { exec, execSync } = require('child_process');
20
+ const { execFile, execSync } = require('child_process');
21
21
  const { beginOAuth } = require('./oauth-callback');
22
22
  const actorSession = require('./actor-session');
23
23
 
@@ -290,18 +290,21 @@ function openBrowser(url) {
290
290
  console.log(`${colors.dim} (browser suppressed for conformance run)${colors.reset}`);
291
291
  return;
292
292
  }
293
- const platform = process.platform;
294
- let command;
295
-
296
- if (platform === 'darwin') {
297
- command = `open "${url}"`;
298
- } else if (platform === 'win32') {
299
- command = `start "" "${url}"`;
293
+ // No shell: the URL is one argument to the opener, so nothing in it (a
294
+ // quote, an &, a $) can be read as a command.
295
+ let file;
296
+ let args;
297
+ if (process.platform === 'darwin') {
298
+ file = 'open'; args = [url];
299
+ } else if (process.platform === 'win32') {
300
+ // `cmd /c start` would hand the URL to cmd's parser, where & ends the
301
+ // command. The URL handler opens it in the default browser without one.
302
+ file = 'rundll32'; args = ['url.dll,FileProtocolHandler', url];
300
303
  } else {
301
- command = `xdg-open "${url}"`;
304
+ file = 'xdg-open'; args = [url];
302
305
  }
303
306
 
304
- exec(command, (err) => {
307
+ execFile(file, args, (err) => {
305
308
  if (err) {
306
309
  console.log(`${colors.yellow} Could not open browser automatically.${colors.reset}`);
307
310
  console.log(`${colors.cyan} Please open: ${url}${colors.reset}`);
@@ -593,4 +596,5 @@ module.exports = {
593
596
  saveAuthConfig,
594
597
  retireDeadCredential,
595
598
  installHostCommands,
599
+ openBrowser,
596
600
  };
package/store/api.js CHANGED
@@ -534,8 +534,8 @@ async function sendMessage(from, to, body, type = 'dm', payload = null, options
534
534
 
535
535
  // Handle auth errors
536
536
  if (!result.success && result.error?.includes('Authentication')) {
537
- console.error('[vibe] Auth failed for message. Try `vibe init` to re-register.');
538
- return { error: 'auth_failed', message: 'Authentication failed. Try `vibe init` to re-register.' };
537
+ console.error('[vibe] Auth failed for message. Sign in again: npx slashvibe-mcp setup');
538
+ return { error: 'auth_failed', message: 'Authentication failed. Sign in again by running `npx slashvibe-mcp setup` in a terminal.' };
539
539
  }
540
540
 
541
541
  // Handle 401 — distinguish "never signed in" from "session expired".
@@ -543,14 +543,14 @@ async function sendMessage(from, to, body, type = 'dm', payload = null, options
543
543
  // A misleading "expired" message here is a first-session papercut for the pilot.
544
544
  if (result.statusCode === 401) {
545
545
  if (!config.hasOAuth()) {
546
- console.error('[vibe] DM requires sign-in. Run `vibe init` (GitHub OAuth).');
546
+ console.error('[vibe] DM requires sign-in. Run: npx slashvibe-mcp setup');
547
547
  return {
548
548
  error: 'not_signed_in',
549
- message: "You're not signed in yet — sending a DM needs a /vibe identity. Run `vibe init` to sign in with GitHub (opens a browser, no input needed), then try again.",
549
+ message: "You're not signed in yet — sending a DM needs a /vibe identity. Run `npx slashvibe-mcp setup` in a terminal to sign in with GitHub (opens a browser), then try again.",
550
550
  };
551
551
  }
552
- console.error('[vibe] Auth expired. Run `vibe init` to reconnect.');
553
- return { error: 'auth_expired', message: 'Your /vibe session expired. Run `vibe init` to reconnect.' };
552
+ console.error('[vibe] Auth expired. Run: npx slashvibe-mcp setup');
553
+ return { error: 'auth_expired', message: 'Your /vibe session expired. Run `npx slashvibe-mcp setup` in a terminal to sign in again.' };
554
554
  }
555
555
 
556
556
  // Handle storage errors (KV write failed)
@@ -565,12 +565,25 @@ async function sendMessage(from, to, body, type = 'dm', payload = null, options
565
565
  return { error: result.error, message: result.message || 'Failed to send message.' };
566
566
  }
567
567
 
568
+ // Delivered only on a real success: success === true, or the stored
569
+ // message itself. A 200 whose body was not JSON comes back from
570
+ // requestOnce as { raw }, and { success: false } with no error string
571
+ // names no failure; both used to fall through to "Sent" with no receipt.
572
+ // The write may still have happened, so this is an uncertain failure,
573
+ // never a definite one (tools/deliver.js keeps it out of DEFINITE).
574
+ const delivered = result.success === true || Boolean(result.message && typeof result.message === 'object');
575
+ if (!delivered) {
576
+ console.error('[vibe] Send reply unreadable; outcome unknown.');
577
+ return {
578
+ error: 'unconfirmed_response',
579
+ message: "/vibe answered, but its reply could not be read, so it is not known whether the message was stored. It may or may not have reached them.",
580
+ };
581
+ }
582
+
568
583
  // Emit list_changed notification for successful message send
569
584
  // This allows other Claude Code instances to see the new message instantly
570
- if (result.success || result.message) {
571
- if (global.vibeNotifier) {
572
- global.vibeNotifier.emitImmediate(); // Immediate for DMs
573
- }
585
+ if (global.vibeNotifier) {
586
+ global.vibeNotifier.emitImmediate(); // Immediate for DMs
574
587
  }
575
588
 
576
589
  // A success with no message body must still come back truthy — callers read
@@ -593,7 +606,7 @@ async function sendMessage(from, to, body, type = 'dm', payload = null, options
593
606
  console.error('Send failed:', e.message);
594
607
  return {
595
608
  error: 'transport_failed',
596
- message: "That didn't send — the connection dropped mid-request. Nothing was delivered. Worth one retry; if it keeps failing, say `vibe help troubleshooting`.",
609
+ message: "That didn't send — the connection dropped mid-request. Nothing was delivered. Worth one retry.",
597
610
  };
598
611
  }
599
612
  }
@@ -816,7 +829,11 @@ async function getThreadWithRequest(makeRequest, myHandle, theirHandle) {
816
829
  // The proxy accepts both its current snake_case response and the legacy row
817
830
  // names used by older deployments. Keep the array contract for callers while
818
831
  // carrying response metadata alongside it for a lookup-free read PATCH.
819
- const rows = result.messages || result.thread || [];
832
+ const rows = result.messages || result.thread;
833
+ // A reply with no message list (a non-JSON body arrives as { raw }) is not
834
+ // an empty conversation. Callers keep their array; the ones that must tell
835
+ // "nothing there" from "could not read" check readFailed (presence.js).
836
+ if (!Array.isArray(rows)) return failedThread();
820
837
  const messages = rows.map(m => ({
821
838
  id: m.id || null,
822
839
  from: m.from,
@@ -841,12 +858,19 @@ async function getThreadWithRequest(makeRequest, myHandle, theirHandle) {
841
858
  return messages;
842
859
  }
843
860
 
861
+ /** An empty thread that says it is empty because the read failed. */
862
+ function failedThread() {
863
+ const empty = [];
864
+ Object.defineProperty(empty, 'readFailed', { value: true, enumerable: false });
865
+ return empty;
866
+ }
867
+
844
868
  async function getThread(myHandle, theirHandle) {
845
869
  try {
846
870
  return await getThreadWithRequest(request, myHandle, theirHandle);
847
871
  } catch (e) {
848
872
  console.error('Thread failed:', e.message);
849
- return [];
873
+ return failedThread();
850
874
  }
851
875
  }
852
876
 
@@ -907,6 +931,18 @@ async function markThreadRead(myHandle, theirHandle, lastMessageId = null, threa
907
931
 
908
932
  // ============ INVITES ============
909
933
 
934
+ /**
935
+ * POST /api/invites — a held message for someone not on /vibe yet (a
936
+ * thought-bearing invitation named for one GitHub login). Sent ONCE, never
937
+ * retried here: the route has no idempotency key, so a transport retry after
938
+ * a lost response could mint a second invitation. The caller decides what an
939
+ * unanswered request means. `body.dry_run: true` is the platform's
940
+ * side-effect-free preview of the same request.
941
+ */
942
+ async function createInvite(body) {
943
+ return request('POST', '/api/invites', body, { maxRetries: 0 });
944
+ }
945
+
910
946
  // ============ AUTH ============
911
947
 
912
948
  /**
@@ -1021,6 +1057,9 @@ module.exports = {
1021
1057
  // Auth
1022
1058
  verifyAuthToken,
1023
1059
 
1060
+ // Invites (a held message for someone not on /vibe yet)
1061
+ createInvite,
1062
+
1024
1063
  // Hermetic request-count tests for the named-thread fast path.
1025
1064
  _testing: { getThreadWithRequest, markThreadReadWithRequest },
1026
1065
  };
package/tools/_shared.js CHANGED
@@ -24,7 +24,7 @@ const store = require('../store');
24
24
  function requireInit() {
25
25
  if (!config.isInitialized()) {
26
26
  return {
27
- display: "You're not signed in yet. Run `vibe init` — GitHub opens in your browser and your username becomes your @handle.",
27
+ display: "You're not signed in yet. Run `npx slashvibe-mcp setup` in a terminal — GitHub opens in your browser and your username becomes your @handle.",
28
28
  error: 'not_initialized'
29
29
  };
30
30
  }
@@ -36,13 +36,17 @@ function requireInit() {
36
36
  // ─────────────────────────────────────────────────────────────
37
37
 
38
38
  /**
39
- * Normalize a handle string (remove @, lowercase, trim)
39
+ * Normalize a handle string (trim, remove leading @s, lowercase).
40
+ * Trim comes first: stripping the @ before trimming turned " @alice " into
41
+ * "@alice", which then failed to equal "alice" (protocol/handle.js has the
42
+ * history). For anything that decides who a message goes to, use
43
+ * canonicalHandle from protocol/handle.js.
40
44
  * @param {string} handle - Raw handle input
41
45
  * @returns {string} Normalized handle
42
46
  */
43
47
  function normalizeHandle(handle) {
44
48
  if (!handle) return '';
45
- return handle.toString().replace(/^@/, '').toLowerCase().trim();
49
+ return handle.toString().trim().replace(/^@+/, '').trim().toLowerCase();
46
50
  }
47
51
 
48
52
  /**
package/tools/deliver.js CHANGED
@@ -11,7 +11,8 @@
11
11
 
12
12
  const config = require('../config');
13
13
  const store = require('../store');
14
- const { requireInit, normalizeHandle, isHereNow } = require('./_shared');
14
+ const { requireInit, isHereNow } = require('./_shared');
15
+ const { canonicalHandle } = require('../protocol/handle');
15
16
 
16
17
  const MAX_LENGTH = 2000;
17
18
 
@@ -22,8 +23,10 @@ const MAX_LENGTH = 2000;
22
23
  const DEFINITE = new Set(['not_signed_in', 'self_dm', 'message_too_long', 'approved_content_mismatch',
23
24
  'approved_sha256_malformed', 'approved_send_unsupported_route', 'private_composition_data', 'idempotency_conflict']);
24
25
  // Errors whose message already names the fix; they get no generic retry hint.
26
+ // An unreadable reply is one of them: it may have been stored, and a typed
27
+ // resend carries a fresh key, so "worth one retry" could deliver it twice.
25
28
  const REMEDY_CARRYING = new Set(['auth_expired', 'not_signed_in', 'auth_failed', 'handle_not_found',
26
- 'self_dm', 'storage_error', 'transport_failed']);
29
+ 'self_dm', 'storage_error', 'transport_failed', 'unconfirmed_response']);
27
30
 
28
31
  /**
29
32
  * @param {{to: string, message: string, replyTo?: string|null, origin?: string,
@@ -33,10 +36,12 @@ async function deliver(m) {
33
36
  const initCheck = requireInit();
34
37
  if (initCheck) return { ...initCheck, data: { sent: false, definite: true } };
35
38
 
39
+ // Both sides in the one canonical form, so a padded or prefixed "@me" is
40
+ // still recognised as you (protocol/handle.js).
36
41
  const me = config.getHandle();
37
- const them = normalizeHandle(m.to);
42
+ const them = canonicalHandle(typeof m.to === 'string' ? m.to : String(m.to || ''));
38
43
  if (!them) return { display: 'Nothing sent. Who is it for?', data: { sent: false, definite: true } };
39
- if (them === me) return { display: "You can't message yourself.", data: { sent: false, definite: true } };
44
+ if (them === canonicalHandle(me || '')) return { display: "You can't message yourself.", data: { sent: false, definite: true } };
40
45
 
41
46
  const text = typeof m.message === 'string' ? m.message.trim() : '';
42
47
  if (!text) return { display: 'Nothing sent. The message is empty.', data: { sent: false, definite: true } };
@@ -91,9 +96,11 @@ async function deliver(m) {
91
96
 
92
97
  // Nobody has to be online. Say so once, when it applies; presence being
93
98
  // unreadable never turns a real send into noise.
99
+ // Only a presence read that succeeded can say they are not here; a failed
100
+ // one says nothing (getActiveUsers flattens a failure to an empty room).
94
101
  try {
95
- const room = await store.getActiveUsers();
96
- if (!isHereNow((room || []).find((u) => u.handle === them))) {
102
+ const room = await store.getActiveUsersResult();
103
+ if (room && room.ok === true && !isHereNow((room.users || []).find((u) => u && u.handle === them))) {
97
104
  display += `\n_@${them} is not in a session right now. It reaches them when they next are._`;
98
105
  }
99
106
  } catch (e) {}
package/tools/drafts.js CHANGED
@@ -23,6 +23,12 @@
23
23
  *
24
24
  * Draft states: previewed → sending → sent
25
25
  * ↘ cancelled ↘ unknown (retry/cancel only)
26
+ *
27
+ * Held drafts: a draft to a handle /vibe says does not exist (a definite 404,
28
+ * never a lookup that merely failed) and that is a GitHub login is HELD: Send
29
+ * creates a thought-bearing invitation named for that GitHub account instead
30
+ * of a message, so the exact approved text becomes the sender's first message
31
+ * when that person signs in. previewed → sending → held. It is never "sent".
26
32
  */
27
33
 
28
34
  const fs = require('fs');
@@ -34,6 +40,7 @@ const { requireInit, normalizeHandle, isHereNow } = require('./_shared');
34
40
  const { canonicalHandle, storedRecipientHandle } = require('../protocol/handle');
35
41
  const { inertField } = require('../incoming');
36
42
  const { deliver } = require('./deliver');
43
+ const invite = require('../invite');
37
44
 
38
45
  const DRAFTS_FILE = path.join(config.VIBE_DIR, 'drafts.json');
39
46
  const BINDINGS_FILE = path.join(config.VIBE_DIR, 'return-bindings.json');
@@ -194,19 +201,44 @@ function reconcileAbandoned(d) {
194
201
  const newId = (prefix) => `${prefix}${crypto.randomBytes(4).toString('hex')}`;
195
202
  // The reply target is part of what the person approves: answering a
196
203
  // different message is a different act, so it changes the rev and the key.
197
- const textHash = (d) => crypto.createHash('sha1').update(compose(d) + (d.replyTo ? `\n\u21a9${d.replyTo}` : '')).digest('hex');
204
+ // Holding a message for a newcomer is a different act from sending one, so
205
+ // it is part of the rev too (a held draft never shares a rev with a send).
206
+ const textHash = (d) => crypto.createHash('sha1').update(compose(d) + (d.replyTo ? `\n\u21a9${d.replyTo}` : '') + (d.held ? '\nheld-for-github' : '')).digest('hex');
198
207
  const sendKey = (d) => `draft-${d.id}-${textHash(d).slice(0, 10)}`;
199
208
  /**
200
209
  * The #392 approval digest over the EXACT snapshot the person approved:
201
210
  * SHA-256 of "<stored recipient>\n<body>", where the recipient is the form
202
211
  * the platform stores (lowercase, no @) and the body is the composed text
203
- * trimmed — exactly what vibe_dm sends. Computed once, at claim, from the
212
+ * trimmed — exactly what deliver() sends. Computed once, at claim, from the
204
213
  * snapshot; never recomputed after a change to the previewed content.
205
214
  */
206
215
  const approvedDigest = (to, message) => crypto.createHash('sha256').update(`${storedRecipientHandle(to)}\n${message}`, 'utf8').digest('hex');
207
216
  /** The preview revision: what the person SAW. Send must name it (codex P1). */
208
217
  const revOf = (d) => textHash(d).slice(0, 8);
209
218
 
219
+ // ── held: a message kept for someone not on /vibe yet ─────────────────────────
220
+ // Platform contract: api/invites.js (POST /api/invites with first_thought +
221
+ // for_github), api/lib/invitation-email.js (APPROVAL_RULE, approvalInput).
222
+
223
+ const HELD_DAYS = 30;
224
+ /** The platform's for_github shape (api/invites.js), applied to the canonical handle. */
225
+ const GITHUB_LOGIN = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/;
226
+ const isGithubLogin = (h) => GITHUB_LOGIN.test(String(h || ''));
227
+ /** generateCode(): 'VIBE-' + 4 of an unambiguous alphabet + '-' + the inviter handle's first 4. */
228
+ const INVITE_CODE = /^VIBE-[A-Z0-9]{4}-[A-Z0-9_-]{1,4}$/;
229
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
230
+ /**
231
+ * The platform's invitation approval digest (APPROVAL_RULE 'invitation-v1'):
232
+ * sha256 over [rule, for_email, subject, text, html, open_note, question,
233
+ * first_thought] joined by U+0000. A held draft carries only first_thought,
234
+ * so every other field is the empty string. Note: for_github is NOT covered
235
+ * by the platform digest; the recipient is bound here by the draft rev.
236
+ */
237
+ const heldDigest = (firstThought) => crypto.createHash('sha256')
238
+ .update(['invitation-v1', '', '', '', '', '', '', firstThought].join('\u0000'), 'utf8').digest('hex');
239
+ /** The handle the platform gives a GitHub login on first sign-in (handles.js normalizeHandle folds '-' to '_'). */
240
+ const handleForLogin = (login) => String(login || '').replace(/-/g, '_');
241
+
210
242
  // Field ceilings keep a draft inside the 2000-char message limit. A field
211
243
  // over its ceiling is REPORTED, never silently cut: a draft that ends
212
244
  // mid-word is not "the exact text you approve" (product-test finding —
@@ -235,7 +267,7 @@ function compose(d) { return `${d.body || ''}${refLines(d.refs)}`; }
235
267
 
236
268
  const draftDefinition = {
237
269
  name: 'vibe_prepare',
238
- description: "Prepare a message to a person for review. Sends NOTHING. Use this whenever YOU wrote the words (from the work in this session, or as an answer to a message that arrived): pass handle + message, and reply_to when it answers a specific message. Returns the exact preview and the three choices: Send / Edit / Cancel. To edit, call again with the draft id and the new message.",
270
+ description: "Prepare a message to a person for review. Sends NOTHING. Use this whenever YOU wrote the words (from the work in this session, or as an answer to a message that arrived): pass handle + message, and reply_to when it answers a specific message. Returns the exact preview and the three choices: Send / Edit / Cancel. To edit, call again with the draft id and the new message. If the handle is not on /vibe yet, the preview says so and the message is held for that GitHub account instead.",
239
271
  inputSchema: {
240
272
  type: 'object',
241
273
  properties: {
@@ -286,28 +318,58 @@ async function draftHandler(args) {
286
318
  const message = typeof (args && args.message) === 'string' ? args.message.trim() : '';
287
319
  const wantId = args && args.id;
288
320
 
321
+ // Is the person on /vibe at all? Asked only for a NEW draft to a handle
322
+ // shaped like a GitHub login. Only a definite "no such handle" (404) makes
323
+ // the draft held; a lookup that could not confirm keeps today's behaviour.
324
+ //
325
+ // A handle with a '-' is also addressed by the platform's spelling of it
326
+ // (invite.resolveRecipient): the draft's `to`, its rev, its digest and the
327
+ // stored recipient all use what the lookup answered. That one lookup also
328
+ // serves the held check, so a prepare never asks twice.
329
+ let absent = false;
330
+ let resolvedTo = null;
331
+ if (!wantId && args && args.handle && message) {
332
+ const to = canonicalHandle(args.handle);
333
+ // Someone you already know is on /vibe: no lookup, so the ordinary
334
+ // preview costs no extra request and cannot be slowed by this one.
335
+ let known = false;
336
+ try { known = require('../reach').isKnown(to); } catch { known = false; }
337
+ if (to && to !== me && to.includes('-') && !to.endsWith('/claude')) {
338
+ const r = await invite.resolveRecipient(to);
339
+ resolvedTo = r.handle;
340
+ // Absent means the login as typed: a held draft is for that GitHub account.
341
+ if (!known && isGithubLogin(to)) absent = Boolean(r.who && r.who.found === false);
342
+ } else if (to && to !== me && to !== 'echo' && !known && isGithubLogin(to)) {
343
+ try { absent = (await invite.lookup(to)).found === false; } catch { absent = false; }
344
+ }
345
+ }
346
+
289
347
  const out = transact(drafts => {
290
348
  let d = wantId ? drafts.find(x => x.id === wantId) : null;
291
349
  if (wantId && !d) return { display: `No draft ${wantId} — it may have expired (drafts live 24h, locally). Prepare it again.` };
292
350
  if (!d) {
293
351
  if (!args || !args.handle || !message) return { display: 'To prepare a message: pass a handle and a message (or a draft id to edit). Nothing is sent by this step.' };
294
- const to = canonicalHandle(args.handle);
352
+ const to = resolvedTo || canonicalHandle(args.handle);
295
353
  if (!to) return { display: 'To prepare a message: pass a handle and a message (or a draft id to edit). Nothing is sent by this step.' };
296
354
  if (to === me) return { display: "You can't draft to yourself." };
297
355
  // @echo is the feedback line with its own path and no receipt shape;
298
356
  // it is not a person to draft to (codex P2).
299
- if (to === 'echo') return { display: '@echo is the feedback line — send to it with vibe_dm directly. Nothing drafted.' };
357
+ if (to === 'echo') return { display: '@echo is the feedback line. To write to it, send the person\'s own words with vibe_send (handle + message). Nothing drafted.' };
300
358
  // An approval-bound send targets a durable conversation; the live
301
359
  // session route stores nothing and the platform refuses it (CB-007).
302
360
  if (to.endsWith('/claude')) return { display: `Drafts go to a person's durable conversation, not a live session — use @${to.replace(/\/claude$/, '')} instead. Nothing drafted.` };
303
361
  const project = typeof args.project === 'string' && args.project.trim() ? args.project.trim().slice(0, 60) : null;
304
362
  d = { id: newId('w'), status: 'previewed', createdAt: Date.now(), from: me, to, body: message, replyTo: cleanId(args.reply_to), refs: cleanContext({ refs: args.refs }).refs, context: { project } };
363
+ // Nothing to answer in a conversation that does not exist yet.
364
+ if (absent) { d.held = true; d.replyTo = null; }
305
365
  drafts.push(d);
306
366
  } else {
307
367
  // A finished draft stays finished; an unconfirmed one may only be
308
368
  // retried as-is or cancelled (its idempotency key names THIS text).
309
369
  if (d.from && d.from !== me) return { display: `Draft ${d.id} was prepared as @${d.from}; you are signed in as @${me}. Nothing sent — open a new draft as yourself.` };
310
370
  reconcileAbandoned(d);
371
+ if (d.status === 'held') return { display: heldAlready(d) };
372
+ if (d.held && d.status === 'unknown') return { display: heldUnknown(d) };
311
373
  if (d.status === 'sent') return { display: `Draft ${d.id} was already sent to @${d.to} — nothing changed. Open a new draft to say more.` };
312
374
  if (d.status === 'cancelled') return { display: d.unconfirmed
313
375
  ? `Draft ${d.id} was cancelled after a Send to @${d.to} that did not confirm — it may or may not have reached them. Open a new draft to say more.`
@@ -323,7 +385,7 @@ async function draftHandler(args) {
323
385
  d.edited = true;
324
386
  }
325
387
  if (args.refs) { d.refs = cleanContext({ refs: args.refs }).refs; }
326
- if (args.reply_to !== undefined) d.replyTo = cleanId(args.reply_to);
388
+ if (args.reply_to !== undefined && !d.held) d.replyTo = cleanId(args.reply_to);
327
389
  d.status = 'previewed';
328
390
  }
329
391
  }
@@ -331,9 +393,31 @@ async function draftHandler(args) {
331
393
  return { draft: { ...d } };
332
394
  });
333
395
  if (out.display) return out;
396
+ if (out.draft.held) return heldPreview(out.draft);
334
397
  return preview(out.draft, await findPerson(out.draft.to));
335
398
  }
336
399
 
400
+ function heldPreview(d) {
401
+ const att = d.refs && d.refs.length ? d.refs.map(r => `${r.title}: ${r.url}`).join('\n') : 'none';
402
+ const message = compose(d);
403
+ const rev = revOf(d);
404
+ return {
405
+ display: `**To:** @${d.to} (not on /vibe yet)\n**Message (exact):**\n${message}\n**Attachments:** ${att}\n\n`
406
+ + `@${d.to} is not on /vibe yet. If you keep it, this exact message is held for the GitHub account ${d.to} for ${HELD_DAYS} days and arrives as your first message when they sign in to /vibe with that account. You get a link to pass on to them.\n\n`
407
+ + `Keep for @${d.to} · Edit · Cancel — nothing has been sent. _(draft ${d.id} · rev ${rev})_`,
408
+ data: {
409
+ draft: { id: d.id, to: d.to, body: d.body, message, refs: d.refs || [], status: d.status, rev, held: true, for_github: d.to },
410
+ actions: [{ label: `Keep for @${d.to}`, tool: 'vibe_send', args: { id: d.id, rev } }, { label: 'Edit', tool: 'vibe_prepare', args: { id: d.id, message: '<new body text — links are kept separately>' } }, { label: 'Cancel', tool: 'vibe_discard', args: { id: d.id } }],
411
+ },
412
+ };
413
+ }
414
+ function heldAlready(d) {
415
+ return `Draft ${d.id} is already held for @${d.to} — not creating a second invitation.${d.joinUrl ? ` Join link: ${d.joinUrl}` : ''}`;
416
+ }
417
+ function heldUnknown(d) {
418
+ return `Draft ${d.id}: the last Keep for @${d.to} did not confirm — the invitation may or may not have been created, and a second try could create two. Cancel it, then open a new draft if you still want to say it. Nothing more was done.`;
419
+ }
420
+
337
421
  // ── vibe_discard ───────────────────────────────────────────────────────
338
422
 
339
423
  const discardDefinition = {
@@ -349,12 +433,21 @@ async function discardHandler(args) {
349
433
  if (!d) return { display: `No draft ${id} to cancel — nothing was sent either way.` };
350
434
  reconcileAbandoned(d);
351
435
  if (d.status === 'sending') return { display: `Draft ${d.id} is being sent to @${d.to} right now — it can't be cancelled at this point.`, data: { draft: { id: d.id, status: d.status } } };
436
+ if (d.status === 'held') return { display: `Draft ${d.id} is already held for @${d.to} — a held message can't be taken back from here.`, data: { draft: { id: d.id, status: d.status } } };
352
437
  if (d.status === 'sent') return { display: `Draft ${d.id} was already sent to @${d.to} — a sent message can't be unsent.`, data: { draft: { id: d.id, status: d.status } } };
353
438
  if (d.status === 'cancelled') return { display: d.unconfirmed
354
439
  ? `Draft ${d.id} is already cancelled — and the earlier Send to @${d.to} did not confirm, so it may or may not have reached them.`
355
440
  : `Draft ${d.id} is already cancelled — nothing was sent.`, data: { draft: { id: d.id, status: d.status } } };
356
441
  const wasUnknown = d.status === 'unknown' || Boolean(d.unconfirmed);
357
442
  d.status = 'cancelled';
443
+ if (d.held) {
444
+ return {
445
+ display: wasUnknown
446
+ ? `Cancelled — nothing more will be done for @${d.to}. Note: the earlier Keep did not confirm, so an invitation may or may not have been created.`
447
+ : `Cancelled — nothing kept for @${d.to}. The draft stays on your machine.`,
448
+ data: { draft: { id: d.id, status: 'cancelled' } },
449
+ };
450
+ }
358
451
  return {
359
452
  display: wasUnknown
360
453
  ? `Cancelled — no further send to @${d.to}. Note: the earlier attempt did not confirm, so it may or may not have reached them.`
@@ -392,9 +485,17 @@ async function sendHandler(args) {
392
485
  if (!args || !args.handle || typeof args.message !== 'string' || !args.message.trim()) {
393
486
  return { display: 'Nothing sent. Pass a draft id and rev, or a handle and the exact message.' };
394
487
  }
395
- const result = await deliver({ to: args.handle, message: args.message, replyTo: cleanId(args.reply_to) });
488
+ // Addressed by the platform's spelling when the handle has a '-'
489
+ // (invite.resolveRecipient). Done here, not in deliver: a draft's digest
490
+ // is computed over its `to` before deliver runs, so deliver must not
491
+ // change the recipient.
492
+ let to = canonicalHandle(args.handle);
493
+ if (to && to !== canonicalHandle(me || '') && !to.endsWith('/claude')) {
494
+ try { to = (await invite.resolveRecipient(to)).handle; } catch (e) {}
495
+ }
496
+ const result = await deliver({ to: to || args.handle, message: args.message, replyTo: cleanId(args.reply_to) });
396
497
  // The thread has moved on: what they say next answers THIS.
397
- if (result.data && result.data.sent) { try { clearReturnBinding(args.handle); } catch (e) {} }
498
+ if (result.data && result.data.sent) { try { clearReturnBinding(to || args.handle); } catch (e) {} }
398
499
  return result;
399
500
  }
400
501
 
@@ -407,6 +508,7 @@ async function sendHandler(args) {
407
508
  // The approval was given as one account; it is not transferable to
408
509
  // whoever is signed in now (codex P1).
409
510
  if (d.from && d.from !== me) return { display: `Draft ${d.id} was prepared as @${d.from}; you are signed in as @${me}. Nothing sent — open a new draft as yourself.` };
511
+ if (d.status === 'held') return { display: heldAlready(d) };
410
512
  if (d.status === 'sent') return { display: `Draft ${d.id} was already sent to @${d.to} — not sending it twice.` };
411
513
  if (d.status === 'cancelled') return { display: `Draft ${d.id} was cancelled — nothing sent. Open a new draft if you want it back.` };
412
514
  if (!rev) return { display: `Send needs the rev shown in the preview of draft ${d.id} — open it with vibe_prepare and send with that rev. Nothing sent.` };
@@ -417,6 +519,9 @@ async function sendHandler(args) {
417
519
  // so a later definite refusal cannot erase it.
418
520
  if (!reconcileAbandoned(d)) return { display: `Draft ${d.id} is already being sent — not sending it twice.` };
419
521
  }
522
+ // POST /api/invites has no idempotency key: an unconfirmed Keep is never
523
+ // retried, because a retry could create a second invitation.
524
+ if (d.held && d.status === 'unknown') return { display: heldUnknown(d) };
420
525
  if (d.status === 'unknown' && !transportDedupes()) {
421
526
  // Without server-side deduplication a retry could deliver twice; the
422
527
  // honest options are to cancel (with the warning) or write anew.
@@ -425,11 +530,12 @@ async function sendHandler(args) {
425
530
  d.status = 'sending'; d.claimedAt = Date.now(); d.claimedBy = process.pid;
426
531
  d.idempotencyKey = sendKey(d);
427
532
  const message = compose(d).trim();
428
- d.approvedSha256 = approvedDigest(d.to, message);
429
- return { snapshot: { id: d.id, to: d.to, body: d.body, refs: d.refs, context: d.context, replyTo: d.replyTo || null, message, key: d.idempotencyKey, approvedSha256: d.approvedSha256 } };
533
+ d.approvedSha256 = d.held ? heldDigest(message) : approvedDigest(d.to, message);
534
+ return { snapshot: { id: d.id, to: d.to, body: d.body, refs: d.refs, context: d.context, replyTo: d.replyTo || null, message, key: d.idempotencyKey, approvedSha256: d.approvedSha256, held: Boolean(d.held) } };
430
535
  });
431
536
  if (claim.display) return claim;
432
537
  const s = claim.snapshot;
538
+ if (s.held) return keepHeld(s, me);
433
539
 
434
540
  // 2. Deliver, outside the lock.
435
541
  let result;
@@ -470,6 +576,115 @@ async function sendHandler(args) {
470
576
  return result;
471
577
  }
472
578
 
579
+ // ── Keep: create the invitation that holds the approved message ───────────────
580
+
581
+ /**
582
+ * One fix per refusal, built from the status and the platform's stable error
583
+ * token only — server prose is never shown. Every refusal here is definite:
584
+ * it comes from a reply the platform sent before anything was minted.
585
+ */
586
+ function heldRefusal(r) {
587
+ const status = r && r.statusCode;
588
+ const nothing = 'Nothing was kept.';
589
+ if (status === 401) return `${nothing} /vibe does not see you signed in. Run \`npx slashvibe-mcp setup\` in a terminal to sign in, then keep it again.`;
590
+ if (status === 403) return `${nothing} Holding a message for someone needs a fresh sign-in on this machine. Run \`npx slashvibe-mcp setup\` in a terminal, then keep it again.`;
591
+ if (status === 400 && r.error === 'No invite codes remaining') return `${nothing} You already have 3 unused invitations, the most /vibe allows at once. Pass on one of the links you already have; a slot opens when someone signs in with one or it expires after ${HELD_DAYS} days.`;
592
+ if (status === 400 && typeof r.error === 'string' && /^first_thought is \d+ chars/.test(r.error)) return `${nothing} The message is over the 2000-char limit. Edit it shorter, then keep it again.`;
593
+ if (status === 409 && r.error === 'approval_mismatch') return `${nothing} What /vibe would store is not what you approved. Open the draft again with vibe_prepare and approve what it shows now.`;
594
+ return `${nothing} /vibe refused the invitation${status ? ` (HTTP ${status})` : ''}. Try again in a moment.`;
595
+ }
596
+
597
+ async function keepHeld(s, me) {
598
+ let outcome; // { held: true, code, expiresAt } | { definite: bool, display, cancel? }
599
+ try {
600
+ outcome = await createHeld(s);
601
+ } catch (e) {
602
+ outcome = { definite: false, display: 'The invitation could not be confirmed — it may or may not have been created.' };
603
+ }
604
+
605
+ const at = Date.now();
606
+ const joinUrl = outcome.held ? `https://www.slashvibe.dev/join/${outcome.code}` : null;
607
+ transact(drafts => {
608
+ const cur = drafts.find(x => x.id === s.id);
609
+ if (!cur) return;
610
+ delete cur.claimedAt; delete cur.claimedBy;
611
+ if (outcome.held) { cur.status = 'held'; cur.heldAt = at; cur.joinUrl = joinUrl; cur.expiresAt = outcome.expiresAt || null; return; }
612
+ if (!outcome.definite) { cur.unconfirmed = true; cur.status = 'unknown'; return; }
613
+ cur.status = outcome.cancel ? 'cancelled' : (cur.unconfirmed ? 'unknown' : 'previewed');
614
+ });
615
+
616
+ if (!outcome.held) {
617
+ const tail = outcome.definite ? '' : `\n\n_Draft ${s.id} is kept as unconfirmed. Keeping it again could create a second invitation, so the only choice left is Cancel._`;
618
+ return { display: `${outcome.display}${tail}`, data: { sent: false, held: false, definite: Boolean(outcome.definite) } };
619
+ }
620
+
621
+ const until = outcome.expiresAt ? `, until ${outcome.expiresAt}` : '';
622
+ const pass = invite.line(me);
623
+ const lines = [
624
+ `Held for @${s.to}. /vibe created the invitation.`,
625
+ `**Join link:** ${joinUrl}`,
626
+ ];
627
+ if (pass) lines.push(`**Pass on with it:** ${pass.command}`);
628
+ lines.push(`Your message is kept for the GitHub account ${s.to} for ${HELD_DAYS} days${until}. It arrives as your first message when they sign in to /vibe with that account; nothing reaches them before then.`);
629
+
630
+ // Writing to someone is what lets their answer reach you mid-work. Their
631
+ // handle does not exist yet: it will be their GitHub login with '-' folded
632
+ // to '_' (the platform's first-sign-in rule), so that is the one marked.
633
+ try { require('../reach').know(handleForLogin(s.to)); } catch (e) {}
634
+
635
+ return {
636
+ display: lines.join('\n'),
637
+ data: { sent: false, held: true, definite: true, for_github: s.to, join_url: joinUrl, expires_at: outcome.expiresAt || null },
638
+ };
639
+ }
640
+
641
+ /**
642
+ * dry_run first (side-effect free: the platform checks sign-in, the unused-
643
+ * code cap and the thought before it answers), confirm its digest is the one
644
+ * computed from the approved snapshot, then create with approved_sha256 so
645
+ * the platform refuses anything other than what was previewed.
646
+ */
647
+ async function createHeld(s) {
648
+ if (typeof store.createInvite !== 'function') return { definite: true, display: 'Nothing was kept. Holding a message for someone needs the /vibe service; this session is in local mode.' };
649
+ const thought = s.message;
650
+ if (thought.length > 2000) return { definite: true, display: `Nothing was kept. The message is ${thought.length} chars and the limit is 2000. Edit it shorter, then keep it again.` };
651
+ if (thought.includes('\u0000') || LONE_SURROGATE.test(thought)) return { definite: true, display: 'Nothing was kept. The message has a character /vibe cannot keep. Edit it, then keep it again.' };
652
+
653
+ // They may have joined since the preview: then this is a message, not an invitation.
654
+ const who = await invite.lookup(s.to).catch(() => ({ found: null }));
655
+ if (who.found === true) return { definite: true, cancel: true, display: `Nothing was kept. @${s.to} joined /vibe since you saw the preview, so this draft is cancelled. Prepare it again and it goes to them directly.` };
656
+
657
+ const body = { first_thought: thought, for_github: s.to };
658
+ const dry = await store.createInvite({ ...body, dry_run: true });
659
+ if (!dry || dry.success !== true) {
660
+ if (dry && dry.statusCode) return { definite: true, display: heldRefusal(dry) };
661
+ return { definite: true, display: 'Nothing was kept. /vibe could not be reached. Try again in a moment.' };
662
+ }
663
+ const serverSha = dry.approval && typeof dry.approval.sha256 === 'string' ? dry.approval.sha256 : null;
664
+ if (dry.dry_run !== true || dry.carries_thought !== true || dry.named_for !== s.to || serverSha !== s.approvedSha256) {
665
+ return { definite: true, display: heldRefusal({ statusCode: 409, error: 'approval_mismatch' }) };
666
+ }
667
+
668
+ const made = await store.createInvite({ ...body, approved_sha256: s.approvedSha256 });
669
+ if (made && made.success === true) {
670
+ // Created only on the served truth: a code of the platform's shape, named
671
+ // for this login, carrying the thought. Anything else may have minted
672
+ // something, so it is unconfirmed, never success.
673
+ const code = typeof made.code === 'string' ? made.code : '';
674
+ if (INVITE_CODE.test(code) && made.carries_thought === true && made.named_for === s.to) {
675
+ const t = Date.parse(made.expires_at);
676
+ return { held: true, code, expiresAt: Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : null };
677
+ }
678
+ return { definite: false, display: '/vibe answered, but not with an invitation held for this account. It may or may not have been created.' };
679
+ }
680
+ // A reply with a 4xx status, or a 503 (both of its paths say nothing was
681
+ // saved), was decided before anything was minted. No reply, or a crash,
682
+ // leaves it open.
683
+ const st = made && made.statusCode;
684
+ if (st && (st < 500 || st === 503)) return { definite: true, display: heldRefusal(made) };
685
+ return { definite: false, display: 'The invitation could not be confirmed — it may or may not have been created.' };
686
+ }
687
+
473
688
  module.exports = {
474
689
  vibe_prepare: { definition: draftDefinition, handler: draftHandler },
475
690
  vibe_send: { definition: sendDefinition, handler: sendHandler },
package/tools/line.js CHANGED
@@ -17,6 +17,7 @@
17
17
 
18
18
  const fs = require('fs');
19
19
  const path = require('path');
20
+ const crypto = require('crypto');
20
21
  const config = require('../config');
21
22
  const store = require('../store');
22
23
  const line = require('../line');
@@ -137,6 +138,13 @@ function arrived(id) {
137
138
  } catch { return null; }
138
139
  }
139
140
 
141
+ /**
142
+ * One idempotency key per (this handle, question). Same family and bounds as
143
+ * the draft keys (`draft-<id>-<hash>`): short, ASCII, well under the service's
144
+ * 200-character limit whatever the id looks like.
145
+ */
146
+ const answerKey = (me, id) => `answer-${crypto.createHash('sha1').update(`${me}\n${id}`).digest('hex').slice(0, 20)}`;
147
+
140
148
  async function answerHandler(args = {}) {
141
149
  const initCheck = requireInit();
142
150
  if (initCheck) return initCheck;
@@ -154,7 +162,11 @@ async function answerHandler(args = {}) {
154
162
  if (line.isAgentAnswer(row.text)) return refuse('Nothing sent. That message is itself an agent\'s answer; answers are not answered unattended. If something real remains to say, prepare it with vibe_prepare.');
155
163
  if (line.receipts().some((r) => r.kind === 'answered' && r.answers === id)) return refuse('Nothing sent. That question was already answered from this machine.');
156
164
 
157
- const sent = await deliver({ to, message: message + line.ANSWERED(me), replyTo: id, origin: 'agent_line' });
165
+ // The receipt check above is local and not atomic with the send: two answers
166
+ // to one question in flight together would both pass it. The key is the same
167
+ // for any answer from this handle to this question, so the service stores at
168
+ // most one (a second, different answer is refused as an idempotency conflict).
169
+ const sent = await deliver({ to, message: message + line.ANSWERED(me), replyTo: id, origin: 'agent_line', idempotencyKey: answerKey(me, id) });
158
170
  if (!sent.data || !sent.data.sent) return sent;
159
171
  line.record({ kind: 'answered', with: to, id: sent.data.message_id, answers: id, asked: line.stripMark(row.text || ''), said: message });
160
172
  // The person is shown the answer by the hook, not by the agent's memory.
@@ -168,4 +180,5 @@ async function answerHandler(args = {}) {
168
180
  module.exports = {
169
181
  vibe_ask: { definition: askDefinition, handler: askHandler },
170
182
  vibe_answer: { definition: answerDefinition, handler: answerHandler },
183
+ answerKey,
171
184
  };