@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.
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,21 +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
- function unblockFrozenPolicy(params) {
76
- const plugins = params.config?.plugins;
77
- const entry = plugins?.entries?.["unblock-codex-prompt"];
78
- if (plugins?.enabled === false || entry?.enabled !== true || entry.config?.frozenContext !== true ||
79
- (Array.isArray(plugins.allow) && !plugins.allow.includes("unblock-codex-prompt"))) return null;
80
- const target = entry.config?.agentId ?? "main";
81
- if (params.agentId !== target) return null;
82
- if (target !== ${JSON.stringify(agentId)}) throw new Error("Frozen bridge target changed; restore and reinstall the adapter");
108
+ function unblockNormalizeAdditions(text) { return unblockPromptRequire(${JSON.stringify(runtimePath)}).normalizeOpenClawAdditions(text); }
109
+ function unblockNormalizeTurnContext(context) { return unblockPromptRequire(${JSON.stringify(runtimePath)}).normalizeOpenClawTurnContext(context); }
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;
83
126
  return unblockPromptRequire(${JSON.stringify(runtimePath)}).readFrozenPolicy(${JSON.stringify(agentDir)});
84
127
  }
85
128
  `;
@@ -95,48 +138,13 @@ export function patchAdapterSources(sources, agentDir, agentId, runtimePath) {
95
138
  throw new Error("Unsupported Codex adapter shape: " + name);
96
139
  return matches[0];
97
140
  };
98
- // 2026.9.9 has the workspace producer but still uses the legacy carriers.
99
- if (!functions.some(fn => fn.node.id?.name === "buildTurnScopedCollaborationInstructions") &&
100
- functions.some(fn => fn.node.id?.name === "buildCodexWorkspaceBootstrapContext")) {
101
- return patchRefreshableAdapter(sources, find, bridgePrefix(agentDir, agentId, runtimePath));
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}`);
102
145
  }
103
- const developer = find("buildDeveloperInstructions");
104
- const collaboration = find("buildTurnScopedCollaborationInstructions");
105
- const parent = functions.some(fn => fn.node.id?.name === "buildCodexParentLocalInstructions") ? find("buildCodexParentLocalInstructions") : null;
106
- const thread = functions.some(fn => fn.node.id?.name === "buildCodexThreadConfiguration") ? find("buildCodexThreadConfiguration") : null;
107
- for (const { node, bundle } of [developer, collaboration, ...(parent ? [parent] : []), ...(thread ? [thread] : [])]) {
108
- if (node.async || node.generator || node.params.length !== 2 || node.params[0]?.type !== "Identifier" || node.params[0].name !== "params" ||
109
- !/^(options|options\s*=\s*\{\})$/u.test(sources[bundle].slice(node.params[1].start, node.params[1].end)))
110
- throw new Error("Unsupported Codex adapter shape: parameters");
111
- }
112
- for (const name of ["buildDefaultCollaborationInstructions", "buildCronCollaborationInstructions"]) {
113
- const helper = find(name);
114
- if (helper.node.params.length !== 0 || helper.bundle !== collaboration.bundle)
115
- throw new Error("Unsupported Codex adapter shape: mode helpers");
116
- }
117
- const fingerprint = (fn) => sha256(sources[fn.bundle].slice(fn.node.start, fn.node.end));
118
- const split = parent !== null && fingerprint(parent) === CONTEXT_HASHES.splitParent;
119
- if (fingerprint(collaboration) !== (parent ? CONTEXT_HASHES.collaboration : CONTEXT_HASHES.legacy) ||
120
- (parent && (parent.bundle !== collaboration.bundle || ![CONTEXT_HASHES.parent, CONTEXT_HASHES.splitParent].includes(fingerprint(parent)))) ||
121
- (thread && thread.bundle !== developer.bundle) ||
122
- (split ? !thread || fingerprint(thread) !== CONTEXT_HASHES.thread : thread !== null && fingerprint(thread) !== CONTEXT_HASHES.legacyThread))
123
- throw new Error("Unsupported Codex context assembly; review the changed upstream functions before syncing");
124
146
  const prefix = bridgePrefix(agentDir, agentId, runtimePath);
125
- const insertions = [
126
- { fn: developer, text: '\n\tconst unblockPolicy = unblockFrozenPolicy(params);\n\tif (unblockPolicy !== null) return [unblockPolicy, params.gitCoauthorPrompt, params.extraSystemPrompt].filter(section => typeof section === "string" && section.trim()).join("\\n\\n");' },
127
- { fn: collaboration, text: '\n\tif (unblockFrozenPolicy(params) !== null) return params.trigger === "cron" ? buildCronCollaborationInstructions() : buildDefaultCollaborationInstructions();' },
128
- ...(parent ? [{ fn: parent, text: '\n\tif (unblockFrozenPolicy(params) !== null) return params.trigger === "cron" ? buildCronCollaborationInstructions() : null;' }] : []),
129
- // 2026.9.8 moved skills to the start/resume/fork carrier, outside developer policy.
130
- ...(split && thread ? [{ fn: thread, text: '\n\tif (unblockFrozenPolicy(params) !== null) options = { ...options, skillsInstructions: undefined };' }] : []),
131
- ];
132
- return sources.map((source, bundle) => {
133
- const edits = insertions.filter(edit => edit.fn.bundle === bundle).sort((a, b) => b.fn.node.body.start - a.fn.node.body.start);
134
- for (const { fn, text } of edits) {
135
- const at = fn.node.body.start + 1;
136
- source = source.slice(0, at) + text + source.slice(at);
137
- }
138
- return edits.length ? prefix + source : source;
139
- });
147
+ return patchOperationalAdapter(patchRefreshableAdapter(sources, find, prefix), prefix);
140
148
  }
141
149
  function patchRefreshableAdapter(sources, find, prefix) {
142
150
  for (const [name, expected] of Object.entries(REFRESHABLE_CONTEXT_HASHES)) {
@@ -148,22 +156,54 @@ function patchRefreshableAdapter(sources, find, prefix) {
148
156
  const developer = find("buildDeveloperInstructions");
149
157
  const skills = find("renderCodexSkillsInstructions");
150
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
+ `;
151
172
  const originalWorkspace = sources[workspace.bundle].slice(workspace.node.start, workspace.node.end)
152
173
  .replace("async function buildCodexWorkspaceBootstrapContext", "async function unblockOriginalWorkspaceContext");
153
- // Suppress at the producers: initial, warm, fork, parent-local and post-compaction
154
- // 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
+ `;
155
193
  const wrapper = `async function buildCodexWorkspaceBootstrapContext(params) {
156
194
  const policy = unblockFrozenPolicy(params.params);
157
195
  const context = await unblockOriginalWorkspaceContext(params);
158
- 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 };
159
199
  }
160
200
  `;
161
201
  const edits = [
162
202
  { bundle: developer.bundle, start: developer.node.body.start + 1, end: developer.node.body.start + 1,
163
- text: '\n\tconst unblockPolicy = unblockFrozenPolicy(params);\n\tif (unblockPolicy !== null) return [unblockPolicy, params.gitCoauthorPrompt, params.extraSystemPrompt].filter(section => typeof section === "string" && section.trim()).join("\\n\\n");' },
164
- { bundle: skills.bundle, start: skills.node.body.start + 1, end: skills.node.body.start + 1,
165
- 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 },
166
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 },
167
207
  ];
168
208
  return sources.map((source, bundle) => {
169
209
  const selected = edits.filter(edit => edit.bundle === bundle).sort((a, b) => b.start - a.start);
@@ -172,21 +212,67 @@ function patchRefreshableAdapter(sources, find, prefix) {
172
212
  return selected.length ? prefix + source : source;
173
213
  });
174
214
  }
215
+ const OPERATIONAL_HASHES = {
216
+ buildTurnStartParams: "166c4d2ca9873f5ced180475487775c2965583aa1ff087e599321fcb408fd053",
217
+ buildCodexTemporalAdditionalContext: "7b546f0ad79ce26d856f8645bfd5b232f1fdfce699dfe2e84c24fe5f61401094",
218
+ resumeExistingCodexThread: "1b8d4038ee162b276095d9f3e1ad771f33c7cd794c47fb5088783dae9e7c1494",
219
+ refreshCodexThreadPolicy: "69d6e9903896c77e71542957dbadddaca5d3cbb4d7cd56b8ff0de2a5ca42b995",
220
+ };
221
+ function patchOperationalAdapter(sources, prefix) {
222
+ const functionsByBundle = sources.map(source => parse(source, { ecmaVersion: "latest", sourceType: "module" }).body
223
+ .filter(node => node.type === "FunctionDeclaration"));
224
+ const names = functionsByBundle.flat().map(node => node.id?.name);
225
+ const required = Object.keys(OPERATIONAL_HASHES);
226
+ if (required.some(name => names.includes(name)) && required.some(name => names.filter(found => found === name).length !== 1)) {
227
+ throw new Error("Unsupported Codex operational context: missing or duplicate carrier; review before syncing");
228
+ }
229
+ return sources.map((source, bundle) => {
230
+ const functions = functionsByBundle[bundle];
231
+ const edits = [];
232
+ for (const [name, hash] of Object.entries(OPERATIONAL_HASHES)) {
233
+ const matches = functions.filter(node => node.id?.name === name);
234
+ if (!matches.length)
235
+ continue; // Older carriers have no per-turn additional context.
236
+ const node = matches[0];
237
+ const original = source.slice(node.start, node.end);
238
+ if (matches.length !== 1 || sha256(original) !== hash)
239
+ throw new Error("Unsupported Codex operational context: " + name + "; review before syncing");
240
+ let replacement;
241
+ if (name === "resumeExistingCodexThread") {
242
+ replacement = original.replace("await refreshCodexThreadPolicy({", "await refreshCodexThreadPolicy({\n\t\t\tunblockManaged: unblockFrozenPolicy(params.params) !== null,");
243
+ }
244
+ else if (name === "refreshCodexThreadPolicy") {
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');
246
+ }
247
+ else {
248
+ const originalName = "unblockOriginal" + name;
249
+ const value = name === "buildTurnStartParams" ? "result.additionalContext" : "result";
250
+ const normalized = name === "buildTurnStartParams" ? "{ ...result, additionalContext: unblockNormalizeTurnContext(result.additionalContext) }" : "unblockNormalizeTurnContext(result)";
251
+ replacement = `function ${name}(params, options) {\n const managed = unblockFrozenPolicy(params) !== null;\n const result = ${originalName}(params, options);\n return managed && ${value} ? ${normalized} : result;\n}\n` + original.replace(`function ${name}(`, `function ${originalName}(`);
252
+ }
253
+ edits.push({ start: node.start, end: node.end, text: replacement });
254
+ }
255
+ for (const edit of edits.sort((a, b) => b.start - a.start))
256
+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);
257
+ return edits.length && !source.includes(MARKER) ? prefix + source : source;
258
+ });
259
+ }
175
260
  export async function prepareAdapter(agentDir, agentId, suppliedDir, runtimePath) {
176
261
  await openclawRoot();
177
262
  if (!isAbsolute(runtimePath) || await readOptional(runtimePath) === null)
178
263
  throw new Error("Missing durable plugin runtime");
179
- const previousReceipt = await readOptional(receiptPath(agentDir));
180
- const receipt = parseReceipt(previousReceipt);
181
- 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;
182
268
  if (!packageDir)
183
269
  throw new Error("First frozen sync requires --codex-plugin-dir from openclaw plugins inspect codex --json");
184
- if (receipt && receipt.packageDir !== packageDir)
185
- throw new Error("Restore the previous adapter before changing Codex installations");
270
+ const patch = await beginPatch(set, opened, packageDir);
186
271
  const pkg = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8"));
187
272
  if (!pkg || typeof pkg !== "object" || !("name" in pkg) || pkg.name !== "@openclaw/codex")
188
273
  throw new Error("Expected the official @openclaw/codex package");
189
274
  assertSupportedVersion("version" in pkg ? pkg.version : undefined, "@openclaw/codex");
275
+ const version = String(pkg.version);
190
276
  const dist = join(packageDir, "dist");
191
277
  if (!(await lstat(dist)).isDirectory())
192
278
  throw new Error("Unsupported Codex bundle layout");
@@ -198,77 +284,28 @@ export async function prepareAdapter(agentDir, agentId, suppliedDir, runtimePath
198
284
  if (setup)
199
285
  paths.push(...(await readdir(join(dist, ".setup"))).filter(name => BUNDLE_NAME.test(name)).map(name => join(dist, ".setup", name)));
200
286
  paths.sort();
201
- if (!paths.length || (receipt && receiptFiles(receipt).some(file => !paths.includes(file.path))))
202
- throw new Error("Unsupported Codex bundle layout; restore before changing installations");
203
- const bundles = await Promise.all(paths.map(async (path) => {
204
- const current = await readOptional(path);
205
- if (current === null)
206
- throw new Error("Missing Codex adapter");
207
- const file = receipt && receiptFiles(receipt).find(file => file.path === path);
208
- const original = file ? await readOptional(backupPath(agentDir, file, receipt?.schema === 1)) : current;
209
- if (original === null || (file && sha256(original) !== file.originalSha256))
210
- throw new Error("Codex adapter backup invalid; refusing to patch");
211
- if (file && !ownsSource(file, current))
212
- throw new Error("Codex adapter changed by another writer; refusing to overwrite");
213
- return { path, current, original };
214
- }));
215
- const patches = patchAdapterSources(bundles.map(bundle => bundle.original), agentDir, agentId, runtimePath);
216
- const files = bundles.flatMap((bundle, index) => {
217
- const patched = patches[index];
218
- return patched === bundle.original ? [] : [{ ...bundle, patched }];
219
- });
220
- if (receipt && (files.length !== receiptFiles(receipt).length || files.some(file => !receiptFiles(receipt).some(previous => previous.path === file.path))))
221
- throw new Error("Codex adapter path changed; restore before changing installations");
222
- const nextReceipt = { schema: 2, packageDir, files: files.map(file => ({
223
- path: file.path, originalSha256: sha256(file.original), patchedSha256: sha256(file.patched),
224
- // Receipt-first upgrades must remain recoverable if source swapping is interrupted.
225
- ...(file.current !== file.original && file.current !== file.patched ? { previousPatchedSha256: sha256(file.current) } : {}),
226
- })) };
227
- 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 };
228
294
  }
229
295
  export async function installAdapter(agentDir, plan) {
230
- // Validate every target before any bundle changes; retain exact backups for recovery.
231
- const backups = await Promise.all(plan.files.map(async (file) => {
232
- const path = backupPath(agentDir, file);
233
- const backup = await readOptional(path);
234
- if (backup !== null && backup !== file.original)
235
- throw new Error("Foreign adapter backup");
236
- if (await readOptional(file.path) !== file.current)
237
- throw new Error("Concurrent adapter edit; refusing to overwrite");
238
- return { path, backup, original: file.original };
239
- }));
240
- for (const backup of backups)
241
- await replaceFile(backup.path, backup.backup, backup.original);
242
- await replaceFile(receiptPath(agentDir), plan.previousReceipt, JSON.stringify(plan.receipt, null, 2) + "\n");
243
- let adapterChanged = false;
244
- for (const file of plan.files)
245
- adapterChanged = await replaceFile(file.path, file.current, file.patched) || adapterChanged;
246
- return { adapterChanged, restartRequired: true };
296
+ return installPatch(codexFiles(agentDir), plan, JSON.stringify(plan.receipt, null, 2) + "\n");
247
297
  }
248
298
  export async function adapterStatus(agentDir) {
249
- const receipt = await readReceipt(agentDir);
250
- if (!receipt)
251
- return { installed: false };
252
- const files = receiptFiles(receipt);
253
- const installed = (await Promise.all(files.map(async (file) => {
254
- const current = await readOptional(file.path);
255
- return current !== null && sha256(current) === file.patchedSha256;
256
- }))).every(Boolean);
257
- 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));
258
308
  }
259
- export async function restoreAdapter(agentDir) {
260
- const receipt = await readReceipt(agentDir);
261
- if (!receipt)
262
- return;
263
- const files = await Promise.all(receiptFiles(receipt).map(async (file) => {
264
- const current = await readOptional(file.path);
265
- const original = await readOptional(backupPath(agentDir, file, receipt.schema === 1));
266
- if (original === null || sha256(original) !== file.originalSha256)
267
- throw new Error("Adapter backup invalid");
268
- if (!ownsSource(file, current))
269
- throw new Error("Foreign adapter edit; refusing restore");
270
- return { path: file.path, current, original };
271
- }));
272
- for (const file of files)
273
- await replaceFile(file.path, file.current, file.original);
309
+ export async function applyAdapterRestore(plan) {
310
+ return applyPatchedRestore(plan);
274
311
  }
package/dist/catalog.d.ts CHANGED
@@ -2,10 +2,23 @@ export declare const CATALOG_REFRESH_MS: number;
2
2
  export declare function patchCatalog(value: unknown): {
3
3
  models: {
4
4
  model_messages: {
5
+ collaboration_modes: {
6
+ default: string;
7
+ };
5
8
  multi_agent: {
6
9
  mode: {
7
10
  explicit: string;
8
11
  };
12
+ role: {
13
+ root: string;
14
+ subagent: string;
15
+ };
16
+ };
17
+ permissions: {
18
+ danger_full_access: string;
19
+ };
20
+ approvals: {
21
+ never: string;
9
22
  };
10
23
  };
11
24
  }[];
@@ -48,4 +61,4 @@ export declare function refreshCatalog(agentDir: string, options?: {
48
61
  }>;
49
62
  export declare function restoreCatalog(agentDir: string): Promise<void>;
50
63
  /** Start promptly if overdue, persist successful refresh time, retry failures hourly. */
51
- export declare function startCatalogRefresh(run: () => Promise<void>, nextAt: number, onError: () => void): () => Promise<void>;
64
+ export declare function startCatalogRefresh(run: () => Promise<void>, nextAt: number, onError: (error: unknown, retryAt: number) => void): () => Promise<void>;
package/dist/catalog.js CHANGED
@@ -41,7 +41,21 @@ export function patchCatalog(value) {
41
41
  const mode = multi.mode ?? {};
42
42
  if (!record(mode))
43
43
  throw new Error("Invalid multi_agent mode metadata");
44
- return { ...model, model_messages: { ...messages, multi_agent: { ...multi, mode: { ...mode, explicit: "" } } } };
44
+ const role = multi.role ?? {};
45
+ const collaboration = messages.collaboration_modes ?? {};
46
+ const permissions = messages.permissions ?? {};
47
+ const approvals = messages.approvals ?? {};
48
+ if (![role, collaboration, permissions, approvals].every(record))
49
+ throw new Error("Invalid model message metadata");
50
+ return { ...model, model_messages: { ...messages,
51
+ collaboration_modes: { ...collaboration, default: "" },
52
+ multi_agent: { ...multi, mode: { ...mode, explicit: "" }, role: { ...role,
53
+ root: "You are `/root`, the primary agent.",
54
+ subagent: "You are a child agent. Your final response is delivered to your parent. Your task address identifies you.",
55
+ } },
56
+ permissions: { ...permissions, danger_full_access: "Native execution: filesystem unrestricted; network {{ network_access }}." },
57
+ approvals: { ...approvals, never: "Approval escalation unavailable; omit sandbox_permissions." },
58
+ } };
45
59
  });
46
60
  return { ...value, models };
47
61
  }
@@ -170,9 +184,9 @@ export function startCatalogRefresh(run, nextAt, onError) {
170
184
  try {
171
185
  await run();
172
186
  }
173
- catch {
174
- onError();
187
+ catch (error) {
175
188
  next = 60 * 60 * 1000;
189
+ onError(error, Date.now() + next);
176
190
  }
177
191
  if (!stopped)
178
192
  schedule(next);
@@ -0,0 +1,63 @@
1
+ import { type FunctionDeclaration, type Program } from "acorn";
2
+ import { type PatchedFile, type RestorePlan } from "./patched-files.js";
3
+ export declare const CLAUDE_ASSEMBLY_HASHES: {
4
+ readonly buildCliAgentSystemPrompt: "6b21cdba8192074f8014243b8f8588bdcf51f8dada2f52f61c1787c7d3a60eb3";
5
+ readonly buildConfiguredAgentSystemPrompt: "9f5a1c2923678008d7f276f7fc3af62af4e1cef8c5cc7678fcfe665d036e154a";
6
+ readonly buildAgentSystemPrompt: "c81eb1a28a58a943bc17cec18459a2080ebf411a92811dc61b868d574312aa86";
7
+ };
8
+ type Role = keyof typeof CLAUDE_ASSEMBLY_HASHES;
9
+ type Located = {
10
+ role: Role;
11
+ path: string;
12
+ node: FunctionDeclaration;
13
+ program: Program;
14
+ };
15
+ type Receipt = {
16
+ schema: 1;
17
+ openclawRoot: string;
18
+ openclawVersion: string;
19
+ files: PatchedFile[];
20
+ };
21
+ export declare function claudeAdapterOwnership(agentDir: string): Promise<import("./patched-files.js").Ownership>;
22
+ /** Pure patch over original sources keyed by path; fingerprints are checked first. */
23
+ export declare function patchClaudeAssembly(sources: Map<string, string>, located: Located[], agentDir: string, agentId: string, runtimePath: string): Map<string, string>;
24
+ /** Locate the selected assembly chain from its single definition, following imports. */
25
+ export declare function locateClaudeAssembly(root: string, read: (path: string) => Promise<string>): Promise<{
26
+ sources: Map<string, string>;
27
+ located: Located[];
28
+ }>;
29
+ export declare function prepareClaudeAdapter(agentDir: string, agentId: string, runtimePath: string, root?: string): Promise<{
30
+ files: import("./patched-files.js").PreparedFile[];
31
+ receipt: Receipt;
32
+ previousReceipt: string | null;
33
+ staleBackups: Set<string>;
34
+ }>;
35
+ export declare function installClaudeAdapter(agentDir: string, plan: Awaited<ReturnType<typeof prepareClaudeAdapter>>): Promise<{
36
+ adapterChanged: boolean;
37
+ restartRequired: boolean;
38
+ }>;
39
+ /** Disk state: distinguishes missing (e.g. after an OpenClaw update) from foreign edits. */
40
+ export declare function claudeAdapterStatus(agentDir: string): Promise<{
41
+ installed: boolean;
42
+ state: "absent";
43
+ openclawRoot?: never;
44
+ openclawVersion?: never;
45
+ paths?: never;
46
+ coreIntegrity?: never;
47
+ } | {
48
+ installed: boolean;
49
+ state: "changed" | "patched" | "partial" | "original" | "missing";
50
+ openclawRoot: string;
51
+ openclawVersion: string | undefined;
52
+ paths: string[];
53
+ coreIntegrity: string;
54
+ }>;
55
+ /** Validates every recorded chunk before any write; empty unless this adapter's bytes are installed. */
56
+ export declare function planClaudeRestore(agentDir: string): Promise<RestorePlan>;
57
+ export declare function applyClaudeRestore(plan: RestorePlan): Promise<{
58
+ ownership: import("./patched-files.js").Ownership;
59
+ files: string[];
60
+ superseded: string[];
61
+ restartRequired: boolean;
62
+ }>;
63
+ export {};