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