@cohortapp/agent-sdk 2.18.25 → 2.18.28

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.
@@ -463,6 +463,13 @@ const STATUS_NOTICE_PATTERNS = Object.freeze([
463
463
  /^the work (on ".+?"|you asked for)\s+(broke|didn'?t|never|has)\b/i,
464
464
  // The board-status shape that closed the loop on itself.
465
465
  /^here'?s where i got to:/i,
466
+ // composeRefusedSend — the notice that replaced "my fault" for the case where
467
+ // a send was actually TRIED and stopped. Registered here in the same breath as
468
+ // the composer, because the 142-of-188 amplification on 2026-09-30 happened
469
+ // precisely when an emitted notice was not recognisable to the seat receiving
470
+ // it: the gate missed, the notice was dispatched as an ask, and the answering
471
+ // seat's own rescue fired back.
472
+ /^couldn'?t get this out to you\s*[\u2014\u2013-]\s*the send was blocked\b/i,
466
473
  ]);
467
474
 
468
475
  /**
@@ -485,62 +492,78 @@ export function isAgentStatusNotice(body) {
485
492
  }
486
493
 
487
494
  /**
488
- * A SESSION SAYING IT HAS ALREADY ANSWERED THIS ONE.
495
+ * A SESSION STATING NO REPLY WAS OWED.
489
496
  *
490
497
  * The silent-success rescue (`assurance.settleSession`) exists to hand a waiting
491
498
  * requester the result their session produced but failed to send. It reads
492
499
  * "exited 0 having sent nothing" as exactly one state — the answer got stuck on
493
- * the way out — when there are two. The second is a session that read the item,
494
- * recognised it as something it had ALREADY replied to, and declined to reply
495
- * twice.
496
- *
497
- * Published, that second state is nonsense in the room. Measured, 2026-09-30
498
- * 18:21:49Z, one seat into a shared engineering channel:
499
- *
500
- * Here's where I got to:
501
- * Archived — this is a duplicate delivery of the same audit I already
502
- * responded to in-channel this session. Logged to
503
- * `logs/audit/2026-09-30-actions.jsonl`, no second response sent.
504
- *
505
- * Every word was true. The seat HAD answered, and declining to answer twice is
506
- * the owner's standing instruction ("sometimes a reply isn't needed"). The
507
- * rescue overrode that judgement and posted the reasoning, addressed to nobody,
508
- * citing a path no colleague can open.
509
- *
510
- * WHY NOT SIMPLY "THE SESSION SAID IT SENT NOTHING". That was this function's
511
- * first cut and it was wrong — three existing tests caught it, which is what
512
- * they are for. "Nothing was sent." is the marker for BOTH states: the live
513
- * sighting that created the rescue in the first place is a session whose final
514
- * text read "I reviewed the three failing checks and pushed fixes for two. The
515
- * third needs a decision from you. Nothing was sent." There the human is owed
516
- * the result and suppressing it loses a decision they must make. The sentence
517
- * does not separate the states; ALREADY-ANSWERED does, because it is the only
518
- * one of the two in which the ask is genuinely discharged.
519
- *
520
- * Deliberately NOT matched: "no action needed", "nothing to do", "already
521
- * handled". Those describe the WORK, not the REPLY — a session that says the
500
+ * the way out. There are two, and the second is a session that read the item,
501
+ * judged that nothing was owed in reply, and said so.
502
+ *
503
+ * Published, that second state posts a seat's own triage reasoning into a room,
504
+ * addressed to nobody. Measured over 48h to 2026-10-01: 40 such posts across
505
+ * SEVEN seats, in shared channels, all wearing the rescue's own wrapper.
506
+ *
507
+ * THE TEST IS AN OBLIGATION CLAIM, NOT A DELIVERY CLAIM, and the distinction is
508
+ * the whole design:
509
+ *
510
+ * "no reply owed" / "no response needed" / "it asks nothing of me"
511
+ * → a judgement that nothing is outstanding. Withhold.
512
+ * "Nothing was sent." / "I didn't reply."
513
+ * → a report that delivery did not happen, which is ALSO what a stuck
514
+ * answer says. Narrate.
515
+ *
516
+ * That second line is not hypothetical. The live sighting that created this
517
+ * rescue is a session whose final text read "I reviewed the three failing checks
518
+ * and pushed fixes for two. The third needs a decision from you. Nothing was
519
+ * sent." Keying on the delivery sentence suppresses it and loses a decision a
520
+ * person has to make — three existing tests in `assurance.test.mjs` pin exactly
521
+ * that, and they killed an earlier, broader cut of this function.
522
+ *
523
+ * MEASURED, not fitted. Against the 60-message production corpus these six
524
+ * patterns withhold 20 and produce zero false positives on the must-narrate set.
525
+ * Two further candidates ("it only confirms…", "closes the thread") were tried
526
+ * and DROPPED: between them they added one single match, which is curve-fitting
527
+ * to a corpus rather than naming a property.
528
+ *
529
+ * DELIBERATELY PARTIAL. The remaining posts in that corpus are genuinely mixed —
530
+ * some are real answers the rescue is the only route for ("Ethan, gate (2) was
531
+ * for #433's window… your read is right"), others are bare dispositions
532
+ * ("Filed.", "Queued."). No text test separates those two reliably, so this
533
+ * function does not try. Closing the rest is a structural question — whether the
534
+ * rescue should narrate into a CHANNEL at all, where there is no single waiting
535
+ * person — and that is an owner's call, not a regex's.
536
+ *
537
+ * NOT matched, on purpose: "no action needed", "nothing to do", "already
538
+ * handled". Those describe the WORK, not the REPLY, and a session that says the
522
539
  * work needs nothing may still owe the asker that sentence.
523
540
  */
524
- const ALREADY_ANSWERED_PATTERNS = Object.freeze([
541
+ const NO_REPLY_OWED_PATTERNS = Object.freeze([
542
+ /\bno (?:reply|response|answer)\b[^.!?]{0,40}\b(?:owed|needed|required|necessary|warranted|due)\b/i,
543
+ /\b(?:none|nothing) (?:is |was )?owed\b/i,
544
+ /\bnothing (?:needs|needed|requires|required) (?:an? )?(?:answer|reply|response)\b/i,
545
+ // Bare \b, not "nothing of me" — the corpus happened to continue the clause
546
+ // every time ("asked nothing and confirmed…"), so a trailing-space variant
547
+ // passed against it while failing on "asked nothing." at a sentence end. A
548
+ // pattern that only works because the sample never ended there is a latent
549
+ // miss, and redacting a fixture for the identity check is what surfaced it.
550
+ /\b(?:asked|asks) nothing\b/i,
525
551
  /\balready (?:responded|replied|answered)\b/i,
526
552
  /\bduplicate (?:delivery|copy|of the same|of an?)\b/i,
527
- /\b(?:responded|replied|answered) to (?:this|it|the same) (?:already|earlier|in[- ]channel)\b/i,
528
- /\bsame (?:item|message|request|ask) (?:i|we) (?:already |have already )?(?:answered|replied to|responded to)\b/i,
529
553
  ]);
530
554
 
531
555
  /**
532
- * Does this session's final text state that it had ALREADY replied to this
533
- * item, so the ask is discharged and a rescue would be a second voice?
556
+ * Does this session's final text state that no reply was owed, so a rescue would
557
+ * be publishing its reasoning rather than delivering an answer?
534
558
  *
535
- * Judged over the WHOLE text, not per paragraph: the statement is routinely a
536
- * mid-sentence clause ("…duplicate delivery of the same audit I already
537
- * responded to in-channel this session.").
559
+ * Judged over the WHOLE text: the claim is routinely a trailing clause after the
560
+ * reasoning ("…Logged and archived — no reply owed.").
538
561
  *
539
562
  * @param {unknown} finalText the session's own end-of-turn text
540
563
  * @returns {boolean}
541
564
  */
542
- export function isAlreadyAnsweredElsewhere(finalText) {
565
+ export function statesNoReplyOwed(finalText) {
543
566
  const t = String(finalText == null ? "" : finalText);
544
567
  if (!t.trim()) return false;
545
- return ALREADY_ANSWERED_PATTERNS.some((re) => re.test(t));
568
+ return NO_REPLY_OWED_PATTERNS.some((re) => re.test(t));
546
569
  }
@@ -32,6 +32,15 @@
32
32
  import { appendFileSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync } from "fs";
33
33
  import { join } from "path";
34
34
 
35
+ /**
36
+ * The receipt kind for a send that DID NOT HAPPEN.
37
+ *
38
+ * Kept distinct from every delivery kind and listed in `NON_ANSWER_KINDS`, so a
39
+ * no-send row can live in the same append-only ledger as a delivery without any
40
+ * reader ever mistaking one for the other.
41
+ */
42
+ export const NO_SEND_KIND = "no-send";
43
+
35
44
  /** Receipts older than this are irrelevant to any live obligation. */
36
45
  const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
37
46
 
@@ -225,7 +234,15 @@ export function spokeSince(q = {}) {
225
234
  * information about the MACHINE, not about the ask. `plan` is the plan-tier
226
235
  * interim.
227
236
  */
228
- export const NON_ANSWER_KINDS = Object.freeze(["ack", "progress", "notice", "failure", "plan"]);
237
+ export const NON_ANSWER_KINDS = Object.freeze([
238
+ "ack", "progress", "notice", "failure", "plan",
239
+ // A send that did NOT happen. `no-send` rows are written by `recordNoSend`
240
+ // and must never discharge a debt as answered — the whole point of them is to
241
+ // say why the human heard nothing. They are excluded here so a refusal can be
242
+ // recorded in the same ledger as a delivery without ever being mistaken for
243
+ // one; `noSendFor` is the reader that actually consumes them.
244
+ NO_SEND_KIND,
245
+ ]);
229
246
 
230
247
  export function spokeFor(q = {}) {
231
248
  const rec = q.obligation || {};
@@ -254,6 +271,148 @@ export function spokeFor(q = {}) {
254
271
  return { heard: true, basis: "sole-debt-in-room" };
255
272
  }
256
273
 
274
+ /**
275
+ * Why a reply that was owed never reached anyone. Exactly two values, because
276
+ * the difference between them is the difference between a bug and a decision:
277
+ *
278
+ * "refused" — something tried to send and was stopped: the outbound gate,
279
+ * a transport error, an ACL, a stale MCP server. The work is
280
+ * done and the human has nothing. This is a FAULT, and it is
281
+ * the one the recovery notice should name out loud.
282
+ * "declined" — nothing tried to send, because nothing was owed: the
283
+ * classifier archived it, the ask was not addressed here and
284
+ * asked nothing, the flurry's first message already answered.
285
+ * This is the design working (see `first-reply.firstReplyShape`,
286
+ * and `2.16.0 — silence is the default`).
287
+ *
288
+ * @typedef {"refused"|"declined"} NoSendDecision
289
+ */
290
+
291
+ /**
292
+ * Record that a reply did not go out, and why.
293
+ *
294
+ * ── WHY THIS EXISTS ──────────────────────────────────────────────────────────
295
+ *
296
+ * Until now the ONLY evidence this ledger carried was the positive one: a
297
+ * delivery happened. `spokeFor` therefore answers "did the human hear from us"
298
+ * and nothing else, and `assurance.settleSession` reads a `false` from it as
299
+ * "the session finished and its reply never sent — apologise and dump the
300
+ * result into the room".
301
+ *
302
+ * Measured in production on 2026-09-30, that reading was wrong far more often
303
+ * than it was right. 188 recovery notices landed in the org in one day; of the
304
+ * seed notices sampled, every single one carried the session's own words saying
305
+ * it had decided NOT to reply — "I marked it processed and sent no reply, since
306
+ * it closes the thread", "Logged and archived — no response needed", "no reply
307
+ * owed". Nothing had failed. The absence of a delivery receipt was being read
308
+ * as a failed send when it was a deliberate silence, and 59% of two days' worth
309
+ * of notices said so in their own body text.
310
+ *
311
+ * The absence of evidence cannot distinguish those two, and no amount of
312
+ * cleverness downstream will make it. So the decision is recorded positively,
313
+ * by whoever made it, at the moment it is made — a refusal by the thing that
314
+ * refused, a decline by the thing that decided. Then `heard === false` stops
315
+ * being one undifferentiated silence and becomes three distinguishable states:
316
+ * refused (say what stopped it, and retry if retry is sensible), declined
317
+ * (close quietly, say nothing), or genuinely unexplained (the only case the
318
+ * "my fault" notice was ever right about).
319
+ *
320
+ * FAIL-OPEN and never throws, exactly like `recordOutbound`: bookkeeping must
321
+ * not be able to break — or, here, to block — a send.
322
+ *
323
+ * @param {object} rec
324
+ * @param {NoSendDecision} rec.decision
325
+ * @param {string} rec.channel the room the reply would have gone to
326
+ * @param {string} [rec.service]
327
+ * @param {string} [rec.code] machine code, when there is one (FORBIDDEN_SCOPE, …)
328
+ * @param {string} [rec.reason] short human cause; NEVER the message body
329
+ * @param {string} [rec.surface] which plane refused: "daemon" | "session" | …
330
+ * @param {boolean} [rec.permanent] true when retrying changes nothing
331
+ * @param {string} [rec.obligationKey]
332
+ * @param {string} [rec.sessionId]
333
+ * @param {object} [rec.env]
334
+ * @param {string} [rec.agentRoot]
335
+ * @param {number} [rec.now]
336
+ * @returns {boolean} true if the row was durably appended
337
+ */
338
+ export function recordNoSend(rec = {}) {
339
+ try {
340
+ const ch = channelKey(rec.channel);
341
+ if (!ch) return false;
342
+ const decision = rec.decision === "declined" ? "declined" : "refused";
343
+ const now = Number.isFinite(rec.now) ? rec.now : Date.now();
344
+ const ambient = ambientAttribution(rec.env || process.env);
345
+ const line = JSON.stringify({
346
+ ts: new Date(now).toISOString(),
347
+ at: now,
348
+ service: rec.service || "unknown",
349
+ channel: ch,
350
+ kind: NO_SEND_KIND,
351
+ decision,
352
+ code: rec.code ? String(rec.code) : null,
353
+ // Bounded on purpose. A reason is a cause, not a transcript, and this
354
+ // ledger is read by a daemon deciding one sentence — an unbounded string
355
+ // here is how a whole session result ends up quoted back into a room.
356
+ reason: rec.reason ? String(rec.reason).slice(0, 300) : null,
357
+ surface: rec.surface || null,
358
+ permanent: rec.permanent === true,
359
+ obligationKey: rec.obligationKey || ambient.obligationKey,
360
+ sessionId: rec.sessionId || ambient.sessionId,
361
+ });
362
+ appendFileSync(dayFile(rec.agentRoot, now), line + "\n");
363
+ return true;
364
+ } catch {
365
+ // Fail-open: a send must never be broken by its own bookkeeping.
366
+ return false;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Why did THIS obligation produce no reply?
372
+ *
373
+ * The attribution ladder is deliberately STRICTER than `spokeFor`'s, and in the
374
+ * opposite direction. `spokeFor` may fall back to an unattributed receipt in an
375
+ * unambiguous room, because its bias is "one redundant message beats silence".
376
+ * Here the bias inverts: a no-send row is used to SUPPRESS or REWORD what the
377
+ * human is told, so borrowing another debt's row would silence a real fault.
378
+ * Only rows stamped with this obligation's key or this obligation's session
379
+ * count. Anything else returns `null`, and the caller keeps its old behaviour.
380
+ *
381
+ * When several rows match, a `refused` beats a `declined`: a turn that decided
382
+ * nothing was owed AND hit a refusal has a fault in it, and the fault is the
383
+ * thing worth saying.
384
+ *
385
+ * @param {object} q
386
+ * @param {object} q.obligation {key, channel, openedAt, sessionId}
387
+ * @param {number} [q.now]
388
+ * @param {string} [q.agentRoot]
389
+ * @returns {{decision:NoSendDecision, code:string|null, reason:string|null, surface:string|null, permanent:boolean, at:number}|null}
390
+ */
391
+ export function noSendFor(q = {}) {
392
+ const rec = q.obligation || {};
393
+ const ch = channelKey(rec.channel);
394
+ const since = Number.isFinite(rec.openedAt) ? rec.openedAt : q.now;
395
+ if (!ch || !Number.isFinite(since)) return null;
396
+ const rows = readReceiptsSince(since, q).filter(
397
+ (r) =>
398
+ r.kind === NO_SEND_KIND &&
399
+ r.channel === ch &&
400
+ ((rec.key && r.obligationKey === rec.key) ||
401
+ (rec.sessionId && r.sessionId && r.sessionId === rec.sessionId)),
402
+ );
403
+ if (!rows.length) return null;
404
+ const refused = rows.filter((r) => r.decision === "refused");
405
+ const pick = (refused.length ? refused : rows).at(-1);
406
+ return {
407
+ decision: pick.decision === "declined" ? "declined" : "refused",
408
+ code: pick.code || null,
409
+ reason: pick.reason || null,
410
+ surface: pick.surface || null,
411
+ permanent: pick.permanent === true,
412
+ at: pick.at,
413
+ };
414
+ }
415
+
257
416
  /** Drop receipt day-files past retention. Best-effort; returns files removed. */
258
417
  export function pruneReceipts(o = {}) {
259
418
  let removed = 0;
@@ -287,12 +446,34 @@ export function pruneReceipts(o = {}) {
287
446
  * the bug it fixes.
288
447
  */
289
448
  export function runReceiptCli(argv = []) {
290
- if (argv[0] !== "record") return 0;
449
+ const verb = argv[0];
450
+ if (verb !== "record" && verb !== "no-send") return 0;
291
451
  const a = {};
292
452
  for (let i = 1; i < argv.length; i++) {
293
453
  const m = /^--([a-zA-Z-]+)$/.exec(argv[i]);
294
454
  if (m) a[m[1]] = argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[++i] : "1";
295
455
  }
456
+ // `no-send` is the same entry point for the opposite fact: a reply that was
457
+ // owed did not go out, and why. A spawned session reaches this module by no
458
+ // other route (the org MCP send tools are hard-blocked by a pre-tool hook and
459
+ // the mandated send lanes are bash/python/node scripts that cannot import
460
+ // it), so without the verb here a session's own account of why it stayed
461
+ // quiet can never cross back to the daemon that will speak for it.
462
+ if (verb === "no-send") {
463
+ recordNoSend({
464
+ decision: a.decision === "declined" ? "declined" : "refused",
465
+ service: a.service,
466
+ channel: a.channel,
467
+ code: a.code || undefined,
468
+ reason: a.reason || undefined,
469
+ surface: a.surface || "session",
470
+ permanent: a.permanent === "1" || a.permanent === "true",
471
+ obligationKey: a["obligation-key"] || undefined,
472
+ sessionId: a["session-id"] || undefined,
473
+ agentRoot: a["agent-root"] || undefined,
474
+ });
475
+ return 0;
476
+ }
296
477
  recordOutbound({
297
478
  service: a.service,
298
479
  channel: a.channel,
@@ -310,4 +491,4 @@ if (process.argv[1] && process.argv[1].endsWith("receipts.mjs")) {
310
491
  try { runReceiptCli(process.argv.slice(2)); } catch { /* never fail a send */ }
311
492
  }
312
493
 
313
- export default { recordOutbound, readReceiptsSince, spokeSince, spokeFor, channelKey, pruneReceipts };
494
+ export default { recordOutbound, recordNoSend, noSendFor, runReceiptCli, readReceiptsSince, spokeSince, spokeFor, channelKey, pruneReceipts };
@@ -68,6 +68,9 @@ import {
68
68
  import { join } from "node:path";
69
69
  import { writeFileAtomic, appendJsonl } from "../fs-atomic.mjs";
70
70
  import { isRetiredFirstReply } from "../assurance/first-reply.mjs";
71
+ // The no-send ledger. `receipts.mjs` imports only node:fs and node:path, so this
72
+ // is not a cycle; `recordNoSend` is fail-open and never throws.
73
+ import { recordNoSend } from "./receipts.mjs";
71
74
 
72
75
  /* ─────────────────────────── policy file locations ───────────────────────── */
73
76
 
@@ -961,6 +964,36 @@ export function extractHookRecipient(payload) {
961
964
  return v === undefined ? "" : shellCaptured(jqString(v));
962
965
  }
963
966
 
967
+ /**
968
+ * The room a REFUSED hook payload would have gone to, for the no-send ledger.
969
+ *
970
+ * ── WHY THIS IS NOT `extractHookRecipient` ───────────────────────────────────
971
+ *
972
+ * `extractHookRecipient` is a PORT of the frozen shell hook and is pinned
973
+ * verbatim by `scripts/hooks/pre-send-audit.parity.test.mjs`. It reads `to`,
974
+ * `recipient`, `channel`, `email` and `thread_ts` — and NOT `channelId`, which is
975
+ * the field `mcp__cohort__messaging_send` actually carries. Adding it there would
976
+ * silently activate the recipient-allowlist limb (`if (recipient && allowlist)`)
977
+ * for every org message, changing verdicts that the parity contract pins. That is
978
+ * a separate decision with its own blast radius, and it is not this one's to make.
979
+ *
980
+ * So the ledger gets its own resolver. It is used for ONE purpose — keying a
981
+ * no-send row so `noSendFor` can find it — and it cannot change any verdict,
982
+ * because nothing that decides `allow` reads it.
983
+ *
984
+ * @param {object} payload parsed PreToolUse JSON
985
+ * @returns {string} "" when no room can be named
986
+ */
987
+ export function hookNoSendChannel(payload) {
988
+ const named = extractHookRecipient(payload);
989
+ if (named) return named;
990
+ const ti = payload && payload.tool_input;
991
+ const t = isPlainObject(ti) ? ti : {};
992
+ const chain = [t.channelId, t.channel_id, t.threadId, t.thread_id, t.memberId, t.member_id];
993
+ const v = chain.find(jqPresent);
994
+ return v === undefined ? "" : shellCaptured(jqString(v));
995
+ }
996
+
964
997
  /**
965
998
  * The agent's first name for the `<first>-main` check, resolved as the hook
966
999
  * did: MAESTRO_AGENT_FIRST, else the first candidate file (AGENT_ROOT and
@@ -1200,7 +1233,7 @@ export function runPreSendHook(o = {}) {
1200
1233
  * @param {Parameters<typeof runPreSendHook>[0]} o
1201
1234
  * @returns {{ok:false, result:{code:2, stdout:string, stderr:string}} | {ok:true, commit:() => {code:0|2, stdout:string, stderr:string}}}
1202
1235
  */
1203
- export function preparePreSendHook({ channel, stdin, env = process.env, now = new Date(), fs: injected = {} } = {}) {
1236
+ export function preparePreSendHook({ channel, stdin, env = process.env, now = new Date(), fs: injected = {}, recordNoSendImpl = null } = {}) {
1204
1237
  const fsx = {
1205
1238
  readFileSync: injected.readFileSync || nodeReadFileSync,
1206
1239
  statSync: injected.statSync || nodeStatSync,
@@ -1219,7 +1252,63 @@ export function preparePreSendHook({ channel, stdin, env = process.env, now = ne
1219
1252
  // built as the shell built it (e.g. "/config/agent.json" when AGENT_ROOT is unset).
1220
1253
  const v = (k) => (typeof e[k] === "string" ? e[k] : "");
1221
1254
 
1222
- const refuse = (reason) => ({ ok: false, result: deny(reason) });
1255
+ // ── A HOOK DENIAL IS A REFUSED SEND, AND IT WAS THE INVISIBLE ONE ─────────
1256
+ //
1257
+ // This function runs in the PreToolUse hook, which means it decides BEFORE any
1258
+ // application code. When it denies, `executeOrgTool` never runs — so the
1259
+ // no-send row that path writes is never written, the tool call never happened
1260
+ // as far as the ledger is concerned, and the daemon that spawned the session
1261
+ // later sees "exit 0, no delivery receipt" and says "Finished this but didn't
1262
+ // get a reply out to you — my fault".
1263
+ //
1264
+ // That is not a hypothetical: it is the plane the production evidence names.
1265
+ // Four notices in the 2026-09-29/30 window report a blocked Cohort send lane
1266
+ // in prose (cmun731th2fvpm9013jihfgob 09-29T11:39:52Z, cmunr4biu4djim901asuqb1i7
1267
+ // 09-30T06:55Z, latest 09-30T16:04:35Z) — narrating it into a room was the only
1268
+ // reporting channel a blocked session had. Recording the denial here is what
1269
+ // gives it a real one, and `assurance.settleSession` then names the cause
1270
+ // instead of apologising for a silence nobody chose.
1271
+ //
1272
+ // FAIL-OPEN and never throws: a recording fault must not turn a clean denial
1273
+ // into a crash, and must never turn one into a PASS.
1274
+ const noteRefusal = (reason) => {
1275
+ try {
1276
+ const record = recordNoSendImpl || recordNoSend;
1277
+ let recipient = null;
1278
+ try {
1279
+ recipient = hookNoSendChannel(JSON.parse(shellCaptured(stdin == null ? "" : stdin)));
1280
+ } catch { recipient = null; }
1281
+ if (!recipient) return; // nothing to key the row to; see noSendFor's ladder
1282
+ // No agent root, no write. `recordNoSend` falls back to `process.cwd()`,
1283
+ // and a hook runs with whatever cwd the harness gave it — writing a
1284
+ // `state/comms/` tree into a random directory is worse than not recording:
1285
+ // nothing reads it and it is indistinguishable from a checkout's own state.
1286
+ const root = v("AGENT_ROOT") || v("AGENT_DIR");
1287
+ if (!root) return;
1288
+ record({
1289
+ decision: "refused",
1290
+ service: channel || "unknown",
1291
+ channel: recipient,
1292
+ code: "HOOK_BLOCKED",
1293
+ reason,
1294
+ // Named distinctly from "session": a refusal HERE means the tool never
1295
+ // ran, so an operator reading the ledger can tell "the gate stopped it"
1296
+ // from "the server stopped it".
1297
+ surface: "pre-send-hook",
1298
+ // A denial here is a content or cap verdict on THIS body — reword it, or
1299
+ // wait out the cap — so another attempt is meaningful. Calling it
1300
+ // permanent is how a fixable refusal becomes a final apology.
1301
+ permanent: false,
1302
+ env: e,
1303
+ agentRoot: root,
1304
+ });
1305
+ } catch { /* bookkeeping must never change a verdict */ }
1306
+ };
1307
+
1308
+ const refuse = (reason) => {
1309
+ noteRefusal(reason);
1310
+ return { ok: false, result: deny(reason) };
1311
+ };
1223
1312
  if (!channel) return refuse(HOOK_CHANNEL_REQUIRED);
1224
1313
 
1225
1314
  const first = hookFirstName({
@@ -119,7 +119,7 @@ import {
119
119
  // in its own process; the receipt is the only way the daemon that spawned it can
120
120
  // later tell "the session answered" from "the session exited 0 and said
121
121
  // nothing". Fail-open by construction — recordOutbound never throws.
122
- import { recordOutbound } from "../comms/receipts.mjs";
122
+ import { recordNoSend, recordOutbound } from "../comms/receipts.mjs";
123
123
 
124
124
  /** Default org server origin when neither env nor config names one. */
125
125
  export const DEFAULT_COHORT_BASE = "https://os.cohortapp.com";
@@ -3369,6 +3369,38 @@ const HUMAN_FACING_TOOLS = {
3369
3369
  email_reply: (i) => i.to || i.threadId,
3370
3370
  };
3371
3371
 
3372
+ /**
3373
+ * The room a call to `name` would speak into, or `null` if `name` does not speak
3374
+ * to a person at all.
3375
+ *
3376
+ * ── WHY THIS IS A NAMED, EXPORTED FUNCTION RATHER THAN AN INLINE LOOKUP ──────
3377
+ *
3378
+ * Both halves of the ledger — the delivery receipt and the no-send row — are
3379
+ * gated on "is this a tool that talks to a human". The table above is the whole
3380
+ * of that decision, and a test that only exercises it through `executeOrgTool`
3381
+ * cannot actually pin it: the read tools it reaches for (`messaging_history`)
3382
+ * would resolve no channel even if the table were deleted, so the test passes
3383
+ * for the wrong reason and goes on passing after the filter it claims to pin is
3384
+ * gone. (Verified by deleting the filter: the behavioural test stayed green.)
3385
+ *
3386
+ * Exposing the predicate makes the distinction directly assertable — a READ tool
3387
+ * carrying the very same `{channelId}` input as a send must still resolve
3388
+ * `null` — so deleting the table is a test failure rather than a silent widening
3389
+ * of what gets recorded as an attempted send.
3390
+ *
3391
+ * @param {string} name org tool name
3392
+ * @param {object} [input]
3393
+ * @returns {string|null}
3394
+ */
3395
+ export function humanFacingChannel(name, input = {}) {
3396
+ const locate = Object.prototype.hasOwnProperty.call(HUMAN_FACING_TOOLS, name)
3397
+ ? HUMAN_FACING_TOOLS[name]
3398
+ : null;
3399
+ if (typeof locate !== "function") return null;
3400
+ const ch = locate(input || {});
3401
+ return ch ? String(ch) : null;
3402
+ }
3403
+
3372
3404
  /**
3373
3405
  * Execute an org tool and, when it was one that speaks to a person and it
3374
3406
  * succeeded, leave a delivery receipt.
@@ -3382,19 +3414,45 @@ const HUMAN_FACING_TOOLS = {
3382
3414
  export async function executeOrgTool(name, input = {}, o = {}) {
3383
3415
  const frame = await executeOrgToolInner(name, input, o);
3384
3416
  try {
3385
- const locate = HUMAN_FACING_TOOLS[name];
3386
- if (locate && frame && frame.ok) {
3387
- const channel = locate(input || {});
3388
- if (channel) {
3389
- recordOutbound({
3390
- service: name.startsWith("email") ? "gmail" : "cohort",
3391
- channel,
3392
- kind: "session",
3393
- via: name,
3394
- chars: typeof (input && input.body) === "string" ? input.body.length : null,
3395
- agentRoot: (o && o.agentRoot) || process.env.AGENT_ROOT || process.env.AGENT_DIR,
3396
- });
3397
- }
3417
+ const channel = humanFacingChannel(name, input);
3418
+ if (channel && frame && frame.ok) {
3419
+ recordOutbound({
3420
+ service: name.startsWith("email") ? "gmail" : "cohort",
3421
+ channel,
3422
+ kind: "session",
3423
+ via: name,
3424
+ chars: typeof (input && input.body) === "string" ? input.body.length : null,
3425
+ agentRoot: (o && o.agentRoot) || process.env.AGENT_ROOT || process.env.AGENT_DIR,
3426
+ });
3427
+ }
3428
+ // ── THE SYMMETRIC HALF, AND THE REASON IT WAS MISSING ────────────────────
3429
+ // A session's send is refused on this plane by returning an error frame:
3430
+ // the outbound gate (FORBIDDEN_SCOPE), hq declining, a stale long-lived MCP
3431
+ // server refusing to act. The session SEES that frame — it is the tool
3432
+ // result — but nothing durable is written, so the daemon that spawned the
3433
+ // session cannot see it at all. When the session then ends, the daemon
3434
+ // observes only "exit 0, no delivery receipt" and says "Finished this but
3435
+ // didn't get a reply out to you — my fault", which is both an apology for
3436
+ // the wrong thing and a refusal to name the one fact that would fix it.
3437
+ //
3438
+ // Recording the refusal next to the receipt, in the same ledger and keyed to
3439
+ // the same obligation, is what lets the notice say WHY — and lets a refusal
3440
+ // that is merely transient be retried instead of narrated.
3441
+ if (channel && frame && !frame.ok) {
3442
+ const err = frame.error || {};
3443
+ recordNoSend({
3444
+ decision: "refused",
3445
+ service: name.startsWith("email") ? "gmail" : "cohort",
3446
+ channel,
3447
+ code: err.code || null,
3448
+ reason: err.message || null,
3449
+ surface: "session",
3450
+ // Only a policy decision is knowably final here. Everything else — a
3451
+ // 5xx, a dropped socket, hq restarting — is worth another attempt, and
3452
+ // calling it permanent is how a recoverable send becomes an apology.
3453
+ permanent: err.code === "FORBIDDEN_SCOPE" || err.code === "NOT_FOUND",
3454
+ agentRoot: (o && o.agentRoot) || process.env.AGENT_ROOT || process.env.AGENT_DIR,
3455
+ });
3398
3456
  }
3399
3457
  } catch { /* never let a receipt break a send */ }
3400
3458
  return frame;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohortapp/agent-sdk",
3
- "version": "2.18.25",
3
+ "version": "2.18.28",
4
4
  "description": "Cohort Agent SDK — autonomous AI colleague runtime. Deploy senior AI colleagues on dedicated Mac minis, wired to the Cohort operating surface.",
5
5
  "type": "module",
6
6
  "bin": {