@botiverse/raft-sdk 0.9.0 → 0.10.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.
@@ -4753,6 +4753,7 @@ const AGENT_API_ROUTE_META = {
4753
4753
  attachmentUploadSessionCancel: naturalDestructive,
4754
4754
  attachmentUploadSessionStatus: read,
4755
4755
  attachmentDownload: read,
4756
+ attachmentDownloadUrl: read,
4756
4757
  attachmentCommentsList: read,
4757
4758
  pushWebhookStatus: {
4758
4759
  sideEffect: "read",
@@ -5281,6 +5282,18 @@ const agentApiMessageReactionBodySchema = passthroughObject({ emoji: string().tr
5281
5282
  const agentApiChannelMembershipParamsSchema = passthroughObject({ channelId: string().trim().min(1).transform(asChannelId) });
5282
5283
  const agentApiChannelLifecycleBodySchema = passthroughObject({ target: string().trim().min(1) });
5283
5284
  const agentApiAttachmentDownloadParamsSchema = passthroughObject({ attachmentId: string().trim().min(1) });
5285
+ /**
5286
+ * Short-lived download URL for an attachment visible to the bound agent
5287
+ * credential (`GET /attachments/:attachmentId/url`). For runtimes that cannot
5288
+ * take binary tool results: the agent fetches the bytes itself from `url`
5289
+ * before `expiresAt`. The URL is a bearer capability; never log it.
5290
+ */
5291
+ const agentApiAttachmentDownloadUrlResponseSchema = passthroughObject({
5292
+ url: string().min(1),
5293
+ expiresAt: string().datetime(),
5294
+ filename: string(),
5295
+ mimeType: string()
5296
+ });
5284
5297
  const agentApiAttachmentCommentsParamsSchema = passthroughObject({ attachmentId: string().trim().min(1) });
5285
5298
  const agentApiAttachmentCommentsQuerySchema = passthroughObject({ limit: optionalStringSchema });
5286
5299
  const agentApiAttachmentCommentAnchorSchema = passthroughObject({
@@ -7337,6 +7350,19 @@ const agentApiContract = {
7337
7350
  request: { params: agentApiAttachmentDownloadParamsSchema },
7338
7351
  response: { kind: "binary" }
7339
7352
  }),
7353
+ attachmentDownloadUrl: route({
7354
+ key: "attachmentDownloadUrl",
7355
+ method: "GET",
7356
+ path: "/attachments/:attachmentId/url",
7357
+ client: {
7358
+ resource: "attachments",
7359
+ method: "downloadUrl"
7360
+ },
7361
+ capability: "read",
7362
+ description: "Mint a short-lived (5 minute) download URL for an attachment visible to the bound agent credential, with its filename and MIME type. 409 download_url_unavailable when this Server's storage cannot presign; use the binary download instead.",
7363
+ request: { params: agentApiAttachmentDownloadParamsSchema },
7364
+ response: { body: agentApiAttachmentDownloadUrlResponseSchema }
7365
+ }),
7340
7366
  attachmentCommentsList: route({
7341
7367
  key: "attachmentCommentsList",
7342
7368
  method: "GET",
@@ -9732,6 +9758,31 @@ const AGENT_API_ROUTE_MANIFEST = [
9732
9758
  "body": false
9733
9759
  }
9734
9760
  },
9761
+ {
9762
+ "key": "attachmentDownloadUrl",
9763
+ "method": "GET",
9764
+ "path": "/attachments/:attachmentId/url",
9765
+ "fullPath": "/internal/agent-api/attachments/:attachmentId/url",
9766
+ "client": {
9767
+ "resource": "attachments",
9768
+ "method": "downloadUrl"
9769
+ },
9770
+ "capability": "read",
9771
+ "description": "Mint a short-lived (5 minute) download URL for an attachment visible to the bound agent credential, with its filename and MIME type. 409 download_url_unavailable when this Server's storage cannot presign; use the binary download instead.",
9772
+ "sideEffect": "read",
9773
+ "idempotency": "natural",
9774
+ "destructive": false,
9775
+ "audience": "both",
9776
+ "request": {
9777
+ "params": true,
9778
+ "query": false,
9779
+ "body": false
9780
+ },
9781
+ "response": {
9782
+ "kind": "json",
9783
+ "body": true
9784
+ }
9785
+ },
9735
9786
  {
9736
9787
  "key": "attachmentCommentsList",
9737
9788
  "method": "GET",
@@ -9859,7 +9910,7 @@ const AGENT_API_ROUTE_MANIFEST = [
9859
9910
  }
9860
9911
  ];
9861
9912
  /** Content hash of AGENT_API_ROUTE_MANIFEST; see computeAgentApiManifestVersion. */
9862
- const AGENT_API_MANIFEST_VERSION = "2a3c2201ea57a9d1";
9913
+ const AGENT_API_MANIFEST_VERSION = "c762a744e3542f89";
9863
9914
  //#endregion
9864
9915
  //#region src/routes.ts
9865
9916
  const ROUTE_INFO = Object.fromEntries(AGENT_API_ROUTE_MANIFEST.map((entry) => {
@@ -10454,6 +10505,280 @@ function fileReadError() {
10454
10505
  return new RaftCredentialError("CREDENTIAL_STORE_READ_FAILED", "The Raft credential file is invalid or unreadable");
10455
10506
  }
10456
10507
  //#endregion
10508
+ //#region ../shared/src/agentOps/hint.ts
10509
+ /** `tasks.updateStatus` → `tasks_update_status`: the manifest's tool name for an operation name. */
10510
+ function raftToolNameFor(name) {
10511
+ return name.replace(/\./g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
10512
+ }
10513
+ /** Tool-form wording for a CLI command that has no operation (channel / server admin writes). */
10514
+ const RAFT_NO_TOOL_WORDING = "ask a human via an action card (`actions_prepare`)";
10515
+ const ELLIPSIS = "…";
10516
+ function q(value) {
10517
+ return `"${value}"`;
10518
+ }
10519
+ function hint(cli, op, fill) {
10520
+ if (!op) return { cli };
10521
+ const args = Object.fromEntries(Object.entries(op.args).filter(([, value]) => value !== void 0));
10522
+ return fill && fill.length > 0 ? {
10523
+ cli,
10524
+ op: {
10525
+ name: op.name,
10526
+ args,
10527
+ partial: true
10528
+ },
10529
+ fill
10530
+ } : {
10531
+ cli,
10532
+ op: {
10533
+ name: op.name,
10534
+ args
10535
+ }
10536
+ };
10537
+ }
10538
+ function toolArgs(hint) {
10539
+ const parts = Object.entries(hint.op?.args ?? {}).map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
10540
+ for (const key of hint.fill ?? []) parts.push(`${key}: ${ELLIPSIS}`);
10541
+ return parts.length > 0 ? `{ ${parts.join(", ")} }` : "{}";
10542
+ }
10543
+ /** Render a hint: `raft message read --target "#ops"` (cli) or `messages_read({ target: "#ops" })` (tool). */
10544
+ function formatHint(hint, style = "cli") {
10545
+ if (style === "cli") return ["raft", ...hint.cli].join(" ");
10546
+ if (!hint.op) return RAFT_NO_TOOL_WORDING;
10547
+ if (hint.codeOnly) return `raft.${hint.op.name}(${toolArgs(hint)})`;
10548
+ return `${raftToolNameFor(hint.op.name)}(${toolArgs(hint)})`;
10549
+ }
10550
+ /** Just the command's name, for prose that lists commands: `raft channel join` (cli) or `channels_join` (tool). */
10551
+ function formatHintName(hint, style = "cli") {
10552
+ if (style === "cli") return ["raft", ...hint.cli].join(" ");
10553
+ if (!hint.op) return RAFT_NO_TOOL_WORDING;
10554
+ return hint.codeOnly ? `raft.${hint.op.name}` : raftToolNameFor(hint.op.name);
10555
+ }
10556
+ /** A flag named in prose: `--limit` (cli) or `limit` (tool, the argument name). */
10557
+ function formatHintFlag(flag, arg, style = "cli") {
10558
+ return style === "cli" ? `--${flag}` : arg;
10559
+ }
10560
+ /**
10561
+ * The hint as a next step: `command` is the rendered hint, `operation` the
10562
+ * structured call (when there is one). `args` keeps the step's own arguments.
10563
+ */
10564
+ function hintStep(kind, hint, why, style = "cli", args) {
10565
+ return {
10566
+ kind,
10567
+ command: formatHint(hint, style),
10568
+ ...args ? { args } : {},
10569
+ ...hint.op ? { operation: hint.op } : {},
10570
+ why
10571
+ };
10572
+ }
10573
+ /**
10574
+ * Every hint the shared formatters and operations produce. Placeholder
10575
+ * arguments (`<name>`, `"…"`) are `fill` keys: the CLI form prints the
10576
+ * placeholder, the tool form `name: …`.
10577
+ */
10578
+ const RAFT_HINTS = {
10579
+ messageRead: ({ target, after, before, around }) => hint([
10580
+ "message",
10581
+ "read",
10582
+ "--target",
10583
+ q(target),
10584
+ ...after === void 0 ? [] : ["--after", String(after)],
10585
+ ...before === void 0 ? [] : ["--before", String(before)],
10586
+ ...around === void 0 ? [] : ["--around", around.shown]
10587
+ ], {
10588
+ name: "messages.read",
10589
+ args: {
10590
+ target,
10591
+ after,
10592
+ before,
10593
+ around: around?.id
10594
+ }
10595
+ }),
10596
+ /** Send into a conversation; `content` is always the caller's. Without a target the target is left too. */
10597
+ messageSend: ({ target, attachmentId }) => hint([
10598
+ "message",
10599
+ "send",
10600
+ ...target === void 0 ? [] : ["--target", q(target)],
10601
+ ...attachmentId === void 0 ? [] : ["--attachment-id", attachmentId]
10602
+ ], {
10603
+ name: "messages.send",
10604
+ args: {
10605
+ target,
10606
+ attachmentIds: attachmentId === void 0 ? void 0 : [attachmentId]
10607
+ }
10608
+ }, target === void 0 ? ["target", "content"] : ["content"]),
10609
+ /** The send command's name alone (prose, never a call). */
10610
+ messageSendName: () => hint(["message", "send"], {
10611
+ name: "messages.send",
10612
+ args: {}
10613
+ }, ["target", "content"]),
10614
+ messageCheck: () => hint(["message", "check"], {
10615
+ name: "inbox.check",
10616
+ args: {}
10617
+ }),
10618
+ inboxList: ({ view, before } = {}) => hint([
10619
+ "inbox",
10620
+ "check",
10621
+ ...view === void 0 ? [] : ["--view", view],
10622
+ ...before === void 0 ? [] : ["--before", String(before)]
10623
+ ], {
10624
+ name: "inbox.list",
10625
+ args: {
10626
+ view,
10627
+ before
10628
+ }
10629
+ }),
10630
+ /** `query: true` is the `<name>` placeholder. */
10631
+ serverInfo: ({ view, offset, limit, query, joined } = {}) => hint([
10632
+ "server",
10633
+ "info",
10634
+ ...view === void 0 ? [] : [`--${view}`],
10635
+ ...offset === void 0 ? [] : ["--offset", String(offset)],
10636
+ ...limit === void 0 ? [] : ["--limit", String(limit)],
10637
+ ...query === void 0 ? [] : ["--query", query === true ? "<name>" : JSON.stringify(query)],
10638
+ ...joined ? ["--joined"] : []
10639
+ ], {
10640
+ name: "server.info",
10641
+ args: {
10642
+ view,
10643
+ offset,
10644
+ limit,
10645
+ query: typeof query === "string" ? query : void 0,
10646
+ joined: joined ? true : void 0
10647
+ }
10648
+ }, query === true ? ["query"] : void 0),
10649
+ /** `name` undefined is the `<name>` placeholder. */
10650
+ userInfo: ({ name, offset, limit } = {}) => hint([
10651
+ "user",
10652
+ "info",
10653
+ name === void 0 ? "<name>" : `@${name}`,
10654
+ ...offset === void 0 ? [] : ["--offset", String(offset)],
10655
+ ...limit === void 0 ? [] : ["--limit", String(limit)]
10656
+ ], {
10657
+ name: "users.info",
10658
+ args: {
10659
+ name: name === void 0 ? void 0 : `@${name}`,
10660
+ offset,
10661
+ limit
10662
+ }
10663
+ }, name === void 0 ? ["name"] : void 0),
10664
+ /** The `<name>` placeholder form. */
10665
+ channelInfo: () => hint([
10666
+ "channel",
10667
+ "info",
10668
+ "<name>"
10669
+ ], {
10670
+ name: "channels.info",
10671
+ args: {}
10672
+ }, ["target"]),
10673
+ channelMembers: (target) => hint([
10674
+ "channel",
10675
+ "members",
10676
+ q(target)
10677
+ ], {
10678
+ name: "channels.members",
10679
+ args: { target }
10680
+ }),
10681
+ /** Channel attention commands by name (prose). */
10682
+ channelJoinName: () => hint(["channel", "join"], {
10683
+ name: "channels.join",
10684
+ args: {}
10685
+ }, ["target"]),
10686
+ channelLeaveName: () => hint(["channel", "leave"], {
10687
+ name: "channels.leave",
10688
+ args: {}
10689
+ }, ["target"]),
10690
+ channelMuteName: () => hint(["channel", "mute"], {
10691
+ name: "channels.mute",
10692
+ args: {}
10693
+ }, ["target"]),
10694
+ channelUnmuteName: () => hint(["channel", "unmute"], {
10695
+ name: "channels.unmute",
10696
+ args: {}
10697
+ }, ["target"]),
10698
+ threadUnfollowName: () => hint(["thread", "unfollow"], {
10699
+ name: "threads.unfollow",
10700
+ args: {}
10701
+ }, ["target"]),
10702
+ /** Channel / server admin writes: no operation by policy (a human acts through an action card). */
10703
+ channelCreateName: () => hint(["channel", "create"]),
10704
+ serverUpdateName: () => hint(["server", "update"]),
10705
+ taskClaim: ({ target, taskNumber }) => hint([
10706
+ "task",
10707
+ "claim",
10708
+ "--target",
10709
+ q(target),
10710
+ "--number",
10711
+ String(taskNumber)
10712
+ ], {
10713
+ name: "tasks.claim",
10714
+ args: {
10715
+ target,
10716
+ taskNumbers: [taskNumber]
10717
+ }
10718
+ }),
10719
+ taskListAll: (target) => hint([
10720
+ "task",
10721
+ "list",
10722
+ "--target",
10723
+ q(target),
10724
+ "--status",
10725
+ "all"
10726
+ ], {
10727
+ name: "tasks.list",
10728
+ args: {
10729
+ target,
10730
+ status: "all"
10731
+ }
10732
+ }),
10733
+ mentionAction: (action, resolutionId) => hint([
10734
+ "mention",
10735
+ action,
10736
+ resolutionId
10737
+ ], {
10738
+ name: "mentions.execute",
10739
+ args: {
10740
+ action,
10741
+ resolutionIds: [resolutionId]
10742
+ }
10743
+ }),
10744
+ mentionPending: () => hint(["mention", "pending"], {
10745
+ name: "mentions.pending",
10746
+ args: {}
10747
+ }),
10748
+ /** `intent` and `reason` are always the caller's. */
10749
+ manualGet: (topic) => hint([
10750
+ "manual",
10751
+ "get",
10752
+ topic,
10753
+ "--intent",
10754
+ q(ELLIPSIS),
10755
+ "--reason",
10756
+ q(ELLIPSIS)
10757
+ ], {
10758
+ name: "manual.get",
10759
+ args: { topic }
10760
+ }, ["intent", "reason"]),
10761
+ /** The download pointer on message lines; the tool form mints a URL (one attachment: its id; several: left to fill). */
10762
+ attachmentView: (attachmentId) => hint(["attachment", "view"], {
10763
+ name: "attachments.downloadUrl",
10764
+ args: { attachmentId }
10765
+ }, attachmentId === void 0 ? ["attachmentId"] : void 0),
10766
+ /** The binary download (typed method only): where an attachment whose URL cannot be minted is fetched. */
10767
+ attachmentDownload: (attachmentId) => ({
10768
+ ...hint([
10769
+ "attachment",
10770
+ "view",
10771
+ attachmentId,
10772
+ "--output",
10773
+ "<path>"
10774
+ ], {
10775
+ name: "attachments.download",
10776
+ args: { attachmentId }
10777
+ }),
10778
+ codeOnly: true
10779
+ })
10780
+ };
10781
+ //#endregion
10457
10782
  //#region ../shared/src/agentOps/outcome.ts
10458
10783
  const SERVER_ERROR_CODE = /^[A-Za-z0-9_.:-]{1,64}$/;
10459
10784
  const DEFAULT_MESSAGES = {
@@ -10470,6 +10795,9 @@ const DEFAULT_MESSAGES = {
10470
10795
  UNAVAILABLE: "The Raft Server could not serve this operation right now.",
10471
10796
  MODEL_ONLY: "This operation only counts when the model sees its result, so it cannot be run from code; nothing was sent."
10472
10797
  };
10798
+ function notFoundNextAction(style) {
10799
+ return `Check the target spelling with \`${formatHint(RAFT_HINTS.serverInfo({ view: "channels" }), style)}\` or resolve the message id first.`;
10800
+ }
10473
10801
  const DEFAULT_NEXT_ACTION = {
10474
10802
  INVALID_REQUEST: "Fix the request arguments; nothing was sent.",
10475
10803
  TRANSPORT_ERROR: "Check connectivity to the Raft Server and retry if the operation is safe to repeat.",
@@ -10477,7 +10805,7 @@ const DEFAULT_NEXT_ACTION = {
10477
10805
  INVALID_RESPONSE: "Upgrade the SDK or report the Server version; the response shape is not the one this SDK knows.",
10478
10806
  CAPABILITY_NOT_AUTHORIZED: "Ask a human who can mint credentials to include the missing capability.",
10479
10807
  SCOPE_DENIED: "Ask a human with editAgents authority to extend this agent's scopes.",
10480
- NOT_FOUND: "Check the target spelling with `raft server info --channels` or resolve the message id first.",
10808
+ NOT_FOUND: notFoundNextAction("cli"),
10481
10809
  CONFLICT: "Read the current state before repeating this operation.",
10482
10810
  IDEMPOTENCY_KEY_REUSED: "Use a new idempotency key for a different request, or resend the identical request to reconcile.",
10483
10811
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: "Use your own runtime for this; the Server does not provide it to External Agents.",
@@ -10569,6 +10897,31 @@ function failureOutcome(error) {
10569
10897
  };
10570
10898
  }
10571
10899
  /**
10900
+ * Render the SDK's own default next action in a hint style. Only NOT_FOUND's
10901
+ * default names a command; it is set deep in the shared client-error mapping,
10902
+ * so `createRaft({ hints: "tool" })` re-renders it here instead of threading
10903
+ * the style through every failure. A Server-sent next action is left as is.
10904
+ */
10905
+ function restyleDefaultNextAction(outcome, style) {
10906
+ if (style === "cli" || !outcome || typeof outcome !== "object") return outcome;
10907
+ const failure = outcome;
10908
+ if (failure.ok !== false || !failure.error || failure.error.nextAction !== DEFAULT_NEXT_ACTION.NOT_FOUND) return outcome;
10909
+ const error = {
10910
+ ...failure.error,
10911
+ nextAction: notFoundNextAction(style)
10912
+ };
10913
+ const next = failure.next && failure.next.why === DEFAULT_NEXT_ACTION.NOT_FOUND ? {
10914
+ ...failure.next,
10915
+ why: error.nextAction
10916
+ } : failure.next ?? null;
10917
+ return {
10918
+ ...failure,
10919
+ error,
10920
+ next,
10921
+ text: formatOpErrorText(error)
10922
+ };
10923
+ }
10924
+ /**
10572
10925
  * A failure of a keyed write (`idempotencyKey`). A retryable failure (the
10573
10926
  * request may not have reached the Server, or the Server was unavailable)
10574
10927
  * says to repeat the SAME request with the SAME key, and carries the key in
@@ -10991,9 +11344,10 @@ function formatAgentSenderHandle(m) {
10991
11344
  const desc = m.sender_description ?? null;
10992
11345
  return desc ? `@${name} — ${desc}` : `@${name}`;
10993
11346
  }
10994
- function formatAgentAttachmentSuffix(attachments) {
11347
+ function formatAgentAttachmentSuffix(attachments, style = "cli") {
10995
11348
  if (!attachments?.length) return "";
10996
- return ` [${attachments.length} attachment${attachments.length > 1 ? "s" : ""}: ${attachments.map((a) => `${a.filename} (id:${a.id})`).join(", ")} — use raft attachment view to download]`;
11349
+ const download = formatHint(RAFT_HINTS.attachmentView(style === "tool" && attachments.length === 1 ? attachments[0].id : void 0), style);
11350
+ return ` [${attachments.length} attachment${attachments.length > 1 ? "s" : ""}: ${attachments.map((a) => `${a.filename} (id:${a.id})`).join(", ")} — use ${download} to download]`;
10997
11351
  }
10998
11352
  function formatAgentTaskAssigneeSuffix(assigneeId, assigneeName) {
10999
11353
  if (!assigneeId) return "";
@@ -11019,7 +11373,7 @@ function formatAgentTaskCurrentProjection(projection, taskNumber, neutralize) {
11019
11373
  return `\n${lines.join("\n")}`;
11020
11374
  }
11021
11375
  /** One received-message line: header bracket + sender + content + suffixes. */
11022
- function formatAgentMessageLine(m) {
11376
+ function formatAgentMessageLine(m, style = "cli") {
11023
11377
  if (m.third_party_event) {
11024
11378
  const msgId = m.message_id ? m.message_id.slice(0, 8) : m.third_party_event.id.slice(0, 8);
11025
11379
  const time = m.timestamp ? formatUtcTimestamp(m.timestamp) : "-";
@@ -11035,22 +11389,22 @@ function formatAgentMessageLine(m) {
11035
11389
  const time = m.timestamp ? formatUtcTimestamp(m.timestamp) : "-";
11036
11390
  const senderType = ` type=${m.sender_type}`;
11037
11391
  const content = indentAgentBodyContinuationLines(m.content ?? "");
11038
- const attachSuffix = formatAgentAttachmentSuffix(m.attachments);
11392
+ const attachSuffix = formatAgentAttachmentSuffix(m.attachments, style);
11039
11393
  const taskSuffix = m.task_status ? ` [task #${m.task_number} status=${m.task_status}${formatAgentTaskAssigneeSuffix(m.task_assignee_id, m.task_assignee_name)}]` : "";
11040
11394
  return `[target=${target} msg=${msgId} time=${time}${senderType}] ${formatAgentSenderHandle(m)}: ${content}${attachSuffix}${taskSuffix}${formatAgentReplyAffordanceSuffix(m)}${formatAgentTaskCurrentProjection(m.task_current_projection)}`;
11041
11395
  }
11042
11396
  /** Batch of received-message lines (`raft message check` output). */
11043
- function formatAgentMessages(messages) {
11397
+ function formatAgentMessages(messages, style = "cli") {
11044
11398
  if (messages.length === 0) return "No new inbox messages.";
11045
- return messages.map(formatAgentMessageLine).join("\n");
11399
+ return messages.map((m) => formatAgentMessageLine(m, style)).join("\n");
11046
11400
  }
11047
11401
  /**
11048
11402
  * `message check` hands over a bounded batch, oldest first per conversation;
11049
11403
  * the server reports how many conversations still have unread after it.
11050
11404
  */
11051
- function formatAgentInboxHint(hint) {
11405
+ function formatAgentInboxHint(hint, style = "cli") {
11052
11406
  const n = hint.unread_conversations;
11053
- return `Still unread: ${n} ${n === 1 ? "conversation" : "conversations"}. Run \`raft inbox check\` to list them.`;
11407
+ return `Still unread: ${n} ${n === 1 ? "conversation" : "conversations"}. Run \`${formatHint(RAFT_HINTS.inboxList(), style)}\` to list them.`;
11054
11408
  }
11055
11409
  //#endregion
11056
11410
  //#region ../shared/src/agentOps/message.ts
@@ -11094,7 +11448,7 @@ function hasAgentMessageIdentity(envelope) {
11094
11448
  return true;
11095
11449
  }
11096
11450
  /** Project one envelope; `null` when it has no conversation identity (skip it rather than render `#undefined`). */
11097
- function projectRaftMessage(envelope) {
11451
+ function projectRaftMessage(envelope, style = "cli") {
11098
11452
  if (!hasAgentMessageIdentity(envelope)) return null;
11099
11453
  const like = toAgentMessageLike(envelope);
11100
11454
  const id = nullableString(like.message_id);
@@ -11127,7 +11481,7 @@ function projectRaftMessage(envelope) {
11127
11481
  id: nullableString(envelope.threadId),
11128
11482
  replyCount: nullableNumber(envelope.replyCount)
11129
11483
  },
11130
- text: formatAgentMessageLine(like),
11484
+ text: formatAgentMessageLine(like, style),
11131
11485
  raw: envelope
11132
11486
  };
11133
11487
  }
@@ -11135,8 +11489,8 @@ function sortBySeq(messages) {
11135
11489
  return [...messages].sort((a, b) => (a.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER));
11136
11490
  }
11137
11491
  /** Project a list, skipping envelopes without a conversation identity. */
11138
- function projectRaftMessages(envelopes) {
11139
- return envelopes.map(projectRaftMessage).filter((m) => m !== null);
11492
+ function projectRaftMessages(envelopes, style = "cli") {
11493
+ return envelopes.map((envelope) => projectRaftMessage(envelope, style)).filter((m) => m !== null);
11140
11494
  }
11141
11495
  /** The conversation fields a target string names; `null` for a shape this cannot read. */
11142
11496
  function identityFromTarget(target) {
@@ -11168,12 +11522,12 @@ function identityFromTarget(target) {
11168
11522
  * because the request already named the target; fill them from `target`
11169
11523
  * instead of dropping the message.
11170
11524
  */
11171
- function projectRaftMessagesInTarget(envelopes, target) {
11525
+ function projectRaftMessagesInTarget(envelopes, target, style = "cli") {
11172
11526
  const identity = identityFromTarget(target);
11173
11527
  return envelopes.map((envelope) => projectRaftMessage(identity && !hasAgentMessageIdentity(envelope) ? {
11174
11528
  ...envelope,
11175
11529
  ...identity
11176
- } : envelope)).filter((m) => m !== null);
11530
+ } : envelope, style)).filter((m) => m !== null);
11177
11531
  }
11178
11532
  //#endregion
11179
11533
  //#region ../shared/src/agentOps/interrupt.ts
@@ -11185,7 +11539,7 @@ function isInterrupted(outcome) {
11185
11539
  function unreadMessagesInterrupt(input) {
11186
11540
  const { hold, target } = input;
11187
11541
  const withheld = input.withheld === true || hold.freshnessContextMode === "withheld";
11188
- const heldMessages = withheld ? [] : projectRaftMessagesInTarget(hold.heldMessages ?? [], target);
11542
+ const heldMessages = withheld ? [] : projectRaftMessagesInTarget(hold.heldMessages ?? [], target, input.hints);
11189
11543
  const newMessageCount = withheld ? hold.withheldMessageCount ?? hold.newMessageCount ?? 0 : hold.newMessageCount ?? heldMessages.length;
11190
11544
  const omittedMessageCount = withheld ? 0 : hold.omittedMessageCount ?? 0;
11191
11545
  return {
@@ -11476,18 +11830,9 @@ const inboxPullFields = {
11476
11830
  };
11477
11831
  const checkInboxRequestSchema = requestSchema()(object(inboxPullFields));
11478
11832
  const MAX_DRAIN_ROUNDS = 50;
11479
- function batchNext(batch) {
11480
- if (batch.hasMore) return {
11481
- kind: "check_inbox_again",
11482
- command: "raft message check",
11483
- ...batch.cursor === null ? {} : { args: { since: batch.cursor } },
11484
- why: "The Server trimmed this batch; more messages are pending."
11485
- };
11486
- if ((batch.stillUnreadConversations ?? 0) > 0) return {
11487
- kind: "list_inbox",
11488
- command: "raft inbox check",
11489
- why: "Conversations remain unread beyond this batch."
11490
- };
11833
+ function batchNext(batch, style) {
11834
+ if (batch.hasMore) return hintStep("check_inbox_again", RAFT_HINTS.messageCheck(), "The Server trimmed this batch; more messages are pending.", style, batch.cursor === null ? void 0 : { since: batch.cursor });
11835
+ if ((batch.stillUnreadConversations ?? 0) > 0) return hintStep("list_inbox", RAFT_HINTS.inboxList(), "Conversations remain unread beyond this batch.", style);
11491
11836
  if (batch.messages.length > 0) return {
11492
11837
  kind: "reply_or_act",
11493
11838
  args: { target: batch.messages[0].target },
@@ -11495,11 +11840,11 @@ function batchNext(batch) {
11495
11840
  };
11496
11841
  return null;
11497
11842
  }
11498
- function batchText(batch) {
11499
- const lines = [formatAgentMessages(batch.messages.map((m) => toAgentMessageLike(m.raw)))];
11500
- if (batch.hasMore) lines.push("More messages are pending. Run `raft message check` again.");
11843
+ function batchText(batch, style) {
11844
+ const lines = [formatAgentMessages(batch.messages.map((m) => toAgentMessageLike(m.raw)), style)];
11845
+ if (batch.hasMore) lines.push(`More messages are pending. Run \`${formatHint(RAFT_HINTS.messageCheck(), style)}\` again.`);
11501
11846
  else if (batch.messages.length > 0) lines.push("No more new inbox messages.");
11502
- if ((batch.stillUnreadConversations ?? 0) > 0) lines.push(formatAgentInboxHint({ unread_conversations: batch.stillUnreadConversations }));
11847
+ if ((batch.stillUnreadConversations ?? 0) > 0) lines.push(formatAgentInboxHint({ unread_conversations: batch.stillUnreadConversations }, style));
11503
11848
  return lines.join("\n");
11504
11849
  }
11505
11850
  function recordExactSeen(frontier, messages) {
@@ -11512,7 +11857,8 @@ function recordExactSeen(frontier, messages) {
11512
11857
  for (const [target, seqs] of byTarget) frontier.recordExact(target, seqs);
11513
11858
  }
11514
11859
  /** One bounded pull. Records exact seen seqs on `frontier` (sparse drains never advance the high-water mark). */
11515
- async function checkInbox(client, request = {}, frontier) {
11860
+ async function checkInbox(client, request = {}, frontier, options = {}) {
11861
+ const style = options.hints ?? "cli";
11516
11862
  const invalid = validateOpRequest(checkInboxRequestSchema, request);
11517
11863
  if (invalid) return invalid;
11518
11864
  const ack = request.ack ?? "cursor";
@@ -11523,7 +11869,7 @@ async function checkInbox(client, request = {}, frontier) {
11523
11869
  });
11524
11870
  if (!result.ok) return failureFromClientResult(result);
11525
11871
  const data = result.data;
11526
- const messages = sortBySeq(projectRaftMessages(data.events));
11872
+ const messages = sortBySeq(projectRaftMessages(data.events, style));
11527
11873
  recordExactSeen(frontier, messages);
11528
11874
  const batch = {
11529
11875
  messages,
@@ -11537,8 +11883,8 @@ async function checkInbox(client, request = {}, frontier) {
11537
11883
  ok: true,
11538
11884
  state: messages.length > 0 ? "batch" : "empty",
11539
11885
  data: batch,
11540
- next: batchNext(batch),
11541
- text: batchText(batch)
11886
+ next: batchNext(batch, style),
11887
+ text: batchText(batch, style)
11542
11888
  };
11543
11889
  }
11544
11890
  const drainInboxRequestSchema = requestSchema()(object(inboxPullFields));
@@ -11552,7 +11898,7 @@ const drainInboxRequestSchema = requestSchema()(object(inboxPullFields));
11552
11898
  * return value summarises the drain; the batch that ends the iteration is
11553
11899
  * acknowledged only by the caller's next pull (`summary.cursor`).
11554
11900
  */
11555
- async function* drainInbox(client, request = {}, frontier, onPull) {
11901
+ async function* drainInbox(client, request = {}, frontier, onPull, options = {}) {
11556
11902
  const ack = request.ack ?? "cursor";
11557
11903
  const invalid = validateOpRequest(drainInboxRequestSchema, request);
11558
11904
  if (invalid) return {
@@ -11574,7 +11920,7 @@ async function* drainInbox(client, request = {}, frontier, onPull) {
11574
11920
  ...sent === null ? {} : { since: sent },
11575
11921
  limit: request.limit,
11576
11922
  ack
11577
- }, frontier);
11923
+ }, frontier, options);
11578
11924
  if (!round.ok) return {
11579
11925
  cursor,
11580
11926
  ackMode,
@@ -11624,25 +11970,18 @@ async function* drainInbox(client, request = {}, frontier, onPull) {
11624
11970
  };
11625
11971
  }
11626
11972
  /** Fold a finished drain into one outcome; a drain that failed before its first batch is that failure. */
11627
- function drainedInboxOutcome(batches, summary) {
11973
+ function drainedInboxOutcome(batches, summary, options = {}) {
11628
11974
  if (summary.error && batches.length === 0) return summary.error;
11975
+ const style = options.hints ?? "cli";
11629
11976
  const messages = batches.flatMap((batch) => batch.messages);
11630
- const lines = [formatAgentMessages(messages.map((m) => toAgentMessageLike(m.raw)))];
11977
+ const lines = [formatAgentMessages(messages.map((m) => toAgentMessageLike(m.raw)), style)];
11631
11978
  if (summary.error) lines.push("The drain stopped early on an error; more messages may be pending. Check the inbox again.");
11632
11979
  else if (summary.hasMore) lines.push("More messages are pending. Check the inbox again.");
11633
11980
  else if (messages.length > 0) lines.push("No more new inbox messages.");
11634
11981
  const stillUnread = summary.stillUnreadConversations ?? 0;
11635
- if (stillUnread > 0) lines.push(formatAgentInboxHint({ unread_conversations: stillUnread }));
11982
+ if (stillUnread > 0) lines.push(formatAgentInboxHint({ unread_conversations: stillUnread }, style));
11636
11983
  const first = messages[0];
11637
- const next = summary.hasMore ? {
11638
- kind: "check_inbox_again",
11639
- command: "raft message check",
11640
- why: "More messages are pending."
11641
- } : stillUnread > 0 ? {
11642
- kind: "list_inbox",
11643
- command: "raft inbox check",
11644
- why: "Conversations remain unread beyond this drain."
11645
- } : first ? {
11984
+ const next = summary.hasMore ? hintStep("check_inbox_again", RAFT_HINTS.messageCheck(), "More messages are pending.", style) : stillUnread > 0 ? hintStep("list_inbox", RAFT_HINTS.inboxList(), "Conversations remain unread beyond this drain.", style) : first ? {
11646
11985
  kind: "reply_or_act",
11647
11986
  args: { target: first.target },
11648
11987
  why: "Handle the messages above; reply where each one came from."
@@ -11664,23 +12003,21 @@ const listInboxRequestSchema = requestSchema()(object({
11664
12003
  before: number$1().int().nonnegative().optional().describe("Next page: the nextBeforeSeq of the previous page."),
11665
12004
  limit: number$1().int().positive().optional().describe("Conversations per page, 1..50 (Server default 20).")
11666
12005
  }));
11667
- function openCommandFor(item) {
11668
- return `raft message read --target "${item.target}" --after ${item.lastReadSeq}`;
12006
+ function openHint(item) {
12007
+ return RAFT_HINTS.messageRead({
12008
+ target: item.target,
12009
+ after: item.lastReadSeq
12010
+ });
11669
12011
  }
11670
- function listingNext(listing) {
12012
+ function listingNext(listing, style) {
11671
12013
  const first = listing.conversations[0];
11672
- if (first) return {
11673
- kind: "read_target",
11674
- command: first.openCommand,
11675
- args: {
11676
- target: first.target,
11677
- after: first.lastReadSeq
11678
- },
11679
- why: "Open the newest unread conversation from your read position."
11680
- };
12014
+ if (first) return hintStep("read_target", openHint(first), "Open the newest unread conversation from your read position.", style, {
12015
+ target: first.target,
12016
+ after: first.lastReadSeq
12017
+ });
11681
12018
  return null;
11682
12019
  }
11683
- function listingText(listing) {
12020
+ function listingText(listing, style) {
11684
12021
  const t = listing.totals;
11685
12022
  const head = t.conversations === 0 ? "Inbox: nothing unread." : `Inbox: ${t.conversations} unread ${t.conversations === 1 ? "conversation" : "conversations"} (${t.dms} DMs, ${t.mentions} with mentions).${listing.conversations.length > 0 ? " Newest activity first." : ""}`;
11686
12023
  const rows = listing.conversations.map((c) => {
@@ -11688,8 +12025,14 @@ function listingText(listing) {
11688
12025
  return `${c.target} · ${c.unread} unread${flags ? ` · ${flags}` : ""}${c.latestSenderName ? ` · latest @${c.latestSenderName}` : ""}\n open: ${c.openCommand}`;
11689
12026
  });
11690
12027
  const trailer = [];
11691
- if (listing.hasMore && listing.nextBeforeSeq !== null) trailer.push(`More: raft inbox check${listing.view === "mentions" ? " --view mentions" : ""} --before ${listing.nextBeforeSeq}`);
11692
- const next = listingNext(listing);
12028
+ if (listing.hasMore && listing.nextBeforeSeq !== null) {
12029
+ const more = RAFT_HINTS.inboxList({
12030
+ ...listing.view === "mentions" ? { view: "mentions" } : {},
12031
+ before: listing.nextBeforeSeq
12032
+ });
12033
+ trailer.push(`More: ${formatHint(more, style)}`);
12034
+ }
12035
+ const next = listingNext(listing, style);
11693
12036
  trailer.push(next?.command ? `Next: open the first conversation above: ${next.command}` : "Next: nothing to do.");
11694
12037
  return [
11695
12038
  head,
@@ -11698,7 +12041,8 @@ function listingText(listing) {
11698
12041
  ].join("\n");
11699
12042
  }
11700
12043
  /** The agent's Activity panel. Lists only; nothing is consumed. */
11701
- async function listInbox(client, request = {}) {
12044
+ async function listInbox(client, request = {}, options = {}) {
12045
+ const style = options.hints ?? "cli";
11702
12046
  const invalid = validateOpRequest(listInboxRequestSchema, request);
11703
12047
  if (invalid) return invalid;
11704
12048
  const result = await client.inbox.list({
@@ -11719,7 +12063,7 @@ async function listInbox(client, request = {}) {
11719
12063
  activitySeq: item.activitySeq,
11720
12064
  latestSenderName: item.latestSenderName,
11721
12065
  latestAt: item.latestAt,
11722
- openCommand: openCommandFor(item)
12066
+ openCommand: formatHint(openHint(item), style)
11723
12067
  })),
11724
12068
  totals: data.totals,
11725
12069
  hasMore: data.hasMore,
@@ -11729,8 +12073,8 @@ async function listInbox(client, request = {}) {
11729
12073
  ok: true,
11730
12074
  state: listing.conversations.length > 0 ? "listed" : "empty",
11731
12075
  data: listing,
11732
- next: listingNext(listing),
11733
- text: listingText(listing)
12076
+ next: listingNext(listing, style),
12077
+ text: listingText(listing, style)
11734
12078
  };
11735
12079
  }
11736
12080
  //#endregion
@@ -11745,38 +12089,34 @@ const readHistoryRequestSchema = requestSchema()(object({
11745
12089
  limit: number$1().int().positive().optional().describe("Maximum messages in the window."),
11746
12090
  consume: boolean().optional().describe("false reads without consuming: the conversation is not marked read and nothing counts as seen.")
11747
12091
  }));
11748
- function historyNext(page) {
12092
+ function historyNext(page, style) {
11749
12093
  const seqs = page.messages.map((m) => m.seq).filter((s) => s !== null);
11750
12094
  if (page.hasNewer && seqs.length > 0) {
11751
12095
  const max = Math.max(...seqs);
11752
- return {
11753
- kind: "read_newer",
11754
- command: `raft message read --target "${page.target}" --after ${max}`,
11755
- args: {
11756
- target: page.target,
11757
- after: max
11758
- },
11759
- why: "Newer messages exist beyond this window."
11760
- };
12096
+ return hintStep("read_newer", RAFT_HINTS.messageRead({
12097
+ target: page.target,
12098
+ after: max
12099
+ }), "Newer messages exist beyond this window.", style, {
12100
+ target: page.target,
12101
+ after: max
12102
+ });
11761
12103
  }
11762
12104
  if (page.hasOlder && seqs.length > 0) {
11763
12105
  const min = Math.min(...seqs);
11764
- return {
11765
- kind: "read_older",
11766
- command: `raft message read --target "${page.target}" --before ${min}`,
11767
- args: {
11768
- target: page.target,
11769
- before: min
11770
- },
11771
- why: "Older messages exist before this window; read them only if the task needs them."
11772
- };
12106
+ return hintStep("read_older", RAFT_HINTS.messageRead({
12107
+ target: page.target,
12108
+ before: min
12109
+ }), "Older messages exist before this window; read them only if the task needs them.", style, {
12110
+ target: page.target,
12111
+ before: min
12112
+ });
11773
12113
  }
11774
12114
  return null;
11775
12115
  }
11776
- function historyText(page) {
12116
+ function historyText(page, style) {
11777
12117
  if (page.messages.length === 0) return `No messages in ${page.target}.`;
11778
- const lines = [formatAgentMessages(page.messages.map((m) => toAgentMessageLike(m.raw)))];
11779
- const next = historyNext(page);
12118
+ const lines = [formatAgentMessages(page.messages.map((m) => toAgentMessageLike(m.raw)), style)];
12119
+ const next = historyNext(page, style);
11780
12120
  if (next?.command) lines.push(`${next.kind === "read_newer" ? "Newer" : "Older"} exist: ${next.command}`);
11781
12121
  return lines.join("\n");
11782
12122
  }
@@ -11796,7 +12136,8 @@ function recordHistorySeen(frontier, requested, page, around) {
11796
12136
  }
11797
12137
  frontier.recordExact(page.target, seqs);
11798
12138
  }
11799
- async function readHistory(client, request, frontier) {
12139
+ async function readHistory(client, request, frontier, options = {}) {
12140
+ const style = options.hints ?? "cli";
11800
12141
  const invalid = validateOpRequest(readHistoryRequestSchema, request);
11801
12142
  if (invalid) return invalid;
11802
12143
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to read history." }));
@@ -11812,7 +12153,7 @@ async function readHistory(client, request, frontier) {
11812
12153
  const data = result.data;
11813
12154
  const page = {
11814
12155
  target: typeof data.target === "string" && data.target ? data.target : request.target,
11815
- messages: sortBySeq(projectRaftMessages(data.messages)),
12156
+ messages: sortBySeq(projectRaftMessages(data.messages, style)),
11816
12157
  hasOlder: data.has_older === true,
11817
12158
  hasNewer: data.has_newer === true,
11818
12159
  lastReadSeq: typeof data.last_read_seq === "number" ? data.last_read_seq : null,
@@ -11823,8 +12164,8 @@ async function readHistory(client, request, frontier) {
11823
12164
  ok: true,
11824
12165
  state: page.messages.length > 0 ? "page" : "empty",
11825
12166
  data: page,
11826
- next: historyNext(page),
11827
- text: historyText(page)
12167
+ next: historyNext(page, style),
12168
+ text: historyText(page, style)
11828
12169
  };
11829
12170
  }
11830
12171
  /** Attempts for a keyed send whose request never reached the Server (transport failure only). */
@@ -11848,68 +12189,60 @@ const replyToRequestSchema = requestSchema()(object({
11848
12189
  ...sendMessageFields
11849
12190
  }));
11850
12191
  /** Today's held text (unchanged); it is the interrupt's `context` and the outcome's `text`. */
11851
- function heldText(held, action) {
12192
+ function heldText(held, action, style) {
11852
12193
  const noun = held.newMessageCount === 1 ? "message" : "messages";
11853
12194
  const head = `Held — ${held.newMessageCount} unread ${noun} in ${held.target}. ${action}`;
11854
12195
  if (held.withheld) return `${head}\nContext withheld (reviewer isolation).`;
11855
12196
  const lines = [head];
11856
12197
  if (held.formalMentionCount > 0) lines.push(`Note: ${held.formalMentionCount} of these messages formally @mention you.`);
11857
12198
  if (held.omittedMessageCount > 0) lines.push(`${held.omittedMessageCount} earlier ${held.omittedMessageCount === 1 ? "message" : "messages"} not shown.`);
11858
- if (held.heldMessages.length > 0) lines.push(formatAgentMessages(held.heldMessages.map((m) => toAgentMessageLike(m.raw))));
12199
+ if (held.heldMessages.length > 0) lines.push(formatAgentMessages(held.heldMessages.map((m) => toAgentMessageLike(m.raw)), style));
11859
12200
  if (!held.contextComplete) lines.push("Not all of them are shown here; read the conversation before sending again.");
11860
- lines.push(`Full text: raft message read --target "${held.target}"`);
12201
+ lines.push(`Full text: ${formatHint(RAFT_HINTS.messageRead({ target: held.target }), style)}`);
11861
12202
  return lines.join("\n");
11862
12203
  }
11863
12204
  /**
11864
12205
  * A Server freshness hold as the `unread_messages` interrupt: the structured
11865
12206
  * details, today's held text as `context`, and the given resume / cancel.
11866
12207
  */
11867
- function heldInterrupt(target, data, action, resume, cancel) {
12208
+ function heldInterrupt(target, data, action, resume, cancel, style = "cli") {
11868
12209
  const interrupt = unreadMessagesInterrupt({
11869
12210
  target,
11870
12211
  hold: data,
11871
12212
  context: "",
11872
12213
  resume,
11873
- ...cancel ? { cancel } : {}
12214
+ ...cancel ? { cancel } : {},
12215
+ hints: style
11874
12216
  });
11875
12217
  return {
11876
12218
  ...interrupt,
11877
- context: heldText(interrupt, action)
12219
+ context: heldText(interrupt, action, style)
11878
12220
  };
11879
12221
  }
11880
- function heldSendNext(interrupt) {
11881
- return {
11882
- kind: "resend",
11883
- command: `raft message read --target "${interrupt.target}"`,
11884
- args: { target: interrupt.target },
11885
- why: interrupt.withheld ? "Newer messages exist in this conversation but were withheld; read them, then resume the send (interrupt.resume, same idempotencyKey) or cancel it." : !interrupt.contextComplete ? "Newer messages arrived in this conversation and not all of them are shown here; read the conversation, then resume the send (interrupt.resume, same idempotencyKey) or cancel it." : "Newer messages arrived in this conversation. Show interrupt.context to the model, call frontier.recordHeld(interrupt) to attest that, then resume the send (interrupt.resume, same idempotencyKey) or cancel it."
11886
- };
12222
+ function heldSendNext(interrupt, style) {
12223
+ return hintStep("resend", RAFT_HINTS.messageRead({ target: interrupt.target }), interrupt.withheld ? "Newer messages exist in this conversation but were withheld; read them, then resume the send (interrupt.resume, same idempotencyKey) or cancel it." : !interrupt.contextComplete ? "Newer messages arrived in this conversation and not all of them are shown here; read the conversation, then resume the send (interrupt.resume, same idempotencyKey) or cancel it." : "Newer messages arrived in this conversation. Show interrupt.context to the model, call frontier.recordHeld(interrupt) to attest that, then resume the send (interrupt.resume, same idempotencyKey) or cancel it.", style, { target: interrupt.target });
11887
12224
  }
11888
12225
  function isHeldResponse(data) {
11889
12226
  return Boolean(data) && typeof data === "object" && data.state === "held";
11890
12227
  }
11891
- function sentOutcome(target, data) {
12228
+ function sentOutcome(target, data, style) {
11892
12229
  const sent = {
11893
12230
  messageId: data.messageId,
11894
12231
  messageSeq: typeof data.messageSeq === "number" ? data.messageSeq : null,
11895
12232
  unresolvedMentionHandles: data.unresolvedMentionHandles ?? [],
11896
- recentUnread: projectRaftMessages(data.recentUnread ?? [])
12233
+ recentUnread: projectRaftMessages(data.recentUnread ?? [], style)
11897
12234
  };
11898
12235
  const warn = sent.unresolvedMentionHandles.length > 0 ? ` Unresolved @handles: ${sent.unresolvedMentionHandles.map((h) => `@${h}`).join(", ")}.` : "";
11899
12236
  return {
11900
12237
  ok: true,
11901
12238
  state: "sent",
11902
12239
  data: sent,
11903
- next: sent.recentUnread.length > 0 ? {
11904
- kind: "read_target",
11905
- command: `raft message read --target "${target}"`,
11906
- args: { target },
11907
- why: "Newer messages arrived while you were sending."
11908
- } : null,
12240
+ next: sent.recentUnread.length > 0 ? hintStep("read_target", RAFT_HINTS.messageRead({ target }), "Newer messages arrived while you were sending.", style, { target }) : null,
11909
12241
  text: `Message sent to ${target}. Message ID: ${sent.messageId}${warn}`
11910
12242
  };
11911
12243
  }
11912
- async function sendMessage(client, request, frontier) {
12244
+ async function sendMessage(client, request, frontier, options = {}) {
12245
+ const style = options.hints ?? "cli";
11913
12246
  const invalid = validateOpRequest(sendMessageRequestSchema, request);
11914
12247
  if (invalid) return invalid;
11915
12248
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to send a message." }));
@@ -11933,16 +12266,16 @@ async function sendMessage(client, request, frontier) {
11933
12266
  if (!result.ok) return failureFromClientResult(result);
11934
12267
  const data = result.data;
11935
12268
  if (isHeldResponse(data)) {
11936
- const interrupt = heldInterrupt(request.target, data, "Your message was not sent.", inProcessSendResume(idempotencyKey));
12269
+ const interrupt = heldInterrupt(request.target, data, "Your message was not sent.", inProcessSendResume(idempotencyKey), void 0, style);
11937
12270
  return {
11938
12271
  ok: true,
11939
12272
  state: "interrupted",
11940
12273
  interrupt,
11941
- next: heldSendNext(interrupt),
12274
+ next: heldSendNext(interrupt, style),
11942
12275
  text: interrupt.context
11943
12276
  };
11944
12277
  }
11945
- if (data.state === "sent") return sentOutcome(request.target, data);
12278
+ if (data.state === "sent") return sentOutcome(request.target, data, style);
11946
12279
  return failureOutcome(opError("INVALID_RESPONSE", { message: `Unexpected send state "${data.state}".` }));
11947
12280
  }
11948
12281
  function taskTimestamps(t) {
@@ -12024,13 +12357,13 @@ function formatAgentMyTaskList(data, statusFilter) {
12024
12357
  ].join("\n");
12025
12358
  }
12026
12359
  /** Receipt for task create. */
12027
- function formatAgentTasksCreated(channel, data) {
12360
+ function formatAgentTasksCreated(channel, data, style = "cli") {
12028
12361
  const created = data.tasks.map((t) => {
12029
12362
  const assignee = t.claimedById ? t.claimedByName ? `@${t.claimedByName}` : "<unresolved>" : "unassigned";
12030
12363
  const resourceReceipt = t.requiresResourceReceipt ? " resource-receipt=pending" : "";
12031
12364
  return `#${t.taskNumber} [${t.status}] assignee=${assignee} claimedAt=${t.claimedAt ?? "null"} msg=${t.messageId.slice(0, 8)}${resourceReceipt} "${t.title}"`;
12032
12365
  }).join("\n");
12033
- const threadHints = data.tasks.map((t) => `#${t.taskNumber} → raft message send --target "${channel}:${t.messageId.slice(0, 8)}"`).join("\n");
12366
+ const threadHints = data.tasks.map((t) => `#${t.taskNumber} → ${formatHint(RAFT_HINTS.messageSend({ target: `${channel}:${t.messageId.slice(0, 8)}` }), style)}`).join("\n");
12034
12367
  const receipt = data.assignmentReceipt ? `\n\nAssignment receipt (msg=${data.assignmentReceipt.messageId.slice(0, 8)}):\n${data.assignmentReceipt.content}` : "";
12035
12368
  return `Created ${data.tasks.length} task(s) in ${channel}:\n${created}${receipt}\n\nTo follow up in each task's thread:\n${threadHints}`;
12036
12369
  }
@@ -12053,7 +12386,7 @@ function agentTaskThreadTarget(target, messageId) {
12053
12386
  return `${canonicalAgentTaskTarget(target)}:${messageId.slice(0, 8)}`;
12054
12387
  }
12055
12388
  /** Claim results incl. concurrency-lock guidance on failed claims. */
12056
- function formatAgentClaimResults(channel, data) {
12389
+ function formatAgentClaimResults(channel, data, style = "cli") {
12057
12390
  const lines = data.results.map((r) => {
12058
12391
  const label = r.taskNumber ? `#${r.taskNumber}` : `msg:${r.messageId}`;
12059
12392
  if (r.success) return `${label} (msg:${r.messageId ? r.messageId.slice(0, 8) : ""}): claimed`;
@@ -12065,7 +12398,7 @@ function formatAgentClaimResults(channel, data) {
12065
12398
  const failed = data.results.length - succeeded;
12066
12399
  let summary = `${succeeded} claimed`;
12067
12400
  if (failed > 0) summary += `, ${failed} failed`;
12068
- const claimedMsgs = data.results.filter((r) => r.success && r.messageId).map((r) => `#${r.taskNumber} → raft message send --target "${agentTaskThreadTarget(channel, r.messageId)}"`).join("\n");
12401
+ const claimedMsgs = data.results.filter((r) => r.success && r.messageId).map((r) => `#${r.taskNumber} → ${formatHint(RAFT_HINTS.messageSend({ target: agentTaskThreadTarget(channel, r.messageId) }), style)}`).join("\n");
12069
12402
  const threadHint = claimedMsgs ? `\n\nFollow up in each task's thread:\n${claimedMsgs}` : "";
12070
12403
  return `Claim results (${summary}):\n${lines.join("\n")}${threadHint}`;
12071
12404
  }
@@ -12082,13 +12415,13 @@ function formatAgentTaskDeleted(taskNumber) {
12082
12415
  return `#${taskNumber} deleted.`;
12083
12416
  }
12084
12417
  /** Message→task conversion receipt. */
12085
- function formatAgentTaskConverted(channel, task) {
12418
+ function formatAgentTaskConverted(channel, task, style = "cli") {
12086
12419
  const target = `${canonicalAgentTaskTarget(channel)}:${task.messageId.slice(0, 8)}`;
12087
12420
  return [
12088
12421
  `Converted msg=${task.messageId.slice(0, 8)} to task #${task.taskNumber} [${task.status}] assignee=unassigned "${task.title}"`,
12089
12422
  "",
12090
12423
  `To follow up in the task's thread:`,
12091
- `raft message send --target "${target}"`
12424
+ formatHint(RAFT_HINTS.messageSend({ target }), style)
12092
12425
  ].join("\n");
12093
12426
  }
12094
12427
  function formatAgentTaskAmended(data) {
@@ -12150,15 +12483,16 @@ const claimTasksRequestSchema = requestSchema()(object({
12150
12483
  * A held task call: the interrupt whose resume is the identical command, with
12151
12484
  * no cancel (a held task call saved nothing). `context` is today's held text.
12152
12485
  */
12153
- function heldTaskInterrupt(target, data, action, after, argv) {
12486
+ function heldTaskInterrupt(target, data, action, after, argv, style) {
12154
12487
  const interrupt = unreadMessagesInterrupt({
12155
12488
  target,
12156
12489
  hold: data,
12157
12490
  context: "",
12158
- resume: { argv }
12491
+ resume: { argv },
12492
+ hints: style
12159
12493
  });
12160
12494
  const noun = interrupt.newMessageCount === 1 ? "message" : "messages";
12161
- const context = `Held — ${interrupt.newMessageCount} unread ${noun} in ${target}. ${action}\nRead them with: raft message read --target "${target}"\n${after}`;
12495
+ const context = `Held — ${interrupt.newMessageCount} unread ${noun} in ${target}. ${action}\nRead them with: ${formatHint(RAFT_HINTS.messageRead({ target }), style)}\n${after}`;
12162
12496
  return {
12163
12497
  ...interrupt,
12164
12498
  context
@@ -12170,17 +12504,14 @@ function rowState(result) {
12170
12504
  if (result.conflict?.kind === "claim_conflict") return "conflict";
12171
12505
  return "refused";
12172
12506
  }
12173
- function claimNext(claim) {
12507
+ function claimNext(claim, style) {
12174
12508
  const first = claim.rows.find((row) => row.mayWork);
12175
12509
  if (first) {
12176
12510
  const thread = first.messageId ? agentTaskThreadTarget(claim.target, first.messageId) : null;
12177
- return {
12511
+ const why = "The claim is yours; post progress in the task's thread.";
12512
+ return thread ? hintStep("start_work", RAFT_HINTS.messageSend({ target: thread }), why, style, { target: thread }) : {
12178
12513
  kind: "start_work",
12179
- ...thread ? {
12180
- command: `raft message send --target "${thread}"`,
12181
- args: { thread }
12182
- } : {},
12183
- why: "The claim is yours; post progress in the task's thread."
12514
+ why
12184
12515
  };
12185
12516
  }
12186
12517
  return {
@@ -12188,10 +12519,11 @@ function claimNext(claim) {
12188
12519
  why: "No claim authorised work. Do not retry the identical claim and do not start conflicting execution; if you own this lane, correct the routing in the original thread."
12189
12520
  };
12190
12521
  }
12191
- function claimText(claim) {
12192
- return formatAgentClaimResults(claim.target, { results: claim.rows.map((row) => row.raw) });
12522
+ function claimText(claim, style) {
12523
+ return formatAgentClaimResults(claim.target, { results: claim.rows.map((row) => row.raw) }, style);
12193
12524
  }
12194
- async function claimTasks(client, request) {
12525
+ async function claimTasks(client, request, options = {}) {
12526
+ const style = options.hints ?? "cli";
12195
12527
  const numbers = (request.taskNumbers ?? []).filter((n) => Number.isInteger(n) && n > 0);
12196
12528
  const ids = (request.messageIds ?? []).map((id) => id.trim()).filter(Boolean);
12197
12529
  const invalid = validateOpRequest(claimTasksRequestSchema, request);
@@ -12206,17 +12538,12 @@ async function claimTasks(client, request) {
12206
12538
  if (!result.ok) return failureFromClientResult(result);
12207
12539
  const data = result.data;
12208
12540
  if (isHeldResponse(data)) {
12209
- const interrupt = heldTaskInterrupt(request.target, data, "Your task claim was not applied.", "After reviewing, rerun the claim if it is still correct.", taskClaimArgv(request.target, numbers, ids));
12541
+ const interrupt = heldTaskInterrupt(request.target, data, "Your task claim was not applied.", "After reviewing, rerun the claim if it is still correct.", taskClaimArgv(request.target, numbers, ids), style);
12210
12542
  return {
12211
12543
  ok: true,
12212
12544
  state: "interrupted",
12213
12545
  interrupt,
12214
- next: {
12215
- kind: "retry_claim",
12216
- command: `raft message read --target "${request.target}"`,
12217
- args: { target: request.target },
12218
- why: "Unread messages in this channel may change the task; read them (frontier.recordHeld(interrupt) once the model saw them), then resume the claim (interrupt.resume) if it is still right."
12219
- },
12546
+ next: hintStep("retry_claim", RAFT_HINTS.messageRead({ target: request.target }), "Unread messages in this channel may change the task; read them (frontier.recordHeld(interrupt) once the model saw them), then resume the claim (interrupt.resume) if it is still right.", style, { target: request.target }),
12220
12547
  text: interrupt.context
12221
12548
  };
12222
12549
  }
@@ -12243,8 +12570,8 @@ async function claimTasks(client, request) {
12243
12570
  ok: true,
12244
12571
  state: !claim.anyAuthorised ? "refused" : rows.every((row) => row.mayWork) ? "claimed" : "partial",
12245
12572
  data: claim,
12246
- next: claimNext(claim),
12247
- text: claimText(claim)
12573
+ next: claimNext(claim, style),
12574
+ text: claimText(claim, style)
12248
12575
  };
12249
12576
  }
12250
12577
  const listTasksRequestSchema = requestSchema()(object({
@@ -12259,7 +12586,7 @@ const listTasksRequestSchema = requestSchema()(object({
12259
12586
  "all"
12260
12587
  ]).optional().describe("Filter by status; all includes done and closed.")
12261
12588
  }));
12262
- async function listTasks(client, request) {
12589
+ async function listTasks(client, request, options = {}) {
12263
12590
  const invalid = validateOpRequest(listTasksRequestSchema, request);
12264
12591
  if (invalid) return invalid;
12265
12592
  const mine = request.mine === true;
@@ -12278,15 +12605,13 @@ async function listTasks(client, request) {
12278
12605
  };
12279
12606
  const text = mine ? formatAgentMyTaskList(data, request.status) : formatAgentTaskList(request.target, data, request.status);
12280
12607
  const open = board.tasks.find((t) => t.status === "todo" && !t.claimedByName);
12281
- const next = open?.taskNumber && board.target ? {
12282
- kind: "claim_task",
12283
- command: `raft task claim --target "${board.target}" --number ${open.taskNumber}`,
12284
- args: {
12285
- target: board.target,
12286
- taskNumbers: [open.taskNumber]
12287
- },
12288
- why: "An unassigned todo task is open; claim it before working on it."
12289
- } : null;
12608
+ const next = open?.taskNumber && board.target ? hintStep("claim_task", RAFT_HINTS.taskClaim({
12609
+ target: board.target,
12610
+ taskNumber: open.taskNumber
12611
+ }), "An unassigned todo task is open; claim it before working on it.", options.hints, {
12612
+ target: board.target,
12613
+ taskNumbers: [open.taskNumber]
12614
+ }) : null;
12290
12615
  return {
12291
12616
  ok: true,
12292
12617
  state: board.tasks.length > 0 ? "board" : "empty",
@@ -12304,7 +12629,7 @@ const createTasksRequestSchema = requestSchema()(object({
12304
12629
  assignee: string().optional().describe("`@handle`: yourself to start in_progress, or (owner/admin) someone else to reserve a todo."),
12305
12630
  idempotencyKey: string().optional().describe("One key per logical create; generated when omitted and returned. Repeat the same request with the same key within 24 hours to retry without creating the tasks twice.")
12306
12631
  }));
12307
- async function createTasks(client, request) {
12632
+ async function createTasks(client, request, options = {}) {
12308
12633
  const invalid = validateOpRequest(createTasksRequestSchema, request);
12309
12634
  if (invalid) return invalid;
12310
12635
  if (!request.target?.trim() || !request.tasks?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and at least one task title are required." }));
@@ -12329,15 +12654,15 @@ async function createTasks(client, request) {
12329
12654
  target: request.target,
12330
12655
  idempotencyKey
12331
12656
  },
12332
- next: first ? {
12333
- kind: "post_in_task_thread",
12334
- command: `raft message send --target "${agentTaskThreadTarget(request.target, first.messageId)}"`,
12335
- args: { thread: agentTaskThreadTarget(request.target, first.messageId) },
12336
- why: "Follow up in each task's thread."
12337
- } : null,
12338
- text: formatAgentTasksCreated(request.target, data)
12657
+ next: first ? taskThreadStep(request.target, first.messageId, "Follow up in each task's thread.", options.hints) : null,
12658
+ text: formatAgentTasksCreated(request.target, data, options.hints)
12339
12659
  };
12340
12660
  }
12661
+ /** Post in a task's thread (a send: `content` is the caller's). */
12662
+ function taskThreadStep(target, messageId, why, style = "cli") {
12663
+ const thread = agentTaskThreadTarget(target, messageId);
12664
+ return hintStep("post_in_task_thread", RAFT_HINTS.messageSend({ target: thread }), why, style, { target: thread });
12665
+ }
12341
12666
  const taskRefFields = {
12342
12667
  target: taskChannelSchema,
12343
12668
  taskNumber: taskNumberSchema
@@ -12427,22 +12752,17 @@ const updateTaskStatusRequestSchema = requestSchema()(object({
12427
12752
  status: raftTaskStatusSchema.describe("todo → in_progress → in_review → done; closed from anywhere.")
12428
12753
  }));
12429
12754
  /** A held task write: the interrupt whose resume is the identical command; nothing to cancel. */
12430
- function heldTaskWrite(target, data, action, kind, argv) {
12431
- const interrupt = heldTaskInterrupt(target, data, action, "After reviewing, repeat the operation if it is still correct.", argv);
12755
+ function heldTaskWrite(target, data, action, kind, argv, style) {
12756
+ const interrupt = heldTaskInterrupt(target, data, action, "After reviewing, repeat the operation if it is still correct.", argv, style);
12432
12757
  return {
12433
12758
  ok: true,
12434
12759
  state: "interrupted",
12435
12760
  interrupt,
12436
- next: {
12437
- kind,
12438
- command: `raft message read --target "${target}"`,
12439
- args: { target },
12440
- why: "Unread messages in this channel may change the task; read them (frontier.recordHeld(interrupt) once the model saw them), then resume (interrupt.resume) if it is still right."
12441
- },
12761
+ next: hintStep(kind, RAFT_HINTS.messageRead({ target }), "Unread messages in this channel may change the task; read them (frontier.recordHeld(interrupt) once the model saw them), then resume (interrupt.resume) if it is still right.", style, { target }),
12442
12762
  text: interrupt.context
12443
12763
  };
12444
12764
  }
12445
- async function updateTaskStatus(client, request) {
12765
+ async function updateTaskStatus(client, request, options = {}) {
12446
12766
  const invalid = requireTaskRef(request, updateTaskStatusRequestSchema);
12447
12767
  if (invalid) return invalid;
12448
12768
  const result = await client.tasks.updateStatus({
@@ -12451,7 +12771,7 @@ async function updateTaskStatus(client, request) {
12451
12771
  status: request.status
12452
12772
  });
12453
12773
  if (!result.ok) return failureFromClientResult(result);
12454
- if (isHeldResponse(result.data)) return heldTaskWrite(request.target, result.data, "The status change was not applied.", "retry_update_status", taskUpdateArgv(request.target, request.taskNumber, request.status));
12774
+ if (isHeldResponse(result.data)) return heldTaskWrite(request.target, result.data, "The status change was not applied.", "retry_update_status", taskUpdateArgv(request.target, request.taskNumber, request.status), options.hints ?? "cli");
12455
12775
  return {
12456
12776
  ok: true,
12457
12777
  state: "updated",
@@ -12480,7 +12800,7 @@ function taskAmendArgv(request) {
12480
12800
  ...request.description === void 0 ? [] : request.description === null ? ["--clear-description"] : ["--description", request.description]
12481
12801
  ];
12482
12802
  }
12483
- async function amendTask(client, request) {
12803
+ async function amendTask(client, request, options = {}) {
12484
12804
  const invalid = requireTaskRef(request, amendTaskRequestSchema);
12485
12805
  if (invalid) return invalid;
12486
12806
  if (request.title === void 0 && request.description === void 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a new title, a new description, or description: null to clear it." }));
@@ -12491,7 +12811,7 @@ async function amendTask(client, request) {
12491
12811
  ...request.description === void 0 ? {} : { description: request.description }
12492
12812
  });
12493
12813
  if (!result.ok) return failureFromClientResult(result);
12494
- if (isHeldResponse(result.data)) return heldTaskWrite(request.target, result.data, "The amendment was not applied.", "retry_amend", taskAmendArgv(request));
12814
+ if (isHeldResponse(result.data)) return heldTaskWrite(request.target, result.data, "The amendment was not applied.", "retry_amend", taskAmendArgv(request), options.hints ?? "cli");
12495
12815
  return {
12496
12816
  ok: true,
12497
12817
  state: "amended",
@@ -12528,7 +12848,7 @@ async function taskHistory(client, request) {
12528
12848
  * and picks the task; a miss says whether the Server asserted the list is
12529
12849
  * complete, exactly as the CLI does.
12530
12850
  */
12531
- async function showTask(client, request) {
12851
+ async function showTask(client, request, options = {}) {
12532
12852
  const invalid = requireTaskRef(request);
12533
12853
  if (invalid) return invalid;
12534
12854
  const { target, taskNumber } = request;
@@ -12541,7 +12861,7 @@ async function showTask(client, request) {
12541
12861
  const task = tasks.find((candidate) => candidate.taskNumber === taskNumber);
12542
12862
  if (!task) return failureOutcome(opError("NOT_FOUND", {
12543
12863
  message: result.data.pagination?.mode === "complete" && result.data.pagination.truncated === false ? `task #${taskNumber} not found in ${target} (searched ${tasks.length} task(s), status=all; server asserts this list is complete)` : tasks.length === 0 ? `task #${taskNumber} not found in ${target}: the server returned 0 tasks and did not assert the list is complete. That can mean the channel has no tasks, or that the server failed to read them (it currently reports some read errors as an empty list), and this command cannot tell which — so this is not evidence that task #${taskNumber} does not exist` : `task #${taskNumber} not found in ${target} (searched ${tasks.length} task(s), status=all; this surface does NOT assert completeness — so this is "absent from what was returned", not "does not exist")`,
12544
- nextAction: `Check the number with \`raft task list --target "${target}" --status all\`.`
12864
+ nextAction: `Check the number with \`${formatHint(RAFT_HINTS.taskListAll(target), options.hints)}\`.`
12545
12865
  }));
12546
12866
  return {
12547
12867
  ok: true,
@@ -12558,7 +12878,7 @@ const convertMessageToTaskRequestSchema = requestSchema()(object({
12558
12878
  target: taskChannelSchema,
12559
12879
  messageId: string().describe("Full or short id of a top-level message in that channel.")
12560
12880
  }));
12561
- async function convertMessageToTask(client, request) {
12881
+ async function convertMessageToTask(client, request, options = {}) {
12562
12882
  const invalid = validateOpRequest(convertMessageToTaskRequestSchema, request);
12563
12883
  if (invalid) return invalid;
12564
12884
  if (!request.target?.trim() || !request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a message id are required." }));
@@ -12575,13 +12895,8 @@ async function convertMessageToTask(client, request) {
12575
12895
  target: request.target,
12576
12896
  task
12577
12897
  },
12578
- next: {
12579
- kind: "post_in_task_thread",
12580
- command: `raft message send --target "${agentTaskThreadTarget(request.target, task.messageId)}"`,
12581
- args: { thread: agentTaskThreadTarget(request.target, task.messageId) },
12582
- why: "Follow up in the task's thread; it is unassigned until someone claims it."
12583
- },
12584
- text: formatAgentTaskConverted(request.target, task)
12898
+ next: taskThreadStep(request.target, task.messageId, "Follow up in the task's thread; it is unassigned until someone claims it.", options.hints),
12899
+ text: formatAgentTaskConverted(request.target, task, options.hints)
12585
12900
  };
12586
12901
  }
12587
12902
  async function deleteTask(client, request) {
@@ -12811,7 +13126,7 @@ function formatCurrentAgent(data) {
12811
13126
  return `${lines.join("\n")}\n\n`;
12812
13127
  }
12813
13128
  /** Server overview: runtime context, channels, agents, humans. */
12814
- function formatAgentServerInfo(data) {
13129
+ function formatAgentServerInfo(data, style = "cli") {
12815
13130
  let text = "## Server\n\n";
12816
13131
  const channels = data.channels ?? [];
12817
13132
  const agents = data.agents ?? [];
@@ -12819,8 +13134,14 @@ function formatAgentServerInfo(data) {
12819
13134
  text += formatRuntimeContext(data.runtimeContext);
12820
13135
  text += formatCurrentAgent(data);
12821
13136
  text += "### Channels\n";
12822
- text += "Visible public channels may appear even when `joined=false`. Private channels are shown only when you are a member; do not disclose private-channel names, membership, or content outside that channel. Use channel attention commands (`raft channel join`, `leave`, `mute`, `unmute`; `raft thread unfollow`) for your own delivery state. Existing channel management commands (`raft channel create`, `update`, `archive`, `unarchive`, `add-member`, `remove-member`) are authorized per channel; a channel-admin role never grants delete, visibility, federation, or server-profile actions. There is no Agent command for changing channel roles. Run any subcommand with `--help` for syntax.\n";
12823
- text += "Server-profile changes still use raft server update and remain server-role gated.\n";
13137
+ text += "Visible public channels may appear even when `joined=false`. Private channels are shown only when you are a member; do not disclose private-channel names, membership, or content outside that channel. ";
13138
+ text += style === "cli" ? `Use channel attention commands (\`${formatHintName(RAFT_HINTS.channelJoinName())}\`, \`leave\`, \`mute\`, \`unmute\`; \`${formatHintName(RAFT_HINTS.threadUnfollowName())}\`) for your own delivery state. Existing channel management commands (\`${formatHintName(RAFT_HINTS.channelCreateName())}\`, \`update\`, \`archive\`, \`unarchive\`, \`add-member\`, \`remove-member\`) are authorized per channel; a channel-admin role never grants delete, visibility, federation, or server-profile actions. There is no Agent command for changing channel roles. Run any subcommand with \`--help\` for syntax.\n` : `Use the channel attention tools (${[
13139
+ RAFT_HINTS.channelJoinName(),
13140
+ RAFT_HINTS.channelLeaveName(),
13141
+ RAFT_HINTS.channelMuteName(),
13142
+ RAFT_HINTS.channelUnmuteName()
13143
+ ].map((hint) => `\`${formatHintName(hint, style)}\``).join(", ")}; \`${formatHintName(RAFT_HINTS.threadUnfollowName(), style)}\`) for your own delivery state. Channel management (create, update, archive, unarchive, add-member, remove-member) has no tool: ${RAFT_NO_TOOL_WORDING}; a channel-admin role never grants delete, visibility, federation, or server-profile actions. There is no tool for changing channel roles.\n`;
13144
+ text += style === "cli" ? `Server-profile changes still use ${formatHintName(RAFT_HINTS.serverUpdateName())} and remain server-role gated.\n` : `Server-profile changes have no tool and remain server-role gated: ${RAFT_NO_TOOL_WORDING}.\n`;
12824
13145
  text += "Mute state is shown when the server provides it; otherwise it is omitted.\n";
12825
13146
  if (channels.length > 0) for (const t of channels) {
12826
13147
  const statusParts = [channelVisibility(t), t.joined ? "joined" : "not joined"];
@@ -12843,7 +13164,8 @@ function formatAgentServerInfo(data) {
12843
13164
  }
12844
13165
  else text += " (none)\n";
12845
13166
  text += "\n### Humans\n";
12846
- text += "To start a new DM: raft message send --target \"dm:@name\" <<'RAFTMSG' followed by the message body and RAFTMSG. To reply in an existing DM: reuse the target from received messages.\n";
13167
+ const newDm = formatHint(RAFT_HINTS.messageSend({ target: "dm:@name" }), style);
13168
+ text += style === "cli" ? `To start a new DM: ${newDm} <<'RAFTMSG' followed by the message body and RAFTMSG. To reply in an existing DM: reuse the target from received messages.\n` : `To start a new DM: ${newDm}. To reply in an existing DM: reuse the target from received messages.\n`;
12847
13169
  text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
12848
13170
  if (humans.length > 0) for (const u of humans) {
12849
13171
  const role = roleLabel(u.role);
@@ -12883,7 +13205,7 @@ function formatPageFooter(page) {
12883
13205
  return `${lines.join("\n")}\n`;
12884
13206
  }
12885
13207
  /** Single channel detail block. */
12886
- function formatAgentChannelInfo(channel, memberCounts) {
13208
+ function formatAgentChannelInfo(channel, memberCounts, style = "cli") {
12887
13209
  const lines = ["## Channel", ""];
12888
13210
  lines.push(`Channel: ${agentChannelRef(channel.name, channel.type)}`);
12889
13211
  if (channel.id) lines.push(`ID: ${channel.id}`);
@@ -12903,11 +13225,11 @@ function formatAgentChannelInfo(channel, memberCounts) {
12903
13225
  lines.push(`Members: ${agents + humans} (${agents} agents, ${humans} humans)`);
12904
13226
  }
12905
13227
  lines.push("");
12906
- lines.push(`More: raft channel members "${agentChannelRef(channel.name, channel.type)}"`);
13228
+ lines.push(`More: ${formatHint(RAFT_HINTS.channelMembers(agentChannelRef(channel.name, channel.type)), style)}`);
12907
13229
  return `${lines.join("\n")}\n`;
12908
13230
  }
12909
13231
  /** Compact server summary. */
12910
- function formatAgentServerSummary(data) {
13232
+ function formatAgentServerSummary(data, style = "cli") {
12911
13233
  const channels = data.channels ?? [];
12912
13234
  const agents = data.agents ?? [];
12913
13235
  const humans = data.humans ?? [];
@@ -12920,13 +13242,15 @@ function formatAgentServerSummary(data) {
12920
13242
  `Humans: ${humans.length}`,
12921
13243
  "",
12922
13244
  "Narrow queries:",
12923
- "- raft server info --channels",
12924
- "- raft server info --agents",
12925
- "- raft server info --humans",
12926
- "- raft channel info <name>",
12927
- "- raft user info <name>",
13245
+ ...[
13246
+ RAFT_HINTS.serverInfo({ view: "channels" }),
13247
+ RAFT_HINTS.serverInfo({ view: "agents" }),
13248
+ RAFT_HINTS.serverInfo({ view: "humans" }),
13249
+ RAFT_HINTS.channelInfo(),
13250
+ RAFT_HINTS.userInfo()
13251
+ ].map((hint) => `- ${formatHint(hint, style)}`),
12928
13252
  "",
12929
- "Full dump: raft server info --full"
13253
+ `Full dump: ${formatHint(RAFT_HINTS.serverInfo({ view: "full" }), style)}`
12930
13254
  ].join("\n")}\n`;
12931
13255
  }
12932
13256
  /** Channel listing page. */
@@ -13207,7 +13531,7 @@ const unfollowThreadRequestSchema = requestSchema()(object({
13207
13531
  reason: string().optional().describe("Short reason, kept with the unfollow.")
13208
13532
  }));
13209
13533
  const INVALID_CHANNEL_TARGET = "Target must be a regular channel in the form '#channel-name'. DMs and thread targets are not supported.";
13210
- async function resolveRegularChannel(client, target) {
13534
+ async function resolveRegularChannel(client, target, options) {
13211
13535
  const name = parseRaftRegularChannelTarget$1(target ?? "");
13212
13536
  if (!name) return failureOutcome(opError("INVALID_REQUEST", { message: INVALID_CHANNEL_TARGET }));
13213
13537
  const info = await client.server.info();
@@ -13215,7 +13539,7 @@ async function resolveRegularChannel(client, target) {
13215
13539
  const channel = info.data.channels.find((candidate) => candidate.name === name);
13216
13540
  if (!channel) return failureOutcome(opError("NOT_FOUND", {
13217
13541
  message: `Channel not found: ${target}`,
13218
- nextAction: "List visible channels with `raft server info --channels`; private channels need a human to add you."
13542
+ nextAction: `List visible channels with \`${formatHint(RAFT_HINTS.serverInfo({ view: "channels" }), options.hints)}\`; private channels need a human to add you.`
13219
13543
  }));
13220
13544
  return {
13221
13545
  id: channel.id,
@@ -13223,7 +13547,7 @@ async function resolveRegularChannel(client, target) {
13223
13547
  joined: channel.joined
13224
13548
  };
13225
13549
  }
13226
- async function joinChannel(client, request) {
13550
+ async function joinChannel(client, request, options = {}) {
13227
13551
  const invalid = validateOpRequest(channelTargetRequestSchema, request);
13228
13552
  if (invalid) return invalid;
13229
13553
  const result = await joinRaftChannelByTarget$1(client, { target: request.target });
@@ -13249,19 +13573,14 @@ async function joinChannel(client, request) {
13249
13573
  target: result.data.target,
13250
13574
  channelId: result.data.channelId
13251
13575
  },
13252
- next: {
13253
- kind: "read_target",
13254
- command: `raft message read --target "${result.data.target}"`,
13255
- args: { target: result.data.target },
13256
- why: "Read the channel before posting."
13257
- },
13576
+ next: hintStep("read_target", RAFT_HINTS.messageRead({ target: result.data.target }), "Read the channel before posting.", options.hints, { target: result.data.target }),
13258
13577
  text: state === "joined" ? `Joined ${result.data.target}.` : `Already a member of ${result.data.target}.`
13259
13578
  };
13260
13579
  }
13261
- async function leaveChannel(client, request) {
13580
+ async function leaveChannel(client, request, options = {}) {
13262
13581
  const invalid = validateOpRequest(channelTargetRequestSchema, request);
13263
13582
  if (invalid) return invalid;
13264
- const channel = await resolveRegularChannel(client, request.target);
13583
+ const channel = await resolveRegularChannel(client, request.target, options);
13265
13584
  if ("ok" in channel) return channel;
13266
13585
  if (!channel.joined) return {
13267
13586
  ok: true,
@@ -13292,10 +13611,10 @@ async function leaveChannel(client, request) {
13292
13611
  function formatSeq(value) {
13293
13612
  return value == null ? "none" : String(value);
13294
13613
  }
13295
- async function setChannelMute(client, request, action) {
13614
+ async function setChannelMute(client, request, action, options) {
13296
13615
  const invalid = validateOpRequest(channelTargetRequestSchema, request);
13297
13616
  if (invalid) return invalid;
13298
- const channel = await resolveRegularChannel(client, request.target);
13617
+ const channel = await resolveRegularChannel(client, request.target, options);
13299
13618
  if ("ok" in channel) return channel;
13300
13619
  const result = action === "mute" ? await client.channels.mute({ channelId: channel.id }, {}) : await client.channels.unmute({ channelId: channel.id });
13301
13620
  if (!result.ok) return failureFromClientResult(result);
@@ -13330,11 +13649,11 @@ async function setChannelMute(client, request, action) {
13330
13649
  text: lines.join("\n")
13331
13650
  };
13332
13651
  }
13333
- function muteChannel(client, request) {
13334
- return setChannelMute(client, request, "mute");
13652
+ function muteChannel(client, request, options = {}) {
13653
+ return setChannelMute(client, request, "mute", options);
13335
13654
  }
13336
- function unmuteChannel(client, request) {
13337
- return setChannelMute(client, request, "unmute");
13655
+ function unmuteChannel(client, request, options = {}) {
13656
+ return setChannelMute(client, request, "unmute", options);
13338
13657
  }
13339
13658
  async function channelMembers(client, request) {
13340
13659
  const invalid = validateOpRequest(channelMembersRequestSchema, request);
@@ -13384,7 +13703,7 @@ const channelInfoRequestSchema = requestSchema()(object({ target: string().descr
13384
13703
  * `raft channel info <target>`: the channel's facts from `server.info`, plus
13385
13704
  * member counts from its roster when the Server shows it.
13386
13705
  */
13387
- async function channelInfo(client, request) {
13706
+ async function channelInfo(client, request, options = {}) {
13388
13707
  const invalid = validateOpRequest(channelInfoRequestSchema, request);
13389
13708
  if (invalid) return invalid;
13390
13709
  const trimmed = request.target.trim();
@@ -13396,7 +13715,10 @@ async function channelInfo(client, request) {
13396
13715
  const channel = info.data.channels.find((candidate) => candidate.name === name);
13397
13716
  if (!channel) return failureOutcome(opError("NOT_FOUND", {
13398
13717
  message: `Channel not found or not visible: ${input}`,
13399
- nextAction: "Run `raft server info --channels --query <name>` to inspect visible channels, or ask a channel member to add you if this is private."
13718
+ nextAction: `Run \`${formatHint(RAFT_HINTS.serverInfo({
13719
+ view: "channels",
13720
+ query: true
13721
+ }), options.hints)}\` to inspect visible channels, or ask a channel member to add you if this is private.`
13400
13722
  }));
13401
13723
  const members = await client.channels.members({ channel: `#${name}` });
13402
13724
  const memberCounts = members.ok ? {
@@ -13411,7 +13733,7 @@ async function channelInfo(client, request) {
13411
13733
  memberCounts
13412
13734
  },
13413
13735
  next: null,
13414
- text: formatAgentChannelInfo(channel, memberCounts)
13736
+ text: formatAgentChannelInfo(channel, memberCounts, options.hints)
13415
13737
  };
13416
13738
  }
13417
13739
  //#endregion
@@ -13426,45 +13748,54 @@ const serverInfoRequestSchema = requestSchema()(object({
13426
13748
  ]).optional().describe("summary (default): counts; full: the whole overview; channels / agents / humans: one paged section."),
13427
13749
  offset: number$1().optional().describe("Section paging: rows to skip."),
13428
13750
  limit: number$1().optional().describe("Section paging: rows per page (default 50)."),
13429
- joined: boolean().optional().describe("channels view only: only channels you have joined.")
13751
+ joined: boolean().optional().describe("channels view only: only channels you have joined."),
13752
+ query: string().optional().describe("channels / agents / humans view only: keep rows whose name, description, or other visible text contains this (case-insensitive).")
13430
13753
  }));
13431
13754
  const showProfileRequestSchema = requestSchema()(object({ target: string().optional().describe("`@handle` of someone else; omit for your own profile.") }));
13432
13755
  /** The Agent API's profile body schema; at least one field is required (checked by the operation). */
13433
13756
  const updateProfileRequestSchema = agentApiProfileUpdateBodySchema;
13434
- function nextCommand(section, request, offset, limit, total) {
13757
+ /** The next page of a section, or null on the last page (`--query` / `--joined` carried, in the CLI's order). */
13758
+ function nextPageArgs(section, request, offset, limit, total) {
13435
13759
  const nextOffset = offset + limit;
13436
- if (nextOffset >= total) return void 0;
13437
- const parts = [
13438
- "raft server info",
13439
- `--${section}`,
13440
- `--offset ${nextOffset}`,
13441
- `--limit ${limit}`
13442
- ];
13443
- if (section === "channels" && request.joined) parts.push("--joined");
13444
- return parts.join(" ");
13760
+ if (nextOffset >= total) return null;
13761
+ const query = request.query?.trim() || void 0;
13762
+ const joined = section === "channels" && request.joined === true ? true : void 0;
13763
+ return {
13764
+ view: section,
13765
+ offset: nextOffset,
13766
+ limit,
13767
+ ...query === void 0 ? {} : { query },
13768
+ ...joined ? { joined } : {}
13769
+ };
13770
+ }
13771
+ /** The CLI's `--query` match: any string field contains the needle, case-insensitively. */
13772
+ function includesQuery(row, query) {
13773
+ const needle = query?.trim().toLowerCase();
13774
+ if (!needle) return true;
13775
+ return Object.values(row).some((value) => typeof value === "string" && value.toLowerCase().includes(needle));
13445
13776
  }
13446
- async function serverInfo(client, request = {}) {
13777
+ async function serverInfo(client, request = {}, options = {}) {
13447
13778
  const invalid = validateOpRequest(serverInfoRequestSchema, request);
13448
13779
  if (invalid) return invalid;
13780
+ const style = options.hints ?? "cli";
13449
13781
  const result = await client.server.info();
13450
13782
  if (!result.ok) return failureFromClientResult(result);
13451
13783
  const server = result.data;
13452
13784
  const view = request.view ?? "summary";
13453
- if (view === "summary") return {
13454
- ok: true,
13455
- state: "info",
13456
- data: {
13457
- view,
13458
- server,
13459
- page: null
13460
- },
13461
- next: {
13462
- kind: "list_channels",
13463
- command: "raft server info --channels",
13464
- why: "The summary only counts; list a section to see names."
13465
- },
13466
- text: formatAgentServerSummary(server)
13467
- };
13785
+ if (view === "summary") {
13786
+ const next = hintStep("list_channels", RAFT_HINTS.serverInfo({ view: "channels" }), "The summary only counts; list a section to see names.", style);
13787
+ return {
13788
+ ok: true,
13789
+ state: "info",
13790
+ data: {
13791
+ view,
13792
+ server,
13793
+ page: null
13794
+ },
13795
+ next,
13796
+ text: formatAgentServerSummary(server, style)
13797
+ };
13798
+ }
13468
13799
  if (view === "full") return {
13469
13800
  ok: true,
13470
13801
  state: "info",
@@ -13474,30 +13805,23 @@ async function serverInfo(client, request = {}) {
13474
13805
  page: null
13475
13806
  },
13476
13807
  next: null,
13477
- text: formatAgentServerInfo(server)
13808
+ text: formatAgentServerInfo(server, style)
13478
13809
  };
13479
13810
  const limit = Math.max(1, Math.trunc(request.limit ?? 50));
13480
13811
  const offset = Math.max(0, Math.trunc(request.offset ?? 0));
13481
- const rows = view === "channels" ? server.channels.filter((c) => !request.joined || c.joined) : view === "agents" ? server.agents : server.humans;
13812
+ const rows = (view === "channels" ? server.channels.filter((c) => !request.joined || c.joined) : view === "agents" ? server.agents : server.humans).filter((row) => includesQuery(row, request.query));
13482
13813
  const pageRows = rows.slice(offset, offset + limit);
13814
+ const nextArgs = nextPageArgs(view, request, offset, limit, rows.length);
13815
+ const nextHint = nextArgs ? RAFT_HINTS.serverInfo(nextArgs) : null;
13483
13816
  const page = {
13484
13817
  section: view,
13485
13818
  total: rows.length,
13486
13819
  offset,
13487
13820
  limit,
13488
- nextCommand: nextCommand(view, request, offset, limit, rows.length)
13821
+ nextCommand: nextHint ? formatHint(nextHint, style) : void 0
13489
13822
  };
13490
13823
  const text = view === "channels" ? formatAgentServerChannels(pageRows, page) : view === "agents" ? formatAgentServerAgents(pageRows, page) : formatAgentServerHumans(pageRows, page);
13491
- const next = page.nextCommand ? {
13492
- kind: "next_page",
13493
- command: page.nextCommand,
13494
- args: {
13495
- view,
13496
- offset: offset + limit,
13497
- limit
13498
- },
13499
- why: "More rows exist; one page is one page."
13500
- } : null;
13824
+ const next = nextArgs && nextHint ? hintStep("next_page", nextHint, "More rows exist; one page is one page.", style, nextArgs) : null;
13501
13825
  return {
13502
13826
  ok: true,
13503
13827
  state: "info",
@@ -13547,7 +13871,7 @@ const userInfoRequestSchema = requestSchema()(object({
13547
13871
  * their memberships among one page of the visible channels, checked one
13548
13872
  * channel roster at a time (a rejected roster is skipped and counted).
13549
13873
  */
13550
- async function userInfo(client, request) {
13874
+ async function userInfo(client, request, options = {}) {
13551
13875
  const invalid = validateOpRequest(userInfoRequestSchema, request);
13552
13876
  if (invalid) return invalid;
13553
13877
  const trimmed = request.name.trim();
@@ -13568,7 +13892,13 @@ async function userInfo(client, request) {
13568
13892
  } : null;
13569
13893
  if (!user) return failureOutcome(opError("NOT_FOUND", {
13570
13894
  message: `User not found or not visible: @${name}`,
13571
- nextAction: "Run `raft server info --agents --query <name>` or `raft server info --humans --query <name>` to inspect visible users."
13895
+ nextAction: `Run \`${formatHint(RAFT_HINTS.serverInfo({
13896
+ view: "agents",
13897
+ query: true
13898
+ }), options.hints)}\` or \`${formatHint(RAFT_HINTS.serverInfo({
13899
+ view: "humans",
13900
+ query: true
13901
+ }), options.hints)}\` to inspect visible users.`
13572
13902
  }));
13573
13903
  const visibleChannels = info.data.channels;
13574
13904
  const memberships = [];
@@ -13587,22 +13917,22 @@ async function userInfo(client, request) {
13587
13917
  });
13588
13918
  }
13589
13919
  const nextOffset = offset + limit;
13920
+ const nextHint = nextOffset < visibleChannels.length ? RAFT_HINTS.userInfo({
13921
+ name,
13922
+ offset: nextOffset,
13923
+ limit
13924
+ }) : null;
13590
13925
  const page = {
13591
13926
  total: visibleChannels.length,
13592
13927
  offset,
13593
13928
  limit,
13594
- nextCommand: nextOffset < visibleChannels.length ? `raft user info @${name} --offset ${nextOffset} --limit ${limit}` : void 0
13929
+ nextCommand: nextHint ? formatHint(nextHint, options.hints) : void 0
13595
13930
  };
13596
- const next = page.nextCommand ? {
13597
- kind: "next_page",
13598
- command: page.nextCommand,
13599
- args: {
13600
- name: `@${name}`,
13601
- offset: nextOffset,
13602
- limit
13603
- },
13604
- why: "Only one page of visible channels was inspected for memberships."
13605
- } : null;
13931
+ const next = nextHint ? hintStep("next_page", nextHint, "Only one page of visible channels was inspected for memberships.", options.hints, {
13932
+ name: `@${name}`,
13933
+ offset: nextOffset,
13934
+ limit
13935
+ }) : null;
13606
13936
  return {
13607
13937
  ok: true,
13608
13938
  state: "info",
@@ -13619,8 +13949,9 @@ async function userInfo(client, request) {
13619
13949
  //#endregion
13620
13950
  //#region ../shared/src/agentText/attachments.ts
13621
13951
  /** Upload receipt with attachment id and send-usage hint. */
13622
- function formatAgentAttachmentUploaded(attachment) {
13623
- return `File uploaded: ${attachment.filename} (${(attachment.sizeBytes / 1024).toFixed(1)}KB)\nAttachment ID: ${attachment.id}\n\nUse this ID with raft message send --attachment-id ${attachment.id} to include it in a message.\n`;
13952
+ function formatAgentAttachmentUploaded(attachment, style = "cli") {
13953
+ const send = formatHint(RAFT_HINTS.messageSend({ attachmentId: attachment.id }), style);
13954
+ return `File uploaded: ${attachment.filename} (${(attachment.sizeBytes / 1024).toFixed(1)}KB)\nAttachment ID: ${attachment.id}\n\nUse this ID with ${send} to include it in a message.\n`;
13624
13955
  }
13625
13956
  function anchorSummary(anchor) {
13626
13957
  if (anchor.type === "md-section") {
@@ -13662,6 +13993,7 @@ const attachmentCommentsRequestSchema = requestSchema()(object({
13662
13993
  attachmentId: string().describe("The attachment id."),
13663
13994
  limit: number$1().int().positive().optional().describe("Maximum comments to return.")
13664
13995
  }));
13996
+ const downloadAttachmentUrlRequestSchema = requestSchema()(object({ attachmentId: string().describe("The attachment id, as message lines show it (`id:…`).") }));
13665
13997
  /** Compatibility fallback for Servers that predate the capability endpoint (the CLI's constant). */
13666
13998
  const AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES = 52428800;
13667
13999
  const FILENAME_MIME_MAP = {
@@ -13714,7 +14046,7 @@ function inferAttachmentMimeType(filename, bytes, explicit) {
13714
14046
  * `POST /upload` below the Server's direct-upload threshold, an upload session
13715
14047
  * (create → PUT to a presigned URL → complete) at or above it.
13716
14048
  */
13717
- async function uploadAttachment(client, transport, request) {
14049
+ async function uploadAttachment(client, transport, request, options = {}) {
13718
14050
  if (!request.target?.trim() || !request.filename?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and a filename are required to upload." }));
13719
14051
  if (!(request.bytes instanceof Uint8Array) || request.bytes.byteLength === 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Refusing to upload a 0-byte attachment." }));
13720
14052
  if (request.mimeType !== void 0 && !MIME_TYPE_RE.test(request.mimeType.trim())) return failureOutcome(opError("INVALID_REQUEST", { message: `mimeType must look like type/subtype, got: ${request.mimeType}` }));
@@ -13726,7 +14058,7 @@ async function uploadAttachment(client, transport, request) {
13726
14058
  if (!resolved.ok) return failureFromClientResult(resolved);
13727
14059
  const channelId = resolved.data.channelId;
13728
14060
  const mimeType = inferAttachmentMimeType(request.filename, request.bytes, request.mimeType);
13729
- if (threshold !== null && request.bytes.byteLength >= threshold) return uploadThroughSession(client, transport, request, channelId, mimeType);
14061
+ if (threshold !== null && request.bytes.byteLength >= threshold) return uploadThroughSession(client, transport, request, channelId, mimeType, options);
13730
14062
  const copy = new Uint8Array(request.bytes.byteLength);
13731
14063
  copy.set(request.bytes);
13732
14064
  const form = new FormData();
@@ -13766,9 +14098,9 @@ async function uploadAttachment(client, transport, request) {
13766
14098
  }
13767
14099
  const parsed = agentApiContract.attachmentUpload.response.body.safeParse(body);
13768
14100
  if (!parsed.success) return failureOutcome(opError("INVALID_RESPONSE"));
13769
- return uploadedOutcome(request.target, parsed.data, mimeType);
14101
+ return uploadedOutcome(request.target, parsed.data, mimeType, options);
13770
14102
  }
13771
- function uploadedOutcome(target, data, mimeType) {
14103
+ function uploadedOutcome(target, data, mimeType, options) {
13772
14104
  return {
13773
14105
  ok: true,
13774
14106
  state: "uploaded",
@@ -13777,16 +14109,14 @@ function uploadedOutcome(target, data, mimeType) {
13777
14109
  target,
13778
14110
  mimeType: data.mimeType ?? mimeType
13779
14111
  },
13780
- next: {
13781
- kind: "send_with_attachment",
13782
- command: `raft message send --target "${target}" --attachment-id ${data.id}`,
13783
- args: {
13784
- target,
13785
- attachmentIds: [data.id]
13786
- },
13787
- why: "The upload alone posts nothing; send a message that links the attachment id."
13788
- },
13789
- text: formatAgentAttachmentUploaded(data)
14112
+ next: hintStep("send_with_attachment", RAFT_HINTS.messageSend({
14113
+ target,
14114
+ attachmentId: data.id
14115
+ }), "The upload alone posts nothing; send a message that links the attachment id.", options.hints, {
14116
+ target,
14117
+ attachmentIds: [data.id]
14118
+ }),
14119
+ text: formatAgentAttachmentUploaded(data, options.hints)
13790
14120
  };
13791
14121
  }
13792
14122
  const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -13797,7 +14127,7 @@ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13797
14127
  * verifies against the object store. A PUT that definitely failed cancels the
13798
14128
  * session; a PUT whose outcome is unknown leaves it for completion to verify.
13799
14129
  */
13800
- async function uploadThroughSession(client, transport, request, channelId, mimeType) {
14130
+ async function uploadThroughSession(client, transport, request, channelId, mimeType, options) {
13801
14131
  const created = await client.attachments.createUploadSession({
13802
14132
  channelId,
13803
14133
  filename: request.filename,
@@ -13844,7 +14174,7 @@ async function uploadThroughSession(client, transport, request, channelId, mimeT
13844
14174
  const completed = await client.attachments.completeUploadSession({ uploadId });
13845
14175
  if (completed.ok) {
13846
14176
  const attachment = completed.data.attachment;
13847
- return uploadedOutcome(request.target, attachment, mimeType);
14177
+ return uploadedOutcome(request.target, attachment, mimeType, options);
13848
14178
  }
13849
14179
  const code = completed.error.kind === "http" ? completed.error.errorCode : null;
13850
14180
  if (!(code === "UPLOAD_OBJECT_NOT_FOUND" || code === "UPLOAD_VERIFICATION_IN_PROGRESS") || attempt === 2) return failureFromClientResult(completed);
@@ -13868,6 +14198,46 @@ async function downloadAttachment(client, request) {
13868
14198
  text: `Downloaded attachment ${request.attachmentId.slice(0, 8)} (${bytes.byteLength} bytes).`
13869
14199
  };
13870
14200
  }
14201
+ /**
14202
+ * Mint a short-lived URL for an attachment's bytes, for runtimes whose tools
14203
+ * cannot return binary data: the runtime (not the model) fetches `url` before
14204
+ * `expiresAt`. The URL is a bearer capability; do not log it. A Server whose
14205
+ * storage cannot presign answers 409 `download_url_unavailable`; that failure's
14206
+ * `next` points at the binary download (`attachments.download`).
14207
+ */
14208
+ async function downloadAttachmentUrl(client, request, options = {}) {
14209
+ const invalid = validateOpRequest(downloadAttachmentUrlRequestSchema, request);
14210
+ if (invalid) return invalid;
14211
+ const attachmentId = request.attachmentId?.trim();
14212
+ if (!attachmentId) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
14213
+ const result = await client.attachments.downloadUrl({ attachmentId });
14214
+ if (!result.ok) {
14215
+ const failure = failureFromClientResult(result);
14216
+ if (failure.error.serverCode !== "download_url_unavailable") return failure;
14217
+ const download = RAFT_HINTS.attachmentDownload(attachmentId);
14218
+ const nextAction = `This Server's storage cannot mint download URLs; download the bytes instead: \`${formatHint(download, options.hints)}\`.`;
14219
+ return {
14220
+ ...failureOutcome({
14221
+ ...failure.error,
14222
+ nextAction
14223
+ }),
14224
+ next: hintStep("download_bytes", download, nextAction, options.hints, { attachmentId })
14225
+ };
14226
+ }
14227
+ const { url, expiresAt, filename, mimeType } = result.data;
14228
+ return {
14229
+ ok: true,
14230
+ state: "url",
14231
+ data: {
14232
+ url,
14233
+ expiresAt,
14234
+ filename,
14235
+ mimeType
14236
+ },
14237
+ next: null,
14238
+ text: `Download URL for ${filename} (${mimeType}), valid until ${expiresAt}:\n${url}`
14239
+ };
14240
+ }
13871
14241
  async function attachmentComments(client, request) {
13872
14242
  const invalid = validateOpRequest(attachmentCommentsRequestSchema, request);
13873
14243
  if (invalid) return invalid;
@@ -14016,14 +14386,15 @@ function renderSearchPreview(content, query) {
14016
14386
  ].join("");
14017
14387
  }
14018
14388
  /** Search results with <match>/<omit /> preview markup. */
14019
- function formatAgentSearchResults(query, data, offset, sort, limit) {
14389
+ function formatAgentSearchResults(query, data, offset, sort, limit, style = "cli") {
14020
14390
  const trimmedQuery = query.trim();
14391
+ const flag = (name) => formatHintFlag(name, name, style);
14021
14392
  const oldestShown = data.results?.length ? data.results[data.results.length - 1]?.createdAt : void 0;
14022
- const nextPageHint = sort === "recent" && oldestShown ? `page with --before ${oldestShown} (pages OLDER only; NOT a complete traversal: stored times are microsecond but this key is millisecond, so rows inside the boundary millisecond can be skipped, and a full page sharing one timestamp can repeat indefinitely; copy the key verbatim)` : `page with --offset ${(offset ?? 0) + (data.results?.length ?? 0)}`;
14393
+ const nextPageHint = sort === "recent" && oldestShown ? `page with ${flag("before")} ${oldestShown} (pages OLDER only; NOT a complete traversal: stored times are microsecond but this key is millisecond, so rows inside the boundary millisecond can be skipped, and a full page sharing one timestamp can repeat indefinitely; copy the key verbatim)` : `page with ${flag("offset")} ${(offset ?? 0) + (data.results?.length ?? 0)}`;
14023
14394
  const effectiveLimit = Math.min(limit ?? 20, 50);
14024
14395
  const countEqualsLimit = (data.results?.length ?? 0) === effectiveLimit;
14025
- const limitSource = limit === void 0 ? `the server default of ${effectiveLimit}` : limit > 50 ? `the server cap of ${effectiveLimit} (your --limit ${limit} was clamped)` : `the --limit ${effectiveLimit} that was requested`;
14026
- const atCapRemedy = effectiveLimit < 50 ? "re-run with a higher --limit to tell the two apart" : `this is already the server's maximum page, so completeness CANNOT be determined from this result: a higher --limit is clamped back to ${effectiveLimit} and paging will not reveal it; narrow the query (add --sender, --target, --after or --before) until fewer than ${effectiveLimit} results match`;
14396
+ const limitSource = limit === void 0 ? `the server default of ${effectiveLimit}` : limit > 50 ? `the server cap of ${effectiveLimit} (your ${flag("limit")} ${limit} was clamped)` : `the ${flag("limit")} ${effectiveLimit} that was requested`;
14397
+ const atCapRemedy = effectiveLimit < 50 ? `re-run with a higher ${flag("limit")} to tell the two apart` : `this is already the server's maximum page, so completeness CANNOT be determined from this result: a higher ${flag("limit")} is clamped back to ${effectiveLimit} and paging will not reveal it; narrow the query (add ${flag("sender")}, ${flag("target")}, ${flag("after")} or ${flag("before")}) until fewer than ${effectiveLimit} results match`;
14027
14398
  const truncation = data.hasMore === true ? `truncated=true · more results exist, ${nextPageHint}` : data.hasMore === false ? countEqualsLimit ? `truncated=unknown · server reported hasMore=false, but this page returned exactly ${limitSource}, which is also what a capped page returns; ${atCapRemedy}` : "truncated=false" : "truncated=unknown · server did not report hasMore";
14028
14399
  if (!data.results || data.results.length === 0) return `No search results. (${truncation})`;
14029
14400
  const formatted = data.results.map((result) => {
@@ -14072,7 +14443,7 @@ const reactRequestSchema = requestSchema()(object({
14072
14443
  messageId: string().describe("Full or short message id."),
14073
14444
  emoji: string().describe("One reaction emoji.")
14074
14445
  }));
14075
- async function searchMessages(client, request) {
14446
+ async function searchMessages(client, request, options = {}) {
14076
14447
  const invalid = validateOpRequest(searchMessagesRequestSchema, request);
14077
14448
  if (invalid) return invalid;
14078
14449
  if (!request.query?.trim() && !request.target && !request.sender) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a query, or filter by target or sender." }));
@@ -14094,11 +14465,16 @@ async function searchMessages(client, request) {
14094
14465
  results: data.results,
14095
14466
  hasMore
14096
14467
  };
14468
+ const nextArgs = {
14469
+ ...request,
14470
+ offset: (request.offset ?? 0) + data.results.length
14471
+ };
14097
14472
  const next = hasMore ? {
14098
14473
  kind: "next_search_page",
14099
- args: {
14100
- ...request,
14101
- offset: (request.offset ?? 0) + data.results.length
14474
+ args: nextArgs,
14475
+ operation: {
14476
+ name: "messages.search",
14477
+ args: nextArgs
14102
14478
  },
14103
14479
  why: "More results exist; page on, or narrow the query."
14104
14480
  } : null;
@@ -14110,31 +14486,32 @@ async function searchMessages(client, request) {
14110
14486
  text: formatAgentSearchResults(page.query, {
14111
14487
  results: data.results,
14112
14488
  ...hasMore === null ? {} : { hasMore }
14113
- }, request.offset, request.sort, request.limit)
14489
+ }, request.offset, request.sort, request.limit, options.hints)
14114
14490
  };
14115
14491
  }
14116
- async function resolveMessage(client, request) {
14492
+ async function resolveMessage(client, request, options = {}) {
14117
14493
  const invalid = validateOpRequest(resolveMessageRequestSchema, request);
14118
14494
  if (invalid) return invalid;
14119
14495
  if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
14120
14496
  const result = await client.messages.resolve({ msgId: request.messageId });
14121
14497
  if (!result.ok) return failureFromClientResult(result);
14122
- const message = projectRaftMessage(result.data.message);
14498
+ const message = projectRaftMessage(result.data.message, options.hints);
14123
14499
  if (!message) return failureOutcome(opError("INVALID_RESPONSE", { message: "The resolved message carries no conversation identity." }));
14124
14500
  return {
14125
14501
  ok: true,
14126
14502
  state: "message",
14127
14503
  data: message,
14128
- next: {
14129
- kind: "read_target",
14130
- command: `raft message read --target "${message.target}" --around ${message.shortId ?? request.messageId}`,
14131
- args: {
14132
- target: message.target,
14133
- around: message.id ?? request.messageId
14134
- },
14135
- why: "Read the surrounding context before acting on one message."
14136
- },
14137
- text: formatAgentMessages([toAgentMessageLike(message.raw)])
14504
+ next: hintStep("read_target", RAFT_HINTS.messageRead({
14505
+ target: message.target,
14506
+ around: {
14507
+ shown: message.shortId ?? request.messageId,
14508
+ id: message.id ?? request.messageId
14509
+ }
14510
+ }), "Read the surrounding context before acting on one message.", options.hints, {
14511
+ target: message.target,
14512
+ around: message.id ?? request.messageId
14513
+ }),
14514
+ text: formatAgentMessages([toAgentMessageLike(message.raw)], options.hints)
14138
14515
  };
14139
14516
  }
14140
14517
  async function reactToMessage(client, request, action = "add") {
@@ -14164,17 +14541,20 @@ function normalizeAgentMentionAction(action) {
14164
14541
  if (action === "add" || action === "invite") return "add";
14165
14542
  return null;
14166
14543
  }
14167
- function formatActionCommands(action) {
14544
+ function actionVerbs(action) {
14168
14545
  const verbs = action.availableActions.map(normalizeAgentMentionAction).filter((verb) => verb !== null);
14169
- return Array.from(new Set(verbs)).map((verb) => ` ${verb}: raft mention ${verb} ${action.resolutionId}`);
14546
+ return Array.from(new Set(verbs));
14547
+ }
14548
+ function formatActionCommands(action, style) {
14549
+ return actionVerbs(action).map((verb) => ` ${verb}: ${formatHint(RAFT_HINTS.mentionAction(verb, action.resolutionId), style)}`);
14170
14550
  }
14171
14551
  function formatAuthoredMentionToken(targetHandle) {
14172
14552
  return targetHandle.startsWith("@") ? targetHandle : `@${targetHandle}`;
14173
14553
  }
14174
14554
  const PENDING_MENTION_ACTION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14175
14555
  /** Per-token mention recovery command line; null when the id is not a UUID (fail closed). */
14176
- function formatAgentMentionNotifyRecoveryCommand(resolutionId) {
14177
- return PENDING_MENTION_ACTION_ID_RE.test(resolutionId) ? `raft mention notify ${resolutionId}` : null;
14556
+ function formatAgentMentionNotifyRecoveryCommand(resolutionId, style = "cli") {
14557
+ return PENDING_MENTION_ACTION_ID_RE.test(resolutionId) ? formatHint(RAFT_HINTS.mentionAction("notify", resolutionId), style) : null;
14178
14558
  }
14179
14559
  function toAgentSenderPendingMentionAction(action) {
14180
14560
  return {
@@ -14231,22 +14611,24 @@ function normalizeAgentMentionActionResults(data) {
14231
14611
  })).filter((item) => item.resolutionId.length > 0);
14232
14612
  }
14233
14613
  const PENDING_DEFAULT_LIMIT = 50;
14234
- function pendingPageVerdict(hasMore, limit, shown) {
14235
- const asked = limit === void 0 ? "server default 50" : `--limit ${limit}`;
14236
- if (hasMore === true) return (limit ?? PENDING_DEFAULT_LIMIT) >= 100 ? `shown ${shown}, ${asked} — truncated=true · more pending actions exist AND this is the server's maximum page (100); this route has no offset or cursor, so the rest cannot be reached from here — resolve what you can and re-run; rows with no available actions are not actionable here and will remain until they expire` : `shown ${shown}, ${asked} — truncated=true · more pending actions exist; raise --limit (server caps at 100) or resolve these first and re-run`;
14614
+ function pendingPageVerdict(hasMore, limit, shown, style) {
14615
+ const limitFlag = formatHintFlag("limit", "limit", style);
14616
+ const asked = limit === void 0 ? "server default 50" : `${limitFlag} ${limit}`;
14617
+ if (hasMore === true) return (limit ?? PENDING_DEFAULT_LIMIT) >= 100 ? `shown ${shown}, ${asked} — truncated=true · more pending actions exist AND this is the server's maximum page (100); this route has no offset or cursor, so the rest cannot be reached from here — resolve what you can and re-run; rows with no available actions are not actionable here and will remain until they expire` : `shown ${shown}, ${asked} — truncated=true · more pending actions exist; raise ${limitFlag} (server caps at 100) or resolve these first and re-run`;
14237
14618
  if (hasMore === false) return `shown ${shown}, ${asked} — truncated=false · this is the complete list`;
14238
14619
  return `shown ${shown}, ${asked} — truncated=unknown · server did not report has_more, so completeness is NOT asserted`;
14239
14620
  }
14240
14621
  /** Undelivered-mentions partial result (send) or the pending list. */
14241
14622
  function formatAgentPendingMentionActions(actions, opts = {}) {
14623
+ const style = opts.hints ?? "cli";
14242
14624
  const unresolvedMentionHandles = opts.source === "send" ? Array.from(new Set(opts.unresolvedMentionHandles ?? [])) : [];
14243
- const pageNote = opts.source === "pending" ? pendingPageVerdict(opts.hasMore, opts.limit, actions.length) : "";
14625
+ const pageNote = opts.source === "pending" ? pendingPageVerdict(opts.hasMore, opts.limit, actions.length, style) : "";
14244
14626
  if (actions.length === 0 && unresolvedMentionHandles.length === 0) return opts.source === "pending" ? `Pending mention actions\n\nNo pending mention actions. (${pageNote})\n` : "";
14245
14627
  if (opts.source === "send") {
14246
14628
  const lines = [
14247
14629
  "Undelivered mentions — partial result",
14248
14630
  "Message effect: status=queued. Queue acceptance is the only message proof.",
14249
- "Do not rerun `raft message send`; the message is already queued and a retry could duplicate it.",
14631
+ `Do not rerun \`${formatHintName(RAFT_HINTS.messageSendName(), style)}\`; the message is already queued and a retry could duplicate it.`,
14250
14632
  "Each row below is bound to the literal @token from your message.",
14251
14633
  "For a literal name rather than a recipient, wrap the @handle in inline or fenced code.",
14252
14634
  ""
@@ -14260,10 +14642,10 @@ function formatAgentPendingMentionActions(actions, opts = {}) {
14260
14642
  if (action.messageId) lines.push(` message: ${action.messageId}`);
14261
14643
  lines.push(` expires: ${action.expiresAt ?? "unknown"}`);
14262
14644
  if (action.recoveryCommand) {
14263
- lines.push(` recovery: ${action.recoveryCommand}`);
14645
+ lines.push(` recovery: ${style === "cli" ? action.recoveryCommand : formatAgentMentionNotifyRecoveryCommand(action.resolutionId, style)}`);
14264
14646
  lines.push(" note: the handle resolved, but the target was not in this conversation at send time. This does not prove the person left the server.");
14265
14647
  lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
14266
- } else lines.push(" recovery: unavailable because the pending action id is invalid; inspect `raft mention pending` without resending the message.");
14648
+ } else lines.push(` recovery: unavailable because the pending action id is invalid; inspect \`${formatHint(RAFT_HINTS.mentionPending(), style)}\` without resending the message.`);
14267
14649
  }
14268
14650
  for (const rawHandle of unresolvedMentionHandles) {
14269
14651
  const warning = toAgentSenderUnresolvedMentionWarning(rawHandle);
@@ -14287,11 +14669,11 @@ function formatAgentPendingMentionActions(actions, opts = {}) {
14287
14669
  if (action.messageId) lines.push(` message: ${action.messageId}`);
14288
14670
  lines.push(` reason: ${formatPendingReason(action.reason)}`);
14289
14671
  if (action.expiresAt) lines.push(` expires: ${action.expiresAt}`);
14290
- const commands = formatActionCommands(action);
14672
+ const commands = formatActionCommands(action, style);
14291
14673
  if (commands.length > 0) {
14292
14674
  lines.push(" recovery commands:");
14293
14675
  lines.push(...commands);
14294
- if (commands.some((command) => command.includes(" mention notify "))) lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
14676
+ if (actionVerbs(action).includes("notify")) lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
14295
14677
  }
14296
14678
  }
14297
14679
  return `${lines.join("\n")}\n`;
@@ -14347,7 +14729,7 @@ const executeMentionActionRequestSchema = requestSchema()(object({
14347
14729
  resolutionIds: array(string()).describe("resolutionId values from mentions.pending.")
14348
14730
  }));
14349
14731
  const senderMentionDeliveriesRequestSchema = requestSchema()(object({ messageId: string().describe("Id of a message you sent.") }));
14350
- async function pendingMentionActions(client, request = {}) {
14732
+ async function pendingMentionActions(client, request = {}, options = {}) {
14351
14733
  const invalid = validateOpRequest(pendingMentionActionsRequestSchema, request);
14352
14734
  if (invalid) return invalid;
14353
14735
  const result = await client.mentions.pendingActions(request.limit === void 0 ? {} : { limit: String(request.limit) });
@@ -14355,15 +14737,10 @@ async function pendingMentionActions(client, request = {}) {
14355
14737
  const actions = normalizeAgentPendingMentionActions(result.data);
14356
14738
  const hasMore = typeof result.data.has_more === "boolean" ? result.data.has_more : null;
14357
14739
  const first = actions.find((a) => a.availableActions.length > 0);
14358
- const next = first ? {
14359
- kind: "resolve_mention",
14360
- command: `raft mention notify ${first.resolutionId}`,
14361
- args: {
14362
- action: "notify",
14363
- resolutionIds: [first.resolutionId]
14364
- },
14365
- why: "This @mention reached nobody at send time; notify the target (or add them) so the message is seen."
14366
- } : null;
14740
+ const next = first ? hintStep("resolve_mention", RAFT_HINTS.mentionAction("notify", first.resolutionId), "This @mention reached nobody at send time; notify the target (or add them) so the message is seen.", options.hints, {
14741
+ action: "notify",
14742
+ resolutionIds: [first.resolutionId]
14743
+ }) : null;
14367
14744
  return {
14368
14745
  ok: true,
14369
14746
  state: actions.length > 0 ? "pending" : "empty",
@@ -14376,7 +14753,8 @@ async function pendingMentionActions(client, request = {}) {
14376
14753
  text: formatAgentPendingMentionActions(actions, {
14377
14754
  source: "pending",
14378
14755
  ...hasMore === null ? {} : { hasMore },
14379
- limit: request.limit
14756
+ limit: request.limit,
14757
+ hints: options.hints
14380
14758
  })
14381
14759
  };
14382
14760
  }
@@ -14474,7 +14852,7 @@ async function getManualTopic(client, request) {
14474
14852
  text: formatAgentKnowledgeStdout(result.data.content)
14475
14853
  };
14476
14854
  }
14477
- async function searchManual(client, request) {
14855
+ async function searchManual(client, request, options = {}) {
14478
14856
  const malformed = validateOpRequest(searchManualRequestSchema, request);
14479
14857
  if (malformed) return malformed;
14480
14858
  const invalid = requireContext(request);
@@ -14490,12 +14868,7 @@ async function searchManual(client, request) {
14490
14868
  const data = result.data;
14491
14869
  const results = data.results;
14492
14870
  const first = results[0];
14493
- const next = first ? {
14494
- kind: "read_manual_topic",
14495
- command: `raft manual get ${first.slug} --intent "…" --reason "…"`,
14496
- args: { topic: first.slug },
14497
- why: "Open the best-matching topic."
14498
- } : null;
14871
+ const next = first ? hintStep("read_manual_topic", RAFT_HINTS.manualGet(first.slug), "Open the best-matching topic.", options.hints, { topic: first.slug }) : null;
14499
14872
  return {
14500
14873
  ok: true,
14501
14874
  state: results.length > 0 ? "results" : "empty",
@@ -14696,29 +15069,26 @@ function formatAgentActionCardPosted(target, messageId) {
14696
15069
  * the preparer in the card's own thread; a card posted inside a thread has no
14697
15070
  * thread of its own, so the reply lands in that same thread.
14698
15071
  */
14699
- function awaitConfirmationNext(target, messageId) {
15072
+ function awaitConfirmationNext(target, messageId, style) {
14700
15073
  const short = messageId.slice(0, 8);
14701
- if (getParentTargetForThread(target) !== null) return {
14702
- kind: "await_confirmation",
14703
- command: `raft message read --target "${target}" --around ${short}`,
14704
- args: {
14705
- target,
14706
- messageId
14707
- },
14708
- why: "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in this thread that @mentions you; you do not need to poll."
14709
- };
15074
+ if (getParentTargetForThread(target) !== null) return hintStep("await_confirmation", RAFT_HINTS.messageRead({
15075
+ target,
15076
+ around: {
15077
+ shown: short,
15078
+ id: messageId
15079
+ }
15080
+ }), "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in this thread that @mentions you; you do not need to poll.", style, {
15081
+ target,
15082
+ around: messageId,
15083
+ messageId
15084
+ });
14710
15085
  const thread = agentTaskThreadTarget(target, messageId);
14711
- return {
14712
- kind: "await_confirmation",
14713
- command: `raft message read --target "${thread}"`,
14714
- args: {
14715
- target: thread,
14716
- messageId
14717
- },
14718
- why: "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in the card's thread that @mentions you; you do not need to poll."
14719
- };
15086
+ return hintStep("await_confirmation", RAFT_HINTS.messageRead({ target: thread }), "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in the card's thread that @mentions you; you do not need to poll.", style, {
15087
+ target: thread,
15088
+ messageId
15089
+ });
14720
15090
  }
14721
- async function prepareActionCard(client, request) {
15091
+ async function prepareActionCard(client, request, options = {}) {
14722
15092
  if (typeof request?.target !== "string" || !request.target.trim() || !request.action) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and an action are required to prepare a card." }));
14723
15093
  const invalid = validateOpRequest(prepareActionCardRequestSchema, request);
14724
15094
  if (invalid) return invalid;
@@ -14737,7 +15107,7 @@ async function prepareActionCard(client, request) {
14737
15107
  ok: true,
14738
15108
  state: "prepared",
14739
15109
  data: card,
14740
- next: awaitConfirmationNext(request.target, card.messageId),
15110
+ next: awaitConfirmationNext(request.target, card.messageId, options.hints ?? "cli"),
14741
15111
  text: formatAgentActionCardPosted(request.target, card.messageId)
14742
15112
  };
14743
15113
  }
@@ -15148,6 +15518,14 @@ const OPERATION_DEFS = [
15148
15518
  consumes: nothing,
15149
15519
  output: small
15150
15520
  },
15521
+ {
15522
+ name: "attachments.downloadUrl",
15523
+ description: "Get a short-lived (5 minute) URL for an attachment's bytes, with its filename and MIME type, for runtimes that fetch files themselves. The URL grants access to the file: do not post it in messages.",
15524
+ schema: downloadAttachmentUrlRequestSchema,
15525
+ routes: ["attachmentDownloadUrl"],
15526
+ consumes: nothing,
15527
+ output: small
15528
+ },
15151
15529
  {
15152
15530
  name: "attachments.comments",
15153
15531
  description: "List the comments on an attachment.",
@@ -15449,10 +15827,6 @@ const OPERATION_DEFS = [
15449
15827
  output: small
15450
15828
  }
15451
15829
  ];
15452
- /** `tasks.updateStatus` → `tasks_update_status`. */
15453
- function raftToolNameFor(name) {
15454
- return name.replace(/\./g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
15455
- }
15456
15830
  const IDEMPOTENCY_STRENGTH = {
15457
15831
  natural: 0,
15458
15832
  key: 1,
@@ -15524,11 +15898,17 @@ function createRaft(options) {
15524
15898
  const serverUrl = requireServerUrl(options.serverUrl);
15525
15899
  const authorization = `Bearer ${requireAgentCredential(options.credential)}`;
15526
15900
  const frontier = SeenFrontier.fromSnapshot(options.frontier);
15901
+ if (options.hints !== void 0 && options.hints !== "cli" && options.hints !== "tool") throw new TypeError("createRaft: hints must be \"cli\" or \"tool\".");
15902
+ const hints = options.hints ?? "cli";
15903
+ /** How every operation renders its hints. */
15904
+ const style = { hints };
15905
+ /** The SDK's default NOT_FOUND next action names a command; render it in the configured style. */
15906
+ const styled = (outcome) => restyleDefaultNextAction(outcome, hints);
15527
15907
  const session = new RaftStateSession(options.state, frontier, options.onStateSaveError);
15528
15908
  /** Load before, run, then save if the operation succeeded and changed the state. */
15529
15909
  const withState = async (run) => {
15530
15910
  await session.ensureLoaded();
15531
- const outcome = await run();
15911
+ const outcome = styled(await run());
15532
15912
  if (outcome.ok) await session.save();
15533
15913
  return outcome;
15534
15914
  };
@@ -15564,7 +15944,7 @@ function createRaft(options) {
15564
15944
  const outcome = await sendMessage(api, pending ? {
15565
15945
  ...request,
15566
15946
  idempotencyKey: pending.idempotencyKey
15567
- } : request, seen);
15947
+ } : request, seen, style);
15568
15948
  if (outcome.ok && outcome.state === "interrupted" && outcome.interrupt.resume.idempotencyKey) session.rememberContinuation({
15569
15949
  target: request.target,
15570
15950
  idempotencyKey: outcome.interrupt.resume.idempotencyKey,
@@ -15579,7 +15959,7 @@ function createRaft(options) {
15579
15959
  const outcome = await checkInbox(inboxApi, {
15580
15960
  ...request,
15581
15961
  ...since === void 0 ? {} : { since }
15582
- }, seen);
15962
+ }, seen, style);
15583
15963
  if (outcome.ok) {
15584
15964
  session.markDirty();
15585
15965
  if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
@@ -15598,7 +15978,7 @@ function createRaft(options) {
15598
15978
  if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
15599
15979
  session.markDirty();
15600
15980
  await session.save();
15601
- });
15981
+ }, style);
15602
15982
  })();
15603
15983
  const commitInbox = async (target) => {
15604
15984
  await session.ensureLoaded();
@@ -15610,7 +15990,7 @@ function createRaft(options) {
15610
15990
  };
15611
15991
  /** `seen` undefined: read without recording anything (a code read). */
15612
15992
  const readWithState = (request, seen) => withState(async () => {
15613
- const outcome = await readHistory(api, request, seen);
15993
+ const outcome = await readHistory(api, request, seen, style);
15614
15994
  if (outcome.ok && seen) session.markDirty();
15615
15995
  return outcome;
15616
15996
  });
@@ -15619,16 +15999,16 @@ function createRaft(options) {
15619
15999
  wake: {
15620
16000
  verifyNotice: (input) => verifyInboxNotice(input),
15621
16001
  webhook: {
15622
- status: () => webhookStatus(api),
15623
- register: (request) => registerWebhook(api, request),
15624
- unregister: () => unregisterWebhook(api)
16002
+ status: () => webhookStatus(api).then(styled),
16003
+ register: (request) => registerWebhook(api, request).then(styled),
16004
+ unregister: () => unregisterWebhook(api).then(styled)
15625
16005
  }
15626
16006
  },
15627
16007
  inbox: {
15628
16008
  check: (request = {}) => checkWithState(request, frontier),
15629
16009
  commit: (target) => commitInbox(target),
15630
16010
  drain: (request = {}) => drainWithState(request, frontier),
15631
- list: (request) => listInbox(api, request)
16011
+ list: (request) => listInbox(api, request, style).then(styled)
15632
16012
  },
15633
16013
  messages: {
15634
16014
  read: (request) => readWithState(request, frontier),
@@ -15637,10 +16017,10 @@ function createRaft(options) {
15637
16017
  ...request,
15638
16018
  target: message.target
15639
16019
  }, frontier),
15640
- search: (request) => searchMessages(api, request),
15641
- resolve: (request) => resolveMessage(api, request),
15642
- react: (request) => reactToMessage(api, request, "add"),
15643
- unreact: (request) => reactToMessage(api, request, "remove")
16020
+ search: (request) => searchMessages(api, request, style).then(styled),
16021
+ resolve: (request) => resolveMessage(api, request, style).then(styled),
16022
+ react: (request) => reactToMessage(api, request, "add").then(styled),
16023
+ unreact: (request) => reactToMessage(api, request, "remove").then(styled)
15644
16024
  },
15645
16025
  attachments: {
15646
16026
  upload: (request) => uploadAttachment(api, {
@@ -15648,51 +16028,52 @@ function createRaft(options) {
15648
16028
  fetch: options.fetch ?? fetch,
15649
16029
  headers: Object.fromEntries(new Headers(options.headers)),
15650
16030
  authorization
15651
- }, request),
15652
- download: (request) => downloadAttachment(api, request),
15653
- comments: (request) => attachmentComments(api, request)
16031
+ }, request, style).then(styled),
16032
+ download: (request) => downloadAttachment(api, request).then(styled),
16033
+ downloadUrl: (request) => downloadAttachmentUrl(api, request, style).then(styled),
16034
+ comments: (request) => attachmentComments(api, request).then(styled)
15654
16035
  },
15655
16036
  mentions: {
15656
- pending: (request) => pendingMentionActions(api, request),
15657
- execute: (request) => executeMentionAction(api, request),
15658
- deliveries: (request) => senderMentionDeliveries(api, request)
16037
+ pending: (request) => pendingMentionActions(api, request, style).then(styled),
16038
+ execute: (request) => executeMentionAction(api, request).then(styled),
16039
+ deliveries: (request) => senderMentionDeliveries(api, request).then(styled)
15659
16040
  },
15660
- actions: { prepare: (request) => prepareActionCard(api, request) },
16041
+ actions: { prepare: (request) => prepareActionCard(api, request, style).then(styled) },
15661
16042
  manual: {
15662
- get: (request) => getManualTopic(api, request),
15663
- search: (request) => searchManual(api, request)
16043
+ get: (request) => getManualTopic(api, request).then(styled),
16044
+ search: (request) => searchManual(api, request, style).then(styled)
15664
16045
  },
15665
16046
  tasks: {
15666
- claim: (request) => claimTasks(api, request),
15667
- list: (request) => listTasks(api, request),
15668
- create: (request) => createTasks(api, request),
15669
- unclaim: (request) => unclaimTask(api, request),
15670
- assign: (request) => assignTask(api, request),
15671
- unassign: (request) => unassignTask(api, request),
15672
- updateStatus: (request) => updateTaskStatus(api, request),
15673
- amend: (request) => amendTask(api, request),
15674
- history: (request) => taskHistory(api, request),
15675
- show: (request) => showTask(api, request),
15676
- convert: (request) => convertMessageToTask(api, request),
15677
- delete: (request) => deleteTask(api, request)
16047
+ claim: (request) => claimTasks(api, request, style).then(styled),
16048
+ list: (request) => listTasks(api, request, style).then(styled),
16049
+ create: (request) => createTasks(api, request, style).then(styled),
16050
+ unclaim: (request) => unclaimTask(api, request).then(styled),
16051
+ assign: (request) => assignTask(api, request).then(styled),
16052
+ unassign: (request) => unassignTask(api, request).then(styled),
16053
+ updateStatus: (request) => updateTaskStatus(api, request, style).then(styled),
16054
+ amend: (request) => amendTask(api, request, style).then(styled),
16055
+ history: (request) => taskHistory(api, request).then(styled),
16056
+ show: (request) => showTask(api, request, style).then(styled),
16057
+ convert: (request) => convertMessageToTask(api, request, style).then(styled),
16058
+ delete: (request) => deleteTask(api, request).then(styled)
15678
16059
  },
15679
16060
  channels: {
15680
- join: (request) => joinChannel(api, request),
15681
- leave: (request) => leaveChannel(api, request),
15682
- mute: (request) => muteChannel(api, request),
15683
- unmute: (request) => unmuteChannel(api, request),
15684
- members: (request) => channelMembers(api, request),
15685
- info: (request) => channelInfo(api, request)
16061
+ join: (request) => joinChannel(api, request, style).then(styled),
16062
+ leave: (request) => leaveChannel(api, request, style).then(styled),
16063
+ mute: (request) => muteChannel(api, request, style).then(styled),
16064
+ unmute: (request) => unmuteChannel(api, request, style).then(styled),
16065
+ members: (request) => channelMembers(api, request).then(styled),
16066
+ info: (request) => channelInfo(api, request, style).then(styled)
15686
16067
  },
15687
16068
  threads: {
15688
- list: () => listThreads(api),
15689
- unfollow: (request) => unfollowThread(api, request)
16069
+ list: () => listThreads(api).then(styled),
16070
+ unfollow: (request) => unfollowThread(api, request).then(styled)
15690
16071
  },
15691
- server: { info: (request) => serverInfo(api, request) },
15692
- users: { info: (request) => userInfo(api, request) },
16072
+ server: { info: (request) => serverInfo(api, request, style).then(styled) },
16073
+ users: { info: (request) => userInfo(api, request, style).then(styled) },
15693
16074
  profile: {
15694
- show: (request) => showProfile(api, request),
15695
- update: (request) => updateProfile(api, request)
16075
+ show: (request) => showProfile(api, request).then(styled),
16076
+ update: (request) => updateProfile(api, request).then(styled)
15696
16077
  },
15697
16078
  frontier,
15698
16079
  state: {
@@ -15713,7 +16094,7 @@ function createRaft(options) {
15713
16094
  const drain = drainWithState(args, call.seen);
15714
16095
  const batches = [];
15715
16096
  for (let step = await drain.next();; step = await drain.next()) {
15716
- if (step.done) return drainedInboxOutcome(batches, step.value);
16097
+ if (step.done) return styled(drainedInboxOutcome(batches, step.value, style));
15717
16098
  batches.push(step.value);
15718
16099
  }
15719
16100
  },
@@ -15741,6 +16122,7 @@ function createRaft(options) {
15741
16122
  "messages.resolve": (args) => raft.messages.resolve(args),
15742
16123
  "messages.react": (args) => raft.messages.react(args),
15743
16124
  "messages.unreact": (args) => raft.messages.unreact(args),
16125
+ "attachments.downloadUrl": (args) => raft.attachments.downloadUrl(args),
15744
16126
  "attachments.comments": (args) => raft.attachments.comments(args),
15745
16127
  "mentions.pending": (args) => raft.mentions.pending(args),
15746
16128
  "mentions.execute": (args) => raft.mentions.execute(args),
@@ -15844,6 +16226,7 @@ exports.createRaftClientFromStore = createRaftClientFromStore;
15844
16226
  exports.createRaftRoutes = createRaftRoutes;
15845
16227
  exports.createTasksRequestSchema = createTasksRequestSchema;
15846
16228
  exports.describeRaftRoute = describeRaftRoute;
16229
+ exports.downloadAttachmentUrlRequestSchema = downloadAttachmentUrlRequestSchema;
15847
16230
  exports.drainInboxRequestSchema = drainInboxRequestSchema;
15848
16231
  exports.executeMentionActionRequestSchema = executeMentionActionRequestSchema;
15849
16232
  exports.getManualTopicRequestSchema = getManualTopicRequestSchema;