@denizokcu/haze 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +74 -5
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/DynamicFrame.d.ts +0 -13
  6. package/dist/cli/chat/DynamicFrame.js +7 -2
  7. package/dist/cli/chat/inputSuggestions.js +2 -0
  8. package/dist/cli/chat/resizeGuard.d.ts +20 -0
  9. package/dist/cli/chat/resizeGuard.js +25 -0
  10. package/dist/cli/chat/terminalControl.d.ts +4 -2
  11. package/dist/cli/chat/terminalControl.js +16 -5
  12. package/dist/cli/chat/wizard/pluginHandlers.d.ts +10 -0
  13. package/dist/cli/chat/wizard/pluginHandlers.js +156 -0
  14. package/dist/cli/chat/wizard/skillsHandlers.js +2 -2
  15. package/dist/cli/chat/wizard/types.d.ts +20 -0
  16. package/dist/cli/chat/wizard/uiState.d.ts +25 -1
  17. package/dist/cli/chat/wizard/uiState.js +3 -1
  18. package/dist/cli/chat/wizardDispatch.js +6 -0
  19. package/dist/cli/commands/chat.js +27 -5
  20. package/dist/cli/commands/commandHelp.js +7 -2
  21. package/dist/cli/commands/commands.d.ts +5 -0
  22. package/dist/cli/commands/commands.js +17 -3
  23. package/dist/cli/commands/initCommand.js +3 -2
  24. package/dist/cli/commands/pluginCommand.d.ts +16 -0
  25. package/dist/cli/commands/pluginCommand.js +127 -0
  26. package/dist/cli/commands/reasoningCommand.d.ts +0 -15
  27. package/dist/cli/commands/reasoningCommand.js +1 -3
  28. package/dist/cli/commands/skillsWizard.js +4 -0
  29. package/dist/cli/commands/streaming/agentAttempt.js +2 -1
  30. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  31. package/dist/cli/commands/streaming/attemptOutcome.js +4 -3
  32. package/dist/cli/commands/streaming/attemptSetup.d.ts +2 -0
  33. package/dist/cli/commands/streaming/attemptSetup.js +3 -2
  34. package/dist/cli/commands/streaming/stallRecovery.d.ts +6 -0
  35. package/dist/cli/commands/streaming/stallRecovery.js +6 -5
  36. package/dist/cli/commands/streaming/turnRuntime.js +2 -4
  37. package/dist/cli/commands/wizardFlow.d.ts +59 -0
  38. package/dist/cli/commands/wizardFlow.js +40 -0
  39. package/dist/cli/contextReportCli.js +4 -3
  40. package/dist/cli/index.js +19 -2
  41. package/dist/config/contextFiles.js +3 -2
  42. package/dist/config/inputHistory.js +3 -3
  43. package/dist/config/paths.d.ts +1 -0
  44. package/dist/config/paths.js +1 -0
  45. package/dist/config/providerAuth.js +3 -3
  46. package/dist/config/settings.d.ts +14 -2
  47. package/dist/config/settings.js +8 -4
  48. package/dist/config/updateCheck.js +3 -3
  49. package/dist/core/agent/budgets.d.ts +17 -0
  50. package/dist/core/agent/budgets.js +19 -0
  51. package/dist/core/agent/reasoningPolicy.js +1 -1
  52. package/dist/core/agent/workState.d.ts +0 -2
  53. package/dist/core/agent/workState.js +1 -1
  54. package/dist/core/log/llmLog.js +1 -1
  55. package/dist/core/providerContracts.d.ts +6 -3
  56. package/dist/core/session/sessionStore.js +4 -3
  57. package/dist/core/subagent/contracts.d.ts +1 -11
  58. package/dist/core/subagent/contracts.js +0 -22
  59. package/dist/llm/client.js +28 -7
  60. package/dist/llm/subagentRunner.d.ts +1 -6
  61. package/dist/llm/subagentRunner.js +11 -23
  62. package/dist/llm/tools/fileTools.js +2 -3
  63. package/dist/llm/tools/gitIgnore.js +1 -1
  64. package/dist/llm/tools/grepRunner.d.ts +10 -0
  65. package/dist/llm/tools/grepRunner.js +24 -0
  66. package/dist/llm/tools/toolContext.d.ts +2 -3
  67. package/dist/llm/tools/toolContext.js +2 -3
  68. package/dist/llm/tools/toolContextState.d.ts +0 -1
  69. package/dist/llm/tools/toolContextState.js +1 -4
  70. package/dist/llm/workerContext.d.ts +0 -7
  71. package/dist/llm/workerContext.js +0 -17
  72. package/dist/skills/SkillLoader.js +3 -2
  73. package/dist/skills/SkillRegistry.js +7 -4
  74. package/dist/skills/builder/SkillBuilder.js +11 -10
  75. package/dist/skills/plugins/installer.d.ts +25 -0
  76. package/dist/skills/plugins/installer.js +272 -0
  77. package/dist/skills/plugins/package.d.ts +41 -0
  78. package/dist/skills/plugins/package.js +275 -0
  79. package/dist/skills/plugins/runtime.d.ts +3 -0
  80. package/dist/skills/plugins/runtime.js +108 -0
  81. package/dist/skills/skillTools.js +10 -5
  82. package/dist/skills/types.d.ts +4 -0
  83. package/dist/ui/codeHighlight.d.ts +1 -1
  84. package/dist/ui/codeHighlight.js +112 -4
  85. package/dist/ui/components/StreamingMarkdownText.d.ts +0 -2
  86. package/dist/ui/components/StreamingMarkdownText.js +1 -1
  87. package/dist/ui/components/TextInput.d.ts +1 -1
  88. package/dist/utils/fs.d.ts +10 -0
  89. package/dist/utils/fs.js +37 -2
  90. package/package.json +17 -20
@@ -0,0 +1,272 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { HAZE_DIR } from '../../config/paths.js';
5
+ import { boundedRead, canonicalRoot, inspectPlugin, localPath, object, PLUGIN_LIMITS, readJson, safePath, validatePluginName } from './package.js';
6
+ const hash = (data) => createHash('sha256').update(data).digest('hex');
7
+ const missing = (error) => error.code === 'ENOENT';
8
+ // Host aliases in ~/.haze ancestors (e.g. /var -> /private/var on macOS) are
9
+ // canonicalized once per operation; package-relative paths below the roots
10
+ // still refuse all symlinks through safePath.
11
+ const pluginsHome = () => canonicalRoot(path.join(HAZE_DIR, 'plugins'));
12
+ const receiptsHome = () => canonicalRoot(path.join(HAZE_DIR, 'plugin-receipts'));
13
+ async function exists(file) {
14
+ try {
15
+ await fs.lstat(file);
16
+ return true;
17
+ }
18
+ catch (error) {
19
+ if (missing(error))
20
+ return false;
21
+ throw error;
22
+ }
23
+ }
24
+ /** Receipts always live in the user's global ~/.haze, never in a workspace. */
25
+ async function receipt(receiptsRoot, name) {
26
+ const file = await safePath(receiptsRoot, `${name}.json`);
27
+ if (!await exists(file))
28
+ return undefined;
29
+ const raw = await readJson(file);
30
+ if (raw.name !== name || (raw.version !== undefined && typeof raw.version !== 'string') || !Array.isArray(raw.files) || raw.files.length > PLUGIN_LIMITS.entries + 100)
31
+ throw new Error('Invalid plugin receipt.');
32
+ const seen = new Set();
33
+ const files = raw.files.map(value => {
34
+ const entry = object(value);
35
+ if (typeof entry.path !== 'string' || typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256) || typeof entry.executable !== 'boolean' || entry.mode !== 'package')
36
+ throw new Error('Invalid plugin receipt file.');
37
+ const relative = localPath(entry.path);
38
+ if (!relative.startsWith(`plugins/${name}/`))
39
+ throw new Error('Invalid receipt ownership path.');
40
+ if (seen.has(relative))
41
+ throw new Error('Duplicate receipt ownership path.');
42
+ seen.add(relative);
43
+ return { path: relative, sha256: entry.sha256, mode: 'package', executable: entry.executable };
44
+ });
45
+ return { name, version: raw.version, files };
46
+ }
47
+ async function withLock(receiptsRoot, action) {
48
+ await fs.mkdir(receiptsRoot, { recursive: true });
49
+ const lock = await safePath(receiptsRoot, '.lock');
50
+ let handle;
51
+ try {
52
+ handle = await fs.open(lock, 'wx', 0o600);
53
+ }
54
+ catch (error) {
55
+ if (error.code === 'EEXIST')
56
+ throw new Error(`Plugin operation is locked. Wait for the other operation; if interrupted, remove the stale ${lock} manually.`, { cause: error });
57
+ throw error;
58
+ }
59
+ try {
60
+ return await action();
61
+ }
62
+ finally {
63
+ await handle.close();
64
+ await fs.unlink(lock);
65
+ }
66
+ }
67
+ async function currentHash(pluginsRoot, entry) {
68
+ const target = await safePath(pluginsRoot, entry.path.slice('plugins/'.length));
69
+ if (!await exists(target))
70
+ return undefined;
71
+ return hash(await boundedRead(target));
72
+ }
73
+ async function prune(pluginsRoot, relative) {
74
+ // Remove only empty directories, never recurse over potentially user-owned data.
75
+ let parent = path.posix.dirname(relative);
76
+ while (parent !== '.' && parent !== 'plugins') {
77
+ try {
78
+ await fs.rmdir(await safePath(pluginsRoot, parent.slice('plugins/'.length)));
79
+ }
80
+ catch {
81
+ break;
82
+ }
83
+ parent = path.posix.dirname(parent);
84
+ }
85
+ }
86
+ const pluginTarget = (pluginsRoot, entry) => safePath(pluginsRoot, entry.path.slice('plugins/'.length));
87
+ export async function installPlugin(sourceDir, pluginName) {
88
+ const inspected = await inspectPlugin(sourceDir, pluginName);
89
+ const { name, version } = inspected.manifest;
90
+ const pluginsRoot = await pluginsHome();
91
+ const receiptsRoot = await receiptsHome();
92
+ return withLock(receiptsRoot, async () => {
93
+ const warnings = [...inspected.warnings];
94
+ const pending = [];
95
+ let totalBytes = 0;
96
+ for (const file of inspected.files) {
97
+ const source = await safePath(inspected.root, file);
98
+ const data = await boundedRead(source);
99
+ const executable = ((await fs.stat(source)).mode & 0o111) !== 0;
100
+ totalBytes += data.length;
101
+ if (totalBytes > PLUGIN_LIMITS.total)
102
+ throw new Error('Plugin package exceeds aggregate size limit.');
103
+ pending.push({ entry: { path: `plugins/${name}/${file}`, sha256: hash(data), mode: 'package', executable }, data });
104
+ }
105
+ const prior = await receipt(receiptsRoot, name);
106
+ if (prior) {
107
+ if (prior.version !== version || pending.some(item => !prior.files.some(file => JSON.stringify(file) === JSON.stringify(item.entry))) || prior.files.some(file => !pending.some(item => JSON.stringify(file) === JSON.stringify(item.entry))))
108
+ throw new Error('Plugin is already installed with different content. Remove it before installing another version.');
109
+ for (const entry of prior.files)
110
+ if (await currentHash(pluginsRoot, entry) !== entry.sha256)
111
+ throw new Error(`Installed plugin file was changed or removed: ${entry.path}`);
112
+ return { name, version, alreadyInstalled: true, warnings };
113
+ }
114
+ const packageRoot = await safePath(pluginsRoot, name);
115
+ if (await exists(packageRoot))
116
+ throw new Error('Plugin directory already exists without a receipt; refusing to overwrite it.');
117
+ const owned = pending;
118
+ const serialized = JSON.stringify({ name, version, files: owned.map(item => item.entry) }, null, 2);
119
+ if (Buffer.byteLength(serialized) > PLUGIN_LIMITS.json)
120
+ throw new Error('Plugin receipt exceeds size limit.');
121
+ const created = [];
122
+ const receiptPath = await safePath(receiptsRoot, `${name}.json`);
123
+ const temporaryReceipt = await safePath(receiptsRoot, `.${name}-${randomUUID()}.tmp`);
124
+ try {
125
+ for (const item of pending) {
126
+ const target = await pluginTarget(pluginsRoot, item.entry);
127
+ await fs.mkdir(path.dirname(target), { recursive: true });
128
+ const handle = await fs.open(target, 'wx', item.entry.executable ? 0o755 : 0o644);
129
+ try {
130
+ const record = { entry: item.entry, identity: await handle.stat(), completed: undefined };
131
+ created.push(record);
132
+ await handle.writeFile(item.data);
133
+ await handle.chmod(item.entry.executable ? 0o755 : 0o644);
134
+ record.completed = await handle.stat();
135
+ }
136
+ finally {
137
+ await handle.close();
138
+ }
139
+ }
140
+ await fs.writeFile(temporaryReceipt, serialized, { flag: 'wx', mode: 0o600 });
141
+ await fs.rename(temporaryReceipt, receiptPath);
142
+ }
143
+ catch (error) {
144
+ for (const { entry, identity, completed } of created.reverse()) {
145
+ try {
146
+ // Only a completed, untouched write is ours to undo. In particular,
147
+ // a same-content replacement inode is not transaction-owned.
148
+ if (!completed)
149
+ continue;
150
+ const target = await pluginTarget(pluginsRoot, entry);
151
+ const actual = await fs.lstat(target);
152
+ if (!actual.isFile() || actual.dev !== identity.dev || actual.ino !== identity.ino ||
153
+ actual.size !== completed.size || actual.mode !== completed.mode ||
154
+ actual.mtimeMs !== completed.mtimeMs || actual.ctimeMs !== completed.ctimeMs ||
155
+ await currentHash(pluginsRoot, entry) !== entry.sha256)
156
+ continue;
157
+ await fs.unlink(target);
158
+ await prune(pluginsRoot, entry.path);
159
+ }
160
+ catch { /* Cleanup is best-effort and must not mask the install error. */ }
161
+ }
162
+ try {
163
+ if (await exists(temporaryReceipt))
164
+ await fs.unlink(temporaryReceipt);
165
+ }
166
+ catch { /* Preserve the original error. */ }
167
+ throw error;
168
+ }
169
+ return { name, version, alreadyInstalled: false, warnings };
170
+ });
171
+ }
172
+ export async function enumeratePlugins() {
173
+ const receiptsRoot = await receiptsHome();
174
+ const directory = await safePath(receiptsRoot);
175
+ if (!await exists(directory))
176
+ return { plugins: [], errors: [] };
177
+ const entries = [];
178
+ for await (const entry of await fs.opendir(directory)) {
179
+ if (entries.length >= PLUGIN_LIMITS.entries)
180
+ throw new Error('Too many plugin receipts.');
181
+ entries.push(entry.name);
182
+ }
183
+ const plugins = [];
184
+ const errors = [];
185
+ for (const entry of entries.sort()) {
186
+ if (!entry.endsWith('.json'))
187
+ continue;
188
+ const name = entry.slice(0, -5);
189
+ try {
190
+ validatePluginName(name);
191
+ const installed = await receipt(receiptsRoot, name);
192
+ if (installed)
193
+ plugins.push({ name, ...(installed.version === undefined ? {} : { version: installed.version }) });
194
+ }
195
+ catch (error) {
196
+ errors.push({ directory: `${path.join(receiptsRoot, entry)}`, message: error instanceof Error ? error.message : String(error) });
197
+ }
198
+ }
199
+ return { plugins, errors };
200
+ }
201
+ export async function listPlugins() {
202
+ const { plugins, errors } = await enumeratePlugins();
203
+ if (errors.length)
204
+ throw new Error(errors.map(error => `${error.directory}: ${error.message}`).join('\n'));
205
+ return plugins;
206
+ }
207
+ export async function removePlugin(name) {
208
+ validatePluginName(name);
209
+ const pluginsRoot = await pluginsHome();
210
+ const receiptsRoot = await receiptsHome();
211
+ return withLock(receiptsRoot, async () => {
212
+ const installed = await receipt(receiptsRoot, name);
213
+ if (!installed)
214
+ throw new Error('Plugin is not installed.');
215
+ const retained = [];
216
+ const removable = [];
217
+ // Preflight all paths before any mutation. Changed files are never removed.
218
+ for (const entry of installed.files) {
219
+ try {
220
+ const actual = await currentHash(pluginsRoot, entry);
221
+ if (actual === undefined)
222
+ continue;
223
+ if (actual === entry.sha256)
224
+ removable.push(entry);
225
+ else
226
+ retained.push(entry.path);
227
+ }
228
+ catch {
229
+ retained.push(entry.path);
230
+ }
231
+ }
232
+ for (const entry of removable) {
233
+ // Recheck immediately before unlinking, to avoid deleting changed content.
234
+ if (await currentHash(pluginsRoot, entry) !== entry.sha256) {
235
+ retained.push(entry.path);
236
+ continue;
237
+ }
238
+ await fs.unlink(await pluginTarget(pluginsRoot, entry));
239
+ await prune(pluginsRoot, entry.path);
240
+ }
241
+ // Report leftover unowned package content as well as changed owned files.
242
+ let visited = 0;
243
+ async function leftovers(relative, depth = 0) {
244
+ try {
245
+ const directory = await safePath(pluginsRoot, relative);
246
+ if (!await exists(directory))
247
+ return;
248
+ if (depth > 32) {
249
+ retained.push(`plugins/${relative}`);
250
+ return;
251
+ }
252
+ for await (const entry of await fs.opendir(directory)) {
253
+ if (++visited > PLUGIN_LIMITS.entries) {
254
+ retained.push(`plugins/${relative}`);
255
+ return;
256
+ }
257
+ const child = `${relative}/${entry.name}`;
258
+ if (entry.isDirectory())
259
+ await leftovers(child, depth + 1);
260
+ else
261
+ retained.push(`plugins/${child}`);
262
+ }
263
+ }
264
+ catch {
265
+ retained.push(`plugins/${relative}`);
266
+ }
267
+ }
268
+ await leftovers(name);
269
+ await fs.unlink(await safePath(receiptsRoot, `${name}.json`));
270
+ return { name, retained: [...new Set(retained)].sort() };
271
+ });
272
+ }
@@ -0,0 +1,41 @@
1
+ export interface PluginManifest extends Record<string, unknown> {
2
+ name: string;
3
+ version?: string;
4
+ description?: string;
5
+ }
6
+ export interface PluginInspection {
7
+ root: string;
8
+ manifest: PluginManifest;
9
+ warnings: string[];
10
+ /** Sorted package-relative regular file paths; no symlinks or secret files. */
11
+ files: string[];
12
+ }
13
+ export declare const PLUGIN_LIMITS: {
14
+ json: number;
15
+ file: number;
16
+ total: number;
17
+ entries: number;
18
+ };
19
+ export declare function validatePluginName(name: string): void;
20
+ export declare function localPath(value: string): string;
21
+ /** Refuse symlinks in every existing ancestor, including the supplied root. */
22
+ export declare function safePath(root: string, relative?: string): Promise<string>;
23
+ /**
24
+ * Canonicalize host aliases (e.g. /var -> /private/var on macOS) in the
25
+ * nearest existing ancestor of a root path; the final path segments are never
26
+ * resolved, so a symlink at the root itself stays visible to safePath and is
27
+ * refused. Mirrors the ancestor-only alias handling in inspectPlugin.
28
+ */
29
+ export declare function canonicalRoot(root: string): Promise<string>;
30
+ export declare function boundedRead(file: string, limit?: number): Promise<Buffer>;
31
+ export declare function object(value: unknown): Record<string, unknown>;
32
+ export declare function readJson(file: string): Promise<Record<string, unknown>>;
33
+ export declare const PLUGIN_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
34
+ export interface PluginManifestRead {
35
+ manifest: PluginManifest;
36
+ warnings: string[];
37
+ format: 'portable' | 'claude' | 'codex';
38
+ }
39
+ /** Read only the selected manifest; runtime loading must not walk unrelated components. */
40
+ export declare function readPluginManifest(root: string, inferredName?: string): Promise<PluginManifestRead>;
41
+ export declare function inspectPlugin(sourceDir: string, pluginName?: string): Promise<PluginInspection>;
@@ -0,0 +1,275 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { isProtectedSecretPath } from '../../core/safety/secretPaths.js';
5
+ export const PLUGIN_LIMITS = { json: 256 * 1024, file: 4 * 1024 * 1024, total: 32 * 1024 * 1024, entries: 2000 };
6
+ export function validatePluginName(name) {
7
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,99}$/.test(name) || /[^a-zA-Z0-9_.-]/.test(name) || name.includes('..'))
8
+ throw new Error('Invalid plugin name. Use letters, numbers, hyphens, dots or underscores.');
9
+ }
10
+ export function localPath(value) {
11
+ if (!value || value.includes('\\') || value.includes('\0') || path.isAbsolute(value) || value.split('/').includes('..')) {
12
+ throw new Error('Plugin path must be relative and cannot escape its root.');
13
+ }
14
+ return path.posix.normalize(value.replace(/^\.\//, ''));
15
+ }
16
+ /** Refuse symlinks in every existing ancestor, including the supplied root. */
17
+ export async function safePath(root, relative = '') {
18
+ const target = path.resolve(root, relative ? localPath(relative) : '.');
19
+ const parts = target.slice(path.parse(target).root.length).split(path.sep);
20
+ let current = path.parse(target).root;
21
+ for (const part of parts) {
22
+ current = path.join(current, part);
23
+ if (isProtectedSecretPath(current))
24
+ throw new Error('Protected secret path in plugin package.');
25
+ try {
26
+ const stat = await fs.lstat(current);
27
+ if (stat.isSymbolicLink())
28
+ throw new Error('Symlinks are not allowed in plugin paths.');
29
+ }
30
+ catch (error) {
31
+ if (error.code !== 'ENOENT')
32
+ throw error;
33
+ }
34
+ }
35
+ return target;
36
+ }
37
+ /**
38
+ * Canonicalize host aliases (e.g. /var -> /private/var on macOS) in the
39
+ * nearest existing ancestor of a root path; the final path segments are never
40
+ * resolved, so a symlink at the root itself stays visible to safePath and is
41
+ * refused. Mirrors the ancestor-only alias handling in inspectPlugin.
42
+ */
43
+ export async function canonicalRoot(root) {
44
+ try {
45
+ const parent = await fs.realpath(path.dirname(root));
46
+ return path.join(parent, path.basename(root));
47
+ }
48
+ catch {
49
+ const parent = path.dirname(root);
50
+ if (parent === root)
51
+ return root;
52
+ return path.join(await canonicalRoot(parent), path.basename(root));
53
+ }
54
+ }
55
+ export async function boundedRead(file, limit = PLUGIN_LIMITS.file) {
56
+ await safePath(file);
57
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
58
+ try {
59
+ const stat = await handle.stat();
60
+ if (!stat.isFile() || stat.size > limit)
61
+ throw new Error('Plugin file exceeds size limit or is not a regular file.');
62
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, limit + 1));
63
+ let length = 0;
64
+ while (length < buffer.length) {
65
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
66
+ if (!bytesRead)
67
+ break;
68
+ length += bytesRead;
69
+ }
70
+ if (length > limit || length > stat.size)
71
+ throw new Error('Plugin file changed or exceeds size limit.');
72
+ return buffer.subarray(0, length);
73
+ }
74
+ finally {
75
+ await handle.close();
76
+ }
77
+ }
78
+ export function object(value) {
79
+ if (!value || typeof value !== 'object' || Array.isArray(value))
80
+ throw new Error('Expected a plugin JSON object.');
81
+ return value;
82
+ }
83
+ export async function readJson(file) {
84
+ return object(JSON.parse((await boundedRead(file, PLUGIN_LIMITS.json)).toString('utf8')));
85
+ }
86
+ async function exists(file) {
87
+ await safePath(file);
88
+ try {
89
+ await fs.lstat(file);
90
+ return true;
91
+ }
92
+ catch (error) {
93
+ if (error.code === 'ENOENT')
94
+ return false;
95
+ throw error;
96
+ }
97
+ }
98
+ export const PLUGIN_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json';
99
+ function isObject(value) {
100
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
101
+ }
102
+ async function hasStandardSkills(root) {
103
+ const directory = await safePath(root, 'skills');
104
+ try {
105
+ return (await fs.lstat(directory)).isDirectory();
106
+ }
107
+ catch (error) {
108
+ if (error.code === 'ENOENT')
109
+ return false;
110
+ throw error;
111
+ }
112
+ }
113
+ /** Read only the selected manifest; runtime loading must not walk unrelated components. */
114
+ export async function readPluginManifest(root, inferredName) {
115
+ const locations = [
116
+ ['plugin.json', 'portable'],
117
+ ['.claude-plugin/plugin.json', 'claude'],
118
+ ['.codex-plugin/plugin.json', 'codex'],
119
+ ];
120
+ for (const [manifestPath, format] of locations) {
121
+ const file = await safePath(root, manifestPath);
122
+ if (!await exists(file))
123
+ continue;
124
+ const raw = await readJson(file);
125
+ const warnings = [];
126
+ if (typeof raw.name !== 'string')
127
+ throw new Error('Plugin manifest requires a name.');
128
+ if (format === 'portable') {
129
+ if (raw.$schema !== PLUGIN_SCHEMA)
130
+ throw new Error(`Plugin $schema must be ${PLUGIN_SCHEMA}.`);
131
+ if (raw.name.length > 64 || /[^a-z0-9.-]/.test(raw.name) || !/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(raw.name)) {
132
+ throw new Error('Invalid portable plugin name: use 1–64 lowercase letters, numbers, hyphens or dots, starting and ending with a letter or number, without consecutive hyphens or dots.');
133
+ }
134
+ }
135
+ else
136
+ validatePluginName(raw.name);
137
+ const stringFields = format === 'portable'
138
+ ? ['version', 'description', 'homepage', 'repository', 'license']
139
+ : ['version', 'description'];
140
+ for (const key of stringFields)
141
+ if (key in raw && typeof raw[key] !== 'string')
142
+ throw new Error(`Plugin ${key} must be a string.`);
143
+ if (format === 'portable') {
144
+ if ('keywords' in raw && (!Array.isArray(raw.keywords) || raw.keywords.some(value => typeof value !== 'string')))
145
+ throw new Error('Plugin keywords must be an array of strings.');
146
+ if ('author' in raw) {
147
+ const author = object(raw.author);
148
+ for (const key of Object.keys(author)) {
149
+ if (!['name', 'email', 'url'].includes(key) || typeof author[key] !== 'string')
150
+ throw new Error('Plugin author must contain only string name, email and url fields.');
151
+ }
152
+ }
153
+ }
154
+ const supported = new Set(['name', 'version', 'description', 'extensions', 'author', 'license', 'homepage', 'repository', 'keywords', '$schema']);
155
+ if (format !== 'portable')
156
+ supported.add('skills');
157
+ const manifest = { name: raw.name };
158
+ for (const key of Object.keys(raw)) {
159
+ if (!supported.has(key))
160
+ warnings.push(`Unsupported plugin field/component: ${key}; ignored.`);
161
+ else if (key !== 'extensions')
162
+ manifest[key] = raw[key];
163
+ }
164
+ if (format !== 'portable' && manifest.skills !== undefined)
165
+ warnings.push('Declared legacy skills paths require explicit runtime resolution.');
166
+ if ('extensions' in raw) {
167
+ if (!isObject(raw.extensions))
168
+ warnings.push('Non-object plugin extensions; ignored.');
169
+ else {
170
+ const extensions = {};
171
+ for (const key of Object.keys(raw.extensions)) {
172
+ // Plugins install globally under ~/.haze and never write workspace
173
+ // content, so no extension namespace (including dev.haze) activates.
174
+ warnings.push(`Unsupported extension: ${key}; ignored.`);
175
+ }
176
+ manifest.extensions = extensions;
177
+ }
178
+ }
179
+ return { manifest, warnings, format };
180
+ }
181
+ if (await hasStandardSkills(root)) {
182
+ const name = inferredName ?? path.basename(path.resolve(root));
183
+ validatePluginName(name);
184
+ return { manifest: { name }, format: 'claude', warnings: [`No plugin manifest found; inferred Claude standard-layout plugin name: ${name}.`] };
185
+ }
186
+ throw new Error('No plugin.json, Claude or Codex plugin manifest found.');
187
+ }
188
+ export async function inspectPlugin(sourceDir, pluginName) {
189
+ return inspectPluginAt(sourceDir, pluginName, 0);
190
+ }
191
+ async function inspectPluginAt(sourceDir, pluginName, collectionDepth) {
192
+ if (collectionDepth > 32)
193
+ throw new Error('Plugin collection nesting exceeds limit.');
194
+ if (/^[a-z][a-z0-9+.-]*:|^git@/i.test(sourceDir))
195
+ throw new Error('Remote plugins are not supported. Clone the repository locally, then install its local directory.');
196
+ const source = path.resolve(sourceDir);
197
+ if (isProtectedSecretPath(source))
198
+ throw new Error('Protected secret path in plugin package.');
199
+ // Source roots may have host aliases (e.g. /var -> /private/var on macOS).
200
+ // Package-relative paths below this canonical root still refuse all symlinks.
201
+ const root = await safePath(await fs.realpath(source));
202
+ if (!(await fs.stat(root)).isDirectory())
203
+ throw new Error('Plugin source must be a directory.');
204
+ const hasManifest = await exists(path.join(root, 'plugin.json')) || await exists(path.join(root, '.claude-plugin/plugin.json')) || await exists(path.join(root, '.codex-plugin/plugin.json'));
205
+ if (hasManifest || await hasStandardSkills(root)) {
206
+ const { manifest, warnings } = await readPluginManifest(root, pluginName);
207
+ if (pluginName && manifest.name !== pluginName)
208
+ throw new Error('Selected plugin does not match manifest name.');
209
+ const files = [];
210
+ let total = 0;
211
+ let entries = 0;
212
+ async function walk(relative, depth = 0) {
213
+ if (depth > 32)
214
+ throw new Error('Plugin directory nesting exceeds limit.');
215
+ const directory = await fs.opendir(path.join(root, relative));
216
+ for await (const entry of directory) {
217
+ if (++entries > PLUGIN_LIMITS.entries)
218
+ throw new Error('Plugin has too many entries.');
219
+ const name = relative ? `${relative}/${entry.name}` : entry.name;
220
+ // Git metadata is not package content, and may contain credential URLs.
221
+ if (entry.name === '.git')
222
+ continue;
223
+ const target = await safePath(root, name);
224
+ if (entry.isDirectory())
225
+ await walk(name, depth + 1);
226
+ else if (entry.isFile()) {
227
+ const stat = await fs.stat(target);
228
+ total += stat.size;
229
+ if (stat.size > PLUGIN_LIMITS.file || total > PLUGIN_LIMITS.total)
230
+ throw new Error('Plugin package exceeds size limits.');
231
+ files.push(name);
232
+ }
233
+ else
234
+ throw new Error('Plugin contains a symlink or special file.');
235
+ }
236
+ }
237
+ await walk('');
238
+ const unsupported = new Set(['mcp.json', '.mcp.json', '.lsp.json', 'hooks', 'agents', 'commands', 'rules', 'lsp']);
239
+ const components = new Set(files.map(file => file.split('/')[0]).filter(component => unsupported.has(component)));
240
+ for (const component of [...components].sort())
241
+ warnings.push(`Unsupported plugin component: ${component}; not activated.`);
242
+ return { root, manifest, warnings, files: files.sort() };
243
+ }
244
+ for (const marketplacePath of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json']) {
245
+ const file = path.join(root, marketplacePath);
246
+ if (!await exists(file))
247
+ continue;
248
+ const marketplace = await readJson(file);
249
+ if (!pluginName)
250
+ throw new Error('This is a plugin collection; select a plugin name.');
251
+ validatePluginName(pluginName);
252
+ if (!Array.isArray(marketplace.plugins) || marketplace.plugins.length > PLUGIN_LIMITS.entries)
253
+ throw new Error('Invalid marketplace plugins list.');
254
+ const matches = marketplace.plugins.map(object).filter(entry => entry.name === pluginName);
255
+ if (matches.length !== 1)
256
+ throw new Error('Selected plugin must occur exactly once in the collection.');
257
+ const entry = matches[0];
258
+ let source = entry.source;
259
+ if (source && typeof source === 'object') {
260
+ const local = object(source);
261
+ if (local.source !== 'local')
262
+ throw new Error('Remote plugins are not supported. Clone the repository locally first.');
263
+ source = local.path;
264
+ }
265
+ else if (source === 'local')
266
+ source = entry.path;
267
+ if (typeof source !== 'string' || !source.startsWith('./'))
268
+ throw new Error('Collection sources must be local ./paths. Clone remote repositories locally first.');
269
+ const relative = localPath(source);
270
+ if (!relative || relative === '.')
271
+ throw new Error('Collection plugin source cannot point at the collection root.');
272
+ return inspectPluginAt(await safePath(root, relative), pluginName, collectionDepth + 1);
273
+ }
274
+ throw new Error('No plugin.json, Claude or Codex plugin manifest found.');
275
+ }
@@ -0,0 +1,3 @@
1
+ import type { LoadedSkill, SkillRegistry } from '../types.js';
2
+ /** Installed receipts are the only activation authority; never discover caches or collections. */
3
+ export declare function loadPluginSkills(errors: SkillRegistry['errors']): Promise<LoadedSkill[]>;