Skip to content

Commit 89a5bda

Browse files
authored
Merge branch 'main' into codex/fix-memory-cache-migration
2 parents 5d3c6ed + bb6874f commit 89a5bda

47 files changed

Lines changed: 3359 additions & 441 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/concepts/session-state.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ OpenClaw appends a typed event to the shared state database (`session_state_even
2828
| `run_completed` | A child run ends successfully | No (log only) |
2929
| `run_failed` | A child run fails, times out, or is cancelled | No (log only) |
3030
| `compacted` | The session's history is compacted | No (log only) |
31+
| `adopted` | A catalog session is adopted into OpenClaw | No (log only) |
3132

3233
Each event names its actor (`human`, `agent`, or `system`). Cancelled and timed-out child runs are recorded as failures with the precise outcome (`cancelled`, `timeout`, or `error`) preserved in the event payload.
3334

@@ -46,6 +47,8 @@ Watcher identity must be an agent-qualified session key. Under `session.scope="g
4647

4748
Watches clean themselves up: cursor rows expire with signal-log retention, are removed when the watcher session resets, and are deleted with either session. There is no unwatch verb in v1.
4849

50+
Watched sessions adopted from a session catalog are checked for direct upstream human activity on a fixed cadence. Detected activity enters the same signal log and watcher flow as other direct human turns.
51+
4952
## Notices: one, not many
5053

5154
When a notify-eligible event lands and a watcher's cursor is behind, the watcher receives one system notice on its next turn:
@@ -97,6 +100,12 @@ Current limits:
97100
- Notice delivery assumes one gateway process owns the shared state database. Multiple gateways share the durable log and `changesSince`, but v1 does not push notices across processes.
98101
- Compaction events cover the embedded runtime's compaction owners; native-harness-only compaction is not fully logged.
99102
- Cancelled-outcome payload detail is currently produced by ACP child runs; native sub-agent cancellations surface as generic failures.
103+
- Upstream self-echo detection compares normalized user text. An external prompt matching one of the session's 10 most recent OpenClaw-side user messages is treated as self-echo.
104+
- A single local Claude JSONL row larger than the 1 MiB per-cadence scan cap blocks that session's cursor in v1; unclassified bytes are never skipped.
105+
- Paired-node Claude checks classify the latest 50 transcript items per cadence. Larger bursts can fall outside the v1 scan window.
106+
- Catalog sessions that have not been adopted remain outside the awareness layer in v1.
107+
- Sessions adopted before this feature carry no upstream link; continue them from the catalog once to start upstream monitoring.
108+
- Upstream links assume each adopted session key maps to one owning agent (adoption uses the default store agent). Multi-agent adoption of the same external thread is not monitored in v1.
100109

101110
## Related
102111

‎docs/plugins/codex-supervision.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ Its private supervision binding uses the supervision connection for source
9999
reads, canonical branch creation, history injection, and every later turn. With
100100
the default local connection, that preserves the native user Codex home, auth,
101101
and provider configuration without changing the default for other sessions.
102+
Watched adopted Chats also participate in [session state awareness](/concepts/session-state).
102103

103104
For the default local supervision connection, the store is shared with native
104105
Codex clients. OpenClaw does not assume that another client shares the same live
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import { describe, expect, it, vi } from "vitest";
3+
import { importClaudeHistory } from "./session-catalog-history.js";
4+
5+
const appended: Array<Record<string, unknown>> = [];
6+
7+
vi.mock("openclaw/plugin-sdk/session-transcript-runtime", () => ({
8+
withSessionTranscriptWriteLock: async (
9+
_params: unknown,
10+
run: (transcript: {
11+
appendMessage: (input: { message: Record<string, unknown> }) => Promise<void>;
12+
}) => Promise<void>,
13+
) => {
14+
await run({
15+
appendMessage: async ({ message }) => {
16+
appended.push(message);
17+
},
18+
});
19+
},
20+
}));
21+
22+
describe("importClaudeHistory", () => {
23+
it("tags imported native user rows so self-echo provenance excludes them", async () => {
24+
appended.length = 0;
25+
await importClaudeHistory({
26+
items: [
27+
{ type: "userMessage", text: "continue", uuid: "u-1" },
28+
{ type: "assistantMessage", text: "done", uuid: "a-1" },
29+
],
30+
threadId: "thread-1",
31+
sessionFile: "/tmp/unused.jsonl",
32+
sessionId: "session-1",
33+
sessionKey: "agent:main:catalog-adopt",
34+
agentId: "main",
35+
config: {} as OpenClawConfig,
36+
});
37+
38+
const userRow = appended.find((message) => message.role === "user");
39+
// mirrorOrigin keeps imported native prompts out of ownRecentUserTexts; without
40+
// it a repeated external prompt like "continue" is swallowed as self-echo.
41+
expect(userRow?.["__openclaw"]).toMatchObject({ mirrorOrigin: "claude-catalog-import" });
42+
const assistantRow = appended.find((message) => message.role === "assistant");
43+
expect(assistantRow).toBeDefined();
44+
expect(assistantRow?.["__openclaw"]).toBeUndefined();
45+
});
46+
});
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import type { AgentMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
2+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
3+
import { withSessionTranscriptWriteLock } from "openclaw/plugin-sdk/session-transcript-runtime";
4+
import { CLAUDE_CLI_BACKEND_ID } from "./cli-constants.js";
5+
import type { ClaudeTranscriptItem } from "./session-catalog-transcript.js";
6+
7+
function importedClaudeMessage(
8+
item: ClaudeTranscriptItem,
9+
fallbackTimestamp: number,
10+
): AgentMessage {
11+
const timestamp = item.timestamp ? Date.parse(item.timestamp) : fallbackTimestamp;
12+
const text = item.text?.trim() || "[Unsupported Claude transcript item]";
13+
if (item.type === "userMessage") {
14+
// Imported native rows are not OpenClaw-authored; mirrorOrigin excludes them
15+
// from self-echo provenance so a repeated native prompt stays observable.
16+
return {
17+
role: "user",
18+
content: text,
19+
timestamp,
20+
__openclaw: { mirrorOrigin: "claude-catalog-import" },
21+
} as AgentMessage;
22+
}
23+
const prefix =
24+
item.type === "reasoning"
25+
? "Thinking\n\n"
26+
: item.type === "toolCall"
27+
? "Tool call\n\n"
28+
: item.type === "toolResult"
29+
? "Tool result\n\n"
30+
: "";
31+
return {
32+
role: "assistant",
33+
content: [{ type: "text", text: `${prefix}${text}` }],
34+
timestamp,
35+
api: "anthropic-messages",
36+
provider: CLAUDE_CLI_BACKEND_ID,
37+
model: "native-history",
38+
usage: {
39+
input: 0,
40+
output: 0,
41+
cacheRead: 0,
42+
cacheWrite: 0,
43+
totalTokens: 0,
44+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
45+
},
46+
stopReason: "stop",
47+
} as AgentMessage;
48+
}
49+
50+
export async function importClaudeHistory(params: {
51+
items: ClaudeTranscriptItem[];
52+
threadId: string;
53+
sessionFile: string;
54+
sessionId: string;
55+
sessionKey: string;
56+
agentId: string;
57+
cwd?: string;
58+
config: OpenClawConfig;
59+
}): Promise<void> {
60+
const items = params.items.toReversed();
61+
await withSessionTranscriptWriteLock(params, async (transcript) => {
62+
for (const [index, item] of items.entries()) {
63+
// The idempotency key rides on the message so recovery re-imports dedupe.
64+
const message = {
65+
...(importedClaudeMessage(item, Date.now() + index) as unknown as Record<string, unknown>),
66+
idempotencyKey: `claude-catalog:${params.threadId}:${item.uuid ?? index}`,
67+
} as unknown as AgentMessage;
68+
await transcript.appendMessage({
69+
message,
70+
idempotencyLookup: "scan",
71+
cwd: params.cwd,
72+
});
73+
}
74+
});
75+
}

‎extensions/anthropic/session-catalog.test.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,18 @@ describe("Claude session catalog", () => {
216216

217217
await expect(
218218
provider?.continueSession?.({ hostId: "gateway:local", threadId: sessionId }),
219-
).resolves.toEqual({
220-
sessionKey: expect.stringContaining("plugin:anthropic:catalog-adopt:claude:"),
221-
});
219+
).resolves.toEqual(
220+
expect.objectContaining({
221+
sessionKey: expect.stringContaining("plugin:anthropic:catalog-adopt:claude:"),
222+
upstream: {
223+
kind: "claude-cli",
224+
ref: {
225+
filePath: expect.stringContaining(`${sessionId}.jsonl`),
226+
},
227+
marker: { offset: expect.any(Number) },
228+
},
229+
}),
230+
);
222231
expect(createSessionEntry).toHaveBeenCalledWith(
223232
expect.objectContaining({
224233
spawnedCwd: "/work/source",
@@ -462,9 +471,12 @@ describe("Claude session catalog", () => {
462471
]);
463472
await expect(
464473
provider?.continueSession?.({ hostId: "gateway:local", threadId: sessionId }),
465-
).resolves.toEqual({
466-
sessionKey: expect.stringContaining("plugin:anthropic:catalog-adopt:claude:"),
467-
});
474+
).resolves.toEqual(
475+
expect.objectContaining({
476+
sessionKey: expect.stringContaining("plugin:anthropic:catalog-adopt:claude:"),
477+
upstream: expect.objectContaining({ kind: "claude-cli" }),
478+
}),
479+
);
468480
expect(createSessionEntry).toHaveBeenCalledWith(
469481
expect.objectContaining({
470482
initialEntry: expect.objectContaining({
@@ -563,6 +575,11 @@ describe("Claude session catalog", () => {
563575
await expect(provider?.continueSession?.({ hostId: "node:node-a", threadId })).resolves.toEqual(
564576
{
565577
sessionKey: expect.stringContaining("plugin:anthropic:catalog-adopt:claude:"),
578+
upstream: {
579+
kind: "claude-cli",
580+
ref: { nodeId: "node-a", threadId },
581+
marker: { uuid: "history-1" },
582+
},
566583
},
567584
);
568585
expect(createSessionEntry).toHaveBeenCalledWith(

‎extensions/anthropic/session-catalog.ts‎

Lines changed: 31 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
11
import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
4-
import type { AgentMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
54
import { resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-runtime";
6-
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
75
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
86
import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";
97
import type {
108
SessionCatalogHost,
119
SessionCatalogProvider,
1210
SessionCatalogTranscriptItem,
1311
} from "openclaw/plugin-sdk/session-catalog";
14-
import { withSessionTranscriptWriteLock } from "openclaw/plugin-sdk/session-transcript-runtime";
1512
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1613
import { CLAUDE_CLI_BACKEND_ID, CLAUDE_CLI_DEFAULT_MODEL_REF } from "./cli-constants.js";
1714
import {
1815
adoptedSessionKey,
1916
adoptedSourceKey,
2017
CLAUDE_LOCAL_SESSION_HOST_ID,
2118
} from "./session-catalog-adoption.js";
19+
import { importClaudeHistory } from "./session-catalog-history.js";
2220
import { createNodeListFailedError, resolveNodeLabel } from "./session-catalog-node-helpers.js";
2321
import {
2422
currentClaudeSessionCatalogConfig,
@@ -45,6 +43,7 @@ import type {
4543
ClaudeSessionCatalogSession,
4644
ClaudeSessionTranscriptPage,
4745
} from "./session-catalog-types.js";
46+
import * as upstream from "./session-upstream-activity.js";
4847

4948
export type { ClaudeTranscriptItem } from "./session-catalog-transcript.js";
5049
export type {
@@ -1065,72 +1064,6 @@ async function readBoundedClaudeHistory(params: {
10651064
return items;
10661065
}
10671066

1068-
function importedClaudeMessage(
1069-
item: ClaudeTranscriptItem,
1070-
fallbackTimestamp: number,
1071-
): AgentMessage {
1072-
const timestamp = item.timestamp ? Date.parse(item.timestamp) : fallbackTimestamp;
1073-
const text = item.text?.trim() || "[Unsupported Claude transcript item]";
1074-
if (item.type === "userMessage") {
1075-
return { role: "user", content: text, timestamp } as AgentMessage;
1076-
}
1077-
const prefix =
1078-
item.type === "reasoning"
1079-
? "Thinking\n\n"
1080-
: item.type === "toolCall"
1081-
? "Tool call\n\n"
1082-
: item.type === "toolResult"
1083-
? "Tool result\n\n"
1084-
: "";
1085-
return {
1086-
role: "assistant",
1087-
content: [{ type: "text", text: `${prefix}${text}` }],
1088-
timestamp,
1089-
api: "anthropic-messages",
1090-
provider: CLAUDE_CLI_BACKEND_ID,
1091-
model: "native-history",
1092-
usage: {
1093-
input: 0,
1094-
output: 0,
1095-
cacheRead: 0,
1096-
cacheWrite: 0,
1097-
totalTokens: 0,
1098-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1099-
},
1100-
stopReason: "stop",
1101-
} as AgentMessage;
1102-
}
1103-
1104-
async function importClaudeHistory(params: {
1105-
items: ClaudeTranscriptItem[];
1106-
threadId: string;
1107-
sessionFile: string;
1108-
sessionId: string;
1109-
sessionKey: string;
1110-
agentId: string;
1111-
cwd?: string;
1112-
config: OpenClawConfig;
1113-
}): Promise<void> {
1114-
const items = params.items.toReversed();
1115-
await withSessionTranscriptWriteLock(params, async (transcript) => {
1116-
for (const [index, item] of items.entries()) {
1117-
// The idempotency key rides on the message so recovery re-imports dedupe
1118-
// against the transcript instead of appending duplicate history.
1119-
const message = {
1120-
...(importedClaudeMessage(item, Date.now() + index) as unknown as Record<string, unknown>),
1121-
idempotencyKey: `claude-catalog:${params.threadId}:${item.uuid ?? index}`,
1122-
} as unknown as AgentMessage;
1123-
await transcript.appendMessage({
1124-
message,
1125-
idempotencyLookup: "scan",
1126-
cwd: params.cwd,
1127-
});
1128-
}
1129-
});
1130-
}
1131-
1132-
const claudeContinueOperations = new Map<string, Promise<{ sessionKey: string }>>();
1133-
11341067
export async function resolveNodeClaudeRecord(params: {
11351068
runtime: PluginRuntime;
11361069
nodeId: string;
@@ -1167,11 +1100,22 @@ async function continueClaudeSession(
11671100
threadId: string,
11681101
): Promise<{ sessionKey: string }> {
11691102
const sourceKey = adoptedSourceKey(hostId, threadId);
1103+
const linkSession = async (sessionKey: string, history?: ClaudeTranscriptItem[]) =>
1104+
await upstream.linkContinued({
1105+
sessionKey,
1106+
hostId,
1107+
threadId,
1108+
...(history ? { history } : {}),
1109+
listLocalSessions: listClaudeSessions,
1110+
readRemote: async () =>
1111+
(await readClaudeSessionTranscript({ runtime: api.runtime, hostId, threadId, limit: 1 }))
1112+
.items,
1113+
});
11701114
const existing = listBoundClaudeSessions(api).get(sourceKey);
11711115
if (existing) {
1172-
return { sessionKey: existing };
1116+
return await linkSession(existing);
11731117
}
1174-
const pending = claudeContinueOperations.get(sourceKey);
1118+
const pending = upstream.continueOperations.get(sourceKey);
11751119
if (pending) {
11761120
return await pending;
11771121
}
@@ -1257,21 +1201,21 @@ async function continueClaudeSession(
12571201
return { pluginExtensions: { anthropic: { sessionCatalog: marker } } };
12581202
},
12591203
});
1260-
return { sessionKey: created.key };
1204+
return await linkSession(created.key, history);
12611205
} catch (error) {
12621206
const raced = listBoundClaudeSessions(api).get(sourceKey);
12631207
if (raced) {
1264-
return { sessionKey: raced };
1208+
return await linkSession(raced, history);
12651209
}
12661210
throw error;
12671211
}
12681212
})();
1269-
claudeContinueOperations.set(sourceKey, operation);
1213+
upstream.continueOperations.set(sourceKey, operation);
12701214
try {
12711215
return await operation;
12721216
} finally {
1273-
if (claudeContinueOperations.get(sourceKey) === operation) {
1274-
claudeContinueOperations.delete(sourceKey);
1217+
if (upstream.continueOperations.get(sourceKey) === operation) {
1218+
upstream.continueOperations.delete(sourceKey);
12751219
}
12761220
}
12771221
}
@@ -1375,6 +1319,17 @@ export function registerClaudeSessionCatalog(api: OpenClawPluginApi): void {
13751319
listClaudeSessions,
13761320
resolveNodeClaudeRecord,
13771321
}),
1322+
checkUpstreamActivity: async (probes) =>
1323+
await upstream.checkClaudeUpstreamActivity(probes, async (probe) => {
1324+
return (
1325+
await readClaudeSessionTranscript({
1326+
runtime: api.runtime,
1327+
hostId: probe.hostId,
1328+
threadId: probe.threadId,
1329+
limit: MAX_TRANSCRIPT_LIMIT,
1330+
})
1331+
).items;
1332+
}),
13781333
};
13791334
api.registerSessionCatalog(provider);
13801335
}

0 commit comments

Comments
 (0)