@tagma/sdk 0.7.3 → 0.7.4

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 (92) hide show
  1. package/README.md +26 -5
  2. package/dist/adapters/stdin-approval.d.ts +1 -5
  3. package/dist/adapters/stdin-approval.d.ts.map +1 -1
  4. package/dist/adapters/stdin-approval.js +1 -89
  5. package/dist/adapters/stdin-approval.js.map +1 -1
  6. package/dist/adapters/websocket-approval.d.ts +1 -27
  7. package/dist/adapters/websocket-approval.d.ts.map +1 -1
  8. package/dist/adapters/websocket-approval.js +1 -146
  9. package/dist/adapters/websocket-approval.js.map +1 -1
  10. package/dist/approval.d.ts +2 -12
  11. package/dist/approval.d.ts.map +1 -1
  12. package/dist/approval.js +1 -90
  13. package/dist/approval.js.map +1 -1
  14. package/dist/bootstrap.d.ts +1 -1
  15. package/dist/bootstrap.d.ts.map +1 -1
  16. package/dist/core/task-executor.d.ts.map +1 -1
  17. package/dist/core/task-executor.js +13 -4
  18. package/dist/core/task-executor.js.map +1 -1
  19. package/dist/engine.d.ts +5 -56
  20. package/dist/engine.d.ts.map +1 -1
  21. package/dist/engine.js +7 -297
  22. package/dist/engine.js.map +1 -1
  23. package/dist/index.d.ts +4 -6
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/logger.d.ts +2 -60
  28. package/dist/logger.d.ts.map +1 -1
  29. package/dist/logger.js +1 -153
  30. package/dist/logger.js.map +1 -1
  31. package/dist/plugins.d.ts +2 -2
  32. package/dist/plugins.d.ts.map +1 -1
  33. package/dist/plugins.js +1 -1
  34. package/dist/plugins.js.map +1 -1
  35. package/dist/registry.d.ts +2 -66
  36. package/dist/registry.d.ts.map +1 -1
  37. package/dist/registry.js +1 -292
  38. package/dist/registry.js.map +1 -1
  39. package/dist/runner.d.ts +1 -35
  40. package/dist/runner.d.ts.map +1 -1
  41. package/dist/runner.js +1 -610
  42. package/dist/runner.js.map +1 -1
  43. package/dist/runtime/adapters/stdin-approval.d.ts +2 -0
  44. package/dist/runtime/adapters/stdin-approval.d.ts.map +1 -0
  45. package/dist/runtime/adapters/stdin-approval.js +2 -0
  46. package/dist/runtime/adapters/stdin-approval.js.map +1 -0
  47. package/dist/runtime/adapters/websocket-approval.d.ts +2 -0
  48. package/dist/runtime/adapters/websocket-approval.d.ts.map +1 -0
  49. package/dist/runtime/adapters/websocket-approval.js +2 -0
  50. package/dist/runtime/adapters/websocket-approval.js.map +1 -0
  51. package/dist/runtime/bun-process-runner.d.ts +2 -0
  52. package/dist/runtime/bun-process-runner.d.ts.map +1 -0
  53. package/dist/runtime/bun-process-runner.js +2 -0
  54. package/dist/runtime/bun-process-runner.js.map +1 -0
  55. package/dist/runtime.d.ts +2 -8
  56. package/dist/runtime.d.ts.map +1 -1
  57. package/dist/runtime.js +1 -7
  58. package/dist/runtime.js.map +1 -1
  59. package/dist/tagma.d.ts +3 -4
  60. package/dist/tagma.d.ts.map +1 -1
  61. package/dist/tagma.js +2 -3
  62. package/dist/tagma.js.map +1 -1
  63. package/dist/triggers/file.d.ts.map +1 -1
  64. package/dist/triggers/file.js +74 -107
  65. package/dist/triggers/file.js.map +1 -1
  66. package/package.json +15 -4
  67. package/src/adapters/stdin-approval.ts +1 -106
  68. package/src/adapters/websocket-approval.ts +1 -224
  69. package/src/approval.ts +5 -127
  70. package/src/bootstrap.ts +1 -1
  71. package/src/core/run-context.test.ts +35 -0
  72. package/src/core/task-executor.ts +13 -4
  73. package/src/engine-ports-mixed.test.ts +70 -44
  74. package/src/engine-ports.test.ts +77 -33
  75. package/src/engine.ts +18 -444
  76. package/src/index.ts +4 -6
  77. package/src/logger.ts +2 -182
  78. package/src/package-split.test.ts +15 -0
  79. package/src/pipeline-runner.test.ts +65 -12
  80. package/src/plugin-registry.test.ts +69 -3
  81. package/src/plugins.ts +2 -2
  82. package/src/registry.ts +7 -353
  83. package/src/runner.ts +1 -666
  84. package/src/runtime/adapters/stdin-approval.ts +1 -0
  85. package/src/runtime/adapters/websocket-approval.ts +1 -0
  86. package/src/runtime/bun-process-runner.ts +1 -0
  87. package/src/runtime-adapters.test.ts +10 -0
  88. package/src/runtime.ts +12 -20
  89. package/src/tagma.test.ts +162 -0
  90. package/src/tagma.ts +9 -4
  91. package/src/triggers/file.test.ts +79 -0
  92. package/src/triggers/file.ts +85 -118
package/src/registry.ts CHANGED
@@ -1,353 +1,7 @@
1
- import { createRequire } from 'node:module';
2
- import { pathToFileURL } from 'node:url';
3
- import type {
4
- CapabilityHandler,
5
- PluginCategory,
6
- DriverPlugin,
7
- TriggerPlugin,
8
- CompletionPlugin,
9
- MiddlewarePlugin,
10
- PluginManifest,
11
- TagmaPlugin,
12
- } from './types';
13
-
14
- type PluginType = CapabilityHandler;
15
-
16
- const CAPABILITY_CATEGORIES = [
17
- 'drivers',
18
- 'triggers',
19
- 'completions',
20
- 'middlewares',
21
- ] as const satisfies readonly PluginCategory[];
22
-
23
- const VALID_CATEGORIES: ReadonlySet<PluginCategory> = new Set(CAPABILITY_CATEGORIES);
24
- const PLUGIN_TYPE_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
25
-
26
- export interface RegisteredCapability {
27
- readonly category: PluginCategory;
28
- readonly type: string;
29
- readonly result: RegisterResult;
30
- }
31
-
32
- function singularCategory(category: PluginCategory): string {
33
- switch (category) {
34
- case 'drivers':
35
- return 'driver';
36
- case 'triggers':
37
- return 'trigger';
38
- case 'completions':
39
- return 'completion';
40
- case 'middlewares':
41
- return 'middleware';
42
- }
43
- }
44
-
45
- /**
46
- * Minimal contract enforcement so a malformed plugin fails fast at
47
- * registration time rather than crashing the engine mid-run.
48
- *
49
- * For drivers we materialize `capabilities` and assert each field is a
50
- * boolean —otherwise a plugin author can write
51
- * get capabilities() { throw new Error('boom') }
52
- * and pass the basic typeof check, then crash preflight when the engine
53
- * touches `driver.capabilities.sessionResume`. (R8)
54
- */
55
- function validateContract(category: PluginCategory, handler: unknown): void {
56
- if (!handler || typeof handler !== 'object') {
57
- throw new Error(`Plugin handler for category "${category}" must be an object`);
58
- }
59
- const h = handler as Record<string, unknown>;
60
- if (typeof h.name !== 'string' || h.name.length === 0) {
61
- throw new Error(`Plugin handler for category "${category}" must declare a non-empty "name"`);
62
- }
63
- switch (category) {
64
- case 'drivers': {
65
- if (typeof h.buildCommand !== 'function') {
66
- throw new Error(`drivers plugin "${h.name}" must export buildCommand()`);
67
- }
68
- // Materialize capabilities —this triggers any throwing getter NOW
69
- // instead of during preflight.
70
- let caps: unknown;
71
- try {
72
- caps = h.capabilities;
73
- } catch (err) {
74
- throw new Error(
75
- `drivers plugin "${h.name}" capabilities accessor threw: ` +
76
- (err instanceof Error ? err.message : String(err)),
77
- );
78
- }
79
- if (!caps || typeof caps !== 'object') {
80
- throw new Error(`drivers plugin "${h.name}" must declare capabilities object`);
81
- }
82
- const c = caps as Record<string, unknown>;
83
- for (const field of ['sessionResume', 'systemPrompt', 'outputFormat'] as const) {
84
- if (typeof c[field] !== 'boolean') {
85
- throw new Error(
86
- `drivers plugin "${h.name}".capabilities.${field} must be a boolean (got ${typeof c[field]})`,
87
- );
88
- }
89
- }
90
- // Optional methods, but if present must be functions.
91
- for (const opt of ['parseResult', 'resolveModel', 'resolveTools'] as const) {
92
- if (h[opt] !== undefined && typeof h[opt] !== 'function') {
93
- throw new Error(`drivers plugin "${h.name}".${opt} must be a function or undefined`);
94
- }
95
- }
96
- break;
97
- }
98
- case 'triggers':
99
- if (typeof h.watch !== 'function') {
100
- throw new Error(`triggers plugin "${h.name}" must export watch()`);
101
- }
102
- break;
103
- case 'completions':
104
- if (typeof h.check !== 'function') {
105
- throw new Error(`completions plugin "${h.name}" must export check()`);
106
- }
107
- break;
108
- case 'middlewares':
109
- if (typeof h.enhanceDoc !== 'function') {
110
- throw new Error(
111
- `middlewares plugin "${h.name}" must export enhanceDoc()`,
112
- );
113
- }
114
- break;
115
- }
116
- }
117
-
118
- export type RegisterResult = 'registered' | 'replaced' | 'unchanged';
119
-
120
- // Plugin name must be a scoped npm package or a tagma-prefixed package.
121
- // Reject absolute/relative paths and suspicious patterns to prevent
122
- // arbitrary code execution via crafted YAML configs.
123
- export const PLUGIN_NAME_RE = /^(@[a-z0-9-]+\/[a-z0-9._-]+|tagma-plugin-[a-z0-9._-]+)$/;
124
-
125
- export function isValidPluginName(name: unknown): name is string {
126
- return typeof name === 'string' && PLUGIN_NAME_RE.test(name);
127
- }
128
-
129
- /**
130
- * Parse and validate the `tagmaPlugin` field of a `package.json` blob.
131
- *
132
- * Returns the strongly-typed manifest if the field is present and
133
- * well-formed (`category` is one of the four known categories and `type`
134
- * is a non-empty string). Returns `null` if the field is absent —that
135
- * is the host's signal that the package is a library, not a plugin.
136
- *
137
- * Throws if the field is present but malformed: that's a packaging bug
138
- * the plugin author should hear about loudly, not a silent skip.
139
- *
140
- * Hosts use this during auto-discovery to decide whether to load a
141
- * package as a plugin without having to dynamically `import()` it.
142
- */
143
- export function readPluginManifest(pkgJson: unknown): PluginManifest | null {
144
- if (!pkgJson || typeof pkgJson !== 'object') return null;
145
- const raw = (pkgJson as Record<string, unknown>).tagmaPlugin;
146
- if (raw === undefined) return null;
147
- if (!raw || typeof raw !== 'object') {
148
- throw new Error('tagmaPlugin field must be an object with { category, type }');
149
- }
150
- const m = raw as Record<string, unknown>;
151
- const category = m.category;
152
- const type = m.type;
153
- if (typeof category !== 'string' || !VALID_CATEGORIES.has(category as PluginCategory)) {
154
- throw new Error(
155
- `tagmaPlugin.category must be one of ${[...VALID_CATEGORIES].join(', ')}, got ${JSON.stringify(category)}`,
156
- );
157
- }
158
- if (typeof type !== 'string' || type.length === 0) {
159
- throw new Error(`tagmaPlugin.type must be a non-empty string, got ${JSON.stringify(type)}`);
160
- }
161
- if (!PLUGIN_TYPE_RE.test(type)) {
162
- throw new Error(
163
- `tagmaPlugin.type must match ${PLUGIN_TYPE_RE} (letters, digits, underscores, hyphens; no paths or dots), got ${JSON.stringify(type)}`,
164
- );
165
- }
166
- return { category: category as PluginCategory, type };
167
- }
168
-
169
- function isRecord(value: unknown): value is Record<string, unknown> {
170
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
171
- }
172
-
173
- function isTagmaPlugin(value: unknown): value is TagmaPlugin {
174
- if (!isRecord(value)) return false;
175
- if (typeof value.name !== 'string' || value.name.length === 0) return false;
176
- if (value.capabilities !== undefined && !isRecord(value.capabilities)) return false;
177
- if (value.setup !== undefined && typeof value.setup !== 'function') return false;
178
- return true;
179
- }
180
-
181
- function hasSupportedCapabilityMap(plugin: TagmaPlugin): boolean {
182
- if (!plugin.capabilities) return false;
183
- const capabilities = plugin.capabilities as Record<string, unknown>;
184
- return CAPABILITY_CATEGORIES.some((category) => capabilities[category] !== undefined);
185
- }
186
-
187
- function moduleDefaultPlugin(name: string, mod: unknown): TagmaPlugin {
188
- if (!isRecord(mod) || !isTagmaPlugin(mod.default) || !hasSupportedCapabilityMap(mod.default)) {
189
- throw new Error(
190
- `Plugin "${name}" must default-export a TagmaPlugin with capabilities maps`,
191
- );
192
- }
193
- return mod.default;
194
- }
195
-
196
- /**
197
- * Instance-scoped plugin registry. Each workspace in a multi-tenant sidecar
198
- * owns its own PluginRegistry, so installing/uninstalling a driver in one
199
- * workspace cannot clobber another.
200
- */
201
- export class PluginRegistry {
202
- private readonly registries = {
203
- drivers: new Map<string, DriverPlugin>(),
204
- triggers: new Map<string, TriggerPlugin>(),
205
- completions: new Map<string, CompletionPlugin>(),
206
- middlewares: new Map<string, MiddlewarePlugin>(),
207
- };
208
-
209
- /**
210
- * Register a plugin under (category, type). Returns:
211
- * - 'registered' on first registration
212
- * - 'replaced' when an existing entry was overwritten with a different handler
213
- * - 'unchanged' when the same handler instance was already present
214
- *
215
- * Throws if `category` is unknown, `type` is empty, or `handler` violates
216
- * the minimum interface contract for the category.
217
- */
218
- registerPlugin<T extends PluginType>(
219
- category: PluginCategory,
220
- type: string,
221
- handler: T,
222
- ): RegisterResult {
223
- if (!VALID_CATEGORIES.has(category)) {
224
- throw new Error(`Unknown plugin category "${category}"`);
225
- }
226
- if (typeof type !== 'string' || type.length === 0) {
227
- throw new Error(`Plugin type must be a non-empty string (category="${category}")`);
228
- }
229
- if (!PLUGIN_TYPE_RE.test(type)) {
230
- throw new Error(
231
- `Plugin type "${type}" must match ${PLUGIN_TYPE_RE} (letters, digits, underscores, hyphens; no paths or dots)`,
232
- );
233
- }
234
- validateContract(category, handler);
235
- const registry = this.registries[category] as Map<string, T>;
236
- const existing = registry.get(type);
237
- if (existing === handler) return 'unchanged';
238
- const wasReplaced = existing !== undefined;
239
- registry.set(type, handler);
240
- if (wasReplaced) {
241
- // D18: surface silent shadowing. Hot-reload flows legitimately replace
242
- // handlers; installing two different plugin packages that both claim
243
- // the same (category, type) does not —the second wins and breaks the
244
- // first's consumers with no audit trail. A console.warn is cheap,
245
- // respects existing callers that rely on 'replaced', and gives ops a
246
- // grep-able signal when registrations collide unexpectedly.
247
- console.warn(
248
- `[tagma-sdk] registerPlugin: replaced existing ${category}/${type} - ` +
249
- `check for duplicate plugin packages claiming the same type.`,
250
- );
251
- }
252
- return wasReplaced ? 'replaced' : 'registered';
253
- }
254
-
255
- registerTagmaPlugin(plugin: TagmaPlugin): RegisteredCapability[] {
256
- if (!isTagmaPlugin(plugin)) {
257
- throw new Error('TagmaPlugin must be an object with a non-empty "name"');
258
- }
259
- if (!plugin.capabilities) {
260
- throw new Error(`TagmaPlugin "${plugin.name}" must declare capabilities`);
261
- }
262
-
263
- const registered: RegisteredCapability[] = [];
264
- const capabilities = plugin.capabilities as Record<string, unknown>;
265
- for (const category of CAPABILITY_CATEGORIES) {
266
- const handlers = capabilities[category];
267
- if (handlers === undefined) continue;
268
- if (!isRecord(handlers)) {
269
- throw new Error(
270
- `TagmaPlugin "${plugin.name}" capabilities.${category} must be an object map`,
271
- );
272
- }
273
- for (const [type, handler] of Object.entries(handlers)) {
274
- const result = this.registerPlugin(category, type, handler as PluginType);
275
- registered.push({ category, type, result });
276
- }
277
- }
278
-
279
- if (registered.length === 0) {
280
- throw new Error(
281
- `TagmaPlugin "${plugin.name}" must declare at least one supported capability`,
282
- );
283
- }
284
- return registered;
285
- }
286
-
287
- /**
288
- * Remove a plugin from the in-process registry. Returns true if a plugin
289
- * was actually removed. Note: ESM module caching is not affected, so
290
- * re-importing the same file after unregister will yield the cached module — * callers wanting a fresh load must restart the host process.
291
- */
292
- unregisterPlugin(category: PluginCategory, type: string): boolean {
293
- if (!VALID_CATEGORIES.has(category)) return false;
294
- return this.registries[category].delete(type);
295
- }
296
-
297
- getHandler<T extends PluginType>(category: PluginCategory, type: string): T {
298
- const handler = this.registries[category].get(type);
299
- if (!handler) {
300
- throw new Error(
301
- `${category} type "${type}" not registered.\n` +
302
- `Install the plugin: bun add @tagma/${singularCategory(category)}-${type}`,
303
- );
304
- }
305
- return handler as T;
306
- }
307
-
308
- hasHandler(category: PluginCategory, type: string): boolean {
309
- return this.registries[category].has(type);
310
- }
311
-
312
- listRegistered(category: PluginCategory): string[] {
313
- return [...this.registries[category].keys()];
314
- }
315
-
316
- /**
317
- * Load and register a list of plugin packages into this registry.
318
- *
319
- * @param pluginNames - Validated npm package names to load.
320
- * @param resolveFrom - Optional absolute path to resolve plugins from (e.g.
321
- * the workspace's working directory). When omitted, the default ESM
322
- * resolution uses the SDK's own `node_modules`, which will fail for
323
- * plugins installed only in the user's workspace. CLI callers should
324
- * pass `process.cwd()` or the workspace root so that workspace-local
325
- * plugins resolve correctly.
326
- */
327
- async loadPlugins(
328
- pluginNames: readonly string[],
329
- resolveFrom?: string,
330
- ): Promise<void> {
331
- for (const name of pluginNames) {
332
- if (!isValidPluginName(name)) {
333
- throw new Error(
334
- `Plugin "${name}" rejected: plugin names must be scoped npm packages ` +
335
- `(e.g. @tagma/trigger-xyz) or tagma-plugin-* packages. ` +
336
- `Relative/absolute paths are not allowed.`,
337
- );
338
- }
339
- let moduleUrl: string = name;
340
- if (resolveFrom) {
341
- // Resolve the package entry point relative to the caller's directory
342
- // so plugins installed in the workspace's node_modules are found
343
- // even when the SDK itself lives elsewhere (e.g. a global install
344
- // or a monorepo sibling package).
345
- const req = createRequire(resolveFrom.endsWith('/') ? resolveFrom : resolveFrom + '/');
346
- const resolved = req.resolve(name);
347
- moduleUrl = pathToFileURL(resolved).href;
348
- }
349
- const mod = await import(moduleUrl);
350
- this.registerTagmaPlugin(moduleDefaultPlugin(name, mod));
351
- }
352
- }
353
- }
1
+ export {
2
+ isValidPluginName,
3
+ PluginRegistry,
4
+ PLUGIN_NAME_RE,
5
+ readPluginManifest,
6
+ } from '@tagma/core';
7
+ export type { RegisteredCapability, RegisterResult } from '@tagma/core';