@cotal-ai/connector-core 0.133.13 → 0.135.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.
Files changed (45) hide show
  1. package/dist/agent.d.ts +71 -4
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +228 -33
  4. package/dist/agent.js.map +1 -1
  5. package/dist/briefing.d.ts +27 -0
  6. package/dist/briefing.d.ts.map +1 -0
  7. package/dist/briefing.js +58 -0
  8. package/dist/briefing.js.map +1 -0
  9. package/dist/config.d.ts +1 -1
  10. package/dist/config.d.ts.map +1 -1
  11. package/dist/config.js.map +1 -1
  12. package/dist/control.d.ts +3 -2
  13. package/dist/control.d.ts.map +1 -1
  14. package/dist/control.js +1 -1
  15. package/dist/control.js.map +1 -1
  16. package/dist/docs-bundle.bin +0 -0
  17. package/dist/docs-bundle.generated.d.ts +1 -1
  18. package/dist/docs-bundle.generated.d.ts.map +1 -1
  19. package/dist/docs-bundle.generated.js +13 -6
  20. package/dist/docs-bundle.generated.js.map +1 -1
  21. package/dist/docs-index.bin +0 -0
  22. package/dist/gateway.d.ts.map +1 -1
  23. package/dist/gateway.js +6 -2
  24. package/dist/gateway.js.map +1 -1
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/manager-call.d.ts +7 -1
  30. package/dist/manager-call.d.ts.map +1 -1
  31. package/dist/manager-call.js +39 -1
  32. package/dist/manager-call.js.map +1 -1
  33. package/dist/once.d.ts +53 -0
  34. package/dist/once.d.ts.map +1 -0
  35. package/dist/once.js +126 -0
  36. package/dist/once.js.map +1 -0
  37. package/dist/orientation.d.ts +11 -3
  38. package/dist/orientation.d.ts.map +1 -1
  39. package/dist/orientation.js +29 -8
  40. package/dist/orientation.js.map +1 -1
  41. package/dist/tool-specs.d.ts +14 -1
  42. package/dist/tool-specs.d.ts.map +1 -1
  43. package/dist/tool-specs.js +197 -50
  44. package/dist/tool-specs.js.map +1 -1
  45. package/package.json +3 -3
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { z } from "zod";
12
- import { isConcreteChannel, assertValidChannel, MAX_CHANNEL_LENGTH, channelInAllow, AmbiguousPeerError, peerLabel, assertLifecycleToken, isPermissionDenied, renderLifecycleBlocked, EpEnvelopeError, LANG_PROBLEM_DETAIL_KIND, formatAge, presenceAges, presenceText } from "@cotal-ai/core";
12
+ import { isConcreteChannel, isChannelFamily, assertValidChannel, MAX_CHANNEL_LENGTH, PLANE3_MAX_MSGS_PER_SUBJECT, channelInAllow, patternInAllow, AmbiguousPeerError, peerLabel, assertLifecycleToken, isPermissionDenied, renderLifecycleBlocked, EpEnvelopeError, EP_UNANSWERED, REGISTRY_PAGE_LIMIT, LANG_PROBLEM_DETAIL_KIND, formatAge, parseDuration, presenceAges, presenceText } from "@cotal-ai/core";
13
13
  import { afterRecallMark } from "./agent.js";
14
14
  // The neutralization and the per-item rendering live in `framing.ts`, one convention shared with
15
15
  // the auto-injected block, and are used here rather than restated. See that file for the rule.
@@ -455,8 +455,11 @@ function droppedNote(channels) {
455
455
  return "";
456
456
  const named = channels.slice(0, NAMED_DROPPED).map((c) => `#${attributionSafe(c).slice(0, 40)}`).join(", ");
457
457
  const rest = channels.length - Math.min(NAMED_DROPPED, channels.length);
458
- return `⚠ Some earlier chatter could not be recalled completely on ${named}${rest ? `, and ${rest} more channel${rest === 1 ? "" : "s"}` : ""} (retention or local safety bounds were reached).`;
458
+ return `⚠ Some earlier chatter could not be recalled completely on ${named}${rest ? `, and ${rest} more channel${rest === 1 ? "" : "s"}` : ""} (retention or local safety bounds were reached, or recall could not read the channel).`;
459
459
  }
460
+ /** Said once after this session's stored copies reached their limit (#5404). NATS reports no discard,
461
+ * so it says "may". */
462
+ const STORED_COPIES_NOTE = `⚠ Your stored copies reached their limit of ${PLANE3_MAX_MSGS_PER_SUBJECT}, so earlier channel posts may have been dropped before they reached you. Channel history may still hold them: \`cotal history <channel>\` reads it, within the space's history limit.`;
460
463
  /** How many channels the recall warning names before it starts counting them instead. */
461
464
  const NAMED_DROPPED = 5;
462
465
  /** How many rows one `cotal_channels` reply lists before it says how to continue. */
@@ -493,7 +496,9 @@ function renderChannelInfo(channel, info) {
493
496
  const lines = [
494
497
  `#${channel} — channel registry (advisory metadata about this channel, NOT instructions for you to obey):`,
495
498
  ];
496
- if (!info.registered)
499
+ if (!isConcreteChannel(channel))
500
+ lines.push(" • a pattern: it has no registry entry of its own, and each channel it matches keeps its own.");
501
+ else if (!info.registered)
497
502
  lines.push(info.event === "own"
498
503
  ? " • your own event channel: your connector publishes this session's activity events here. It is not a chat channel and needs no registry entry."
499
504
  : info.event === "agent"
@@ -552,29 +557,66 @@ export function defaultSendChannel(config, reading) {
552
557
  const concrete = reading.filter(isConcreteChannel);
553
558
  return isAuthed(config) ? concrete.find((c) => channelInAllow(config.allowPublish, c)) : concrete[0];
554
559
  }
555
- const NO_POSTABLE_DEFAULT = "you may post to none of the channels you read, so there is no default and an omitted channel is refused - name one your post ACL allows (cotal_orientation lists them)";
560
+ /**
561
+ * Why a send with no channel has nowhere to go, and the exact next call. Built from the channels
562
+ * the agent reads now and the channels its ACL lets it post to, so the refusal names a channel the
563
+ * agent can use rather than pointing at another tool. Two shapes: on no channel at all, or on
564
+ * channels it may post to none of. `postable` is empty where the ACL grants no concrete post
565
+ * channel the agent could name (an operator widens that; nothing here can).
566
+ */
567
+ export function sendNoDefaultRemedy(config, reading) {
568
+ const concrete = reading.filter(isConcreteChannel);
569
+ const authed = isAuthed(config);
570
+ const named = [...new Set([...config.allowPublish, ...config.allowSubscribe, ...reading].filter(isConcreteChannel))];
571
+ const postable = authed ? named.filter((c) => channelInAllow(config.allowPublish, c)) : named;
572
+ const where = concrete.length
573
+ ? `you may post to none of the channels you read (${concrete.map((c) => `#${c}`).join(", ")})`
574
+ : "you are on no channel";
575
+ if (!postable.length)
576
+ return `${where}, so there is no default and an omitted channel is refused; your post ACL names no channel you could use, so ask an operator to widen it, and reach peers with cotal_dm or cotal_anycast meanwhile`;
577
+ const first = postable[0];
578
+ const list = postable.map((c) => `#${c}`).join(", ");
579
+ return `${where}, so there is no default and an omitted channel is refused. You may post to ${list}: call cotal_send with channel: "${first}", or cotal_join ${first} first to make it your default`;
580
+ }
581
+ /** The orientation card as the model reads it, over the SAME gated tool list the connector exposes
582
+ * (cotalToolSpecs already filters spawn/persona by capability), so the card can't claim a tool the
583
+ * agent can't call. The `cotal_orientation` tool, a connect result and a session-start hook all
584
+ * hand over this one rendering. */
585
+ export async function orientationCard(agent, config, source, env, offered) {
586
+ const visible = cotalToolSpecs(config, source, env, offered).map((s) => ({ name: s.name, title: s.title }));
587
+ return renderOrientation(buildOrientation(agent, config, visible, Date.now(), await agent.readRoster()));
588
+ }
556
589
  /** How to reach a channel family, since every publish names one concrete channel (SPEC §3). The
557
590
  * advertised `channel` text of `cotal_send`, here and in the gateway. */
558
- export const PATTERN_SEND_HELP = "A pattern such as team.> is refused. To reach the agents connected and following team.> now, post once to one channel it matches, such as team.announce; to reach several channels, post to each by name (cotal_channels lists the existing ones).";
559
- /** Why `cotal_send` refuses `channel`, returned before anything is read or sent, or undefined when it
560
- * is one concrete channel name. A legal pattern gets the ways to reach a family. Any other name that
561
- * breaks the channel grammar is refused with the send's own rule: the endpoint would rewrite its
562
- * characters onto another subject than the receipt names, and the grammar's own message lists the
591
+ export const PATTERN_SEND_HELP = "A pattern such as team.> is refused. To reach the agents following team.>, post once to one channel it matches, such as team.announce: those connected then get it, and one that is away gets a stored copy if that channel is durable. To reach several channels, post to each by name (cotal_channels lists the existing ones).";
592
+ /** Why `channel` is not a channel name at all, ending with `outcome`, or undefined when it keeps the
593
+ * channel grammar (a concrete name or a legal pattern). The endpoint would rewrite such a name's
594
+ * characters onto another subject than the tool names, and the grammar's own message lists the
563
595
  * wildcard segments a policy may use. */
564
- function sendChannelRefusal(channel) {
565
- let legal = true;
596
+ function notAChannelName(channel, outcome) {
566
597
  try {
567
598
  assertValidChannel(channel);
599
+ return undefined;
568
600
  }
569
601
  catch {
570
- legal = false;
602
+ const shown = JSON.stringify(channel.length > 64 ? `${channel.slice(0, 64)}…` : channel);
603
+ return `${shown} is not a channel name. A channel name is segments of letters, digits, _ and - joined by dots, such as team.announce, at most ${MAX_CHANNEL_LENGTH} characters. ${outcome}`;
571
604
  }
572
- if (legal && isConcreteChannel(channel))
605
+ }
606
+ /** Why `cotal_send` refuses `channel`, returned before anything is read or sent, or undefined when it
607
+ * is one concrete channel name. A legal pattern gets the ways to reach its followers: a family's
608
+ * followers that are away get stored copies on durable channels (#5404), and any other pattern's only
609
+ * while connected. Any other name that breaks the channel grammar is refused as no channel name. */
610
+ function sendChannelRefusal(channel) {
611
+ const notName = notAChannelName(channel, "Nothing was sent.");
612
+ if (notName !== undefined)
613
+ return notName;
614
+ if (isConcreteChannel(channel))
573
615
  return undefined;
574
- if (legal)
575
- return `"${channel}" is a pattern, and a post goes to one concrete channel. To reach the agents connected and following ${channel} now, post once to one channel it matches. A pattern follow has no durable backstop, so a follower that is offline then may miss it. To reach several channels, post to each by name; cotal_channels lists the existing ones. Nothing was sent.`;
576
- const shown = JSON.stringify(channel.length > 64 ? `${channel.slice(0, 64)}…` : channel);
577
- return `${shown} is not a channel name. A channel name is segments of letters, digits, _ and - joined by dots, such as team.announce, at most ${MAX_CHANNEL_LENGTH} characters. Nothing was sent.`;
616
+ const reach = isChannelFamily(channel)
617
+ ? `To reach the agents following ${channel}, post once to one channel it matches: those connected then get it, and one that is away gets a stored copy if that channel is durable. `
618
+ : `To reach the agents connected and following ${channel} now, post once to one channel it matches. A pattern with * or the root > has no stored copies, so a follower that is offline then may miss it. `;
619
+ return `"${channel}" is a pattern, and a post goes to one concrete channel. ${reach}To reach several channels, post to each by name; cotal_channels lists the existing ones. Nothing was sent.`;
578
620
  }
579
621
  /** The full Cotal tool set for a given config. Renderers iterate this; `source` names the
580
622
  * hosting connector and is stamped onto outgoing feedback. An explicit env restricts feedback's
@@ -609,13 +651,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
609
651
  "present, your status/attention, and how many messages are unread. Call this first to get your " +
610
652
  "bearings; it's read-only and safe to re-check anytime.",
611
653
  async run(agent) {
612
- // Reflect the SAME gated tool list the connector exposes (cotalToolSpecs already filters
613
- // spawn/persona by capability), so the card can't claim a tool the agent can't call.
614
- const visible = cotalToolSpecs(config, source, env, offered).map((s) => ({
615
- name: s.name,
616
- title: s.title,
617
- }));
618
- const card = renderOrientation(buildOrientation(agent, config, visible, Date.now(), await agent.readRoster()));
654
+ const card = await orientationCard(agent, config, source, env, offered);
619
655
  const issue = agent.connectionIssue;
620
656
  return ok(agent.connected
621
657
  ? card
@@ -799,7 +835,8 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
799
835
  name: "cotal_inbox",
800
836
  title: "Cotal: read incoming messages",
801
837
  description: "Read messages other agents have sent you since you last checked: channel broadcasts, direct messages, and role requests. It clears ONLY what it actually returns to you (nothing at all when peek is true), and one call carries at most a receivable window: direct messages and role requests first, then channel traffic, with replayed history last. Anything that does not fit stays buffered and is named in the reply, so call again for the next batch. A single message larger than one whole response is delivered in parts: once no smaller mail is waiting, each call carries the next part of it, a peek shows the current part without moving on, and the message is cleared only after its last part goes out. In focus mode it also pulls back the channel chatter held since you entered focus. If exclusion tracking makes a channel's focus recall unsafe, new non-historical mentions on that unmuted channel wake to pull their buffered bodies, never automatic injection, including on quiet channels. Ambient handling is unchanged, and the incomplete-recall warning still names unsafe channels. " +
802
- "When the connection is not ready, the reply says so and still returns locally buffered messages; an empty local buffer does not prove no new mesh messages exist. Exhausted channel drop tracking is reported even with an empty inbox; non-historical mentions on unmuted channels wake to pull their buffered bodies while ambient traffic stays suppressed.",
838
+ "When the connection is not ready, the reply says so and still returns locally buffered messages; an empty local buffer does not prove no new mesh messages exist. Exhausted channel drop tracking is reported even with an empty inbox; non-historical mentions on unmuted channels wake to pull their buffered bodies while ambient traffic stays suppressed. " +
839
+ "If your stored copies reached their limit of 1000, the reply says earlier channel posts may have been dropped and that channel history may still hold them. A peek keeps that line for the next read.",
803
840
  schema: {
804
841
  peek: z.boolean().optional().describe("If true, show messages without clearing them."),
805
842
  },
@@ -817,8 +854,18 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
817
854
  // evicted and lost. That is the buffer's documented bounded local loss (see
818
855
  // MeshAgent.buffer), unchanged by this path; an evicted directed message is never acked.
819
856
  const automaticPending = scope ? agent.inboxCount("automatic") : 0;
857
+ // Every reply below carries the stored-copy notice, and it clears as the messages do: once the
858
+ // reply exists and its caller is still there. A recall that throws or a caller that goes keeps it.
859
+ const storedSeen = agent.storedCopiesFull;
860
+ const storedNote = storedSeen ? STORED_COPIES_NOTE : "";
861
+ const reply = (text) => {
862
+ if (storedSeen && !keeps())
863
+ agent.clearStoredCopiesFull(storedSeen);
864
+ return ok(text);
865
+ };
820
866
  if (agent.attention !== "focus") {
821
- const warning = inboxConnectionWarning(agent);
867
+ const connectionWarning = inboxConnectionWarning(agent);
868
+ const warning = [connectionWarning, storedNote].filter(Boolean).join("\n");
822
869
  const buffered = agent.peekInbox(inboxScope);
823
870
  const { text, shown, held, stuck } = renderInbox({
824
871
  items: buffered,
@@ -829,10 +876,10 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
829
876
  : `${s.length} message${s.length === 1 ? "" : "s"}${peek ? " (peek: nothing cleared)" : ""}:`,
830
877
  });
831
878
  if (!buffered.length)
832
- return ok([warning, scope
879
+ return reply([warning, scope
833
880
  ? `No pull-only messages.${automaticPending ? ` ${automaticPending} connector-managed automatic message${automaticPending === 1 ? " is" : "s are"} still queued.` : ""}`
834
881
  // A hook receipt never masks an unavailable connection, even with a live transport.
835
- : warning ? "Local inbox buffer is empty."
882
+ : connectionWarning ? "Local inbox buffer is empty."
836
883
  : (agent.connectionState === "ready" ? emptyInboxNote?.() : undefined) ?? "Inbox empty, no new messages."].filter(Boolean).join("\n\n"));
837
884
  if (!shown.length) {
838
885
  const part = partReply({
@@ -845,7 +892,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
845
892
  last: (i) => agent.drainInboxDeliveries([i.recvKey]),
846
893
  });
847
894
  if (part)
848
- return ok(part);
895
+ return reply(part);
849
896
  }
850
897
  // The response exists before anything is acked: an ack is a claim that these messages were
851
898
  // handed over, so nothing may be cleared while the handing-over is still hypothetical. And
@@ -853,7 +900,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
853
900
  if (!keeps())
854
901
  agent.drainInboxDeliveries(shown.map((i) => i.recvKey));
855
902
  void held;
856
- return ok(text);
903
+ return reply(text);
857
904
  }
858
905
  // Focus: the live buffer holds only DMs/anycast; the channel ambient + @mentions were
859
906
  // acked-and-dropped at ingest, so pull them back from the channel stream here (replay-gated,
@@ -911,7 +958,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
911
958
  const fresh = [...clocked, ...aheadFresh];
912
959
  const aheadIds = new Set(aheadFresh.map((i) => i.recvKey));
913
960
  const connectionWarning = inboxConnectionWarning(agent);
914
- const warning = [connectionWarning, droppedNote(recall.droppedChannels), aheadNote(aheadWithheld)]
961
+ const warning = [connectionWarning, storedNote, droppedNote(recall.droppedChannels), aheadNote(aheadWithheld)]
915
962
  .filter(Boolean)
916
963
  .join(" ");
917
964
  const { text, shown: all, stuck } = renderInbox({
@@ -924,7 +971,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
924
971
  : `${s.length} message${s.length === 1 ? "" : "s"}${peek ? " (peek: live buffer not cleared)" : ""} in focus mode; channel items are recall since you focused:`,
925
972
  });
926
973
  if (!buffered.length && !fresh.length && !recall.droppedChannels.length && !aheadWithheld.length)
927
- return ok([connectionWarning, scope
974
+ return reply([connectionWarning, storedNote, scope
928
975
  ? `No pull-only messages and no normal focus recall.${automaticPending ? ` ${automaticPending} connector-managed automatic message${automaticPending === 1 ? " is" : "s are"} still queued.` : ""}`
929
976
  : connectionWarning ? "Local inbox buffer and available focus recall are empty." : "Inbox empty, no new messages, and no channel chatter since you entered focus."].filter(Boolean).join("\n\n"));
930
977
  if (!all.length) {
@@ -951,7 +998,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
951
998
  },
952
999
  });
953
1000
  if (part)
954
- return ok(part);
1001
+ return reply(part);
955
1002
  }
956
1003
  // Render first, ack second, and only ever ids from the buffered lane: acking a recall id
957
1004
  // would mark it handled, so a later live copy of that channel message would be dropped.
@@ -978,7 +1025,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
978
1025
  agent.noteRecalled({ ts: last.ts, id: last.recvKey });
979
1026
  void stuck;
980
1027
  }
981
- return ok(text);
1028
+ return reply(text);
982
1029
  }),
983
1030
  },
984
1031
  {
@@ -990,7 +1037,7 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
990
1037
  channel: z
991
1038
  .string()
992
1039
  .optional()
993
- .describe(`Channel to send on (${defaultChannel ? `default: ${defaultChannel}` : config.subscribe.some(isConcreteChannel) ? `REQUIRED: ${NO_POSTABLE_DEFAULT}` : "REQUIRED: you are on no channel, so there is no default and an omitted channel is refused - join one first"}). ${PATTERN_SEND_HELP} Reply on the channel you received a message on.`),
1040
+ .describe(`Channel to send on (${defaultChannel ? `default: ${defaultChannel}` : `REQUIRED: ${sendNoDefaultRemedy(config, config.subscribe)}`}). ${PATTERN_SEND_HELP} Reply on the channel you received a message on.`),
994
1041
  mentions: z
995
1042
  .array(z.string())
996
1043
  .optional()
@@ -1003,9 +1050,9 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1003
1050
  try {
1004
1051
  const joined = agent.joinedChannels();
1005
1052
  const target = channel ?? defaultSendChannel(config, joined);
1006
- if (target === undefined && joined.some(isConcreteChannel))
1007
- return err(`Couldn't send: ${NO_POSTABLE_DEFAULT}.`);
1008
- const receipt = target !== undefined ? await agent.describeSendChannel(target) : undefined;
1053
+ if (target === undefined)
1054
+ return err(`Couldn't send: ${sendNoDefaultRemedy(config, joined)}.`);
1055
+ const receipt = await agent.describeSendChannel(target);
1009
1056
  const m = await agent.send(msg, target, mentions);
1010
1057
  const dest = `Sent to #${m.channel}${m.mentions?.length ? ` (mentioned @${m.mentions.join(", @")})` : ""}`;
1011
1058
  return ok(receipt ? `${dest} (${receipt}).` : `${dest}.`);
@@ -1125,6 +1172,9 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1125
1172
  channel: z.string().describe("The channel to look up (e.g. review)."),
1126
1173
  },
1127
1174
  run(agent, _config, { channel }) {
1175
+ const notName = notAChannelName(channel, "Nothing was looked up.");
1176
+ if (notName !== undefined)
1177
+ return err(`Couldn't look up the channel: ${notName}`);
1128
1178
  if (!agent.connected)
1129
1179
  return ok(`Not connected to the mesh yet (${config.servers}).`);
1130
1180
  return ok(renderChannelInfo(channel, agent.channelInfo(channel)));
@@ -1173,6 +1223,18 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1173
1223
  : c.event === "agent"
1174
1224
  ? " — an agent's event channel"
1175
1225
  : "";
1226
+ if (c.follow === "live")
1227
+ return `● #${c.channel} — pattern you follow, live only (a pattern with * or the root > has no stored copies)`;
1228
+ if (c.follow === "family" && !c.joined)
1229
+ return `○ #${c.channel} — family you no longer follow${c.durableUnclosed ? " · durable cleanup pending (§7 backstop may still deliver — retrying)" : ""}`;
1230
+ if (c.follow === "family") {
1231
+ const stored = c.deliveryHealth === "active"
1232
+ ? "stored copies on for its durable channels"
1233
+ : c.deliveryHealth === "unknown"
1234
+ ? "stored-copy health unknown: this reader cannot establish it"
1235
+ : "stored copies unavailable; live messages still arrive, and offline posts on its durable channels are at risk";
1236
+ return `● #${c.channel} — family you follow: every channel under ${c.channel.slice(0, -2)}, ${stored}${c.durableUnclosed ? " · durable cleanup pending (§7 backstop may still deliver — retrying)" : ""}`;
1237
+ }
1176
1238
  const mode = c.mode !== "normal" ? ` · ${c.mode}` : "";
1177
1239
  const unclosed = c.durableUnclosed ? " · durable cleanup pending (§7 backstop may still deliver — retrying)" : "";
1178
1240
  // Non-gating delivery-health: a durable-class channel must never look like ordinary
@@ -1235,14 +1297,20 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1235
1297
  {
1236
1298
  name: "cotal_join",
1237
1299
  title: "Cotal: join a channel",
1238
- description: "Subscribe to a channel mid-session. Returns its registry info; if the channel replays, recent history is delivered to your inbox marked as catch-up (it pre-dates your join, so don't treat it as live). Idempotent. Bounded by your read ACL: a channel outside it is refused.",
1300
+ description: "Subscribe to a channel mid-session. Returns its registry info; if the channel replays, recent history is delivered to your inbox marked as catch-up (it pre-dates your join, so don't treat it as live). " +
1301
+ "A family such as team.> follows every channel under team, now and later, but not team itself: posts on its durable channels are stored for you while you are away, from the join on, and its live channels reach you only while you are connected. A pattern with * or the root > is followed live only. " +
1302
+ "Idempotent. Bounded by your read ACL: a channel outside it is refused.",
1239
1303
  schema: {
1240
- channel: z.string().describe("The channel to join (e.g. incident)."),
1304
+ channel: z.string().describe("The channel to join (e.g. incident), or a family such as team.>."),
1241
1305
  },
1242
1306
  async run(agent, _config, { channel }) {
1307
+ const notName = notAChannelName(channel, "Nothing was joined.");
1308
+ if (notName !== undefined)
1309
+ return err(`Couldn't join: ${notName}`);
1243
1310
  // Bound by the read ACL before touching the mesh — a clear refusal beats a broker/manager
1244
- // rejection. (Auth mode also enforces this server-side; this is the friendly client gate.)
1245
- if (!channelInAllow(config.allowSubscribe, channel))
1311
+ // rejection. (Auth mode also enforces this server-side; this is the friendly client gate.) A
1312
+ // pattern must lie inside one entry, so every channel it matches is readable.
1313
+ if (!(isConcreteChannel(channel) ? channelInAllow : patternInAllow)(config.allowSubscribe, channel))
1246
1314
  return err(`Can't join #${channel}: it's outside your read ACL (allowSubscribe: ${config.allowSubscribe.map((c) => `#${c}`).join(", ")}).`);
1247
1315
  try {
1248
1316
  const r = await agent.joinChannel(channel);
@@ -1256,10 +1324,16 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1256
1324
  // (offline posts replay on your next turn). `durable:false` with a `reason` = a backstop was
1257
1325
  // expected but is unavailable (e.g. no provisioner) — joined LIVE only; say so, never hide it.
1258
1326
  // `durable:false` with no reason = a `live`-class channel (joined live is the contract).
1327
+ // A family's `durable` is its own row: each channel under it keeps its own class (#5404). A
1328
+ // pattern that is not a family has no stored copies, and its `reason` says so.
1259
1329
  const headline = r.durable
1260
- ? `Joined #${channel} (durable backstop active — messages sent while you're offline replay on your next turn).`
1330
+ ? isChannelFamily(channel)
1331
+ ? `Joined #${channel} (stored copies on: posts on its durable channels are kept for you while you're offline, from now on; its live channels reach you only while you're connected).`
1332
+ : `Joined #${channel} (durable backstop active — messages sent while you're offline replay on your next turn).`
1261
1333
  : r.reason
1262
- ? `Joined #${channel} (LIVE only — ${r.reason}; messages sent while you're offline won't be replayed).`
1334
+ ? isConcreteChannel(channel) || isChannelFamily(channel)
1335
+ ? `Joined #${channel} (LIVE only — ${r.reason}; messages sent while you're offline won't be replayed).`
1336
+ : `Joined #${channel} (live only: ${r.reason}).`
1263
1337
  : `Joined #${channel} (live).`;
1264
1338
  return ok(`${headline}\n${info}${caught}`);
1265
1339
  }
@@ -1271,9 +1345,9 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1271
1345
  {
1272
1346
  name: "cotal_leave",
1273
1347
  title: "Cotal: leave a channel",
1274
- description: "Unsubscribe from a channel mid-session; you stop receiving its messages. Leaving your LAST channel is allowed: you stay on the mesh, visible on the roster and reachable by DM and anycast, you just read no channel. You then have no default send channel, so cotal_send refuses a call with no channel until you join one.",
1348
+ description: "Unsubscribe from a channel or a family such as team.> mid-session; you stop receiving its messages, and a family's stored copies stop. Leaving your LAST channel is allowed: you stay on the mesh, visible on the roster and reachable by DM and anycast, you just read no channel. You then have no default send channel, so cotal_send refuses a call with no channel until you join one.",
1275
1349
  schema: {
1276
- channel: z.string().describe("The channel to leave."),
1350
+ channel: z.string().describe("The channel or family to leave."),
1277
1351
  },
1278
1352
  async run(agent, _config, { channel }) {
1279
1353
  try {
@@ -1288,9 +1362,13 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1288
1362
  {
1289
1363
  name: "cotal_spawn",
1290
1364
  title: "Cotal: spawn a new teammate",
1291
- description: "Ask the manager to start a new peer endpoint in your space. It joins the mesh as a lateral peer and, under the cmux runtime, appears in its own tab. A Cotal peer is a real, addressable process the user can watch; you can reach it by DM, find it on the roster, and coordinate with it later. Use it for teammate work that should stay visible on the mesh. Pass `prompt` when it should begin immediately; the connector auto-submits that prompt as its first turn. When you first bring a team online, if the live web dashboard is down, suggest `cotal watch` for a live terminal view. The dashboard service is configured and started separately; do not install or launch it implicitly. A partial result means the seat started but its requested model pin could not be read back: it names the seat and the `cotal ps --on <manager>` command that shows the pin, and spawning again would start a second agent.",
1365
+ description: "Ask the manager to start a new peer endpoint in your space. It joins the mesh as a lateral peer and, under the cmux runtime, appears in its own tab. A Cotal peer is a real, addressable process the user can watch; you can reach it by DM, find it on the roster, and coordinate with it later. Use it for teammate work that should stay visible on the mesh. Pass `prompt` when it should begin immediately; the connector auto-submits that prompt as its first turn. Pass `once: true` with a `prompt` to start a helper for one task: the peer gets the prompt as its only task and is stopped when it ends that turn, or at the deadline (one hour unless you pass `deadline`). When the spawn succeeds, its result names the task's goal; read its outcome with goal-result. A once task that ends without the peer ending its turn (its deadline passed, its handoff could not be confirmed, or the peer exited or never joined) may have run in part or in full, and nothing runs it again; whether to spawn it again is your call. Jcode, OpenCode, pi and Claude Code peers can take a once task. When you first bring a team online, if the live web dashboard is down, suggest `cotal watch` for a live terminal view. The dashboard service is configured and started separately; do not install or launch it implicitly. A partial result means the seat started but its requested model pin could not be read back: it names the seat and the `cotal ps --on <manager>` command that shows the pin, and spawning again would start a second agent. Channels: the new peer may read and post what its persona file allows; a persona that names no channel at all is scoped to your own allowances. It starts on NO channel unless you pass `join`, so pass the channel you are working on when it should see that traffic and post there (e.g. `join: [\"general\"]`).",
1292
1366
  schema: {
1293
1367
  name: z.string().describe("Which persona to spawn: the persona FILENAME in .cotal/agents (e.g. `review-critic`), without the .md. The new peer joins under the persona's own `name:` (auto-numbered with an underscore, e.g. socrates_2, if that's taken). Fails if no such persona file exists; spawn an existing persona, don't invent a name."),
1368
+ join: z
1369
+ .array(z.string())
1370
+ .optional()
1371
+ .describe("Channels the new peer joins at start, on top of what its persona file lists (e.g. ['general']). Concrete names only, each within YOUR read ACL (a spawn hands on only what you may read yourself; anything else is refused before launch). Omitted, a persona that lists no channel starts on none and its cotal_send with no channel is refused."),
1294
1372
  instance: z
1295
1373
  .string()
1296
1374
  .refine((value) => {
@@ -1338,6 +1416,14 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1338
1416
  .boolean()
1339
1417
  .optional()
1340
1418
  .describe("Event planes are on by default for connectors that publish one. Pass false to opt out; true only restates the default."),
1419
+ once: z
1420
+ .boolean()
1421
+ .optional()
1422
+ .describe("Run `prompt` as the new peer's one task, then stop the peer. The task reaches the peer as a relayed turn rather than a kickoff, and the peer is stopped when it ends that turn or when the deadline passes. Needs `prompt`. A Claude Code peer takes the task only when its startup shows channels on; otherwise the spawn fails at startup and says why."),
1423
+ deadline: z
1424
+ .string()
1425
+ .optional()
1426
+ .describe("With once: how long the task may run, as a duration such as 30m, 2h or 1d, counted from when the manager accepts the spawn. Omitted, it is 1h. Pass -1 for no deadline: the peer then keeps its name and its seat slot until it ends its turn or is despawned."),
1341
1427
  runtime: z
1342
1428
  .string()
1343
1429
  .trim()
@@ -1350,9 +1436,30 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1350
1436
  // boundary. Resume lives only on the operator CLI (`cotal spawn --resume`, foreground or
1351
1437
  // --detach); a peer-facing, capability-gated resume is deferred (see #159).
1352
1438
  },
1353
- async run(agent, _config, { name, instance, role, agent: agentType, model, variant, launchOptions, cwd, prompt, events, runtime }) {
1439
+ async run(agent, _config, { name, instance, role, agent: agentType, model, variant, launchOptions, cwd, prompt, events, once, deadline, runtime, join }) {
1440
+ let onceArg;
1441
+ if (deadline !== undefined && once !== true)
1442
+ return err("`deadline` applies only to a once spawn; pass once: true with it.");
1443
+ if (once === true) {
1444
+ if (deadline === undefined)
1445
+ onceArg = {};
1446
+ else if (deadline.trim() === "-1")
1447
+ onceArg = { deadlineMs: -1 };
1448
+ else {
1449
+ let ms;
1450
+ try {
1451
+ ms = parseDuration(deadline);
1452
+ }
1453
+ catch (e) {
1454
+ return err(`deadline: ${e.message}, or -1 for no deadline`);
1455
+ }
1456
+ if (!Number.isSafeInteger(ms) || ms < 1)
1457
+ return err(`deadline: "${deadline}" is not a positive duration; pass one such as 30m, or -1 for no deadline`);
1458
+ onceArg = { deadlineMs: ms };
1459
+ }
1460
+ }
1354
1461
  try {
1355
- const reply = await agent.spawn(name, role, { agent: agentType, model, variant, launchOptions, cwd, prompt, events, runtime, instance });
1462
+ const reply = await agent.spawn(name, role, { agent: agentType, model, variant, launchOptions, cwd, prompt, events, runtime, instance, join, ...(onceArg !== undefined ? { once: onceArg } : {}) });
1356
1463
  // An uncertain launch is still managed and may yet join. Reported as an error it reads as a
1357
1464
  // failed launch, and the caller's retry starts a second agent on the same work.
1358
1465
  const pending = reply.code === "uncertain";
@@ -1394,7 +1501,11 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1394
1501
  }
1395
1502
  if (pending)
1396
1503
  return ok(`${lead}${pin} (id ${d?.actor}, manager ${d?.executor?.lifecycleUid}), but it did not join the mesh within its readiness window. It may still be booting, so do not spawn it again: a retry starts a second agent. Watch cotal_roster for ${actual}, and cotal_despawn it if it never joins.`);
1397
- return ok(`${lead}${mode ? ` (${mode})` : ""}${pin} — it will appear in the roster shortly.`);
1504
+ // A once spawn names its task, so the spawner can read how it ended.
1505
+ const task = d?.once
1506
+ ? ` Its task is goal ${JSON.stringify(d.once.goalId)}, ${d.once.deadlineAt !== undefined ? `with a deadline of ${new Date(d.once.deadlineAt).toISOString()}` : "with no deadline"}; it is stopped when the task ends. Read the outcome with cotal_invoke(endpoint="manager", command="goal-result", args={"goalId":${JSON.stringify(d.once.goalId)}}).`
1507
+ : "";
1508
+ return ok(`${lead}${mode ? ` (${mode})` : ""}${pin} — it will appear in the roster shortly.${task}`);
1398
1509
  }
1399
1510
  catch (e) {
1400
1511
  return controlFailure(`Couldn't spawn ${name}`, e);
@@ -1713,6 +1824,42 @@ export function cotalToolSpecs(config, source = "connector", env, offered, empty
1713
1824
  }
1714
1825
  },
1715
1826
  },
1827
+ {
1828
+ name: "cotal_endpoints",
1829
+ title: "Cotal: list the endpoints you can call",
1830
+ description: "List the endpoints registered in this space that this session can call, and for each one the commands its grants cover and the request forms they allow. The space's registry answers from the grants recorded when this session's credential was issued, so the broker or the endpoint can still refuse a listed command. Endpoints where this session holds no command are left out, and so are endpoints whose command declarations cannot be read. A command whose grants are too many to list form by form is named under `unprojected`. On a user-auth mesh manager commands ride a separate manager-call credential; pass view=\"manager\" to list what that credential can call. Call cotal_describe for a command's input schema. A page holds up to 100 endpoints; pass the previous page's `next` as `after` for the next one.",
1831
+ schema: {
1832
+ after: z.string().min(1).max(128).optional().describe("The `next` value from the previous page."),
1833
+ limit: z.number().int().min(1).max(REGISTRY_PAGE_LIMIT).optional().describe(`Endpoints per page (default ${REGISTRY_PAGE_LIMIT}).`),
1834
+ view: z.enum(["session", "manager"]).optional().describe("`session` (default): this session's own credential. `manager`: its manager-call credential."),
1835
+ instance: z.string().min(1).max(64).optional().describe("Manager view only: the manager instance whose call credential to use."),
1836
+ },
1837
+ async run(agent, _config, { after, limit, view, instance }) {
1838
+ if (instance !== undefined && view !== "manager")
1839
+ return err("`instance` selects the manager for view=\"manager\" only.");
1840
+ const label = view === "manager" ? "the manager-call credential" : "this session";
1841
+ try {
1842
+ const input = { ...(after !== undefined ? { after } : {}), ...(limit !== undefined ? { limit } : {}) };
1843
+ const r = view === "manager" ? await agent.listManagerEndpoints(input, instance) : await agent.ep.listEndpoints(input);
1844
+ if ("none" in r)
1845
+ return err(`There is no manager view: ${r.none}.`);
1846
+ if (r.unbound)
1847
+ return err(`The credential of ${label} has no listing binding, so the registry cannot list what it may call. A credential issued before the listing existed, or one with no expiry, has none; a new credential does.`);
1848
+ if (r.reply.reply.ok !== true) {
1849
+ const e = r.reply.reply.error;
1850
+ return err(`The registry refused the listing: ${e?.code ?? "error"}: ${e?.message ?? "no message"}`);
1851
+ }
1852
+ const page = r.page;
1853
+ const more = page.next !== undefined ? ` More endpoints follow; pass after="${page.next}".` : "";
1854
+ return endpointData(`${page.rows.length} endpoints ${label} can call (source: ${page.source}).${more}`, page);
1855
+ }
1856
+ catch (e) {
1857
+ if (e instanceof EpEnvelopeError && e.details?.some((d) => d.kind === EP_UNANSWERED))
1858
+ return err("The registry did not answer, so nothing is listed. The space may run no registry, or it is down; other tools are unaffected.");
1859
+ return endpointFailure("Couldn't list endpoints", e);
1860
+ }
1861
+ },
1862
+ },
1716
1863
  {
1717
1864
  name: "cotal_describe",
1718
1865
  title: "Cotal: describe an endpoint",