Compare commits
5 Commits
feat/triag
...
6fe06f55dd
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fe06f55dd | |||
| a15dc880af | |||
| 5dcbd99c28 | |||
| cd36d1b9e2 | |||
| 9c910f082b |
28
index.ts
28
index.ts
@@ -13,11 +13,17 @@ import { registerFabricTools } from './src/tools.js';
|
|||||||
import { FabricClient } from './src/fabric-client.js';
|
import { FabricClient } from './src/fabric-client.js';
|
||||||
import { IdentityRegistry } from './src/identity.js';
|
import { IdentityRegistry } from './src/identity.js';
|
||||||
import { syncFabricCommands } from './src/command-sync.js';
|
import { syncFabricCommands } from './src/command-sync.js';
|
||||||
|
import { PresenceSync } from './src/presence-sync.js';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
|
|
||||||
let runtimeRef: unknown = null;
|
let runtimeRef: unknown = null;
|
||||||
let inbound: FabricInbound | null = null;
|
let inbound: FabricInbound | null = null;
|
||||||
|
let presence: PresenceSync | null = null;
|
||||||
|
// Periodic re-harvest of presence accounts so newly-connected agents
|
||||||
|
// (registered through tool-based identity flow AFTER initial start)
|
||||||
|
// get picked up. Cleared on gateway_stop.
|
||||||
|
let presenceRefreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
export { fabricChannelPlugin } from './src/channel.js';
|
export { fabricChannelPlugin } from './src/channel.js';
|
||||||
|
|
||||||
@@ -82,7 +88,24 @@ export default defineChannelPluginEntry({
|
|||||||
api.logger,
|
api.logger,
|
||||||
accounts,
|
accounts,
|
||||||
);
|
);
|
||||||
void inbound.start();
|
// start() resolves once all accounts have attempted login; per-
|
||||||
|
// agent failures are logged but don't reject. Once it resolves we
|
||||||
|
// can harvest the presence accounts (those that DID log in have
|
||||||
|
// their fabricUserId + first guild endpoint populated).
|
||||||
|
void inbound.start().then(() => {
|
||||||
|
if (!inbound) return;
|
||||||
|
presence = new PresenceSync(api.logger);
|
||||||
|
presence.setAccounts(inbound.getPresenceAccounts());
|
||||||
|
presence.start();
|
||||||
|
api.logger.info(`fabric: presence-sync started for ${inbound.getPresenceAccounts().length} account(s)`);
|
||||||
|
|
||||||
|
// Re-harvest every 5 min: catches agents added via tool-based
|
||||||
|
// identity provisioning after gateway_start (recruitment flow).
|
||||||
|
// setAccounts is idempotent — duplicates collapse on agentId.
|
||||||
|
presenceRefreshTimer = setInterval(() => {
|
||||||
|
if (inbound && presence) presence.setAccounts(inbound.getPresenceAccounts());
|
||||||
|
}, 5 * 60_000);
|
||||||
|
});
|
||||||
api.logger.info(`fabric: inbound started for ${accounts.length} account(s)`);
|
api.logger.info(`fabric: inbound started for ${accounts.length} account(s)`);
|
||||||
void syncFabricCommands(client, cfg, accounts, api.logger);
|
void syncFabricCommands(client, cfg, accounts, api.logger);
|
||||||
});
|
});
|
||||||
@@ -93,6 +116,9 @@ export default defineChannelPluginEntry({
|
|||||||
// BEFORE deliver()). gateway_stop only flushes any leftover buffer.
|
// BEFORE deliver()). gateway_stop only flushes any leftover buffer.
|
||||||
api.on('gateway_stop', () => {
|
api.on('gateway_stop', () => {
|
||||||
void flushAllFabric();
|
void flushAllFabric();
|
||||||
|
if (presenceRefreshTimer) { clearInterval(presenceRefreshTimer); presenceRefreshTimer = null; }
|
||||||
|
presence?.stop();
|
||||||
|
presence = null;
|
||||||
inbound?.stop();
|
inbound?.stop();
|
||||||
inbound = null;
|
inbound = null;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,12 @@
|
|||||||
"create-work-channel",
|
"create-work-channel",
|
||||||
"create-report-channel",
|
"create-report-channel",
|
||||||
"create-discussion-channel",
|
"create-discussion-channel",
|
||||||
"discussion-complete"
|
"discussion-complete",
|
||||||
|
"fabric-canvas",
|
||||||
|
"fabric-channel",
|
||||||
|
"fabric-send-message",
|
||||||
|
"fabric-channel-list",
|
||||||
|
"fabric-message-history"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"configSchema": {
|
"configSchema": {
|
||||||
|
|||||||
@@ -190,6 +190,76 @@ export class FabricClient {
|
|||||||
removeCanvas(endpoint: string, token: string, channelId: string): Promise<unknown> {
|
removeCanvas(endpoint: string, token: string, channelId: string): Promise<unknown> {
|
||||||
return this.req('DELETE', this.canvasUrl(endpoint, channelId), token);
|
return this.req('DELETE', this.canvasUrl(endpoint, channelId), token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- channel discovery + message read (used by the agent-facing
|
||||||
|
// fabric-channel-list / fabric-message-history tools) ----
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List channels in a guild visible to the calling user. Backend
|
||||||
|
* filters to public + channels the user is a member of.
|
||||||
|
*/
|
||||||
|
listChannels(
|
||||||
|
guildEndpoint: string,
|
||||||
|
guildToken: string,
|
||||||
|
guildNodeId: string,
|
||||||
|
): Promise<Array<{
|
||||||
|
id: string;
|
||||||
|
guildId: string;
|
||||||
|
name: string;
|
||||||
|
xType: string;
|
||||||
|
kind: string;
|
||||||
|
isPublic: boolean;
|
||||||
|
closed: boolean;
|
||||||
|
lastSeq: number;
|
||||||
|
createdAt: string;
|
||||||
|
}>> {
|
||||||
|
return this.req(
|
||||||
|
'GET',
|
||||||
|
`${guildEndpoint}/api/channels?guildId=${encodeURIComponent(guildNodeId)}`,
|
||||||
|
guildToken,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page through a channel's message history by `seq`.
|
||||||
|
*
|
||||||
|
* Backend defaults: 50 / call, max 200. The `seq` field starts at 1
|
||||||
|
* per channel; pass `seqFrom=channel.lastSeq - N + 1` to get the
|
||||||
|
* tail. Page metadata in the response describes what to ask next.
|
||||||
|
*/
|
||||||
|
listMessages(
|
||||||
|
guildEndpoint: string,
|
||||||
|
guildToken: string,
|
||||||
|
channelId: string,
|
||||||
|
opts: { seqFrom?: number; seqTo?: number; limit?: number } = {},
|
||||||
|
): Promise<{
|
||||||
|
items: Array<{
|
||||||
|
messageId: string;
|
||||||
|
seq: number;
|
||||||
|
content: string;
|
||||||
|
authorUserId: string;
|
||||||
|
createdAt: string;
|
||||||
|
editedAt: string | null;
|
||||||
|
deletedAt: string | null;
|
||||||
|
isDeleted: boolean;
|
||||||
|
}>;
|
||||||
|
page: {
|
||||||
|
seqFrom: number;
|
||||||
|
seqTo: number;
|
||||||
|
limit: number;
|
||||||
|
returned: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
nextExpectedSeq: number;
|
||||||
|
highestCommittedSeq: number;
|
||||||
|
};
|
||||||
|
}> {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (opts.seqFrom !== undefined) qs.set('seq_from', String(opts.seqFrom));
|
||||||
|
if (opts.seqTo !== undefined) qs.set('seq_to', String(opts.seqTo));
|
||||||
|
if (opts.limit !== undefined) qs.set('limit', String(opts.limit));
|
||||||
|
const url = `${guildEndpoint}/api/channels/${channelId}/messages` + (qs.toString() ? `?${qs}` : '');
|
||||||
|
return this.req('GET', url, guildToken);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CanvasFormat = 'md' | 'html' | 'text';
|
export type CanvasFormat = 'md' | 'html' | 'text';
|
||||||
|
|||||||
@@ -263,8 +263,52 @@ export class FabricInbound {
|
|||||||
this.sockets = [];
|
this.sockets = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-account metadata harvested during `start()` — used by
|
||||||
|
* PresenceSync to know where to push each agent's HF status.
|
||||||
|
*
|
||||||
|
* `fabricUserId` is filled from `session.user.id` after agent-login.
|
||||||
|
* `guildBaseUrl` is the FIRST guild the agent is connected to (multi-
|
||||||
|
* guild presence push is a future concern; for sim/prod-v1 each agent
|
||||||
|
* is in one guild).
|
||||||
|
*
|
||||||
|
* Returns ONLY agents that successfully connected — failed-login
|
||||||
|
* agents have no fabricUserId yet and are excluded.
|
||||||
|
*/
|
||||||
|
getPresenceAccounts(): Array<{
|
||||||
|
agentId: string;
|
||||||
|
fabricUserId: string;
|
||||||
|
guildBaseUrl: string;
|
||||||
|
fabricApiKey: string;
|
||||||
|
}> {
|
||||||
|
const out: Array<{ agentId: string; fabricUserId: string; guildBaseUrl: string; fabricApiKey: string }> = [];
|
||||||
|
for (const entry of this.identity.list()) {
|
||||||
|
if (!entry.fabricUserId) continue;
|
||||||
|
const presenceGuildUrl = this.firstGuildEndpointByAgent.get(entry.agentId);
|
||||||
|
if (!presenceGuildUrl) continue;
|
||||||
|
out.push({
|
||||||
|
agentId: entry.agentId,
|
||||||
|
fabricUserId: entry.fabricUserId,
|
||||||
|
guildBaseUrl: presenceGuildUrl,
|
||||||
|
fabricApiKey: entry.fabricApiKey,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filled by connectAgent for each (agent, guild). Tracks ONLY the first
|
||||||
|
// guild per agent (used as the presence-push target).
|
||||||
|
private firstGuildEndpointByAgent = new Map<string, string>();
|
||||||
|
|
||||||
private async connectAgent(agentId: string, session: FabricSession): Promise<void> {
|
private async connectAgent(agentId: string, session: FabricSession): Promise<void> {
|
||||||
const selfUserId = session.user.id;
|
const selfUserId = session.user.id;
|
||||||
|
// First-guild capture for presence-sync push target. session.guilds is
|
||||||
|
// already in priority order from Center; we take the first one with a
|
||||||
|
// valid endpoint and stop. Multi-guild presence is a future concern.
|
||||||
|
if (!this.firstGuildEndpointByAgent.has(agentId)) {
|
||||||
|
const firstGuild = session.guilds.find((g) => typeof g.endpoint === 'string' && g.endpoint.length > 0);
|
||||||
|
if (firstGuild) this.firstGuildEndpointByAgent.set(agentId, firstGuild.endpoint);
|
||||||
|
}
|
||||||
for (const g of session.guilds) {
|
for (const g of session.guilds) {
|
||||||
const tok = session.guildAccessTokens.find((t) => t.guildNodeId === g.nodeId)?.token;
|
const tok = session.guildAccessTokens.find((t) => t.guildNodeId === g.nodeId)?.token;
|
||||||
if (!tok) continue;
|
if (!tok) continue;
|
||||||
|
|||||||
92
src/presence-sync.ts
Normal file
92
src/presence-sync.ts
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
/**
|
||||||
|
* presence-sync — read each connected agent's HF status (via the
|
||||||
|
* cross-plugin `globalThis.__hfAgentStatus.get(agentId)` exposed by
|
||||||
|
* HarborForge.OpenclawPlugin) and push diffs to Fabric.Backend.Guild
|
||||||
|
* `PUT /agents/:userId/presence` so the backend can apply busy-discard
|
||||||
|
* on `announce`-type channel deliveries.
|
||||||
|
*
|
||||||
|
* Push model: we only PUT when an agent's status actually changes
|
||||||
|
* (since the last push). The HF-side accessor has its own TTL cache
|
||||||
|
* to absorb the every-30s polling.
|
||||||
|
*
|
||||||
|
* If HF plugin isn't loaded (`__hfAgentStatus` undefined), the loop
|
||||||
|
* is a no-op — Fabric backend defaults presence to 'unknown' which is
|
||||||
|
* treated as not-busy. Announce-channel delivery still works; busy
|
||||||
|
* filtering simply doesn't kick in.
|
||||||
|
*/
|
||||||
|
|
||||||
|
type HfStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline';
|
||||||
|
type Bridge = { get(agentId: string): Promise<HfStatus | undefined> };
|
||||||
|
type Logger = { info: (m: string) => void; warn: (m: string) => void };
|
||||||
|
|
||||||
|
export interface PresenceSyncAccount {
|
||||||
|
agentId: string;
|
||||||
|
fabricUserId: string; // the agent's Fabric Center user id (UUID)
|
||||||
|
guildBaseUrl: string; // e.g. https://fabric.hangman-lab.top/guild/<id>
|
||||||
|
fabricApiKey: string; // existing per-account key
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PresenceSync {
|
||||||
|
private timer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
private readonly lastStatus = new Map<string, HfStatus>(); // by agentId
|
||||||
|
private readonly accounts = new Map<string, PresenceSyncAccount>();
|
||||||
|
|
||||||
|
constructor(private readonly logger: Logger) {}
|
||||||
|
|
||||||
|
setAccounts(accounts: PresenceSyncAccount[]): void {
|
||||||
|
this.accounts.clear();
|
||||||
|
for (const a of accounts) this.accounts.set(a.agentId, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
start(intervalMs = 30_000): void {
|
||||||
|
if (this.timer) return;
|
||||||
|
this.timer = setInterval(() => {
|
||||||
|
this.tick().catch((err) => this.logger.warn(`fabric: presence-sync error: ${String(err)}`));
|
||||||
|
}, intervalMs);
|
||||||
|
// run once immediately so initial state lands fast
|
||||||
|
void this.tick();
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.timer) {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async tick(): Promise<void> {
|
||||||
|
const bridge = (globalThis as Record<string, unknown>)['__hfAgentStatus'] as Bridge | undefined;
|
||||||
|
if (!bridge || typeof bridge.get !== 'function') return; // HF plugin not loaded — skip
|
||||||
|
|
||||||
|
for (const [agentId, acct] of this.accounts) {
|
||||||
|
let status: HfStatus | undefined;
|
||||||
|
try {
|
||||||
|
status = await bridge.get(agentId);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!status) continue;
|
||||||
|
if (this.lastStatus.get(agentId) === status) continue; // no change → no PUT
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `${acct.guildBaseUrl.replace(/\/$/, '')}/agents/${encodeURIComponent(acct.fabricUserId)}/presence`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
'x-api-key': acct.fabricApiKey,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ status, source: 'hf-plugin' }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
this.lastStatus.set(agentId, status);
|
||||||
|
this.logger.info(`fabric: presence-sync ${agentId} → ${status}`);
|
||||||
|
} else {
|
||||||
|
this.logger.warn(`fabric: presence-sync PUT ${agentId} failed: ${res.status}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(`fabric: presence-sync PUT ${agentId} threw: ${String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
169
src/tools.ts
169
src/tools.ts
@@ -243,4 +243,173 @@ export function registerFabricTools(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// fabric-send-message: post a message into a specific channel.
|
||||||
|
//
|
||||||
|
// Unlike a normal channel reply (which goes back to whatever channel
|
||||||
|
// woke the agent), this lets the agent proactively initiate text into
|
||||||
|
// any channel they are a member of — e.g. ARD broadcasting daily
|
||||||
|
// workload to #agents-room, or triage agent following up on an
|
||||||
|
// already-routed task by commenting in #updates.
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
api.registerTool((ctx: Ctx) => ({
|
||||||
|
name: 'fabric-send-message',
|
||||||
|
description:
|
||||||
|
'Send a text message into a specific Fabric channel. Author is the calling agent. ' +
|
||||||
|
'Requires guildNodeId + channelId + content. Returns {ok, messageId, seq}.',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ['guildNodeId', 'channelId', 'content'],
|
||||||
|
properties: {
|
||||||
|
guildNodeId: { type: 'string' },
|
||||||
|
channelId: { type: 'string' },
|
||||||
|
content: { type: 'string', description: 'Message body (markdown supported by the renderer).' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
execute: async (p: { guildNodeId: string; channelId: string; content: string }) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
if (!agentId) return { ok: false, error: 'no agent context' };
|
||||||
|
const { session, guild, token } = await ctxGuild(agentId, p.guildNodeId);
|
||||||
|
const res = (await client.postMessage(
|
||||||
|
guild.endpoint,
|
||||||
|
token,
|
||||||
|
p.channelId,
|
||||||
|
p.content,
|
||||||
|
session.user.id,
|
||||||
|
)) as { messageId?: string; seq?: number };
|
||||||
|
return { ok: true, messageId: res.messageId, seq: res.seq };
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// fabric-channel-list: enumerate channels the calling agent can see
|
||||||
|
// in a given guild. Backend filters to public channels + channels the
|
||||||
|
// agent is a member of. Returns id / name / xType per channel so the
|
||||||
|
// agent can pick a channelId for fabric-send-message etc.
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
api.registerTool((ctx: Ctx) => ({
|
||||||
|
name: 'fabric-channel-list',
|
||||||
|
description:
|
||||||
|
'List channels visible to the calling agent in a guild. Optional ' +
|
||||||
|
'nameFilter does a case-insensitive substring match client-side. ' +
|
||||||
|
'Use this to find a channelId before fabric-send-message / fabric-message-history.',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ['guildNodeId'],
|
||||||
|
properties: {
|
||||||
|
guildNodeId: { type: 'string' },
|
||||||
|
nameFilter: { type: 'string', description: 'optional substring match on channel name (case-insensitive)' },
|
||||||
|
xType: {
|
||||||
|
type: 'string',
|
||||||
|
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'],
|
||||||
|
description: 'optional filter by x_type',
|
||||||
|
},
|
||||||
|
includeClosed: { type: 'boolean', description: 'default false — closed channels filtered out' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
execute: async (p: {
|
||||||
|
guildNodeId: string;
|
||||||
|
nameFilter?: string;
|
||||||
|
xType?: string;
|
||||||
|
includeClosed?: boolean;
|
||||||
|
}) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
if (!agentId) return { ok: false, error: 'no agent context' };
|
||||||
|
const { guild, token } = await ctxGuild(agentId, p.guildNodeId);
|
||||||
|
const all = await client.listChannels(guild.endpoint, token, p.guildNodeId);
|
||||||
|
const needle = (p.nameFilter ?? '').toLowerCase();
|
||||||
|
const filtered = all.filter((c) => {
|
||||||
|
if (!p.includeClosed && c.closed) return false;
|
||||||
|
if (p.xType && c.xType !== p.xType) return false;
|
||||||
|
if (needle && !c.name.toLowerCase().includes(needle)) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
count: filtered.length,
|
||||||
|
channels: filtered.map((c) => ({
|
||||||
|
id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
xType: c.xType,
|
||||||
|
isPublic: c.isPublic,
|
||||||
|
closed: c.closed,
|
||||||
|
lastSeq: c.lastSeq,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// fabric-message-history: read a channel's recent message history by
|
||||||
|
// `seq`. Tail-by-default: when `seqFrom`/`seqTo` are omitted, returns
|
||||||
|
// the last `limit` messages (limit defaults to 20, max 200).
|
||||||
|
//
|
||||||
|
// Use cases: catch-up on a channel that was muted while the agent was
|
||||||
|
// gated; verify a previous message went through; lookup recent
|
||||||
|
// duplicates before opening a new task in triage.
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
api.registerTool((ctx: Ctx) => ({
|
||||||
|
name: 'fabric-message-history',
|
||||||
|
description:
|
||||||
|
"Read a channel's recent message history. Omit seqFrom/seqTo to " +
|
||||||
|
'tail (last `limit` messages, default 20, max 200). Backend ' +
|
||||||
|
'requires the calling agent to be a channel participant.',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
additionalProperties: false,
|
||||||
|
required: ['guildNodeId', 'channelId'],
|
||||||
|
properties: {
|
||||||
|
guildNodeId: { type: 'string' },
|
||||||
|
channelId: { type: 'string' },
|
||||||
|
seqFrom: { type: 'integer', minimum: 1, description: 'inclusive lower bound; default = tail' },
|
||||||
|
seqTo: { type: 'integer', minimum: 1, description: 'inclusive upper bound; default = channel head' },
|
||||||
|
limit: { type: 'integer', minimum: 1, maximum: 200, description: 'default 20' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
execute: async (p: {
|
||||||
|
guildNodeId: string;
|
||||||
|
channelId: string;
|
||||||
|
seqFrom?: number;
|
||||||
|
seqTo?: number;
|
||||||
|
limit?: number;
|
||||||
|
}) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
if (!agentId) return { ok: false, error: 'no agent context' };
|
||||||
|
const { guild, token } = await ctxGuild(agentId, p.guildNodeId);
|
||||||
|
const limit = p.limit ?? 20;
|
||||||
|
|
||||||
|
// Tail mode: discover channel head via channel listing, then ask
|
||||||
|
// for [head-limit+1, head]. Avoids needing the agent to know seq.
|
||||||
|
let seqFrom = p.seqFrom;
|
||||||
|
let seqTo = p.seqTo;
|
||||||
|
if (seqFrom === undefined && seqTo === undefined) {
|
||||||
|
const channels = await client.listChannels(guild.endpoint, token, p.guildNodeId);
|
||||||
|
const ch = channels.find((c) => c.id === p.channelId);
|
||||||
|
const head = ch?.lastSeq ?? 0;
|
||||||
|
seqFrom = Math.max(1, head - limit + 1);
|
||||||
|
seqTo = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await client.listMessages(guild.endpoint, token, p.channelId, {
|
||||||
|
seqFrom,
|
||||||
|
seqTo,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
page: res.page,
|
||||||
|
messages: res.items.map((m) => ({
|
||||||
|
messageId: m.messageId,
|
||||||
|
seq: m.seq,
|
||||||
|
authorUserId: m.authorUserId,
|
||||||
|
content: m.content,
|
||||||
|
createdAt: m.createdAt,
|
||||||
|
isDeleted: m.isDeleted,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user