mirror of
https://github.com/openclaw/openclaw.git
synced 2026-03-12 07:20:45 +00:00
Merge remote-tracking branch 'origin/main' into dashboard-v2-chat-infra
This commit is contained in:
@@ -78,6 +78,7 @@ Docs: https://docs.openclaw.ai
|
||||
- Secrets/SecretRef: reject exec SecretRef traversal ids across schema, runtime, and gateway. (#42370) Thanks @joshavant.
|
||||
- Telegram/docs: clarify that `channels.telegram.groups` allowlists chats while `groupAllowFrom` allowlists users inside those chats, and point invalid negative chat IDs at the right config key. (#42451) Thanks @altaywtf.
|
||||
- Models/Alibaba Cloud Model Studio: wire `MODELSTUDIO_API_KEY` through shared env auth, implicit provider discovery, and shell-env fallback so onboarding works outside the wizard too. (#40634) Thanks @pomelo-nwu.
|
||||
- Subagents/authority: persist leaf vs orchestrator control scope at spawn time and route tool plus slash-command control through shared ownership checks, so leaf sessions cannot regain orchestration privileges after restore or flat-key lookups. Thanks @tdjackey.
|
||||
- ACP/sessions_spawn: implicitly stream `mode="run"` ACP spawns to parent only for eligible subagent orchestrator sessions (heartbeat `target: "last"` with a usable session-local route), restoring parent progress relays without thread binding. (#42404) Thanks @davidguttman.
|
||||
- Sessions/reset model recompute: clear stale runtime model, context-token, and system-prompt metadata before session resets recompute the replacement session, so resets pick up current defaults and explicit overrides instead of reusing old runtime model state. (#41173) thanks @PonyX-lab.
|
||||
- Browser/Browserbase 429 handling: surface stable no-retry rate-limit guidance without buffering discarded HTTP 429 response bodies from remote browser services. (#40491) thanks @mvanhorn.
|
||||
|
||||
@@ -182,6 +182,7 @@ Each level only sees announces from its direct children.
|
||||
|
||||
### Tool policy by depth
|
||||
|
||||
- Role and control scope are written into session metadata at spawn time. That keeps flat or restored session keys from accidentally regaining orchestrator privileges.
|
||||
- **Depth 1 (orchestrator, when `maxSpawnDepth >= 2`)**: Gets `sessions_spawn`, `subagents`, `sessions_list`, `sessions_history` so it can manage its children. Other session/system tools remain denied.
|
||||
- **Depth 1 (leaf, when `maxSpawnDepth == 1`)**: No session tools (current default behavior).
|
||||
- **Depth 2 (leaf worker)**: No session tools — `sessions_spawn` is always denied at depth 2. Cannot spawn further children.
|
||||
|
||||
@@ -7,7 +7,7 @@ import { callGatewayTool } from "./tools/gateway.js";
|
||||
|
||||
export type RequestExecApprovalDecisionParams = {
|
||||
id: string;
|
||||
command: string;
|
||||
command?: string;
|
||||
commandArgv?: string[];
|
||||
systemRunPlan?: SystemRunApprovalPlan;
|
||||
env?: Record<string, string>;
|
||||
@@ -35,8 +35,8 @@ function buildExecApprovalRequestToolParams(
|
||||
): ExecApprovalRequestToolParams {
|
||||
return {
|
||||
id: params.id,
|
||||
command: params.command,
|
||||
commandArgv: params.commandArgv,
|
||||
...(params.command ? { command: params.command } : {}),
|
||||
...(params.commandArgv ? { commandArgv: params.commandArgv } : {}),
|
||||
systemRunPlan: params.systemRunPlan,
|
||||
env: params.env,
|
||||
cwd: params.cwd,
|
||||
@@ -150,7 +150,7 @@ export async function requestExecApprovalDecision(
|
||||
|
||||
type HostExecApprovalParams = {
|
||||
approvalId: string;
|
||||
command: string;
|
||||
command?: string;
|
||||
commandArgv?: string[];
|
||||
systemRunPlan?: SystemRunApprovalPlan;
|
||||
env?: Record<string, string>;
|
||||
|
||||
@@ -125,7 +125,7 @@ export async function executeNodeHostCommand(
|
||||
throw new Error("invalid system.run.prepare response");
|
||||
}
|
||||
const runArgv = prepared.plan.argv;
|
||||
const runRawCommand = prepared.plan.rawCommand ?? prepared.cmdText;
|
||||
const runRawCommand = prepared.plan.commandText;
|
||||
const runCwd = prepared.plan.cwd ?? params.workdir;
|
||||
const runAgentId = prepared.plan.agentId ?? params.agentId;
|
||||
const runSessionKey = prepared.plan.sessionKey ?? params.sessionKey;
|
||||
@@ -238,8 +238,6 @@ export async function executeNodeHostCommand(
|
||||
// Register first so the returned approval ID is actionable immediately.
|
||||
const registration = await registerExecApprovalRequestForHostOrThrow({
|
||||
approvalId,
|
||||
command: prepared.cmdText,
|
||||
commandArgv: prepared.plan.argv,
|
||||
systemRunPlan: prepared.plan,
|
||||
env: nodeEnv,
|
||||
workdir: runCwd,
|
||||
@@ -391,7 +389,7 @@ export async function executeNodeHostCommand(
|
||||
warningText,
|
||||
approvalSlug,
|
||||
approvalId,
|
||||
command: prepared.cmdText,
|
||||
command: prepared.plan.commandText,
|
||||
cwd: runCwd,
|
||||
host: "node",
|
||||
nodeId,
|
||||
|
||||
@@ -135,11 +135,10 @@ function setupNodeInvokeMock(params: {
|
||||
function createSystemRunPreparePayload(cwd: string | null) {
|
||||
return {
|
||||
payload: {
|
||||
cmdText: "echo hi",
|
||||
plan: {
|
||||
argv: ["echo", "hi"],
|
||||
cwd,
|
||||
rawCommand: "echo hi",
|
||||
commandText: "echo hi",
|
||||
agentId: null,
|
||||
sessionKey: null,
|
||||
},
|
||||
@@ -662,10 +661,9 @@ describe("nodes run", () => {
|
||||
onApprovalRequest: (approvalParams) => {
|
||||
expect(approvalParams).toMatchObject({
|
||||
id: expect.any(String),
|
||||
command: "echo hi",
|
||||
commandArgv: ["echo", "hi"],
|
||||
systemRunPlan: expect.objectContaining({
|
||||
argv: ["echo", "hi"],
|
||||
commandText: "echo hi",
|
||||
}),
|
||||
nodeId: NODE_ID,
|
||||
host: "node",
|
||||
|
||||
@@ -149,4 +149,97 @@ describe("openclaw-tools: subagents scope isolation", () => {
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaf subagents cannot kill even explicitly-owned child sessions", async () => {
|
||||
const leafKey = "agent:main:subagent:leaf";
|
||||
const childKey = `${leafKey}:subagent:child`;
|
||||
|
||||
writeStore(storePath, {
|
||||
[leafKey]: {
|
||||
sessionId: "leaf-session",
|
||||
updatedAt: Date.now(),
|
||||
spawnedBy: "agent:main:main",
|
||||
subagentRole: "leaf",
|
||||
subagentControlScope: "none",
|
||||
},
|
||||
[childKey]: {
|
||||
sessionId: "child-session",
|
||||
updatedAt: Date.now(),
|
||||
spawnedBy: leafKey,
|
||||
subagentRole: "leaf",
|
||||
subagentControlScope: "none",
|
||||
},
|
||||
});
|
||||
|
||||
addSubagentRunForTests({
|
||||
runId: "run-child",
|
||||
childSessionKey: childKey,
|
||||
controllerSessionKey: leafKey,
|
||||
requesterSessionKey: leafKey,
|
||||
requesterDisplayKey: leafKey,
|
||||
task: "impossible child",
|
||||
cleanup: "keep",
|
||||
createdAt: Date.now() - 30_000,
|
||||
startedAt: Date.now() - 30_000,
|
||||
});
|
||||
|
||||
const tool = createSubagentsTool({ agentSessionKey: leafKey });
|
||||
const result = await tool.execute("call-leaf-kill", {
|
||||
action: "kill",
|
||||
target: childKey,
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({
|
||||
status: "forbidden",
|
||||
error: "Leaf subagents cannot control other sessions.",
|
||||
});
|
||||
expect(callGatewayMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaf subagents cannot steer even explicitly-owned child sessions", async () => {
|
||||
const leafKey = "agent:main:subagent:leaf";
|
||||
const childKey = `${leafKey}:subagent:child`;
|
||||
|
||||
writeStore(storePath, {
|
||||
[leafKey]: {
|
||||
sessionId: "leaf-session",
|
||||
updatedAt: Date.now(),
|
||||
spawnedBy: "agent:main:main",
|
||||
subagentRole: "leaf",
|
||||
subagentControlScope: "none",
|
||||
},
|
||||
[childKey]: {
|
||||
sessionId: "child-session",
|
||||
updatedAt: Date.now(),
|
||||
spawnedBy: leafKey,
|
||||
subagentRole: "leaf",
|
||||
subagentControlScope: "none",
|
||||
},
|
||||
});
|
||||
|
||||
addSubagentRunForTests({
|
||||
runId: "run-child",
|
||||
childSessionKey: childKey,
|
||||
controllerSessionKey: leafKey,
|
||||
requesterSessionKey: leafKey,
|
||||
requesterDisplayKey: leafKey,
|
||||
task: "impossible child",
|
||||
cleanup: "keep",
|
||||
createdAt: Date.now() - 30_000,
|
||||
startedAt: Date.now() - 30_000,
|
||||
});
|
||||
|
||||
const tool = createSubagentsTool({ agentSessionKey: leafKey });
|
||||
const result = await tool.execute("call-leaf-steer", {
|
||||
action: "steer",
|
||||
target: childKey,
|
||||
message: "continue",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({
|
||||
status: "forbidden",
|
||||
error: "Leaf subagents cannot control other sessions.",
|
||||
});
|
||||
expect(callGatewayMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,11 +6,6 @@ import { addSubagentRunForTests, resetSubagentRegistryForTests } from "./subagen
|
||||
import { createPerSenderSessionConfig } from "./test-helpers/session-config.js";
|
||||
import { createSessionsSpawnTool } from "./tools/sessions-spawn-tool.js";
|
||||
|
||||
vi.mock("@mariozechner/pi-ai/oauth", () => ({
|
||||
getOAuthApiKey: () => undefined,
|
||||
getOAuthProviders: () => [],
|
||||
}));
|
||||
|
||||
const callGatewayMock = vi.fn();
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
@@ -121,6 +116,8 @@ describe("sessions_spawn depth + child limits", () => {
|
||||
(entry) => entry.method === "sessions.patch" && entry.params?.spawnDepth === 2,
|
||||
);
|
||||
expect(spawnDepthPatch?.params?.key).toMatch(/^agent:main:subagent:/);
|
||||
expect(spawnDepthPatch?.params?.subagentRole).toBe("leaf");
|
||||
expect(spawnDepthPatch?.params?.subagentControlScope).toBe("none");
|
||||
});
|
||||
|
||||
it("rejects depth-2 callers when maxSpawnDepth is 2 (using stored spawnDepth on flat keys)", async () => {
|
||||
|
||||
@@ -5,11 +5,6 @@ export type LoadedConfig = ReturnType<(typeof import("../config/config.js"))["lo
|
||||
|
||||
export const callGatewayMock: MockFn = vi.fn();
|
||||
|
||||
vi.mock("@mariozechner/pi-ai/oauth", () => ({
|
||||
getOAuthApiKey: () => undefined,
|
||||
getOAuthProviders: () => [],
|
||||
}));
|
||||
|
||||
const defaultConfig: LoadedConfig = {
|
||||
session: {
|
||||
mainKey: "main",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import {
|
||||
@@ -5,6 +8,7 @@ import {
|
||||
isToolAllowedByPolicyName,
|
||||
resolveEffectiveToolPolicy,
|
||||
resolveSubagentToolPolicy,
|
||||
resolveSubagentToolPolicyForSession,
|
||||
} from "./pi-tools.policy.js";
|
||||
import { createStubTool } from "./test-helpers/pi-tool-stubs.js";
|
||||
|
||||
@@ -165,6 +169,41 @@ describe("resolveSubagentToolPolicy depth awareness", () => {
|
||||
expect(isToolAllowedByPolicyName("sessions_list", policy)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses stored leaf role for flat depth-1 session keys", () => {
|
||||
const storePath = path.join(
|
||||
os.tmpdir(),
|
||||
`openclaw-subagent-policy-${Date.now()}-${Math.random().toString(16).slice(2)}.json`,
|
||||
);
|
||||
fs.mkdirSync(path.dirname(storePath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
storePath,
|
||||
JSON.stringify(
|
||||
{
|
||||
"agent:main:subagent:flat-leaf": {
|
||||
sessionId: "flat-leaf",
|
||||
updatedAt: Date.now(),
|
||||
spawnDepth: 1,
|
||||
subagentRole: "leaf",
|
||||
subagentControlScope: "none",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
"utf-8",
|
||||
);
|
||||
const cfg = {
|
||||
...baseCfg,
|
||||
session: {
|
||||
store: storePath,
|
||||
},
|
||||
} as unknown as OpenClawConfig;
|
||||
|
||||
const policy = resolveSubagentToolPolicyForSession(cfg, "agent:main:subagent:flat-leaf");
|
||||
expect(isToolAllowedByPolicyName("sessions_spawn", policy)).toBe(false);
|
||||
expect(isToolAllowedByPolicyName("subagents", policy)).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults to leaf behavior when no depth is provided", () => {
|
||||
const policy = resolveSubagentToolPolicy(baseCfg);
|
||||
// Default depth=1, maxSpawnDepth=2 → orchestrator
|
||||
|
||||
@@ -11,6 +11,10 @@ import { compileGlobPatterns, matchesAnyGlobPattern } from "./glob-pattern.js";
|
||||
import type { AnyAgentTool } from "./pi-tools.types.js";
|
||||
import { pickSandboxToolPolicy } from "./sandbox-tool-policy.js";
|
||||
import type { SandboxToolPolicy } from "./sandbox.js";
|
||||
import {
|
||||
resolveStoredSubagentCapabilities,
|
||||
type SubagentSessionRole,
|
||||
} from "./subagent-capabilities.js";
|
||||
import { expandToolGroups, normalizeToolName } from "./tool-policy.js";
|
||||
|
||||
function makeToolPolicyMatcher(policy: SandboxToolPolicy) {
|
||||
@@ -89,6 +93,13 @@ function resolveSubagentDenyList(depth: number, maxSpawnDepth: number): string[]
|
||||
return [...SUBAGENT_TOOL_DENY_ALWAYS];
|
||||
}
|
||||
|
||||
function resolveSubagentDenyListForRole(role: SubagentSessionRole): string[] {
|
||||
if (role === "leaf") {
|
||||
return [...SUBAGENT_TOOL_DENY_ALWAYS, ...SUBAGENT_TOOL_DENY_LEAF];
|
||||
}
|
||||
return [...SUBAGENT_TOOL_DENY_ALWAYS];
|
||||
}
|
||||
|
||||
export function resolveSubagentToolPolicy(cfg?: OpenClawConfig, depth?: number): SandboxToolPolicy {
|
||||
const configured = cfg?.tools?.subagents?.tools;
|
||||
const maxSpawnDepth =
|
||||
@@ -108,6 +119,27 @@ export function resolveSubagentToolPolicy(cfg?: OpenClawConfig, depth?: number):
|
||||
return { allow: mergedAllow, deny };
|
||||
}
|
||||
|
||||
export function resolveSubagentToolPolicyForSession(
|
||||
cfg: OpenClawConfig | undefined,
|
||||
sessionKey: string,
|
||||
): SandboxToolPolicy {
|
||||
const configured = cfg?.tools?.subagents?.tools;
|
||||
const capabilities = resolveStoredSubagentCapabilities(sessionKey, { cfg });
|
||||
const allow = Array.isArray(configured?.allow) ? configured.allow : undefined;
|
||||
const alsoAllow = Array.isArray(configured?.alsoAllow) ? configured.alsoAllow : undefined;
|
||||
const explicitAllow = new Set(
|
||||
[...(allow ?? []), ...(alsoAllow ?? [])].map((toolName) => normalizeToolName(toolName)),
|
||||
);
|
||||
const deny = [
|
||||
...resolveSubagentDenyListForRole(capabilities.role).filter(
|
||||
(toolName) => !explicitAllow.has(normalizeToolName(toolName)),
|
||||
),
|
||||
...(Array.isArray(configured?.deny) ? configured.deny : []),
|
||||
];
|
||||
const mergedAllow = allow && alsoAllow ? Array.from(new Set([...allow, ...alsoAllow])) : allow;
|
||||
return { allow: mergedAllow, deny };
|
||||
}
|
||||
|
||||
export function isToolAllowedByPolicyName(name: string, policy?: SandboxToolPolicy): boolean {
|
||||
if (!policy) {
|
||||
return true;
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
isToolAllowedByPolicies,
|
||||
resolveEffectiveToolPolicy,
|
||||
resolveGroupToolPolicy,
|
||||
resolveSubagentToolPolicy,
|
||||
resolveSubagentToolPolicyForSession,
|
||||
} from "./pi-tools.policy.js";
|
||||
import {
|
||||
assertRequiredParams,
|
||||
@@ -45,7 +45,6 @@ import { cleanToolSchemaForGemini, normalizeToolParameters } from "./pi-tools.sc
|
||||
import type { AnyAgentTool } from "./pi-tools.types.js";
|
||||
import type { SandboxContext } from "./sandbox.js";
|
||||
import { isXaiProvider } from "./schema/clean-for-xai.js";
|
||||
import { getSubagentDepthFromSessionStore } from "./subagent-depth.js";
|
||||
import { createToolFsPolicy, resolveToolFsConfig } from "./tool-fs-policy.js";
|
||||
import {
|
||||
applyToolPolicyPipeline,
|
||||
@@ -321,10 +320,7 @@ export function createOpenClawCodingTools(options?: {
|
||||
options?.exec?.scopeKey ?? options?.sessionKey ?? (agentId ? `agent:${agentId}` : undefined);
|
||||
const subagentPolicy =
|
||||
isSubagentSessionKey(options?.sessionKey) && options?.sessionKey
|
||||
? resolveSubagentToolPolicy(
|
||||
options.config,
|
||||
getSubagentDepthFromSessionStore(options.sessionKey, { cfg: options.config }),
|
||||
)
|
||||
? resolveSubagentToolPolicyForSession(options.config, options.sessionKey)
|
||||
: undefined;
|
||||
const allowBackground = isToolAllowedByPolicies("process", [
|
||||
profilePolicyWithAlsoAllow,
|
||||
|
||||
156
src/agents/subagent-capabilities.ts
Normal file
156
src/agents/subagent-capabilities.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH } from "../config/agent-limits.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
|
||||
import { isSubagentSessionKey, parseAgentSessionKey } from "../routing/session-key.js";
|
||||
import { getSubagentDepthFromSessionStore } from "./subagent-depth.js";
|
||||
|
||||
export const SUBAGENT_SESSION_ROLES = ["main", "orchestrator", "leaf"] as const;
|
||||
export type SubagentSessionRole = (typeof SUBAGENT_SESSION_ROLES)[number];
|
||||
|
||||
export const SUBAGENT_CONTROL_SCOPES = ["children", "none"] as const;
|
||||
export type SubagentControlScope = (typeof SUBAGENT_CONTROL_SCOPES)[number];
|
||||
|
||||
type SessionCapabilityEntry = {
|
||||
sessionId?: unknown;
|
||||
spawnDepth?: unknown;
|
||||
subagentRole?: unknown;
|
||||
subagentControlScope?: unknown;
|
||||
};
|
||||
|
||||
function normalizeSessionKey(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
function normalizeSubagentRole(value: unknown): SubagentSessionRole | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim().toLowerCase();
|
||||
return SUBAGENT_SESSION_ROLES.find((entry) => entry === trimmed);
|
||||
}
|
||||
|
||||
function normalizeSubagentControlScope(value: unknown): SubagentControlScope | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim().toLowerCase();
|
||||
return SUBAGENT_CONTROL_SCOPES.find((entry) => entry === trimmed);
|
||||
}
|
||||
|
||||
function readSessionStore(storePath: string): Record<string, SessionCapabilityEntry> {
|
||||
try {
|
||||
return loadSessionStore(storePath);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function findEntryBySessionId(
|
||||
store: Record<string, SessionCapabilityEntry>,
|
||||
sessionId: string,
|
||||
): SessionCapabilityEntry | undefined {
|
||||
const normalizedSessionId = normalizeSessionKey(sessionId);
|
||||
if (!normalizedSessionId) {
|
||||
return undefined;
|
||||
}
|
||||
for (const entry of Object.values(store)) {
|
||||
const candidateSessionId = normalizeSessionKey(entry?.sessionId);
|
||||
if (candidateSessionId === normalizedSessionId) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveSessionCapabilityEntry(params: {
|
||||
sessionKey: string;
|
||||
cfg?: OpenClawConfig;
|
||||
store?: Record<string, SessionCapabilityEntry>;
|
||||
}): SessionCapabilityEntry | undefined {
|
||||
if (params.store) {
|
||||
return params.store[params.sessionKey] ?? findEntryBySessionId(params.store, params.sessionKey);
|
||||
}
|
||||
if (!params.cfg) {
|
||||
return undefined;
|
||||
}
|
||||
const parsed = parseAgentSessionKey(params.sessionKey);
|
||||
if (!parsed?.agentId) {
|
||||
return undefined;
|
||||
}
|
||||
const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId });
|
||||
const store = readSessionStore(storePath);
|
||||
return store[params.sessionKey] ?? findEntryBySessionId(store, params.sessionKey);
|
||||
}
|
||||
|
||||
export function resolveSubagentRoleForDepth(params: {
|
||||
depth: number;
|
||||
maxSpawnDepth?: number;
|
||||
}): SubagentSessionRole {
|
||||
const depth = Number.isInteger(params.depth) ? Math.max(0, params.depth) : 0;
|
||||
const maxSpawnDepth =
|
||||
typeof params.maxSpawnDepth === "number" && Number.isFinite(params.maxSpawnDepth)
|
||||
? Math.max(1, Math.floor(params.maxSpawnDepth))
|
||||
: DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH;
|
||||
if (depth <= 0) {
|
||||
return "main";
|
||||
}
|
||||
return depth < maxSpawnDepth ? "orchestrator" : "leaf";
|
||||
}
|
||||
|
||||
export function resolveSubagentControlScopeForRole(
|
||||
role: SubagentSessionRole,
|
||||
): SubagentControlScope {
|
||||
return role === "leaf" ? "none" : "children";
|
||||
}
|
||||
|
||||
export function resolveSubagentCapabilities(params: { depth: number; maxSpawnDepth?: number }) {
|
||||
const role = resolveSubagentRoleForDepth(params);
|
||||
const controlScope = resolveSubagentControlScopeForRole(role);
|
||||
return {
|
||||
depth: Math.max(0, Math.floor(params.depth)),
|
||||
role,
|
||||
controlScope,
|
||||
canSpawn: role === "main" || role === "orchestrator",
|
||||
canControlChildren: controlScope === "children",
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveStoredSubagentCapabilities(
|
||||
sessionKey: string | undefined | null,
|
||||
opts?: {
|
||||
cfg?: OpenClawConfig;
|
||||
store?: Record<string, SessionCapabilityEntry>;
|
||||
},
|
||||
) {
|
||||
const normalizedSessionKey = normalizeSessionKey(sessionKey);
|
||||
const maxSpawnDepth =
|
||||
opts?.cfg?.agents?.defaults?.subagents?.maxSpawnDepth ?? DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH;
|
||||
const depth = getSubagentDepthFromSessionStore(normalizedSessionKey, {
|
||||
cfg: opts?.cfg,
|
||||
store: opts?.store,
|
||||
});
|
||||
if (!normalizedSessionKey || !isSubagentSessionKey(normalizedSessionKey)) {
|
||||
return resolveSubagentCapabilities({ depth, maxSpawnDepth });
|
||||
}
|
||||
const entry = resolveSessionCapabilityEntry({
|
||||
sessionKey: normalizedSessionKey,
|
||||
cfg: opts?.cfg,
|
||||
store: opts?.store,
|
||||
});
|
||||
const storedRole = normalizeSubagentRole(entry?.subagentRole);
|
||||
const storedControlScope = normalizeSubagentControlScope(entry?.subagentControlScope);
|
||||
const fallback = resolveSubagentCapabilities({ depth, maxSpawnDepth });
|
||||
const role = storedRole ?? fallback.role;
|
||||
const controlScope = storedControlScope ?? resolveSubagentControlScopeForRole(role);
|
||||
return {
|
||||
depth,
|
||||
role,
|
||||
controlScope,
|
||||
canSpawn: role === "main" || role === "orchestrator",
|
||||
canControlChildren: controlScope === "children",
|
||||
};
|
||||
}
|
||||
768
src/agents/subagent-control.ts
Normal file
768
src/agents/subagent-control.ts
Normal file
@@ -0,0 +1,768 @@
|
||||
import crypto from "node:crypto";
|
||||
import { clearSessionQueues } from "../auto-reply/reply/queue.js";
|
||||
import {
|
||||
resolveSubagentLabel,
|
||||
resolveSubagentTargetFromRuns,
|
||||
sortSubagentRuns,
|
||||
type SubagentTargetResolution,
|
||||
} from "../auto-reply/reply/subagents-utils.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import type { SessionEntry } from "../config/sessions.js";
|
||||
import { loadSessionStore, resolveStorePath, updateSessionStore } from "../config/sessions.js";
|
||||
import { callGateway } from "../gateway/call.js";
|
||||
import { logVerbose } from "../globals.js";
|
||||
import {
|
||||
isSubagentSessionKey,
|
||||
parseAgentSessionKey,
|
||||
type ParsedAgentSessionKey,
|
||||
} from "../routing/session-key.js";
|
||||
import {
|
||||
formatDurationCompact,
|
||||
formatTokenUsageDisplay,
|
||||
resolveTotalTokens,
|
||||
truncateLine,
|
||||
} from "../shared/subagents-format.js";
|
||||
import { INTERNAL_MESSAGE_CHANNEL } from "../utils/message-channel.js";
|
||||
import { AGENT_LANE_SUBAGENT } from "./lanes.js";
|
||||
import { abortEmbeddedPiRun } from "./pi-embedded.js";
|
||||
import { resolveStoredSubagentCapabilities } from "./subagent-capabilities.js";
|
||||
import {
|
||||
clearSubagentRunSteerRestart,
|
||||
countPendingDescendantRuns,
|
||||
listSubagentRunsForController,
|
||||
markSubagentRunTerminated,
|
||||
markSubagentRunForSteerRestart,
|
||||
replaceSubagentRunAfterSteer,
|
||||
type SubagentRunRecord,
|
||||
} from "./subagent-registry.js";
|
||||
import {
|
||||
extractAssistantText,
|
||||
resolveInternalSessionKey,
|
||||
resolveMainSessionAlias,
|
||||
stripToolMessages,
|
||||
} from "./tools/sessions-helpers.js";
|
||||
|
||||
export const DEFAULT_RECENT_MINUTES = 30;
|
||||
export const MAX_RECENT_MINUTES = 24 * 60;
|
||||
export const MAX_STEER_MESSAGE_CHARS = 4_000;
|
||||
export const STEER_RATE_LIMIT_MS = 2_000;
|
||||
export const STEER_ABORT_SETTLE_TIMEOUT_MS = 5_000;
|
||||
|
||||
const steerRateLimit = new Map<string, number>();
|
||||
|
||||
export type SessionEntryResolution = {
|
||||
storePath: string;
|
||||
entry: SessionEntry | undefined;
|
||||
};
|
||||
|
||||
export type ResolvedSubagentController = {
|
||||
controllerSessionKey: string;
|
||||
callerSessionKey: string;
|
||||
callerIsSubagent: boolean;
|
||||
controlScope: "children" | "none";
|
||||
};
|
||||
|
||||
export type SubagentListItem = {
|
||||
index: number;
|
||||
line: string;
|
||||
runId: string;
|
||||
sessionKey: string;
|
||||
label: string;
|
||||
task: string;
|
||||
status: string;
|
||||
pendingDescendants: number;
|
||||
runtime: string;
|
||||
runtimeMs: number;
|
||||
model?: string;
|
||||
totalTokens?: number;
|
||||
startedAt?: number;
|
||||
endedAt?: number;
|
||||
};
|
||||
|
||||
export type BuiltSubagentList = {
|
||||
total: number;
|
||||
active: SubagentListItem[];
|
||||
recent: SubagentListItem[];
|
||||
text: string;
|
||||
};
|
||||
|
||||
function resolveStorePathForKey(
|
||||
cfg: OpenClawConfig,
|
||||
key: string,
|
||||
parsed?: ParsedAgentSessionKey | null,
|
||||
) {
|
||||
return resolveStorePath(cfg.session?.store, {
|
||||
agentId: parsed?.agentId,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveSessionEntryForKey(params: {
|
||||
cfg: OpenClawConfig;
|
||||
key: string;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
}): SessionEntryResolution {
|
||||
const parsed = parseAgentSessionKey(params.key);
|
||||
const storePath = resolveStorePathForKey(params.cfg, params.key, parsed);
|
||||
let store = params.cache.get(storePath);
|
||||
if (!store) {
|
||||
store = loadSessionStore(storePath);
|
||||
params.cache.set(storePath, store);
|
||||
}
|
||||
return {
|
||||
storePath,
|
||||
entry: store[params.key],
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSubagentController(params: {
|
||||
cfg: OpenClawConfig;
|
||||
agentSessionKey?: string;
|
||||
}): ResolvedSubagentController {
|
||||
const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
|
||||
const callerRaw = params.agentSessionKey?.trim() || alias;
|
||||
const callerSessionKey = resolveInternalSessionKey({
|
||||
key: callerRaw,
|
||||
alias,
|
||||
mainKey,
|
||||
});
|
||||
if (!isSubagentSessionKey(callerSessionKey)) {
|
||||
return {
|
||||
controllerSessionKey: callerSessionKey,
|
||||
callerSessionKey,
|
||||
callerIsSubagent: false,
|
||||
controlScope: "children",
|
||||
};
|
||||
}
|
||||
const capabilities = resolveStoredSubagentCapabilities(callerSessionKey, {
|
||||
cfg: params.cfg,
|
||||
});
|
||||
return {
|
||||
controllerSessionKey: callerSessionKey,
|
||||
callerSessionKey,
|
||||
callerIsSubagent: true,
|
||||
controlScope: capabilities.controlScope,
|
||||
};
|
||||
}
|
||||
|
||||
export function listControlledSubagentRuns(controllerSessionKey: string): SubagentRunRecord[] {
|
||||
return sortSubagentRuns(listSubagentRunsForController(controllerSessionKey));
|
||||
}
|
||||
|
||||
export function createPendingDescendantCounter() {
|
||||
const pendingDescendantCache = new Map<string, number>();
|
||||
return (sessionKey: string) => {
|
||||
if (pendingDescendantCache.has(sessionKey)) {
|
||||
return pendingDescendantCache.get(sessionKey) ?? 0;
|
||||
}
|
||||
const pending = Math.max(0, countPendingDescendantRuns(sessionKey));
|
||||
pendingDescendantCache.set(sessionKey, pending);
|
||||
return pending;
|
||||
};
|
||||
}
|
||||
|
||||
export function isActiveSubagentRun(
|
||||
entry: SubagentRunRecord,
|
||||
pendingDescendantCount: (sessionKey: string) => number,
|
||||
) {
|
||||
return !entry.endedAt || pendingDescendantCount(entry.childSessionKey) > 0;
|
||||
}
|
||||
|
||||
function resolveRunStatus(entry: SubagentRunRecord, options?: { pendingDescendants?: number }) {
|
||||
const pendingDescendants = Math.max(0, options?.pendingDescendants ?? 0);
|
||||
if (pendingDescendants > 0) {
|
||||
const childLabel = pendingDescendants === 1 ? "child" : "children";
|
||||
return `active (waiting on ${pendingDescendants} ${childLabel})`;
|
||||
}
|
||||
if (!entry.endedAt) {
|
||||
return "running";
|
||||
}
|
||||
const status = entry.outcome?.status ?? "done";
|
||||
if (status === "ok") {
|
||||
return "done";
|
||||
}
|
||||
if (status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
function resolveModelRef(entry?: SessionEntry) {
|
||||
const model = typeof entry?.model === "string" ? entry.model.trim() : "";
|
||||
const provider = typeof entry?.modelProvider === "string" ? entry.modelProvider.trim() : "";
|
||||
if (model.includes("/")) {
|
||||
return model;
|
||||
}
|
||||
if (model && provider) {
|
||||
return `${provider}/${model}`;
|
||||
}
|
||||
if (model) {
|
||||
return model;
|
||||
}
|
||||
if (provider) {
|
||||
return provider;
|
||||
}
|
||||
const overrideModel = typeof entry?.modelOverride === "string" ? entry.modelOverride.trim() : "";
|
||||
const overrideProvider =
|
||||
typeof entry?.providerOverride === "string" ? entry.providerOverride.trim() : "";
|
||||
if (overrideModel.includes("/")) {
|
||||
return overrideModel;
|
||||
}
|
||||
if (overrideModel && overrideProvider) {
|
||||
return `${overrideProvider}/${overrideModel}`;
|
||||
}
|
||||
if (overrideModel) {
|
||||
return overrideModel;
|
||||
}
|
||||
return overrideProvider || undefined;
|
||||
}
|
||||
|
||||
function resolveModelDisplay(entry?: SessionEntry, fallbackModel?: string) {
|
||||
const modelRef = resolveModelRef(entry) || fallbackModel || undefined;
|
||||
if (!modelRef) {
|
||||
return "model n/a";
|
||||
}
|
||||
const slash = modelRef.lastIndexOf("/");
|
||||
if (slash >= 0 && slash < modelRef.length - 1) {
|
||||
return modelRef.slice(slash + 1);
|
||||
}
|
||||
return modelRef;
|
||||
}
|
||||
|
||||
function buildListText(params: {
|
||||
active: Array<{ line: string }>;
|
||||
recent: Array<{ line: string }>;
|
||||
recentMinutes: number;
|
||||
}) {
|
||||
const lines: string[] = [];
|
||||
lines.push("active subagents:");
|
||||
if (params.active.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(...params.active.map((entry) => entry.line));
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(`recent (last ${params.recentMinutes}m):`);
|
||||
if (params.recent.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(...params.recent.map((entry) => entry.line));
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function buildSubagentList(params: {
|
||||
cfg: OpenClawConfig;
|
||||
runs: SubagentRunRecord[];
|
||||
recentMinutes: number;
|
||||
taskMaxChars?: number;
|
||||
}): BuiltSubagentList {
|
||||
const now = Date.now();
|
||||
const recentCutoff = now - params.recentMinutes * 60_000;
|
||||
const cache = new Map<string, Record<string, SessionEntry>>();
|
||||
const pendingDescendantCount = createPendingDescendantCounter();
|
||||
let index = 1;
|
||||
const buildListEntry = (entry: SubagentRunRecord, runtimeMs: number) => {
|
||||
const sessionEntry = resolveSessionEntryForKey({
|
||||
cfg: params.cfg,
|
||||
key: entry.childSessionKey,
|
||||
cache,
|
||||
}).entry;
|
||||
const totalTokens = resolveTotalTokens(sessionEntry);
|
||||
const usageText = formatTokenUsageDisplay(sessionEntry);
|
||||
const pendingDescendants = pendingDescendantCount(entry.childSessionKey);
|
||||
const status = resolveRunStatus(entry, {
|
||||
pendingDescendants,
|
||||
});
|
||||
const runtime = formatDurationCompact(runtimeMs);
|
||||
const label = truncateLine(resolveSubagentLabel(entry), 48);
|
||||
const task = truncateLine(entry.task.trim(), params.taskMaxChars ?? 72);
|
||||
const line = `${index}. ${label} (${resolveModelDisplay(sessionEntry, entry.model)}, ${runtime}${usageText ? `, ${usageText}` : ""}) ${status}${task.toLowerCase() !== label.toLowerCase() ? ` - ${task}` : ""}`;
|
||||
const view: SubagentListItem = {
|
||||
index,
|
||||
line,
|
||||
runId: entry.runId,
|
||||
sessionKey: entry.childSessionKey,
|
||||
label,
|
||||
task,
|
||||
status,
|
||||
pendingDescendants,
|
||||
runtime,
|
||||
runtimeMs,
|
||||
model: resolveModelRef(sessionEntry) || entry.model,
|
||||
totalTokens,
|
||||
startedAt: entry.startedAt,
|
||||
...(entry.endedAt ? { endedAt: entry.endedAt } : {}),
|
||||
};
|
||||
index += 1;
|
||||
return view;
|
||||
};
|
||||
const active = params.runs
|
||||
.filter((entry) => isActiveSubagentRun(entry, pendingDescendantCount))
|
||||
.map((entry) => buildListEntry(entry, now - (entry.startedAt ?? entry.createdAt)));
|
||||
const recent = params.runs
|
||||
.filter(
|
||||
(entry) =>
|
||||
!isActiveSubagentRun(entry, pendingDescendantCount) &&
|
||||
!!entry.endedAt &&
|
||||
(entry.endedAt ?? 0) >= recentCutoff,
|
||||
)
|
||||
.map((entry) =>
|
||||
buildListEntry(entry, (entry.endedAt ?? now) - (entry.startedAt ?? entry.createdAt)),
|
||||
);
|
||||
return {
|
||||
total: params.runs.length,
|
||||
active,
|
||||
recent,
|
||||
text: buildListText({ active, recent, recentMinutes: params.recentMinutes }),
|
||||
};
|
||||
}
|
||||
|
||||
function ensureControllerOwnsRun(params: {
|
||||
controller: ResolvedSubagentController;
|
||||
entry: SubagentRunRecord;
|
||||
}) {
|
||||
const owner = params.entry.controllerSessionKey?.trim() || params.entry.requesterSessionKey;
|
||||
if (owner === params.controller.controllerSessionKey) {
|
||||
return undefined;
|
||||
}
|
||||
return "Subagents can only control runs spawned from their own session.";
|
||||
}
|
||||
|
||||
async function killSubagentRun(params: {
|
||||
cfg: OpenClawConfig;
|
||||
entry: SubagentRunRecord;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
}): Promise<{ killed: boolean; sessionId?: string }> {
|
||||
if (params.entry.endedAt) {
|
||||
return { killed: false };
|
||||
}
|
||||
const childSessionKey = params.entry.childSessionKey;
|
||||
const resolved = resolveSessionEntryForKey({
|
||||
cfg: params.cfg,
|
||||
key: childSessionKey,
|
||||
cache: params.cache,
|
||||
});
|
||||
const sessionId = resolved.entry?.sessionId;
|
||||
const aborted = sessionId ? abortEmbeddedPiRun(sessionId) : false;
|
||||
const cleared = clearSessionQueues([childSessionKey, sessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents control kill: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
);
|
||||
}
|
||||
if (resolved.entry) {
|
||||
await updateSessionStore(resolved.storePath, (store) => {
|
||||
const current = store[childSessionKey];
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
current.abortedLastRun = true;
|
||||
current.updatedAt = Date.now();
|
||||
store[childSessionKey] = current;
|
||||
});
|
||||
}
|
||||
const marked = markSubagentRunTerminated({
|
||||
runId: params.entry.runId,
|
||||
childSessionKey,
|
||||
reason: "killed",
|
||||
});
|
||||
const killed = marked > 0 || aborted || cleared.followupCleared > 0 || cleared.laneCleared > 0;
|
||||
return { killed, sessionId };
|
||||
}
|
||||
|
||||
async function cascadeKillChildren(params: {
|
||||
cfg: OpenClawConfig;
|
||||
parentChildSessionKey: string;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
seenChildSessionKeys?: Set<string>;
|
||||
}): Promise<{ killed: number; labels: string[] }> {
|
||||
const childRuns = listSubagentRunsForController(params.parentChildSessionKey);
|
||||
const seenChildSessionKeys = params.seenChildSessionKeys ?? new Set<string>();
|
||||
let killed = 0;
|
||||
const labels: string[] = [];
|
||||
|
||||
for (const run of childRuns) {
|
||||
const childKey = run.childSessionKey?.trim();
|
||||
if (!childKey || seenChildSessionKeys.has(childKey)) {
|
||||
continue;
|
||||
}
|
||||
seenChildSessionKeys.add(childKey);
|
||||
|
||||
if (!run.endedAt) {
|
||||
const stopResult = await killSubagentRun({
|
||||
cfg: params.cfg,
|
||||
entry: run,
|
||||
cache: params.cache,
|
||||
});
|
||||
if (stopResult.killed) {
|
||||
killed += 1;
|
||||
labels.push(resolveSubagentLabel(run));
|
||||
}
|
||||
}
|
||||
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg: params.cfg,
|
||||
parentChildSessionKey: childKey,
|
||||
cache: params.cache,
|
||||
seenChildSessionKeys,
|
||||
});
|
||||
killed += cascade.killed;
|
||||
labels.push(...cascade.labels);
|
||||
}
|
||||
|
||||
return { killed, labels };
|
||||
}
|
||||
|
||||
export async function killAllControlledSubagentRuns(params: {
|
||||
cfg: OpenClawConfig;
|
||||
controller: ResolvedSubagentController;
|
||||
runs: SubagentRunRecord[];
|
||||
}) {
|
||||
if (params.controller.controlScope !== "children") {
|
||||
return {
|
||||
status: "forbidden" as const,
|
||||
error: "Leaf subagents cannot control other sessions.",
|
||||
killed: 0,
|
||||
labels: [],
|
||||
};
|
||||
}
|
||||
const cache = new Map<string, Record<string, SessionEntry>>();
|
||||
const seenChildSessionKeys = new Set<string>();
|
||||
const killedLabels: string[] = [];
|
||||
let killed = 0;
|
||||
for (const entry of params.runs) {
|
||||
const childKey = entry.childSessionKey?.trim();
|
||||
if (!childKey || seenChildSessionKeys.has(childKey)) {
|
||||
continue;
|
||||
}
|
||||
seenChildSessionKeys.add(childKey);
|
||||
|
||||
if (!entry.endedAt) {
|
||||
const stopResult = await killSubagentRun({ cfg: params.cfg, entry, cache });
|
||||
if (stopResult.killed) {
|
||||
killed += 1;
|
||||
killedLabels.push(resolveSubagentLabel(entry));
|
||||
}
|
||||
}
|
||||
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg: params.cfg,
|
||||
parentChildSessionKey: childKey,
|
||||
cache,
|
||||
seenChildSessionKeys,
|
||||
});
|
||||
killed += cascade.killed;
|
||||
killedLabels.push(...cascade.labels);
|
||||
}
|
||||
return { status: "ok" as const, killed, labels: killedLabels };
|
||||
}
|
||||
|
||||
export async function killControlledSubagentRun(params: {
|
||||
cfg: OpenClawConfig;
|
||||
controller: ResolvedSubagentController;
|
||||
entry: SubagentRunRecord;
|
||||
}) {
|
||||
const ownershipError = ensureControllerOwnsRun({
|
||||
controller: params.controller,
|
||||
entry: params.entry,
|
||||
});
|
||||
if (ownershipError) {
|
||||
return {
|
||||
status: "forbidden" as const,
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: ownershipError,
|
||||
};
|
||||
}
|
||||
if (params.controller.controlScope !== "children") {
|
||||
return {
|
||||
status: "forbidden" as const,
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: "Leaf subagents cannot control other sessions.",
|
||||
};
|
||||
}
|
||||
const killCache = new Map<string, Record<string, SessionEntry>>();
|
||||
const stopResult = await killSubagentRun({
|
||||
cfg: params.cfg,
|
||||
entry: params.entry,
|
||||
cache: killCache,
|
||||
});
|
||||
const seenChildSessionKeys = new Set<string>();
|
||||
const targetChildKey = params.entry.childSessionKey?.trim();
|
||||
if (targetChildKey) {
|
||||
seenChildSessionKeys.add(targetChildKey);
|
||||
}
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg: params.cfg,
|
||||
parentChildSessionKey: params.entry.childSessionKey,
|
||||
cache: killCache,
|
||||
seenChildSessionKeys,
|
||||
});
|
||||
if (!stopResult.killed && cascade.killed === 0) {
|
||||
return {
|
||||
status: "done" as const,
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
label: resolveSubagentLabel(params.entry),
|
||||
text: `${resolveSubagentLabel(params.entry)} is already finished.`,
|
||||
};
|
||||
}
|
||||
const cascadeText =
|
||||
cascade.killed > 0 ? ` (+ ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"})` : "";
|
||||
return {
|
||||
status: "ok" as const,
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
label: resolveSubagentLabel(params.entry),
|
||||
cascadeKilled: cascade.killed,
|
||||
cascadeLabels: cascade.killed > 0 ? cascade.labels : undefined,
|
||||
text: stopResult.killed
|
||||
? `killed ${resolveSubagentLabel(params.entry)}${cascadeText}.`
|
||||
: `killed ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"} of ${resolveSubagentLabel(params.entry)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function steerControlledSubagentRun(params: {
|
||||
cfg: OpenClawConfig;
|
||||
controller: ResolvedSubagentController;
|
||||
entry: SubagentRunRecord;
|
||||
message: string;
|
||||
}): Promise<
|
||||
| {
|
||||
status: "forbidden" | "done" | "rate_limited" | "error";
|
||||
runId?: string;
|
||||
sessionKey: string;
|
||||
sessionId?: string;
|
||||
error?: string;
|
||||
text?: string;
|
||||
}
|
||||
| {
|
||||
status: "accepted";
|
||||
runId: string;
|
||||
sessionKey: string;
|
||||
sessionId?: string;
|
||||
mode: "restart";
|
||||
label: string;
|
||||
text: string;
|
||||
}
|
||||
> {
|
||||
const ownershipError = ensureControllerOwnsRun({
|
||||
controller: params.controller,
|
||||
entry: params.entry,
|
||||
});
|
||||
if (ownershipError) {
|
||||
return {
|
||||
status: "forbidden",
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: ownershipError,
|
||||
};
|
||||
}
|
||||
if (params.controller.controlScope !== "children") {
|
||||
return {
|
||||
status: "forbidden",
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: "Leaf subagents cannot control other sessions.",
|
||||
};
|
||||
}
|
||||
if (params.entry.endedAt) {
|
||||
return {
|
||||
status: "done",
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
text: `${resolveSubagentLabel(params.entry)} is already finished.`,
|
||||
};
|
||||
}
|
||||
if (params.controller.callerSessionKey === params.entry.childSessionKey) {
|
||||
return {
|
||||
status: "forbidden",
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: "Subagents cannot steer themselves.",
|
||||
};
|
||||
}
|
||||
|
||||
const rateKey = `${params.controller.callerSessionKey}:${params.entry.childSessionKey}`;
|
||||
if (process.env.VITEST !== "true") {
|
||||
const now = Date.now();
|
||||
const lastSentAt = steerRateLimit.get(rateKey) ?? 0;
|
||||
if (now - lastSentAt < STEER_RATE_LIMIT_MS) {
|
||||
return {
|
||||
status: "rate_limited",
|
||||
runId: params.entry.runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
error: "Steer rate limit exceeded. Wait a moment before sending another steer.",
|
||||
};
|
||||
}
|
||||
steerRateLimit.set(rateKey, now);
|
||||
}
|
||||
|
||||
markSubagentRunForSteerRestart(params.entry.runId);
|
||||
|
||||
const targetSession = resolveSessionEntryForKey({
|
||||
cfg: params.cfg,
|
||||
key: params.entry.childSessionKey,
|
||||
cache: new Map<string, Record<string, SessionEntry>>(),
|
||||
});
|
||||
const sessionId =
|
||||
typeof targetSession.entry?.sessionId === "string" && targetSession.entry.sessionId.trim()
|
||||
? targetSession.entry.sessionId.trim()
|
||||
: undefined;
|
||||
|
||||
if (sessionId) {
|
||||
abortEmbeddedPiRun(sessionId);
|
||||
}
|
||||
const cleared = clearSessionQueues([params.entry.childSessionKey, sessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents control steer: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await callGateway({
|
||||
method: "agent.wait",
|
||||
params: {
|
||||
runId: params.entry.runId,
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS,
|
||||
},
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS + 2_000,
|
||||
});
|
||||
} catch {
|
||||
// Continue even if wait fails; steer should still be attempted.
|
||||
}
|
||||
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
let runId: string = idempotencyKey;
|
||||
try {
|
||||
const response = await callGateway<{ runId: string }>({
|
||||
method: "agent",
|
||||
params: {
|
||||
message: params.message,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
sessionId,
|
||||
idempotencyKey,
|
||||
deliver: false,
|
||||
channel: INTERNAL_MESSAGE_CHANNEL,
|
||||
lane: AGENT_LANE_SUBAGENT,
|
||||
timeout: 0,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (typeof response?.runId === "string" && response.runId) {
|
||||
runId = response.runId;
|
||||
}
|
||||
} catch (err) {
|
||||
clearSubagentRunSteerRestart(params.entry.runId);
|
||||
const error = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
status: "error",
|
||||
runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
sessionId,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
replaceSubagentRunAfterSteer({
|
||||
previousRunId: params.entry.runId,
|
||||
nextRunId: runId,
|
||||
fallback: params.entry,
|
||||
runTimeoutSeconds: params.entry.runTimeoutSeconds ?? 0,
|
||||
});
|
||||
|
||||
return {
|
||||
status: "accepted",
|
||||
runId,
|
||||
sessionKey: params.entry.childSessionKey,
|
||||
sessionId,
|
||||
mode: "restart",
|
||||
label: resolveSubagentLabel(params.entry),
|
||||
text: `steered ${resolveSubagentLabel(params.entry)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function sendControlledSubagentMessage(params: {
|
||||
cfg: OpenClawConfig;
|
||||
entry: SubagentRunRecord;
|
||||
message: string;
|
||||
}) {
|
||||
const targetSessionKey = params.entry.childSessionKey;
|
||||
const parsed = parseAgentSessionKey(targetSessionKey);
|
||||
const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed?.agentId });
|
||||
const store = loadSessionStore(storePath);
|
||||
const targetSessionEntry = store[targetSessionKey];
|
||||
const targetSessionId =
|
||||
typeof targetSessionEntry?.sessionId === "string" && targetSessionEntry.sessionId.trim()
|
||||
? targetSessionEntry.sessionId.trim()
|
||||
: undefined;
|
||||
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
let runId: string = idempotencyKey;
|
||||
const response = await callGateway<{ runId: string }>({
|
||||
method: "agent",
|
||||
params: {
|
||||
message: params.message,
|
||||
sessionKey: targetSessionKey,
|
||||
sessionId: targetSessionId,
|
||||
idempotencyKey,
|
||||
deliver: false,
|
||||
channel: INTERNAL_MESSAGE_CHANNEL,
|
||||
lane: AGENT_LANE_SUBAGENT,
|
||||
timeout: 0,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const responseRunId = typeof response?.runId === "string" ? response.runId : undefined;
|
||||
if (responseRunId) {
|
||||
runId = responseRunId;
|
||||
}
|
||||
|
||||
const waitMs = 30_000;
|
||||
const wait = await callGateway<{ status?: string; error?: string }>({
|
||||
method: "agent.wait",
|
||||
params: { runId, timeoutMs: waitMs },
|
||||
timeoutMs: waitMs + 2_000,
|
||||
});
|
||||
if (wait?.status === "timeout") {
|
||||
return { status: "timeout" as const, runId };
|
||||
}
|
||||
if (wait?.status === "error") {
|
||||
const waitError = typeof wait.error === "string" ? wait.error : "unknown error";
|
||||
return { status: "error" as const, runId, error: waitError };
|
||||
}
|
||||
|
||||
const history = await callGateway<{ messages: Array<unknown> }>({
|
||||
method: "chat.history",
|
||||
params: { sessionKey: targetSessionKey, limit: 50 },
|
||||
});
|
||||
const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
|
||||
const last = filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
|
||||
const replyText = last ? extractAssistantText(last) : undefined;
|
||||
return { status: "ok" as const, runId, replyText };
|
||||
}
|
||||
|
||||
export function resolveControlledSubagentTarget(
|
||||
runs: SubagentRunRecord[],
|
||||
token: string | undefined,
|
||||
options?: { recentMinutes?: number; isActive?: (entry: SubagentRunRecord) => boolean },
|
||||
): SubagentTargetResolution {
|
||||
return resolveSubagentTargetFromRuns({
|
||||
runs,
|
||||
token,
|
||||
recentWindowMinutes: options?.recentMinutes ?? DEFAULT_RECENT_MINUTES,
|
||||
label: (entry) => resolveSubagentLabel(entry),
|
||||
isActive: options?.isActive,
|
||||
errors: {
|
||||
missingTarget: "Missing subagent target.",
|
||||
invalidIndex: (value) => `Invalid subagent index: ${value}`,
|
||||
unknownSession: (value) => `Unknown subagent session: ${value}`,
|
||||
ambiguousLabel: (value) => `Ambiguous subagent label: ${value}`,
|
||||
ambiguousLabelPrefix: (value) => `Ambiguous subagent label prefix: ${value}`,
|
||||
ambiguousRunIdPrefix: (value) => `Ambiguous subagent run id prefix: ${value}`,
|
||||
unknownTarget: (value) => `Unknown subagent target: ${value}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { DeliveryContext } from "../utils/delivery-context.js";
|
||||
import type { SubagentRunRecord } from "./subagent-registry.types.js";
|
||||
|
||||
function resolveControllerSessionKey(entry: SubagentRunRecord): string {
|
||||
return entry.controllerSessionKey?.trim() || entry.requesterSessionKey;
|
||||
}
|
||||
|
||||
export function findRunIdsByChildSessionKeyFromRuns(
|
||||
runs: Map<string, SubagentRunRecord>,
|
||||
childSessionKey: string,
|
||||
@@ -51,6 +55,17 @@ export function listRunsForRequesterFromRuns(
|
||||
});
|
||||
}
|
||||
|
||||
export function listRunsForControllerFromRuns(
|
||||
runs: Map<string, SubagentRunRecord>,
|
||||
controllerSessionKey: string,
|
||||
): SubagentRunRecord[] {
|
||||
const key = controllerSessionKey.trim();
|
||||
if (!key) {
|
||||
return [];
|
||||
}
|
||||
return [...runs.values()].filter((entry) => resolveControllerSessionKey(entry) === key);
|
||||
}
|
||||
|
||||
function findLatestRunForChildSession(
|
||||
runs: Map<string, SubagentRunRecord>,
|
||||
childSessionKey: string,
|
||||
@@ -104,9 +119,9 @@ export function shouldIgnorePostCompletionAnnounceForSessionFromRuns(
|
||||
|
||||
export function countActiveRunsForSessionFromRuns(
|
||||
runs: Map<string, SubagentRunRecord>,
|
||||
requesterSessionKey: string,
|
||||
controllerSessionKey: string,
|
||||
): number {
|
||||
const key = requesterSessionKey.trim();
|
||||
const key = controllerSessionKey.trim();
|
||||
if (!key) {
|
||||
return 0;
|
||||
}
|
||||
@@ -123,7 +138,7 @@ export function countActiveRunsForSessionFromRuns(
|
||||
|
||||
let count = 0;
|
||||
for (const entry of runs.values()) {
|
||||
if (entry.requesterSessionKey !== key) {
|
||||
if (resolveControllerSessionKey(entry) !== key) {
|
||||
continue;
|
||||
}
|
||||
if (typeof entry.endedAt !== "number") {
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
countPendingDescendantRunsExcludingRunFromRuns,
|
||||
countPendingDescendantRunsFromRuns,
|
||||
findRunIdsByChildSessionKeyFromRuns,
|
||||
listRunsForControllerFromRuns,
|
||||
listDescendantRunsForRequesterFromRuns,
|
||||
listRunsForRequesterFromRuns,
|
||||
resolveRequesterForChildSessionFromRuns,
|
||||
@@ -1146,6 +1147,7 @@ export function replaceSubagentRunAfterSteer(params: {
|
||||
export function registerSubagentRun(params: {
|
||||
runId: string;
|
||||
childSessionKey: string;
|
||||
controllerSessionKey?: string;
|
||||
requesterSessionKey: string;
|
||||
requesterOrigin?: DeliveryContext;
|
||||
requesterDisplayKey: string;
|
||||
@@ -1173,6 +1175,7 @@ export function registerSubagentRun(params: {
|
||||
subagentRuns.set(params.runId, {
|
||||
runId: params.runId,
|
||||
childSessionKey: params.childSessionKey,
|
||||
controllerSessionKey: params.controllerSessionKey ?? params.requesterSessionKey,
|
||||
requesterSessionKey: params.requesterSessionKey,
|
||||
requesterOrigin,
|
||||
requesterDisplayKey: params.requesterDisplayKey,
|
||||
@@ -1419,6 +1422,13 @@ export function listSubagentRunsForRequester(
|
||||
return listRunsForRequesterFromRuns(subagentRuns, requesterSessionKey, options);
|
||||
}
|
||||
|
||||
export function listSubagentRunsForController(controllerSessionKey: string): SubagentRunRecord[] {
|
||||
return listRunsForControllerFromRuns(
|
||||
getSubagentRunsSnapshotForRead(subagentRuns),
|
||||
controllerSessionKey,
|
||||
);
|
||||
}
|
||||
|
||||
export function countActiveRunsForSession(requesterSessionKey: string): number {
|
||||
return countActiveRunsForSessionFromRuns(
|
||||
getSubagentRunsSnapshotForRead(subagentRuns),
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { SpawnSubagentMode } from "./subagent-spawn.js";
|
||||
export type SubagentRunRecord = {
|
||||
runId: string;
|
||||
childSessionKey: string;
|
||||
controllerSessionKey?: string;
|
||||
requesterSessionKey: string;
|
||||
requesterOrigin?: DeliveryContext;
|
||||
requesterDisplayKey: string;
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
materializeSubagentAttachments,
|
||||
type SubagentAttachmentReceiptFile,
|
||||
} from "./subagent-attachments.js";
|
||||
import { resolveSubagentCapabilities } from "./subagent-capabilities.js";
|
||||
import { getSubagentDepthFromSessionStore } from "./subagent-depth.js";
|
||||
import { countActiveRunsForSession, registerSubagentRun } from "./subagent-registry.js";
|
||||
import { readStringParam } from "./tools/common.js";
|
||||
@@ -376,6 +377,10 @@ export async function spawnSubagentDirect(
|
||||
}
|
||||
const childDepth = callerDepth + 1;
|
||||
const spawnedByKey = requesterInternalKey;
|
||||
const childCapabilities = resolveSubagentCapabilities({
|
||||
depth: childDepth,
|
||||
maxSpawnDepth,
|
||||
});
|
||||
const targetAgentConfig = resolveAgentConfig(cfg, targetAgentId);
|
||||
const resolvedModel = resolveSubagentSpawnModelSelection({
|
||||
cfg,
|
||||
@@ -414,7 +419,11 @@ export async function spawnSubagentDirect(
|
||||
}
|
||||
};
|
||||
|
||||
const spawnDepthPatchError = await patchChildSession({ spawnDepth: childDepth });
|
||||
const spawnDepthPatchError = await patchChildSession({
|
||||
spawnDepth: childDepth,
|
||||
subagentRole: childCapabilities.role === "main" ? null : childCapabilities.role,
|
||||
subagentControlScope: childCapabilities.controlScope,
|
||||
});
|
||||
if (spawnDepthPatchError) {
|
||||
return {
|
||||
status: "error",
|
||||
@@ -643,6 +652,7 @@ export async function spawnSubagentDirect(
|
||||
registerSubagentRun({
|
||||
runId: childRunId,
|
||||
childSessionKey,
|
||||
controllerSessionKey: requesterInternalKey,
|
||||
requesterSessionKey: requesterInternalKey,
|
||||
requesterOrigin,
|
||||
requesterDisplayKey,
|
||||
|
||||
@@ -97,11 +97,11 @@ describe("createNodesTool screen_record duration guardrails", () => {
|
||||
if (payload?.command === "system.run.prepare") {
|
||||
return {
|
||||
payload: {
|
||||
cmdText: "echo hi",
|
||||
plan: {
|
||||
argv: ["bash", "-lc", "echo hi"],
|
||||
cwd: null,
|
||||
rawCommand: null,
|
||||
commandText: 'bash -lc "echo hi"',
|
||||
commandPreview: "echo hi",
|
||||
agentId: null,
|
||||
sessionKey: null,
|
||||
},
|
||||
|
||||
@@ -664,7 +664,7 @@ export function createNodesTool(options?: {
|
||||
}
|
||||
const runParams = {
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand ?? prepared.cmdText,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
cwd: prepared.plan.cwd ?? cwd,
|
||||
env,
|
||||
timeoutMs: commandTimeoutMs,
|
||||
@@ -699,8 +699,6 @@ export function createNodesTool(options?: {
|
||||
{ ...gatewayOpts, timeoutMs: APPROVAL_TIMEOUT_MS + 5_000 },
|
||||
{
|
||||
id: approvalId,
|
||||
command: prepared.cmdText,
|
||||
commandArgv: prepared.plan.argv,
|
||||
systemRunPlan: prepared.plan,
|
||||
cwd: prepared.plan.cwd ?? cwd,
|
||||
nodeId,
|
||||
|
||||
@@ -1,56 +1,26 @@
|
||||
import crypto from "node:crypto";
|
||||
import { Type } from "@sinclair/typebox";
|
||||
import { clearSessionQueues } from "../../auto-reply/reply/queue.js";
|
||||
import {
|
||||
resolveSubagentLabel,
|
||||
resolveSubagentTargetFromRuns,
|
||||
sortSubagentRuns,
|
||||
type SubagentTargetResolution,
|
||||
} from "../../auto-reply/reply/subagents-utils.js";
|
||||
import { loadConfig } from "../../config/config.js";
|
||||
import type { SessionEntry } from "../../config/sessions.js";
|
||||
import { loadSessionStore, resolveStorePath, updateSessionStore } from "../../config/sessions.js";
|
||||
import { callGateway } from "../../gateway/call.js";
|
||||
import { logVerbose } from "../../globals.js";
|
||||
import {
|
||||
isSubagentSessionKey,
|
||||
parseAgentSessionKey,
|
||||
type ParsedAgentSessionKey,
|
||||
} from "../../routing/session-key.js";
|
||||
import {
|
||||
formatDurationCompact,
|
||||
formatTokenUsageDisplay,
|
||||
resolveTotalTokens,
|
||||
truncateLine,
|
||||
} from "../../shared/subagents-format.js";
|
||||
import { INTERNAL_MESSAGE_CHANNEL } from "../../utils/message-channel.js";
|
||||
import { AGENT_LANE_SUBAGENT } from "../lanes.js";
|
||||
import { abortEmbeddedPiRun } from "../pi-embedded.js";
|
||||
import { optionalStringEnum } from "../schema/typebox.js";
|
||||
import {
|
||||
clearSubagentRunSteerRestart,
|
||||
countPendingDescendantRuns,
|
||||
listSubagentRunsForRequester,
|
||||
markSubagentRunTerminated,
|
||||
markSubagentRunForSteerRestart,
|
||||
replaceSubagentRunAfterSteer,
|
||||
type SubagentRunRecord,
|
||||
} from "../subagent-registry.js";
|
||||
buildSubagentList,
|
||||
DEFAULT_RECENT_MINUTES,
|
||||
isActiveSubagentRun,
|
||||
killAllControlledSubagentRuns,
|
||||
killControlledSubagentRun,
|
||||
listControlledSubagentRuns,
|
||||
MAX_RECENT_MINUTES,
|
||||
MAX_STEER_MESSAGE_CHARS,
|
||||
resolveControlledSubagentTarget,
|
||||
resolveSubagentController,
|
||||
steerControlledSubagentRun,
|
||||
createPendingDescendantCounter,
|
||||
} from "../subagent-control.js";
|
||||
import type { AnyAgentTool } from "./common.js";
|
||||
import { jsonResult, readNumberParam, readStringParam } from "./common.js";
|
||||
import { resolveInternalSessionKey, resolveMainSessionAlias } from "./sessions-helpers.js";
|
||||
|
||||
const SUBAGENT_ACTIONS = ["list", "kill", "steer"] as const;
|
||||
type SubagentAction = (typeof SUBAGENT_ACTIONS)[number];
|
||||
|
||||
const DEFAULT_RECENT_MINUTES = 30;
|
||||
const MAX_RECENT_MINUTES = 24 * 60;
|
||||
const MAX_STEER_MESSAGE_CHARS = 4_000;
|
||||
const STEER_RATE_LIMIT_MS = 2_000;
|
||||
const STEER_ABORT_SETTLE_TIMEOUT_MS = 5_000;
|
||||
|
||||
const steerRateLimit = new Map<string, number>();
|
||||
|
||||
const SubagentsToolSchema = Type.Object({
|
||||
action: optionalStringEnum(SUBAGENT_ACTIONS),
|
||||
target: Type.Optional(Type.String()),
|
||||
@@ -58,284 +28,6 @@ const SubagentsToolSchema = Type.Object({
|
||||
recentMinutes: Type.Optional(Type.Number({ minimum: 1 })),
|
||||
});
|
||||
|
||||
type SessionEntryResolution = {
|
||||
storePath: string;
|
||||
entry: SessionEntry | undefined;
|
||||
};
|
||||
|
||||
type ResolvedRequesterKey = {
|
||||
requesterSessionKey: string;
|
||||
callerSessionKey: string;
|
||||
callerIsSubagent: boolean;
|
||||
};
|
||||
|
||||
function resolveRunStatus(entry: SubagentRunRecord, options?: { pendingDescendants?: number }) {
|
||||
const pendingDescendants = Math.max(0, options?.pendingDescendants ?? 0);
|
||||
if (pendingDescendants > 0) {
|
||||
const childLabel = pendingDescendants === 1 ? "child" : "children";
|
||||
return `active (waiting on ${pendingDescendants} ${childLabel})`;
|
||||
}
|
||||
if (!entry.endedAt) {
|
||||
return "running";
|
||||
}
|
||||
const status = entry.outcome?.status ?? "done";
|
||||
if (status === "ok") {
|
||||
return "done";
|
||||
}
|
||||
if (status === "error") {
|
||||
return "failed";
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
function resolveModelRef(entry?: SessionEntry) {
|
||||
const model = typeof entry?.model === "string" ? entry.model.trim() : "";
|
||||
const provider = typeof entry?.modelProvider === "string" ? entry.modelProvider.trim() : "";
|
||||
if (model.includes("/")) {
|
||||
return model;
|
||||
}
|
||||
if (model && provider) {
|
||||
return `${provider}/${model}`;
|
||||
}
|
||||
if (model) {
|
||||
return model;
|
||||
}
|
||||
if (provider) {
|
||||
return provider;
|
||||
}
|
||||
// Fall back to override fields which are populated at spawn time,
|
||||
// before the first run completes and writes model/modelProvider.
|
||||
const overrideModel = typeof entry?.modelOverride === "string" ? entry.modelOverride.trim() : "";
|
||||
const overrideProvider =
|
||||
typeof entry?.providerOverride === "string" ? entry.providerOverride.trim() : "";
|
||||
if (overrideModel.includes("/")) {
|
||||
return overrideModel;
|
||||
}
|
||||
if (overrideModel && overrideProvider) {
|
||||
return `${overrideProvider}/${overrideModel}`;
|
||||
}
|
||||
if (overrideModel) {
|
||||
return overrideModel;
|
||||
}
|
||||
return overrideProvider || undefined;
|
||||
}
|
||||
|
||||
function resolveModelDisplay(entry?: SessionEntry, fallbackModel?: string) {
|
||||
const modelRef = resolveModelRef(entry) || fallbackModel || undefined;
|
||||
if (!modelRef) {
|
||||
return "model n/a";
|
||||
}
|
||||
const slash = modelRef.lastIndexOf("/");
|
||||
if (slash >= 0 && slash < modelRef.length - 1) {
|
||||
return modelRef.slice(slash + 1);
|
||||
}
|
||||
return modelRef;
|
||||
}
|
||||
|
||||
function resolveSubagentTarget(
|
||||
runs: SubagentRunRecord[],
|
||||
token: string | undefined,
|
||||
options?: { recentMinutes?: number; isActive?: (entry: SubagentRunRecord) => boolean },
|
||||
): SubagentTargetResolution {
|
||||
return resolveSubagentTargetFromRuns({
|
||||
runs,
|
||||
token,
|
||||
recentWindowMinutes: options?.recentMinutes ?? DEFAULT_RECENT_MINUTES,
|
||||
label: (entry) => resolveSubagentLabel(entry),
|
||||
isActive: options?.isActive,
|
||||
errors: {
|
||||
missingTarget: "Missing subagent target.",
|
||||
invalidIndex: (value) => `Invalid subagent index: ${value}`,
|
||||
unknownSession: (value) => `Unknown subagent session: ${value}`,
|
||||
ambiguousLabel: (value) => `Ambiguous subagent label: ${value}`,
|
||||
ambiguousLabelPrefix: (value) => `Ambiguous subagent label prefix: ${value}`,
|
||||
ambiguousRunIdPrefix: (value) => `Ambiguous subagent run id prefix: ${value}`,
|
||||
unknownTarget: (value) => `Unknown subagent target: ${value}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function resolveStorePathForKey(
|
||||
cfg: ReturnType<typeof loadConfig>,
|
||||
key: string,
|
||||
parsed?: ParsedAgentSessionKey | null,
|
||||
) {
|
||||
return resolveStorePath(cfg.session?.store, {
|
||||
agentId: parsed?.agentId,
|
||||
});
|
||||
}
|
||||
|
||||
function resolveSessionEntryForKey(params: {
|
||||
cfg: ReturnType<typeof loadConfig>;
|
||||
key: string;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
}): SessionEntryResolution {
|
||||
const parsed = parseAgentSessionKey(params.key);
|
||||
const storePath = resolveStorePathForKey(params.cfg, params.key, parsed);
|
||||
let store = params.cache.get(storePath);
|
||||
if (!store) {
|
||||
store = loadSessionStore(storePath);
|
||||
params.cache.set(storePath, store);
|
||||
}
|
||||
return {
|
||||
storePath,
|
||||
entry: store[params.key],
|
||||
};
|
||||
}
|
||||
|
||||
function resolveRequesterKey(params: {
|
||||
cfg: ReturnType<typeof loadConfig>;
|
||||
agentSessionKey?: string;
|
||||
}): ResolvedRequesterKey {
|
||||
const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
|
||||
const callerRaw = params.agentSessionKey?.trim() || alias;
|
||||
const callerSessionKey = resolveInternalSessionKey({
|
||||
key: callerRaw,
|
||||
alias,
|
||||
mainKey,
|
||||
});
|
||||
if (!isSubagentSessionKey(callerSessionKey)) {
|
||||
return {
|
||||
requesterSessionKey: callerSessionKey,
|
||||
callerSessionKey,
|
||||
callerIsSubagent: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
// Subagents can only control runs spawned from their own session key.
|
||||
// Announce routing still uses SubagentRunRecord.requesterSessionKey elsewhere.
|
||||
requesterSessionKey: callerSessionKey,
|
||||
callerSessionKey,
|
||||
callerIsSubagent: true,
|
||||
};
|
||||
}
|
||||
|
||||
function ensureSubagentControlsOwnDescendants(params: {
|
||||
requester: ResolvedRequesterKey;
|
||||
entry: SubagentRunRecord;
|
||||
}) {
|
||||
if (!params.requester.callerIsSubagent) {
|
||||
return undefined;
|
||||
}
|
||||
if (params.entry.requesterSessionKey === params.requester.callerSessionKey) {
|
||||
return undefined;
|
||||
}
|
||||
return "Subagents can only control runs spawned from their own session.";
|
||||
}
|
||||
|
||||
async function killSubagentRun(params: {
|
||||
cfg: ReturnType<typeof loadConfig>;
|
||||
entry: SubagentRunRecord;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
}): Promise<{ killed: boolean; sessionId?: string }> {
|
||||
if (params.entry.endedAt) {
|
||||
return { killed: false };
|
||||
}
|
||||
const childSessionKey = params.entry.childSessionKey;
|
||||
const resolved = resolveSessionEntryForKey({
|
||||
cfg: params.cfg,
|
||||
key: childSessionKey,
|
||||
cache: params.cache,
|
||||
});
|
||||
const sessionId = resolved.entry?.sessionId;
|
||||
const aborted = sessionId ? abortEmbeddedPiRun(sessionId) : false;
|
||||
const cleared = clearSessionQueues([childSessionKey, sessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents tool kill: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
);
|
||||
}
|
||||
if (resolved.entry) {
|
||||
await updateSessionStore(resolved.storePath, (store) => {
|
||||
const current = store[childSessionKey];
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
current.abortedLastRun = true;
|
||||
current.updatedAt = Date.now();
|
||||
store[childSessionKey] = current;
|
||||
});
|
||||
}
|
||||
const marked = markSubagentRunTerminated({
|
||||
runId: params.entry.runId,
|
||||
childSessionKey,
|
||||
reason: "killed",
|
||||
});
|
||||
const killed = marked > 0 || aborted || cleared.followupCleared > 0 || cleared.laneCleared > 0;
|
||||
return { killed, sessionId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively kill all descendant subagent runs spawned by a given parent session key.
|
||||
* This ensures that when a subagent is killed, all of its children (and their children) are also killed.
|
||||
*/
|
||||
async function cascadeKillChildren(params: {
|
||||
cfg: ReturnType<typeof loadConfig>;
|
||||
parentChildSessionKey: string;
|
||||
cache: Map<string, Record<string, SessionEntry>>;
|
||||
seenChildSessionKeys?: Set<string>;
|
||||
}): Promise<{ killed: number; labels: string[] }> {
|
||||
const childRuns = listSubagentRunsForRequester(params.parentChildSessionKey);
|
||||
const seenChildSessionKeys = params.seenChildSessionKeys ?? new Set<string>();
|
||||
let killed = 0;
|
||||
const labels: string[] = [];
|
||||
|
||||
for (const run of childRuns) {
|
||||
const childKey = run.childSessionKey?.trim();
|
||||
if (!childKey || seenChildSessionKeys.has(childKey)) {
|
||||
continue;
|
||||
}
|
||||
seenChildSessionKeys.add(childKey);
|
||||
|
||||
if (!run.endedAt) {
|
||||
const stopResult = await killSubagentRun({
|
||||
cfg: params.cfg,
|
||||
entry: run,
|
||||
cache: params.cache,
|
||||
});
|
||||
if (stopResult.killed) {
|
||||
killed += 1;
|
||||
labels.push(resolveSubagentLabel(run));
|
||||
}
|
||||
}
|
||||
|
||||
// Recurse for grandchildren even if this parent already ended.
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg: params.cfg,
|
||||
parentChildSessionKey: childKey,
|
||||
cache: params.cache,
|
||||
seenChildSessionKeys,
|
||||
});
|
||||
killed += cascade.killed;
|
||||
labels.push(...cascade.labels);
|
||||
}
|
||||
|
||||
return { killed, labels };
|
||||
}
|
||||
|
||||
function buildListText(params: {
|
||||
active: Array<{ line: string }>;
|
||||
recent: Array<{ line: string }>;
|
||||
recentMinutes: number;
|
||||
}) {
|
||||
const lines: string[] = [];
|
||||
lines.push("active subagents:");
|
||||
if (params.active.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(...params.active.map((entry) => entry.line));
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(`recent (last ${params.recentMinutes}m):`);
|
||||
if (params.recent.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(...params.recent.map((entry) => entry.line));
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function createSubagentsTool(opts?: { agentSessionKey?: string }): AnyAgentTool {
|
||||
return {
|
||||
label: "Subagents",
|
||||
@@ -347,139 +39,69 @@ export function createSubagentsTool(opts?: { agentSessionKey?: string }): AnyAge
|
||||
const params = args as Record<string, unknown>;
|
||||
const action = (readStringParam(params, "action") ?? "list") as SubagentAction;
|
||||
const cfg = loadConfig();
|
||||
const requester = resolveRequesterKey({
|
||||
const controller = resolveSubagentController({
|
||||
cfg,
|
||||
agentSessionKey: opts?.agentSessionKey,
|
||||
});
|
||||
const runs = sortSubagentRuns(listSubagentRunsForRequester(requester.requesterSessionKey));
|
||||
const runs = listControlledSubagentRuns(controller.controllerSessionKey);
|
||||
const recentMinutesRaw = readNumberParam(params, "recentMinutes");
|
||||
const recentMinutes = recentMinutesRaw
|
||||
? Math.max(1, Math.min(MAX_RECENT_MINUTES, Math.floor(recentMinutesRaw)))
|
||||
: DEFAULT_RECENT_MINUTES;
|
||||
const pendingDescendantCache = new Map<string, number>();
|
||||
const pendingDescendantCount = (sessionKey: string) => {
|
||||
if (pendingDescendantCache.has(sessionKey)) {
|
||||
return pendingDescendantCache.get(sessionKey) ?? 0;
|
||||
}
|
||||
const pending = Math.max(0, countPendingDescendantRuns(sessionKey));
|
||||
pendingDescendantCache.set(sessionKey, pending);
|
||||
return pending;
|
||||
};
|
||||
const isActiveRun = (entry: SubagentRunRecord) =>
|
||||
!entry.endedAt || pendingDescendantCount(entry.childSessionKey) > 0;
|
||||
const pendingDescendantCount = createPendingDescendantCounter();
|
||||
const isActive = (entry: (typeof runs)[number]) =>
|
||||
isActiveSubagentRun(entry, pendingDescendantCount);
|
||||
|
||||
if (action === "list") {
|
||||
const now = Date.now();
|
||||
const recentCutoff = now - recentMinutes * 60_000;
|
||||
const cache = new Map<string, Record<string, SessionEntry>>();
|
||||
|
||||
let index = 1;
|
||||
const buildListEntry = (entry: SubagentRunRecord, runtimeMs: number) => {
|
||||
const sessionEntry = resolveSessionEntryForKey({
|
||||
cfg,
|
||||
key: entry.childSessionKey,
|
||||
cache,
|
||||
}).entry;
|
||||
const totalTokens = resolveTotalTokens(sessionEntry);
|
||||
const usageText = formatTokenUsageDisplay(sessionEntry);
|
||||
const pendingDescendants = pendingDescendantCount(entry.childSessionKey);
|
||||
const status = resolveRunStatus(entry, {
|
||||
pendingDescendants,
|
||||
});
|
||||
const runtime = formatDurationCompact(runtimeMs);
|
||||
const label = truncateLine(resolveSubagentLabel(entry), 48);
|
||||
const task = truncateLine(entry.task.trim(), 72);
|
||||
const line = `${index}. ${label} (${resolveModelDisplay(sessionEntry, entry.model)}, ${runtime}${usageText ? `, ${usageText}` : ""}) ${status}${task.toLowerCase() !== label.toLowerCase() ? ` - ${task}` : ""}`;
|
||||
const baseView = {
|
||||
index,
|
||||
runId: entry.runId,
|
||||
sessionKey: entry.childSessionKey,
|
||||
label,
|
||||
task,
|
||||
status,
|
||||
pendingDescendants,
|
||||
runtime,
|
||||
runtimeMs,
|
||||
model: resolveModelRef(sessionEntry) || entry.model,
|
||||
totalTokens,
|
||||
startedAt: entry.startedAt,
|
||||
};
|
||||
index += 1;
|
||||
return { line, view: entry.endedAt ? { ...baseView, endedAt: entry.endedAt } : baseView };
|
||||
};
|
||||
const active = runs
|
||||
.filter((entry) => isActiveRun(entry))
|
||||
.map((entry) => buildListEntry(entry, now - (entry.startedAt ?? entry.createdAt)));
|
||||
const recent = runs
|
||||
.filter(
|
||||
(entry) =>
|
||||
!isActiveRun(entry) && !!entry.endedAt && (entry.endedAt ?? 0) >= recentCutoff,
|
||||
)
|
||||
.map((entry) =>
|
||||
buildListEntry(entry, (entry.endedAt ?? now) - (entry.startedAt ?? entry.createdAt)),
|
||||
);
|
||||
|
||||
const text = buildListText({ active, recent, recentMinutes });
|
||||
const list = buildSubagentList({
|
||||
cfg,
|
||||
runs,
|
||||
recentMinutes,
|
||||
});
|
||||
return jsonResult({
|
||||
status: "ok",
|
||||
action: "list",
|
||||
requesterSessionKey: requester.requesterSessionKey,
|
||||
callerSessionKey: requester.callerSessionKey,
|
||||
callerIsSubagent: requester.callerIsSubagent,
|
||||
total: runs.length,
|
||||
active: active.map((entry) => entry.view),
|
||||
recent: recent.map((entry) => entry.view),
|
||||
text,
|
||||
requesterSessionKey: controller.controllerSessionKey,
|
||||
callerSessionKey: controller.callerSessionKey,
|
||||
callerIsSubagent: controller.callerIsSubagent,
|
||||
total: list.total,
|
||||
active: list.active.map(({ line: _line, ...view }) => view),
|
||||
recent: list.recent.map(({ line: _line, ...view }) => view),
|
||||
text: list.text,
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "kill") {
|
||||
const target = readStringParam(params, "target", { required: true });
|
||||
if (target === "all" || target === "*") {
|
||||
const cache = new Map<string, Record<string, SessionEntry>>();
|
||||
const seenChildSessionKeys = new Set<string>();
|
||||
const killedLabels: string[] = [];
|
||||
let killed = 0;
|
||||
for (const entry of runs) {
|
||||
const childKey = entry.childSessionKey?.trim();
|
||||
if (!childKey || seenChildSessionKeys.has(childKey)) {
|
||||
continue;
|
||||
}
|
||||
seenChildSessionKeys.add(childKey);
|
||||
|
||||
if (!entry.endedAt) {
|
||||
const stopResult = await killSubagentRun({ cfg, entry, cache });
|
||||
if (stopResult.killed) {
|
||||
killed += 1;
|
||||
killedLabels.push(resolveSubagentLabel(entry));
|
||||
}
|
||||
}
|
||||
|
||||
// Traverse descendants even when the direct run is already finished.
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg,
|
||||
parentChildSessionKey: childKey,
|
||||
cache,
|
||||
seenChildSessionKeys,
|
||||
const result = await killAllControlledSubagentRuns({
|
||||
cfg,
|
||||
controller,
|
||||
runs,
|
||||
});
|
||||
if (result.status === "forbidden") {
|
||||
return jsonResult({
|
||||
status: "forbidden",
|
||||
action: "kill",
|
||||
target: "all",
|
||||
error: result.error,
|
||||
});
|
||||
killed += cascade.killed;
|
||||
killedLabels.push(...cascade.labels);
|
||||
}
|
||||
return jsonResult({
|
||||
status: "ok",
|
||||
action: "kill",
|
||||
target: "all",
|
||||
killed,
|
||||
labels: killedLabels,
|
||||
killed: result.killed,
|
||||
labels: result.labels,
|
||||
text:
|
||||
killed > 0
|
||||
? `killed ${killed} subagent${killed === 1 ? "" : "s"}.`
|
||||
result.killed > 0
|
||||
? `killed ${result.killed} subagent${result.killed === 1 ? "" : "s"}.`
|
||||
: "no running subagents to kill.",
|
||||
});
|
||||
}
|
||||
const resolved = resolveSubagentTarget(runs, target, {
|
||||
const resolved = resolveControlledSubagentTarget(runs, target, {
|
||||
recentMinutes,
|
||||
isActive: isActiveRun,
|
||||
isActive,
|
||||
});
|
||||
if (!resolved.entry) {
|
||||
return jsonResult({
|
||||
@@ -489,66 +111,25 @@ export function createSubagentsTool(opts?: { agentSessionKey?: string }): AnyAge
|
||||
error: resolved.error ?? "Unknown subagent target.",
|
||||
});
|
||||
}
|
||||
const ownershipError = ensureSubagentControlsOwnDescendants({
|
||||
requester,
|
||||
const result = await killControlledSubagentRun({
|
||||
cfg,
|
||||
controller,
|
||||
entry: resolved.entry,
|
||||
});
|
||||
if (ownershipError) {
|
||||
return jsonResult({
|
||||
status: "forbidden",
|
||||
action: "kill",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
error: ownershipError,
|
||||
});
|
||||
}
|
||||
const killCache = new Map<string, Record<string, SessionEntry>>();
|
||||
const stopResult = await killSubagentRun({
|
||||
cfg,
|
||||
entry: resolved.entry,
|
||||
cache: killCache,
|
||||
});
|
||||
const seenChildSessionKeys = new Set<string>();
|
||||
const targetChildKey = resolved.entry.childSessionKey?.trim();
|
||||
if (targetChildKey) {
|
||||
seenChildSessionKeys.add(targetChildKey);
|
||||
}
|
||||
// Traverse descendants even when the selected run is already finished.
|
||||
const cascade = await cascadeKillChildren({
|
||||
cfg,
|
||||
parentChildSessionKey: resolved.entry.childSessionKey,
|
||||
cache: killCache,
|
||||
seenChildSessionKeys,
|
||||
});
|
||||
if (!stopResult.killed && cascade.killed === 0) {
|
||||
return jsonResult({
|
||||
status: "done",
|
||||
action: "kill",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
text: `${resolveSubagentLabel(resolved.entry)} is already finished.`,
|
||||
});
|
||||
}
|
||||
const cascadeText =
|
||||
cascade.killed > 0
|
||||
? ` (+ ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"})`
|
||||
: "";
|
||||
return jsonResult({
|
||||
status: "ok",
|
||||
status: result.status,
|
||||
action: "kill",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
label: resolveSubagentLabel(resolved.entry),
|
||||
cascadeKilled: cascade.killed,
|
||||
cascadeLabels: cascade.killed > 0 ? cascade.labels : undefined,
|
||||
text: stopResult.killed
|
||||
? `killed ${resolveSubagentLabel(resolved.entry)}${cascadeText}.`
|
||||
: `killed ${cascade.killed} descendant${cascade.killed === 1 ? "" : "s"} of ${resolveSubagentLabel(resolved.entry)}.`,
|
||||
runId: result.runId,
|
||||
sessionKey: result.sessionKey,
|
||||
label: result.label,
|
||||
cascadeKilled: "cascadeKilled" in result ? result.cascadeKilled : undefined,
|
||||
cascadeLabels: "cascadeLabels" in result ? result.cascadeLabels : undefined,
|
||||
error: "error" in result ? result.error : undefined,
|
||||
text: result.text,
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "steer") {
|
||||
const target = readStringParam(params, "target", { required: true });
|
||||
const message = readStringParam(params, "message", { required: true });
|
||||
@@ -560,9 +141,9 @@ export function createSubagentsTool(opts?: { agentSessionKey?: string }): AnyAge
|
||||
error: `Message too long (${message.length} chars, max ${MAX_STEER_MESSAGE_CHARS}).`,
|
||||
});
|
||||
}
|
||||
const resolved = resolveSubagentTarget(runs, target, {
|
||||
const resolved = resolveControlledSubagentTarget(runs, target, {
|
||||
recentMinutes,
|
||||
isActive: isActiveRun,
|
||||
isActive,
|
||||
});
|
||||
if (!resolved.entry) {
|
||||
return jsonResult({
|
||||
@@ -572,154 +153,26 @@ export function createSubagentsTool(opts?: { agentSessionKey?: string }): AnyAge
|
||||
error: resolved.error ?? "Unknown subagent target.",
|
||||
});
|
||||
}
|
||||
const ownershipError = ensureSubagentControlsOwnDescendants({
|
||||
requester,
|
||||
entry: resolved.entry,
|
||||
});
|
||||
if (ownershipError) {
|
||||
return jsonResult({
|
||||
status: "forbidden",
|
||||
action: "steer",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
error: ownershipError,
|
||||
});
|
||||
}
|
||||
if (resolved.entry.endedAt) {
|
||||
return jsonResult({
|
||||
status: "done",
|
||||
action: "steer",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
text: `${resolveSubagentLabel(resolved.entry)} is already finished.`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
requester.callerIsSubagent &&
|
||||
requester.callerSessionKey === resolved.entry.childSessionKey
|
||||
) {
|
||||
return jsonResult({
|
||||
status: "forbidden",
|
||||
action: "steer",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
error: "Subagents cannot steer themselves.",
|
||||
});
|
||||
}
|
||||
|
||||
const rateKey = `${requester.callerSessionKey}:${resolved.entry.childSessionKey}`;
|
||||
const now = Date.now();
|
||||
const lastSentAt = steerRateLimit.get(rateKey) ?? 0;
|
||||
if (now - lastSentAt < STEER_RATE_LIMIT_MS) {
|
||||
return jsonResult({
|
||||
status: "rate_limited",
|
||||
action: "steer",
|
||||
target,
|
||||
runId: resolved.entry.runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
error: "Steer rate limit exceeded. Wait a moment before sending another steer.",
|
||||
});
|
||||
}
|
||||
steerRateLimit.set(rateKey, now);
|
||||
|
||||
// Suppress announce for the interrupted run before aborting so we don't
|
||||
// emit stale pre-steer findings if the run exits immediately.
|
||||
markSubagentRunForSteerRestart(resolved.entry.runId);
|
||||
|
||||
const targetSession = resolveSessionEntryForKey({
|
||||
const result = await steerControlledSubagentRun({
|
||||
cfg,
|
||||
key: resolved.entry.childSessionKey,
|
||||
cache: new Map<string, Record<string, SessionEntry>>(),
|
||||
controller,
|
||||
entry: resolved.entry,
|
||||
message,
|
||||
});
|
||||
const sessionId =
|
||||
typeof targetSession.entry?.sessionId === "string" && targetSession.entry.sessionId.trim()
|
||||
? targetSession.entry.sessionId.trim()
|
||||
: undefined;
|
||||
|
||||
// Interrupt current work first so steer takes precedence immediately.
|
||||
if (sessionId) {
|
||||
abortEmbeddedPiRun(sessionId);
|
||||
}
|
||||
const cleared = clearSessionQueues([resolved.entry.childSessionKey, sessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents tool steer: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Best effort: wait for the interrupted run to settle so the steer
|
||||
// message appends onto the existing conversation context.
|
||||
try {
|
||||
await callGateway({
|
||||
method: "agent.wait",
|
||||
params: {
|
||||
runId: resolved.entry.runId,
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS,
|
||||
},
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS + 2_000,
|
||||
});
|
||||
} catch {
|
||||
// Continue even if wait fails; steer should still be attempted.
|
||||
}
|
||||
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
let runId: string = idempotencyKey;
|
||||
try {
|
||||
const response = await callGateway<{ runId: string }>({
|
||||
method: "agent",
|
||||
params: {
|
||||
message,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
sessionId,
|
||||
idempotencyKey,
|
||||
deliver: false,
|
||||
channel: INTERNAL_MESSAGE_CHANNEL,
|
||||
lane: AGENT_LANE_SUBAGENT,
|
||||
timeout: 0,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (typeof response?.runId === "string" && response.runId) {
|
||||
runId = response.runId;
|
||||
}
|
||||
} catch (err) {
|
||||
// Replacement launch failed; restore normal announce behavior for the
|
||||
// original run so completion is not silently suppressed.
|
||||
clearSubagentRunSteerRestart(resolved.entry.runId);
|
||||
const error = err instanceof Error ? err.message : String(err);
|
||||
return jsonResult({
|
||||
status: "error",
|
||||
action: "steer",
|
||||
target,
|
||||
runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
sessionId,
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
replaceSubagentRunAfterSteer({
|
||||
previousRunId: resolved.entry.runId,
|
||||
nextRunId: runId,
|
||||
fallback: resolved.entry,
|
||||
runTimeoutSeconds: resolved.entry.runTimeoutSeconds ?? 0,
|
||||
});
|
||||
|
||||
return jsonResult({
|
||||
status: "accepted",
|
||||
status: result.status,
|
||||
action: "steer",
|
||||
target,
|
||||
runId,
|
||||
sessionKey: resolved.entry.childSessionKey,
|
||||
sessionId,
|
||||
mode: "restart",
|
||||
label: resolveSubagentLabel(resolved.entry),
|
||||
text: `steered ${resolveSubagentLabel(resolved.entry)}.`,
|
||||
runId: result.runId,
|
||||
sessionKey: result.sessionKey,
|
||||
sessionId: result.sessionId,
|
||||
mode: "mode" in result ? result.mode : undefined,
|
||||
label: "label" in result ? result.label : undefined,
|
||||
error: "error" in result ? result.error : undefined,
|
||||
text: result.text,
|
||||
});
|
||||
}
|
||||
|
||||
return jsonResult({
|
||||
status: "error",
|
||||
error: "Unsupported action.",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { getAcpSessionManager } from "../../acp/control-plane/manager.js";
|
||||
import { resolveSessionAgentId } from "../../agents/agent-scope.js";
|
||||
import { abortEmbeddedPiRun } from "../../agents/pi-embedded.js";
|
||||
import {
|
||||
listSubagentRunsForRequester,
|
||||
listSubagentRunsForController,
|
||||
markSubagentRunTerminated,
|
||||
} from "../../agents/subagent-registry.js";
|
||||
import {
|
||||
@@ -222,7 +222,7 @@ export function stopSubagentsForRequester(params: {
|
||||
if (!requesterKey) {
|
||||
return { stopped: 0 };
|
||||
}
|
||||
const runs = listSubagentRunsForRequester(requesterKey);
|
||||
const runs = listSubagentRunsForController(requesterKey);
|
||||
if (runs.length === 0) {
|
||||
return { stopped: 0 };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listSubagentRunsForRequester } from "../../agents/subagent-registry.js";
|
||||
import { listSubagentRunsForController } from "../../agents/subagent-registry.js";
|
||||
import { logVerbose } from "../../globals.js";
|
||||
import { handleSubagentsAgentsAction } from "./commands-subagents/action-agents.js";
|
||||
import { handleSubagentsFocusAction } from "./commands-subagents/action-focus.js";
|
||||
@@ -61,7 +61,7 @@ export const handleSubagentsCommand: CommandHandler = async (params, allowTextCo
|
||||
params,
|
||||
handledPrefix,
|
||||
requesterKey,
|
||||
runs: listSubagentRunsForRequester(requesterKey),
|
||||
runs: listSubagentRunsForController(requesterKey),
|
||||
restTokens,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
import { abortEmbeddedPiRun } from "../../../agents/pi-embedded.js";
|
||||
import { markSubagentRunTerminated } from "../../../agents/subagent-registry.js";
|
||||
import {
|
||||
loadSessionStore,
|
||||
resolveStorePath,
|
||||
updateSessionStore,
|
||||
} from "../../../config/sessions.js";
|
||||
import { logVerbose } from "../../../globals.js";
|
||||
import { stopSubagentsForRequester } from "../abort.js";
|
||||
killAllControlledSubagentRuns,
|
||||
killControlledSubagentRun,
|
||||
} from "../../../agents/subagent-control.js";
|
||||
import type { CommandHandlerResult } from "../commands-types.js";
|
||||
import { clearSessionQueues } from "../queue.js";
|
||||
import { formatRunLabel } from "../subagents-utils.js";
|
||||
import {
|
||||
type SubagentsCommandContext,
|
||||
COMMAND,
|
||||
loadSubagentSessionEntry,
|
||||
resolveCommandSubagentController,
|
||||
resolveSubagentEntryForToken,
|
||||
stopWithText,
|
||||
} from "./shared.js";
|
||||
@@ -30,10 +24,18 @@ export async function handleSubagentsKillAction(
|
||||
}
|
||||
|
||||
if (target === "all" || target === "*") {
|
||||
stopSubagentsForRequester({
|
||||
const controller = resolveCommandSubagentController(params, requesterKey);
|
||||
const result = await killAllControlledSubagentRuns({
|
||||
cfg: params.cfg,
|
||||
requesterSessionKey: requesterKey,
|
||||
controller,
|
||||
runs,
|
||||
});
|
||||
if (result.status === "forbidden") {
|
||||
return stopWithText(`⚠️ ${result.error}`);
|
||||
}
|
||||
if (result.killed > 0) {
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
|
||||
@@ -45,42 +47,17 @@ export async function handleSubagentsKillAction(
|
||||
return stopWithText(`${formatRunLabel(targetResolution.entry)} is already finished.`);
|
||||
}
|
||||
|
||||
const childKey = targetResolution.entry.childSessionKey;
|
||||
const { storePath, store, entry } = loadSubagentSessionEntry(params, childKey, {
|
||||
loadSessionStore,
|
||||
resolveStorePath,
|
||||
});
|
||||
const sessionId = entry?.sessionId;
|
||||
if (sessionId) {
|
||||
abortEmbeddedPiRun(sessionId);
|
||||
}
|
||||
|
||||
const cleared = clearSessionQueues([childKey, sessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents kill: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (entry) {
|
||||
entry.abortedLastRun = true;
|
||||
entry.updatedAt = Date.now();
|
||||
store[childKey] = entry;
|
||||
await updateSessionStore(storePath, (nextStore) => {
|
||||
nextStore[childKey] = entry;
|
||||
});
|
||||
}
|
||||
|
||||
markSubagentRunTerminated({
|
||||
runId: targetResolution.entry.runId,
|
||||
childSessionKey: childKey,
|
||||
reason: "killed",
|
||||
});
|
||||
|
||||
stopSubagentsForRequester({
|
||||
const controller = resolveCommandSubagentController(params, requesterKey);
|
||||
const result = await killControlledSubagentRun({
|
||||
cfg: params.cfg,
|
||||
requesterSessionKey: childKey,
|
||||
controller,
|
||||
entry: targetResolution.entry,
|
||||
});
|
||||
|
||||
if (result.status === "forbidden") {
|
||||
return stopWithText(`⚠️ ${result.error}`);
|
||||
}
|
||||
if (result.status === "done") {
|
||||
return stopWithText(result.text);
|
||||
}
|
||||
return { shouldContinue: false };
|
||||
}
|
||||
|
||||
@@ -1,79 +1,26 @@
|
||||
import { countPendingDescendantRuns } from "../../../agents/subagent-registry.js";
|
||||
import { loadSessionStore, resolveStorePath } from "../../../config/sessions.js";
|
||||
import { buildSubagentList } from "../../../agents/subagent-control.js";
|
||||
import type { CommandHandlerResult } from "../commands-types.js";
|
||||
import { sortSubagentRuns } from "../subagents-utils.js";
|
||||
import {
|
||||
type SessionStoreCache,
|
||||
type SubagentsCommandContext,
|
||||
RECENT_WINDOW_MINUTES,
|
||||
formatSubagentListLine,
|
||||
loadSubagentSessionEntry,
|
||||
stopWithText,
|
||||
} from "./shared.js";
|
||||
import { type SubagentsCommandContext, RECENT_WINDOW_MINUTES, stopWithText } from "./shared.js";
|
||||
|
||||
export function handleSubagentsListAction(ctx: SubagentsCommandContext): CommandHandlerResult {
|
||||
const { params, runs } = ctx;
|
||||
const sorted = sortSubagentRuns(runs);
|
||||
const now = Date.now();
|
||||
const recentCutoff = now - RECENT_WINDOW_MINUTES * 60_000;
|
||||
const storeCache: SessionStoreCache = new Map();
|
||||
const pendingDescendantCache = new Map<string, number>();
|
||||
const pendingDescendantCount = (sessionKey: string) => {
|
||||
if (pendingDescendantCache.has(sessionKey)) {
|
||||
return pendingDescendantCache.get(sessionKey) ?? 0;
|
||||
}
|
||||
const pending = Math.max(0, countPendingDescendantRuns(sessionKey));
|
||||
pendingDescendantCache.set(sessionKey, pending);
|
||||
return pending;
|
||||
};
|
||||
const isActiveRun = (entry: (typeof runs)[number]) =>
|
||||
!entry.endedAt || pendingDescendantCount(entry.childSessionKey) > 0;
|
||||
|
||||
let index = 1;
|
||||
|
||||
const mapRuns = (entries: typeof runs, runtimeMs: (entry: (typeof runs)[number]) => number) =>
|
||||
entries.map((entry) => {
|
||||
const { entry: sessionEntry } = loadSubagentSessionEntry(
|
||||
params,
|
||||
entry.childSessionKey,
|
||||
{
|
||||
loadSessionStore,
|
||||
resolveStorePath,
|
||||
},
|
||||
storeCache,
|
||||
);
|
||||
const line = formatSubagentListLine({
|
||||
entry,
|
||||
index,
|
||||
runtimeMs: runtimeMs(entry),
|
||||
sessionEntry,
|
||||
pendingDescendants: pendingDescendantCount(entry.childSessionKey),
|
||||
});
|
||||
index += 1;
|
||||
return line;
|
||||
});
|
||||
|
||||
const activeEntries = sorted.filter((entry) => isActiveRun(entry));
|
||||
const activeLines = mapRuns(activeEntries, (entry) => now - (entry.startedAt ?? entry.createdAt));
|
||||
const recentEntries = sorted.filter(
|
||||
(entry) => !isActiveRun(entry) && !!entry.endedAt && (entry.endedAt ?? 0) >= recentCutoff,
|
||||
);
|
||||
const recentLines = mapRuns(
|
||||
recentEntries,
|
||||
(entry) => (entry.endedAt ?? now) - (entry.startedAt ?? entry.createdAt),
|
||||
);
|
||||
|
||||
const list = buildSubagentList({
|
||||
cfg: params.cfg,
|
||||
runs,
|
||||
recentMinutes: RECENT_WINDOW_MINUTES,
|
||||
taskMaxChars: 110,
|
||||
});
|
||||
const lines = ["active subagents:", "-----"];
|
||||
if (activeLines.length === 0) {
|
||||
if (list.active.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(activeLines.join("\n"));
|
||||
lines.push(list.active.map((entry) => entry.line).join("\n"));
|
||||
}
|
||||
lines.push("", `recent subagents (last ${RECENT_WINDOW_MINUTES}m):`, "-----");
|
||||
if (recentLines.length === 0) {
|
||||
if (list.recent.length === 0) {
|
||||
lines.push("(none)");
|
||||
} else {
|
||||
lines.push(recentLines.join("\n"));
|
||||
lines.push(list.recent.map((entry) => entry.line).join("\n"));
|
||||
}
|
||||
|
||||
return stopWithText(lines.join("\n"));
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
import crypto from "node:crypto";
|
||||
import { AGENT_LANE_SUBAGENT } from "../../../agents/lanes.js";
|
||||
import { abortEmbeddedPiRun } from "../../../agents/pi-embedded.js";
|
||||
import {
|
||||
clearSubagentRunSteerRestart,
|
||||
replaceSubagentRunAfterSteer,
|
||||
markSubagentRunForSteerRestart,
|
||||
} from "../../../agents/subagent-registry.js";
|
||||
import { loadSessionStore, resolveStorePath } from "../../../config/sessions.js";
|
||||
import { callGateway } from "../../../gateway/call.js";
|
||||
import { logVerbose } from "../../../globals.js";
|
||||
import { INTERNAL_MESSAGE_CHANNEL } from "../../../utils/message-channel.js";
|
||||
sendControlledSubagentMessage,
|
||||
steerControlledSubagentRun,
|
||||
} from "../../../agents/subagent-control.js";
|
||||
import type { CommandHandlerResult } from "../commands-types.js";
|
||||
import { clearSessionQueues } from "../queue.js";
|
||||
import { formatRunLabel } from "../subagents-utils.js";
|
||||
import {
|
||||
type SubagentsCommandContext,
|
||||
COMMAND,
|
||||
STEER_ABORT_SETTLE_TIMEOUT_MS,
|
||||
extractAssistantText,
|
||||
loadSubagentSessionEntry,
|
||||
resolveCommandSubagentController,
|
||||
resolveSubagentEntryForToken,
|
||||
stopWithText,
|
||||
stripToolMessages,
|
||||
} from "./shared.js";
|
||||
|
||||
export async function handleSubagentsSendAction(
|
||||
@@ -49,111 +37,41 @@ export async function handleSubagentsSendAction(
|
||||
return stopWithText(`${formatRunLabel(targetResolution.entry)} is already finished.`);
|
||||
}
|
||||
|
||||
const { entry: targetSessionEntry } = loadSubagentSessionEntry(
|
||||
params,
|
||||
targetResolution.entry.childSessionKey,
|
||||
{
|
||||
loadSessionStore,
|
||||
resolveStorePath,
|
||||
},
|
||||
);
|
||||
const targetSessionId =
|
||||
typeof targetSessionEntry?.sessionId === "string" && targetSessionEntry.sessionId.trim()
|
||||
? targetSessionEntry.sessionId.trim()
|
||||
: undefined;
|
||||
|
||||
if (steerRequested) {
|
||||
markSubagentRunForSteerRestart(targetResolution.entry.runId);
|
||||
|
||||
if (targetSessionId) {
|
||||
abortEmbeddedPiRun(targetSessionId);
|
||||
}
|
||||
|
||||
const cleared = clearSessionQueues([targetResolution.entry.childSessionKey, targetSessionId]);
|
||||
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) {
|
||||
logVerbose(
|
||||
`subagents steer: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`,
|
||||
const controller = resolveCommandSubagentController(params, ctx.requesterKey);
|
||||
const result = await steerControlledSubagentRun({
|
||||
cfg: params.cfg,
|
||||
controller,
|
||||
entry: targetResolution.entry,
|
||||
message,
|
||||
});
|
||||
if (result.status === "accepted") {
|
||||
return stopWithText(
|
||||
`steered ${formatRunLabel(targetResolution.entry)} (run ${result.runId.slice(0, 8)}).`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await callGateway({
|
||||
method: "agent.wait",
|
||||
params: {
|
||||
runId: targetResolution.entry.runId,
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS,
|
||||
},
|
||||
timeoutMs: STEER_ABORT_SETTLE_TIMEOUT_MS + 2_000,
|
||||
});
|
||||
} catch {
|
||||
// Continue even if wait fails; steer should still be attempted.
|
||||
if (result.status === "done" && result.text) {
|
||||
return stopWithText(result.text);
|
||||
}
|
||||
if (result.status === "error") {
|
||||
return stopWithText(`send failed: ${result.error ?? "error"}`);
|
||||
}
|
||||
return stopWithText(`⚠️ ${result.error ?? "send failed"}`);
|
||||
}
|
||||
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
let runId: string = idempotencyKey;
|
||||
try {
|
||||
const response = await callGateway<{ runId: string }>({
|
||||
method: "agent",
|
||||
params: {
|
||||
message,
|
||||
sessionKey: targetResolution.entry.childSessionKey,
|
||||
sessionId: targetSessionId,
|
||||
idempotencyKey,
|
||||
deliver: false,
|
||||
channel: INTERNAL_MESSAGE_CHANNEL,
|
||||
lane: AGENT_LANE_SUBAGENT,
|
||||
timeout: 0,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const responseRunId = typeof response?.runId === "string" ? response.runId : undefined;
|
||||
if (responseRunId) {
|
||||
runId = responseRunId;
|
||||
}
|
||||
} catch (err) {
|
||||
if (steerRequested) {
|
||||
clearSubagentRunSteerRestart(targetResolution.entry.runId);
|
||||
}
|
||||
const messageText =
|
||||
err instanceof Error ? err.message : typeof err === "string" ? err : "error";
|
||||
return stopWithText(`send failed: ${messageText}`);
|
||||
}
|
||||
|
||||
if (steerRequested) {
|
||||
replaceSubagentRunAfterSteer({
|
||||
previousRunId: targetResolution.entry.runId,
|
||||
nextRunId: runId,
|
||||
fallback: targetResolution.entry,
|
||||
runTimeoutSeconds: targetResolution.entry.runTimeoutSeconds ?? 0,
|
||||
});
|
||||
return stopWithText(
|
||||
`steered ${formatRunLabel(targetResolution.entry)} (run ${runId.slice(0, 8)}).`,
|
||||
);
|
||||
}
|
||||
|
||||
const waitMs = 30_000;
|
||||
const wait = await callGateway<{ status?: string; error?: string }>({
|
||||
method: "agent.wait",
|
||||
params: { runId, timeoutMs: waitMs },
|
||||
timeoutMs: waitMs + 2000,
|
||||
const result = await sendControlledSubagentMessage({
|
||||
cfg: params.cfg,
|
||||
entry: targetResolution.entry,
|
||||
message,
|
||||
});
|
||||
if (wait?.status === "timeout") {
|
||||
return stopWithText(`⏳ Subagent still running (run ${runId.slice(0, 8)}).`);
|
||||
if (result.status === "timeout") {
|
||||
return stopWithText(`⏳ Subagent still running (run ${result.runId.slice(0, 8)}).`);
|
||||
}
|
||||
if (wait?.status === "error") {
|
||||
const waitError = typeof wait.error === "string" ? wait.error : "unknown error";
|
||||
return stopWithText(`⚠️ Subagent error: ${waitError} (run ${runId.slice(0, 8)}).`);
|
||||
if (result.status === "error") {
|
||||
return stopWithText(`⚠️ Subagent error: ${result.error} (run ${result.runId.slice(0, 8)}).`);
|
||||
}
|
||||
|
||||
const history = await callGateway<{ messages: Array<unknown> }>({
|
||||
method: "chat.history",
|
||||
params: { sessionKey: targetResolution.entry.childSessionKey, limit: 50 },
|
||||
});
|
||||
const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
|
||||
const last = filtered.length > 0 ? filtered[filtered.length - 1] : undefined;
|
||||
const replyText = last ? extractAssistantText(last) : undefined;
|
||||
return stopWithText(
|
||||
replyText ?? `✅ Sent to ${formatRunLabel(targetResolution.entry)} (run ${runId.slice(0, 8)}).`,
|
||||
result.replyText ??
|
||||
`✅ Sent to ${formatRunLabel(targetResolution.entry)} (run ${result.runId.slice(0, 8)}).`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { resolveStoredSubagentCapabilities } from "../../../agents/subagent-capabilities.js";
|
||||
import type { ResolvedSubagentController } from "../../../agents/subagent-control.js";
|
||||
import {
|
||||
countPendingDescendantRuns,
|
||||
type SubagentRunRecord,
|
||||
@@ -18,6 +20,7 @@ import { parseDiscordTarget } from "../../../discord/targets.js";
|
||||
import { callGateway } from "../../../gateway/call.js";
|
||||
import { formatTimeAgo } from "../../../infra/format-time/format-relative.ts";
|
||||
import { parseAgentSessionKey } from "../../../routing/session-key.js";
|
||||
import { isSubagentSessionKey } from "../../../routing/session-key.js";
|
||||
import { looksLikeSessionId } from "../../../sessions/session-id.js";
|
||||
import { extractTextFromChatContent } from "../../../shared/chat-content.js";
|
||||
import {
|
||||
@@ -247,6 +250,29 @@ export function resolveRequesterSessionKey(
|
||||
return resolveInternalSessionKey({ key: raw, alias, mainKey });
|
||||
}
|
||||
|
||||
export function resolveCommandSubagentController(
|
||||
params: SubagentsCommandParams,
|
||||
requesterKey: string,
|
||||
): ResolvedSubagentController {
|
||||
if (!isSubagentSessionKey(requesterKey)) {
|
||||
return {
|
||||
controllerSessionKey: requesterKey,
|
||||
callerSessionKey: requesterKey,
|
||||
callerIsSubagent: false,
|
||||
controlScope: "children",
|
||||
};
|
||||
}
|
||||
const capabilities = resolveStoredSubagentCapabilities(requesterKey, {
|
||||
cfg: params.cfg,
|
||||
});
|
||||
return {
|
||||
controllerSessionKey: requesterKey,
|
||||
callerSessionKey: requesterKey,
|
||||
callerIsSubagent: true,
|
||||
controlScope: capabilities.controlScope,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveHandledPrefix(normalized: string): string | null {
|
||||
return normalized.startsWith(COMMAND)
|
||||
? COMMAND
|
||||
|
||||
@@ -186,11 +186,10 @@ describe("nodes-cli coverage", () => {
|
||||
});
|
||||
expect(invoke?.params?.timeoutMs).toBe(5000);
|
||||
const approval = getApprovalRequestCall();
|
||||
expect(approval?.params?.["commandArgv"]).toEqual(["echo", "hi"]);
|
||||
expect(approval?.params?.["systemRunPlan"]).toEqual({
|
||||
argv: ["echo", "hi"],
|
||||
cwd: "/tmp",
|
||||
rawCommand: "echo hi",
|
||||
commandText: "echo hi",
|
||||
commandPreview: null,
|
||||
agentId: "main",
|
||||
sessionKey: null,
|
||||
@@ -221,11 +220,10 @@ describe("nodes-cli coverage", () => {
|
||||
runId: expect.any(String),
|
||||
});
|
||||
const approval = getApprovalRequestCall();
|
||||
expect(approval?.params?.["commandArgv"]).toEqual(["/bin/sh", "-lc", "echo hi"]);
|
||||
expect(approval?.params?.["systemRunPlan"]).toEqual({
|
||||
argv: ["/bin/sh", "-lc", "echo hi"],
|
||||
cwd: null,
|
||||
rawCommand: '/bin/sh -lc "echo hi"',
|
||||
commandText: '/bin/sh -lc "echo hi"',
|
||||
commandPreview: "echo hi",
|
||||
agentId: "main",
|
||||
sessionKey: null,
|
||||
|
||||
@@ -189,7 +189,6 @@ async function maybeRequestNodesRunApproval(params: {
|
||||
opts: NodesRunOpts;
|
||||
nodeId: string;
|
||||
agentId: string | undefined;
|
||||
preparedCmdText: string;
|
||||
approvalPlan: ReturnType<typeof requirePreparedRunPayload>["plan"];
|
||||
hostSecurity: ExecSecurity;
|
||||
hostAsk: ExecAsk;
|
||||
@@ -215,8 +214,6 @@ async function maybeRequestNodesRunApproval(params: {
|
||||
params.opts,
|
||||
{
|
||||
id: approvalId,
|
||||
command: params.preparedCmdText,
|
||||
commandArgv: params.approvalPlan.argv,
|
||||
systemRunPlan: params.approvalPlan,
|
||||
cwd: params.approvalPlan.cwd,
|
||||
nodeId: params.nodeId,
|
||||
@@ -272,7 +269,7 @@ function buildSystemRunInvokeParams(params: {
|
||||
command: "system.run",
|
||||
params: {
|
||||
command: params.approvalPlan.argv,
|
||||
rawCommand: params.approvalPlan.rawCommand,
|
||||
rawCommand: params.approvalPlan.commandText,
|
||||
cwd: params.approvalPlan.cwd,
|
||||
env: params.nodeEnv,
|
||||
timeoutMs: params.timeoutMs,
|
||||
@@ -403,7 +400,6 @@ export function registerNodesInvokeCommands(nodes: Command) {
|
||||
opts,
|
||||
nodeId,
|
||||
agentId,
|
||||
preparedCmdText: preparedContext.prepared.cmdText,
|
||||
approvalPlan,
|
||||
hostSecurity: approvals.hostSecurity,
|
||||
hostAsk: approvals.hostAsk,
|
||||
|
||||
@@ -82,6 +82,10 @@ export type SessionEntry = {
|
||||
forkedFromParent?: boolean;
|
||||
/** Subagent spawn depth (0 = main, 1 = sub-agent, 2 = sub-sub-agent). */
|
||||
spawnDepth?: number;
|
||||
/** Explicit role assigned at spawn time for subagent tool policy/control decisions. */
|
||||
subagentRole?: "orchestrator" | "leaf";
|
||||
/** Explicit control scope assigned at spawn time for subagent control decisions. */
|
||||
subagentControlScope?: "children" | "none";
|
||||
systemSent?: boolean;
|
||||
abortedLastRun?: boolean;
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { DiscordExecApprovalConfig } from "../../config/types.discord.js";
|
||||
import { GatewayClient } from "../../gateway/client.js";
|
||||
import { createOperatorApprovalsGatewayClient } from "../../gateway/operator-approvals-client.js";
|
||||
import type { EventFrame } from "../../gateway/protocol/index.js";
|
||||
import { resolveExecApprovalCommandDisplay } from "../../infra/exec-approval-command-display.js";
|
||||
import { getExecApprovalApproverDmNoticeText } from "../../infra/exec-approval-reply.js";
|
||||
import type {
|
||||
ExecApprovalDecision,
|
||||
@@ -257,12 +258,11 @@ function createExecApprovalRequestContainer(params: {
|
||||
accountId: string;
|
||||
actionRow?: Row<Button>;
|
||||
}): ExecApprovalContainer {
|
||||
const commandText = params.request.request.command;
|
||||
const commandPreview = formatCommandPreview(commandText, 1000);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(
|
||||
params.request.request.commandPreview,
|
||||
500,
|
||||
const { commandText, commandPreview: secondaryPreview } = resolveExecApprovalCommandDisplay(
|
||||
params.request.request,
|
||||
);
|
||||
const commandPreview = formatCommandPreview(commandText, 1000);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(secondaryPreview, 500);
|
||||
const expiresAtSeconds = Math.max(0, Math.floor(params.request.expiresAtMs / 1000));
|
||||
|
||||
return new ExecApprovalContainer({
|
||||
@@ -286,12 +286,11 @@ function createResolvedContainer(params: {
|
||||
cfg: OpenClawConfig;
|
||||
accountId: string;
|
||||
}): ExecApprovalContainer {
|
||||
const commandText = params.request.request.command;
|
||||
const commandPreview = formatCommandPreview(commandText, 500);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(
|
||||
params.request.request.commandPreview,
|
||||
300,
|
||||
const { commandText, commandPreview: secondaryPreview } = resolveExecApprovalCommandDisplay(
|
||||
params.request.request,
|
||||
);
|
||||
const commandPreview = formatCommandPreview(commandText, 500);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(secondaryPreview, 300);
|
||||
|
||||
const decisionLabel =
|
||||
params.decision === "allow-once"
|
||||
@@ -324,12 +323,11 @@ function createExpiredContainer(params: {
|
||||
cfg: OpenClawConfig;
|
||||
accountId: string;
|
||||
}): ExecApprovalContainer {
|
||||
const commandText = params.request.request.command;
|
||||
const commandPreview = formatCommandPreview(commandText, 500);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(
|
||||
params.request.request.commandPreview,
|
||||
300,
|
||||
const { commandText, commandPreview: secondaryPreview } = resolveExecApprovalCommandDisplay(
|
||||
params.request.request,
|
||||
);
|
||||
const commandPreview = formatCommandPreview(commandText, 500);
|
||||
const commandSecondaryPreview = formatOptionalCommandPreview(secondaryPreview, 300);
|
||||
|
||||
return new ExecApprovalContainer({
|
||||
cfg: params.cfg,
|
||||
|
||||
@@ -245,7 +245,7 @@ describe("sanitizeSystemRunParamsForForwarding", () => {
|
||||
record.request.systemRunPlan = {
|
||||
argv: ["/usr/bin/echo", "SAFE"],
|
||||
cwd: "/real/cwd",
|
||||
rawCommand: "/usr/bin/echo SAFE",
|
||||
commandText: "/usr/bin/echo SAFE",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
};
|
||||
@@ -282,7 +282,7 @@ describe("sanitizeSystemRunParamsForForwarding", () => {
|
||||
expect.objectContaining({
|
||||
argv: ["/usr/bin/echo", "SAFE"],
|
||||
cwd: "/real/cwd",
|
||||
rawCommand: "/usr/bin/echo SAFE",
|
||||
commandText: "/usr/bin/echo SAFE",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { resolveSystemRunApprovalRuntimeContext } from "../infra/system-run-approval-context.js";
|
||||
import { resolveSystemRunCommand } from "../infra/system-run-command.js";
|
||||
import { resolveSystemRunCommandRequest } from "../infra/system-run-command.js";
|
||||
import type { ExecApprovalRecord } from "./exec-approval-manager.js";
|
||||
import {
|
||||
systemRunApprovalGuardError,
|
||||
@@ -117,7 +117,7 @@ export function sanitizeSystemRunParamsForForwarding(opts: {
|
||||
const next: Record<string, unknown> = pickSystemRunParams(obj);
|
||||
|
||||
if (!wantsApprovalOverride) {
|
||||
const cmdTextResolution = resolveSystemRunCommand({
|
||||
const cmdTextResolution = resolveSystemRunCommandRequest({
|
||||
command: p.command,
|
||||
rawCommand: p.rawCommand,
|
||||
});
|
||||
@@ -230,8 +230,8 @@ export function sanitizeSystemRunParamsForForwarding(opts: {
|
||||
if (runtimeContext.plan) {
|
||||
next.command = [...runtimeContext.plan.argv];
|
||||
next.systemRunPlan = runtimeContext.plan;
|
||||
if (runtimeContext.rawCommand) {
|
||||
next.rawCommand = runtimeContext.rawCommand;
|
||||
if (runtimeContext.commandText) {
|
||||
next.rawCommand = runtimeContext.commandText;
|
||||
} else {
|
||||
delete next.rawCommand;
|
||||
}
|
||||
|
||||
@@ -88,14 +88,14 @@ export const ExecApprovalsNodeSetParamsSchema = Type.Object(
|
||||
export const ExecApprovalRequestParamsSchema = Type.Object(
|
||||
{
|
||||
id: Type.Optional(NonEmptyString),
|
||||
command: NonEmptyString,
|
||||
command: Type.Optional(NonEmptyString),
|
||||
commandArgv: Type.Optional(Type.Array(Type.String())),
|
||||
systemRunPlan: Type.Optional(
|
||||
Type.Object(
|
||||
{
|
||||
argv: Type.Array(Type.String()),
|
||||
cwd: Type.Union([Type.String(), Type.Null()]),
|
||||
rawCommand: Type.Union([Type.String(), Type.Null()]),
|
||||
commandText: Type.String(),
|
||||
commandPreview: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
||||
agentId: Type.Union([Type.String(), Type.Null()]),
|
||||
sessionKey: Type.Union([Type.String(), Type.Null()]),
|
||||
|
||||
@@ -72,6 +72,12 @@ export const SessionsPatchParamsSchema = Type.Object(
|
||||
model: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
|
||||
spawnedBy: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
|
||||
spawnDepth: Type.Optional(Type.Union([Type.Integer({ minimum: 0 }), Type.Null()])),
|
||||
subagentRole: Type.Optional(
|
||||
Type.Union([Type.Literal("orchestrator"), Type.Literal("leaf"), Type.Null()]),
|
||||
),
|
||||
subagentControlScope: Type.Optional(
|
||||
Type.Union([Type.Literal("children"), Type.Literal("none"), Type.Null()]),
|
||||
),
|
||||
sendPolicy: Type.Optional(
|
||||
Type.Union([Type.Literal("allow"), Type.Literal("deny"), Type.Null()]),
|
||||
),
|
||||
|
||||
@@ -75,7 +75,6 @@ export function createExecApprovalHandlers(
|
||||
const effectiveAgentId = approvalContext.agentId;
|
||||
const effectiveSessionKey = approvalContext.sessionKey;
|
||||
const effectiveCommandText = approvalContext.commandText;
|
||||
const effectiveCommandPreview = approvalContext.commandPreview;
|
||||
if (host === "node" && !nodeId) {
|
||||
respond(
|
||||
false,
|
||||
@@ -92,6 +91,10 @@ export function createExecApprovalHandlers(
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!effectiveCommandText) {
|
||||
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "command is required"));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
host === "node" &&
|
||||
(!Array.isArray(effectiveCommandArgv) || effectiveCommandArgv.length === 0)
|
||||
@@ -123,8 +126,8 @@ export function createExecApprovalHandlers(
|
||||
}
|
||||
const request = {
|
||||
command: effectiveCommandText,
|
||||
commandPreview: effectiveCommandPreview,
|
||||
commandArgv: effectiveCommandArgv,
|
||||
commandPreview: host === "node" ? undefined : approvalContext.commandPreview,
|
||||
commandArgv: host === "node" ? undefined : effectiveCommandArgv,
|
||||
envKeys: systemRunBinding?.envKeys?.length ? systemRunBinding.envKeys : undefined,
|
||||
systemRunBinding: systemRunBinding?.binding ?? null,
|
||||
systemRunPlan: approvalContext.plan,
|
||||
|
||||
@@ -305,7 +305,7 @@ describe("exec approval handlers", () => {
|
||||
systemRunPlan: {
|
||||
argv: ["/usr/bin/echo", "ok"],
|
||||
cwd: "/tmp",
|
||||
rawCommand: "/usr/bin/echo ok",
|
||||
commandText: "/usr/bin/echo ok",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
},
|
||||
@@ -358,7 +358,7 @@ describe("exec approval handlers", () => {
|
||||
requestParams.systemRunPlan = {
|
||||
argv: commandArgv,
|
||||
cwd: cwdValue,
|
||||
rawCommand: commandText,
|
||||
commandText: commandText ?? commandArgv.join(" "),
|
||||
agentId:
|
||||
typeof (requestParams as { agentId?: unknown }).agentId === "string"
|
||||
? ((requestParams as { agentId: string }).agentId ?? null)
|
||||
@@ -586,7 +586,7 @@ describe("exec approval handlers", () => {
|
||||
systemRunPlan: {
|
||||
argv: ["/usr/bin/echo", "ok"],
|
||||
cwd: "/real/cwd",
|
||||
rawCommand: "/usr/bin/echo ok",
|
||||
commandText: "/usr/bin/echo ok",
|
||||
commandPreview: "echo ok",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
@@ -597,15 +597,15 @@ describe("exec approval handlers", () => {
|
||||
expect(requested).toBeTruthy();
|
||||
const request = (requested?.payload as { request?: Record<string, unknown> })?.request ?? {};
|
||||
expect(request["command"]).toBe("/usr/bin/echo ok");
|
||||
expect(request["commandPreview"]).toBe("echo ok");
|
||||
expect(request["commandArgv"]).toEqual(["/usr/bin/echo", "ok"]);
|
||||
expect(request["commandPreview"]).toBeUndefined();
|
||||
expect(request["commandArgv"]).toBeUndefined();
|
||||
expect(request["cwd"]).toBe("/real/cwd");
|
||||
expect(request["agentId"]).toBe("main");
|
||||
expect(request["sessionKey"]).toBe("agent:main:main");
|
||||
expect(request["systemRunPlan"]).toEqual({
|
||||
argv: ["/usr/bin/echo", "ok"],
|
||||
cwd: "/real/cwd",
|
||||
rawCommand: "/usr/bin/echo ok",
|
||||
commandText: "/usr/bin/echo ok",
|
||||
commandPreview: "echo ok",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
@@ -625,7 +625,7 @@ describe("exec approval handlers", () => {
|
||||
systemRunPlan: {
|
||||
argv: ["./env", "sh", "-c", "jq --version"],
|
||||
cwd: "/real/cwd",
|
||||
rawCommand: './env sh -c "jq --version"',
|
||||
commandText: './env sh -c "jq --version"',
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
},
|
||||
@@ -635,7 +635,10 @@ describe("exec approval handlers", () => {
|
||||
expect(requested).toBeTruthy();
|
||||
const request = (requested?.payload as { request?: Record<string, unknown> })?.request ?? {};
|
||||
expect(request["command"]).toBe('./env sh -c "jq --version"');
|
||||
expect(request["commandPreview"]).toBe("jq --version");
|
||||
expect(request["commandPreview"]).toBeUndefined();
|
||||
expect((request["systemRunPlan"] as { commandPreview?: string }).commandPreview).toBe(
|
||||
"jq --version",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts resolve during broadcast", async () => {
|
||||
|
||||
@@ -67,6 +67,22 @@ function supportsSpawnLineage(storeKey: string): boolean {
|
||||
return isSubagentSessionKey(storeKey) || isAcpSessionKey(storeKey);
|
||||
}
|
||||
|
||||
function normalizeSubagentRole(raw: string): "orchestrator" | "leaf" | undefined {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === "orchestrator" || normalized === "leaf") {
|
||||
return normalized;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeSubagentControlScope(raw: string): "children" | "none" | undefined {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === "children" || normalized === "none") {
|
||||
return normalized;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function applySessionsPatchToStore(params: {
|
||||
cfg: OpenClawConfig;
|
||||
store: Record<string, SessionEntry>;
|
||||
@@ -134,6 +150,48 @@ export async function applySessionsPatchToStore(params: {
|
||||
}
|
||||
}
|
||||
|
||||
if ("subagentRole" in patch) {
|
||||
const raw = patch.subagentRole;
|
||||
if (raw === null) {
|
||||
if (existing?.subagentRole) {
|
||||
return invalid("subagentRole cannot be cleared once set");
|
||||
}
|
||||
} else if (raw !== undefined) {
|
||||
if (!supportsSpawnLineage(storeKey)) {
|
||||
return invalid("subagentRole is only supported for subagent:* or acp:* sessions");
|
||||
}
|
||||
const normalized = normalizeSubagentRole(String(raw));
|
||||
if (!normalized) {
|
||||
return invalid('invalid subagentRole (use "orchestrator" or "leaf")');
|
||||
}
|
||||
if (existing?.subagentRole && existing.subagentRole !== normalized) {
|
||||
return invalid("subagentRole cannot be changed once set");
|
||||
}
|
||||
next.subagentRole = normalized;
|
||||
}
|
||||
}
|
||||
|
||||
if ("subagentControlScope" in patch) {
|
||||
const raw = patch.subagentControlScope;
|
||||
if (raw === null) {
|
||||
if (existing?.subagentControlScope) {
|
||||
return invalid("subagentControlScope cannot be cleared once set");
|
||||
}
|
||||
} else if (raw !== undefined) {
|
||||
if (!supportsSpawnLineage(storeKey)) {
|
||||
return invalid("subagentControlScope is only supported for subagent:* or acp:* sessions");
|
||||
}
|
||||
const normalized = normalizeSubagentControlScope(String(raw));
|
||||
if (!normalized) {
|
||||
return invalid('invalid subagentControlScope (use "children" or "none")');
|
||||
}
|
||||
if (existing?.subagentControlScope && existing.subagentControlScope !== normalized) {
|
||||
return invalid("subagentControlScope cannot be changed once set");
|
||||
}
|
||||
next.subagentControlScope = normalized;
|
||||
}
|
||||
}
|
||||
|
||||
if ("label" in patch) {
|
||||
const raw = patch.label;
|
||||
if (raw === null) {
|
||||
|
||||
28
src/infra/exec-approval-command-display.ts
Normal file
28
src/infra/exec-approval-command-display.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { ExecApprovalRequestPayload } from "./exec-approvals.js";
|
||||
|
||||
function normalizePreview(commandText: string, commandPreview?: string | null): string | null {
|
||||
const preview = commandPreview?.trim() ?? "";
|
||||
if (!preview || preview === commandText) {
|
||||
return null;
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
|
||||
export function resolveExecApprovalCommandDisplay(request: ExecApprovalRequestPayload): {
|
||||
commandText: string;
|
||||
commandPreview: string | null;
|
||||
} {
|
||||
if (request.host === "node" && request.systemRunPlan) {
|
||||
return {
|
||||
commandText: request.systemRunPlan.commandText,
|
||||
commandPreview: normalizePreview(
|
||||
request.systemRunPlan.commandText,
|
||||
request.systemRunPlan.commandPreview,
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
commandText: request.command,
|
||||
commandPreview: normalizePreview(request.command, request.commandPreview),
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
normalizeMessageChannel,
|
||||
type DeliverableMessageChannel,
|
||||
} from "../utils/message-channel.js";
|
||||
import { resolveExecApprovalCommandDisplay } from "./exec-approval-command-display.js";
|
||||
import { buildExecApprovalPendingReplyPayload } from "./exec-approval-reply.js";
|
||||
import type {
|
||||
ExecApprovalDecision,
|
||||
@@ -211,7 +212,9 @@ function formatApprovalCommand(command: string): { inline: boolean; text: string
|
||||
|
||||
function buildRequestMessage(request: ExecApprovalRequest, nowMs: number) {
|
||||
const lines: string[] = ["🔒 Exec approval required", `ID: ${request.id}`];
|
||||
const command = formatApprovalCommand(request.request.command);
|
||||
const command = formatApprovalCommand(
|
||||
resolveExecApprovalCommandDisplay(request.request).commandText,
|
||||
);
|
||||
if (command.inline) {
|
||||
lines.push(`Command: ${command.text}`);
|
||||
} else {
|
||||
@@ -375,7 +378,7 @@ function buildRequestPayloadForTarget(
|
||||
approvalId: request.id,
|
||||
approvalSlug: request.id.slice(0, 8),
|
||||
approvalCommandId: request.id,
|
||||
command: request.request.command,
|
||||
command: resolveExecApprovalCommandDisplay(request.request).commandText,
|
||||
cwd: request.request.cwd ?? undefined,
|
||||
host: request.request.host === "node" ? "node" : "gateway",
|
||||
nodeId: request.request.nodeId ?? undefined,
|
||||
|
||||
@@ -52,7 +52,7 @@ export type SystemRunApprovalFileOperand = {
|
||||
export type SystemRunApprovalPlan = {
|
||||
argv: string[];
|
||||
cwd: string | null;
|
||||
rawCommand: string | null;
|
||||
commandText: string;
|
||||
commandPreview?: string | null;
|
||||
agentId: string | null;
|
||||
sessionKey: string | null;
|
||||
|
||||
@@ -50,10 +50,15 @@ export function normalizeSystemRunApprovalPlan(value: unknown): SystemRunApprova
|
||||
if (candidate.mutableFileOperand !== undefined && mutableFileOperand === null) {
|
||||
return null;
|
||||
}
|
||||
const commandText =
|
||||
normalizeNonEmptyString(candidate.commandText) ?? normalizeNonEmptyString(candidate.rawCommand);
|
||||
if (!commandText) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
argv,
|
||||
cwd: normalizeNonEmptyString(candidate.cwd),
|
||||
rawCommand: normalizeNonEmptyString(candidate.rawCommand),
|
||||
commandText,
|
||||
commandPreview: normalizeNonEmptyString(candidate.commandPreview),
|
||||
agentId: normalizeNonEmptyString(candidate.agentId),
|
||||
sessionKey: normalizeNonEmptyString(candidate.sessionKey),
|
||||
|
||||
@@ -9,7 +9,7 @@ describe("resolveSystemRunApprovalRequestContext", () => {
|
||||
systemRunPlan: {
|
||||
argv: ["./env", "sh", "-c", "jq --version"],
|
||||
cwd: "/tmp",
|
||||
rawCommand: './env sh -c "jq --version"',
|
||||
commandText: './env sh -c "jq --version"',
|
||||
commandPreview: "jq --version",
|
||||
agentId: "main",
|
||||
sessionKey: "agent:main:main",
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import type { SystemRunApprovalPlan } from "./exec-approvals.js";
|
||||
import { normalizeSystemRunApprovalPlan } from "./system-run-approval-binding.js";
|
||||
import { formatExecCommand, resolveSystemRunCommand } from "./system-run-command.js";
|
||||
import { formatExecCommand, resolveSystemRunCommandRequest } from "./system-run-command.js";
|
||||
import { normalizeNonEmptyString, normalizeStringArray } from "./system-run-normalize.js";
|
||||
|
||||
type PreparedRunPayload = {
|
||||
cmdText: string;
|
||||
plan: SystemRunApprovalPlan;
|
||||
};
|
||||
|
||||
@@ -26,7 +25,7 @@ type SystemRunApprovalRuntimeContext =
|
||||
cwd: string | null;
|
||||
agentId: string | null;
|
||||
sessionKey: string | null;
|
||||
rawCommand: string | null;
|
||||
commandText: string;
|
||||
}
|
||||
| {
|
||||
ok: false;
|
||||
@@ -53,13 +52,33 @@ export function parsePreparedSystemRunPayload(payload: unknown): PreparedRunPayl
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
||||
return null;
|
||||
}
|
||||
const raw = payload as { cmdText?: unknown; plan?: unknown };
|
||||
const cmdText = normalizeNonEmptyString(raw.cmdText);
|
||||
const raw = payload as { plan?: unknown; commandText?: unknown; cmdText?: unknown };
|
||||
const plan = normalizeSystemRunApprovalPlan(raw.plan);
|
||||
if (!cmdText || !plan) {
|
||||
if (plan) {
|
||||
return { plan };
|
||||
}
|
||||
if (!raw.plan || typeof raw.plan !== "object" || Array.isArray(raw.plan)) {
|
||||
return null;
|
||||
}
|
||||
return { cmdText, plan };
|
||||
const legacyPlan = raw.plan as Record<string, unknown>;
|
||||
const argv = normalizeStringArray(legacyPlan.argv);
|
||||
const commandText =
|
||||
normalizeNonEmptyString(legacyPlan.rawCommand) ??
|
||||
normalizeNonEmptyString(raw.commandText) ??
|
||||
normalizeNonEmptyString(raw.cmdText);
|
||||
if (argv.length === 0 || !commandText) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
plan: {
|
||||
argv,
|
||||
cwd: normalizeNonEmptyString(legacyPlan.cwd),
|
||||
commandText,
|
||||
commandPreview: normalizeNonEmptyString(legacyPlan.commandPreview),
|
||||
agentId: normalizeNonEmptyString(legacyPlan.agentId),
|
||||
sessionKey: normalizeNonEmptyString(legacyPlan.sessionKey),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSystemRunApprovalRequestContext(params: {
|
||||
@@ -72,17 +91,22 @@ export function resolveSystemRunApprovalRequestContext(params: {
|
||||
sessionKey?: unknown;
|
||||
}): SystemRunApprovalRequestContext {
|
||||
const host = normalizeNonEmptyString(params.host) ?? "";
|
||||
const plan = host === "node" ? normalizeSystemRunApprovalPlan(params.systemRunPlan) : null;
|
||||
const normalizedPlan =
|
||||
host === "node" ? normalizeSystemRunApprovalPlan(params.systemRunPlan) : null;
|
||||
const fallbackArgv = normalizeStringArray(params.commandArgv);
|
||||
const fallbackCommand = normalizeCommandText(params.command);
|
||||
const commandText = plan ? (plan.rawCommand ?? formatExecCommand(plan.argv)) : fallbackCommand;
|
||||
const commandText = normalizedPlan
|
||||
? normalizedPlan.commandText || formatExecCommand(normalizedPlan.argv)
|
||||
: fallbackCommand;
|
||||
const commandPreview = normalizedPlan
|
||||
? normalizeCommandPreview(normalizedPlan.commandPreview ?? fallbackCommand, commandText)
|
||||
: null;
|
||||
const plan = normalizedPlan ? { ...normalizedPlan, commandPreview } : null;
|
||||
return {
|
||||
plan,
|
||||
commandArgv: plan?.argv ?? (fallbackArgv.length > 0 ? fallbackArgv : undefined),
|
||||
commandText,
|
||||
commandPreview: plan
|
||||
? normalizeCommandPreview(plan.commandPreview ?? fallbackCommand, commandText)
|
||||
: null,
|
||||
commandPreview,
|
||||
cwd: plan?.cwd ?? normalizeNonEmptyString(params.cwd),
|
||||
agentId: plan?.agentId ?? normalizeNonEmptyString(params.agentId),
|
||||
sessionKey: plan?.sessionKey ?? normalizeNonEmptyString(params.sessionKey),
|
||||
@@ -106,10 +130,10 @@ export function resolveSystemRunApprovalRuntimeContext(params: {
|
||||
cwd: normalizedPlan.cwd,
|
||||
agentId: normalizedPlan.agentId,
|
||||
sessionKey: normalizedPlan.sessionKey,
|
||||
rawCommand: normalizedPlan.rawCommand,
|
||||
commandText: normalizedPlan.commandText,
|
||||
};
|
||||
}
|
||||
const command = resolveSystemRunCommand({
|
||||
const command = resolveSystemRunCommandRequest({
|
||||
command: params.command,
|
||||
rawCommand: params.rawCommand,
|
||||
});
|
||||
@@ -123,6 +147,6 @@ export function resolveSystemRunApprovalRuntimeContext(params: {
|
||||
cwd: normalizeNonEmptyString(params.cwd),
|
||||
agentId: normalizeNonEmptyString(params.agentId),
|
||||
sessionKey: normalizeNonEmptyString(params.sessionKey),
|
||||
rawCommand: normalizeNonEmptyString(params.rawCommand),
|
||||
commandText: command.commandText,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { resolveSystemRunCommand } from "./system-run-command.js";
|
||||
import { resolveSystemRunCommandRequest } from "./system-run-command.js";
|
||||
|
||||
type ContractFixture = {
|
||||
cases: ContractCase[];
|
||||
@@ -28,7 +28,7 @@ const fixture = JSON.parse(fs.readFileSync(fixturePath, "utf8")) as ContractFixt
|
||||
describe("system-run command contract fixtures", () => {
|
||||
for (const entry of fixture.cases) {
|
||||
test(entry.name, () => {
|
||||
const result = resolveSystemRunCommand({
|
||||
const result = resolveSystemRunCommandRequest({
|
||||
command: entry.command,
|
||||
rawCommand: entry.rawCommand,
|
||||
});
|
||||
@@ -48,7 +48,7 @@ describe("system-run command contract fixtures", () => {
|
||||
if (!result.ok) {
|
||||
throw new Error(`unexpected validation failure: ${result.message}`);
|
||||
}
|
||||
expect(result.cmdText).toBe(entry.expected.displayCommand);
|
||||
expect(result.commandText).toBe(entry.expected.displayCommand);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
extractShellCommandFromArgv,
|
||||
formatExecCommand,
|
||||
resolveSystemRunCommand,
|
||||
resolveSystemRunCommandRequest,
|
||||
validateSystemRunCommandConsistency,
|
||||
} from "./system-run-command.js";
|
||||
|
||||
@@ -89,8 +90,8 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.shellCommand).toBe(null);
|
||||
expect(res.cmdText).toBe("echo hi");
|
||||
expect(res.shellPayload).toBe(null);
|
||||
expect(res.commandText).toBe("echo hi");
|
||||
});
|
||||
|
||||
test("validateSystemRunCommandConsistency rejects mismatched rawCommand vs direct argv", () => {
|
||||
@@ -104,6 +105,7 @@ describe("system run command helpers", () => {
|
||||
const res = validateSystemRunCommandConsistency({
|
||||
argv: ["/bin/sh", "-lc", "echo hi"],
|
||||
rawCommand: "echo hi",
|
||||
allowLegacyShellText: true,
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
if (!res.ok) {
|
||||
@@ -123,6 +125,7 @@ describe("system run command helpers", () => {
|
||||
const res = validateSystemRunCommandConsistency({
|
||||
argv: ["/usr/bin/env", "bash", "-lc", "echo hi"],
|
||||
rawCommand: "echo hi",
|
||||
allowLegacyShellText: true,
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
if (!res.ok) {
|
||||
@@ -148,8 +151,8 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.shellCommand).toBe("echo hi");
|
||||
expect(res.cmdText).toBe(raw);
|
||||
expect(res.shellPayload).toBe("echo hi");
|
||||
expect(res.commandText).toBe(raw);
|
||||
expect(res.previewText).toBe(null);
|
||||
});
|
||||
|
||||
@@ -177,8 +180,8 @@ describe("system run command helpers", () => {
|
||||
expect(res.details?.code).toBe("MISSING_COMMAND");
|
||||
});
|
||||
|
||||
test("resolveSystemRunCommand returns normalized argv and cmdText", () => {
|
||||
const res = resolveSystemRunCommand({
|
||||
test("resolveSystemRunCommandRequest accepts legacy shell payloads but returns canonical command text", () => {
|
||||
const res = resolveSystemRunCommandRequest({
|
||||
command: ["cmd.exe", "/d", "/s", "/c", "echo", "SAFE&&whoami"],
|
||||
rawCommand: "echo SAFE&&whoami",
|
||||
});
|
||||
@@ -187,12 +190,12 @@ describe("system run command helpers", () => {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.argv).toEqual(["cmd.exe", "/d", "/s", "/c", "echo", "SAFE&&whoami"]);
|
||||
expect(res.shellCommand).toBe("echo SAFE&&whoami");
|
||||
expect(res.cmdText).toBe("echo SAFE&&whoami");
|
||||
expect(res.shellPayload).toBe("echo SAFE&&whoami");
|
||||
expect(res.commandText).toBe("cmd.exe /d /s /c echo SAFE&&whoami");
|
||||
expect(res.previewText).toBe("echo SAFE&&whoami");
|
||||
});
|
||||
|
||||
test("resolveSystemRunCommand binds cmdText to full argv for shell-wrapper positional-argv carriers", () => {
|
||||
test("resolveSystemRunCommand binds commandText to full argv for shell-wrapper positional-argv carriers", () => {
|
||||
const res = resolveSystemRunCommand({
|
||||
command: ["/bin/sh", "-lc", '$0 "$1"', "/usr/bin/touch", "/tmp/marker"],
|
||||
});
|
||||
@@ -200,12 +203,12 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.shellCommand).toBe('$0 "$1"');
|
||||
expect(res.cmdText).toBe('/bin/sh -lc "$0 \\"$1\\"" /usr/bin/touch /tmp/marker');
|
||||
expect(res.shellPayload).toBe('$0 "$1"');
|
||||
expect(res.commandText).toBe('/bin/sh -lc "$0 \\"$1\\"" /usr/bin/touch /tmp/marker');
|
||||
expect(res.previewText).toBe(null);
|
||||
});
|
||||
|
||||
test("resolveSystemRunCommand binds cmdText to full argv when env prelude modifies shell wrapper", () => {
|
||||
test("resolveSystemRunCommand binds commandText to full argv when env prelude modifies shell wrapper", () => {
|
||||
const res = resolveSystemRunCommand({
|
||||
command: ["/usr/bin/env", "BASH_ENV=/tmp/payload.sh", "bash", "-lc", "echo hi"],
|
||||
});
|
||||
@@ -213,12 +216,12 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.shellCommand).toBe("echo hi");
|
||||
expect(res.cmdText).toBe('/usr/bin/env BASH_ENV=/tmp/payload.sh bash -lc "echo hi"');
|
||||
expect(res.shellPayload).toBe("echo hi");
|
||||
expect(res.commandText).toBe('/usr/bin/env BASH_ENV=/tmp/payload.sh bash -lc "echo hi"');
|
||||
expect(res.previewText).toBe(null);
|
||||
});
|
||||
|
||||
test("resolveSystemRunCommand keeps wrapper preview separate from approval text", () => {
|
||||
test("resolveSystemRunCommand keeps wrapper preview separate from canonical command text", () => {
|
||||
const res = resolveSystemRunCommand({
|
||||
command: ["./env", "sh", "-c", "jq --version"],
|
||||
});
|
||||
@@ -226,7 +229,7 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.cmdText).toBe("jq --version");
|
||||
expect(res.commandText).toBe('./env sh -c "jq --version"');
|
||||
expect(res.previewText).toBe("jq --version");
|
||||
});
|
||||
|
||||
@@ -239,8 +242,20 @@ describe("system run command helpers", () => {
|
||||
if (!res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.cmdText).toBe('./env sh -c "jq --version"');
|
||||
expect(res.commandText).toBe('./env sh -c "jq --version"');
|
||||
expect(res.previewText).toBe("jq --version");
|
||||
expect(res.shellCommand).toBe("jq --version");
|
||||
expect(res.shellPayload).toBe("jq --version");
|
||||
});
|
||||
|
||||
test("resolveSystemRunCommand rejects legacy shell payload text in strict mode", () => {
|
||||
const res = resolveSystemRunCommand({
|
||||
command: ["/bin/sh", "-lc", "echo hi"],
|
||||
rawCommand: "echo hi",
|
||||
});
|
||||
expect(res.ok).toBe(false);
|
||||
if (res.ok) {
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
expect(res.message).toContain("rawCommand does not match command");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,8 +14,8 @@ import {
|
||||
export type SystemRunCommandValidation =
|
||||
| {
|
||||
ok: true;
|
||||
shellCommand: string | null;
|
||||
cmdText: string;
|
||||
shellPayload: string | null;
|
||||
commandText: string;
|
||||
previewText: string | null;
|
||||
}
|
||||
| {
|
||||
@@ -28,9 +28,8 @@ export type ResolvedSystemRunCommand =
|
||||
| {
|
||||
ok: true;
|
||||
argv: string[];
|
||||
rawCommand: string | null;
|
||||
shellCommand: string | null;
|
||||
cmdText: string;
|
||||
commandText: string;
|
||||
shellPayload: string | null;
|
||||
previewText: string | null;
|
||||
}
|
||||
| {
|
||||
@@ -58,6 +57,12 @@ export function extractShellCommandFromArgv(argv: string[]): string | null {
|
||||
return extractShellWrapperCommand(argv).command;
|
||||
}
|
||||
|
||||
type SystemRunCommandDisplay = {
|
||||
shellPayload: string | null;
|
||||
commandText: string;
|
||||
previewText: string | null;
|
||||
};
|
||||
|
||||
const POSIX_OR_POWERSHELL_INLINE_WRAPPER_NAMES = new Set([
|
||||
"ash",
|
||||
"bash",
|
||||
@@ -100,29 +105,42 @@ function hasTrailingPositionalArgvAfterInlineCommand(argv: string[]): boolean {
|
||||
return wrapperArgv.slice(inlineCommandIndex + 1).some((entry) => entry.trim().length > 0);
|
||||
}
|
||||
|
||||
function buildSystemRunCommandDisplay(argv: string[]): SystemRunCommandDisplay {
|
||||
const shellWrapperResolution = extractShellWrapperCommand(argv);
|
||||
const shellPayload = shellWrapperResolution.command;
|
||||
const shellWrapperPositionalArgv = hasTrailingPositionalArgvAfterInlineCommand(argv);
|
||||
const envManipulationBeforeShellWrapper =
|
||||
shellWrapperResolution.isWrapper && hasEnvManipulationBeforeShellWrapper(argv);
|
||||
const formattedArgv = formatExecCommand(argv);
|
||||
const previewText =
|
||||
shellPayload !== null && !envManipulationBeforeShellWrapper && !shellWrapperPositionalArgv
|
||||
? shellPayload.trim()
|
||||
: null;
|
||||
return {
|
||||
shellPayload,
|
||||
commandText: formattedArgv,
|
||||
previewText,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRawCommandText(rawCommand?: unknown): string | null {
|
||||
return typeof rawCommand === "string" && rawCommand.trim().length > 0 ? rawCommand.trim() : null;
|
||||
}
|
||||
|
||||
export function validateSystemRunCommandConsistency(params: {
|
||||
argv: string[];
|
||||
rawCommand?: string | null;
|
||||
allowLegacyShellText?: boolean;
|
||||
}): SystemRunCommandValidation {
|
||||
const raw =
|
||||
typeof params.rawCommand === "string" && params.rawCommand.trim().length > 0
|
||||
? params.rawCommand.trim()
|
||||
: null;
|
||||
const shellWrapperResolution = extractShellWrapperCommand(params.argv);
|
||||
const shellCommand = shellWrapperResolution.command;
|
||||
const shellWrapperPositionalArgv = hasTrailingPositionalArgvAfterInlineCommand(params.argv);
|
||||
const envManipulationBeforeShellWrapper =
|
||||
shellWrapperResolution.isWrapper && hasEnvManipulationBeforeShellWrapper(params.argv);
|
||||
const mustBindDisplayToFullArgv = envManipulationBeforeShellWrapper || shellWrapperPositionalArgv;
|
||||
const formattedArgv = formatExecCommand(params.argv);
|
||||
const legacyShellText =
|
||||
shellCommand !== null && !mustBindDisplayToFullArgv ? shellCommand.trim() : null;
|
||||
const previewText = legacyShellText;
|
||||
const cmdText = raw ?? legacyShellText ?? formattedArgv;
|
||||
const raw = normalizeRawCommandText(params.rawCommand);
|
||||
const display = buildSystemRunCommandDisplay(params.argv);
|
||||
|
||||
if (raw) {
|
||||
const matchesCanonicalArgv = raw === formattedArgv;
|
||||
const matchesLegacyShellText = legacyShellText !== null && raw === legacyShellText;
|
||||
const matchesCanonicalArgv = raw === display.commandText;
|
||||
const matchesLegacyShellText =
|
||||
params.allowLegacyShellText === true &&
|
||||
display.previewText !== null &&
|
||||
raw === display.previewText;
|
||||
if (!matchesCanonicalArgv && !matchesLegacyShellText) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -130,8 +148,8 @@ export function validateSystemRunCommandConsistency(params: {
|
||||
details: {
|
||||
code: "RAW_COMMAND_MISMATCH",
|
||||
rawCommand: raw,
|
||||
inferred: legacyShellText ?? formattedArgv,
|
||||
formattedArgv,
|
||||
inferred: display.commandText,
|
||||
formattedArgv: display.commandText,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -139,10 +157,9 @@ export function validateSystemRunCommandConsistency(params: {
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
// Only treat this as a shell command when argv is a recognized shell wrapper.
|
||||
shellCommand: shellCommand !== null ? shellCommand : null,
|
||||
cmdText,
|
||||
previewText,
|
||||
shellPayload: display.shellPayload,
|
||||
commandText: display.commandText,
|
||||
previewText: display.previewText,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -150,10 +167,7 @@ export function resolveSystemRunCommand(params: {
|
||||
command?: unknown;
|
||||
rawCommand?: unknown;
|
||||
}): ResolvedSystemRunCommand {
|
||||
const raw =
|
||||
typeof params.rawCommand === "string" && params.rawCommand.trim().length > 0
|
||||
? params.rawCommand.trim()
|
||||
: null;
|
||||
const raw = normalizeRawCommandText(params.rawCommand);
|
||||
const command = Array.isArray(params.command) ? params.command : [];
|
||||
if (command.length === 0) {
|
||||
if (raw) {
|
||||
@@ -166,9 +180,8 @@ export function resolveSystemRunCommand(params: {
|
||||
return {
|
||||
ok: true,
|
||||
argv: [],
|
||||
rawCommand: null,
|
||||
shellCommand: null,
|
||||
cmdText: "",
|
||||
commandText: "",
|
||||
shellPayload: null,
|
||||
previewText: null,
|
||||
};
|
||||
}
|
||||
@@ -177,6 +190,7 @@ export function resolveSystemRunCommand(params: {
|
||||
const validation = validateSystemRunCommandConsistency({
|
||||
argv,
|
||||
rawCommand: raw,
|
||||
allowLegacyShellText: false,
|
||||
});
|
||||
if (!validation.ok) {
|
||||
return {
|
||||
@@ -189,9 +203,54 @@ export function resolveSystemRunCommand(params: {
|
||||
return {
|
||||
ok: true,
|
||||
argv,
|
||||
rawCommand: raw,
|
||||
shellCommand: validation.shellCommand,
|
||||
cmdText: validation.cmdText,
|
||||
commandText: validation.commandText,
|
||||
shellPayload: validation.shellPayload,
|
||||
previewText: validation.previewText,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSystemRunCommandRequest(params: {
|
||||
command?: unknown;
|
||||
rawCommand?: unknown;
|
||||
}): ResolvedSystemRunCommand {
|
||||
const raw = normalizeRawCommandText(params.rawCommand);
|
||||
const command = Array.isArray(params.command) ? params.command : [];
|
||||
if (command.length === 0) {
|
||||
if (raw) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "rawCommand requires params.command",
|
||||
details: { code: "MISSING_COMMAND" },
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
argv: [],
|
||||
commandText: "",
|
||||
shellPayload: null,
|
||||
previewText: null,
|
||||
};
|
||||
}
|
||||
|
||||
const argv = command.map((v) => String(v));
|
||||
const validation = validateSystemRunCommandConsistency({
|
||||
argv,
|
||||
rawCommand: raw,
|
||||
allowLegacyShellText: true,
|
||||
});
|
||||
if (!validation.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
message: validation.message,
|
||||
details: validation.details ?? { code: "RAW_COMMAND_MISMATCH" },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
argv,
|
||||
commandText: validation.commandText,
|
||||
shellPayload: validation.shellPayload,
|
||||
previewText: validation.previewText,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ describe("hardenApprovedExecutionPaths", () => {
|
||||
mode: "build-plan",
|
||||
argv: ["env", "sh", "-c", "echo SAFE"],
|
||||
expectedArgv: () => ["env", "sh", "-c", "echo SAFE"],
|
||||
expectedCmdText: "echo SAFE",
|
||||
expectedCmdText: 'env sh -c "echo SAFE"',
|
||||
expectedCommandPreview: "echo SAFE",
|
||||
},
|
||||
{
|
||||
@@ -144,7 +144,7 @@ describe("hardenApprovedExecutionPaths", () => {
|
||||
mode: "build-plan",
|
||||
argv: ["./env", "sh", "-c", "echo SAFE"],
|
||||
expectedArgv: () => ["./env", "sh", "-c", "echo SAFE"],
|
||||
expectedCmdText: "echo SAFE",
|
||||
expectedCmdText: './env sh -c "echo SAFE"',
|
||||
checkRawCommandMatchesArgv: true,
|
||||
expectedCommandPreview: "echo SAFE",
|
||||
},
|
||||
@@ -175,10 +175,10 @@ describe("hardenApprovedExecutionPaths", () => {
|
||||
}
|
||||
expect(prepared.plan.argv).toEqual(testCase.expectedArgv({ pathToken }));
|
||||
if (testCase.expectedCmdText) {
|
||||
expect(prepared.cmdText).toBe(testCase.expectedCmdText);
|
||||
expect(prepared.plan.commandText).toBe(testCase.expectedCmdText);
|
||||
}
|
||||
if (testCase.checkRawCommandMatchesArgv) {
|
||||
expect(prepared.plan.rawCommand).toBe(formatExecCommand(prepared.plan.argv));
|
||||
expect(prepared.plan.commandText).toBe(formatExecCommand(prepared.plan.argv));
|
||||
}
|
||||
if ("expectedCommandPreview" in testCase) {
|
||||
expect(prepared.plan.commandPreview ?? null).toBe(testCase.expectedCommandPreview);
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
POSIX_INLINE_COMMAND_FLAGS,
|
||||
resolveInlineCommandMatch,
|
||||
} from "../infra/shell-inline-command.js";
|
||||
import { formatExecCommand, resolveSystemRunCommand } from "../infra/system-run-command.js";
|
||||
import { formatExecCommand, resolveSystemRunCommandRequest } from "../infra/system-run-command.js";
|
||||
|
||||
export type ApprovedCwdSnapshot = {
|
||||
cwd: string;
|
||||
@@ -630,8 +630,8 @@ export function buildSystemRunApprovalPlan(params: {
|
||||
cwd?: unknown;
|
||||
agentId?: unknown;
|
||||
sessionKey?: unknown;
|
||||
}): { ok: true; plan: SystemRunApprovalPlan; cmdText: string } | { ok: false; message: string } {
|
||||
const command = resolveSystemRunCommand({
|
||||
}): { ok: true; plan: SystemRunApprovalPlan } | { ok: false; message: string } {
|
||||
const command = resolveSystemRunCommandRequest({
|
||||
command: params.command,
|
||||
rawCommand: params.rawCommand,
|
||||
});
|
||||
@@ -644,15 +644,15 @@ export function buildSystemRunApprovalPlan(params: {
|
||||
const hardening = hardenApprovedExecutionPaths({
|
||||
approvedByAsk: true,
|
||||
argv: command.argv,
|
||||
shellCommand: command.shellCommand,
|
||||
shellCommand: command.shellPayload,
|
||||
cwd: normalizeString(params.cwd) ?? undefined,
|
||||
});
|
||||
if (!hardening.ok) {
|
||||
return { ok: false, message: hardening.message };
|
||||
}
|
||||
const rawCommand = formatExecCommand(hardening.argv) || null;
|
||||
const commandText = formatExecCommand(hardening.argv);
|
||||
const commandPreview =
|
||||
command.previewText?.trim() && command.previewText.trim() !== rawCommand
|
||||
command.previewText?.trim() && command.previewText.trim() !== commandText
|
||||
? command.previewText.trim()
|
||||
: null;
|
||||
const mutableFileOperand = resolveMutableFileOperandSnapshotSync({
|
||||
@@ -667,12 +667,11 @@ export function buildSystemRunApprovalPlan(params: {
|
||||
plan: {
|
||||
argv: hardening.argv,
|
||||
cwd: hardening.cwd ?? null,
|
||||
rawCommand,
|
||||
commandText,
|
||||
commandPreview,
|
||||
agentId: normalizeString(params.agentId),
|
||||
sessionKey: normalizeString(params.sessionKey),
|
||||
mutableFileOperand: mutableFileOperand.snapshot ?? undefined,
|
||||
},
|
||||
cmdText: commandPreview ?? rawCommand ?? formatExecCommand(hardening.argv),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -432,7 +432,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
expectInvokeOk(sendInvokeResult, { payloadContains: "app-ok" });
|
||||
});
|
||||
|
||||
it("forwards canonical cmdText to mac app exec host for positional-argv shell wrappers", async () => {
|
||||
it("forwards canonical command text to mac app exec host for positional-argv shell wrappers", async () => {
|
||||
const { runViaMacAppExecHost } = await runSystemInvoke({
|
||||
preferMacAppExecHost: true,
|
||||
command: ["/bin/sh", "-lc", '$0 "$1"', "/usr/bin/touch", "/tmp/marker"],
|
||||
@@ -505,7 +505,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
approvals: expect.anything(),
|
||||
request: expect.objectContaining({
|
||||
command: ["env", "sh", "-c", "echo SAFE"],
|
||||
rawCommand: "echo SAFE",
|
||||
rawCommand: 'env sh -c "echo SAFE"',
|
||||
cwd: canonicalCwd,
|
||||
}),
|
||||
});
|
||||
@@ -593,7 +593,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
const { runCommand, sendInvokeResult } = await runSystemInvoke({
|
||||
preferMacAppExecHost: false,
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
approved: true,
|
||||
security: "full",
|
||||
ask: "off",
|
||||
@@ -789,7 +789,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
const { runCommand, sendInvokeResult } = await runSystemInvoke({
|
||||
preferMacAppExecHost: false,
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
systemRunPlan: prepared.plan,
|
||||
cwd: prepared.plan.cwd ?? tmp,
|
||||
approved: true,
|
||||
@@ -827,7 +827,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
const { runCommand, sendInvokeResult } = await runSystemInvoke({
|
||||
preferMacAppExecHost: false,
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
systemRunPlan: prepared.plan,
|
||||
cwd: prepared.plan.cwd ?? tmp,
|
||||
approved: true,
|
||||
@@ -866,7 +866,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
const { runCommand, sendInvokeResult } = await runSystemInvoke({
|
||||
preferMacAppExecHost: false,
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
systemRunPlan: prepared.plan,
|
||||
cwd: prepared.plan.cwd ?? tmp,
|
||||
approved: true,
|
||||
@@ -908,7 +908,7 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
|
||||
const { runCommand, sendInvokeResult } = await runSystemInvoke({
|
||||
preferMacAppExecHost: false,
|
||||
command: prepared.plan.argv,
|
||||
rawCommand: prepared.plan.rawCommand,
|
||||
rawCommand: prepared.plan.commandText,
|
||||
systemRunPlan: prepared.plan,
|
||||
cwd: prepared.plan.cwd ?? tmp,
|
||||
approved: true,
|
||||
|
||||
@@ -16,7 +16,7 @@ import type { ExecHostRequest, ExecHostResponse, ExecHostRunResult } from "../in
|
||||
import { resolveExecSafeBinRuntimePolicy } from "../infra/exec-safe-bin-runtime-policy.js";
|
||||
import { sanitizeSystemRunEnvOverrides } from "../infra/host-env-security.js";
|
||||
import { normalizeSystemRunApprovalPlan } from "../infra/system-run-approval-binding.js";
|
||||
import { resolveSystemRunCommand } from "../infra/system-run-command.js";
|
||||
import { resolveSystemRunCommandRequest } from "../infra/system-run-command.js";
|
||||
import { logWarn } from "../logger.js";
|
||||
import { evaluateSystemRunPolicy, resolveExecApprovalDecision } from "./exec-policy.js";
|
||||
import {
|
||||
@@ -56,7 +56,7 @@ type SystemRunDeniedReason =
|
||||
type SystemRunExecutionContext = {
|
||||
sessionKey: string;
|
||||
runId: string;
|
||||
cmdText: string;
|
||||
commandText: string;
|
||||
suppressNotifyOnExit: boolean;
|
||||
};
|
||||
|
||||
@@ -64,8 +64,9 @@ type ResolvedExecApprovals = ReturnType<typeof resolveExecApprovals>;
|
||||
|
||||
type SystemRunParsePhase = {
|
||||
argv: string[];
|
||||
shellCommand: string | null;
|
||||
cmdText: string;
|
||||
shellPayload: string | null;
|
||||
commandText: string;
|
||||
commandPreview: string | null;
|
||||
approvalPlan: import("../infra/exec-approvals.js").SystemRunApprovalPlan | null;
|
||||
agentId: string | undefined;
|
||||
sessionKey: string;
|
||||
@@ -167,7 +168,7 @@ async function sendSystemRunDenied(
|
||||
sessionKey: execution.sessionKey,
|
||||
runId: execution.runId,
|
||||
host: "node",
|
||||
command: execution.cmdText,
|
||||
command: execution.commandText,
|
||||
reason: params.reason,
|
||||
suppressNotifyOnExit: execution.suppressNotifyOnExit,
|
||||
}),
|
||||
@@ -184,7 +185,7 @@ export { buildSystemRunApprovalPlan } from "./invoke-system-run-plan.js";
|
||||
async function parseSystemRunPhase(
|
||||
opts: HandleSystemRunInvokeOptions,
|
||||
): Promise<SystemRunParsePhase | null> {
|
||||
const command = resolveSystemRunCommand({
|
||||
const command = resolveSystemRunCommandRequest({
|
||||
command: opts.params.command,
|
||||
rawCommand: opts.params.rawCommand,
|
||||
});
|
||||
@@ -203,8 +204,8 @@ async function parseSystemRunPhase(
|
||||
return null;
|
||||
}
|
||||
|
||||
const shellCommand = command.shellCommand;
|
||||
const cmdText = command.cmdText;
|
||||
const shellPayload = command.shellPayload;
|
||||
const commandText = command.commandText;
|
||||
const approvalPlan =
|
||||
opts.params.systemRunPlan === undefined
|
||||
? null
|
||||
@@ -222,17 +223,18 @@ async function parseSystemRunPhase(
|
||||
const suppressNotifyOnExit = opts.params.suppressNotifyOnExit === true;
|
||||
const envOverrides = sanitizeSystemRunEnvOverrides({
|
||||
overrides: opts.params.env ?? undefined,
|
||||
shellWrapper: shellCommand !== null,
|
||||
shellWrapper: shellPayload !== null,
|
||||
});
|
||||
return {
|
||||
argv: command.argv,
|
||||
shellCommand,
|
||||
cmdText,
|
||||
shellPayload,
|
||||
commandText,
|
||||
commandPreview: command.previewText,
|
||||
approvalPlan,
|
||||
agentId,
|
||||
sessionKey,
|
||||
runId,
|
||||
execution: { sessionKey, runId, cmdText, suppressNotifyOnExit },
|
||||
execution: { sessionKey, runId, commandText, suppressNotifyOnExit },
|
||||
approvalDecision: resolveExecApprovalDecision(opts.params.approvalDecision),
|
||||
envOverrides,
|
||||
env: opts.sanitizeEnv(envOverrides),
|
||||
@@ -270,7 +272,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
});
|
||||
const bins = autoAllowSkills ? await opts.skillBins.current() : [];
|
||||
let { analysisOk, allowlistMatches, allowlistSatisfied, segments } = evaluateSystemRunAllowlist({
|
||||
shellCommand: parsed.shellCommand,
|
||||
shellCommand: parsed.shellPayload,
|
||||
argv: parsed.argv,
|
||||
approvals,
|
||||
security,
|
||||
@@ -283,7 +285,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
autoAllowSkills,
|
||||
});
|
||||
const isWindows = process.platform === "win32";
|
||||
const cmdInvocation = parsed.shellCommand
|
||||
const cmdInvocation = parsed.shellPayload
|
||||
? opts.isCmdExeInvocation(segments[0]?.argv ?? [])
|
||||
: opts.isCmdExeInvocation(parsed.argv);
|
||||
const policy = evaluateSystemRunPolicy({
|
||||
@@ -295,7 +297,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
approved: parsed.approved,
|
||||
isWindows,
|
||||
cmdInvocation,
|
||||
shellWrapperInvocation: parsed.shellCommand !== null,
|
||||
shellWrapperInvocation: parsed.shellPayload !== null,
|
||||
});
|
||||
analysisOk = policy.analysisOk;
|
||||
allowlistSatisfied = policy.allowlistSatisfied;
|
||||
@@ -308,7 +310,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
}
|
||||
|
||||
// Fail closed if policy/runtime drift re-allows unapproved shell wrappers.
|
||||
if (security === "allowlist" && parsed.shellCommand && !policy.approvedByAsk) {
|
||||
if (security === "allowlist" && parsed.shellPayload && !policy.approvedByAsk) {
|
||||
await sendSystemRunDenied(opts, parsed.execution, {
|
||||
reason: "approval-required",
|
||||
message: "SYSTEM_RUN_DENIED: approval required",
|
||||
@@ -319,7 +321,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
const hardenedPaths = hardenApprovedExecutionPaths({
|
||||
approvedByAsk: policy.approvedByAsk,
|
||||
argv: parsed.argv,
|
||||
shellCommand: parsed.shellCommand,
|
||||
shellCommand: parsed.shellPayload,
|
||||
cwd: parsed.cwd,
|
||||
});
|
||||
if (!hardenedPaths.ok) {
|
||||
@@ -340,7 +342,7 @@ async function evaluateSystemRunPolicyPhase(
|
||||
|
||||
const plannedAllowlistArgv = resolvePlannedAllowlistArgv({
|
||||
security,
|
||||
shellCommand: parsed.shellCommand,
|
||||
shellCommand: parsed.shellPayload,
|
||||
policy,
|
||||
segments,
|
||||
});
|
||||
@@ -405,7 +407,7 @@ async function executeSystemRunPhase(
|
||||
command: phase.plannedAllowlistArgv ?? phase.argv,
|
||||
// Forward canonical display text so companion approval/prompt surfaces bind to
|
||||
// the exact command context already validated on the node-host.
|
||||
rawCommand: phase.cmdText || null,
|
||||
rawCommand: phase.commandText || null,
|
||||
cwd: phase.cwd ?? null,
|
||||
env: phase.envOverrides ?? null,
|
||||
timeoutMs: phase.timeoutMs ?? null,
|
||||
@@ -437,7 +439,7 @@ async function executeSystemRunPhase(
|
||||
await opts.sendExecFinishedEvent({
|
||||
sessionKey: phase.sessionKey,
|
||||
runId: phase.runId,
|
||||
cmdText: phase.cmdText,
|
||||
commandText: phase.commandText,
|
||||
result,
|
||||
suppressNotifyOnExit: phase.suppressNotifyOnExit,
|
||||
});
|
||||
@@ -476,7 +478,7 @@ async function executeSystemRunPhase(
|
||||
phase.approvals.file,
|
||||
phase.agentId,
|
||||
match,
|
||||
phase.cmdText,
|
||||
phase.commandText,
|
||||
phase.segments[0]?.resolution?.resolvedPath,
|
||||
);
|
||||
}
|
||||
@@ -496,7 +498,7 @@ async function executeSystemRunPhase(
|
||||
security: phase.security,
|
||||
isWindows: phase.isWindows,
|
||||
policy: phase.policy,
|
||||
shellCommand: phase.shellCommand,
|
||||
shellCommand: phase.shellPayload,
|
||||
segments: phase.segments,
|
||||
});
|
||||
|
||||
@@ -505,7 +507,7 @@ async function executeSystemRunPhase(
|
||||
await opts.sendExecFinishedEvent({
|
||||
sessionKey: phase.sessionKey,
|
||||
runId: phase.runId,
|
||||
cmdText: phase.cmdText,
|
||||
commandText: phase.commandText,
|
||||
result,
|
||||
suppressNotifyOnExit: phase.suppressNotifyOnExit,
|
||||
});
|
||||
|
||||
@@ -51,7 +51,7 @@ export type ExecFinishedResult = {
|
||||
export type ExecFinishedEventParams = {
|
||||
sessionKey: string;
|
||||
runId: string;
|
||||
cmdText: string;
|
||||
commandText: string;
|
||||
result: ExecFinishedResult;
|
||||
suppressNotifyOnExit?: boolean;
|
||||
};
|
||||
|
||||
@@ -350,7 +350,7 @@ async function sendExecFinishedEvent(
|
||||
sessionKey: params.sessionKey,
|
||||
runId: params.runId,
|
||||
host: "node",
|
||||
command: params.cmdText,
|
||||
command: params.commandText,
|
||||
exitCode: params.result.exitCode ?? undefined,
|
||||
timedOut: params.result.timedOut,
|
||||
success: params.result.success,
|
||||
@@ -505,7 +505,6 @@ export async function handleInvoke(
|
||||
return;
|
||||
}
|
||||
await sendJsonPayloadResult(client, frame, {
|
||||
cmdText: prepared.cmdText,
|
||||
plan: prepared.plan,
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -549,8 +548,8 @@ export async function handleInvoke(
|
||||
sendInvokeResult: async (result) => {
|
||||
await sendInvokeResult(client, frame, result);
|
||||
},
|
||||
sendExecFinishedEvent: async ({ sessionKey, runId, cmdText, result }) => {
|
||||
await sendExecFinishedEvent({ client, sessionKey, runId, cmdText, result });
|
||||
sendExecFinishedEvent: async ({ sessionKey, runId, commandText, result }) => {
|
||||
await sendExecFinishedEvent({ client, sessionKey, runId, commandText, result });
|
||||
},
|
||||
preferMacAppExecHost,
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
|
||||
import { GatewayClient } from "../gateway/client.js";
|
||||
import { createOperatorApprovalsGatewayClient } from "../gateway/operator-approvals-client.js";
|
||||
import type { EventFrame } from "../gateway/protocol/index.js";
|
||||
import { resolveExecApprovalCommandDisplay } from "../infra/exec-approval-command-display.js";
|
||||
import {
|
||||
buildExecApprovalPendingReplyPayload,
|
||||
type ExecApprovalPendingReplyParams,
|
||||
@@ -312,7 +313,7 @@ export class TelegramExecApprovalHandler {
|
||||
approvalId: request.id,
|
||||
approvalSlug: request.id.slice(0, 8),
|
||||
approvalCommandId: request.id,
|
||||
command: request.request.command,
|
||||
command: resolveExecApprovalCommandDisplay(request.request).commandText,
|
||||
cwd: request.request.cwd ?? undefined,
|
||||
host: request.request.host === "node" ? "node" : "gateway",
|
||||
nodeId: request.request.nodeId ?? undefined,
|
||||
|
||||
@@ -10,19 +10,18 @@ type SystemRunPrepareInput = {
|
||||
|
||||
export function buildSystemRunPreparePayload(params: SystemRunPrepareInput) {
|
||||
const argv = Array.isArray(params.command) ? params.command.map(String) : [];
|
||||
const rawCommand =
|
||||
const previewCommand =
|
||||
typeof params.rawCommand === "string" && params.rawCommand.trim().length > 0
|
||||
? params.rawCommand
|
||||
: null;
|
||||
const formattedArgv = formatExecCommand(argv) || null;
|
||||
const commandPreview = rawCommand && rawCommand !== formattedArgv ? rawCommand : null;
|
||||
const commandText = formatExecCommand(argv) || "";
|
||||
const commandPreview = previewCommand && previewCommand !== commandText ? previewCommand : null;
|
||||
return {
|
||||
payload: {
|
||||
cmdText: rawCommand ?? argv.join(" "),
|
||||
plan: {
|
||||
argv,
|
||||
cwd: typeof params.cwd === "string" ? params.cwd : null,
|
||||
rawCommand: formattedArgv,
|
||||
commandText,
|
||||
commandPreview,
|
||||
agentId: typeof params.agentId === "string" ? params.agentId : null,
|
||||
sessionKey: typeof params.sessionKey === "string" ? params.sessionKey : null,
|
||||
|
||||
@@ -18,12 +18,12 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "shell wrapper accepts shell payload raw command when no positional argv carriers",
|
||||
"name": "shell wrapper accepts shell payload raw command at ingress",
|
||||
"command": ["/bin/sh", "-lc", "echo hi"],
|
||||
"rawCommand": "echo hi",
|
||||
"expected": {
|
||||
"valid": true,
|
||||
"displayCommand": "echo hi"
|
||||
"displayCommand": "/bin/sh -lc \"echo hi\""
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -45,12 +45,12 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "env wrapper shell payload accepted when prelude has no env modifiers",
|
||||
"name": "env wrapper shell payload accepted at ingress when prelude has no env modifiers",
|
||||
"command": ["/usr/bin/env", "bash", "-lc", "echo hi"],
|
||||
"rawCommand": "echo hi",
|
||||
"expected": {
|
||||
"valid": true,
|
||||
"displayCommand": "echo hi"
|
||||
"displayCommand": "/usr/bin/env bash -lc \"echo hi\""
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { afterAll, afterEach, beforeAll, vi } from "vitest";
|
||||
|
||||
vi.mock("@mariozechner/pi-ai/oauth", () => ({
|
||||
getOAuthApiKey: () => undefined,
|
||||
getOAuthProviders: () => [],
|
||||
loginOpenAICodex: vi.fn(),
|
||||
}));
|
||||
|
||||
// Ensure Vitest environment is properly set
|
||||
process.env.VITEST = "true";
|
||||
// Config validation walks plugin manifests; keep an aggressive cache in tests to avoid
|
||||
|
||||
Reference in New Issue
Block a user