pi-oracle 0.1.11 → 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,45 @@
1
+ export const ORACLE_METADATA_WRITE_GRACE_MS: number;
2
+
3
+ export function acquireLock(
4
+ stateDir: string,
5
+ kind: string,
6
+ key: string,
7
+ metadata: unknown,
8
+ timeoutMs?: number,
9
+ ): Promise<string>;
10
+
11
+ export function releaseLock(path: string | undefined): Promise<void>;
12
+
13
+ export function withLock<T>(
14
+ stateDir: string,
15
+ kind: string,
16
+ key: string,
17
+ metadata: unknown,
18
+ fn: () => Promise<T>,
19
+ timeoutMs?: number,
20
+ ): Promise<T>;
21
+
22
+ export function createLease(
23
+ stateDir: string,
24
+ kind: string,
25
+ key: string,
26
+ metadata: unknown,
27
+ timeoutMs?: number,
28
+ ): Promise<string>;
29
+
30
+ export function writeLeaseMetadata(
31
+ stateDir: string,
32
+ kind: string,
33
+ key: string,
34
+ metadata: unknown,
35
+ ): Promise<string>;
36
+
37
+ export function readLeaseMetadata<T = unknown>(
38
+ stateDir: string,
39
+ kind: string,
40
+ key: string,
41
+ ): Promise<T | undefined>;
42
+
43
+ export function listLeaseMetadata<T = unknown>(stateDir: string, kind: string): T[];
44
+
45
+ export function releaseLease(stateDir: string, kind: string, key: string | undefined): Promise<void>;
@@ -0,0 +1,235 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { basename, join } from "node:path";
5
+
6
+ const DEFAULT_WAIT_MS = 30_000;
7
+ const POLL_MS = 200;
8
+ export const ORACLE_METADATA_WRITE_GRACE_MS = 1_000;
9
+
10
+ async function sleep(ms) {
11
+ await new Promise((resolve) => setTimeout(resolve, ms));
12
+ }
13
+
14
+ async function ensurePrivateDir(path) {
15
+ await mkdir(path, { recursive: true, mode: 0o700 });
16
+ await chmod(path, 0o700).catch(() => undefined);
17
+ }
18
+
19
+ function leaseKey(kind, key) {
20
+ return `${kind}-${createHash("sha256").update(key).digest("hex").slice(0, 24)}`;
21
+ }
22
+
23
+ function getLocksDir(stateDir) {
24
+ return join(stateDir, "locks");
25
+ }
26
+
27
+ function getLeasesDir(stateDir) {
28
+ return join(stateDir, "leases");
29
+ }
30
+
31
+ function lockPath(stateDir, kind, key) {
32
+ return join(getLocksDir(stateDir), leaseKey(kind, key));
33
+ }
34
+
35
+ function leasePath(stateDir, kind, key) {
36
+ return join(getLeasesDir(stateDir), leaseKey(kind, key));
37
+ }
38
+
39
+ function getMetadataPath(path) {
40
+ return join(path, "metadata.json");
41
+ }
42
+
43
+ async function writeMetadata(path, metadata) {
44
+ const targetPath = getMetadataPath(path);
45
+ const tempPath = join(path, `metadata.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
46
+ await writeFile(tempPath, `${JSON.stringify(metadata, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
47
+ await chmod(tempPath, 0o600).catch(() => undefined);
48
+ await rename(tempPath, targetPath);
49
+ await chmod(targetPath, 0o600).catch(() => undefined);
50
+ }
51
+
52
+ async function createStateDirAtomically(parentDir, finalPath, metadata) {
53
+ const tempPath = join(parentDir, `.tmp-${basename(finalPath)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`);
54
+ await mkdir(tempPath, { recursive: false, mode: 0o700 });
55
+ try {
56
+ await writeMetadata(tempPath, metadata);
57
+ await rename(tempPath, finalPath);
58
+ } catch (error) {
59
+ await rm(tempPath, { recursive: true, force: true }).catch(() => undefined);
60
+ throw error;
61
+ }
62
+ }
63
+
64
+ function getMetadataState(path) {
65
+ const metadataPath = getMetadataPath(path);
66
+ if (!existsSync(metadataPath)) return "missing";
67
+ try {
68
+ JSON.parse(readFileSync(metadataPath, "utf8"));
69
+ return "present";
70
+ } catch {
71
+ return "invalid";
72
+ }
73
+ }
74
+
75
+ function isIncompleteStateDirStale(path, now = Date.now()) {
76
+ try {
77
+ const stats = statSync(path);
78
+ const baselineMs = Math.max(stats.mtimeMs, stats.ctimeMs);
79
+ return now - baselineMs >= ORACLE_METADATA_WRITE_GRACE_MS;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ function isProcessAlive(pid) {
86
+ try {
87
+ process.kill(pid, 0);
88
+ return true;
89
+ } catch (error) {
90
+ if (error && typeof error === "object" && "code" in error && error.code === "ESRCH") return false;
91
+ return true;
92
+ }
93
+ }
94
+
95
+ function isStateDirExistsError(error) {
96
+ return Boolean(error && typeof error === "object" && "code" in error && (error.code === "EEXIST" || error.code === "ENOTEMPTY"));
97
+ }
98
+
99
+ async function readLockProcessPid(path) {
100
+ const metadataPath = getMetadataPath(path);
101
+ if (!existsSync(metadataPath)) return undefined;
102
+ try {
103
+ const metadata = JSON.parse(await readFile(metadataPath, "utf8"));
104
+ return typeof metadata?.processPid === "number" && Number.isInteger(metadata.processPid) && metadata.processPid > 0
105
+ ? metadata.processPid
106
+ : undefined;
107
+ } catch {
108
+ return undefined;
109
+ }
110
+ }
111
+
112
+ async function maybeReclaimIncompleteStateDir(path, now = Date.now()) {
113
+ if (getMetadataState(path) === "present") return false;
114
+ if (!isIncompleteStateDirStale(path, now)) return false;
115
+ await rm(path, { recursive: true, force: true }).catch(() => undefined);
116
+ return true;
117
+ }
118
+
119
+ async function maybeReclaimStaleLock(path, now = Date.now()) {
120
+ if (await maybeReclaimIncompleteStateDir(path, now)) return true;
121
+ const processPid = await readLockProcessPid(path);
122
+ if (!processPid || isProcessAlive(processPid)) return false;
123
+ await rm(path, { recursive: true, force: true }).catch(() => undefined);
124
+ return true;
125
+ }
126
+
127
+ export async function acquireLock(stateDir, kind, key, metadata, timeoutMs = DEFAULT_WAIT_MS) {
128
+ const parentDir = getLocksDir(stateDir);
129
+ const path = join(parentDir, leaseKey(kind, key));
130
+ const deadline = Date.now() + timeoutMs;
131
+ await ensurePrivateDir(stateDir);
132
+ await ensurePrivateDir(parentDir);
133
+
134
+ while (Date.now() < deadline) {
135
+ try {
136
+ await createStateDirAtomically(parentDir, path, metadata);
137
+ return path;
138
+ } catch (error) {
139
+ if (!isStateDirExistsError(error)) throw error;
140
+ if (await maybeReclaimStaleLock(path)) continue;
141
+ }
142
+ await sleep(POLL_MS);
143
+ }
144
+
145
+ throw new Error(`Timed out waiting for oracle ${kind} lock: ${key}`);
146
+ }
147
+
148
+ export async function releaseLock(path) {
149
+ if (!path) return;
150
+ await rm(path, { recursive: true, force: true }).catch(() => undefined);
151
+ }
152
+
153
+ export async function withLock(stateDir, kind, key, metadata, fn, timeoutMs) {
154
+ const handle = await acquireLock(stateDir, kind, key, metadata, timeoutMs);
155
+ try {
156
+ return await fn();
157
+ } finally {
158
+ await releaseLock(handle);
159
+ }
160
+ }
161
+
162
+ export async function createLease(stateDir, kind, key, metadata, timeoutMs = DEFAULT_WAIT_MS) {
163
+ const parentDir = getLeasesDir(stateDir);
164
+ const path = join(parentDir, leaseKey(kind, key));
165
+ const deadline = Date.now() + timeoutMs;
166
+ await ensurePrivateDir(stateDir);
167
+ await ensurePrivateDir(parentDir);
168
+
169
+ while (Date.now() < deadline) {
170
+ try {
171
+ await createStateDirAtomically(parentDir, path, metadata);
172
+ return path;
173
+ } catch (error) {
174
+ if (!isStateDirExistsError(error)) throw error;
175
+ if (await maybeReclaimIncompleteStateDir(path)) continue;
176
+ if (getMetadataState(path) === "present") throw error;
177
+ }
178
+ await sleep(POLL_MS);
179
+ }
180
+
181
+ throw new Error(`Timed out waiting for oracle ${kind} lease: ${key}`);
182
+ }
183
+
184
+ export async function writeLeaseMetadata(stateDir, kind, key, metadata) {
185
+ const parentDir = getLeasesDir(stateDir);
186
+ const path = join(parentDir, leaseKey(kind, key));
187
+ await ensurePrivateDir(stateDir);
188
+ await ensurePrivateDir(parentDir);
189
+ if (existsSync(path)) {
190
+ await chmod(path, 0o700).catch(() => undefined);
191
+ await writeMetadata(path, metadata);
192
+ return path;
193
+ }
194
+ try {
195
+ await createStateDirAtomically(parentDir, path, metadata);
196
+ } catch (error) {
197
+ if (!isStateDirExistsError(error)) throw error;
198
+ if (await maybeReclaimIncompleteStateDir(path)) {
199
+ await createStateDirAtomically(parentDir, path, metadata);
200
+ } else {
201
+ await writeMetadata(path, metadata);
202
+ }
203
+ }
204
+ return path;
205
+ }
206
+
207
+ export async function readLeaseMetadata(stateDir, kind, key) {
208
+ const path = getMetadataPath(leasePath(stateDir, kind, key));
209
+ if (!existsSync(path)) return undefined;
210
+ try {
211
+ return JSON.parse(await readFile(path, "utf8"));
212
+ } catch {
213
+ return undefined;
214
+ }
215
+ }
216
+
217
+ export function listLeaseMetadata(stateDir, kind) {
218
+ const dir = getLeasesDir(stateDir);
219
+ if (!existsSync(dir)) return [];
220
+ return readdirSync(dir)
221
+ .filter((name) => name.startsWith(`${kind}-`))
222
+ .map((name) => join(dir, name, "metadata.json"))
223
+ .filter((path) => existsSync(path))
224
+ .flatMap((path) => {
225
+ try {
226
+ return [JSON.parse(readFileSync(path, "utf8"))];
227
+ } catch {
228
+ return [];
229
+ }
230
+ });
231
+ }
232
+
233
+ export async function releaseLease(stateDir, kind, key) {
234
+ await rm(leasePath(stateDir, kind, key), { recursive: true, force: true }).catch(() => undefined);
235
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-oracle",
3
- "version": "0.1.11",
3
+ "version": "0.2.0",
4
4
  "description": "ChatGPT web-oracle extension for pi with isolated browser auth, async jobs, and project-context archives.",
5
5
  "private": false,
6
6
  "license": "MIT",
@@ -28,7 +28,9 @@
28
28
  "files": [
29
29
  "extensions",
30
30
  "prompts",
31
+ "docs",
31
32
  "README.md",
33
+ "CHANGELOG.md",
32
34
  "LICENSE"
33
35
  ],
34
36
  "pi": {
@@ -40,16 +42,23 @@
40
42
  ]
41
43
  },
42
44
  "scripts": {
43
- "check:oracle-extension": "node --check extensions/oracle/worker/run-job.mjs && node --check extensions/oracle/worker/artifact-heuristics.mjs && node --check extensions/oracle/worker/auth-cookie-policy.mjs && node --check extensions/oracle/worker/auth-bootstrap.mjs && esbuild extensions/oracle/index.ts --bundle --platform=node --format=esm --external:@mariozechner/pi-coding-agent --external:@mariozechner/pi-ai --external:@sinclair/typebox --outfile=/tmp/pi-oracle-extension-check.js",
45
+ "check:oracle-extension": "node --check extensions/oracle/worker/run-job.mjs && node --check extensions/oracle/worker/state-locks.mjs && node --check extensions/oracle/worker/artifact-heuristics.mjs && node --check extensions/oracle/worker/auth-cookie-policy.mjs && node --check extensions/oracle/worker/auth-bootstrap.mjs && esbuild extensions/oracle/index.ts --bundle --platform=node --format=esm --external:@mariozechner/pi-coding-agent --external:@mariozechner/pi-ai --external:@sinclair/typebox --outfile=/tmp/pi-oracle-extension-check.js",
46
+ "typecheck": "tsc --noEmit -p tsconfig.json",
44
47
  "sanity:oracle": "node scripts/oracle-sanity-runner.mjs",
45
- "pack:check": "npm pack --dry-run"
48
+ "pack:check": "npm pack --dry-run",
49
+ "verify:oracle": "npm run check:oracle-extension && npm run typecheck && npm run sanity:oracle && npm run pack:check"
46
50
  },
47
51
  "dependencies": {
52
+ "@sinclair/typebox": "^0.34.49",
48
53
  "@steipete/sweet-cookie": "^0.2.0"
49
54
  },
50
55
  "devDependencies": {
56
+ "@mariozechner/pi-ai": "^0.65.2",
57
+ "@mariozechner/pi-coding-agent": "^0.65.2",
58
+ "@types/node": "^24.6.0",
51
59
  "esbuild": "^0.27.0",
52
- "tsx": "^4.20.6"
60
+ "tsx": "^4.20.6",
61
+ "typescript": "^5.9.3"
53
62
  },
54
63
  "engines": {
55
64
  "node": ">=20"
package/prompts/oracle.md CHANGED
@@ -8,17 +8,23 @@ Do not answer the user's request directly yet.
8
8
  Required workflow:
9
9
  1. Understand the request.
10
10
  2. Gather repo context first by reading files and searching the codebase.
11
- 3. Select the exact relevant files/directories for the oracle archive.
11
+ 3. Choose archive inputs for the oracle job.
12
12
  4. Craft a concise but complete oracle prompt for ChatGPT web.
13
13
  5. Call oracle_submit with the prompt and exact archive inputs.
14
14
  6. Stop immediately after dispatching the oracle job.
15
15
 
16
16
  Rules:
17
17
  - Always include an archive. Do not submit without context files.
18
- - Keep the archive narrowly scoped and relevant.
18
+ - By default, include the whole repository by passing `.`. Default archive exclusions apply automatically, including common bulky outputs and obvious credentials/private data like `.env` files, key material, credential dotfiles, local database files, and root `secrets/` directories.
19
+ - Only limit file selection if the user explicitly requests it, if the task is clearly scoped to a smaller area, or if privacy/sensitivity requires it.
20
+ - For very targeted asks like reviewing one function or explaining one stack trace, a smaller archive is preferable.
21
+ - If the request depends on git state or pending changes (for example code review, ship readiness, or release approval), create a tracked diff bundle file inside the repo (for example under `.pi/`) containing `git status` plus `git diff` output, include that file in the archive, and tell the oracle to use it because the `.git` directory is not included in oracle exports.
22
+ - When `files=["."]` and the post-exclusion archive is still too large, submit automatically prunes the largest nested directories matching generic generated-output names like `build/`, `dist/`, `out/`, `coverage/`, and `tmp/` outside obvious source roots like `src/` and `lib/` until the archive fits or no candidate remains. Successful submissions report what was pruned.
23
+ - If a submitted oracle job later fails because upload is rejected, retry with a smaller archive in this order: (1) remove the largest obviously irrelevant/generated content, (2) if still too large, include modified files plus adjacent files plus directly relevant subtrees, (3) if still too large, explain the cut or ask the user.
19
24
  - Prefer the configured default model/effort unless the task clearly needs something else.
20
25
  - Only use autoSwitchToThinking with the instant model family.
21
- - If oracle_submit fails, stop and report the error. Do not retry automatically.
26
+ - If `oracle_submit` itself fails because the local archive still exceeds the upload limit after default exclusions and automatic generic generated-output-dir pruning, or for any other submit-time error, stop and report the error. Do not retry automatically.
27
+ - If `oracle_submit` returns a queued job instead of an immediately dispatched one, treat that as success and end your turn exactly the same way.
22
28
  - After oracle_submit returns, end your turn. Do not keep working while the oracle runs.
23
29
 
24
30
  User request: