@denizokcu/haze 1.5.1 → 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 (87) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +61 -3
  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 +1 -1
  7. package/dist/cli/chat/inputSuggestions.js +2 -0
  8. package/dist/cli/chat/terminalControl.d.ts +4 -2
  9. package/dist/cli/chat/terminalControl.js +16 -5
  10. package/dist/cli/chat/wizard/pluginHandlers.d.ts +10 -0
  11. package/dist/cli/chat/wizard/pluginHandlers.js +156 -0
  12. package/dist/cli/chat/wizard/skillsHandlers.js +2 -2
  13. package/dist/cli/chat/wizard/types.d.ts +20 -0
  14. package/dist/cli/chat/wizard/uiState.d.ts +25 -1
  15. package/dist/cli/chat/wizard/uiState.js +3 -1
  16. package/dist/cli/chat/wizardDispatch.js +6 -0
  17. package/dist/cli/commands/chat.js +18 -3
  18. package/dist/cli/commands/commandHelp.js +7 -2
  19. package/dist/cli/commands/commands.d.ts +5 -0
  20. package/dist/cli/commands/commands.js +17 -3
  21. package/dist/cli/commands/initCommand.js +3 -2
  22. package/dist/cli/commands/pluginCommand.d.ts +16 -0
  23. package/dist/cli/commands/pluginCommand.js +127 -0
  24. package/dist/cli/commands/reasoningCommand.d.ts +0 -15
  25. package/dist/cli/commands/reasoningCommand.js +1 -3
  26. package/dist/cli/commands/skillsWizard.js +4 -0
  27. package/dist/cli/commands/streaming/agentAttempt.js +2 -1
  28. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  29. package/dist/cli/commands/streaming/attemptOutcome.js +4 -3
  30. package/dist/cli/commands/streaming/attemptSetup.d.ts +2 -0
  31. package/dist/cli/commands/streaming/attemptSetup.js +3 -2
  32. package/dist/cli/commands/streaming/stallRecovery.d.ts +6 -0
  33. package/dist/cli/commands/streaming/stallRecovery.js +6 -5
  34. package/dist/cli/commands/streaming/turnRuntime.js +2 -4
  35. package/dist/cli/commands/wizardFlow.d.ts +59 -0
  36. package/dist/cli/commands/wizardFlow.js +40 -0
  37. package/dist/cli/contextReportCli.js +4 -3
  38. package/dist/cli/index.js +19 -2
  39. package/dist/config/contextFiles.js +3 -2
  40. package/dist/config/inputHistory.js +3 -3
  41. package/dist/config/paths.d.ts +1 -0
  42. package/dist/config/paths.js +1 -0
  43. package/dist/config/providerAuth.js +3 -3
  44. package/dist/config/settings.d.ts +10 -1
  45. package/dist/config/settings.js +7 -4
  46. package/dist/config/updateCheck.js +3 -3
  47. package/dist/core/agent/budgets.d.ts +17 -0
  48. package/dist/core/agent/budgets.js +19 -0
  49. package/dist/core/agent/reasoningPolicy.js +1 -1
  50. package/dist/core/agent/workState.d.ts +0 -2
  51. package/dist/core/agent/workState.js +1 -1
  52. package/dist/core/log/llmLog.js +1 -1
  53. package/dist/core/session/sessionStore.js +4 -3
  54. package/dist/core/subagent/contracts.d.ts +1 -11
  55. package/dist/core/subagent/contracts.js +0 -22
  56. package/dist/llm/client.js +1 -1
  57. package/dist/llm/subagentRunner.d.ts +1 -6
  58. package/dist/llm/subagentRunner.js +11 -23
  59. package/dist/llm/tools/fileTools.js +2 -3
  60. package/dist/llm/tools/gitIgnore.js +1 -1
  61. package/dist/llm/tools/grepRunner.d.ts +10 -0
  62. package/dist/llm/tools/grepRunner.js +24 -0
  63. package/dist/llm/tools/toolContext.d.ts +2 -3
  64. package/dist/llm/tools/toolContext.js +2 -3
  65. package/dist/llm/tools/toolContextState.d.ts +0 -1
  66. package/dist/llm/tools/toolContextState.js +1 -4
  67. package/dist/llm/workerContext.d.ts +0 -7
  68. package/dist/llm/workerContext.js +0 -17
  69. package/dist/skills/SkillLoader.js +3 -2
  70. package/dist/skills/SkillRegistry.js +7 -4
  71. package/dist/skills/builder/SkillBuilder.js +11 -10
  72. package/dist/skills/plugins/installer.d.ts +25 -0
  73. package/dist/skills/plugins/installer.js +272 -0
  74. package/dist/skills/plugins/package.d.ts +41 -0
  75. package/dist/skills/plugins/package.js +275 -0
  76. package/dist/skills/plugins/runtime.d.ts +3 -0
  77. package/dist/skills/plugins/runtime.js +108 -0
  78. package/dist/skills/skillTools.js +10 -5
  79. package/dist/skills/types.d.ts +4 -0
  80. package/dist/ui/codeHighlight.d.ts +1 -1
  81. package/dist/ui/codeHighlight.js +112 -4
  82. package/dist/ui/components/StreamingMarkdownText.d.ts +0 -2
  83. package/dist/ui/components/StreamingMarkdownText.js +1 -1
  84. package/dist/ui/components/TextInput.d.ts +1 -1
  85. package/dist/utils/fs.d.ts +10 -0
  86. package/dist/utils/fs.js +37 -2
  87. package/package.json +17 -20
@@ -11,7 +11,6 @@ import type { WorkspaceMutationOwner, WorkspaceMutationPolicy } from '../../core
11
11
  export type ToolExecutionContext = {
12
12
  abortSignal?: AbortSignal;
13
13
  context?: unknown;
14
- experimental_context?: unknown;
15
14
  };
16
15
  export type PostMutationDiagnostics = (paths: readonly string[]) => Promise<unknown | undefined>;
17
16
  export type HazeToolContext = {
@@ -27,8 +27,5 @@ export function isHazeToolContext(value) {
27
27
  && validOptional('postMutationDiagnostics', field => typeof field === 'function');
28
28
  }
29
29
  export function hazeContext(context) {
30
- const value = typeof context.context === 'object' && context.context != null
31
- ? context.context
32
- : context.experimental_context;
33
- return isHazeToolContext(value) ? value : undefined;
30
+ return isHazeToolContext(context.context) ? context.context : undefined;
34
31
  }
@@ -16,10 +16,3 @@ export interface WorkerContextBundle {
16
16
  }
17
17
  export declare function workerTaskMessage(task: SubagentTaskCapsule): string;
18
18
  export declare function assembleWorkerContext(task: SubagentTaskCapsule, profile: SubagentExecutionProfile, session?: PromptSession): Promise<WorkerContextBundle>;
19
- /**
20
- * Legacy compatibility bundle for callers (e.g. `/fleet`) that pass explicit
21
- * context files and an optional tool allowlist instead of letting the worker
22
- * resolve its own context. Moved from `llm/subagentRunner.ts` so the
23
- * runner stays free of `llm` imports.
24
- */
25
- export declare function compatibilityBundle(task: SubagentTaskCapsule, profile: SubagentExecutionProfile, contextFiles: ContextFile[], allowedTools: readonly string[] | undefined, session: PromptSession | undefined): Promise<WorkerContextBundle>;
@@ -53,20 +53,3 @@ export async function assembleWorkerContext(task, profile, session) {
53
53
  return { instructions: [], loadedPaths: new Set(), loadedSignatures: new Map(), systemPrompt: '', tools: {}, estimatedTokens: 0, taskTokens: estimateValueTokens(workerTaskMessage(task)), validatedScope: [], policyBlock: reason };
54
54
  }
55
55
  }
56
- /**
57
- * Legacy compatibility bundle for callers (e.g. `/fleet`) that pass explicit
58
- * context files and an optional tool allowlist instead of letting the worker
59
- * resolve its own context. Moved from `llm/subagentRunner.ts` so the
60
- * runner stays free of `llm` imports.
61
- */
62
- export async function compatibilityBundle(task, profile, contextFiles, allowedTools, session) {
63
- const instructions = contextFiles;
64
- const systemPrompt = buildSubagentPrompt(instructions, session, task.mode, profile);
65
- const tools = {};
66
- for (const name of allowedTools ?? MODE_TOOL_NAMES[task.mode])
67
- if (name in hazeTools)
68
- tools[name] = hazeTools[name];
69
- const taskTokens = estimateValueTokens(workerTaskMessage(task));
70
- const estimatedTokens = estimateTextTokens(systemPrompt) + taskTokens + estimateToolSchemas(tools).reduce((sum, value) => sum + value.tokens, 0);
71
- return { instructions, systemPrompt, tools, taskTokens, estimatedTokens, validatedScope: [], loadedPaths: new Set(instructions.map(file => file.path)), loadedSignatures: new Map(instructions.flatMap(file => file.signature ? [[file.path, file.signature]] : [])), ...(estimatedTokens > profile.maxInputTokens ? { policyBlock: `Worker input estimate ${estimatedTokens} exceeds profile ${profile.name} limit ${profile.maxInputTokens}.` } : {}) };
72
- }
@@ -1,4 +1,5 @@
1
- import fs from 'fs-extra';
1
+ import fs from 'node:fs/promises';
2
+ import { pathExists } from '../utils/fs.js';
2
3
  import path from 'node:path';
3
4
  import YAML from 'yaml';
4
5
  import { confinedResolve } from './confinement.js';
@@ -74,7 +75,7 @@ async function loadReference(dir, referencePath) {
74
75
  }
75
76
  export async function loadSkill(dir, source = 'global') {
76
77
  const skillPath = path.join(dir, 'SKILL.md');
77
- if (!(await fs.pathExists(skillPath)))
78
+ if (!(await pathExists(skillPath)))
78
79
  return null;
79
80
  const realSkillPath = await confinedResolve(dir, skillPath, 'SKILL.md', 'skill directory');
80
81
  if (isProtectedSecretPath(realSkillPath))
@@ -1,10 +1,12 @@
1
- import fs from 'fs-extra';
1
+ import fs from 'node:fs/promises';
2
+ import { pathExists, ensureDir } from '../utils/fs.js';
2
3
  import path from 'node:path';
3
4
  import { GLOBAL_SKILLS_DIR } from '../config/paths.js';
4
5
  import { loadSkill } from './SkillLoader.js';
5
6
  import { confinedResolve } from './confinement.js';
7
+ import { loadPluginSkills } from './plugins/runtime.js';
6
8
  async function loadRoot(root, containmentRoot, source, errors) {
7
- if (!(await fs.pathExists(root)))
9
+ if (!(await pathExists(root)))
8
10
  return [];
9
11
  if (source === 'project') {
10
12
  try {
@@ -50,11 +52,12 @@ export function resolveSkillCandidates(candidates, enabled = () => true) {
50
52
  }
51
53
  export async function loadSkillRegistry(cwd = process.cwd()) {
52
54
  const errors = [];
53
- await fs.ensureDir(GLOBAL_SKILLS_DIR);
55
+ await ensureDir(GLOBAL_SKILLS_DIR);
54
56
  const global = await loadRoot(GLOBAL_SKILLS_DIR, GLOBAL_SKILLS_DIR, 'global', errors);
55
57
  const projectRoot = path.join(cwd, '.haze', 'skills');
56
58
  const project = await loadRoot(projectRoot, cwd, 'project', errors);
57
- const candidates = [...project, ...global];
59
+ const plugins = await loadPluginSkills(errors);
60
+ const candidates = [...project, ...plugins, ...global];
58
61
  const skills = resolveSkillCandidates(candidates);
59
62
  return { skills, candidates, errors };
60
63
  }
@@ -1,5 +1,6 @@
1
1
  import { generateObject } from 'ai';
2
- import fs from 'fs-extra';
2
+ import fs from 'node:fs/promises';
3
+ import { ensureDir, move, pathExists } from '../../utils/fs.js';
3
4
  import path from 'node:path';
4
5
  import YAML from 'yaml';
5
6
  import { GLOBAL_SKILLS_DIR } from '../../config/paths.js';
@@ -239,10 +240,10 @@ async function skillTargetRoot(input) {
239
240
  return { root: GLOBAL_SKILLS_DIR, source: 'global' };
240
241
  const cwd = path.resolve(input.cwd ?? process.cwd());
241
242
  const hazeDir = path.join(cwd, '.haze');
242
- if (await fs.pathExists(hazeDir))
243
+ if (await pathExists(hazeDir))
243
244
  await confinedResolve(cwd, hazeDir, '.haze', 'workspace');
244
245
  const root = path.join(hazeDir, 'skills');
245
- await fs.ensureDir(root);
246
+ await ensureDir(root);
246
247
  await confinedResolve(cwd, root, '.haze/skills', 'workspace');
247
248
  return { root, source: 'project' };
248
249
  }
@@ -263,19 +264,19 @@ export async function createSkill(input) {
263
264
  const skillFile = path.join(dir, 'SKILL.md');
264
265
  // Never populate a pre-existing directory: it may contain symlinks planted by
265
266
  // repository content, and creation is expected to be new and atomic in scope.
266
- if (await fs.pathExists(dir))
267
+ if (await pathExists(dir))
267
268
  throw new Error(`Skill already exists: ${finalName}`);
268
- await fs.ensureDir(dir);
269
- if (await fs.pathExists(skillFile))
269
+ await ensureDir(dir);
270
+ if (await pathExists(skillFile))
270
271
  throw new Error(`Skill already exists: ${finalName}`);
271
272
  for (const generatedFile of generated.files) {
272
273
  const safePath = assertSafeGeneratedFile(generatedFile.path);
273
274
  const absolutePath = path.join(dir, safePath);
274
- await fs.ensureDir(path.dirname(absolutePath));
275
+ await ensureDir(path.dirname(absolutePath));
275
276
  const content = safePath === 'SKILL.md' ? withSkillName(withStandardRequirements(generatedFile.content), finalName) : generatedFile.content;
276
277
  await fs.writeFile(absolutePath, content, 'utf8');
277
278
  }
278
- if (!(await fs.pathExists(skillFile))) {
279
+ if (!(await pathExists(skillFile))) {
279
280
  const fallback = fallbackSkill(normalizedInput);
280
281
  await fs.writeFile(skillFile, fallback.files[0].content, 'utf8');
281
282
  }
@@ -284,9 +285,9 @@ export async function createSkill(input) {
284
285
  throw new Error('Generated skill is missing SKILL.md');
285
286
  if (loaded.name !== finalName) {
286
287
  const nextDir = path.join(root, loaded.name);
287
- if (await fs.pathExists(nextDir))
288
+ if (await pathExists(nextDir))
288
289
  throw new Error(`Skill already exists: ${loaded.name}`);
289
- await fs.move(dir, nextDir);
290
+ await move(dir, nextDir);
290
291
  return { name: loaded.name, dir: nextDir, file: path.join(nextDir, 'SKILL.md') };
291
292
  }
292
293
  return { name: finalName, dir, file: skillFile };
@@ -0,0 +1,25 @@
1
+ export interface PluginInstallResult {
2
+ name: string;
3
+ version?: string;
4
+ alreadyInstalled: boolean;
5
+ warnings: string[];
6
+ }
7
+ export interface InstalledPlugin {
8
+ name: string;
9
+ version?: string;
10
+ }
11
+ export interface PluginEnumeration {
12
+ plugins: InstalledPlugin[];
13
+ errors: {
14
+ directory: string;
15
+ message: string;
16
+ }[];
17
+ }
18
+ export interface PluginRemoveResult {
19
+ name: string;
20
+ retained: string[];
21
+ }
22
+ export declare function installPlugin(sourceDir: string, pluginName?: string): Promise<PluginInstallResult>;
23
+ export declare function enumeratePlugins(): Promise<PluginEnumeration>;
24
+ export declare function listPlugins(): Promise<InstalledPlugin[]>;
25
+ export declare function removePlugin(name: string): Promise<PluginRemoveResult>;
@@ -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>;