@unblocklabs/unblock-codex-prompt 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/adapter.d.ts CHANGED
@@ -1,37 +1,27 @@
1
- type AdapterFile = {
2
- path: string;
3
- originalSha256: string;
4
- patchedSha256: string;
5
- previousPatchedSha256?: string;
6
- };
1
+ import { type PatchedFile, type RestorePlan } from "./patched-files.js";
2
+ /** packageVersion (recorded since 0.4) lets restore tell an updater's replacement from a foreign edit. */
7
3
  type Receipt = ({
8
4
  schema: 1;
9
5
  packageDir: string;
10
- } & AdapterFile) | {
6
+ } & PatchedFile) | {
11
7
  schema: 2;
12
8
  packageDir: string;
13
- files: AdapterFile[];
9
+ packageVersion?: string;
10
+ files: PatchedFile[];
14
11
  };
15
12
  export declare function readReceipt(agentDir: string): Promise<Receipt | null>;
13
+ export declare function codexAdapterOwnership(agentDir: string): Promise<import("./patched-files.js").Ownership>;
16
14
  export declare function patchAdapterSources(sources: string[], agentDir: string, agentId: string, runtimePath: string): string[];
17
15
  export declare function prepareAdapter(agentDir: string, agentId: string, suppliedDir: string | undefined, runtimePath: string): Promise<{
18
- files: {
19
- patched: string;
20
- path: string;
21
- current: string;
22
- original: string;
23
- }[];
16
+ files: import("./patched-files.js").PreparedFile[];
24
17
  receipt: {
25
18
  schema: 2;
26
19
  packageDir: string;
27
- files: {
28
- previousPatchedSha256?: string;
29
- path: string;
30
- originalSha256: string;
31
- patchedSha256: string;
32
- }[];
20
+ packageVersion: string;
21
+ files: PatchedFile[];
33
22
  };
34
23
  previousReceipt: string | null;
24
+ staleBackups: Set<string>;
35
25
  }>;
36
26
  export declare function installAdapter(agentDir: string, plan: Awaited<ReturnType<typeof prepareAdapter>>): Promise<{
37
27
  adapterChanged: boolean;
@@ -39,14 +29,22 @@ export declare function installAdapter(agentDir: string, plan: Awaited<ReturnTyp
39
29
  }>;
40
30
  export declare function adapterStatus(agentDir: string): Promise<{
41
31
  installed: boolean;
42
- path?: never;
43
- paths?: never;
44
- minimumVersion?: never;
32
+ state: "absent";
45
33
  } | {
34
+ minimumVersion: string;
35
+ packageVersion?: string;
46
36
  installed: boolean;
37
+ state: "changed" | "patched" | "partial" | "original" | "missing";
47
38
  path: string;
48
39
  paths: string[];
49
- minimumVersion: string;
40
+ packageDir: string;
41
+ }>;
42
+ /** Validates every recorded file before any write; empty unless this adapter's bytes are installed. */
43
+ export declare function planAdapterRestore(agentDir: string): Promise<RestorePlan>;
44
+ export declare function applyAdapterRestore(plan: RestorePlan): Promise<{
45
+ ownership: import("./patched-files.js").Ownership;
46
+ files: string[];
47
+ superseded: string[];
48
+ restartRequired: boolean;
50
49
  }>;
51
- export declare function restoreAdapter(agentDir: string): Promise<void>;
52
50
  export {};
package/dist/adapter.js CHANGED
@@ -1,22 +1,15 @@
1
1
  import { lstat, readFile, readdir } from "node:fs/promises";
2
2
  import { basename, isAbsolute, join, resolve } from "node:path";
3
3
  import { parse } from "acorn";
4
- import { readOptional, replaceFile, sha256 } from "./manager.js";
4
+ import { readOptional, sha256 } from "./manager.js";
5
+ import { applyPatchedRestore, beginPatch, installPatch, openPatchedFiles, patchedFilesOwnership, patchedFilesStatus, planPatchedRestore } from "./patched-files.js";
5
6
  import { openclawRoot } from "./compiler.js";
6
7
  import { assertSupportedVersion, MINIMUM_OPENCLAW } from "./compatibility.js";
8
+ import { managedTargetSource } from "./managed-target.js";
7
9
  const MARKER = "// unblock-codex-prompt bridge v1";
8
10
  const BUNDLE_NAME = /^(?:thread-(?:lifecycle|requests|policy)|dynamic-tools|attempt-workspace-context|run-attempt)-[\w-]+\.m?js$/u;
9
11
  const HASH = /^[a-f0-9]{64}$/u;
10
- // Reviewed context carriers, independent of release-specific bundle names.
11
- const CONTEXT_HASHES = {
12
- legacy: "1fb45c46c50a63f68e8b6bdfbc5d7ae2d323470c00db69779d159592868940bb",
13
- parent: "5ee80edf3f3887e841def5d64896a3d27c35063f6d4803dceeb8b8bf07b654f0",
14
- splitParent: "6515e383260e0edd4379a2e694d9b066ddb02a79b55fd7494bf7f85affee72c6",
15
- collaboration: "aea7e95ca43f0997b0a3f616f327132bfdd057bb731e6eead132fba21de3f981",
16
- legacyThread: "703a32a0b18eacd45a9fd3d68c04a13527bdbeaae50a11a6b76768b84b99a9ed",
17
- thread: "3aa4c414cb449cdb9167e6ed2df9397559176310ce7cff882652bd669ac8cee8",
18
- };
19
- // Identical context producers/carriers in the published 2026.10.6 and 2026.10.8 bundles.
12
+ // Reviewed context producers/carriers, identical in every published @openclaw/codex 2026.10.5-2026.10.9.
20
13
  const REFRESHABLE_CONTEXT_HASHES = {
21
14
  buildDeveloperInstructions: "4b4054cdd5ce65358508182d65e71a4c742b2e9debfa51eb65c5b4e26d1eb0bb",
22
15
  buildCodexWorkspaceBootstrapContext: "91bb36eddcf16741957a775af106ab3226ec02dbbe2576b71675ea6db922c0b9",
@@ -28,19 +21,16 @@ const REFRESHABLE_CONTEXT_HASHES = {
28
21
  restoreCodexThreadInstructionsAfterCompaction: "86d6f792175cfbc604f5408016e00b77ed1f7fbefa33b0210d6fbf8d56a2c0a4",
29
22
  };
30
23
  function receiptPath(agentDir) { return join(agentDir, "codex-home", ".unblock-codex-prompt-adapter.json"); }
31
- function receiptFiles(receipt) { return receipt.schema === 1 ? [receipt] : receipt.files; }
32
- function backupPath(agentDir, file, legacy = false) {
33
- return join(agentDir, "codex-home", legacy ? ".unblock-codex-prompt-adapter-original.js" : ".unblock-codex-prompt-adapter-original-" + basename(file.path));
24
+ function receiptFiles(receipt) {
25
+ if (receipt.schema === 2)
26
+ return receipt.files;
27
+ const { path, originalSha256, patchedSha256, previousPatchedSha256 } = receipt;
28
+ return [{ path, originalSha256, patchedSha256, ...previousPatchedSha256 ? { previousPatchedSha256 } : {} }];
34
29
  }
35
- function ownsSource(file, source) {
36
- if (source === null)
37
- return false;
38
- const hash = sha256(source);
39
- return hash === file.originalSha256 || hash === file.patchedSha256 || hash === file.previousPatchedSha256;
30
+ function backupPath(agentDir, path, legacy = false) {
31
+ return join(agentDir, "codex-home", legacy ? ".unblock-codex-prompt-adapter-original.js" : ".unblock-codex-prompt-adapter-original-" + basename(path));
40
32
  }
41
33
  function parseReceipt(source) {
42
- if (source === null)
43
- return null;
44
34
  const value = JSON.parse(source);
45
35
  if (!value || typeof value !== "object" || !("schema" in value) || (value.schema !== 1 && value.schema !== 2) ||
46
36
  !("packageDir" in value) || typeof value.packageDir !== "string" || !isAbsolute(value.packageDir))
@@ -65,23 +55,74 @@ function parseReceipt(source) {
65
55
  });
66
56
  if (new Set(files.map(file => basename(file.path))).size !== files.length)
67
57
  throw new Error("Invalid adapter receipt");
68
- return value.schema === 1 ? { schema: 1, packageDir, ...files[0] } : { schema: 2, packageDir, files };
58
+ const packageVersion = "packageVersion" in value ? value.packageVersion : undefined;
59
+ if (packageVersion !== undefined && typeof packageVersion !== "string")
60
+ throw new Error("Invalid adapter receipt");
61
+ return value.schema === 1 ? { schema: 1, packageDir, ...files[0] } : { schema: 2, packageDir, ...packageVersion ? { packageVersion } : {}, files };
62
+ }
63
+ export async function readReceipt(agentDir) {
64
+ const source = await readOptional(receiptPath(agentDir));
65
+ return source === null ? null : parseReceipt(source);
66
+ }
67
+ async function packageVersion(packageDir) {
68
+ try {
69
+ const pkg = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8"));
70
+ return pkg && typeof pkg === "object" && "version" in pkg && typeof pkg.version === "string" ? pkg.version : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ /** This agent's Codex patched-file set: receipt, backups and package identity. */
77
+ function codexFiles(agentDir) {
78
+ return {
79
+ receiptPath: receiptPath(agentDir),
80
+ parseReceipt(source) {
81
+ const receipt = parseReceipt(source);
82
+ // Schema-1 (0.2.0) receipts kept their single backup under a legacy name.
83
+ return { root: receipt.packageDir, ...receipt.schema === 2 && receipt.packageVersion !== undefined ? { version: receipt.packageVersion } : {},
84
+ files: receiptFiles(receipt), backupPath: file => backupPath(agentDir, file.path, receipt.schema === 1) };
85
+ },
86
+ installedVersion: packageVersion,
87
+ backupPath: path => backupPath(agentDir, path),
88
+ messages: {
89
+ installChanged: "Restore the previous adapter before changing Codex installations",
90
+ changed: "Codex adapter changed by another writer; refusing to overwrite",
91
+ missing: "Missing Codex adapter",
92
+ prepareBackupInvalid: "Codex adapter backup invalid; refusing to patch",
93
+ moved: "Codex adapter path changed; restore before changing installations",
94
+ foreignBackup: "Foreign adapter backup",
95
+ concurrent: "Concurrent adapter edit; refusing to overwrite",
96
+ foreignEdit: "Foreign adapter edit; refusing restore",
97
+ backupInvalid: "Adapter backup invalid",
98
+ },
99
+ };
100
+ }
101
+ export async function codexAdapterOwnership(agentDir) {
102
+ return patchedFilesOwnership(codexFiles(agentDir));
69
103
  }
70
- export async function readReceipt(agentDir) { return parseReceipt(await readOptional(receiptPath(agentDir))); }
71
104
  function bridgePrefix(agentDir, agentId, runtimePath) {
72
105
  return `${MARKER}
73
106
  import { createRequire as unblockPromptCreateRequire } from "node:module";
74
107
  const unblockPromptRequire = unblockPromptCreateRequire(import.meta.url);
75
108
  function unblockNormalizeAdditions(text) { return unblockPromptRequire(${JSON.stringify(runtimePath)}).normalizeOpenClawAdditions(text); }
76
109
  function unblockNormalizeTurnContext(context) { return unblockPromptRequire(${JSON.stringify(runtimePath)}).normalizeOpenClawTurnContext(context); }
77
- function unblockFrozenPolicy(params) {
78
- const plugins = params.config?.plugins;
79
- const entry = plugins?.entries?.["unblock-codex-prompt"];
80
- if (plugins?.enabled === false || entry?.enabled !== true || entry.config?.frozenContext !== true ||
81
- (Array.isArray(plugins.allow) && !plugins.allow.includes("unblock-codex-prompt"))) return null;
82
- const target = entry.config?.agentId ?? "main";
83
- if (params.agentId !== target) return null;
84
- if (target !== ${JSON.stringify(agentId)}) throw new Error("Frozen bridge target changed; restore and reinstall the adapter");
110
+ // One non-enumerable live-context relay on the attempt params: producers that run first in the
111
+ // reviewed attempt order record their host-rendered text, buildDeveloperInstructions reads it.
112
+ // The registered symbol works across bundles and realms; copies of params never carry it.
113
+ const unblockLiveKey = Symbol.for("unblock-codex-prompt.live-context");
114
+ function unblockRelay(params, part, text) {
115
+ Object.defineProperty(params, unblockLiveKey, { value: { ...params[unblockLiveKey], [part]: text }, configurable: true, writable: true, enumerable: false });
116
+ }
117
+ function unblockBaseInstructions(params) {
118
+ if (unblockFrozenPolicy(params) === null) return null;
119
+ // After a plugin rollback without restore the older runtime lacks this export: Codex then
120
+ // reads the same policy from model_instructions_file, as before this bridge version.
121
+ const runtime = unblockPromptRequire(${JSON.stringify(runtimePath)});
122
+ return typeof runtime.readCodexBaseInstructions === "function" ? runtime.readCodexBaseInstructions(${JSON.stringify(agentDir)}) : null;
123
+ }
124
+ ${managedTargetSource({ name: "unblockManagedTarget", agentId, targetChanged: "Frozen bridge target changed; restore and reinstall the adapter" })}function unblockFrozenPolicy(params) {
125
+ if (!unblockManagedTarget(params)) return null;
85
126
  return unblockPromptRequire(${JSON.stringify(runtimePath)}).readFrozenPolicy(${JSON.stringify(agentDir)});
86
127
  }
87
128
  `;
@@ -97,49 +138,13 @@ export function patchAdapterSources(sources, agentDir, agentId, runtimePath) {
97
138
  throw new Error("Unsupported Codex adapter shape: " + name);
98
139
  return matches[0];
99
140
  };
100
- // 2026.9.9 has the workspace producer but still uses the legacy carriers.
101
- if (!functions.some(fn => fn.node.id?.name === "buildTurnScopedCollaborationInstructions") &&
102
- functions.some(fn => fn.node.id?.name === "buildCodexWorkspaceBootstrapContext")) {
103
- const prefix = bridgePrefix(agentDir, agentId, runtimePath);
104
- return patchOperationalAdapter(patchRefreshableAdapter(sources, find, prefix), prefix);
141
+ // Older layouts carry persona in turn-scoped collaboration text that native children never see.
142
+ if (functions.some(fn => fn.node.id?.name === "buildTurnScopedCollaborationInstructions") ||
143
+ !functions.some(fn => fn.node.id?.name === "buildCodexWorkspaceBootstrapContext")) {
144
+ throw new Error(`Unsupported Codex context layout; live agent context requires @openclaw/codex >=${MINIMUM_OPENCLAW}`);
105
145
  }
106
- const developer = find("buildDeveloperInstructions");
107
- const collaboration = find("buildTurnScopedCollaborationInstructions");
108
- const parent = functions.some(fn => fn.node.id?.name === "buildCodexParentLocalInstructions") ? find("buildCodexParentLocalInstructions") : null;
109
- const thread = functions.some(fn => fn.node.id?.name === "buildCodexThreadConfiguration") ? find("buildCodexThreadConfiguration") : null;
110
- for (const { node, bundle } of [developer, collaboration, ...(parent ? [parent] : []), ...(thread ? [thread] : [])]) {
111
- if (node.async || node.generator || node.params.length !== 2 || node.params[0]?.type !== "Identifier" || node.params[0].name !== "params" ||
112
- !/^(options|options\s*=\s*\{\})$/u.test(sources[bundle].slice(node.params[1].start, node.params[1].end)))
113
- throw new Error("Unsupported Codex adapter shape: parameters");
114
- }
115
- for (const name of ["buildDefaultCollaborationInstructions", "buildCronCollaborationInstructions"]) {
116
- const helper = find(name);
117
- if (helper.node.params.length !== 0 || helper.bundle !== collaboration.bundle)
118
- throw new Error("Unsupported Codex adapter shape: mode helpers");
119
- }
120
- const fingerprint = (fn) => sha256(sources[fn.bundle].slice(fn.node.start, fn.node.end));
121
- const split = parent !== null && fingerprint(parent) === CONTEXT_HASHES.splitParent;
122
- if (fingerprint(collaboration) !== (parent ? CONTEXT_HASHES.collaboration : CONTEXT_HASHES.legacy) ||
123
- (parent && (parent.bundle !== collaboration.bundle || ![CONTEXT_HASHES.parent, CONTEXT_HASHES.splitParent].includes(fingerprint(parent)))) ||
124
- (thread && thread.bundle !== developer.bundle) ||
125
- (split ? !thread || fingerprint(thread) !== CONTEXT_HASHES.thread : thread !== null && fingerprint(thread) !== CONTEXT_HASHES.legacyThread))
126
- throw new Error("Unsupported Codex context assembly; review the changed upstream functions before syncing");
127
146
  const prefix = bridgePrefix(agentDir, agentId, runtimePath);
128
- const insertions = [
129
- { fn: developer, text: '\n\tconst unblockPolicy = unblockFrozenPolicy(params);\n\tif (unblockPolicy !== null) return [unblockPolicy, params.gitCoauthorPrompt, unblockNormalizeAdditions(params.extraSystemPrompt)].filter(section => typeof section === "string" && section.trim()).join("\\n\\n");' },
130
- { fn: collaboration, text: '\n\tif (unblockFrozenPolicy(params) !== null) return params.trigger === "cron" ? buildCronCollaborationInstructions() : buildDefaultCollaborationInstructions();' },
131
- ...(parent ? [{ fn: parent, text: '\n\tif (unblockFrozenPolicy(params) !== null) return params.trigger === "cron" ? buildCronCollaborationInstructions() : null;' }] : []),
132
- // 2026.9.8 moved skills to the start/resume/fork carrier, outside developer policy.
133
- ...(split && thread ? [{ fn: thread, text: '\n\tif (unblockFrozenPolicy(params) !== null) options = { ...options, skillsInstructions: undefined };' }] : []),
134
- ];
135
- return sources.map((source, bundle) => {
136
- const edits = insertions.filter(edit => edit.fn.bundle === bundle).sort((a, b) => b.fn.node.body.start - a.fn.node.body.start);
137
- for (const { fn, text } of edits) {
138
- const at = fn.node.body.start + 1;
139
- source = source.slice(0, at) + text + source.slice(at);
140
- }
141
- return edits.length ? prefix + source : source;
142
- });
147
+ return patchOperationalAdapter(patchRefreshableAdapter(sources, find, prefix), prefix);
143
148
  }
144
149
  function patchRefreshableAdapter(sources, find, prefix) {
145
150
  for (const [name, expected] of Object.entries(REFRESHABLE_CONTEXT_HASHES)) {
@@ -151,22 +156,54 @@ function patchRefreshableAdapter(sources, find, prefix) {
151
156
  const developer = find("buildDeveloperInstructions");
152
157
  const skills = find("renderCodexSkillsInstructions");
153
158
  const workspace = find("buildCodexWorkspaceBootstrapContext");
159
+ const thread = find("buildCodexThreadConfiguration");
160
+ const originalThread = sources[thread.bundle].slice(thread.node.start, thread.node.end)
161
+ .replace("function buildCodexThreadConfiguration(", "function unblockOriginalThreadConfiguration(");
162
+ // Thread start, resume and fork requests carry the verified base file as base instructions.
163
+ // OpenClaw fingerprints these requests, so a refreshed policy resumes the thread on its next
164
+ // turn with the new base; Codex keeps base instructions out of history and compaction. The
165
+ // model_instructions_file pointer to the same file remains the fallback.
166
+ const threadWrapper = `function buildCodexThreadConfiguration(params, options) {
167
+ const base = unblockBaseInstructions(params);
168
+ const request = unblockOriginalThreadConfiguration(params, options);
169
+ return base === null ? request : { ...request, baseInstructions: base };
170
+ }
171
+ `;
154
172
  const originalWorkspace = sources[workspace.bundle].slice(workspace.node.start, workspace.node.end)
155
173
  .replace("async function buildCodexWorkspaceBootstrapContext", "async function unblockOriginalWorkspaceContext");
156
- // Suppress at the producers: initial, warm, fork, parent-local and post-compaction
157
- // carriers all receive the same empty refreshable section. Native AGENTS stays live.
174
+ const originalSkills = sources[skills.bundle].slice(skills.node.start, skills.node.end)
175
+ .replace("function renderCodexSkillsInstructions(", "function unblockOriginalSkillsInstructions(");
176
+ // Live session context, in the host's own rendering, moves from the parent-only and refreshable
177
+ // carriers into the thread developer instructions: rebuilt every turn (a change re-syncs the
178
+ // thread), restored after compaction and inherited by native children. Both producers run on
179
+ // the same attempt params object before buildDeveloperInstructions (reviewed call order in
180
+ // every supported release) and relay their output on it:
181
+ // - skills: OpenClaw's per-session skills catalog with its skills_search/skills_read hints,
182
+ // exactly as upstream renders it (nothing when upstream renders nothing);
183
+ // - persona: SOUL, IDENTITY, shared USER and the session-selected personal USER.
184
+ // Memory stays suppressed at its producer; native AGENTS stays live.
185
+ const skillsWrapper = `function renderCodexSkillsInstructions(params) {
186
+ const policy = unblockFrozenPolicy(params.attempt);
187
+ const skills = unblockOriginalSkillsInstructions(params);
188
+ if (policy === null) return skills;
189
+ unblockRelay(params.attempt, "skills", skills);
190
+ return;
191
+ }
192
+ `;
158
193
  const wrapper = `async function buildCodexWorkspaceBootstrapContext(params) {
159
194
  const policy = unblockFrozenPolicy(params.params);
160
195
  const context = await unblockOriginalWorkspaceContext(params);
161
- return policy === null ? context : { ...context, personaInstructions: undefined, sharedPersonaInstructions: undefined, memoryInstructions: undefined };
196
+ if (policy === null) return context;
197
+ unblockRelay(params.params, "persona", context.personaInstructions);
198
+ return { ...context, personaInstructions: undefined, sharedPersonaInstructions: undefined, memoryInstructions: undefined };
162
199
  }
163
200
  `;
164
201
  const edits = [
165
202
  { bundle: developer.bundle, start: developer.node.body.start + 1, end: developer.node.body.start + 1,
166
- text: '\n\tconst unblockPolicy = unblockFrozenPolicy(params);\n\tif (unblockPolicy !== null) return [unblockPolicy, params.gitCoauthorPrompt, unblockNormalizeAdditions(params.extraSystemPrompt)].filter(section => typeof section === "string" && section.trim()).join("\\n\\n");' },
167
- { bundle: skills.bundle, start: skills.node.body.start + 1, end: skills.node.body.start + 1,
168
- text: '\n\tif (unblockFrozenPolicy(params.attempt) !== null) return;' },
203
+ text: '\n\tconst unblockPolicy = unblockFrozenPolicy(params);\n\tif (unblockPolicy !== null) return [unblockPolicy, params[unblockLiveKey]?.skills, params[unblockLiveKey]?.persona, params.gitCoauthorPrompt, unblockNormalizeAdditions(params.extraSystemPrompt)].filter(section => typeof section === "string" && section.trim()).join("\\n\\n");' },
204
+ { bundle: skills.bundle, start: skills.node.start, end: skills.node.end, text: skillsWrapper + originalSkills },
169
205
  { bundle: workspace.bundle, start: workspace.node.start, end: workspace.node.end, text: wrapper + originalWorkspace },
206
+ { bundle: thread.bundle, start: thread.node.start, end: thread.node.end, text: threadWrapper + originalThread },
170
207
  ];
171
208
  return sources.map((source, bundle) => {
172
209
  const selected = edits.filter(edit => edit.bundle === bundle).sort((a, b) => b.start - a.start);
@@ -205,7 +242,7 @@ function patchOperationalAdapter(sources, prefix) {
205
242
  replacement = original.replace("await refreshCodexThreadPolicy({", "await refreshCodexThreadPolicy({\n\t\t\tunblockManaged: unblockFrozenPolicy(params.params) !== null,");
206
243
  }
207
244
  else if (name === "refreshCodexThreadPolicy") {
208
- replacement = original.replace("{\n", '{\n\tif (params.unblockManaged) {\n\t\tawait injectCodexThreadDeveloperHandoff(params, "Current OpenClaw generic policy replaces all earlier OpenClaw generic policy; removed sections are withdrawn.\\n\\n" + params.developerInstructions);\n\t\treturn;\n\t}\n');
245
+ replacement = original.replace("{\n", '{\n\tif (params.unblockManaged) {\n\t\tawait injectCodexThreadDeveloperHandoff(params, "Follow the OpenClaw developer instructions below in place of any earlier OpenClaw developer instructions in this conversation.\\n\\n" + params.developerInstructions);\n\t\treturn;\n\t}\n');
209
246
  }
210
247
  else {
211
248
  const originalName = "unblockOriginal" + name;
@@ -224,17 +261,18 @@ export async function prepareAdapter(agentDir, agentId, suppliedDir, runtimePath
224
261
  await openclawRoot();
225
262
  if (!isAbsolute(runtimePath) || await readOptional(runtimePath) === null)
226
263
  throw new Error("Missing durable plugin runtime");
227
- const previousReceipt = await readOptional(receiptPath(agentDir));
228
- const receipt = parseReceipt(previousReceipt);
229
- const packageDir = suppliedDir ? resolve(suppliedDir) : receipt?.packageDir;
264
+ const set = codexFiles(agentDir);
265
+ const opened = await openPatchedFiles(set);
266
+ // A cleared receipt still remembers the package for a sync without --codex-plugin-dir.
267
+ const packageDir = suppliedDir ? resolve(suppliedDir) : opened.recorded?.root;
230
268
  if (!packageDir)
231
269
  throw new Error("First frozen sync requires --codex-plugin-dir from openclaw plugins inspect codex --json");
232
- if (receipt && receipt.packageDir !== packageDir)
233
- throw new Error("Restore the previous adapter before changing Codex installations");
270
+ const patch = await beginPatch(set, opened, packageDir);
234
271
  const pkg = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8"));
235
272
  if (!pkg || typeof pkg !== "object" || !("name" in pkg) || pkg.name !== "@openclaw/codex")
236
273
  throw new Error("Expected the official @openclaw/codex package");
237
274
  assertSupportedVersion("version" in pkg ? pkg.version : undefined, "@openclaw/codex");
275
+ const version = String(pkg.version);
238
276
  const dist = join(packageDir, "dist");
239
277
  if (!(await lstat(dist)).isDirectory())
240
278
  throw new Error("Unsupported Codex bundle layout");
@@ -246,77 +284,28 @@ export async function prepareAdapter(agentDir, agentId, suppliedDir, runtimePath
246
284
  if (setup)
247
285
  paths.push(...(await readdir(join(dist, ".setup"))).filter(name => BUNDLE_NAME.test(name)).map(name => join(dist, ".setup", name)));
248
286
  paths.sort();
249
- if (!paths.length || (receipt && receiptFiles(receipt).some(file => !paths.includes(file.path))))
250
- throw new Error("Unsupported Codex bundle layout; restore before changing installations");
251
- const bundles = await Promise.all(paths.map(async (path) => {
252
- const current = await readOptional(path);
253
- if (current === null)
254
- throw new Error("Missing Codex adapter");
255
- const file = receipt && receiptFiles(receipt).find(file => file.path === path);
256
- const original = file ? await readOptional(backupPath(agentDir, file, receipt?.schema === 1)) : current;
257
- if (original === null || (file && sha256(original) !== file.originalSha256))
258
- throw new Error("Codex adapter backup invalid; refusing to patch");
259
- if (file && !ownsSource(file, current))
260
- throw new Error("Codex adapter changed by another writer; refusing to overwrite");
261
- return { path, current, original };
262
- }));
263
- const patches = patchAdapterSources(bundles.map(bundle => bundle.original), agentDir, agentId, runtimePath);
264
- const files = bundles.flatMap((bundle, index) => {
265
- const patched = patches[index];
266
- return patched === bundle.original ? [] : [{ ...bundle, patched }];
267
- });
268
- if (receipt && receiptFiles(receipt).some(previous => !files.some(file => previous.path === file.path)))
269
- throw new Error("Codex adapter path changed; restore before changing installations");
270
- const nextReceipt = { schema: 2, packageDir, files: files.map(file => ({
271
- path: file.path, originalSha256: sha256(file.original), patchedSha256: sha256(file.patched),
272
- // Receipt-first upgrades must remain recoverable if source swapping is interrupted.
273
- ...(file.current !== file.original && file.current !== file.patched ? { previousPatchedSha256: sha256(file.current) } : {}),
274
- })) };
275
- return { files, receipt: nextReceipt, previousReceipt };
287
+ if (!paths.length)
288
+ throw new Error("Unsupported Codex bundle layout");
289
+ const originals = await Promise.all(paths.map(patch.read));
290
+ const patches = patchAdapterSources(originals, agentDir, agentId, runtimePath);
291
+ const { files, entries: receiptEntries, previousReceipt, staleBackups } = patch.finish(new Map(paths.flatMap((path, index) => patches[index] === originals[index] ? [] : [[path, patches[index]]])));
292
+ const receipt = { schema: 2, packageDir, packageVersion: version, files: receiptEntries };
293
+ return { files, receipt, previousReceipt, staleBackups };
276
294
  }
277
295
  export async function installAdapter(agentDir, plan) {
278
- // Validate every target before any bundle changes; retain exact backups for recovery.
279
- const backups = await Promise.all(plan.files.map(async (file) => {
280
- const path = backupPath(agentDir, file);
281
- const backup = await readOptional(path);
282
- if (backup !== null && backup !== file.original)
283
- throw new Error("Foreign adapter backup");
284
- if (await readOptional(file.path) !== file.current)
285
- throw new Error("Concurrent adapter edit; refusing to overwrite");
286
- return { path, backup, original: file.original };
287
- }));
288
- for (const backup of backups)
289
- await replaceFile(backup.path, backup.backup, backup.original);
290
- await replaceFile(receiptPath(agentDir), plan.previousReceipt, JSON.stringify(plan.receipt, null, 2) + "\n");
291
- let adapterChanged = false;
292
- for (const file of plan.files)
293
- adapterChanged = await replaceFile(file.path, file.current, file.patched) || adapterChanged;
294
- return { adapterChanged, restartRequired: true };
296
+ return installPatch(codexFiles(agentDir), plan, JSON.stringify(plan.receipt, null, 2) + "\n");
295
297
  }
296
298
  export async function adapterStatus(agentDir) {
297
- const receipt = await readReceipt(agentDir);
298
- if (!receipt)
299
- return { installed: false };
300
- const files = receiptFiles(receipt);
301
- const installed = (await Promise.all(files.map(async (file) => {
302
- const current = await readOptional(file.path);
303
- return current !== null && sha256(current) === file.patchedSha256;
304
- }))).every(Boolean);
305
- return { installed, path: files[0].path, paths: files.map(file => file.path), minimumVersion: MINIMUM_OPENCLAW };
299
+ const status = await patchedFilesStatus(codexFiles(agentDir));
300
+ if (!status)
301
+ return { installed: false, state: "absent" };
302
+ return { installed: status.installed, state: status.state, path: status.paths[0], paths: status.paths, packageDir: status.recorded.root,
303
+ ...status.recorded.version ? { packageVersion: status.recorded.version } : {}, minimumVersion: MINIMUM_OPENCLAW };
304
+ }
305
+ /** Validates every recorded file before any write; empty unless this adapter's bytes are installed. */
306
+ export async function planAdapterRestore(agentDir) {
307
+ return planPatchedRestore(codexFiles(agentDir));
306
308
  }
307
- export async function restoreAdapter(agentDir) {
308
- const receipt = await readReceipt(agentDir);
309
- if (!receipt)
310
- return;
311
- const files = await Promise.all(receiptFiles(receipt).map(async (file) => {
312
- const current = await readOptional(file.path);
313
- const original = await readOptional(backupPath(agentDir, file, receipt.schema === 1));
314
- if (original === null || sha256(original) !== file.originalSha256)
315
- throw new Error("Adapter backup invalid");
316
- if (!ownsSource(file, current))
317
- throw new Error("Foreign adapter edit; refusing restore");
318
- return { path: file.path, current, original };
319
- }));
320
- for (const file of files)
321
- await replaceFile(file.path, file.current, file.original);
309
+ export async function applyAdapterRestore(plan) {
310
+ return applyPatchedRestore(plan);
322
311
  }
@@ -0,0 +1,32 @@
1
+ import { type RestorePlan } from "./patched-files.js";
2
+ /** "patched" while any recorded core file still holds the 0.4 patch: a leftover to remove. */
3
+ export declare function claudeAdapterOwnership(agentDir: string): Promise<import("./patched-files.js").Ownership>;
4
+ /**
5
+ * Disk state of a 0.4 receipt's files; distinguishes missing (e.g. after an OpenClaw update) from
6
+ * foreign edits. `leftover` is true while any recorded file still holds the 0.4 patch bytes.
7
+ */
8
+ export declare function claudeAdapterStatus(agentDir: string): Promise<{
9
+ installed: boolean;
10
+ leftover: boolean;
11
+ state: "absent";
12
+ openclawRoot?: never;
13
+ openclawVersion?: never;
14
+ paths?: never;
15
+ coreIntegrity?: never;
16
+ } | {
17
+ installed: boolean;
18
+ leftover: boolean;
19
+ state: "changed" | "patched" | "partial" | "original" | "missing";
20
+ openclawRoot: string;
21
+ openclawVersion: string | undefined;
22
+ paths: string[];
23
+ coreIntegrity: string;
24
+ }>;
25
+ /** Validates every recorded chunk and backup before any write; empty unless the 0.4 patch bytes are installed. */
26
+ export declare function planClaudeRestore(agentDir: string): Promise<RestorePlan>;
27
+ export declare function applyClaudeRestore(plan: RestorePlan): Promise<{
28
+ ownership: import("./patched-files.js").Ownership;
29
+ files: string[];
30
+ superseded: string[];
31
+ restartRequired: boolean;
32
+ }>;
@@ -0,0 +1,91 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, isAbsolute, join } from "node:path";
3
+ import { applyPatchedRestore, patchedFilesOwnership, patchedFilesStatus, planPatchedRestore } from "./patched-files.js";
4
+ /**
5
+ * Removal of the 0.4 Claude CLI core patch. 0.4 patched two OpenClaw core functions and kept a
6
+ * receipt with exact-byte backups; 0.5 replaces Claude's prompt through the public
7
+ * before_prompt_build hook and never patches core. Only what restoring a 0.4 install needs
8
+ * remains: the receipt format and the shared patched-file lifecycle's status and restore.
9
+ */
10
+ const HASH = /^[a-f0-9]{64}$/u;
11
+ const CHUNK = /^[\w.-]+\.mjs$/u;
12
+ function receiptPath(agentDir) { return join(agentDir, "codex-home", ".unblock-claude-prompt-adapter.json"); }
13
+ function backupPath(agentDir, path) { return join(agentDir, "codex-home", ".unblock-claude-prompt-adapter-original-" + basename(path)); }
14
+ function parseReceipt(source) {
15
+ const value = JSON.parse(source);
16
+ if (!value || typeof value !== "object" || !("schema" in value) || value.schema !== 1 ||
17
+ !("openclawRoot" in value) || typeof value.openclawRoot !== "string" || !isAbsolute(value.openclawRoot) ||
18
+ !("openclawVersion" in value) || typeof value.openclawVersion !== "string" ||
19
+ !("files" in value) || !Array.isArray(value.files) || !value.files.length)
20
+ throw new Error("Invalid Claude adapter receipt");
21
+ const root = value.openclawRoot;
22
+ const files = value.files.map((entry) => {
23
+ if (!entry || typeof entry !== "object" || !("path" in entry) || typeof entry.path !== "string" ||
24
+ !CHUNK.test(basename(entry.path)) || entry.path !== join(root, "dist", basename(entry.path)) ||
25
+ !("originalSha256" in entry) || typeof entry.originalSha256 !== "string" || !HASH.test(entry.originalSha256) ||
26
+ !("patchedSha256" in entry) || typeof entry.patchedSha256 !== "string" || !HASH.test(entry.patchedSha256))
27
+ throw new Error("Invalid Claude adapter receipt");
28
+ const previous = "previousPatchedSha256" in entry ? entry.previousPatchedSha256 : undefined;
29
+ if (previous !== undefined && (typeof previous !== "string" || !HASH.test(previous)))
30
+ throw new Error("Invalid Claude adapter receipt");
31
+ return { path: entry.path, originalSha256: entry.originalSha256, patchedSha256: entry.patchedSha256, ...previous ? { previousPatchedSha256: previous } : {} };
32
+ });
33
+ if (new Set(files.map(file => file.path)).size !== files.length)
34
+ throw new Error("Invalid Claude adapter receipt");
35
+ return { schema: 1, openclawRoot: root, openclawVersion: value.openclawVersion, files };
36
+ }
37
+ async function openclawVersion(root) {
38
+ const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
39
+ if (!pkg || typeof pkg !== "object" || !("name" in pkg) || pkg.name !== "openclaw" || !("version" in pkg) || typeof pkg.version !== "string")
40
+ throw new Error("Cannot locate the running OpenClaw package");
41
+ return pkg.version;
42
+ }
43
+ /** This agent's 0.4 Claude patched-file set in OpenClaw core: receipt, backups and install identity. */
44
+ function claudeFiles(agentDir) {
45
+ return {
46
+ receiptPath: receiptPath(agentDir),
47
+ parseReceipt(source) {
48
+ const receipt = parseReceipt(source);
49
+ return { root: receipt.openclawRoot, version: receipt.openclawVersion, files: receipt.files, backupPath: file => backupPath(agentDir, file.path) };
50
+ },
51
+ installedVersion: root => openclawVersion(root).catch(() => null),
52
+ backupPath: path => backupPath(agentDir, path),
53
+ messages: {
54
+ // Install-path messages are unreachable: 0.5 never patches OpenClaw core.
55
+ installChanged: "The Claude core patch is no longer installed by this plugin",
56
+ changed: "OpenClaw core changed by another writer",
57
+ missing: "Missing OpenClaw Claude assembly chunk",
58
+ prepareBackupInvalid: "Claude adapter backup invalid",
59
+ moved: "OpenClaw Claude assembly moved",
60
+ foreignBackup: "Foreign Claude adapter backup",
61
+ concurrent: "Concurrent OpenClaw core edit; refusing to overwrite",
62
+ foreignEdit: "Foreign OpenClaw core edit; refusing restore",
63
+ backupInvalid: "Claude adapter backup invalid",
64
+ },
65
+ };
66
+ }
67
+ /** "patched" while any recorded core file still holds the 0.4 patch: a leftover to remove. */
68
+ export async function claudeAdapterOwnership(agentDir) {
69
+ return patchedFilesOwnership(claudeFiles(agentDir));
70
+ }
71
+ /**
72
+ * Disk state of a 0.4 receipt's files; distinguishes missing (e.g. after an OpenClaw update) from
73
+ * foreign edits. `leftover` is true while any recorded file still holds the 0.4 patch bytes.
74
+ */
75
+ export async function claudeAdapterStatus(agentDir) {
76
+ const set = claudeFiles(agentDir);
77
+ const status = await patchedFilesStatus(set);
78
+ if (!status)
79
+ return { installed: false, leftover: false, state: "absent" };
80
+ const leftover = await patchedFilesOwnership(set) === "patched";
81
+ return { installed: status.installed, leftover, state: status.state, openclawRoot: status.recorded.root, openclawVersion: status.recorded.version, paths: status.paths,
82
+ coreIntegrity: leftover ? "modified: run codex-prompt sync or restore to remove the 0.4 Claude core patch, then restart the Gateway"
83
+ : status.state === "original" ? "unmodified" : "no 0.4 patch bytes remain; the recorded files were updated or changed by another writer" };
84
+ }
85
+ /** Validates every recorded chunk and backup before any write; empty unless the 0.4 patch bytes are installed. */
86
+ export async function planClaudeRestore(agentDir) {
87
+ return planPatchedRestore(claudeFiles(agentDir));
88
+ }
89
+ export async function applyClaudeRestore(plan) {
90
+ return applyPatchedRestore(plan);
91
+ }
@@ -0,0 +1,36 @@
1
+ import type { ClaudeManagedContext } from "./runtime.js";
2
+ /**
3
+ * The agent workspace files the Claude CLI prompt carries, in prompt order: OpenClaw's own
4
+ * workspace bootstrap set (`WORKSPACE_BOOTSTRAP_FILENAMES`) without MEMORY.md, whose body stays out
5
+ * of the prompt while the memory reference points to it. BOOTSTRAP.md is included only where
6
+ * OpenClaw would include it: primary interactive runs (see `includeBootstrap`).
7
+ */
8
+ export declare const CLAUDE_WORKSPACE_FILES: readonly ["AGENTS.md", "SOUL.md", "IDENTITY.md", "USER.md", "BOOTSTRAP.md"];
9
+ /** OpenClaw's bootstrap defaults (2026.10.6 and 2026.10.9 `bootstrap-*.mjs`). */
10
+ export declare const DEFAULT_BOOTSTRAP_MAX_CHARS = 20000;
11
+ export declare const DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS = 60000;
12
+ export declare const USER_BOOTSTRAP_MAX_CHARS = 4000;
13
+ /** OpenClaw shows BOOTSTRAP.md only on primary user/manual runs, never to subagents, heartbeats or cron. */
14
+ export declare function includeBootstrap(ctx: {
15
+ trigger?: unknown;
16
+ sessionKey?: unknown;
17
+ }): boolean;
18
+ export declare function bootstrapMaxChars(config: unknown, agentId: string): number;
19
+ /** OpenClaw's total budget across all workspace files (default 60000). */
20
+ export declare function bootstrapTotalMaxChars(config: unknown, agentId: string): number;
21
+ export type SkippedFile = {
22
+ path: string;
23
+ reason: string;
24
+ };
25
+ /**
26
+ * The complete Claude CLI system prompt for the managed agent: the Claude policy, the memory
27
+ * reference, then each present, non-empty workspace file under its absolute path. Files are read
28
+ * on every call, so an edit applies to the next turn. Nothing else is added.
29
+ */
30
+ export declare function buildClaudeSystemPrompt(managed: ClaudeManagedContext, workspaceDir: string, maxChars: number, options?: {
31
+ totalMaxChars?: number;
32
+ includeBootstrap?: boolean;
33
+ }): Promise<{
34
+ systemPrompt: string;
35
+ skipped: SkippedFile[];
36
+ }>;