π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import type {
ListAccountsArgs,
ReadInboxArgs,
SendMessageArgs,
WaitForMessageArgs,
} from '@lobechat/builtin-tool-agent-account';
import { AgentAccountApiName, AgentAccountIdentifier } from '@lobechat/builtin-tool-agent-account';
import { AgentAccountModel } from '@/database/models/agentAccount';
import type { AgentInboxEntry } from '@/database/models/agentInbox';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { AgentAccountService } from '@/server/services/agentIdentity';
import { AgentInboxService } from '@/server/services/agentIdentity/inbox';
import { createDefaultAgentAccountRegistry } from '@/server/services/agentIdentity/providers';
import {
fenceUntrustedInbox,
toUntrustedInboxEntry,
} from '@/server/services/agentIdentity/untrusted';
import { type ServerRuntimeRegistration } from './types';
/**
* The `wait` budget sits under the manifest's `defaultTimeoutMs` (130s) on
* purpose: the tool must return its own "nothing arrived" answer *before* the
* runtime's hard tool timeout kills the call. A timeout is a normal, retryable
* outcome, not an error β the agent can wait again.
*/
const DEFAULT_WAIT_MS = 60_000;
const MAX_WAIT_MS = 120_000;
const POLL_INTERVAL_MS = 1_000;
const DEFAULT_READ_LIMIT = 10;
const MAX_READ_LIMIT = 20;
/**
* Per-message body budget for a read. Bodies are attacker-controlled and a read
* returns up to {@link MAX_READ_LIMIT} of them, so one call must not be able to
* spend the whole context window: each body is clipped the way the wake preview
* clips its own.
*/
const MAX_READ_BODY_CHARS = 2000;
/** How far back a reply is checked for codes relayed from another sender. */
const CODE_RELAY_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
const normalizeAddress = (value: string) => value.trim().toLowerCase();
/**
* Who a provider-side reply to `entry` actually reaches.
*
* The mail API's reply route answers the message's `Reply-To` when it sets one
* and the sender otherwise, so those are not always the same mailbox. Returns
* `undefined` when the mail names several reply targets: no single recipient
* can then be authorized for an unattended reply.
*/
const replyRecipientOf = (entry: AgentInboxEntry): string | undefined => {
const targets = (entry.replyTo ?? [])
.map((target) => target.address?.trim())
.filter((address): address is string => Boolean(address));
if (targets.length === 0) return entry.from;
return targets.length === 1 ? targets[0] : undefined;
};
/** How far back a wait with no cursor and no known run start looks. */
const DEFAULT_WAIT_LOOKBACK_MS = 2 * 60 * 1000;
/** A run that started longer ago than this does not widen the default cursor further. */
const MAX_WAIT_LOOKBACK_MS = 30 * 60 * 1000;
/** Letters and digits only, lowercased: what is left of a code however it is reformatted. */
const compact = (value: string) => value.replaceAll(/[^\da-z]/gi, '').toLowerCase();
/**
* Most secret candidates one unattended reply may carry. Each is one predicate
* in the relay query, so the count is bounded β and a reply over it is held for
* the user rather than checked in part: padding the text with harmless links
* must not push a copied secret past the ones that get checked.
*/
const MAX_SECRET_CANDIDATES = 200;
/**
* Secret-shaped fragments of the outgoing text that the numeric code extractor
* never records: links (magic-login and reset URLs) and long or mixed
* letter/digit tokens (alphanumeric OTPs, API keys, passwords). Each is checked
* verbatim against other senders' mail, so ordinary words never match.
*/
const secretCandidates = (text: string): string[] => {
const urls = text.match(/https?:\/\/[^\s<>"')\]]+/g) ?? [];
const tokens = (text.match(/[\w+./=-]{6,}/g) ?? []).filter(
(token) => token.length >= 20 || (/\d/.test(token) && /[A-Z]/i.test(token)),
);
return [...new Set([...urls, ...tokens, ...splitTokenCandidates(text)])];
};
/**
* Shortest a regrouped token must be once joined β the same six characters the
* ordinary token extractor accepts, so a short OTP sent as `AB 12 CD` is checked
* just like `AB12CD`. Shorter joins are ordinary words and times.
*/
const MIN_SPLIT_TOKEN_CHARS = 6;
const MAX_SPLIT_TOKEN_CHARS = 40;
/**
* Tokens regrouped on the way out β `AB 12 CD 34 EF`, `ab-12-cd-34`. Each group
* is shorter than a token the extractor above recognises, so it never yields a
* candidate there. Runs of short letter/digit groups joined by one separator
* are re-assembled at every start and length, so the secret is found wherever
* it sits in the sentence; only joins long enough and mixing letters and digits
* count, which keeps ordinary prose out.
*/
const splitTokenCandidates = (text: string): string[] => {
const candidates: string[] = [];
const runs = text.match(/[\dA-Z]{1,5}(?:[\s.-][\dA-Z]{1,5})+/gi) ?? [];
for (const run of runs) {
// Every group: a bound here would let leading filler push the secret past it.
// The joined-length cap below already keeps the work per start bounded.
const groups = run.split(/[\s.-]/);
for (let start = 0; start < groups.length; start += 1) {
let joined = '';
for (let end = start; end < groups.length; end += 1) {
joined += groups[end];
if (joined.length > MAX_SPLIT_TOKEN_CHARS) break;
if (
end > start &&
joined.length >= MIN_SPLIT_TOKEN_CHARS &&
/\d/.test(joined) &&
/[A-Z]/i.test(joined)
) {
candidates.push(joined);
}
}
}
}
return candidates;
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const asJson = (value: unknown) => JSON.stringify(value, null, 2);
/**
* Server runtime for the agent-account tool.
*
* The account *state* (addresses + unread count) reaches the model as context.
* Message content does not: it is attacker-controlled, so it is read here and
* handed back inside an `<untrusted_inbox>` fence. Every API is scoped to the
* run's agent β an account id that belongs to someone else is refused, so the
* tool cannot be used as a confused deputy.
*
* `sendMessage` is the exfiltration edge. Its manifest holds any send without a
* thread for the user's approval; a send that names a thread is checked here:
* the thread must exist in this account's inbox, `to` must be its sender, and
* the text must not relay a code this agent received from someone else.
*/
export const agentAccountRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId || !context.serverDB) {
throw new Error('userId and serverDB are required for the agent-account tool');
}
const db = context.serverDB;
const userId = context.userId;
const workspaceId = context.workspaceId;
const agentId = context.agentId;
const requireAgentId = () => {
if (!agentId) throw new Error('Agent id is required for the agent-account tool');
return agentId;
};
const accounts = () =>
new AgentAccountModel(db, userId, undefined, workspaceId).query({
agentId: requireAgentId(),
// A released address is not the agent's any more: it can neither be
// listed, sent from, nor waited on.
liveOnly: true,
});
const inbox = new AgentInboxService(db, userId, workspaceId);
const defaultWaitCursor = async (): Promise<Date> => {
const now = Date.now();
const operation = context.operationId
? await new AgentOperationModel(db, userId, workspaceId)
.findById(context.operationId)
.catch(() => null)
: null;
const startedAt = operation?.startedAt ?? operation?.createdAt;
if (!startedAt) return new Date(now - DEFAULT_WAIT_LOOKBACK_MS);
return new Date(Math.max(new Date(startedAt).getTime(), now - MAX_WAIT_LOOKBACK_MS));
};
/** Accept either the account id or the address the model sees in context. */
const findOwned = (list: Awaited<ReturnType<typeof accounts>>, ref: string) =>
list.find((account) => account.id === ref || account.identifier === ref);
/**
* Check an unattended thread reply. Only reached when the call named a
* thread β without one the send was already held for the user's approval
* by the manifest's outbound audit. Returns the refusal, or the newest
* message from the recipient on that thread, which the reply answers.
*/
const checkThreadReply = async (
accountId: string,
args: SendMessageArgs & { threadKey: string },
): Promise<{ refusal: string } | { replyTo: AgentInboxEntry }> => {
const recipient = normalizeAddress(args.to);
const thread = await inbox.list({
accountId,
agentId: requireAgentId(),
limit: 50,
threadKey: args.threadKey,
});
// `list` is newest first, so this is the message being answered.
const replyTo = thread.find((message) => normalizeAddress(message.from) === recipient);
if (!replyTo) {
return {
refusal: `Thread ${args.threadKey} has no message from ${args.to} in this inbox, so this is not a reply. Send it without \`threadKey\` to ask the user to approve it.`,
};
}
// The reply route answers the message's `Reply-To`, not the address in
// its `From`. Checking only `from` would let a message signed by one
// address redirect the unattended reply β and any code or token it
// carries β to a different mailbox the checks below never looked at.
const deliveredTo = replyRecipientOf(replyTo);
if (!deliveredTo) {
return {
refusal: `The message from ${args.to} in thread ${args.threadKey} sets several Reply-To addresses, so who this reply reaches cannot be determined. Send it without \`threadKey\` to ask the user to approve it.`,
};
}
if (normalizeAddress(deliveredTo) !== recipient) {
return {
refusal: `Replies to ${args.to}'s message in thread ${args.threadKey} are delivered to ${deliveredTo}, because that message sets Reply-To. Reply to ${deliveredTo} instead, or send it without \`threadKey\` to ask the user to approve it.`,
};
}
// One query over the whole lookback window: a page of recent mail would
// let an outside sender flood the inbox until the message carrying the
// code falls off it, and the relay would then go out unattended.
// Compared with separators stripped on both sides, so a code reformatted
// on request (`839 201`, `839-201`, `8.3.9.2.0.1`) is still recognised.
// Fail closed: a reply with more secret-shaped fragments than one check
// covers cannot be cleared, so it goes to the user instead of out.
const candidates = [...new Set(secretCandidates(args.text).map(compact))];
if (candidates.length > MAX_SECRET_CANDIDATES) {
return {
refusal: `This reply carries more links and tokens (${candidates.length}) than can be checked for content copied from other senders' mail (at most ${MAX_SECRET_CANDIDATES}). Send it without \`threadKey\` to ask the user to approve it.`,
};
}
const compactText = compact(args.text);
const relayed = (
await inbox.listCodesFromOtherSenders({
agentId: requireAgentId(),
recipient,
since: new Date(Date.now() - CODE_RELAY_LOOKBACK_MS),
})
).find(({ code }) => {
const compactCode = compact(code);
return compactCode.length > 0 && compactText.includes(compactCode);
});
// Codes are only one kind of secret. A link or token copied out of
// another sender's mail is held for the user just the same.
const copied = relayed
? undefined
: ((await inbox.findTextFromOtherSender({
agentId: requireAgentId(),
// Same treatment as the codes above: a token reformatted on the way
// out (`AB12CD34` sent as `ab-12-cd-34`) is the same secret, so both
// sides are compared with case and separators stripped.
candidates,
recipient,
since: new Date(Date.now() - CODE_RELAY_LOOKBACK_MS),
})) ??
// The same question asked from the source side: does the reply,
// stripped to letters and digits, contain a secret another sender's
// mail carries? Spacing a token out, wrapping it in `token=` or a link
// of the attacker's own changes nothing once both sides are compacted.
(await inbox.findSecretRepeatedFromOtherSender({
agentId: requireAgentId(),
compactText,
recipient,
since: new Date(Date.now() - CODE_RELAY_LOOKBACK_MS),
})));
if (copied) {
return {
refusal: `This reply repeats a link or token from a message ${copied.from} sent you. Content from one sender's mail is never relayed to another without the user's approval β send it without \`threadKey\` to ask the user.`,
};
}
if (relayed) {
return {
refusal: `This reply contains a verification code that ${relayed.from} sent you. Codes are never relayed to another sender without the user's approval β send it without \`threadKey\` to ask the user.`,
};
}
return { replyTo };
};
return {
readInbox: async (args: ReadInboxArgs) => {
let accountId: string | undefined;
if (args?.accountId) {
const target = findOwned(await accounts(), args.accountId);
if (!target) {
return {
content: `No account ${args.accountId} is owned by this agent.`,
success: false,
};
}
accountId = target.id;
}
const limit = Math.min(Math.max(args?.limit ?? DEFAULT_READ_LIMIT, 1), MAX_READ_LIMIT);
const rows = await inbox.list({
accountId,
agentId: requireAgentId(),
limit,
unreadOnly: args?.unreadOnly ?? true,
});
if (rows.length === 0) {
return { content: 'No messages.', success: true };
}
// Reading is what "read" means: the unread count in context drops.
await inbox.markRead(rows.filter((row) => !row.readAt).map((row) => row.id));
return {
content: fenceUntrustedInbox(
rows.map((row) => toUntrustedInboxEntry(row, { maxBodyChars: MAX_READ_BODY_CHARS })),
),
state: { inboxMessageIds: rows.map((row) => row.id) },
success: true,
};
},
listAccounts: async (_args: ListAccountsArgs) => {
const list = await accounts();
return {
content: asJson({
accounts: list.map((account) => ({
capabilities: account.capabilities,
displayName: account.displayName,
identifier: account.identifier,
kind: account.kind,
provider: account.provider,
status: account.status,
})),
}),
success: true,
};
},
sendMessage: async (args: SendMessageArgs) => {
if (!args?.to || !args?.text) {
return { content: 'sendMessage requires both `to` and `text`.', success: false };
}
const list = await accounts();
// Accept either the account id or the address the model sees in
// context β the model refers to accounts by address, so matching only
// on the uuid would refuse a perfectly valid `sendMessage`.
const target = args.accountId
? list.find(
(account) => account.id === args.accountId || account.identifier === args.accountId,
)
: list.find((account) => account.capabilities.send);
// An explicitly chosen account must be able to send too: a receive-only
// account is not an outbound channel just because the model named it.
if (target && !target.capabilities.send) {
return {
content: `Account ${target.identifier} is receive-only and cannot send messages.`,
success: false,
};
}
if (!target) {
return {
content: args.accountId
? `No account ${args.accountId} is owned by this agent.`
: 'This agent has no send-capable account yet.',
success: false,
};
}
let replyTo: AgentInboxEntry | undefined;
if (args.threadKey) {
const checked = await checkThreadReply(target.id, {
...args,
threadKey: args.threadKey,
});
if ('refusal' in checked) return { content: checked.refusal, success: false };
replyTo = checked.replyTo;
}
try {
const service = new AgentAccountService(db, userId, {
gateKeeper: await KeyVaultsGateKeeper.initWithEnvKey(),
registry: createDefaultAgentAccountRegistry(),
workspaceId,
});
const { providerMessageId } = await service.send(target.id, {
replyToProviderMessageId: replyTo?.providerMessageId ?? undefined,
subject: args.subject,
text: args.text,
threadKey: args.threadKey,
to: args.to,
});
// The provider accepted it: keep the sent mail so the thread reads whole.
// Recording is bookkeeping β the mail is already out, so a failure here
// must not turn a successful send into a reported failure.
await inbox
.recordSentMail({
account: target,
inReplyTo: replyTo?.messageId,
providerMessageId,
subject: args.subject,
text: args.text,
threadKey: replyTo?.threadKey ?? args.threadKey,
to: [{ address: args.to }],
})
.catch((error) => {
console.error('[agentAccount] sent mail %s not recorded:', providerMessageId, error);
});
return {
content: asJson({ from: target.identifier, providerMessageId, to: args.to }),
success: true,
};
} catch (error) {
return {
content: `Failed to send from ${target.identifier}: ${
error instanceof Error ? error.message : String(error)
}`,
success: false,
};
}
},
waitForMessage: async (args: WaitForMessageArgs) => {
const waitMs = Math.min(Math.max(args?.timeoutMs ?? DEFAULT_WAIT_MS, 1_000), MAX_WAIT_MS);
// Without an explicit cursor, look back to the start of this run: the
// code usually lands between the action that triggered it (a signup
// or login in an earlier step) and this call, and starting the wait
// "now" would miss exactly that message.
const since = args?.since ? new Date(args.since) : await defaultWaitCursor();
const deadline = Date.now() + waitMs;
// Resolve the requested account against the accounts this agent actually
// owns *before* it reaches the query. The model routinely refers to an
// account by the address it sees in context (e.g. `[email protected]`), not
// by its uuid, and `agent_inbox_messages.account_id` is a uuid column β
// binding a non-uuid there surfaces a raw Postgres cast error (22P02)
// instead of a usable answer. Accept either form, and turn anything the
// agent does not own into the same authored refusal `sendMessage` gives.
let accountId: string | undefined;
if (args?.accountId) {
const owned = await accounts();
const target = owned.find(
(account) => account.id === args.accountId || account.identifier === args.accountId,
);
if (!target) {
return {
content: `No account ${args.accountId} is owned by this agent.`,
success: false,
};
}
accountId = target.id;
}
// Long-poll the inbox. The inbox is the single source of truth, so a
// message delivered by the webhook while this waits is picked up here
// with no coupling between the two paths.
for (;;) {
const [hit] = await inbox.listSince({
accountId,
agentId: requireAgentId(),
from: args?.from,
limit: 1,
// Without an explicit cursor every wait in this run starts from the
// run's start, so a message one wait already returned would satisfy
// the next wait too β the second OTP would never be waited for.
notConsumedBy: context.operationId,
since,
subjectIncludes: args?.subjectIncludes,
});
if (hit) {
// The model now holds this message, so it no longer counts as
// unread in the identity block of the following steps.
await inbox.markRead([hit.id]);
if (context.operationId) await inbox.markWaitConsumed(hit.id, context.operationId);
return {
// Same body budget as a read: one attacker-sized match must not
// spend the context window. The full body stays in the inbox.
content: `matched: true\n${fenceUntrustedInbox([
toUntrustedInboxEntry(hit, { maxBodyChars: MAX_READ_BODY_CHARS }),
])}`,
state: { inboxMessageId: hit.id },
success: true,
};
}
if (Date.now() >= deadline) {
return {
content: asJson({ matched: false, reason: 'timed-out' }),
success: true,
};
}
await sleep(POLL_INTERVAL_MS);
}
},
};
},
identifier: AgentAccountIdentifier,
};
export { AgentAccountApiName };