@introspection-ai/recipes 0.38.0 → 0.40.1
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/README.md +10 -4
- package/dist/channels/index.d.ts +2 -2
- package/dist/channels/index.d.ts.map +1 -1
- package/dist/channels/index.js +1 -1
- package/dist/channels/index.js.map +1 -1
- package/dist/channels/module.d.ts +18 -0
- package/dist/channels/module.d.ts.map +1 -1
- package/dist/channels/module.js +6 -0
- package/dist/channels/module.js.map +1 -1
- package/dist/child/session.d.ts +2 -0
- package/dist/child/session.d.ts.map +1 -1
- package/dist/child/session.js +3 -0
- package/dist/child/session.js.map +1 -1
- package/dist/connector-tools.d.ts +6 -0
- package/dist/connector-tools.d.ts.map +1 -1
- package/dist/connector-tools.js +26 -11
- package/dist/connector-tools.js.map +1 -1
- package/dist/documents/index.d.ts +4 -2
- package/dist/documents/index.d.ts.map +1 -1
- package/dist/documents/index.js +2 -1
- package/dist/documents/index.js.map +1 -1
- package/dist/documents/module.d.ts +44 -11
- package/dist/documents/module.d.ts.map +1 -1
- package/dist/documents/module.js +35 -24
- package/dist/documents/module.js.map +1 -1
- package/dist/documents/python.d.ts +30 -0
- package/dist/documents/python.d.ts.map +1 -0
- package/dist/documents/python.js +64 -0
- package/dist/documents/python.js.map +1 -0
- package/dist/extensions.d.ts +16 -0
- package/dist/extensions.d.ts.map +1 -1
- package/dist/extensions.js +12 -0
- package/dist/extensions.js.map +1 -1
- package/dist/mcp-chunks/{chunk-EQCSXVQ7.js → chunk-EZKOZO3F.js} +5184 -1309
- package/dist/mcp-daemon.js +1 -1
- package/dist/mcp-run-worker.js +1 -1
- package/dist/pi-extension.d.ts.map +1 -1
- package/dist/pi-extension.js +89 -14
- package/dist/pi-extension.js.map +1 -1
- package/dist/python.d.ts +56 -0
- package/dist/python.d.ts.map +1 -0
- package/dist/python.js +100 -0
- package/dist/python.js.map +1 -0
- package/dist/recipe/companions.d.ts +68 -0
- package/dist/recipe/companions.d.ts.map +1 -0
- package/dist/recipe/companions.js +149 -0
- package/dist/recipe/companions.js.map +1 -0
- package/dist/recipe/extensions.d.ts +6 -0
- package/dist/recipe/extensions.d.ts.map +1 -1
- package/dist/recipe/extensions.js +51 -14
- package/dist/recipe/extensions.js.map +1 -1
- package/dist/recipe/package.d.ts +72 -9
- package/dist/recipe/package.d.ts.map +1 -1
- package/dist/recipe/package.js +261 -76
- package/dist/recipe/package.js.map +1 -1
- package/dist/recipe/python.d.ts +152 -0
- package/dist/recipe/python.d.ts.map +1 -0
- package/dist/recipe/python.js +708 -0
- package/dist/recipe/python.js.map +1 -0
- package/dist/recipe/resolve.d.ts +3 -0
- package/dist/recipe/resolve.d.ts.map +1 -1
- package/dist/recipe/resolve.js +32 -16
- package/dist/recipe/resolve.js.map +1 -1
- package/dist/recipe/skills.d.ts +15 -1
- package/dist/recipe/skills.d.ts.map +1 -1
- package/dist/recipe/skills.js +26 -9
- package/dist/recipe/skills.js.map +1 -1
- package/dist/run-controller.d.ts +2 -0
- package/dist/run-controller.d.ts.map +1 -1
- package/dist/run-controller.js +3 -0
- package/dist/run-controller.js.map +1 -1
- package/dist/session.d.ts +8 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +37 -15
- package/dist/session.js.map +1 -1
- package/docs/agent-composition.md +2 -2
- package/docs/channels.md +55 -11
- package/docs/documents.md +109 -27
- package/docs/interactions.md +1 -1
- package/docs/pi-extension.md +4 -1
- package/docs/recipe-format.md +262 -62
- package/docs/slack.md +4 -5
- package/package.json +17 -7
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prepare the Python environments a Recipe declares with `pi.runtime.python`.
|
|
3
|
+
*
|
|
4
|
+
* Two kinds of declaration exist, and they never share an environment:
|
|
5
|
+
*
|
|
6
|
+
* - The Recipe's own declaration is its **shell environment**. Activating it
|
|
7
|
+
* sets `VIRTUAL_ENV` and `UV_PROJECT_ENVIRONMENT`, puts its `bin` first on
|
|
8
|
+
* `PATH` and removes `PYTHONHOME`, so the agent's shell tools run it.
|
|
9
|
+
* - A direct dependency's declaration is that **package's environment**. It is
|
|
10
|
+
* installed with `--no-editable`, never activated and never put on `PATH`;
|
|
11
|
+
* the host passes its interpreter to the package (documents formats receive
|
|
12
|
+
* it through `createAdapter({ python })`).
|
|
13
|
+
*
|
|
14
|
+
* `check` never writes and never touches the network. `sync` checks first and
|
|
15
|
+
* installs only an environment that is missing or outdated.
|
|
16
|
+
*/
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
18
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
19
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeSync, } from "node:fs";
|
|
20
|
+
import { homedir, hostname } from "node:os";
|
|
21
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
22
|
+
import { resolveRecipePackage } from "./companions.js";
|
|
23
|
+
import { installedRecipeDependencies, isPythonModuleName, readPiPackageManifest, recipeChannelPackageName, recipeDocumentPackageName, validateRecipePythonPackage, } from "./package.js";
|
|
24
|
+
/** Hosts read a fixed environment root from this variable (see `environmentRoot`). */
|
|
25
|
+
export const RECIPE_PYTHON_ROOT_ENV = "PI_RECIPES_PYTHON_ROOT";
|
|
26
|
+
export const UV_INSTALL_URL = "https://docs.astral.sh/uv/getting-started/installation/";
|
|
27
|
+
export class RecipePythonError extends Error {
|
|
28
|
+
constructor(message, options) {
|
|
29
|
+
super(message, options);
|
|
30
|
+
this.name = "RecipePythonError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** uv is not installed or not on PATH. */
|
|
34
|
+
export class RecipePythonUvMissingError extends RecipePythonError {
|
|
35
|
+
constructor(uv, options) {
|
|
36
|
+
super(`uv was not found (${uv}); it prepares the Recipe's Python environments. Install it: ${UV_INSTALL_URL}`, options);
|
|
37
|
+
this.name = "RecipePythonUvMissingError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** No interpreter satisfies the declared or required Python version. */
|
|
41
|
+
export class RecipePythonVersionError extends RecipePythonError {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "RecipePythonVersionError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Check mode found an environment missing or not matching its lockfile. */
|
|
48
|
+
export class RecipePythonOutdatedError extends RecipePythonError {
|
|
49
|
+
constructor(message) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "RecipePythonOutdatedError";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** A declared `imports` entry does not import in its environment. */
|
|
55
|
+
export class RecipePythonImportError extends RecipePythonError {
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "RecipePythonImportError";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
62
|
+
const ENVIRONMENT_FORMAT = "1";
|
|
63
|
+
const LOCK_TIMEOUT_MS = 15 * 60_000;
|
|
64
|
+
const LOCK_POLL_MS = 100;
|
|
65
|
+
const TAKEOVER_MARKER_STALE_MS = 60_000;
|
|
66
|
+
function readJson(path) {
|
|
67
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
68
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
69
|
+
? value
|
|
70
|
+
: {};
|
|
71
|
+
}
|
|
72
|
+
function packagePythonDeclaration(name, packageDir) {
|
|
73
|
+
const report = validateRecipePythonPackage(packageDir);
|
|
74
|
+
if (!report.valid) {
|
|
75
|
+
throw new RecipePythonError(`Dependency ${name} declares an invalid pi.runtime.python:\n${report.findings
|
|
76
|
+
.map((item) => `- ${item.message}`)
|
|
77
|
+
.join("\n")}`);
|
|
78
|
+
}
|
|
79
|
+
return report.python ? { kind: "package", owner: name, packageDir, python: report.python } : undefined;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Every `pi.runtime.python` the Recipe declares: its own, its direct
|
|
83
|
+
* dependencies', and that of each channel or document format package its
|
|
84
|
+
* `pi.channels` or `pi.documents` uses but does not list, found as the loader
|
|
85
|
+
* finds it (the copy installed alongside Recipes; see `resolveRecipePackage`).
|
|
86
|
+
*/
|
|
87
|
+
export function recipePythonDeclarations(recipeDir, options = {}) {
|
|
88
|
+
const root = resolve(recipeDir);
|
|
89
|
+
const declarations = [];
|
|
90
|
+
const manifest = readPiPackageManifest(root);
|
|
91
|
+
if (manifest.runtime?.python) {
|
|
92
|
+
declarations.push({
|
|
93
|
+
kind: "recipe",
|
|
94
|
+
owner: manifest.name,
|
|
95
|
+
packageDir: root,
|
|
96
|
+
python: manifest.runtime.python,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
for (const { name, packageDir } of installedRecipeDependencies(root, [
|
|
100
|
+
"dependencies",
|
|
101
|
+
"peerDependencies",
|
|
102
|
+
])) {
|
|
103
|
+
const declaration = packagePythonDeclaration(name, packageDir);
|
|
104
|
+
if (declaration)
|
|
105
|
+
declarations.push(declaration);
|
|
106
|
+
}
|
|
107
|
+
const used = [
|
|
108
|
+
...(manifest.channels ?? []).map((channel) => recipeChannelPackageName(channel.provider)),
|
|
109
|
+
...(manifest.documents ?? []).map((document) => recipeDocumentPackageName(document.format)),
|
|
110
|
+
];
|
|
111
|
+
for (const name of used) {
|
|
112
|
+
if (declarations.some((declaration) => declaration.kind === "package" && declaration.owner === name))
|
|
113
|
+
continue;
|
|
114
|
+
const resolved = resolveRecipePackage(root, name, options.hostDir);
|
|
115
|
+
const declaration = resolved && packagePythonDeclaration(name, resolved.packageDir);
|
|
116
|
+
if (declaration)
|
|
117
|
+
declarations.push(declaration);
|
|
118
|
+
}
|
|
119
|
+
return declarations;
|
|
120
|
+
}
|
|
121
|
+
function hashFile(hash, label, path) {
|
|
122
|
+
hash.update(`${label}\0`);
|
|
123
|
+
hash.update(readFileSync(path));
|
|
124
|
+
hash.update("\0");
|
|
125
|
+
}
|
|
126
|
+
const PIN_FILES = [".python-version", ".python-versions"];
|
|
127
|
+
/** uv's user configuration directory, which holds its global pin (`uv python pin --global`). */
|
|
128
|
+
function uvUserConfigDir(env) {
|
|
129
|
+
if (IS_WINDOWS)
|
|
130
|
+
return join(env.APPDATA || join(homedir(), "AppData", "Roaming"), "uv");
|
|
131
|
+
return join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"), "uv");
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* What uv picks the interpreter from when the declaration names no version:
|
|
135
|
+
* `UV_PYTHON`, a `.python-version` or `.python-versions` pin it discovers from
|
|
136
|
+
* the project, and the global pin. Every pin file from the project directory
|
|
137
|
+
* up to the filesystem root is included, a superset of where any uv version
|
|
138
|
+
* looks, so two projects that may select different interpreters never share a
|
|
139
|
+
* key. A declared version is passed as `--python`, which overrides all of
|
|
140
|
+
* them, so then none is read.
|
|
141
|
+
*/
|
|
142
|
+
function hashDiscoveredPins(hash, projectDir, env) {
|
|
143
|
+
hash.update(`UV_PYTHON\0${env.UV_PYTHON ?? ""}\0`);
|
|
144
|
+
// Labelled by level, not path, so Recipes with the same pins still share.
|
|
145
|
+
const dirs = [];
|
|
146
|
+
let level = 0;
|
|
147
|
+
for (let dir = resolve(projectDir);; dir = dirname(dir)) {
|
|
148
|
+
dirs.push([`pin ${level++}`, dir]);
|
|
149
|
+
if (dirname(dir) === dir)
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
dirs.push(["global pin", uvUserConfigDir(env)]);
|
|
153
|
+
for (const [label, dir] of dirs) {
|
|
154
|
+
for (const name of PIN_FILES) {
|
|
155
|
+
const path = join(dir, name);
|
|
156
|
+
if (existsSync(path) && statSync(path).isFile())
|
|
157
|
+
hashFile(hash, `${label} ${name}`, path);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** A `uv.lock` that installs a source from the local disk: editable, directory or path. */
|
|
162
|
+
const LOCAL_LOCK_SOURCE = /^\s*source\s*=\s*\{\s*(?:editable|directory|path)\s*=/m;
|
|
163
|
+
/**
|
|
164
|
+
* The shared-cache key: the environment kind, platform, `uv.lock`,
|
|
165
|
+
* `pyproject.toml` and the declared version range, plus the identity of any
|
|
166
|
+
* local source the environment installs, since uv does not re-install a local
|
|
167
|
+
* package whose version is unchanged:
|
|
168
|
+
*
|
|
169
|
+
* - Without a declared version, the pins uv would select the interpreter from
|
|
170
|
+
* (`UV_PYTHON`, `.python-version` files, the global pin): see
|
|
171
|
+
* {@link hashDiscoveredPins}.
|
|
172
|
+
*
|
|
173
|
+
* - A package environment installs that package's own project, so its key
|
|
174
|
+
* holds the package's realpath and `name@version`. Two installed copies of a
|
|
175
|
+
* dependency never share one environment, even with identical project files.
|
|
176
|
+
* - The Recipe's shell environment holds local code only when its project is
|
|
177
|
+
* itself a package (`[build-system]`, installed editable) or its lock names a
|
|
178
|
+
* local source; then the project's realpath is in the key. Otherwise Recipes
|
|
179
|
+
* with the same lock share one environment.
|
|
180
|
+
*/
|
|
181
|
+
function environmentHash(declaration, projectDir, lockfile, env) {
|
|
182
|
+
const hash = createHash("sha256");
|
|
183
|
+
hash.update(`recipes-python-env:${ENVIRONMENT_FORMAT}\0${declaration.kind}\0`);
|
|
184
|
+
hash.update(`${process.platform}-${process.arch}\0`);
|
|
185
|
+
hashFile(hash, "uv.lock", lockfile);
|
|
186
|
+
const pyproject = join(projectDir, "pyproject.toml");
|
|
187
|
+
hashFile(hash, "pyproject.toml", pyproject);
|
|
188
|
+
hash.update(`version\0${declaration.python.version ?? ""}\0`);
|
|
189
|
+
if (!declaration.python.version)
|
|
190
|
+
hashDiscoveredPins(hash, projectDir, env);
|
|
191
|
+
if (declaration.kind === "package") {
|
|
192
|
+
const packageJson = readJson(join(declaration.packageDir, "package.json"));
|
|
193
|
+
const version = typeof packageJson.version === "string" ? packageJson.version : "";
|
|
194
|
+
hash.update(`package\0${declaration.owner}@${version}\0${realpathSync(declaration.packageDir)}\0`);
|
|
195
|
+
}
|
|
196
|
+
else if (/^\s*\[build-system\]/m.test(readFileSync(pyproject, "utf8")) ||
|
|
197
|
+
LOCAL_LOCK_SOURCE.test(readFileSync(lockfile, "utf8"))) {
|
|
198
|
+
hash.update(`project\0${realpathSync(projectDir)}\0`);
|
|
199
|
+
}
|
|
200
|
+
return hash.digest("hex").slice(0, 32);
|
|
201
|
+
}
|
|
202
|
+
function environmentDirFor(declaration, projectDir, lockfile, options, env) {
|
|
203
|
+
if (options.environmentRoot) {
|
|
204
|
+
const root = resolve(options.environmentRoot);
|
|
205
|
+
return declaration.kind === "recipe"
|
|
206
|
+
? join(root, "python")
|
|
207
|
+
: join(root, "python-packages", ...declaration.owner.split("/"));
|
|
208
|
+
}
|
|
209
|
+
const home = (IS_WINDOWS ? env.USERPROFILE : env.HOME) || homedir();
|
|
210
|
+
return join(home, ".introspection", "python", environmentHash(declaration, projectDir, lockfile, env));
|
|
211
|
+
}
|
|
212
|
+
function binDir(environmentDir) {
|
|
213
|
+
return join(environmentDir, IS_WINDOWS ? "Scripts" : "bin");
|
|
214
|
+
}
|
|
215
|
+
function interpreterPath(environmentDir) {
|
|
216
|
+
return join(binDir(environmentDir), IS_WINDOWS ? "python.exe" : "python");
|
|
217
|
+
}
|
|
218
|
+
function sameDirectory(a, b) {
|
|
219
|
+
try {
|
|
220
|
+
return realpathSync(a) === realpathSync(b);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function environmentExists(environmentDir) {
|
|
227
|
+
return existsSync(join(environmentDir, "pyvenv.cfg")) && existsSync(interpreterPath(environmentDir));
|
|
228
|
+
}
|
|
229
|
+
function run(command, args, options) {
|
|
230
|
+
return new Promise((resolvePromise, reject) => {
|
|
231
|
+
const child = spawn(command, args, {
|
|
232
|
+
cwd: options.cwd,
|
|
233
|
+
env: options.env,
|
|
234
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
235
|
+
windowsHide: true,
|
|
236
|
+
});
|
|
237
|
+
let stdout = "";
|
|
238
|
+
let stderr = "";
|
|
239
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
|
|
240
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
|
|
241
|
+
child.once("error", reject);
|
|
242
|
+
child.once("close", (code) => resolvePromise({ code, stdout, stderr }));
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** A copy of `env` without `PYTHONHOME`, which would point a venv's Python at another stdlib. */
|
|
246
|
+
function withoutPythonHome(env) {
|
|
247
|
+
const copy = { ...env };
|
|
248
|
+
for (const key of Object.keys(copy)) {
|
|
249
|
+
if (key.toUpperCase() === "PYTHONHOME")
|
|
250
|
+
delete copy[key];
|
|
251
|
+
}
|
|
252
|
+
return copy;
|
|
253
|
+
}
|
|
254
|
+
function pathKey(env) {
|
|
255
|
+
return Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Apply a shell activation to `env` in place. Idempotent: the `bin`
|
|
259
|
+
* directory is moved to the front of `PATH`, never duplicated.
|
|
260
|
+
*/
|
|
261
|
+
export function activateRecipePython(env, activation) {
|
|
262
|
+
for (const key of Object.keys(env)) {
|
|
263
|
+
if (activation.unset.some((name) => name.toUpperCase() === key.toUpperCase()))
|
|
264
|
+
delete env[key];
|
|
265
|
+
}
|
|
266
|
+
Object.assign(env, activation.set);
|
|
267
|
+
const key = pathKey(env);
|
|
268
|
+
const rest = (env[key] ?? "").split(delimiter).filter((entry) => entry && entry !== activation.pathPrepend);
|
|
269
|
+
env[key] = [activation.pathPrepend, ...rest].join(delimiter);
|
|
270
|
+
return env;
|
|
271
|
+
}
|
|
272
|
+
function lastLines(text, count = 12) {
|
|
273
|
+
return text.trim().split(/\r?\n/).slice(-count).join("\n");
|
|
274
|
+
}
|
|
275
|
+
const INTERPRETER_PROBLEM = /no interpreter found|requires-python|python version|python downloads are not allowed|does not satisfy|incompatible with the project/i;
|
|
276
|
+
class Preparer {
|
|
277
|
+
options;
|
|
278
|
+
env;
|
|
279
|
+
uv;
|
|
280
|
+
uvChecked = false;
|
|
281
|
+
constructor(options) {
|
|
282
|
+
this.options = options;
|
|
283
|
+
this.env = options.env ?? process.env;
|
|
284
|
+
this.uv = options.uv ?? "uv";
|
|
285
|
+
}
|
|
286
|
+
async uvRun(args, cwd, environmentDir, variable = "UV_PROJECT_ENVIRONMENT") {
|
|
287
|
+
const env = withoutPythonHome(this.env);
|
|
288
|
+
for (const key of Object.keys(env)) {
|
|
289
|
+
if (["VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"].includes(key.toUpperCase()))
|
|
290
|
+
delete env[key];
|
|
291
|
+
}
|
|
292
|
+
if (environmentDir)
|
|
293
|
+
env[variable] = environmentDir;
|
|
294
|
+
try {
|
|
295
|
+
return await run(this.uv, args, { cwd, env });
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (error.code === "ENOENT") {
|
|
299
|
+
throw new RecipePythonUvMissingError(this.uv, { cause: error });
|
|
300
|
+
}
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
async ensureUv(cwd) {
|
|
305
|
+
if (this.uvChecked)
|
|
306
|
+
return;
|
|
307
|
+
const result = await this.uvRun(["--version"], cwd, "");
|
|
308
|
+
if (result.code !== 0) {
|
|
309
|
+
throw new RecipePythonUvMissingError(this.uv);
|
|
310
|
+
}
|
|
311
|
+
this.uvChecked = true;
|
|
312
|
+
}
|
|
313
|
+
commonArgs(declaration, projectDir) {
|
|
314
|
+
return [
|
|
315
|
+
"sync",
|
|
316
|
+
"--project",
|
|
317
|
+
projectDir,
|
|
318
|
+
"--frozen",
|
|
319
|
+
"--no-dev",
|
|
320
|
+
...(declaration.kind === "package" ? ["--no-editable"] : []),
|
|
321
|
+
...(declaration.python.version ? ["--python", declaration.python.version] : []),
|
|
322
|
+
...(this.options.allowPythonDownloads ? [] : ["--no-python-downloads"]),
|
|
323
|
+
];
|
|
324
|
+
}
|
|
325
|
+
/** `current`, `outdated` (exit 1 or missing), or `interpreter` (exit 2 naming the interpreter). */
|
|
326
|
+
async check(declaration, projectDir, environmentDir) {
|
|
327
|
+
// uv reports "Would create" with exit 0 for an environment that does not
|
|
328
|
+
// exist when nothing needs installing, so a missing one is checked here.
|
|
329
|
+
if (!environmentExists(environmentDir)) {
|
|
330
|
+
return { state: "outdated", detail: `${environmentDir} does not exist` };
|
|
331
|
+
}
|
|
332
|
+
const result = await this.uvRun([...this.commonArgs(declaration, projectDir), "--check", "--offline"], projectDir, environmentDir);
|
|
333
|
+
if (result.code === 0)
|
|
334
|
+
return this.checkInterpreter(declaration, projectDir, environmentDir);
|
|
335
|
+
const detail = lastLines(`${result.stdout}\n${result.stderr}`);
|
|
336
|
+
if (result.code === 1)
|
|
337
|
+
return { state: "outdated", detail };
|
|
338
|
+
if (result.code === 2 && INTERPRETER_PROBLEM.test(detail))
|
|
339
|
+
return { state: "interpreter", detail };
|
|
340
|
+
throw new RecipePythonError(`uv could not check the Python environment for ${declaration.owner} (exit ${result.code}):\n${detail}`);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Whether the environment's interpreter still satisfies the declared version
|
|
344
|
+
* and the project's `requires-python`. `uv sync --check` exits 0 even when
|
|
345
|
+
* the sync it stands for would replace the environment for another
|
|
346
|
+
* interpreter ("Would replace project environment"), so the check alone
|
|
347
|
+
* would accept an environment built for a version no longer declared. Ask
|
|
348
|
+
* uv which interpreter the request selects with this environment active: it
|
|
349
|
+
* prefers the active environment whenever that satisfies the request.
|
|
350
|
+
*
|
|
351
|
+
* The request is the declared version, else `UV_PYTHON`, which `uv sync`
|
|
352
|
+
* reads but `uv python find` does not. A request naming an interpreter path
|
|
353
|
+
* selects that path rather than the environment, so an interpreter found
|
|
354
|
+
* elsewhere is still accepted when it is the environment's base interpreter.
|
|
355
|
+
*/
|
|
356
|
+
async checkInterpreter(declaration, projectDir, environmentDir) {
|
|
357
|
+
const request = declaration.python.version ?? (this.env.UV_PYTHON || undefined);
|
|
358
|
+
const result = await this.uvRun([
|
|
359
|
+
"python",
|
|
360
|
+
"find",
|
|
361
|
+
...(request ? [request] : []),
|
|
362
|
+
"--project",
|
|
363
|
+
projectDir,
|
|
364
|
+
"--no-python-downloads",
|
|
365
|
+
"--offline",
|
|
366
|
+
], projectDir, environmentDir, "VIRTUAL_ENV");
|
|
367
|
+
const detail = lastLines(`${result.stdout}\n${result.stderr}`);
|
|
368
|
+
if (result.code === 2 && INTERPRETER_PROBLEM.test(detail))
|
|
369
|
+
return { state: "interpreter", detail };
|
|
370
|
+
if (result.code !== 0) {
|
|
371
|
+
throw new RecipePythonError(`uv could not check the Python interpreter for ${declaration.owner} (exit ${result.code}):\n${detail}`);
|
|
372
|
+
}
|
|
373
|
+
const found = result.stdout.trim().split(/\r?\n/).at(-1) ?? "";
|
|
374
|
+
// uv names the environment's interpreter by the path it was given; an
|
|
375
|
+
// interpreter elsewhere means the environment no longer satisfies the
|
|
376
|
+
// request, and a warning means it conflicts with `requires-python`.
|
|
377
|
+
if (!INTERPRETER_PROBLEM.test(result.stderr) &&
|
|
378
|
+
(sameDirectory(dirname(dirname(found)), environmentDir) ||
|
|
379
|
+
(await this.sameBaseInterpreter(found, environmentDir)))) {
|
|
380
|
+
return { state: "current", detail: "" };
|
|
381
|
+
}
|
|
382
|
+
const wanted = request ?? "the project's requires-python";
|
|
383
|
+
return {
|
|
384
|
+
state: "outdated",
|
|
385
|
+
detail: `the interpreter in ${environmentDir} does not satisfy ${wanted}${result.stderr.trim() ? `:\n${lastLines(result.stderr)}` : ""}`,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/** Whether `found` is the interpreter `environmentDir` was created from: same implementation, version and base prefix. */
|
|
389
|
+
async sameBaseInterpreter(found, environmentDir) {
|
|
390
|
+
if (!found)
|
|
391
|
+
return false;
|
|
392
|
+
const probe = async (python) => {
|
|
393
|
+
const script = "import os, sys; print(sys.implementation.name, sys.version_info[:3], os.path.realpath(sys.base_prefix))";
|
|
394
|
+
try {
|
|
395
|
+
const result = await run(python, ["-c", script], { cwd: environmentDir, env: withoutPythonHome(this.env) });
|
|
396
|
+
const line = result.stdout.trim();
|
|
397
|
+
return result.code === 0 && line ? line : undefined;
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
return undefined;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const [base, environment] = await Promise.all([probe(found), probe(interpreterPath(environmentDir))]);
|
|
404
|
+
return base !== undefined && base === environment;
|
|
405
|
+
}
|
|
406
|
+
versionError(declaration, detail) {
|
|
407
|
+
const wanted = declaration.python.version ? ` ${declaration.python.version}` : "";
|
|
408
|
+
return new RecipePythonVersionError(`No Python interpreter satisfies${wanted} for ${declaration.owner}${this.options.allowPythonDownloads ? "" : " (Python downloads are disabled)"}:\n${detail}`);
|
|
409
|
+
}
|
|
410
|
+
async sync(declaration, projectDir, environmentDir) {
|
|
411
|
+
const result = await this.uvRun([...this.commonArgs(declaration, projectDir), "--compile-bytecode"], projectDir, environmentDir);
|
|
412
|
+
if (result.code === 0)
|
|
413
|
+
return;
|
|
414
|
+
const detail = lastLines(`${result.stdout}\n${result.stderr}`);
|
|
415
|
+
if (INTERPRETER_PROBLEM.test(detail))
|
|
416
|
+
throw this.versionError(declaration, detail);
|
|
417
|
+
throw new RecipePythonError(`uv could not install the Python environment for ${declaration.owner} (exit ${result.code}):\n${detail}`);
|
|
418
|
+
}
|
|
419
|
+
async importCheck(declaration, environmentDir) {
|
|
420
|
+
const imports = declaration.python.imports;
|
|
421
|
+
if (imports.length === 0)
|
|
422
|
+
return;
|
|
423
|
+
const bad = imports.filter((name) => !isPythonModuleName(name));
|
|
424
|
+
if (bad.length > 0) {
|
|
425
|
+
throw new RecipePythonImportError(`${declaration.owner} declares imports that are not dotted Python module names: ${bad.join(", ")}`);
|
|
426
|
+
}
|
|
427
|
+
const script = [
|
|
428
|
+
"import importlib, sys",
|
|
429
|
+
"failed = []",
|
|
430
|
+
"for name in sys.argv[1:]:",
|
|
431
|
+
" try:",
|
|
432
|
+
" importlib.import_module(name)",
|
|
433
|
+
" except BaseException as error:",
|
|
434
|
+
" failed.append(f'{name}: {type(error).__name__}: {error}')",
|
|
435
|
+
"if failed:",
|
|
436
|
+
" sys.stderr.write('\\n'.join(failed) + '\\n')",
|
|
437
|
+
" sys.exit(1)",
|
|
438
|
+
].join("\n");
|
|
439
|
+
const env = withoutPythonHome(this.env);
|
|
440
|
+
let result;
|
|
441
|
+
try {
|
|
442
|
+
result = await run(interpreterPath(environmentDir), ["-c", script, ...imports], {
|
|
443
|
+
cwd: environmentDir,
|
|
444
|
+
env,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
throw new RecipePythonImportError(`${declaration.owner}: the interpreter in ${environmentDir} could not run: ${error.message}`);
|
|
449
|
+
}
|
|
450
|
+
if (result.code !== 0) {
|
|
451
|
+
throw new RecipePythonImportError(`${declaration.owner}: declared Python imports failed in ${environmentDir}:\n${lastLines(result.stderr)}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
async prepare(declaration) {
|
|
455
|
+
const projectDir = resolve(declaration.packageDir, declaration.python.project);
|
|
456
|
+
const lockfile = resolve(declaration.packageDir, declaration.python.lockfile);
|
|
457
|
+
if (!existsSync(join(projectDir, "pyproject.toml"))) {
|
|
458
|
+
throw new RecipePythonError(`${declaration.owner}: pi.runtime.python.project has no pyproject.toml: ${declaration.python.project}`);
|
|
459
|
+
}
|
|
460
|
+
if (!existsSync(lockfile)) {
|
|
461
|
+
throw new RecipePythonError(`${declaration.owner}: pi.runtime.python.lockfile does not exist: ${declaration.python.lockfile}`);
|
|
462
|
+
}
|
|
463
|
+
if (lockfile !== join(projectDir, "uv.lock")) {
|
|
464
|
+
// uv reads the lockfile beside pyproject.toml and has no flag naming another.
|
|
465
|
+
throw new RecipePythonError(`${declaration.owner}: pi.runtime.python.lockfile must be the project's uv.lock (${declaration.python.project}/uv.lock)`);
|
|
466
|
+
}
|
|
467
|
+
const environmentDir = environmentDirFor(declaration, projectDir, lockfile, this.options, this.env);
|
|
468
|
+
await this.ensureUv(projectDir);
|
|
469
|
+
let synced = false;
|
|
470
|
+
const first = await this.check(declaration, projectDir, environmentDir);
|
|
471
|
+
if (first.state !== "current") {
|
|
472
|
+
if (this.options.mode === "check") {
|
|
473
|
+
if (first.state === "interpreter")
|
|
474
|
+
throw this.versionError(declaration, first.detail);
|
|
475
|
+
throw new RecipePythonOutdatedError(`The Python environment for ${declaration.owner} is not prepared or does not match its uv.lock (${environmentDir}); the host must sync it before the session starts:\n${first.detail}`);
|
|
476
|
+
}
|
|
477
|
+
if (first.state === "interpreter" && !this.options.allowPythonDownloads) {
|
|
478
|
+
throw this.versionError(declaration, first.detail);
|
|
479
|
+
}
|
|
480
|
+
synced = await withEnvironmentLock(environmentDir, async () => {
|
|
481
|
+
// Another process may have finished the same environment while this one waited.
|
|
482
|
+
const again = await this.check(declaration, projectDir, environmentDir);
|
|
483
|
+
if (again.state === "current")
|
|
484
|
+
return false;
|
|
485
|
+
if (again.state === "interpreter" && !this.options.allowPythonDownloads) {
|
|
486
|
+
throw this.versionError(declaration, again.detail);
|
|
487
|
+
}
|
|
488
|
+
this.options.onSync?.({
|
|
489
|
+
owner: declaration.owner,
|
|
490
|
+
kind: declaration.kind,
|
|
491
|
+
environmentDir,
|
|
492
|
+
firstBuild: !environmentExists(environmentDir),
|
|
493
|
+
});
|
|
494
|
+
await this.sync(declaration, projectDir, environmentDir);
|
|
495
|
+
return true;
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
await this.importCheck(declaration, environmentDir);
|
|
499
|
+
return {
|
|
500
|
+
kind: declaration.kind,
|
|
501
|
+
owner: declaration.owner,
|
|
502
|
+
packageDir: declaration.packageDir,
|
|
503
|
+
projectDir,
|
|
504
|
+
lockfile,
|
|
505
|
+
environmentDir,
|
|
506
|
+
interpreter: interpreterPath(environmentDir),
|
|
507
|
+
imports: [...declaration.python.imports],
|
|
508
|
+
synced,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function lockGeneration(lockPath) {
|
|
513
|
+
try {
|
|
514
|
+
const fd = openSync(lockPath, "r");
|
|
515
|
+
try {
|
|
516
|
+
const stat = fstatSync(fd);
|
|
517
|
+
const owner = readFileSync(fd, "utf8");
|
|
518
|
+
const generation = createHash("sha256")
|
|
519
|
+
.update(`${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.size}\0${owner}`)
|
|
520
|
+
.digest("hex")
|
|
521
|
+
.slice(0, 32);
|
|
522
|
+
return { generation, owner };
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
closeSync(fd);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
if (error.code === "ENOENT")
|
|
530
|
+
return undefined;
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
/** Read the lock at `lockPath`; `undefined` when there is none. */
|
|
535
|
+
export function inspectEnvironmentLock(lockPath) {
|
|
536
|
+
const seen = lockGeneration(lockPath);
|
|
537
|
+
if (!seen)
|
|
538
|
+
return undefined;
|
|
539
|
+
let stale;
|
|
540
|
+
try {
|
|
541
|
+
const owner = JSON.parse(seen.owner);
|
|
542
|
+
if (owner.host === hostname() && typeof owner.pid === "number") {
|
|
543
|
+
try {
|
|
544
|
+
process.kill(owner.pid, 0);
|
|
545
|
+
stale = false;
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
stale = error.code === "ESRCH";
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
catch {
|
|
553
|
+
// Unreadable: a writer died between create and write, or the file is mid-write.
|
|
554
|
+
}
|
|
555
|
+
if (stale === undefined) {
|
|
556
|
+
try {
|
|
557
|
+
stale = Date.now() - statSync(lockPath).mtimeMs > LOCK_TIMEOUT_MS;
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
stale = false;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return { generation: seen.generation, stale };
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Remove the lock at `lockPath` only if it is still the `generation` a waiter
|
|
567
|
+
* inspected and judged stale. Returns whether it was removed.
|
|
568
|
+
*
|
|
569
|
+
* Two waiters can both judge one lock stale. Each must first create the
|
|
570
|
+
* takeover marker for that generation exclusively, so only one of them can
|
|
571
|
+
* remove it; the other sees the marker, or, once it is gone, a lock of a new
|
|
572
|
+
* generation, and leaves that lock alone. Nothing but the marker's holder
|
|
573
|
+
* removes a lock of that generation (its owner is gone), so the check and the
|
|
574
|
+
* removal cannot be split by another taker.
|
|
575
|
+
*/
|
|
576
|
+
export function takeOverStaleEnvironmentLock(lockPath, generation) {
|
|
577
|
+
const marker = `${lockPath}.takeover-${generation}`;
|
|
578
|
+
let fd;
|
|
579
|
+
try {
|
|
580
|
+
fd = openSync(marker, "wx");
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
if (error.code !== "EEXIST")
|
|
584
|
+
throw error;
|
|
585
|
+
// A marker outlives its few synchronous steps only when its taker died
|
|
586
|
+
// between them; clear it so the next attempt can take the lock over.
|
|
587
|
+
try {
|
|
588
|
+
if (Date.now() - statSync(marker).mtimeMs > TAKEOVER_MARKER_STALE_MS)
|
|
589
|
+
rmSync(marker, { force: true });
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
// Gone already.
|
|
593
|
+
}
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
closeSync(fd);
|
|
597
|
+
try {
|
|
598
|
+
if (lockGeneration(lockPath)?.generation !== generation)
|
|
599
|
+
return false;
|
|
600
|
+
rmSync(lockPath, { force: true });
|
|
601
|
+
return true;
|
|
602
|
+
}
|
|
603
|
+
finally {
|
|
604
|
+
rmSync(marker, { force: true });
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
/** Create the lock at `lockPath` if there is none. Returns the owner token on success. */
|
|
608
|
+
export function tryAcquireEnvironmentLock(lockPath) {
|
|
609
|
+
let fd;
|
|
610
|
+
try {
|
|
611
|
+
fd = openSync(lockPath, "wx");
|
|
612
|
+
}
|
|
613
|
+
catch (error) {
|
|
614
|
+
if (error.code === "EEXIST")
|
|
615
|
+
return undefined;
|
|
616
|
+
throw error;
|
|
617
|
+
}
|
|
618
|
+
const token = randomUUID();
|
|
619
|
+
try {
|
|
620
|
+
writeSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), token, at: new Date().toISOString() }));
|
|
621
|
+
}
|
|
622
|
+
finally {
|
|
623
|
+
closeSync(fd);
|
|
624
|
+
}
|
|
625
|
+
return token;
|
|
626
|
+
}
|
|
627
|
+
/** Remove the lock at `lockPath` only if it still carries `token`: never another owner's. */
|
|
628
|
+
export function releaseEnvironmentLock(lockPath, token) {
|
|
629
|
+
let owner;
|
|
630
|
+
try {
|
|
631
|
+
owner = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
if (owner.token !== token)
|
|
637
|
+
return false;
|
|
638
|
+
rmSync(lockPath, { force: true });
|
|
639
|
+
return true;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Serialise installs into one environment across processes with an
|
|
643
|
+
* exclusive-create lock file beside it. A lock whose owner is gone is taken
|
|
644
|
+
* over, by one waiter only (see `takeOverStaleEnvironmentLock`); one held
|
|
645
|
+
* longer than the timeout fails the wait. Only the lock this call created is
|
|
646
|
+
* removed when it finishes.
|
|
647
|
+
*/
|
|
648
|
+
export async function withEnvironmentLock(environmentDir, fn) {
|
|
649
|
+
mkdirSync(dirname(environmentDir), { recursive: true });
|
|
650
|
+
const lockPath = `${environmentDir}.lock`;
|
|
651
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
652
|
+
let token;
|
|
653
|
+
while ((token = tryAcquireEnvironmentLock(lockPath)) === undefined) {
|
|
654
|
+
const held = inspectEnvironmentLock(lockPath);
|
|
655
|
+
if (!held)
|
|
656
|
+
continue;
|
|
657
|
+
if (held.stale && takeOverStaleEnvironmentLock(lockPath, held.generation))
|
|
658
|
+
continue;
|
|
659
|
+
if (Date.now() > deadline) {
|
|
660
|
+
throw new RecipePythonError(`Timed out waiting for another process preparing ${environmentDir} (${lockPath})`);
|
|
661
|
+
}
|
|
662
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, LOCK_POLL_MS));
|
|
663
|
+
}
|
|
664
|
+
try {
|
|
665
|
+
return await fn();
|
|
666
|
+
}
|
|
667
|
+
finally {
|
|
668
|
+
releaseEnvironmentLock(lockPath, token);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Find and prepare every `pi.runtime.python` the Recipe at `recipeDir`
|
|
673
|
+
* declares: its own (the shell environment), each direct `dependencies` or
|
|
674
|
+
* `peerDependencies` entry Node resolves from the Recipe directory, and each
|
|
675
|
+
* companion channel or document format package the Recipe uses without
|
|
676
|
+
* listing it (each package in an environment of its own). Dev and transitive
|
|
677
|
+
* dependencies are not read.
|
|
678
|
+
*/
|
|
679
|
+
export async function prepareRecipePython(recipeDir, options) {
|
|
680
|
+
const declarations = recipePythonDeclarations(recipeDir, options.hostDir !== undefined ? { hostDir: options.hostDir } : {});
|
|
681
|
+
const preparer = new Preparer(options);
|
|
682
|
+
const packages = {};
|
|
683
|
+
let recipe;
|
|
684
|
+
// Sequential: uv already parallelises one install, and concurrent first
|
|
685
|
+
// builds would only compete for the same downloads.
|
|
686
|
+
for (const declaration of declarations) {
|
|
687
|
+
const environment = await preparer.prepare(declaration);
|
|
688
|
+
if (declaration.kind === "recipe") {
|
|
689
|
+
recipe = {
|
|
690
|
+
...environment,
|
|
691
|
+
kind: "recipe",
|
|
692
|
+
activation: {
|
|
693
|
+
set: {
|
|
694
|
+
VIRTUAL_ENV: environment.environmentDir,
|
|
695
|
+
UV_PROJECT_ENVIRONMENT: environment.environmentDir,
|
|
696
|
+
},
|
|
697
|
+
pathPrepend: binDir(environment.environmentDir),
|
|
698
|
+
unset: ["PYTHONHOME"],
|
|
699
|
+
},
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
packages[declaration.owner] = environment;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return { ...(recipe ? { recipe } : {}), packages };
|
|
707
|
+
}
|
|
708
|
+
//# sourceMappingURL=python.js.map
|