Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ assigned at release.
## Unreleased

- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns a null session ID and attribution with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`; an independently recorded metadata session kind is preserved. No migration.
- Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` reports whether Amp returned more than the first 100 threads.
- Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` truthfully reports whether Amp returned more than the first 100 threads by requesting one lookahead row.
- Changed: MCP `list_relay_agents` now returns the first at most 100 matching agents in relay order and adds `total_matching` and `truncated`; it previously returned the whole matching roster.
- Changed: MCP `get_session_summary` now returns `summary: { status: "unsupported" }` as a normal result when the selected backend records that status; it previously returned a tool error.
- Added: every MCP `list_session_summaries` row now includes `transcript_status: "not_verified"`, because directory publication does not prove that the transcript index is readable yet.
- Changed: on a managed Desktop connection, MCP `describe_capabilities` now reports `relay_messaging` as `restricted` when the chat's synced Desktop identity cannot be verified, with the safe refusal reason or retry guidance when the check itself is temporarily unavailable.
- Changed: on a managed Desktop connection whose synced identity cannot be verified, MCP `describe_capabilities` keeps `relay_messaging` available for `list_relay_agents` and `get_relay_agent_card` while listing every actor-dependent tool in `restricted_tools`, with the safe refusal reason or retry guidance.
- Fixed: `check_relay_inbox` bounds sender-address enrichment to one second and still returns pending messages with a null address when the lookup fails or stalls.
- Added: Cursor cloud agents can join Agent Relay as their own runs (migration 0081; docs/cursor-cloud-agents.md). A Cursor cloud agent connects with the person's OAuth grant from cursor.com/agents. It proves which run it is with a Cursor-signed OIDC token, minted in its VM for this server's audience and the grant's nonce, and verified against api.cursor.com's keys, once. It then joins with `join_relay` `cursor_identity_token` as `cursor-cloud-<hash>` and acts with `as`. The Cursor account must first be linked to the person: they confirm a one-time link in the browser, or the operator trusts their Cursor team (`SELFHOST_CURSOR_CLOUD_TRUSTED_TEAMS`) and the token carries their own email. `SELFHOST_CURSOR_CLOUD_RUN_IDENTITY=required` refuses the connection's shared agent. Revoking the connection releases its runs.
- Changed: OAuth connections with a `cursor.com/agents` callback are now the `cursor-cloud` connector kind (cards, relaygate `clients`), not `grok-bot`; x.ai callbacks stay `grok-bot`. Grok Bot routines work for both kinds. **On gate-only installs**, a Cursor-hosted Grok Bot that relaygate admitted as `grok-bot` re-enrols as `cursor-cloud` on next use. Add `"cursor-cloud"` to the relaygate rule that allows `"grok-bot"`.
- Changed: the MCP endpoint's `[selfhost-mcp] native chat context refused` log
Expand Down
4 changes: 2 additions & 2 deletions src/amp/provider-origin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"repository": "https://github.com/AgentWorkforce/relayhistory",
"commit": "b904e7ac570a22c3568879f5c4136d48f745984e",
"commit": "703d9f115a31551e70a9f7207be1ede9fe2f0c74",
"path": "sdk-ts/src/amp-source.ts",
"sha256": "aaf7feedda1bdcdeb6ef91bf6138e3662f10c3b6148c6267a484907580c4c1e9"
"sha256": "e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853"
}
4 changes: 2 additions & 2 deletions src/amp/provider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Generated from AgentWorkforce/relayhistory sdk-ts/src/amp-source.ts. Do not edit here.
// sha256: aaf7feedda1bdcdeb6ef91bf6138e3662f10c3b6148c6267a484907580c4c1e9
// sha256: e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853
/** Amp evidence projection. Cloud owns credentials, scheduling and delivery;
* this module owns interpreting provider JSON. Unknown fields stay in raw. */
export type AmpMessage = Record<string, unknown>;
Expand Down Expand Up @@ -193,7 +193,7 @@ let op;try{op=JSON.parse(process.env.RELAY_AMP_OPERATION)}catch{}
if(op&&typeof op.threadId==='string'){op.threadId=op.threadId.trim();const prefix='https://ampcode.com/threads/';if(op.threadId.startsWith(prefix))op.threadId=op.threadId.slice(prefix.length);if(op.threadId.endsWith('/'))op.threadId=op.threadId.slice(0,-1)}
if(!op||!['discover','export','inject'].includes(op.kind)||(op.kind!=='discover'&&(typeof op.threadId!=='string'||!/^T-[A-Za-z0-9-]{6,100}$/.test(op.threadId)))||(op.kind==='inject'&&(typeof op.text!=='string'||!op.text||op.text.includes(String.fromCharCode(0))))){process.stdout.write(JSON.stringify({ok:false,outcome:'rejected',code:'amp_invalid_operation'}));process.exit(0)}
const args=['--log-file','/dev/null'];
if(op.kind==='discover')args.push('threads','search','author:me','--json','--limit','100');
if(op.kind==='discover')args.push('threads','search','author:me','--json','--limit','101');
else if(op.kind==='export')args.push('threads','export',op.threadId);
else if(op.kind==='inject')args.push('threads','continue',op.threadId,'-ox');
const r=spawnSync(process.env.RELAY_AMP_CLI_PATH||'/tmp/relay-amp/node_modules/.bin/amp',args,{encoding:'utf8',input:op.kind==='inject'?op.text:undefined,timeout:45000,maxBuffer:16777216,env:{...process.env,RELAY_AMP_OPERATION:''}});
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function registerCapabilityDiscovery(server: McpServer, context: McpConte
options: { nativeStatus?: () => Promise<unknown> } = {}): void {
server.registerTool(CAPABILITY_DISCOVERY_TOOL, {
title: "Describe this connection's capabilities",
description: "Use when an expected Agent Relay capability is missing or an operation is refused. Returns this MCP connection's endpoint, authentication mode, granted scopes, current workspace role and tool groups; unavailable or restricted groups include the exact reason and enablement requirements. Read-only.",
description: "Use when an expected Agent Relay capability is missing or an operation is refused. Returns this MCP connection's endpoint, authentication mode, granted scopes, current workspace role and tool groups. A group can remain available for directory reads while actor-dependent calls appear in restricted_tools as { name, reason }; unavailable or fully restricted groups include the exact reason and enablement requirements. Read-only.",
inputSchema: {},
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
}, async () => {
Expand Down
13 changes: 10 additions & 3 deletions src/mcp/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export function ensureToolTitles(server: McpServer): void {
export const RELAY_TOOLS = ["list_relay_agents", "get_relay_agent_card", "set_relay_agent_card", "send_relay_message", "get_relay_message_status", "read_relay_conversation", "join_relay", "leave_relay",
"relay_status", "check_relay_inbox", "list_relay_channels", "subscribe_relay_channel", "unsubscribe_relay_channel",
"post_relay_channel", "read_relay_channel"] as const;
/** Directory reads do not act as the managed chat, so they survive a missing synced Desktop identity. */
const RELAY_DIRECTORY_TOOLS = ["list_relay_agents", "get_relay_agent_card"] as const;
const RELAY_SPAWN_TOOLS = ["list_relay_spawn_targets", "spawn_relay_agent", "get_relay_spawn_status", "release_relay_agent"] as const;
const AMP_TOOLS = ["list_amp_threads", "bind_amp_thread", "unbind_amp_thread"] as const;
const WEBHOOK_INBOX_TOOLS = ["link_webhook_inbox", "unlink_webhook_inbox"] as const;
Expand Down Expand Up @@ -160,6 +162,8 @@ export type CapabilityGroup = {
title: string;
status: "available" | "restricted" | "unavailable";
tools: string[];
/** Listed tools whose calls are refused while the rest of the group remains usable. */
restricted_tools?: Array<{ name: string; reason: string }>;
reason?: string;
how_to_enable?: string;
call_requirements?: string;
Expand Down Expand Up @@ -256,9 +260,12 @@ export function describeCapabilities(input: {
? "Use your own Agent Relay sign-in (a person connection) for these tools."
: "An operator adds events_shim to SELFHOST_FEATURES (chart selectedFeatures)." };
if (item && id === "relay_messaging" && input.nativeAuthorityAvailable === false) {
return { ...base, status: "restricted", tools: [...item.tools],
reason: input.nativeAuthorityReason ?? "Agent Relay could not verify this chat's synced Desktop identity.",
how_to_enable: input.nativeAuthorityHowToEnable ?? "Reconnect this chat from Agent Relay Desktop and wait for its identity to sync, then retry." };
const reason = input.nativeAuthorityReason ?? "Agent Relay could not verify this chat's synced Desktop identity.";
return { ...base, status: "available", tools: [...item.tools],
restricted_tools: item.tools.filter(name => !(RELAY_DIRECTORY_TOOLS as readonly string[]).includes(name))
.map(name => ({ name, reason })),
how_to_enable: input.nativeAuthorityHowToEnable ?? "Reconnect this chat from Agent Relay Desktop and wait for its identity to sync, then retry.",
call_requirements: "Agent directory reads remain available. Acting as this managed chat requires its synced Desktop identity." };
}
if (item) return { ...base, status: "available", tools: [...item.tools], ...(id === "customer_support"
? { call_requirements: "Available to all signed-in customers. Current credentials and workspace membership are checked before sending and before returning an answer." } : {}) };
Expand Down
15 changes: 12 additions & 3 deletions src/mcp/relay-participants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ const ownerEnrichmentFailed = (operation: "list_relay_agents" | "get_relay_agent
operation, error: error instanceof Error ? error.name : "unknown",
});
};
const inboxSenderEnrichmentFailed = (error: unknown) => {
console.warn("[selfhost-mcp] inbox sender enrichment failed", {
operation: "check_relay_inbox", error: error instanceof Error ? error.name : "unknown",
});
};
const sessionEnrichmentFailed = (error: unknown) => {
console.warn("[selfhost-mcp] session enrichment failed", {
operation: "list_relay_agents", error: error instanceof Error ? error.name : "unknown",
Expand Down Expand Up @@ -109,6 +114,7 @@ const DESKTOP_LINK_FIELDS = "desktop_address cannot be combined with name or des
const DESKTOP_LINK_NEEDS_SESSION = "Initialize MCP to receive Mcp-Session-Id before linking a desktop identity.";
const DESKTOP_LINK_OAUTH = "This connection acts only as the agent approved for it and cannot link a desktop identity. Use a native MCP session (one that keeps Mcp-Session-Id) to call join_relay with desktop_address.";
const DESKTOP_INBOX_GUIDANCE = "Replies are injected into your session by Agent Relay Desktop; check_relay_inbox is not used for this linked identity.";
const INBOX_SENDER_LOOKUP_TIMEOUT_MS = 1_000;
const CHANNEL_REPLY_GUIDANCE = "Reply to a post in this channel with post_relay_channel channel=<name> thread_id=<message_id>. Use send_relay_message only when the reply is private.";
const RESERVED_CHANNEL_PREFIX = "agent-events-";
const CHANNEL_NAME = /^[a-z0-9][a-z0-9_-]{0,79}$/;
Expand Down Expand Up @@ -1599,16 +1605,19 @@ function createRelayService(context: McpContext) {
const hosted = await participant(as);
if (!hosted) throw new RelayToolError("No hosted participant is bound to this MCP session. Send a message with send_relay_message to auto-join, or call join_relay first.");
await touchPresence(hosted);
// Every fallible read finishes before any acknowledgement, so a failed
// enrichment leaves the deliveries pending for a retry.
// Required inbox and conversation reads finish before acknowledgement.
// Sender-address enrichment is optional and bounded: failure is logged
// and returned as a null address without failing the delivery read.
const via = clientFor(hosted);
const dir = directory(hosted);
const [messages, conversations] = await Promise.all([
via.readHostedInbox(hosted.token), via.listConversations(hosted.token),
]);
// Sender addresses come from one bounded lookup of the senders' names.
const senders = [...new Set(messages.flatMap(message => message.sender ? [message.sender] : []))];
const agents = senders.length ? (await dir.via.findAgentsByNames(dir.credential, senders)).filter(isListedRelayAgent) : [];
const agents = senders.length ? (await dir.via.findAgentsByNames(dir.credential, senders, {
signal: AbortSignal.timeout(INBOX_SENDER_LOOKUP_TIMEOUT_MS),
}).catch(error => { inboxSenderEnrichmentFailed(error); return []; })).filter(isListedRelayAgent) : [];
const addresses = new Map(agents.map(agent => [agent.name, agent.address]));
const channelNames = new Map<string, string>();
if (messages.some(isChannelDelivery)) {
Expand Down
8 changes: 4 additions & 4 deletions src/messaging/relaycast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,14 +266,14 @@ export function createRelaycastClient(input: {
}

/** Bounded name lookup behind findAgentsByNames and findAgentByName. */
async function agentsByNames(workspaceKey: string, names: string[]): Promise<RosterAgent[]> {
async function agentsByNames(workspaceKey: string, names: string[], options: { signal?: AbortSignal } = {}): Promise<RosterAgent[]> {
const wanted = [...new Set(names.map(name => name.trim()).filter(Boolean))];
const found: RosterAgent[] = [];
for (let start = 0; start < wanted.length; start += AGENT_NAME_LOOKUP_MAX) {
const chunk = wanted.slice(start, start + AGENT_NAME_LOOKUP_MAX);
const query = new URLSearchParams();
for (const name of chunk) query.append("names", name);
const data = await labeled("find_agents", () => call("GET", `/v1/agents?${query}`, workspaceKey));
const data = await labeled("find_agents", () => call("GET", `/v1/agents?${query}`, workspaceKey, undefined, undefined, false, options.signal));
if (!Array.isArray(data)) throw new RelaycastCallError(200, "", true);
const requested = new Set(chunk);
for (const item of data) {
Expand Down Expand Up @@ -498,8 +498,8 @@ export function createRelaycastClient(input: {
* filtering keeps the result bounded and correct there too. Errors are not
* retried with a full-roster read.
*/
async findAgentsByNames(workspaceKey: string, names: string[]): Promise<RosterAgent[]> {
return agentsByNames(workspaceKey, names);
async findAgentsByNames(workspaceKey: string, names: string[], options: { signal?: AbortSignal } = {}): Promise<RosterAgent[]> {
return agentsByNames(workspaceKey, names, options);
},

/**
Expand Down
14 changes: 14 additions & 0 deletions test/amp.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
import { runInNewContext } from "node:vm";
import { registerAmpTools } from "../src/amp/mcp-tools.js";
import { claimNext, RELAY_EVENT_MAX_BYTES } from "../src/amp/delivery.js";
import { decrypt, ownedThreadPage } from "../src/amp/service.js";
import { AMP_CLI_BRIDGE } from "../src/amp/provider.js";
import { startAmpWorker } from "../src/amp/worker.js";
import { planToolGroups } from "../src/mcp/catalog.js";
import type { McpContext } from "../src/mcp/context.js";
Expand All @@ -15,6 +17,18 @@ import { BOOTSTRAP } from "./flows-helpers.js";

const NOT_FOUND = { error: "Not found" };

test("Amp discovery requests one lookahead row for the bounded 100-thread page", () => {
let args: string[] = [];
runInNewContext(AMP_CLI_BRIDGE, {
require: () => ({ spawnSync: (_command: string, value: string[]) => {
args = value; return { status: 0, stdout: "[]" };
} }),
process: { env: { RELAY_AMP_OPERATION: JSON.stringify({ kind: "discover" }) },
stdout: { write: () => undefined }, exit: () => undefined },
});
assert.deepEqual(Array.from(args), ["--log-file", "/dev/null", "threads", "search", "author:me", "--json", "--limit", "101"]);
});

test("amp gating: off answers 404 before auth on every route and starts no worker (req 8)", async (t) => {
for (const variant of [{ amp: null }, { amp: ampConfig({ enabled: false }) }]) {
const h = await startAmp(t, variant);
Expand Down
Loading
Loading