feat: add sessions_spawn sub-agent tool

This commit is contained in:
Peter Steinberger
2026-01-06 08:41:45 +01:00
parent 952657d55c
commit a279bcfeb1
14 changed files with 842 additions and 86 deletions

View File

@@ -0,0 +1,56 @@
import crypto from "node:crypto";
import { callGateway } from "../../gateway/call.js";
import { extractAssistantText, stripToolMessages } from "./sessions-helpers.js";
export async function readLatestAssistantReply(params: {
sessionKey: string;
limit?: number;
}): Promise<string | undefined> {
const history = (await callGateway({
method: "chat.history",
params: { sessionKey: params.sessionKey, limit: params.limit ?? 50 },
})) as { messages?: unknown[] };
const filtered = stripToolMessages(
Array.isArray(history?.messages) ? history.messages : [],
);
const last = filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
return last ? extractAssistantText(last) : undefined;
}
export async function runAgentStep(params: {
sessionKey: string;
message: string;
extraSystemPrompt: string;
timeoutMs: number;
lane?: string;
}): Promise<string | undefined> {
const stepIdem = crypto.randomUUID();
const response = (await callGateway({
method: "agent",
params: {
message: params.message,
sessionKey: params.sessionKey,
idempotencyKey: stepIdem,
deliver: false,
lane: params.lane ?? "nested",
extraSystemPrompt: params.extraSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string; acceptedAt?: number };
const stepRunId =
typeof response?.runId === "string" && response.runId ? response.runId : "";
const resolvedRunId = stepRunId || stepIdem;
const stepWaitMs = Math.min(params.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: resolvedRunId,
timeoutMs: stepWaitMs,
},
timeoutMs: stepWaitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return undefined;
return await readLatestAssistantReply({ sessionKey: params.sessionKey });
}

View File

@@ -0,0 +1,36 @@
import { callGateway } from "../../gateway/call.js";
import type { AnnounceTarget } from "./sessions-send-helpers.js";
import { resolveAnnounceTargetFromKey } from "./sessions-send-helpers.js";
export async function resolveAnnounceTarget(params: {
sessionKey: string;
displayKey: string;
}): Promise<AnnounceTarget | null> {
const parsed = resolveAnnounceTargetFromKey(params.sessionKey);
if (parsed) return parsed;
const parsedDisplay = resolveAnnounceTargetFromKey(params.displayKey);
if (parsedDisplay) return parsedDisplay;
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: true,
includeUnknown: true,
limit: 200,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
const match =
sessions.find((entry) => entry?.key === params.sessionKey) ??
sessions.find((entry) => entry?.key === params.displayKey);
const channel =
typeof match?.lastChannel === "string" ? match.lastChannel : undefined;
const to = typeof match?.lastTo === "string" ? match.lastTo : undefined;
if (channel && to) return { channel, to };
} catch {
// ignore
}
return null;
}

View File

@@ -4,8 +4,10 @@ import { Type } from "@sinclair/typebox";
import { loadConfig } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { readLatestAssistantReply, runAgentStep } from "./agent-step.js";
import type { AnyAgentTool } from "./common.js";
import { jsonResult, readStringParam } from "./common.js";
import { resolveAnnounceTarget } from "./sessions-announce-target.js";
import {
extractAssistantText,
resolveDisplaySessionKey,
@@ -14,13 +16,11 @@ import {
stripToolMessages,
} from "./sessions-helpers.js";
import {
type AnnounceTarget,
buildAgentToAgentAnnounceContext,
buildAgentToAgentMessageContext,
buildAgentToAgentReplyContext,
isAnnounceSkip,
isReplySkip,
resolveAnnounceTargetFromKey,
resolvePingPongTurns,
} from "./sessions-send-helpers.js";
@@ -83,87 +83,6 @@ export function createSessionsSendTool(opts?: {
const requesterSurface = opts?.agentSurface;
const maxPingPongTurns = resolvePingPongTurns(cfg);
const resolveAnnounceTarget =
async (): Promise<AnnounceTarget | null> => {
const parsed = resolveAnnounceTargetFromKey(resolvedKey);
if (parsed) return parsed;
try {
const list = (await callGateway({
method: "sessions.list",
params: {
includeGlobal: true,
includeUnknown: true,
limit: 200,
},
})) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(list?.sessions) ? list.sessions : [];
const match =
sessions.find((entry) => entry?.key === resolvedKey) ??
sessions.find((entry) => entry?.key === displayKey);
const channel =
typeof match?.lastChannel === "string"
? match.lastChannel
: undefined;
const to =
typeof match?.lastTo === "string" ? match.lastTo : undefined;
if (channel && to) return { channel, to };
} catch {
// ignore; fall through to null
}
return null;
};
const readLatestAssistantReply = async (
sessionKeyToRead: string,
): Promise<string | undefined> => {
const history = (await callGateway({
method: "chat.history",
params: { sessionKey: sessionKeyToRead, limit: 50 },
})) as { messages?: unknown[] };
const filtered = stripToolMessages(
Array.isArray(history?.messages) ? history.messages : [],
);
const last =
filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
return last ? extractAssistantText(last) : undefined;
};
const runAgentStep = async (step: {
sessionKey: string;
message: string;
extraSystemPrompt: string;
timeoutMs: number;
}): Promise<string | undefined> => {
const stepIdem = crypto.randomUUID();
const response = (await callGateway({
method: "agent",
params: {
message: step.message,
sessionKey: step.sessionKey,
idempotencyKey: stepIdem,
deliver: false,
lane: "nested",
extraSystemPrompt: step.extraSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string; acceptedAt?: number };
const stepRunId =
typeof response?.runId === "string" && response.runId
? response.runId
: stepIdem;
const stepWaitMs = Math.min(step.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: stepRunId,
timeoutMs: stepWaitMs,
},
timeoutMs: stepWaitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return undefined;
return readLatestAssistantReply(step.sessionKey);
};
const runAgentToAgentFlow = async (
roundOneReply?: string,
runInfo?: { runId: string },
@@ -182,12 +101,17 @@ export function createSessionsSendTool(opts?: {
timeoutMs: waitMs + 2000,
})) as { status?: string };
if (wait?.status === "ok") {
primaryReply = await readLatestAssistantReply(resolvedKey);
primaryReply = await readLatestAssistantReply({
sessionKey: resolvedKey,
});
latestReply = primaryReply;
}
}
if (!latestReply) return;
const announceTarget = await resolveAnnounceTarget();
const announceTarget = await resolveAnnounceTarget({
sessionKey: resolvedKey,
displayKey,
});
const targetChannel = announceTarget?.channel ?? "unknown";
if (
maxPingPongTurns > 0 &&
@@ -216,6 +140,7 @@ export function createSessionsSendTool(opts?: {
message: incomingMessage,
extraSystemPrompt: replyPrompt,
timeoutMs: announceTimeoutMs,
lane: "nested",
});
if (!replyText || isReplySkip(replyText)) {
break;
@@ -241,6 +166,7 @@ export function createSessionsSendTool(opts?: {
message: "Agent-to-agent announce step.",
extraSystemPrompt: announcePrompt,
timeoutMs: announceTimeoutMs,
lane: "nested",
});
if (
announceTarget &&

View File

@@ -0,0 +1,348 @@
import crypto from "node:crypto";
import { Type } from "@sinclair/typebox";
import { loadConfig } from "../../config/config.js";
import { callGateway } from "../../gateway/call.js";
import { readLatestAssistantReply, runAgentStep } from "./agent-step.js";
import type { AnyAgentTool } from "./common.js";
import { jsonResult, readStringParam } from "./common.js";
import { resolveAnnounceTarget } from "./sessions-announce-target.js";
import {
resolveDisplaySessionKey,
resolveInternalSessionKey,
resolveMainSessionAlias,
} from "./sessions-helpers.js";
import { isAnnounceSkip } from "./sessions-send-helpers.js";
const SessionsSpawnToolSchema = Type.Object({
task: Type.String(),
label: Type.Optional(Type.String()),
timeoutSeconds: Type.Optional(Type.Integer({ minimum: 0 })),
cleanup: Type.Optional(
Type.Union([Type.Literal("delete"), Type.Literal("keep")]),
),
});
function buildSubagentSystemPrompt(params: {
requesterSessionKey?: string;
requesterSurface?: string;
childSessionKey: string;
label?: string;
}) {
const lines = [
"Sub-agent context:",
params.label ? `Label: ${params.label}` : undefined,
params.requesterSessionKey
? `Requester session: ${params.requesterSessionKey}.`
: undefined,
params.requesterSurface
? `Requester surface: ${params.requesterSurface}.`
: undefined,
`Your session: ${params.childSessionKey}.`,
"Run the task. Provide a clear final answer (plain text).",
'After you finish, you may be asked to produce an "announce" message to post back to the requester chat.',
].filter(Boolean);
return lines.join("\n");
}
function buildSubagentAnnouncePrompt(params: {
requesterSessionKey?: string;
requesterSurface?: string;
announceChannel: string;
task: string;
subagentReply?: string;
}) {
const lines = [
"Sub-agent announce step:",
params.requesterSessionKey
? `Requester session: ${params.requesterSessionKey}.`
: undefined,
params.requesterSurface
? `Requester surface: ${params.requesterSurface}.`
: undefined,
`Post target surface: ${params.announceChannel}.`,
`Original task: ${params.task}`,
params.subagentReply
? `Sub-agent result: ${params.subagentReply}`
: "Sub-agent result: (not available).",
'Reply exactly "ANNOUNCE_SKIP" to stay silent.',
"Any other reply will be posted to the requester chat surface.",
].filter(Boolean);
return lines.join("\n");
}
async function runSubagentAnnounceFlow(params: {
childSessionKey: string;
childRunId: string;
requesterSessionKey: string;
requesterSurface?: string;
requesterDisplayKey: string;
task: string;
timeoutMs: number;
cleanup: "delete" | "keep";
roundOneReply?: string;
}) {
try {
let reply = params.roundOneReply;
if (!reply) {
const waitMs = Math.min(params.timeoutMs, 60_000);
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: params.childRunId,
timeoutMs: waitMs,
},
timeoutMs: waitMs + 2000,
})) as { status?: string };
if (wait?.status !== "ok") return;
reply = await readLatestAssistantReply({
sessionKey: params.childSessionKey,
});
}
const announceTarget = await resolveAnnounceTarget({
sessionKey: params.requesterSessionKey,
displayKey: params.requesterDisplayKey,
});
if (!announceTarget) return;
const announcePrompt = buildSubagentAnnouncePrompt({
requesterSessionKey: params.requesterSessionKey,
requesterSurface: params.requesterSurface,
announceChannel: announceTarget.channel,
task: params.task,
subagentReply: reply,
});
const announceReply = await runAgentStep({
sessionKey: params.childSessionKey,
message: "Sub-agent announce step.",
extraSystemPrompt: announcePrompt,
timeoutMs: params.timeoutMs,
lane: "nested",
});
if (
!announceReply ||
!announceReply.trim() ||
isAnnounceSkip(announceReply)
)
return;
await callGateway({
method: "send",
params: {
to: announceTarget.to,
message: announceReply.trim(),
provider: announceTarget.channel,
idempotencyKey: crypto.randomUUID(),
},
timeoutMs: 10_000,
});
} catch {
// Best-effort follow-ups; ignore failures to avoid breaking the caller response.
} finally {
if (params.cleanup === "delete") {
try {
await callGateway({
method: "sessions.delete",
params: { key: params.childSessionKey, deleteTranscript: true },
timeoutMs: 10_000,
});
} catch {
// ignore
}
}
}
}
export function createSessionsSpawnTool(opts?: {
agentSessionKey?: string;
agentSurface?: string;
}): AnyAgentTool {
return {
label: "Sessions",
name: "sessions_spawn",
description:
"Spawn a background sub-agent run in an isolated session and announce the result back to the requester chat.",
parameters: SessionsSpawnToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const task = readStringParam(params, "task", { required: true });
const label = typeof params.label === "string" ? params.label.trim() : "";
const cleanup =
params.cleanup === "keep" || params.cleanup === "delete"
? (params.cleanup as "keep" | "delete")
: "delete";
const timeoutSeconds =
typeof params.timeoutSeconds === "number" &&
Number.isFinite(params.timeoutSeconds)
? Math.max(0, Math.floor(params.timeoutSeconds))
: 0;
const timeoutMs = timeoutSeconds * 1000;
const cfg = loadConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const requesterSessionKey = opts?.agentSessionKey;
const requesterInternalKey = requesterSessionKey
? resolveInternalSessionKey({
key: requesterSessionKey,
alias,
mainKey,
})
: alias;
const requesterDisplayKey = resolveDisplaySessionKey({
key: requesterInternalKey,
alias,
mainKey,
});
const childSessionKey = `subagent:${crypto.randomUUID()}`;
const childSystemPrompt = buildSubagentSystemPrompt({
requesterSessionKey,
requesterSurface: opts?.agentSurface,
childSessionKey,
label: label || undefined,
});
const childIdem = crypto.randomUUID();
let childRunId: string = childIdem;
try {
const response = (await callGateway({
method: "agent",
params: {
message: task,
sessionKey: childSessionKey,
idempotencyKey: childIdem,
deliver: false,
lane: "subagent",
extraSystemPrompt: childSystemPrompt,
},
timeoutMs: 10_000,
})) as { runId?: string };
if (typeof response?.runId === "string" && response.runId) {
childRunId = response.runId;
}
} catch (err) {
const messageText =
err instanceof Error
? err.message
: typeof err === "string"
? err
: "error";
return jsonResult({
status: "error",
error: messageText,
childSessionKey,
runId: childRunId,
});
}
if (timeoutSeconds === 0) {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "accepted",
childSessionKey,
runId: childRunId,
});
}
let waitStatus: string | undefined;
let waitError: string | undefined;
try {
const wait = (await callGateway({
method: "agent.wait",
params: {
runId: childRunId,
timeoutMs,
},
timeoutMs: timeoutMs + 2000,
})) as { status?: string; error?: string };
waitStatus = typeof wait?.status === "string" ? wait.status : undefined;
waitError = typeof wait?.error === "string" ? wait.error : undefined;
} catch (err) {
const messageText =
err instanceof Error
? err.message
: typeof err === "string"
? err
: "error";
return jsonResult({
status: messageText.includes("gateway timeout") ? "timeout" : "error",
error: messageText,
childSessionKey,
runId: childRunId,
});
}
if (waitStatus === "timeout") {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "timeout",
error: waitError,
childSessionKey,
runId: childRunId,
});
}
if (waitStatus === "error") {
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
});
return jsonResult({
status: "error",
error: waitError ?? "agent error",
childSessionKey,
runId: childRunId,
});
}
const replyText = await readLatestAssistantReply({
sessionKey: childSessionKey,
});
void runSubagentAnnounceFlow({
childSessionKey,
childRunId,
requesterSessionKey: requesterInternalKey,
requesterSurface: opts?.agentSurface,
requesterDisplayKey,
task,
timeoutMs: 30_000,
cleanup,
roundOneReply: replyText,
});
return jsonResult({
status: "ok",
childSessionKey,
runId: childRunId,
reply: replyText,
});
},
};
}