@h-rig/core 0.0.6-alpha.18 → 0.0.6-alpha.181

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 (105) hide show
  1. package/dist/src/agent-role-registry.d.ts +4 -0
  2. package/dist/src/agent-role-registry.js +27 -0
  3. package/dist/src/authority-paths.d.ts +15 -0
  4. package/dist/src/authority-paths.js +80 -0
  5. package/dist/src/baked-secrets.d.ts +3 -0
  6. package/dist/src/baked-secrets.js +63 -0
  7. package/dist/src/build-time-config.d.ts +12 -0
  8. package/dist/src/build-time-config.js +25 -0
  9. package/dist/src/build-time-config.macro.d.ts +1 -0
  10. package/dist/src/capability-loaders.d.ts +51 -0
  11. package/dist/src/capability-loaders.js +870 -0
  12. package/dist/src/capability.d.ts +79 -0
  13. package/dist/src/capability.js +63 -0
  14. package/dist/src/checkout-root.d.ts +1 -0
  15. package/dist/src/checkout-root.js +30 -0
  16. package/dist/src/config-env.d.ts +4 -0
  17. package/dist/src/config-env.js +23 -0
  18. package/dist/src/config.d.ts +3 -0
  19. package/dist/src/config.js +44 -0
  20. package/dist/src/declarative-config.d.ts +14 -0
  21. package/dist/src/declarative-config.js +85 -0
  22. package/dist/src/default-kernel.d.ts +1 -0
  23. package/dist/src/default-kernel.js +12 -0
  24. package/dist/src/define-config.d.ts +20 -0
  25. package/dist/src/define-config.js +28 -15
  26. package/dist/src/define-plugin.d.ts +13 -0
  27. package/dist/src/define-plugin.js +4 -43
  28. package/dist/src/embedded-plugins.d.ts +59 -0
  29. package/dist/src/embedded-plugins.js +22 -0
  30. package/dist/src/exec.d.ts +13 -0
  31. package/dist/src/exec.js +101 -0
  32. package/dist/src/harness-paths.d.ts +9 -0
  33. package/dist/src/harness-paths.js +126 -0
  34. package/dist/src/hook-materializer.d.ts +21 -0
  35. package/dist/src/hook-materializer.js +152 -0
  36. package/dist/src/hook-protocol.d.ts +2 -0
  37. package/dist/src/hook-protocol.js +432 -0
  38. package/dist/src/hook-runner.d.ts +48 -0
  39. package/dist/src/hook-runner.js +868 -0
  40. package/dist/src/hook-runtime.d.ts +52 -0
  41. package/dist/src/hook-runtime.js +432 -0
  42. package/dist/src/index.d.ts +8 -0
  43. package/dist/src/index.js +210 -2499
  44. package/dist/src/json-files.d.ts +9 -0
  45. package/dist/src/json-files.js +124 -0
  46. package/dist/src/kernel-boot.d.ts +2 -0
  47. package/dist/src/kernel-boot.js +10 -0
  48. package/dist/src/kernel-entrypoint.d.ts +22 -0
  49. package/dist/src/kernel-entrypoint.js +660 -0
  50. package/dist/src/kernel-plugin-abi.d.ts +1 -0
  51. package/dist/src/kernel-plugin-abi.js +1 -0
  52. package/dist/src/kernel-resolver.d.ts +2 -0
  53. package/dist/src/kernel-resolver.js +6 -0
  54. package/dist/src/layout.d.ts +10 -0
  55. package/dist/src/layout.js +138 -0
  56. package/dist/src/load-config.d.ts +2 -0
  57. package/dist/src/load-config.js +535 -30
  58. package/dist/src/placement.d.ts +58 -0
  59. package/dist/src/placement.js +53 -0
  60. package/dist/src/plugin-host-context.d.ts +65 -0
  61. package/dist/src/plugin-host-context.js +1171 -0
  62. package/dist/src/plugin-host-registries.d.ts +31 -0
  63. package/dist/src/plugin-host-registries.js +79 -0
  64. package/dist/src/plugin-host.d.ts +77 -0
  65. package/dist/src/plugin-host.js +127 -63
  66. package/dist/src/plugin-runtime.d.ts +173 -0
  67. package/dist/src/project-plugins.d.ts +63 -0
  68. package/dist/src/project-plugins.js +905 -0
  69. package/dist/src/remote-config.d.ts +125 -0
  70. package/dist/src/remote-config.js +85 -0
  71. package/dist/src/root-resolver.d.ts +5 -0
  72. package/dist/src/root-resolver.js +68 -0
  73. package/dist/src/run-provisioning.d.ts +37 -0
  74. package/dist/src/run-provisioning.js +35 -0
  75. package/dist/src/runtime-context.d.ts +20 -0
  76. package/dist/src/runtime-context.js +257 -0
  77. package/dist/src/runtime-events.d.ts +44 -0
  78. package/dist/src/runtime-events.js +208 -0
  79. package/dist/src/runtime-overlay.d.ts +11 -0
  80. package/dist/src/runtime-overlay.js +69 -0
  81. package/dist/src/runtime-paths.d.ts +21 -0
  82. package/dist/src/runtime-paths.js +181 -0
  83. package/dist/src/runtime-provisioning-env.d.ts +5 -0
  84. package/dist/src/runtime-provisioning-env.js +217 -0
  85. package/dist/src/runtime-runner-context.d.ts +12 -0
  86. package/dist/src/runtime-runner-context.js +1 -0
  87. package/dist/src/safe-identifiers.d.ts +44 -0
  88. package/dist/src/safe-identifiers.js +96 -0
  89. package/dist/src/scope-rules.d.ts +4 -0
  90. package/dist/src/scope-rules.js +21 -0
  91. package/dist/src/server-paths.d.ts +22 -0
  92. package/dist/src/server-paths.js +219 -0
  93. package/dist/src/setup-version.d.ts +3 -0
  94. package/dist/src/setup-version.js +14 -0
  95. package/dist/src/task-record-reader.d.ts +3 -0
  96. package/dist/src/task-record-reader.js +9 -0
  97. package/dist/src/validator-registry.d.ts +27 -0
  98. package/dist/src/validator-registry.js +64 -0
  99. package/package.json +162 -10
  100. package/dist/src/engineReadModelReducer.js +0 -1780
  101. package/dist/src/rig-init-builder.js +0 -57
  102. package/dist/src/rigSelectors.js +0 -293
  103. package/dist/src/taskGraph.js +0 -64
  104. package/dist/src/taskGraphCodes.js +0 -26
  105. package/dist/src/taskGraphLayout.js +0 -374
@@ -0,0 +1,1171 @@
1
+ // @bun
2
+ // packages/core/src/project-plugins.ts
3
+ import { existsSync as existsSync3, statSync as statSync2 } from "fs";
4
+ import { resolve as resolve2 } from "path";
5
+
6
+ // packages/core/src/plugin-host.ts
7
+ function indexById(contributions, kind) {
8
+ const map = new Map;
9
+ const registrant = new Map;
10
+ for (const { item, pluginName } of contributions) {
11
+ if (map.has(item.id)) {
12
+ throw new Error(`duplicate ${kind} id "${item.id}": registered by plugins "${registrant.get(item.id)}" and "${pluginName}"`);
13
+ }
14
+ map.set(item.id, item);
15
+ registrant.set(item.id, pluginName);
16
+ }
17
+ return map;
18
+ }
19
+ function assertUniquePluginNames(plugins) {
20
+ const seen = new Set;
21
+ for (const plugin of plugins) {
22
+ if (seen.has(plugin.name)) {
23
+ throw new Error(`duplicate plugin name "${plugin.name}"`);
24
+ }
25
+ seen.add(plugin.name);
26
+ }
27
+ }
28
+ function createPluginHost(plugins) {
29
+ assertUniquePluginNames(plugins);
30
+ const validators = [];
31
+ const hooks = [];
32
+ const skills = [];
33
+ const repoSources = [];
34
+ const agentRoles = [];
35
+ const taskFieldExtensions = [];
36
+ const taskSources = [];
37
+ const cliCommands = [];
38
+ const capabilities = [];
39
+ const panels = [];
40
+ const blockerClassifiers = [];
41
+ const sessionExtensions = [];
42
+ const seedEntrypoints = [];
43
+ const stages = [];
44
+ const stageMutations = [];
45
+ const stageExecutors = {};
46
+ for (const plugin of plugins) {
47
+ const c = plugin.contributes;
48
+ if (!c)
49
+ continue;
50
+ const pluginName = plugin.name;
51
+ if (c.validators)
52
+ validators.push(...c.validators.map((item) => ({ item, pluginName })));
53
+ if (c.hooks)
54
+ hooks.push(...c.hooks.map((item) => ({ item, pluginName })));
55
+ if (c.skills)
56
+ skills.push(...c.skills.map((item) => ({ item, pluginName })));
57
+ if (c.repoSources)
58
+ repoSources.push(...c.repoSources.map((item) => ({ item, pluginName })));
59
+ if (c.agentRoles)
60
+ agentRoles.push(...c.agentRoles.map((item) => ({ item, pluginName })));
61
+ if (c.taskFieldSchemas)
62
+ taskFieldExtensions.push(...c.taskFieldSchemas.map((item) => ({ item, pluginName })));
63
+ if (c.taskSources)
64
+ taskSources.push(...c.taskSources.map((item) => ({ item, pluginName })));
65
+ if (c.cliCommands)
66
+ cliCommands.push(...c.cliCommands.map((item) => ({ item, pluginName })));
67
+ if (c.capabilities)
68
+ capabilities.push(...c.capabilities.map((item) => ({ item, pluginName })));
69
+ if (c.panels)
70
+ panels.push(...c.panels.map((item) => ({ item, pluginName })));
71
+ if (c.blockerClassifiers)
72
+ blockerClassifiers.push(...c.blockerClassifiers.map((item) => ({ item, pluginName })));
73
+ if (c.sessionExtensions)
74
+ sessionExtensions.push(...c.sessionExtensions.map((item) => ({ item, pluginName })));
75
+ if (c.seedEntrypoints)
76
+ seedEntrypoints.push(...c.seedEntrypoints.map((item) => ({ item, pluginName })));
77
+ if (c.stageMutations)
78
+ stageMutations.push(...c.stageMutations.map((item) => ({ item, pluginName })));
79
+ if (c.stages) {
80
+ for (const stage of c.stages) {
81
+ stages.push({ item: stage, pluginName });
82
+ if (stage.run)
83
+ stageExecutors[stage.id] = stage.run;
84
+ }
85
+ }
86
+ }
87
+ const validatorMap = indexById(validators, "validator");
88
+ const hookMap = indexById(hooks, "hook");
89
+ const skillMap = indexById(skills, "skill");
90
+ const repoSourceMap = indexById(repoSources, "repoSource");
91
+ const agentRoleMap = indexById(agentRoles, "agentRole");
92
+ const taskFieldExtMap = indexById(taskFieldExtensions, "taskFieldExtension");
93
+ const taskSourceMap = indexById(taskSources, "taskSource");
94
+ const cliCommandMap = indexById(cliCommands, "cliCommand");
95
+ const capabilityMap = indexById(capabilities, "capability");
96
+ const panelMap = indexById(panels, "panel");
97
+ const blockerClassifierMap = indexById(blockerClassifiers, "blockerClassifier");
98
+ indexById(sessionExtensions, "sessionExtension");
99
+ indexById(seedEntrypoints, "seedEntrypoint");
100
+ const taskSourceFactoryByKind = new Map;
101
+ const taskSourceKindRegistrant = new Map;
102
+ for (const { item, pluginName } of taskSources) {
103
+ if (taskSourceFactoryByKind.has(item.kind)) {
104
+ throw new Error(`duplicate task source kind "${item.kind}": registered by plugins "${taskSourceKindRegistrant.get(item.kind)}" and "${pluginName}"`);
105
+ }
106
+ taskSourceFactoryByKind.set(item.kind, item);
107
+ taskSourceKindRegistrant.set(item.kind, pluginName);
108
+ }
109
+ const seedEntrypointByBasename = new Map;
110
+ const seedEntrypointByWorkerArg = new Map;
111
+ let insidePtySeedEntrypoint;
112
+ const registerSeedEntrypointSelector = (map, selectorKind, selector, contribution) => {
113
+ const existing = map.get(selector);
114
+ if (existing) {
115
+ throw new Error(`duplicate seed entrypoint ${selectorKind} "${selector}": registered by entrypoint "${existing.item.id}" from plugin "${existing.pluginName}" and entrypoint "${contribution.item.id}" from plugin "${contribution.pluginName}"`);
116
+ }
117
+ map.set(selector, contribution);
118
+ };
119
+ for (const contribution of seedEntrypoints) {
120
+ const entrypoint = contribution.item;
121
+ let selectorCount = 0;
122
+ if (entrypoint.basename) {
123
+ selectorCount += 1;
124
+ registerSeedEntrypointSelector(seedEntrypointByBasename, "basename", entrypoint.basename, contribution);
125
+ }
126
+ if (entrypoint.workerArg) {
127
+ selectorCount += 1;
128
+ registerSeedEntrypointSelector(seedEntrypointByWorkerArg, "workerArg", entrypoint.workerArg, contribution);
129
+ }
130
+ if (entrypoint.insidePty) {
131
+ selectorCount += 1;
132
+ if (insidePtySeedEntrypoint) {
133
+ throw new Error(`duplicate seed entrypoint inside-pty selector: registered by entrypoint "${insidePtySeedEntrypoint.item.id}" from plugin "${insidePtySeedEntrypoint.pluginName}" and entrypoint "${entrypoint.id}" from plugin "${contribution.pluginName}"`);
134
+ }
135
+ insidePtySeedEntrypoint = contribution;
136
+ }
137
+ if (selectorCount === 0) {
138
+ throw new Error(`seed entrypoint "${entrypoint.id}" from plugin "${contribution.pluginName}" must declare at least one selector (basename, workerArg, or insidePty)`);
139
+ }
140
+ }
141
+ const allValidators = validators.map((c) => c.item);
142
+ const allHooks = hooks.map((c) => c.item);
143
+ const allSkills = skills.map((c) => c.item);
144
+ const allRepoSources = repoSources.map((c) => c.item);
145
+ const allAgentRoles = agentRoles.map((c) => c.item);
146
+ const allTaskFieldExtensions = taskFieldExtensions.map((c) => c.item);
147
+ const allTaskSources = taskSources.map((c) => c.item);
148
+ const allCliCommands = cliCommands.map((c) => c.item);
149
+ const allStageMutations = stageMutations.map((c) => c.item);
150
+ const allStages = stages.map((c) => c.item);
151
+ const allCapabilities = capabilities.map((c) => c.item);
152
+ const allPanels = panels.map((c) => c.item);
153
+ const allBlockerClassifiers = blockerClassifiers.map((c) => c.item);
154
+ const allSessionExtensions = sessionExtensions.map((c) => c.item);
155
+ const allSeedEntrypoints = seedEntrypoints.map((c) => c.item);
156
+ const executableCliCommandByName = new Map;
157
+ const registerExecutableCliCommandSelector = (selector, contribution) => {
158
+ const existing = executableCliCommandByName.get(selector);
159
+ if (existing && existing.item.id !== contribution.item.id) {
160
+ throw new Error(`duplicate executable CLI selector "${selector}" registered by command "${existing.item.id}" from plugin "${existing.pluginName}" and command "${contribution.item.id}" from plugin "${contribution.pluginName}"`);
161
+ }
162
+ executableCliCommandByName.set(selector, contribution);
163
+ };
164
+ for (const contribution of cliCommands) {
165
+ const command = contribution.item;
166
+ const family = command.family ?? command.id;
167
+ registerExecutableCliCommandSelector(command.id, contribution);
168
+ registerExecutableCliCommandSelector(family, contribution);
169
+ for (const alias of command.aliases ?? []) {
170
+ registerExecutableCliCommandSelector(alias, contribution);
171
+ }
172
+ }
173
+ let defaultRootCliCommand;
174
+ for (const contribution of cliCommands) {
175
+ if (!contribution.item.rootDefault)
176
+ continue;
177
+ if (defaultRootCliCommand) {
178
+ throw new Error(`duplicate default root CLI command registered by command "${defaultRootCliCommand.item.id}" from plugin "${defaultRootCliCommand.pluginName}" and command "${contribution.item.id}" from plugin "${contribution.pluginName}"`);
179
+ }
180
+ defaultRootCliCommand = contribution;
181
+ }
182
+ return {
183
+ getValidator: (id) => validatorMap.get(id),
184
+ getHook: (id) => hookMap.get(id),
185
+ getSkill: (id) => skillMap.get(id),
186
+ getRepoSource: (id) => repoSourceMap.get(id),
187
+ getAgentRole: (id) => agentRoleMap.get(id),
188
+ getTaskFieldExtension: (id) => taskFieldExtMap.get(id),
189
+ getTaskSource: (id) => taskSourceMap.get(id),
190
+ getCliCommand: (id) => cliCommandMap.get(id),
191
+ getCapability: (id) => capabilityMap.get(id),
192
+ getPanel: (id) => panelMap.get(id),
193
+ getBlockerClassifier: (id) => blockerClassifierMap.get(id),
194
+ listValidators: () => allValidators,
195
+ listHooks: () => allHooks,
196
+ listSkills: () => allSkills,
197
+ listRepoSources: () => allRepoSources,
198
+ listAgentRoles: () => allAgentRoles,
199
+ listTaskFieldExtensions: () => allTaskFieldExtensions,
200
+ listTaskSources: () => allTaskSources,
201
+ listCliCommands: () => allCliCommands,
202
+ listCapabilities: () => allCapabilities,
203
+ listPanels: () => allPanels,
204
+ listBlockerClassifiers: () => allBlockerClassifiers,
205
+ listStages: () => allStages,
206
+ listStageMutations: () => allStageMutations,
207
+ listStageExecutors: () => stageExecutors,
208
+ listExecutableValidators: () => allValidators.filter((v) => typeof v.run === "function"),
209
+ listExecutableTaskSources: () => allTaskSources,
210
+ listExecutableCapabilities: () => allCapabilities.filter((c) => typeof c.run === "function"),
211
+ listExecutablePanels: () => allPanels.filter((p) => typeof p.produce === "function"),
212
+ listExecutableBlockerClassifiers: () => allBlockerClassifiers,
213
+ listExecutableCliCommands: () => allCliCommands,
214
+ listSessionExtensions: () => allSessionExtensions,
215
+ listSeedEntrypoints: () => allSeedEntrypoints,
216
+ resolveSeedEntrypointByBasename: (value) => seedEntrypointByBasename.get(value)?.item,
217
+ resolveSeedEntrypointByWorkerArg: (value) => seedEntrypointByWorkerArg.get(value)?.item,
218
+ resolveInsidePtySeedEntrypoint: () => insidePtySeedEntrypoint?.item,
219
+ resolveExecutableCliCommand: (requested) => executableCliCommandByName.get(requested)?.item,
220
+ resolveDefaultRootCliCommand: () => defaultRootCliCommand?.item,
221
+ resolveTaskSourceFactoryByKind: (kind) => taskSourceFactoryByKind.get(kind)
222
+ };
223
+ }
224
+
225
+ // packages/core/src/load-config.ts
226
+ import { existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync as readFileSync2, readdirSync, rmSync, statSync } from "fs";
227
+ import { isBuiltin } from "module";
228
+ import { basename, dirname, isAbsolute, join as join2, relative, resolve } from "path";
229
+ import { pathToFileURL } from "url";
230
+ import { Schema as Schema3 } from "effect";
231
+ import { RigConfig as RigConfig3 } from "@rig/contracts";
232
+
233
+ // packages/core/src/define-config.ts
234
+ import { Schema } from "effect";
235
+ import { RigConfig } from "@rig/contracts";
236
+ function normalizeWorkspaceConfig(raw) {
237
+ const workspace = raw && typeof raw === "object" && !Array.isArray(raw) ? { ...raw } : {};
238
+ if (workspace.mainRepo === undefined)
239
+ workspace.mainRepo = ".";
240
+ if (workspace.checkout === undefined && workspace.isolation !== undefined)
241
+ workspace.checkout = workspace.isolation;
242
+ if (workspace.isolation === undefined && workspace.checkout !== undefined)
243
+ workspace.isolation = workspace.checkout;
244
+ return workspace;
245
+ }
246
+ function applyConfigDefaults(raw) {
247
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
248
+ return raw;
249
+ const record = raw;
250
+ return {
251
+ ...record,
252
+ plugins: Array.isArray(record.plugins) ? record.plugins.flat() : [],
253
+ workspace: normalizeWorkspaceConfig(record.workspace)
254
+ };
255
+ }
256
+
257
+ // packages/core/src/declarative-config.ts
258
+ import { existsSync, readFileSync } from "fs";
259
+ import { join } from "path";
260
+ import { parse as parseToml } from "smol-toml";
261
+ import { Schema as Schema2 } from "effect";
262
+ import { RigConfig as RigConfig2 } from "@rig/contracts";
263
+
264
+ // packages/core/src/embedded-plugins.ts
265
+ var registered = null;
266
+ function getStandardPluginsResolver() {
267
+ return registered;
268
+ }
269
+ var bakedProjectConfig = null;
270
+ function getEmbeddedProjectConfig() {
271
+ return bakedProjectConfig;
272
+ }
273
+
274
+ // packages/core/src/declarative-config.ts
275
+ var DECLARATIVE_CONFIG_NAMES = ["rigfig.toml", "rigfig.json"];
276
+ function findDeclarativeConfigPath(cwd) {
277
+ const dir = join(cwd, ".rig");
278
+ for (const name of DECLARATIVE_CONFIG_NAMES) {
279
+ const candidate = join(dir, name);
280
+ if (existsSync(candidate))
281
+ return candidate;
282
+ }
283
+ return null;
284
+ }
285
+ function parseDeclarativeFile(path) {
286
+ const raw = readFileSync(path, "utf8");
287
+ const parsed = path.endsWith(".json") ? JSON.parse(raw) : parseToml(raw);
288
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
289
+ throw new Error(`Declarative config ${path} must parse to an object.`);
290
+ }
291
+ return parsed;
292
+ }
293
+ function loadDeclarativeConfig(path) {
294
+ const data = parseDeclarativeFile(path);
295
+ const standardSection = data.standard && typeof data.standard === "object" && !Array.isArray(data.standard) ? data.standard : null;
296
+ if (standardSection?.enabled !== true && standardSection?.enabled !== false) {
297
+ throw new Error(`Declarative config ${path} must explicitly set [standard] enabled = true or false.`);
298
+ }
299
+ const useStandard = standardSection.enabled === true;
300
+ let plugins = [];
301
+ if (useStandard) {
302
+ const resolver = getStandardPluginsResolver();
303
+ if (!resolver) {
304
+ throw new Error(`Declarative config ${path} needs the embedded standard plugins, but none were registered. ` + `This is a seed/boot wiring error (the binary entrypoint must import the standard-plugin registration).`);
305
+ }
306
+ plugins = resolver(data);
307
+ }
308
+ const { standard: _standardDirective, ...configFields } = data;
309
+ const withDefaults = applyConfigDefaults({ ...configFields, plugins });
310
+ const explicitPlugins = Array.isArray(withDefaults.plugins) ? [...withDefaults.plugins] : [];
311
+ const decoded = Schema2.decodeUnknownSync(RigConfig2)({
312
+ ...withDefaults,
313
+ plugins: explicitPlugins
314
+ });
315
+ return { ...decoded, plugins: explicitPlugins };
316
+ }
317
+
318
+ // packages/core/src/load-config.ts
319
+ var TS_NAMES = [".rig/rig.config.ts", ".rig/rig.config.mts"];
320
+ var JSON_NAMES = [".rig/rig.config.json"];
321
+ function isModuleResolutionError(error) {
322
+ const message = error instanceof Error ? error.message : String(error);
323
+ return message.includes("Cannot find module") || message.includes("Could not resolve");
324
+ }
325
+ function runningFromCompiledBinary() {
326
+ return import.meta.url.includes("$bunfs");
327
+ }
328
+ function packageNameAndSubpath(specifier) {
329
+ if (specifier.startsWith(".") || specifier.startsWith("/") || /^[a-zA-Z]+:/.test(specifier))
330
+ return null;
331
+ const parts = specifier.split("/");
332
+ const packageName = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
333
+ if (!packageName)
334
+ return null;
335
+ const rest = parts.slice(specifier.startsWith("@") ? 2 : 1).join("/");
336
+ return { packageName, subpath: rest ? `./${rest}` : "." };
337
+ }
338
+ function exportTargetFromEntry(entry) {
339
+ if (typeof entry === "string")
340
+ return entry;
341
+ if (Array.isArray(entry)) {
342
+ for (const candidate of entry) {
343
+ const target = exportTargetFromEntry(candidate);
344
+ if (target)
345
+ return target;
346
+ }
347
+ return null;
348
+ }
349
+ if (entry && typeof entry === "object") {
350
+ const conditions = entry;
351
+ for (const key of ["bun", "node", "import", "default", "require"]) {
352
+ const target = exportTargetFromEntry(conditions[key]);
353
+ if (target)
354
+ return target;
355
+ }
356
+ }
357
+ return null;
358
+ }
359
+ function patternExportTarget(record, subpath) {
360
+ const entries = Object.entries(record).filter(([pattern]) => pattern.includes("*")).sort(([a], [b]) => b.replace("*", "").length - a.replace("*", "").length);
361
+ for (const [pattern, entry] of entries) {
362
+ const [prefix = "", suffix = ""] = pattern.split("*");
363
+ if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix))
364
+ continue;
365
+ const replacement = subpath.slice(prefix.length, subpath.length - suffix.length);
366
+ const target = exportTargetFromEntry(entry);
367
+ if (target)
368
+ return target.replace("*", replacement);
369
+ }
370
+ return null;
371
+ }
372
+ function exportTargetFromPackageJson(pkg, subpath) {
373
+ const exportsField = pkg.exports;
374
+ const target = (() => {
375
+ if (typeof exportsField === "string" && subpath === ".")
376
+ return exportsField;
377
+ if (!exportsField || typeof exportsField !== "object" || Array.isArray(exportsField))
378
+ return null;
379
+ const record = exportsField;
380
+ return exportTargetFromEntry(record[subpath] ?? (subpath === "." ? record["."] : undefined)) ?? patternExportTarget(record, subpath);
381
+ })();
382
+ if (target)
383
+ return target;
384
+ return subpath === "." && typeof pkg.module === "string" ? pkg.module : subpath === "." && typeof pkg.main === "string" ? pkg.main : null;
385
+ }
386
+ function patternImportTarget(record, specifier) {
387
+ for (const [pattern, entry] of Object.entries(record)) {
388
+ if (!pattern.includes("*"))
389
+ continue;
390
+ const [prefix = "", suffix = ""] = pattern.split("*");
391
+ if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix))
392
+ continue;
393
+ const replacement = specifier.slice(prefix.length, specifier.length - suffix.length);
394
+ const target = exportTargetFromEntry(entry);
395
+ if (target)
396
+ return target.replace("*", replacement);
397
+ }
398
+ return null;
399
+ }
400
+ function resolvePackagePrivateImport(specifier, importer, projectRoot) {
401
+ if (!specifier.startsWith("#") || !importer || !isAbsolute(importer))
402
+ return null;
403
+ let dir = dirname(importer);
404
+ const stop = resolve(projectRoot);
405
+ while (isWithinDir(dir, stop)) {
406
+ const packageJsonPath = join2(dir, "package.json");
407
+ if (existsSync2(packageJsonPath)) {
408
+ try {
409
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
410
+ const imports = pkg.imports;
411
+ if (imports && typeof imports === "object" && !Array.isArray(imports)) {
412
+ const record = imports;
413
+ const target = exportTargetFromEntry(record[specifier]) ?? patternImportTarget(record, specifier);
414
+ if (target)
415
+ return resolveModulePath(join2(dir, target));
416
+ }
417
+ } catch {
418
+ return null;
419
+ }
420
+ return null;
421
+ }
422
+ const parent = dirname(dir);
423
+ if (parent === dir)
424
+ return null;
425
+ dir = parent;
426
+ }
427
+ return null;
428
+ }
429
+ function resolvePackageDirFromBunStore(packageName, nodeModulesDir) {
430
+ const storeDir = join2(nodeModulesDir, ".bun");
431
+ if (!existsSync2(storeDir))
432
+ return null;
433
+ const encoded = packageName.replace("/", "+");
434
+ try {
435
+ const candidates = readdirSync(storeDir).filter((entry) => entry.startsWith(`${encoded}@`)).map((entry) => {
436
+ const candidateDir = join2(storeDir, entry, "node_modules", packageName);
437
+ const packageJsonPath = join2(candidateDir, "package.json");
438
+ if (!existsSync2(packageJsonPath))
439
+ return null;
440
+ try {
441
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
442
+ return {
443
+ dir: candidateDir,
444
+ sortKey: pkg.version?.trim() || entry
445
+ };
446
+ } catch {
447
+ return {
448
+ dir: candidateDir,
449
+ sortKey: entry
450
+ };
451
+ }
452
+ }).filter((candidate) => candidate !== null).sort((a, b) => b.sortKey.localeCompare(a.sortKey, undefined, { numeric: true, sensitivity: "base" }));
453
+ return candidates[0]?.dir ?? null;
454
+ } catch {
455
+ return null;
456
+ }
457
+ }
458
+ function resolveDirectoryModulePath(directoryPath) {
459
+ const packageJsonPath = join2(directoryPath, "package.json");
460
+ if (existsSync2(packageJsonPath)) {
461
+ try {
462
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
463
+ const target = exportTargetFromPackageJson(pkg, ".");
464
+ if (target) {
465
+ const resolved = resolveModulePath(join2(directoryPath, target));
466
+ if (resolved)
467
+ return resolved;
468
+ }
469
+ } catch {}
470
+ }
471
+ for (const candidate of ["index.js", "index.mjs", "index.cjs", "index.ts", "index.json"]) {
472
+ const resolved = resolveModulePath(join2(directoryPath, candidate));
473
+ if (resolved)
474
+ return resolved;
475
+ }
476
+ return null;
477
+ }
478
+ function resolveModulePath(candidatePath) {
479
+ if (!existsSync2(candidatePath)) {
480
+ for (const extension of [".ts", ".mts", ".tsx", ".js", ".mjs", ".cjs", ".json"]) {
481
+ const withExtension = `${candidatePath}${extension}`;
482
+ if (existsSync2(withExtension))
483
+ return resolveModulePath(withExtension);
484
+ }
485
+ return null;
486
+ }
487
+ try {
488
+ const stat = statSync(candidatePath);
489
+ if (stat.isFile())
490
+ return candidatePath;
491
+ if (stat.isDirectory())
492
+ return resolveDirectoryModulePath(candidatePath);
493
+ } catch {
494
+ return null;
495
+ }
496
+ return null;
497
+ }
498
+ function resolvePackageExportFromDir(packageDir, subpath) {
499
+ const packageJsonPath = join2(packageDir, "package.json");
500
+ if (existsSync2(packageJsonPath)) {
501
+ try {
502
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
503
+ const targets = [
504
+ exportTargetFromPackageJson(pkg, subpath),
505
+ ...subpath === "." ? [typeof pkg.module === "string" ? pkg.module : null, typeof pkg.main === "string" ? pkg.main : null] : []
506
+ ];
507
+ const seen = new Set;
508
+ for (const target of targets) {
509
+ if (!target || seen.has(target))
510
+ continue;
511
+ seen.add(target);
512
+ const resolved = resolveModulePath(join2(packageDir, target));
513
+ if (resolved)
514
+ return resolved;
515
+ }
516
+ } catch {
517
+ return null;
518
+ }
519
+ }
520
+ if (subpath !== ".") {
521
+ const legacySubpath = subpath.replace(/^\.\//, "");
522
+ for (const candidate of [
523
+ join2(packageDir, legacySubpath),
524
+ join2(packageDir, `${legacySubpath}.js`),
525
+ join2(packageDir, `${legacySubpath}.mjs`),
526
+ join2(packageDir, `${legacySubpath}.cjs`),
527
+ join2(packageDir, `${legacySubpath}.ts`),
528
+ join2(packageDir, `${legacySubpath}.json`)
529
+ ]) {
530
+ const resolved = resolveModulePath(candidate);
531
+ if (resolved)
532
+ return resolved;
533
+ }
534
+ }
535
+ return subpath === "." ? resolveDirectoryModulePath(packageDir) : null;
536
+ }
537
+ var runtimeBundleQueue = Promise.resolve();
538
+ function enqueueRuntimeBundle(operation) {
539
+ const next = runtimeBundleQueue.then(operation, operation);
540
+ runtimeBundleQueue = next.then(() => {
541
+ return;
542
+ }, () => {
543
+ return;
544
+ });
545
+ return next;
546
+ }
547
+ function isWithinDir(candidatePath, rootPath) {
548
+ const rel = relative(resolve(rootPath), resolve(candidatePath));
549
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
550
+ }
551
+ function resolvedFilePath(path, rootPath) {
552
+ if (!path || !isAbsolute(path))
553
+ return null;
554
+ const resolved = resolveModulePath(path);
555
+ if (!resolved)
556
+ return null;
557
+ return rootPath && !isWithinDir(resolved, rootPath) ? null : resolved;
558
+ }
559
+ function resolveProjectPackageImport(specifier, configDir) {
560
+ const parsed = packageNameAndSubpath(specifier);
561
+ if (!parsed)
562
+ return null;
563
+ const nodeModulesDir = join2(configDir, "node_modules");
564
+ const directPackageDir = join2(nodeModulesDir, parsed.packageName);
565
+ const packageDir = existsSync2(join2(directPackageDir, "package.json")) ? directPackageDir : resolvePackageDirFromBunStore(parsed.packageName, nodeModulesDir);
566
+ return packageDir ? resolvePackageExportFromDir(packageDir, parsed.subpath) : null;
567
+ }
568
+ function canImportRigWorkspacePackagesDirectly(source, configDir) {
569
+ const packageNames = new Set;
570
+ for (const match of source.matchAll(/(?:from\s*|import\s*\(\s*|import\s*)["'](@rig\/[^"']+)["']/g)) {
571
+ const parsed = packageNameAndSubpath(match[1] ?? "");
572
+ if (parsed?.packageName)
573
+ packageNames.add(parsed.packageName);
574
+ }
575
+ if (packageNames.size === 0)
576
+ return false;
577
+ for (const packageName of packageNames) {
578
+ const shortName = packageName.replace(/^@rig\//, "");
579
+ const manifestPath = join2(configDir, "packages", shortName, "package.json");
580
+ if (!existsSync2(manifestPath))
581
+ return false;
582
+ try {
583
+ const parsed = JSON.parse(readFileSync2(manifestPath, "utf8"));
584
+ if (parsed.name !== packageName)
585
+ return false;
586
+ } catch {
587
+ return false;
588
+ }
589
+ }
590
+ return true;
591
+ }
592
+ async function importConfigViaRuntimeBundleUnserialized(configPath) {
593
+ const bun = globalThis.Bun;
594
+ if (!bun?.build) {
595
+ throw new Error(`Failed to import ${configPath}: bare imports could not be resolved and no Bun.build runtime bundler is available.`);
596
+ }
597
+ const RUNTIME_ONLY_EXTERNAL_PACKAGES = new Set(["effect", "mupdf", "fastembed", "onnxruntime-node", "markit-ai"]);
598
+ const configDir = dirname(configPath);
599
+ const configProjectRoot = basename(configDir) === ".rig" ? dirname(configDir) : configDir;
600
+ const UNRESOLVED_NAMESPACE = "rig-config-unresolved";
601
+ const ABSOLUTE_EXTERNAL_NAMESPACE = "rig-config-absolute-external";
602
+ const unresolvedLocalPlugin = {
603
+ name: "rig-config-unresolved-local",
604
+ setup(build) {
605
+ build.onLoad({ filter: /[\\/]@oh-my-pi[\\/]pi-coding-agent[\\/]src[\\/]export[\\/]html[\\/](?:template\.css|template\.html|template\.js|tool-views\.generated\.js)$/ }, (args) => ({
606
+ loader: "js",
607
+ contents: `export default ${JSON.stringify(readFileSync2(args.path, "utf8"))};
608
+ `
609
+ }));
610
+ build.onLoad({ filter: /\.(?:html|txt)$/ }, (args) => ({
611
+ loader: "js",
612
+ contents: `export default ${JSON.stringify(readFileSync2(args.path, "utf8"))};
613
+ `
614
+ }));
615
+ build.onResolve({ filter: /.*/ }, (args) => {
616
+ const directFilePath = resolvedFilePath(args.path, configDir);
617
+ if (directFilePath)
618
+ return { path: directFilePath };
619
+ if (args.path.startsWith("#")) {
620
+ const packagePrivatePath = resolvePackagePrivateImport(args.path, args.importer, configProjectRoot);
621
+ if (packagePrivatePath)
622
+ return { path: packagePrivatePath };
623
+ try {
624
+ const parent2 = args.importer && isAbsolute(args.importer) ? dirname(args.importer) : configProjectRoot;
625
+ const resolved = bun.resolveSync?.(args.path, parent2);
626
+ const filePath = resolvedFilePath(resolved, configProjectRoot);
627
+ if (filePath)
628
+ return { path: filePath };
629
+ } catch {}
630
+ return;
631
+ }
632
+ const packageImport = packageNameAndSubpath(args.path);
633
+ if (packageImport?.packageName === "uhyphen" && packageImport.subpath === ".") {
634
+ const uhyphenPath = resolveProjectPackageImport("uhyphen", configProjectRoot);
635
+ if (uhyphenPath)
636
+ return { path: uhyphenPath };
637
+ }
638
+ if (packageImport && packageImport.packageName !== "uhyphen") {
639
+ try {
640
+ const parent2 = args.importer && isAbsolute(args.importer) ? dirname(args.importer) : configProjectRoot;
641
+ const resolved = bun.resolveSync?.(args.path, parent2);
642
+ const filePath = resolvedFilePath(resolved, configProjectRoot);
643
+ if (filePath)
644
+ return { path: filePath };
645
+ } catch {}
646
+ }
647
+ const projectPackagePath = packageImport ? resolveProjectPackageImport(args.path, configProjectRoot) : null;
648
+ if (projectPackagePath)
649
+ return { path: projectPackagePath };
650
+ if (packageImport && (packageImport.packageName.startsWith("@rig/") || RUNTIME_ONLY_EXTERNAL_PACKAGES.has(packageImport.packageName))) {
651
+ return { path: args.path, external: true };
652
+ }
653
+ if (/^(?:node|bun):/.test(args.path) || isBuiltin(args.path))
654
+ return;
655
+ if (packageImport)
656
+ return { path: args.path, external: true };
657
+ const importerDir = args.importer && isAbsolute(args.importer) ? dirname(args.importer) : null;
658
+ if (args.path.startsWith(".") && importerDir) {
659
+ const fromImporter = resolveModulePath(resolve(importerDir, args.path));
660
+ if (fromImporter)
661
+ return { path: fromImporter };
662
+ if (/[\\/]node_modules[\\/]/.test(args.importer ?? ""))
663
+ return;
664
+ }
665
+ const parentCandidates = args.path.startsWith(".") ? [importerDir, configDir].filter((value) => Boolean(value)) : [importerDir ?? configDir];
666
+ for (const parent2 of parentCandidates) {
667
+ const filePath = resolvedFilePath(resolve(parent2, args.path), configProjectRoot);
668
+ if (filePath)
669
+ return { path: filePath };
670
+ }
671
+ const parent = parentCandidates[0] ?? configDir;
672
+ try {
673
+ const resolved = bun.resolveSync?.(args.path, parent) ?? resolve(parent, args.path);
674
+ const filePath = resolvedFilePath(resolved, configProjectRoot);
675
+ if (filePath)
676
+ return { path: filePath };
677
+ } catch {}
678
+ return { path: args.path, namespace: UNRESOLVED_NAMESPACE };
679
+ });
680
+ build.onLoad({ filter: /.*/, namespace: ABSOLUTE_EXTERNAL_NAMESPACE }, (args) => {
681
+ const href = pathToFileURL(args.path).href;
682
+ return {
683
+ loader: "js",
684
+ contents: `export * from ${JSON.stringify(href)};
685
+ const mod = await import(${JSON.stringify(href)});
686
+ export default (mod && "default" in mod) ? mod.default : mod;
687
+ `
688
+ };
689
+ });
690
+ build.onLoad({ filter: /.*/, namespace: UNRESOLVED_NAMESPACE }, (args) => ({
691
+ loader: "js",
692
+ contents: `module.exports = {};
693
+ throw new Error(${JSON.stringify(`Failed to bundle ${configPath}: Could not resolve local import "${args.path}". Maybe you need to fix a relative import in rig.config.ts or install project deps.`)});
694
+ `
695
+ }));
696
+ }
697
+ };
698
+ const result = await bun.build({
699
+ entrypoints: [configPath],
700
+ target: "bun",
701
+ format: "esm",
702
+ throw: false,
703
+ packages: "bundle",
704
+ plugins: [unresolvedLocalPlugin]
705
+ });
706
+ if (!result.success || !result.outputs[0]) {
707
+ const detail = result.logs.map((log) => String(log)).join(`
708
+ `);
709
+ throw new Error(`Failed to bundle ${configPath}: ${detail || "unknown bundler error"}`);
710
+ }
711
+ const bundleParentDir = join2(configProjectRoot, ".rig", "tmp");
712
+ mkdirSync(bundleParentDir, { recursive: true });
713
+ const dir = mkdtempSync(join2(bundleParentDir, "rig-config-bundle-"));
714
+ try {
715
+ const bundledPath = join2(dir, "rig.config.bundled.js");
716
+ await bun.write(bundledPath, await result.outputs[0].text());
717
+ return await import(pathToFileURL(bundledPath).href);
718
+ } finally {
719
+ try {
720
+ rmSync(dir, { recursive: true, force: true });
721
+ } catch {}
722
+ }
723
+ }
724
+ async function loadConfig(cwd) {
725
+ const baked = getEmbeddedProjectConfig();
726
+ if (baked && resolve(baked.projectRoot) === resolve(cwd)) {
727
+ return decodeExplicitPluginConfig(baked.raw);
728
+ }
729
+ for (const name of TS_NAMES) {
730
+ const p = join2(cwd, name);
731
+ if (existsSync2(p)) {
732
+ const mod = await enqueueRuntimeBundle(async () => {
733
+ if (runningFromCompiledBinary()) {
734
+ return importConfigViaRuntimeBundleUnserialized(p);
735
+ }
736
+ const source = readFileSync2(p, "utf8");
737
+ const importsRigHostPackages = /(?:import\s+[^;]*?from\s*|import\s*\()\s*["']@rig\//.test(source);
738
+ if (importsRigHostPackages && !canImportRigWorkspacePackagesDirectly(source, cwd)) {
739
+ return importConfigViaRuntimeBundleUnserialized(p);
740
+ }
741
+ try {
742
+ return await import(pathToFileURL(p).href);
743
+ } catch (error) {
744
+ if (!isModuleResolutionError(error))
745
+ throw error;
746
+ return importConfigViaRuntimeBundleUnserialized(p);
747
+ }
748
+ });
749
+ const raw = mod.default ?? mod.config;
750
+ return decodeExplicitPluginConfig(raw);
751
+ }
752
+ }
753
+ const declarativePath = findDeclarativeConfigPath(cwd);
754
+ if (declarativePath) {
755
+ return loadDeclarativeConfig(declarativePath);
756
+ }
757
+ for (const name of JSON_NAMES) {
758
+ const p = join2(cwd, name);
759
+ if (existsSync2(p)) {
760
+ const raw = JSON.parse(readFileSync2(p, "utf-8"));
761
+ return decodeExplicitPluginConfig(raw);
762
+ }
763
+ }
764
+ throw new Error(`no .rig/rig.config.{ts,mts,json} or .rig/rigfig.{toml,json} found in ${cwd}`);
765
+ }
766
+ function decodeExplicitPluginConfig(raw) {
767
+ const withDefaults = applyConfigDefaults(raw);
768
+ const explicitPlugins = Array.isArray(withDefaults.plugins) ? [...withDefaults.plugins] : [];
769
+ const decoded = Schema3.decodeUnknownSync(RigConfig3)({
770
+ ...withDefaults,
771
+ plugins: explicitPlugins
772
+ });
773
+ return { ...decoded, plugins: explicitPlugins };
774
+ }
775
+
776
+ // packages/core/src/project-plugins.ts
777
+ var TS_CONFIG_FILENAMES = ["rig.config.ts", "rig.config.mts"];
778
+ var JSON_CONFIG_FILENAMES = ["rig.config.json"];
779
+ function findProjectConfigPath(projectRoot) {
780
+ for (const name of TS_CONFIG_FILENAMES) {
781
+ const path = resolve2(projectRoot, ".rig", name);
782
+ if (existsSync3(path))
783
+ return path;
784
+ }
785
+ const declarativePath = findDeclarativeConfigPath(projectRoot);
786
+ if (declarativePath)
787
+ return declarativePath;
788
+ for (const name of JSON_CONFIG_FILENAMES) {
789
+ const path = resolve2(projectRoot, ".rig", name);
790
+ if (existsSync3(path))
791
+ return path;
792
+ }
793
+ return null;
794
+ }
795
+ var pluginHostCache = new Map;
796
+ function configFileMtimeMs(normalizedRoot) {
797
+ const path = findProjectConfigPath(normalizedRoot);
798
+ if (!path)
799
+ return 0;
800
+ try {
801
+ return statSync2(path).mtimeMs;
802
+ } catch {
803
+ return 0;
804
+ }
805
+ }
806
+ function resolvePluginHost(projectRoot, options = {}) {
807
+ const normalizedRoot = resolve2(projectRoot);
808
+ const build = (load) => load(normalizedRoot).then((config) => ({
809
+ host: createPluginHost(config.plugins),
810
+ config
811
+ }));
812
+ if (options.load)
813
+ return build(options.load);
814
+ const mtimeMs = configFileMtimeMs(normalizedRoot);
815
+ const cached = pluginHostCache.get(normalizedRoot);
816
+ if (cached && cached.mtimeMs === mtimeMs)
817
+ return cached.promise;
818
+ const promise = build(loadConfig);
819
+ promise.catch(() => {
820
+ if (pluginHostCache.get(normalizedRoot)?.promise === promise) {
821
+ pluginHostCache.delete(normalizedRoot);
822
+ }
823
+ });
824
+ pluginHostCache.set(normalizedRoot, { mtimeMs, promise });
825
+ return promise;
826
+ }
827
+
828
+ // packages/core/src/plugin-host-registries.ts
829
+ function createTaskSourceRegistry() {
830
+ const byId = new Map;
831
+ const order = [];
832
+ return {
833
+ register(s) {
834
+ if (byId.has(s.id))
835
+ throw new Error(`task source already registered: ${s.id}`);
836
+ byId.set(s.id, s);
837
+ order.push(s);
838
+ },
839
+ resolveById(id) {
840
+ const s = byId.get(id);
841
+ if (!s)
842
+ throw new Error(`task source not registered: ${id}`);
843
+ return s;
844
+ },
845
+ resolveByKind(kind) {
846
+ for (const s of order)
847
+ if (s.kind === kind)
848
+ return s;
849
+ throw new Error(`no task source registered for kind: ${kind}`);
850
+ },
851
+ list: () => order
852
+ };
853
+ }
854
+ function formatRegisteredKinds(pluginHost) {
855
+ const kinds = pluginHost ? pluginHost.listExecutableTaskSources().map((source) => source.kind) : [];
856
+ return kinds.length > 0 ? kinds.join(", ") : "none";
857
+ }
858
+ function buildTaskSourceRegistry(config, pluginHost, context) {
859
+ const registry = createTaskSourceRegistry();
860
+ const taskSourceConfig = config.taskSource;
861
+ const factory = pluginHost?.resolveTaskSourceFactoryByKind(taskSourceConfig.kind);
862
+ if (!factory) {
863
+ throw new Error(`No task source factory registered for kind "${taskSourceConfig.kind}". ` + `Registered kinds: ${formatRegisteredKinds(pluginHost)}. ` + "Load a plugin that contributes an executable task source factory for this kind.");
864
+ }
865
+ registry.register(factory.factory(taskSourceConfig, context ? { ...context, rigConfig: config } : undefined));
866
+ return registry;
867
+ }
868
+ function createTaskFieldRegistry(extensions) {
869
+ const byId = new Map;
870
+ for (const e of extensions) {
871
+ if (byId.has(e.id))
872
+ throw new Error(`task field extension already registered: ${e.id}`);
873
+ byId.set(e.id, e);
874
+ }
875
+ return {
876
+ get: (id) => byId.get(id),
877
+ list: () => Array.from(byId.values()),
878
+ fieldNames: () => Array.from(byId.values()).map((e) => e.fieldName),
879
+ validateTaskFields(task) {
880
+ const errors = [];
881
+ for (const ext of byId.values()) {
882
+ let schema;
883
+ try {
884
+ schema = JSON.parse(ext.schemaJson);
885
+ } catch {
886
+ errors.push(`task field "${ext.id}": schemaJson is not valid JSON`);
887
+ continue;
888
+ }
889
+ const isRequired = typeof schema === "object" && schema !== null && schema.required === true;
890
+ if (!isRequired)
891
+ continue;
892
+ const value = task[ext.fieldName];
893
+ if (value === undefined || value === null || value === "") {
894
+ errors.push(`task field "${ext.fieldName}" (from extension "${ext.id}") is required but missing`);
895
+ }
896
+ }
897
+ return errors.length === 0 ? { ok: true } : { ok: false, errors };
898
+ }
899
+ };
900
+ }
901
+
902
+ // packages/core/src/plugin-host-context.ts
903
+ import {
904
+ MANAGED_REPO_SERVICE_CAPABILITY,
905
+ REPO_CHANGE_SET,
906
+ REPO_GIT_BINARY,
907
+ REPO_NATIVE_GIT,
908
+ RUNTIME_SECRETS,
909
+ SESSION_ASSET_MATERIALIZER,
910
+ SESSION_HOOK_MATERIALIZER,
911
+ TASK_ARTIFACTS,
912
+ TASK_STATE_STORE,
913
+ TASK_TRACKER_READINESS_POLICY,
914
+ TASK_TRACKER_RECONCILIATION_POLICY,
915
+ TASK_TRACKER_REPO_LOCATOR,
916
+ TASK_TRACKER_STATE,
917
+ TOOL_MATERIALIZER
918
+ } from "@rig/contracts";
919
+
920
+ // packages/core/src/capability.ts
921
+ import { resolveCapability } from "@rig/kernel-seed";
922
+
923
+ class CapabilityProviderMissingError extends Error {
924
+ capabilityId;
925
+ name = "CapabilityProviderMissingError";
926
+ constructor(capabilityId) {
927
+ super(`No provider resolved for capability "${capabilityId}"`);
928
+ this.capabilityId = capabilityId;
929
+ }
930
+ }
931
+ function isFactory(impl) {
932
+ return typeof impl === "function";
933
+ }
934
+ function defineCapability(id) {
935
+ const idString = String(id);
936
+ const tag = idString;
937
+ async function resolve3(host) {
938
+ const providers = host.listExecutableCapabilities().filter((c) => c.id === idString && typeof c.run === "function").map((c) => ({
939
+ name: c.id,
940
+ provides: [c.id],
941
+ capabilityProviders: { [c.id]: c.run }
942
+ }));
943
+ const resolution = resolveCapability(providers, tag);
944
+ const run = resolution?.value;
945
+ if (!run)
946
+ return null;
947
+ return await run(undefined);
948
+ }
949
+ return {
950
+ id,
951
+ provide(impl, opts) {
952
+ return {
953
+ id: idString,
954
+ title: opts?.title ?? idString,
955
+ ...opts?.description !== undefined ? { description: opts.description } : {},
956
+ run: isFactory(impl) ? () => impl() : () => impl
957
+ };
958
+ },
959
+ resolve: resolve3,
960
+ async require(host) {
961
+ const value = await resolve3(host);
962
+ if (value === null)
963
+ throw new CapabilityProviderMissingError(idString);
964
+ return value;
965
+ }
966
+ };
967
+ }
968
+
969
+ // packages/core/src/capability-loaders.ts
970
+ var INSTALLED = new Map;
971
+ function installCapability(capability, impl) {
972
+ INSTALLED.set(String(capability.id), impl);
973
+ }
974
+
975
+ // packages/core/src/agent-role-registry.ts
976
+ function createAgentRoleRegistry(pluginRoles, configOverrides) {
977
+ const map = new Map;
978
+ for (const r of pluginRoles) {
979
+ if (map.has(r.id))
980
+ throw new Error(`agent role already registered: ${r.id}`);
981
+ const override = configOverrides?.[r.id];
982
+ const model = override?.model ?? r.defaultModel;
983
+ if (!model) {
984
+ throw new Error(`agent role "${r.id}" has no model \u2014 provide defaultModel in plugin or model in config.runtime.agentRoles.${r.id}`);
985
+ }
986
+ map.set(r.id, { ...r, model });
987
+ }
988
+ return {
989
+ resolve(id) {
990
+ const r = map.get(id);
991
+ if (!r)
992
+ throw new Error(`agent role not registered: ${id}`);
993
+ return r;
994
+ },
995
+ list: () => Array.from(map.values())
996
+ };
997
+ }
998
+
999
+ // packages/core/src/validator-registry.ts
1000
+ import { existsSync as existsSync4 } from "fs";
1001
+ import { join as join3 } from "path";
1002
+ function createValidatorRegistry() {
1003
+ const map = new Map;
1004
+ const order = [];
1005
+ const registry = {
1006
+ register(v) {
1007
+ if (map.has(v.id))
1008
+ throw new Error(`validator already registered: ${v.id}`);
1009
+ map.set(v.id, v);
1010
+ order.push(v);
1011
+ },
1012
+ resolve(id) {
1013
+ const v = map.get(id);
1014
+ if (!v)
1015
+ throw new Error(`validator not registered: ${id}`);
1016
+ return v;
1017
+ },
1018
+ list: () => order
1019
+ };
1020
+ registerBuiltInValidators(registry);
1021
+ return registry;
1022
+ }
1023
+ function registerBuiltInValidators(registry) {
1024
+ registry.register({
1025
+ id: "std:typecheck",
1026
+ category: "custom",
1027
+ description: "Runs the package typecheck script when present.",
1028
+ run: async (ctx) => runStdTypecheck(ctx)
1029
+ });
1030
+ }
1031
+ async function runStdTypecheck(ctx) {
1032
+ const packageJsonPath = join3(ctx.workspaceRoot, "package.json");
1033
+ if (!existsSync4(packageJsonPath)) {
1034
+ return {
1035
+ id: "std:typecheck",
1036
+ passed: false,
1037
+ summary: `package.json not found at ${packageJsonPath}`
1038
+ };
1039
+ }
1040
+ const proc = Bun.spawn(["bun", "run", "typecheck"], {
1041
+ cwd: ctx.workspaceRoot,
1042
+ env: process.env,
1043
+ stdout: "pipe",
1044
+ stderr: "pipe"
1045
+ });
1046
+ const [exitCode, stdout, stderr] = await Promise.all([
1047
+ proc.exited,
1048
+ new Response(proc.stdout).text(),
1049
+ new Response(proc.stderr).text()
1050
+ ]);
1051
+ const output = `${stdout}${stderr}`.trim();
1052
+ return {
1053
+ id: "std:typecheck",
1054
+ passed: exitCode === 0,
1055
+ summary: exitCode === 0 ? "typecheck passed" : "typecheck failed",
1056
+ ...output ? { details: output.slice(0, 4000) } : {}
1057
+ };
1058
+ }
1059
+
1060
+ // packages/core/src/scope-rules.ts
1061
+ var SCOPE_RULES_KEY = Symbol.for("rig.scope-normalization-rules");
1062
+ function scopeRulesState() {
1063
+ const global = globalThis;
1064
+ return global[SCOPE_RULES_KEY] ??= { rules: null };
1065
+ }
1066
+ function setScopeRules(rules) {
1067
+ scopeRulesState().rules = rules ?? null;
1068
+ }
1069
+
1070
+ // packages/core/src/plugin-host-context.ts
1071
+ var ManagedRepoCap = defineCapability(MANAGED_REPO_SERVICE_CAPABILITY);
1072
+ var RepoChangeSetCap = defineCapability(REPO_CHANGE_SET);
1073
+ var RepoGitBinaryCap = defineCapability(REPO_GIT_BINARY);
1074
+ var RepoNativeGitCap = defineCapability(REPO_NATIVE_GIT);
1075
+ var RuntimeSecretsCap = defineCapability(RUNTIME_SECRETS);
1076
+ var SessionAssetMaterializerCap = defineCapability(SESSION_ASSET_MATERIALIZER);
1077
+ var SessionHookMaterializerCap = defineCapability(SESSION_HOOK_MATERIALIZER);
1078
+ var TaskArtifactsCap = defineCapability(TASK_ARTIFACTS);
1079
+ var TaskStateStoreCap = defineCapability(TASK_STATE_STORE);
1080
+ var TaskTrackerReadinessPolicyCap = defineCapability(TASK_TRACKER_READINESS_POLICY);
1081
+ var TaskTrackerReconciliationPolicyCap = defineCapability(TASK_TRACKER_RECONCILIATION_POLICY);
1082
+ var TaskTrackerRepoLocatorCap = defineCapability(TASK_TRACKER_REPO_LOCATOR);
1083
+ var TaskTrackerStateCap = defineCapability(TASK_TRACKER_STATE);
1084
+ var ToolMaterializerCap = defineCapability(TOOL_MATERIALIZER);
1085
+ async function buildPluginHostContext(projectRoot) {
1086
+ let config;
1087
+ let pluginHost;
1088
+ try {
1089
+ ({ config, host: pluginHost } = await resolvePluginHost(projectRoot));
1090
+ } catch (err) {
1091
+ const msg = err instanceof Error ? err.message : String(err);
1092
+ if (msg.includes("no .rig/rig.config") || msg.includes("no rig.config")) {
1093
+ return null;
1094
+ }
1095
+ throw err;
1096
+ }
1097
+ setScopeRules(config.workspace.scopeNormalization);
1098
+ if (config.workspace.sandbox && !process.env.RIG_RUNTIME_SANDBOX?.trim()) {
1099
+ process.env.RIG_RUNTIME_SANDBOX = config.workspace.sandbox;
1100
+ }
1101
+ const validatorRegistry = createValidatorRegistry();
1102
+ for (const impl of pluginHost.listExecutableValidators()) {
1103
+ validatorRegistry.register(impl);
1104
+ }
1105
+ const taskSourceRegistry = buildTaskSourceRegistry(config, pluginHost, { projectRoot });
1106
+ async function installIfResolved(capability) {
1107
+ const impl = await capability.resolve(pluginHost);
1108
+ if (impl)
1109
+ installCapability(capability, impl);
1110
+ }
1111
+ await installIfResolved(RepoChangeSetCap);
1112
+ await installIfResolved(RepoGitBinaryCap);
1113
+ await installIfResolved(RepoNativeGitCap);
1114
+ await installIfResolved(RuntimeSecretsCap);
1115
+ await installIfResolved(TaskArtifactsCap);
1116
+ await installIfResolved(TaskStateStoreCap);
1117
+ await installIfResolved(TaskTrackerReadinessPolicyCap);
1118
+ await installIfResolved(TaskTrackerReconciliationPolicyCap);
1119
+ await installIfResolved(TaskTrackerRepoLocatorCap);
1120
+ await installIfResolved(TaskTrackerStateCap);
1121
+ const toolMaterializer = await ToolMaterializerCap.resolve(pluginHost);
1122
+ if (toolMaterializer) {
1123
+ installCapability(ToolMaterializerCap, toolMaterializer);
1124
+ }
1125
+ const managedRepoService = await ManagedRepoCap.resolve(pluginHost);
1126
+ let repoRegistry;
1127
+ if (managedRepoService) {
1128
+ installCapability(ManagedRepoCap, managedRepoService);
1129
+ repoRegistry = managedRepoService.createRepoRegistry(pluginHost.listRepoSources());
1130
+ const managedEntries = pluginHost.listRepoSources().map((reg) => managedRepoService.repoRegistrationToManagedEntry(reg)).filter((e) => e !== null);
1131
+ managedRepoService.setManagedRepos(managedEntries);
1132
+ } else {
1133
+ repoRegistry = { getById: () => {
1134
+ return;
1135
+ }, list: () => [] };
1136
+ }
1137
+ const configRoleOverrides = config.runtime?.agentRoles;
1138
+ const agentRoleRegistry = createAgentRoleRegistry(pluginHost.listAgentRoles(), configRoleOverrides);
1139
+ const taskFieldRegistry = createTaskFieldRegistry(pluginHost.listTaskFieldExtensions());
1140
+ try {
1141
+ const hookEntries = config.plugins.flatMap((plugin) => (plugin.contributes?.hooks ?? []).map((hook) => ({
1142
+ pluginName: plugin.name,
1143
+ hook,
1144
+ typed: Boolean(hook.handler)
1145
+ })));
1146
+ if (hookEntries.length > 0) {
1147
+ const sessionHookMaterializer = await SessionHookMaterializerCap.resolve(pluginHost);
1148
+ if (sessionHookMaterializer) {
1149
+ await sessionHookMaterializer.materializeSessionHooks(projectRoot, hookEntries);
1150
+ }
1151
+ }
1152
+ } catch (err) {
1153
+ console.warn(`[plugin-host] hook materialization failed: ${err instanceof Error ? err.message : err}`);
1154
+ }
1155
+ const sessionAssetMaterializer = await SessionAssetMaterializerCap.resolve(pluginHost);
1156
+ if (sessionAssetMaterializer) {
1157
+ await sessionAssetMaterializer.materializeSessionAssets(projectRoot, config);
1158
+ }
1159
+ return {
1160
+ config,
1161
+ pluginHost,
1162
+ validatorRegistry,
1163
+ taskSourceRegistry,
1164
+ repoRegistry,
1165
+ agentRoleRegistry,
1166
+ taskFieldRegistry
1167
+ };
1168
+ }
1169
+ export {
1170
+ buildPluginHostContext
1171
+ };