@zentropi/reflexes-openclaw 0.0.0-stage → 0.2.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,35 @@
1
+ export type PolicyScheme = "file" | "zentropi" | "github";
2
+ export interface PolicyRef {
3
+ scheme: PolicyScheme;
4
+ locator: string;
5
+ version: string | null;
6
+ raw: string;
7
+ isPinned: boolean;
8
+ }
9
+ export declare function parseRef(ref: string): PolicyRef;
10
+ export declare class PolicyNotFound extends Error {
11
+ ref: PolicyRef;
12
+ constructor(ref: PolicyRef, detail?: string);
13
+ }
14
+ type FetchImpl = typeof fetch;
15
+ export declare function fileFetch(ref: PolicyRef, baseDir?: string): string;
16
+ declare function fetchCriteria(ref: PolicyRef, baseDir: string | undefined, fetchImpl: FetchImpl): Promise<string>;
17
+ declare function cacheDir(): string;
18
+ declare function ttlSeconds(): number;
19
+ declare function cachePath(ref: PolicyRef): string;
20
+ declare function getOrFetch(ref: PolicyRef, fetch: () => Promise<string>): Promise<string>;
21
+ export declare function stripFrontmatter(text: string): string;
22
+ export interface ResolveOptions {
23
+ baseDir?: string;
24
+ fetchImpl?: FetchImpl;
25
+ }
26
+ export declare function resolveCriteria(ref: PolicyRef, opts?: ResolveOptions): Promise<string>;
27
+ export declare const _internal: {
28
+ cachePath: typeof cachePath;
29
+ cacheDir: typeof cacheDir;
30
+ getOrFetch: typeof getOrFetch;
31
+ fetchCriteria: typeof fetchCriteria;
32
+ ttlSeconds: typeof ttlSeconds;
33
+ CACHEABLE_SCHEMES: Set<string>;
34
+ };
35
+ export {};
package/dist/policy.js ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Hosted policy references for OpenClaw — a TypeScript port of the Python
3
+ * reflexes.policy_ref / policy_sources / policy_cache. A binding's `policy:` can
4
+ * be a local file (default), `zentropi:<labeler_id>[@<version>]`, or
5
+ * `github:<owner>/<repo>/<path>[@<tag-or-sha>]`. All resolve to criteria text,
6
+ * so hosted policies work with any evaluator.
7
+ *
8
+ * The on-disk cache uses the SAME format as the Python implementation
9
+ * (~/.reflexes/.policy-cache/<scheme>-<sha256[:32]>.json), so the two share
10
+ * cache entries. Pinned refs are cached permanently; unpinned use a TTL with
11
+ * write-through + fail-safe-to-stale. There is intentionally no http: scheme.
12
+ */
13
+ import { readFileSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
14
+ import { join, isAbsolute } from "node:path";
15
+ import { homedir } from "node:os";
16
+ import { createHash } from "node:crypto";
17
+ const REGISTERED_SCHEMES = new Set(["file", "zentropi", "github"]);
18
+ const VERSIONED_SCHEMES = new Set(["zentropi", "github"]);
19
+ export function parseRef(ref) {
20
+ const raw = ref;
21
+ const text = ref.trim();
22
+ let scheme = "file";
23
+ let locator = text;
24
+ const idx = text.indexOf(":");
25
+ if (idx > 0) {
26
+ const head = text.slice(0, idx);
27
+ if (REGISTERED_SCHEMES.has(head)) {
28
+ scheme = head;
29
+ locator = text.slice(idx + 1);
30
+ }
31
+ }
32
+ let version = null;
33
+ if (VERSIONED_SCHEMES.has(scheme)) {
34
+ const at = locator.lastIndexOf("@");
35
+ if (at >= 0) {
36
+ version = locator.slice(at + 1) || null;
37
+ locator = locator.slice(0, at);
38
+ }
39
+ }
40
+ return { scheme, locator, version, raw, isPinned: version !== null };
41
+ }
42
+ export class PolicyNotFound extends Error {
43
+ ref;
44
+ constructor(ref, detail = "") {
45
+ super(`Could not resolve policy: ${ref.raw}${detail ? ` (${detail})` : ""}`);
46
+ this.name = "PolicyNotFound";
47
+ this.ref = ref;
48
+ }
49
+ }
50
+ // --- HTTP GET with transient retries (mirrors policy_sources._get) ----------
51
+ const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
52
+ const RETRY_DELAYS_MS = [300, 1000]; // before retry 2 and retry 3 (3 attempts)
53
+ const FETCH_TIMEOUT_MS = 15_000;
54
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
55
+ async function httpGet(url, headers, fetchImpl) {
56
+ const attempts = RETRY_DELAYS_MS.length + 1;
57
+ let lastErr;
58
+ let resp;
59
+ for (let attempt = 0; attempt < attempts; attempt++) {
60
+ const controller = new AbortController();
61
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
62
+ try {
63
+ resp = await fetchImpl(url, { headers, signal: controller.signal });
64
+ }
65
+ catch (e) {
66
+ lastErr = e;
67
+ resp = undefined;
68
+ }
69
+ finally {
70
+ clearTimeout(timer);
71
+ }
72
+ if (resp && !RETRYABLE_STATUS.has(resp.status))
73
+ return resp; // success or terminal
74
+ if (attempt < attempts - 1)
75
+ await sleep(RETRY_DELAYS_MS[attempt]);
76
+ }
77
+ if (resp)
78
+ return resp; // exhausted on a retryable status; caller interprets it
79
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
80
+ }
81
+ // --- zentropi -------------------------------------------------------------
82
+ function zentropiBuildBase() {
83
+ return (process.env.ZENTROPI_BUILD_API_BASE ?? "https://zentropi.ai").replace(/\/+$/, "");
84
+ }
85
+ function zentropiHeaders() {
86
+ const headers = { Accept: "application/json" };
87
+ const key = process.env.ZENTROPI_API_KEY;
88
+ if (key)
89
+ headers.Authorization = `Bearer ${key}`;
90
+ return headers;
91
+ }
92
+ function checkZentropiStatus(ref, resp) {
93
+ if (resp.status === 404)
94
+ throw new PolicyNotFound(ref, "labeler/version not found (404)");
95
+ if (resp.status === 401 || resp.status === 403) {
96
+ throw new Error(`Zentropi denied access fetching policy ${ref.raw} (HTTP ${resp.status}). ` +
97
+ `Check ZENTROPI_API_KEY and that the labeler is accessible.`);
98
+ }
99
+ if (!resp.ok)
100
+ throw new Error(`Zentropi fetch failed (HTTP ${resp.status}) for ${ref.raw}`);
101
+ }
102
+ async function zentropiFetch(ref, fetchImpl) {
103
+ const base = zentropiBuildBase();
104
+ const headers = zentropiHeaders();
105
+ let criteria;
106
+ if (ref.version !== null) {
107
+ const resp = await httpGet(`${base}/v1/labelers/${ref.locator}/versions/${ref.version}`, headers, fetchImpl);
108
+ checkZentropiStatus(ref, resp);
109
+ criteria = (await resp.json())?.criteria_text;
110
+ }
111
+ else {
112
+ const resp = await httpGet(`${base}/v1/labelers/${ref.locator}/versions`, headers, fetchImpl);
113
+ checkZentropiStatus(ref, resp);
114
+ const versions = (await resp.json()) ?? [];
115
+ const deployed = versions.filter((v) => v?.is_deployed);
116
+ if (deployed.length === 0)
117
+ throw new PolicyNotFound(ref, "labeler has no deployed version");
118
+ deployed.sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
119
+ criteria = deployed[deployed.length - 1]?.criteria_text;
120
+ }
121
+ if (!criteria)
122
+ throw new PolicyNotFound(ref, "resolved version has empty criteria");
123
+ return criteria;
124
+ }
125
+ // --- github (public repos only) -------------------------------------------
126
+ async function githubFetch(ref, fetchImpl) {
127
+ const parts = ref.locator.split("/");
128
+ if (parts.length < 3 || parts.some((p) => !p)) {
129
+ throw new PolicyNotFound(ref, "expected github:<owner>/<repo>/<path-to-file>");
130
+ }
131
+ const [owner, repo, ...rest] = parts;
132
+ const path = rest.join("/");
133
+ const gitRef = ref.version ?? "HEAD";
134
+ const url = `https://raw.githubusercontent.com/${owner}/${repo}/${gitRef}/${path}`;
135
+ const resp = await httpGet(url, {}, fetchImpl);
136
+ if (resp.status === 404)
137
+ throw new PolicyNotFound(ref, "file not found on GitHub (404)");
138
+ if (resp.status === 401 || resp.status === 403) {
139
+ throw new Error(`GitHub denied access fetching ${ref.raw} (HTTP ${resp.status}). Only public repos are supported.`);
140
+ }
141
+ if (!resp.ok)
142
+ throw new Error(`GitHub fetch failed (HTTP ${resp.status}) for ${ref.raw}`);
143
+ const text = await resp.text();
144
+ if (!text.trim())
145
+ throw new PolicyNotFound(ref, "GitHub file is empty");
146
+ return text;
147
+ }
148
+ // --- file -----------------------------------------------------------------
149
+ export function fileFetch(ref, baseDir) {
150
+ const p = ref.locator;
151
+ const path = isAbsolute(p) ? p : join(baseDir ?? process.cwd(), p);
152
+ return readFileSync(path, "utf8");
153
+ }
154
+ async function fetchCriteria(ref, baseDir, fetchImpl) {
155
+ if (ref.scheme === "file")
156
+ return fileFetch(ref, baseDir);
157
+ if (ref.scheme === "zentropi")
158
+ return zentropiFetch(ref, fetchImpl);
159
+ if (ref.scheme === "github")
160
+ return githubFetch(ref, fetchImpl);
161
+ throw new Error(`Unknown policy scheme: ${ref.scheme}`);
162
+ }
163
+ // --- cache (same on-disk format as the Python policy_cache) ---------------
164
+ const DEFAULT_TTL_SECONDS = 3600;
165
+ const CACHEABLE_SCHEMES = new Set(["zentropi", "github"]);
166
+ function cacheDir() {
167
+ // Lazy so tests can point HOME at a temp dir; default matches the Python impl.
168
+ return join(homedir(), ".reflexes", ".policy-cache");
169
+ }
170
+ function ttlSeconds() {
171
+ const raw = process.env.REFLEXES_POLICY_CACHE_TTL;
172
+ if (raw) {
173
+ const n = parseInt(raw, 10);
174
+ if (!Number.isNaN(n) && n >= 0)
175
+ return n;
176
+ }
177
+ return DEFAULT_TTL_SECONDS;
178
+ }
179
+ function cachePath(ref) {
180
+ const identity = `${ref.scheme}:${ref.locator}@${ref.version ?? ""}`;
181
+ const digest = createHash("sha256").update(identity).digest("hex").slice(0, 32);
182
+ return join(cacheDir(), `${ref.scheme}-${digest}.json`);
183
+ }
184
+ function readEntry(path) {
185
+ try {
186
+ const entry = JSON.parse(readFileSync(path, "utf8"));
187
+ if (entry && typeof entry.criteria === "string")
188
+ return entry;
189
+ }
190
+ catch {
191
+ /* miss */
192
+ }
193
+ return null;
194
+ }
195
+ function writeEntry(path, entry) {
196
+ try {
197
+ mkdirSync(cacheDir(), { recursive: true });
198
+ const tmp = `${path}.${process.pid}.tmp`;
199
+ writeFileSync(tmp, JSON.stringify(entry));
200
+ renameSync(tmp, path); // atomic
201
+ }
202
+ catch {
203
+ /* caching is best-effort */
204
+ }
205
+ }
206
+ async function getOrFetch(ref, fetch) {
207
+ if (!CACHEABLE_SCHEMES.has(ref.scheme))
208
+ return fetch();
209
+ const path = cachePath(ref);
210
+ const entry = readEntry(path);
211
+ if (ref.isPinned) {
212
+ if (entry)
213
+ return entry.criteria; // immutable → permanent cache
214
+ const criteria = await fetch();
215
+ writeEntry(path, { criteria });
216
+ return criteria;
217
+ }
218
+ // Unpinned → TTL + write-through + fail-safe.
219
+ const now = Date.now() / 1000;
220
+ if (entry && now - (entry.fetched_at ?? 0) < ttlSeconds())
221
+ return entry.criteria;
222
+ let criteria;
223
+ try {
224
+ criteria = await fetch();
225
+ }
226
+ catch (e) {
227
+ if (entry)
228
+ return entry.criteria; // fail-safe to stale
229
+ throw e;
230
+ }
231
+ writeEntry(path, { criteria, fetched_at: now });
232
+ return criteria;
233
+ }
234
+ // --- public resolve -------------------------------------------------------
235
+ const FRONTMATTER_RE = /^\s*---\s*\n[\s\S]*?\n---\s*\n/;
236
+ export function stripFrontmatter(text) {
237
+ return text.replace(FRONTMATTER_RE, "").trim();
238
+ }
239
+ export async function resolveCriteria(ref, opts = {}) {
240
+ const fetchImpl = opts.fetchImpl ?? fetch;
241
+ const raw = await getOrFetch(ref, () => fetchCriteria(ref, opts.baseDir, fetchImpl));
242
+ return stripFrontmatter(raw);
243
+ }
244
+ // Exposed for tests.
245
+ export const _internal = { cachePath, cacheDir, getOrFetch, fetchCriteria, ttlSeconds, CACHEABLE_SCHEMES };
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@zentropi/reflexes-openclaw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Reflexes for OpenClaw \u2014 an open safety harness for AI agents: inference-time, plain-English policy checks on tool calls and replies.",
8
+ "license": "Apache-2.0",
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "files": [
13
+ "dist",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.json",
18
+ "test": "npm run build && node --test test/plugin.test.js test/policy.test.js test/evaluators.test.js test/readme.test.js"
19
+ },
20
+ "dependencies": {
21
+ "yaml": "^2.4.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^26.1.1",
25
+ "typescript": "^5.5.0"
26
+ },
27
+ "openclaw": {
28
+ "extensions": [
29
+ "./dist/index.js"
30
+ ]
31
+ }
6
32
  }