@saturn-universe/runtime-host 0.1.1 → 0.1.2-dev.10

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 (42) hide show
  1. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +2 -2
  2. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +1 -1
  3. package/dist/command-dispatch.js +2 -1
  4. package/dist/composition.d.ts +20 -55
  5. package/dist/composition.js +316 -89
  6. package/dist/context-extensions.d.ts +132 -10
  7. package/dist/context-extensions.js +30 -4
  8. package/dist/cordis/model-responses-plugin.d.ts +2 -1
  9. package/dist/cordis/model-responses-plugin.js +16 -11
  10. package/dist/cordis/plugin-lifecycle.d.ts +1 -0
  11. package/dist/cordis/plugin-lifecycle.js +3 -0
  12. package/dist/cordis/plugin-loader.d.ts +1 -1
  13. package/dist/cordis/plugin-loader.js +45 -10
  14. package/dist/cordis/sandbox-plugin.d.ts +1 -0
  15. package/dist/cordis/sandbox-plugin.js +1 -0
  16. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +2 -2
  17. package/dist/cordis/tools/builtin-agent-tools-plugin.js +27 -3
  18. package/dist/cordis/tools/index.d.ts +5 -1
  19. package/dist/cordis/tools/index.js +3 -3
  20. package/dist/cordis/tools/process-manager-plugin.d.ts +1 -1
  21. package/dist/cordis/tools/process-manager-plugin.js +8 -8
  22. package/dist/cordis/tools/tools-core-plugin.js +54 -11
  23. package/dist/env-probe.js +33 -20
  24. package/dist/host-configuration.d.ts +4 -0
  25. package/dist/host-configuration.js +25 -1
  26. package/dist/index.js +9 -2
  27. package/dist/mode-configuration.d.ts +197 -0
  28. package/dist/mode-configuration.js +109 -0
  29. package/dist/modes.js +52 -10
  30. package/dist/provider-catalog.d.ts +301 -34
  31. package/dist/provider-catalog.js +80 -79
  32. package/dist/run-budget.d.ts +30 -7
  33. package/dist/run-budget.js +49 -5
  34. package/dist/runtime-tuning.d.ts +23 -0
  35. package/dist/runtime-tuning.js +68 -0
  36. package/dist/sandbox-manager.d.ts +2 -0
  37. package/dist/sandbox-manager.js +18 -12
  38. package/dist/session-mode-runtime.d.ts +99 -0
  39. package/dist/session-mode-runtime.js +306 -0
  40. package/dist/skills-runtime.d.ts +5 -2
  41. package/dist/skills-runtime.js +8 -5
  42. package/package.json +9 -9
@@ -21,17 +21,17 @@ function processGuidance(visible) {
21
21
  'A timeout or unknown result does not prove the process stopped. Check any existing handle and actual side effects before retrying. Never launch a blind duplicate.',
22
22
  ].join('\n');
23
23
  }
24
- export function createProcessManagerPlugin(root, options) {
24
+ export function createProcessManagerPlugin(root, options, shared) {
25
25
  return {
26
26
  name: 'process-manager',
27
27
  apply(ctx) {
28
- const manager = createProcessManager({
29
- ...options,
30
- directory: path.join(root, '.saturn', 'processes'),
31
- });
32
- ctx.effect(() => async () => {
33
- await manager.close();
34
- });
28
+ const manager = shared ??
29
+ createProcessManager({
30
+ ...options,
31
+ directory: path.join(root, '.saturn', 'processes'),
32
+ });
33
+ if (!shared)
34
+ ctx.effect(() => () => manager.close());
35
35
  ctx.provide('saturnProcessManager', manager);
36
36
  registerToolGuidance(ctx, 'process-tool-guidance', -20, processGuidance);
37
37
  },
@@ -1,11 +1,34 @@
1
- import { configForDerivedAgent, RuntimeError } from '@saturn-universe/core';
2
- import { Registry, dataReviewToolName, dataReviewToolSet, outsideWorkspacePrefix, plannerToolName, spawnTeamToolName, teamNotifyParentToolName, todoWriteToolName, } from '@saturn-universe/tools';
1
+ import { configForDerivedAgent, isAsyncCoordinatorConfig, RuntimeError } from '@saturn-universe/core';
2
+ import { Registry, dataReviewToolName, dataReviewToolSet, outsideWorkspacePrefix, plannerToolName, spawnTeamToolName, teamNotifyParentToolName, isTeamMemberControlTool, todoWriteToolName, } from '@saturn-universe/tools';
3
3
  import { resolveWorkerReasoning } from '../../provider-catalog.js';
4
4
  import { skillToolName } from '../../skills-runtime.js';
5
5
  import { contributionScopeKey, globalScope, matchesScope, primaryRole, ScopedLayers, validateContributionScope, } from '../scoped-layers.js';
6
6
  import { contributionIdentity, registerPluginContribution, trackPluginTool, } from '../plugin-contributions.js';
7
7
  import { sandboxTargetToolNames } from './sandbox-target-tools-plugin.js';
8
8
  import { webToolNames } from './web-search-tools-plugin.js';
9
+ function configForToolRole(config, role) {
10
+ const context = config.contextExtensions;
11
+ const mode = context?.mode;
12
+ const filter = role === 'main' || role === 'worker' ? mode?.toolRoles?.[role] : undefined;
13
+ if (!context || !mode || !filter)
14
+ return config;
15
+ const { allowedTools: globalAllowed, deniedTools: globalDenied } = mode;
16
+ const { allowedTools: roleAllowed, deniedTools: roleDenied } = filter;
17
+ const allowedTools = globalAllowed && roleAllowed
18
+ ? globalAllowed.filter((name) => roleAllowed.includes(name))
19
+ : (globalAllowed ?? roleAllowed);
20
+ return {
21
+ ...config,
22
+ contextExtensions: {
23
+ ...context,
24
+ mode: {
25
+ ...mode,
26
+ ...(allowedTools !== undefined ? { allowedTools } : {}),
27
+ deniedTools: [...(globalDenied ?? []), ...(roleDenied ?? [])],
28
+ },
29
+ },
30
+ };
31
+ }
9
32
  export const interactiveToolPolicies = {
10
33
  strict: 'interactive-strict-v1',
11
34
  default: 'interactive-default-v2',
@@ -280,7 +303,8 @@ function createToolsService(config, trustedConfig, hash) {
280
303
  return { decision: 'allow' };
281
304
  if (definition.name === spawnTeamToolName ||
282
305
  definition.name === todoWriteToolName ||
283
- definition.name === teamNotifyParentToolName)
306
+ definition.name === teamNotifyParentToolName ||
307
+ isTeamMemberControlTool(definition.name))
284
308
  return { decision: 'allow' };
285
309
  if (definition.name === skillToolName)
286
310
  return { decision: 'allow' };
@@ -342,7 +366,21 @@ function createToolsService(config, trustedConfig, hash) {
342
366
  const overrides = new Map(scoped
343
367
  .resolve(target, ({ scopeKey, toolSets }) => scopeKey !== undefined && toolSets.includes(runConfig.toolSetVersion))
344
368
  .map((entry) => [entry.name, entry]));
345
- const snapshot = registry.snapshotForAdmission(runConfig, overrides, ({ name, version, scopeKey }) => knownPluginTools.has(contributionIdentity({
369
+ if (runConfig.teamDefaultConcurrency !== undefined &&
370
+ (runConfig.toolSetVersion === '4' ||
371
+ mcp ||
372
+ [
373
+ previousWorkspaceToolSetVersion,
374
+ patchWorkspaceToolSetVersion,
375
+ phaseOneToolSetVersion,
376
+ workspaceToolSetVersion,
377
+ ].includes(runConfig.toolSetVersion)) &&
378
+ registry.isActive(spawnTeamToolName, '3') &&
379
+ !overrides.has(spawnTeamToolName)) {
380
+ overrides.set(spawnTeamToolName, { name: spawnTeamToolName, version: '3', toolSets: [] });
381
+ }
382
+ const filtered = configForToolRole(runConfig, target.role);
383
+ const snapshot = registry.snapshotForAdmission(filtered, overrides, ({ name, version, scopeKey }) => knownPluginTools.has(contributionIdentity({
346
384
  kind: 'tool',
347
385
  id: name,
348
386
  version,
@@ -351,11 +389,11 @@ function createToolsService(config, trustedConfig, hash) {
351
389
  const rawDefinitions = runConfig.team
352
390
  ? snapshot.definitions.map((definition) => teamVariant(definition, runConfig.toolSetVersion))
353
391
  : snapshot.definitions;
354
- const definitions = target.role === 'worker' && !config.workerAllowTargetServices
355
- ? rawDefinitions.filter(({ name }) => !sandboxTargetToolNames.has(name))
356
- : rawDefinitions;
357
- const allowed = runConfig.contextExtensions?.mode?.allowedTools;
358
- const denied = runConfig.contextExtensions?.mode?.deniedTools;
392
+ const allowMemberControl = target.role === 'main' && isAsyncCoordinatorConfig(runConfig);
393
+ const definitions = rawDefinitions.filter(({ name }) => (allowMemberControl || !isTeamMemberControlTool(name)) &&
394
+ (target.role !== 'worker' || config.workerAllowTargetServices || !sandboxTargetToolNames.has(name)));
395
+ const allowed = filtered.contextExtensions?.mode?.allowedTools;
396
+ const denied = filtered.contextExtensions?.mode?.deniedTools;
359
397
  if (allowed) {
360
398
  const selected = new Set(definitions.map(({ name }) => name));
361
399
  const inactive = [...knownPluginTools.values()].find(({ name, version, scopeKey, scope, toolSets }) => allowed.includes(name) &&
@@ -446,9 +484,14 @@ function createToolsService(config, trustedConfig, hash) {
446
484
  const allowSpawnTeam = agentDepth < teamMaxDepth;
447
485
  const allowNotifyParent = agentDepth === 1;
448
486
  const allowTargetServices = Boolean(config.workerAllowTargetServices);
449
- const snapshot = await registry.snapshot(workerBase);
487
+ const filtered = configForToolRole(workerBase, 'worker');
488
+ const { allowedTools, deniedTools } = filtered.contextExtensions?.mode ?? {};
489
+ const snapshot = await registry.snapshot(filtered);
450
490
  const definitions = snapshot.definitions
451
- .filter(({ name }) => name !== todoWriteToolName &&
491
+ .filter(({ name }) => (!allowedTools || allowedTools.includes(name)) &&
492
+ !deniedTools?.includes(name) &&
493
+ name !== todoWriteToolName &&
494
+ !isTeamMemberControlTool(name) &&
452
495
  (allowSpawnTeam || name !== spawnTeamToolName) &&
453
496
  (allowNotifyParent || name !== teamNotifyParentToolName) &&
454
497
  (allowTargetServices || !sandboxTargetToolNames.has(name)))
package/dist/env-probe.js CHANGED
@@ -41,33 +41,45 @@ async function isExecutableFile(candidate, platform) {
41
41
  return false;
42
42
  }
43
43
  }
44
- export async function isCommandOnPath(command, env = process.env, platform = process.platform) {
44
+ function commandLookup(env, platform, batch) {
45
45
  const rawPath = env.PATH ?? env.Path ?? '';
46
- if (!rawPath)
47
- return false;
48
46
  const pathDirs = rawPath
49
47
  .split(path.delimiter)
50
48
  .map((dir) => dir.trim().replace(/^"(.*)"$/, '$1'))
51
49
  .filter(Boolean);
52
- if (!pathDirs.length)
53
- return false;
54
50
  const suffixes = platform === 'win32'
55
- ? path.extname(command)
56
- ? ['']
57
- : (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
58
- .split(';')
59
- .map((ext) => ext.trim())
60
- .filter(Boolean)
51
+ ? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
52
+ .split(';')
53
+ .map((ext) => ext.trim())
54
+ .filter(Boolean)
61
55
  : [''];
62
- for (const dir of pathDirs) {
63
- for (const suffix of suffixes) {
64
- const candidate = path.join(dir, `${command}${suffix}`);
65
- if (await isExecutableFile(candidate, platform)) {
66
- return true;
67
- }
56
+ const listings = new Map();
57
+ function namesIn(dir) {
58
+ let names = listings.get(dir);
59
+ if (!names) {
60
+ names = readdir(dir).then((entries) => new Set(entries.map((name) => name.toLowerCase())), (error) => error.code === 'ENOENT' || error.code === 'ENOTDIR' ? new Set() : undefined);
61
+ listings.set(dir, names);
68
62
  }
63
+ return names;
69
64
  }
70
- return false;
65
+ return async (command) => {
66
+ const filenames = (platform === 'win32' && path.extname(command) ? [''] : suffixes).map((ext) => command + ext);
67
+ for (const dir of pathDirs) {
68
+ // Enumerate each Windows PATH directory once per probe. If listing is denied,
69
+ // direct checks can still succeed for a known filename.
70
+ const names = batch && platform === 'win32' ? await namesIn(dir) : undefined;
71
+ for (const filename of filenames) {
72
+ if (names && !names.has(filename.toLowerCase()))
73
+ continue;
74
+ if (await isExecutableFile(path.join(dir, filename), platform))
75
+ return true;
76
+ }
77
+ }
78
+ return false;
79
+ };
80
+ }
81
+ export function isCommandOnPath(command, env = process.env, platform = process.platform) {
82
+ return commandLookup(env, platform, false)(command);
71
83
  }
72
84
  export async function collectWorkspaceSnapshot(root) {
73
85
  let isGitRepo = false;
@@ -144,9 +156,10 @@ export async function collectWorkspaceSnapshot(root) {
144
156
  }
145
157
  export async function probeHostEnvironment(root) {
146
158
  const allowlist = [...readonlyCommandAllowlist].sort((a, b) => a.localeCompare(b));
159
+ const lookup = commandLookup(process.env, process.platform, true);
147
160
  const [readonlyResults, runtimeResults, snapshot] = await Promise.all([
148
- Promise.all(allowlist.map(async (cmd) => [cmd, await isCommandOnPath(cmd)])),
149
- Promise.all(commonRuntimes.map(async (cmd) => [cmd, await isCommandOnPath(cmd)])),
161
+ Promise.all(allowlist.map(async (cmd) => [cmd, await lookup(cmd)])),
162
+ Promise.all(commonRuntimes.map(async (cmd) => [cmd, await lookup(cmd)])),
150
163
  collectWorkspaceSnapshot(root),
151
164
  ]);
152
165
  const availableReadonlyCommands = [];
@@ -1,4 +1,5 @@
1
1
  import type { ProviderCatalog } from './provider-catalog.js';
2
+ import { loadModeConfiguration } from './mode-configuration.js';
2
3
  export type ConfigSource = 'explicit' | 'workspace' | 'user' | 'none';
3
4
  export interface McpServerMeta {
4
5
  readonly scope: Exclude<ConfigSource, 'none'> | 'project';
@@ -8,6 +9,7 @@ export interface McpServerMeta {
8
9
  }
9
10
  export declare function parseHostArguments(args: readonly string[]): {
10
11
  allowUnsafeSandboxFallback?: boolean;
12
+ inspectModes?: boolean;
11
13
  mode?: string;
12
14
  taskProfile?: string;
13
15
  profile?: string;
@@ -20,6 +22,8 @@ export declare function loadHostConfiguration(root: string, explicitFile?: strin
20
22
  configPath: string | undefined;
21
23
  trustedMcp: boolean;
22
24
  trustedPlugins: boolean;
25
+ modePluginSources?: Awaited<ReturnType<typeof loadModeConfiguration>>['modePluginSources'];
26
+ modePackageDirectories: ReadonlyMap<string, string>;
23
27
  webSearch?: ProviderCatalog['webSearch'];
24
28
  mcpServers?: ProviderCatalog['mcpServers'];
25
29
  mcpServerMeta?: Readonly<Record<string, McpServerMeta>>;
@@ -3,18 +3,23 @@ import { readFile } from 'node:fs/promises';
3
3
  import { RuntimeError } from '@saturn-universe/core';
4
4
  import { normalizeWorkspaceTrustPath, parseProjectMcpJson, projectMcpConfigPath, userConfigPath, workspaceConfigPath, } from '@saturn-universe/protocol';
5
5
  import { parseProviderToml } from './provider-catalog.js';
6
+ import { loadModeConfiguration } from './mode-configuration.js';
6
7
  export function parseHostArguments(args) {
7
8
  let root;
8
9
  let configFile;
9
10
  let profile;
10
11
  let taskProfile;
11
12
  let mode;
13
+ let inspectModes = false;
12
14
  let allowUnsafeSandboxFallback = false;
13
15
  for (let i = 0; i < args.length; i++) {
14
16
  const arg = args[i];
15
17
  if (arg === '--allow-unsafe-sandbox-fallback') {
16
18
  allowUnsafeSandboxFallback = true;
17
19
  }
20
+ else if (arg === '--inspect-modes') {
21
+ inspectModes = true;
22
+ }
18
23
  else if (['--config', '--profile', '--task-profile', '--mode'].includes(arg)) {
19
24
  const value = args[++i];
20
25
  if (!value || value.startsWith('--'))
@@ -55,6 +60,7 @@ export function parseHostArguments(args) {
55
60
  ...(profile ? { profile } : {}),
56
61
  ...(taskProfile ? { taskProfile } : {}),
57
62
  ...(mode ? { mode } : {}),
63
+ ...(inspectModes ? { inspectModes: true } : {}),
58
64
  ...(allowUnsafeSandboxFallback ? { allowUnsafeSandboxFallback: true } : {}),
59
65
  };
60
66
  }
@@ -123,6 +129,22 @@ export async function loadHostConfiguration(root, explicitFile, env = process.en
123
129
  break;
124
130
  }
125
131
  const userCatalog = configSource === 'user' ? resolvedCatalog : await readOptionalUserCatalog(env);
132
+ const { modes, modePluginSources, modePackageDirectories } = await loadModeConfiguration(env, [
133
+ ...(configSource !== 'user' && userCatalog?.modes
134
+ ? [
135
+ {
136
+ modes: userCatalog.modes,
137
+ pluginSource: { directory: path.dirname(userConfigPath(env)), bundled: false },
138
+ },
139
+ ]
140
+ : []),
141
+ {
142
+ modes: resolvedCatalog?.modes,
143
+ ...(trusted && configPath
144
+ ? { pluginSource: { directory: path.dirname(configPath), bundled: false } }
145
+ : {}),
146
+ },
147
+ ]);
126
148
  const trustedWorkspaces = new Set((userCatalog?.trustedMcpWorkspaces ?? []).map((entry) => normalizeWorkspaceTrustPath(entry)));
127
149
  const workspaceTrustedForMcp = trustedWorkspaces.has(normalizeWorkspaceTrustPath(root));
128
150
  const mcpJsonPath = projectMcpConfigPath(root);
@@ -170,11 +192,13 @@ export async function loadHostConfiguration(root, explicitFile, env = process.en
170
192
  // A workspace-controlled TOML cannot select which Host secret to send to a remote endpoint.
171
193
  const webSearch = trusted ? resolvedCatalog?.webSearch : userCatalog?.webSearch;
172
194
  return {
173
- catalog: resolvedCatalog,
195
+ catalog: modes ? { ...(resolvedCatalog ?? { profiles: [], taskProfiles: {} }), modes } : resolvedCatalog,
174
196
  configSource,
175
197
  configPath,
176
198
  trustedMcp: trusted,
177
199
  trustedPlugins: trusted,
200
+ modePluginSources,
201
+ modePackageDirectories,
178
202
  ...(webSearch ? { webSearch } : {}),
179
203
  ...(hasMergedMcp ? { mcpServers: mergedMcpServers, mcpServerMeta } : {}),
180
204
  ...(projectMcp.error ? { mcpJsonError: projectMcp.error } : {}),
package/dist/index.js CHANGED
@@ -11,12 +11,19 @@ import { acquireOwnership } from './ownership.js';
11
11
  import { composeRuntime } from './composition.js';
12
12
  import { ReplyWriter, receiveCommands } from './ipc.js';
13
13
  import { createCommandDispatch } from './command-dispatch.js';
14
- import { parseHostArguments } from './host-configuration.js';
14
+ import { loadHostConfiguration, parseHostArguments } from './host-configuration.js';
15
15
  import { createHostLogger, openHostDiagnostics } from './logger.js';
16
+ import { resolveActiveMode } from './modes.js';
16
17
  async function main() {
17
18
  const startup = performance.now();
18
19
  const args = parseHostArguments(process.argv.slice(2));
19
20
  const root = await realpath(path.resolve(args.root));
21
+ if (args.inspectModes) {
22
+ const { catalog } = await loadHostConfiguration(root, args.configFile);
23
+ const { availableModes } = resolveActiveMode(catalog, args.mode);
24
+ process.stdout.write(JSON.stringify(availableModes.map(({ ref, displayName, description }) => ({ ref, displayName, description }))) + '\n');
25
+ return;
26
+ }
20
27
  const dataDir = path.join(root, '.saturn');
21
28
  await mkdir(dataDir, { recursive: true });
22
29
  const { key, endpoint } = resolveHostEndpoint(root);
@@ -126,7 +133,7 @@ function failure(requestId, error) {
126
133
  code: error instanceof RuntimeError ? error.code : 'INTERNAL',
127
134
  message: `Command failed [diagnosticId: ${randomUUID()}]`,
128
135
  retryable: error instanceof RuntimeError &&
129
- ['VERSION_CONFLICT', 'STORAGE_BUSY', 'HOST_BUSY'].includes(error.code),
136
+ ['VERSION_CONFLICT', 'STORAGE_BUSY', 'HOST_BUSY', 'SESSION_BUSY'].includes(error.code),
130
137
  },
131
138
  };
132
139
  }
@@ -0,0 +1,197 @@
1
+ import type { ProviderCatalog } from './provider-catalog.js';
2
+ interface ModePluginSource {
3
+ readonly directory: string;
4
+ readonly bundled: boolean;
5
+ }
6
+ type ModeLayer = {
7
+ readonly modes: ProviderCatalog['modes'];
8
+ readonly pluginSource?: ModePluginSource;
9
+ };
10
+ export declare function loadModeConfiguration(env: NodeJS.ProcessEnv, configured: readonly ModeLayer[]): Promise<{
11
+ modes: {
12
+ [k: string]: {
13
+ display_name?: string | undefined;
14
+ description?: string | undefined;
15
+ instructions?: string | undefined;
16
+ allowed_tools?: string[] | undefined;
17
+ denied_tools?: string[] | undefined;
18
+ prompts?: {
19
+ instructions?: string | undefined;
20
+ core?: {
21
+ mode: "append" | "replace";
22
+ text: string;
23
+ } | undefined;
24
+ execution_policy?: {
25
+ mode: "append" | "replace";
26
+ text: string;
27
+ } | undefined;
28
+ roles?: {
29
+ main?: {
30
+ text: string;
31
+ id?: string | undefined;
32
+ priority?: number | undefined;
33
+ required?: boolean | undefined;
34
+ mode?: "append" | "replace" | undefined;
35
+ }[] | undefined;
36
+ planner?: {
37
+ text: string;
38
+ id?: string | undefined;
39
+ priority?: number | undefined;
40
+ required?: boolean | undefined;
41
+ mode?: "append" | "replace" | undefined;
42
+ }[] | undefined;
43
+ worker?: {
44
+ text: string;
45
+ id?: string | undefined;
46
+ priority?: number | undefined;
47
+ required?: boolean | undefined;
48
+ mode?: "append" | "replace" | undefined;
49
+ }[] | undefined;
50
+ } | undefined;
51
+ } | undefined;
52
+ tools?: {
53
+ roles?: {
54
+ main?: {
55
+ allowed_tools?: string[] | undefined;
56
+ denied_tools?: string[] | undefined;
57
+ } | undefined;
58
+ worker?: {
59
+ allowed_tools?: string[] | undefined;
60
+ denied_tools?: string[] | undefined;
61
+ } | undefined;
62
+ } | undefined;
63
+ permission_mode?: "default" | "strict" | "full" | undefined;
64
+ allowed_tools?: string[] | undefined;
65
+ denied_tools?: string[] | undefined;
66
+ workspace_tools?: boolean | undefined;
67
+ process_manager?: boolean | undefined;
68
+ builtin_agent_tools?: boolean | undefined;
69
+ } | undefined;
70
+ reasoning?: {
71
+ main_effort?: "low" | "off" | "none" | "minimal" | "medium" | "high" | "xhigh" | "max" | undefined;
72
+ worker_effort?: "low" | "off" | "none" | "minimal" | "medium" | "high" | "xhigh" | "max" | undefined;
73
+ } | undefined;
74
+ plugins?: string[] | Record<string, {
75
+ allowed_tools?: string[] | undefined;
76
+ read_only_tools?: string[] | undefined;
77
+ auto_approve_tools?: string[] | undefined;
78
+ enabled?: boolean | undefined;
79
+ entry?: string | undefined;
80
+ config?: Record<string, string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | {
81
+ [key: string]: string | number | boolean | /*elided*/ any | /*elided*/ any;
82
+ })[] | {
83
+ [key: string]: string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any;
84
+ })[] | {
85
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
86
+ })[] | {
87
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
88
+ })[] | {
89
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
90
+ })[] | {
91
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
92
+ })[] | {
93
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
94
+ })[] | {
95
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
96
+ })[] | {
97
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
98
+ })[] | {
99
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
100
+ })[] | {
101
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
102
+ })[] | {
103
+ [key: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
104
+ }> | undefined;
105
+ }> | undefined;
106
+ sandbox?: {
107
+ backend?: "host" | "docker" | "gvisor" | "sysbox" | undefined;
108
+ scope?: "none" | "per_run_and_worker" | undefined;
109
+ image?: string | undefined;
110
+ network?: "none" | "internal" | "proxy" | "bridge" | undefined;
111
+ network_name?: string | undefined;
112
+ proxy_url?: string | undefined;
113
+ cap_add?: string[] | undefined;
114
+ readonly_mounts?: {
115
+ host_path: string;
116
+ container_path: string;
117
+ }[] | undefined;
118
+ kvm?: boolean | undefined;
119
+ tmpfs_size_mb?: number | undefined;
120
+ resources?: {
121
+ cpus?: number | undefined;
122
+ memory_mb?: number | undefined;
123
+ pids_limit?: number | undefined;
124
+ disk_soft_limit_mb?: number | undefined;
125
+ } | undefined;
126
+ retention?: {
127
+ mode: "always" | "on_success" | "ttl";
128
+ ttl_hours?: number | undefined;
129
+ } | undefined;
130
+ fallback_policy?: "fail_closed" | "allow_host_fallback" | undefined;
131
+ allow_target_services?: boolean | undefined;
132
+ worker_allow_target_services?: boolean | undefined;
133
+ max_targets_per_run?: number | undefined;
134
+ max_concurrent_containers?: number | undefined;
135
+ allowed_target_capabilities?: string[] | undefined;
136
+ } | undefined;
137
+ team?: {
138
+ max_depth?: number | undefined;
139
+ default_concurrency?: number | undefined;
140
+ default_preset?: string | undefined;
141
+ max_concurrency?: number | undefined;
142
+ max_active_depth1?: number | undefined;
143
+ worker_soft_checkpoint_ms?: number | undefined;
144
+ async_coordinator?: boolean | undefined;
145
+ coordinator_poll_interval_ms?: number | undefined;
146
+ } | undefined;
147
+ limits?: {
148
+ model_timeout_ms?: number | undefined;
149
+ stream_idle_timeout_ms?: number | undefined;
150
+ request_total_timeout_ms?: number | undefined;
151
+ tool_timeout_ms?: number | undefined;
152
+ shell_timeout_ms?: number | undefined;
153
+ max_parallel_tools?: number | undefined;
154
+ max_model_attempts?: number | undefined;
155
+ max_tool_calls?: number | undefined;
156
+ max_steps?: number | undefined;
157
+ max_total_tokens?: number | undefined;
158
+ subagent_max_model_attempts?: number | undefined;
159
+ wall_time_ms?: number | undefined;
160
+ subagent_wall_time_ms?: number | undefined;
161
+ } | undefined;
162
+ retry?: {
163
+ model_max_attempts_per_call?: number | undefined;
164
+ tool_max_attempts_per_call?: number | undefined;
165
+ base_delay_ms?: number | undefined;
166
+ max_delay_ms?: number | undefined;
167
+ } | undefined;
168
+ compaction?: {
169
+ enabled?: boolean | undefined;
170
+ threshold_ratio?: number | undefined;
171
+ max_headroom_tokens?: number | undefined;
172
+ headroom_ratio?: number | undefined;
173
+ min_recent_steps?: number | undefined;
174
+ tail_window_ratio?: number | undefined;
175
+ preflight_window_ratio?: number | undefined;
176
+ max_halvings?: number | undefined;
177
+ min_prefix_chars?: number | undefined;
178
+ summary_timeout_ms?: number | undefined;
179
+ } | undefined;
180
+ max_active_challenges?: number | undefined;
181
+ max_helpers_per_challenge?: number | undefined;
182
+ per_challenge_wall_time_ms?: number | undefined;
183
+ worker_soft_checkpoint_ms?: number | undefined;
184
+ board_port?: number | undefined;
185
+ board_token?: string | undefined;
186
+ board_public_host?: string | undefined;
187
+ coordinator_poll_interval_ms?: number | undefined;
188
+ auto_submit?: boolean | undefined;
189
+ max_remote_instances?: number | undefined;
190
+ instance_cooldown_ms?: number | undefined;
191
+ auto_stop_on_solve?: boolean | undefined;
192
+ };
193
+ } | undefined;
194
+ modePluginSources: Map<string, Map<string, ModePluginSource>>;
195
+ modePackageDirectories: Map<string, string>;
196
+ }>;
197
+ export {};
@@ -0,0 +1,109 @@
1
+ import { lstat, readFile, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { parse } from 'smol-toml';
4
+ import { RuntimeError } from '@saturn-universe/core';
5
+ import { userModeDirectories } from '@saturn-universe/protocol';
6
+ import { modeDefinitionsSchema } from './context-extensions.js';
7
+ export async function loadModeConfiguration(env, configured) {
8
+ const discovered = new Map();
9
+ const modePackageDirectories = new Map();
10
+ for (const directory of await userModeDirectories(env)) {
11
+ const filename = path.join(directory, 'mode.toml');
12
+ try {
13
+ if (path.relative(directory, await realpath(directory)) !== '')
14
+ continue;
15
+ const stat = await lstat(filename);
16
+ if (!stat.isFile() || stat.nlink !== 1)
17
+ continue;
18
+ const modes = modeDefinitionsSchema.parse(parse(await readFile(filename, 'utf8')).modes);
19
+ for (const [ref, mode] of Object.entries(modes)) {
20
+ discovered.set(ref, { modes: { [ref]: mode }, pluginSource: { directory, bundled: true } });
21
+ modePackageDirectories.set(ref, directory);
22
+ }
23
+ }
24
+ catch (error) {
25
+ if (error.code === 'ENOENT')
26
+ continue;
27
+ throw new RuntimeError('INVALID_CONFIG', `Invalid mode.toml in Mode directory ${path.basename(directory)}`);
28
+ }
29
+ }
30
+ const modes = new Map();
31
+ const modePluginSources = new Map();
32
+ for (const layer of [...discovered.values(), ...configured]) {
33
+ for (const [ref, mode] of Object.entries(layer.modes ?? {})) {
34
+ const base = modes.get(ref);
35
+ modes.set(ref, base ? mergeModes(base, mode) : mode);
36
+ const sources = modePluginSources.get(ref) ?? new Map();
37
+ modePluginSources.set(ref, sources);
38
+ if (Array.isArray(mode.plugins)) {
39
+ for (const id of sources.keys())
40
+ if (!mode.plugins.includes(id))
41
+ sources.delete(id);
42
+ }
43
+ else {
44
+ for (const [id, plugin] of Object.entries(mode.plugins ?? {})) {
45
+ // A workspace declaration must never gain trust from an inherited entry.
46
+ if (!layer.pluginSource)
47
+ sources.delete(id);
48
+ else if (plugin.entry !== undefined)
49
+ sources.set(id, layer.pluginSource);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ return {
55
+ modes: modes.size ? Object.fromEntries(modes) : undefined,
56
+ modePluginSources,
57
+ modePackageDirectories,
58
+ };
59
+ }
60
+ function mergeModes(base, override) {
61
+ const { instructions, allowed_tools, denied_tools, ...rest } = override;
62
+ const normalized = {
63
+ ...rest,
64
+ prompts: { ...override.prompts, ...(instructions === undefined ? {} : { instructions }) },
65
+ tools: {
66
+ ...override.tools,
67
+ ...(allowed_tools === undefined ? {} : { allowed_tools }),
68
+ ...(denied_tools === undefined ? {} : { denied_tools }),
69
+ },
70
+ };
71
+ const { instructions: baseInstructions, allowed_tools: baseAllowed, denied_tools: baseDenied, ...baseRest } = base;
72
+ const merged = mergeTables({
73
+ ...baseRest,
74
+ prompts: { instructions: baseInstructions, ...base.prompts },
75
+ tools: { allowed_tools: baseAllowed, denied_tools: baseDenied, ...base.tools },
76
+ }, normalized);
77
+ if (Array.isArray(base.plugins) && !Array.isArray(override.plugins) && override.plugins) {
78
+ merged.plugins = { ...Object.fromEntries(base.plugins.map((id) => [id, {}])), ...override.plugins };
79
+ }
80
+ else if (Array.isArray(override.plugins) && base.plugins && !Array.isArray(base.plugins)) {
81
+ const basePlugins = base.plugins;
82
+ merged.plugins = Object.fromEntries(override.plugins.map((id) => [id, Object.hasOwn(basePlugins, id) ? basePlugins[id] : {}]));
83
+ }
84
+ else if (isTable(merged.plugins) && override.plugins && !Array.isArray(override.plugins)) {
85
+ for (const [id, plugin] of Object.entries(override.plugins)) {
86
+ if (plugin.allowed_tools === undefined)
87
+ continue;
88
+ const binding = merged.plugins[id];
89
+ if (!isTable(binding))
90
+ continue;
91
+ if (plugin.read_only_tools === undefined)
92
+ delete binding.read_only_tools;
93
+ if (plugin.auto_approve_tools === undefined)
94
+ delete binding.auto_approve_tools;
95
+ }
96
+ }
97
+ return merged;
98
+ }
99
+ function isTable(value) {
100
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
101
+ }
102
+ function mergeTables(base, override) {
103
+ const fields = new Map(Object.entries(base));
104
+ for (const [key, value] of Object.entries(override)) {
105
+ const previous = fields.get(key);
106
+ fields.set(key, isTable(previous) && isTable(value) ? mergeTables(previous, value) : value);
107
+ }
108
+ return Object.fromEntries(fields);
109
+ }