@unblocklabs/unblock-codex-prompt 0.2.4 → 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.
@@ -0,0 +1,160 @@
1
+ import { readOptional, replaceFile, sha256 } from "./manager.js";
2
+ async function observe(recorded) {
3
+ return Promise.all(recorded.files.map(async (file) => {
4
+ const current = await readOptional(file.path);
5
+ return { file, current, hash: current === null ? null : sha256(current) };
6
+ }));
7
+ }
8
+ const holdsPatched = ({ file, hash }) => hash !== null && (hash === file.patchedSha256 || hash === file.previousPatchedSha256);
9
+ const holdsOriginal = ({ file, hash }) => hash === file.originalSha256;
10
+ /** An update replaced the recorded install: only receipts that recorded a version can say so. */
11
+ async function versionChanged(set, recorded) {
12
+ return recorded.version !== undefined && await set.installedVersion(recorded.root) !== recorded.version;
13
+ }
14
+ async function ownershipOf(set, recorded, observed) {
15
+ if (observed.some(holdsPatched))
16
+ return "patched";
17
+ if (observed.every(holdsOriginal))
18
+ return "restored";
19
+ // Updates rename hashed bundles (old files missing) or replace a recorded version.
20
+ if (observed.every(entry => holdsOriginal(entry) || entry.current === null) || await versionChanged(set, recorded))
21
+ return "superseded";
22
+ return "changed";
23
+ }
24
+ async function load(set) {
25
+ const source = await readOptional(set.receiptPath);
26
+ return { source, recorded: source === null ? null : set.parseReceipt(source) };
27
+ }
28
+ export async function patchedFilesOwnership(set) {
29
+ const { recorded } = await load(set);
30
+ return recorded ? ownershipOf(set, recorded, await observe(recorded)) : "none";
31
+ }
32
+ /** The previous receipt, its ownership, and the root a new install may default to. */
33
+ export async function openPatchedFiles(set) {
34
+ const { source, recorded } = await load(set);
35
+ const ownership = recorded ? await ownershipOf(set, recorded, await observe(recorded)) : "none";
36
+ return { previousReceipt: source, recorded, ownership };
37
+ }
38
+ /**
39
+ * Start a patch at `root`. A restored or superseded receipt counts as cleared: any root is
40
+ * allowed and its backups may be replaced. Otherwise every recorded file must still hold this
41
+ * adapter's bytes (an interrupted re-patch is recognized by previousPatchedSha256) unless it
42
+ * is missing or the recorded version was replaced; the adapter then reads originals through
43
+ * `read` (backups for owned files) and hands its patched sources to `finish`.
44
+ */
45
+ export async function beginPatch(set, opened, root) {
46
+ const { previousReceipt, recorded, ownership } = opened;
47
+ const cleared = ownership === "restored" || ownership === "superseded";
48
+ const kept = cleared ? null : recorded;
49
+ if (kept && kept.root !== root)
50
+ throw new Error(set.messages.installChanged);
51
+ const owned = new Map();
52
+ const superseded = [];
53
+ if (kept) {
54
+ const updated = await versionChanged(set, kept);
55
+ for (const entry of await observe(kept)) {
56
+ if (holdsPatched(entry) || holdsOriginal(entry))
57
+ owned.set(entry.file.path, entry.file);
58
+ else if (entry.current === null || updated)
59
+ superseded.push(entry.file);
60
+ else
61
+ throw new Error(set.messages.changed);
62
+ }
63
+ }
64
+ const originals = new Map();
65
+ const read = async (path) => {
66
+ const current = await readOptional(path);
67
+ if (current === null)
68
+ throw new Error(set.messages.missing);
69
+ const file = owned.get(path);
70
+ const original = file ? await readOptional(kept.backupPath(file)) : current;
71
+ if (original === null || (file && sha256(original) !== file.originalSha256))
72
+ throw new Error(set.messages.prepareBackupInvalid);
73
+ originals.set(path, { current, original });
74
+ return original;
75
+ };
76
+ /** `patched` maps each changed path (read through `read`) to its patched source, in receipt order. */
77
+ const finish = (patched) => {
78
+ if ([...owned.keys()].some(path => !patched.has(path)))
79
+ throw new Error(set.messages.moved);
80
+ const files = [...patched].map(([path, contents]) => {
81
+ const source = originals.get(path);
82
+ if (!source)
83
+ throw new Error(set.messages.missing);
84
+ return { path, ...source, patched: contents };
85
+ });
86
+ const entries = files.map(file => ({
87
+ path: file.path, originalSha256: sha256(file.original), patchedSha256: sha256(file.patched),
88
+ // Receipt-first upgrades must remain recoverable if source swapping is interrupted.
89
+ ...file.current !== file.original && file.current !== file.patched ? { previousPatchedSha256: sha256(file.current) } : {},
90
+ }));
91
+ // Backups of a cleared receipt, or of files an update superseded, may be replaced; any other is foreign.
92
+ const staleBackups = new Set((cleared ? recorded.files : superseded).map(file => file.originalSha256));
93
+ return { files, entries, previousReceipt, staleBackups };
94
+ };
95
+ return { read, finish };
96
+ }
97
+ /** Validates every target before any change; keeps exact original backups, then the receipt, then the files. */
98
+ export async function installPatch(set, plan, receipt) {
99
+ const backups = await Promise.all(plan.files.map(async (file) => {
100
+ const path = set.backupPath(file.path);
101
+ const backup = await readOptional(path);
102
+ if (backup !== null && backup !== file.original && !plan.staleBackups.has(sha256(backup)))
103
+ throw new Error(set.messages.foreignBackup);
104
+ if (await readOptional(file.path) !== file.current)
105
+ throw new Error(set.messages.concurrent);
106
+ return { path, backup, original: file.original };
107
+ }));
108
+ for (const backup of backups)
109
+ await replaceFile(backup.path, backup.backup, backup.original);
110
+ await replaceFile(set.receiptPath, plan.previousReceipt, receipt);
111
+ let adapterChanged = false;
112
+ for (const file of plan.files)
113
+ adapterChanged = await replaceFile(file.path, file.current, file.patched) || adapterChanged;
114
+ return { adapterChanged, restartRequired: true };
115
+ }
116
+ /** Disk state of every recorded file; distinguishes missing files (an update) from foreign edits. */
117
+ export async function patchedFilesStatus(set) {
118
+ const { recorded } = await load(set);
119
+ if (!recorded)
120
+ return null;
121
+ const states = (await observe(recorded)).map(entry => entry.current === null ? "missing" : entry.hash === entry.file.patchedSha256 ? "patched"
122
+ : holdsPatched(entry) ? "stale" : holdsOriginal(entry) ? "original" : "changed");
123
+ const state = states.every(value => value === "patched") ? "patched" : states.includes("changed") ? "changed"
124
+ : states.includes("missing") ? "missing" : states.some(value => value === "patched" || value === "stale") ? "partial" : "original";
125
+ return { recorded, state, installed: state === "patched", paths: recorded.files.map(file => file.path) };
126
+ }
127
+ export async function planPatchedRestore(set) {
128
+ const { recorded } = await load(set);
129
+ if (!recorded)
130
+ return { ownership: "none", files: [], superseded: [] };
131
+ const observed = await observe(recorded);
132
+ const ownership = await ownershipOf(set, recorded, observed);
133
+ if (ownership !== "patched")
134
+ return { ownership, files: [], superseded: [] };
135
+ const updated = await versionChanged(set, recorded);
136
+ const ours = [];
137
+ const superseded = [];
138
+ for (const entry of observed) {
139
+ if (holdsOriginal(entry))
140
+ continue;
141
+ if (holdsPatched(entry))
142
+ ours.push(entry);
143
+ else if (entry.current === null || updated)
144
+ superseded.push(entry.file.path);
145
+ else
146
+ throw new Error(set.messages.foreignEdit);
147
+ }
148
+ const files = await Promise.all(ours.map(async ({ file, current }) => {
149
+ const original = await readOptional(recorded.backupPath(file));
150
+ if (original === null || sha256(original) !== file.originalSha256)
151
+ throw new Error(set.messages.backupInvalid);
152
+ return { path: file.path, current: current, original };
153
+ }));
154
+ return { ownership, files, superseded };
155
+ }
156
+ export async function applyPatchedRestore(plan) {
157
+ for (const file of plan.files)
158
+ await replaceFile(file.path, file.current, file.original);
159
+ return { ownership: plan.ownership, files: plan.files.map(file => file.path), superseded: plan.superseded, restartRequired: plan.files.length > 0 };
160
+ }
@@ -0,0 +1 @@
1
+ export declare function refreshFailure(component: "catalog" | "shared prompt" | "skills", error: unknown): Error;
@@ -0,0 +1,40 @@
1
+ // Only plugin-owned diagnostics are safe to log. Transport errors and parser
2
+ // exceptions can contain credentials, configuration, or remote response bodies.
3
+ const SAFE_CAUSES = new Set([
4
+ "Catalog refresh requires an explicit Codex provider",
5
+ "Catalog refresh requires a provider base_url and existing env_key credential",
6
+ "Configured catalog provider credential is unavailable in the plugin environment",
7
+ "Managed Codex client version missing from its model cache",
8
+ "Catalog request failed; installed catalog retained",
9
+ "Catalog endpoint returned invalid JSON",
10
+ "Upstream response is not a full Codex model catalog",
11
+ "Invalid or duplicate Codex model metadata",
12
+ "Invalid model_messages", "Invalid multi_agent metadata", "Invalid multi_agent mode metadata", "Invalid model message metadata",
13
+ "Invalid Codex TOML", "Unsupported catalog provider URL", "Catalog response exceeds 8 MiB",
14
+ "A different model_catalog_json is configured; refusing to replace it",
15
+ "Unowned model catalog exists; recover its receipt first",
16
+ "Managed prompt pointer missing or changed; refusing refresh",
17
+ "Valid enrolled remote snapshot required; run codex-prompt sync",
18
+ "Frozen context boundary is ambiguous; run codex-prompt sync",
19
+ "Prompt endpoint returned HTTP 400 for runtime=claude; deploy the fleet-prompt Worker with runtime support first",
20
+ "Prompt endpoint did not confirm runtime=claude; deploy the fleet-prompt Worker with runtime support first",
21
+ "Prompt endpoint must return plain text", "Prompt exceeds 256 KiB limit",
22
+ "Prompt is empty or contains NUL bytes", "Prompt revision does not match response body",
23
+ "The managed codex skills block in config.toml is damaged; restore its BEGIN/END markers or remove it",
24
+ "config.toml would be invalid with the managed skills block; is skills.config defined inline?",
25
+ "Managed skills rules did not parse as the last skills.config entries",
26
+ "Invalid catalog receipt", "Invalid prompt enrollment state",
27
+ "Invalid shared prompt revision", "Enrollment or configuration changed during refresh",
28
+ ]);
29
+ export function refreshFailure(component, error) {
30
+ const message = error instanceof Error ? error.message : "";
31
+ const safe = SAFE_CAUSES.has(message) || /^(?:Catalog endpoint returned HTTP \d{3}|Prompt endpoint returned HTTP \d{3}; existing snapshot retained)$/u.test(message);
32
+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
33
+ const cause = safe ? message : error instanceof SyntaxError ? "Managed JSON state is invalid; inspect codex-prompt status"
34
+ : error instanceof Error && error.name === "TimeoutError" ? "Endpoint request timed out"
35
+ : error instanceof Error && message.startsWith("Prompt sync is locked:") ? "Prompt sync is locked; check for an active sync before recovery"
36
+ : ["EACCES", "EPERM", "ENOENT", "ENOSPC"].includes(String(code))
37
+ ? `Local state I/O failed (${code}); check managed files and access`
38
+ : "Request or local-state validation failed; check the endpoint and managed state with codex-prompt status";
39
+ return new Error(`${component}: ${cause}`);
40
+ }
package/dist/remote.d.ts CHANGED
@@ -1,9 +1,33 @@
1
- export declare const REMOTE_POLICY = "The shared operating instructions and frozen agent context are provided in the base instructions. Current tool schemas, permissions and session routing remain separate.";
2
- /** Explicit sync and daily shared-prompt refresh validate before changing local state. */
3
- export declare function fetchPrompt(url: string, request?: typeof fetch): Promise<{
1
+ export declare const WORKER_RUNTIME_HINT = "deploy the fleet-prompt Worker with runtime support first";
2
+ /**
3
+ * Explicit sync and daily shared-prompt refresh validate before changing local state.
4
+ * Without `runtime` the configured URL is fetched exactly as written (the Codex artifact, which
5
+ * every Worker version serves). `runtime: "claude"` adds the parameter with the URL API, keeping
6
+ * `channel` and any other parameters, and requires the Worker to confirm it in X-Prompt-Runtime.
7
+ */
8
+ export declare function fetchPrompt(url: string, request?: typeof fetch, options?: {
9
+ runtime?: "claude";
10
+ }): Promise<{
4
11
  prompt: string;
5
12
  source: {
6
13
  url: string;
7
14
  revision: string;
8
15
  };
9
16
  }>;
17
+ /** Per-runtime fetchers for one configured promptUrl; Codex never sends `runtime`. */
18
+ export declare function policyFetchers(url: string, request?: typeof fetch): {
19
+ codex: () => Promise<{
20
+ prompt: string;
21
+ source: {
22
+ url: string;
23
+ revision: string;
24
+ };
25
+ }>;
26
+ claude: () => Promise<{
27
+ prompt: string;
28
+ source: {
29
+ url: string;
30
+ revision: string;
31
+ };
32
+ }>;
33
+ };
package/dist/remote.js CHANGED
@@ -1,18 +1,31 @@
1
1
  import { validatePromptUrl } from "./config.js";
2
2
  import { sha256 } from "./manager.js";
3
3
  const MAX_BYTES = 256 * 1024;
4
- // The operating policy lives in the downloaded base, not in a second policy copy.
5
- export const REMOTE_POLICY = "The shared operating instructions and frozen agent context are provided in the base instructions. Current tool schemas, permissions and session routing remain separate.";
6
- /** Explicit sync and daily shared-prompt refresh validate before changing local state. */
7
- export async function fetchPrompt(url, request = fetch) {
8
- const response = await request(validatePromptUrl(url), {
4
+ export const WORKER_RUNTIME_HINT = "deploy the fleet-prompt Worker with runtime support first";
5
+ /**
6
+ * Explicit sync and daily shared-prompt refresh validate before changing local state.
7
+ * Without `runtime` the configured URL is fetched exactly as written (the Codex artifact, which
8
+ * every Worker version serves). `runtime: "claude"` adds the parameter with the URL API, keeping
9
+ * `channel` and any other parameters, and requires the Worker to confirm it in X-Prompt-Runtime.
10
+ */
11
+ export async function fetchPrompt(url, request = fetch, options = {}) {
12
+ const target = validatePromptUrl(url);
13
+ if (options.runtime)
14
+ target.searchParams.set("runtime", options.runtime);
15
+ const response = await request(target, {
9
16
  redirect: "error",
10
17
  credentials: "omit",
11
18
  signal: AbortSignal.timeout(10_000),
12
19
  headers: { Accept: "text/plain", "Cache-Control": "no-cache" },
13
20
  });
21
+ // Workers before runtime support reject the unknown parameter with 400.
22
+ if (!response.ok && response.status === 400 && options.runtime)
23
+ throw new Error(`Prompt endpoint returned HTTP 400 for runtime=${options.runtime}; ${WORKER_RUNTIME_HINT}`);
14
24
  if (!response.ok)
15
25
  throw new Error(`Prompt endpoint returned HTTP ${response.status}; existing snapshot retained`);
26
+ if (options.runtime && response.headers.get("x-prompt-runtime") !== options.runtime) {
27
+ throw new Error(`Prompt endpoint did not confirm runtime=${options.runtime}; ${WORKER_RUNTIME_HINT}`);
28
+ }
16
29
  const type = response.headers.get("content-type")?.split(";")[0]?.trim();
17
30
  if (type !== "text/plain" || !response.body)
18
31
  throw new Error("Prompt endpoint must return plain text");
@@ -40,5 +53,9 @@ export async function fetchPrompt(url, request = fetch) {
40
53
  const revision = sha256(prompt);
41
54
  if (response.headers.get("x-prompt-revision") !== revision)
42
55
  throw new Error("Prompt revision does not match response body");
43
- return { prompt, source: { url, revision } };
56
+ return { prompt, source: { url: options.runtime ? target.href : url, revision } };
57
+ }
58
+ /** Per-runtime fetchers for one configured promptUrl; Codex never sends `runtime`. */
59
+ export function policyFetchers(url, request) {
60
+ return { codex: () => fetchPrompt(url, request), claude: () => fetchPrompt(url, request, { runtime: "claude" }) };
44
61
  }
package/dist/runtime.d.ts CHANGED
@@ -1,2 +1,41 @@
1
- /** Called at the actual adapter assembly boundary; failures abort, not a swallowed hook. */
1
+ export { normalizeOpenClawAdditions, normalizeOpenClawTurnContext } from "./context.js";
2
+ /**
3
+ * Called at the actual adapter assembly boundary; failures abort, not a swallowed hook. Non-null
4
+ * means this Codex run is managed. The value is the bundle's `policy`, which current syncs leave
5
+ * "": the Codex policy is the prompt-file prefix, delivered as base instructions.
6
+ */
2
7
  export declare function readFrozenPolicy(agentDir: string): string | null;
8
+ /**
9
+ * The verified base file, sent as each managed thread's base instructions at start and resume.
10
+ * Codex reads base instructions per session rather than from history, so a refreshed file
11
+ * reaches an existing thread when OpenClaw resumes it; the file itself stays the fallback.
12
+ */
13
+ export declare function readCodexBaseInstructions(agentDir: string): string | null;
14
+ export type ClaudeManagedPrompt = {
15
+ prompt: string;
16
+ sha256: string;
17
+ };
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.
25
+ */
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;
package/dist/runtime.js CHANGED
@@ -2,29 +2,133 @@ import { lstatSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { readPromptPointer } from "./toml.js";
5
+ import { parseClaudePolicy, parseEnrollment } from "./manager.js";
6
+ export { normalizeOpenClawAdditions, normalizeOpenClawTurnContext } from "./context.js";
5
7
  function readPrivate(path) {
6
8
  const stat = lstatSync(path);
7
9
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
8
10
  throw new Error("Frozen bridge refuses linked or non-regular state");
9
11
  return readFileSync(path, "utf8");
10
12
  }
11
- /** Called at the actual adapter assembly boundary; failures abort, not a swallowed hook. */
12
- export function readFrozenPolicy(agentDir) {
13
+ function readOptionalPrivate(path) {
14
+ try {
15
+ return readPrivate(path);
16
+ }
17
+ catch (error) {
18
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
19
+ return null;
20
+ throw error;
21
+ }
22
+ }
23
+ function sha256(text) { return createHash("sha256").update(text).digest("hex"); }
24
+ function readEnrollment(home) {
25
+ try {
26
+ return parseEnrollment(readOptionalPrivate(join(home, ".unblock-codex-prompt.json")));
27
+ }
28
+ catch (error) {
29
+ throw error instanceof Error && error.message === "Invalid prompt enrollment state" ? new Error("Invalid frozen bridge enrollment") : error;
30
+ }
31
+ }
32
+ /** The compiled snapshot, verified against its sync receipt. */
33
+ function readVerifiedSnapshot(home) {
34
+ const bundle = JSON.parse(readPrivate(join(home, ".unblock-codex-prompt-bundle.json")));
35
+ if (!bundle || typeof bundle !== "object" || !("schema" in bundle) || bundle.schema !== 1 ||
36
+ !("policy" in bundle) || typeof bundle.policy !== "string" || !("promptSha256" in bundle))
37
+ throw new Error("Frozen bundle missing or invalid; run codex-prompt sync");
38
+ const prompt = readPrivate(join(home, "unblock-codex-prompt.md"));
39
+ if (sha256(prompt) !== bundle.promptSha256)
40
+ throw new Error("Frozen prompt changed outside sync; refusing context suppression");
41
+ return { bundle, policy: bundle.policy, prompt };
42
+ }
43
+ function readCodexSnapshot(agentDir) {
13
44
  const home = join(agentDir, "codex-home");
14
- const state = JSON.parse(readPrivate(join(home, ".unblock-codex-prompt.json")));
15
- if (!state || typeof state !== "object" || !("schema" in state) || state.schema !== 1 || !("active" in state) || typeof state.active !== "boolean")
45
+ const state = readEnrollment(home);
46
+ if (!state)
16
47
  throw new Error("Invalid frozen bridge enrollment");
17
48
  if (!state.active)
18
49
  return null;
19
- const bundle = JSON.parse(readPrivate(join(home, ".unblock-codex-prompt-bundle.json")));
20
- if (!bundle || typeof bundle !== "object" || !("schema" in bundle) || bundle.schema !== 1 ||
21
- !("policy" in bundle) || typeof bundle.policy !== "string" || !bundle.policy.trim() || !("promptSha256" in bundle))
22
- throw new Error("Frozen bundle missing or invalid; run codex-prompt sync");
23
- const path = join(home, "unblock-codex-prompt.md");
24
- if (readPromptPointer(readPrivate(join(home, "config.toml"))) !== path)
50
+ if (!state.runtimes.includes("codex"))
51
+ throw new Error("Codex bridge installed without Codex enrollment; restore or run codex-prompt sync");
52
+ const snapshot = readVerifiedSnapshot(home);
53
+ if (readPromptPointer(readPrivate(join(home, "config.toml"))) !== join(home, "unblock-codex-prompt.md")) {
25
54
  throw new Error("Frozen prompt pointer changed; refusing context suppression");
26
- const hash = createHash("sha256").update(readPrivate(path)).digest("hex");
27
- if (hash !== bundle.promptSha256)
28
- throw new Error("Frozen prompt changed outside sync; refusing context suppression");
29
- return bundle.policy;
55
+ }
56
+ return snapshot;
57
+ }
58
+ /**
59
+ * Called at the actual adapter assembly boundary; failures abort, not a swallowed hook. Non-null
60
+ * means this Codex run is managed. The value is the bundle's `policy`, which current syncs leave
61
+ * "": the Codex policy is the prompt-file prefix, delivered as base instructions.
62
+ */
63
+ export function readFrozenPolicy(agentDir) {
64
+ return readCodexSnapshot(agentDir)?.policy ?? null;
65
+ }
66
+ /**
67
+ * The verified base file, sent as each managed thread's base instructions at start and resume.
68
+ * Codex reads base instructions per session rather than from history, so a refreshed file
69
+ * reaches an existing thread when OpenClaw resumes it; the file itself stays the fallback.
70
+ */
71
+ export function readCodexBaseInstructions(agentDir) {
72
+ return readCodexSnapshot(agentDir)?.prompt ?? null;
73
+ }
74
+ /**
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.
81
+ */
82
+ export function readClaudeManagedPrompt(agentDir) {
83
+ const home = join(agentDir, "codex-home");
84
+ 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)
88
+ 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
+ const { bundle } = readVerifiedSnapshot(home);
92
+ const claudePolicy = parseClaudePolicy("claudePolicy" in bundle ? bundle.claudePolicy : undefined);
93
+ const agentContext = "agentContext" in bundle ? bundle.agentContext : undefined;
94
+ if (typeof agentContext !== "string" || !agentContext.trim())
95
+ 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" };
30
134
  }
@@ -0,0 +1,34 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/plugin-entry";
2
+ type PolicyResolver = (params: {
3
+ config: OpenClawConfig;
4
+ provider?: string;
5
+ modelId?: string;
6
+ agentId?: string;
7
+ }) => {
8
+ policy?: {
9
+ id?: unknown;
10
+ };
11
+ } | undefined;
12
+ type Detection = {
13
+ ref: string;
14
+ runtime: string | null;
15
+ };
16
+ /** OpenClaw's public configured-policy resolver (2026.10.6+), feature-detected for older hosts. */
17
+ export declare function runtimePolicyResolver(api: unknown): PolicyResolver | undefined;
18
+ /**
19
+ * Model refs the agent can select by configuration, resolved like OpenClaw: the agent's model
20
+ * replaces the default primary (and default fallbacks unless it lists its own), plus the agent's
21
+ * own allowed-model map, which it can switch to at run time. The Gateway-wide default map
22
+ * (agents.defaults.models) does not enroll a runtime for this agent.
23
+ */
24
+ export declare function configuredModelRefs(config: OpenClawConfig, agentId: string): string[];
25
+ /**
26
+ * Explicit-sync detection only. This reads authored policy; it does not establish runtime
27
+ * availability. Each turn's actual execution path stays authoritative at the patched seams.
28
+ */
29
+ export declare function detectConfiguredRuntimes(config: OpenClawConfig, agentId: string, resolve: PolicyResolver | undefined): {
30
+ runtimes: Set<"codex" | "claude-cli">;
31
+ detections: Detection[];
32
+ resolver: "openclaw" | "unavailable";
33
+ };
34
+ export {};
@@ -0,0 +1,79 @@
1
+ function record(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
2
+ /** OpenClaw's public configured-policy resolver (2026.10.6+), feature-detected for older hosts. */
3
+ export function runtimePolicyResolver(api) {
4
+ const runtime = record(api) ? api.runtime : undefined;
5
+ const modelConfig = record(runtime) ? runtime.modelConfig : undefined;
6
+ const resolve = record(modelConfig) ? modelConfig.resolveModelRuntimePolicy : undefined;
7
+ return typeof resolve === "function" ? resolve : undefined;
8
+ }
9
+ function agentEntry(config, agentId) {
10
+ const agents = config.agents;
11
+ if (!record(agents))
12
+ return undefined;
13
+ if (Array.isArray(agents.list))
14
+ return agents.list.find((entry) => record(entry) && entry.id === agentId);
15
+ return record(agents.entries) && record(agents.entries[agentId]) ? agents.entries[agentId] : undefined;
16
+ }
17
+ function primaryOf(model) {
18
+ const value = typeof model === "string" ? model : record(model) ? model.primary : undefined;
19
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
20
+ }
21
+ /** OpenClaw's fallback override: an agent model replaces default fallbacks unless it lists its own. */
22
+ function fallbacksOverride(model) {
23
+ if (!model)
24
+ return undefined;
25
+ if (typeof model === "string")
26
+ return primaryOf(model) ? [] : undefined;
27
+ if (!record(model))
28
+ return undefined;
29
+ if (!Object.hasOwn(model, "fallbacks"))
30
+ return Object.hasOwn(model, "primary") && primaryOf(model) ? [] : undefined;
31
+ return Array.isArray(model.fallbacks) ? model.fallbacks : undefined;
32
+ }
33
+ /**
34
+ * Model refs the agent can select by configuration, resolved like OpenClaw: the agent's model
35
+ * replaces the default primary (and default fallbacks unless it lists its own), plus the agent's
36
+ * own allowed-model map, which it can switch to at run time. The Gateway-wide default map
37
+ * (agents.defaults.models) does not enroll a runtime for this agent.
38
+ */
39
+ export function configuredModelRefs(config, agentId) {
40
+ const agents = config.agents;
41
+ const defaults = record(agents) && record(agents.defaults) ? agents.defaults : undefined;
42
+ const agent = agentEntry(config, agentId);
43
+ const refs = new Set();
44
+ const add = (value) => { if (typeof value === "string" && value.trim())
45
+ refs.add(value.trim()); };
46
+ add(primaryOf(agent?.model) ?? primaryOf(defaults?.model));
47
+ const fallbacks = fallbacksOverride(agent?.model) ?? (record(defaults?.model) && Array.isArray(defaults.model.fallbacks) ? defaults.model.fallbacks : []);
48
+ fallbacks.forEach(add);
49
+ if (record(agent?.models))
50
+ Object.keys(agent.models).forEach(add);
51
+ return [...refs];
52
+ }
53
+ /**
54
+ * Explicit-sync detection only. This reads authored policy; it does not establish runtime
55
+ * availability. Each turn's actual execution path stays authoritative at the patched seams.
56
+ */
57
+ export function detectConfiguredRuntimes(config, agentId, resolve) {
58
+ const detections = configuredModelRefs(config, agentId).map(ref => {
59
+ const slash = ref.indexOf("/");
60
+ const provider = slash > 0 ? ref.slice(0, slash) : undefined;
61
+ const modelId = slash > 0 ? ref.slice(slash + 1) : ref;
62
+ // Legacy `claude-cli/<model>` refs name the CLI backend directly (OpenClaw compatibility input).
63
+ if (provider?.toLowerCase() === "claude-cli")
64
+ return { ref, runtime: "claude-cli" };
65
+ let id;
66
+ try {
67
+ id = resolve?.({ config, agentId, ...provider ? { provider } : {}, modelId })?.policy?.id;
68
+ }
69
+ catch {
70
+ id = undefined;
71
+ }
72
+ return { ref, runtime: typeof id === "string" && id.trim() ? id.trim().toLowerCase() : null };
73
+ });
74
+ const runtimes = new Set();
75
+ for (const { runtime } of detections)
76
+ if (runtime === "codex" || runtime === "claude-cli")
77
+ runtimes.add(runtime);
78
+ return { runtimes, detections, resolver: resolve ? "openclaw" : "unavailable" };
79
+ }
@@ -1,27 +1,28 @@
1
1
  {
2
2
  "id": "unblock-codex-prompt",
3
3
  "name": "Unblock Codex Prompt",
4
- "version": "0.2.4",
5
- "description": "Maintain an agent-scoped Codex base prompt and its model_instructions_file pointer.",
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).",
6
6
  "activation": { "onStartup": true },
7
7
  "configSchema": {
8
8
  "type": "object",
9
9
  "additionalProperties": false,
10
+ "required": ["promptUrl", "frozenContext"],
10
11
  "properties": {
11
12
  "agentId": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$", "default": "main" },
12
- "agentName": { "type": "string", "minLength": 1, "maxLength": 100 },
13
- "frozenContext": { "type": "boolean", "default": false },
13
+ "agentName": { "type": "string", "minLength": 1, "maxLength": 100, "deprecated": true },
14
+ "frozenContext": { "type": "boolean", "const": true },
14
15
  "promptUrl": { "type": "string", "format": "uri", "pattern": "^https://" },
15
16
  "suppressExplicitDelegationPrompt": { "type": "boolean", "default": false },
16
17
  "disabledCodexSkills": { "type": "array", "default": ["pages", "work-pets"], "maxItems": 64, "uniqueItems": true, "items": { "type": "string", "pattern": "^[\\w.@:-]{1,128}$" } }
17
18
  }
18
19
  },
19
20
  "uiHints": {
20
- "agentId": { "label": "OpenClaw agent ID", "help": "Only this agent's managed Codex home is modified. Defaults to main." },
21
- "agentName": { "label": "Agent name", "help": "Optional name in the shared prompt. Omit for a generic opening." },
22
- "frozenContext": { "label": "Frozen context bridge", "help": "Opt in on OpenClaw/Codex >=2026.9.2 with a supported context-assembly layout. Initial setup requires explicit sync and activation. Local documents and skills stay frozen until another sync." },
23
- "promptUrl": { "label": "Fleet prompt endpoint", "help": "Public HTTPS plain-text endpoint with X-Prompt-Revision SHA-256. After initial sync, refreshed daily and when overdue on startup without refreshing agent context. Requires frozenContext; replaces both bundled policy files." },
24
- "suppressExplicitDelegationPrompt": { "label": "Suppress conflicting Codex delegation policy", "help": "Manage a model_catalog_json override, refreshed from the configured provider daily and when overdue on startup. Requires frozenContext and an available provider env_key. Generated-file edits are replaced on refresh." },
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." },
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." },
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
+ "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." },
25
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." }
26
27
  }
27
28
  }