@tagma/sdk 0.4.2 → 0.4.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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -5
  3. package/dist/adapters/stdin-approval.d.ts +6 -0
  4. package/dist/adapters/stdin-approval.d.ts.map +1 -0
  5. package/dist/adapters/stdin-approval.js +90 -0
  6. package/dist/adapters/stdin-approval.js.map +1 -0
  7. package/dist/adapters/websocket-approval.d.ts +28 -0
  8. package/dist/adapters/websocket-approval.d.ts.map +1 -0
  9. package/dist/adapters/websocket-approval.js +145 -0
  10. package/dist/adapters/websocket-approval.js.map +1 -0
  11. package/dist/approval.d.ts +13 -0
  12. package/dist/approval.d.ts.map +1 -0
  13. package/dist/approval.js +91 -0
  14. package/dist/approval.js.map +1 -0
  15. package/dist/bootstrap.d.ts +2 -0
  16. package/dist/bootstrap.d.ts.map +1 -0
  17. package/dist/bootstrap.js +30 -0
  18. package/dist/bootstrap.js.map +1 -0
  19. package/dist/completions/exit-code.d.ts +3 -0
  20. package/dist/completions/exit-code.d.ts.map +1 -0
  21. package/dist/completions/exit-code.js +25 -0
  22. package/dist/completions/exit-code.js.map +1 -0
  23. package/dist/completions/file-exists.d.ts +3 -0
  24. package/dist/completions/file-exists.d.ts.map +1 -0
  25. package/dist/completions/file-exists.js +58 -0
  26. package/dist/completions/file-exists.js.map +1 -0
  27. package/dist/completions/output-check.d.ts +3 -0
  28. package/dist/completions/output-check.d.ts.map +1 -0
  29. package/dist/completions/output-check.js +81 -0
  30. package/dist/completions/output-check.js.map +1 -0
  31. package/dist/config-ops.d.ts +55 -0
  32. package/dist/config-ops.d.ts.map +1 -0
  33. package/dist/config-ops.js +258 -0
  34. package/dist/config-ops.js.map +1 -0
  35. package/dist/dag.d.ts +46 -0
  36. package/dist/dag.d.ts.map +1 -0
  37. package/dist/dag.js +193 -0
  38. package/dist/dag.js.map +1 -0
  39. package/dist/drivers/claude-code.d.ts +3 -0
  40. package/dist/drivers/claude-code.d.ts.map +1 -0
  41. package/dist/drivers/claude-code.js +210 -0
  42. package/dist/drivers/claude-code.js.map +1 -0
  43. package/dist/engine.d.ts +89 -0
  44. package/dist/engine.d.ts.map +1 -0
  45. package/dist/engine.js +815 -0
  46. package/dist/engine.js.map +1 -0
  47. package/dist/hooks.d.ts +73 -0
  48. package/dist/hooks.d.ts.map +1 -0
  49. package/dist/hooks.js +103 -0
  50. package/dist/hooks.js.map +1 -0
  51. package/dist/logger.d.ts +61 -0
  52. package/dist/logger.d.ts.map +1 -0
  53. package/dist/logger.js +151 -0
  54. package/dist/logger.js.map +1 -0
  55. package/dist/middlewares/static-context.d.ts +3 -0
  56. package/dist/middlewares/static-context.d.ts.map +1 -0
  57. package/dist/middlewares/static-context.js +36 -0
  58. package/dist/middlewares/static-context.js.map +1 -0
  59. package/dist/pipeline-runner.d.ts +50 -0
  60. package/dist/pipeline-runner.d.ts.map +1 -0
  61. package/dist/pipeline-runner.js +139 -0
  62. package/dist/pipeline-runner.js.map +1 -0
  63. package/dist/registry.d.ts +43 -0
  64. package/dist/registry.d.ts.map +1 -0
  65. package/dist/registry.js +182 -0
  66. package/dist/registry.js.map +1 -0
  67. package/dist/runner.d.ts +19 -0
  68. package/dist/runner.d.ts.map +1 -0
  69. package/dist/runner.js +364 -0
  70. package/dist/runner.js.map +1 -0
  71. package/dist/schema.d.ts +27 -0
  72. package/dist/schema.d.ts.map +1 -0
  73. package/dist/schema.js +373 -0
  74. package/dist/schema.js.map +1 -0
  75. package/dist/sdk.d.ts +27 -0
  76. package/dist/sdk.d.ts.map +1 -0
  77. package/dist/sdk.js +33 -0
  78. package/dist/sdk.js.map +1 -0
  79. package/dist/templates.d.ts +20 -0
  80. package/dist/templates.d.ts.map +1 -0
  81. package/dist/templates.js +93 -0
  82. package/dist/templates.js.map +1 -0
  83. package/dist/triggers/file.d.ts +3 -0
  84. package/dist/triggers/file.d.ts.map +1 -0
  85. package/dist/triggers/file.js +123 -0
  86. package/dist/triggers/file.js.map +1 -0
  87. package/dist/triggers/manual.d.ts +3 -0
  88. package/dist/triggers/manual.d.ts.map +1 -0
  89. package/dist/triggers/manual.js +73 -0
  90. package/dist/triggers/manual.js.map +1 -0
  91. package/dist/types.d.ts +4 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +14 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/utils.d.ts +14 -0
  96. package/dist/utils.d.ts.map +1 -0
  97. package/dist/utils.js +138 -0
  98. package/dist/utils.js.map +1 -0
  99. package/dist/validate-raw.d.ts +44 -0
  100. package/dist/validate-raw.d.ts.map +1 -0
  101. package/dist/validate-raw.js +327 -0
  102. package/dist/validate-raw.js.map +1 -0
  103. package/package.json +26 -17
  104. package/src/approval.ts +5 -3
  105. package/src/registry.ts +214 -214
  106. package/src/validate-raw.ts +92 -3
  107. package/scripts/preinstall.js +0 -38
package/src/registry.ts CHANGED
@@ -1,214 +1,214 @@
1
- import type {
2
- PluginCategory, DriverPlugin, TriggerPlugin,
3
- CompletionPlugin, MiddlewarePlugin, PluginManifest,
4
- } from './types';
5
-
6
- type PluginType = DriverPlugin | TriggerPlugin | CompletionPlugin | MiddlewarePlugin;
7
-
8
- const VALID_CATEGORIES: ReadonlySet<PluginCategory> = new Set([
9
- 'drivers', 'triggers', 'completions', 'middlewares',
10
- ]);
11
-
12
- const registries = {
13
- drivers: new Map<string, DriverPlugin>(),
14
- triggers: new Map<string, TriggerPlugin>(),
15
- completions: new Map<string, CompletionPlugin>(),
16
- middlewares: new Map<string, MiddlewarePlugin>(),
17
- };
18
-
19
- /**
20
- * Minimal contract enforcement so a malformed plugin fails fast at
21
- * registration time rather than crashing the engine mid-run.
22
- *
23
- * For drivers we materialize `capabilities` and assert each field is a
24
- * boolean — otherwise a plugin author can write
25
- * get capabilities() { throw new Error('boom') }
26
- * and pass the basic typeof check, then crash preflight when the engine
27
- * touches `driver.capabilities.sessionResume`. (R8)
28
- */
29
- function validateContract(category: PluginCategory, handler: unknown): void {
30
- if (!handler || typeof handler !== 'object') {
31
- throw new Error(`Plugin handler for category "${category}" must be an object`);
32
- }
33
- const h = handler as Record<string, unknown>;
34
- if (typeof h.name !== 'string' || h.name.length === 0) {
35
- throw new Error(`Plugin handler for category "${category}" must declare a non-empty "name"`);
36
- }
37
- switch (category) {
38
- case 'drivers': {
39
- if (typeof h.buildCommand !== 'function') {
40
- throw new Error(`drivers plugin "${h.name}" must export buildCommand()`);
41
- }
42
- // Materialize capabilities — this triggers any throwing getter NOW
43
- // instead of during preflight.
44
- let caps: unknown;
45
- try {
46
- caps = h.capabilities;
47
- } catch (err) {
48
- throw new Error(
49
- `drivers plugin "${h.name}" capabilities accessor threw: ` +
50
- (err instanceof Error ? err.message : String(err))
51
- );
52
- }
53
- if (!caps || typeof caps !== 'object') {
54
- throw new Error(`drivers plugin "${h.name}" must declare capabilities object`);
55
- }
56
- const c = caps as Record<string, unknown>;
57
- for (const field of ['sessionResume', 'systemPrompt', 'outputFormat'] as const) {
58
- if (typeof c[field] !== 'boolean') {
59
- throw new Error(
60
- `drivers plugin "${h.name}".capabilities.${field} must be a boolean (got ${typeof c[field]})`
61
- );
62
- }
63
- }
64
- // Optional methods, but if present must be functions.
65
- for (const opt of ['parseResult', 'resolveModel', 'resolveTools'] as const) {
66
- if (h[opt] !== undefined && typeof h[opt] !== 'function') {
67
- throw new Error(
68
- `drivers plugin "${h.name}".${opt} must be a function or undefined`
69
- );
70
- }
71
- }
72
- break;
73
- }
74
- case 'triggers':
75
- if (typeof h.watch !== 'function') {
76
- throw new Error(`triggers plugin "${h.name}" must export watch()`);
77
- }
78
- break;
79
- case 'completions':
80
- if (typeof h.check !== 'function') {
81
- throw new Error(`completions plugin "${h.name}" must export check()`);
82
- }
83
- break;
84
- case 'middlewares':
85
- if (typeof h.enhance !== 'function') {
86
- throw new Error(`middlewares plugin "${h.name}" must export enhance()`);
87
- }
88
- break;
89
- }
90
- }
91
-
92
- export type RegisterResult = 'registered' | 'replaced' | 'unchanged';
93
-
94
- /**
95
- * Register a plugin under (category, type). Returns:
96
- * - 'registered' on first registration
97
- * - 'replaced' when an existing entry was overwritten with a different handler
98
- * - 'unchanged' when the same handler instance was already present
99
- *
100
- * Throws if `category` is unknown, `type` is empty, or `handler` violates the
101
- * minimum interface contract for the category.
102
- */
103
- export function registerPlugin<T extends PluginType>(
104
- category: PluginCategory, type: string, handler: T,
105
- ): RegisterResult {
106
- if (!VALID_CATEGORIES.has(category)) {
107
- throw new Error(`Unknown plugin category "${category}"`);
108
- }
109
- if (typeof type !== 'string' || type.length === 0) {
110
- throw new Error(`Plugin type must be a non-empty string (category="${category}")`);
111
- }
112
- validateContract(category, handler);
113
- const registry = registries[category] as Map<string, T>;
114
- const existing = registry.get(type);
115
- if (existing === handler) return 'unchanged';
116
- const wasReplaced = existing !== undefined;
117
- registry.set(type, handler);
118
- return wasReplaced ? 'replaced' : 'registered';
119
- }
120
-
121
- /**
122
- * Remove a plugin from the in-process registry. Returns true if a plugin
123
- * was actually removed. Note: ESM module caching is not affected, so
124
- * re-importing the same file after unregister will yield the cached module —
125
- * callers wanting a fresh load must restart the host process.
126
- */
127
- export function unregisterPlugin(category: PluginCategory, type: string): boolean {
128
- if (!VALID_CATEGORIES.has(category)) return false;
129
- return registries[category].delete(type);
130
- }
131
-
132
- export function getHandler<T extends PluginType>(
133
- category: PluginCategory, type: string,
134
- ): T {
135
- const handler = registries[category].get(type);
136
- if (!handler) {
137
- throw new Error(
138
- `${category} type "${type}" not registered.\n` +
139
- `Install the plugin: bun add @tagma/${category.replace(/s$/, '')}-${type}`
140
- );
141
- }
142
- return handler as T;
143
- }
144
-
145
- export function hasHandler(category: PluginCategory, type: string): boolean {
146
- return registries[category].has(type);
147
- }
148
-
149
- // Plugin name must be a scoped npm package or a tagma-prefixed package.
150
- // Reject absolute/relative paths and suspicious patterns to prevent
151
- // arbitrary code execution via crafted YAML configs.
152
- export const PLUGIN_NAME_RE = /^(@[a-z0-9-]+\/[a-z0-9._-]+|tagma-plugin-[a-z0-9._-]+)$/;
153
-
154
- export function isValidPluginName(name: unknown): name is string {
155
- return typeof name === 'string' && PLUGIN_NAME_RE.test(name);
156
- }
157
-
158
- /**
159
- * Parse and validate the `tagmaPlugin` field of a `package.json` blob.
160
- *
161
- * Returns the strongly-typed manifest if the field is present and
162
- * well-formed (`category` is one of the four known categories and `type`
163
- * is a non-empty string). Returns `null` if the field is absent — that
164
- * is the host's signal that the package is a library, not a plugin.
165
- *
166
- * Throws if the field is present but malformed: that's a packaging bug
167
- * the plugin author should hear about loudly, not a silent skip.
168
- *
169
- * Hosts use this during auto-discovery to decide whether to load a
170
- * package as a plugin without having to dynamically `import()` it.
171
- */
172
- export function readPluginManifest(pkgJson: unknown): PluginManifest | null {
173
- if (!pkgJson || typeof pkgJson !== 'object') return null;
174
- const raw = (pkgJson as Record<string, unknown>).tagmaPlugin;
175
- if (raw === undefined) return null;
176
- if (!raw || typeof raw !== 'object') {
177
- throw new Error('tagmaPlugin field must be an object with { category, type }');
178
- }
179
- const m = raw as Record<string, unknown>;
180
- const category = m.category;
181
- const type = m.type;
182
- if (typeof category !== 'string' || !VALID_CATEGORIES.has(category as PluginCategory)) {
183
- throw new Error(
184
- `tagmaPlugin.category must be one of ${[...VALID_CATEGORIES].join(', ')}, got ${JSON.stringify(category)}`
185
- );
186
- }
187
- if (typeof type !== 'string' || type.length === 0) {
188
- throw new Error(`tagmaPlugin.type must be a non-empty string, got ${JSON.stringify(type)}`);
189
- }
190
- return { category: category as PluginCategory, type };
191
- }
192
-
193
- export async function loadPlugins(pluginNames: readonly string[]): Promise<void> {
194
- for (const name of pluginNames) {
195
- if (!isValidPluginName(name)) {
196
- throw new Error(
197
- `Plugin "${name}" rejected: plugin names must be scoped npm packages ` +
198
- `(e.g. @tagma/trigger-xyz) or tagma-plugin-* packages. ` +
199
- `Relative/absolute paths are not allowed.`
200
- );
201
- }
202
- const mod = await import(name);
203
- if (!mod.pluginCategory || !mod.pluginType || !mod.default) {
204
- throw new Error(
205
- `Plugin "${name}" must export pluginCategory, pluginType, and default`
206
- );
207
- }
208
- registerPlugin(mod.pluginCategory, mod.pluginType, mod.default);
209
- }
210
- }
211
-
212
- export function listRegistered(category: PluginCategory): string[] {
213
- return [...registries[category].keys()];
214
- }
1
+ import type {
2
+ PluginCategory, DriverPlugin, TriggerPlugin,
3
+ CompletionPlugin, MiddlewarePlugin, PluginManifest,
4
+ } from './types';
5
+
6
+ type PluginType = DriverPlugin | TriggerPlugin | CompletionPlugin | MiddlewarePlugin;
7
+
8
+ const VALID_CATEGORIES: ReadonlySet<PluginCategory> = new Set([
9
+ 'drivers', 'triggers', 'completions', 'middlewares',
10
+ ]);
11
+
12
+ const registries = {
13
+ drivers: new Map<string, DriverPlugin>(),
14
+ triggers: new Map<string, TriggerPlugin>(),
15
+ completions: new Map<string, CompletionPlugin>(),
16
+ middlewares: new Map<string, MiddlewarePlugin>(),
17
+ };
18
+
19
+ /**
20
+ * Minimal contract enforcement so a malformed plugin fails fast at
21
+ * registration time rather than crashing the engine mid-run.
22
+ *
23
+ * For drivers we materialize `capabilities` and assert each field is a
24
+ * boolean — otherwise a plugin author can write
25
+ * get capabilities() { throw new Error('boom') }
26
+ * and pass the basic typeof check, then crash preflight when the engine
27
+ * touches `driver.capabilities.sessionResume`. (R8)
28
+ */
29
+ function validateContract(category: PluginCategory, handler: unknown): void {
30
+ if (!handler || typeof handler !== 'object') {
31
+ throw new Error(`Plugin handler for category "${category}" must be an object`);
32
+ }
33
+ const h = handler as Record<string, unknown>;
34
+ if (typeof h.name !== 'string' || h.name.length === 0) {
35
+ throw new Error(`Plugin handler for category "${category}" must declare a non-empty "name"`);
36
+ }
37
+ switch (category) {
38
+ case 'drivers': {
39
+ if (typeof h.buildCommand !== 'function') {
40
+ throw new Error(`drivers plugin "${h.name}" must export buildCommand()`);
41
+ }
42
+ // Materialize capabilities — this triggers any throwing getter NOW
43
+ // instead of during preflight.
44
+ let caps: unknown;
45
+ try {
46
+ caps = h.capabilities;
47
+ } catch (err) {
48
+ throw new Error(
49
+ `drivers plugin "${h.name}" capabilities accessor threw: ` +
50
+ (err instanceof Error ? err.message : String(err))
51
+ );
52
+ }
53
+ if (!caps || typeof caps !== 'object') {
54
+ throw new Error(`drivers plugin "${h.name}" must declare capabilities object`);
55
+ }
56
+ const c = caps as Record<string, unknown>;
57
+ for (const field of ['sessionResume', 'systemPrompt', 'outputFormat'] as const) {
58
+ if (typeof c[field] !== 'boolean') {
59
+ throw new Error(
60
+ `drivers plugin "${h.name}".capabilities.${field} must be a boolean (got ${typeof c[field]})`
61
+ );
62
+ }
63
+ }
64
+ // Optional methods, but if present must be functions.
65
+ for (const opt of ['parseResult', 'resolveModel', 'resolveTools'] as const) {
66
+ if (h[opt] !== undefined && typeof h[opt] !== 'function') {
67
+ throw new Error(
68
+ `drivers plugin "${h.name}".${opt} must be a function or undefined`
69
+ );
70
+ }
71
+ }
72
+ break;
73
+ }
74
+ case 'triggers':
75
+ if (typeof h.watch !== 'function') {
76
+ throw new Error(`triggers plugin "${h.name}" must export watch()`);
77
+ }
78
+ break;
79
+ case 'completions':
80
+ if (typeof h.check !== 'function') {
81
+ throw new Error(`completions plugin "${h.name}" must export check()`);
82
+ }
83
+ break;
84
+ case 'middlewares':
85
+ if (typeof h.enhance !== 'function') {
86
+ throw new Error(`middlewares plugin "${h.name}" must export enhance()`);
87
+ }
88
+ break;
89
+ }
90
+ }
91
+
92
+ export type RegisterResult = 'registered' | 'replaced' | 'unchanged';
93
+
94
+ /**
95
+ * Register a plugin under (category, type). Returns:
96
+ * - 'registered' on first registration
97
+ * - 'replaced' when an existing entry was overwritten with a different handler
98
+ * - 'unchanged' when the same handler instance was already present
99
+ *
100
+ * Throws if `category` is unknown, `type` is empty, or `handler` violates the
101
+ * minimum interface contract for the category.
102
+ */
103
+ export function registerPlugin<T extends PluginType>(
104
+ category: PluginCategory, type: string, handler: T,
105
+ ): RegisterResult {
106
+ if (!VALID_CATEGORIES.has(category)) {
107
+ throw new Error(`Unknown plugin category "${category}"`);
108
+ }
109
+ if (typeof type !== 'string' || type.length === 0) {
110
+ throw new Error(`Plugin type must be a non-empty string (category="${category}")`);
111
+ }
112
+ validateContract(category, handler);
113
+ const registry = registries[category] as Map<string, T>;
114
+ const existing = registry.get(type);
115
+ if (existing === handler) return 'unchanged';
116
+ const wasReplaced = existing !== undefined;
117
+ registry.set(type, handler);
118
+ return wasReplaced ? 'replaced' : 'registered';
119
+ }
120
+
121
+ /**
122
+ * Remove a plugin from the in-process registry. Returns true if a plugin
123
+ * was actually removed. Note: ESM module caching is not affected, so
124
+ * re-importing the same file after unregister will yield the cached module —
125
+ * callers wanting a fresh load must restart the host process.
126
+ */
127
+ export function unregisterPlugin(category: PluginCategory, type: string): boolean {
128
+ if (!VALID_CATEGORIES.has(category)) return false;
129
+ return registries[category].delete(type);
130
+ }
131
+
132
+ export function getHandler<T extends PluginType>(
133
+ category: PluginCategory, type: string,
134
+ ): T {
135
+ const handler = registries[category].get(type);
136
+ if (!handler) {
137
+ throw new Error(
138
+ `${category} type "${type}" not registered.\n` +
139
+ `Install the plugin: bun add @tagma/${category.replace(/s$/, '')}-${type}`
140
+ );
141
+ }
142
+ return handler as T;
143
+ }
144
+
145
+ export function hasHandler(category: PluginCategory, type: string): boolean {
146
+ return registries[category].has(type);
147
+ }
148
+
149
+ // Plugin name must be a scoped npm package or a tagma-prefixed package.
150
+ // Reject absolute/relative paths and suspicious patterns to prevent
151
+ // arbitrary code execution via crafted YAML configs.
152
+ export const PLUGIN_NAME_RE = /^(@[a-z0-9-]+\/[a-z0-9._-]+|tagma-plugin-[a-z0-9._-]+)$/;
153
+
154
+ export function isValidPluginName(name: unknown): name is string {
155
+ return typeof name === 'string' && PLUGIN_NAME_RE.test(name);
156
+ }
157
+
158
+ /**
159
+ * Parse and validate the `tagmaPlugin` field of a `package.json` blob.
160
+ *
161
+ * Returns the strongly-typed manifest if the field is present and
162
+ * well-formed (`category` is one of the four known categories and `type`
163
+ * is a non-empty string). Returns `null` if the field is absent — that
164
+ * is the host's signal that the package is a library, not a plugin.
165
+ *
166
+ * Throws if the field is present but malformed: that's a packaging bug
167
+ * the plugin author should hear about loudly, not a silent skip.
168
+ *
169
+ * Hosts use this during auto-discovery to decide whether to load a
170
+ * package as a plugin without having to dynamically `import()` it.
171
+ */
172
+ export function readPluginManifest(pkgJson: unknown): PluginManifest | null {
173
+ if (!pkgJson || typeof pkgJson !== 'object') return null;
174
+ const raw = (pkgJson as Record<string, unknown>).tagmaPlugin;
175
+ if (raw === undefined) return null;
176
+ if (!raw || typeof raw !== 'object') {
177
+ throw new Error('tagmaPlugin field must be an object with { category, type }');
178
+ }
179
+ const m = raw as Record<string, unknown>;
180
+ const category = m.category;
181
+ const type = m.type;
182
+ if (typeof category !== 'string' || !VALID_CATEGORIES.has(category as PluginCategory)) {
183
+ throw new Error(
184
+ `tagmaPlugin.category must be one of ${[...VALID_CATEGORIES].join(', ')}, got ${JSON.stringify(category)}`
185
+ );
186
+ }
187
+ if (typeof type !== 'string' || type.length === 0) {
188
+ throw new Error(`tagmaPlugin.type must be a non-empty string, got ${JSON.stringify(type)}`);
189
+ }
190
+ return { category: category as PluginCategory, type };
191
+ }
192
+
193
+ export async function loadPlugins(pluginNames: readonly string[]): Promise<void> {
194
+ for (const name of pluginNames) {
195
+ if (!isValidPluginName(name)) {
196
+ throw new Error(
197
+ `Plugin "${name}" rejected: plugin names must be scoped npm packages ` +
198
+ `(e.g. @tagma/trigger-xyz) or tagma-plugin-* packages. ` +
199
+ `Relative/absolute paths are not allowed.`
200
+ );
201
+ }
202
+ const mod = await import(name);
203
+ if (!mod.pluginCategory || !mod.pluginType || !mod.default) {
204
+ throw new Error(
205
+ `Plugin "${name}" must export pluginCategory, pluginType, and default`
206
+ );
207
+ }
208
+ registerPlugin(mod.pluginCategory, mod.pluginType, mod.default);
209
+ }
210
+ }
211
+
212
+ export function listRegistered(category: PluginCategory): string[] {
213
+ return [...registries[category].keys()];
214
+ }
@@ -16,6 +16,31 @@ function isValidDuration(input: string): boolean {
16
16
  const VALID_ON_FAILURE = new Set(['skip_downstream', 'stop_all', 'ignore']);
17
17
  const VALID_MODEL_TIERS = new Set(['low', 'medium', 'high']);
18
18
 
19
+ // Built-in plugin types always known to the SDK core, regardless of which
20
+ // external plugin packages are installed. These MUST stay in sync with the
21
+ // types that `bootstrapBuiltins()` registers, otherwise the editor will
22
+ // emit false-positive "unknown type" warnings for stock pipelines.
23
+ const BUILTIN_TRIGGER_TYPES: ReadonlySet<string> = new Set(['manual', 'file']);
24
+ const BUILTIN_COMPLETION_TYPES: ReadonlySet<string> = new Set([
25
+ 'exit_code', 'file_exists', 'output_check',
26
+ ]);
27
+ const BUILTIN_MIDDLEWARE_TYPES: ReadonlySet<string> = new Set(['static_context']);
28
+
29
+ /**
30
+ * Optional second argument to `validateRaw`: the set of plugin types currently
31
+ * registered in the SDK runtime, keyed by category. Hosts (e.g. the editor
32
+ * server) pass this so `validateRaw` can emit a soft warning when a task
33
+ * references a type that isn't loaded — otherwise the Task panel would show
34
+ * no hint and the pipeline would only blow up at run time. Callers that
35
+ * legitimately validate a config offline (before plugins are loaded) can omit
36
+ * this argument and no plugin warnings will be produced.
37
+ */
38
+ export interface KnownPluginTypes {
39
+ readonly triggers?: readonly string[];
40
+ readonly completions?: readonly string[];
41
+ readonly middlewares?: readonly string[];
42
+ }
43
+
19
44
  export type ValidationSeverity = 'error' | 'warning';
20
45
 
21
46
  export interface ValidationError {
@@ -38,12 +63,29 @@ export interface ValidationError {
38
63
  * Checks structure, required fields, prompt/command exclusivity,
39
64
  * depends_on reference integrity, and circular dependencies.
40
65
  *
41
- * Does NOT check plugin registration plugins may not be loaded yet
42
- * when the frontend is editing a config offline.
66
+ * Plugin type checks: when `knownTypes` is provided, task/track references to
67
+ * trigger/completion/middleware types that are neither built-in nor in the
68
+ * supplied set produce a soft warning (severity: 'warning') — these don't
69
+ * block save/run but light up the Task panel so users discover the broken
70
+ * reference in the editor instead of at run time. Omit `knownTypes` to skip
71
+ * plugin checks entirely (offline/pre-load validation).
43
72
  */
44
- export function validateRaw(config: RawPipelineConfig): ValidationError[] {
73
+ export function validateRaw(
74
+ config: RawPipelineConfig,
75
+ knownTypes?: KnownPluginTypes,
76
+ ): ValidationError[] {
45
77
  const errors: ValidationError[] = [];
46
78
 
79
+ const knownTriggers = knownTypes
80
+ ? new Set<string>([...BUILTIN_TRIGGER_TYPES, ...(knownTypes.triggers ?? [])])
81
+ : null;
82
+ const knownCompletions = knownTypes
83
+ ? new Set<string>([...BUILTIN_COMPLETION_TYPES, ...(knownTypes.completions ?? [])])
84
+ : null;
85
+ const knownMiddlewares = knownTypes
86
+ ? new Set<string>([...BUILTIN_MIDDLEWARE_TYPES, ...(knownTypes.middlewares ?? [])])
87
+ : null;
88
+
47
89
  // ── Top level ──
48
90
  if (!config.name?.trim()) {
49
91
  errors.push({ path: 'name', message: 'Pipeline name is required' });
@@ -98,6 +140,22 @@ export function validateRaw(config: RawPipelineConfig): ValidationError[] {
98
140
  errors.push({ path: `${trackPath}.model_tier`, message: `Invalid model_tier "${track.model_tier}". Expected "low", "medium", or "high".` });
99
141
  }
100
142
 
143
+ // Track-level middlewares can reference a plugin that was uninstalled
144
+ // after the YAML was written — surface a warning so the user notices
145
+ // before hitting Run.
146
+ if (knownMiddlewares && track.middlewares) {
147
+ for (let mi = 0; mi < track.middlewares.length; mi++) {
148
+ const mw = track.middlewares[mi];
149
+ if (mw?.type && !knownMiddlewares.has(mw.type)) {
150
+ errors.push({
151
+ path: `${trackPath}.middlewares[${mi}].type`,
152
+ message: `Middleware type "${mw.type}" is not registered. Install the plugin (e.g. @tagma/middleware-${mw.type}) or remove the reference — the pipeline will fail at run time.`,
153
+ severity: 'warning',
154
+ });
155
+ }
156
+ }
157
+ }
158
+
101
159
  if (!track.tasks || track.tasks.length === 0) {
102
160
  errors.push({ path: `${trackPath}.tasks`, message: `Track "${track.id || ti}": must have at least one task` });
103
161
  continue;
@@ -157,6 +215,37 @@ export function validateRaw(config: RawPipelineConfig): ValidationError[] {
157
215
  errors.push({ path: `${taskPath}.model_tier`, message: `Invalid model_tier "${task.model_tier}". Expected "low", "medium", or "high".` });
158
216
  }
159
217
 
218
+ // ── Plugin type warnings (trigger / completion / middlewares) ──
219
+ // Only fire when the host supplied a `knownTypes` snapshot, so offline
220
+ // validation stays quiet. The messages deliberately name the npm
221
+ // scope so users can copy-paste the install command.
222
+ if (knownTriggers && task.trigger?.type && !knownTriggers.has(task.trigger.type)) {
223
+ errors.push({
224
+ path: `${taskPath}.trigger.type`,
225
+ message: `Trigger type "${task.trigger.type}" is not registered. Install the plugin (e.g. @tagma/trigger-${task.trigger.type}) or the task will fail at run time.`,
226
+ severity: 'warning',
227
+ });
228
+ }
229
+ if (knownCompletions && task.completion?.type && !knownCompletions.has(task.completion.type)) {
230
+ errors.push({
231
+ path: `${taskPath}.completion.type`,
232
+ message: `Completion type "${task.completion.type}" is not registered. Install the plugin (e.g. @tagma/completion-${task.completion.type}) or the task will fail at run time.`,
233
+ severity: 'warning',
234
+ });
235
+ }
236
+ if (knownMiddlewares && task.middlewares) {
237
+ for (let mi = 0; mi < task.middlewares.length; mi++) {
238
+ const mw = task.middlewares[mi];
239
+ if (mw?.type && !knownMiddlewares.has(mw.type)) {
240
+ errors.push({
241
+ path: `${taskPath}.middlewares[${mi}].type`,
242
+ message: `Middleware type "${mw.type}" is not registered. Install the plugin (e.g. @tagma/middleware-${mw.type}) or remove the reference — the pipeline will fail at run time.`,
243
+ severity: 'warning',
244
+ });
245
+ }
246
+ }
247
+ }
248
+
160
249
  // ── depends_on reference checks ──
161
250
  if (task.depends_on && task.depends_on.length > 0) {
162
251
  for (const dep of task.depends_on) {
@@ -1,38 +0,0 @@
1
- // Preinstall guard — refuses installation under npm / yarn / pnpm.
2
- // @tagma/sdk ships TypeScript source (main: ./src/sdk.ts) and relies on
3
- // Bun's native .ts loader, so installing under Node-based managers leaves
4
- // users with a broken package.
5
- //
6
- // Bun detection: we can't rely on process.versions.bun alone, because bun
7
- // invokes lifecycle scripts via the interpreter named in the script command
8
- // ("node scripts/preinstall.js" runs under node even when called from bun
9
- // install). Bun does, however, set npm_config_user_agent to a string that
10
- // starts with "bun/<version> ...", which is the canonical cross-manager
11
- // signal. Check both for safety.
12
-
13
- const ua = process.env.npm_config_user_agent || '';
14
- if (process.versions.bun || ua.startsWith('bun/') || ua.startsWith('bun ')) {
15
- process.exit(0);
16
- }
17
-
18
- const red = (s) => `\x1b[31m${s}\x1b[0m`;
19
- const bold = (s) => `\x1b[1m${s}\x1b[0m`;
20
- const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
21
-
22
- process.stderr.write(
23
- [
24
- '',
25
- red(bold(' @tagma/sdk requires Bun (>= 1.3).')),
26
- '',
27
- ' This package ships TypeScript source and uses Bun\'s native .ts loader.',
28
- ' npm / yarn / pnpm cannot consume it.',
29
- '',
30
- ' Install with:',
31
- cyan(' bun add @tagma/sdk'),
32
- '',
33
- ' Get Bun: https://bun.sh',
34
- '',
35
- ].join('\n') + '\n',
36
- );
37
-
38
- process.exit(1);