@unblocklabs/unblock-codex-prompt 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ import { readFile, realpath, stat } from "node:fs/promises";
2
+ import { join, resolve, sep } from "node:path";
3
+ /**
4
+ * The agent workspace files the Claude CLI prompt carries, in prompt order: OpenClaw's own
5
+ * workspace bootstrap set (`WORKSPACE_BOOTSTRAP_FILENAMES`) without MEMORY.md, whose body stays out
6
+ * of the prompt while the memory reference points to it. BOOTSTRAP.md is included only where
7
+ * OpenClaw would include it: primary interactive runs (see `includeBootstrap`).
8
+ */
9
+ export const CLAUDE_WORKSPACE_FILES = ["AGENTS.md", "SOUL.md", "IDENTITY.md", "USER.md", "BOOTSTRAP.md"];
10
+ /** OpenClaw's bootstrap defaults (2026.10.6 and 2026.10.9 `bootstrap-*.mjs`). */
11
+ export const DEFAULT_BOOTSTRAP_MAX_CHARS = 20_000;
12
+ export const DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS = 60_000;
13
+ export const USER_BOOTSTRAP_MAX_CHARS = 4_000;
14
+ /** OpenClaw shows BOOTSTRAP.md only on primary user/manual runs, never to subagents, heartbeats or cron. */
15
+ export function includeBootstrap(ctx) {
16
+ const trigger = typeof ctx.trigger === "string" ? ctx.trigger : "user";
17
+ return (trigger === "user" || trigger === "manual") && !(typeof ctx.sessionKey === "string" && ctx.sessionKey.includes(":subagent:"));
18
+ }
19
+ // OpenClaw's own read bound for a workspace bootstrap file.
20
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
21
+ function record(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
22
+ function agentEntry(config, agentId) {
23
+ const agents = record(config) ? config.agents : undefined;
24
+ if (!record(agents))
25
+ return undefined;
26
+ if (Array.isArray(agents.list)) {
27
+ const entry = agents.list.find((item) => record(item) && item.id === agentId);
28
+ return record(entry) ? entry : undefined;
29
+ }
30
+ return record(agents.entries) && record(agents.entries[agentId]) ? agents.entries[agentId] : undefined;
31
+ }
32
+ /**
33
+ * OpenClaw's per-file cap: the agent's `bootstrapMaxChars`, else `agents.defaults.bootstrapMaxChars`,
34
+ * else 20000. A positive finite number is floored; anything else falls back, as OpenClaw does.
35
+ */
36
+ function bootstrapLimit(config, agentId, key, fallback) {
37
+ const agents = record(config) ? config.agents : undefined;
38
+ const defaults = record(agents) && record(agents.defaults) ? agents.defaults : undefined;
39
+ const raw = agentEntry(config, agentId)?.[key] ?? defaults?.[key];
40
+ return typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : fallback;
41
+ }
42
+ export function bootstrapMaxChars(config, agentId) {
43
+ return bootstrapLimit(config, agentId, "bootstrapMaxChars", DEFAULT_BOOTSTRAP_MAX_CHARS);
44
+ }
45
+ /** OpenClaw's total budget across all workspace files (default 60000). */
46
+ export function bootstrapTotalMaxChars(config, agentId) {
47
+ return bootstrapLimit(config, agentId, "bootstrapTotalMaxChars", DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS);
48
+ }
49
+ /** Keeps the head of over-long content without splitting a surrogate pair. */
50
+ function cap(text, maxChars) {
51
+ if (text.length <= maxChars)
52
+ return text;
53
+ const end = /[\uD800-\uDBFF]/u.test(text[maxChars - 1] ?? "") ? maxChars - 1 : maxChars;
54
+ return text.slice(0, end).trimEnd();
55
+ }
56
+ function isMissing(error) {
57
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
58
+ }
59
+ /**
60
+ * A workspace file's text, or null when it is absent. Like OpenClaw, symlinks are followed only
61
+ * within the workspace; a file resolving outside it, a non-regular file or one above OpenClaw's
62
+ * read bound is skipped and reported.
63
+ */
64
+ async function readWorkspaceFile(root, path, skipped) {
65
+ let real;
66
+ try {
67
+ real = await realpath(path);
68
+ }
69
+ catch (error) {
70
+ if (isMissing(error))
71
+ return null;
72
+ skipped.push({ path, reason: "unreadable" });
73
+ return null;
74
+ }
75
+ if (!real.startsWith(root + sep)) {
76
+ skipped.push({ path, reason: "outside the workspace" });
77
+ return null;
78
+ }
79
+ try {
80
+ const info = await stat(real);
81
+ if (!info.isFile()) {
82
+ skipped.push({ path, reason: "not a regular file" });
83
+ return null;
84
+ }
85
+ if (info.size > MAX_FILE_BYTES) {
86
+ skipped.push({ path, reason: "larger than 2 MiB" });
87
+ return null;
88
+ }
89
+ return await readFile(real, "utf8");
90
+ }
91
+ catch (error) {
92
+ if (isMissing(error))
93
+ return null;
94
+ skipped.push({ path, reason: "unreadable" });
95
+ return null;
96
+ }
97
+ }
98
+ /**
99
+ * The complete Claude CLI system prompt for the managed agent: the Claude policy, the memory
100
+ * reference, then each present, non-empty workspace file under its absolute path. Files are read
101
+ * on every call, so an edit applies to the next turn. Nothing else is added.
102
+ */
103
+ export async function buildClaudeSystemPrompt(managed, workspaceDir, maxChars, options = {}) {
104
+ let remaining = options.totalMaxChars ?? DEFAULT_BOOTSTRAP_TOTAL_MAX_CHARS;
105
+ const workspace = resolve(workspaceDir);
106
+ const skipped = [];
107
+ let root;
108
+ try {
109
+ root = await realpath(workspace);
110
+ }
111
+ catch (error) {
112
+ if (!isMissing(error))
113
+ throw error;
114
+ root = null;
115
+ }
116
+ const sections = [managed.policy, managed.agentContext];
117
+ if (root !== null) {
118
+ for (const name of CLAUDE_WORKSPACE_FILES) {
119
+ if (name === "BOOTSTRAP.md" && options.includeBootstrap === false)
120
+ continue;
121
+ if (remaining <= 0)
122
+ break;
123
+ const path = join(workspace, name);
124
+ // Leading blank lines and trailing whitespace go; indentation is kept.
125
+ const text = (await readWorkspaceFile(root, path, skipped))?.replace(/^(?:[ \t]*\r?\n)+/u, "").trimEnd();
126
+ if (!text?.trim())
127
+ continue;
128
+ const body = cap(text, Math.min(remaining, name === "USER.md" ? Math.min(maxChars, USER_BOOTSTRAP_MAX_CHARS) : maxChars));
129
+ remaining -= body.length;
130
+ sections.push(`## ${path}\n${body}`);
131
+ }
132
+ }
133
+ return { systemPrompt: sections.join("\n\n"), skipped };
134
+ }
@@ -1,2 +1,2 @@
1
- export declare const MINIMUM_OPENCLAW = "2026.9.2";
1
+ export declare const MINIMUM_OPENCLAW = "2026.10.5";
2
2
  export declare function assertSupportedVersion(version: unknown, product: string): void;
@@ -1,9 +1,10 @@
1
- export const MINIMUM_OPENCLAW = "2026.9.2";
1
+ // The reviewed live-persona carriers first ship in OpenClaw/@openclaw/codex 2026.10.5.
2
+ export const MINIMUM_OPENCLAW = "2026.10.5";
2
3
  export function assertSupportedVersion(version, product) {
3
4
  const match = typeof version === "string" ? /^(\d+)\.(\d+)\.(\d+)(?:-\d+)?$/u.exec(version) : null;
4
5
  const supported = match && (Number(match[1]) > 2026 ||
5
- (Number(match[1]) === 2026 && (Number(match[2]) > 9 ||
6
- (Number(match[2]) === 9 && Number(match[3]) >= 2))));
6
+ (Number(match[1]) === 2026 && (Number(match[2]) > 10 ||
7
+ (Number(match[2]) === 10 && Number(match[3]) >= 5))));
7
8
  if (!supported)
8
9
  throw new Error(`Frozen bridge requires ${product} >=${MINIMUM_OPENCLAW} (stable release)`);
9
10
  }
@@ -1,22 +1,112 @@
1
- import type { OpenClawConfig } from "openclaw/plugin-sdk/plugin-entry";
1
+ import { type ClaudePolicy } from "./manager.js";
2
2
  export declare function openclawRoot(): Promise<string>;
3
- export declare function buildSkillsCatalog(config: OpenClawConfig, agentId: string, workspaceDir: string): Promise<{
3
+ /**
4
+ * Compile the prompt file and bundle for the enrolled runtimes. Skills are never compiled: both
5
+ * runtimes receive OpenClaw's per-session skills catalog through their own assembly.
6
+ * - Codex (`base` given): the file is the Codex policy followed by the agent context. The bundle
7
+ * keeps `policy: ""`.
8
+ * - Claude (`claude` given): the bundle also stores the Claude policy and the agent context text.
9
+ * - Claude only (`base` null): nothing Codex-specific is built. The file holds just the agent
10
+ * context, so its hash still anchors the bundle and refresh has no prefix to replace.
11
+ */
12
+ export declare function compilePrompt(base: string | null, workspaceDir: string, claude?: ClaudePolicy): Promise<{
4
13
  prompt: string;
5
- count: number;
6
- }>;
7
- export declare function compilePrompt(base: string, workspaceDir: string, catalog: {
8
- prompt: string;
9
- count: number;
10
- }): Promise<{
14
+ bundle: {
15
+ claudePolicy: {
16
+ text: string;
17
+ url: string;
18
+ revision: string;
19
+ checkedAt: number;
20
+ };
21
+ agentContext: string;
22
+ schema: 1;
23
+ policy: string;
24
+ } | {
25
+ claudePolicy?: never;
26
+ agentContext?: never;
27
+ schema: 1;
28
+ policy: string;
29
+ };
30
+ } | {
11
31
  prompt: string;
12
32
  bundle: {
33
+ claudePolicy: {
34
+ text: string;
35
+ url: string;
36
+ revision: string;
37
+ checkedAt: number;
38
+ };
39
+ agentContext: string;
40
+ schema: 1;
41
+ policy: string;
42
+ basePromptLength: number;
43
+ } | {
44
+ claudePolicy?: never;
45
+ agentContext?: never;
13
46
  schema: 1;
14
47
  policy: string;
15
- sources: {
16
- name: string;
17
- sha256: string | null;
18
- }[];
19
- skillCount: number;
20
48
  basePromptLength: number;
21
49
  };
22
50
  }>;
51
+ /**
52
+ * Everything a sync needs before it may write: every enrolled runtime's policy is fetched first
53
+ * (Codex without `runtime`, Claude with runtime=claude). Any failure throws here, so nothing has
54
+ * been written.
55
+ */
56
+ export declare function fetchAndCompile(options: {
57
+ codex: boolean;
58
+ claude: boolean;
59
+ promptUrl: string;
60
+ workspaceDir: string;
61
+ request?: typeof fetch;
62
+ now?: number;
63
+ }): Promise<{
64
+ compiled: {
65
+ prompt: string;
66
+ bundle: {
67
+ claudePolicy: {
68
+ text: string;
69
+ url: string;
70
+ revision: string;
71
+ checkedAt: number;
72
+ };
73
+ agentContext: string;
74
+ schema: 1;
75
+ policy: string;
76
+ } | {
77
+ claudePolicy?: never;
78
+ agentContext?: never;
79
+ schema: 1;
80
+ policy: string;
81
+ };
82
+ } | {
83
+ prompt: string;
84
+ bundle: {
85
+ claudePolicy: {
86
+ text: string;
87
+ url: string;
88
+ revision: string;
89
+ checkedAt: number;
90
+ };
91
+ agentContext: string;
92
+ schema: 1;
93
+ policy: string;
94
+ basePromptLength: number;
95
+ } | {
96
+ claudePolicy?: never;
97
+ agentContext?: never;
98
+ schema: 1;
99
+ policy: string;
100
+ basePromptLength: number;
101
+ };
102
+ };
103
+ remote: {
104
+ url: string;
105
+ revision: string;
106
+ } | undefined;
107
+ claudePolicy: {
108
+ url: string;
109
+ revision: string;
110
+ checkedAt: number;
111
+ } | undefined;
112
+ }>;
package/dist/compiler.js CHANGED
@@ -1,8 +1,8 @@
1
- import { readFile, readdir } from "node:fs/promises";
2
1
  import { dirname, join } from "node:path";
3
- import { fileURLToPath, pathToFileURL } from "node:url";
4
- import { readOptional, sha256 } from "./manager.js";
2
+ import { fileURLToPath } from "node:url";
3
+ import { MEMORY_REFERENCE_HEADER, readOptional } from "./manager.js";
5
4
  import { assertSupportedVersion } from "./compatibility.js";
5
+ import { policyFetchers } from "./remote.js";
6
6
  export async function openclawRoot() {
7
7
  let directory = dirname(fileURLToPath(import.meta.resolve("openclaw/plugin-sdk/agent-runtime")));
8
8
  for (;;) {
@@ -20,39 +20,44 @@ export async function openclawRoot() {
20
20
  directory = parent;
21
21
  }
22
22
  }
23
- // OpenClaw has no public catalog-building SDK. Validate this internal export,
24
- // retaining its eligibility, agent allowlist, prompt visibility and size limits.
25
- export async function buildSkillsCatalog(config, agentId, workspaceDir) {
26
- const dist = join(await openclawRoot(), "dist");
27
- const names = (await readdir(dist)).filter(name => /^workspace-skill-prompt-[\w-]+\.m?js$/u.test(name));
28
- if (names.length !== 1)
29
- throw new Error("Unsupported OpenClaw skills module layout");
30
- const path = join(dist, names[0]);
31
- const source = await readFile(path, "utf8");
32
- const exports = [...source.matchAll(/\bbuildSkillSnapshot as ([\w$]+)\b/gu)];
33
- if (exports.length !== 1)
34
- throw new Error("Unsupported OpenClaw skills export");
35
- const module = await import(pathToFileURL(path).href);
36
- const buildSnapshot = module[exports[0][1]];
37
- if (typeof buildSnapshot !== "function")
38
- throw new Error("Missing OpenClaw skill snapshot builder");
39
- const result = await buildSnapshot(workspaceDir, { config, agentId });
40
- if (!result || typeof result !== "object" || !("prompt" in result) || typeof result.prompt !== "string" ||
41
- !("resolvedSkills" in result) || !Array.isArray(result.resolvedSkills))
42
- throw new Error("Unsupported OpenClaw skill snapshot result");
43
- return { prompt: result.prompt, count: result.resolvedSkills.length };
23
+ /**
24
+ * Shared agent context, identical for every runtime: a pointer to the memory tools and the
25
+ * workspace MEMORY.md. Identity and workspace files reach each runtime through its own assembly.
26
+ */
27
+ function agentContextText(workspaceDir) {
28
+ return `${MEMORY_REFERENCE_HEADER.trimStart()}When prior context matters, use the available memory tools and follow their schemas. If retrieval is unavailable, say so; do not invent results. The workspace memory reference is ${join(workspaceDir, "MEMORY.md")}. Read it only when the active session's privacy policy permits; do not expose private memory in group or customer conversations.`;
44
29
  }
45
- export async function compilePrompt(base, workspaceDir, catalog) {
46
- const sources = [];
47
- const sections = [base.trim(), "## Frozen agent context\nThis context is a local snapshot, refreshed explicitly by the operator. Native AGENTS.md, native skills, actual tool schemas and current session context remain separate. This snapshot does not grant tools or permissions."];
48
- for (const name of ["SOUL.md", "IDENTITY.md", "USER.md"]) {
49
- const content = await readOptional(join(workspaceDir, name));
50
- sources.push({ name, sha256: content === null ? null : sha256(content) });
51
- if (content?.trim())
52
- sections.push(`### ${name}\n${content.trim()}`);
53
- }
54
- sections.push(`## Frozen memory reference\nWhen prior context matters, use the currently available memory tools and follow their schemas. If retrieval is unavailable, say so; do not invent results. The workspace memory reference is ${join(workspaceDir, "MEMORY.md")}. Its contents are not included here. Read it only when the active session's privacy policy permits; do not expose private memory in group or customer conversations.`);
55
- sources.push({ name: "OpenClaw skills catalog", sha256: sha256(catalog.prompt) });
56
- sections.push(`## Frozen OpenClaw skills catalog\nThis is the approved agent-workspace catalog at sync time, not a promise that credentials or tools remain available. Session-local skill selection and execution-directory skill discovery do not refresh this snapshot. Use the native catalog separately.\n\n${catalog.prompt.trim() || "No eligible model-visible OpenClaw skills at sync time."}`);
57
- return { prompt: `${sections.join("\n\n")}\n`, bundle: { schema: 1, policy: "", sources, skillCount: catalog.count, basePromptLength: base.trim().length } };
30
+ /**
31
+ * Compile the prompt file and bundle for the enrolled runtimes. Skills are never compiled: both
32
+ * runtimes receive OpenClaw's per-session skills catalog through their own assembly.
33
+ * - Codex (`base` given): the file is the Codex policy followed by the agent context. The bundle
34
+ * keeps `policy: ""`.
35
+ * - Claude (`claude` given): the bundle also stores the Claude policy and the agent context text.
36
+ * - Claude only (`base` null): nothing Codex-specific is built. The file holds just the agent
37
+ * context, so its hash still anchors the bundle and refresh has no prefix to replace.
38
+ */
39
+ export async function compilePrompt(base, workspaceDir, claude) {
40
+ if (base === null && !claude)
41
+ throw new Error("compilePrompt needs a Codex base, a Claude policy, or both");
42
+ const agentContext = agentContextText(workspaceDir);
43
+ const claudeFields = claude ? { claudePolicy: { ...claude, text: claude.text.trim() }, agentContext } : {};
44
+ if (base === null)
45
+ return { prompt: agentContext, bundle: { schema: 1, policy: "", ...claudeFields } };
46
+ return { prompt: `${base.trim()}\n\n${agentContext}\n`, bundle: { schema: 1, policy: "",
47
+ basePromptLength: base.trim().length, ...claudeFields } };
48
+ }
49
+ /**
50
+ * Everything a sync needs before it may write: every enrolled runtime's policy is fetched first
51
+ * (Codex without `runtime`, Claude with runtime=claude). Any failure throws here, so nothing has
52
+ * been written.
53
+ */
54
+ export async function fetchAndCompile(options) {
55
+ const fetchers = policyFetchers(options.promptUrl, options.request);
56
+ const [remote, claudeRemote] = await Promise.all([options.codex ? fetchers.codex() : undefined, options.claude ? fetchers.claude() : undefined]);
57
+ const checkedAt = options.now ?? Date.now();
58
+ const claudePolicy = claudeRemote ? { text: claudeRemote.prompt, ...claudeRemote.source, checkedAt } : undefined;
59
+ const compiled = await compilePrompt(remote?.prompt ?? null, options.workspaceDir, claudePolicy);
60
+ if (remote)
61
+ Object.assign(compiled.bundle, { remotePrompt: { ...remote.source, checkedAt } });
62
+ return { compiled, remote: remote?.source, claudePolicy: claudePolicy && { url: claudePolicy.url, revision: claudePolicy.revision, checkedAt } };
58
63
  }