@botiverse/raft-sdk 1.0.0-alpha.1 → 1.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -11043,13 +11043,17 @@ var SeenFrontier = class SeenFrontier {
11043
11043
  aliases = /* @__PURE__ */ new Map();
11044
11044
  static fromSnapshot(snapshot) {
11045
11045
  const frontier = new SeenFrontier();
11046
- if (!snapshot || snapshot.version !== 1) return frontier;
11046
+ frontier.absorb(snapshot);
11047
+ return frontier;
11048
+ }
11049
+ /** Merge a snapshot into this frontier by the same monotonic rules (never lowers a mark). */
11050
+ absorb(snapshot) {
11051
+ if (!snapshot || snapshot.version !== 1) return;
11052
+ for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) this.recordAlias(alias, canonical);
11047
11053
  for (const [target, state] of Object.entries(snapshot.targets ?? {})) {
11048
- if (positiveInt(state.upTo)) frontier.recordUpTo(target, state.upTo);
11049
- if (Array.isArray(state.exact)) frontier.recordExact(target, state.exact);
11054
+ if (positiveInt(state.upTo)) this.recordUpTo(target, state.upTo);
11055
+ if (Array.isArray(state.exact)) this.recordExact(target, state.exact);
11050
11056
  }
11051
- for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) frontier.recordAlias(alias, canonical);
11052
- return frontier;
11053
11057
  }
11054
11058
  /** Remember that the Server resolved `requested` to `canonical` (a thread spelling, a `~agent` suffix, …). */
11055
11059
  recordAlias(requested, canonical) {
@@ -11196,7 +11200,7 @@ async function checkInbox(client, request = {}, frontier) {
11196
11200
  * return value summarises the drain; the batch that ends the iteration is
11197
11201
  * acknowledged only by the caller's next pull (`summary.cursor`).
11198
11202
  */
11199
- async function* drainInbox(client, request = {}, frontier) {
11203
+ async function* drainInbox(client, request = {}, frontier, onPull) {
11200
11204
  const ack = request.ack ?? "cursor";
11201
11205
  let cursor = request.since ?? null;
11202
11206
  let ackMode = ack;
@@ -11219,6 +11223,7 @@ async function* drainInbox(client, request = {}, frontier) {
11219
11223
  error: round
11220
11224
  };
11221
11225
  const batch = round.data;
11226
+ await onPull?.(sent, batch);
11222
11227
  ackMode = batch.ackMode;
11223
11228
  stillUnread = batch.stillUnreadConversations;
11224
11229
  if (batch.messages.length > 0) {
@@ -11527,12 +11532,173 @@ async function sendMessage(client, request, frontier, internal = {}) {
11527
11532
  if (data.state === "sent") return sentOutcome(request.target, data);
11528
11533
  return failureOutcome(opError("INVALID_RESPONSE", { message: `Unexpected send state "${data.state}".` }));
11529
11534
  }
11530
- /** Reply where a received message came from. */
11531
- function replyTo(client, message, request, frontier) {
11532
- return sendMessage(client, {
11533
- ...request,
11534
- target: message.target
11535
- }, frontier);
11535
+ function taskTimestamps(t) {
11536
+ return `${t.createdAt ? ` created=${formatUtcTimestamp(t.createdAt)}` : ""}${t.updatedAt ? ` updated=${formatUtcTimestamp(t.updatedAt)}` : ""}`;
11537
+ }
11538
+ const TASK_STATUS_ORDER = [
11539
+ "todo",
11540
+ "in_progress",
11541
+ "in_review",
11542
+ "done",
11543
+ "closed"
11544
+ ];
11545
+ function oneLineTaskTitle(title) {
11546
+ return (title ?? "").replace(/\s+/g, " ").trim();
11547
+ }
11548
+ /** Channel task board listing. */
11549
+ function formatAgentTaskList(channel, data, statusFilter) {
11550
+ if (!data.tasks || data.tasks.length === 0) return `No${statusFilter && statusFilter !== "all" ? ` ${statusFilter}` : ""} tasks in ${channel}.`;
11551
+ const formatted = data.tasks.map((t) => {
11552
+ const assignee = t.claimedById ? ` → ${t.claimedByName ? `@${t.claimedByName}` : "<unresolved>"}` : "";
11553
+ const departedCreator = t.createdByMembershipStatus === "left" || t.createdByMembershipStatus === "removed";
11554
+ const creator = t.createdByName ? ` (by @${t.createdByName}${departedCreator ? " [departed]" : ""})` : "";
11555
+ const msgId = t.messageId ? ` msg=${t.messageId.slice(0, 8)}` : "";
11556
+ const revision = Number.isInteger(t.revision) ? ` rev=${t.revision}` : "";
11557
+ const legacy = t.isLegacy ? " [LEGACY — read-only]" : "";
11558
+ const resourceReceipt = t.requiresResourceReceipt ? ` resource-receipt=${t.resourceReceiptRecordedAt ? "recorded" : "pending"}` : "";
11559
+ const details = t.description ? `\n Current description: ${t.description.replace(/\n/g, `\n${" ".repeat(23)}`)}` : "";
11560
+ return `#${t.taskNumber} [${t.status}]${assignee}${creator}${msgId}${revision}${resourceReceipt}${taskTimestamps(t)}${legacy} Current title: ${oneLineTaskTitle(t.title)}${details}`;
11561
+ }).join("\n");
11562
+ return `## Task Board for ${channel} (${data.tasks.length} tasks)\n\n${formatted}`;
11563
+ }
11564
+ /** Cross-channel --mine task listing with coverage notes. */
11565
+ function formatAgentMyTaskList(data, statusFilter) {
11566
+ const tasks = data.tasks ?? [];
11567
+ const visibleTypes = data.coverage?.visibleChannelTypes?.join("|") ?? "unknown";
11568
+ const archived = data.coverage?.includesArchived ? "included" : "not included";
11569
+ const coverage = [
11570
+ `Coverage: ${data.coverage?.status ?? "unknown"}`,
11571
+ `visible types=${visibleTypes}`,
11572
+ `archived=${archived}`,
11573
+ `inaccessible scope=${data.coverage?.inaccessibleScope ?? "unknown"}`
11574
+ ].join(" · ");
11575
+ const output = `Output: showing ${tasks.length} of ${tasks.length} visible matches · mode=${data.pagination?.mode ?? "unknown"} · truncated=${String(data.pagination?.truncated ?? "unknown")}`;
11576
+ const title = `## My assigned tasks on this server${statusFilter ? ` (status=${statusFilter})` : " (unfinished)"}`;
11577
+ if (tasks.length === 0) return [
11578
+ title,
11579
+ "",
11580
+ coverage,
11581
+ output,
11582
+ "",
11583
+ "No tasks matched in the covered visible scope."
11584
+ ].join("\n");
11585
+ const grouped = /* @__PURE__ */ new Map();
11586
+ for (const task of tasks) {
11587
+ const status = task.status ?? "unknown";
11588
+ const bucket = grouped.get(status) ?? [];
11589
+ bucket.push(task);
11590
+ grouped.set(status, bucket);
11591
+ }
11592
+ return [
11593
+ title,
11594
+ "",
11595
+ coverage,
11596
+ output,
11597
+ "",
11598
+ ...[...TASK_STATUS_ORDER.filter((status) => grouped.has(status)), ...[...grouped.keys()].filter((status) => !TASK_STATUS_ORDER.includes(status)).sort()].map((status) => {
11599
+ const rows = grouped.get(status);
11600
+ const rendered = rows.map((task) => {
11601
+ const channelRef = task.channelRef ?? "<unresolved-visible-target>";
11602
+ const taskNumber = task.taskNumber ?? "?";
11603
+ const departedCreator = task.createdByMembershipStatus === "left" || task.createdByMembershipStatus === "removed";
11604
+ const creator = task.createdByName ? ` by=@${task.createdByName}${departedCreator ? " creator=departed" : ""}` : "";
11605
+ const message = task.messageId ? ` msg=${task.messageId.slice(0, 8)}` : "";
11606
+ const legacy = task.isLegacy ? " legacy=read-only" : "";
11607
+ return `- ${channelRef} task #${taskNumber} [${status}]${creator}${message}${task.requiresResourceReceipt ? ` resource-receipt=${task.resourceReceiptRecordedAt ? "recorded" : "pending"}` : ""}${taskTimestamps(task)}${legacy} Current title: ${oneLineTaskTitle(task.title)}`.trimEnd();
11608
+ });
11609
+ return [`### ${status} (${rows.length})`, ...rendered].join("\n");
11610
+ })
11611
+ ].join("\n");
11612
+ }
11613
+ /** Receipt for task create. */
11614
+ function formatAgentTasksCreated(channel, data) {
11615
+ const created = data.tasks.map((t) => {
11616
+ const assignee = t.claimedById ? t.claimedByName ? `@${t.claimedByName}` : "<unresolved>" : "unassigned";
11617
+ const resourceReceipt = t.requiresResourceReceipt ? " resource-receipt=pending" : "";
11618
+ return `#${t.taskNumber} [${t.status}] assignee=${assignee} claimedAt=${t.claimedAt ?? "null"} msg=${t.messageId.slice(0, 8)}${resourceReceipt} "${t.title}"`;
11619
+ }).join("\n");
11620
+ const threadHints = data.tasks.map((t) => `#${t.taskNumber} → raft message send --target "${channel}:${t.messageId.slice(0, 8)}"`).join("\n");
11621
+ const receipt = data.assignmentReceipt ? `\n\nAssignment receipt (msg=${data.assignmentReceipt.messageId.slice(0, 8)}):\n${data.assignmentReceipt.content}` : "";
11622
+ return `Created ${data.tasks.length} task(s) in ${channel}:\n${created}${receipt}\n\nTo follow up in each task's thread:\n${threadHints}`;
11623
+ }
11624
+ const BLOCKED_ACTION_COPY = { start_conflicting_execution: "starting conflicting implementation/change work" };
11625
+ function formatClaimConflict(label, conflict) {
11626
+ const holder = conflict.currentAssignee?.name ? `@${conflict.currentAssignee.name}` : "another actor";
11627
+ const blocked = conflict.blockedActions.map((action) => BLOCKED_ACTION_COPY[action] ?? action).join("; ");
11628
+ const examples = conflict.unblockedActionExamples.join(" · ");
11629
+ return [
11630
+ `${label}: Claim failed — ${holder} currently holds the implementation lock (assignment state as of ${conflict.observedAt}).`,
11631
+ ` Blocked: ${blocked}.`,
11632
+ ` Not blocked by this claim conflict (each still subject to its own authority/policy): ${examples}.`,
11633
+ ` This is not a ruling on who owns or leads this lane. If you are its canonical owner or believe it is misrouted: correct the routing in the original thread, or file request_reassign (a request — it does not itself reassign).`
11634
+ ].join("\n");
11635
+ }
11636
+ function canonicalAgentTaskTarget(target) {
11637
+ return target.replace(/^dm:user:/i, "dm:@");
11638
+ }
11639
+ function agentTaskThreadTarget(target, messageId) {
11640
+ return `${canonicalAgentTaskTarget(target)}:${messageId.slice(0, 8)}`;
11641
+ }
11642
+ /** Claim results incl. concurrency-lock guidance on failed claims. */
11643
+ function formatAgentClaimResults(channel, data) {
11644
+ const lines = data.results.map((r) => {
11645
+ const label = r.taskNumber ? `#${r.taskNumber}` : `msg:${r.messageId}`;
11646
+ if (r.success) return `${label} (msg:${r.messageId ? r.messageId.slice(0, 8) : ""}): claimed`;
11647
+ if (r.reason === "already claimed by you") return `${label}: already claimed by you.`;
11648
+ if (r.conflict?.kind === "claim_conflict") return formatClaimConflict(label, r.conflict);
11649
+ return `${label}: FAILED — ${r.reason || "already claimed"}. Do not start conflicting execution on this task or take over its scope without a redirect; a failed claim is a concurrency lock, not a ruling on lane ownership.`;
11650
+ });
11651
+ const succeeded = data.results.filter((r) => r.success).length;
11652
+ const failed = data.results.length - succeeded;
11653
+ let summary = `${succeeded} claimed`;
11654
+ if (failed > 0) summary += `, ${failed} failed`;
11655
+ const claimedMsgs = data.results.filter((r) => r.success && r.messageId).map((r) => `#${r.taskNumber} → raft message send --target "${agentTaskThreadTarget(channel, r.messageId)}"`).join("\n");
11656
+ const threadHint = claimedMsgs ? `\n\nFollow up in each task's thread:\n${claimedMsgs}` : "";
11657
+ return `Claim results (${summary}):\n${lines.join("\n")}${threadHint}`;
11658
+ }
11659
+ function formatAgentTaskUnclaimed(taskNumber) {
11660
+ return `#${taskNumber} unclaimed — now open.`;
11661
+ }
11662
+ function formatAgentTaskAssigned(taskNumber, assignee) {
11663
+ return assignee ? `#${taskNumber} assigned to ${assignee}.` : `#${taskNumber} unassigned — now open.`;
11664
+ }
11665
+ function formatAgentTaskStatusUpdated(taskNumber, status) {
11666
+ return `#${taskNumber} moved to ${status}.`;
11667
+ }
11668
+ function formatAgentTaskDeleted(taskNumber) {
11669
+ return `#${taskNumber} deleted.`;
11670
+ }
11671
+ /** Message→task conversion receipt. */
11672
+ function formatAgentTaskConverted(channel, task) {
11673
+ const target = `${canonicalAgentTaskTarget(channel)}:${task.messageId.slice(0, 8)}`;
11674
+ return [
11675
+ `Converted msg=${task.messageId.slice(0, 8)} to task #${task.taskNumber} [${task.status}] assignee=unassigned "${task.title}"`,
11676
+ "",
11677
+ `To follow up in the task's thread:`,
11678
+ `raft message send --target "${target}"`
11679
+ ].join("\n");
11680
+ }
11681
+ function formatAgentTaskAmended(data) {
11682
+ const details = data.task.description === null ? "details: <none>" : `details:\n${data.task.description.split("\n").map((line) => ` ${line}`).join("\n")}`;
11683
+ return [
11684
+ `#${data.task.taskNumber} amended — revision ${data.task.revision}, event seq ${data.event.seq}.`,
11685
+ `title: ${data.task.title}`,
11686
+ details
11687
+ ].join("\n");
11688
+ }
11689
+ function formatAgentTaskHistory(data) {
11690
+ const description = data.task.description === null ? "(none set)" : data.task.description.replace(/\n/g, `\n${" ".repeat(21)}`);
11691
+ const header = [
11692
+ `## Task #${data.task.taskNumber} history — revision ${data.task.revision}`,
11693
+ "",
11694
+ `Current title: ${data.task.title.replace(/\s+/g, " ").trim()}`,
11695
+ `Current description: ${description}`
11696
+ ].join("\n");
11697
+ if (data.events.length === 0) return `${header}\n\nNo recorded events.`;
11698
+ return `${header}\n\n${data.events.map((event) => {
11699
+ const actor = event.actorType === "system" ? "@system" : event.actorName ? `@${event.actorName}` : "<unresolved>";
11700
+ return `seq=${event.seq} time=${event.createdAt} actor=${actor} type=${event.eventType}\n ${JSON.stringify(event.payload)}`;
11701
+ }).join("\n")}`;
11536
11702
  }
11537
11703
  //#endregion
11538
11704
  //#region ../shared/src/agentOps/tasks.ts
@@ -11546,12 +11712,12 @@ function rowState(result) {
11546
11712
  function claimNext(claim) {
11547
11713
  const first = claim.rows.find((row) => row.mayWork);
11548
11714
  if (first) {
11549
- const suffix = first.messageId ? first.messageId.slice(0, 8) : null;
11715
+ const thread = first.messageId ? agentTaskThreadTarget(claim.target, first.messageId) : null;
11550
11716
  return {
11551
11717
  kind: "start_work",
11552
- ...suffix ? {
11553
- command: `raft message send --target "${claim.target}:${suffix}"`,
11554
- args: { thread: `${claim.target}:${suffix}` }
11718
+ ...thread ? {
11719
+ command: `raft message send --target "${thread}"`,
11720
+ args: { thread }
11555
11721
  } : {},
11556
11722
  why: "The claim is yours; post progress in the task's thread."
11557
11723
  };
@@ -11562,20 +11728,7 @@ function claimNext(claim) {
11562
11728
  };
11563
11729
  }
11564
11730
  function claimText(claim) {
11565
- const lines = claim.rows.map((row) => {
11566
- const label = row.taskNumber ? `#${row.taskNumber}` : `msg:${row.ref}`;
11567
- if (row.state === "claimed") return `${label}: claimed`;
11568
- if (row.state === "already_yours") return `${label}: already claimed by you`;
11569
- if (row.state === "conflict") return `${label}: held by ${row.holder?.name ? `@${row.holder.name}` : "another assignee"}`;
11570
- return `${label}: refused${row.reason ? ` (${row.reason})` : ""}`;
11571
- });
11572
- const head = `Claim results (${claim.rows.filter((row) => row.mayWork).length} of ${claim.rows.length} authorise work):`;
11573
- const next = claimNext(claim);
11574
- return [
11575
- head,
11576
- ...lines,
11577
- next?.command ? `Follow up in the task's thread: ${next.command}` : next?.why ?? ""
11578
- ].filter(Boolean).join("\n");
11731
+ return formatAgentClaimResults(claim.target, { results: claim.rows.map((row) => row.raw) });
11579
11732
  }
11580
11733
  async function claimTasks(client, request) {
11581
11734
  const numbers = (request.taskNumbers ?? []).filter((n) => Number.isInteger(n) && n > 0);
@@ -11619,7 +11772,8 @@ async function claimTasks(client, request) {
11619
11772
  mayWork: state === "claimed" || state === "already_yours",
11620
11773
  reason: row.reason ?? null,
11621
11774
  holder: row.conflict?.currentAssignee ?? null,
11622
- conflict: row.conflict ?? null
11775
+ conflict: row.conflict ?? null,
11776
+ raw: row
11623
11777
  };
11624
11778
  });
11625
11779
  const claim = {
@@ -11635,6 +11789,235 @@ async function claimTasks(client, request) {
11635
11789
  text: claimText(claim)
11636
11790
  };
11637
11791
  }
11792
+ async function listTasks(client, request) {
11793
+ const mine = request.mine === true;
11794
+ if (mine === Boolean(request.target?.trim())) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass exactly one of a channel target or mine: true." }));
11795
+ const result = await client.tasks.list({
11796
+ ...mine ? { mine: "true" } : { channel: request.target },
11797
+ ...request.status ? { status: request.status } : {}
11798
+ });
11799
+ if (!result.ok) return failureFromClientResult(result);
11800
+ const data = result.data;
11801
+ const board = {
11802
+ scope: mine ? "mine" : "channel",
11803
+ target: mine ? null : request.target,
11804
+ tasks: data.tasks,
11805
+ coverage: data.coverage ?? null
11806
+ };
11807
+ const text = mine ? formatAgentMyTaskList(data, request.status) : formatAgentTaskList(request.target, data, request.status);
11808
+ const open = board.tasks.find((t) => t.status === "todo" && !t.claimedByName);
11809
+ const next = open?.taskNumber && board.target ? {
11810
+ kind: "claim_task",
11811
+ command: `raft task claim --target "${board.target}" --number ${open.taskNumber}`,
11812
+ args: {
11813
+ target: board.target,
11814
+ taskNumbers: [open.taskNumber]
11815
+ },
11816
+ why: "An unassigned todo task is open; claim it before working on it."
11817
+ } : null;
11818
+ return {
11819
+ ok: true,
11820
+ state: board.tasks.length > 0 ? "board" : "empty",
11821
+ data: board,
11822
+ next,
11823
+ text
11824
+ };
11825
+ }
11826
+ async function createTasks(client, request) {
11827
+ if (!request.target?.trim() || !request.tasks?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and at least one task title are required." }));
11828
+ const result = await client.tasks.create({
11829
+ channel: request.target,
11830
+ tasks: request.tasks.map((t) => ({
11831
+ title: t.title,
11832
+ ...t.createsResource ? { creates_resource: true } : {}
11833
+ })),
11834
+ ...request.assignee ? { assignee: request.assignee } : {}
11835
+ });
11836
+ if (!result.ok) return failureFromClientResult(result);
11837
+ const data = result.data;
11838
+ const first = data.tasks[0];
11839
+ return {
11840
+ ok: true,
11841
+ state: "created",
11842
+ data: {
11843
+ ...data,
11844
+ target: request.target
11845
+ },
11846
+ next: first ? {
11847
+ kind: "post_in_task_thread",
11848
+ command: `raft message send --target "${agentTaskThreadTarget(request.target, first.messageId)}"`,
11849
+ args: { thread: agentTaskThreadTarget(request.target, first.messageId) },
11850
+ why: "Follow up in each task's thread."
11851
+ } : null,
11852
+ text: formatAgentTasksCreated(request.target, data)
11853
+ };
11854
+ }
11855
+ function requireTaskRef(request) {
11856
+ if (!request.target?.trim() || !Number.isInteger(request.taskNumber) || request.taskNumber <= 0) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a positive task number are required." }));
11857
+ return null;
11858
+ }
11859
+ async function unclaimTask(client, request) {
11860
+ const invalid = requireTaskRef(request);
11861
+ if (invalid) return invalid;
11862
+ const result = await client.tasks.unclaim({
11863
+ channel: request.target,
11864
+ task_number: request.taskNumber
11865
+ });
11866
+ if (!result.ok) return failureFromClientResult(result);
11867
+ return {
11868
+ ok: true,
11869
+ state: "unclaimed",
11870
+ data: request,
11871
+ next: null,
11872
+ text: formatAgentTaskUnclaimed(request.taskNumber)
11873
+ };
11874
+ }
11875
+ async function assignTask(client, request) {
11876
+ const invalid = requireTaskRef(request);
11877
+ if (invalid) return invalid;
11878
+ const result = await client.tasks.assign({
11879
+ channel: request.target,
11880
+ task_number: request.taskNumber,
11881
+ assignee: request.assignee,
11882
+ ...request.expectedRevision === void 0 ? {} : { expected_revision: request.expectedRevision }
11883
+ });
11884
+ if (!result.ok) return failureFromClientResult(result);
11885
+ const assignee = result.data.assignee;
11886
+ return {
11887
+ ok: true,
11888
+ state: assignee ? "assigned" : "unassigned",
11889
+ data: {
11890
+ target: request.target,
11891
+ taskNumber: request.taskNumber,
11892
+ assignee,
11893
+ revision: result.data.revision
11894
+ },
11895
+ next: null,
11896
+ text: formatAgentTaskAssigned(request.taskNumber, assignee)
11897
+ };
11898
+ }
11899
+ function heldTaskWrite(request, data, action, kind) {
11900
+ const { idempotencyKey: _k, continuation: _c, ...base } = projectHeld(request.target, data, "");
11901
+ const held = {
11902
+ ...base,
11903
+ request
11904
+ };
11905
+ return {
11906
+ ok: true,
11907
+ state: "held",
11908
+ data: held,
11909
+ next: {
11910
+ kind,
11911
+ command: `raft message read --target "${request.target}"`,
11912
+ args: { ...request },
11913
+ why: `Unread messages in this channel may change the task; read them (frontier.recordHeld(held) once the model saw them), then repeat with these args if it is still right.`
11914
+ },
11915
+ text: `Held — ${held.newMessageCount} unread ${held.newMessageCount === 1 ? "message" : "messages"} in ${request.target}. ${action}\nRead them with: raft message read --target "${request.target}"\nAfter reviewing, repeat the operation if it is still correct.`
11916
+ };
11917
+ }
11918
+ async function updateTaskStatus(client, request) {
11919
+ const invalid = requireTaskRef(request);
11920
+ if (invalid) return invalid;
11921
+ const result = await client.tasks.updateStatus({
11922
+ channel: request.target,
11923
+ task_number: request.taskNumber,
11924
+ status: request.status
11925
+ });
11926
+ if (!result.ok) return failureFromClientResult(result);
11927
+ if (isHeldResponse(result.data)) return heldTaskWrite(request, result.data, "The status change was not applied.", "retry_update_status");
11928
+ return {
11929
+ ok: true,
11930
+ state: "updated",
11931
+ data: request,
11932
+ next: request.status === "in_review" ? {
11933
+ kind: "await_review",
11934
+ why: "A human validates the work; set done after approval."
11935
+ } : null,
11936
+ text: formatAgentTaskStatusUpdated(request.taskNumber, request.status)
11937
+ };
11938
+ }
11939
+ async function amendTask(client, request) {
11940
+ const invalid = requireTaskRef(request);
11941
+ if (invalid) return invalid;
11942
+ 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." }));
11943
+ const result = await client.tasks.amend({
11944
+ channel: request.target,
11945
+ task_number: request.taskNumber,
11946
+ ...request.title === void 0 ? {} : { title: request.title },
11947
+ ...request.description === void 0 ? {} : { description: request.description }
11948
+ });
11949
+ if (!result.ok) return failureFromClientResult(result);
11950
+ if (isHeldResponse(result.data)) return heldTaskWrite(request, result.data, "The amendment was not applied.", "retry_amend");
11951
+ return {
11952
+ ok: true,
11953
+ state: "amended",
11954
+ data: {
11955
+ ...result.data,
11956
+ target: request.target
11957
+ },
11958
+ next: null,
11959
+ text: formatAgentTaskAmended(result.data)
11960
+ };
11961
+ }
11962
+ async function taskHistory(client, request) {
11963
+ const invalid = requireTaskRef(request);
11964
+ if (invalid) return invalid;
11965
+ const result = await client.tasks.history({
11966
+ channel: request.target,
11967
+ task_number: request.taskNumber
11968
+ });
11969
+ if (!result.ok) return failureFromClientResult(result);
11970
+ return {
11971
+ ok: true,
11972
+ state: "history",
11973
+ data: {
11974
+ ...result.data,
11975
+ target: request.target
11976
+ },
11977
+ next: null,
11978
+ text: formatAgentTaskHistory(result.data)
11979
+ };
11980
+ }
11981
+ async function convertMessageToTask(client, request) {
11982
+ if (!request.target?.trim() || !request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a message id are required." }));
11983
+ const result = await client.tasks.convert({
11984
+ channel: request.target,
11985
+ message_id: request.messageId
11986
+ });
11987
+ if (!result.ok) return failureFromClientResult(result);
11988
+ const task = result.data.task;
11989
+ return {
11990
+ ok: true,
11991
+ state: "converted",
11992
+ data: {
11993
+ target: request.target,
11994
+ task
11995
+ },
11996
+ next: {
11997
+ kind: "post_in_task_thread",
11998
+ command: `raft message send --target "${agentTaskThreadTarget(request.target, task.messageId)}"`,
11999
+ args: { thread: agentTaskThreadTarget(request.target, task.messageId) },
12000
+ why: "Follow up in the task's thread; it is unassigned until someone claims it."
12001
+ },
12002
+ text: formatAgentTaskConverted(request.target, task)
12003
+ };
12004
+ }
12005
+ async function deleteTask(client, request) {
12006
+ const invalid = requireTaskRef(request);
12007
+ if (invalid) return invalid;
12008
+ const result = await client.tasks.delete({
12009
+ channel: request.target,
12010
+ task_number: request.taskNumber
12011
+ });
12012
+ if (!result.ok) return failureFromClientResult(result);
12013
+ return {
12014
+ ok: true,
12015
+ state: "deleted",
12016
+ data: request,
12017
+ next: null,
12018
+ text: formatAgentTaskDeleted(request.taskNumber)
12019
+ };
12020
+ }
11638
12021
  //#endregion
11639
12022
  //#region ../shared/src/agentOps/wake.ts
11640
12023
  const RAFT_INBOX_NOTICE_SCHEMA = "raft-agent-inbox-notice.v1";
@@ -11802,11 +12185,1605 @@ async function unregisterWebhook(client) {
11802
12185
  };
11803
12186
  }
11804
12187
  //#endregion
12188
+ //#region ../shared/src/agentText/server.ts
12189
+ function formatRuntimeContext(ctx) {
12190
+ if (!ctx) return "";
12191
+ const lines = ["### Current Runtime", "Authoritative context for this agent process. Do not infer computer identity from hostname or cwd when this section is present."];
12192
+ if (ctx.agentId) lines.push(`- Agent ID: ${ctx.agentId}`);
12193
+ if (ctx.runtime) lines.push(`- Runtime: ${ctx.runtime}`);
12194
+ if (ctx.model) lines.push(`- Model: ${ctx.model}`);
12195
+ if (ctx.reasoningEffort) lines.push(`- Reasoning: ${ctx.reasoningEffort}`);
12196
+ if (ctx.serverId) lines.push(`- Server ID: ${ctx.serverId}`);
12197
+ if (ctx.machineName || ctx.machineId) {
12198
+ const label = ctx.machineName && ctx.machineId ? `${ctx.machineName} (${ctx.machineId})` : ctx.machineName || ctx.machineId;
12199
+ lines.push(`- Computer: ${label}`);
12200
+ }
12201
+ if (ctx.machineDescription) lines.push(`- Computer Description: ${ctx.machineDescription}`);
12202
+ if (ctx.machineHostname) lines.push(`- Hostname: ${ctx.machineHostname}`);
12203
+ if (ctx.machineOs) lines.push(`- OS: ${ctx.machineOs}`);
12204
+ if (ctx.daemonVersion) lines.push(`- Daemon: v${ctx.daemonVersion}`);
12205
+ if (ctx.workspacePath) lines.push(`- Workspace: ${ctx.workspacePath}`);
12206
+ return lines.length > 2 ? `${lines.join("\n")}\n\n` : "";
12207
+ }
12208
+ function roleLabel(role) {
12209
+ return role && role !== "member" ? ` (${role})` : "";
12210
+ }
12211
+ function channelMemberRoleDetail(member) {
12212
+ const details = [];
12213
+ if (member.serverRole) details.push(`server role=${member.serverRole}`);
12214
+ if (member.channelRole) details.push(`channel role=${member.channelRole}`);
12215
+ if (member.channelAdminBasis) details.push(`admin via=${member.channelAdminBasis}`);
12216
+ return details.length > 0 ? ` [${details.join(", ")}]` : "";
12217
+ }
12218
+ function agentStatusLabel(agent) {
12219
+ const lifecycle = agent.status?.trim() || "unknown";
12220
+ const activity = agent.activity?.trim();
12221
+ if (!activity) return lifecycle;
12222
+ const activityWithDetail = agent.activityDetail?.trim() ? `${activity}: ${agent.activityDetail.trim()}` : activity;
12223
+ return activity === lifecycle ? lifecycle : `${lifecycle}; ${activityWithDetail}`;
12224
+ }
12225
+ function formatCurrentAgent(data) {
12226
+ if (!data.serverRole) return "";
12227
+ const lines = ["### Current Agent"];
12228
+ lines.push(`- Role: ${data.serverRole}`);
12229
+ return `${lines.join("\n")}\n\n`;
12230
+ }
12231
+ /** Server overview: runtime context, channels, agents, humans. */
12232
+ function formatAgentServerInfo(data) {
12233
+ let text = "## Server\n\n";
12234
+ const channels = data.channels ?? [];
12235
+ const agents = data.agents ?? [];
12236
+ const humans = data.humans ?? [];
12237
+ text += formatRuntimeContext(data.runtimeContext);
12238
+ text += formatCurrentAgent(data);
12239
+ text += "### Channels\n";
12240
+ 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";
12241
+ text += "Server-profile changes still use raft server update and remain server-role gated.\n";
12242
+ text += "Mute state is shown when the server provides it; otherwise it is omitted.\n";
12243
+ if (channels.length > 0) for (const t of channels) {
12244
+ const statusParts = [t.type === "private" || t.type === "dm" ? "private" : "public", t.joined ? "joined" : "not joined"];
12245
+ if (t.channelRole) statusParts.push(`channel role=${t.channelRole}`);
12246
+ if (t.channelAdminBasis) statusParts.push(`admin via=${t.channelAdminBasis}`);
12247
+ const muted = channelMuted(t);
12248
+ if (muted !== void 0) statusParts.push(muted ? "muted" : "not muted");
12249
+ const status = statusParts.join(", ");
12250
+ const ref = agentChannelRef(t.name, t.type);
12251
+ text += t.description ? ` - ${ref} [${status}] — ${t.description}\n` : ` - ${ref} [${status}]\n`;
12252
+ }
12253
+ else text += " (none)\n";
12254
+ text += "\n### Agents\n";
12255
+ text += "Other AI agents in this server.\n";
12256
+ text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
12257
+ if (agents.length > 0) for (const a of agents) {
12258
+ const role = roleLabel(a.role);
12259
+ const status = agentStatusLabel(a);
12260
+ text += a.description ? ` - @${a.name} (${status})${role} — ${a.description}\n` : ` - @${a.name} (${status})${role}\n`;
12261
+ }
12262
+ else text += " (none)\n";
12263
+ text += "\n### Humans\n";
12264
+ 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";
12265
+ text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
12266
+ if (humans.length > 0) for (const u of humans) {
12267
+ const role = roleLabel(u.role);
12268
+ text += u.description ? ` - @${u.name}${role} — ${u.description}\n` : ` - @${u.name}${role}\n`;
12269
+ }
12270
+ else text += " (none)\n";
12271
+ return text;
12272
+ }
12273
+ function agentChannelRef(name, type) {
12274
+ if (type === "dm") return `dm:@${name}`;
12275
+ return name.startsWith("#") ? name : `#${name}`;
12276
+ }
12277
+ function channelVisibility(channel) {
12278
+ const type = channel.type?.trim();
12279
+ return type === "private" || type === "dm" ? "private" : "public";
12280
+ }
12281
+ function channelMuted(channel) {
12282
+ if (typeof channel.muted === "boolean") return channel.muted;
12283
+ if (typeof channel.activityMuted === "boolean") return channel.activityMuted;
12284
+ }
12285
+ function channelStatus(channel) {
12286
+ const parts = [channelVisibility(channel), channel.joined ? "joined" : "not joined"];
12287
+ const muted = channelMuted(channel);
12288
+ if (channel.channelRole) parts.push(`channel role=${channel.channelRole}`);
12289
+ if (channel.channelAdminBasis) parts.push(`admin via=${channel.channelAdminBasis}`);
12290
+ if (muted !== void 0) parts.push(muted ? "muted" : "not muted");
12291
+ if (typeof channel.archived === "boolean") parts.push(channel.archived ? "archived" : "not archived");
12292
+ return parts.join(", ");
12293
+ }
12294
+ function formatPageFooter(page) {
12295
+ if (!page) return "";
12296
+ const start = page.total === 0 ? 0 : Math.min(page.offset + 1, page.total);
12297
+ const end = Math.min(page.offset + page.limit, page.total);
12298
+ const lines = [`\nShowing ${start}-${end} of ${page.total}.`];
12299
+ if (page.nextCommand && end < page.total) lines.push(`More: ${page.nextCommand}`);
12300
+ return `${lines.join("\n")}\n`;
12301
+ }
12302
+ /** Compact server summary. */
12303
+ function formatAgentServerSummary(data) {
12304
+ const channels = data.channels ?? [];
12305
+ const agents = data.agents ?? [];
12306
+ const humans = data.humans ?? [];
12307
+ const joined = channels.filter((channel) => channel.joined).length;
12308
+ return `${[
12309
+ "## Server",
12310
+ "",
12311
+ `Channels: ${channels.length} visible (${joined} joined)`,
12312
+ `Agents: ${agents.length}`,
12313
+ `Humans: ${humans.length}`,
12314
+ "",
12315
+ "Narrow queries:",
12316
+ "- raft server info --channels",
12317
+ "- raft server info --agents",
12318
+ "- raft server info --humans",
12319
+ "- raft channel info <name>",
12320
+ "- raft user info <name>",
12321
+ "",
12322
+ "Full dump: raft server info --full"
12323
+ ].join("\n")}\n`;
12324
+ }
12325
+ /** Channel listing page. */
12326
+ function formatAgentServerChannels(channels, page) {
12327
+ const lines = [
12328
+ "## Server Channels",
12329
+ "",
12330
+ "Private channels are shown only when this agent is a member. Do not disclose private-channel names or metadata outside that channel."
12331
+ ];
12332
+ if (channels.length === 0) lines.push("(none)");
12333
+ else for (const channel of channels) {
12334
+ const description = channel.description?.trim();
12335
+ lines.push(description ? `${agentChannelRef(channel.name, channel.type)} [${channelStatus(channel)}] — ${description}` : `${agentChannelRef(channel.name, channel.type)} [${channelStatus(channel)}]`);
12336
+ }
12337
+ return `${lines.join("\n")}${formatPageFooter(page)}`;
12338
+ }
12339
+ /** Agent listing page. */
12340
+ function formatAgentServerAgents(agents, page) {
12341
+ const lines = [
12342
+ "## Server Agents",
12343
+ "",
12344
+ "Role labels show server-level owner/admin authority; no role label means ordinary member."
12345
+ ];
12346
+ if (agents.length === 0) lines.push("(none)");
12347
+ else for (const agent of agents) {
12348
+ const role = roleLabel(agent.role);
12349
+ const status = agentStatusLabel(agent);
12350
+ lines.push(agent.description ? `@${agent.name} (${status})${role} — ${agent.description}` : `@${agent.name} (${status})${role}`);
12351
+ }
12352
+ return `${lines.join("\n")}${formatPageFooter(page)}`;
12353
+ }
12354
+ /** Human listing page. */
12355
+ function formatAgentServerHumans(humans, page) {
12356
+ const lines = [
12357
+ "## Server Humans",
12358
+ "",
12359
+ "Role labels show server-level owner/admin authority; no role label means ordinary member."
12360
+ ];
12361
+ if (humans.length === 0) lines.push("(none)");
12362
+ else for (const human of humans) {
12363
+ const role = roleLabel(human.role);
12364
+ lines.push(human.description ? `@${human.name}${role} — ${human.description}` : `@${human.name}${role}`);
12365
+ }
12366
+ return `${lines.join("\n")}${formatPageFooter(page)}`;
12367
+ }
12368
+ /** Channel membership with server-role labels. */
12369
+ function formatAgentChannelMembers(data) {
12370
+ let text = "## Channel Members\n\n";
12371
+ const ref = data.channel?.ref ?? "(unknown)";
12372
+ const type = data.channel?.type ? ` (${data.channel.type})` : "";
12373
+ const agents = data.agents ?? [];
12374
+ const humans = data.humans ?? [];
12375
+ text += `Channel: ${ref}${type}\n`;
12376
+ text += "Members means join/post authority for this surface.\n\n";
12377
+ text += "### Agents\n";
12378
+ text += "Server and stored channel roles are shown separately when available.\n";
12379
+ if (agents.length > 0) for (const a of agents) {
12380
+ const role = roleLabel(a.role);
12381
+ const channelRole = channelMemberRoleDetail(a);
12382
+ const status = agentStatusLabel(a);
12383
+ text += a.description ? ` - @${a.name} (${status})${role}${channelRole} — ${a.description}\n` : ` - @${a.name} (${status})${role}${channelRole}\n`;
12384
+ }
12385
+ else text += " (none)\n";
12386
+ text += "\n### Humans\n";
12387
+ text += "Server and stored channel roles are shown separately when available.\n";
12388
+ if (humans.length > 0) for (const u of humans) {
12389
+ const role = roleLabel(u.role);
12390
+ const channelRole = channelMemberRoleDetail(u);
12391
+ text += u.description ? ` - @${u.name}${role}${channelRole} — ${u.description}\n` : ` - @${u.name}${role}${channelRole}\n`;
12392
+ }
12393
+ else text += " (none)\n";
12394
+ return text;
12395
+ }
12396
+ //#endregion
12397
+ //#region ../shared/src/runtimeCatalog.ts
12398
+ const EXTERNAL_AGENT_RUNTIME_ID = "external";
12399
+ const EXTERNAL_AGENT_RUNTIME_DISPLAY_NAME = "External agent";
12400
+ function isExternalAgentRuntime(runtime) {
12401
+ return runtime === EXTERNAL_AGENT_RUNTIME_ID;
12402
+ }
12403
+ const RUNTIMES = [
12404
+ {
12405
+ id: "claude",
12406
+ displayName: "Claude Code",
12407
+ abbreviation: "CC",
12408
+ binary: "claude",
12409
+ supported: true
12410
+ },
12411
+ {
12412
+ id: "codex",
12413
+ displayName: "Codex CLI",
12414
+ abbreviation: "CX",
12415
+ binary: "codex",
12416
+ supported: true
12417
+ },
12418
+ {
12419
+ id: "grok",
12420
+ displayName: "Grok Build",
12421
+ abbreviation: "GK",
12422
+ binary: "grok",
12423
+ supported: true
12424
+ },
12425
+ {
12426
+ id: "builtin",
12427
+ displayName: "Built-in Pi",
12428
+ abbreviation: "BP",
12429
+ binary: "",
12430
+ supported: true
12431
+ },
12432
+ {
12433
+ id: "antigravity",
12434
+ displayName: "Antigravity CLI",
12435
+ abbreviation: "AG",
12436
+ binary: "agy",
12437
+ supported: true,
12438
+ deprecated: true
12439
+ },
12440
+ {
12441
+ id: "kimi-sdk",
12442
+ displayName: "Kimi Code",
12443
+ abbreviation: "KC",
12444
+ binary: "",
12445
+ supported: true
12446
+ },
12447
+ {
12448
+ id: "kimi",
12449
+ displayName: "Kimi CLI",
12450
+ abbreviation: "KL",
12451
+ binary: "kimi",
12452
+ supported: true,
12453
+ deprecated: true
12454
+ },
12455
+ {
12456
+ id: "copilot",
12457
+ displayName: "Copilot CLI",
12458
+ abbreviation: "CP",
12459
+ binary: "copilot",
12460
+ supported: true
12461
+ },
12462
+ {
12463
+ id: "cursor",
12464
+ displayName: "Cursor CLI",
12465
+ abbreviation: "CU",
12466
+ binary: "cursor-agent",
12467
+ supported: true
12468
+ },
12469
+ {
12470
+ id: "gemini",
12471
+ displayName: "Gemini CLI",
12472
+ abbreviation: "GM",
12473
+ binary: "gemini",
12474
+ supported: true,
12475
+ deprecated: true
12476
+ },
12477
+ {
12478
+ id: "opencode",
12479
+ displayName: "OpenCode",
12480
+ abbreviation: "OC",
12481
+ binary: "opencode",
12482
+ supported: true
12483
+ },
12484
+ {
12485
+ id: "pi",
12486
+ displayName: "Pi",
12487
+ abbreviation: "PI",
12488
+ binary: "pi",
12489
+ supported: true
12490
+ }
12491
+ ];
12492
+ function isRuntimeDeprecated(runtimeId) {
12493
+ return RUNTIMES.some((runtime) => runtime.id === runtimeId && Boolean(runtime.deprecated));
12494
+ }
12495
+ /** Map runtime ID → display name. Falls back to the ID itself. */
12496
+ function getRuntimeDisplayName(id) {
12497
+ if (isExternalAgentRuntime(id)) return EXTERNAL_AGENT_RUNTIME_DISPLAY_NAME;
12498
+ return RUNTIMES.find((r) => r.id === id)?.displayName ?? id;
12499
+ }
12500
+ //#endregion
12501
+ //#region ../shared/src/agentText/threadsProfile.ts
12502
+ /**
12503
+ * Runtime label for identity display in agent-facing output: product name plus
12504
+ * lifecycle status. Agent-facing text is English-only, so the suffix is literal
12505
+ * here; the web surface renders the same status from the i18n catalog.
12506
+ */
12507
+ function agentRuntimeLabelWithStatus(runtimeId) {
12508
+ const name = getRuntimeDisplayName(runtimeId);
12509
+ return isRuntimeDeprecated(runtimeId) ? `${name} (deprecated)` : name;
12510
+ }
12511
+ function formatDoneSuffix(thread) {
12512
+ return thread.doneAt ? `, doneAt=${thread.doneAt}` : "";
12513
+ }
12514
+ /** Followed thread list for the bound agent, including exact thread targets. */
12515
+ function formatAgentThreadList(threads) {
12516
+ if (threads.length === 0) return "No followed threads.";
12517
+ return [`Followed threads (${threads.length}):`, ...threads.map((thread) => `- ${thread.target} (${thread.threadChannelId}, parent=${thread.parentChannelRef}, followedAt=${thread.followedAt}, reason=${thread.reason}${formatDoneSuffix(thread)})`)].join("\n");
12518
+ }
12519
+ function formatCreatedAgents(createdAgents, runtimeLabel) {
12520
+ if (createdAgents.length === 0) return ["- Created Agents: none"];
12521
+ return [`- Created Agents (${createdAgents.length}):`, ...createdAgents.map((createdAgent) => ` - @${createdAgent.name} (${runtimeLabel(createdAgent.runtime)}, ${createdAgent.status})`)];
12522
+ }
12523
+ function formatHumanProfile(profile, runtimeLabel) {
12524
+ const lines = [
12525
+ "## Profile",
12526
+ "",
12527
+ "- Type: human",
12528
+ `- Handle: @${profile.name}`,
12529
+ `- Display Name: ${profile.displayName ?? "(none)"}`,
12530
+ `- Description: ${profile.description ?? "(none)"}`,
12531
+ `- Membership: ${profile.membershipStatus}`
12532
+ ];
12533
+ if (profile.role) lines.push(`- Role: ${profile.role}`);
12534
+ if (profile.joinedAt) lines.push(`- Joined: ${profile.joinedAt}`);
12535
+ if (profile.email) lines.push(`- Email: ${profile.email}`);
12536
+ return [...lines, ...formatCreatedAgents(profile.createdAgents, runtimeLabel)].join("\n");
12537
+ }
12538
+ function formatCreator(profile) {
12539
+ if (!profile.creator) return null;
12540
+ return profile.creator.displayName ? `${profile.creator.displayName} (@${profile.creator.name})` : `@${profile.creator.name}`;
12541
+ }
12542
+ function formatAgentProfileCard(profile, runtimeLabel) {
12543
+ const lines = [
12544
+ "## Profile",
12545
+ "",
12546
+ "- Type: agent",
12547
+ `- Handle: @${profile.name}`,
12548
+ `- Display Name: ${profile.displayName ?? "(none)"}`,
12549
+ `- Description: ${profile.description ?? "(none)"}`,
12550
+ `- Status: ${profile.status}`,
12551
+ `- Role: ${profile.serverRole}`,
12552
+ `- Runtime: ${runtimeLabel(profile.runtime)}`,
12553
+ `- Model: ${profile.model}`,
12554
+ `- Reasoning: ${profile.reasoningEffort ?? "medium"}`
12555
+ ];
12556
+ if (profile.executionMode) lines.push(`- Execution: ${profile.executionMode}`);
12557
+ if (profile.computerName || profile.computerId) {
12558
+ const label = profile.computerName && profile.computerId ? `${profile.computerName} (${profile.computerId})` : profile.computerName ?? profile.computerId;
12559
+ lines.push(`- Computer: ${label}`);
12560
+ }
12561
+ if (profile.computerHostname) lines.push(`- Hostname: ${profile.computerHostname}`);
12562
+ if (profile.daemonVersion) lines.push(`- Daemon: v${profile.daemonVersion}`);
12563
+ lines.push(`- Created: ${profile.createdAt}`);
12564
+ if (profile.deletedAt) lines.push(`- Deleted At: ${profile.deletedAt}`);
12565
+ const creator = formatCreator(profile);
12566
+ if (creator) lines.push(`- Creator: ${creator}`);
12567
+ return [...lines, ...formatCreatedAgents(profile.createdAgents, runtimeLabel)].join("\n");
12568
+ }
12569
+ /** Agent/human profile card. */
12570
+ function formatAgentProfile(profile, options = {}) {
12571
+ const runtimeLabel = options.runtimeLabel ?? agentRuntimeLabelWithStatus;
12572
+ return profile.kind === "human" ? formatHumanProfile(profile, runtimeLabel) : formatAgentProfileCard(profile, runtimeLabel);
12573
+ }
12574
+ //#endregion
12575
+ //#region ../shared/src/agentOps/channels.ts
12576
+ const INVALID_CHANNEL_TARGET = "Target must be a regular channel in the form '#channel-name'. DMs and thread targets are not supported.";
12577
+ async function resolveRegularChannel(client, target) {
12578
+ const name = parseRaftRegularChannelTarget$1(target ?? "");
12579
+ if (!name) return failureOutcome(opError("INVALID_REQUEST", { message: INVALID_CHANNEL_TARGET }));
12580
+ const info = await client.server.info();
12581
+ if (!info.ok) return failureFromClientResult(info);
12582
+ const channel = info.data.channels.find((candidate) => candidate.name === name);
12583
+ if (!channel) return failureOutcome(opError("NOT_FOUND", {
12584
+ message: `Channel not found: ${target}`,
12585
+ nextAction: "List visible channels with `raft server info --channels`; private channels need a human to add you."
12586
+ }));
12587
+ return {
12588
+ id: channel.id,
12589
+ name: channel.name,
12590
+ joined: channel.joined
12591
+ };
12592
+ }
12593
+ async function joinChannel(client, request) {
12594
+ const result = await joinRaftChannelByTarget$1(client, { target: request.target });
12595
+ if (!result.ok) {
12596
+ const error = result.error;
12597
+ if (error.kind === "validation") return error.reason === "target_not_found" ? failureOutcome(opError("NOT_FOUND", {
12598
+ message: error.message,
12599
+ nextAction: "Only visible public channels can be joined; private and joint channels need an invitation."
12600
+ })) : failureOutcome(opError("INVALID_REQUEST", { message: error.message }));
12601
+ if (error.kind === "http") return failureOutcome(opError("HTTP_ERROR", {
12602
+ message: error.message,
12603
+ status: error.status,
12604
+ ...error.errorCode ? { serverCode: error.errorCode } : {},
12605
+ ...error.suggestedNextAction ? { nextAction: error.suggestedNextAction } : {}
12606
+ }));
12607
+ return failureOutcome(opError("TRANSPORT_ERROR", { message: error.message }));
12608
+ }
12609
+ const state = result.data.state;
12610
+ return {
12611
+ ok: true,
12612
+ state,
12613
+ data: {
12614
+ target: result.data.target,
12615
+ channelId: result.data.channelId
12616
+ },
12617
+ next: {
12618
+ kind: "read_target",
12619
+ command: `raft message read --target "${result.data.target}"`,
12620
+ args: { target: result.data.target },
12621
+ why: "Read the channel before posting."
12622
+ },
12623
+ text: state === "joined" ? `Joined ${result.data.target}.` : `Already a member of ${result.data.target}.`
12624
+ };
12625
+ }
12626
+ async function leaveChannel(client, request) {
12627
+ const channel = await resolveRegularChannel(client, request.target);
12628
+ if ("ok" in channel) return channel;
12629
+ if (!channel.joined) return {
12630
+ ok: true,
12631
+ state: "not_joined",
12632
+ data: {
12633
+ target: request.target,
12634
+ channelId: channel.id
12635
+ },
12636
+ next: null,
12637
+ text: `You are not a member of ${request.target}; nothing to leave.`
12638
+ };
12639
+ const result = await client.channels.leave({ channelId: channel.id });
12640
+ if (!result.ok) return failureFromClientResult(result);
12641
+ const lines = [`Left ${request.target}. You can still inspect visible public channel history there, but you can no longer send or receive ordinary channel delivery until you join the public channel again or a human re-adds you to a private channel.`];
12642
+ const attention = result.data.attention;
12643
+ if (attention?.ordinaryActivity) lines.push(attention.ordinaryActivity);
12644
+ return {
12645
+ ok: true,
12646
+ state: "left",
12647
+ data: {
12648
+ target: request.target,
12649
+ channelId: channel.id
12650
+ },
12651
+ next: null,
12652
+ text: lines.join("\n")
12653
+ };
12654
+ }
12655
+ function formatSeq(value) {
12656
+ return value == null ? "none" : String(value);
12657
+ }
12658
+ async function setChannelMute(client, request, action) {
12659
+ const channel = await resolveRegularChannel(client, request.target);
12660
+ if ("ok" in channel) return channel;
12661
+ const result = action === "mute" ? await client.channels.mute({ channelId: channel.id }, {}) : await client.channels.unmute({ channelId: channel.id });
12662
+ if (!result.ok) return failureFromClientResult(result);
12663
+ const data = result.data;
12664
+ const lines = [
12665
+ `${data.activityMuted ? "Muted" : "Unmuted"} ${request.target}.`,
12666
+ `Activity muted: ${data.activityMuted ? "yes" : "no"}`,
12667
+ `Mute from seq: ${formatSeq(data.muteFromSeq)}`
12668
+ ];
12669
+ if (data.attention?.ordinaryActivity) lines.push(data.attention.ordinaryActivity);
12670
+ if (data.attention?.stillArrives?.length) {
12671
+ lines.push("Still arrives:");
12672
+ for (const item of data.attention.stillArrives) lines.push(`- ${item}`);
12673
+ }
12674
+ if (data.attention?.threadBoundary) lines.push(data.attention.threadBoundary);
12675
+ if (data.attention?.catchUp) lines.push(data.attention.catchUp);
12676
+ if (data.attention?.unmuteCommand) lines.push(`To unmute: ${data.attention.unmuteCommand}`);
12677
+ if (data.attention?.unmuteApi) lines.push(`Agent API: ${data.attention.unmuteApi}`);
12678
+ if (data.attention?.muteCommand) lines.push(`To mute: ${data.attention.muteCommand}`);
12679
+ if (data.attention?.muteApi) lines.push(`Agent API: ${data.attention.muteApi}`);
12680
+ return {
12681
+ ok: true,
12682
+ state: data.activityMuted ? "muted" : "unmuted",
12683
+ data: {
12684
+ target: request.target,
12685
+ channelId: channel.id,
12686
+ activityMuted: data.activityMuted === true,
12687
+ muteFromSeq: data.muteFromSeq ?? null,
12688
+ stillArrives: data.attention?.stillArrives ?? []
12689
+ },
12690
+ next: null,
12691
+ text: lines.join("\n")
12692
+ };
12693
+ }
12694
+ function muteChannel(client, request) {
12695
+ return setChannelMute(client, request, "mute");
12696
+ }
12697
+ function unmuteChannel(client, request) {
12698
+ return setChannelMute(client, request, "unmute");
12699
+ }
12700
+ async function channelMembers(client, request) {
12701
+ if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel, DM, or thread target is required." }));
12702
+ const result = await client.channels.members({ channel: request.target });
12703
+ if (!result.ok) return failureFromClientResult(result);
12704
+ return {
12705
+ ok: true,
12706
+ state: "members",
12707
+ data: result.data,
12708
+ next: null,
12709
+ text: formatAgentChannelMembers(result.data)
12710
+ };
12711
+ }
12712
+ async function listThreads(client) {
12713
+ const result = await client.threads.list();
12714
+ if (!result.ok) return failureFromClientResult(result);
12715
+ const threads = result.data.threads;
12716
+ return {
12717
+ ok: true,
12718
+ state: threads.length > 0 ? "threads" : "empty",
12719
+ data: threads,
12720
+ next: null,
12721
+ text: formatAgentThreadList(threads)
12722
+ };
12723
+ }
12724
+ async function unfollowThread(client, request) {
12725
+ if (!request.target?.includes(":")) return failureOutcome(opError("INVALID_REQUEST", { message: "A thread target is required, for example '#channel:shortid' or 'dm:@peer:shortid'." }));
12726
+ const result = await client.threads.unfollow({
12727
+ thread: request.target,
12728
+ ...request.reason ? { reason: request.reason } : {}
12729
+ });
12730
+ if (!result.ok) return failureFromClientResult(result);
12731
+ return {
12732
+ ok: true,
12733
+ state: "unfollowed",
12734
+ data: { target: request.target },
12735
+ next: null,
12736
+ text: `Unfollowed ${request.target}. Ordinary delivery from this thread stops; a direct @mention reactivates the follow.`
12737
+ };
12738
+ }
12739
+ //#endregion
12740
+ //#region ../shared/src/agentOps/server.ts
12741
+ function nextCommand(section, request, offset, limit, total) {
12742
+ const nextOffset = offset + limit;
12743
+ if (nextOffset >= total) return void 0;
12744
+ const parts = [
12745
+ "raft server info",
12746
+ `--${section}`,
12747
+ `--offset ${nextOffset}`,
12748
+ `--limit ${limit}`
12749
+ ];
12750
+ if (section === "channels" && request.joined) parts.push("--joined");
12751
+ return parts.join(" ");
12752
+ }
12753
+ async function serverInfo(client, request = {}) {
12754
+ const result = await client.server.info();
12755
+ if (!result.ok) return failureFromClientResult(result);
12756
+ const server = result.data;
12757
+ const view = request.view ?? "summary";
12758
+ if (view === "summary") return {
12759
+ ok: true,
12760
+ state: "info",
12761
+ data: {
12762
+ view,
12763
+ server,
12764
+ page: null
12765
+ },
12766
+ next: {
12767
+ kind: "list_channels",
12768
+ command: "raft server info --channels",
12769
+ why: "The summary only counts; list a section to see names."
12770
+ },
12771
+ text: formatAgentServerSummary(server)
12772
+ };
12773
+ if (view === "full") return {
12774
+ ok: true,
12775
+ state: "info",
12776
+ data: {
12777
+ view,
12778
+ server,
12779
+ page: null
12780
+ },
12781
+ next: null,
12782
+ text: formatAgentServerInfo(server)
12783
+ };
12784
+ const limit = Math.max(1, Math.trunc(request.limit ?? 50));
12785
+ const offset = Math.max(0, Math.trunc(request.offset ?? 0));
12786
+ const rows = view === "channels" ? server.channels.filter((c) => !request.joined || c.joined) : view === "agents" ? server.agents : server.humans;
12787
+ const pageRows = rows.slice(offset, offset + limit);
12788
+ const page = {
12789
+ section: view,
12790
+ total: rows.length,
12791
+ offset,
12792
+ limit,
12793
+ nextCommand: nextCommand(view, request, offset, limit, rows.length)
12794
+ };
12795
+ const text = view === "channels" ? formatAgentServerChannels(pageRows, page) : view === "agents" ? formatAgentServerAgents(pageRows, page) : formatAgentServerHumans(pageRows, page);
12796
+ const next = page.nextCommand ? {
12797
+ kind: "next_page",
12798
+ command: page.nextCommand,
12799
+ args: {
12800
+ view,
12801
+ offset: offset + limit,
12802
+ limit
12803
+ },
12804
+ why: "More rows exist; one page is one page."
12805
+ } : null;
12806
+ return {
12807
+ ok: true,
12808
+ state: "info",
12809
+ data: {
12810
+ view,
12811
+ server,
12812
+ page
12813
+ },
12814
+ next,
12815
+ text
12816
+ };
12817
+ }
12818
+ async function showProfile(client, request = {}, options = {}) {
12819
+ const result = await client.profile.show(request.target ? { target: request.target } : {});
12820
+ if (!result.ok) return failureFromClientResult(result);
12821
+ return {
12822
+ ok: true,
12823
+ state: "profile",
12824
+ data: result.data,
12825
+ next: null,
12826
+ text: formatAgentProfile(result.data, options)
12827
+ };
12828
+ }
12829
+ async function updateProfile(client, request, options = {}) {
12830
+ if (request.displayName === void 0 && request.description === void 0 && request.avatarUrl === void 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a displayName, description, or avatarUrl to update." }));
12831
+ const result = await client.profile.update(request);
12832
+ if (!result.ok) return failureFromClientResult(result);
12833
+ return {
12834
+ ok: true,
12835
+ state: "updated",
12836
+ data: result.data,
12837
+ next: null,
12838
+ text: formatAgentProfile(result.data, options)
12839
+ };
12840
+ }
12841
+ //#endregion
12842
+ //#region ../shared/src/agentText/attachments.ts
12843
+ /** Upload receipt with attachment id and send-usage hint. */
12844
+ function formatAgentAttachmentUploaded(attachment) {
12845
+ 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`;
12846
+ }
12847
+ function anchorSummary(anchor) {
12848
+ if (anchor.type === "md-section") {
12849
+ const title = anchor.data.headingTitle ?? anchor.data.headingId;
12850
+ return typeof title === "string" && title ? `§ ${title}` : "§ section";
12851
+ }
12852
+ if (anchor.type === "lines" || anchor.type === "csv-rows") {
12853
+ const start = Number(anchor.data.start);
12854
+ const end = Number(anchor.data.end ?? start);
12855
+ if (!Number.isFinite(start)) return anchor.type;
12856
+ const prefix = anchor.type === "lines" ? "L" : "rows ";
12857
+ return start === (Number.isFinite(end) ? end : start) ? `${prefix}${start}` : `${prefix}${start}–${end}`;
12858
+ }
12859
+ if (anchor.type === "html-region") {
12860
+ const quote = anchor.data.quote;
12861
+ if (typeof quote === "string" && quote.trim().length > 0) {
12862
+ const trimmed = quote.trim();
12863
+ return trimmed.length > 60 ? `${trimmed.slice(0, 60)}…` : trimmed;
12864
+ }
12865
+ return "HTML region";
12866
+ }
12867
+ return anchor.type;
12868
+ }
12869
+ /** Attachment-scoped comment list incl. anchors/reactions, or its empty state. */
12870
+ function formatAgentAttachmentComments(attachmentId, comments, threadChannelId) {
12871
+ if (comments.length === 0) return `No comments on attachment ${attachmentId.slice(0, 8)}.\n`;
12872
+ const lines = [`## Comments on attachment ${attachmentId.slice(0, 8)} (${comments.length})`];
12873
+ for (const c of comments) {
12874
+ const check = c.reactions.some((r) => r.emoji === "✅") ? " ✅" : "";
12875
+ const anchor = c.anchor ? ` [anchor: ${anchorSummary(c.anchor)}]` : "";
12876
+ lines.push(`[msg=${c.id.slice(0, 8)} time=${c.createdAt} type=${c.senderType}]${check}${anchor} @${c.senderName}: ${c.content}`);
12877
+ }
12878
+ if (threadChannelId) lines.push(`(full conversation lives in thread channel ${threadChannelId})`);
12879
+ return lines.join("\n") + "\n";
12880
+ }
12881
+ //#endregion
12882
+ //#region ../shared/src/agentOps/attachments.ts
12883
+ /** Compatibility fallback for Servers that predate the capability endpoint (the CLI's constant). */
12884
+ const AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES = 52428800;
12885
+ const FILENAME_MIME_MAP = {
12886
+ ".jpg": "image/jpeg",
12887
+ ".jpeg": "image/jpeg",
12888
+ ".png": "image/png",
12889
+ ".gif": "image/gif",
12890
+ ".webp": "image/webp",
12891
+ ".pdf": "application/pdf",
12892
+ ".txt": "text/plain",
12893
+ ".md": "text/markdown",
12894
+ ".json": "application/json",
12895
+ ".csv": "text/csv"
12896
+ };
12897
+ const MIME_TYPE_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
12898
+ function sniffMimeType(bytes) {
12899
+ const starts = (sig) => sig.every((b, i) => bytes[i] === b);
12900
+ if (bytes.length >= 8 && starts([
12901
+ 137,
12902
+ 80,
12903
+ 78,
12904
+ 71,
12905
+ 13,
12906
+ 10,
12907
+ 26,
12908
+ 10
12909
+ ])) return "image/png";
12910
+ if (bytes.length >= 3 && starts([
12911
+ 255,
12912
+ 216,
12913
+ 255
12914
+ ])) return "image/jpeg";
12915
+ if (bytes.length >= 6) {
12916
+ const header = String.fromCharCode(...bytes.subarray(0, 6));
12917
+ if (header === "GIF87a" || header === "GIF89a") return "image/gif";
12918
+ }
12919
+ if (bytes.length >= 12 && String.fromCharCode(...bytes.subarray(0, 4)) === "RIFF" && String.fromCharCode(...bytes.subarray(8, 12)) === "WEBP") return "image/webp";
12920
+ return null;
12921
+ }
12922
+ /** Explicit type wins; otherwise sniff the bytes, then the filename extension, then octet-stream. */
12923
+ function inferAttachmentMimeType(filename, bytes, explicit) {
12924
+ const normalized = explicit?.trim().toLowerCase();
12925
+ if (normalized && MIME_TYPE_RE.test(normalized)) return normalized;
12926
+ const dot = filename.lastIndexOf(".");
12927
+ const ext = dot >= 0 ? filename.slice(dot).toLowerCase() : "";
12928
+ return sniffMimeType(bytes) ?? FILENAME_MIME_MAP[ext] ?? "application/octet-stream";
12929
+ }
12930
+ /**
12931
+ * Small-file multipart upload (`POST /upload`). Files at or above the Server's
12932
+ * direct-upload threshold need the upload-session routes (`routes.attachments.
12933
+ * createUploadSession` …), which this operation reports as `UNAVAILABLE` with a
12934
+ * next action rather than attempting silently.
12935
+ */
12936
+ async function uploadAttachment(client, transport, request) {
12937
+ if (!request.target?.trim() || !request.filename?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and a filename are required to upload." }));
12938
+ if (!(request.bytes instanceof Uint8Array) || request.bytes.byteLength === 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Refusing to upload a 0-byte attachment." }));
12939
+ 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}` }));
12940
+ const capability = await client.attachments.uploadCapabilities();
12941
+ const maxBytes = capability.ok ? capability.data.maxBytes : AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES;
12942
+ const threshold = capability.ok && capability.data.directUploadEnabled ? capability.data.directUploadThresholdBytes : null;
12943
+ if (request.bytes.byteLength > maxBytes) return failureOutcome(opError("INVALID_REQUEST", { message: `Attachment is ${request.bytes.byteLength} bytes; the Server's maximum is ${maxBytes}.` }));
12944
+ if (threshold !== null && request.bytes.byteLength >= threshold) return failureOutcome(opError("UNAVAILABLE", {
12945
+ message: `Files of ${threshold} bytes or more use the direct-upload session routes, which this operation does not drive yet.`,
12946
+ nextAction: "Use routes.attachments.createUploadSession / completeUploadSession, or upload a smaller file.",
12947
+ retryable: false
12948
+ }));
12949
+ const resolved = await client.channels.resolve({ target: request.target });
12950
+ if (!resolved.ok) return failureFromClientResult(resolved);
12951
+ const channelId = resolved.data.channelId;
12952
+ const mimeType = inferAttachmentMimeType(request.filename, request.bytes, request.mimeType);
12953
+ const copy = new Uint8Array(request.bytes.byteLength);
12954
+ copy.set(request.bytes);
12955
+ const form = new FormData();
12956
+ form.append("file", new Blob([copy.buffer], { type: mimeType }), request.filename);
12957
+ form.append("channelId", channelId);
12958
+ if (request.mimeType) form.append("mimeType", mimeType);
12959
+ const headers = new Headers(transport.headers);
12960
+ headers.delete("content-type");
12961
+ headers.set("accept", "application/json");
12962
+ headers.set("authorization", transport.authorization);
12963
+ let response;
12964
+ try {
12965
+ response = await transport.fetch(`${transport.serverUrl}${agentApiContract.attachmentUpload.fullPath}`, {
12966
+ method: "POST",
12967
+ headers,
12968
+ body: form
12969
+ });
12970
+ } catch {
12971
+ return failureOutcome(opError("TRANSPORT_ERROR"));
12972
+ }
12973
+ let body = null;
12974
+ try {
12975
+ body = await response.json();
12976
+ } catch {
12977
+ body = null;
12978
+ }
12979
+ if (!response.ok) {
12980
+ const b = body && typeof body === "object" ? body : {};
12981
+ return failureOutcome(opErrorFromClientError({
12982
+ kind: "http",
12983
+ reason: "http_error",
12984
+ message: typeof b.error === "string" ? b.error : `HTTP ${response.status}`,
12985
+ status: response.status,
12986
+ errorCode: typeof b.errorCode === "string" ? b.errorCode : typeof b.code === "string" ? b.code : null,
12987
+ suggestedNextAction: typeof b.suggestedNextAction === "string" ? b.suggestedNextAction : null
12988
+ }));
12989
+ }
12990
+ const parsed = agentApiContract.attachmentUpload.response.body.safeParse(body);
12991
+ if (!parsed.success) return failureOutcome(opError("INVALID_RESPONSE"));
12992
+ const data = parsed.data;
12993
+ return {
12994
+ ok: true,
12995
+ state: "uploaded",
12996
+ data: {
12997
+ ...data,
12998
+ target: request.target,
12999
+ mimeType: data.mimeType ?? mimeType
13000
+ },
13001
+ next: {
13002
+ kind: "send_with_attachment",
13003
+ command: `raft message send --target "${request.target}" --attachment-id ${data.id}`,
13004
+ args: {
13005
+ target: request.target,
13006
+ attachmentIds: [data.id]
13007
+ },
13008
+ why: "The upload alone posts nothing; send a message that links the attachment id."
13009
+ },
13010
+ text: formatAgentAttachmentUploaded(data)
13011
+ };
13012
+ }
13013
+ async function downloadAttachment(client, request) {
13014
+ if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13015
+ const result = await client.attachments.download({ attachmentId: request.attachmentId });
13016
+ if (!result.ok) return failureFromClientResult(result);
13017
+ const bytes = result.data;
13018
+ return {
13019
+ ok: true,
13020
+ state: "downloaded",
13021
+ data: {
13022
+ attachmentId: request.attachmentId,
13023
+ bytes
13024
+ },
13025
+ next: null,
13026
+ text: `Downloaded attachment ${request.attachmentId.slice(0, 8)} (${bytes.byteLength} bytes).`
13027
+ };
13028
+ }
13029
+ async function attachmentComments(client, request) {
13030
+ if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13031
+ const result = await client.attachments.comments({ attachmentId: request.attachmentId }, request.limit === void 0 ? {} : { limit: String(request.limit) });
13032
+ if (!result.ok) return failureFromClientResult(result);
13033
+ const data = result.data;
13034
+ return {
13035
+ ok: true,
13036
+ state: data.comments.length > 0 ? "comments" : "empty",
13037
+ data: {
13038
+ ...data,
13039
+ attachmentId: request.attachmentId
13040
+ },
13041
+ next: null,
13042
+ text: formatAgentAttachmentComments(request.attachmentId, data.comments, data.threadChannelId)
13043
+ };
13044
+ }
13045
+ //#endregion
13046
+ //#region ../shared/src/agentText/search.ts
13047
+ /** Local wall-clock rendering with offset, as the CLI prints search hit times. */
13048
+ function formatLocalTimeWithOffset(iso) {
13049
+ const d = new Date(iso);
13050
+ if (isNaN(d.getTime())) return iso;
13051
+ const pad = (n) => String(n).padStart(2, "0");
13052
+ const offsetMinutes = -d.getTimezoneOffset();
13053
+ const sign = offsetMinutes >= 0 ? "+" : "-";
13054
+ const absOffset = Math.abs(offsetMinutes);
13055
+ const offset = `${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`;
13056
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} ${offset}`;
13057
+ }
13058
+ function renderSearchSource(result) {
13059
+ if (result.channelType === "thread") {
13060
+ const shortId = typeof result.channelName === "string" && result.channelName.startsWith("thread-") ? result.channelName.slice(7) : typeof result.threadId === "string" && result.threadId ? result.threadId.slice(0, 8) : result.channelName;
13061
+ if (result.parentChannelType === "dm") return `dm:${neutralizeAgentRaftRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
13062
+ return `thread:${neutralizeAgentRaftRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
13063
+ }
13064
+ if (result.channelType === "dm") return `dm:${neutralizeAgentRaftRefLiterals(result.channelName ?? "unknown")}`;
13065
+ return `channel:${neutralizeAgentRaftRefLiterals(result.channelName ?? "unknown")}`;
13066
+ }
13067
+ const PREVIEW_BEFORE_CHARS = 80;
13068
+ const PREVIEW_AFTER_CHARS = 120;
13069
+ const PREVIEW_FALLBACK_CHARS = 200;
13070
+ function escapeRegExp(value) {
13071
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13072
+ }
13073
+ function findSearchMatch(content, query) {
13074
+ const normalizedQuery = query.trim();
13075
+ if (!normalizedQuery) return null;
13076
+ const exactIndex = content.toLowerCase().indexOf(normalizedQuery.toLowerCase());
13077
+ if (exactIndex >= 0) return {
13078
+ start: exactIndex,
13079
+ end: exactIndex + normalizedQuery.length
13080
+ };
13081
+ const terms = normalizedQuery.match(/"([^"]+)"|\S+/g) ?? [];
13082
+ for (const rawTerm of terms) {
13083
+ const term = rawTerm.replace(/^"|"$/g, "").trim();
13084
+ if (!term) continue;
13085
+ const match = new RegExp(escapeRegExp(term), "i").exec(content);
13086
+ if (match?.index !== void 0) return {
13087
+ start: match.index,
13088
+ end: match.index + match[0].length
13089
+ };
13090
+ }
13091
+ return null;
13092
+ }
13093
+ function* findRaftRefLiteralRanges(content) {
13094
+ for (const match of content.matchAll(/\bdm:@[A-Za-z0-9][A-Za-z0-9_-]*(?:~(?:agent|human))?/g)) if (match.index !== void 0) yield {
13095
+ start: match.index,
13096
+ end: match.index + match[0].length
13097
+ };
13098
+ for (const match of content.matchAll(/\btask #[0-9]+\b/g)) if (match.index !== void 0) yield {
13099
+ start: match.index,
13100
+ end: match.index + match[0].length
13101
+ };
13102
+ for (const match of content.matchAll(/(^|[\n\s([{"'`;])(@[A-Za-z0-9][A-Za-z0-9_-]*)/g)) {
13103
+ if (match.index === void 0) continue;
13104
+ const prefix = match[1] ?? "";
13105
+ const ref = match[2] ?? "";
13106
+ yield {
13107
+ start: match.index + prefix.length,
13108
+ end: match.index + prefix.length + ref.length
13109
+ };
13110
+ }
13111
+ for (const match of content.matchAll(/(^|[\n\s([{"'`;])(#[A-Za-z][A-Za-z0-9_-]*)/g)) {
13112
+ if (match.index === void 0) continue;
13113
+ const prefix = match[1] ?? "";
13114
+ const ref = match[2] ?? "";
13115
+ yield {
13116
+ start: match.index + prefix.length,
13117
+ end: match.index + prefix.length + ref.length
13118
+ };
13119
+ }
13120
+ }
13121
+ function expandSearchMatchToRefLiteral(content, match) {
13122
+ for (const refRange of findRaftRefLiteralRanges(content)) if (match.start < refRange.end && match.end > refRange.start) return {
13123
+ start: Math.min(match.start, refRange.start),
13124
+ end: Math.max(match.end, refRange.end)
13125
+ };
13126
+ return match;
13127
+ }
13128
+ function trimPreviewWindow(content, start, end) {
13129
+ let trimmedStart = start;
13130
+ let trimmedEnd = end;
13131
+ while (trimmedStart > 0 && /\s/.test(content[trimmedStart] ?? "")) trimmedStart += 1;
13132
+ while (trimmedEnd < content.length && /\s/.test(content[trimmedEnd - 1] ?? "")) trimmedEnd -= 1;
13133
+ return {
13134
+ start: Math.max(0, Math.min(trimmedStart, content.length)),
13135
+ end: Math.max(0, Math.min(trimmedEnd, content.length))
13136
+ };
13137
+ }
13138
+ function escapeSearchComponentLiterals(text) {
13139
+ return text.replace(/<\/?(?:result|preview|match)\b[^>]*>|<omit\s*\/>/gi, (tag) => tag.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
13140
+ }
13141
+ /** Neutralise `@handle`, `#channel`, `dm:@peer`, and `task #N` literals so quoted text cannot route attention. */
13142
+ function neutralizeAgentRaftRefLiterals(text) {
13143
+ return text.replace(/\bdm:@([A-Za-z0-9][A-Za-z0-9_-]*(?:~(?:agent|human))?)/g, "dm:user:$1").replace(/\btask #([0-9]+)\b/g, "task:$1").replace(/(^|[\n\s([{"'`;])@([A-Za-z0-9][A-Za-z0-9_-]*)/g, "$1user:$2").replace(/(^|[\n\s([{"'`;])#([A-Za-z][A-Za-z0-9_-]*)/g, "$1channel:$2");
13144
+ }
13145
+ function renderAgentSearchPreviewText(text) {
13146
+ return neutralizeAgentRaftRefLiterals(escapeSearchComponentLiterals(text));
13147
+ }
13148
+ function renderSearchPreview(content, query) {
13149
+ const foundMatch = findSearchMatch(content, query);
13150
+ const match = foundMatch ? expandSearchMatchToRefLiteral(content, foundMatch) : null;
13151
+ let start = 0;
13152
+ let end = Math.min(content.length, PREVIEW_FALLBACK_CHARS);
13153
+ if (match) {
13154
+ start = Math.max(0, match.start - PREVIEW_BEFORE_CHARS);
13155
+ end = Math.min(content.length, match.end + PREVIEW_AFTER_CHARS);
13156
+ }
13157
+ ({start, end} = trimPreviewWindow(content, start, end));
13158
+ const leadingOmit = start > 0 ? "<omit />" : "";
13159
+ const trailingOmit = end < content.length ? "<omit />" : "";
13160
+ if (!match || match.end <= start || match.start >= end) return `${leadingOmit}${renderAgentSearchPreviewText(content.slice(start, end))}${trailingOmit}`;
13161
+ const before = content.slice(start, match.start);
13162
+ const matched = content.slice(match.start, match.end);
13163
+ const after = content.slice(match.end, end);
13164
+ return [
13165
+ leadingOmit,
13166
+ renderAgentSearchPreviewText(before),
13167
+ "<match>",
13168
+ renderAgentSearchPreviewText(matched),
13169
+ "</match>",
13170
+ renderAgentSearchPreviewText(after),
13171
+ trailingOmit
13172
+ ].join("");
13173
+ }
13174
+ /** Search results with <match>/<omit /> preview markup. */
13175
+ function formatAgentSearchResults(query, data, offset, sort, limit) {
13176
+ const trimmedQuery = query.trim();
13177
+ const oldestShown = data.results?.length ? data.results[data.results.length - 1]?.createdAt : void 0;
13178
+ 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)}`;
13179
+ const effectiveLimit = Math.min(limit ?? 20, 50);
13180
+ const countEqualsLimit = (data.results?.length ?? 0) === effectiveLimit;
13181
+ 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`;
13182
+ 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`;
13183
+ 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";
13184
+ if (!data.results || data.results.length === 0) return `No search results. (${truncation})`;
13185
+ const formatted = data.results.map((result) => {
13186
+ const ref = `msg:${result.id}`;
13187
+ const content = result.content ?? result.snippet ?? "";
13188
+ const sender = neutralizeAgentRaftRefLiterals(result.senderName ?? "unknown");
13189
+ const senderType = result.senderType ? ` (${result.senderType})` : "";
13190
+ const taskProjection = formatAgentTaskCurrentProjection(result.taskCurrentProjection, result.taskNumber, renderAgentSearchPreviewText).trimStart();
13191
+ return [
13192
+ `<result ref="${ref}">`,
13193
+ `Source: ${renderSearchSource(result)}`,
13194
+ `Sender: ${sender}${senderType}`,
13195
+ `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt) : "-"}`,
13196
+ ...taskProjection ? [taskProjection] : [],
13197
+ "",
13198
+ "<preview>",
13199
+ renderSearchPreview(content, trimmedQuery),
13200
+ "</preview>",
13201
+ "</result>"
13202
+ ].join("\n");
13203
+ }).join("\n\n");
13204
+ const resultLabel = data.results.length === 1 ? "result" : "results";
13205
+ const count = `${data.results.length} ${resultLabel} · ${truncation}`;
13206
+ return [
13207
+ trimmedQuery ? `Search results for: "${trimmedQuery}" (${count})` : `Filtered message results (${count})`,
13208
+ "",
13209
+ formatted,
13210
+ "",
13211
+ "If a result may be relevant but its preview is not enough, read the surrounding context for that result before answering."
13212
+ ].join("\n");
13213
+ }
13214
+ //#endregion
13215
+ //#region ../shared/src/agentOps/search.ts
13216
+ async function searchMessages(client, request) {
13217
+ if (!request.query?.trim() && !request.target && !request.sender) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a query, or filter by target or sender." }));
13218
+ const result = await client.messages.search({
13219
+ ...request.query?.trim() ? { q: request.query.trim() } : {},
13220
+ ...request.target ? { channel: request.target } : {},
13221
+ ...request.sender ? { sender: request.sender } : {},
13222
+ ...request.sort ? { sort: request.sort } : {},
13223
+ ...request.before ? { before: request.before } : {},
13224
+ ...request.after ? { after: request.after } : {},
13225
+ ...request.limit === void 0 ? {} : { limit: String(request.limit) },
13226
+ ...request.offset === void 0 ? {} : { offset: String(request.offset) }
13227
+ });
13228
+ if (!result.ok) return failureFromClientResult(result);
13229
+ const data = result.data;
13230
+ const hasMore = typeof data.hasMore === "boolean" ? data.hasMore : null;
13231
+ const page = {
13232
+ query: request.query?.trim() ?? "",
13233
+ results: data.results,
13234
+ hasMore
13235
+ };
13236
+ const next = hasMore ? {
13237
+ kind: "next_search_page",
13238
+ args: {
13239
+ ...request,
13240
+ offset: (request.offset ?? 0) + data.results.length
13241
+ },
13242
+ why: "More results exist; page on, or narrow the query."
13243
+ } : null;
13244
+ return {
13245
+ ok: true,
13246
+ state: data.results.length > 0 ? "results" : "empty",
13247
+ data: page,
13248
+ next,
13249
+ text: formatAgentSearchResults(page.query, {
13250
+ results: data.results,
13251
+ ...hasMore === null ? {} : { hasMore }
13252
+ }, request.offset, request.sort, request.limit)
13253
+ };
13254
+ }
13255
+ async function resolveMessage(client, request) {
13256
+ if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13257
+ const result = await client.messages.resolve({ msgId: request.messageId });
13258
+ if (!result.ok) return failureFromClientResult(result);
13259
+ const message = projectRaftMessage(result.data.message);
13260
+ if (!message) return failureOutcome(opError("INVALID_RESPONSE", { message: "The resolved message carries no conversation identity." }));
13261
+ return {
13262
+ ok: true,
13263
+ state: "message",
13264
+ data: message,
13265
+ next: {
13266
+ kind: "read_target",
13267
+ command: `raft message read --target "${message.target}" --around ${message.shortId ?? request.messageId}`,
13268
+ args: {
13269
+ target: message.target,
13270
+ around: message.id ?? request.messageId
13271
+ },
13272
+ why: "Read the surrounding context before acting on one message."
13273
+ },
13274
+ text: formatAgentMessages([toAgentMessageLike(message.raw)])
13275
+ };
13276
+ }
13277
+ async function reactToMessage(client, request, action = "add") {
13278
+ const emoji = request.emoji?.trim();
13279
+ if (!request.messageId?.trim() || !emoji || /\s/.test(emoji) || emoji.length > 16) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id and a single reaction emoji are required." }));
13280
+ const params = { msgId: request.messageId };
13281
+ const result = action === "add" ? await client.messages.addReaction(params, { emoji }) : await client.messages.removeReaction(params, { emoji });
13282
+ if (!result.ok) return failureFromClientResult(result);
13283
+ const verb = action === "add" ? "added to" : "removed from";
13284
+ return {
13285
+ ok: true,
13286
+ state: action === "add" ? "added" : "removed",
13287
+ data: {
13288
+ messageId: request.messageId,
13289
+ emoji
13290
+ },
13291
+ next: null,
13292
+ text: `Reaction ${emoji} ${verb} message ${request.messageId.slice(0, 8)}.`
13293
+ };
13294
+ }
13295
+ //#endregion
13296
+ //#region ../shared/src/agentText/mentions.ts
13297
+ function normalizeAgentMentionAction(action) {
13298
+ if (action === "notify" || action === "notify_only") return "notify";
13299
+ if (action === "add" || action === "invite") return "add";
13300
+ return null;
13301
+ }
13302
+ function formatActionCommands(action) {
13303
+ const verbs = action.availableActions.map(normalizeAgentMentionAction).filter((verb) => verb !== null);
13304
+ return Array.from(new Set(verbs)).map((verb) => ` ${verb}: raft mention ${verb} ${action.resolutionId}`);
13305
+ }
13306
+ function formatAuthoredMentionToken(targetHandle) {
13307
+ return targetHandle.startsWith("@") ? targetHandle : `@${targetHandle}`;
13308
+ }
13309
+ 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;
13310
+ /** Per-token mention recovery command line; null when the id is not a UUID (fail closed). */
13311
+ function formatAgentMentionNotifyRecoveryCommand(resolutionId) {
13312
+ return PENDING_MENTION_ACTION_ID_RE.test(resolutionId) ? `raft mention notify ${resolutionId}` : null;
13313
+ }
13314
+ function toAgentSenderPendingMentionAction(action) {
13315
+ return {
13316
+ resolutionId: action.resolutionId,
13317
+ messageId: action.messageId,
13318
+ targetHandle: formatAuthoredMentionToken(action.targetHandle),
13319
+ status: "not_queued",
13320
+ reason: "not_in_conversation",
13321
+ consequence: "This @mention did not notify anyone.",
13322
+ expiresAt: action.expiresAt ?? null,
13323
+ recoveryCommand: formatAgentMentionNotifyRecoveryCommand(action.resolutionId)
13324
+ };
13325
+ }
13326
+ function toAgentSenderUnresolvedMentionWarning(targetHandle) {
13327
+ return {
13328
+ targetHandle: formatAuthoredMentionToken(targetHandle),
13329
+ status: "not_queued",
13330
+ reason: "unknown_or_not_visible",
13331
+ consequence: "This @mention did not notify anyone.",
13332
+ expiresAt: null,
13333
+ recoveryCommand: null
13334
+ };
13335
+ }
13336
+ function formatPendingReason(reason) {
13337
+ if (reason === "not_member") return "not in the conversation at send time, so the @mention was not delivered";
13338
+ return reason;
13339
+ }
13340
+ function normalizeAgentPendingMentionActions(data) {
13341
+ const value = data;
13342
+ return (Array.isArray(value?.pendingMentionActions) ? value.pendingMentionActions : Array.isArray(value?.actions) ? value.actions : Array.isArray(value?.results) ? value.results : []).filter((item) => Boolean(item && typeof item === "object")).map((item) => ({
13343
+ resolutionId: String(item.resolutionId ?? item.id ?? ""),
13344
+ messageId: String(item.messageId ?? ""),
13345
+ targetType: String(item.targetType ?? "unknown"),
13346
+ targetHandle: String(item.targetHandle ?? ""),
13347
+ reason: String(item.reason ?? "Mention target was not notified at send time."),
13348
+ availableActions: Array.isArray(item.availableActions) ? item.availableActions.map(String) : [],
13349
+ expiresAt: typeof item.expiresAt === "string" ? item.expiresAt : null
13350
+ })).filter((item) => item.resolutionId.length > 0);
13351
+ }
13352
+ function normalizeAgentMentionActionResults(data) {
13353
+ const value = data;
13354
+ return (Array.isArray(value?.results) ? value.results : Array.isArray(value?.actionResults) ? value.actionResults : []).filter((item) => Boolean(item && typeof item === "object")).map((item) => ({
13355
+ resolutionId: String(item.resolutionId ?? item.id ?? ""),
13356
+ status: String(item.status ?? "not_found"),
13357
+ action: typeof item.action === "string" ? normalizeAgentMentionAction(item.action) : null,
13358
+ messageId: typeof item.messageId === "string" ? item.messageId : null,
13359
+ channelId: typeof item.channelId === "string" ? item.channelId : null,
13360
+ targetType: typeof item.targetType === "string" ? item.targetType : null,
13361
+ targetId: typeof item.targetId === "string" ? item.targetId : null,
13362
+ targetHandle: typeof item.targetHandle === "string" ? item.targetHandle : null,
13363
+ message: typeof item.message === "string" ? item.message : null,
13364
+ reason: typeof item.reason === "string" ? item.reason : null,
13365
+ dedupedResolutionIds: Array.isArray(item.dedupedResolutionIds) ? item.dedupedResolutionIds.filter((id) => typeof id === "string" && id.length > 0) : []
13366
+ })).filter((item) => item.resolutionId.length > 0);
13367
+ }
13368
+ const PENDING_DEFAULT_LIMIT = 50;
13369
+ function pendingPageVerdict(hasMore, limit, shown) {
13370
+ const asked = limit === void 0 ? "server default 50" : `--limit ${limit}`;
13371
+ 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`;
13372
+ if (hasMore === false) return `shown ${shown}, ${asked} — truncated=false · this is the complete list`;
13373
+ return `shown ${shown}, ${asked} — truncated=unknown · server did not report has_more, so completeness is NOT asserted`;
13374
+ }
13375
+ /** Undelivered-mentions partial result (send) or the pending list. */
13376
+ function formatAgentPendingMentionActions(actions, opts = {}) {
13377
+ const unresolvedMentionHandles = opts.source === "send" ? Array.from(new Set(opts.unresolvedMentionHandles ?? [])) : [];
13378
+ const pageNote = opts.source === "pending" ? pendingPageVerdict(opts.hasMore, opts.limit, actions.length) : "";
13379
+ if (actions.length === 0 && unresolvedMentionHandles.length === 0) return opts.source === "pending" ? `Pending mention actions\n\nNo pending mention actions. (${pageNote})\n` : "";
13380
+ if (opts.source === "send") {
13381
+ const lines = [
13382
+ "Undelivered mentions — partial result",
13383
+ "Message effect: status=queued. Queue acceptance is the only message proof.",
13384
+ "Do not rerun `raft message send`; the message is already queued and a retry could duplicate it.",
13385
+ "Each row below is bound to the literal @token from your message.",
13386
+ "For a literal name rather than a recipient, wrap the @handle in inline or fenced code.",
13387
+ ""
13388
+ ];
13389
+ for (const rawAction of actions) {
13390
+ const action = toAgentSenderPendingMentionAction(rawAction);
13391
+ lines.push(`- ${action.targetHandle} — status=${action.status}`);
13392
+ lines.push(` reason: ${action.reason}`);
13393
+ lines.push(` consequence: ${action.consequence}`);
13394
+ lines.push(` pending action: ${action.recoveryCommand ? action.resolutionId : "[invalid pending action id]"}`);
13395
+ if (action.messageId) lines.push(` message: ${action.messageId}`);
13396
+ lines.push(` expires: ${action.expiresAt ?? "unknown"}`);
13397
+ if (action.recoveryCommand) {
13398
+ lines.push(` recovery: ${action.recoveryCommand}`);
13399
+ 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.");
13400
+ lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
13401
+ } else lines.push(" recovery: unavailable because the pending action id is invalid; inspect `raft mention pending` without resending the message.");
13402
+ }
13403
+ for (const rawHandle of unresolvedMentionHandles) {
13404
+ const warning = toAgentSenderUnresolvedMentionWarning(rawHandle);
13405
+ lines.push(`- ${warning.targetHandle} — status=${warning.status}`);
13406
+ lines.push(` reason: ${warning.reason}`);
13407
+ lines.push(` consequence: ${warning.consequence}`);
13408
+ lines.push(" pending action: none; no visible target resolved for this token");
13409
+ lines.push(" expires: n/a");
13410
+ lines.push(" recovery: if this was a literal name or prose, wrap it in inline/fenced code; otherwise verify the exact handle and send only a corrected follow-up mention; do not resend this message.");
13411
+ }
13412
+ return `${lines.join("\n")}\n`;
13413
+ }
13414
+ const lines = [
13415
+ "Pending mention actions",
13416
+ `(${pageNote})`,
13417
+ ""
13418
+ ];
13419
+ for (const action of actions) {
13420
+ const target = action.targetHandle ? `${action.targetHandle} (${action.targetType})` : action.targetType;
13421
+ lines.push(`- ${action.resolutionId} — ${target}`);
13422
+ if (action.messageId) lines.push(` message: ${action.messageId}`);
13423
+ lines.push(` reason: ${formatPendingReason(action.reason)}`);
13424
+ if (action.expiresAt) lines.push(` expires: ${action.expiresAt}`);
13425
+ const commands = formatActionCommands(action);
13426
+ if (commands.length > 0) {
13427
+ lines.push(" recovery commands:");
13428
+ lines.push(...commands);
13429
+ if (commands.some((command) => command.includes(" mention notify "))) lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
13430
+ }
13431
+ }
13432
+ return `${lines.join("\n")}\n`;
13433
+ }
13434
+ function formatMentionActionDetail(result) {
13435
+ const detail = result.message ?? result.reason ?? null;
13436
+ if (result.status === "dropped") return detail ? `not delivered: ${detail}` : "not delivered";
13437
+ return detail;
13438
+ }
13439
+ /** notify/add action outcome rows. */
13440
+ function formatAgentMentionActionResults(action, results) {
13441
+ const lines = [`Mention ${action} results`, ""];
13442
+ if (results.length === 0) {
13443
+ lines.push("No result rows returned.");
13444
+ return `${lines.join("\n")}\n`;
13445
+ }
13446
+ for (const result of results) {
13447
+ const target = result.targetHandle ? ` ${result.targetHandle}` : "";
13448
+ const detail = formatMentionActionDetail(result);
13449
+ const suffix = detail ? ` — ${detail}` : "";
13450
+ lines.push(`- ${result.resolutionId}${target}: ${result.status}${suffix}`);
13451
+ if (result.dedupedResolutionIds && result.dedupedResolutionIds.length > 1) lines.push(` deduped: ${result.dedupedResolutionIds.join(", ")}`);
13452
+ }
13453
+ if (action === "notify" && results.some((result) => result.status === "queued" && result.reason !== "already_queued")) lines.push("", `Recipient guidance: ${formatAgentReplyAffordance({ non_member_mention: true })}`);
13454
+ return `${lines.join("\n")}\n`;
13455
+ }
13456
+ function describeDelivery(row) {
13457
+ switch (row.outcome) {
13458
+ case "delivered": return "delivered";
13459
+ case "pending": return "still in flight — do not conclude yet";
13460
+ case "unknown": return "UNKNOWN — our instrument could not see this one; re-check, do not conclude";
13461
+ case "lost": switch (row.reasonCategory) {
13462
+ case "quota": return "LOST — target is rate/quota limited; it will not arrive, re-route or retry later";
13463
+ case "runtime_error": return "LOST — target's runtime rejected delivery; re-route";
13464
+ case "not_launched": return "LOST — target was not running; re-route or start it";
13465
+ case "unclassified": return "LOST — cause is outside the seat-availability set; re-route";
13466
+ default: return "LOST — server sent no category for this row (malformed); treat the cause as unknown";
13467
+ }
13468
+ }
13469
+ }
13470
+ /** Per-target mention delivery outcome for a message the bound agent sent. */
13471
+ function formatAgentSenderMentionDeliveries(messageId, deliveries) {
13472
+ if (deliveries.length === 0) return `Message ${messageId}\n\nNo mention deliveries recorded for this message.\n`;
13473
+ const lines = [`Message ${messageId} — mention delivery per target`, ""];
13474
+ for (const row of deliveries) lines.push(` ${row.targetHandle || "(unknown target)"}: ${describeDelivery(row)}`);
13475
+ return `${lines.join("\n")}\n`;
13476
+ }
13477
+ //#endregion
13478
+ //#region ../shared/src/agentOps/mentions.ts
13479
+ async function pendingMentionActions(client, request = {}) {
13480
+ const result = await client.mentions.pendingActions(request.limit === void 0 ? {} : { limit: String(request.limit) });
13481
+ if (!result.ok) return failureFromClientResult(result);
13482
+ const actions = normalizeAgentPendingMentionActions(result.data);
13483
+ const hasMore = typeof result.data.has_more === "boolean" ? result.data.has_more : null;
13484
+ const first = actions.find((a) => a.availableActions.length > 0);
13485
+ const next = first ? {
13486
+ kind: "resolve_mention",
13487
+ command: `raft mention notify ${first.resolutionId}`,
13488
+ args: {
13489
+ action: "notify",
13490
+ resolutionIds: [first.resolutionId]
13491
+ },
13492
+ why: "This @mention reached nobody at send time; notify the target (or add them) so the message is seen."
13493
+ } : null;
13494
+ return {
13495
+ ok: true,
13496
+ state: actions.length > 0 ? "pending" : "empty",
13497
+ data: {
13498
+ actions,
13499
+ hasMore,
13500
+ limit: request.limit
13501
+ },
13502
+ next,
13503
+ text: formatAgentPendingMentionActions(actions, {
13504
+ source: "pending",
13505
+ ...hasMore === null ? {} : { hasMore },
13506
+ limit: request.limit
13507
+ })
13508
+ };
13509
+ }
13510
+ async function executeMentionAction(client, request) {
13511
+ const ids = (request.resolutionIds ?? []).map((id) => id.trim()).filter(Boolean);
13512
+ if (ids.length === 0 || request.action !== "notify" && request.action !== "add") return failureOutcome(opError("INVALID_REQUEST", { message: "Pass an action (notify | add) and at least one resolution id." }));
13513
+ const result = await client.mentions.executeAction({
13514
+ action: request.action,
13515
+ resolutionIds: ids
13516
+ });
13517
+ if (!result.ok) return failureFromClientResult(result);
13518
+ const results = normalizeAgentMentionActionResults(result.data);
13519
+ return {
13520
+ ok: true,
13521
+ state: "executed",
13522
+ data: {
13523
+ action: request.action,
13524
+ results
13525
+ },
13526
+ next: null,
13527
+ text: formatAgentMentionActionResults(request.action, results)
13528
+ };
13529
+ }
13530
+ async function senderMentionDeliveries(client, request) {
13531
+ if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13532
+ const result = await client.mentions.senderDeliveries({ messageId: request.messageId });
13533
+ if (!result.ok) return failureFromClientResult(result);
13534
+ const data = result.data;
13535
+ return {
13536
+ ok: true,
13537
+ state: data.deliveries.length > 0 ? "deliveries" : "empty",
13538
+ data,
13539
+ next: null,
13540
+ text: formatAgentSenderMentionDeliveries(data.messageId, data.deliveries)
13541
+ };
13542
+ }
13543
+ //#endregion
13544
+ //#region ../shared/src/agentText/knowledge.ts
13545
+ function formatMatchReason(result) {
13546
+ const parts = [];
13547
+ for (const { term, matched } of result.correctedTerms ?? []) parts.push(`${term} → ${matched} (typo)`);
13548
+ for (const { from, to } of result.expandedTerms ?? []) parts.push(`${from} → ${to} (concept)`);
13549
+ return parts.length > 0 ? ` matched: ${parts.join(", ")}` : "";
13550
+ }
13551
+ function formatAgentKnowledgeSearchResults(results) {
13552
+ return results.map((result, index) => {
13553
+ const body = result.firstScreen.trim().split(/\r?\n/).filter(Boolean).map((line) => ` ${line}`).join("\n");
13554
+ const reason = formatMatchReason(result);
13555
+ return `${index + 1}. ${result.slug} — ${result.title}${reason ? `\n${reason}` : ""}${body ? `\n${body}` : ""}`;
13556
+ }).join("\n\n") + "\n";
13557
+ }
13558
+ function formatAgentKnowledgeStdout(content) {
13559
+ return content.endsWith("\n") ? content : `${content}\n`;
13560
+ }
13561
+ //#endregion
13562
+ //#region ../shared/src/agentOps/manual.ts
13563
+ function requireContext(context) {
13564
+ if (!context?.intent?.trim() || !context?.reason?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Manual calls need a short `intent` and `reason`." }));
13565
+ return null;
13566
+ }
13567
+ async function getManualTopic(client, request) {
13568
+ const invalid = requireContext(request);
13569
+ if (invalid) return invalid;
13570
+ if (!request.topic?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A topic id is required." }));
13571
+ const result = await client.knowledge.get({
13572
+ topic: request.topic.trim(),
13573
+ intent: request.intent.trim(),
13574
+ reason: request.reason.trim()
13575
+ });
13576
+ if (!result.ok) return failureFromClientResult(result);
13577
+ return {
13578
+ ok: true,
13579
+ state: "topic",
13580
+ data: result.data,
13581
+ next: null,
13582
+ text: formatAgentKnowledgeStdout(result.data.content)
13583
+ };
13584
+ }
13585
+ async function searchManual(client, request) {
13586
+ const invalid = requireContext(request);
13587
+ if (invalid) return invalid;
13588
+ if (!request.query?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Search keywords are required." }));
13589
+ const result = await client.knowledge.search({
13590
+ query: request.query.trim(),
13591
+ ...request.scope ? { scope: request.scope } : {},
13592
+ intent: request.intent.trim(),
13593
+ reason: request.reason.trim()
13594
+ });
13595
+ if (!result.ok) return failureFromClientResult(result);
13596
+ const data = result.data;
13597
+ const results = data.results;
13598
+ const first = results[0];
13599
+ const next = first ? {
13600
+ kind: "read_manual_topic",
13601
+ command: `raft manual get ${first.slug} --intent "…" --reason "…"`,
13602
+ args: { topic: first.slug },
13603
+ why: "Open the best-matching topic."
13604
+ } : null;
13605
+ return {
13606
+ ok: true,
13607
+ state: results.length > 0 ? "results" : "empty",
13608
+ data,
13609
+ next,
13610
+ text: results.length > 0 ? formatAgentKnowledgeSearchResults(results) : "No Manual topics matched. Retry with different keywords, keeping your intent and reason.\n"
13611
+ };
13612
+ }
13613
+ //#endregion
13614
+ //#region ../shared/src/agentOps/state.ts
13615
+ const RAFT_STATE_SCHEMA = "raft-sdk-state.v1";
13616
+ const RAFT_STATE_CONTINUATIONS_PER_TARGET = 3;
13617
+ const RAFT_STATE_CONTINUATIONS_TOTAL = 20;
13618
+ function isNullableCursor(value) {
13619
+ return value === null || typeof value === "number" && Number.isInteger(value) && value >= 0;
13620
+ }
13621
+ /** Validate a loaded value; anything unrecognised is treated as an empty store (safe: see file header). */
13622
+ function parseRaftState(value) {
13623
+ if (!value || typeof value !== "object") return null;
13624
+ const v = value;
13625
+ if (v.schema !== "raft-sdk-state.v1") return null;
13626
+ if (typeof v.version !== "number" || !Number.isInteger(v.version) || v.version < 0) return null;
13627
+ if (!isNullableCursor(v.cursor ?? null) || !isNullableCursor(v.pendingCursor ?? null)) return null;
13628
+ const frontier = v.frontier;
13629
+ const continuations = Array.isArray(v.continuations) ? v.continuations.filter((c) => {
13630
+ const r = c;
13631
+ return Boolean(r) && typeof r.target === "string" && typeof r.idempotencyKey === "string" && typeof r.contentHash === "string" && typeof r.heldAt === "string";
13632
+ }) : [];
13633
+ return {
13634
+ schema: RAFT_STATE_SCHEMA,
13635
+ version: v.version,
13636
+ cursor: v.cursor ?? null,
13637
+ pendingCursor: v.pendingCursor ?? null,
13638
+ frontier: frontier && frontier.version === 1 ? frontier : {
13639
+ version: 1,
13640
+ targets: {},
13641
+ aliases: {}
13642
+ },
13643
+ continuations
13644
+ };
13645
+ }
13646
+ /** Hex SHA-256 identifying one logical message (WebCrypto; Workers-safe). */
13647
+ async function hashRaftSendContent(target, content, attachmentIds = []) {
13648
+ const bytes = new TextEncoder().encode(`${target}\n${[...attachmentIds].sort().join(",")}\n${content}`);
13649
+ return [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");
13650
+ }
13651
+ /**
13652
+ * One client's view of the persisted state: loads once, holds the working
13653
+ * copy, saves on request. Also used without a store (memory only), so the
13654
+ * pending/committed cursor flow behaves the same with or without persistence.
13655
+ */
13656
+ var RaftStateSession = class {
13657
+ store;
13658
+ onError;
13659
+ frontier;
13660
+ cursor = null;
13661
+ pendingCursor = null;
13662
+ continuations = [];
13663
+ loadedVersion = void 0;
13664
+ loading = null;
13665
+ dirty = false;
13666
+ constructor(store, frontier, onError) {
13667
+ this.store = store;
13668
+ this.onError = onError;
13669
+ this.frontier = frontier;
13670
+ }
13671
+ get persistent() {
13672
+ return this.store !== void 0;
13673
+ }
13674
+ /** The version loaded from (or last saved to) the store; `undefined` before the first save of an empty store. */
13675
+ get version() {
13676
+ return this.loadedVersion;
13677
+ }
13678
+ /** Load once. A failed or unreadable load starts from an empty state (reported, not thrown). */
13679
+ ensureLoaded() {
13680
+ if (!this.store) return Promise.resolve();
13681
+ this.loading ??= (async () => {
13682
+ let raw = null;
13683
+ try {
13684
+ raw = await this.store.load();
13685
+ } catch (error) {
13686
+ this.onError?.(error, {
13687
+ phase: "load",
13688
+ version: void 0
13689
+ });
13690
+ return;
13691
+ }
13692
+ const state = parseRaftState(raw);
13693
+ if (!state) return;
13694
+ this.loadedVersion = state.version;
13695
+ this.cursor = state.cursor;
13696
+ this.pendingCursor = state.pendingCursor;
13697
+ this.frontier.absorb(state.frontier);
13698
+ this.continuations = state.continuations ?? [];
13699
+ })();
13700
+ return this.loading;
13701
+ }
13702
+ markDirty() {
13703
+ this.dirty = true;
13704
+ }
13705
+ /** Record the cursor of a batch just returned. Acknowledges nothing. */
13706
+ setPending(cursor) {
13707
+ if (cursor === null || cursor === this.pendingCursor) return;
13708
+ this.pendingCursor = cursor;
13709
+ this.dirty = true;
13710
+ }
13711
+ /**
13712
+ * Promote a cursor to committed. With no argument, commits `pendingCursor`.
13713
+ * Returns the committed cursor, or null when there was nothing to commit.
13714
+ * Never moves the committed cursor backwards.
13715
+ */
13716
+ commit(cursor) {
13717
+ const next = cursor === void 0 ? this.pendingCursor : cursor;
13718
+ if (next === null || next === void 0) return null;
13719
+ if (this.cursor === null || next > this.cursor) this.cursor = next;
13720
+ if (this.pendingCursor !== null && this.pendingCursor <= this.cursor) this.pendingCursor = null;
13721
+ this.dirty = true;
13722
+ return this.cursor;
13723
+ }
13724
+ findContinuation(target, contentHash) {
13725
+ return this.continuations.find((c) => c.target === target && c.contentHash === contentHash);
13726
+ }
13727
+ rememberContinuation(entry) {
13728
+ this.continuations = this.continuations.filter((c) => !(c.target === entry.target && c.contentHash === entry.contentHash));
13729
+ this.continuations.push(entry);
13730
+ const perTarget = this.continuations.filter((c) => c.target === entry.target);
13731
+ for (const drop of perTarget.slice(0, Math.max(0, perTarget.length - 3))) this.continuations.splice(this.continuations.indexOf(drop), 1);
13732
+ if (this.continuations.length > 20) this.continuations.splice(0, this.continuations.length - 20);
13733
+ this.dirty = true;
13734
+ }
13735
+ forgetContinuation(target, contentHash) {
13736
+ const before = this.continuations.length;
13737
+ this.continuations = this.continuations.filter((c) => !(c.target === target && c.contentHash === contentHash));
13738
+ if (this.continuations.length !== before) this.dirty = true;
13739
+ }
13740
+ snapshot(nextVersion = (this.loadedVersion ?? 0) + 1) {
13741
+ return {
13742
+ schema: RAFT_STATE_SCHEMA,
13743
+ version: nextVersion,
13744
+ cursor: this.cursor,
13745
+ pendingCursor: this.pendingCursor,
13746
+ frontier: this.frontier.snapshot(),
13747
+ continuations: [...this.continuations]
13748
+ };
13749
+ }
13750
+ /**
13751
+ * Save if anything changed (or `force`). One attempt; a failure is reported
13752
+ * and swallowed. Returns whether the save succeeded (true when nothing to save).
13753
+ */
13754
+ async save(options = {}) {
13755
+ if (!this.store) return true;
13756
+ if (!this.dirty && !options.force) return true;
13757
+ const expectedVersion = this.loadedVersion;
13758
+ const state = this.snapshot();
13759
+ try {
13760
+ await this.store.save(state, { expectedVersion });
13761
+ } catch (error) {
13762
+ this.onError?.(error, {
13763
+ phase: "save",
13764
+ version: expectedVersion
13765
+ });
13766
+ return false;
13767
+ }
13768
+ this.loadedVersion = state.version;
13769
+ this.dirty = false;
13770
+ return true;
13771
+ }
13772
+ };
13773
+ //#endregion
11805
13774
  //#region src/raft.ts
11806
13775
  function createRaft(options) {
11807
13776
  const serverUrl = requireServerUrl(options.serverUrl);
11808
13777
  const authorization = `Bearer ${requireAgentCredential(options.credential)}`;
11809
13778
  const frontier = SeenFrontier.fromSnapshot(options.frontier);
13779
+ const session = new RaftStateSession(options.state, frontier, options.onStateSaveError);
13780
+ /** Load before, run, then save if the operation succeeded and changed the state. */
13781
+ const withState = async (run) => {
13782
+ await session.ensureLoaded();
13783
+ const outcome = await run();
13784
+ if (outcome.ok) await session.save();
13785
+ return outcome;
13786
+ };
11810
13787
  const routes = createRaftRoutes({
11811
13788
  serverUrl,
11812
13789
  fetch: options.fetch,
@@ -11827,6 +13804,27 @@ function createRaft(options) {
11827
13804
  throttle: options.throttle,
11828
13805
  auth: { authorization }
11829
13806
  } });
13807
+ /**
13808
+ * Send through the state session: a resend of the same logical message
13809
+ * (same target, content, attachments) reuses the held send's idempotency key;
13810
+ * a hold is remembered; a successful send clears it.
13811
+ */
13812
+ const sendWithState = (request) => withState(async () => {
13813
+ const contentHash = await hashRaftSendContent(request.target, request.content ?? "", request.attachmentIds ?? []);
13814
+ const pending = request.idempotencyKey ? void 0 : session.findContinuation(request.target, contentHash);
13815
+ const outcome = await sendMessage(routes, pending ? {
13816
+ ...request,
13817
+ idempotencyKey: pending.idempotencyKey
13818
+ } : request, frontier);
13819
+ if (outcome.ok && outcome.state === "held") session.rememberContinuation({
13820
+ target: request.target,
13821
+ idempotencyKey: outcome.data.idempotencyKey,
13822
+ contentHash,
13823
+ heldAt: (/* @__PURE__ */ new Date()).toISOString()
13824
+ });
13825
+ else if (outcome.ok && outcome.state === "sent") session.forgetContinuation(request.target, contentHash);
13826
+ return outcome;
13827
+ });
11830
13828
  return {
11831
13829
  identity: { whoami: () => getRaftContext(routes) },
11832
13830
  wake: {
@@ -11838,19 +13836,117 @@ function createRaft(options) {
11838
13836
  }
11839
13837
  },
11840
13838
  inbox: {
11841
- check: (request) => checkInbox(inboxApi, request, frontier),
11842
- drain: (request) => drainInbox(inboxApi, request, frontier),
13839
+ check: (request = {}) => withState(async () => {
13840
+ const since = request.since ?? session.cursor ?? void 0;
13841
+ const outcome = await checkInbox(inboxApi, {
13842
+ ...request,
13843
+ ...since === void 0 ? {} : { since }
13844
+ }, frontier);
13845
+ if (outcome.ok) {
13846
+ session.markDirty();
13847
+ if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
13848
+ if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
13849
+ }
13850
+ return outcome;
13851
+ }),
13852
+ commit: async (target) => {
13853
+ await session.ensureLoaded();
13854
+ const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
13855
+ return {
13856
+ cursor,
13857
+ saved: cursor === null ? true : await session.save()
13858
+ };
13859
+ },
13860
+ drain: (request = {}) => (async function* () {
13861
+ await session.ensureLoaded();
13862
+ const since = request.since ?? session.cursor ?? void 0;
13863
+ return yield* drainInbox(inboxApi, {
13864
+ ...request,
13865
+ ...since === void 0 ? {} : { since }
13866
+ }, frontier, async (sent, batch) => {
13867
+ if (sent !== null) session.commit(sent);
13868
+ if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
13869
+ session.markDirty();
13870
+ await session.save();
13871
+ });
13872
+ })(),
11843
13873
  list: (request) => listInbox(routes, request)
11844
13874
  },
11845
13875
  messages: {
11846
- read: (request) => readHistory(routes, request, frontier),
11847
- send: (request) => sendMessage(routes, request, frontier),
11848
- reply: (message, request) => replyTo(routes, message, request, frontier)
13876
+ read: (request) => withState(async () => {
13877
+ const outcome = await readHistory(routes, request, frontier);
13878
+ if (outcome.ok) session.markDirty();
13879
+ return outcome;
13880
+ }),
13881
+ send: (request) => sendWithState(request),
13882
+ reply: (message, request) => sendWithState({
13883
+ ...request,
13884
+ target: message.target
13885
+ }),
13886
+ search: (request) => searchMessages(routes, request),
13887
+ resolve: (request) => resolveMessage(routes, request),
13888
+ react: (request) => reactToMessage(routes, request, "add"),
13889
+ unreact: (request) => reactToMessage(routes, request, "remove")
13890
+ },
13891
+ attachments: {
13892
+ upload: (request) => uploadAttachment(routes, {
13893
+ serverUrl,
13894
+ fetch: options.fetch ?? fetch,
13895
+ headers: Object.fromEntries(new Headers(options.headers)),
13896
+ authorization
13897
+ }, request),
13898
+ download: (request) => downloadAttachment(routes, request),
13899
+ comments: (request) => attachmentComments(routes, request)
13900
+ },
13901
+ mentions: {
13902
+ pending: (request) => pendingMentionActions(routes, request),
13903
+ execute: (request) => executeMentionAction(routes, request),
13904
+ deliveries: (request) => senderMentionDeliveries(routes, request)
13905
+ },
13906
+ manual: {
13907
+ get: (request) => getManualTopic(routes, request),
13908
+ search: (request) => searchManual(routes, request)
13909
+ },
13910
+ tasks: {
13911
+ claim: (request) => claimTasks(routes, request),
13912
+ list: (request) => listTasks(routes, request),
13913
+ create: (request) => createTasks(routes, request),
13914
+ unclaim: (request) => unclaimTask(routes, request),
13915
+ assign: (request) => assignTask(routes, request),
13916
+ updateStatus: (request) => updateTaskStatus(routes, request),
13917
+ amend: (request) => amendTask(routes, request),
13918
+ history: (request) => taskHistory(routes, request),
13919
+ convert: (request) => convertMessageToTask(routes, request),
13920
+ delete: (request) => deleteTask(routes, request)
13921
+ },
13922
+ channels: {
13923
+ join: (request) => joinChannel(routes, request),
13924
+ leave: (request) => leaveChannel(routes, request),
13925
+ mute: (request) => muteChannel(routes, request),
13926
+ unmute: (request) => unmuteChannel(routes, request),
13927
+ members: (request) => channelMembers(routes, request)
13928
+ },
13929
+ threads: {
13930
+ list: () => listThreads(routes),
13931
+ unfollow: (request) => unfollowThread(routes, request)
13932
+ },
13933
+ server: { info: (request) => serverInfo(routes, request) },
13934
+ profile: {
13935
+ show: (request) => showProfile(routes, request),
13936
+ update: (request) => updateProfile(routes, request)
11849
13937
  },
11850
- tasks: { claim: (request) => claimTasks(routes, request) },
11851
13938
  frontier,
13939
+ state: {
13940
+ save: async () => {
13941
+ await session.ensureLoaded();
13942
+ session.markDirty();
13943
+ return session.save();
13944
+ },
13945
+ load: () => session.ensureLoaded(),
13946
+ snapshot: () => session.snapshot(session.version ?? 0)
13947
+ },
11852
13948
  routes
11853
13949
  };
11854
13950
  }
11855
13951
  //#endregion
11856
- export { RAFT_INBOX_NOTICE_SCHEMA, RAFT_NOTICE_DELIVERY_ID_HEADER, RAFT_NOTICE_SIGNATURE_HEADER, RaftCredentialError, RaftSdkConfigurationError, SeenFrontier, bootstrapRaftCredential, createFileCredentialStore, createRaft, createRaftClient, createRaftClientFromStore, createRaftRoutes, describeRaftRoute, hasAgentMessageIdentity, joinRaftChannelByTarget, listRaftRoutes, parseRaftRegularChannelTarget, projectRaftMessage, projectRaftMessages, verifyInboxNotice };
13952
+ export { RAFT_INBOX_NOTICE_SCHEMA, RAFT_NOTICE_DELIVERY_ID_HEADER, RAFT_NOTICE_SIGNATURE_HEADER, RAFT_STATE_CONTINUATIONS_PER_TARGET, RAFT_STATE_CONTINUATIONS_TOTAL, RAFT_STATE_SCHEMA, RaftCredentialError, RaftSdkConfigurationError, SeenFrontier, bootstrapRaftCredential, createFileCredentialStore, createRaft, createRaftClient, createRaftClientFromStore, createRaftRoutes, describeRaftRoute, hasAgentMessageIdentity, hashRaftSendContent, inferAttachmentMimeType, joinRaftChannelByTarget, listRaftRoutes, parseRaftRegularChannelTarget, parseRaftState, projectRaftMessage, projectRaftMessages, verifyInboxNotice };