espennilsen/pi / extensions/pi-a2a
pi-a2a
Flaggedclient.ts
View on GitHub/**
* pi-a2a — A2A client for sending messages to remote agents.
*
* Uses @a2a-js/sdk Client for spec-compliant A2A messaging:
* - Proper JSON-RPC 2.0 with A2A-Version header
* - MessageSendParams with configuration (blocking, historyLength, etc.)
* - Typed Message/Task responses
* - Auth retry via SDK's AuthenticationHandler pattern
*/
import { randomUUID } from "node:crypto";
import {
Client,
JsonRpcTransport,
createAuthenticatingFetchWithRetry,
type AuthenticationHandler,
} from "@a2a-js/sdk/client";
import type { AgentCard, MessageSendParams, Task, Message, Part } from "@a2a-js/sdk";
import type { LogFn } from "./logger.ts";
import type { OutboundAuthContext } from "./outbound-auth.ts";
import type { LoopMetadata } from "./supervisor.ts";
import { injectLoopMetadata } from "./supervisor.ts";
/** Sender identity to include in message metadata. */
export interface SenderIdentity {
/** Agent display name (e.g. "Aivena"). */
name: string;
/** Agent description (optional). */
description?: string;
/** Agent's own A2A endpoint URL — allows the receiver to reply directly. */
url?: string;
}
export interface SendMessageOptions {
/** Remote agent's A2A endpoint URL. */
url: string;
/** Message text to send. */
message: string;
/** Bearer token for authenticating with the remote agent. */
credential?: string | null;
/** Negotiated authentication. Takes precedence over the legacy credential. */
authContext?: OutboundAuthContext;
/** Timeout in milliseconds. No timeout by default (requests are async/background). */
timeoutMs?: number;
/** Local agent identity to include as sender metadata. */
sender?: SenderIdentity;
/**
* Callback to refresh a stale credential on 401.
* Called once on auth failure — should evict cache and return a fresh token.
* If not provided, 401 is returned as-is.
*/
onRefreshCredential?: () => Promise<string | null>;
/**
* Loop-control metadata to propagate on the outbound message.
* When set, pi:hopCount, pi:visitedAgents, and pi:budgets are injected
* into the message metadata for downstream loop prevention.
*/
loopMetadata?: LoopMetadata | null;
/**
* Context ID for grouping related messages into a conversation.
* Generated by the caller. When provided, the remote agent can correlate
* follow-up messages with earlier ones in the same context.
*/
contextId?: string;
/**
* Task ID to continue an existing task on the remote agent.
* When provided, the remote agent appends this message to the specified
* task rather than creating a new one. Omit for the first message.
*/
taskId?: string;
}
export interface SendMessageResult {
ok: boolean;
/** Extracted text from the agent's response artifacts/status. */
response?: string;
/** The raw SDK result for inspection. */
raw?: unknown;
/** Error message if the request failed. */
error?: string;
/** True when the remote agent returned HTTP 401 — credential may be stale. */
unauthorized?: boolean;
/** True when the remote agent ACKed with "working" — poll via getRemoteTask(). */
working?: boolean;
/** Task ID from the remote agent — use with getRemoteTask() to poll for completion. */
taskId?: string;
/** Context ID from the remote agent's response — use for follow-up messages. */
contextId?: string;
}
/** Options for polling a remote task's status. */
export interface GetRemoteTaskOptions {
/** Remote agent's A2A endpoint URL. */
url: string;
/** Task ID to poll. */
taskId: string;
/** Bearer token for authenticating with the remote agent. */
credential?: string | null;
/** Negotiated authentication. Takes precedence over the legacy credential. */
authContext?: OutboundAuthContext;
/** Callback to refresh a stale credential on 401. */
onRefreshCredential?: () => Promise<string | null>;
/** Per-request timeout in milliseconds. Defaults to 30000 (30s). */
timeoutMs?: number;
}
/** Result of polling a remote task. */
export interface GetRemoteTaskResult {
/** Task state: submitted, working, completed, failed, canceled. */
state: string;
/** Extracted text if completed. */
response?: string;
/** Error message if failed. */
error?: string;
/** Raw task object for inspection. */
raw?: unknown;
}
/**
* Send a message to a remote A2A agent via the SDK Client.
*
* Creates a short-lived Client per call (agents may have different URLs/credentials).
* The SDK handles JSON-RPC framing, A2A-Version headers, and content negotiation.
*/
export async function sendA2AMessage(
opts: SendMessageOptions,
log: LogFn,
): Promise<SendMessageResult> {
const { url, message, credential, authContext, timeoutMs, sender, onRefreshCredential, loopMetadata, contextId, taskId } = opts;
log("a2a_send_start", {
url,
messageLength: message.length,
hasCredential: !!(authContext ?? credential),
hopCount: loopMetadata?.hopCount,
...(contextId ? { contextId } : {}),
...(taskId ? { taskId } : {}),
});
// Track auth state explicitly so we can set `unauthorized: true`
// without relying on SDK error message format (which is unstable
// in pre-1.0 @a2a-js/sdk). Declared outside try so catch can read it.
let sawUnauthorized = false;
try {
// ── Build auth-aware fetch ─────────────────────────────────
let currentCredential = authContext ? null : credential ?? null;
let retried = false;
const canRefresh = !authContext || isOAuthContext(authContext);
const authHandler: AuthenticationHandler = {
async headers() {
const hdrs: Record<string, string> = authContext ? { ...authContext.headers } : {};
if (currentCredential) {
hdrs["Authorization"] = `Bearer ${currentCredential}`;
}
return hdrs;
},
async shouldRetryWithHeaders(_req, res) {
if (res.status === 401) {
sawUnauthorized = true;
if (canRefresh && !retried && onRefreshCredential) {
retried = true;
log("credential_retry_via_auth_handler", { url });
try {
const fresh = await onRefreshCredential();
if (fresh) {
currentCredential = fresh;
// Don't reset sawUnauthorized here — the retry hasn't
// fired yet. onSuccessfulRetry will clear it if the
// retry succeeds; if it fails, the flag stays true so
// the caller gets { unauthorized: true }.
return { Authorization: `Bearer ${fresh}` };
}
} catch (refreshErr) {
// Refresh failed (e.g. network error) — not an auth
// rejection from the remote agent. Reset the flag so
// the catch block doesn't misclassify this as a 401.
sawUnauthorized = false;
throw refreshErr;
}
}
}
return undefined;
},
async onSuccessfulRetry() {
// Retry succeeded — clear the unauthorized flag
sawUnauthorized = false;
},
};
const fetchImpl = createAuthenticatingFetchWithRetry(fetch, authHandler);
// ── Create SDK transport + client ──────────────────────────
const transport = new JsonRpcTransport({
endpoint: url,
fetchImpl,
});
// Minimal agent card for outbound messaging. We don't fetch the remote
// card since we already know the endpoint URL. All required AgentCard
// fields are provided; optional fields are omitted.
const minimalCard: AgentCard = {
name: "remote-agent",
description: "",
url,
version: "1.0.0",
protocolVersion: "0.3.0",
capabilities: {},
defaultInputModes: ["text/plain"],
defaultOutputModes: ["text/plain"],
skills: [],
};
const client = new Client(transport, minimalCard);
// ── Build the A2A message ─────────────────────────────────
// Start with sender identity, then layer in loop-control metadata
let metadata: Record<string, unknown> | undefined = sender
? {
"pi:sender": {
name: sender.name,
...(sender.description ? { description: sender.description } : {}),
},
}
: undefined;
// Inject loop-control metadata for downstream loop prevention
if (loopMetadata) {
metadata = injectLoopMetadata(metadata, loopMetadata);
}
const params: MessageSendParams = {
message: {
kind: "message",
messageId: randomUUID(),
role: "user",
parts: [{ kind: "text", text: message }],
...(contextId ? { contextId } : {}),
...(taskId ? { taskId } : {}),
...(metadata ? { metadata } : {}),
},
configuration: {
blocking: false,
},
};
// ── Send via SDK (non-blocking) ───────────────────────────
// With blocking: false, the remote agent returns a Task immediately
// with submitted/working status. We return the taskId for polling.
const requestOpts = timeoutMs
? { signal: AbortSignal.timeout(timeoutMs) }
: undefined;
const result = await client.sendMessage(params, requestOpts);
// Extract task ID and context ID from the result
const resultTaskId = (result as { id?: string }).id;
const resultContextId = (result as { contextId?: string }).contextId;
// Check if the remote returned a completed result immediately
// (possible if the task was trivial or already cached)
const status = (result as { status?: { state?: string } }).status;
const state = status?.state;
if (state === "completed") {
const responseText = extractResponseText(result);
log("a2a_send_completed_immediately", { url, taskId: resultTaskId, responseLength: responseText.length });
return { ok: true, response: responseText, raw: result, taskId: resultTaskId ?? undefined, contextId: resultContextId ?? contextId };
}
if (state === "failed") {
const errorText = extractResponseText(result);
log("a2a_send_failed_immediately", { url, taskId: resultTaskId }, "ERROR");
return { ok: false, error: errorText, raw: result, taskId: resultTaskId ?? undefined, contextId: resultContextId ?? contextId };
}
// Task is submitted or working — return for polling
log("a2a_send_working", { url, taskId: resultTaskId, state });
return { ok: true, response: "", raw: result, working: true, taskId: resultTaskId ?? undefined, contextId: resultContextId ?? contextId };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
// Use the auth handler's state flag rather than parsing SDK error
// messages, which are unstable in pre-1.0 @a2a-js/sdk.
if (sawUnauthorized) {
log("a2a_send_unauthorized", { url }, "ERROR");
return {
ok: false,
error: "Unauthorized — the remote agent rejected the credential",
unauthorized: true,
};
}
log("a2a_send_error", { url, error: msg }, "ERROR");
return { ok: false, error: msg };
}
}
/**
* Poll a remote A2A task's status via the SDK Client's getTask method.
*
* Creates a short-lived Client per call (same pattern as sendA2AMessage).
* Returns the task state and extracted response/error text.
*/
export async function getRemoteTask(
opts: GetRemoteTaskOptions,
log: LogFn,
): Promise<GetRemoteTaskResult> {
const { url, taskId, credential, authContext, onRefreshCredential } = opts;
try {
// Build auth-aware fetch (same pattern as sendA2AMessage)
let currentCredential = authContext ? null : credential ?? null;
let retried = false;
const canRefresh = !authContext || isOAuthContext(authContext);
const authHandler: AuthenticationHandler = {
async headers() {
const hdrs: Record<string, string> = authContext ? { ...authContext.headers } : {};
if (currentCredential) {
hdrs["Authorization"] = `Bearer ${currentCredential}`;
}
return hdrs;
},
async shouldRetryWithHeaders(_req, res) {
if (res.status === 401 && canRefresh && !retried && onRefreshCredential) {
retried = true;
const fresh = await onRefreshCredential();
if (fresh) {
currentCredential = fresh;
return { Authorization: `Bearer ${fresh}` };
}
}
return undefined;
},
};
const fetchImpl = createAuthenticatingFetchWithRetry(fetch, authHandler);
const transport = new JsonRpcTransport({ endpoint: url, fetchImpl });
const minimalCard: AgentCard = {
name: "remote-agent",
description: "",
url,
version: "1.0.0",
protocolVersion: "0.3.0",
capabilities: {},
defaultInputModes: ["text/plain"],
defaultOutputModes: ["text/plain"],
skills: [],
};
const client = new Client(transport, minimalCard);
const requestTimeoutMs = opts.timeoutMs ?? 30_000;
const task = await client.getTask({ id: taskId }, { signal: AbortSignal.timeout(requestTimeoutMs) });
const state = task.status?.state ?? "unknown";
if (state === "completed") {
const response = extractResponseText(task);
log("a2a_poll_completed", { url, taskId, responseLength: response.length });
return { state, response, raw: task };
}
if (state === "failed") {
const errorText = extractResponseText(task);
log("a2a_poll_failed", { url, taskId }, "WARN");
return { state, error: errorText, raw: task };
}
if (state === "input-required") {
// Extract the question from the status message
const questionText = task.status?.message?.parts
? extractPartsText(task.status.message.parts as Part[])
: undefined;
log("a2a_poll_input_required", { url, taskId, hasQuestion: !!questionText });
return { state, response: questionText, raw: task };
}
// Still working/submitted/canceled
return { state, raw: task };
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
log("a2a_poll_error", { url, taskId, error: msg }, "ERROR");
throw err;
}
}
/** True only for negotiated OAuth modes, which may safely refresh after a 401. */
function isOAuthContext(context: OutboundAuthContext): boolean {
return context.mode === "oauth2" || context.mode === "oauth2+mtls";
}
/**
* Extract readable text from an A2A SDK result (Task or Message).
*
* The SDK's sendMessage returns Task | Message:
* - Task: check artifacts → status.message → fallback
* - Message: check parts directly
*/
function extractResponseText(result: Task | Message): string {
if (result.kind === "message") {
return extractPartsText(result.parts) || JSON.stringify(result, null, 2);
}
// Task response
const task = result;
const parts: string[] = [];
// Try artifacts first (primary response content)
if (task.artifacts?.length) {
for (const artifact of task.artifacts) {
const text = extractPartsText(artifact.parts);
if (text) parts.push(text);
}
}
if (parts.length > 0) return parts.join("\n");
// Fall back to status message
if (task.status?.message?.parts) {
const text = extractPartsText(task.status.message.parts as Part[]);
if (text) return text;
}
// Last resort: serialize the whole result
return JSON.stringify(result, null, 2);
}
/** Extract text from an array of A2A parts. */
function extractPartsText(parts: Part[]): string {
const texts: string[] = [];
for (const part of parts) {
if (part.kind === "text" && "text" in part) {
texts.push((part as { kind: "text"; text: string }).text);
}
}
return texts.join("\n");
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |