|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry"; |
| 3 | +import { createSessionCatalogAdoptionCoordinator } from "openclaw/plugin-sdk/session-catalog"; |
| 4 | +import { CLAUDE_CLI_BACKEND_ID, CLAUDE_CLI_DEFAULT_MODEL_REF } from "./cli-constants.js"; |
| 5 | +import { |
| 6 | + adoptedSessionKey, |
| 7 | + adoptedSourceKey, |
| 8 | + CLAUDE_LOCAL_SESSION_HOST_ID, |
| 9 | +} from "./session-catalog-adoption.js"; |
| 10 | +import { type CatalogRecord, listClaudeSessions } from "./session-catalog-discovery.js"; |
| 11 | +import { importClaudeHistory } from "./session-catalog-history.js"; |
| 12 | +import { |
| 13 | + readBoundedClaudeHistory, |
| 14 | + readClaudeSessionTranscript, |
| 15 | + resolveNodeClaudeRecord, |
| 16 | +} from "./session-catalog-listing.js"; |
| 17 | +import { |
| 18 | + currentClaudeSessionCatalogConfig, |
| 19 | + listBoundClaudeSessions, |
| 20 | + resolveClaudeCliRoutedModelId, |
| 21 | +} from "./session-catalog-runtime.js"; |
| 22 | +import { currentHomeDir, gatewayClaudeScanOptions } from "./session-catalog-scan.js"; |
| 23 | +import { |
| 24 | + CLAUDE_CLI_NODE_RUN_COMMAND, |
| 25 | + CLAUDE_SESSION_READ_COMMAND, |
| 26 | + CLAUDE_SESSIONS_LIST_COMMAND, |
| 27 | + ClaudeCatalogParamsError, |
| 28 | + isResumableClaudeSource, |
| 29 | +} from "./session-catalog-shared.js"; |
| 30 | +import type { ClaudeTranscriptItem } from "./session-catalog-transcript.js"; |
| 31 | +import type { ClaudeSessionCatalogSession } from "./session-catalog-types.js"; |
| 32 | +import * as upstream from "./session-upstream-activity.js"; |
| 33 | + |
| 34 | +const continueClaudeAdoption = |
| 35 | + createSessionCatalogAdoptionCoordinator<Awaited<ReturnType<typeof upstream.linkContinued>>>(); |
| 36 | + |
| 37 | +export async function continueClaudeSession( |
| 38 | + api: OpenClawPluginApi, |
| 39 | + agentId: string, |
| 40 | + hostId: string, |
| 41 | + threadId: string, |
| 42 | + allowProcessHomeFallback?: boolean, |
| 43 | +): Promise<{ sessionKey: string }> { |
| 44 | + const scanOptions = gatewayClaudeScanOptions(allowProcessHomeFallback); |
| 45 | + const sourceKey = adoptedSourceKey(hostId, threadId); |
| 46 | + const operationKey = `${agentId}\0${sourceKey}`; |
| 47 | + const linkSession = async (sessionKey: string, history?: ClaudeTranscriptItem[]) => |
| 48 | + await upstream.linkContinued({ |
| 49 | + sessionKey, |
| 50 | + hostId, |
| 51 | + threadId, |
| 52 | + ...(history ? { history } : {}), |
| 53 | + listLocalSessions: () => listClaudeSessions(currentHomeDir(), scanOptions), |
| 54 | + readRemote: async () => |
| 55 | + ( |
| 56 | + await readClaudeSessionTranscript({ |
| 57 | + runtime: api.runtime, |
| 58 | + hostId, |
| 59 | + threadId, |
| 60 | + limit: 1, |
| 61 | + allowProcessHomeFallback, |
| 62 | + }) |
| 63 | + ).items, |
| 64 | + }); |
| 65 | + const existing = listBoundClaudeSessions(api, agentId).get(sourceKey); |
| 66 | + if (existing) { |
| 67 | + return await linkSession(existing); |
| 68 | + } |
| 69 | + let history: ClaudeTranscriptItem[] | undefined; |
| 70 | + return await continueClaudeAdoption({ |
| 71 | + sourceKey: operationKey, |
| 72 | + findExisting: () => listBoundClaudeSessions(api, agentId).get(sourceKey), |
| 73 | + create: async () => { |
| 74 | + let nodeId: string | undefined; |
| 75 | + let record: ClaudeSessionCatalogSession | undefined; |
| 76 | + if (hostId === CLAUDE_LOCAL_SESSION_HOST_ID) { |
| 77 | + record = (await listClaudeSessions(currentHomeDir(), scanOptions)).find( |
| 78 | + (candidate) => candidate.threadId === threadId, |
| 79 | + ); |
| 80 | + if (!record || !isResumableClaudeSource(record.source)) { |
| 81 | + throw new ClaudeCatalogParamsError("only local Claude Code sessions can be continued"); |
| 82 | + } |
| 83 | + } else if (hostId.startsWith("node:")) { |
| 84 | + nodeId = hostId.slice("node:".length); |
| 85 | + const node = (await api.runtime.nodes.list()).nodes.find( |
| 86 | + (candidate) => |
| 87 | + candidate.nodeId === nodeId && |
| 88 | + candidate.connected === true && |
| 89 | + candidate.commands?.includes(CLAUDE_SESSIONS_LIST_COMMAND) && |
| 90 | + candidate.commands.includes(CLAUDE_SESSION_READ_COMMAND) && |
| 91 | + candidate.commands.includes(CLAUDE_CLI_NODE_RUN_COMMAND) && |
| 92 | + candidate.invocableCommands?.includes(CLAUDE_SESSIONS_LIST_COMMAND) === true && |
| 93 | + candidate.invocableCommands.includes(CLAUDE_SESSION_READ_COMMAND) && |
| 94 | + candidate.invocableCommands.includes(CLAUDE_CLI_NODE_RUN_COMMAND), |
| 95 | + ); |
| 96 | + if (!node) { |
| 97 | + throw new ClaudeCatalogParamsError( |
| 98 | + "paired node does not permit Claude CLI session continuation", |
| 99 | + ); |
| 100 | + } |
| 101 | + // Node rows stay CLI-only: desktop transcripts on nodes have no |
| 102 | + // node-side run command and remain view-only. |
| 103 | + record = await resolveNodeClaudeRecord({ runtime: api.runtime, nodeId, threadId }); |
| 104 | + if (!record || record.source !== "claude-cli") { |
| 105 | + throw new ClaudeCatalogParamsError("only Claude CLI sessions can be continued"); |
| 106 | + } |
| 107 | + } else { |
| 108 | + throw new ClaudeCatalogParamsError("hostId is invalid"); |
| 109 | + } |
| 110 | + if (hostId === CLAUDE_LOCAL_SESSION_HOST_ID) { |
| 111 | + const source = await fs.stat((record as CatalogRecord).filePath).catch(() => undefined); |
| 112 | + if (!source?.isFile()) { |
| 113 | + throw new ClaudeCatalogParamsError("Claude session transcript is unavailable"); |
| 114 | + } |
| 115 | + } |
| 116 | + // Narrowed local: afterCreate below needs a definite array, while the outer |
| 117 | + // `history` stays optional so complete() can link without a reread on races. |
| 118 | + const loadedHistory = await readBoundedClaudeHistory({ |
| 119 | + runtime: api.runtime, |
| 120 | + hostId, |
| 121 | + threadId, |
| 122 | + allowProcessHomeFallback, |
| 123 | + }); |
| 124 | + history = loadedHistory; |
| 125 | + const config = currentClaudeSessionCatalogConfig(api); |
| 126 | + const adoptingAgentId = agentId; |
| 127 | + // Adopt onto the model this agent actually routes to the CLI backend; the |
| 128 | + // packaged default may not be routed or allowed in an existing config. |
| 129 | + const model = |
| 130 | + resolveClaudeCliRoutedModelId(config, adoptingAgentId) ?? |
| 131 | + CLAUDE_CLI_DEFAULT_MODEL_REF.slice(`${CLAUDE_CLI_BACKEND_ID}/`.length); |
| 132 | + const marker = { |
| 133 | + sourceThreadId: threadId, |
| 134 | + ...(hostId !== CLAUDE_LOCAL_SESSION_HOST_ID ? { sourceHostId: hostId } : {}), |
| 135 | + }; |
| 136 | + const created = await api.runtime.agent.session.createSessionEntry({ |
| 137 | + cfg: config, |
| 138 | + key: adoptedSessionKey(hostId, threadId), |
| 139 | + agentId: adoptingAgentId, |
| 140 | + recoverMatchingInitialEntry: true, |
| 141 | + ...(record.name ? { label: record.name } : {}), |
| 142 | + ...(record.cwd ? { spawnedCwd: record.cwd } : {}), |
| 143 | + ...(nodeId ? { execNode: nodeId, ...(record.cwd ? { execCwd: record.cwd } : {}) } : {}), |
| 144 | + initialEntry: { |
| 145 | + cliBackendId: CLAUDE_CLI_BACKEND_ID, |
| 146 | + model, |
| 147 | + modelSelectionLocked: true, |
| 148 | + pluginOwnerId: api.id, |
| 149 | + cliSessionBinding: { sessionId: threadId, forceReuse: true, forkNextResume: true }, |
| 150 | + pluginExtensions: { anthropic: { sessionCatalog: marker } }, |
| 151 | + }, |
| 152 | + afterCreate: async (entry) => { |
| 153 | + await importClaudeHistory({ |
| 154 | + items: loadedHistory, |
| 155 | + threadId, |
| 156 | + sessionId: entry.sessionId, |
| 157 | + sessionKey: entry.key, |
| 158 | + agentId: entry.agentId, |
| 159 | + storePath: api.runtime.agent.session.resolveStorePath(config.session?.store, { |
| 160 | + agentId: entry.agentId, |
| 161 | + }), |
| 162 | + ...(record.cwd ? { cwd: record.cwd } : {}), |
| 163 | + config, |
| 164 | + }); |
| 165 | + return { pluginExtensions: { anthropic: { sessionCatalog: marker } } }; |
| 166 | + }, |
| 167 | + }); |
| 168 | + return { sessionKey: created.key }; |
| 169 | + }, |
| 170 | + complete: async (continued) => await linkSession(continued.sessionKey, history), |
| 171 | + }); |
| 172 | +} |
0 commit comments