@unblocklabs/unblock-codex-prompt 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +376 -70
- package/dist/adapter.d.ts +23 -25
- package/dist/adapter.js +141 -152
- package/dist/claude-adapter.d.ts +32 -0
- package/dist/claude-adapter.js +91 -0
- package/dist/claude-prompt.d.ts +36 -0
- package/dist/claude-prompt.js +134 -0
- package/dist/compatibility.d.ts +1 -1
- package/dist/compatibility.js +4 -3
- package/dist/compiler.d.ts +103 -13
- package/dist/compiler.js +42 -37
- package/dist/index.js +249 -64
- package/dist/managed-target.d.ts +25 -0
- package/dist/managed-target.js +46 -0
- package/dist/manager.d.ts +72 -18
- package/dist/manager.js +131 -40
- package/dist/patched-files.d.ts +117 -0
- package/dist/patched-files.js +160 -0
- package/dist/refresh-error.js +2 -0
- package/dist/remote.d.ts +27 -2
- package/dist/remote.js +23 -4
- package/dist/runtime.d.ts +23 -1
- package/dist/runtime.js +84 -14
- package/dist/runtimes.d.ts +34 -0
- package/dist/runtimes.js +79 -0
- package/openclaw.plugin.json +4 -4
- package/package.json +8 -8
package/dist/index.js
CHANGED
|
@@ -1,23 +1,41 @@
|
|
|
1
1
|
import { listAgentIds, resolveAgentDir, resolveAgentWorkspaceDir } from "openclaw/plugin-sdk/agent-runtime";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
3
|
import { parseConfig, PLUGIN_ID } from "./config.js";
|
|
4
|
-
import { promptStatus, restorePrompt, syncPrompt, refreshSharedPrompt } from "./manager.js";
|
|
5
|
-
import { adapterStatus, installAdapter,
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
4
|
+
import { promptStatus, readEnrollment, restorePrompt, syncPrompt, refreshSharedPrompt } from "./manager.js";
|
|
5
|
+
import { adapterStatus, applyAdapterRestore, codexAdapterOwnership, installAdapter, planAdapterRestore, prepareAdapter } from "./adapter.js";
|
|
6
|
+
import { applyClaudeRestore, claudeAdapterStatus, planClaudeRestore } from "./claude-adapter.js";
|
|
7
|
+
import { bootstrapMaxChars, buildClaudeSystemPrompt, bootstrapTotalMaxChars, includeBootstrap } from "./claude-prompt.js";
|
|
8
|
+
import { fetchAndCompile } from "./compiler.js";
|
|
9
|
+
import { managedTargetAgent } from "./managed-target.js";
|
|
10
|
+
import { readClaudeManagedContext, readFrozenPolicy } from "./runtime.js";
|
|
11
|
+
import { detectConfiguredRuntimes, runtimePolicyResolver } from "./runtimes.js";
|
|
12
|
+
import { policyFetchers } from "./remote.js";
|
|
13
|
+
import { parseClaudePolicy, readOptional } from "./manager.js";
|
|
10
14
|
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
11
15
|
import { CATALOG_REFRESH_MS, catalogStatus, refreshCatalog, restoreCatalog, startCatalogRefresh } from "./catalog.js";
|
|
12
16
|
import { codexSkillsStatus, refreshCodexSkills, removeCodexSkills } from "./skills.js";
|
|
13
17
|
import { refreshFailure } from "./refresh-error.js";
|
|
18
|
+
const codexEnrolled = (enrollment) => enrollment?.runtimes.includes("codex") === true;
|
|
19
|
+
/** Revision metadata of each runtime's stored policy; never the policy text. */
|
|
20
|
+
function claudePolicyReceipt(bundle) {
|
|
21
|
+
if (!bundle || typeof bundle !== "object" || !("claudePolicy" in bundle))
|
|
22
|
+
return null;
|
|
23
|
+
try {
|
|
24
|
+
const { url, revision, checkedAt } = parseClaudePolicy(bundle.claudePolicy);
|
|
25
|
+
return { url, revision, checkedAt };
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
14
31
|
async function refresh(target, automatic = false) {
|
|
15
32
|
const failures = [];
|
|
33
|
+
const codex = codexEnrolled(await readEnrollment(target.agentDir));
|
|
16
34
|
let catalog;
|
|
17
35
|
let prompt;
|
|
18
36
|
let skills;
|
|
19
|
-
// Attempt each independently, sequentially because they share the enrollment lock.
|
|
20
|
-
if (target.settings.suppressExplicitDelegationPrompt) {
|
|
37
|
+
// Attempt each owned component independently, sequentially because they share the enrollment lock.
|
|
38
|
+
if (codex && target.settings.suppressExplicitDelegationPrompt) {
|
|
21
39
|
try {
|
|
22
40
|
catalog = await refreshCatalog(target.agentDir, { automatic });
|
|
23
41
|
}
|
|
@@ -26,62 +44,115 @@ async function refresh(target, automatic = false) {
|
|
|
26
44
|
}
|
|
27
45
|
}
|
|
28
46
|
try {
|
|
29
|
-
prompt = await refreshSharedPrompt(target.agentDir, (
|
|
47
|
+
prompt = await refreshSharedPrompt(target.agentDir, policyFetchers(target.settings.promptUrl));
|
|
30
48
|
}
|
|
31
49
|
catch (error) {
|
|
32
50
|
failures.push(refreshFailure("shared prompt", error));
|
|
33
51
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
52
|
+
if (codex) {
|
|
53
|
+
try {
|
|
54
|
+
skills = await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
failures.push(refreshFailure("skills", error));
|
|
58
|
+
}
|
|
39
59
|
}
|
|
40
60
|
if (failures.length)
|
|
41
61
|
throw new AggregateError(failures, "Refresh incomplete; failed components retain their installed data");
|
|
42
62
|
return { catalog, prompt, skills };
|
|
43
63
|
}
|
|
64
|
+
/** Why the configured Codex app-server cannot read this agent's managed files, if it cannot. */
|
|
65
|
+
function codexAppServerProblem(config) {
|
|
66
|
+
const appServer = config.plugins?.entries?.codex?.config?.appServer;
|
|
67
|
+
if (appServer === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
if (!appServer || typeof appServer !== "object" || Array.isArray(appServer))
|
|
70
|
+
return "Invalid Codex appServer config";
|
|
71
|
+
if (("transport" in appServer && appServer.transport !== "stdio") ||
|
|
72
|
+
("homeScope" in appServer && appServer.homeScope !== "agent")) {
|
|
73
|
+
return "Only agent-scoped local stdio Codex is supported";
|
|
74
|
+
}
|
|
75
|
+
// OpenClaw owns launching Codex, including operator-selected binaries/args.
|
|
76
|
+
// We own this agent's prompt files, not its executable selection.
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
function assertCodexAppServer(config) {
|
|
80
|
+
const problem = codexAppServerProblem(config);
|
|
81
|
+
if (problem)
|
|
82
|
+
throw new Error(problem);
|
|
83
|
+
}
|
|
44
84
|
async function resolveTarget(config) {
|
|
45
85
|
const settings = parseConfig(config.plugins?.entries?.[PLUGIN_ID]?.config);
|
|
46
86
|
if (!listAgentIds(config).includes(settings.agentId))
|
|
47
87
|
throw new Error(`Unknown OpenClaw agent: ${settings.agentId}`);
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
88
|
+
const agentDir = resolveAgentDir(config, settings.agentId);
|
|
89
|
+
// Codex app-server settings are validated by sync once it selects Codex, and reported by
|
|
90
|
+
// status; restore and Claude-only management never depend on them.
|
|
91
|
+
return { agentDir, settings, workspaceDir: resolveAgentWorkspaceDir(config, settings.agentId) };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Why OpenClaw would not register the Claude prompt hook, if it would not. OpenClaw (2026.10.6 and
|
|
95
|
+
* 2026.10.9) blocks before_prompt_build when `hooks.allowPromptInjection` is false, and registers
|
|
96
|
+
* it for a non-bundled plugin only with `hooks.allowConversationAccess: true`.
|
|
97
|
+
*/
|
|
98
|
+
function promptHookProblem(config) {
|
|
99
|
+
// Inspection and metadata-only registration may not supply a config.
|
|
100
|
+
const raw = config?.plugins?.entries?.[PLUGIN_ID]?.hooks;
|
|
101
|
+
const hooks = raw && typeof raw === "object" ? raw : {};
|
|
102
|
+
if (hooks.allowPromptInjection === false) {
|
|
103
|
+
return `plugins.entries.${PLUGIN_ID}.hooks.allowPromptInjection is false, which blocks the before_prompt_build hook that replaces the Claude CLI prompt; remove it or set it to true`;
|
|
59
104
|
}
|
|
60
|
-
|
|
105
|
+
if (hooks.allowConversationAccess !== true) {
|
|
106
|
+
return `OpenClaw registers the before_prompt_build hook that replaces the Claude CLI prompt only with plugins.entries.${PLUGIN_ID}.hooks.allowConversationAccess: true`;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
61
109
|
}
|
|
110
|
+
function errorMessage(error) { return error instanceof Error ? error.message : "Invalid frozen state"; }
|
|
62
111
|
async function status(config) {
|
|
63
112
|
const target = await resolveTarget(config);
|
|
64
113
|
const disk = await promptStatus({ ...target, prompt: "" });
|
|
114
|
+
const runtimes = disk.runtimes;
|
|
65
115
|
const adapter = await adapterStatus(target.agentDir);
|
|
66
|
-
let ready = false;
|
|
67
116
|
let error;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
117
|
+
let codexReady = false;
|
|
118
|
+
const codexConfigError = runtimes.includes("codex") ? codexAppServerProblem(config) : undefined;
|
|
119
|
+
if (runtimes.includes("codex") && !codexConfigError)
|
|
120
|
+
try {
|
|
121
|
+
codexReady = disk.enrolled && readFrozenPolicy(target.agentDir) !== null && adapter.installed;
|
|
122
|
+
}
|
|
123
|
+
catch (cause) {
|
|
124
|
+
error = errorMessage(cause);
|
|
125
|
+
}
|
|
126
|
+
// A 0.4 install patched OpenClaw core for Claude; any receipt it left is reported. An unreadable
|
|
127
|
+
// receipt is reported too, and counts as a possible leftover until sync or restore resolves it.
|
|
128
|
+
const legacyClaudeCore = await claudeAdapterStatus(target.agentDir)
|
|
129
|
+
.catch(cause => ({ installed: false, leftover: true, state: "invalid", error: errorMessage(cause) }));
|
|
130
|
+
let claude;
|
|
131
|
+
if (runtimes.includes("claude-cli")) {
|
|
132
|
+
let managed = false;
|
|
133
|
+
let claudeError;
|
|
134
|
+
try {
|
|
135
|
+
managed = disk.enrolled && readClaudeManagedContext(target.agentDir) !== null;
|
|
136
|
+
}
|
|
137
|
+
catch (cause) {
|
|
138
|
+
claudeError = errorMessage(cause);
|
|
139
|
+
}
|
|
140
|
+
const hookProblem = promptHookProblem(config);
|
|
141
|
+
claude = { ready: managed && !hookProblem && !legacyClaudeCore.leftover, promptHook: hookProblem ?? "granted", error: claudeError };
|
|
73
142
|
}
|
|
143
|
+
const ready = disk.enrolled && runtimes.length > 0 && (!runtimes.includes("codex") || codexReady) && (!claude || claude.ready);
|
|
74
144
|
// Status inspects installed instructions without fetching or rebuilding them.
|
|
75
|
-
const { promptMatches: _matches, expectedSha256: _expected, ...frozenDisk } = disk;
|
|
76
145
|
const bundle = await readOptional(join(target.agentDir, "codex-home", ".unblock-codex-prompt-bundle.json"));
|
|
77
146
|
const receipt = bundle ? JSON.parse(bundle) : null;
|
|
78
147
|
const remotePrompt = receipt && typeof receipt === "object" && "remotePrompt" in receipt ? receipt.remotePrompt : null;
|
|
79
|
-
|
|
148
|
+
const claudePolicy = runtimes.includes("claude-cli") ? claudePolicyReceipt(receipt) : null;
|
|
149
|
+
return { ...disk, frozen: true, ready, adapter, error, ...codexConfigError ? { codexConfigError } : {}, ...claude ? { claude } : {},
|
|
150
|
+
...legacyClaudeCore.state !== "absent" ? { legacyClaudeCore } : {}, configuredPromptUrl: target.settings.promptUrl, remotePrompt, ...runtimes.includes("claude-cli") ? { claudePolicy } : {} };
|
|
80
151
|
}
|
|
81
152
|
export default definePluginEntry({
|
|
82
153
|
id: PLUGIN_ID,
|
|
83
154
|
name: "Unblock Codex Prompt",
|
|
84
|
-
description: "Explicitly compile a frozen
|
|
155
|
+
description: "Explicitly compile a frozen fleet prompt with a guarded Codex bridge and a Claude CLI prompt hook.",
|
|
85
156
|
register(api) {
|
|
86
157
|
let stopCatalogRefresh;
|
|
87
158
|
// Registration/import stays read-only, including plugin inspection and CLI discovery.
|
|
@@ -92,7 +163,8 @@ export default definePluginEntry({
|
|
|
92
163
|
const result = await status(ctx.config);
|
|
93
164
|
ctx.logger.info(`${PLUGIN_ID}: ${JSON.stringify(result)}`);
|
|
94
165
|
const target = await resolveTarget(ctx.config);
|
|
95
|
-
|
|
166
|
+
const codex = result.runtimes.includes("codex");
|
|
167
|
+
if (result.enrolled && codex) {
|
|
96
168
|
// Remote Codex plugins can add skills at any time; reconcile before app-servers start.
|
|
97
169
|
try {
|
|
98
170
|
ctx.logger.info(`${PLUGIN_ID}: codex skills ${JSON.stringify(await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills))}`);
|
|
@@ -101,11 +173,31 @@ export default definePluginEntry({
|
|
|
101
173
|
ctx.logger.error(`${PLUGIN_ID}: codex skills not applied: ${error instanceof Error ? error.message : String(error)}`);
|
|
102
174
|
}
|
|
103
175
|
}
|
|
176
|
+
if (result.enrolled && result.codexConfigError) {
|
|
177
|
+
ctx.logger.error(`${PLUGIN_ID}: Codex management is not effective: ${result.codexConfigError}; restore, or return Codex to agent-scoped local stdio and re-sync`);
|
|
178
|
+
}
|
|
179
|
+
if (result.legacyClaudeCore?.state === "invalid") {
|
|
180
|
+
ctx.logger.error(`${PLUGIN_ID}: the 0.4 Claude CLI core receipt is unreadable (${"error" in result.legacyClaudeCore ? result.legacyClaudeCore.error : "invalid"}); inspect it, then run openclaw codex-prompt sync or restore`);
|
|
181
|
+
}
|
|
182
|
+
else if (result.legacyClaudeCore?.leftover) {
|
|
183
|
+
ctx.logger.error(`${PLUGIN_ID}: OpenClaw core still holds the 0.4 Claude CLI patch; run openclaw codex-prompt sync (or restore), then restart the Gateway`);
|
|
184
|
+
}
|
|
185
|
+
if (result.enrolled && result.claude && !result.claude.ready) {
|
|
186
|
+
if (result.claude.promptHook !== "granted") {
|
|
187
|
+
ctx.logger.error(`${PLUGIN_ID}: the Claude CLI prompt hook is not registered (${result.claude.promptHook}); the target agent's Claude runs use OpenClaw's prompt. Restore the grant, or run openclaw codex-prompt restore`);
|
|
188
|
+
}
|
|
189
|
+
else if (result.claude.error) {
|
|
190
|
+
ctx.logger.error(`${PLUGIN_ID}: Claude CLI managed state is invalid (${result.claude.error}); the target agent's Claude runs use OpenClaw's prompt until openclaw codex-prompt sync`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
104
193
|
if (result.enrolled) {
|
|
105
|
-
const catalog = await catalogStatus(target.agentDir);
|
|
194
|
+
const catalog = codex ? await catalogStatus(target.agentDir) : undefined;
|
|
195
|
+
// The oldest check among the enrolled runtimes' policies decides when the next refresh is due.
|
|
106
196
|
const remote = result.remotePrompt;
|
|
107
|
-
const
|
|
108
|
-
const
|
|
197
|
+
const codexChecked = remote && typeof remote === "object" && "checkedAt" in remote && typeof remote.checkedAt === "number" ? remote.checkedAt : 0;
|
|
198
|
+
const claudeChecked = result.claudePolicy?.checkedAt ?? 0;
|
|
199
|
+
const checkedAt = Math.min(...[codex ? codexChecked : Infinity, result.claudePolicy !== undefined ? claudeChecked : Infinity]);
|
|
200
|
+
const nextAt = Math.min(codex && target.settings.suppressExplicitDelegationPrompt ? catalog?.nextRefreshAt ?? 0 : Infinity, checkedAt ? checkedAt + CATALOG_REFRESH_MS : 0, Date.now() + CATALOG_REFRESH_MS);
|
|
109
201
|
stopCatalogRefresh = startCatalogRefresh(async () => {
|
|
110
202
|
const refreshed = await refresh(target, true);
|
|
111
203
|
ctx.logger.info(`${PLUGIN_ID}: daily refresh ${JSON.stringify(refreshed)}`);
|
|
@@ -118,52 +210,145 @@ export default definePluginEntry({
|
|
|
118
210
|
},
|
|
119
211
|
async stop() { await stopCatalogRefresh?.(); stopCatalogRefresh = undefined; },
|
|
120
212
|
});
|
|
213
|
+
// Claude CLI prompt: for the target agent's claude-cli runs (subagent sessions included) the
|
|
214
|
+
// hook returns the complete system prompt, which OpenClaw uses in place of its own. It is
|
|
215
|
+
// built on every call from the verified enrollment and the live workspace files. Other agents
|
|
216
|
+
// and providers, and paused or unenrolled state, return nothing. Invalid or tampered state is
|
|
217
|
+
// logged and also returns nothing, so that run keeps OpenClaw's prompt. Prompt text is never logged.
|
|
218
|
+
if (!promptHookProblem(api.config)) {
|
|
219
|
+
const reportedSkips = new Set();
|
|
220
|
+
api.on("before_prompt_build", async (_event, ctx) => {
|
|
221
|
+
if (typeof ctx.modelProviderId !== "string" || ctx.modelProviderId.trim().toLowerCase() !== "claude-cli")
|
|
222
|
+
return;
|
|
223
|
+
const config = api.config;
|
|
224
|
+
const agentId = managedTargetAgent(config);
|
|
225
|
+
if (agentId === undefined || ctx.agentId !== agentId)
|
|
226
|
+
return;
|
|
227
|
+
try {
|
|
228
|
+
const managed = readClaudeManagedContext(resolveAgentDir(config, agentId));
|
|
229
|
+
if (!managed)
|
|
230
|
+
return;
|
|
231
|
+
const workspace = typeof ctx.workspaceDir === "string" && isAbsolute(ctx.workspaceDir) ? ctx.workspaceDir : resolveAgentWorkspaceDir(config, agentId);
|
|
232
|
+
const { systemPrompt, skipped } = await buildClaudeSystemPrompt(managed, workspace, bootstrapMaxChars(config, agentId), { totalMaxChars: bootstrapTotalMaxChars(config, agentId), includeBootstrap: includeBootstrap(ctx) });
|
|
233
|
+
for (const { path, reason } of skipped) {
|
|
234
|
+
if (reportedSkips.has(`${path}\0${reason}`))
|
|
235
|
+
continue;
|
|
236
|
+
reportedSkips.add(`${path}\0${reason}`);
|
|
237
|
+
api.logger.warn(`${PLUGIN_ID}: ${path} is left out of the Claude CLI prompt: ${reason}`);
|
|
238
|
+
}
|
|
239
|
+
return { systemPrompt };
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
api.logger.error(`${PLUGIN_ID}: Claude CLI run for agent ${agentId} uses OpenClaw's prompt: ${errorMessage(error)}`);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
// OpenClaw keeps the first systemPrompt in priority order (higher first): run ahead of other plugins.
|
|
246
|
+
}, { priority: 1000 });
|
|
247
|
+
}
|
|
121
248
|
api.registerCli(({ program, config }) => {
|
|
122
|
-
const root = program.command("codex-prompt").description("Manage this agent's Codex
|
|
249
|
+
const root = program.command("codex-prompt").description("Manage this agent's fleet prompt for Codex and Claude CLI (JSON output)");
|
|
123
250
|
root.command("status").description("Inspect disk state without writing or claiming live adoption")
|
|
124
251
|
.action(async () => {
|
|
125
252
|
const target = await resolveTarget(config);
|
|
126
|
-
|
|
127
|
-
|
|
253
|
+
const codex = codexEnrolled(await readEnrollment(target.agentDir));
|
|
254
|
+
console.log(JSON.stringify({ ...await status(config), ...codex ? { catalog: await catalogStatus(target.agentDir),
|
|
255
|
+
codexSkills: await codexSkillsStatus(target.agentDir, target.settings.disabledCodexSkills) } : {} }, null, 2));
|
|
128
256
|
});
|
|
129
257
|
root.command("refresh-catalog").description("Fetch fresh provider metadata and repair the managed instruction catalog")
|
|
130
258
|
.action(async () => {
|
|
131
259
|
const target = await resolveTarget(config);
|
|
132
260
|
if (!target.settings.suppressExplicitDelegationPrompt)
|
|
133
261
|
throw new Error("Enable suppressExplicitDelegationPrompt before refreshing the catalog");
|
|
262
|
+
if (!codexEnrolled(await readEnrollment(target.agentDir)))
|
|
263
|
+
throw new Error("The model catalog applies only to Codex enrollment");
|
|
134
264
|
console.log(JSON.stringify(await refreshCatalog(target.agentDir), null, 2));
|
|
135
265
|
});
|
|
136
266
|
root.command("refresh").description("Refresh remote prompt, enabled catalog and codex skills without rereading frozen agent context")
|
|
137
267
|
.action(async () => console.log(JSON.stringify(await refresh(await resolveTarget(config)), null, 2)));
|
|
138
|
-
const sync = root.command("sync").description("Explicitly refresh the prompt snapshot
|
|
268
|
+
const sync = root.command("sync").description("Explicitly refresh the prompt snapshot, install the reviewed Codex adapter and enable the Claude CLI prompt for configured runtimes")
|
|
139
269
|
.option("--adopt", "Take ownership of an existing custom prompt pointer")
|
|
140
|
-
.option("--codex-plugin-dir <path>", "Verified official Codex package directory (required on first
|
|
270
|
+
.option("--codex-plugin-dir <path>", "Verified official Codex package directory (required on first Codex sync)");
|
|
141
271
|
sync.action(async () => {
|
|
142
272
|
const target = await resolveTarget(config);
|
|
143
273
|
const options = sync.opts();
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
274
|
+
const enrollment = await readEnrollment(target.agentDir);
|
|
275
|
+
const enrolled = enrollment?.active ? enrollment.runtimes : [];
|
|
276
|
+
const detection = detectConfiguredRuntimes(config, target.settings.agentId, runtimePolicyResolver(api));
|
|
277
|
+
// Configured policy and explicit flags propose components; active enrollment keeps them.
|
|
278
|
+
const codex = detection.runtimes.has("codex") || options.codexPluginDir !== undefined || enrolled.includes("codex");
|
|
279
|
+
const claude = detection.runtimes.has("claude-cli") || enrolled.includes("claude-cli");
|
|
280
|
+
// A receipt retained by restore is rollback evidence, not ownership. Bytes this plugin
|
|
281
|
+
// still holds (an interrupted restore) are never re-enrolled implicitly or orphaned.
|
|
282
|
+
if (!codex && await codexAdapterOwnership(target.agentDir) === "patched") {
|
|
283
|
+
throw new Error("The Codex adapter is still patched but Codex is neither enrolled nor configured; run openclaw codex-prompt restore to finish removing it");
|
|
284
|
+
}
|
|
285
|
+
if (!codex && !claude) {
|
|
286
|
+
throw new Error(`No managed runtime detected for agent ${target.settings.agentId} (policy resolver ${detection.resolver}); configure a claude-cli runtime or pass --codex-plugin-dir for Codex`);
|
|
287
|
+
}
|
|
288
|
+
const hookProblem = claude ? promptHookProblem(config) : undefined;
|
|
289
|
+
if (hookProblem)
|
|
290
|
+
throw new Error(`Claude CLI management needs its prompt hook: ${hookProblem}`);
|
|
291
|
+
// Validate every adapter before writing any prompt state.
|
|
292
|
+
let codexPlan;
|
|
293
|
+
if (codex) {
|
|
294
|
+
assertCodexAppServer(config);
|
|
295
|
+
// Captured import.meta.url paths expire with the CLI. Older hosts expose the
|
|
296
|
+
// published dist/index.js via source; newer hosts select it via runtimeSource.
|
|
297
|
+
const source = "runtimeSource" in api && typeof api.runtimeSource === "string" ? api.runtimeSource : api.source;
|
|
298
|
+
if (!isAbsolute(source) || basename(source) !== "index.js")
|
|
299
|
+
throw new Error("Frozen sync requires the packaged plugin runtime entry");
|
|
300
|
+
codexPlan = await prepareAdapter(target.agentDir, target.settings.agentId, options.codexPluginDir, join(dirname(source), "runtime.js"));
|
|
301
|
+
}
|
|
302
|
+
// A 0.4 install patched OpenClaw core for Claude. Its restore is validated (files and
|
|
303
|
+
// backups) here, before any write, and applied with this sync.
|
|
304
|
+
let legacyClaude;
|
|
305
|
+
try {
|
|
306
|
+
legacyClaude = await planClaudeRestore(target.agentDir);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
throw new Error(`Cannot remove the 0.4 Claude CLI core patch: ${errorMessage(error)}`);
|
|
310
|
+
}
|
|
311
|
+
// Every enrolled runtime's policy is fetched before anything is written: Codex without
|
|
312
|
+
// `runtime` (any Worker version), Claude with runtime=claude. Claude-only never reads the
|
|
313
|
+
// Codex artifact. Skills are not compiled: both runtimes get the session catalog live.
|
|
314
|
+
const { compiled, remote, claudePolicy } = await fetchAndCompile({ codex, claude, promptUrl: target.settings.promptUrl, workspaceDir: target.workspaceDir });
|
|
315
|
+
const runtimes = [...codex ? ["codex"] : [], ...claude ? ["claude-cli"] : []];
|
|
316
|
+
const result = await syncPrompt({ ...target, ...compiled }, { adopt: options.adopt === true, runtimes });
|
|
317
|
+
const adapter = codexPlan ? await installAdapter(target.agentDir, codexPlan) : undefined;
|
|
318
|
+
const legacyClaudeCoreRestored = legacyClaude.files.length ? await applyClaudeRestore(legacyClaude) : undefined;
|
|
319
|
+
const catalog = codex && target.settings.suppressExplicitDelegationPrompt ? await refreshCatalog(target.agentDir) : undefined;
|
|
320
|
+
const codexSkills = codex ? await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills) : undefined;
|
|
321
|
+
const activation = legacyClaudeCoreRestored
|
|
322
|
+
? `${result.activation} The 0.4 Claude CLI patch was removed from OpenClaw core: restart the Gateway to reload the restored core.`
|
|
323
|
+
: result.activation;
|
|
324
|
+
console.log(JSON.stringify({ ...result, activation, adapter, detection: { resolver: detection.resolver, models: detection.detections },
|
|
325
|
+
...remote ? { remotePrompt: remote } : {}, ...claudePolicy ? { claudePolicy } : {}, catalog, codexSkills,
|
|
326
|
+
...legacyClaudeCoreRestored ? { legacyClaudeCoreRestored, restartRequired: true } : {} }, null, 2));
|
|
158
327
|
});
|
|
159
|
-
root.command("restore").description("Restore
|
|
328
|
+
root.command("restore").description("Restore owned prompt components; pause automatic management and retain files")
|
|
160
329
|
.action(async () => {
|
|
161
330
|
const target = await resolveTarget(config);
|
|
162
|
-
await
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
331
|
+
const enrollment = await readEnrollment(target.agentDir);
|
|
332
|
+
// Each plan validates its files and backups before any write, and is empty unless this
|
|
333
|
+
// plugin's bytes are still installed: a receipt left by an earlier restore or superseded
|
|
334
|
+
// by an update never blocks restoring the other runtime.
|
|
335
|
+
const codexPlan = await planAdapterRestore(target.agentDir);
|
|
336
|
+
const claudePlan = await planClaudeRestore(target.agentDir);
|
|
337
|
+
if (!enrollment && !codexPlan.files.length && !claudePlan.files.length)
|
|
338
|
+
throw new Error("This agent has no prompt enrollment to restore");
|
|
339
|
+
// Pause enrollment (validating the prompt pointer) before changing anything else, so a
|
|
340
|
+
// refusal leaves every component unchanged and no run sees a half-restored bridge.
|
|
341
|
+
const prompt = enrollment ? await restorePrompt({ ...target, prompt: "" }) : { restored: false };
|
|
342
|
+
if (codexEnrolled(enrollment)) {
|
|
343
|
+
await restoreCatalog(target.agentDir);
|
|
344
|
+
await removeCodexSkills(target.agentDir);
|
|
345
|
+
}
|
|
346
|
+
const codexAdapter = await applyAdapterRestore(codexPlan);
|
|
347
|
+
const legacyClaudeCore = await applyClaudeRestore(claudePlan);
|
|
348
|
+
console.log(JSON.stringify({ ...prompt, ...codexAdapter.ownership !== "none" ? { codexAdapter } : {}, ...legacyClaudeCore.ownership !== "none" ? { legacyClaudeCore } : {},
|
|
349
|
+
...legacyClaudeCore.restartRequired ? { activation: "The 0.4 Claude CLI patch was removed from OpenClaw core: restart the Gateway to reload the restored core." }
|
|
350
|
+
: enrollment?.runtimes.includes("claude-cli") ? { activation: "The target agent's next Claude CLI turn uses OpenClaw's prompt." } : {} }, null, 2));
|
|
166
351
|
});
|
|
167
|
-
}, { descriptors: [{ name: "codex-prompt", description: "Manage an agent-scoped Codex
|
|
352
|
+
}, { descriptors: [{ name: "codex-prompt", description: "Manage an agent-scoped fleet prompt for Codex and Claude CLI", hasSubcommands: true }] });
|
|
168
353
|
},
|
|
169
354
|
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source of the "is this the managed target agent" predicate the patched Codex bridge inlines.
|
|
3
|
+
* The generated function takes the run's params (`config`, `agentId`) and returns true only when:
|
|
4
|
+
* the plugin is enabled and allowed, its entry is enabled with `frozenContext: true`, the run's
|
|
5
|
+
* agent is the configured target (default `main`) and `eligible` (a JavaScript expression over
|
|
6
|
+
* `params`, if given) holds. A managed run whose configured target is no longer the agent the
|
|
7
|
+
* bridge was installed for throws `targetChanged` instead of managing the wrong agent.
|
|
8
|
+
* It is generated inline, never loaded from the plugin, so a plugin rollback without restore
|
|
9
|
+
* keeps the installed bridge's own gate.
|
|
10
|
+
*/
|
|
11
|
+
export declare function managedTargetSource(options: {
|
|
12
|
+
name: string;
|
|
13
|
+
agentId: string;
|
|
14
|
+
targetChanged: string;
|
|
15
|
+
eligible?: string;
|
|
16
|
+
}): string;
|
|
17
|
+
/**
|
|
18
|
+
* The same predicate, evaluated in the plugin (the Claude prompt hook): the configured target
|
|
19
|
+
* agent when the plugin is enabled and allowed and its entry is enabled with
|
|
20
|
+
* `frozenContext: true`, otherwise undefined. There is no installed agent to compare with: the
|
|
21
|
+
* hook reads the configured target's own enrollment, so a retargeted, unenrolled agent is
|
|
22
|
+
* simply unmanaged.
|
|
23
|
+
*/
|
|
24
|
+
export declare function managedTargetAgent(config: unknown): string | undefined;
|
|
25
|
+
export declare function isManagedTarget(config: unknown, agentId: unknown): boolean;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { PLUGIN_ID } from "./config.js";
|
|
2
|
+
/**
|
|
3
|
+
* Source of the "is this the managed target agent" predicate the patched Codex bridge inlines.
|
|
4
|
+
* The generated function takes the run's params (`config`, `agentId`) and returns true only when:
|
|
5
|
+
* the plugin is enabled and allowed, its entry is enabled with `frozenContext: true`, the run's
|
|
6
|
+
* agent is the configured target (default `main`) and `eligible` (a JavaScript expression over
|
|
7
|
+
* `params`, if given) holds. A managed run whose configured target is no longer the agent the
|
|
8
|
+
* bridge was installed for throws `targetChanged` instead of managing the wrong agent.
|
|
9
|
+
* It is generated inline, never loaded from the plugin, so a plugin rollback without restore
|
|
10
|
+
* keeps the installed bridge's own gate.
|
|
11
|
+
*/
|
|
12
|
+
export function managedTargetSource(options) {
|
|
13
|
+
const id = JSON.stringify(PLUGIN_ID);
|
|
14
|
+
const eligible = options.eligible ? ` || !(${options.eligible})` : "";
|
|
15
|
+
return `function ${options.name}(params) {
|
|
16
|
+
const plugins = params.config?.plugins;
|
|
17
|
+
const entry = plugins?.entries?.[${id}];
|
|
18
|
+
if (plugins?.enabled === false || entry?.enabled !== true || entry.config?.frozenContext !== true ||
|
|
19
|
+
(Array.isArray(plugins.allow) && !plugins.allow.includes(${id}))) return false;
|
|
20
|
+
const target = entry.config?.agentId ?? "main";
|
|
21
|
+
if (params.agentId !== target${eligible}) return false;
|
|
22
|
+
if (target !== ${JSON.stringify(options.agentId)}) throw new Error(${JSON.stringify(options.targetChanged)});
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The same predicate, evaluated in the plugin (the Claude prompt hook): the configured target
|
|
29
|
+
* agent when the plugin is enabled and allowed and its entry is enabled with
|
|
30
|
+
* `frozenContext: true`, otherwise undefined. There is no installed agent to compare with: the
|
|
31
|
+
* hook reads the configured target's own enrollment, so a retargeted, unenrolled agent is
|
|
32
|
+
* simply unmanaged.
|
|
33
|
+
*/
|
|
34
|
+
export function managedTargetAgent(config) {
|
|
35
|
+
const plugins = config?.plugins;
|
|
36
|
+
const entry = plugins?.entries?.[PLUGIN_ID];
|
|
37
|
+
if (plugins?.enabled === false || entry?.enabled !== true || entry.config?.frozenContext !== true ||
|
|
38
|
+
(Array.isArray(plugins?.allow) && !plugins.allow.includes(PLUGIN_ID)))
|
|
39
|
+
return undefined;
|
|
40
|
+
const target = entry.config?.agentId ?? "main";
|
|
41
|
+
return typeof target === "string" ? target : undefined;
|
|
42
|
+
}
|
|
43
|
+
export function isManagedTarget(config, agentId) {
|
|
44
|
+
const target = managedTargetAgent(config);
|
|
45
|
+
return target !== undefined && agentId === target;
|
|
46
|
+
}
|