@unblocklabs/unblock-codex-prompt 0.4.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/dist/index.js CHANGED
@@ -3,9 +3,11 @@ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { parseConfig, PLUGIN_ID } from "./config.js";
4
4
  import { promptStatus, readEnrollment, restorePrompt, syncPrompt, refreshSharedPrompt } from "./manager.js";
5
5
  import { adapterStatus, applyAdapterRestore, codexAdapterOwnership, installAdapter, planAdapterRestore, prepareAdapter } from "./adapter.js";
6
- import { applyClaudeRestore, claudeAdapterOwnership, claudeAdapterStatus, installClaudeAdapter, planClaudeRestore, prepareClaudeAdapter } from "./claude-adapter.js";
6
+ import { applyClaudeRestore, claudeAdapterStatus, planClaudeRestore } from "./claude-adapter.js";
7
+ import { bootstrapMaxChars, buildClaudeSystemPrompt, bootstrapTotalMaxChars, includeBootstrap } from "./claude-prompt.js";
7
8
  import { fetchAndCompile } from "./compiler.js";
8
- import { checkClaudeAdoption, readClaudeManagedPrompt, readFrozenPolicy } from "./runtime.js";
9
+ import { managedTargetAgent } from "./managed-target.js";
10
+ import { readClaudeManagedContext, readFrozenPolicy } from "./runtime.js";
9
11
  import { detectConfiguredRuntimes, runtimePolicyResolver } from "./runtimes.js";
10
12
  import { policyFetchers } from "./remote.js";
11
13
  import { parseClaudePolicy, readOptional } from "./manager.js";
@@ -89,15 +91,21 @@ async function resolveTarget(config) {
89
91
  return { agentDir, settings, workspaceDir: resolveAgentWorkspaceDir(config, settings.agentId) };
90
92
  }
91
93
  /**
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.
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`.
95
97
  */
96
- function gateGranted(config) {
98
+ function promptHookProblem(config) {
97
99
  // 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);
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`;
104
+ }
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;
101
109
  }
102
110
  function errorMessage(error) { return error instanceof Error ? error.message : "Invalid frozen state"; }
103
111
  async function status(config) {
@@ -115,19 +123,22 @@ async function status(config) {
115
123
  catch (cause) {
116
124
  error = errorMessage(cause);
117
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) }));
118
130
  let claude;
119
131
  if (runtimes.includes("claude-cli")) {
120
- const claudeAdapter = await claudeAdapterStatus(target.agentDir);
121
- let snapshot = false;
132
+ let managed = false;
122
133
  let claudeError;
123
134
  try {
124
- snapshot = disk.enrolled && readClaudeManagedPrompt(target.agentDir) !== null;
135
+ managed = disk.enrolled && readClaudeManagedContext(target.agentDir) !== null;
125
136
  }
126
137
  catch (cause) {
127
138
  claudeError = errorMessage(cause);
128
139
  }
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 };
140
+ const hookProblem = promptHookProblem(config);
141
+ claude = { ready: managed && !hookProblem && !legacyClaudeCore.leftover, promptHook: hookProblem ?? "granted", error: claudeError };
131
142
  }
132
143
  const ready = disk.enrolled && runtimes.length > 0 && (!runtimes.includes("codex") || codexReady) && (!claude || claude.ready);
133
144
  // Status inspects installed instructions without fetching or rebuilding them.
@@ -135,12 +146,13 @@ async function status(config) {
135
146
  const receipt = bundle ? JSON.parse(bundle) : null;
136
147
  const remotePrompt = receipt && typeof receipt === "object" && "remotePrompt" in receipt ? receipt.remotePrompt : null;
137
148
  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 } : {} };
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 } : {} };
139
151
  }
140
152
  export default definePluginEntry({
141
153
  id: PLUGIN_ID,
142
154
  name: "Unblock Codex Prompt",
143
- description: "Explicitly compile a frozen fleet prompt with guarded OpenClaw bridges for Codex and Claude CLI.",
155
+ description: "Explicitly compile a frozen fleet prompt with a guarded Codex bridge and a Claude CLI prompt hook.",
144
156
  register(api) {
145
157
  let stopCatalogRefresh;
146
158
  // Registration/import stays read-only, including plugin inspection and CLI discovery.
@@ -164,13 +176,18 @@ export default definePluginEntry({
164
176
  if (result.enrolled && result.codexConfigError) {
165
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`);
166
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
+ }
167
185
  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`);
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`);
171
188
  }
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`);
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`);
174
191
  }
175
192
  }
176
193
  if (result.enrolled) {
@@ -193,61 +210,40 @@ export default definePluginEntry({
193
210
  },
194
211
  async stop() { await stopCatalogRefresh?.(); stopCatalogRefresh = undefined; },
195
212
  });
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)
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")
212
222
  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);
223
+ const config = api.config;
224
+ const agentId = managedTargetAgent(config);
225
+ if (agentId === undefined || ctx.agentId !== agentId)
217
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 };
218
240
  }
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);
241
+ catch (error) {
242
+ api.logger.error(`${PLUGIN_ID}: Claude CLI run for agent ${agentId} uses OpenClaw's prompt: ${errorMessage(error)}`);
231
243
  return;
232
244
  }
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
- });
245
+ // OpenClaw keeps the first systemPrompt in priority order (higher first): run ahead of other plugins.
246
+ }, { priority: 1000 });
251
247
  }
252
248
  api.registerCli(({ program, config }) => {
253
249
  const root = program.command("codex-prompt").description("Manage this agent's fleet prompt for Codex and Claude CLI (JSON output)");
@@ -269,18 +265,12 @@ export default definePluginEntry({
269
265
  });
270
266
  root.command("refresh").description("Refresh remote prompt, enabled catalog and codex skills without rereading frozen agent context")
271
267
  .action(async () => console.log(JSON.stringify(await refresh(await resolveTarget(config)), null, 2)));
272
- const sync = root.command("sync").description("Explicitly refresh the prompt snapshot and install the reviewed adapters for configured runtimes")
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")
273
269
  .option("--adopt", "Take ownership of an existing custom prompt pointer")
274
270
  .option("--codex-plugin-dir <path>", "Verified official Codex package directory (required on first Codex sync)");
275
271
  sync.action(async () => {
276
272
  const target = await resolveTarget(config);
277
273
  const options = sync.opts();
278
- // Captured import.meta.url paths expire with the CLI. Older hosts expose the
279
- // published dist/index.js via source; newer hosts select it via runtimeSource.
280
- const source = "runtimeSource" in api && typeof api.runtimeSource === "string" ? api.runtimeSource : api.source;
281
- if (!isAbsolute(source) || basename(source) !== "index.js")
282
- throw new Error("Frozen sync requires the packaged plugin runtime entry");
283
- const runtimePath = join(dirname(source), "runtime.js");
284
274
  const enrollment = await readEnrollment(target.agentDir);
285
275
  const enrolled = enrollment?.active ? enrollment.runtimes : [];
286
276
  const detection = detectConfiguredRuntimes(config, target.settings.agentId, runtimePolicyResolver(api));
@@ -292,20 +282,32 @@ export default definePluginEntry({
292
282
  if (!codex && await codexAdapterOwnership(target.agentDir) === "patched") {
293
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");
294
284
  }
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
285
  if (!codex && !claude) {
299
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`);
300
287
  }
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
- }
288
+ const hookProblem = claude ? promptHookProblem(config) : undefined;
289
+ if (hookProblem)
290
+ throw new Error(`Claude CLI management needs its prompt hook: ${hookProblem}`);
304
291
  // Validate every adapter before writing any prompt state.
305
- if (codex)
292
+ let codexPlan;
293
+ if (codex) {
306
294
  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;
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
+ }
309
311
  // Every enrolled runtime's policy is fetched before anything is written: Codex without
310
312
  // `runtime` (any Worker version), Claude with runtime=claude. Claude-only never reads the
311
313
  // Codex artifact. Skills are not compiled: both runtimes get the session catalog live.
@@ -313,12 +315,15 @@ export default definePluginEntry({
313
315
  const runtimes = [...codex ? ["codex"] : [], ...claude ? ["claude-cli"] : []];
314
316
  const result = await syncPrompt({ ...target, ...compiled }, { adopt: options.adopt === true, runtimes });
315
317
  const adapter = codexPlan ? await installAdapter(target.agentDir, codexPlan) : undefined;
316
- const claudeAdapter = claudePlan ? await installClaudeAdapter(target.agentDir, claudePlan) : undefined;
318
+ const legacyClaudeCoreRestored = legacyClaude.files.length ? await applyClaudeRestore(legacyClaude) : undefined;
317
319
  const catalog = codex && target.settings.suppressExplicitDelegationPrompt ? await refreshCatalog(target.agentDir) : undefined;
318
320
  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 },
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 },
320
325
  ...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));
326
+ ...legacyClaudeCoreRestored ? { legacyClaudeCoreRestored, restartRequired: true } : {} }, null, 2));
322
327
  });
323
328
  root.command("restore").description("Restore owned prompt components; pause automatic management and retain files")
324
329
  .action(async () => {
@@ -339,9 +344,10 @@ export default definePluginEntry({
339
344
  await removeCodexSkills(target.agentDir);
340
345
  }
341
346
  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));
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));
345
351
  });
346
352
  }, { descriptors: [{ name: "codex-prompt", description: "Manage an agent-scoped fleet prompt for Codex and Claude CLI", hasSubcommands: true }] });
347
353
  },
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Source of the one "is this the managed target agent" predicate both patched bridges inline.
2
+ * Source of the "is this the managed target agent" predicate the patched Codex bridge inlines.
3
3
  * The generated function takes the run's params (`config`, `agentId`) and returns true only when:
4
4
  * the plugin is enabled and allowed, its entry is enabled with `frozenContext: true`, the run's
5
5
  * agent is the configured target (default `main`) and `eligible` (a JavaScript expression over
@@ -14,3 +14,12 @@ export declare function managedTargetSource(options: {
14
14
  targetChanged: string;
15
15
  eligible?: string;
16
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;
@@ -1,6 +1,6 @@
1
1
  import { PLUGIN_ID } from "./config.js";
2
2
  /**
3
- * Source of the one "is this the managed target agent" predicate both patched bridges inline.
3
+ * Source of the "is this the managed target agent" predicate the patched Codex bridge inlines.
4
4
  * The generated function takes the run's params (`config`, `agentId`) and returns true only when:
5
5
  * the plugin is enabled and allowed, its entry is enabled with `frozenContext: true`, the run's
6
6
  * agent is the configured target (default `main`) and `eligible` (a JavaScript expression over
@@ -24,3 +24,23 @@ export function managedTargetSource(options) {
24
24
  }
25
25
  `;
26
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
+ }
package/dist/manager.d.ts CHANGED
@@ -52,7 +52,7 @@ export declare function parseEnrollment(source: string | null): Enrollment | nul
52
52
  /**
53
53
  * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
54
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.
55
+ * managing Codex and registers no Claude prompt hook, so Claude falls back upstream) and paused ones.
56
56
  * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
57
57
  * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
58
58
  */
package/dist/manager.js CHANGED
@@ -87,7 +87,7 @@ function sortRuntimes(runtimes) { return RUNTIMES.filter(runtime => runtimes.inc
87
87
  /**
88
88
  * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
89
89
  * Every state 0.3.x can safely act on uses it: Codex enrollments (with Claude too, 0.3.x keeps
90
- * managing Codex while the feature-detected Claude patch falls back upstream) and paused ones.
90
+ * managing Codex and registers no Claude prompt hook, so Claude falls back upstream) and paused ones.
91
91
  * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
92
92
  * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
93
93
  */
@@ -173,7 +173,7 @@ export async function withLock(target, operation) {
173
173
  }
174
174
  export const ACTIVATION = {
175
175
  codex: "Restart the managed app-server and use a new Codex session; existing threads may retain old instructions.",
176
- "claude-cli": "Restart the Gateway to load the patched OpenClaw core. The next Claude CLI process receives the managed prompt; it may resume the existing conversation, whose earlier history is not cleaned.",
176
+ "claude-cli": "No restart is needed once the Gateway has loaded this plugin version: the plugin builds the Claude CLI prompt on every turn, so the target agent's next Claude turn uses it. A plugin install or update needs a Gateway restart to load the plugin. The new prompt starts a new Claude CLI process that may resume the existing conversation, whose earlier history is not cleaned.",
177
177
  };
178
178
  export async function syncPrompt(target, options = {}) {
179
179
  if (!target.prompt.trim())
@@ -301,7 +301,7 @@ export async function refreshSharedPrompt(agentDir, fetchers, now = Date.now())
301
301
  }
302
302
  const claudeChanged = claudePolicy !== undefined && claudePolicy.text !== previousClaude?.text;
303
303
  // Codex's reviewed bridge resends the base file as each thread's base instructions, so a change
304
- // re-syncs existing threads on their next turn; Claude starts its next CLI process with its policy.
304
+ // re-syncs existing threads on their next turn; Claude's prompt hook reads the policy every turn.
305
305
  return { changed: changed || claudeChanged, checkedAt: now,
306
306
  ...codexRemote ? { revision: codexRemote.source.revision, nextCodexTurn: changed } : {},
307
307
  ...claudeRemote ? { claudeRevision: claudeRemote.source.revision, nextClaudeProcess: claudeChanged } : {} };
package/dist/runtime.d.ts CHANGED
@@ -11,31 +11,15 @@ export declare function readFrozenPolicy(agentDir: string): string | null;
11
11
  * reaches an existing thread when OpenClaw resumes it; the file itself stays the fallback.
12
12
  */
13
13
  export declare function readCodexBaseInstructions(agentDir: string): string | null;
14
- export type ClaudeManagedPrompt = {
15
- prompt: string;
16
- sha256: string;
14
+ export type ClaudeManagedContext = {
15
+ policy: string;
16
+ agentContext: string;
17
17
  };
18
18
  /**
19
- * Called from the reviewed OpenClaw CLI prompt assembly. Returns null while management is
20
- * paused (restored); throws, aborting the run, when enrolled state is missing, invalid or
21
- * tampered. The prompt is the Claude policy followed by the shared agent context, both read from
22
- * the bundle: it never touches the Codex policy (the prompt-file prefix). Skills reach Claude live,
23
- * through OpenClaw's native skills mount or the session skills prompt. The bundle is the trust
24
- * root, and readVerifiedSnapshot checks the prompt file against its promptSha256.
19
+ * The Claude policy and the shared agent context (memory reference), both read from the bundle,
20
+ * for the Claude CLI prompt hook. Null unless this agent has an active enrollment that includes
21
+ * Claude CLI (never enrolled, paused by restore, or Codex only). Throws when that enrolled state
22
+ * is invalid or tampered: the bundle is the trust root, and readVerifiedSnapshot checks the prompt
23
+ * file against its promptSha256. It never touches the Codex policy (the prompt-file prefix).
25
24
  */
26
- export declare function readClaudeManagedPrompt(agentDir: string): ClaudeManagedPrompt | null;
27
- /** OpenClaw's generic CLI identity line; its presence means the managed assembly was lost. */
28
- export declare const GENERIC_CLI_POLICY_MARKER = "You are a personal assistant running inside OpenClaw.";
29
- export type ClaudeAdoption = {
30
- outcome: "unmanaged";
31
- } | {
32
- outcome: "pass";
33
- } | {
34
- outcome: "block";
35
- reason: string;
36
- };
37
- /**
38
- * Final-adoption check for an enrolled Claude CLI run. Never-enrolled and restored agents
39
- * stay upstream. Prompt text is compared only; it is never returned or logged.
40
- */
41
- export declare function checkClaudeAdoption(agentDir: string, systemPrompt: string | undefined): ClaudeAdoption;
25
+ export declare function readClaudeManagedContext(agentDir: string): ClaudeManagedContext | null;
package/dist/runtime.js CHANGED
@@ -31,7 +31,16 @@ function readEnrollment(home) {
31
31
  }
32
32
  /** The compiled snapshot, verified against its sync receipt. */
33
33
  function readVerifiedSnapshot(home) {
34
- const bundle = JSON.parse(readPrivate(join(home, ".unblock-codex-prompt-bundle.json")));
34
+ let bundle;
35
+ // A parse error would quote the start of the file; never let bundle text reach a log.
36
+ try {
37
+ bundle = JSON.parse(readPrivate(join(home, ".unblock-codex-prompt-bundle.json")));
38
+ }
39
+ catch (error) {
40
+ if (error instanceof SyntaxError)
41
+ throw new Error("Frozen bundle missing or invalid; run codex-prompt sync");
42
+ throw error;
43
+ }
35
44
  if (!bundle || typeof bundle !== "object" || !("schema" in bundle) || bundle.schema !== 1 ||
36
45
  !("policy" in bundle) || typeof bundle.policy !== "string" || !("promptSha256" in bundle))
37
46
  throw new Error("Frozen bundle missing or invalid; run codex-prompt sync");
@@ -72,63 +81,21 @@ export function readCodexBaseInstructions(agentDir) {
72
81
  return readCodexSnapshot(agentDir)?.prompt ?? null;
73
82
  }
74
83
  /**
75
- * Called from the reviewed OpenClaw CLI prompt assembly. Returns null while management is
76
- * paused (restored); throws, aborting the run, when enrolled state is missing, invalid or
77
- * tampered. The prompt is the Claude policy followed by the shared agent context, both read from
78
- * the bundle: it never touches the Codex policy (the prompt-file prefix). Skills reach Claude live,
79
- * through OpenClaw's native skills mount or the session skills prompt. The bundle is the trust
80
- * root, and readVerifiedSnapshot checks the prompt file against its promptSha256.
84
+ * The Claude policy and the shared agent context (memory reference), both read from the bundle,
85
+ * for the Claude CLI prompt hook. Null unless this agent has an active enrollment that includes
86
+ * Claude CLI (never enrolled, paused by restore, or Codex only). Throws when that enrolled state
87
+ * is invalid or tampered: the bundle is the trust root, and readVerifiedSnapshot checks the prompt
88
+ * file against its promptSha256. It never touches the Codex policy (the prompt-file prefix).
81
89
  */
82
- export function readClaudeManagedPrompt(agentDir) {
90
+ export function readClaudeManagedContext(agentDir) {
83
91
  const home = join(agentDir, "codex-home");
84
92
  const state = readEnrollment(home);
85
- if (!state)
86
- throw new Error("Claude bridge installed without enrollment; restore or run codex-prompt sync");
87
- if (!state.active)
93
+ if (!state?.active || !state.runtimes.includes("claude-cli"))
88
94
  return null;
89
- if (!state.runtimes.includes("claude-cli"))
90
- throw new Error("Claude bridge installed without Claude CLI enrollment; restore or run codex-prompt sync");
91
95
  const { bundle } = readVerifiedSnapshot(home);
92
96
  const claudePolicy = parseClaudePolicy("claudePolicy" in bundle ? bundle.claudePolicy : undefined);
93
97
  const agentContext = "agentContext" in bundle ? bundle.agentContext : undefined;
94
98
  if (typeof agentContext !== "string" || !agentContext.trim())
95
99
  throw new Error("Claude policy missing or invalid; run codex-prompt sync");
96
- const managed = `${claudePolicy.text}\n\n${agentContext}`;
97
- return { prompt: managed, sha256: sha256(managed) };
98
- }
99
- /** OpenClaw's generic CLI identity line; its presence means the managed assembly was lost. */
100
- export const GENERIC_CLI_POLICY_MARKER = "You are a personal assistant running inside OpenClaw.";
101
- /**
102
- * Final-adoption check for an enrolled Claude CLI run. Never-enrolled and restored agents
103
- * stay upstream. Prompt text is compared only; it is never returned or logged.
104
- */
105
- export function checkClaudeAdoption(agentDir, systemPrompt) {
106
- const home = join(agentDir, "codex-home");
107
- let state;
108
- try {
109
- state = readEnrollment(home);
110
- }
111
- catch {
112
- return { outcome: "block", reason: "Managed enrollment state is invalid; inspect codex-prompt status" };
113
- }
114
- if (!state?.active || !state.runtimes.includes("claude-cli"))
115
- return { outcome: "unmanaged" };
116
- let managed;
117
- try {
118
- managed = readClaudeManagedPrompt(agentDir);
119
- }
120
- catch {
121
- return { outcome: "block", reason: "Managed snapshot is invalid or changed outside sync; run codex-prompt sync" };
122
- }
123
- if (!managed)
124
- return { outcome: "unmanaged" };
125
- if (typeof systemPrompt !== "string")
126
- return { outcome: "block", reason: "The final system prompt is unavailable to verify managed policy" };
127
- if (systemPrompt.includes(GENERIC_CLI_POLICY_MARKER)) {
128
- return { outcome: "block", reason: "Generic OpenClaw policy is present: the Claude assembly patch is missing or inactive; restore, re-sync and restart the Gateway" };
129
- }
130
- if (!systemPrompt.includes(managed.prompt)) {
131
- return { outcome: "block", reason: "Managed policy was replaced or altered after assembly, for example by a prompt hook or registered text transform; review those plugins" };
132
- }
133
- return { outcome: "pass" };
100
+ return { policy: claudePolicy.text.trim(), agentContext: agentContext.trim() };
134
101
  }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "unblock-codex-prompt",
3
3
  "name": "Unblock Codex Prompt",
4
- "version": "0.4.0",
5
- "description": "Maintain an agent-scoped fleet prompt for Codex (model_instructions_file) and Claude CLI (guarded OpenClaw prompt assembly).",
4
+ "version": "0.5.0",
5
+ "description": "Maintain an agent-scoped fleet prompt for Codex (model_instructions_file) and Claude CLI (before_prompt_build hook).",
6
6
  "activation": { "onStartup": true },
7
7
  "configSchema": {
8
8
  "type": "object",
@@ -18,9 +18,9 @@
18
18
  }
19
19
  },
20
20
  "uiHints": {
21
- "agentId": { "label": "OpenClaw agent ID", "help": "Only this agent's prompt is managed; on Claude CLI only its runs through the claude-cli backend. Defaults to main." },
21
+ "agentId": { "label": "OpenClaw agent ID", "help": "Only this agent's prompt is managed (on Claude CLI, its claude-cli runs, subagent sessions included). Defaults to main." },
22
22
  "agentName": { "label": "Legacy agent name (unused)", "help": "Accepted for existing configs only. Identity comes from agent documents; shared prompt text comes only from promptUrl." },
23
- "frozenContext": { "label": "Managed prompt bridge", "help": "Required: true. Codex: replaces base instructions and OpenClaw generic policy on reviewed OpenClaw/Codex >=2026.10.5 layouts. Claude CLI: replaces only OpenClaw's generic policy on reviewed OpenClaw core layouts (2026.10.6-2026.10.9) and needs hooks.allowConversationAccess for its adoption gate. Runtimes come from the agent's configured model policy at explicit sync. SOUL, IDENTITY, USER and AGENTS stay live." },
23
+ "frozenContext": { "label": "Managed prompt bridge", "help": "Required: true. Codex: replaces base instructions and OpenClaw generic policy on reviewed OpenClaw/Codex >=2026.10.5 layouts. Claude CLI: replaces OpenClaw's entire system prompt through the public before_prompt_build hook (policy, memory reference and the workspace AGENTS, SOUL, IDENTITY, USER, TOOLS, HEARTBEAT and BOOTSTRAP files, read every turn); no OpenClaw core patch. Needs hooks.allowConversationAccess: true and allowPromptInjection not false. Runtimes come from the agent's configured model policy at explicit sync. SOUL, IDENTITY, USER and AGENTS stay live." },
24
24
  "promptUrl": { "label": "Fleet prompt endpoint", "help": "Required public HTTPS plain-text endpoint with X-Prompt-Revision SHA-256. The only shared-policy source. After initial sync, refreshed daily and when overdue on startup without refreshing agent context. No bundled prompt fallback." },
25
25
  "suppressExplicitDelegationPrompt": { "label": "Compact managed Codex instructions", "help": "Manage a model_catalog_json override: suppress explicit-only delegation and Default-mode prose, trim role introductions and compact full-access/never-approval text. Runtime mechanics and permissions are unchanged. Refreshed daily from the configured provider. Requires frozenContext and an available provider env_key. Generated-file edits are replaced on refresh." },
26
26
  "disabledCodexSkills": { "label": "Codex skills to remove", "help": "Plugin names (all of their skills) or exact skill names to disable in Codex's native skills list. Defaults to ChatGPT Pages and Pets. Applied through a managed [[skills.config]] block at startup, sync and daily refresh; other skills are untouched. Set [] to stop managing Codex skills." }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unblocklabs/unblock-codex-prompt",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Manage a shared fleet prompt for an OpenClaw agent on Codex and Claude CLI.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",