@botiverse/raft-sdk 0.3.0 → 1.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -7389,13 +7389,8 @@ function encodeQuery(routeKey, query) {
7389
7389
  return params;
7390
7390
  }
7391
7391
  function parseBody(routeKey, body) {
7392
+ if (body === void 0) return void 0;
7392
7393
  const route = agentApiContract[routeKey];
7393
- if (body === void 0) {
7394
- if (!("body" in route.request)) return void 0;
7395
- const schema = route.request.body;
7396
- if (schema.safeParse(void 0).success || schema.safeParse({}).success) return void 0;
7397
- return failure$3(routeKey, "request_contract_mismatch", `Agent API ${route.key} requires a request body`);
7398
- }
7399
7394
  try {
7400
7395
  return "body" in route.request ? route.request.body.parse(body) : void 0;
7401
7396
  } catch (cause) {
@@ -7500,19 +7495,7 @@ function createAgentApiRawClient(transport, options = {}) {
7500
7495
  const routeKey = route.key;
7501
7496
  const { resource, method } = route.client;
7502
7497
  const resourceClient = client[resource] ??= {};
7503
- const expectedArgs = [
7504
- "params",
7505
- "query",
7506
- "body"
7507
- ].filter((part) => part in route.request).length;
7508
- resourceClient[method] = (...args) => {
7509
- if (args.length > expectedArgs) return Promise.resolve(failure$3(routeKey, "request_contract_mismatch", `Agent API ${route.key} takes ${expectedArgs} argument${expectedArgs === 1 ? "" : "s"} (${[
7510
- "params",
7511
- "query",
7512
- "body"
7513
- ].filter((part) => part in route.request).join(", ") || "none"}); got ${args.length}`));
7514
- return requestAgentApiRawRoute(transport, routeKey, requestOptionsFromMethodArgs(routeKey, pathPrefix, args));
7515
- };
7498
+ resourceClient[method] = (...args) => requestAgentApiRawRoute(transport, routeKey, requestOptionsFromMethodArgs(routeKey, pathPrefix, args));
7516
7499
  }
7517
7500
  return client;
7518
7501
  }
@@ -9903,7 +9886,7 @@ function clampAttempts(value) {
9903
9886
  * The split is decided per route from `AGENT_API_ROUTE_META`, never by the
9904
9887
  * caller and never by the HTTP method.
9905
9888
  */
9906
- function createRaftRouteClient(options) {
9889
+ function createRaftRoutes(options) {
9907
9890
  const base = {
9908
9891
  baseUrl: options.serverUrl,
9909
9892
  fetch: options.fetch,
@@ -9930,61 +9913,12 @@ function createRaftRouteClient(options) {
9930
9913
  ...merged,
9931
9914
  request: (routeKey, requestOptions) => {
9932
9915
  return (ROUTE_INFO[routeKey].retryPolicy === "retry" ? retrying : single).request(routeKey, requestOptions);
9933
- }
9934
- };
9935
- }
9936
- const ROUTE_PARTS = [
9937
- "params",
9938
- "query",
9939
- "body"
9940
- ];
9941
- function inputMismatch(routeKey, message) {
9942
- return Promise.resolve({
9943
- ok: false,
9944
- routeKey,
9945
- error: {
9946
- kind: "validation",
9947
- reason: "request_contract_mismatch",
9948
- message: `Agent API ${routeKey} ${message}`
9949
- }
9950
- });
9951
- }
9952
- /**
9953
- * The public routes layer: one named-object call shape for every route,
9954
- * `routes.<resource>.<method>({ params, query, body })`. The types reject a
9955
- * missing required part or a part the route does not have; for callers
9956
- * without type checking, the same rules are enforced at runtime and nothing
9957
- * is sent on a mismatch.
9958
- */
9959
- function raftRoutesFromClient(client) {
9960
- const call = (routeKey, args) => {
9961
- if (args.length > 1) return inputMismatch(routeKey, `takes one { params, query, body } object; got ${args.length} arguments`);
9962
- const input = args[0];
9963
- if (input !== void 0 && (input === null || typeof input !== "object" || Array.isArray(input))) return inputMismatch(routeKey, "takes one { params, query, body } object");
9964
- const route = agentApiContract[routeKey];
9965
- const declared = ROUTE_PARTS.filter((part) => part in route.request);
9966
- const unknown = (input === void 0 ? [] : Object.keys(input)).filter((key) => !declared.includes(key));
9967
- if (unknown.length > 0) return inputMismatch(routeKey, `has no ${unknown.join(", ")} (it takes ${declared.join(", ") || "no input"})`);
9968
- return client.request(routeKey, input ?? {});
9969
- };
9970
- const methods = {};
9971
- for (const route of Object.values(agentApiContract)) {
9972
- const key = route.key;
9973
- methods[route.client.resource] ??= {};
9974
- methods[route.client.resource][route.client.method] = (...args) => call(key, args);
9975
- }
9976
- return {
9977
- ...methods,
9978
- request: (routeKey, ...rest) => call(routeKey, rest),
9916
+ },
9979
9917
  manifestVersion: AGENT_API_MANIFEST_VERSION,
9980
9918
  describe: describeRaftRoute,
9981
9919
  list: listRaftRoutes
9982
9920
  };
9983
9921
  }
9984
- /** Build the public routes layer directly (convenience over createRaftRouteClient + raftRoutesFromClient). */
9985
- function createRaftRoutes(options) {
9986
- return raftRoutesFromClient(createRaftRouteClient(options));
9987
- }
9988
9922
  //#endregion
9989
9923
  //#region src/context.ts
9990
9924
  const projection = object({
@@ -11040,22 +10974,7 @@ function toAgentMessageLike(envelope) {
11040
10974
  task_current_projection: envelope.task_current_projection ?? envelope.taskCurrentProjection ?? null
11041
10975
  };
11042
10976
  }
11043
- /**
11044
- * An envelope carries a reply target only when it names its conversation
11045
- * (`channel_type` + `channel_name`, or a third-party event). Some Server
11046
- * responses embed bare envelopes (for example `recentUnread: [{ content }]`);
11047
- * those must not be rendered with a made-up target.
11048
- */
11049
- function hasAgentMessageIdentity(envelope) {
11050
- const like = toAgentMessageLike(envelope);
11051
- if (like.third_party_event) return true;
11052
- if (typeof like.channel_type !== "string" || typeof like.channel_name !== "string" || !like.channel_name) return false;
11053
- if (like.channel_type === "thread" && !like.parent_channel_name) return false;
11054
- return true;
11055
- }
11056
- /** Project one envelope; `null` when it has no conversation identity (skip it rather than render `#undefined`). */
11057
10977
  function projectRaftMessage(envelope) {
11058
- if (!hasAgentMessageIdentity(envelope)) return null;
11059
10978
  const like = toAgentMessageLike(envelope);
11060
10979
  const id = nullableString(like.message_id);
11061
10980
  const taskNumber = nullableNumber(like.task_number);
@@ -11094,10 +11013,6 @@ function projectRaftMessage(envelope) {
11094
11013
  function sortBySeq(messages) {
11095
11014
  return [...messages].sort((a, b) => (a.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER));
11096
11015
  }
11097
- /** Project a list, skipping envelopes without a conversation identity. */
11098
- function projectRaftMessages(envelopes) {
11099
- return envelopes.map(projectRaftMessage).filter((m) => m !== null);
11100
- }
11101
11016
  //#endregion
11102
11017
  //#region ../shared/src/agentOps/frontier.ts
11103
11018
  const MAX_EXACT_SEQS = 2500;
@@ -11109,17 +11024,13 @@ var SeenFrontier = class SeenFrontier {
11109
11024
  aliases = /* @__PURE__ */ new Map();
11110
11025
  static fromSnapshot(snapshot) {
11111
11026
  const frontier = new SeenFrontier();
11112
- frontier.absorb(snapshot);
11113
- return frontier;
11114
- }
11115
- /** Merge a snapshot into this frontier by the same monotonic rules (never lowers a mark). */
11116
- absorb(snapshot) {
11117
- if (!snapshot || snapshot.version !== 1) return;
11118
- for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) this.recordAlias(alias, canonical);
11027
+ if (!snapshot || snapshot.version !== 1) return frontier;
11119
11028
  for (const [target, state] of Object.entries(snapshot.targets ?? {})) {
11120
- if (positiveInt(state.upTo)) this.recordUpTo(target, state.upTo);
11121
- if (Array.isArray(state.exact)) this.recordExact(target, state.exact);
11029
+ if (positiveInt(state.upTo)) frontier.recordUpTo(target, state.upTo);
11030
+ if (Array.isArray(state.exact)) frontier.recordExact(target, state.exact);
11122
11031
  }
11032
+ for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) frontier.recordAlias(alias, canonical);
11033
+ return frontier;
11123
11034
  }
11124
11035
  /** Remember that the Server resolved `requested` to `canonical` (a thread spelling, a `~agent` suffix, …). */
11125
11036
  recordAlias(requested, canonical) {
@@ -11149,17 +11060,6 @@ var SeenFrontier = class SeenFrontier {
11149
11060
  for (const seq of keep) state.exact.add(seq);
11150
11061
  }
11151
11062
  }
11152
- /**
11153
- * Attest that the model saw the context a held send/claim returned. Call it
11154
- * only after the held messages actually reached the model (the SDK cannot
11155
- * know that, so it never records this implicitly). Returns false and records
11156
- * nothing when the context was withheld or the Server sent no boundary.
11157
- */
11158
- recordHeld(held) {
11159
- if (held.withheld || held.seenUpToSeq === null) return false;
11160
- this.recordUpTo(held.target, held.seenUpToSeq);
11161
- return true;
11162
- }
11163
11063
  /** What to attest on a send or claim to `target`; omits `seenUpToSeq` when nothing contiguous is known. */
11164
11064
  attestation(target) {
11165
11065
  const state = this.targets.get(this.canonical(target));
@@ -11238,7 +11138,7 @@ async function checkInbox(client, request = {}, frontier) {
11238
11138
  });
11239
11139
  if (!result.ok) return failureFromClientResult(result);
11240
11140
  const data = result.data;
11241
- const messages = sortBySeq(projectRaftMessages(data.events));
11141
+ const messages = sortBySeq(data.events.map(projectRaftMessage));
11242
11142
  recordExactSeen(frontier, messages);
11243
11143
  const batch = {
11244
11144
  messages,
@@ -11266,7 +11166,7 @@ async function checkInbox(client, request = {}, frontier) {
11266
11166
  * return value summarises the drain; the batch that ends the iteration is
11267
11167
  * acknowledged only by the caller's next pull (`summary.cursor`).
11268
11168
  */
11269
- async function* drainInbox(client, request = {}, frontier, onPull) {
11169
+ async function* drainInbox(client, request = {}, frontier) {
11270
11170
  const ack = request.ack ?? "cursor";
11271
11171
  let cursor = request.since ?? null;
11272
11172
  let ackMode = ack;
@@ -11289,7 +11189,6 @@ async function* drainInbox(client, request = {}, frontier, onPull) {
11289
11189
  error: round
11290
11190
  };
11291
11191
  const batch = round.data;
11292
- await onPull?.(sent, batch);
11293
11192
  ackMode = batch.ackMode;
11294
11193
  stillUnread = batch.stillUnreadConversations;
11295
11194
  if (batch.messages.length > 0) {
@@ -11461,7 +11360,7 @@ async function readHistory(client, request, frontier) {
11461
11360
  const data = result.data;
11462
11361
  const page = {
11463
11362
  target: typeof data.target === "string" && data.target ? data.target : request.target,
11464
- messages: sortBySeq(projectRaftMessages(data.messages)),
11363
+ messages: sortBySeq(data.messages.map(projectRaftMessage)),
11465
11364
  hasOlder: data.has_older === true,
11466
11365
  hasNewer: data.has_newer === true,
11467
11366
  lastReadSeq: typeof data.last_read_seq === "number" ? data.last_read_seq : null,
@@ -11491,31 +11390,25 @@ function heldText(held, action) {
11491
11390
  }
11492
11391
  function heldNext(held) {
11493
11392
  return {
11494
- kind: "resend",
11393
+ kind: "review_then_resend",
11495
11394
  command: `raft message read --target "${held.target}"`,
11496
11395
  args: {
11497
11396
  target: held.target,
11498
- ...held.continuation
11397
+ newMessageCount: held.newMessageCount
11499
11398
  },
11500
- why: held.withheld ? "Newer messages exist in this conversation but were withheld; read them, then send again with the same idempotencyKey." : "Newer messages arrived in this conversation. Show the held messages to the model, call frontier.recordHeld(held) to attest that, then send again with these args (same idempotencyKey, seen.upToSeq)."
11399
+ why: "Newer messages arrived in this conversation; read them, then resend if the message still applies."
11501
11400
  };
11502
11401
  }
11503
- function projectHeld(target, data, idempotencyKey) {
11402
+ function projectHeld(target, data) {
11504
11403
  const withheld = data.freshnessContextMode === "withheld";
11505
- const heldMessages = projectRaftMessages(data.heldMessages ?? []);
11506
- const seenUpToSeq = typeof data.seenUpToSeq === "number" ? data.seenUpToSeq : null;
11404
+ const heldMessages = (data.heldMessages ?? []).map(projectRaftMessage);
11507
11405
  return {
11508
11406
  target,
11509
- idempotencyKey,
11510
- continuation: {
11511
- idempotencyKey,
11512
- ...!withheld && seenUpToSeq !== null ? { seen: { upToSeq: seenUpToSeq } } : {}
11513
- },
11514
11407
  newMessageCount: withheld ? data.withheldMessageCount ?? 0 : data.newMessageCount ?? heldMessages.length,
11515
11408
  heldMessages,
11516
11409
  omittedMessageCount: data.omittedMessageCount ?? 0,
11517
11410
  formalMentionCount: data.mentionAnnotation?.formalMentionCount ?? 0,
11518
- seenUpToSeq,
11411
+ seenUpToSeq: typeof data.seenUpToSeq === "number" ? data.seenUpToSeq : null,
11519
11412
  withheld
11520
11413
  };
11521
11414
  }
@@ -11527,7 +11420,7 @@ function sentOutcome(target, data) {
11527
11420
  messageId: data.messageId,
11528
11421
  messageSeq: typeof data.messageSeq === "number" ? data.messageSeq : null,
11529
11422
  unresolvedMentionHandles: data.unresolvedMentionHandles ?? [],
11530
- recentUnread: projectRaftMessages(data.recentUnread ?? [])
11423
+ recentUnread: (data.recentUnread ?? []).map(projectRaftMessage)
11531
11424
  };
11532
11425
  const warn = sent.unresolvedMentionHandles.length > 0 ? ` Unresolved @handles: ${sent.unresolvedMentionHandles.map((h) => `@${h}`).join(", ")}.` : "";
11533
11426
  return {
@@ -11574,7 +11467,7 @@ async function sendMessage(client, request, frontier, internal = {}) {
11574
11467
  idempotencyKey
11575
11468
  };
11576
11469
  const held = {
11577
- ...projectHeld(request.target, data, idempotencyKey),
11470
+ ...projectHeld(request.target, data),
11578
11471
  resend: (options) => sendMessage(client, options.seen === "held" && typeof data.seenUpToSeq === "number" ? {
11579
11472
  ...keyed,
11580
11473
  seen: {
@@ -11598,173 +11491,12 @@ async function sendMessage(client, request, frontier, internal = {}) {
11598
11491
  if (data.state === "sent") return sentOutcome(request.target, data);
11599
11492
  return failureOutcome(opError("INVALID_RESPONSE", { message: `Unexpected send state "${data.state}".` }));
11600
11493
  }
11601
- function taskTimestamps(t) {
11602
- return `${t.createdAt ? ` created=${formatUtcTimestamp(t.createdAt)}` : ""}${t.updatedAt ? ` updated=${formatUtcTimestamp(t.updatedAt)}` : ""}`;
11603
- }
11604
- const TASK_STATUS_ORDER = [
11605
- "todo",
11606
- "in_progress",
11607
- "in_review",
11608
- "done",
11609
- "closed"
11610
- ];
11611
- function oneLineTaskTitle(title) {
11612
- return (title ?? "").replace(/\s+/g, " ").trim();
11613
- }
11614
- /** Channel task board listing. */
11615
- function formatAgentTaskList(channel, data, statusFilter) {
11616
- if (!data.tasks || data.tasks.length === 0) return `No${statusFilter && statusFilter !== "all" ? ` ${statusFilter}` : ""} tasks in ${channel}.`;
11617
- const formatted = data.tasks.map((t) => {
11618
- const assignee = t.claimedById ? ` → ${t.claimedByName ? `@${t.claimedByName}` : "<unresolved>"}` : "";
11619
- const departedCreator = t.createdByMembershipStatus === "left" || t.createdByMembershipStatus === "removed";
11620
- const creator = t.createdByName ? ` (by @${t.createdByName}${departedCreator ? " [departed]" : ""})` : "";
11621
- const msgId = t.messageId ? ` msg=${t.messageId.slice(0, 8)}` : "";
11622
- const revision = Number.isInteger(t.revision) ? ` rev=${t.revision}` : "";
11623
- const legacy = t.isLegacy ? " [LEGACY — read-only]" : "";
11624
- const resourceReceipt = t.requiresResourceReceipt ? ` resource-receipt=${t.resourceReceiptRecordedAt ? "recorded" : "pending"}` : "";
11625
- const details = t.description ? `\n Current description: ${t.description.replace(/\n/g, `\n${" ".repeat(23)}`)}` : "";
11626
- return `#${t.taskNumber} [${t.status}]${assignee}${creator}${msgId}${revision}${resourceReceipt}${taskTimestamps(t)}${legacy} Current title: ${oneLineTaskTitle(t.title)}${details}`;
11627
- }).join("\n");
11628
- return `## Task Board for ${channel} (${data.tasks.length} tasks)\n\n${formatted}`;
11629
- }
11630
- /** Cross-channel --mine task listing with coverage notes. */
11631
- function formatAgentMyTaskList(data, statusFilter) {
11632
- const tasks = data.tasks ?? [];
11633
- const visibleTypes = data.coverage?.visibleChannelTypes?.join("|") ?? "unknown";
11634
- const archived = data.coverage?.includesArchived ? "included" : "not included";
11635
- const coverage = [
11636
- `Coverage: ${data.coverage?.status ?? "unknown"}`,
11637
- `visible types=${visibleTypes}`,
11638
- `archived=${archived}`,
11639
- `inaccessible scope=${data.coverage?.inaccessibleScope ?? "unknown"}`
11640
- ].join(" · ");
11641
- const output = `Output: showing ${tasks.length} of ${tasks.length} visible matches · mode=${data.pagination?.mode ?? "unknown"} · truncated=${String(data.pagination?.truncated ?? "unknown")}`;
11642
- const title = `## My assigned tasks on this server${statusFilter ? ` (status=${statusFilter})` : " (unfinished)"}`;
11643
- if (tasks.length === 0) return [
11644
- title,
11645
- "",
11646
- coverage,
11647
- output,
11648
- "",
11649
- "No tasks matched in the covered visible scope."
11650
- ].join("\n");
11651
- const grouped = /* @__PURE__ */ new Map();
11652
- for (const task of tasks) {
11653
- const status = task.status ?? "unknown";
11654
- const bucket = grouped.get(status) ?? [];
11655
- bucket.push(task);
11656
- grouped.set(status, bucket);
11657
- }
11658
- return [
11659
- title,
11660
- "",
11661
- coverage,
11662
- output,
11663
- "",
11664
- ...[...TASK_STATUS_ORDER.filter((status) => grouped.has(status)), ...[...grouped.keys()].filter((status) => !TASK_STATUS_ORDER.includes(status)).sort()].map((status) => {
11665
- const rows = grouped.get(status);
11666
- const rendered = rows.map((task) => {
11667
- const channelRef = task.channelRef ?? "<unresolved-visible-target>";
11668
- const taskNumber = task.taskNumber ?? "?";
11669
- const departedCreator = task.createdByMembershipStatus === "left" || task.createdByMembershipStatus === "removed";
11670
- const creator = task.createdByName ? ` by=@${task.createdByName}${departedCreator ? " creator=departed" : ""}` : "";
11671
- const message = task.messageId ? ` msg=${task.messageId.slice(0, 8)}` : "";
11672
- const legacy = task.isLegacy ? " legacy=read-only" : "";
11673
- return `- ${channelRef} task #${taskNumber} [${status}]${creator}${message}${task.requiresResourceReceipt ? ` resource-receipt=${task.resourceReceiptRecordedAt ? "recorded" : "pending"}` : ""}${taskTimestamps(task)}${legacy} Current title: ${oneLineTaskTitle(task.title)}`.trimEnd();
11674
- });
11675
- return [`### ${status} (${rows.length})`, ...rendered].join("\n");
11676
- })
11677
- ].join("\n");
11678
- }
11679
- /** Receipt for task create. */
11680
- function formatAgentTasksCreated(channel, data) {
11681
- const created = data.tasks.map((t) => {
11682
- const assignee = t.claimedById ? t.claimedByName ? `@${t.claimedByName}` : "<unresolved>" : "unassigned";
11683
- const resourceReceipt = t.requiresResourceReceipt ? " resource-receipt=pending" : "";
11684
- return `#${t.taskNumber} [${t.status}] assignee=${assignee} claimedAt=${t.claimedAt ?? "null"} msg=${t.messageId.slice(0, 8)}${resourceReceipt} "${t.title}"`;
11685
- }).join("\n");
11686
- const threadHints = data.tasks.map((t) => `#${t.taskNumber} → raft message send --target "${channel}:${t.messageId.slice(0, 8)}"`).join("\n");
11687
- const receipt = data.assignmentReceipt ? `\n\nAssignment receipt (msg=${data.assignmentReceipt.messageId.slice(0, 8)}):\n${data.assignmentReceipt.content}` : "";
11688
- return `Created ${data.tasks.length} task(s) in ${channel}:\n${created}${receipt}\n\nTo follow up in each task's thread:\n${threadHints}`;
11689
- }
11690
- const BLOCKED_ACTION_COPY = { start_conflicting_execution: "starting conflicting implementation/change work" };
11691
- function formatClaimConflict(label, conflict) {
11692
- const holder = conflict.currentAssignee?.name ? `@${conflict.currentAssignee.name}` : "another actor";
11693
- const blocked = conflict.blockedActions.map((action) => BLOCKED_ACTION_COPY[action] ?? action).join("; ");
11694
- const examples = conflict.unblockedActionExamples.join(" · ");
11695
- return [
11696
- `${label}: Claim failed — ${holder} currently holds the implementation lock (assignment state as of ${conflict.observedAt}).`,
11697
- ` Blocked: ${blocked}.`,
11698
- ` Not blocked by this claim conflict (each still subject to its own authority/policy): ${examples}.`,
11699
- ` 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).`
11700
- ].join("\n");
11701
- }
11702
- function canonicalAgentTaskTarget(target) {
11703
- return target.replace(/^dm:user:/i, "dm:@");
11704
- }
11705
- function agentTaskThreadTarget(target, messageId) {
11706
- return `${canonicalAgentTaskTarget(target)}:${messageId.slice(0, 8)}`;
11707
- }
11708
- /** Claim results incl. concurrency-lock guidance on failed claims. */
11709
- function formatAgentClaimResults(channel, data) {
11710
- const lines = data.results.map((r) => {
11711
- const label = r.taskNumber ? `#${r.taskNumber}` : `msg:${r.messageId}`;
11712
- if (r.success) return `${label} (msg:${r.messageId ? r.messageId.slice(0, 8) : ""}): claimed`;
11713
- if (r.reason === "already claimed by you") return `${label}: already claimed by you.`;
11714
- if (r.conflict?.kind === "claim_conflict") return formatClaimConflict(label, r.conflict);
11715
- 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.`;
11716
- });
11717
- const succeeded = data.results.filter((r) => r.success).length;
11718
- const failed = data.results.length - succeeded;
11719
- let summary = `${succeeded} claimed`;
11720
- if (failed > 0) summary += `, ${failed} failed`;
11721
- const claimedMsgs = data.results.filter((r) => r.success && r.messageId).map((r) => `#${r.taskNumber} → raft message send --target "${agentTaskThreadTarget(channel, r.messageId)}"`).join("\n");
11722
- const threadHint = claimedMsgs ? `\n\nFollow up in each task's thread:\n${claimedMsgs}` : "";
11723
- return `Claim results (${summary}):\n${lines.join("\n")}${threadHint}`;
11724
- }
11725
- function formatAgentTaskUnclaimed(taskNumber) {
11726
- return `#${taskNumber} unclaimed — now open.`;
11727
- }
11728
- function formatAgentTaskAssigned(taskNumber, assignee) {
11729
- return assignee ? `#${taskNumber} assigned to ${assignee}.` : `#${taskNumber} unassigned — now open.`;
11730
- }
11731
- function formatAgentTaskStatusUpdated(taskNumber, status) {
11732
- return `#${taskNumber} moved to ${status}.`;
11733
- }
11734
- function formatAgentTaskDeleted(taskNumber) {
11735
- return `#${taskNumber} deleted.`;
11736
- }
11737
- /** Message→task conversion receipt. */
11738
- function formatAgentTaskConverted(channel, task) {
11739
- const target = `${canonicalAgentTaskTarget(channel)}:${task.messageId.slice(0, 8)}`;
11740
- return [
11741
- `Converted msg=${task.messageId.slice(0, 8)} to task #${task.taskNumber} [${task.status}] assignee=unassigned "${task.title}"`,
11742
- "",
11743
- `To follow up in the task's thread:`,
11744
- `raft message send --target "${target}"`
11745
- ].join("\n");
11746
- }
11747
- function formatAgentTaskAmended(data) {
11748
- const details = data.task.description === null ? "details: <none>" : `details:\n${data.task.description.split("\n").map((line) => ` ${line}`).join("\n")}`;
11749
- return [
11750
- `#${data.task.taskNumber} amended — revision ${data.task.revision}, event seq ${data.event.seq}.`,
11751
- `title: ${data.task.title}`,
11752
- details
11753
- ].join("\n");
11754
- }
11755
- function formatAgentTaskHistory(data) {
11756
- const description = data.task.description === null ? "(none set)" : data.task.description.replace(/\n/g, `\n${" ".repeat(21)}`);
11757
- const header = [
11758
- `## Task #${data.task.taskNumber} history — revision ${data.task.revision}`,
11759
- "",
11760
- `Current title: ${data.task.title.replace(/\s+/g, " ").trim()}`,
11761
- `Current description: ${description}`
11762
- ].join("\n");
11763
- if (data.events.length === 0) return `${header}\n\nNo recorded events.`;
11764
- return `${header}\n\n${data.events.map((event) => {
11765
- const actor = event.actorType === "system" ? "@system" : event.actorName ? `@${event.actorName}` : "<unresolved>";
11766
- return `seq=${event.seq} time=${event.createdAt} actor=${actor} type=${event.eventType}\n ${JSON.stringify(event.payload)}`;
11767
- }).join("\n")}`;
11494
+ /** Reply where a received message came from. */
11495
+ function replyTo(client, message, request, frontier) {
11496
+ return sendMessage(client, {
11497
+ ...request,
11498
+ target: message.target
11499
+ }, frontier);
11768
11500
  }
11769
11501
  //#endregion
11770
11502
  //#region ../shared/src/agentOps/tasks.ts
@@ -11778,12 +11510,12 @@ function rowState(result) {
11778
11510
  function claimNext(claim) {
11779
11511
  const first = claim.rows.find((row) => row.mayWork);
11780
11512
  if (first) {
11781
- const thread = first.messageId ? agentTaskThreadTarget(claim.target, first.messageId) : null;
11513
+ const suffix = first.messageId ? first.messageId.slice(0, 8) : null;
11782
11514
  return {
11783
11515
  kind: "start_work",
11784
- ...thread ? {
11785
- command: `raft message send --target "${thread}"`,
11786
- args: { thread }
11516
+ ...suffix ? {
11517
+ command: `raft message send --target "${claim.target}:${suffix}"`,
11518
+ args: { thread: `${claim.target}:${suffix}` }
11787
11519
  } : {},
11788
11520
  why: "The claim is yours; post progress in the task's thread."
11789
11521
  };
@@ -11794,7 +11526,20 @@ function claimNext(claim) {
11794
11526
  };
11795
11527
  }
11796
11528
  function claimText(claim) {
11797
- return formatAgentClaimResults(claim.target, { results: claim.rows.map((row) => row.raw) });
11529
+ const lines = claim.rows.map((row) => {
11530
+ const label = row.taskNumber ? `#${row.taskNumber}` : `msg:${row.ref}`;
11531
+ if (row.state === "claimed") return `${label}: claimed`;
11532
+ if (row.state === "already_yours") return `${label}: already claimed by you`;
11533
+ if (row.state === "conflict") return `${label}: held by ${row.holder?.name ? `@${row.holder.name}` : "another assignee"}`;
11534
+ return `${label}: refused${row.reason ? ` (${row.reason})` : ""}`;
11535
+ });
11536
+ const head = `Claim results (${claim.rows.filter((row) => row.mayWork).length} of ${claim.rows.length} authorise work):`;
11537
+ const next = claimNext(claim);
11538
+ return [
11539
+ head,
11540
+ ...lines,
11541
+ next?.command ? `Follow up in the task's thread: ${next.command}` : next?.why ?? ""
11542
+ ].filter(Boolean).join("\n");
11798
11543
  }
11799
11544
  async function claimTasks(client, request) {
11800
11545
  const numbers = (request.taskNumbers ?? []).filter((n) => Number.isInteger(n) && n > 0);
@@ -11809,10 +11554,8 @@ async function claimTasks(client, request) {
11809
11554
  if (!result.ok) return failureFromClientResult(result);
11810
11555
  const data = result.data;
11811
11556
  if (isHeldResponse(data)) {
11812
- const { idempotencyKey: _unused, continuation: _c, ...heldBase } = projectHeld(request.target, data, "");
11813
11557
  const held = {
11814
- ...heldBase,
11815
- request,
11558
+ ...projectHeld(request.target, data),
11816
11559
  retry: () => claimTasks(client, request)
11817
11560
  };
11818
11561
  return {
@@ -11820,10 +11563,13 @@ async function claimTasks(client, request) {
11820
11563
  state: "held",
11821
11564
  data: held,
11822
11565
  next: {
11823
- kind: "retry_claim",
11566
+ kind: "review_then_retry",
11824
11567
  command: `raft message read --target "${request.target}"`,
11825
- args: { ...request },
11826
- why: "Unread messages in this channel may change the task; read them (frontier.recordHeld(held) once the model saw them), then claim again with these args if it is still right."
11568
+ args: {
11569
+ target: request.target,
11570
+ newMessageCount: held.newMessageCount
11571
+ },
11572
+ why: "Unread messages in this channel may change the task; read them, then claim again if it is still right."
11827
11573
  },
11828
11574
  text: `Held — ${held.newMessageCount} unread ${held.newMessageCount === 1 ? "message" : "messages"} in ${request.target}. Your task claim was not applied.\nRead them with: raft message read --target "${request.target}"\nAfter reviewing, rerun the claim if it is still correct.`
11829
11575
  };
@@ -11838,8 +11584,7 @@ async function claimTasks(client, request) {
11838
11584
  mayWork: state === "claimed" || state === "already_yours",
11839
11585
  reason: row.reason ?? null,
11840
11586
  holder: row.conflict?.currentAssignee ?? null,
11841
- conflict: row.conflict ?? null,
11842
- raw: row
11587
+ conflict: row.conflict ?? null
11843
11588
  };
11844
11589
  });
11845
11590
  const claim = {
@@ -11855,235 +11600,6 @@ async function claimTasks(client, request) {
11855
11600
  text: claimText(claim)
11856
11601
  };
11857
11602
  }
11858
- async function listTasks(client, request) {
11859
- const mine = request.mine === true;
11860
- if (mine === Boolean(request.target?.trim())) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass exactly one of a channel target or mine: true." }));
11861
- const result = await client.tasks.list({
11862
- ...mine ? { mine: "true" } : { channel: request.target },
11863
- ...request.status ? { status: request.status } : {}
11864
- });
11865
- if (!result.ok) return failureFromClientResult(result);
11866
- const data = result.data;
11867
- const board = {
11868
- scope: mine ? "mine" : "channel",
11869
- target: mine ? null : request.target,
11870
- tasks: data.tasks,
11871
- coverage: data.coverage ?? null
11872
- };
11873
- const text = mine ? formatAgentMyTaskList(data, request.status) : formatAgentTaskList(request.target, data, request.status);
11874
- const open = board.tasks.find((t) => t.status === "todo" && !t.claimedByName);
11875
- const next = open?.taskNumber && board.target ? {
11876
- kind: "claim_task",
11877
- command: `raft task claim --target "${board.target}" --number ${open.taskNumber}`,
11878
- args: {
11879
- target: board.target,
11880
- taskNumbers: [open.taskNumber]
11881
- },
11882
- why: "An unassigned todo task is open; claim it before working on it."
11883
- } : null;
11884
- return {
11885
- ok: true,
11886
- state: board.tasks.length > 0 ? "board" : "empty",
11887
- data: board,
11888
- next,
11889
- text
11890
- };
11891
- }
11892
- async function createTasks(client, request) {
11893
- if (!request.target?.trim() || !request.tasks?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and at least one task title are required." }));
11894
- const result = await client.tasks.create({
11895
- channel: request.target,
11896
- tasks: request.tasks.map((t) => ({
11897
- title: t.title,
11898
- ...t.createsResource ? { creates_resource: true } : {}
11899
- })),
11900
- ...request.assignee ? { assignee: request.assignee } : {}
11901
- });
11902
- if (!result.ok) return failureFromClientResult(result);
11903
- const data = result.data;
11904
- const first = data.tasks[0];
11905
- return {
11906
- ok: true,
11907
- state: "created",
11908
- data: {
11909
- ...data,
11910
- target: request.target
11911
- },
11912
- next: first ? {
11913
- kind: "post_in_task_thread",
11914
- command: `raft message send --target "${agentTaskThreadTarget(request.target, first.messageId)}"`,
11915
- args: { thread: agentTaskThreadTarget(request.target, first.messageId) },
11916
- why: "Follow up in each task's thread."
11917
- } : null,
11918
- text: formatAgentTasksCreated(request.target, data)
11919
- };
11920
- }
11921
- function requireTaskRef(request) {
11922
- 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." }));
11923
- return null;
11924
- }
11925
- async function unclaimTask(client, request) {
11926
- const invalid = requireTaskRef(request);
11927
- if (invalid) return invalid;
11928
- const result = await client.tasks.unclaim({
11929
- channel: request.target,
11930
- task_number: request.taskNumber
11931
- });
11932
- if (!result.ok) return failureFromClientResult(result);
11933
- return {
11934
- ok: true,
11935
- state: "unclaimed",
11936
- data: request,
11937
- next: null,
11938
- text: formatAgentTaskUnclaimed(request.taskNumber)
11939
- };
11940
- }
11941
- async function assignTask(client, request) {
11942
- const invalid = requireTaskRef(request);
11943
- if (invalid) return invalid;
11944
- const result = await client.tasks.assign({
11945
- channel: request.target,
11946
- task_number: request.taskNumber,
11947
- assignee: request.assignee,
11948
- ...request.expectedRevision === void 0 ? {} : { expected_revision: request.expectedRevision }
11949
- });
11950
- if (!result.ok) return failureFromClientResult(result);
11951
- const assignee = result.data.assignee;
11952
- return {
11953
- ok: true,
11954
- state: assignee ? "assigned" : "unassigned",
11955
- data: {
11956
- target: request.target,
11957
- taskNumber: request.taskNumber,
11958
- assignee,
11959
- revision: result.data.revision
11960
- },
11961
- next: null,
11962
- text: formatAgentTaskAssigned(request.taskNumber, assignee)
11963
- };
11964
- }
11965
- function heldTaskWrite(request, data, action, kind) {
11966
- const { idempotencyKey: _k, continuation: _c, ...base } = projectHeld(request.target, data, "");
11967
- const held = {
11968
- ...base,
11969
- request
11970
- };
11971
- return {
11972
- ok: true,
11973
- state: "held",
11974
- data: held,
11975
- next: {
11976
- kind,
11977
- command: `raft message read --target "${request.target}"`,
11978
- args: { ...request },
11979
- 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.`
11980
- },
11981
- 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.`
11982
- };
11983
- }
11984
- async function updateTaskStatus(client, request) {
11985
- const invalid = requireTaskRef(request);
11986
- if (invalid) return invalid;
11987
- const result = await client.tasks.updateStatus({
11988
- channel: request.target,
11989
- task_number: request.taskNumber,
11990
- status: request.status
11991
- });
11992
- if (!result.ok) return failureFromClientResult(result);
11993
- if (isHeldResponse(result.data)) return heldTaskWrite(request, result.data, "The status change was not applied.", "retry_update_status");
11994
- return {
11995
- ok: true,
11996
- state: "updated",
11997
- data: request,
11998
- next: request.status === "in_review" ? {
11999
- kind: "await_review",
12000
- why: "A human validates the work; set done after approval."
12001
- } : null,
12002
- text: formatAgentTaskStatusUpdated(request.taskNumber, request.status)
12003
- };
12004
- }
12005
- async function amendTask(client, request) {
12006
- const invalid = requireTaskRef(request);
12007
- if (invalid) return invalid;
12008
- 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." }));
12009
- const result = await client.tasks.amend({
12010
- channel: request.target,
12011
- task_number: request.taskNumber,
12012
- ...request.title === void 0 ? {} : { title: request.title },
12013
- ...request.description === void 0 ? {} : { description: request.description }
12014
- });
12015
- if (!result.ok) return failureFromClientResult(result);
12016
- if (isHeldResponse(result.data)) return heldTaskWrite(request, result.data, "The amendment was not applied.", "retry_amend");
12017
- return {
12018
- ok: true,
12019
- state: "amended",
12020
- data: {
12021
- ...result.data,
12022
- target: request.target
12023
- },
12024
- next: null,
12025
- text: formatAgentTaskAmended(result.data)
12026
- };
12027
- }
12028
- async function taskHistory(client, request) {
12029
- const invalid = requireTaskRef(request);
12030
- if (invalid) return invalid;
12031
- const result = await client.tasks.history({
12032
- channel: request.target,
12033
- task_number: request.taskNumber
12034
- });
12035
- if (!result.ok) return failureFromClientResult(result);
12036
- return {
12037
- ok: true,
12038
- state: "history",
12039
- data: {
12040
- ...result.data,
12041
- target: request.target
12042
- },
12043
- next: null,
12044
- text: formatAgentTaskHistory(result.data)
12045
- };
12046
- }
12047
- async function convertMessageToTask(client, request) {
12048
- if (!request.target?.trim() || !request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a message id are required." }));
12049
- const result = await client.tasks.convert({
12050
- channel: request.target,
12051
- message_id: request.messageId
12052
- });
12053
- if (!result.ok) return failureFromClientResult(result);
12054
- const task = result.data.task;
12055
- return {
12056
- ok: true,
12057
- state: "converted",
12058
- data: {
12059
- target: request.target,
12060
- task
12061
- },
12062
- next: {
12063
- kind: "post_in_task_thread",
12064
- command: `raft message send --target "${agentTaskThreadTarget(request.target, task.messageId)}"`,
12065
- args: { thread: agentTaskThreadTarget(request.target, task.messageId) },
12066
- why: "Follow up in the task's thread; it is unassigned until someone claims it."
12067
- },
12068
- text: formatAgentTaskConverted(request.target, task)
12069
- };
12070
- }
12071
- async function deleteTask(client, request) {
12072
- const invalid = requireTaskRef(request);
12073
- if (invalid) return invalid;
12074
- const result = await client.tasks.delete({
12075
- channel: request.target,
12076
- task_number: request.taskNumber
12077
- });
12078
- if (!result.ok) return failureFromClientResult(result);
12079
- return {
12080
- ok: true,
12081
- state: "deleted",
12082
- data: request,
12083
- next: null,
12084
- text: formatAgentTaskDeleted(request.taskNumber)
12085
- };
12086
- }
12087
11603
  //#endregion
12088
11604
  //#region ../shared/src/agentOps/wake.ts
12089
11605
  const RAFT_INBOX_NOTICE_SCHEMA = "raft-agent-inbox-notice.v1";
@@ -12251,1861 +11767,55 @@ async function unregisterWebhook(client) {
12251
11767
  };
12252
11768
  }
12253
11769
  //#endregion
12254
- //#region ../shared/src/agentText/server.ts
12255
- function formatRuntimeContext(ctx) {
12256
- if (!ctx) return "";
12257
- const lines = ["### Current Runtime", "Authoritative context for this agent process. Do not infer computer identity from hostname or cwd when this section is present."];
12258
- if (ctx.agentId) lines.push(`- Agent ID: ${ctx.agentId}`);
12259
- if (ctx.runtime) lines.push(`- Runtime: ${ctx.runtime}`);
12260
- if (ctx.model) lines.push(`- Model: ${ctx.model}`);
12261
- if (ctx.reasoningEffort) lines.push(`- Reasoning: ${ctx.reasoningEffort}`);
12262
- if (ctx.serverId) lines.push(`- Server ID: ${ctx.serverId}`);
12263
- if (ctx.machineName || ctx.machineId) {
12264
- const label = ctx.machineName && ctx.machineId ? `${ctx.machineName} (${ctx.machineId})` : ctx.machineName || ctx.machineId;
12265
- lines.push(`- Computer: ${label}`);
12266
- }
12267
- if (ctx.machineDescription) lines.push(`- Computer Description: ${ctx.machineDescription}`);
12268
- if (ctx.machineHostname) lines.push(`- Hostname: ${ctx.machineHostname}`);
12269
- if (ctx.machineOs) lines.push(`- OS: ${ctx.machineOs}`);
12270
- if (ctx.daemonVersion) lines.push(`- Daemon: v${ctx.daemonVersion}`);
12271
- if (ctx.workspacePath) lines.push(`- Workspace: ${ctx.workspacePath}`);
12272
- return lines.length > 2 ? `${lines.join("\n")}\n\n` : "";
12273
- }
12274
- function roleLabel(role) {
12275
- return role && role !== "member" ? ` (${role})` : "";
12276
- }
12277
- function channelMemberRoleDetail(member) {
12278
- const details = [];
12279
- if (member.serverRole) details.push(`server role=${member.serverRole}`);
12280
- if (member.channelRole) details.push(`channel role=${member.channelRole}`);
12281
- if (member.channelAdminBasis) details.push(`admin via=${member.channelAdminBasis}`);
12282
- return details.length > 0 ? ` [${details.join(", ")}]` : "";
12283
- }
12284
- function agentStatusLabel(agent) {
12285
- const lifecycle = agent.status?.trim() || "unknown";
12286
- const activity = agent.activity?.trim();
12287
- if (!activity) return lifecycle;
12288
- const activityWithDetail = agent.activityDetail?.trim() ? `${activity}: ${agent.activityDetail.trim()}` : activity;
12289
- return activity === lifecycle ? lifecycle : `${lifecycle}; ${activityWithDetail}`;
12290
- }
12291
- function formatCurrentAgent(data) {
12292
- if (!data.serverRole) return "";
12293
- const lines = ["### Current Agent"];
12294
- lines.push(`- Role: ${data.serverRole}`);
12295
- return `${lines.join("\n")}\n\n`;
12296
- }
12297
- /** Server overview: runtime context, channels, agents, humans. */
12298
- function formatAgentServerInfo(data) {
12299
- let text = "## Server\n\n";
12300
- const channels = data.channels ?? [];
12301
- const agents = data.agents ?? [];
12302
- const humans = data.humans ?? [];
12303
- text += formatRuntimeContext(data.runtimeContext);
12304
- text += formatCurrentAgent(data);
12305
- text += "### Channels\n";
12306
- 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";
12307
- text += "Server-profile changes still use raft server update and remain server-role gated.\n";
12308
- text += "Mute state is shown when the server provides it; otherwise it is omitted.\n";
12309
- if (channels.length > 0) for (const t of channels) {
12310
- const statusParts = [t.type === "private" || t.type === "dm" ? "private" : "public", t.joined ? "joined" : "not joined"];
12311
- if (t.channelRole) statusParts.push(`channel role=${t.channelRole}`);
12312
- if (t.channelAdminBasis) statusParts.push(`admin via=${t.channelAdminBasis}`);
12313
- const muted = channelMuted(t);
12314
- if (muted !== void 0) statusParts.push(muted ? "muted" : "not muted");
12315
- const status = statusParts.join(", ");
12316
- const ref = agentChannelRef(t.name, t.type);
12317
- text += t.description ? ` - ${ref} [${status}] — ${t.description}\n` : ` - ${ref} [${status}]\n`;
12318
- }
12319
- else text += " (none)\n";
12320
- text += "\n### Agents\n";
12321
- text += "Other AI agents in this server.\n";
12322
- text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
12323
- if (agents.length > 0) for (const a of agents) {
12324
- const role = roleLabel(a.role);
12325
- const status = agentStatusLabel(a);
12326
- text += a.description ? ` - @${a.name} (${status})${role} — ${a.description}\n` : ` - @${a.name} (${status})${role}\n`;
12327
- }
12328
- else text += " (none)\n";
12329
- text += "\n### Humans\n";
12330
- 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";
12331
- text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
12332
- if (humans.length > 0) for (const u of humans) {
12333
- const role = roleLabel(u.role);
12334
- text += u.description ? ` - @${u.name}${role} — ${u.description}\n` : ` - @${u.name}${role}\n`;
12335
- }
12336
- else text += " (none)\n";
12337
- return text;
12338
- }
12339
- function agentChannelRef(name, type) {
12340
- if (type === "dm") return `dm:@${name}`;
12341
- return name.startsWith("#") ? name : `#${name}`;
12342
- }
12343
- function channelVisibility(channel) {
12344
- const type = channel.type?.trim();
12345
- return type === "private" || type === "dm" ? "private" : "public";
12346
- }
12347
- function channelMuted(channel) {
12348
- if (typeof channel.muted === "boolean") return channel.muted;
12349
- if (typeof channel.activityMuted === "boolean") return channel.activityMuted;
12350
- }
12351
- function channelStatus(channel) {
12352
- const parts = [channelVisibility(channel), channel.joined ? "joined" : "not joined"];
12353
- const muted = channelMuted(channel);
12354
- if (channel.channelRole) parts.push(`channel role=${channel.channelRole}`);
12355
- if (channel.channelAdminBasis) parts.push(`admin via=${channel.channelAdminBasis}`);
12356
- if (muted !== void 0) parts.push(muted ? "muted" : "not muted");
12357
- if (typeof channel.archived === "boolean") parts.push(channel.archived ? "archived" : "not archived");
12358
- return parts.join(", ");
12359
- }
12360
- function formatPageFooter(page) {
12361
- if (!page) return "";
12362
- const start = page.total === 0 ? 0 : Math.min(page.offset + 1, page.total);
12363
- const end = Math.min(page.offset + page.limit, page.total);
12364
- const lines = [`\nShowing ${start}-${end} of ${page.total}.`];
12365
- if (page.nextCommand && end < page.total) lines.push(`More: ${page.nextCommand}`);
12366
- return `${lines.join("\n")}\n`;
12367
- }
12368
- /** Compact server summary. */
12369
- function formatAgentServerSummary(data) {
12370
- const channels = data.channels ?? [];
12371
- const agents = data.agents ?? [];
12372
- const humans = data.humans ?? [];
12373
- const joined = channels.filter((channel) => channel.joined).length;
12374
- return `${[
12375
- "## Server",
12376
- "",
12377
- `Channels: ${channels.length} visible (${joined} joined)`,
12378
- `Agents: ${agents.length}`,
12379
- `Humans: ${humans.length}`,
12380
- "",
12381
- "Narrow queries:",
12382
- "- raft server info --channels",
12383
- "- raft server info --agents",
12384
- "- raft server info --humans",
12385
- "- raft channel info <name>",
12386
- "- raft user info <name>",
12387
- "",
12388
- "Full dump: raft server info --full"
12389
- ].join("\n")}\n`;
12390
- }
12391
- /** Channel listing page. */
12392
- function formatAgentServerChannels(channels, page) {
12393
- const lines = [
12394
- "## Server Channels",
12395
- "",
12396
- "Private channels are shown only when this agent is a member. Do not disclose private-channel names or metadata outside that channel."
12397
- ];
12398
- if (channels.length === 0) lines.push("(none)");
12399
- else for (const channel of channels) {
12400
- const description = channel.description?.trim();
12401
- lines.push(description ? `${agentChannelRef(channel.name, channel.type)} [${channelStatus(channel)}] — ${description}` : `${agentChannelRef(channel.name, channel.type)} [${channelStatus(channel)}]`);
12402
- }
12403
- return `${lines.join("\n")}${formatPageFooter(page)}`;
12404
- }
12405
- /** Agent listing page. */
12406
- function formatAgentServerAgents(agents, page) {
12407
- const lines = [
12408
- "## Server Agents",
12409
- "",
12410
- "Role labels show server-level owner/admin authority; no role label means ordinary member."
12411
- ];
12412
- if (agents.length === 0) lines.push("(none)");
12413
- else for (const agent of agents) {
12414
- const role = roleLabel(agent.role);
12415
- const status = agentStatusLabel(agent);
12416
- lines.push(agent.description ? `@${agent.name} (${status})${role} — ${agent.description}` : `@${agent.name} (${status})${role}`);
12417
- }
12418
- return `${lines.join("\n")}${formatPageFooter(page)}`;
12419
- }
12420
- /** Human listing page. */
12421
- function formatAgentServerHumans(humans, page) {
12422
- const lines = [
12423
- "## Server Humans",
12424
- "",
12425
- "Role labels show server-level owner/admin authority; no role label means ordinary member."
12426
- ];
12427
- if (humans.length === 0) lines.push("(none)");
12428
- else for (const human of humans) {
12429
- const role = roleLabel(human.role);
12430
- lines.push(human.description ? `@${human.name}${role} — ${human.description}` : `@${human.name}${role}`);
12431
- }
12432
- return `${lines.join("\n")}${formatPageFooter(page)}`;
12433
- }
12434
- /** Channel membership with server-role labels. */
12435
- function formatAgentChannelMembers(data) {
12436
- let text = "## Channel Members\n\n";
12437
- const ref = data.channel?.ref ?? "(unknown)";
12438
- const type = data.channel?.type ? ` (${data.channel.type})` : "";
12439
- const agents = data.agents ?? [];
12440
- const humans = data.humans ?? [];
12441
- text += `Channel: ${ref}${type}\n`;
12442
- text += "Members means join/post authority for this surface.\n\n";
12443
- text += "### Agents\n";
12444
- text += "Server and stored channel roles are shown separately when available.\n";
12445
- if (agents.length > 0) for (const a of agents) {
12446
- const role = roleLabel(a.role);
12447
- const channelRole = channelMemberRoleDetail(a);
12448
- const status = agentStatusLabel(a);
12449
- text += a.description ? ` - @${a.name} (${status})${role}${channelRole} — ${a.description}\n` : ` - @${a.name} (${status})${role}${channelRole}\n`;
12450
- }
12451
- else text += " (none)\n";
12452
- text += "\n### Humans\n";
12453
- text += "Server and stored channel roles are shown separately when available.\n";
12454
- if (humans.length > 0) for (const u of humans) {
12455
- const role = roleLabel(u.role);
12456
- const channelRole = channelMemberRoleDetail(u);
12457
- text += u.description ? ` - @${u.name}${role}${channelRole} — ${u.description}\n` : ` - @${u.name}${role}${channelRole}\n`;
12458
- }
12459
- else text += " (none)\n";
12460
- return text;
12461
- }
12462
- //#endregion
12463
- //#region ../shared/src/runtimeCatalog.ts
12464
- const EXTERNAL_AGENT_RUNTIME_ID = "external";
12465
- const EXTERNAL_AGENT_RUNTIME_DISPLAY_NAME = "External agent";
12466
- function isExternalAgentRuntime(runtime) {
12467
- return runtime === EXTERNAL_AGENT_RUNTIME_ID;
12468
- }
12469
- const RUNTIMES = [
12470
- {
12471
- id: "claude",
12472
- displayName: "Claude Code",
12473
- abbreviation: "CC",
12474
- binary: "claude",
12475
- supported: true
12476
- },
12477
- {
12478
- id: "codex",
12479
- displayName: "Codex CLI",
12480
- abbreviation: "CX",
12481
- binary: "codex",
12482
- supported: true
12483
- },
12484
- {
12485
- id: "grok",
12486
- displayName: "Grok Build",
12487
- abbreviation: "GK",
12488
- binary: "grok",
12489
- supported: true
12490
- },
12491
- {
12492
- id: "builtin",
12493
- displayName: "Built-in Pi",
12494
- abbreviation: "BP",
12495
- binary: "",
12496
- supported: true
12497
- },
12498
- {
12499
- id: "antigravity",
12500
- displayName: "Antigravity CLI",
12501
- abbreviation: "AG",
12502
- binary: "agy",
12503
- supported: true,
12504
- deprecated: true
12505
- },
12506
- {
12507
- id: "kimi-sdk",
12508
- displayName: "Kimi Code",
12509
- abbreviation: "KC",
12510
- binary: "",
12511
- supported: true
12512
- },
12513
- {
12514
- id: "kimi",
12515
- displayName: "Kimi CLI",
12516
- abbreviation: "KL",
12517
- binary: "kimi",
12518
- supported: true,
12519
- deprecated: true
12520
- },
12521
- {
12522
- id: "copilot",
12523
- displayName: "Copilot CLI",
12524
- abbreviation: "CP",
12525
- binary: "copilot",
12526
- supported: true
12527
- },
12528
- {
12529
- id: "cursor",
12530
- displayName: "Cursor CLI",
12531
- abbreviation: "CU",
12532
- binary: "cursor-agent",
12533
- supported: true
12534
- },
12535
- {
12536
- id: "gemini",
12537
- displayName: "Gemini CLI",
12538
- abbreviation: "GM",
12539
- binary: "gemini",
12540
- supported: true,
12541
- deprecated: true
12542
- },
12543
- {
12544
- id: "opencode",
12545
- displayName: "OpenCode",
12546
- abbreviation: "OC",
12547
- binary: "opencode",
12548
- supported: true
12549
- },
12550
- {
12551
- id: "pi",
12552
- displayName: "Pi",
12553
- abbreviation: "PI",
12554
- binary: "pi",
12555
- supported: true
12556
- }
12557
- ];
12558
- function isRuntimeDeprecated(runtimeId) {
12559
- return RUNTIMES.some((runtime) => runtime.id === runtimeId && Boolean(runtime.deprecated));
12560
- }
12561
- /** Map runtime ID → display name. Falls back to the ID itself. */
12562
- function getRuntimeDisplayName(id) {
12563
- if (isExternalAgentRuntime(id)) return EXTERNAL_AGENT_RUNTIME_DISPLAY_NAME;
12564
- return RUNTIMES.find((r) => r.id === id)?.displayName ?? id;
12565
- }
12566
- //#endregion
12567
- //#region ../shared/src/agentText/threadsProfile.ts
12568
- /**
12569
- * Runtime label for identity display in agent-facing output: product name plus
12570
- * lifecycle status. Agent-facing text is English-only, so the suffix is literal
12571
- * here; the web surface renders the same status from the i18n catalog.
12572
- */
12573
- function agentRuntimeLabelWithStatus(runtimeId) {
12574
- const name = getRuntimeDisplayName(runtimeId);
12575
- return isRuntimeDeprecated(runtimeId) ? `${name} (deprecated)` : name;
12576
- }
12577
- function formatDoneSuffix(thread) {
12578
- return thread.doneAt ? `, doneAt=${thread.doneAt}` : "";
12579
- }
12580
- /** Followed thread list for the bound agent, including exact thread targets. */
12581
- function formatAgentThreadList(threads) {
12582
- if (threads.length === 0) return "No followed threads.";
12583
- 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");
12584
- }
12585
- function formatCreatedAgents(createdAgents, runtimeLabel) {
12586
- if (createdAgents.length === 0) return ["- Created Agents: none"];
12587
- return [`- Created Agents (${createdAgents.length}):`, ...createdAgents.map((createdAgent) => ` - @${createdAgent.name} (${runtimeLabel(createdAgent.runtime)}, ${createdAgent.status})`)];
12588
- }
12589
- function formatHumanProfile(profile, runtimeLabel) {
12590
- const lines = [
12591
- "## Profile",
12592
- "",
12593
- "- Type: human",
12594
- `- Handle: @${profile.name}`,
12595
- `- Display Name: ${profile.displayName ?? "(none)"}`,
12596
- `- Description: ${profile.description ?? "(none)"}`,
12597
- `- Membership: ${profile.membershipStatus}`
12598
- ];
12599
- if (profile.role) lines.push(`- Role: ${profile.role}`);
12600
- if (profile.joinedAt) lines.push(`- Joined: ${profile.joinedAt}`);
12601
- if (profile.email) lines.push(`- Email: ${profile.email}`);
12602
- return [...lines, ...formatCreatedAgents(profile.createdAgents, runtimeLabel)].join("\n");
12603
- }
12604
- function formatCreator(profile) {
12605
- if (!profile.creator) return null;
12606
- return profile.creator.displayName ? `${profile.creator.displayName} (@${profile.creator.name})` : `@${profile.creator.name}`;
12607
- }
12608
- function formatAgentProfileCard(profile, runtimeLabel) {
12609
- const lines = [
12610
- "## Profile",
12611
- "",
12612
- "- Type: agent",
12613
- `- Handle: @${profile.name}`,
12614
- `- Display Name: ${profile.displayName ?? "(none)"}`,
12615
- `- Description: ${profile.description ?? "(none)"}`,
12616
- `- Status: ${profile.status}`,
12617
- `- Role: ${profile.serverRole}`,
12618
- `- Runtime: ${runtimeLabel(profile.runtime)}`,
12619
- `- Model: ${profile.model}`,
12620
- `- Reasoning: ${profile.reasoningEffort ?? "medium"}`
12621
- ];
12622
- if (profile.executionMode) lines.push(`- Execution: ${profile.executionMode}`);
12623
- if (profile.computerName || profile.computerId) {
12624
- const label = profile.computerName && profile.computerId ? `${profile.computerName} (${profile.computerId})` : profile.computerName ?? profile.computerId;
12625
- lines.push(`- Computer: ${label}`);
12626
- }
12627
- if (profile.computerHostname) lines.push(`- Hostname: ${profile.computerHostname}`);
12628
- if (profile.daemonVersion) lines.push(`- Daemon: v${profile.daemonVersion}`);
12629
- lines.push(`- Created: ${profile.createdAt}`);
12630
- if (profile.deletedAt) lines.push(`- Deleted At: ${profile.deletedAt}`);
12631
- const creator = formatCreator(profile);
12632
- if (creator) lines.push(`- Creator: ${creator}`);
12633
- return [...lines, ...formatCreatedAgents(profile.createdAgents, runtimeLabel)].join("\n");
12634
- }
12635
- /** Agent/human profile card. */
12636
- function formatAgentProfile(profile, options = {}) {
12637
- const runtimeLabel = options.runtimeLabel ?? agentRuntimeLabelWithStatus;
12638
- return profile.kind === "human" ? formatHumanProfile(profile, runtimeLabel) : formatAgentProfileCard(profile, runtimeLabel);
12639
- }
12640
- //#endregion
12641
- //#region ../shared/src/agentOps/channels.ts
12642
- const INVALID_CHANNEL_TARGET = "Target must be a regular channel in the form '#channel-name'. DMs and thread targets are not supported.";
12643
- async function resolveRegularChannel(client, target) {
12644
- const name = parseRaftRegularChannelTarget$1(target ?? "");
12645
- if (!name) return failureOutcome(opError("INVALID_REQUEST", { message: INVALID_CHANNEL_TARGET }));
12646
- const info = await client.server.info();
12647
- if (!info.ok) return failureFromClientResult(info);
12648
- const channel = info.data.channels.find((candidate) => candidate.name === name);
12649
- if (!channel) return failureOutcome(opError("NOT_FOUND", {
12650
- message: `Channel not found: ${target}`,
12651
- nextAction: "List visible channels with `raft server info --channels`; private channels need a human to add you."
12652
- }));
12653
- return {
12654
- id: channel.id,
12655
- name: channel.name,
12656
- joined: channel.joined
12657
- };
12658
- }
12659
- async function joinChannel(client, request) {
12660
- const result = await joinRaftChannelByTarget$1(client, { target: request.target });
12661
- if (!result.ok) {
12662
- const error = result.error;
12663
- if (error.kind === "validation") return error.reason === "target_not_found" ? failureOutcome(opError("NOT_FOUND", {
12664
- message: error.message,
12665
- nextAction: "Only visible public channels can be joined; private and joint channels need an invitation."
12666
- })) : failureOutcome(opError("INVALID_REQUEST", { message: error.message }));
12667
- if (error.kind === "http") return failureOutcome(opError("HTTP_ERROR", {
12668
- message: error.message,
12669
- status: error.status,
12670
- ...error.errorCode ? { serverCode: error.errorCode } : {},
12671
- ...error.suggestedNextAction ? { nextAction: error.suggestedNextAction } : {}
12672
- }));
12673
- return failureOutcome(opError("TRANSPORT_ERROR", { message: error.message }));
12674
- }
12675
- const state = result.data.state;
11770
+ //#region src/raft.ts
11771
+ function createRaft(options) {
11772
+ const serverUrl = requireServerUrl(options.serverUrl);
11773
+ const authorization = `Bearer ${requireAgentCredential(options.credential)}`;
11774
+ const frontier = SeenFrontier.fromSnapshot(options.frontier);
11775
+ const routes = createRaftRoutes({
11776
+ serverUrl,
11777
+ fetch: options.fetch,
11778
+ headers: options.headers,
11779
+ authorization,
11780
+ readAttempts: options.retry?.attempts,
11781
+ beforeRequest: options.throttle?.beforeRequest
11782
+ });
11783
+ const inboxApi = createAgentApiClient({ fetch: {
11784
+ baseUrl: serverUrl,
11785
+ fetch: (input, init) => (options.fetch ?? fetch)(input, {
11786
+ ...init,
11787
+ cache: "no-store",
11788
+ redirect: "error"
11789
+ }),
11790
+ headers: Object.fromEntries(new Headers(options.headers)),
11791
+ retry: { attempts: 1 },
11792
+ throttle: options.throttle,
11793
+ auth: { authorization }
11794
+ } });
12676
11795
  return {
12677
- ok: true,
12678
- state,
12679
- data: {
12680
- target: result.data.target,
12681
- channelId: result.data.channelId
12682
- },
12683
- next: {
12684
- kind: "read_target",
12685
- command: `raft message read --target "${result.data.target}"`,
12686
- args: { target: result.data.target },
12687
- why: "Read the channel before posting."
11796
+ identity: { whoami: () => getRaftContext(routes) },
11797
+ wake: {
11798
+ verifyNotice: (input) => verifyInboxNotice(input),
11799
+ webhook: {
11800
+ status: () => webhookStatus(routes),
11801
+ register: (request) => registerWebhook(routes, request),
11802
+ unregister: () => unregisterWebhook(routes)
11803
+ }
12688
11804
  },
12689
- text: state === "joined" ? `Joined ${result.data.target}.` : `Already a member of ${result.data.target}.`
12690
- };
12691
- }
12692
- async function leaveChannel(client, request) {
12693
- const channel = await resolveRegularChannel(client, request.target);
12694
- if ("ok" in channel) return channel;
12695
- if (!channel.joined) return {
12696
- ok: true,
12697
- state: "not_joined",
12698
- data: {
12699
- target: request.target,
12700
- channelId: channel.id
11805
+ inbox: {
11806
+ check: (request) => checkInbox(inboxApi, request, frontier),
11807
+ drain: (request) => drainInbox(inboxApi, request, frontier),
11808
+ list: (request) => listInbox(routes, request)
12701
11809
  },
12702
- next: null,
12703
- text: `You are not a member of ${request.target}; nothing to leave.`
12704
- };
12705
- const result = await client.channels.leave({ channelId: channel.id });
12706
- if (!result.ok) return failureFromClientResult(result);
12707
- 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.`];
12708
- const attention = result.data.attention;
12709
- if (attention?.ordinaryActivity) lines.push(attention.ordinaryActivity);
12710
- return {
12711
- ok: true,
12712
- state: "left",
12713
- data: {
12714
- target: request.target,
12715
- channelId: channel.id
12716
- },
12717
- next: null,
12718
- text: lines.join("\n")
12719
- };
12720
- }
12721
- function formatSeq(value) {
12722
- return value == null ? "none" : String(value);
12723
- }
12724
- async function setChannelMute(client, request, action) {
12725
- const channel = await resolveRegularChannel(client, request.target);
12726
- if ("ok" in channel) return channel;
12727
- const result = action === "mute" ? await client.channels.mute({ channelId: channel.id }, {}) : await client.channels.unmute({ channelId: channel.id });
12728
- if (!result.ok) return failureFromClientResult(result);
12729
- const data = result.data;
12730
- const lines = [
12731
- `${data.activityMuted ? "Muted" : "Unmuted"} ${request.target}.`,
12732
- `Activity muted: ${data.activityMuted ? "yes" : "no"}`,
12733
- `Mute from seq: ${formatSeq(data.muteFromSeq)}`
12734
- ];
12735
- if (data.attention?.ordinaryActivity) lines.push(data.attention.ordinaryActivity);
12736
- if (data.attention?.stillArrives?.length) {
12737
- lines.push("Still arrives:");
12738
- for (const item of data.attention.stillArrives) lines.push(`- ${item}`);
12739
- }
12740
- if (data.attention?.threadBoundary) lines.push(data.attention.threadBoundary);
12741
- if (data.attention?.catchUp) lines.push(data.attention.catchUp);
12742
- if (data.attention?.unmuteCommand) lines.push(`To unmute: ${data.attention.unmuteCommand}`);
12743
- if (data.attention?.unmuteApi) lines.push(`Agent API: ${data.attention.unmuteApi}`);
12744
- if (data.attention?.muteCommand) lines.push(`To mute: ${data.attention.muteCommand}`);
12745
- if (data.attention?.muteApi) lines.push(`Agent API: ${data.attention.muteApi}`);
12746
- return {
12747
- ok: true,
12748
- state: data.activityMuted ? "muted" : "unmuted",
12749
- data: {
12750
- target: request.target,
12751
- channelId: channel.id,
12752
- activityMuted: data.activityMuted === true,
12753
- muteFromSeq: data.muteFromSeq ?? null,
12754
- stillArrives: data.attention?.stillArrives ?? []
12755
- },
12756
- next: null,
12757
- text: lines.join("\n")
12758
- };
12759
- }
12760
- function muteChannel(client, request) {
12761
- return setChannelMute(client, request, "mute");
12762
- }
12763
- function unmuteChannel(client, request) {
12764
- return setChannelMute(client, request, "unmute");
12765
- }
12766
- async function channelMembers(client, request) {
12767
- if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel, DM, or thread target is required." }));
12768
- const result = await client.channels.members({ channel: request.target });
12769
- if (!result.ok) return failureFromClientResult(result);
12770
- return {
12771
- ok: true,
12772
- state: "members",
12773
- data: result.data,
12774
- next: null,
12775
- text: formatAgentChannelMembers(result.data)
12776
- };
12777
- }
12778
- async function listThreads(client) {
12779
- const result = await client.threads.list();
12780
- if (!result.ok) return failureFromClientResult(result);
12781
- const threads = result.data.threads;
12782
- return {
12783
- ok: true,
12784
- state: threads.length > 0 ? "threads" : "empty",
12785
- data: threads,
12786
- next: null,
12787
- text: formatAgentThreadList(threads)
12788
- };
12789
- }
12790
- async function unfollowThread(client, request) {
12791
- if (!request.target?.includes(":")) return failureOutcome(opError("INVALID_REQUEST", { message: "A thread target is required, for example '#channel:shortid' or 'dm:@peer:shortid'." }));
12792
- const result = await client.threads.unfollow({
12793
- thread: request.target,
12794
- ...request.reason ? { reason: request.reason } : {}
12795
- });
12796
- if (!result.ok) return failureFromClientResult(result);
12797
- return {
12798
- ok: true,
12799
- state: "unfollowed",
12800
- data: { target: request.target },
12801
- next: null,
12802
- text: `Unfollowed ${request.target}. Ordinary delivery from this thread stops; a direct @mention reactivates the follow.`
12803
- };
12804
- }
12805
- //#endregion
12806
- //#region ../shared/src/agentOps/server.ts
12807
- function nextCommand(section, request, offset, limit, total) {
12808
- const nextOffset = offset + limit;
12809
- if (nextOffset >= total) return void 0;
12810
- const parts = [
12811
- "raft server info",
12812
- `--${section}`,
12813
- `--offset ${nextOffset}`,
12814
- `--limit ${limit}`
12815
- ];
12816
- if (section === "channels" && request.joined) parts.push("--joined");
12817
- return parts.join(" ");
12818
- }
12819
- async function serverInfo(client, request = {}) {
12820
- const result = await client.server.info();
12821
- if (!result.ok) return failureFromClientResult(result);
12822
- const server = result.data;
12823
- const view = request.view ?? "summary";
12824
- if (view === "summary") return {
12825
- ok: true,
12826
- state: "info",
12827
- data: {
12828
- view,
12829
- server,
12830
- page: null
12831
- },
12832
- next: {
12833
- kind: "list_channels",
12834
- command: "raft server info --channels",
12835
- why: "The summary only counts; list a section to see names."
12836
- },
12837
- text: formatAgentServerSummary(server)
12838
- };
12839
- if (view === "full") return {
12840
- ok: true,
12841
- state: "info",
12842
- data: {
12843
- view,
12844
- server,
12845
- page: null
12846
- },
12847
- next: null,
12848
- text: formatAgentServerInfo(server)
12849
- };
12850
- const limit = Math.max(1, Math.trunc(request.limit ?? 50));
12851
- const offset = Math.max(0, Math.trunc(request.offset ?? 0));
12852
- const rows = view === "channels" ? server.channels.filter((c) => !request.joined || c.joined) : view === "agents" ? server.agents : server.humans;
12853
- const pageRows = rows.slice(offset, offset + limit);
12854
- const page = {
12855
- section: view,
12856
- total: rows.length,
12857
- offset,
12858
- limit,
12859
- nextCommand: nextCommand(view, request, offset, limit, rows.length)
12860
- };
12861
- const text = view === "channels" ? formatAgentServerChannels(pageRows, page) : view === "agents" ? formatAgentServerAgents(pageRows, page) : formatAgentServerHumans(pageRows, page);
12862
- const next = page.nextCommand ? {
12863
- kind: "next_page",
12864
- command: page.nextCommand,
12865
- args: {
12866
- view,
12867
- offset: offset + limit,
12868
- limit
12869
- },
12870
- why: "More rows exist; one page is one page."
12871
- } : null;
12872
- return {
12873
- ok: true,
12874
- state: "info",
12875
- data: {
12876
- view,
12877
- server,
12878
- page
12879
- },
12880
- next,
12881
- text
12882
- };
12883
- }
12884
- async function showProfile(client, request = {}, options = {}) {
12885
- const result = await client.profile.show(request.target ? { target: request.target } : {});
12886
- if (!result.ok) return failureFromClientResult(result);
12887
- return {
12888
- ok: true,
12889
- state: "profile",
12890
- data: result.data,
12891
- next: null,
12892
- text: formatAgentProfile(result.data, options)
12893
- };
12894
- }
12895
- async function updateProfile(client, request, options = {}) {
12896
- 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." }));
12897
- const result = await client.profile.update(request);
12898
- if (!result.ok) return failureFromClientResult(result);
12899
- return {
12900
- ok: true,
12901
- state: "updated",
12902
- data: result.data,
12903
- next: null,
12904
- text: formatAgentProfile(result.data, options)
12905
- };
12906
- }
12907
- //#endregion
12908
- //#region ../shared/src/agentText/attachments.ts
12909
- /** Upload receipt with attachment id and send-usage hint. */
12910
- function formatAgentAttachmentUploaded(attachment) {
12911
- 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`;
12912
- }
12913
- function anchorSummary(anchor) {
12914
- if (anchor.type === "md-section") {
12915
- const title = anchor.data.headingTitle ?? anchor.data.headingId;
12916
- return typeof title === "string" && title ? `§ ${title}` : "§ section";
12917
- }
12918
- if (anchor.type === "lines" || anchor.type === "csv-rows") {
12919
- const start = Number(anchor.data.start);
12920
- const end = Number(anchor.data.end ?? start);
12921
- if (!Number.isFinite(start)) return anchor.type;
12922
- const prefix = anchor.type === "lines" ? "L" : "rows ";
12923
- return start === (Number.isFinite(end) ? end : start) ? `${prefix}${start}` : `${prefix}${start}–${end}`;
12924
- }
12925
- if (anchor.type === "html-region") {
12926
- const quote = anchor.data.quote;
12927
- if (typeof quote === "string" && quote.trim().length > 0) {
12928
- const trimmed = quote.trim();
12929
- return trimmed.length > 60 ? `${trimmed.slice(0, 60)}…` : trimmed;
12930
- }
12931
- return "HTML region";
12932
- }
12933
- return anchor.type;
12934
- }
12935
- /** Attachment-scoped comment list incl. anchors/reactions, or its empty state. */
12936
- function formatAgentAttachmentComments(attachmentId, comments, threadChannelId) {
12937
- if (comments.length === 0) return `No comments on attachment ${attachmentId.slice(0, 8)}.\n`;
12938
- const lines = [`## Comments on attachment ${attachmentId.slice(0, 8)} (${comments.length})`];
12939
- for (const c of comments) {
12940
- const check = c.reactions.some((r) => r.emoji === "✅") ? " ✅" : "";
12941
- const anchor = c.anchor ? ` [anchor: ${anchorSummary(c.anchor)}]` : "";
12942
- lines.push(`[msg=${c.id.slice(0, 8)} time=${c.createdAt} type=${c.senderType}]${check}${anchor} @${c.senderName}: ${c.content}`);
12943
- }
12944
- if (threadChannelId) lines.push(`(full conversation lives in thread channel ${threadChannelId})`);
12945
- return lines.join("\n") + "\n";
12946
- }
12947
- //#endregion
12948
- //#region ../shared/src/agentOps/attachments.ts
12949
- /** Compatibility fallback for Servers that predate the capability endpoint (the CLI's constant). */
12950
- const AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES = 52428800;
12951
- const FILENAME_MIME_MAP = {
12952
- ".jpg": "image/jpeg",
12953
- ".jpeg": "image/jpeg",
12954
- ".png": "image/png",
12955
- ".gif": "image/gif",
12956
- ".webp": "image/webp",
12957
- ".pdf": "application/pdf",
12958
- ".txt": "text/plain",
12959
- ".md": "text/markdown",
12960
- ".json": "application/json",
12961
- ".csv": "text/csv"
12962
- };
12963
- const MIME_TYPE_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
12964
- function sniffMimeType(bytes) {
12965
- const starts = (sig) => sig.every((b, i) => bytes[i] === b);
12966
- if (bytes.length >= 8 && starts([
12967
- 137,
12968
- 80,
12969
- 78,
12970
- 71,
12971
- 13,
12972
- 10,
12973
- 26,
12974
- 10
12975
- ])) return "image/png";
12976
- if (bytes.length >= 3 && starts([
12977
- 255,
12978
- 216,
12979
- 255
12980
- ])) return "image/jpeg";
12981
- if (bytes.length >= 6) {
12982
- const header = String.fromCharCode(...bytes.subarray(0, 6));
12983
- if (header === "GIF87a" || header === "GIF89a") return "image/gif";
12984
- }
12985
- if (bytes.length >= 12 && String.fromCharCode(...bytes.subarray(0, 4)) === "RIFF" && String.fromCharCode(...bytes.subarray(8, 12)) === "WEBP") return "image/webp";
12986
- return null;
12987
- }
12988
- /** Explicit type wins; otherwise sniff the bytes, then the filename extension, then octet-stream. */
12989
- function inferAttachmentMimeType(filename, bytes, explicit) {
12990
- const normalized = explicit?.trim().toLowerCase();
12991
- if (normalized && MIME_TYPE_RE.test(normalized)) return normalized;
12992
- const dot = filename.lastIndexOf(".");
12993
- const ext = dot >= 0 ? filename.slice(dot).toLowerCase() : "";
12994
- return sniffMimeType(bytes) ?? FILENAME_MIME_MAP[ext] ?? "application/octet-stream";
12995
- }
12996
- /**
12997
- * Upload bytes into a conversation, choosing the path the CLI would: multipart
12998
- * `POST /upload` below the Server's direct-upload threshold, an upload session
12999
- * (create → PUT to a presigned URL → complete) at or above it.
13000
- */
13001
- async function uploadAttachment(client, transport, request) {
13002
- if (!request.target?.trim() || !request.filename?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and a filename are required to upload." }));
13003
- if (!(request.bytes instanceof Uint8Array) || request.bytes.byteLength === 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Refusing to upload a 0-byte attachment." }));
13004
- 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}` }));
13005
- const capability = await client.attachments.uploadCapabilities();
13006
- const maxBytes = capability.ok ? capability.data.maxBytes : AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES;
13007
- const threshold = capability.ok && capability.data.directUploadEnabled ? capability.data.directUploadThresholdBytes : null;
13008
- if (request.bytes.byteLength > maxBytes) return failureOutcome(opError("INVALID_REQUEST", { message: `Attachment is ${request.bytes.byteLength} bytes; the Server's maximum is ${maxBytes}.` }));
13009
- const resolved = await client.channels.resolve({ target: request.target });
13010
- if (!resolved.ok) return failureFromClientResult(resolved);
13011
- const channelId = resolved.data.channelId;
13012
- const mimeType = inferAttachmentMimeType(request.filename, request.bytes, request.mimeType);
13013
- if (threshold !== null && request.bytes.byteLength >= threshold) return uploadThroughSession(client, transport, request, channelId, mimeType);
13014
- const copy = new Uint8Array(request.bytes.byteLength);
13015
- copy.set(request.bytes);
13016
- const form = new FormData();
13017
- form.append("file", new Blob([copy.buffer], { type: mimeType }), request.filename);
13018
- form.append("channelId", channelId);
13019
- if (request.mimeType) form.append("mimeType", mimeType);
13020
- const headers = new Headers(transport.headers);
13021
- headers.delete("content-type");
13022
- headers.set("accept", "application/json");
13023
- headers.set("authorization", transport.authorization);
13024
- let response;
13025
- try {
13026
- response = await transport.fetch(`${transport.serverUrl}${agentApiContract.attachmentUpload.fullPath}`, {
13027
- method: "POST",
13028
- headers,
13029
- body: form
13030
- });
13031
- } catch {
13032
- return failureOutcome(opError("TRANSPORT_ERROR"));
13033
- }
13034
- let body = null;
13035
- try {
13036
- body = await response.json();
13037
- } catch {
13038
- body = null;
13039
- }
13040
- if (!response.ok) {
13041
- const b = body && typeof body === "object" ? body : {};
13042
- return failureOutcome(opErrorFromClientError({
13043
- kind: "http",
13044
- reason: "http_error",
13045
- message: typeof b.error === "string" ? b.error : `HTTP ${response.status}`,
13046
- status: response.status,
13047
- errorCode: typeof b.errorCode === "string" ? b.errorCode : typeof b.code === "string" ? b.code : null,
13048
- suggestedNextAction: typeof b.suggestedNextAction === "string" ? b.suggestedNextAction : null
13049
- }));
13050
- }
13051
- const parsed = agentApiContract.attachmentUpload.response.body.safeParse(body);
13052
- if (!parsed.success) return failureOutcome(opError("INVALID_RESPONSE"));
13053
- return uploadedOutcome(request.target, parsed.data, mimeType);
13054
- }
13055
- function uploadedOutcome(target, data, mimeType) {
13056
- return {
13057
- ok: true,
13058
- state: "uploaded",
13059
- data: {
13060
- ...data,
13061
- target,
13062
- mimeType: data.mimeType ?? mimeType
13063
- },
13064
- next: {
13065
- kind: "send_with_attachment",
13066
- command: `raft message send --target "${target}" --attachment-id ${data.id}`,
13067
- args: {
13068
- target,
13069
- attachmentIds: [data.id]
13070
- },
13071
- why: "The upload alone posts nothing; send a message that links the attachment id."
13072
- },
13073
- text: formatAgentAttachmentUploaded(data)
13074
- };
13075
- }
13076
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13077
- /**
13078
- * Direct upload for files at or above the Server's threshold, mirroring the
13079
- * CLI: create a session, PUT the bytes to the presigned URL (fetch; one retry
13080
- * when the object store may have committed), then complete, which the Server
13081
- * verifies against the object store. A PUT that definitely failed cancels the
13082
- * session; a PUT whose outcome is unknown leaves it for completion to verify.
13083
- */
13084
- async function uploadThroughSession(client, transport, request, channelId, mimeType) {
13085
- const created = await client.attachments.createUploadSession({
13086
- channelId,
13087
- filename: request.filename,
13088
- mimeType,
13089
- sizeBytes: request.bytes.byteLength,
13090
- clientRequestId: crypto.randomUUID()
13091
- });
13092
- if (!created.ok) return failureFromClientResult(created);
13093
- const { uploadId, upload } = created.data;
13094
- const body = new Uint8Array(request.bytes.byteLength);
13095
- body.set(request.bytes);
13096
- let definitelyFailed = null;
13097
- for (let attempt = 0; attempt < 2; attempt += 1) {
13098
- let response;
13099
- try {
13100
- response = await transport.fetch(upload.url, {
13101
- method: upload.method ?? "PUT",
13102
- headers: { ...upload.headers },
13103
- body: body.buffer,
13104
- redirect: "error"
13105
- });
13106
- } catch {
13107
- if (attempt === 0) continue;
13108
- break;
13109
- }
13110
- if (response.ok || response.status === 412) {
13111
- definitelyFailed = null;
13112
- break;
13113
- }
13114
- const mayExist = response.status === 408 || response.status === 429 || response.status >= 500;
13115
- if (mayExist && attempt === 0) continue;
13116
- if (!mayExist) definitelyFailed = response.status;
13117
- break;
13118
- }
13119
- if (definitelyFailed !== null) {
13120
- await client.attachments.cancelUploadSession({ uploadId }).catch(() => void 0);
13121
- return failureOutcome(opError("HTTP_ERROR", {
13122
- message: `Direct object upload failed with HTTP ${definitelyFailed}; the upload session was cancelled.`,
13123
- status: definitelyFailed,
13124
- nextAction: "Retry the upload; nothing was attached."
13125
- }));
13126
- }
13127
- for (let attempt = 0; attempt < 3; attempt += 1) {
13128
- const completed = await client.attachments.completeUploadSession({ uploadId });
13129
- if (completed.ok) {
13130
- const attachment = completed.data.attachment;
13131
- return uploadedOutcome(request.target, attachment, mimeType);
13132
- }
13133
- const code = completed.error.kind === "http" ? completed.error.errorCode : null;
13134
- if (!(code === "UPLOAD_OBJECT_NOT_FOUND" || code === "UPLOAD_VERIFICATION_IN_PROGRESS") || attempt === 2) return failureFromClientResult(completed);
13135
- await wait(250 * (attempt + 1));
13136
- }
13137
- return failureOutcome(opError("UNAVAILABLE", { message: "Direct upload completion ended without a terminal response." }));
13138
- }
13139
- async function downloadAttachment(client, request) {
13140
- if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13141
- const result = await client.attachments.download({ attachmentId: request.attachmentId });
13142
- if (!result.ok) return failureFromClientResult(result);
13143
- const bytes = result.data;
13144
- return {
13145
- ok: true,
13146
- state: "downloaded",
13147
- data: {
13148
- attachmentId: request.attachmentId,
13149
- bytes
13150
- },
13151
- next: null,
13152
- text: `Downloaded attachment ${request.attachmentId.slice(0, 8)} (${bytes.byteLength} bytes).`
13153
- };
13154
- }
13155
- async function attachmentComments(client, request) {
13156
- if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13157
- const result = await client.attachments.comments({ attachmentId: request.attachmentId }, request.limit === void 0 ? {} : { limit: String(request.limit) });
13158
- if (!result.ok) return failureFromClientResult(result);
13159
- const data = result.data;
13160
- return {
13161
- ok: true,
13162
- state: data.comments.length > 0 ? "comments" : "empty",
13163
- data: {
13164
- ...data,
13165
- attachmentId: request.attachmentId
13166
- },
13167
- next: null,
13168
- text: formatAgentAttachmentComments(request.attachmentId, data.comments, data.threadChannelId)
13169
- };
13170
- }
13171
- //#endregion
13172
- //#region ../shared/src/agentText/search.ts
13173
- /** Local wall-clock rendering with offset, as the CLI prints search hit times. */
13174
- function formatLocalTimeWithOffset(iso) {
13175
- const d = new Date(iso);
13176
- if (isNaN(d.getTime())) return iso;
13177
- const pad = (n) => String(n).padStart(2, "0");
13178
- const offsetMinutes = -d.getTimezoneOffset();
13179
- const sign = offsetMinutes >= 0 ? "+" : "-";
13180
- const absOffset = Math.abs(offsetMinutes);
13181
- const offset = `${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`;
13182
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} ${offset}`;
13183
- }
13184
- function renderSearchSource(result) {
13185
- if (result.channelType === "thread") {
13186
- 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;
13187
- if (result.parentChannelType === "dm") return `dm:${neutralizeAgentRaftRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
13188
- return `thread:${neutralizeAgentRaftRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
13189
- }
13190
- if (result.channelType === "dm") return `dm:${neutralizeAgentRaftRefLiterals(result.channelName ?? "unknown")}`;
13191
- return `channel:${neutralizeAgentRaftRefLiterals(result.channelName ?? "unknown")}`;
13192
- }
13193
- const PREVIEW_BEFORE_CHARS = 80;
13194
- const PREVIEW_AFTER_CHARS = 120;
13195
- const PREVIEW_FALLBACK_CHARS = 200;
13196
- function escapeRegExp(value) {
13197
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13198
- }
13199
- function findSearchMatch(content, query) {
13200
- const normalizedQuery = query.trim();
13201
- if (!normalizedQuery) return null;
13202
- const exactIndex = content.toLowerCase().indexOf(normalizedQuery.toLowerCase());
13203
- if (exactIndex >= 0) return {
13204
- start: exactIndex,
13205
- end: exactIndex + normalizedQuery.length
13206
- };
13207
- const terms = normalizedQuery.match(/"([^"]+)"|\S+/g) ?? [];
13208
- for (const rawTerm of terms) {
13209
- const term = rawTerm.replace(/^"|"$/g, "").trim();
13210
- if (!term) continue;
13211
- const match = new RegExp(escapeRegExp(term), "i").exec(content);
13212
- if (match?.index !== void 0) return {
13213
- start: match.index,
13214
- end: match.index + match[0].length
13215
- };
13216
- }
13217
- return null;
13218
- }
13219
- function* findRaftRefLiteralRanges(content) {
13220
- for (const match of content.matchAll(/\bdm:@[A-Za-z0-9][A-Za-z0-9_-]*(?:~(?:agent|human))?/g)) if (match.index !== void 0) yield {
13221
- start: match.index,
13222
- end: match.index + match[0].length
13223
- };
13224
- for (const match of content.matchAll(/\btask #[0-9]+\b/g)) if (match.index !== void 0) yield {
13225
- start: match.index,
13226
- end: match.index + match[0].length
13227
- };
13228
- for (const match of content.matchAll(/(^|[\n\s([{"'`;])(@[A-Za-z0-9][A-Za-z0-9_-]*)/g)) {
13229
- if (match.index === void 0) continue;
13230
- const prefix = match[1] ?? "";
13231
- const ref = match[2] ?? "";
13232
- yield {
13233
- start: match.index + prefix.length,
13234
- end: match.index + prefix.length + ref.length
13235
- };
13236
- }
13237
- for (const match of content.matchAll(/(^|[\n\s([{"'`;])(#[A-Za-z][A-Za-z0-9_-]*)/g)) {
13238
- if (match.index === void 0) continue;
13239
- const prefix = match[1] ?? "";
13240
- const ref = match[2] ?? "";
13241
- yield {
13242
- start: match.index + prefix.length,
13243
- end: match.index + prefix.length + ref.length
13244
- };
13245
- }
13246
- }
13247
- function expandSearchMatchToRefLiteral(content, match) {
13248
- for (const refRange of findRaftRefLiteralRanges(content)) if (match.start < refRange.end && match.end > refRange.start) return {
13249
- start: Math.min(match.start, refRange.start),
13250
- end: Math.max(match.end, refRange.end)
13251
- };
13252
- return match;
13253
- }
13254
- function trimPreviewWindow(content, start, end) {
13255
- let trimmedStart = start;
13256
- let trimmedEnd = end;
13257
- while (trimmedStart > 0 && /\s/.test(content[trimmedStart] ?? "")) trimmedStart += 1;
13258
- while (trimmedEnd < content.length && /\s/.test(content[trimmedEnd - 1] ?? "")) trimmedEnd -= 1;
13259
- return {
13260
- start: Math.max(0, Math.min(trimmedStart, content.length)),
13261
- end: Math.max(0, Math.min(trimmedEnd, content.length))
13262
- };
13263
- }
13264
- function escapeSearchComponentLiterals(text) {
13265
- return text.replace(/<\/?(?:result|preview|match)\b[^>]*>|<omit\s*\/>/gi, (tag) => tag.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
13266
- }
13267
- /** Neutralise `@handle`, `#channel`, `dm:@peer`, and `task #N` literals so quoted text cannot route attention. */
13268
- function neutralizeAgentRaftRefLiterals(text) {
13269
- 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");
13270
- }
13271
- function renderAgentSearchPreviewText(text) {
13272
- return neutralizeAgentRaftRefLiterals(escapeSearchComponentLiterals(text));
13273
- }
13274
- function renderSearchPreview(content, query) {
13275
- const foundMatch = findSearchMatch(content, query);
13276
- const match = foundMatch ? expandSearchMatchToRefLiteral(content, foundMatch) : null;
13277
- let start = 0;
13278
- let end = Math.min(content.length, PREVIEW_FALLBACK_CHARS);
13279
- if (match) {
13280
- start = Math.max(0, match.start - PREVIEW_BEFORE_CHARS);
13281
- end = Math.min(content.length, match.end + PREVIEW_AFTER_CHARS);
13282
- }
13283
- ({start, end} = trimPreviewWindow(content, start, end));
13284
- const leadingOmit = start > 0 ? "<omit />" : "";
13285
- const trailingOmit = end < content.length ? "<omit />" : "";
13286
- if (!match || match.end <= start || match.start >= end) return `${leadingOmit}${renderAgentSearchPreviewText(content.slice(start, end))}${trailingOmit}`;
13287
- const before = content.slice(start, match.start);
13288
- const matched = content.slice(match.start, match.end);
13289
- const after = content.slice(match.end, end);
13290
- return [
13291
- leadingOmit,
13292
- renderAgentSearchPreviewText(before),
13293
- "<match>",
13294
- renderAgentSearchPreviewText(matched),
13295
- "</match>",
13296
- renderAgentSearchPreviewText(after),
13297
- trailingOmit
13298
- ].join("");
13299
- }
13300
- /** Search results with <match>/<omit /> preview markup. */
13301
- function formatAgentSearchResults(query, data, offset, sort, limit) {
13302
- const trimmedQuery = query.trim();
13303
- const oldestShown = data.results?.length ? data.results[data.results.length - 1]?.createdAt : void 0;
13304
- 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)}`;
13305
- const effectiveLimit = Math.min(limit ?? 20, 50);
13306
- const countEqualsLimit = (data.results?.length ?? 0) === effectiveLimit;
13307
- 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`;
13308
- 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`;
13309
- 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";
13310
- if (!data.results || data.results.length === 0) return `No search results. (${truncation})`;
13311
- const formatted = data.results.map((result) => {
13312
- const ref = `msg:${result.id}`;
13313
- const content = result.content ?? result.snippet ?? "";
13314
- const sender = neutralizeAgentRaftRefLiterals(result.senderName ?? "unknown");
13315
- const senderType = result.senderType ? ` (${result.senderType})` : "";
13316
- const taskProjection = formatAgentTaskCurrentProjection(result.taskCurrentProjection, result.taskNumber, renderAgentSearchPreviewText).trimStart();
13317
- return [
13318
- `<result ref="${ref}">`,
13319
- `Source: ${renderSearchSource(result)}`,
13320
- `Sender: ${sender}${senderType}`,
13321
- `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt) : "-"}`,
13322
- ...taskProjection ? [taskProjection] : [],
13323
- "",
13324
- "<preview>",
13325
- renderSearchPreview(content, trimmedQuery),
13326
- "</preview>",
13327
- "</result>"
13328
- ].join("\n");
13329
- }).join("\n\n");
13330
- const resultLabel = data.results.length === 1 ? "result" : "results";
13331
- const count = `${data.results.length} ${resultLabel} · ${truncation}`;
13332
- return [
13333
- trimmedQuery ? `Search results for: "${trimmedQuery}" (${count})` : `Filtered message results (${count})`,
13334
- "",
13335
- formatted,
13336
- "",
13337
- "If a result may be relevant but its preview is not enough, read the surrounding context for that result before answering."
13338
- ].join("\n");
13339
- }
13340
- //#endregion
13341
- //#region ../shared/src/agentOps/search.ts
13342
- async function searchMessages(client, request) {
13343
- if (!request.query?.trim() && !request.target && !request.sender) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a query, or filter by target or sender." }));
13344
- const result = await client.messages.search({
13345
- ...request.query?.trim() ? { q: request.query.trim() } : {},
13346
- ...request.target ? { channel: request.target } : {},
13347
- ...request.sender ? { sender: request.sender } : {},
13348
- ...request.sort ? { sort: request.sort } : {},
13349
- ...request.before ? { before: request.before } : {},
13350
- ...request.after ? { after: request.after } : {},
13351
- ...request.limit === void 0 ? {} : { limit: String(request.limit) },
13352
- ...request.offset === void 0 ? {} : { offset: String(request.offset) }
13353
- });
13354
- if (!result.ok) return failureFromClientResult(result);
13355
- const data = result.data;
13356
- const hasMore = typeof data.hasMore === "boolean" ? data.hasMore : null;
13357
- const page = {
13358
- query: request.query?.trim() ?? "",
13359
- results: data.results,
13360
- hasMore
13361
- };
13362
- const next = hasMore ? {
13363
- kind: "next_search_page",
13364
- args: {
13365
- ...request,
13366
- offset: (request.offset ?? 0) + data.results.length
13367
- },
13368
- why: "More results exist; page on, or narrow the query."
13369
- } : null;
13370
- return {
13371
- ok: true,
13372
- state: data.results.length > 0 ? "results" : "empty",
13373
- data: page,
13374
- next,
13375
- text: formatAgentSearchResults(page.query, {
13376
- results: data.results,
13377
- ...hasMore === null ? {} : { hasMore }
13378
- }, request.offset, request.sort, request.limit)
13379
- };
13380
- }
13381
- async function resolveMessage(client, request) {
13382
- if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13383
- const result = await client.messages.resolve({ msgId: request.messageId });
13384
- if (!result.ok) return failureFromClientResult(result);
13385
- const message = projectRaftMessage(result.data.message);
13386
- if (!message) return failureOutcome(opError("INVALID_RESPONSE", { message: "The resolved message carries no conversation identity." }));
13387
- return {
13388
- ok: true,
13389
- state: "message",
13390
- data: message,
13391
- next: {
13392
- kind: "read_target",
13393
- command: `raft message read --target "${message.target}" --around ${message.shortId ?? request.messageId}`,
13394
- args: {
13395
- target: message.target,
13396
- around: message.id ?? request.messageId
13397
- },
13398
- why: "Read the surrounding context before acting on one message."
13399
- },
13400
- text: formatAgentMessages([toAgentMessageLike(message.raw)])
13401
- };
13402
- }
13403
- async function reactToMessage(client, request, action = "add") {
13404
- const emoji = request.emoji?.trim();
13405
- 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." }));
13406
- const params = { msgId: request.messageId };
13407
- const result = action === "add" ? await client.messages.addReaction(params, { emoji }) : await client.messages.removeReaction(params, { emoji });
13408
- if (!result.ok) return failureFromClientResult(result);
13409
- const verb = action === "add" ? "added to" : "removed from";
13410
- return {
13411
- ok: true,
13412
- state: action === "add" ? "added" : "removed",
13413
- data: {
13414
- messageId: request.messageId,
13415
- emoji
13416
- },
13417
- next: null,
13418
- text: `Reaction ${emoji} ${verb} message ${request.messageId.slice(0, 8)}.`
13419
- };
13420
- }
13421
- //#endregion
13422
- //#region ../shared/src/agentText/mentions.ts
13423
- function normalizeAgentMentionAction(action) {
13424
- if (action === "notify" || action === "notify_only") return "notify";
13425
- if (action === "add" || action === "invite") return "add";
13426
- return null;
13427
- }
13428
- function formatActionCommands(action) {
13429
- const verbs = action.availableActions.map(normalizeAgentMentionAction).filter((verb) => verb !== null);
13430
- return Array.from(new Set(verbs)).map((verb) => ` ${verb}: raft mention ${verb} ${action.resolutionId}`);
13431
- }
13432
- function formatAuthoredMentionToken(targetHandle) {
13433
- return targetHandle.startsWith("@") ? targetHandle : `@${targetHandle}`;
13434
- }
13435
- 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;
13436
- /** Per-token mention recovery command line; null when the id is not a UUID (fail closed). */
13437
- function formatAgentMentionNotifyRecoveryCommand(resolutionId) {
13438
- return PENDING_MENTION_ACTION_ID_RE.test(resolutionId) ? `raft mention notify ${resolutionId}` : null;
13439
- }
13440
- function toAgentSenderPendingMentionAction(action) {
13441
- return {
13442
- resolutionId: action.resolutionId,
13443
- messageId: action.messageId,
13444
- targetHandle: formatAuthoredMentionToken(action.targetHandle),
13445
- status: "not_queued",
13446
- reason: "not_in_conversation",
13447
- consequence: "This @mention did not notify anyone.",
13448
- expiresAt: action.expiresAt ?? null,
13449
- recoveryCommand: formatAgentMentionNotifyRecoveryCommand(action.resolutionId)
13450
- };
13451
- }
13452
- function toAgentSenderUnresolvedMentionWarning(targetHandle) {
13453
- return {
13454
- targetHandle: formatAuthoredMentionToken(targetHandle),
13455
- status: "not_queued",
13456
- reason: "unknown_or_not_visible",
13457
- consequence: "This @mention did not notify anyone.",
13458
- expiresAt: null,
13459
- recoveryCommand: null
13460
- };
13461
- }
13462
- function formatPendingReason(reason) {
13463
- if (reason === "not_member") return "not in the conversation at send time, so the @mention was not delivered";
13464
- return reason;
13465
- }
13466
- function normalizeAgentPendingMentionActions(data) {
13467
- const value = data;
13468
- 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) => ({
13469
- resolutionId: String(item.resolutionId ?? item.id ?? ""),
13470
- messageId: String(item.messageId ?? ""),
13471
- targetType: String(item.targetType ?? "unknown"),
13472
- targetHandle: String(item.targetHandle ?? ""),
13473
- reason: String(item.reason ?? "Mention target was not notified at send time."),
13474
- availableActions: Array.isArray(item.availableActions) ? item.availableActions.map(String) : [],
13475
- expiresAt: typeof item.expiresAt === "string" ? item.expiresAt : null
13476
- })).filter((item) => item.resolutionId.length > 0);
13477
- }
13478
- function normalizeAgentMentionActionResults(data) {
13479
- const value = data;
13480
- return (Array.isArray(value?.results) ? value.results : Array.isArray(value?.actionResults) ? value.actionResults : []).filter((item) => Boolean(item && typeof item === "object")).map((item) => ({
13481
- resolutionId: String(item.resolutionId ?? item.id ?? ""),
13482
- status: String(item.status ?? "not_found"),
13483
- action: typeof item.action === "string" ? normalizeAgentMentionAction(item.action) : null,
13484
- messageId: typeof item.messageId === "string" ? item.messageId : null,
13485
- channelId: typeof item.channelId === "string" ? item.channelId : null,
13486
- targetType: typeof item.targetType === "string" ? item.targetType : null,
13487
- targetId: typeof item.targetId === "string" ? item.targetId : null,
13488
- targetHandle: typeof item.targetHandle === "string" ? item.targetHandle : null,
13489
- message: typeof item.message === "string" ? item.message : null,
13490
- reason: typeof item.reason === "string" ? item.reason : null,
13491
- dedupedResolutionIds: Array.isArray(item.dedupedResolutionIds) ? item.dedupedResolutionIds.filter((id) => typeof id === "string" && id.length > 0) : []
13492
- })).filter((item) => item.resolutionId.length > 0);
13493
- }
13494
- const PENDING_DEFAULT_LIMIT = 50;
13495
- function pendingPageVerdict(hasMore, limit, shown) {
13496
- const asked = limit === void 0 ? "server default 50" : `--limit ${limit}`;
13497
- 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`;
13498
- if (hasMore === false) return `shown ${shown}, ${asked} — truncated=false · this is the complete list`;
13499
- return `shown ${shown}, ${asked} — truncated=unknown · server did not report has_more, so completeness is NOT asserted`;
13500
- }
13501
- /** Undelivered-mentions partial result (send) or the pending list. */
13502
- function formatAgentPendingMentionActions(actions, opts = {}) {
13503
- const unresolvedMentionHandles = opts.source === "send" ? Array.from(new Set(opts.unresolvedMentionHandles ?? [])) : [];
13504
- const pageNote = opts.source === "pending" ? pendingPageVerdict(opts.hasMore, opts.limit, actions.length) : "";
13505
- if (actions.length === 0 && unresolvedMentionHandles.length === 0) return opts.source === "pending" ? `Pending mention actions\n\nNo pending mention actions. (${pageNote})\n` : "";
13506
- if (opts.source === "send") {
13507
- const lines = [
13508
- "Undelivered mentions — partial result",
13509
- "Message effect: status=queued. Queue acceptance is the only message proof.",
13510
- "Do not rerun `raft message send`; the message is already queued and a retry could duplicate it.",
13511
- "Each row below is bound to the literal @token from your message.",
13512
- "For a literal name rather than a recipient, wrap the @handle in inline or fenced code.",
13513
- ""
13514
- ];
13515
- for (const rawAction of actions) {
13516
- const action = toAgentSenderPendingMentionAction(rawAction);
13517
- lines.push(`- ${action.targetHandle} — status=${action.status}`);
13518
- lines.push(` reason: ${action.reason}`);
13519
- lines.push(` consequence: ${action.consequence}`);
13520
- lines.push(` pending action: ${action.recoveryCommand ? action.resolutionId : "[invalid pending action id]"}`);
13521
- if (action.messageId) lines.push(` message: ${action.messageId}`);
13522
- lines.push(` expires: ${action.expiresAt ?? "unknown"}`);
13523
- if (action.recoveryCommand) {
13524
- lines.push(` recovery: ${action.recoveryCommand}`);
13525
- 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.");
13526
- lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
13527
- } else lines.push(" recovery: unavailable because the pending action id is invalid; inspect `raft mention pending` without resending the message.");
13528
- }
13529
- for (const rawHandle of unresolvedMentionHandles) {
13530
- const warning = toAgentSenderUnresolvedMentionWarning(rawHandle);
13531
- lines.push(`- ${warning.targetHandle} — status=${warning.status}`);
13532
- lines.push(` reason: ${warning.reason}`);
13533
- lines.push(` consequence: ${warning.consequence}`);
13534
- lines.push(" pending action: none; no visible target resolved for this token");
13535
- lines.push(" expires: n/a");
13536
- 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.");
13537
- }
13538
- return `${lines.join("\n")}\n`;
13539
- }
13540
- const lines = [
13541
- "Pending mention actions",
13542
- `(${pageNote})`,
13543
- ""
13544
- ];
13545
- for (const action of actions) {
13546
- const target = action.targetHandle ? `${action.targetHandle} (${action.targetType})` : action.targetType;
13547
- lines.push(`- ${action.resolutionId} — ${target}`);
13548
- if (action.messageId) lines.push(` message: ${action.messageId}`);
13549
- lines.push(` reason: ${formatPendingReason(action.reason)}`);
13550
- if (action.expiresAt) lines.push(` expires: ${action.expiresAt}`);
13551
- const commands = formatActionCommands(action);
13552
- if (commands.length > 0) {
13553
- lines.push(" recovery commands:");
13554
- lines.push(...commands);
13555
- if (commands.some((command) => command.includes(" mention notify "))) lines.push(" note: notify exits nonzero unless the target queue accepts the delivery.");
13556
- }
13557
- }
13558
- return `${lines.join("\n")}\n`;
13559
- }
13560
- function formatMentionActionDetail(result) {
13561
- const detail = result.message ?? result.reason ?? null;
13562
- if (result.status === "dropped") return detail ? `not delivered: ${detail}` : "not delivered";
13563
- return detail;
13564
- }
13565
- /** notify/add action outcome rows. */
13566
- function formatAgentMentionActionResults(action, results) {
13567
- const lines = [`Mention ${action} results`, ""];
13568
- if (results.length === 0) {
13569
- lines.push("No result rows returned.");
13570
- return `${lines.join("\n")}\n`;
13571
- }
13572
- for (const result of results) {
13573
- const target = result.targetHandle ? ` ${result.targetHandle}` : "";
13574
- const detail = formatMentionActionDetail(result);
13575
- const suffix = detail ? ` — ${detail}` : "";
13576
- lines.push(`- ${result.resolutionId}${target}: ${result.status}${suffix}`);
13577
- if (result.dedupedResolutionIds && result.dedupedResolutionIds.length > 1) lines.push(` deduped: ${result.dedupedResolutionIds.join(", ")}`);
13578
- }
13579
- if (action === "notify" && results.some((result) => result.status === "queued" && result.reason !== "already_queued")) lines.push("", `Recipient guidance: ${formatAgentReplyAffordance({ non_member_mention: true })}`);
13580
- return `${lines.join("\n")}\n`;
13581
- }
13582
- function describeDelivery(row) {
13583
- switch (row.outcome) {
13584
- case "delivered": return "delivered";
13585
- case "pending": return "still in flight — do not conclude yet";
13586
- case "unknown": return "UNKNOWN — our instrument could not see this one; re-check, do not conclude";
13587
- case "lost": switch (row.reasonCategory) {
13588
- case "quota": return "LOST — target is rate/quota limited; it will not arrive, re-route or retry later";
13589
- case "runtime_error": return "LOST — target's runtime rejected delivery; re-route";
13590
- case "not_launched": return "LOST — target was not running; re-route or start it";
13591
- case "unclassified": return "LOST — cause is outside the seat-availability set; re-route";
13592
- default: return "LOST — server sent no category for this row (malformed); treat the cause as unknown";
13593
- }
13594
- }
13595
- }
13596
- /** Per-target mention delivery outcome for a message the bound agent sent. */
13597
- function formatAgentSenderMentionDeliveries(messageId, deliveries) {
13598
- if (deliveries.length === 0) return `Message ${messageId}\n\nNo mention deliveries recorded for this message.\n`;
13599
- const lines = [`Message ${messageId} — mention delivery per target`, ""];
13600
- for (const row of deliveries) lines.push(` ${row.targetHandle || "(unknown target)"}: ${describeDelivery(row)}`);
13601
- return `${lines.join("\n")}\n`;
13602
- }
13603
- //#endregion
13604
- //#region ../shared/src/agentOps/mentions.ts
13605
- async function pendingMentionActions(client, request = {}) {
13606
- const result = await client.mentions.pendingActions(request.limit === void 0 ? {} : { limit: String(request.limit) });
13607
- if (!result.ok) return failureFromClientResult(result);
13608
- const actions = normalizeAgentPendingMentionActions(result.data);
13609
- const hasMore = typeof result.data.has_more === "boolean" ? result.data.has_more : null;
13610
- const first = actions.find((a) => a.availableActions.length > 0);
13611
- const next = first ? {
13612
- kind: "resolve_mention",
13613
- command: `raft mention notify ${first.resolutionId}`,
13614
- args: {
13615
- action: "notify",
13616
- resolutionIds: [first.resolutionId]
13617
- },
13618
- why: "This @mention reached nobody at send time; notify the target (or add them) so the message is seen."
13619
- } : null;
13620
- return {
13621
- ok: true,
13622
- state: actions.length > 0 ? "pending" : "empty",
13623
- data: {
13624
- actions,
13625
- hasMore,
13626
- limit: request.limit
13627
- },
13628
- next,
13629
- text: formatAgentPendingMentionActions(actions, {
13630
- source: "pending",
13631
- ...hasMore === null ? {} : { hasMore },
13632
- limit: request.limit
13633
- })
13634
- };
13635
- }
13636
- async function executeMentionAction(client, request) {
13637
- const ids = (request.resolutionIds ?? []).map((id) => id.trim()).filter(Boolean);
13638
- 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." }));
13639
- const result = await client.mentions.executeAction({
13640
- action: request.action,
13641
- resolutionIds: ids
13642
- });
13643
- if (!result.ok) return failureFromClientResult(result);
13644
- const results = normalizeAgentMentionActionResults(result.data);
13645
- return {
13646
- ok: true,
13647
- state: "executed",
13648
- data: {
13649
- action: request.action,
13650
- results
13651
- },
13652
- next: null,
13653
- text: formatAgentMentionActionResults(request.action, results)
13654
- };
13655
- }
13656
- async function senderMentionDeliveries(client, request) {
13657
- if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13658
- const result = await client.mentions.senderDeliveries({ messageId: request.messageId });
13659
- if (!result.ok) return failureFromClientResult(result);
13660
- const data = result.data;
13661
- return {
13662
- ok: true,
13663
- state: data.deliveries.length > 0 ? "deliveries" : "empty",
13664
- data,
13665
- next: null,
13666
- text: formatAgentSenderMentionDeliveries(data.messageId, data.deliveries)
13667
- };
13668
- }
13669
- //#endregion
13670
- //#region ../shared/src/agentText/knowledge.ts
13671
- function formatMatchReason(result) {
13672
- const parts = [];
13673
- for (const { term, matched } of result.correctedTerms ?? []) parts.push(`${term} → ${matched} (typo)`);
13674
- for (const { from, to } of result.expandedTerms ?? []) parts.push(`${from} → ${to} (concept)`);
13675
- return parts.length > 0 ? ` matched: ${parts.join(", ")}` : "";
13676
- }
13677
- function formatAgentKnowledgeSearchResults(results) {
13678
- return results.map((result, index) => {
13679
- const body = result.firstScreen.trim().split(/\r?\n/).filter(Boolean).map((line) => ` ${line}`).join("\n");
13680
- const reason = formatMatchReason(result);
13681
- return `${index + 1}. ${result.slug} — ${result.title}${reason ? `\n${reason}` : ""}${body ? `\n${body}` : ""}`;
13682
- }).join("\n\n") + "\n";
13683
- }
13684
- function formatAgentKnowledgeStdout(content) {
13685
- return content.endsWith("\n") ? content : `${content}\n`;
13686
- }
13687
- //#endregion
13688
- //#region ../shared/src/agentOps/manual.ts
13689
- function requireContext(context) {
13690
- if (!context?.intent?.trim() || !context?.reason?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Manual calls need a short `intent` and `reason`." }));
13691
- return null;
13692
- }
13693
- async function getManualTopic(client, request) {
13694
- const invalid = requireContext(request);
13695
- if (invalid) return invalid;
13696
- if (!request.topic?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A topic id is required." }));
13697
- const result = await client.knowledge.get({
13698
- topic: request.topic.trim(),
13699
- intent: request.intent.trim(),
13700
- reason: request.reason.trim()
13701
- });
13702
- if (!result.ok) return failureFromClientResult(result);
13703
- return {
13704
- ok: true,
13705
- state: "topic",
13706
- data: result.data,
13707
- next: null,
13708
- text: formatAgentKnowledgeStdout(result.data.content)
13709
- };
13710
- }
13711
- async function searchManual(client, request) {
13712
- const invalid = requireContext(request);
13713
- if (invalid) return invalid;
13714
- if (!request.query?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Search keywords are required." }));
13715
- const result = await client.knowledge.search({
13716
- query: request.query.trim(),
13717
- ...request.scope ? { scope: request.scope } : {},
13718
- intent: request.intent.trim(),
13719
- reason: request.reason.trim()
13720
- });
13721
- if (!result.ok) return failureFromClientResult(result);
13722
- const data = result.data;
13723
- const results = data.results;
13724
- const first = results[0];
13725
- const next = first ? {
13726
- kind: "read_manual_topic",
13727
- command: `raft manual get ${first.slug} --intent "…" --reason "…"`,
13728
- args: { topic: first.slug },
13729
- why: "Open the best-matching topic."
13730
- } : null;
13731
- return {
13732
- ok: true,
13733
- state: results.length > 0 ? "results" : "empty",
13734
- data,
13735
- next,
13736
- text: results.length > 0 ? formatAgentKnowledgeSearchResults(results) : "No Manual topics matched. Retry with different keywords, keeping your intent and reason.\n"
13737
- };
13738
- }
13739
- //#endregion
13740
- //#region ../shared/src/agentOps/state.ts
13741
- const RAFT_STATE_SCHEMA = "raft-sdk-state.v1";
13742
- const RAFT_STATE_CONTINUATIONS_PER_TARGET = 3;
13743
- const RAFT_STATE_CONTINUATIONS_TOTAL = 20;
13744
- function isNullableCursor(value) {
13745
- return value === null || typeof value === "number" && Number.isInteger(value) && value >= 0;
13746
- }
13747
- /** Validate a loaded value; anything unrecognised is treated as an empty store (safe: see file header). */
13748
- function parseRaftState(value) {
13749
- if (!value || typeof value !== "object") return null;
13750
- const v = value;
13751
- if (v.schema !== "raft-sdk-state.v1") return null;
13752
- if (typeof v.version !== "number" || !Number.isInteger(v.version) || v.version < 0) return null;
13753
- if (!isNullableCursor(v.cursor ?? null) || !isNullableCursor(v.pendingCursor ?? null)) return null;
13754
- const frontier = v.frontier;
13755
- const continuations = Array.isArray(v.continuations) ? v.continuations.filter((c) => {
13756
- const r = c;
13757
- return Boolean(r) && typeof r.target === "string" && typeof r.idempotencyKey === "string" && typeof r.contentHash === "string" && typeof r.heldAt === "string";
13758
- }) : [];
13759
- return {
13760
- schema: RAFT_STATE_SCHEMA,
13761
- version: v.version,
13762
- cursor: v.cursor ?? null,
13763
- pendingCursor: v.pendingCursor ?? null,
13764
- frontier: frontier && frontier.version === 1 ? frontier : {
13765
- version: 1,
13766
- targets: {},
13767
- aliases: {}
13768
- },
13769
- continuations
13770
- };
13771
- }
13772
- /** Hex SHA-256 identifying one logical message (WebCrypto; Workers-safe). */
13773
- async function hashRaftSendContent(target, content, attachmentIds = []) {
13774
- const bytes = new TextEncoder().encode(`${target}\n${[...attachmentIds].sort().join(",")}\n${content}`);
13775
- return [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");
13776
- }
13777
- /**
13778
- * One client's view of the persisted state: loads once, holds the working
13779
- * copy, saves on request. Also used without a store (memory only), so the
13780
- * pending/committed cursor flow behaves the same with or without persistence.
13781
- */
13782
- var RaftStateSession = class {
13783
- store;
13784
- onError;
13785
- frontier;
13786
- cursor = null;
13787
- pendingCursor = null;
13788
- continuations = [];
13789
- loadedVersion = void 0;
13790
- loading = null;
13791
- dirty = false;
13792
- constructor(store, frontier, onError) {
13793
- this.store = store;
13794
- this.onError = onError;
13795
- this.frontier = frontier;
13796
- }
13797
- get persistent() {
13798
- return this.store !== void 0;
13799
- }
13800
- /** The version loaded from (or last saved to) the store; `undefined` before the first save of an empty store. */
13801
- get version() {
13802
- return this.loadedVersion;
13803
- }
13804
- /** Load once. A failed or unreadable load starts from an empty state (reported, not thrown). */
13805
- ensureLoaded() {
13806
- if (!this.store) return Promise.resolve();
13807
- this.loading ??= (async () => {
13808
- let raw = null;
13809
- try {
13810
- raw = await this.store.load();
13811
- } catch (error) {
13812
- this.onError?.(error, {
13813
- phase: "load",
13814
- version: void 0
13815
- });
13816
- return;
13817
- }
13818
- const state = parseRaftState(raw);
13819
- if (!state) return;
13820
- this.loadedVersion = state.version;
13821
- this.cursor = state.cursor;
13822
- this.pendingCursor = state.pendingCursor;
13823
- this.frontier.absorb(state.frontier);
13824
- this.continuations = state.continuations ?? [];
13825
- })();
13826
- return this.loading;
13827
- }
13828
- markDirty() {
13829
- this.dirty = true;
13830
- }
13831
- /** Record the cursor of a batch just returned. Acknowledges nothing. */
13832
- setPending(cursor) {
13833
- if (cursor === null || cursor === this.pendingCursor) return;
13834
- this.pendingCursor = cursor;
13835
- this.dirty = true;
13836
- }
13837
- /**
13838
- * Promote a cursor to committed. With no argument, commits `pendingCursor`.
13839
- * Returns the committed cursor, or null when there was nothing to commit.
13840
- * Never moves the committed cursor backwards.
13841
- */
13842
- commit(cursor) {
13843
- const next = cursor === void 0 ? this.pendingCursor : cursor;
13844
- if (next === null || next === void 0) return null;
13845
- if (this.cursor === null || next > this.cursor) this.cursor = next;
13846
- if (this.pendingCursor !== null && this.pendingCursor <= this.cursor) this.pendingCursor = null;
13847
- this.dirty = true;
13848
- return this.cursor;
13849
- }
13850
- findContinuation(target, contentHash) {
13851
- return this.continuations.find((c) => c.target === target && c.contentHash === contentHash);
13852
- }
13853
- rememberContinuation(entry) {
13854
- this.continuations = this.continuations.filter((c) => !(c.target === entry.target && c.contentHash === entry.contentHash));
13855
- this.continuations.push(entry);
13856
- const perTarget = this.continuations.filter((c) => c.target === entry.target);
13857
- for (const drop of perTarget.slice(0, Math.max(0, perTarget.length - 3))) this.continuations.splice(this.continuations.indexOf(drop), 1);
13858
- if (this.continuations.length > 20) this.continuations.splice(0, this.continuations.length - 20);
13859
- this.dirty = true;
13860
- }
13861
- forgetContinuation(target, contentHash) {
13862
- const before = this.continuations.length;
13863
- this.continuations = this.continuations.filter((c) => !(c.target === target && c.contentHash === contentHash));
13864
- if (this.continuations.length !== before) this.dirty = true;
13865
- }
13866
- snapshot(nextVersion = (this.loadedVersion ?? 0) + 1) {
13867
- return {
13868
- schema: RAFT_STATE_SCHEMA,
13869
- version: nextVersion,
13870
- cursor: this.cursor,
13871
- pendingCursor: this.pendingCursor,
13872
- frontier: this.frontier.snapshot(),
13873
- continuations: [...this.continuations]
13874
- };
13875
- }
13876
- /**
13877
- * Save if anything changed (or `force`). One attempt; a failure is reported
13878
- * and swallowed. Returns whether the save succeeded (true when nothing to save).
13879
- */
13880
- async save(options = {}) {
13881
- if (!this.store) return true;
13882
- if (!this.dirty && !options.force) return true;
13883
- const expectedVersion = this.loadedVersion;
13884
- const state = this.snapshot();
13885
- try {
13886
- await this.store.save(state, { expectedVersion });
13887
- } catch (error) {
13888
- this.onError?.(error, {
13889
- phase: "save",
13890
- version: expectedVersion
13891
- });
13892
- return false;
13893
- }
13894
- this.loadedVersion = state.version;
13895
- this.dirty = false;
13896
- return true;
13897
- }
13898
- };
13899
- //#endregion
13900
- //#region ../shared/src/agentOps/actions.ts
13901
- /** Text is the CLI's `raft action prepare` output. */
13902
- function formatAgentActionCardPosted(target, messageId) {
13903
- const shortId = messageId ? messageId.slice(0, 8) : null;
13904
- return shortId ? `Action card posted to ${target} as message ${messageId} (short ${shortId}). The human can click the action verb to commit.\n` : `Action card posted to ${target}.\n`;
13905
- }
13906
- async function prepareActionCard(client, request) {
13907
- if (!request?.target?.trim() || !request.action) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and an action are required to prepare a card." }));
13908
- const result = await client.actions.prepare(request);
13909
- if (!result.ok) return failureFromClientResult(result);
13910
- const card = {
13911
- target: request.target,
13912
- messageId: result.data.messageId
13913
- };
13914
- return {
13915
- ok: true,
13916
- state: "prepared",
13917
- data: card,
13918
- next: {
13919
- kind: "await_confirmation",
13920
- command: `raft message read --target "${request.target}" --around ${card.messageId.slice(0, 8)}`,
13921
- args: {
13922
- target: request.target,
13923
- messageId: card.messageId
13924
- },
13925
- why: "A human must click the card to commit it; its outcome arrives in your inbox."
13926
- },
13927
- text: formatAgentActionCardPosted(request.target, card.messageId)
13928
- };
13929
- }
13930
- //#endregion
13931
- //#region src/raft.ts
13932
- function createRaft(options) {
13933
- const serverUrl = requireServerUrl(options.serverUrl);
13934
- const authorization = `Bearer ${requireAgentCredential(options.credential)}`;
13935
- const frontier = SeenFrontier.fromSnapshot(options.frontier);
13936
- const session = new RaftStateSession(options.state, frontier, options.onStateSaveError);
13937
- /** Load before, run, then save if the operation succeeded and changed the state. */
13938
- const withState = async (run) => {
13939
- await session.ensureLoaded();
13940
- const outcome = await run();
13941
- if (outcome.ok) await session.save();
13942
- return outcome;
13943
- };
13944
- const api = createRaftRouteClient({
13945
- serverUrl,
13946
- fetch: options.fetch,
13947
- headers: options.headers,
13948
- authorization,
13949
- readAttempts: options.retry?.attempts,
13950
- beforeRequest: options.throttle?.beforeRequest
13951
- });
13952
- const routes = raftRoutesFromClient(api);
13953
- const inboxApi = createAgentApiClient({ fetch: {
13954
- baseUrl: serverUrl,
13955
- fetch: (input, init) => (options.fetch ?? fetch)(input, {
13956
- ...init,
13957
- cache: "no-store",
13958
- redirect: "error"
13959
- }),
13960
- headers: Object.fromEntries(new Headers(options.headers)),
13961
- retry: { attempts: 1 },
13962
- throttle: options.throttle,
13963
- auth: { authorization }
13964
- } });
13965
- /**
13966
- * Send through the state session: a resend of the same logical message
13967
- * (same target, content, attachments) reuses the held send's idempotency key;
13968
- * a hold is remembered; a successful send clears it.
13969
- */
13970
- const sendWithState = (request) => withState(async () => {
13971
- const contentHash = await hashRaftSendContent(request.target, request.content ?? "", request.attachmentIds ?? []);
13972
- const pending = request.idempotencyKey ? void 0 : session.findContinuation(request.target, contentHash);
13973
- const outcome = await sendMessage(api, pending ? {
13974
- ...request,
13975
- idempotencyKey: pending.idempotencyKey
13976
- } : request, frontier);
13977
- if (outcome.ok && outcome.state === "held") session.rememberContinuation({
13978
- target: request.target,
13979
- idempotencyKey: outcome.data.idempotencyKey,
13980
- contentHash,
13981
- heldAt: (/* @__PURE__ */ new Date()).toISOString()
13982
- });
13983
- else if (outcome.ok && outcome.state === "sent") session.forgetContinuation(request.target, contentHash);
13984
- return outcome;
13985
- });
13986
- return {
13987
- identity: { whoami: () => getRaftContext(api) },
13988
- wake: {
13989
- verifyNotice: (input) => verifyInboxNotice(input),
13990
- webhook: {
13991
- status: () => webhookStatus(api),
13992
- register: (request) => registerWebhook(api, request),
13993
- unregister: () => unregisterWebhook(api)
13994
- }
13995
- },
13996
- inbox: {
13997
- check: (request = {}) => withState(async () => {
13998
- const since = request.since ?? session.cursor ?? void 0;
13999
- const outcome = await checkInbox(inboxApi, {
14000
- ...request,
14001
- ...since === void 0 ? {} : { since }
14002
- }, frontier);
14003
- if (outcome.ok) {
14004
- session.markDirty();
14005
- if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
14006
- if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
14007
- }
14008
- return outcome;
14009
- }),
14010
- commit: async (target) => {
14011
- await session.ensureLoaded();
14012
- const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
14013
- return {
14014
- cursor,
14015
- saved: cursor === null ? true : await session.save()
14016
- };
14017
- },
14018
- drain: (request = {}) => (async function* () {
14019
- await session.ensureLoaded();
14020
- const since = request.since ?? session.cursor ?? void 0;
14021
- return yield* drainInbox(inboxApi, {
14022
- ...request,
14023
- ...since === void 0 ? {} : { since }
14024
- }, frontier, async (sent, batch) => {
14025
- if (sent !== null) session.commit(sent);
14026
- if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
14027
- session.markDirty();
14028
- await session.save();
14029
- });
14030
- })(),
14031
- list: (request) => listInbox(api, request)
14032
- },
14033
- messages: {
14034
- read: (request) => withState(async () => {
14035
- const outcome = await readHistory(api, request, frontier);
14036
- if (outcome.ok) session.markDirty();
14037
- return outcome;
14038
- }),
14039
- send: (request) => sendWithState(request),
14040
- reply: (message, request) => sendWithState({
14041
- ...request,
14042
- target: message.target
14043
- }),
14044
- search: (request) => searchMessages(api, request),
14045
- resolve: (request) => resolveMessage(api, request),
14046
- react: (request) => reactToMessage(api, request, "add"),
14047
- unreact: (request) => reactToMessage(api, request, "remove")
14048
- },
14049
- attachments: {
14050
- upload: (request) => uploadAttachment(api, {
14051
- serverUrl,
14052
- fetch: options.fetch ?? fetch,
14053
- headers: Object.fromEntries(new Headers(options.headers)),
14054
- authorization
14055
- }, request),
14056
- download: (request) => downloadAttachment(api, request),
14057
- comments: (request) => attachmentComments(api, request)
14058
- },
14059
- mentions: {
14060
- pending: (request) => pendingMentionActions(api, request),
14061
- execute: (request) => executeMentionAction(api, request),
14062
- deliveries: (request) => senderMentionDeliveries(api, request)
14063
- },
14064
- actions: { prepare: (request) => prepareActionCard(api, request) },
14065
- manual: {
14066
- get: (request) => getManualTopic(api, request),
14067
- search: (request) => searchManual(api, request)
14068
- },
14069
- tasks: {
14070
- claim: (request) => claimTasks(api, request),
14071
- list: (request) => listTasks(api, request),
14072
- create: (request) => createTasks(api, request),
14073
- unclaim: (request) => unclaimTask(api, request),
14074
- assign: (request) => assignTask(api, request),
14075
- updateStatus: (request) => updateTaskStatus(api, request),
14076
- amend: (request) => amendTask(api, request),
14077
- history: (request) => taskHistory(api, request),
14078
- convert: (request) => convertMessageToTask(api, request),
14079
- delete: (request) => deleteTask(api, request)
14080
- },
14081
- channels: {
14082
- join: (request) => joinChannel(api, request),
14083
- leave: (request) => leaveChannel(api, request),
14084
- mute: (request) => muteChannel(api, request),
14085
- unmute: (request) => unmuteChannel(api, request),
14086
- members: (request) => channelMembers(api, request)
14087
- },
14088
- threads: {
14089
- list: () => listThreads(api),
14090
- unfollow: (request) => unfollowThread(api, request)
14091
- },
14092
- server: { info: (request) => serverInfo(api, request) },
14093
- profile: {
14094
- show: (request) => showProfile(api, request),
14095
- update: (request) => updateProfile(api, request)
11810
+ messages: {
11811
+ read: (request) => readHistory(routes, request, frontier),
11812
+ send: (request) => sendMessage(routes, request, frontier),
11813
+ reply: (message, request) => replyTo(routes, message, request, frontier)
14096
11814
  },
11815
+ tasks: { claim: (request) => claimTasks(routes, request) },
14097
11816
  frontier,
14098
- state: {
14099
- save: async () => {
14100
- await session.ensureLoaded();
14101
- session.markDirty();
14102
- return session.save();
14103
- },
14104
- load: () => session.ensureLoaded(),
14105
- snapshot: () => session.snapshot(session.version ?? 0)
14106
- },
14107
11817
  routes
14108
11818
  };
14109
11819
  }
14110
11820
  //#endregion
14111
- 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 };
11821
+ export { RAFT_INBOX_NOTICE_SCHEMA, RAFT_NOTICE_DELIVERY_ID_HEADER, RAFT_NOTICE_SIGNATURE_HEADER, RaftCredentialError, RaftSdkConfigurationError, SeenFrontier, bootstrapRaftCredential, createFileCredentialStore, createRaft, createRaftClient, createRaftClientFromStore, createRaftRoutes, describeRaftRoute, joinRaftChannelByTarget, listRaftRoutes, parseRaftRegularChannelTarget, verifyInboxNotice };