@larkup/marketplace 0.1.25 → 0.2.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 (40) hide show
  1. package/.env.example +3 -0
  2. package/CHANGELOG.md +173 -0
  3. package/README.md +34 -0
  4. package/db/drizzle/0000_hesitant_joseph.sql +69 -0
  5. package/db/drizzle/0001_deep_phil_sheldon.sql +1 -0
  6. package/db/drizzle/0002_jittery_living_mummy.sql +18 -0
  7. package/db/drizzle/meta/0000_snapshot.json +483 -0
  8. package/db/drizzle/meta/0001_snapshot.json +490 -0
  9. package/db/drizzle/meta/0002_snapshot.json +615 -0
  10. package/db/drizzle/meta/_journal.json +27 -0
  11. package/db/drizzle.config.ts +19 -0
  12. package/db/tsconfig.build.json +11 -0
  13. package/db/tsconfig.json +17 -0
  14. package/db/vitest.config.ts +11 -0
  15. package/package.json +31 -4
  16. package/src/db/builtin-tools.ts +613 -0
  17. package/src/db/client.ts +26 -0
  18. package/src/db/repo.test.ts +309 -0
  19. package/src/db/repo.ts +558 -0
  20. package/src/db/schema/audit.ts +27 -0
  21. package/src/db/schema/extensions.ts +73 -0
  22. package/src/db/schema/index.ts +5 -0
  23. package/src/db/schema/installations.ts +23 -0
  24. package/src/db/schema/publishers.ts +13 -0
  25. package/src/db/schema/versions.ts +22 -0
  26. package/src/db/seed.ts +33 -0
  27. package/src/db/validate.test.ts +79 -0
  28. package/src/db/validate.ts +84 -0
  29. package/src/output-sanitizer.test.ts +17 -0
  30. package/src/output-sanitizer.ts +8 -0
  31. package/src/storage-provider-s3.test.ts +110 -0
  32. package/src/storage-provider.ts +164 -13
  33. package/src/tool-extension.ts +247 -0
  34. package/src/tool-installer.ts +80 -109
  35. package/src/tool-loader.test.ts +120 -0
  36. package/src/tool-loader.ts +99 -37
  37. package/src/tool-manifest.schema.ts +89 -32
  38. package/src/tool-registry.ts +34 -111
  39. package/src/types.ts +217 -87
  40. package/vitest.config.ts +13 -0
@@ -0,0 +1,247 @@
1
+ import { loadTool } from './tool-loader';
2
+
3
+ export interface ToolExtensionContext {
4
+ config: Record<string, unknown>;
5
+ fetch?: typeof globalThis.fetch;
6
+ trackUsage?: (event: {
7
+ meter: string;
8
+ quantity: number;
9
+ unit: string;
10
+ metadata?: Record<string, unknown>;
11
+ }) => void | Promise<void>;
12
+ }
13
+
14
+ /** Per-call data supplied by a host after the tool has been installed. */
15
+ export interface AgentToolExecutionContext {
16
+ /** The host application's origin, for a tool-owned host API adapter when needed. */
17
+ origin?: string;
18
+ /** Isolates a tool action to the active project/workspace. */
19
+ projectId?: string;
20
+ /** Lets a long-running tool associate progress with the visible chat row. */
21
+ toolCallId?: string;
22
+ /**
23
+ * Optional host-owned immutable media evidence access. Tools keep the
24
+ * investigation policy; the host only supplies scoped data access.
25
+ */
26
+ mediaEvidence?: {
27
+ getAsset: (mediaAssetId: string) => Promise<
28
+ | {
29
+ id: string;
30
+ type: string;
31
+ processingStatus?: string;
32
+ durationSecs?: number;
33
+ fileName?: string;
34
+ originalUrl?: string;
35
+ }
36
+ | undefined
37
+ >;
38
+ planQuestion: (question: string) => {
39
+ kinds: string[];
40
+ requiresInspectionWhenInsufficient: boolean;
41
+ requiresBothRanges?: boolean;
42
+ requiresBroadCoverage?: boolean;
43
+ /** Optional named subject resolved by the host's generic media planner. */
44
+ subjectName?: string;
45
+ };
46
+ /**
47
+ * Ranked windows worth looking at for this question, fused from every
48
+ * timestamped retrieval signal the host holds (semantic evidence, clip
49
+ * vectors). It reports agreement about *where*, never what is there, so a
50
+ * tool still reads the evidence itself before making any claim. Optional:
51
+ * a host without embeddings does not provide it.
52
+ */
53
+ locate?: (
54
+ mediaAssetId: string,
55
+ question: string,
56
+ options?: { maxRanges?: number; maxWindowSecs?: number },
57
+ ) => Promise<
58
+ Array<{
59
+ startSecs: number;
60
+ endSecs: number;
61
+ score: number;
62
+ sources: string[];
63
+ label?: string;
64
+ }>
65
+ >;
66
+ planInvestigation?: (
67
+ mediaAssetId: string,
68
+ question: string,
69
+ ) => Promise<
70
+ | {
71
+ candidateRanges: Array<{
72
+ startSecs: number;
73
+ endSecs: number;
74
+ precision?: string;
75
+ reason: string;
76
+ }>;
77
+ chapters?: Array<{
78
+ title: string;
79
+ summary: string;
80
+ timeRange: { startSecs: number; endSecs: number; precision?: string };
81
+ }>;
82
+ scenes?: Array<{
83
+ title: string;
84
+ summary: string;
85
+ timeRange: { startSecs: number; endSecs: number; precision?: string };
86
+ }>;
87
+ coverage?: {
88
+ mode: 'focused' | 'broad';
89
+ totalChapters: number;
90
+ totalScenes: number;
91
+ representedRanges: number;
92
+ };
93
+ }
94
+ | undefined
95
+ >;
96
+ /**
97
+ * Re-reads bounded windows of the original source to settle a question the
98
+ * index cannot, and reports what that reading established.
99
+ *
100
+ * This is the interactive counterpart to dispatching a re-index: windows are
101
+ * read together and the whole step is budgeted for a live turn, so a tool
102
+ * can verify a claim inside a reply instead of leaving it unconfirmed.
103
+ * Optional -- a host without source access or a vision capability omits it,
104
+ * and a tool must still work when it is absent.
105
+ */
106
+ reWatch?: (
107
+ mediaAssetId: string,
108
+ question: string,
109
+ ranges: Array<{ startSecs: number; endSecs: number; lookingFor?: string }>,
110
+ options?: { maxWaitMs?: number; knownEntities?: string[] },
111
+ ) => Promise<
112
+ Array<{
113
+ range: { startSecs: number; endSecs: number };
114
+ at: string;
115
+ found: string;
116
+ read: string[];
117
+ confidence: 'high' | 'medium' | 'low';
118
+ /** True only when this reading actually settles the asked question. */
119
+ settlesQuestion: boolean;
120
+ }>
121
+ >;
122
+ search: (
123
+ mediaAssetId: string,
124
+ query: string,
125
+ limit: number,
126
+ options?: Record<string, unknown>,
127
+ ) => Promise<
128
+ Array<{
129
+ evidence: {
130
+ id: string;
131
+ modality: string;
132
+ timeRange: { startSecs: number; endSecs: number; precision?: string };
133
+ /**
134
+ * When this record entered the index, as an ISO timestamp. It lets a
135
+ * tool tell evidence it just caused to be gathered from evidence that
136
+ * was already there -- which is not something the payload can say.
137
+ */
138
+ createdAt: string;
139
+ payload: unknown;
140
+ source?: {
141
+ kind: string;
142
+ provider?: string;
143
+ model?: string;
144
+ version?: string;
145
+ };
146
+ confidence: unknown;
147
+ };
148
+ }>
149
+ >;
150
+ };
151
+ }
152
+
153
+ /** A client method invoked by an AgentToolDefinition. */
154
+ export type AgentToolHandler = (
155
+ input: unknown,
156
+ context: AgentToolExecutionContext,
157
+ ) => unknown | Promise<unknown>;
158
+
159
+ export interface ToolExtension<TClient = unknown> {
160
+ id: string;
161
+ apiVersion: '1';
162
+ createClient(context: ToolExtensionContext): TClient;
163
+ /** Optionally prepares a declared runtime after the user has installed and selected it. */
164
+ ensureRuntime?(context: ToolExtensionContext): Promise<void>;
165
+ /** Restarts a user-managed runtime after credentials or other runtime settings change. */
166
+ restartRuntime?(context: ToolExtensionContext): Promise<void>;
167
+ /** Prepares a local runtime (e.g. pulls an image, syncs dependencies) without starting it. */
168
+ installRuntime?(context: ToolExtensionContext): Promise<void>;
169
+ /** Stops a running local runtime without uninstalling it. */
170
+ stopRuntime?(context: ToolExtensionContext): Promise<void>;
171
+ /** Verifies a tool-owned runtime or model configuration before it is saved. */
172
+ verifyConfiguration?(context: ToolExtensionContext & { verifyKey?: string }): Promise<void>;
173
+ /** Removes a local runtime's container/process and persisted runtime data after tool removal. */
174
+ removeRuntime?(context: ToolExtensionContext): Promise<void>;
175
+ /**
176
+ * Optional, tool-defined host/environment report (e.g. Docker vs. native
177
+ * availability, system suitability) for a settings UI to render before
178
+ * installing a local runtime. Shape is entirely up to the tool — the host
179
+ * only passes it through as JSON.
180
+ */
181
+ getHostCapabilities?(context: ToolExtensionContext): Promise<Record<string, unknown>>;
182
+ /**
183
+ * Optional runtime-specific provisioning. The host persists only `config`,
184
+ * keeping tool names and credential formats out of host UI code.
185
+ */
186
+ provisionRuntime?(context: ToolExtensionContext): Promise<{
187
+ config: Record<string, unknown>;
188
+ display?: Record<string, string>;
189
+ }>;
190
+ }
191
+
192
+ /** Defines the stable server-side boundary implemented by installable tools. */
193
+ export function defineToolExtension<TClient>(
194
+ extension: ToolExtension<TClient>,
195
+ ): ToolExtension<TClient> {
196
+ return extension;
197
+ }
198
+
199
+ /** Loads and validates an installed tool extension without knowing its domain API. */
200
+ export async function loadToolExtension<TClient = unknown>(
201
+ toolId: string,
202
+ ): Promise<ToolExtension<TClient> | null> {
203
+ const module = await loadTool<Record<string, unknown>>(toolId);
204
+ if (!module) return null;
205
+ const candidate = (module.TOOL_EXTENSION ?? module.default) as Partial<ToolExtension<TClient>>;
206
+ if (
207
+ !candidate ||
208
+ candidate.id !== toolId ||
209
+ candidate.apiVersion !== '1' ||
210
+ typeof candidate.createClient !== 'function'
211
+ ) {
212
+ throw new Error(`Installed tool "${toolId}" does not expose a valid ToolExtension v1.`);
213
+ }
214
+ return candidate as ToolExtension<TClient>;
215
+ }
216
+
217
+ /**
218
+ * One agent-callable action a tool exposes generically to any chat runtime.
219
+ * A host reads this off the installed module — never hardcodes a tool's
220
+ * name, schema, or behavior — and calls `client[method](input)` on the
221
+ * client `ToolExtension.createClient()` already returned. A tool with
222
+ * several distinct actions exports `AGENT_TOOLS: AgentToolDefinition[]`
223
+ * instead of a single `AGENT_TOOL`.
224
+ */
225
+ export interface AgentToolDefinition {
226
+ /** Tool-call name shown to the model. Must be unique among a session's active tools. */
227
+ name: string;
228
+ description: string;
229
+ /** JSON Schema (not a framework-specific schema type) for the call's input. */
230
+ parameters: Record<string, unknown>;
231
+ /** Method on the ToolExtension client this call invokes, e.g. `client[method](input)`. */
232
+ method: string;
233
+ /** Appended to the agent's system prompt once this tool is installed and authorized. */
234
+ systemPromptFragment?: string;
235
+ /**
236
+ * Optional host-generic workflow role. This is intentionally about the
237
+ * action, not a tool id, so a replacement Marketplace tool can provide the
238
+ * same capability without changes to the chat route.
239
+ */
240
+ workflow?: 'evidence-refinement' | 'evidence-query';
241
+ /** Source handle accepted by an evidence-query capability. */
242
+ evidenceInput?: 'media-asset';
243
+ }
244
+
245
+ export function defineAgentTool(definition: AgentToolDefinition): AgentToolDefinition {
246
+ return definition;
247
+ }
@@ -1,4 +1,5 @@
1
1
  import { promises as fs } from 'node:fs';
2
+ import type { Dirent } from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { exec as execCb } from 'node:child_process';
4
5
  import { promisify } from 'node:util';
@@ -12,11 +13,19 @@ import type {
12
13
  } from './types';
13
14
  import { getToolById, invalidateRegistryCache } from './tool-registry';
14
15
 
16
+ const installingTools = new Set<string>();
17
+ const uninstallingTools = new Set<string>();
18
+
19
+ export function getOngoingOperations() {
20
+ return {
21
+ installing: Array.from(installingTools),
22
+ uninstalling: Array.from(uninstallingTools),
23
+ };
24
+ }
25
+
15
26
  const execAsync = promisify(execCb);
16
27
 
17
- // npm mutates a shared node_modules tree. Serializing those mutations prevents
18
- // double-clicks or concurrent API requests from colliding during npm's rename
19
- // phase (the source of the ENOTEMPTY failures seen in installed applications).
28
+ // npm mutates a shared node_modules tree.
20
29
  let packageMutationChain: Promise<unknown> = Promise.resolve();
21
30
  function serializePackageMutation<T>(fn: () => Promise<T>): Promise<T> {
22
31
  const run = packageMutationChain.then(fn, fn);
@@ -26,27 +35,8 @@ function serializePackageMutation<T>(fn: () => Promise<T>): Promise<T> {
26
35
 
27
36
  /**
28
37
  * Tool installer — manages installing / uninstalling marketplace tools.
29
- *
30
- * Architecture:
31
- * ─────────────────────────────────────────────────────────────────────
32
- * Tools are installed into an ISOLATED directory:
33
- * `.larkup/tools/node_modules/@larkup/tool-*`
34
- *
35
- * This design:
36
- * - Keeps the user's project package.json clean (no pollution)
37
- * - Makes tools portable — copy `.larkup/tools/` to any machine
38
- * - Enables per-agent tool sets (future: each agent has its own tools dir)
39
- * - Works identically across local, Docker, and sandbox deployments
40
- *
41
- * The installer tracks state in `.larkup/tools/installed.json`.
42
- * The loader resolves modules from the isolated node_modules.
43
- * ─────────────────────────────────────────────────────────────────────
44
38
  */
45
39
 
46
- /* ------------------------------------------------------------------ */
47
- /* Paths */
48
- /* ------------------------------------------------------------------ */
49
-
50
40
  /** Root directory for tool installations. */
51
41
  function getToolsDir(): string {
52
42
  return path.join(process.cwd(), '.larkup', 'tools');
@@ -62,10 +52,6 @@ export function getToolsNodeModulesDir(): string {
62
52
  return path.join(getToolsDir(), 'node_modules');
63
53
  }
64
54
 
65
- /* ------------------------------------------------------------------ */
66
- /* Manifest persistence */
67
- /* ------------------------------------------------------------------ */
68
-
69
55
  async function ensureDir() {
70
56
  await fs.mkdir(getToolsDir(), { recursive: true });
71
57
  }
@@ -99,16 +85,8 @@ async function writeManifest(manifest: InstalledToolsManifest) {
99
85
  await fs.writeFile(getManifestPath(), JSON.stringify(manifest, null, 2), 'utf8');
100
86
  }
101
87
 
102
- /* ------------------------------------------------------------------ */
103
- /* Public query API */
104
- /* ------------------------------------------------------------------ */
105
-
106
88
  export async function getInstalledTools(): Promise<InstalledTool[]> {
107
89
  const manifest = await readManifest();
108
- // A package being bundled with the application only makes it *available* to
109
- // install. It must not silently enable an optional capability or make the
110
- // Marketplace claim it was installed. The manifest is the single source of
111
- // truth, which also makes uninstall immediately reflect in the UI.
112
90
  return [...manifest.tools];
113
91
  }
114
92
 
@@ -128,10 +106,6 @@ export async function getDownloadCounts(): Promise<Record<string, number>> {
128
106
  return manifest.downloadCounts;
129
107
  }
130
108
 
131
- /* ------------------------------------------------------------------ */
132
- /* System dependency checks */
133
- /* ------------------------------------------------------------------ */
134
-
135
109
  /** Known install commands per dependency per platform. */
136
110
  const INSTALL_HINTS: Record<string, Record<string, string>> = {
137
111
  ffmpeg: {
@@ -151,10 +125,6 @@ function detectPlatform(): string {
151
125
  return 'linux';
152
126
  }
153
127
 
154
- /**
155
- * Attempt to auto-install a system dependency using the platform package manager.
156
- * Returns true if the dependency is available after the attempt.
157
- */
158
128
  async function tryAutoInstallDep(
159
129
  dep: string,
160
130
  onProgress?: (message: string) => void,
@@ -254,13 +224,7 @@ export async function checkSystemDeps(toolId: string): Promise<string[]> {
254
224
  const missing: string[] = [];
255
225
  for (const dep of descriptor.systemDeps) {
256
226
  // Video & Audio ships a platform binary via @ffmpeg-installer/ffmpeg.
257
- // Older Hub manifests still advertise ffmpeg as a host prerequisite; do
258
- // not let that stale metadata block installation.
259
227
  if (toolId === 'video-audio' && dep === 'ffmpeg') continue;
260
- // A container cannot normally talk to the host Docker daemon. Do not block
261
- // installation of tools that use Docker only for optional capabilities
262
- // (for example DOCX/PPTX editing); those capabilities report their own
263
- // actionable error when actually used.
264
228
  if (target === 'docker' && dep === 'docker') continue;
265
229
  try {
266
230
  await execAsync(`which ${dep}`);
@@ -271,10 +235,6 @@ export async function checkSystemDeps(toolId: string): Promise<string[]> {
271
235
  return missing;
272
236
  }
273
237
 
274
- /* ------------------------------------------------------------------ */
275
- /* Install execution — the core logic */
276
- /* ------------------------------------------------------------------ */
277
-
278
238
  /**
279
239
  * Detect the current deployment target from environment.
280
240
  */
@@ -468,19 +428,12 @@ async function resolveManifest(toolId: string): Promise<ToolDescriptor> {
468
428
 
469
429
  /**
470
430
  * Determine the install source based on the environment.
471
- * In the monorepo (development), tools are already available as workspace packages.
472
- * Outside the monorepo, tools are downloaded from npm.
473
431
  */
474
432
  async function isWorkspaceTool(packageName: string): Promise<boolean> {
475
433
  return Boolean(await resolveWorkspaceToolPath(packageName));
476
434
  }
477
435
 
478
- /**
479
- * Return the real package root for a pnpm/workspace-linked tool. This must not
480
- * rely on CommonJS `require.resolve`: Next.js route handlers run as ESM and
481
- * can otherwise mistake a bundled workspace tool for a remote npm package.
482
- */
483
- async function resolveWorkspaceToolPath(packageName: string): Promise<string | undefined> {
436
+ export async function resolveWorkspaceToolPath(packageName: string): Promise<string | undefined> {
484
437
  try {
485
438
  const linkedPath = path.join(process.cwd(), 'node_modules', ...packageName.split('/'));
486
439
  const packageRoot = await fs.realpath(linkedPath);
@@ -489,38 +442,61 @@ async function resolveWorkspaceToolPath(packageName: string): Promise<string | u
489
442
  ) as {
490
443
  name?: string;
491
444
  };
492
- // Registry packages resolve inside node_modules; a pnpm workspace link
493
- // resolves to the repository package directory outside of it.
494
445
  return manifest.name === packageName &&
495
446
  !packageRoot.includes(`${path.sep}node_modules${path.sep}`)
496
447
  ? packageRoot
497
448
  : undefined;
449
+ } catch {
450
+ // A newly scaffolded workspace tool may not be linked into root
451
+ // node_modules until the next pnpm install. Resolve it from the workspace
452
+ // package directory so Marketplace development never falls through to npm.
453
+ }
454
+
455
+ let workspaceRoot = process.cwd();
456
+ while (true) {
457
+ try {
458
+ await fs.access(path.join(workspaceRoot, 'pnpm-workspace.yaml'));
459
+ break;
460
+ } catch {
461
+ const parent = path.dirname(workspaceRoot);
462
+ if (parent === workspaceRoot) return undefined;
463
+ workspaceRoot = parent;
464
+ }
465
+ }
466
+
467
+ const toolsRoot = path.join(workspaceRoot, 'packages', 'marketplace-tools');
468
+ let entries: Dirent[];
469
+ try {
470
+ entries = await fs.readdir(toolsRoot, { withFileTypes: true });
498
471
  } catch {
499
472
  return undefined;
500
473
  }
501
- }
502
474
 
503
- /* ------------------------------------------------------------------ */
504
- /* Install / uninstall public API */
505
- /* ------------------------------------------------------------------ */
475
+ for (const entry of entries) {
476
+ if (!entry.isDirectory()) continue;
477
+ const packageRoot = path.join(toolsRoot, entry.name);
478
+ try {
479
+ const manifest = JSON.parse(
480
+ await fs.readFile(path.join(packageRoot, 'package.json'), 'utf8'),
481
+ ) as { name?: string };
482
+ if (manifest.name === packageName) return packageRoot;
483
+ } catch {
484
+ // Ignore incomplete workspace folders and keep searching.
485
+ }
486
+ }
487
+
488
+ return undefined;
489
+ }
506
490
 
507
491
  /**
508
492
  * Install a marketplace tool.
509
- *
510
- * The install process:
511
- * 1. Resolve the tool manifest (local → Hub → fallback)
512
- * 2. Check system dependencies (ffmpeg, docker, etc.)
513
- * 3. Determine install strategy:
514
- * - Workspace tool (monorepo dev)? → resolve path, no download needed
515
- * - Remote tool? → `npm install` into `.larkup/tools/node_modules/`
516
- * 4. Record in `installed.json`
517
- * 5. Notify Hub API (fire-and-forget install counter)
518
- * 6. Refresh registry cache
519
493
  */
520
494
  export async function installTool(
521
495
  toolId: string,
522
496
  onProgress?: (progress: InstallProgress) => void,
497
+ initialConfig: Record<string, unknown> = {},
523
498
  ): Promise<void> {
499
+ installingTools.add(toolId);
524
500
  const report = (stage: InstallProgress['stage'], percent: number, message: string) => {
525
501
  onProgress?.({ toolId, stage, percent, message });
526
502
  };
@@ -602,7 +578,7 @@ export async function installTool(
602
578
  packageName: descriptor.packageName,
603
579
  resolvedPath,
604
580
  source,
605
- config: buildDefaultConfig(descriptor),
581
+ config: { ...buildDefaultConfig(descriptor), ...initialConfig },
606
582
  };
607
583
 
608
584
  if (existing >= 0) {
@@ -628,34 +604,41 @@ export async function installTool(
628
604
  const message = err instanceof Error ? err.message : 'Installation failed.';
629
605
  report('failed', 0, message);
630
606
  throw err;
607
+ } finally {
608
+ installingTools.delete(toolId);
631
609
  }
632
610
  }
633
611
 
634
612
  export async function uninstallTool(toolId: string): Promise<void> {
635
- const manifest = await readManifest();
636
- const tool = manifest.tools.find((t) => t.id === toolId);
613
+ uninstallingTools.add(toolId);
614
+ try {
615
+ const manifest = await readManifest();
616
+ const tool = manifest.tools.find((t) => t.id === toolId);
637
617
 
638
- // Remove from manifest
639
- manifest.tools = manifest.tools.filter((t) => t.id !== toolId);
640
- await writeManifest(manifest);
618
+ // Remove from manifest
619
+ manifest.tools = manifest.tools.filter((t) => t.id !== toolId);
620
+ await writeManifest(manifest);
641
621
 
642
- // If it was installed from npm, remove from isolated node_modules
643
- if (tool?.source === 'registry' && tool.packageName) {
644
- try {
645
- const toolsDir = getToolsDir();
646
- await execAsync(`npm uninstall ${tool.packageName} --prefix "${toolsDir}"`, {
647
- cwd: toolsDir,
648
- timeout: 30_000,
649
- });
650
- } catch {
651
- // Best-effort cleanup
622
+ // If it was installed from npm, remove from isolated node_modules
623
+ if (tool?.source === 'registry' && tool.packageName) {
624
+ try {
625
+ const toolsDir = getToolsDir();
626
+ await execAsync(`npm uninstall ${tool.packageName} --prefix "${toolsDir}"`, {
627
+ cwd: toolsDir,
628
+ timeout: 30_000,
629
+ });
630
+ } catch {
631
+ // Best-effort cleanup
632
+ }
652
633
  }
653
- }
654
634
 
655
- // Refresh registry cache
656
- invalidateRegistryCache();
657
- const { unloadTool } = await import('./tool-loader');
658
- unloadTool(toolId);
635
+ // Refresh registry cache
636
+ invalidateRegistryCache();
637
+ const { unloadTool } = await import('./tool-loader');
638
+ unloadTool(toolId);
639
+ } finally {
640
+ uninstallingTools.delete(toolId);
641
+ }
659
642
  }
660
643
 
661
644
  export async function updateToolConfig(toolId: string, config: Record<string, any>): Promise<void> {
@@ -666,14 +649,6 @@ export async function updateToolConfig(toolId: string, config: Record<string, an
666
649
  await writeManifest(manifest);
667
650
  }
668
651
 
669
- /* ------------------------------------------------------------------ */
670
- /* Hub notification */
671
- /* ------------------------------------------------------------------ */
672
-
673
- /**
674
- * Notify the Hub API that a tool was installed (increment counter).
675
- * This is fire-and-forget — never blocks the install flow.
676
- */
677
652
  async function notifyHubInstall(toolId: string): Promise<void> {
678
653
  const hubUrl = process.env.LARKUP_HUB_URL ?? 'https://hub.larkup.de';
679
654
  try {
@@ -691,10 +666,6 @@ async function notifyHubInstall(toolId: string): Promise<void> {
691
666
  }
692
667
  }
693
668
 
694
- /* ------------------------------------------------------------------ */
695
- /* Helpers */
696
- /* ------------------------------------------------------------------ */
697
-
698
669
  function buildDefaultConfig(descriptor: {
699
670
  configSchema?: { key: string; defaultValue?: string }[];
700
671
  }): Record<string, any> {
@@ -0,0 +1,120 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { promises as fs } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import type { InstalledTool } from './types';
6
+
7
+ const mocks = vi.hoisted(() => ({
8
+ getInstalledTool: vi.fn(),
9
+ resolveWorkspaceToolPath: vi.fn(),
10
+ }));
11
+
12
+ vi.mock('./tool-installer', () => ({
13
+ getInstalledTool: mocks.getInstalledTool,
14
+ resolveWorkspaceToolPath: mocks.resolveWorkspaceToolPath,
15
+ }));
16
+
17
+ import { loadTool, unloadTool } from './tool-loader';
18
+
19
+ const temporaryDirectories: string[] = [];
20
+
21
+ afterEach(async () => {
22
+ mocks.getInstalledTool.mockReset();
23
+ mocks.resolveWorkspaceToolPath.mockReset();
24
+ unloadTool('workspace-fixture');
25
+ await Promise.all(
26
+ temporaryDirectories
27
+ .splice(0)
28
+ .map((directory) => fs.rm(directory, { recursive: true, force: true })),
29
+ );
30
+ });
31
+
32
+ describe('loadTool', () => {
33
+ it('loads an unlinked workspace package from its resolved directory', async () => {
34
+ const packageDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'larkup-tool-loader-'));
35
+ temporaryDirectories.push(packageDirectory);
36
+ await fs.writeFile(
37
+ path.join(packageDirectory, 'package.json'),
38
+ JSON.stringify({ type: 'module', exports: { '.': './index.mjs' } }),
39
+ );
40
+ await fs.writeFile(path.join(packageDirectory, 'index.mjs'), 'export const ready = true;\n');
41
+
42
+ mocks.getInstalledTool.mockResolvedValue({
43
+ id: 'workspace-fixture',
44
+ version: '1.0.0',
45
+ installedAt: new Date(0).toISOString(),
46
+ packageName: '@larkup/unlinked-workspace-fixture',
47
+ resolvedPath: packageDirectory,
48
+ source: 'local',
49
+ config: {},
50
+ } satisfies InstalledTool);
51
+
52
+ await expect(loadTool<{ ready: boolean }>('workspace-fixture')).resolves.toMatchObject({
53
+ ready: true,
54
+ });
55
+ });
56
+
57
+ it('recovers a local tool whose saved workspace path is stale', async () => {
58
+ const packageDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'larkup-tool-loader-'));
59
+ temporaryDirectories.push(packageDirectory);
60
+ await fs.writeFile(
61
+ path.join(packageDirectory, 'package.json'),
62
+ JSON.stringify({ type: 'module', exports: { '.': './index.mjs' } }),
63
+ );
64
+ await fs.writeFile(
65
+ path.join(packageDirectory, 'index.mjs'),
66
+ 'export const recovered = true;\n',
67
+ );
68
+
69
+ mocks.getInstalledTool.mockResolvedValue({
70
+ id: 'workspace-fixture',
71
+ version: '1.0.0',
72
+ installedAt: new Date(0).toISOString(),
73
+ packageName: '@larkup/unlinked-workspace-fixture',
74
+ resolvedPath: path.join(packageDirectory, 'previous-location'),
75
+ source: 'local',
76
+ config: {},
77
+ } satisfies InstalledTool);
78
+ mocks.resolveWorkspaceToolPath.mockResolvedValue(packageDirectory);
79
+
80
+ await expect(loadTool<{ recovered: boolean }>('workspace-fixture')).resolves.toMatchObject({
81
+ recovered: true,
82
+ });
83
+ expect(mocks.resolveWorkspaceToolPath).toHaveBeenCalledWith(
84
+ '@larkup/unlinked-workspace-fixture',
85
+ );
86
+ });
87
+
88
+ it('reloads a local tool after it is reinstalled at the same path', async () => {
89
+ const packageDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'larkup-tool-loader-'));
90
+ temporaryDirectories.push(packageDirectory);
91
+ await fs.writeFile(
92
+ path.join(packageDirectory, 'package.json'),
93
+ JSON.stringify({ type: 'module', exports: { '.': './index.mjs' } }),
94
+ );
95
+ await fs.writeFile(path.join(packageDirectory, 'index.mjs'), 'export const revision = 1;\n');
96
+
97
+ const installed = {
98
+ id: 'workspace-fixture',
99
+ version: '1.0.0',
100
+ installedAt: new Date(0).toISOString(),
101
+ packageName: '@larkup/unlinked-workspace-fixture',
102
+ resolvedPath: packageDirectory,
103
+ source: 'local',
104
+ config: {},
105
+ } satisfies InstalledTool;
106
+ mocks.getInstalledTool.mockResolvedValue(installed);
107
+ await expect(loadTool<{ revision: number }>('workspace-fixture')).resolves.toMatchObject({
108
+ revision: 1,
109
+ });
110
+
111
+ await fs.writeFile(path.join(packageDirectory, 'index.mjs'), 'export const revision = 2;\n');
112
+ mocks.getInstalledTool.mockResolvedValue({
113
+ ...installed,
114
+ installedAt: new Date(1_000).toISOString(),
115
+ });
116
+ await expect(loadTool<{ revision: number }>('workspace-fixture')).resolves.toMatchObject({
117
+ revision: 2,
118
+ });
119
+ });
120
+ });