Skip to content

Commit 357643f

Browse files
committed
feat(agents): session self-service tools
New grouped sessions tool: patch (label/pin/archive/model/thinking, own tree only, owner-gated) + global group CRUD; no reset/delete/compact. sessions_spawn gains visible+worktree via sessions.create with admission reservation, abort-confirmed rollback, and kept completion announces. subagents tool reads the unified task ledger tree-scoped (subagent, acp, media, cron) and cancels detached runs. session_status gains a cost line. Agent-origin model patches record a fallback marker; runs failing on auth/billing/model_not_found revert to the last working model with a system note (transient provider errors never revert). Refs #107237
1 parent 332ed32 commit 357643f

33 files changed

Lines changed: 2645 additions & 246 deletions

‎src/agents/core-tool-factory-descriptors.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export const CORE_TOOL_FACTORY_DESCRIPTORS = [
3030
{ name: "nodes", family: "openclaw" },
3131
{ name: "pdf", family: "openclaw" },
3232
{ name: "session_status", family: "openclaw" },
33+
{ name: "sessions", family: "openclaw" },
3334
{ name: "sessions_history", family: "openclaw" },
3435
{ name: "sessions_list", family: "openclaw" },
3536
{ name: "sessions_search", family: "openclaw" },

‎src/agents/openclaw-tools.ts‎

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import type { AnyAgentTool } from "./tools/common.js";
4646
import { createComputerTool } from "./tools/computer-tool.js";
4747
import { createCronTool, type CronCreatorToolAllowlistEntry } from "./tools/cron-tool.js";
4848
import { createEmbeddedCallGateway } from "./tools/embedded-gateway-stub.js";
49-
import { wrapToolWithGatewayCallerIdentity } from "./tools/gateway-caller-context.js";
49+
import { createGatewayToolCallerWrapper } from "./tools/gateway-caller-context.js";
5050
import { createGatewayTool } from "./tools/gateway-tool.js";
5151
import {
5252
createCreateGoalTool,
@@ -66,6 +66,7 @@ import { createSessionsListTool } from "./tools/sessions-list-tool.js";
6666
import { createSessionsSearchTool } from "./tools/sessions-search-tool.js";
6767
import { createSessionsSendTool } from "./tools/sessions-send-tool.js";
6868
import { createSessionsSpawnTool } from "./tools/sessions-spawn-tool.js";
69+
import { createSessionsTool } from "./tools/sessions-tool.js";
6970
import { createSessionsYieldTool } from "./tools/sessions-yield-tool.js";
7071
import { createConfiguredSkillWorkshopTool } from "./tools/skill-workshop-tool-factory.js";
7172
import { createSubagentsTool } from "./tools/subagents-tool.js";
@@ -477,6 +478,11 @@ export function createOpenClawTools(
477478
? { selfRemoveOnlyJobId: options.cronSelfRemoveOnlyJobId }
478479
: {}),
479480
}),
481+
createSessionsTool({
482+
agentSessionKey: options?.runSessionKey ?? options?.agentSessionKey,
483+
sandboxed: options?.sandboxed,
484+
config: resolvedConfig,
485+
}),
480486
]),
481487
...(!embedded && taskSuggestionSessionKey && options?.taskSuggestionDeliveryMode === "gateway"
482488
? createTaskSuggestionTools({
@@ -578,6 +584,9 @@ export function createOpenClawTools(
578584
agentAccountId: options?.agentAccountId,
579585
agentTo: options?.agentTo,
580586
agentThreadId: options?.agentThreadId,
587+
currentMessagingTarget: options?.currentMessagingTarget,
588+
currentChannelId: options?.currentChannelId,
589+
currentThreadTs: options?.currentThreadTs,
581590
agentGroupId: options?.agentGroupId,
582591
agentGroupChannel: options?.agentGroupChannel,
583592
agentGroupSpace: options?.agentGroupSpace,
@@ -597,6 +606,7 @@ export function createOpenClawTools(
597606
}),
598607
createSubagentsTool({
599608
agentSessionKey: options?.agentSessionKey,
609+
config: resolvedConfig,
600610
}),
601611
createSessionStatusTool({
602612
agentSessionKey: options?.agentSessionKey,
@@ -636,20 +646,7 @@ export function createOpenClawTools(
636646
options?.recordToolPrepStage?.("openclaw-tools:client-capabilities");
637647

638648
const hookAgentId = options?.requesterAgentIdOverride ?? sessionAgentId;
639-
const gatewayCallerIdentity =
640-
hookAgentId && options?.agentSessionKey?.trim()
641-
? {
642-
agentId: hookAgentId,
643-
sessionKey: options.agentSessionKey.trim(),
644-
turnSourceChannel: options.agentChannel,
645-
turnSourceTo:
646-
options.currentMessagingTarget ?? options.currentChannelId ?? options.agentTo,
647-
turnSourceAccountId: options.agentAccountId,
648-
turnSourceThreadId: options.currentThreadTs ?? options.agentThreadId,
649-
}
650-
: undefined;
651-
const wrapGatewayCallerIdentity = (tool: AnyAgentTool) =>
652-
wrapToolWithGatewayCallerIdentity(tool, gatewayCallerIdentity);
649+
const wrapGatewayCallerIdentity = createGatewayToolCallerWrapper(hookAgentId, options);
653650

654651
if (options?.wrapBeforeToolCallHook === false) {
655652
return allTools.map(wrapGatewayCallerIdentity);
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
/** One-run rollback for agent-selected session models. */
2+
import {
3+
appendTranscriptMessage,
4+
loadSessionEntry,
5+
patchSessionEntry,
6+
} from "../config/sessions/session-accessor.js";
7+
import {
8+
createAgentPatchedSessionModelFallback,
9+
type AgentPatchedSessionModelFallback,
10+
} from "../config/sessions/session-model-fallback.js";
11+
import type { OpenClawConfig } from "../config/types.openclaw.js";
12+
import type { FailoverReason } from "./embedded-agent-helpers/types.js";
13+
import { resolveFailoverReasonFromError } from "./failover-error.js";
14+
import { resolveSessionModelRef } from "./session-model-ref.js";
15+
16+
// Revert only when the chosen model is definitively unusable. Transient
17+
// provider states (rate_limit/overloaded/timeout/server_error) hit working
18+
// models too; reverting on them would undo a valid choice.
19+
const REVERT_REASONS = new Set<FailoverReason>([
20+
"auth",
21+
"auth_permanent",
22+
"billing",
23+
"model_not_found",
24+
]);
25+
26+
type SessionModelRunOutcome =
27+
| { success: true }
28+
| { success: false; error?: unknown; reason?: FailoverReason };
29+
30+
export async function reconcileAgentPatchedSessionModel(params: {
31+
cfg: OpenClawConfig;
32+
agentId?: string;
33+
sessionKey: string;
34+
storePath?: string;
35+
outcome: SessionModelRunOutcome;
36+
expectedMarkerTs?: number;
37+
validatedFallback?: AgentPatchedSessionModelFallback;
38+
now?: number;
39+
}): Promise<"cleared" | "promoted" | "reverted" | "kept" | "none"> {
40+
const reason = params.outcome.success
41+
? undefined
42+
: (params.outcome.reason ?? resolveFailoverReasonFromError(params.outcome.error));
43+
if (!params.outcome.success && (!reason || !REVERT_REASONS.has(reason))) {
44+
return "kept";
45+
}
46+
47+
let note: string | undefined;
48+
let sessionId: string | undefined;
49+
let result: "cleared" | "promoted" | "reverted" | "none" = "none";
50+
await patchSessionEntry(
51+
{
52+
agentId: params.agentId,
53+
sessionKey: params.sessionKey,
54+
storePath: params.storePath,
55+
},
56+
(entry) => {
57+
const marker = entry.modelFallback;
58+
if (marker?.source !== "agent-patch") {
59+
return null;
60+
}
61+
if (params.expectedMarkerTs !== undefined && marker.ts !== params.expectedMarkerTs) {
62+
if (
63+
params.outcome.success &&
64+
params.validatedFallback &&
65+
marker.ts > params.expectedMarkerTs &&
66+
params.expectedMarkerTs > (marker.lastValidatedPatchTs ?? -1)
67+
) {
68+
result = "promoted";
69+
return {
70+
modelFallback: {
71+
...params.validatedFallback,
72+
ts: marker.ts,
73+
lastValidatedPatchTs: params.expectedMarkerTs,
74+
},
75+
};
76+
}
77+
return null;
78+
}
79+
sessionId = entry.sessionId;
80+
if (params.outcome.success) {
81+
result = "cleared";
82+
return { modelFallback: undefined };
83+
}
84+
const failed = resolveSessionModelRef(params.cfg, entry, params.agentId);
85+
result = "reverted";
86+
note = `System note: model ${failed.provider}/${failed.model} failed; reverted to ${marker.prevProvider}/${marker.prevModel}.`;
87+
return {
88+
model: marker.prevModel,
89+
modelProvider: marker.prevProvider,
90+
modelOverride: marker.prevModelOverride,
91+
providerOverride: marker.prevProviderOverride,
92+
modelOverrideSource: marker.prevModelOverrideSource,
93+
modelOverrideFallbackOriginProvider: marker.prevModelOverrideFallbackOriginProvider,
94+
modelOverrideFallbackOriginModel: marker.prevModelOverrideFallbackOriginModel,
95+
authProfileOverride: marker.prevAuthProfileOverride,
96+
authProfileOverrideSource: marker.prevAuthProfileOverrideSource,
97+
authProfileOverrideCompactionCount: marker.prevAuthProfileOverrideCompactionCount,
98+
thinkingLevel: marker.prevThinkingLevel,
99+
modelFallback: undefined,
100+
liveModelSwitchPending: undefined,
101+
};
102+
},
103+
);
104+
if (note && sessionId) {
105+
try {
106+
const timestamp = params.now ?? Date.now();
107+
await appendTranscriptMessage(
108+
{
109+
agentId: params.agentId,
110+
sessionId,
111+
sessionKey: params.sessionKey,
112+
storePath: params.storePath,
113+
},
114+
{
115+
config: params.cfg,
116+
message: {
117+
role: "custom" as const,
118+
customType: "openclaw.system-note",
119+
content: note,
120+
display: true,
121+
timestamp,
122+
},
123+
...(params.now === undefined ? {} : { now: params.now }),
124+
},
125+
);
126+
} catch {
127+
// Rollback is authoritative; transcript note is best effort.
128+
}
129+
}
130+
return result;
131+
}
132+
133+
export function createAgentPatchedSessionModelRunGuard(params: {
134+
cfg: OpenClawConfig;
135+
agentId: string | undefined;
136+
sessionKey: string | undefined;
137+
storePath: string | undefined;
138+
onError?: (error: unknown) => void;
139+
}) {
140+
let markerTs: number | undefined;
141+
let validatedFallback: AgentPatchedSessionModelFallback | undefined;
142+
if (params.sessionKey) {
143+
try {
144+
const entry = loadSessionEntry({
145+
agentId: params.agentId,
146+
sessionKey: params.sessionKey,
147+
storePath: params.storePath,
148+
});
149+
const marker = entry?.modelFallback;
150+
markerTs = marker?.source === "agent-patch" ? marker.ts : undefined;
151+
if (entry && markerTs !== undefined) {
152+
const current = resolveSessionModelRef(params.cfg, entry, params.agentId);
153+
validatedFallback = createAgentPatchedSessionModelFallback({
154+
model: current.model,
155+
provider: current.provider,
156+
entry,
157+
ts: markerTs,
158+
});
159+
}
160+
} catch {
161+
markerTs = undefined;
162+
}
163+
}
164+
let failure: { error?: unknown; reason?: FailoverReason } = {};
165+
let reconciled = false;
166+
const captureFailure = (error: unknown, reason?: string) => {
167+
const classifiedReason = reason
168+
? (reason as FailoverReason)
169+
: resolveFailoverReasonFromError(error);
170+
const revertReason =
171+
classifiedReason && REVERT_REASONS.has(classifiedReason) ? classifiedReason : undefined;
172+
failure = { error, ...(revertReason ? { reason: revertReason } : {}) };
173+
return revertReason !== undefined;
174+
};
175+
const captureFallbackFailure = (
176+
attempts: readonly { error: string; reason?: string }[],
177+
): boolean | undefined => {
178+
const attempt = attempts[0];
179+
return attempt ? captureFailure(new Error(attempt.error), attempt.reason) : undefined;
180+
};
181+
const reconcile = async (success: boolean) => {
182+
if (reconciled || !params.sessionKey || markerTs === undefined) {
183+
return;
184+
}
185+
reconciled = true;
186+
try {
187+
await reconcileAgentPatchedSessionModel({
188+
cfg: params.cfg,
189+
...(params.agentId ? { agentId: params.agentId } : {}),
190+
sessionKey: params.sessionKey,
191+
...(params.storePath ? { storePath: params.storePath } : {}),
192+
expectedMarkerTs: markerTs,
193+
...(validatedFallback ? { validatedFallback } : {}),
194+
outcome: success ? { success: true } : { success: false, ...failure },
195+
});
196+
} catch (error) {
197+
params.onError?.(error);
198+
}
199+
};
200+
return {
201+
captureFailure,
202+
captureFallbackFailure,
203+
async fail(error: unknown, reason?: string) {
204+
captureFailure(error, reason);
205+
await reconcile(false);
206+
},
207+
async finish(success: boolean) {
208+
await reconcile(success);
209+
},
210+
};
211+
}

‎src/agents/subagent-depth.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ describe("getSubagentDepthFromSessionStore", () => {
5959
expect(depth).toBe(3);
6060
});
6161

62+
it("derives visible dashboard depth from parentSessionKey", () => {
63+
const depth = getSubagentDepthFromSessionStore("agent:main:dashboard:child", {
64+
store: {
65+
"agent:main:main": { sessionId: "root" },
66+
"agent:main:dashboard:child": {
67+
sessionId: "child",
68+
parentSessionKey: "agent:main:main",
69+
},
70+
},
71+
});
72+
73+
expect(depth).toBe(1);
74+
});
75+
6276
it("resolves depth when caller is identified by sessionId", () => {
6377
const key1 = "agent:main:subagent:one";
6478
const key2 = "agent:main:subagent:two";
@@ -100,6 +114,41 @@ describe("getSubagentDepthFromSessionStore", () => {
100114

101115
expect(depth).toBe(2);
102116
});
117+
118+
it("resolves a cross-agent parent outside the supplied child store", async () => {
119+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-subagent-depth-cross-agent-"));
120+
try {
121+
const storeTemplate = path.join(tmpDir, "sessions-{agentId}.json");
122+
const parentKey = "agent:main:dashboard:parent";
123+
await replaceSessionEntry(
124+
{
125+
agentId: "main",
126+
storePath: storeTemplate.replaceAll("{agentId}", "main"),
127+
sessionKey: parentKey,
128+
},
129+
{
130+
sessionId: "parent",
131+
updatedAt: Date.now(),
132+
spawnDepth: 2,
133+
},
134+
);
135+
136+
const depth = getSubagentDepthFromSessionStore("agent:work:dashboard:child", {
137+
cfg: { session: { store: storeTemplate } },
138+
store: {
139+
"agent:work:dashboard:child": {
140+
sessionId: "child",
141+
parentSessionKey: parentKey,
142+
},
143+
},
144+
});
145+
146+
expect(depth).toBe(3);
147+
} finally {
148+
fs.rmSync(tmpDir, { recursive: true, force: true });
149+
}
150+
});
151+
103152
it("falls back to session-key segment counting when metadata is missing", () => {
104153
const key = "agent:main:subagent:flat";
105154
const depth = getSubagentDepthFromSessionStore(key, {

‎src/agents/subagent-depth.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type SessionDepthEntry = {
1515
sessionId?: unknown;
1616
spawnDepth?: unknown;
1717
spawnedBy?: unknown;
18+
parentSessionKey?: unknown;
1819
};
1920

2021
function normalizeSpawnDepth(value: unknown): number | undefined {
@@ -88,7 +89,10 @@ function resolveEntryForSessionKey(params: {
8889
return entry;
8990
}
9091
}
91-
return findEntryBySessionId(params.store, params.sessionKey);
92+
const entry = findEntryBySessionId(params.store, params.sessionKey);
93+
if (entry || !params.cfg) {
94+
return entry;
95+
}
9296
}
9397

9498
if (!params.cfg) {
@@ -153,17 +157,18 @@ export function getSubagentDepthFromSessionStore(
153157
return storedDepth;
154158
}
155159

156-
const spawnedBy = normalizeOptionalString(entry?.spawnedBy);
157-
if (!spawnedBy) {
160+
const parentKey =
161+
normalizeOptionalString(entry?.spawnedBy) ?? normalizeOptionalString(entry?.parentSessionKey);
162+
if (!parentKey) {
158163
return undefined;
159164
}
160165

161-
const parentDepth = depthFromStore(spawnedBy);
166+
const parentDepth = depthFromStore(parentKey);
162167
if (parentDepth !== undefined) {
163168
return parentDepth + 1;
164169
}
165170

166-
return getSubagentDepth(spawnedBy) + 1;
171+
return getSubagentDepth(parentKey) + 1;
167172
};
168173

169174
return depthFromStore(raw) ?? fallbackDepth;

0 commit comments

Comments
 (0)