@unieai/rabi-tool-workspace-dependencies 0.2.1-rc.3 → 0.2.2-rc.5

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/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Arbeitsbereichsabhängigkeiten",
4
+ "description": "Geben Sie absolute Pfade zu den gebündelten Python-, Node.js- und pnpm-Laufzeiten an."
5
+ }
6
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Workspace dependencies",
4
+ "description": "Provide absolute paths to the bundled Python, Node.js, and pnpm runtimes."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Dependencias del espacio de trabajo",
4
+ "description": "Proporcione rutas absolutas a los tiempos de ejecución de Python, Node.js y pnpm incluidos."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Dépendances de l'espace de travail",
4
+ "description": "Fournissez des chemins absolus vers les environnements d'exécution Python, Node.js et pnpm fournis."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "ワークスペース依存関係",
4
+ "description": "組み込みの Python、Node.js、pnpm の絶対パスを提供します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Dependências do espaço de trabalho",
4
+ "description": "Forneça caminhos absolutos para os tempos de execução Python, Node.js e pnpm incluídos."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Зависимости рабочей области",
4
+ "description": "Укажите абсолютные пути к связанным средам выполнения Python, Node.js и pnpm."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "工作区依赖",
4
+ "description": "提供内置 Python、Node.js 和 pnpm 的绝对路径。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-tool-workspace-dependencies",
3
3
  "description": "The load_workspace_dependencies tool: absolute paths into a bundled Python, Node.js, and pnpm payload",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -13,19 +13,24 @@
13
13
  "types": "./lib/types/index.d.ts",
14
14
  "default": "./lib/index.js"
15
15
  },
16
+ "./locale/*.json": "./locale/*.json",
16
17
  "./package.json": "./package.json"
17
18
  },
18
19
  "files": [
20
+ "locale/*.json",
19
21
  "lib/index.js",
20
22
  "lib/types/**/*.d.ts",
23
+ "lib/types/**/*.d.ts.map",
24
+ "lib/**/*.js.map",
25
+ "src",
21
26
  "README.md"
22
27
  ],
23
28
  "license": "MIT",
24
29
  "peerDependencies": {
25
- "@unieai/rabi-tools": "0.2.1-rc.3",
26
- "@unieai/cordis": "4.0.5"
30
+ "@unieai/rabi-tools": "0.2.2-rc.5",
31
+ "@unieai/cordis": "4.1.0"
27
32
  },
28
33
  "dependencies": {
29
- "@unieai/schemastery": "3.18.5"
34
+ "@unieai/schemastery": "3.19.0"
30
35
  }
31
36
  }
package/src/index.ts ADDED
@@ -0,0 +1,322 @@
1
+ /** Model-facing query for a bundled Python, Node.js, and pnpm payload, in place or installed under the Harness home. */
2
+
3
+ import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rename, rm, stat, symlink } from 'node:fs/promises'
4
+ import { dirname, isAbsolute, join } from 'node:path'
5
+ import type { Context } from '@unieai/cordis'
6
+ import z from '@unieai/schemastery'
7
+ import { defineTool } from '@unieai/rabi-tools'
8
+
9
+ /** Cordis plugin identity. */
10
+ export const name = 'tool-workspace-dependencies'
11
+ /** Registry the tool registers into. */
12
+ export const inject = ['tools']
13
+
14
+ /** Payload location and optional installation directory. */
15
+ export interface Config {
16
+ /** Payload directory carrying `runtime.json` and `dependencies/`. */
17
+ readonly source: string
18
+ /**
19
+ * Installation directory under the Harness home. When set, the payload is copied there on the
20
+ * first call (the Desktop behavior); when omitted, the payload is used in place without copying,
21
+ * which suits read-only carriers such as container image layers.
22
+ */
23
+ readonly root?: string
24
+ }
25
+
26
+ /** Require a named payload source before the Loader activates the tool. */
27
+ export const Config: z<Config> = z.object({
28
+ source: z.string().min(1).required(),
29
+ root: z.string().min(1),
30
+ })
31
+
32
+ /** Canonical build metadata, independent of user-installed packages; legacy files are normalized on read. */
33
+ export interface PrimaryRuntimeManifest {
34
+ readonly desktopVersion: string
35
+ readonly platform: string
36
+ readonly arch: string
37
+ /** Locked payload identity; absent only in installations made before payload hashing. */
38
+ readonly payloadDigest?: string
39
+ /** Bundled Python interpreter version. */
40
+ readonly python: string
41
+ /** Absent when the payload ships no Node.js. */
42
+ readonly node?: string
43
+ /** Bundled pnpm version; requires a bundled Node.js executable. */
44
+ readonly pnpm?: string
45
+ /** All recorded Python distribution versions; empty for legacy files without a distribution map. */
46
+ readonly pythonPackages: Readonly<Record<string, string>>
47
+ }
48
+
49
+ /** Absolute entry points and bundled versions; pnpm runs through the returned Node executable. */
50
+ export interface WorkspaceDependencies {
51
+ readonly python: string
52
+ readonly node?: string
53
+ readonly pnpm?: string
54
+ readonly pythonPackages: string
55
+ readonly nodePackages?: string
56
+ /** Locked distribution versions; excludes packages users add to the installed environment. */
57
+ readonly pythonDistributions: Readonly<Record<string, string>>
58
+ }
59
+
60
+ const VERSION = /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/u
61
+ const PLATFORMS = ['win32', 'darwin', 'linux']
62
+
63
+ function isVersion(value: unknown): value is string {
64
+ return typeof value === 'string' && VERSION.test(value)
65
+ }
66
+
67
+ function isRecord(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
69
+ }
70
+
71
+ function isDistributionMap(value: unknown): value is Readonly<Record<string, string>> {
72
+ return isRecord(value) && Object.entries(value).every(([name, version]) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(name)
73
+ && typeof version === 'string' && /^\d[\w.!+-]*$/u.test(version))
74
+ }
75
+
76
+ /**
77
+ * Validate payload JSON and normalize legacy component fields to top-level versions.
78
+ * @param value - Untrusted decoded runtime.json contents.
79
+ * @returns Canonical metadata with one Python distribution map and no components field.
80
+ * @throws For malformed or mixed formats, duplicate distribution names, or inconsistent legacy metadata.
81
+ */
82
+ export function parsePrimaryRuntime(value: unknown): PrimaryRuntimeManifest {
83
+ if (!isRecord(value)) throw new Error('primary runtime: invalid metadata')
84
+ const legacy = value.components !== undefined
85
+ const versions = legacy ? value.components : value
86
+ if (!isRecord(versions) || (legacy && ['python', 'node', 'pnpm'].some(key => value[key] !== undefined))) {
87
+ throw new Error('primary runtime: invalid metadata')
88
+ }
89
+ const { desktopVersion, platform, arch, payloadDigest } = value
90
+ const { python, node, pnpm } = versions
91
+ const pythonPackages = value.pythonPackages === undefined && legacy ? {} : value.pythonPackages
92
+ if (typeof desktopVersion !== 'string' || desktopVersion.length === 0
93
+ || typeof platform !== 'string' || !PLATFORMS.includes(platform)
94
+ || typeof arch !== 'string' || !['x64', 'arm64'].includes(arch)
95
+ || !isVersion(python)
96
+ || (node !== undefined && !isVersion(node))
97
+ || (pnpm !== undefined && (!isVersion(pnpm) || node === undefined))
98
+ || (payloadDigest !== undefined && (typeof payloadDigest !== 'string' || !/^[a-f0-9]{64}$/u.test(payloadDigest)))
99
+ || !isDistributionMap(pythonPackages)) {
100
+ throw new Error('primary runtime: invalid metadata')
101
+ }
102
+ const entries = Object.entries(pythonPackages)
103
+ const distributions = new Map(entries.map(([name, version]) => [name.toLowerCase().replace(/[-_.]+/gu, '-'), version]))
104
+ if (distributions.size !== entries.length) throw new Error('primary runtime: invalid metadata')
105
+ // Only the old on-disk format duplicates these versions. New manifests use the distribution map alone.
106
+ if (legacy) {
107
+ for (const name of ['numpy', 'pandas'] as const) {
108
+ if (!isVersion(versions[name])) throw new Error('primary runtime: invalid metadata')
109
+ const version = distributions.get(name)
110
+ if (version !== undefined && version !== versions[name]) {
111
+ throw new Error(`primary runtime: conflicting ${name} distribution version`)
112
+ }
113
+ }
114
+ }
115
+ return {
116
+ desktopVersion, platform, arch,
117
+ ...(payloadDigest === undefined ? {} : { payloadDigest }),
118
+ python,
119
+ ...(node === undefined ? {} : { node }),
120
+ ...(pnpm === undefined ? {} : { pnpm }),
121
+ pythonPackages,
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Read and normalize build metadata without rewriting the source file.
127
+ * @param root - Installed or bundled primary runtime directory.
128
+ * @returns Validated top-level versions and target identifiers, including for legacy components manifests.
129
+ */
130
+ export async function readPrimaryRuntime(root: string): Promise<PrimaryRuntimeManifest> {
131
+ const value: unknown = JSON.parse(await readFile(join(root, 'runtime.json'), 'utf8'))
132
+ return parsePrimaryRuntime(value)
133
+ }
134
+
135
+ /**
136
+ * Identify POSIX interpreter aliases that can survive payload relocation.
137
+ * @param root - Payload directory.
138
+ * @param manifest - Validated payload metadata.
139
+ * @returns Relative alias paths mapped to their sibling interpreter filename; regular command files are omitted.
140
+ * @throws When an interpreter alias does not point directly to the versioned regular file.
141
+ */
142
+ export async function primaryRuntimePythonAliases(root: string, manifest: PrimaryRuntimeManifest): Promise<ReadonlyMap<string, string>> {
143
+ const aliases = new Map<string, string>()
144
+ if (manifest.platform === 'win32') return aliases
145
+ const interpreter = `python${manifest.python.split('.').slice(0, 2).join('.')}`
146
+ for (const name of ['python', 'python3']) {
147
+ const path = `dependencies/python/bin/${name}`
148
+ let entry
149
+ try { entry = await lstat(join(root, path)) } catch (error) {
150
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
151
+ throw error
152
+ }
153
+ if (!entry.isSymbolicLink()) continue
154
+ if (await readlink(join(root, path)) !== interpreter
155
+ || !(await lstat(join(root, 'dependencies/python/bin', interpreter))).isFile()) {
156
+ throw new Error(`primary runtime: invalid Python alias ${path}`)
157
+ }
158
+ aliases.set(path, interpreter)
159
+ }
160
+ return aliases
161
+ }
162
+
163
+ /**
164
+ * Copy a payload, retaining only validated Python interpreter aliases as relative links.
165
+ * @param source - Payload directory; all other links are materialized.
166
+ * @param destination - Empty destination owned by the caller.
167
+ * @param manifest - Validated source metadata.
168
+ * @returns Resolves after every copied file and interpreter alias is available independently of the source.
169
+ */
170
+ export async function copyPrimaryRuntime(source: string, destination: string, manifest: PrimaryRuntimeManifest): Promise<void> {
171
+ const aliases = await primaryRuntimePythonAliases(source, manifest)
172
+ const excluded = new Set([...aliases.keys()].map(path => join(source, path)))
173
+ await cp(source, destination, { recursive: true, dereference: true, filter: path => !excluded.has(path) })
174
+ for (const [path, target] of aliases) await symlink(target, join(destination, path))
175
+ }
176
+
177
+ /**
178
+ * Resolve platform-specific interpreter and library locations without changing the environment.
179
+ * @param root - Absolute payload or installation directory.
180
+ * @param manifest - Validated runtime metadata.
181
+ * @returns Absolute paths for explicit script execution and recorded bundled Python versions.
182
+ */
183
+ export function workspaceDependencyPaths(root: string, manifest: PrimaryRuntimeManifest): WorkspaceDependencies {
184
+ const dependencies = join(root, 'dependencies')
185
+ const windows = manifest.platform === 'win32'
186
+ const node = manifest.node === undefined ? {} : {
187
+ node: join(dependencies, 'node', 'bin', windows ? 'node.exe' : 'node'),
188
+ nodePackages: join(dependencies, 'node', 'node_modules'),
189
+ }
190
+ const pnpm = manifest.pnpm === undefined ? {} : { pnpm: join(dependencies, 'pnpm', 'bin', 'pnpm.mjs') }
191
+ return {
192
+ python: join(dependencies, 'python', ...(windows ? ['python.exe'] : ['bin', 'python3'])),
193
+ ...node,
194
+ ...pnpm,
195
+ pythonPackages: join(dependencies, 'python', ...(windows ? ['Lib'] : ['lib', `python${manifest.python.split('.').slice(0, 2).join('.')}`]), 'site-packages'),
196
+ pythonDistributions: manifest.pythonPackages,
197
+ }
198
+ }
199
+
200
+ async function validatePayloadEntries(paths: WorkspaceDependencies): Promise<void> {
201
+ for (const [path, kind] of [
202
+ [paths.python, 'file'], [paths.node, 'file'], [paths.pnpm, 'file'],
203
+ [paths.pythonPackages, 'directory'], [paths.nodePackages, 'directory'],
204
+ ] as const) {
205
+ if (path === undefined) continue
206
+ const entry = await stat(path)
207
+ if (!(kind === 'file' ? entry.isFile() : entry.isDirectory())) {
208
+ throw new Error(`primary runtime: expected ${kind} at ${path}`)
209
+ }
210
+ }
211
+ }
212
+
213
+ async function exists(path: string): Promise<boolean> {
214
+ try {
215
+ if ((await lstat(path)).isSymbolicLink()) throw new Error(`primary runtime: installation path is a filesystem link: ${path}`)
216
+ return true
217
+ } catch (error) {
218
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
219
+ throw error
220
+ }
221
+ }
222
+
223
+ async function compatibleManifest(source: string): Promise<PrimaryRuntimeManifest> {
224
+ const manifest = await readPrimaryRuntime(source)
225
+ if (manifest.platform !== process.platform || manifest.arch !== process.arch) throw new Error('primary runtime: incompatible platform or architecture')
226
+ return manifest
227
+ }
228
+
229
+ /**
230
+ * Use a payload where it lies: validate its metadata and entries, copying nothing.
231
+ * @param source - Payload directory, typically a read-only carrier.
232
+ * @returns Paths into the payload itself.
233
+ */
234
+ export async function resolvePrimaryRuntime(source: string): Promise<WorkspaceDependencies> {
235
+ const manifest = await compatibleManifest(source)
236
+ await primaryRuntimePythonAliases(source, manifest)
237
+ const paths = workspaceDependencyPaths(source, manifest)
238
+ await validatePayloadEntries(paths)
239
+ return paths
240
+ }
241
+
242
+ /**
243
+ * Install the application-owned payload locally, retaining a complete previous tree on copy failure.
244
+ * @param source - Payload carried by the current installation.
245
+ * @param root - Fixed primary runtime directory under the Harness home.
246
+ * @returns Paths into the installed payload; no PATH or package-manager configuration is changed.
247
+ */
248
+ export async function installPrimaryRuntime(source: string, root: string): Promise<WorkspaceDependencies> {
249
+ const manifest = await compatibleManifest(source)
250
+ await mkdir(dirname(root), { recursive: true })
251
+ const previous = `${root}.previous`
252
+ const previousExists = await exists(previous)
253
+ const rootExists = await exists(root)
254
+ if (!rootExists && previousExists) await rename(previous, root)
255
+ if (await exists(join(root, 'runtime.json')) && JSON.stringify(await readPrimaryRuntime(root)) === JSON.stringify(manifest)) {
256
+ await primaryRuntimePythonAliases(root, manifest)
257
+ const paths = workspaceDependencyPaths(root, manifest)
258
+ await validatePayloadEntries(paths)
259
+ return paths
260
+ }
261
+ const staging = await mkdtemp(join(dirname(root), '.primary-runtime-'))
262
+ try {
263
+ await copyPrimaryRuntime(source, staging, manifest)
264
+ const paths = workspaceDependencyPaths(staging, manifest)
265
+ await validatePayloadEntries(paths)
266
+ await rm(previous, { recursive: true, force: true })
267
+ const replacing = await exists(root)
268
+ if (replacing) await rename(root, previous)
269
+ try { await rename(staging, root) } catch (error) {
270
+ if (replacing) await rename(previous, root)
271
+ throw error
272
+ }
273
+ await rm(previous, { recursive: true, force: true })
274
+ } finally {
275
+ await rm(staging, { recursive: true, force: true })
276
+ }
277
+ return workspaceDependencyPaths(root, manifest)
278
+ }
279
+
280
+ /**
281
+ * Register the read-only path query; the first invocation prepares (or merely validates) the payload.
282
+ * @param ctx - Tool registry owner.
283
+ * @param config - Payload location and optional installation directory.
284
+ */
285
+ export function apply(ctx: Context, config: Config): void {
286
+ if (!isAbsolute(config.source) || (config.root !== undefined && !isAbsolute(config.root))) {
287
+ throw new Error('workspace dependencies: source and root must be absolute paths')
288
+ }
289
+ let preparation: Promise<WorkspaceDependencies> | undefined
290
+ ctx.effect(() => async () => {
291
+ // Tool execution reports preparation failures; disposal only waits for filesystem work to settle.
292
+ await preparation?.catch(() => undefined)
293
+ })
294
+ ctx.tools.register(defineTool({
295
+ name: 'load_workspace_dependencies',
296
+ description: 'Get absolute paths to bundled Python and library directories, plus bundled Python distribution versions. Node.js and pnpm paths are included when the payload provides them. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml, and XlsxWriter. Use these libraries for Office files unless the user or workspace instructions select another environment. When Node.js and pnpm paths are returned, run pnpm with that Node executable and pnpm script path. This does not change PATH or package-manager settings.',
297
+ parameters: {},
298
+ output: {
299
+ schema: {
300
+ type: 'object', additionalProperties: false,
301
+ properties: {
302
+ python: { type: 'string', required: true },
303
+ node: { type: 'string', description: 'Absent when the payload ships no Node.js.' },
304
+ pnpm: { type: 'string', description: 'Absent when the payload ships no pnpm.' },
305
+ pythonPackages: { type: 'string', required: true },
306
+ nodePackages: { type: 'string', description: 'Absent when the payload ships no Node.js.' },
307
+ pythonDistributions: { type: 'object', additionalProperties: true, required: true, description: 'Bundled distribution names and versions recorded in runtime.json; excludes user-installed additions.' },
308
+ },
309
+ },
310
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, undefined, 2) }],
311
+ },
312
+ execute: () => {
313
+ preparation ??= (config.root === undefined ? resolvePrimaryRuntime(config.source) : installPrimaryRuntime(config.source, config.root))
314
+ .catch((error: unknown) => {
315
+ preparation = undefined
316
+ throw error
317
+ })
318
+ return preparation
319
+ },
320
+ presentCall: () => ({ card: 'generic', title: 'Load workspace dependencies', kind: 'read' }),
321
+ }))
322
+ }