agent-plugin-lifecycle 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +102 -2
- package/bin/cli.js +2 -0
- package/config/config.example.json +22 -0
- package/dist/cjs/apm.d.cts +19 -0
- package/dist/cjs/apm.d.ts +19 -0
- package/dist/cjs/apm.js +313 -0
- package/dist/cjs/apm.js.map +1 -0
- package/dist/cjs/cli.d.cts +1 -0
- package/dist/cjs/cli.d.ts +1 -0
- package/dist/cjs/cli.js +366 -0
- package/dist/cjs/cli.js.map +1 -0
- package/dist/cjs/config.d.cts +16 -0
- package/dist/cjs/config.d.ts +16 -0
- package/dist/cjs/config.js +251 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/index.d.cts +6 -0
- package/dist/cjs/index.d.ts +6 -0
- package/dist/cjs/index.js +34 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/runner.d.cts +19 -0
- package/dist/cjs/runner.d.ts +19 -0
- package/dist/cjs/runner.js +1157 -0
- package/dist/cjs/runner.js.map +1 -0
- package/dist/esm/apm.d.ts +19 -0
- package/dist/esm/apm.js +121 -0
- package/dist/esm/apm.js.map +1 -0
- package/dist/esm/cli.d.ts +1 -0
- package/dist/esm/cli.js +70 -0
- package/dist/esm/cli.js.map +1 -0
- package/dist/esm/config.d.ts +16 -0
- package/dist/esm/config.js +74 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/index.d.ts +6 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/runner.d.ts +19 -0
- package/dist/esm/runner.js +248 -0
- package/dist/esm/runner.js.map +1 -0
- package/package.json +62 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/runner.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport spawn from 'cross-spawn-cb';\nimport lockfile from 'proper-lockfile';\nimport { type LockedPlugin, loadLock, localEventName, matchesSource, samePath, sourceParts } from './apm.js';\nimport { loadConfig, type PluginPolicy, recordId } from './config.js';\n\nexport type Mode = 'run' | 'check';\nexport interface LifecycleEvent {\n schema_version: 1;\n event: 'post-install' | 'post-update' | 'post-uninstall';\n scope: 'user';\n packages: { name: string; reference: string | null }[];\n}\ninterface State {\n version: 1;\n receipts: Record<string, string>;\n}\nexport interface RunOptions {\n home?: string;\n apmHome?: string;\n configPath?: string;\n environment?: NodeJS.ProcessEnv;\n output?: (line: string) => void;\n event?: LifecycleEvent;\n}\nfunction inside(root: string, child: string): boolean {\n const subpath = relative(root, child);\n return subpath === '' || (subpath !== '..' && !subpath.startsWith(`..${sep}`) && !isAbsolute(subpath));\n}\nasync function existingWithin(root: string, path: string, label: string): Promise<string> {\n const rootReal = await realpath(root);\n const candidate = resolve(rootReal, path);\n if (!inside(rootReal, candidate)) throw new Error(`${label} escapes ${root}`);\n const candidateReal = await realpath(candidate);\n if (!inside(rootReal, candidateReal)) throw new Error(`${label} resolves outside ${root}`);\n return candidateReal;\n}\nfunction pluginRoot(plugin: LockedPlugin, apmHome: string): string {\n return join(apmHome, 'apm_modules', plugin.repo, plugin.path);\n}\nasync function destinations(plugin: LockedPlugin, policy: PluginPolicy, home: string, apmHome: string): Promise<string[]> {\n const output = new Set<string>();\n const root = pluginRoot(plugin, apmHome);\n if (!policy.skill) {\n output.add(await existingWithin(join(apmHome, 'apm_modules'), join(plugin.repo, plugin.path), 'kept plugin'));\n if (plugin.nativePluginRoot) {\n const nativeBase = join(home, '.agents', 'plugins');\n if (plugin.nativePluginRoot.startsWith('.agents/plugins/')) output.add(await existingWithin(nativeBase, plugin.nativePluginRoot.slice('.agents/plugins/'.length), 'native plugin'));\n }\n } else {\n try {\n output.add(await existingWithin(root, `skills/${policy.skill}`, `kept skill ${policy.skill}`));\n } catch (error) {\n if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;\n }\n if (plugin.nativePluginRoot?.startsWith('.agents/plugins/')) {\n const nativeRoot = plugin.nativePluginRoot.slice('.agents/plugins/'.length);\n try {\n output.add(await existingWithin(join(home, '.agents', 'plugins'), `${nativeRoot}/skills/${policy.skill}`, `native skill ${policy.skill}`));\n } catch (error) {\n if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')) throw error;\n }\n }\n for (const file of plugin.deployedFiles) {\n const parts = file.split('/');\n const index = parts.lastIndexOf('skills');\n if (index < 0 || parts[index + 1] !== policy.skill) continue;\n const deployment = parts.slice(0, index + 2).join('/');\n const prefix = ['.agents/skills/', '.hermes/skills/', '.claude/skills/'].find((candidate) => deployment.startsWith(candidate));\n if (prefix) output.add(await existingWithin(home, deployment, `skill ${policy.skill}`));\n }\n if (output.size === 0) throw new Error(`no deployed copy found for skill ${policy.skill}`);\n }\n return [...output];\n}\nasync function readState(path: string): Promise<State> {\n if (!existsSync(path)) return { version: 1, receipts: {} };\n const value: unknown = JSON.parse(await readFile(path, 'utf8'));\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('state must be an object');\n const item = value as Record<string, unknown>;\n if (item.version !== 1 || !item.receipts || typeof item.receipts !== 'object' || Array.isArray(item.receipts)) throw new Error('unsupported state format');\n if (Object.values(item.receipts).some((receipt) => typeof receipt !== 'string')) throw new Error('invalid state receipt');\n return item as unknown as State;\n}\nasync function saveState(path: string, state: State): Promise<void> {\n const temp = join(dirname(path), `.state-${process.pid}-${Date.now()}.tmp`);\n try {\n await writeFile(temp, `${JSON.stringify(state, null, 2)}\\n`, { mode: 0o600, flag: 'wx' });\n await rename(temp, path);\n } catch (error) {\n try {\n await unlink(temp);\n } catch {\n /* preserve original error */\n }\n throw error;\n }\n}\nfunction receiptKey(policy: PluginPolicy, destination: string): string {\n return JSON.stringify([recordId(policy), destination]);\n}\nfunction digest(policy: PluginPolicy, command: string): string {\n return createHash('sha256')\n .update(JSON.stringify([recordId(policy), command]))\n .digest('hex');\n}\n// The platform shell runs the configured string as written, as with npm and Node's `shell` option.\nasync function execute(command: string, cwd: string, environment: NodeJS.ProcessEnv): Promise<void> {\n await spawn(command, [], { cwd, env: environment, stdio: ['ignore', 'inherit', 'inherit'], shell: true });\n}\nfunction lockLoadError(error: unknown): boolean {\n return !!error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\nexport async function runLifecycle(mode: Mode, options: RunOptions = {}): Promise<number> {\n const home = resolve(options.home ?? homedir());\n const apmHome = resolve(options.apmHome ?? join(home, '.apm'));\n const configPath = options.configPath ?? join(home, '.config', 'agent-plugin-lifecycle', 'config.json');\n const environment = options.environment ?? process.env;\n const output = options.output ?? console.log;\n const config = await loadConfig(configPath);\n let locked: LockedPlugin[];\n try {\n locked = await loadLock(join(apmHome, 'apm.lock.yaml'));\n } catch (error) {\n if (mode === 'run' && options.event?.event === 'post-uninstall' && lockLoadError(error)) {\n const apmDirectory = await stat(apmHome);\n if (!apmDirectory.isDirectory()) throw error;\n locked = [];\n } else throw error;\n }\n const statePath = join(dirname(configPath), 'state.json');\n if (mode === 'run') await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });\n const release = mode === 'run' ? await lockfile.lock(dirname(statePath), { realpath: false }) : undefined;\n try {\n const state = await readState(statePath);\n let failed = 0;\n if (mode === 'run' && options.event?.event === 'post-uninstall') {\n const eventNames = new Set(options.event.packages.map(({ name }) => name));\n for (const policy of config.plugins) {\n const id = recordId(policy);\n const receiptKeys = Object.keys(state.receipts).filter((key) => {\n try {\n return JSON.parse(key)[0] === id;\n } catch {\n return false;\n }\n });\n if (!receiptKeys.length) continue;\n const sourceCandidate =\n policy.source.startsWith('.') || isAbsolute(policy.source) ? locked.find((plugin) => plugin.localPath !== undefined && samePath(policy.source, plugin.localPath)) : locked.find((plugin) => matchesSource(policy.source, plugin) && (plugin.path === (policy.path ?? '.') || plugin.localPath !== undefined));\n const sourcePartsValue = sourceParts(policy.source);\n const removedNameMatch =\n eventNames.has(sourceCandidate?.repo ?? '') ||\n eventNames.has(sourceCandidate ? `${sourceCandidate.host}/${sourceCandidate.repo}` : '') ||\n eventNames.has(sourcePartsValue?.repo ?? '') ||\n eventNames.has(sourcePartsValue ? `${sourcePartsValue.host}/${sourcePartsValue.repo}` : '') ||\n // APM names a removed subfolder plugin `owner/repo/<folder>` (install and update events name it `owner/repo`); exact match only, so removing one folder never matches another plugin of the repository\n (!!sourcePartsValue && !!policy.path && policy.path !== '.' && (eventNames.has(`${sourcePartsValue.repo}/${policy.path}`) || eventNames.has(`${sourcePartsValue.host}/${sourcePartsValue.repo}/${policy.path}`))) ||\n eventNames.has(localEventName(policy.source)) ||\n eventNames.has(policy.source);\n const anyStillInstalled = locked.some((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (anyStillInstalled || !removedNameMatch) continue;\n const command = policy['post-uninstall'];\n if (!command) {\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n continue;\n }\n try {\n await execute(command, home, environment);\n for (const key of receiptKeys) delete state.receipts[key];\n await saveState(statePath, state);\n output(`cleaned ${id}`);\n } catch (error) {\n output(`failed cleanup ${id}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n return failed ? 1 : 0;\n }\n if (mode === 'run' && !options.event) throw new Error('run requires an APM event');\n const event = options.event?.event ?? 'post-install';\n for (const policy of config.plugins) {\n const command = event === 'post-update' ? (policy['post-update'] ?? policy['post-install']) : policy['post-install'];\n if (!command) continue;\n const matches = locked.filter((plugin) => matchesSource(policy.source, plugin) && plugin.path === (policy.path ?? '.'));\n if (matches.length > 1) {\n output(`failed ambiguous source/path record ${recordId(policy)}`);\n failed++;\n continue;\n }\n if (!matches.length) {\n output(`skipped source not installed ${recordId(policy)}`);\n continue;\n }\n const plugin = matches[0];\n try {\n const found = await destinations(plugin, policy, home, apmHome);\n for (const destination of found) {\n const key = receiptKey(policy, destination);\n if (mode === 'check') {\n const validDigests = [policy['post-install'], policy['post-update']].filter((item): item is string => !!item).map((item) => digest(policy, item));\n const ready = validDigests.includes(state.receipts[key]);\n output(`${ready ? 'ok' : 'missing'} ${recordId(policy)} ${destination}`);\n if (!ready) failed++;\n } else {\n delete state.receipts[key];\n await saveState(statePath, state);\n await execute(command, destination, environment);\n state.receipts[key] = digest(policy, command);\n await saveState(statePath, state);\n output(`ran ${recordId(policy)} ${destination}`);\n }\n }\n } catch (error) {\n output(`failed ${recordId(policy)}: ${error instanceof Error ? error.message : String(error)}`);\n failed++;\n }\n }\n return failed ? 1 : 0;\n } finally {\n await release?.();\n }\n}\n"],"names":["runLifecycle","inside","root","child","subpath","relative","startsWith","sep","isAbsolute","existingWithin","path","label","rootReal","candidate","candidateReal","realpath","resolve","Error","pluginRoot","plugin","apmHome","join","repo","destinations","policy","home","output","nativeBase","error","nativeRoot","Set","skill","add","nativePluginRoot","slice","length","code","file","parts","index","deployment","prefix","split","lastIndexOf","find","deployedFiles","size","readState","value","item","existsSync","version","receipts","JSON","parse","readFile","Array","isArray","Object","values","some","receipt","saveState","state","temp","dirname","Date","process","pid","now","writeFile","stringify","mode","flag","rename","unlink","receiptKey","destination","recordId","digest","command","createHash","update","execute","cwd","environment","spawn","env","stdio","shell","lockLoadError","options","configPath","config","locked","apmDirectory","statePath","release","failed","eventNames","event","homedir","console","log","loadConfig","loadLock","stat","isDirectory","mkdir","recursive","lockfile","lock","undefined","packages","map","name","id","receiptKeys","sourceCandidate","sourcePartsValue","removedNameMatch","anyStillInstalled","key","keys","filter","source","localPath","samePath","matchesSource","sourceParts","has","host","localEventName","message","String","plugins","matches","found","validDigests","ready","includes"],"mappings":";;;;+BAqHsBA;;;eAAAA;;;0BArHK;sBACA;wBACgD;sBACnD;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D,SAAQ,KAAe,OAAZqD;;;oCAbjC;;;;;;;;;;;;oCAAA;oCAAA;;;;;;;6CAAA,6BAAA;4CAAA;;;4CAAA;kDAAA;;;;;;;;;;;;oCAgBEjD;oCACPF,OAAO,AAAC,UAA8BE,OAArBkD,IAAAA,gBAAQ,EAACtD,SAAQ,MAA2D,OAAvDI,AAAK,YAALA,OAAiBX,SAAQW,MAAMyG,OAAO,GAAGC,OAAO1G;oCACtFsE;;;;;;;;;;;oBAEJ;oBApCK,aAAgBL,OAAO0C,OAAO;;;2BAA9B,8BAAA,SAAA;;;;;;;;;;;;oBAAA;;;;;;;;;;;;oBAAA;oBAAA;;;;;;;6BAAA,8BAAA;4BAAA;;;4BAAA;kCAAA;;;;;;;oBAqCL;;wBAAOrC,SAAS,IAAI;;;oBAEpB;;wBAAMD,oBAAAA,8BAAAA;;;oBAAN;;;;;;;;;;IAEJ"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface LockedPlugin {
|
|
2
|
+
host: string;
|
|
3
|
+
repo: string;
|
|
4
|
+
path: string;
|
|
5
|
+
revision: string;
|
|
6
|
+
localPath?: string;
|
|
7
|
+
nativePluginRoot?: string;
|
|
8
|
+
deployedFiles: string[];
|
|
9
|
+
}
|
|
10
|
+
export declare function sourceParts(source: string): {
|
|
11
|
+
host: string;
|
|
12
|
+
repo: string;
|
|
13
|
+
} | undefined;
|
|
14
|
+
export declare function samePath(left: string, right: string, platform?: NodeJS.Platform): boolean;
|
|
15
|
+
export declare function matchesSource(policySource: string, plugin: LockedPlugin, platform?: NodeJS.Platform): boolean;
|
|
16
|
+
export declare function localEventName(source: string): string;
|
|
17
|
+
export declare function lockIdentity(plugin: LockedPlugin): string;
|
|
18
|
+
export declare function parseLock(value: unknown): LockedPlugin[];
|
|
19
|
+
export declare function loadLock(path: string): Promise<LockedPlugin[]>;
|
package/dist/esm/apm.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, posix, win32 } from 'node:path';
|
|
3
|
+
import { parse } from 'yaml';
|
|
4
|
+
function record(value, label) {
|
|
5
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
function requiredString(value, label) {
|
|
9
|
+
if (typeof value !== 'string' || !value) throw new Error(`${label} must be a nonempty string`);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function safePath(value, label, dot = false) {
|
|
13
|
+
const path = requiredString(value, label);
|
|
14
|
+
if (dot && path === '.') return path;
|
|
15
|
+
if (path.startsWith('/') || path.includes('\\') || /^[A-Za-z]:/.test(path) || path.split('/').some((part)=>!part || part === '.' || part === '..')) throw new Error(`${label} contains an unsafe path segment`);
|
|
16
|
+
return path;
|
|
17
|
+
}
|
|
18
|
+
export function sourceParts(source) {
|
|
19
|
+
let host;
|
|
20
|
+
let path;
|
|
21
|
+
const scp = source.includes('://') ? null : /^(?:[^@/:]+@)?([^/:]+):(.+)$/.exec(source);
|
|
22
|
+
if (scp) {
|
|
23
|
+
host = scp[1];
|
|
24
|
+
path = scp[2];
|
|
25
|
+
} else {
|
|
26
|
+
try {
|
|
27
|
+
const url = new URL(source);
|
|
28
|
+
if (![
|
|
29
|
+
'https:',
|
|
30
|
+
'ssh:',
|
|
31
|
+
'http:'
|
|
32
|
+
].includes(url.protocol)) return undefined;
|
|
33
|
+
host = url.hostname;
|
|
34
|
+
path = url.pathname.replace(/^\//, '');
|
|
35
|
+
} catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
path = path.replace(/\.git$/, '').replace(/\/$/, '');
|
|
40
|
+
if (!host || !path || path.split('/').some((part)=>!part || part === '.' || part === '..')) return undefined;
|
|
41
|
+
return {
|
|
42
|
+
host: host.toLowerCase(),
|
|
43
|
+
repo: path
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
// Same path whatever separators or trailing slash either side was written with; Windows paths also ignore case.
|
|
47
|
+
export function samePath(left, right, platform = process.platform) {
|
|
48
|
+
if (platform !== 'win32') return posix.resolve(left) === posix.resolve(right);
|
|
49
|
+
return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
export function matchesSource(policySource, plugin, platform = process.platform) {
|
|
52
|
+
if (plugin.localPath !== undefined) return samePath(policySource, plugin.localPath, platform);
|
|
53
|
+
const parts = sourceParts(policySource);
|
|
54
|
+
return !!parts && parts.host === plugin.host.toLowerCase() && parts.repo === plugin.repo.replace(/\.git$/, '');
|
|
55
|
+
}
|
|
56
|
+
export function localEventName(source) {
|
|
57
|
+
return `_local/${basename(source).replace(/\/$/, '')}`;
|
|
58
|
+
}
|
|
59
|
+
export function lockIdentity(plugin) {
|
|
60
|
+
var _plugin_localPath;
|
|
61
|
+
return JSON.stringify([
|
|
62
|
+
plugin.host,
|
|
63
|
+
plugin.repo,
|
|
64
|
+
plugin.path,
|
|
65
|
+
(_plugin_localPath = plugin.localPath) !== null && _plugin_localPath !== void 0 ? _plugin_localPath : null
|
|
66
|
+
]);
|
|
67
|
+
}
|
|
68
|
+
export function parseLock(value) {
|
|
69
|
+
const root = record(value, 'APM lock');
|
|
70
|
+
if (!Array.isArray(root.dependencies)) throw new Error('APM lock dependencies must be an array');
|
|
71
|
+
const seen = new Set();
|
|
72
|
+
return root.dependencies.map((raw, index)=>{
|
|
73
|
+
const label = `APM lock dependencies[${index}]`;
|
|
74
|
+
const source = record(raw, label);
|
|
75
|
+
let plugin;
|
|
76
|
+
if (source.source === 'local' && source.package_type === 'agent_plugin') {
|
|
77
|
+
const repo = safePath(source.repo_url, `${label}.repo_url`);
|
|
78
|
+
if (!repo.startsWith('_local/')) throw new Error(`${label}.repo_url is not a local plugin key`);
|
|
79
|
+
const localPath = requiredString(source.local_path, `${label}.local_path`);
|
|
80
|
+
const hash = requiredString(source.content_hash, `${label}.content_hash`);
|
|
81
|
+
if (!/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid content hash`);
|
|
82
|
+
plugin = {
|
|
83
|
+
host: 'local',
|
|
84
|
+
repo,
|
|
85
|
+
path: '.',
|
|
86
|
+
revision: hash,
|
|
87
|
+
localPath,
|
|
88
|
+
deployedFiles: []
|
|
89
|
+
};
|
|
90
|
+
} else {
|
|
91
|
+
var _source_deployed_files;
|
|
92
|
+
const host = requiredString(source.host, `${label}.host`);
|
|
93
|
+
const repo = safePath(source.repo_url, `${label}.repo_url`);
|
|
94
|
+
// APM writes no virtual_path for a plugin at the repository root (recorded from APM 0.37.0)
|
|
95
|
+
const path = source.virtual_path === undefined || source.virtual_path === null ? '.' : safePath(source.virtual_path, `${label}.virtual_path`, true);
|
|
96
|
+
const commit = requiredString(source.resolved_commit, `${label}.resolved_commit`);
|
|
97
|
+
const hash = requiredString(source.content_hash, `${label}.content_hash`);
|
|
98
|
+
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) || !/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid revision evidence`);
|
|
99
|
+
const native = source.native_plugin === undefined || source.native_plugin === null ? undefined : record(source.native_plugin, `${label}.native_plugin`);
|
|
100
|
+
const nativePluginRoot = native ? safePath(native.root, `${label}.native_plugin.root`) : undefined;
|
|
101
|
+
const deployed = (_source_deployed_files = source.deployed_files) !== null && _source_deployed_files !== void 0 ? _source_deployed_files : [];
|
|
102
|
+
if (!Array.isArray(deployed) || !deployed.every((file)=>typeof file === 'string')) throw new Error(`${label}.deployed_files must be an array of paths`);
|
|
103
|
+
const deployedFiles = deployed.map((file, fileIndex)=>safePath(file, `${label}.deployed_files[${fileIndex}]`));
|
|
104
|
+
plugin = {
|
|
105
|
+
host,
|
|
106
|
+
repo,
|
|
107
|
+
path,
|
|
108
|
+
revision: `${commit}:${hash}`,
|
|
109
|
+
nativePluginRoot,
|
|
110
|
+
deployedFiles
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const identity = lockIdentity(plugin);
|
|
114
|
+
if (seen.has(identity)) throw new Error(`${label} duplicates another lock entry`);
|
|
115
|
+
seen.add(identity);
|
|
116
|
+
return plugin;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
export async function loadLock(path) {
|
|
120
|
+
return parseLock(parse(await readFile(path, 'utf8')));
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/apm.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename, posix, win32 } from 'node:path';\nimport { parse } from 'yaml';\n\nexport interface LockedPlugin {\n host: string;\n repo: string;\n path: string;\n revision: string;\n localPath?: string;\n nativePluginRoot?: string;\n deployedFiles: string[];\n}\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n return value as Record<string, unknown>;\n}\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction safePath(value: unknown, label: string, dot = false): string {\n const path = requiredString(value, label);\n if (dot && path === '.') return path;\n if (path.startsWith('/') || path.includes('\\\\') || /^[A-Za-z]:/.test(path) || path.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`${label} contains an unsafe path segment`);\n return path;\n}\nexport function sourceParts(source: string): { host: string; repo: string } | undefined {\n let host: string;\n let path: string;\n const scp = source.includes('://') ? null : /^(?:[^@/:]+@)?([^/:]+):(.+)$/.exec(source);\n if (scp) {\n host = scp[1];\n path = scp[2];\n } else {\n try {\n const url = new URL(source);\n if (!['https:', 'ssh:', 'http:'].includes(url.protocol)) return undefined;\n host = url.hostname;\n path = url.pathname.replace(/^\\//, '');\n } catch {\n return undefined;\n }\n }\n path = path.replace(/\\.git$/, '').replace(/\\/$/, '');\n if (!host || !path || path.split('/').some((part) => !part || part === '.' || part === '..')) return undefined;\n return { host: host.toLowerCase(), repo: path };\n}\n// Same path whatever separators or trailing slash either side was written with; Windows paths also ignore case.\nexport function samePath(left: string, right: string, platform: NodeJS.Platform = process.platform): boolean {\n if (platform !== 'win32') return posix.resolve(left) === posix.resolve(right);\n return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();\n}\nexport function matchesSource(policySource: string, plugin: LockedPlugin, platform: NodeJS.Platform = process.platform): boolean {\n if (plugin.localPath !== undefined) return samePath(policySource, plugin.localPath, platform);\n const parts = sourceParts(policySource);\n return !!parts && parts.host === plugin.host.toLowerCase() && parts.repo === plugin.repo.replace(/\\.git$/, '');\n}\nexport function localEventName(source: string): string {\n return `_local/${basename(source).replace(/\\/$/, '')}`;\n}\nexport function lockIdentity(plugin: LockedPlugin): string {\n return JSON.stringify([plugin.host, plugin.repo, plugin.path, plugin.localPath ?? null]);\n}\nexport function parseLock(value: unknown): LockedPlugin[] {\n const root = record(value, 'APM lock');\n if (!Array.isArray(root.dependencies)) throw new Error('APM lock dependencies must be an array');\n const seen = new Set<string>();\n return root.dependencies.map((raw, index): LockedPlugin => {\n const label = `APM lock dependencies[${index}]`;\n const source = record(raw, label);\n let plugin: LockedPlugin;\n if (source.source === 'local' && source.package_type === 'agent_plugin') {\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n if (!repo.startsWith('_local/')) throw new Error(`${label}.repo_url is not a local plugin key`);\n const localPath = requiredString(source.local_path, `${label}.local_path`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid content hash`);\n plugin = { host: 'local', repo, path: '.', revision: hash, localPath, deployedFiles: [] };\n } else {\n const host = requiredString(source.host, `${label}.host`);\n const repo = safePath(source.repo_url, `${label}.repo_url`);\n // APM writes no virtual_path for a plugin at the repository root (recorded from APM 0.37.0)\n const path = source.virtual_path === undefined || source.virtual_path === null ? '.' : safePath(source.virtual_path, `${label}.virtual_path`, true);\n const commit = requiredString(source.resolved_commit, `${label}.resolved_commit`);\n const hash = requiredString(source.content_hash, `${label}.content_hash`);\n if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) || !/^sha256:[0-9a-f]{64}$/.test(hash)) throw new Error(`${label} has invalid revision evidence`);\n const native = source.native_plugin === undefined || source.native_plugin === null ? undefined : record(source.native_plugin, `${label}.native_plugin`);\n const nativePluginRoot = native ? safePath(native.root, `${label}.native_plugin.root`) : undefined;\n const deployed = source.deployed_files ?? [];\n if (!Array.isArray(deployed) || !deployed.every((file) => typeof file === 'string')) throw new Error(`${label}.deployed_files must be an array of paths`);\n const deployedFiles = deployed.map((file: string, fileIndex: number) => safePath(file, `${label}.deployed_files[${fileIndex}]`));\n plugin = { host, repo, path, revision: `${commit}:${hash}`, nativePluginRoot, deployedFiles };\n }\n const identity = lockIdentity(plugin);\n if (seen.has(identity)) throw new Error(`${label} duplicates another lock entry`);\n seen.add(identity);\n return plugin;\n });\n}\nexport async function loadLock(path: string): Promise<LockedPlugin[]> {\n return parseLock(parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","basename","posix","win32","parse","record","value","label","Array","isArray","Error","requiredString","safePath","dot","path","startsWith","includes","test","split","some","part","sourceParts","source","host","scp","exec","url","URL","protocol","undefined","hostname","pathname","replace","toLowerCase","repo","samePath","left","right","platform","process","resolve","matchesSource","policySource","plugin","localPath","parts","localEventName","lockIdentity","JSON","stringify","parseLock","root","dependencies","seen","Set","map","raw","index","package_type","repo_url","local_path","hash","content_hash","revision","deployedFiles","virtual_path","commit","resolved_commit","native","native_plugin","nativePluginRoot","deployed","deployed_files","every","file","fileIndex","identity","has","add","loadLock"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,mBAAmB;AAC5C,SAASC,QAAQ,EAAEC,KAAK,EAAEC,KAAK,QAAQ,YAAY;AACnD,SAASC,KAAK,QAAQ,OAAO;AAW7B,SAASC,OAAOC,KAAc,EAAEC,KAAa;IAC3C,IAAI,C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m/cli.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { runLifecycle } from './runner.js';
|
|
3
|
+
const HELP = `agent-plugin-lifecycle
|
|
4
|
+
|
|
5
|
+
Usage:
|
|
6
|
+
agent-plugin-lifecycle run Dispatch an APM post-install/update/uninstall event from stdin
|
|
7
|
+
agent-plugin-lifecycle check Report missing or failed plugin setup
|
|
8
|
+
agent-plugin-lifecycle --help
|
|
9
|
+
|
|
10
|
+
Policy: ~/.config/agent-plugin-lifecycle/config.json
|
|
11
|
+
APM lock: ~/.apm/apm.lock.yaml (or $APM_HOME/apm.lock.yaml)
|
|
12
|
+
`;
|
|
13
|
+
async function readEvent() {
|
|
14
|
+
if (process.stdin.isTTY) throw new Error('run requires an APM event on stdin');
|
|
15
|
+
let payload = '';
|
|
16
|
+
for await (const chunk of process.stdin){
|
|
17
|
+
payload += chunk.toString();
|
|
18
|
+
if (payload.length > 1024 * 1024) throw new Error('APM event exceeds 1 MiB');
|
|
19
|
+
}
|
|
20
|
+
if (!payload.trim()) throw new Error('run requires an APM event on stdin');
|
|
21
|
+
const event = JSON.parse(payload);
|
|
22
|
+
if (!event || typeof event !== 'object' || Array.isArray(event)) throw new Error('APM event must be an object');
|
|
23
|
+
const value = event;
|
|
24
|
+
if (value.schema_version !== 1 || ![
|
|
25
|
+
'post-install',
|
|
26
|
+
'post-update',
|
|
27
|
+
'post-uninstall'
|
|
28
|
+
].includes(String(value.event)) || ![
|
|
29
|
+
'user',
|
|
30
|
+
'project'
|
|
31
|
+
].includes(String(value.scope)) || !Array.isArray(value.packages) || !value.packages.every((p)=>p && typeof p === 'object' && typeof p.name === 'string' && (p.reference === null || typeof p.reference === 'string'))) {
|
|
32
|
+
throw new Error('unsupported APM lifecycle event');
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
async function main() {
|
|
37
|
+
const { values, positionals } = parseArgs({
|
|
38
|
+
args: process.argv.slice(2),
|
|
39
|
+
options: {
|
|
40
|
+
help: {
|
|
41
|
+
type: 'boolean',
|
|
42
|
+
short: 'h'
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
allowPositionals: true
|
|
46
|
+
});
|
|
47
|
+
if (values.help || positionals.length === 0) {
|
|
48
|
+
process.stdout.write(HELP);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (positionals.length !== 1 || ![
|
|
52
|
+
'run',
|
|
53
|
+
'check'
|
|
54
|
+
].includes(positionals[0])) throw new Error('expected run or check; use --help');
|
|
55
|
+
const event = positionals[0] === 'run' ? await readEvent() : undefined;
|
|
56
|
+
if ((event === null || event === void 0 ? void 0 : event.scope) !== undefined && event.scope !== 'user') {
|
|
57
|
+
console.log(`skipped APM ${event.scope} scope event`);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
return runLifecycle(positionals[0], {
|
|
61
|
+
apmHome: process.env.APM_HOME,
|
|
62
|
+
event
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
main().then((status)=>{
|
|
66
|
+
process.exitCode = status;
|
|
67
|
+
}).catch((error)=>{
|
|
68
|
+
console.error(`agent-plugin-lifecycle: ${error instanceof Error ? error.message : String(error)}`);
|
|
69
|
+
process.exitCode = 2;
|
|
70
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/cli.ts"],"sourcesContent":["import { parseArgs } from 'node:util';\n\nimport { runLifecycle } from './runner.js';\n\nconst HELP = `agent-plugin-lifecycle\n\nUsage:\n agent-plugin-lifecycle run Dispatch an APM post-install/update/uninstall event from stdin\n agent-plugin-lifecycle check Report missing or failed plugin setup\n agent-plugin-lifecycle --help\n\nPolicy: ~/.config/agent-plugin-lifecycle/config.json\nAPM lock: ~/.apm/apm.lock.yaml (or $APM_HOME/apm.lock.yaml)\n`;\n\nasync function readEvent(): Promise<import('./runner.js').LifecycleEvent> {\n if (process.stdin.isTTY) throw new Error('run requires an APM event on stdin');\n let payload = '';\n for await (const chunk of process.stdin) {\n payload += chunk.toString();\n if (payload.length > 1024 * 1024) throw new Error('APM event exceeds 1 MiB');\n }\n if (!payload.trim()) throw new Error('run requires an APM event on stdin');\n const event: unknown = JSON.parse(payload);\n if (!event || typeof event !== 'object' || Array.isArray(event)) throw new Error('APM event must be an object');\n const value = event as Record<string, unknown>;\n if (\n value.schema_version !== 1 ||\n !['post-install', 'post-update', 'post-uninstall'].includes(String(value.event)) ||\n !['user', 'project'].includes(String(value.scope)) ||\n !Array.isArray(value.packages) ||\n !value.packages.every((p) => p && typeof p === 'object' && typeof p.name === 'string' && (p.reference === null || typeof p.reference === 'string'))\n ) {\n throw new Error('unsupported APM lifecycle event');\n }\n return value as unknown as import('./runner.js').LifecycleEvent;\n}\n\nasync function main(): Promise<number> {\n const { values, positionals } = parseArgs({\n args: process.argv.slice(2),\n options: { help: { type: 'boolean', short: 'h' } },\n allowPositionals: true,\n });\n if (values.help || positionals.length === 0) {\n process.stdout.write(HELP);\n return 0;\n }\n if (positionals.length !== 1 || !['run', 'check'].includes(positionals[0])) throw new Error('expected run or check; use --help');\n const event = positionals[0] === 'run' ? await readEvent() : undefined;\n if (event?.scope !== undefined && event.scope !== 'user') {\n console.log(`skipped APM ${event.scope} scope event`);\n return 0;\n }\n return runLifecycle(positionals[0] as 'run' | 'check', { apmHome: process.env.APM_HOME, event });\n}\n\nmain()\n .then((status) => {\n process.exitCode = status;\n })\n .catch((error: unknown) => {\n console.error(`agent-plugin-lifecycle: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n });\n"],"names":["parseArgs","runLifecycle","HELP","readEvent","process","stdin","isTTY","Error","payload","chunk","toString","length","trim","event","JSON","parse","Array","isArray","value","schema_version","includes","String","scope","packages","every","p","name","reference","main","values","positionals","args","argv","slice","options","help","type","short","allowPositionals","stdout","write","undefined","console","log","apmHome","env","APM_HOME","then","status","exitC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DC,kBAAkB;IACpB;IACA,IAAIT,OAAOM,IAAI,IAAIL,YAAYnB,MAAM,KAAK,GAAG;QAC3CP,QAAQmC,MAAM,CAACC,KAAK,CAACtC;QACrB,OAAO;IACT;IACA,IAAI4B,YAAYnB,MAAM,KAAK,KAAK,CAAC;QAAC;QAAO;KAAQ,CAACS,QAAQ,CAACU,WAAW,CAAC,EAAE,GAAG,MAAM,IAAIvB,MAAM;IAC5F,MAAMM,QAAQiB,WAAW,CAAC,EAAE,KAAK,QAAQ,MAAM3B,cAAcsC;IAC7D,IAAI5B,CAAAA,kBAAAA,4BAAAA,MAAOS,KAAK,MAAKmB,aAAa5B,MAAMS,KAAK,KAAK,QAAQ;QACxDoB,QAAQC,GAAG,CAAC,CAAC,YAAY,EAAE9B,MAAMS,KAAK,CAAC,YAAY,CAAC;QACpD,OAAO;IACT;IACA,OAAOrB,aAAa6B,WAAW,CAAC,EAAE,EAAqB;QAAEc,SAASxC,QAAQyC,GAAG,CAACC,QAAQ;QAAEjC;IAAM;AAChG;AAEAe,OACGmB,IAAI,CAAC,CAACC;IACL5C,QAAQ6C,QAAQ,GAAGD;AACrB,GACCE,KAAK,CAAC,CAACC;IACNT,QAAQS,KAAK,CAAC,CAAC,wBAAwB,EAAEA,iBAAiB5C,QAAQ4C,MAAMC,OAAO,GAAG/B,OAAO8B,QAAQ;IACjG/C,QAAQ6C,QAAQ,GAAG;AACrB"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type Platform = 'darwin' | 'linux' | 'win32';
|
|
2
|
+
export interface PluginPolicy {
|
|
3
|
+
source: string;
|
|
4
|
+
path?: string;
|
|
5
|
+
skill?: string;
|
|
6
|
+
'post-install'?: string;
|
|
7
|
+
'post-update'?: string;
|
|
8
|
+
'post-uninstall'?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Config {
|
|
11
|
+
version: 1;
|
|
12
|
+
plugins: PluginPolicy[];
|
|
13
|
+
}
|
|
14
|
+
export declare function recordId(plugin: PluginPolicy): string;
|
|
15
|
+
export declare function parseConfig(value: unknown): Config;
|
|
16
|
+
export declare function loadConfig(path: string): Promise<Config>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
function object(value, label, allowed) {
|
|
3
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
4
|
+
const result = value;
|
|
5
|
+
const unknown = Object.keys(result).find((key)=>!allowed.includes(key));
|
|
6
|
+
if (unknown) throw new Error(`${label} has unknown field: ${unknown}`);
|
|
7
|
+
return result;
|
|
8
|
+
}
|
|
9
|
+
function nonempty(value, label) {
|
|
10
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} must be a nonempty string`);
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function relativePath(value, label) {
|
|
14
|
+
const path = nonempty(value, label);
|
|
15
|
+
if (path === '.') return path;
|
|
16
|
+
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:/.test(path) || path.includes('\\') || path.split('/').some((part)=>!part || part === '.' || part === '..')) {
|
|
17
|
+
throw new Error(`${label} must be a safe relative POSIX path`);
|
|
18
|
+
}
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
21
|
+
export function recordId(plugin) {
|
|
22
|
+
var _plugin_path, _plugin_skill;
|
|
23
|
+
return JSON.stringify([
|
|
24
|
+
plugin.source,
|
|
25
|
+
(_plugin_path = plugin.path) !== null && _plugin_path !== void 0 ? _plugin_path : '.',
|
|
26
|
+
(_plugin_skill = plugin.skill) !== null && _plugin_skill !== void 0 ? _plugin_skill : null
|
|
27
|
+
]);
|
|
28
|
+
}
|
|
29
|
+
export function parseConfig(value) {
|
|
30
|
+
const root = object(value, 'config', [
|
|
31
|
+
'version',
|
|
32
|
+
'plugins'
|
|
33
|
+
]);
|
|
34
|
+
if (root.version !== 1 || !Array.isArray(root.plugins)) throw new Error('config must have version 1 and a plugins array');
|
|
35
|
+
const seen = new Set();
|
|
36
|
+
const plugins = root.plugins.map((raw, index)=>{
|
|
37
|
+
const label = `plugins[${index}]`;
|
|
38
|
+
const item = object(raw, label, [
|
|
39
|
+
'source',
|
|
40
|
+
'path',
|
|
41
|
+
'skill',
|
|
42
|
+
'post-install',
|
|
43
|
+
'post-update',
|
|
44
|
+
'post-uninstall'
|
|
45
|
+
]);
|
|
46
|
+
const source = nonempty(item.source, `${label}.source`);
|
|
47
|
+
const path = item.path === undefined ? undefined : relativePath(item.path, `${label}.path`);
|
|
48
|
+
const skill = item.skill === undefined ? undefined : nonempty(item.skill, `${label}.skill`);
|
|
49
|
+
if (skill && (skill.includes('/') || skill.includes('\\') || skill === '.' || skill === '..')) throw new Error(`${label}.skill must be one directory name`);
|
|
50
|
+
const plugin = {
|
|
51
|
+
source,
|
|
52
|
+
path,
|
|
53
|
+
skill
|
|
54
|
+
};
|
|
55
|
+
for (const event of [
|
|
56
|
+
'post-install',
|
|
57
|
+
'post-update',
|
|
58
|
+
'post-uninstall'
|
|
59
|
+
]){
|
|
60
|
+
if (item[event] !== undefined) plugin[event] = nonempty(item[event], `${label}.${event}`);
|
|
61
|
+
}
|
|
62
|
+
const id = recordId(plugin);
|
|
63
|
+
if (seen.has(id)) throw new Error(`${label} duplicates another source/path/skill record`);
|
|
64
|
+
seen.add(id);
|
|
65
|
+
return plugin;
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
version: 1,
|
|
69
|
+
plugins
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
export async function loadConfig(path) {
|
|
73
|
+
return parseConfig(JSON.parse(await readFile(path, 'utf8')));
|
|
74
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/config.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\n\nexport type Platform = 'darwin' | 'linux' | 'win32';\nexport interface PluginPolicy {\n source: string;\n path?: string;\n skill?: string;\n 'post-install'?: string;\n 'post-update'?: string;\n 'post-uninstall'?: string;\n}\nexport interface Config {\n version: 1;\n plugins: PluginPolicy[];\n}\n\nfunction object(value: unknown, label: string, allowed: string[]): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);\n const result = value as Record<string, unknown>;\n const unknown = Object.keys(result).find((key) => !allowed.includes(key));\n if (unknown) throw new Error(`${label} has unknown field: ${unknown}`);\n return result;\n}\nfunction nonempty(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} must be a nonempty string`);\n return value;\n}\nfunction relativePath(value: unknown, label: string): string {\n const path = nonempty(value, label);\n if (path === '.') return path;\n if (path.startsWith('/') || path.startsWith('\\\\') || /^[A-Za-z]:/.test(path) || path.includes('\\\\') || path.split('/').some((part) => !part || part === '.' || part === '..')) {\n throw new Error(`${label} must be a safe relative POSIX path`);\n }\n return path;\n}\nexport function recordId(plugin: PluginPolicy): string {\n return JSON.stringify([plugin.source, plugin.path ?? '.', plugin.skill ?? null]);\n}\nexport function parseConfig(value: unknown): Config {\n const root = object(value, 'config', ['version', 'plugins']);\n if (root.version !== 1 || !Array.isArray(root.plugins)) throw new Error('config must have version 1 and a plugins array');\n const seen = new Set<string>();\n const plugins = root.plugins.map((raw, index): PluginPolicy => {\n const label = `plugins[${index}]`;\n const item = object(raw, label, ['source', 'path', 'skill', 'post-install', 'post-update', 'post-uninstall']);\n const source = nonempty(item.source, `${label}.source`);\n const path = item.path === undefined ? undefined : relativePath(item.path, `${label}.path`);\n const skill = item.skill === undefined ? undefined : nonempty(item.skill, `${label}.skill`);\n if (skill && (skill.includes('/') || skill.includes('\\\\') || skill === '.' || skill === '..')) throw new Error(`${label}.skill must be one directory name`);\n const plugin: PluginPolicy = { source, path, skill };\n for (const event of ['post-install', 'post-update', 'post-uninstall'] as const) {\n if (item[event] !== undefined) plugin[event] = nonempty(item[event], `${label}.${event}`);\n }\n const id = recordId(plugin);\n if (seen.has(id)) throw new Error(`${label} duplicates another source/path/skill record`);\n seen.add(id);\n return plugin;\n });\n return { version: 1, plugins };\n}\nexport async function loadConfig(path: string): Promise<Config> {\n return parseConfig(JSON.parse(await readFile(path, 'utf8')));\n}\n"],"names":["readFile","object","value","label","allowed","Array","isArray","Error","result","unknown","Object","keys","find","key","includes","nonempty","trim","relativePath","path","startsWith","test","split","some","part","recordId","plugin","JSON","stringify","source","skill","parseConfig","root","version","plugins","seen","Set","map","raw","index","item","undefined","event","id","has","add","loadConfig","parse"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,mBAAmB;AAgB5C,SAASC,OAAOC,KAAc,EAAEC,KAAa,EAAEC,OAAiB;IAC9D,IAAI,CAACF,SAAS,OAAOA,UAAU,YAAYG,MAAMC,OAAO,CAACJ,QAAQ,MAAM,IAAIK,MAAM,GAAGJ,MAAM,kBAAkB,CAAC;IAC7G,MAAMK,SAASN;IACf,MAAMO,UAAUC,OAAOC,IAAI,CAACH,QAAQI,IAAI,CAAC,CAACC,MAAQ,CAACT,QAAQU,QAAQ,CAACD;IACpE,IAAIJ,SAAS,MAAM,IAAIF,MAAM,GAAGJ,MAAM,oBAAoB,EAAEM,SAAS;IACrE,OAAOD;AACT;AACA,SAASO,SAASb,KAAc,EAAEC,KAAa;IAC7C,IAAI,OAAOD,UAAU,YAAY,CAACA,MAAMc,IAAI,IAAI,MAAM,IAAIT,MAAM,GAAGJ,MAAM,0BAA0B,CAAC;IACpG,OAAOD;AACT;AACA,SAASe,aAAaf,KAAc,EAAEC,KAAa;IACjD,MAAMe,OAAOH,SAASb,OAAOC;IAC7B,IAAIe,SAAS,KAAK,OAAOA;IACzB,IAAIA,KAAKC,UAAU,CAAC,QAAQD,KAAKC,UAAU,CAAC,SAAS,aAAaC,IAAI,CAACF,SAASA,KAAKJ,QAAQ,CAAC,SAASI,KAAKG,KAAK,CAAC,KAAKC,IAAI,CAAC,CAACC,OAAS,CAACA,QAAQA,SAAS,OAAOA,SAAS,OAAO;QAC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QV;YAAMW;QAAM;QACnD,KAAK,MAAMY,SAAS;YAAC;YAAgB;YAAe;SAAiB,CAAW;YAC9E,IAAIF,IAAI,CAACE,MAAM,KAAKD,WAAWf,MAAM,CAACgB,MAAM,GAAG1B,SAASwB,IAAI,CAACE,MAAM,EAAE,GAAGtC,MAAM,CAAC,EAAEsC,OAAO;QAC1F;QACA,MAAMC,KAAKlB,SAASC;QACpB,IAAIS,KAAKS,GAAG,CAACD,KAAK,MAAM,IAAInC,MAAM,GAAGJ,MAAM,4CAA4C,CAAC;QACxF+B,KAAKU,GAAG,CAACF;QACT,OAAOjB;IACT;IACA,OAAO;QAAEO,SAAS;QAAGC;IAAQ;AAC/B;AACA,OAAO,eAAeY,WAAW3B,IAAY;IAC3C,OAAOY,YAAYJ,KAAKoB,KAAK,CAAC,MAAM9C,SAASkB,MAAM;AACrD"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { LockedPlugin } from './apm.js';
|
|
2
|
+
export { matchesSource, parseLock, sourceParts } from './apm.js';
|
|
3
|
+
export type { Config, PluginPolicy } from './config.js';
|
|
4
|
+
export { parseConfig, recordId } from './config.js';
|
|
5
|
+
export type { LifecycleEvent, Mode, RunOptions } from './runner.js';
|
|
6
|
+
export { runLifecycle } from './runner.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/agent-plugin-lifecycle/src/index.ts"],"sourcesContent":["export type { LockedPlugin } from './apm.js';\nexport { matchesSource, parseLock, sourceParts } from './apm.js';\nexport type { Config, PluginPolicy } from './config.js';\nexport { parseConfig, recordId } from './config.js';\nexport type { LifecycleEvent, Mode, RunOptions } from './runner.js';\nexport { runLifecycle } from './runner.js';\n"],"names":["matchesSource","parseLock","sourceParts","parseConfig","recordId","runLifecycle"],"mappings":"AACA,SAASA,aAAa,EAAEC,SAAS,EAAEC,WAAW,QAAQ,WAAW;AAEjE,SAASC,WAAW,EAAEC,QAAQ,QAAQ,cAAc;AAEpD,SAASC,YAAY,QAAQ,cAAc"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "type": "module" }
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type Mode = 'run' | 'check';
|
|
2
|
+
export interface LifecycleEvent {
|
|
3
|
+
schema_version: 1;
|
|
4
|
+
event: 'post-install' | 'post-update' | 'post-uninstall';
|
|
5
|
+
scope: 'user';
|
|
6
|
+
packages: {
|
|
7
|
+
name: string;
|
|
8
|
+
reference: string | null;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
export interface RunOptions {
|
|
12
|
+
home?: string;
|
|
13
|
+
apmHome?: string;
|
|
14
|
+
configPath?: string;
|
|
15
|
+
environment?: NodeJS.ProcessEnv;
|
|
16
|
+
output?: (line: string) => void;
|
|
17
|
+
event?: LifecycleEvent;
|
|
18
|
+
}
|
|
19
|
+
export declare function runLifecycle(mode: Mode, options?: RunOptions): Promise<number>;
|