Compare commits

...

4 Commits

Author SHA1 Message Date
Peter Steinberger
984499197d fix: drop stale ts-expect-error in pdf input parsing 2026-01-20 08:51:32 +00:00
Peter Steinberger
f78c6fb785 fix: enforce tool-dispatch policy + media (#1235) (thanks @dougvk) 2026-01-20 08:46:11 +00:00
Doug von Kohorn
872911a176 feat: add tool_result_persist hook 2026-01-20 08:45:06 +00:00
Doug von Kohorn
1e37efb13a feat: tool-dispatch skill commands 2026-01-20 08:45:06 +00:00
18 changed files with 884 additions and 8 deletions

View File

@ -11,6 +11,7 @@ Docs: https://docs.clawd.bot
- Web search: infer Perplexity base URL from API key source (direct vs OpenRouter).
- TUI: keep thinking blocks ordered before content during streaming and isolate per-run assembly. (#1202) — thanks @aaronveklabs.
- CLI: avoid duplicating --profile/--dev flags when formatting commands.
- Agents: enforce tool policy/sandbox rules for tool-dispatched skill commands and forward tool media outputs. (#1235) — thanks @dougvk.
## 2026.1.19-3

View File

@ -73,6 +73,7 @@ These run inside the agent loop or gateway pipeline:
- **`agent_end`**: inspect the final message list and run metadata after completion.
- **`before_compaction` / `after_compaction`**: observe or annotate compaction cycles.
- **`before_tool_call` / `after_tool_call`**: intercept tool params/results.
- **`tool_result_persist`**: synchronously transform tool results before they are written to the session transcript.
- **`message_received` / `message_sending` / `message_sent`**: inbound + outbound message hooks.
- **`session_start` / `session_end`**: session lifecycle boundaries.
- **`gateway_start` / `gateway_stop`**: gateway lifecycle events.

View File

@ -82,6 +82,14 @@ Notes:
- `homepage` — URL surfaced as “Website” in the macOS Skills UI (also supported via `metadata.clawdbot.homepage`).
- `user-invocable``true|false` (default: `true`). When `true`, the skill is exposed as a user slash command.
- `disable-model-invocation``true|false` (default: `false`). When `true`, the skill is excluded from the model prompt (still available via user invocation).
- `command-dispatch``tool` (optional). When set to `tool`, the slash command bypasses the model and dispatches directly to a tool.
- `command-tool` — tool name to invoke when `command-dispatch: tool` is set.
- `command-arg-mode``raw` (default). For tool dispatch, forwards the raw args string to the tool (no core parsing).
The tool is invoked with params:
`{ command: "<raw args>", commandName: "<slash command>", skillName: "<skill name>" }`.
Tool-dispatch commands still respect tool policies/sandbox rules (same as normal model tools).
Replies are derived from tool results; include `MEDIA:` tokens or media URLs in tool output to send attachments.
## Gating (load-time filters)

View File

@ -102,6 +102,9 @@ Notes:
- Currently: `/help`, `/commands`, `/status`, `/whoami` (`/id`).
- Unauthorized command-only messages are silently ignored, and inline `/...` tokens are treated as plain text.
- **Skill commands:** `user-invocable` skills are exposed as slash commands. Names are sanitized to `a-z0-9_` (max 32 chars); collisions get numeric suffixes (e.g. `_2`).
- By default, skill commands are forwarded to the model as a normal request.
- Skills may optionally declare `command-dispatch: tool` to route the command directly to a tool (deterministic, no model).
- Tool-dispatch still respects tool policies/sandbox rules; replies use the tool result text/media (including `MEDIA:` tokens).
- **Native command arguments:** Discord uses autocomplete for dynamic options (and button menus when you omit required args). Telegram and Slack show a button menu when a command supports choices and you omit the arg.
## Usage surfaces (what shows where)

View File

@ -292,7 +292,10 @@ export async function compactEmbeddedPiSession(params: {
});
try {
await prewarmSessionFile(params.sessionFile);
const sessionManager = guardSessionManager(SessionManager.open(params.sessionFile));
const sessionManager = guardSessionManager(SessionManager.open(params.sessionFile), {
agentId: sessionAgentId,
sessionKey: params.sessionKey,
});
trackSessionManagerAccess(params.sessionFile);
const settingsManager = SettingsManager.create(effectiveWorkspace, agentDir);
ensurePiCompactionReserveTokens({

View File

@ -285,7 +285,10 @@ export async function runEmbeddedAttempt(
.catch(() => false);
await prewarmSessionFile(params.sessionFile);
sessionManager = guardSessionManager(SessionManager.open(params.sessionFile));
sessionManager = guardSessionManager(SessionManager.open(params.sessionFile), {
agentId: sessionAgentId,
sessionKey: params.sessionKey,
});
trackSessionManagerAccess(params.sessionFile);
await prepareSessionManagerForRun({

View File

@ -1,5 +1,6 @@
import type { SessionManager } from "@mariozechner/pi-coding-agent";
import { getGlobalHookRunner } from "../plugins/hook-runner-global.js";
import { installSessionToolResultGuard } from "./session-tool-result-guard.js";
export type GuardedSessionManager = SessionManager & {
@ -11,12 +12,38 @@ export type GuardedSessionManager = SessionManager & {
* Apply the tool-result guard to a SessionManager exactly once and expose
* a flush method on the instance for easy teardown handling.
*/
export function guardSessionManager(sessionManager: SessionManager): GuardedSessionManager {
export function guardSessionManager(
sessionManager: SessionManager,
opts?: { agentId?: string; sessionKey?: string },
): GuardedSessionManager {
if (typeof (sessionManager as GuardedSessionManager).flushPendingToolResults === "function") {
return sessionManager as GuardedSessionManager;
}
const guard = installSessionToolResultGuard(sessionManager);
const hookRunner = getGlobalHookRunner();
const transform = hookRunner?.hasHooks("tool_result_persist")
? (message: any, meta: { toolCallId?: string; toolName?: string; isSynthetic?: boolean }) => {
const out = hookRunner.runToolResultPersist(
{
toolName: meta.toolName,
toolCallId: meta.toolCallId,
message,
isSynthetic: meta.isSynthetic,
},
{
agentId: opts?.agentId,
sessionKey: opts?.sessionKey,
toolName: meta.toolName,
toolCallId: meta.toolCallId,
},
);
return out?.message ?? message;
}
: undefined;
const guard = installSessionToolResultGuard(sessionManager, {
transformToolResultForPersistence: transform,
});
(sessionManager as GuardedSessionManager).flushPendingToolResults = guard.flushPendingToolResults;
return sessionManager as GuardedSessionManager;
}

View File

@ -0,0 +1,143 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { AgentMessage } from "@mariozechner/pi-agent-core";
import { SessionManager } from "@mariozechner/pi-coding-agent";
import { describe, expect, it, afterEach } from "vitest";
import { loadClawdbotPlugins } from "../plugins/loader.js";
import { resetGlobalHookRunner } from "../plugins/hook-runner-global.js";
import { setActivePluginRegistry } from "../plugins/runtime.js";
import { createTestRegistry } from "../test-utils/channel-plugins.js";
import { guardSessionManager } from "./session-tool-result-guard-wrapper.js";
const EMPTY_CONFIG_SCHEMA = `configSchema: {
validate: () => ({ ok: true }),
jsonSchema: { type: "object", additionalProperties: true },
uiHints: {}
}`;
function writeTempPlugin(params: { dir: string; id: string; body: string }): string {
const file = path.join(params.dir, `${params.id}.mjs`);
fs.writeFileSync(file, params.body, "utf-8");
return file;
}
const ORIGINAL_BUNDLED_PLUGINS_DIR = process.env.CLAWDBOT_BUNDLED_PLUGINS_DIR;
afterEach(() => {
if (ORIGINAL_BUNDLED_PLUGINS_DIR === undefined) {
delete process.env.CLAWDBOT_BUNDLED_PLUGINS_DIR;
} else {
process.env.CLAWDBOT_BUNDLED_PLUGINS_DIR = ORIGINAL_BUNDLED_PLUGINS_DIR;
}
setActivePluginRegistry(createTestRegistry([]));
resetGlobalHookRunner();
});
describe("tool_result_persist hook", () => {
it("does not modify persisted toolResult messages when no hook is registered", () => {
const sm = guardSessionManager(SessionManager.inMemory(), {
agentId: "main",
sessionKey: "main",
});
sm.appendMessage({
role: "assistant",
content: [{ type: "toolCall", id: "call_1", name: "read", arguments: {} }],
} as AgentMessage);
sm.appendMessage({
role: "toolResult",
toolCallId: "call_1",
isError: false,
content: [{ type: "text", text: "ok" }],
details: { big: "x".repeat(10_000) },
} as any);
const messages = sm
.getEntries()
.filter((e) => e.type === "message")
.map((e) => (e as { message: AgentMessage }).message);
const toolResult = messages.find((m) => (m as any).role === "toolResult") as any;
expect(toolResult).toBeTruthy();
expect(toolResult.details).toBeTruthy();
});
it("composes transforms in priority order and allows stripping toolResult.details", () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-toolpersist-"));
process.env.CLAWDBOT_BUNDLED_PLUGINS_DIR = "/nonexistent/bundled/plugins";
const pluginA = writeTempPlugin({
dir: tmp,
id: "persist-a",
body: `export default { id: "persist-a", ${EMPTY_CONFIG_SCHEMA}, register(api) {
api.on("tool_result_persist", (event, ctx) => {
const msg = event.message;
// Example: remove large diagnostic payloads before persistence.
const { details: _details, ...rest } = msg;
return { message: { ...rest, persistOrder: ["a"], agentSeen: ctx.agentId ?? null } };
}, { priority: 10 });
} };`,
});
const pluginB = writeTempPlugin({
dir: tmp,
id: "persist-b",
body: `export default { id: "persist-b", ${EMPTY_CONFIG_SCHEMA}, register(api) {
api.on("tool_result_persist", (event) => {
const prior = (event.message && event.message.persistOrder) ? event.message.persistOrder : [];
return { message: { ...event.message, persistOrder: [...prior, "b"] } };
}, { priority: 5 });
} };`,
});
loadClawdbotPlugins({
cache: false,
workspaceDir: tmp,
config: {
plugins: {
load: { paths: [pluginA, pluginB] },
allow: ["persist-a", "persist-b"],
},
},
});
const sm = guardSessionManager(SessionManager.inMemory(), {
agentId: "main",
sessionKey: "main",
});
// Tool call (so the guard can infer tool name -> id mapping).
sm.appendMessage({
role: "assistant",
content: [{ type: "toolCall", id: "call_1", name: "read", arguments: {} }],
} as AgentMessage);
// Tool result containing a large-ish details payload.
sm.appendMessage({
role: "toolResult",
toolCallId: "call_1",
isError: false,
content: [{ type: "text", text: "ok" }],
details: { big: "x".repeat(10_000) },
} as any);
const messages = sm
.getEntries()
.filter((e) => e.type === "message")
.map((e) => (e as { message: AgentMessage }).message);
const toolResult = messages.find((m) => (m as any).role === "toolResult") as any;
expect(toolResult).toBeTruthy();
// Default behavior: strip details.
expect(toolResult.details).toBeUndefined();
// Hook composition: priority 10 runs before priority 5.
expect(toolResult.persistOrder).toEqual(["a", "b"]);
expect(toolResult.agentSeen).toBe("main");
});
});

View File

@ -68,17 +68,44 @@ function extractToolResultId(msg: Extract<AgentMessage, { role: "toolResult" }>)
return null;
}
export function installSessionToolResultGuard(sessionManager: SessionManager): {
export function installSessionToolResultGuard(
sessionManager: SessionManager,
opts?: {
/**
* Optional, synchronous transform applied to toolResult messages *before* they are
* persisted to the session transcript.
*/
transformToolResultForPersistence?: (
message: AgentMessage,
meta: { toolCallId?: string; toolName?: string; isSynthetic?: boolean },
) => AgentMessage;
},
): {
flushPendingToolResults: () => void;
getPendingIds: () => string[];
} {
const originalAppend = sessionManager.appendMessage.bind(sessionManager);
const pending = new Map<string, string | undefined>();
const persistToolResult = (
message: AgentMessage,
meta: { toolCallId?: string; toolName?: string; isSynthetic?: boolean },
) => {
const transformer = opts?.transformToolResultForPersistence;
return transformer ? transformer(message, meta) : message;
};
const flushPendingToolResults = () => {
if (pending.size === 0) return;
for (const [id, name] of pending.entries()) {
originalAppend(makeMissingToolResult({ toolCallId: id, toolName: name }));
const synthetic = makeMissingToolResult({ toolCallId: id, toolName: name });
originalAppend(
persistToolResult(synthetic, {
toolCallId: id,
toolName: name,
isSynthetic: true,
}) as never,
);
}
pending.clear();
};
@ -88,8 +115,15 @@ export function installSessionToolResultGuard(sessionManager: SessionManager): {
if (role === "toolResult") {
const id = extractToolResultId(message as Extract<AgentMessage, { role: "toolResult" }>);
const toolName = id ? pending.get(id) : undefined;
if (id) pending.delete(id);
return originalAppend(message as never);
return originalAppend(
persistToolResult(message, {
toolCallId: id ?? undefined,
toolName,
isSynthetic: false,
}) as never,
);
}
const sanitized =

View File

@ -89,4 +89,18 @@ describe("buildWorkspaceSkillCommandSpecs", () => {
expect(longCmd?.description.endsWith("…")).toBe(true);
expect(shortCmd?.description).toBe("Short description");
});
it("includes tool-dispatch metadata from frontmatter", async () => {
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-"));
await writeSkill({
dir: path.join(workspaceDir, "skills", "tool-dispatch"),
name: "tool-dispatch",
description: "Dispatch to a tool",
frontmatterExtra: "command-dispatch: tool\ncommand-tool: sessions_send",
});
const commands = buildWorkspaceSkillCommandSpecs(workspaceDir);
const cmd = commands.find((entry) => entry.skillName === "tool-dispatch");
expect(cmd?.dispatch).toEqual({ kind: "tool", toolName: "sessions_send", argMode: "raw" });
});
});

View File

@ -31,10 +31,23 @@ export type SkillInvocationPolicy = {
disableModelInvocation: boolean;
};
export type SkillCommandDispatchSpec = {
kind: "tool";
/** Name of the tool to invoke (AnyAgentTool.name). */
toolName: string;
/**
* How to forward user-provided args to the tool.
* - raw: forward the raw args string (no core parsing).
*/
argMode?: "raw";
};
export type SkillCommandSpec = {
name: string;
skillName: string;
description: string;
/** Optional deterministic dispatch behavior for this command. */
dispatch?: SkillCommandDispatchSpec;
};
export type SkillsInstallPreferences = {

View File

@ -357,10 +357,55 @@ export function buildWorkspaceSkillCommandSpecs(
rawDescription.length > SKILL_COMMAND_DESCRIPTION_MAX_LENGTH
? rawDescription.slice(0, SKILL_COMMAND_DESCRIPTION_MAX_LENGTH - 1) + "…"
: rawDescription;
const dispatch = (() => {
const kindRaw = (
entry.frontmatter?.["command-dispatch"] ??
entry.frontmatter?.["command_dispatch"] ??
""
)
.trim()
.toLowerCase();
if (!kindRaw) return undefined;
if (kindRaw !== "tool") return undefined;
const toolName = (
entry.frontmatter?.["command-tool"] ??
entry.frontmatter?.["command_tool"] ??
""
).trim();
if (!toolName) {
debugSkillCommandOnce(
`dispatch:missingTool:${rawName}`,
`Skill command "/${unique}" requested tool dispatch but did not provide command-tool. Ignoring dispatch.`,
{ skillName: rawName, command: unique },
);
return undefined;
}
const argModeRaw = (
entry.frontmatter?.["command-arg-mode"] ??
entry.frontmatter?.["command_arg_mode"] ??
""
)
.trim()
.toLowerCase();
const argMode = !argModeRaw || argModeRaw === "raw" ? "raw" : null;
if (!argMode) {
debugSkillCommandOnce(
`dispatch:badArgMode:${rawName}:${argModeRaw}`,
`Skill command "/${unique}" requested tool dispatch but has unknown command-arg-mode. Falling back to raw.`,
{ skillName: rawName, command: unique, argMode: argModeRaw },
);
}
return { kind: "tool", toolName, argMode: "raw" } as const;
})();
specs.push({
name: unique,
skillName: rawName,
description,
...(dispatch ? { dispatch } : {}),
});
}
return specs;

View File

@ -0,0 +1,177 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import type { SkillCommandSpec } from "../../agents/skills.js";
import type { AnyAgentTool } from "../../agents/pi-tools.types.js";
import type { ClawdbotConfig } from "../../config/config.js";
import type { MsgContext, TemplateContext } from "../templating.js";
import type { InlineDirectives } from "./directive-handling.js";
import { parseInlineDirectives } from "./directive-handling.js";
import type { TypingController } from "./typing.js";
import { handleInlineActions } from "./get-reply-inline-actions.js";
vi.mock("../../agents/clawdbot-tools.js", () => ({
createClawdbotTools: vi.fn(),
}));
import { createClawdbotTools } from "../../agents/clawdbot-tools.js";
const mockedCreateClawdbotTools = vi.mocked(createClawdbotTools);
const createTypingController = (): TypingController => ({
onReplyStart: vi.fn(),
startTypingLoop: vi.fn(),
startTypingOnText: vi.fn(),
refreshTypingTtl: vi.fn(),
isActive: vi.fn(() => false),
markRunComplete: vi.fn(),
markDispatchIdle: vi.fn(),
cleanup: vi.fn(),
});
const baseCommand = {
surface: "slack",
channel: "slack",
ownerList: [],
isAuthorizedSender: true,
rawBodyNormalized: "/dispatch",
commandBodyNormalized: "/dispatch",
senderId: "user-1",
};
const baseDirectives = parseInlineDirectives("/dispatch") as InlineDirectives;
function createParams(overrides: Partial<Parameters<typeof handleInlineActions>[0]> = {}) {
const cfg = (overrides.cfg ??
({
tools: {
allow: ["tool_allowed"],
},
} as ClawdbotConfig)) as ClawdbotConfig;
return {
ctx: {
Surface: "slack",
Provider: "slack",
AccountId: "default",
} satisfies MsgContext as MsgContext,
sessionCtx: {
Body: "",
BodyForAgent: "",
BodyStripped: "",
} satisfies TemplateContext as TemplateContext,
cfg,
agentId: "main",
agentDir: "/tmp",
sessionEntry: undefined,
previousSessionEntry: undefined,
sessionStore: undefined,
sessionKey: "main",
storePath: undefined,
sessionScope: "per-sender",
workspaceDir: "/tmp",
isGroup: false,
opts: undefined,
typing: createTypingController(),
allowTextCommands: true,
inlineStatusRequested: false,
command: baseCommand,
skillCommands: [],
directives: baseDirectives,
cleanedBody: "/dispatch",
elevatedEnabled: false,
elevatedAllowed: false,
elevatedFailures: [],
defaultActivation: () => "always",
resolvedThinkLevel: "off",
resolvedVerboseLevel: "off",
resolvedReasoningLevel: "off",
resolvedElevatedLevel: "off",
resolveDefaultThinkingLevel: async () => undefined,
provider: "openai",
model: "gpt-4o-mini",
contextTokens: 0,
directiveAck: undefined,
abortedLastRun: false,
skillFilter: undefined,
...overrides,
};
}
function createTool(name: string, execute: AnyAgentTool["execute"]): AnyAgentTool {
return {
name,
label: name,
description: name,
parameters: {},
execute,
} as AnyAgentTool;
}
describe("handleInlineActions tool-dispatch", () => {
beforeEach(() => {
mockedCreateClawdbotTools.mockReset();
});
it("returns media payloads from tool results", async () => {
const tool = createTool("tool_allowed", async () => ({
content: [{ type: "text", text: "Done\nMEDIA:/tmp/photo.jpg" }],
}));
mockedCreateClawdbotTools.mockReturnValue([tool]);
const skillCommands: SkillCommandSpec[] = [
{
name: "dispatch",
skillName: "dispatch",
description: "Dispatch",
dispatch: { kind: "tool", toolName: "tool_allowed", argMode: "raw" },
},
];
const result = await handleInlineActions(
createParams({
command: { ...baseCommand, commandBodyNormalized: "/dispatch hi" },
skillCommands,
cleanedBody: "/dispatch hi",
}),
);
expect(result.kind).toBe("reply");
const reply = (result as { reply?: unknown }).reply as { text?: string; mediaUrl?: string };
expect(reply.text).toBe("Done");
expect(reply.mediaUrl).toBe("file:///tmp/photo.jpg");
});
it("blocks tool dispatch when policy disallows the tool", async () => {
const allowed = createTool("tool_allowed", async () => ({ content: "ok" }));
const blocked = createTool("tool_blocked", async () => ({ content: "nope" }));
mockedCreateClawdbotTools.mockReturnValue([allowed, blocked]);
const cfg = {
tools: {
allow: ["tool_allowed"],
},
} as ClawdbotConfig;
const skillCommands: SkillCommandSpec[] = [
{
name: "dispatch",
skillName: "dispatch",
description: "Dispatch",
dispatch: { kind: "tool", toolName: "tool_blocked", argMode: "raw" },
},
];
const result = await handleInlineActions(
createParams({
cfg,
skillCommands,
command: { ...baseCommand, commandBodyNormalized: "/dispatch arg" },
cleanedBody: "/dispatch arg",
}),
);
expect(result.kind).toBe("reply");
const reply = (result as { reply?: { text?: string; isError?: boolean } }).reply;
expect(reply?.text).toContain("Tool blocked by policy");
expect(reply?.isError).toBe(true);
});
});

View File

@ -1,19 +1,47 @@
import { pathToFileURL } from "node:url";
import { getChannelDock } from "../../channels/dock.js";
import type { SkillCommandSpec } from "../../agents/skills.js";
import type { AnyAgentTool } from "../../agents/pi-tools.types.js";
import type { ClawdbotConfig } from "../../config/config.js";
import type { SessionEntry } from "../../config/sessions.js";
import type { MsgContext, TemplateContext } from "../templating.js";
import type { ElevatedLevel, ReasoningLevel, ThinkLevel, VerboseLevel } from "../thinking.js";
import type { GetReplyOptions, ReplyPayload } from "../types.js";
import {
resolveSubagentToolPolicy,
resolveEffectiveToolPolicy,
filterToolsByPolicy,
} from "../../agents/pi-tools.policy.js";
import {
buildPluginToolGroups,
collectExplicitAllowlist,
expandPolicyWithPluginGroups,
normalizeToolName,
resolveToolProfilePolicy,
} from "../../agents/tool-policy.js";
import {
resolveSandboxRuntimeStatus,
formatSandboxToolPolicyBlockedMessage,
} from "../../agents/sandbox/runtime-status.js";
import { isSubagentSessionKey } from "../../routing/session-key.js";
import { resolveUserPath } from "../../utils.js";
import { getAbortMemory } from "./abort.js";
import { buildStatusReply, handleCommands } from "./commands.js";
import type { InlineDirectives } from "./directive-handling.js";
import { isDirectiveOnly } from "./directive-handling.js";
import type { createModelSelectionState } from "./model-selection.js";
import { extractInlineSimpleCommand } from "./reply-inline.js";
import { parseReplyDirectives } from "./reply-directives.js";
import type { TypingController } from "./typing.js";
import { listSkillCommandsForWorkspace, resolveSkillCommandInvocation } from "../skill-commands.js";
import { logVerbose } from "../../globals.js";
import { createClawdbotTools } from "../../agents/clawdbot-tools.js";
import {
resolveGatewayMessageChannel,
type GatewayMessageChannel,
} from "../../utils/message-channel.js";
import { getPluginToolMeta } from "../../plugins/tools.js";
export type InlineActionResult =
| { kind: "reply"; reply: ReplyPayload | ReplyPayload[] | undefined }
@ -23,11 +51,238 @@ export type InlineActionResult =
abortedLastRun: boolean;
};
function normalizeMediaUrlCandidate(raw: string): string | null {
const trimmed = raw.trim();
if (!trimmed) return null;
if (/^https?:\/\//i.test(trimmed)) return trimmed;
if (trimmed.startsWith("file://")) return trimmed;
const resolved = trimmed.startsWith("~") ? resolveUserPath(trimmed) : trimmed;
if (resolved.startsWith("/")) {
return pathToFileURL(resolved).toString();
}
if (resolved.startsWith("./") || resolved.startsWith("../")) return resolved;
return trimmed;
}
function extractTextFromToolResultContent(content: unknown): string | null {
if (typeof content === "string") {
const trimmed = content.trim();
return trimmed ? trimmed : null;
}
if (!Array.isArray(content)) return null;
const parts: string[] = [];
for (const block of content) {
if (!block || typeof block !== "object") continue;
const rec = block as { type?: unknown; text?: unknown };
if (rec.type === "text" && typeof rec.text === "string") {
parts.push(rec.text);
}
}
const out = parts.join("\n").trim();
return out ? out : null;
}
function extractMediaUrlsFromDetails(details: unknown): string[] {
if (!details || typeof details !== "object") return [];
const record = details as Record<string, unknown>;
const candidates: string[] = [];
const mediaUrls = record.mediaUrls;
if (Array.isArray(mediaUrls)) {
for (const entry of mediaUrls) {
if (typeof entry === "string") candidates.push(entry);
}
}
const mediaUrl = record.mediaUrl;
if (typeof mediaUrl === "string") candidates.push(mediaUrl);
const media = record.media;
if (typeof media === "string") candidates.push(media);
const path = record.path;
if (typeof path === "string") candidates.push(path);
return candidates
.map((entry) => normalizeMediaUrlCandidate(entry))
.filter((entry): entry is string => Boolean(entry));
}
function extractReplyPayloadFromToolResult(result: unknown): ReplyPayload | null {
if (!result || typeof result !== "object") return null;
const maybePayload = result as ReplyPayload & { content?: unknown; details?: unknown };
if (
typeof maybePayload.text === "string" ||
typeof maybePayload.mediaUrl === "string" ||
Array.isArray(maybePayload.mediaUrls)
) {
return {
text: maybePayload.text?.trim() ? maybePayload.text.trim() : undefined,
mediaUrl: maybePayload.mediaUrl,
mediaUrls: maybePayload.mediaUrls,
replyToId: maybePayload.replyToId,
replyToTag: maybePayload.replyToTag,
replyToCurrent: maybePayload.replyToCurrent,
audioAsVoice: maybePayload.audioAsVoice,
isError: maybePayload.isError,
};
}
const content = maybePayload.content;
const text = extractTextFromToolResultContent(content);
const parsed = text
? parseReplyDirectives(text)
: {
text: "",
mediaUrls: undefined,
mediaUrl: undefined,
replyToId: undefined,
replyToCurrent: false,
replyToTag: false,
audioAsVoice: undefined,
isSilent: false,
};
if (parsed.isSilent) return null;
const mediaFromText = parsed.mediaUrls ?? (parsed.mediaUrl ? [parsed.mediaUrl] : []);
const mediaFromDetails = extractMediaUrlsFromDetails(maybePayload.details);
const mediaUrls = Array.from(new Set([...mediaFromText, ...mediaFromDetails]))
.map((entry) => normalizeMediaUrlCandidate(entry))
.filter((entry): entry is string => Boolean(entry));
const cleanedText = parsed.text?.trim() ? parsed.text.trim() : undefined;
if (!cleanedText && mediaUrls.length === 0) return null;
return {
text: cleanedText,
mediaUrls: mediaUrls.length ? mediaUrls : undefined,
mediaUrl: mediaUrls[0],
replyToId: parsed.replyToId,
replyToTag: parsed.replyToTag,
replyToCurrent: parsed.replyToCurrent,
audioAsVoice: parsed.audioAsVoice,
isError: (result as { isError?: unknown }).isError === true,
};
}
function resolveToolDispatchTools(params: {
cfg: ClawdbotConfig;
sessionKey: string;
provider: string;
model: string;
agentDir?: string;
agentChannel?: GatewayMessageChannel;
agentAccountId?: string;
workspaceDir: string;
}): {
allTools: AnyAgentTool[];
allowedTools: AnyAgentTool[];
sandboxed: boolean;
} {
const sandboxRuntime = resolveSandboxRuntimeStatus({
cfg: params.cfg,
sessionKey: params.sessionKey,
});
const {
profile,
providerProfile,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
} = resolveEffectiveToolPolicy({
config: params.cfg,
sessionKey: params.sessionKey,
modelProvider: params.provider,
modelId: params.model,
});
const profilePolicy = resolveToolProfilePolicy(profile);
const providerProfilePolicy = resolveToolProfilePolicy(providerProfile);
const sandboxPolicy = sandboxRuntime.sandboxed ? sandboxRuntime.toolPolicy : undefined;
const subagentPolicy =
isSubagentSessionKey(params.sessionKey) && params.sessionKey
? resolveSubagentToolPolicy(params.cfg)
: undefined;
const pluginToolAllowlist = collectExplicitAllowlist([
profilePolicy,
providerProfilePolicy,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
sandboxPolicy,
subagentPolicy,
]);
const allTools = createClawdbotTools({
agentSessionKey: params.sessionKey,
agentChannel: params.agentChannel,
agentAccountId: params.agentAccountId,
agentDir: params.agentDir,
workspaceDir: params.workspaceDir,
config: params.cfg,
sandboxed: sandboxRuntime.sandboxed,
pluginToolAllowlist,
}) as AnyAgentTool[];
const pluginGroups = buildPluginToolGroups({
tools: allTools,
toolMeta: (tool) => getPluginToolMeta(tool),
});
const profilePolicyExpanded = expandPolicyWithPluginGroups(profilePolicy, pluginGroups);
const providerProfilePolicyExpanded = expandPolicyWithPluginGroups(
providerProfilePolicy,
pluginGroups,
);
const globalPolicyExpanded = expandPolicyWithPluginGroups(globalPolicy, pluginGroups);
const globalProviderPolicyExpanded = expandPolicyWithPluginGroups(
globalProviderPolicy,
pluginGroups,
);
const agentPolicyExpanded = expandPolicyWithPluginGroups(agentPolicy, pluginGroups);
const agentProviderPolicyExpanded = expandPolicyWithPluginGroups(
agentProviderPolicy,
pluginGroups,
);
const sandboxPolicyExpanded = expandPolicyWithPluginGroups(sandboxPolicy, pluginGroups);
const subagentPolicyExpanded = expandPolicyWithPluginGroups(subagentPolicy, pluginGroups);
const toolsFiltered = profilePolicyExpanded
? filterToolsByPolicy(allTools, profilePolicyExpanded)
: allTools;
const providerProfileFiltered = providerProfilePolicyExpanded
? filterToolsByPolicy(toolsFiltered, providerProfilePolicyExpanded)
: toolsFiltered;
const globalFiltered = globalPolicyExpanded
? filterToolsByPolicy(providerProfileFiltered, globalPolicyExpanded)
: providerProfileFiltered;
const globalProviderFiltered = globalProviderPolicyExpanded
? filterToolsByPolicy(globalFiltered, globalProviderPolicyExpanded)
: globalFiltered;
const agentFiltered = agentPolicyExpanded
? filterToolsByPolicy(globalProviderFiltered, agentPolicyExpanded)
: globalProviderFiltered;
const agentProviderFiltered = agentProviderPolicyExpanded
? filterToolsByPolicy(agentFiltered, agentProviderPolicyExpanded)
: agentFiltered;
const sandboxed = sandboxPolicyExpanded
? filterToolsByPolicy(agentProviderFiltered, sandboxPolicyExpanded)
: agentProviderFiltered;
const subagentFiltered = subagentPolicyExpanded
? filterToolsByPolicy(sandboxed, subagentPolicyExpanded)
: sandboxed;
return {
allTools,
allowedTools: subagentFiltered,
sandboxed: sandboxRuntime.sandboxed,
};
}
export async function handleInlineActions(params: {
ctx: MsgContext;
sessionCtx: TemplateContext;
cfg: ClawdbotConfig;
agentId: string;
agentDir?: string;
sessionEntry?: SessionEntry;
previousSessionEntry?: SessionEntry;
sessionStore?: Record<string, SessionEntry>;
@ -67,6 +322,7 @@ export async function handleInlineActions(params: {
sessionCtx,
cfg,
agentId,
agentDir,
sessionEntry,
previousSessionEntry,
sessionStore,
@ -129,6 +385,63 @@ export async function handleInlineActions(params: {
typing.cleanup();
return { kind: "reply", reply: undefined };
}
const dispatch = skillInvocation.command.dispatch;
if (dispatch?.kind === "tool") {
const rawArgs = (skillInvocation.args ?? "").trim();
const channel =
resolveGatewayMessageChannel(ctx.Surface) ??
resolveGatewayMessageChannel(ctx.Provider) ??
undefined;
const { allTools, allowedTools } = resolveToolDispatchTools({
cfg,
sessionKey,
provider,
model,
agentDir,
agentChannel: channel,
agentAccountId: (ctx as { AccountId?: string }).AccountId,
workspaceDir,
});
const requestedName = normalizeToolName(dispatch.toolName);
const findTool = (tools: AnyAgentTool[]) =>
tools.find((candidate) => normalizeToolName(candidate.name) === requestedName);
const tool = findTool(allowedTools);
if (!tool) {
const allTool = findTool(allTools);
if (allTool) {
const sandboxReason = formatSandboxToolPolicyBlockedMessage({
cfg,
sessionKey,
toolName: requestedName,
});
const message = sandboxReason
? `❌ Tool blocked by policy: ${dispatch.toolName}\n${sandboxReason}`
: `❌ Tool blocked by policy: ${dispatch.toolName}`;
typing.cleanup();
return { kind: "reply", reply: { text: message, isError: true } };
}
typing.cleanup();
return { kind: "reply", reply: { text: `❌ Tool not available: ${dispatch.toolName}` } };
}
const toolCallId = `cmd_${Date.now()}_${Math.random().toString(16).slice(2)}`;
try {
const result = await tool.execute(toolCallId, {
command: rawArgs,
commandName: skillInvocation.command.name,
skillName: skillInvocation.command.skillName,
} as any);
const reply = extractReplyPayloadFromToolResult(result) ?? { text: "✅ Done." };
typing.cleanup();
return { kind: "reply", reply };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
typing.cleanup();
return { kind: "reply", reply: { text: `${message}`, isError: true } };
}
}
const promptParts = [
`Use the "${skillInvocation.command.skillName}" skill for this request.`,
skillInvocation.args ? `User input:\n${skillInvocation.args}` : null,

View File

@ -178,6 +178,7 @@ export async function getReplyFromConfig(
sessionCtx,
cfg,
agentId,
agentDir,
sessionEntry,
previousSessionEntry,
sessionStore,

View File

@ -240,7 +240,6 @@ async function extractPdfContent(params: {
const { buffer, limits } = params;
const pdf = await getDocument({
data: new Uint8Array(buffer),
// @ts-expect-error pdfjs-dist legacy option not in current type defs.
disableWorker: true,
}).promise;
const maxPages = Math.min(pdf.numPages, limits.pdf.maxPages);

View File

@ -30,6 +30,9 @@ import type {
PluginHookSessionEndEvent,
PluginHookSessionStartEvent,
PluginHookToolContext,
PluginHookToolResultPersistContext,
PluginHookToolResultPersistEvent,
PluginHookToolResultPersistResult,
} from "./types.js";
// Re-export types for consumers
@ -49,6 +52,9 @@ export type {
PluginHookBeforeToolCallEvent,
PluginHookBeforeToolCallResult,
PluginHookAfterToolCallEvent,
PluginHookToolResultPersistContext,
PluginHookToolResultPersistEvent,
PluginHookToolResultPersistResult,
PluginHookSessionContext,
PluginHookSessionStartEvent,
PluginHookSessionEndEvent,
@ -302,6 +308,59 @@ export function createHookRunner(registry: PluginRegistry, options: HookRunnerOp
return runVoidHook("after_tool_call", event, ctx);
}
/**
* Run tool_result_persist hook.
*
* This hook is intentionally synchronous: it runs in hot paths where session
* transcripts are appended synchronously.
*
* Handlers are executed sequentially in priority order (higher first). Each
* handler may return `{ message }` to replace the message passed to the next
* handler.
*/
function runToolResultPersist(
event: PluginHookToolResultPersistEvent,
ctx: PluginHookToolResultPersistContext,
): PluginHookToolResultPersistResult | undefined {
const hooks = getHooksForName(registry, "tool_result_persist");
if (hooks.length === 0) return undefined;
let current = event.message;
for (const hook of hooks) {
try {
const out = (hook.handler as any)({ ...event, message: current }, ctx) as
| PluginHookToolResultPersistResult
| void
| Promise<unknown>;
// Guard against accidental async handlers (this hook is sync-only).
if (out && typeof (out as any).then === "function") {
const msg =
`[hooks] tool_result_persist handler from ${hook.pluginId} returned a Promise; ` +
`this hook is synchronous and the result was ignored.`;
if (catchErrors) {
logger?.warn?.(msg);
continue;
}
throw new Error(msg);
}
const next = (out as PluginHookToolResultPersistResult | undefined)?.message;
if (next) current = next;
} catch (err) {
const msg = `[hooks] tool_result_persist handler from ${hook.pluginId} failed: ${String(err)}`;
if (catchErrors) {
logger?.error(msg);
} else {
throw new Error(msg);
}
}
}
return { message: current };
}
// =========================================================================
// Session Hooks
// =========================================================================
@ -385,6 +444,7 @@ export function createHookRunner(registry: PluginRegistry, options: HookRunnerOp
// Tool hooks
runBeforeToolCall,
runAfterToolCall,
runToolResultPersist,
// Session hooks
runSessionStart,
runSessionEnd,

View File

@ -1,6 +1,8 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import type { Command } from "commander";
import type { AgentMessage } from "@mariozechner/pi-agent-core";
import type { AuthProfileCredential, OAuthCredential } from "../agents/auth-profiles/types.js";
import type { AnyAgentTool } from "../agents/tools/common.js";
import type { ChannelDock } from "../channels/dock.js";
@ -231,6 +233,7 @@ export type PluginHookName =
| "message_sent"
| "before_tool_call"
| "after_tool_call"
| "tool_result_persist"
| "session_start"
| "session_end"
| "gateway_start"
@ -338,6 +341,30 @@ export type PluginHookAfterToolCallEvent = {
durationMs?: number;
};
// tool_result_persist hook
export type PluginHookToolResultPersistContext = {
agentId?: string;
sessionKey?: string;
toolName?: string;
toolCallId?: string;
};
export type PluginHookToolResultPersistEvent = {
toolName?: string;
toolCallId?: string;
/**
* The toolResult message about to be written to the session transcript.
* Handlers may return a modified message (e.g. drop non-essential fields).
*/
message: AgentMessage;
/** True when the tool result was synthesized by a guard/repair step. */
isSynthetic?: boolean;
};
export type PluginHookToolResultPersistResult = {
message?: AgentMessage;
};
// Session context
export type PluginHookSessionContext = {
agentId?: string;
@ -407,6 +434,10 @@ export type PluginHookHandlerMap = {
event: PluginHookAfterToolCallEvent,
ctx: PluginHookToolContext,
) => Promise<void> | void;
tool_result_persist: (
event: PluginHookToolResultPersistEvent,
ctx: PluginHookToolResultPersistContext,
) => PluginHookToolResultPersistResult | void;
session_start: (
event: PluginHookSessionStartEvent,
ctx: PluginHookSessionContext,