@unblocklabs/unblock-codex-prompt 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -2,7 +2,23 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { readPromptPointer, setPromptPointer } from "./toml.js";
5
- export const FROZEN_CONTEXT_HEADER = "\n\n## Frozen agent context\n";
5
+ export const RUNTIMES = ["codex", "claude-cli"];
6
+ /** First heading of the agent context, the boundary after the shared policy prefix. */
7
+ export const MEMORY_REFERENCE_HEADER = "\n\n## Memory reference\n";
8
+ /**
9
+ * Accepted boundaries: the current first heading, then the 0.4 branch builds' `## Agent context`
10
+ * and the 0.3 `## Frozen agent context`, so their prompt files still refresh in place.
11
+ */
12
+ export const CONTEXT_BOUNDARY_HEADERS = [MEMORY_REFERENCE_HEADER, "\n\n## Agent context\n", "\n\n## Frozen agent context\n"];
13
+ function record(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
14
+ /** Strict shape check for a stored Claude policy; throws on anything else. */
15
+ export function parseClaudePolicy(value) {
16
+ if (!record(value) || typeof value.text !== "string" || !value.text.trim() || typeof value.url !== "string" || !value.url ||
17
+ typeof value.revision !== "string" || !value.revision || typeof value.checkedAt !== "number" || !Number.isFinite(value.checkedAt)) {
18
+ throw new Error("Claude policy missing or invalid; run codex-prompt sync");
19
+ }
20
+ return { text: value.text, url: value.url, revision: value.revision, checkedAt: value.checkedAt };
21
+ }
6
22
  function paths(target) {
7
23
  const home = join(resolve(target.agentDir), "codex-home");
8
24
  return {
@@ -43,7 +59,7 @@ export async function readOptional(path) {
43
59
  throw new Error(`Refusing non-regular, linked, or shared file: ${path}`);
44
60
  return readFile(path, "utf8");
45
61
  }
46
- function parseEnrollment(source) {
62
+ export function parseEnrollment(source) {
47
63
  if (source === null)
48
64
  return null;
49
65
  let value;
@@ -53,12 +69,34 @@ function parseEnrollment(source) {
53
69
  catch {
54
70
  throw new Error("Invalid prompt enrollment state");
55
71
  }
56
- if (!value || typeof value !== "object" || !("schema" in value) || value.schema !== 1 ||
72
+ if (!value || typeof value !== "object" || !("schema" in value) || (value.schema !== 1 && value.schema !== 2) ||
57
73
  !("active" in value) || typeof value.active !== "boolean" || !("previousPointer" in value) ||
58
74
  (value.previousPointer !== null && typeof value.previousPointer !== "string")) {
59
75
  throw new Error("Invalid prompt enrollment state");
60
76
  }
61
- return { schema: 1, active: value.active, previousPointer: value.previousPointer };
77
+ // Schema 1 without runtimes is the pre-0.4 Codex enrollment.
78
+ if (value.schema === 1 && !("runtimes" in value))
79
+ return { active: value.active, previousPointer: value.previousPointer, runtimes: ["codex"] };
80
+ const runtimes = "runtimes" in value ? value.runtimes : undefined;
81
+ if (!Array.isArray(runtimes) || !runtimes.length || new Set(runtimes).size !== runtimes.length ||
82
+ runtimes.some(runtime => !RUNTIMES.includes(runtime)))
83
+ throw new Error("Invalid prompt enrollment state");
84
+ return { active: value.active, previousPointer: value.previousPointer, runtimes: sortRuntimes(runtimes) };
85
+ }
86
+ function sortRuntimes(runtimes) { return RUNTIMES.filter(runtime => runtimes.includes(runtime)); }
87
+ /**
88
+ * Schema 1 is the format 0.3.x reads (it checks only schema, active and previousPointer).
89
+ * Every state 0.3.x can safely act on uses it: Codex enrollments (with Claude too, 0.3.x keeps
90
+ * managing Codex while the feature-detected Claude patch falls back upstream) and paused ones.
91
+ * Active Claude-only enrollment is schema 2, which 0.3.x refuses rather than mismanaging it.
92
+ * Codex-only enrollment omits runtimes: exactly the 0.3.x shape.
93
+ */
94
+ export function serializeEnrollment(enrollment) {
95
+ const runtimes = sortRuntimes(enrollment.runtimes);
96
+ const codexOnly = runtimes.length === 1 && runtimes[0] === "codex";
97
+ const value = { schema: enrollment.active && !runtimes.includes("codex") ? 2 : 1, active: enrollment.active,
98
+ previousPointer: enrollment.previousPointer, ...codexOnly ? {} : { runtimes } };
99
+ return `${JSON.stringify(value, null, 2)}\n`;
62
100
  }
63
101
  async function snapshot(target) {
64
102
  const files = paths(target);
@@ -66,20 +104,27 @@ async function snapshot(target) {
66
104
  const [config, prompt, state] = await Promise.all([
67
105
  readOptional(files.config), readOptional(files.prompt), readOptional(files.state),
68
106
  ]);
69
- return { files, config, prompt, state, pointer: readPromptPointer(config ?? ""), enrollment: parseEnrollment(state) };
107
+ const enrollment = parseEnrollment(state);
108
+ // Claude-only enrollment never parses or edits Codex configuration.
109
+ const pointer = () => readPromptPointer(config ?? "");
110
+ return { files, config, prompt, state, pointer, enrollment };
111
+ }
112
+ /** Disk-only enrollment for callers that select runtime components. */
113
+ export async function readEnrollment(agentDir) {
114
+ return (await snapshot({ agentDir, prompt: "" })).enrollment;
70
115
  }
71
116
  export function sha256(text) { return createHash("sha256").update(text).digest("hex"); }
72
- /** Disk state only: this cannot attest to instructions retained by a live Codex thread. */
117
+ /** Disk state only: this cannot attest to instructions retained by a live Codex thread or Claude process. */
73
118
  export async function promptStatus(target) {
74
119
  const s = await snapshot(target);
120
+ const codex = s.enrollment?.runtimes.includes("codex") ?? true;
75
121
  return {
76
122
  enrolled: s.enrollment?.active === true,
77
123
  restored: s.enrollment?.active === false,
124
+ runtimes: s.enrollment?.runtimes ?? [],
78
125
  configPath: s.files.config,
79
126
  promptPath: s.files.prompt,
80
- pointerMatches: s.pointer === s.files.prompt,
81
- promptMatches: s.prompt === target.prompt,
82
- expectedSha256: sha256(target.prompt),
127
+ pointerMatches: codex ? s.pointer() === s.files.prompt : null,
83
128
  actualSha256: s.prompt === null ? null : sha256(s.prompt),
84
129
  runtimeVerified: false,
85
130
  };
@@ -126,31 +171,45 @@ export async function withLock(target, operation) {
126
171
  await rmdir(files.lock);
127
172
  }
128
173
  }
174
+ export const ACTIVATION = {
175
+ codex: "Restart the managed app-server and use a new Codex session; existing threads may retain old instructions.",
176
+ "claude-cli": "Restart the Gateway to load the patched OpenClaw core. The next Claude CLI process receives the managed prompt; it may resume the existing conversation, whose earlier history is not cleaned.",
177
+ };
129
178
  export async function syncPrompt(target, options = {}) {
130
179
  if (!target.prompt.trim())
131
180
  throw new Error("Refusing an empty base prompt");
181
+ const requested = sortRuntimes(options.runtimes ?? ["codex"]);
182
+ if (!requested.length)
183
+ throw new Error("Select at least one managed runtime");
132
184
  // Reject invalid state before creating even the lock directory.
133
185
  await snapshot(target);
134
186
  return withLock(target, async () => {
135
187
  const s = await snapshot(target);
136
188
  if (s.enrollment?.active === false && options.automatic)
137
189
  return { changed: false, restored: true };
138
- if (s.pointer !== null && s.pointer !== s.files.prompt && !options.adopt) {
190
+ const current = s.enrollment?.active ? s.enrollment : null;
191
+ // Sync adds components; removing one requires restore so its owned edits are reverted.
192
+ const runtimes = sortRuntimes([...current?.runtimes ?? [], ...requested]);
193
+ const codex = runtimes.includes("codex");
194
+ const pointer = codex ? s.pointer() : null;
195
+ const addingCodex = codex && !current?.runtimes.includes("codex");
196
+ if (codex && pointer !== null && pointer !== s.files.prompt && !options.adopt) {
139
197
  throw new Error("A different model_instructions_file is configured. Review it, then run openclaw codex-prompt sync --adopt to take ownership.");
140
198
  }
141
- if (!s.enrollment && (s.prompt !== null || s.pointer === s.files.prompt)) {
199
+ if (!s.enrollment && (s.prompt !== null || pointer === s.files.prompt)) {
142
200
  throw new Error("Managed prompt exists without enrollment state; recover the state before syncing");
143
201
  }
144
- const enrollment = s.enrollment?.active ? s.enrollment : {
145
- schema: 1, active: true, previousPointer: s.pointer,
202
+ const enrollment = {
203
+ active: true, runtimes,
204
+ previousPointer: addingCodex ? pointer : current?.previousPointer ?? null,
146
205
  };
147
- const nextConfig = setPromptPointer(s.config ?? "", s.files.prompt);
148
206
  // Save rollback information first; point Codex at the file only after it exists.
149
- const stateChanged = await replaceFile(s.files.state, s.state, `${JSON.stringify(enrollment, null, 2)}\n`);
207
+ const stateChanged = await replaceFile(s.files.state, s.state, serializeEnrollment(enrollment));
150
208
  const promptChanged = await replaceFile(s.files.prompt, s.prompt, target.prompt);
151
209
  const bundleChanged = target.bundle ? await replaceFile(s.files.bundle, await readOptional(s.files.bundle), `${JSON.stringify({ ...target.bundle, promptSha256: sha256(target.prompt) }, null, 2)}\n`) : false;
152
- const configChanged = await replaceFile(s.files.config, s.config, nextConfig);
153
- return { changed: stateChanged || promptChanged || configChanged || bundleChanged, promptChanged, configChanged, sha256: sha256(target.prompt), activation: "Restart the managed app-server and use a new Codex session; existing threads may retain old instructions." };
210
+ const configChanged = codex ? await replaceFile(s.files.config, s.config, setPromptPointer(s.config ?? "", s.files.prompt)) : false;
211
+ return { changed: stateChanged || promptChanged || configChanged || bundleChanged, promptChanged, configChanged, runtimes,
212
+ sha256: sha256(target.prompt), activation: runtimes.map(runtime => ACTIVATION[runtime]).join(" ") };
154
213
  });
155
214
  }
156
215
  export async function restorePrompt(target) {
@@ -161,48 +220,75 @@ export async function restorePrompt(target) {
161
220
  const s = await snapshot(target);
162
221
  if (!s.enrollment)
163
222
  throw new Error("Enrollment disappeared during restore");
164
- if (s.pointer !== s.files.prompt && s.pointer !== s.enrollment.previousPointer) {
223
+ const codex = s.enrollment.runtimes.includes("codex");
224
+ const pointer = codex ? s.pointer() : null;
225
+ if (codex && pointer !== s.files.prompt && pointer !== s.enrollment.previousPointer) {
165
226
  throw new Error("Prompt pointer was changed by another writer; refusing to restore over it");
166
227
  }
167
- const nextConfig = setPromptPointer(s.config ?? "", s.enrollment.previousPointer);
168
228
  // A restart must not re-enroll while a restore is in progress.
169
- await replaceFile(s.files.state, s.state, `${JSON.stringify({ ...s.enrollment, active: false }, null, 2)}\n`);
170
- const changed = await replaceFile(s.files.config, s.config, nextConfig);
171
- return { changed, restored: true, retainedPromptPath: s.files.prompt };
229
+ await replaceFile(s.files.state, s.state, serializeEnrollment({ ...s.enrollment, active: false }));
230
+ const changed = codex ? await replaceFile(s.files.config, s.config, setPromptPointer(s.config ?? "", s.enrollment.previousPointer)) : false;
231
+ return { changed, restored: true, runtimes: s.enrollment.runtimes, retainedPromptPath: s.files.prompt };
172
232
  });
173
233
  }
174
- /** Replace only the shared prefix; never reread workspace documents or skills. */
175
- export async function refreshSharedPrompt(agentDir, fetchBase, now = Date.now()) {
234
+ /**
235
+ * Daily/explicit refresh of each enrolled runtime's fleet policy; it never rereads the agent
236
+ * context. Every enrolled runtime is fetched before anything is written, so one failure leaves
237
+ * all local state untouched. Then, in one locked write:
238
+ * - Codex: only the policy prefix of the prompt file is replaced (the file keeps its inode when
239
+ * unchanged). Everything after `basePromptLength` is kept byte-for-byte, so a snapshot from an
240
+ * older sync keeps its frozen skills catalog tail until the next sync rewrites the file;
241
+ * - Claude: only `claudePolicy` in the bundle is replaced; the prompt file is not touched for it.
242
+ */
243
+ export async function refreshSharedPrompt(agentDir, fetchers, now = Date.now()) {
176
244
  const target = { agentDir, prompt: "" };
177
245
  return withLock(target, async () => {
178
246
  const s = await snapshot(target);
179
247
  if (!s.enrollment?.active)
180
248
  return { changed: false, skipped: true };
181
- if (s.pointer !== s.files.prompt || s.prompt === null)
249
+ const codex = s.enrollment.runtimes.includes("codex");
250
+ const claude = s.enrollment.runtimes.includes("claude-cli");
251
+ if ((codex && s.pointer() !== s.files.prompt) || s.prompt === null)
182
252
  throw new Error("Managed prompt pointer missing or changed; refusing refresh");
183
253
  const previousBundle = await readOptional(s.files.bundle);
184
254
  const bundle = JSON.parse(previousBundle ?? "null");
185
- if (!bundle || typeof bundle !== "object" || !("schema" in bundle) || bundle.schema !== 1 ||
186
- !("promptSha256" in bundle) || bundle.promptSha256 !== sha256(s.prompt) ||
187
- !("policy" in bundle) || typeof bundle.policy !== "string" ||
188
- !("remotePrompt" in bundle) || !bundle.remotePrompt) {
255
+ if (!record(bundle) || bundle.schema !== 1 || bundle.promptSha256 !== sha256(s.prompt) || typeof bundle.policy !== "string" ||
256
+ (codex && !bundle.remotePrompt)) {
189
257
  throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
190
258
  }
191
- // Legacy snapshots can migrate only when the compiler boundary is unambiguous.
192
- const boundary = "basePromptLength" in bundle ? bundle.basePromptLength : s.prompt.indexOf(FROZEN_CONTEXT_HEADER);
193
- if (typeof boundary !== "number" || !Number.isInteger(boundary) || boundary <= 0 ||
194
- !s.prompt.slice(boundary).startsWith(FROZEN_CONTEXT_HEADER) ||
195
- (!("basePromptLength" in bundle) && boundary !== s.prompt.lastIndexOf(FROZEN_CONTEXT_HEADER))) {
259
+ let previousClaude;
260
+ if (claude) {
261
+ try {
262
+ previousClaude = parseClaudePolicy(bundle.claudePolicy);
263
+ }
264
+ catch {
265
+ throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
266
+ }
267
+ if (typeof bundle.agentContext !== "string" || !bundle.agentContext.trim())
268
+ throw new Error("Valid enrolled remote snapshot required; run codex-prompt sync");
269
+ }
270
+ // Every remote snapshot records its prefix length (0.1.0 onwards); the agent context after it
271
+ // starts with one of the accepted boundary headings (current, 0.4 branch or 0.3).
272
+ const boundary = bundle.basePromptLength;
273
+ if (codex && (typeof boundary !== "number" || !Number.isInteger(boundary) || boundary <= 0 ||
274
+ !CONTEXT_BOUNDARY_HEADERS.some(header => s.prompt.slice(boundary).startsWith(header)))) {
196
275
  throw new Error("Frozen context boundary is ambiguous; run codex-prompt sync");
197
276
  }
198
- const remote = await fetchBase();
199
- if (!remote.prompt.trim() || remote.source.revision !== sha256(remote.prompt))
277
+ const [codexRemote, claudeRemote] = await Promise.all([codex ? fetchers.codex?.() : undefined, claude ? fetchers.claude?.() : undefined]);
278
+ if ((codex && !codexRemote) || (claude && !claudeRemote))
200
279
  throw new Error("Invalid shared prompt revision");
280
+ for (const remote of [codexRemote, claudeRemote]) {
281
+ if (remote && (!remote.prompt.trim() || remote.source.revision !== sha256(remote.prompt)))
282
+ throw new Error("Invalid shared prompt revision");
283
+ }
201
284
  if (await readOptional(s.files.config) !== s.config || await readOptional(s.files.state) !== s.state)
202
285
  throw new Error("Enrollment or configuration changed during refresh");
203
- const prompt = remote.prompt.trim() + s.prompt.slice(boundary);
204
- const nextBundle = `${JSON.stringify({ ...bundle, basePromptLength: remote.prompt.trim().length,
205
- remotePrompt: { ...remote.source, checkedAt: now }, promptSha256: sha256(prompt) }, null, 2)}\n`;
286
+ const prompt = codexRemote ? codexRemote.prompt.trim() + s.prompt.slice(boundary) : s.prompt;
287
+ const claudePolicy = claudeRemote ? { text: claudeRemote.prompt.trim(), url: claudeRemote.source.url,
288
+ revision: claudeRemote.source.revision, checkedAt: now } : undefined;
289
+ const nextBundle = `${JSON.stringify({ ...bundle,
290
+ ...codexRemote ? { basePromptLength: codexRemote.prompt.trim().length, remotePrompt: { ...codexRemote.source, checkedAt: now } } : {},
291
+ ...claudePolicy ? { claudePolicy } : {}, promptSha256: sha256(prompt) }, null, 2)}\n`;
206
292
  const changed = await replaceFile(s.files.prompt, s.prompt, prompt);
207
293
  try {
208
294
  await replaceFile(s.files.bundle, previousBundle, nextBundle);
@@ -213,6 +299,11 @@ export async function refreshSharedPrompt(agentDir, fetchBase, now = Date.now())
213
299
  await replaceFile(s.files.prompt, prompt, s.prompt);
214
300
  throw error;
215
301
  }
216
- return { changed, revision: remote.source.revision, checkedAt: now, newSessionRequired: changed };
302
+ const claudeChanged = claudePolicy !== undefined && claudePolicy.text !== previousClaude?.text;
303
+ // Codex's reviewed bridge resends the base file as each thread's base instructions, so a change
304
+ // re-syncs existing threads on their next turn; Claude starts its next CLI process with its policy.
305
+ return { changed: changed || claudeChanged, checkedAt: now,
306
+ ...codexRemote ? { revision: codexRemote.source.revision, nextCodexTurn: changed } : {},
307
+ ...claudeRemote ? { claudeRevision: claudeRemote.source.revision, nextClaudeProcess: claudeChanged } : {} };
217
308
  });
218
309
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The patched-file-set lifecycle both adapters share: receipt ownership, prepare, install,
3
+ * status and restore. Each adapter keeps its own discovery, fingerprints, patch rendering,
4
+ * receipt format and install identity (Codex package or OpenClaw root).
5
+ */
6
+ /** A receipt's file entry; the field names are the on-disk receipt format. */
7
+ export type PatchedFile = {
8
+ path: string;
9
+ originalSha256: string;
10
+ patchedSha256: string;
11
+ previousPatchedSha256?: string;
12
+ };
13
+ /**
14
+ * What a receipt's files show on disk. Only "patched" (any recorded file still holding this
15
+ * adapter's bytes, including a partial restore) is ownership. "restored" (every file original)
16
+ * and "superseded" (every non-original file gone, or the recorded install version replaced)
17
+ * leave only rollback evidence. "changed" is anything else.
18
+ */
19
+ export type Ownership = "none" | "patched" | "restored" | "superseded" | "changed";
20
+ export type PatchedFilesState = "absent" | "patched" | "partial" | "original" | "missing" | "changed";
21
+ /** A parsed receipt, reduced to what the shared lifecycle needs. */
22
+ export type RecordedFiles = {
23
+ /** Install identity recorded at patch time: the Codex package or the OpenClaw root. */
24
+ root: string;
25
+ /** Install version recorded at patch time; receipts before 0.4 may lack it. */
26
+ version?: string;
27
+ files: PatchedFile[];
28
+ /** Where this receipt kept a file's original bytes. */
29
+ backupPath(file: PatchedFile): string;
30
+ };
31
+ export type PatchedFileSet = {
32
+ receiptPath: string;
33
+ parseReceipt(source: string): RecordedFiles;
34
+ /** The version installed at a recorded root now; null when it cannot be read. */
35
+ installedVersion(root: string): Promise<string | null>;
36
+ /** Where a new install keeps a file's original bytes. */
37
+ backupPath(path: string): string;
38
+ messages: {
39
+ installChanged: string;
40
+ changed: string;
41
+ missing: string;
42
+ prepareBackupInvalid: string;
43
+ moved: string;
44
+ foreignBackup: string;
45
+ concurrent: string;
46
+ foreignEdit: string;
47
+ backupInvalid: string;
48
+ };
49
+ };
50
+ export declare function patchedFilesOwnership(set: PatchedFileSet): Promise<Ownership>;
51
+ /** The previous receipt, its ownership, and the root a new install may default to. */
52
+ export declare function openPatchedFiles(set: PatchedFileSet): Promise<{
53
+ previousReceipt: string | null;
54
+ recorded: RecordedFiles | null;
55
+ ownership: Ownership;
56
+ }>;
57
+ export type PreparedFile = {
58
+ path: string;
59
+ current: string;
60
+ original: string;
61
+ patched: string;
62
+ };
63
+ /**
64
+ * Start a patch at `root`. A restored or superseded receipt counts as cleared: any root is
65
+ * allowed and its backups may be replaced. Otherwise every recorded file must still hold this
66
+ * adapter's bytes (an interrupted re-patch is recognized by previousPatchedSha256) unless it
67
+ * is missing or the recorded version was replaced; the adapter then reads originals through
68
+ * `read` (backups for owned files) and hands its patched sources to `finish`.
69
+ */
70
+ export declare function beginPatch(set: PatchedFileSet, opened: Awaited<ReturnType<typeof openPatchedFiles>>, root: string): Promise<{
71
+ read: (path: string) => Promise<string>;
72
+ finish: (patched: Map<string, string>) => {
73
+ files: PreparedFile[];
74
+ entries: PatchedFile[];
75
+ previousReceipt: string | null;
76
+ staleBackups: Set<string>;
77
+ };
78
+ }>;
79
+ export type PatchPlan = {
80
+ files: PreparedFile[];
81
+ previousReceipt: string | null;
82
+ staleBackups: Set<string>;
83
+ };
84
+ /** Validates every target before any change; keeps exact original backups, then the receipt, then the files. */
85
+ export declare function installPatch(set: PatchedFileSet, plan: PatchPlan, receipt: string): Promise<{
86
+ adapterChanged: boolean;
87
+ restartRequired: boolean;
88
+ }>;
89
+ /** Disk state of every recorded file; distinguishes missing files (an update) from foreign edits. */
90
+ export declare function patchedFilesStatus(set: PatchedFileSet): Promise<{
91
+ recorded: RecordedFiles;
92
+ state: "changed" | "patched" | "partial" | "original" | "missing";
93
+ installed: boolean;
94
+ paths: string[];
95
+ } | null>;
96
+ /**
97
+ * Validates the whole restore before any write, and plans nothing unless this adapter's bytes
98
+ * are installed. Files holding them are restored; missing files are superseded; foreign bytes
99
+ * are superseded only after the recorded version was replaced, otherwise refused. Backups are
100
+ * checked only for files that will be written.
101
+ */
102
+ export type RestorePlan = {
103
+ ownership: Ownership;
104
+ files: {
105
+ path: string;
106
+ current: string;
107
+ original: string;
108
+ }[];
109
+ superseded: string[];
110
+ };
111
+ export declare function planPatchedRestore(set: PatchedFileSet): Promise<RestorePlan>;
112
+ export declare function applyPatchedRestore(plan: RestorePlan): Promise<{
113
+ ownership: Ownership;
114
+ files: string[];
115
+ superseded: string[];
116
+ restartRequired: boolean;
117
+ }>;
@@ -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
+ }
@@ -16,6 +16,8 @@ const SAFE_CAUSES = new Set([
16
16
  "Managed prompt pointer missing or changed; refusing refresh",
17
17
  "Valid enrolled remote snapshot required; run codex-prompt sync",
18
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",
19
21
  "Prompt endpoint must return plain text", "Prompt exceeds 256 KiB limit",
20
22
  "Prompt is empty or contains NUL bytes", "Prompt revision does not match response body",
21
23
  "The managed codex skills block in config.toml is damaged; restore its BEGIN/END markers or remove it",
package/dist/remote.d.ts CHANGED
@@ -1,8 +1,33 @@
1
- /** Explicit sync and daily shared-prompt refresh validate before changing local state. */
2
- 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<{
3
11
  prompt: string;
4
12
  source: {
5
13
  url: string;
6
14
  revision: string;
7
15
  };
8
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,16 +1,31 @@
1
1
  import { validatePromptUrl } from "./config.js";
2
2
  import { sha256 } from "./manager.js";
3
3
  const MAX_BYTES = 256 * 1024;
4
- /** Explicit sync and daily shared-prompt refresh validate before changing local state. */
5
- export async function fetchPrompt(url, request = fetch) {
6
- 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, {
7
16
  redirect: "error",
8
17
  credentials: "omit",
9
18
  signal: AbortSignal.timeout(10_000),
10
19
  headers: { Accept: "text/plain", "Cache-Control": "no-cache" },
11
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}`);
12
24
  if (!response.ok)
13
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
+ }
14
29
  const type = response.headers.get("content-type")?.split(";")[0]?.trim();
15
30
  if (type !== "text/plain" || !response.body)
16
31
  throw new Error("Prompt endpoint must return plain text");
@@ -38,5 +53,9 @@ export async function fetchPrompt(url, request = fetch) {
38
53
  const revision = sha256(prompt);
39
54
  if (response.headers.get("x-prompt-revision") !== revision)
40
55
  throw new Error("Prompt revision does not match response body");
41
- 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" }) };
42
61
  }