@unblocklabs/unblock-codex-prompt 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -1,23 +1,39 @@
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, prepareAdapter, restoreAdapter } from "./adapter.js";
6
- import { buildSkillsCatalog, compilePrompt } from "./compiler.js";
7
- import { readFrozenPolicy } from "./runtime.js";
8
- import { fetchPrompt } from "./remote.js";
9
- import { readOptional } from "./manager.js";
4
+ import { promptStatus, readEnrollment, restorePrompt, syncPrompt, refreshSharedPrompt } from "./manager.js";
5
+ import { adapterStatus, applyAdapterRestore, codexAdapterOwnership, installAdapter, planAdapterRestore, prepareAdapter } from "./adapter.js";
6
+ import { applyClaudeRestore, claudeAdapterOwnership, claudeAdapterStatus, installClaudeAdapter, planClaudeRestore, prepareClaudeAdapter } from "./claude-adapter.js";
7
+ import { fetchAndCompile } from "./compiler.js";
8
+ import { checkClaudeAdoption, readClaudeManagedPrompt, readFrozenPolicy } from "./runtime.js";
9
+ import { detectConfiguredRuntimes, runtimePolicyResolver } from "./runtimes.js";
10
+ import { policyFetchers } from "./remote.js";
11
+ import { parseClaudePolicy, readOptional } from "./manager.js";
10
12
  import { basename, dirname, isAbsolute, join } from "node:path";
11
13
  import { CATALOG_REFRESH_MS, catalogStatus, refreshCatalog, restoreCatalog, startCatalogRefresh } from "./catalog.js";
12
14
  import { codexSkillsStatus, refreshCodexSkills, removeCodexSkills } from "./skills.js";
13
15
  import { refreshFailure } from "./refresh-error.js";
16
+ const codexEnrolled = (enrollment) => enrollment?.runtimes.includes("codex") === true;
17
+ /** Revision metadata of each runtime's stored policy; never the policy text. */
18
+ function claudePolicyReceipt(bundle) {
19
+ if (!bundle || typeof bundle !== "object" || !("claudePolicy" in bundle))
20
+ return null;
21
+ try {
22
+ const { url, revision, checkedAt } = parseClaudePolicy(bundle.claudePolicy);
23
+ return { url, revision, checkedAt };
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
14
29
  async function refresh(target, automatic = false) {
15
30
  const failures = [];
31
+ const codex = codexEnrolled(await readEnrollment(target.agentDir));
16
32
  let catalog;
17
33
  let prompt;
18
34
  let skills;
19
- // Attempt each independently, sequentially because they share the enrollment lock.
20
- if (target.settings.suppressExplicitDelegationPrompt) {
35
+ // Attempt each owned component independently, sequentially because they share the enrollment lock.
36
+ if (codex && target.settings.suppressExplicitDelegationPrompt) {
21
37
  try {
22
38
  catalog = await refreshCatalog(target.agentDir, { automatic });
23
39
  }
@@ -26,62 +42,105 @@ async function refresh(target, automatic = false) {
26
42
  }
27
43
  }
28
44
  try {
29
- prompt = await refreshSharedPrompt(target.agentDir, () => fetchPrompt(target.settings.promptUrl));
45
+ prompt = await refreshSharedPrompt(target.agentDir, policyFetchers(target.settings.promptUrl));
30
46
  }
31
47
  catch (error) {
32
48
  failures.push(refreshFailure("shared prompt", error));
33
49
  }
34
- try {
35
- skills = await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills);
36
- }
37
- catch (error) {
38
- failures.push(refreshFailure("skills", error));
50
+ if (codex) {
51
+ try {
52
+ skills = await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills);
53
+ }
54
+ catch (error) {
55
+ failures.push(refreshFailure("skills", error));
56
+ }
39
57
  }
40
58
  if (failures.length)
41
59
  throw new AggregateError(failures, "Refresh incomplete; failed components retain their installed data");
42
60
  return { catalog, prompt, skills };
43
61
  }
62
+ /** Why the configured Codex app-server cannot read this agent's managed files, if it cannot. */
63
+ function codexAppServerProblem(config) {
64
+ const appServer = config.plugins?.entries?.codex?.config?.appServer;
65
+ if (appServer === undefined)
66
+ return undefined;
67
+ if (!appServer || typeof appServer !== "object" || Array.isArray(appServer))
68
+ return "Invalid Codex appServer config";
69
+ if (("transport" in appServer && appServer.transport !== "stdio") ||
70
+ ("homeScope" in appServer && appServer.homeScope !== "agent")) {
71
+ return "Only agent-scoped local stdio Codex is supported";
72
+ }
73
+ // OpenClaw owns launching Codex, including operator-selected binaries/args.
74
+ // We own this agent's prompt files, not its executable selection.
75
+ return undefined;
76
+ }
77
+ function assertCodexAppServer(config) {
78
+ const problem = codexAppServerProblem(config);
79
+ if (problem)
80
+ throw new Error(problem);
81
+ }
44
82
  async function resolveTarget(config) {
45
83
  const settings = parseConfig(config.plugins?.entries?.[PLUGIN_ID]?.config);
46
84
  if (!listAgentIds(config).includes(settings.agentId))
47
85
  throw new Error(`Unknown OpenClaw agent: ${settings.agentId}`);
48
- const codexConfig = config.plugins?.entries?.codex?.config;
49
- const appServer = codexConfig?.appServer;
50
- if (appServer !== undefined) {
51
- if (!appServer || typeof appServer !== "object" || Array.isArray(appServer))
52
- throw new Error("Invalid Codex appServer config");
53
- if (("transport" in appServer && appServer.transport !== "stdio") ||
54
- ("homeScope" in appServer && appServer.homeScope !== "agent")) {
55
- throw new Error("Only agent-scoped local stdio Codex is supported");
56
- }
57
- // OpenClaw owns launching Codex, including operator-selected binaries/args.
58
- // We own this agent's prompt files, not its executable selection.
59
- }
60
- return { agentDir: resolveAgentDir(config, settings.agentId), settings, workspaceDir: resolveAgentWorkspaceDir(config, settings.agentId) };
86
+ const agentDir = resolveAgentDir(config, settings.agentId);
87
+ // Codex app-server settings are validated by sync once it selects Codex, and reported by
88
+ // status; restore and Claude-only management never depend on them.
89
+ return { agentDir, settings, workspaceDir: resolveAgentWorkspaceDir(config, settings.agentId) };
61
90
  }
91
+ /**
92
+ * The final-adoption gate needs conversation access; non-bundled plugins must opt in.
93
+ * Its run correlation uses an observe-only prompt-build hook, so prompt injection must
94
+ * not be disabled either.
95
+ */
96
+ function gateGranted(config) {
97
+ // Inspection and metadata-only registration may not supply a config.
98
+ const hooks = config?.plugins?.entries?.[PLUGIN_ID]?.hooks;
99
+ return !!hooks && typeof hooks === "object" && "allowConversationAccess" in hooks && hooks.allowConversationAccess === true &&
100
+ !("allowPromptInjection" in hooks && hooks.allowPromptInjection === false);
101
+ }
102
+ function errorMessage(error) { return error instanceof Error ? error.message : "Invalid frozen state"; }
62
103
  async function status(config) {
63
104
  const target = await resolveTarget(config);
64
105
  const disk = await promptStatus({ ...target, prompt: "" });
106
+ const runtimes = disk.runtimes;
65
107
  const adapter = await adapterStatus(target.agentDir);
66
- let ready = false;
67
108
  let error;
68
- try {
69
- ready = disk.enrolled && readFrozenPolicy(target.agentDir) !== null;
70
- }
71
- catch (cause) {
72
- error = cause instanceof Error ? cause.message : "Invalid frozen state";
109
+ let codexReady = false;
110
+ const codexConfigError = runtimes.includes("codex") ? codexAppServerProblem(config) : undefined;
111
+ if (runtimes.includes("codex") && !codexConfigError)
112
+ try {
113
+ codexReady = disk.enrolled && readFrozenPolicy(target.agentDir) !== null && adapter.installed;
114
+ }
115
+ catch (cause) {
116
+ error = errorMessage(cause);
117
+ }
118
+ let claude;
119
+ if (runtimes.includes("claude-cli")) {
120
+ const claudeAdapter = await claudeAdapterStatus(target.agentDir);
121
+ let snapshot = false;
122
+ let claudeError;
123
+ try {
124
+ snapshot = disk.enrolled && readClaudeManagedPrompt(target.agentDir) !== null;
125
+ }
126
+ catch (cause) {
127
+ claudeError = errorMessage(cause);
128
+ }
129
+ const granted = gateGranted(config);
130
+ claude = { ready: snapshot && claudeAdapter.installed && granted, adapter: claudeAdapter, adoptionGate: granted ? "granted" : "requires hooks.allowConversationAccess: true and allowPromptInjection not false", error: claudeError };
73
131
  }
132
+ const ready = disk.enrolled && runtimes.length > 0 && (!runtimes.includes("codex") || codexReady) && (!claude || claude.ready);
74
133
  // Status inspects installed instructions without fetching or rebuilding them.
75
- const { promptMatches: _matches, expectedSha256: _expected, ...frozenDisk } = disk;
76
134
  const bundle = await readOptional(join(target.agentDir, "codex-home", ".unblock-codex-prompt-bundle.json"));
77
135
  const receipt = bundle ? JSON.parse(bundle) : null;
78
136
  const remotePrompt = receipt && typeof receipt === "object" && "remotePrompt" in receipt ? receipt.remotePrompt : null;
79
- return { ...frozenDisk, frozen: true, ready: ready && adapter.installed, adapter, error, configuredPromptUrl: target.settings.promptUrl, remotePrompt };
137
+ const claudePolicy = runtimes.includes("claude-cli") ? claudePolicyReceipt(receipt) : null;
138
+ return { ...disk, frozen: true, ready, adapter, error, ...codexConfigError ? { codexConfigError } : {}, ...claude ? { claude } : {}, configuredPromptUrl: target.settings.promptUrl, remotePrompt, ...runtimes.includes("claude-cli") ? { claudePolicy } : {} };
80
139
  }
81
140
  export default definePluginEntry({
82
141
  id: PLUGIN_ID,
83
142
  name: "Unblock Codex Prompt",
84
- description: "Explicitly compile a frozen Codex prompt with a guarded OpenClaw bridge.",
143
+ description: "Explicitly compile a frozen fleet prompt with guarded OpenClaw bridges for Codex and Claude CLI.",
85
144
  register(api) {
86
145
  let stopCatalogRefresh;
87
146
  // Registration/import stays read-only, including plugin inspection and CLI discovery.
@@ -92,7 +151,8 @@ export default definePluginEntry({
92
151
  const result = await status(ctx.config);
93
152
  ctx.logger.info(`${PLUGIN_ID}: ${JSON.stringify(result)}`);
94
153
  const target = await resolveTarget(ctx.config);
95
- if (result.enrolled) {
154
+ const codex = result.runtimes.includes("codex");
155
+ if (result.enrolled && codex) {
96
156
  // Remote Codex plugins can add skills at any time; reconcile before app-servers start.
97
157
  try {
98
158
  ctx.logger.info(`${PLUGIN_ID}: codex skills ${JSON.stringify(await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills))}`);
@@ -101,11 +161,26 @@ export default definePluginEntry({
101
161
  ctx.logger.error(`${PLUGIN_ID}: codex skills not applied: ${error instanceof Error ? error.message : String(error)}`);
102
162
  }
103
163
  }
164
+ if (result.enrolled && result.codexConfigError) {
165
+ ctx.logger.error(`${PLUGIN_ID}: Codex management is not effective: ${result.codexConfigError}; restore, or return Codex to agent-scoped local stdio and re-sync`);
166
+ }
167
+ if (result.enrolled && result.claude && !result.claude.ready) {
168
+ if (result.claude.adoptionGate !== "granted") {
169
+ // Without the grant the gate is never registered, so nothing checks or blocks these runs.
170
+ ctx.logger.error(`${PLUGIN_ID}: the Claude CLI final-adoption gate is not registered (${result.claude.adoptionGate}); enrolled Claude runs are not checked (adapter ${result.claude.adapter.state}). Restore the grant and restart the Gateway, or run codex-prompt restore`);
171
+ }
172
+ else {
173
+ ctx.logger.error(`${PLUGIN_ID}: Claude CLI management is not ready (${result.claude.adapter.state}); enrolled Claude runs are blocked until codex-prompt sync and a Gateway restart`);
174
+ }
175
+ }
104
176
  if (result.enrolled) {
105
- const catalog = await catalogStatus(target.agentDir);
177
+ const catalog = codex ? await catalogStatus(target.agentDir) : undefined;
178
+ // The oldest check among the enrolled runtimes' policies decides when the next refresh is due.
106
179
  const remote = result.remotePrompt;
107
- const checkedAt = remote && typeof remote === "object" && "checkedAt" in remote && typeof remote.checkedAt === "number" ? remote.checkedAt : 0;
108
- const nextAt = Math.min(target.settings.suppressExplicitDelegationPrompt ? catalog.nextRefreshAt ?? 0 : Infinity, checkedAt ? checkedAt + CATALOG_REFRESH_MS : 0, Date.now() + CATALOG_REFRESH_MS);
180
+ const codexChecked = remote && typeof remote === "object" && "checkedAt" in remote && typeof remote.checkedAt === "number" ? remote.checkedAt : 0;
181
+ const claudeChecked = result.claudePolicy?.checkedAt ?? 0;
182
+ const checkedAt = Math.min(...[codex ? codexChecked : Infinity, result.claudePolicy !== undefined ? claudeChecked : Infinity]);
183
+ const nextAt = Math.min(codex && target.settings.suppressExplicitDelegationPrompt ? catalog?.nextRefreshAt ?? 0 : Infinity, checkedAt ? checkedAt + CATALOG_REFRESH_MS : 0, Date.now() + CATALOG_REFRESH_MS);
109
184
  stopCatalogRefresh = startCatalogRefresh(async () => {
110
185
  const refreshed = await refresh(target, true);
111
186
  ctx.logger.info(`${PLUGIN_ID}: daily refresh ${JSON.stringify(refreshed)}`);
@@ -118,26 +193,85 @@ export default definePluginEntry({
118
193
  },
119
194
  async stop() { await stopCatalogRefresh?.(); stopCatalogRefresh = undefined; },
120
195
  });
196
+ // Claude-scoped final-adoption gate. The CLI runner's before_agent_run context has no
197
+ // runtime identity, so its preparation-path prompt-build hook (which does) marks the
198
+ // run first. Other agents and runtimes pass immediately; never-enrolled Claude runs stay
199
+ // upstream and are reported, enrolled broken management blocks.
200
+ if (gateGranted(api.config)) {
201
+ const claudeRuns = new Set();
202
+ const reported = new Set();
203
+ const targetAgent = () => {
204
+ const entry = api.config.plugins?.entries?.[PLUGIN_ID];
205
+ const raw = entry?.config;
206
+ if (entry?.enabled !== true)
207
+ return undefined;
208
+ return raw && typeof raw === "object" && "agentId" in raw && typeof raw.agentId === "string" ? raw.agentId : "main";
209
+ };
210
+ api.on("before_prompt_build", (_event, ctx) => {
211
+ if (!ctx.runId)
212
+ return;
213
+ // Model fallback reuses the runId per attempt; each preparation replaces the mark, so a
214
+ // Claude attempt that failed before execution cannot gate a later non-Claude attempt.
215
+ if (ctx.modelProviderId !== "claude-cli" || ctx.agentId !== targetAgent()) {
216
+ claudeRuns.delete(ctx.runId);
217
+ return;
218
+ }
219
+ claudeRuns.add(ctx.runId);
220
+ // Bound runs that were prepared but never reached execution.
221
+ if (claudeRuns.size > 256)
222
+ claudeRuns.delete(claudeRuns.values().next().value);
223
+ });
224
+ api.on("before_agent_run", (event, ctx) => {
225
+ if (!ctx.runId)
226
+ return;
227
+ // Embedded and worker attempts name their provider (some skip prompt-build); the CLI
228
+ // runner does not. A named non-Claude provider is never a Claude CLI run.
229
+ if (ctx.modelProviderId !== undefined && ctx.modelProviderId !== "claude-cli") {
230
+ claudeRuns.delete(ctx.runId);
231
+ return;
232
+ }
233
+ if (!claudeRuns.delete(ctx.runId))
234
+ return;
235
+ // Preparation already matched the target agent; the runner's agentId may be unset.
236
+ const target = targetAgent();
237
+ if (target === undefined)
238
+ return;
239
+ const result = checkClaudeAdoption(resolveAgentDir(api.config, target), event.systemPrompt);
240
+ if (result.outcome === "pass")
241
+ return;
242
+ if (result.outcome === "unmanaged") {
243
+ if (!reported.has(target))
244
+ api.logger.warn(`${PLUGIN_ID}: Claude CLI run for agent ${target} is not managed; run openclaw codex-prompt sync to enroll it`);
245
+ reported.add(target);
246
+ return;
247
+ }
248
+ api.logger.error(`${PLUGIN_ID}: blocked Claude CLI run for agent ${target}: ${result.reason}`);
249
+ return { outcome: "block", reason: result.reason, message: `Blocked by ${PLUGIN_ID}: ${result.reason}.` };
250
+ });
251
+ }
121
252
  api.registerCli(({ program, config }) => {
122
- const root = program.command("codex-prompt").description("Manage this agent's Codex base prompt (JSON output)");
253
+ const root = program.command("codex-prompt").description("Manage this agent's fleet prompt for Codex and Claude CLI (JSON output)");
123
254
  root.command("status").description("Inspect disk state without writing or claiming live adoption")
124
255
  .action(async () => {
125
256
  const target = await resolveTarget(config);
126
- console.log(JSON.stringify({ ...await status(config), catalog: await catalogStatus(target.agentDir),
127
- codexSkills: await codexSkillsStatus(target.agentDir, target.settings.disabledCodexSkills) }, null, 2));
257
+ const codex = codexEnrolled(await readEnrollment(target.agentDir));
258
+ console.log(JSON.stringify({ ...await status(config), ...codex ? { catalog: await catalogStatus(target.agentDir),
259
+ codexSkills: await codexSkillsStatus(target.agentDir, target.settings.disabledCodexSkills) } : {} }, null, 2));
128
260
  });
129
261
  root.command("refresh-catalog").description("Fetch fresh provider metadata and repair the managed instruction catalog")
130
262
  .action(async () => {
131
263
  const target = await resolveTarget(config);
132
264
  if (!target.settings.suppressExplicitDelegationPrompt)
133
265
  throw new Error("Enable suppressExplicitDelegationPrompt before refreshing the catalog");
266
+ if (!codexEnrolled(await readEnrollment(target.agentDir)))
267
+ throw new Error("The model catalog applies only to Codex enrollment");
134
268
  console.log(JSON.stringify(await refreshCatalog(target.agentDir), null, 2));
135
269
  });
136
270
  root.command("refresh").description("Refresh remote prompt, enabled catalog and codex skills without rereading frozen agent context")
137
271
  .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 and install the reviewed adapter")
272
+ const sync = root.command("sync").description("Explicitly refresh the prompt snapshot and install the reviewed adapters for configured runtimes")
139
273
  .option("--adopt", "Take ownership of an existing custom prompt pointer")
140
- .option("--codex-plugin-dir <path>", "Verified official Codex package directory (required on first frozen sync)");
274
+ .option("--codex-plugin-dir <path>", "Verified official Codex package directory (required on first Codex sync)");
141
275
  sync.action(async () => {
142
276
  const target = await resolveTarget(config);
143
277
  const options = sync.opts();
@@ -146,24 +280,69 @@ export default definePluginEntry({
146
280
  const source = "runtimeSource" in api && typeof api.runtimeSource === "string" ? api.runtimeSource : api.source;
147
281
  if (!isAbsolute(source) || basename(source) !== "index.js")
148
282
  throw new Error("Frozen sync requires the packaged plugin runtime entry");
149
- const plan = await prepareAdapter(target.agentDir, target.settings.agentId, options.codexPluginDir, join(dirname(source), "runtime.js"));
150
- const remote = await fetchPrompt(target.settings.promptUrl);
151
- const compiled = await compilePrompt(remote.prompt, target.workspaceDir, await buildSkillsCatalog(config, target.settings.agentId, target.workspaceDir));
152
- Object.assign(compiled.bundle, { remotePrompt: { ...remote.source, checkedAt: Date.now() } });
153
- const result = await syncPrompt({ ...target, ...compiled }, { adopt: options.adopt === true });
154
- const adapter = await installAdapter(target.agentDir, plan);
155
- const catalog = target.settings.suppressExplicitDelegationPrompt ? await refreshCatalog(target.agentDir) : undefined;
156
- const codexSkills = await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills);
157
- console.log(JSON.stringify({ ...result, adapter, skillCount: compiled.bundle.skillCount, remotePrompt: remote.source, catalog, codexSkills }, null, 2));
283
+ const runtimePath = join(dirname(source), "runtime.js");
284
+ const enrollment = await readEnrollment(target.agentDir);
285
+ const enrolled = enrollment?.active ? enrollment.runtimes : [];
286
+ const detection = detectConfiguredRuntimes(config, target.settings.agentId, runtimePolicyResolver(api));
287
+ // Configured policy and explicit flags propose components; active enrollment keeps them.
288
+ const codex = detection.runtimes.has("codex") || options.codexPluginDir !== undefined || enrolled.includes("codex");
289
+ const claude = detection.runtimes.has("claude-cli") || enrolled.includes("claude-cli");
290
+ // A receipt retained by restore is rollback evidence, not ownership. Bytes this plugin
291
+ // still holds (an interrupted restore) are never re-enrolled implicitly or orphaned.
292
+ if (!codex && await codexAdapterOwnership(target.agentDir) === "patched") {
293
+ 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");
294
+ }
295
+ if (!claude && await claudeAdapterOwnership(target.agentDir) === "patched") {
296
+ throw new Error("OpenClaw core still holds the Claude CLI adapter but Claude CLI is neither enrolled nor configured; run openclaw codex-prompt restore to finish removing it");
297
+ }
298
+ if (!codex && !claude) {
299
+ 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`);
300
+ }
301
+ if (claude && !gateGranted(config)) {
302
+ throw new Error(`Claude CLI management requires plugins.entries.${PLUGIN_ID}.hooks.allowConversationAccess: true (and allowPromptInjection not false) for its final-adoption gate`);
303
+ }
304
+ // Validate every adapter before writing any prompt state.
305
+ if (codex)
306
+ assertCodexAppServer(config);
307
+ const codexPlan = codex ? await prepareAdapter(target.agentDir, target.settings.agentId, options.codexPluginDir, runtimePath) : undefined;
308
+ const claudePlan = claude ? await prepareClaudeAdapter(target.agentDir, target.settings.agentId, runtimePath) : undefined;
309
+ // Every enrolled runtime's policy is fetched before anything is written: Codex without
310
+ // `runtime` (any Worker version), Claude with runtime=claude. Claude-only never reads the
311
+ // Codex artifact. Skills are not compiled: both runtimes get the session catalog live.
312
+ const { compiled, remote, claudePolicy } = await fetchAndCompile({ codex, claude, promptUrl: target.settings.promptUrl, workspaceDir: target.workspaceDir });
313
+ const runtimes = [...codex ? ["codex"] : [], ...claude ? ["claude-cli"] : []];
314
+ const result = await syncPrompt({ ...target, ...compiled }, { adopt: options.adopt === true, runtimes });
315
+ const adapter = codexPlan ? await installAdapter(target.agentDir, codexPlan) : undefined;
316
+ const claudeAdapter = claudePlan ? await installClaudeAdapter(target.agentDir, claudePlan) : undefined;
317
+ const catalog = codex && target.settings.suppressExplicitDelegationPrompt ? await refreshCatalog(target.agentDir) : undefined;
318
+ const codexSkills = codex ? await refreshCodexSkills(target.agentDir, target.settings.disabledCodexSkills) : undefined;
319
+ console.log(JSON.stringify({ ...result, adapter, claudeAdapter, detection: { resolver: detection.resolver, models: detection.detections },
320
+ ...remote ? { remotePrompt: remote } : {}, ...claudePolicy ? { claudePolicy } : {}, catalog, codexSkills,
321
+ ...claude ? { coreIntegrity: "OpenClaw core is patched; run openclaw codex-prompt restore before updating OpenClaw, then re-sync" } : {} }, null, 2));
158
322
  });
159
- root.command("restore").description("Restore the original pointer; pause automatic management and retain files")
323
+ root.command("restore").description("Restore owned prompt components; pause automatic management and retain files")
160
324
  .action(async () => {
161
325
  const target = await resolveTarget(config);
162
- await restoreCatalog(target.agentDir);
163
- await removeCodexSkills(target.agentDir);
164
- await restoreAdapter(target.agentDir);
165
- console.log(JSON.stringify(await restorePrompt({ ...target, prompt: "" }), null, 2));
326
+ const enrollment = await readEnrollment(target.agentDir);
327
+ // Each plan validates its files and backups before any write, and is empty unless this
328
+ // plugin's bytes are still installed: a receipt left by an earlier restore or superseded
329
+ // by an update never blocks restoring the other runtime.
330
+ const codexPlan = await planAdapterRestore(target.agentDir);
331
+ const claudePlan = await planClaudeRestore(target.agentDir);
332
+ if (!enrollment && !codexPlan.files.length && !claudePlan.files.length)
333
+ throw new Error("This agent has no prompt enrollment to restore");
334
+ // Pause enrollment (validating the prompt pointer) before changing anything else, so a
335
+ // refusal leaves every component unchanged and no run sees a half-restored bridge.
336
+ const prompt = enrollment ? await restorePrompt({ ...target, prompt: "" }) : { restored: false };
337
+ if (codexEnrolled(enrollment)) {
338
+ await restoreCatalog(target.agentDir);
339
+ await removeCodexSkills(target.agentDir);
340
+ }
341
+ const codexAdapter = await applyAdapterRestore(codexPlan);
342
+ const claudeAdapter = await applyClaudeRestore(claudePlan);
343
+ console.log(JSON.stringify({ ...prompt, ...codexAdapter.ownership !== "none" ? { codexAdapter } : {}, ...claudeAdapter.ownership !== "none" ? { claudeAdapter } : {},
344
+ ...claudeAdapter.restartRequired ? { activation: "Restart the Gateway to reload the restored OpenClaw core; Claude CLI runs then use upstream prompts." } : {} }, null, 2));
166
345
  });
167
- }, { descriptors: [{ name: "codex-prompt", description: "Manage an agent-scoped Codex base prompt", hasSubcommands: true }] });
346
+ }, { descriptors: [{ name: "codex-prompt", description: "Manage an agent-scoped fleet prompt for Codex and Claude CLI", hasSubcommands: true }] });
168
347
  },
169
348
  });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Source of the one "is this the managed target agent" predicate both patched bridges inline.
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;
@@ -0,0 +1,26 @@
1
+ import { PLUGIN_ID } from "./config.js";
2
+ /**
3
+ * Source of the one "is this the managed target agent" predicate both patched bridges inline.
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
+ }
package/dist/manager.d.ts CHANGED
@@ -1,54 +1,96 @@
1
+ export declare const RUNTIMES: readonly ["codex", "claude-cli"];
2
+ export type ManagedRuntime = typeof RUNTIMES[number];
3
+ /** previousPointer is Codex's original model_instructions_file; unused by Claude-only enrollment. */
4
+ export type Enrollment = {
5
+ active: boolean;
6
+ previousPointer: string | null;
7
+ runtimes: ManagedRuntime[];
8
+ };
9
+ /** A fetched fleet policy and its provenance. Metadata (never `text`) is safe to report. */
10
+ export type PolicyReceipt = {
11
+ url: string;
12
+ revision: string;
13
+ checkedAt: number;
14
+ };
15
+ export type ClaudePolicy = PolicyReceipt & {
16
+ text: string;
17
+ };
18
+ /**
19
+ * `policy` stays "" (0.3 runtimes require the field; they read only `schema`, `policy` and
20
+ * `promptSha256`). The Codex policy is the prompt-file prefix, with `basePromptLength` and
21
+ * `remotePrompt` describing it. Claude's policy and the shared agent context live in the bundle
22
+ * itself, so Claude never reads the Codex artifact.
23
+ */
1
24
  export type FrozenBundle = {
2
25
  schema: 1;
3
26
  policy: string;
4
- sources: {
5
- name: string;
6
- sha256: string | null;
7
- }[];
8
- skillCount: number;
9
27
  basePromptLength?: number;
10
28
  remotePrompt?: {
11
29
  url: string;
12
30
  revision: string;
13
31
  checkedAt?: number;
14
32
  };
33
+ claudePolicy?: ClaudePolicy;
34
+ agentContext?: string;
15
35
  };
16
- export declare const FROZEN_CONTEXT_HEADER = "\n\n## Frozen agent context\n";
36
+ /** First heading of the agent context, the boundary after the shared policy prefix. */
37
+ export declare const MEMORY_REFERENCE_HEADER = "\n\n## Memory reference\n";
38
+ /**
39
+ * Accepted boundaries: the current first heading, then the 0.4 branch builds' `## Agent context`
40
+ * and the 0.3 `## Frozen agent context`, so their prompt files still refresh in place.
41
+ */
42
+ export declare const CONTEXT_BOUNDARY_HEADERS: readonly ["\n\n## Memory reference\n", "\n\n## Agent context\n", "\n\n## Frozen agent context\n"];
43
+ /** Strict shape check for a stored Claude policy; throws on anything else. */
44
+ export declare function parseClaudePolicy(value: unknown): ClaudePolicy;
17
45
  export type PromptTarget = {
18
46
  agentDir: string;
19
47
  prompt: string;
20
48
  bundle?: FrozenBundle;
21
49
  };
22
50
  export declare function readOptional(path: string): Promise<string | null>;
51
+ export declare function parseEnrollment(source: string | null): Enrollment | null;
52
+ /**
53
+ * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
54
+ * Every state 0.3.x can safely act on uses it: Codex enrollments (with Claude too, 0.3.x keeps
55
+ * managing Codex while the feature-detected Claude patch falls back upstream) and paused ones.
56
+ * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
57
+ * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
58
+ */
59
+ export declare function serializeEnrollment(enrollment: Enrollment): string;
60
+ /** Disk-only enrollment for callers that select runtime components. */
61
+ export declare function readEnrollment(agentDir: string): Promise<Enrollment | null>;
23
62
  export declare function sha256(text: string): string;
24
- /** Disk state only: this cannot attest to instructions retained by a live Codex thread. */
63
+ /** Disk state only: this cannot attest to instructions retained by a live Codex thread or Claude process. */
25
64
  export declare function promptStatus(target: PromptTarget): Promise<{
26
65
  enrolled: boolean;
27
66
  restored: boolean;
67
+ runtimes: ("codex" | "claude-cli")[];
28
68
  configPath: string;
29
69
  promptPath: string;
30
- pointerMatches: boolean;
31
- promptMatches: boolean;
32
- expectedSha256: string;
70
+ pointerMatches: boolean | null;
33
71
  actualSha256: string | null;
34
72
  runtimeVerified: boolean;
35
73
  }>;
36
74
  export declare function replaceFile(path: string, previous: string | null, contents: string): Promise<boolean>;
37
75
  export declare function withLock<T>(target: PromptTarget, operation: () => Promise<T>): Promise<T>;
76
+ export declare const ACTIVATION: Record<ManagedRuntime, string>;
38
77
  export declare function syncPrompt(target: PromptTarget, options?: {
39
78
  adopt?: boolean;
40
79
  automatic?: boolean;
80
+ runtimes?: readonly ManagedRuntime[];
41
81
  }): Promise<{
42
82
  changed: boolean;
43
83
  restored: boolean;
44
84
  promptChanged?: never;
45
85
  configChanged?: never;
86
+ runtimes?: never;
46
87
  sha256?: never;
47
88
  activation?: never;
48
89
  } | {
49
90
  changed: boolean;
50
91
  promptChanged: boolean;
51
92
  configChanged: boolean;
93
+ runtimes: ("codex" | "claude-cli")[];
52
94
  sha256: string;
53
95
  activation: string;
54
96
  restored?: never;
@@ -56,25 +98,37 @@ export declare function syncPrompt(target: PromptTarget, options?: {
56
98
  export declare function restorePrompt(target: PromptTarget): Promise<{
57
99
  changed: boolean;
58
100
  restored: boolean;
101
+ runtimes: ("codex" | "claude-cli")[];
59
102
  retainedPromptPath: string;
60
103
  }>;
61
- /** Replace only the shared prefix; never reread workspace documents or skills. */
62
- export declare function refreshSharedPrompt(agentDir: string, fetchBase: () => Promise<{
104
+ export type FetchedPolicy = () => Promise<{
63
105
  prompt: string;
64
106
  source: {
65
107
  url: string;
66
108
  revision: string;
67
109
  };
68
- }>, now?: number): Promise<{
110
+ }>;
111
+ /**
112
+ * Daily/explicit refresh of each enrolled runtime's fleet policy; it never rereads the agent
113
+ * context. Every enrolled runtime is fetched before anything is written, so one failure leaves
114
+ * all local state untouched. Then, in one locked write:
115
+ * - Codex: only the policy prefix of the prompt file is replaced (the file keeps its inode when
116
+ * unchanged). Everything after `basePromptLength` is kept byte-for-byte, so a snapshot from an
117
+ * older sync keeps its frozen skills catalog tail until the next sync rewrites the file;
118
+ * - Claude: only `claudePolicy` in the bundle is replaced; the prompt file is not touched for it.
119
+ */
120
+ export declare function refreshSharedPrompt(agentDir: string, fetchers: {
121
+ codex?: FetchedPolicy;
122
+ claude?: FetchedPolicy;
123
+ }, now?: number): Promise<{
69
124
  changed: boolean;
70
125
  skipped: boolean;
71
- revision?: never;
72
- checkedAt?: never;
73
- newSessionRequired?: never;
74
126
  } | {
127
+ claudeRevision?: string;
128
+ nextClaudeProcess?: boolean;
129
+ revision?: string;
130
+ nextCodexTurn?: boolean;
75
131
  changed: boolean;
76
- revision: string;
77
132
  checkedAt: number;
78
- newSessionRequired: boolean;
79
133
  skipped?: never;
80
134
  }>;