@unblocklabs/unblock-codex-prompt 0.5.2 → 0.6.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
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
3
- import { dirname, join, resolve } from "node:path";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { agentCodexHome, assertDedicatedCodexHome } from "./codex-home.js";
4
5
  import { readPromptPointer, setPromptPointer } from "./toml.js";
5
6
  export const RUNTIMES = ["codex", "claude-cli"];
6
7
  /** First heading of the agent context, the boundary after the shared policy prefix. */
@@ -10,6 +11,10 @@ export const MEMORY_REFERENCE_HEADER = "\n\n## Memory reference\n";
10
11
  * and the 0.3 `## Frozen agent context`, so their prompt files still refresh in place.
11
12
  */
12
13
  export const CONTEXT_BOUNDARY_HEADERS = [MEMORY_REFERENCE_HEADER, "\n\n## Agent context\n", "\n\n## Frozen agent context\n"];
14
+ export function isCodexPolicyBoundary(prompt, boundary) {
15
+ return typeof boundary === "number" && Number.isInteger(boundary) && boundary > 0 &&
16
+ CONTEXT_BOUNDARY_HEADERS.some(header => prompt.startsWith(header, boundary));
17
+ }
13
18
  function record(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
14
19
  /** Strict shape check for a stored Claude policy; throws on anything else. */
15
20
  export function parseClaudePolicy(value) {
@@ -19,11 +24,10 @@ export function parseClaudePolicy(value) {
19
24
  }
20
25
  return { text: value.text, url: value.url, revision: value.revision, checkedAt: value.checkedAt };
21
26
  }
22
- function paths(target) {
23
- const home = join(resolve(target.agentDir), "codex-home");
27
+ function paths(agentDir) {
28
+ const home = agentCodexHome(agentDir);
24
29
  return {
25
30
  home,
26
- config: join(home, "config.toml"),
27
31
  prompt: join(home, "unblock-codex-prompt.md"),
28
32
  state: join(home, ".unblock-codex-prompt.json"),
29
33
  lock: join(home, ".unblock-codex-prompt.lock"),
@@ -69,19 +73,23 @@ export function parseEnrollment(source) {
69
73
  catch {
70
74
  throw new Error("Invalid prompt enrollment state");
71
75
  }
72
- if (!value || typeof value !== "object" || !("schema" in value) || (value.schema !== 1 && value.schema !== 2) ||
76
+ if (!value || typeof value !== "object" || !("schema" in value) || (value.schema !== 1 && value.schema !== 2 && value.schema !== 3) ||
73
77
  !("active" in value) || typeof value.active !== "boolean" || !("previousPointer" in value) ||
74
78
  (value.previousPointer !== null && typeof value.previousPointer !== "string")) {
75
79
  throw new Error("Invalid prompt enrollment state");
76
80
  }
77
81
  // Schema 1 without runtimes is the pre-0.4 Codex enrollment.
78
- if (value.schema === 1 && !("runtimes" in value))
82
+ if (value.schema === 1 && !("runtimes" in value) && !("codexHome" in value))
79
83
  return { active: value.active, previousPointer: value.previousPointer, runtimes: ["codex"] };
80
84
  const runtimes = "runtimes" in value ? value.runtimes : undefined;
81
85
  if (!Array.isArray(runtimes) || !runtimes.length || new Set(runtimes).size !== runtimes.length ||
82
86
  runtimes.some(runtime => !RUNTIMES.includes(runtime)))
83
87
  throw new Error("Invalid prompt enrollment state");
84
- return { active: value.active, previousPointer: value.previousPointer, runtimes: sortRuntimes(runtimes) };
88
+ const codexHome = "codexHome" in value ? value.codexHome : undefined;
89
+ if (value.schema === 3 ? typeof codexHome !== "string" || !isAbsolute(codexHome) || resolve(codexHome) !== codexHome || !runtimes.includes("codex") : codexHome !== undefined) {
90
+ throw new Error("Invalid prompt enrollment Codex home");
91
+ }
92
+ return { active: value.active, previousPointer: value.previousPointer, runtimes: sortRuntimes(runtimes), ...typeof codexHome === "string" ? { codexHome } : {} };
85
93
  }
86
94
  function sortRuntimes(runtimes) { return RUNTIMES.filter(runtime => runtimes.includes(runtime)); }
87
95
  /**
@@ -94,29 +102,44 @@ function sortRuntimes(runtimes) { return RUNTIMES.filter(runtime => runtimes.inc
94
102
  export function serializeEnrollment(enrollment) {
95
103
  const runtimes = sortRuntimes(enrollment.runtimes);
96
104
  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 } };
105
+ const value = { schema: enrollment.codexHome ? 3 : enrollment.active && !runtimes.includes("codex") ? 2 : 1, active: enrollment.active,
106
+ previousPointer: enrollment.previousPointer, ...codexOnly && !enrollment.codexHome ? {} : { runtimes }, ...enrollment.codexHome ? { codexHome: enrollment.codexHome } : {} };
99
107
  return `${JSON.stringify(value, null, 2)}\n`;
100
108
  }
101
- async function snapshot(target) {
102
- const files = paths(target);
103
- await assertDirectoryChain(files.home);
104
- const [config, prompt, state] = await Promise.all([
105
- readOptional(files.config), readOptional(files.prompt), readOptional(files.state),
106
- ]);
109
+ async function snapshot(target, mode) {
110
+ const local = paths(target.agentDir);
111
+ await assertDirectoryChain(local.home);
112
+ const state = await readOptional(local.state);
107
113
  const enrollment = parseEnrollment(state);
114
+ if (mode === "sync" && enrollment?.active && enrollment.runtimes.includes("codex") && enrollment.codexHome !== target.codexHome) {
115
+ throw new Error("Codex home changed; restore the previous enrollment before syncing");
116
+ }
117
+ const codexHome = mode === "sync" ? target.codexHome : enrollment?.codexHome;
118
+ if (codexHome && mode !== "skip-config")
119
+ assertDedicatedCodexHome(codexHome, target.agentDir);
120
+ const files = { ...local, config: join(codexHome ?? local.home, "config.toml") };
121
+ const [config, prompt] = await Promise.all([mode === "skip-config" ? null : readOptional(files.config), readOptional(files.prompt)]);
108
122
  // Claude-only enrollment never parses or edits Codex configuration.
109
123
  const pointer = () => readPromptPointer(config ?? "");
110
124
  return { files, config, prompt, state, pointer, enrollment };
111
125
  }
112
126
  /** Disk-only enrollment for callers that select runtime components. */
113
127
  export async function readEnrollment(agentDir) {
114
- return (await snapshot({ agentDir, prompt: "" })).enrollment;
128
+ const files = paths(agentDir);
129
+ await assertDirectoryChain(files.home);
130
+ return parseEnrollment(await readOptional(files.state));
131
+ }
132
+ /** For Codex TOML, skills and provider cache; ownership records stay agent-local. */
133
+ export async function recordedCodexHome(agentDir) {
134
+ const enrollment = await readEnrollment(agentDir);
135
+ if (enrollment?.codexHome)
136
+ assertDedicatedCodexHome(enrollment.codexHome, agentDir);
137
+ return enrollment?.codexHome ?? agentCodexHome(agentDir);
115
138
  }
116
139
  export function sha256(text) { return createHash("sha256").update(text).digest("hex"); }
117
140
  /** Disk state only: this cannot attest to instructions retained by a live Codex thread or Claude process. */
118
- export async function promptStatus(target) {
119
- const s = await snapshot(target);
141
+ export async function promptStatus(target, { skipCodexConfig = false } = {}) {
142
+ const s = await snapshot(target, skipCodexConfig ? "skip-config" : undefined);
120
143
  const codex = s.enrollment?.runtimes.includes("codex") ?? true;
121
144
  return {
122
145
  enrolled: s.enrollment?.active === true,
@@ -124,7 +147,7 @@ export async function promptStatus(target) {
124
147
  runtimes: s.enrollment?.runtimes ?? [],
125
148
  configPath: s.files.config,
126
149
  promptPath: s.files.prompt,
127
- pointerMatches: codex ? s.pointer() === s.files.prompt : null,
150
+ pointerMatches: codex && !skipCodexConfig ? s.pointer() === s.files.prompt : null,
128
151
  actualSha256: s.prompt === null ? null : sha256(s.prompt),
129
152
  runtimeVerified: false,
130
153
  };
@@ -152,7 +175,7 @@ export async function replaceFile(path, previous, contents) {
152
175
  return true;
153
176
  }
154
177
  export async function withLock(target, operation) {
155
- const files = paths(target);
178
+ const files = paths(target.agentDir);
156
179
  await assertDirectoryChain(files.home);
157
180
  await mkdir(files.home, { recursive: true, mode: 0o700 });
158
181
  try {
@@ -182,9 +205,9 @@ export async function syncPrompt(target, options = {}) {
182
205
  if (!requested.length)
183
206
  throw new Error("Select at least one managed runtime");
184
207
  // Reject invalid state before creating even the lock directory.
185
- await snapshot(target);
208
+ await snapshot(target, "sync");
186
209
  return withLock(target, async () => {
187
- const s = await snapshot(target);
210
+ const s = await snapshot(target, "sync");
188
211
  if (s.enrollment?.active === false && options.automatic)
189
212
  return { changed: false, restored: true };
190
213
  const current = s.enrollment?.active ? s.enrollment : null;
@@ -202,6 +225,7 @@ export async function syncPrompt(target, options = {}) {
202
225
  const enrollment = {
203
226
  active: true, runtimes,
204
227
  previousPointer: addingCodex ? pointer : current?.previousPointer ?? null,
228
+ ...codex && target.codexHome ? { codexHome: target.codexHome } : {},
205
229
  };
206
230
  // Save rollback information first; point Codex at the file only after it exists.
207
231
  const stateChanged = await replaceFile(s.files.state, s.state, serializeEnrollment(enrollment));
@@ -270,8 +294,7 @@ export async function refreshSharedPrompt(agentDir, fetchers, now = Date.now())
270
294
  // Every remote snapshot records its prefix length (0.1.0 onwards); the agent context after it
271
295
  // starts with one of the accepted boundary headings (current, 0.4 branch or 0.3).
272
296
  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)))) {
297
+ if (codex && !isCodexPolicyBoundary(s.prompt, boundary)) {
275
298
  throw new Error("Frozen context boundary is ambiguous; run codex-prompt sync");
276
299
  }
277
300
  const [codexRemote, claudeRemote] = await Promise.all([codex ? fetchers.codex?.() : undefined, claude ? fetchers.claude?.() : undefined]);
package/dist/runtime.d.ts CHANGED
@@ -4,13 +4,14 @@ export { normalizeOpenClawAdditions, normalizeOpenClawTurnContext } from "./cont
4
4
  * means this Codex run is managed. The value is the bundle's `policy`, which current syncs leave
5
5
  * "": the Codex policy is the prompt-file prefix, delivered as base instructions.
6
6
  */
7
- export declare function readFrozenPolicy(agentDir: string): string | null;
7
+ export declare function readFrozenPolicy(agentDir: string, config?: unknown): string | null;
8
8
  /**
9
9
  * The verified base file, sent as each managed thread's base instructions at start and resume.
10
10
  * Codex reads base instructions per session rather than from history, so a refreshed file
11
11
  * reaches an existing thread when OpenClaw resumes it; the file itself stays the fallback.
12
+ * Lightweight runs take only the recorded policy prefix, without the agent-context tail.
12
13
  */
13
- export declare function readCodexBaseInstructions(agentDir: string): string | null;
14
+ export declare function readCodexBaseInstructions(agentDir: string, config?: unknown, contextMode?: "full" | "lightweight"): string | null;
14
15
  export type ClaudeManagedContext = {
15
16
  policy: string;
16
17
  agentContext: string;
package/dist/runtime.js CHANGED
@@ -2,7 +2,8 @@ import { lstatSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { readPromptPointer } from "./toml.js";
5
- import { parseClaudePolicy, parseEnrollment } from "./manager.js";
5
+ import { isCodexPolicyBoundary, parseClaudePolicy, parseEnrollment } from "./manager.js";
6
+ import { assertDedicatedCodexHome, configuredCodexHome } from "./codex-home.js";
6
7
  export { normalizeOpenClawAdditions, normalizeOpenClawTurnContext } from "./context.js";
7
8
  function readPrivate(path) {
8
9
  const stat = lstatSync(path);
@@ -49,7 +50,7 @@ function readVerifiedSnapshot(home) {
49
50
  throw new Error("Frozen prompt changed outside sync; refusing context suppression");
50
51
  return { bundle, policy: bundle.policy, prompt };
51
52
  }
52
- function readCodexSnapshot(agentDir) {
53
+ function readCodexSnapshot(agentDir, config) {
53
54
  const home = join(agentDir, "codex-home");
54
55
  const state = readEnrollment(home);
55
56
  if (!state)
@@ -58,8 +59,13 @@ function readCodexSnapshot(agentDir) {
58
59
  return null;
59
60
  if (!state.runtimes.includes("codex"))
60
61
  throw new Error("Codex bridge installed without Codex enrollment; restore or run codex-prompt sync");
62
+ if (config !== undefined && configuredCodexHome(config) !== state.codexHome) {
63
+ throw new Error("Codex app-server home changed; restore and re-sync the prompt bridge");
64
+ }
65
+ if (state.codexHome)
66
+ assertDedicatedCodexHome(state.codexHome, agentDir);
61
67
  const snapshot = readVerifiedSnapshot(home);
62
- if (readPromptPointer(readPrivate(join(home, "config.toml"))) !== join(home, "unblock-codex-prompt.md")) {
68
+ if (readPromptPointer(readPrivate(join(state.codexHome ?? home, "config.toml"))) !== join(home, "unblock-codex-prompt.md")) {
63
69
  throw new Error("Frozen prompt pointer changed; refusing context suppression");
64
70
  }
65
71
  return snapshot;
@@ -69,16 +75,27 @@ function readCodexSnapshot(agentDir) {
69
75
  * means this Codex run is managed. The value is the bundle's `policy`, which current syncs leave
70
76
  * "": the Codex policy is the prompt-file prefix, delivered as base instructions.
71
77
  */
72
- export function readFrozenPolicy(agentDir) {
73
- return readCodexSnapshot(agentDir)?.policy ?? null;
78
+ export function readFrozenPolicy(agentDir, config) {
79
+ return readCodexSnapshot(agentDir, config)?.policy ?? null;
74
80
  }
75
81
  /**
76
82
  * The verified base file, sent as each managed thread's base instructions at start and resume.
77
83
  * Codex reads base instructions per session rather than from history, so a refreshed file
78
84
  * reaches an existing thread when OpenClaw resumes it; the file itself stays the fallback.
85
+ * Lightweight runs take only the recorded policy prefix, without the agent-context tail.
79
86
  */
80
- export function readCodexBaseInstructions(agentDir) {
81
- return readCodexSnapshot(agentDir)?.prompt ?? null;
87
+ export function readCodexBaseInstructions(agentDir, config, contextMode) {
88
+ const snapshot = readCodexSnapshot(agentDir, config);
89
+ if (!snapshot)
90
+ return null;
91
+ const { bundle, prompt } = snapshot;
92
+ if (contextMode !== "lightweight")
93
+ return prompt;
94
+ const boundary = "basePromptLength" in bundle ? bundle.basePromptLength : undefined;
95
+ if (!isCodexPolicyBoundary(prompt, boundary)) {
96
+ throw new Error("Frozen context boundary is ambiguous; run codex-prompt sync");
97
+ }
98
+ return prompt.slice(0, boundary);
82
99
  }
83
100
  /**
84
101
  * The Claude policy and the shared agent context (memory reference), both read from the bundle,
package/dist/skills.js CHANGED
@@ -1,16 +1,12 @@
1
1
  import { readFile, readdir } from "node:fs/promises";
2
2
  import { join, resolve } from "node:path";
3
3
  import { getStaticTOMLValue, parseTOML } from "toml-eslint-parser";
4
- import { readOptional, replaceFile, withLock } from "./manager.js";
4
+ import { readEnrollment, recordedCodexHome, readOptional, replaceFile, withLock } from "./manager.js";
5
5
  // Codex loads every discovered skill unless a [[skills.config]] rule turns it off, and remote
6
6
  // plugins can add skills at any time. This block disables the listed skills and plugins by name,
7
7
  // the selector Codex applies to plugin skills (`plugin:skill`) as well as system skills.
8
8
  const BEGIN = "# BEGIN unblock-codex-prompt codex skills (managed; replaced on refresh)";
9
9
  const END = "# END unblock-codex-prompt codex skills";
10
- function files(agentDir) {
11
- const home = join(resolve(agentDir), "codex-home");
12
- return { home, config: join(home, "config.toml"), state: join(home, ".unblock-codex-prompt.json") };
13
- }
14
10
  function isMissing(error) {
15
11
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
16
12
  }
@@ -53,7 +49,7 @@ async function skillsUnder(root, depth) {
53
49
  }
54
50
  /** Skills Codex loads from this agent's home: system, user and cached plugin skills (`plugin:skill`). */
55
51
  export async function discoverCodexSkills(agentDir) {
56
- const { home } = files(agentDir);
52
+ const home = await recordedCodexHome(agentDir);
57
53
  const found = [];
58
54
  for (const name of await skillsUnder(join(home, "skills", ".system"), 1))
59
55
  found.push({ name, plugin: null });
@@ -138,19 +134,13 @@ export function setSkillsBlock(source, block) {
138
134
  }
139
135
  return result;
140
136
  }
141
- async function enrolled(agentDir) {
142
- const source = await readOptional(files(agentDir).state);
143
- if (source === null)
144
- return false;
145
- const state = JSON.parse(source);
146
- return !!state && typeof state === "object" && "active" in state && state.active === true;
147
- }
148
137
  /** Disable the listed skills in this agent's Codex home. New plugin skills are caught on the next refresh. */
149
138
  export async function refreshCodexSkills(agentDir, disable) {
150
139
  return withLock({ agentDir, prompt: "" }, async () => {
151
- if (!await enrolled(agentDir))
140
+ const enrollment = await readEnrollment(agentDir);
141
+ if (!enrollment?.active || !enrollment.runtimes.includes("codex"))
152
142
  return { skipped: true, changed: false };
153
- const path = files(agentDir).config;
143
+ const path = join(await recordedCodexHome(agentDir), "config.toml");
154
144
  const current = await readOptional(path) ?? "";
155
145
  const skills = await discoverCodexSkills(agentDir);
156
146
  const changed = await replaceFile(path, current, setSkillsBlock(current, renderSkillsBlock(skills, disable)));
@@ -165,7 +155,7 @@ export async function refreshCodexSkills(agentDir, disable) {
165
155
  }
166
156
  export async function removeCodexSkills(agentDir) {
167
157
  return withLock({ agentDir, prompt: "" }, async () => {
168
- const path = files(agentDir).config;
158
+ const path = join(await recordedCodexHome(agentDir), "config.toml");
169
159
  const current = await readOptional(path);
170
160
  if (current === null)
171
161
  return { changed: false };
@@ -173,7 +163,7 @@ export async function removeCodexSkills(agentDir) {
173
163
  });
174
164
  }
175
165
  export async function codexSkillsStatus(agentDir, disable) {
176
- const source = await readOptional(files(agentDir).config) ?? "";
166
+ const source = await readOptional(join(await recordedCodexHome(agentDir), "config.toml")) ?? "";
177
167
  const found = locateBlock(source);
178
168
  const managed = found ? source.slice(found.begin, found.end) : "";
179
169
  const disabled = [...managed.matchAll(/^name = (".*")\nenabled = false$/gmu)].map(match => JSON.parse(match[1]));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "unblock-codex-prompt",
3
3
  "name": "Unblock Codex Prompt",
4
- "version": "0.5.2",
4
+ "version": "0.6.0",
5
5
  "description": "Maintain an agent-scoped fleet prompt for Codex (model_instructions_file) and Claude CLI (before_prompt_build hook).",
6
6
  "activation": { "onStartup": true },
7
7
  "configSchema": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unblocklabs/unblock-codex-prompt",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "Manage a shared fleet prompt for an OpenClaw agent on Codex and Claude CLI.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",